Пример #1
0
def test_labeltable():
    img = GiftiImage()
    assert_equal(len(img.labeltable.labels), 0)

    new_table = GiftiLabelTable()
    new_table.labels += ['test', 'me']
    img.labeltable = new_table
    assert_equal(len(img.labeltable.labels), 2)
Пример #2
0
def test_labeltable():
    img = GiftiImage()
    assert_equal(len(img.labeltable.labels), 0)

    new_table = GiftiLabelTable()
    new_table.labels += ['test', 'me']
    img.labeltable = new_table
    assert_equal(len(img.labeltable.labels), 2)
Пример #3
0
def write_mesh(cor, tri, filename):
    from nibabel.gifti import GiftiImage, GiftiDataArray
    nimg = GiftiImage()
    intent = 'NIFTI_INTENT_POINTSET'
    nimg.add_gifti_data_array(GiftiDataArray.from_array(cor,intent))
    intent = 'NIFTI_INTENT_TRIANGLE'
    nimg.add_gifti_data_array(GiftiDataArray.from_array(tri,intent))
    gifti.write(nimg, filename)
Пример #4
0
    def write(self, surface_obj, file_path):
        image_metadata = GiftiMetaData().from_dict(
            surface_obj.generic_metadata)
        vertices_metadata = GiftiMetaData().from_dict(
            surface_obj.vertices_metadata)
        triangles_metadata = GiftiMetaData().from_dict(
            surface_obj.triangles_metadata)

        gifti_image = GiftiImage()
        gifti_image.set_metadata(image_metadata)

        data = GiftiDataArray(surface_obj.vertices,
                              datatype='NIFTI_TYPE_FLOAT32',
                              intent='NIFTI_INTENT_POINTSET')
        data.meta = vertices_metadata
        data.coordsys = surface_obj.vertices_coord_system
        gifti_image.add_gifti_data_array(data)

        data = GiftiDataArray(surface_obj.triangles,
                              datatype='NIFTI_TYPE_INT32',
                              intent='NIFTI_INTENT_TRIANGLE')
        data.meta = triangles_metadata
        data.coordsys = None
        gifti_image.add_gifti_data_array(data)

        nibabel.save(gifti_image, file_path)
Пример #5
0
def test_darray_dtype_coercion_failures():
    dtypes = (np.uint8, np.int32, np.int64, np.float32, np.float64)
    encodings = ('ASCII', 'B64BIN', 'B64GZ')
    for data_dtype, darray_dtype, encoding in itertools.product(
            dtypes, dtypes, encodings):
        da = GiftiDataArray(np.arange(10).astype(data_dtype),
                            encoding=encoding,
                            intent='NIFTI_INTENT_NODE_INDEX',
                            datatype=darray_dtype)
        gii = GiftiImage(darrays=[da])
        gii_copy = GiftiImage.from_bytes(gii.to_bytes())
        da_copy = gii_copy.darrays[0]
        assert_equal(np.dtype(da_copy.data.dtype), np.dtype(darray_dtype))
        assert_array_equal(da_copy.data, da.data)
Пример #6
0
def ply2gii(in_file, metadata, out_file=None):
    """Convert from ply to GIfTI"""
    from pathlib import Path
    from numpy import eye
    from nibabel.gifti import (
        GiftiMetaData,
        GiftiCoordSystem,
        GiftiImage,
        GiftiDataArray,
    )
    from pyntcloud import PyntCloud

    in_file = Path(in_file)
    surf = PyntCloud.from_file(str(in_file))

    # Update centroid metadata
    metadata.update(
        zip(
            ("SurfaceCenterX", "SurfaceCenterY", "SurfaceCenterZ"),
            ["%.4f" % c for c in surf.centroid],
        ))

    # Prepare data arrays
    da = (
        GiftiDataArray(
            data=surf.xyz.astype("float32"),
            datatype="NIFTI_TYPE_FLOAT32",
            intent="NIFTI_INTENT_POINTSET",
            meta=GiftiMetaData.from_dict(metadata),
            coordsys=GiftiCoordSystem(xform=eye(4), xformspace=3),
        ),
        GiftiDataArray(
            data=surf.mesh.values,
            datatype="NIFTI_TYPE_INT32",
            intent="NIFTI_INTENT_TRIANGLE",
            coordsys=None,
        ),
    )
    surfgii = GiftiImage(darrays=da)

    if out_file is None:
        out_file = fname_presuffix(in_file.name,
                                   suffix=".gii",
                                   use_ext=False,
                                   newpath=str(Path.cwd()))

    surfgii.to_filename(str(out_file))
    return out_file
Пример #7
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 elementary_contrasts_surf(con_imgs, var_imgs):
    """ """
    from nibabel.gifti import GiftiDataArray, GiftiImage
    outputs = []
    n_contrasts = 4
    for i in range(n_contrasts):
        con = nib.load(con_imgs[i]).darrays[0].data
        var = nib.load(var_imgs[i]).darrays[0].data
        effects = [
            con - nib.load(con_imgs[j]).darrays[0].data
            for j in range(n_contrasts) if j != i
        ]
        variance = [
            var + nib.load(var_imgs[j]).darrays[0].data
            for j in range(n_contrasts) if j != i
        ]

        fixed_con = np.array(effects).sum(0)
        fixed_var = np.array(variance).sum(0)
        stat = fixed_con / np.sqrt(fixed_var)
        output = []
        intents = ['NIFTI_INTENT_ESTIMATE', 'NIFTI_INTENT_ESTIMATE', 't test']
        arrays = [fixed_con, fixed_var, stat]
        for array, intent in zip(arrays, intents):
            gii = GiftiImage(
                darrays=[GiftiDataArray().from_array(array, intent)])
            output.append(gii)
        outputs.append(output)
    return (outputs)
Пример #9
0
def test_data_array_round_trip():
    # Test valid XML generated from new in-memory array
    # See: https://github.com/nipy/nibabel/issues/469
    verts = np.zeros((4, 3), np.float32)
    verts[0, 0] = 10.5
    verts[1, 1] = 20.5
    verts[2, 2] = 30.5

    vertices = GiftiDataArray(verts)
    img = GiftiImage()
    img.add_gifti_data_array(vertices)
    bio = BytesIO()
    fmap = dict(image=FileHolder(fileobj=bio))
    bio.write(img.to_xml())
    bio.seek(0)
    gio = GiftiImage.from_file_map(fmap)
    vertices = gio.darrays[0].data
    assert_array_equal(vertices, verts)
Пример #10
0
def test_labeltable():
    img = GiftiImage()
    assert_equal(len(img.labeltable.labels), 0)

    new_table = GiftiLabelTable()
    new_table.labels += ['test', 'me']
    img.labeltable = new_table
    assert_equal(len(img.labeltable.labels), 2)

    # Test deprecations
    with clear_and_catch_warnings() as w:
        warnings.filterwarnings('always', category=DeprecationWarning)
        newer_table = GiftiLabelTable()
        newer_table.labels += ['test', 'me', 'again']
        img.set_labeltable(newer_table)
        assert_equal(len(w), 1)
        assert_equal(len(img.get_labeltable().labels), 3)
        assert_equal(len(w), 2)
Пример #11
0
def extract_sub_mesh_with_files(input_mesh, center_node, radius, 
                                output_mesh=None):
    from nibabel import gifti
    from nibabel.gifti import GiftiImage, GiftiDataArray
    from pyhrf.tools._io import read_mesh
    cor, tri, coord_sys = read_mesh(input_mesh)
    sub_cor, sub_tri = extract_sub_mesh(cor, tri, center_node, radius)
    
    #nimg = GiftiImage_fromTriangles(sub_cor, sub_tri)
    nimg = GiftiImage()
    intent = 'NIFTI_INTENT_POINTSET'
    nimg.add_gifti_data_array(GiftiDataArray.from_array(sub_cor,intent))
    intent = 'NIFTI_INTENT_TRIANGLE'
    nimg.add_gifti_data_array(GiftiDataArray.from_array(sub_tri,intent))

    if output_mesh is None:
        output_mesh = non_existent_file(add_suffix(input_mesh, '_sub'))
    pyhrf.verbose(1, 'Saving extracted mesh to %s' %output_mesh)
    gifti.write(nimg, output_mesh)
    return sub_cor, sub_tri, coord_sys
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
Пример #13
0
def mesh_from_arrays(coord, triangles, path=None):
    """ Create a mesh object from two arrays

    fixme:  intent should be set !
    """
    carray = GiftiDataArray().from_array(coord.astype(np.float32),
                                         "NIFTI_INTENT_POINTSET")
    tarray = GiftiDataArray().from_array(triangles, "NIFTI_INTENT_TRIANGLE")
    img = GiftiImage(darrays=[carray, tarray])
    if path is not None:
        write(img, path)
    return img
Пример #14
0
def ply2gii(in_file, metadata, out_file=None):
    """Convert from ply to GIfTI"""
    from pathlib import Path
    from numpy import eye
    from nibabel.gifti import (
        GiftiMetaData, GiftiCoordSystem, GiftiImage, GiftiDataArray,
    )
    from pyntcloud import PyntCloud

    in_file = Path(in_file)
    surf = PyntCloud.from_file(str(in_file))

    # Update centroid metadata
    metadata.update(
        zip(('SurfaceCenterX', 'SurfaceCenterY', 'SurfaceCenterZ'),
            ['%.4f' % c for c in surf.centroid])
    )

    # Prepare data arrays
    da = (
        GiftiDataArray(
            data=surf.xyz.astype('float32'),
            datatype='NIFTI_TYPE_FLOAT32',
            intent='NIFTI_INTENT_POINTSET',
            meta=GiftiMetaData.from_dict(metadata),
            coordsys=GiftiCoordSystem(xform=eye(4), xformspace=3)),
        GiftiDataArray(
            data=surf.mesh.values,
            datatype='NIFTI_TYPE_INT32',
            intent='NIFTI_INTENT_TRIANGLE',
            coordsys=None))
    surfgii = GiftiImage(darrays=da)

    if out_file is None:
        out_file = fname_presuffix(
            in_file.name, suffix='.gii', use_ext=False, newpath=str(Path.cwd()))

    surfgii.to_filename(str(out_file))
    return out_file
Пример #15
0
def write_mesh(cor, tri, filename):
    from nibabel.gifti import GiftiImage, GiftiDataArray
    nimg = GiftiImage()
    intent = 'NIFTI_INTENT_POINTSET'
    nimg.add_gifti_data_array(GiftiDataArray.from_array(cor, intent))
    intent = 'NIFTI_INTENT_TRIANGLE'
    nimg.add_gifti_data_array(GiftiDataArray.from_array(tri, intent))
    gifti.write(nimg, filename)
Пример #16
0
def test_gifti_image_bad_inputs():
    img = GiftiImage()
    # Try to set a non-data-array
    assert_raises(TypeError, img.add_gifti_data_array, 'not-a-data-array')

    # Try to set to non-table
    def assign_labeltable(val):
        img.labeltable = val
    assert_raises(TypeError, assign_labeltable, 'not-a-table')

    # Try to set to non-table
    def assign_metadata(val):
        img.meta = val
    assert_raises(TypeError, assign_metadata, 'not-a-meta')
def fixed_effects_surf(con_imgs, var_imgs):
    """Idem fixed_effects_img but for surfaces"""
    from nibabel import load
    from nibabel.gifti import GiftiDataArray, GiftiImage
    con, var = [], []
    for (con_img, var_img) in zip(con_imgs, var_imgs):
        con.append(np.ravel([darrays.data for darrays in load(con_img).darrays]))
        var.append(np.ravel([darrays.data for darrays in load(var_img).darrays]))

    outputs = []
    intents = ['NIFTI_INTENT_ESTIMATE', 'NIFTI_INTENT_ESTIMATE', 't test']
    arrays = fixed_effects(con, var)
    for array, intent in zip(arrays, intents):
        gii = GiftiImage(
            darrays=[GiftiDataArray().from_array(array, intent)])
        outputs.append(gii)
            
    return outputs
Пример #18
0
def test_gifti_image():
    img = GiftiImage()
    assert_true(img.darrays is not None)
    assert_true(img.meta is not None)
    assert_true(img.labeltable is not None)

    # Try to set a non-data-array
    assert_raises(TypeError, img.add_gifti_data_array, 'not-a-data-array')

    # Try to set to non-table
    def assign_labeltable(val):
        img.labeltable = val

    assert_raises(TypeError, assign_labeltable, 'not-a-table')

    # Try to set to non-table
    def assign_metadata(val):
        img.meta = val

    assert_raises(TypeError, assign_metadata, 'not-a-meta')
Пример #19
0
    def write_gifti(self, surface, surface_path):
        gifti_image = GiftiImage()

        data_array = [0 for _ in xrange(2)]
        data_array[0] = surface.vertices
        data_array[1] = surface.triangles

        image_metadata = GiftiMetaData().from_dict(surface.image_metadata)
        vertices_metadata = GiftiMetaData().from_dict(surface.vertices_metadata)
        triangles_metadata = GiftiMetaData().from_dict(surface.triangles_metadata)

        # TODO We currently write metadata of the old surface
        gifti_image.set_metadata(image_metadata)

        data = GiftiDataArray(data_array[0], datatype='NIFTI_TYPE_FLOAT32', intent='NIFTI_INTENT_POINTSET')
        data.meta = vertices_metadata
        data.coordsys = surface.vertices_coord_system
        gifti_image.add_gifti_data_array(data)
        data = GiftiDataArray(data_array[1], datatype='NIFTI_TYPE_INT32', intent='NIFTI_INTENT_TRIANGLE')
        data.meta = triangles_metadata
        data.coordsys = None
        gifti_image.add_gifti_data_array(data)

        nibabel.save(gifti_image, surface_path)
Пример #20
0
    def write(self, surface_obj, file_path):
        image_metadata = GiftiMetaData().from_dict(surface_obj.generic_metadata)
        vertices_metadata = GiftiMetaData().from_dict(surface_obj.vertices_metadata)
        triangles_metadata = GiftiMetaData().from_dict(surface_obj.triangles_metadata)

        gifti_image = GiftiImage()
        gifti_image.set_metadata(image_metadata)

        data = GiftiDataArray(
            surface_obj.vertices, datatype='NIFTI_TYPE_FLOAT32', intent='NIFTI_INTENT_POINTSET')
        data.meta = vertices_metadata
        data.coordsys = surface_obj.vertices_coord_system
        gifti_image.add_gifti_data_array(data)

        data = GiftiDataArray(
            surface_obj.triangles, datatype='NIFTI_TYPE_INT32', intent='NIFTI_INTENT_TRIANGLE')
        data.meta = triangles_metadata
        data.coordsys = None
        gifti_image.add_gifti_data_array(data)

        nibabel.save(gifti_image, file_path)
def save_texture(path, data, intent='none', verbose=False):
    """
    volume saving utility for textures
    
    Parameters
    ----------
    path, string, output image path
    data, array of shape (nnode)
          data to be put in the volume
    intent: string, optional
            intent

    Fixme
    -----
    Missing checks
    Handle the case where data is multi-dimensional ? 
    """
    from nibabel.gifti import write, GiftiDataArray, GiftiImage
    if verbose:
        print 'Warning: assuming a float32 gifti file'
    darray = GiftiDataArray().from_array(data.astype(np.float32), intent)
    img = GiftiImage(darrays=[darray])
    write(img, path)
Пример #22
0
def test_data_array_round_trip():
    # Test valid XML generated from new in-memory array
    # See: https://github.com/nipy/nibabel/issues/469
    verts = np.zeros((4, 3), np.float32)
    verts[0, 0] = 10.5
    verts[1, 1] = 20.5
    verts[2, 2] = 30.5

    vertices = GiftiDataArray(verts)
    img = GiftiImage()
    img.add_gifti_data_array(vertices)
    bio = BytesIO()
    fmap = dict(image=FileHolder(fileobj=bio))
    bio.write(img.to_xml())
    bio.seek(0)
    gio = GiftiImage.from_file_map(fmap)
    vertices = gio.darrays[0].data
    assert_array_equal(vertices, verts)
Пример #23
0
def test_labeltable():
    img = GiftiImage()
    assert_equal(len(img.labeltable.labels), 0)

    new_table = GiftiLabelTable()
    new_table.labels += ['test', 'me']
    img.labeltable = new_table
    assert_equal(len(img.labeltable.labels), 2)

    # Test deprecations
    with clear_and_catch_warnings() as w:
        warnings.filterwarnings('always', category=DeprecationWarning)
        newer_table = GiftiLabelTable()
        newer_table.labels += ['test', 'me', 'again']
        img.set_labeltable(newer_table)
        assert_equal(len(w), 1)
        assert_equal(len(img.get_labeltable().labels), 3)
        assert_equal(len(w), 2)
Пример #24
0
def extract_sub_mesh_with_files(input_mesh,
                                center_node,
                                radius,
                                output_mesh=None):
    from nibabel import gifti
    from nibabel.gifti import GiftiImage, GiftiDataArray
    from pyhrf.tools._io import read_mesh
    cor, tri, coord_sys = read_mesh(input_mesh)
    sub_cor, sub_tri = extract_sub_mesh(cor, tri, center_node, radius)

    #nimg = GiftiImage_fromTriangles(sub_cor, sub_tri)
    nimg = GiftiImage()
    intent = 'NIFTI_INTENT_POINTSET'
    nimg.add_gifti_data_array(GiftiDataArray.from_array(sub_cor, intent))
    intent = 'NIFTI_INTENT_TRIANGLE'
    nimg.add_gifti_data_array(GiftiDataArray.from_array(sub_tri, intent))

    if output_mesh is None:
        output_mesh = non_existent_file(add_suffix(input_mesh, '_sub'))
    logger.info('Saving extracted mesh to %s', output_mesh)
    gifti.write(nimg, output_mesh)
    return sub_cor, sub_tri, coord_sys
    # Compute the fixed effects across sessions
    # quick and dirty approach: sum z maps
    if do_surface:
        for hemi in ['lh', 'rh']:
            z_maps = [
                pjoin(work_dir, acq, 'z_surf',
                      'effects_interest_%s.gii' % hemi) for acq in acqs
            ]

            mean_z = np.mean([
                np.ravel([darrays.data for darrays in load(z_map).darrays])
                for z_map in z_maps
            ], 0)
            n_maps = len(z_maps)
            fixed_effects = mean_z * np.sqrt(n_maps)
            gii = GiftiImage(
                darrays=[GiftiDataArray().from_array(fixed_effects, 't test')])
            gii.to_filename(pjoin(write_dir, 'retinotopicity_%s.gii' % hemi))
            fixed_effects[np.isnan(fixed_effects)] = 0
            bh = fdr_threshold(fixed_effects, alpha)
            print(bh)
            mask = fixed_effects > bh

            # todo: plot on a surface
            """
            output_file = pjoin(write_dir, 'retinotopicity_%s.png' % hemi)
            if hemi == 'lh':
                plot_surf_stat_map(
                    lh_inflated, fixed_effects, bg_map=sulc_left, output_file=output_file,
                    hemi='left', view='medial', bg_on_data=True, darkness=1, alpha=1,
                    threshold=THRESHOLD)
            else:
Пример #26
0
def test_gifti_image():
    # Check that we're not modifying the default empty list in the default
    # arguments.
    gi = GiftiImage()
    assert_equal(gi.darrays, [])
    assert_equal(gi.meta.metadata, {})
    assert_equal(gi.labeltable.labels, [])
    arr = np.zeros((2, 3))
    gi.darrays.append(arr)
    # Now check we didn't overwrite the default arg
    gi = GiftiImage()
    assert_equal(gi.darrays, [])

    # Test darrays / numDA
    gi = GiftiImage()
    assert_equal(gi.numDA, 0)

    # Test from numpy numeric array
    data = np.random.random((5, ))
    da = GiftiDataArray(data)
    gi.add_gifti_data_array(da)
    assert_equal(gi.numDA, 1)
    assert_array_equal(gi.darrays[0].data, data)

    # Test removing
    gi.remove_gifti_data_array(0)
    assert_equal(gi.numDA, 0)

    # Remove from empty
    gi = GiftiImage()
    gi.remove_gifti_data_array_by_intent(0)
    assert_equal(gi.numDA, 0)

    # Remove one
    gi = GiftiImage()
    da = GiftiDataArray(np.zeros((5, )), intent=0)
    gi.add_gifti_data_array(da)

    gi.remove_gifti_data_array_by_intent(3)
    assert_equal(gi.numDA, 1, "data array should exist on 'missed' remove")

    gi.remove_gifti_data_array_by_intent(da.intent)
    assert_equal(gi.numDA, 0)
Пример #27
0
def test_gifti_round_trip():
    # From section 14.4 in GIFTI Surface Data Format Version 1.0
    # (with some adaptations)

    test_data = b'''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE GIFTI SYSTEM "http://www.nitrc.org/frs/download.php/1594/gifti.dtd">
<GIFTI
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.nitrc.org/frs/download.php/1303/GIFTI_Caret.xsd"
Version="1.0"
NumberOfDataArrays="2">
<MetaData>
<MD>
<Name><![CDATA[date]]></Name>
<Value><![CDATA[Thu Nov 15 09:05:22 2007]]></Value>
</MD>
</MetaData>
<LabelTable/>
<DataArray Intent="NIFTI_INTENT_POINTSET"
DataType="NIFTI_TYPE_FLOAT32"
ArrayIndexingOrder="RowMajorOrder"
Dimensionality="2"
Dim0="4"
Dim1="3"
Encoding="ASCII"
Endian="LittleEndian"
ExternalFileName=""
ExternalFileOffset="">
<CoordinateSystemTransformMatrix>
<DataSpace><![CDATA[NIFTI_XFORM_TALAIRACH]]></DataSpace>
<TransformedSpace><![CDATA[NIFTI_XFORM_TALAIRACH]]></TransformedSpace>
<MatrixData>
1.000000 0.000000 0.000000 0.000000
0.000000 1.000000 0.000000 0.000000
0.000000 0.000000 1.000000 0.000000
0.000000 0.000000 0.000000 1.000000
</MatrixData>
</CoordinateSystemTransformMatrix>
<Data>
10.5 0 0
0 20.5 0
0 0 30.5
0 0 0
</Data>
</DataArray>
<DataArray Intent="NIFTI_INTENT_TRIANGLE"
DataType="NIFTI_TYPE_INT32"
ArrayIndexingOrder="RowMajorOrder"
Dimensionality="2"
Dim0="4"
Dim1="3"
Encoding="ASCII"
Endian="LittleEndian"
ExternalFileName="" ExternalFileOffset="">
<Data>
0 1 2
1 2 3
0 1 3
0 2 3
</Data>
</DataArray>
</GIFTI>'''

    exp_verts = np.zeros((4, 3))
    exp_verts[0, 0] = 10.5
    exp_verts[1, 1] = 20.5
    exp_verts[2, 2] = 30.5
    exp_faces = np.asarray([[0, 1, 2], [1, 2, 3], [0, 1, 3], [0, 2, 3]],
                           dtype=np.int32)

    def _check_gifti(gio):
        vertices = gio.get_arrays_from_intent('NIFTI_INTENT_POINTSET')[0].data
        faces = gio.get_arrays_from_intent('NIFTI_INTENT_TRIANGLE')[0].data
        assert_array_equal(vertices, exp_verts)
        assert_array_equal(faces, exp_faces)

    bio = BytesIO()
    fmap = dict(image=FileHolder(fileobj=bio))

    bio.write(test_data)
    bio.seek(0)
    gio = GiftiImage.from_file_map(fmap)
    _check_gifti(gio)
    # Write and read again
    bio.seek(0)
    gio.to_file_map(fmap)
    bio.seek(0)
    gio2 = GiftiImage.from_file_map(fmap)
    _check_gifti(gio2)
Пример #28
0
def test_gifti_image():
    # Check that we're not modifying the default empty list in the default
    # arguments.
    gi = GiftiImage()
    assert_equal(gi.darrays, [])
    arr = np.zeros((2, 3))
    gi.darrays.append(arr)
    # Now check we didn't overwrite the default arg
    gi = GiftiImage()
    assert_equal(gi.darrays, [])

    # Test darrays / numDA
    gi = GiftiImage()
    assert_equal(gi.numDA, 0)

    da = GiftiDataArray(data='data')
    gi.add_gifti_data_array(da)
    assert_equal(gi.numDA, 1)
    assert_equal(gi.darrays[0].data, 'data')

    gi.remove_gifti_data_array(0)
    assert_equal(gi.numDA, 0)

    # Remove from empty
    gi = GiftiImage()
    gi.remove_gifti_data_array_by_intent(0)
    assert_equal(gi.numDA, 0)

    # Remove one
    gi = GiftiImage()
    da = GiftiDataArray(data='data')
    gi.add_gifti_data_array(da)

    gi.remove_gifti_data_array_by_intent(0)
    assert_equal(gi.numDA, 1)

    gi.darrays[0].intent = 0
    gi.remove_gifti_data_array_by_intent(0)
    assert_equal(gi.numDA, 0)
Пример #29
0
def test_data_tag_deprecated():
    img = GiftiImage()
    with clear_and_catch_warnings() as w:
        warnings.filterwarnings('once', category=DeprecationWarning)
        data_tag(np.array([]), 'ASCII', '%i', 1)
        assert_equal(len(w), 1)
Пример #30
0
def test_gifti_image():
    # Check that we're not modifying the default empty list in the default
    # arguments.
    gi = GiftiImage()
    assert_equal(gi.darrays, [])
    arr = np.zeros((2, 3))
    gi.darrays.append(arr)
    # Now check we didn't overwrite the default arg
    gi = GiftiImage()
    assert_equal(gi.darrays, [])

    # Test darrays / numDA
    gi = GiftiImage()
    assert_equal(gi.numDA, 0)

    da = GiftiDataArray(data='data')
    gi.add_gifti_data_array(da)
    assert_equal(gi.numDA, 1)
    assert_equal(gi.darrays[0].data, 'data')

    gi.remove_gifti_data_array(0)
    assert_equal(gi.numDA, 0)

    # Remove from empty
    gi = GiftiImage()
    gi.remove_gifti_data_array_by_intent(0)
    assert_equal(gi.numDA, 0)

    # Remove one
    gi = GiftiImage()
    da = GiftiDataArray(data='data')
    gi.add_gifti_data_array(da)

    gi.remove_gifti_data_array_by_intent(0)
    assert_equal(gi.numDA, 1)

    gi.darrays[0].intent = 0
    gi.remove_gifti_data_array_by_intent(0)
    assert_equal(gi.numDA, 0)
Пример #31
0
def test_gifti_round_trip():
    # From section 14.4 in GIFTI Surface Data Format Version 1.0
    # (with some adaptations)

    test_data = b'''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE GIFTI SYSTEM "http://www.nitrc.org/frs/download.php/1594/gifti.dtd">
<GIFTI
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.nitrc.org/frs/download.php/1303/GIFTI_Caret.xsd"
Version="1.0"
NumberOfDataArrays="2">
<MetaData>
<MD>
<Name><![CDATA[date]]></Name>
<Value><![CDATA[Thu Nov 15 09:05:22 2007]]></Value>
</MD>
</MetaData>
<LabelTable/>
<DataArray Intent="NIFTI_INTENT_POINTSET"
DataType="NIFTI_TYPE_FLOAT32"
ArrayIndexingOrder="RowMajorOrder"
Dimensionality="2"
Dim0="4"
Dim1="3"
Encoding="ASCII"
Endian="LittleEndian"
ExternalFileName=""
ExternalFileOffset="">
<CoordinateSystemTransformMatrix>
<DataSpace><![CDATA[NIFTI_XFORM_TALAIRACH]]></DataSpace>
<TransformedSpace><![CDATA[NIFTI_XFORM_TALAIRACH]]></TransformedSpace>
<MatrixData>
1.000000 0.000000 0.000000 0.000000
0.000000 1.000000 0.000000 0.000000
0.000000 0.000000 1.000000 0.000000
0.000000 0.000000 0.000000 1.000000
</MatrixData>
</CoordinateSystemTransformMatrix>
<Data>
10.5 0 0
0 20.5 0
0 0 30.5
0 0 0
</Data>
</DataArray>
<DataArray Intent="NIFTI_INTENT_TRIANGLE"
DataType="NIFTI_TYPE_INT32"
ArrayIndexingOrder="RowMajorOrder"
Dimensionality="2"
Dim0="4"
Dim1="3"
Encoding="ASCII"
Endian="LittleEndian"
ExternalFileName="" ExternalFileOffset="">
<Data>
0 1 2
1 2 3
0 1 3
0 2 3
</Data>
</DataArray>
</GIFTI>'''

    exp_verts = np.zeros((4, 3))
    exp_verts[0, 0] = 10.5
    exp_verts[1, 1] = 20.5
    exp_verts[2, 2] = 30.5
    exp_faces = np.asarray([[0, 1, 2], [1, 2, 3], [0, 1, 3], [0, 2, 3]],
                           dtype=np.int32)

    def _check_gifti(gio):
        vertices = gio.get_arrays_from_intent('NIFTI_INTENT_POINTSET')[0].data
        faces = gio.get_arrays_from_intent('NIFTI_INTENT_TRIANGLE')[0].data
        assert_array_equal(vertices, exp_verts)
        assert_array_equal(faces, exp_faces)

    bio = BytesIO()
    fmap = dict(image=FileHolder(fileobj=bio))

    bio.write(test_data)
    bio.seek(0)
    gio = GiftiImage.from_file_map(fmap)
    _check_gifti(gio)
    # Write and read again
    bio.seek(0)
    gio.to_file_map(fmap)
    bio.seek(0)
    gio2 = GiftiImage.from_file_map(fmap)
    _check_gifti(gio2)
Пример #32
0
def test_gifti_image():
    # Check that we're not modifying the default empty list in the default
    # arguments.
    gi = GiftiImage()
    assert_equal(gi.darrays, [])
    assert_equal(gi.meta.metadata, {})
    assert_equal(gi.labeltable.labels, [])
    arr = np.zeros((2, 3))
    gi.darrays.append(arr)
    # Now check we didn't overwrite the default arg
    gi = GiftiImage()
    assert_equal(gi.darrays, [])

    # Test darrays / numDA
    gi = GiftiImage()
    assert_equal(gi.numDA, 0)

    # Test from numpy numeric array
    data = np.random.random((5,))
    da = GiftiDataArray(data)
    gi.add_gifti_data_array(da)
    assert_equal(gi.numDA, 1)
    assert_array_equal(gi.darrays[0].data, data)

    # Test removing
    gi.remove_gifti_data_array(0)
    assert_equal(gi.numDA, 0)

    # Remove from empty
    gi = GiftiImage()
    gi.remove_gifti_data_array_by_intent(0)
    assert_equal(gi.numDA, 0)

    # Remove one
    gi = GiftiImage()
    da = GiftiDataArray(np.zeros((5,)), intent=0)
    gi.add_gifti_data_array(da)

    gi.remove_gifti_data_array_by_intent(3)
    assert_equal(gi.numDA, 1, "data array should exist on 'missed' remove")

    gi.remove_gifti_data_array_by_intent(da.intent)
    assert_equal(gi.numDA, 0)
Пример #33
0
def smooth_texture(mesh,
                   input_texture,
                   output_texture=None,
                   sigma=1,
                   lsigma=1.,
                   mask=None):
    """ Smooth a texture along some mesh

   parameters
   ----------
   mesh: string,
         path to gii mesh
   input_texture: string,
                  texture path
   ouput_texture: string,
                  smooth texture path
   sigma: float,
          desired amount of smoothing
   lsigma: float,
           approximate smoothing in one iteration
   mask: string,
         path of a mask texture
   """
    import nipy.algorithms.graph.field as ff

    G = mesh_to_graph(mesh)
    if mask is not None:
        mask = read(mask).darrays[0].data > 0
        G = G.subgraph(mask)
    add_edges = np.vstack((np.arange(G.V), np.arange(G.V))).T
    edges = np.vstack((G.edges, add_edges))
    weights = np.concatenate((G.weights, np.zeros(G.V)))
    weights = np.maximum(np.exp(-weights**2 / (2 * lsigma**2)), 1.e-15)

    f = ff.Field(G.V, edges, weights)
    # need to re-order the edges
    order = np.argsort(f.edges.T[0] * f.V + f.edges.T[1])
    f.edges, f.weights = f.edges[order], f.weights[order]
    f.normalize(0)
    niter = (sigma * 1. / lsigma)**2

    if input_texture[-4:] == '.tex':
        import tio as tio
        data = tio.Texture("").read(input_texture).data
    else:
        data = read(input_texture).darrays[0].data
    if mask is not None:
        data = data[mask]
    dtype = data.dtype
    data[np.isnan(data)] = 0
    f.set_field(data.T)
    f.diffusion(niter)
    data = f.get_field().astype(dtype)

    if output_texture is not None:
        if output_texture[-4:] == '.tex':
            import tio as tio
            tio.Texture("", data=data.T).write(output_texture)
            print 'tex'
        else:
            intent = 0
            wdata = data
            if mask is not None:
                wdata = mask.astype(np.float)
                wdata[mask > 0] = data
            darray = GiftiDataArray().from_array(wdata.astype(np.float32),
                                                 intent)
            img = GiftiImage(darrays=[darray])
            write(img, output_texture)
    return data
def project_volume(work_dir, subject, do_bbr=True):
    # first find the session where T1w and T2w files could be
    ref_file = sorted(
        glob.glob(
            os.path.join(work_dir, subject, 'ses-*', 'anat',
                         '*-highres_T1w.nii*')))[-1]
    # session = ref_file.split('/')[-3]
    anat_dir = os.path.dirname(ref_file)

    write_dir = os.path.join(anat_dir, 'analysis')
    if not os.path.exists(write_dir):
        os.mkdir(write_dir)
    os.environ['SUBJECTS_DIR'] = anat_dir
    data = {}
    for modality in ['T1w', 'T2w']:
        if modality == ['T1w']:
            image = ref_file
        else:
            image = sorted(
                glob.glob(
                    os.path.join(work_dir, subject, 'ses-*', 'anat',
                                 '*-highres_T2w.nii*')))[-1]

        image_ = closing(image)

        # --------------------------------------------------------------------
        # run the projection using freesurfer
        print("image", image)
        basename = os.path.basename(image).split('.')[0]

        if modality == 'T1w':
            bbreg = BBRegister(subject_id=subject,
                               source_file=image,
                               init='header',
                               contrast_type='t1')
        else:
            # use BBR registration to finesse the coregistration
            bbreg = BBRegister(subject_id=subject,
                               source_file=image,
                               init='header',
                               contrast_type='t2')

        regheader = os.path.join(anat_dir,
                                 basename + '_bbreg_%s.dat' % subject)
        bbreg.run()

        if 1:
            # output names
            # the .gii files will be put in the same directory as the input
            left_tex = os.path.join(write_dir, basename + '_lh.gii')
            right_tex = os.path.join(write_dir, basename + '_rh.gii')

            # run freesrufer command for projection
            os.system(
                '$FREESURFER_HOME/bin/mri_vol2surf --src %s --o %s '
                '--out_type gii --srcreg %s --hemi lh --projfrac-avg 0 1 0.1' %
                (image_, left_tex, regheader))

            os.system(
                '$FREESURFER_HOME/bin/mri_vol2surf --src %s --o %s '
                '--out_type gii --srcreg %s --hemi rh --projfrac-avg 0 1 0.1' %
                (image_, right_tex, regheader))

            # resample to fsaverage
            left_smooth_tex = os.path.join(write_dir,
                                           basename + '_fsaverage_lh.gii')
            right_smooth_tex = os.path.join(write_dir,
                                            basename + '_fsaverage_rh.gii')

            os.system('$FREESURFER_HOME/bin/mri_surf2surf --srcsubject %s '
                      '--srcsurfval %s --trgsurfval %s --trgsubject ico '
                      '--trgicoorder 7 --hemi lh' %
                      (subject, left_tex, left_smooth_tex))
            os.system('$FREESURFER_HOME/bin/mri_surf2surf --srcsubject %s '
                      '--srcsurfval %s --trgsubject ico --trgicoorder 7 '
                      '--trgsurfval %s --hemi rh' %
                      (subject, right_tex, right_smooth_tex))
            data[modality] = {
                'lh': nib.load(left_smooth_tex).darrays[0].data,
                'rh': nib.load(right_smooth_tex).darrays[0].data
            }
        else:
            from surfer import project_volume_data
            data[modality] = {}
            for hemi in ['lh', 'rh']:
                data_ = project_volume_data(image_,
                                            hemi,
                                            regheader,
                                            projarg=[0, 1., .1],
                                            smooth_fwhm=0)
                data[modality][hemi] = data_

    # reset subject_dir to set fsaverage
    os.environ['SUBJECTS_DIR'] = os.path.join(work_dir, subject, 'ses-00',
                                              'anat')
    for hemi in ['lh', 'rh']:
        ratio = data['T1w'][hemi] / data['T2w'][hemi]
        from nibabel.gifti import write, GiftiImage, GiftiDataArray as gda
        file_ratio = os.path.join(write_dir, 't1_t2_ratio_%s.gii' % hemi)
        write(GiftiImage(darrays=[gda(data=ratio.astype('float32'))]),
              file_ratio)
        """