Example #1
0
    def setDummyInputData(self, xmlFile):

        f = open(xmlFile, 'r')
        xml = f.read()
        t = xmlio.from_xml(xml)
        if t.data.data_type == 'volume':
            dataFn = pyhrf.get_data_file_name('dummySmallBOLD.nii.gz')
            maskFn = pyhrf.get_data_file_name('dummySmallMask.nii.gz')
            sd = FMRISessionVolumicData(bold_file=dataFn)
            t.set_init_param(
                'fmri_data',
                FmriData.from_vol_ui(mask_file=maskFn, sessions_data=[sd]))

        elif t.data.data_type == 'surface':
            fn = 'real_data_surf_tiny_bold.gii'
            dataFn = pyhrf.get_data_file_name(fn)
            fn = 'real_data_surf_tiny_parcellation.gii'
            maskFn = pyhrf.get_data_file_name(fn)
            fn = 'real_data_surf_tiny_mesh.gii'
            meshFn = pyhrf.get_data_file_name(fn)
            sd = FMRISessionSurfacicData(bold_file=dataFn)
            t.set_init_param(
                'fmri_data',
                FmriData.from_surf_ui(mask_file=maskFn,
                                      mesh_file=meshFn,
                                      sessions_data=[sd]))
        else:
            raise Exception('Unsupported class ... todo')

        f = open(xmlFile, 'w')
        f.write(xmlio.to_xml(t))
        f.close()
Example #2
0
    def setDummyInputData(self, xmlFile):

        f = open(xmlFile, 'r')
        xml = f.read()
        t = xmlio.from_xml(xml)
        if t.data.data_type == 'volume':
            dataFn = pyhrf.get_data_file_name('dummySmallBOLD.nii.gz')
            maskFn = pyhrf.get_data_file_name('dummySmallMask.nii.gz')
            sd = FMRISessionVolumicData(bold_file=dataFn)
            t.set_init_param('fmri_data',
                             FmriData.from_vol_ui(mask_file=maskFn,
                                                  sessions_data=[sd]))

        elif t.data.data_type == 'surface':
            fn = 'real_data_surf_tiny_bold.gii'
            dataFn = pyhrf.get_data_file_name(fn)
            fn = 'real_data_surf_tiny_parcellation.gii'
            maskFn = pyhrf.get_data_file_name(fn)
            fn = 'real_data_surf_tiny_mesh.gii'
            meshFn = pyhrf.get_data_file_name(fn)
            sd = FMRISessionSurfacicData(bold_file=dataFn)
            t.set_init_param('fmri_data',
                             FmriData.from_surf_ui(mask_file=maskFn,
                                                   mesh_file=meshFn,
                                                   sessions_data=[sd]))
        else:
            raise Exception('Unsupported class ... todo')

        f = open(xmlFile, 'w')
        f.write(xmlio.to_xml(t))
        f.close()
Example #3
0
    def setDummyInputData(self, xmlFile):

        f = open(xmlFile, "r")
        xml = f.read()
        t = xmlio.fromXML(xml)
        if t.data.data_type == "volume":
            dataFn = pyhrf.get_data_file_name("dummySmallBOLD.nii.gz")
            maskFn = pyhrf.get_data_file_name("dummySmallMask.nii.gz")
            sd = FMRISessionVolumicData(bold_file=dataFn)
            t.set_init_param("fmri_data", FmriData.from_vol_ui(mask_file=maskFn, sessions_data=[sd]))

        elif t.data.data_type == "surface":
            fn = "real_data_surf_tiny_bold.gii"
            dataFn = pyhrf.get_data_file_name(fn)
            fn = "real_data_surf_tiny_parcellation.gii"
            maskFn = pyhrf.get_data_file_name(fn)
            fn = "real_data_surf_tiny_mesh.gii"
            meshFn = pyhrf.get_data_file_name(fn)
            sd = FMRISessionSurfacicData(bold_file=dataFn)
            t.set_init_param("fmri_data", FmriData.from_surf_ui(mask_file=maskFn, mesh_file=meshFn, sessions_data=[sd]))
        else:
            raise Exception("Unsupported class ... todo")

        f = open(xmlFile, "w")
        f.write(xmlio.toXML(t, handler=NumpyXMLHandler()))
        f.close()
Example #4
0
    def test_fir_glm(self):

        from pyhrf import FmriData
        from pyhrf.glm import glm_nipy

        fdata = FmriData.from_vol_ui()
        glm_nipy(fdata, hrf_model='FIR', fir_delays=range(10))
Example #5
0
    def test_fir_glm(self):

        from pyhrf import FmriData
        from pyhrf.glm import glm_nipy

        fdata = FmriData.from_vol_ui()
        glm_nipy(fdata, hrf_model='FIR', fir_delays=range(10))
Example #6
0
    def test_glm_default_real_data(self):

        from pyhrf import FmriData
        from pyhrf.glm import glm_nipy

        fdata = FmriData.from_vol_ui()
        glm_nipy(fdata)
Example #7
0
    def test_glm_default_real_data(self):

        from pyhrf import FmriData
        from pyhrf.glm import glm_nipy

        fdata = FmriData.from_vol_ui()
        glm_nipy(fdata)
Example #8
0
    def setUp(self):
        np.random.seed(8652761)

        tmpDir = tempfile.mkdtemp(prefix='pyhrf_tests',
                                  dir=pyhrf.cfg['global']['tmp_path'])
        self.tmp_dir = tmpDir
        simu = simulate_bold(self.tmp_dir, spatial_size='random_small')
        self.data_simu = FmriData.from_simulation_dict(simu)
Example #9
0
    def setUp(self):
        np.random.seed(8652761)

        tmpDir = tempfile.mkdtemp(prefix='pyhrf_tests',
                                  dir=pyhrf.cfg['global']['tmp_path'])
        self.tmp_dir = tmpDir
        self.clean_tmp = True
        simu = simulate_bold(self.tmp_dir, spatial_size='random_small')
        self.data_simu = FmriData.from_simulation_dict(simu)
Example #10
0
    def test_glm_contrasts(self):

        from pyhrf import FmriData
        from pyhrf.glm import glm_nipy
        cons = {'audio-video': 'audio - video',
                'video-audio': 'video - audio',
                }
        fdata = FmriData.from_vol_ui()
        g, dm, cons = glm_nipy(fdata, contrasts=cons)
Example #11
0
    def test_glm_contrasts(self):

        from pyhrf import FmriData
        from pyhrf.glm import glm_nipy
        cons = {
            'audio-video': 'audio - video',
            'video-audio': 'video - audio',
        }
        fdata = FmriData.from_vol_ui()
        g, dm, cons = glm_nipy(fdata, contrasts=cons)
Example #12
0
    def test_fir_glm(self):

        from pyhrf import FmriData
        from pyhrf.glm import glm_nipy

        #pyhrf.verbose.set_verbosity(3)
        fdata = FmriData.from_vol_ui()
        # print 'fdata:'
        # print fdata.getSummary()
        glm_nipy(fdata, hrf_model='FIR', fir_delays=range(10))
Example #13
0
    def test_glm_default_real_data(self):

        from pyhrf import FmriData
        from pyhrf.glm import glm_nipy

        #pyhrf.verbose.set_verbosity(3)
        fdata = FmriData.from_vol_ui()
        # print 'fdata:'
        # print fdata.getSummary()
        glm_nipy(fdata)
Example #14
0
    def test_glm_contrasts(self):

        from pyhrf import FmriData
        from pyhrf.glm import glm_nipy
        cons = {'audio-video': 'audio - video',
                'video-audio': 'video - audio',
                }
        #pyhrf.verbose.set_verbosity(3)
        fdata = FmriData.from_vol_ui()
        # print 'fdata:'
        # print fdata.getSummary()
        g, dm, cons = glm_nipy(fdata, contrasts=cons)
Example #15
0
    def setSimulationData(self, xmlFile, simu_file):

        f = open(xmlFile, 'r')
        xml = f.read()
        t = xmlio.from_xml(xml)
        sd = FMRISessionSimulationData(simulation_file=simu_file)
        t.set_init_param('fmri_data',
                         FmriData.from_simu_ui(sessions_data=[sd]))

        f = open(xmlFile, 'w')
        sxml = xmlio.to_xml(t)
        f.write(sxml)
        f.close()
Example #16
0
    def setSimulationData(self, xmlFile, simu_file):

        f = open(xmlFile, 'r')
        xml = f.read()
        t = xmlio.from_xml(xml)
        sd = FMRISessionSimulationData(simulation_file=simu_file)
        t.set_init_param(
            'fmri_data', FmriData.from_simu_ui(sessions_data=[sd]))

        f = open(xmlFile, 'w')
        sxml = xmlio.to_xml(t)
        f.write(sxml)
        f.close()
    def test_hrf_with_var_sampler_2(self):
        # estimation of HRF and its variance tested in the following situation:
        #    -  simulated gaussian smooth HRF is not normalized

        pyhrf.verbose.set_verbosity(2)

        simu = simulate_bold(self.tmp_dir, spatial_size='small',
                             normalize_hrf=False)
        simu = FmriData.from_simulation_dict(simu)

        self._test_specific_samplers(['HRFVariance','HRF'], simu_scenario=simu,
                                     check_fv='print', nb_its=100,
                                     hrf_prior_type='voxelwiseIID')
Example #18
0
    def test_parcellation(self):

        p_size = 300
        np.random.seed(125437)
        parcellation, _ = parcellation_for_jde(FmriData.from_vol_ui(), p_size,
                                               output_dir=self.tmp_dir)
        ms = np.mean([(parcellation == i).sum()
                      for i in np.unique(parcellation) if i != 0])
        size_tol = 50
        if np.abs(ms - p_size) > size_tol:
            raise Exception('Mean size of parcellation seems too '
                            'large: %1.2f >%d+-%d ' % (ms, p_size, size_tol))
        if 0:
            print parcellation_report(parcellation)
    def test_hrf_with_var_sampler_2(self):
        # estimation of HRF and its variance tested in the following situation:
        #    -  simulated gaussian smooth HRF is not normalized

        # pyhrf.verbose.set_verbosity(2)
        pyhrf.logger.setLevel(logging.INFO)

        simu = simulate_bold(self.tmp_dir, spatial_size='small',
                             normalize_hrf=False)
        simu = FmriData.from_simulation_dict(simu)

        self._test_specific_samplers(['HRFVariance', 'HRF'], simu_scenario=simu,
                                     check_fv='print', nb_its=100,
                                     hrf_prior_type='voxelwiseIID')
Example #20
0
    def setSimulationData(self, xmlFile, simu_file):

        f = open(xmlFile, "r")
        xml = f.read()
        t = xmlio.fromXML(xml)
        sd = FMRISessionSimulationData(simulation_file=simu_file)
        t.set_init_param("fmri_data", FmriData.from_simu_ui(sessions_data=[sd]))

        f = open(xmlFile, "w")
        sxml = xmlio.toXML(t, handler=NumpyXMLHandler())
        # print 'sxml:'
        # print sxml
        f.write(sxml)
        f.close()
    def test_hrf_var_sampler(self):

        # estimation of HRF variance tested in the following situation:
        #    -  simulated gaussian smooth HRF is not normalized
        #       -> else the simulated HRF variance is not consistent

        pyhrf.verbose.set_verbosity(2)

        simu = simulate_bold(self.tmp_dir, spatial_size='small',
                             normalize_hrf=False)
        simu = FmriData.from_simulation_dict(simu)

        self._test_specific_samplers(['HRFVariance'], simu_scenario=simu,
                                     check_fv='raise', nb_its=100,
                                     hrf_prior_type='singleHRF')
    def test_hrf_var_sampler(self):

        # estimation of HRF variance tested in the following situation:
        #    -  simulated gaussian smooth HRF is not normalized
        #       -> else the simulated HRF variance is not consistent

        # pyhrf.verbose.set_verbosity(2)
        pyhrf.logger.setLevel(logging.INFO)

        simu = simulate_bold(self.tmp_dir, spatial_size='small',
                             normalize_hrf=False)
        simu = FmriData.from_simulation_dict(simu)

        self._test_specific_samplers(['HRFVariance'], simu_scenario=simu,
                                     check_fv='raise', nb_its=100,
                                     hrf_prior_type='singleHRF')
Example #23
0
    def test_default_jde_small_simulation(self):
        """ Test ASL sampler on small simulation with small nb of iterations.
        Estimation accuracy is not tested.
        """

        simu = simulate_asl(spatial_size='random_small')
        fdata = FmriData.from_simulation_dict(simu)

        sampler = jde_asl.ASLSampler()

        analyser = JDEMCMCAnalyser(sampler=sampler, osfMax=4, dtMin=.4,
                                   dt=.5, driftParam=4, driftType='polynomial',
                                   outputPrefix='jde_mcmc_', randomSeed=None)

        treatment = FMRITreatment(fmri_data=fdata, analyser=analyser,
                                  output_dir=None)

        treatment.run()
Example #24
0
    def test_default_jde_small_simulation(self):
        """ Test ASL Physio sampler on small simulation with small nb of
        iterations. Estimation accuracy is not tested.
        """
        pyhrf.verbose.set_verbosity(0)

        sampler_params = {
            'nb_iterations' : 3,
            'smpl_hist_pace' : 1,
            'obs_hist_pace' : 1,
            'brf' : jde_asl_physio.PhysioBOLDResponseSampler(zero_constraint=False),
            'brf_var' : jde_asl_physio.PhysioBOLDResponseVarianceSampler(val_ini=\
                                                                         np.array([1e-3])),
            'prf' : jde_asl_physio.PhysioPerfResponseSampler(zero_constraint=False),
            'prf_var' : jde_asl_physio.PhysioPerfResponseVarianceSampler(val_ini=\
                                                                         np.array([1e-3])),
            'noise_var' : jde_asl_physio.NoiseVarianceSampler(),
            'drift_var' : jde_asl_physio.DriftVarianceSampler(),
            'drift' : jde_asl_physio.DriftCoeffSampler(),
            'bold_response_levels' : jde_asl_physio.BOLDResponseLevelSampler(),
            'perf_response_levels' : jde_asl_physio.PerfResponseLevelSampler(),
            'bold_mixt_params' : jde_asl_physio.BOLDMixtureSampler(),
            'perf_mixt_params' : jde_asl_physio.PerfMixtureSampler(),
            'labels' : jde_asl_physio.LabelSampler(),
            'perf_baseline' : jde_asl_physio.PerfBaselineSampler(),
            'perf_baseline_var' : jde_asl_physio.PerfBaselineVarianceSampler(),
            'check_final_value' : None,
        }


        sampler = jde_asl_physio.ASLPhysioSampler(**sampler_params)

        simu_items = phym.simulate_asl_physio_rfs(spatial_size='random_small')
        simu_fdata = FmriData.from_simulation_dict(simu_items)

        dt = simu_items['dt']
        analyser = JDEMCMCAnalyser(sampler=sampler, osfMax=4, dtMin=.4,
                                   dt=dt, driftParam=4, driftType='polynomial',
                                   outputPrefix='jde_mcmc_')

        treatment = FMRITreatment(fmri_data=simu_fdata, analyser=analyser,
                                  output_dir=None)
        treatment.run()
Example #25
0
    def test_default_jde_small_simulation(self):
        """ Test ASL Physio sampler on small simulation with small nb of
        iterations. Estimation accuracy is not tested.
        """
        pyhrf.verbose.set_verbosity(0)

        sampler_params = {
            jde_asl_physio.ASLPhysioSampler.P_NB_ITERATIONS : 100,
            jde_asl_physio.ASLPhysioSampler.P_SMPL_HIST_PACE : 1,
            jde_asl_physio.ASLPhysioSampler.P_OBS_HIST_PACE : 1,
            'brf' : jde_asl_physio.PhysioBOLDResponseSampler(zero_constraint=False),
            'brf_var' : jde_asl_physio.PhysioBOLDResponseVarianceSampler(val_ini=\
                                                                         np.array([1e-3])),
            'prf' : jde_asl_physio.PhysioPerfResponseSampler(zero_constraint=False),
            'prf_var' : jde_asl_physio.PhysioPerfResponseVarianceSampler(val_ini=\
                                                                         np.array([1e-3])),
            'noise_var' : jde_asl_physio.NoiseVarianceSampler(),
            'drift_var' : jde_asl_physio.DriftVarianceSampler(),
            'drift_coeff' : jde_asl_physio.DriftCoeffSampler(),
            'brl' : jde_asl_physio.BOLDResponseLevelSampler(),
            'prl' : jde_asl_physio.PerfResponseLevelSampler(),
            'bold_mixt_params' : jde_asl_physio.BOLDMixtureSampler(),
            'perf_mixt_params' : jde_asl_physio.PerfMixtureSampler(),
            'label' : jde_asl_physio.LabelSampler(),
            'perf_baseline' : jde_asl_physio.PerfBaselineSampler(),
            'perf_baseline_var' : jde_asl_physio.PerfBaselineVarianceSampler(),
            'assert_final_value_close_to_true' : False,
        }


        sampler = jde_asl_physio.ASLPhysioSampler(sampler_params)

        simu_items = phym.simulate_asl_physio_rfs(spatial_size='random_small')
        simu_fdata = FmriData.from_simulation_dict(simu_items)

        dt = simu_items['dt']
        analyser = JDEMCMCAnalyser(sampler=sampler, osfMax=4, dtMin=.4,
                                   dt=dt, driftParam=4, driftType='polynomial',
                                   outputFile=None,outputPrefix='jde_mcmc_',
                                   randomSeed=None)

        treatment = FMRITreatment(fmri_data=simu_fdata, analyser=analyser)
        treatment.run()
Example #26
0
    def test_default_jde_small_simulation(self):
        """ Test ASL Physio sampler on small simulation with small nb of
        iterations. Estimation accuracy is not tested.
        """

        sampler_params = {
            'nb_iterations': 3,
            'smpl_hist_pace': 1,
            'obs_hist_pace': 1,
            'brf': jde_asl_physio.PhysioBOLDResponseSampler(zero_constraint=False),
            'brf_var': jde_asl_physio.PhysioBOLDResponseVarianceSampler(val_ini=np.array([1e-3])),
            'prf': jde_asl_physio.PhysioPerfResponseSampler(zero_constraint=False),
            'prf_var': jde_asl_physio.PhysioPerfResponseVarianceSampler(val_ini=np.array([1e-3])),
            'noise_var': jde_asl_physio.NoiseVarianceSampler(),
            'drift_var': jde_asl_physio.DriftVarianceSampler(),
            'drift': jde_asl_physio.DriftCoeffSampler(),
            'bold_response_levels': jde_asl_physio.BOLDResponseLevelSampler(),
            'perf_response_levels': jde_asl_physio.PerfResponseLevelSampler(),
            'bold_mixt_params': jde_asl_physio.BOLDMixtureSampler(),
            'perf_mixt_params': jde_asl_physio.PerfMixtureSampler(),
            'labels': jde_asl_physio.LabelSampler(),
            'perf_baseline': jde_asl_physio.PerfBaselineSampler(),
            'perf_baseline_var': jde_asl_physio.PerfBaselineVarianceSampler(),
            'check_final_value': None,
        }

        sampler = jde_asl_physio.ASLPhysioSampler(**sampler_params)

        simu_items = phym.simulate_asl_physio_rfs(spatial_size='random_small')
        simu_fdata = FmriData.from_simulation_dict(simu_items)

        dt = simu_items['dt']
        analyser = JDEMCMCAnalyser(sampler=sampler, osfMax=4, dtMin=.4,
                                   dt=dt, driftParam=4, driftType='polynomial',
                                   outputPrefix='jde_mcmc_')

        treatment = FMRITreatment(fmri_data=simu_fdata, analyser=analyser,
                                  output_dir=None)
        treatment.run()
    def test_full_sampler(self):
        """ Test JDE on simulation with normal size.
        Estimation accuracy is tested.
        """
        # pyhrf.verbose.set_verbosity(2)
        pyhrf.logger.setLevel(logging.INFO)

        simu = simulate_bold(self.tmp_dir, spatial_size='normal',
                             normalize_hrf=False)
        simu = FmriData.from_simulation_dict(simu)

        sampler = BG(self.sampler_params_for_full_test)

        analyser = JDEMCMCAnalyser(sampler=sampler, osfMax=4, dtMin=.4,
                                   dt=.5, driftParam=4, driftType='polynomial',
                                   outputPrefix='jde_mcmc_',
                                   randomSeed=None)

        treatment = FMRITreatment(fmri_data=simu,
                                  analyser=analyser, output_dir=self.tmp_dir)

        treatment.run()
        print 'output_dir:', self.tmp_dir
    def test_full_sampler(self):
        """ Test JDE on simulation with normal size.
        Estimation accuracy is tested.
        """
        # pyhrf.verbose.set_verbosity(2)
        pyhrf.logger.setLevel(logging.INFO)

        simu = simulate_bold(self.tmp_dir, spatial_size='normal',
                             normalize_hrf=False)
        simu = FmriData.from_simulation_dict(simu)

        sampler = BG(self.sampler_params_for_full_test)

        analyser = JDEMCMCAnalyser(sampler=sampler, osfMax=4, dtMin=.4,
                                   dt=.5, driftParam=4, driftType='polynomial',
                                   outputPrefix='jde_mcmc_',
                                   randomSeed=None)

        treatment = FMRITreatment(fmri_data=simu,
                                  analyser=analyser, output_dir=self.tmp_dir)

        treatment.run()
        print 'output_dir:', self.tmp_dir
Example #29
0
def glm_nipy_from_files(bold_file, tr,  paradigm_csv_file, output_dir,
                        mask_file, session=0, contrasts=None,
                        con_test_baseline=0.0,
                        hrf_model='Canonical',
                        drift_model='Cosine', hfcut=128,
                        residuals_model='spherical', fit_method='ols',
                        fir_delays=[0]):
    """
    #TODO: handle surface data
    hrf_model : Canonical | Canonical with Derivative | FIR

    """

    fdata = FmriData.from_vol_files(mask_file, paradigm_csv_file,
                                    [bold_file], tr)
    g, dm, cons = glm_nipy(fdata, contrasts=contrasts, hrf_model=hrf_model,
                            hfcut=hfcut, drift_model=drift_model,
                            residuals_model=residuals_model,
                            fit_method=fit_method, fir_delays=fir_delays)

    ns, nr = dm.matrix.shape
    cdesign_matrix = xndarray(dm.matrix, axes_names=['time','regressor'],
                            axes_domains={'time':np.arange(ns)*tr,
                                          'regressor':dm.names})

    cdesign_matrix.save(op.join(output_dir, 'design_matrix.nii'))

    beta_files = []
    beta_values = dict.fromkeys(dm.names)
    beta_vars = dict.fromkeys(dm.names)
    beta_vars_voxels = dict.fromkeys(dm.names)
    for ib, bname in enumerate(dm.names):
        #beta values
        beta_vol = expand_array_in_mask(g.beta[ib], fdata.roiMask>0)
        beta_fn = op.join(output_dir, 'beta_%s.nii' %bname)
        write_volume(beta_vol, beta_fn, fdata.meta_obj)
        beta_files.append(beta_fn)
        beta_values[bname] = beta_vol

        #normalized variance of betas
        beta_vars[bname] = sp.diag(g.nvbeta)[ib] #variance: diag of cov matrix
        #sig2 = g.s2 #ResMS
        var_cond = sp.diag(g.nvbeta)[ib]*g.s2 #variance for all voxels, condition ib
        beta_vars_voxels[bname] = var_cond
        #beta_var_fn = op.join(output_dir, 'var_beta_%s.nii' %bname)
        #write_volume(beta_var, beta_var_fn, fdata.meta_obj)
        #beta_var_files.append(beta_var_fn)

    if cons is not None:
        con_files = []
        pval_files = []
        for cname, con in cons.iteritems():
            con_vol = expand_array_in_mask(con.effect, fdata.roiMask>0)
            con_fn = op.join(output_dir, 'con_effect_%s.nii' %cname)
            write_volume(con_vol, con_fn, fdata.meta_obj)
            con_files.append(con_fn)

            pval_vol = expand_array_in_mask(con.pvalue(con_test_baseline),
                                            fdata.roiMask>0)
            pval_fn = op.join(output_dir, 'con_pvalue_%s.nii' %cname)
            write_volume(pval_vol, pval_fn, fdata.meta_obj)
            pval_files.append(pval_fn)
    else:
        con_files = None
        pval_files = None

    dof = g.dof
    #if do_ppm:
        #for

    #TODO: FIR stuffs
    return beta_files, beta_values, beta_vars_voxels, dof#, con_files, pval_files
Example #30
0
def glm_nipy_from_files(bold_file,
                        tr,
                        paradigm_csv_file,
                        output_dir,
                        mask_file,
                        session=0,
                        contrasts=None,
                        con_test_baseline=0.0,
                        hrf_model='Canonical',
                        drift_model='Cosine',
                        hfcut=128,
                        residuals_model='spherical',
                        fit_method='ols',
                        fir_delays=[0]):
    """
    #TODO: handle surface data
    hrf_model : Canonical | Canonical with Derivative | FIR

    """

    fdata = FmriData.from_vol_files(mask_file, paradigm_csv_file, [bold_file],
                                    tr)
    g, dm, cons = glm_nipy(fdata,
                           contrasts=contrasts,
                           hrf_model=hrf_model,
                           hfcut=hfcut,
                           drift_model=drift_model,
                           residuals_model=residuals_model,
                           fit_method=fit_method,
                           fir_delays=fir_delays)

    ns, nr = dm.matrix.shape
    cdesign_matrix = xndarray(dm.matrix,
                              axes_names=['time', 'regressor'],
                              axes_domains={
                                  'time': np.arange(ns) * tr,
                                  'regressor': dm.names
                              })

    cdesign_matrix.save(op.join(output_dir, 'design_matrix.nii'))

    beta_files = []
    beta_values = dict.fromkeys(dm.names)
    beta_vars = dict.fromkeys(dm.names)
    beta_vars_voxels = dict.fromkeys(dm.names)
    for ib, bname in enumerate(dm.names):
        # beta values
        beta_vol = expand_array_in_mask(g.beta[ib], fdata.roiMask > 0)
        beta_fn = op.join(output_dir, 'beta_%s.nii' % bname)
        write_volume(beta_vol, beta_fn, fdata.meta_obj)
        beta_files.append(beta_fn)
        beta_values[bname] = beta_vol

        # normalized variance of betas
        # variance: diag of cov matrix
        beta_vars[bname] = sp.diag(g.nvbeta)[ib]
        # sig2 = g.s2 #ResMS
        # variance for all voxels, condition ib
        var_cond = sp.diag(g.nvbeta)[ib] * g.s2
        beta_vars_voxels[bname] = var_cond
        #beta_var_fn = op.join(output_dir, 'var_beta_%s.nii' %bname)
        #write_volume(beta_var, beta_var_fn, fdata.meta_obj)
        # beta_var_files.append(beta_var_fn)

    if cons is not None:
        con_files = []
        pval_files = []
        for cname, con in cons.iteritems():
            con_vol = expand_array_in_mask(con.effect, fdata.roiMask > 0)
            con_fn = op.join(output_dir, 'con_effect_%s.nii' % cname)
            write_volume(con_vol, con_fn, fdata.meta_obj)
            con_files.append(con_fn)

            pval_vol = expand_array_in_mask(con.pvalue(con_test_baseline),
                                            fdata.roiMask > 0)
            pval_fn = op.join(output_dir, 'con_pvalue_%s.nii' % cname)
            write_volume(pval_vol, pval_fn, fdata.meta_obj)
            pval_files.append(pval_fn)
    else:
        con_files = None
        pval_files = None

    dof = g.dof
    # if do_ppm:
    # for

    # TODO: FIR stuffs
    # , con_files, pval_files
    return beta_files, beta_values, beta_vars_voxels, dof
Example #31
0
    def setUp(self):
        np.random.seed(8652761)
        tmpDir = tempfile.mkdtemp(prefix='pyhrf_tests',
                                  dir=pyhrf.cfg['global']['tmp_path'])
        self.tmp_dir = tmpDir
        self.clean_tmp = True
        bf = 'subj0_bold_session0.nii.gz'
        self.boldFiles = [pyhrf.get_data_file_name(bf)]
        pf = 'subj0_parcellation.nii.gz'
        self.parcelFile = pyhrf.get_data_file_name(pf)
        self.tr = 2.4
        self.dt = .6
        self.onsets = pyhrf.paradigm.onsets_loc_av
        self.durations = None
        self.nbIt = 3
        self.pfMethod = 'es'

        simu = simulate_bold(self.tmp_dir, spatial_size='random_small')
        self.data_simu = FmriData.from_simulation_dict(simu)

        self.sampler_params_for_single_test = {
            'nb_iterations': 100,
            'smpl_hist_pace': 1,
            'obs_hist_pace': 1,
            # level of spatial correlation = beta
            'beta': BS({
                'do_sampling': False,
                'use_true_value': False,
                'val_ini': np.array([0.6]),
            }),
            # HRF
            'hrf': HS({
                'do_sampling': False,
                'use_true_value': True,
                'prior_type': 'singleHRF',
            }),
            # HRF variance
            'hrf_var': HVS({
                'use_true_value': True,
                'do_sampling': False,
            }),
            # neural response levels (stimulus-induced effects)
            'nrl': NS({
                'use_true_nrls': True,
                'use_true_labels': True,
                'do_sampling': False,
                'do_label_sampling': False,
            }),
            'mixt_params': BGMS({
                'do_sampling': False,
                'use_true_value': True,
            }),
            'noise_var': NoiseVarianceSampler({
                'do_sampling': False,
                'use_true_value': True,
            }),
            'check_final_value_close_to_true': 'raise',  # print or raise
        }

        self.sampler_params_for_full_test = {
            'nb_iterations': 500,
            'smpl_hist_pace': 1,
            'obs_hist_pace': 1,
            # level of spatial correlation = beta
            'beta': BS({
                'do_sampling': True,
                'use_true_value': False,
                'val_ini': np.array([0.6]),
            }),
            # HRF
            'hrf': HS({
                'do_sampling': True,
                'use_true_value': False,
                'normalise': 1.,
            }),
            # HRF variance
            'hrf_var': HVS({
                'use_true_value': False,
                'do_sampling': True,
            }),
            # neural response levels (stimulus-induced effects)
            'nrl': NS({
                'use_true_nrls': False,
                'use_true_labels': False,
                'do_sampling': True,
                'do_label_sampling': True,
            }),
            'mixt_params': BGMS({
                'do_sampling': True,
                'use_true_value': False,
            }),
            'noise_var': NoiseVarianceSampler({
                'do_sampling': True,
                'use_true_value': False,
            }),
            'check_final_value_close_to_true': 'print',  # print or raise
        }
Example #32
0
        def setUp(self):
            np.random.seed(8652761)

            tmpDir = tempfile.mkdtemp(prefix='pyhrf_tests',
                                      dir=pyhrf.cfg['global']['tmp_path'])
            self.tmp_dir = tmpDir
            self.clean_tmp = True

            bf = 'subj0_bold_session0.nii.gz'
            self.boldFiles = [pyhrf.get_data_file_name(bf)]
            pf = 'subj0_parcellation.nii.gz'
            self.parcelFile = pyhrf.get_data_file_name(pf)
            self.tr = 2.4
            self.dt = .6
            self.onsets = pyhrf.onsets_loc_av
            self.durations = None
            self.nbIt = 3
            self.pfMethod = 'es'

            simu = simulate_bold(self.tmp_dir, spatial_size='random_small')
            self.data_simu = FmriData.from_simulation_dict(simu)

            self.sampler_params_for_single_test = {
                BG.P_NB_ITERATIONS: 100,
                BG.P_SMPL_HIST_PACE: 1,
                BG.P_OBS_HIST_PACE: 1,
                # level of spatial correlation = beta
                BG.P_BETA: BS({
                    BS.P_SAMPLE_FLAG: False,
                    BS.P_USE_TRUE_VALUE: False,
                    BS.P_VAL_INI: np.array([0.6]),
                }),
                # HRF
                BG.P_HRF: HRFARSampler({
                    HS.P_SAMPLE_FLAG: False,
                    HS.P_USE_TRUE_VALUE: True,
                    HS.P_PRIOR_TYPE: 'singleHRF',
                }),
                # HRF variance
                BG.P_RH: HVS({
                    HVS.P_USE_TRUE_VALUE: True,
                    HVS.P_SAMPLE_FLAG: False,
                }),
                # neural response levels (stimulus-induced effects)
                BG.P_NRLS: NRLARSampler({
                    NS.P_USE_TRUE_NRLS: True,
                    NS.P_USE_TRUE_LABELS: True,
                    NS.P_SAMPLE_FLAG: False,
                    NS.P_SAMPLE_LABELS: False,
                }),
                BG.P_MIXT_PARAM: BGMS({
                    BGMS.P_SAMPLE_FLAG: False,
                    BGMS.P_USE_TRUE_VALUE: True,
                }),
                BG.P_NOISE_VAR: NoiseVarianceARSampler({
                    NoiseVarianceARSampler.P_SAMPLE_FLAG: False,
                    NoiseVarianceARSampler.P_USE_TRUE_VALUE: True,
                }),
                BG.P_NOISE_ARP: NoiseARParamsSampler({
                    NoiseARParamsSampler.P_SAMPLE_FLAG: False,
                    NoiseARParamsSampler.P_USE_TRUE_VALUE: True,
                }),

                BG.P_CHECK_FINAL_VALUE: 'raise',  # print or raise
            }

            self.sampler_params_for_full_test = {
                BG.P_NB_ITERATIONS: 500,
                BG.P_SMPL_HIST_PACE: 1,
                BG.P_OBS_HIST_PACE: 1,
                # level of spatial correlation = beta
                BG.P_BETA: BS({
                    BS.P_SAMPLE_FLAG: True,
                    BS.P_USE_TRUE_VALUE: False,
                    BS.P_VAL_INI: np.array([0.6]),
                }),
                # HRF
                BG.P_HRF: HRFARSampler({
                    HS.P_SAMPLE_FLAG: True,
                    HS.P_USE_TRUE_VALUE: False,
                    HS.P_NORMALISE: 1.,
                }),
                # HRF variance
                BG.P_RH: HVS({
                    HVS.P_USE_TRUE_VALUE: False,
                    HVS.P_SAMPLE_FLAG: True,
                }),
                # neural response levels (stimulus-induced effects)
                BG.P_NRLS: NRLARSampler({
                    NS.P_USE_TRUE_NRLS: False,
                    NS.P_USE_TRUE_LABELS: False,
                    NS.P_SAMPLE_FLAG: True,
                    NS.P_SAMPLE_LABELS: True,
                }),
                BG.P_MIXT_PARAM: BGMS({
                    BGMS.P_SAMPLE_FLAG: True,
                    BGMS.P_USE_TRUE_VALUE: False,
                }),
                BG.P_NOISE_VAR: NoiseVarianceARSampler({
                    NoiseVarianceARSampler.P_SAMPLE_FLAG: True,
                    NoiseVarianceARSampler.P_USE_TRUE_VALUE: False,
                }),
                BG.P_NOISE_ARP: NoiseARParamsSampler({
                    NoiseARParamsSampler.P_SAMPLE_FLAG: True,
                    NoiseARParamsSampler.P_USE_TRUE_VALUE: False,
                }),
                BG.P_CHECK_FINAL_VALUE: 'print',  # print or raise
            }