Skip to content
28 changes: 28 additions & 0 deletions docs/source/distributions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,34 @@ Empirical Distributions
StepFunction
monotone_fn_inverter

Count Distributions
-------------------

The `discrete` module contains classes for count distributions that are based
on discretizing a continouus distribution, and specific count distributions
that are not available in scipy.distributions like generalized poisson and
zero-inflated count models.

The latter are mainly in support of the corresponding models in
`statsmodels.discrete`. Some methods are not specifically implemented and will
use potentially slow inherited generic methods.

.. module:: statsmodels.distributions.discrete
:synopsis: Support for count distributions

.. currentmodule:: statsmodels.distributions.discrete

.. autosummary::
:toctree: generated/

DiscretizedCount
DiscretizedModel
genpoisson_p
zigenpoisson
zinegbin
zipoisson


Distribution Extras
-------------------

Expand Down
8 changes: 6 additions & 2 deletions statsmodels/base/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -2281,7 +2281,9 @@ def df_modelwc(self):
# collect different ways of defining the number of parameters, used for
# aic, bic
if hasattr(self, 'df_model'):
if hasattr(self, 'hasconst'):
if hasattr(self, 'k_constant'):
hasconst = self.k_constant
elif hasattr(self, 'hasconst'):
hasconst = self.hasconst
else:
# default assumption
Expand Down Expand Up @@ -2396,8 +2398,10 @@ def bootstrap(self, nrep=100, method='nm', disp=0, store=1):
exog_resamp = self.exog[rvsind, :]
else:
exog_resamp = None
# build auxiliary model and fit
init_kwds = self.model._get_init_kwds()
fitmod = self.model.__class__(self.endog[rvsind],
exog=exog_resamp)
exog=exog_resamp, **init_kwds)
if hascloneattr:
for attr in self.model.cloneattr:
setattr(fitmod, attr, getattr(self.model, attr))
Expand Down
219 changes: 219 additions & 0 deletions statsmodels/distributions/discrete.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from scipy.special import gammaln
from scipy._lib._util import _lazywhere

from statsmodels.base.model import GenericLikelihoodModel


class genpoisson_p_gen(rv_discrete):
'''Generalized Poisson distribution
Expand Down Expand Up @@ -148,3 +150,220 @@ def convert_params(self, mu, alpha, p):

zinegbin = zinegativebinomial_gen(name='zinegbin',
longname='Zero Inflated Generalized Negative Binomial')


class DiscretizedCount(rv_discrete):
"""Count distribution based on discretized distribution

Parameters
----------
distr : distribution instance
d_offset : float
Offset for integer interval, default is zero.
The discrete random variable is ``y = floor(x + offset)`` where x is
the continuous random variable.
Warning: not verified for all methods.
add_scale : bool
If True (default), then the scale of the base distribution is added
as parameter for the discrete distribution. The scale parameter is in
the last position.
kwds : keyword arguments
The extra keyword arguments are used delegated to the ``__init__`` of
the super class.
Their usage has not been checked, e.g. currently the support of the
distribution is assumed to be all non-negative integers.

Notes
-----
`loc` argument is currently not supported, scale is not available for
discrete distributions in scipy. The scale parameter of the underlying
continuous distribution is the last shape parameter in this
DiscretizedCount distribution if ``add_scale`` is True.

The implementation was based mainly on [1]_ and [2]_. However, many new
discrete distributions have been developed based on the approach that we
use here. Note, that in many cases authors reparameterize the distribution,
while this class inherits the parameterization from the underlying
continuous distribution.

References
----------
.. [1] Chakraborty, Subrata, and Dhrubajyoti Chakravarty. "Discrete gamma
distributions: Properties and parameter estimations." Communications in
Statistics-Theory and Methods 41, no. 18 (2012): 3301-3324.

.. [2] Alzaatreh, Ayman, Carl Lee, and Felix Famoye. 2012. “On the Discrete
Analogues of Continuous Distributions.” Statistical Methodology 9 (6):
589–603.


"""

def __new__(cls, *args, **kwds):
# rv_discrete.__new__ does not allow `kwds`, skip it
# only does dispatch to multinomial
return super(rv_discrete, cls).__new__(cls)

def __init__(self, distr, d_offset=0, add_scale=True, **kwds):
# kwds are extras in rv_discrete
self.distr = distr
self.d_offset = d_offset
self._ctor_param = distr._ctor_param
self.add_scale = add_scale
if distr.shapes is not None:
self.k_shapes = len(distr.shapes.split(","))
if add_scale:
kwds.update({"shapes": distr.shapes + ", s"})
self.k_shapes += 1
else:
# no shape parameters in underlying distribution
if add_scale:
kwds.update({"shapes": "s"})
self.k_shapes = 1
else:
self.k_shapes = 0

super().__init__(**kwds)

def _updated_ctor_param(self):
dic = super()._updated_ctor_param()
dic["distr"] = self.distr
return dic

def _unpack_args(self, args):
if self.add_scale:
scale = args[-1]
args = args[:-1]
else:
scale = 1
return args, scale

def _rvs(self, *args, size=None, random_state=None):
args, scale = self._unpack_args(args)
if size is None:
size = getattr(self, "_size", 1)
rv = np.trunc(self.distr.rvs(*args, scale=scale, size=size,
random_state=random_state) +
self.d_offset)
return rv

def _pmf(self, x, *args):
distr = self.distr
if self.d_offset != 0:
x = x + self.d_offset

args, scale = self._unpack_args(args)

p = (distr.sf(x, *args, scale=scale) -
distr.sf(x + 1, *args, scale=scale))
return p

def _cdf(self, x, *args):
distr = self.distr
args, scale = self._unpack_args(args)
if self.d_offset != 0:
x = x + self.d_offset
p = distr.cdf(x + 1, *args, scale=scale)
return p

def _sf(self, x, *args):
distr = self.distr
args, scale = self._unpack_args(args)
if self.d_offset != 0:
x = x + self.d_offset
p = distr.sf(x + 1, *args, scale=scale)
return p

def _ppf(self, p, *args):
distr = self.distr
args, scale = self._unpack_args(args)

qc = distr.ppf(p, *args, scale=scale)
if self.d_offset != 0:
qc = qc + self.d_offset
q = np.floor(qc * (1 - 1e-15))
return q

def _isf(self, p, *args):
distr = self.distr
args, scale = self._unpack_args(args)

qc = distr.isf(p, *args, scale=scale)
if self.d_offset != 0:
qc = qc + self.d_offset
q = np.floor(qc * (1 - 1e-15))
return q


class DiscretizedModel(GenericLikelihoodModel):
"""experimental model to fit discretized distribution

Count models based on discretized distributions can be used to model
data that is under- or over-dispersed relative to Poisson or that has
heavier tails.

Parameters
----------
endog : array_like, 1-D
Univariate data for fitting the distribution.
exog : None
Explanatory variables are not supported. The ``exog`` argument is
only included for consistency in the signature across models.
distr : DiscretizedCount instance
(required) Instance of a DiscretizedCount distribution.

See Also
--------
DiscretizedCount

Examples
--------
>>> from scipy import stats
>>> from statsmodels.distributions.discrete import (
DiscretizedCount, DiscretizedModel)

>>> dd = DiscretizedCount(stats.gamma)
>>> mod = DiscretizedModel(y, distr=dd)
>>> res = mod.fit()
>>> probs = res.predict(which="probs", k_max=5)

"""
def __init__(self, endog, exog=None, distr=None):
if exog is not None:
raise ValueError("exog is not supported")

super().__init__(endog, exog, distr=distr)
self._init_keys.append('distr')
self.df_resid = len(endog) - distr.k_shapes
self.df_model = distr.k_shapes # no constant subtracted
self.k_constant = 0
self.nparams = distr.k_shapes # needed for start_params
self.start_params = 0.5 * np.ones(self.nparams)

def loglike(self, params):

# this does not allow exog yet,
# model `params` are also distribution `args`
# For regression model this needs to be replaced by a conversion method
args = params
ll = np.log(self.distr._pmf(self.endog, *args))
return ll.sum()

def predict(self, params, exog=None, which=None, k_max=20):

if exog is not None:
raise ValueError("exog is not supported")

args = params
if which == "probs":
pr = self.distr.pmf(np.arange(k_max), *args)
return pr
else:
raise ValueError('only which="probs" is currently implemented')

def get_distr(self, params):
"""frozen distribution instance of the discrete distribution.
"""
args = params
distr = self.distr(*args)
return distr
Loading