Beispiel #1
0
def test_readwritedata():
    img = gi.read(DATA_FILE2)
    with InTemporaryDirectory():
        gi.write(img, "test.gii")
        img2 = gi.read("test.gii")
        assert_equal(img.numDA, img2.numDA)
        assert_array_almost_equal(img.darrays[0].data, img2.darrays[0].data)
def load_texture(path):
    """Return an array from texture data stored in a gifti file

    Parameters
    ----------
    path string or list of strings
         path of the texture files

    Returns
    -------
    data array of shape (nnode) or (nnode, len(path)) 
         the corresponding data
    """
    from nibabel.gifti import read

    # use alternative libraries than nibabel if necessary
    if hasattr(path, '__iter__'):
        tex_data = []
        for f in path:
            ftex = read(f).getArraysFromIntent('NIFTI_INTENT_TIME_SERIES')
            tex = np.array([f.data for f in ftex])
            tex_data.append(tex)
        tex_data = np.array(tex_data)
        if len(tex_data.shape) > 2:
            tex_data = np.squeeze(tex_data)
    else:
        tex_ = read(path)
        tex_data = np.array([darray.data for darray in tex_.darrays])
    return tex_data
    def check_surf_mesh(self, index):

        from nilearn._utils.compat import _basestring
        import nibabel

        # if input is a filename, try to load it

        surf_mesh = self.meshes[index]

        if isinstance(surf_mesh, _basestring):
            if (surf_mesh.endswith('orig') or surf_mesh.endswith('pial') or
                    surf_mesh.endswith('white') or surf_mesh.endswith('sphere') or
                    surf_mesh.endswith('inflated')):
                coords, faces = nibabel.freesurfer.io.read_geometry(surf_mesh)
            elif surf_mesh.endswith('gii'):
                coords, faces = gifti.read(surf_mesh).darrays[0].data, \
                                gifti.read(surf_mesh).darrays[1].data
            else:
                raise ValueError('Format of mesh file not recognized.')
        # if a dictionary is given, check it contains entries for coords and faces
        elif isinstance(surf_mesh, dict):
            if ('faces' in surf_mesh and 'coords' in surf_mesh):
                coords, faces = surf_mesh['coords'], surf_mesh['faces']
            else:
                raise ValueError('If surf_mesh is given as a dictionary it must '
                                 'contain items with keys "coords" and "faces"')
        else:
            raise ValueError('surf_mesh must be a either filename or a dictionary '
                             'containing items with keys "coords" and "faces"')
        return coords, faces
Beispiel #4
0
def load_conte_mesh(conte_atlas, inflation):
    """ Load conte69 mesh: load midthickness nomatter what and then other """
    l_atlas = os.path.join(conte_atlas, 'Conte69.L.{}.32k_fs_LR.surf.gii')
    r_atlas = l_atlas.replace('Conte69.L.', 'Conte69.R.')

    l_surf = gifti.read(l_atlas.format('midthickness'))
    verts_L_data, faces_L_data = l_surf.darrays[0].data, l_surf.darrays[1].data

    r_surf = gifti.read(r_atlas.format('midthickness'))
    verts_R_data, faces_R_data = r_surf.darrays[0].data, r_surf.darrays[1].data

    if inflation != 'low':
        if inflation == 'medium':
            inf = 'inflated'
        elif inflation == 'high':
            inf = 'very_inflated'

        l_surf2 = gifti.read(l_atlas.format(inf))
        verts_L_display = l_surf2.darrays[0].data
        faces_L_display = l_surf2.darrays[1].data

        r_surf2 = gifti.read(r_atlas.format(inf))
        verts_R_display = r_surf2.darrays[0].data
        faces_R_display = r_surf2.darrays[1].data

    else:
        verts_L_display = verts_L_data.copy()
        verts_R_display = verts_R_data.copy()
        faces_L_display = faces_L_data.copy()
        faces_R_display = faces_R_data.copy()

    return (verts_L_data, faces_L_data, verts_R_data, faces_R_data,
            verts_L_display, verts_R_display, faces_L_display, faces_R_display)
    def check_surf_mesh(self, index):

        from nilearn._utils.compat import _basestring
        import nibabel

        # if input is a filename, try to load it

        surf_mesh = self.meshes[index]

        if isinstance(surf_mesh, _basestring):
            if (surf_mesh.endswith('orig') or surf_mesh.endswith('pial')
                    or surf_mesh.endswith('white')
                    or surf_mesh.endswith('sphere')
                    or surf_mesh.endswith('inflated')):
                coords, faces = nibabel.freesurfer.io.read_geometry(surf_mesh)
            elif surf_mesh.endswith('gii'):
                coords, faces = gifti.read(surf_mesh).darrays[0].data, \
                                gifti.read(surf_mesh).darrays[1].data
            else:
                raise ValueError('Format of mesh file not recognized.')
        # if a dictionary is given, check it contains entries for coords and faces
        elif isinstance(surf_mesh, dict):
            if ('faces' in surf_mesh and 'coords' in surf_mesh):
                coords, faces = surf_mesh['coords'], surf_mesh['faces']
            else:
                raise ValueError(
                    'If surf_mesh is given as a dictionary it must '
                    'contain items with keys "coords" and "faces"')
        else:
            raise ValueError(
                'surf_mesh must be a either filename or a dictionary '
                'containing items with keys "coords" and "faces"')
        return coords, faces
Beispiel #6
0
def test_readwritedata():
    img = gi.read(DATA_FILE2)
    newp = pjoin(tempfile.gettempdir(), 'test.gii')
    gi.write(img, newp)
    img2 = gi.read(newp)

    assert_equal(img.numDA, img2.numDA)
    assert_array_almost_equal(img.darrays[0].data, img2.darrays[0].data)
Beispiel #7
0
def test_readwritedata():
    img = gi.read(DATA_FILE2)
    newp = pjoin(tempfile.gettempdir(), "test.gii")
    gi.write(img, newp)
    img2 = gi.read(newp)

    assert_equal(img.numDA, img2.numDA)
    assert_array_almost_equal(img.darrays[0].data, img2.darrays[0].data)
Beispiel #8
0
def test_read_ordering():
    # DATA_FILE1 has an expected darray[0].data shape of (3,3).  However if we
    # read another image first (DATA_FILE2) then the shape is wrong
    # Read an image
    img2 = gi.read(DATA_FILE2)
    assert_equal(img2.darrays[0].data.shape, (143479, 1))
    # Read image for which we know output shape
    img = gi.read(DATA_FILE1)
    assert_equal(img.darrays[0].data.shape, (3, 3))
Beispiel #9
0
def test_read_ordering():
    # DATA_FILE1 has an expected darray[0].data shape of (3,3).  However if we
    # read another image first (DATA_FILE2) then the shape is wrong
    # Read an image
    img2 = gi.read(DATA_FILE2)
    assert_equal(img2.darrays[0].data.shape, (143479, 1))
    # Read image for which we know output shape
    img = gi.read(DATA_FILE1)
    assert_equal(img.darrays[0].data.shape, (3, 3))
Beispiel #10
0
def test_constraint_structure():
    ''' Tests if we recover the right structure from a gifti surface '''
    l_surf = gifti.read('./logpar/cli/tests/data/L.white.surf.gii')
    r_surf = gifti.read('./logpar/cli/tests/data/R.pial.surf.gii')

    l_struct = cifti_utils.principal_structure(l_surf)
    r_struct = cifti_utils.principal_structure(r_surf)

    assert (l_struct == 'CIFTI_STRUCTURE_CORTEX_LEFT')
    assert (r_struct == 'CIFTI_STRUCTURE_CORTEX_RIGHT')
Beispiel #11
0
def loadsurf_gifti(fname, surftype, quiet=True):
    from nibabel import gifti
    from dataset import SurfData
    fname = '%s.%sgii' % (fname, '%s')
    fname = match_gifti_intent(fname, 'surface')

    surf_lh = gifti.read(parse.hemineutral(fname) % 'lh')
    surf_rh = gifti.read(parse.hemineutral(fname) % 'rh')

    sverts_lh, sfaces_lh = surf_lh.darrays[0].data, surf_lh.darrays[1].data
    sverts_rh, sfaces_rh = surf_rh.darrays[0].data, surf_rh.darrays[1].data

    return SurfData(sverts_lh, sfaces_lh, sverts_rh, sfaces_rh, surftype)
Beispiel #12
0
def loadsurf_gifti(fname,surftype,quiet=True):
    from nibabel import gifti
    from dataset import SurfData
    fname = '%s.%sgii'%(fname,'%s')
    fname = match_gifti_intent(fname, 'surface')

    surf_lh = gifti.read(parse.hemineutral(fname)%'lh')
    surf_rh = gifti.read(parse.hemineutral(fname)%'rh')
    
    sverts_lh,sfaces_lh = surf_lh.darrays[0].data, surf_lh.darrays[1].data
    sverts_rh,sfaces_rh = surf_rh.darrays[0].data, surf_rh.darrays[1].data

    return SurfData(sverts_lh,sfaces_lh,sverts_rh,sfaces_rh,surftype)
Beispiel #13
0
def GetMesh(g):
    # read a gifti (.gii) surface file

    #g = '/mesh/cortex_20484.surf.gii'
    v, f = gifti.read(g).getArraysFromIntent(1008)[0].data, \
           gifti.read(g).getArraysFromIntent(1009)[0].data

    Centre = spherefit(v)
    v[0] = v[0] - Centre[0]
    v[1] = v[1] - Centre[1]
    v[2] = v[2] - Centre[2]
    #v = fixboundary(v)

    return v, f
    def check_surf_data(self, index, gii_darray=0):

        from nilearn._utils.compat import _basestring
        import nibabel

        surf_data = self.backgrounds[index]

        # if the input is a filename, load it
        if isinstance(surf_data, _basestring):
            if (surf_data.endswith('nii') or surf_data.endswith('nii.gz') or
                    surf_data.endswith('mgz')):
                data = np.squeeze(nibabel.load(surf_data).get_data())
            elif (surf_data.endswith('curv') or surf_data.endswith('sulc') or
                    surf_data.endswith('thickness')):
                data = nibabel.freesurfer.io.read_morph_data(surf_data)
            elif surf_data.endswith('annot'):
                data = nibabel.freesurfer.io.read_annot(surf_data)[0]
            elif surf_data.endswith('label'):
                data = nibabel.freesurfer.io.read_label(surf_data)
            elif surf_data.endswith('gii'):
                data = gifti.read(surf_data).darrays[gii_darray].data
            else:
                raise ValueError('Format of data file not recognized.')
        # if the input is an array, it should have a single dimension
        elif isinstance(surf_data, np.ndarray):
            data = np.squeeze(surf_data)
            if len(data.shape) is not 1:
                raise ValueError('Data array cannot have more than one dimension.')
        return data
Beispiel #15
0
def get_surface(fname, subject, hemi, trans=None):
    """ Get surface whith a file

    Parameters
    ----------
    fname : str
        Filename of the surface
    subject : str
        Name of the subject
    hemi : 'lh' | 'rh'
        Hemisphere of interest
    trans : str | array | None
        The matrix transformation or the filename to get this

    Returns
    -------
    surface : instance of mne.SourceSpace ?
        Surface source space
    """

    try:
        coords, triangles = mne.read_surface(fname)
    except Exception:
        try:
            giftiImage = gifti.read(fname)

            coords = giftiImage.darrays[0].data
            triangles = giftiImage.darrays[1].data
        except Exception:
            raise Exception('surface file must be in FreeSurfer or BrainVisa format')

    # Apply trans to coords
    coords = compute_trans(coords, trans) ######################
    # coords = tranform(coords, trans)

    # Locations in meters
    coords = coords * 1e-3

    inuse = np.ones(len(coords), dtype=int)
    remains = len(coords)

    vertno = np.where(inuse == 1)[0]

    if hemi == 'lh':
        Id = 101
    elif hemi == 'rh':
        Id = 102

    # Creating surface dict
    surface = {'rr': coords, 'coord_frame': np.array((FIFF.FIFFV_COORD_MRI), np.int32), 'tris': triangles,
               'ntri': len(triangles), 'use_tris': None, 'np': len(coords), 'inuse': inuse, 'nuse_tris': 0,
               'nuse': remains, 'vertno': vertno, 'subject_his_id': subject, 'type': 'surf', 'id': Id,
               'nearest': None, 'dist': None}

    surface = mne.surface.complete_surface_info(surface)

    # Invert normals since BrainVISA surfaces give in-ward pointing dipoles
    surface['nn'] *= -1.

    return surface
def display(fun_dir, fs_dir, contrast):
    mlab.figure(bgcolor=(1, 1, 1))
    left_mesh = freesurfer.read_geometry(os.path.join(fs_dir, 'lh.inflated'))
    right_mesh = freesurfer.read_geometry(os.path.join(fs_dir, 'rh.inflated'))
    left_curv = os.path.join(fs_dir, 'lh.curv')
    right_curv = os.path.join(fs_dir, 'rh.curv')
    meshes = [left_mesh, right_mesh]
    curves = [left_curv, right_curv]
    for hemisphere, mesh_file, curv_file in zip(['lh', 'rh'], meshes, curves):
        fun_file = os.path.join(fun_dir, '%s_z_map_%s.gii' % (
                contrast, hemisphere))
        coords, triangles = mesh_file
        x, y, z = coords.T

        if hemisphere == 'lh':
            x -= 50
        else:
            x += 50

        curv = freesurfer.read_morph_data(curv_file).astype(np.float)
        tex = np.array([darrays.data for darrays in 
                        read(fun_file).darrays]).ravel()
        print fun_file, tex.min(), tex.max()
        name = ''
        cmin = -1
        cmax = 1
        mlab.triangular_mesh(x, y, z, triangles, transparent=True, opacity=1.,
                             name=name, scalars=curv, colormap="bone",
                             vmin=cmin, vmax=cmax)
        func_mesh = mlab.pipeline.triangular_mesh_source(
            x, y, z, triangles, scalars=tex)
        thresh = mlab.pipeline.threshold(func_mesh, low=THRESHOLD)
        mlab.pipeline.surface(thresh, colormap="hot", vmin=THRESHOLD, vmax=7)
    def check_surf_data(self, index, gii_darray=0):

        from nilearn._utils.compat import _basestring
        import nibabel
        import numpy as np

        surf_data = self.backgrounds[index]

        # if the input is a filename, load it
        if isinstance(surf_data, _basestring):
            if (surf_data.endswith('nii') or surf_data.endswith('nii.gz')
                    or surf_data.endswith('mgz')):
                data = np.squeeze(nibabel.load(surf_data).get_data())
            elif (surf_data.endswith('curv') or surf_data.endswith('sulc')
                  or surf_data.endswith('thickness')):
                data = nibabel.freesurfer.io.read_morph_data(surf_data)
            elif surf_data.endswith('annot'):
                data = nibabel.freesurfer.io.read_annot(surf_data)[0]
            elif surf_data.endswith('label'):
                data = nibabel.freesurfer.io.read_label(surf_data)
            elif surf_data.endswith('gii'):
                data = gifti.read(surf_data).darrays[gii_darray].data
            else:
                raise ValueError('Format of data file not recognized.')
        # if the input is an array, it should have a single dimension
        elif isinstance(surf_data, np.ndarray):
            data = np.squeeze(surf_data)
            if len(data.shape) is not 1:
                raise ValueError(
                    'Data array cannot have more than one dimension.')
        return data
Beispiel #18
0
def run_surface_glm(dmtx, contrasts, fmri_path, subject_session_output_dir):
    """ """
    from nibabel.gifti import read, write, GiftiDataArray, GiftiImage
    from nilearn.glm.first_level import run_glm as run_glm_nl
    from nilearn.glm import compute_contrast
    Y = np.array([darrays.data for darrays in read(fmri_path).darrays])
    labels, res = run_glm_nl(Y, dmtx.values)
    # Estimate the contrasts
    print('Computing contrasts...')
    side = fmri_path[-6:-4]
    for index, contrast_id in enumerate(contrasts):
        print('  Contrast % i out of %i: %s' %
              (index + 1, len(contrasts), contrast_id))
        # compute contrasts
        con_ = contrasts[contrast_id]
        contrast_ = compute_contrast(labels, res, con_)
        stats = [
            contrast_.z_score(), contrast_.stat_, contrast_.effect,
            contrast_.variance
        ]
        for map_type, out_map in zip(['z', 't', 'effects', 'variance'], stats):
            map_dir = os.path.join(subject_session_output_dir,
                                   '%s_surf' % map_type)
            if not os.path.exists(map_dir):
                os.makedirs(map_dir)
            map_path = os.path.join(map_dir, '%s_%s.gii' % (contrast_id, side))
            print("\t\tWriting %s ..." % map_path)
            tex = GiftiImage(darrays=[
                GiftiDataArray().from_array(out_map, intent='t test')
            ])
            write(tex, map_path)
def read_surface(filename):
    # load gifti image
    surface = gifti.read(filename)

    # get point set
    points = surface.get_arrays_from_intent('NIFTI_INTENT_POINTSET')[0]

    # get triangle set
    trig = surface.get_arrays_from_intent('NIFTI_INTENT_TRIANGLE')[0]

    # create output dict
    output_dict = {}
    output_dict['vertices'] = []
    output_dict['faces'] = []

    # store data in dict
    for item in points.data:
        dataset = [float(element) for element in item]
        output_dict['vertices'].append(dataset)
    for item in trig.data:
        dataset = [int(element) for element in item]
        output_dict['faces'].append(dataset)

    # return dict
    return output_dict
Beispiel #20
0
def run_from_args(args):
    if args.thickness is not None and args.algorithm != 'line':
        raise ValueError("Optional thickness output only available for the 'line algorithm, not for %s" % args.algorithm)
    white = CorticalMesh.read(args.white)
    pial = CorticalMesh.read(args.pial)
    if args.sulcal_depth is None:
        sd = np.zeros(white.nvertices)
    else:
        sd = gifti.read(args.sulcal_depth).darrays[0].data
    img_mask = nibabel.load(args.mask)
    mask = img_mask.get_data()
    if mask.ndim != 3:
        raise ValueError("Input mask should be 3-dimenasional")

    wo = WeightedOrientation(white, pial, sd, 1., img_mask.affine)
    wo._flip_inpr = args.flip_inpr
    rough = wo.closest_vertex_grid(mask, zval=args.zval, outside_pial=args.outside_pial)
    if args.algorithm == 'closest':
        field = rough
    elif args.algorithm == 'line':
        field, thickness = wo.average_line_grid(mask, norient=args.norient, power_dist=args.power_dist, zval=args.zval)
        # line algorithm might fail for voxels on the edge
        replace = ~np.isfinite(thickness[..., 0])
        field[replace] = rough[replace]
        if args.thickness is not None:
            nibabel.Nifti1Image(thickness, affine=img_mask.affine).to_filename(args.thickness)
    elif args.algorithm == 'interp':
        field = wo.average_point_grid(mask, power_dist=args.power_dist, zval=args.zval, outside_pial=args.outside_pial)
    flipped = align_vector_field(field, rough)
    coords = make_perpendicular(flipped[..., 0], flipped[..., 1])

    nibabel.Nifti1Image(coords, affine=img_mask.affine).to_filename(args.output)
Beispiel #21
0
def get_surface(fname, subject='S4', hemi='lh', trans=None):
    """get surface whith a file

    Parameters
    ----------
    fname : float
        Filename of the surface
    subject : float
        Name of the subject
    hemi : 'lh' | 'rh'
        Hemisphere of interest
    trans : str | array | None
        The matrix transformation or the filename to get this

    Returns
    -------
    surface : instance of Surface
    -------
    Author : Alexandre Fabre
    """

    try:
        coords, triangles = mne.read_surface(fname)
    except Exception:
        try:
            giftiImage = gifti.read(fname)

            coords = giftiImage.darrays[0].data
            triangles = giftiImage.darrays[1].data
        except Exception:
            raise Exception('surface file must be in FreeSurfer or BrainVisa format')

    surface = Surface(coords, triangles, subject=subject, hemi=hemi, trans=trans)

    return surface
Beispiel #22
0
def domain_from_mesh(mesh):
    """Instantiate a StructuredDomain from a gifti mesh

    Parameters
    ----------
    mesh: nibabel gifti mesh instance, or path to such a mesh

    """
    if isinstance(mesh, basestring):
        from nibabel.gifti import read
        mesh_ = read(mesh)
    else:
        mesh_ = mesh

    if len(mesh_.darrays) == 2:
        cor, tri = mesh_.darrays
    elif len(mesh_.darrays) == 3:
        cor, nor, tri = mesh_.darrays
    else:
        raise Exception("%d arrays in gifti file (case not handled)" \
                            % len(mesh_.darrays))
    mesh_dom = MeshDomain(cor.data, tri.data)

    vol = mesh_dom.area()
    topology = mesh_dom.topology()
    dim = 2
    return StructuredDomain(dim, mesh_dom.coord, vol, topology)
Beispiel #23
0
def read_mesh(filename):
    if has_ext_gzsafe(filename, 'gii'):
        mesh_gii = gifti.read(filename)
        cor,tri = (mesh_gii.darrays[0].data, mesh_gii.darrays[1].data)
        return cor,tri,mesh_gii.darrays[0].coordsys
    else:
        raise Exception('Unsupported file format (%s)' %filename)
Beispiel #24
0
def domain_from_mesh(mesh):
    """Instantiate a StructuredDomain from a gifti mesh

    Parameters
    ----------
    mesh: nibabel gifti mesh instance, or path to such a mesh
    """
    if isinstance(mesh, basestring):
        from nibabel.gifti import read
        mesh_ = read(mesh)
    else:
        mesh_ = mesh

    if len(mesh_.darrays) == 2:
        cor, tri = mesh_.darrays
    elif len(mesh_.darrays) == 3:
        cor, nor, tri = mesh_.darrays
    else:
        raise Exception("%d arrays in gifti file (case not handled)" \
                            % len(mesh_.darrays))
    mesh_dom = MeshDomain(cor.data, tri.data)

    vol = mesh_dom.area()
    topology = mesh_dom.topology()
    dim = 2
    return StructuredDomain(dim, mesh_dom.coord, vol, topology)
Beispiel #25
0
def read_mesh(filename):
    if has_ext_gzsafe(filename, 'gii'):
        mesh_gii = gifti.read(filename)
        cor, tri = (mesh_gii.darrays[0].data, mesh_gii.darrays[1].data)
        return cor, tri, mesh_gii.darrays[0].coordsys
    else:
        raise Exception('Unsupported file format (%s)' % filename)
Beispiel #26
0
def loadannot_gifti(parcname,
                    subject,
                    subjects_dir,
                    labnam=None,
                    surf_type='pial',
                    surf_struct=None,
                    quiet=False):

    import numpy as np
    from nibabel import gifti

    fname = os.path.join(subjects_dir, subject, 'label',
                         'lh.%s.%sgii' % (parcname, '%s'))
    fname = match_gifti_intent(fname, 'label')

    annot_lh = gifti.read(parse.hemineutral(fname) % 'lh')
    annot_rh = gifti.read(parse.hemineutral(fname) % 'rh')

    #unpack the annotation data
    labdict_lh = parse.appendhemis(annot_lh.labeltable.get_labels_as_dict(),
                                   "lh_")
    labv_lh = map(labdict_lh.get, annot_lh.darrays[0].data)

    labdict_rh = parse.appendhemis(annot_rh.labeltable.get_labels_as_dict(),
                                   "rh_")
    labv_rh = map(labdict_rh.get, annot_rh.darrays[0].data)

    labv = labv_lh + labv_rh

    #return labv
    #The objective is now to create MNE label files for these on the fly

    vertices = np.vstack((surf_struct.lh_verts, surf_struct.rh_verts))
    mne_labels = []

    for lab in labnam:
        cur_lab_verts = np.flatnonzero(np.array(labv) == lab)
        cur_lab_pos = vertices[cur_lab_verts]

        cur_lab = mne.Label(cur_lab_verts,
                            pos=cur_lab_pos / 1000,
                            hemi=lab[:2],
                            name=parse.demangle_hemi(lab))
        mne_labels.append(cur_lab)

    return mne_labels
Beispiel #27
0
def load_gii(img_path):
  """Load Gifti."""
  try:
    img = gifti.read(img_path)
  except:
    raise NPDLError('Image file ({}) could not be loaded'.format(img))
  img = np.array(map(lambda d: d.data, img.darrays))
  return img
Beispiel #28
0
def test_getbyintent():
    img = gi.read(DATA_FILE1)
    da = img.getArraysFromIntent("NIFTI_INTENT_POINTSET")
    assert_equal(len(da), 1)
    da = img.getArraysFromIntent("NIFTI_INTENT_TRIANGLE")
    assert_equal(len(da), 1)
    da = img.getArraysFromIntent("NIFTI_INTENT_CORREL")
    assert_equal(len(da), 0)
    assert_equal(da, [])
Beispiel #29
0
def test_getbyintent():
    img = gi.read(DATA_FILE1)
    da = img.getArraysFromIntent("NIFTI_INTENT_POINTSET")
    assert_equal(len(da), 1)
    da = img.getArraysFromIntent("NIFTI_INTENT_TRIANGLE")
    assert_equal(len(da), 1)
    da = img.getArraysFromIntent("NIFTI_INTENT_CORREL")
    assert_equal(len(da), 0)
    assert_equal(da, [])
Beispiel #30
0
def test_metadata():

    for i, dat in enumerate(datafiles):

        img = gi.read(dat)
        me = img.get_metadata()
        medat = me.get_metadata()

        assert_equal(numda[i], img.numDA)
        assert_equal(img.version, '1.0')
Beispiel #31
0
def test_metadata():

    for i, dat in enumerate(datafiles):

        img = gi.read(dat)
        me = img.get_metadata()
        medat = me.get_metadata()

        assert_equal(numda[i], img.numDA)
        assert_equal(img.version, "1.0")
def texture_gradient(mesh, texture, mask=None):
    """ Compute the gradient of a given texture at each point of the mesh
        
    Parameters
    ---------
    mesh: string, a path to a mesh file
    texture: string, a path to a texture file
    mask: string, optional, a path to mask texture for that mesh/subject,
          so that only part of the vertices are conssidered.
    Returns
    -------
    gradient: array of shape (mesh.n_vertices, 3) 
    the gradient vector at each mesh node.
       
    fixme
    -----
    Put in mesh_processing
    
    Note
    ----
    the gradient is expressedn in 3D space, note on surface coordinates
    """
    # get coordinates and triangles
    coord, triangles = mesh_arrays(mesh)
    if mask == None:
        mask = np.ones(coord.shape[0]).astype(np.bool)
    else: 
        mask = read(mask).darrays[0].data.astype(np.bool)

    # compute the neighborhood system
    neighb = mesh_to_graph(mesh).to_coo_matrix().tolil().rows

    # read the texture
    y = read(texture).darrays[0].data

    # compute the gradient
    gradient = []
    for i in np.where(mask)[0]:
        yi = y[neighb[i]]
        yi[mask[neighb[i]] == False] = y[i]
        grad = np.linalg.lstsq(coord[neighb[i]], yi)[0]
        gradient.append(grad)
    return np.array(gradient)
Beispiel #33
0
def texture_gradient(mesh, texture, mask=None):
    """ Compute the gradient of a given texture at each point of the mesh

    Parameters
    ---------
    mesh: string, a path to a mesh file
    texture: string, a path to a texture file
    mask: string, optional, a path to mask texture for that mesh/subject,
          so that only part of the vertices are conssidered.
    Returns
    -------
    gradient: array of shape (mesh.n_vertices, 3)
    the gradient vector at each mesh node.

    fixme
    -----
    Put in mesh_processing

    Note
    ----
    the gradient is expressedn in 3D space, note on surface coordinates
    """
    # get coordinates and triangles
    coord, triangles = mesh_arrays(mesh)
    if mask is None:
        mask = np.ones(coord.shape[0]).astype(np.bool)
    else:
        mask = gifti.read(mask).darrays[0].data.astype(np.bool)

    # compute the neighborhood system
    neighb = mesh_to_graph(mesh).to_coo_matrix().tolil().rows

    # read the texture
    y = gifti.read(texture).darrays[0].data

    # compute the gradient
    gradient = []
    for i in np.where(mask)[0]:
        yi = y[neighb[i]]
        yi[mask[neighb[i]] is False] = y[i]
        grad = np.linalg.lstsq(coord[neighb[i]], yi)[0]
        gradient.append(grad)
    return np.array(gradient)
Beispiel #34
0
def extract_ts_from_mesh(mesh_file, num_ts=1200):
    mesh = gi.read(mesh_file)
    data = []

    if (num_ts != len(mesh.darrays)):
        print(len(mesh.darrays))
    assert (num_ts == len(mesh.darrays))
    for i in range(num_ts):
        data.append(mesh.darrays[i].data)
    data = np.asarray(data).T
    return data
Beispiel #35
0
def load_surf_data(surf_data):
    """Loading data to be represented on a surface mesh.

    Parameters
    ----------
    surf_data : str or numpy.ndarray
        Either a file containing surface data (valid format are .gii,
        .gii.gz, .mgz, .nii, .nii.gz, or Freesurfer specific files such as
        .thickness, .curv, .sulc, .annot, .label) or
        a Numpy array containing surface data.
    Returns
    -------
    data : numpy.ndarray
        An array containing surface data
    """
    # if the input is a filename, load it
    if isinstance(surf_data, _basestring):
        if (surf_data.endswith('nii') or surf_data.endswith('nii.gz')
                or surf_data.endswith('mgz')):
            data = np.squeeze(nibabel.load(surf_data).get_data())
        elif (surf_data.endswith('curv') or surf_data.endswith('sulc')
              or surf_data.endswith('thickness')):
            data = nibabel.freesurfer.io.read_morph_data(surf_data)
        elif surf_data.endswith('annot'):
            data = nibabel.freesurfer.io.read_annot(surf_data)[0]
        elif surf_data.endswith('label'):
            data = nibabel.freesurfer.io.read_label(surf_data)
        elif surf_data.endswith('gii'):
            if LooseVersion(nibabel.__version__) >= LooseVersion('2.1.0'):
                gii = nibabel.load(surf_data)
            else:
                gii = gifti.read(surf_data)
            data = _gifti_img_to_data(gii)
        elif surf_data.endswith('gii.gz'):
            gii = _load_surf_files_gifti_gzip(surf_data)
            data = _gifti_img_to_data(gii)
        else:
            raise ValueError(('The input type is not recognized. %r was given '
                              'while valid inputs are a Numpy array or one of '
                              'the following file formats: .gii, .gii.gz, '
                              '.mgz, .nii, .nii.gz, Freesurfer specific files '
                              'such as .curv, .sulc, .thickness, .annot, '
                              '.label') % surf_data)
    # if the input is a numpy array
    elif isinstance(surf_data, np.ndarray):
        data = np.squeeze(surf_data)
    else:
        raise ValueError('The input type is not recognized. '
                         'Valid inputs are a Numpy array or one of the '
                         'following file formats: .gii, .gii.gz, .mgz, .nii, '
                         '.nii.gz, Freesurfer specific files such as .curv, '
                         '.sulc, .thickness, .annot, .label')
    return data
Beispiel #36
0
def load_surf_data(surf_data):
    """Loading data to be represented on a surface mesh.

    Parameters
    ----------
    surf_data : str or numpy.ndarray
        Either a file containing surface data (valid format are .gii,
        .gii.gz, .mgz, .nii, .nii.gz, or Freesurfer specific files such as
        .thickness, .curv, .sulc, .annot, .label) or
        a Numpy array containing surface data.
    Returns
    -------
    data : numpy.ndarray
        An array containing surface data
    """
    # if the input is a filename, load it
    if isinstance(surf_data, _basestring):
        if (surf_data.endswith('nii') or surf_data.endswith('nii.gz') or
                surf_data.endswith('mgz')):
            data = np.squeeze(nibabel.load(surf_data).get_data())
        elif (surf_data.endswith('curv') or surf_data.endswith('sulc') or
                surf_data.endswith('thickness')):
            data = nibabel.freesurfer.io.read_morph_data(surf_data)
        elif surf_data.endswith('annot'):
            data = nibabel.freesurfer.io.read_annot(surf_data)[0]
        elif surf_data.endswith('label'):
            data = nibabel.freesurfer.io.read_label(surf_data)
        elif surf_data.endswith('gii'):
            if LooseVersion(nibabel.__version__) >= LooseVersion('2.1.0'):
                gii = nibabel.load(surf_data)
            else:
                gii = gifti.read(surf_data)
            data = _gifti_img_to_data(gii)
        elif surf_data.endswith('gii.gz'):
            gii = _load_surf_files_gifti_gzip(surf_data)
            data = _gifti_img_to_data(gii)
        else:
            raise ValueError(('The input type is not recognized. %r was given '
                              'while valid inputs are a Numpy array or one of '
                              'the following file formats: .gii, .gii.gz, '
                              '.mgz, .nii, .nii.gz, Freesurfer specific files '
                              'such as .curv, .sulc, .thickness, .annot, '
                              '.label') % surf_data)
    # if the input is a numpy array
    elif isinstance(surf_data, np.ndarray):
        data = np.squeeze(surf_data)
    else:
        raise ValueError('The input type is not recognized. '
                         'Valid inputs are a Numpy array or one of the '
                         'following file formats: .gii, .gii.gz, .mgz, .nii, '
                         '.nii.gz, Freesurfer specific files such as .curv, '
                         '.sulc, .thickness, .annot, .label')
    return data
Beispiel #37
0
def test_labeltable():
    img = gi.read(DATA_FILE6)
    assert_array_almost_equal(img.darrays[0].data[:3], DATA_FILE6_darr1)
    assert_equal(len(img.labeltable.labels), 36)
    labeldict = img.labeltable.get_labels_as_dict()
    assert_true(labeldict.has_key(660700))
    assert_equal(labeldict[660700], u"entorhinal")
    assert_equal(img.labeltable.labels[1].key, 2647065)
    assert_equal(img.labeltable.labels[1].red, 0.0980392)
    assert_equal(img.labeltable.labels[1].green, 0.392157)
    assert_equal(img.labeltable.labels[1].blue, 0.156863)
    assert_equal(img.labeltable.labels[1].alpha, 1)
def smooth_data_as_texture(data, subject, hemi):
    """To smooth the data, save them as texture,
        surfs2surf and extract the data """
    from nibabel.gifti import read, write, GiftiImage, GiftiDataArray as gda
    file_raw = '/tmp/data.gii'
    file_smooth = '/tmp/smooth_data.gii'
    write(GiftiImage(darrays=[gda(data=data.astype('float32'))]), file_raw)
    os.system('$FREESURFER_HOME/bin/mri_surf2surf' +
              ' --srcsubject %s' % subject + ' --srcsurfval %s' % file_raw +
              ' --trgsurfval %s' % file_smooth + ' --trgsubject %s' % subject +
              ' --hemi %s' % hemi + ' --nsmooth-out 2')
    return read(file_smooth).darrays[0].data
Beispiel #39
0
def load_surf_data(surf_data):
    """Loading data to be represented on a surface mesh.

    Parameters
    ----------
    surf_data : str or numpy.ndarray
        Either a file containing surface data (valid format are .gii,
        .mgz, .nii, .nii.gz, or Freesurfer specific files such as
        .thickness, .curv, .sulc, .annot, .label) or
        a Numpy array containing surface data.
    Returns
    -------
    data : numpy.ndarray
        An array containing surface data
    """
    # if the input is a filename, load it
    if isinstance(surf_data, _basestring):
        if (surf_data.endswith('nii') or surf_data.endswith('nii.gz')
                or surf_data.endswith('mgz')):
            data = np.squeeze(nibabel.load(surf_data).get_data())
        elif (surf_data.endswith('curv') or surf_data.endswith('sulc')
              or surf_data.endswith('thickness')):
            data = nibabel.freesurfer.io.read_morph_data(surf_data)
        elif surf_data.endswith('annot'):
            data = nibabel.freesurfer.io.read_annot(surf_data)[0]
        elif surf_data.endswith('label'):
            data = nibabel.freesurfer.io.read_label(surf_data)
        elif surf_data.endswith('gii'):
            gii = gifti.read(surf_data)
            try:
                data = np.zeros((len(gii.darrays[0].data), len(gii.darrays)))
                for arr in range(len(gii.darrays)):
                    data[:, arr] = gii.darrays[arr].data
                data = np.squeeze(data)
            except IndexError:
                raise ValueError('Gifti must contain at least one data array')
        else:
            raise ValueError(('The input type is not recognized. %r was given '
                              'while valid inputs are a Numpy array or one of '
                              'the following file formats: .gii, .mgz, .nii, '
                              '.nii.gz, Freesurfer specific files such as '
                              '.curv, .sulc, .thickness, .annot, '
                              '.label') % surf_data)
    # if the input is a numpy array
    elif isinstance(surf_data, np.ndarray):
        data = np.squeeze(surf_data)
    else:
        raise ValueError('The input type is not recognized. '
                         'Valid inputs are a Numpy array or one of the '
                         'following file formats: .gii, .mgz, .nii, .nii.gz, '
                         'Freesurfer specific files such as .curv,  .sulc, '
                         '.thickness, .annot, .label')
    return data
Beispiel #40
0
def test_correctly_configured_32bit():
    ''' Tests the clustering with many different parameters using 32bit
        TODO: Improve this '''

    cifti_test = './logpar/cli/tests/data/test.dconn.nii'
    l_surf = './logpar/cli/tests/data/L.white.surf.gii'
    r_surf = './logpar/cli/tests/data/R.pial.surf.gii'

    cifti = nibabel.load(cifti_test)

    header = cifti.header
    data = cifti.get_data()[0, 0, 0, 0].astype(numpy.float32)

    output = NamedTemporaryFile(mode='w', delete=True, suffix='.csv').name

    for direction in ["ROW", "COLUMN"]:
        for constraint in [None, l_surf, r_surf]:
            for to_logodds in [True, False]:
                # Result from cifti_parcellate CLI
                cifti_parcellate.cifti_parcellate(cifti_test,
                                                  output,
                                                  direction=direction,
                                                  constraint=constraint,
                                                  to_logodds=to_logodds)
                dendro1 = numpy.loadtxt(output, delimiter=',')

                # Result from clustering function
                test_data = data.copy()
                if direction == 'COLUMN':
                    test_data = test_data.T

                ady_matrix = None
                if constraint is not None:
                    surf = gifti.read(constraint)
                    struc = cifti_utils.principal_structure(surf)
                    off, ind = cifti_utils.surface_attributes(
                        header, struc, direction)
                    test_data = test_data[off:off + len(ind)]

                    ady_matrix = cifti_utils.constraint_from_surface(surf, ind)

                if to_logodds:
                    test_data = transform.to_logodds(test_data, True)

                dendro2 = our_hie.clustering(test_data, constraints=ady_matrix)

                # They should be the same
                try:
                    numpy.testing.assert_almost_equal(dendro1, dendro2)
                except AssertionError:
                    print direction, constraint, to_logodds, ady_matrix
                    raise
Beispiel #41
0
def mesh_arrays(mesh, nibabel=True):
    """ Returns the arrays associated with a mesh
    if len(output)==2, the arrays are coordiantes and triangle lists
    if len(output)==3, the arrays are  coordiantes, triangle lists
    and outer normal
    fixme: use intent !
    """
    if isinstance(mesh, str):
        mesh_ = gifti.read(mesh)
    else:
        mesh_ = mesh
    cor = mesh_.getArraysFromIntent("NIFTI_INTENT_POINTSET")[0].data
    tri = mesh_.getArraysFromIntent("NIFTI_INTENT_TRIANGLE")[0].data
    return cor, tri
def mesh_arrays(mesh, nibabel=True):
   """ Returns the arrays associated with a mesh
   if len(output)==2, the arrays are coordiantes and triangle lists
   if len(output)==3, the arrays are  coordiantes, triangle lists
       and outer normal
   fixme: use intent !
   """
   if isinstance(mesh, basestring):
       mesh_ = read(mesh)
   else:
       mesh_ = mesh
   cor = mesh_.getArraysFromIntent("NIFTI_INTENT_POINTSET")[0].data
   tri = mesh_.getArraysFromIntent("NIFTI_INTENT_TRIANGLE")[0].data
   return cor, tri
Beispiel #43
0
def test_dataarray1():

    img = gi.read(DATA_FILE1)
    assert_array_almost_equal(img.darrays[0].data, DATA_FILE1_darr1)
    assert_array_almost_equal(img.darrays[1].data, DATA_FILE1_darr2)

    me = img.darrays[0].meta.get_metadata()

    assert_true("AnatomicalStructurePrimary" in me)
    assert_true("AnatomicalStructureSecondary" in me)
    assert_equal(me["AnatomicalStructurePrimary"], "CortexLeft")

    assert_array_almost_equal(img.darrays[0].coordsys.xform, np.eye(4, 4))
    assert_equal(gi.xform_codes.niistring[img.darrays[0].coordsys.dataspace], "NIFTI_XFORM_TALAIRACH")
    assert_equal(gi.xform_codes.niistring[img.darrays[0].coordsys.xformspace], "NIFTI_XFORM_TALAIRACH")
Beispiel #44
0
def loadannot_gifti(parcname, subject, subjects_dir, labnam=None, surf_type='pial',
        surf_struct=None, quiet=False):

    import numpy as np
    from nibabel import gifti

    fname = os.path.join(subjects_dir, subject, 'label', 'lh.%s.%sgii'%(parcname,'%s'))
    fname = match_gifti_intent(fname, 'label')

    annot_lh = gifti.read(parse.hemineutral(fname)%'lh')
    annot_rh = gifti.read(parse.hemineutral(fname)%'rh')
    
    #unpack the annotation data
    labdict_lh=parse.appendhemis(annot_lh.labeltable.get_labels_as_dict(),"lh_")
    labv_lh=map(labdict_lh.get,annot_lh.darrays[0].data)

    labdict_rh=parse.appendhemis(annot_rh.labeltable.get_labels_as_dict(),"rh_")
    labv_rh=map(labdict_rh.get,annot_rh.darrays[0].data)

    labv=labv_lh+labv_rh

    #return labv
    #The objective is now to create MNE label files for these on the fly

    vertices = np.vstack((surf_struct.lh_verts, surf_struct.rh_verts))
    mne_labels = []

    for lab in labnam:
        cur_lab_verts = np.flatnonzero(np.array(labv)==lab)
        cur_lab_pos = vertices[cur_lab_verts]

        cur_lab = mne.Label(cur_lab_verts, pos=cur_lab_pos/1000, hemi=lab[:2],
            name = parse.demangle_hemi(lab))
        mne_labels.append(cur_lab)
        
    return mne_labels	
Beispiel #45
0
  def __init__(self, surf_path, max_neighbors=50):
    self.surf_path = surf_path
    try:
      surf = gifti.read(surf_path)
    except:
      raise NPDLError(('Surface: {} does not exist ' +
                       'or is not a valid Gifti file.').format(surf))

    self.coords, self.faces = [surf.darrays[i].data for i in 0, 1]
    self.coords = self.coords.astype(np.float64)
    self.faces = self.faces.astype(np.int32)

    self.num_verts = self.coords.shape[0]
    self.neighbors = self.construct_neighbors(max_neighbors)
    return
Beispiel #46
0
def test_dataarray1():

    img = gi.read(DATA_FILE1)
    assert_array_almost_equal(img.darrays[0].data, DATA_FILE1_darr1)
    assert_array_almost_equal(img.darrays[1].data, DATA_FILE1_darr2)

    me = img.darrays[0].meta.get_metadata()

    assert_true('AnatomicalStructurePrimary' in me)
    assert_true('AnatomicalStructureSecondary' in me)
    assert_equal(me['AnatomicalStructurePrimary'], 'CortexLeft')

    assert_array_almost_equal(img.darrays[0].coordsys.xform, np.eye(4, 4))
    assert_equal(gi.xform_codes.niistring[img.darrays[0].coordsys.dataspace],
                 'NIFTI_XFORM_TALAIRACH')
    assert_equal(gi.xform_codes.niistring[img.darrays[0].coordsys.xformspace],
                 'NIFTI_XFORM_TALAIRACH')
def gii_convert_to_texture(gii_f, out_gii_f=None, meta=None, verbose=0):
    """ Change intent of first data array and create a new Gifti """
    # TODO: verify the that description is good and function is general
    orig_gii = ng.read(gii_f)

    data = orig_gii.darrays[len(orig_gii.darrays) - 1].data[0]
    darray = ng.GiftiDataArray(data=data, intent='NIFTI_INTENT_ESTIMATE')
    gii = ng.GiftiImage(darrays=[darray])

    if meta:
        gii.meta = ng.GiftiMetaData().from_dict(meta)

    out_f = out_gii_f if out_gii_f else gii_f
    ng.write(gii, out_f)

    if verbose > 0:
        print("Texture saved at: {}".format(out_f))
Beispiel #48
0
def read_texture(tex):

    if has_ext_gzsafe(tex, 'gii'):
        #from gifti import loadImage
        #texture = loadImage(tex).arrays[0].data
        tex_gii = gifti.read(tex)
        if len(tex_gii.darrays) > 1: #2D texture ... #TODO: check
            texture = np.vstack([a.data for a in tex_gii.darrays])
        else:
            texture = tex_gii.darrays[0].data
        return texture, tex_gii
    elif has_ext_gzsafe(tex, 'tex'):
        from pyhrf.tools.io.tio import Texture
        texture = Texture.read(tex).data
        return texture, None
    else:
        raise NotImplementedError('Unsupported %s extension' \
                                      %op.splitext(tex)[1])
Beispiel #49
0
def read_texture(tex):

    if has_ext_gzsafe(tex, 'gii'):
        #from gifti import loadImage
        #texture = loadImage(tex).arrays[0].data
        tex_gii = gifti.read(tex)
        if len(tex_gii.darrays) > 1:  # 2D texture ... #TODO: check
            texture = np.vstack([a.data for a in tex_gii.darrays])
        else:
            texture = tex_gii.darrays[0].data
        return texture, tex_gii
    elif has_ext_gzsafe(tex, 'tex'):
        from pyhrf.tools._io.tio import Texture
        texture = Texture.read(tex).data
        return texture, None
    else:
        raise NotImplementedError('Unsupported %s extension'
                                  % op.splitext(tex)[1])
Beispiel #50
0
def test_constraint_matrix():
    ''' Test that the constraint matrix is correctly generated '''
    surf_left = gifti.read('./logpar/cli/tests/data/L.white.surf.gii')

    triangles = surf_left.darrays[1].data
    N = len(surf_left.darrays[0].data)

    ady_matrix = numpy.zeros((N, N), dtype=numpy.int8)

    for (edg1, edg2, edg3) in triangles:
        ady_matrix[edg1, edg2] = ady_matrix[edg2, edg1] = 1
        ady_matrix[edg1, edg3] = ady_matrix[edg3, edg1] = 1
        ady_matrix[edg2, edg3] = ady_matrix[edg3, edg2] = 1

    vertices = numpy.arange(0, N, 2)

    sub_ady_matrix = cifti_utils.constraint_from_surface(surf_left, vertices)

    base = squareform(ady_matrix[vertices[:, None], vertices])

    numpy.testing.assert_equal(sub_ady_matrix, base)
def compute_normal_vertex(mesh, mask=None):
    """ Compute the normal vector at each vertex of the mesh
    
    Parameters
    ---------
    mesh: string, a path to a mesh file

    Returns
    -------
    normals: array of shape (mesh.n_vertices, 3) 
             the normal vector at each mesh node
     mask: string, optional, a path to mask texture for that mesh/subject,
           so that only part of the vertices are conssidered.
    fixme
    -----
    Put in mesh_processing
    """
    # get coordinates and triangles
    coord, triangles = mesh_arrays(mesh)
    if mask == None:
        mask = np.ones(coord.shape[0]).astype(np.bool)
    else: 
        mask = read(mask).darrays[0].data.astype(np.bool)
    
    # compute the normal for each triangle
    norms = np.zeros((mask.size, 3))
    for triangle in triangles:
        if mask[triangle].any():
            sa, sb, sc = triangle
            a = coord[sb] - coord[sa]
            b = coord[sc] - coord[sa]
            norm = vectp(a, b)
            norms[sa] += norm
            norms[sb] += norm
            norms[sc] += norm

    # normalize the normal at each vertex
    eps = 1.e-15
    norms = (norms.T / np.sqrt(eps + np.sum(norms ** 2, 1))).T
    return norms[mask]
def isomap_patch(mesh, mask, show=False):
    """return low-dimensional coordinates for the the patch
    
    Parameters
    ==========
    mesh: string or nibabel mesh,
          the input mesh to be cherted
    mask: string or array of shape (n_vertices)
          a mask for the region of interest on the mesh
    show: boolean, optional,
          if yes, make an image of the coordinates
    """
    from sklearn.manifold.isomap import Isomap
    # Read the data
    coord, tri = mesh_arrays(mesh)
    if isinstance(mask, basestring):
        mask = read(mask).darrays[0].data > 0
    else:
        mask = mask.astype(np.bool)
    coord, tri = coord[mask], tri[mask[tri].all(1)]
    tri = np.hstack((0, np.cumsum(mask)[:-1]))[tri]

    # perform the dimension reduction
    xy = Isomap().fit_transform(coord)

    # try to make the sign invariant and repect the orientations
    xy *= np.sign((xy ** 3).sum(0)) 
    a, b, c = tri[0]
    xy[:, 1] *= np.sign(np.linalg.det(np.vstack((xy[b] - xy[a], xy[c] -xy[a]))))
    
    if show:
        import matplotlib.pyplot as plt
        plt.figure()
        plt.tripcolor(xy.T[0], xy.T[1], tri, (xy ** 2).sum(1), 
                        shading='faceted')
        plt.show()
    return xy
            design_matrix = make_dmtx(
                frametimes, add_regs=reg_matrix, add_reg_names=reg,
                drift_model=drift_model, hfcut=hfcut)

            # plot the design matrix
            ax = design_matrix.show()
            ax.set_position([.05, .25, .9, .65])
            ax.set_title('Design matrix')
            pylab.savefig(os.path.join(write_dir, 'design_matrix_%s.png') %\
                              session)
            # get the data
            if side == False:
                Y, _ = data_scaling(load(fmri_data).get_data()[mask_array].T)
                affine = load(fmri_data).get_affine()
            else:
                Y = np.array([x.data for x in read(fmri_data).darrays])
                Y, _ = data_scaling(Y)
                if sess == 0: # do not redefine the mask later !
                    mask_array = np.var(Y, 0) > 0
                Y = Y[:, mask_array]

            # fit the glm
            print 'Fitting a GLM'
            result = GeneralLinearModel(design_matrix.matrix)
            result.fit(Y, model='ar1', steps=100)

            for contrast_id, contrast_val in contrasts.iteritems():
                if (contrast_val[session] == 0).all():
                    continue
                contrast_obj[contrast_id] =\
                    result.contrast(contrast_val[session])
Beispiel #54
0
def load_surf_mesh(surf_mesh):
    """Loading a surface mesh geometry

    Parameters
    ----------
    surf_mesh : str or numpy.ndarray
        Either a file containing surface mesh geometry (valid formats
        are .gii .gii.gz or Freesurfer specific files such as .orig, .pial,
        .sphere, .white, .inflated) or a list or tuple of two Numpy arrays,
        the first containing the x-y-z coordinates of the mesh
        vertices, the second containing the indices (into coords)
        of the mesh faces.

    Returns
    --------
    [coords, faces] : List of two numpy.ndarray
        The first containing the x-y-z coordinates of the mesh vertices,
        the second containing the indices (into coords) of the mesh faces.
    """
    # if input is a filename, try to load it
    if isinstance(surf_mesh, _basestring):
        # resolve globbing
        file_list = _resolve_globbing(surf_mesh)
        if len(file_list) == 1:
            surf_mesh = file_list[0]
        elif len(file_list) > 1:
            # empty list is handled inside _resolve_globbing function
            raise ValueError(("More than one file matching path: %s \n"
                             "load_surf_mesh can only load one file at a time")
                             % surf_mesh)

        if (surf_mesh.endswith('orig') or surf_mesh.endswith('pial') or
                surf_mesh.endswith('white') or surf_mesh.endswith('sphere') or
                surf_mesh.endswith('inflated')):
            coords, faces = fs.io.read_geometry(surf_mesh)
        elif surf_mesh.endswith('gii'):
            if LooseVersion(nibabel.__version__) >= LooseVersion('2.1.0'):
                gifti_img = nibabel.load(surf_mesh)
            else:
                gifti_img = gifti.read(surf_mesh)
            coords, faces = _gifti_img_to_mesh(gifti_img)
        elif surf_mesh.endswith('.gii.gz'):
            gifti_img = _load_surf_files_gifti_gzip(surf_mesh)
            coords, faces = _gifti_img_to_mesh(gifti_img)
        else:
            raise ValueError(('The input type is not recognized. %r was given '
                              'while valid inputs are one of the following '
                              'file formats: .gii, .gii.gz, Freesurfer '
                              'specific files such as .orig, .pial, .sphere, '
                              '.white, .inflated or a list containing two '
                              'Numpy arrays [vertex coordinates, face indices]'
                              ) % surf_mesh)
    elif isinstance(surf_mesh, (list, tuple)):
        try:
            coords, faces = surf_mesh
        except Exception:
            raise ValueError(('If a list or tuple is given as input, '
                              'it must have two elements, the first is '
                              'a Numpy array containing the x-y-z coordinates '
                              'of the mesh vertices, the second is a Numpy '
                              'array containing  the indices (into coords) of '
                              'the mesh faces. The input was a list with '
                              '%r elements.') % len(surf_mesh))
    else:
        raise ValueError('The input type is not recognized. '
                         'Valid inputs are one of the following file '
                         'formats: .gii, .gii.gz, Freesurfer specific files '
                         'such as .orig, .pial, .sphere, .white, .inflated '
                         'or a list containing two Numpy arrays '
                         '[vertex coordinates, face indices]')

    return [coords, faces]
Beispiel #55
0
def load_surf_data(surf_data):
    """Loading data to be represented on a surface mesh.

    Parameters
    ----------
    surf_data : str or numpy.ndarray
        Either a file containing surface data (valid format are .gii,
        .gii.gz, .mgz, .nii, .nii.gz, or Freesurfer specific files such as
        .thickness, .curv, .sulc, .annot, .label), lists of 1D data files are
        returned as 2D arrays, or
        a Numpy array containing surface data.

    Returns
    -------
    data : numpy.ndarray
        An array containing surface data
    """
    # if the input is a filename, load it
    if isinstance(surf_data, _basestring):

        # resolve globbing
        file_list = _resolve_globbing(surf_data)
        # _resolve_globbing handles empty lists

        for f in range(len(file_list)):
            surf_data = file_list[f]
            if (surf_data.endswith('nii') or surf_data.endswith('nii.gz') or
                    surf_data.endswith('mgz')):
                data_part = np.squeeze(nibabel.load(surf_data).get_data())
            elif (surf_data.endswith('curv') or surf_data.endswith('sulc') or
                    surf_data.endswith('thickness')):
                data_part = fs.io.read_morph_data(surf_data)
            elif surf_data.endswith('annot'):
                data_part = fs.io.read_annot(surf_data)[0]
            elif surf_data.endswith('label'):
                data_part = fs.io.read_label(surf_data)
            elif surf_data.endswith('gii'):
                if LooseVersion(nibabel.__version__) >= LooseVersion('2.1.0'):
                    gii = nibabel.load(surf_data)
                else:
                    gii = gifti.read(surf_data)
                data_part = _gifti_img_to_data(gii)
            elif surf_data.endswith('gii.gz'):
                gii = _load_surf_files_gifti_gzip(surf_data)
                data_part = _gifti_img_to_data(gii)
            else:
                raise ValueError(('The input type is not recognized. %r was '
                                  'given while valid inputs are a Numpy array '
                                  'or one of the following file formats: .gii,'
                                  ' .gii.gz, .mgz, .nii, .nii.gz, Freesurfer '
                                  'specific files such as .curv, .sulc, '
                                  '.thickness, .annot, .label') % surf_data)

            if len(data_part.shape) == 1:
                data_part = data_part[:, np.newaxis]
            if f == 0:
                data = data_part
            elif f > 0:
                try:
                    data = np.concatenate((data, data_part), axis=1)
                except ValueError:
                    raise ValueError('When more than one file is input, all '
                                     'files must contain data with the same '
                                     'shape in axis=0')

    # if the input is a numpy array
    elif isinstance(surf_data, np.ndarray):
        data = surf_data
    else:
        raise ValueError('The input type is not recognized. '
                         'Valid inputs are a Numpy array or one of the '
                         'following file formats: .gii, .gii.gz, .mgz, .nii, '
                         '.nii.gz, Freesurfer specific files such as .curv, '
                         '.sulc, .thickness, .annot, .label')
    return np.squeeze(data)
Beispiel #56
0
def test_dataarray2():
    img2 = gi.read(DATA_FILE2)
    assert_array_almost_equal(img2.darrays[0].data[:10], DATA_FILE2_darr1)
Beispiel #57
0
def test_dataarray5():
    img3 = gi.read(DATA_FILE5)
    assert_array_almost_equal(img3.darrays[0].data, DATA_FILE5_darr1)
    assert_array_almost_equal(img3.darrays[1].data, DATA_FILE5_darr2)
Beispiel #58
0
def test_dataarray4():
    img4 = gi.read(DATA_FILE4)
    assert_array_almost_equal(img4.darrays[0].data[:10], DATA_FILE4_darr1)
Beispiel #59
0
def test_dataarray3():
    img3 = gi.read(DATA_FILE3)
    assert_array_almost_equal(img3.darrays[0].data[30:50], DATA_FILE3_darr1)