Skip to content

Instantly share code, notes, and snippets.

@cwindolf
cwindolf / ipygif.py
Last active October 11, 2021 15:59
Quickly animate numpy arrays in Jupyter
import tempfile
import imageio
from IPython.display import Image
def ipygif(z, fps=16, width=200, height=200):
f = tempfile.NamedTemporaryFile(prefix="ipygif", suffix=".gif")
z = z - z.min()
z *= 255.0 / z.max()
imageio.mimwrite(f.name, z.astype(np.uint8), fps=fps)
return Image(filename=f.name, embed=True, width=width, height=height)
@cwindolf
cwindolf / modified_mandel_betensky.py
Last active October 13, 2021 17:32
Modified Mandel-Betensky simultaneous nonparametric confidence interval
"""
Implements the nonparametric simultaneous confidence interval described
in Gao et al. [1], which modifies the Mandel-Betensky simultaneous CI [2]
such that it is admissible. Notation in the code below comes from [1].
Takes as input an array of bootstrap samples / replicates, returns lower
and upper bounds at 1-alpha confidence.
[1]: https://www.mdpi.com/2073-8994/13/7/1212
[2]: https://pubmed.ncbi.nlm.nih.gov/26452746/
@cwindolf
cwindolf / triginterp.py
Created November 2, 2021 15:27
Trigonometric interpolation (quadratic Wikipedia algorithm, supports nonuniform input/output domains)
import numpy as np
from .triginterp_inner import triginterp_inner
def triginterp(x, y, xi):
"""Trigonometric interpolation with zero-padding (lol, not periodic). Easy to change."""
P = np.zeros_like(xi, dtype=np.float64)
triginterp_inner(
x.astype(np.float64), y.astype(np.float64), xi.astype(np.float64), P
)
@cwindolf
cwindolf / translate_torch.py
Last active November 24, 2021 15:26
Translate a batch of images in PyTorch
import torch
import torch.nn.functional as F
def translate(input, shifts, mode='bilinear', padding_mode='zeros'):
"""Translate a batch of images by a batch of xy shifts
Arguments
---------
input : torch.Tensor NCHW
@cwindolf
cwindolf / cluster_scatter.py
Last active March 9, 2022 17:43
Categorical scatterplot with Gaussian contours
# adapted from https://matplotlib.org/3.1.1/gallery/statistics/confidence_ellipse.html
import numpy as np
import matplotlib.pyplot as plt
import colorcet
from matplotlib.patches import Ellipse
import matplotlib.transforms as transforms
def cluster_scatter(xs, ys, ids, ax=None, n_std=2.0):
ax = ax or plt.gca()
@cwindolf
cwindolf / cmdstanpy_helpers.py
Created January 25, 2022 21:30
CmdStanPy helpers
from pathlib import Path
import cmdstanpy
import ujson
def stanc(name, code, workdir=".stan"):
Path(workdir).mkdir(exist_ok=True)
path = Path(workdir) / f"{name}.stan"
with open(path, "w") as f:
f.write(code)
model = cmdstanpy.CmdStanModel(stan_file=path, stanc_options={'warn-pedantic': True})
def tukey_scatter(x, y, iqrs=1.5, ax=None, **kwargs):
ax = ax or plt.gca()
x_25, x_75 = np.percentile(x, [25, 75])
x_iqr = x_75 - x_25
y_25, y_75 = np.percentile(x, [25, 75])
y_iqr = y_75 - y_25
inliers = np.flatnonzero(
(x_25 - iqrs * x_iqr < x)
& (x < x_75 + iqrs * x_iqr)
& (y_25 - iqrs * y_iqr < y)
def regline(x, y, ax=None, **kwargs):
b = ((x - x.mean()) * (y - y.mean())).sum() / np.square(x - x.mean()).sum()
a = y.mean() - b * x.mean()
x0, x1 = ax.get_xlim()
r = np.corrcoef(x, y)[0, 1]
ax.plot([x0, x1], [a + b * x0, a + b * x1], lw=1)
ax.text(
0.1,
0.9,
f"$\\rho={r:.2f}$",
@cwindolf
cwindolf / normxcorr1d.py
Last active February 3, 2023 16:20
1D optionally normalized, optionally weighted, optionally centered cross-correlation in PyTorch (+ SciPy fallback), with API like F.conv1d
try:
import torch
import torch.nn.functional as F
HAVE_TORCH = True
except ImportError:
HAVE_TORCH = False
def normxcorr1d(
template,
x,
@cwindolf
cwindolf / inline_labels.py
Last active December 6, 2022 22:59
Inline {x,y}axis labels in Matplotlib
# https://stackoverflow.com/a/74706214/3979938
from matplotlib.transforms import offset_copy
def inline_xlabel(ax, label):
t = offset_copy(
ax.transAxes,
y=-(ax.xaxis.get_tick_padding() + ax.xaxis.get_tick_space()),
fig=fig,
units='points'
)