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 algebraic variables
nflows = 0
if self.system.tds.config.compute_flows:
nflows = 2 * self.system.Bus.n + \
8 * self.system.Line.n + \
2 * self.system.Area.n_combination
# output variable indices
if system.Recorder.n == 0:
state_idx = list(range(dae.n))
algeb_idx = list(range(dae.n, dae.n + dae.m + nflows))
idx = state_idx + algeb_idx
else:
idx = system.Recorder.varout_idx
# variable names concatenated
uname = varname.unamex + varname.unamey
fname = varname.fnamex + varname.fnamey
for e, i in enumerate(idx):
out += template.format(e + 1, uname[i], fname[i])
try:
with open(self.system.files.lst, 'w') as f:
f.write(out)
ret = True
except IOError:
logger.error('I/O Error while writing the lst file.')
return ret | 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],
len(self.vars))).trans()
self.vars_array = np.array(vars_matrix)
return self.vars_array | 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')
fh = logging.FileHandler(log_full_path)
fh.setLevel(logging.DEBUG)
fh.setFormatter(fh_formatter)
logger.addHandler(fh)
logger.debug('Writing log to {}'.format(log_full_path))
if stream is True:
sh_formatter = logging.Formatter('%(message)s')
sh = logging.StreamHandler()
sh.setFormatter(sh_formatter)
sh.setLevel(stream_level)
logger.addHandler(sh)
globals()['logger'] = logger | 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 affect the loggers in modules and
cause unexpected behaviours.
log_file : str, optional
Logg file name for `FileHandler`, ``'andes.log'`` by default.
If ``None``, the `FileHandler` will not be created.
log_path : str, optional
Path to store the log file. By default, the path is generated by
get_log_dir() in utils.misc.
stream : bool, optional
Create a `StreamHandler` for `stdout` if ``True``.
If ``False``, the handler will not be created.
stream_level : {10, 20, 30, 40, 50}, optional
`StreamHandler` verbosity level.
Returns
-------
None | 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() + ', '
except OSError:
username = ''
logger.info('Session: {}{}'.format(username,
strftime("%m/%d/%Y %I:%M:%S %p")))
logger.info('') | 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 default editors
if platform.system() == 'Linux':
editor = os.environ.get('EDITOR', 'gedit')
elif platform.system() == 'Darwin':
editor = os.environ.get('EDITOR', 'vim')
elif platform.system() == 'Windows':
editor = 'notepad.exe'
else:
# use `edit_config` as default editor
editor = edit_config
call([editor, conf_path])
ret = True
else:
logger.info('Config file does not exist. Save config with \'andes '
'--save-config\'')
ret = True
return ret | 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 first in the
search order.
kwargs : dict
Other keyword arguments.
Returns
-------
bool
``True`` is a config file is found and an editor is opened. ``False``
if ``edit_config`` is False. | 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 \
file.endswith('_prof.txt'):
found = True
try:
os.remove(file)
logger.info('<{:s}> removed.'.format(file))
except IOError:
logger.error('Error removing file <{:s}>.'.format(file))
if not found:
logger.info('no output found in the working directory.')
return True | 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
Other keyword arguments
Returns
-------
bool
``True`` is the function body executes with success. ``False``
otherwise. | 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():
out.append(key + '.' + item)
if out:
print('Search result: <file.model> containing <{}>'
.format(search))
print(' '.join(out))
else:
print('No model containing <{:s}> found'.format(search))
return out | 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
Other keyword arguments.
Returns
-------
list
The list of model names that match the given pattern. | 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(path)
cf_path = os.path.join(path, cf_path)
ps = PowerSystem()
ps.dump_config(cf_path)
ret = True
return ret | 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 action will not run. Save to
`~/.andes/andes.conf` if ``None``.
kwargs : dict, optional
Other keyword arguments
Returns
-------
bool
``True`` is the save action is run. ``False`` otherwise. | 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.pformat(args))
if andeshelp(**args) or search(**args) or edit_conf(**args) or remove_output(**args) \
or save_config(**args):
return
# process input files
if len(args['filename']) == 0:
logger.info('error: no input file. Try \'andes -h\' for help.')
# preprocess cli args
path = args.get('input_path', os.getcwd())
ncpu = args['ncpu']
if ncpu == 0 or ncpu > os.cpu_count():
ncpu = os.cpu_count()
cases = []
for file in args['filename']:
# use absolute path for cases which will be respected by FileMan
full_paths = os.path.abspath(os.path.join(path, file))
found = glob.glob(full_paths)
if len(found) == 0:
logger.info('error: file {} does not exist.'.format(full_paths))
else:
cases += found
# remove folders and make cases unique
cases = list(set(cases))
valid_cases = []
for case in cases:
if os.path.isfile(case):
valid_cases.append(case)
logger.debug('Found files: ' + pprint.pformat(valid_cases))
if len(valid_cases) <= 0:
pass
elif len(valid_cases) == 1:
run(valid_cases[0], **args)
else:
# set verbose level for multi processing
logger.info('Processing {} jobs on {} CPUs'.format(len(valid_cases), ncpu))
logger.handlers[1].setLevel(logging.WARNING)
# start processes
jobs = []
for idx, file in enumerate(valid_cases):
args['pid'] = idx
job = Process(
name='Process {0:d}'.format(idx),
target=run,
args=(file, ),
kwargs=args)
jobs.append(job)
job.start()
start_msg = 'Process {:d} <{:s}> started.'.format(idx, file)
print(start_msg)
logger.debug(start_msg)
if (idx % ncpu == ncpu - 1) or (idx == len(valid_cases) - 1):
sleep(0.1)
for job in jobs:
job.join()
jobs = []
# restore command line output when all jobs are done
logger.handlers[1].setLevel(logging.INFO)
t0, s0 = elapsed(t0)
if len(valid_cases) == 1:
logger.info('-> Single process finished in {:s}.'.format(s0))
elif len(valid_cases) >= 2:
logger.info('-> Multiple processes finished in {:s}.'.format(s0))
return | 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 the input files and call ``main.run()`` using single- or
multi-processing
* Show the execution time and exit
Returns
-------
None | 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
if dump_raw:
filters.dump_raw(system)
system.setup()
# show data
if show_data is not None:
if len(show_data) == 0:
show_data = sorted(system.devman.devices)
for mdl in show_data:
logger.info('Model <{}> data in system base'.format(mdl))
logger.info(system.__dict__[mdl].data_to_df(sysbase=True).to_string())
logger.info('')
if routine is None or exit is True:
pass
else:
# run power flow first
if 'pflow' in routine:
routine.remove('pflow')
system.pflow.run()
system.tds.init()
system.report.write(content='powerflow')
# run the rest of the routines
for r in routine:
system.__dict__[r.lower()].run()
# Disable profiler and output results
if profile:
pr.disable()
if system.files.no_output:
s = io.StringIO()
nlines = 40
ps = pstats.Stats(pr, stream=sys.stdout).sort_stats('cumtime')
ps.print_stats(nlines)
logger.info(s.getvalue())
s.close()
else:
s = open(system.files.prof, 'w')
nlines = 999
ps = pstats.Stats(pr, stream=s).sort_stats('cumtime')
ps.print_stats(nlines)
s.close()
logger.info('cProfile results for job{:s} written.'.format(
' ' + str(pid) if pid >= 0 else ''))
if pid >= 0:
_, s = elapsed(t0)
msg_finish = 'Process {:d} finished in {:s}.'.format(pid, s)
logger.info(msg_finish)
print(msg_finish)
return system | 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)
Parameters
----------
case : str
Path to the case file
profile : bool, optional
Enable cProfile if ``True``.
dump_raw : ``False`` or str, optional
Path to the file to dump the system parameters in the dm format
routine : Iterable, optional
A list of routines to run in sequence (``('pflow')`` as default)
pid : idx, optional
Process idx of the current run
kwargs : dict, optional
Other keyword arguments
Returns
-------
PowerSystem
Andes PowerSystem object | 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
self.build_vec()
self.build_strings()
self._compile_newton()
self._compile_fdpf()
self._compile_pfload()
self._compile_pfgen()
self._compile_seriesflow()
self._compile_int()
self._compile_int_f()
self._compile_int_g()
self._compile_bus_injection() | 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, False)
self.__dict__[item].append(val) | 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] = header + '.fxcall(system.dae)\n'
self.jac0s[idx] = header + '.jac0(system.dae)\n' | 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:
string += ' ' + call
string += ' system.dae.temp_to_spmatrix(\'jac0\')\n'
# evaluate Jacobians Gy and Fx
string += 'system.dae.setup_FxGy()\n'
for gycall, call in zip(self.gycall, self.gycalls):
if gycall:
string += call
string += '\n'
for fxcall, call in zip(self.fxcall, self.fxcalls):
if fxcall:
string += call
string += self.gyisland
string += 'system.dae.temp_to_spmatrix(\'jac\')\n'
string += '"""'
if SHOW_INT_CALL:
logger.debug(string)
self.int = compile(eval(string), '', 'exec') | 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)
if not self._unamex:
self._unamex = self._states
else:
assert len(self._unamex) == len(self._states)
for item in self._data.keys():
self.__dict__[item] = []
for bus in self._ac.keys():
for var in self._ac[bus]:
self.__dict__[var] = []
for node in self._dc.keys():
for var in self._dc[node]:
self.__dict__[var] = []
for var in self._states + self._algebs + self._service:
self.__dict__[var] = []
self._flags['sysbase'] = False
self._flags['allocate'] = False
self._flags['address'] = False | 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._descr.update({param: descr})
if tomatrix:
self._params.append(param)
if nonzero:
self._zeros.append(param)
if mandatory:
self._mandatory.append(param)
if power:
self._powers.append(param)
if voltage:
self._voltages.append(param)
if current:
self._currents.append(param)
if z:
self._z.append(param)
if y:
self._y.append(param)
if r:
self._r.append(param)
if g:
self._g.append(param)
if dccurrent:
self._dccurrents.append(param)
if dcvoltage:
self._dcvoltages.append(param)
if time:
self._times.append(param)
if event_time:
self._event_times.append(param) | def param_define(self,
param,
default,
unit='',
descr='',
tomatrix=True,
nonzero=False,
mandatory=False,
power=False,
voltage=False,
current=False,
z=False,
y=False,
r=False,
g=False,
dccurrent=False,
dcvoltage=False,
time=False,
event_time=False,
**kwargs) | 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 mandatory
:param power: is a power value in the `self.Sn` base
:param voltage: is a voltage value in the `self.Vn` base
:param current: is a current value in the device base
:param z: is an impedance value in the device base
:param y: is an admittance value in the device base
:param r: is a dc resistance value in the device base
:param g: is a dc conductance value in the device base
:param dccurrent: is a dc current value in the device base
:param dcvoltage: is a dc votlage value in the device base
:param time: is a time value in the device base
:param event_time: is a variable for timed event
:type param: str
:type tomatrix: bool
:type default: str, float
:type unit: str
:type descr: str
:type nonzero: bool
:type mandatory: bool
:type power: bool
:type voltage: bool
:type current: bool
:type z: bool
:type y: bool
:type r: bool
:type g: bool
:type dccurrent: bool
:type dcvoltage: bool
:type time: bool
:type event_time: bool | 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})
elif ty == 'y':
self._algebs.append(variable)
self._fnamey.append(fname)
self._unamey.append(uname)
if descr:
self._algebs_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 variable: str
:type ty: str
:type descr: str
:return: | 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))
ret.append(self.uid[i])
return ret | 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}.{field}> could be unsafe.'
# .format(field=field, model=self._name)
# )
# =================================================================
uid = self.get_uid(idx)
field_data = self.__dict__[field]
if isinstance(field_data, matrix):
ret = field_data[uid]
elif isinstance(field_data, list):
if isinstance(idx, (float, int, str)):
ret = field_data[uid]
else:
ret = [field_data[x] for x in uid]
if astype is not None:
ret = astype(ret)
return ret | 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]
else:
val = self.__dict__[key][i]
e[key] = val
ret.append(e)
return ret | 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 length'.
format(self._name, key))
nvars.append(len(val))
# assign idx-uid mapping
for i, idx in zip(range(self.n), self.idx):
self.uid[idx] = i | 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.system.dae.x[idx]})
for y in self._algebs:
idx = self.__dict__[y]
ret.update({y: self.system.dae.y[idx]})
var_df = pd.DataFrame.from_dict(ret).set_index('idx')
return var_df | 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.__dict__[attr].append(p)
elif (value is False) and (p in self.__dict__[attr]):
self.__dict__[attr].remove(p)
else:
self.log('No need to alter {} for {}'.format(attr, p))
if default is not None:
self._data.update({param: default})
if unit is not None:
self._units.update({param: unit})
if descr is not None:
self._descr.update({param: descr})
alter_attr(param, '_params', tomatrix)
alter_attr(param, '_zeros', nonzero)
alter_attr(param, '_mandatory', mandatory)
alter_attr(param, '_powers', power)
alter_attr(param, '_voltages', voltage)
alter_attr(param, '_currents', current)
alter_attr(param, '_z', z)
alter_attr(param, '_y', y)
alter_attr(param, '_r', r)
alter_attr(param, '_g', g)
alter_attr(param, '_dcvoltages', dcvoltage)
alter_attr(param, '_dccurrents', dccurrent)
alter_attr(param, '_times', time) | def param_alter(self,
param,
default=None,
unit=None,
descr=None,
tomatrix=None,
nonzero=None,
mandatory=None,
power=None,
voltage=None,
current=None,
z=None,
y=None,
r=None,
g=None,
dccurrent=None,
dcvoltage=None,
time=None,
**kwargs) | 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'
elif var in self._states:
ty = 'f'
else:
for _, item in self._ac:
if var in item:
ty = 'g'
if intf is False:
intf = True
for _, item in self._dc:
if var == item:
ty = 'g'
if intf is False:
intf = True
if ty == '':
self.log(
'Equation associated with interface variable {var} '
'assumed as algeb'.
format(var=var),
DEBUG)
ty = 'g'
self._equations.append((expr, var, intf, ty)) | 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 expression
:param str var: variable name to be associated with
:param bool intf: if this equation is added to an interface equation,
namely, an equation outside this model
:return: None | 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.devman.group`` is an unordered dictionary,
# ``idx`` must be given to retrieve ``field`` across models.
#
# Returns a matrix by default
# ===============================================================
assert idx is not None, \
'idx must be specified when accessing group fields'
astype = matrix
for item in idx:
dev_name = self.system.devman.group[model].get(item, None)
ret.append(self.read_data_ext(dev_name, field, idx=item))
else:
raise NameError(
'Model or Group <{0}> does not exist.'.format(model))
if (ret is None) or isinstance(ret, (int, float, str)):
return ret
elif astype is None:
return ret
else:
return astype(ret) | 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:
self.link_to(model, idx, self.idx) | 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 astype: type cast
:type model: str
:type field: str
:type dest: str
:type idx: list, matrix
:type astype: None, list, matrix
:return: None | 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 += 1
if name is None:
self.name.append(self._name + ' ' + str(self.n))
else:
self.name.append(name)
# check mandatory parameters
for key in self._mandatory:
if key not in kwargs.keys():
self.log(
'Mandatory parameter <{:s}.{:s}> missing'.format(
self.name[-1], key), ERROR)
sys.exit(1)
# set default values
for key, value in self._data.items():
self.__dict__[key].append(value)
# overwrite custom values
for key, value in kwargs.items():
if key not in self._data:
self.log(
'Parameter <{:s}.{:s}> is not used.'.format(
self.name[-1], key), WARNING)
continue
self.__dict__[key][-1] = value
# check data consistency
if not value and key in self._zeros:
if key == 'Sn':
default = self.system.mva
elif key == 'fn':
default = self.system.config.freq
else:
default = self._data[key]
self.__dict__[key][-1] = default
self.log(
'Using default value for <{:s}.{:s}>'.format(
self.name[-1], key), WARNING)
return idx | 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
if isinstance(self.__dict__[self._params[0]], matrix):
self._param_to_list()
convert = True
# self.n -= 1
self.uid.pop(key, '')
self.idx.pop(item)
self.mdl_from.pop(item)
self.mdl_to.pop(item)
for x, y in self.uid.items():
if y > item:
self.uid[x] = y - 1
for param in self._data:
self.__dict__[param].pop(item)
for param in self._service:
if len(self.__dict__[param]) == (self.n + 1):
if isinstance(self.__dict__[param], list):
self.__dict__[param].pop(item)
elif isinstance(self.__dict__[param], matrix):
service = list(self.__dict__[param])
service.pop(item)
self.__dict__[param] = matrix(service)
for x in self._states:
if len(self.__dict__[x]):
self.__dict__[x].pop(item)
for y in self._algebs:
if self.__dict__[y]:
self.__dict__[y].pop(item)
for key, param in self._ac.items():
if isinstance(param, list):
for subparam in param:
if len(self.__dict__[subparam]):
self.__dict__[subparam].pop(item)
else:
self.__dict__[param].pop(item)
for key, param in self._dc.items():
self.__dict__[param].pop(item)
self.name.pop(item)
if convert and self.n:
self._param_to_matrix() | 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', idx=self.bus1)
for var in self._voltages:
self._store[var] = self.__dict__[var]
self.__dict__[var] = mul(self.__dict__[var], self.Vn)
self.__dict__[var] = div(self.__dict__[var], Vb)
for var in self._powers:
self._store[var] = self.__dict__[var]
self.__dict__[var] = mul(self.__dict__[var], self.Sn)
self.__dict__[var] /= Sb
for var in self._currents:
self._store[var] = self.__dict__[var]
self.__dict__[var] = mul(self.__dict__[var], self.Sn)
self.__dict__[var] = div(self.__dict__[var], self.Vn)
self.__dict__[var] = mul(self.__dict__[var], Vb)
self.__dict__[var] /= Sb
if len(self._z) or len(self._y):
Zn = div(self.Vn**2, self.Sn)
Zb = (Vb**2) / Sb
for var in self._z:
self._store[var] = self.__dict__[var]
self.__dict__[var] = mul(self.__dict__[var], Zn)
self.__dict__[var] = div(self.__dict__[var], Zb)
for var in self._y:
self._store[var] = self.__dict__[var]
if self.__dict__[var].typecode == 'd':
self.__dict__[var] = div(self.__dict__[var], Zn)
self.__dict__[var] = mul(self.__dict__[var], Zb)
elif self.__dict__[var].typecode == 'z':
self.__dict__[var] = div(self.__dict__[var], Zn + 0j)
self.__dict__[var] = mul(self.__dict__[var], Zb + 0j)
if len(self._dcvoltages) or len(self._dccurrents) or len(
self._r) or len(self._g):
dckey = sorted(self._dc.keys())[0]
Vbdc = self.read_data_ext('Node', 'Vdcn', self.__dict__[dckey])
Ib = div(Sb, Vbdc)
Rb = div(Vbdc, Ib)
for var in self._dcvoltages:
self._store[var] = self.__dict__[var]
self.__dict__[var] = mul(self.__dict__[var], self.Vdcn)
self.__dict__[var] = div(self.__dict__[var], Vbdc)
for var in self._dccurrents:
self._store[var] = self.__dict__[var]
self.__dict__[var] = mul(self.__dict__[var], self.Idcn)
self.__dict__[var] = div(self.__dict__[var], Ib)
for var in self._r:
self._store[var] = self.__dict__[var]
self.__dict__[var] = div(self.__dict__[var], Rb)
for var in self._g:
self._store[var] = self.__dict__[var]
self.__dict__[var] = mul(self.__dict__[var], Rb)
self._flags['sysbase'] = True | 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():
self.copy_data_ext(
model='Node', field='v', dest=val, idx=self.__dict__[key])
# check for interface voltage differences
self._check_Vn() | 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.node1
- system.Node.v-> self.v1
:return: None | 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)``.
:Example:
``self._ctrl = {'syn', ('Synchronous', 'omega', 'w', list)}``
- indices: self.syn
- self.w = list(system.Synchronous.omega)
:return: None | 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
nend = n0 + len(self._states) * self.n
if group_by == 'variable':
for idx, item in enumerate(self._algebs):
self.__dict__[item] = list(
range(m0 + idx * self.n, m0 + (idx + 1) * self.n))
for idx, item in enumerate(self._states):
self.__dict__[item] = list(
range(n0 + idx * self.n, n0 + (idx + 1) * self.n))
elif group_by == 'element':
for idx, item in enumerate(self._algebs):
self.__dict__[item] = list(
range(m0 + idx, mend, len(self._algebs)))
for idx, item in enumerate(self._states):
self.__dict__[item] = list(
range(n0 + idx, nend, len(self._states)))
self.system.dae.m = mend
self.system.dae.n = nend
self._flags['address'] = True | 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._states):
unamex = self._unamex[e]
fnamex = self._fnamex[e]
idx = self.__dict__[var][i]
varname.unamex[idx] = '{} {}'.format(unamex, iname)[:33]
varname.fnamex[idx] = '$' + '{}\\ {}'.format(
fnamex, iname.replace(' ', '\\ '))[:33] + '$'
for e, var in enumerate(self._algebs):
unamey = self._unamey[e]
fnamey = self._fnamey[e]
idx = self.__dict__[var][i]
varname.unamey[idx] = '{} {}'.format(unamey, iname)[:33]
varname.fnamey[idx] = '$' + '{}\\ {}'.format(
fnamey, iname.replace(' ', '\\ '))[:33] + '$' | 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, key, maxval), ERROR)
if limit:
self.__dict__[key][idx] = maxval
below = altb(self.__dict__[key], lower)
for idx, item in enumerate(below):
if item == 0.:
continue
minval = lower[idx]
self.log(
'{0} <{1}.{2}> below its minimum of {3}.'.format(
self.name[idx], self._name, key, minval), ERROR)
if limit:
self.__dict__[key][idx] = minval | 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:
suf = ' *'
elif key in self._powers + \
self._voltages + \
self._currents + \
self._z + \
self._y + \
self._dccurrents + \
self._dcvoltages + \
self._r + \
self._g + \
self._times:
suf = ' #'
c1 = key + suf
c2 = self._descr.get(key, '')
c3 = val
c4 = self._units.get(key, '-')
rows.append([c1, c2, c3, c4])
table.add_rows(rows, header=False)
table.header(['Parameter', 'Description', 'Default', 'Unit'])
if export == 'plain':
pass
elif export == 'latex':
raise NotImplementedError('LaTex output not implemented')
return table.draw() | 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
val = matrix(self.__dict__[varname])
vmin = matrix(self.__dict__[vmin])
comp = altb(val, vmin)
comp = mul(self.u, comp)
for c, n, idx in zip(comp, self.name, range(self.n)):
if c == 1:
v = val[idx]
vm = vmin[idx]
self.log(
'Init of <{}.{}>={:.4g} is lower than min={:6.4g}'.format(
n, varname, v, vm), ERROR)
retval = False
vmax = matrix(self.__dict__[vmax])
comp = agtb(val, vmax)
comp = mul(self.u, comp)
for c, n, idx in zip(comp, self.name, range(self.n)):
if c == 1:
v = val[idx]
vm = vmax[idx]
self.log(
'Init of <{}.{}>={:.4g} is higher than max={:.4g}'.format(
n, varname, v, vm), ERROR)
retval = False
return retval | 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])
if len(idx) == 1:
idx = idx[0]
elif len(idx) == 0:
idx = None
ret.append(idx)
if len(ret) == 1:
ret = ret[0]
return ret | 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]
fkey = list(self._ac.keys())
if 'bus' in fkey:
fkey.remove('bus')
nfkey = len(fkey)
fkey_val = [self.__dict__[i] for i in fkey]
for item in bus_idx:
idx = []
key = []
for i in range(self.n):
for j in range(nfkey):
if fkey_val[j][i] == item:
idx.append(self.idx[i])
key.append(fkey[j])
# <= 1 terminal should connect to the same bus
break
if len(idx) == 0:
idx = None
if len(key) == 0:
key = None
ret.append((idx, key))
return ret | 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 elements
:rtype: list, int, float, str | 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(
'<{}> has Vn={} different from bus <{}> Vn={}.'.format(
name, Vn, bus, Vn0), WARNING)
if hasattr(self, 'node') and hasattr(self, 'Vdcn'):
node_Vdcn = self.read_data_ext('Node', field='Vdcn', idx=self.node)
for name, node, Vdcn, Vdcn0 in zip(self.name, self.node, self.Vdcn,
node_Vdcn):
if Vdcn != Vdcn0:
self.log(
'<{}> has Vdcn={} different from node <{}> Vdcn={}.'
.format(name, Vdcn, node, Vdcn0), WARNING) | 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_model[i]
mdl = self.system.__dict__[mdl_name]
# query the corresponding uid
u = mdl.get_uid(i)
# update `mdl_from`
name_idx_pair = (self._name, self_i)
if name_idx_pair not in mdl.mdl_from[u]:
mdl.mdl_from[u].append(name_idx_pair)
else:
# access model instance
mdl = self.system.__dict__[model]
uid = mdl.get_uid(idx)
for u, self_i in zip(uid, self_idx):
name_idx_pair = (self._name, self_i)
if name_idx_pair not in mdl.mdl_from[u]:
mdl.mdl_from[u].append(name_idx_pair) | 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, pflow, init0 in zip(system.devman.devices,
system.call.pflow, system.call.init0):
if pflow and init0:
system.__dict__[device].init0(dae)
# check for islands
system.check_islands(show_info=True)
t, s = elapsed(t)
logger.debug('Power flow initialized in {:s}.'.format(s)) | 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.config.method in ('FDPF', 'FDBX', 'FDXB'):
ret = self.fdpf()
self.post()
_, s = elapsed(t)
if self.solved:
logger.info(' Solution converged in {} in {} iterations'.format(s, self.niter))
else:
logger.warning(' Solution failed in {} in {} iterations'.format(s,
self.niter))
return ret | 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)
if max_mis < self.config.tol:
self.solved = True
break
elif self.niter > 5 and max_mis > 1000 * self.iter_mis[0]:
logger.warning('Blown up in {0} iterations.'.format(self.niter))
break
if self.niter > self.config.maxit:
logger.warning('Reached maximum number of iterations.')
break
return self.solved, 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.__dict__[model].gcall(dae)
sw = self.system.SW.a
sw.sort(reverse=True)
no_sw = self.system.Bus.a[:]
no_swv = self.system.Bus.v[:]
for item in sw:
no_sw.pop(item)
no_swv.pop(item)
Bp = self.system.Line.Bp[no_sw, no_sw]
p = matrix(self.system.dae.g[no_sw], (no_sw.__len__(), 1))
p = p-self.system.Line.Bp[no_sw, sw]*Va0[sw]
Sp = self.solver.symbolic(Bp)
N = self.solver.numeric(Bp, Sp)
self.solver.solve(Bp, Sp, N, p)
self.system.dae.y[no_sw] = p
self.solved = True
self.niter = 1
return self.solved, self.niter | 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.dae.factorize = False
try:
N = self.solver.numeric(A, self.F)
self.solver.solve(A, self.F, N, inc)
except ValueError:
logger.warning('Unexpected symbolic factorization.')
system.dae.factorize = True
except ArithmeticError:
logger.warning('Jacobian matrix is singular.')
system.dae.check_diag(system.dae.Gy, 'unamey')
return -inc | 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,
system.call.pflow, system.call.gcall):
if pflow and gcall:
system.__dict__[model].gcall(dae)
# eval differential equations
for model, pflow, fcall in zip(system.devman.devices,
system.call.pflow, system.call.fcall):
if pflow and fcall:
system.__dict__[model].fcall(dae)
# reset islanded buses mismatches
system.Bus.gisland(dae)
if system.dae.factorize:
system.dae.init_jac0()
# evaluate constant Jacobian elements
for model, pflow, jac0 in zip(system.devman.devices,
system.call.pflow, system.call.jac0):
if pflow and jac0:
system.__dict__[model].jac0(dae)
dae.temp_to_spmatrix('jac0')
dae.setup_FxGy()
# evaluate Gy
for model, pflow, gycall in zip(system.devman.devices,
system.call.pflow, system.call.gycall):
if pflow and gycall:
system.__dict__[model].gycall(dae)
# evaluate Fx
for model, pflow, fxcall in zip(system.devman.devices,
system.call.pflow, system.call.fxcall):
if pflow and fxcall:
system.__dict__[model].fxcall(dae)
# reset islanded buses Jacobians
system.Bus.gyisland(dae)
dae.temp_to_spmatrix('jac') | 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.Bus.Qg = system.dae.g[system.Bus.v]
if system.PV.n:
system.PV.qg = system.dae.y[system.PV.q]
if system.SW.n:
system.SW.pg = system.dae.y[system.SW.p]
system.SW.qg = system.dae.y[system.SW.q]
exec(system.call.seriesflow)
system.Area.seriesflow(system.dae) | 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.build_b()
# initialize indexing and Jacobian
# ngen = system.SW.n + system.PV.n
sw = system.SW.a
sw.sort(reverse=True)
no_sw = system.Bus.a[:]
no_swv = system.Bus.v[:]
for item in sw:
no_sw.pop(item)
no_swv.pop(item)
gen = system.SW.a + system.PV.a
gen.sort(reverse=True)
no_g = system.Bus.a[:]
no_gv = system.Bus.v[:]
for item in gen:
no_g.pop(item)
no_gv.pop(item)
Bp = system.Line.Bp[no_sw, no_sw]
Bpp = system.Line.Bpp[no_g, no_g]
Fp = self.solver.symbolic(Bp)
Fpp = self.solver.symbolic(Bpp)
Np = self.solver.numeric(Bp, Fp)
Npp = self.solver.numeric(Bpp, Fpp)
exec(system.call.fdpf)
# main loop
while error > tol:
# P-theta
da = matrix(div(system.dae.g[no_sw], system.dae.y[no_swv]))
self.solver.solve(Bp, Fp, Np, da)
system.dae.y[no_sw] += da
exec(system.call.fdpf)
normP = max(abs(system.dae.g[no_sw]))
# Q-V
dV = matrix(div(system.dae.g[no_gv], system.dae.y[no_gv]))
self.solver.solve(Bpp, Fpp, Npp, dV)
system.dae.y[no_gv] += dV
exec(system.call.fdpf)
normQ = max(abs(system.dae.g[no_gv]))
err = max([normP, normQ])
self.iter_mis.append(err)
error = err
self._iter_info(self.niter)
self.niter += 1
if self.niter > 4 and self.iter_mis[-1] > 1000 * self.iter_mis[0]:
logger.warning('Blown up in {0} iterations.'.format(self.niter))
self.solved = False
break
if self.niter > iter_max:
logger.warning('Reached maximum number of iterations.')
self.solved = False
break
return self.solved, self.niter | 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))
else:
self.message_box.addstr(
", " + field + ":", curses.color_pair(1)
)
self.message_box.addstr(header[field])
self.message_box.addstr(": ", curses.color_pair(1))
self.message_box.addstr(
str(message), curses.color_pair(2) + curses.A_BOLD
)
self.message_box.refresh()
if (
message["host"] not in self._node_status
or int(header["timestamp"])
>= self._node_status[message["host"]]["last_seen"]
):
self._node_status[message["host"]] = message
self._node_status[message["host"]]["last_seen"] = int(
header["timestamp"]
) | 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 message", color_pair=1
)
self.message_box.scrollok(True)
self.cards = [] | 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,
35,
7 + 6 * (number // max_cards_horiz),
35 * (number % max_cards_horiz),
)
obliterate.erase()
obliterate.noutrefresh()
del self.cards[number] | 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)
try:
while not self.shutdown:
now = int(time.time())
with self._lock:
overview = self._node_status.copy()
cardnumber = 0
for host, status in overview.items():
age = now - int(status["last_seen"] / 1000)
with self._lock:
if age > 90:
del self._node_status[host]
else:
card = self._get_card(cardnumber)
card.erase()
card.move(0, 0)
card.addstr("Host: ", curses.color_pair(3))
card.addstr(host)
card.move(1, 0)
card.addstr("Service: ", curses.color_pair(3))
if "service" in status and status["service"]:
card.addstr(status["service"])
else:
card.addstr("---", curses.color_pair(2))
card.move(2, 0)
card.addstr("State: ", curses.color_pair(3))
if "status" in status:
status_code = status["status"]
state_string = CommonService.human_readable_state.get(
status_code, str(status_code)
)
state_color = None
if status_code in (
CommonService.SERVICE_STATUS_PROCESSING,
CommonService.SERVICE_STATUS_TIMER,
):
state_color = curses.color_pair(3) + curses.A_BOLD
if status_code == CommonService.SERVICE_STATUS_IDLE:
state_color = curses.color_pair(2) + curses.A_BOLD
if status_code == CommonService.SERVICE_STATUS_ERROR:
state_color = curses.color_pair(1)
if state_color:
card.addstr(state_string, state_color)
else:
card.addstr(state_string)
card.move(3, 0)
if age >= 10:
card.addstr(
"last seen %d seconds ago" % age,
curses.color_pair(1)
+ (0 if age < 60 else curses.A_BOLD),
)
card.noutrefresh()
cardnumber = cardnumber + 1
if cardnumber < len(self.cards):
with self._lock:
self._erase_card(cardnumber)
with self._lock:
curses.doupdate()
time.sleep(0.2)
except KeyboardInterrupt:
pass # User pressed CTRL+C
self._transport.disconnect() | 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:
old = 'PQ'
new = 'vQ'
elif self.PV[idx] == 1:
old = 'PV'
new = 'vV'
elif control == 'V':
if self.PV[idx] == 1:
old = 'PV'
new = 'PQ'
elif self.vV[idx] == 1:
old = 'vV'
new = 'vQ'
elif control == 'v':
if self.vQ[idx] == 1:
old = 'vQ'
new = 'PQ'
elif self.vV[idx] == 1:
old = 'vV'
new = 'PV'
if old and new:
self.__dict__[old][idx] = 0
self.__dict__[new][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 = self.__dict__.get(opt, '')
c4 = self.get_alt(opt)
rows.append([c1, c2, c3, c4])
else:
print('Setting {:s} has no {:s} option. Correct in config_descr.'.
format(self.__class__.__name__, opt))
table.add_rows(rows, header=False)
table.header(['Option', 'Description', 'Value', 'Alt.'])
return table.draw() | 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):
logger.debug('Config key {}.{} skipped'.format(section, key))
continue
val = conf[section].get(key)
try:
val = conf[section].getfloat(key)
except ValueError:
try:
val = conf[section].getboolean(key)
except ValueError:
pass
self.__dict__.update({key: val})
self.check() | 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"]] = (
summary.get(event["status"], 0)
+ event["end"]
- max(cutoff, event["start"])
)
summary[self.status_history[-1]["status"]] = (
summary.get(self.status_history[-1]["status"], 0)
+ timestamp
- max(cutoff, self.status_history[-1]["start"])
)
if truncate:
self.status_history = self.status_history[truncate:]
total_duration = sum(summary.values())
summary = {s: round(d / total_duration, 4) for s, d in summary.items()}
return summary | 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:
return fullname
else:
return os.path.join(self.case_path, path, name) | 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(
self.idx[idx], t)) | 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 = conj(self.m)
# build self and mutual admittances into Y
self.Y = spmatrix(
div(self.y12 + self.y1, self.m2), self.a1, self.a1,
(self.nb, self.nb), 'z')
self.Y -= spmatrix(
div(self.y12, self.mconj), self.a1, self.a2, (self.nb, self.nb),
'z')
self.Y -= spmatrix(
div(self.y12, self.m), self.a2, self.a1, (self.nb, self.nb), 'z')
self.Y += spmatrix(self.y12 + self.y2, self.a2, self.a2,
(self.nb, self.nb), 'z') | 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
) # y2 neglects line charging shunt, and g2 is usually 0 in HV lines
m = polar(1.0, self.phi * deg2rad) # neglected tap ratio
self.mconj = conj(m)
m2 = matrix(1.0, (self.n, 1), 'z')
if method in ('fdxb', 'dcpf'):
# neglect line resistance in Bp in XB method
y12 = div(self.u, self.x * 1j)
else:
y12 = div(self.u, self.r + self.x * 1j)
self.Bp = spmatrix(
div(y12 + y1, m2), self.a1, self.a1, (self.nb, self.nb), 'z')
self.Bp -= spmatrix(
div(y12, conj(m)), self.a1, self.a2, (self.nb, self.nb), 'z')
self.Bp -= spmatrix(
div(y12, m), self.a2, self.a1, (self.nb, self.nb), 'z')
self.Bp += spmatrix(y12 + y2, self.a2, self.a2, (self.nb, self.nb),
'z')
self.Bp = self.Bp.imag()
# Build B double prime matrix
y1 = mul(
self.u, self.g1 + self.b1 * 1j
) # y1 neglected line charging shunt, and g1 is usually 0 in HV lines
y2 = mul(
self.u, self.g2 + self.b2 * 1j
) # y2 neglected line charging shunt, and g2 is usually 0 in HV lines
m = self.tap + 0j # neglected phase shifter
m2 = abs(m)**2 + 0j
if method in ('fdbx', 'fdpf', 'dcpf'):
# neglect line resistance in Bpp in BX method
y12 = div(self.u, self.x * 1j)
else:
y12 = div(self.u, self.r + self.x * 1j)
self.Bpp = spmatrix(
div(y12 + y1, m2), self.a1, self.a1, (self.nb, self.nb), 'z')
self.Bpp -= spmatrix(
div(y12, conj(m)), self.a1, self.a2, (self.nb, self.nb), 'z')
self.Bpp -= spmatrix(
div(y12, m), self.a2, self.a1, (self.nb, self.nb), 'z')
self.Bpp += spmatrix(y12 + y2, self.a2, self.a2, (self.nb, self.nb),
'z')
self.Bpp = self.Bpp.imag()
for item in range(self.nb):
if abs(self.Bp[item, item]) == 0:
self.Bp[item, item] = 1e-6 + 0j
if abs(self.Bpp[item, item]) == 0:
self.Bpp[item, item] = 1e-6 + 0j | 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')))
nib = bus.n_islanded_buses = diag.count(0)
bus.islanded_buses = []
for idx in range(n):
if diag[idx] == 0:
bus.islanded_buses.append(idx)
# find islanded areas
temp = spmatrix(
list(self.u) * 4, fr + to + fr + to, to + fr + fr + to, (n, n),
'd')
cons = temp[0, :]
nelm = len(cons.J)
conn = spmatrix([], [], [], (1, n), 'd')
bus.island_sets = []
idx = islands = 0
enum = 0
while 1:
while 1:
cons = cons * temp
cons = sparse(cons) # remove zero values
new_nelm = len(cons.J)
if new_nelm == nelm:
break
nelm = new_nelm
if len(cons.J) == n: # all buses are interconnected
return
bus.island_sets.append(list(cons.J))
conn += cons
islands += 1
nconn = len(conn.J)
if nconn >= (n - nib):
bus.island_sets = [i for i in bus.island_sets if i != []]
break
for element in conn.J[idx:]:
if not diag[idx]:
enum += 1 # skip islanded buses
if element <= enum:
idx += 1
enum += 1
else:
break
cons = temp[enum, :] | 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)
dS = self.Y * diagVn
dS = diagVc * conj(dS)
dS += conj(diagIc) * diagVn
dR = diagIc
dR -= self.Y * diagVc
dR = diagVc.H.T * dR
self.gy_store = sparse([[dR.imag(), dR.real()], [dS.real(),
dS.imag()]])
return self.gy_store | 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.y2) - \
mul(self.v2, div(self.y12, self.m))
self.I1_real = I1.real()
self.I1_imag = I1.imag()
self.I2_real = I2.real()
self.I2_imag = I2.imag()
self.S1 = mul(self.v1, conj(I1))
self.S2 = mul(self.v2, conj(I2))
self.P1 = self.S1.real()
self.P2 = self.S2.real()
self.Q1 = self.S1.imag()
self.Q2 = self.S2.imag()
self.chg1 = mul(self.g1 + 1j * self.b1, div(self.v1**2, self.m2))
self.chg2 = mul(self.g2 + 1j * self.b2, self.v2**2)
self.Pchg1 = self.chg1.real()
self.Pchg2 = self.chg2.real()
self.Qchg1 = self.chg1.imag()
self.Qchg2 = self.chg2.imag()
self._line_flows = matrix([self.P1, self.P2, self.Q1, self.Q2,
self.I1_real, self.I1_imag,
self.I2_real, self.I2_imag]) | 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.