Made fig_invariance_rect_lp.pdf and corresponding appendix figure.

Adjusted fig_invariance_log_hp.pdf with 2nd yaxis in dB.

Co-authored-by: Copilot <copilot@github.com>
This commit is contained in:
j-hartling
2026-04-27 18:18:34 +02:00
parent 5411a309f7
commit 7e1aa8721a
26 changed files with 994 additions and 195 deletions

View File

@@ -33,7 +33,7 @@ normalization = [
'max',
'base',
'range',
][3]
][0]
suffix = dict(
none='_unnormed',
min='_norm-min',

View File

@@ -7,8 +7,8 @@ from thunderhopper.modeltools import load_data
from misc_functions import shorten_species, get_saturation
from color_functions import load_colors
from plot_functions import hide_axis, ylimits, super_xlabel, ylabel, hide_ticks,\
plot_line, strip_zeros, time_bar, zoom_inset,\
letter_subplot, letter_subplots, title_subplot
plot_line, strip_zeros, time_bar, zoom_inset, shift_subplot,\
letter_subplot, letter_subplots, title_subplot, color_axis
from IPython import embed
def add_snip_axes(fig, grid_kwargs):
@@ -27,10 +27,10 @@ def plot_snippets(axes, time, snippets, ymin=None, ymax=None, **kwargs):
handles.extend(plot_line(ax, time, snippet, ymin=ymin, ymax=ymax, **kwargs))
return handles
# GENERAL SETTINGS:
target = 'Omocestus_rufipes_DJN_32-40s724ms-48s779ms'
data_path = search_files(target, excl='noise', dir='../data/inv/log_hp/')[0]
ref_path = '../data/inv/log_hp/ref_measures.npz'
save_path = '../figures/fig_invariance_log_hp.pdf'
target_species = [
'Chorthippus_biguttulus',
@@ -46,7 +46,7 @@ load_kwargs = dict(
files=stages,
keywords=['scales', 'snip', 'measure']
)
compute_ratios = True
relate_to_noise = True
exclude_zero = True
show_diag = True
show_plateaus = True
@@ -79,7 +79,7 @@ pure_grid_kwargs = dict(
wspace=0.1,
hspace=0.15,
left=0.11,
right=0.95,
right=0.98,
bottom=1 - block_height - edge_padding,
top=1 - edge_padding,
height_ratios=[1, 2, 1]
@@ -95,14 +95,15 @@ noise_grid_kwargs = dict(
top=edge_padding + block_height,
height_ratios=[1, 2, 1]
)
big_col_shift = -0.12
big_grid_kwargs = dict(
nrows=1,
ncols=3,
wspace=0.3,
wspace=0.25,
hspace=0,
left=pure_grid_kwargs['left'],
left=pure_grid_kwargs['left'] - big_col_shift,
right=pure_grid_kwargs['right'],
bottom=0.05,
bottom=0.03,
top=1
)
anchor_kwargs = dict(
@@ -137,7 +138,9 @@ ylabels = dict(
env='$x_{\\text{env}}$',
log='$x_{\\text{dB}}$',
inv='$x_{\\text{adapt}}$',
big='$\\sigma_x\\,/\\,\\sigma_{\\eta}$',
big_pure='$\\sigma_x$',
big_log='$\\sigma_x\\,[\\text{dB}]$',
big_noise='$\\sigma_x\\,/\\,\\sigma_{\\eta}$' if relate_to_noise else None,
)
xlab_big_kwargs = dict(
y=0,
@@ -145,6 +148,18 @@ xlab_big_kwargs = dict(
ha='center',
va='bottom',
)
ylab_big_left_kwargs = dict(
x=-0.2,
fontsize=fs['lab_tex'],
ha='center',
va='bottom'
)
ylab_big_right_kwargs = dict(
x=1.2,
fontsize=fs['lab_tex'],
ha='center',
va='top'
)
ylab_snip_kwargs = dict(
x=0,
fontsize=fs['lab_tex'],
@@ -152,12 +167,6 @@ ylab_snip_kwargs = dict(
ha='left',
va='center',
)
ylab_big_kwargs = dict(
x=0,
fontsize=fs['lab_tex'],
ha='center',
va='top',
)
yloc = dict(
env=1000,
log=40,
@@ -233,7 +242,7 @@ leg_kwargs = dict(
),
borderpad=0,
borderaxespad=0,
handlelength=1,
handlelength=0.5,
columnspacing=1,
)
diag_kwargs = dict(
@@ -287,11 +296,7 @@ noise_data, _ = load_data(data_path.replace('pure', 'noise'), **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']
if compute_ratios:
# Relate pure-song measures to near-zero scale:
pure_data['measure_env'] /= pure_data['measure_env'][1]
pure_data['measure_log'] /= pure_data['measure_log'][1]
pure_data['measure_inv'] /= pure_data['measure_inv'][1]
if relate_to_noise:
# Relate noise-song measures to zero scale:
noise_data['measure_env'] /= noise_data['measure_env'][0]
noise_data['measure_log'] /= noise_data['measure_log'][0]
@@ -354,8 +359,10 @@ big_axes = np.zeros((big_grid.ncols,), dtype=object)
for i, scales in enumerate([pure_scales, noise_scales, noise_scales]):
ax = big_subfig.add_subplot(big_grid[0, i])
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.xaxis.set_major_locator(plt.LogLocator(base=10, subs=[1]))
ax.set_aspect(**anchor_kwargs)
if i in [0, 1]:
ax.set_ylim(scales[0], scales[-1])
@@ -365,10 +372,19 @@ for i, scales in enumerate([pure_scales, noise_scales, noise_scales]):
ax.set_aspect('auto', adjustable='box', anchor=(0.5, 0.5))
ax.set_position([pos_auto[0], pos_equal[1], pos_auto[2], pos_equal[3]])
ax.set_ylim(0.9, 30)
if i == 1:
hide_ticks(ax, 'left')
big_axes[i] = ax
ylabel(big_axes[0], ylabels['big'], transform=big_subfig.transSubfigure, **ylab_big_kwargs)
shift_subplot(big_axes[0], dx=big_col_shift)
ylabel(big_axes[0], ylabels['big_pure'], transform=big_axes[0].transAxes, **ylab_big_left_kwargs)
ylabel(big_axes[1], ylabels['big_noise'], transform=big_axes[1].transAxes, **ylab_big_left_kwargs)
big_twin = big_axes[0].twinx()
hide_axis(big_twin, 'left')
big_twin.spines['right'].set_visible(True)
big_twin.set_position(big_axes[0].get_position().bounds)
big_twin.set_ylim(scales[0], scales[-1])
big_twin.set_yscale('symlog', linthresh=scales[1], linscale=0.5)
ylabel(big_twin, ylabels['big_log'], transform=big_twin.transAxes, **ylab_big_right_kwargs)
color_axis(big_axes[0], colors['env'], side='left')
color_axis(big_twin, colors['log'], side='right')
super_xlabel(xlabels['big'], big_subfig, big_axes[0], big_axes[-1], **xlab_big_kwargs)
letter_subplots(big_axes, 'cde', **letter_big_kwargs)

View File

@@ -65,7 +65,7 @@ mean_colors = {
'Pseudochorthippus_parallelus': (0,) * 3,
}
xlab = 'scale $\\alpha$'
ylab = '$\\sigma_{\\alpha}\\,/\\,\\sigma_{\\eta}$'
ylab = '$\\sigma_{\\text{adapt}}\\,/\\,\\sigma_{\\eta}$'
xlab_kwargs = dict(
y=0,
fontsize=16,

View File

@@ -0,0 +1,424 @@
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 misc_functions import shorten_species
from color_functions import load_colors
from plot_functions import hide_axis, shift_subplot, shift_subplot, ylimits,\
super_xlabel, ylabel, hide_ticks,\
plot_line, strip_zeros, time_bar,\
letter_subplot, letter_subplots, 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])
if j == 0:
shift_subplot(axes[i, j], dx=snip_col_shift)
[hide_axis(ax, 'left') for ax in axes[:, 2:].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_DJN_32-40s724ms-48s779ms'
data_path = search_files(target, excl='noise', dir='../data/inv/rect_lp/')[0]
save_path = '../figures/fig_invariance_rect_lp.pdf'
target_species = [
'Chorthippus_biguttulus',
'Chorthippus_mollis',
'Chrysochraon_dispar',
# 'Euchorthippus_declivus',
'Gomphocerippus_rufus',
'Omocestus_rufipes',
'Pseudochorthippus_parallelus',
]
stages = ['filt', 'env']
load_kwargs = dict(
files=stages,
keywords=['scales', 'cutoff', 'snip', 'measure']
)
# ANALYSIS SETTINGS:
relate_to_noise = True
exclude_zero = True
show_diag = True
snip_cutoff = np.array([np.nan, 2500, 250, 25])[2]
# GRAPH SETTINGS:
fig_kwargs = dict(
figsize=(32/2.54, 32/2.54),
)
super_grid_kwargs = dict(
nrows=3,
ncols=1,
wspace=0,
hspace=0,
left=0,
right=1,
bottom=0,
top=1,
height_ratios=[1, 1, 1]
)
subfig_specs = dict(
pure=(0, slice(None)),
noise=(1, slice(None)),
big=(2, slice(None)),
)
block_height = 0.8
edge_padding = 0.08
snip_col_shift = -0.05
pure_grid_kwargs = dict(
nrows=len(stages),
ncols=None,
wspace=0.1,
hspace=0.15,
left=0.08 - snip_col_shift,
right=0.95,
bottom=1 - block_height - edge_padding,
top=1 - edge_padding,
height_ratios=[1, 1]
)
noise_grid_kwargs = dict(
nrows=len(stages),
ncols=None,
wspace=pure_grid_kwargs['wspace'],
hspace=pure_grid_kwargs['hspace'],
left=pure_grid_kwargs['left'],
right=pure_grid_kwargs['right'],
bottom=edge_padding,
top=edge_padding + block_height,
height_ratios=[1, 1]
)
big_col_shift = -0.05
big_grid_kwargs = dict(
nrows=1,
ncols=3,
wspace=0.25,
hspace=0,
left=pure_grid_kwargs['left'] + snip_col_shift - big_col_shift,
right=pure_grid_kwargs['right'],
bottom=0.04,
top=1
)
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')
colors['raw'] = (0., 0., 0.,)
species_colors = load_colors('../data/species_colors.npz')
lw = dict(
snip=0.5,
big=3,
spec=2,
legend=5,
)
dash_cycle = 6 # points
ls_env = [
(0, np.array((0.2, 0.8)) * dash_cycle),
(0, np.array((0.6, 0.1, 0.2, 0.1)) * dash_cycle),
(0, np.array((0.5, 0.5)) * dash_cycle),
'solid',
] # [np.nan, 2500, 250, 25]
xlabels = dict(
big='scale $\\alpha$',
)
ylabels = dict(
raw='$x$',
filt='$x_{\\text{filt}}$',
env='$x_{\\text{env}}$',
big_pure='$\\sigma_x$',
big_noise='$\\sigma_x\\,/\\,\\sigma_{\\eta}$' if relate_to_noise else None,
)
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_pure_kwargs = dict(
x=0,
fontsize=fs['lab_tex'],
ha='center',
va='top',
)
ylab_noise_kwargs = dict(
y=0.5,
fontsize=fs['lab_tex'],
ha='center',
va='top',
)
ylim_zoom_factor = 0.03
yloc = dict(
filt=(3, 100),
env=(0.5, 30),
)
ypad = dict(
filt=0.05,
env=0.05,
)
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,
y=1,
ha='left',
va='bottom',
fontsize=fs['letter'],
)
bar_time = 5
bar_kwargs = dict(
dur=bar_time,
y0=-0.2,
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',
)
)
cutoff_leg_kwargs = dict(
ncols=1,
loc='upper left',
bbox_to_anchor=(0.05, 0.5, 0.5, 0.5),
frameon=False,
prop=dict(
size=14,
),
borderpad=0,
borderaxespad=0,
handletextpad=0.3
)
cutoff_leg_kwargs['handlelength'] = 2 * dash_cycle * lw['big'] / cutoff_leg_kwargs['prop']['size']
spec_leg_kwargs = dict(
ncols=2,
loc='lower center',
bbox_to_anchor=(0, 0, 1, 0.5),
frameon=False,
prop=dict(
size=13,
style='italic',
),
borderpad=0,
borderaxespad=0,
handlelength=0.75,
handletextpad=0.5,
columnspacing=1,
)
diag_kwargs = dict(
c=(0.3,) * 3,
lw=2,
ls='--',
zorder=1.9,
)
# PREPARATION:
species_measures = {}
for i, species in enumerate(target_species):
spec_path = search_files(species, incl=['noise', 'norm-base'], dir='../data/inv/rect_lp/condensed/')[0]
spec_data = dict(np.load(spec_path))
measure = spec_data['mean_env'].mean(axis=-1)
if exclude_zero:
measure = measure[spec_data['scales'] > 0, :]
species_measures[species] = measure
# EXECUTION:
print(f'Processing {data_path}')
# Load invariance data:
pure_data, config = load_data(data_path, **load_kwargs)
noise_data, _ = load_data(data_path.replace('pure', 'noise'), **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']
cutoff_ind = np.nonzero(pure_data['cutoffs'] == snip_cutoff)[0][0]
if relate_to_noise:
# Relate noise-song measures to zero scale:
noise_data['measure_filt'] /= noise_data['measure_filt'][0]
noise_data['measure_env'] /= noise_data['measure_env'][0]
if exclude_zero:
# Exclude zero scales:
inds = pure_scales > 0
pure_scales = pure_scales[inds]
pure_data['measure_filt'] = pure_data['measure_filt'][inds]
pure_data['measure_env'] = pure_data['measure_env'][inds]
inds = noise_scales > 0
noise_scales = noise_scales[inds]
noise_data['measure_filt'] = noise_data['measure_filt'][inds]
noise_data['measure_env'] = noise_data['measure_env'][inds]
symlog_kwargs = dict(linthresh=pure_scales[pure_scales > 0][0], linscale=0.5)
# 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 (ax1, ax2), stage in zip(pure_axes[:, :2], stages):
ax1.yaxis.set_major_locator(plt.MultipleLocator(yloc[stage][0]))
ax2.yaxis.set_major_locator(plt.MultipleLocator(yloc[stage][1]))
ylabel(ax1, 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)
# 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 (ax1, ax2), stage in zip(noise_axes[:, :2], stages):
ax1.yaxis.set_major_locator(plt.MultipleLocator(yloc[stage][0]))
ax2.yaxis.set_major_locator(plt.MultipleLocator(yloc[stage][1]))
ylabel(ax1, 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, 'b', ref=noise_title, **letter_snip_kwargs)
# 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.ncols,), dtype=object)
for i, scales in enumerate([pure_scales, noise_scales, noise_scales]):
ax = big_subfig.add_subplot(big_grid[0, i])
ax.set_xlim(scales[0], scales[-1])
ax.set_ylim(scales[0], scales[-1])
ax.set_xscale('symlog', **symlog_kwargs)
ax.set_yscale('symlog', **symlog_kwargs)
ax.set_aspect(**anchor_kwargs)
if i in [0, 1]:
ax.set_ylim(scales[0], scales[-1])
pos_equal = ax.get_position().bounds
else:
pos_auto = list(ax.get_position().bounds)
ax.set_aspect('auto', adjustable='box', anchor=(0.5, 0.5))
ax.set_position([pos_auto[0], pos_equal[1], pos_auto[2], pos_equal[3]])
ax.set_ylim(0.1, 100)
big_axes[i] = ax
shift_subplot(big_axes[0], dx=big_col_shift)
ylabel(big_axes[0], ylabels['big_pure'], transform=big_subfig.transSubfigure, **ylab_pure_kwargs)
ylabel(big_axes[1], ylabels['big_noise'], transform=big_axes[1].transAxes, **ylab_noise_kwargs,
x=(big_subfig.transSubfigure + big_axes[0].transAxes.inverted()).transform((ylab_pure_kwargs['x'], 0))[0])
super_xlabel(xlabels['big'], big_subfig, big_axes[0], big_axes[-1], **xlab_big_kwargs)
letter_subplots(big_axes, 'cde', **letter_big_kwargs)
# Plot pure-song filtered snippets:
handle = plot_snippets(pure_axes[0, :], t_full, pure_data['snip_filt'],
c=colors['filt'], lw=lw['snip'], ypad=ypad['filt'])
# Plot pure-song envelope snippets:
plot_snippets(pure_axes[1, :], t_full, pure_data['snip_env'][..., cutoff_ind],
ymin=0, c=colors['env'], lw=lw['snip'], ypad=ypad['env'])
# Plot noise-song filtered snippets:
handle = plot_snippets(noise_axes[0, :], t_full, noise_data['snip_filt'], ypad=ypad['filt'],
*pure_axes[0, 0].get_ylim(), c=colors['filt'], lw=lw['snip'])
# Plot noise-song envelope snippets:
plot_snippets(noise_axes[1, :], t_full, noise_data['snip_env'][..., cutoff_ind],
*pure_axes[1, 0].get_ylim(), c=colors['env'], lw=lw['snip'])
# Zoom into first filtered snippet:
# ylim_zoom = np.array(noise_axes[0, -1].get_ylim()) * ylim_zoom_factor
# noise_axes[0, 0].set_ylim(*ylim_zoom)
ylim_zoom = ylimits(noise_data['snip_filt'][:, 0], noise_axes[0, 0], pad=ypad['filt'])
pure_axes[0, 0].set_ylim(*ylim_zoom)
# Zoom into first envelope snippet:
# ylim_zoom = np.array(noise_axes[1, -1].get_ylim()) * ylim_zoom_factor
# noise_axes[1, 0].set_ylim(*ylim_zoom)
ylim_zoom = ylimits(noise_data['snip_env'][:, 0, cutoff_ind], noise_axes[1, 0], minval=0, pad=ypad['env'])
pure_axes[1, 0].set_ylim(*ylim_zoom)
# Indicate time scale:
time_bar(noise_axes[-1, -1], **bar_kwargs)
# Plot pure-song measures (ideal):
big_axes[0].plot(pure_scales, pure_data['measure_filt'], c=colors['filt'], lw=lw['big'])
handles = big_axes[0].plot(pure_scales, pure_data['measure_env'], c=colors['env'], lw=lw['big'])
[handle.set_ls(ls) for handle, ls in zip(handles, ls_env)]
# Plot noise-song measures (limited):
big_axes[1].plot(noise_scales, noise_data['measure_filt'], c=colors['filt'], lw=lw['big'])
handles = big_axes[1].plot(noise_scales, noise_data['measure_env'], c=colors['env'], lw=lw['big'])
[handle.set_ls(ls) for handle, ls in zip(handles, ls_env)]
# Add proxy legend:
proxy_handles = []
for i, cutoff in enumerate(pure_data['cutoffs']):
label = '$\\text{unfiltered}$' if np.isnan(cutoff) else f'${int(cutoff)}\\,\\text{{Hz}}$'
proxy_handles.append(big_axes[0].plot([], [], c=colors['env'], lw=lw['big'],
ls=ls_env[i], label=label)[0])
big_axes[0].legend(handles=proxy_handles, **cutoff_leg_kwargs)
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)
# Plot species-specific noise-song invariance curves:
leg_handles = []
for i, (species, measure) in enumerate(species_measures.items()):
handles = big_axes[2].plot(noise_scales, measure, label=shorten_species(species),
c=species_colors[species], lw=lw['spec'])
[handle.set_ls(ls) for handle, ls in zip(handles, ls_env)]
leg_handles.append(handles[-1])
legend = big_axes[2].legend(handles=leg_handles, **spec_leg_kwargs)
[h.set_lw(lw['legend']) for h in legend.legend_handles]
if save_path is not None:
fig.savefig(save_path, bbox_inches='tight')
plt.show()
print('Done.')
embed()

View File

@@ -0,0 +1,159 @@
import plotstyle_plt
import numpy as np
import matplotlib.pyplot as plt
from thunderhopper.filetools import search_files
from thunderhopper.modeltools import load_data
from plot_functions import ylabel, super_xlabel, super_ylabel, title_subplot, time_bar
from color_functions import load_colors
from misc_functions import shorten_species
from IPython import embed
# GENERAL SETTINGS:
target_species = [
'Chorthippus_biguttulus',
'Chorthippus_mollis',
'Chrysochraon_dispar',
# 'Euchorthippus_declivus',
'Gomphocerippus_rufus',
'Omocestus_rufipes',
'Pseudochorthippus_parallelus',
]
data_path = '../data/inv/rect_lp/condensed/'
save_path = '../figures/fig_invariance_rect-lp_appendix.pdf'
# ANALYSIS SETTINGS:
relate_to_noise = True
exclude_zero = True
cutoffs = np.array([np.nan, 2500, 250, 25])
search_kwargs = dict(
incl=['noise', 'norm-base' if relate_to_noise else 'unnormed'],
dir=data_path,
)
# GRAPH SETTINGS:
fig_kwargs = dict(
figsize=(32/2.54, 16/2.54),
nrows=cutoffs.size,
ncols=len(target_species),
sharex=True,
sharey=True,
gridspec_kw=dict(
wspace=0.4,
hspace=0.2,
left=0.12,
right=0.98,
bottom=0.1,
top=0.95,
)
)
# PLOT SETTINGS:
species_colors = load_colors('../data/species_colors.npz')
line_kwargs = dict(
lw=2,
alpha=0.5,
zorder=2,
)
fill_kwargs = dict(
alpha=0.3,
zorder=1,
)
mean_kwargs = dict(
lw=2,
alpha=1,
zorder=3,
ls='--'
)
mean_colors = {
'Chorthippus_biguttulus': (1,) * 3,
'Chorthippus_mollis': (0,) * 3,
'Chrysochraon_dispar': (0,) * 3,
'Euchorthippus_declivus': (0,) * 3,
'Gomphocerippus_rufus': (0,) * 3,
'Omocestus_rufipes': (0,) * 3,
'Pseudochorthippus_parallelus': (1,) * 3,
}
xlab = 'scale $\\alpha$'
ylabs = ['$\\text{unfiltered}$'] + [f'${int(cutoff)}\\,\\text{{Hz}}$' for cutoff in cutoffs[1:]]
super_ylab = '$\\sigma_{\\text{env}}\\,/\\,\\sigma_{\\eta}$' if relate_to_noise else '$\\sigma_{\\text{env}}$'
xlab_kwargs = dict(
y=0,
fontsize=16,
ha='center',
va='bottom',
)
ylab_kwargs = dict(
x=0.05,
fontsize=16,
ha='center',
va='top',
)
ylab_super_kwargs = dict(
x=0,
fontsize=20,
ha='left',
va='center',
)
title_kwargs = dict(
x=0.5,
yref=0.99,
ha='center',
va='top',
fontsize=16,
fontstyle='italic',
)
letter_kwargs = dict(
x=0.005,
y=0.99,
fontsize=22,
ha='left',
va='top',
)
# Prepare graph:
fig, axes = plt.subplots(**fig_kwargs)
[ylabel(ax, lab, transform=fig.transFigure, **ylab_kwargs) for ax, lab in zip(axes[:, 0], ylabs)]
super_xlabel(xlab, fig, axes[-1, 0], axes[-1, -1], **xlab_kwargs)
super_ylabel(super_ylab, fig, axes[0, 0], axes[-1, 0], **ylab_super_kwargs)
# Run through species:
for i, (species, spec_axes) in enumerate(zip(target_species, axes.T)):
title_subplot(spec_axes[0], shorten_species(species), ref=fig, **title_kwargs)
# Load species data:
path = search_files(species, **search_kwargs)[0]
data, config = load_data(path, files=['scales', 'mean_env', 'sd_env'])
scales = data['scales']
means = data['mean_env']
sds = data['sd_env']
if exclude_zero:
# Exclude zero scale:
inds = scales > 0
scales = scales[inds]
means = means[inds, ...]
sds = sds[inds, ...]
# Run through cutoffs:
for j, ax in enumerate(spec_axes):
# Plot recording-specific traces:
for k in range(means.shape[-1]):
ax.plot(scales, means[:, j, k], c=species_colors[species], **line_kwargs)
spread = (means[:, j, k] - sds[:, j, k], means[:, j, k] + sds[:, j, k])
ax.fill_between(scales, *spread, color=species_colors[species], **fill_kwargs)
# Plot cutoff-specific mean trace:
ax.plot(scales, means[:, j, :].mean(axis=-1), c=mean_colors[species], **mean_kwargs)
# Posthocs:
sylog_kwargs = dict(linthresh=scales[scales > 0][0], linscale=0.5)
axes[0, 0].set_xscale('symlog', **sylog_kwargs)
axes[0, 0].set_yscale('symlog', **sylog_kwargs)
axes[0, 0].set_xlim(scales[0], scales[-1])
axes[0, 0].set_ylim(0.9, scales[-1])
axes[0, 0].xaxis.set_major_locator(plt.LogLocator(base=10, subs=[1]))
# Save graph:
fig.savefig(save_path)
plt.show()

View File

@@ -98,7 +98,7 @@ snip_grid_kwargs = dict(
ncols=None,
wspace=0.3,
hspace=0,
left=0.25,
left=0.2 - snip_col_shift,
right=0.93,
bottom=0.15,
top=0.95,

View File

@@ -1,8 +1,7 @@
import plotstyle_plt
import numpy as np
import matplotlib.pyplot as plt
from thunderhopper.modeltools import load_data
from thunderhopper.filetools import search_files, crop_paths
from scipy.stats import norm
from plot_functions import xlabel, ylabel
from IPython import embed
@@ -26,10 +25,22 @@ fig_kwargs = dict(
)
)
line_kwargs = dict(
color='black',
c='black',
lw=1,
alpha=0.5,
)
fit_kwargs = dict(
c='red',
lw=3,
ls='--',
)
grid_line_kwargs = dict(
visible=True,
which='major',
axis='both',
color='k',
lw=0.5,
)
xlab = '$\\text{multiple of }\\sigma_{k_i}$'
ylab = '$P\\,(c_i > \\Theta_i)$'
xlab_kwargs = dict(
@@ -50,15 +61,20 @@ data = dict(np.load(thresh_path))
factors = data['factors']
perc = data['percs']
# Get Gaussian CDF for reference:
fit = norm.cdf(factors, loc=0, scale=1)[::-1]
# Prepare graph:
fig, ax = plt.subplots(**fig_kwargs)
ax.grid(**grid_line_kwargs)
ax.set_xlim(factors[0], factors[-1])
ax.set_ylim(0, 1)
ax.set_ylim(-0.01, 1.01)
ylabel(ax, ylab, transform=fig.transFigure, **ylab_kwargs)
xlabel(ax, xlab, transform=fig.transFigure, **xlab_kwargs)
# Plotting:
ax.plot(factors, perc, **line_kwargs)
ax.plot(factors, fit, **fit_kwargs)
# Save figure:
fig.savefig(save_path)

View File

@@ -300,6 +300,12 @@ def set_clip_box(artist, ax, bounds=[[0, -0.05], [1, 1.05]]):
artist.set_clip_box(TransformedBbox(Bbox(bounds), ax.transAxes))
return None
def color_axis(ax, color, axis='y', side='left'):
ax.spines[side].set_color(color)
ax.tick_params(colors=color, axis=axis, which='both')
ax.yaxis.label.set_color(color)
return None
def plot_dist_shifted(ax, data, axis, pdf=None, sigma=0.1, which='x',
base=None, cap=None, add_pdf=False, shifted=False, **kwargs):
if pdf is None:

View File

@@ -7,16 +7,17 @@ from IPython import embed
# GENERAL SETTINGS:
example_file = 'Omocestus_rufipes_DJN_32-40s724ms-48s779ms'
data_paths = search_files('*', excl='noise', dir='../data/processed/')
search_target = ['*', example_file][0]
data_paths = search_files(search_target, excl='noise', dir='../data/processed/')
noise_path = '../data/processed/white_noise_sd-1.npz'
save_path = '../data/inv/rect_lp/'
# ANALYSIS SETTINGS:
mode = ['pure', 'noise'][1]
example_scales = np.array([0.1, 1, 10, 30, 100, 300])
scales = np.geomspace(0.01, 10000, 1000)
example_scales = np.array([0.1, 0.3, 1, 3, 10])
scales = np.geomspace(0.01, 100, 1000)
scales = np.unique(np.concatenate(([0], scales, example_scales)))
cutoffs = np.array([np.nan, 125, 250, 500])
cutoffs = np.array([np.nan, 2500, 250, 25])
# PREPARATION:
if mode == 'noise':