Krang reference

The Krang is the main class of krangpower. It has facilities to drive the OpenDSS engine, retrieve and query elements and options, saving and loading circuit data as JSON, representing the circuit as graph, perform repeated solutions and reporting the results as DataFrames. The basic workflow pertaining the Krang is illustrated in the Usage page.

It’s worth spending a word about the attribute Krang.brain. It points to the krang.enhancer submodule and is designed to expose the exact same interface as the module OpenDSSDirect.py. This means that you can use Krang.brain exactly as you would use this module, with two advantages:

  • Results are returned in enhanced data containers as suitable, rather than as raw strings (integers will be of type int, arrays will be of type numpy.ndarray, pyhysical quantities will have a pint unit measure);
  • It’s bracket-indicizable with a string and returns a PackedOpendssElement.

More info on krang.enhancer is available at the krang.enhancer reference page.

Important

Krang is a singleton, meaning that you cannot have more than one instance around at any given time - an Exception will be raised when trying to instantiate more than one. This is because OpenDSS supports only one circuit at any given time. If, in the future, the capability to have more than one circuit will be built in Opendss, this limitation will be removed.

Note

Krang can be deleted with the del keyword. After doing it, it will be possible (in principle) to instantiate a new one; beware, though, that if you made strong references to it (for example, assigning it to variables, to lists, to object attributes) the new instantiation will fail even after the del command. In other words, a new instantiation will be possible after you del the last strong reference that was made to the Krang.

Class reference

class krangpower.Krang(name='Unnamed_Krang', voltage_source=<krangpower.Vsource()(@0x7f08dbb56750)>, source_bus_name='sourcebus', working_frequency=50.0, redirect_path=False, override_log=False)

The krang is an object capable of creating, editing, solving and retrieving information about an electrical distribution system.

Ybus_noload()

Returns the Ybus matrix of the existing circuit with all loads, generators set to 0 kW and 0 kVAr. The Ybus computed in such a way can be used to compute the load/generator injection currents as Ybus_noload * V, where V is the node voltage vector computed in any other condition of load. The matrix is returned in Compressed Sparse Column representation.

__getattr__(item)

Krang.item, aside from retrieving the builtin attributes, wraps by default the calls to opendssdirect’s ‘class_to_dataframe’ utility function. These are accessible via capital letter calls. Both singular and plural are accepted. (e.g., ‘Line’ or ‘Lines’, ‘RegControl’ , ‘Regcontrol’, ‘RegControls’, but not ‘transformers’)

__getitem__(item)

Krang[‘bus.nname’], Krang[‘load.load1’], Krang[‘load1’] gets the component or a list of components of the bus; Krang[(‘bus.nname’,)], Krang[‘bus.b1’,’bus.b2’] gets a BusView to which you can add components with <<. Note that in order to get a BusView of a single bus, one needs to explicitly pack it in a tuple.

__init__(name='Unnamed_Krang', voltage_source=<krangpower.Vsource()(@0x7f08dbb56750)>, source_bus_name='sourcebus', working_frequency=50.0, redirect_path=False, override_log=False)

Initialize self. See help(type(self)) for accurate signature.

__lshift__(other)

The left-shift operator << adds components to the Krang. Components that can and have to be directly added to the krang are those that represent data (WireData, TSData, LineGeometry…) or those that are in the circuit but above the topology (such as Monitors and all the Controllers). The names of these elements must not be blank when they are added.

static __new__(cls, *args, **kwargs)

Create and return a new object. See help(type) for accurate signature.

brain = None

Krang.brain points to krangpower.enhancer It has the same interface as OpenDSSDirect.py, but can pack objects and returns enhanced data structures such as pint qtys and numpy arrays.

bus_coords()

Returns a dict with the bus coordinates already loaded in Opendss. Beware that coordinates loaded through a link_kml or link_csv are not immediately loaded in the Opendss, but they are just before a solution is launched.

com

Krang.com is a list of all the commands sent to the text interface throughout the Krang’s lifespan.

command(cmd_str: str, echo=True)

Performs an opendss textual command and adds the commands to the record Krang.com if echo is True.

custom_drag_solve(*qties, as_dict=False)

This command solves one step at a time and returns a list of values (of length equal to the number of steps solved) for each of the quantities indicated, as strings, in the arguments. For example:

pwr, lss = myKrang.custom_drag_solve(‘myKrang[“agent_1”].Powers()’, ‘myKrang.brain.Circuit.Losses()’)

(returns two lists with the values assumed by the expressions passed after each solution steps).

DEPRECATED IN FAVOR OF Krang.evalsolve

drag_solve()

This command solves one step at a time and saves node currents and voltages in the two DataFrames returned.

evalsolve(*fns, every_steps=1, always_rebuild_Y=False, as_df=True, detect_multindex=True)

Solves the circuit for the set number of steps, evaluating the function passed at each step and returning the results. Accepts as arguments a series of functions that take a Krang object as input. Returns a dictionary or a DF; each item/column contains the returned values of the corresponding function passed, indicized by simulation time.

Parameters:
  • fns – the functions to evaluate, passed as sequence of *args. The functions have to accept one positional argument of type Krang, as they will be passed this instance.
  • every_steps – Every how many steps to perform the evaluation. Default = 1.
  • always_rebuild_Y – Whether to impart the ‘BuildY’ command before solving.
  • as_df – Whether to return the results in a dict or in a pandas.DataFrame
  • detect_multindex – (NOT YET IMPLEMENTED) if set to True, and so is as_df, evalsolve checks if all the individual results returned by the functions are dicts with the same keys. If so, those keys are used as a multi-index for the DataFrame.
export(object_descriptor)

Wraps the OpenDSS export command. Returns a DataFrame for csv exports, an ElementTree for xml exports. This method has a help attribute that prints to console the available options.

fingerprint()

Returns the md5 hash digest for Krang.make_json_dict() in canonical form. Its main use is to compare two circuits in order to confirm that they are equivalent.

classmethod from_dss(file_path, target_krang=None, frequency=50.0)

from_dss(file_path, target_krang, frequency) allows to create a krang from an existing dss script or to pass commands to a krang from an existing dss script. USE AT YOUR OWN RISK.

Parameters:
  • file_path – The path of the dss file to utilize
  • target_krang
    • If None, a new krang will be created and initialized with the information from the file (must contain a ‘new circuit’ command).
    • If a Krang is passed, the commands in the script will be passed to that Krang.
  • frequency – the general frequency to use for the krang, if a new one is created.
classmethod from_json(path, override_log=False)

Loads circuit data from a json structured like the ones returned by Krang.save_json. Declaration precedence due to dependency between objects is automatically taken care of.

get(*opts)

Takes a list of circuit options and returns them as dict of name, value.

static get_unit_registry()

Retrieves krangpower’s UnitRegistry.

graph()

Krang.graph is a Networkx.Graph that contains a description of the circuit. The elements are stored as _PackedOpendssElement’s in the edge/node property ‘el’. More information about how to make use of the graph can be found in the dedicated page.

id = None

Krang.id is a string identifier for the krang that is used in the logs.

Notifies Krang of a csv file with bus coordinates to use.

make_json_dict()

Returns a complete description of the circuit and its objects as a json.dumpable-dict.

name

The name of the circuit..

classmethod open_ckt(path, strict=True)

Loads a ckt package saved through Krang.pack_ckt() and returns a Krang.

pack_ckt(path=None)

Packs a ckt archive with all the information needed to reproduce the Krang. If a valid path string is passed, a file will be created, and None will be returned; if None is passed as path, a Binary buffered I/O (io.BytesIO) with the exact same information as the file will be returned instead.

plot(object_descriptor)

Wraps the OpenDSS plot command. This method has a help attribute that prints to console the available options.

save_dss(path=None)

Saves a file with the text commands that were imparted by the Krang.command method aside from those for which echo was False. The file output should be loadable and runnable in traditional OpenDSS with no modifications.

save_json(path=None, indent=2)

Saves a complete JSON description of the circuit and its objects. If a valid path string is passed, a file will be created, and None will be returned; if None is passed as path, a Text buffered Stream (io.StringIO) with the exact same information as the file will be returned instead.

set(**opts_vals)

Sets circuit options according to a dict. Option that have a physical dimensionality (such as stepsize) can be specified as pint quantities; otherwise, the default opendss units will be used.

show(object_descriptor)

Wraps the OpenDSS show command. This method has a help attribute that prints to console the available options.

snap()

Solves a circuit snapshot.

solve(echo=True)

Imparts the solve command to OpenDSS.