class RandomizeLabels(capsul.api.Process):
    """Randomize the labels of an image with consecutive labels"""

    input = File(
        Undefined, output=False, allowed_extensions=VOLUME_EXTENSIONS,
        desc="input label image")

    output = File(
        Undefined, output=True, allowed_extensions=VOLUME_EXTENSIONS,
        desc="output label image")

    def get_commandline(self):
        # bv_env automatically launches the command through Python on Windows
        return [
            "bv_env",
            "ylRandomizeLabels",
            self.input,
            self.output
        ]
class Relabel(capsul.api.Process):
    """Assign new consecutive labels to an existing label image"""

    input = File(
        Undefined, output=False, allowed_extensions=VOLUME_EXTENSIONS,
        desc="input label image")

    output = File(
        Undefined, output=True, allowed_extensions=VOLUME_EXTENSIONS,
        desc="output label image")

    def get_commandline(self):
        # bv_env automatically launches the command through Python on Windows
        return [
            "bv_env",
            "ylRelabel",
            self.input,
            self.output
        ]
class SourceFile(HasTraits):

    # The search object this source file is associated with:
    live_search = Instance(LiveSearch)

    # The full path and file name of the source file:
    full_name = File()

    # The base file name of the source file:
    base_name = Property  # Str

    # The portion of the file path beyond the root search path:
    ext_path = Property  # Str

    # The contents of the source file:
    contents = Property  # List( Str )

    # The list of matches for the current search criteria:
    matches = Property  # List( Str )

    #-- Property Implementations ---------------------------------------------

    @property_depends_on('full_name')
    def _get_base_name(self):
        return basename(self.full_name)

    @property_depends_on('full_name')
    def _get_ext_path(self):
        return dirname(self.full_name)[len(self.live_search.root):]

    @property_depends_on('full_name')
    def _get_contents(self):
        try:
            with open(self.full_name, 'rU', encoding='utf8') as fh:
                contents = fh.readlines()
                return contents
        except Exception:
            return ''

    @property_depends_on('full_name, live_search.[search, case_sensitive]')
    def _get_matches(self):
        search = self.live_search.search
        if search == '':
            return []

        case_sensitive = self.live_search.case_sensitive
        if case_sensitive:
            return ['%5d: %s' % ((i + 1), line.strip())
                    for i, line in enumerate(self.contents)
                    if line.find(search) >= 0]

        search = search.lower()
        return ['%5d: %s' % ((i + 1), line.strip())
                for i, line in enumerate(self.contents)
                if line.lower().find(search) >= 0]
Exemple #4
0
class bk_mat_import( time_data_import ):
    """
    Import of BK pulse matlab data.
    """

    #: Name of the mat file to import
    from_file = File(filter = ['*.mat'], 
        desc = "name of the BK pulse mat file to import")

    traits_view = View(
        ['from_file', 
            '|[Import]'
        ], 
        title = 'Time data', 
        buttons = OKCancelButtons
                    )

    def get_data (self, td):
        """
        Main work is done here: imports the data from pulse .mat file into
        time_data object 'td' and saves also a `*.h5` file so this import
        need not be performed every time the data is needed.
        """
        if not path.isfile(self.from_file):
            # no file there
            time_data_import.get_data(self, td)
            return
        #import data
        from scipy.io import loadmat
        m = loadmat(self.from_file)
        fh = m['File_Header']
        numchannels = int(fh.NumberOfChannels)
        l = int(fh.NumberOfSamplesPerChannel)
        sample_freq = float(fh.SampleFrequency.replace(', ', '.'))
        data = empty((l, numchannels), 'f')
        for i in range(numchannels):
            # map SignalName "Point xx" to channel xx-1
            ii = int(m["Channel_%i_Header" % (i+1)].SignalName[-2:])-1
            data[:, ii] = m["Channel_%i_Data" % (i+1)]
        name = td.name
        if name == "":
            name = path.join(td_dir, \
                path.splitext(path.basename(self.from_file))[0]+'.h5')
        else:
            if td.h5f !=  None:
                td.h5f.close()
        # TODO problems with already open h5 files from other instances
        f5h = tables.open_file(name, mode = 'w')
        ac = f5h.create_earray(f5h.root, 'time_data', \
            tables.atom.Float32Atom(), (0, numchannels))
        ac.set_attr('sample_freq', sample_freq)
        ac.append(data)
        f5h.close()
        td.name = name
        td.load_data()
Exemple #5
0
class datx_d_file(HasPrivateTraits):
    """
    Helper class for import of `*.datx` data, represents
    datx data file.
    """
    # File name
    name = File(filter = ['*.datx'], 
        desc = "name of datx data file")

    # File object
    f = Any()

    # Properties
    data_offset = Int()
    channel_count = Int()
    num_samples_per_block = Int()
    bytes_per_sample = Int()
    block_size = Property()

    # Number of blocks to read in one pull
    blocks = Int()
    # The actual block data
    data = CArray()

    def _get_block_size( self ):
        return self.channel_count*self.num_samples_per_block*\
                self.bytes_per_sample

    def get_next_blocks( self ):
        """ pulls next blocks """
        s = self.f.read(self.blocks*self.block_size)
        ls = len(s)
        if ls == 0:
            return -1
        bl_no = ls/self.block_size
        self.data = fromstring(s, dtype = 'Int16').reshape((bl_no, \
            self.channel_count, self.num_samples_per_block)).swapaxes(0, \
            1).reshape((self.channel_count, bl_no*self.num_samples_per_block))

    def __init__(self, name, blocks = 128):
        self.name = name
        self.f = open(self.name, 'rb')
        s = self.f.read(32)
        # header
        s0 = struct.unpack('IIIIIIHHf', s)        
        # Getting information about Properties of data-file 
        # 3 = Offset to data 4 = channel count 
        # 5 = number of samples per block 6 = bytes per sample
        self.data_offset = s0[3]
        self.channel_count = s0[4]
        self.num_samples_per_block = s0[5]
        self.bytes_per_sample = s0[6]
        self.blocks = blocks
        self.f.seek(self.data_offset)
Exemple #6
0
class ImageModel(HasStrictTraits):
    """A model object holding an image stored in an array.

    This has methods for basic transformation of the image, as well as an
    example of a more complex denoising filter using scikits image.
    """

    #: The path to the image file.
    image_path = File('~')

    #: The RGB(A) bytes of the image
    data = ImageArray()

    def load_image(self):
        try:
            self.data = imread(self.image_path)
        except Exception:
            self.data = blank_image

    def rotate(self, direction):
        """Rotate the image clockwise or anticlockwise."""
        if direction == "clockwise":
            self.data = np.rot90(self.data, axes=(1, 0))
        else:
            self.data = np.rot90(self.data, axes=(0, 1))

    def flip(self, direction):
        """Flip the image horizontally or vertically."""
        if direction == "vertical":
            self.data = np.flipud(self.data)
        else:
            self.data = np.fliplr(self.data)

    def denoise(self):
        """Do denoising with scikit image."""
        data = img_as_float(self.data)
        sigma_est = np.mean(estimate_sigma(data, channel_axis=-1))
        new_data = denoise_nl_means(
            data,
            h=0.8 * sigma_est,
            sigma=sigma_est,
            fast_mode=True,
            patch_size=5,
            patch_distance=6,
            channel_axis=-1,
        )
        self.data = img_as_ubyte(new_data)

    @observe('image_path')
    def _update_image(self, event):
        self.load_image()

    def _data_default(self):
        return blank_image
Exemple #7
0
 def __init__(self, study_config, configuration):
     super(AFNIConfig, self).__init__(study_config, configuration)
     self.study_config.add_trait('afni_path', File(
         Undefined,
         output=False,
         desc='Parameter to specify the AFNI path', groups=['afni']))
     self.study_config.add_trait('use_afni', Bool(
         Undefined,
         output=False,
         desc='Parameter to tell that we need to configure AFNI',
         groups=['afni']))
class EuclideanAdvectionAlongGradient(capsul.api.Process):
    """Measure the Euclidean length of an advection path."""

    domain = File(
        Undefined, output=False, allowed_extensions=VOLUME_EXTENSIONS,
        desc="mask of the calculation domain: one inside, zero outside")
    grad_field = File(
        Undefined, output=False, allowed_extensions=VOLUME_EXTENSIONS,
        desc="scalar field whose gradient is to be advected along")
    step_size = Float(
        0.03, output=False, optional=True,
        desc="size of the advection step (millimetres)")
    upfield = Bool(
        False, optional=False,
        desc="Direction of advection (upfield if True, downfield if False)")
    max_dist = Float(
        6, output=False, optional=True,
        desc="maximum advection distance (millimetres)")
    domain_type = Enum(
        "interpolated", "boolean", output=False, optional=True,
        desc="interpolation type for the domain")
    verbosity = Int(1, output=False, optional=True, desc="Verbosity level")

    output_length = File(
        Undefined, output=True, allowed_extensions=VOLUME_EXTENSIONS,
        desc="output volume containing the length of the advection path")

    def get_commandline(self):
        command_step_size = ((-self.step_size) if self.upfield
                             else self.step_size)
        args = [
            "bv_env",  # needed to set DYLD_* in environment on Mac OS 10.11+
            "ylAdvectEuclidean",
            "--domain", self.domain,
            "--grad-field", self.grad_field,
            "--step-size", repr(command_step_size),
            "--max-dist", repr(self.max_dist),
            "--domain-type", self.domain_type,
            "--verbose", str(self.verbosity),
            "--output-length", self.output_length]
        return args
Exemple #9
0
class DummyProcess2(Process):
    """ A dummy process.
    """
    f1 = Float(output=False, optional=False, desc="a float")
    f2 = Float(output=False, optional=False, desc="a float")
    output_file = File(output=True,
                       optional=False,
                       input_filename=True,
                       desc="an output file")

    def _run_process(self):
        open(self.output_file, 'w').write(str(self.f1 * self.f2))
Exemple #10
0
class BinarizeCortex(capsul.api.Process):
    """Extract a binary image (0/1) of the cortex"""

    classif = File(
        Undefined,
        output=False,
        allowed_extensions=VOLUME_EXTENSIONS,
        desc="classification image of the cortex (100 inside, 0 in CSF, "
        "200 in white matter)")

    output_image = File(
        Undefined,
        output=True,
        allowed_extensions=VOLUME_EXTENSIONS,
        desc="binary image of the cortex (1 in the cortex, 0 elsewhere)")

    def get_commandline(self):
        return [
            "AimsThreshold", "--verbose", "0", "-b", "--fg", "1", "-m", "eq",
            "-t", "100", "--input", self.classif, "--output", self.output_image
        ]
Exemple #11
0
 def __init__(self, study_config, configuration):
     super(MatlabConfig, self).__init__(study_config, configuration)
     self.study_config.add_trait(
         'matlab_exec',
         File(Undefined,
              output=False,
              desc='Matlab command path',
              exists=True))
     self.study_config.add_trait(
         "use_matlab",
         Bool(Undefined,
              desc="If True, Matlab configuration is set up on startup"))
class SolverPreferenceGroup(BasePreferenceGroup):
    """ Storage for solver related preferences.
    """
    #: Path (or name) to the solver executable to use
    solver_binary_path = File

    # Folder containing the solver input files
    input_file_location = Directory

    #: Number of max worker processes to run simulation grids on. 0=all CPUs.
    executor_num_worker = Int

    #: Clean up solver input files when exiting?
    auto_delete_solver_files_on_exit = Bool(True)

    #: CADET allows to run 1 simulation using multiple openMP threads
    cadet_num_threads = PositiveInt(1, exclude_low=True)

    #: Wrap solver execution with SLURM scheduling?
    use_slurm_scheduler = Bool

    #: Slurm scheduler batch run command
    slurm_binary = File("sbatch")

    #: SLURM Partition to run the solver on
    slurm_partition = Str

    #: Name of the SLURM jobs submitted when running the solver
    slurm_job_name = Str("slurm_chrom_solver")

    def _attrs_to_store_default(self):
        return [
            "input_file_location", "auto_delete_solver_files_on_exit",
            "executor_num_worker", "cadet_num_threads", "solver_binary_path",
            "use_slurm_scheduler", "slurm_partition", "slurm_job_name"
        ]

    def _input_file_location_default(self):
        """ Returns the directory to create datasource files in.
        """
        return join(get_app_folder(), CADET_INPUT_DIRNAME)

    def _solver_binary_path_default(self):
        if IS_WINDOWS:
            return 'cadet-cs.exe'
        elif IS_OSX or IS_LINUX:
            return 'cadet-cs'
        else:
            msg = "Platform {} currently not supported.".format(sys.platform)
            raise NotImplementedError(msg)

    def _executor_num_worker_default(self):
        return multiprocessing.cpu_count()
Exemple #13
0
 def __init__(self, study_config, configuration):
     super(FSLConfig, self).__init__(study_config, configuration)
     self.study_config.add_trait('fsl_config', File(
         Undefined,
         output=False,
         desc='Parameter to specify the fsl.sh path'))
     self.study_config.add_trait('fsl_prefix', String(Undefined,
         desc='Prefix to add to FSL commands'))
     self.study_config.add_trait('use_fsl', Bool(
         Undefined,
         output=False,
         desc='Parameter to tell that we need to configure FSL'))
Exemple #14
0
class MergeCortexColumnRegions(capsul.api.Process):
    """Aggregate over-segmented cortical traverses."""

    input_traverses = File(
        Undefined, output=False, allowed_extensions=VOLUME_EXTENSIONS,
        desc="input label volume")
    proj_csf = File(
        Undefined, output=False, optional=True,
        allowed_extensions=VOLUME_EXTENSIONS,
        desc="projected coordinates of the CSF surface")
    proj_white = File(
        Undefined, output=False, optional=True,
        allowed_extensions=VOLUME_EXTENSIONS,
        desc="projected coordinates of the white surface")
    classif = File(
        Undefined, output=False, allowed_extensions=VOLUME_EXTENSIONS,
        desc="classification image of the cortex (100 inside, 0 in CSF, "
        "200 in white matter)")
    goal_diameter = Float(
        0.5, output=False, optional=True,
        desc="goal region diameter (millimetres)")
    verbosity = Int(2, output=False, optional=True, desc="Verbosity level")

    output = File(
        Undefined, output=True, allowed_extensions=VOLUME_EXTENSIONS,
        desc="output label volume")

    def get_commandline(self):
        args = [
            "bv_env",  # needed to set DYLD_* in environment on Mac OS 10.11+
            "ylMergeCortexColumnRegions",
            "--input", self.input_traverses,
            "--proj-csf", self.proj_csf,
            "--proj-white", self.proj_white,
            "--classif", self.classif,
            "--goal-diameter", repr(self.goal_diameter),
            "--verbose", str(self.verbosity),
            "--output", self.output,
        ]
        return args
Exemple #15
0
class AutofluorescencePluginOp(PluginOpMixin, AutofluorescenceOp):
    handler_factory = Callable(AutofluorescenceHandler)

    channels = List(Str, estimate=True)
    blank_file = File(filter=["*.fcs"], estimate=True)

    @on_trait_change('channels', post_init=True)
    def _channels_changed(self):
        self.changed = (Changed.ESTIMATE, ('channels', self.channels))

    # bits to support the subset editor

    subset_list = List(ISubset, estimate=True)
    subset = Property(Str, depends_on="subset_list.str")

    # MAGIC - returns the value of the "subset" Property, above
    def _get_subset(self):
        return " and ".join(
            [subset.str for subset in self.subset_list if subset.str])

    @on_trait_change('subset_list.str', post_init=True)
    def _subset_changed(self, obj, name, old, new):
        self.changed = (Changed.ESTIMATE, ('subset_list', self.subset_list))

    def default_view(self, **kwargs):
        return AutofluorescencePluginView(op=self, **kwargs)

    def estimate(self, experiment):
        if not self.subset:
            warnings.warn(
                "Are you sure you don't want to specify a subset "
                "used to estimate the model?", util.CytoflowOpWarning)

        AutofluorescenceOp.estimate(self, experiment, subset=self.subset)
        self.changed = (Changed.ESTIMATE_RESULT, self)

    def clear_estimate(self):
        self._af_median.clear()
        self._af_stdev.clear()
        self.changed = (Changed.ESTIMATE_RESULT, self)

    def should_apply(self, changed):
        if changed == Changed.PREV_RESULT or changed == Changed.ESTIMATE_RESULT:
            return True

        return False

    def should_clear_estimate(self, changed):
        if changed == Changed.ESTIMATE:
            return True

        return False
Exemple #16
0
class SurfaceSource(HasTraits):
    """Expose points and tris of a file storing a surface.

    Parameters
    ----------
    file : File
        Path to a *-bem.fif file or a surface containing a Freesurfer surface.

    Attributes
    ----------
    pts : Array, shape = (n_pts, 3)
        Point coordinates.
    tris : Array, shape = (n_tri, 3)
        Triangles.

    Notes
    -----
    tri is always updated after pts, so in case downstream objects depend on
    both, they should sync to a change in tris.
    """

    file = File(exists=True, filter=['*.fif', '*.*'])
    points = Array(shape=(None, 3), value=np.empty((0, 3)))
    norms = Array
    tris = Array(shape=(None, 3), value=np.empty((0, 3)))

    @on_trait_change('file')
    def read_file(self):
        """Read the file."""
        if op.exists(self.file):
            if self.file.endswith('.fif'):
                bem = read_bem_surfaces(self.file, verbose=False)[0]
                self.points = bem['rr']
                self.norms = bem['nn']
                self.tris = bem['tris']
            else:
                try:
                    points, tris = read_surface(self.file)
                    points /= 1e3
                    self.points = points
                    self.norms = []
                    self.tris = tris
                except Exception:
                    error(message="Error loading surface from %s (see "
                          "Terminal for details).",
                          title="Error Loading Surface")
                    self.reset_traits(['file'])
                    raise
        else:
            self.points = np.empty((0, 3))
            self.norms = np.empty((0, 3))
            self.tris = np.empty((0, 3))
Exemple #17
0
class MergeImagesSameValues(capsul.api.Process):
    """Merge values into an image using a mask image."""

    input_image = File(Undefined,
                       output=False,
                       allowed_extensions=VOLUME_EXTENSIONS,
                       desc="input image")
    mask_image = File(Undefined,
                      output=False,
                      allowed_extensions=VOLUME_EXTENSIONS,
                      desc="mask image (must have an integer voxel type)")

    output_image = File(Undefined,
                        output=True,
                        allowed_extensions=VOLUME_EXTENSIONS,
                        desc="output image")

    def get_commandline(self):
        return [
            "AimsMerge", "--mode", "sv", "--input", self.input_image, "--Mask",
            self.mask_image, "--output", self.output_image
        ]
Exemple #18
0
class LabelEachVoxel(capsul.api.Process):
    """Assign a unique label to each voxel of a mask"""

    input_image = File(
        Undefined, output=False, allowed_extensions=VOLUME_EXTENSIONS,
        desc="input mask")
    first_label = Int(
        1, output=False, optional=True,
        desc="assign labels starting with this value")

    output_image = File(
        Undefined, output=True, allowed_extensions=VOLUME_EXTENSIONS,
        desc="output label volume with S32 datatype")

    def get_commandline(self):
        return [
            "bv_env",  # needed to set DYLD_* in environment on Mac OS 10.11+
            "ylLabelEachVoxel",
            "--first-label", str(self.first_label),
            "--input", self.input_image,
            "--output", self.output_image
        ]
Exemple #19
0
class MovieTheater(HasTraits):
    url = File(filename)

    state = PlayerState()
    duration = Float()
    position = Range(low=0.0, high='duration')
    error = Str()
    status = MediaStatus()
    buffer = Range(0, 100)
    muted = Bool(True)
    volume = Range(0.0, 100.0)
    playback_rate = Float(1.0)
    image_func = Callable()
Exemple #20
0
class GSODDataPlotterView(HasTraits):
    """ Application of the zoom tool to the GSOD plotting tool.
    Load a HDF file containing one or more timeseries and plot the entire data inside.
    The zoom tool allows to explore a subset of it. The legend allows to (de)select some
    timeseries.
    """
    data_file = File()
    ts_data = Dict()
    ts_plot = Instance(ToolbarPlot)

    traits_view = View(
            VGroup(Item('data_file', style = 'simple', label="HDF file to load"), 
                   Item('ts_plot', editor=ComponentEditor(size=(800, 600)), 
                        show_label=False),), 
            title='Chaco Plot with file loader and legend highlighter',
            width=900, height=800, resizable=True)

    def __init__(self, pandas_list = [], array_dict = {}, *args, **kw):
        """ If a (list of) pandas or a dict of arrays is passed, load them up. 
        """
        ts_data = {}
        super(GSODDataPlotterView, self).__init__(*args, **kw)
        if not isinstance(pandas_list, list):
            pandas_list = [pandas_list]
        if pandas_list:
            ts_data.update(pandas2array_dict(pandas_list))
        if array_dict:
            ts_data.update(ts_dict)
        self.ts_data = ts_data # Now trigger the plot redraw

    def _data_file_changed(self):
       """ Update the data from the HDF5 file.
       """
       self.ts_data = pandas_hdf_to_data_dict(self.data_file)
       assert("index" in self.ts_data)

    def _ts_data_changed(self):
        """ Dataset has changed: update the plot.
        ENH: add the possibility to pass a dict to ArrayPlotData.
        """
        arr_data = ArrayPlotData()
        for k,v in self.ts_data.items():
            arr_data.set_data(k,v)
        self.ts_plot = ToolbarPlot(arr_data)
        for i, k in enumerate([k for k in self.ts_data.keys() if k != "index"]):
            self.ts_plot.plot(("index", k), name = k, color = colors[i % len(colors)])
        if self.data_file:
            self.ts_plot.title = "Time series visualization from %s" % self.data_file
        else:
            self.ts_plot.title = "Time series visualization"
        attach_tools(self.ts_plot)
class Timestamps(VisModule):
    name = Str('Time Stamps')
    file = File(exists=True)
    timing_array = Str
    timing_channels = Str('0')
    time_set = List(TimeStampSet)
    selected_set = Instance(TimeStampSet)
    add_set = Button('Load timestamps')
    pop_set = Button('Remove timestamps')

    def _add_set_fired(self):
        used_colors = set([s.color for s in self.time_set])
        unused_colors = color_cycle - used_colors
        clr = list(unused_colors)[0]
        new_set = TimeStampSet(name='Set ' + str(len(self.time_set) + 1),
                               color=clr,
                               file=self.file,
                               timing_array=self.timing_array,
                               timing_channels=self.timing_channels,
                               parent=self.parent)
        self.time_set.append(new_set)

    def _pop_set_fired(self):
        set = self.selected_set
        set._unload()
        self.selected_set = None
        self.time_set.remove(set)

    def default_traits_view(self):
        from ..data_files import FileHandler
        v = View(
            HGroup(
                VGroup(
                    Group(Label('HDF5 file with timing signal'),
                          UItem('file')),
                    HGroup(
                        Group(
                            Label('Array with timing channel(s)'),
                            UItem('timing_array',
                                  editor=EnumEditor(name='handler.fields'))),
                        Group(
                            Label('Channel(s) with timing signal (comma-sep)'),
                            UItem('timing_channels')))),
                ## Item('is_binary', label='Binary series?'),
                VGroup(UItem('add_set', enabled_when='len(timing_source) > 0'),
                       UItem('pop_set',
                             enabled_when='len(timing_source) > 0')),
                Group(UItem('time_set', editor=tab_editor), show_border=True),
            ),
            handler=FileHandler)
        return v
Exemple #22
0
class TrackLabelSource(HasTraits):
    """ Contains connection ids for streamlines
    """
    # identifying traits
    name = Str("")
    description = Str("")
    parameters = Dict()

    # file paths to data
    numpy_path = File("")
    graphml_path = File("")
    volume_path = File("")
    b0_volume_path = File("")
    qsdr_volume_path = File("")

    scalars = Array

    def load_array(self):
        self.scalars = np.load(os.path.join(self.base_dir,
                                            self.numpy_path)).astype(np.uint64)
        return self.scalars

    @on_trait_change("b0_volume_path")
    def update_params(self):
        if len(self.parameters) == 0:
            self.parameters = get_builtin_atlas_parameters(self.b0_volume_path)
        print self.parameters

    def to_json(self):
        return {
            "name": self.name,
            "description": self.description,
            "parameters": self.parameters,
            "numpy_path": self.numpy_path,
            "graphml_path": self.graphml_path,
            "b0_volume_path": self.b0_volume_path,
            "qsdr_volume_path": self.qsdr_volume_path
        }
Exemple #23
0
class ConnectedComponents(capsul.api.Process):
    """Extract connected components of a labelled volume"""

    input_image = File(
        Undefined, output=False, allowed_extensions=VOLUME_EXTENSIONS,
        desc="input label image")
    connectivity = Enum(
        "26", "4xy", "4xz", "4yz", "6", "8xy", "8xz", "8yz", "18",
        output=False, optional=True,
        desc="connectivity")

    output = File(
        Undefined, output=True, allowed_extensions=VOLUME_EXTENSIONS,
        desc="output labelled connected components volume")

    def get_commandline(self):
        return [
            "bv_env",  # needed to set DYLD_* in environment on Mac OS 10.11+
            "AimsConnectComp",
            "--input", self.input_image,
            "--output", self.output,
            "--connectivity", self.connectivity,
        ]
Exemple #24
0
class RelabelConjunction(capsul.api.Process):
    """Assign new labels to voxels that have the same pair of labels"""

    labels1 = File(Undefined,
                   output=False,
                   allowed_extensions=VOLUME_EXTENSIONS,
                   desc="input label image")
    labels2 = File(Undefined,
                   output=False,
                   allowed_extensions=VOLUME_EXTENSIONS,
                   desc="input label image")

    output = File(Undefined,
                  output=True,
                  allowed_extensions=VOLUME_EXTENSIONS,
                  desc="output label image")

    def get_commandline(self):
        # bv_env automatically launches the command through Python on Windows
        return [
            "bv_env", "ylRelabelConjunction", self.labels1, self.labels2,
            self.output
        ]
Exemple #25
0
class SurfaceSource(HasTraits):
    """Expose points and tris of a file storing a surface.

    Parameters
    ----------
    file : File
        Path to a *-bem.fif file or a surface containing a Freesurfer surface.

    Attributes
    ----------
    pts : Array, shape = (n_pts, 3)
        Point coordinates.
    tris : Array, shape = (n_tri, 3)
        Triangles.

    Notes
    -----
    tri is always updated after pts, so in case downstream objects depend on
    both, they should sync to a change in tris.
    """

    file = File(exists=True, filter=['*.fif', '*.*'])
    surf = Instance(Surf)

    @on_trait_change('file')
    def read_file(self):
        """Read the file."""
        if op.exists(self.file):
            if self.file.endswith('.fif'):
                bem = read_bem_surfaces(self.file, verbose=False)[0]
            else:
                try:
                    bem = read_surface(self.file, return_dict=True)[2]
                    bem['rr'] *= 1e-3
                    complete_surface_info(bem, copy=False)
                except Exception:
                    error(parent=None,
                          message="Error loading surface from %s (see "
                          "Terminal for details)." % self.file,
                          title="Error Loading Surface")
                    self.reset_traits(['file'])
                    raise
            self.surf = Surf(rr=bem['rr'], tris=bem['tris'], nn=bem['nn'])
        else:
            self.surf = self._default_surf()

    def _surf_default(self):
        return Surf(rr=np.empty((0, 3)),
                    tris=np.empty((0, 3), int),
                    nn=np.empty((0, 3)))
Exemple #26
0
    def test_trait(self):
        """ Method to test trait characterisitics: value, type.
        """
        self.assertTrue(is_trait_value_defined(5))
        self.assertFalse(is_trait_value_defined(""))
        self.assertFalse(is_trait_value_defined(None))
        self.assertFalse(is_trait_value_defined(Undefined))

        trait = CTrait(0)
        trait.handler = Float()
        self.assertFalse(is_trait_pathname(trait))
        for handler in [File(), Directory()]:
            trait.handler = handler
            self.assertTrue(is_trait_pathname(trait))
Exemple #27
0
class Laplacian(capsul.api.Process):
    """Solve the Laplacian model in the cortex"""

    classif = File(
        Undefined,
        output=False,
        allowed_extensions=VOLUME_EXTENSIONS,
        desc="classification image of the cortex (100 inside, 0 in CSF, "
        "200 in white matter)")
    precision = Float(
        0.001,
        output=False,
        optional=True,
        desc="target maximum relative error in first-order finite differences")
    typical_cortical_thickness = Float(
        3,
        output=False,
        optional=True,
        desc="typical thickness of the cortex (mm), used for accelerating "
        "convergence")
    verbosity = Int(1, output=False, optional=True, desc="Verbosity level")

    laplace_field = File(
        Undefined,
        output=True,
        allowed_extensions=VOLUME_EXTENSIONS,
        desc="output pseudo-temperature field (from 0 in CSF to 1 in the "
        "white matter)")

    def get_commandline(self):
        return [
            "ylLaplacian", "--classif", self.classif, "--output",
            self.laplace_field, "--precision",
            repr(self.precision), "--typical-cortical-thickness",
            repr(self.typical_cortical_thickness), "--verbose",
            str(self.verbosity)
        ]
Exemple #28
0
class BaseViewer(HasTraits):
    reconstruction = Instance(Component)
    image = Array
    result = Array
    save_file = File(exists=False, auto_set=False, enter_set=True)
    save_button = Button('Save Result as .npy')

    def __init__(self, **kwargs):
        HasTraits.__init__(self, **kwargs)

    def _reconstruction_default(self):
        self.plot_data = ArrayPlotData(original=self.image,
                                       reconstruction=self.result)

        rows, cols = self.image.shape[:2]
        aspect = cols / float(rows)

        old = Plot(self.plot_data)
        old.img_plot('original', colormap=gray, origin='top left')
        old.title = 'Old'
        old.aspect_ratio = aspect

        self.new = Plot(self.plot_data)
        self.new.img_plot('reconstruction', colormap=gray, origin='top left')
        self.new.title = 'New'
        self.new.aspect_ratio = aspect

        container = HPlotContainer(bgcolor='none')
        container.add(old)
        container.add(self.new)

        return container

    def update_plot(self):
        self.plot_data.set_data('reconstruction', self.result)
        self.new.request_redraw()

    def _save_button_changed(self):
        try:
            np.save(self.save_file, self.result)
        except IOError, e:
            message('Could not save file: %s' % str(e))

        try:
            f = open(self.save_file + '.txt', 'w')
            f.write(str(self))
            f.close()
        except IOError:
            message('Could not save file: %s' % str(e))
Exemple #29
0
class td_import( time_data_import ):
    """
    Import of `*.td` data as saved by earlier versions
    """

    #: Name of the comma delimited file to import.
    from_file = File(filter = ['*.td'], 
        desc = "name of the *.td file to import")

    traits_view = View(
        ['from_file', 
            '|[Import]'
        ], 
        title  = 'Time data', 
        buttons = OKCancelButtons
                    )

    def get_data (self, td):
        """
        Main work is done here: imports the data from `*.td` file into
        TimeSamples object `td` and saves also a `*.h5` file so this import
        need not be performed only once.
        """
        if not path.isfile(self.from_file):
            # no file there
            time_data_import.get_data(self, td)
            return
        f = open(self.from_file, 'rb')
        h = pickle.load(f)
        f.close()
        sample_freq = h['sample_freq']
        data = h['data']
        numchannels = data.shape[1]
        name = td.name
        if name == "":
            name = path.join(td_dir, \
                        path.splitext(path.basename(self.from_file))[0]+'.h5')
        else:
            if td.h5f !=  None:
                td.h5f.close()
        # TODO problems with already open h5 files from other instances
        f5h = tables.open_file(name, mode = 'w')
        ac = f5h.create_earray(f5h.root, 'time_data', \
            tables.atom.Float32Atom(), (0, numchannels))
        ac.set_attr('sample_freq', sample_freq)
        ac.append(data)
        f5h.close()
        td.name = name
        td.load_data()
Exemple #30
0
class MarkerPointSource(MarkerPoints):  # noqa: D401
    """MarkerPoints subclass for source files."""

    file = File(filter=mrk_wildcard, exists=True)
    name = Property(Str, depends_on='file')
    dir = Property(Str, depends_on='file')

    use = List(list(range(5)),
               desc="Which points to use for the interpolated "
               "marker.")
    enabled = Property(Bool, depends_on=['points', 'use'])
    clear = Button(desc="Clear the current marker data")
    edit = Button(desc="Edit the marker coordinates manually")

    view = mrk_view_basic

    @cached_property
    def _get_enabled(self):
        return np.any(self.points)

    @cached_property
    def _get_dir(self):
        if self.file:
            return os.path.dirname(self.file)

    @cached_property
    def _get_name(self):
        if self.file:
            return os.path.basename(self.file)

    @on_trait_change('file')
    def load(self, fname):
        if not fname:
            self.reset_traits(['points'])
            return

        try:
            pts = read_mrk(fname)
        except Exception as err:
            error(None, str(err), "Error Reading mrk")
            self.reset_traits(['points'])
        else:
            self.points = pts

    def _clear_fired(self):
        self.reset_traits(['file', 'points', 'use'])

    def _edit_fired(self):
        self.edit_traits(view=mrk_view_edit)