_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q17400 | CommonService.initialize_logging | train | def initialize_logging(self):
"""Reset the logging for the service process. All logged messages are
forwarded to the frontend. If any filtering is desired, then this must
take place on the service side."""
# Reset logging to pass logrecords into the queue to the frontend only.
# ... | python | {
"resource": ""
} |
q17401 | CommonService.start | train | def start(self, **kwargs):
"""Start listening to command queue, process commands in main loop,
set status, etc...
This function is most likely called by the frontend in a separate
process."""
# Keep a copy of keyword arguments for use in subclasses
self.start_kwargs.upda... | python | {
"resource": ""
} |
q17402 | CommonService.process_uncaught_exception | train | def process_uncaught_exception(self, e):
"""This is called to handle otherwise uncaught exceptions from the service.
The service will terminate either way, but here we can do things such as
gathering useful environment information and logging for posterity."""
# Add information about the... | python | {
"resource": ""
} |
q17403 | IRCBot.connect | train | def connect(self, *args, **kwargs):
"""
Connect to a server.
This overrides the function in SimpleIRCClient
to provide SSL functionality.
:param args:
:param kwargs:
:return:
"""
if self.use_ssl:
factory = irc.connection.Factory(wrapp... | python | {
"resource": ""
} |
q17404 | IRCBot.set_metadata | train | def set_metadata(self, e):
"""
This function sets the metadata that is common between pub and priv
"""
metadata = Metadata(source=self.actor_urn).__dict__
metadata['source_connector'] = 'irc'
metadata['source_channel'] = e.target
metadata['source_user'] = e.source... | python | {
"resource": ""
} |
q17405 | IRCBot.on_pubmsg | train | def on_pubmsg(self, c, e):
"""
This function runs when the bot receives a public message.
"""
text = e.arguments[0]
metadata = self.set_metadata(e)
metadata['is_private_message'] = False
message = Message(text=text, metadata=metadata).__dict__
self.basepla... | python | {
"resource": ""
} |
q17406 | IRCBot.on_welcome | train | def on_welcome(self, c, e):
"""
This function runs when the bot successfully connects to the IRC server
"""
self.backoff = 1 # Assume we had a good connection. Reset backoff.
if self.nickserv:
if Utilities.isNotEmpty(self.nickserv_pass):
self.identify... | python | {
"resource": ""
} |
q17407 | IRCBot.run | train | def run(self):
"""
Run the bot in a thread.
Implementing the IRC listener as a thread allows it to
listen without blocking IRCLego's ability to listen
as a pykka actor.
:return: None
"""
self._connect()
super(irc.bot.SingleServerIRCBot, self).sta... | python | {
"resource": ""
} |
q17408 | System.check | train | def check(self):
"""
Check config data consistency
Returns
-------
"""
if self.sparselib not in self.sparselib_alt:
logger.warning("Invalid sparse library <{}>".format(self.sparselib))
self.sparselib = 'umfpack'
if self.sparselib == 'klu... | python | {
"resource": ""
} |
q17409 | Fault.apply | train | def apply(self, actual_time):
"""Check time and apply faults"""
if self.time != actual_time:
self.time = actual_time
else:
return
for i in range(self.n):
if self.tf[i] == self.time:
logger.info(
' <Fault> Applying f... | python | {
"resource": ""
} |
q17410 | SampleConsumer.consume_message | train | def consume_message(self, header, message):
"""Consume a message"""
logmessage = {
"time": (time.time() % 1000) * 1000,
"header": "",
"message": message,
}
if header:
logmessage["header"] = (
json.dumps(header, indent=2) + "... | python | {
"resource": ""
} |
q17411 | Lego.on_receive | train | def on_receive(self, message):
"""
Handle being informed of a message.
This function is called whenever a Lego receives a message, as
specified in the pykka documentation.
Legos should not override this function.
:param message:
:return:
"""
if ... | python | {
"resource": ""
} |
q17412 | Lego.cleanup | train | def cleanup(self):
"""
Clean up finished children.
:return: None
"""
self.lock.acquire()
logger.debug('Acquired lock in cleanup for ' + str(self))
self.children = [child for child in self.children if child.is_alive()]
self.lock.release() | python | {
"resource": ""
} |
q17413 | Lego.add_child | train | def add_child(self, child_type, *args, **kwargs):
"""
Initialize and keep track of a child.
:param child_type: a class inheriting from Lego to initialize \
an instance of
:param args: arguments for initializing the child
:param kwargs: keyword argument... | python | {
"resource": ""
} |
q17414 | Lego.reply | train | def reply(self, message, text, opts=None):
"""
Reply to the sender of the provided message with a message \
containing the provided text.
:param message: the message to reply to
:param text: the text to reply with
:param opts: A dictionary of additional values to add to ... | python | {
"resource": ""
} |
q17415 | Lego.build_reply_opts | train | def build_reply_opts(self, message):
"""
Convenience method for constructing default options for a
reply message.
:param message: the message to reply to
:return: opts
"""
try:
source = message['metadata']['source_channel']
thread = messag... | python | {
"resource": ""
} |
q17416 | alter | train | def alter(data, system):
"""Alter data in dm format devices"""
device = data[0]
action = data[1]
if data[2] == '*':
data[2] = '.*'
regex = re.compile(data[2])
prop = data[3]
value = float(data[4])
if action == 'MUL':
for item in range(system.__dict__[device].n):
... | python | {
"resource": ""
} |
q17417 | write | train | def write(file, system):
"""
Write data in system to a dm file
"""
# TODO: Check for bugs!!!
out = list()
out.append('# DOME format version 1.0')
ppl = 7 # parameter per line
retval = True
dev_list = sorted(system.devman.devices)
for dev in dev_list:
model = system.__d... | python | {
"resource": ""
} |
q17418 | StompTransport.add_command_line_options | train | def add_command_line_options(cls, parser):
"""function to inject command line parameters"""
if "add_argument" in dir(parser):
return cls.add_command_line_options_argparse(parser)
else:
return cls.add_command_line_options_optparse(parser) | python | {
"resource": ""
} |
q17419 | StompTransport.add_command_line_options_argparse | train | def add_command_line_options_argparse(cls, argparser):
"""function to inject command line parameters into
a Python ArgumentParser."""
import argparse
class SetParameter(argparse.Action):
"""callback object for ArgumentParser"""
def __call__(self, parser, namespa... | python | {
"resource": ""
} |
q17420 | StompTransport.add_command_line_options_optparse | train | def add_command_line_options_optparse(cls, optparser):
"""function to inject command line parameters into
a Python OptionParser."""
def set_parameter(option, opt, value, parser):
"""callback function for OptionParser"""
cls.config[opt] = value
if opt == "--st... | python | {
"resource": ""
} |
q17421 | StompTransport.is_connected | train | def is_connected(self):
"""Return connection status"""
self._connected = self._connected and self._conn.is_connected()
return self._connected | python | {
"resource": ""
} |
q17422 | StompTransport.disconnect | train | def disconnect(self):
"""Gracefully close connection to stomp server."""
if self._connected:
self._connected = False
self._conn.disconnect() | python | {
"resource": ""
} |
q17423 | StompTransport.broadcast_status | train | def broadcast_status(self, status):
"""Broadcast transient status information to all listeners"""
self._broadcast(
"transient.status",
json.dumps(status),
headers={"expires": str(int((15 + time.time()) * 1000))},
) | python | {
"resource": ""
} |
q17424 | DevMan.register_device | train | def register_device(self, dev_name):
"""register a device to the device list"""
if dev_name not in self.devices:
self.devices.append(dev_name)
group_name = self.system.__dict__[dev_name]._group
if group_name not in self.group.keys():
self.group[group_name] = {} | python | {
"resource": ""
} |
q17425 | DevMan.register_element | train | def register_element(self, dev_name, idx=None):
"""
Register a device element to the group list
Parameters
----------
dev_name : str
model name
idx : str
element idx
Returns
-------
str
assigned idx
"""... | python | {
"resource": ""
} |
q17426 | DevMan.sort_device | train | def sort_device(self):
"""
Sort device to follow the order of initialization
:return: None
"""
self.devices.sort()
# idx: the indices of order-sensitive models
# names: an ordered list of order-sensitive models
idx = []
names = []
for dev... | python | {
"resource": ""
} |
q17427 | TDS._calc_time_step_first | train | def _calc_time_step_first(self):
"""
Compute the first time step and save to ``self.h``
Returns
-------
None
"""
system = self.system
config = self.config
if not system.dae.n:
freq = 1.0
elif system.dae.n == 1:
B =... | python | {
"resource": ""
} |
q17428 | TDS.calc_time_step | train | def calc_time_step(self):
"""
Set the time step during time domain simulations
Parameters
----------
convergence: bool
truth value of the convergence of the last step
niter: int
current iteration count
t: float
current simulati... | python | {
"resource": ""
} |
q17429 | TDS.init | train | def init(self):
"""
Initialize time domain simulation
Returns
-------
None
"""
system = self.system
config = self.config
dae = self.system.dae
if system.pflow.solved is False:
return
t, s = elapsed()
# Assign ... | python | {
"resource": ""
} |
q17430 | TDS.restore_values | train | def restore_values(self):
"""
Restore x, y, and f values if not converged
Returns
-------
None
"""
if self.convergence is True:
return
dae = self.system.dae
system = self.system
inc_g = self.inc[dae.n:dae.m + dae.n]
ma... | python | {
"resource": ""
} |
q17431 | TDS.implicit_step | train | def implicit_step(self):
"""
Integrate one step using trapezoidal method. Sets convergence and niter flags.
Returns
-------
None
"""
config = self.config
system = self.system
dae = self.system.dae
# constant short names
In = spdia... | python | {
"resource": ""
} |
q17432 | TDS.event_actions | train | def event_actions(self):
"""
Take actions for timed events
Returns
-------
None
"""
system = self.system
dae = system.dae
if self.switch:
system.Breaker.apply(self.t)
for item in system.check_event(self.t):
... | python | {
"resource": ""
} |
q17433 | TDS.load_pert | train | def load_pert(self):
"""
Load perturbation files to ``self.callpert``
Returns
-------
None
"""
system = self.system
if system.files.pert:
try:
sys.path.append(system.files.path)
module = importlib.import_module... | python | {
"resource": ""
} |
q17434 | TDS.run_step0 | train | def run_step0(self):
"""
For the 0th step, store the data and stream data
Returns
-------
None
"""
dae = self.system.dae
system = self.system
self.inc = zeros(dae.m + dae.n, 1)
system.varout.store(self.t, self.step)
self.streamin... | python | {
"resource": ""
} |
q17435 | TDS.streaming_step | train | def streaming_step(self):
"""
Sync, handle and streaming for each integration step
Returns
-------
None
"""
system = self.system
if system.config.dime_enable:
system.streaming.sync_and_handle()
system.streaming.vars_to_modules()
... | python | {
"resource": ""
} |
q17436 | TDS.streaming_init | train | def streaming_init(self):
"""
Send out initialization variables and process init from modules
Returns
-------
None
"""
system = self.system
config = self.config
if system.config.dime_enable:
config.compute_flows = True
syst... | python | {
"resource": ""
} |
q17437 | TDS.compute_flows | train | def compute_flows(self):
"""
If enabled, compute the line flows after each step
Returns
-------
None
"""
system = self.system
config = self.config
dae = system.dae
if config.compute_flows:
# compute and append series injection... | python | {
"resource": ""
} |
q17438 | TDS.dump_results | train | def dump_results(self, success):
"""
Dump simulation results to ``dat`` and ``lst`` files
Returns
-------
None
"""
system = self.system
t, _ = elapsed()
if success and (not system.files.no_output):
# system.varout.dump()
... | python | {
"resource": ""
} |
q17439 | de_blank | train | def de_blank(val):
"""Remove blank elements in `val` and return `ret`"""
ret = list(val)
if type(val) == list:
for idx, item in enumerate(val):
if item.strip() == '':
ret.remove(item)
else:
ret[idx] = item.strip()
return ret | python | {
"resource": ""
} |
q17440 | stringfy | train | def stringfy(expr, sym_const=None, sym_states=None, sym_algebs=None):
"""Convert the right-hand-side of an equation into CVXOPT matrix operations"""
if not sym_const:
sym_const = []
if not sym_states:
sym_states = []
if not sym_algebs:
sym_algebs = []
expr_str = []
if typ... | python | {
"resource": ""
} |
q17441 | readadd | train | def readadd(file, system):
"""read DYR file"""
dyr = {}
data = []
end = 0
retval = True
sep = ','
fid = open(file, 'r')
for line in fid.readlines():
if line.find('/') >= 0:
line = line.split('/')[0]
end = 1
if line.find(',') >= 0: # mixed comma a... | python | {
"resource": ""
} |
q17442 | Recipe._sanitize | train | def _sanitize(recipe):
"""Clean up a recipe that may have been stored as serialized json string.
Convert any numerical pointers that are stored as strings to integers."""
recipe = recipe.copy()
for k in list(recipe):
if k not in ("start", "error") and int(k) and k != int(k):
... | python | {
"resource": ""
} |
q17443 | parse_string | train | def parse_string(data, unquote=default_unquote):
"""Decode URL-encoded strings to UTF-8 containing the escaped chars.
"""
if data is None:
return None
# We'll soon need to unquote to recover our UTF-8 data.
# In Python 2, unquote crashes on chars beyond ASCII. So encode functions
# had ... | python | {
"resource": ""
} |
q17444 | parse_value | train | def parse_value(value, allow_spaces=True, unquote=default_unquote):
"Process a cookie value"
if value is None:
return None
value = strip_spaces_and_quotes(value)
value = parse_string(value, unquote=unquote)
if not allow_spaces:
assert ' ' not in value
return value | python | {
"resource": ""
} |
q17445 | valid_name | train | def valid_name(name):
"Validate a cookie name string"
if isinstance(name, bytes):
name = name.decode('ascii')
if not Definitions.COOKIE_NAME_RE.match(name):
return False
# This module doesn't support $identifiers, which are part of an obsolete
# and highly complex standard which is n... | python | {
"resource": ""
} |
q17446 | valid_value | train | def valid_value(value, quote=default_cookie_quote, unquote=default_unquote):
"""Validate a cookie value string.
This is generic across quote/unquote functions because it directly verifies
the encoding round-trip using the specified quote/unquote functions.
So if you use different quote/unquote function... | python | {
"resource": ""
} |
q17447 | valid_date | train | def valid_date(date):
"Validate an expires datetime object"
# We want something that acts like a datetime. In particular,
# strings indicate a failure to parse down to an object and ints are
# nonstandard and ambiguous at best.
if not hasattr(date, 'tzinfo'):
return False
# Relevant RFCs... | python | {
"resource": ""
} |
q17448 | valid_domain | train | def valid_domain(domain):
"Validate a cookie domain ASCII string"
# Using encoding on domain would confuse browsers into not sending cookies.
# Generate UnicodeDecodeError up front if it can't store as ASCII.
domain.encode('ascii')
# Domains starting with periods are not RFC-valid, but this is very ... | python | {
"resource": ""
} |
q17449 | valid_path | train | def valid_path(value):
"Validate a cookie path ASCII string"
# Generate UnicodeDecodeError if path can't store as ASCII.
value.encode("ascii")
# Cookies without leading slash will likely be ignored, raise ASAP.
if not (value and value[0] == "/"):
return False
if not Definitions.PATH_RE.m... | python | {
"resource": ""
} |
q17450 | valid_max_age | train | def valid_max_age(number):
"Validate a cookie Max-Age"
if isinstance(number, basestring):
try:
number = long(number)
except (ValueError, TypeError):
return False
if number >= 0 and number % 1 == 0:
return True
return False | python | {
"resource": ""
} |
q17451 | encode_cookie_value | train | def encode_cookie_value(data, quote=default_cookie_quote):
"""URL-encode strings to make them safe for a cookie value.
By default this uses urllib quoting, as used in many other cookie
implementations and in other Python code, instead of an ad hoc escaping
mechanism which includes backslashes (these al... | python | {
"resource": ""
} |
q17452 | Cookie.from_dict | train | def from_dict(cls, cookie_dict, ignore_bad_attributes=True):
"""Construct an instance from a dict of strings to parse.
The main difference between this and Cookie(name, value, **kwargs) is
that the values in the argument to this method are parsed.
If ignore_bad_attributes=True (default... | python | {
"resource": ""
} |
q17453 | Cookie.from_string | train | def from_string(cls, line, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"Construct a Cookie object from a line of Set-Cookie header data."
cookie_dict = parse_one_response(
line, ignore_bad_cookies=ignore_bad_cookies,
ignore_bad_attributes=ignore_bad... | python | {
"resource": ""
} |
q17454 | Cookie.validate | train | def validate(self, name, value):
"""Validate a cookie attribute with an appropriate validator.
The value comes in already parsed (for example, an expires value
should be a datetime). Called automatically when an attribute
value is set.
"""
validator = self.attribute_vali... | python | {
"resource": ""
} |
q17455 | Cookie.attributes | train | def attributes(self):
"""Export this cookie's attributes as a dict of encoded values.
This is an important part of the code for rendering attributes, e.g.
render_response().
"""
dictionary = {}
# Only look for attributes registered in attribute_names.
for python_... | python | {
"resource": ""
} |
q17456 | Cookies.add | train | def add(self, *args, **kwargs):
"""Add Cookie objects by their names, or create new ones under
specified names.
Any unnamed arguments are interpreted as existing cookies, and
are added under the value in their .name attribute. With keyword
arguments, the key is interpreted as th... | python | {
"resource": ""
} |
q17457 | Cookies.parse_request | train | def parse_request(self, header_data, ignore_bad_cookies=False):
"""Parse 'Cookie' header data into Cookie objects, and add them to
this Cookies object.
:arg header_data: string containing only 'Cookie:' request headers or
header values (as in CGI/WSGI HTTP_COOKIE); if more than one, the... | python | {
"resource": ""
} |
q17458 | Cookies.parse_response | train | def parse_response(self, header_data, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"""Parse 'Set-Cookie' header data into Cookie objects, and add them to
this Cookies object.
:arg header_data: string containing only 'Set-Cookie:' request headers
or their... | python | {
"resource": ""
} |
q17459 | Cookies.from_request | train | def from_request(cls, header_data, ignore_bad_cookies=False):
"Construct a Cookies object from request header data."
cookies = cls()
cookies.parse_request(
header_data, ignore_bad_cookies=ignore_bad_cookies)
return cookies | python | {
"resource": ""
} |
q17460 | Cookies.from_response | train | def from_response(cls, header_data, ignore_bad_cookies=False,
ignore_bad_attributes=True):
"Construct a Cookies object from response header data."
cookies = cls()
cookies.parse_response(
header_data,
ignore_bad_cookies=ignore_bad_cookies,
... | python | {
"resource": ""
} |
q17461 | not0 | train | def not0(a):
"""Return u if u!= 0, return 1 if u == 0"""
return matrix(list(map(lambda x: 1 if x == 0 else x, a)), a.size) | python | {
"resource": ""
} |
q17462 | index | train | def index(m, val):
"""
Return the indices of all the ``val`` in ``m``
"""
mm = np.array(m)
idx_tuple = np.where(mm == val)
idx = idx_tuple[0].tolist()
return idx | python | {
"resource": ""
} |
q17463 | to_number | train | def to_number(s):
"""
Convert a string to a number.
If not successful, return the string without blanks
"""
ret = s
# try converting to float
try:
ret = float(s)
except ValueError:
ret = ret.strip('\'').strip()
# try converting to uid
try:
ret = int(s)
... | python | {
"resource": ""
} |
q17464 | get_config_load_path | train | def get_config_load_path(conf_path=None):
"""
Return config file load path
Priority:
1. conf_path
2. current directory
3. home directory
Parameters
----------
conf_path
Returns
-------
"""
if conf_path is None:
# test ./andes.conf
if o... | python | {
"resource": ""
} |
q17465 | get_log_dir | train | def get_log_dir():
"""
Get a directory for logging
On Linux or macOS, '/tmp/andes' is the default. On Windows,
'%APPDATA%/andes' is the default.
Returns
-------
str
Path to the logging directory
"""
PATH = ''
if platform.system() in ('Linux', 'Darwin'):
PATH = t... | python | {
"resource": ""
} |
q17466 | VarOut.show | train | def show(self):
"""
The representation of an Varout object
:return: the full result matrix (for use with PyCharm viewer)
:rtype: np.array
"""
out = []
for item in self.vars:
out.append(list(item))
return np.array(out) | python | {
"resource": ""
} |
q17467 | VarOut.concat_t_vars | train | def concat_t_vars(self):
"""
Concatenate ``self.t`` with ``self.vars`` and output a single matrix
for data dump
:return matrix: concatenated matrix with ``self.t`` as the 0-th column
"""
logger.warning('This function is deprecated and replaced by `concat_t_vars_np`.')
... | python | {
"resource": ""
} |
q17468 | VarOut.concat_t_vars_np | train | def concat_t_vars_np(self, vars_idx=None):
"""
Concatenate `self.np_t` with `self.np_vars` and return a single matrix.
The first column corresponds to time, and the rest of the matrix is the variables.
Returns
-------
np.array : concatenated matrix
"""
s... | python | {
"resource": ""
} |
q17469 | VarOut.get_xy | train | def get_xy(self, yidx, xidx=0):
"""
Return stored data for the given indices for plot
:param yidx: the indices of the y-axis variables(1-indexing)
:param xidx: the index of the x-axis variables
:return: None
"""
assert isinstance(xidx, int)
if isinstance(... | python | {
"resource": ""
} |
q17470 | VarOut.dump_np_vars | train | def dump_np_vars(self, store_format='csv', delimiter=','):
"""
Dump the TDS simulation data to files by calling subroutines `write_lst` and
`write_np_dat`.
Parameters
-----------
store_format : str
dump format in `('csv', 'txt', 'hdf5')`
delimiter :... | python | {
"resource": ""
} |
q17471 | VarOut.dump | train | def dump(self):
"""
Dump the TDS results to the output `dat` file
:return: succeed flag
"""
logger.warn('This function is deprecated and replaced by `dump_np_vars`.')
ret = False
if self.system.files.no_output:
# return ``True`` because it did not f... | python | {
"resource": ""
} |
q17472 | VarOut.write_np_dat | train | def write_np_dat(self, store_format='csv', delimiter=',', fmt='%.12g'):
"""
Write TDS data stored in `self.np_vars` to the output file
Parameters
----------
store_format : str
dump format in ('csv', 'txt', 'hdf5')
delimiter : str
delimiter for th... | python | {
"resource": ""
} |
q17473 | VarOut.write_lst | train | def write_lst(self):
"""
Dump the variable name lst file
:return: succeed flag
"""
ret = False
out = ''
system = self.system
dae = self.system.dae
varname = self.system.varname
template = '{:>6g}, {:>25s}, {:>35s}\n'
# header lin... | python | {
"resource": ""
} |
q17474 | VarOut.vars_to_array | train | def vars_to_array(self):
"""
Convert `self.vars` to a numpy array
Returns
-------
numpy.array
"""
logger.warn('This function is deprecated. You can inspect `self.np_vars` directly as NumPy arrays '
'without conversion.')
if not self.v... | python | {
"resource": ""
} |
q17475 | preamble | train | def preamble():
"""
Log the Andes command-line preamble at the `logging.INFO` level
Returns
-------
None
"""
from . import __version__ as version
logger.info('ANDES {ver} (Build {b}, Python {p} on {os})'
.format(ver=version[:5], b=version[-8:],
p=... | python | {
"resource": ""
} |
q17476 | edit_conf | train | 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 ... | python | {
"resource": ""
} |
q17477 | remove_output | train | 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 f... | python | {
"resource": ""
} |
q17478 | search | train | 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... | python | {
"resource": ""
} |
q17479 | save_config | train | 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 fil... | python | {
"resource": ""
} |
q17480 | Call.setup | train | def setup(self):
"""
setup the call list after case file is parsed and jit models are loaded
"""
self.devices = self.system.devman.devices
self.ndevice = len(self.devices)
self.gcalls = [''] * self.ndevice
self.fcalls = [''] * self.ndevice
self.gycalls = ... | python | {
"resource": ""
} |
q17481 | Call.build_vec | train | def build_vec(self):
"""build call validity vector for each device"""
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... | python | {
"resource": ""
} |
q17482 | Call.build_strings | train | def build_strings(self):
"""build call string for each device"""
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] = hea... | python | {
"resource": ""
} |
q17483 | Call._compile_pfgen | train | def _compile_pfgen(self):
"""Post power flow computation for PV and SW"""
string = '"""\n'
string += 'system.dae.init_g()\n'
for gcall, pflow, shunt, series, stagen, call in zip(
self.gcall, self.pflow, self.shunt, self.series, self.stagen,
self.gcalls):
... | python | {
"resource": ""
} |
q17484 | Call._compile_bus_injection | train | def _compile_bus_injection(self):
"""Impose injections on buses"""
string = '"""\n'
for device, series in zip(self.devices, self.series):
if series:
string += 'system.' + device + '.gcall(system.dae)\n'
string += '\n'
string += 'system.dae.reset_small_... | python | {
"resource": ""
} |
q17485 | Call._compile_seriesflow | train | def _compile_seriesflow(self):
"""Post power flow computation of series device flow"""
string = '"""\n'
for device, pflow, series in zip(self.devices, self.pflow,
self.series):
if pflow and series:
string += 'system.' + device ... | python | {
"resource": ""
} |
q17486 | Call._compile_int_f | train | def _compile_int_f(self):
"""Time Domain Simulation - update differential equations"""
string = '"""\n'
string += 'system.dae.init_f()\n'
# evaluate differential equations f
for fcall, call in zip(self.fcall, self.fcalls):
if fcall:
string += call
... | python | {
"resource": ""
} |
q17487 | Call._compile_int_g | train | def _compile_int_g(self):
"""Time Domain Simulation - update algebraic equations and Jacobian"""
string = '"""\n'
# evaluate the algebraic equations g
string += 'system.dae.init_g()\n'
for gcall, call in zip(self.gcall, self.gcalls):
if gcall:
string ... | python | {
"resource": ""
} |
q17488 | ModelBase._init | train | def _init(self):
"""
Convert model metadata to class attributes.
This function is called automatically after ``define()`` in new
versions.
:return: None
"""
assert self._name
assert self._group
# self.n = 0
self.u = []
self.name ... | python | {
"resource": ""
} |
q17489 | ModelBase.param_define | train | def param_define(self,
param,
default,
unit='',
descr='',
tomatrix=True,
nonzero=False,
mandatory=False,
power=False,
voltage=False... | python | {
"resource": ""
} |
q17490 | ModelBase.var_define | train | 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 ... | python | {
"resource": ""
} |
q17491 | ModelBase.service_define | train | 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
"""
assert service not in self._data
assert service not in self._algebs + self._s... | python | {
"resource": ""
} |
q17492 | ModelBase.get_uid | train | 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
"""
assert idx is not None
if isinstance(idx, (int, float, str)):
ret... | python | {
"resource": ""
} |
q17493 | ModelBase.get_field | train | 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: ... | python | {
"resource": ""
} |
q17494 | ModelBase._alloc | train | def _alloc(self):
"""
Allocate empty memory for dae variable indices.
Called in device setup phase.
:return: None
"""
nzeros = [0] * self.n
for var in self._states:
self.__dict__[var] = nzeros[:]
for var in self._algebs:
self.__dic... | python | {
"resource": ""
} |
q17495 | ModelBase.data_to_dict | train | 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
"... | python | {
"resource": ""
} |
q17496 | ModelBase.data_to_list | train | 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
"""
ret = list()
# for each elem... | python | {
"resource": ""
} |
q17497 | ModelBase.data_from_dict | train | def data_from_dict(self, data):
"""
Populate model parameters from a dictionary of parameters
Parameters
----------
data : dict
List of parameter dictionaries
Returns
-------
None
"""
nvars = []
for key, val in data.i... | python | {
"resource": ""
} |
q17498 | ModelBase.var_to_df | train | def var_to_df(self):
"""
Return the current var_to_df of variables
:return: pandas.DataFrame
"""
ret = {}
self._check_pd()
if self._flags['address'] is False:
return pd.DataFrame.from_dict(ret)
ret.update({'name': self.name})
ret.upd... | python | {
"resource": ""
} |
q17499 | ModelBase.param_remove | train | 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
"""
for attr in self._param_attr_dicts:
if param in self.__dict__[attr]:
self.__dict__[attr].po... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.