def plot_logMUA_estimation(asig, logMUA_asig, highpass_freq, lowpass_freq, t_start, t_stop, channel): asig = time_slice(asig, t_start, t_stop) logMUA_asig = time_slice(logMUA_asig, t_start, t_stop) filt_asig = butter(asig, highpass_freq=highpass_freq, lowpass_freq=lowpass_freq) sns.set(style='ticks', palette="deep", context="notebook") fig, ax = plt.subplots() ax.plot(asig.times, zscore(asig.as_array()[:,channel]), label='original signal') ax.plot(filt_asig.times, zscore(filt_asig.as_array()[:,channel]) + 10, label=f'signal [{highpass_freq}-{lowpass_freq}]', alpha=0.5) ax.plot(logMUA_asig.times, zscore(logMUA_asig.as_array()[:,channel]) + 20, label='logMUA') ax.set_title('Channel {}'.format(channel)) ax.set_xlabel('time [{}]'.format(asig.times.units.dimensionality.string)) ax.set_yticklabels([]) plt.legend() return ax
def phase_phase_coupling(low_fr_signal, high_fr_signal, bands4highfr, fd, nmarray, thresh_std=None, circ_distr=False, butter_order=2): """ run cossfrequency_phase_phase_coupling for diffrent bands """ couplings = [] distrss = [] for band in bands4highfr: high_signal_band = sigp.butter(high_fr_signal, highpass_freq=band[0], lowpass_freq=band[1], order=butter_order, fs=fd) coupling, bins, distrs = cossfrequency_phase_phase_coupling( low_fr_signal, high_signal_band, nmarray, thresh_std=thresh_std, circ_distr=circ_distr) couplings.append(coupling) distrss.append(distrs) return couplings, bins, distrss
# lfp_sp[freqs < 0].imag = -lfp_sp[freqs > 0].imag # lfp = np.fft.ifft(lfp_sp).real # lfp[lfp > 0.1] = 0 # lfp *= 50 #decres_phases = (phases > 0.5) & (phases < np.pi) lfp = np.cos(phases) + np.random.normal(0, 0.5, t.size) lfp += 0.7 * np.cos( 2 * np.pi * 45 * t ) * vonmises.pdf(phases, 3.0, loc=1.5) plt.plot(t, lfp) plt.show() theta = sigp.butter(lfp, highpass_freq=4, lowpass_freq=20, order=3, fs=fd ) gamma_freqs = np.arange(25, 90, 1) W = sigp.wavelet_transform(lfp, gamma_freqs, nco=6, fs=fd) # W = W[:, (t>0.4)&(t<1.6)] # t = t[(t>0.4)&(t<1.6)] mi = [] for fr_idx in range(gamma_freqs.size):
def processing_and_save(filepath): with h5py.File(filepath, 'a') as h5file: for elecr in h5file["extracellular"].keys(): lfp_group = h5file["extracellular/" + elecr + "/lfp"] lfp_group_origin = lfp_group["origin_data"] try: process_group = lfp_group.create_group("processing") except ValueError: del h5file["extracellular/" + elecr + "/lfp/processing"] process_group = lfp_group.create_group("processing") fd = lfp_group_origin.attrs["SamplingRate"] lfp_keys = lfp_group_origin.keys() for key_idx in range(len(lfp_keys)): key = "channel_" + str(key_idx + 1) lfp = lfp_group_origin[key][:] freqs = np.fft.rfftfreq(lfp.size, d=1 / fd) freqs = freqs[1:] # remove 0 frequency freqs = freqs[freqs <= processing_param[ "max_freq_lfp"]] # remove frequencies below 500 Hz wavelet_group = process_group.create_group(key + "_wavelet") wavelet_group.create_dataset("frequencies", data=freqs) wdset = wavelet_group.create_dataset(key + "wavelet_coeff", (len(freqs), len(lfp)), dtype="c16") for start_idx in range(0, freqs.size, processing_param["freqs_step"]): end_idx = start_idx + processing_param["freqs_step"] if end_idx > freqs.size: end_idx = freqs.size W = sigp.wavelet_transform( lfp, freqs[start_idx:end_idx], nco=processing_param["morlet_w0"], fs=fd) wdset[start_idx:end_idx, :] = W bands_group = process_group.create_group(key + "_bands") for band_name, freq_lims in processing_param[ "filt_bands"].items(): filtered_signal = sigp.butter(lfp, highpass_freq=freq_lims[0], \ lowpass_freq=freq_lims[1], order=processing_param["butter_order"], fs=fd ) bands_group.create_dataset(band_name, data=filtered_signal) """ try: firing_group = h5file["extracellular/electrode_1/firing"] except ValueError: return try: # тут можно сделать цикл по ритмам, пока берем только тета firing_process_group = firing_group.create_group("processing") except ValueError: del h5file["extracellular/electrode_1/firing/processing"] firing_process_group = firing_group.create_group("processing") firing_origin = firing_group["origin_data"] firing_theta = firing_process_group.create_group("theta") # print( firing_origin.keys() ) for celltype in firing_origin.keys(): celltype_firings = np.empty(shape=0, dtype=np.float64) for dsetname, cell_firing_dset in firing_origin[celltype].items(): celltype_firings = np.append(celltype_firings, cell_firing_dset[:]) # тут нужно взять канал из пирамидного слоя theta_lfp = h5file["extracellular/electrode_1/lfp/processing/channel_2_bands/theta"][:] bins, phase_distr = plib.get_phase_disrtibution(celltype_firings, theta_lfp, fd) firing_theta.create_dataset(celltype, data = phase_distr) """ return
# ============================================================================= filtered_anasig = [] # Loop through all AnalogSignal objects in the loaded data for anasig in data_block.segments[0].analogsignals: if anasig.annotations['nsx'] == 2: # AnalogSignal is LFP from ns2 anasig.name = 'LFP (online filter, ns%i)' % anasig.annotations['nsx'] elif anasig.annotations['nsx'] in [5, 6]: # AnalogSignal is raw signal from ns5 or ns6 anasig.name = 'raw (ns%i)' % anasig.annotations['nsx'] # Use the Elephant library to filter the analog signal f_anasig = butter( anasig, highpass_freq=None, lowpass_freq=250 * pq.Hz, order=4) f_anasig.name = 'LFP (offline filtered ns%i)' % \ anasig.annotations['nsx'] filtered_anasig.append(f_anasig) # Attach all offline filtered LFPs to the segment of data data_block.segments[0].analogsignals.extend(filtered_anasig) # ============================================================================= # Construct analysis epochs # # In this step we extract and cut the data into time segments (termed analysis # epochs) that we wish to analyze. We contrast these analysis epochs to the # behavioral trials that are defined by the experiment as occurrence of a Trial
def processing_and_save(filepath): with h5py.File(filepath, 'a') as h5file: lfp_group = h5file["extracellular/electrode_1/lfp"] lfp_group_origin = lfp_group["origin_data"] try: process_group = lfp_group.create_group("processing") except ValueError: del h5file["extracellular/electrode_1/lfp/processing"] process_group = lfp_group.create_group("processing") wavelet_group = process_group.create_group("wavelet") bands_group = process_group.create_group("bands") theta_gamma_coupling_group = process_group.create_group( "theta_gamma_coupling") theta_gamma_phase_phase_coupling_group = process_group.create_group( "theta_gamma_phase_phase_coupling") modulation_index_group = process_group.create_group("modulation_index") fd = lfp_group_origin.attrs["SamplingRate"] lfp_keys = lfp_group_origin.keys() for key_idx in range(len(lfp_keys)): key = "channel_" + str(key_idx + 1) lfp = lfp_group_origin[key][:] freqs = np.linspace(2, 200, 198) # freqs = freqs[freqs <= processing_param["max_freq_lfp"] ] # remove frequencies below 500 Hz channel_wavelet_group = wavelet_group.create_group(key) channel_wavelet_group.create_dataset("frequecies", data=freqs) wdset = channel_wavelet_group.create_dataset( "wavelet_coeff", (len(freqs), len(lfp)), dtype="c16") for start_idx in range(0, freqs.size, processing_param["freqs_step"]): end_idx = start_idx + processing_param["freqs_step"] if end_idx > freqs.size: end_idx = freqs.size W = sigp.wavelet_transform(lfp, freqs[start_idx:end_idx], nco=processing_param["morlet_w0"], fs=fd) wdset[start_idx:end_idx, :] = W ##################################### channel_bands_group = bands_group.create_group(key) # lfp = zscore(lfp) for band_name, freq_lims in processing_param["filt_bands"].items(): filtered_signal = sigp.butter(lfp, highpass_freq=freq_lims[0], \ lowpass_freq=freq_lims[1], order=processing_param["butter_order"], fs=fd ) channel_bands_group.create_dataset(band_name, data=filtered_signal) ##################################### # theta-gamma phase amplitude coupling channel_theta_gamma_coupling_group = theta_gamma_coupling_group.create_group( key) phase_signal = channel_bands_group["theta"][:] gamma_freqs = channel_wavelet_group["frequecies"][:] is_gamma_freqs = ( gamma_freqs >= processing_param["freqs4theta_gamma_coupling"] [0]) & (gamma_freqs <= processing_param["freqs4theta_gamma_coupling"][1]) coefAmp = channel_wavelet_group["wavelet_coeff"][:] coefAmp = coefAmp[is_gamma_freqs, :] gamma_freqs = gamma_freqs[is_gamma_freqs] phasebins = 50 coupling = plib.cossfrequency_phase_amp_coupling( phase_signal, coefAmp, phasebins=phasebins, nkernel=15) channel_theta_gamma_coupling_group.create_dataset( "coupling_matrix", data=coupling) channel_theta_gamma_coupling_group.create_dataset("gamma_freqs", data=gamma_freqs) channel_theta_gamma_coupling_group.create_dataset( "theta_phase", data=np.linspace(-np.pi, np.pi, phasebins)) #################################################################################### # theta-gamma phase phase coupling channel_theta_gamma_phase_phase_coupling_group = theta_gamma_phase_phase_coupling_group.create_group( key) phase_signal = channel_bands_group["theta"][:] couplings, binss, distrss = plib.phase_phase_coupling(phase_signal, lfp, processing_param["gamma_bands4phase_phase_coupling"], \ fd, processing_param["nmarray"], thresh_std=None, circ_distr=True, butter_order=processing_param["butter_order"]) channel_theta_gamma_phase_phase_coupling_group.create_dataset( "nmarray", data=processing_param["nmarray"]) channel_theta_gamma_phase_phase_coupling_group.create_dataset( "bins", data=binss) for band_idx, phase_phase_band in enumerate( processing_param["gamma_bands4phase_phase_coupling"]): diap_name = "_" + str(phase_phase_band[0]) + "-" + str( phase_phase_band[1]) channel_theta_gamma_phase_phase_coupling_group.create_dataset( "coupling" + diap_name, data=couplings[band_idx]) channel_theta_gamma_phase_phase_coupling_group.create_dataset( "distrs" + diap_name, data=distrss[band_idx]) #################################################################################### # phase amplidute modulation index channel_modulation_index_group = modulation_index_group.create_group( key) freqs = channel_wavelet_group["frequecies"][:] freqs4phase_sl = plib.slice_by_bound_values( freqs, processing_param["modulation_index"]["freqs4phase"][0], processing_param["modulation_index"]["freqs4phase"][1]) freqs4ampl_sl = plib.slice_by_bound_values( freqs, processing_param["modulation_index"]["freqs4amplitude"][0], processing_param["modulation_index"]["freqs4amplitude"][1]) W4phase = channel_wavelet_group["wavelet_coeff"][freqs4phase_sl, :] W4ampls = channel_wavelet_group["wavelet_coeff"][freqs4ampl_sl, :] mi = plib.get_modulation_index(W4phase, W4ampls, nbins=20) channel_modulation_index_group.create_dataset( "freqs4phase", data=freqs[freqs4phase_sl]) channel_modulation_index_group.create_dataset( "freqs4ampl", data=freqs[freqs4ampl_sl]) channel_modulation_index_group.create_dataset("modulation_index", data=mi) #################################################################################### # current source density current_source_density_group = process_group.create_group( "current_source_density") for band_name in processing_param["filt_bands"].keys(): lfp_band_list = [] for channel_name, channel_group in sorted( process_group["bands"].items(), key=lambda x: int(x[0].split("_")[-1])): lfp_band_list.append(channel_group[band_name][:]) csd = plib.current_sourse_density(lfp_band_list, dz=1) csd = zoom(csd, zoom=(processing_param["upsamling4csd"], 1), mode="nearest") current_source_density_group.create_dataset(band_name, data=csd) firing_group = h5file["extracellular/electrode_1/firing"] try: firing_process_group = firing_group.create_group("processing") except ValueError: del h5file["extracellular/electrode_1/firing/processing"] firing_process_group = firing_group.create_group("processing") firing_origin = firing_group["origin_data"] phase_distrs_group = firing_process_group.create_group("phase_distrs") # signal from pyramidal layer band_pyr_channel = h5file[ "extracellular/electrode_1/lfp/processing/bands/channel_" + str(processing_param["number_pyr_layer"])] for celltype in firing_origin.keys(): celltype_phase_distrs_group = phase_distrs_group.create_group( celltype) celltype_firings = np.empty(shape=0, dtype=np.float64) for dsetname, cell_firing_dset in firing_origin[celltype].items(): celltype_firings = np.append(celltype_firings, cell_firing_dset[:]) for band_name in processing_param["filt_bands"].keys(): lfp_band = band_pyr_channel[band_name][:] bins, phase_distr, R = plib.get_phase_disrtibution( celltype_firings, lfp_band, fd) celltype_phase_distrs_group.create_dataset(band_name, data=phase_distr) #################################################################################### # save modulation (R) for all neurons celltype_phase_distrs_group.create_dataset(band_name + "_R", data=np.asarray(R)) return
CLI.add_argument("--lowpass_freq", nargs='?', type=none_or_float) CLI.add_argument("--order", nargs='?', type=int) CLI.add_argument("--filter_function", nargs='?', type=str) args = CLI.parse_args() # load images with neo.NixIO(args.data) as io: block = io.read_block() check_analogsignal_shape(block.segments[0].analogsignals) remove_annotations([block] + block.segments + block.segments[0].analogsignals) asig = butter(block.segments[0].analogsignals[0], highpass_freq=args.highpass_freq * pq.Hz, lowpass_freq=args.lowpass_freq * pq.Hz, order=args.order, filter_function=args.filter_function, axis=0) # save processed data asig.name += "" asig.description += "Frequency filtered with [{}, {}]Hz order {} "\ .format(args.highpass_freq, args.lowpass_freq, args.order)\ + " using {} scipy algorithm.({}). "\ .format(args.filter_function, os.path.basename(__file__)) block.segments[0].analogsignals[0] = asig with neo.NixIO(args.output) as io: