_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q17600 | RtmBot.get_userid_from_botid | train | def get_userid_from_botid(self, botid):
'''Perform a lookup of bots.info to resolve a botid to a userid
Args:
botid (string): Slack botid to lookup.
Returns:
string: userid value
'''
botinfo = self.slack_client.api_call('bots.info', bot=botid)
if ... | python | {
"resource": ""
} |
q17601 | RtmBot._parse_metadata | train | def _parse_metadata(self, message):
'''Parse incoming messages to build metadata dict
Lots of 'if' statements. It sucks, I know.
Args:
message (dict): JSON dump of message sent from Slack
Returns:
Legobot.Metadata
'''
# Try to handle all the fie... | python | {
"resource": ""
} |
q17602 | Slack.build_attachment | train | def build_attachment(self, text, target, attachment, thread):
'''Builds a slack attachment.
Args:
message (Legobot.Message): message w/ metadata to send.
Returns:
attachment (dict): attachment data.
'''
attachment = {
'as_user': True,
... | python | {
"resource": ""
} |
q17603 | guess | train | def guess(system):
"""
input format guess function. First guess by extension, then test by lines
"""
files = system.files
maybe = []
if files.input_format:
maybe.append(files.input_format)
# first, guess by extension
for key, val in input_formats.items():
if type(val) == ... | python | {
"resource": ""
} |
q17604 | parse | train | def parse(system):
"""
Parse input file with the given format in system.files.input_format
"""
t, _ = elapsed()
input_format = system.files.input_format
add_format = system.files.add_format
# exit when no input format is given
if not input_format:
logger.error(
'No ... | python | {
"resource": ""
} |
q17605 | EIG.calc_state_matrix | train | def calc_state_matrix(self):
"""
Return state matrix and store to ``self.As``
Returns
-------
matrix
state matrix
"""
system = self.system
Gyx = matrix(system.dae.Gx)
self.solver.linsolve(system.dae.Gy, Gyx)
self.As = matrix(... | python | {
"resource": ""
} |
q17606 | EIG.calc_eigvals | train | def calc_eigvals(self):
"""
Solve eigenvalues of the state matrix ``self.As``
Returns
-------
None
"""
self.eigs = numpy.linalg.eigvals(self.As)
# TODO: use scipy.sparse.linalg.eigs(self.As)
return self.eigs | python | {
"resource": ""
} |
q17607 | EIG.calc_part_factor | train | def calc_part_factor(self):
"""
Compute participation factor of states in eigenvalues
Returns
-------
"""
mu, N = numpy.linalg.eig(self.As)
# TODO: use scipy.sparse.linalg.eigs(self.As)
N = matrix(N)
n = len(mu)
idx = range(n)
W... | python | {
"resource": ""
} |
q17608 | Breaker.get_times | train | def get_times(self):
"""Return all the action times and times-1e-6 in a list"""
if not self.n:
return []
self.times = list(mul(self.u1, self.t1)) + \
list(mul(self.u2, self.t2)) + \
list(mul(self.u3, self.t3)) + \
list(mul(self.u4, self.t4))
... | python | {
"resource": ""
} |
q17609 | Heartbeat.send | train | def send(self, ws, seq):
"""
Sends heartbeat message to Discord
Attributes:
ws: Websocket connection to discord
seq: Sequence number of heartbeat
"""
payload = {'op': 1, 'd': seq}
payload = json.dumps(payload)
logger.debug("Sending heartb... | python | {
"resource": ""
} |
q17610 | DiscoBot.create_message | train | def create_message(self, channel_id, text):
"""
Sends a message to a Discord channel or user via REST API
Args:
channel_id (string): ID of destingation Discord channel
text (string): Content of message
"""
baseurl = self.rest_baseurl + \
'/ch... | python | {
"resource": ""
} |
q17611 | DiscoBot.identify | train | def identify(self, token):
"""
Identifies to the websocket endpoint
Args:
token (string): Discord bot token
"""
payload = {
'op': 2,
'd': {
'token': self.token,
'properties': {
'$os': sys.pl... | python | {
"resource": ""
} |
q17612 | DiscoBot.on_hello | train | def on_hello(self, message):
"""
Runs on a hello event from websocket connection
Args:
message (dict): Full message from Discord websocket connection"
"""
logger.info("Got a hello")
self.identify(self.token)
self.heartbeat_thread = Heartbeat(self.ws,... | python | {
"resource": ""
} |
q17613 | DiscoBot.on_heartbeat | train | def on_heartbeat(self, message):
"""
Runs on a heartbeat event from websocket connection
Args:
message (dict): Full message from Discord websocket connection"
"""
logger.info("Got a heartbeat")
logger.info("Heartbeat message: {}".format(message))
sel... | python | {
"resource": ""
} |
q17614 | DiscoBot.on_message | train | def on_message(self, message):
"""
Runs on a create_message event from websocket connection
Args:
message (dict): Full message from Discord websocket connection"
"""
if 'content' in message['d']:
metadata = self._parse_metadata(message)
messa... | python | {
"resource": ""
} |
q17615 | DiscoBot._parse_metadata | train | def _parse_metadata(self, message):
"""
Sets metadata in Legobot message
Args:
message (dict): Full message from Discord websocket connection"
Returns:
Legobot.Metadata
"""
metadata = Metadata(source=self.actor_urn).__dict__
if 'author' ... | python | {
"resource": ""
} |
q17616 | DiscoBot.handle | train | def handle(self, message):
"""
Dispatches messages to appropriate handler based on opcode
Args:
message (dict): Full message from Discord websocket connection
"""
opcode = message['op']
if opcode == 10:
self.on_hello(message)
elif opcode ... | python | {
"resource": ""
} |
q17617 | DAE.resize | train | def resize(self):
"""Resize dae and and extend for init1 variables
"""
yext = self.m - len(self.y)
xext = self.n - len(self.x)
if yext > 0:
yzeros = zeros(yext, 1)
yones = ones(yext, 1)
self.y = matrix([self.y, yzeros], (self.m, 1), 'd')
... | python | {
"resource": ""
} |
q17618 | DAE.hard_limit | train | def hard_limit(self, yidx, ymin, ymax, min_set=None, max_set=None):
"""Set hard limits for algebraic variables and reset the equation mismatches
:param yidx: algebraic variable indices
:param ymin: lower limit to check for
:param ymax: upper limit to check for
:param min_set: op... | python | {
"resource": ""
} |
q17619 | DAE.hard_limit_remote | train | def hard_limit_remote(self,
yidx,
ridx,
rtype='y',
rmin=None,
rmax=None,
min_yset=0,
max_yset=0):
"""Limit the output of yidx if t... | python | {
"resource": ""
} |
q17620 | DAE.anti_windup | train | def anti_windup(self, xidx, xmin, xmax):
"""
Anti-windup limiter for state variables.
Resets the limited variables and differential equations.
:param xidx: state variable indices
:param xmin: lower limit
:param xmax: upper limit
:type xidx: matrix, list
... | python | {
"resource": ""
} |
q17621 | DAE.reset_Ac | train | def reset_Ac(self):
"""
Reset ``dae.Ac`` sparse matrix for disabled equations
due to hard_limit and anti_windup limiters.
:return: None
"""
if self.ac_reset is False:
return
mn = self.m + self.n
x = index(aandb(self.zxmin, self.zxmax), 0.)
... | python | {
"resource": ""
} |
q17622 | DAE.get_size | train | def get_size(self, m):
"""
Return the 2-D size of a Jacobian matrix in tuple
"""
nrow, ncol = 0, 0
if m[0] == 'F':
nrow = self.n
elif m[0] == 'G':
nrow = self.m
if m[1] == 'x':
ncol = self.n
elif m[1] == 'y':
... | python | {
"resource": ""
} |
q17623 | DAE.temp_to_spmatrix | train | def temp_to_spmatrix(self, ty):
"""
Convert Jacobian tuples to matrices
:param ty: name of the matrices to convert in ``('jac0','jac')``
:return: None
"""
assert ty in ('jac0', 'jac')
jac0s = ['Fx0', 'Fy0', 'Gx0', 'Gy0']
jacs = ['Fx', 'Fy', 'Gx', 'Gy']
... | python | {
"resource": ""
} |
q17624 | DAE.apply_set | train | def apply_set(self, ty):
"""
Apply Jacobian set values to matrices
:param ty: Jacobian type in ``('jac0', 'jac')``
:return:
"""
assert ty in ('jac0', 'jac')
if ty == 'jac0':
todo = ['Fx0', 'Fy0', 'Gx0', 'Gy0']
else:
todo = ['Fx', ... | python | {
"resource": ""
} |
q17625 | DAE.show | train | def show(self, eq, value=None):
"""Show equation or variable array along with the names"""
if eq in ['f', 'x']:
key = 'unamex'
elif eq in ['g', 'y']:
key = 'unamey'
if value:
value = list(value)
else:
value = list(self.__dict__[eq]... | python | {
"resource": ""
} |
q17626 | DAE.find_val | train | def find_val(self, eq, val):
"""Return the name of the equation having the given value"""
if eq not in ('f', 'g', 'q'):
return
elif eq in ('f', 'q'):
key = 'unamex'
elif eq == 'g':
key = 'unamey'
idx = 0
for m, n in zip(self.system.varn... | python | {
"resource": ""
} |
q17627 | DAE.reset_small | train | def reset_small(self, eq):
"""Reset numbers smaller than 1e-12 in f and g equations"""
assert eq in ('f', 'g')
for idx, var in enumerate(self.__dict__[eq]):
if abs(var) <= 1e-12:
self.__dict__[eq][idx] = 0 | python | {
"resource": ""
} |
q17628 | DAE.check_diag | train | def check_diag(self, jac, name):
"""
Check matrix ``jac`` for diagonal elements that equals 0
"""
system = self.system
pos = []
names = []
pairs = ''
size = jac.size
diag = jac[0:size[0] ** 2:size[0] + 1]
for idx in range(size[0]):
... | python | {
"resource": ""
} |
q17629 | get_exception_source | train | def get_exception_source():
"""Returns full file path, file name, line number, function name, and line contents
causing the last exception."""
_, _, tb = sys.exc_info()
while tb.tb_next:
tb = tb.tb_next
f = tb.tb_frame
lineno = tb.tb_lineno
co = f.f_code
filefullpath = co.co_file... | python | {
"resource": ""
} |
q17630 | CallbackHandler.prepare | train | def prepare(self, record):
# Function taken from Python 3.6 QueueHandler
"""
Prepares a record for queuing. The object returned by this method is
enqueued.
The base implementation formats the record to merge the message
and arguments, and removes unpickleable items from t... | python | {
"resource": ""
} |
q17631 | CallbackHandler.emit | train | def emit(self, record):
"""Send a LogRecord to the callback function, after preparing it
for serialization."""
try:
self._callback(self.prepare(record))
except Exception:
self.handleError(record) | python | {
"resource": ""
} |
q17632 | Frontend.run | train | def run(self):
"""The main loop of the frontend. Here incoming messages from the service
are processed and forwarded to the corresponding callback methods."""
self.log.debug("Entered main loop")
while not self.shutdown:
# If no service is running slow down the main loop
... | python | {
"resource": ""
} |
q17633 | Frontend.send_command | train | def send_command(self, command):
"""Send command to service via the command queue."""
if self._pipe_commands:
self._pipe_commands.send(command)
else:
if self.shutdown:
# Stop delivering messages in shutdown.
self.log.info(
... | python | {
"resource": ""
} |
q17634 | Frontend.process_transport_command | train | def process_transport_command(self, header, message):
"""Parse a command coming in through the transport command subscription"""
if not isinstance(message, dict):
return
relevant = False
if "host" in message: # Filter by host
if message["host"] != self.__hostid:... | python | {
"resource": ""
} |
q17635 | Frontend.parse_band_log | train | def parse_band_log(self, message):
"""Process incoming logging messages from the service."""
if "payload" in message and hasattr(message["payload"], "name"):
record = message["payload"]
for k in dir(record):
if k.startswith("workflows_exc_"):
s... | python | {
"resource": ""
} |
q17636 | Frontend.parse_band_request_termination | train | def parse_band_request_termination(self, message):
"""Service declares it should be terminated."""
self.log.debug("Service requests termination")
self._terminate_service()
if not self.restart_service:
self.shutdown = True | python | {
"resource": ""
} |
q17637 | Frontend.parse_band_set_name | train | def parse_band_set_name(self, message):
"""Process incoming message indicating service name change."""
if message.get("name"):
self._service_name = message["name"]
else:
self.log.warning(
"Received broken record on set_name band\nMessage: %s", str(message)... | python | {
"resource": ""
} |
q17638 | Frontend.parse_band_status_update | train | def parse_band_status_update(self, message):
"""Process incoming status updates from the service."""
self.log.debug("Status update: " + str(message))
self.update_status(status_code=message["statuscode"]) | python | {
"resource": ""
} |
q17639 | Frontend.get_status | train | def get_status(self):
"""Returns a dictionary containing all relevant status information to be
broadcast across the network."""
return {
"host": self.__hostid,
"status": self._service_status_announced,
"statustext": CommonService.human_readable_state.get(
... | python | {
"resource": ""
} |
q17640 | Frontend.exponential_backoff | train | def exponential_backoff(self):
"""A function that keeps waiting longer and longer the more rapidly it is called.
It can be used to increasingly slow down service starts when they keep failing."""
last_service_switch = self._service_starttime
if not last_service_switch:
return... | python | {
"resource": ""
} |
q17641 | Frontend._terminate_service | train | def _terminate_service(self):
"""Force termination of running service.
Disconnect queues, end queue feeder threads.
Wait for service process to clear, drop all references."""
with self.__lock:
if self._service:
self._service.terminate()
if self._pi... | python | {
"resource": ""
} |
q17642 | Solver.symbolic | train | def symbolic(self, A):
"""
Return the symbolic factorization of sparse matrix ``A``
Parameters
----------
sparselib
Library name in ``umfpack`` and ``klu``
A
Sparse matrix
Returns
symbolic factorization
-------
""... | python | {
"resource": ""
} |
q17643 | Solver.numeric | train | def numeric(self, A, F):
"""
Return the numeric factorization of sparse matrix ``A`` using symbolic factorization ``F``
Parameters
----------
A
Sparse matrix
F
Symbolic factorization
Returns
-------
N
Numeric f... | python | {
"resource": ""
} |
q17644 | Solver.solve | train | def solve(self, A, F, N, b):
"""
Solve linear system ``Ax = b`` using numeric factorization ``N`` and symbolic factorization ``F``.
Store the solution in ``b``.
Parameters
----------
A
Sparse matrix
F
Symbolic factorization
N
... | python | {
"resource": ""
} |
q17645 | Solver.linsolve | train | def linsolve(self, A, b):
"""
Solve linear equation set ``Ax = b`` and store the solutions in ``b``.
Parameters
----------
A
Sparse matrix
b
RHS of the equation
Returns
-------
None
"""
if self.sparselib =... | python | {
"resource": ""
} |
q17646 | Bus._varname_inj | train | def _varname_inj(self):
"""Customize varname for bus injections"""
# Bus Pi
if not self.n:
return
m = self.system.dae.m
xy_idx = range(m, self.n + m)
self.system.varname.append(
listname='unamey',
xy_idx=xy_idx,
var_name='P'... | python | {
"resource": ""
} |
q17647 | Bus.init0 | train | def init0(self, dae):
"""Set bus Va and Vm initial values"""
if not self.system.pflow.config.flatstart:
dae.y[self.a] = self.angle + 1e-10 * uniform(self.n)
dae.y[self.v] = self.voltage
else:
dae.y[self.a] = matrix(0.0,
(self... | python | {
"resource": ""
} |
q17648 | get_known_transports | train | def get_known_transports():
"""Return a dictionary of all known transport mechanisms."""
if not hasattr(get_known_transports, "cache"):
setattr(
get_known_transports,
"cache",
{
e.name: e.load()
for e in pkg_resources.iter_entry_points(... | python | {
"resource": ""
} |
q17649 | WindBase.windspeed | train | def windspeed(self, t):
"""Return the wind speed list at time `t`"""
ws = [0] * self.n
for i in range(self.n):
q = ceil(t / self.dt[i])
q_prev = 0 if q == 0 else q - 1
r = t % self.dt[i]
r = 0 if abs(r) < 1e-6 else r
if r == 0:
... | python | {
"resource": ""
} |
q17650 | PowerSystem.to_sysbase | train | def to_sysbase(self):
"""
Convert model parameters to system base. This function calls the
``data_to_sys_base`` function of the loaded models.
Returns
-------
None
"""
if self.config.base:
for item in self.devman.devices:
self.... | python | {
"resource": ""
} |
q17651 | PowerSystem.to_elembase | train | def to_elembase(self):
"""
Convert parameters back to element base. This function calls the
```data_to_elem_base``` function.
Returns
-------
None
"""
if self.config.base:
for item in self.devman.devices:
self.__dict__[item].da... | python | {
"resource": ""
} |
q17652 | PowerSystem.group_add | train | def group_add(self, name='Ungrouped'):
"""
Dynamically add a group instance to the system if not exist.
Parameters
----------
name : str, optional ('Ungrouped' as default)
Name of the group
Returns
-------
None
"""
if not hasa... | python | {
"resource": ""
} |
q17653 | PowerSystem.model_import | train | def model_import(self):
"""
Import and instantiate the non-JIT models and the JIT models.
Models defined in ``jits`` and ``non_jits`` in ``models/__init__.py``
will be imported and instantiated accordingly.
Returns
-------
None
"""
# non-JIT mode... | python | {
"resource": ""
} |
q17654 | PowerSystem.model_setup | train | def model_setup(self):
"""
Call the ``setup`` function of the loaded models. This function is
to be called after parsing all the data files during the system set up.
Returns
-------
None
"""
for device in self.devman.devices:
if self.__dict__[... | python | {
"resource": ""
} |
q17655 | PowerSystem.xy_addr0 | train | def xy_addr0(self):
"""
Assign indicies and variable names for variables used in power flow
For each loaded model with the ``pflow`` flag as ``True``, the following
functions are called sequentially:
* ``_addr()``
* ``_intf_network()``
* ``_intf_ctrl()``
... | python | {
"resource": ""
} |
q17656 | PowerSystem.rmgen | train | def rmgen(self, idx):
"""
Remove the static generators if their dynamic models exist
Parameters
----------
idx : list
A list of static generator idx
Returns
-------
None
"""
stagens = []
for device, stagen in zip(self.d... | python | {
"resource": ""
} |
q17657 | PowerSystem.check_event | train | def check_event(self, sim_time):
"""
Check for event occurrance for``Event`` group models at ``sim_time``
Parameters
----------
sim_time : float
The current simulation time
Returns
-------
list
A list of model names who report (an... | python | {
"resource": ""
} |
q17658 | PowerSystem.get_event_times | train | def get_event_times(self):
"""
Return event times of Fault, Breaker and other timed events
Returns
-------
list
A sorted list of event times
"""
times = []
times.extend(self.Breaker.get_times())
for model in self.__dict__['Event'].al... | python | {
"resource": ""
} |
q17659 | PowerSystem.load_config | train | def load_config(self, conf_path):
"""
Load config from an ``andes.conf`` file.
This function creates a ``configparser.ConfigParser`` object to read
the specified conf file and calls the ``load_config`` function of the
config instances of the system and the routines.
Par... | python | {
"resource": ""
} |
q17660 | PowerSystem.dump_config | train | def dump_config(self, file_path):
"""
Dump system and routine configurations to an rc-formatted file.
Parameters
----------
file_path : str
path to the configuration file. The user will be prompted if the
file already exists.
Returns
----... | python | {
"resource": ""
} |
q17661 | PowerSystem.check_islands | train | def check_islands(self, show_info=False):
"""
Check the connectivity for the ac system
Parameters
----------
show_info : bool
Show information when the system has islands. To be used when
initializing power flow.
Returns
-------
N... | python | {
"resource": ""
} |
q17662 | PowerSystem.get_busdata | train | def get_busdata(self, sort_names=False):
"""
get ac bus data from solved power flow
"""
if self.pflow.solved is False:
logger.error('Power flow not solved when getting bus data.')
return tuple([False] * 8)
idx = self.Bus.idx
names = self.Bus.name
... | python | {
"resource": ""
} |
q17663 | PowerSystem.get_nodedata | train | def get_nodedata(self, sort_names=False):
"""
get dc node data from solved power flow
"""
if not self.Node.n:
return
if not self.pflow.solved:
logger.error('Power flow not solved when getting bus data.')
return tuple([False] * 7)
idx = ... | python | {
"resource": ""
} |
q17664 | PowerSystem.get_linedata | train | def get_linedata(self, sort_names=False):
"""
get line data from solved power flow
"""
if not self.pflow.solved:
logger.error('Power flow not solved when getting line data.')
return tuple([False] * 7)
idx = self.Line.idx
fr = self.Line.bus1
... | python | {
"resource": ""
} |
q17665 | Group.register_model | train | def register_model(self, model):
"""
Register ``model`` to this group
:param model: model name
:return: None
"""
assert isinstance(model, str)
if model not in self.all_models:
self.all_models.append(model) | python | {
"resource": ""
} |
q17666 | Group.register_element | train | def register_element(self, model, idx):
"""
Register element with index ``idx`` to ``model``
:param model: model name
:param idx: element idx
:return: final element idx
"""
if idx is None:
idx = model + '_' + str(len(self._idx_model))
self._... | python | {
"resource": ""
} |
q17667 | Group.get_field | train | def get_field(self, field, idx):
"""
Return the field ``field`` of elements ``idx`` in the group
:param field: field name
:param idx: element idx
:return: values of the requested field
"""
ret = []
scalar = False
# TODO: ensure idx is unique in t... | python | {
"resource": ""
} |
q17668 | Group.set_field | train | def set_field(self, field, idx, value):
"""
Set the field ``field`` of elements ``idx`` to ``value``.
This function does not if the field is valid for all models.
:param field: field name
:param idx: element idx
:param value: value of fields to set
:return: None... | python | {
"resource": ""
} |
q17669 | get_sort_field | train | def get_sort_field(request):
"""
Retrieve field used for sorting a queryset
:param request: HTTP request
:return: the sorted field name, prefixed with "-" if ordering is descending
"""
sort_direction = request.GET.get("dir")
field_name = (request.GET.get("sort") or "") if sort_direction els... | python | {
"resource": ""
} |
q17670 | MediaWiki.normalize_api_url | train | def normalize_api_url(self):
"""
Checks that the API URL used to initialize this object actually returns
JSON. If it doesn't, make some educated guesses and try to find the
correct URL.
:returns: a valid API URL or ``None``
"""
def tester(self, api_url):
... | python | {
"resource": ""
} |
q17671 | build | train | def build(
documentPath,
outputUFOFormatVersion=3,
roundGeometry=True,
verbose=True, # not supported
logPath=None, # not supported
progressFunc=None, # not supported
processRules=True,
logger=None,
useVarlib=False,
... | python | {
"resource": ""
} |
q17672 | DesignSpaceProcessor.getInfoMutator | train | def getInfoMutator(self):
""" Returns a info mutator """
if self._infoMutator:
return self._infoMutator
infoItems = []
for sourceDescriptor in self.sources:
if sourceDescriptor.layerName is not None:
continue
loc = Location(sourceDescri... | python | {
"resource": ""
} |
q17673 | DesignSpaceProcessor.collectMastersForGlyph | train | def collectMastersForGlyph(self, glyphName, decomposeComponents=False):
""" Return a glyph mutator.defaultLoc
decomposeComponents = True causes the source glyphs to be decomposed first
before building the mutator. That gives you instances that do not depend
on a complete font... | python | {
"resource": ""
} |
q17674 | checkGlyphIsEmpty | train | def checkGlyphIsEmpty(glyph, allowWhiteSpace=True):
"""
This will establish if the glyph is completely empty by drawing the glyph with an EmptyPen.
Additionally, the unicode of the glyph is checked against a list of known unicode whitespace
characters. This makes it possible to filter out gl... | python | {
"resource": ""
} |
q17675 | SimulationRunner.configure_and_build | train | def configure_and_build(self, show_progress=True, optimized=True,
skip_configuration=False):
"""
Configure and build the ns-3 code.
Args:
show_progress (bool): whether or not to display a progress bar
during compilation.
optimi... | python | {
"resource": ""
} |
q17676 | SimulationRunner.get_build_output | train | def get_build_output(self, process):
"""
Parse the output of the ns-3 build process to extract the information
that is needed to draw the progress bar.
Args:
process: the subprocess instance to listen to.
"""
while True:
output = process.stdout.r... | python | {
"resource": ""
} |
q17677 | SimulationRunner.run_simulations | train | def run_simulations(self, parameter_list, data_folder):
"""
Run several simulations using a certain combination of parameters.
Yields results as simulations are completed.
Args:
parameter_list (list): list of parameter combinations to simulate.
data_folder (str)... | python | {
"resource": ""
} |
q17678 | list_param_combinations | train | def list_param_combinations(param_ranges):
"""
Create a list of all parameter combinations from a dictionary specifying
desired parameter values as lists.
Example:
>>> param_ranges = {'a': [1], 'b': [2, 3]}
>>> list_param_combinations(param_ranges)
[{'a': 1, 'b': 2}, {'a': 1, '... | python | {
"resource": ""
} |
q17679 | get_command_from_result | train | def get_command_from_result(script, result, debug=False):
"""
Return the command that is needed to obtain a certain result.
Args:
params (dict): Dictionary containing parameter: value pairs.
debug (bool): Whether the command should include the debugging
template.
"""
if ... | python | {
"resource": ""
} |
q17680 | automatic_parser | train | def automatic_parser(result, dtypes={}, converters={}):
"""
Try and automatically convert strings formatted as tables into nested
list structures.
Under the hood, this function essentially applies the genfromtxt function
to all files in the output, and passes it the additional kwargs.
Args:
... | python | {
"resource": ""
} |
q17681 | CampaignManager.new | train | def new(cls, ns_path, script, campaign_dir, runner_type='Auto',
overwrite=False, optimized=True, check_repo=True):
"""
Create a new campaign from an ns-3 installation and a campaign
directory.
This method will create a DatabaseManager, which will install a
database i... | python | {
"resource": ""
} |
q17682 | CampaignManager.load | train | def load(cls, campaign_dir, ns_path=None, runner_type='Auto',
optimized=True, check_repo=True):
"""
Load an existing simulation campaign.
Note that specifying an ns-3 installation is not compulsory when using
this method: existing results will be available, but in order to ... | python | {
"resource": ""
} |
q17683 | CampaignManager.create_runner | train | def create_runner(ns_path, script, runner_type='Auto',
optimized=True):
"""
Create a SimulationRunner from a string containing the desired
class implementation, and return it.
Args:
ns_path (str): path to the ns-3 installation to employ in this
... | python | {
"resource": ""
} |
q17684 | CampaignManager.run_simulations | train | def run_simulations(self, param_list, show_progress=True):
"""
Run several simulations specified by a list of parameter combinations.
Note: this function does not verify whether we already have the
required simulations in the database - it just runs all the parameter
combination... | python | {
"resource": ""
} |
q17685 | CampaignManager.get_missing_simulations | train | def get_missing_simulations(self, param_list, runs=None):
"""
Return a list of the simulations among the required ones that are not
available in the database.
Args:
param_list (list): a list of dictionaries containing all the
parameters combinations.
... | python | {
"resource": ""
} |
q17686 | CampaignManager.run_missing_simulations | train | def run_missing_simulations(self, param_list, runs=None):
"""
Run the simulations from the parameter list that are not yet available
in the database.
This function also makes sure that we have at least runs replications
for each parameter combination.
Additionally, para... | python | {
"resource": ""
} |
q17687 | CampaignManager.get_results_as_numpy_array | train | def get_results_as_numpy_array(self, parameter_space,
result_parsing_function, runs):
"""
Return the results relative to the desired parameter space in the form
of a numpy array.
Args:
parameter_space (dict): dictionary containing
... | python | {
"resource": ""
} |
q17688 | CampaignManager.save_to_mat_file | train | def save_to_mat_file(self, parameter_space,
result_parsing_function,
filename, runs):
"""
Return the results relative to the desired parameter space in the form
of a .mat file.
Args:
parameter_space (dict): dictionary contain... | python | {
"resource": ""
} |
q17689 | CampaignManager.save_to_npy_file | train | def save_to_npy_file(self, parameter_space,
result_parsing_function,
filename, runs):
"""
Save results to a numpy array file format.
"""
np.save(filename, self.get_results_as_numpy_array(
parameter_space, result_parsing_functi... | python | {
"resource": ""
} |
q17690 | CampaignManager.save_to_folders | train | def save_to_folders(self, parameter_space, folder_name, runs):
"""
Save results to a folder structure.
"""
self.space_to_folders(self.db.get_results(), {}, parameter_space, runs,
folder_name) | python | {
"resource": ""
} |
q17691 | CampaignManager.space_to_folders | train | def space_to_folders(self, current_result_list, current_query, param_space,
runs, current_directory):
"""
Convert a parameter space specification to a directory tree with a
nested structure.
"""
# Base case: we iterate over the runs and copy files in the ... | python | {
"resource": ""
} |
q17692 | CampaignManager.get_results_as_xarray | train | def get_results_as_xarray(self, parameter_space,
result_parsing_function,
output_labels, runs):
"""
Return the results relative to the desired parameter space in the form
of an xarray data structure.
Args:
parameter... | python | {
"resource": ""
} |
q17693 | run | train | def run(ns_3_path, results_dir, script, no_optimization, parameters,
max_processes):
"""
Run multiple simulations.
"""
sem.parallelrunner.MAX_PARALLEL_PROCESSES = max_processes
# Create a campaign
campaign = sem.CampaignManager.new(ns_3_path,
scri... | python | {
"resource": ""
} |
q17694 | view | train | def view(results_dir, result_id, hide_simulation_output, parameters, no_pager):
"""
View results of simulations.
"""
campaign = sem.CampaignManager.load(results_dir)
# Pick the most appropriate function based on the level of detail we want
if hide_simulation_output:
get_results_functio... | python | {
"resource": ""
} |
q17695 | command | train | def command(results_dir, result_id):
"""
Print the command that needs to be used to reproduce a result.
"""
campaign = sem.CampaignManager.load(results_dir)
result = campaign.db.get_results(result_id=result_id)[0]
click.echo("Simulation command:")
click.echo(sem.utils.get_command_from_resu... | python | {
"resource": ""
} |
q17696 | export | train | def export(results_dir, filename, do_not_try_parsing, parameters):
"""
Export results to file.
An extension in filename is required to deduce the file type. If no
extension is specified, a directory tree export will be used. Note that
this command automatically tries to parse the simulation output.... | python | {
"resource": ""
} |
q17697 | merge | train | def merge(move, output_dir, sources):
"""
Merge multiple results folder into one, by copying the results over to a new folder.
For a faster operation (which on the other hand destroys the campaign data
if interrupted), the move option can be used to directly move results to
the new folder.
"""
... | python | {
"resource": ""
} |
q17698 | query_parameters | train | def query_parameters(param_list, defaults=None):
"""
Asks the user for parameters. If available, proposes some defaults.
Args:
param_list (list): List of parameters to ask the user for values.
defaults (list): A list of proposed defaults. It must be a list of the
same length as ... | python | {
"resource": ""
} |
q17699 | import_parameters_from_file | train | def import_parameters_from_file(parameters_file):
"""
Try importing a parameter dictionary from file.
We expect values in parameters_file to be defined as follows:
param1: value1
param2: [value2, value3]
"""
params = {}
with open(parameters_file, 'r') as f:
matches = re... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.