Skip to content

Commit

Permalink
Updates for DSS C-API 0.13.1, includes basic sample
Browse files Browse the repository at this point in the history
- README.md: tweaks and pt-BR version.
- csproj: Add README.md as PackageReadmeFile, add licenses
- examples: add sample WinForms app and some notes, images
- add a dss_sharp.targets for copying native DLLs when building framework projects
  • Loading branch information
PMeira committed Apr 3, 2023
1 parent bcb60bf commit c70e310
Show file tree
Hide file tree
Showing 19 changed files with 1,128 additions and 119 deletions.
62 changes: 57 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
[![Build](https://github.com/dss-extensions/dss_sharp/actions/workflows/dotnet.yml/badge.svg)](https://github.com/dss-extensions/dss_sharp/actions/workflows/dotnet.yml)
[![Latest NuGet release](https://img.shields.io/nuget/v/dss_sharp?label=NuGet+release&cacheSeconds=3600)](https://www.nuget.org/packages/dss_sharp/)

*Para uma versão em português 🇧🇷 deste arquivo, veja [README.pt-BR.md](https://github.com/dss-extensions/dss_sharp/blob/master/README.pt-BR.md).*

# DSS Sharp

DSS Sharp is a C#/.NET wrapper library for DSS C-API, which is an open-source, multiplatform, multiarchitecture, extended alternative (unofficial, not provided by EPRI) OpenDSS engine, highly compatible with the official OpenDSS COM implementation and more.
DSS Sharp is a C#/.NET wrapper library for DSS C-API, which is an open-source, multi-platform, multi-architecture, extended alternative (unofficial, not provided by EPRI) OpenDSS engine, highly compatible with the official OpenDSS COM implementation and more.

DSS Sharp tries to mimic the organization of the official OpenDSS COM interfaces, plus several extensions (new properties and methods, and whole new classes). If you find conflicting behavior, feel free to report.

This projects exposes most of the funcionality implemented in DSS C-API, including performance benefits, ZIP file support, initial JSON exports, multi-platform (Linux, Windows, macOS) support, including Intel x86/x64 and ARM architectures. Contrary to the official implementation, DSS Sharp supports multiple OpenDSS instances ([`dss_sharp.DSS.NewContext()`](https://dss-extensions.org/dss_sharp/html/d0e4d400-3bd9-1244-3cac-8f1234cbad9f.htm)), effectively enabling user-controlled multi-threading applications. Most of the official [parallel-machine](https://dss-extensions.org/dss_sharp/html/f3440753-3e74-bdb2-81c6-9052f8742d7e.htm) functions are also available.
This projects exposes most of the functionality implemented in DSS C-API, including performance benefits, ZIP file support, initial JSON exports, multi-platform (Linux, Windows, macOS) support, including Intel x86/x64 and ARM architectures. Contrary to the official implementation, DSS Sharp supports multiple OpenDSS instances ([`dss_sharp.DSS.NewContext()`](https://dss-extensions.org/dss_sharp/html/d0e4d400-3bd9-1244-3cac-8f1234cbad9f.htm)), effectively enabling user-controlled multi-threading applications. Most of the official [parallel-machine](https://dss-extensions.org/dss_sharp/html/f3440753-3e74-bdb2-81c6-9052f8742d7e.htm) functions are also available.

For a general introduction visit https://dss-extensions.org and follow the development of the general documentation at https://github.com/dss-extensions/dss-extensions

Expand All @@ -18,13 +20,63 @@ For a general introduction visit https://dss-extensions.org and follow the devel
If you are looking for the bindings to other languages:

- [DSS C-API library](http://github.com/dss-extensions/dss_capi/): the base library that exposes a modified version of EPRI's OpenDSS through a more traditional C interface, built with the open-source Free Pascal compiler instead of Delphi. As of 2022, this base library includes several extensive changes, while retaining very good compatibility.
- [DSS Python](http://github.com/dss-extensions/dss_python/) is a multi-platform Python module (Windows, Linux, MacOS) very compatible with the original COM DLL. See also [OpenDSSDirect.py](http://github.com/dss-extensions/OpenDSSDirect.py/) if you don't need COM compatibility, or just would like to check its extra functionalities (you can mix DSS Python and OpenDSSDirect.py). DSS Python includes preliminary plotting capabilites.
- [dss.hpp](https://dss-extensions.org/dss_capi/): header-only library for C++, hosted within DSS C-API (`include/` directory). Allows using DSS C-API more comfortably from C++, abstract memory management and low-level details such as API conventions of the DSS C-API library.
- [DSS-Python](http://github.com/dss-extensions/dss_python/) is a multi-platform Python module (Windows, Linux, macOS) very compatible with the original COM DLL. See also [OpenDSSDirect.py](http://github.com/dss-extensions/OpenDSSDirect.py/) if you don't need COM compatibility, or just would like to check its extra functionalities (you can mix DSS-Python and OpenDSSDirect.py). DSS-Python includes preliminary plotting capabilites.
[`opendssdirect.utils`](https://dss-extensions.org/OpenDSSDirect.py/opendssdirect.html#module-opendssdirect.utils) to generate some DataFrames.
- [OpenDSSDirect.jl](http://github.com/dss-extensions/OpenDSSDirect.jl/): a Julia module, created by Tom Short (@tshort), recently migrated with the help of Dheepak Krishnamurthy (@kdheepak) to DSS C-API instead of the DDLL.
- [DSS MATLAB](http://github.com/dss-extensions/dss_matlab/): presents multi-platform integration (Windows, Linux, MacOS) with DSS C-API and is also very compatible with the COM classes.
- [DSS_MATLAB](http://github.com/dss-extensions/dss_matlab/): presents multi-platform integration (Windows, Linux, macOS) with DSS C-API and is also very compatible with the COM classes.

# Documentation

We will grow general documentation at https://github.com/dss-extensions/dss-extensions
We will grow general documentation at [https://github.com/dss-extensions/dss-extensions](https://github.com/dss-extensions/dss-extensions). Several notes and a FAQ are already available there.

Currently, users can rely on the official OpenDSS COM documentation (as seen in the official installation and from the [SVN repo](https://sourceforge.net/p/electricdss/code/HEAD/tree/trunk/Version8/Distrib/Doc/)). We provide C#/.NET class library docs at https://dss-extensions.org/dss_sharp/

## At a glance

If you are new to C# or have not use it a few years, it's recommended to check updated material on the current state of .NET and best practices.

If you are new to OpenDSS in general, there are two main aspects you need to study:

- The DSS language, which is used to create and edit the components of the circuits, and also run commands to the DSS engine.
- The APIs, mostly notably the class organization and logic sequences of the COM API. These are used to further automate the DSS engine, extract data and integrate to third party software. The current APIs all follow the concept of "active object" that may be new for many users.
- The official COM DLL is available only for Microsoft Windows ([COM is a Microsoft technology](https://en.wikipedia.org/wiki/Component_Object_Model)), while DSS Sharp tries to reproduce the same API without depending on specific platforms — we can use Windows, Linux, or macOS, even on ARM processors.

The official OpenDSS version from EPRI contains lots of material for both topics and, ignoring the whole installation and registering related to COM, are also applicable to DSS Sharp and other DSS Extensions.

You can learn the basics using the official version and migrate to DSS Sharp when required or when you are interested in the extras from DSS Extensions.

### Installing

There multiple ways, we recommend using NuGet.

If you are using recent versions of Microsoft Visual Studio, you [install the package using NuGet](https://www.nuget.org/packages/dss_sharp/).

If you're using the SDK style .csproj, you can add a reference like (remember to adjust the version if required):

```xml
<ItemGroup>
<PackageReference Include="dss_sharp" Version="0.13.*" />
</ItemGroup>
```

Finally, if you wish to clone the repository and customize the library code instead, remember to manually download the required DLLs, either using the `scripts/download_native_libs.sh`, or by visiting [the DSS C-API releases](https://github.com/dss-extensions/dss_capi/releases) page.

### Minimal usage

After installing and/or adding the reference to `dss_sharp` in your project, you can test with a circuit.

Assuming you have OpenDSS installed at `C:\Program Files`, this should work:

```cs
using dss_sharp;

//...
var dss = new DSS();
dss.Start(0);
dss.Text.Command = @"redirect 'C:\Program Files\OpenDSS\IEEETestCases\13Bus\IEEE13Nodeckt.dss'";
var voltageMags = dss.ActiveCircuit.AllBusVmag;
```

You can also download our repository [electricdss-tst](https://github.com/dss-extensions/electricdss-tst) to obtain the test/reference circuits and more already adjusted for multi-platform usage (the original files are distributed in the official OpenDSS installer).
84 changes: 84 additions & 0 deletions README.pt-BR.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
[![Build](https://github.com/dss-extensions/dss_sharp/actions/workflows/dotnet.yml/badge.svg)](https://github.com/dss-extensions/dss_sharp/actions/workflows/dotnet.yml)
[![Latest NuGet release](https://img.shields.io/nuget/v/dss_sharp?label=NuGet+release&cacheSeconds=3600)](https://www.nuget.org/packages/dss_sharp/)

*For an English version of this file, see [README.md](https://github.com/dss-extensions/dss_sharp/blob/master/README.md).*

# DSS Sharp

DSS Sharp é um projeto para manter um assembly C#/.NET que exponha o motor do OpenDSS na sua implementação customizada da [biblioteca nativa DSS C-API](https://github.com/dss-extensions/dss_capi/blob/master/README.pt-BR.md). DSS C-API é um motor alternativo (sem suporte do EPRI) do OpenDSS: código aberto (totalmente), multiplataforma, multiarquitetura, com diversas extensões, e altamente compatível com a implementação oficial do OpenDSS conforme exposta em seu módulo COM.

Para compatibilidade, DSS Sharp tenta reproduzir a mesma interface/API que o módulo COM oficial do OpenDSS em nível de código do usuário, além de conter várias extensões (novas propriedades e métodos, e mesmo classes completas para alguns componentes de circuito). Se você encontrar comportamento conflitante além do documentado, sinta-se à vontade para entrar em contato ou [reportar no GitHub](https://github.com/dss-extensions/dss_sharp/issues).

Com exceção de gráficos e outros componentes visuais, este projeto expõe a maioria das funcionalidades implementadas na DSS C-API, incluindo algumas otimizações de desempenho, suporte a executar scripts .DSS dentro de arquivos ZIP, suporte inicial a exportação JSON, compatibilidade multiplataforma (Linux, Windows, macOS), includindo Intel x86/x64 e ARM.
Ao contrário da implementação oficial, DSS Sharp suporta a criação de múltiplas instâncias independentes do motor do OpenDSS ([`dss_sharp.DSS.NewContext()`](https://dss-extensions.org/dss_sharp/html/d0e4d400-3bd9-1244-3cac-8f1234cbad9f.htm)), efetivamente permitindo que o usuário empregue aplicações com múltiplos threads de forma mais efetiva. A maioria das funções da versão PM do OpenDSS também estão [disponíveis](https://dss-extensions.org/dss_sharp/html/f3440753-3e74-bdb2-81c6-9052f8742d7e.htm).

Para uma introdução geral, visite https://dss-extensions.org e siga o desenvolvimento através da organização DSS Extensions e https://github.com/dss-extensions/dss-extensions

<p align="center">
<img alt="Visão geral dos repositórios" src="https://raw.githubusercontent.com/dss-extensions/dss_capi/master/docs/images/repomap.png" width=600>
</p>

Caso você tenha interesse em outras linguagens além de .NET:

- [DSS C-API library](http://github.com/dss-extensions/dss_capi/): a biblioteca base que expõe a versão modificada do OpenDSS através de uma interface C mais tradicional, criada empregando o compilador de código aberto Free Pascal ao invés do Delphi. Em 2023, contém diversas extensões e aprimoramentos, mantendo ainda boa compatibilidade.
- [dss.hpp](https://dss-extensions.org/dss_capi/): biblioteca de headers para C++, hospedada também neste repositório (pasta `include/`). Permite usar a DSS C-API de forma confortável sem ser necessário gerenciar os detalhes como o gerenciamento de memória ou convenção de API da DSS C-API. Atualmente usa Eigen e fmt.
- [DSS-Python](http://github.com/dss-extensions/dss_python/) é o módulo Python multi-plataforma (Windows, Linux, MacOS) bastante compatível com o módulo COM. Veja também [OpenDSSDirect.py](http://github.com/dss-extensions/OpenDSSDirect.py/) caso não precise de compatibilidade com COM, ou deseje empregar as funcionalidades extras do módulo (inclusive em conjunto).
- [OpenDSSDirect.jl](http://github.com/dss-extensions/OpenDSSDirect.jl/) é um módulo em Julia, criado por Tom Short (@tshort), que recentemente passou a empregar DSS C-API no lugar do DLL direto com a ajuda de Dheepak Krishnamurthy (@kdheepak).
- [DSS MATLAB](http://github.com/dss-extensions/dss_matlab/) permite integração multi-plataforma (Windows, Linux, MacOS) bastante compatível com a API do módulo COM oficial, de fato contorna algumas dificuldades de COM.

# Documentação

Estamos criando documentação geral, inicialmente em inglês, em [https://github.com/dss-extensions/dss-extensions](https://github.com/dss-extensions/dss-extensions). Diversas notas e um FAQ já estão disponíveis. Há também espaço dedicado para discussões, etc.

No momento, os usuários podem seguir a documentação do módulo COM oficial do OpenDSS, pulando a parte de instalação. Caso não tenha OpenDSS instalado, os arquivos também estão disponíveis no [repositório SVN oficial](https://sourceforge.net/p/electricdss/code/HEAD/tree/trunk/Version8/Distrib/Doc/)).

Em geral atualizada alguns dias após o lançamento de uma nova versão, temos documentação das nossas classes de C#/.NET em https://dss-extensions.org/dss_sharp/

## Primeiros passos

Se você é um usuário novo de C# ou não tem usado em vários anos, é recomendável buscar por material atualizado sobre .NET e as práticas recomendadas para versões modernas.

Se ainda não é proficiente em OpenDSS, há dois principais aspectos a investigar:

- A linguagem DSS, que é usada para criar e editar os componentes dos circuitos elétricos, além de enviar comandos diversos para o motor do OpenDSS.
- As interfaces de programação (APIs), em especial a organização de classes e lógica empregada na API COM. As interfaces são usadas para automatizar ainda mais o uso do motor do DSS, extrair dados e integrar programas e bibliotecas de terceiros. As APIs atuais todas seguem o conceito de "objeto ativo" ("Active...") que pode ser novo para muitos usuários.
- O DLL do módulo COM oficial está disponível apenas no Microsoft Windows ([COM é uma tecnologia da Microsoft](https://pt.wikipedia.org/wiki/Component_Object_Model)). DSS Sharp tenta reproduzir a mesma interface em nível do usuário sem depender de plataformas específicas — podemos usar Windows, Linux, or macOS, mesmo em processadores ARM.

A instalação da versão oficial do OpenDSS desenvolvida pelo EPRI contém bastante material para ambos os tópicos e, pulando a parte de instalação e registro do módulo COM (não necessário aqui), o material é aplicável para DSS Sharp e outras DSS Extensions.

Usuários podem estudar e aprender os principais conceitos empregando a versão oficial e migrar para DSS Sharp quando necessário ou houver interesse de empregar as funcionalidades extras disponíveis nas DSS Extensions.

### Instalação

Há multiplas formas. Recomendamos empregar NuGet.

Se estiver usando versões recentes do Microsoft Visual Studio, pode [instalar empregando o pacote NuGet](https://www.nuget.org/packages/dss_sharp/).

Caso esteja usando arquivos .csproj no estilo SDK, basta adicionar uma referência no XML como no exemplo abaixo (ajuste a versão de acordo com suas necessidades):

```xml
<ItemGroup>
<PackageReference Include="dss_sharp" Version="0.13.*" />
</ItemGroup>
```

Por fim, se houver interesse em editar o código da DSS Sharp em si, após clonar lembra-se de baixar os DLLs necessários, seja usando o script `scripts/download_native_libs.sh`, ou visitando manualmente a [página de lançamentos da DSS C-API](https://github.com/dss-extensions/dss_capi/releases) para obter as versões necessárias.

### Uso mínimo

Após a instalação ou inclusão da referência ao `dss_sharp` no seu projeto, é possível testar a execução com um circuito qualquer.

Assumindo a instalação padrão do OpenDSS para todos os usuários na pasta `C:\Program Files`, o seguinte deve funcionar:

```cs
using dss_sharp;

//...
var dss = new DSS();
dss.Start(0);
dss.Text.Command = @"redirect 'C:\Program Files\OpenDSS\IEEETestCases\13Bus\IEEE13Nodeckt.dss'";
var voltageMags = dss.ActiveCircuit.AllBusVmag;
```

Você também pode baixar o repositório [electricdss-tst](https://github.com/dss-extensions/electricdss-tst) para obter os circuitos de teste e exemplos já ajustados para uso for multiplataforma (os arquivos originais são distribuídos com a instalação do OpenDSS oficial).
Loading

0 comments on commit c70e310

Please sign in to comment.