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 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 simBrainAreaForOptimVars(N, area, keysAndValues): global neuro_act simulateActivitySubject(C, N, we) for key, value in keysAndValues.items(): exec('BOLDHemModel2.'+key+' = '+str(value)) 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
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
def fitPltErrorForBrainArea(BOLDSignal, area): N,T = BOLDSignal.shape simulateActivitySubject(C, N, we) # popt, pcov, finalError = optimBOLD.fitBOLDBrainAreaCatchingErrors(neuro_act, BOLDSignal, area) # perr = np.sqrt(np.diag(pcov)) # print("Computed minimum:", popt, "value:", finalError, "Std Dev:", perr) interval=range(T) emp_filt = BOLDFilters.filterBrainArea(BOLDSignal, area) emp_filt /= np.std(emp_filt) empSignal, = plt.plot(interval, emp_filt, 'r--', label='empirical') sim_filtOptim = simBrainAreaForOptimVars(N, area, {'epsilon': 0.5}) # popt[0]) simSignalOptim, = plt.plot(interval, sim_filtOptim, 'b-', label='simulated(epsilon={})'.format(0.5)) #popt[0])) plt.suptitle('Optimal Sim and Empirical BOLD for area {}'.format(area)) plt.legend(handles=[empSignal, simSignalOptim]) plt.show()
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 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 fitAndPltBrainArea(BOLDSignal, area): # init... N,T = BOLDSignal.shape simulateActivitySubject(C, N, we) # fit !!! t = time.time() popt, perr, finalError = fitBrainArea(BOLDSignal, area) print(np.round_(time.time() - t, 3), 'sec elapsed') # print("Area {} processed:".format(area)) # print("Computed minimum:", pairVarsAndValues(popt), "\n Std Dev:", pairVarsAndValues(perr, "\n value:", finalError)) # and plot. interval=range(T) emp_filt = BOLDFilters.filterBrainArea(BOLDSignal, area) emp_filt /= np.std(emp_filt) empSignal, = plt.plot(interval, emp_filt, 'r--', label='Empirical') sim_filtOptim = simBrainAreaForOptimVars(N, area, optimBOLD.pairVarsAndValues(popt)) simSignalOptim, = plt.plot(interval, sim_filtOptim, 'b-', label='Simulated') plt.suptitle('Optimal Sim and Empirical BOLD for area {}'.format(area)) plt.legend(handles=[empSignal, simSignalOptim]) plt.show()