adapt for new FiCurve class

This commit is contained in:
a.ott 2020-05-20 15:17:42 +02:00
parent 256931845e
commit 676a0e4945

View File

@ -10,12 +10,9 @@ import functions as fu
class Adaption: class Adaption:
def __init__(self, cell_data: CellData, fi_curve: FICurve = None): def __init__(self, fi_curve: FICurve):
self.cell_data = cell_data
if fi_curve is None: self.fi_curve = fi_curve
self.fi_curve = get_fi_curve_class(cell_data, cell_data.get_fi_contrasts())
else:
self.fi_curve = fi_curve
# [[a, tau_eff, c], [], [a, tau_eff, c], ...] # [[a, tau_eff, c], [], [a, tau_eff, c], ...]
self.exponential_fit_vars = [] self.exponential_fit_vars = []
@ -25,27 +22,42 @@ class Adaption:
self.calculate_tau_from_tau_eff() self.calculate_tau_from_tau_eff()
def fit_exponential(self, length_of_fit=0.1): def fit_exponential(self, length_of_fit=0.1):
mean_frequencies = self.cell_data.get_mean_isi_frequencies() time_axes, mean_frequencies = self.fi_curve.get_mean_time_and_freq_traces()
time_axes = self.cell_data.get_time_axes_mean_frequencies() f_baselines = self.fi_curve.get_f_baseline_frequencies()
f_infinities = self.fi_curve.get_f_inf_frequencies()
f_zeros = self.fi_curve.get_f_zero_frequencies()
for i in range(len(mean_frequencies)): for i in range(len(mean_frequencies)):
start_idx = self.__find_start_idx_for_exponential_fit(i)
if abs(f_zeros[i] - f_infinities[i]) < 20:
self.exponential_fit_vars.append([])
continue
start_idx = self.__find_start_idx_for_exponential_fit(time_axes[i], mean_frequencies[i],
f_baselines[i], f_infinities[i], f_zeros[i])
if start_idx == -1: if start_idx == -1:
print("start index negative") # print("start index negative")
self.exponential_fit_vars.append([]) self.exponential_fit_vars.append([])
continue continue
# shorten length of fit to stay in stimulus region if given length is too long # shorten length of fit to stay in stimulus region if given length is too long
sampling_interval = self.cell_data.get_sampling_interval() sampling_interval = self.fi_curve.get_sampling_interval()
used_length_of_fit = length_of_fit used_length_of_fit = length_of_fit
if (start_idx * sampling_interval) - self.cell_data.get_delay() + length_of_fit > self.cell_data.get_stimulus_end(): if (start_idx * sampling_interval) - self.fi_curve.get_delay() + length_of_fit > self.fi_curve.get_stimulus_end():
print(start_idx * sampling_interval, "start - end", start_idx * sampling_interval + length_of_fit) print(start_idx * sampling_interval, "start - end", start_idx * sampling_interval + length_of_fit)
print("Shortened length of fit to keep it in the stimulus region!") print("Shortened length of fit to keep it in the stimulus region!")
used_length_of_fit = self.cell_data.get_stimulus_end() - (start_idx * sampling_interval) used_length_of_fit = self.fi_curve.get_stimulus_end() - (start_idx * sampling_interval)
end_idx = start_idx + int(used_length_of_fit/sampling_interval) end_idx = start_idx + int(used_length_of_fit/sampling_interval)
y_values = mean_frequencies[i][start_idx:end_idx+1] y_values = mean_frequencies[i][start_idx:end_idx+1]
x_values = time_axes[i][start_idx:end_idx+1] x_values = time_axes[i][start_idx:end_idx+1]
# plt.title("f_zero {:.2f}, f_inf {:.2f}".format(f_zeros[i], f_infinities[i]))
# plt.plot(time_axes[i], mean_frequencies[i])
# plt.plot(x_values, y_values)
# plt.show()
# plt.close()
tau = self.__approximate_tau_for_exponential_fit(x_values, y_values, i) tau = self.__approximate_tau_for_exponential_fit(x_values, y_values, i)
@ -54,6 +66,12 @@ class Adaption:
p0 = (self.fi_curve.f_zero_frequencies[i], tau, self.fi_curve.f_inf_frequencies[i]) p0 = (self.fi_curve.f_zero_frequencies[i], tau, self.fi_curve.f_inf_frequencies[i])
popt, pcov = curve_fit(fu.exponential_function, x_values, y_values, popt, pcov = curve_fit(fu.exponential_function, x_values, y_values,
p0=p0, maxfev=10000, bounds=([-np.inf, 0, -np.inf], [np.inf, np.inf, np.inf])) p0=p0, maxfev=10000, bounds=([-np.inf, 0, -np.inf], [np.inf, np.inf, np.inf]))
# plt.plot(time_axes[i], mean_frequencies[i])
# plt.plot(x_values, [fu.exponential_function(x, popt[0], popt[1], popt[2]) for x in x_values])
# plt.show()
# plt.close()
except RuntimeError: except RuntimeError:
print("RuntimeError happened in fit_exponential.") print("RuntimeError happened in fit_exponential.")
self.exponential_fit_vars.append([]) self.exponential_fit_vars.append([])
@ -82,16 +100,17 @@ class Adaption:
return tau return tau
def __find_start_idx_for_exponential_fit(self, mean_freq_idx): def __find_start_idx_for_exponential_fit(self, time, frequency, f_base, f_inf, f_zero):
time_axes = self.cell_data.get_time_axes_mean_frequencies()[mean_freq_idx]
stimulus_start_idx = int((self.cell_data.get_stimulus_start() + time_axes[0]) / self.cell_data.get_sampling_interval()) stimulus_start_idx = int((self.fi_curve.get_stimulus_start() - time[0]) / self.fi_curve.get_sampling_interval())
if self.fi_curve.f_inf_frequencies[mean_freq_idx] > self.fi_curve.f_baseline_frequencies[mean_freq_idx] * 1.1:
if f_inf > f_base * 1.1:
# start setting starting variables for the fit # start setting starting variables for the fit
# search for the start_index by searching for the max # search for the start_index by searching for the max
j = 0 j = 0
while True: while True:
try: try:
if self.cell_data.get_mean_isi_frequencies()[mean_freq_idx][stimulus_start_idx + j] == self.fi_curve.f_zero_frequencies[mean_freq_idx]: if frequency[stimulus_start_idx + j] == f_zero:
start_idx = stimulus_start_idx + j start_idx = stimulus_start_idx + j
break break
except IndexError as e: except IndexError as e:
@ -99,21 +118,21 @@ class Adaption:
j += 1 j += 1
elif self.fi_curve.f_inf_frequencies[mean_freq_idx] < self.fi_curve.f_baseline_frequencies[mean_freq_idx] * 0.9: elif f_inf < f_base * 0.9:
# start setting starting variables for the fit # start setting starting variables for the fit
# search for start by finding the end of the minimum # search for start by finding the end of the minimum
found_min = False found_min = False
j = int(0.05 / self.cell_data.get_sampling_interval()) j = int(0.05 / self.fi_curve.get_sampling_interval())
nothing_to_fit = False nothing_to_fit = False
while True: while True:
if not found_min: if not found_min:
if self.cell_data.get_mean_isi_frequencies()[mean_freq_idx][stimulus_start_idx + j] == self.fi_curve.f_zero_frequencies[mean_freq_idx]: if frequency[stimulus_start_idx + j] == f_zero:
found_min = True found_min = True
else: else:
if self.cell_data.get_mean_isi_frequencies()[mean_freq_idx][stimulus_start_idx + j + 1] > self.fi_curve.f_zero_frequencies[mean_freq_idx]: if frequency[stimulus_start_idx + j + 1] > f_zero:
start_idx = stimulus_start_idx + j start_idx = stimulus_start_idx + j
break break
if j > 0.1 / self.cell_data.get_sampling_interval(): if j > 0.1 / self.fi_curve.get_sampling_interval():
# no rise in freq until to close to the end of the stimulus (to little place to fit) # no rise in freq until to close to the end of the stimulus (to little place to fit)
return -1 return -1
j += 1 j += 1
@ -124,28 +143,29 @@ class Adaption:
# there is nothing to fit to: # there is nothing to fit to:
return -1 return -1
# plt.plot(time, frequency)
# plt.plot(time[start_idx], frequency[start_idx], 'o')
# plt.show()
# plt.close()
return start_idx return start_idx
def calculate_tau_from_tau_eff(self): def calculate_tau_from_tau_eff(self):
tau_effs = [] tau_effs = []
indices = []
for i in range(len(self.exponential_fit_vars)): for i in range(len(self.exponential_fit_vars)):
if len(self.exponential_fit_vars[i]) == 0: if len(self.exponential_fit_vars[i]) == 0:
continue continue
indices.append(i)
tau_effs.append(self.exponential_fit_vars[i][1]) tau_effs.append(self.exponential_fit_vars[i][1])
f_infinity_slope = self.fi_curve.get_f_inf_slope() f_infinity_slope = self.fi_curve.get_f_inf_slope()
# --- old way to calculate with the fi slope at middle of the fi curve approx_tau_reals = []
# fi_curve_slope = self.fi_curve.get_fi_curve_slope_of_straight() for i, idx in enumerate(indices):
# self.tau_real = np.median(tau_effs) * (fi_curve_slope / f_infinity_slope) factor = self.fi_curve.get_f_zero_fit_slope_at_stimulus_value(self.fi_curve.stimulus_values[idx]) / f_infinity_slope
approx_tau_reals.append(tau_effs[i] * factor)
# print("fi_slope to f_inf slope:", fi_curve_slope/f_infinity_slope)
# print("fi_slope:", fi_curve_slope, "f_inf slope:", f_infinity_slope)
# print("current tau: {:.1f}ms".format(np.median(tau_effs) * (fi_curve_slope / f_infinity_slope) * 1000))
# new way to calculate with the fi curve slope at the intersection point of it and the f_inf line self.tau_real = np.median(approx_tau_reals)
factor = self.fi_curve.get_f_zero_fit_slope_at_f_inf_fit_intersection() / f_infinity_slope
self.tau_real = np.median(tau_effs) * factor
print("###### tau: {:.1f}ms".format(self.tau_real*1000), "other f_0 slope:", self.fi_curve.get_f_zero_fit_slope_at_f_inf_fit_intersection())
def get_tau_real(self): def get_tau_real(self):
return np.median(self.tau_real) return np.median(self.tau_real)
@ -153,26 +173,30 @@ class Adaption:
def get_tau_effs(self): def get_tau_effs(self):
return [ex_vars[1] for ex_vars in self.exponential_fit_vars if ex_vars != []] return [ex_vars[1] for ex_vars in self.exponential_fit_vars if ex_vars != []]
def get_delta_a(self):
return self.fi_curve.get_f_zero_fit_slope_at_straight() / self.fi_curve.get_f_inf_slope() / 100
def plot_exponential_fits(self, save_path: str = None, indices: list = None, delete_previous: bool = False): def plot_exponential_fits(self, save_path: str = None, indices: list = None, delete_previous: bool = False):
if delete_previous: if delete_previous:
for val in self.cell_data.get_fi_contrasts(): for val in self.fi_curve.stimulus_values():
prev_path = save_path + "mean_freq_exp_fit_contrast:" + str(round(val, 3)) + ".png" prev_path = save_path + "mean_freq_exp_fit_contrast:" + str(round(val, 3)) + ".png"
if os.path.exists(prev_path): if os.path.exists(prev_path):
os.remove(prev_path) os.remove(prev_path)
for i in range(len(self.cell_data.get_fi_contrasts())): time_axes, mean_freqs = self.fi_curve.get_mean_time_and_freq_traces()
for i in range(len(self.fi_curve.stimulus_values)):
if indices is not None and i not in indices: if indices is not None and i not in indices:
continue continue
if self.exponential_fit_vars[i] == []: if self.exponential_fit_vars[i] == []:
print("no fit vars for index!") print("no fit vars for index {}!".format(i))
continue continue
plt.plot(self.cell_data.get_time_axes_mean_frequencies()[i], self.cell_data.get_mean_isi_frequencies()[i]) plt.plot(time_axes[i], mean_freqs[i])
vars = self.exponential_fit_vars[i] vars = self.exponential_fit_vars[i]
fit_x = np.arange(0, 0.4, self.cell_data.get_sampling_interval()) fit_x = np.arange(0, 0.4, self.fi_curve.get_sampling_interval())
plt.plot(fit_x, [fu.exponential_function(x, vars[0], vars[1], vars[2]) for x in fit_x]) plt.plot(fit_x, [fu.exponential_function(x, vars[0], vars[1], vars[2]) for x in fit_x])
plt.ylim([0, max(self.fi_curve.f_zero_frequencies[i], self.fi_curve.f_baseline_frequencies[i])*1.1]) plt.ylim([0, max(self.fi_curve.f_zero_frequencies[i], self.fi_curve.f_baseline_frequencies[i])*1.1])
plt.xlabel("Time [s]") plt.xlabel("Time [s]")
@ -181,6 +205,6 @@ class Adaption:
if save_path is None: if save_path is None:
plt.show() plt.show()
else: else:
plt.savefig(save_path + "mean_freq_exp_fit_contrast:" + str(round(self.cell_data.get_fi_contrasts()[i], 3)) + ".png") plt.savefig(save_path + "mean_freq_exp_fit_contrast:" + str(round(self.fi_curve.stimulus_values[i], 3)) + ".png")
plt.close() plt.close()