### Redirecting Circuit for Integration Examples Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/GettingStarted.ipynb Basic setup code using the `dss_python` interface to redirect a circuit file. This is a prerequisite step before demonstrating integration capabilities with other OpenDSS Python libraries like OpenDSSDirect.py and AltDSS-Python. ```python from dss import dss dss(f'Redirect "{IEEE13_PATH}"') ``` -------------------------------- ### Clone Example Repository with Git (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb This command clones the 'electricdss-tst' repository from GitHub with a shallow depth (1) and quiet output. This repository contains the necessary example files used in the notebook. It assumes Git is installed and accessible. ```python ! git clone --depth=1 -q https://github.com/dss-extensions/electricdss-tst ``` -------------------------------- ### Installing DSS-Python with All Features via Pip (Shell) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/index.md Installs the dss-python package including all optional dependencies, enabling all available features of the library. ```Shell pip install dss-python[all] ``` -------------------------------- ### Installing DSS-Python Standard via Pip (Shell) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/index.md Installs the basic dss-python package using pip, which provides core functionality for interacting with DSS-Extensions. ```Shell pip install dss-python ``` -------------------------------- ### Instantiating DSS using DSS-Python (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/index.md This snippet shows the simplified method for obtaining the main DSS instance when using the DSS-Python library, intended as a drop-in replacement for the traditional COM interface. ```python from dss import DSS ``` -------------------------------- ### Instantiating OpenDSS COM using comtypes.client (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/index.md This snippet illustrates how to instantiate the OpenDSS COM object using the comtypes library, providing an alternative to win32com. ```python import comtypes.client DSS = comtypes.client.CreateObject("OpenDSSEngine.DSS") ``` -------------------------------- ### Instantiating OpenDSS COM using win32com.client.Dispatch (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/index.md This snippet demonstrates a common way to instantiate the OpenDSS COM object using the win32com library's Dispatch method. ```python import win32com.client DSS = win32com.client.Dispatch("OpenDSSEngine.DSS") ``` -------------------------------- ### Compile, Solve, and Plot Circuit Profile Source: https://github.com/dss-extensions/dss-python/blob/master/docs/index.md Demonstrates how to use the DSS text interface via `dss.Text.Command` to compile a circuit file, solve the active circuit's solution, and then execute a plotting command like 'plot profile' using the previously enabled plotting feature. ```python dss.Text.Command = 'compile some_circuit/Master.dss' dss.ActiveCircuit.Solution.Solve() dss.Text.Command = 'plot profile' ``` -------------------------------- ### Example of Reading DSS Files in Python (Commented) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb This commented-out Python code demonstrates how to read the content of DSS script files using the pathlib module. It is provided as an example for inspecting script contents. ```python # from pathlib import Path # print(Path('./electricdss-tst/Version8/Distrib/IEEETestCases/123Bus/Run_IEEE123Bus.DSS').read_text()) # print(Path('./electricdss-tst/Version8/Distrib/IEEETestCases/123Bus/CircuitPlottingScripts.dss').read_text()) ``` -------------------------------- ### Run Yearly Simulation and Setup Second Scenario in DSS Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Redirects to a DSS script that performs a yearly simulation. It then sets up a second simulation scenario by changing the case name, assigning a default yearly loadshape to all loads, configuring the simulation mode and number of steps, setting the starting year, solving the simulation, and closing any open DI (Daily/Interval) files. ```dss // the original script already runs a scenario redirect electricdss-tst/Version8/Distrib/IEEETestCases/123Bus/Run_YearlySim.dss // we need a second scenario to compare later Set CaseName=another batchedit load..* yearly=default set mode=yearly number=720 Set Year=1 solve closedi ``` -------------------------------- ### Using DSS Cell Magic for Visualization Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/GettingStarted.ipynb Example of using the `%%dss` cell magic (typically in a Jupyter environment) to execute a DSS command directly within a code cell. This specific command visualizes voltages for a transformer element. ```dss visualize voltages element=transformer.sub ``` -------------------------------- ### Instantiating OpenDSS COM using win32com.client.gencache (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/index.md This snippet shows how to instantiate the OpenDSS COM object using the win32com library's gencache.EnsureDispatch method, which is often used to ensure type libraries are cached for better performance. ```python import win32com.client DSS = win32com.client.gencache.EnsureDispatch("OpenDSSEngine.DSS") ``` -------------------------------- ### Installing DSS-Python Dependencies (Colab) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Checks if the code is running in a Google Colab environment and, if so, installs the necessary Python packages for dss-python with plotting capabilities and opendssdirect.py. ```python import os, subprocess if os.getenv("COLAB_RELEASE_TAG"): print(subprocess.check_output('pip install dss-python[plot] opendssdirect.py[extras] ipympl scienceplots', shell=True).decode()) ``` -------------------------------- ### Enable Plotting in DSS-Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/index.md Imports the necessary `dss` and `plot` modules from the DSS-Python library and calls `plot.enable()` to activate the matplotlib-based plotting functionality. ```python from dss import dss, plot plot.enable() ``` -------------------------------- ### Install Packages in Google Colab (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb This Python code block checks if the script is running within a Google Colab environment. If the 'COLAB_RELEASE_TAG' environment variable is set, it executes a shell command to install required Python packages: 'dss-python' with plotting extras, 'opendssdirect.py' with extras, and 'pandas' version 2. ```python import os, subprocess if os.getenv("COLAB_RELEASE_TAG"): print(subprocess.check_output('pip install dss-python[plot] opendssdirect.py[extras] pandas==2', shell=True).decode()) ``` -------------------------------- ### Applying SciencePlots Style to DSS Plots Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Provides an example of applying a style from the optional SciencePlots library to a DSS plot. It includes a try-except block to handle cases where SciencePlots is not installed. Requires `matplotlib.pyplot`, `dss`, and optionally `scienceplots`. ```python try: import scienceplots with plt.style.context(['science', 'no-latex']): # if you have LaTeX installed, remove 'no-latex' dss.Text.Command = 'plot circuit c1=red' except: # let's ignore if the user didn“t install SciencePlots pass ``` -------------------------------- ### Plot Circuit Powers using DSS-Python API Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Demonstrates enabling plotting and executing DSS commands through the DSS-Python API to solve a circuit and plot circuit powers. This example shows how to integrate plotting into a standard DSS-Python workflow. ```python from dss import dss dss.Plotting.enable() dss.Text.Command = 'redirect ./electricdss-tst/Version8/Distrib/EPRITestCircuits/ckt5/Master_ckt5.dss' dss.ActiveCircuit.Solution.Solve() dss.Text.Command = 'plot circuit powers' # The shorthand version would also work fine # dss('plot circuit powers') ``` -------------------------------- ### Execute DSS Simulations with Multithreading - Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Multithreading.ipynb This snippet sets up and runs the simulation cases using multiple threads. It copies the case list, creates a thread for each DSS context, starts the threads, waits for them to complete, and then asserts that all simulations converged and prints the elapsed time. ```python # Copy the list of scenarios cases_to_run_threads = list(cases) t0 = perf_counter() threads = [] for ctx in ctxs: t = threading.Thread(target=_run, args=(ctx, cases_to_run_threads, tconverged, tresults)) threads.append(t) for t in threads: t.start() for t in threads: t.join() t1 = perf_counter() # Check if all solutions converged assert all(tconverged.values()) dt_thread = (t1 - t0) print(f'Done in {dt_thread:.3f} s with {num} threads') ``` -------------------------------- ### Install DSS-Python with Plotting Features using pip Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Install the dss-python package including the optional plotting dependencies (matplotlib and SciPy) using pip. This command ensures the necessary libraries for plotting are available. ```shell python -m pip install dss-python[plot] ``` -------------------------------- ### Import DSS and Enable Plotting in Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Imports the dss library from the dss-python package and enables the default plotting features. This is a common setup step for using plotting capabilities. ```python from dss import dss dss.Plotting.enable() ``` -------------------------------- ### Select Load and Get Active Element Name (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Sets the active load element in the DSS circuit by name and then retrieves the name of the currently active DSS element. ```python dss.ActiveCircuit.Loads.Name = '670a' dss.ActiveCircuit.ActiveDSSElement.Name ``` -------------------------------- ### Determining Number of Instances/Threads Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Multithreading.ipynb Calculates the recommended number of instances or threads to use for parallel execution. It takes the minimum of the total number of cases and the detected CPU core count, suggesting a starting point for optimization. ```python # Use the number of threads as CPU count, number of cases num = min(len(cases), os.cpu_count()) ``` -------------------------------- ### Patching COM Object for Iteration in Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/changelog.md This example shows how to use the `dss.patch_dss_com` function to add iterable capabilities to a standard OpenDSS COM object, allowing iteration over elements like Loads and Buses similar to the native dss-python API. It requires the `win32com.client` library. ```Python import win32com.client, dss com = dss.patch_dss_com(win32com.client.gencache.EnsureDispatch("OpenDSSEngine.DSS")) # ...compile a circuit, etc. for l in com.ActiveCircuit.Loads: print(l.Name, l.kva) for b in com.ActiveCircuit.ActiveBus: print(b.Name, b.x, b.y) ``` -------------------------------- ### Get Active DSS Element as JSON (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Calls the ToJSON method on the active DSS element to obtain its properties as a JSON string. ```python dss.ActiveCircuit.ActiveDSSElement.ToJSON() ``` -------------------------------- ### Get Specific Transformer JSON (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Selects the transformer element named 'reg1' in the active circuit and then retrieves its properties as a JSON string, parsing it into a Python dictionary for inspection. ```python dss.ActiveCircuit.Transformers.Name = 'reg1' json.loads(dss.ActiveCircuit.ActiveDSSElement.ToJSON()) ``` -------------------------------- ### Get Active Class Elements as JSON (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Sets the active class in the DSS circuit to 'Load' and then retrieves the JSON representation of all elements belonging to that class using ActiveClass.ToJSON(), parsing it into a Python dictionary. ```python dss.SetActiveClass('Load') json.loads(dss.ActiveCircuit.ActiveClass.ToJSON()) ``` -------------------------------- ### Select Line Element and Get JSON (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Sets the active Line element in the DSS circuit by its name ('684611'), retrieves the active element's data as a JSON string using ToJSON(), and parses the JSON string into a Python dictionary. ```python dss.ActiveCircuit.Lines.Name = '684611' import json json.loads(dss.ActiveCircuit.ActiveDSSElement.ToJSON()) ``` -------------------------------- ### Plot Scatter Diagram in DSS Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Executes the DSS 'plot scatter' command. Note that this specific plot style may require the OpenDSS Viewer application to be installed and configured to function correctly. ```dss plot scatter ``` -------------------------------- ### Interacting with OpenDSS using DSS-Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/GettingStarted.ipynb Illustrates how to initialize DSS-Python, load a circuit using a DSS script, select and modify a load's properties, solve the circuit, and retrieve simulation results. This code is API-compatible with the COM version but does not use COM. ```python # Load DSS-Python from dss import dss # Run a DSS script to load a circuit # (DSS-Extensions do not change the CWD when importing, relative paths are fine) dss.Text.Command = f'Redirect "{IEEE13_PATH}"' # Select a load and update its kW dss.ActiveCircuit.Loads.Name = "675c" dss.ActiveCircuit.Loads.kW = 320 # Solve dss.ActiveCircuit.Solution.Solve() # Get the voltage magnitudes voltages = dss.ActiveCircuit.AllBusVmag ``` -------------------------------- ### Interacting with OpenDSS COM Engine using Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/GettingStarted.ipynb Demonstrates how to initialize the OpenDSS COM engine using `win32com` or `comtypes`, load a circuit from a DSS script, select and modify a load's properties, solve the circuit, and access simulation results like bus voltages. Requires a Windows environment and the OpenDSS COM engine. ```python # Load OpenDSS import win32com.client dss = win32com.client.Dispatch('OpenDSSengine.DSS') # ...or for win32com with ensured early bindings: # import win32com.client # dss = win32com.client.gencache.EnsureDispatch('OpenDSSengine.DSS') # ...or: # import comtypes.client # dss = comtypes.client.CreateObject('OpenDSSengine.DSS') # Run a DSS script to load a circuit # (NOTE: typically you would use either the full path here since the official OpenDSS implementation changes the current working directory of the process) dss.Text.Command = f'Redirect "{IEEE13_PATH}"' # Select a load and update its kW dss.ActiveCircuit.Loads.Name = "675c" dss.ActiveCircuit.Loads.kW = 320 # Solve dss.ActiveCircuit.Solution.Solve() # Get the voltage magnitudes voltages = dss.ActiveCircuit.AllBusVmag ``` -------------------------------- ### Mapping DSS Context to OpenDSSDirect and AltDSS Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/GettingStarted.ipynb Illustrates how to use the `to_opendssdirect()` and `to_altdss()` methods available in `dss_python` to obtain context objects compatible with the respective libraries, allowing seamless switching or parallel use. ```python odd = dss.to_opendssdirect() print(odd.Version()) print() alt = dss.to_altdss() print(alt.Version()) ``` -------------------------------- ### Running Multiple DSS Engines in Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/GettingStarted.ipynb Demonstrates how to create and manage multiple independent DSS engine contexts within a single Python process using `dss.NewContext()`. Each context can solve the same circuit with different parameters (e.g., load multipliers) concurrently. ```python from dss import dss import numpy as np dss.AllowChangeDir = False NUM_ENGINES = 5 load_mults = np.linspace(0.8, 1.2, NUM_ENGINES) engines = [dss.NewContext() for _ in load_mults] for load_mult, engine in zip(load_mults, engines): engine.Text.Command = f'Redirect "{IEEE13_PATH}"' engine.ActiveCircuit.Solution.LoadMult = load_mult engine.ActiveCircuit.Solution.Solve() for engine in engines: lm = engine.ActiveCircuit.Solution.LoadMult losses = engine.ActiveCircuit.Losses[0] print(f'{lm:5.3} {losses:10.1f}') ``` -------------------------------- ### Downloading DSS Sample Circuits (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Uses the dss.examples utility to download a snapshot of the electricdss-tst repository, specifically targeting the IEEE 13-bus test case, and verifies its existence. ```python # Download the sample circuits and test cases from dss.examples import download_repo_snapshot IEEE13_PATH = download_repo_snapshot('.', repo_name='electricdss-tst', use_version=False) / 'Version8/Distrib/IEEETestCases/13Bus/IEEE13Nodeckt.dss' assert IEEE13_PATH.exists() print("Examples downloaded. IEEE13 file path:", str(IEEE13_PATH)) ``` -------------------------------- ### Initializing DSS and Loading Circuit (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb This snippet shows how to import the DSS library in Python, initialize the DSS engine, and load a circuit definition file using the classic API's Text interface. ```python from dss import dss dss.Text.Command = 'redirect electricdss-tst/Version8/Distrib/IEEETestCases/13Bus/IEEE13Nodeckt.dss' ``` -------------------------------- ### Accessing Elements via AltDSS-Python Context Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/GettingStarted.ipynb Shows how to access circuit elements (specifically the first load) using the context object obtained from `dss.to_altdss()`. It demonstrates accessing element properties and exporting the element's data to JSON using the AltDSS-Python interface. ```python load = alt.Load[0] load, load.Powers(), load.to_json() ``` -------------------------------- ### Initialize DSS and Load Circuit (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Sets the AllowEditor property to False and executes a DSS command to redirect input from a specified .dss file, loading the circuit definition. ```python dss.AllowEditor = False dss.Text.Command = 'redirect ./electricdss-tst/Test/IEEE13_Assets.dss' ``` -------------------------------- ### Enabling DSS Plotting in Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/GettingStarted.ipynb Shows how to import and enable the integrated plotting functionality provided by the `dss_python` library using `plot.enable()`. It also includes redirecting a circuit file and executing a basic plot command. ```python from dss import dss, plot plot.enable() dss.Text.Command = f'Redirect "{IEEE13_PATH}"' dss.Text.Command = 'plot circuit' ``` -------------------------------- ### Assembling Simulation Scenarios Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Multithreading.ipynb Creates a list of simulation cases. Each case is a tuple containing a circuit file path and a load multiplier, generating multiple scenarios for each circuit. ```python cases = [] for fn in fns: for load_mult in (0.9, 0.95, 1.0, 1.05, 1.1): cases.append((fn, load_mult)) ``` -------------------------------- ### Plot Circuit Powers using OpenDSSDirect.py API Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Demonstrates enabling plotting via `dss.plot` and executing DSS commands through the OpenDSSDirect.py API to solve a circuit and plot circuit powers. This highlights the shared backend and interoperability between DSS-Python and OpenDSSDirect.py. ```python import dss.plot import opendssdirect as odd dss.plot.enable() odd.Text.Command('redirect ./electricdss-tst/Version8/Distrib/EPRITestCircuits/ckt5/Master_ckt5.dss') odd.Solution.Solve() odd.Text.Command('plot circuit powers') ``` -------------------------------- ### Configuring Case-Insensitive Attributes in DSS-Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/GettingStarted.ipynb Demonstrates how to use `set_case_insensitive_attributes` in DSS-Python to allow case-insensitive access to properties, optionally enabling warnings for capitalization mismatches to aid in code migration and cleanup. ```python from dss import set_case_insensitive_attributes set_case_insensitive_attributes(use=True, warn=True) print(dss.activecircuit.Loads.kW) # this produces a warning print(dss.ActiveCircuit.Loads.kvar) # this one works fine since the capitalization is correct ``` -------------------------------- ### Run Time Series Analysis with PV using DSS Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Compiles the no-PV master file, redirects to the PV file, solves, defines a loadshape from a CSV file and two monitors, assigns the loadshape to all PV systems, solves in daily mode for 1800 steps, changes the PV power factor, and plots the monitor outputs. ```dss %%dss compile Master_noPV.dss Redirect ExistingPV.dss solve new loadshape.mypv npts=1800 sinterval=1 csvfile=StrwPlns1sec30min.csv new monitor.PVSite4VI element=PVSystem.3P_ExistingSite4 terminal=1 mode=0 new monitor.PVSite4PQ element=Line.Site4_PV terminal=2 mode=65 ppolar=no ! Assign same PV curve to all PV systems (single curve used for demo only) batchedit pvsystem..* daily=mypv solve mode=daily stepsize=1s number=1800 batchedit pvsystem..* pf=-0.98 ! Plotting plot monitor object=pvsite4vi channels=(1 ) plot monitor object=pvsite4pq channels=(1 ) ``` -------------------------------- ### Clear, Redirect, Solve, Plot Daisy, and Plot Profile with PV using DSS Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Clears the DSS engine, redirects to the no-PV master file and solves, then redirects to the PV file, sets daisy plot options, plots the daisy plot, solves again with PV, and plots the voltage profile for all phases. ```dss %%dss clear redirect Master_noPV.dss solve Redirect ExistingPV.dss Set DaisySize=2.5 set markregulators=yes plot daisy power max=2000 dots=y buslist=(file=PVbuses.txt) solve plot profile phases=all ``` -------------------------------- ### Load Different Circuit File (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Executes a DSS command to redirect input from a different .dss file, loading a new circuit definition that includes Line and Cable Spacing data. ```python dss.Text.Command = 'redirect electricdss-tst/Test/IEEE13_LineAndCableSpacing.dss' ``` -------------------------------- ### Load and Solve IEEE13 Test Case via DSS-Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Uses the DSS-Python Text interface to execute a 'redirect' command, loading the IEEE 13-bus test circuit from a specified file path. It then calls the Solve method on the ActiveCircuit's Solution object to perform a power flow analysis. ```python # Load and solve the IEEE13 test case dss.Text.Command = 'redirect electricdss-tst/Version8/Distrib/IEEETestCases/13Bus/IEEE13Nodeckt.dss' dss.ActiveCircuit.Solution.Solve() ``` -------------------------------- ### Cloning DSS Test Repository (Notebook) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Clones the electricdss-tst repository using a shell command within a notebook environment (like Colab or Jupyter) to obtain sample circuits and test cases. ```shell ! git clone --depth=1 -q https://github.com/dss-extensions/electricdss-tst ``` -------------------------------- ### Defining Base Directory and Circuit Files Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Multithreading.ipynb Sets the base directory for circuit files and defines a list of paths to various OpenDSS master circuit files to be used in the simulation scenarios. The user should adjust `BASE_DIR` as needed. ```python BASE_DIR = './electricdss-tst' fns = [ f"{BASE_DIR}/Version8/Distrib/EPRITestCircuits/epri_dpv/M1/Master_NoPV.dss", f"{BASE_DIR}/Version8/Distrib/EPRITestCircuits/epri_dpv/K1/Master_NoPV.dss", f"{BASE_DIR}/Version8/Distrib/EPRITestCircuits/epri_dpv/J1/Master_withPV.dss", f"{BASE_DIR}/Version8/Distrib/IEEETestCases/8500-Node/Master-unbal.dss", f"{BASE_DIR}/Version8/Distrib/IEEETestCases/NEVTestCase/NEVMASTER.DSS" ] ``` -------------------------------- ### Execute DSS Simulations with Multiprocessing - Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Multithreading.ipynb This snippet demonstrates running the simulation cases using `multiprocessing.Pool`. It creates a pool of worker processes, maps the `_run_mp` function to the cases, collects the results, assembles them into dictionaries, and prints the elapsed time. ```python import multiprocessing as mp t0 = perf_counter() pool = mp.Pool(processes=num) results_mp = pool.starmap(_run_mp, cases) # Assemble back the results mpresults = {(item[0], item[1]): item[3] for item in results_mp} mpconverged = {(item[0], item[1]): item[2] for item in results_mp} t1 = perf_counter() dt_mp = (t1 - t0) print(f'Done in {dt_mp:.3f} s using {num} processes') ``` -------------------------------- ### Exporting Active DSS Element to JSON using OpenDSSDirect.py (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Uses the `opendssdirect` library (`odd`) to select the first load object using `odd.Loads.First()`. It then exports the currently active DSS element (which is now the first load) to a JSON string using `odd.Element.ToJSON()` with default options. Dependencies: `opendssdirect` library. ```python odd.Loads.First() odd.Element.ToJSON() ``` -------------------------------- ### Configuring NumPy Print Options in Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/GettingStarted.ipynb Sets the print options for the NumPy library, specifically adjusting the `linewidth` to prevent array output from wrapping excessively, improving readability for large arrays or matrices. ```python # Setting numpy to avoid wrapping the text output import numpy as np np.set_printoptions(linewidth=200) ``` -------------------------------- ### Manually Cloning DSS Test Repository (Shell) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Provides a manual shell command to clone the electricdss-tst repository. This is suggested as an alternative if the automated download method fails. ```shell git clone --depth=1 -q https://github.com/dss-extensions/electricdss-tst ``` -------------------------------- ### Exporting DSS Element to JSON in Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/GettingStarted.ipynb Demonstrates how to export the data of the currently active DSS element (after iterating to the first load) to a JSON string using the `ToJSON()` method and then parse it into a Python dictionary using the `json.loads()` function. ```python import json from dss import dss import numpy as np dss(f'Redirect "{IEEE13_PATH}"') dss.ActiveCircuit.Loads.First; json.loads(dss.ActiveCircuit.ActiveDSSElement.ToJSON()) ``` -------------------------------- ### Initialize Result Dictionaries - Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Multithreading.ipynb This snippet initializes empty dictionaries to store the simulation results and convergence status for both the multithreaded ('t' prefix) and single-threaded ('s' prefix) runs. These dictionaries will be populated by the worker function. ```python tresults = {} tconverged = {} sresults = {} sconverged = {} ``` -------------------------------- ### Patching OpenDSS COM Object with DSS-Python Features Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/GettingStarted.ipynb Illustrates using `dss.patch_dss_com` to enhance a standard OpenDSS COM object created via `comtypes` or `win32com` with additional Python functionality, such as iterators for loads or buses, while still using the COM engine. ```python import comtypes, dss dss_com = dss.patch_dss_com(comtypes.client.CreateObject("OpenDSSEngine.DSS")) print(dss_com.Version) # ...compile a circuit, etc. for l in dss_com.ActiveCircuit.Loads: print(l.Name, l.kva) for b in dss_com.ActiveCircuit.ActiveBus: print(b.Name, b.x, b.y) ``` -------------------------------- ### Inspecting DSS JSON Flags (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Uses an interactive shell command (e.g., `??` in IPython) to display information about the `DSSJSONFlags` object, such as its source code or documentation. This is not standard Python syntax for execution. ```python ?? DSSJSONFlags ``` -------------------------------- ### Execute DSS Simulations Sequentially - Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Multithreading.ipynb This snippet runs the same simulation cases sequentially in a single thread for performance comparison. It copies the case list and calls the `_run` function directly with the main DSS context, then prints the elapsed time. ```python # Copy the list of scenarios cases_to_run_seq = list(cases) t0 = perf_counter() _run(dss, cases_to_run_seq, sconverged, sresults) t1 = perf_counter() dt_seq = (t1 - t0) print(f'Done in {dt_seq:.3f} s sequentially') ``` -------------------------------- ### Initialize DSS Contexts for Multithreading - Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Multithreading.ipynb This snippet initializes multiple independent DSS contexts, one for each thread that will be used for parallel simulation. Each context represents a separate instance of the OpenDSS engine. ```python ctxs = [dss.NewContext() for n in range(num)] print(f"Using {len(ctxs)} DSS contexts") ``` -------------------------------- ### Importing Libraries for Parallel DSS Execution Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Multithreading.ipynb Imports necessary Python libraries including os, threading, time, numpy, and the dss module from dss-python. IDSS is imported for type hinting and improved autocomplete. ```python import os import threading from time import perf_counter import numpy as np from dss import dss, IDSS # IDSS for type hints and better autocomplete ``` -------------------------------- ### Exporting DSS Class Data to Pandas DataFrame Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/GettingStarted.ipynb Shows how to set the active class in DSS (e.g., 'load') using `SetActiveClass()`, export the data for all elements of that class as a JSON string using `ToJSON()`, and then read it directly into a Pandas DataFrame using `pd.read_json`. ```python import pandas as pd dss.ActiveCircuit.SetActiveClass('load') df = pd.read_json(dss.ActiveCircuit.ActiveClass.ToJSON(), dtype_backend='pyarrow') df.dtypes ``` -------------------------------- ### Set Voltage Limits, Load Multiplier, Solve, and Plot Profile using DSS Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Sets emergency and normal minimum voltage per unit limits, sets the load multiplier to 0.1 to simulate a minimum load case, solves the circuit, and then plots the voltage profile for all phases. ```dss %%dss set emergvminpu=1.0 set normvminpu=1.035 set loadmult=.1 solve plot profile phases = all ``` -------------------------------- ### Read DSS File and Find Transformer Definition (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Opens and reads a DSS circuit file line by line to locate the definition of the 'transformer.reg1' element, printing the definition line and any subsequent lines continued with the '~' character. ```python with open('electricdss-tst/Version8/Distrib/IEEETestCases/13Bus/IEEE13Nodeckt.dss', 'r') as ckt_file: for text_line in ckt_file: if 'transformer.reg1' in text_line.lower(): # Found the transformer print(text_line, end='') #...but need to check for the MORE command: text_line = next(ckt_file) while text_line.startswith('~'): print(text_line, end='') text_line = next(ckt_file) break ``` -------------------------------- ### Configuring macOS SDK in conda_build_config.yaml Source: https://github.com/dss-extensions/dss-python/blob/master/conda/README.md This YAML snippet shows how to configure the macOS SDK path within the conda_build_config.yaml file. This is necessary for conda-build to locate the correct SDK when compiling packages on macOS. ```YAML CONDA_BUILD_SYSROOT: - /opt/MacOSX10.9.sdk # [osx] ``` -------------------------------- ### Exporting Batch of DSS Objects to Pretty JSON using dss.Obj Batch API (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Imports the `Connection` enum from `dss.IObj`. It then uses the `batch()` method on the `Load` object collection to select all loads where the connection type (`conn`) is `Connection.delta`. Finally, it exports this batch of selected loads to a pretty-formatted JSON string using the `to_json()` method with the `DSSJSONFlags.Pretty` flag and prints the result. Dependencies: `dss.IObj` library. ```python from dss.IObj import Connection print(Load.batch(conn=Connection.delta).to_json(DSSJSONFlags.Pretty)) ``` -------------------------------- ### Exporting DSS Class to JSON using OpenDSSDirect.py (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Imports the `opendssdirect` library, aliasing it as `odd`. It then sets the active DSS class to 'Capacitor' using the `odd.Basic.SetActiveClass()` method and exports all objects of this class to a JSON string using `odd.ActiveClass.ToJSON()` with default options. Dependencies: `opendssdirect` library. ```python from opendssdirect import dss as odd odd.Basic.SetActiveClass('Capacitor') odd.ActiveClass.ToJSON() ``` -------------------------------- ### Initializing DSS and Matplotlib for API Customization Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Sets up the environment for customizing DSS plots using the matplotlib API. It disables auto-show, loads and solves a specific test circuit, selects a bus by name, and retrieves its coordinates for later use in adding custom elements. Requires `matplotlib.pyplot` and `dss`. ```python from matplotlib import pyplot as plt from dss import dss dss.Plotting.enable(show=False) # We'll use the EPRI ckt5 test circuit here dss.Text.Command = 'redirect electricdss-tst/Version8/Distrib/EPRITestCircuits/ckt5/Run_ckt5.dss' # Select a bus name = '820' bus = dss.ActiveCircuit.Buses[name] x, y = bus.x, bus.y print('Selected bus:', name) ``` -------------------------------- ### Change Directory, Redirect Circuit, and Solve using DSS Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Changes the current directory in the DSS engine to locate circuit files, redirects to a master circuit file, and then solves the circuit simulation. ```dss %%dss cd electricdss-tst/Version8/Distrib/EPRITestCircuits/epri_dpv/J1/ redirect "Master_noPV.dss" solve ``` -------------------------------- ### Plot Monitor Results from Daily Simulation in DSS Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Creates a new monitor object attached to a line element, assigns a daily loadshape to all loads using 'batchedit', solves the circuit in daily mode, and then plots the recorded data from the monitor object. ```dss new monitor.montest element=line.mdv201_connector batchedit load..* daily=commercial_sm solve mode=daily plot monitor object=montest ``` -------------------------------- ### Redirect, Set Export Visibility, and Export Voltages using DSS Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Redirects to a specific DSS circuit file, sets the showexport option to true to make export files visible, and then exports voltage data to a file. ```dss %%dss redirect electricdss-tst/Version8/Distrib/IEEETestCases/13Bus/IEEE13Nodeckt.dss set showexport=true export voltages ``` -------------------------------- ### Exporting Active DSS Element to Full JSON using OpenDSSDirect.py and Parsing (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Exports the currently active DSS element (presumably set by a previous command) to a JSON string using `odd.Element.ToJSON()` with the `DSSJSONFlags.Full` flag (including all properties), and then parses the resulting JSON string into a Python dictionary using `json.loads()`. Dependencies: `opendssdirect`, `json` libraries. ```python json.loads(odd.Element.ToJSON(DSSJSONFlags.Full)) ``` -------------------------------- ### Defining Number of Solutions Constant Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Multithreading.ipynb Sets a constant `NUM_SOLVE` which is used later in the notebook to specify the number of solutions to perform for each scenario. ```python NUM_SOLVE = 96 ``` -------------------------------- ### Exporting Active DSS Element to Full JSON and Parsing (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Sets the active transformer to 'reg1', exports the active DSS element to a JSON string using the `ToJSON()` method with the `DSSJSONFlags.Full` flag (including all properties), and then parses the resulting JSON string into a Python dictionary using `json.loads()`. Dependencies: `json` library. ```python dss.ActiveCircuit.Transformers.Name = 'reg1' json.loads(dss.ActiveCircuit.ActiveDSSElement.ToJSON(DSSJSONFlags.Full)) ``` -------------------------------- ### Importing DSS Enumerations (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/enumerations.md This snippet demonstrates how to import a specific enumeration, `SolveModes`, directly from the main `dss` module. This allows users to reference enums conveniently without needing to access the `dss.enums` submodule explicitly. Using these enums is recommended for clarity and is sometimes required for certain API functions. ```Python from dss import SolveModes ``` -------------------------------- ### Set Voltage Limit and Plot Profile for Primary and All Phases using DSS Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Sets the normal minimum voltage per unit limit for plotting, then plots the voltage profile specifically for primary phases and subsequently for all phases. ```dss %%dss set normvminpu=0.95 plot profile phases = primary plot profile phases = all ``` -------------------------------- ### Iterating over DSS Loads in Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/changelog.md This snippet demonstrates how to iterate directly over the Load objects within the active circuit using the dss-python API, leveraging the new iterable feature for most DSS classes introduced in version 0.10.0. ```Python for l in DSS.ActiveCircuit.Loads: print(l.Name) ``` -------------------------------- ### Plot Profile using DSS Magic Command Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Executes the 'plot profile' command directly in the DSS engine using the %%dss notebook magic command. This is a convenient way to run DSS commands interactively. ```dss %%dss plot profile ``` -------------------------------- ### Enable DSS Editor Output in Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Sets the AllowEditor property in dss-python to True, allowing DSS text outputs to open in the editor. This is the default behavior for show commands. ```python dss.AllowEditor = True ``` -------------------------------- ### Accessing Yprim with Advanced Types Enabled in DSS-Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/GettingStarted.ipynb Shows how to access the `Yprim` matrix of the active circuit element after setting `AdvancedTypes` to `True` in DSS-Python. The output will be a matrix, potentially containing complex numbers. ```python dss.ActiveCircuit.Lines.idx = 6 dss.ActiveCircuit.ActiveCktElement.Yprim ``` -------------------------------- ### Export Voltages using DSS Magic Command Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Executes the 'export voltages' command directly in the DSS engine using the %%dss notebook magic command. This exports voltage data to a file. ```dss %%dss export voltages ``` -------------------------------- ### Set Plot Options and Plot Circuit Power using DSS Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Sets marker code and regulator marking options for circuit plotting, then plots the circuit power flow for phase 3. This visualizes power flow on the network diagram. ```dss %%dss set markercode=24 set markregulators=yes plot circuit power 1ph=3 ``` -------------------------------- ### Compare Voltages with and without PV using DSS Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Solves the no-PV case and saves voltages, then solves the PV case with controls off, creates a voltage difference file using the vdiff command, sets plot options, and plots the voltage difference between the two cases. ```dss %%dss redirect "Master_noPV.dss" solve save voltages Redirect ExistingPV.dss ! Disable all controls set controlmode=off solve plot profile phases=all vdiff ! creates voltage difference file set markercode=24 nodewidth=2.5 ! Plot difference in voltage between no-PV and with-PV cases plot general quantity=1 max=3.5 min=0.0 C1=$0000FFFF C2=$000000FF dots=y labels=n object=electricdss-tst/Version8/Distrib/EPRITestCircuits/epri_dpv/J1/J1_VDIFF.txt ``` -------------------------------- ### Execute DSS Commands using IPython %%dss Cell Magic Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Shows how to use the `%%dss` cell magic in an IPython environment (like Jupyter) to execute DSS commands directly within a notebook cell. This provides a convenient way to run DSS scripts or commands interactively. ```ipython %%dss redirect somefile.dss ``` -------------------------------- ### Exporting DSS Class to JSON with Multiple Flags, Reading into Pandas, and Transposing Head (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Sets the active class to 'LineCode', exports all objects of this class to a JSON string using the `ToJSON()` method with `DSSJSONFlags.SkipDSSClass`, `DSSJSONFlags.SkipRedundant`, and `DSSJSONFlags.Full` flags combined using bitwise OR, reads the resulting JSON string into a pandas DataFrame, selects the first few rows using `.head()`, and transposes the resulting DataFrame using `.T`. Dependencies: `pandas` library. ```python dss.SetActiveClass('LineCode') pd.read_json(dss.ActiveCircuit.ActiveClass.ToJSON(DSSJSONFlags.SkipDSSClass | DSSJSONFlags.SkipRedundant | DSSJSONFlags.Full)).head().T ``` -------------------------------- ### Visualize Transformer Quantities in DSS Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Executes DSS 'visualize' commands to display power, current, and voltage magnitudes for a specific transformer element named 'xfm1'. This command typically opens a graphical representation or outputs data depending on the DSS environment. ```dss visualize powers Transformer.xfm1 visualize currents Transformer.xfm1 visualize voltages Transformer.xfm1 ``` -------------------------------- ### Adding Simple Bus Marker via DSS Command Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Shows how to add a simple marker to a specific bus on a DSS plot using DSS text commands. It clears previous markers, adds a red marker to the selected bus, and then plots the circuit. Requires `dss` and the `name` variable from the previous snippet. ```python dss.Text.Command = 'ClearBusMarkers' # remove the previous marker dss.Text.Command = f'AddBusMarker Bus={name} code=24 color=red size=5' dss.Text.Command = 'plot circuit c1=$555555' ``` -------------------------------- ### Exporting DSS Class to JSON with SkipDSSClass Flag, Reading into Pandas, and Transposing Head (Python) Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/JSON.ipynb Sets the active class to 'LineCode', exports all objects of this class to a JSON string using the `ToJSON()` method with the `DSSJSONFlags.SkipDSSClass` flag, reads the resulting JSON string into a pandas DataFrame, selects the first few rows using `.head()`, and transposes the resulting DataFrame using `.T`. Dependencies: `pandas` library. ```python dss.SetActiveClass('LineCode') pd.read_json(dss.ActiveCircuit.ActiveClass.ToJSON(DSSJSONFlags.SkipDSSClass)).head().T ``` -------------------------------- ### Define DSS Simulation Worker Function (Multithreading) - Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Multithreading.ipynb This function defines the core simulation logic executed by each thread. It takes a DSS context, a list of cases, and dictionaries for results and convergence. It pops cases from the list, loads the circuit, sets the load multiplier, solves the circuit, and stores the convergence status and bus voltages. ```python def _run(ctx: IDSS, case_list, converged, results): tname = threading.current_thread().name circ = ctx.ActiveCircuit while case_list: fn, load_mult = case_list.pop() ctx('clear') try: ctx(f'redirect "{fn}"') circ.Solution.LoadMult = load_mult # print(f'{tname}: Running "{fn}", circuit "{ctx.ActiveCircuit.Name}", mult={load_mult}') ctx(f'Solve mode=daily number={NUM_SOLVE}') except Exception as ex: print('ERROR:', tname, (fn, load_mult)) print(' ', ex.args) # print(f'{tname}: Done "{fn}" (LoadMult={load_mult}), circuit "{circ.Name}"') converged[(fn, load_mult)] = circ.Solution.Converged # Just get the voltages to compare later; an actual study could get other # useful values or calculate specific indices for each scenario results[(fn, load_mult)] = circ.AllBusVolts ``` -------------------------------- ### Applying Matplotlib Styles to DSS Plots Python Source: https://github.com/dss-extensions/dss-python/blob/master/docs/examples/Plotting.ipynb Shows how to apply different matplotlib styles temporarily using `plt.style.context` to plots generated by DSS commands. It first disables auto-show, loads and solves a circuit, then plots the circuit twice with different styles. Requires `matplotlib.pyplot` and `dss`. ```python from matplotlib import pyplot as plt from dss import dss dss.Plotting.enable(show=False) dss.Text.Command = 'redirect electricdss-tst/Version8/Distrib/EPRITestCircuits/ckt5/Run_ckt5.dss' dss.ActiveCircuit.Solution.Solve() with plt.style.context('dark_background'): dss.Text.Command = 'plot circuit c1=lime' with plt.style.context('Solarize_Light2'): dss.Text.Command = 'plot circuit c1=red' ```