idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
22,900 | def _get_ants_args ( self ) : args = { 'moving_image' : self . inputs . moving_image , 'num_threads' : self . inputs . num_threads , 'float' : self . inputs . float , 'terminal_output' : 'file' , 'write_composite_transform' : True , 'initial_moving_transform' : self . inputs . initial_moving_transform } if isdefined ( self . inputs . moving_mask ) : if self . inputs . explicit_masking : args [ 'moving_image' ] = mask ( self . inputs . moving_image , self . inputs . moving_mask , "moving_masked.nii.gz" ) else : args [ 'moving_image_masks' ] = self . inputs . moving_mask if isdefined ( self . inputs . lesion_mask ) : args [ 'moving_image_masks' ] = create_cfm ( self . inputs . moving_mask , lesion_mask = self . inputs . lesion_mask , global_mask = self . inputs . explicit_masking ) elif isdefined ( self . inputs . lesion_mask ) : args [ 'moving_image_masks' ] = create_cfm ( self . inputs . moving_image , lesion_mask = self . inputs . lesion_mask , global_mask = True ) if isdefined ( self . inputs . reference_image ) : args [ 'fixed_image' ] = self . inputs . reference_image if isdefined ( self . inputs . reference_mask ) : if self . inputs . explicit_masking : args [ 'fixed_image' ] = mask ( self . inputs . reference_image , self . inputs . reference_mask , "fixed_masked.nii.gz" ) if isdefined ( self . inputs . lesion_mask ) : args [ 'fixed_image_masks' ] = create_cfm ( self . inputs . reference_mask , lesion_mask = None , global_mask = True ) else : args [ 'fixed_image_masks' ] = self . inputs . reference_mask elif isdefined ( self . inputs . lesion_mask ) : args [ 'fixed_image_masks' ] = create_cfm ( self . inputs . reference_image , lesion_mask = None , global_mask = True ) else : if self . inputs . orientation == 'LAS' : raise NotImplementedError resolution = self . inputs . template_resolution ref_template = get_template ( self . inputs . template , resolution = resolution , desc = None , suffix = self . inputs . reference ) ref_mask = get_template ( self . inputs . template , resolution = resolution , desc = 'brain' , suffix = 'mask' ) args [ 'fixed_image' ] = str ( ref_template ) args [ 'fixed_image_masks' ] = str ( ref_mask ) if self . inputs . explicit_masking : args [ 'fixed_image' ] = mask ( str ( ref_template ) , str ( ref_mask ) , "fixed_masked.nii.gz" ) args . pop ( 'fixed_image_masks' , None ) if isdefined ( self . inputs . lesion_mask ) : args [ 'fixed_image_masks' ] = create_cfm ( str ( ref_mask ) , lesion_mask = None , global_mask = True ) return args | Moving image handling - The following truth table maps out the intended action sequence . Future refactoring may more directly encode this . |
22,901 | def dollars_to_math ( source ) : r s = "\n" . join ( source ) if s . find ( "$" ) == - 1 : return global _data _data = { } def repl ( matchobj ) : global _data s = matchobj . group ( 0 ) t = " XXX_REPL_%d " % len ( _data ) _data [ t ] = s return t s = re . sub ( r"({[^{}$]*\$[^{}$]*\$[^{}]*})" , repl , s ) dollars = re . compile ( r"(?<!\$)(?<!\\)\$([^\$]+?)\$" ) slashdollar = re . compile ( r"\\\$" ) s = dollars . sub ( r":math:`\1`" , s ) s = slashdollar . sub ( r"$" , s ) for r in _data : s = s . replace ( r , _data [ r ] ) source [ : ] = [ s ] | r Replace dollar signs with backticks . |
22,902 | def _post_run_hook ( self , runtime ) : self . _fixed_image = self . inputs . after self . _moving_image = self . inputs . before self . _contour = self . inputs . wm_seg if isdefined ( self . inputs . wm_seg ) else None NIWORKFLOWS_LOG . info ( 'Report - setting before (%s) and after (%s) images' , self . _fixed_image , self . _moving_image ) return super ( SimpleBeforeAfterRPT , self ) . _post_run_hook ( runtime ) | there is not inner interface to run |
22,903 | def _get_data_path ( data_dir = None ) : data_dir = data_dir or '' default_dirs = [ Path ( d ) . expanduser ( ) . resolve ( ) for d in os . getenv ( 'CRN_SHARED_DATA' , '' ) . split ( os . pathsep ) if d . strip ( ) ] default_dirs += [ Path ( d ) . expanduser ( ) . resolve ( ) for d in os . getenv ( 'CRN_DATA' , '' ) . split ( os . pathsep ) if d . strip ( ) ] default_dirs += [ NIWORKFLOWS_CACHE_DIR ] return [ Path ( d ) . expanduser ( ) for d in data_dir . split ( os . pathsep ) if d . strip ( ) ] or default_dirs | Get data storage directory |
22,904 | def _get_dataset ( dataset_name , dataset_prefix = None , data_dir = None , default_paths = None , verbose = 1 ) : dataset_folder = dataset_name if not dataset_prefix else '%s%s' % ( dataset_prefix , dataset_name ) default_paths = default_paths or '' paths = [ p / dataset_folder for p in _get_data_path ( data_dir ) ] all_paths = [ Path ( p ) / dataset_folder for p in default_paths . split ( os . pathsep ) ] + paths for path in all_paths : if path . is_dir ( ) and list ( path . iterdir ( ) ) : if verbose > 1 : NIWORKFLOWS_LOG . info ( 'Dataset "%s" already cached in %s' , dataset_name , path ) return path , True for path in paths : if verbose > 0 : NIWORKFLOWS_LOG . info ( 'Dataset "%s" not cached, downloading to %s' , dataset_name , path ) path . mkdir ( parents = True , exist_ok = True ) return path , False | Create if necessary and returns data directory of given dataset . |
22,905 | def _md5_sum_file ( path ) : with Path ( path ) . open ( 'rb' ) as fhandle : md5sum = hashlib . md5 ( ) while True : data = fhandle . read ( 8192 ) if not data : break md5sum . update ( data ) return md5sum . hexdigest ( ) | Calculates the MD5 sum of a file . |
22,906 | def _chunk_report_ ( bytes_so_far , total_size , initial_size , t_0 ) : if not total_size : sys . stderr . write ( "\rDownloaded {0:d} of ? bytes." . format ( bytes_so_far ) ) else : total_percent = float ( bytes_so_far ) / total_size current_download_size = bytes_so_far - initial_size bytes_remaining = total_size - bytes_so_far delta_t = time . time ( ) - t_0 download_rate = current_download_size / max ( 1e-8 , float ( delta_t ) ) time_remaining = bytes_remaining / max ( 0.01 , download_rate ) sys . stderr . write ( "\rDownloaded {0:d} of {1:d} bytes ({2:.1f}%, {3!s} remaining)" . format ( bytes_so_far , total_size , total_percent * 100 , _format_time ( time_remaining ) ) ) | Show downloading percentage . |
22,907 | def refine_aseg ( aseg , ball_size = 4 ) : bmask = aseg . copy ( ) bmask [ bmask > 0 ] = 1 bmask = bmask . astype ( np . uint8 ) selem = sim . ball ( ball_size ) newmask = sim . binary_closing ( bmask , selem ) newmask = binary_fill_holes ( newmask . astype ( np . uint8 ) , selem ) . astype ( np . uint8 ) return newmask . astype ( np . uint8 ) | First step to reconcile ANTs and FreeSurfer s brain masks . |
22,908 | def grow_mask ( anat , aseg , ants_segs = None , ww = 7 , zval = 2.0 , bw = 4 ) : selem = sim . ball ( bw ) if ants_segs is None : ants_segs = np . zeros_like ( aseg , dtype = np . uint8 ) aseg [ aseg == 42 ] = 3 gm = anat . copy ( ) gm [ aseg != 3 ] = 0 refined = refine_aseg ( aseg ) newrefmask = sim . binary_dilation ( refined , selem ) - refined indices = np . argwhere ( newrefmask > 0 ) for pixel in indices : if ants_segs [ tuple ( pixel ) ] == 2 : refined [ tuple ( pixel ) ] = 1 continue window = gm [ pixel [ 0 ] - ww : pixel [ 0 ] + ww , pixel [ 1 ] - ww : pixel [ 1 ] + ww , pixel [ 2 ] - ww : pixel [ 2 ] + ww ] if np . any ( window > 0 ) : mu = window [ window > 0 ] . mean ( ) sigma = max ( window [ window > 0 ] . std ( ) , 1.e-5 ) zstat = abs ( anat [ tuple ( pixel ) ] - mu ) / sigma refined [ tuple ( pixel ) ] = int ( zstat < zval ) refined = sim . binary_opening ( refined , selem ) return refined | Grow mask including pixels that have a high likelihood . GM tissue parameters are sampled in image patches of ww size . |
22,909 | def medial_wall_to_nan ( in_file , subjects_dir , target_subject , newpath = None ) : import nibabel as nb import numpy as np import os fn = os . path . basename ( in_file ) if not target_subject . startswith ( 'fs' ) : return in_file cortex = nb . freesurfer . read_label ( os . path . join ( subjects_dir , target_subject , 'label' , '{}.cortex.label' . format ( fn [ : 2 ] ) ) ) func = nb . load ( in_file ) medial = np . delete ( np . arange ( len ( func . darrays [ 0 ] . data ) ) , cortex ) for darray in func . darrays : darray . data [ medial ] = np . nan out_file = os . path . join ( newpath or os . getcwd ( ) , fn ) func . to_filename ( out_file ) return out_file | Convert values on medial wall to NaNs |
22,910 | def make_link_node ( rawtext , app , type , slug , options ) : try : base = app . config . github_project_url if not base : raise AttributeError if not base . endswith ( '/' ) : base += '/' except AttributeError as err : raise ValueError ( 'github_project_url configuration value is not set (%s)' % str ( err ) ) ref = base + type + '/' + slug + '/' set_classes ( options ) prefix = "#" if type == 'pull' : prefix = "PR " + prefix node = nodes . reference ( rawtext , prefix + utils . unescape ( slug ) , refuri = ref , ** options ) return node | Create a link to a github resource . |
22,911 | def ghissue_role ( name , rawtext , text , lineno , inliner , options = { } , content = [ ] ) : try : issue_num = int ( text ) if issue_num <= 0 : raise ValueError except ValueError : msg = inliner . reporter . error ( 'GitHub issue number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text , line = lineno ) prb = inliner . problematic ( rawtext , rawtext , msg ) return [ prb ] , [ msg ] app = inliner . document . settings . env . app if 'pull' in name . lower ( ) : category = 'pull' elif 'issue' in name . lower ( ) : category = 'issues' else : msg = inliner . reporter . error ( 'GitHub roles include "ghpull" and "ghissue", ' '"%s" is invalid.' % name , line = lineno ) prb = inliner . problematic ( rawtext , rawtext , msg ) return [ prb ] , [ msg ] node = make_link_node ( rawtext , app , category , str ( issue_num ) , options ) return [ node ] , [ ] | Link to a GitHub issue . |
22,912 | def ghuser_role ( name , rawtext , text , lineno , inliner , options = { } , content = [ ] ) : app = inliner . document . settings . env . app ref = 'https://www.github.com/' + text node = nodes . reference ( rawtext , text , refuri = ref , ** options ) return [ node ] , [ ] | Link to a GitHub user . |
22,913 | def ghcommit_role ( name , rawtext , text , lineno , inliner , options = { } , content = [ ] ) : app = inliner . document . settings . env . app try : base = app . config . github_project_url if not base : raise AttributeError if not base . endswith ( '/' ) : base += '/' except AttributeError as err : raise ValueError ( 'github_project_url configuration value is not set (%s)' % str ( err ) ) ref = base + text node = nodes . reference ( rawtext , text [ : 6 ] , refuri = ref , ** options ) return [ node ] , [ ] | Link to a GitHub commit . |
22,914 | def _import ( self , name ) : mod = __import__ ( name ) components = name . split ( '.' ) for comp in components [ 1 : ] : mod = getattr ( mod , comp ) return mod | Import namespace package |
22,915 | def discover_modules ( self ) : modules = [ self . package_name ] for dirpath , dirnames , filenames in os . walk ( self . root_path ) : root_uri = self . _path2uri ( os . path . join ( self . root_path , dirpath ) ) filenames = [ f [ : - 3 ] for f in filenames if f . endswith ( '.py' ) and not f . startswith ( '__init__' ) ] for filename in filenames : package_uri = '/' . join ( ( dirpath , filename ) ) for subpkg_name in dirnames + filenames : package_uri = '.' . join ( ( root_uri , subpkg_name ) ) package_path = self . _uri2path ( package_uri ) if ( package_path and self . _survives_exclude ( package_uri , 'package' ) ) : modules . append ( package_uri ) return sorted ( modules ) | Return module sequence discovered from self . package_name |
22,916 | def get_metadata_for_nifti ( in_file , bids_dir = None , validate = True ) : return _init_layout ( in_file , bids_dir , validate ) . get_metadata ( str ( in_file ) ) | Fetch metadata for a given nifti file |
22,917 | def group_multiecho ( bold_sess ) : from itertools import groupby def _grp_echos ( x ) : if '_echo-' not in x : return x echo = re . search ( "_echo-\\d*" , x ) . group ( 0 ) return x . replace ( echo , "_echo-?" ) ses_uids = [ ] for _ , bold in groupby ( bold_sess , key = _grp_echos ) : bold = list ( bold ) action = getattr ( ses_uids , 'append' if len ( bold ) > 2 else 'extend' ) action ( bold ) return ses_uids | Multiplexes multi - echo EPIs into arrays . Dual - echo is a special case of multi - echo which is treated as single - echo data . |
22,918 | def _define_variant ( self ) : space = None variants = { 'space1' : [ 'fsaverage5' , 'MNI152NLin2009cAsym' ] , 'space2' : [ 'fsaverage6' , 'MNI152NLin2009cAsym' ] , } for sp , targets in variants . items ( ) : if all ( target in targets for target in [ self . inputs . surface_target , self . inputs . volume_target ] ) : space = sp if space is None : raise NotImplementedError variant_key = os . path . abspath ( 'dtseries_variant.json' ) with open ( variant_key , 'w' ) as fp : json . dump ( { space : variants [ space ] } , fp ) return variant_key , space | Assign arbitrary label to combination of CIFTI spaces |
22,919 | def _fetch_data ( self ) : if ( self . inputs . surface_target == "fsnative" or self . inputs . volume_target != "MNI152NLin2009cAsym" ) : raise NotImplementedError annotation_files = sorted ( glob ( os . path . join ( self . inputs . subjects_dir , self . inputs . surface_target , 'label' , '*h.aparc.annot' ) ) ) if not annotation_files : raise IOError ( "Freesurfer annotations for %s not found in %s" % ( self . inputs . surface_target , self . inputs . subjects_dir ) ) label_file = str ( get_template ( 'MNI152NLin2009cAsym' , resolution = 2 , desc = 'DKT31' , suffix = 'dseg' ) ) return annotation_files , label_file | Converts inputspec to files |
22,920 | def reorient ( in_file , newpath = None ) : out_file = fname_presuffix ( in_file , suffix = '_ras' , newpath = newpath ) nb . as_closest_canonical ( nb . load ( in_file ) ) . to_filename ( out_file ) return out_file | Reorient Nifti files to RAS |
22,921 | def normalize_xform ( img ) : tmp_header = img . header . copy ( ) tmp_header . set_qform ( img . affine ) xform = tmp_header . get_qform ( ) xform_code = 2 qform , qform_code = img . get_qform ( coded = True ) sform , sform_code = img . get_sform ( coded = True ) if all ( ( qform is not None and np . allclose ( qform , xform ) , sform is not None and np . allclose ( sform , xform ) , int ( qform_code ) == xform_code , int ( sform_code ) == xform_code ) ) : return img new_img = img . __class__ ( img . get_data ( ) , xform , img . header ) new_img . set_sform ( xform , xform_code ) new_img . set_qform ( xform , xform_code ) return new_img | Set identical valid qform and sform matrices in an image |
22,922 | def demean ( in_file , in_mask , only_mask = False , newpath = None ) : import os import numpy as np import nibabel as nb from nipype . utils . filemanip import fname_presuffix out_file = fname_presuffix ( in_file , suffix = '_demeaned' , newpath = os . getcwd ( ) ) nii = nb . load ( in_file ) msk = nb . load ( in_mask ) . get_data ( ) data = nii . get_data ( ) if only_mask : data [ msk > 0 ] -= np . median ( data [ msk > 0 ] ) else : data -= np . median ( data [ msk > 0 ] ) nb . Nifti1Image ( data , nii . affine , nii . header ) . to_filename ( out_file ) return out_file | Demean in_file within the mask defined by in_mask |
22,923 | def nii_ones_like ( in_file , value , dtype , newpath = None ) : import os import numpy as np import nibabel as nb nii = nb . load ( in_file ) data = np . ones ( nii . shape , dtype = float ) * value out_file = os . path . join ( newpath or os . getcwd ( ) , "filled.nii.gz" ) nii = nb . Nifti1Image ( data , nii . affine , nii . header ) nii . set_data_dtype ( dtype ) nii . to_filename ( out_file ) return out_file | Create a NIfTI file filled with value matching properties of in_file |
22,924 | def reorient_wf ( name = 'ReorientWorkflow' ) : workflow = pe . Workflow ( name = name ) inputnode = pe . Node ( niu . IdentityInterface ( fields = [ 'in_file' ] ) , name = 'inputnode' ) outputnode = pe . Node ( niu . IdentityInterface ( fields = [ 'out_file' ] ) , name = 'outputnode' ) deoblique = pe . Node ( afni . Refit ( deoblique = True ) , name = 'deoblique' ) reorient = pe . Node ( afni . Resample ( orientation = 'RPI' , outputtype = 'NIFTI_GZ' ) , name = 'reorient' ) workflow . connect ( [ ( inputnode , deoblique , [ ( 'in_file' , 'in_file' ) ] ) , ( deoblique , reorient , [ ( 'out_file' , 'in_file' ) ] ) , ( reorient , outputnode , [ ( 'out_file' , 'out_file' ) ] ) ] ) return workflow | A workflow to reorient images to RPI orientation |
22,925 | def _tsv2json ( in_tsv , out_json , index_column , additional_metadata = None , drop_columns = None , enforce_case = True ) : import pandas as pd re_to_camel = r'(.*?)_([a-zA-Z0-9])' re_to_snake = r'(^.+?|.*?)((?<![_A-Z])[A-Z]|(?<![_0-9])[0-9]+)' def snake ( match ) : return '{}_{}' . format ( match . group ( 1 ) . lower ( ) , match . group ( 2 ) . lower ( ) ) def camel ( match ) : return '{}{}' . format ( match . group ( 1 ) , match . group ( 2 ) . upper ( ) ) def less_breakable ( a_string ) : return '' . join ( a_string . split ( ) ) . strip ( '#' ) drop_columns = drop_columns or [ ] additional_metadata = additional_metadata or { } tsv_data = pd . read_csv ( in_tsv , '\t' ) for k , v in additional_metadata . items ( ) : tsv_data [ k ] = v for col in drop_columns : tsv_data . drop ( labels = col , axis = 'columns' , inplace = True ) tsv_data . set_index ( index_column , drop = True , inplace = True ) if enforce_case : tsv_data . index = [ re . sub ( re_to_snake , snake , less_breakable ( i ) , 0 ) . lower ( ) for i in tsv_data . index ] tsv_data . columns = [ re . sub ( re_to_camel , camel , less_breakable ( i ) . title ( ) , 0 ) for i in tsv_data . columns ] json_data = tsv_data . to_json ( orient = 'index' ) json_data = json . JSONDecoder ( object_pairs_hook = OrderedDict ) . decode ( json_data ) if out_json is None : return json_data with open ( out_json , 'w' ) as f : json . dump ( json_data , f , indent = 4 ) return out_json | Convert metadata from TSV format to JSON format . |
22,926 | def _tpm2roi ( in_tpm , in_mask , mask_erosion_mm = None , erosion_mm = None , mask_erosion_prop = None , erosion_prop = None , pthres = 0.95 , newpath = None ) : tpm_img = nb . load ( in_tpm ) roi_mask = ( tpm_img . get_data ( ) >= pthres ) . astype ( np . uint8 ) eroded_mask_file = None erode_in = ( mask_erosion_mm is not None and mask_erosion_mm > 0 or mask_erosion_prop is not None and mask_erosion_prop < 1 ) if erode_in : eroded_mask_file = fname_presuffix ( in_mask , suffix = '_eroded' , newpath = newpath ) mask_img = nb . load ( in_mask ) mask_data = mask_img . get_data ( ) . astype ( np . uint8 ) if mask_erosion_mm : iter_n = max ( int ( mask_erosion_mm / max ( mask_img . header . get_zooms ( ) ) ) , 1 ) mask_data = nd . binary_erosion ( mask_data , iterations = iter_n ) else : orig_vol = np . sum ( mask_data > 0 ) while np . sum ( mask_data > 0 ) / orig_vol > mask_erosion_prop : mask_data = nd . binary_erosion ( mask_data , iterations = 1 ) eroded = nb . Nifti1Image ( mask_data , mask_img . affine , mask_img . header ) eroded . set_data_dtype ( np . uint8 ) eroded . to_filename ( eroded_mask_file ) roi_mask [ ~ mask_data ] = 0 erode_out = ( erosion_mm is not None and erosion_mm > 0 or erosion_prop is not None and erosion_prop < 1 ) if erode_out : if erosion_mm : iter_n = max ( int ( erosion_mm / max ( tpm_img . header . get_zooms ( ) ) ) , 1 ) iter_n = int ( erosion_mm / max ( tpm_img . header . get_zooms ( ) ) ) roi_mask = nd . binary_erosion ( roi_mask , iterations = iter_n ) else : orig_vol = np . sum ( roi_mask > 0 ) while np . sum ( roi_mask > 0 ) / orig_vol > erosion_prop : roi_mask = nd . binary_erosion ( roi_mask , iterations = 1 ) roi_fname = fname_presuffix ( in_tpm , suffix = '_roi' , newpath = newpath ) roi_img = nb . Nifti1Image ( roi_mask , tpm_img . affine , tpm_img . header ) roi_img . set_data_dtype ( np . uint8 ) roi_img . to_filename ( roi_fname ) return roi_fname , eroded_mask_file or in_mask | Generate a mask from a tissue probability map |
22,927 | def run_reports ( reportlets_dir , out_dir , subject_label , run_uuid , config = None , packagename = None ) : report = Report ( Path ( reportlets_dir ) , out_dir , run_uuid , config = config , subject_id = subject_label , packagename = packagename ) return report . generate_report ( ) | Runs the reports |
22,928 | def generate_reports ( subject_list , output_dir , work_dir , run_uuid , config = None , packagename = None ) : reports_dir = str ( Path ( work_dir ) / 'reportlets' ) report_errors = [ run_reports ( reports_dir , output_dir , subject_label , run_uuid , config , packagename = packagename ) for subject_label in subject_list ] errno = sum ( report_errors ) if errno : import logging logger = logging . getLogger ( 'cli' ) error_list = ', ' . join ( '%s (%d)' % ( subid , err ) for subid , err in zip ( subject_list , report_errors ) if err ) logger . error ( 'Preprocessing did not finish successfully. Errors occurred while processing ' 'data from participants: %s. Check the HTML reports for details.' , error_list ) return errno | A wrapper to run_reports on a given subject_list |
22,929 | def index ( self , config ) : for subrep_cfg in config : orderings = [ s for s in subrep_cfg . get ( 'ordering' , '' ) . strip ( ) . split ( ',' ) if s ] queries = [ ] for key in orderings : values = getattr ( self . layout , 'get_%s%s' % ( key , PLURAL_SUFFIX [ key ] ) ) ( ) if values : queries . append ( ( key , values ) ) if not queries : reportlets = [ Reportlet ( self . layout , self . out_dir , config = cfg ) for cfg in subrep_cfg [ 'reportlets' ] ] else : reportlets = [ ] entities , values = zip ( * queries ) combinations = list ( product ( * values ) ) for c in combinations : title = 'Reports for: %s.' % ', ' . join ( [ '%s <span class="bids-entity">%s</span>' % ( entities [ i ] , c [ i ] ) for i in range ( len ( c ) ) ] ) for cfg in subrep_cfg [ 'reportlets' ] : cfg [ 'bids' ] . update ( { entities [ i ] : c [ i ] for i in range ( len ( c ) ) } ) rlet = Reportlet ( self . layout , self . out_dir , config = cfg ) if not rlet . is_empty ( ) : rlet . title = title title = None reportlets . append ( rlet ) reportlets = [ r for r in reportlets if not r . is_empty ( ) ] if reportlets : sub_report = SubReport ( subrep_cfg [ 'name' ] , isnested = len ( queries ) > 0 , reportlets = reportlets , title = subrep_cfg . get ( 'title' ) ) self . sections . append ( sub_report ) error_dir = self . out_dir / self . packagename / 'sub-{}' . format ( self . subject_id ) / 'log' / self . run_uuid if error_dir . is_dir ( ) : from . . utils . misc import read_crashfile self . errors = [ read_crashfile ( str ( f ) ) for f in error_dir . glob ( 'crash*.*' ) ] | Traverse the reports config definition and instantiate reportlets . This method also places figures in their final location . |
22,930 | def generate_report ( self ) : logs_path = self . out_dir / 'logs' boilerplate = [ ] boiler_idx = 0 if ( logs_path / 'CITATION.html' ) . exists ( ) : text = ( logs_path / 'CITATION.html' ) . read_text ( encoding = 'UTF-8' ) text = '<div class="boiler-html">%s</div>' % re . compile ( '<body>(.*?)</body>' , re . DOTALL | re . IGNORECASE ) . findall ( text ) [ 0 ] . strip ( ) boilerplate . append ( ( boiler_idx , 'HTML' , text ) ) boiler_idx += 1 if ( logs_path / 'CITATION.md' ) . exists ( ) : text = '<pre>%s</pre>\n' % ( logs_path / 'CITATION.md' ) . read_text ( encoding = 'UTF-8' ) boilerplate . append ( ( boiler_idx , 'Markdown' , text ) ) boiler_idx += 1 if ( logs_path / 'CITATION.tex' ) . exists ( ) : text = ( logs_path / 'CITATION.tex' ) . read_text ( encoding = 'UTF-8' ) text = re . compile ( r'\\begin{document}(.*?)\\end{document}' , re . DOTALL | re . IGNORECASE ) . findall ( text ) [ 0 ] . strip ( ) text = '<pre>%s</pre>\n' % text text += '<h3>Bibliography</h3>\n' text += '<pre>%s</pre>\n' % Path ( pkgrf ( self . packagename , 'data/boilerplate.bib' ) ) . read_text ( encoding = 'UTF-8' ) boilerplate . append ( ( boiler_idx , 'LaTeX' , text ) ) boiler_idx += 1 env = jinja2 . Environment ( loader = jinja2 . FileSystemLoader ( searchpath = str ( self . template_path . parent ) ) , trim_blocks = True , lstrip_blocks = True ) report_tpl = env . get_template ( self . template_path . name ) report_render = report_tpl . render ( sections = self . sections , errors = self . errors , boilerplate = boilerplate ) ( self . out_dir / self . out_filename ) . write_text ( report_render , encoding = 'UTF-8' ) return len ( self . errors ) | Once the Report has been indexed the final HTML can be generated |
22,931 | def _applytfms ( args ) : import nibabel as nb from nipype . utils . filemanip import fname_presuffix from niworkflows . interfaces . fixes import FixHeaderApplyTransforms as ApplyTransforms in_file , in_xform , ifargs , index , newpath = args out_file = fname_presuffix ( in_file , suffix = '_xform-%05d' % index , newpath = newpath , use_ext = True ) copy_dtype = ifargs . pop ( 'copy_dtype' , False ) xfm = ApplyTransforms ( input_image = in_file , transforms = in_xform , output_image = out_file , ** ifargs ) xfm . terminal_output = 'allatonce' xfm . resource_monitor = False runtime = xfm . run ( ) . runtime if copy_dtype : nii = nb . load ( out_file ) in_dtype = nb . load ( in_file ) . get_data_dtype ( ) if in_dtype != nii . get_data_dtype ( ) : nii . set_data_dtype ( in_dtype ) nii . to_filename ( out_file ) return ( out_file , runtime . cmdline ) | Applies ANTs antsApplyTransforms to the input image . All inputs are zipped in one tuple to make it digestible by multiprocessing s map |
22,932 | def _arrange_xfms ( transforms , num_files , tmp_folder ) : base_xform = [ '#Insight Transform File V1.0' , '#Transform 0' ] xfms_T = [ ] for i , tf_file in enumerate ( transforms ) : if guess_type ( tf_file ) [ 0 ] != 'text/plain' : xfms_T . append ( [ tf_file ] * num_files ) continue with open ( tf_file ) as tf_fh : tfdata = tf_fh . read ( ) . strip ( ) if not tfdata . startswith ( '#Insight Transform File' ) : xfms_T . append ( [ tf_file ] * num_files ) continue nxforms = tfdata . count ( '#Transform' ) tfdata = tfdata . split ( '\n' ) [ 1 : ] if nxforms == 1 : xfms_T . append ( [ tf_file ] * num_files ) continue if nxforms != num_files : raise RuntimeError ( 'Number of transforms (%d) found in the ITK file does not match' ' the number of input image files (%d).' % ( nxforms , num_files ) ) out_base = fname_presuffix ( tf_file , suffix = '_pos-%03d_xfm-{:05d}' % i , newpath = tmp_folder . name ) . format split_xfms = [ ] for xform_i in range ( nxforms ) : startidx = tfdata . index ( '#Transform %d' % xform_i ) next_xform = base_xform + tfdata [ startidx + 1 : startidx + 4 ] + [ '' ] xfm_file = out_base ( xform_i ) with open ( xfm_file , 'w' ) as out_xfm : out_xfm . write ( '\n' . join ( next_xform ) ) split_xfms . append ( xfm_file ) xfms_T . append ( split_xfms ) return list ( map ( list , zip ( * xfms_T ) ) ) | Convenience method to arrange the list of transforms that should be applied to each input file |
22,933 | def normalize_surfs ( in_file , transform_file , newpath = None ) : img = nb . load ( in_file ) transform = load_transform ( transform_file ) pointset = img . get_arrays_from_intent ( 'NIFTI_INTENT_POINTSET' ) [ 0 ] coords = pointset . data . T c_ras_keys = ( 'VolGeomC_R' , 'VolGeomC_A' , 'VolGeomC_S' ) ras = np . array ( [ [ float ( pointset . metadata [ key ] ) ] for key in c_ras_keys ] ) ones = np . ones ( ( 1 , coords . shape [ 1 ] ) , dtype = coords . dtype ) pointset . data = transform . dot ( np . vstack ( ( coords + ras , ones ) ) ) [ : 3 ] . T . astype ( coords . dtype ) secondary = nb . gifti . GiftiNVPairs ( 'AnatomicalStructureSecondary' , 'MidThickness' ) geom_type = nb . gifti . GiftiNVPairs ( 'GeometricType' , 'Anatomical' ) has_ass = has_geo = False for nvpair in pointset . meta . data : if nvpair . name in c_ras_keys : nvpair . value = '0.000000' elif nvpair . name == secondary . name : has_ass = True elif nvpair . name == geom_type . name : has_geo = True fname = os . path . basename ( in_file ) if 'midthickness' in fname . lower ( ) or 'graymid' in fname . lower ( ) : if not has_ass : pointset . meta . data . insert ( 1 , secondary ) if not has_geo : pointset . meta . data . insert ( 2 , geom_type ) if newpath is not None : newpath = os . getcwd ( ) out_file = os . path . join ( newpath , fname ) img . to_filename ( out_file ) return out_file | Re - center GIFTI coordinates to fit align to native T1 space |
22,934 | def load_transform ( fname ) : if fname is None : return np . eye ( 4 ) if fname . endswith ( '.mat' ) : return np . loadtxt ( fname ) elif fname . endswith ( '.lta' ) : with open ( fname , 'rb' ) as fobj : for line in fobj : if line . startswith ( b'1 4 4' ) : break lines = fobj . readlines ( ) [ : 4 ] return np . genfromtxt ( lines ) raise ValueError ( "Unknown transform type; pass FSL (.mat) or LTA (.lta)" ) | Load affine transform from file |
22,935 | def vertex_normals ( vertices , faces ) : def normalize_v3 ( arr ) : lens = np . sqrt ( arr [ : , 0 ] ** 2 + arr [ : , 1 ] ** 2 + arr [ : , 2 ] ** 2 ) arr /= lens [ : , np . newaxis ] tris = vertices [ faces ] facenorms = np . cross ( tris [ : : , 1 ] - tris [ : : , 0 ] , tris [ : : , 2 ] - tris [ : : , 0 ] ) normalize_v3 ( facenorms ) norm = np . zeros ( vertices . shape , dtype = vertices . dtype ) norm [ faces [ : , 0 ] ] += facenorms norm [ faces [ : , 1 ] ] += facenorms norm [ faces [ : , 2 ] ] += facenorms normalize_v3 ( norm ) return norm | Calculates the normals of a triangular mesh |
22,936 | def pointcloud2ply ( vertices , normals , out_file = None ) : from pathlib import Path import pandas as pd from pyntcloud import PyntCloud df = pd . DataFrame ( np . hstack ( ( vertices , normals ) ) ) df . columns = [ 'x' , 'y' , 'z' , 'nx' , 'ny' , 'nz' ] cloud = PyntCloud ( df ) if out_file is None : out_file = Path ( 'pointcloud.ply' ) . resolve ( ) cloud . to_file ( str ( out_file ) ) return out_file | Converts the file to PLY format |
22,937 | def ply2gii ( in_file , metadata , out_file = None ) : from pathlib import Path from numpy import eye from nibabel . gifti import ( GiftiMetaData , GiftiCoordSystem , GiftiImage , GiftiDataArray , ) from pyntcloud import PyntCloud in_file = Path ( in_file ) surf = PyntCloud . from_file ( str ( in_file ) ) metadata . update ( zip ( ( 'SurfaceCenterX' , 'SurfaceCenterY' , 'SurfaceCenterZ' ) , [ '%.4f' % c for c in surf . centroid ] ) ) da = ( GiftiDataArray ( data = surf . xyz . astype ( 'float32' ) , datatype = 'NIFTI_TYPE_FLOAT32' , intent = 'NIFTI_INTENT_POINTSET' , meta = GiftiMetaData . from_dict ( metadata ) , coordsys = GiftiCoordSystem ( xform = eye ( 4 ) , xformspace = 3 ) ) , GiftiDataArray ( data = surf . mesh . values , datatype = 'NIFTI_TYPE_INT32' , intent = 'NIFTI_INTENT_TRIANGLE' , coordsys = None ) ) surfgii = GiftiImage ( darrays = da ) if out_file is None : out_file = fname_presuffix ( in_file . name , suffix = '.gii' , use_ext = False , newpath = str ( Path . cwd ( ) ) ) surfgii . to_filename ( str ( out_file ) ) return out_file | Convert from ply to GIfTI |
22,938 | def fix_multi_T1w_source_name ( in_files ) : import os from nipype . utils . filemanip import filename_to_list base , in_file = os . path . split ( filename_to_list ( in_files ) [ 0 ] ) subject_label = in_file . split ( "_" , 1 ) [ 0 ] . split ( "-" ) [ 1 ] return os . path . join ( base , "sub-%s_T1w.nii.gz" % subject_label ) | Make up a generic source name when there are multiple T1s |
22,939 | def add_suffix ( in_files , suffix ) : import os . path as op from nipype . utils . filemanip import fname_presuffix , filename_to_list return op . basename ( fname_presuffix ( filename_to_list ( in_files ) [ 0 ] , suffix = suffix ) ) | Wrap nipype s fname_presuffix to conveniently just add a prefix |
22,940 | def _read_txt ( path ) : from pathlib import Path lines = Path ( path ) . read_text ( ) . splitlines ( ) data = { 'file' : str ( path ) } traceback_start = 0 if lines [ 0 ] . startswith ( 'Node' ) : data [ 'node' ] = lines [ 0 ] . split ( ': ' , 1 ) [ 1 ] . strip ( ) data [ 'node_dir' ] = lines [ 1 ] . split ( ': ' , 1 ) [ 1 ] . strip ( ) inputs = [ ] cur_key = '' cur_val = '' for i , line in enumerate ( lines [ 5 : ] ) : if not line . strip ( ) : continue if line [ 0 ] . isspace ( ) : cur_val += line continue if cur_val : inputs . append ( ( cur_key , cur_val . strip ( ) ) ) if line . startswith ( "Traceback (" ) : traceback_start = i + 5 break cur_key , cur_val = tuple ( line . split ( ' = ' , 1 ) ) data [ 'inputs' ] = sorted ( inputs ) else : data [ 'node_dir' ] = "Node crashed before execution" data [ 'traceback' ] = '\n' . join ( lines [ traceback_start : ] ) . strip ( ) return data | Read a txt crashfile |
22,941 | def _conform_mask ( in_mask , in_reference ) : from pathlib import Path import nibabel as nb from nipype . utils . filemanip import fname_presuffix ref = nb . load ( in_reference ) nii = nb . load ( in_mask ) hdr = nii . header . copy ( ) hdr . set_data_dtype ( 'int16' ) hdr . set_slope_inter ( 1 , 0 ) qform , qcode = ref . header . get_qform ( coded = True ) if qcode is not None : hdr . set_qform ( qform , int ( qcode ) ) sform , scode = ref . header . get_sform ( coded = True ) if scode is not None : hdr . set_sform ( sform , int ( scode ) ) if '_maths' in in_mask : ext = '' . join ( Path ( in_mask ) . suffixes ) basename = Path ( in_mask ) . name in_mask = basename . split ( '_maths' ) [ 0 ] + ext out_file = fname_presuffix ( in_mask , suffix = '_mask' , newpath = str ( Path ( ) ) ) nii . __class__ ( nii . get_data ( ) . astype ( 'int16' ) , ref . affine , hdr ) . to_filename ( out_file ) return out_file | Ensures the mask headers make sense and match those of the T1w |
22,942 | def get_template ( template_name , data_dir = None , url = None , resume = True , verbose = 1 ) : warn ( DEPRECATION_MSG ) if template_name . startswith ( 'tpl-' ) : template_name = template_name [ 4 : ] template_name = TEMPLATE_ALIASES . get ( template_name , template_name ) return get_dataset ( template_name , dataset_prefix = 'tpl-' , data_dir = data_dir , url = url , resume = resume , verbose = verbose ) | Download and load a template |
22,943 | def get_bids_examples ( data_dir = None , url = None , resume = True , verbose = 1 , variant = 'BIDS-examples-1-1.0.0-rc3u5' ) : warn ( DEPRECATION_MSG ) variant = 'BIDS-examples-1-1.0.0-rc3u5' if variant not in BIDS_EXAMPLES else variant if url is None : url = BIDS_EXAMPLES [ variant ] [ 0 ] md5 = BIDS_EXAMPLES [ variant ] [ 1 ] return fetch_file ( variant , url , data_dir , resume = resume , verbose = verbose , md5sum = md5 ) | Download BIDS - examples - 1 |
22,944 | def svg2str ( display_object , dpi = 300 ) : from io import StringIO image_buf = StringIO ( ) display_object . frame_axes . figure . savefig ( image_buf , dpi = dpi , format = 'svg' , facecolor = 'k' , edgecolor = 'k' ) return image_buf . getvalue ( ) | Serializes a nilearn display object as a string |
22,945 | def extract_svg ( display_object , dpi = 300 , compress = 'auto' ) : image_svg = svg2str ( display_object , dpi ) if compress is True or compress == 'auto' : image_svg = svg_compress ( image_svg , compress ) image_svg = re . sub ( ' height="[0-9]+[a-z]*"' , '' , image_svg , count = 1 ) image_svg = re . sub ( ' width="[0-9]+[a-z]*"' , '' , image_svg , count = 1 ) image_svg = re . sub ( ' viewBox' , ' preseveAspectRation="xMidYMid meet" viewBox' , image_svg , count = 1 ) start_tag = '<svg ' start_idx = image_svg . find ( start_tag ) end_tag = '</svg>' end_idx = image_svg . rfind ( end_tag ) if start_idx is - 1 or end_idx is - 1 : NIWORKFLOWS_LOG . info ( 'svg tags not found in extract_svg' ) end_idx += len ( end_tag ) return image_svg [ start_idx : end_idx ] | Removes the preamble of the svg files generated with nilearn |
22,946 | def cuts_from_bbox ( mask_nii , cuts = 3 ) : from nibabel . affines import apply_affine mask_data = mask_nii . get_data ( ) > 0.0 ijk_counts = [ mask_data . sum ( 2 ) . sum ( 1 ) , mask_data . sum ( 2 ) . sum ( 0 ) , mask_data . sum ( 1 ) . sum ( 0 ) , ] ijk_th = [ int ( ( mask_data . shape [ 1 ] * mask_data . shape [ 2 ] ) * 0.2 ) , int ( ( mask_data . shape [ 0 ] * mask_data . shape [ 2 ] ) * 0.0 ) , int ( ( mask_data . shape [ 0 ] * mask_data . shape [ 1 ] ) * 0.3 ) , ] vox_coords = [ ] for ax , ( c , th ) in enumerate ( zip ( ijk_counts , ijk_th ) ) : B = np . argwhere ( c > th ) if B . size : smin , smax = B . min ( ) , B . max ( ) if not B . size or ( th > 0 and ( smin + cuts + 1 ) >= smax ) : B = np . argwhere ( c > 0 ) smin , smax = B . min ( ) , B . max ( ) if B . size else ( 0 , mask_data . shape [ ax ] ) inc = ( smax - smin ) / ( cuts + 1 ) vox_coords . append ( [ smin + ( i + 1 ) * inc for i in range ( cuts ) ] ) ras_coords = [ ] for cross in np . array ( vox_coords ) . T : ras_coords . append ( apply_affine ( mask_nii . affine , cross ) . tolist ( ) ) ras_cuts = [ list ( coords ) for coords in np . transpose ( ras_coords ) ] return { k : v for k , v in zip ( [ 'x' , 'y' , 'z' ] , ras_cuts ) } | Finds equi - spaced cuts for presenting images |
22,947 | def _3d_in_file ( in_file ) : in_file = filemanip . filename_to_list ( in_file ) [ 0 ] try : in_file = nb . load ( in_file ) except AttributeError : in_file = in_file if in_file . get_data ( ) . ndim == 3 : return in_file return nlimage . index_img ( in_file , 0 ) | if self . inputs . in_file is 3d return it . if 4d pick an arbitrary volume and return that . |
22,948 | def transform_to_2d ( data , max_axis ) : import numpy as np new_shape = list ( data . shape ) del new_shape [ max_axis ] a1 , a2 = np . indices ( new_shape ) inds = [ a1 , a2 ] inds . insert ( max_axis , np . abs ( data ) . argmax ( axis = max_axis ) ) maximum_intensity_data = data [ inds ] return np . rot90 ( maximum_intensity_data ) | Projects 3d data cube along one axis using maximum intensity with preservation of the signs . Adapted from nilearn . |
22,949 | def main ( ) : from os import path as op from inspect import getfile , currentframe from setuptools import setup , find_packages from niworkflows . __about__ import ( __packagename__ , __author__ , __email__ , __maintainer__ , __license__ , __description__ , __longdesc__ , __url__ , DOWNLOAD_URL , CLASSIFIERS , REQUIRES , SETUP_REQUIRES , LINKS_REQUIRES , TESTS_REQUIRES , EXTRA_REQUIRES , ) pkg_data = { 'niworkflows' : [ 'data/t1-mni_registration*.json' , 'data/bold-mni_registration*.json' , 'reports/figures.json' , 'reports/fmriprep.yml' , 'reports/report.tpl' , ] } root_dir = op . dirname ( op . abspath ( getfile ( currentframe ( ) ) ) ) version = None cmdclass = { } if op . isfile ( op . join ( root_dir , __packagename__ , 'VERSION' ) ) : with open ( op . join ( root_dir , __packagename__ , 'VERSION' ) ) as vfile : version = vfile . readline ( ) . strip ( ) pkg_data [ __packagename__ ] . insert ( 0 , 'VERSION' ) if version is None : import versioneer version = versioneer . get_version ( ) cmdclass = versioneer . get_cmdclass ( ) setup ( name = __packagename__ , version = version , description = __description__ , long_description = __longdesc__ , author = __author__ , author_email = __email__ , maintainer = __maintainer__ , maintainer_email = __email__ , license = __license__ , url = __url__ , download_url = DOWNLOAD_URL , classifiers = CLASSIFIERS , packages = find_packages ( exclude = [ '*.tests' ] ) , zip_safe = False , setup_requires = SETUP_REQUIRES , install_requires = list ( set ( REQUIRES ) ) , dependency_links = LINKS_REQUIRES , tests_require = TESTS_REQUIRES , extras_require = EXTRA_REQUIRES , package_data = pkg_data , include_package_data = True , cmdclass = cmdclass , ) | Install entry - point |
22,950 | def afni_wf ( name = 'AFNISkullStripWorkflow' , unifize = False , n4_nthreads = 1 ) : workflow = pe . Workflow ( name = name ) inputnode = pe . Node ( niu . IdentityInterface ( fields = [ 'in_file' ] ) , name = 'inputnode' ) outputnode = pe . Node ( niu . IdentityInterface ( fields = [ 'bias_corrected' , 'out_file' , 'out_mask' , 'bias_image' ] ) , name = 'outputnode' ) inu_n4 = pe . Node ( ants . N4BiasFieldCorrection ( dimension = 3 , save_bias = True , num_threads = n4_nthreads , copy_header = True ) , n_procs = n4_nthreads , name = 'inu_n4' ) sstrip = pe . Node ( afni . SkullStrip ( outputtype = 'NIFTI_GZ' ) , name = 'skullstrip' ) sstrip_orig_vol = pe . Node ( afni . Calc ( expr = 'a*step(b)' , outputtype = 'NIFTI_GZ' ) , name = 'sstrip_orig_vol' ) binarize = pe . Node ( fsl . Threshold ( args = '-bin' , thresh = 1.e-3 ) , name = 'binarize' ) if unifize : inu_uni_0 = pe . Node ( afni . Unifize ( outputtype = 'NIFTI_GZ' ) , name = 'unifize_pre_skullstrip' ) inu_uni_1 = pe . Node ( afni . Unifize ( gm = True , outputtype = 'NIFTI_GZ' ) , name = 'unifize_post_skullstrip' ) workflow . connect ( [ ( inu_n4 , inu_uni_0 , [ ( 'output_image' , 'in_file' ) ] ) , ( inu_uni_0 , sstrip , [ ( 'out_file' , 'in_file' ) ] ) , ( inu_uni_0 , sstrip_orig_vol , [ ( 'out_file' , 'in_file_a' ) ] ) , ( sstrip_orig_vol , inu_uni_1 , [ ( 'out_file' , 'in_file' ) ] ) , ( inu_uni_1 , outputnode , [ ( 'out_file' , 'out_file' ) ] ) , ( inu_uni_0 , outputnode , [ ( 'out_file' , 'bias_corrected' ) ] ) , ] ) else : workflow . connect ( [ ( inputnode , sstrip_orig_vol , [ ( 'in_file' , 'in_file_a' ) ] ) , ( inu_n4 , sstrip , [ ( 'output_image' , 'in_file' ) ] ) , ( sstrip_orig_vol , outputnode , [ ( 'out_file' , 'out_file' ) ] ) , ( inu_n4 , outputnode , [ ( 'output_image' , 'bias_corrected' ) ] ) , ] ) workflow . connect ( [ ( sstrip , sstrip_orig_vol , [ ( 'out_file' , 'in_file_b' ) ] ) , ( inputnode , inu_n4 , [ ( 'in_file' , 'input_image' ) ] ) , ( sstrip_orig_vol , binarize , [ ( 'out_file' , 'in_file' ) ] ) , ( binarize , outputnode , [ ( 'out_file' , 'out_mask' ) ] ) , ( inu_n4 , outputnode , [ ( 'bias_image' , 'bias_image' ) ] ) , ] ) return workflow | Skull - stripping workflow |
22,951 | def _get ( url , headers = { } , params = None ) : param_string = _foursquare_urlencode ( params ) for i in xrange ( NUM_REQUEST_RETRIES ) : try : try : response = requests . get ( url , headers = headers , params = param_string , verify = VERIFY_SSL ) return _process_response ( response ) except requests . exceptions . RequestException as e : _log_and_raise_exception ( 'Error connecting with foursquare API' , e ) except FoursquareException as e : if e . __class__ in [ InvalidAuth , ParamError , EndpointError , NotAuthorized , Deprecated ] : raise if ( ( i + 1 ) == NUM_REQUEST_RETRIES ) : raise time . sleep ( 1 ) | Tries to GET data from an endpoint using retries |
22,952 | def _post ( url , headers = { } , data = None , files = None ) : try : response = requests . post ( url , headers = headers , data = data , files = files , verify = VERIFY_SSL ) return _process_response ( response ) except requests . exceptions . RequestException as e : _log_and_raise_exception ( 'Error connecting with foursquare API' , e ) | Tries to POST data to an endpoint |
22,953 | def _process_response ( response ) : try : data = response . json ( ) except ValueError : _log_and_raise_exception ( 'Invalid response' , response . text ) if response . status_code == 200 : return { 'headers' : response . headers , 'data' : data } return _raise_error_from_response ( data ) | Make the request and handle exception processing |
22,954 | def _raise_error_from_response ( data ) : meta = data . get ( 'meta' ) if meta : if meta . get ( 'code' ) in ( 200 , 409 ) : return data exc = error_types . get ( meta . get ( 'errorType' ) ) if exc : raise exc ( meta . get ( 'errorDetail' ) ) else : _log_and_raise_exception ( 'Unknown error. meta' , meta ) else : _log_and_raise_exception ( 'Response format invalid, missing meta property. data' , data ) | Processes the response data |
22,955 | def _foursquare_urlencode ( query , doseq = 0 , safe_chars = "&/,+" ) : if hasattr ( query , "items" ) : query = query . items ( ) else : try : if len ( query ) and not isinstance ( query [ 0 ] , tuple ) : raise TypeError except TypeError : ty , va , tb = sys . exc_info ( ) raise TypeError ( "not a valid non-string sequence or mapping object" ) . with_traceback ( tb ) l = [ ] if not doseq : for k , v in query : k = parse . quote ( _as_utf8 ( k ) , safe = safe_chars ) v = parse . quote ( _as_utf8 ( v ) , safe = safe_chars ) l . append ( k + '=' + v ) else : for k , v in query : k = parse . quote ( _as_utf8 ( k ) , safe = safe_chars ) if isinstance ( v , six . string_types ) : v = parse . quote ( _as_utf8 ( v ) , safe = safe_chars ) l . append ( k + '=' + v ) else : try : len ( v ) except TypeError : v = parse . quote ( _as_utf8 ( v ) , safe = safe_chars ) l . append ( k + '=' + v ) else : for elt in v : l . append ( k + '=' + parse . quote ( _as_utf8 ( elt ) ) ) return '&' . join ( l ) | Gnarly hack because Foursquare doesn t properly handle standard url encoding |
22,956 | def _attach_endpoints ( self ) : for name , endpoint in inspect . getmembers ( self ) : if inspect . isclass ( endpoint ) and issubclass ( endpoint , self . _Endpoint ) and ( endpoint is not self . _Endpoint ) : endpoint_instance = endpoint ( self . base_requester ) setattr ( self , endpoint_instance . endpoint , endpoint_instance ) | Dynamically attach endpoint callables to this client |
22,957 | def register ( self , widget , basename , ** parameters ) : self . registry . append ( ( widget , basename , parameters ) ) | Register a widget URL basename and any optional URL parameters . |
22,958 | def iterator ( self ) : for obj in ( self . execute ( ) . json ( ) . get ( "items" ) or [ ] ) : yield self . api_obj_class ( self . api , obj ) | Execute the API request and return an iterator over the objects . This method does not use the query cache . |
22,959 | def version ( self ) : response = self . get ( version = "" , base = "/version" ) response . raise_for_status ( ) data = response . json ( ) return ( data [ "major" ] , data [ "minor" ] ) | Get Kubernetes API version |
22,960 | def get_kwargs ( self , ** kwargs ) : version = kwargs . pop ( "version" , "v1" ) if version == "v1" : base = kwargs . pop ( "base" , "/api" ) elif "/" in version : base = kwargs . pop ( "base" , "/apis" ) else : if "base" not in kwargs : raise TypeError ( "unknown API version; base kwarg must be specified." ) base = kwargs . pop ( "base" ) bits = [ base , version ] if "namespace" in kwargs : n = kwargs . pop ( "namespace" ) if n is not None : if n : namespace = n else : namespace = self . config . namespace if namespace : bits . extend ( [ "namespaces" , namespace , ] ) url = kwargs . get ( "url" , "" ) if url . startswith ( "/" ) : url = url [ 1 : ] bits . append ( url ) kwargs [ "url" ] = self . url + posixpath . join ( * bits ) return kwargs | Creates a full URL to request based on arguments . |
22,961 | def request ( self , * args , ** kwargs ) : return self . session . request ( * args , ** self . get_kwargs ( ** kwargs ) ) | Makes an API request based on arguments . |
22,962 | def get ( self , * args , ** kwargs ) : return self . session . get ( * args , ** self . get_kwargs ( ** kwargs ) ) | Executes an HTTP GET . |
22,963 | def options ( self , * args , ** kwargs ) : return self . session . options ( * args , ** self . get_kwargs ( ** kwargs ) ) | Executes an HTTP OPTIONS . |
22,964 | def head ( self , * args , ** kwargs ) : return self . session . head ( * args , ** self . get_kwargs ( ** kwargs ) ) | Executes an HTTP HEAD . |
22,965 | def post ( self , * args , ** kwargs ) : return self . session . post ( * args , ** self . get_kwargs ( ** kwargs ) ) | Executes an HTTP POST . |
22,966 | def put ( self , * args , ** kwargs ) : return self . session . put ( * args , ** self . get_kwargs ( ** kwargs ) ) | Executes an HTTP PUT . |
22,967 | def patch ( self , * args , ** kwargs ) : return self . session . patch ( * args , ** self . get_kwargs ( ** kwargs ) ) | Executes an HTTP PATCH . |
22,968 | def delete ( self , * args , ** kwargs ) : return self . session . delete ( * args , ** self . get_kwargs ( ** kwargs ) ) | Executes an HTTP DELETE . |
22,969 | def from_file ( cls , filename , ** kwargs ) : filename = os . path . expanduser ( filename ) if not os . path . isfile ( filename ) : raise exceptions . PyKubeError ( "Configuration file {} not found" . format ( filename ) ) with open ( filename ) as f : doc = yaml . safe_load ( f . read ( ) ) self = cls ( doc , ** kwargs ) self . filename = filename return self | Creates an instance of the KubeConfig class from a kubeconfig file . |
22,970 | def clusters ( self ) : if not hasattr ( self , "_clusters" ) : cs = { } for cr in self . doc [ "clusters" ] : cs [ cr [ "name" ] ] = c = copy . deepcopy ( cr [ "cluster" ] ) if "server" not in c : c [ "server" ] = "http://localhost" BytesOrFile . maybe_set ( c , "certificate-authority" ) self . _clusters = cs return self . _clusters | Returns known clusters by exposing as a read - only property . |
22,971 | def users ( self ) : if not hasattr ( self , "_users" ) : us = { } if "users" in self . doc : for ur in self . doc [ "users" ] : us [ ur [ "name" ] ] = u = copy . deepcopy ( ur [ "user" ] ) BytesOrFile . maybe_set ( u , "client-certificate" ) BytesOrFile . maybe_set ( u , "client-key" ) self . _users = us return self . _users | Returns known users by exposing as a read - only property . |
22,972 | def contexts ( self ) : if not hasattr ( self , "_contexts" ) : cs = { } for cr in self . doc [ "contexts" ] : cs [ cr [ "name" ] ] = copy . deepcopy ( cr [ "context" ] ) self . _contexts = cs return self . _contexts | Returns known contexts by exposing as a read - only property . |
22,973 | def user ( self ) : return self . users . get ( self . contexts [ self . current_context ] . get ( "user" , "" ) , { } ) | Returns the current user set by current context |
22,974 | def bytes ( self ) : if self . _filename : with open ( self . _filename , "rb" ) as f : return f . read ( ) else : return self . _bytes | Returns the provided data as bytes . |
22,975 | def filename ( self ) : if self . _filename : return self . _filename else : with tempfile . NamedTemporaryFile ( delete = False ) as f : f . write ( self . _bytes ) return f . name | Returns the provided data as a file location . |
22,976 | def object_factory ( api , api_version , kind ) : resource_list = api . resource_list ( api_version ) resource = next ( ( resource for resource in resource_list [ "resources" ] if resource [ "kind" ] == kind ) , None ) base = NamespacedAPIObject if resource [ "namespaced" ] else APIObject return type ( kind , ( base , ) , { "version" : api_version , "endpoint" : resource [ "name" ] , "kind" : kind } ) | Dynamically builds a Python class for the given Kubernetes object in an API . |
22,977 | def _handle_info ( self , * args , ** kwargs ) : if 'version' in kwargs : self . api_version = kwargs [ 'version' ] print ( "Initialized API with version %s" % self . api_version ) return try : info_code = str ( kwargs [ 'code' ] ) except KeyError : raise FaultyPayloadError ( "_handle_info: %s" % kwargs ) if not info_code . startswith ( '2' ) : raise ValueError ( "Info Code must start with 2! %s" , kwargs ) output_msg = "_handle_info(): %s" % kwargs log . info ( output_msg ) try : self . _code_handlers [ info_code ] ( ) except KeyError : raise UnknownWSSInfo ( output_msg ) | Handles info messages and executed corresponding code |
22,978 | def setup ( app ) : global _is_sphinx _is_sphinx = True app . add_config_value ( 'no_underscore_emphasis' , False , 'env' ) app . add_config_value ( 'm2r_parse_relative_links' , False , 'env' ) app . add_config_value ( 'm2r_anonymous_references' , False , 'env' ) app . add_config_value ( 'm2r_disable_inline_math' , False , 'env' ) app . add_source_parser ( '.md' , M2RParser ) app . add_directive ( 'mdinclude' , MdInclude ) metadata = dict ( version = __version__ , parallel_read_safe = True , parallel_write_safe = True , ) return metadata | When used for sphinx extension . |
22,979 | def link ( self , link , title , text ) : if self . anonymous_references : underscore = '__' else : underscore = '_' if title : return self . _raw_html ( '<a href="{link}" title="{title}">{text}</a>' . format ( link = link , title = title , text = text ) ) if not self . parse_relative_links : return '\ `{text} <{target}>`{underscore}\ ' . format ( target = link , text = text , underscore = underscore ) else : url_info = urlparse ( link ) if url_info . scheme : return '\ `{text} <{target}>`{underscore}\ ' . format ( target = link , text = text , underscore = underscore ) else : link_type = 'doc' anchor = url_info . fragment if url_info . fragment : if url_info . path : anchor = '' else : link_type = 'ref' doc_link = '{doc_name}{anchor}' . format ( doc_name = os . path . splitext ( url_info . path ) [ 0 ] , anchor = anchor ) return '\ :{link_type}:`{text} <{doc_link}>`\ ' . format ( link_type = link_type , doc_link = doc_link , text = text ) | Rendering a given link with content and title . |
22,980 | def events ( url = None , file = None , string_content = None , start = None , end = None , fix_apple = False ) : found_events = [ ] content = None if url : content = ICalDownload ( ) . data_from_url ( url , apple_fix = fix_apple ) if not content and file : content = ICalDownload ( ) . data_from_file ( file , apple_fix = fix_apple ) if not content and string_content : content = ICalDownload ( ) . data_from_string ( string_content , apple_fix = fix_apple ) found_events += parse_events ( content , start = start , end = end ) return found_events | Get all events form the given iCal URL occurring in the given time range . |
22,981 | def request_data ( key , url , file , string_content , start , end , fix_apple ) : data = [ ] try : data += events ( url = url , file = file , string_content = string_content , start = start , end = end , fix_apple = fix_apple ) finally : update_events ( key , data ) request_finished ( key ) | Request data update local data cache and remove this Thread form queue . |
22,982 | def events_async ( key , url = None , file = None , start = None , string_content = None , end = None , fix_apple = False ) : t = Thread ( target = request_data , args = ( key , url , file , string_content , start , end , fix_apple ) ) with event_lock : if key not in threads : threads [ key ] = [ ] threads [ key ] . append ( t ) if not threads [ key ] [ 0 ] . is_alive ( ) : threads [ key ] [ 0 ] . start ( ) | Trigger an asynchronous data request . |
22,983 | def request_finished ( key ) : with event_lock : threads [ key ] = threads [ key ] [ 1 : ] if threads [ key ] : threads [ key ] [ 0 ] . run ( ) | Remove finished Thread from queue . |
22,984 | def data_from_url ( self , url , apple_fix = False ) : if apple_fix : url = apple_url_fix ( url ) _ , content = self . http . request ( url ) if not content : raise ConnectionError ( 'Could not get data from %s!' % url ) return self . decode ( content , apple_fix = apple_fix ) | Download iCal data from URL . |
22,985 | def data_from_file ( self , file , apple_fix = False ) : with open ( file , mode = 'rb' ) as f : content = f . read ( ) if not content : raise IOError ( "File %f is not readable or is empty!" % file ) return self . decode ( content , apple_fix = apple_fix ) | Read iCal data from file . |
22,986 | def decode ( self , content , apple_fix = False ) : content = content . decode ( self . encoding ) content = content . replace ( '\r' , '' ) if apple_fix : content = apple_data_fix ( content ) return content | Decode content using the set charset . |
22,987 | def create_event ( component , tz = UTC ) : event = Event ( ) event . start = normalize ( component . get ( 'dtstart' ) . dt , tz = tz ) if component . get ( 'dtend' ) : event . end = normalize ( component . get ( 'dtend' ) . dt , tz = tz ) elif component . get ( 'duration' ) : event . end = event . start + component . get ( 'duration' ) . dt else : event . end = event . start try : event . summary = str ( component . get ( 'summary' ) ) except UnicodeEncodeError as e : event . summary = str ( component . get ( 'summary' ) . encode ( 'utf-8' ) ) try : event . description = str ( component . get ( 'description' ) ) except UnicodeEncodeError as e : event . description = str ( component . get ( 'description' ) . encode ( 'utf-8' ) ) event . all_day = type ( component . get ( 'dtstart' ) . dt ) is date if component . get ( 'rrule' ) : event . recurring = True try : event . location = str ( component . get ( 'location' ) ) except UnicodeEncodeError as e : event . location = str ( component . get ( 'location' ) . encode ( 'utf-8' ) ) if component . get ( 'attendee' ) : event . attendee = component . get ( 'attendee' ) if type ( event . attendee ) is list : temp = [ ] for a in event . attendee : temp . append ( a . encode ( 'utf-8' ) . decode ( 'ascii' ) ) event . attendee = temp else : event . attendee = event . attendee . encode ( 'utf-8' ) . decode ( 'ascii' ) if component . get ( 'uid' ) : event . uid = component . get ( 'uid' ) . encode ( 'utf-8' ) . decode ( 'ascii' ) if component . get ( 'organizer' ) : event . organizer = component . get ( 'organizer' ) . encode ( 'utf-8' ) . decode ( 'ascii' ) return event | Create an event from its iCal representation . |
22,988 | def normalize ( dt , tz = UTC ) : if type ( dt ) is date : dt = dt + relativedelta ( hour = 0 ) elif type ( dt ) is datetime : pass else : raise ValueError ( "unknown type %s" % type ( dt ) ) if dt . tzinfo : dt = dt . astimezone ( tz ) else : dt = dt . replace ( tzinfo = tz ) return dt | Convert date or datetime to datetime with timezone . |
22,989 | def parse_events ( content , start = None , end = None , default_span = timedelta ( days = 7 ) ) : if not start : start = now ( ) if not end : end = start + default_span if not content : raise ValueError ( 'Content is invalid!' ) calendar = Calendar . from_ical ( content ) for c in calendar . walk ( ) : if c . name == 'VTIMEZONE' : cal_tz = gettz ( str ( c [ 'TZID' ] ) ) break else : cal_tz = UTC start = normalize ( start , cal_tz ) end = normalize ( end , cal_tz ) found = [ ] for component in calendar . walk ( ) : if component . name == "VEVENT" : e = create_event ( component ) if e . recurring : rule = parse_rrule ( component , cal_tz ) dur = e . end - e . start found . extend ( e . copy_to ( dt ) for dt in rule . between ( start - dur , end , inc = True ) ) elif e . end >= start and e . start <= end : found . append ( e ) return found | Query the events occurring in a given time range . |
22,990 | def copy_to ( self , new_start = None , uid = None ) : if not new_start : new_start = self . start if not uid : uid = "%s_%d" % ( self . uid , randint ( 0 , 1000000 ) ) ne = Event ( ) ne . summary = self . summary ne . description = self . description ne . start = new_start if self . end : duration = self . end - self . start ne . end = ( new_start + duration ) ne . all_day = self . all_day ne . recurring = self . recurring ne . location = self . location ne . uid = uid return ne | Create a new event equal to this with new start date . |
22,991 | def fetch_public_key ( repo ) : keyurl = 'https://api.travis-ci.org/repos/{0}/key' . format ( repo ) data = json . loads ( urlopen ( keyurl ) . read ( ) ) if 'key' not in data : errmsg = "Could not find public key for repo: {}.\n" . format ( repo ) errmsg += "Have you already added your GitHub repo to Travis?" raise ValueError ( errmsg ) return data [ 'key' ] | Download RSA public key Travis will use for this repo . |
22,992 | def kill_the_system ( self , warning : str ) : log . critical ( 'Kill reason: ' + warning ) if self . DEBUG : return try : self . mail_this ( warning ) except socket . gaierror : current_time = time . localtime ( ) formatted_time = time . strftime ( '%Y-%m-%d %I:%M:%S%p' , current_time ) with open ( self . config [ 'global' ] [ 'killer_file' ] , 'a' , encoding = 'utf-8' ) as killer_file : killer_file . write ( 'Time: {0}\nInternet is out.\n' 'Failure: {1}\n\n' . format ( formatted_time , warning ) ) | Send an e - mail and then shut the system down quickly . |
22,993 | def get_killer ( args ) : if POSIX : log . debug ( 'Platform: POSIX' ) from killer . killer_posix import KillerPosix return KillerPosix ( config_path = args . config , debug = args . debug ) elif WINDOWS : log . debug ( 'Platform: Windows' ) from killer . killer_windows import KillerWindows return KillerWindows ( config_path = args . config , debug = args . debug ) else : raise NotImplementedError ( "Your platform is not currently supported." "If you would like support to be added, or " "if your platform is supported and this is " "a bug, please open an issue on GitHub!" ) | Returns a KillerBase instance subclassed based on the OS . |
22,994 | def get_devices ( device_type : DeviceType ) -> Iterator [ str ] : for device in BASE_PATH . iterdir ( ) : with open ( str ( Path ( device , 'type' ) ) ) as type_file : if type_file . readline ( ) . strip ( ) == device_type . value : yield device . name | Gets names of power devices of the specified type . |
22,995 | def _get_property ( device_path : Union [ Path , str ] , property_name : str ) -> str : with open ( str ( Path ( device_path , property_name ) ) ) as file : return file . readline ( ) . strip ( ) | Gets the given property for a device . |
22,996 | def get_power_status ( ) -> SystemPowerStatus : get_system_power_status = ctypes . windll . kernel32 . GetSystemPowerStatus get_system_power_status . argtypes = [ ctypes . POINTER ( SystemPowerStatus ) ] get_system_power_status . restype = wintypes . BOOL status = SystemPowerStatus ( ) if not get_system_power_status ( ctypes . pointer ( status ) ) : raise ctypes . WinError ( ) else : return status | Retrieves the power status of the system . |
22,997 | def abilities ( api_key = None , add_headers = None ) : client = ClientMixin ( api_key = api_key ) result = client . request ( 'GET' , endpoint = 'abilities' , add_headers = add_headers , ) return result [ 'abilities' ] | Fetch a list of permission - like strings for this account . |
22,998 | def can ( ability , add_headers = None ) : client = ClientMixin ( api_key = None ) try : client . request ( 'GET' , endpoint = 'abilities/%s' % ability , add_headers = add_headers ) return True except Exception : pass return False | Test whether an ability is allowed . |
22,999 | def set_api_key_from_file ( path , set_global = True ) : with open ( path , 'r+b' ) as f : global api_key api_key = f . read ( ) . strip ( ) return api_key | Set the global api_key from a file path . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.