Skip to content

Instantly share code, notes, and snippets.

@cwindolf
cwindolf / matplotlib_preamble_sans.py
Last active September 22, 2023 16:51
Example matplotlib config with latex fonts
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
from matplotlib.markers import MarkerStyle
from matplotlib.transforms import offset_copy
from matplotlib.patches import Ellipse, Rectangle, ConnectionPatch
from matplotlib.lines import Line2D
from matplotlib.legend_handler import HandlerTuple
import contextlib
plt.rc("figure", dpi=300)
def runs_to_ranges(x, one_more=False):
ranges = []
cur = x[0]
b = x[0]
for a, b in zip(x, x[1:]):
assert b > a
if b - a == 1:
continue
else:
ranges.append(range(cur, a + 1 + one_more))
@cwindolf
cwindolf / matplotlib_contextmanagers.py
Created June 21, 2023 17:27
Matplotlib context manager helpers
import matplotlib.pyplot as plt
import contextlib
@contextlib.contextmanager
def subplots(*args, **kwargs):
fig, axes = plt.subplots(*args, **kwargs)
try:
yield fig, axes
finally:
plt.show()
@cwindolf
cwindolf / ppca.py
Last active April 11, 2024 15:18
Probabilistic PCA in PyTorch with missing data. See the very nice JMLR paper of Ilin and Raiko in 2010.
import torch
from torch import nn
from tqdm.auto import trange
class PPCA(nn.Module):
def __init__(self, d, c):
super().__init__()
self.d = d
self.c = c
@cwindolf
cwindolf / ciline.py
Created September 12, 2024 21:01
Plot moving means and standard deviations
def sliding_mean_and_stddev_interval(
axis, xs, ys, n_neighbors=30, linewidth=1, color="k", ci_alpha=0.25
):
"""Plot moving means and standard deviations"""
_1 = np.ones(2 * n_neighbors + 1)
_ys = np.nan_to_num(ys)
sliding_sum = correlate1d(_ys, _1, mode="constant")
sliding_N = correlate1d(np.isfinite(ys).astype(float), _1, mode="constant")
sliding_mean = sliding_sum / sliding_N
sliding_sumsq = correlate1d(_ys**2, _1, mode="constant")