def test_basic(self): assert_allclose(signal.parzen(6), [0.009259259259259254, 0.25, 0.8611111111111112, 0.8611111111111112, 0.25, 0.009259259259259254]) assert_allclose(signal.parzen(7, sym=True), [0.00583090379008747, 0.1574344023323616, 0.6501457725947521, 1.0, 0.6501457725947521, 0.1574344023323616, 0.00583090379008747]) assert_allclose(signal.parzen(6, False), [0.00583090379008747, 0.1574344023323616, 0.6501457725947521, 1.0, 0.6501457725947521, 0.1574344023323616])
def run_optimization(self): self.full_model.update(self.dt, self.duration) self.etalonV = np.asarray(self.full_model.getVhist()) self.win = parzen(15) self.etalonspikes = argrelmax(self.etalonV)[0][1:20] self.fr_el = 1.0 / np.mean(np.diff(self.etalonspikes)) x0 = [0.8, -60, 12.0] res = minimize( self.need2optimize, x0, method="Powell") # , bounds=[[-61, -50], [-70, 30], [0, 1]] print(res.x) self.optimized_model.default() self.optimized_model.n_reset = res.x[0] self.optimized_model.Vt = res.x[1] self.optimized_model.V_reset = res.x[2] self.optimized_model.update(self.dt, self.duration) return res
def update_on_plot(self, idx): x1, y1, x2, y2, y3 = self.model.update(self.dt) # y3 = self.model.get_artificial_signals() V = np.empty(0, dtype=float) for n in self.model.neurons: V = np.append(V, n.channels[4].get_g()) disridution_y, disridution_x = np.histogram(V, bins=100, range=[0, 0.5], density=True) disridution_x = disridution_x[:-1] self.disridution_x = disridution_x disridution_y = np.convolve(disridution_y, parzen(7), mode="same") self.disridution_y = np.append(self.disridution_y, disridution_y.reshape(-1, 1), axis=1) self.line1.set_data(disridution_x, disridution_y) self.time_text.set_text("simulation time is %.2f in ms" % idx) self.line2.set_data(x2, y2) if len(y3) > 0: # print(len(x2), len(y3) ) # self.line3.set_data(x2, y3) pass return [self.line1, self.time_text, self.line2, self.line3]
def coherence(self, wave, window): freq, f0 = vector.fourier_spectrum(self.wave, 1 / self.dt) freq, f1 = vector.fourier_spectrum(wave.wave, 1 / self.dt) p0 = np.conjugate(f0) * f0 p1 = np.conjugate(f1) * f1 c01 = np.conjugate(f0) * f1 nw = int(window / (freq[1] - freq[0])) if nw % 2 == 0: nw += 1 nw2 = int((nw - 1) / 2) w = signal.parzen(nw) a = np.r_[c01[nw2:0:-1], c01, c01[0], c01[-1:-nw2:-1]] c01_s = np.convolve(w / w.sum(), a, mode='valid') a = np.r_[p0[nw2:0:-1], p0, p0[0], p0[-1:-nw2:-1]] p0_s = np.convolve(w / w.sum(), a, mode='valid') a = np.r_[p1[nw2:0:-1], p1, p1[0], p1[-1:-nw2:-1]] p1_s = np.convolve(w / w.sum(), a, mode='valid') c01_abs = np.conjugate(c01_s) * c01_s return freq, c01_abs / (p0_s * p1_s)
def __init__(self, N, muext, sigmaext, tau=20, Vt=20, Vr=0): self.N = N self.tau = 20 self.Vt = Vt # threshold self.Vr = Vr # reset self.muext = muext self.sigmaext = sigmaext self.V = np.zeros(self.N) + self.Vr self.win = parzen(7)
def gen_parzen(samples, fraction): window = _np.ones(samples) samples_fraction = round(samples * fraction) parzen_window = signal.parzen(samples_fraction, ) parzen_window_left = parzen_window[:round(parzen_window.shape[0] / 2)] parzen_window_right = parzen_window[round(parzen_window.shape[0] / 2):] window[:parzen_window_left.shape[0]] = parzen_window_left window[-parzen_window_right.shape[0]:] = parzen_window_right # return parzen_window_left.shape,parzen_window_right.shape return window
def __init__(self, N, muext, sigmaext, S, tau=20, Vt=20, Vr=0): self.N = N self.tau = 20 self.Vt = Vt # threshold self.Vr = Vr # reset self.muext = muext self.sigmaext = sigmaext self.S = S self.V = np.zeros(self.N) + self.Vr self.win = parzen(7) self.Isyn = 0 self.firings_x = np.empty((1, 0), dtype=float) self.firings_y = np.empty((1, 0), dtype=float) self.neuron_indexes = np.arange(self.N) self.t = 0
def smoothing(self, window, abs=True): s = copy.deepcopy(self) nw = int(window / s.df) if nw > 0: if nw % 2 == 0: nw += 1 nw2 = int((nw - 1) / 2) w = signal.parzen(nw) a = np.r_[self.ew[nw2:0:-1], self.ew, self.ew[0], self.ew[-1:-nw2:-1]] if abs: s.ew = np.convolve(w / w.sum(), np.abs(a), mode='valid') else: s.ew = np.convolve(w / w.sum(), a, mode='valid') a = np.r_[self.ns[nw2:0:-1], self.ns, self.ns[0], self.ns[-1:-nw2:-1]] if abs: s.ns = np.convolve(w / w.sum(), np.abs(a), mode='valid') else: s.ns = np.convolve(w / w.sum(), a, mode='valid') a = np.r_[self.ud[nw2:0:-1], self.ud, self.ud[0], self.ud[-1:-nw2:-1]] if abs: s.ud = np.convolve(w / w.sum(), np.abs(a), mode='valid') else: s.ud = np.convolve(w / w.sum(), a, mode='valid') return s
from scipy import signal from matplotlib import pyplot as plt from matplotlib import style import mysignals as sigs import numpy as np from scipy.fftpack import fft, fftshift window = signal.parzen(51) plt.plot(window) plt.title("Parzen Window") plt.ylabel("Amplitude") plt.xlabel("Sample") plt.show() #frequency response plt.figure() A = fft(window, 2048) / (len(window) / 2.0) freq = np.linspace(-0.5, 0.5, len(A)) response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) plt.plot(freq, response) plt.axis([-0.5, 0.5, -120, 0]) plt.title("Frequency Response of Parzen Window") plt.ylabel("Normalized Magnitude(dB)") plt.xlabel("Normalized Frequency in cycles/sample") plt.show()
def generateMCvsCBRD(path): paramsofplot = { 'legend.fontsize': '18', # 'figure.figsize': (15, 5), 'axes.labelsize': '18', 'axes.titlesize': '18', 'xtick.labelsize': '18', 'ytick.labelsize': '18' } plt.rcParams.update(paramsofplot) win = parzen(15) win /= np.sum(win) fig, ax = plt.subplots(nrows=2, ncols=1, sharex=True) #, figsize=(10, 10) # sim_params = get_default_simulation_params4LIF() # # sim_params["duration"] = 500 # sim_params["Iext"] = 0.3 # sim_params["ext_sinapse_w"] = 0.0 # 0.002 # sim_params["use_CBRD"] = False # flow_mc, Vhistmc = run_simulation_LIF(sim_params) # flow_mc = np.convolve(flow_mc, win, mode="same") # t_mc = np.linspace(0, flow_mc.size * 0.1, flow_mc.size) # # sim_params["use_CBRD"] = True # flow_cbrd, Vhistcbrd = run_simulation_LIF(sim_params) # t_cbrd = np.linspace(0, flow_cbrd.size * 0.1, flow_cbrd.size) # # # ax[0].plot(t_mc, flow_mc, "r", label="Монте-Карло", color="k", linestyle=":") # ax[0].plot(t_cbrd, flow_cbrd, "b", label="РРП", color="k", linestyle="-") # ax[0].set_ylim(0, 1.5 * flow_cbrd.max()) # ax[0].set_xlabel("время, мс") # ax[0].set_ylabel("частота, Гц") # ax[0].legend() # ax[1].plot(t_cbrd, Vhistcbrd) sim_params = get_default_simulation_params4HH() sim_params["duration"] = 500 sim_params["sigma"] = 0.3 sim_params["Iext"] = 0.9 sim_params["Vt"] = -55.0 sim_params["std_of_Iext"] = 0.2 sim_params["Nstates"] = 800 sim_params["dts"] = 0.5 sim_params["ext_sinapse_w"] = 0.0 sim_params["use_CBRD"] = False flow_mc, Vhistmc = run_simulation_HH(sim_params) flow_mc = np.convolve(flow_mc, win, mode="same") t_mc = np.linspace(0, flow_mc.size * 0.1, flow_mc.size) sim_params["show_animation"] = False sim_params["use_CBRD"] = True #sim_params["sigma"] = 0.165 flow_cbrd, Vhistcbrd = run_simulation_HH(sim_params) t_cbrd = np.linspace(0, flow_cbrd.size * 0.1, flow_cbrd.size) ax[1].plot(t_mc, flow_mc, "r", label="Монте-Карло", color="r", linestyle=":") ax[1].plot(t_cbrd, flow_cbrd, "b", label="РРП", color="g", linestyle="-") ax[1].set_xlim(0, sim_params["duration"]) ax[1].set_ylim(0, 1.5 * flow_cbrd.max()) ax[1].set_xlabel("время, мс") ax[1].set_ylabel("частота, Гц") ax[1].legend() ax[0].plot(t_mc, Vhistmc, "r", label="Монте-Карло", color="k", linestyle=":") ax[0].plot(t_cbrd, Vhistcbrd, "b", label="РРП", color="k", linestyle="-") ax[0].set_ylim(-80, 5) ax[0].set_xlabel("время, мс") ax[0].set_ylabel("Потенциал, мВ") ax[0].legend() fig.savefig(path + "fig.png") plt.show()
# Plot the window and its frequency response: from scipy import signal from scipy.fftpack import fft, fftshift import matplotlib.pyplot as plt window = signal.parzen(51) plt.plot(window) plt.title("Parzen window") plt.ylabel("Amplitude") plt.xlabel("Sample") plt.figure() A = fft(window, 2048) / (len(window)/2.0) freq = np.linspace(-0.5, 0.5, len(A)) response = 20 * np.log10(np.abs(fftshift(A / abs(A).max()))) plt.plot(freq, response) plt.axis([-0.5, 0.5, -120, 0]) plt.title("Frequency response of the Parzen window") plt.ylabel("Normalized magnitude [dB]") plt.xlabel("Normalized frequency [cycles per sample]")
def answer_2_spacial_inputs_HH(path): iscompute = False std_iext_arr = np.linspace(0, 1, 5) # 10 iext = 0.2 fp_arr = np.linspace(2, 15, 10) # np.linspace(50, 70, 3) # ppv_arr = [] max_ppv_arr = [] win = parzen(15) win /= np.sum(win) fig, axs = plt.subplots(nrows=1, ncols=2) for fp in fp_arr: for stext in std_iext_arr: path_tmp = path + '{:.2f}'.format(stext) + "_" + '{:.2f}'.format( fp) print(path_tmp) if iscompute: flow_spatial, generators_signal, cv = run_HH(Nn=10, std_of_iext=stext, iext=iext, nspatialinputs=1, fp=fp, path=path_tmp) generators_signal = generators_signal[0] np.savez(path_tmp, flow=flow_spatial, artsignal=generators_signal, cv=cv) else: data = np.load(path_tmp + ".npz") flow_spatial = data["flow"] generators_signal = data["artsignal"] flow_spatial = np.convolve(flow_spatial, win, mode="same") answs_idx = argrelextrema(flow_spatial, np.greater, order=50)[0] input_idx = np.argwhere(np.diff(generators_signal) < 0) # answs_idx = answs_idx[flow_spatial[answs_idx] > np.percentile(flow_spatial, 80)] ppv = calculate_ppv(input_idx, answs_idx) ppv_arr.append(ppv) time = np.linspace(0, 1500, flow_spatial.size) fig_flow, ax = plt.subplots(ncols=1, nrows=2, sharex=True) ax[0].plot(time, flow_spatial) ax[1].plot(time, generators_signal) fig_flow.savefig(path_tmp + ".png") plt.close(fig_flow) ppv_arr = np.asarray(ppv_arr) max_ppv_arr.append(np.max(ppv_arr)) axs[0].plot(std_iext_arr, ppv_arr, label='{:.2f}'.format(fp)) ppv_arr = [] axs[0].set_ylabel("PPV") axs[0].set_xlabel(r"$\sigma_{I_{ext}}$") axs[0].legend() axs[1].plot(fp_arr, max_ppv_arr) axs[1].set_ylabel("PPV*") axs[1].set_xlabel("Частота стимулов") fig.tight_layout() path_tmp = path + "ppv_from_iext_std" fig.savefig(path_tmp) plt.close(fig)
def answer_2_inputs(): std_vt_arr = np.linspace(0, 5, 2) # 10 iext = 14 flow_spatial_arr = [] ppv_arr = [] win = parzen(15) for stdvt in std_vt_arr: flow_spatial, generators_signal = run_simulation(std_of_Vt=stdvt, iext=iext, nspatialinputs=1) generators_signal = generators_signal[0] flow_spatial = np.convolve(flow_spatial, win, mode="same") flow_spatial_arr.append(flow_spatial) t = np.linspace(0, 900, flow_spatial.size) answs_idx = argrelextrema(flow_spatial, np.greater, order=150)[0] input_idx = np.argwhere(np.diff(generators_signal) < 0) answs_idx = answs_idx[ flow_spatial[answs_idx] > np.percentile(flow_spatial, 80)] print(answs_idx) ppv = calculate_ppv(input_idx, answs_idx) ppv_arr.append(ppv) fig, axs = plt.subplots(nrows=1, ncols=1) axs.scatter(t[input_idx], np.zeros_like(t[input_idx]) + np.max(flow_spatial)) axs.scatter(t[answs_idx], flow_spatial[answs_idx], color="black") axs.plot(t, flow_spatial, color="red") plt.show(block=False) flow_spatial_arr = np.asarray(flow_spatial_arr) np.save("spatial_input", flow_spatial_arr) fig, axs = plt.subplots(nrows=1, ncols=1) axs.plot(std_vt_arr, ppv_arr) axs.set_title("PPV") plt.show(block=False) std_vt_arr = np.linspace(0, 12, 2) # 24 flow_time_arr = [] corr_arr = [] for stdvt in std_vt_arr: flow_time, generators_signal = run_simulation(std_of_Vt=stdvt, iext=iext, nspatialinputs=0, ntimesinputs=1) t = np.linspace(0, 900, flow_time.size) generators_signal = generators_signal[0] flow_time_arr.append(flow_time) R, p = pearsonr(flow_time, generators_signal) corr_arr.append(R) fig, axs = plt.subplots(nrows=1, ncols=1) sine = generators_signal * np.std(flow_time) + np.mean(flow_time) axs.plot(t, sine, color="blue") axs.plot(t, flow_time, color="red") plt.show(block=False) flow_time_arr = np.asarray(flow_time_arr) np.save("time_input", flow_time_arr) fig, axs = plt.subplots(nrows=1, ncols=1) axs.plot(std_vt_arr, corr_arr) axs.set_title("I/O correlation") plt.show()
$${\displaystyle {\hat {f}}_{h}(x)={\\frac {1}{n}}\sum _{i=1}^{n}K_{h}(x-x_{i})={\\frac {1}{nh}}\sum _{i=1}^{n}K{\Big (}{\\frac {x-x_{i}}{h}}{\Big )},}$$ where K is the kernel — a non-negative function that integrates to one — and h > 0 is a smoothing parameter called the bandwidth. A kernel with subscript h is called the scaled kernel and defined as $Kh(x) = 1/h K(x/h)$. ''') #%% from scipy import signal from scipy.fftpack import fft, fftshift import matplotlib.pyplot as plt #Number of points in the output window. If zero or less, an empty array is #returned. window = signal.parzen(51) plt.plot(window) plt.title("Parzen window") plt.ylabel("Amplitude") plt.xlabel("Sample") plt.figure() window = signal.parzen(100) plt.plot(window) plt.title("Parzen window") plt.ylabel("Amplitude") plt.xlabel("Sample") plt.figure() # A = fft(window, 2048) / (len(window)/2.0) # freq = np.linspace(-0.5, 0.5, len(A)) # response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
def fft(self, time, wave, taper_on=True, left=0.05, start=0.1, end=20, right=30, parzen_on=True, parzen_setting=0.1): dt = time[1] - time[0] #基線補正した元データ(時間領域) wave = wave - wave.mean() #FFTのために後続の0を付ける データの倍の長さの0を付けた後2の累乗にする flag = math.floor(math.log2(2 * len(time))) #切り捨て N = int(math.pow(2, flag + 1)) #flagに1追加する t = np.arange(0, N * dt, dt) add_zeros = np.zeros(len(t) - len(wave)) freq = np.linspace(0, 1.0 / dt, N) # 周波数軸 wave = np.append(wave, add_zeros) # 高速フーリエ変換 # fft_data = np.fft.fft(acc)/(N/2)*(1/dt) #逆変換するときは周期注意 fft = np.fft.fft(wave) / (N / 2) phase = np.angle(fft) if taper_on: #周波数フィルターの配列番号 f_left, f_start, f_end, f_right = int(left / (1 / (N * dt))), int( start / (1 / (N * dt))), int(end / (1 / (N * dt))), int( right / (1 / (N * dt))) #コサインテーパー作成 cos_taper = np.zeros(len(freq)) cos_taper[f_left:f_start] = [ 1 / 2 * (1 + math.cos(2 * math.pi / (2 * (f_start - f_left)) * (x * N * dt - f_start))) for x in freq[f_left:f_start] ] cos_taper[f_start:f_end] = 1 cos_taper[f_end:f_right] = [ 1 / 2 * (1 + math.cos(2 * math.pi / (2 * (f_right - f_end)) * (x * N * dt - f_end))) for x in freq[f_end:f_right] ] #costaper fft = fft * cos_taper abs_fft = "" #parzen window if parzen_setting: parzen_num = int(parzen_setting / (freq[1] - freq[0])) if parzen_num % 2 != 0: parzen_num += 1 #奇数点のparzen w_parzen = signal.parzen(parzen_num) * parzen_setting abs_fft = np.convolve(w_parzen, np.abs(fft), mode='same') # valid same full else: abs_fft = np.abs(fft) return freq[:N // 2], abs_fft[:N // 2], phase[:N // 2]