Exemple #1
0
    def test_read_default_real_data_tiny(self):
        mesh_file = pyhrf.get_data_file_name('real_data_surf_tiny_mesh.gii')
        bold_file = pyhrf.get_data_file_name('real_data_surf_tiny_bold.gii')
        fn = 'real_data_surf_tiny_parcellation.gii'
        parcel_file = pyhrf.get_data_file_name(fn)

        cor, tri, mesh_gii = pio.read_mesh(mesh_file)
        bold, bold_gii = pio.read_texture(bold_file)
        parcellation, parcel_gii = pio.read_texture(parcel_file)
Exemple #2
0
    def test_read_default_real_data_tiny(self):
        mesh_file = pyhrf.get_data_file_name('real_data_surf_tiny_mesh.gii')
        bold_file = pyhrf.get_data_file_name('real_data_surf_tiny_bold.gii')
        fn = 'real_data_surf_tiny_parcellation.gii'
        parcel_file = pyhrf.get_data_file_name(fn)

        cor, tri, mesh_gii = pio.read_mesh(mesh_file)
        bold, bold_gii = pio.read_texture(bold_file)
        parcellation, parcel_gii = pio.read_texture(parcel_file)
Exemple #3
0
    def load_and_get_fdata_params(self):
        pyhrf.verbose(1,'Load mask from: %s' %self.mask_file)
        if self.data_type == 'surface':
            pyhrf.verbose(2,'Read mesh from: %s' %self.mesh_file)
        p = {'mask' : xndarray.load(self.mask_file).data}
        pyhrf.verbose(1, 'Mask shape %s' %str(p['mask'].shape))

        if self.data_type == 'surface':
            p['graph'] = graph_from_mesh(read_mesh(self.mesh_file))

        return p
Exemple #4
0
    def test_read_default_real_data_tiny(self):
        mesh_file = pyhrf.get_data_file_name('real_data_surf_tiny_mesh.gii')
        bold_file = pyhrf.get_data_file_name('real_data_surf_tiny_bold.gii')
        fn = 'real_data_surf_tiny_parcellation.gii'
        parcel_file = pyhrf.get_data_file_name(fn)

        cor, tri, mesh_gii = pio.read_mesh(mesh_file)
        bold, bold_gii = pio.read_texture(bold_file)
        parcellation, parcel_gii = pio.read_texture(parcel_file)

        if 0:
            print 'cor:', cor.shape, cor.dtype
            print 'tri:', tri.shape, tri.dtype
            print 'bold:', bold.shape, bold.dtype
            print 'parcellation:', parcellation.shape, parcellation.dtype
Exemple #5
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
Exemple #6
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
Exemple #7
0
def load_surf_bold_mask(bold_files, mesh_file, mask_file=None):
    from pyhrf.tools._io import read_mesh, read_texture, discard_bad_data

    logger.info('Load mesh: ' + mesh_file)
    coords, triangles, coord_sys = read_mesh(mesh_file)
    logger.debug('Build graph...')
    fgraph = graph_from_mesh(triangles)
    assert graph_is_sane(fgraph)

    logger.info('Mesh has %d nodes', len(fgraph))

    logger.debug('Compute length of edges ... ')
    edges_l = np.array([np.array([distance(coords[i],
                                           coords[n],
                                           coord_sys.xform)
                                  for n in nl])
                        for i, nl in enumerate(fgraph)], dtype=object)

    if mask_file is None or not op.exists(mask_file):
        logger.warning('Mask file %s does not exist. Taking '
                       'all nodes ...', mask_file)
        mask = np.ones(len(fgraph))
        mask_meta_obj = None
        mask_loaded_from_file = False
    else:
        mask, mask_meta_obj = read_texture(mask_file)
        mask_loaded_from_file = True

    if not (np.round(mask) == mask).all():
        raise Exception("Mask is not n-ary")

    if len(mask) != len(fgraph):
        raise Exception('Size of mask (%d) is different from size '
                        'of graph (%d)' % (len(mask), len(fgraph)))

    mask = mask.astype(np.int32)
    if mask.min() == -1:
        mask += 1

    # Split graph into rois:
    graphs = {}
    edge_lengths = {}
    for roi_id in np.unique(mask):
        mroi = np.where(mask == roi_id)
        graph, _ = sub_graph(fgraph, mroi[0])
        edge_lengths[roi_id] = edges_l[mroi]
        graphs[roi_id] = graph

    # Load BOLD:
    last_scan = 0
    session_scans = []
    bolds = []
    for bold_file in bold_files:
        logger.info('load bold: %s', bold_file)
        bold, _ = read_texture(bold_file)
        logger.info('bold shape: %s', str(bold.shape))
        bolds.append(bold)
        session_scans.append(np.arange(last_scan, last_scan + bold.shape[0],
                                       dtype=int))
        last_scan += bold.shape[0]

    bold = np.concatenate(tuple(bolds))
    if len(fgraph) != bold.shape[1]:
        raise Exception('Nb positions not consistent between BOLD (%d) '
                        'and mesh (%d)' % (bold.shape[1], len(fgraph)))

    # discard bad data (bold with var=0 and nan values):
    discard_bad_data(bold, mask, time_axis=0)

    return mask, mask_meta_obj, mask_loaded_from_file, bold, session_scans, \
        graphs, edge_lengths
Exemple #8
0
def load_surf_bold_mask(bold_files, mesh_file, mask_file=None):
    from pyhrf.tools._io import read_mesh, read_texture, discard_bad_data

    logger.info('Load mesh: ' + mesh_file)
    coords, triangles, coord_sys = read_mesh(mesh_file)
    logger.debug('Build graph...')
    fgraph = graph_from_mesh(triangles)
    assert graph_is_sane(fgraph)

    logger.info('Mesh has %d nodes', len(fgraph))

    logger.debug('Compute length of edges ... ')
    edges_l = np.array([
        np.array([distance(coords[i], coords[n], coord_sys.xform) for n in nl])
        for i, nl in enumerate(fgraph)
    ],
                       dtype=object)

    if mask_file is None or not op.exists(mask_file):
        logger.warning('Mask file %s does not exist. Taking '
                       'all nodes ...', mask_file)
        mask = np.ones(len(fgraph))
        mask_meta_obj = None
        mask_loaded_from_file = False
    else:
        mask, mask_meta_obj = read_texture(mask_file)
        mask_loaded_from_file = True

    if not (np.round(mask) == mask).all():
        raise Exception("Mask is not n-ary")

    if len(mask) != len(fgraph):
        raise Exception('Size of mask (%d) is different from size '
                        'of graph (%d)' % (len(mask), len(fgraph)))

    mask = mask.astype(np.int32)
    if mask.min() == -1:
        mask += 1

    # Split graph into rois:
    graphs = {}
    edge_lengths = {}
    for roi_id in np.unique(mask):
        mroi = np.where(mask == roi_id)
        graph, _ = sub_graph(fgraph, mroi[0])
        edge_lengths[roi_id] = edges_l[mroi]
        graphs[roi_id] = graph

    # Load BOLD:
    last_scan = 0
    session_scans = []
    bolds = []
    for bold_file in bold_files:
        logger.info('load bold: %s', bold_file)
        bold, _ = read_texture(bold_file)
        logger.info('bold shape: %s', str(bold.shape))
        bolds.append(bold)
        session_scans.append(
            np.arange(last_scan, last_scan + bold.shape[0], dtype=int))
        last_scan += bold.shape[0]

    bold = np.concatenate(tuple(bolds))
    if len(fgraph) != bold.shape[1]:
        raise Exception('Nb positions not consistent between BOLD (%d) '
                        'and mesh (%d)' % (bold.shape[1], len(fgraph)))

    # discard bad data (bold with var=0 and nan values):
    discard_bad_data(bold, mask, time_axis=0)

    return mask, mask_meta_obj, mask_loaded_from_file, bold, session_scans, \
        graphs, edge_lengths