code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
ret = False
out = ''
system = self.system
dae = self.system.dae
varname = self.system.varname
template = '{:>6g}, {:>25s}, {:>35s}\n'
# header line
out += template.format(0, 'Time [s]', '$Time\\ [s]$')
# include line flow variables in a... | def write_lst(self) | Dump the variable name lst file
:return: succeed flag | 5.008849 | 4.945106 | 1.01289 |
logger.warn('This function is deprecated. You can inspect `self.np_vars` directly as NumPy arrays '
'without conversion.')
if not self.vars:
return None
vars_matrix = matrix(self.vars, size=(self.vars[0].size[0],
... | def vars_to_array(self) | Convert `self.vars` to a numpy array
Returns
-------
numpy.array | 8.003667 | 7.564005 | 1.058126 |
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# file handler for level DEBUG and up
if log_file is not None:
log_full_path = os.path.join(log_path, log_file)
fh_formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
... | def config_logger(name='andes',
log_file='andes.log',
log_path='',
stream=True,
stream_level=logging.INFO
) | Configure a logger for the andes package with options for a `FileHandler`
and a `StreamHandler`. This function is called at the beginning of
``andes.main.main()``.
Parameters
----------
name : str, optional
Base logger name, ``'andes'`` by default. Changing this
parameter will affec... | 1.832204 | 1.986612 | 0.922276 |
from . import __version__ as version
logger.info('ANDES {ver} (Build {b}, Python {p} on {os})'
.format(ver=version[:5], b=version[-8:],
p=platform.python_version(),
os=platform.system()))
try:
username = os.getlogin() + ', '
ex... | def preamble() | Log the Andes command-line preamble at the `logging.INFO` level
Returns
-------
None | 4.871424 | 4.89014 | 0.996173 |
ret = False
# no `edit-config` supplied
if edit_config == '':
return ret
conf_path = misc.get_config_load_path(load_config)
if conf_path is not None:
logger.info('Editing config file {}'.format(conf_path))
if edit_config is None:
# use the following defau... | def edit_conf(edit_config=False, load_config=None, **kwargs) | Edit the Andes config file which occurs first in the search path.
Parameters
----------
edit_config : bool
If ``True``, try to open up an editor and edit the config file.
Otherwise returns.
load_config : None or str, optional
Path to the config file, which will be placed to the... | 3.45083 | 3.455404 | 0.998676 |
if not clean:
return False
found = False
cwd = os.getcwd()
for file in os.listdir(cwd):
if file.endswith('_eig.txt') or \
file.endswith('_out.txt') or \
file.endswith('_out.lst') or \
file.endswith('_out.dat') or \
fi... | def remove_output(clean=False, **kwargs) | Remove the outputs generated by Andes, including power flow reports
``_out.txt``, time-domain list ``_out.lst`` and data ``_out.dat``,
eigenvalue analysis report ``_eig.txt``.
Parameters
----------
clean : bool
If ``True``, execute the function body. Returns otherwise.
kwargs : dict
... | 3.326411 | 2.930132 | 1.135243 |
from .models import all_models
out = []
if not search:
return out
keys = sorted(list(all_models.keys()))
for key in keys:
vals = all_models[key]
val = list(vals.keys())
val = sorted(val)
for item in val:
if search.lower() in item.lower():... | def search(search, **kwargs) | Search for models whose names matches the given pattern. Print the
results to stdout.
.. deprecated :: 1.0.0
`search` will be moved to ``andeshelp`` in future versions.
Parameters
----------
search : str
Partial or full name of the model to search for
kwargs : dict
Oth... | 3.834291 | 3.772348 | 1.01642 |
ret = False
cf_path = save_config
# no ``--save-config ``
if cf_path == '':
return ret
if cf_path is None:
cf_path = 'andes.conf'
home = str(pathlib.Path.home())
path = os.path.join(home, '.andes')
if not os.path.exists(path):
os.makedirs(p... | def save_config(save_config='', **kwargs) | Save the Andes config to a file at the path specified by ``save_config``.
The save action will not run if `save_config = ''`.
Parameters
----------
save_config : None or str, optional, ('' by default)
Path to the file to save the config file. If the path is an emtpy
string, the save act... | 3.950146 | 4.206744 | 0.939003 |
t0, s = elapsed()
# parser command line arguments
args = vars(cli_new())
# configure stream handler verbose level
config_logger(log_path=misc.get_log_dir(), stream_level=args['verbose'])
# show preamble
preamble()
logger.debug('command line arguments:')
logger.debug(pprint.p... | def main() | The main function of the Andes command-line tool.
This function executes the following workflow:
* Parse the command line inputs
* Show the tool preamble
* Output the requested helps, edit/save configs or remove outputs. Exit
the main program if any of the above is executed
* Process th... | 3.57999 | 3.455421 | 1.03605 |
t0, _ = elapsed()
# enable profiler if requested
pr = cProfile.Profile()
if profile is True:
pr.enable()
system = PowerSystem(case, **kwargs)
if not filters.guess(system):
return
if not filters.parse(system):
return
# dump system as raw file if requested... | def run(case, routine=None, profile=False, dump_raw=False, pid=-1, show_data=None, exit=False,
**kwargs) | Entry function to run a single case study. This function executes the
following workflow:
* Turn on cProfile if requested
* Populate a ``PowerSystem`` object
* Parse the input files using filters
* Dump the case file is requested
* Set up the system
* Run the specified routine(s)
... | 4.143453 | 3.896521 | 1.063372 |
self.devices = self.system.devman.devices
self.ndevice = len(self.devices)
self.gcalls = [''] * self.ndevice
self.fcalls = [''] * self.ndevice
self.gycalls = [''] * self.ndevice
self.fxcalls = [''] * self.ndevice
self.jac0s = [''] * self.ndevice
... | def setup(self) | setup the call list after case file is parsed and jit models are loaded | 5.318365 | 4.964922 | 1.071188 |
for item in all_calls:
self.__dict__[item] = []
for dev in self.devices:
for item in all_calls:
if self.system.__dict__[dev].n == 0:
val = False
else:
val = self.system.__dict__[dev].calls.get(item,... | def build_vec(self) | build call validity vector for each device | 4.392051 | 3.556805 | 1.23483 |
for idx, dev in enumerate(self.devices):
header = 'system.' + dev
self.gcalls[idx] = header + '.gcall(system.dae)\n'
self.fcalls[idx] = header + '.fcall(system.dae)\n'
self.gycalls[idx] = header + '.gycall(system.dae)\n'
self.fxcalls[idx] = he... | def build_strings(self) | build call string for each device | 3.596922 | 3.190429 | 1.12741 |
string = ''
if SHOW_PF_CALL:
logger.debug(string)
self.newton = compile(eval(string), '', 'exec') | def _compile_newton(self) | Newton power flow execution
1. evaluate g and f;
1.1. handle islanded buses by Bus.gisland()
2. factorize when needed;
3. evaluate Gy and Fx.
3.1. take care of islanded buses by Bus.gyisland() | 18.078741 | 18.682304 | 0.967693 |
string = ''
self.fdpf = compile(eval(string), '', 'exec') | def _compile_fdpf(self) | Fast Decoupled Power Flow execution: Implement g(y) | 19.058094 | 20.786652 | 0.916843 |
string = ''
self.pfload = compile(eval(string), '', 'exec') | def _compile_pfload(self) | Post power flow computation for load
S_gen + S_line + [S_shunt - S_load] = 0 | 16.395037 | 20.816898 | 0.787583 |
string = ''
self.pfgen = compile(eval(string), '', 'exec') | def _compile_pfgen(self) | Post power flow computation for PV and SW | 15.406267 | 16.846672 | 0.914499 |
string = ''
self.bus_injection = compile(eval(string), '', 'exec') | def _compile_bus_injection(self) | Impose injections on buses | 15.730833 | 13.097031 | 1.201099 |
string = ''
self.seriesflow = compile(eval(string), '', 'exec') | def _compile_seriesflow(self) | Post power flow computation of series device flow | 19.615673 | 18.010725 | 1.089111 |
string = ''
self.int_fg = compile(eval(fg_string), '', 'exec')
# rebuild constant Jacobian elements if needed
string += 'if system.dae.factorize:\n'
string += ' system.dae.init_jac0()\n'
for jac0, call in zip(self.jac0, self.jac0s):
if jac0:
... | def _compile_int(self) | Time Domain Simulation routine execution | 5.686812 | 5.524142 | 1.029447 |
string = ''
self.int_f = compile(eval(string), '', 'exec') | def _compile_int_f(self) | Time Domain Simulation - update differential equations | 14.941133 | 12.134664 | 1.231277 |
string = ''
self.int_g = compile(eval(string), '', 'exec') | def _compile_int_g(self) | Time Domain Simulation - update algebraic equations and Jacobian | 14.987232 | 12.800092 | 1.170869 |
assert self._name
assert self._group
# self.n = 0
self.u = []
self.name = []
self.idx = []
self.uid = {}
if not self._unamey:
self._unamey = self._algebs
else:
assert len(self._unamey) == len(self._algebs)
... | def _init(self) | Convert model metadata to class attributes.
This function is called automatically after ``define()`` in new
versions.
:return: None | 3.608772 | 3.591596 | 1.004782 |
assert param not in self._data
assert param not in self._algebs
assert param not in self._states
assert param not in self._service
self._data.update({param: default})
if unit:
self._units.update({param: unit})
if descr:
self._desc... | def param_define(self,
param,
default,
unit='',
descr='',
tomatrix=True,
nonzero=False,
mandatory=False,
power=False,
voltage=False... | Define a parameter in the model
:param tomatrix: convert this parameter list to matrix
:param param: parameter name
:param default: parameter default value
:param unit: parameter unit
:param descr: description
:param nonzero: is non-zero
:param mandatory: is mand... | 1.462801 | 1.500111 | 0.975128 |
assert ty in ('x', 'y')
if not uname:
uname = variable
if ty == 'x':
self._states.append(variable)
self._fnamex.append(fname)
self._unamex.append(uname)
if descr:
self._states_descr.update({variable: descr})
... | def var_define(self, variable, ty, fname, descr='', uname='') | Define a variable in the model
:param fname: LaTex formatted variable name string
:param uname: unformatted variable name string, `variable` as default
:param variable: variable name
:param ty: type code in ``('x', 'y')``
:param descr: variable description
:type variabl... | 2.509072 | 2.40326 | 1.044029 |
assert service not in self._data
assert service not in self._algebs + self._states
self._service.append(service)
self._service_ty.append(ty) | def service_define(self, service, ty) | Add a service variable of type ``ty`` to this model
:param str service: variable name
:param type ty: variable type
:return: None | 7.743941 | 6.640202 | 1.166221 |
assert idx is not None
if isinstance(idx, (int, float, str)):
return self.uid[idx]
ret = []
for i in idx:
tmp = self.uid.get(i, None)
assert tmp is not None, (
'Model <{}> does not have element <{}>'.format(self._name, i))
... | def get_uid(self, idx) | Return the `uid` of the elements with the given `idx`
:param list, matrix idx: external indices
:type idx: list, matrix
:return: a matrix of uid | 3.607447 | 3.929589 | 0.918021 |
assert astype in (None, list, matrix)
ret = None
if idx is None:
idx = self.idx
# ===================disable warning ==============================
# if field in self._service:
# logger.warning(
# 'Reading service variable <{model}.{fiel... | def get_field(self, field, idx=None, astype=None) | Return `self.field` for the elements labeled by `idx`
:param astype: type cast of the return value
:param field: field name of this model
:param idx: element indices, will be the whole list if not specified
:return: field values | 4.342449 | 4.600849 | 0.943836 |
nzeros = [0] * self.n
for var in self._states:
self.__dict__[var] = nzeros[:]
for var in self._algebs:
self.__dict__[var] = nzeros[:] | def _alloc(self) | Allocate empty memory for dae variable indices.
Called in device setup phase.
:return: None | 5.565771 | 5.514455 | 1.009306 |
assert isinstance(sysbase, bool)
ret = {}
for key in self.data_keys:
if (not sysbase) and (key in self._store):
val = self._store[key]
else:
val = self.__dict__[key]
ret[key] = val
return ret | def data_to_dict(self, sysbase=False) | Return the loaded model parameters as one dictionary.
Each key of the dictionary is a parameter name, and the value is a
list of all the parameter values.
:param sysbase: use system base quantities
:type sysbase: bool | 3.157843 | 3.57657 | 0.882925 |
ret = list()
# for each element
for i in range(self.n):
# read the parameter values and put in the temp dict ``e``
e = {}
for key in self.data_keys:
if sysbase and (key in self._store):
val = self._store[key][i]
... | def data_to_list(self, sysbase=False) | Return the loaded model data as a list of dictionaries.
Each dictionary contains the full parameters of an element.
:param sysbase: use system base quantities
:type sysbase: bool | 4.575123 | 4.231201 | 1.081282 |
nvars = []
for key, val in data.items():
self.__dict__[key].extend(val)
# assure the same parameter matrix size
if len(nvars) > 1 and len(val) != nvars[-1]:
raise IndexError(
'Model <{}> parameter <{}> must have the same ... | def data_from_dict(self, data) | Populate model parameters from a dictionary of parameters
Parameters
----------
data : dict
List of parameter dictionaries
Returns
-------
None | 5.654102 | 5.894325 | 0.959245 |
p_dict_comp = self.data_to_dict(sysbase=sysbase)
self._check_pd()
self.param_df = pd.DataFrame(data=p_dict_comp).set_index('idx')
return self.param_df | def data_to_df(self, sysbase=False) | Return a pandas.DataFrame of device parameters.
:param sysbase: save per unit values in system base | 5.115293 | 5.47539 | 0.934233 |
ret = {}
self._check_pd()
if self._flags['address'] is False:
return pd.DataFrame.from_dict(ret)
ret.update({'name': self.name})
ret.update({'idx': self.idx})
for x in self._states:
idx = self.__dict__[x]
ret.update({x: self... | def var_to_df(self) | Return the current var_to_df of variables
:return: pandas.DataFrame | 3.839734 | 3.98472 | 0.963614 |
for attr in self._param_attr_dicts:
if param in self.__dict__[attr]:
self.__dict__[attr].pop(param)
for attr in self._param_attr_lists:
if param in self.__dict__[attr]:
self.__dict__[attr].remove(param) | def param_remove(self, param: 'str') -> None | Remove a param from this model
:param param: name of the parameter to be removed
:type param: str | 2.754945 | 2.574528 | 1.070078 |
assert param in self._data, \
'parameter <{}> does not exist in {}'.format(param, self._name)
def alter_attr(p, attr, value):
if value is None:
return
elif (value is True) and (p not in self.__dict__[attr]):
self.... | def param_alter(self,
param,
default=None,
unit=None,
descr=None,
tomatrix=None,
nonzero=None,
mandatory=None,
power=None,
voltage=None,
... | Set attribute of an existing parameter.
To be used to alter an attribute inherited from parent models.
See .. self.param_define for argument descriptions. | 1.823248 | 1.917661 | 0.950767 |
# determine the type of the equation, ('f', 'g') based on var
# We assume that all differential equations are only modifiable by
# the model itself
# Only interface to algebraic varbailes of external models
ty = ''
if var in self._algebs:
ty = 'g... | def eq_add(self, expr, var, intf=False) | Add an equation to this model.
An equation is associated with the addresses of a variable. The
number of equations must equal that of variables.
Stored to ``self._equations`` is a tuple of ``(expr, var, intf,
ty)`` where ``ty`` is in ('f', 'g')
:param str expr: equation expre... | 6.980226 | 5.796968 | 1.204117 |
ret = list()
if model in self.system.devman.devices:
ret = self.system.__dict__[model].get_field(field, idx)
elif model in self.system.devman.group.keys():
# ===============================================================
# Since ``self.system.devma... | def read_data_ext(self, model: str, field: str, idx=None, astype=None) | Return a field of a model or group at the given indices
:param str model: name of the group or model to retrieve
:param str field: name of the field
:param list, int, float str idx: idx of elements to access
:param type astype: type cast
:return: | 4.504283 | 4.297299 | 1.048166 |
# use default destination
if not dest:
dest = field
assert dest not in self._states + self._algebs
self.__dict__[dest] = self.read_data_ext(
model, field, idx, astype=astype)
if idx is not None:
if len(idx) == self.n:
... | def copy_data_ext(self, model, field, dest=None, idx=None, astype=None) | Retrieve the field of another model and store it as a field.
:param model: name of the source model being a model name or a group name
:param field: name of the field to retrieve
:param dest: name of the destination field in ``self``
:param idx: idx of elements to access
:param ... | 6.475491 | 7.025508 | 0.921711 |
idx = self.system.devman.register_element(dev_name=self._name, idx=idx)
self.system.__dict__[self._group].register_element(self._name, idx)
self.uid[idx] = self.n
self.idx.append(idx)
self.mdl_to.append(list())
self.mdl_from.append(list())
# self.n +=... | def elem_add(self, idx=None, name=None, **kwargs) | Add an element of this model
:param idx: element idx
:param name: element name
:param kwargs: keyword arguments of the parameters
:return: allocated idx | 3.360205 | 3.394094 | 0.990015 |
if idx is not None:
if idx in self.uid:
key = idx
item = self.uid[idx]
else:
self.log('The item <{:s}> does not exist.'.format(idx), ERROR)
return None
else:
return None
convert = False
... | def elem_remove(self, idx=None) | Remove elements labeled by idx from this model instance.
:param list,matrix idx: indices of elements to be removed
:return: None | 2.89183 | 2.929979 | 0.98698 |
if (not self.n) or self._flags['sysbase']:
return
Sb = self.system.mva
Vb = matrix([])
if 'bus' in self._ac.keys():
Vb = self.read_data_ext('Bus', 'Vn', idx=self.bus)
elif 'bus1' in self._ac.keys():
Vb = self.read_data_ext('Bus', 'Vn',... | def data_to_sys_base(self) | Converts parameters to system base. Stores a copy in ``self._store``.
Sets the flag ``self.flag['sysbase']`` to True.
:return: None | 1.9982 | 1.967694 | 1.015504 |
if self._flags['sysbase'] is False:
return
for key, val in self._store.items():
self.__dict__[key] = val
self._flags['sysbase'] = False | def data_to_elem_base(self) | Convert parameter data to element base
Returns
-------
None | 6.847498 | 6.928811 | 0.988265 |
for key, val in self._ac.items():
self.copy_data_ext(
model='Bus', field='a', dest=val[0], idx=self.__dict__[key])
self.copy_data_ext(
model='Bus', field='v', dest=val[1], idx=self.__dict__[key])
for key, val in self._dc.items():
... | def _intf_network(self) | Retrieve the ac and dc network interface variable indices.
:Example:
``self._ac = {'bus1': (a1, v1)}`` gives
- indices: self.bus1
- system.Bus.a -> self.a1
- system.Bus.v -> self.v1
``self._dc = {'node1': v1}`` gives
- indices: self... | 4.778439 | 3.298709 | 1.448579 |
for key, val in self._ctrl.items():
model, field, dest, astype = val
self.copy_data_ext(
model, field, dest=dest, idx=self.__dict__[key], astype=astype) | def _intf_ctrl(self) | Retrieve variable indices of controlled models.
Control interfaces are specified in ``self._ctrl``.
Each ``key:value`` pair has ``key`` being the variable names
for the reference idx and ``value`` being a tuple of
``(model name, field to read, destination field, return type)``.
... | 11.76887 | 5.535217 | 2.126181 |
group_by = self._config['address_group_by']
assert not self._flags['address'], "{} address already assigned".format(self._name)
assert group_by in ('element', 'variable')
m0 = self.system.dae.m
n0 = self.system.dae.n
mend = m0 + len(self._algebs) * self.n
... | def _addr(self) | Assign dae addresses for algebraic and state variables.
Addresses are stored in ``self.__dict__[var]``.
``dae.m`` and ``dae.n`` are updated accordingly.
Returns
-------
None | 2.209228 | 2.024799 | 1.091085 |
if not self._flags['address']:
self.log('Unable to assign Varname before allocating address',
ERROR)
return
varname = self.system.varname
for i in range(self.n):
iname = str(self.name[i])
for e, var in enumerate(self... | def _varname(self) | Set up variable names in ``self.system.varname``.
Variable names follows the convention ``VariableName,Model Name``.
A maximum of 24 characters are allowed for each variable.
:return: None | 3.840022 | 3.52185 | 1.090342 |
for item in self._params:
self.__dict__[item] = matrix(self.__dict__[item], tc='d') | def _param_to_matrix(self) | Convert parameters defined in `self._params` to `cvxopt.matrix`
:return None | 5.361472 | 4.261115 | 1.258232 |
for item in self._params:
self.__dict__[item] = list(self.__dict__[item]) | def _param_to_list(self) | Convert parameters defined in `self._param` to list
:return None | 4.550193 | 4.883672 | 0.931715 |
logger.log(level, '<{}> - '.format(self._name) + msg) | def log(self, msg, level=INFO) | Record a line of log in logger
:param str msg: content of the messag
:param level: logging level
:return: None | 7.484169 | 13.224224 | 0.565944 |
above = agtb(self.__dict__[key], upper)
for idx, item in enumerate(above):
if item == 0.:
continue
maxval = upper[idx]
self.log(
'{0} <{1}.{2}> above its maximum of {3}.'.format(
self.name[idx], self._name, ... | def init_limit(self, key, lower=None, upper=None, limit=False) | check if data is within limits. reset if violates | 2.864867 | 2.75208 | 1.040982 |
title = '<{}.{}>'.format(self._group, self._name)
table = Tab(export=export, title=title, descr=self.__doc__)
rows = []
keys = sorted(self._data.keys())
for key in keys:
val = self._data[key]
suf = ''
if key in self._mandatory:
... | def doc(self, export='plain') | Build help document into a Texttable table
:param ('plain', 'latex') export: export format
:param save: save to file ``help_model.extension`` or not
:param writemode: file write mode
:return: None | 3.790157 | 3.783599 | 1.001733 |
retval = True
assert varname in self.__dict__
if varname in self._algebs:
val = self.system.dae.y[self.__dict__[varname]]
elif varname in self._states:
val = self.system.dae.x[self.__dict__[varname]]
else: # service or temporary variable
... | def check_limit(self, varname, vmin=None, vmax=None) | Check if the variable values are within the limits.
Return False if fails. | 3.275416 | 3.244258 | 1.009604 |
assert hasattr(self, 'bus')
ret = []
if isinstance(bus_idx, (int, float, str)):
bus_idx = [bus_idx]
for item in bus_idx:
idx = []
for e, b in enumerate(self.bus):
if b == item:
idx.append(self.idx[e])
... | def on_bus(self, bus_idx) | Return the indices of elements on the given buses for shunt-connected
elements
:param bus_idx: idx of the buses to which the elements are connected
:return: idx of elements connected to bus_idx | 2.335138 | 2.392873 | 0.975872 |
ret = []
if not self._config['is_series']:
self.log(
'link_bus function is not valid for non-series model <{}>'.
format(self.name))
return []
if isinstance(bus_idx, (int, float, str)):
bus_idx = [bus_idx]
fke... | def link_bus(self, bus_idx) | Return the indices of elements linking the given buses
:param bus_idx:
:return: | 3.734491 | 3.65701 | 1.021187 |
if isinstance(value, (int, float, str)):
value = [value]
f = list(self.__dict__[field])
uid = np.vectorize(f.index)(value)
return self.get_idx(uid) | def elem_find(self, field, value) | Return the indices of elements whose field first satisfies the given values
``value`` should be unique in self.field.
This function does not check the uniqueness.
:param field: name of the supplied field
:param value: value of field of the elemtn to find
:return: idx of the ele... | 6.034688 | 5.227403 | 1.154433 |
if hasattr(self, 'bus') and hasattr(self, 'Vn'):
bus_Vn = self.read_data_ext('Bus', field='Vn', idx=self.bus)
for name, bus, Vn, Vn0 in zip(self.name, self.bus, self.Vn,
bus_Vn):
if Vn != Vn0:
self.log... | def _check_Vn(self) | Check data consistency of Vn and Vdcn if connected to Bus or Node
:return None | 2.339253 | 2.134202 | 1.096078 |
if model in self.system.loaded_groups:
# access group instance
grp = self.system.__dict__[model]
# doing it one by one
for i, self_i in zip(idx, self_idx):
# query model name and access model instance
mdl_name = grp._idx_... | def link_to(self, model, idx, self_idx) | Register (self.name, self.idx) in `model._from`
Returns
------- | 3.33368 | 3.319632 | 1.004232 |
self.solved = False
self.niter = 0
self.iter_mis = []
self.F = None
self.system.dae.factorize = True | def reset(self) | Reset all internal storage to initial status
Returns
-------
None | 16.463932 | 14.144989 | 1.163941 |
logger.info('-> Power flow study: {} method, {} start'.format(
self.config.method.upper(), 'flat' if self.config.flatstart else 'non-flat')
)
t, s = elapsed()
system = self.system
dae = self.system.dae
system.dae.init_xy()
for device, pflo... | def pre(self) | Initialize system for power flow study
Returns
-------
None | 9.063228 | 8.093596 | 1.119802 |
ret = None
# initialization Y matrix and inital guess
self.pre()
t, _ = elapsed()
# call solution methods
if self.config.method == 'NR':
ret = self.newton()
elif self.config.method == 'DCPF':
ret = self.dcpf()
elif self.c... | def run(self, **kwargs) | call the power flow solution routine
Returns
-------
bool
True for success, False for fail | 6.284662 | 6.129351 | 1.025339 |
dae = self.system.dae
while True:
inc = self.calc_inc()
dae.x += inc[:dae.n]
dae.y += inc[dae.n:dae.n + dae.m]
self.niter += 1
max_mis = max(abs(inc))
self.iter_mis.append(max_mis)
self._iter_info(self.niter... | def newton(self) | Newton power flow routine
Returns
-------
(bool, int)
success flag, number of iterations | 3.853507 | 4.058975 | 0.949379 |
dae = self.system.dae
self.system.Bus.init0(dae)
self.system.dae.init_g()
Va0 = self.system.Bus.angle
for model, pflow, gcall in zip(self.system.devman.devices, self.system.call.pflow, self.system.call.gcall):
if pflow and gcall:
self.system... | def dcpf(self) | Calculate linearized power flow
Returns
-------
(bool, int)
success flag, number of iterations | 5.483073 | 5.366775 | 1.02167 |
max_mis = self.iter_mis[niter - 1]
msg = ' Iter {:<d}. max mismatch = {:8.7f}'.format(niter, max_mis)
logger.info(msg) | def _iter_info(self, niter, level=logging.INFO) | Log iteration number and mismatch
Parameters
----------
level
logging level
Returns
-------
None | 7.970232 | 8.083858 | 0.985944 |
system = self.system
self.newton_call()
A = sparse([[system.dae.Fx, system.dae.Gx],
[system.dae.Fy, system.dae.Gy]])
inc = matrix([system.dae.f, system.dae.g])
if system.dae.factorize:
self.F = self.solver.symbolic(A)
system... | def calc_inc(self) | Calculate the Newton incrementals for each step
Returns
-------
matrix
The solution to ``x = -A\\b`` | 5.927105 | 6.383195 | 0.928548 |
# system = self.system
# exec(system.call.newton)
system = self.system
dae = self.system.dae
system.dae.init_fg()
system.dae.reset_small_g()
# evaluate algebraic equation mismatches
for model, pflow, gcall in zip(system.devman.devices,
... | def newton_call(self) | Function calls for Newton power flow
Returns
-------
None | 3.566112 | 3.514854 | 1.014583 |
if not self.solved:
return
system = self.system
exec(system.call.pfload)
system.Bus.Pl = system.dae.g[system.Bus.a]
system.Bus.Ql = system.dae.g[system.Bus.v]
exec(system.call.pfgen)
system.Bus.Pg = system.dae.g[system.Bus.a]
system... | def post(self) | Post processing for solved systems.
Store load, generation data on buses.
Store reactive power generation on PVs and slack generators.
Calculate series flows and area flows.
Returns
-------
None | 4.030751 | 3.351593 | 1.202637 |
system = self.system
# general settings
self.niter = 1
iter_max = self.config.maxit
self.solved = True
tol = self.config.tol
error = tol + 1
self.iter_mis = []
if (not system.Line.Bp) or (not system.Line.Bpp):
system.Line.bui... | def fdpf(self) | Fast Decoupled Power Flow
Returns
-------
bool, int
Success flag, number of iterations | 3.306238 | 3.279683 | 1.008097 |
dae.y[self.v] = self.v0
dae.y[self.q] = mul(self.u, self.qg) | def init0(self, dae) | Set initial voltage and reactive power for PQ.
Overwrites Bus.voltage values | 6.499634 | 6.106317 | 1.064411 |
self.u[self.uid[idx]] = 0
self.system.dae.factorize = True | def disable_gen(self, idx) | Disable a PV element for TDS
Parameters
----------
idx
Returns
------- | 19.230236 | 25.291811 | 0.760334 |
self.p0 = matrix(self.p, (self.n, 1), 'd')
self.q0 = matrix(self.q, (self.n, 1), 'd') | def init0(self, dae) | Set initial p and q for power flow | 2.836405 | 2.21464 | 1.280752 |
self.v0 = matrix(dae.y[self.v]) | def init1(self, dae) | Set initial voltage for time domain simulation | 18.228127 | 16.832573 | 1.082908 |
with self._lock:
if self.message_box:
self.message_box.erase()
self.message_box.move(0, 0)
for n, field in enumerate(header):
if n == 0:
self.message_box.addstr(field + ":", curses.color_pair(1))
... | def update_status(self, header, message) | Process incoming status message. Acquire lock for status dictionary before updating. | 2.205579 | 2.120098 | 1.040319 |
with self._lock:
stdscr.clear()
stdscr.addstr(
0, 0, "workflows service monitor -- quit with Ctrl+C", curses.A_BOLD
)
stdscr.refresh()
self.message_box = self._boxwin(
5, curses.COLS, 2, 0, title="last seen mess... | def _redraw_screen(self, stdscr) | Redraw screen. This could be to initialize, or to redraw after resizing. | 7.304554 | 6.978061 | 1.046788 |
with self._lock:
if number < (len(self.cards) - 1):
self._erase_card(number + 1)
if number > (len(self.cards) - 1):
return
max_cards_horiz = int(curses.COLS / 35)
obliterate = curses.newwin(
6,
... | def _erase_card(self, number) | Destroy cards with this or higher number. | 3.750468 | 3.591095 | 1.04438 |
with self._lock:
curses.use_default_colors()
curses.curs_set(False)
curses.init_pair(1, curses.COLOR_RED, -1)
curses.init_pair(2, curses.COLOR_BLACK, -1)
curses.init_pair(3, curses.COLOR_GREEN, -1)
self._redraw_screen(stdscr)
... | def _run(self, stdscr) | Start the actual service monitor | 2.228559 | 2.18119 | 1.021717 |
old = None
new = None
if control == 'Q':
if self.PQ[idx] == 1:
old = 'PQ'
new = 'PV'
elif self.vQ[idx] == 1:
old = 'vQ'
new = 'vV'
elif control == 'P':
if self.PQ[idx] == 1:
... | def switch(self, idx, control) | Switch a single control of <idx> | 1.643497 | 1.627277 | 1.009968 |
if idx not in self.uid.keys():
self.log('Element index {0} does not exist.'.format(idx))
return
self.u[self.uid[idx]] = 0 | def disable(self, idx) | Disable an element and reset the outputs | 5.113089 | 4.437157 | 1.152334 |
assert hasattr(self, option)
alt = option + '_alt'
if not hasattr(self, alt):
return ''
return ', '.join(self.__dict__[alt]) | def get_alt(self, option) | Return the alternative values of an option
Parameters
----------
option: str
option name
Returns
-------
str
a string of alternative options | 5.344948 | 6.507276 | 0.82138 |
rows = []
title = '<{:s}> config options'.format(self.__class__.__name__)
table = Tab(export=export, title=title)
for opt in sorted(self.config_descr):
if hasattr(self, opt):
c1 = opt
c2 = self.config_descr[opt]
c3 = s... | def doc(self, export='plain') | Dump help document for setting classes | 4.003893 | 3.988478 | 1.003865 |
if conf is None:
conf = configparser.ConfigParser()
tab = self.__class__.__name__
conf[tab] = {}
for key, val in self.__dict__.items():
if key.endswith('_alt'):
continue
conf[tab][key] = str(val)
return conf | def dump_conf(self, conf=None) | Dump settings to an rc config file
Parameters
----------
conf
configparser.ConfigParser() object
Returns
-------
None | 3.395007 | 3.408285 | 0.996104 |
section = self.__class__.__name__
if section not in conf.sections():
logger.debug('Config section {} not in rc file'.format(
self.__class__.__name__))
return
for key in conf[section].keys():
if not hasattr(self, key):
... | def load_config(self, conf) | Load configurations from an rc file
Parameters
----------
rc: str
path to the rc file
Returns
-------
None | 2.85135 | 2.891243 | 0.986202 |
timestamp = time.time()
self.status_history[-1]["end"] = timestamp
self.status_history.append(
{"start": timestamp, "end": None, "status": new_status}
) | def update_status(self, new_status) | Record a status change with a current timestamp. | 3.247349 | 2.760988 | 1.176155 |
timestamp = time.time()
cutoff = timestamp - self.period
truncate = 0
summary = {}
for event in self.status_history[:-1]:
if event["end"] < cutoff:
truncate = truncate + 1
continue
summary[event["status"]] = (
... | def report(self) | Return a dictionary of different status codes and the percentage of time
spent in each throughout the last summation_period seconds.
Truncate the aggregated history appropriately. | 2.548141 | 2.358061 | 1.080609 |
host = ".".join(reversed(socket.gethostname().split(".")))
pid = os.getpid()
return "%s.%d" % (host, pid) | def generate_unique_host_id() | Generate a unique ID, that is somewhat guaranteed to be unique among all
instances running at the same time. | 3.720363 | 3.411309 | 1.090597 |
if not self.n or self._flags['sysbase'] is True:
return
self.copy_data_ext(model='Synchronous', field='Sn', dest='Sn', idx=self.gen)
super(GovernorBase, self).data_to_sys_base()
self._store['R'] = self.R
self.R = self.system.mva * div(self.R, self.Sn) | def data_to_sys_base(self) | Custom system base conversion function | 12.617591 | 12.315443 | 1.024534 |
if not self.n or self._flags['sysbase'] is False:
return
self.R = mul(self.R, self.Sn) / self.system.mva
super(GovernorBase, self).data_to_elem_base() | def data_to_elem_base(self) | Custom system base unconversion function | 14.999894 | 12.107723 | 1.23887 |
name, ext = os.path.splitext(fullname)
return name + '_' + suffix + ext | def add_suffix(fullname, suffix) | Add suffix to a full file name | 2.924664 | 2.835128 | 1.031581 |
# if is an empty path
if not fullname:
return fullname
isabs = os.path.isabs(fullname)
path, name = os.path.split(fullname)
if not name: # path to a folder
return None
else: # path to a file
if isabs:
retur... | def get_fullpath(self, fullname=None, relative_to=None) | Return the original full path if full path is specified, otherwise
search in the case file path | 3.991763 | 3.486154 | 1.145033 |
t = self.system.dae.t
for idx in range(0, self.n):
if t >= self.tl[idx]:
if self.en[idx] == 0:
self.en[idx] = 1
logger.info(
'Extended ACE <{}> activated at t = {}.'.format(
s... | def switch(self) | Switch if time for eAgc has come | 6.502779 | 5.476944 | 1.187301 |
ret = []
for r in all_pkg:
module = importlib.import_module(__name__ + '.' + r.lower())
ret.append(getattr(module, hook))
return ret | def get_command(all_pkg, hook) | Collect the command-line interface names by querying ``hook`` in ``all_pkg``
Parameters
----------
all_pkg: list
list of package files
hook: str
A variable where the command is stored. ``__cli__`` by default.
Returns
-------
list | 3.675405 | 4.672785 | 0.786556 |
if not self.n:
return list()
ret = list()
for item in self._event_times:
ret += list(self.__dict__[item])
return ret + list(matrix(ret) - 1e-6) | def get_times(self) | Return a list of occurrance times of the events
:return: list of times | 10.199739 | 9.890352 | 1.031282 |
if not self.n:
return
# skip if already applied
if self._last_time != sim_time:
self._last_time = sim_time
else:
return | def apply(self, sim_time) | Apply the event and
:param sim_time:
:return: | 5.660882 | 6.073331 | 0.932089 |
if not self.n:
return
self.y1 = mul(self.u, self.g1 + self.b1 * 1j)
self.y2 = mul(self.u, self.g2 + self.b2 * 1j)
self.y12 = div(self.u, self.r + self.x * 1j)
self.m = polar(self.tap, self.phi * deg2rad)
self.m2 = abs(self.m)**2
self.mconj = c... | def build_y(self) | Build transmission line admittance matrix into self.Y | 3.115977 | 2.879555 | 1.082104 |
if not self.n:
return
method = self.system.pflow.config.method.lower()
# Build B prime matrix
y1 = mul(
self.u, self.g1
) # y1 neglects line charging shunt, and g1 is usually 0 in HV lines
y2 = mul(
self.u, self.g2
) ... | def build_b(self) | build Bp and Bpp for fast decoupled method | 2.558178 | 2.502418 | 1.022283 |
self.C = \
spmatrix(self.u, range(self.n), self.a1, (self.n, self.nb), 'd') -\
spmatrix(self.u, range(self.n), self.a2, (self.n, self.nb), 'd') | def incidence(self) | Build incidence matrix into self.C | 4.37918 | 3.28392 | 1.333522 |
if not self.n:
return
n = self.nb
fr = self.a1
to = self.a2
os = [0] * self.n
# find islanded buses
diag = list(
matrix(
spmatrix(self.u, to, os, (n, 1), 'd') +
spmatrix(self.u, fr, os, (n, 1), 'd')... | def connectivity(self, bus) | check connectivity of network using Goderya's algorithm | 4.670374 | 4.623528 | 1.010132 |
if not self.n:
idx = range(dae.m)
dae.set_jac(Gy, 1e-6, idx, idx)
return
Vn = polar(1.0, dae.y[self.a])
Vc = mul(dae.y[self.v], Vn)
Ic = self.Y * Vc
diagVn = spdiag(Vn)
diagVc = spdiag(Vc)
diagIc = spdiag(Ic)
... | def build_gy(self, dae) | Build line Jacobian matrix | 5.960608 | 5.579424 | 1.06832 |
# Vm = dae.y[self.v]
# Va = dae.y[self.a]
# V1 = polar(Vm[self.a1], Va[self.a1])
# V2 = polar(Vm[self.a2], Va[self.a2])
I1 = mul(self.v1, div(self.y12 + self.y1, self.m2)) - \
mul(self.v2, div(self.y12, self.mconj))
I2 = mul(self.v2, self.y12 + self... | def seriesflow(self, dae) | Compute the flow through the line after solving PF.
Compute terminal injections, line losses | 2.200597 | 2.186344 | 1.006519 |
Vm = self.system.dae.y[self.v]
Va = self.system.dae.y[self.a]
return polar(Vm[self.a1], Va[self.a1]) | def v1(self) | Return voltage phasors at the "from buses" (bus1) | 7.453624 | 6.168023 | 1.20843 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.