Beispiel #1
0
 def save_time_series(k):
     if simulation.has_key(k):
         fn_stim_induced = add_prefix(op.join(output_dir, k + '.nii'),
                                      prefix)
         logger.info('%s flat shape %s', k, str(simulation[k].shape))
         vol = expand_array_in_mask(simulation[k], mask_vol, flat_axis=1)
         write_volume(np.rollaxis(vol, 0, 4), fn_stim_induced)
Beispiel #2
0
 def save_time_series(k):
     if simulation.has_key(k):
         fn_stim_induced = add_prefix(
             op.join(output_dir, k + '.nii'), prefix)
         logger.info('%s flat shape %s', k, str(simulation[k].shape))
         vol = expand_array_in_mask(simulation[k], mask_vol, flat_axis=1)
         write_volume(np.rollaxis(vol, 0, 4), fn_stim_induced)
Beispiel #3
0
 def __init__(self, outputPrefix='', roiAverage=False, pass_error=True):
     xmlio.XMLable2.__init__(self)
     if len(outputPrefix) == 0: outputPrefix = 'pyhrf_'
     self.outPrefix = outputPrefix
     self.outFile = add_prefix('outputs.xml', self.outPrefix)
     self.roiAverage = roiAverage
     self.pass_error = pass_error
Beispiel #4
0
    def make_outputs_single_subject(self, data_rois, irois, all_outputs,
                                    targetAxes, ext, meta_data, output_dir):

        coutputs = {}
        output_fns = []

        roi_masks = [(data_roi.roiMask != data_roi.backgroundLabel)
                     for data_roi in data_rois]
        np_roi_masks = [np.where(roi_mask) for roi_mask in roi_masks]

        for output_name, roi_outputs in all_outputs.iteritems():
            logger.info('Merge output %s ...', output_name)
            try:
                if roi_outputs[0].has_axis('voxel'):
                    logger.debug('Merge as expansion ...')
                    dest_c = None
                    for i_roi, c in enumerate(roi_outputs):
                        dest_c = c.expand(roi_masks[i_roi],
                                          'voxel', targetAxes,
                                          dest=dest_c, do_checks=False,
                                          m=np_roi_masks[i_roi])
                else:
                    logger.debug('Merge as stack (%d elements)...', len(irois))
                    c_to_stack = [roi_outputs[i] for i in np.argsort(irois)]
                    # print 'c_to_stack:', c_to_stack
                    # print 'sorted(irois):', sorted(irois)
                    dest_c = stack_cuboids(c_to_stack, domain=sorted(irois),
                                           axis='ROI')
            except Exception, e:
                print "Could not merge outputs for %s" % output_name
                print "Exception was:"
                print e
                # raise e #stop here
            if 0 and dest_c is not None:
                print '-> ', dest_c.data.shape
            output_fn = op.join(output_dir, output_name + ext)
            output_fn = add_prefix(output_fn, self.outPrefix)
            output_fns.append(output_fn)
            logger.debug('Save output %s to %s', output_name, output_fn)
            try:
                if dest_c.meta_data:
                    tmp_meta_data = (meta_data[0], meta_data[1].copy())
                    tmp_meta_data[1]["descrip"] = dest_c.meta_data[1]["descrip"]
                    dest_c.meta_data = tmp_meta_data
                    dest_c.save(output_fn, set_MRI_orientation=True)
                else:
                    dest_c.save(output_fn, meta_data=meta_data,
                                set_MRI_orientation=True)
            except Exception:
                print 'Could not save output "%s", error stack was:' \
                    % output_name
                exc_type, exc_value, exc_traceback = sys.exc_info()
                traceback.print_exception(exc_type, exc_value, exc_traceback,
                                          limit=4, file=sys.stdout)
            coutputs[output_name] = dest_c
Beispiel #5
0
 def __init__(self,
              outputPrefix='',
              roiAverage=False,
              pass_error=True,
              gzip_outputs=False):
     xmlio.XmlInitable.__init__(self)
     if len(outputPrefix) == 0:
         outputPrefix = 'pyhrf_'
     self.outPrefix = outputPrefix
     self.outFile = add_prefix('outputs.xml', self.outPrefix)
     self.roiAverage = roiAverage
     self.pass_error = pass_error
     self.gzip_outputs = gzip_outputs
Beispiel #6
0
def make_outfile(fn, path, pre='', suf=''):
    if fn is None or path is None:
        return None
    ofn = op.join(path, fn)
    return add_prefix(add_suffix(ofn, suf), pre)
Beispiel #7
0
from pyhrf.ui.jde import DEFAULT_CFG_FILE as DEFAULT_CFG_FILE_JDE

from pyhrf.jde.models import BOLDGibbsSampler as BG


from pyhrf.jde.beta import BetaSampler as BS
from pyhrf.jde.nrl.bigaussian import NRLSampler as NS
from pyhrf.jde.nrl.trigaussian import GGGNRLSampler as NS3
from pyhrf.jde.hrf import RHSampler as HVS
from pyhrf.jde.hrf import HRFSampler as HS

#VT = FMRIVolumeTreatment
#ST = FMRISurfaceTreatment

DEFAULT_JDE_OUT_MASK_VOL = add_prefix(DEFAULT_OUT_MASK_VOL_FILE, 'jde_')
DEFAULT_JDE_OUT_MASK_SURF = add_prefix(DEFAULT_OUT_MASK_SURF_FILE, 'jde_')

def make_outfile(fn, path, pre='', suf=''):
    if fn is None or path is None:
        return None
    ofn = op.join(path, fn)
    return add_prefix(add_suffix(ofn, suf), pre)

def create_treatment(boldFiles, parcelFile, dt, tr, paradigmFile,
                     nbIterations=4000,
                     writeXmlSetup=True, parallelize=False,
                     outputDir=None, outputSuffix=None, outputPrefix=None,
                     contrasts=None, beta=.6, estimBeta=True,
                     pfMethod='ps', estimHrf=True, hrfVar=.01,
                     roiIds=None,
Beispiel #8
0
    def make_outputs_multi_subjects(self, data_rois, irois, all_outputs,
                                    targetAxes, ext, meta_data, output_dir):

        coutputs = {}
        output_fns = []

        roi_masks = [[(ds.roiMask != ds.backgroundLabel)
                      for ds in dr.data_subjects]
                     for dr in data_rois]
        #-> roi_masks[roi_id][subject]

        np_roi_masks = [[np.where(roi_subj_mask)
                         for roi_subj_mask in roi_subj_masks]
                        for roi_subj_masks in roi_masks]
        #-> np_roi_masks[roi_id][subject]

        for output_name, roi_outputs in all_outputs.iteritems():
            logger.info('Merge output %s ...', output_name)
            dest_c = {}
            try:
                if roi_outputs[0].has_axis('voxel'):
                    if not roi_outputs[0].has_axis('subject'):
                        raise Exception('Voxel-mapped output "%s" does not'
                                        'have a subject axis')
                    logger.debug('Merge as expansion ...')
                    dest_c_tmp = None
                    for isubj in roi_outputs[0].get_domain('subject'):
                        for i_roi, c in enumerate(roi_outputs):
                            m = np_roi_masks[i_roi][isubj]
                            dest_c_tmp = c.expand(roi_masks[i_roi][isubj],
                                                  'voxel', targetAxes,
                                                  dest=dest_c_tmp,
                                                  do_checks=False,
                                                  m=m)
                    dest_c[output_name] = dest_c_tmp
                else:
                    logger.debug('Merge as stack (%d elements)...', len(irois))
                    c_to_stack = [roi_outputs[i] for i in np.argsort(irois)]
                    dest_c[output_name] = stack_cuboids(c_to_stack,
                                                        domain=sorted(irois),
                                                        axis='ROI')
            except Exception, e:
                logger.error("Could not merge outputs for %s", output_name)
                logger.error("Exception was:")
                logger.error(e)

            for output_name, c in dest_c.iteritems():
                output_fn = op.join(output_dir, output_name + ext)
                output_fn = add_prefix(output_fn, self.outPrefix)
                output_fns.append(output_fn)
                logger.debug('Save output %s to %s', output_name, output_fn)
                try:
                    c.save(output_fn, meta_data=meta_data,
                           set_MRI_orientation=True)
                except Exception:
                    print 'Could not save output "%s", error stack was:' \
                        % output_name
                    exc_type, exc_value, exc_traceback = sys.exc_info()
                    traceback.print_exception(exc_type, exc_value,
                                              exc_traceback,
                                              limit=4, file=sys.stdout)
                coutputs[output_name] = c
Beispiel #9
0
def simulation_save_vol_outputs(simulation,
                                output_dir,
                                bold_3D_vols_dir=None,
                                simulation_graph_output=None,
                                prefix=None,
                                vol_meta=None):
    """ simulation_graph_output : None, 'simple', 'thumbnails' #TODO
    """

    if simulation.has_key('paradigm'):
        fn = add_prefix(op.join(output_dir, 'paradigm.csv'), prefix)
        simulation['paradigm'].save_csv(fn)

    # Save all volumes in nifti format:
    if simulation.has_key('labels_vol'):
        mask_vol = np.ones_like(simulation['labels_vol'][0])
    elif simulation.has_key('mask'):
        mask_vol = simulation.get('mask', None)
    elif simulation.has_key('labels'):
        mask_vol = np.ones_like(simulation['labels'][0])
    else:
        raise Exception('Dunno where to get mask')

    logger.info('Vol mask of shape %s', str(mask_vol.shape))

    fn_mask = add_prefix(op.join(output_dir, 'mask.nii'), prefix)
    write_volume(mask_vol.astype(np.int32), fn_mask, vol_meta)

    if simulation.has_key('hrf_territories'):
        fn_h_territories = add_prefix(
            op.join(output_dir, 'hrf_territories.nii'), prefix)

        ht = expand_array_in_mask(simulation['hrf_territories'] + 1, mask_vol)
        write_volume(ht, fn_h_territories, vol_meta)

    if simulation.has_key('hrf'):
        from pyhrf.ndarray import MRI3Daxes
        fn_hrf = add_prefix(op.join(output_dir, 'hrf.nii'), prefix)
        logger.info('hrf flat shape %s', str(simulation['hrf'].shape))
        if simulation['hrf'].ndim == 1:
            hrf = (np.ones(mask_vol.size) * simulation['hrf'][:, np.newaxis])
        else:
            hrf = simulation['hrf']

        hrfs_vol = expand_array_in_mask(hrf, mask_vol, flat_axis=1)
        dt = simulation['dt']
        chrfs = xndarray(
            hrfs_vol,
            axes_names=[
                'time',
            ] + MRI3Daxes,
            axes_domains={'time': np.arange(hrfs_vol.shape[0]) * dt})
        chrfs.save(fn_hrf, vol_meta)

        ttp_vol = hrfs_vol.argmax(0)
        fn_ttp = add_prefix(op.join(output_dir, 'ttp.nii'), prefix)
        write_volume(ttp_vol, fn_ttp, vol_meta)

    if simulation.has_key('brf'):
        from pyhrf.ndarray import MRI3Daxes
        fn_brf = add_prefix(op.join(output_dir, 'brf.nii'), prefix)
        logger.info('brf flat shape %s', str(simulation['brf'].shape))
        brfs_vol = expand_array_in_mask(simulation['brf'],
                                        mask_vol,
                                        flat_axis=1)
        dt = simulation['dt']
        cbrfs = xndarray(
            brfs_vol,
            axes_names=[
                'time',
            ] + MRI3Daxes,
            axes_domains={'time': np.arange(brfs_vol.shape[0]) * dt})
        cbrfs.save(fn_brf, vol_meta)

    if simulation.has_key('prf'):
        from pyhrf.ndarray import MRI3Daxes
        fn_brf = add_prefix(op.join(output_dir, 'prf.nii'), prefix)
        logger.info('prf flat shape %s', str(simulation['prf'].shape))
        brfs_vol = expand_array_in_mask(simulation['prf'],
                                        mask_vol,
                                        flat_axis=1)
        dt = simulation['dt']
        cbrfs = xndarray(
            brfs_vol,
            axes_names=[
                'time',
            ] + MRI3Daxes,
            axes_domains={'time': np.arange(brfs_vol.shape[0]) * dt})
        cbrfs.save(fn_brf, vol_meta)

    if simulation.has_key('drift'):
        fn_drift = add_prefix(op.join(output_dir, 'drift.nii'), prefix)
        logger.info('drift flat shape %s', str(simulation['drift'].shape))
        drift_vol = expand_array_in_mask(simulation['drift'],
                                         mask_vol,
                                         flat_axis=1)
        write_volume(np.rollaxis(drift_vol, 0, 4), fn_drift)

    if simulation.has_key('drift_coeffs'):
        fn_drift = add_prefix(op.join(output_dir, 'drift_coeffs.nii'), prefix)
        logger.info('drift flat shape %s',
                    str(simulation['drift_coeffs'].shape))
        drift_vol = expand_array_in_mask(simulation['drift'],
                                         mask_vol,
                                         flat_axis=1)
        write_volume(np.rollaxis(drift_vol, 0, 4), fn_drift)

    if simulation.has_key('noise'):
        fn_noise = add_prefix(op.join(output_dir, 'noise.nii'), prefix)
        logger.info('noise flat shape %s', str(simulation['noise'].shape))
        noise_vol = expand_array_in_mask(simulation['noise'],
                                         mask_vol,
                                         flat_axis=1)
        write_volume(np.rollaxis(noise_vol, 0, 4), fn_noise, vol_meta)

        fn_noise = add_prefix(op.join(output_dir, 'noise_emp_var.nii'), prefix)
        noise_vol = expand_array_in_mask(simulation['noise'].var(0), mask_vol)
        write_volume(noise_vol, fn_noise, vol_meta)

    if simulation.has_key('noise_var'):
        fn_noise_var = add_prefix(op.join(output_dir, 'noise_var.nii'), prefix)
        logger.info('noise_var flat shape %s',
                    str(simulation['noise_var'].shape))
        noise_var_vol = expand_array_in_mask(simulation['noise_var'], mask_vol)
        write_volume(noise_var_vol, fn_noise_var, vol_meta)

    if simulation.has_key('stim_induced_signal'):
        fn_stim_induced = add_prefix(op.join(output_dir, 'stim_induced.nii'),
                                     prefix)
        logger.info('stim_induced flat shape %s',
                    str(simulation['stim_induced_signal'].shape))
        stim_induced_vol = expand_array_in_mask(
            simulation['stim_induced_signal'], mask_vol, flat_axis=1)
        write_volume(np.rollaxis(stim_induced_vol, 0, 4), fn_stim_induced)

    if simulation.has_key('perf_stim_induced'):
        fn_stim_induced = add_prefix(
            op.join(output_dir, 'perf_stim_induced.nii'), prefix)
        logger.info('asl_stim_induced flat shape %s',
                    str(simulation['perf_stim_induced'].shape))
        stim_induced_vol = expand_array_in_mask(
            simulation['perf_stim_induced'], mask_vol, flat_axis=1)
        write_volume(np.rollaxis(stim_induced_vol, 0, 4), fn_stim_induced)

        fn_stim_induced = add_prefix(
            op.join(output_dir, 'perf_stim_induced_ct.nii'), prefix)
        logger.info('asl_stim_induced flat shape %s',
                    str(simulation['perf_stim_induced'].shape))

        dsf = simulation['dsf']
        perf = np.dot(simulation['ctrl_tag_mat'],
                      simulation['perf_stim_induced'][0:-1:dsf])
        stim_induced_vol = expand_array_in_mask(perf, mask_vol, flat_axis=1)
        write_volume(np.rollaxis(stim_induced_vol, 0, 4), fn_stim_induced)

    if simulation.has_key('perf_baseline'):
        fn = add_prefix(op.join(output_dir, 'perf_baseline.nii'), prefix)
        pb = np.zeros_like(simulation['bold']) + simulation['perf_baseline']
        write_volume(expand_array_in_mask(pb[0], mask_vol), fn, vol_meta)

    if simulation.has_key('bold_stim_induced'):
        fn_stim_induced = add_prefix(
            op.join(output_dir, 'bold_stim_induced.nii'), prefix)
        logger.info('asl_stim_induced flat shape %s',
                    str(simulation['bold_stim_induced'].shape))
        stim_induced_vol = expand_array_in_mask(
            simulation['bold_stim_induced'], mask_vol, flat_axis=1)
        write_volume(np.rollaxis(stim_induced_vol, 0, 4), fn_stim_induced)

    m = np.where(mask_vol)
    labels_and_mask = mask_vol.copy()[m]

    for ic in xrange(simulation['labels'].shape[0]):
        if simulation.has_key('condition_defs'):
            c_name = simulation['condition_defs'][ic].name
        else:
            c_name = 'cond%d' % ic
        fn_labels = add_prefix(op.join(output_dir, 'labels_%s.nii' % c_name),
                               prefix)
        if simulation.has_key('labels'):
            labels_c = simulation['labels'][ic]
            labels_and_mask[np.where(labels_c)] = ic + 2
            write_volume(
                expand_array_in_mask(labels_c, mask_vol).astype(np.int32),
                fn_labels, vol_meta)
        elif simulation.has_key('labels_vol'):
            labels_c = simulation['labels_vol'][ic]
            labels_and_mask[np.where(labels_c[m])] = ic + 2
            write_volume(labels_c.astype(np.int32), fn_labels, vol_meta)

        if simulation.has_key('nrls'):
            nrls_c = simulation['nrls'][ic]
            fn = add_prefix(op.join(output_dir, 'nrls_%s.nii' % c_name),
                            prefix)
            write_volume(expand_array_in_mask(nrls_c, mask_vol), fn, vol_meta)
        if simulation.has_key('nrls_session'):
            nrls_session_c = simulation['nrls_session'][ic]
            fn = add_prefix(
                op.join(output_dir, 'nrls_session_%s.nii' % (c_name)), prefix)
            write_volume(expand_array_in_mask(nrls_session_c, mask_vol), fn,
                         vol_meta)

        if simulation.has_key('brls'):
            brls_c = simulation['brls'][ic]
            fn = add_prefix(op.join(output_dir, 'brls_%s.nii' % c_name),
                            prefix)
            write_volume(expand_array_in_mask(brls_c, mask_vol), fn, vol_meta)
        if simulation.has_key('prls'):
            prls_c = simulation['prls'][ic]
            fn = add_prefix(op.join(output_dir, 'prls_%s.nii' % c_name),
                            prefix)
            write_volume(expand_array_in_mask(prls_c, mask_vol), fn, vol_meta)

        if simulation.has_key('neural_efficacies'):
            ne_c = simulation['neural_efficacies'][ic]
            fn = add_prefix(
                op.join(output_dir, 'neural_efficacies_%s.nii' % c_name),
                prefix)
            write_volume(expand_array_in_mask(ne_c, mask_vol), fn, vol_meta)

    fn_labels_and_mask = add_prefix(op.join(output_dir, 'mask_and_labels.nii'),
                                    prefix)

    write_volume(
        expand_array_in_mask(labels_and_mask, mask_vol).astype(int),
        fn_labels_and_mask, vol_meta)

    if simulation.has_key('bold_full_vol') or simulation.has_key('bold'):
        fn = add_prefix(op.join(output_dir, 'bold.nii'), prefix)
        if simulation.has_key('bold_full_vol'):
            bold4D = simulation['bold_full_vol']
        else:
            bold = simulation['bold']
            bold4D = expand_array_in_mask(bold, mask_vol, flat_axis=1)

        write_volume(np.rollaxis(bold4D, 0, 4), fn, vol_meta)

    def save_time_series(k):
        if simulation.has_key(k):
            fn_stim_induced = add_prefix(op.join(output_dir, k + '.nii'),
                                         prefix)
            logger.info('%s flat shape %s', k, str(simulation[k].shape))
            vol = expand_array_in_mask(simulation[k], mask_vol, flat_axis=1)
            write_volume(np.rollaxis(vol, 0, 4), fn_stim_induced)

    save_time_series('flow_induction')
    save_time_series('cbv')
    save_time_series('hbr')
    save_time_series('bold_stim_induced_rescaled')

    if simulation.has_key('asl'):
        fn = add_prefix(op.join(output_dir, 'asl.nii'), prefix)
        asl4D = expand_array_in_mask(simulation['asl'], mask_vol, flat_axis=1)
        write_volume(np.rollaxis(asl4D, 0, 4), fn, vol_meta)

    if simulation.has_key('outliers'):
        fn = add_prefix(op.join(output_dir, 'outliers.nii'), prefix)
        outliers = expand_array_in_mask(simulation['outliers'],
                                        mask_vol,
                                        flat_axis=1)

        write_volume(np.rollaxis(outliers, 0, 4), fn, vol_meta)

    if simulation.has_key('hrf_group'):
        hrfgroup = simulation['hrf_group']
        nb_vox = mask_vol.size
        fn_hrf = add_prefix(op.join(output_dir, 'hrf_group.nii'), prefix)
        logger.info('hrf group shape %s', str(simulation['hrf_group'].shape))
        hrfGd = duplicate_hrf(nb_vox, hrfgroup)
        hrfs_vol = expand_array_in_mask(hrfGd, mask_vol, flat_axis=1)
        dt = simulation['dt']
        chrfs = xndarray(
            hrfs_vol,
            axes_names=[
                'time',
            ] + MRI3Daxes,
            axes_domains={'time': np.arange(hrfs_vol.shape[0]) * dt})
        chrfs.save(fn_hrf, vol_meta)

    if bold_3D_vols_dir is not None:
        assert op.exists(bold_3D_vols_dir)
        for iscan, bscan in enumerate(bold4D):
            fnout = add_prefix('bold_%06d.nii' % (iscan), prefix)
            write_volume(bscan, op.join(bold_3D_vols_dir, fnout), vol_meta)
Beispiel #10
0
    def make_outputs_multi_subjects(self, data_rois, irois, all_outputs,
                                    targetAxes, ext, meta_data, output_dir):

        coutputs = {}
        output_fns = []

        roi_masks = [[(ds.roiMask != ds.backgroundLabel)
                      for ds in dr.data_subjects] for dr in data_rois]
        #-> roi_masks[roi_id][subject]

        np_roi_masks = [[
            np.where(roi_subj_mask) for roi_subj_mask in roi_subj_masks
        ] for roi_subj_masks in roi_masks]
        #-> np_roi_masks[roi_id][subject]

        for output_name, roi_outputs in all_outputs.iteritems():
            logger.info('Merge output %s ...', output_name)
            dest_c = {}
            try:
                if roi_outputs[0].has_axis('voxel'):
                    if not roi_outputs[0].has_axis('subject'):
                        raise Exception('Voxel-mapped output "%s" does not'
                                        'have a subject axis')
                    logger.debug('Merge as expansion ...')
                    dest_c_tmp = None
                    for isubj in roi_outputs[0].get_domain('subject'):
                        for i_roi, c in enumerate(roi_outputs):
                            m = np_roi_masks[i_roi][isubj]
                            dest_c_tmp = c.expand(roi_masks[i_roi][isubj],
                                                  'voxel',
                                                  targetAxes,
                                                  dest=dest_c_tmp,
                                                  do_checks=False,
                                                  m=m)
                    dest_c[output_name] = dest_c_tmp
                else:
                    logger.debug('Merge as stack (%d elements)...', len(irois))
                    c_to_stack = [roi_outputs[i] for i in np.argsort(irois)]
                    dest_c[output_name] = stack_cuboids(c_to_stack,
                                                        domain=sorted(irois),
                                                        axis='ROI')
            except Exception, e:
                logger.error("Could not merge outputs for %s", output_name)
                logger.error("Exception was:")
                logger.error(e)

            for output_name, c in dest_c.iteritems():
                output_fn = op.join(output_dir, output_name + ext)
                output_fn = add_prefix(output_fn, self.outPrefix)
                output_fns.append(output_fn)
                logger.debug('Save output %s to %s', output_name, output_fn)
                try:
                    c.save(output_fn,
                           meta_data=meta_data,
                           set_MRI_orientation=True)
                except Exception:
                    print 'Could not save output "%s", error stack was:' \
                        % output_name
                    exc_type, exc_value, exc_traceback = sys.exc_info()
                    traceback.print_exception(exc_type,
                                              exc_value,
                                              exc_traceback,
                                              limit=4,
                                              file=sys.stdout)
                coutputs[output_name] = c
Beispiel #11
0
    def make_outputs_single_subject(self, data_rois, irois, all_outputs,
                                    targetAxes, ext, meta_data, output_dir):

        coutputs = {}
        output_fns = []

        roi_masks = [(data_roi.roiMask != data_roi.backgroundLabel)
                     for data_roi in data_rois]
        np_roi_masks = [np.where(roi_mask) for roi_mask in roi_masks]

        for output_name, roi_outputs in all_outputs.iteritems():
            logger.info('Merge output %s ...', output_name)
            try:
                if roi_outputs[0].has_axis('voxel'):
                    logger.debug('Merge as expansion ...')
                    dest_c = None
                    for i_roi, c in enumerate(roi_outputs):
                        dest_c = c.expand(roi_masks[i_roi],
                                          'voxel',
                                          targetAxes,
                                          dest=dest_c,
                                          do_checks=False,
                                          m=np_roi_masks[i_roi])
                else:
                    logger.debug('Merge as stack (%d elements)...', len(irois))
                    c_to_stack = [roi_outputs[i] for i in np.argsort(irois)]
                    # print 'c_to_stack:', c_to_stack
                    # print 'sorted(irois):', sorted(irois)
                    dest_c = stack_cuboids(c_to_stack,
                                           domain=sorted(irois),
                                           axis='ROI')
            except Exception, e:
                print "Could not merge outputs for %s" % output_name
                print "Exception was:"
                print e
                # raise e #stop here
            if 0 and dest_c is not None:
                print '-> ', dest_c.data.shape
            output_fn = op.join(output_dir, output_name + ext)
            output_fn = add_prefix(output_fn, self.outPrefix)
            output_fns.append(output_fn)
            logger.debug('Save output %s to %s', output_name, output_fn)
            try:
                if dest_c.meta_data:
                    tmp_meta_data = (meta_data[0], meta_data[1].copy())
                    tmp_meta_data[1]["descrip"] = dest_c.meta_data[1][
                        "descrip"]
                    dest_c.meta_data = tmp_meta_data
                    dest_c.save(output_fn, set_MRI_orientation=True)
                else:
                    dest_c.save(output_fn,
                                meta_data=meta_data,
                                set_MRI_orientation=True)
            except Exception:
                print 'Could not save output "%s", error stack was:' \
                    % output_name
                exc_type, exc_value, exc_traceback = sys.exc_info()
                traceback.print_exception(exc_type,
                                          exc_value,
                                          exc_traceback,
                                          limit=4,
                                          file=sys.stdout)
            coutputs[output_name] = dest_c
Beispiel #12
0
def simulation_save_vol_outputs(
    simulation, output_dir, bold_3D_vols_dir=None, simulation_graph_output=None, prefix=None, vol_meta=None
):
    """ simulation_graph_output : None, 'simple', 'thumbnails' #TODO
    """

    if simulation.has_key("paradigm"):
        fn = add_prefix(op.join(output_dir, "paradigm.csv"), prefix)
        simulation["paradigm"].save_csv(fn)

    # Save all volumes in nifti format:
    if simulation.has_key("labels_vol"):
        mask_vol = np.ones_like(simulation["labels_vol"][0])
    elif simulation.has_key("mask"):
        mask_vol = simulation.get("mask", None)
    elif simulation.has_key("labels"):
        mask_vol = np.ones_like(simulation["labels"][0])
    else:
        raise Exception("Dunno where to get mask")

    logger.info("Vol mask of shape %s", str(mask_vol.shape))

    fn_mask = add_prefix(op.join(output_dir, "mask.nii"), prefix)
    write_volume(mask_vol.astype(np.int32), fn_mask, vol_meta)

    if simulation.has_key("hrf_territories"):
        fn_h_territories = add_prefix(op.join(output_dir, "hrf_territories.nii"), prefix)

        ht = expand_array_in_mask(simulation["hrf_territories"] + 1, mask_vol)
        write_volume(ht, fn_h_territories, vol_meta)

    if simulation.has_key("hrf"):
        from pyhrf.ndarray import MRI3Daxes

        fn_hrf = add_prefix(op.join(output_dir, "hrf.nii"), prefix)
        logger.info("hrf flat shape %s", str(simulation["hrf"].shape))
        if simulation["hrf"].ndim == 1:
            hrf = np.ones(mask_vol.size) * simulation["hrf"][:, np.newaxis]
        else:
            hrf = simulation["hrf"]

        hrfs_vol = expand_array_in_mask(hrf, mask_vol, flat_axis=1)
        dt = simulation["dt"]
        chrfs = xndarray(
            hrfs_vol, axes_names=["time"] + MRI3Daxes, axes_domains={"time": np.arange(hrfs_vol.shape[0]) * dt}
        )
        chrfs.save(fn_hrf, vol_meta)

        ttp_vol = hrfs_vol.argmax(0)
        fn_ttp = add_prefix(op.join(output_dir, "ttp.nii"), prefix)
        write_volume(ttp_vol, fn_ttp, vol_meta)

    if simulation.has_key("brf"):
        from pyhrf.ndarray import MRI3Daxes

        fn_brf = add_prefix(op.join(output_dir, "brf.nii"), prefix)
        logger.info("brf flat shape %s", str(simulation["brf"].shape))
        brfs_vol = expand_array_in_mask(simulation["brf"], mask_vol, flat_axis=1)
        dt = simulation["dt"]
        cbrfs = xndarray(
            brfs_vol, axes_names=["time"] + MRI3Daxes, axes_domains={"time": np.arange(brfs_vol.shape[0]) * dt}
        )
        cbrfs.save(fn_brf, vol_meta)

    if simulation.has_key("prf"):
        from pyhrf.ndarray import MRI3Daxes

        fn_brf = add_prefix(op.join(output_dir, "prf.nii"), prefix)
        logger.info("prf flat shape %s", str(simulation["prf"].shape))
        brfs_vol = expand_array_in_mask(simulation["prf"], mask_vol, flat_axis=1)
        dt = simulation["dt"]
        cbrfs = xndarray(
            brfs_vol, axes_names=["time"] + MRI3Daxes, axes_domains={"time": np.arange(brfs_vol.shape[0]) * dt}
        )
        cbrfs.save(fn_brf, vol_meta)

    if simulation.has_key("drift"):
        fn_drift = add_prefix(op.join(output_dir, "drift.nii"), prefix)
        logger.info("drift flat shape %s", str(simulation["drift"].shape))
        drift_vol = expand_array_in_mask(simulation["drift"], mask_vol, flat_axis=1)
        write_volume(np.rollaxis(drift_vol, 0, 4), fn_drift)

    if simulation.has_key("drift_coeffs"):
        fn_drift = add_prefix(op.join(output_dir, "drift_coeffs.nii"), prefix)
        logger.info("drift flat shape %s", str(simulation["drift_coeffs"].shape))
        drift_vol = expand_array_in_mask(simulation["drift"], mask_vol, flat_axis=1)
        write_volume(np.rollaxis(drift_vol, 0, 4), fn_drift)

    if simulation.has_key("noise"):
        fn_noise = add_prefix(op.join(output_dir, "noise.nii"), prefix)
        logger.info("noise flat shape %s", str(simulation["noise"].shape))
        noise_vol = expand_array_in_mask(simulation["noise"], mask_vol, flat_axis=1)
        write_volume(np.rollaxis(noise_vol, 0, 4), fn_noise, vol_meta)

        fn_noise = add_prefix(op.join(output_dir, "noise_emp_var.nii"), prefix)
        noise_vol = expand_array_in_mask(simulation["noise"].var(0), mask_vol)
        write_volume(noise_vol, fn_noise, vol_meta)

    if simulation.has_key("noise_var"):
        fn_noise_var = add_prefix(op.join(output_dir, "noise_var.nii"), prefix)
        logger.info("noise_var flat shape %s", str(simulation["noise_var"].shape))
        noise_var_vol = expand_array_in_mask(simulation["noise_var"], mask_vol)
        write_volume(noise_var_vol, fn_noise_var, vol_meta)

    if simulation.has_key("stim_induced_signal"):
        fn_stim_induced = add_prefix(op.join(output_dir, "stim_induced.nii"), prefix)
        logger.info("stim_induced flat shape %s", str(simulation["stim_induced_signal"].shape))
        stim_induced_vol = expand_array_in_mask(simulation["stim_induced_signal"], mask_vol, flat_axis=1)
        write_volume(np.rollaxis(stim_induced_vol, 0, 4), fn_stim_induced)

    if simulation.has_key("perf_stim_induced"):
        fn_stim_induced = add_prefix(op.join(output_dir, "perf_stim_induced.nii"), prefix)
        logger.info("asl_stim_induced flat shape %s", str(simulation["perf_stim_induced"].shape))
        stim_induced_vol = expand_array_in_mask(simulation["perf_stim_induced"], mask_vol, flat_axis=1)
        write_volume(np.rollaxis(stim_induced_vol, 0, 4), fn_stim_induced)

        fn_stim_induced = add_prefix(op.join(output_dir, "perf_stim_induced_ct.nii"), prefix)
        logger.info("asl_stim_induced flat shape %s", str(simulation["perf_stim_induced"].shape))

        dsf = simulation["dsf"]
        perf = np.dot(simulation["ctrl_tag_mat"], simulation["perf_stim_induced"][0:-1:dsf])
        stim_induced_vol = expand_array_in_mask(perf, mask_vol, flat_axis=1)
        write_volume(np.rollaxis(stim_induced_vol, 0, 4), fn_stim_induced)

    if simulation.has_key("perf_baseline"):
        fn = add_prefix(op.join(output_dir, "perf_baseline.nii"), prefix)
        pb = np.zeros_like(simulation["bold"]) + simulation["perf_baseline"]
        write_volume(expand_array_in_mask(pb[0], mask_vol), fn, vol_meta)

    if simulation.has_key("bold_stim_induced"):
        fn_stim_induced = add_prefix(op.join(output_dir, "bold_stim_induced.nii"), prefix)
        logger.info("asl_stim_induced flat shape %s", str(simulation["bold_stim_induced"].shape))
        stim_induced_vol = expand_array_in_mask(simulation["bold_stim_induced"], mask_vol, flat_axis=1)
        write_volume(np.rollaxis(stim_induced_vol, 0, 4), fn_stim_induced)

    m = np.where(mask_vol)
    labels_and_mask = mask_vol.copy()[m]

    for ic in xrange(simulation["labels"].shape[0]):
        if simulation.has_key("condition_defs"):
            c_name = simulation["condition_defs"][ic].name
        else:
            c_name = "cond%d" % ic
        fn_labels = add_prefix(op.join(output_dir, "labels_%s.nii" % c_name), prefix)
        if simulation.has_key("labels"):
            labels_c = simulation["labels"][ic]
            labels_and_mask[np.where(labels_c)] = ic + 2
            write_volume(expand_array_in_mask(labels_c, mask_vol).astype(np.int32), fn_labels, vol_meta)
        elif simulation.has_key("labels_vol"):
            labels_c = simulation["labels_vol"][ic]
            labels_and_mask[np.where(labels_c[m])] = ic + 2
            write_volume(labels_c.astype(np.int32), fn_labels, vol_meta)

        if simulation.has_key("nrls"):
            nrls_c = simulation["nrls"][ic]
            fn = add_prefix(op.join(output_dir, "nrls_%s.nii" % c_name), prefix)
            write_volume(expand_array_in_mask(nrls_c, mask_vol), fn, vol_meta)
        if simulation.has_key("nrls_session"):
            nrls_session_c = simulation["nrls_session"][ic]
            fn = add_prefix(op.join(output_dir, "nrls_session_%s.nii" % (c_name)), prefix)
            write_volume(expand_array_in_mask(nrls_session_c, mask_vol), fn, vol_meta)

        if simulation.has_key("brls"):
            brls_c = simulation["brls"][ic]
            fn = add_prefix(op.join(output_dir, "brls_%s.nii" % c_name), prefix)
            write_volume(expand_array_in_mask(brls_c, mask_vol), fn, vol_meta)
        if simulation.has_key("prls"):
            prls_c = simulation["prls"][ic]
            fn = add_prefix(op.join(output_dir, "prls_%s.nii" % c_name), prefix)
            write_volume(expand_array_in_mask(prls_c, mask_vol), fn, vol_meta)

        if simulation.has_key("neural_efficacies"):
            ne_c = simulation["neural_efficacies"][ic]
            fn = add_prefix(op.join(output_dir, "neural_efficacies_%s.nii" % c_name), prefix)
            write_volume(expand_array_in_mask(ne_c, mask_vol), fn, vol_meta)

    fn_labels_and_mask = add_prefix(op.join(output_dir, "mask_and_labels.nii"), prefix)

    write_volume(expand_array_in_mask(labels_and_mask, mask_vol).astype(int), fn_labels_and_mask, vol_meta)

    if simulation.has_key("bold_full_vol") or simulation.has_key("bold"):
        fn = add_prefix(op.join(output_dir, "bold.nii"), prefix)
        if simulation.has_key("bold_full_vol"):
            bold4D = simulation["bold_full_vol"]
        else:
            bold = simulation["bold"]
            bold4D = expand_array_in_mask(bold, mask_vol, flat_axis=1)

        write_volume(np.rollaxis(bold4D, 0, 4), fn, vol_meta)

    def save_time_series(k):
        if simulation.has_key(k):
            fn_stim_induced = add_prefix(op.join(output_dir, k + ".nii"), prefix)
            logger.info("%s flat shape %s", k, str(simulation[k].shape))
            vol = expand_array_in_mask(simulation[k], mask_vol, flat_axis=1)
            write_volume(np.rollaxis(vol, 0, 4), fn_stim_induced)

    save_time_series("flow_induction")
    save_time_series("cbv")
    save_time_series("hbr")
    save_time_series("bold_stim_induced_rescaled")

    if simulation.has_key("asl"):
        fn = add_prefix(op.join(output_dir, "asl.nii"), prefix)
        asl4D = expand_array_in_mask(simulation["asl"], mask_vol, flat_axis=1)
        write_volume(np.rollaxis(asl4D, 0, 4), fn, vol_meta)

    if simulation.has_key("outliers"):
        fn = add_prefix(op.join(output_dir, "outliers.nii"), prefix)
        outliers = expand_array_in_mask(simulation["outliers"], mask_vol, flat_axis=1)

        write_volume(np.rollaxis(outliers, 0, 4), fn, vol_meta)

    if simulation.has_key("hrf_group"):
        hrfgroup = simulation["hrf_group"]
        nb_vox = mask_vol.size
        fn_hrf = add_prefix(op.join(output_dir, "hrf_group.nii"), prefix)
        logger.info("hrf group shape %s", str(simulation["hrf_group"].shape))
        hrfGd = duplicate_hrf(nb_vox, hrfgroup)
        hrfs_vol = expand_array_in_mask(hrfGd, mask_vol, flat_axis=1)
        dt = simulation["dt"]
        chrfs = xndarray(
            hrfs_vol, axes_names=["time"] + MRI3Daxes, axes_domains={"time": np.arange(hrfs_vol.shape[0]) * dt}
        )
        chrfs.save(fn_hrf, vol_meta)

    if bold_3D_vols_dir is not None:
        assert op.exists(bold_3D_vols_dir)
        for iscan, bscan in enumerate(bold4D):
            fnout = add_prefix("bold_%06d.nii" % (iscan), prefix)
            write_volume(bscan, op.join(bold_3D_vols_dir, fnout), vol_meta)
Beispiel #13
0
def simulation_save_vol_outputs(simulation, output_dir, bold_3D_vols_dir=None,
                                simulation_graph_output=None, prefix=None,
                                vol_meta=None):
    """ simulation_graph_output : None, 'simple', 'thumbnails' #TODO
    """

    if simulation.has_key('paradigm'):
        fn = add_prefix(op.join(output_dir, 'paradigm.csv'), prefix)
        simulation['paradigm'].save_csv(fn)

    # Save all volumes in nifti format:
    if simulation.has_key('labels_vol'):
        mask_vol = np.ones_like(simulation['labels_vol'][0])
    elif simulation.has_key('mask'):
        mask_vol = simulation.get('mask', None)
    elif simulation.has_key('labels'):
        mask_vol = np.ones_like(simulation['labels'][0])
    else:
        raise Exception('Dunno where to get mask')

    logger.info('Vol mask of shape %s', str(mask_vol.shape))

    fn_mask = add_prefix(op.join(output_dir, 'mask.nii'), prefix)
    write_volume(mask_vol.astype(np.int32), fn_mask, vol_meta)

    if simulation.has_key('hrf_territories'):
        fn_h_territories = add_prefix(op.join(output_dir, 'hrf_territories.nii'),
                                      prefix)

        ht = expand_array_in_mask(simulation['hrf_territories'] + 1, mask_vol)
        write_volume(ht, fn_h_territories, vol_meta)

    if simulation.has_key('hrf'):
        from pyhrf.ndarray import MRI3Daxes
        fn_hrf = add_prefix(op.join(output_dir, 'hrf.nii'), prefix)
        logger.info('hrf flat shape %s', str(simulation['hrf'].shape))
        if simulation['hrf'].ndim == 1:
            hrf = (np.ones(mask_vol.size) * simulation['hrf'][:, np.newaxis])
        else:
            hrf = simulation['hrf']

        hrfs_vol = expand_array_in_mask(hrf, mask_vol, flat_axis=1)
        dt = simulation['dt']
        chrfs = xndarray(hrfs_vol, axes_names=['time', ] + MRI3Daxes,
                         axes_domains={'time': np.arange(hrfs_vol.shape[0]) * dt})
        chrfs.save(fn_hrf, vol_meta)

        ttp_vol = hrfs_vol.argmax(0)
        fn_ttp = add_prefix(op.join(output_dir, 'ttp.nii'), prefix)
        write_volume(ttp_vol, fn_ttp, vol_meta)

    if simulation.has_key('brf'):
        from pyhrf.ndarray import MRI3Daxes
        fn_brf = add_prefix(op.join(output_dir, 'brf.nii'), prefix)
        logger.info('brf flat shape %s', str(simulation['brf'].shape))
        brfs_vol = expand_array_in_mask(
            simulation['brf'], mask_vol, flat_axis=1)
        dt = simulation['dt']
        cbrfs = xndarray(brfs_vol, axes_names=['time', ] + MRI3Daxes,
                         axes_domains={'time': np.arange(brfs_vol.shape[0]) * dt})
        cbrfs.save(fn_brf, vol_meta)

    if simulation.has_key('prf'):
        from pyhrf.ndarray import MRI3Daxes
        fn_brf = add_prefix(op.join(output_dir, 'prf.nii'), prefix)
        logger.info('prf flat shape %s', str(simulation['prf'].shape))
        brfs_vol = expand_array_in_mask(
            simulation['prf'], mask_vol, flat_axis=1)
        dt = simulation['dt']
        cbrfs = xndarray(brfs_vol, axes_names=['time', ] + MRI3Daxes,
                         axes_domains={'time': np.arange(brfs_vol.shape[0]) * dt})
        cbrfs.save(fn_brf, vol_meta)

    if simulation.has_key('drift'):
        fn_drift = add_prefix(op.join(output_dir, 'drift.nii'), prefix)
        logger.info('drift flat shape %s', str(simulation['drift'].shape))
        drift_vol = expand_array_in_mask(simulation['drift'], mask_vol,
                                         flat_axis=1)
        write_volume(np.rollaxis(drift_vol, 0, 4), fn_drift)

    if simulation.has_key('drift_coeffs'):
        fn_drift = add_prefix(op.join(output_dir, 'drift_coeffs.nii'), prefix)
        logger.info(
            'drift flat shape %s', str(simulation['drift_coeffs'].shape))
        drift_vol = expand_array_in_mask(simulation['drift'], mask_vol,
                                         flat_axis=1)
        write_volume(np.rollaxis(drift_vol, 0, 4), fn_drift)

    if simulation.has_key('noise'):
        fn_noise = add_prefix(op.join(output_dir, 'noise.nii'), prefix)
        logger.info('noise flat shape %s', str(simulation['noise'].shape))
        noise_vol = expand_array_in_mask(simulation['noise'], mask_vol,
                                         flat_axis=1)
        write_volume(np.rollaxis(noise_vol, 0, 4), fn_noise, vol_meta)

        fn_noise = add_prefix(op.join(output_dir, 'noise_emp_var.nii'), prefix)
        noise_vol = expand_array_in_mask(simulation['noise'].var(0), mask_vol)
        write_volume(noise_vol, fn_noise, vol_meta)

    if simulation.has_key('noise_var'):
        fn_noise_var = add_prefix(op.join(output_dir, 'noise_var.nii'), prefix)
        logger.info(
            'noise_var flat shape %s', str(simulation['noise_var'].shape))
        noise_var_vol = expand_array_in_mask(simulation['noise_var'], mask_vol)
        write_volume(noise_var_vol, fn_noise_var, vol_meta)

    if simulation.has_key('stim_induced_signal'):
        fn_stim_induced = add_prefix(op.join(output_dir, 'stim_induced.nii'),
                                     prefix)
        logger.info('stim_induced flat shape %s',
                    str(simulation['stim_induced_signal'].shape))
        stim_induced_vol = expand_array_in_mask(simulation['stim_induced_signal'],
                                                mask_vol, flat_axis=1)
        write_volume(np.rollaxis(stim_induced_vol, 0, 4), fn_stim_induced)

    if simulation.has_key('perf_stim_induced'):
        fn_stim_induced = add_prefix(op.join(output_dir, 'perf_stim_induced.nii'),
                                     prefix)
        logger.info('asl_stim_induced flat shape %s',
                    str(simulation['perf_stim_induced'].shape))
        stim_induced_vol = expand_array_in_mask(simulation['perf_stim_induced'],
                                                mask_vol, flat_axis=1)
        write_volume(np.rollaxis(stim_induced_vol, 0, 4), fn_stim_induced)

        fn_stim_induced = add_prefix(op.join(output_dir,
                                             'perf_stim_induced_ct.nii'),
                                     prefix)
        logger.info('asl_stim_induced flat shape %s',
                    str(simulation['perf_stim_induced'].shape))

        dsf = simulation['dsf']
        perf = np.dot(simulation['ctrl_tag_mat'],
                      simulation['perf_stim_induced'][0:-1:dsf])
        stim_induced_vol = expand_array_in_mask(perf, mask_vol, flat_axis=1)
        write_volume(np.rollaxis(stim_induced_vol, 0, 4), fn_stim_induced)

    if simulation.has_key('perf_baseline'):
        fn = add_prefix(op.join(output_dir, 'perf_baseline.nii'), prefix)
        pb = np.zeros_like(simulation['bold']) + simulation['perf_baseline']
        write_volume(expand_array_in_mask(pb[0], mask_vol), fn, vol_meta)

    if simulation.has_key('bold_stim_induced'):
        fn_stim_induced = add_prefix(op.join(output_dir, 'bold_stim_induced.nii'),
                                     prefix)
        logger.info('asl_stim_induced flat shape %s',
                    str(simulation['bold_stim_induced'].shape))
        stim_induced_vol = expand_array_in_mask(simulation['bold_stim_induced'],
                                                mask_vol, flat_axis=1)
        write_volume(np.rollaxis(stim_induced_vol, 0, 4), fn_stim_induced)

    m = np.where(mask_vol)
    labels_and_mask = mask_vol.copy()[m]

    for ic in xrange(simulation['labels'].shape[0]):
        if simulation.has_key('condition_defs'):
            c_name = simulation['condition_defs'][ic].name
        else:
            c_name = 'cond%d' % ic
        fn_labels = add_prefix(op.join(output_dir, 'labels_%s.nii' % c_name),
                               prefix)
        if simulation.has_key('labels'):
            labels_c = simulation['labels'][ic]
            labels_and_mask[np.where(labels_c)] = ic + 2
            write_volume(expand_array_in_mask(labels_c, mask_vol).astype(np.int32),
                         fn_labels, vol_meta)
        elif simulation.has_key('labels_vol'):
            labels_c = simulation['labels_vol'][ic]
            labels_and_mask[np.where(labels_c[m])] = ic + 2
            write_volume(labels_c.astype(np.int32), fn_labels, vol_meta)

        if simulation.has_key('nrls'):
            nrls_c = simulation['nrls'][ic]
            fn = add_prefix(
                op.join(output_dir, 'nrls_%s.nii' % c_name), prefix)
            write_volume(expand_array_in_mask(nrls_c, mask_vol), fn, vol_meta)
        if simulation.has_key('nrls_session'):
            nrls_session_c = simulation['nrls_session'][ic]
            fn = add_prefix(op.join(output_dir, 'nrls_session_%s.nii'
                                    % (c_name)), prefix)
            write_volume(expand_array_in_mask(nrls_session_c, mask_vol),
                         fn, vol_meta)

        if simulation.has_key('brls'):
            brls_c = simulation['brls'][ic]
            fn = add_prefix(
                op.join(output_dir, 'brls_%s.nii' % c_name), prefix)
            write_volume(expand_array_in_mask(brls_c, mask_vol), fn, vol_meta)
        if simulation.has_key('prls'):
            prls_c = simulation['prls'][ic]
            fn = add_prefix(
                op.join(output_dir, 'prls_%s.nii' % c_name), prefix)
            write_volume(expand_array_in_mask(prls_c, mask_vol), fn, vol_meta)

        if simulation.has_key('neural_efficacies'):
            ne_c = simulation['neural_efficacies'][ic]
            fn = add_prefix(op.join(output_dir, 'neural_efficacies_%s.nii'
                                    % c_name), prefix)
            write_volume(expand_array_in_mask(ne_c, mask_vol), fn, vol_meta)

    fn_labels_and_mask = add_prefix(op.join(output_dir, 'mask_and_labels.nii'),
                                    prefix)

    write_volume(expand_array_in_mask(labels_and_mask, mask_vol).astype(int),
                 fn_labels_and_mask, vol_meta)

    if simulation.has_key('bold_full_vol') or simulation.has_key('bold'):
        fn = add_prefix(op.join(output_dir, 'bold.nii'), prefix)
        if simulation.has_key('bold_full_vol'):
            bold4D = simulation['bold_full_vol']
        else:
            bold = simulation['bold']
            bold4D = expand_array_in_mask(bold, mask_vol, flat_axis=1)

        write_volume(np.rollaxis(bold4D, 0, 4), fn, vol_meta)

    def save_time_series(k):
        if simulation.has_key(k):
            fn_stim_induced = add_prefix(
                op.join(output_dir, k + '.nii'), prefix)
            logger.info('%s flat shape %s', k, str(simulation[k].shape))
            vol = expand_array_in_mask(simulation[k], mask_vol, flat_axis=1)
            write_volume(np.rollaxis(vol, 0, 4), fn_stim_induced)
    save_time_series('flow_induction')
    save_time_series('cbv')
    save_time_series('hbr')
    save_time_series('bold_stim_induced_rescaled')

    if simulation.has_key('asl'):
        fn = add_prefix(op.join(output_dir, 'asl.nii'), prefix)
        asl4D = expand_array_in_mask(simulation['asl'], mask_vol, flat_axis=1)
        write_volume(np.rollaxis(asl4D, 0, 4), fn, vol_meta)

    if simulation.has_key('outliers'):
        fn = add_prefix(op.join(output_dir, 'outliers.nii'), prefix)
        outliers = expand_array_in_mask(simulation['outliers'], mask_vol,
                                        flat_axis=1)

        write_volume(np.rollaxis(outliers, 0, 4), fn, vol_meta)

    if simulation.has_key('hrf_group'):
        hrfgroup = simulation['hrf_group']
        nb_vox = mask_vol.size
        fn_hrf = add_prefix(op.join(output_dir, 'hrf_group.nii'), prefix)
        logger.info('hrf group shape %s', str(simulation['hrf_group'].shape))
        hrfGd = duplicate_hrf(nb_vox, hrfgroup)
        hrfs_vol = expand_array_in_mask(hrfGd, mask_vol, flat_axis=1)
        dt = simulation['dt']
        chrfs = xndarray(hrfs_vol, axes_names=['time', ] + MRI3Daxes,
                         axes_domains={'time': np.arange(hrfs_vol.shape[0]) * dt})
        chrfs.save(fn_hrf, vol_meta)

    if bold_3D_vols_dir is not None:
        assert op.exists(bold_3D_vols_dir)
        for iscan, bscan in enumerate(bold4D):
            fnout = add_prefix('bold_%06d.nii' % (iscan), prefix)
            write_volume(bscan, op.join(bold_3D_vols_dir, fnout), vol_meta)
Beispiel #14
0
def make_outfile(fn, path, pre='', suf=''):
    if fn is None or path is None:
        return None
    ofn = op.join(path, fn)
    return add_prefix(add_suffix(ofn, suf), pre)
Beispiel #15
0
from pyhrf.ui.vb_jde_analyser import JDEVEMAnalyser as VBJDE

from pyhrf.ui.jde import DEFAULT_CFG_FILE as DEFAULT_CFG_FILE_JDE

from pyhrf.jde.models import BOLDGibbsSampler as BG

from pyhrf.jde.beta import BetaSampler as BS
from pyhrf.jde.nrl.bigaussian import NRLSampler as NS
from pyhrf.jde.nrl.trigaussian import GGGNRLSampler as NS3
from pyhrf.jde.hrf import RHSampler as HVS
from pyhrf.jde.hrf import HRFSampler as HS

#VT = FMRIVolumeTreatment
#ST = FMRISurfaceTreatment

DEFAULT_JDE_OUT_MASK_VOL = add_prefix(DEFAULT_OUT_MASK_VOL_FILE, 'jde_')
DEFAULT_JDE_OUT_MASK_SURF = add_prefix(DEFAULT_OUT_MASK_SURF_FILE, 'jde_')


def make_outfile(fn, path, pre='', suf=''):
    if fn is None or path is None:
        return None
    ofn = op.join(path, fn)
    return add_prefix(add_suffix(ofn, suf), pre)


def create_treatment(boldFiles,
                     parcelFile,
                     dt,
                     tr,
                     paradigmFile,
Beispiel #16
0
    def outputResults_old2(self, results, output_dir, filter='.\A',):
        """
        Return: a tuple (dictionary of outputs, output file names)
        """
        if output_dir is None:
            return {}, []

        if not isinstance(results[0][0], FmriData, FmriGroupData):
            self.outputResults_back_compat(results, output_dir, filter)
            return {}, []

        pyhrf.verbose(1,'Building outputs from %d results ...' %len(results))
        pyhrf.verbose(6, 'results :')
        pyhrf.verbose.printDict(6, results, exclude=['xmlHandler'])

        to_pop = []
        for  i,r in enumerate(results[:]):
            roi_data,result,report = r
            roi_id = roi_data.get_roi_id()
            if report != 'ok':
                pyhrf.verbose(1, '-> Sampling crashed, roi %d!' \
                                  %roi_id)
                pyhrf.verbose(2, report)
                to_pop.insert(0,i)

            elif result is None:
                pyhrf.verbose(1, '-> Sampling crashed (result is None), '
                              'roi %d!' %roi_id)
                to_pop.insert(0,i)

        for i in to_pop:
            results.pop(i)

        if len(results) == 0:
            pyhrf.verbose(1, 'No more result to treat. Did everything crash ?')
            return {}, []

        target_shape = results[0][0].spatial_shape
        meta_data = results[0][0].meta_obj

        if len(target_shape) == 3: #Volumic data:
            targetAxes = MRI3Daxes #['axial','coronal', 'sagittal']
            ext = '.nii'
        else: #surfacic
            targetAxes = ['voxel']
            ext = '.gii'

        def genzip(gens):
            while True:
                yield [g.next() for g in gens]

        coutputs = {}
        output_fns = []

        pyhrf.verbose(1,'Get each ROI output ...')
        #print 'roi outputs:'
        if hasattr(results[0][1], 'getOutputs'):
            gen_outputs = [r[1].getOutputs() for r in results]
        else:
            gen_outputs = [r[1].iteritems() for r in results]

        data_rois = [r[0] for r in results]
        irois = [d.get_roi_id() for d in data_rois]
        for roi_outputs in genzip(gen_outputs):
            output_name = roi_outputs[0][0]
            pyhrf.verbose(3,'Merge output %s ...' %output_name)
            try:
                if roi_outputs[0][1].has_axis('voxel'):
                    pyhrf.verbose(5,'Merge as expansion ...')
                    dest_c = None
                    for data_roi,output in zip(data_rois,roi_outputs):
                        _, c = output
                        roi_mask = (data_roi.roiMask != data_roi.backgroundLabel)

                        dest_c = c.expand(roi_mask, 'voxel', targetAxes,
                                          dest=dest_c)
                else:
                    pyhrf.verbose(5,'Merge as stack (%d elements)...' \
                                      %len(irois))
                    c_to_stack = [roi_outputs[i][1] for i in np.argsort(irois)]
                    # print 'c_to_stack:', c_to_stack
                    # print 'sorted(irois):', sorted(irois)
                    dest_c = stack_cuboids(c_to_stack, domain=sorted(irois),
                                           axis='ROI')
            except Exception, e:
                print "Could not merge outputs for %s" %output_name
                print "Exception was:"
                print e
                #raise e #stop here
            if 0 and dest_c is not None:
                print '-> ', dest_c.data.shape
            output_fn = op.join(output_dir,output_name + ext)
            output_fn = add_prefix(output_fn, self.outPrefix)
            output_fns.append(output_fn)
            pyhrf.verbose(5,'Save output %s to %s' %(output_name, output_fn))
            try:
                dest_c.save(output_fn, meta_data=meta_data,
                            set_MRI_orientation=True)
            except Exception:
                print 'Could not save output "%s", error stack was:' \
                    %output_name
                exc_type, exc_value, exc_traceback = sys.exc_info()
                traceback.print_exception(exc_type, exc_value, exc_traceback,
                                          limit=4, file=sys.stdout)
            coutputs[output_name] = dest_c