Ejemplo n.º 1
0
    def load_and_get_fdata_params(self, sessions_data, mask):
        params = stack_trees([sd.to_dict() for sd in sessions_data])

        fns = params.pop('func_data_file')
        pyhrf.verbose(1, 'Load functional data from: %s' %',\n'.join(fns))
        fdata = stack_cuboids([xndarray.load(fn) for fn in fns], 'session')

        fdata = np.concatenate(fdata.data) #scan sessions along time axis
        pio.discard_bad_data(fdata, mask)
        pyhrf.verbose(1, 'Functional data shape %s' %str(fdata.shape))
        params['func_data'] = fdata

        return params
Ejemplo n.º 2
0
    def load_and_get_fdata_params(self, mask):

        if op.splitext(self.paradigm_file)[-1] == '.csv':
            onsets, durations = pio.load_paradigm_from_csv(self.paradigm_file)
        else:
            raise Exception('Only CSV file format support for paradigm')

        fns = self.func_data_files
        pyhrf.verbose(1, 'Load functional data from: %s' %',\n'.join(fns))
        fdata = stack_cuboids([xndarray.load(fn) for fn in fns], 'session')

        fdata = np.concatenate(fdata.data) #scan sessions along time axis
        pio.discard_bad_data(fdata, mask)
        pyhrf.verbose(1, 'Functional data shape %s' %str(fdata.shape))

        return {'stim_onsets': onsets, 'stim_durations':durations,
                'func_data': fdata}
Ejemplo n.º 3
0
Archivo: core.py Proyecto: Solvi/pyhrf
def load_surf_bold_mask(bold_files, mesh_file, mask_file=None):

    pyhrf.verbose(1, 'Load mesh: ' + mesh_file)
    coords,triangles,coord_sys = read_mesh(mesh_file)
    pyhrf.verbose(2, 'Build graph ... ')
    fgraph = graph_from_mesh(triangles)
    assert graph_is_sane(fgraph)

    pyhrf.verbose(1, 'Mesh has %d nodes' %len(fgraph))

    pyhrf.verbose(2, '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):
        pyhrf.verbose(1,'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 roiId in np.unique(mask):
        mroi = np.where(mask==roiId)
        g, nm = sub_graph(fgraph, mroi[0])
        edge_lengths[roiId] = edges_l[mroi]
        graphs[roiId] = g


    #Load BOLD:
    lastScan = 0
    sessionScans = []
    bolds = []
    for boldFile in bold_files:
        pyhrf.verbose(1, 'load bold: ' + boldFile)
        b,_ = read_texture(boldFile)
        pyhrf.verbose(1, 'bold shape: ' + str(b.shape))
        bolds.append(b)
        sessionScans.append(np.arange(lastScan, lastScan+b.shape[0],
                                      dtype=int))
        lastScan += b.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, sessionScans, \
        graphs, edge_lengths
Ejemplo n.º 4
0
Archivo: core.py Proyecto: Solvi/pyhrf
def load_vol_bold_and_mask(bold_files, mask_file):

    # Handle mask
    if not op.exists(mask_file):
        pyhrf.verbose(1,'Mask file %s does not exist. Mask is '\
                          ' computed from BOLD ...' %mask_file)
        bf = 'subj0_bold_session0.nii.gz'
        # HACK
        if bold_files[0] == pyhrf.get_data_file_name(bf):
            max_frac = .99999 #be sure to keep non zero voxels
            cc = 0 # default BOLD vol has 2 ROIs
        else:
            max_frac = .9
            cc = 1
        compute_mask_files(bold_files[0], mask_file, False, .4,
                           max_frac, cc=cc)
        mask_loaded_from_file = False
    else:
        mask_loaded_from_file = True
        pyhrf.verbose(1,'Assuming orientation for mask file: ' + \
                          string.join(MRI3Daxes, ','))

    pyhrf.verbose(2,'Read mask from: %s' %mask_file)
    mask, mask_meta_obj = read_volume(mask_file)

    if not np.allclose(np.round(mask),mask):
        raise Exception("Mask is not n-ary (%s)" %mask_file)
    mask = mask.astype(np.int32)

    pyhrf.verbose(1,'Mask has shape %s' %str(mask.shape))
    pyhrf.verbose(1,'Mask min value: %d' %mask.min())
    pyhrf.verbose(1,'Mask max value: %d' %mask.max())
    mshape = mask.shape
    if mask.min() == -1:
        mask += 1

    #Load BOLD:
    lastScan = 0
    sessionScans = []
    bolds = []
    pyhrf.verbose(1,'Assuming orientation for BOLD files: ' + \
                      string.join(MRI4Daxes, ','))

    #print 'type of bold_files[0]:', type(bold_files[0])
    #print 'bold_files:', bold_files
    if type(bold_files[0]) is list:
        bold_files = bold_files[0]

    for bold_file in bold_files:
        if not op.exists(bold_file):
            raise Exception('File not found: ' + bold_file)

        b, bold_meta = read_volume(bold_file)
        bolds.append(b)
        sessionScans.append(np.arange(lastScan,
                                      lastScan+b.shape[TIME_AXIS],
                                      dtype=int))
        lastScan += b.shape[TIME_AXIS]

    bold = np.concatenate(tuple(bolds), axis=TIME_AXIS)

    pyhrf.verbose(1,'BOLD has shape %s' %str(bold.shape))
    discard_bad_data(bold, mask)

    # #HACK
    # if mask_file != DEFAULT_MASK_VOL_FILE:
    #     write_volume(mask,'./treated_mask.nii')
    #     sys.exit(0)


    return mask, mask_meta_obj, mask_loaded_from_file, bold, sessionScans