In [25]:
def plotband(x, y, ups, downs, color='#0067ea', alpha=.25, **kwargs):
"""
plots a line surrounded by a ribbon of the same color, but semi-transparent
:args:
x (N-by-1): positions on horizontal axis
y (N-by-1): corresponding vertical values of the (center) line
ups (N-by-1): upper edge of the ribbon
downs (N-by-1): lower edge of the ribbon
:returns:
[line, patch] returns of underlying "plot" and "fill_between" function
"""
pt1 = plot(x, y, color, **kwargs )
pt2 = fill_between(xdat, ups, downs, color='None', facecolor=color, lw=0, alpha=alpha)
return [pt1, pt2]
In [26]:
figure()
xdat = arange(10)/5.
ydat = xdat**2
plotband(xdat, ydat, ydat+.5, ydat-.7, linestyle='--')
Out[26]:
In [1]:
%load_ext cythonmagic
In [40]:
%%cython -lm
import numpy as np
cimport numpy as np
#from libc.math cimport sqrt # much, much faster than np.sqrt
from cpython cimport bool
def find_first(np.ndarray[np.float_t, ndim=1] data, double value):
"""
finds the index of the first elem in data that is larger than value
:args:
data (1d numpy array): array to be searched
value (float): value for comparison
:returns:
idx (int): the index of the first elem in data that is > than value
"""
cdef int ii
for ii in range(data.shape[0]):
if data[ii] > value:
return ii
return ii
def find_first_sorted(np.ndarray[np.float_t, ndim=1] data, double value):
"""
finds the index of the first elem in data that is larger than value
it is assumed that data is sorted
:args:
data (1d numpy array): array to be searched
value (float): value for comparison
:returns:
idx (int): the index of the first elem in data that is > than value
"""
cdef int ii
cdef bool is_larger = True
ii = data.shape[0] - 1
while data[ii] > value:
ii = ii//2
if ii == 1:
break
while data[ii] > value:
ii -= 1
if ii == 0:
break
return ii
In [11]:
tst = arange(1000, dtype=float)
In [26]:
%timeit find_first(tst, 5.)
In [19]:
%timeit find(tst > 500.)[0]
In [29]:
%timeit idxe = find_first_sorted(-tst, -5.)
In [39]:
idxe = find_first_sorted(tst, -2)
print idxe
In [36]:
-tst[999] > -5
Out[36]:
In [ ]: