def testSingleSubjectMultipleTimes(signal, times): print("Testing single subject, multiple {} times...".format(times)) results = [] for t in range(times): neuro_act = simulateFCD.computeSubjectSimulation(C, N) bds = simulateFCD.computeSubjectBOLD(neuro_act) bdsT = bds.T sim_filt = BOLDFilters.filterBrainArea(bdsT, 0) sim_filt /= np.std(sim_filt) error = errorMetrics.l2(signal, sim_filt) print("Trial: {} ({}) of {}".format(t+1, t, times), "Error:", error) results.append([error]) avg = np.average(results) std = np.std(results) print("Average:", avg, "std:", std) # the histogram of the data n, bins, patches = plt.hist(results/avg*10, bins=10, facecolor='g', alpha=0.75) plt.xlabel('error') plt.ylabel('Probability') plt.title('Histogram of errors') plt.text(60, .025, '$\mu$={}, $\sigma$={}'.format(avg, std)) #plt.xlim(40, 160) #plt.ylim(0, 0.03) #plt.grid(True) plt.show()
def processBrainAreasBOLDForEpsilon(brainAreaSignal, areas): global neuro_act simulateActivitySubject(C, N, we) epsilons = np.arange(0,2.1,0.1) results = [] #np.zeros([len(epsilons), len(areas)]) minEpsilon=0 minValue=1e99 for epsilon in epsilons: print("Epsilon:", epsilon, end=' ') BOLDHemModel_Stephan2008.epsilon = epsilon bds = simulateFCD.computeSubjectBOLD(neuro_act, N, areasToSimulate=areas) bdsT = bds.T #for area, areaID in enumerate(areas): norm_bdsT = normalizeSignal(brainAreaSignal, bdsT) #print("sim: ", np.average(norm_bdsT), "+/-", np.sqrt(np.var(norm_bdsT))) #print("fMRFI:", np.average(signal), "+/-", np.sqrt(np.var(signal))) error = errorMetrics.l2(brainAreaSignal, norm_bdsT) if error < minValue: minEpsilon = epsilon minValue = error results.append([error]) print("Error:", error) print("Minimum:", minValue, "at:", minEpsilon,) plt.plot(epsilons, results, 'r-') plt.show() BOLDHemModel_Stephan2008.epsilon = minEpsilon bds = simulateFCD.computeSubjectBOLD(neuro_act, N, areasToSimulate=[0]) bdsT = bds.T norm_bdsT = normalizeSignal(brainAreaSignal, bdsT) interval=range(len(brainAreaSignal)) plt.plot(interval,brainAreaSignal.flatten(), 'b-', interval,norm_bdsT.flatten(), 'r-') plt.suptitle('Area:'+str(areas[0])) plt.show()
def fitBOLDBrainArea(neuronal_act, BOLDSignal, area, lowerBounds = initialLowerBounds): def errorFunc(neuro_act, epsilon, alpha, tau, gamma, kappa): if Verbose: global evalCounter evalCounter += 1 print("Test:", evalCounter) BOLDModel.epsilon = epsilon BOLDModel.alpha = alpha BOLDModel.tau = tau BOLDModel.gamma = gamma BOLDModel.kappa = kappa bds = simulateFCD.computeSubjectBOLD(neuro_act, areasToSimulate=[area]) bdsT = bds.T sim_filt = BOLDFilters.filterBrainArea(bdsT, 0) sim_filt /= np.std(sim_filt) return sim_filt # init... from scipy.optimize import curve_fit emp_filt = BOLDFilters.filterBrainArea(BOLDSignal, area) emp_filt /= np.std(emp_filt) # Now, fit it !!! # Note: Be careful with max_nfev, evaluations include numerical derivatives, so the actual number will be around 4.6 (or more) * this number before stopping!!! if numMethod == 'trf': popt, pcov = curve_fit(errorFunc, neuronal_act, emp_filt, method='trf', bounds=(lowerBounds, 3.0), p0 = initialValues, max_nfev = 100) else: # use 'lm' popt, pcov = curve_fit(errorFunc, neuronal_act, emp_filt, method='lm', p0 = initialValues) final_values = errorFunc(neuronal_act, popt[0], popt[1], popt[2], popt[3], popt[4]) finalError = errorMetrics.l2(emp_filt, final_values) return popt, pcov, finalError
def pltSimAndEmpiricalBrainAreaForVariousVariableValues(BOLDSignal, area, varKey, subplot=False): N,T = BOLDSignal.shape interval=range(T) plt.rcParams.update({'font.size': 22}) if subplot: plt.subplot(2, 1, 1) plt.title("Empirical BOLD for area {}".format(area)) emp_filt = BOLDFilters.filterBrainArea(BOLDSignal, area) emp_filt /= np.std(emp_filt) empSignal, = plt.plot(interval, emp_filt, 'r--', label='empirical') if subplot: plt.subplot(2, 1, 2) plt.title("Simulated BOLD for area {}".format(area)) sim_filt00 = simBrainAreaForOptimVars(N, area, {varKey: 0.05}) # Some vars cannot be just 0.0... simSignal00, = plt.plot(interval, sim_filt00, 'b-', label='simulated('+varKey+'=0.05)') sim_filt05 = simBrainAreaForOptimVars(N, area, {varKey: 0.5}) simSignal05, = plt.plot(interval, sim_filt05, 'g-', label='simulated('+varKey+'=0.5)') sim_filt10 = simBrainAreaForOptimVars(N, area, {varKey: 1.0}) simSignal10, = plt.plot(interval, sim_filt10, 'c-', label='simulated('+varKey+'=1.0)') sim_filt15 = simBrainAreaForOptimVars(N, area, {varKey: 1.5}) simSignal15, = plt.plot(interval, sim_filt15, 'm-', label='simulated('+varKey+'=1.5)') plt.suptitle('Sim and Empirical BOLD for single area, '+varKey) if not subplot: plt.legend(handles=[empSignal, simSignal00, simSignal05, simSignal10, simSignal15]) else: plt.legend(handles=[simSignal00, simSignal05, simSignal10, simSignal15]) plt.tight_layout() # plt.legend(handles=[simSignal00, simSignal05, simSignal10, simSignal15]) # plt.legend(handles=[empSignal, simSignal05]) plt.show() # just some computations to know a little bit better this stuff print("l^2 Error (0.05):", errorMetrics.l2(emp_filt, sim_filt00)) print("l^2 Error (0.5):", errorMetrics.l2(emp_filt, sim_filt05)) print("l^2 Error (1.0):", errorMetrics.l2(emp_filt, sim_filt10)) print("l^2 Error (1.5):", errorMetrics.l2(emp_filt, sim_filt15)) from scipy.stats.stats import pearsonr print("Pearson.r (0.05):", pearsonr(emp_filt, sim_filt00)) print("Pearson.r (0.5):", pearsonr(emp_filt, sim_filt05)) print("Pearson.r (1.0):", pearsonr(emp_filt, sim_filt10)) print("Pearson.r (1.5):", pearsonr(emp_filt, sim_filt15))
def distTo3Hz(curr): import functions.Utils.errorMetrics as error tmin = 1000 if (tmax > 1000) else int(tmax / 10) currm = np.mean( curr[tmin:tmax, :], 0) # takes the mean of all xn values along dimension 1... # return np.abs(np.average(f)-targetFreq) return error.l2(currm, targetFreq)
def checkAveragedValuesOverSubjects(tc_aal, area, condition): print("function checkAveragedValuesOverSubjects ({} Subjects)".format(Subjects)) print("======================================================") allErrors = np.zeros([Subjects]) avgResult, avgError = averageSingleBrainAreaForAllSubjects(tc_aal, area, condition) print("Average error (area by area):", avgError) for subject in range(Subjects): print("Checking area {} from subject {} !!!".format(area,subject)) BOLDData = tc_aal[subject, condition] emp_filt = BOLDFilters.filterBrainArea(BOLDData, area) emp_filt /= np.std(emp_filt) sim_filtOptim = simBrainAreaForOptimVars(N, area, optimBOLD.pairVarsAndValues(avgResult)) error = errorMetrics.l2(emp_filt, sim_filtOptim) print("Error computed:", error) allErrors[subject] = error finalAvgError = np.mean(allErrors) print("Final avg error (all areas same parms):", finalAvgError)
def pltErrorForBrainAreaFitOptimVariable(BOLDSignal, area, key, minValue = -0.5, maxValue=2.6, stepValue=0.1): from scipy.stats.stats import pearsonr emp_filt = BOLDFilters.filterBrainArea(BOLDSignal, area) emp_filt /= np.std(emp_filt) N,T = BOLDSignal.shape global neuro_act simulateActivitySubject(C, N, we) values = np.arange(minValue,maxValue,stepValue) results = [] #np.zeros([len(epsilons), len(areas)]) resultsPearson = [] minVar=-1 minValue=1e99 for value in values: print("Var value:", value, end=' ') sim_filt = simBrainAreaForOptimVars(N, area, {key: value}) # simSignal, = plt.plot(interval, sim_filt, label='simulated(epsilon={}})'.format(epsilon)) error = errorMetrics.l2(emp_filt, sim_filt) errorPearson = (1-pearsonr(emp_filt, sim_filt)[0])*20 if error < minValue: minVar = value minValue = error results.append([error]) resultsPearson.append([errorPearson]) print("Error:", error, "Pearson.r:", errorPearson) print("'Manual' minimum:", minValue, "at:", minVar,) plt.rcParams.update({'font.size': 22}) plt.suptitle('BOLD Error for '+ key +', area ({})'.format(area)) plt.plot(values, results, 'r-') plt.plot(values, resultsPearson, 'b-') #popt, pcov, finalError = optimBOLD.fitBOLDBrainAreaCatchingErrors(neuro_act, BOLDSignal, area) #perr = np.sqrt(np.diag(pcov)) #print("Computed minimum:", popt, "value:", finalError,"Std Dev:", perr) lineAt = minVar # popt[0] or minVar plt.axvline(x=lineAt, color='g', linestyle='--') plt.show() interval=range(T) empSignal, = plt.plot(interval, emp_filt, 'r--', label='empirical') sim_filtOptim = simBrainAreaForOptimVars(N, area, {key: lineAt}) simSignalOptim, = plt.plot(interval, sim_filtOptim, 'b-', label='simulated(epsilon={})'.format(lineAt)) plt.suptitle('Optimal Sim and Empirical ('+key+') BOLD for area {}'.format(area)) plt.legend(handles=[empSignal, simSignalOptim]) plt.show()
def pltSubjectBOLDForEpsilon(signal): global neuro_act simulateActivitySubject(C, N, we) results = [] epsilons = np.arange(0,2.1,0.2) for epsilon in epsilons: print("Epsilon:", epsilon, end=' ') BOLDHemModel_Stephan2008.epsilon = epsilon bds = simulateFCD.computeSubjectBOLD(neuro_act, N) bdsT = bds.T norm_bdsT = normalizeSignal(signal, bdsT) #print("sim: ", np.average(norm_bdsT), "+/-", np.sqrt(np.var(norm_bdsT))) #print("fMRFI:", np.average(signal), "+/-", np.sqrt(np.var(signal))) error = errorMetrics.l2(signal, norm_bdsT) results = np.append(results, [error]) print("Error:", error) plt.plot(epsilons, results, 'r-') plt.show()
def processSubjectForEpsilon(signal): global neuro_act if doIndividualSim: # each subject goes with his/her own sim... simulateActivitySubject(C, N, we) results = [] epsilons = np.arange(0,1.5,0.1) for epsilon in epsilons: print("Epsilon:", epsilon, end=' ') BOLDHemModel_Stephan2008.epsilon = epsilon bds = simulateFCD.computeSubjectBOLD(neuro_act) bdsT = bds.T norm_bdsT = normalizeSignal(signal, bdsT) #print("sim: ", np.average(norm_bdsT), "+/-", np.sqrt(np.var(norm_bdsT))) #print("fMRFI:", np.average(signal), "+/-", np.sqrt(np.var(signal))) error = errorMetrics.l2(signal, norm_bdsT) np.append(results, [error]) print("Error:", error) plt.plot(epsilons, results, 'r-') plt.show()
def distTo3Hz(f): import functions.Utils.errorMetrics as error # return np.abs(np.average(f)-targetFreq) return error.l2(f, targetFreq)