import plotstyle_plt import numpy as np import matplotlib.pyplot as plt from itertools import product from thunderhopper.filetools import search_files from thunderhopper.modeltools import load_data from color_functions import load_colors from plot_functions import hide_axis, ylimits, xlabel, ylabel, hide_ticks,\ plot_line, strip_zeros, time_bar, zoom_inset,\ letter_subplot, title_subplot from IPython import embed def add_snip_axes(fig, grid_kwargs): grid = fig.add_gridspec(**grid_kwargs) axes = np.zeros((grid.nrows, grid.ncols), dtype=object) for i, j in product(range(grid.nrows), range(grid.ncols)): axes[i, j] = fig.add_subplot(grid[i, j]) [hide_axis(ax, 'left') for ax in axes[:, 1:].flatten()] [hide_axis(ax, 'bottom') for ax in axes.flatten()] return axes def plot_snippets(axes, time, snippets, ymin=None, ymax=None, **kwargs): ymin, ymax = ylimits(snippets, minval=ymin, maxval=ymax, pad=0.05) handles = [] for ax, snippet in zip(axes, snippets.T): handles.extend(plot_line(ax, time, snippet, ymin=ymin, ymax=ymax, **kwargs)) return handles # GENERAL SETTINGS: target = 'Omocestus_rufipes' data_paths = search_files(target, excl='noise', dir='../data/inv/log_hp/') stages = ['env', 'log', 'inv'] load_kwargs = dict( files=stages, keywords=['scales', 'snip', 'measure'] ) save_path = '../figures/fig_invariance_log_hp.pdf' compute_ratios = True show_diag = True show_noise = True if compute_ratios: ref_data = load_data('../data/processed/white_noise_sd-1.npz', files=stages)[0] ref_measures = {k: v.std() for k, v in ref_data.items() if not k.endswith('rate')} # GRAPH SETTINGS: fig_kwargs = dict( figsize=(32/2.54, 16/2.54), ) super_grid_kwargs = dict( nrows=2, ncols=3, wspace=0, hspace=0, left=0, right=1, bottom=0, top=1 ) subfig_specs = dict( pure=(0, slice(0, -1)), noise=(1, slice(0, -1)), big=(slice(None), -1), ) block_height = 0.8 edge_padding = 0.08 pure_grid_kwargs = dict( nrows=len(stages), ncols=None, wspace=0.1, hspace=0.15, left=0.16, right=0.95, bottom=1 - block_height - edge_padding, top=1 - edge_padding, height_ratios=[1, 2, 1] ) noise_grid_kwargs = dict( nrows=len(stages), ncols=None, wspace=0.1, hspace=0.15, left=0.16, right=0.95, bottom=edge_padding, top=edge_padding + block_height, height_ratios=[1, 2, 1] ) big_grid_kwargs = dict( nrows=2, ncols=1, wspace=0, hspace=0.3, left=0.19, right=0.96, bottom=0.09, top=0.98 ) anchor_kwargs = dict( aspect='equal', adjustable='box', anchor=(0.5, 0.5) ) # PLOT SETTINGS: fs = dict( lab_norm=16, lab_tex=20, letter=22, tit_norm=16, tit_tex=20, bar=16, ) colors = load_colors('../data/stage_colors.npz') lw_snippets = 1 lw_big = 3 xlabels = dict( big='scale $\\alpha$', ) ylabels = dict( env='$x_{\\text{env}}$', log='$x_{\\text{dB}}$', inv='$x_{\\text{adapt}}$', big='$\\sigma_{\\alpha}\\,/\\,\\sigma_{\\eta}$', ) xlab_big_kwargs = dict( y=0, fontsize=fs['lab_norm'], ha='center', va='bottom', ) ylab_snip_kwargs = dict( x=0, fontsize=fs['lab_tex'], rotation=0, ha='left', va='center', ) ylab_big_kwargs = dict( x=0.05, fontsize=fs['lab_tex'], ha='center', va='top', ) yloc = dict( env=1000, log=40, inv=20 ) title_kwargs = dict( x=0.5, y=1, ha='center', va='bottom', fontsize=fs['tit_norm'], ) letter_snip_kwargs = dict( x=0, yref=0.5, ha='left', va='center', fontsize=fs['letter'], ) letter_big_kwargs = dict( x=0.05, yref=letter_snip_kwargs['yref'], ha='left', va='center', fontsize=fs['letter'], ) zoom_inset_bounds = [0.1, 0.2, 0.8, 0.6] zoom_kwargs = dict( x0=0.45, x1=0.55, y0=0, y1=0.0006, low_left=True, low_right=True, ec='k', lw=1, alpha=1, ) inset_tick_kwargs = dict( axis='y', length=3, pad=1, left=False, labelleft=False, right=True, labelright=True, ) bar_time = 5 bar_kwargs = dict( dur=bar_time, y0=-0.25, y1=-0.1, xshift=1, color='k', lw=0, clip_on=False, text_pos=(-0.1, 0.5), text_str=f'${bar_time}\\,\\text{{s}}$', text_kwargs=dict( fontsize=fs['bar'], ha='right', va='center', ) ) diag_kwargs = dict( c=(0.75, 0.75, 0.75), lw=2, ls='--', zorder=1.9, ) noise_rel_thresh = 0.95 noise_kwargs = dict( fc=(0.9, 0.9, 0.9), ec='none', lw=0, zorder=1.5, ) # EXECUTION: for data_path in data_paths: print(f'Processing {data_path}') # Load invariance data: pure_data, config = load_data(data_path, **load_kwargs) noise_data, _ = load_data(data_path.replace('.npz', '_noise.npz'), **load_kwargs) pure_scales, noise_scales = pure_data['scales'], noise_data['scales'] t_full = np.arange(pure_data['snip_env'].shape[0]) / config['env_rate'] # Prepare overall graph: fig = plt.figure(**fig_kwargs) super_grid = fig.add_gridspec(**super_grid_kwargs) fig.canvas.draw() # Prepare pure-song snippet axes: pure_grid_kwargs['ncols'] = pure_data['example_scales'].size pure_subfig = fig.add_subfigure(super_grid[subfig_specs['pure']]) pure_axes = add_snip_axes(pure_subfig, pure_grid_kwargs) for ax, stage in zip(pure_axes[:, 0], stages): ax.yaxis.set_major_locator(plt.MultipleLocator(yloc[stage])) ylabel(ax, ylabels[stage], **ylab_snip_kwargs, transform=pure_subfig.transSubfigure) for ax, scale in zip(pure_axes[0, :], pure_data['example_scales']): pure_title = title_subplot(ax, f'$\\alpha={strip_zeros(scale)}$', **title_kwargs) letter_subplot(pure_subfig, 'a', ref=pure_title, **letter_snip_kwargs) pure_inset = pure_axes[0, 0].inset_axes(zoom_inset_bounds) pure_inset.spines[:].set(visible=True, lw=zoom_kwargs['lw']) pure_inset.tick_params(**inset_tick_kwargs) hide_ticks(pure_inset, 'bottom', ticks=False) # Prepare noise-song snippet axes: noise_grid_kwargs['ncols'] = noise_data['example_scales'].size noise_subfig = fig.add_subfigure(super_grid[subfig_specs['noise']]) noise_axes = add_snip_axes(noise_subfig, noise_grid_kwargs) for ax, stage in zip(noise_axes[:, 0], stages): ax.yaxis.set_major_locator(plt.MultipleLocator(yloc[stage])) ylabel(ax, ylabels[stage], **ylab_snip_kwargs, transform=noise_subfig.transSubfigure) for ax, scale in zip(noise_axes[0, :], noise_data['example_scales']): noise_title = title_subplot(ax, f'$\\alpha={strip_zeros(scale)}$', **title_kwargs) letter_subplot(noise_subfig, 'c', ref=noise_title, **letter_snip_kwargs) noise_inset = noise_axes[0, 0].inset_axes(zoom_inset_bounds) noise_inset.spines[:].set(visible=True, lw=zoom_kwargs['lw']) noise_inset.tick_params(**inset_tick_kwargs) hide_ticks(noise_inset, 'bottom', ticks=False) # Prepare analysis axes: big_subfig = fig.add_subfigure(super_grid[subfig_specs['big']]) big_grid = big_subfig.add_gridspec(**big_grid_kwargs) big_axes = np.zeros((big_grid.nrows,), dtype=object) for i, scales in enumerate([pure_scales, noise_scales]): ax = big_subfig.add_subplot(big_grid[i, 0]) ax.set_xlim(scales[0], scales[-1]) ax.set_ylim(scales[0], scales[-1]) ax.set_xscale('symlog', linthresh=scales[1], linscale=0.5) ax.set_yscale('symlog', linthresh=scales[1], linscale=0.5) ax.set_aspect(**anchor_kwargs) ylabel(ax, ylabels['big'], transform=big_subfig.transSubfigure, **ylab_big_kwargs) if i == 0: hide_ticks(ax, 'bottom') letter_subplot(big_subfig, 'b', ref=pure_title, **letter_big_kwargs) else: xlabel(ax, xlabels['big'], transform=big_subfig.transSubfigure, **xlab_big_kwargs) letter_subplot(big_subfig, 'd', ref=noise_title, **letter_big_kwargs) big_axes[i] = ax # Plot pure-song envelope snippets: handle = plot_snippets(pure_axes[0, :], t_full, pure_data['snip_env'], ymin=0, c=colors['env'], lw=lw_snippets)[0] zoom_inset(pure_axes[0, 0], pure_inset, handle, transform=pure_axes[0, 0].transAxes, **zoom_kwargs) # Plot pure-song logarithmic snippets: plot_snippets(pure_axes[1, :], t_full, pure_data['snip_log'], c=colors['log'], lw=lw_snippets) # Plot pure-song invariant snippets: plot_snippets(pure_axes[2, :], t_full, pure_data['snip_inv'], c=colors['inv'], lw=lw_snippets) # Plot noise-song envelope snippets: ymin, ymax = pure_axes[0, 0].get_ylim() handle = plot_snippets(noise_axes[0, :], t_full, noise_data['snip_env'], ymin, ymax, c=colors['env'], lw=lw_snippets)[0] zoom_inset(noise_axes[0, 0], noise_inset, handle, transform=noise_axes[0, 0].transAxes, **zoom_kwargs) # Plot noise-song logarithmic snippets: ymin, ymax = pure_axes[1, 0].get_ylim() plot_snippets(noise_axes[1, :], t_full, noise_data['snip_log'], ymin, ymax, c=colors['log'], lw=lw_snippets) # Plot noise-song invariant snippets: ymin, ymax = pure_axes[2, 0].get_ylim() plot_snippets(noise_axes[2, :], t_full, noise_data['snip_inv'], ymin, ymax, c=colors['inv'], lw=lw_snippets) # Indicate time scale: time_bar(noise_axes[-1, -1], **bar_kwargs) if compute_ratios: # Relate pure-song measures to zero scale: pure_data['measure_env'] /= ref_measures['env'] pure_data['measure_log'] /= ref_measures['log'] pure_data['measure_inv'] /= ref_measures['inv'] # Relate noise-song measures to zero scale: noise_data['measure_env'] /= ref_measures['env'] noise_data['measure_log'] /= ref_measures['log'] noise_data['measure_inv'] /= ref_measures['inv'] # Plot pure-song measures (ideal): big_axes[0].plot(pure_scales, pure_data['measure_env'], c=colors['env'], lw=lw_big) big_axes[0].plot(pure_scales, pure_data['measure_log'], c=colors['log'], lw=lw_big) big_axes[0].plot(pure_scales, pure_data['measure_inv'], c=colors['inv'], lw=lw_big) # Plot noise-song measures (limited): big_axes[1].plot(noise_scales, noise_data['measure_env'], c=colors['env'], lw=lw_big) big_axes[1].plot(noise_scales, noise_data['measure_log'], c=colors['log'], lw=lw_big) big_axes[1].plot(noise_scales, noise_data['measure_inv'], c=colors['inv'], lw=lw_big) if show_diag: # Indicate diagonal: big_axes[0].plot(pure_scales, pure_scales, **diag_kwargs) big_axes[1].plot(noise_scales, noise_scales, **diag_kwargs) if show_noise: # Indicate noise floor: if compute_ratios: span_measure = noise_data['measure_inv'][-1] - ref_measures['inv'] thresh_measure = ref_measures['inv'] + noise_rel_thresh * span_measure else: span_measure = noise_data['measure_inv'][-1] - noise_data['measure_inv'][0] thresh_measure = noise_data['measure_inv'][0] + noise_rel_thresh * span_measure thresh_ind = np.nonzero(noise_data['measure_inv'] < thresh_measure)[0][-1] thresh_scale = noise_scales[thresh_ind] big_axes[1].axvspan(noise_scales[0], thresh_scale, **noise_kwargs) if save_path is not None: fig.savefig(save_path, bbox_inches='tight') plt.show() print('Done.') embed()