Skip to content

Instantly share code, notes, and snippets.

@dkirkby
dkirkby / Numpy array divide with zeros
Last active September 7, 2020 17:29
Ratio X/Y of numpy arrays with zeros in the output where Y=0.
# https://stackoverflow.com/a/37977222/4726728
# Requires numpy >= 1.7
c = np.divide(a, b, out=np.zeros_like(a), where=b!=0)
# Another method that maps all inexact values with finite ones.
# Unlike the method above, this also works inside @jax.jit
c = np.nan_to_num(a / b, posinf=0., neginf=0.)
@dkirkby
dkirkby / Draw ellipse
Last active August 9, 2019 17:03
Draw an ellipse starting from different parameterizations
# Given ellipticity parameters (e1, e2) and size s = det(Q)**(1/4)
# https://github.com/dkirkby/desietcimg/blob/master/desietcimg/plot.py
def draw_ellipse_se1e2(ax, x0, y0, s, g1, g2, nsigmas=1, **ellipseopts):
g = np.sqrt(g1 ** 2 + g2 ** 2)
if g > 1:
raise ValueError('g1 ** 2 + g2 ** 2 > 1')
center = np.array([x0, y0])
angle = np.rad2deg(0.5 * np.arctan2(g2, g1))
ratio = np.sqrt((1 + g) / (1 - g))
width = 2 * s * ratio * nsigmas
@dkirkby
dkirkby / downsample.py
Created August 1, 2019 15:27
Downsample a 2D image array
def downsample(data, downsampling, summary=np.sum, allow_trim=False):
"""Downsample a 2D array.
Parameters
----------
data : array
Two dimensional array of values to downsample.
downsampling : int
Downsampling factor to use along both dimensions. Must evenly divide the
data dimensions when allow_trim is False.
@dkirkby
dkirkby / cmd_line_script.py
Last active May 3, 2022 21:37
Skeleton command line script
'''
Save this file to scripts/myprog.py then add these lines to setup.py:
entry_points = {
'console_scripts': [
'myprog=fpoffline.scripts.myprog:main',
],
}
'''
import argparse
# See https://stackoverflow.com/questions/6910641/how-do-i-get-indices-of-n-maximum-values-in-a-numpy-array
# argpartition requires numpy >= 1.8.0
# See also http://seanlaw.github.io/2020/01/03/finding-top-or-bottom-k-in-a-numpy-array/
def argkmax1(a, k, axis=-1):
"""Return the indices of the k largest elements of a.
With k=1, this is identical to argmax except that it
returns an array of length 1 instead of a scalar.
"""
@dkirkby
dkirkby / jupyter notebook preamble
Last active February 17, 2021 19:07
Useful bits for a jupyter notebook preamble
%reload_ext autoreload
%autoreload 1
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# Modules imported by devpkg must also be listed here to get the same treatment.
%aimport devpkg
%aimport devpkg.util
# Get the latest name using tab completion or check sys.prefix from within jupyterhub
#module load python/3.8-anaconda-2020.11
module load python/3.9-anaconda-2021.11
# Create a new env. Only list the pkgs you need since they will be downloaded into ~/.conda/pkgs/
#conda create -n desi pip ipython jupyter ipykernel numpy scipy matplotlib pyyaml
conda create -n desi39 pip ipython jupyter ipykernel numpy scipy matplotlib pyyaml astropy pandas
# conda activate <env> *was* not supported at NERSC yet but is now
conda activate desi39
import time, sys
import IPython.display
class ProgressBar(object):
"""Replace existing contents of the current output cell with a progress bar.
"""
def __init__(self, maxval=1., label='Progress', width=40):
self.maxval = maxval
self.label = label
self.width = width
@dkirkby
dkirkby / Conda envs
Last active December 13, 2020 22:03
## DESI
conda create -n desi python=3.8 pip ipython jupyter jupyterlab ipykernel numpy scipy pandas matplotlib pyyaml requests psycopg2 astropy
conda activate desi
conda install -c conda-forge galsim fitsio
# Reuse the automatically selected color from a plot
line2d = plt.plot([0, 1], [0, 1], ':')
plt.scatter([0, 1], [0, 1], c=line2d[0].get_color())
# Reuse the automatically selected color from a scatter
pathcol = plt.scatter([0, 1], [0, 1])
plt.plot([0, 1], [0, 1], c=pathcol.get_fc()[0], ls=':')
# Use the j-th default color
c = plt.rcParams['axes.prop_cycle'].by_key()['color'][j]