class config(HasTraits): uuid = traits.Str(desc="UUID") desc = traits.Str(desc="Workflow Description") # Directories working_dir = Directory(mandatory=True, desc="Location of the Nipype working directory") sink_dir = Directory(os.path.abspath('.'), mandatory=True, desc="Location where the BIP will store the results") crash_dir = Directory(mandatory=False, desc="Location to store crash files") surf_dir = Directory(mandatory=True, desc= "Freesurfer subjects directory") save_script_only = traits.Bool(False) # Execution run_using_plugin = Bool(False, usedefault=True, desc="True to run pipeline with plugin, False to run serially") plugin = traits.Enum("PBS", "MultiProc", "SGE", "Condor", usedefault=True, desc="plugin to use, if run_using_plugin=True") plugin_args = traits.Dict({"qsub_args": "-q many"}, usedefault=True, desc='Plugin arguments.') test_mode = Bool(False, mandatory=False, usedefault=True, desc='Affects whether where and if the workflow keeps its \ intermediary files. True to keep intermediary files. ') timeout = traits.Float(14.0) subjects = traits.List(desc="subjects") split_files = traits.List(traits.File(),desc="""list of split files""") # First Level #advanced_options use_advanced_options = Bool(False) advanced_options = traits.Code()
def __init__(self, pipeline, name, is_output=True, input_type=None): in_traitsl = ['inputs', 'exclude'] if is_output: out_traitsl = ['filtered'] else: out_traitsl = [] in_traitsl.append('filtered') in_traits = [] out_traits = [] for tr in in_traitsl: in_traits.append({'name': tr, 'optional': True}) for tr in out_traitsl: out_traits.append({'name': tr, 'optional': True}) super(ExcludeNode, self).__init__(pipeline, name, in_traits, out_traits) if input_type: ptype = input_type else: ptype = traits.Any(traits.Undefined) self.add_trait('inputs', traits.List(ptype, output=False)) self.add_trait('exclude', ptype) self.add_trait('filtered', traits.List(ptype, output=is_output)) self.set_callbacks()
def __init__(self, pipeline, name, input_names=['inputs'], output_names=['output_%d'], input_types=None): in_traits = [] out_traits = [{'name': 'lengths', 'optional': True}] if input_types: ptypes = input_types else: ptypes = [traits.File(traits.Undefined, output=False)] \ * len(input_names) self.input_types = ptypes for tr in input_names: in_traits.append({'name': tr, 'optional': False}) super(MapNode, self).__init__(pipeline, name, in_traits, out_traits) for tr, ptype in zip(input_names, ptypes): self.add_trait(tr, traits.List(ptype, output=False)) self.add_trait( 'lengths', traits.List(traits.Int(), output=True, optional=True, desc='lists lengths')) self.input_names = input_names self.output_names = output_names self.lengths = [0] * len(input_names) self.set_callbacks()
def __init__(self): super(ErrorComputation, self).__init__() self.add_trait('t1mri', traits.File(output=False, desc='MRI scan')) self.add_trait( 'true_graph', traits.File(output=False, desc='corresponding graph manually labeled')) self.add_trait( 'labeled_graphs', traits.List( traits.File(output=False), desc='corresponding set of graphs automatically labeled')) self.add_trait( 'sulci_side_list', traits.List( traits.Str(output=False), desc='list of sulci (e.g. S.C._right) considered to compute the' ' error rates. It is not supposed to contain the labels' ' "unknown", "ventricle_left" and "ventricle_right".')) self.add_trait( 'error_file', traits.File( output=True, desc= 'file (.csv) storing the error rates for each labeled graph'))
def configure_controller(cls): c = Controller() c.add_trait('parameters', traits.List(traits.Str())) c.add_trait('concat_plug', traits.Str()) c.add_trait('outputs', traits.List(traits.Str())) c.add_trait('param_types', traits.List(traits.Str('Str'))) return c
def __init__(self, pipeline, name, is_output=True, input_type=None): in_traitsl = ['inputs', 'fold', 'nfolds'] if is_output: out_traitsl = ['learn_list', 'test_list'] else: out_traitsl = [] in_traitsl += ['learn_list', 'test_list'] in_traits = [] out_traits = [] for tr in in_traitsl: in_traits.append({'name': tr, 'optional': True}) for tr in out_traitsl: out_traits.append({'name': tr, 'optional': True}) super(CVFilterNode, self).__init__(pipeline, name, in_traits, out_traits) if input_type: ptype = input_type else: ptype = traits.Any(traits.Undefined) self.add_trait('inputs', traits.List(ptype, output=False)) self.add_trait('fold', traits.Int()) self.add_trait('nfolds', traits.Int(10)) self.add_trait('learn_list', traits.List(ptype, output=is_output)) self.add_trait('test_list', traits.List(ptype, output=is_output)) self.set_callbacks()
class config(BaseWorkflowConfig): uuid = traits.Str(desc="UUID") # Directories base_dir = Directory(os.path.abspath('.'),mandatory=True, desc='Base directory of data. (Should be subject-independent)') sink_dir = Directory(mandatory=True, desc="Location where the BIP will store the results") # Subjects subjects = traits.List(traits.Str, mandatory=True, usedefault=True, desc="Subject id's. Note: These MUST match the subject id's in the \ Freesurfer directory. For simplicity, the subject id's should \ also match with the location of individual functional files.") fwhm=traits.List(traits.Float()) inputs_template = traits.String('%s/preproc/output/fwhm_%s/*.nii.gz') meanfunc_template = traits.String('%s/preproc/mean/*_mean.nii.gz') fsl_mat_template = traits.String('%s/preproc/bbreg/*.mat') unwarped_brain_template = traits.String('%s/smri/unwarped_brain/*.nii*') affine_transformation_template = traits.String('%s/smri/affine_transformation/*.nii*') warp_field_template = traits.String('%s/smri/warped_field/*.nii*') #Normalization standard_transform_template = traits.File(mandatory=True,desc='Standard template to warp to') standard_warp_field_template = traits.String() standard_affine_transformation_template = traits.String() standard_norm_template = traits.File() standard_warp_field_template = traits.File() standard_affine_transformation_template = traits.File() # Advanced Options use_advanced_options = traits.Bool() advanced_script = traits.Code() # Buttons check_func_datagrabber = Button("Check")
class DataRecordDefinition(T.HasTraits): types = T.List(T.Int) # 0 - UInt, 1 - Int, 2,3 - Float, 7 - string sizeList = T.List(T.Int) positionByteList = T.List(T.Int) positionOffsetList = T.List(T.Int) def addChannel(self, dataType, initialPosition, dataSize): self.types.append(dataType) self.sizeList.append(dataSize) self.positionByteList.append(initialPosition // 8) self.positionOffsetList.append(initialPosition % 8) def getValue(self, record, channelIndex, structFmt): thisByte = self.positionByteList[channelIndex] thisOffset = self.positionOffsetList[channelIndex] thisSize = self.sizeList[channelIndex] if (thisSize < 8): mask = np.sum(2**np.arange(thisSize) << thisOffset) result = struct.unpack('B', record[thisByte])[0] & mask else: result = struct.unpack( structFmt, record[thisByte:(thisByte + thisSize // 8)])[0] return result def parseRecord(self, record): result = [] for i in range(len(self.types)): value = None thisType = self.types[i] thisSize = self.sizeList[i] # Real if (thisType == 2 or thisType == 3): if (thisSize == 32): value = self.getValue(record, i, 'f') elif (thisSize == 64): value = self.getValue(record, i, 'd') # Unsigned integer elif (thisType == 0): if (thisSize == 8): value = self.getValue(record, i, 'B') elif (thisSize == 16): value = self.getValue(record, i, 'H') elif (thisSize == 32): value = self.getValue(record, i, 'I') elif (thisSize < 8): value = self.getValue(record, i, None) # Signed integer elif (thisType == 1): if (thisSize == 8): value = self.getValue(record, i, 'b') elif (thisSize == 16): value = self.getValue(record, i, 'h') elif (thisSize == 32): value = self.getValue(record, i, 'i') elif (thisSize < 8): value = self.getValue(record, i, None) result.append(value) return result
class Geo(tr.HasStrictTraits): eta = tr.List([eta_0, eta_1, eta_2]) R_r = tr.List([sp.sin(eta_0) * eta_0, sp.cos(eta_0 + 1)**2, eta_1]) def F_r(self, *eta_): r = np.array([ re.subs({e: et for e, et in zip(self.eta, eta_)}) for re in self.R_r ], dtype=np.float_) return np.einsum('ij,jk->ki', r[:, np.newaxis], np.identity(3)) M_ra = tr.Property(depends_on='R_r, R_r_items') @tr.cached_property def _get_M_ra(self): return [[sp.diff(r, e) for r in self.R_r] for e in self.eta] def F_m(self, *eta_): return np.array( [[m.subs({e: et for e, et in zip(self.eta, eta_)}) for m in m_a] for m_a in self.M_ra], dtype=np.float_) def orthogonal_base(self, *eta_): m_01 = self.F_m(*eta_) m_2 = np.einsum('...i,...j,ijk->...k', m_01[0, :], m_01[1, :], EPS) m_1a = np.einsum('...i,...j,ijk->...k', m_2, m_01[0, :], EPS) m = np.array([m_01[0, :], m_1a, m_2]) m1 = m / np.sqrt(np.einsum('ij,ij->i', m, m))[:, np.newaxis] return m1 def plot_basis(self, *eta): r = self.F_r(*eta) m = self.orthogonal_base(*eta) rm = r + m mp = np.vstack([r[np.newaxis, ...], rm[np.newaxis, ...]]) mlab.plot3d(mp[:, 0, 0], mp[:, 0, 1], mp[:, 0, 2], color=black, tube_radius=0.01) mlab.plot3d(mp[:, 1, 0], mp[:, 1, 1], mp[:, 1, 2], color=black, tube_radius=0.01) mlab.plot3d(mp[:, 2, 0], mp[:, 2, 1], mp[:, 2, 2], color=black, tube_radius=0.01) mlab.text3d(rm[0, 0], rm[0, 1], rm[0, 2], 'X', color=black, scale=0.1) mlab.text3d(rm[1, 0], rm[1, 1], rm[1, 2], 'Y', color=black, scale=0.1) mlab.text3d(rm[2, 0], rm[2, 1], rm[2, 2], 'Z', color=black, scale=0.1)
class Conjoint(Model): # The imput data for calculation owner_ref = _traits.WeakRef() # design = DataSet() design = _traits.DelegatesTo('owner_ref') design_vars = _traits.List(_traits.Str()) liking = DataSet() # consumers = DataSet() consumers = _traits.DelegatesTo('owner_ref') consumers_vars = _traits.List(_traits.Str()) # Conjoint settings model_struct = _traits.Enum('Struct 1', 'Struct 2', 'Struct 3') # Conjoint calculation state ccs = _traits.Instance(ConjointCalcState, ()) cm = _traits.Instance(ConjointMachine) # depends_on res = _traits.Property( depends_on='design_vars, consumers_vars, model_struct') def _cm_default(self): try: return ConjointMachine() except RNotFoundException: self.ccs.messages = ("Was not able to find and start R.\n" "You have to check the installation of R") self.ccs.edit_traits(kind='livemodal') @_traits.on_trait_change('owner_ref.model_struct') def _struc_altered(self, new): self.model_struct = new @_traits.on_trait_change('owner_ref.sel_design_var') def _des_var_altered(self, new): self.design_vars = new @_traits.on_trait_change('owner_ref.sel_cons_char') def _cons_char_altered(self, new): self.consumers_vars = new @_traits.cached_property def _get_res(self): if not self.cm.run_state: self.cm.run_state = self.ccs model = { 'Struct 1': 1, 'Struct 2': 2, 'Struct 3': 3 }[self.model_struct] self.cm.schedule_calculation(self.design, sorted(self.design_vars), self.liking, model, self.consumers, sorted(self.consumers_vars)) self.ccs.edit_traits(kind='livemodal') return self.cm.get_result()
class Hdf5GroupNode(api.HasTraits): name = api.Str('<unknown>') path = api.Str('<unknown>') parent_path = api.Str('<unknown>') # Can't have recursive traits? Really? # groups = api.List( Hdf5GroupNode ) groups = api.List() arrays = api.List(Hdf5ArrayNode) groups_and_arrays = api.List()
def configure_controller(cls): c = Controller() c.add_trait('input_types', traits.List(traits.Str)) c.add_trait('input_names', traits.List(traits.Str)) c.add_trait('output_names', traits.List(traits.Str)) c.input_names = ['inputs'] c.output_names = ['output_%d'] c.input_types = ['File'] return c
class config(HasTraits): uuid = traits.Str(desc="UUID") desc = traits.Str(desc='Workflow description') # Directories working_dir = Directory(mandatory=True, desc="Location of the Nipype working directory") crash_dir = Directory(mandatory=False, desc="Location to store crash files") sink_dir = Directory(mandatory=False, desc="Location to store BIPS results") surf_dir = Directory(mandatory=True, desc="Freesurfer subjects directory") save_script_only = traits.Bool(False) # Execution run_using_plugin = Bool( False, usedefault=True, desc="True to run pipeline with plugin, False to run serially") plugin = traits.Enum("PBS", "PBSGraph", "MultiProc", "SGE", "Condor", usedefault=True, desc="plugin to use, if run_using_plugin=True") plugin_args = traits.Dict({"qsub_args": "-q many"}, usedefault=True, desc='Plugin arguments.') # Subjects datagrabber = traits.Instance(Data, ()) # Motion Correction do_slicetiming = Bool(True, usedefault=True, desc="Perform slice timing correction") SliceOrder = traits.List(traits.Int) TR = traits.Float(1.0, mandatory=True, desc="TR of functional") motion_correct_node = traits.Enum( 'nipy', 'fsl', 'spm', 'afni', desc="motion correction algorithm to use", usedefault=True, ) use_metadata = traits.Bool(True) order = traits.Enum('motion_slicetime', 'slicetime_motion', use_default=True) loops = traits.List([5], traits.Int(5), usedefault=True) #between_loops = traits.Either("None",traits.List([5]),usedefault=True) speedup = traits.List([5], traits.Int(5), usedefault=True) # Advanced Options use_advanced_options = traits.Bool() advanced_script = traits.Code()
class FilePreviewer(_tui.Handler): _raw_lines = _tr.List(_tr.Str) _unicode_lines = _tr.List(_tr.Unicode) _parsed_data = _tr.List() def init(self, info): self._probe_read(info.object) self._decode_chars(info.object.char_encoding) def object_have_var_names_changed(self, info): preview_table.update_cells = True def object_delimiter_changed(self, info): self._split_table(info.object.delimiter) def _split_table(self, delimiter): preview_matrix = [ line.split(delimiter) for line in self._unicode_lines ] max_cols = 7 for row in preview_matrix: max_cols = min(max_cols, len(row)) self._parsed_data = self._fix_preview_matrix(preview_matrix, max_cols) preview_table.adapter.ncols = max_cols def object_char_encoding_changed(self, info): self._decode_chars(info.object.char_encoding) self._split_table(info.object.delimiter) def _decode_chars(self, encoding): self._unicode_lines = [ line.decode(encoding, errors='replace') for line in self._raw_lines ] def _fix_preview_matrix(self, preview_matrix, length): for i, row in enumerate(preview_matrix): if len(row) < length: preview_matrix[i] += [''] * (length - len(row)) elif len(row) > length: preview_matrix[i] = preview_matrix[i][0:length] return preview_matrix def _probe_read(self, obj, n_lines=100, length=200): lines = [] with open(obj.file_path, 'rU') as fp: for i in range(n_lines): line = fp.readline(length) if not line: break if not ('\r' in line or '\n' in line): fp.readline() logger.debug("linje {}: {}".format(i, line.rstrip('\n'))) lines.append(line.rstrip('\n')) self._raw_lines = lines
class config(BaseWorkflowConfig): uuid = traits.Str(desc="UUID") desc = traits.Str(desc='Workflow description') # Directories base_dir = Directory( os.path.abspath('.'), exists=True, desc='Base directory of data. (Should be subject-independent)') sink_dir = Directory(mandatory=True, desc="Location where the BIP will store the results") field_dir = Directory( exists=True, desc="Base directory of field-map data (Should be subject-independent) \ Set this value to None if you don't want fieldmap distortion correction" ) json_sink = Directory(mandatory=False, desc="Location to store json_files") surf_dir = Directory(mandatory=True, desc="Freesurfer subjects directory") # Subjects subjects = traits.List( traits.Str, mandatory=True, usedefault=True, desc="Subject id's. Note: These MUST match the subject id's in the \ Freesurfer directory. For simplicity, the subject id's should \ also match with the location of individual functional files." ) func_template = traits.String('%s/functional.nii.gz') run_datagrabber_without_submitting = Bool(True, usedefault=True) # Motion Correction do_slicetiming = Bool(True, usedefault=True, desc="Perform slice timing correction") SliceOrder = traits.List(traits.Int) TR = traits.Float(mandatory=True, desc="TR of functional") save_script_only = traits.Bool(False) # Buttons check_func_datagrabber = Button("Check") def _check_func_datagrabber_fired(self): subs = self.subjects for s in subs: if not os.path.exists( os.path.join(self.base_dir, self.func_template % s)): print "ERROR", os.path.join(self.base_dir, self.func_template % s), "does NOT exist!" break else: print os.path.join(self.base_dir, self.func_template % s), "exists!"
class PcaPluginController(PluginController): available_ds = _traits.List() selected_ds = _traits.List() dummy_model_controller = _traits.Instance(PcaController, PcaController(Pca())) # FIXME: I dont know why the initial populating is not handled by # _update_selection_list() def _available_ds_default(self): return self._get_selectable() @_traits.on_trait_change('model:dsc:[dsl_changed,ds_changed]', post_init=False) def _update_selection_list(self, obj, name, new): self.available_ds = self._get_selectable() def _get_selectable(self): return self.model.dsc.get_id_name_map(kind_exclude='Product design') @_traits.on_trait_change('selected_ds') def _selection_made(self, obj, name, old_value, new_value): last = set(old_value) new = set(new_value) removed = last.difference(new) added = new.difference(last) if removed: self.model.remove(list(removed)[0]) elif added: self._make_calculation(list(added)[0]) self.update_tree = True def _make_calculation(self, ds_id): pcads = self.model.dsc[ds_id] if pcads.missing_data: self._show_missing_warning() return calc_model = Pca(id=ds_id, ds=pcads, settings=self.model.calculator) calculation = PcaController(calc_model, win_handle=self.win_handle) self.model.add(calculation) def _show_missing_warning(self): dlg = ErrorMessage() dlg.err_msg = 'This matrix has missing values' dlg.err_val = ( "At the current version of ConsumerCheck PCA does not handle missing values. There are three options to work around this problem:\n" " 1. Impute the missing values with the imputation method of your choice outside ConsumerCheck and re-import the data\n" " 2. Remove the column with the missing values and re-import the data\n" " 3. Remove the row with the missing values and re-import the data" ) dlg.edit_traits(parent=self.win_handle, kind='modal')
class config(BaseWorkflowConfig): uuid = traits.Str(desc="UUID") desc = traits.Str(desc='Workflow description') # Directories base_dir = Directory(os.path.abspath('.'),mandatory=True, desc='Base directory of data. (Should be subject-independent)') sink_dir = Directory(os.path.abspath('.'),mandatory=True, desc="Location where the BIP will store the results") field_dir = Directory(desc="Base directory of field-map data (Should be subject-independent) \ Set this value to None if you don't want fieldmap distortion correction") surf_dir = Directory(mandatory=True, desc= "Freesurfer subjects directory") # Subjects subjects= traits.List(traits.Str, mandatory=True, usedefault=True, desc="Subject id's. Note: These MUST match the subject id's in the \ Freesurfer directory. For simplicity, the subject id's should \ also match with the location of individual functional files.") func_template = traits.String('%s/functional.nii.gz') run_datagrabber_without_submitting = traits.Bool(desc="Run the datagrabber without \ submitting to the cluster") timepoints_to_remove = traits.Int(0,usedefault=True) do_slicetiming = Bool(True, usedefault=True, desc="Perform slice timing correction") SliceOrder = traits.List(traits.Int) order = traits.Enum('motion_slicetime','slicetime_motion',use_default=True) TR = traits.Float(mandatory=True, desc = "TR of functional") motion_correct_node = traits.Enum('nipy','fsl','spm','afni', desc="motion correction algorithm to use", usedefault=True,) csf_prob = traits.File(desc='CSF_prob_map') grey_prob = traits.File(desc='grey_prob_map') white_prob = traits.File(desc='white_prob_map') # Artifact Detection norm_thresh = traits.Float(1, min=0, usedefault=True, desc="norm thresh for art") z_thresh = traits.Float(3, min=0, usedefault=True, desc="z thresh for art") # Smoothing fwhm = traits.Float(6.0,usedefault=True) save_script_only = traits.Bool(False) check_func_datagrabber = Button("Check") def _check_func_datagrabber_fired(self): subs = self.subjects for s in subs: if not os.path.exists(os.path.join(self.base_dir,self.func_template % s)): print "ERROR", os.path.join(self.base_dir,self.func_template % s), "does NOT exist!" break else: print os.path.join(self.base_dir,self.func_template % s), "exists!"
def protect_parameter(self, param, state=True): """ Protect the named parameter. Protecting is not a real lock, it just marks the parameter a list of "protected" parameters. This is typically used to mark values that have been set manually by the user (using the ControllerWidget for instance) and that should not be later modified by automatic parameters tweaking (such as completion systems). Protected parameters are listed in an additional trait, "protected_parameters". If the "state" parameter is False, then we will unprotect it (calling unprotect_parameter()) """ if not state: return self.unprotect_parameter(param) if not self.trait('protected_parameters'): # add a 'protected_parameters' trait bypassing the # Controller.add_trait mechanism (it will not be a "user_trait") HasTraits.add_trait(self, 'protected_parameters', traits.List(traits.Str(), default=[], hidden=True)) #self.locked_parameters = [] protected = set(self.protected_parameters) protected.update([param]) self.protected_parameters = sorted(protected)
class DataGroup(T.HasTraits): channelGroups = T.List(ChannelGroup) numberRecordIds = T.Int def getRepr(self): s = "DataGroup(nuberRecordIds = %d)" % self.numberRecordIds return s def readFromMat(self, f, dataBeginAddress): for channelGroup in self.channelGroups: for channel in channelGroup.channels: channel.data = np.zeros((channelGroup.numberRecords, )) for i in range(channelGroup.numberRecords): recordBegin = dataBeginAddress + i * channelGroup.recordSize f.seek(recordBegin) recordRawData = f.read(channelGroup.recordSize) recordData = channelGroup.dataRecordDefinition.parseRecord( recordRawData) j = 0 for channel in channelGroup.channels: if (channel.conversionFormula != None): channel.data[i] = channel.conversionFormula( recordData[j]) else: channel.data[i] = recordData[j] j += 1
class config(BaseWorkflowConfig): uuid = traits.Str(desc="UUID") desc = traits.Str(desc="Workflow Description") # Directories sink_dir = Directory(os.path.abspath('.'), mandatory=True, desc="Location where the BIP will store the results") surf_dir = Directory(mandatory=True, desc="Freesurfer subjects directory") save_script_only = traits.Bool(False) datagrabber = traits.Instance(Data, ()) projection_stem = traits.Str('-projfrac-avg 0 1 0.1', desc='how to project data onto the surface') out_type = traits.Enum('mat', 'hdf5', desc='mat or hdf5') hdf5_package = traits.Enum('h5py', 'pytables', desc='which hdf5 package to use') target_surf = traits.Enum('fsaverage4', 'fsaverage3', 'fsaverage5', 'fsaverage6', 'fsaverage', 'subject', desc='which average surface to map to') surface_fwhm = traits.List([5], traits.Float(), mandatory=True, usedefault=True, desc="How much to smooth on target surface") roiname = traits.String('amygdala') use_advanced_options = Bool(False) advanced_options = traits.Code()
class config(BaseWorkflowConfig): uuid = traits.Str(desc="UUID") # Directories base_dir = Directory( os.path.abspath('.'), mandatory=True, desc='Base directory of data. (Should be subject-independent)') sink_dir = Directory(mandatory=True, desc="Location where the BIP will store the results") surf_dir = Directory(os.environ['SUBJECTS_DIR'], desc='Freesurfer subjects dir') save_script_only = traits.Bool(False) # Subjects subjects = traits.List( traits.Str, mandatory=True, usedefault=True, desc="Subject id's. Note: These MUST match the subject id's in the \ Freesurfer directory. For simplicity, the subject id's should \ also match with the location of individual functional files." ) # Advanced Options use_advanced_options = traits.Bool() advanced_script = traits.Code()
class config(HasTraits): uuid = traits.Str(desc="UUID") desc = traits.Str(desc='Workflow description') # Directories working_dir = Directory(mandatory=True, desc="Location of the Nipype working directory") sink_dir = Directory(mandatory=True, desc="Location where the BIP will store the results") crash_dir = Directory(mandatory=False, desc="Location to store crash files") # Execution run_using_plugin = Bool(False, usedefault=True, desc="True to run pipeline with plugin, False to run serially") plugin = traits.Enum("PBS", "PBSGraph","MultiProc", "SGE", "Condor", usedefault=True, desc="plugin to use, if run_using_plugin=True") plugin_args = traits.Dict({"qsub_args": "-q many"}, usedefault=True, desc='Plugin arguments.') test_mode = Bool(False, mandatory=False, usedefault=True, desc='Affects whether where and if the workflow keeps its \ intermediary files. True to keep intermediary files. ') # Subjects subjects= traits.List(traits.Str, mandatory=True, usedefault=True, desc="Subject id's. Note: These MUST match the subject id's in the \ Freesurfer directory. For simplicity, the subject id's should \ also match with the location of individual functional files.") # Preprocessing info preproc_config = traits.File(desc="preproc json file") #Advanced use_advanced_options = traits.Bool() advanced_script = traits.Code() save_script_only = traits.Bool(False)
class config(HasTraits): # Directories working_dir = Directory(mandatory=True, desc="Location of the Nipype working directory") base_dir = Directory(mandatory=True, desc='Base directory of data. (Should be subject-independent)') sink_dir = Directory(mandatory=True, desc="Location where the BIP will store the results") crash_dir = Directory(mandatory=False, desc="Location to store crash files") # Execution run_using_plugin = Bool(False, usedefault=True, desc="True to run pipeline with plugin, False to run serially") plugin = traits.Enum("PBS", "PBSGraph","MultiProc", "SGE", "Condor", usedefault=True, desc="plugin to use, if run_using_plugin=True") plugin_args = traits.Dict({"qsub_args": "-q many"}, usedefault=True, desc='Plugin arguments.') test_mode = Bool(False, mandatory=False, usedefault=True, desc='Affects whether where and if the workflow keeps its \ intermediary files. True to keep intermediary files. ') timeout = traits.Float(14.0) #Subjects subjects= traits.List(traits.Str, mandatory=True, usedefault=True, desc="Subject id's. Bips expects dicoms to be organized by subject id's") dicom_dir_template = traits.String('%s/dicoms/') #Conversion Options embed_meta = traits.Bool(True) info_only = traits.Bool(True) no_moco = traits.Bool(False,desc="only convert non-moco files") use_heuristic = traits.Bool(False) heuristic_file = traits.File(desc="heuristic file")
class CommitInfo(tr.HasStrictTraits): hash = tr.Str parents = tr.List(tr.This) children = tr.Set(tr.This) diff = tr.Either(None, tr.CLong) gitdiff = tr.Either(None, tr.CLong)
def checked_trait(trait): """ Check the trait and build a new one if needed. This function mainly checks the default value of the given trait, and tests in some ways whether it is valid ot not. If not, a new trait is created to replace it. For now it just checks that lists with a non-null minlen will actually get a default value which is a list with this minimum size. Otherwise it causes exceptions in the traits notification system at some point. Parameters ---------- trait: Trait instance to be checked Returns ------- new_trait: Trait instance the returned trait may be the input one (trait), or a new one if it had to be modified. """ ut = getattr(trait, 'trait_type', trait) if isinstance(ut, traits.List): if ut.minlen != 0 and (not isinstance(ut.default, list) or len(ut.default) < ut.minlen): # default value is not OK, we have to build another one if isinstance(ut.default, list): default = list(ut.default) else: default = [] default += [ut.item_trait.default] * (ut.minlen - len(default)) trait = traits.List(ut.item_trait, default, minlen = ut.minlen, maxlen=ut.maxlen) return trait
class Model(BMCSTreeNode): '''Contains the primary unknowns variables U_k ''' tstep_type = tr.Type(TStep) tloop_type = tr.Type(TLoop) hist_type = tr.Type(Hist) sim_type = tr.Type(SimControler) tstep = tr.Property(depends_on='tstep_type') @tr.cached_property def _get_tstep(self): return self.tstep_type(model=self) tloop = tr.Property(depends_on='tloop_type') @tr.cached_property def _get_tloop(self): return self.tloop_type(tstep=self.tstep) hist = tr.Property(depends_on='hist_type') @tr.cached_property def _get_hist(self): return self.hist_type(model=self) sim = tr.Property(depends_on='sim_type') @tr.cached_property def _get_sim(self): return self.sim_type(model=self) bc = tr.List(tr.Callable) U_shape = tr.Tuple(1,) def init_state(self): self.U_k = np.zeros(self.U_shape, dtype=np.float) self.U_n = np.copy(self.U_n) self.hist.init_state() def get_plot_sheet(self): return U_k = tr.Array(np.float_, TRIAL_STATE=True) U_n = tr.Array(np.float_, FUND_STATE=True) S = tr.Dict(tr.Str, tr.Array(np.float), STATE=True) F = tr.Property(depends_on='+TRIAL_STATE,+INPUT') @tr.cached_property def _get_F(self): raise NotImplemented d_F_U = tr.Property(depends_on='+TRIAL_STATE,+INPUT') @tr.cached_property def _get_d_F_U(self): raise NotImplemented
def __init__(self): super(PatternSnipeLabeling, self).__init__() self.add_trait( 'graphs', traits.List(traits.File(output=False), desc='graphs to classify')) self.add_trait( 'traindata_file', traits.File(output=False, desc='file (.json) storing the data extracted' ' from the training base graphs')) self.add_trait( 'param_file', traits.File(output=False, desc='file (.json) storing the hyperparameters' ' (OPM number, patch sizes)')) self.add_trait( 'num_cpu', traits.Int( 1, output=False, optional=True, desc='number of processes that can be used to parallel the' ' calculations')) self.add_trait( 'result_file', traits.File(output=True, desc='file (.csv) with predicted class (y_pred)' ' for each of the input graphs'))
class TreeElement(_traits.HasTraits): '''Represent a calculation (analysis) in the Individual Difference methods ensembe ''' name = _traits.Str() calcc = _traits.WeakRef() plots_act = _traits.List(DiffWindowLauncher) def _plots_act_default(self): acts = [ ("X Scores", 'plsr_x_scores_plot'), ("X & Y correlation loadings", 'plsr_corr_loadings_plot'), ("X Loadings", 'plsr_x_loadings_plot'), ("Y loadings", 'plsr_y_loadings_plot'), ("Explained variance in X", 'plsr_x_expl_var_plot'), ("Explained variance in Y", 'plsr_y_expl_var_plot'), ] return [ DiffWindowLauncher( node_name=nn, plot_func_name=fn, owner_ref=self, loop_name='plots_act', ) for nn, fn in acts ]
def get_attribute_values(self): ''' Get attributes Controller associated to a process Returns ------- attributes: Controller ''' t = self.trait('capsul_attributes') if t is None: try: pattributes = ProcessCompletionEngine.get_completion_engine( self.process.process).get_attribute_values() except AttributeError: # ProcessCompletionEngine not implemented for this process: # no completion return schemas = self._get_schemas() attributes = ProcessAttributes(self.process, schemas) self.add_trait('capsul_attributes', ControllerTrait(Controller())) self.capsul_attributes = attributes iter_attrib = self.get_iterated_attributes() for attrib, trait in six.iteritems(pattributes.user_traits()): if attrib not in iter_attrib: attributes.add_trait(attrib, trait) for attrib in iter_attrib: trait = pattributes.trait(attrib) if trait is not None: attributes.add_trait( attrib, traits.List(trait, output=trait.output)) value = getattr(pattributes, attrib, None) if value is not None and value is not traits.Undefined: setattr(attributes, attrib, [value]) return self.capsul_attributes
class FileSelectedFrame(ta.HasTraits): """ Frame for current files selected """ file_list = ta.List(ta.Str, []) Add_File = ta.Button() Add_Folder = ta.Button() Undo_Add = ta.Button() view = tua.View(tua.Item('file_list'), tua.Item('Add_File', show_label=False), tua.Item('Add_Folder', show_label=False), tua.Item('Undo_Add', show_label=False), resizable=True) def _Add_File_fired(self): global select_files self.file_list.append(select_files.file_name) def _Add_Folder_fired(self): global select_files self.file_list += GetAllPDF(select_files.file_directory) def _Undo_Add_fired(self): del self.file_list[-1]