Skip to content

Commit e48239d

Browse files
committed
Deprecated ibllib.version; fix Globus patcher
1 parent 8a1c736 commit e48239d

File tree

9 files changed

+46
-36
lines changed

9 files changed

+46
-36
lines changed

ibllib/io/extractors/biased_trials.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
StimOnTimes_deprecated, StimOnTriggerTimes, StimOnOffFreezeTimes, ItiInTimes,
1313
StimOffTriggerTimes, StimFreezeTriggerTimes, ErrorCueTriggerTimes, PhasePosQuiescence)
1414
from ibllib.io.extractors.training_wheel import Wheel
15-
from ibllib.misc import version
1615

1716

1817
class ContrastLR(BaseBpodTrialsExtractor):
@@ -163,7 +162,7 @@ def extract_all(session_path, save=False, bpod_trials=False, settings=False, ext
163162

164163
base = [GoCueTriggerTimes]
165164
# Version check
166-
if version.ge(settings['IBLRIG_VERSION_TAG'], '5.0.0'):
165+
if parse_version(settings['IBLRIG_VERSION_TAG']) >= parse_version('5.0.0'):
167166
# We now extract a single trials table
168167
base.extend([
169168
StimOnTriggerTimes, ItiInTimes, StimOffTriggerTimes, StimFreezeTriggerTimes, ErrorCueTriggerTimes,

ibllib/io/extractors/bpod_trials.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@
55
import logging
66
from collections import OrderedDict
77

8+
from pkg_resources import parse_version
89
from ibllib.io.extractors import habituation_trials, training_trials, biased_trials, opto_trials
910
import ibllib.io.extractors.base
1011
import ibllib.io.raw_data_loaders as rawio
11-
from ibllib.misc import version
1212

1313
_logger = logging.getLogger('ibllib')
1414

@@ -54,7 +54,8 @@ def extract_all(session_path, save=True, bpod_trials=None, settings=None):
5454
files_wheel = []
5555
wheel = OrderedDict({k: trials.pop(k) for k in tuple(trials.keys()) if 'wheel' in k})
5656
elif extractor_type == 'habituation':
57-
if settings['IBLRIG_VERSION_TAG'] and version.le(settings['IBLRIG_VERSION_TAG'], '5.0.0'):
57+
if settings['IBLRIG_VERSION_TAG'] and \
58+
parse_version(settings['IBLRIG_VERSION_TAG']) <= parse_version('5.0.0'):
5859
_logger.warning("No extraction of legacy habituation sessions")
5960
return None, None, None
6061
trials, files_trials = habituation_trials.extract_all(

ibllib/io/extractors/training_trials.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import ibllib.io.raw_data_loaders as raw
77
from ibllib.io.extractors.base import BaseBpodTrialsExtractor, run_extractor_classes
88
from ibllib.io.extractors.training_wheel import Wheel
9-
from ibllib.misc import version
109

1110

1211
_logger = logging.getLogger('ibllib')
@@ -211,7 +210,7 @@ def get_feedback_times_ge5(session_path, data=False):
211210

212211
def _extract(self):
213212
# Version check
214-
if version.ge(self.settings['IBLRIG_VERSION_TAG'], '5.0.0'):
213+
if parse_version(self.settings['IBLRIG_VERSION_TAG']) >= parse_version('5.0.0'):
215214
merge = self.get_feedback_times_ge5(self.session_path, data=self.bpod_trials)
216215
else:
217216
merge = self.get_feedback_times_lt5(self.session_path, data=self.bpod_trials)
@@ -282,7 +281,7 @@ class GoCueTriggerTimes(BaseBpodTrialsExtractor):
282281
var_names = 'goCueTrigger_times'
283282

284283
def _extract(self):
285-
if version.ge(self.settings['IBLRIG_VERSION_TAG'], '5.0.0'):
284+
if parse_version(self.settings['IBLRIG_VERSION_TAG']) >= parse_version('5.0.0'):
286285
goCue = np.array([tr['behavior_data']['States timestamps']
287286
['play_tone'][0][0] for tr in self.bpod_trials])
288287
else:
@@ -356,7 +355,7 @@ class IncludedTrials(BaseBpodTrialsExtractor):
356355
var_names = 'included'
357356

358357
def _extract(self):
359-
if version.ge(self.settings['IBLRIG_VERSION_TAG'], '5.0.0'):
358+
if parse_version(self.settings['IBLRIG_VERSION_TAG']) >= parse_version('5.0.0'):
360359
trials_included = self.get_included_trials_ge5(
361360
data=self.bpod_trials, settings=self.settings)
362361
else:
@@ -513,7 +512,7 @@ def _extract(self):
513512
# Version check
514513
_logger.warning("Deprecation Warning: this is an old version of stimOn extraction."
515514
"From version 5., use StimOnOffFreezeTimes")
516-
if version.ge(self.settings['IBLRIG_VERSION_TAG'], '5.0.0'):
515+
if parse_version(self.settings['IBLRIG_VERSION_TAG']) >= parse_version('5.0.0'):
517516
stimOn_times = self.get_stimOn_times_ge5(self.session_path, data=self.bpod_trials)
518517
else:
519518
stimOn_times = self.get_stimOn_times_lt5(self.session_path, data=self.bpod_trials)
@@ -719,7 +718,7 @@ def extract_all(session_path, save=False, bpod_trials=None, settings=None):
719718

720719
base = [RepNum, GoCueTriggerTimes]
721720
# Version check
722-
if version.ge(settings['IBLRIG_VERSION_TAG'], '5.0.0'):
721+
if parse_version(settings['IBLRIG_VERSION_TAG']) >= parse_version('5.0.0'):
723722
# We now extract a single trials table
724723
base.extend([
725724
StimOnTriggerTimes, ItiInTimes, StimOffTriggerTimes, StimFreezeTriggerTimes,

ibllib/io/raw_data_loaders.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,12 @@
1515
from pathlib import Path
1616
from typing import Union
1717

18+
from pkg_resources import parse_version
1819
import numpy as np
1920
import pandas as pd
2021

2122
from iblutil.io import jsonable
2223
from ibllib.io.video import assert_valid_label
23-
from ibllib.misc import version
2424
from ibllib.time import uncycle_pgts, convert_pgts
2525

2626
_logger = logging.getLogger('ibllib')
@@ -374,7 +374,7 @@ def load_encoder_events(session_path, settings=False):
374374
settings = {'IBLRIG_VERSION_TAG': '0.0.0'}
375375
if not path:
376376
return None
377-
if version.ge(settings['IBLRIG_VERSION_TAG'], '5.0.0'):
377+
if parse_version(settings['IBLRIG_VERSION_TAG']) >= parse_version('5.0.0'):
378378
return _load_encoder_events_file_ge5(path)
379379
else:
380380
return _load_encoder_events_file_lt5(path)
@@ -479,7 +479,7 @@ def load_encoder_positions(session_path, settings=False):
479479
if not path:
480480
_logger.warning("No data loaded: could not find raw encoderPositions file")
481481
return None
482-
if version.ge(settings['IBLRIG_VERSION_TAG'], '5.0.0'):
482+
if parse_version(settings['IBLRIG_VERSION_TAG']) >= parse_version('5.0.0'):
483483
return _load_encoder_positions_file_ge5(path)
484484
else:
485485
return _load_encoder_positions_file_lt5(path)

ibllib/misc/version.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,15 @@
11
import pkg_resources
2+
import traceback
3+
import warnings
4+
5+
for line in traceback.format_stack():
6+
print(line.strip())
7+
8+
warnings.warn(
9+
'ibllib.version is deprecated and functionality will be removed! '
10+
'use pkg_resources.parse_version and ibllib.__version__ instead. See stack above.',
11+
DeprecationWarning
12+
)
213

314

415
def _compare_version_tag(v1, v2, fcn):

ibllib/oneibl/patcher.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212
from one.alf.spec import is_uuid_string
1313
from one import params
1414
from one.converters import path_from_dataset
15+
from one.remote import globus
1516

16-
from ibllib.io import globus
1717
from ibllib.oneibl.registration import register_dataset
1818

1919
_logger = logging.getLogger('ibllib')
@@ -97,7 +97,7 @@ def _patch_dataset(self, path, dset_id=None, dry=False, ftp=False):
9797
full_remote_path = PurePosixPath(FLATIRON_MOUNT, remote_path)
9898
if isinstance(path, WindowsPath) and not ftp:
9999
# On Windows replace drive map with Globus uri, e.g. C:/ -> /~/C/
100-
path = '/~/' + path.as_posix().replace(':', '')
100+
path = globus.as_globus_path(path)
101101
status = self._scp(path, full_remote_path, dry=dry)[0]
102102
return status
103103

@@ -140,8 +140,8 @@ def patch_dataset(self, file_list, dry=False, ftp=False, **kwargs):
140140
Rules for creation/patching are the same that apply for registration via Alyx
141141
as this uses the registration endpoint to get the dataset.
142142
An existing file (same session and path relative to session) will be patched.
143-
:param path: full file path. Must be whithin an ALF session folder (subject/date/number)
144-
can also be a list of full file pathes belonging to the same session.
143+
:param path: full file path. Must be within an ALF session folder (subject/date/number)
144+
can also be a list of full file paths belonging to the same session.
145145
:param server_repository: Alyx server repository name
146146
:param created_by: alyx username for the dataset (optional, defaults to root)
147147
:param ftp: flag for case when using ftppatcher. Don't adjust windows path in
@@ -197,13 +197,12 @@ class GlobusPatcher(Patcher):
197197
198198
"""
199199

200-
def __init__(self, one=None, globus_client_id=None, local_endpoint=None, label='ibllib patch'):
201-
assert globus_client_id
200+
def __init__(self, client_name='default', one=None, label='ibllib patch'):
202201
assert one
203-
self.local_endpoint = local_endpoint or globus.get_local_endpoint()
202+
self.local_endpoint = getattr(globus.load_client_params(f'globus.{client_name}'),
203+
'local_endpoint', globus.get_local_endpoint_id())
204+
self.transfer_client = globus.create_globus_client(client_name)
204205
self.label = label
205-
self.transfer_client = globus.login_auto(
206-
globus_client_id=globus_client_id, str_app='globus/admin')
207206
# transfers/delete from the current computer to the flatiron: mandatory and executed first
208207
self.globus_transfer = globus_sdk.TransferData(
209208
self.transfer_client, self.local_endpoint, FLAT_IRON_GLOBUS_ID, verify_checksum=True,
@@ -296,11 +295,11 @@ def _wait_for_task(resp):
296295
# on an errored task
297296
# Out[10]: TransferResponse({'bytes_checksummed': 0, 'bytes_transferred': 0, 'canceled_by_admin': None, 'canceled_by_admin_message': None, 'command': 'API 0.10', 'completion_time': '2021-01-03T17:39:00+00:00', 'deadline': '2021-01-04T17:37:34+00:00', 'delete_destination_extra': False, 'destination_endpoint': 'simonsfoundation#ibl', 'destination_endpoint_display_name': 'IBL Flatiron SDSC Data', 'destination_endpoint_id': 'ab2d064c-413d-11eb-b188-0ee0d5d9299f', 'directories': 0, 'effective_bytes_per_second': 0, 'encrypt_data': False, 'fatal_error': {'code': 'CANCELED', 'description': 'canceled'}, 'faults': 2, 'files': 6, 'files_skipped': 0, 'files_transferred': 0, 'history_deleted': False, 'is_ok': None, 'is_paused': False, 'key': 'complete,2021-01-03T17:38:59.697413', 'label': 'test 3B analog sync patch', 'nice_status': None, 'nice_status_details': None, 'nice_status_expires_in': None, 'nice_status_short_description': None, 'owner_id': 'e633663a-8561-4a5d-ac92-f198d43b14dc', 'preserve_timestamp': False, 'recursive_symlinks': 'ignore', 'request_time': '2021-01-03T17:37:34+00:00', 'source_endpoint': 'internationalbrainlab#916c2766-bd2a-11ea-8f22-0a21f750d19b', 'source_endpoint_display_name': 'olivier_laptop', 'source_endpoint_id': '916c2766-bd2a-11ea-8f22-0a21f750d19b', 'status': 'FAILED', 'subtasks_canceled': 6, 'subtasks_expired': 0, 'subtasks_failed': 0, 'subtasks_pending': 0, 'subtasks_retrying': 0, 'subtasks_succeeded': 6, 'subtasks_total': 12, 'symlinks': 0, 'sync_level': 3, 'task_id': '5706dd2c-4dea-11eb-8ffb-0a34088e79f9', 'type': 'TRANSFER', 'username': 'internationalbrainlab', 'verify_checksum': True}) # noqa
298297
while True:
299-
tinfo = gtc.get_task(task_id=resp['task_id'])['completion_time']
300-
if tinfo['completion_time'] is not None:
298+
tinfo = gtc.get_task(task_id=resp['task_id'])
299+
if tinfo and tinfo['completion_time'] is not None:
301300
break
302301
_ = gtc.task_wait(task_id=resp['task_id'], timeout=30)
303-
if tinfo['fatal_error'] is not None:
302+
if tinfo and tinfo['fatal_error'] is not None:
304303
raise ConnectionError(f"Globus transfer failed \n {tinfo}")
305304

306305
# handles the transfers first

ibllib/oneibl/registration.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,15 @@
44
import logging
55
import re
66

7+
from pkg_resources import parse_version
78
from dateutil import parser as dateparser
89
from iblutil.io import hashfile
910
from one.alf.files import get_session_path
1011
import one.alf.exceptions as alferr
1112
from one.api import ONE
1213

14+
import ibllib
1315
import ibllib.io.extractors.base
14-
from ibllib.misc import version
1516
import ibllib.time
1617
import ibllib.io.raw_data_loaders as raw
1718
from ibllib.io import flags
@@ -67,7 +68,7 @@ def register_dataset(file_list, one=None, created_by=None, repository=None, serv
6768
assert len(set([get_session_path(f) for f in file_list])) == 1
6869
assert all([Path(f).exists() for f in file_list])
6970
if versions is None:
70-
versions = version.ibllib()
71+
versions = ibllib.__version__
7172
if isinstance(versions, str):
7273
versions = [versions for _ in file_list]
7374
assert isinstance(versions, list) and len(versions) == len(file_list)
@@ -339,7 +340,7 @@ def register_session(self, ses_path, file_list=True):
339340
'filenames': F,
340341
'hashes': md5s,
341342
'filesizes': file_sizes,
342-
'versions': [version.ibllib() for _ in F]
343+
'versions': [ibllib.__version__ for _ in F]
343344
}
344345
self.one.alyx.post('/register-file', data=r_)
345346
return session
@@ -393,7 +394,7 @@ def _read_settings_json_compatibility_enforced(json_file):
393394
_logger.warning("You appear to be on an untagged version...")
394395
return md
395396
# 2018-12-05 Version 3.2.3 fixes (permanent fixes in IBL_RIG from 3.2.4 on)
396-
if version.le(md['IBLRIG_VERSION_TAG'], '3.2.3'):
397+
if parse_version(md['IBLRIG_VERSION_TAG']) <= parse_version('3.2.3'):
397398
if 'LAST_TRIAL_DATA' in md.keys():
398399
md.pop('LAST_TRIAL_DATA')
399400
if 'weighings' in md['PYBPOD_SUBJECT_EXTRA'].keys():
@@ -414,7 +415,7 @@ def _read_settings_json_compatibility_enforced(json_file):
414415
def rename_files_compatibility(ses_path, version_tag):
415416
if not version_tag:
416417
return
417-
if version.le(version_tag, '3.2.3'):
418+
if parse_version(version_tag) <= parse_version('3.2.3'):
418419
task_code = ses_path.glob('**/_ibl_trials.iti_duration.npy')
419420
for fn in task_code:
420421
fn.replace(fn.parent.joinpath('_ibl_trials.itiDuration.npy'))

ibllib/pipes/tasks.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
from graphviz import Digraph
1212

13-
from ibllib.misc import version
13+
import ibllib
1414
from ibllib.oneibl import data_handlers
1515
import one.params
1616
from one.api import ONE
@@ -30,7 +30,7 @@ class Task(abc.ABC):
3030
outputs = None # place holder for a list of Path containing output files
3131
time_elapsed_secs = None
3232
time_out_secs = 3600 * 2 # time-out after which a task is considered dead
33-
version = version.ibllib()
33+
version = ibllib.__version__
3434
signature = {'input_files': [], 'output_files': []} # list of tuples (filename, collection, required_flag)
3535
force = False # whether or not to re-download missing input files on local server if not present
3636

@@ -100,7 +100,7 @@ def run(self, **kwargs):
100100
_logger.info(f"Starting job {self.__class__}")
101101
if self.machine:
102102
_logger.info(f"Running on machine: {self.machine}")
103-
_logger.info(f"running ibllib version {version.ibllib()}")
103+
_logger.info(f"running ibllib version {ibllib.__version__}")
104104
# setup
105105
start_time = time.time()
106106
try:
@@ -193,7 +193,7 @@ def _run(self, overwrite=False):
193193
:param overwrite: (bool) if the output already exists,
194194
:return: out_files: files to be registered. Could be a list of files (pathlib.Path),
195195
a single file (pathlib.Path) an empty list [] or None.
196-
Whithin the pipeline, there is a distinction between a job that returns an empty list
196+
Within the pipeline, there is a distinction between a job that returns an empty list
197197
and a job that returns None. If the function returns None, the job will be labeled as
198198
"empty" status in the database, otherwise, the job has an expected behaviour of not
199199
returning any dataset.

ibllib/plots/snapshot.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@
77

88
from one.api import ONE
99
from ibllib.pipes import tasks
10-
from ibllib.misc import version
1110
from one.alf.exceptions import ALFObjectNotFound
1211
from neuropixel import trace_header, TIP_SIZE_UM
1312

13+
from ibllib import __version__ as ibllib_version
1414
from ibllib.pipes.ephys_alignment import EphysAlignment
1515
from ibllib.pipes.histology import interpolate_along_track
1616
from ibllib.atlas import AllenAtlas
@@ -36,7 +36,7 @@ def register_images(self, widths=None, function=None, extra_dict=None):
3636
jsons = []
3737
texts = []
3838
for f in self.outputs:
39-
json_dict = dict(tag=report_tag, version=version.ibllib(),
39+
json_dict = dict(tag=report_tag, version=ibllib_version,
4040
function=(function or str(self.__class__).split("'")[1]), name=f.stem)
4141
if extra_dict is not None:
4242
assert isinstance(extra_dict, dict)

0 commit comments

Comments
 (0)