コード例 #1
0
    def analyse_roi(self, roiData):
        # roiData is of type FmriRoiData, see pyhrf.core.FmriRoiData
        # roiData.bold : numpy array of shape
        # BOLD has shape (nscans, nvoxels)
        # roiData.graph #list of neighbours
        n_scan_allsession, nvox = roiData.bold.shape
        n_scan = n_scan_allsession / self.n_session
        data0 = roiData.bold.reshape(self.n_session, n_scan, nvox)
        data = np.zeros_like(data0)
        for s in xrange(self.n_session):
            data_mean = np.mean(data0[s, :, :])
            data_range = (np.max(data0[s, :, :]) - np.min(data0[s, :, :]))
            data[s, :, :] = (data0[s, :, :] - data_mean) * 100 / data_range
        Onsets = roiData.paradigm.get_joined_onsets_dim()
        durations = roiData.paradigm.get_joined_durations_dim()
        TR = roiData.tr
        beta = self.beta
        scale = 1  # roiData.nbVoxels
        #nvox = roiData.get_nb_vox_in_mask()
        if self.scale:
            scale = nvox
        rid = roiData.get_roi_id()
        logger.info("JDE VEM - roi %d, nvox=%d, nconds=%d, nItMax=%d", rid,
                    nvox, len(Onsets), self.nItMax)

        #self.contrasts.pop('dummy_example', None)
        cNames = roiData.paradigm.get_stimulus_names()
        graph = roiData.get_graph()
        idx_tag1 = roiData.get_extra_data('asl_first_tag_scan_idx', 0)

        t_start = time()

        logger.info("fast VEM with drift estimation and a constraint")
        try:
            simu = roiData.simulation[0]
        except:
            try:
                simu = roiData.simulation
            except:
                simu = None

        if self.physio:
            NbIter, brls, estimated_brf, prls, estimated_prf, labels, \
            noiseVar, mu_Ma, sigma_Ma, mu_Mc, sigma_Mc, Beta, L, PL, alpha,\
            Sigma_brls, Sigma_prls, Sigma_brf, Sigma_prf, rerror, \
            CONTRAST_A, CONTRASTVAR_A, CONTRAST_C, CONTRASTVAR_C, \
            cA, cH, cC, cG, cZ, cAH, cCG, cTime, FE = Main_vbjde_physio(
                                       graph, data, Onsets, durations, self.hrfDuration,
                                       self.nbClasses, TR, beta, self.dt, scale=scale,
                                       estimateSigmaG=self.estimateSigmaG,
                                       sigmaH=self.sigmaH, sigmaG=self.sigmaG,
                                       gamma_h=self.gammaH, gamma_g=self.gammaG,
                                       NitMax=self.nItMax, NitMin=self.nItMin,
                                       estimateSigmaH=self.estimateSigmaH,
                                       estimateBeta=self.estimateBeta, PLOT=self.PLOT,
                                       contrasts=self.contrasts,
                                       computeContrast=self.computeContrast,
                                       idx_first_tag=idx_tag1,
                                       simulation=simu, sigmaMu=self.sigmaMu,
                                       estimateH=self.estimateH,
                                       estimateG=self.estimateG,
                                       estimateA=self.estimateA,
                                       estimateC=self.estimateC,
                                       estimateNoise=self.estimateNoise,
                                       estimateMP=self.estimateMixtParam,
                                       estimateZ=self.estimateLabels,
                                       estimateLA=self.estimateLA,
                                       constraint=self.constrained,
                                       positivity=self.positivity,
                                       use_hyperprior=self.use_hyperprior,
                                       phy_params=self.phy_params,
                                       prior=self.prior, zc=self.zc)

        # Plot analysis duration
        self.analysis_duration = time() - t_start
        logger.info('JDE VEM analysis took: %s',
                    format_duration(self.analysis_duration))

        # OUTPUTS: Pack all outputs within a dict
        logger.info("Preparing outputs... ")
        outputs = {}
        brf_time = np.arange(len(estimated_brf)) * self.dt
        outputs['brf'] = xndarray(estimated_brf,
                                  axes_names=['time'],
                                  axes_domains={'time': brf_time},
                                  value_label="BRF")
        #logger.info("BRF prepared ")
        domCondition = {'condition': cNames}
        outputs['brls'] = xndarray(brls.T,
                                   value_label="BRLs",
                                   axes_names=['condition', 'voxel'],
                                   axes_domains=domCondition)
        #logger.info("BRLs prepared ")
        prf_time = np.arange(len(estimated_prf)) * self.dt
        outputs['prf'] = xndarray(estimated_prf,
                                  axes_names=['time'],
                                  axes_domains={'time': prf_time},
                                  value_label="PRF")
        #logger.info("PRF prepared ")
        outputs['prls'] = xndarray(prls.T,
                                   value_label="PRLs",
                                   axes_names=['condition', 'voxel'],
                                   axes_domains=domCondition)
        #logger.info("PRLs prepared ")

        outputs['Sigma_brf'] = xndarray(Sigma_brf, value_label="Sigma_BRF")
        #logger.info("Sigma_BRF prepared ")
        outputs['Sigma_prf'] = xndarray(Sigma_prf, value_label="Sigma_PRF")
        #logger.info("Sigma_PRF prepared ")

        ad = {'condition': cNames, 'condition2': Onsets.keys()}
        outputs['Sigma_brls'] = xndarray(
            Sigma_brls,
            value_label="Sigma_BRLs",
            axes_names=['condition', 'condition2', 'voxel'],
            axes_domains=ad)
        #logger.info("Sigma_a prepared ")
        outputs['Sigma_prls'] = xndarray(
            Sigma_prls,
            value_label="Sigma_PRLs",
            axes_names=['condition', 'condition2', 'voxel'],
            axes_domains=ad)
        #logger.info("Sigma_c prepared ")
        outputs['NbIter'] = xndarray(np.array([NbIter]), value_label="NbIter")
        outputs['beta'] = xndarray(Beta,
                                   value_label="beta",
                                   axes_names=['condition'],
                                   axes_domains=domCondition)

        #logger.info("perfusion baseline prepared ")
        outputs['alpha'] = xndarray(alpha,
                                    value_label="Perf_baseline",
                                    axes_names=['voxel'])

        #logger.info("Beta prepared ")
        nbc, nbv = len(cNames), brls.shape[0]
        repeatedBeta = np.repeat(Beta, nbv).reshape(nbc, nbv)
        outputs['beta_mapped'] = xndarray(repeatedBeta,
                                          value_label="beta",
                                          axes_names=['condition', 'voxel'],
                                          axes_domains=domCondition)

        repeated_brf = np.repeat(estimated_brf, nbv).reshape(-1, nbv)
        outputs["brf_mapped"] = xndarray(repeated_brf,
                                         value_label="BRFs",
                                         axes_names=["time", "voxel"],
                                         axes_domains={"time": brf_time})

        repeated_prf = np.repeat(estimated_prf, nbv).reshape(-1, nbv)
        outputs["prf_mapped"] = xndarray(repeated_prf,
                                         value_label="PRFs",
                                         axes_names=["time", "voxel"],
                                         axes_domains={"time": prf_time})

        #logger.info("beta mapped prepared ")
        outputs['roi_mask'] = xndarray(np.zeros(nbv) + roiData.get_roi_id(),
                                       value_label="ROI",
                                       axes_names=['voxel'])

        #logger.info("ROI mask prepared ")
        mixtpB = np.zeros((roiData.nbConditions, self.nbClasses, 2))
        mixtpB[:, :, 0] = mu_Ma
        mixtpB[:, :, 1] = sigma_Ma**2
        mixtpP = np.zeros((roiData.nbConditions, self.nbClasses, 2))
        mixtpP[:, :, 0] = mu_Mc
        mixtpP[:, :, 1] = sigma_Mc**2
        an = ['condition', 'Act_class', 'component']
        ad = {
            'Act_class': ['inactiv', 'activ'],
            'condition': cNames,
            'component': ['mean', 'var']
        }
        outputs['mixt_pB'] = xndarray(mixtpB, axes_names=an, axes_domains=ad)
        outputs['mixt_pP'] = xndarray(mixtpP, axes_names=an, axes_domains=ad)
        #logger.info("Mixture parameters prepared ")
        an = ['condition', 'Act_class', 'voxel']
        ad = {'Act_class': ['inactiv', 'activ'], 'condition': cNames}
        #logger.info("mixt params prepared ")
        outputs['labels'] = xndarray(labels,
                                     value_label="Labels",
                                     axes_names=an,
                                     axes_domains=ad)
        #logger.info("labels prepared ")
        outputs['noiseVar'] = xndarray(noiseVar,
                                       value_label="noiseVar",
                                       axes_names=['voxel'])
        #logger.info("noise variance prepared ")
        if self.estimateLA:
            outputs['drift_coeff'] = xndarray(L,
                                              value_label="Drift",
                                              axes_names=['coeff', 'voxel'])
            outputs['drift'] = xndarray(PL,
                                        value_label="Delta BOLD",
                                        axes_names=['time', 'voxel'])
            logger.info("drift prepared ")
        logger.info("outputs prepared ")

        if (len(self.contrasts) > 0) and self.computeContrast:
            #keys = list((self.contrasts[nc]) for nc in self.contrasts)
            domContrast = {'contrast': self.contrasts.keys()}
            outputs['contrastsA'] = xndarray(CONTRAST_A,
                                             value_label="Contrast_A",
                                             axes_names=['voxel', 'contrast'],
                                             axes_domains=domContrast)
            outputs['contrastsC'] = xndarray(CONTRAST_C,
                                             value_label="Contrast_C",
                                             axes_names=['voxel', 'contrast'],
                                             axes_domains=domContrast)
            c = xndarray(CONTRASTVAR_A,
                         value_label="Contrasts_Variance_A",
                         axes_names=['voxel', 'contrast'],
                         axes_domains=domContrast)
            outputs['contrasts_variance_a'] = c
            outputs['ncontrasts_a'] = xndarray(
                CONTRAST_A / CONTRASTVAR_A**.5,
                value_label="Normalized Contrast A",
                axes_names=['voxel', 'contrast'],
                axes_domains=domContrast)
            c = xndarray(CONTRASTVAR_C,
                         value_label="Contrasts_Variance_C",
                         axes_names=['voxel', 'contrast'],
                         axes_domains=domContrast)
            outputs['contrasts_variance_c'] = c
            outputs['ncontrasts_c'] = xndarray(
                CONTRAST_C / CONTRASTVAR_C**.5,
                value_label="Normalized Contrast C",
                axes_names=['voxel', 'contrast'],
                axes_domains=domContrast)

        #######################################################################
        # CONVERGENCE
        if 1:
            cTimeMean = cTime[-1] / np.float(NbIter)
            logger.info("Saving convergence... ")

            axes_names = ['duration']
            ax = (np.arange(self.nItMax) + 1) * cTimeMean
            ax[:len(cTime)] = cTime
            ad = {'duration': ax}

            outName = 'convergence_Labels'
            c = np.zeros(self.nItMax)  # -.001 #
            c[:len(cZ)] = cZ
            outputs[outName] = xndarray(c,
                                        axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_Z')
            outName = 'convergence_BRF'
            #ad = {'Conv_Criterion':np.arange(len(cH))}
            c = np.zeros(self.nItMax)  # -.001 #
            c[:len(cH)] = cH
            outputs[outName] = xndarray(c,
                                        axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_H')
            outName = 'convergence_BRL'
            c = np.zeros(self.nItMax)  # -.001 #
            c[:len(cA)] = cA
            #ad = {'Conv_Criterion':np.arange(len(cA))}
            outputs[outName] = xndarray(c,
                                        axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_A')
            outName = 'convergence_PRF'
            #ad = {'Conv_Criterion':np.arange(len(cH))}
            c = np.zeros(self.nItMax)  # -.001 #
            c[:len(cG)] = cG
            outputs[outName] = xndarray(c,
                                        axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_G')
            outName = 'convergence_PRL'
            c = np.zeros(self.nItMax)  # -.001 #
            c[:len(cC)] = cC
            #ad = {'Conv_Criterion':np.arange(len(cA))}
            outputs[outName] = xndarray(c,
                                        axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_C')
            outName = 'convergence_FE'
            c = np.zeros(self.nItMax)  # -.001 #
            c[:len(FE)] = FE
            outputs[outName] = xndarray(c,
                                        axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_FE')
            logger.info("Convergence saved ")

        #######################################################################
        # SIMULATION
        if self.simulation is not None and 0:
            logger.info("Prepare parameters to compare if simulation")
            M = labels.shape[0]
            K = labels.shape[1]
            J = labels.shape[2]

            true_labels = np.zeros((M, J))
            for m in xrange(0, M):
                true_labels[
                    m, :] = roiData.simulation[0]['labels'][m].flatten()

            newlabels = np.reshape(labels[:, 1, :], (M, J))
            #true_labels = roiData.simulation[0]['labels']
            #newlabels = labels

            se = []
            sp = []
            size = np.prod(labels.shape)
            for i in xrange(0, 2):  # (0, M):
                se0, sp0, auc = roc_curve(newlabels[i, :].tolist(),
                                          true_labels[i, :].tolist())
                se.append(se0)
                sp.append(sp0)
                size = min(size, len(sp0))
            SE = np.zeros((M, size), dtype=float)
            SP = np.zeros((M, size), dtype=float)
            for i in xrange(0, 2):  # M):
                tmp = np.array(se[i])
                SE[i, :] = tmp[0:size]
                tmp = np.array(sp[i])
                SP[i, :] = tmp[0:size]
            sensData, specData = SE, SP
            axes_names = ['1-specificity', 'condition']
            outName = 'ROC_audio'
            #ad = {'1-specificity': specData[0], 'condition': cNames}
            outputs[outName] = xndarray(
                sensData,
                axes_names=axes_names,
                #axes_domains=ad,
                value_label='sensitivity')

            m = specData[0].min()
            import matplotlib.font_manager as fm
            import matplotlib.pyplot as plt
            plt.figure(200)
            plt.plot(sensData[0],
                     specData[0],
                     '--',
                     color='k',
                     linewidth=2.0,
                     label='m=1')
            plt.hold(True)
            plt.plot(sensData[1],
                     specData[1],
                     color='k',
                     linewidth=2.0,
                     label='m=2')
            # legend(('audio','video'))
            plt.xticks(color='k', size=14, fontweight='bold')
            plt.yticks(color='k', size=14, fontweight='bold')
            #xlabel('1 - Specificity',fontsize=16,fontweight='bold')
            # ylabel('Sensitivity',fontsize=16,fontweight='bold')
            prop = fm.FontProperties(size=14, weight='bold')
            plt.legend(loc=1, prop=prop)
            plt.axis([0., 1., m, 1.02])

            true_labels = roiData.simulation[0]['labels']
            true_brls = roiData.simulation[0]['nrls']
            true_prls = roiData.simulation[0]['prls']
            true_brf = roiData.simulation[0]['hrf'][:, 0]
            true_prf = roiData.simulation[0]['prf'][:, 0]
            true_drift = roiData.simulation[0]['drift']
            true_noise = roiData.simulation[0]['noise']

            if simu is not None:
                logger.info("Check parameters errors")
                self.finalizeEstimation(true_labels, newlabels, nvox, true_brf,
                                        estimated_brf, true_prf, estimated_prf,
                                        true_brls, brls.T, true_prls, prls.T,
                                        true_drift, PL, L, true_noise,
                                        noiseVar)

        # END SIMULATION
        #######################################################################
        d = {'parcel_size': np.array([nvox])}
        outputs['analysis_duration'] = xndarray(np.array(
            [self.analysis_duration]),
                                                axes_names=['parcel_size'],
                                                axes_domains=d)
        """outputs['rerror'] = xndarray(np.array(  rerror),
                                                axes_names=['parcel_size'])"""
        return outputs
コード例 #2
0
    def analyse_roi(self, roiData):
        #roiData is of type FmriRoiData, see pyhrf.core.FmriRoiData
        # roiData.bold : numpy array of shape
        ## BOLD has shape (nscans, nvoxels)

        #roiData.graph #list of neighbours
        data = roiData.bold
        Onsets = roiData.get_joined_onsets()
        durations = roiData.get_joined_durations()
        TR = roiData.tr
        #K = 2 #number of classes
        scale = 1#roiData.nbVoxels
        nvox = roiData.get_nb_vox_in_mask()
        if self.scale:
            scale = nvox
        rid = roiData.get_roi_id()
        logger.info("JDE VEM - roi %d, nvox=%d, nconds=%d, nItMax=%d", rid,
                    nvox, len(Onsets), self.nItMax)

        self.contrasts.pop('dummy_example', None)
        cNames = roiData.paradigm.get_stimulus_names()
        graph = roiData.get_graph()

        t_start = time()

        if self.fast:
            logger.info("fast VEM with drift estimation"+
                        ("and a constraint"*self.constrained))
            (nb_iter, nrls_mean, hrf_mean, hrf_covar, labels_proba, noise_var,
             nrls_class_mean, nrls_class_var, beta, drift_coeffs, drift,
             contrasts_mean, contrasts_var, _, _, nrls_covar, _, density_ratio,
             density_ratio_cano, density_ratio_diff, density_ratio_prod,
             ppm_a_nrl, ppm_g_nrl, ppm_a_contrasts, ppm_g_contrasts,
             variation_coeff, free_energy, free_energy_crit, beta_list,
             delay_of_response, delay_of_undershoot, dispersion_of_response,
             dispersion_of_undershoot, ratio_resp_under, delay) = jde_vem_bold(
                 graph, data, Onsets, durations, self.hrfDuration, self.nbClasses,
                 TR, self.beta, self.dt, self.estimateSigmaH, self.sigmaH, self.nItMax,
                 self.nItMin, self.estimateBeta, self.contrasts,
                 self.computeContrast, self.hyper_prior_sigma_H, self.estimateHRF,
                 constrained=self.constrained, zero_constraint=self.zero_constraint,
                 drifts_type=self.drifts_type
             )
        else:
            # if not self.fast
            if self.estimateDrifts:
                logger.info("not fast VEM")
                logger.info("NOT WORKING")
                nrls_mean, hrf_mean, \
                labels_proba, noise_var, nrls_class_mean, \
                nrls_class_var, beta, drift_coeffs, \
                drift = Main_vbjde_Python_constrained(graph,data,Onsets,
                                       self.hrfDuration,self.nbClasses,
                                       TR,beta,self.dt,scale,
                                       self.estimateSigmaH,self.sigmaH,
                                       self.nItMax,self.nItMin,
                                       self.estimateBeta,self.PLOT)

        # Plot analysis duration
        self.analysis_duration = time() - t_start
        logger.info('JDE VEM analysis took: %s',
                    format_duration(self.analysis_duration))


        if self.fast:
            ### OUTPUTS: Pack all outputs within a dict
            outputs = {}
            hrf_time = np.arange(len(hrf_mean)) * self.dt

            axes_names = ['iteration']
            """axes_domains = {'iteration':np.arange(FreeEnergy.shape[0])}
            outputs['FreeEnergy'] = xndarray(FreeEnergy,
                                        axes_names=axes_names,
                                        axes_domains=axes_domains)
            """
            outputs['hrf'] = xndarray(hrf_mean, axes_names=['time'],
                                      axes_domains={'time':hrf_time},
                                      value_label="HRF")

            domCondition = {'condition': cNames}
            outputs['nrls'] = xndarray(nrls_mean.transpose(), value_label="nrls",
                                       axes_names=['condition','voxel'],
                                       axes_domains=domCondition)

            ad = {'condition': cNames,'condition2': Onsets.keys()}

            outputs['Sigma_nrls'] = xndarray(nrls_covar, value_label="Sigma_NRLs",
                                             axes_names=['condition', 'condition2', 'voxel'],
                                             axes_domains=ad)

            outputs['nb_iter'] = xndarray(np.array([nb_iter]), value_label="nb_iter")

            outputs['beta'] = xndarray(beta, value_label="beta",
                                       axes_names=['condition'],
                                       axes_domains=domCondition)

            nbc, nbv = len(cNames), nrls_mean.shape[0]
            repeatedBeta = np.repeat(beta, nbv).reshape(nbc, nbv)
            outputs['beta_mapped'] = xndarray(repeatedBeta, value_label="beta",
                                              axes_names=['condition', 'voxel'],
                                              axes_domains=domCondition)

            repeated_hrf = np.repeat(hrf_mean, nbv).reshape(-1, nbv)
            outputs["hrf_mapped"] = xndarray(repeated_hrf, value_label="HRFs",
                                             axes_names=["time", "voxel"],
                                             axes_domains={"time": hrf_time})

            repeated_hrf_covar = np.repeat(np.diag(hrf_covar), nbv).reshape(-1, nbv)
            outputs["hrf_variance_mapped"] = xndarray(repeated_hrf_covar,
                                                      value_label="HRFs covariance",
                                                      axes_names=["time", "voxel"],
                                                      axes_domains={"time": hrf_time})

            outputs['roi_mask'] = xndarray(np.zeros(nbv)+roiData.get_roi_id(),
                                           value_label="ROI",
                                           axes_names=['voxel'])

            outputs["density_ratio"] = xndarray(np.zeros(nbv)+density_ratio,
                                                value_label="Density Ratio to zero",
                                                axes_names=["voxel"])

            outputs["density_ratio_cano"] = xndarray(np.zeros(nbv)+density_ratio_cano,
                                                     value_label="Density Ratio to canonical",
                                                     axes_names=["voxel"])

            outputs["density_ratio_diff"] = xndarray(np.zeros(nbv)+density_ratio_diff,
                                                     value_label="Density Ratio to canonical",
                                                     axes_names=["voxel"])

            outputs["density_ratio_prod"] = xndarray(np.zeros(nbv)+density_ratio_prod,
                                                     value_label="Density Ratio to canonical",
                                                     axes_names=["voxel"])

            outputs["variation_coeff"] = xndarray(np.zeros(nbv)+variation_coeff,
                                                  value_label="Coefficient of variation of the HRF",
                                                  axes_names=["voxel"])
            free_energy = np.concatenate((np.asarray(free_energy), np.zeros((self.nItMax - len(free_energy)))))
            free_energy[free_energy == 0.] = np.nan
            free_energy = np.repeat(free_energy, nbv).reshape(-1, nbv)
            outputs["free_energy"] = xndarray(free_energy,
                                              value_label="free energy",
                                              axes_names=["time", "voxel"])

            if self.estimateHRF:
                fitting_parameters = {
                    "hrf_fit_delay_of_response":  delay_of_response,
                    "hrf_fit_delay_of_undershoot":  delay_of_undershoot,
                    "hrf_fit_dispersion_of_response":  dispersion_of_response,
                    "hrf_fit_dispersion_of_undershoot":  dispersion_of_undershoot,
                    "hrf_fit_ratio_response_undershoot": ratio_resp_under,
                    "hrf_fit_delay": delay,
                }
                affine = np.eye(4)
                for param_name in fitting_parameters:
                    header = nibabel.Nifti1Header()
                    description = param_name[8:].replace("_", " ").capitalize()
                    outputs[param_name] = xndarray(
                        np.zeros(nbv)+fitting_parameters[param_name],
                        value_label=description + " of the fitted estimated HRF",
                        axes_names=["voxel"], meta_data=(affine, header)
                    )
                    outputs[param_name].meta_data[1]["descrip"] = description

            h = hrf_mean
            nrls_mean = nrls_mean.transpose()

            nvox = nrls_mean.shape[1]
            nbconds = nrls_mean.shape[0]
            ah = np.zeros((h.shape[0], nvox, nbconds))

            mixtp = np.zeros((roiData.nbConditions, self.nbClasses, 2))
            mixtp[:, :, 0] = nrls_class_mean
            mixtp[:, :, 1] = np.sqrt(nrls_class_var)

            an = ['condition', 'Act_class', 'component']
            ad = {'Act_class': ['inactiv', 'activ'],
                  'condition': cNames,
                  'component': ['mean', 'var']}
            outputs['mixt_p'] = xndarray(mixtp, axes_names=an, axes_domains=ad)

            ad = {'class': ['inactiv', 'activ'],
                  'condition': cNames}
            outputs['labels'] = xndarray(labels_proba, value_label="Labels",
                                         axes_names=['condition', 'class', 'voxel'],
                                         axes_domains=ad)
            outputs['noise_var'] = xndarray(noise_var,value_label="noise_var",
                                           axes_names=['voxel'])
            if self.estimateDrifts and self.output_drifts:
                outputs['drift_coeff'] = xndarray(drift_coeffs, value_label="Drift",
                                                  axes_names=['coeff', 'voxel'])
                outputs['drift'] = xndarray(drift, value_label="Delta BOLD",
                                            axes_names=['time', 'voxel'])

            affine = np.eye(4)
            for condition_nb, condition_name in enumerate(cNames):
                header = nibabel.Nifti1Header()
                outputs["ppm_a_nrl_"+condition_name] = xndarray(ppm_a_nrl[:, condition_nb],
                                                value_label="PPM NRL alpha fixed",
                                                axes_names=["voxel"],
                                                meta_data=(affine, header))
                outputs["ppm_a_nrl_"+condition_name].meta_data[1]["descrip"] = condition_name


                outputs["ppm_g_nrl_"+condition_name] = xndarray(ppm_g_nrl[:, condition_nb],
                                                                value_label="PPM NRL gamma fixed",
                                                                axes_names=["voxel"],
                                                                meta_data=(affine, header))
                outputs["ppm_g_nrl_"+condition_name].meta_data[1]["descrip"] = condition_name

            if (len(self.contrasts) > 0) and self.computeContrast:
                #keys = list((self.contrasts[nc]) for nc in self.contrasts)
                domContrast = {'contrast': self.contrasts.keys()}
                outputs['contrasts'] = xndarray(contrasts_mean, value_label="Contrast",
                                                axes_names=['voxel', 'contrast'],
                                                axes_domains=domContrast)
                #print 'contrast output:'
                #print outputs['contrasts'].descrip()

                c = xndarray(contrasts_var, value_label="Contrasts_Variance",
                             axes_names=['voxel', 'contrast'],
                             axes_domains=domContrast)
                outputs['contrasts_variance'] = c

                outputs['ncontrasts'] = xndarray(contrasts_mean/contrasts_var**.5,
                                                 value_label="Normalized Contrast",
                                                 axes_names=['voxel', 'contrast'],
                                                 axes_domains=domContrast)

                for i, contrast in enumerate(self.contrasts.keys()):
                    header = nibabel.Nifti1Header()
                    outputs["ppm_a_"+contrast] = xndarray(ppm_a_contrasts[:, i],
                                                          value_label="PPM Contrasts alpha fixed",
                                                          axes_names=["voxel"],
                                                          meta_data=(affine, header))
                    outputs["ppm_a_"+contrast].meta_data[1]["descrip"] = contrast

                    outputs["ppm_g_"+contrast] = xndarray(ppm_g_contrasts[:, i],
                                                          value_label="PPM Contrasts gamma fixed",
                                                          axes_names=["voxel"],
                                                          meta_data=(affine, header))
                    outputs["ppm_g_"+contrast].meta_data[1]["descrip"] = contrast


        ################################################################################
        # SIMULATION

        if self.simulation and self.fast:

            labels_vem_audio = roiData.simulation[0]['labels'][0]
            labels_vem_video = roiData.simulation[0]['labels'][1]

            M = labels_proba.shape[0]
            K = labels_proba.shape[1]
            J = labels_proba.shape[2]
            true_labels = np.zeros((K,J))
            true_labels[0,:] = np.reshape(labels_vem_audio,(J))
            true_labels[1,:] = np.reshape(labels_vem_video,(J))
            newlabels = np.reshape(labels_proba[:,1,:],(M,J))
            se = []
            sp = []
            size = np.prod(labels_proba.shape)

            for i in xrange(0,M):
                se0,sp0, auc = roc_curve(newlabels[i,:].tolist(),
                                         true_labels[i,:].tolist())
                se.append(se0)
                sp.append(sp0)
                size = min(size,len(sp0))
            SE = np.zeros((M,size),dtype=float)
            SP = np.zeros((M,size),dtype=float)
            for i in xrange(0,M):
                tmp = np.array(se[i])
                SE[i,:] = tmp[0:size]
                tmp = np.array(sp[i])
                SP[i,:] = tmp[0:size]

            sensData, specData = SE, SP
            axes_names = ['condition','1-specificity']
            outName = 'ROC_audio'
            ad = {'1-specificity':specData[0],'condition':cNames}
            outputs[outName] = xndarray(sensData, axes_names=axes_names,
                                      axes_domains=ad,
                                      value_label='sensitivity')

            m = specData[0].min()
            import matplotlib.font_manager as fm
            figure(200)
            plot(sensData[0],specData[0],'--',color='k',linewidth=2.0,label='m=1')
            hold(True)
            plot(sensData[1],specData[1],color='k',linewidth=2.0,label='m=2')
            #legend(('audio','video'))
            xticks(color = 'k', size = 14,fontweight='bold')
            yticks(color = 'k', size = 14,fontweight='bold')
            #xlabel('1 - Specificity',fontsize=16,fontweight='bold')
            #ylabel('Sensitivity',fontsize=16,fontweight='bold')
            prop = fm.FontProperties(size=14,weight='bold')
            legend(loc=1,prop=prop)
            axis([0., 1., m, 1.02])


            if hasattr(roiData.simulation, 'nrls'):
                true_labels = roiData.simulation.nrls.labels
                true_nrls = roiData.simulation.nrls.data
            elif isinstance(roiData.simulation, dict) and \
                    roiData.simulation.has_key('labels') and \
                    roiData.simulation.has_key('nrls') :
                true_labels = roiData.simulation['labels']
                true_nrls = roiData.simulation['nrls']
            else:
                raise Exception('Simulation can not be retrieved from %s' \
                                    %str(roiData.simulation))

            domCondition = {'condition':cNames}
            outputs['Truenrls'] = xndarray(true_nrls,value_label="True_nrls",
                                         axes_names=['condition','voxel'],
                                         axes_domains=domCondition)
            M = labels_proba.shape[0]
            K = labels_proba.shape[1]
            J = labels_proba.shape[2]

            newlabels = np.reshape(labels_proba[:,1,:],(M,J))

            for i in xrange(0,M):
                se0,sp0, auc = roc_curve(newlabels[i,:].tolist(),
                                         true_labels[i,:].tolist())
                se.append(se0)
                sp.append(sp0)
                size = min(size,len(sp0))
            SE = np.zeros((M,size),dtype=float)
            SP = np.zeros((M,size),dtype=float)
            for i in xrange(0,M):
                tmp = np.array(se[i])
                SE[i,:] = tmp[0:size]
                tmp = np.array(sp[i])
                SP[i,:] = tmp[0:size]

        # END SIMULATION
        ##########################################################################
        if self.fast:
            d = {'parcel_size': np.array([nvox])}
            outputs['analysis_duration'] = xndarray(np.array([self.analysis_duration]),
                                                    axes_names=['parcel_size'],
                                                    axes_domains=d)

        return outputs
コード例 #3
0
ファイル: vb_jde_analyser.py プロジェクト: ainafp/pyhrf
    def analyse_roi(self, roiData):
        #roiData is of type FmriRoiData, see pyhrf.core.FmriRoiData
        # roiData.bold : numpy array of shape
        ## BOLD has shape (nscans, nvoxels)

        #roiData.graph #list of neighbours
        data = roiData.bold
        Onsets = roiData.get_joined_onsets()
        TR = roiData.tr
        #K = 2 #number of classes
        beta = self.beta
        scale = 1#roiData.nbVoxels
        nvox = roiData.get_nb_vox_in_mask()
        if self.scale:
            scale = nvox
        rid = roiData.get_roi_id()
        logger.info("JDE VEM - roi %d, nvox=%d, nconds=%d, nItMax=%d", rid,
                    nvox, len(Onsets), self.nItMax)

        self.contrasts.pop('dummy_example', None)
        cNames = roiData.paradigm.get_stimulus_names()
        graph = roiData.get_graph()

        t_start = time()

        if self.fast:
            if not self.constrained:
                logger.info("fast VEM with drift estimation")

                NbIter, nrls, estimated_hrf, \
                labels, noiseVar, mu_k, sigma_k, \
                Beta, L, PL, CONTRAST, CONTRASTVAR, \
                cA,cH,cZ,cAH,cTime,cTimeMean, Sigma_nrls, \
                StimuIndSignal = Main_vbjde_Extension_stable(graph,data,Onsets, \
                                        self.hrfDuration, self.nbClasses,TR,
                                        beta,self.dt,scale,self.estimateSigmaH,
                                        self.sigmaH,self.nItMax, self.nItMin,
                                        self.estimateBeta,self.PLOT,
                                        self.contrasts,self.computeContrast,
                                        self.hyper_prior_sigma_H,self.estimateHRF,
                                        self.TrueHrfFlag, self.HrfFilename,
                                        self.estimateLabels,self.LabelsFilename,
                                        self.MFapprox,self.InitVar,self.InitMean,
                                        self.MiniVemFlag,self.NbItMiniVem)
            else:
                logger.info("fast VEM with drift estimation and a constraint")

                NbIter, nrls, estimated_hrf, \
                labels, noiseVar, mu_k, sigma_k, \
                Beta, L, PL, CONTRAST, CONTRASTVAR, \
                cA,cH,cZ,cAH,cTime,cTimeMean, \
                Sigma_nrls, StimuIndSignal,\
                FreeEnergy = Main_vbjde_Extension_constrained(graph,data,Onsets, \
                                        self.hrfDuration, self.nbClasses,TR,
                                        beta,self.dt,scale,self.estimateSigmaH,
                                        self.sigmaH,self.nItMax, self.nItMin,
                                        self.estimateBeta,self.PLOT,
                                        self.contrasts,self.computeContrast,
                                        self.hyper_prior_sigma_H,self.estimateHRF,
                                        self.TrueHrfFlag, self.HrfFilename,
                                        self.estimateLabels,self.LabelsFilename,
                                        self.MFapprox,self.InitVar,self.InitMean,
                                        self.MiniVemFlag,self.NbItMiniVem)
        else:
            # if not self.fast
            if self.estimateDrifts:
                logger.info("not fast VEM")
                logger.info("NOT WORKING")
                nrls, estimated_hrf, \
                labels, noiseVar, mu_k, \
                sigma_k, Beta, L, \
                PL = Main_vbjde_Python_constrained(graph,data,Onsets,
                                       self.hrfDuration,self.nbClasses,
                                       TR,beta,self.dt,scale,
                                       self.estimateSigmaH,self.sigmaH,
                                       self.nItMax,self.nItMin,
                                       self.estimateBeta,self.PLOT)

        # Plot analysis duration
        self.analysis_duration = time() - t_start
        logger.info('JDE VEM analysis took: %s',
                    format_duration(self.analysis_duration))


        if self.fast:
            ### OUTPUTS: Pack all outputs within a dict
            outputs = {}
            hrf_time = np.arange(len(estimated_hrf)) * self.dt

            axes_names = ['iteration']
            """axes_domains = {'iteration':np.arange(FreeEnergy.shape[0])}
            outputs['FreeEnergy'] = xndarray(FreeEnergy,
                                        axes_names=axes_names,
                                        axes_domains=axes_domains)
            """
            outputs['hrf'] = xndarray(estimated_hrf, axes_names=['time'],
                                axes_domains={'time':hrf_time},
                                value_label="HRF")

            domCondition = {'condition':cNames}
            outputs['nrls'] = xndarray(nrls.transpose(),value_label="NRLs",
                                    axes_names=['condition','voxel'],
                                    axes_domains=domCondition)

            ad = {'condition':cNames,'condition2':Onsets.keys()}

            outputs['Sigma_nrls'] = xndarray(Sigma_nrls,value_label="Sigma_NRLs",
                                            axes_names=['condition','condition2','voxel'],
                                            axes_domains=ad)

            outputs['NbIter'] = xndarray(np.array([NbIter]),value_label="NbIter")

            outputs['beta'] = xndarray(Beta,value_label="beta",
                                    axes_names=['condition'],
                                    axes_domains=domCondition)

            nbc, nbv = len(cNames), nrls.shape[0]
            repeatedBeta = np.repeat(Beta, nbv).reshape(nbc, nbv)
            outputs['beta_mapped'] = xndarray(repeatedBeta,value_label="beta",
                                            axes_names=['condition','voxel'],
                                            axes_domains=domCondition)

            outputs['roi_mask'] = xndarray(np.zeros(nbv)+roiData.get_roi_id(),
                                        value_label="ROI",
                                        axes_names=['voxel'])

            h = estimated_hrf
            nrls = nrls.transpose()

            nvox = nrls.shape[1]
            nbconds = nrls.shape[0]
            ah = np.zeros((h.shape[0], nvox, nbconds))

            mixtp = np.zeros((roiData.nbConditions, self.nbClasses, 2))
            mixtp[:, :, 0] = mu_k
            mixtp[:, :, 1] = sigma_k**2

            an = ['condition','Act_class','component']
            ad = {'Act_class':['inactiv','activ'],
                'condition': cNames,
                'component':['mean','var']}
            outputs['mixt_p'] = xndarray(mixtp, axes_names=an, axes_domains=ad)

            ad = {'class' : ['inactiv','activ'],
                'condition': cNames,
                }
            outputs['labels'] = xndarray(labels,value_label="Labels",
                                    axes_names=['condition','class','voxel'],
                                    axes_domains=ad)
            outputs['noiseVar'] = xndarray(noiseVar,value_label="noiseVar",
                                        axes_names=['voxel'])
            if self.estimateDrifts:
                outputs['drift_coeff'] = xndarray(L,value_label="Drift",
                                axes_names=['coeff','voxel'])
                outputs['drift'] = xndarray(PL,value_label="Delta BOLD",
                            axes_names=['time','voxel'])
            if (len(self.contrasts) >0) and self.computeContrast:
                #keys = list((self.contrasts[nc]) for nc in self.contrasts)
                domContrast = {'contrast':self.contrasts.keys()}
                outputs['contrasts'] = xndarray(CONTRAST, value_label="Contrast",
                                            axes_names=['voxel','contrast'],
                                            axes_domains=domContrast)
                #print 'contrast output:'
                #print outputs['contrasts'].descrip()

                c = xndarray(CONTRASTVAR, value_label="Contrasts_Variance",
                        axes_names=['voxel','contrast'],
                        axes_domains=domContrast)
                outputs['contrasts_variance'] = c

                outputs['ncontrasts'] = xndarray(CONTRAST/CONTRASTVAR**.5,
                                            value_label="Normalized Contrast",
                                            axes_names=['voxel','contrast'],
                                            axes_domains=domContrast)

            ################################################################################
            # CONVERGENCE

            axes_names = ['duration']
            outName = 'Convergence_Labels'
            ax = np.arange(self.nItMax)*cTimeMean
            ax[:len(cTime)] = cTime
            ad = {'duration':ax}
            c = np.zeros(self.nItMax) #-.001 #
            c[:len(cZ)] = cZ
            outputs[outName] = xndarray(c, axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_Z')
            outName = 'Convergence_HRF'
            #ad = {'Conv_Criterion':np.arange(len(cH))}
            c = np.zeros(self.nItMax) #-.001 #
            c[:len(cH)] = cH
            outputs[outName] = xndarray(c, axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_H')
            outName = 'Convergence_NRL'
            c = np.zeros(self.nItMax)# -.001 #
            c[:len(cA)] = cA
            #ad = {'Conv_Criterion':np.arange(len(cA))}
            outputs[outName] = xndarray(c, axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_A')

        ################################################################################
        # SIMULATION

        if self.simulation and self.fast:
            from pyhrf.stats import compute_roc_labels
            labels_vem_audio = roiData.simulation['labels'][0]
            labels_vem_video = roiData.simulation['labels'][1]

            M = labels.shape[0]
            K = labels.shape[1]
            J = labels.shape[2]
            true_labels = np.zeros((K,J))
            true_labels[0,:] = reshape(labels_vem_audio,(J))
            true_labels[1,:] = reshape(labels_vem_video,(J))
            newlabels = np.reshape(labels[:,1,:],(M,J))
            se = []
            sp = []
            size = prod(labels.shape)

            for i in xrange(0,M):
                se0,sp0, auc = roc_curve(newlabels[i,:].tolist(),
                                         true_labels[i,:].tolist())
                se.append(se0)
                sp.append(sp0)
                size = min(size,len(sp0))
            SE = np.zeros((M,size),dtype=float)
            SP = np.zeros((M,size),dtype=float)
            for i in xrange(0,M):
                tmp = np.array(se[i])
                SE[i,:] = tmp[0:size]
                tmp = np.array(sp[i])
                SP[i,:] = tmp[0:size]

            sensData, specData = SE, SP
            axes_names = ['condition','1-specificity']
            outName = 'ROC_audio'
            ad = {'1-specificity':specData[0],'condition':cNames}
            outputs[outName] = xndarray(sensData, axes_names=axes_names,
                                      axes_domains=ad,
                                      value_label='sensitivity')

            m = specData[0].min()
            import matplotlib.font_manager as fm
            figure(200)
            plot(sensData[0],specData[0],'--',color='k',linewidth=2.0,label='m=1')
            hold(True)
            plot(sensData[1],specData[1],color='k',linewidth=2.0,label='m=2')
            #legend(('audio','video'))
            xticks(color = 'k', size = 14,fontweight='bold')
            yticks(color = 'k', size = 14,fontweight='bold')
            #xlabel('1 - Specificity',fontsize=16,fontweight='bold')
            #ylabel('Sensitivity',fontsize=16,fontweight='bold')
            prop = fm.FontProperties(size=14,weight='bold')
            legend(loc=1,prop=prop)
            axis([0., 1., m, 1.02])


            from pyhrf.stats import compute_roc_labels
            if hasattr(roiData.simulation, 'nrls'):
                true_labels = roiData.simulation.nrls.labels
                true_nrls = roiData.simulation.nrls.data
            elif isinstance(roiData.simulation, dict) and \
                    roiData.simulation.has_key('labels') and \
                    roiData.simulation.has_key('nrls') :
                true_labels = roiData.simulation['labels']
                true_nrls = roiData.simulation['nrls']
            else:
                raise Exception('Simulation can not be retrieved from %s' \
                                    %str(roiData.simulation))

            domCondition = {'condition':cNames}
            outputs['Truenrls'] = xndarray(true_nrls,value_label="True_nrls",
                                         axes_names=['condition','voxel'],
                                         axes_domains=domCondition)
            M = labels.shape[0]
            K = labels.shape[1]
            J = labels.shape[2]

            newlabels = np.reshape(labels[:,1,:],(M,J))

            for i in xrange(0,M):
                se0,sp0, auc = roc_curve(newlabels[i,:].tolist(),
                                         true_labels[i,:].tolist())
                se.append(se0)
                sp.append(sp0)
                size = min(size,len(sp0))
            SE = np.zeros((M,size),dtype=float)
            SP = np.zeros((M,size),dtype=float)
            for i in xrange(0,M):
                tmp = np.array(se[i])
                SE[i,:] = tmp[0:size]
                tmp = np.array(sp[i])
                SP[i,:] = tmp[0:size]

        # END SIMULATION
        ##########################################################################
        if self.fast:
            d = {'parcel_size':np.array([nvox])}
            outputs['analysis_duration'] = xndarray(np.array([self.analysis_duration]),
                                                axes_names=['parcel_size'],
                                                axes_domains=d)

        return #outputs
コード例 #4
0
    def analyse_roi(self, roiData):
        # roiData is of type FmriRoiData, see pyhrf.core.FmriRoiData
        # roiData.bold : numpy array of shape
        # BOLD has shape (nscans, nvoxels)
        # roiData.graph #list of neighbours
        n_scan_allsession, nvox = roiData.bold.shape
        n_scan = n_scan_allsession / self.n_session
        data0 = roiData.bold.reshape(self.n_session, n_scan, nvox)
        data = np.zeros_like(data0)
        for s in xrange(self.n_session):
            data_mean = np.mean(data0[s, :, :])
            data_range = (np.max(data0[s, :, :]) - np.min(data0[s, :, :]))
            data[s, :, :] = (data0[s, :, :] - data_mean) * 100 / data_range
        Onsets = roiData.paradigm.get_joined_onsets_dim()
        durations = roiData.paradigm.get_joined_durations_dim()
        TR = roiData.tr
        beta = self.beta
        scale = 1                   # roiData.nbVoxels
        #nvox = roiData.get_nb_vox_in_mask()
        if self.scale:
            scale = nvox
        rid = roiData.get_roi_id()
        logger.info("JDE VEM - roi %d, nvox=%d, nconds=%d, nItMax=%d", rid,
                    nvox, len(Onsets), self.nItMax)

        #self.contrasts.pop('dummy_example', None)
        cNames = roiData.paradigm.get_stimulus_names()
        graph = roiData.get_graph()
        idx_tag1 = roiData.get_extra_data('asl_first_tag_scan_idx', 0)

        t_start = time()

        logger.info("fast VEM with drift estimation and a constraint")
        try:
            simu = roiData.simulation[0]
        except:
            try:
                simu = roiData.simulation
            except:
                simu = None

        if self.physio:
            NbIter, brls, estimated_brf, prls, estimated_prf, labels, \
            noiseVar, mu_Ma, sigma_Ma, mu_Mc, sigma_Mc, Beta, L, PL, alpha,\
            Sigma_brls, Sigma_prls, Sigma_brf, Sigma_prf, rerror, \
            CONTRAST_A, CONTRASTVAR_A, CONTRAST_C, CONTRASTVAR_C, \
            cA, cH, cC, cG, cZ, cAH, cCG, cTime, FE = Main_vbjde_physio(
                                       graph, data, Onsets, durations, self.hrfDuration,
                                       self.nbClasses, TR, beta, self.dt, scale=scale,
                                       estimateSigmaG=self.estimateSigmaG,
                                       sigmaH=self.sigmaH, sigmaG=self.sigmaG,
                                       gamma_h=self.gammaH, gamma_g=self.gammaG,
                                       NitMax=self.nItMax, NitMin=self.nItMin,
                                       estimateSigmaH=self.estimateSigmaH,
                                       estimateBeta=self.estimateBeta, PLOT=self.PLOT,
                                       contrasts=self.contrasts,
                                       computeContrast=self.computeContrast,
                                       idx_first_tag=idx_tag1,
                                       simulation=simu, sigmaMu=self.sigmaMu,
                                       estimateH=self.estimateH,
                                       estimateG=self.estimateG,
                                       estimateA=self.estimateA,
                                       estimateC=self.estimateC,
                                       estimateNoise=self.estimateNoise,
                                       estimateMP=self.estimateMixtParam,
                                       estimateZ=self.estimateLabels,
                                       estimateLA=self.estimateLA,
                                       constraint=self.constrained,
                                       positivity=self.positivity,
                                       use_hyperprior=self.use_hyperprior,
                                       phy_params=self.phy_params,
                                       prior=self.prior, zc=self.zc)

        # Plot analysis duration
        self.analysis_duration = time() - t_start
        logger.info('JDE VEM analysis took: %s',
                    format_duration(self.analysis_duration))

        # OUTPUTS: Pack all outputs within a dict
        logger.info("Preparing outputs... ")
        outputs = {}
        brf_time = np.arange(len(estimated_brf)) * self.dt
        outputs['brf'] = xndarray(estimated_brf, axes_names=['time'],
                                  axes_domains={'time': brf_time},
                                  value_label="BRF")
        #logger.info("BRF prepared ")
        domCondition = {'condition': cNames}
        outputs['brls'] = xndarray(brls.T, value_label="BRLs",
                                   axes_names=['condition', 'voxel'],
                                   axes_domains=domCondition)
        #logger.info("BRLs prepared ")
        prf_time = np.arange(len(estimated_prf)) * self.dt
        outputs['prf'] = xndarray(estimated_prf, axes_names=['time'],
                                  axes_domains={'time': prf_time},
                                  value_label="PRF")
        #logger.info("PRF prepared ")
        outputs['prls'] = xndarray(prls.T, value_label="PRLs",
                                   axes_names=['condition', 'voxel'],
                                   axes_domains=domCondition)
        #logger.info("PRLs prepared ")

        outputs['Sigma_brf'] = xndarray(Sigma_brf, value_label="Sigma_BRF")
        #logger.info("Sigma_BRF prepared ")
        outputs['Sigma_prf'] = xndarray(Sigma_prf, value_label="Sigma_PRF")
        #logger.info("Sigma_PRF prepared ")

        ad = {'condition': cNames, 'condition2': Onsets.keys()}
        outputs['Sigma_brls'] = xndarray(Sigma_brls, value_label="Sigma_BRLs",
                                         axes_names=['condition', 'condition2',
                                                     'voxel'],
                                         axes_domains=ad)
        #logger.info("Sigma_a prepared ")
        outputs['Sigma_prls'] = xndarray(Sigma_prls, value_label="Sigma_PRLs",
                                         axes_names=['condition', 'condition2',
                                                     'voxel'],
                                         axes_domains=ad)
        #logger.info("Sigma_c prepared ")
        outputs['NbIter'] = xndarray(np.array([NbIter]), value_label="NbIter")
        outputs['beta'] = xndarray(Beta, value_label="beta",
                                   axes_names=['condition'],
                                   axes_domains=domCondition)

        #logger.info("perfusion baseline prepared ")
        outputs['alpha'] = xndarray(alpha, value_label="Perf_baseline",
                                          axes_names=['voxel'])

        #logger.info("Beta prepared ")
        nbc, nbv = len(cNames), brls.shape[0]
        repeatedBeta = np.repeat(Beta, nbv).reshape(nbc, nbv)
        outputs['beta_mapped'] = xndarray(repeatedBeta, value_label="beta",
                                          axes_names=['condition', 'voxel'],
                                          axes_domains=domCondition)

        repeated_brf = np.repeat(estimated_brf, nbv).reshape(-1, nbv)
        outputs["brf_mapped"] = xndarray(repeated_brf, value_label="BRFs",
                                         axes_names=["time", "voxel"],
                                         axes_domains={"time": brf_time})

        repeated_prf = np.repeat(estimated_prf, nbv).reshape(-1, nbv)
        outputs["prf_mapped"] = xndarray(repeated_prf, value_label="PRFs",
                                         axes_names=["time", "voxel"],
                                         axes_domains={"time": prf_time})

        #logger.info("beta mapped prepared ")
        outputs['roi_mask'] = xndarray(np.zeros(nbv) + roiData.get_roi_id(),
                                       value_label="ROI",
                                       axes_names=['voxel'])

        #logger.info("ROI mask prepared ")
        mixtpB = np.zeros((roiData.nbConditions, self.nbClasses, 2))
        mixtpB[:, :, 0] = mu_Ma
        mixtpB[:, :, 1] = sigma_Ma ** 2
        mixtpP = np.zeros((roiData.nbConditions, self.nbClasses, 2))
        mixtpP[:, :, 0] = mu_Mc
        mixtpP[:, :, 1] = sigma_Mc ** 2
        an = ['condition', 'Act_class', 'component']
        ad = {'Act_class': ['inactiv', 'activ'],
              'condition': cNames,
              'component': ['mean', 'var']}
        outputs['mixt_pB'] = xndarray(mixtpB, axes_names=an, axes_domains=ad)
        outputs['mixt_pP'] = xndarray(mixtpP, axes_names=an, axes_domains=ad)
        #logger.info("Mixture parameters prepared ")
        an = ['condition', 'Act_class', 'voxel']
        ad = {'Act_class': ['inactiv', 'activ'],
              'condition': cNames}
        #logger.info("mixt params prepared ")
        outputs['labels'] = xndarray(labels, value_label="Labels",
                                     axes_names=an, axes_domains=ad)
        #logger.info("labels prepared ")
        outputs['noiseVar'] = xndarray(noiseVar, value_label="noiseVar",
                                       axes_names=['voxel'])
        #logger.info("noise variance prepared ")
        if self.estimateLA:
            outputs['drift_coeff'] = xndarray(L, value_label="Drift",
                                              axes_names=['coeff', 'voxel'])
            outputs['drift'] = xndarray(PL, value_label="Delta BOLD",
                                        axes_names=['time', 'voxel'])
            logger.info("drift prepared ")
        logger.info("outputs prepared ")

        if (len(self.contrasts) >0) and self.computeContrast:
            #keys = list((self.contrasts[nc]) for nc in self.contrasts)
            domContrast = {'contrast':self.contrasts.keys()}
            outputs['contrastsA'] = xndarray(CONTRAST_A, value_label="Contrast_A",
                                            axes_names=['voxel','contrast'],
                                            axes_domains=domContrast)
            outputs['contrastsC'] = xndarray(CONTRAST_C, value_label="Contrast_C",
                                            axes_names=['voxel','contrast'],
                                            axes_domains=domContrast)
            c = xndarray(CONTRASTVAR_A, value_label="Contrasts_Variance_A",
                         axes_names=['voxel','contrast'],
                         axes_domains=domContrast)
            outputs['contrasts_variance_a'] = c
            outputs['ncontrasts_a'] = xndarray(CONTRAST_A/CONTRASTVAR_A**.5,
                                             value_label="Normalized Contrast A",
                                             axes_names=['voxel','contrast'],
                                             axes_domains=domContrast)
            c = xndarray(CONTRASTVAR_C, value_label="Contrasts_Variance_C",
                         axes_names=['voxel','contrast'],
                         axes_domains=domContrast)
            outputs['contrasts_variance_c'] = c
            outputs['ncontrasts_c'] = xndarray(CONTRAST_C/CONTRASTVAR_C**.5,
                                             value_label="Normalized Contrast C",
                                             axes_names=['voxel','contrast'],
                                             axes_domains=domContrast)

        #######################################################################
        # CONVERGENCE
        if 1:
            cTimeMean = cTime[-1] / np.float(NbIter)
            logger.info("Saving convergence... ")

            axes_names = ['duration']
            ax = (np.arange(self.nItMax) + 1) * cTimeMean
            ax[:len(cTime)] = cTime
            ad = {'duration': ax}

            outName = 'convergence_Labels'
            c = np.zeros(self.nItMax)  # -.001 #
            c[:len(cZ)] = cZ
            outputs[outName] = xndarray(c, axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_Z')
            outName = 'convergence_BRF'
            #ad = {'Conv_Criterion':np.arange(len(cH))}
            c = np.zeros(self.nItMax)   # -.001 #
            c[:len(cH)] = cH
            outputs[outName] = xndarray(c, axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_H')
            outName = 'convergence_BRL'
            c = np.zeros(self.nItMax)  # -.001 #
            c[:len(cA)] = cA
            #ad = {'Conv_Criterion':np.arange(len(cA))}
            outputs[outName] = xndarray(c, axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_A')
            outName = 'convergence_PRF'
            #ad = {'Conv_Criterion':np.arange(len(cH))}
            c = np.zeros(self.nItMax)   # -.001 #
            c[:len(cG)] = cG
            outputs[outName] = xndarray(c, axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_G')
            outName = 'convergence_PRL'
            c = np.zeros(self.nItMax)  # -.001 #
            c[:len(cC)] = cC
            #ad = {'Conv_Criterion':np.arange(len(cA))}
            outputs[outName] = xndarray(c, axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_C')
            outName = 'convergence_FE'
            c = np.zeros(self.nItMax)  # -.001 #
            c[:len(FE)] = FE
            outputs[outName] = xndarray(c, axes_names=axes_names,
                                        axes_domains=ad,
                                        value_label='Conv_Criterion_FE')
            logger.info("Convergence saved ")

        #######################################################################
        # SIMULATION
        if self.simulation is not None and 0:
            logger.info("Prepare parameters to compare if simulation")
            M = labels.shape[0]
            K = labels.shape[1]
            J = labels.shape[2]

            true_labels = np.zeros((M, J))
            for m in xrange(0,M):
                true_labels[m, :] = roiData.simulation[0]['labels'][m].flatten()

            newlabels = np.reshape(labels[:, 1, :], (M, J))
            #true_labels = roiData.simulation[0]['labels']
            #newlabels = labels

            se = []
            sp = []
            size = np.prod(labels.shape)
            for i in xrange(0, 2):  # (0, M):
                se0, sp0, auc = roc_curve(newlabels[i, :].tolist(),
                                          true_labels[i, :].tolist())
                se.append(se0)
                sp.append(sp0)
                size = min(size, len(sp0))
            SE = np.zeros((M, size), dtype=float)
            SP = np.zeros((M, size), dtype=float)
            for i in xrange(0, 2):  # M):
                tmp = np.array(se[i])
                SE[i, :] = tmp[0:size]
                tmp = np.array(sp[i])
                SP[i, :] = tmp[0:size]
            sensData, specData = SE, SP
            axes_names = ['1-specificity', 'condition']
            outName = 'ROC_audio'
            #ad = {'1-specificity': specData[0], 'condition': cNames}
            outputs[outName] = xndarray(sensData, axes_names=axes_names,
                                        #axes_domains=ad,
                                        value_label='sensitivity')

            m = specData[0].min()
            import matplotlib.font_manager as fm
            import matplotlib.pyplot as plt
            plt.figure(200)
            plt.plot(sensData[0], specData[0], '--', color='k', linewidth=2.0,
                     label='m=1')
            plt.hold(True)
            plt.plot(sensData[1], specData[1], color='k', linewidth=2.0,
                     label='m=2')
            # legend(('audio','video'))
            plt.xticks(color='k', size=14, fontweight='bold')
            plt.yticks(color='k', size=14, fontweight='bold')
            #xlabel('1 - Specificity',fontsize=16,fontweight='bold')
            # ylabel('Sensitivity',fontsize=16,fontweight='bold')
            prop = fm.FontProperties(size=14, weight='bold')
            plt.legend(loc=1, prop=prop)
            plt.axis([0., 1., m, 1.02])

            true_labels = roiData.simulation[0]['labels']
            true_brls = roiData.simulation[0]['nrls']
            true_prls = roiData.simulation[0]['prls']
            true_brf = roiData.simulation[0]['hrf'][:, 0]
            true_prf = roiData.simulation[0]['prf'][:, 0]
            true_drift = roiData.simulation[0]['drift']
            true_noise = roiData.simulation[0]['noise']

            if simu is not None:
                logger.info("Check parameters errors")
                self.finalizeEstimation(true_labels, newlabels, nvox,
                                        true_brf, estimated_brf,
                                        true_prf, estimated_prf,
                                        true_brls, brls.T,
                                        true_prls, prls.T,
                                        true_drift, PL, L,
                                        true_noise, noiseVar)

        # END SIMULATION
        #######################################################################
        d = {'parcel_size': np.array([nvox])}
        outputs['analysis_duration'] = xndarray(np.array(
                                                [self.analysis_duration]),
                                                axes_names=['parcel_size'],
                                                axes_domains=d)
        """outputs['rerror'] = xndarray(np.array(  rerror),
                                                axes_names=['parcel_size'])"""
        return outputs