Ejemplo n.º 1
0
def map2gifti(ds, filename=None, encoding='GIFTI_ENCODING_B64GZ'):
    """Maps data(sets) into a GiftiImage, and optionally saves it to disc.

    Parameters
    ----------
    ds : AttrDataset or numpy.ndarray
      The data to be mapepd
    filename : basestring or None, optional
      Filename to which the GiftiImage is stored
    encoding : "ASCII" or "Base64Binary" or "GZipBase64Binary", optional
      Encoding format of data

    Returns
    -------
    img : GiftiImage
      dataset contents represented in GiftiImage
    """

    darrays = []

    if isinstance(ds, np.ndarray):
        samples = ds
    elif isinstance(ds, AttrDataset):
        samples = ds.samples
        _warn_if_fmri_dataset(ds)
    else:
        raise TypeError('first argument must be AttrDataset or numpy.ndarray')

    [nsamples, nfeatures] = samples.shape

    def _get_attribute_value(ds, attr_name, keys_):
        if isinstance(ds, np.ndarray):
            # no attributes
            return None

        attr_collection = ds.__dict__.get(attr_name)

        if isinstance(keys_, basestring):
            keys_ = (keys_, )

        for key in keys_:
            if key in attr_collection:
                return attr_collection[key].value
        return None

    def _build_array(data, intent, encoding=encoding):
        return gifti.GiftiDataArray.from_array(data, intent, encoding=encoding)

    node_indices_labels = ('node_indices', 'center_ids', 'ids', 'roi_ids')
    node_indices = _get_attribute_value(ds, 'fa', node_indices_labels)

    if node_indices is not None:
        darray = _build_array(node_indices, 'NIFTI_INTENT_NODE_INDEX')
        darrays.append(darray)

    intents = _get_attribute_value(ds, 'sa', 'intents')
    for i, sample in enumerate(samples):
        intent = 'NIFTI_INTENT_NONE' if intents is None else intents[i]
        darray = _build_array(sample, intent)
        darrays.append(darray)

    image = gifti.GiftiImage(darrays=darrays)

    if filename is not None:
        giftiio.write(image, filename)

    return image
Ejemplo n.º 2
0
def to_gifti_image(s, add_indices=False, swap_LPI_RAI=False):
    '''
    Converts a surface to nibabel's gifti format.

    Parameters
    ----------
    s: surf
        Input surface
    add_indices: True or False (default: False)
        if True then indices of the nodes are added.
        Note: caret may not be able to read these
    swap_LPI_RAI: True or False (default: False)
        If True then the diagonal elements of the xform matrix
        are set to [-1,-1,1,1], otherwise to [1,1,1,1].


    Returns
    -------
    img: gifti.GiftiImage
        Surface representated as GiftiImage
    '''

    vertices = gifti.GiftiDataArray(np.asarray(s.vertices, np.float32))
    vertices.intent = gifti.intent_codes.field1['pointset']
    vertices.datatype = 16  # this is what gifti likes

    if add_indices:
        nvertices = s.nvertices
        indices = gifti.GiftiDataArray(
            np.asarray(np.arange(nvertices), np.int32))
        indices.datatype = 8  # this is what gifti likes
        indices.coordsys = None  # otherwise SUMA might complain
        indices.intent = gifti.intent_codes.field1['node index']

    faces = gifti.GiftiDataArray(np.asarray(s.faces, np.int32))
    faces.intent = gifti.intent_codes.field1['triangle']
    faces.datatype = 8  # this is what gifti likes
    faces.coordsys = None  # otherwise SUMA might complain

    # set some fields common to faces and vertices
    for arr in (vertices, faces) + ((indices, ) if add_indices else ()):
        arr.ind_ord = 1
        arr.encoding = 3
        arr.endian = 'LittleEndian'  # XXX this does not work (see below)
        arr.dims = list(arr.data.shape)
        if externals.versions['nibabel'] < '2.1':
            # in later versions it is a computed property
            arr.num_dim = len(arr.dims)

    # make the image
    meta = gifti.GiftiMetaData()
    labeltable = gifti.GiftiLabelTable()

    img = gifti.GiftiImage(meta=meta, labeltable=labeltable)

    if swap_LPI_RAI:
        xform = np.asarray(vertices.coordsys.xform)
        xform[0, 0] = -1
        xform[1, 1] = -1
        vertices.coordsys.xform = xform

    if add_indices:
        img.add_gifti_data_array(indices)
    img.add_gifti_data_array(vertices)
    img.add_gifti_data_array(faces)

    return img
Ejemplo n.º 3
0
def map2gifti2(ds,
               filename=None,
               encoding='GIFTI_ENCODING_B64GZ',
               surface=None,
               vertices=None):
    """Maps data(sets) into a GiftiImage, and optionally saves it to disc.
    Parameters
    ----------
    ds : AttrDataset or numpy.ndarray
      The data to be mapepd
    filename : basestring or None, optional
      Filename to which the GiftiImage is stored
    encoding : "ASCII" or "Base64Binary" or "GZipBase64Binary", optional
      Encoding format of data
    surface : mvpa2.surf.nibabel.surf.Surface or str, optional
      Optional anatomical Surface object, or filename of anatomical surface
      file, to be stored together with the data. This should allow
      FreeSurfer's mris_convert to read files written by this function
    Returns
    -------
    img : GiftiImage
      dataset contents represented in GiftiImage
    """

    darrays = []

    if isinstance(ds, np.ndarray):
        samples = ds
    elif isinstance(ds, AttrDataset):
        samples = ds.samples
        _warn_if_fmri_dataset(ds)
    else:
        raise TypeError('first argument must be AttrDataset or numpy.ndarray')

    [nsamples, nfeatures] = samples.shape

    def _get_attribute_value(ds, attr_name, keys_):
        if isinstance(ds, np.ndarray):
            # no attributes
            return None

        attr_collection = ds.__dict__.get(attr_name)

        if isinstance(keys_, basestring):
            keys_ = (keys_, )

        for key in keys_:
            if key in attr_collection:
                return attr_collection[key].value
        return None

    def _build_array(data, intent, encoding=encoding):
        is_integer = intent == 'NIFTI_INTENT_NODE_INDEX'
        dtype = np.int32 if is_integer else np.float32
        arr = gifti.GiftiDataArray(data.astype(dtype),
                                   intent,
                                   encoding=encoding)
        # Setting the coordsys argument the constructor would set the matrix
        # to the 4x4 identity matrix, which is not desired. Instead the
        # coordsys is explicitly set to None afterwards
        arr.coordsys = None

        return arr

    node_indices_labels = ('node_indices', 'center_ids', 'ids', 'roi_ids')
    node_indices = _get_attribute_value(ds, 'fa', node_indices_labels)

    if vertices is not None:
        values = np.zeros((samples.shape[0], vertices))
        for i, sample in enumerate(samples):
            values[i, node_indices] = sample
        #darray = _build_array(np.arange(vertices), 'NIFTI_INTENT_NODE_INDEX')
        #darrays.append(darray)
        samples = values

    else:
        if node_indices is not None:
            darray = _build_array(node_indices, 'NIFTI_INTENT_NODE_INDEX')
            darrays.append(darray)

    intents = _get_attribute_value(ds, 'sa', 'intents')
    for i, sample in enumerate(samples):
        intent = 'NIFTI_INTENT_NONE' if intents is None else intents[i]
        darray = _build_array(sample, intent)
        darrays.append(darray)

    # if there is a surface, add it
    if surface is not None:
        surface_object = surf_from_any(surface, )
        anat_image = anat_surf_to_gifti_image(surface_object,
                                              add_indices=False)

        for darray in anat_image.darrays:
            darrays.append(darray)

    image = gifti.GiftiImage(darrays=darrays)
    if filename is not None:
        nb.save(image, filename)
    return (image)