_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | 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:
| 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)
| 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): | 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'] | 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,
| python | {
"resource": ""
} |
q274205 | Trajectory.f_lock_parameters | test | def f_lock_parameters(self):
"""Locks all non-empty parameters"""
for par in self._parameters.values():
| python | {
"resource": ""
} |
q274206 | Trajectory.f_lock_derived_parameters | test | def f_lock_derived_parameters(self):
"""Locks all non-empty derived parameters"""
| 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.
| 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.
"""
| 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 | 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
| 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)):
| 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,
| 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']
| 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
| 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,
| 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 '
| 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:
| 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():
| 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.
"""
| 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``.
| 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,
| 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 | 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
| 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
| 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 | 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
| 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 = []
| 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
| 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 | 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]
| 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 = | 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
| 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'
| 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
| 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 | 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 | 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 | 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']`.
| 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.
"""
| 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)
| 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.
| 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:
| 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:
| 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`
# | python | {
"resource": ""
} |
q274245 | _configure_pool | test | def _configure_pool(kwargs):
"""Configures the pool and keeps the storage service"""
| 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 | 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)
| 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
| 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:
| 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'] | 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 | 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 = | 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
| 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 | 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')
| 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 | 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():
| 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.
"""
| 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`.
| 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():
| 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
| 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])
| 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 | 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
| 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, '
| 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)
| 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)
| 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
| 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):
| 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)
| 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
| 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):
| 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:
| 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, '
| 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 = | 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:
| 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: | 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
| 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: '
| 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 | 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):
| 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)
| 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 | 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 '
| python | {
"resource": ""
} |
q274285 | PickleResult._store | test | def _store(self):
"""Returns a dictionary containing pickle dumps"""
store_dict = {}
for key, val in | 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
| 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
| 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, | 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)
| 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
| 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 | 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))
| python | {
"resource": ""
} |
q274293 | multiply | test | def multiply(traj):
"""Sophisticated simulation of multiplication"""
z=traj.x*traj.y
| 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 | 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 | 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,
| 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'))
# | 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 | 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 | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.