_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q274200 | Trajectory._remove_exploration | test | def _remove_exploration(self):
""" Called if trajectory is expanded, deletes all explored parameters from disk """
for param in self._explored_parameters.values():
if param._stored:
try:
self.f_delete_item(param)
except Exception:
self._logger.exception('Could not delete expanded parameter `%s` '
'from disk.' % param.v_full_name) | python | {
"resource": ""
} |
q274201 | Trajectory._copy_from | test | def _copy_from(self, node,
copy_leaves=True,
overwrite=False,
with_links=True):
"""Pass a ``node`` to insert the full tree to the trajectory.
Considers all links in the given node!
Ignored nodes already found in the current trajectory.
:param node: The node to insert
:param copy_leaves:
If leaves should be **shallow** copied or simply referred to by both trees.
**Shallow** copying is established using the copy module.
Accepts the setting ``'explored'`` to only copy explored parameters.
Note that ``v_full_copy`` determines how these will be copied.
:param overwrite:
If existing elemenst should be overwritten. Requries ``__getstate__`` and
``__setstate__`` being implemented in the leaves.
:param with_links: If links should be ignored or followed and copied as well
:return: The corresponding (new) node in the tree.
"""
def _copy_skeleton(node_in, node_out):
"""Copies the skeleton of from `node_out` to `node_in`"""
new_annotations = node_out.v_annotations
node_in._annotations = new_annotations
node_in.v_comment = node_out.v_comment
def _add_leaf(leaf):
"""Adds a leaf to the trajectory"""
leaf_full_name = leaf.v_full_name
try:
found_leaf = self.f_get(leaf_full_name,
with_links=False,
shortcuts=False,
auto_load=False)
if overwrite:
found_leaf.__setstate__(leaf.__getstate__())
return found_leaf
except AttributeError:
pass
if copy_leaves is True or (copy_leaves == 'explored' and
leaf.v_is_parameter and leaf.v_explored):
new_leaf = self.f_add_leaf(cp.copy(leaf))
else:
new_leaf = self.f_add_leaf(leaf)
if new_leaf.v_is_parameter and new_leaf.v_explored:
self._explored_parameters[new_leaf.v_full_name] = new_leaf
return new_leaf
def _add_group(group):
"""Adds a new group to the trajectory"""
group_full_name = group.v_full_name
try:
found_group = self.f_get(group_full_name,
with_links=False,
shortcuts=False,
auto_load=False)
if overwrite:
_copy_skeleton(found_group, group)
return found_group
except AttributeError:
pass
new_group = self.f_add_group(group_full_name)
_copy_skeleton(new_group, group)
return new_group
is_run = self._is_run
self._is_run = False # So that we can copy Config Groups and Config Data
try:
if node.v_is_leaf:
return _add_leaf(node)
elif node.v_is_group:
other_root = node.v_root
if other_root is self:
raise RuntimeError('You cannot copy a given tree to itself!')
result = _add_group(node)
nodes_iterator = node.f_iter_nodes(recursive=True, with_links=with_links)
has_links = []
if node._links:
has_links.append(node)
for child in nodes_iterator:
if child.v_is_leaf:
_add_leaf(child)
else:
_add_group(child)
if child._links:
has_links.append(child)
if with_links:
for current in has_links:
mine = self.f_get(current.v_full_name, with_links=False,
shortcuts=False, auto_load=False)
my_link_set = set(mine._links.keys())
other_link_set = set(current._links.keys())
new_links = other_link_set - my_link_set
for link in new_links:
where_full_name = current._links[link].v_full_name
mine.f_add_link(link, where_full_name)
return result
else:
raise RuntimeError('You shall not pass!')
except Exception:
self._is_run = is_run | python | {
"resource": ""
} |
q274202 | Trajectory.f_explore | test | def f_explore(self, build_dict):
"""Prepares the trajectory to explore the parameter space.
To explore the parameter space you need to provide a dictionary with the names of the
parameters to explore as keys and iterables specifying the exploration ranges as values.
All iterables need to have the same length otherwise a ValueError is raised.
A ValueError is also raised if the names from the dictionary map to groups or results
and not parameters.
If your trajectory is already explored but not stored yet and your parameters are
not locked you can add new explored parameters to the current ones if their
iterables match the current length of the trajectory.
Raises an AttributeError if the names from the dictionary are not found at all in
the trajectory and NotUniqueNodeError if the keys not unambiguously map
to single parameters.
Raises a TypeError if the trajectory has been stored already, please use
:func:`~pypet.trajectory.Trajectory.f_expand` then instead.
Example usage:
>>> traj.f_explore({'groupA.param1' : [1,2,3,4,5], 'groupA.param2':['a','b','c','d','e']})
Could also be called consecutively:
>>> traj.f_explore({'groupA.param1' : [1,2,3,4,5]})
>>> traj.f_explore({'groupA.param2':['a','b','c','d','e']})
NOTE:
Since parameters are very conservative regarding the data they accept
(see :ref:`type_conservation`), you sometimes won't be able to use Numpy arrays
for exploration as iterables.
For instance, the following code snippet won't work:
::
import numpy a np
from pypet.trajectory import Trajectory
traj = Trajectory()
traj.f_add_parameter('my_float_parameter', 42.4,
comment='My value is a standard python float')
traj.f_explore( { 'my_float_parameter': np.arange(42.0, 44.876, 0.23) } )
This will result in a `TypeError` because your exploration iterable
`np.arange(42.0, 44.876, 0.23)` contains `numpy.float64` values
whereas you parameter is supposed to use standard python floats.
Yet, you can use Numpys `tolist()` function to overcome this problem:
::
traj.f_explore( { 'my_float_parameter': np.arange(42.0, 44.876, 0.23).tolist() } )
Or you could specify your parameter directly as a numpy float:
::
traj.f_add_parameter('my_float_parameter', np.float64(42.4),
comment='My value is a numpy 64 bit float')
"""
for run_idx in range(len(self)):
if self.f_is_completed(run_idx):
raise TypeError('You cannot explore a trajectory which has been explored before, '
'please use `f_expand` instead.')
added_explored_parameters = []
try:
length = len(self)
for key, builditerable in build_dict.items():
act_param = self.f_get(key)
if not act_param.v_is_leaf or not act_param.v_is_parameter:
raise ValueError('%s is not an appropriate search string for a parameter.' % key)
act_param.f_unlock()
act_param._explore(builditerable)
added_explored_parameters.append(act_param)
full_name = act_param.v_full_name
self._explored_parameters[full_name] = act_param
act_param._explored = True
# Compare the length of two consecutive parameters in the `build_dict`
if len(self._explored_parameters) == 1:
length = act_param.f_get_range_length()
elif not length == act_param.f_get_range_length():
raise ValueError('The parameters to explore have not the same size!')
for irun in range(length):
self._add_run_info(irun)
self._test_run_addition(length)
except Exception:
# Remove the added parameters again
for param in added_explored_parameters:
param.f_unlock()
param._shrink()
param._explored = False
full_name = param.v_full_name
del self._explored_parameters[full_name]
if len(self._explored_parameters) == 0:
self.f_shrink(force=True)
raise | python | {
"resource": ""
} |
q274203 | Trajectory._update_run_information | test | def _update_run_information(self, run_information_dict):
"""Overwrites the run information of a particular run"""
idx = run_information_dict['idx']
name = run_information_dict['name']
self._run_information[name] = run_information_dict
self._updated_run_information.add(idx) | python | {
"resource": ""
} |
q274204 | Trajectory._add_run_info | test | def _add_run_info(self, idx, name='', timestamp=42.0, finish_timestamp=1.337,
runtime='forever and ever', time='>>Maybe time`s gone on strike',
completed=0, parameter_summary='Not yet my friend!',
short_environment_hexsha='N/A'):
"""Adds a new run to the `_run_information` dict."""
if idx in self._single_run_ids:
# Delete old entries, they might be replaced by a new name
old_name = self._single_run_ids[idx]
del self._single_run_ids[old_name]
del self._single_run_ids[idx]
del self._run_information[old_name]
if name == '':
name = self.f_wildcard('$', idx)
# The `_single_run_ids` dict is bidirectional and maps indices to run names and vice versa
self._single_run_ids[name] = idx
self._single_run_ids[idx] = name
info_dict = {'idx': idx,
'timestamp': timestamp,
'finish_timestamp': finish_timestamp,
'runtime': runtime,
'time': time,
'completed': completed,
'name': name,
'parameter_summary': parameter_summary,
'short_environment_hexsha': short_environment_hexsha}
self._run_information[name] = info_dict
self._length = len(self._run_information) | python | {
"resource": ""
} |
q274205 | Trajectory.f_lock_parameters | test | def f_lock_parameters(self):
"""Locks all non-empty parameters"""
for par in self._parameters.values():
if not par.f_is_empty():
par.f_lock() | python | {
"resource": ""
} |
q274206 | Trajectory.f_lock_derived_parameters | test | def f_lock_derived_parameters(self):
"""Locks all non-empty derived parameters"""
for par in self._derived_parameters.values():
if not par.f_is_empty():
par.f_lock() | python | {
"resource": ""
} |
q274207 | Trajectory._finalize | test | def _finalize(self, store_meta_data=True):
"""Final rollback initiated by the environment
Restores the trajectory as root of the tree, and stores meta data to disk.
This updates the trajectory's information about single runs, i.e. if they've been
completed, when they were started, etc.
"""
self._is_run = False
self.f_set_crun(None)
if store_meta_data:
self.f_store(only_init=True) | python | {
"resource": ""
} |
q274208 | Trajectory.f_load_skeleton | test | def f_load_skeleton(self):
"""Loads the full skeleton from the storage service.
This needs to be done after a successful exploration in order to update the
trajectory tree with all results and derived parameters from the individual single runs.
This will only add empty results and derived parameters (i.e. the skeleton)
and load annotations.
"""
self.f_load(self.v_name, as_new=False, load_parameters=pypetconstants.LOAD_SKELETON,
load_derived_parameters=pypetconstants.LOAD_SKELETON,
load_results=pypetconstants.LOAD_SKELETON,
load_other_data=pypetconstants.LOAD_SKELETON,
with_run_information=False) | python | {
"resource": ""
} |
q274209 | Trajectory.f_load | test | def f_load(self, name=None, index=None, as_new=False, load_parameters=pypetconstants.LOAD_DATA,
load_derived_parameters=pypetconstants.LOAD_SKELETON,
load_results=pypetconstants.LOAD_SKELETON,
load_other_data=pypetconstants.LOAD_SKELETON,
recursive=True,
load_data=None,
max_depth=None,
force=False,
dynamic_imports=None,
with_run_information=True,
with_meta_data=True,
storage_service=None, **kwargs):
"""Loads a trajectory via the storage service.
If you want to load individual results or parameters manually, you can take
a look at :func:`~pypet.trajectory.Trajectory.f_load_items`.
To only load subtrees check out :func:`~pypet.naturalnaming.NNGroupNode.f_load_child`.
For `f_load` you can pass the following arguments:
:param name:
Name of the trajectory to be loaded. If no name or index is specified
the current name of the trajectory is used.
:param index:
If you don't specify a name you can specify an integer index instead.
The corresponding trajectory in the hdf5 file at the index
position is loaded (counting starts with 0). Negative indices are also allowed
counting in reverse order. For instance, `-1` refers to the last trajectory in
the file, `-2` to the second last, and so on.
:param as_new:
Whether you want to rerun the experiments. So the trajectory is loaded only
with parameters. The current trajectory name is kept in this case, which should be
different from the trajectory name specified in the input parameter `name`.
If you load `as_new=True` all parameters are unlocked.
If you load `as_new=False` the current trajectory is replaced by the one on disk,
i.e. name, timestamp, formatted time etc. are all taken from disk.
:param load_parameters: How parameters and config items are loaded
:param load_derived_parameters: How derived parameters are loaded
:param load_results: How results are loaded
You can specify how to load the parameters, derived parameters and results
as follows:
* :const:`pypet.pypetconstants.LOAD_NOTHING`: (0)
Nothing is loaded.
* :const:`pypet.pypetconstants.LOAD_SKELETON`: (1)
The skeleton is loaded including annotations (See :ref:`more-on-annotations`).
This means that only empty
*parameter* and *result* objects will
be created and you can manually load the data into them afterwards.
Note that :class:`pypet.annotations.Annotations` do not count as data and they
will be loaded because they are assumed to be small.
* :const:`pypet.pypetconstants.LOAD_DATA`: (2)
The whole data is loaded. Note in case you have non-empty leaves
already in RAM, these are left untouched.
* :const:`pypet.pypetconstants.OVERWRITE_DATA`: (3)
As before, but non-empty nodes are emptied and reloaded.
Note that in all cases except :const:`pypet.pypetconstants.LOAD_NOTHING`,
annotations will be reloaded if the corresponding instance
is created or the annotations of an existing instance were emptied before.
:param recursive:
If data should be loaded recursively. If set to `None`, this is equivalent to
set all data loading to `:const:`pypet.pypetconstants.LOAD_NOTHING`.
:param load_data:
As the above, per default set to `None`. If not `None` the setting of `load_data`
will overwrite the settings of `load_parameters`, `load_derived_parameters`,
`load_results`, and `load_other_data`. This is more or less or shortcut if all
types should be loaded the same.
:param max_depth:
Maximum depth to load nodes (inclusive).
:param force:
*pypet* will refuse to load trajectories that have been created using *pypet* with a
different version number or a different python version.
To force the load of a trajectory from a previous version
simply set ``force = True``. Note that it is not checked if other versions of packages
differ from previous experiments, i.e. numpy, scipy, etc. But you can check
for this manually. The versions of other packages can be found under
``'config.environment.name_of_environment.versions.package_name'``.
:param dynamic_imports:
If you've written a custom parameter that needs to be loaded dynamically
during runtime, this needs to be specified here as a list of classes or
strings naming classes and there module paths. For example:
`dynamic_imports = ['pypet.parameter.PickleParameter',MyCustomParameter]`
If you only have a single class to import, you do not need the list brackets:
`dynamic_imports = 'pypet.parameter.PickleParameter'`
The classes passed here are added for good and will be kept by the trajectory.
Please add your dynamically imported classes only once.
:param with_run_information:
If information about the individual runs should be loaded. If you have many
runs, like 1,000,000 or more you can spare time by setting
`with_run_information=False`.
Note that `f_get_run_information` and `f_idx_to_run` do not work in such a case.
Moreover, setting `v_idx` does not work either. If you load the trajectory
without this information, be careful, this is not recommended.
:param wiht_meta_data:
If meta data should be loaded.
:param storage_service:
Pass a storage service used by the trajectory. Alternatively pass a constructor
and other ``**kwargs`` are passed onto the constructor. Leave `None` in combination
with using no other kwargs, if you don't want to change the service
the trajectory is currently using.
:param kwargs:
Other arguments passed to the storage service constructor. Don't pass any
other kwargs and ``storage_service=None``,
if you don't want to change the current service.
"""
# Do some argument validity checks first
if name is None and index is None:
name = self.v_name
if as_new:
load_parameters = pypetconstants.LOAD_DATA
load_derived_parameters = pypetconstants.LOAD_NOTHING
load_results = pypetconstants.LOAD_NOTHING
load_other_data = pypetconstants.LOAD_NOTHING
unused_kwargs = set(kwargs.keys())
if self.v_storage_service is None or storage_service is not None or len(kwargs) > 0:
self._storage_service, unused_kwargs = storage_factory(storage_service=storage_service,
trajectory=self, **kwargs)
if len(unused_kwargs) > 0:
raise ValueError('The following keyword arguments were not used: `%s`' %
str(unused_kwargs))
if dynamic_imports is not None:
self.f_add_to_dynamic_imports(dynamic_imports)
if load_data is not None:
load_parameters = load_data
load_derived_parameters = load_data
load_results = load_data
load_other_data = load_data
self._storage_service.load(pypetconstants.TRAJECTORY, self, trajectory_name=name,
trajectory_index=index,
as_new=as_new, load_parameters=load_parameters,
load_derived_parameters=load_derived_parameters,
load_results=load_results,
load_other_data=load_other_data,
recursive=recursive,
max_depth=max_depth,
with_run_information=with_run_information,
with_meta_data=with_meta_data,
force=force)
# If a trajectory is newly loaded, all parameters are unlocked.
if as_new:
for param in self._parameters.values():
param.f_unlock() | python | {
"resource": ""
} |
q274210 | Trajectory.f_backup | test | def f_backup(self, **kwargs):
"""Backs up the trajectory with the given storage service.
Arguments of ``kwargs`` are directly passed to the storage service,
for the HDF5StorageService you can provide the following argument:
:param backup_filename:
Name of file where to store the backup.
In case you use the standard HDF5 storage service and `backup_filename=None`,
the file will be chosen automatically.
The backup file will be in the same folder as your hdf5 file and
named 'backup_XXXXX.hdf5' where 'XXXXX' is the name of your current trajectory.
"""
self._storage_service.store(pypetconstants.BACKUP, self, trajectory_name=self.v_name,
**kwargs) | python | {
"resource": ""
} |
q274211 | Trajectory._make_reversed_wildcards | test | def _make_reversed_wildcards(self, old_length=-1):
"""Creates a full mapping from all wildcard translations to the corresponding wildcards"""
if len(self._reversed_wildcards) > 0:
# We already created reversed wildcards, so we don't need to do all of them
# again
start = old_length
else:
start = -1
for wildcards, func in self._wildcard_functions.items():
for irun in range(start, len(self)):
translated_name = func(irun)
if not translated_name in self._reversed_wildcards:
self._reversed_wildcards[translated_name] = ([], wildcards)
self._reversed_wildcards[translated_name][0].append(irun) | python | {
"resource": ""
} |
q274212 | Trajectory.f_merge_many | test | def f_merge_many(self, other_trajectories,
ignore_data=(),
move_data=False,
delete_other_trajectory=False,
keep_info=True,
keep_other_trajectory_info=True,
merge_config=True,
backup=True):
"""Can be used to merge several `other_trajectories` into your current one.
IMPORTANT `backup=True` only backs up the current trajectory not any of
the `other_trajectories`. If you need a backup of these, do it manually.
Parameters as for :func:`~pypet.trajectory.Trajectory.f_merge`.
"""
other_length = len(other_trajectories)
self._logger.info('Merging %d trajectories into the current one.' % other_length)
self.f_load_skeleton()
if backup:
self.f_backup()
for idx, other in enumerate(other_trajectories):
self.f_merge(other, ignore_data=ignore_data,
move_data=move_data,
delete_other_trajectory=delete_other_trajectory,
keep_info=keep_info,
keep_other_trajectory_info=keep_other_trajectory_info,
merge_config=merge_config,
backup=False,
consecutive_merge=True)
self._logger.log(21,'Merged %d out of %d' % (idx + 1, other_length))
self._logger.info('Storing data to disk')
self._reversed_wildcards = {}
self.f_store()
self._logger.info('Finished final storage') | python | {
"resource": ""
} |
q274213 | Trajectory._merge_single_runs | test | def _merge_single_runs(self, other_trajectory, used_runs):
""" Updates the `run_information` of the current trajectory."""
count = len(self) # Variable to count the increasing new run indices and create
# new run names
run_indices = range(len(other_trajectory))
run_name_dict = OrderedDict()
to_store_groups_with_annotations = []
for idx in run_indices:
# Iterate through all used runs and store annotated groups and mark results and
# derived parameters for merging
if idx in used_runs:
# Update the run information dict of the current trajectory
other_info_dict = other_trajectory.f_get_run_information(idx)
time_ = other_info_dict['time']
timestamp = other_info_dict['timestamp']
completed = other_info_dict['completed']
short_environment_hexsha = other_info_dict['short_environment_hexsha']
finish_timestamp = other_info_dict['finish_timestamp']
runtime = other_info_dict['runtime']
new_idx = used_runs[idx]
new_runname = self.f_wildcard('$', new_idx)
run_name_dict[idx] = new_runname
info_dict = dict(
idx=new_idx,
time=time_,
timestamp=timestamp,
completed=completed,
short_environment_hexsha=short_environment_hexsha,
finish_timestamp=finish_timestamp,
runtime=runtime)
self._add_run_info(**info_dict) | python | {
"resource": ""
} |
q274214 | Trajectory._rename_full_name | test | def _rename_full_name(self, full_name, other_trajectory, used_runs=None, new_run_idx=None):
"""Renames a full name based on the wildcards and a particular run"""
split_name = full_name.split('.')
for idx, name in enumerate(split_name):
if name in other_trajectory._reversed_wildcards:
run_indices, wildcards = other_trajectory._reversed_wildcards[name]
if new_run_idx is None:
# We can safely take the first index of the index list that matches
run_idx = None
for run_jdx in run_indices:
if run_jdx in used_runs:
run_idx = used_runs[run_jdx]
break
elif run_jdx == -1:
run_idx = -1
break
if run_idx is None:
raise RuntimeError('You shall not pass!')
else:
run_idx = new_run_idx
new_name = self.f_wildcard(wildcards[0], run_idx)
split_name[idx] = new_name
full_name = '.'.join(split_name)
return full_name | python | {
"resource": ""
} |
q274215 | Trajectory._merge_derived_parameters | test | def _merge_derived_parameters(self,
other_trajectory,
used_runs,
rename_dict,
allowed_translations,
ignore_data):
""" Merges derived parameters that have the `run_ALL` in a name.
Creates a new parameter with the name of the first new run and links to this
parameter to avoid copying in all other runs.
"""
other_derived_parameters = other_trajectory._derived_parameters.copy()
# get first run_idx
new_first_run_idx = min(used_runs.values())
run_name_dummy = other_trajectory.f_wildcard('$', -1)
for param_name in other_derived_parameters:
if param_name in ignore_data:
continue
split_name = param_name.split('.')
if not any(x in run_name_dummy for x in split_name):
continue
ignore_data.add(param_name)
param = other_derived_parameters[param_name]
new_param_name = self._rename_full_name(param_name, other_trajectory,
used_runs=used_runs)
if new_param_name in self:
my_param = self.f_get(new_param_name, fast_access=False)
if (my_param._equal_values(my_param.f_get(), param.f_get()) and
not (my_param.f_has_range() or param.f_has_range())):
continue
first_new_param_name = self._rename_full_name(param_name,
other_trajectory,
new_run_idx=new_first_run_idx)
rename_dict[param_name] = first_new_param_name
comment = param.v_comment
param_type = param.f_get_class_name()
param_type = self._create_class(param_type)
first_param = self.f_add_leaf(param_type,
first_new_param_name,
comment=comment)
for run_idx in used_runs.values():
if run_idx == new_first_run_idx:
continue
next_name = self._rename_full_name(param_name, other_trajectory,
new_run_idx=run_idx)
split_name = next_name.split('.')
link_name = split_name.pop()
location_name = '.'.join(split_name)
if not self.f_contains(location_name, shortcuts=False):
the_group = self.f_add_group(location_name)
else:
the_group = self.f_get(location_name)
the_group.f_add_link(link_name, first_param)
for param_name in other_derived_parameters:
if param_name in ignore_data:
continue
split_name = param_name.split('.')
ignore_data.add(param_name)
if any(x in other_trajectory._reversed_wildcards and x not in allowed_translations
for x in split_name):
continue
new_name = self._rename_full_name(param_name, other_trajectory,
used_runs=used_runs)
if self.f_contains(new_name):
my_param = self.f_get(new_name, fast_access=False)
param = other_derived_parameters[param_name]
if (my_param._equal_values(my_param.f_get(), param.f_get()) and
not (my_param.f_has_range() or param.f_has_range())):
continue
else:
self._logger.error('Could not merge parameter `%s`. '
'I will ignore it!' % new_name)
rename_dict[param_name] = new_name | python | {
"resource": ""
} |
q274216 | Trajectory._merge_links | test | def _merge_links(self, other_trajectory, used_runs, allowed_translations, ignore_data):
""" Merges all links"""
linked_items = other_trajectory._linked_by
run_name_dummys = set([f(-1) for f in other_trajectory._wildcard_functions.values()])
if len(linked_items) > 0:
self._logger.info('Merging potential links!')
for old_linked_name in other_trajectory._linked_by:
if old_linked_name in ignore_data:
continue
split_name = old_linked_name.split('.')
if any(x in run_name_dummys for x in split_name):
self._logger.warning('Ignoring all links linking to `%s` because '
'I don`t know how to resolve links under `%s` nodes.' %
(old_linked_name, str(run_name_dummys)))
continue
old_link_dict = other_trajectory._linked_by[old_linked_name]
split_name = old_linked_name.split('.')
if all(x in allowed_translations for x in split_name):
new_linked_full_name = self._rename_full_name(old_linked_name,
other_trajectory,
used_runs=used_runs)
else:
new_linked_full_name = old_linked_name
for linking_node, link_set in old_link_dict.values():
linking_full_name = linking_node.v_full_name
split_name = linking_full_name .split('.')
if any(x in run_name_dummys for x in split_name):
self._logger.warning('Ignoring links under `%s` because '
'I don`t know how to resolve links '
'under a `%s` node.' %
(linking_full_name, str(run_name_dummys)))
split_name = linking_full_name .split('.')
if any(x in allowed_translations for x in split_name):
new_linking_full_name = self._rename_full_name(linking_full_name,
other_trajectory,
used_runs=used_runs)
else:
new_linking_full_name = linking_full_name
for link in link_set:
if (linking_full_name + '.' + link) in ignore_data:
continue
if link in run_name_dummys:
self._logger.warning('Ignoring link `%s` under `%s` because '
'I don`t know how to resolve '
'links named as `%s`.' %
(link,
linking_full_name,
str(run_name_dummys)))
continue
try:
new_linked_item = self.f_get(new_linked_full_name,
shortcuts=False)
if self.f_contains(new_linking_full_name):
new_linking_item = self.f_get(new_linking_full_name,
shortcuts=False)
else:
new_linking_item = self.f_add_group(new_linking_full_name)
if link in allowed_translations:
run_indices, wildcards = other_trajectory._reversed_wildcards[link]
link = self.f_wildcard(wildcards[0], used_runs[run_indices[0]])
if not link in new_linking_item._links:
new_linking_item.f_add_link(link, new_linked_item)
else:
self._logger.debug('Link `%s` exists already under `%s`.' %
(link, new_linked_item.v_full_name))
except (AttributeError, ValueError) as exc:
self._logger.error('Could not copy link `%s` under `%s` linking '
'to `%s` due to `%s`' %
(link, linking_full_name, old_linked_name,
repr(exc))) | python | {
"resource": ""
} |
q274217 | Trajectory._merge_config | test | def _merge_config(self, other_trajectory):
"""Merges meta data about previous merges, git commits, and environment settings
of the other trajectory into the current one.
"""
self._logger.info('Merging config!')
# Merge git commit meta data
if 'config.git' in other_trajectory:
self._logger.info('Merging git commits!')
git_node = other_trajectory.f_get('config.git')
param_list = []
for param in git_node.f_iter_leaves(with_links=False):
if not self.f_contains(param.v_full_name, shortcuts=False):
param_list.append(self.f_add_config(param))
if param_list:
self.f_store_items(param_list)
self._logger.info('Merging git commits successful!')
# Merge environment meta data
if 'config.environment' in other_trajectory:
self._logger.info('Merging environment config!')
env_node = other_trajectory.f_get('config.environment')
param_list = []
for param in env_node.f_iter_leaves(with_links=False):
if not self.f_contains(param.v_full_name, shortcuts=False):
param_list.append(self.f_add_config(param))
if param_list:
self.f_store_items(param_list)
self._logger.info('Merging config successful!')
# Merge meta data of previous merges
if 'config.merge' in other_trajectory:
self._logger.info('Merging merge config!')
merge_node = other_trajectory.f_get('config.merge')
param_list = []
for param in merge_node.f_iter_leaves(with_links=False):
if not self.f_contains(param.v_full_name, shortcuts=False):
param_list.append(self.f_add_config(param))
if param_list:
self.f_store_items(param_list)
self._logger.info('Merging config successful!') | python | {
"resource": ""
} |
q274218 | Trajectory._merge_slowly | test | def _merge_slowly(self, other_trajectory, rename_dict):
"""Merges trajectories by loading iteratively items of the other trajectory and
store it into the current trajectory.
:param rename_dict:
Dictionary containing mappings from the old result names in the `other_trajectory`
to the new names in the current trajectory.
"""
for other_key in rename_dict:
new_key = rename_dict[other_key]
other_instance = other_trajectory.f_get(other_key)
if other_instance.f_is_empty():
# To suppress warnings if nothing needs to be loaded
with self._nn_interface._disable_logging:
other_trajectory.f_load_item(other_instance)
if not self.f_contains(new_key):
class_name = other_instance.f_get_class_name()
class_ = self._create_class(class_name)
my_instance = self.f_add_leaf(class_, new_key)
else:
my_instance = self.f_get(new_key, shortcuts=False)
if not my_instance.f_is_empty():
raise RuntimeError('Something is wrong! Your item `%s` should be empty.' % new_key)
load_dict = other_instance._store()
my_instance._load(load_dict)
my_instance.f_set_annotations(**other_instance.v_annotations.f_to_dict(copy=False))
my_instance.v_comment = other_instance.v_comment
self.f_store_item(my_instance)
# We do not want to blow up the RAM Memory
if other_instance.v_is_parameter:
other_instance.f_unlock()
my_instance.f_unlock()
other_instance.f_empty()
my_instance.f_empty() | python | {
"resource": ""
} |
q274219 | Trajectory._merge_results | test | def _merge_results(self, other_trajectory, rename_dict, used_runs, allowed_translations,
ignore_data):
"""Merges all results.
:param rename_dict:
Dictionary that is filled with the names of results in the `other_trajectory`
as keys and the corresponding new names in the current trajectory as values.
Note for results kept under trajectory run branch there is actually no need to
change the names. So we will simply keep the original name.
"""
other_results = other_trajectory._results.copy()
for result_name in other_results:
if result_name in ignore_data:
continue
split_name = result_name.split('.')
ignore_data.add(result_name)
if any(x in other_trajectory._reversed_wildcards and x not in allowed_translations
for x in split_name):
continue
new_name = self._rename_full_name(result_name, other_trajectory,
used_runs=used_runs)
if self.f_contains(new_name):
self._logger.warning('I found result `%s` already, I will ignore it.' % new_name)
continue
rename_dict[result_name] = new_name | python | {
"resource": ""
} |
q274220 | Trajectory.f_migrate | test | def f_migrate(self, new_name=None, in_store=False,
new_storage_service=None, **kwargs):
"""Can be called to rename and relocate the trajectory.
:param new_name: New name of the trajectory, None if you do not want to change the name.
:param in_store:
Set this to True if the trajectory has been stored with the new name at the new
file before and you just want to "switch back" to the location.
If you migrate to a store used before and you do not set `in_store=True`,
the storage service will throw a RuntimeError in case you store the Trajectory
because it will assume that you try to store a new trajectory that accidentally has
the very same name as another trajectory. If set to `True` and trajectory is not found
in the file, the trajectory is simply stored to the file.
:param new_storage_service:
New service where you want to migrate to. Leave none if you want to keep the olde one.
:param kwargs:
Additional keyword arguments passed to the service.
For instance, to change the file of the trajectory use ``filename='my_new_file.hdf5``.
"""
if new_name is not None:
self._name = new_name
unused_kwargs = set(kwargs.keys())
if new_storage_service is not None or len(kwargs) > 0:
self._storage_service, unused_kwargs = storage_factory(
storage_service=new_storage_service,
trajectory=self, **kwargs)
if len(unused_kwargs) > 0:
raise ValueError('The following keyword arguments were not used: `%s`' %
str(unused_kwargs))
self._stored = in_store | python | {
"resource": ""
} |
q274221 | Trajectory.f_store | test | def f_store(self, only_init=False, store_data=pypetconstants.STORE_DATA,
max_depth=None):
""" Stores the trajectory to disk and recursively all data in the tree.
:param only_init:
If you just want to initialise the store. If yes, only meta information about
the trajectory is stored and none of the groups/leaves within the trajectory.
Alternatively, you can pass `recursive=False`.
:param store_data:
Only considered if ``only_init=False``. Choose of the following:
* :const:`pypet.pypetconstants.STORE_NOTHING`: (0)
Nothing is store.
* :const:`pypet.pypetconstants.STORE_DATA_SKIPPING`: (1)
Speedy version of normal ``STORE_DATA`` will entirely skip groups
(but not their children) and leaves if they have been stored before.
No new data is added in this case.
* :const:`pypet.pypetconstants.STORE_DATA`: (2)
Stores every group and leave node. If they contain data that is not yet stored
to disk it is added.
* :const:`pypet.pypetconstants.OVERWRITE_DATA`: (3)
Stores all groups and leave nodes and will delete all data on disk
and overwrite it with the current data in RAM.
**NOT RECOMMENDED**! Overwriting data on disk fragments the HDF5 file and
yields badly compressed large files. Better stick to the concept
write once and read many!
If you use the HDF5 Storage Service usually (STORE_DATA (2)) only novel data
is stored to disk.
If you have results that have been stored to disk before only new data items are added and
already present data is NOT overwritten.
Overwriting (OVERWRITE_DATA (3)) existing data with the HDF5 storage service
is not recommended due to fragmentation of the HDF5 file. Better stick to the concept
write once, but read often.
If you want to store individual parameters or results, you might want to
take a look at :func:`~pypet.Trajectory.f_store_items`.
To store whole subtrees of your trajectory check out
:func:`~pypet.naturalnaming.NNGroupNode.f_store_child`.
Note both functions require that your trajectory was stored to disk with `f_store`
at least once before.
**ATTENTION**: Calling `f_store` during a single run the behavior is different.
To avoid re-storing the full trajectory in every single run, which is redundant,
only sub-trees of the trajectory are really stored.
The storage serivce looks for new data that is added below groups called `run_XXXXXXXXXX`
and stores it where `XXXXXXXXX` is the index of this run. The `only_init` parameter is
ignored in this case. You can avoid this behavior by using the argument from below.
:param max_depth:
Maximum depth to store tree (inclusive). During single runs `max_depth` is also counted
from root.
"""
if self._is_run:
if self._new_nodes or self._new_links:
self._storage_service.store(pypetconstants.SINGLE_RUN, self,
trajectory_name=self.v_name,
recursive=not only_init,
store_data=store_data,
max_depth=max_depth)
else:
self._storage_service.store(pypetconstants.TRAJECTORY, self,
trajectory_name=self.v_name,
only_init=only_init,
store_data=store_data,
max_depth=max_depth)
self._stored = True | python | {
"resource": ""
} |
q274222 | Trajectory.f_restore_default | test | def f_restore_default(self):
""" Restores the default value in all explored parameters and sets the
v_idx property back to -1 and v_crun to None."""
self._idx = -1
self._crun = None
for param in self._explored_parameters.values():
if param is not None:
param._restore_default() | python | {
"resource": ""
} |
q274223 | Trajectory._set_explored_parameters_to_idx | test | def _set_explored_parameters_to_idx(self, idx):
""" Notifies the explored parameters what current point in the parameter space
they should represent.
"""
for param in self._explored_parameters.values():
if param is not None:
param._set_parameter_access(idx) | python | {
"resource": ""
} |
q274224 | Trajectory._make_single_run | test | def _make_single_run(self):
""" Modifies the trajectory for single runs executed by the environment """
self._is_run = False # to be able to use f_set_crun
self._new_nodes = OrderedDict()
self._new_links = OrderedDict()
self._is_run = True
return self | python | {
"resource": ""
} |
q274225 | Trajectory.f_get_run_names | test | def f_get_run_names(self, sort=True):
""" Returns a list of run names.
ONLY useful for a single run during multiprocessing if ``v_full_copy` was set to ``True``.
Otherwise only the current run is available.
:param sort:
Whether to get them sorted, will only require O(N) [and not O(N*log N)] since we
use (sort of) bucket sort.
"""
if sort:
return [self.f_idx_to_run(idx) for idx in range(len(self))]
else:
return list(self._run_information.keys()) | python | {
"resource": ""
} |
q274226 | Trajectory.f_get_run_information | test | def f_get_run_information(self, name_or_idx=None, copy=True):
""" Returns a dictionary containing information about a single run.
ONLY useful during a single run if ``v_full_copy` was set to ``True``.
Otherwise only the current run is available.
The information dictionaries have the following key, value pairings:
* completed: Boolean, whether a run was completed
* idx: Index of a run
* timestamp: Timestamp of the run as a float
* time: Formatted time string
* finish_timestamp: Timestamp of the finishing of the run
* runtime: Total runtime of the run in human readable format
* name: Name of the run
* parameter_summary:
A string summary of the explored parameter settings for the particular run
* short_environment_hexsha: The short version of the environment SHA-1 code
If no name or idx is given then a nested dictionary with keys as run names and
info dictionaries as values is returned.
:param name_or_idx: str or int
:param copy:
Whether you want the dictionary used by the trajectory or a copy. Note if
you want the real thing, please do not modify it, i.e. popping or adding stuff. This
could mess up your whole trajectory.
:return:
A run information dictionary or a nested dictionary of information dictionaries
with the run names as keys.
"""
if name_or_idx is None:
if copy:
return cp.deepcopy(self._run_information)
else:
return self._run_information
try:
if copy:
# Since the information dictionaries only contain immutable items
# (float, int, str)
# the normal copy operation is sufficient
return self._run_information[name_or_idx].copy()
else:
return self._run_information[name_or_idx]
except KeyError:
# Maybe the user provided an idx, this would yield a key error and we
# have to convert it to a run name
name_or_idx = self.f_idx_to_run(name_or_idx)
if copy:
return self._run_information[name_or_idx].copy()
else:
return self._run_information[name_or_idx] | python | {
"resource": ""
} |
q274227 | Trajectory.f_find_idx | test | def f_find_idx(self, name_list, predicate):
""" Finds a single run index given a particular condition on parameters.
ONLY useful for a single run if ``v_full_copy` was set to ``True``.
Otherwise a TypeError is thrown.
:param name_list:
A list of parameter names the predicate applies to, if you have only a single
parameter name you can omit the list brackets.
:param predicate:
A lambda predicate for filtering that evaluates to either ``True`` or ``False``
:return: A generator yielding the matching single run indices
Example:
>>> predicate = lambda param1, param2: param1==4 and param2 in [1.0, 2.0]
>>> iterator = traj.f_find_idx(['groupA.param1', 'groupA.param2'], predicate)
>>> [x for x in iterator]
[0, 2, 17, 36]
"""
if self._is_run and not self.v_full_copy:
raise TypeError('You cannot use this function during a multiprocessing signle run and '
'not having ``v_full_copy=True``.')
if isinstance(name_list, str):
name_list = [name_list]
# First create a list of iterators, each over the range of the matched parameters
iter_list = []
for name in name_list:
param = self.f_get(name)
if not param.v_is_parameter:
raise TypeError('`%s` is not a parameter it is a %s, find idx is not applicable' %
(name, str(type(param))))
if param.f_has_range():
iter_list.append(iter(param.f_get_range(copy=False)))
else:
iter_list.append(itools.repeat(param.f_get(), len(self)))
# Create a logical iterator returning `True` or `False`
# whether the user's predicate matches the parameter data
logic_iter = map(predicate, *iter_list)
# Now the run indices are the the indices where `logic_iter` evaluates to `True`
for idx, item in enumerate(logic_iter):
if item:
yield idx | python | {
"resource": ""
} |
q274228 | Trajectory.f_start_run | test | def f_start_run(self, run_name_or_idx=None, turn_into_run=True):
""" Can be used to manually allow running of an experiment without using an environment.
:param run_name_or_idx:
Can manually set a trajectory to a particular run. If `None` the current run
the trajectory is set to is used.
:param turn_into_run:
Turns the trajectory into a run, i.e. reduces functionality but makes storing
more efficient.
"""
if self._run_started:
return self
if run_name_or_idx is None:
if self.v_idx == -1:
raise ValueError('Cannot start run if trajectory is not set to a particular run')
else:
self.f_set_crun(run_name_or_idx)
self._run_started = True
if turn_into_run:
self._make_single_run()
self._set_start()
return self | python | {
"resource": ""
} |
q274229 | Trajectory.f_finalize_run | test | def f_finalize_run(self, store_meta_data=True, clean_up=True):
""" Can be called to finish a run if manually started.
Does NOT reset the index of the run,
i.e. ``f_restore_default`` should be called manually if desired.
Does NOT store any data (except meta data) so you have to call
``f_store`` manually before to avoid data loss.
:param store_meta_data:
If meta data like the runtime should be stored
:param clean_up:
If data added during the run should be cleaned up.
Only works if ``turn_into_run`` was set to ``True``.
"""
if not self._run_started:
return self
self._set_finish()
if clean_up and self._is_run:
self._finalize_run()
self._is_run = False
self._run_started = False
self._updated_run_information.add(self.v_idx)
if store_meta_data:
self.f_store(only_init=True)
return self | python | {
"resource": ""
} |
q274230 | Trajectory._set_start | test | def _set_start(self):
""" Sets the start timestamp and formatted time to the current time. """
init_time = time.time()
formatted_time = datetime.datetime.fromtimestamp(init_time).strftime('%Y_%m_%d_%Hh%Mm%Ss')
run_info_dict = self._run_information[self.v_crun]
run_info_dict['timestamp'] = init_time
run_info_dict['time'] = formatted_time
if self._environment_hexsha is not None:
run_info_dict['short_environment_hexsha'] = self._environment_hexsha[0:7] | python | {
"resource": ""
} |
q274231 | Trajectory._set_finish | test | def _set_finish(self):
""" Sets the finish time and computes the runtime in human readable format """
run_info_dict = self._run_information[self.v_crun]
timestamp_run = run_info_dict['timestamp']
run_summary = self._summarize_explored_parameters()
finish_timestamp_run = time.time()
findatetime = datetime.datetime.fromtimestamp(finish_timestamp_run)
startdatetime = datetime.datetime.fromtimestamp(timestamp_run)
runtime_run = str(findatetime - startdatetime)
run_info_dict['parameter_summary'] = run_summary
run_info_dict['completed'] = 1
run_info_dict['finish_timestamp'] = finish_timestamp_run
run_info_dict['runtime'] = runtime_run | python | {
"resource": ""
} |
q274232 | Trajectory._construct_instance | test | def _construct_instance(self, constructor, full_name, *args, **kwargs):
""" Creates a new node. Checks if the new node needs to know the trajectory.
:param constructor: The constructor to use
:param full_name: Full name of node
:param args: Arguments passed to constructor
:param kwargs: Keyword arguments passed to the constructor
:return:
"""
if getattr(constructor, 'KNOWS_TRAJECTORY', False):
return constructor(full_name, self, *args, **kwargs)
else:
return constructor(full_name, *args, **kwargs) | python | {
"resource": ""
} |
q274233 | Trajectory._return_item_dictionary | test | def _return_item_dictionary(param_dict, fast_access, copy):
"""Returns a dictionary containing either all parameters, all explored parameters,
all config, all derived parameters, or all results.
:param param_dict: The dictionary which is about to be returned
:param fast_access: Whether to use fast access
:param copy: If the original dict should be returned or a shallow copy
:return: The dictionary
:raises: ValueError if `copy=False` and fast_access=True`
"""
if not copy and fast_access:
raise ValueError('You cannot access the original dictionary and use fast access at the'
' same time!')
if not fast_access:
if copy:
return param_dict.copy()
else:
return param_dict
else:
resdict = {}
for key in param_dict:
param = param_dict[key]
val = param.f_get()
resdict[key] = val
return resdict | python | {
"resource": ""
} |
q274234 | Trajectory._finalize_run | test | def _finalize_run(self):
"""Called by the environment after storing to perform some rollback operations.
All results and derived parameters created in the current run are removed.
Important for single processing to not blow up the parent trajectory with the results
of all runs.
"""
self._run_information[self.v_crun]['completed'] = 1
while len(self._new_links):
name_pair, child_parent_pair = self._new_links.popitem(last=False)
parent_node, _ = child_parent_pair
_, link = name_pair
parent_node.f_remove_child(link)
while len(self._new_nodes):
_, child_parent_pair = self._new_nodes.popitem(last=False)
parent, child = child_parent_pair
child_name = child.v_name
parent.f_remove_child(child_name, recursive=True) | python | {
"resource": ""
} |
q274235 | Trajectory.f_get_config | test | def f_get_config(self, fast_access=False, copy=True):
"""Returns a dictionary containing the full config names as keys and the config parameters
or the config parameter data items as values.
:param fast_access:
Determines whether the parameter objects or their values are returned
in the dictionary.
:param copy:
Whether the original dictionary or a shallow copy is returned.
If you want the real dictionary please do not modify it at all!
Not Copying and fast access do not work at the same time! Raises ValueError
if fast access is true and copy false.
:return: Dictionary containing the config data
:raises: ValueError
"""
return self._return_item_dictionary(self._config, fast_access, copy) | python | {
"resource": ""
} |
q274236 | Trajectory.f_get_results | test | def f_get_results(self, fast_access=False, copy=True):
""" Returns a dictionary containing the full result names as keys and the corresponding
result objects or result data items as values.
:param fast_access:
Determines whether the result objects or their values are returned
in the dictionary. Works only for results if they contain a single item with
the name of the result.
:param copy:
Whether the original dictionary or a shallow copy is returned.
If you want the real dictionary please do not modify it at all!
Not Copying and fast access do not work at the same time! Raises ValueError
if fast access is true and copy false.
:return: Dictionary containing the results.
:raises: ValueError
"""
return self._return_item_dictionary(self._results, fast_access, copy) | python | {
"resource": ""
} |
q274237 | Trajectory.f_store_items | test | def f_store_items(self, iterator, *args, **kwargs):
"""Stores individual items to disk.
This function is useful if you calculated very large results (or large derived parameters)
during runtime and you want to write these to disk immediately and empty them afterwards
to free some memory.
Instead of storing individual parameters or results you can also store whole subtrees with
:func:`~pypet.naturalnaming.NNGroupNode.f_store_child`.
You can pass the following arguments to `f_store_items`:
:param iterator:
An iterable containing the parameters or results to store, either their
names or the instances. You can also pass group instances or names here
to store the annotations of the groups.
:param non_empties:
Optional keyword argument (boolean),
if `True` will only store the subset of provided items that are not empty.
Empty parameters or results found in `iterator` are simply ignored.
:param args: Additional arguments passed to the storage service
:param kwargs:
If you use the standard hdf5 storage service, you can pass the following additional
keyword argument:
:param overwrite:
List names of parts of your item that should
be erased and overwritten by the new data in your leaf.
You can also set `overwrite=True`
to overwrite all parts.
For instance:
>>> traj.f_add_result('mygroup.myresult', partA=42, partB=44, partC=46)
>>> traj.f_store()
>>> traj.mygroup.myresult.partA = 333
>>> traj.mygroup.myresult.partB = 'I am going to change to a string'
>>> traj.f_store_item('mygroup.myresult', overwrite=['partA', 'partB'])
Will store `'mygroup.myresult'` to disk again and overwrite the parts
`'partA'` and `'partB'` with the new values `333` and
`'I am going to change to a string'`.
The data stored as `partC` is not changed.
Be aware that you need to specify the names of parts as they were stored
to HDF5. Depending on how your leaf construction works, this may differ
from the names the data might have in your leaf in the trajectory container.
Note that massive overwriting will fragment and blow up your HDF5 file.
Try to avoid changing data on disk whenever you can.
:raises:
TypeError:
If the (parent) trajectory has never been stored to disk. In this case
use :func:`pypet.trajectory.f_store` first.
ValueError: If no item could be found to be stored.
Note if you use the standard hdf5 storage service, there are no additional arguments
or keyword arguments to pass!
"""
if not self._stored:
raise TypeError('Cannot store stuff for a trajectory that has never been '
'stored to disk. Please call traj.f_store(only_init=True) first.')
fetched_items = self._nn_interface._fetch_items(STORE, iterator, args, kwargs)
if fetched_items:
self._storage_service.store(pypetconstants.LIST, fetched_items,
trajectory_name=self.v_name)
else:
raise ValueError('Your storage was not successful, could not find a single item '
'to store.') | python | {
"resource": ""
} |
q274238 | Trajectory.f_load_items | test | def f_load_items(self, iterator, *args, **kwargs):
"""Loads parameters and results specified in `iterator`.
You can directly list the Parameter objects or just their names.
If names are given the `~pypet.naturalnaming.NNGroupNode.f_get` method is applied to find the
parameters or results in the trajectory. Accordingly, the parameters and results
you want to load must already exist in your trajectory (in RAM), probably they
are just empty skeletons waiting desperately to handle data.
If they do not exist in RAM yet, but have been stored to disk before,
you can call :func:`~pypet.trajectory.Trajectory.f_load_skeleton` in order to
bring your trajectory tree skeleton up to date. In case of a single run you can
use the :func:`~pypet.naturalnaming.NNGroupNode.f_load_child` method to recursively
load a subtree without any data.
Then you can load the data of individual results or parameters one by one.
If want to load the whole trajectory at once or ALL results and parameters that are
still empty take a look at :func:`~pypet.trajectory.Trajectory.f_load`.
As mentioned before, to load subtrees of your trajectory you might want to check out
:func:`~pypet.naturalnaming.NNGroupNode.f_load_child`.
To load a list of parameters or results with `f_load_items` you can pass
the following arguments:
:param iterator: A list with parameters or results to be loaded.
:param only_empties:
Optional keyword argument (boolean),
if `True` only empty parameters or results are passed
to the storage service to get loaded. Non-empty parameters or results found in
`iterator` are simply ignored.
:param args: Additional arguments directly passed to the storage service
:param kwargs:
Additional keyword arguments directly passed to the storage service
(except the kwarg `only_empties`)
If you use the standard hdf5 storage service, you can pass the following additional
keyword arguments:
:param load_only:
If you load a result, you can partially load it and ignore the rest of data items.
Just specify the name of the data you want to load. You can also provide a list,
for example `load_only='spikes'`, `load_only=['spikes','membrane_potential']`.
Be aware that you need to specify the names of parts as they were stored
to HDF5. Depending on how your leaf construction works, this may differ
from the names the data might have in your leaf in the trajectory container.
A warning is issued if data specified in `load_only` cannot be found in the
instances specified in `iterator`.
:param load_except:
Analogous to the above, but everything is loaded except names or parts
specified in `load_except`.
You cannot use `load_only` and `load_except` at the same time. If you do
a ValueError is thrown.
A warning is issued if names listed in `load_except` are not part of the
items to load.
"""
if not self._stored:
raise TypeError(
'Cannot load stuff from disk for a trajectory that has never been stored.')
fetched_items = self._nn_interface._fetch_items(LOAD, iterator, args, kwargs)
if fetched_items:
self._storage_service.load(pypetconstants.LIST, fetched_items,
trajectory_name=self.v_name)
else:
self._logger.warning('Your loading was not successful, could not find a single item '
'to load.') | python | {
"resource": ""
} |
q274239 | Trajectory.f_remove_items | test | def f_remove_items(self, iterator, recursive=False):
"""Removes parameters, results or groups from the trajectory.
This function ONLY removes items from your current trajectory and does not delete
data stored to disk. If you want to delete data from disk, take a look at
:func:`~pypet.trajectory.Trajectory.f_delete_items`.
This will also remove all links if items are linked.
:param iterator:
A sequence of items you want to remove. Either the instances themselves
or strings with the names of the items.
:param recursive:
In case you want to remove group nodes, if the children should be removed, too.
"""
# Will format the request in a form that is understood by the storage service
# aka (msg, item, args, kwargs)
fetched_items = self._nn_interface._fetch_items(REMOVE, iterator, (), {})
if fetched_items:
for _, item, dummy1, dummy2 in fetched_items:
self._nn_interface._remove_node_or_leaf(item, recursive=recursive)
else:
self._logger.warning('Your removal was not successful, could not find a single '
'item to remove.') | python | {
"resource": ""
} |
q274240 | Trajectory.f_delete_links | test | def f_delete_links(self, iterator_of_links, remove_from_trajectory=False):
"""Deletes several links from the hard disk.
Links can be passed as a string ``'groupA.groupB.linkA'``
or as a tuple containing the node from which the link should be removed and the
name of the link ``(groupWithLink, 'linkA')``.
"""
to_delete_links = []
group_link_pairs = []
for elem in iterator_of_links:
if isinstance(elem, str):
split_names = elem.split('.')
parent_name = '.'.join(split_names[:-1])
link = split_names[-1]
parent_node = self.f_get(parent_name) if parent_name != '' else self
link_name = parent_node.v_full_name + '.' + link if parent_name != '' else link
to_delete_links.append((pypetconstants.DELETE_LINK, link_name))
group_link_pairs.append((parent_node, link))
else:
link_name = elem[0].v_full_name + '.' + elem[1]
to_delete_links.append((pypetconstants.DELETE_LINK, link_name))
group_link_pairs.append(elem)
try:
self._storage_service.store(pypetconstants.LIST, to_delete_links,
trajectory_name=self.v_name)
except:
self._logger.error('Could not remove `%s` from the trajectory. Maybe the'
' item(s) was/were never stored to disk.' % str(to_delete_links))
raise
if remove_from_trajectory:
for group, link in group_link_pairs:
group.f_remove_link(link) | python | {
"resource": ""
} |
q274241 | Trajectory.f_remove | test | def f_remove(self, recursive=True, predicate=None):
"""Recursively removes all children of the trajectory
:param recursive:
Only here for consistency with signature of parent method. Cannot be set
to `False` because the trajectory root node cannot be removed.
:param predicate:
Predicate which can evaluate for each node to ``True`` in order to remove the node or
``False`` if the node should be kept. Leave ``None`` if you want to remove all nodes.
"""
if not recursive:
raise ValueError('Nice try ;-)')
for child in list(self._children.keys()):
self.f_remove_child(child, recursive=True, predicate=predicate) | python | {
"resource": ""
} |
q274242 | Trajectory.f_delete_items | test | def f_delete_items(self, iterator, *args, **kwargs):
"""Deletes items from storage on disk.
Per default the item is NOT removed from the trajectory.
Links are NOT deleted on the hard disk, please delete links manually before deleting
data!
:param iterator:
A sequence of items you want to remove. Either the instances themselves
or strings with the names of the items.
:param remove_from_trajectory:
If items should also be removed from trajectory. Default is `False`.
:param args: Additional arguments passed to the storage service
:param kwargs: Additional keyword arguments passed to the storage service
If you use the standard hdf5 storage service, you can pass the following additional
keyword argument:
:param delete_only:
You can partially delete leaf nodes. Specify a list of parts of the result node
that should be deleted like `delete_only=['mystuff','otherstuff']`.
This wil only delete the hdf5 sub parts `mystuff` and `otherstuff` from disk.
BE CAREFUL,
erasing data partly happens at your own risk. Depending on how complex the
loading process of your result node is, you might not be able to reconstruct
any data due to partially deleting some of it.
Be aware that you need to specify the names of parts as they were stored
to HDF5. Depending on how your leaf construction works, this may differ
from the names the data might have in your leaf in the trajectory container.
If the hdf5 nodes you specified in `delete_only` cannot be found a warning
is issued.
Note that massive deletion will fragment your HDF5 file.
Try to avoid changing data on disk whenever you can.
If you want to erase a full node, simply ignore this argument or set to `None`.
:param remove_from_item:
If data that you want to delete from storage should also be removed from
the items in `iterator` if they contain these. Default is `False`.
:param recursive:
If you want to delete a group node and it has children you need to
set `recursive` to `True. Default is `False`.
"""
remove_from_trajectory = kwargs.pop('remove_from_trajectory', False)
recursive = kwargs.get('recursive', False)
# Will format the request in a form that is understood by the storage service
# aka (msg, item, args, kwargs)
fetched_items = self._nn_interface._fetch_items(REMOVE, iterator, args, kwargs)
if fetched_items:
try:
self._storage_service.store(pypetconstants.LIST, fetched_items,
trajectory_name=self.v_name)
except:
self._logger.error('Could not remove `%s` from the trajectory. Maybe the'
' item(s) was/were never stored to disk.' % str(fetched_items))
raise
for _, item, dummy1, dummy2 in fetched_items:
if remove_from_trajectory:
self._nn_interface._remove_node_or_leaf(item, recursive=recursive)
else:
item._stored = False
else:
self._logger.warning('Your removal was not successful, could not find a single '
'item to remove.') | python | {
"resource": ""
} |
q274243 | _pool_single_run | test | def _pool_single_run(kwargs):
"""Starts a pool single run and passes the storage service"""
wrap_mode = kwargs['wrap_mode']
traj = kwargs['traj']
traj.v_storage_service = _pool_single_run.storage_service
if wrap_mode == pypetconstants.WRAP_MODE_LOCAL:
# Free references from previous runs
traj.v_storage_service.free_references()
return _sigint_handling_single_run(kwargs) | python | {
"resource": ""
} |
q274244 | _frozen_pool_single_run | test | def _frozen_pool_single_run(kwargs):
"""Single run wrapper for the frozen pool, makes a single run and passes kwargs"""
idx = kwargs.pop('idx')
frozen_kwargs = _frozen_pool_single_run.kwargs
frozen_kwargs.update(kwargs) # in case of `run_map`
# we need to update job's args and kwargs
traj = frozen_kwargs['traj']
traj.f_set_crun(idx)
return _sigint_handling_single_run(frozen_kwargs) | python | {
"resource": ""
} |
q274245 | _configure_pool | test | def _configure_pool(kwargs):
"""Configures the pool and keeps the storage service"""
_pool_single_run.storage_service = kwargs['storage_service']
_configure_niceness(kwargs)
_configure_logging(kwargs, extract=False) | python | {
"resource": ""
} |
q274246 | _configure_frozen_pool | test | def _configure_frozen_pool(kwargs):
"""Configures the frozen pool and keeps all kwargs"""
_frozen_pool_single_run.kwargs = kwargs
_configure_niceness(kwargs)
_configure_logging(kwargs, extract=False)
# Reset full copy to it's old value
traj = kwargs['traj']
traj.v_full_copy = kwargs['full_copy'] | python | {
"resource": ""
} |
q274247 | _process_single_run | test | def _process_single_run(kwargs):
"""Wrapper function that first configures logging and starts a single run afterwards."""
_configure_niceness(kwargs)
_configure_logging(kwargs)
result_queue = kwargs['result_queue']
result = _sigint_handling_single_run(kwargs)
result_queue.put(result)
result_queue.close() | python | {
"resource": ""
} |
q274248 | _configure_frozen_scoop | test | def _configure_frozen_scoop(kwargs):
"""Wrapper function that configures a frozen SCOOP set up.
Deletes of data if necessary.
"""
def _delete_old_scoop_rev_data(old_scoop_rev):
if old_scoop_rev is not None:
try:
elements = shared.elements
for key in elements:
var_dict = elements[key]
if old_scoop_rev in var_dict:
del var_dict[old_scoop_rev]
logging.getLogger('pypet.scoop').debug('Deleted old SCOOP data from '
'revolution `%s`.' % old_scoop_rev)
except AttributeError:
logging.getLogger('pypet.scoop').error('Could not delete old SCOOP data from '
'revolution `%s`.' % old_scoop_rev)
scoop_rev = kwargs.pop('scoop_rev')
# Check if we need to reconfigure SCOOP
try:
old_scoop_rev = _frozen_scoop_single_run.kwargs['scoop_rev']
configured = old_scoop_rev == scoop_rev
except (AttributeError, KeyError):
old_scoop_rev = None
configured = False
if not configured:
_frozen_scoop_single_run.kwargs = shared.getConst(scoop_rev, timeout=424.2)
frozen_kwargs = _frozen_scoop_single_run.kwargs
frozen_kwargs['scoop_rev'] = scoop_rev
frozen_kwargs['traj'].v_full_copy = frozen_kwargs['full_copy']
if not scoop.IS_ORIGIN:
_configure_niceness(frozen_kwargs)
_configure_logging(frozen_kwargs, extract=False)
_delete_old_scoop_rev_data(old_scoop_rev)
logging.getLogger('pypet.scoop').info('Configured Worker %s' % str(scoop.worker)) | python | {
"resource": ""
} |
q274249 | _scoop_single_run | test | def _scoop_single_run(kwargs):
"""Wrapper function for scoop, that does not configure logging"""
try:
try:
is_origin = scoop.IS_ORIGIN
except AttributeError:
# scoop is not properly started, i.e. with `python -m scoop...`
# in this case scoop uses default `map` function, i.e.
# the main process
is_origin = True
if not is_origin:
# configure logging and niceness if not the main process:
_configure_niceness(kwargs)
_configure_logging(kwargs)
return _single_run(kwargs)
except Exception:
scoop.logger.exception('ERROR occurred during a single run!')
raise | python | {
"resource": ""
} |
q274250 | _configure_logging | test | def _configure_logging(kwargs, extract=True):
"""Requests the logging manager to configure logging.
:param extract:
If naming data should be extracted from the trajectory
"""
try:
logging_manager = kwargs['logging_manager']
if extract:
logging_manager.extract_replacements(kwargs['traj'])
logging_manager.make_logging_handlers_and_tools(multiproc=True)
except Exception as exc:
sys.stderr.write('Could not configure logging system because of: %s' % repr(exc))
traceback.print_exc() | python | {
"resource": ""
} |
q274251 | _configure_niceness | test | def _configure_niceness(kwargs):
"""Sets niceness of a process"""
niceness = kwargs['niceness']
if niceness is not None:
try:
try:
current = os.nice(0)
if niceness - current > 0:
# Under Linux you cannot decrement niceness if set elsewhere
os.nice(niceness-current)
except AttributeError:
# Fall back on psutil under Windows
psutil.Process().nice(niceness)
except Exception as exc:
sys.stderr.write('Could not configure niceness because of: %s' % repr(exc))
traceback.print_exc() | python | {
"resource": ""
} |
q274252 | _sigint_handling_single_run | test | def _sigint_handling_single_run(kwargs):
"""Wrapper that allow graceful exits of single runs"""
try:
graceful_exit = kwargs['graceful_exit']
if graceful_exit:
sigint_handling.start()
if sigint_handling.hit:
result = (sigint_handling.SIGINT, None)
else:
result = _single_run(kwargs)
if sigint_handling.hit:
result = (sigint_handling.SIGINT, result)
return result
return _single_run(kwargs)
except:
# Log traceback of exception
pypet_root_logger = logging.getLogger('pypet')
pypet_root_logger.exception('ERROR occurred during a single run! ')
raise | python | {
"resource": ""
} |
q274253 | _single_run | test | def _single_run(kwargs):
""" Performs a single run of the experiment.
:param kwargs: Dict of arguments
traj: The trajectory containing all parameters set to the corresponding run index.
runfunc: The user's job function
runargs: The arguments handed to the user's job function (as *args)
runkwargs: The keyword arguments handed to the user's job function (as **kwargs)
clean_up_after_run: Whether to clean up after the run
automatic_storing: Whether or not the data should be automatically stored
result_queue: A queue object to store results into in case a pool is used, otherwise None
:return:
Results computed by the user's job function which are not stored into the trajectory.
Returns a nested tuple of run index and result and run information:
``((traj.v_idx, result), run_information_dict)``
"""
pypet_root_logger = logging.getLogger('pypet')
traj = kwargs['traj']
runfunc = kwargs['runfunc']
runargs = kwargs['runargs']
kwrunparams = kwargs['runkwargs']
clean_up_after_run = kwargs['clean_up_runs']
automatic_storing = kwargs['automatic_storing']
wrap_mode = kwargs['wrap_mode']
idx = traj.v_idx
total_runs = len(traj)
pypet_root_logger.info('\n=========================================\n '
'Starting single run #%d of %d '
'\n=========================================\n' % (idx, total_runs))
# Measure start time
traj.f_start_run(turn_into_run=True)
# Run the job function of the user
result = runfunc(traj, *runargs, **kwrunparams)
# Store data if desired
if automatic_storing:
traj.f_store()
# Add the index to the result and the run information
if wrap_mode == pypetconstants.WRAP_MODE_LOCAL:
result = ((traj.v_idx, result),
traj.f_get_run_information(traj.v_idx, copy=False),
traj.v_storage_service.references)
traj.v_storage_service.free_references()
else:
result = ((traj.v_idx, result),
traj.f_get_run_information(traj.v_idx, copy=False))
# Measure time of finishing
traj.f_finalize_run(store_meta_data=False,
clean_up=clean_up_after_run)
pypet_root_logger.info('\n=========================================\n '
'Finished single run #%d of %d '
'\n=========================================\n' % (idx, total_runs))
return result | python | {
"resource": ""
} |
q274254 | _wrap_handling | test | def _wrap_handling(kwargs):
""" Starts running a queue handler and creates a log file for the queue."""
_configure_logging(kwargs, extract=False)
# Main job, make the listener to the queue start receiving message for writing to disk.
handler=kwargs['handler']
graceful_exit = kwargs['graceful_exit']
# import cProfile as profile
# profiler = profile.Profile()
# profiler.enable()
if graceful_exit:
sigint_handling.start()
handler.run() | python | {
"resource": ""
} |
q274255 | load_class | test | def load_class(full_class_string):
"""Loads a class from a string naming the module and class name.
For example:
>>> load_class(full_class_string = 'pypet.brian.parameter.BrianParameter')
<BrianParameter>
"""
class_data = full_class_string.split(".")
module_path = ".".join(class_data[:-1])
class_str = class_data[-1]
module = importlib.import_module(module_path)
# We retrieve the Class from the module
return getattr(module, class_str) | python | {
"resource": ""
} |
q274256 | create_class | test | def create_class(class_name, dynamic_imports):
"""Dynamically creates a class.
It is tried if the class can be created by the already given imports.
If not the list of the dynamically loaded classes is used.
"""
try:
new_class = globals()[class_name]
if not inspect.isclass(new_class):
raise TypeError('Not a class!')
return new_class
except (KeyError, TypeError):
for dynamic_class in dynamic_imports:
# Dynamic classes can be provided directly as a Class instance,
# for example as `MyCustomParameter`,
# or as a string describing where to import the class from,
# for instance as `'mypackage.mymodule.MyCustomParameter'`.
if inspect.isclass(dynamic_class):
if class_name == dynamic_class.__name__:
return dynamic_class
else:
# The class name is always the last in an import string,
# e.g. `'mypackage.mymodule.MyCustomParameter'`
class_name_to_test = dynamic_class.split('.')[-1]
if class_name == class_name_to_test:
new_class = load_class(dynamic_class)
return new_class
raise ImportError('Could not create the class named `%s`.' % class_name) | python | {
"resource": ""
} |
q274257 | BaseParameter.f_get_range_length | test | def f_get_range_length(self):
"""Returns the length of the parameter range.
Raises TypeError if the parameter has no range.
Does not need to be implemented if the parameter supports
``__len__`` appropriately.
"""
if not self.f_has_range():
raise TypeError('Not applicable, parameter does not have a range')
elif hasattr(self, '__len__'):
return len(self)
else:
raise NotImplementedError("Should have implemented this.") | python | {
"resource": ""
} |
q274258 | BaseParameter.f_val_to_str | test | def f_val_to_str(self):
"""String summary of the value handled by the parameter.
Note that representing the parameter as a string accesses its value,
but for simpler debugging, this does not lock the parameter or counts as usage!
Calls `__repr__` of the contained value.
"""
old_locked = self._locked
try:
return repr(self.f_get())
except Exception:
return 'No Evaluation possible (yet)!'
finally:
self._locked = old_locked | python | {
"resource": ""
} |
q274259 | BaseParameter._equal_values | test | def _equal_values(self, val1, val2):
"""Checks if the parameter considers two values as equal.
This is important for the trajectory in case of merging. In case you want to delete
duplicate parameter points, the trajectory needs to know when two parameters
are equal. Since equality is not always implemented by values handled by
parameters in the same way, the parameters need to judge whether their values are equal.
The straightforward example here is a numpy array.
Checking for equality of two numpy arrays yields
a third numpy array containing truth values of a piecewise comparison.
Accordingly, the parameter could judge two numpy arrays equal if ALL of the numpy
array elements are equal.
In this BaseParameter class values are considered to be equal if they obey
the function :func:`~pypet.utils.comparisons.nested_equal`.
You might consider implementing a different equality comparison in your subclass.
:raises: TypeError: If both values are not supported by the parameter.
"""
if self.f_supports(val1) != self.f_supports(val2):
return False
if not self.f_supports(val1) and not self.f_supports(val2):
raise TypeError('I do not support the types of both inputs (`%s` and `%s`), '
'therefore I cannot judge whether '
'the two are equal.' % (str(type(val1)), str(type(val2))))
if not self._values_of_same_type(val1, val2):
return False
return comparisons.nested_equal(val1, val2) | python | {
"resource": ""
} |
q274260 | Parameter.f_get_range | test | def f_get_range(self, copy=True):
"""Returns a python iterable containing the exploration range.
:param copy:
If the range should be copied before handed over to avoid tempering with data
Example usage:
>>> param = Parameter('groupA.groupB.myparam',data=22, comment='I am a neat example')
>>> param._explore([42,43,43])
>>> param.f_get_range()
(42,43,44)
:raises: TypeError: If parameter is not explored.
"""
if not self.f_has_range():
raise TypeError('Your parameter `%s` is not array, so cannot return array.' %
self.v_full_name)
elif copy:
return self._explored_range[:]
else:
return self._explored_range | python | {
"resource": ""
} |
q274261 | Parameter._explore | test | def _explore(self, explore_iterable):
"""Explores the parameter according to the iterable.
Raises ParameterLockedException if the parameter is locked.
Raises TypeError if the parameter does not support the data,
the types of the data in the iterable are not the same as the type of the default value,
or the parameter has already an exploration range.
Note that the parameter will iterate over the whole iterable once and store
the individual data values into a tuple. Thus, the whole exploration range is
explicitly stored in memory.
:param explore_iterable: An iterable specifying the exploration range
For example:
>>> param._explore([3.0,2.0,1.0])
>>> param.f_get_range()
(3.0, 2.0, 1.0)
:raises TypeError,ParameterLockedException
"""
if self.v_locked:
raise pex.ParameterLockedException('Parameter `%s` is locked!' % self.v_full_name)
if self.f_has_range():
raise TypeError('Your parameter `%s` is already explored, '
'cannot _explore it further!' % self._name)
if self._data is None:
raise TypeError('Your parameter `%s` has no default value, please specify one '
'via `f_set` before exploration. ' % self.v_full_name)
data_list = self._data_sanity_checks(explore_iterable)
self._explored_range = data_list
self._explored = True
self.f_lock() | python | {
"resource": ""
} |
q274262 | Parameter._expand | test | def _expand(self, explore_iterable):
"""Explores the parameter according to the iterable and appends to the exploration range.
Raises ParameterLockedException if the parameter is locked.
Raises TypeError if the parameter does not support the data,
the types of the data in the iterable are not the same as the type of the default value,
or the parameter did not have an array before.
Note that the parameter will iterate over the whole iterable once and store
the individual data values into a tuple. Thus, the whole exploration range is
explicitly stored in memory.
:param explore_iterable: An iterable specifying the exploration range
For example:
>>> param = Parameter('Im.an.example', data=33.33, comment='Wooohoo!')
>>> param._explore([3.0,2.0,1.0])
>>> param._expand([42.0, 43.42])
>>> param.f_get_range()
>>> [3.0, 2.0, 1.0, 42.0, 43.42]
:raises TypeError, ParameterLockedException
"""
if self.v_locked:
raise pex.ParameterLockedException('Parameter `%s` is locked!' % self.v_full_name)
if not self.f_has_range():
raise TypeError('Your Parameter `%s` is not an array and can therefore '
'not be expanded.' % self._name)
data_list = self._data_sanity_checks(explore_iterable)
self._explored_range.extend(data_list)
self.f_lock() | python | {
"resource": ""
} |
q274263 | Parameter._data_sanity_checks | test | def _data_sanity_checks(self, explore_iterable):
"""Checks if data values are valid.
Checks if the data values are supported by the parameter and if the values are of the same
type as the default value.
"""
data_list = []
for val in explore_iterable:
if not self.f_supports(val):
raise TypeError('%s is of not supported type %s.' % (repr(val), str(type(val))))
if not self._values_of_same_type(val, self._default):
raise TypeError(
'Data of `%s` is not of the same type as the original entry value, '
'new type is %s vs old type %s.' %
(self.v_full_name, str(type(val)), str(type(self._default))))
data_list.append(val)
if len(data_list) == 0:
raise ValueError('Cannot explore an empty list!')
return data_list | python | {
"resource": ""
} |
q274264 | Parameter._store | test | def _store(self):
"""Returns a dictionary of formatted data understood by the storage service.
The data is put into an :class:`~pypet.parameter.ObjectTable` named 'data'.
If the parameter is explored, the exploration range is also put into another table
named 'explored_data'.
:return: Dictionary containing the data and optionally the exploration range.
"""
if self._data is not None:
store_dict = {'data': ObjectTable(data={'data': [self._data]})}
if self.f_has_range():
store_dict['explored_data'] = ObjectTable(data={'data': self._explored_range})
self._locked = True
return store_dict | python | {
"resource": ""
} |
q274265 | Parameter._load | test | def _load(self, load_dict):
"""Loads the data and exploration range from the `load_dict`.
The `load_dict` needs to be in the same format as the result of the
:func:`~pypet.parameter.Parameter._store` method.
"""
if self.v_locked:
raise pex.ParameterLockedException('Parameter `%s` is locked!' % self.v_full_name)
if 'data' in load_dict:
self._data = load_dict['data']['data'][0]
self._default = self._data
else:
self._logger.warning('Your parameter `%s` is empty, '
'I did not find any data on disk.' % self.v_full_name)
if 'explored_data' in load_dict:
self._explored_range = [x for x in load_dict['explored_data']['data'].tolist()]
self._explored = True
self._locked = True | python | {
"resource": ""
} |
q274266 | ArrayParameter._load | test | def _load(self, load_dict):
"""Reconstructs the data and exploration array.
Checks if it can find the array identifier in the `load_dict`, i.e. '__rr__'.
If not calls :class:`~pypet.parameter.Parameter._load` of the parent class.
If the parameter is explored, the exploration range of arrays is reconstructed
as it was stored in :func:`~pypet.parameter.ArrayParameter._store`.
"""
if self.v_locked:
raise pex.ParameterLockedException('Parameter `%s` is locked!' % self.v_full_name)
try:
self._data = load_dict['data' + ArrayParameter.IDENTIFIER]
if 'explored_data' + ArrayParameter.IDENTIFIER in load_dict:
explore_table = load_dict['explored_data' + ArrayParameter.IDENTIFIER]
idx = explore_table['idx']
explore_list = []
# Recall the arrays in the order stored in the ObjectTable 'explored_data__rr__'
for name_idx in idx:
arrayname = self._build_name(name_idx)
explore_list.append(load_dict[arrayname])
self._explored_range = [x for x in explore_list]
self._explored = True
except KeyError:
super(ArrayParameter, self)._load(load_dict)
self._default = self._data
self._locked = True | python | {
"resource": ""
} |
q274267 | SparseParameter._equal_values | test | def _equal_values(self, val1, val2):
"""Matrices are equal if they hash to the same value."""
if self._is_supported_matrix(val1):
if self._is_supported_matrix(val2):
_, _, hash_tuple_1 = self._serialize_matrix(val1)
_, _, hash_tuple_2 = self._serialize_matrix(val2)
return hash(hash_tuple_1) == hash(hash_tuple_2)
else:
return False
else:
return super(SparseParameter, self)._equal_values(val1, val2) | python | {
"resource": ""
} |
q274268 | SparseParameter._is_supported_matrix | test | def _is_supported_matrix(data):
"""Checks if a data is csr, csc, bsr, or dia Scipy sparse matrix"""
return (spsp.isspmatrix_csc(data) or
spsp.isspmatrix_csr(data) or
spsp.isspmatrix_bsr(data) or
spsp.isspmatrix_dia(data)) | python | {
"resource": ""
} |
q274269 | SparseParameter._serialize_matrix | test | def _serialize_matrix(matrix):
"""Extracts data from a sparse matrix to make it serializable in a human readable format.
:return: Tuple with following elements:
1.
A list containing data that is necessary to reconstruct the matrix.
For csr, csc, and bsr matrices the following attributes are extracted:
`format`, `data`, `indices`, `indptr`, `shape`.
Where format is simply one of the strings 'csr', 'csc', or 'bsr'.
For dia matrices the following attributes are extracted:
`format`, `data`, `offsets`, `shape`.
Where `format` is simply the string 'dia'.
2.
A list containing the names of the extracted attributes.
For csr, csc, and bsr:
[`format`, `data`, `indices`, `indptr`, `shape`]
For dia:
[`format`, `data`, `offsets`, `shape`]
3.
A tuple containing the hashable parts of (1) in order to use the tuple as
a key for a dictionary. Accordingly, the numpy arrays of (1) are
changed to read-only.
"""
if (spsp.isspmatrix_csc(matrix) or
spsp.isspmatrix_csr(matrix) or
spsp.isspmatrix_bsr(matrix)):
if matrix.size > 0:
return_list = [matrix.data, matrix.indices, matrix.indptr, matrix.shape]
else:
# For empty matrices we only need the shape
return_list = ['__empty__', (), (), matrix.shape]
return_names = SparseParameter.OTHER_NAME_LIST
if spsp.isspmatrix_csc(matrix):
return_list = ['csc'] + return_list
elif spsp.isspmatrix_csr(matrix):
return_list = ['csr'] + return_list
elif spsp.isspmatrix_bsr(matrix):
return_list = ['bsr'] + return_list
else:
raise RuntimeError('You shall not pass!')
elif spsp.isspmatrix_dia(matrix):
if matrix.size > 0:
return_list = ['dia', matrix.data, matrix.offsets, matrix.shape]
else:
# For empty matrices we only need the shape
return_list = ['dia', '__empty__', (), matrix.shape]
return_names = SparseParameter.DIA_NAME_LIST
else:
raise RuntimeError('You shall not pass!')
hash_list = []
# Extract the `data` property of a read-only numpy array in order to have something
# hashable.
for item in return_list:
if type(item) is np.ndarray:
# item.flags.writeable = False
hash_list.append(HashArray(item))
else:
hash_list.append(item)
return return_list, return_names, tuple(hash_list) | python | {
"resource": ""
} |
q274270 | SparseParameter._build_names | test | def _build_names(self, name_idx, is_dia):
"""Formats a name for storage
:return: A tuple of names with the following format:
`xspm__spsp__XXXX__spsp__XXXXXXXX` where the first 'XXXX' refer to the property and
the latter 'XXXXXXX' to the sparse matrix index.
"""
name_list = self._get_name_list(is_dia)
return tuple(['explored%s.set_%05d.xspm_%s_%08d' % (SparseParameter.IDENTIFIER,
name_idx // 200, name, name_idx)
for name in name_list]) | python | {
"resource": ""
} |
q274271 | SparseParameter._reconstruct_matrix | test | def _reconstruct_matrix(data_list):
"""Reconstructs a matrix from a list containing sparse matrix extracted properties
`data_list` needs to be formatted as the first result of
:func:`~pypet.parameter.SparseParameter._serialize_matrix`
"""
matrix_format = data_list[0]
data = data_list[1]
is_empty = isinstance(data, str) and data == '__empty__'
if matrix_format == 'csc':
if is_empty:
return spsp.csc_matrix(data_list[4])
else:
return spsp.csc_matrix(tuple(data_list[1:4]), shape=data_list[4])
elif matrix_format == 'csr':
if is_empty:
return spsp.csr_matrix(data_list[4])
else:
return spsp.csr_matrix(tuple(data_list[1:4]), shape=data_list[4])
elif matrix_format == 'bsr':
if is_empty:
# We have an empty matrix, that cannot be build as in elee case
return spsp.bsr_matrix(data_list[4])
else:
return spsp.bsr_matrix(tuple(data_list[1:4]), shape=data_list[4])
elif matrix_format == 'dia':
if is_empty:
return spsp.dia_matrix(data_list[3])
else:
return spsp.dia_matrix(tuple(data_list[1:3]), shape=data_list[3])
else:
raise RuntimeError('You shall not pass!') | python | {
"resource": ""
} |
q274272 | SparseParameter._load | test | def _load(self, load_dict):
"""Reconstructs the data and exploration array
Checks if it can find the array identifier in the `load_dict`, i.e. '__spsp__'.
If not, calls :class:`~pypet.parameter.ArrayParameter._load` of the parent class.
If the parameter is explored, the exploration range of matrices is reconstructed
as it was stored in :func:`~pypet.parameter.SparseParameter._store`.
"""
if self.v_locked:
raise pex.ParameterLockedException('Parameter `%s` is locked!' % self.v_full_name)
try:
is_dia = load_dict['data%sis_dia' % SparseParameter.IDENTIFIER]
name_list = self._get_name_list(is_dia)
rename_list = ['data%s%s' % (SparseParameter.IDENTIFIER, name)
for name in name_list]
data_list = [load_dict[name] for name in rename_list]
self._data = self._reconstruct_matrix(data_list)
if 'explored_data' + SparseParameter.IDENTIFIER in load_dict:
explore_table = load_dict['explored_data' + SparseParameter.IDENTIFIER]
idx_col = explore_table['idx']
dia_col = explore_table['is_dia']
explore_list = []
for irun, name_id in enumerate(idx_col):
is_dia = dia_col[irun]
# To make everything work with the old format we have the try catch block
try:
name_list = self._build_names(name_id, is_dia)
data_list = [load_dict[name] for name in name_list]
except KeyError:
name_list = self._build_names_old(name_id, is_dia)
data_list = [load_dict[name] for name in name_list]
matrix = self._reconstruct_matrix(data_list)
explore_list.append(matrix)
self._explored_range = explore_list
self._explored = True
except KeyError:
super(SparseParameter, self)._load(load_dict)
self._default = self._data
self._locked = True | python | {
"resource": ""
} |
q274273 | PickleParameter._store | test | def _store(self):
"""Returns a dictionary for storage.
Every element in the dictionary except for 'explored_data' is a pickle dump.
Reusage of objects is identified over the object id, i.e. python's built-in id function.
'explored_data' contains the references to the objects to be able to recall the
order of objects later on.
"""
store_dict = {}
if self._data is not None:
dump = pickle.dumps(self._data, protocol=self.v_protocol)
store_dict['data'] = dump
store_dict[PickleParameter.PROTOCOL] = self.v_protocol
if self.f_has_range():
store_dict['explored_data'] = \
ObjectTable(columns=['idx'], index=list(range(len(self))))
smart_dict = {}
count = 0
for idx, val in enumerate(self._explored_range):
obj_id = id(val)
if obj_id in smart_dict:
name_id = smart_dict[obj_id]
add = False
else:
name_id = count
add = True
name = self._build_name(name_id)
store_dict['explored_data']['idx'][idx] = name_id
if add:
store_dict[name] = pickle.dumps(val, protocol=self.v_protocol)
smart_dict[obj_id] = name_id
count += 1
self._locked = True
return store_dict | python | {
"resource": ""
} |
q274274 | PickleParameter._load | test | def _load(self, load_dict):
"""Reconstructs objects from the pickle dumps in `load_dict`.
The 'explored_data' entry in `load_dict` is used to reconstruct
the exploration range in the correct order.
Sets the `v_protocol` property to the protocol used to store 'data'.
"""
if self.v_locked:
raise pex.ParameterLockedException('Parameter `%s` is locked!' % self.v_full_name)
if 'data' in load_dict:
dump = load_dict['data']
self._data = pickle.loads(dump)
else:
self._logger.warning('Your parameter `%s` is empty, '
'I did not find any data on disk.' % self.v_full_name)
try:
self.v_protocol = load_dict[PickleParameter.PROTOCOL]
except KeyError:
# For backwards compatibility
self.v_protocol = PickleParameter._get_protocol(dump)
if 'explored_data' in load_dict:
explore_table = load_dict['explored_data']
name_col = explore_table['idx']
explore_list = []
for name_id in name_col:
arrayname = self._build_name(name_id)
loaded = pickle.loads(load_dict[arrayname])
explore_list.append(loaded)
self._explored_range = explore_list
self._explored = True
self._default = self._data
self._locked = True | python | {
"resource": ""
} |
q274275 | Result.f_translate_key | test | def f_translate_key(self, key):
"""Translates integer indices into the appropriate names"""
if isinstance(key, int):
if key == 0:
key = self.v_name
else:
key = self.v_name + '_%d' % key
return key | python | {
"resource": ""
} |
q274276 | Result.f_val_to_str | test | def f_val_to_str(self):
"""Summarizes data handled by the result as a string.
Calls `__repr__` on all handled data. Data is NOT ordered.
Truncates the string if it is longer than
:const:`pypetconstants.HDF5_STRCOL_MAX_VALUE_LENGTH`
:return: string
"""
resstrlist = []
strlen = 0
for key in self._data:
val = self._data[key]
resstr = '%s=%s, ' % (key, repr(val))
resstrlist.append(resstr)
strlen += len(resstr)
if strlen > pypetconstants.HDF5_STRCOL_MAX_VALUE_LENGTH:
break
return_string = "".join(resstrlist)
if len(return_string) > pypetconstants.HDF5_STRCOL_MAX_VALUE_LENGTH:
return_string =\
return_string[0:pypetconstants.HDF5_STRCOL_MAX_VALUE_LENGTH - 3] + '...'
else:
return_string = return_string[0:-2] # Delete the last `, `
return return_string | python | {
"resource": ""
} |
q274277 | Result.f_to_dict | test | def f_to_dict(self, copy=True):
"""Returns all handled data as a dictionary.
:param copy:
Whether the original dictionary or a shallow copy is returned.
:return: Data dictionary
"""
if copy:
return self._data.copy()
else:
return self._data | python | {
"resource": ""
} |
q274278 | Result.f_set | test | def f_set(self, *args, **kwargs):
""" Method to put data into the result.
:param args:
The first positional argument is stored with the name of the result.
Following arguments are stored with `name_X` where `X` is the position
of the argument.
:param kwargs: Arguments are stored with the key as name.
:raises: TypeError if outer data structure is not understood.
Example usage:
>>> res = Result('supergroup.subgroup.myresult', comment='I am a neat example!')
>>> res.f_set(333,42.0, mystring='String!')
>>> res.f_get('myresult')
333
>>> res.f_get('myresult_1')
42.0
>>> res.f_get(1)
42.0
>>> res.f_get('mystring')
'String!'
"""
if args and self.v_name is None:
raise AttributeError('Cannot set positional value because I do not have a name!')
for idx, arg in enumerate(args):
valstr = self.f_translate_key(idx)
self.f_set_single(valstr, arg)
for key, arg in kwargs.items():
self.f_set_single(key, arg) | python | {
"resource": ""
} |
q274279 | Result.f_get | test | def f_get(self, *args):
"""Returns items handled by the result.
If only a single name is given, a single data item is returned. If several names are
given, a list is returned. For integer inputs the result returns `resultname_X`.
If the result contains only a single entry you can call `f_get()` without arguments.
If you call `f_get()` and the result contains more than one element a ValueError is
thrown.
If the requested item(s) cannot be found an AttributeError is thrown.
:param args: strings-names or integers
:return: Single data item or tuple of data
Example:
>>> res = Result('supergroup.subgroup.myresult', comment='I am a neat example!' \
[1000,2000], {'a':'b','c':333}, hitchhiker='Arthur Dent')
>>> res.f_get('hitchhiker')
'Arthur Dent'
>>> res.f_get(0)
[1000,2000]
>>> res.f_get('hitchhiker', 'myresult')
('Arthur Dent', [1000,2000])
"""
if len(args) == 0:
if len(self._data) == 1:
return list(self._data.values())[0]
elif len(self._data) > 1:
raise ValueError('Your result `%s` contains more than one entry: '
'`%s` Please use >>f_get<< with one of these.' %
(self.v_full_name, str(list(self._data.keys()))))
else:
raise AttributeError('Your result `%s` is empty, cannot access data.' %
self.v_full_name)
result_list = []
for name in args:
name = self.f_translate_key(name)
if not name in self._data:
if name == 'data' and len(self._data) == 1:
return self._data[list(self._data.keys())[0]]
else:
raise AttributeError('`%s` is not part of your result `%s`.' %
(name, self.v_full_name))
result_list.append(self._data[name])
if len(args) == 1:
return result_list[0]
else:
return result_list | python | {
"resource": ""
} |
q274280 | Result.f_set_single | test | def f_set_single(self, name, item):
"""Sets a single data item of the result.
Raises TypeError if the type of the outer data structure is not understood.
Note that the type check is shallow. For example, if the data item is a list,
the individual list elements are NOT checked whether their types are appropriate.
:param name: The name of the data item
:param item: The data item
:raises: TypeError
Example usage:
>>> res.f_set_single('answer', 42)
>>> res.f_get('answer')
42
"""
if self.v_stored:
self._logger.debug('You are changing an already stored result. If '
'you not explicitly overwrite the data on disk, this change '
'might be lost and not propagated to disk.')
if self._supports(item):
# self._check_if_empty(item, name) # No longer needed
if name in self._data:
self._logger.debug('Replacing `%s` in result `%s`.' % (name, self.v_full_name))
self._data[name] = item
else:
raise TypeError('Your result `%s` of type `%s` is not supported.' %
(name, str(type(item)))) | python | {
"resource": ""
} |
q274281 | SparseResult._supports | test | def _supports(self, item):
"""Supports everything of parent class and csr, csc, bsr, and dia sparse matrices."""
if SparseParameter._is_supported_matrix(item):
return True
else:
return super(SparseResult, self)._supports(item) | python | {
"resource": ""
} |
q274282 | SparseResult._store | test | def _store(self):
"""Returns a storage dictionary understood by the storage service.
Sparse matrices are extracted similar to the :class:`~pypet.parameter.SparseParameter` and
marked with the identifier `__spsp__`.
"""
store_dict = {}
for key in self._data:
val = self._data[key]
if SparseParameter._is_supported_matrix(val):
data_list, name_list, hash_tuple = SparseParameter._serialize_matrix(val)
rename_list = ['%s%s%s' % (key, SparseParameter.IDENTIFIER, name)
for name in name_list]
is_dia = int(len(rename_list) == 4)
store_dict[key + SparseResult.IDENTIFIER + 'is_dia'] = is_dia
for idx, name in enumerate(rename_list):
store_dict[name] = data_list[idx]
else:
store_dict[key] = val
return store_dict | python | {
"resource": ""
} |
q274283 | SparseResult._load | test | def _load(self, load_dict):
"""Loads data from `load_dict`
Reconstruction of sparse matrices similar to the :class:`~pypet.parameter.SparseParameter`.
"""
for key in list(load_dict.keys()):
# We delete keys over time:
if key in load_dict:
if SparseResult.IDENTIFIER in key:
new_key = key.split(SparseResult.IDENTIFIER)[0]
is_dia = load_dict.pop(new_key + SparseResult.IDENTIFIER + 'is_dia')
name_list = SparseParameter._get_name_list(is_dia)
rename_list = ['%s%s%s' % (new_key, SparseResult.IDENTIFIER, name)
for name in name_list]
data_list = [load_dict.pop(name) for name in rename_list]
matrix = SparseParameter._reconstruct_matrix(data_list)
self._data[new_key] = matrix
else:
self._data[key] = load_dict[key] | python | {
"resource": ""
} |
q274284 | PickleResult.f_set_single | test | def f_set_single(self, name, item):
"""Adds a single data item to the pickle result.
Note that it is NOT checked if the item can be pickled!
"""
if self.v_stored:
self._logger.debug('You are changing an already stored result. If '
'you not explicitly overwrite the data on disk, this change '
'might be lost and not propagated to disk.')
if name == PickleResult.PROTOCOL:
raise AttributeError('You cannot name an entry `%s`' % PickleResult.PROTOCOL)
self._data[name] = item | python | {
"resource": ""
} |
q274285 | PickleResult._store | test | def _store(self):
"""Returns a dictionary containing pickle dumps"""
store_dict = {}
for key, val in self._data.items():
store_dict[key] = pickle.dumps(val, protocol=self.v_protocol)
store_dict[PickleResult.PROTOCOL] = self.v_protocol
return store_dict | python | {
"resource": ""
} |
q274286 | PickleResult._load | test | def _load(self, load_dict):
"""Reconstructs all items from the pickle dumps in `load_dict`.
Sets the `v_protocol` property to the protocol of the first reconstructed item.
"""
try:
self.v_protocol = load_dict.pop(PickleParameter.PROTOCOL)
except KeyError:
# For backwards compatibility
dump = next(load_dict.values())
self.v_protocol = PickleParameter._get_protocol(dump)
for key in load_dict:
val = load_dict[key]
self._data[key] = pickle.loads(val) | python | {
"resource": ""
} |
q274287 | main | test | def main():
"""Simply merge all trajectories in the working directory"""
folder = os.getcwd()
print('Merging all files')
merge_all_in_folder(folder,
delete_other_files=True, # We will only keep one trajectory
dynamic_imports=FunctionParameter,
backup=False)
print('Done') | python | {
"resource": ""
} |
q274288 | upload_file | test | def upload_file(filename, session):
""" Uploads a file """
print('Uploading file %s' % filename)
outfilesource = os.path.join(os.getcwd(), filename)
outfiletarget = 'sftp://' + ADDRESS + WORKING_DIR
out = saga.filesystem.File(outfilesource, session=session, flags=OVERWRITE)
out.copy(outfiletarget)
print('Transfer of `%s` to `%s` successful' % (filename, outfiletarget)) | python | {
"resource": ""
} |
q274289 | download_file | test | def download_file(filename, session):
""" Downloads a file """
print('Downloading file %s' % filename)
infilesource = os.path.join('sftp://' + ADDRESS + WORKING_DIR,
filename)
infiletarget = os.path.join(os.getcwd(), filename)
incoming = saga.filesystem.File(infilesource, session=session, flags=OVERWRITE)
incoming.copy(infiletarget)
print('Transfer of `%s` to `%s` successful' % (filename, infiletarget)) | python | {
"resource": ""
} |
q274290 | create_session | test | def create_session():
""" Creates and returns a new SAGA session """
ctx = saga.Context("UserPass")
ctx.user_id = USER
ctx.user_pass = PASSWORD
session = saga.Session()
session.add_context(ctx)
return session | python | {
"resource": ""
} |
q274291 | merge_trajectories | test | def merge_trajectories(session):
""" Merges all trajectories found in the working directory """
jd = saga.job.Description()
jd.executable = 'python'
jd.arguments = ['merge_trajs.py']
jd.output = "mysagajob_merge.stdout"
jd.error = "mysagajob_merge.stderr"
jd.working_directory = WORKING_DIR
js = saga.job.Service('ssh://' + ADDRESS, session=session)
myjob = js.create_job(jd)
print("\n...starting job...\n")
# Now we can start our job.
myjob.run()
print("Job ID : %s" % (myjob.id))
print("Job State : %s" % (myjob.state))
print("\n...waiting for job...\n")
# wait for the job to either finish or fail
myjob.wait()
print("Job State : %s" % (myjob.state))
print("Exitcode : %s" % (myjob.exit_code)) | python | {
"resource": ""
} |
q274292 | start_jobs | test | def start_jobs(session):
""" Starts all jobs and runs `the_task.py` in batches. """
js = saga.job.Service('ssh://' + ADDRESS, session=session)
batches = range(3)
jobs = []
for batch in batches:
print('Starting batch %d' % batch)
jd = saga.job.Description()
jd.executable = 'python'
jd.arguments = ['the_task.py --batch=' + str(batch)]
jd.output = "mysagajob.stdout" + str(batch)
jd.error = "mysagajob.stderr" + str(batch)
jd.working_directory = WORKING_DIR
myjob = js.create_job(jd)
print("Job ID : %s" % (myjob.id))
print("Job State : %s" % (myjob.state))
print("\n...starting job...\n")
myjob.run()
jobs.append(myjob)
for myjob in jobs:
print("Job ID : %s" % (myjob.id))
print("Job State : %s" % (myjob.state))
print("\n...waiting for job...\n")
# wait for the job to either finish or fail
myjob.wait()
print("Job State : %s" % (myjob.state))
print("Exitcode : %s" % (myjob.exit_code)) | python | {
"resource": ""
} |
q274293 | multiply | test | def multiply(traj):
"""Sophisticated simulation of multiplication"""
z=traj.x*traj.y
traj.f_add_result('z',z=z, comment='I am the product of two reals!') | python | {
"resource": ""
} |
q274294 | run_neuron | test | def run_neuron(traj):
"""Runs a simulation of a model neuron.
:param traj:
Container with all parameters.
:return:
An estimate of the firing rate of the neuron
"""
# Extract all parameters from `traj`
V_init = traj.par.neuron.V_init
I = traj.par.neuron.I
tau_V = traj.par.neuron.tau_V
tau_ref = traj.par.neuron.tau_ref
dt = traj.par.simulation.dt
duration = traj.par.simulation.duration
steps = int(duration / float(dt))
# Create some containers for the Euler integration
V_array = np.zeros(steps)
V_array[0] = V_init
spiketimes = [] # List to collect all times of action potentials
# Do the Euler integration:
print('Starting Euler Integration')
for step in range(1, steps):
if V_array[step-1] >= 1:
# The membrane potential crossed the threshold and we mark this as
# an action potential
V_array[step] = 0
spiketimes.append((step-1)*dt)
elif spiketimes and step * dt - spiketimes[-1] <= tau_ref:
# We are in the refractory period, so we simply clamp the voltage
# to 0
V_array[step] = 0
else:
# Euler Integration step:
dV = -1/tau_V * V_array[step-1] + I
V_array[step] = V_array[step-1] + dV*dt
print('Finished Euler Integration')
# Add the voltage trace and spike times
traj.f_add_result('neuron.$', V=V_array, nspikes=len(spiketimes),
comment='Contains the development of the membrane potential over time '
'as well as the number of spikes.')
# This result will be renamed to `traj.results.neuron.run_XXXXXXXX`.
# And finally we return the estimate of the firing rate
return len(spiketimes) / float(traj.par.simulation.duration) *1000 | python | {
"resource": ""
} |
q274295 | neuron_postproc | test | def neuron_postproc(traj, result_list):
"""Postprocessing, sorts computed firing rates into a table
:param traj:
Container for results and parameters
:param result_list:
List of tuples, where first entry is the run index and second is the actual
result of the corresponding run.
:return:
"""
# Let's create a pandas DataFrame to sort the computed firing rate according to the
# parameters. We could have also used a 2D numpy array.
# But a pandas DataFrame has the advantage that we can index into directly with
# the parameter values without translating these into integer indices.
I_range = traj.par.neuron.f_get('I').f_get_range()
ref_range = traj.par.neuron.f_get('tau_ref').f_get_range()
I_index = sorted(set(I_range))
ref_index = sorted(set(ref_range))
rates_frame = pd.DataFrame(columns=ref_index, index=I_index)
# This frame is basically a two dimensional table that we can index with our
# parameters
# Now iterate over the results. The result list is a list of tuples, with the
# run index at first position and our result at the second
for result_tuple in result_list:
run_idx = result_tuple[0]
firing_rates = result_tuple[1]
I_val = I_range[run_idx]
ref_val = ref_range[run_idx]
rates_frame.loc[I_val, ref_val] = firing_rates # Put the firing rate into the
# data frame
# Finally we going to store our new firing rate table into the trajectory
traj.f_add_result('summary.firing_rates', rates_frame=rates_frame,
comment='Contains a pandas data frame with all firing rates.') | python | {
"resource": ""
} |
q274296 | add_parameters | test | def add_parameters(traj):
"""Adds all parameters to `traj`"""
print('Adding Parameters')
traj.f_add_parameter('neuron.V_init', 0.0,
comment='The initial condition for the '
'membrane potential')
traj.f_add_parameter('neuron.I', 0.0,
comment='The externally applied current.')
traj.f_add_parameter('neuron.tau_V', 10.0,
comment='The membrane time constant in milliseconds')
traj.f_add_parameter('neuron.tau_ref', 5.0,
comment='The refractory period in milliseconds '
'where the membrane potnetial '
'is clamped.')
traj.f_add_parameter('simulation.duration', 1000.0,
comment='The duration of the experiment in '
'milliseconds.')
traj.f_add_parameter('simulation.dt', 0.1,
comment='The step size of an Euler integration step.') | python | {
"resource": ""
} |
q274297 | add_exploration | test | def add_exploration(traj):
"""Explores different values of `I` and `tau_ref`."""
print('Adding exploration of I and tau_ref')
explore_dict = {'neuron.I': np.arange(0, 1.01, 0.01).tolist(),
'neuron.tau_ref': [5.0, 7.5, 10.0]}
explore_dict = cartesian_product(explore_dict, ('neuron.tau_ref', 'neuron.I'))
# The second argument, the tuple, specifies the order of the cartesian product,
# The variable on the right most side changes fastest and defines the
# 'inner for-loop' of the cartesian product
traj.f_explore(explore_dict) | python | {
"resource": ""
} |
q274298 | NetworkRunner.execute_network_pre_run | test | def execute_network_pre_run(self, traj, network, network_dict, component_list, analyser_list):
"""Runs a network before the actual experiment.
Called by a :class:`~pypet.brian2.network.NetworkManager`.
Similar to :func:`~pypet.brian2.network.NetworkRunner.run_network`.
Subruns and their durations are extracted from the trajectory. All
:class:`~pypet.brian2.parameter.Brian2Parameter` instances found under
`traj.parameters.simulation.pre_durations` (default, you can change the
name of the group where to search for durations at runner initialisation).
The order is determined from
the `v_annotations.order` attributes. There must be at least one subrun in the trajectory,
otherwise an AttributeError is thrown. If two subruns equal in their order
property a RuntimeError is thrown.
:param traj: Trajectory container
:param network: BRIAN2 network
:param network_dict: Dictionary of items shared among all components
:param component_list: List of :class:`~pypet.brian2.network.NetworkComponent` objects
:param analyser_list: List of :class:`~pypet.brian2.network.NetworkAnalyser` objects
"""
self._execute_network_run(traj, network, network_dict, component_list, analyser_list,
pre_run=True) | python | {
"resource": ""
} |
q274299 | NetworkRunner.execute_network_run | test | def execute_network_run(self, traj, network, network_dict, component_list, analyser_list):
"""Runs a network in an experimental run.
Called by a :class:`~pypet.brian2.network.NetworkManager`.
A network run is divided into several subruns which are defined as
:class:`~pypet.brian2.parameter.Brian2Parameter` instances.
These subruns are extracted from the trajectory. All
:class:`~pypet.brian2.parameter.Brian2Parameter` instances found under
`traj.parameters.simulation.durations` (default, you can change the
name of the group where to search for durations at runner initialisation).
The order is determined from
the `v_annotations.order` attributes. An error is thrown if no orders attribute
can be found or if two parameters have the same order.
There must be at least one subrun in the trajectory,
otherwise an AttributeError is thrown. If two subruns equal in their order
property a RuntimeError is thrown.
For every subrun the following steps are executed:
1. Calling :func:`~pypet.brian2.network.NetworkComponent.add_to_network` for every
every :class:`~pypet.brian2.network.NetworkComponent` in the order as
they were passed to the :class:`~pypet.brian2.network.NetworkManager`.
2. Calling :func:`~pypet.brian2.network.NetworkComponent.add_to_network` for every
every :class:`~pypet.brian2.network.NetworkAnalyser` in the order as
they were passed to the :class:`~pypet.brian2.network.NetworkManager`.
3. Calling :func:`~pypet.brian2.network.NetworkComponent.add_to_network` of the
NetworkRunner itself (usually the network runner should not add or remove
anything from the network, but this step is executed for completeness).
4. Running the BRIAN2 network for the duration of the current subrun by calling
the network's `run` function.
5. Calling :func:`~pypet.brian2.network.NetworkAnalyser.analyse` for every
every :class:`~pypet.brian2.network.NetworkAnalyser` in the order as
they were passed to the :class:`~pypet.brian2.network.NetworkManager`.
6. Calling :func:`~pypet.brian2.network.NetworkComponent.remove_from_network` of the
NetworkRunner itself (usually the network runner should not add or remove
anything from the network, but this step is executed for completeness).
7. Calling :func:`~pypet.brian2.network.NetworkComponent.remove_from_network` for every
every :class:`~pypet.brian2.network.NetworkAnalyser` in the order as
they were passed to the :class:`~pypet.brian2.network.NetworkManager`
8. Calling :func:`~pypet.brian2.network.NetworkComponent.remove_from_network` for every
every :class:`~pypet.brian2.network.NetworkComponent` in the order as
they were passed to the :class:`~pypet.brian2.network.NetworkManager`.
These 8 steps are repeated for every subrun in the `subrun_list`.
The `subrun_list` passed to all `add_to_network`, `analyse` and
`remove_from_network` methods can be modified
within these functions to potentially alter the order of execution or
even erase or add upcoming subruns if necessary.
For example, a NetworkAnalyser checks
for epileptic pathological activity and cancels all coming subruns in case
of undesired network dynamics.
:param traj: Trajectory container
:param network: BRIAN2 network
:param network_dict: Dictionary of items shared among all components
:param component_list: List of :class:`~pypet.brian2.network.NetworkComponent` objects
:param analyser_list: List of :class:`~pypet.brian2.network.NetworkAnalyser` objects
"""
self._execute_network_run(traj, network, network_dict, component_list, analyser_list,
pre_run=False) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.