type=none_or_int, default=None, help="list of channels to plot") args, unknown = CLI.parse_known_args() asig = load_neo(args.data, 'analogsignal') signal = asig.as_array() dim_t, dim_channels = signal.shape non_nan_channels = [ i for i in range(dim_channels) if np.isfinite(signal[:, i]).all() ] thresholds = np.empty(dim_channels) thresholds.fill(np.nan) for channel in non_nan_channels: if channel in args.plot_channels: plot_channel = channel else: plot_channel = False thresholds[channel] = fit_amplitude_distribution( signal[:, channel], args.sigma_factor, args.fit_function, args.bin_num, plot_channel) if plot_channel: output_path = os.path.join( args.img_dir, args.img_name.replace('_channel0', f'_channel{channel}')) save_plot(output_path) np.save(args.output, thresholds)
def plot_downsampled_image(image, output_path): plt.figure() plt.imshow(image, interpolation='nearest', cmap='viridis', origin='lower') save_plot(output_path) return plt.gca()
CLI.add_argument("--output_img", nargs='?', type=none_or_str, default=None, help="path of output image file") CLI.add_argument("--event_name", "--EVENT_NAME", nargs='?', type=str, default='wavefronts', help="name of neo.Event to analyze (must contain waves)") args, unknown = CLI.parse_known_args() block = load_neo(args.data) evt = block.filter(name=args.event_name, objects="Event")[0] evt = evt[evt.labels.astype('str') != '-1'] optical_flow = block.filter(name='optical_flow', objects="AnalogSignal")[0] df_dict = {f'{args.event_name}_id': evt.labels, 'channel_id': evt.array_annotations['channels'], 'flow_direction_local_x': np.empty(len(evt), dtype=float), 'flow_direction_local_y': np.empty(len(evt), dtype=float), } for i, trigger in enumerate(evt): t_idx = np.argmax(optical_flow.times >= trigger) channel_id = evt.array_annotations['channels'][i], direction = optical_flow[t_idx, channel_id] df_dict['flow_direction_local_x'][i] = np.real(direction) df_dict['flow_direction_local_y'][i] = np.imag(direction) df = pd.DataFrame(df_dict) df.to_csv(args.output) if args.output_img is not None: save_plot(args.output_img)
help="lower bound of frequency band in Hz") CLI.add_argument("--lowpass_freq", nargs='?', type=none_or_float, default='None', help="upper bound of frequency band in Hz") CLI.add_argument("--psd_freq_res", nargs='?', type=float, default=5, help="frequency resolution of the power spectrum in Hz") CLI.add_argument("--psd_overlap", nargs='?', type=float, default=0.5, help="overlap parameter for Welch's algorithm [0-1]") args = CLI.parse_args() asig = load_neo(args.data, 'analogsignal') freqs, psd = welch_psd(asig, freq_res=args.psd_freq_res * pq.Hz, overlap=args.psd_overlap) plot_psd(freqs=freqs, psd=psd, highpass_freq=args.highpass_freq, lowpass_freq=args.lowpass_freq) save_plot(args.output)
wavefront_evt = block.filter(name=args.event_name, objects="Event")[0] wavefront_evt = wavefront_evt[wavefront_evt.labels.astype('str') != '-1'] optical_flow = block.filter(name='optical_flow', objects="ImageSequence")[0] planar_labels = label_planar(waves_event=wavefront_evt, vector_field=optical_flow, times=asig.times, threshold=args.alignment_threshold) planar_labels[f'{args.event_name}_id'] = np.unique(wavefront_evt.labels) planar_labels.to_csv(args.output) dim_t, dim_x, dim_y = optical_flow.shape skip_step = int(min([dim_x, dim_y]) / 50) + 1 for i, wave_id in enumerate(np.unique(wavefront_evt.labels)): fig, ax = plt.subplots() plot_planarity(waves_event=wavefront_evt, vector_field=optical_flow, times=asig.times, skip_step=skip_step, wave_id=i, ax=ax) save_plot( os.path.join(os.path.dirname(args.output), f'wave_{wave_id}.png')) if not i: save_plot(args.output_img) plt.close()
num_frames=dim_t, frame_rate=args.frame_rate) if args.colormap == 'gray': cmap = plt.cm.gray else: # 'gray', 'viridis' (sequential), 'coolwarm' (diverging), 'twilight' (cyclic) cmap = plt.get_cmap(args.colormap) frames = imgseq.as_array() vmin = np.nanmin(frames) vmax = np.nanmax(frames) markersize = 50 / max([dim_x, dim_y]) skip_step = int(min([dim_x, dim_y]) / 50) + 1 # plot frames for i, frame_num in enumerate(frame_idx): ax = plot_frame(frames[frame_num], cmap=cmap, vmin=vmin, vmax=vmax) if optical_flow is not None: plot_vectorfield(optical_flow[frame_num], skip_step=skip_step) if args.event is not None and up_coords is not None: plot_transitions(up_coords[frame_num], markersize=markersize, markercolor=args.markercolor) ax.set_ylabel('pixel size: {:.2f} mm'.format(imgseq.spatial_scale.rescale('mm').magnitude)) ax.set_xlabel('{:.3f} s'.format(times[frame_num].rescale('s').magnitude)) save_plot(os.path.join(args.frame_folder, args.frame_name + '_{}.{}'.format(str(i).zfill(5), args.frame_format))) plt.close()
psd_overlap=args.psd_overlap, fft_slice=fft_slice) # if args.channels[0] is not None: # WARNING! TypeError: 'NoneType' object is not subscriptable if it is None # (the condition args.channel[0] cannot be evaluated) if args.channels is not None: if not len(args.output_img) == len(args.channels): raise InputError("The number of plotting channels must "\ + "correspond to the number of image output paths!") for output_img, channel in zip(args.output_img, args.channels): #[output_img] = output_img # otherwise... "TypeError: expected str, bytes or os.PathLike object, not list" plot_logMUA_estimation(asig=block.segments[0].analogsignals[0], logMUA_asig=asig, highpass_freq=args.highpass_freq * pq.Hz, lowpass_freq=args.lowpass_freq * pq.Hz, t_start=args.t_start, t_stop=args.t_stop, channel=channel) save_plot(output_img) asig.name += "" asig.description += "Estimated logMUA signal [{}, {}] Hz ({}). "\ .format(args.highpass_freq, args.lowpass_freq, os.path.basename(__file__)) block.segments[0].analogsignals[0] = asig write_neo(args.output, block)
save_path = os.path.splitext(args.output)[0] + f'_wave{wave_id}' np.save(save_path + '.npy', inter_wave_intervals) fig, ax = plt.subplots() num_intervals = np.sum(np.isfinite(inter_wave_intervals).astype(int)) if np.isfinite(inter_wave_intervals).any(): bin_width = asig.sampling_period.rescale(t_unit).magnitude bins = np.arange( np.nanmin(inter_wave_intervals) - bin_width / 2, np.nanmax(inter_wave_intervals) + bin_width / 2, bin_width) else: bins = 'auto' sns.histplot(inter_wave_intervals, kde=False, ax=ax, bins=bins) ax.set_title( f'wave {wave_id}; {num_intervals}/{num_nonnan_channels} channels') ax.set_xlabel(f'time until next wave (UP transition) [{t_unit}]') ax.set_ylabel('') save_plot(save_path + '.png') # transform to DataFrame df = pd.DataFrame( IWIs, columns=['inter_wave_interval', 'inter_wave_interval_std']) df['inter_wave_interval_unit'] = t_unit df[f'{args.event_name}_id'] = wave_ids df.to_csv(args.output) # ToDo save_plot(args.output_img)