code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
def deriv2(self, p): """ Second derivative of the log-complement transform link function Parameters ---------- p : array_like Mean parameters Returns ------- g''(p) : ndarray Second derivative of log-complement transform of x Notes ----- g''(x) = -(-1/(1 - x))^2 """ p = self._clean(p) return -1 * np.power(-1. / (1. - p), 2)
Second derivative of the log-complement transform link function Parameters ---------- p : array_like Mean parameters Returns ------- g''(p) : ndarray Second derivative of log-complement transform of x Notes ----- g''(x) = -(-1/(1 - x))^2
deriv2
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def inverse_deriv(self, z): """ Derivative of the inverse of the log-complement transform link function Parameters ---------- z : ndarray The inverse of the link function at `p` Returns ------- g^(-1)'(z) : ndarray The value of the derivative of the inverse of the log-complement function. """ return -np.exp(z)
Derivative of the inverse of the log-complement transform link function Parameters ---------- z : ndarray The inverse of the link function at `p` Returns ------- g^(-1)'(z) : ndarray The value of the derivative of the inverse of the log-complement function.
inverse_deriv
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def inverse_deriv2(self, z): """ Second derivative of the inverse link function g^(-1)(z). Parameters ---------- z : array_like The inverse of the link function at `p` Returns ------- g^(-1)''(z) : ndarray The value of the second derivative of the inverse of the log-complement function. """ return -np.exp(z)
Second derivative of the inverse link function g^(-1)(z). Parameters ---------- z : array_like The inverse of the link function at `p` Returns ------- g^(-1)''(z) : ndarray The value of the second derivative of the inverse of the log-complement function.
inverse_deriv2
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def __call__(self, p): """ CDF link function Parameters ---------- p : array_like Mean parameters Returns ------- z : ndarray (ppf) inverse of CDF transform of p Notes ----- g(`p`) = `dbn`.ppf(`p`) """ p = self._clean(p) return self.dbn.ppf(p)
CDF link function Parameters ---------- p : array_like Mean parameters Returns ------- z : ndarray (ppf) inverse of CDF transform of p Notes ----- g(`p`) = `dbn`.ppf(`p`)
__call__
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def inverse(self, z): """ The inverse of the CDF link Parameters ---------- z : array_like The value of the inverse of the link function at `p` Returns ------- p : ndarray Mean probabilities. The value of the inverse of CDF link of `z` Notes ----- g^(-1)(`z`) = `dbn`.cdf(`z`) """ return self.dbn.cdf(z)
The inverse of the CDF link Parameters ---------- z : array_like The value of the inverse of the link function at `p` Returns ------- p : ndarray Mean probabilities. The value of the inverse of CDF link of `z` Notes ----- g^(-1)(`z`) = `dbn`.cdf(`z`)
inverse
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def deriv(self, p): """ Derivative of CDF link Parameters ---------- p : array_like mean parameters Returns ------- g'(p) : ndarray The derivative of CDF transform at `p` Notes ----- g'(`p`) = 1./ `dbn`.pdf(`dbn`.ppf(`p`)) """ p = self._clean(p) return 1. / self.dbn.pdf(self.dbn.ppf(p))
Derivative of CDF link Parameters ---------- p : array_like mean parameters Returns ------- g'(p) : ndarray The derivative of CDF transform at `p` Notes ----- g'(`p`) = 1./ `dbn`.pdf(`dbn`.ppf(`p`))
deriv
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def deriv2(self, p): """ Second derivative of the link function g''(p) implemented through numerical differentiation """ p = self._clean(p) linpred = self.dbn.ppf(p) return - self.inverse_deriv2(linpred) / self.dbn.pdf(linpred) ** 3
Second derivative of the link function g''(p) implemented through numerical differentiation
deriv2
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def deriv2_numdiff(self, p): """ Second derivative of the link function g''(p) implemented through numerical differentiation """ from statsmodels.tools.numdiff import _approx_fprime_scalar p = np.atleast_1d(p) # Note: special function for norm.ppf does not support complex return _approx_fprime_scalar(p, self.deriv, centered=True)
Second derivative of the link function g''(p) implemented through numerical differentiation
deriv2_numdiff
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def inverse_deriv(self, z): """ Derivative of the inverse link function Parameters ---------- z : ndarray The inverse of the link function at `p` Returns ------- g^(-1)'(z) : ndarray The value of the derivative of the inverse of the logit function. This is just the pdf in a CDFLink, """ return self.dbn.pdf(z)
Derivative of the inverse link function Parameters ---------- z : ndarray The inverse of the link function at `p` Returns ------- g^(-1)'(z) : ndarray The value of the derivative of the inverse of the logit function. This is just the pdf in a CDFLink,
inverse_deriv
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def inverse_deriv2(self, z): """ Second derivative of the inverse link function g^(-1)(z). Parameters ---------- z : array_like `z` is usually the linear predictor for a GLM or GEE model. Returns ------- g^(-1)''(z) : ndarray The value of the second derivative of the inverse of the link function Notes ----- This method should be overwritten by subclasses. The inherited method is implemented through numerical differentiation. """ from statsmodels.tools.numdiff import _approx_fprime_scalar z = np.atleast_1d(z) # Note: special function for norm.ppf does not support complex return _approx_fprime_scalar(z, self.inverse_deriv, centered=True)
Second derivative of the inverse link function g^(-1)(z). Parameters ---------- z : array_like `z` is usually the linear predictor for a GLM or GEE model. Returns ------- g^(-1)''(z) : ndarray The value of the second derivative of the inverse of the link function Notes ----- This method should be overwritten by subclasses. The inherited method is implemented through numerical differentiation.
inverse_deriv2
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def inverse_deriv2(self, z): """ Second derivative of the inverse link function This is the derivative of the pdf in a CDFLink """ return - z * self.dbn.pdf(z)
Second derivative of the inverse link function This is the derivative of the pdf in a CDFLink
inverse_deriv2
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def deriv2(self, p): """ Second derivative of the link function g''(p) """ p = self._clean(p) linpred = self.dbn.ppf(p) return linpred / self.dbn.pdf(linpred) ** 2
Second derivative of the link function g''(p)
deriv2
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def deriv2(self, p): """ Second derivative of the Cauchy link function. Parameters ---------- p : array_like Probabilities Returns ------- g''(p) : ndarray Value of the second derivative of Cauchy link function at `p` """ p = self._clean(p) a = np.pi * (p - 0.5) d2 = 2 * np.pi ** 2 * np.sin(a) / np.cos(a) ** 3 return d2
Second derivative of the Cauchy link function. Parameters ---------- p : array_like Probabilities Returns ------- g''(p) : ndarray Value of the second derivative of Cauchy link function at `p`
deriv2
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def __call__(self, p): """ C-Log-Log transform link function Parameters ---------- p : ndarray Mean parameters Returns ------- z : ndarray The CLogLog transform of `p` Notes ----- g(p) = log(-log(1-p)) """ p = self._clean(p) return np.log(-np.log(1 - p))
C-Log-Log transform link function Parameters ---------- p : ndarray Mean parameters Returns ------- z : ndarray The CLogLog transform of `p` Notes ----- g(p) = log(-log(1-p))
__call__
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def inverse(self, z): """ Inverse of C-Log-Log transform link function Parameters ---------- z : array_like The value of the inverse of the CLogLog link function at `p` Returns ------- p : ndarray Mean parameters Notes ----- g^(-1)(`z`) = 1-exp(-exp(`z`)) """ return 1 - np.exp(-np.exp(z))
Inverse of C-Log-Log transform link function Parameters ---------- z : array_like The value of the inverse of the CLogLog link function at `p` Returns ------- p : ndarray Mean parameters Notes ----- g^(-1)(`z`) = 1-exp(-exp(`z`))
inverse
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def deriv(self, p): """ Derivative of C-Log-Log transform link function Parameters ---------- p : array_like Mean parameters Returns ------- g'(p) : ndarray The derivative of the CLogLog transform link function Notes ----- g'(p) = - 1 / ((p-1)*log(1-p)) """ p = self._clean(p) return 1. / ((p - 1) * (np.log(1 - p)))
Derivative of C-Log-Log transform link function Parameters ---------- p : array_like Mean parameters Returns ------- g'(p) : ndarray The derivative of the CLogLog transform link function Notes ----- g'(p) = - 1 / ((p-1)*log(1-p))
deriv
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def deriv2(self, p): """ Second derivative of the C-Log-Log ink function Parameters ---------- p : array_like Mean parameters Returns ------- g''(p) : ndarray The second derivative of the CLogLog link function """ p = self._clean(p) fl = np.log(1 - p) d2 = -1 / ((1 - p) ** 2 * fl) d2 *= 1 + 1 / fl return d2
Second derivative of the C-Log-Log ink function Parameters ---------- p : array_like Mean parameters Returns ------- g''(p) : ndarray The second derivative of the CLogLog link function
deriv2
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def inverse_deriv(self, z): """ Derivative of the inverse of the C-Log-Log transform link function Parameters ---------- z : array_like The value of the inverse of the CLogLog link function at `p` Returns ------- g^(-1)'(z) : ndarray The derivative of the inverse of the CLogLog link function """ return np.exp(z - np.exp(z))
Derivative of the inverse of the C-Log-Log transform link function Parameters ---------- z : array_like The value of the inverse of the CLogLog link function at `p` Returns ------- g^(-1)'(z) : ndarray The derivative of the inverse of the CLogLog link function
inverse_deriv
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def __call__(self, p): """ Log-Log transform link function Parameters ---------- p : ndarray Mean parameters Returns ------- z : ndarray The LogLog transform of `p` Notes ----- g(p) = -log(-log(p)) """ p = self._clean(p) return -np.log(-np.log(p))
Log-Log transform link function Parameters ---------- p : ndarray Mean parameters Returns ------- z : ndarray The LogLog transform of `p` Notes ----- g(p) = -log(-log(p))
__call__
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def inverse(self, z): """ Inverse of Log-Log transform link function Parameters ---------- z : array_like The value of the inverse of the LogLog link function at `p` Returns ------- p : ndarray Mean parameters Notes ----- g^(-1)(`z`) = exp(-exp(-`z`)) """ return np.exp(-np.exp(-z))
Inverse of Log-Log transform link function Parameters ---------- z : array_like The value of the inverse of the LogLog link function at `p` Returns ------- p : ndarray Mean parameters Notes ----- g^(-1)(`z`) = exp(-exp(-`z`))
inverse
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def deriv(self, p): """ Derivative of Log-Log transform link function Parameters ---------- p : array_like Mean parameters Returns ------- g'(p) : ndarray The derivative of the LogLog transform link function Notes ----- g'(p) = - 1 /(p * log(p)) """ p = self._clean(p) return -1. / (p * (np.log(p)))
Derivative of Log-Log transform link function Parameters ---------- p : array_like Mean parameters Returns ------- g'(p) : ndarray The derivative of the LogLog transform link function Notes ----- g'(p) = - 1 /(p * log(p))
deriv
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def deriv2(self, p): """ Second derivative of the Log-Log link function Parameters ---------- p : array_like Mean parameters Returns ------- g''(p) : ndarray The second derivative of the LogLog link function """ p = self._clean(p) d2 = (1 + np.log(p)) / (p * (np.log(p))) ** 2 return d2
Second derivative of the Log-Log link function Parameters ---------- p : array_like Mean parameters Returns ------- g''(p) : ndarray The second derivative of the LogLog link function
deriv2
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def inverse_deriv(self, z): """ Derivative of the inverse of the Log-Log transform link function Parameters ---------- z : array_like The value of the inverse of the LogLog link function at `p` Returns ------- g^(-1)'(z) : ndarray The derivative of the inverse of the LogLog link function """ return np.exp(-np.exp(-z) - z)
Derivative of the inverse of the Log-Log transform link function Parameters ---------- z : array_like The value of the inverse of the LogLog link function at `p` Returns ------- g^(-1)'(z) : ndarray The derivative of the inverse of the LogLog link function
inverse_deriv
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def inverse_deriv2(self, z): """ Second derivative of the inverse of the Log-Log transform link function Parameters ---------- z : array_like The value of the inverse of the LogLog link function at `p` Returns ------- g^(-1)''(z) : ndarray The second derivative of the inverse of the LogLog link function """ return self.inverse_deriv(z) * (np.exp(-z) - 1)
Second derivative of the inverse of the Log-Log transform link function Parameters ---------- z : array_like The value of the inverse of the LogLog link function at `p` Returns ------- g^(-1)''(z) : ndarray The second derivative of the inverse of the LogLog link function
inverse_deriv2
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def __call__(self, p): """ Negative Binomial transform link function Parameters ---------- p : array_like Mean parameters Returns ------- z : ndarray The negative binomial transform of `p` Notes ----- g(p) = log(p/(p + 1/alpha)) """ p = self._clean(p) return np.log(p / (p + 1 / self.alpha))
Negative Binomial transform link function Parameters ---------- p : array_like Mean parameters Returns ------- z : ndarray The negative binomial transform of `p` Notes ----- g(p) = log(p/(p + 1/alpha))
__call__
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def inverse(self, z): """ Inverse of the negative binomial transform Parameters ---------- z : array_like The value of the inverse of the negative binomial link at `p`. Returns ------- p : ndarray Mean parameters Notes ----- g^(-1)(z) = exp(z)/(alpha*(1-exp(z))) """ return -1 / (self.alpha * (1 - np.exp(-z)))
Inverse of the negative binomial transform Parameters ---------- z : array_like The value of the inverse of the negative binomial link at `p`. Returns ------- p : ndarray Mean parameters Notes ----- g^(-1)(z) = exp(z)/(alpha*(1-exp(z)))
inverse
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def deriv(self, p): """ Derivative of the negative binomial transform Parameters ---------- p : array_like Mean parameters Returns ------- g'(p) : ndarray The derivative of the negative binomial transform link function Notes ----- g'(x) = 1/(x+alpha*x^2) """ return 1 / (p + self.alpha * p ** 2)
Derivative of the negative binomial transform Parameters ---------- p : array_like Mean parameters Returns ------- g'(p) : ndarray The derivative of the negative binomial transform link function Notes ----- g'(x) = 1/(x+alpha*x^2)
deriv
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def deriv2(self, p): """ Second derivative of the negative binomial link function. Parameters ---------- p : array_like Mean parameters Returns ------- g''(p) : ndarray The second derivative of the negative binomial transform link function Notes ----- g''(x) = -(1+2*alpha*x)/(x+alpha*x^2)^2 """ numer = -(1 + 2 * self.alpha * p) denom = (p + self.alpha * p ** 2) ** 2 return numer / denom
Second derivative of the negative binomial link function. Parameters ---------- p : array_like Mean parameters Returns ------- g''(p) : ndarray The second derivative of the negative binomial transform link function Notes ----- g''(x) = -(1+2*alpha*x)/(x+alpha*x^2)^2
deriv2
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def inverse_deriv(self, z): """ Derivative of the inverse of the negative binomial transform Parameters ---------- z : array_like Usually the linear predictor for a GLM or GEE model Returns ------- g^(-1)'(z) : ndarray The value of the derivative of the inverse of the negative binomial link """ t = np.exp(z) return t / (self.alpha * (1 - t) ** 2)
Derivative of the inverse of the negative binomial transform Parameters ---------- z : array_like Usually the linear predictor for a GLM or GEE model Returns ------- g^(-1)'(z) : ndarray The value of the derivative of the inverse of the negative binomial link
inverse_deriv
python
statsmodels/statsmodels
statsmodels/genmod/families/links.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/links.py
BSD-3-Clause
def __call__(self, mu): """ Default variance function Parameters ---------- mu : array_like mean parameters Returns ------- v : ndarray ones(mu.shape) """ mu = np.asarray(mu) return np.ones(mu.shape, np.float64)
Default variance function Parameters ---------- mu : array_like mean parameters Returns ------- v : ndarray ones(mu.shape)
__call__
python
statsmodels/statsmodels
statsmodels/genmod/families/varfuncs.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/varfuncs.py
BSD-3-Clause
def deriv(self, mu): """ Derivative of the variance function v'(mu) """ return np.zeros_like(mu)
Derivative of the variance function v'(mu)
deriv
python
statsmodels/statsmodels
statsmodels/genmod/families/varfuncs.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/varfuncs.py
BSD-3-Clause
def __call__(self, mu): """ Power variance function Parameters ---------- mu : array_like mean parameters Returns ------- variance : ndarray numpy.fabs(mu)**self.power """ return np.power(np.fabs(mu), self.power)
Power variance function Parameters ---------- mu : array_like mean parameters Returns ------- variance : ndarray numpy.fabs(mu)**self.power
__call__
python
statsmodels/statsmodels
statsmodels/genmod/families/varfuncs.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/varfuncs.py
BSD-3-Clause
def deriv(self, mu): """ Derivative of the variance function v'(mu) May be undefined at zero. """ der = self.power * np.fabs(mu) ** (self.power - 1) ii = np.flatnonzero(mu < 0) der[ii] *= -1 return der
Derivative of the variance function v'(mu) May be undefined at zero.
deriv
python
statsmodels/statsmodels
statsmodels/genmod/families/varfuncs.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/varfuncs.py
BSD-3-Clause
def __call__(self, mu): """ Binomial variance function Parameters ---------- mu : array_like mean parameters Returns ------- variance : ndarray variance = mu/n * (1 - mu/n) * self.n """ p = self._clean(mu / self.n) return p * (1 - p) * self.n
Binomial variance function Parameters ---------- mu : array_like mean parameters Returns ------- variance : ndarray variance = mu/n * (1 - mu/n) * self.n
__call__
python
statsmodels/statsmodels
statsmodels/genmod/families/varfuncs.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/varfuncs.py
BSD-3-Clause
def deriv(self, mu): """ Derivative of the variance function v'(mu) """ return 1 - 2*mu
Derivative of the variance function v'(mu)
deriv
python
statsmodels/statsmodels
statsmodels/genmod/families/varfuncs.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/varfuncs.py
BSD-3-Clause
def __call__(self, mu): """ Negative binomial variance function Parameters ---------- mu : array_like mean parameters Returns ------- variance : ndarray variance = mu + alpha*mu**2 """ p = self._clean(mu) return p + self.alpha*p**2
Negative binomial variance function Parameters ---------- mu : array_like mean parameters Returns ------- variance : ndarray variance = mu + alpha*mu**2
__call__
python
statsmodels/statsmodels
statsmodels/genmod/families/varfuncs.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/varfuncs.py
BSD-3-Clause
def deriv(self, mu): """ Derivative of the negative binomial variance function. """ p = self._clean(mu) return 1 + 2 * self.alpha * p
Derivative of the negative binomial variance function.
deriv
python
statsmodels/statsmodels
statsmodels/genmod/families/varfuncs.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/varfuncs.py
BSD-3-Clause
def test_tweedie_loglike_obs(power): """Test that Tweedie loglike is normalized to 1.""" tweedie = Tweedie(var_power=power, eql=False) mu = 2.0 scale = 2.9 def pdf(y): return np.squeeze( np.exp( tweedie.loglike_obs(endog=y, mu=mu, scale=scale) ) ) assert_allclose(pdf(0) + integrate.quad(pdf, 0, 1e2)[0], 1, atol=1e-4)
Test that Tweedie loglike is normalized to 1.
test_tweedie_loglike_obs
python
statsmodels/statsmodels
statsmodels/genmod/families/tests/test_family.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/tests/test_family.py
BSD-3-Clause
def get_domainvalue(link): """ Get a value in the domain for a given family. """ z = -np.log(np.random.uniform(0, 1)) if isinstance(link, links.CLogLog): # prone to overflow z = min(z, 3) elif isinstance(link, links.LogLog): z = max(z, -3) elif isinstance(link, (links.NegativeBinomial, links.LogC)): # domain is negative numbers z = -z return z
Get a value in the domain for a given family.
get_domainvalue
python
statsmodels/statsmodels
statsmodels/genmod/families/tests/test_link.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/genmod/families/tests/test_link.py
BSD-3-Clause
def _check_data(data): """ Check if data is a DataFrame and issue a warning if it is not. Parameters ---------- data : {dict, list, recarray, DataFrame} The data used to create a formula. Notes ----- Warns if data is not a DataFrame. """ if not isinstance(data, pd.DataFrame): warnings.warn( f"Using {type(data).__name__} data structures with formula is " "deprecated and will be removed in a future version of statsmodels. " "DataFrames are the only supported data structure.", DeprecationWarning, )
Check if data is a DataFrame and issue a warning if it is not. Parameters ---------- data : {dict, list, recarray, DataFrame} The data used to create a formula. Notes ----- Warns if data is not a DataFrame.
_check_data
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def formula_engine(self) -> Literal["patsy", "formulaic"]: """ Get or set the formula engine Returns ------- str: {"patsy", "formulaic"} The name of the formula engine. """ return self._formula_engine
Get or set the formula engine Returns ------- str: {"patsy", "formulaic"} The name of the formula engine.
formula_engine
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def ordering(self): """ Get or set the ordering. Returns ------- {"degree", "sort", "none", "legacy"} The name of the ordering. Only used if engine is formulaic. """ return self._ordering
Get or set the ordering. Returns ------- {"degree", "sort", "none", "legacy"} The name of the ordering. Only used if engine is formulaic.
ordering
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def _get_engine( engine: Literal["patsy", "formulaic"] | None = None, ) -> Literal["patsy", "formulaic"]: """ Check user engine selection or get the default engine to use. Parameters ---------- engine : {"patsy", "formulaic"} or None The formula engine to use. If None, the default engine, which appears in the attribute statsmodels.formula.formula_options.engine, is used. Returns ------- engine : {"patsy", "formulaic"} The selected engine Raises ------ ValueError If the selected engine is not available. """ # Patsy for now, to be changed to a user-settable variable before release _engine: Literal["patsy", "formulaic"] if engine is not None: _engine = engine else: import statsmodels.formula _engine = statsmodels.formula.options.formula_engine assert _engine is not None if _engine not in ("patsy", "formulaic"): raise ValueError( f"Unknown engine: {_engine}. Only patsy and formulaic are supported." ) # Ensure selected engine is available msg_base = " is not available. Please install patsy." if _engine == "patsy" and not HAVE_PATSY: raise ImportError(f"patsy {msg_base}.") if _engine == "formulaic" and not HAVE_FORMULAIC: raise ImportError(f"formulaic {msg_base}.") return _engine
Check user engine selection or get the default engine to use. Parameters ---------- engine : {"patsy", "formulaic"} or None The formula engine to use. If None, the default engine, which appears in the attribute statsmodels.formula.formula_options.engine, is used. Returns ------- engine : {"patsy", "formulaic"} The selected engine Raises ------ ValueError If the selected engine is not available.
_get_engine
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def engine(self): """Get the formula engine.""" return self._engine
Get the formula engine.
engine
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def spec(self): """ Get the model specification. Only available after calling get_arrays. """ return self._spec
Get the model specification. Only available after calling get_arrays.
spec
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def factor_evaluation_error(self): """ Get the engine-specific error that may occur when evaluating a factor. """ if self._using_patsy: return patsy.PatsyError else: return formulaic.errors.FactorEvaluationError
Get the engine-specific error that may occur when evaluating a factor.
factor_evaluation_error
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def formula_materializer_error(self): """ Get the engine-specific error that may occur when materializing a formula. """ if self._using_patsy: return patsy.PatsyError else: return formulaic.errors.FormulaMaterializerNotFoundError
Get the engine-specific error that may occur when materializing a formula.
formula_materializer_error
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def missing_mask(self): """ Get a mask indicating if data are missing. Returns ------- ndarray A boolean array indicating if data are missing. True if missing. """ return self._missing_mask
Get a mask indicating if data are missing. Returns ------- ndarray A boolean array indicating if data are missing. True if missing.
missing_mask
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def intercept_term(self): """ Get the formula-engine-specific intercept term. Returns ------- Term The intercept term. """ if self._using_patsy: from patsy.desc import INTERCEPT return INTERCEPT else: from formulaic.parser.types.factor import Factor from formulaic.parser.types.term import Term return Term((Factor("1"),))
Get the formula-engine-specific intercept term. Returns ------- Term The intercept term.
intercept_term
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def model_spec_type(self): """ Returns the engine-specific model specification type. Returns ------- {type[ModelSpect], type[DesignInto]} The model specification type of formulaic is ModelSpec. patsy uses DesignInfo. """ if self._using_patsy: return patsy.design_info.DesignInfo else: return formulaic.model_spec.ModelSpec
Returns the engine-specific model specification type. Returns ------- {type[ModelSpect], type[DesignInto]} The model specification type of formulaic is ModelSpec. patsy uses DesignInfo.
model_spec_type
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def _legacy_orderer( formula: str, data: pd.DataFrame, context: int | Mapping[str, Any] ) -> formulaic.Formula: """ Function to order a formulaic formula so when materialized it matches patsy. Parameters ---------- formula : str The string formula. If not a string, it is returned as is. data : DataFrame The data used to materialize the formula. context The context used to evaluate the formula. Returns ------- Formula The ordered formula. """ if isinstance(formula, (formulaic.Formula, formulaic.ModelSpec)): return formula if isinstance(context, int): context += 1 mm = formulaic.model_matrix(formula, data, context=context) feature_flags = formulaic.parser.DefaultFormulaParser.FeatureFlags.TWOSIDED parser = formulaic.parser.DefaultFormulaParser(feature_flags=feature_flags) _formula = formulaic.Formula(formula, _parser=parser, _ordering="none") if isinstance(mm, formulaic.ModelMatrices): rhs = mm.rhs rhs_formula = _formula.rhs lhs_formula = _formula.lhs else: rhs = mm rhs_formula = _formula lhs_formula = None include_intercept = any( [(term.degree == 0 and str(term) == "1") for term in rhs_formula] ) parser = formulaic.parser.DefaultFormulaParser( feature_flags=feature_flags, include_intercept=include_intercept ) original = list(parser.get_terms(str(rhs_formula)).root) categorical_variables = list(rhs.model_spec.factor_contrasts.keys()) def all_cat(term): return all([f in categorical_variables for f in term.factors]) def drop_terms(term_list, terms): for term in terms: term_list.remove(term) intercept = [term for term in original if term.degree == 0] drop_terms(original, intercept) cats = sorted( [term for term in original if all_cat(term)], key=lambda term: term.degree ) drop_terms(original, cats) conts = defaultdict(list) for term in original: cont = [ factor for factor in term.factors if factor not in categorical_variables ] conts[tuple(sorted(cont))].append((term, term.degree)) final_conts = [] for key, value in conts.items(): tmp = sorted(value, key=lambda term_degree: term_degree[1]) final_conts.extend([value[0] for value in tmp]) if lhs_formula is not None: return formulaic.Formula( lhs=formulaic.Formula(lhs_formula, _ordering="none"), rhs=formulaic.Formula(intercept + cats + final_conts, _ordering="none"), _ordering="none", ) else: return formulaic.Formula(intercept + cats + final_conts, _ordering="none")
Function to order a formulaic formula so when materialized it matches patsy. Parameters ---------- formula : str The string formula. If not a string, it is returned as is. data : DataFrame The data used to materialize the formula. context The context used to evaluate the formula. Returns ------- Formula The ordered formula.
_legacy_orderer
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def get_linear_constraints( self, constraints: np.ndarray | str | Sequence[str], variable_names: list[str] ): """ Get the linear constraints from the constraints and variable names. Parameters ---------- constraints : ndarray, str, list[str] The constraints either as an array, a string, or a list of strings. Single strings can be comma-separated so that multiple constraints can be passed in this format. variable_names : list[str] The ordered list of variable names. Returns ------- LinearConstraintValues The constraint matrix, constraint values, and variable names. """ if self._using_patsy: from patsy.design_info import DesignInfo lc = DesignInfo(variable_names).linear_constraint(constraints) return LinearConstraintValues( constraint_matrix=lc.coefs, constraint_values=lc.constants, variable_names=lc.variable_names, ) else: # self._engine == "formulaic" # Handle list of constraints, which is not supported by formulaic if isinstance(constraints, list): if len(constraints) == 0: raise ValueError("Constraints must be non-empty") if isinstance(constraints[0], str): if not all(isinstance(c, str) for c in constraints): raise ValueError( "All constraints must be strings when passed as a list." ) _constraints = ", ".join(str(v) for v in constraints) else: _constraints = np.array(constraints) else: _constraints = constraints if isinstance(_constraints, tuple): _constraints = ( _constraints[0], np.atleast_1d(np.squeeze(_constraints[1])), ) lc_f = formulaic.utils.constraints.LinearConstraints.from_spec( _constraints, variable_names=list(variable_names) ) return LinearConstraintValues( constraint_matrix=lc_f.constraint_matrix, constraint_values=np.atleast_2d(lc_f.constraint_values).T, variable_names=lc_f.variable_names, )
Get the linear constraints from the constraints and variable names. Parameters ---------- constraints : ndarray, str, list[str] The constraints either as an array, a string, or a list of strings. Single strings can be comma-separated so that multiple constraints can be passed in this format. variable_names : list[str] The ordered list of variable names. Returns ------- LinearConstraintValues The constraint matrix, constraint values, and variable names.
get_linear_constraints
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def get_empty_eval_env(self): """ Get an empty evaluation environment. Returns ------- {EvalEnvironment, dict} A formula-engine-dependent empty evaluation environment. """ if self._using_patsy: from patsy.eval import EvalEnvironment return EvalEnvironment({}) else: return {}
Get an empty evaluation environment. Returns ------- {EvalEnvironment, dict} A formula-engine-dependent empty evaluation environment.
get_empty_eval_env
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def remove_intercept(self, terms): """ Remove intercept from Patsy terms. Parameters ---------- terms : list[Term] A list of terms that might have an intercept Returns ------- list[Term] The terms with the intercept removed, if present. """ intercept = self.intercept_term if intercept in terms: terms.remove(intercept) return terms
Remove intercept from Patsy terms. Parameters ---------- terms : list[Term] A list of terms that might have an intercept Returns ------- list[Term] The terms with the intercept removed, if present.
remove_intercept
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def has_intercept(self, spec): """ Check if the model specification has an intercept term. Parameters ---------- spec Returns ------- bool True if the model specification has an intercept term, False otherwise. """ return self.intercept_term in spec.terms
Check if the model specification has an intercept term. Parameters ---------- spec Returns ------- bool True if the model specification has an intercept term, False otherwise.
has_intercept
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def intercept_idx(self, spec): """ Returns boolean array index indicating which column holds the intercept. Parameters ---------- spec Returns ------- ndarray Boolean array index indicating which column holds the intercept. """ from numpy import array intercept = self.intercept_term return array([intercept == i for i in spec.terms])
Returns boolean array index indicating which column holds the intercept. Parameters ---------- spec Returns ------- ndarray Boolean array index indicating which column holds the intercept.
intercept_idx
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def get_na_action(self, action: str = "drop", types: Sequence[Any] = _NoDefault): """ Get the NA action for the formula engine. Parameters ---------- action types Returns ------- NAAction | str The formula-engine-specific NA action. Notes ----- types is ignored when using formulaic. """ types = ["None", "NaN"] if types is _NoDefault else types if self._using_patsy: return NAAction(on_NA=action, NA_types=types) else: return action
Get the NA action for the formula engine. Parameters ---------- action types Returns ------- NAAction | str The formula-engine-specific NA action. Notes ----- types is ignored when using formulaic.
get_na_action
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def get_spec(self, formula): """ Get the model specification from a formula. Parameters ---------- formula : str The formula to parse. Returns ------- {ModelDesc, Formula} The engine-specific model specification. """ if self._using_patsy: return patsy.ModelDesc.from_formula(formula) else: return formulaic.Formula(formula)
Get the model specification from a formula. Parameters ---------- formula : str The formula to parse. Returns ------- {ModelDesc, Formula} The engine-specific model specification.
get_spec
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def get_term_names(self, spec_or_frame): """ Get the term names from a model specification or DataFrame. Parameters ---------- spec_or_frame Returns ------- """ spec = self._ensure_spec(spec_or_frame) if self._using_patsy: return list(spec.term_names) else: return [str(term) for term in spec.terms]
Get the term names from a model specification or DataFrame. Parameters ---------- spec_or_frame Returns -------
get_term_names
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def get_column_names(self, spec_or_frame): """ Returns a list of column names from a model specification or DataFrame. Parameters ---------- spec_or_frame : {DataFrame, ModelSpec, DesignInfo Returns ------- list[str] The column names. """ spec = self._ensure_spec(spec_or_frame) return list(spec.column_names)
Returns a list of column names from a model specification or DataFrame. Parameters ---------- spec_or_frame : {DataFrame, ModelSpec, DesignInfo Returns ------- list[str] The column names.
get_column_names
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def get_term_name_slices(self, spec_or_frame): """ Get a dictionary containing the term names and their location in the formula. Parameters ---------- spec_or_frame : {DataFrame, ModelSpec, DesignInfo} The DataFrame with a model specification attached or the model specification. Returns ------- dict[str, slice] A dictionary mapping term names to location in the materialized formula. """ spec = self._ensure_spec(spec_or_frame) if self._using_patsy: return dict(spec.term_name_slices) else: return spec.term_slices
Get a dictionary containing the term names and their location in the formula. Parameters ---------- spec_or_frame : {DataFrame, ModelSpec, DesignInfo} The DataFrame with a model specification attached or the model specification. Returns ------- dict[str, slice] A dictionary mapping term names to location in the materialized formula.
get_term_name_slices
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def get_model_spec(self, frame, optional=False): """ Parameters ---------- frame : DataFrame The frame to get the model specification from. optional : bool Whether to return None if the frame does not have a model specification. Returns ------- {ModelSpec, DesignInfo} The engine-specific model specification """ if self._using_patsy: if optional and not hasattr(frame, "design_info"): return None return frame.design_info else: if optional and not hasattr(frame, "model_spec"): return None return frame.model_spec
Parameters ---------- frame : DataFrame The frame to get the model specification from. optional : bool Whether to return None if the frame does not have a model specification. Returns ------- {ModelSpec, DesignInfo} The engine-specific model specification
get_model_spec
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def get_slice(self, model_spec, term): """ Parameters ---------- model_spec : {ModelSpec, DesignInfo} The model specification. term : Term The model term. Returns ------- slice The slice indicating the variables connected to a specific model term. """ if self._using_patsy: return model_spec.slice(term) else: return model_spec.get_slice(term)
Parameters ---------- model_spec : {ModelSpec, DesignInfo} The model specification. term : Term The model term. Returns ------- slice The slice indicating the variables connected to a specific model term.
get_slice
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def get_term_name(self, term): """ Gets the string name of a term Parameters ---------- term : Term Returns ------- str The term's name. """ if self._using_patsy: return term.name() else: return str(term)
Gets the string name of a term Parameters ---------- term : Term Returns ------- str The term's name.
get_term_name
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def get_description(self, spec_or_frame): """ Gets a string representation of the model specification. Parameters ---------- spec_or_frame : {DataFrame, ModelSpec, DesignInfo Returns ------- str The human-readable description of the model specification., """ spec = self._ensure_spec(spec_or_frame) if self._using_patsy: return spec.describe() else: return str(spec.formula)
Gets a string representation of the model specification. Parameters ---------- spec_or_frame : {DataFrame, ModelSpec, DesignInfo Returns ------- str The human-readable description of the model specification.,
get_description
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def get_factor_categories(self, factor, model_spec): """ Get the list of categories for a factor. Parameters ---------- factor : {EvalFactor, Factor} The factor to get the categories for. model_spec : {ModelSpec, DesignInfo} The model specification. Returns ------- tuple The categories for the factor. """ if self._using_patsy: return model_spec.factor_infos[factor].categories else: return tuple(model_spec.encoder_state[factor][1]["categories"])
Get the list of categories for a factor. Parameters ---------- factor : {EvalFactor, Factor} The factor to get the categories for. model_spec : {ModelSpec, DesignInfo} The model specification. Returns ------- tuple The categories for the factor.
get_factor_categories
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def get_contrast_matrix(self, term, factor, model_spec): """ Get the contrast matrix for a term and factor. Parameters ---------- term : Term Either a formulaic Term or a patsy Term. factor : EvalFactor or Factor Either a formulaic Factor or a patsy EvalFactor model_spec : engine-specific model specification Either a formulaic ModelSpec or a patsy DesignInfo. Returns ------- ndarray The contract matrix to use for hypothesis testing. """ if self._using_patsy: return model_spec.term_codings[term][0].contrast_matrices[factor].matrix else: cat = self.get_factor_categories(factor, model_spec) reduced_rank = True for ts in model_spec.structure: if ts.term == term: reduced_rank = len(ts.columns) != len(cat) break return np.asarray( model_spec.factor_contrasts[factor].get_coding_matrix( reduced_rank=reduced_rank ) )
Get the contrast matrix for a term and factor. Parameters ---------- term : Term Either a formulaic Term or a patsy Term. factor : EvalFactor or Factor Either a formulaic Factor or a patsy EvalFactor model_spec : engine-specific model specification Either a formulaic ModelSpec or a patsy DesignInfo. Returns ------- ndarray The contract matrix to use for hypothesis testing.
get_contrast_matrix
python
statsmodels/statsmodels
statsmodels/formula/_manager.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/_manager.py
BSD-3-Clause
def handle_formula_data(Y, X, formula, depth=0, missing="drop"): """ Returns endog, exog, and the model specification from arrays and formula. Parameters ---------- Y : array_like Either endog (the LHS) of a model specification or all of the data. Y must define __getitem__ for now. X : array_like Either exog or None. If all the data for the formula is provided in Y then you must explicitly set X to None. formula : str or patsy.model_desc You can pass a handler by import formula_handler and adding a key-value pair where the key is the formula object class and the value is a function that returns endog, exog, formula object. Returns ------- endog : array_like Should preserve the input type of Y,X. exog : array_like Should preserve the input type of Y,X. Could be None. """ # half ass attempt to handle other formula objects if isinstance(formula, tuple(formula_handler.keys())): return formula_handler[type(formula)] na_action = FormulaManager().get_na_action(action=missing) mgr = FormulaManager() if X is not None: result = mgr.get_matrices( formula, (Y, X), eval_env=depth, pandas=True, na_action=na_action, attach_spec=True, ) else: result = mgr.get_matrices( formula, Y, eval_env=depth, pandas=True, na_action=na_action, ) missing_mask = mgr.missing_mask if not np.any(missing_mask): missing_mask = None if len(result) > 1: # have RHS design model_spec = mgr.spec # detach it from DataFrame else: model_spec = None # NOTE: is there ever a case where we'd need LHS's model_spec? return result, missing_mask, model_spec
Returns endog, exog, and the model specification from arrays and formula. Parameters ---------- Y : array_like Either endog (the LHS) of a model specification or all of the data. Y must define __getitem__ for now. X : array_like Either exog or None. If all the data for the formula is provided in Y then you must explicitly set X to None. formula : str or patsy.model_desc You can pass a handler by import formula_handler and adding a key-value pair where the key is the formula object class and the value is a function that returns endog, exog, formula object. Returns ------- endog : array_like Should preserve the input type of Y,X. exog : array_like Should preserve the input type of Y,X. Could be None.
handle_formula_data
python
statsmodels/statsmodels
statsmodels/formula/formulatools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/formulatools.py
BSD-3-Clause
def advance_eval_env(kwargs): """ Adjusts the keyword arguments for from_formula to account for the patsy eval environment being passed down once on the stack. Adjustments are made in place. Parameters ---------- kwargs : dict The dictionary of keyword arguments passed to `from_formula`. """ eval_env = kwargs.get("eval_env", None) if eval_env is None: kwargs["eval_env"] = 2 elif eval_env == -1: kwargs["eval_env"] = FormulaManager().get_empty_eval_env()
Adjusts the keyword arguments for from_formula to account for the patsy eval environment being passed down once on the stack. Adjustments are made in place. Parameters ---------- kwargs : dict The dictionary of keyword arguments passed to `from_formula`.
advance_eval_env
python
statsmodels/statsmodels
statsmodels/formula/formulatools.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/formula/formulatools.py
BSD-3-Clause
def webuse(data, baseurl='https://www.stata-press.com/data/r11/', as_df=True): """ Download and return an example dataset from Stata. Parameters ---------- data : str Name of dataset to fetch. baseurl : str The base URL to the stata datasets. as_df : bool Deprecated. Always returns a DataFrame Returns ------- dta : DataFrame A DataFrame containing the Stata dataset. Examples -------- >>> dta = webuse('auto') Notes ----- Make sure baseurl has trailing forward slash. Does not do any error checking in response URLs. """ url = urljoin(baseurl, data+'.dta') return read_stata(url)
Download and return an example dataset from Stata. Parameters ---------- data : str Name of dataset to fetch. baseurl : str The base URL to the stata datasets. as_df : bool Deprecated. Always returns a DataFrame Returns ------- dta : DataFrame A DataFrame containing the Stata dataset. Examples -------- >>> dta = webuse('auto') Notes ----- Make sure baseurl has trailing forward slash. Does not do any error checking in response URLs.
webuse
python
statsmodels/statsmodels
statsmodels/datasets/utils.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/utils.py
BSD-3-Clause
def _maybe_reset_index(data): """ All the Rdatasets have the integer row.labels from R if there is no real index. Strip this for a zero-based index """ if data.index.equals(Index(lrange(1, len(data) + 1))): data = data.reset_index(drop=True) return data
All the Rdatasets have the integer row.labels from R if there is no real index. Strip this for a zero-based index
_maybe_reset_index
python
statsmodels/statsmodels
statsmodels/datasets/utils.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/utils.py
BSD-3-Clause
def _urlopen_cached(url, cache): """ Tries to load data from cache location otherwise downloads it. If it downloads the data and cache is not None then it will put the downloaded data in the cache path. """ from_cache = False if cache is not None: file_name = url.split("://")[-1].replace('/', ',') file_name = file_name.split('.') if len(file_name) > 1: file_name[-2] += '-v2' else: file_name[0] += '-v2' file_name = '.'.join(file_name) + ".zip" cache_path = join(cache, file_name) try: data = _open_cache(cache_path) from_cache = True except Exception: # Hit this if not in cache pass # not using the cache or did not find it in cache if not from_cache: data = urlopen(url, timeout=3).read() if cache is not None: # then put it in the cache _cache_it(data, cache_path) return data, from_cache
Tries to load data from cache location otherwise downloads it. If it downloads the data and cache is not None then it will put the downloaded data in the cache path.
_urlopen_cached
python
statsmodels/statsmodels
statsmodels/datasets/utils.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/utils.py
BSD-3-Clause
def get_rdataset(dataname, package="datasets", cache=False): """download and return R dataset Parameters ---------- dataname : str The name of the dataset you want to download package : str The package in which the dataset is found. The default is the core 'datasets' package. cache : bool or str If True, will download this data into the STATSMODELS_DATA folder. The default location is a folder called statsmodels_data in the user home folder. Otherwise, you can specify a path to a folder to use for caching the data. If False, the data will not be cached. Returns ------- dataset : Dataset A `statsmodels.data.utils.Dataset` instance. This objects has attributes: * data - A pandas DataFrame containing the data * title - The dataset title * package - The package from which the data came * from_cache - Whether not cached data was retrieved * __doc__ - The verbatim R documentation. Notes ----- If the R dataset has an integer index. This is reset to be zero-based. Otherwise the index is preserved. The caching facilities are dumb. That is, no download dates, e-tags, or otherwise identifying information is checked to see if the data should be downloaded again or not. If the dataset is in the cache, it's used. """ # NOTE: use raw github bc html site might not be most up to date data_base_url = ("https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/" "master/csv/"+package+"/") docs_base_url = ("https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/" "master/doc/"+package+"/rst/") cache = _get_cache(cache) data, from_cache = _get_data(data_base_url, dataname, cache) data = read_csv(data, index_col=0) data = _maybe_reset_index(data) title = _get_dataset_meta(dataname, package, cache) doc, _ = _get_data(docs_base_url, dataname, cache, "rst") return Dataset(data=data, __doc__=doc.read(), package=package, title=title, from_cache=from_cache)
download and return R dataset Parameters ---------- dataname : str The name of the dataset you want to download package : str The package in which the dataset is found. The default is the core 'datasets' package. cache : bool or str If True, will download this data into the STATSMODELS_DATA folder. The default location is a folder called statsmodels_data in the user home folder. Otherwise, you can specify a path to a folder to use for caching the data. If False, the data will not be cached. Returns ------- dataset : Dataset A `statsmodels.data.utils.Dataset` instance. This objects has attributes: * data - A pandas DataFrame containing the data * title - The dataset title * package - The package from which the data came * from_cache - Whether not cached data was retrieved * __doc__ - The verbatim R documentation. Notes ----- If the R dataset has an integer index. This is reset to be zero-based. Otherwise the index is preserved. The caching facilities are dumb. That is, no download dates, e-tags, or otherwise identifying information is checked to see if the data should be downloaded again or not. If the dataset is in the cache, it's used.
get_rdataset
python
statsmodels/statsmodels
statsmodels/datasets/utils.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/utils.py
BSD-3-Clause
def get_data_home(data_home=None): """Return the path of the statsmodels data dir. This folder is used by some large dataset loaders to avoid downloading the data several times. By default the data dir is set to a folder named 'statsmodels_data' in the user home folder. Alternatively, it can be set by the 'STATSMODELS_DATA' environment variable or programatically by giving an explicit folder path. The '~' symbol is expanded to the user home folder. If the folder does not already exist, it is automatically created. """ if data_home is None: data_home = environ.get('STATSMODELS_DATA', join('~', 'statsmodels_data')) data_home = expanduser(data_home) if not exists(data_home): makedirs(data_home) return data_home
Return the path of the statsmodels data dir. This folder is used by some large dataset loaders to avoid downloading the data several times. By default the data dir is set to a folder named 'statsmodels_data' in the user home folder. Alternatively, it can be set by the 'STATSMODELS_DATA' environment variable or programatically by giving an explicit folder path. The '~' symbol is expanded to the user home folder. If the folder does not already exist, it is automatically created.
get_data_home
python
statsmodels/statsmodels
statsmodels/datasets/utils.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/utils.py
BSD-3-Clause
def clear_data_home(data_home=None): """Delete all the content of the data home cache.""" data_home = get_data_home(data_home) shutil.rmtree(data_home)
Delete all the content of the data home cache.
clear_data_home
python
statsmodels/statsmodels
statsmodels/datasets/utils.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/utils.py
BSD-3-Clause
def check_internet(url=None): """Check if internet is available""" url = "https://github.com" if url is None else url try: urlopen(url) except URLError: return False return True
Check if internet is available
check_internet
python
statsmodels/statsmodels
statsmodels/datasets/utils.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/utils.py
BSD-3-Clause
def strip_column_names(df): """ Remove leading and trailing single quotes Parameters ---------- df : DataFrame DataFrame to process Returns ------- df : DataFrame DataFrame with stripped column names Notes ----- In-place modification """ columns = [] for c in df: if c.startswith('\'') and c.endswith('\''): c = c[1:-1] elif c.startswith('\''): c = c[1:] elif c.endswith('\''): c = c[:-1] columns.append(c) df.columns = columns return df
Remove leading and trailing single quotes Parameters ---------- df : DataFrame DataFrame to process Returns ------- df : DataFrame DataFrame with stripped column names Notes ----- In-place modification
strip_column_names
python
statsmodels/statsmodels
statsmodels/datasets/utils.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/utils.py
BSD-3-Clause
def load_csv(base_file, csv_name, sep=',', convert_float=False): """Standard simple csv loader""" filepath = dirname(abspath(base_file)) filename = join(filepath,csv_name) engine = 'python' if sep != ',' else 'c' float_precision = {} if engine == 'c': float_precision = {'float_precision': 'high'} data = read_csv(filename, sep=sep, engine=engine, **float_precision) if convert_float: data = data.astype(float) return data
Standard simple csv loader
load_csv
python
statsmodels/statsmodels
statsmodels/datasets/utils.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/utils.py
BSD-3-Clause
def load(): """ Load the data and return a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ return load_pandas()
Load the data and return a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load
python
statsmodels/statsmodels
statsmodels/datasets/template_data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/template_data.py
BSD-3-Clause
def load_pandas(): """ Load the strikes data and return a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_pandas(data, endog_idx=0)
Load the strikes data and return a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load_pandas
python
statsmodels/statsmodels
statsmodels/datasets/template_data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/template_data.py
BSD-3-Clause
def load(): """ Load the data and return a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ return load_pandas()
Load the data and return a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load
python
statsmodels/statsmodels
statsmodels/datasets/heart/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/heart/data.py
BSD-3-Clause
def load(): """ Load the Nile data and return a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ return load_pandas()
Load the Nile data and return a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load
python
statsmodels/statsmodels
statsmodels/datasets/nile/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/nile/data.py
BSD-3-Clause
def load(): """Load the committee data and returns a data class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ return load_pandas()
Load the committee data and returns a data class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load
python
statsmodels/statsmodels
statsmodels/datasets/committee/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/committee/data.py
BSD-3-Clause
def load(): """ Load the US macro data and return a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. Notes ----- The Dataset instance does not contain endog and exog attributes. """ return load_pandas()
Load the US macro data and return a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. Notes ----- The Dataset instance does not contain endog and exog attributes.
load
python
statsmodels/statsmodels
statsmodels/datasets/danish_data/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/danish_data/data.py
BSD-3-Clause
def load(): """ Load the star98 data and returns a Dataset class instance. Returns ------- Load instance: a class of the data with array attrbutes 'endog' and 'exog' """ return load_pandas()
Load the star98 data and returns a Dataset class instance. Returns ------- Load instance: a class of the data with array attrbutes 'endog' and 'exog'
load
python
statsmodels/statsmodels
statsmodels/datasets/star98/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/star98/data.py
BSD-3-Clause
def load(): """ Loads the Grunfeld data and returns a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. Notes ----- raw_data has the firm variable expanded to dummy variables for each firm (ie., there is no reference dummy) """ return load_pandas()
Loads the Grunfeld data and returns a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. Notes ----- raw_data has the firm variable expanded to dummy variables for each firm (ie., there is no reference dummy)
load
python
statsmodels/statsmodels
statsmodels/datasets/grunfeld/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/grunfeld/data.py
BSD-3-Clause
def load_pandas(): """ Loads the Grunfeld data and returns a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. Notes ----- raw_data has the firm variable expanded to dummy variables for each firm (ie., there is no reference dummy) """ data = _get_data() data.year = data.year.astype(float) raw_data = pd.get_dummies(data) ds = du.process_pandas(data, endog_idx=0) ds.raw_data = raw_data return ds
Loads the Grunfeld data and returns a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. Notes ----- raw_data has the firm variable expanded to dummy variables for each firm (ie., there is no reference dummy)
load_pandas
python
statsmodels/statsmodels
statsmodels/datasets/grunfeld/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/grunfeld/data.py
BSD-3-Clause
def load(): """ Load the data and return a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ return load_pandas()
Load the data and return a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load
python
statsmodels/statsmodels
statsmodels/datasets/cancer/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/cancer/data.py
BSD-3-Clause
def load_pandas(): """Load the anes96 data and returns a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_pandas(data, endog_idx=5, exog_idx=[10, 2, 6, 7, 8])
Load the anes96 data and returns a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load_pandas
python
statsmodels/statsmodels
statsmodels/datasets/anes96/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/anes96/data.py
BSD-3-Clause
def load(): """Load the anes96 data and returns a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ return load_pandas()
Load the anes96 data and returns a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load
python
statsmodels/statsmodels
statsmodels/datasets/anes96/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/anes96/data.py
BSD-3-Clause
def load(): """ Load the stack loss data and returns a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ return load_pandas()
Load the stack loss data and returns a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load
python
statsmodels/statsmodels
statsmodels/datasets/stackloss/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/stackloss/data.py
BSD-3-Clause
def load_pandas(): """ Load the stack loss data and returns a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_pandas(data, endog_idx=0)
Load the stack loss data and returns a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load_pandas
python
statsmodels/statsmodels
statsmodels/datasets/stackloss/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/stackloss/data.py
BSD-3-Clause
def load(): """ Load the yearly sunspot data and returns a data class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. Notes ----- This dataset only contains data for one variable, so the attributes data, raw_data, and endog are all the same variable. There is no exog attribute defined. """ return load_pandas()
Load the yearly sunspot data and returns a data class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. Notes ----- This dataset only contains data for one variable, so the attributes data, raw_data, and endog are all the same variable. There is no exog attribute defined.
load
python
statsmodels/statsmodels
statsmodels/datasets/sunspots/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/sunspots/data.py
BSD-3-Clause
def load(): """ Load the Longley data and return a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ return load_pandas()
Load the Longley data and return a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load
python
statsmodels/statsmodels
statsmodels/datasets/longley/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/longley/data.py
BSD-3-Clause
def load_pandas(): """ Load the Longley data and return a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_pandas(data, endog_idx=0)
Load the Longley data and return a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load_pandas
python
statsmodels/statsmodels
statsmodels/datasets/longley/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/longley/data.py
BSD-3-Clause
def load_pandas(): """ Load the copper data and returns a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_pandas(data, endog_idx=0)
Load the copper data and returns a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load_pandas
python
statsmodels/statsmodels
statsmodels/datasets/copper/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/copper/data.py
BSD-3-Clause
def load(): """ Load the copper data and returns a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ return load_pandas()
Load the copper data and returns a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load
python
statsmodels/statsmodels
statsmodels/datasets/copper/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/copper/data.py
BSD-3-Clause
def load(): """ Load the data and return a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ return load_pandas()
Load the data and return a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load
python
statsmodels/statsmodels
statsmodels/datasets/fertility/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/fertility/data.py
BSD-3-Clause
def load(): """ Load the El Nino data and return a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. Notes ----- The elnino Dataset instance does not contain endog and exog attributes. """ return load_pandas()
Load the El Nino data and return a Dataset class. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. Notes ----- The elnino Dataset instance does not contain endog and exog attributes.
load
python
statsmodels/statsmodels
statsmodels/datasets/elnino/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/elnino/data.py
BSD-3-Clause
def load_pandas(): """ Load the strikes data and return a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information. """ data = _get_data() return du.process_pandas(data, endog_idx=0)
Load the strikes data and return a Dataset class instance. Returns ------- Dataset See DATASET_PROPOSAL.txt for more information.
load_pandas
python
statsmodels/statsmodels
statsmodels/datasets/strikes/data.py
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/datasets/strikes/data.py
BSD-3-Clause