code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
status = _status_decode(int(msg[7:8], 16)) return {'zone_number': int(msg[4:7])-1, 'zone_status': status}
def _zc_decode(self, msg)
ZC: Zone Change.
6.163877
4.905725
1.256466
zone_definitions = [ord(x)-0x30 for x in msg[4:4+Max.ZONES.value]] return {'zone_definitions': zone_definitions}
def _zd_decode(self, msg)
ZD: Zone definitions.
11.182454
8.584964
1.302563
zone_partitions = [ord(x)-0x31 for x in msg[4:4+Max.ZONES.value]] return {'zone_partitions': zone_partitions}
def _zp_decode(self, msg)
ZP: Zone partitions.
10.911744
7.825229
1.394431
status = [_status_decode(int(x, 16)) for x in msg[4:4+Max.ZONES.value]] return {'zone_statuses': status}
def _zs_decode(self, msg)
ZS: Zone statuses.
11.200786
8.301646
1.349225
sess_kwargs = {} if self._user is not None: sess_kwargs['user'] = self._user if self._password is not None: sess_kwargs['password'] = self._password self._login = xnat.connect(server=self._server, **sess_kwargs)
def connect(self)
Parameters ---------- prev_login : xnat.XNATSession An XNAT login that has been opened in the code that calls the method that calls login. It is wrapped in a NoExitWrapper so the returned connection can be used in a "with" statement in the method.
3.171204
2.975576
1.065745
if fileset.format is None: raise ArcanaUsageError( "Attempting to download {}, which has not been assigned a " "file format (see Fileset.formatted)".format(fileset)) self._check_repository(fileset) with self: # Connect to the XNAT repository ...
def get_fileset(self, fileset)
Caches a single fileset (if the 'path' attribute is accessed and it has not been previously cached for example Parameters ---------- fileset : Fileset The fileset to cache prev_login : xnat.XNATSession An XNATSession object to use for the connection. A ne...
3.315624
3.278728
1.011253
if fileset.uri is None: raise ArcanaUsageError( "Can't retrieve checksums as URI has not been set for {}" .format(fileset)) with self: checksums = {r['Name']: r['digest'] for r in self._login.get_json(fileset.uri +...
def get_checksums(self, fileset)
Downloads the MD5 digests associated with the files in the file-set. These are saved with the downloaded files in the cache and used to check if the files have been updated on the server Parameters ---------- resource : xnat.ResourceCatalog The xnat resource ...
7.256807
5.620864
1.291048
# TODO: need to make this generalisable via a # splitting+mapping function passed to the repository if subject_ids is not None: subject_ids = set( ('{:03d}'.format(s) if isinstance(s, int) else s) for s in subject_ids) return su...
def convert_subject_ids(self, subject_ids)
Convert subject ids to strings if they are integers
7.574833
6.963337
1.087817
subj_label, sess_label = self._get_item_labels(item) with self: xproject = self._login.projects[self.project_id] try: xsubject = xproject.subjects[subj_label] except KeyError: xsubject = self._login.classes.SubjectData( ...
def get_xsession(self, item)
Returns the XNAT session and cache dir corresponding to the item.
4.007036
3.674467
1.090508
subject_id = self.inv_map_subject_id(item.subject_id) visit_id = self.inv_map_visit_id(item.visit_id) subj_label, sess_label = self._get_labels( item.frequency, subject_id, visit_id) if not no_from_study and item.from_study is not None: sess_label += '_' ...
def _get_item_labels(self, item, no_from_study=False)
Returns the labels for the XNAT subject and sessions given the frequency and provided IDs.
3.007655
2.692597
1.117009
if frequency == 'per_session': subj_label = '{}_{}'.format(self.project_id, subject_id) sess_label = '{}_{}_{}'.format(self.project_id, subject_id, visit...
def _get_labels(self, frequency, subject_id=None, visit_id=None)
Returns the labels for the XNAT subject and sessions given the frequency and provided IDs.
1.604783
1.558589
1.029638
self._elk.send(cn_encode(self._index, time))
def turn_on(self, time)
(Helper) Turn on an output
35.54871
34.868462
1.019509
self.elk.send(cs_encode()) self.get_descriptions(TextDescriptions.OUTPUT.value)
def sync(self)
Retrieve areas from ElkM1
79.011665
42.926777
1.840615
help_text = run_matlab_cmd("help('{}')".format(self.test_func)) if not help_text: raise ArcanaRequirementNotFoundError( "Did not find test function '{}' for {}" .format(self.test_func, self)) return self.parse_help_text(help_text)
def detect_version_str(self)
Try to detect version of package from command help text. Bit of a long shot as they are typically included
7.308075
6.476799
1.128347
try: if self.side == 'left': level = self.device.device_data['leftTargetHeatingLevel'] elif self.side == 'right': level = self.device.device_data['rightTargetHeatingLevel'] return level except TypeError: return None
def target_heating_level(self)
Return target heating level.
2.997157
2.81345
1.065296
try: if self.side == 'left': level = self.device.device_data['leftHeatingLevel'] elif self.side == 'right': level = self.device.device_data['rightHeatingLevel'] return level except TypeError: return None
def heating_level(self)
Return heating level.
3.142774
2.902941
1.082617
if num > 9: return 0 try: if self.side == 'left': level = self.device.device_data_history[ num]['leftHeatingLevel'] elif self.side == 'right': level = self.device.device_data_history[ nu...
def past_heating_level(self, num)
Return a heating level from the past.
3.643637
3.489052
1.044306
try: if self.side == 'left': heat = self.device.device_data['leftNowHeating'] elif self.side == 'right': heat = self.device.device_data['rightNowHeating'] return heat except TypeError: return None
def now_heating(self)
Return current heating state.
3.386117
3.295445
1.027514
try: if self.side == 'left': timerem = self.device.device_data['leftHeatingDuration'] elif self.side == 'right': timerem = self.device.device_data['rightHeatingDuration'] return timerem except TypeError: return None
def heating_remaining(self)
Return seconds of heat time remaining.
4.123232
3.584817
1.150193
try: if self.side == 'left': lastseen = self.device.device_data['leftPresenceEnd'] elif self.side == 'right': lastseen = self.device.device_data['rightPresenceEnd'] date = datetime.fromtimestamp(int(lastseen)) \ ...
def last_seen(self)
Return mattress last seen time.
3.77111
3.249031
1.160688
heating_dict = { 'level': self.heating_level, 'target': self.target_heating_level, 'active': self.now_heating, 'remaining': self.heating_remaining, 'last_seen': self.last_seen, } return heating_dict
def heating_values(self)
Return a dict of all the current heating values.
3.227104
2.905425
1.110716
try: stages = self.intervals[0]['stages'] num_stages = len(stages) if num_stages == 0: return None # API now always has an awake state last in the dict # so always pull the second to last stage while we are # in a...
def current_sleep_stage(self)
Return sleep stage for in-progress session.
5.486022
5.251315
1.044695
try: stages = self.intervals[0]['stages'] breakdown = {'awake': 0, 'light': 0, 'deep': 0, 'rem': 0} for stage in stages: if stage['stage'] == 'awake': breakdown['awake'] += stage['duration'] elif stage['stage'] == '...
def current_sleep_breakdown(self)
Return durations of sleep stages for in-progress session.
1.904069
1.759895
1.081922
try: bedtemps = self.intervals[0]['timeseries']['tempBedC'] num_temps = len(bedtemps) if num_temps == 0: return None bedtemp = bedtemps[num_temps-1][1] except KeyError: bedtemp = None return bedtemp
def current_bed_temp(self)
Return current bed temperature for in-progress session.
4.310525
4.059783
1.061763
try: rmtemps = self.intervals[0]['timeseries']['tempRoomC'] num_temps = len(rmtemps) if num_temps == 0: return None rmtemp = rmtemps[num_temps-1][1] except KeyError: rmtemp = None return rmtemp
def current_room_temp(self)
Return current room temperature for in-progress session.
4.974461
4.575265
1.087251
try: rates = self.intervals[0]['timeseries']['respiratoryRate'] num_rates = len(rates) if num_rates == 0: return None rate = rates[num_rates-1][1] except KeyError: rate = None return rate
def current_resp_rate(self)
Return current respiratory rate for in-progress session.
4.535407
3.984542
1.13825
try: rates = self.intervals[0]['timeseries']['heartRate'] num_rates = len(rates) if num_rates == 0: return None rate = rates[num_rates-1][1] except KeyError: rate = None return rate
def current_heart_rate(self)
Return current heart rate for in-progress session.
4.574781
4.257783
1.074451
current_dict = { 'date': self.current_session_date, 'score': self.current_sleep_score, 'stage': self.current_sleep_stage, 'breakdown': self.current_sleep_breakdown, 'tnt': self.current_tnt, 'bed_temp': self.current_bed_temp, ...
def current_values(self)
Return a dict of all the 'current' parameters.
3.064357
2.955675
1.036771
try: date = self.intervals[1]['ts'] except KeyError: return None date_f = datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%fZ') now = time.time() offset = datetime.fromtimestamp(now) - datetime.utcfromtimestamp(now) return date_f + offset
def last_session_date(self)
Return date/time for start of last session data.
3.56898
3.329789
1.071834
try: stages = self.intervals[1]['stages'] except KeyError: return None breakdown = {'awake': 0, 'light': 0, 'deep': 0, 'rem': 0} for stage in stages: if stage['stage'] == 'awake': breakdown['awake'] += stage['duration'] ...
def last_sleep_breakdown(self)
Return durations of sleep stages for last complete session.
1.948748
1.789089
1.08924
try: bedtemps = self.intervals[1]['timeseries']['tempBedC'] except KeyError: return None tmp = 0 num_temps = len(bedtemps) if num_temps == 0: return None for temp in bedtemps: tmp += temp[1] bedtemp = tmp/...
def last_bed_temp(self)
Return avg bed temperature for last session.
4.556995
3.937922
1.157208
try: rmtemps = self.intervals[1]['timeseries']['tempRoomC'] except KeyError: return None tmp = 0 num_temps = len(rmtemps) if num_temps == 0: return None for temp in rmtemps: tmp += temp[1] rmtemp = tmp/num...
def last_room_temp(self)
Return avg room temperature for last session.
5.031084
4.342864
1.158471
try: rates = self.intervals[1]['timeseries']['heartRate'] except KeyError: return None tmp = 0 num_rates = len(rates) if num_rates == 0: return None for rate in rates: tmp += rate[1] rateavg = tmp/num_rate...
def last_heart_rate(self)
Return avg heart rate for last session.
4.964406
4.358387
1.139047
last_dict = { 'date': self.last_session_date, 'score': self.last_sleep_score, 'breakdown': self.last_sleep_breakdown, 'tnt': self.last_tnt, 'bed_temp': self.last_bed_temp, 'room_temp': self.last_room_temp, 'resp_rate': ...
def last_values(self)
Return a dict of all the 'last' parameters.
3.141378
2.986673
1.051798
local_5 = [] local_10 = [] for i in range(0, 10): level = self.past_heating_level(i) if level == 0: _LOGGER.debug('Cant calculate stats yet...') return if i < 5: local_5.append(level) local_...
def heating_stats(self)
Calculate some heating data stats.
2.169693
2.118294
1.024264
# self.heating_stats() if not self.presence: if self.heating_level > 50: # Can likely make this better if not self.now_heating: self.presence = True elif self.heating_level - self.target_heating_level >= 8: ...
def dynamic_presence(self)
Determine presence based on bed heating level and end presence time reported by the api. Idea originated from Alex Lee Yuk Cheung SmartThings Code.
2.902645
2.750426
1.055344
url = '{}/devices/{}'.format(API_URL, self.device.deviceid) # Catch bad inputs level = 10 if level < 10 else level level = 100 if level > 100 else level if self.side == 'left': data = { 'leftHeatingDuration': duration, 'leftT...
async def set_heating_level(self, level, duration=0)
Update heating data json.
3.782757
3.637857
1.039831
url = '{}/users/{}/trends'.format(API_URL, self.userid) params = { 'tz': self.device.tzone, 'from': startdate, 'to': enddate } trends = await self.device.api_get(url, params) if trends is None: _LOGGER.error('Unable to...
async def update_trend_data(self, startdate, enddate)
Update trends data json for specified time period.
4.536777
4.428565
1.024435
url = '{}/users/{}/intervals'.format(API_URL, self.userid) intervals = await self.device.api_get(url) if intervals is None: _LOGGER.error('Unable to fetch eight intervals data.') else: self.intervals = intervals['intervals']
async def update_intervals_data(self)
Update intervals data json for specified time period.
5.824703
5.152364
1.130491
m2m_data = {} if m2m_data is None else m2m_data obj.save_base(raw=True) for attr, values in m2m_data.items(): for value in values: getattr(obj, attr).add(value)
def save(obj=None, m2m_data=None)
Saves a deserialized model object. Uses save_base to avoid running code in model.save() and to avoid triggering signals (if raw=True).
2.639446
2.525619
1.045069
if ( not self.allow_self and transactions.filter(producer=socket.gethostname()).exists() ): raise TransactionDeserializerError( f"Not deserializing own transactions. Got " f"allow_self=False, hostname={socket.gethostname()}" ...
def deserialize_transactions(self, transactions=None, deserialize_only=None)
Deserializes the encrypted serialized model instances, tx, in a queryset of transactions. Note: each transaction instance contains encrypted JSON text that represents just ONE model instance.
5.079323
4.887338
1.039282
app_config = django_apps.get_app_config("django_collect_offline") for json_parser in app_config.custom_json_parsers: json_text = json_parser(json_text) return json_text
def custom_parser(self, json_text=None)
Runs json_text thru custom parsers.
5.617849
4.635785
1.211844
client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(hostname=self.private_hostname, username=self.username, key_filename=self.key_filename, timeout=self.timeout, ...
def cli(self)
cli lazy property
2.467827
2.406396
1.025528
# start shell, non-blocking channel chan = self.cli.invoke_shell(width=360, height=80) chan.setblocking(0) # set channel timeout chan.settimeout(10) # now waiting for shell prompt ('username@') result = "" count = 0 while count < 10: ...
def channel(self)
channel lazy property
5.602033
5.550159
1.009346
if not self.disable_rpyc: from plumbum import SshMachine return SshMachine(host=self.private_hostname, user=self.username, keyfile=self.key_filename, ssh_opts=["-o", "UserKnownHostsFile=/dev/null", ...
def pbm(self)
Plumbum lazy property
4.273166
3.477747
1.228717
if not self.disable_rpyc: try: import rpyc devnull_fd = open("/dev/null", "w") rpyc_dirname = os.path.dirname(rpyc.__file__) rnd_id = ''.join(random.choice(string.ascii_lowercase) for x in range(10)) pid_filena...
def rpyc(self)
RPyC lazy property
2.98631
2.96631
1.006742
if hasattr(self, '_lazy_sftp'): if self.sftp is not None: self.sftp.close() delattr(self, '_lazy_sftp') if hasattr(self, '_lazy_channel'): if self.channel is not None: self.channel.close() delattr(self, '_lazy_chann...
def disconnect(self)
Close the connection
1.678028
1.680761
0.998374
self.last_command = command return self.cli.exec_command(command, bufsize, get_pty=get_pty)
def exec_command(self, command, bufsize=-1, get_pty=False)
Execute a command in the connection @param command: command to execute @type command: str @param bufsize: buffer size @type bufsize: int @param get_pty: get pty @type get_pty: bool @return: the stdin, stdout, and stderr of the executing command @rtype:...
3.02864
4.605528
0.65761
status = None self.last_command = command stdin, stdout, stderr = self.cli.exec_command(command, get_pty=get_pty) if stdout and stderr and stdin: for _ in range(timeout): if stdout.channel.exit_status_ready(): status = stdout.chann...
def recv_exit_status(self, command, timeout=10, get_pty=False)
Execute a command and get its return value @param command: command to execute @type command: str @param timeout: command execution timeout @type timeout: int @param get_pty: get pty @type get_pty: bool @return: the exit code of the process or None in case of t...
2.288093
2.473081
0.925199
self._elk.send(cx_encode(self._index, value))
def set(self, value)
(Helper) Set counter to value
39.077744
40.052734
0.975657
with open(path, 'w') as f: try: json.dump(self.prov, f, indent=2) except TypeError: raise ArcanaError( "Could not serialise provenance record dictionary:\n{}" .format(pformat(self.prov)))
def save(self, path)
Saves the provenance object to a JSON file, optionally including checksums for inputs and outputs (which are initially produced mid- run) to insert during the write Parameters ---------- path : str Path to save the generated JSON file inputs : dict[str, str |...
4.843749
4.408436
1.098745
with open(path) as f: prov = json.load(f) return Record(pipeline_name, frequency, subject_id, visit_id, from_study, prov)
def load(cls, pipeline_name, frequency, subject_id, visit_id, from_study, path)
Loads a saved provenance object from a JSON file Parameters ---------- path : str Path to the provenance file frequency : str The frequency of the record subject_id : str | None The subject ID of the provenance record visit_id : str | ...
3.494669
3.202957
1.091076
if include is not None: include_res = [self._gen_prov_path_regex(p) for p in include] if exclude is not None: exclude_res = [self._gen_prov_path_regex(p) for p in exclude] diff = DeepDiff(self._prov, other._prov, ignore_order=True) # Create regular expres...
def mismatches(self, other, include=None, exclude=None)
Compares information stored within provenance objects with the exception of version information to see if they match. Matches are constrained to the paths passed to the 'include' kwarg, with the exception of sub-paths passed to the 'exclude' kwarg Parameters ---------- o...
2.716277
2.644968
1.02696
assert isinstance(substudy_name, basestring) assert isinstance(pipeline_getter, basestring) def translated_getter(self, **name_maps): substudy_spec = self.substudy_spec(substudy_name) # Combine mapping of names of sub-study specs with return getattr(...
def translate(cls, substudy_name, pipeline_getter, auto_added=False)
A method for translating pipeline constructors from a sub-study to the namespace of a multi-study. Returns a new method that calls the sub-study pipeline constructor with appropriate keyword arguments Parameters ---------- substudy_name : str Name of the sub-study ...
4.755776
4.769403
0.997143
for spec in self.study_class.data_specs(): if spec.name not in self._name_map: yield spec
def auto_data_specs(self)
Data specs in the sub-study class that are not explicitly provided in the name map
8.188116
3.715175
2.203965
for spec in self.study_class.parameter_specs(): if spec.name not in self._name_map: yield spec
def auto_param_specs(self)
Parameter pecs in the sub-study class that are not explicitly provided in the name map
9.261223
4.228038
2.19043
for i, node in NipypeMapNode._make_nodes(self, cwd=cwd): # "Cast" NiPype node to a Arcana Node and set Arcana Node # parameters node.__class__ = self.node_cls node._environment = self._environment node._versions = self._versions no...
def _make_nodes(self, cwd=None)
Cast generated nodes to be Arcana nodes
7.240436
6.207536
1.166395
query_file_match = list( filter(lambda i: query_name == i.stem, FLAT_QUERIES)) if not query_file_match: return None # TODO: Log warning if more than one match query_file = query_file_match[0] with open(query_file) as f: metadata, query_body = frontmatter.parse(f.read()) ...
def get_query(query_name)
Find file matching query_name, read and return query object
3.92931
3.836132
1.024289
query = get_query(query_name) if not query: query = SimpleNamespace() query.error = f"No query found matching '{query_name}'" return query try: result_mod = import_module( f'nerium.contrib.resultset.{query.result_mod}') except ModuleNotFoundError: ...
def get_result_set(query_name, **kwargs)
Call get_query, then submit query from file to resultset module
4.699644
4.769854
0.985281
query = get_result_set(query_name, **kwargs) result = query.result columns = list(result[0].keys()) data = [tuple(row.values()) for row in result] frame = tablib.Dataset() frame.headers = columns for row in data: frame.append(row) csvs = frame.export('csv') return csvs
def results_to_csv(query_name, **kwargs)
Generate CSV from result data
3.075996
2.997393
1.026224
self.loaded = True for model in models: model = model.lower() if model not in self.registry: self.registry.update({model: wrapper_cls or self.wrapper_cls}) if self.register_historical: historical_model = ".historical".j...
def register(self, models=None, wrapper_cls=None)
Registers with app_label.modelname, wrapper_cls.
3.313117
3.280563
1.009923
models = [] exclude_models = exclude_models or [] app_config = django_apps.get_app_config(app_label) for model in app_config.get_models(): if model._meta.label_lower in exclude_models: pass elif exclude_model_classes and issubclass(model, ...
def register_for_app( self, app_label=None, exclude_models=None, exclude_model_classes=None )
Registers all models for this app_label.
2.188404
2.077667
1.053298
if instance._meta.label_lower not in self.registry: raise ModelNotRegistered(f"{repr(instance)} is not registered with {self}.") wrapper_cls = self.registry.get(instance._meta.label_lower) or self.wrapper_cls if wrapper_cls: return wrapper_cls(instance) r...
def get_wrapped_instance(self, instance=None)
Returns a wrapped model instance.
3.993649
3.607326
1.107094
site_models = {} app_configs = ( django_apps.get_app_configs() if app_label is None else [django_apps.get_app_config(app_label)] ) for app_config in app_configs: model_list = [ model for model in app...
def site_models(self, app_label=None)
Returns a dictionary of registered models.
2.007491
1.962787
1.022776
# Don't need to cache fileset as it is already local as long # as the path is set if fileset._path is None: primary_path = self.fileset_path(fileset) aux_files = fileset.format.default_aux_file_paths(primary_path) if not op.exists(primary_path): ...
def get_fileset(self, fileset)
Set the path of the fileset from the repository
4.115158
4.194569
0.981068
# Load fields JSON, locking to prevent read/write conflicts # Would be better if only checked if locked to allow # concurrent reads but not possible with multi-process # locks (in my understanding at least). fpath = self.fields_json_path(field) try: w...
def get_field(self, field)
Update the value of the field from the repository
5.776665
5.669293
1.018939
target_path = self.fileset_path(fileset) if op.isfile(fileset.path): shutil.copyfile(fileset.path, target_path) # Copy side car files into repository for aux_name, aux_path in fileset.format.default_aux_file_paths( target_path).items(): ...
def put_fileset(self, fileset)
Inserts or updates a fileset in the repository
3.361089
3.261452
1.03055
fpath = self.fields_json_path(field) # Open fields JSON, locking to prevent other processes # reading or writing with InterProcessLock(fpath + self.LOCK_SUFFIX, logger=logger): try: with open(fpath, 'r') as f: dct = json.load(f) ...
def put_field(self, field)
Inserts or updates a field in the repository
2.947237
2.983972
0.987689
all_filesets = [] all_fields = [] all_records = [] for session_path, dirs, files in os.walk(self.root_dir): relpath = op.relpath(session_path, self.root_dir) path_parts = relpath.split(op.sep) if relpath != '.' else [] ids = self._extract_ids_...
def find_data(self, subject_ids=None, visit_ids=None, **kwargs)
Find all data within a repository, registering filesets, fields and provenance with the found_fileset, found_field and found_provenance methods, respectively Parameters ---------- subject_ids : list(str) List of subject IDs with which to filter the tree with. If ...
2.500369
2.356323
1.061132
deepest = -1 for path, dirs, files in os.walk(root_dir): depth = self.path_depth(path) filtered_files = self._filter_files(files, path) if filtered_files: logger.info("Guessing depth of directory repository at '{}' is" ...
def guess_depth(self, root_dir)
Try to guess the depth of a directory repository (i.e. whether it has sub-folders for multiple subjects or visits, depending on where files and/or derived label files are found in the hierarchy of sub-directories under the root dir. Parameters ---------- root_dir : str ...
3.52825
3.452729
1.021873
# *** GET CONNECTION PARAMS: *** # from frontmatter try: return query.metadata['data_source'] except KeyError: try: return dict(url=query.metadata['database_url']) except KeyError: pass # from file in directory if present db_file = query.path...
def get_data_source(query)
Get data source connection metadata based on config. Prefer, in order: - Query file frontmatter - `db.yaml` file in query subdirectory - DATABASE_URL in environment To allow for possible non-SQL sources to be contributed, we only return a config value here, and leave connecting to concr...
4.13576
3.445184
1.200447
if self.frequency == 'per_session': if subject_id is None or visit_id is None: raise ArcanaError( "The 'subject_id' ({}) and 'visit_id' ({}) must be " "provided to get an item from {}".format( subject_id, visit...
def item(self, subject_id=None, visit_id=None)
Returns a particular fileset|field in the collection corresponding to the given subject and visit_ids. subject_id and visit_id must be provided for relevant frequencies. Note that subject_id/visit_id can also be provided for non-relevant frequencies, they will just be ignored. P...
1.864742
1.862697
1.001098
tree_subject_ids = list(study.tree.subject_ids) subject_ids = list(self._collection.keys()) if tree_subject_ids != subject_ids: raise ArcanaUsageError( "Subject IDs in collection provided to '{}' ('{}') " "do not match Study tre...
def bind(self, study, **kwargs): # @UnusedVariable if self.frequency == 'per_subject'
Used for duck typing Collection objects with Spec and Match in source and sink initiation. Checks IDs match sessions in study.
2.053062
1.964975
1.044829
if from_study is None and name.derived: from_study = name.study.name name = name.name try: format_dct = self._filesets[(name, from_study)] except KeyError: available = [ ('{}(format={})'.format(f.name, f._resource_name) ...
def fileset(self, name, from_study=None, format=None): # @ReservedAssignment @IgnorePep8 if isinstance(name, BaseFileset)
Gets the fileset named 'name' produced by the Study named 'study' if provided. If a spec is passed instead of a str to the name argument, then the study will be set from the spec iff it is derived Parameters ---------- name : str | FilesetSpec The name of the fileset...
2.942298
3.001811
0.980174
if isinstance(name, BaseField): if from_study is None and name.derived: from_study = name.study.name name = name.name try: return self._fields[(name, from_study)] except KeyError: available = [d.name for d in self.fields ...
def field(self, name, from_study=None)
Gets the field named 'name' produced by the Study named 'study' if provided. If a spec is passed instead of a str to the name argument, then the study will be set from the spec iff it is derived Parameters ---------- name : str | BaseField The name of the field or a ...
3.710154
3.697107
1.003529
try: return self._records[(pipeline_name, from_study)] except KeyError: found = [] for sname, pnames in groupby(sorted(self._records, key=itemgetter(1)), key=itemgetter(1...
def record(self, pipeline_name, from_study)
Returns the provenance record for a given pipeline Parameters ---------- pipeline_name : str The name of the pipeline that generated the record from_study : str The name of the study that the pipeline was generated from Returns ------- re...
4.483698
4.05845
1.104781
if self != other: mismatch = "\n{}{}".format(indent, type(self).__name__) else: mismatch = '' sub_indent = indent + ' ' if len(list(self.filesets)) != len(list(other.filesets)): mismatch += ('\n{indent}mismatching summary fileset lengths ' ...
def find_mismatch(self, other, indent='')
Highlights where two nodes differ in a human-readable form Parameters ---------- other : TreeNode The node to compare indent : str The white-space with which to indent output string Returns ------- mismatch : str The human-rea...
1.788579
1.815703
0.985062
if frequency is None: nodes = chain(*(self._nodes(f) for f in ('per_study', 'per_subject', 'per_visit', 'per_session'))) else: nodes = self._nodes(frequency=frequency) return nodes
def nodes(self, frequency=None)
Returns an iterator over all nodes in the tree for the specified frequency. If no frequency is specified then all nodes are returned Parameters ---------- frequency : str | None The frequency of the nodes to iterate over. If None all frequencies are returned ...
4.591336
5.384992
0.852617
mismatch = super(Tree, self).find_mismatch(other, indent) sub_indent = indent + ' ' if len(list(self.subjects)) != len(list(other.subjects)): mismatch += ('\n{indent}mismatching subject lengths ' '(self={} vs other={}): ' '\...
def find_mismatch(self, other, indent='')
Used in debugging unittests
1.653893
1.636653
1.010534
if fill_subjects is None: fill_subjects = [s.id for s in self.subjects] if fill_visits is None: fill_visits = [v.id for v in self.complete_visits] for subject_id in fill_subjects: try: subject = self.subject(subject_id) exc...
def _fill_empty_sessions(self, fill_subjects, fill_visits)
Fill in tree with additional empty subjects and/or visits to allow the study to pull its inputs from external repositories
2.017778
2.052865
0.982908
# Sort the data by subject and visit ID filesets_dict = defaultdict(list) for fset in filesets: if file_formats: fset.set_format(file_formats) filesets_dict[(fset.subject_id, fset.visit_id)].append(fset) fields_dict = defaultdict(list) ...
def construct(cls, repository, filesets=(), fields=(), records=(), file_formats=(), **kwargs)
Return the hierarchical tree of the filesets and fields stored in a repository Parameters ---------- respository : Repository The repository that the tree comes from filesets : list[Fileset] List of all filesets in the tree fields : list[Field] ...
1.853824
1.816709
1.02043
if frequency is None: [] elif frequency == 'per_session': return [self] elif frequency in ('per_visit', 'per_subject'): return [self.parent] elif frequency == 'per_study': return [self.parent.parent]
def nodes(self, frequency=None)
Returns all nodes of the specified frequency that are related to the given Session Parameters ---------- frequency : str | None The frequency of the nodes to return Returns ------- nodes : iterable[TreeNode] All nodes related to the Sessi...
3.977059
4.325195
0.91951
if self._transport is None: return if self._paused: return if self._waiting_for_response: LOG.debug("queueing write %s", data) self._queued_writes.append((data, response_required, timeout)) return if response_require...
def write_data(self, data, response_required=None, timeout=5.0, raw=False)
Write data on the asyncio Protocol
3.072603
2.970723
1.034295
new_dict = { key: (obj[key][0] if len(obj[key]) == 1 else obj[key]) for key in obj.keys() } return new_dict
def unwrap_querystring_lists(obj)
Convert responder querystring params, pulling values out of list if there's only one.
3.2821
2.968242
1.105739
"For duck-typing with *Spec types" if not self.derivable: raise ArcanaUsageError( "There is no pipeline getter for {} because it doesn't " "fallback to a derived spec".format(self)) return self._fallback.pipeline_getter
def pipeline_getter(self)
For duck-typing with *Spec types
15.692305
8.229893
1.906745
# Loop through the inputs to the pipeline and add the instancemethods # for the pipelines to generate each of the processed inputs prereqs = defaultdict(set) for input in self.inputs: # @ReservedAssignment spec = self._study.spec(input) # Could be an inp...
def prerequisites(self)
Iterates through the inputs of the pipelinen and determines the all prerequisite pipelines
12.793145
12.247216
1.044576
return set(chain( (i for i in self.inputs if not i.derived), *(self.study.pipeline(p, required_outputs=r).study_inputs for p, r in self.prerequisites.items())))
def study_inputs(self)
Returns all inputs of the study used by the pipeline, including inputs of prerequisites (and their prerequisites recursively)
9.397069
7.895997
1.190105
self._iterator_conns[spec_name].append((node, node_input, format)) else: name = self._map_name(spec_name, self._input_map) if name not in self.study.data_spec_names(): raise ArcanaDesignError( "Proposed input '{}' to {} is not a valid spec ...
def connect_input(self, spec_name, node, node_input, format=None, **kwargs): # @ReservedAssignment @IgnorePep8 if spec_name in self.study.ITERFIELDS
Connects a study fileset_spec as an input to the provided node Parameters ---------- spec_name : str Name of the study data spec (or one of the IDs from the iterator nodes, 'subject_id' or 'visit_id') to connect to the node node : arcana.Node The node...
4.627057
5.339937
0.8665
name = self._map_name(spec_name, self._output_map) if name not in self.study.data_spec_names(): raise ArcanaDesignError( "Proposed output '{}' to {} is not a valid spec name ('{}')" .format(name, self._error_msg_loc, "', '".joi...
def connect_output(self, spec_name, node, node_output, format=None, # @ReservedAssignment @IgnorePep8 **kwargs)
Connects an output to a study fileset spec Parameters ---------- spec_name : str Name of the study fileset spec to connect to node : arcana.Node The node to connect the output from node_output : str Name of the output on the node to connect to...
3.30601
3.371138
0.98068
if mapper is not None: if isinstance(mapper, basestring): name = mapper + name try: name = mapper[name] except KeyError: pass return name
def _map_name(self, name, mapper)
Maps a spec name to a new value based on the provided mapper
3.324056
3.177818
1.046018
if file_format is None: return False try: filset_format = fileset.format except AttributeError: return False # Field input else: return (file_format != filset_format)
def requires_conversion(cls, fileset, file_format)
Checks whether the fileset matches the requested file format
5.813045
5.962067
0.975005
fname += '.png' orig_dir = os.getcwd() tmpdir = tempfile.mkdtemp() os.chdir(tmpdir) workflow = self._workflow workflow.write_graph(graph2use=style, format=format, **kwargs) os.chdir(orig_dir) try: shutil.move(os.path.join(tmpdir, 'graph_det...
def save_graph(self, fname, style='flat', format='png', **kwargs): # @ReservedAssignment @IgnorePep8 fname = os.path.expanduser(fname) if not fname.endswith('.png')
Saves a graph of the pipeline to file Parameters ---------- fname : str The filename for the saved graph style : str The style of the graph, can be one of can be one of 'orig', 'flat', 'exec', 'hierarchical' plot : bool Whether to ...
2.42025
2.848076
0.849784
iterators = set() if frequency is None: input_freqs = list(self.input_frequencies) else: input_freqs = [frequency] for freq in input_freqs: iterators.update(self.study.FREQUENCIES[freq]) return iterators
def iterators(self, frequency=None)
Returns the iterators (i.e. subject_id, visit_id) that the pipeline iterates over Parameters ---------- frequency : str | None A selected data frequency to use to determine which iterators are required. If None, all input frequencies of the pipeline are ...
3.529749
4.019757
0.8781
# Set values of name and study name = name_maps.get('name', name) name = name_maps.get('prefix', '') + name study = name_maps.get('study', study) # Flatten input and output maps, combining maps from inner nests with # those in the "mods" dictionary maps =...
def _unwrap_maps(self, name_maps, name, study=None, **inner_maps)
Unwraps potentially nested name-mapping dictionaries to get values for name, input_map, output_map and study. Unsed in __init__. Parameters ---------- name_maps : dict A dictionary containing the name_maps to apply to the values name : str Name passed fro...
2.720868
2.564794
1.060852
to_cap = (self._inputnodes, self._outputnodes, self._prov) if to_cap == (None, None, None): self._inputnodes = { f: self._make_inputnode(f) for f in self.input_frequencies} self._outputnodes = { f: self._make_outputnode(f) for f in self.ou...
def cap(self)
"Caps" the construction of the pipeline, signifying that no more inputs and outputs are expected to be added and therefore the input and output nodes can be created along with the provenance.
4.509518
3.958955
1.139068
# Check to see whether there are any outputs for the given frequency inputs = list(self.frequency_inputs(frequency)) # Get list of input names for the requested frequency, addding fields # to hold iterator IDs input_names = [i.name for i in inputs] input_names.ex...
def _make_inputnode(self, frequency)
Generates an input node for the given frequency. It also adds implicit file format conversion nodes to the pipeline. Parameters ---------- frequency : str The frequency (i.e. 'per_session', 'per_visit', 'per_subject' or 'per_study') of the input node to retrieve
4.470104
4.509527
0.991258
# Check to see whether there are any outputs for the given frequency outputs = list(self.frequency_outputs(frequency)) if not outputs: raise ArcanaError( "No outputs to '{}' pipeline for requested freqency '{}'" .format(self.name, frequency)) ...
def _make_outputnode(self, frequency)
Generates an output node for the given frequency. It also adds implicit file format conversion nodes to the pipeline. Parameters ---------- frequency : str The frequency (i.e. 'per_session', 'per_visit', 'per_subject' or 'per_study') of the output node to retriev...
5.83856
5.952798
0.980809
# Export worfklow graph to node-link data format wf_dict = nx_json.node_link_data(self.workflow._graph) # Replace references to Node objects with the node's provenance # information and convert to a dict organised by node name to allow it # to be compared more easily. Al...
def _gen_prov(self)
Extracts provenance information from the pipeline into a PipelineProv object Returns ------- prov : dict[str, *] A dictionary containing the provenance information to record for the pipeline
5.017113
4.874635
1.029229
exp_inputs = {} # Get checksums/values of all inputs that would have been used in # previous runs of an equivalent pipeline to compare with that saved # in provenance to see if any have been updated. for inpt in self.inputs: # @ReservedAssignment # Get itera...
def expected_record(self, node)
Constructs the provenance record that would be saved in the given node if the pipeline was run on the current state of the repository Parameters ---------- node : arcana.repository.tree.TreeNode A node of the Tree representation of the study data stored in the re...
4.382061
4.113353
1.065326
joined_prov = {} if self.joins_subjects: joined_prov['subject_ids'] = list(self.study.subject_ids) if self.joins_visits: joined_prov['visit_ids'] = list(self.study.visit_ids) return joined_prov
def _joined_ids(self)
Adds the subjects/visits used to generate the derivatives iff there are any joins over them in the pipeline
3.739123
2.77884
1.34557