INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Return appropriate parser for given type. | def get_parser(typ):
"""
Return appropriate parser for given type.
:param typ: Type to get parser for.
:return function: Parser
"""
try:
return {
str: parse_str,
bool: parse_bool,
int: parse_int,
tuple: parse_tuple,
list: parse... |
Get and parse prefixed django settings from env. | def get_settings():
"""
Get and parse prefixed django settings from env.
TODO: Implement support for complex settings
DATABASES = {}
CACHES = {}
INSTALLED_APPS -> EXCLUDE_APPS ?
:return dict:
"""
settings = {}
prefix = environ.get("DJANGO_SETTINGS_PREFIX", "DJANGO_"... |
Work - in - progress constructor consuming fields and values from django model instance. | def from_model(cls, model, *fields, **named_fields):
"""
Work-in-progress constructor,
consuming fields and values from django model instance.
"""
d = ModelDict()
if not (fields or named_fields):
# Default to all fields
fields = [f.attname for f i... |
Implementation of Y64 non - standard URL - safe base64 variant. | def y64_encode(s):
"""
Implementation of Y64 non-standard URL-safe base64 variant.
See http://en.wikipedia.org/wiki/Base64#Variants_summary_table
:return: base64-encoded result with substituted
``{"+", "/", "="} => {".", "_", "-"}``.
"""
first_pass = base64.urls... |
Create a field by field info dict. | def create_field(field_info):
"""
Create a field by field info dict.
"""
field_type = field_info.get('type')
if field_type not in FIELDS_NAME_MAP:
raise ValueError(_('not support this field: {}').format(field_type))
field_class = FIELDS_NAME_MAP.get(field_type)
params = dict(field_in... |
create a Validator instance from data_struct_dict | def create_validator(data_struct_dict, name=None):
"""
create a Validator instance from data_struct_dict
:param data_struct_dict: a dict describe validator's fields, like the dict `to_dict()` method returned.
:param name: name of Validator class
:return: Validator instance
"""
if name is... |
Generates a Cartesian product of the input parameter dictionary. | def cartesian_product(parameter_dict, combined_parameters=()):
""" Generates a Cartesian product of the input parameter dictionary.
For example:
>>> print cartesian_product({'param1':[1,2,3], 'param2':[42.0, 52.5]})
{'param1':[1,1,2,2,3,3],'param2': [42.0,52.5,42.0,52.5,42.0,52.5]}
:param paramet... |
Takes a list of explored parameters and finds unique parameter combinations. | def find_unique_points(explored_parameters):
"""Takes a list of explored parameters and finds unique parameter combinations.
If parameter ranges are hashable operates in O(N), otherwise O(N**2).
:param explored_parameters:
List of **explored** parameters
:return:
List of tuples, fir... |
Helper function to turn the simple logging kwargs into a log_config. | def _change_logging_kwargs(kwargs):
""" Helper function to turn the simple logging kwargs into a `log_config`."""
log_levels = kwargs.pop('log_level', None)
log_folder = kwargs.pop('log_folder', 'logs')
logger_names = kwargs.pop('logger_names', '')
if log_levels is None:
log_levels = kwargs.... |
Decorator to allow a simple logging configuration. | def simple_logging_config(func):
"""Decorator to allow a simple logging configuration.
This encompasses giving a `log_folder`, `logger_names` as well as `log_levels`.
"""
@functools.wraps(func)
def new_func(self, *args, **kwargs):
if use_simple_logging(kwargs):
if 'log_config'... |
Tries to make directories for a given filename. | def try_make_dirs(filename):
""" Tries to make directories for a given `filename`.
Ignores any error but notifies via stderr.
"""
try:
dirname = os.path.dirname(os.path.normpath(filename))
racedirs(dirname)
except Exception as exc:
sys.stderr.write('ERROR during log config ... |
Returns all valid python strings inside a given argument string. | def get_strings(args):
"""Returns all valid python strings inside a given argument string."""
string_list = []
for elem in ast.walk(ast.parse(args)):
if isinstance(elem, ast.Str):
string_list.append(elem.s)
return string_list |
Renames a given filename with valid wildcard placements. | def rename_log_file(filename, trajectory=None,
env_name=None,
traj_name=None,
set_name=None,
run_name=None,
process_name=None,
host_name=None):
""" Renames a given `filename` with valid wildcard p... |
Adds a logger with a given name. | def _set_logger(self, name=None):
"""Adds a logger with a given `name`.
If no name is given, name is constructed as
`type(self).__name__`.
"""
if name is None:
cls = self.__class__
name = '%s.%s' % (cls.__module__, cls.__name__)
self._logger = lo... |
Extracts the wildcards and file replacements from the trajectory | def extract_replacements(self, trajectory):
"""Extracts the wildcards and file replacements from the `trajectory`"""
self.env_name = trajectory.v_environment_name
self.traj_name = trajectory.v_name
self.set_name = trajectory.f_wildcard('$set')
self.run_name = trajectory.f_wildca... |
Displays a progressbar | def show_progress(self, n, total_runs):
"""Displays a progressbar"""
if self.report_progress:
percentage, logger_name, log_level = self.report_progress
if logger_name == 'print':
logger = 'print'
else:
logger = logging.getLogger(logger_... |
Searches for parser settings that define filenames. | def _check_and_replace_parser_args(parser, section, option, rename_func, make_dirs=True):
""" Searches for parser settings that define filenames.
If such settings are found, they are renamed according to the wildcard
rules. Moreover, it is also tried to create the corresponding folders.
... |
Turns a ConfigParser into a StringIO stream. | def _parser_to_string_io(parser):
"""Turns a ConfigParser into a StringIO stream."""
memory_file = StringIO()
parser.write(memory_file)
memory_file.flush()
memory_file.seek(0)
return memory_file |
Searches for multiprocessing options within a ConfigParser. | def _find_multiproc_options(parser):
""" Searches for multiprocessing options within a ConfigParser.
If such options are found, they are copied (without the `'multiproc_'` prefix)
into a new parser.
"""
sections = parser.sections()
if not any(section.startswith('multipr... |
Searches for multiprocessing options in a given dictionary. | def _find_multiproc_dict(dictionary):
""" Searches for multiprocessing options in a given `dictionary`.
If found they are copied (without the `'multiproc_'` prefix)
into a new dictionary
"""
if not any(key.startswith('multiproc_') for key in dictionary.keys()):
retu... |
Checks and converts all settings if necessary passed to the Manager. | def check_log_config(self):
""" Checks and converts all settings if necessary passed to the Manager.
Searches for multiprocessing options as well.
"""
if self.report_progress:
if self.report_progress is True:
self.report_progress = (5, 'pypet', logging.INFO)... |
Checks for filenames within a config file and translates them. | def _handle_config_parsing(self, log_config):
""" Checks for filenames within a config file and translates them.
Moreover, directories for the files are created as well.
:param log_config: Config file as a stream (like StringIO)
"""
parser = NoInterpolationParser()
par... |
Recursively walks and copies the log_config dict and searches for filenames. | def _handle_dict_config(self, log_config):
"""Recursively walks and copies the `log_config` dict and searches for filenames.
Translates filenames and creates directories if necessary.
"""
new_dict = dict()
for key in log_config.keys():
if key == 'filename':
... |
Creates logging handlers and redirects stdout. | def make_logging_handlers_and_tools(self, multiproc=False):
"""Creates logging handlers and redirects stdout."""
log_stdout = self.log_stdout
if sys.stdout is self._stdout_to_logger:
# If we already redirected stdout we don't neet to redo it again
log_stdout = False
... |
Finalizes the manager closes and removes all handlers if desired. | def finalize(self, remove_all_handlers=True):
"""Finalizes the manager, closes and removes all handlers if desired."""
for tool in self._tools:
tool.finalize()
self._tools = []
self._stdout_to_logger = None
for config in (self._sp_config, self._mp_config):
... |
Starts redirection of stdout | def start(self):
"""Starts redirection of `stdout`"""
if sys.stdout is not self:
self._original_steam = sys.stdout
sys.stdout = self
self._redirection = True
if self._redirection:
print('Established redirection of `stdout`.') |
Writes data from buffer to logger | def write(self, buf):
"""Writes data from buffer to logger"""
if not self._recursion:
self._recursion = True
try:
for line in buf.rstrip().splitlines():
self._logger.log(self._log_level, line.rstrip())
finally:
self.... |
Disables redirection | def finalize(self):
"""Disables redirection"""
if self._original_steam is not None and self._redirection:
sys.stdout = self._original_steam
print('Disabled redirection of `stdout`.')
self._redirection = False
self._original_steam = None |
Compares two result instances | def results_equal(a, b):
"""Compares two result instances
Checks full name and all data. Does not consider the comment.
:return: True or False
:raises: ValueError if both inputs are no result instances
"""
if a.v_is_parameter and b.v_is_parameter:
raise ValueError('Both inputs are no... |
Compares two parameter instances | def parameters_equal(a, b):
"""Compares two parameter instances
Checks full name, data, and ranges. Does not consider the comment.
:return: True or False
:raises: ValueError if both inputs are no parameter instances
"""
if (not b.v_is_parameter and
not a.v_is_parameter):
... |
Returns an attribute value dictionary much like __dict__ but incorporates __slots__ | def get_all_attributes(instance):
"""Returns an attribute value dictionary much like `__dict__` but incorporates `__slots__`"""
try:
result_dict = instance.__dict__.copy()
except AttributeError:
result_dict = {}
if hasattr(instance, '__all_slots__'):
all_slots = instance.__all_s... |
Compares two objects recursively by their elements. | def nested_equal(a, b):
"""Compares two objects recursively by their elements.
Also handles numpy arrays, pandas data and sparse matrices.
First checks if the data falls into the above categories.
If not, it is checked if a or b are some type of sequence or mapping and
the contained elements are c... |
Can be used to decorate a function as a manual run function. | def manual_run(turn_into_run=True, store_meta_data=True, clean_up=True):
"""Can be used to decorate a function as a manual run function.
This can be helpful if you want the run functionality without using an environment.
:param turn_into_run:
If the trajectory should become a `single run` with mo... |
This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. | def deprecated(msg=''):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used.
:param msg:
Additional message added to the warning.
"""
def wrapper(func):
@functools.wraps(func)
de... |
Decorator: Copy the docstring of fromfunc | def copydoc(fromfunc, sep="\n"):
"""Decorator: Copy the docstring of `fromfunc`
If the doc contains a line with the keyword `ABSTRACT`,
like `ABSTRACT: Needs to be defined in subclass`, this line and the line after are removed.
"""
def _decorator(func):
sourcedoc = fromfunc.__doc__
... |
If there exist mutually exclusive parameters checks for them and maps param2 to 1. | def kwargs_mutual_exclusive(param1_name, param2_name, map2to1=None):
""" If there exist mutually exclusive parameters checks for them and maps param2 to 1."""
def wrapper(func):
@functools.wraps(func)
def new_func(*args, **kwargs):
if param2_name in kwargs:
if param1_... |
This is a decorator which can be used if a kwarg has changed its name over versions to also support the old argument name. | def kwargs_api_change(old_name, new_name=None):
"""This is a decorator which can be used if a kwarg has changed
its name over versions to also support the old argument name.
Issues a warning if the old keyword argument is detected and
converts call to new API.
:param old_name:
Old name of... |
This is a decorator that signaling that a function is not available during a single run. | def not_in_run(func):
"""This is a decorator that signaling that a function is not available during a single run.
"""
doc = func.__doc__
na_string = '''\nATTENTION: This function is not available during a single run!\n'''
if doc is not None:
func.__doc__ = '\n'.join([doc, na_string])
f... |
This is a decorator that signaling that a function is only available if the storage is open. | def with_open_store(func):
"""This is a decorator that signaling that a function is only available if the storage is open.
"""
doc = func.__doc__
na_string = '''\nATTENTION: This function can only be used if the store is open!\n'''
if doc is not None:
func.__doc__ = '\n'.join([doc, na_stri... |
This is a decorator that retries a function. | def retry(n, errors, wait=0.0, logger_name=None):
"""This is a decorator that retries a function.
Tries `n` times and catches a given tuple of `errors`.
If the `n` retries are not enough, the error is reraised.
If desired `waits` some seconds.
Optionally takes a 'logger_name' of a given logger t... |
Replacement of __getattr__ | def _prfx_getattr_(obj, item):
"""Replacement of __getattr__"""
if item.startswith('f_') or item.startswith('v_'):
return getattr(obj, item[2:])
raise AttributeError('`%s` object has no attribute `%s`' % (obj.__class__.__name__, item)) |
Replacement of __setattr__ | def _prfx_setattr_(obj, item, value):
"""Replacement of __setattr__"""
if item.startswith('v_'):
return setattr(obj, item[2:], value)
else:
return super(obj.__class__, obj).__setattr__(item, value) |
Decorate that adds the prefix naming scheme | def prefix_naming(cls):
"""Decorate that adds the prefix naming scheme"""
if hasattr(cls, '__getattr__'):
raise TypeError('__getattr__ already defined')
cls.__getattr__ = _prfx_getattr_
cls.__setattr__ = _prfx_setattr_
return cls |
Adds all necessary parameters to traj. | def add_params(traj):
"""Adds all necessary parameters to `traj`."""
# We set the BrianParameter to be the standard parameter
traj.v_standard_parameter=Brian2Parameter
traj.v_fast_access=True
# Add parameters we need for our network
traj.f_add_parameter('Net.C',281*pF)
traj.f_add_parameter... |
Creates and runs BRIAN network based on the parameters in traj. | def run_net(traj):
"""Creates and runs BRIAN network based on the parameters in `traj`."""
eqs=traj.eqs
# Create a namespace dictionairy
namespace = traj.Net.f_to_dict(short_names=True, fast_access=True)
# Create the Neuron Group
neuron=NeuronGroup(traj.N, model=eqs, threshold=traj.Vcut, reset... |
Simulation function for Euler integration. | def euler_scheme(traj, diff_func):
"""Simulation function for Euler integration.
:param traj:
Container for parameters and results
:param diff_func:
The differential equation we want to integrate
"""
steps = traj.steps
initial_conditions = traj.initial_conditions
dimens... |
Adds all necessary parameters to the traj container | def add_parameters(traj):
"""Adds all necessary parameters to the `traj` container"""
traj.f_add_parameter('steps', 10000, comment='Number of time steps to simulate')
traj.f_add_parameter('dt', 0.01, comment='Step size')
# Here we want to add the initial conditions as an array parameter. We will simul... |
The Lorenz attractor differential equation | def diff_lorenz(value_array, sigma, beta, rho):
"""The Lorenz attractor differential equation
:param value_array: 3d array containing the x,y, and z component values.
:param sigma: Constant attractor parameter
:param beta: FConstant attractor parameter
:param rho: Constant attractor parameter
... |
Creates a service from a constructor and checks which kwargs are not used | def _create_storage(storage_service, trajectory=None, **kwargs):
"""Creates a service from a constructor and checks which kwargs are not used"""
kwargs_copy = kwargs.copy()
kwargs_copy['trajectory'] = trajectory
matching_kwargs = get_matching_kwargs(storage_service, kwargs_copy)
storage_service = st... |
Creates a storage service to be extended if new storage services are added | def storage_factory(storage_service, trajectory=None, **kwargs):
"""Creates a storage service, to be extended if new storage services are added
:param storage_service:
Storage Service instance of constructor or a string pointing to a file
:param trajectory:
A trajectory instance
:pa... |
Example of a sophisticated simulation that involves multiplying two values. | def multiply(traj):
"""Example of a sophisticated simulation that involves multiplying two values.
:param traj:
Trajectory containing
the parameters in a particular combination,
it also serves as a container for results.
"""
z=traj.mylink1*traj.mylink2 # And again we now can a... |
Adds all necessary parameters to the traj container. | def add_parameters(traj):
"""Adds all necessary parameters to the `traj` container.
You can choose between two parameter sets. One for the Lorenz attractor and
one for the Roessler attractor.
The former is chosen for `traj.diff_name=='diff_lorenz'`, the latter for
`traj.diff_name=='diff_roessler'`.... |
The Roessler attractor differential equation | def diff_roessler(value_array, a, c):
"""The Roessler attractor differential equation
:param value_array: 3d array containing the x,y, and z component values.
:param a: Constant attractor parameter
:param c: Constant attractor parameter
:return: 3d array of the Roessler system evaluated at `value_... |
Can compress an HDF5 to reduce file size. | def compact_hdf5_file(filename, name=None, index=None, keep_backup=True):
"""Can compress an HDF5 to reduce file size.
The properties on how to compress the new file are taken from a given
trajectory in the file.
Simply calls ``ptrepack`` from the command line.
(Se also https://pytables.github.io/u... |
Checks if one the parameters in group_node is explored. | def _explored_parameters_in_group(traj, group_node):
"""Checks if one the parameters in `group_node` is explored.
:param traj: Trajectory container
:param group_node: Group node
:return: `True` or `False`
"""
explored = False
for param in traj.f_get_explored_parameters():
if pa... |
Adds all neuron group parameters to traj. | def add_parameters(traj):
"""Adds all neuron group parameters to `traj`."""
assert(isinstance(traj,Trajectory))
scale = traj.simulation.scale
traj.v_standard_parameter = Brian2Parameter
model_eqs = '''dV/dt= 1.0/tau_POST * (mu - V) + I_syn : 1
mu : 1
... |
Computes model equations for the excitatory and inhibitory population. | def _build_model_eqs(traj):
"""Computes model equations for the excitatory and inhibitory population.
Equation objects are created by fusing `model.eqs` and `model.synaptic.eqs`
and replacing `PRE` by `i` (for inhibitory) or `e` (for excitatory) depending
on the type of population.
... |
Pre - builds the neuron groups. | def pre_build(self, traj, brian_list, network_dict):
"""Pre-builds the neuron groups.
Pre-build is only performed if none of the
relevant parameters is explored.
:param traj: Trajectory container
:param brian_list:
List of objects passed to BRIAN network construct... |
Builds the neuron groups. | def build(self, traj, brian_list, network_dict):
"""Builds the neuron groups.
Build is only performed if neuron group was not
pre-build before.
:param traj: Trajectory container
:param brian_list:
List of objects passed to BRIAN network constructor.
A... |
Builds the neuron groups from traj. | def _build_model(self, traj, brian_list, network_dict):
"""Builds the neuron groups from `traj`.
Adds the neuron groups to `brian_list` and `network_dict`.
"""
model = traj.parameters.model
# Create the equations for both models
eqs_dict = self._build_model_eqs(traj)
... |
Adds all neuron group parameters to traj. | def add_parameters(traj):
"""Adds all neuron group parameters to `traj`."""
assert(isinstance(traj,Trajectory))
traj.v_standard_parameter = Brian2Parameter
scale = traj.simulation.scale
traj.f_add_parameter('connections.R_ee', 1.0, comment='Scaling factor for clustering')
... |
Pre - builds the connections. | def pre_build(self, traj, brian_list, network_dict):
"""Pre-builds the connections.
Pre-build is only performed if none of the
relevant parameters is explored and the relevant neuron groups
exist.
:param traj: Trajectory container
:param brian_list:
List o... |
Builds the connections. | def build(self, traj, brian_list, network_dict):
"""Builds the connections.
Build is only performed if connections have not
been pre-build.
:param traj: Trajectory container
:param brian_list:
List of objects passed to BRIAN network constructor.
Adds:... |
Connects neuron groups neurons_i and neurons_e. | def _build_connections(self, traj, brian_list, network_dict):
"""Connects neuron groups `neurons_i` and `neurons_e`.
Adds all connections to `brian_list` and adds a list of connections
with the key 'connections' to the `network_dict`.
"""
connections = traj.connections
... |
Adds all necessary parameters to traj container. | def add_parameters(self, traj):
"""Adds all necessary parameters to `traj` container."""
par= traj.f_add_parameter(Brian2Parameter,'simulation.durations.initial_run', 500*ms,
comment='Initialisation run for more realistic '
'measur... |
Computes Fano Factor for one neuron. | def _compute_fano_factor(spike_res, neuron_id, time_window, start_time, end_time):
"""Computes Fano Factor for one neuron.
:param spike_res:
Result containing the spiketimes of all neurons
:param neuron_id:
Index of neuron for which FF is computed
:param time... |
Computes average Fano Factor over many neurons. | def _compute_mean_fano_factor( neuron_ids, spike_res, time_window, start_time, end_time):
"""Computes average Fano Factor over many neurons.
:param neuron_ids:
List of neuron indices to average over
:param spike_res:
Result containing all the spikes
:param ti... |
Calculates average Fano Factor of a network. | def analyse(self, traj, network, current_subrun, subrun_list, network_dict):
"""Calculates average Fano Factor of a network.
:param traj:
Trajectory container
Expects:
`results.monitors.spikes_e`: Data from SpikeMonitor for excitatory neurons
Adds:
... |
Adds monitors to the network if the measurement run is carried out. | def add_to_network(self, traj, network, current_subrun, subrun_list, network_dict):
"""Adds monitors to the network if the measurement run is carried out.
:param traj: Trajectory container
:param network: The BRIAN network
:param current_subrun: BrianParameter
:param subrun_l... |
Adds monitors to the network | def _add_monitors(self, traj, network, network_dict):
"""Adds monitors to the network"""
neurons_e = network_dict['neurons_e']
monitor_list = []
# Spiketimes
self.spike_monitor = SpikeMonitor(neurons_e)
monitor_list.append(self.spike_monitor)
# Membrane Poten... |
Makes a subfolder for plots. | def _make_folder(self, traj):
"""Makes a subfolder for plots.
:return: Path name to print folder
"""
print_folder = os.path.join(traj.analysis.plot_folder,
traj.v_name, traj.v_crun)
print_folder = os.path.abspath(print_folder)
if not ... |
Plots a state variable graph for several neurons into one figure | def _plot_result(self, traj, result_name):
"""Plots a state variable graph for several neurons into one figure"""
result = traj.f_get(result_name)
varname = result.record_variables[0]
values = result[varname]
times = result.t
record = result.record
for idx, celi... |
Makes some plots and stores them into subfolders | def _print_graphs(self, traj):
"""Makes some plots and stores them into subfolders"""
print_folder = self._make_folder(traj)
# If we use BRIAN's own raster_plot functionality we
# need to sue the SpikeMonitor directly
plt.figure()
plt.scatter(self.spike_monitor.t, self.s... |
Extracts monitor data and plots. | def analyse(self, traj, network, current_subrun, subrun_list, network_dict):
"""Extracts monitor data and plots.
Data extraction is done if all subruns have been completed,
i.e. `len(subrun_list)==0`
First, extracts results from the monitors and stores them into `traj`.
Next, ... |
Function that parses the batch id from the command line arguments | def get_batch():
"""Function that parses the batch id from the command line arguments"""
optlist, args = getopt.getopt(sys.argv[1:], '', longopts='batch=')
batch = 0
for o, a in optlist:
if o == '--batch':
batch = int(a)
print('Found batch %d' % batch)
return batch |
Chooses exploration according to batch | def explore_batch(traj, batch):
"""Chooses exploration according to `batch`"""
explore_dict = {}
explore_dict['sigma'] = np.arange(10.0 * batch, 10.0*(batch+1), 1.0).tolist()
# for batch = 0 explores sigma in [0.0, 1.0, 2.0, ..., 9.0],
# for batch = 1 explores sigma in [10.0, 11.0, 12.0, ..., 19.0]
... |
Alternative naming you can use node. vars. name instead of node. v_name | def vars(self):
"""Alternative naming, you can use `node.vars.name` instead of `node.v_name`"""
if self._vars is None:
self._vars = NNTreeNodeVars(self)
return self._vars |
Alternative naming you can use node. func. name instead of node. f_func | def func(self):
"""Alternative naming, you can use `node.func.name` instead of `node.f_func`"""
if self._func is None:
self._func = NNTreeNodeFunc(self)
return self._func |
Renames the tree node | def _rename(self, full_name):
"""Renames the tree node"""
self._full_name = full_name
if full_name:
self._name = full_name.rsplit('.', 1)[-1] |
Sets some details for internal handling. | def _set_details(self, depth, branch, run_branch):
"""Sets some details for internal handling."""
self._depth = depth
self._branch = branch
self._run_branch = run_branch |
Maps a an instance type representation string ( e. g. RESULT ) to the corresponding dictionary in root. | def _map_type_to_dict(self, type_name):
""" Maps a an instance type representation string (e.g. 'RESULT')
to the corresponding dictionary in root.
"""
root = self._root_instance
if type_name == RESULT:
return root._results
elif type_name == PARAMETER:
... |
Method used by f_store/ load/ remove_items to find a corresponding item in the tree. | def _fetch_from_string(self, store_load, name, args, kwargs):
"""Method used by f_store/load/remove_items to find a corresponding item in the tree.
:param store_load:
String constant specifying if we want to store, load or remove.
The corresponding constants are defined at the ... |
Method used by f_store/ load/ remove_items to find a corresponding item in the tree. | def _fetch_from_node(self, store_load, node, args, kwargs):
"""Method used by f_store/load/remove_items to find a corresponding item in the tree.
:param store_load: String constant specifying if we want to store, load or remove
:param node: A group, parameter or result instance.
:param ... |
Method used by f_store/ load/ remove_items to find a corresponding item in the tree. | def _fetch_from_tuple(self, store_load, store_tuple, args, kwargs):
""" Method used by f_store/load/remove_items to find a corresponding item in the tree.
The input to the method should already be in the correct format, this method only
checks for sanity.
:param store_load: String cons... |
Maps a given node and a store_load constant to the message that is understood by the storage service. | def _node_to_msg(store_load, node):
"""Maps a given node and a store_load constant to the message that is understood by
the storage service.
"""
if node.v_is_leaf:
if store_load == STORE:
return pypetconstants.LEAF
elif store_load == LOAD:
... |
Method used by f_store/ load/ remove_items to find corresponding items in the tree. | def _fetch_items(self, store_load, iterable, args, kwargs):
""" Method used by f_store/load/remove_items to find corresponding items in the tree.
:param store_load:
String constant specifying if we want to store, load or remove.
The corresponding constants are defined at the t... |
Removes a subtree from the trajectory tree. | def _remove_subtree(self, start_node, name, predicate=None):
"""Removes a subtree from the trajectory tree.
Does not delete stuff from disk only from RAM.
:param start_node: The parent node from where to start
:param name: Name of child which will be deleted and recursively all nodes b... |
Deletes a single node from the tree. | def _delete_node(self, node):
"""Deletes a single node from the tree.
Removes all references to the node.
Note that the 'parameters', 'results', 'derived_parameters', and 'config' groups
hanging directly below root cannot be deleted. Also the root node itself cannot be
deleted.... |
Removes a single node from the tree. | def _remove_node_or_leaf(self, instance, recursive=False):
"""Removes a single node from the tree.
Only from RAM not from hdf5 file!
:param instance: The node to be deleted
:param recursive: If group nodes with children should be deleted
"""
full_name = instance.v_ful... |
Removes a given node from the tree. | def _remove_along_branch(self, actual_node, split_name, recursive=False):
"""Removes a given node from the tree.
Starts from a given node and walks recursively down the tree to the location of the node
we want to remove.
We need to walk from a start node in case we want to check on the... |
Maps a given shortcut to corresponding name | def _translate_shortcut(self, name):
"""Maps a given shortcut to corresponding name
* 'run_X' or 'r_X' to 'run_XXXXXXXXX'
* 'crun' to the current run name in case of a
single run instance if trajectory is used via `v_crun`
* 'par' 'parameters'
* 'dpar' to 'derived_p... |
Adds the correct sub branch prefix to a given name. | def _add_prefix(self, split_names, start_node, group_type_name):
"""Adds the correct sub branch prefix to a given name.
Usually the prefix is the full name of the parent node. In case items are added
directly to the trajectory the prefixes are chosen according to the matching subbranch.
... |
Determines types for generic additions | def _determine_types(start_node, first_name, add_leaf, add_link):
"""Determines types for generic additions"""
if start_node.v_is_root:
where = first_name
else:
where = start_node._branch
if where in SUBTREE_MAPPING:
type_tuple = SUBTREE_MAPPING[where... |
Adds a given item to the tree irrespective of the subtree. | def _add_generic(self, start_node, type_name, group_type_name, args, kwargs,
add_prefix=True, check_naming=True):
"""Adds a given item to the tree irrespective of the subtree.
Infers the subtree from the arguments.
:param start_node: The parental node the adding was initia... |
Replaces the $ wildcards and returns True/ False in case it was replaced | def _replace_wildcards(self, name, run_idx=None):
"""Replaces the $ wildcards and returns True/False in case it was replaced"""
if self._root_instance.f_is_wildcard(name):
return True, self._root_instance.f_wildcard(name, run_idx)
else:
return False, name |
Adds a new item to the tree. | def _add_to_tree(self, start_node, split_names, type_name, group_type_name,
instance, constructor, args, kwargs):
"""Adds a new item to the tree.
The item can be an already given instance or it is created new.
:param start_node:
Parental node the adding of the... |
Creates a link and checks if names are appropriate | def _create_link(self, act_node, name, instance):
"""Creates a link and checks if names are appropriate
"""
act_node._links[name] = instance
act_node._children[name] = instance
full_name = instance.v_full_name
if full_name not in self._root_instance._linked_by:
... |
Checks if a list contains strings with invalid names. | def _check_names(self, split_names, parent_node=None):
"""Checks if a list contains strings with invalid names.
Returns a description of the name violations. If names are correct the empty
string is returned.
:param split_names: List of strings
:param parent_node:
... |
Generically creates a new group inferring from the type_name. | def _create_any_group(self, parent_node, name, type_name, instance=None, constructor=None,
args=None, kwargs=None):
"""Generically creates a new group inferring from the `type_name`."""
if args is None:
args = []
if kwargs is None:
kwargs = {}
... |
Generically creates a novel parameter or result instance inferring from the type_name. | def _create_any_param_or_result(self, parent_node, name, type_name, instance, constructor,
args, kwargs):
"""Generically creates a novel parameter or result instance inferring from the `type_name`.
If the instance is already supplied it is NOT constructed new.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.