def run(): netrc_path = os.path.join(expanduser("~"), '.netrc') user = '******' password = '******' bad_netrc = """machine dev.xnat.sydney.edu.au user unittest password bad_pass""" try: shutil.move(netrc_path, netrc_path + '.good') except IOError as e: if e.errno != errno.ENOENT: raise try: # Create bad netrc file to test login failure with open(netrc_path, 'w') as f: f.write(bad_netrc) with connect() as login: print(login.projects) with connect() as login: print(login.projects) finally: remove_ignore_errors(netrc_path) shutil.move(netrc_path + '.good', netrc_path)
def test_outer_connect(self): with connect() as login: self.assertEqual(ls(self.test_proj, connection=login), self._subjects) # Check to see that the context hasn't been closed by the first # ls call self.assertEqual(ls(self.test_proj, connection=login), self._subjects)
def test_outer_connect(self): with connect() as mbi_xnat: self.assertEqual(ls(self.test_proj, connection=mbi_xnat), self._subjects) # Check to see that the context hasn't been closed by the first # ls call self.assertEqual(ls(self.test_proj, connection=mbi_xnat), self._subjects) self.assertRaises(AttributeError, ls, self.test_proj, connection=mbi_xnat)
def run(): parser = argparse.ArgumentParser() parser.add_argument('xnat_id', help="The XNAT session with the duplicates") parser.add_argument('scan_ids', nargs='+', help="The scans to strip enhanced mr images from") parser.add_argument('--download_dir', default='.', help=("A directory to download the scans to")) parser.add_argument( '--dry_run', action='store_true', default=False, help=("Don't actually delete anything just display what " "would be deleted")) args = parser.parse_args() ENHANCED_MR_STORAGE = '1.2.840.10008.5.1.4.1.1.4.1' with xnatutils.connect() as xlogin: xsession = xlogin.experiments[args.xnat_id] # noqa pylint:disable=no-member for scan_id in args.scan_ids: xscan = xsession.scans[scan_id] xscan.download_dir(args.download_dir) files_path = op.join( args.download_dir, args.xnat_id, 'scans', '{}-{}'.format(xscan.id, re.sub(r'[^a-zA-Z_0-9]', '_', xscan.type)), 'resources', 'DICOM', 'files') for fname, xfile in sorted(xscan.files.items(), key=itemgetter(0)): fpath = op.join(files_path, fname) with open(fpath, 'rb') as f: dcm = pydicom.dcmread(fpath) if dcm.file_meta.MediaStorageSOPClassUID == ENHANCED_MR_STORAGE: print("Deleting '{}".format(fname)) if not args.dry_run: xfile.delete() if args.dry_run: print( 'Would delete proceeding "Enhanced MR Image Storage" from {}:[{}]'. format(args.xnat_id, ', '.join(args.scan_ids))) else: print('Deleted all "Enhanced MR Image Storage" from {}:[{}]'.format( args.xnat_id, ', '.join(args.scan_ids)))
from xnatutils import connect from xnatutils.base import remove_ignore_errors from os.path import expanduser import errno netrc_path = os.path.join(expanduser("~"), '.netrc') user = '******' password = '******' bad_netrc = """machine mbi-xnat.erc.monash.edu.au user unittest password bad_pass""" try: shutil.move(netrc_path, netrc_path + '.good') except IOError as e: if e.errno != errno.ENOENT: raise try: # Create bad netrc file to test login failure with open(netrc_path, 'w') as f: f.write(bad_netrc) with connect() as login: print(login.projects) with connect() as login: print(login.projects) finally: remove_ignore_errors(netrc_path) shutil.move(netrc_path + '.good', netrc_path)
def setUp(self): self.xnat_login = connect(server=self.server, loglevel='DEBUG', logger=logger) self.delete_subject()
import os import shutil from xnatutils import connect from xnatutils.base import remove_ignore_errors from os.path import expanduser import errno netrc_path = os.path.join(expanduser("~"), '.netrc') user = '******' password = '******' bad_netrc = """machine mbi-xnat.erc.monash.edu.au user unittest password bad_pass""" try: shutil.move(netrc_path, netrc_path + '.good') except IOError as e: if e.errno != errno.ENOENT: raise try: # Create bad netrc file to test login failure with open(netrc_path, 'w') as f: f.write(bad_netrc) with connect() as mbi_xnat: print(mbi_xnat.projects) finally: remove_ignore_errors(netrc_path) shutil.move(netrc_path + '.good', netrc_path)
def import_(): export_file = app.config['FILEMAKER_EXPORT_FILE'] if not op.exists(export_file): raise Exception("Could not find an FileMaker export file at {}".format( export_file)) num_imported = 0 num_prev = 0 skipped = [] malformed = [] no_xnat = [] # Get previous reporters nick_ferris = User.query.filter_by( email='*****@*****.**').one() paul_beech = User.query.filter_by(email='*****@*****.**').one() axis = User.query.filter_by(name='AXIS Reporting').one() with xnatutils.connect(server=app.config['XNAT_URL']) as alfred_xnat: with open(export_file) as f: for row in csv.DictReader(f): project_id = row['ProjectID'] if project_id is None: malformed.append(row) continue project_id = project_id.strip() if not project_id.startswith('M') or project_id[2] == 'A': skipped.append(row) continue mbi_subject_id = row['SubjectID'].strip() study_id = row['StudyID'].strip() first_name = row['FirstName'].strip() last_name = row['LastName'].strip() try: subject = Subject.query.filter_by( mbi_id=mbi_subject_id).one() except orm.exc.NoResultFound: subject = Subject( mbi_subject_id, first_name, last_name, datetime.strptime(row['DOB'], '%d/%m/%Y')) db.session.add(subject) # pylint: disable=no-member if ImagingSession.query.get(study_id) is None: if row['DarisID']: _, subject_id, visit_id = daris_id_re.match( row['DarisID']).groups() if visit_id is None: visit_id = '1' else: try: subject_id = row['XnatSubjectID'].strip() visit_id = row['XnatVisitID'].strip() except KeyError: malformed.append(row) continue if not subject_id or not visit_id: malformed.append(row) continue try: subject_id = int(subject_id) except ValueError: pass else: subject_id = '{:03}'.format(subject_id) if project_id.startswith('MMH'): visit_prefix = 'MRPT' else: visit_prefix = 'MR' numeral, suffix = re.match(r'(\d+)(.*)', visit_id).groups() visit_id = '{}{:02}{}'.format( visit_prefix, int(numeral), (suffix if suffix is not None else '')) xnat_id = '_'.join( (project_id, subject_id, visit_id)).upper() try: exp = alfred_xnat.experiments[xnat_id] # noqa pylint: disable=no-member except KeyError: no_xnat.append(row) continue avail_scan_types = [] for scan in exp.scans.values(): try: scan_type = ScanType.query.filter_by( name=scan.type).one() except orm.exc.NoResultFound: scan_type = ScanType(scan.type) db.session.add(scan_type) # noqa pylint: disable=no-member avail_scan_types.append(scan_type) xnat_uri = exp.uri.split('/')[-1] scan_date = datetime.strptime(row['ScanDate'], '%d/%m/%Y') priority = LOW session = ImagingSession(study_id, subject, xnat_id, xnat_uri, scan_date, avail_scan_types, priority=priority) db.session.add(session) # pylint: disable=no-member if row['MrReport'] is not None and row['MrReport'].strip(): if 'MSH' in row['MrReport']: reporter = axis else: reporter = nick_ferris db.session.add( Report( # noqa pylint: disable=no-member session.id, reporter.id, '', NOT_RECORDED, [], MRI, date=scan_date, dummy=True)) if (row['PetReport'] is not None and row['PetReport'].strip()): db.session.add( Report( # noqa pylint: disable=no-member session.id, paul_beech.id, '', NOT_RECORDED, [], PET, date=scan_date, dummy=True)) # noqa pylint: disable=no-member db.session.commit() # pylint: disable=no-member num_imported += 1 print(study_id) else: num_prev += 1 return render_template('reporting/import.html', num_imported=num_imported, num_prev=num_prev, malformed=malformed, no_xnat=no_xnat, skipped=skipped)
def setUp(self): self.xnat_login = connect() self.delete_subject()
def setUp(self): self.mbi_xnat = connect() self.delete_subject()
parser.add_argument('scan_ids', nargs='+', help="The scans to strip enhanced mr images from") parser.add_argument('--download_dir', default='.', help=("A directory to download the scans to")) parser.add_argument('--dry_run', action='store_true', default=False, help=("Don't actually delete anything just display what " "would be deleted")) args = parser.parse_args() ENHANCED_MR_STORAGE = '1.2.840.10008.5.1.4.1.1.4.1' with xnatutils.connect() as xlogin: xsession = xlogin.experiments[args.xnat_id] # noqa pylint:disable=no-member for scan_id in args.scan_ids: xscan = xsession.scans[scan_id] xscan.download_dir(args.download_dir) files_path = op.join( args.download_dir, args.xnat_id, 'scans', '{}-{}'.format(xscan.id, re.sub(r'[^a-zA-Z_0-9]', '_', xscan.type)), 'resources', 'DICOM', 'files') for fname, xfile in sorted(xscan.files.items(), key=itemgetter(0)):