Esempio n. 1
0
def execution(self, context):
    from soma import aims
    graph = aims.read(self.read.fullPath())
    aims.GraphManip.buckets2Volume(graph)
    if self.extract_volume:
        vol = graph[self.extract_volume]
    else:
        atts = [
            x for x in graph.keys()
            if isinstance(graph[x], aims.rc_ptr_Volume_S16)
        ]
        if len(atts) == 0:
            raise RuntimeError(_t_('the ROI graph contains no voxel data'))
        elif len(atts) > 1:
            raise RuntimeError(
                _t_('the ROI graph contains several volumes. '
                    'Select the extract_volume parameter as one in ') + '( ' +
                ', '.join(atts) + ' )')
        vol = graph[atts[0]]
    # handle bounding box which may have cropped the data
    bmin = graph['boundingbox_min']
    bmax = graph['boundingbox_max']
    context.write('vol:', vol)
    context.write('bmin:', bmin, ', bmax:', bmax, ', size:', vol.getSize())
    if bmin[:3] != [0, 0, 0] \
            or bmax[:3] != [x+1 for x in vol.getSize()[:3]]:
        context.write('enlarging')
        # needs expanding in a bigger volume
        vol2 = aims.Volume_S16(bmax[0] + 1, bmax[1] + 1, bmax[2] + 1)
        vol2.fill(0)
        ar = vol2.np
        ar[bmin[0]:bmax[0] + 1, bmin[1]:bmax[1] + 1, bmin[2]:bmax[2] + 1, :] \
            = vol.np

        if self.extract_contours == 'Yes':
            ar_copy = ar.copy()
            for label in [v['roi_label'] for v in graph.vertices()]:
                ind = list(zip(*np.where(ar_copy == label)))
                for i in ind:
                    erase = True
                    for neigh in neighbors(*i):
                        if ar_copy[neigh] != label:
                            erase = False
                    if erase:
                        ar[i] = 0

        vol2.copyHeaderFrom(vol.header())
        aims.write(vol2, self.write.fullPath())
    else:
        # bounding box OK
        aims.write(vol.get(), self.write.fullPath())
    registration.getTransformationManager().copyReferential(
        self.read, self.write)
    if self.removeSource:
        for f in self.read.fullPaths():
            shelltools.rm(f)
Esempio n. 2
0
def execution(self, context):
    from soma import aims
    r = aims.Reader({'Volume': {'S16': 'Graph'}})
    graph = r.read(self.read.fullPath())
    graph['filename_base'] = '*'
    aims.GraphManip.volume2Buckets(graph)
    aims.write(graph, self.write.fullPath())
    registration.getTransformationManager().copyReferential(self.read,
                                                            self.write)
    if self.removeSource:
        for f in self.read.fullPaths():
            shelltools.rm(f)
Esempio n. 3
0
def execution(self, context):

    #Load light objects first
    csd = load(self.csd_model.fullPath())

    dmri_vol = aims.read(self.diffusion_data.fullPath())
    header = dmri_vol.header()
    data = np.asarray(dmri_vol)

    if self.mask is not None:
        mask_vol = aims.read(self.mask.fullPath())
        mask_arr = np.array(mask_vol, copy=True)
        mask = mask_arr[..., 0]
        if data.shape[:-1] != mask.shape:
            raise ValueError(
                'Diffusion data and mask used do not have the same shape')
    else:
        mask = self.mask

    csdfit = csd.fit(data, mask=mask)
    sh_coeff = csdfit.shm_coeff

    sh_coeff_volume = array_to_vol(sh_coeff, header)
    aims.write(sh_coeff_volume, self.fibre_odf_sh_coeff.fullPath())
    transformManager = getTransformationManager()
    transformManager.copyReferential(self.diffusion_data,
                                     self.fibre_odf_sh_coeff)

    pass
def execution(self, context):
    tr = aims.AffineTransformation3d()
    for t in self.MNI_transform_chain:
        ti = aims.read(t.fullPath())
        tr = ti * tr
    #context.write('transform:', tr)
    vol = aims.read(self.volume.fullPath())
    trl = vol.header().get('transformations', [])
    refl = vol.header().get('referentials', [])

    rname = aims.StandardReferentials.mniTemplateReferential()
    if rname in refl:
        trl[refl.index(rname)] = tr.toVector()
    elif len(trl) < 2:
        #else:
        trl.append(tr.toVector())
        refl.append(rname)
    else:
        trl = [list(trl[0]), list(tr.toVector())] \
            + [list(t) for t in list(trl)[1:]]
        refl = [refl[0], rname] + list(refl)[1:]
    # context.write('now:', refl, trl)
    vol.header()['referentials'] = refl
    vol.header()['transformations'] = trl
    context.write('new header:', vol.header())
    aims.write(vol, self.output_volume.fullPath())
    self.output_volume.readAndUpdateMinf()
    tm = registration.getTransformationManager()
    tm.copyReferential(self.volume,
                       self.output_volume,
                       copy_transformations=False)
Esempio n. 5
0
def execution(self, context):
    n_faces = 21
    transformManager = getTransformationManager()
    seeds_referential = transformManager.referential(self.seeds)

    seeds_centers = np.loadtxt(self.seeds.fullPath())
    n_sample = min(len(seeds_centers), self.n_sampling)
    if len(seeds_centers) > self.n_display:
        context.warning(
            "You try to display more than ", str(self.n_display), " seeds. It may causes Memory Error. The first ", str(self.display)," seeds ONLY are displayed in order to prevent crashes")
    radius = np.min(pdist(seeds_centers[:n_sample])) / 2.0
    sphere = aims.SurfaceGenerator.icosphere((0, 0, 0), radius, n_faces)
    vertices = np.array(sphere.vertex())
    triangles = np.array(sphere.polygon())
    seeds_centers = seeds_centers[:min(self.n_display, len(seeds_centers))]
    new_vertices, new_triangles = quick_replicate_meshes(seeds_centers, vertices, triangles)
    mesh = vertices_and_faces_to_mesh(new_vertices, new_triangles)

    a = anatomist.Anatomist()
    w3d = a.createWindow("3D")

    A_graph = a.toAObject(mesh)
    #yellow colors for the seeds (different form Red, Green , Blue so that they appears with orientation coded fibers
    material = a.Material(diffuse=[1, 1, 0, 1])
    A_graph.setMaterial(material)
    A_graph.assignReferential(seeds_referential)
    w3d.addObjects(A_graph)
    return [w3d, A_graph]
Esempio n. 6
0
def execution(self, context):

    img = []
    col = 0
    for selfImg in self.images:
        if col == 0:
            imgcol = []
            img.append(imgcol)
        imgcol.append(selfImg)
        col += 1
        if col == len(self.colTitles):
            col = 0

    objs = displayTitledGrid(registration.getTransformationManager(),
                             None,
                             self.inverseRawColumn,
                             img,
                             rowTitles=self.rowTitles,
                             rowColors=self.rowColors,
                             colTitles=self.colTitles,
                             windowTitle=self.windowTitle,
                             linkWindows=self.linkWindows,
                             overlaidImages=self.overlaid_images,
                             mainColormap=self.mainColormap,
                             overlayColormap=self.overlayColormap,
                             customOverlayColormap=self.customOverlayColormap,
                             rowButtonSubTitles=self.rowButtonSubTitles)

    return objs
def execution(self, context):

    csd_model = load(self.csd_model.fullPath())
    csd_coeff = aims.read(self.fibre_odf_sh_coeff.fullPath())
    header = csd_coeff.header()
    sh_coeff = np.asarray(csd_coeff)
    mask_vol = aims.read(self.mask.fullPath())
    mask = vol_to_array(mask_vol)
    mask = array_to_mask(mask)

    try:
        S0 = aims.read(self.S0_signal.fullPath())
    except:
        context.write("No B0 volume provided, I assume the non ponderated signal value is 1.0 in all voxels")
        S0 = 1

    csd_fit = SphHarmFit(csd_model,sh_coeff, mask)
    prediction = csd_fit.predict(gtab=None, S0=S0)
    prediction_volume = array_to_vol(prediction, header)
    aims.write(prediction_volume,self.predicted_signal.fullPath())

    #Handling referentials
    transformManager = getTransformationManager()
    # Mandatory parameters
    transformManager.copyReferential(self.fibre_odf_sh_coeff, self.predicted_signal)
    pass
def execution(self, context):

    #lazy load just to estimate the number of streamlines
    tractogram, header = load_streamlines(self.streamlines.fullPath(),
                                          lazy=False)
    transformManager = getTransformationManager()
    referential = transformManager.referential(self.streamlines)
    #streamlines are in the LPI mm space
    nb_streamlines = header['nb_streamlines']
    streamlines = tractogram.streamlines
    if nb_streamlines > self.max_number:
        message = "The tractogram you try to display contains" + str(
            nb_streamlines
        ) + "streamlines\n In order to avoid memory crash only the first " + self.max_number, " streamlines will be displayed"
        "If your computer crashes consider decreasing self.max_number value \n. On the contrary if you have enough memory to display the whole tractogram you may want to increase self.max_number value"
        context.write(message)
        bundle = [s for i, s in enumerate(streamlines) if i < self.max_number]
    else:
        bundle = list(streamlines)
    bundle_aims = bundle_to_mesh(bundle, encode_local=True)
    del bundle

    a = anatomist.Anatomist()
    bundle_ana = a.toAObject(bundle_aims)
    bundle_ana.setMaterial(use_shader=1, shader_color_normals=1)
    bundle_ana.assignReferential(referential)

    del bundle_aims
    win = a.createWindow('3D')
    win.addObjects(bundle_ana)
    return [win, bundle_ana]
Esempio n. 9
0
def execution(self, context):

    context.write('Brain extraction using T1 mask')

    mask_bin = context.temporary('gz compressed NIFTI-1 image')
    cmd = [
        'AimsThreshold', '-i', self.T1_to_b0_mask, '-o', mask_bin, '-m', 'gt',
        '-t', '0', '-b', '--fg', '1'
    ]
    context.system(*cmd)
    cmd = [
        'AimsMorphoMath', '-i', mask_bin, '-o', self.b0_brain_mask, '-r', '10',
        '-m', 'clo'
    ]
    context.system(*cmd)
    cmd = [
        'AimsMask', '-i', self.b0_volume, '-o', self.b0_brain, '-m',
        self.b0_brain_mask
    ]
    context.system(*cmd)
    transformManager = getTransformationManager()
    transformManager.copyReferential(self.b0_volume, self.b0_brain)
    transformManager.copyReferential(self.b0_volume, self.b0_brain_mask)

    context.write('Finished')
Esempio n. 10
0
def search_transform(self, proc, dummy):
    if self.volume is None:
        return None
    tm = registration.getTransformationManager()
    pl = tm.findPaths(tm.referential(self.volume),
                      registration.talairachMNIReferentialId)
    for p in pl:
        return p
Esempio n. 11
0
 def linkRef(self, dummy):
     if self.data is not None:
         t = self.referential_type
         if t == '':
             t = None
         return registration.getTransformationManager(
         ).findOrCreateReferential(diskItem=self.data,
                                   referentialType=t,
                                   simulation=True)
Esempio n. 12
0
def execution(self, context):
    self.read = None
    if self.input_file:
        self.read = self.input_file
    elif self.input_directory:
        self.read = self.input_directory
    else:
        context.error(
            "You must give a valid value for input_file or input_directory.")
    if self.read:
        context.system(
            'AimsFileConvert', '-i', self.read, '-o', self.write)

        registration.getTransformationManager().copyReferential(self.read,
                                                                self.write)
        if self.removeSource:
            for f in self.read.fullPaths():
                shelltools.rm(f)
Esempio n. 13
0
def execution(self, context):

    BrainExtraction.interactiveBrainExtraction(context,
                                               self.b0_volume.fullPath(),
                                               self.b0_brain.fullPath())
    transformManager = getTransformationManager()
    transformManager.copyReferential(self.b0_volume, self.b0_brain)

    context.write('Finished')
Esempio n. 14
0
def execution(self, context):
    tex = aims.read(self.label_texture.fullPath())
    mesh = aims.read(self.mesh.fullPath())
    outmesh = aims.SurfaceManip.meshTextureBoundary(mesh, tex, -1)
    diffuse = [1., 0, 0., 1.]
    ncomp = min(len(self.mesh_color), 4)
    diffuse[:ncomp] = self.mesh_color[:ncomp]
    context.write(self.mesh_color)
    outmesh.header()[ 'material' ] = \
        {'line_width': self.line_width, 'diffuse': diffuse}
    aims.write(outmesh, self.output_boundaries_mesh.fullPath())
    tm = registration.getTransformationManager()
    tm.copyReferential(self.mesh, self.output_boundaries_mesh)
Esempio n. 15
0
 def linkMNItransformation(proc, dummy):
     if proc.source_volume:
         tm = registration.getTransformationManager()
         ref = tm.referential(registration.talairachMNIReferentialId)
         if ref and tm.referential(proc.source_volume):
             trans = tm.createNewTransformation('Transformation matrix',
                                                proc.source_volume,
                                                ref,
                                                simulation=True)
             return trans
         else:
             return WriteDiskItem(
                 'Transform Raw T1 MRI to Talairach-MNI template-SPM',
                 'Transformation Matrix').findValue(proc.source_volume)
Esempio n. 16
0
def execution(self, context):
    sourceUuid = self.image.uuid(saveMinf=False)
    self.ROI.setMinf('source_volume', str(sourceUuid))

    a = anatomist.Anatomist()
    imageObject = a.loadObject(self.image)

    nodesObjects = []
    if not self.ROI.isReadable():
        regionsObject = a.createGraph(object=imageObject,
                                      name=self.ROI.fullPath(),
                                      filename=self.ROI.fullPath())
        # Create a region
        nodesObjects.append(
            regionsObject.createNode(name='region', duplicate=False))
    else:
        regionsObject = a.loadObject(self.ROI)
        nodesObjects = regionsObject.children

    # Show regions and linked image
    block = a.createWindowsBlock()
    windowC = a.createWindow('Coronal', block=block)
    windowS = a.createWindow('Sagittal', block=block)
    windowA = a.createWindow('Axial', block=block)
    window3 = a.createWindow('3D', block=block)

    # set the referential of the image to all the window and to the roi graph
    ref = imageObject.referential
    if ref != a.centralRef:
        a.assignReferential(
            ref, [windowC, windowS, windowA, window3, regionsObject])

    a.addObjects([imageObject, regionsObject], [windowC, windowS, windowA])
    a.setWindowsControl(windows=[windowC, windowS, windowA],
                        control="PaintControl")
    window3.addObjects([regionsObject])

    if nodesObjects:  # the region must be selected to draw
        a.getDefaultWindowsGroup().addToSelection(nodesObjects)

    rep = context.ask("Click here when finished", "OK", "Cancel", modal=0)
    if rep != 1:
        regionsObject.save(self.ROI.fullPath())
        a.sync()
        # make sure that anatomist has finished to process previous
        # commands

    tm = registration.getTransformationManager()
    tm.copyReferential(self.image, self.ROI)
Esempio n. 17
0
def execution(self, context):
    context.write('data:', self.data)
    tm = registration.getTransformationManager()
    ref = tm.referential(self.data)
    context.write('existing referential:', ref)
    # even if a referential exists, it can be incorrect, so use find or create
    # referential
    t = self.referential_type
    if t == '':
        t = None
    ref = tm.findOrCreateReferential(diskItem=self.data,
                                     referentialType=t,
                                     assign=True,
                                     output_diskitem=self.referential)
    context.write('new ref:', ref)
def execution(self, context):

    mesh = aims.read(self.white_mesh.fullPath())
    vertices = np.array(mesh.vertex())
    #extract texture
    if self.roi_texture is None:
        v = vertices
    else:
        texture = aims.read(self.roi_texture.fullPath())
        tex = np.array(texture[0])
        v = vertices[tex != 0]
    np.savetxt(self.seeds.fullPath(), v)

    transformManager = getTransformationManager()
    transformManager.copyReferential(self.white_mesh, self.seeds)
Esempio n. 19
0
def execution(self, context):
    # Read header information
    atts = aimsGlobals.aimsVolumeAttributes(self.volume_input)
    ref = atts['referentials']
    trf = atts['transformations']
    if ("Scanner-based anatomical coordinates" in ref):
        trm_to_scannerBased = trf[
            ref.index("Scanner-based anatomical coordinates")]

    # Create a referential for Scanner-based
    tm = registration.getTransformationManager()
    dest = tm.referential(self.new_referential)
    context.write('dest:', dest)
    if dest is None:
        dest = tm.createNewReferentialFor(
            self.new_referential, referentialType='Scanner Based Referential')

    # Create a new referential if needed for the volume

    # src = tm.referential( self.volume_input )
    # print "Attributes"
    # print self.volume_input.hierarchyAttributes()
    # if src is None:
        # print "create src"
        # src = tm.createNewReferentialFor(self.volume_input)
        # print "apres"
        # print src

    src = tm.referential(self.referential_volume_input)
    context.write('src:', src)
    # print "Attributes"
    # print self.volume_input.hierarchyAttributes()
    if src is None:
        src = tm.createNewReferentialFor(self.volume_input,
                                         referentialType='Referential of Raw T1 MRI',
                                         output_diskitem=self.referential_volume_input)
    dest.setMinf('direct_referential', 1, saveMinf=True)

    # Store information into the trm file
    mot = aims.Motion(trm_to_scannerBased)
    aims.write(mot, self.T1_TO_Scanner_Based.fullPath())

    # set and update database
    tm.setNewTransformationInfo(
        self.T1_TO_Scanner_Based, source_referential=src, destination_referential=dest)
Esempio n. 20
0
def execution(self, context):
    filetype = self.read.type
    if filetype is getDiskItemType( 'SPM99 normalization matrix' ) \
       or self.read.fullName()[-5:] == '_sn3d':
        spm2 = 0
    else:
        spm2 = 1

    AtoT = aims.readSpmNormalization(self.read.fullPath(),
                                     self.source_volume.fullPath())
    srcref = None
    h = AtoT.header()
    if 'source_referential' in h:
        srcref = h['source_referential']
    tm = registration.getTransformationManager()

    if self.target != 'normalized_volume in AIMS orientation':
        aims.write(AtoT, self.write.fullPath())
        if self.target == 'MNI template':
            destref = tm.referential(registration.talairachMNIReferentialId)
        else:
            destref = None

    else:  # normalized_volume in AIMS orientation

        nim = self.normalized_volume
        if not nim or not nim.isReadable():
            raise RuntimeError(
                _t_('normalized_volume shoud be specified when using this target mode'
                    ))
        context.write('use normalized image:', nim.fullPath(), '\n')
        hasnorm = 1
        attrs = shfjGlobals.aimsVolumeAttributes(nim)
        t1 = aims.Motion(attrs['transformations'][-1])
        AIMS = t1.inverse() * AtoT
        AIMS.header().update(AtoT.header())
        destref = tm.referential(nim)
        aims.write(AIMS, self.write.fullPath())

    if srcref or destref:
        tm.setNewTransformationInfo(self.write, srcref, destref)

    if self.removeSource:
        for f in self.read.fullPaths():
            os.unlink(f)
def execution(self, context):

	mask_vol = aims.read(self.mask.fullPath())
	h = mask_vol.header()
	mask = np.asarray(mask_vol)[..., 0]
	mask = mask.astype(bool)
	voxel_size = np.array(h['voxel_size'])
	if len(voxel_size) == 4:
		voxel_size[-1] = 1
	elif len(voxel_size) == 3:
		voxel_size = np.concatenate((voxel_size,np.ones(1)))
	scaling = np.diag(voxel_size)

	density = [self.nb_seeds_x, self.nb_seeds_y, self.nb_seeds_z ]
	seeds = seeds_from_mask(mask, density=density,affine=scaling)
	np.savetxt(self.seeds.fullPath(), seeds)

	transformManager = getTransformationManager()
	transformManager.copyReferential(self.mask, self.seeds)
Esempio n. 22
0
def execution(self, context):
    from soma import aims, aimsalgo
    import numpy as np
    vol = aims.read(self.image_input.fullPath())
    old_t1_to_scanner = aims.AffineTransformation3d(
        vol.header()['transformations'][0])
    new_t1 = aims.read(self.target_space_image.fullPath())
    new_t1_to_scanner = aims.AffineTransformation3d(
        new_t1.header()['transformations'][0])
    old_to_new = new_t1_to_scanner.inverse() * old_t1_to_scanner
    rsp = getattr(aims, 'ResamplerFactory_' +
                  aims.typeCode(np.asarray(vol).dtype))().getResampler(0)
    rsp.setRef(vol)
    vol_resamp = rsp.doit(old_to_new, new_t1.getSizeX(), new_t1.getSizeY(),
                          new_t1.getSizeZ(),
                          new_t1.getVoxelSize()[:3])

    aims.write(vol_resamp, self.image_output.fullPath())
    tm = registration.getTransformationManager()
    tm.copyReferential(self.target_space_image, self.image_output)
Esempio n. 23
0
def execution(self, context):

    context.write("Loading input files")
    data_vol = aims.read(self.diffusion_data.fullPath())
    hdr = data_vol.header()
    data = vol_to_array(data_vol)
    del data_vol
    if self.mask is not None:
        mask_vol = aims.read(self.mask.fullPath())
        mask = vol_to_array(mask_vol)
        del mask_vol
        mask = array_to_mask(mask)
    else:
        mask = self.mask
    tensor = load(self.tensor_model.fullPath())
    context.write("Input files loaded successfully")

    context.write(
        "Fitting Diffusion Tensor model on data...it migh take some time")
    tenfit = tensor.fit(data, mask=mask)
    context.write("Diffusion Tensor Model fitted successfully")

    tensor_coefficients = tenfit.model_params
    vol_tensor = array_to_vol(tensor_coefficients, header=hdr)
    context.write('Writing coefficient volume on disk')
    aims.write(vol_tensor, self.tensor_coefficients.fullPath())

    #saving other metadata
    self.tensor_coefficients.setMinf('model_uuid', self.tensor_model.uuid())
    self.tensor_coefficients.setMinf('data_uuid', self.diffusion_data.uuid())
    try:
        assert self.mask is not None
        self.tensor_coefficients.setMinf('mask_uuid', self.mask.uuid())
    except Exception:
        self.tensor_coefficients.setMinf('mask_uuid', 'None')

    transformManager = getTransformationManager()
    transformManager.copyReferential(self.diffusion_data,
                                     self.tensor_coefficients)
    context.write("Processed Finished")
    pass
Esempio n. 24
0
def execution(self, context):
    if not self.input.isWriteable():
        raise RuntimeError(self.input.fullPath() + ' is not writeable')
    tm = registration.getTransformationManager()
    if self.normalization_template == 0:
        ref = '49e6b349-b115-211a-c8b9-20d0ece9846d'
        trans = tm.findPaths(ref, registration.talairachMNIReferentialId)
        tm.setReferentialTo(self.input, ref)
        self.fixtransformation(trans, context)
    elif self.normalization_template == 1:
        ref = '19bfee8e-51b1-4d9e-8721-990b9f88b12f'
        trans = tm.findPaths(ref, registration.talairachMNIReferentialId)
        tm.setReferentialTo(self.input, ref)
        self.fixtransformation(trans, context)
    elif self.normalization_template == 2:
        ref = 'f3848046-b581-cae4-ecb9-d80ada0278d5'
        trans = tm.findPaths(ref, registration.talairachMNIReferentialId)
        tm.setReferentialTo(self.input, ref)
        self.fixtransformation(trans, context)
    else:
        pass  # TODO
Esempio n. 25
0
def execution(self, context):

    csd_model = load(self.csd_model.fullPath())
    csd_coeff = aims.read(self.fibre_odf_sh_coeff.fullPath())
    h = csd_coeff.header()
    sh_coeff = np.asarray(csd_coeff)
    mask_vol = aims.read(self.mask.fullPath())
    mask = np.array(mask_vol,copy=False)[...,0].copy()
    context.write(mask.shape)


    csd_fit = SphHarmFit(csd_model,sh_coeff, mask)


    transformManager = getTransformationManager()
    # Mandatory parameters
    gfa = csd_fit.gfa
    GFA = self.array_to_vol(gfa,h)
    aims.write(GFA, self.generalized_fractionnal_anisotropy.fullPath())
    transformManager.copyReferential(self.fibre_odf_sh_coeff, self.generalized_fractionnal_anisotropy)

    pass
def execution(self, context):

    tensor_coeff = aims.read(self.tensor_coefficients.fullPath())
    tensor_params = np.asarray(tensor_coeff)
    tensor_model = load(self.tensor_model.fullPath())
    gtab = tensor_model.gtab
    #Loading base signal
    S0 = aims.read(self.S0_signal.fullPath())
    S0 = vol_to_array(S0)

    tenfit = TensorFit(tensor_model, tensor_params)
    pred_sign = tenfit.predict(gtab=gtab, S0=S0)
    hdr = tensor_coeff.header()
    pred_vol = array_to_vol(pred_sign, header=hdr)
    aims.write(pred_vol, self.predicted_signal.fullPath())

    #Handling metada
    transformManager = getTransformationManager()
    transformManager.copyReferential(self.predicted_signal,
                                     self.tensor_coefficients)

    context.write("Process finish successfully")
    pass
def execution(self, context):

    context.write(
        'Susceptibility induced distortion correction using Fieldmap... [~1mn]'
    )

    context.write('- Identification of first b0 volume')
    img = aims.read(self.dwi_data.fullPath())
    dwi_data = img.arraydata()
    bvals = numpy.loadtxt(self.bvals.fullPath())
    b0_index = numpy.where(bvals < 100)[
        0]  ## bvals==0 not possible when bvalues take values +-5 or +-10
    b0 = dwi_data[b0_index[0], :, :, :]
    b0_vol = aims.Volume(b0)
    b0_vol.copyHeaderFrom(img.header())
    b0_tmp = context.temporary('NIFTI-1 image')
    aims.write(b0_vol, b0_tmp.fullPath())

    configuration = Application().configuration
    FSL_directory = os.path.dirname(self.fieldmap_brain.fullPath())

    PE_list = ["AP", "PA", "LR", "RL"]
    dir_list = ["y-", "y", "x-", "x"]
    warping_direction = dir_list[PE_list.index(self.phase_encoding_direction)]

    context.write('- Brain extraction of magnitude image')
    BrainExtraction.defaultBrainExtraction(self.magnitude.fullPath(),
                                           self.magnitude_brain.fullPath(),
                                           f=str(self.brain_extraction_factor))
    # cmd = [ configuration.FSL.fsl_commands_prefix + 'fslmaths', self.fieldmap.fullPath(), '-mas', self.magnitude_brain.fullPath(), self.fieldmap_brain.fullPath() ]
    # context.system( *cmd )

    # unmask the fieldmap (necessary to avoid edge effects)
    cmd = [
        configuration.FSL.fsl_commands_prefix + 'fslmaths',
        self.magnitude_brain.fullPath(), '-bin',
        self.magnitude_brain_mask.fullPath()
    ]  #
    context.system(*cmd)  #
    cmd = [
        configuration.FSL.fsl_commands_prefix + 'fugue',
        '--loadfmap=' + self.fieldmap.fullPath(),
        '--mask=' + self.magnitude_brain_mask.fullPath(), '--unmaskfmap',
        '--savefmap=' + self.fieldmap_brain.fullPath(),
        '--unwarpdir=' + warping_direction
    ]  #
    context.system(*cmd)  #

    context.write('- Fieldmap smoothing')
    cmd = [
        configuration.FSL.fsl_commands_prefix + 'fugue',
        '--loadfmap=' + self.fieldmap_brain.fullPath(), '--despike',
        '--smooth3=' + str(self.fieldmap_smoothing),
        '--savefmap=' + self.fieldmap_brain.fullPath()
    ]
    context.system(*cmd)

    context.write('- Magnitude image warping using fieldmap')
    cmd = [
        configuration.FSL.fsl_commands_prefix + 'fugue', '-v', '-i',
        self.magnitude_brain.fullPath(), '--dwell=' + str(self.echo_spacing),
        '--unwarpdir=' + warping_direction,
        '--loadfmap=' + self.fieldmap_brain.fullPath(), '-w',
        self.magnitude_warped.fullPath()
    ]
    context.system(*cmd)

    context.write('- Registration of fieldmap into diffusion space')
    cmd1 = [
        configuration.FSL.fsl_commands_prefix + 'flirt', '-dof', '12', '-in',
        self.magnitude_warped.fullPath(), '-ref',
        b0_tmp.fullPath(), '-out',
        self.magnitude_warped_to_dwi.fullPath(), '-omat',
        self.fieldmap_to_dwi_mat.fullPath()
    ]
    cmd2 = [
        configuration.FSL.fsl_commands_prefix + 'flirt', '-dof', '12', '-in',
        self.fieldmap_brain.fullPath(), '-ref',
        b0_tmp.fullPath(), '-applyxfm', '-init',
        self.fieldmap_to_dwi_mat.fullPath(), '-out',
        self.fieldmap_to_dwi.fullPath()
    ]
    context.system(*cmd1)
    context.system(*cmd2)
    transformManager = getTransformationManager()
    transformManager.copyReferential(self.dwi_data,
                                     self.magnitude_warped_to_dwi)
    transformManager.copyReferential(self.dwi_data, self.fieldmap_to_dwi)

    context.write('- Unwarping of dwi image using fieldmap')
    cmd = [
        configuration.FSL.fsl_commands_prefix + 'fugue', '-v', '-i',
        self.dwi_data.fullPath(), '--dwell=' + str(self.echo_spacing),
        '--unwarpdir=' + warping_direction,
        '--loadfmap=' + self.fieldmap_to_dwi.fullPath(), '-u',
        self.dwi_unwarped.fullPath(), '--icorr',
        '--saveshift=' + FSL_directory + '/pixel_shift.nii.gz'
    ]  #'--mask=' + self.magnitude_warped_to_dwi_brain_mask.fullPath(), '--smooth3='  + str(self.fieldmap_smoothing),
    context.system(*cmd)
    cmd = [
        configuration.FSL.fsl_commands_prefix + 'fslmaths',
        self.dwi_unwarped.fullPath(), '-abs',
        self.dwi_unwarped.fullPath()
    ]
    context.system(*cmd)

    transformManager.copyReferential(self.dwi_data, self.dwi_unwarped)

    context.write('Finished')
Esempio n. 28
0
def execution(self, context):

    configuration = Application().configuration

    tmp_file = context.temporary('File')
    tmp_deform = context.temporary('File')

    #if self.registration_method == 'niftyreg':
    # new niftyreg deformation volume is X,Y,Z,1,3 instead of X,Y,Z,3
    deform_vol = nib.load(self.diff_to_T1_nonlinear_dfm.fullPath())
    if len(deform_vol.shape) == 5:
        deform = deform_vol.get_data()
        deform = deform[..., 0, :]
        nib.save(nib.Nifti1Image(deform, deform_vol.affine),
                 tmp_deform.fullPath() + '.nii.gz')
    else:
        nib.save(deform_vol, tmp_deform.fullPath() + '.nii.gz')
    #reuse Lucile code to split volume cause dont want to mess with orientations as it worked
    cmd = [
        configuration.FSL.fsl_commands_prefix + 'fslsplit',
        tmp_deform.fullPath() + '.nii.gz',
        tmp_file.fullPath(), '-t'
    ]
    context.system(*cmd)
    context.write(tmp_file.fullPath())
    f1 = aims.read(tmp_file.fullPath() + '0000.nii.gz')
    f2 = aims.read(tmp_file.fullPath() + '0001.nii.gz')
    f3 = aims.read(tmp_file.fullPath() + '0002.nii.gz')
    f = np.concatenate((f1.arraydata(), f2.arraydata(), f3.arraydata()))
    field = np.swapaxes(f, 0, 3)
    field = np.swapaxes(field, 1, 2)
    vxsize = np.array(f1.header()['voxel_size'][:3])
    affine = f1.header()['transformations']
    affine_mm = np.reshape(affine[0], (4, 4))

    mesh = aims.read(self.WM_mesh_in_T1.fullPath())
    new_mesh = meshTransform(mesh, field, vxsize, affine_mm)
    aims.write(new_mesh, self.WM_mesh_in_DWI.fullPath())
    cmd = [
        'AimsMeshTransform', '-i', self.WM_mesh_in_DWI, '-t',
        self.T1_to_diff_linear_xfm, '-o', self.WM_mesh_in_DWI
    ]
    context.system(*cmd)
    transformManager = getTransformationManager()
    transformManager.copyReferential(self.b0_volume, self.WM_mesh_in_DWI)

    mesh = aims.read(self.GM_mesh_in_T1.fullPath())
    new_mesh = meshTransform(mesh, field, vxsize, affine_mm)
    aims.write(new_mesh, self.GM_mesh_in_DWI.fullPath())
    cmd = [
        'AimsMeshTransform', '-i', self.GM_mesh_in_DWI, '-t',
        self.T1_to_diff_linear_xfm, '-o', self.GM_mesh_in_DWI
    ]
    context.system(*cmd)
    transformManager = getTransformationManager()
    transformManager.copyReferential(self.b0_volume, self.GM_mesh_in_DWI)

    # elif self.registration_method == 'fnirt':
    #     field_file = context.temporary('gz compressed NIFTI-1 image')
    #     # cmd = [configuration.FSL.fsl_commands_prefix + 'fnirtfileutils', '-i', self.diff_to_T1_nonlinear_dfm.fullPath(), '-r', self.T1_volume.fullPath(), '-o', field_file.fullPath()]
    #     # context.system(*cmd)
    #     cmd = [configuration.FSL.fsl_commands_prefix + 'fslsplit', self.diff_to_T1_nonlinear_dfm.fullPath(), tmp_file.fullPath(), '-t']
    #     context.system(*cmd)
    #     f1 = aims.read(tmp_file.fullPath() + '0000.nii.gz')
    #     f2 = aims.read(tmp_file.fullPath() + '0001.nii.gz')
    #     f3 = aims.read(tmp_file.fullPath() + '0002.nii.gz')
    #     f = np.concatenate((f1.arraydata(), f2.arraydata(), f3.arraydata()))
    #     field = np.swapaxes(f, 0, 3)
    #     field = np.swapaxes(field, 1, 2)
    #     t1 = aims.read(self.T1_volume.fullPath())
    #     vxsize = np.array(f1.header()['voxel_size'][:3])
    #     affine = t1.header()['transformations']
    #     # affine = f1.header()['transformations']
    #     affine_mm = np.reshape(affine[0], (4, 4))
    #
    #     mesh = aims.read(self.WM_mesh_in_T1.fullPath())
    #     new_mesh = meshTransform(mesh, field, vxsize, affine_mm)
    #     aims.write(new_mesh, self.WM_mesh_in_DWI.fullPath())
    #     transformManager = getTransformationManager()
    #     transformManager.copyReferential(self.b0_volume, self.WM_mesh_in_DWI)
    #
    #     mesh = aims.read(self.GM_mesh_in_T1.fullPath())
    #     new_mesh = meshTransform(mesh, field, vxsize, affine_mm)
    #     aims.write(new_mesh, self.GM_mesh_in_DWI.fullPath())
    #     transformManager = getTransformationManager()
    #     transformManager.copyReferential(self.b0_volume, self.GM_mesh_in_DWI)

    context.write('Finished')
def execution(self, context):

    tensor_coeff_vol = aims.read(self.tensor_coefficients.fullPath())
    tensor_coeff = np.asarray(tensor_coeff_vol)
    hdr = tensor_coeff_vol.header()

    tensor_model = load(self.tensor_model.fullPath())

    tenfit = TensorFit(tensor_model, tensor_coeff)
    #Mandatory parameters
    fa = tenfit.fa
    FA = array_to_vol(fa, hdr)
    aims.write(FA, self.fractionnal_anisotropy.fullPath())
    md = tenfit.md
    MD = array_to_vol(md, hdr)
    aims.write(MD, self.mean_diffusivity.fullPath())
    evecs = tenfit.evecs
    vectors = [
        evecs[:, :, :, :, 0], evecs[:, :, :, :, 1], evecs[:, :, :, :, 2]
    ]
    evals = tenfit.evals

    eigen_values = array_to_vol(evals, hdr)
    aims.write(eigen_values, self.evals.fullPath())

    vectors_volume = [array_to_vol(v, hdr) for v in vectors]

    aims.write(vectors_volume[0], self.first_eigen_vector.fullPath())
    aims.write(vectors_volume[1], self.second_eigen_vector.fullPath())
    aims.write(vectors_volume[2], self.third_eigen_vector.fullPath())

    color_fa = tenfit.color_fa
    color_fa_vol = array_to_vol(color_fa)
    aims.write(color_fa_vol, self.colored_fractionnal_anisotropy.fullPath())
    # handling referentials
    transformManager = getTransformationManager()
    transformManager.copyReferential(self.tensor_coefficients,
                                     self.fractionnal_anisotropy)
    transformManager.copyReferential(self.tensor_coefficients,
                                     self.mean_diffusivity)
    # additionnal metadata
    self.mean_diffusivity.setMinf('tensor_coefficients_uuid',
                                  self.tensor_coefficients.uuid())
    self.fractionnal_anisotropy.setMinf('tensor_coefficients_uuid',
                                        self.tensor_coefficients.uuid())

    if self.advanced_indices:
        axial_diffusivity = tenfit.ad
        planarity = tenfit.planarity
        sphericity = tenfit.sphericity
        linearity = tenfit.linearity
        mode = tenfit.mode

        disk_items = [
            self.axial_diffusivity, self.planarity, self.sphericity,
            self.linearity, self.mode
        ]
        arrays = [axial_diffusivity, planarity, sphericity, linearity, mode]

        for ind, a in enumerate(arrays):
            vol = array_to_vol(a, hdr)
            aims.write(vol, disk_items[ind].fullPath())
            transformManager.copyReferential(self.tensor_coefficients,
                                             disk_items[ind])

    pass
def execution(self, context):

    configuration = Application().configuration
    transformManager = getTransformationManager()
    niftyreg_resample = find_executable('reg_resample')
    #no longer needed since validation check !
    #if not niftyreg_resample:
    #raise RuntimeError(_t_('Niftyreg executable NOT found !'))

    reg = context.temporary('File')
    tmp_file = context.temporary('gz compressed NIFTI-1 image')

    cmd = [
        configuration.FSL.fsl_commands_prefix + 'fslmaths',
        self.ROI_in_T1.fullPath()
    ]
    if self.lower_thresh is not None:
        cmd += ['-thr', self.lower_thresh]
    if self.upper_thresh is not None:
        cmd += ['-uthr', self.upper_thresh]
    cmd += ['-bin', tmp_file.fullPath()]
    context.system(*cmd)

    ## A SUPPRIMER EN DEHORS DU HCP : A CAUSE ORIENTATION RAS A POSTERIORI
    # tmp_b0 = context.temporary('gz compressed NIFTI-1 image')
    # os.system(' '.join(['AimsFileConvert', '-i', self.b0_volume.fullPath(), '-o', tmp_b0.fullPath(), '--orient', '"abs: 1 -1 -1"']))
    ##

    if self.T1_to_b0_registration_method == 'niftyreg':
        cmd = [
            niftyreg_resample, '-ref',
            self.T1_volume.fullPath(), '-flo',
            tmp_file.fullPath(), '-trans',
            self.T1_to_diff_nonlinear_dfm.fullPath(), '-res',
            reg.fullPath() + '_ROI.nii.gz', '-inter', '0'
        ]
        context.system(*cmd)
        cmd = [
            'AimsResample', '-i',
            reg.fullPath() + '_ROI.nii.gz', '-m', self.T1_to_diff_linear_xfm,
            '-t', '0', '-o', self.ROI_in_DWI, '-d', '1', '-r',
            self.b0_volume.fullPath()
        ]
        context.system(*cmd)

    elif self.T1_to_b0_registration_method == 'fnirt':
        cmd = [
            configuration.FSL.fsl_commands_prefix + 'applywarp', '-i',
            tmp_file.fullPath(), '-r',
            self.b0_volume.fullPath(), '-o',
            self.ROI_in_DWI.fullPath(), '-w',
            self.T1_to_diff_nonlinear_dfm.fullPath(), '--interp=nn'
        ]
        context.system(*cmd)

    if self.binarise:
        cmd = [
            configuration.FSL.fsl_commands_prefix + 'fslmaths',
            self.ROI_in_DWI.fullPath(), '-thr', self.threshold, '-bin',
            self.ROI_in_DWI.fullPath()
        ]  # , '--fg', '1']
    else:
        cmd = [
            configuration.FSL.fsl_commands_prefix + 'fslmaths',
            self.ROI_in_DWI.fullPath(), '-thr', self.threshold,
            self.ROI_in_DWI.fullPath()
        ]  # , '--fg', '1']
    context.system(*cmd)
    # ref = self.b0_volume.get('storage_to_memory', search_header=True)
    # transformManager.copyReferential(self.b0_volume, self.ROI_in_DWI)

    ## A SUPPRIMER EN DEHORS DU HCP : A CAUSE ORIENTATION RAS A POSTERIORI
    # os.system(' '.join(['AimsFileConvert', '-i', self.ROI_in_DWI.fullPath(), '-o', self.ROI_in_DWI.fullPath(), '--orient', '"abs: -1 -1 -1"']))
    ##

    context.write('Finished')