Search is not available for this dataset
text
stringlengths
75
104k
def _handle_dict_config(self, log_config): """Recursively walks and copies the `log_config` dict and searches for filenames. Translates filenames and creates directories if necessary. """ new_dict = dict() for key in log_config.keys(): if key == 'filename': ...
def make_logging_handlers_and_tools(self, multiproc=False): """Creates logging handlers and redirects stdout.""" log_stdout = self.log_stdout if sys.stdout is self._stdout_to_logger: # If we already redirected stdout we don't neet to redo it again log_stdout = False ...
def finalize(self, remove_all_handlers=True): """Finalizes the manager, closes and removes all handlers if desired.""" for tool in self._tools: tool.finalize() self._tools = [] self._stdout_to_logger = None for config in (self._sp_config, self._mp_config): ...
def start(self): """Starts redirection of `stdout`""" if sys.stdout is not self: self._original_steam = sys.stdout sys.stdout = self self._redirection = True if self._redirection: print('Established redirection of `stdout`.')
def write(self, buf): """Writes data from buffer to logger""" if not self._recursion: self._recursion = True try: for line in buf.rstrip().splitlines(): self._logger.log(self._log_level, line.rstrip()) finally: self....
def finalize(self): """Disables redirection""" if self._original_steam is not None and self._redirection: sys.stdout = self._original_steam print('Disabled redirection of `stdout`.') self._redirection = False self._original_steam = None
def results_equal(a, b): """Compares two result instances Checks full name and all data. Does not consider the comment. :return: True or False :raises: ValueError if both inputs are no result instances """ if a.v_is_parameter and b.v_is_parameter: raise ValueError('Both inputs are no...
def parameters_equal(a, b): """Compares two parameter instances Checks full name, data, and ranges. Does not consider the comment. :return: True or False :raises: ValueError if both inputs are no parameter instances """ if (not b.v_is_parameter and not a.v_is_parameter): ...
def get_all_attributes(instance): """Returns an attribute value dictionary much like `__dict__` but incorporates `__slots__`""" try: result_dict = instance.__dict__.copy() except AttributeError: result_dict = {} if hasattr(instance, '__all_slots__'): all_slots = instance.__all_s...
def nested_equal(a, b): """Compares two objects recursively by their elements. Also handles numpy arrays, pandas data and sparse matrices. First checks if the data falls into the above categories. If not, it is checked if a or b are some type of sequence or mapping and the contained elements are c...
def manual_run(turn_into_run=True, store_meta_data=True, clean_up=True): """Can be used to decorate a function as a manual run function. This can be helpful if you want the run functionality without using an environment. :param turn_into_run: If the trajectory should become a `single run` with mo...
def deprecated(msg=''): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. :param msg: Additional message added to the warning. """ def wrapper(func): @functools.wraps(func) de...
def copydoc(fromfunc, sep="\n"): """Decorator: Copy the docstring of `fromfunc` If the doc contains a line with the keyword `ABSTRACT`, like `ABSTRACT: Needs to be defined in subclass`, this line and the line after are removed. """ def _decorator(func): sourcedoc = fromfunc.__doc__ ...
def kwargs_mutual_exclusive(param1_name, param2_name, map2to1=None): """ If there exist mutually exclusive parameters checks for them and maps param2 to 1.""" def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): if param2_name in kwargs: if param1_...
def kwargs_api_change(old_name, new_name=None): """This is a decorator which can be used if a kwarg has changed its name over versions to also support the old argument name. Issues a warning if the old keyword argument is detected and converts call to new API. :param old_name: Old name of...
def not_in_run(func): """This is a decorator that signaling that a function is not available during a single run. """ doc = func.__doc__ na_string = '''\nATTENTION: This function is not available during a single run!\n''' if doc is not None: func.__doc__ = '\n'.join([doc, na_string]) f...
def with_open_store(func): """This is a decorator that signaling that a function is only available if the storage is open. """ doc = func.__doc__ na_string = '''\nATTENTION: This function can only be used if the store is open!\n''' if doc is not None: func.__doc__ = '\n'.join([doc, na_stri...
def retry(n, errors, wait=0.0, logger_name=None): """This is a decorator that retries a function. Tries `n` times and catches a given tuple of `errors`. If the `n` retries are not enough, the error is reraised. If desired `waits` some seconds. Optionally takes a 'logger_name' of a given logger t...
def _prfx_getattr_(obj, item): """Replacement of __getattr__""" if item.startswith('f_') or item.startswith('v_'): return getattr(obj, item[2:]) raise AttributeError('`%s` object has no attribute `%s`' % (obj.__class__.__name__, item))
def _prfx_setattr_(obj, item, value): """Replacement of __setattr__""" if item.startswith('v_'): return setattr(obj, item[2:], value) else: return super(obj.__class__, obj).__setattr__(item, value)
def prefix_naming(cls): """Decorate that adds the prefix naming scheme""" if hasattr(cls, '__getattr__'): raise TypeError('__getattr__ already defined') cls.__getattr__ = _prfx_getattr_ cls.__setattr__ = _prfx_setattr_ return cls
def add_params(traj): """Adds all necessary parameters to `traj`.""" # We set the BrianParameter to be the standard parameter traj.v_standard_parameter=Brian2Parameter traj.v_fast_access=True # Add parameters we need for our network traj.f_add_parameter('Net.C',281*pF) traj.f_add_parameter...
def run_net(traj): """Creates and runs BRIAN network based on the parameters in `traj`.""" eqs=traj.eqs # Create a namespace dictionairy namespace = traj.Net.f_to_dict(short_names=True, fast_access=True) # Create the Neuron Group neuron=NeuronGroup(traj.N, model=eqs, threshold=traj.Vcut, reset...
def euler_scheme(traj, diff_func): """Simulation function for Euler integration. :param traj: Container for parameters and results :param diff_func: The differential equation we want to integrate """ steps = traj.steps initial_conditions = traj.initial_conditions dimens...
def add_parameters(traj): """Adds all necessary parameters to the `traj` container""" traj.f_add_parameter('steps', 10000, comment='Number of time steps to simulate') traj.f_add_parameter('dt', 0.01, comment='Step size') # Here we want to add the initial conditions as an array parameter. We will simul...
def diff_lorenz(value_array, sigma, beta, rho): """The Lorenz attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param sigma: Constant attractor parameter :param beta: FConstant attractor parameter :param rho: Constant attractor parameter ...
def _create_storage(storage_service, trajectory=None, **kwargs): """Creates a service from a constructor and checks which kwargs are not used""" kwargs_copy = kwargs.copy() kwargs_copy['trajectory'] = trajectory matching_kwargs = get_matching_kwargs(storage_service, kwargs_copy) storage_service = st...
def storage_factory(storage_service, trajectory=None, **kwargs): """Creates a storage service, to be extended if new storage services are added :param storage_service: Storage Service instance of constructor or a string pointing to a file :param trajectory: A trajectory instance :pa...
def multiply(traj): """Example of a sophisticated simulation that involves multiplying two values. :param traj: Trajectory containing the parameters in a particular combination, it also serves as a container for results. """ z=traj.mylink1*traj.mylink2 # And again we now can a...
def add_parameters(traj): """Adds all necessary parameters to the `traj` container. You can choose between two parameter sets. One for the Lorenz attractor and one for the Roessler attractor. The former is chosen for `traj.diff_name=='diff_lorenz'`, the latter for `traj.diff_name=='diff_roessler'`....
def diff_roessler(value_array, a, c): """The Roessler attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param a: Constant attractor parameter :param c: Constant attractor parameter :return: 3d array of the Roessler system evaluated at `value_...
def compact_hdf5_file(filename, name=None, index=None, keep_backup=True): """Can compress an HDF5 to reduce file size. The properties on how to compress the new file are taken from a given trajectory in the file. Simply calls ``ptrepack`` from the command line. (Se also https://pytables.github.io/u...
def _explored_parameters_in_group(traj, group_node): """Checks if one the parameters in `group_node` is explored. :param traj: Trajectory container :param group_node: Group node :return: `True` or `False` """ explored = False for param in traj.f_get_explored_parameters(): if pa...
def add_parameters(traj): """Adds all neuron group parameters to `traj`.""" assert(isinstance(traj,Trajectory)) scale = traj.simulation.scale traj.v_standard_parameter = Brian2Parameter model_eqs = '''dV/dt= 1.0/tau_POST * (mu - V) + I_syn : 1 mu : 1 ...
def _build_model_eqs(traj): """Computes model equations for the excitatory and inhibitory population. Equation objects are created by fusing `model.eqs` and `model.synaptic.eqs` and replacing `PRE` by `i` (for inhibitory) or `e` (for excitatory) depending on the type of population. ...
def pre_build(self, traj, brian_list, network_dict): """Pre-builds the neuron groups. Pre-build is only performed if none of the relevant parameters is explored. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network construct...
def build(self, traj, brian_list, network_dict): """Builds the neuron groups. Build is only performed if neuron group was not pre-build before. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. A...
def _build_model(self, traj, brian_list, network_dict): """Builds the neuron groups from `traj`. Adds the neuron groups to `brian_list` and `network_dict`. """ model = traj.parameters.model # Create the equations for both models eqs_dict = self._build_model_eqs(traj) ...
def add_parameters(traj): """Adds all neuron group parameters to `traj`.""" assert(isinstance(traj,Trajectory)) traj.v_standard_parameter = Brian2Parameter scale = traj.simulation.scale traj.f_add_parameter('connections.R_ee', 1.0, comment='Scaling factor for clustering') ...
def pre_build(self, traj, brian_list, network_dict): """Pre-builds the connections. Pre-build is only performed if none of the relevant parameters is explored and the relevant neuron groups exist. :param traj: Trajectory container :param brian_list: List o...
def build(self, traj, brian_list, network_dict): """Builds the connections. Build is only performed if connections have not been pre-build. :param traj: Trajectory container :param brian_list: List of objects passed to BRIAN network constructor. Adds:...
def _build_connections(self, traj, brian_list, network_dict): """Connects neuron groups `neurons_i` and `neurons_e`. Adds all connections to `brian_list` and adds a list of connections with the key 'connections' to the `network_dict`. """ connections = traj.connections ...
def add_parameters(self, traj): """Adds all necessary parameters to `traj` container.""" par= traj.f_add_parameter(Brian2Parameter,'simulation.durations.initial_run', 500*ms, comment='Initialisation run for more realistic ' 'measur...
def _compute_fano_factor(spike_res, neuron_id, time_window, start_time, end_time): """Computes Fano Factor for one neuron. :param spike_res: Result containing the spiketimes of all neurons :param neuron_id: Index of neuron for which FF is computed :param time...
def _compute_mean_fano_factor( neuron_ids, spike_res, time_window, start_time, end_time): """Computes average Fano Factor over many neurons. :param neuron_ids: List of neuron indices to average over :param spike_res: Result containing all the spikes :param ti...
def analyse(self, traj, network, current_subrun, subrun_list, network_dict): """Calculates average Fano Factor of a network. :param traj: Trajectory container Expects: `results.monitors.spikes_e`: Data from SpikeMonitor for excitatory neurons Adds: ...
def add_to_network(self, traj, network, current_subrun, subrun_list, network_dict): """Adds monitors to the network if the measurement run is carried out. :param traj: Trajectory container :param network: The BRIAN network :param current_subrun: BrianParameter :param subrun_l...
def _add_monitors(self, traj, network, network_dict): """Adds monitors to the network""" neurons_e = network_dict['neurons_e'] monitor_list = [] # Spiketimes self.spike_monitor = SpikeMonitor(neurons_e) monitor_list.append(self.spike_monitor) # Membrane Poten...
def _make_folder(self, traj): """Makes a subfolder for plots. :return: Path name to print folder """ print_folder = os.path.join(traj.analysis.plot_folder, traj.v_name, traj.v_crun) print_folder = os.path.abspath(print_folder) if not ...
def _plot_result(self, traj, result_name): """Plots a state variable graph for several neurons into one figure""" result = traj.f_get(result_name) varname = result.record_variables[0] values = result[varname] times = result.t record = result.record for idx, celi...
def _print_graphs(self, traj): """Makes some plots and stores them into subfolders""" print_folder = self._make_folder(traj) # If we use BRIAN's own raster_plot functionality we # need to sue the SpikeMonitor directly plt.figure() plt.scatter(self.spike_monitor.t, self.s...
def analyse(self, traj, network, current_subrun, subrun_list, network_dict): """Extracts monitor data and plots. Data extraction is done if all subruns have been completed, i.e. `len(subrun_list)==0` First, extracts results from the monitors and stores them into `traj`. Next, ...
def get_batch(): """Function that parses the batch id from the command line arguments""" optlist, args = getopt.getopt(sys.argv[1:], '', longopts='batch=') batch = 0 for o, a in optlist: if o == '--batch': batch = int(a) print('Found batch %d' % batch) return batch
def explore_batch(traj, batch): """Chooses exploration according to `batch`""" explore_dict = {} explore_dict['sigma'] = np.arange(10.0 * batch, 10.0*(batch+1), 1.0).tolist() # for batch = 0 explores sigma in [0.0, 1.0, 2.0, ..., 9.0], # for batch = 1 explores sigma in [10.0, 11.0, 12.0, ..., 19.0] ...
def vars(self): """Alternative naming, you can use `node.vars.name` instead of `node.v_name`""" if self._vars is None: self._vars = NNTreeNodeVars(self) return self._vars
def func(self): """Alternative naming, you can use `node.func.name` instead of `node.f_func`""" if self._func is None: self._func = NNTreeNodeFunc(self) return self._func
def _rename(self, full_name): """Renames the tree node""" self._full_name = full_name if full_name: self._name = full_name.rsplit('.', 1)[-1]
def _set_details(self, depth, branch, run_branch): """Sets some details for internal handling.""" self._depth = depth self._branch = branch self._run_branch = run_branch
def _map_type_to_dict(self, type_name): """ Maps a an instance type representation string (e.g. 'RESULT') to the corresponding dictionary in root. """ root = self._root_instance if type_name == RESULT: return root._results elif type_name == PARAMETER: ...
def _fetch_from_string(self, store_load, name, args, kwargs): """Method used by f_store/load/remove_items to find a corresponding item in the tree. :param store_load: String constant specifying if we want to store, load or remove. The corresponding constants are defined at the ...
def _fetch_from_node(self, store_load, node, args, kwargs): """Method used by f_store/load/remove_items to find a corresponding item in the tree. :param store_load: String constant specifying if we want to store, load or remove :param node: A group, parameter or result instance. :param ...
def _fetch_from_tuple(self, store_load, store_tuple, args, kwargs): """ Method used by f_store/load/remove_items to find a corresponding item in the tree. The input to the method should already be in the correct format, this method only checks for sanity. :param store_load: String cons...
def _node_to_msg(store_load, node): """Maps a given node and a store_load constant to the message that is understood by the storage service. """ if node.v_is_leaf: if store_load == STORE: return pypetconstants.LEAF elif store_load == LOAD: ...
def _fetch_items(self, store_load, iterable, args, kwargs): """ Method used by f_store/load/remove_items to find corresponding items in the tree. :param store_load: String constant specifying if we want to store, load or remove. The corresponding constants are defined at the t...
def _remove_subtree(self, start_node, name, predicate=None): """Removes a subtree from the trajectory tree. Does not delete stuff from disk only from RAM. :param start_node: The parent node from where to start :param name: Name of child which will be deleted and recursively all nodes b...
def _delete_node(self, node): """Deletes a single node from the tree. Removes all references to the node. Note that the 'parameters', 'results', 'derived_parameters', and 'config' groups hanging directly below root cannot be deleted. Also the root node itself cannot be deleted....
def _remove_node_or_leaf(self, instance, recursive=False): """Removes a single node from the tree. Only from RAM not from hdf5 file! :param instance: The node to be deleted :param recursive: If group nodes with children should be deleted """ full_name = instance.v_ful...
def _remove_along_branch(self, actual_node, split_name, recursive=False): """Removes a given node from the tree. Starts from a given node and walks recursively down the tree to the location of the node we want to remove. We need to walk from a start node in case we want to check on the...
def _translate_shortcut(self, name): """Maps a given shortcut to corresponding name * 'run_X' or 'r_X' to 'run_XXXXXXXXX' * 'crun' to the current run name in case of a single run instance if trajectory is used via `v_crun` * 'par' 'parameters' * 'dpar' to 'derived_p...
def _add_prefix(self, split_names, start_node, group_type_name): """Adds the correct sub branch prefix to a given name. Usually the prefix is the full name of the parent node. In case items are added directly to the trajectory the prefixes are chosen according to the matching subbranch. ...
def _determine_types(start_node, first_name, add_leaf, add_link): """Determines types for generic additions""" if start_node.v_is_root: where = first_name else: where = start_node._branch if where in SUBTREE_MAPPING: type_tuple = SUBTREE_MAPPING[where...
def _add_generic(self, start_node, type_name, group_type_name, args, kwargs, add_prefix=True, check_naming=True): """Adds a given item to the tree irrespective of the subtree. Infers the subtree from the arguments. :param start_node: The parental node the adding was initia...
def _replace_wildcards(self, name, run_idx=None): """Replaces the $ wildcards and returns True/False in case it was replaced""" if self._root_instance.f_is_wildcard(name): return True, self._root_instance.f_wildcard(name, run_idx) else: return False, name
def _add_to_tree(self, start_node, split_names, type_name, group_type_name, instance, constructor, args, kwargs): """Adds a new item to the tree. The item can be an already given instance or it is created new. :param start_node: Parental node the adding of the...
def _create_link(self, act_node, name, instance): """Creates a link and checks if names are appropriate """ act_node._links[name] = instance act_node._children[name] = instance full_name = instance.v_full_name if full_name not in self._root_instance._linked_by: ...
def _check_names(self, split_names, parent_node=None): """Checks if a list contains strings with invalid names. Returns a description of the name violations. If names are correct the empty string is returned. :param split_names: List of strings :param parent_node: ...
def _create_any_group(self, parent_node, name, type_name, instance=None, constructor=None, args=None, kwargs=None): """Generically creates a new group inferring from the `type_name`.""" if args is None: args = [] if kwargs is None: kwargs = {} ...
def _create_any_param_or_result(self, parent_node, name, type_name, instance, constructor, args, kwargs): """Generically creates a novel parameter or result instance inferring from the `type_name`. If the instance is already supplied it is NOT constructed new. ...
def _set_details_tree_node(self, parent_node, name, instance): """Renames a given `instance` based on `parent_node` and `name`. Adds meta information like depth as well. """ depth = parent_node._depth + 1 if parent_node.v_is_root: branch = name # We add below root ...
def _iter_nodes(self, node, recursive=False, max_depth=float('inf'), with_links=True, in_search=False, predicate=None): """Returns an iterator over nodes hanging below a given start node. :param node: Start node :param recursive: Whether recursivel...
def _to_dict(self, node, fast_access=True, short_names=False, nested=False, copy=True, with_links=True): """ Returns a dictionary with pairings of (full) names as keys and instances as values. :param fast_access: If true parameter or result values are returned instead of t...
def _make_child_iterator(node, with_links, current_depth=0): """Returns an iterator over a node's children. In case of using a trajectory as a run (setting 'v_crun') some sub branches that do not belong to the run are blinded out. """ cdp1 = current_depth + 1 if with_li...
def _recursive_traversal_bfs(node, linked_by=None, max_depth=float('inf'), with_links=True, in_search=False, predicate=None): """Iterator function traversing the tree below `node` in breadth first search manner. If `run_name` is given on...
def _very_fast_search(self, node, key, max_depth, with_links, crun): """Fast search for a node in the tree. The tree is not traversed but the reference dictionaries are searched. :param node: Parent node to start from :param key: Name of node to find ...
def _search(self, node, key, max_depth=float('inf'), with_links=True, crun=None): """ Searches for an item in the tree below `node` :param node: The parent node below which the search is performed :param key: Name to search for. Can be the short name, the full name or...
def _backwards_search(self, start_node, split_name, max_depth=float('inf'), shortcuts=True): """ Performs a backwards search from the terminal node back to the start node :param start_node: The node from where search starts, or here better way where backwards search should end....
def _get_all(self, node, name, max_depth, shortcuts): """ Searches for all occurrences of `name` under `node`. :param node: Start node :param name: Name what to look for can be longer and separated by colons, i.e. `mygroupA.mygroupB.myparam`. :par...
def _get(self, node, name, fast_access, shortcuts, max_depth, auto_load, with_links): """Searches for an item (parameter/result/group node) with the given `name`. :param node: The node below which the search is performed :param name: Name of the item (full name or parts of the ful...
def _perform_get(self, node, split_name, fast_access, shortcuts, max_depth, auto_load, with_links, try_auto_load_directly): """Searches for an item (parameter/result/group node) with the given `name`. :param node: The node below which the search is performed ...
def kids(self): """Alternative naming, you can use `node.kids.name` instead of `node.name` for easier tab completion.""" if self._kids is None: self._kids = NNTreeNodeKids(self) return self._kids
def _add_group_from_storage(self, args, kwargs): """Can be called from storage service to create a new group to bypass name checking""" return self._nn_interface._add_generic(self, type_name=GROUP, group_type...
def _add_leaf_from_storage(self, args, kwargs): """Can be called from storage service to create a new leaf to bypass name checking""" return self._nn_interface._add_generic(self, type_name=LEAF, group_type_na...
def f_dir_data(self): """Returns a list of all children names""" if (self._nn_interface is not None and self._nn_interface._root_instance is not None and self.v_root.v_auto_load): try: if self.v_is_root: self.f_l...
def _debug(self): """Creates a dummy object containing the whole tree to make unfolding easier. This method is only useful for debugging purposes. If you use an IDE and want to unfold the trajectory tree, you always need to open the private attribute `_children`. Use to this function to...
def f_get_parent(self): """Returns the parent of the node. Raises a TypeError if current node is root. """ if self.v_is_root: raise TypeError('Root does not have a parent') elif self.v_location == '': return self.v_root else: return s...
def f_add_group(self, *args, **kwargs): """Adds an empty generic group under the current node. You can add to a generic group anywhere you want. So you are free to build your parameter tree with any structure. You do not necessarily have to follow the four subtrees `config`, `parameters...
def f_add_link(self, name_or_item, full_name_or_item=None): """Adds a link to an existing node. Can be called as ``node.f_add_link(other_node)`` this will add a link the `other_node` with the link name as the name of the node. Or can be called as ``node.f_add_link(name, other_node)`` t...
def f_remove_link(self, name): """ Removes a link from from the current group node with a given name. Does not delete the link from the hard drive. If you want to do this, checkout :func:`~pypet.trajectory.Trajectory.f_delete_links` """ if name not in self._links: r...
def f_add_leaf(self, *args, **kwargs): """Adds an empty generic leaf under the current node. You can add to a generic leaves anywhere you want. So you are free to build your trajectory tree with any structure. You do not necessarily have to follow the four subtrees `config`, `parameters...
def f_remove(self, recursive=True, predicate=None): """Recursively removes the group and all it's children. :param recursive: If removal should be applied recursively. If not, node can only be removed if it has no children. :param predicate: In case of rec...