示例#1
0
def execution(self, context):
    from soma import aims
    reader = aims.Reader()

    texture2 = reader.read(str(self.input[0]))
    texture = aims.TimeTexture_FLOAT(len(self.input), len(texture2[0]))

    # for i in six.moves.xrange(len(texture2[0])):
    # texture[0][i] = texture2[0][i]

    for i in six.moves.xrange(len(self.input)):
        aux = reader.read(str(self.input[i]))
        for j in six.moves.xrange(len(aux[0])):
            texture[i][j] = aux[0][j]
    context.write(texture.size())
    writer = aims.Writer()
    writer.write(texture, str(self.output))
    context.write("Finished")
示例#2
0
def aims__main__():
    interp = "nn"
    # Set default values to parameters
    # parse command line options
    #parser = optparse.OptionParser(description=__doc__)
    parser = argparse.ArgumentParser()
    parser.add_argument('--input', help='Input image to resample', type=str)
    parser.add_argument('--ref', help='Reference volume', type=str)
    parser.add_argument('--interp', help='Interpolation method nn, lin, quad', type=str)
    parser.add_argument('--output', help='Ouptut', type=str)

    options = parser.parse_args()
    src_filename = options.input
    ref_filename = options.ref
    src = aims.read(src_filename)
    ref = aims.read(ref_filename)
    output_ima = resample(src, ref)
    assert output_ima.maximum() == src.arraydata().max()

    writer = aims.Writer()
    writer.write(output_ima, options.output)
def mesh_large_clusters(arr, clust_labeled, clust_sizes, labels,
                        output_clusters_large_mesh_filename, tempdir, ima,
                        thresh_size):
    large_clust_ima = aims.Volume(ima)
    large_clust_arr = np.asarray(large_clust_ima).squeeze()
    large_clust_arr[:] = 0
    for i in xrange(len(labels)):
        label = labels[i]
        if clust_sizes[i] > thresh_size:
            large_clust_arr[clust_labeled == label] = 1
    large_clust_ima_filename = os.path.join(tempdir, "large_clusters.nii")
    writer = aims.Writer()
    writer.write(large_clust_ima, large_clust_ima_filename)
    large_clust_graph_filename = os.path.join(tempdir, "large_clusters.arg")
    cmd = 'AimsClusterArg --input %s --output %s' % \
    (large_clust_ima_filename, large_clust_graph_filename)
    print "\n============="
    print cmd
    print "============="
    os.popen(cmd)
    graph = aims.read(large_clust_graph_filename)
    print "-----"
    large_clust_meshs = None
    for v in graph.vertices():
        if large_clust_meshs is None:
            large_clust_meshs = v['aims_Tmtktri']
        else:
            aims.SurfaceManip.meshMerge(large_clust_meshs, v['aims_Tmtktri'])
    if large_clust_meshs is not None:
        large_clust_meshs.header()['referentials'] = ima.header(
        )['referentials']
        large_clust_meshs.header()['transformations'] = ima.header(
        )['transformations']
        writer.write(large_clust_meshs, output_clusters_large_mesh_filename)
        return large_clust_meshs
    else:
        print "No large cluster generated"
        return None
def cingular_project(parameters):
    DATABASE, s_id = parameters

    subj_dir = os.path.join(DATABASE, s_id)

    for sd in ['L', 'R']:
        file_white_mesh = os.path.join(subj_dir, "t1mri", "BL",
                                       "default_analysis", "segmentation",
                                       "mesh", s_id + "_" + sd + "white.gii")
        pole_cingular = os.path.join(
            subj_dir, "t1mri", "BL", "default_analysis", "segmentation",
            "mesh", "surface_analysis",
            s_id + "_" + sd + "white_pole_cingular.gii")
        #aparc = os.path.join(subj_dir, "label",
        #                     s_id+ "."+sd+".aparc.native.label.gii")
        fs_cortex_label = os.path.join(subj_dir, "label",
                                       sd.lower() + 'h.cortex.label')
        re = aims.Reader()
        ws = aims.Writer()
        mesh = re.read(file_white_mesh)
        nbv = len(mesh.vertex())
        data = np.ones(nbv)

        f = open(fs_cortex_label, 'r')
        lines = f.readlines()
        for a in lines[2:]:
            a_spl = a.split()
            data[int(a_spl[0])] = a_spl[4]
        f.close()
        #data_in = gio.read(file_aparc).darrays[0].data
        #data = np.zeros_like(data_in)
        #data[data_in==-1]=1
        a, b = textureTls.textureTopologicalCorrection(mesh, data, 1)
        cingular_tex_clean, cingular_tex_boundary = a, b
        tex_out = aims.TimeTexture_S16()
        tex_out[0].assign(cingular_tex_clean)
        ws.write(tex_out, pole_cingular)
示例#5
0
def write_aims_Mesh(vertex, polygon, fileName):
    """
    Given a set of vertices, polygons and a filename,
    write the corresponding aims mesh
    the aims mesh is returned

    Caveat
    ======
    depends on aims
    """
    from soma import aims
    vv = aims.vector_POINT3DF()
    vp = aims.vector_AimsVector_U32_3()
    for x in vertex:
        vv.append(x)
    for x in polygon:
        vp.append(x)
    m = aims.AimsTimeSurface_3()
    m.vertex().assign(vv)
    m.polygon().assign(vp)
    m.updateNormals()
    W = aims.Writer()
    W.write(m, fileName)
    return m
示例#6
0
def main(Primate1, Primate2, side):
    nameLon = Primate2 + '_' + side + 'white_lon.gii'
    nameLat = Primate2 + '_' + side + 'white_lat.gii'

    print('reading models\' informations')

    modelP1F = 'model_' + Primate1 + '_' + side + '.txt'
    modelP2F = 'model_' + Primate2 + '_' + side + '.txt'
    modelP1 = read_model(modelP1F)
    modelP2 = read_model(modelP2F)
    dimRect_P1, poles_lat_P1, longID_P1, latID_P1, sulci_lon_P1, sulci_lat_P1, lon_coor_P1, lat_coor_P1 = modelP1
    dimRect_P2, poles_lat_P2, longID_P2, latID_P2, sulci_lon_P2, sulci_lat_P2, lon_coor_P2, lat_coor_P2 = modelP2

    print('reading correspondences\' table')

    name_corr = Primate1 + '_' + Primate2 + '_' + 'corr.txt'
    if os.path.exists(name_corr):
        corrTable = read_corr(name_corr)
    else:
        name_corr = Primate2 + '_' + Primate1 + '_' + 'corr.txt'
        corrTable = read_corr(name_corr)

    print('reading coordinates')

    r = aims.Reader()
    texLatF = r.read(nameLat)
    texLonF = r.read(nameLon)
    texLat = np.array(texLatF[0])
    texLon = np.array(texLonF[0])

    print('rescaling square coordinates to sphere coordinates')

    sulciP1, sulciP2 = SquareToSphere(dimRect_P1, dimRect_P2,
                                      [lon_coor_P1, lat_coor_P1],
                                      [lon_coor_P2, lat_coor_P2], poles_lat_P1,
                                      poles_lat_P2)

    print('extracting correspondences')

    assert (len(corrTable['lon_' + Primate1]) == len(corrTable['lon_' + Primate2]) and
            len(corrTable['lat_' + Primate1]) == len(corrTable['lat_' + Primate2])), \
        "Number of corresponding sulci do not match in corr text file."

    Ncorr_lon = len(corrTable['lon_' + Primate1])
    Ncorr_lat = len(corrTable['lat_' + Primate1])
    long_corr = np.zeros((Ncorr_lon, 2)).astype('int')
    lat_corr = np.zeros((Ncorr_lat, 2)).astype('int')
    for i in range(Ncorr_lon):
        long_corr[i][0] = longID_P1[sulci_lon_P1[corrTable['lon_' +
                                                           Primate1][i]]]
        long_corr[i][1] = longID_P2[sulci_lon_P2[corrTable['lon_' +
                                                           Primate2][i]]]
    for i in range(Ncorr_lat):
        lat_corr[i][0] = latID_P1[sulci_lat_P1[corrTable['lat_' +
                                                         Primate1][i]]]
        lat_corr[i][1] = latID_P2[sulci_lat_P2[corrTable['lat_' +
                                                         Primate2][i]]]

    print('computing affine transformations')

    long_transform, lat_transform = Affine_Transform(sulciP1, sulciP2,
                                                     long_corr, lat_corr,
                                                     poles_lat_P1,
                                                     poles_lat_P2)

    print('processing longitude')

    intervals_lon = np.concatenate(([0], sulciP2[0][long_corr[:, 1]], [360]))
    intervals_lon = np.sort(intervals_lon)
    newLon = rescale(texLon, long_transform, intervals_lon)

    print('processing latitude')

    intervals_lat = np.concatenate(([30], sulciP2[1][lat_corr[:, 1]], [150]))
    intervals_lat = np.sort(intervals_lat)
    newLat = rescale(texLat, lat_transform, intervals_lat)

    print('writing textures')

    nv = texLat.size
    newLatT = aims.TimeTexture_FLOAT(1, nv)
    newLonT = aims.TimeTexture_FLOAT(1, nv)

    for i in range(nv):
        newLatT[0][i] = newLat[i]
        newLonT[0][i] = newLon[i]

    outLat = Primate1 + '_' + side + 'white_lat_to' + Primate2 + '.gii'
    outLon = Primate1 + '_' + side + 'white_lon_to' + Primate2 + '.gii'

    r = aims.Writer()
    r.write(newLatT, outLat)
    r.write(newLonT, outLon)
    print('done')

    return None
示例#7
0
def iterate(Primate1, Primate2, side, Primate_inter=None):
    """
    Meant to be used on a database to iterate the reparametrization on a list of individuals of one species to the
    coordinate system of Primate1.
    :param Primate1: string - name of Primate1
    :param Primate2: string - name of Primate2
    :param side: string - hemisphere 'L' or 'R'
    :return: the rescaled longitudinal and latitudinal textures for each individual of Primate2
    """

    individuals = [i for i in os.listdir(Primate2) if '.' not in i]

    print('reading affine transformations')

    dir = Primate1 + '_to_' + Primate2
    if Primate_inter is not None:
        dir = Primate1 + '_to_' + Primate2 + '_via' + Primate_inter

    affine_model = os.path.join(dir,
                                'affine_trans_' + dir + '_' + side + '.txt')
    int_lon, int_lat, lon_transform, lat_transform = read_affine(affine_model)

    for ind in individuals:

        nameLon = os.path.join(Primate2, ind,
                               ind + '_' + side + 'white_lon.gii')
        nameLat = os.path.join(Primate2, ind,
                               ind + '_' + side + 'white_lat.gii')

        # print('reading coordinates')

        r = aims.Reader()
        texLatF = r.read(nameLat)
        texLonF = r.read(nameLon)
        texLat = np.array(texLatF[0])
        texLon = np.array(texLonF[0])

        # print('processing longitude')

        newLon = rescale(texLon, lon_transform, int_lon)

        # print('processing latitude')

        newLat = rescale(texLat, lat_transform, int_lat)

        # print('writing textures')

        nv = texLat.size
        newLatT = aims.TimeTexture_FLOAT(1, nv)
        newLonT = aims.TimeTexture_FLOAT(1, nv)

        for i in range(nv):
            newLatT[0][i] = newLat[i]
            newLonT[0][i] = newLon[i]

        outLat = os.path.join(
            dir, Primate1 + '_' + side + 'white_lat_to' + ind + '.gii')
        outLon = os.path.join(
            dir, Primate1 + '_' + side + 'white_lon_to' + ind + '.gii')

        r = aims.Writer()
        r.write(newLatT, outLat)
        r.write(newLonT, outLon)

    print('done')
    output_csv_clusters_info_filename = os.path.join(output, "clust_info.csv")
    output_clusters_labels_filename = os.path.join(output,
                                                   "clust_labels.nii.gz")
    output_clusters_values_filename = os.path.join(output,
                                                   "clust_values.nii.gz")
    output_clusters_small_mesh_filename = os.path.join(output,
                                                       "clust_small.gii")
    output_clusters_large_mesh_filename = os.path.join(output,
                                                       "clust_large.gii")
    output_clusters_mesh_filename = os.path.join(output, "clust.gii")
    output_MNI152_T1_1mm_brain_filename = os.path.join(
        output, os.path.basename(MNI152_T1_1mm_brain_filename))

    tempdir = tempfile.mkdtemp()

    writer = aims.Writer()
    ##########################################################################
    # Read volume
    ima = aims.read(map_filename)
    """
    # force referential to MNI
    has_to_force_to_mni = False
    for i in xrange(len(ima.header()['referentials'])):
        if ima.header()['referentials'][i] != referential:
             ima.header()['referentials'][i] = referential
             has_to_force_to_mni = True
    if has_to_force_to_mni:
        writer.write(ima, map_filename)
        ima = aims.read(map_filename)
    """
    trm_xyz_to_mm = ima_get_trm_xyz_to_mm(ima)