_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q274100
LockerServer._lock
test
def _lock(self, name, client_id, request_id): """Hanldes locking of locks If a lock is already locked sends a WAIT command, else LOCKs it and sends GO. Complains if a given client re-locks a lock without releasing it before. """ if name in self._locks: other_client_id, other_request_id = self._locks[name] if other_client_id == client_id: response = (self.LOCK_ERROR + self.DELIMITER + 'Re-request of lock `%s` (old request id
python
{ "resource": "" }
q274101
ReliableClient.send_done
test
def send_done(self): """Notifies the Server to shutdown""" self.start(test_connection=False)
python
{ "resource": "" }
q274102
ReliableClient.finalize
test
def finalize(self): """Closes socket and terminates context NO-OP if already closed. """ if self._context is not None: if self._socket is not None:
python
{ "resource": "" }
q274103
ReliableClient.start
test
def start(self, test_connection=True): """Starts connection to server if not existent. NO-OP if connection is already established. Makes ping-pong test as well if desired. """ if self._context is None: self._logger.debug('Starting Client')
python
{ "resource": "" }
q274104
ReliableClient._req_rep_retry
test
def _req_rep_retry(self, request): """Returns response and number of retries""" retries_left = self.RETRIES while retries_left: self._logger.log(1, 'Sending REQ `%s`', request) self._send_request(request) socks = dict(self._poll.poll(self.TIMEOUT)) if socks.get(self._socket) == zmq.POLLIN: response = self._receive_response() self._logger.log(1, 'Received REP `%s`', response) return response, self.RETRIES - retries_left else:
python
{ "resource": "" }
q274105
LockerClient.acquire
test
def acquire(self): """Acquires lock and returns `True` Blocks until lock is available. """ self.start(test_connection=False) while True: str_response, retries = self._req_rep_retry(LockerServer.LOCK) response = str_response.split(LockerServer.DELIMITER) if response[0] == LockerServer.GO: return True elif response[0] == LockerServer.LOCK_ERROR and retries > 0: # Message was sent but Server response was lost and we tried again
python
{ "resource": "" }
q274106
QueuingServerMessageListener.listen
test
def listen(self): """ Handles listening requests from the client. There are 4 types of requests: 1- Check space in the queue 2- Tests the socket 3- If there is a space, it sends data 4- after data is sent, puts it to queue for storing """ count = 0 self._start() while True: result = self._socket.recv_pyobj() if isinstance(result, tuple): request, data = result else: request = result data = None if request == self.SPACE: if self.queue.qsize() + count < self.queue_maxsize: self._socket.send_string(self.SPACE_AVAILABLE) count += 1 else: self._socket.send_string(self.SPACE_NOT_AVAILABLE) elif request == self.PING:
python
{ "resource": "" }
q274107
QueuingClient.put
test
def put(self, data, block=True): """ If there is space it sends data to server If no space in the queue It returns the request in every 10 millisecond until there will be space in the queue. """ self.start(test_connection=False) while True: response = self._req_rep(QueuingServerMessageListener.SPACE)
python
{ "resource": "" }
q274108
ForkDetector._detect_fork
test
def _detect_fork(self): """Detects if lock client was forked. Forking is detected by comparing the PID of the current process with the stored PID. """ if self._pid is None: self._pid = os.getpid()
python
{ "resource": "" }
q274109
StorageServiceDataHandler._handle_data
test
def _handle_data(self, msg, args, kwargs): """Handles data and returns `True` or `False` if everything is done.""" stop = False try: if msg == 'DONE': stop = True elif msg == 'STORE': if 'msg' in kwargs: store_msg = kwargs.pop('msg') else: store_msg = args[0] args = args[1:] if 'stuff_to_store' in kwargs: stuff_to_store = kwargs.pop('stuff_to_store') else: stuff_to_store = args[0] args = args[1:] trajectory_name = kwargs['trajectory_name'] if self._trajectory_name != trajectory_name: if self._storage_service.is_open: self._close_file() self._trajectory_name = trajectory_name self._open_file() self._storage_service.store(store_msg, stuff_to_store, *args, **kwargs)
python
{ "resource": "" }
q274110
StorageServiceDataHandler.run
test
def run(self): """Starts listening to the queue.""" try: while True: msg, args, kwargs = self._receive_data() stop = self._handle_data(msg, args, kwargs) if stop:
python
{ "resource": "" }
q274111
QueueStorageServiceWriter._receive_data
test
def _receive_data(self): """Gets data from queue""" result = self.queue.get(block=True) if
python
{ "resource": "" }
q274112
PipeStorageServiceWriter._receive_data
test
def _receive_data(self): """Gets data from pipe""" while True: while len(self._buffer) < self.max_size and self.conn.poll(): data = self._read_chunks() if
python
{ "resource": "" }
q274113
LockWrapper.store
test
def store(self, *args, **kwargs): """Acquires a lock before storage and releases it afterwards.""" try: self.acquire_lock() return self._storage_service.store(*args, **kwargs)
python
{ "resource": "" }
q274114
ReferenceWrapper.store
test
def store(self, msg, stuff_to_store, *args, **kwargs): """Simply keeps a reference to the stored data """ trajectory_name = kwargs['trajectory_name'] if trajectory_name not in self.references:
python
{ "resource": "" }
q274115
ReferenceStore.store_references
test
def store_references(self, references): """Stores references to disk and may collect garbage.""" for trajectory_name in
python
{ "resource": "" }
q274116
parse_config
test
def parse_config(init_func): """Decorator wrapping the environment to use a config file""" @functools.wraps(init_func) def new_func(env, *args, **kwargs): config_interpreter = ConfigInterpreter(kwargs) # Pass the config data to the kwargs new_kwargs = config_interpreter.interpret() init_func(env,
python
{ "resource": "" }
q274117
ConfigInterpreter._collect_section
test
def _collect_section(self, section): """Collects all settings within a section""" kwargs = {} try: if self.parser.has_section(section): options = self.parser.options(section) for option in options:
python
{ "resource": "" }
q274118
ConfigInterpreter._collect_config
test
def _collect_config(self): """Collects all info from three sections""" kwargs = {} sections =
python
{ "resource": "" }
q274119
ConfigInterpreter.interpret
test
def interpret(self): """Copies parsed arguments into the kwargs passed to the environment""" if self.config_file: new_kwargs = self._collect_config() for key in new_kwargs: #
python
{ "resource": "" }
q274120
ConfigInterpreter.add_parameters
test
def add_parameters(self, traj): """Adds parameters and config from the `.ini` file to the trajectory""" if self.config_file: parameters = self._collect_section('parameters') for name in parameters: value = parameters[name] if not isinstance(value, tuple): value = (value,) traj.f_add_parameter(name, *value)
python
{ "resource": "" }
q274121
convert_rule
test
def convert_rule(rule_number): """ Converts a rule given as an integer into a binary list representation. It reads from left to right (contrary to the Wikipedia article given below), i.e. the 2**0 is found on the left hand side and 2**7 on the right. For example: ``convert_rule(30)`` returns [0, 1, 1, 1, 1, 0, 0, 0] The resulting binary list can be interpreted as the following transition table: neighborhood new cell state 000 0 001 1 010 1 011 1 100 1
python
{ "resource": "" }
q274122
make_initial_state
test
def make_initial_state(name, ncells, seed=42): """ Creates an initial state for the automaton. :param name: Either ``'single'`` for a single live cell in the middle of the cell ring, or ``'random'`` for uniformly distributed random pattern of zeros and ones. :param ncells: Number of cells in the automaton :param seed: Random number seed for the ``#random'``
python
{ "resource": "" }
q274123
plot_pattern
test
def plot_pattern(pattern, rule_number, filename): """ Plots an automaton ``pattern`` and stores the image under a given ``filename``. For axes labels the ``rule_number`` is also required. """ plt.figure()
python
{ "resource": "" }
q274124
cellular_automaton_1D
test
def cellular_automaton_1D(initial_state, rule_number, steps): """ Simulates a 1 dimensional cellular automaton. :param initial_state: The initial state of *dead* and *alive* cells as a 1D numpy array. It's length determines the size of the simulation. :param rule_number: The update rule as an integer from 0 to 255. :param steps: Number of cell iterations :return: A 2D numpy array (steps x len(initial_state)) containing zeros and ones representing the automaton development over time. """ ncells = len(initial_state) # Create an array for the full pattern pattern = np.zeros((steps, ncells)) # Pass
python
{ "resource": "" }
q274125
main
test
def main(): """ Main simulation function """ rules_to_test = [10, 30, 90, 110, 184] # rules we want to explore: steps = 250 # cell iterations ncells = 400 # number of cells seed = 100042 # RNG seed initial_states = ['single', 'random'] # Initial states we want to explore # create a folder for the plots and the data folder = os.path.join(os.getcwd(), 'experiments', 'ca_patterns_original') if not os.path.isdir(folder): os.makedirs(folder) filename = os.path.join(folder, 'all_patterns.p') print('Computing all patterns') all_patterns = [] # list containing the simulation results for idx, rule_number in enumerate(rules_to_test): # iterate over all rules for initial_name in initial_states: # iterate over the initial states # make the initial state initial_state = make_initial_state(initial_name, ncells, seed=seed) # simulate the automaton pattern = cellular_automaton_1D(initial_state, rule_number, steps) # keep the resulting pattern all_patterns.append((rule_number, initial_name, pattern)) # Print a progressbar, because I am always impatient
python
{ "resource": "" }
q274126
NodeProcessingTimer.signal_update
test
def signal_update(self): """Signals the process timer. If more time than the display time has passed a message is emitted. """ if not self.active: return self._updates += 1 current_time = time.time() dt = current_time - self._last_time if dt > self._display_time: dfullt = current_time - self._start_time seconds = int(dfullt) % 60 minutes = int(dfullt) / 60 if minutes == 0: formatted_time = '%ds' %
python
{ "resource": "" }
q274127
HDF5StorageService._overview_group
test
def _overview_group(self): """Direct link to the overview group""" if self._overview_group_ is
python
{ "resource": "" }
q274128
HDF5StorageService.load
test
def load(self, msg, stuff_to_load, *args, **kwargs): """Loads a particular item from disk. The storage service always accepts these parameters: :param trajectory_name: Name of current trajectory and name of top node in hdf5 file. :param trajectory_index: If no `trajectory_name` is provided, you can specify an integer index. The trajectory at the index position in the hdf5 file is considered to loaded. Negative indices are also possible for reverse indexing. :param filename: Name of the hdf5 file The following messages (first argument msg) are understood and the following arguments can be provided in combination with the message: * :const:`pypet.pypetconstants.TRAJECTORY` ('TRAJECTORY') Loads a trajectory. :param stuff_to_load: The trajectory :param as_new: Whether to load trajectory as new :param load_parameters: How to load parameters and config :param load_derived_parameters: How to load derived parameters :param load_results: How to load results :param force: Force load in case there is a pypet version mismatch 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 including annotations are loaded, i.e. the items are empty. Non-empty items in RAM are left untouched. :const:`pypet.pypetconstants.LOAD_DATA`: (2) The whole data is loaded. Only empty or in RAM non-existing instance are filled with the data found on disk. :const:`pypet.pypetconstants.OVERWRITE_DATA`: (3) The whole data is loaded. If items that are to be loaded are already in RAM and not empty, they are emptied and new data is loaded from disk. * :const:`pypet.pypetconstants.LEAF` ('LEAF') Loads a parameter or result. :param stuff_to_load: The item to be loaded :param load_data: How to load data :param load_only: If you load a result, you can partially load it and ignore the rest of the data. 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']`. Issues a warning if items cannot be found. :param load_except: If you load a result you can partially load in and specify items that should NOT be loaded here. You cannot use `load_except` and `load_only` at the same time. * :const:`pypet.pyetconstants.GROUP` Loads a group a node (comment and annotations) :param recursive: Recursively loads everything below :param load_data: How to load stuff if ``recursive=True`` accepted values as above for loading the trajectory :param max_depth: Maximum depth in case of recursion. `None` for no limit. * :const:`pypet.pypetconstants.TREE` ('TREE') Loads a whole subtree
python
{ "resource": "" }
q274129
HDF5StorageService.store
test
def store(self, msg, stuff_to_store, *args, **kwargs): """ Stores a particular item to disk. The storage service always accepts these parameters: :param trajectory_name: Name or current trajectory and name of top node in hdf5 file :param filename: Name of the hdf5 file :param file_title: If file needs to be created, assigns a title to the file. The following messages (first argument msg) are understood and the following arguments can be provided in combination with the message: * :const:`pypet.pypetconstants.PREPARE_MERGE` ('PREPARE_MERGE'): Called to prepare a trajectory for merging, see also 'MERGE' below. Will also be called if merging cannot happen within the same hdf5 file. Stores already enlarged parameters and updates meta information. :param stuff_to_store: Trajectory that is about to be extended by another one :param changed_parameters: List containing all parameters that were enlarged due to merging :param old_length: Old length of trajectory before merge * :const:`pypet.pypetconstants.MERGE` ('MERGE') Note that before merging within HDF5 file, the storage service will be called with msg='PREPARE_MERGE' before, see above. Raises a ValueError if the two trajectories are not stored within the very same hdf5 file. Then the current trajectory needs to perform the merge slowly item by item. Merges two trajectories, parameters are: :param stuff_to_store: The trajectory data is merged into :param other_trajectory_name: Name of the other trajectory :param rename_dict: Dictionary containing the old result and derived parameter names in the other trajectory and their new names in the current trajectory. :param move_nodes: Whether to move the nodes from the other to the current trajectory :param delete_trajectory: Whether to delete the other trajectory after merging. * :const:`pypet.pypetconstants.BACKUP` ('BACKUP') :param stuff_to_store: Trajectory to be backed up :param backup_filename: Name of file where to store the backup. If None the backup file will be in the same folder as your hdf5 file and named 'backup_XXXXX.hdf5' where 'XXXXX' is the name of your current trajectory. * :const:`pypet.pypetconstants.TRAJECTORY` ('TRAJECTORY') Stores the whole trajectory :param stuff_to_store: The trajectory to be stored :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 nodes/leaves within the trajectory. :param store_data: How to store data, the following settings are understood: :const:`pypet.pypetconstants.STORE_NOTHING`: (0) Nothing is stored :const:`pypet.pypetconstants.STORE_DATA_SKIPPING`: (1) Data of not already stored nodes is stored :const:`pypet.pypetconstants.STORE_DATA`: (2) Data of all nodes is stored. However, existing data on disk is left untouched. :const:`pypet.pypetconstants.OVERWRITE_DATA`: (3) Data of all nodes is stored and data on disk is overwritten. May lead to fragmentation of the HDF5 file. The user is adviced to recompress the file manually later on. * :const:`pypet.pypetconstants.SINGLE_RUN` ('SINGLE_RUN') :param stuff_to_store: The trajectory :param store_data: How to store data see above :param store_final: If final meta info should be stored * :const:`pypet.pypetconstants.LEAF` Stores a parameter or result Note that everything that is supported by the storage service and that is stored to disk will be perfectly recovered. For instance, you store a tuple of numpy 32 bit integers, you will get a tuple of numpy 32 bit integers after loading independent of the platform! :param stuff_to_sore: Result or parameter to store In order to determine what to store, the function '_store' of the parameter or result is called. This function returns a dictionary with name keys and data to store as values. In order to determine how to store the data, the storage flags are considered, see below. The function '_store' has to return a dictionary containing values only from the following objects: * python natives (int, long, str, bool, float, complex), * numpy natives, arrays and matrices of type np.int8-64, np.uint8-64, np.float32-64, np.complex, np.str * python lists and tuples of the previous types (python natives + numpy natives and arrays) Lists and tuples are not allowed to be nested and must be homogeneous, i.e. only contain data of one particular type. Only integers, or only floats, etc. * python dictionaries of the previous types (not nested!), data can be heterogeneous, keys must be strings. For example, one key-value-pair of string and int and one key-value pair of string and float, and so on. * pandas DataFrames_ * :class:`~pypet.parameter.ObjectTable` .. _DataFrames: http://pandas.pydata.org/pandas-docs/dev/dsintro.html#dataframe The keys from the '_store' dictionaries determine how the data will be named in the hdf5 file. :param store_data: How to store the data, see above for a descitpion. :param store_flags: Flags describing how to store data. :const:`~pypet.HDF5StorageService.ARRAY` ('ARRAY') Store stuff as array :const:`~pypet.HDF5StorageService.CARRAY` ('CARRAY') Store stuff as carray :const:`~pypet.HDF5StorageService.TABLE` ('TABLE') Store stuff as pytable :const:`~pypet.HDF5StorageService.DICT` ('DICT') Store stuff as pytable but reconstructs it later as dictionary on loading :const:`~pypet.HDF%StorageService.FRAME` ('FRAME') Store stuff as pandas data frame Storage flags can also be provided by the parameters and results themselves if they implement a function '_store_flags' that returns a dictionary with the names of the data to store as keys and the flags as values. If no storage flags are provided, they are automatically inferred from the data. See :const:`pypet.HDF5StorageService.TYPE_FLAG_MAPPING` for the mapping from type to flag. :param overwrite: Can be used if parts of a leaf should be replaced. Either a list of HDF5 names or `True` if this should account for all. * :const:`pypet.pypetconstants.DELETE` ('DELETE')
python
{ "resource": "" }
q274130
HDF5StorageService._srvc_load_several_items
test
def _srvc_load_several_items(self, iterable, *args, **kwargs): """Loads several items from an iterable Iterables are supposed to be of a format like `[(msg, item, args, kwarg),...]` If `args` and `kwargs` are not part of a tuple, they are taken from the current `args` and `kwargs` provided to this function. """ for input_tuple in iterable: msg = input_tuple[0] item = input_tuple[1] if len(input_tuple) > 2:
python
{ "resource": "" }
q274131
HDF5StorageService._srvc_check_hdf_properties
test
def _srvc_check_hdf_properties(self, traj): """Reads out the properties for storing new data into the hdf5file :param traj: The trajectory """ for attr_name in HDF5StorageService.ATTR_LIST: try: config = traj.f_get('config.hdf5.' + attr_name).f_get() setattr(self, attr_name, config) except AttributeError: self._logger.debug('Could not find `%s` in traj config, ' 'using (default) value `%s`.' % (attr_name, str(getattr(self, attr_name)))) for attr_name, table_name in HDF5StorageService.NAME_TABLE_MAPPING.items(): try: if table_name in ('parameters', 'config'): table_name += '_overview' config = traj.f_get('config.hdf5.overview.' + table_name).f_get() setattr(self, attr_name, config) except AttributeError: self._logger.debug('Could not find `%s` in traj config, ' 'using (default) value `%s`.' % (table_name, str(getattr(self, attr_name))))
python
{ "resource": "" }
q274132
HDF5StorageService._srvc_store_several_items
test
def _srvc_store_several_items(self, iterable, *args, **kwargs): """Stores several items from an iterable Iterables are supposed to be of a format like `[(msg, item, args, kwarg),...]` If `args` and `kwargs` are not part of a tuple, they are taken from the current `args` and `kwargs` provided to this function. """ for input_tuple in iterable: msg = input_tuple[0] item = input_tuple[1] if len(input_tuple) >
python
{ "resource": "" }
q274133
HDF5StorageService._srvc_closing_routine
test
def _srvc_closing_routine(self, closing): """Routine to close an hdf5 file The file is closed only when `closing=True`. `closing=True` means that the file was opened in the current highest recursion level. This prevents re-opening and closing of the file if `store` or `load` are called recursively. """ if (not self._keep_open and closing and self.is_open): f_fd = self._hdf5file.fileno() self._hdf5file.flush() try: os.fsync(f_fd) try: self._hdf5store.flush(fsync=True) except TypeError: f_fd = self._hdf5store._handle.fileno() self._hdf5store.flush() os.fsync(f_fd) except OSError as exc: # This seems to be the only way to avoid an OSError under Windows errmsg = ('Encountered OSError while flushing file.'
python
{ "resource": "" }
q274134
HDF5StorageService._srvc_extract_file_information
test
def _srvc_extract_file_information(self, kwargs): """Extracts file information from kwargs. Note that `kwargs` is not passed as `**kwargs` in order to also `pop` the elements on the level of the function calling `_srvc_extract_file_information`. """ if 'filename' in kwargs: self._filename = kwargs.pop('filename') if 'file_title' in kwargs: self._file_title = kwargs.pop('file_title')
python
{ "resource": "" }
q274135
HDF5StorageService._trj_backup_trajectory
test
def _trj_backup_trajectory(self, traj, backup_filename=None): """Backs up a trajectory. :param traj: Trajectory that should be backed up :param backup_filename: Path and filename of backup file. If None is specified the storage service defaults to `path_to_trajectory_hdf5_file/backup_trajectory_name.hdf`. """ self._logger.info('Storing backup of %s.' % traj.v_name) mypath, _ = os.path.split(self._filename) if backup_filename is None: backup_filename = os.path.join('%s' % mypath, 'backup_%s.hdf5' % traj.v_name) backup_hdf5file = pt.open_file(filename=backup_filename,
python
{ "resource": "" }
q274136
HDF5StorageService._trj_read_out_row
test
def _trj_read_out_row(colnames, row): """Reads out a row and returns a dictionary containing the row content. :param colnames: List of column names :param row: A pytables table row :return: A dictionary with colnames as keys and content as values
python
{ "resource": "" }
q274137
HDF5StorageService._trj_prepare_merge
test
def _trj_prepare_merge(self, traj, changed_parameters, old_length): """Prepares a trajectory for merging. This function will already store extended parameters. :param traj: Target of merge :param changed_parameters: List of extended parameters (i.e. their names). """ if not traj._stored: traj.f_store() # Update meta information infotable = getattr(self._overview_group, 'info') insert_dict = self._all_extract_insert_dict(traj, infotable.colnames) self._all_add_or_modify_row(traj.v_name, insert_dict, infotable, index=0, flags=(HDF5StorageService.MODIFY_ROW,)) # Store extended parameters for param_name in changed_parameters: param = traj.f_get(param_name) try: self._all_delete_parameter_or_result_or_group(param) except pt.NoSuchNodeError: pass # We are fine and the node did not exist in the first place # Increase the run table by the number of new runs run_table = getattr(self._overview_group, 'runs') actual_rows = run_table.nrows self._trj_fill_run_table(traj, actual_rows, len(traj)) # Extract parameter summary and if
python
{ "resource": "" }
q274138
HDF5StorageService._trj_load_meta_data
test
def _trj_load_meta_data(self, traj, load_data, as_new, with_run_information, force): """Loads meta information about the trajectory Checks if the version number does not differ from current pypet version Loads, comment, timestamp, name, version from disk in case trajectory is not loaded as new. Updates the run information as well. """ metatable = self._overview_group.info metarow = metatable[0] try: version = metarow['version'].decode('utf-8') except (IndexError, ValueError) as ke: self._logger.error('Could not check version due to: %s' % str(ke)) version = '`COULD NOT BE LOADED`' try: python = metarow['python'].decode('utf-8') except (IndexError, ValueError) as ke: self._logger.error('Could not check version due to: %s' % str(ke)) python = '`COULD NOT BE LOADED`' self._trj_check_version(version, python, force) # Load the skeleton information self._grp_load_group(traj, load_data=load_data, with_links=False, recursive=False, _traj=traj, _as_new=as_new, _hdf5_group=self._trajectory_group) if as_new: length = int(metarow['length']) for irun in range(length): traj._add_run_info(irun) else: traj._comment = metarow['comment'].decode('utf-8') traj._timestamp = float(metarow['timestamp']) traj._trajectory_timestamp = traj._timestamp traj._time = metarow['time'].decode('utf-8') traj._trajectory_time = traj._time traj._name = metarow['name'].decode('utf-8') traj._trajectory_name = traj._name traj._version = version traj._python = python single_run_table = self._overview_group.runs if with_run_information: for row in single_run_table.iterrows(): name = row['name'].decode('utf-8') idx = int(row['idx']) timestamp = float(row['timestamp']) time_ = row['time'].decode('utf-8') completed = int(row['completed'])
python
{ "resource": "" }
q274139
HDF5StorageService._tree_load_sub_branch
test
def _tree_load_sub_branch(self, traj_node, branch_name, load_data=pypetconstants.LOAD_DATA, with_links=True, recursive=False, max_depth=None, _trajectory=None, _as_new=False, _hdf5_group=None): """Loads data starting from a node along a branch and starts recursively loading all data at end of branch. :param traj_node: The node from where loading starts :param branch_name: A branch along which loading progresses. Colon Notation is used: 'group1.group2.group3' loads 'group1', then 'group2', then 'group3' and then finally recursively all children and children's children below 'group3' :param load_data: How to load the data :param with_links: If links should be loaded :param recursive: If loading recursively :param max_depth: The maximum depth to load the tree :param _trajectory: The trajectory :param _as_new: If trajectory is loaded as new :param _hdf5_group: HDF5 node in the file corresponding to `traj_node`. """ if load_data == pypetconstants.LOAD_NOTHING: return if max_depth is None: max_depth = float('inf') if _trajectory is None: _trajectory = traj_node.v_root if _hdf5_group is None: hdf5_group_name = traj_node.v_full_name.replace('.', '/') # Get child node to load if hdf5_group_name == '': _hdf5_group = self._trajectory_group else: try: _hdf5_group = self._hdf5file.get_node(where=self._trajectory_group, name=hdf5_group_name) except pt.NoSuchNodeError: self._logger.error('Cannot find `%s` the hdf5 node `%s` does not exist!'
python
{ "resource": "" }
q274140
HDF5StorageService._trj_check_version
test
def _trj_check_version(self, version, python, force): """Checks for version mismatch Raises a VersionMismatchError if version of loaded trajectory and current pypet version do not match. In case of `force=True` error is not raised only a warning is emitted. """ curr_python = pypetconstants.python_version_string if (version != VERSION or curr_python != python) and not force: raise pex.VersionMismatchError('Current pypet version is %s used under python %s ' ' but your trajectory' ' was created with version %s and python %s.' ' Use >>force=True<< to perform your load regardless'
python
{ "resource": "" }
q274141
HDF5StorageService._trj_fill_run_table
test
def _trj_fill_run_table(self, traj, start, stop): """Fills the `run` overview table with information. Will also update new information. """ def _make_row(info_dict): row = (info_dict['idx'], info_dict['name'], info_dict['time'], info_dict['timestamp'], info_dict['finish_timestamp'], info_dict['runtime'], info_dict['parameter_summary'], info_dict['short_environment_hexsha'], info_dict['completed'])
python
{ "resource": "" }
q274142
HDF5StorageService._trj_load_exploration
test
def _trj_load_exploration(self, traj): """Recalls names of all explored parameters""" if hasattr(self._overview_group, 'explorations'): explorations_table = self._overview_group._f_get_child( 'explorations') for row in explorations_table.iterrows(): param_name = row['explorations'].decode('utf-8') if param_name not in traj._explored_parameters: traj._explored_parameters[param_name] = None else: # This is for backwards compatibility for what in ('parameters', 'derived_parameters'): if hasattr(self._trajectory_group, what):
python
{ "resource": "" }
q274143
HDF5StorageService._trj_store_explorations
test
def _trj_store_explorations(self, traj): """Stores a all explored parameter names for internal recall""" nexplored = len(traj._explored_parameters) if nexplored > 0: if hasattr(self._overview_group, 'explorations'): explorations_table = self._overview_group._f_get_child('explorations') if len(explorations_table) != nexplored: self._hdf5file.remove_node(where=self._overview_group, name='explorations') if not hasattr(self._overview_group, 'explorations'): explored_list = list(traj._explored_parameters.keys()) if explored_list: string_col = self._all_get_table_col('explorations', explored_list,
python
{ "resource": "" }
q274144
HDF5StorageService._srvc_make_overview_tables
test
def _srvc_make_overview_tables(self, tables_to_make, traj=None): """Creates the overview tables in overview group""" for table_name in tables_to_make: # Prepare the tables desciptions, depending on which overview table we create # we need different columns paramdescriptiondict = {} expectedrows = 0 # Every overview table has a name and location column paramdescriptiondict['location'] = pt.StringCol( pypetconstants.HDF5_STRCOL_MAX_LOCATION_LENGTH, pos=0) paramdescriptiondict['name'] = pt.StringCol(pypetconstants.HDF5_STRCOL_MAX_NAME_LENGTH, pos=1) paramdescriptiondict['comment'] = pt.StringCol( pypetconstants.HDF5_STRCOL_MAX_COMMENT_LENGTH) paramdescriptiondict['value'] = pt.StringCol( pypetconstants.HDF5_STRCOL_MAX_VALUE_LENGTH, pos=2) if table_name == 'config_overview': if traj is not None: expectedrows = len(traj._config) if table_name == 'parameters_overview': if traj is not None: expectedrows = len(traj._parameters) if table_name == 'explored_parameters_overview': paramdescriptiondict['range'] = pt.StringCol( pypetconstants.HDF5_STRCOL_MAX_RANGE_LENGTH) paramdescriptiondict['length'] = pt.IntCol() if traj is not None: expectedrows = len(traj._explored_parameters) if table_name.endswith('summary'): paramdescriptiondict['hexdigest'] = pt.StringCol(64, pos=10) # Check if the user provided an estimate of the amount of results per run # This can help to speed up storing if table_name == 'derived_parameters_overview': expectedrows = self._derived_parameters_per_run if traj is not None: expectedrows *=
python
{ "resource": "" }
q274145
HDF5StorageService._trj_store_trajectory
test
def _trj_store_trajectory(self, traj, only_init=False, store_data=pypetconstants.STORE_DATA, max_depth=None): """ Stores a trajectory to an hdf5 file Stores all groups, parameters and results """ if not only_init: self._logger.info('Start storing Trajectory `%s`.' % self._trajectory_name) else: self._logger.info('Initialising storage or updating meta data of Trajectory `%s`.' % self._trajectory_name) store_data = pypetconstants.STORE_NOTHING # In case we accidentally chose a trajectory name that already exist # We do not want to mess up the stored trajectory but raise an Error if not traj._stored and self._trajectory_group is not None: raise RuntimeError('You want to store a completely new trajectory with name' ' `%s` but this trajectory is already found in file `%s`.' 'Did you try to accidentally overwrite existing data? If ' 'you DO want to override existing data, use `overwrite_file=True`.' 'Note that this deletes the whole HDF5 file not just the particular ' 'trajectroy therein! ' % (traj.v_name, self._filename)) # Extract HDF5 settings from the trajectory self._srvc_check_hdf_properties(traj) # Store the trajectory for the first time if necessary: if self._trajectory_group is None: self._trajectory_group = self._hdf5file.create_group(where='/', name=self._trajectory_name, title=self._trajectory_name, filters=self._all_get_filters()) # Store meta information self._trj_store_meta_data(traj) # # Store recursively the config subtree # self._tree_store_recursively(pypetconstants.LEAF,traj.config,self._trajectory_group) if store_data in (pypetconstants.STORE_DATA_SKIPPING,
python
{ "resource": "" }
q274146
HDF5StorageService._tree_store_sub_branch
test
def _tree_store_sub_branch(self, traj_node, branch_name, store_data=pypetconstants.STORE_DATA, with_links=True, recursive=False, max_depth=None, hdf5_group=None): """Stores data starting from a node along a branch and starts recursively loading all data at end of branch. :param traj_node: The node where storing starts :param branch_name: A branch along which storing progresses. Colon Notation is used: 'group1.group2.group3' loads 'group1', then 'group2', then 'group3', and then finally recursively all children and children's children below 'group3'. :param store_data: How data should be stored :param with_links: If links should be stored :param recursive: If the rest of the tree should be recursively stored :param max_depth: Maximum depth to store :param hdf5_group: HDF5 node in the file corresponding to `traj_node` """ if store_data == pypetconstants.STORE_NOTHING: return if max_depth is None: max_depth = float('inf') if hdf5_group is None: # Get parent hdf5 node location = traj_node.v_full_name hdf5_location = location.replace('.', '/') try: if location == '': hdf5_group = self._trajectory_group else: hdf5_group = self._hdf5file.get_node( where=self._trajectory_group, name=hdf5_location) except pt.NoSuchNodeError: self._logger.debug('Cannot store `%s` the parental hdf5 node with path `%s` does ' 'not exist on disk.' % (traj_node.v_name, hdf5_location)) if traj_node.v_is_leaf: self._logger.error('Cannot store `%s` the parental hdf5 ' 'node with path `%s` does ' 'not exist on disk! The child ' 'you want to store is a leaf node,' 'that cannot be stored without ' 'the parental node existing on ' 'disk.' % (traj_node.v_name, hdf5_location)) raise else: self._logger.debug('I will try to store the path from trajectory root to ' 'the child now.') self._tree_store_sub_branch(traj_node._nn_interface._root_instance,
python
{ "resource": "" }
q274147
HDF5StorageService._tree_create_leaf
test
def _tree_create_leaf(self, name, trajectory, hdf5_group): """ Creates a new pypet leaf instance. Returns the leaf and if it is an explored parameter the length of the range. """
python
{ "resource": "" }
q274148
HDF5StorageService._tree_load_nodes_dfs
test
def _tree_load_nodes_dfs(self, parent_traj_node, load_data, with_links, recursive, max_depth, current_depth, trajectory, as_new, hdf5_group): """Loads a node from hdf5 file and if desired recursively everything below :param parent_traj_node: The parent node whose child should be loaded :param load_data: How to load the data :param with_links: If links should be loaded :param recursive: Whether loading recursively below hdf5_group :param max_depth: Maximum depth :param current_depth: Current depth :param trajectory: The trajectory object :param as_new: If trajectory is loaded as new :param hdf5_group: The hdf5 group containing the child to be loaded """ if max_depth is None: max_depth = float('inf') loading_list = [(parent_traj_node, current_depth, hdf5_group)] while loading_list: parent_traj_node, current_depth, hdf5_group = loading_list.pop() if isinstance(hdf5_group, pt.link.SoftLink): if with_links: # We end up here when auto-loading a soft link self._tree_load_link(parent_traj_node, load_data=load_data, traj=trajectory, as_new=as_new, hdf5_soft_link=hdf5_group) continue name = hdf5_group._v_name is_leaf = self._all_get_from_attrs(hdf5_group, HDF5StorageService.LEAF) in_trajectory = name in parent_traj_node._children if is_leaf: # In case we have a leaf node, we need to check if we have to create a new # parameter or result
python
{ "resource": "" }
q274149
HDF5StorageService._tree_store_nodes_dfs
test
def _tree_store_nodes_dfs(self, parent_traj_node, name, store_data, with_links, recursive, max_depth, current_depth, parent_hdf5_group): """Stores a node to hdf5 and if desired stores recursively everything below it. :param parent_traj_node: The parental node :param name: Name of node to be stored :param store_data: How to store data :param with_links: If links should be stored :param recursive: Whether to store recursively the subtree :param max_depth: Maximum recursion depth in tree :param current_depth: Current depth :param parent_hdf5_group: Parent hdf5 group """ if max_depth is None: max_depth = float('inf') store_list = [(parent_traj_node, name, current_depth, parent_hdf5_group)] while store_list: parent_traj_node, name, current_depth, parent_hdf5_group = store_list.pop() # Check if we create a link if name in parent_traj_node._links: if with_links: self._tree_store_link(parent_traj_node, name, parent_hdf5_group) continue traj_node = parent_traj_node._children[name] # If the node does not exist in the hdf5 file create it if not hasattr(parent_hdf5_group, name): newly_created = True new_hdf5_group = self._hdf5file.create_group(where=parent_hdf5_group, name=name, filters=self._all_get_filters()) else: newly_created = False new_hdf5_group = getattr(parent_hdf5_group, name) if traj_node.v_is_leaf:
python
{ "resource": "" }
q274150
HDF5StorageService._all_store_param_or_result_table_entry
test
def _all_store_param_or_result_table_entry(self, instance, table, flags, additional_info=None): """Stores a single row into an overview table :param instance: A parameter or result instance :param table: Table where row will be inserted :param flags: Flags how to insert into the table. Potential Flags are `ADD_ROW`, `REMOVE_ROW`, `MODIFY_ROW` :param additional_info: Dictionary containing information that cannot be extracted from `instance`, but needs to be inserted, too. """ # assert isinstance(table, pt.Table) location = instance.v_location name = instance.v_name fullname = instance.v_full_name if (flags == (HDF5StorageService.ADD_ROW,) and table.nrows < 2 and 'location' in table.colnames): # We add the modify row option here because you cannot delete the very first # row of the table, so there is the rare condition, that the row might already # exist. # We also need to check if 'location' is in the columns in order to avoid # confusion with the smaller explored parameter overviews flags = (HDF5StorageService.ADD_ROW, HDF5StorageService.MODIFY_ROW) if flags == (HDF5StorageService.ADD_ROW,): # If we are sure we only want to
python
{ "resource": "" }
q274151
HDF5StorageService._all_get_or_create_table
test
def _all_get_or_create_table(self, where, tablename, description, expectedrows=None): """Creates a new table, or if the table already exists, returns it.""" where_node = self._hdf5file.get_node(where) if not tablename in where_node: if not expectedrows is None: table = self._hdf5file.create_table(where=where_node, name=tablename, description=description, title=tablename, expectedrows=expectedrows, filters=self._all_get_filters()) else:
python
{ "resource": "" }
q274152
HDF5StorageService._all_get_node_by_name
test
def _all_get_node_by_name(self, name): """Returns an HDF5 node by the path specified in `name`""" path_name = name.replace('.', '/')
python
{ "resource": "" }
q274153
HDF5StorageService._all_set_attributes_to_recall_natives
test
def _all_set_attributes_to_recall_natives(data, ptitem, prefix): """Stores original data type to hdf5 node attributes for preserving the data type. :param data: Data to be stored :param ptitem: HDF5 node to store data types as attributes. Can also be just a PTItemMock. :param prefix: String prefix to label and name data in HDF5 attributes """ # If `data` is a container, remember the container type if type(data) is tuple: HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.COLL_TYPE, HDF5StorageService.COLL_TUPLE) elif type(data) is list: HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.COLL_TYPE, HDF5StorageService.COLL_LIST) elif type(data) is np.ndarray: HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.COLL_TYPE, HDF5StorageService.COLL_NDARRAY) elif type(data) is np.matrix: HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.COLL_TYPE, HDF5StorageService.COLL_MATRIX) elif type(data) in pypetconstants.PARAMETER_SUPPORTED_DATA: HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.COLL_TYPE, HDF5StorageService.COLL_SCALAR) strtype = type(data).__name__ if not strtype in pypetconstants.PARAMETERTYPEDICT: raise TypeError('I do not know how to handle `%s` its type is `%s`.' % (str(data), repr(type(data)))) HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.SCALAR_TYPE, strtype) elif type(data) is dict: if len(data) > 0: HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.COLL_TYPE, HDF5StorageService.COLL_DICT) else: HDF5StorageService._all_set_attr(ptitem, prefix + HDF5StorageService.COLL_TYPE,
python
{ "resource": "" }
q274154
HDF5StorageService._all_recall_native_type
test
def _all_recall_native_type(self, data, ptitem, prefix): """Checks if loaded data has the type it was stored in. If not converts it. :param data: Data item to be checked and converted :param ptitem: HDf5 Node or Leaf from where data was loaded :param prefix: Prefix for recalling the data type from the hdf5 node attributes :return: Tuple, first item is the (converted) `data` item, second boolean whether item was converted or not. """ typestr = self._all_get_from_attrs(ptitem, prefix + HDF5StorageService.SCALAR_TYPE) colltype = self._all_get_from_attrs(ptitem, prefix + HDF5StorageService.COLL_TYPE) type_changed = False # Check what the original data type was from the hdf5 node attributes if colltype == HDF5StorageService.COLL_SCALAR: # Here data item was a scalar if isinstance(data, np.ndarray): # If we recall a numpy scalar, pytables loads a 1d array :-/ # So we have to change it to a real scalar value data = np.array([data])[0] type_changed = True if not typestr is None: # Check if current type and stored type match # if not convert the data if typestr != type(data).__name__: if typestr == str.__name__: data = data.decode(self._encoding) else: try: data = pypetconstants.PARAMETERTYPEDICT[typestr](data) except KeyError: # For compatibility with
python
{ "resource": "" }
q274155
HDF5StorageService._all_add_or_modify_row
test
def _all_add_or_modify_row(self, item_name, insert_dict, table, index=None, condition=None, condvars=None, flags=(ADD_ROW, MODIFY_ROW,)): """Adds or changes a row in a pytable. :param item_name: Name of item, the row is about, only important for throwing errors. :param insert_dict: Dictionary of data that is about to be inserted into the pytables row. :param table: The table to insert or modify a row in :param index: Index of row to be modified. Instead of an index a search condition can be used as well, see below. :param condition: Condition to search for in the table :param condvars: Variables for the search condition :param flags: Flags whether to add, modify, or remove a row in the table """ if len(flags) == 0: # No flags means no-op return # You can only specify either an index or a condition not both if index is not None and condition is not None: raise ValueError('Please give either a condition or an index or none!') elif condition is not None: row_iterator = table.where(condition, condvars=condvars) elif index is not None: row_iterator = table.iterrows(index, index + 1) else: row_iterator = None try: row = next(row_iterator) except TypeError: row = None except StopIteration: row = None # multiple_entries = [] if ((HDF5StorageService.MODIFY_ROW in flags or HDF5StorageService.ADD_ROW in flags) and HDF5StorageService.REMOVE_ROW in flags): # You cannot remove and modify or add at the same time raise ValueError('You cannot add or modify and remove a row at the same time.') if row is None and HDF5StorageService.ADD_ROW in flags: # Here we add a new row row = table.row self._all_insert_into_row(row, insert_dict)
python
{ "resource": "" }
q274156
HDF5StorageService._all_insert_into_row
test
def _all_insert_into_row(self, row, insert_dict): """Copies data from `insert_dict` into a pytables `row`.""" for key, val in insert_dict.items(): try: row[key] = val
python
{ "resource": "" }
q274157
HDF5StorageService._all_extract_insert_dict
test
def _all_extract_insert_dict(self, item, colnames, additional_info=None): """Extracts information from a given item to be stored into a pytable row. Items can be a variety of things here, trajectories, single runs, group node, parameters, results. :param item: Item from which data should be extracted :param colnames: Names of the columns in the pytable :param additional_info: (dict) Additional information that should be stored into the pytable row that cannot be read out from `item`. :return: Dictionary containing the data to be inserted into a row """ insert_dict = {} if 'length' in colnames: insert_dict['length'] = len(item) if 'comment' in colnames: comment = self._all_cut_string(item.v_comment.encode('utf-8'), pypetconstants.HDF5_STRCOL_MAX_COMMENT_LENGTH, self._logger) insert_dict['comment'] = comment if 'location' in colnames: insert_dict['location'] = item.v_location.encode('utf-8') if 'name' in colnames: name = item._name if (not item.v_is_root or not item.v_is_run) else item._crun insert_dict['name'] = name.encode('utf-8') if 'class_name' in colnames: insert_dict['class_name'] = item.f_get_class_name().encode('utf-8') if 'value' in colnames: insert_dict['value'] = self._all_cut_string( item.f_val_to_str().encode('utf-8'), pypetconstants.HDF5_STRCOL_MAX_VALUE_LENGTH, self._logger) if 'hexdigest' in colnames: insert_dict['hexdigest'] = additional_info['hexdigest'] if 'idx' in colnames: insert_dict['idx'] = item.v_idx if 'time' in colnames: time_ = item._time insert_dict['time'] = time_.encode('utf-8') if 'timestamp' in colnames: timestamp = item._timestamp insert_dict['timestamp'] = timestamp if 'range' in colnames: third_length = pypetconstants.HDF5_STRCOL_MAX_RANGE_LENGTH // 3 + 10 item_range = itools.islice(item.f_get_range(copy=False), 0, third_length)
python
{ "resource": "" }
q274158
HDF5StorageService._all_cut_string
test
def _all_cut_string(string, max_length, logger): """Cuts string data to the maximum length allowed in a pytables column if string is too long. :param string: String to be cut :param max_length: Maximum allowed string length :param logger: Logger where messages about truncating should be written :return: String, cut if too long """
python
{ "resource": "" }
q274159
HDF5StorageService._all_create_or_get_group
test
def _all_create_or_get_group(self, name, parent_hdf5_group=None): """Creates or returns a group""" if not name in parent_hdf5_group: new_hdf5_group = self._hdf5file.create_group(where=parent_hdf5_group, name=name, title=name,
python
{ "resource": "" }
q274160
HDF5StorageService._all_create_or_get_groups
test
def _all_create_or_get_groups(self, key, start_hdf5_group=None): """Creates new or follows existing group nodes along a given colon separated `key`. :param key: Colon separated path along hdf5 file, e.g. `parameters.mobiles.cars`. :param start_hdf5_group: HDF5 group from where to start, leave `None` for the trajectory group. :return: Final group node, e.g. group node with name `cars`. """ if start_hdf5_group is None: newhdf5_group = self._trajectory_group
python
{ "resource": "" }
q274161
HDF5StorageService._ann_store_annotations
test
def _ann_store_annotations(self, item_with_annotations, node, overwrite=False): """Stores annotations into an hdf5 file.""" # If we overwrite delete all annotations first if overwrite is True or overwrite == 'v_annotations': annotated = self._all_get_from_attrs(node, HDF5StorageService.ANNOTATED) if annotated: current_attrs = node._v_attrs for attr_name in current_attrs._v_attrnames: if attr_name.startswith(HDF5StorageService.ANNOTATION_PREFIX): delattr(current_attrs, attr_name) delattr(current_attrs, HDF5StorageService.ANNOTATED) self._hdf5file.flush() # Only store annotations if the item has some if not item_with_annotations.v_annotations.f_is_empty(): anno_dict = item_with_annotations.v_annotations._dict current_attrs = node._v_attrs changed = False for field_name in anno_dict: val = anno_dict[field_name]
python
{ "resource": "" }
q274162
HDF5StorageService._ann_load_annotations
test
def _ann_load_annotations(self, item_with_annotations, node): """Loads annotations from disk.""" annotated = self._all_get_from_attrs(node, HDF5StorageService.ANNOTATED) if annotated: annotations = item_with_annotations.v_annotations # You can only load into non-empty annotations, to prevent overwriting data in RAM if not annotations.f_is_empty(): raise TypeError('Loading into non-empty annotations!') current_attrs = node._v_attrs for attr_name in current_attrs._v_attrnames:
python
{ "resource": "" }
q274163
HDF5StorageService._grp_store_group
test
def _grp_store_group(self, traj_group, store_data=pypetconstants.STORE_DATA, with_links=True, recursive=False, max_depth=None, _hdf5_group=None, _newly_created=False): """Stores a group node. For group nodes only annotations and comments need to be stored. """ if store_data == pypetconstants.STORE_NOTHING: return elif store_data == pypetconstants.STORE_DATA_SKIPPING and traj_group._stored: self._logger.debug('Already found `%s` on disk I will not store it!' % traj_group.v_full_name) elif not recursive: if _hdf5_group is None: _hdf5_group, _newly_created = self._all_create_or_get_groups(traj_group.v_full_name) overwrite = store_data == pypetconstants.OVERWRITE_DATA if (traj_group.v_comment != '' and (HDF5StorageService.COMMENT not in _hdf5_group._v_attrs or overwrite)): setattr(_hdf5_group._v_attrs, HDF5StorageService.COMMENT, traj_group.v_comment) if ((_newly_created or overwrite) and type(traj_group) not in (nn.NNGroupNode, nn.ConfigGroup, nn.ParameterGroup, nn.DerivedParameterGroup, nn.ResultGroup)): # We only store the name of the class if it is not one of the standard groups,
python
{ "resource": "" }
q274164
HDF5StorageService._grp_load_group
test
def _grp_load_group(self, traj_group, load_data=pypetconstants.LOAD_DATA, with_links=True, recursive=False, max_depth=None, _traj=None, _as_new=False, _hdf5_group=None): """Loads a group node and potentially everything recursively below""" if _hdf5_group is None: _hdf5_group = self._all_get_node_by_name(traj_group.v_full_name) _traj = traj_group.v_root if recursive: parent_traj_node = traj_group.f_get_parent() self._tree_load_nodes_dfs(parent_traj_node, load_data=load_data, with_links=with_links, recursive=recursive, max_depth=max_depth, current_depth=0, trajectory=_traj, as_new=_as_new,
python
{ "resource": "" }
q274165
HDF5StorageService._all_load_skeleton
test
def _all_load_skeleton(self, traj_node, hdf5_group): """Reloads skeleton data of a tree node""" if traj_node.v_annotations.f_is_empty(): self._ann_load_annotations(traj_node, hdf5_group) if traj_node.v_comment == '':
python
{ "resource": "" }
q274166
HDF5StorageService._prm_extract_missing_flags
test
def _prm_extract_missing_flags(data_dict, flags_dict): """Extracts storage flags for data in `data_dict` if they were not specified in `flags_dict`. See :const:`~pypet.storageservice.HDF5StorageService.TYPE_FLAG_MAPPING` for how to store different types of data per default. """ for key, data in data_dict.items(): if not key in flags_dict: dtype = type(data) if (dtype is np.ndarray or dtype is dict) and len(data) == 0: # Empty containers are stored as an Array # No need to ask for tuple or list, because they are always # stored as arrays. flags_dict[key] = HDF5StorageService.ARRAY
python
{ "resource": "" }
q274167
HDF5StorageService._prm_meta_add_summary
test
def _prm_meta_add_summary(self, instance): """Adds data to the summary tables and returns if `instance`s comment has to be stored. Also moves comments upwards in the hierarchy if purge_duplicate_comments is true and a lower index run has completed. Only necessary for *multiprocessing*. :return: Tuple * String specifying the subtree * Boolean whether to store the comment to `instance`s hdf5 node """ if instance.v_comment == '': return False where = instance.v_branch definitely_store_comment = True # Get the hexdigest of the comment to see if such a comment has been stored before bytes_comment = instance.v_comment.encode('utf-8') hexdigest = hashlib.sha1(bytes_comment).hexdigest() hexdigest = hexdigest.encode('utf-8') # Get the overview table table_name = where + '_summary' # Check if the overview
python
{ "resource": "" }
q274168
HDF5StorageService._prm_add_meta_info
test
def _prm_add_meta_info(self, instance, group, overwrite=False): """Adds information to overview tables and meta information to the `instance`s hdf5 `group`. :param instance: Instance to store meta info about :param group: HDF5 group of instance :param overwrite: If data should be explicitly overwritten """ if overwrite: flags = () else: flags = (HDF5StorageService.ADD_ROW,) definitely_store_comment = True try: # Check if we need to store the comment. Maybe update the overview tables # accordingly if the current run index is lower than the one in the table. definitely_store_comment = self._prm_meta_add_summary(instance) try: # Update the summary overview table table_name = instance.v_branch + '_overview' table = getattr(self._overview_group, table_name) if len(table) < pypetconstants.HDF5_MAX_OVERVIEW_TABLE_LENGTH: self._all_store_param_or_result_table_entry(instance, table, flags=flags) except pt.NoSuchNodeError: pass except Exception as exc: self._logger.error('Could not store information table due to `%s`.' % repr(exc)) if ((not self._purge_duplicate_comments or definitely_store_comment) and
python
{ "resource": "" }
q274169
HDF5StorageService._prm_store_from_dict
test
def _prm_store_from_dict(self, fullname, store_dict, hdf5_group, store_flags, kwargs): """Stores a `store_dict`""" for key, data_to_store in store_dict.items(): # self._logger.log(1, 'SUB-Storing %s [%s]', key, str(store_dict[key])) original_hdf5_group = None flag = store_flags[key] if '.' in key: original_hdf5_group = hdf5_group split_key = key.split('.') key = split_key.pop() for inner_key in split_key: hdf5_group, newly_created = self._all_create_or_get_group(inner_key, hdf5_group) if newly_created: setattr(hdf5_group._v_attrs, HDF5StorageService.STORAGE_TYPE, HDF5StorageService.NESTED_GROUP) else: store_type = self._all_get_from_attrs(hdf5_group, HDF5StorageService.STORAGE_TYPE) if store_type != HDF5StorageService.NESTED_GROUP: raise ValueError('You want to nested results but `%s` is already ' 'of type `%s`!' % (hdf5_group._v_name, store_type)) # Iterate through the data and store according to the storage flags if key in hdf5_group: # We won't change any data that is found on disk self._logger.debug( 'Found %s already in hdf5 node of %s, so I will ignore it.' % (key, fullname)) continue if flag == HDF5StorageService.TABLE: # self._logger.log(1, 'SUB-Storing %s TABLE', key) self._prm_write_into_pytable(key, data_to_store, hdf5_group, fullname, **kwargs) elif flag == HDF5StorageService.DICT: # self._logger.log(1, 'SUB-Storing %s DICT', key) self._prm_write_dict_as_table(key, data_to_store, hdf5_group, fullname,
python
{ "resource": "" }
q274170
HDF5StorageService._prm_store_parameter_or_result
test
def _prm_store_parameter_or_result(self, instance, store_data=pypetconstants.STORE_DATA, store_flags=None, overwrite=None, with_links=False, recursive=False, _hdf5_group=None, _newly_created=False, **kwargs): """Stores a parameter or result to hdf5. :param instance: The instance to be stored :param store_data: How to store data :param store_flags: Dictionary containing how to store individual data, usually empty. :param overwrite: Instructions how to overwrite data :param with_links: Placeholder because leaves have no links :param recursive: Placeholder, because leaves have no children :param _hdf5_group: The hdf5 group for storing the parameter or result :param _newly_created: If should be created in a new form """ if store_data == pypetconstants.STORE_NOTHING: return elif store_data == pypetconstants.STORE_DATA_SKIPPING and instance._stored: self._logger.debug('Already found `%s` on disk I will not store it!' % instance.v_full_name) return elif store_data == pypetconstants.OVERWRITE_DATA: if not overwrite: overwrite = True fullname = instance.v_full_name self._logger.debug('Storing `%s`.' % fullname) if _hdf5_group is None: # If no group is provided we might need to create one _hdf5_group, _newly_created = self._all_create_or_get_groups(fullname) # kwargs_flags = {} # Dictionary to change settings # old_kwargs = {} store_dict = {} # If the user did not supply storage flags, we need to set it to the empty dictionary if store_flags is None: store_flags = {} try: # Get the data to store from the instance if not instance.f_is_empty(): store_dict = instance._store() try: # Ask the instance for storage flags instance_flags = instance._store_flags().copy() # copy to avoid modifying the # original data except AttributeError: # If it does not provide any, set it to the empty dictionary instance_flags = {} # User specified flags have priority over the flags from the instance instance_flags.update(store_flags) store_flags = instance_flags # If we still have data in `store_dict` about which we do not know how to store # it, pick default storage flags self._prm_extract_missing_flags(store_dict, store_flags) if overwrite: if isinstance(overwrite, str): overwrite = [overwrite] if overwrite is True: to_delete = [key for key in store_dict.keys() if key in _hdf5_group] self._all_delete_parameter_or_result_or_group(instance, delete_only=to_delete, _hdf5_group=_hdf5_group) elif isinstance(overwrite, (list, tuple)): overwrite_set = set(overwrite) key_set = set(store_dict.keys()) stuff_not_to_be_overwritten = overwrite_set - key_set if overwrite!='v_annotations' and len(stuff_not_to_be_overwritten)
python
{ "resource": "" }
q274171
HDF5StorageService._prm_write_shared_array
test
def _prm_write_shared_array(self, key, data, hdf5_group, full_name, flag, **kwargs): """Creates and array that can be used with an HDF5 array object""" if flag == HDF5StorageService.ARRAY: self._prm_write_into_array(key, data, hdf5_group, full_name, **kwargs) elif flag in (HDF5StorageService.CARRAY, HDF5StorageService.EARRAY, HDF5StorageService.VLARRAY): self._prm_write_into_other_array(key, data, hdf5_group, full_name,
python
{ "resource": "" }
q274172
HDF5StorageService._prm_write_shared_table
test
def _prm_write_shared_table(self, key, hdf5_group, fullname, **kwargs): """Creates a new empty table""" first_row = None description = None if 'first_row' in kwargs: first_row = kwargs.pop('first_row') if not 'description' in kwargs: description = {} for colname in first_row: data = first_row[colname] column = self._all_get_table_col(key, [data], fullname)
python
{ "resource": "" }
q274173
HDF5StorageService._prm_write_dict_as_table
test
def _prm_write_dict_as_table(self, key, data_to_store, group, fullname, **kwargs): """Stores a python dictionary as pytable :param key: Name of data item to store :param data_to_store: Dictionary to store :param group: Group node where to store data in hdf5 file :param fullname: Full name of the `data_to_store`s original container, only needed for throwing errors. """ if key in group: raise ValueError( 'Dictionary `%s` already exists in `%s`. Appending is not supported (yet).')
python
{ "resource": "" }
q274174
HDF5StorageService._prm_write_pandas_data
test
def _prm_write_pandas_data(self, key, data, group, fullname, flag, **kwargs): """Stores a pandas DataFrame into hdf5. :param key: Name of data item to store :param data: Pandas Data to Store :param group: Group node where to store data in hdf5 file :param fullname: Full name of the `data_to_store`s original container, only needed for throwing errors. :param flag: If it is a series, frame or panel """ try: if 'filters' not in kwargs: filters = self._all_get_filters(kwargs) kwargs['filters'] = filters if 'format' not in kwargs: kwargs['format'] = self.pandas_format if 'encoding' not in kwargs: kwargs['encoding'] = self.encoding overwrite = kwargs.pop('overwrite', False) if key in group and not (overwrite or kwargs.get('append', False)): raise ValueError( 'DataFrame `%s` already exists in `%s`. ' 'To append pass ``append=`True```.' %
python
{ "resource": "" }
q274175
HDF5StorageService._prm_write_into_other_array
test
def _prm_write_into_other_array(self, key, data, group, fullname, flag, **kwargs): """Stores data as carray, earray or vlarray depending on `flag`. :param key: Name of data item to store :param data: Data to store :param group: Group node where to store data in hdf5 file :param fullname: Full name of the `data_to_store`s original container, only needed for throwing errors. :param recall: If container type and data type for perfect recall should be stored :param flag: How to store: CARRAY, EARRAY, VLARRAY """ try: if flag == HDF5StorageService.CARRAY: factory = self._hdf5file.create_carray elif flag == HDF5StorageService.EARRAY: factory = self._hdf5file.create_earray elif flag == HDF5StorageService.VLARRAY: factory = self._hdf5file.create_vlarray else: raise RuntimeError('You shall not pass!') if key in group: raise ValueError( 'CArray `%s` already exists in `%s`. Appending is not supported (yet).') if 'filters' in kwargs: filters = kwargs.pop('filters') else: filters = self._all_get_filters(kwargs) try: other_array = factory(where=group, name=key, obj=data, filters=filters, **kwargs) except (ValueError, TypeError) as exc: try:
python
{ "resource": "" }
q274176
HDF5StorageService._prm_write_into_array
test
def _prm_write_into_array(self, key, data, group, fullname, **kwargs): """Stores data as array. :param key: Name of data item to store :param data: Data to store :param group: Group node where to store data in hdf5 file :param fullname: Full name of the `data_to_store`s original container, only needed for throwing errors. :param recall: If container type and data type for perfect recall should be stored """ try: if key in group: raise ValueError( 'Array `%s` already exists in `%s`. Appending is not supported (yet).') try: array = self._hdf5file.create_array(where=group, name=key, obj=data, **kwargs) except (TypeError, ValueError) as exc: try: if type(data) is dict and len(data) == 0: # We cannot store an empty dictionary, # but we can use an empty tuple as a dummy. conv_data = () elif isinstance(data, str): conv_data = data.encode(self._encoding) elif isinstance(data, int): conv_data = np.int64(data) else: conv_data = [] for string in data:
python
{ "resource": "" }
q274177
HDF5StorageService._lnk_delete_link
test
def _lnk_delete_link(self, link_name): """Removes a link from disk""" translated_name =
python
{ "resource": "" }
q274178
HDF5StorageService._all_delete_parameter_or_result_or_group
test
def _all_delete_parameter_or_result_or_group(self, instance, delete_only=None, remove_from_item=False, recursive=False, _hdf5_group=None): """Removes a parameter or result or group from the hdf5 file. :param instance: Instance to be removed :param delete_only: List of elements if you only want to delete parts of a leaf node. Note that this needs to list the names of the hdf5 subnodes. BE CAREFUL if you erase parts of a leaf. Erasing partly happens at your own risk, it might be the case that you can no longer reconstruct the leaf from the leftovers! :param remove_from_item: If using `delete_only` and `remove_from_item=True` after deletion the data item is also removed from the `instance`. :param recursive: If a group node has children, you will can delete it if recursive is True. """ split_name = instance.v_location.split('.') if _hdf5_group is None: where = '/' + self._trajectory_name + '/' + '/'.join(split_name) node_name = instance.v_name _hdf5_group = self._hdf5file.get_node(where=where, name=node_name) if delete_only is None: if instance.v_is_group and not recursive and len(_hdf5_group._v_children) != 0: raise TypeError('You cannot remove the group `%s`, it has children, please ' 'use `recursive=True` to enforce removal.' % instance.v_full_name) _hdf5_group._f_remove(recursive=True) else: if not instance.v_is_leaf: raise ValueError('You can only choose `delete_only` mode for leafs.')
python
{ "resource": "" }
q274179
HDF5StorageService._prm_write_into_pytable
test
def _prm_write_into_pytable(self, tablename, data, hdf5_group, fullname, **kwargs): """Stores data as pytable. :param tablename: Name of the data table :param data: Data to store :param hdf5_group: Group node where to store data in hdf5 file :param fullname: Full name of the `data_to_store`s original container, only needed for throwing errors. """ datasize = data.shape[0] try: # Get a new pytables description from the data and create a new table description_dict, data_type_dict = self._prm_make_description(data, fullname) description_dicts = [{}] if len(description_dict) > ptpa.MAX_COLUMNS: # For optimization we want to store the original data types into another table # and split the tables into several ones new_table_group = self._hdf5file.create_group(where=hdf5_group, name=tablename, filters=self._all_get_filters(kwargs.copy())) count = 0 for innerkey in description_dict: val = description_dict[innerkey] if count == ptpa.MAX_COLUMNS: description_dicts.append({}) count = 0 description_dicts[-1][innerkey] = val count += 1 setattr(new_table_group._v_attrs, HDF5StorageService.STORAGE_TYPE, HDF5StorageService.TABLE) setattr(new_table_group._v_attrs, HDF5StorageService.SPLIT_TABLE, 1) hdf5_group = new_table_group else: description_dicts = [description_dict] for idx, descr_dict in enumerate(description_dicts): if idx == 0: tblname = tablename else: tblname = tablename + '_%d' % idx table = self._hdf5file.create_table(where=hdf5_group, name=tblname, description=descr_dict, title=tblname, expectedrows=datasize, filters=self._all_get_filters(kwargs.copy())) row = table.row for n in range(datasize): # Fill the columns with data, note if the parameter was extended nstart!=0 for key in descr_dict: row[key] = data[key][n] row.append() # Remember the original types of the data for perfect recall if idx == 0 and len(description_dict) <= ptpa.MAX_COLUMNS: # We only have a single table and # we can store the original data types as attributes for field_name in data_type_dict: type_description = data_type_dict[field_name]
python
{ "resource": "" }
q274180
HDF5StorageService._prm_make_description
test
def _prm_make_description(self, data, fullname): """ Returns a description dictionary for pytables table creation""" def _convert_lists_and_tuples(series_of_data): """Converts lists and tuples to numpy arrays""" if isinstance(series_of_data[0], (list, tuple)): # and not isinstance(series_of_data[0], np.ndarray): # If the first data item is a list, the rest must be as well, since # data has to be homogeneous for idx, item in enumerate(series_of_data): series_of_data[idx] = np.array(item) descriptiondict = {} # dictionary containing the description to build a pytables table original_data_type_dict = {} # dictionary containing the original data types
python
{ "resource": "" }
q274181
HDF5StorageService._all_get_table_col
test
def _all_get_table_col(self, key, column, fullname): """ Creates a pytables column instance. The type of column depends on the type of `column[0]`. Note that data in `column` must be homogeneous! """ val = column[0] try: # # We do not want to loose int_ if type(val) is int: return pt.IntCol() if isinstance(val, (str, bytes)): itemsize = int(self._prm_get_longest_stringsize(column))
python
{ "resource": "" }
q274182
HDF5StorageService._prm_get_longest_stringsize
test
def _prm_get_longest_stringsize(string_list): """ Returns the longest string size for a string entry across data.""" maxlength = 1 for stringar in string_list: if isinstance(stringar, np.ndarray): if stringar.ndim > 0: for string in stringar.ravel(): maxlength = max(len(string), maxlength) else:
python
{ "resource": "" }
q274183
HDF5StorageService._prm_load_into_dict
test
def _prm_load_into_dict(self, full_name, load_dict, hdf5_group, instance, load_only, load_except, load_flags, _prefix = ''): """Loads into dictionary""" for node in hdf5_group: load_type = self._all_get_from_attrs(node, HDF5StorageService.STORAGE_TYPE) if _prefix: load_name = '%s.%s' % (_prefix, node._v_name) else: load_name = node._v_name if load_type == HDF5StorageService.NESTED_GROUP: self._prm_load_into_dict(full_name=full_name, load_dict=load_dict, hdf5_group=node, instance=instance, load_only=load_only, load_except=load_except, load_flags=load_flags, _prefix=load_name) continue if load_only is not None: if load_name not in load_only: continue else: load_only.remove(load_name) elif load_except is not None: if load_name in load_except: load_except.remove(load_name) continue # Recall from the hdf5 node attributes how the data was stored and reload accordingly if load_name in load_flags: load_type = load_flags[load_name] if load_type == HDF5StorageService.DICT: to_load = self._prm_read_dictionary(node, full_name) elif load_type == HDF5StorageService.TABLE: to_load = self._prm_read_table(node, full_name) elif load_type in (HDF5StorageService.ARRAY, HDF5StorageService.CARRAY,
python
{ "resource": "" }
q274184
HDF5StorageService._prm_read_dictionary
test
def _prm_read_dictionary(self, leaf, full_name): """Loads data that was originally a dictionary when stored :param leaf: PyTables table containing the dictionary data :param full_name: Full name of the parameter or result whose data is to be loaded :return: Data to be loaded """ try: # Load as Pbject Table temp_table = self._prm_read_table(leaf, full_name) # Turn the ObjectTable into a dictionary of lists (with length 1). temp_dict = temp_table.to_dict('list')
python
{ "resource": "" }
q274185
HDF5StorageService._prm_read_shared_data
test
def _prm_read_shared_data(self, shared_node, instance): """Reads shared data and constructs the appropraite class. :param shared_node: hdf5 node storing the pandas DataFrame :param full_name: Full name of the parameter or result whose data is to be loaded :return: Data to load """ try: data_type = self._all_get_from_attrs(shared_node, HDF5StorageService.SHARED_DATA_TYPE)
python
{ "resource": "" }
q274186
HDF5StorageService._prm_read_table
test
def _prm_read_table(self, table_or_group, full_name): """Reads a non-nested PyTables table column by column and created a new ObjectTable for the loaded data. :param table_or_group: PyTables table to read from or a group containing subtables. :param full_name: Full name of the parameter or result whose data is to be loaded :return: Data to be loaded """ try: result_table = None if self._all_get_from_attrs(table_or_group, HDF5StorageService.SPLIT_TABLE): table_name = table_or_group._v_name data_type_table_name = table_name + '__' + HDF5StorageService.STORAGE_TYPE data_type_table = table_or_group._v_children[data_type_table_name] data_type_dict = {} for row in data_type_table: fieldname = row['field_name'].decode('utf-8') data_type_dict[fieldname] = row['data_type'].decode('utf-8') for sub_table in table_or_group: sub_table_name = sub_table._v_name if sub_table_name == data_type_table_name: continue for colname in sub_table.colnames: # Read Data column by column col = sub_table.col(colname) data_list = list(col) prefix = HDF5StorageService.FORMATTED_COLUMN_PREFIX % colname for idx, data in enumerate(data_list): # Recall original type of data data, type_changed = self._all_recall_native_type(data, PTItemMock( data_type_dict), prefix) if type_changed: data_list[idx] = data else: break # Construct or insert into an ObjectTable if result_table is None: result_table = ObjectTable(data={colname: data_list})
python
{ "resource": "" }
q274187
HDF5StorageService._prm_read_array
test
def _prm_read_array(self, array, full_name): """Reads data from an array or carray :param array: PyTables array or carray to read from :param full_name: Full name of the parameter or result whose data is to be loaded :return: Data to load """ try: result = self._svrc_read_array(array) # Recall original data types result, dummy = self._all_recall_native_type(result, array,
python
{ "resource": "" }
q274188
load_trajectory
test
def load_trajectory(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, new_name='my_trajectory', add_time=True, wildcard_functions=None, with_run_information=True, storage_service=storage.HDF5StorageService, **kwargs): """Helper function that creates a novel trajectory and loads it from disk. For the parameters see :func:`~pypet.trajectory.Trajectory.f_load`. ``new_name`` and ``add_time`` are only used in case ``as_new`` is ``True``. Accordingly, they determine the new name of trajectory. """ if name is None and index is None: raise ValueError('Please specify either a name or an index') elif name is not None and index is not None: raise ValueError('Please specify either a name or an index')
python
{ "resource": "" }
q274189
make_set_name
test
def make_set_name(idx): """Creates a run set name based on ``idx``""" GROUPSIZE = 1000 set_idx = idx // GROUPSIZE if set_idx >= 0:
python
{ "resource": "" }
q274190
Trajectory.f_set_properties
test
def f_set_properties(self, **kwargs): """Sets properties like ``v_fast_access``. For example: ``traj.f_set_properties(v_fast_access=True, v_auto_load=False)`` """ for name in kwargs:
python
{ "resource": "" }
q274191
Trajectory.f_add_to_dynamic_imports
test
def f_add_to_dynamic_imports(self, dynamic_imports): """Adds classes or paths to classes to the trajectory to create custom parameters. :param dynamic_imports: If you've written 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'` """ if not isinstance(dynamic_imports, (list, tuple)):
python
{ "resource": "" }
q274192
Trajectory.f_set_crun
test
def f_set_crun(self, name_or_idx): """Can make the trajectory behave as during a particular single run. It allows easier data analysis. Has the following effects: * `v_idx` and `v_crun` are set to the appropriate index and run name * All explored parameters are set to the corresponding value in the exploration ranges, i.e. when you call :func:`~pypet.parameter.Parameter.f_get` (or fast access) on them you will get in return the value at the corresponding `v_idx` position in the exploration range. * If you perform a search in the trajectory tree, the trajectory will
python
{ "resource": "" }
q274193
Trajectory.f_iter_runs
test
def f_iter_runs(self, start=0, stop=None, step=1, yields='name'): """Makes the trajectory iterate over all runs. :param start: Start index of run :param stop: Stop index, leave ``None`` for length of trajectory :param step: Stepsize :param yields: What should be yielded: ``'name'`` of run, ``idx`` of run or ``'self'`` to simply return the trajectory container. You can also pick ``'copy'`` to get **shallow** copies (ie the tree is copied but no leave nodes except explored ones.) of your trajectory, might lead to some of overhead. Note that after a full iteration, the trajectory is set back to normal. Thus, the following code snippet :: for run_name in traj.f_iter_runs(): # Do some stuff here... is equivalent to :: for run_name in traj.f_get_run_names(sort=True): traj.f_set_crun(run_name) # Do some stuff here... traj.f_set_crun(None) :return: Iterator over runs. The iterator itself
python
{ "resource": "" }
q274194
Trajectory.f_shrink
test
def f_shrink(self, force=False): """ Shrinks the trajectory and removes all exploration ranges from the parameters. Only possible if the trajectory has not been stored to disk before or was loaded as new. :param force: Usually you cannot shrink the trajectory if it has been stored to disk, because there's no guarantee that it is actually shrunk if there still exist explored parameters on disk. In case you are certain that you did not store explored parameters to disk set or you deleted all of them from disk set `force=True`. :raises: TypeError if the trajectory was stored before. """ if self._stored and not force: raise TypeError('Your trajectory is already stored to disk or database, shrinking is ' 'not allowed.') for param in self._explored_parameters.values(): param.f_unlock() try:
python
{ "resource": "" }
q274195
Trajectory._preset
test
def _preset(self, name, args, kwargs): """Generic preset function, marks a parameter or config for presetting.""" if self.f_contains(name, shortcuts=False): raise ValueError('Parameter `%s` is already part of your trajectory, use the normal'
python
{ "resource": "" }
q274196
Trajectory.f_preset_parameter
test
def f_preset_parameter(self, param_name, *args, **kwargs): """Presets parameter value before a parameter is added. Can be called before parameters are added to the Trajectory in order to change the values that are stored into the parameter on creation. After creation of a parameter, the instance of the parameter is called with `param.f_set(*args,**kwargs)` with `*args`, and `**kwargs` provided by the user with `f_preset_parameter`. Before an experiment is carried out it is checked if all
python
{ "resource": "" }
q274197
Trajectory._prepare_experiment
test
def _prepare_experiment(self): """Called by the environment to make some initial configurations before performing the individual runs. Checks if all parameters marked for presetting were preset. If not raises a DefaultReplacementError. Locks all parameters. Removal of potential results of previous runs in case the trajectory was expanded to avoid mixing up undesired shortcuts in natural naming. """ if len(self._changed_default_parameters): raise pex.PresettingError(
python
{ "resource": "" }
q274198
Trajectory.f_get_from_runs
test
def f_get_from_runs(self, name, include_default_run=True, use_indices=False, fast_access=False, with_links = True, shortcuts=True, max_depth=None, auto_load=False): """Searches for all occurrences of `name` in each run. Generates an ordered dictionary with the run names or indices as keys and found items as values. Example: >>> traj.f_get_from_runs(self, 'deep.universal_answer', use_indices=True, fast_access=True) OrderedDict([(0, 42), (1, 42), (2, 'fortytwo), (3, 43)]) :param name: String description of the item(s) to find. Cannot be full names but the part of the names that are below a `run_XXXXXXXXX` group. :param include_default_run: If results found under ``run_ALL`` should be accounted for every run or simply be ignored. :param use_indices: If `True` the keys of the resulting dictionary are the run indices (e.g. 0,1,2,3), otherwise the keys are run names (e.g. `run_00000000`, `run_000000001`) :param fast_access: Whether to return parameter or result instances or the values handled by these. :param with_links: If links should be considered :param shortcuts: If shortcuts are allowed and the trajectory can *hop* over nodes in the path. :param max_depth: Maximum depth (relative to start node) how search should progress in tree. `None` means no depth limit. Only relevant if `shortcuts` are allowed. :param auto_load: If data should be loaded from the storage service if it cannot be found in the current trajectory tree. Auto-loading will load group and leaf nodes currently not in memory and it will load data into empty leaves. Be aware that auto-loading does not work with shortcuts. :return: Ordered dictionary with run names or indices as keys and found items as values. Will only include runs where an item was actually found. """ result_dict = OrderedDict() old_crun = self.v_crun try: if len(self._run_parent_groups) > 0: for run_name in self.f_iter_runs(): # Iterate over all runs value = None already_found = False for run_parent_group in self._run_parent_groups.values(): if run_name not in run_parent_group._children: continue try: value = run_parent_group.f_get(run_name + '.' + name, fast_access=False, with_links=with_links, shortcuts=shortcuts, max_depth=max_depth,
python
{ "resource": "" }
q274199
Trajectory._is_completed
test
def _is_completed(self, name_or_id=None): """Private function such that it can still be called by the environment during a single run""" if name_or_id is None: return all(
python
{ "resource": "" }