Skip to content

Commit

Permalink
Merge pull request statsmodels#7385 from bashtage/use-scipy-lazywhere
Browse files Browse the repository at this point in the history
MAINT: Use scipy's lazywhere
  • Loading branch information
bashtage committed Mar 18, 2021
2 parents 6226369 + ed94c83 commit 42e377f
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 40 deletions.
34 changes: 0 additions & 34 deletions statsmodels/compat/scipy.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,37 +63,3 @@ def _valarray(shape, value=np.nan, typecode=None):
if not isinstance(out, np.ndarray):
out = np.asarray(out)
return out


def _lazywhere(cond, arrays, f, fillvalue=None, f2=None):
"""
np.where(cond, x, fillvalue) always evaluates x even where cond is False.
This one only evaluates f(arr1[cond], arr2[cond], ...).
For example,
>>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8])
>>> def f(a, b):
return a*b
>>> _lazywhere(a > 2, (a, b), f, np.nan)
array([ nan, nan, 21., 32.])
Notice it assumes that all `arrays` are of the same shape, or can be
broadcasted together.
"""
if fillvalue is None:
if f2 is None:
raise ValueError("One of (fillvalue, f2) must be given.")
else:
fillvalue = np.nan
else:
if f2 is not None:
raise ValueError("Only one of (fillvalue, f2) can be given.")

arrays = np.broadcast_arrays(*arrays)
temp = tuple(np.extract(cond, arr) for arr in arrays)
tcode = np.mintypecode([a.dtype.char for a in arrays])
out = _valarray(np.shape(arrays[0]), value=fillvalue, typecode=tcode)
np.place(out, cond, f(*temp))
if f2 is not None:
temp = tuple(np.extract(~cond, arr) for arr in arrays)
np.place(out, ~cond, f2(*temp))

return out
2 changes: 1 addition & 1 deletion statsmodels/distributions/discrete.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import numpy as np
from scipy.stats import rv_discrete, nbinom, poisson
from scipy.special import gammaln
from statsmodels.compat.scipy import _lazywhere
from scipy._lib._util import _lazywhere


class genpoisson_p_gen(rv_discrete):
Expand Down
10 changes: 5 additions & 5 deletions statsmodels/genmod/_tweedie_compound_poisson.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
insurance claims data: dispersion modelling. ASTIN Bulletin 32: 143–157
"""
import numpy as np
from scipy._lib._util import _lazywhere as lazywhere
from scipy._lib._util import _lazywhere
from scipy.special import gammaln


Expand Down Expand Up @@ -76,10 +76,10 @@ def density_otherwise(y, mu, p, phi):


def series_density(y, mu, p, phi):
density = lazywhere(np.array(y) > 0,
(y, mu, p, phi),
f=density_otherwise,
f2=density_at_zero)
density = _lazywhere(np.array(y) > 0,
(y, mu, p, phi),
f=density_otherwise,
f2=density_at_zero)
return density


Expand Down

0 comments on commit 42e377f

Please sign in to comment.