Skip to content

Instantly share code, notes, and snippets.

View syrte's full-sized avatar

Zhaozhou Li syrte

View GitHub Profile
@syrte
syrte / mid.py
Created March 23, 2016 01:54
Return mean value of adjacent member of an array. Useful for plotting bin counts.
def mid(x, base=None):
'''Return mean value of adjacent member of an array.
Useful for plotting bin counts.
'''
if base is None:
x = np.asarray(x)
return (x[1:] + x[:-1])/2.
elif base == 'log':
return np.exp(mid(np.log(x)))
elif base == 'exp':
@syrte
syrte / EqualGridInterpolator.py
Last active July 2, 2016 02:17
Interpolation on a equal spaced regular grid in arbitrary dimensions. Fock from https://github.com/JohannesBuchner/regulargrid
import numpy as np
import scipy.ndimage as ndimage
__all__ = ["EqualGridInterpolator"]
class EqualGridInterpolator(object):
"""
Interpolation on a equal spaced regular grid in arbitrary dimensions.
Fock from https://github.com/JohannesBuchner/regulargrid
@syrte
syrte / siground.py
Last active July 5, 2016 16:31
print required significant figures.
def siground(x, n):
from math import log10, floor
x, n = float(x), int(n)
assert n > 0
if x == 0:
return ("%%.%if" % (n - 1)) % x
m = 10 ** floor(log10(abs(x)))
x = round(x / m, n - 1) * m
p = floor(log10(abs(x)))
def findroot(y0, x, y):
"""
y0: scalar
x: 1D array
y: function or 1D array
"""
import numpy as np
x = np.asarray(x)
assert x.ndim == 1
def quantile(a, q=None, nsig=None, weights=None, sorted=False, nmin=0):
'''
nmin: int
Set `nmin` if you want a more reliable result.
Return `nan` when the tail probability is less than `nmin/a.size`.
'''
import numpy as np
from scipy.stats import norm
a = np.asarray(a)
@syrte
syrte / binstats.py
Last active July 11, 2016 02:26
nd version
from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
from collections import namedtuple
BinStats = namedtuple('BinStats',
('stats', 'bin_edges', 'bin_count'))
import numpy as np
from matplotlib import pyplot as plt
def hist_stats(x, y, bins=10, func=np.mean, nmin=None, **kwds):
"""
x = np.random.rand(1000)
hist_stats(x, x, func=lambda x:np.percentile(x, [15,50,85]),
ls=['--', '-', '--'], lw=[1, 2, 1])
"""
stats, edges, count = binstats(x, y, bins=bins, func=func, nmin=nmin)
from matplotlib import pyplot as plt
def twin(show="xy", ax=None):
"""
Call signature::
ax = twin()
create a twin of Axes for generating a plot with a shared
x-axis and y-axis.
The x-axis (y-axis) of ax will have ticks on bottom (left)
@syrte
syrte / hide_cell_number.yaml
Created August 2, 2016 05:35
hide_cell_number
Type: IPython Notebook Extension
Compatibility: 3.x 4.x
Main: main.js
Name: Hide cell number
Description: "toggle number of all cells"
__all__ = ['recordtype']
import sys
from textwrap import dedent
from keyword import iskeyword
def recordtype(typename, field_names, verbose=False, **default_kwds):
'''Returns a new class with named fields.