### Install and Setup OpenDSSDirect.py Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Saving.ipynb Installs the opendssdirect.py package and downloads example circuits. This is a prerequisite for running the subsequent code examples. ```python # When running via Colab, install the package first import os, subprocess if os.getenv("COLAB_RELEASE_TAG"): print(subprocess.check_output('pip install opendssdirect.py[extras]', shell=True).decode()) # Download the sample circuits and test cases if they do not exist already from dss.examples import download_repo_snapshot REPO_PATH = download_repo_snapshot('.', repo_name='electricdss-tst', use_version=False) IEEE13_PATH = REPO_PATH / 'Version8/Distrib/IEEETestCases/13Bus/IEEE13Nodeckt.dss' assert IEEE13_PATH.exists() ``` -------------------------------- ### Install OpenDSSDirect.py with Extras (Windows) Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Installation.ipynb On Windows, double quotes may be required instead of single quotes for the package name when installing with extras. ```shell pip install "OpenDSSDirect.py[extras]" ``` -------------------------------- ### Install OpenDSSDirect.py with Extras Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Installation.ipynb Installs OpenDSSDirect.py along with optional dependencies like AltDSS-Python, Pandas, NetworkX, SciPy, and matplotlib. Recommended for exploring the ecosystem. ```bash pip install 'OpenDSSDirect.py[extras]' ``` -------------------------------- ### Access Bus Properties and Results in OpenDSSDirect.py Source: https://context7.com/dss-extensions/opendssdirect.py/llms.txt Demonstrates how to set an active bus, retrieve its name, number of nodes, node order, and base kV. Shows how to get various voltage representations (complex, magnitude-angle, per-unit, sequence) and line-to-line voltages. Includes examples for short-circuit analysis, retrieving bus coordinates, listing connected elements, and accessing reliability indices. ```python from opendssdirect import dss dss('Redirect "IEEE13Nodeckt.dss"') dss.Solution.Solve() # Set active bus dss.Circuit.SetActiveBus("671") # Get bus information print(f"Bus name: {dss.Bus.Name()}") print(f"Number of nodes: {dss.Bus.NumNodes()}") print(f"Node order: {dss.Bus.Nodes()}") print(f"kV base: {dss.Bus.kVBase()}") # Get voltages voltages = dss.Bus.Voltages() # Complex array vmag_angle = dss.Bus.VMagAngle() # [mag1, angle1, mag2, angle2, ...] pu_voltages = dss.Bus.PuVoltage() # Per-unit complex voltages seq_voltages = dss.Bus.SeqVoltages() # Sequence voltage magnitudes print(f"Voltages (complex): {voltages}") print(f"Per-unit voltages: {pu_voltages}") # Line-to-line voltages (for 2 or 3-phase buses) vll = dss.Bus.VLL() pu_vll = dss.Bus.puVLL() # Short circuit analysis (requires ZscRefresh first) dss.Bus.ZscRefresh() zsc0 = dss.Bus.Zsc0() # Zero-sequence short circuit impedance zsc1 = dss.Bus.Zsc1() # Positive-sequence short circuit impedance isc = dss.Bus.Isc() # Short circuit currents voc = dss.Bus.Voc() # Open circuit voltages # Bus coordinates if dss.Bus.Coorddefined(): x = dss.Bus.X() y = dss.Bus.Y() print(f"Coordinates: ({x}, {y})") # Connected elements pce_list = dss.Bus.AllPCEatBus() # Power Conversion Elements pde_list = dss.Bus.AllPDEatBus() # Power Delivery Elements load_list = dss.Bus.LoadList() line_list = dss.Bus.LineList() # Reliability indices print(f"Distance from source: {dss.Bus.Distance()}") print(f"Customers downstream: {dss.Bus.N_Customers()}") print(f"Failure rate (lambda): {dss.Bus.Lambda()}") ``` -------------------------------- ### Minimal Installation of OpenDSSDirect.py Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Installation.ipynb Installs only the core OpenDSSDirect.py package, which depends on DSS-Python. Useful for restricted environments. ```bash pip install OpenDSSDirect.py ``` -------------------------------- ### Output of DSS context initialization Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Multithreading.ipynb Example output showing the number of DSS contexts initialized for parallel processing. ```text Using 24 DSS contexts ``` -------------------------------- ### Install OpenDSSDirect.py in Editable Mode with Extras and Dev Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Installation.ipynb Installs OpenDSSDirect.py in editable mode, including development dependencies and extras. This is useful for contributing to the project. ```bash pip install -e '.[extras,dev]' --upgrade ``` -------------------------------- ### Migrate from COM Implementation - Load OpenDSS Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/GettingStarted.ipynb Example of loading the OpenDSS engine using the COM implementation with win32com.client. This is for comparison with OpenDSSDirect.py. ```python # Load OpenDSS import win32com.client dss = win32com.client.Dispatch('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 = 'Redirect "../../tests/data/13Bus/IEEE13Nodeckt.dss"' # 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 ``` -------------------------------- ### Add Storage Elements to Circuit Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/ActiveClass.ipynb Use the `dss.Command` to add new Storage elements to the circuit. Ensure the `extras` dependencies are installed. This example adds two storage units with specified ratings and initial states. ```python from opendssdirect import dss dss('Redirect "../../tests/data/13Bus/IEEE13Nodeckt.dss"') dss.Circuit.AllBusNames() dss.Command( "New Storage.{bus_name} Bus1={bus_name} phases=1 kV=2.2 kWRated={rating} kWhRated={kwh_rating} kWhStored={initial_state} %IdlingkW=0 %reserve=0 %EffCharge=100 %EffDischarge=100 State=CHARGING".format( bus_name='675', rating=20, kwh_rating=20, initial_state=20 )) dss.Command( "New Storage.{bus_name} Bus1={bus_name} phases=1 kV=2.2 kWRated={rating} kWhRated={kwh_rating} kWhStored={initial_state} %IdlingkW=0 %reserve=0 %EffCharge=100 %EffDischarge=100 State=CHARGING".format( bus_name='611', rating=20, kwh_rating=20, initial_state=20 )) dss.Solution.Solve() ``` -------------------------------- ### Install OpenDSSDirect.py in Editable Mode (Escaped Brackets) Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Installation.ipynb On some systems, brackets in the package name may need to be escaped when installing in editable mode with extras and dev dependencies. ```bash pip install -e '.\ [extras,dev\]' --upgrade ``` -------------------------------- ### Create and start simulation threads Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Multithreading.ipynb Initializes and starts multiple threads, each executing the `_run` worker function with a dedicated DSS context and a shared list of cases. The threads consume cases from `cases_to_run_threads` and store results in `tconverged` and `tresults`. ```python 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() ``` -------------------------------- ### Executing DSS Commands Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Example-OpenDSSDirect.py.ipynb Shows how to execute DSS commands using `dss.Command()` and the shorthand `dss()`. Includes examples of both successful execution and error handling. ```APIDOC ## Executing DSS Commands ### Description The `dss.Command()` method (or its shorthand `dss()`) allows you to execute any valid OpenDSS script command. The high-level interface automatically handles errors by raising `DSSException`. ### Method ```python # Example of a command that will cause an error dss.Command('Redirect this_file_does_not_exist.dss') ``` ### Error Response Example ``` DSSException: (#243) Redirect file not found: "this_file_does_not_exist.dss" ``` ### Method ```python # Example of a successful command execution dss.Command('Redirect "../../tests/data/13Bus/IEEE13Nodeckt.dss"') # Shorthand for single command dss('Redirect "../../tests/data/13Bus/IEEE13Nodeckt.dss"') # Executing multiple commands using a multi-line string dss(""" Redirect "../../tests/data/13Bus/IEEE13Nodeckt.dss" Solve """ ) ``` ``` -------------------------------- ### Upgrade OpenDSSDirect.py with Extras Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Installation.ipynb Upgrades an existing installation of OpenDSSDirect.py to the latest version, including all optional dependencies. ```bash pip install 'OpenDSSDirect.py[extras]' --upgrade ``` -------------------------------- ### Access Circuit Information Source: https://context7.com/dss-extensions/opendssdirect.py/llms.txt Shows how to load a circuit and retrieve various circuit-wide details such as name, bus count, element count, node count, bus names, element names, losses, and power. Also includes examples for setting active bus and enabling/disabling elements. ```python from opendssdirect import dss # Load a circuit dss('Redirect "IEEE13Nodeckt.dss"') # Get circuit information print(f"Circuit name: {dss.Circuit.Name()}") print(f"Number of buses: {dss.Circuit.NumBuses()}") print(f"Number of elements: {dss.Circuit.NumCktElements()}") print(f"Number of nodes: {dss.Circuit.NumNodes()}") # Get all bus names bus_names = dss.Circuit.AllBusNames() print(f"Buses: {bus_names}") # Get all element names element_names = dss.Circuit.AllElementNames() # Get circuit losses (complex kW + jkvar) total_losses = dss.Circuit.Losses() print(f"Total losses: {total_losses[0]/1000:.2f} kW + j{total_losses[1]/1000:.2f} kvar") # Get line losses line_losses = dss.Circuit.LineLosses() # Get total power delivered to circuit total_power = dss.Circuit.TotalPower() print(f"Total power: {total_power}") # Get all bus voltage magnitudes all_vmag = dss.Circuit.AllBusVMag() all_vmag_pu = dss.Circuit.AllBusMagPu() # Get all bus voltages (complex) all_voltages = dss.Circuit.AllBusVolts() # Set active bus and get its voltages dss.Circuit.SetActiveBus("671") voltages = dss.Bus.Voltages() print(f"Bus 671 voltages: {voltages}") # Enable/disable circuit elements dss.Circuit.Disable("Load.Load1") dss.Circuit.Enable("Load.Load1") # Export circuit to JSON json_str = dss.Circuit.ToJSON() ``` -------------------------------- ### Iterate and Access Line Properties in OpenDSSDirect.py Source: https://context7.com/dss-extensions/opendssdirect.py/llms.txt Demonstrates iterating through all lines in a circuit using both Python iterators and explicit first/next calls. Shows how to access and print various line properties like name, buses, length, phases, and impedance. Also includes examples of accessing specific lines by name and modifying line parameters. ```python from opendssdirect import dss from opendssdirect.enums import LineUnits dss('Redirect "IEEE13Nodeckt.dss"') # Iterate through all lines using Python iterator for line in dss.Lines: print(f"Line: {line.Name()}") print(f" Bus1: {line.Bus1()}, Bus2: {line.Bus2()}") print(f" Length: {line.Length()} {line.Units()}") print(f" Phases: {line.Phases()}") # Alternative iteration method line_count = dss.Lines.Count() print(f"Total lines: {line_count}") dss.Lines.First() for _ in range(line_count): name = dss.Lines.Name() r1 = dss.Lines.R1() x1 = dss.Lines.X1() print(f"{name}: R1={r1:.4f}, X1={x1:.4f} ohms/unit length") dss.Lines.Next() # Access specific line by name dss.Lines.Name("650632") print(f"Line 650632:") print(f" LineCode: {dss.Lines.LineCode()}") print(f" Normal amps: {dss.Lines.NormAmps()}") print(f" Emergency amps: {dss.Lines.EmergAmps()}") print(f" Customers: {dss.Lines.NumCust()}") # Modify line properties dss.Lines.Length(1.5) dss.Lines.R1(0.01) dss.Lines.X1(0.04) dss.Lines.Units(LineUnits.mi) # Get impedance matrices r_matrix = dss.Lines.RMatrix() x_matrix = dss.Lines.XMatrix() c_matrix = dss.Lines.CMatrix() # Get Yprim (primitive admittance matrix) yprim = dss.Lines.Yprim() # Check if line is a switch is_switch = dss.Lines.IsSwitch() ``` -------------------------------- ### Access and Modify Load Properties in OpenDSSDirect.py Source: https://context7.com/dss-extensions/opendssdirect.py/llms.txt Shows how to retrieve all load names, count total loads, and iterate through each load to access its properties like kW, kvar, kV, PF, phases, and status. Includes examples of accessing specific loads by name, modifying their parameters, setting voltage limits, and configuring load shapes and ZIPV coefficients. ```python from opendssdirect import dss from opendssdirect.enums import LoadStatus dss('Redirect "IEEE13Nodeckt.dss"') # Get all load names load_names = dss.Loads.AllNames() print(f"Loads in circuit: {load_names}") print(f"Total loads: {dss.Loads.Count()}") # Iterate through loads for load in dss.Loads: print(f"Load {load.Name()}:") print(f" kW: {load.kW()}, kvar: {load.kvar()}") print(f" kV: {load.kV()}, PF: {load.PF():.3f}") print(f" Phases: {load.Phases()}") # Access specific load dss.Loads.Name("671") print(f"\nLoad 671 details:") print(f" kW: {dss.Loads.kW()}") print(f" kvar: {dss.Loads.kvar()}") print(f" kVA base: {dss.Loads.kVABase()}") print(f" Model: {dss.Loads.Model()}") # 1=PQ, 2=Z, 5=CVR print(f" Is Delta: {dss.Loads.IsDelta()}") print(f" Status: {dss.Loads.Status()}") # Modify load properties dss.Loads.kW(1200.0) dss.Loads.PF(0.95) dss.Loads.Model(1) # Constant PQ model # Set voltage limits for load model switching dss.Loads.Vminpu(0.85) dss.Loads.Vmaxpu(1.10) # Load allocation factors dss.Loads.AllocationFactor(0.8) dss.Loads.CFactor(4.0) # Average to peak ratio # Load shapes for time-varying simulations dss.Loads.Daily("default") dss.Loads.Yearly("default") # ZIPV coefficients for voltage-dependent load model zipv = dss.Loads.ZipV() # Array of 7 coefficients ``` -------------------------------- ### Get Voltage Magnitudes with OpenDSSDirect.py Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/GettingStarted.ipynb Retrieves voltage magnitudes using the OpenDSSDirect.py instance (`odd`), demonstrating an alternative to the DSS-Python compatible interface. ```python voltages2 = odd.Circuit.AllBusVMag() list(voltages) == list(voltages2) ``` -------------------------------- ### Get OpenDSSDirect.py and Engine Versions Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Example-OpenDSSDirect.py.ipynb Print the versions of the OpenDSSDirect.py package and its underlying DSS engine. This is useful for debugging and compatibility checks. ```python print('OpenDSSDirect.py and engine versions:', dss.Version()) ``` -------------------------------- ### Export Circuit Data to Pandas DataFrames Source: https://context7.com/dss-extensions/opendssdirect.py/llms.txt Shows how to export various circuit elements like loads, lines, and transformers into pandas DataFrames for easier data manipulation and analysis. Requires the pandas library to be installed. ```python from opendssdirect import dss dss('Redirect "IEEE13Nodeckt.dss"') dss.Solution.Solve() # Export element data to DataFrames loads_df = dss.utils.loads_to_dataframe() lines_df = dss.utils.lines_to_dataframe() transformers_df = dss.utils.transformers_to_dataframe() generators_df = dss.utils.generators_to_dataframe() capacitors_df = dss.utils.capacitors_to_dataframe() print("Loads DataFrame:") print(loads_df[['kW', 'kvar', 'kV', 'PF', 'Phases']].head()) print("\nLines DataFrame:") print(lines_df[['Bus1', 'Bus2', 'Length', 'Phases']].head()) # Generic DataFrame export for any iterable from opendssdirect.utils import to_dataframe meters_df = to_dataframe(dss.Meters) # JSON export (preferred for large circuits) circuit_json = dss.Circuit.ToJSON() # Save circuit to file dss.Circuit.Save("./output", 0) # Class-level JSON export loads_json = dss.ActiveClass.ToJSON() ``` -------------------------------- ### Accessing Load Properties Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Example-OpenDSSDirect.py.ipynb Demonstrates how to get the value of various Load properties using OpenDSSDirect.py. Properties are accessed by calling their corresponding functions without arguments. ```APIDOC ## Accessing Load Properties ### Description This section shows how to retrieve the current values of different properties associated with a Load object in OpenDSSDirect.py. To get a property's value, call the corresponding method with no arguments. ### Method GET (Implicit) ### Endpoint N/A (Direct property access) ### Parameters None ### Request Example ```python # Get the kW of the active load kw_value = dss.Loads.kW() # Get the kV base of the active load kva_base_value = dss.Loads.kVABase() # Get the number of phases phases_value = dss.Loads.Phases() ``` ### Response #### Success Response (200) - **Value** (float/int) - The current value of the requested property. #### Response Example ```json { "example": "120.0" } ``` ``` -------------------------------- ### Create Network Graph and Position Data Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/VoltageProfilePlot.ipynb Generates a NetworkX graph from OpenDSS line data and calculates node positions based on distance and voltage. Requires 'networkx' and 'matplotlib' to be installed. ```python import networkx as nx import matplotlib.pyplot as plt from opendssdirect import dss df = dss.utils.lines_to_dataframe() def create_graph(phase=1): G = nx.Graph() data = df[['Bus1', 'Bus2']].to_dict(orient="index") for name in data: line = data[name] if f".{phase}" in line["Bus1"] and f".{phase}" in line["Bus2"]: G.add_edge(line["Bus1"].split(".")[0], line["Bus2"].split(".")[0]) pos = {} for name in dss.Circuit.AllBusNames(): dss.Circuit.SetActiveBus(f"{name}") if phase in dss.Bus.Nodes(): index = dss.Bus.Nodes().index(phase) re, im = dss.Bus.PuVoltage()[index:index+2] V = abs(complex(re, im)) D = dss.Bus.Distance() pos[dss.Bus.Name()] = (D, V) return G, pos ``` -------------------------------- ### Initialize and Execute DSS Commands Source: https://context7.com/dss-extensions/opendssdirect.py/llms.txt Demonstrates how to initialize the OpenDSSDirect.py interface and execute DSS commands using both a callable shortcut and the Text.Command method. Also shows how to check the DSS version. ```python from opendssdirect import dss # Execute DSS commands using the callable shortcut dss(""" clear new Circuit.TestCircuit basekv=115 pu=1.05 angle=30 new Line.Line1 bus1=sourcebus bus2=bus1 length=1 units=mi new Load.Load1 bus1=bus1 phases=3 kv=4.16 kw=500 pf=0.9 ") # Or use Text.Command for single commands dss.Text.Command('Redirect "path/to/circuit.dss"') # Check DSS version print(dss.Version) # e.g., "0.9.0" ``` -------------------------------- ### Get All Transformer Data as Pandas DataFrame Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/GettingStarted.ipynb Use this function to retrieve all transformer data from OpenDSS and return it as a pandas DataFrame. Ensure pandas is installed. ```python dss.utils.transformers_to_dataframe() ``` -------------------------------- ### Get All Load Data as Pandas DataFrame Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/GettingStarted.ipynb Use this function to retrieve all load data from OpenDSS and return it as a pandas DataFrame. Ensure pandas is installed. ```python dss.utils.loads_to_dataframe() ``` -------------------------------- ### Basic Usage and Initialization Source: https://context7.com/dss-extensions/opendssdirect.py/llms.txt Demonstrates how to initialize OpenDSSDirect.py and execute DSS commands. ```APIDOC ## Basic Usage and Initialization The main entry point is the `dss` instance which provides access to all OpenDSS interfaces. Use it to execute DSS commands and access circuit elements. ### Request Example ```python from opendssdirect import dss # Execute DSS commands using the callable shortcut dss(""" clear new Circuit.TestCircuit basekv=115 pu=1.05 angle=30 new Line.Line1 bus1=sourcebus bus2=bus1 length=1 units=mi new Load.Load1 bus1=bus1 phases=3 kv=4.16 kw=500 pf=0.9 ") # Or use Text.Command for single commands dss.Text.Command('Redirect "path/to/circuit.dss"') # Check DSS version print(dss.Version) # e.g., "0.9.0" ``` ``` -------------------------------- ### Create and Use Multiple DSS Contexts Source: https://context7.com/dss-extensions/opendssdirect.py/llms.txt Demonstrates how to create independent DSS engine instances for parallel simulations. Each context can load and solve different circuits independently. ```python from opendssdirect import dss import threading # Create new independent DSS context dss2 = dss.NewContext() # Each context is independent dss('new Circuit.Circuit1 basekv=115') dss2('new Circuit.Circuit2 basekv=230') print(f"Context 1 circuit: {dss.Circuit.Name()}") print(f"Context 2 circuit: {dss2.Circuit.Name()}") # Parallel simulation function def run_simulation(dss_ctx, circuit_file, results): dss_ctx(f'Redirect "{circuit_file}"') dss_ctx.Solution.Solve() results['losses'] = dss_ctx.Circuit.Losses() results['converged'] = dss_ctx.Solution.Converged() # Run simulations in parallel results1 = {} results2 = {} t1 = threading.Thread(target=run_simulation, args=(dss.NewContext(), "circuit1.dss", results1)) t2 = threading.Thread(target=run_simulation, args=(dss.NewContext(), "circuit2.dss", results2)) t1.start() t2.start() t1.join() t2.join() # Convert to DSS-Python or AltDSS for alternative APIs dss_python = dss.to_dss_python() # altdss = dss.to_altdss() # Requires altdss package ``` -------------------------------- ### Basic Usage and Version Check Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Example-OpenDSSDirect.py.ipynb Demonstrates how to import the OpenDSSDirect.py module and check the versions of the engine and the package. ```APIDOC ## Basic Usage and Version Check ### Description Import the `opendssdirect` module and use the `dss` instance to access OpenDSS functionalities. This example shows how to retrieve version information. ### Method ```python from opendssdirect import dss print('OpenDSSDirect.py and engine versions:', dss.Version()) ``` ### Response Example ``` OpenDSSDirect.py and engine versions: DSS C-API Library version DEV revision UNKNOWN based on OpenDSS SVN UNKNOWN [FPC 3.2.2] (64-bit build) MVMULT INCREMENTAL_Y CONTEXT_API PM 20240206090705; License Status: Open DSS-Python version: 0.0dev OpenDSSDirect.py version: 0.0dev ``` ``` -------------------------------- ### Get Active Load kW Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Example-OpenDSSDirect.py.ipynb Retrieve the kW value of the active load. This demonstrates calling a property function without arguments to get its value. ```python dss.Loads.kW() ``` -------------------------------- ### Manage Multiple DSS Instances with Contexts Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/updating_to_0.9.md Demonstrates how to create and manage multiple independent DSS instances using `NewContext()`. It's recommended to disable automatic directory changes when using multiple contexts to avoid unexpected behavior. ```python from opendssdirect import dss as odd_default # When using multiple contexts, it's better avoid changing the # working directory of the process odd_default.Basic.AllowChangeDir(False) odd1 = odd_default.NewContext() odd2 = odd_default.NewContext() odd1('new circuit.circuit1') odd2('new circuit.circuit2') assert odd1.Circuit.Name() == 'circuit1' assert odd2.Circuit.Name() == 'circuit2' ``` -------------------------------- ### Initialize result storage Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Multithreading.ipynb Sets up dictionaries to store the convergence status and results (voltages) from both threaded and sequential simulations. ```python tresults = {} tconverged = {} sresults = {} sconverged = {} ``` -------------------------------- ### Query DSS Engine Property and Get Result Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Example-OpenDSSDirect.py.ipynb Query a property from the DSS engine using a direct call to `dss` and then retrieve the text result using `dss.Text.Result()`. This is useful for getting scalar string outputs from DSS commands. ```python dss('? Load.634a.kW') ``` ```python dss.Text.Result() ``` -------------------------------- ### Get the Number of Lines Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/GettingStarted.ipynb Retrieves the total count of lines in the circuit using the `dss.Lines` iterator. ```python print(len(dss.Lines)) ``` -------------------------------- ### Initialize and Use DSS-Python Compatible Instance Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/GettingStarted.ipynb Initializes OpenDSSDirect.py and creates a DSS-Python compatible instance, aliased as `dss`. This allows using DSS-Python syntax with OpenDSSDirect.py. ```python from opendssdirect import dss as odd dss = odd.to_dss_python() dss.Text.Command = 'Redirect "../../tests/data/13Bus/IEEE13Nodeckt.dss"' dss.ActiveCircuit.Loads.Name = "675c" dss.ActiveCircuit.Loads.kW = 320 dss.ActiveCircuit.Solution.Solve() voltages = dss.ActiveCircuit.AllBusVmag ``` -------------------------------- ### Get Voltage Magnitudes Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/GettingStarted.ipynb Retrieves the voltage magnitudes for all buses in the active circuit after a solution has been computed. ```python voltages = dss.Circuit.AllBusVMag() ``` -------------------------------- ### Perform Power Flow Solutions Source: https://context7.com/dss-extensions/opendssdirect.py/llms.txt Demonstrates how to control power flow solutions, including setting solution modes, configuring time-series parameters, adjusting load multipliers, and running simulations. It also covers setting frequency, convergence criteria, and retrieving solution status. ```python from opendssdirect import dss from opendssdirect.enums import SolveModes, ControlModes # Load circuit dss('Redirect "IEEE13Nodeckt.dss"') # Basic power flow solution dss.Solution.Solve() print(f"Converged: {dss.Solution.Converged()}") print(f"Iterations: {dss.Solution.Iterations()}") print(f"Process time: {dss.Solution.ProcessTime():.4f} seconds") # Set solution mode for time-series simulation dss.Solution.Mode(SolveModes.Daily) # Daily simulation print(f"Mode: {dss.Solution.ModeID()}") # Configure time-series parameters dss.Solution.Number(24) # Number of solutions dss.Solution.StepSize(3600) # Step size in seconds (1 hour) dss.Solution.Hour(0) # Starting hour # Set load multiplier dss.Solution.LoadMult(1.2) # 120% of nominal load # Control mode settings dss.Solution.ControlMode(ControlModes.Static) dss.Solution.MaxControlIterations(10) # Run the simulation for i in range(24): dss.Solution.Solve() hour = dss.Solution.Hour() total_power = dss.Circuit.TotalPower() print(f"Hour {hour}: P = {-total_power[0]:.2f} kW") # Set frequency for analysis dss.Solution.Frequency(60.0) # Solution tolerance and iteration limits dss.Solution.Convergence(0.0001) dss.Solution.MaxIterations(100) # Get incidence matrix information bus_levels = dss.Solution.BusLevels() inc_matrix = dss.Solution.IncMatrix() ``` -------------------------------- ### Get Active Load Name Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Example-OpenDSSDirect.py.ipynb Retrieve the name of the currently active load. This is useful for identifying the load being manipulated. ```python dss.Loads.Name() ``` -------------------------------- ### Retrieving Text Results Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Example-OpenDSSDirect.py.ipynb Demonstrates how to get text output from the DSS engine after executing a command, using `dss.Text.Result()`. ```APIDOC ## Retrieving Text Results ### Description After executing a command that produces text output (e.g., querying a property), you can retrieve the result using `dss.Text.Result()`. ### Method ```python # Query a property dss('? Load.634a.kW') # Retrieve the result result = dss.Text.Result() print(f'Result: {result}') ``` ### Response Example ``` Result: '160' ``` ``` -------------------------------- ### Get All Load Names Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Example-OpenDSSDirect.py.ipynb Retrieve a list of all load names in the circuit. This function call returns a Python list of strings. ```python dss.Loads.AllNames() ``` -------------------------------- ### Access and Control Monitors Source: https://context7.com/dss-extensions/opendssdirect.py/llms.txt Demonstrates how to create, configure, solve, and retrieve data from monitors for time-series analysis. This includes saving, resetting, and sampling monitors, as well as converting data to a pandas DataFrame. ```python from opendssdirect import dss dss(""" Redirect "IEEE13Nodeckt.dss" new Monitor.mon_671 element=Load.671 terminal=1 mode=0 new Monitor.mon_line element=Line.650632 terminal=1 mode=0 """) # Run a daily simulation dss.Solution.Mode(1) # Daily mode dss.Solution.Number(24) dss.Solution.StepSize(3600) dss.Solution.Solve() # Save all monitors dss.Monitors.SaveAll() # Get monitor names print(f"Monitor count: {dss.Monitors.Count()}") print(f"Monitor names: {dss.Monitors.AllNames()}") # Access specific monitor dss.Monitors.Name("mon_671") print(f"\nMonitor mon_671:") print(f" Element: {dss.Monitors.Element()}") print(f" Terminal: {dss.Monitors.Terminal()}") print(f" Mode: {dss.Monitors.Mode()}") print(f" Channels: {dss.Monitors.NumChannels()}") print(f" Sample count: {dss.Monitors.SampleCount()}") # Get channel headers headers = dss.Monitors.Header() print(f" Headers: {headers}") # Get specific channel data (1-indexed) channel1 = dss.Monitors.Channel(1) print(f" Channel 1 data: {channel1[:5]}...") # Get all data as matrix data_matrix = dss.Monitors.AsMatrix() print(f" Data shape: {data_matrix.shape if data_matrix is not None else 'None'}") # Get hour/time arrays hours = dss.Monitors.dblHour() print(f" Hours: {hours[:5]}...") # Monitor control dss.Monitors.Reset() # Reset active monitor dss.Monitors.ResetAll() # Reset all monitors dss.Monitors.Sample() # Take sample from active monitor dss.Monitors.SampleAll() # Sample all monitors # Using pandas utility for monitor data from opendssdirect.utils import monitor_to_dataframe df = monitor_to_dataframe() print(df.head()) ``` -------------------------------- ### Run DSS Script Snippets in Notebooks Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/VoltageProfilePlot.ipynb Demonstrates how to run DSS script snippets directly within notebook cells using the '%%dss' magic command. This enables interactive script execution and visualization. ```python %%dss BatchEdit Load..* daily=default New Monitor.Sub Element=Transformer.sub Terminal=2 Mode=1 Solve Mode=Daily Plot Monitor Object=Sub ``` -------------------------------- ### Get Load Phases Property Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Example-OpenDSSDirect.py.ipynb Retrieve the number of phases for the active Load. This is an API extension not present in the original OpenDSS COM. ```python ? dss.Loads.Phases ``` -------------------------------- ### Load a Circuit Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Saving.ipynb Loads the IEEE13Nodeckt.dss circuit. This step is necessary before saving or exporting the circuit. ```python # Don't forget to load a circuit first: odd(f'redirect "{IEEE13_PATH}"') ``` -------------------------------- ### Plot Sparse Y Matrix with Matplotlib Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/SystemY.ipynb Visualize the sparsity pattern of the Y matrix using matplotlib's spy function. This requires matplotlib to be installed. ```python from matplotlib import pyplot as plt plt.spy(systemY) ``` -------------------------------- ### Create and Control Generators Source: https://context7.com/dss-extensions/opendssdirect.py/llms.txt Demonstrates creating a circuit with a generator, solving the circuit, and accessing/modifying generator properties. Ensure the 'GeneratorStatus' enum is available if using it. ```python dss("\n clear\n new Circuit.GenTest basekv=12.47 pu=1.0\n new Line.Line1 bus1=sourcebus bus2=bus1 length=1 units=mi r1=0.01 x1=0.04\n new Generator.Gen1 bus1=bus1 phases=3 kv=12.47 kw=500 pf=0.9 model=1\n new Load.Load1 bus1=bus1 phases=3 kv=12.47 kw=1000 pf=0.95\n") dss.Solution.Solve() # Get generator count and names print(f"Generator count: {dss.Generators.Count()}") print(f"Generator names: {dss.Generators.AllNames()}") # Access generator by name dss.Generators.Name("Gen1") print(f"\nGenerator Gen1:") print(f" kW: {dss.Generators.kW()}") print(f" kvar: {dss.Generators.kvar()}") print(f" kVA rated: {dss.Generators.kVARated()}") print(f" kV: {dss.Generators.kV()}") print(f" Power Factor: {dss.Generators.PF()}") print(f" Phases: {dss.Generators.Phases()}") print(f" Model: {dss.Generators.Model()}") print(f" Bus: {dss.Generators.Bus1()}") # Modify generator settings dss.Generators.kW(750.0) dss.Generators.PF(0.95) dss.Generators.ForcedON(True) # Force generator ON # Generator status (Fixed or Variable dispatch) dss.Generators.Status(GeneratorStatus.Variable) # Generator limits dss.Generators.Vminpu(0.9) dss.Generators.Vmaxpu(1.1) # Load shapes for time-varying generation dss.Generators.daily("solar_shape") dss.Generators.Yearly("yearly_gen") # Get register values for energy metering register_names = dss.Generators.RegisterNames() register_values = dss.Generators.RegisterValues() ``` -------------------------------- ### Deprecated Iterator Usage (Pre-v0.9) Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Example-OpenDSSDirect.py.ipynb Provides an example of using the deprecated `Iterator` class from the `utils` module for iterating over loads in versions prior to v0.9. ```APIDOC ## Deprecated Iterator Usage (Pre-v0.9) ### Description For versions of OpenDSSDirect.py prior to v0.9, the `utils.Iterator` class could be used to iterate over objects. This method has greater overhead compared to native Python iteration and is now deprecated. Prefer using standard Python `for` loops. ### Method ITERATE (Deprecated) ### Endpoint N/A (Iteration over collection) ### Parameters - **obj** (object) - The object to iterate over (e.g., `dss.Loads`). - **property_name** (string) - The name of the property to retrieve for each object. ### Request Example ```python from opendssdirect.utils import Iterator # Get kW for all loads using the deprecated Iterator load_kW = [i() for i in Iterator(dss.Loads, 'kW')] print(load_kW) ``` ### Response #### Success Response (200) - **Output** (list) - A list containing the requested property values for each load. #### Response Example ```json { "example": "[1155.0, 160.0, 120.0, ...]" } ``` ``` -------------------------------- ### Settings Module Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/opendssdirect.md Documentation for the `Settings` module, controlling various OpenDSS simulation settings. ```APIDOC ## opendssdirect.Settings ```autodoc2-object``` opendssdirect.Settings.ISettings ``` -------------------------------- ### Get Load kW Property Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Example-OpenDSSDirect.py.ipynb Retrieve the kW property of the active Load. This method corresponds to the OpenDSS COM API's kW property. ```python ? dss.Loads.kW ``` -------------------------------- ### Instantiate OpenDSSDirect with NumPy Preference Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/updating_to_0.9.md Shows how to instantiate `OpenDSSDirect` to prefer NumPy arrays over Python lists for results. This can be set globally via an environment variable or per instance using the `prefer_lists` constructor argument. ```python from opendssdirect.OpenDSSDirect import OpenDSSDirect from numpy import ndarray # NOTE: this constructors ALWAYS binds to the default DSS engine. odd_np = OpenDSSDirect(prefer_lists=False) # Use it normally odd_np(f"Redirect '{PATH_TO_DSS}'") assert isinstance(odd_np.Circuit.AllBusMagPu(), ndarray) odd_lst = OpenDSSDirect(prefer_lists=True) # Same global instance, we can just reuse the result assert isinstance(odd_lst.Circuit.AllBusMagPu(), list) ``` -------------------------------- ### Define IEEE4 Bus Circuit Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Saving.ipynb Defines a 4-bus circuit for testing compatibility flags. This setup is used to demonstrate the effect of property tracking on output. ```python IEEE4_DSS = ''' clear Set DefaultBaseFrequency=60 new circuit.4busDYBal basekV=12.47 phases=3 mvasc3=200000 200000 set earthmodel=carson new wiredata.conductor Runits=mi Rac=0.306 GMRunits=ft GMRac=0.0244 Radunits=in Diam=0.721 normamps=530 new wiredata.neutral Runits=mi Rac=0.592 GMRunits=ft GMRac=0.00814 Radunits=in Diam=0.563 normamps=340 new linegeometry.4wire nconds=4 nphases=3 reduce=yes ~ cond=1 wire=conductor units=ft x=-4 h=28 ~ cond=2 wire=conductor units=ft x=-1.5 h=28 ~ cond=3 wire=conductor units=ft x=3 h=28 ~ cond=4 wire=neutral units=ft x=0 h=24 new line.line1 geometry=4wire length=2000 units=ft bus1=sourcebus bus2=n2 new transformer.t1 xhl=6 ~ wdg=1 bus=n2 conn=delta kV=12.47 kVA=6000 %r=0.5 ~ wdg=2 bus=n3 conn=wye kV=4.16 kVA=6000 %r=0.5 new line.line2 bus1=n3 bus2=n4 geometry=4wire length=2500 units=ft new load.load1 phases=3 bus1=n4 conn=wye kV=4.16 kW=5400 pf=0.9 model=1 vminpu=0.75 set voltagebases=[12.47, 4.16] ''' ``` -------------------------------- ### Import OpenDSS Direct Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/VoltageProfilePlot.ipynb Import the necessary OpenDSS Direct library for interacting with OpenDSS. ```python from opendssdirect import dss ``` -------------------------------- ### Get Dense System Y Matrix Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/SystemY.ipynb Access the entire dense system Y matrix. This method is memory-intensive and not recommended for large circuits, but is kept for compatibility with the official OpenDSS COM implementation. ```python dss.Circuit.SystemY() # avoid, this is a dense matrix (memory intensive) ``` -------------------------------- ### OpenDSSDirect Class Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/opendssdirect.md The main OpenDSSDirect class, exposed as the default instance `dss`, provides access to all submodules and additional functions. ```APIDOC ## OpenDSSDirect Class This class, as exposed in the default instance `dss` (`from opendssdirect import dss`), has attributes representing all the submodules listed in the next section, plus extra functions. ```autodoc2-object``` opendssdirect.OpenDSSDirect.OpenDSSDirect ``` -------------------------------- ### Get Sparse Y Matrix Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/SystemY.ipynb Retrieve the compressed sparse representation of the system's Y matrix using getYsparse(). This is efficient for large systems. It is recommended to use scipy.sparse for handling this data. ```python from scipy.sparse import csc_matrix systemY = csc_matrix(dss.YMatrix.getYsparse()) ``` -------------------------------- ### Progress Module Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/opendssdirect.md Documentation for the `Progress` module, likely for tracking simulation progress. ```APIDOC ## opendssdirect.Progress ```autodoc2-object``` opendssdirect.Progress.IProgress ``` -------------------------------- ### Get Load kW using Low-Level API Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/Example-OpenDSSDirect.py.ipynb Reads the kW property of the active load element using the low-level `Loads_Get_kW` function. This function is part of the direct DSS C-API wrapper. ```python dss.dss_lib.Loads_Get_kW() ``` -------------------------------- ### ReduceCkt Module Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/opendssdirect.md Documentation for the `ReduceCkt` module, likely for circuit reduction functionalities. ```APIDOC ## opendssdirect.ReduceCkt ```autodoc2-object``` opendssdirect.ReduceCkt.IReduceCkt ``` -------------------------------- ### CtrlQueue Module Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/opendssdirect.md Documentation for the `CtrlQueue` module, managing the control queue. ```APIDOC ## opendssdirect.CtrlQueue ```autodoc2-object``` opendssdirect.CtrlQueue.ICtrlQueue ``` -------------------------------- ### Retrieve Storage Class Properties Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/notebooks/ActiveClass.ipynb Use the `dss.utils.class_to_dataframe` method to get a DataFrame of all Storage elements and their properties. Transpose the DataFrame for a more readable format, showing properties as rows and storage units as columns. ```python dss.utils.class_to_dataframe('Storage').transpose() ``` -------------------------------- ### Access and Control Transformers Source: https://context7.com/dss-extensions/opendssdirect.py/llms.txt Shows how to list, iterate through, and access properties of transformers in the circuit. This includes winding details, tap settings, and losses. Ensure the circuit is loaded before using these functions. ```python from opendssdirect import dss dss('Redirect "IEEE13Nodeckt.dss"') dss.Solution.Solve() # List all transformers print(f"Transformer count: {dss.Transformers.Count()}") print(f"Transformer names: {dss.Transformers.AllNames()}") # Iterate through transformers for xfmr in dss.Transformers: print(f"\nTransformer: {xfmr.Name()}") print(f" Windings: {xfmr.NumWindings()}") print(f" XfmrCode: {xfmr.XfmrCode()}") # Access each winding for wdg in range(1, xfmr.NumWindings() + 1): xfmr.Wdg(wdg) print(f" Winding {wdg}: kV={xfmr.kV()}, kVA={xfmr.kVA()}, " f"Tap={xfmr.Tap()}, IsDelta={xfmr.IsDelta()}") # Access specific transformer dss.Transformers.Name("sub") print(f"\nSubstation transformer details:") print(f" Xhl: {dss.Transformers.Xhl()}%)") print(f" Min tap: {dss.Transformers.MinTap()}") print(f" Max tap: {dss.Transformers.MaxTap()}") print(f" Num taps: {dss.Transformers.NumTaps()}") # Set tap position dss.Transformers.Wdg(2) # Select winding 2 dss.Transformers.Tap(1.05) # Set tap to 1.05 per-unit # Get winding currents and voltages wdg_currents = dss.Transformers.WdgCurrents() wdg_voltages = dss.Transformers.WdgVoltages() # Get losses by type losses = dss.Transformers.LossesByType() # [total, load, no-load] print(f"Losses (VA): Total={losses[0]}, Load={losses[2]}, No-load={losses[4]}") # Modify transformer properties dss.Transformers.R(0.5) # Winding resistance % dss.Transformers.Xhl(8.0) # Reactance between windings 1-2 % ``` -------------------------------- ### Basic Module Source: https://github.com/dss-extensions/opendssdirect.py/blob/master/docs/opendssdirect.md Documentation for the `Basic` module, potentially containing fundamental OpenDSS functionalities. ```APIDOC ## opendssdirect.Basic ```autodoc2-object``` opendssdirect.Basic.IBasic ```