id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
239,200 | pymc-devs/pymc | pymc/distributions.py | dirichlet_like | def dirichlet_like(x, theta):
R"""
Dirichlet log-likelihood.
This is a multivariate continuous distribution.
.. math::
f(\mathbf{x}) = \frac{\Gamma(\sum_{i=1}^k \theta_i)}{\prod \Gamma(\theta_i)}\prod_{i=1}^{k-1} x_i^{\theta_i - 1}
\cdot\left(1-\sum_{i=1}^{k-1}x_i\right)^\theta_k
:Parameters:
x : (n, k-1) array
Array of shape (n, k-1) where `n` is the number of samples
and `k` the dimension.
:math:`0 < x_i < 1`, :math:`\sum_{i=1}^{k-1} x_i < 1`
theta : array
An (n,k) or (1,k) array > 0.
.. note::
Only the first `k-1` elements of `x` are expected. Can be used
as a parent of Multinomial and Categorical nevertheless.
"""
x = np.atleast_2d(x)
theta = np.atleast_2d(theta)
if (np.shape(x)[-1] + 1) != np.shape(theta)[-1]:
raise ValueError('The dimension of x in dirichlet_like must be k-1.')
return flib.dirichlet(x, theta) | python | def dirichlet_like(x, theta):
R"""
Dirichlet log-likelihood.
This is a multivariate continuous distribution.
.. math::
f(\mathbf{x}) = \frac{\Gamma(\sum_{i=1}^k \theta_i)}{\prod \Gamma(\theta_i)}\prod_{i=1}^{k-1} x_i^{\theta_i - 1}
\cdot\left(1-\sum_{i=1}^{k-1}x_i\right)^\theta_k
:Parameters:
x : (n, k-1) array
Array of shape (n, k-1) where `n` is the number of samples
and `k` the dimension.
:math:`0 < x_i < 1`, :math:`\sum_{i=1}^{k-1} x_i < 1`
theta : array
An (n,k) or (1,k) array > 0.
.. note::
Only the first `k-1` elements of `x` are expected. Can be used
as a parent of Multinomial and Categorical nevertheless.
"""
x = np.atleast_2d(x)
theta = np.atleast_2d(theta)
if (np.shape(x)[-1] + 1) != np.shape(theta)[-1]:
raise ValueError('The dimension of x in dirichlet_like must be k-1.')
return flib.dirichlet(x, theta) | [
"def",
"dirichlet_like",
"(",
"x",
",",
"theta",
")",
":",
"x",
"=",
"np",
".",
"atleast_2d",
"(",
"x",
")",
"theta",
"=",
"np",
".",
"atleast_2d",
"(",
"theta",
")",
"if",
"(",
"np",
".",
"shape",
"(",
"x",
")",
"[",
"-",
"1",
"]",
"+",
"1",... | R"""
Dirichlet log-likelihood.
This is a multivariate continuous distribution.
.. math::
f(\mathbf{x}) = \frac{\Gamma(\sum_{i=1}^k \theta_i)}{\prod \Gamma(\theta_i)}\prod_{i=1}^{k-1} x_i^{\theta_i - 1}
\cdot\left(1-\sum_{i=1}^{k-1}x_i\right)^\theta_k
:Parameters:
x : (n, k-1) array
Array of shape (n, k-1) where `n` is the number of samples
and `k` the dimension.
:math:`0 < x_i < 1`, :math:`\sum_{i=1}^{k-1} x_i < 1`
theta : array
An (n,k) or (1,k) array > 0.
.. note::
Only the first `k-1` elements of `x` are expected. Can be used
as a parent of Multinomial and Categorical nevertheless. | [
"R",
"Dirichlet",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1148-L1175 |
239,201 | pymc-devs/pymc | pymc/distributions.py | rexponweib | def rexponweib(alpha, k, loc=0, scale=1, size=None):
"""
Random exponentiated Weibull variates.
"""
q = np.random.uniform(size=size)
r = flib.exponweib_ppf(q, alpha, k)
return loc + r * scale | python | def rexponweib(alpha, k, loc=0, scale=1, size=None):
q = np.random.uniform(size=size)
r = flib.exponweib_ppf(q, alpha, k)
return loc + r * scale | [
"def",
"rexponweib",
"(",
"alpha",
",",
"k",
",",
"loc",
"=",
"0",
",",
"scale",
"=",
"1",
",",
"size",
"=",
"None",
")",
":",
"q",
"=",
"np",
".",
"random",
".",
"uniform",
"(",
"size",
"=",
"size",
")",
"r",
"=",
"flib",
".",
"exponweib_ppf",... | Random exponentiated Weibull variates. | [
"Random",
"exponentiated",
"Weibull",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1225-L1232 |
239,202 | pymc-devs/pymc | pymc/distributions.py | exponweib_like | def exponweib_like(x, alpha, k, loc=0, scale=1):
R"""
Exponentiated Weibull log-likelihood.
The exponentiated Weibull distribution is a generalization of the Weibull
family. Its value lies in being able to model monotone and non-monotone
failure rates.
.. math::
f(x \mid \alpha,k,loc,scale) & = \frac{\alpha k}{scale} (1-e^{-z^k})^{\alpha-1} e^{-z^k} z^{k-1} \\
z & = \frac{x-loc}{scale}
:Parameters:
- `x` : x > 0
- `alpha` : Shape parameter
- `k` : k > 0
- `loc` : Location parameter
- `scale` : Scale parameter (scale > 0).
"""
return flib.exponweib(x, alpha, k, loc, scale) | python | def exponweib_like(x, alpha, k, loc=0, scale=1):
R"""
Exponentiated Weibull log-likelihood.
The exponentiated Weibull distribution is a generalization of the Weibull
family. Its value lies in being able to model monotone and non-monotone
failure rates.
.. math::
f(x \mid \alpha,k,loc,scale) & = \frac{\alpha k}{scale} (1-e^{-z^k})^{\alpha-1} e^{-z^k} z^{k-1} \\
z & = \frac{x-loc}{scale}
:Parameters:
- `x` : x > 0
- `alpha` : Shape parameter
- `k` : k > 0
- `loc` : Location parameter
- `scale` : Scale parameter (scale > 0).
"""
return flib.exponweib(x, alpha, k, loc, scale) | [
"def",
"exponweib_like",
"(",
"x",
",",
"alpha",
",",
"k",
",",
"loc",
"=",
"0",
",",
"scale",
"=",
"1",
")",
":",
"return",
"flib",
".",
"exponweib",
"(",
"x",
",",
"alpha",
",",
"k",
",",
"loc",
",",
"scale",
")"
] | R"""
Exponentiated Weibull log-likelihood.
The exponentiated Weibull distribution is a generalization of the Weibull
family. Its value lies in being able to model monotone and non-monotone
failure rates.
.. math::
f(x \mid \alpha,k,loc,scale) & = \frac{\alpha k}{scale} (1-e^{-z^k})^{\alpha-1} e^{-z^k} z^{k-1} \\
z & = \frac{x-loc}{scale}
:Parameters:
- `x` : x > 0
- `alpha` : Shape parameter
- `k` : k > 0
- `loc` : Location parameter
- `scale` : Scale parameter (scale > 0). | [
"R",
"Exponentiated",
"Weibull",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1241-L1261 |
239,203 | pymc-devs/pymc | pymc/distributions.py | rgamma | def rgamma(alpha, beta, size=None):
"""
Random gamma variates.
"""
return np.random.gamma(shape=alpha, scale=1. / beta, size=size) | python | def rgamma(alpha, beta, size=None):
return np.random.gamma(shape=alpha, scale=1. / beta, size=size) | [
"def",
"rgamma",
"(",
"alpha",
",",
"beta",
",",
"size",
"=",
"None",
")",
":",
"return",
"np",
".",
"random",
".",
"gamma",
"(",
"shape",
"=",
"alpha",
",",
"scale",
"=",
"1.",
"/",
"beta",
",",
"size",
"=",
"size",
")"
] | Random gamma variates. | [
"Random",
"gamma",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1275-L1280 |
239,204 | pymc-devs/pymc | pymc/distributions.py | gev_expval | def gev_expval(xi, mu=0, sigma=1):
"""
Expected value of generalized extreme value distribution.
"""
return mu - (sigma / xi) + (sigma / xi) * flib.gamfun(1 - xi) | python | def gev_expval(xi, mu=0, sigma=1):
return mu - (sigma / xi) + (sigma / xi) * flib.gamfun(1 - xi) | [
"def",
"gev_expval",
"(",
"xi",
",",
"mu",
"=",
"0",
",",
"sigma",
"=",
"1",
")",
":",
"return",
"mu",
"-",
"(",
"sigma",
"/",
"xi",
")",
"+",
"(",
"sigma",
"/",
"xi",
")",
"*",
"flib",
".",
"gamfun",
"(",
"1",
"-",
"xi",
")"
] | Expected value of generalized extreme value distribution. | [
"Expected",
"value",
"of",
"generalized",
"extreme",
"value",
"distribution",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1333-L1337 |
239,205 | pymc-devs/pymc | pymc/distributions.py | gev_like | def gev_like(x, xi, mu=0, sigma=1):
R"""
Generalized Extreme Value log-likelihood
.. math::
pdf(x \mid \xi,\mu,\sigma) = \frac{1}{\sigma}(1 + \xi \left[\frac{x-\mu}{\sigma}\right])^{-1/\xi-1}\exp{-(1+\xi \left[\frac{x-\mu}{\sigma}\right])^{-1/\xi}}
.. math::
\sigma & > 0,\\
x & > \mu-\sigma/\xi \text{ if } \xi > 0,\\
x & < \mu-\sigma/\xi \text{ if } \xi < 0\\
x & \in [-\infty,\infty] \text{ if } \xi = 0
"""
return flib.gev(x, xi, mu, sigma) | python | def gev_like(x, xi, mu=0, sigma=1):
R"""
Generalized Extreme Value log-likelihood
.. math::
pdf(x \mid \xi,\mu,\sigma) = \frac{1}{\sigma}(1 + \xi \left[\frac{x-\mu}{\sigma}\right])^{-1/\xi-1}\exp{-(1+\xi \left[\frac{x-\mu}{\sigma}\right])^{-1/\xi}}
.. math::
\sigma & > 0,\\
x & > \mu-\sigma/\xi \text{ if } \xi > 0,\\
x & < \mu-\sigma/\xi \text{ if } \xi < 0\\
x & \in [-\infty,\infty] \text{ if } \xi = 0
"""
return flib.gev(x, xi, mu, sigma) | [
"def",
"gev_like",
"(",
"x",
",",
"xi",
",",
"mu",
"=",
"0",
",",
"sigma",
"=",
"1",
")",
":",
"return",
"flib",
".",
"gev",
"(",
"x",
",",
"xi",
",",
"mu",
",",
"sigma",
")"
] | R"""
Generalized Extreme Value log-likelihood
.. math::
pdf(x \mid \xi,\mu,\sigma) = \frac{1}{\sigma}(1 + \xi \left[\frac{x-\mu}{\sigma}\right])^{-1/\xi-1}\exp{-(1+\xi \left[\frac{x-\mu}{\sigma}\right])^{-1/\xi}}
.. math::
\sigma & > 0,\\
x & > \mu-\sigma/\xi \text{ if } \xi > 0,\\
x & < \mu-\sigma/\xi \text{ if } \xi < 0\\
x & \in [-\infty,\infty] \text{ if } \xi = 0 | [
"R",
"Generalized",
"Extreme",
"Value",
"log",
"-",
"likelihood"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1340-L1355 |
239,206 | pymc-devs/pymc | pymc/distributions.py | rhalf_cauchy | def rhalf_cauchy(alpha, beta, size=None):
"""
Returns half-Cauchy random variates.
"""
return abs(alpha + beta * np.tan(pi * random_number(size) - pi / 2.0)) | python | def rhalf_cauchy(alpha, beta, size=None):
return abs(alpha + beta * np.tan(pi * random_number(size) - pi / 2.0)) | [
"def",
"rhalf_cauchy",
"(",
"alpha",
",",
"beta",
",",
"size",
"=",
"None",
")",
":",
"return",
"abs",
"(",
"alpha",
"+",
"beta",
"*",
"np",
".",
"tan",
"(",
"pi",
"*",
"random_number",
"(",
"size",
")",
"-",
"pi",
"/",
"2.0",
")",
")"
] | Returns half-Cauchy random variates. | [
"Returns",
"half",
"-",
"Cauchy",
"random",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1403-L1408 |
239,207 | pymc-devs/pymc | pymc/distributions.py | half_cauchy_like | def half_cauchy_like(x, alpha, beta):
R"""
Half-Cauchy log-likelihood. Simply the absolute value of Cauchy.
.. math::
f(x \mid \alpha, \beta) = \frac{2}{\pi \beta [1 + (\frac{x-\alpha}{\beta})^2]}
:Parameters:
- `alpha` : Location parameter.
- `beta` : Scale parameter (beta > 0).
.. note::
- x must be non-negative.
"""
x = np.atleast_1d(x)
if sum(x.ravel() < 0):
return -inf
return flib.cauchy(x, alpha, beta) + len(x) * np.log(2) | python | def half_cauchy_like(x, alpha, beta):
R"""
Half-Cauchy log-likelihood. Simply the absolute value of Cauchy.
.. math::
f(x \mid \alpha, \beta) = \frac{2}{\pi \beta [1 + (\frac{x-\alpha}{\beta})^2]}
:Parameters:
- `alpha` : Location parameter.
- `beta` : Scale parameter (beta > 0).
.. note::
- x must be non-negative.
"""
x = np.atleast_1d(x)
if sum(x.ravel() < 0):
return -inf
return flib.cauchy(x, alpha, beta) + len(x) * np.log(2) | [
"def",
"half_cauchy_like",
"(",
"x",
",",
"alpha",
",",
"beta",
")",
":",
"x",
"=",
"np",
".",
"atleast_1d",
"(",
"x",
")",
"if",
"sum",
"(",
"x",
".",
"ravel",
"(",
")",
"<",
"0",
")",
":",
"return",
"-",
"inf",
"return",
"flib",
".",
"cauchy"... | R"""
Half-Cauchy log-likelihood. Simply the absolute value of Cauchy.
.. math::
f(x \mid \alpha, \beta) = \frac{2}{\pi \beta [1 + (\frac{x-\alpha}{\beta})^2]}
:Parameters:
- `alpha` : Location parameter.
- `beta` : Scale parameter (beta > 0).
.. note::
- x must be non-negative. | [
"R",
"Half",
"-",
"Cauchy",
"log",
"-",
"likelihood",
".",
"Simply",
"the",
"absolute",
"value",
"of",
"Cauchy",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1421-L1439 |
239,208 | pymc-devs/pymc | pymc/distributions.py | rhalf_normal | def rhalf_normal(tau, size=None):
"""
Random half-normal variates.
"""
return abs(np.random.normal(0, np.sqrt(1 / tau), size)) | python | def rhalf_normal(tau, size=None):
return abs(np.random.normal(0, np.sqrt(1 / tau), size)) | [
"def",
"rhalf_normal",
"(",
"tau",
",",
"size",
"=",
"None",
")",
":",
"return",
"abs",
"(",
"np",
".",
"random",
".",
"normal",
"(",
"0",
",",
"np",
".",
"sqrt",
"(",
"1",
"/",
"tau",
")",
",",
"size",
")",
")"
] | Random half-normal variates. | [
"Random",
"half",
"-",
"normal",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1445-L1450 |
239,209 | pymc-devs/pymc | pymc/distributions.py | rhypergeometric | def rhypergeometric(n, m, N, size=None):
"""
Returns hypergeometric random variates.
"""
if n == 0:
return np.zeros(size, dtype=int)
elif n == N:
out = np.empty(size, dtype=int)
out.fill(m)
return out
return np.random.hypergeometric(n, N - n, m, size) | python | def rhypergeometric(n, m, N, size=None):
if n == 0:
return np.zeros(size, dtype=int)
elif n == N:
out = np.empty(size, dtype=int)
out.fill(m)
return out
return np.random.hypergeometric(n, N - n, m, size) | [
"def",
"rhypergeometric",
"(",
"n",
",",
"m",
",",
"N",
",",
"size",
"=",
"None",
")",
":",
"if",
"n",
"==",
"0",
":",
"return",
"np",
".",
"zeros",
"(",
"size",
",",
"dtype",
"=",
"int",
")",
"elif",
"n",
"==",
"N",
":",
"out",
"=",
"np",
... | Returns hypergeometric random variates. | [
"Returns",
"hypergeometric",
"random",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1483-L1493 |
239,210 | pymc-devs/pymc | pymc/distributions.py | hypergeometric_like | def hypergeometric_like(x, n, m, N):
R"""
Hypergeometric log-likelihood.
Discrete probability distribution that describes the number of successes in
a sequence of draws from a finite population without replacement.
.. math::
f(x \mid n, m, N) = \frac{\left({ \begin{array}{c} {m} \\ {x} \\
\end{array} }\right)\left({ \begin{array}{c} {N-m} \\ {n-x} \\
\end{array}}\right)}{\left({ \begin{array}{c} {N} \\ {n} \\
\end{array}}\right)}
:Parameters:
- `x` : [int] Number of successes in a sample drawn from a population.
- `n` : [int] Size of sample drawn from the population.
- `m` : [int] Number of successes in the population.
- `N` : [int] Total number of units in the population.
.. note::
:math:`E(X) = \frac{n n}{N}`
"""
return flib.hyperg(x, n, m, N) | python | def hypergeometric_like(x, n, m, N):
R"""
Hypergeometric log-likelihood.
Discrete probability distribution that describes the number of successes in
a sequence of draws from a finite population without replacement.
.. math::
f(x \mid n, m, N) = \frac{\left({ \begin{array}{c} {m} \\ {x} \\
\end{array} }\right)\left({ \begin{array}{c} {N-m} \\ {n-x} \\
\end{array}}\right)}{\left({ \begin{array}{c} {N} \\ {n} \\
\end{array}}\right)}
:Parameters:
- `x` : [int] Number of successes in a sample drawn from a population.
- `n` : [int] Size of sample drawn from the population.
- `m` : [int] Number of successes in the population.
- `N` : [int] Total number of units in the population.
.. note::
:math:`E(X) = \frac{n n}{N}`
"""
return flib.hyperg(x, n, m, N) | [
"def",
"hypergeometric_like",
"(",
"x",
",",
"n",
",",
"m",
",",
"N",
")",
":",
"return",
"flib",
".",
"hyperg",
"(",
"x",
",",
"n",
",",
"m",
",",
"N",
")"
] | R"""
Hypergeometric log-likelihood.
Discrete probability distribution that describes the number of successes in
a sequence of draws from a finite population without replacement.
.. math::
f(x \mid n, m, N) = \frac{\left({ \begin{array}{c} {m} \\ {x} \\
\end{array} }\right)\left({ \begin{array}{c} {N-m} \\ {n-x} \\
\end{array}}\right)}{\left({ \begin{array}{c} {N} \\ {n} \\
\end{array}}\right)}
:Parameters:
- `x` : [int] Number of successes in a sample drawn from a population.
- `n` : [int] Size of sample drawn from the population.
- `m` : [int] Number of successes in the population.
- `N` : [int] Total number of units in the population.
.. note::
:math:`E(X) = \frac{n n}{N}` | [
"R",
"Hypergeometric",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1503-L1529 |
239,211 | pymc-devs/pymc | pymc/distributions.py | rlogistic | def rlogistic(mu, tau, size=None):
"""
Logistic random variates.
"""
u = np.random.random(size)
return mu + np.log(u / (1 - u)) / tau | python | def rlogistic(mu, tau, size=None):
u = np.random.random(size)
return mu + np.log(u / (1 - u)) / tau | [
"def",
"rlogistic",
"(",
"mu",
",",
"tau",
",",
"size",
"=",
"None",
")",
":",
"u",
"=",
"np",
".",
"random",
".",
"random",
"(",
"size",
")",
"return",
"mu",
"+",
"np",
".",
"log",
"(",
"u",
"/",
"(",
"1",
"-",
"u",
")",
")",
"/",
"tau"
] | Logistic random variates. | [
"Logistic",
"random",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1685-L1691 |
239,212 | pymc-devs/pymc | pymc/distributions.py | rlognormal | def rlognormal(mu, tau, size=None):
"""
Return random lognormal variates.
"""
return np.random.lognormal(mu, np.sqrt(1. / tau), size) | python | def rlognormal(mu, tau, size=None):
return np.random.lognormal(mu, np.sqrt(1. / tau), size) | [
"def",
"rlognormal",
"(",
"mu",
",",
"tau",
",",
"size",
"=",
"None",
")",
":",
"return",
"np",
".",
"random",
".",
"lognormal",
"(",
"mu",
",",
"np",
".",
"sqrt",
"(",
"1.",
"/",
"tau",
")",
",",
"size",
")"
] | Return random lognormal variates. | [
"Return",
"random",
"lognormal",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1726-L1731 |
239,213 | pymc-devs/pymc | pymc/distributions.py | rmultinomial | def rmultinomial(n, p, size=None):
"""
Random multinomial variates.
"""
# Leaving size=None as the default means return value is 1d array
# if not specified-- nicer.
# Single value for p:
if len(np.shape(p)) == 1:
return np.random.multinomial(n, p, size)
# Multiple values for p:
if np.isscalar(n):
n = n * np.ones(np.shape(p)[0], dtype=np.int)
out = np.empty(np.shape(p))
for i in xrange(np.shape(p)[0]):
out[i, :] = np.random.multinomial(n[i], p[i,:], size)
return out | python | def rmultinomial(n, p, size=None):
# Leaving size=None as the default means return value is 1d array
# if not specified-- nicer.
# Single value for p:
if len(np.shape(p)) == 1:
return np.random.multinomial(n, p, size)
# Multiple values for p:
if np.isscalar(n):
n = n * np.ones(np.shape(p)[0], dtype=np.int)
out = np.empty(np.shape(p))
for i in xrange(np.shape(p)[0]):
out[i, :] = np.random.multinomial(n[i], p[i,:], size)
return out | [
"def",
"rmultinomial",
"(",
"n",
",",
"p",
",",
"size",
"=",
"None",
")",
":",
"# Leaving size=None as the default means return value is 1d array",
"# if not specified-- nicer.",
"# Single value for p:",
"if",
"len",
"(",
"np",
".",
"shape",
"(",
"p",
")",
")",
"=="... | Random multinomial variates. | [
"Random",
"multinomial",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1773-L1790 |
239,214 | pymc-devs/pymc | pymc/distributions.py | multinomial_like | def multinomial_like(x, n, p):
R"""
Multinomial log-likelihood.
Generalization of the binomial
distribution, but instead of each trial resulting in "success" or
"failure", each one results in exactly one of some fixed finite number k
of possible outcomes over n independent trials. 'x[i]' indicates the number
of times outcome number i was observed over the n trials.
.. math::
f(x \mid n, p) = \frac{n!}{\prod_{i=1}^k x_i!} \prod_{i=1}^k p_i^{x_i}
:Parameters:
x : (ns, k) int
Random variable indicating the number of time outcome i is
observed. :math:`\sum_{i=1}^k x_i=n`, :math:`x_i \ge 0`.
n : int
Number of trials.
p : (k,)
Probability of each one of the different outcomes.
:math:`\sum_{i=1}^k p_i = 1)`, :math:`p_i \ge 0`.
.. note::
- :math:`E(X_i)=n p_i`
- :math:`Var(X_i)=n p_i(1-p_i)`
- :math:`Cov(X_i,X_j) = -n p_i p_j`
- If :math:`\sum_i p_i < 0.999999` a log-likelihood value of -inf
will be returned.
"""
# flib expects 2d arguments. Do we still want to support multiple p
# values along realizations ?
x = np.atleast_2d(x)
p = np.atleast_2d(p)
return flib.multinomial(x, n, p) | python | def multinomial_like(x, n, p):
R"""
Multinomial log-likelihood.
Generalization of the binomial
distribution, but instead of each trial resulting in "success" or
"failure", each one results in exactly one of some fixed finite number k
of possible outcomes over n independent trials. 'x[i]' indicates the number
of times outcome number i was observed over the n trials.
.. math::
f(x \mid n, p) = \frac{n!}{\prod_{i=1}^k x_i!} \prod_{i=1}^k p_i^{x_i}
:Parameters:
x : (ns, k) int
Random variable indicating the number of time outcome i is
observed. :math:`\sum_{i=1}^k x_i=n`, :math:`x_i \ge 0`.
n : int
Number of trials.
p : (k,)
Probability of each one of the different outcomes.
:math:`\sum_{i=1}^k p_i = 1)`, :math:`p_i \ge 0`.
.. note::
- :math:`E(X_i)=n p_i`
- :math:`Var(X_i)=n p_i(1-p_i)`
- :math:`Cov(X_i,X_j) = -n p_i p_j`
- If :math:`\sum_i p_i < 0.999999` a log-likelihood value of -inf
will be returned.
"""
# flib expects 2d arguments. Do we still want to support multiple p
# values along realizations ?
x = np.atleast_2d(x)
p = np.atleast_2d(p)
return flib.multinomial(x, n, p) | [
"def",
"multinomial_like",
"(",
"x",
",",
"n",
",",
"p",
")",
":",
"# flib expects 2d arguments. Do we still want to support multiple p",
"# values along realizations ?",
"x",
"=",
"np",
".",
"atleast_2d",
"(",
"x",
")",
"p",
"=",
"np",
".",
"atleast_2d",
"(",
"p"... | R"""
Multinomial log-likelihood.
Generalization of the binomial
distribution, but instead of each trial resulting in "success" or
"failure", each one results in exactly one of some fixed finite number k
of possible outcomes over n independent trials. 'x[i]' indicates the number
of times outcome number i was observed over the n trials.
.. math::
f(x \mid n, p) = \frac{n!}{\prod_{i=1}^k x_i!} \prod_{i=1}^k p_i^{x_i}
:Parameters:
x : (ns, k) int
Random variable indicating the number of time outcome i is
observed. :math:`\sum_{i=1}^k x_i=n`, :math:`x_i \ge 0`.
n : int
Number of trials.
p : (k,)
Probability of each one of the different outcomes.
:math:`\sum_{i=1}^k p_i = 1)`, :math:`p_i \ge 0`.
.. note::
- :math:`E(X_i)=n p_i`
- :math:`Var(X_i)=n p_i(1-p_i)`
- :math:`Cov(X_i,X_j) = -n p_i p_j`
- If :math:`\sum_i p_i < 0.999999` a log-likelihood value of -inf
will be returned. | [
"R",
"Multinomial",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1800-L1836 |
239,215 | pymc-devs/pymc | pymc/distributions.py | rmultivariate_hypergeometric | def rmultivariate_hypergeometric(n, m, size=None):
"""
Random multivariate hypergeometric variates.
Parameters:
- `n` : Number of draws.
- `m` : Number of items in each categoy.
"""
N = len(m)
urn = np.repeat(np.arange(N), m)
if size:
draw = np.array([[urn[i] for i in np.random.permutation(len(urn))[:n]]
for j in range(size)])
r = [[np.sum(draw[j] == i) for i in range(len(m))]
for j in range(size)]
else:
draw = np.array([urn[i] for i in np.random.permutation(len(urn))[:n]])
r = [np.sum(draw == i) for i in range(len(m))]
return np.asarray(r) | python | def rmultivariate_hypergeometric(n, m, size=None):
N = len(m)
urn = np.repeat(np.arange(N), m)
if size:
draw = np.array([[urn[i] for i in np.random.permutation(len(urn))[:n]]
for j in range(size)])
r = [[np.sum(draw[j] == i) for i in range(len(m))]
for j in range(size)]
else:
draw = np.array([urn[i] for i in np.random.permutation(len(urn))[:n]])
r = [np.sum(draw == i) for i in range(len(m))]
return np.asarray(r) | [
"def",
"rmultivariate_hypergeometric",
"(",
"n",
",",
"m",
",",
"size",
"=",
"None",
")",
":",
"N",
"=",
"len",
"(",
"m",
")",
"urn",
"=",
"np",
".",
"repeat",
"(",
"np",
".",
"arange",
"(",
"N",
")",
",",
"m",
")",
"if",
"size",
":",
"draw",
... | Random multivariate hypergeometric variates.
Parameters:
- `n` : Number of draws.
- `m` : Number of items in each categoy. | [
"Random",
"multivariate",
"hypergeometric",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1841-L1863 |
239,216 | pymc-devs/pymc | pymc/distributions.py | multivariate_hypergeometric_expval | def multivariate_hypergeometric_expval(n, m):
"""
Expected value of multivariate hypergeometric distribution.
Parameters:
- `n` : Number of draws.
- `m` : Number of items in each categoy.
"""
m = np.asarray(m, float)
return n * (m / m.sum()) | python | def multivariate_hypergeometric_expval(n, m):
m = np.asarray(m, float)
return n * (m / m.sum()) | [
"def",
"multivariate_hypergeometric_expval",
"(",
"n",
",",
"m",
")",
":",
"m",
"=",
"np",
".",
"asarray",
"(",
"m",
",",
"float",
")",
"return",
"n",
"*",
"(",
"m",
"/",
"m",
".",
"sum",
"(",
")",
")"
] | Expected value of multivariate hypergeometric distribution.
Parameters:
- `n` : Number of draws.
- `m` : Number of items in each categoy. | [
"Expected",
"value",
"of",
"multivariate",
"hypergeometric",
"distribution",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1866-L1875 |
239,217 | pymc-devs/pymc | pymc/distributions.py | mv_normal_like | def mv_normal_like(x, mu, tau):
R"""
Multivariate normal log-likelihood
.. math::
f(x \mid \pi, T) = \frac{|T|^{1/2}}{(2\pi)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}T(x-\mu) \right\}
:Parameters:
- `x` : (n,k)
- `mu` : (k) Location parameter sequence.
- `Tau` : (k,k) Positive definite precision matrix.
.. seealso:: :func:`mv_normal_chol_like`, :func:`mv_normal_cov_like`
"""
# TODO: Vectorize in Fortran
if len(np.shape(x)) > 1:
return np.sum([flib.prec_mvnorm(r, mu, tau) for r in x])
else:
return flib.prec_mvnorm(x, mu, tau) | python | def mv_normal_like(x, mu, tau):
R"""
Multivariate normal log-likelihood
.. math::
f(x \mid \pi, T) = \frac{|T|^{1/2}}{(2\pi)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}T(x-\mu) \right\}
:Parameters:
- `x` : (n,k)
- `mu` : (k) Location parameter sequence.
- `Tau` : (k,k) Positive definite precision matrix.
.. seealso:: :func:`mv_normal_chol_like`, :func:`mv_normal_cov_like`
"""
# TODO: Vectorize in Fortran
if len(np.shape(x)) > 1:
return np.sum([flib.prec_mvnorm(r, mu, tau) for r in x])
else:
return flib.prec_mvnorm(x, mu, tau) | [
"def",
"mv_normal_like",
"(",
"x",
",",
"mu",
",",
"tau",
")",
":",
"# TODO: Vectorize in Fortran",
"if",
"len",
"(",
"np",
".",
"shape",
"(",
"x",
")",
")",
">",
"1",
":",
"return",
"np",
".",
"sum",
"(",
"[",
"flib",
".",
"prec_mvnorm",
"(",
"r",... | R"""
Multivariate normal log-likelihood
.. math::
f(x \mid \pi, T) = \frac{|T|^{1/2}}{(2\pi)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}T(x-\mu) \right\}
:Parameters:
- `x` : (n,k)
- `mu` : (k) Location parameter sequence.
- `Tau` : (k,k) Positive definite precision matrix.
.. seealso:: :func:`mv_normal_chol_like`, :func:`mv_normal_cov_like` | [
"R",
"Multivariate",
"normal",
"log",
"-",
"likelihood"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1939-L1958 |
239,218 | pymc-devs/pymc | pymc/distributions.py | mv_normal_cov_like | def mv_normal_cov_like(x, mu, C):
R"""
Multivariate normal log-likelihood parameterized by a covariance
matrix.
.. math::
f(x \mid \pi, C) = \frac{1}{(2\pi|C|)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}C^{-1}(x-\mu) \right\}
:Parameters:
- `x` : (n,k)
- `mu` : (k) Location parameter.
- `C` : (k,k) Positive definite covariance matrix.
.. seealso:: :func:`mv_normal_like`, :func:`mv_normal_chol_like`
"""
# TODO: Vectorize in Fortran
if len(np.shape(x)) > 1:
return np.sum([flib.cov_mvnorm(r, mu, C) for r in x])
else:
return flib.cov_mvnorm(x, mu, C) | python | def mv_normal_cov_like(x, mu, C):
R"""
Multivariate normal log-likelihood parameterized by a covariance
matrix.
.. math::
f(x \mid \pi, C) = \frac{1}{(2\pi|C|)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}C^{-1}(x-\mu) \right\}
:Parameters:
- `x` : (n,k)
- `mu` : (k) Location parameter.
- `C` : (k,k) Positive definite covariance matrix.
.. seealso:: :func:`mv_normal_like`, :func:`mv_normal_chol_like`
"""
# TODO: Vectorize in Fortran
if len(np.shape(x)) > 1:
return np.sum([flib.cov_mvnorm(r, mu, C) for r in x])
else:
return flib.cov_mvnorm(x, mu, C) | [
"def",
"mv_normal_cov_like",
"(",
"x",
",",
"mu",
",",
"C",
")",
":",
"# TODO: Vectorize in Fortran",
"if",
"len",
"(",
"np",
".",
"shape",
"(",
"x",
")",
")",
">",
"1",
":",
"return",
"np",
".",
"sum",
"(",
"[",
"flib",
".",
"cov_mvnorm",
"(",
"r"... | R"""
Multivariate normal log-likelihood parameterized by a covariance
matrix.
.. math::
f(x \mid \pi, C) = \frac{1}{(2\pi|C|)^{1/2}} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}C^{-1}(x-\mu) \right\}
:Parameters:
- `x` : (n,k)
- `mu` : (k) Location parameter.
- `C` : (k,k) Positive definite covariance matrix.
.. seealso:: :func:`mv_normal_like`, :func:`mv_normal_chol_like` | [
"R",
"Multivariate",
"normal",
"log",
"-",
"likelihood",
"parameterized",
"by",
"a",
"covariance",
"matrix",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L1982-L2002 |
239,219 | pymc-devs/pymc | pymc/distributions.py | mv_normal_chol_like | def mv_normal_chol_like(x, mu, sig):
R"""
Multivariate normal log-likelihood.
.. math::
f(x \mid \pi, \sigma) = \frac{1}{(2\pi)^{1/2}|\sigma|)} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}(\sigma \sigma^{\prime})^{-1}(x-\mu) \right\}
:Parameters:
- `x` : (n,k)
- `mu` : (k) Location parameter.
- `sigma` : (k,k) Lower triangular matrix.
.. seealso:: :func:`mv_normal_like`, :func:`mv_normal_cov_like`
"""
# TODO: Vectorize in Fortran
if len(np.shape(x)) > 1:
return np.sum([flib.chol_mvnorm(r, mu, sig) for r in x])
else:
return flib.chol_mvnorm(x, mu, sig) | python | def mv_normal_chol_like(x, mu, sig):
R"""
Multivariate normal log-likelihood.
.. math::
f(x \mid \pi, \sigma) = \frac{1}{(2\pi)^{1/2}|\sigma|)} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}(\sigma \sigma^{\prime})^{-1}(x-\mu) \right\}
:Parameters:
- `x` : (n,k)
- `mu` : (k) Location parameter.
- `sigma` : (k,k) Lower triangular matrix.
.. seealso:: :func:`mv_normal_like`, :func:`mv_normal_cov_like`
"""
# TODO: Vectorize in Fortran
if len(np.shape(x)) > 1:
return np.sum([flib.chol_mvnorm(r, mu, sig) for r in x])
else:
return flib.chol_mvnorm(x, mu, sig) | [
"def",
"mv_normal_chol_like",
"(",
"x",
",",
"mu",
",",
"sig",
")",
":",
"# TODO: Vectorize in Fortran",
"if",
"len",
"(",
"np",
".",
"shape",
"(",
"x",
")",
")",
">",
"1",
":",
"return",
"np",
".",
"sum",
"(",
"[",
"flib",
".",
"chol_mvnorm",
"(",
... | R"""
Multivariate normal log-likelihood.
.. math::
f(x \mid \pi, \sigma) = \frac{1}{(2\pi)^{1/2}|\sigma|)} \exp\left\{ -\frac{1}{2} (x-\mu)^{\prime}(\sigma \sigma^{\prime})^{-1}(x-\mu) \right\}
:Parameters:
- `x` : (n,k)
- `mu` : (k) Location parameter.
- `sigma` : (k,k) Lower triangular matrix.
.. seealso:: :func:`mv_normal_like`, :func:`mv_normal_cov_like` | [
"R",
"Multivariate",
"normal",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2041-L2060 |
239,220 | pymc-devs/pymc | pymc/distributions.py | rnegative_binomial | def rnegative_binomial(mu, alpha, size=None):
"""
Random negative binomial variates.
"""
# Using gamma-poisson mixture rather than numpy directly
# because numpy apparently rounds
mu = np.asarray(mu, dtype=float)
pois_mu = np.random.gamma(alpha, mu / alpha, size)
return np.random.poisson(pois_mu, size) | python | def rnegative_binomial(mu, alpha, size=None):
# Using gamma-poisson mixture rather than numpy directly
# because numpy apparently rounds
mu = np.asarray(mu, dtype=float)
pois_mu = np.random.gamma(alpha, mu / alpha, size)
return np.random.poisson(pois_mu, size) | [
"def",
"rnegative_binomial",
"(",
"mu",
",",
"alpha",
",",
"size",
"=",
"None",
")",
":",
"# Using gamma-poisson mixture rather than numpy directly",
"# because numpy apparently rounds",
"mu",
"=",
"np",
".",
"asarray",
"(",
"mu",
",",
"dtype",
"=",
"float",
")",
... | Random negative binomial variates. | [
"Random",
"negative",
"binomial",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2065-L2073 |
239,221 | pymc-devs/pymc | pymc/distributions.py | negative_binomial_like | def negative_binomial_like(x, mu, alpha):
R"""
Negative binomial log-likelihood.
The negative binomial
distribution describes a Poisson random variable whose rate
parameter is gamma distributed. PyMC's chosen parameterization is
based on this mixture interpretation.
.. math::
f(x \mid \mu, \alpha) = \frac{\Gamma(x+\alpha)}{x! \Gamma(\alpha)} (\alpha/(\mu+\alpha))^\alpha (\mu/(\mu+\alpha))^x
:Parameters:
- `x` : x = 0,1,2,...
- `mu` : mu > 0
- `alpha` : alpha > 0
.. note::
- :math:`E[x]=\mu`
- In Wikipedia's parameterization,
:math:`r=\alpha`,
:math:`p=\mu/(\mu+\alpha)`,
:math:`\mu=rp/(1-p)`
"""
alpha = np.array(alpha)
if (alpha > 1e10).any():
if (alpha > 1e10).all():
# Return Poisson when alpha gets very large
return flib.poisson(x, mu)
# Split big and small dispersion values
big = alpha > 1e10
return flib.poisson(x[big], mu[big]) + flib.negbin2(x[big - True],
mu[big - True], alpha[big - True])
return flib.negbin2(x, mu, alpha) | python | def negative_binomial_like(x, mu, alpha):
R"""
Negative binomial log-likelihood.
The negative binomial
distribution describes a Poisson random variable whose rate
parameter is gamma distributed. PyMC's chosen parameterization is
based on this mixture interpretation.
.. math::
f(x \mid \mu, \alpha) = \frac{\Gamma(x+\alpha)}{x! \Gamma(\alpha)} (\alpha/(\mu+\alpha))^\alpha (\mu/(\mu+\alpha))^x
:Parameters:
- `x` : x = 0,1,2,...
- `mu` : mu > 0
- `alpha` : alpha > 0
.. note::
- :math:`E[x]=\mu`
- In Wikipedia's parameterization,
:math:`r=\alpha`,
:math:`p=\mu/(\mu+\alpha)`,
:math:`\mu=rp/(1-p)`
"""
alpha = np.array(alpha)
if (alpha > 1e10).any():
if (alpha > 1e10).all():
# Return Poisson when alpha gets very large
return flib.poisson(x, mu)
# Split big and small dispersion values
big = alpha > 1e10
return flib.poisson(x[big], mu[big]) + flib.negbin2(x[big - True],
mu[big - True], alpha[big - True])
return flib.negbin2(x, mu, alpha) | [
"def",
"negative_binomial_like",
"(",
"x",
",",
"mu",
",",
"alpha",
")",
":",
"alpha",
"=",
"np",
".",
"array",
"(",
"alpha",
")",
"if",
"(",
"alpha",
">",
"1e10",
")",
".",
"any",
"(",
")",
":",
"if",
"(",
"alpha",
">",
"1e10",
")",
".",
"all"... | R"""
Negative binomial log-likelihood.
The negative binomial
distribution describes a Poisson random variable whose rate
parameter is gamma distributed. PyMC's chosen parameterization is
based on this mixture interpretation.
.. math::
f(x \mid \mu, \alpha) = \frac{\Gamma(x+\alpha)}{x! \Gamma(\alpha)} (\alpha/(\mu+\alpha))^\alpha (\mu/(\mu+\alpha))^x
:Parameters:
- `x` : x = 0,1,2,...
- `mu` : mu > 0
- `alpha` : alpha > 0
.. note::
- :math:`E[x]=\mu`
- In Wikipedia's parameterization,
:math:`r=\alpha`,
:math:`p=\mu/(\mu+\alpha)`,
:math:`\mu=rp/(1-p)` | [
"R",
"Negative",
"binomial",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2084-L2119 |
239,222 | pymc-devs/pymc | pymc/distributions.py | rnormal | def rnormal(mu, tau, size=None):
"""
Random normal variates.
"""
return np.random.normal(mu, 1. / np.sqrt(tau), size) | python | def rnormal(mu, tau, size=None):
return np.random.normal(mu, 1. / np.sqrt(tau), size) | [
"def",
"rnormal",
"(",
"mu",
",",
"tau",
",",
"size",
"=",
"None",
")",
":",
"return",
"np",
".",
"random",
".",
"normal",
"(",
"mu",
",",
"1.",
"/",
"np",
".",
"sqrt",
"(",
"tau",
")",
",",
"size",
")"
] | Random normal variates. | [
"Random",
"normal",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2128-L2132 |
239,223 | pymc-devs/pymc | pymc/distributions.py | rvon_mises | def rvon_mises(mu, kappa, size=None):
"""
Random von Mises variates.
"""
# TODO: Just return straight from numpy after release 1.3
return (np.random.mtrand.vonmises(
mu, kappa, size) + np.pi) % (2. * np.pi) - np.pi | python | def rvon_mises(mu, kappa, size=None):
# TODO: Just return straight from numpy after release 1.3
return (np.random.mtrand.vonmises(
mu, kappa, size) + np.pi) % (2. * np.pi) - np.pi | [
"def",
"rvon_mises",
"(",
"mu",
",",
"kappa",
",",
"size",
"=",
"None",
")",
":",
"# TODO: Just return straight from numpy after release 1.3",
"return",
"(",
"np",
".",
"random",
".",
"mtrand",
".",
"vonmises",
"(",
"mu",
",",
"kappa",
",",
"size",
")",
"+",... | Random von Mises variates. | [
"Random",
"von",
"Mises",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2191-L2197 |
239,224 | pymc-devs/pymc | pymc/distributions.py | rtruncated_pareto | def rtruncated_pareto(alpha, m, b, size=None):
"""
Random bounded Pareto variates.
"""
u = random_number(size)
return (-(u * b ** alpha - u * m ** alpha - b ** alpha) /
(b ** alpha * m ** alpha)) ** (-1. / alpha) | python | def rtruncated_pareto(alpha, m, b, size=None):
u = random_number(size)
return (-(u * b ** alpha - u * m ** alpha - b ** alpha) /
(b ** alpha * m ** alpha)) ** (-1. / alpha) | [
"def",
"rtruncated_pareto",
"(",
"alpha",
",",
"m",
",",
"b",
",",
"size",
"=",
"None",
")",
":",
"u",
"=",
"random_number",
"(",
"size",
")",
"return",
"(",
"-",
"(",
"u",
"*",
"b",
"**",
"alpha",
"-",
"u",
"*",
"m",
"**",
"alpha",
"-",
"b",
... | Random bounded Pareto variates. | [
"Random",
"bounded",
"Pareto",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2274-L2280 |
239,225 | pymc-devs/pymc | pymc/distributions.py | truncated_pareto_expval | def truncated_pareto_expval(alpha, m, b):
"""
Expected value of truncated Pareto distribution.
"""
if alpha <= 1:
return inf
part1 = (m ** alpha) / (1. - (m / b) ** alpha)
part2 = 1. * alpha / (alpha - 1)
part3 = (1. / (m ** (alpha - 1)) - 1. / (b ** (alpha - 1.)))
return part1 * part2 * part3 | python | def truncated_pareto_expval(alpha, m, b):
if alpha <= 1:
return inf
part1 = (m ** alpha) / (1. - (m / b) ** alpha)
part2 = 1. * alpha / (alpha - 1)
part3 = (1. / (m ** (alpha - 1)) - 1. / (b ** (alpha - 1.)))
return part1 * part2 * part3 | [
"def",
"truncated_pareto_expval",
"(",
"alpha",
",",
"m",
",",
"b",
")",
":",
"if",
"alpha",
"<=",
"1",
":",
"return",
"inf",
"part1",
"=",
"(",
"m",
"**",
"alpha",
")",
"/",
"(",
"1.",
"-",
"(",
"m",
"/",
"b",
")",
"**",
"alpha",
")",
"part2",... | Expected value of truncated Pareto distribution. | [
"Expected",
"value",
"of",
"truncated",
"Pareto",
"distribution",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2283-L2293 |
239,226 | pymc-devs/pymc | pymc/distributions.py | rtruncated_poisson | def rtruncated_poisson(mu, k, size=None):
"""
Random truncated Poisson variates with minimum value k, generated
using rejection sampling.
"""
# Calculate m
try:
m = max(0, np.floor(k - mu))
except (TypeError, ValueError):
# More than one mu
return np.array([rtruncated_poisson(x, i)
for x, i in zip(mu, np.resize(k, np.size(mu)))]).squeeze()
k -= 1
# Calculate constant for acceptance probability
C = np.exp(flib.factln(k + 1) - flib.factln(k + 1 - m))
# Empty array to hold random variates
rvs = np.empty(0, int)
total_size = np.prod(size or 1)
while(len(rvs) < total_size):
# Propose values by sampling from untruncated Poisson with mean mu + m
proposals = np.random.poisson(
mu + m, (total_size * 4, np.size(m))).squeeze()
# Acceptance probability
a = C * np.array([np.exp(flib.factln(y - m) - flib.factln(y))
for y in proposals])
a *= proposals > k
# Uniform random variates
u = np.random.random(total_size * 4)
rvs = np.append(rvs, proposals[u < a])
return np.reshape(rvs[:total_size], size) | python | def rtruncated_poisson(mu, k, size=None):
# Calculate m
try:
m = max(0, np.floor(k - mu))
except (TypeError, ValueError):
# More than one mu
return np.array([rtruncated_poisson(x, i)
for x, i in zip(mu, np.resize(k, np.size(mu)))]).squeeze()
k -= 1
# Calculate constant for acceptance probability
C = np.exp(flib.factln(k + 1) - flib.factln(k + 1 - m))
# Empty array to hold random variates
rvs = np.empty(0, int)
total_size = np.prod(size or 1)
while(len(rvs) < total_size):
# Propose values by sampling from untruncated Poisson with mean mu + m
proposals = np.random.poisson(
mu + m, (total_size * 4, np.size(m))).squeeze()
# Acceptance probability
a = C * np.array([np.exp(flib.factln(y - m) - flib.factln(y))
for y in proposals])
a *= proposals > k
# Uniform random variates
u = np.random.random(total_size * 4)
rvs = np.append(rvs, proposals[u < a])
return np.reshape(rvs[:total_size], size) | [
"def",
"rtruncated_poisson",
"(",
"mu",
",",
"k",
",",
"size",
"=",
"None",
")",
":",
"# Calculate m",
"try",
":",
"m",
"=",
"max",
"(",
"0",
",",
"np",
".",
"floor",
"(",
"k",
"-",
"mu",
")",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
"... | Random truncated Poisson variates with minimum value k, generated
using rejection sampling. | [
"Random",
"truncated",
"Poisson",
"variates",
"with",
"minimum",
"value",
"k",
"generated",
"using",
"rejection",
"sampling",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2365-L2404 |
239,227 | pymc-devs/pymc | pymc/distributions.py | rtruncated_normal | def rtruncated_normal(mu, tau, a=-np.inf, b=np.inf, size=None):
"""
Random truncated normal variates.
"""
sigma = 1. / np.sqrt(tau)
na = utils.normcdf((a - mu) / sigma)
nb = utils.normcdf((b - mu) / sigma)
# Use the inverse CDF generation method.
U = np.random.mtrand.uniform(size=size)
q = U * nb + (1 - U) * na
R = utils.invcdf(q)
# Unnormalize
return R * sigma + mu | python | def rtruncated_normal(mu, tau, a=-np.inf, b=np.inf, size=None):
sigma = 1. / np.sqrt(tau)
na = utils.normcdf((a - mu) / sigma)
nb = utils.normcdf((b - mu) / sigma)
# Use the inverse CDF generation method.
U = np.random.mtrand.uniform(size=size)
q = U * nb + (1 - U) * na
R = utils.invcdf(q)
# Unnormalize
return R * sigma + mu | [
"def",
"rtruncated_normal",
"(",
"mu",
",",
"tau",
",",
"a",
"=",
"-",
"np",
".",
"inf",
",",
"b",
"=",
"np",
".",
"inf",
",",
"size",
"=",
"None",
")",
":",
"sigma",
"=",
"1.",
"/",
"np",
".",
"sqrt",
"(",
"tau",
")",
"na",
"=",
"utils",
"... | Random truncated normal variates. | [
"Random",
"truncated",
"normal",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2447-L2462 |
239,228 | pymc-devs/pymc | pymc/distributions.py | truncated_normal_expval | def truncated_normal_expval(mu, tau, a, b):
"""Expected value of the truncated normal distribution.
.. math::
E(X) =\mu + \frac{\sigma(\varphi_1-\varphi_2)}{T}
where
.. math::
T & =\Phi\left(\frac{B-\mu}{\sigma}\right)-\Phi
\left(\frac{A-\mu}{\sigma}\right)\text \\
\varphi_1 &=
\varphi\left(\frac{A-\mu}{\sigma}\right) \\
\varphi_2 &=
\varphi\left(\frac{B-\mu}{\sigma}\right) \\
and :math:`\varphi = N(0,1)` and :math:`tau & 1/sigma**2`.
:Parameters:
- `mu` : Mean of the distribution.
- `tau` : Precision of the distribution, which corresponds to 1/sigma**2 (tau > 0).
- `a` : Left bound of the distribution.
- `b` : Right bound of the distribution.
"""
phia = np.exp(normal_like(a, mu, tau))
phib = np.exp(normal_like(b, mu, tau))
sigma = 1. / np.sqrt(tau)
Phia = utils.normcdf((a - mu) / sigma)
if b == np.inf:
Phib = 1.0
else:
Phib = utils.normcdf((b - mu) / sigma)
return (mu + (phia - phib) / (Phib - Phia))[0] | python | def truncated_normal_expval(mu, tau, a, b):
phia = np.exp(normal_like(a, mu, tau))
phib = np.exp(normal_like(b, mu, tau))
sigma = 1. / np.sqrt(tau)
Phia = utils.normcdf((a - mu) / sigma)
if b == np.inf:
Phib = 1.0
else:
Phib = utils.normcdf((b - mu) / sigma)
return (mu + (phia - phib) / (Phib - Phia))[0] | [
"def",
"truncated_normal_expval",
"(",
"mu",
",",
"tau",
",",
"a",
",",
"b",
")",
":",
"phia",
"=",
"np",
".",
"exp",
"(",
"normal_like",
"(",
"a",
",",
"mu",
",",
"tau",
")",
")",
"phib",
"=",
"np",
".",
"exp",
"(",
"normal_like",
"(",
"b",
",... | Expected value of the truncated normal distribution.
.. math::
E(X) =\mu + \frac{\sigma(\varphi_1-\varphi_2)}{T}
where
.. math::
T & =\Phi\left(\frac{B-\mu}{\sigma}\right)-\Phi
\left(\frac{A-\mu}{\sigma}\right)\text \\
\varphi_1 &=
\varphi\left(\frac{A-\mu}{\sigma}\right) \\
\varphi_2 &=
\varphi\left(\frac{B-\mu}{\sigma}\right) \\
and :math:`\varphi = N(0,1)` and :math:`tau & 1/sigma**2`.
:Parameters:
- `mu` : Mean of the distribution.
- `tau` : Precision of the distribution, which corresponds to 1/sigma**2 (tau > 0).
- `a` : Left bound of the distribution.
- `b` : Right bound of the distribution. | [
"Expected",
"value",
"of",
"the",
"truncated",
"normal",
"distribution",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2467-L2501 |
239,229 | pymc-devs/pymc | pymc/distributions.py | truncated_normal_like | def truncated_normal_like(x, mu, tau, a=None, b=None):
R"""
Truncated normal log-likelihood.
.. math::
f(x \mid \mu, \tau, a, b) = \frac{\phi(\frac{x-\mu}{\sigma})} {\Phi(\frac{b-\mu}{\sigma}) - \Phi(\frac{a-\mu}{\sigma})},
where :math:`\sigma^2=1/\tau`, `\phi` is the standard normal PDF and `\Phi` is the standard normal CDF.
:Parameters:
- `x` : Input data.
- `mu` : Mean of the distribution.
- `tau` : Precision of the distribution, which corresponds to 1/sigma**2 (tau > 0).
- `a` : Left bound of the distribution.
- `b` : Right bound of the distribution.
"""
x = np.atleast_1d(x)
if a is None:
a = -np.inf
a = np.atleast_1d(a)
if b is None:
b = np.inf
b = np.atleast_1d(b)
mu = np.atleast_1d(mu)
sigma = (1. / np.atleast_1d(np.sqrt(tau)))
if (x < a).any() or (x > b).any():
return -np.inf
else:
n = len(x)
phi = normal_like(x, mu, tau)
lPhia = utils.normcdf((a - mu) / sigma, log=True)
lPhib = utils.normcdf((b - mu) / sigma, log=True)
try:
d = utils.log_difference(lPhib, lPhia)
except ValueError:
return -np.inf
# d = np.log(Phib-Phia)
if len(d) == n:
Phi = d.sum()
else:
Phi = n * d
if np.isnan(Phi) or np.isinf(Phi):
return -np.inf
return phi - Phi | python | def truncated_normal_like(x, mu, tau, a=None, b=None):
R"""
Truncated normal log-likelihood.
.. math::
f(x \mid \mu, \tau, a, b) = \frac{\phi(\frac{x-\mu}{\sigma})} {\Phi(\frac{b-\mu}{\sigma}) - \Phi(\frac{a-\mu}{\sigma})},
where :math:`\sigma^2=1/\tau`, `\phi` is the standard normal PDF and `\Phi` is the standard normal CDF.
:Parameters:
- `x` : Input data.
- `mu` : Mean of the distribution.
- `tau` : Precision of the distribution, which corresponds to 1/sigma**2 (tau > 0).
- `a` : Left bound of the distribution.
- `b` : Right bound of the distribution.
"""
x = np.atleast_1d(x)
if a is None:
a = -np.inf
a = np.atleast_1d(a)
if b is None:
b = np.inf
b = np.atleast_1d(b)
mu = np.atleast_1d(mu)
sigma = (1. / np.atleast_1d(np.sqrt(tau)))
if (x < a).any() or (x > b).any():
return -np.inf
else:
n = len(x)
phi = normal_like(x, mu, tau)
lPhia = utils.normcdf((a - mu) / sigma, log=True)
lPhib = utils.normcdf((b - mu) / sigma, log=True)
try:
d = utils.log_difference(lPhib, lPhia)
except ValueError:
return -np.inf
# d = np.log(Phib-Phia)
if len(d) == n:
Phi = d.sum()
else:
Phi = n * d
if np.isnan(Phi) or np.isinf(Phi):
return -np.inf
return phi - Phi | [
"def",
"truncated_normal_like",
"(",
"x",
",",
"mu",
",",
"tau",
",",
"a",
"=",
"None",
",",
"b",
"=",
"None",
")",
":",
"x",
"=",
"np",
".",
"atleast_1d",
"(",
"x",
")",
"if",
"a",
"is",
"None",
":",
"a",
"=",
"-",
"np",
".",
"inf",
"a",
"... | R"""
Truncated normal log-likelihood.
.. math::
f(x \mid \mu, \tau, a, b) = \frac{\phi(\frac{x-\mu}{\sigma})} {\Phi(\frac{b-\mu}{\sigma}) - \Phi(\frac{a-\mu}{\sigma})},
where :math:`\sigma^2=1/\tau`, `\phi` is the standard normal PDF and `\Phi` is the standard normal CDF.
:Parameters:
- `x` : Input data.
- `mu` : Mean of the distribution.
- `tau` : Precision of the distribution, which corresponds to 1/sigma**2 (tau > 0).
- `a` : Left bound of the distribution.
- `b` : Right bound of the distribution. | [
"R",
"Truncated",
"normal",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2506-L2549 |
239,230 | pymc-devs/pymc | pymc/distributions.py | rskew_normal | def rskew_normal(mu, tau, alpha, size=()):
"""
Skew-normal random variates.
"""
size_ = size or (1,)
len_ = np.prod(size_)
return flib.rskewnorm(
len_, mu, tau, alpha, np.random.normal(size=2 * len_)).reshape(size) | python | def rskew_normal(mu, tau, alpha, size=()):
size_ = size or (1,)
len_ = np.prod(size_)
return flib.rskewnorm(
len_, mu, tau, alpha, np.random.normal(size=2 * len_)).reshape(size) | [
"def",
"rskew_normal",
"(",
"mu",
",",
"tau",
",",
"alpha",
",",
"size",
"=",
"(",
")",
")",
":",
"size_",
"=",
"size",
"or",
"(",
"1",
",",
")",
"len_",
"=",
"np",
".",
"prod",
"(",
"size_",
")",
"return",
"flib",
".",
"rskewnorm",
"(",
"len_"... | Skew-normal random variates. | [
"Skew",
"-",
"normal",
"random",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2557-L2564 |
239,231 | pymc-devs/pymc | pymc/distributions.py | skew_normal_expval | def skew_normal_expval(mu, tau, alpha):
"""
Expectation of skew-normal random variables.
"""
delta = alpha / np.sqrt(1. + alpha ** 2)
return mu + np.sqrt(2 / pi / tau) * delta | python | def skew_normal_expval(mu, tau, alpha):
delta = alpha / np.sqrt(1. + alpha ** 2)
return mu + np.sqrt(2 / pi / tau) * delta | [
"def",
"skew_normal_expval",
"(",
"mu",
",",
"tau",
",",
"alpha",
")",
":",
"delta",
"=",
"alpha",
"/",
"np",
".",
"sqrt",
"(",
"1.",
"+",
"alpha",
"**",
"2",
")",
"return",
"mu",
"+",
"np",
".",
"sqrt",
"(",
"2",
"/",
"pi",
"/",
"tau",
")",
... | Expectation of skew-normal random variables. | [
"Expectation",
"of",
"skew",
"-",
"normal",
"random",
"variables",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2567-L2572 |
239,232 | pymc-devs/pymc | pymc/distributions.py | skew_normal_like | def skew_normal_like(x, mu, tau, alpha):
R"""
Azzalini's skew-normal log-likelihood
.. math::
f(x \mid \mu, \tau, \alpha) = 2 \Phi((x-\mu)\sqrt{\tau}\alpha) \phi(x,\mu,\tau)
where :math:\Phi is the normal CDF and :math: \phi is the normal PDF.
:Parameters:
- `x` : Input data.
- `mu` : Mean of the distribution.
- `tau` : Precision of the distribution (> 0).
- `alpha` : Shape parameter of the distribution.
.. note::
See http://azzalini.stat.unipd.it/SN/
"""
return flib.sn_like(x, mu, tau, alpha) | python | def skew_normal_like(x, mu, tau, alpha):
R"""
Azzalini's skew-normal log-likelihood
.. math::
f(x \mid \mu, \tau, \alpha) = 2 \Phi((x-\mu)\sqrt{\tau}\alpha) \phi(x,\mu,\tau)
where :math:\Phi is the normal CDF and :math: \phi is the normal PDF.
:Parameters:
- `x` : Input data.
- `mu` : Mean of the distribution.
- `tau` : Precision of the distribution (> 0).
- `alpha` : Shape parameter of the distribution.
.. note::
See http://azzalini.stat.unipd.it/SN/
"""
return flib.sn_like(x, mu, tau, alpha) | [
"def",
"skew_normal_like",
"(",
"x",
",",
"mu",
",",
"tau",
",",
"alpha",
")",
":",
"return",
"flib",
".",
"sn_like",
"(",
"x",
",",
"mu",
",",
"tau",
",",
"alpha",
")"
] | R"""
Azzalini's skew-normal log-likelihood
.. math::
f(x \mid \mu, \tau, \alpha) = 2 \Phi((x-\mu)\sqrt{\tau}\alpha) \phi(x,\mu,\tau)
where :math:\Phi is the normal CDF and :math: \phi is the normal PDF.
:Parameters:
- `x` : Input data.
- `mu` : Mean of the distribution.
- `tau` : Precision of the distribution (> 0).
- `alpha` : Shape parameter of the distribution.
.. note::
See http://azzalini.stat.unipd.it/SN/ | [
"R",
"Azzalini",
"s",
"skew",
"-",
"normal",
"log",
"-",
"likelihood"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2575-L2593 |
239,233 | pymc-devs/pymc | pymc/distributions.py | rt | def rt(nu, size=None):
"""
Student's t random variates.
"""
return rnormal(0, 1, size) / np.sqrt(rchi2(nu, size) / nu) | python | def rt(nu, size=None):
return rnormal(0, 1, size) / np.sqrt(rchi2(nu, size) / nu) | [
"def",
"rt",
"(",
"nu",
",",
"size",
"=",
"None",
")",
":",
"return",
"rnormal",
"(",
"0",
",",
"1",
",",
"size",
")",
"/",
"np",
".",
"sqrt",
"(",
"rchi2",
"(",
"nu",
",",
"size",
")",
"/",
"nu",
")"
] | Student's t random variates. | [
"Student",
"s",
"t",
"random",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2598-L2602 |
239,234 | pymc-devs/pymc | pymc/distributions.py | t_like | def t_like(x, nu):
R"""
Student's T log-likelihood.
Describes a zero-mean normal variable
whose precision is gamma distributed. Alternatively, describes the
mean of several zero-mean normal random variables divided by their
sample standard deviation.
.. math::
f(x \mid \nu) = \frac{\Gamma(\frac{\nu+1}{2})}{\Gamma(\frac{\nu}{2}) \sqrt{\nu\pi}} \left( 1 + \frac{x^2}{\nu} \right)^{-\frac{\nu+1}{2}}
:Parameters:
- `x` : Input data.
- `nu` : Degrees of freedom.
"""
nu = np.asarray(nu)
return flib.t(x, nu) | python | def t_like(x, nu):
R"""
Student's T log-likelihood.
Describes a zero-mean normal variable
whose precision is gamma distributed. Alternatively, describes the
mean of several zero-mean normal random variables divided by their
sample standard deviation.
.. math::
f(x \mid \nu) = \frac{\Gamma(\frac{\nu+1}{2})}{\Gamma(\frac{\nu}{2}) \sqrt{\nu\pi}} \left( 1 + \frac{x^2}{\nu} \right)^{-\frac{\nu+1}{2}}
:Parameters:
- `x` : Input data.
- `nu` : Degrees of freedom.
"""
nu = np.asarray(nu)
return flib.t(x, nu) | [
"def",
"t_like",
"(",
"x",
",",
"nu",
")",
":",
"nu",
"=",
"np",
".",
"asarray",
"(",
"nu",
")",
"return",
"flib",
".",
"t",
"(",
"x",
",",
"nu",
")"
] | R"""
Student's T log-likelihood.
Describes a zero-mean normal variable
whose precision is gamma distributed. Alternatively, describes the
mean of several zero-mean normal random variables divided by their
sample standard deviation.
.. math::
f(x \mid \nu) = \frac{\Gamma(\frac{\nu+1}{2})}{\Gamma(\frac{\nu}{2}) \sqrt{\nu\pi}} \left( 1 + \frac{x^2}{\nu} \right)^{-\frac{\nu+1}{2}}
:Parameters:
- `x` : Input data.
- `nu` : Degrees of freedom. | [
"R",
"Student",
"s",
"T",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2612-L2630 |
239,235 | pymc-devs/pymc | pymc/distributions.py | rnoncentral_t | def rnoncentral_t(mu, lam, nu, size=None):
"""
Non-central Student's t random variates.
"""
tau = rgamma(nu / 2., nu / (2. * lam), size)
return rnormal(mu, tau) | python | def rnoncentral_t(mu, lam, nu, size=None):
tau = rgamma(nu / 2., nu / (2. * lam), size)
return rnormal(mu, tau) | [
"def",
"rnoncentral_t",
"(",
"mu",
",",
"lam",
",",
"nu",
",",
"size",
"=",
"None",
")",
":",
"tau",
"=",
"rgamma",
"(",
"nu",
"/",
"2.",
",",
"nu",
"/",
"(",
"2.",
"*",
"lam",
")",
",",
"size",
")",
"return",
"rnormal",
"(",
"mu",
",",
"tau"... | Non-central Student's t random variates. | [
"Non",
"-",
"central",
"Student",
"s",
"t",
"random",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2636-L2641 |
239,236 | pymc-devs/pymc | pymc/distributions.py | noncentral_t_like | def noncentral_t_like(x, mu, lam, nu):
R"""
Non-central Student's T log-likelihood.
Describes a normal variable whose precision is gamma distributed.
.. math::
f(x|\mu,\lambda,\nu) = \frac{\Gamma(\frac{\nu +
1}{2})}{\Gamma(\frac{\nu}{2})}
\left(\frac{\lambda}{\pi\nu}\right)^{\frac{1}{2}}
\left[1+\frac{\lambda(x-\mu)^2}{\nu}\right]^{-\frac{\nu+1}{2}}
:Parameters:
- `x` : Input data.
- `mu` : Location parameter.
- `lambda` : Scale parameter.
- `nu` : Degrees of freedom.
"""
mu = np.asarray(mu)
lam = np.asarray(lam)
nu = np.asarray(nu)
return flib.nct(x, mu, lam, nu) | python | def noncentral_t_like(x, mu, lam, nu):
R"""
Non-central Student's T log-likelihood.
Describes a normal variable whose precision is gamma distributed.
.. math::
f(x|\mu,\lambda,\nu) = \frac{\Gamma(\frac{\nu +
1}{2})}{\Gamma(\frac{\nu}{2})}
\left(\frac{\lambda}{\pi\nu}\right)^{\frac{1}{2}}
\left[1+\frac{\lambda(x-\mu)^2}{\nu}\right]^{-\frac{\nu+1}{2}}
:Parameters:
- `x` : Input data.
- `mu` : Location parameter.
- `lambda` : Scale parameter.
- `nu` : Degrees of freedom.
"""
mu = np.asarray(mu)
lam = np.asarray(lam)
nu = np.asarray(nu)
return flib.nct(x, mu, lam, nu) | [
"def",
"noncentral_t_like",
"(",
"x",
",",
"mu",
",",
"lam",
",",
"nu",
")",
":",
"mu",
"=",
"np",
".",
"asarray",
"(",
"mu",
")",
"lam",
"=",
"np",
".",
"asarray",
"(",
"lam",
")",
"nu",
"=",
"np",
".",
"asarray",
"(",
"nu",
")",
"return",
"... | R"""
Non-central Student's T log-likelihood.
Describes a normal variable whose precision is gamma distributed.
.. math::
f(x|\mu,\lambda,\nu) = \frac{\Gamma(\frac{\nu +
1}{2})}{\Gamma(\frac{\nu}{2})}
\left(\frac{\lambda}{\pi\nu}\right)^{\frac{1}{2}}
\left[1+\frac{\lambda(x-\mu)^2}{\nu}\right]^{-\frac{\nu+1}{2}}
:Parameters:
- `x` : Input data.
- `mu` : Location parameter.
- `lambda` : Scale parameter.
- `nu` : Degrees of freedom. | [
"R",
"Non",
"-",
"central",
"Student",
"s",
"T",
"log",
"-",
"likelihood",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2655-L2677 |
239,237 | pymc-devs/pymc | pymc/distributions.py | rdiscrete_uniform | def rdiscrete_uniform(lower, upper, size=None):
"""
Random discrete_uniform variates.
"""
return np.random.randint(lower, upper + 1, size) | python | def rdiscrete_uniform(lower, upper, size=None):
return np.random.randint(lower, upper + 1, size) | [
"def",
"rdiscrete_uniform",
"(",
"lower",
",",
"upper",
",",
"size",
"=",
"None",
")",
":",
"return",
"np",
".",
"random",
".",
"randint",
"(",
"lower",
",",
"upper",
"+",
"1",
",",
"size",
")"
] | Random discrete_uniform variates. | [
"Random",
"discrete_uniform",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2691-L2695 |
239,238 | pymc-devs/pymc | pymc/distributions.py | runiform | def runiform(lower, upper, size=None):
"""
Random uniform variates.
"""
return np.random.uniform(lower, upper, size) | python | def runiform(lower, upper, size=None):
return np.random.uniform(lower, upper, size) | [
"def",
"runiform",
"(",
"lower",
",",
"upper",
",",
"size",
"=",
"None",
")",
":",
"return",
"np",
".",
"random",
".",
"uniform",
"(",
"lower",
",",
"upper",
",",
"size",
")"
] | Random uniform variates. | [
"Random",
"uniform",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2723-L2727 |
239,239 | pymc-devs/pymc | pymc/distributions.py | rweibull | def rweibull(alpha, beta, size=None):
"""
Weibull random variates.
"""
tmp = -np.log(runiform(0, 1, size))
return beta * (tmp ** (1. / alpha)) | python | def rweibull(alpha, beta, size=None):
tmp = -np.log(runiform(0, 1, size))
return beta * (tmp ** (1. / alpha)) | [
"def",
"rweibull",
"(",
"alpha",
",",
"beta",
",",
"size",
"=",
"None",
")",
":",
"tmp",
"=",
"-",
"np",
".",
"log",
"(",
"runiform",
"(",
"0",
",",
"1",
",",
"size",
")",
")",
"return",
"beta",
"*",
"(",
"tmp",
"**",
"(",
"1.",
"/",
"alpha",... | Weibull random variates. | [
"Weibull",
"random",
"variates",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2761-L2766 |
239,240 | pymc-devs/pymc | pymc/distributions.py | rwishart_cov | def rwishart_cov(n, C):
"""
Return a Wishart random matrix.
:Parameters:
n : int
Degrees of freedom, > 0.
C : matrix
Symmetric and positive definite
"""
# return rwishart(n, np.linalg.inv(C))
p = np.shape(C)[0]
# Need cholesky decomposition of precision matrix C^-1?
sig = np.linalg.cholesky(C)
if n <= (p-1):
raise ValueError('Wishart parameter n must be greater '
'than size of matrix.')
norms = np.random.normal(size=(p * (p - 1)) // 2)
chi_sqs = np.sqrt(np.random.chisquare(df=np.arange(n, n - p, -1)))
A = flib.expand_triangular(chi_sqs, norms)
flib.dtrmm_wrap(sig, A, side='L', uplo='L', transa='N', alpha=1.)
w = np.asmatrix(np.dot(A, A.T))
flib.symmetrize(w)
return w | python | def rwishart_cov(n, C):
# return rwishart(n, np.linalg.inv(C))
p = np.shape(C)[0]
# Need cholesky decomposition of precision matrix C^-1?
sig = np.linalg.cholesky(C)
if n <= (p-1):
raise ValueError('Wishart parameter n must be greater '
'than size of matrix.')
norms = np.random.normal(size=(p * (p - 1)) // 2)
chi_sqs = np.sqrt(np.random.chisquare(df=np.arange(n, n - p, -1)))
A = flib.expand_triangular(chi_sqs, norms)
flib.dtrmm_wrap(sig, A, side='L', uplo='L', transa='N', alpha=1.)
w = np.asmatrix(np.dot(A, A.T))
flib.symmetrize(w)
return w | [
"def",
"rwishart_cov",
"(",
"n",
",",
"C",
")",
":",
"# return rwishart(n, np.linalg.inv(C))",
"p",
"=",
"np",
".",
"shape",
"(",
"C",
")",
"[",
"0",
"]",
"# Need cholesky decomposition of precision matrix C^-1?",
"sig",
"=",
"np",
".",
"linalg",
".",
"cholesky"... | Return a Wishart random matrix.
:Parameters:
n : int
Degrees of freedom, > 0.
C : matrix
Symmetric and positive definite | [
"Return",
"a",
"Wishart",
"random",
"matrix",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2866-L2893 |
239,241 | pymc-devs/pymc | pymc/distributions.py | valuewrapper | def valuewrapper(f, arguments=None):
"""Return a likelihood accepting value instead of x as a keyword argument.
This is specifically intended for the instantiator above.
"""
def wrapper(**kwds):
value = kwds.pop('value')
return f(value, **kwds)
if arguments is None:
wrapper.__dict__.update(f.__dict__)
else:
wrapper.__dict__.update(arguments)
return wrapper | python | def valuewrapper(f, arguments=None):
def wrapper(**kwds):
value = kwds.pop('value')
return f(value, **kwds)
if arguments is None:
wrapper.__dict__.update(f.__dict__)
else:
wrapper.__dict__.update(arguments)
return wrapper | [
"def",
"valuewrapper",
"(",
"f",
",",
"arguments",
"=",
"None",
")",
":",
"def",
"wrapper",
"(",
"*",
"*",
"kwds",
")",
":",
"value",
"=",
"kwds",
".",
"pop",
"(",
"'value'",
")",
"return",
"f",
"(",
"value",
",",
"*",
"*",
"kwds",
")",
"if",
"... | Return a likelihood accepting value instead of x as a keyword argument.
This is specifically intended for the instantiator above. | [
"Return",
"a",
"likelihood",
"accepting",
"value",
"instead",
"of",
"x",
"as",
"a",
"keyword",
"argument",
".",
"This",
"is",
"specifically",
"intended",
"for",
"the",
"instantiator",
"above",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2968-L2981 |
239,242 | pymc-devs/pymc | pymc/distributions.py | local_decorated_likelihoods | def local_decorated_likelihoods(obj):
"""
New interface likelihoods
"""
for name, like in six.iteritems(likelihoods):
obj[name + '_like'] = gofwrapper(like, snapshot) | python | def local_decorated_likelihoods(obj):
for name, like in six.iteritems(likelihoods):
obj[name + '_like'] = gofwrapper(like, snapshot) | [
"def",
"local_decorated_likelihoods",
"(",
"obj",
")",
":",
"for",
"name",
",",
"like",
"in",
"six",
".",
"iteritems",
"(",
"likelihoods",
")",
":",
"obj",
"[",
"name",
"+",
"'_like'",
"]",
"=",
"gofwrapper",
"(",
"like",
",",
"snapshot",
")"
] | New interface likelihoods | [
"New",
"interface",
"likelihoods"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L2994-L3000 |
239,243 | pymc-devs/pymc | pymc/distributions.py | _inject_dist | def _inject_dist(distname, kwargs={}, ns=locals()):
"""
Reusable function to inject Stochastic subclasses into module
namespace
"""
dist_logp, dist_random, grad_logp = name_to_funcs(distname, ns)
classname = capitalize(distname)
ns[classname] = stochastic_from_dist(distname, dist_logp,
dist_random,
grad_logp, **kwargs) | python | def _inject_dist(distname, kwargs={}, ns=locals()):
dist_logp, dist_random, grad_logp = name_to_funcs(distname, ns)
classname = capitalize(distname)
ns[classname] = stochastic_from_dist(distname, dist_logp,
dist_random,
grad_logp, **kwargs) | [
"def",
"_inject_dist",
"(",
"distname",
",",
"kwargs",
"=",
"{",
"}",
",",
"ns",
"=",
"locals",
"(",
")",
")",
":",
"dist_logp",
",",
"dist_random",
",",
"grad_logp",
"=",
"name_to_funcs",
"(",
"distname",
",",
"ns",
")",
"classname",
"=",
"capitalize",
... | Reusable function to inject Stochastic subclasses into module
namespace | [
"Reusable",
"function",
"to",
"inject",
"Stochastic",
"subclasses",
"into",
"module",
"namespace"
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L3009-L3019 |
239,244 | pymc-devs/pymc | pymc/distributions.py | mod_categorical_expval | def mod_categorical_expval(p):
"""
Expected value of categorical distribution with parent p of length k-1.
An implicit k'th category is assumed to exist with associated
probability 1-sum(p).
"""
p = extend_dirichlet(p)
return np.sum([p * i for i, p in enumerate(p)]) | python | def mod_categorical_expval(p):
p = extend_dirichlet(p)
return np.sum([p * i for i, p in enumerate(p)]) | [
"def",
"mod_categorical_expval",
"(",
"p",
")",
":",
"p",
"=",
"extend_dirichlet",
"(",
"p",
")",
"return",
"np",
".",
"sum",
"(",
"[",
"p",
"*",
"i",
"for",
"i",
",",
"p",
"in",
"enumerate",
"(",
"p",
")",
"]",
")"
] | Expected value of categorical distribution with parent p of length k-1.
An implicit k'th category is assumed to exist with associated
probability 1-sum(p). | [
"Expected",
"value",
"of",
"categorical",
"distribution",
"with",
"parent",
"p",
"of",
"length",
"k",
"-",
"1",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L3104-L3112 |
239,245 | pymc-devs/pymc | pymc/distributions.py | Impute | def Impute(name, dist_class, imputable, **parents):
"""
This function accomodates missing elements for the data of simple
Stochastic distribution subclasses. The masked_values argument is an
object of type numpy.ma.MaskedArray, which contains the raw data and
a boolean mask indicating missing values. The resulting list contains
a list of stochastics of type dist_class, with the extant values as data
stochastics and the missing values as variable stochastics.
:Arguments:
- name : string
Name of the data stochastic
- dist_class : Stochastic
Stochastic subclass such as Poisson, Normal, etc.
- imputable : numpy.ma.core.MaskedArray or iterable
A masked array with missing elements (where mask=True, value
is assumed missing), or any iterable that contains None
elements that will be imputed.
- parents (optional): dict
Arbitrary keyword arguments.
"""
dims = np.shape(imputable)
masked_values = np.ravel(imputable)
if not isinstance(masked_values, np.ma.core.MaskedArray):
# Generate mask
mask = [v is None or np.isnan(v) for v in masked_values]
# Generate masked array
masked_values = np.ma.masked_array(masked_values, mask)
# Initialise list
vars = []
for i in xrange(len(masked_values)):
# Name of element
this_name = name + '[%i]' % i
# Dictionary to hold parents
these_parents = {}
# Parse parents
for key, parent in six.iteritems(parents):
try:
# If parent is a PyMCObject
shape = np.shape(parent.value)
except AttributeError:
shape = np.shape(parent)
if shape == dims:
these_parents[key] = Lambda(key + '[%i]' % i,
lambda p=np.ravel(parent),
i=i: p[i])
elif shape == np.shape(masked_values):
these_parents[key] = Lambda(key + '[%i]' % i, lambda p=parent,
i=i: p[i])
else:
these_parents[key] = parent
if masked_values.mask[i]:
# Missing values
vars.append(dist_class(this_name, **these_parents))
else:
# Observed values
vars.append(dist_class(this_name, value=masked_values[i],
observed=True, **these_parents))
return np.reshape(vars, dims) | python | def Impute(name, dist_class, imputable, **parents):
dims = np.shape(imputable)
masked_values = np.ravel(imputable)
if not isinstance(masked_values, np.ma.core.MaskedArray):
# Generate mask
mask = [v is None or np.isnan(v) for v in masked_values]
# Generate masked array
masked_values = np.ma.masked_array(masked_values, mask)
# Initialise list
vars = []
for i in xrange(len(masked_values)):
# Name of element
this_name = name + '[%i]' % i
# Dictionary to hold parents
these_parents = {}
# Parse parents
for key, parent in six.iteritems(parents):
try:
# If parent is a PyMCObject
shape = np.shape(parent.value)
except AttributeError:
shape = np.shape(parent)
if shape == dims:
these_parents[key] = Lambda(key + '[%i]' % i,
lambda p=np.ravel(parent),
i=i: p[i])
elif shape == np.shape(masked_values):
these_parents[key] = Lambda(key + '[%i]' % i, lambda p=parent,
i=i: p[i])
else:
these_parents[key] = parent
if masked_values.mask[i]:
# Missing values
vars.append(dist_class(this_name, **these_parents))
else:
# Observed values
vars.append(dist_class(this_name, value=masked_values[i],
observed=True, **these_parents))
return np.reshape(vars, dims) | [
"def",
"Impute",
"(",
"name",
",",
"dist_class",
",",
"imputable",
",",
"*",
"*",
"parents",
")",
":",
"dims",
"=",
"np",
".",
"shape",
"(",
"imputable",
")",
"masked_values",
"=",
"np",
".",
"ravel",
"(",
"imputable",
")",
"if",
"not",
"isinstance",
... | This function accomodates missing elements for the data of simple
Stochastic distribution subclasses. The masked_values argument is an
object of type numpy.ma.MaskedArray, which contains the raw data and
a boolean mask indicating missing values. The resulting list contains
a list of stochastics of type dist_class, with the extant values as data
stochastics and the missing values as variable stochastics.
:Arguments:
- name : string
Name of the data stochastic
- dist_class : Stochastic
Stochastic subclass such as Poisson, Normal, etc.
- imputable : numpy.ma.core.MaskedArray or iterable
A masked array with missing elements (where mask=True, value
is assumed missing), or any iterable that contains None
elements that will be imputed.
- parents (optional): dict
Arbitrary keyword arguments. | [
"This",
"function",
"accomodates",
"missing",
"elements",
"for",
"the",
"data",
"of",
"simple",
"Stochastic",
"distribution",
"subclasses",
".",
"The",
"masked_values",
"argument",
"is",
"an",
"object",
"of",
"type",
"numpy",
".",
"ma",
".",
"MaskedArray",
"whic... | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/distributions.py#L3269-L3335 |
239,246 | pymc-devs/pymc | pymc/Node.py | logp_gradient_of_set | def logp_gradient_of_set(variable_set, calculation_set=None):
"""
Calculates the gradient of the joint log posterior with respect to all the variables in variable_set.
Calculation of the log posterior is restricted to the variables in calculation_set.
Returns a dictionary of the gradients.
"""
logp_gradients = {}
for variable in variable_set:
logp_gradients[variable] = logp_gradient(variable, calculation_set)
return logp_gradients | python | def logp_gradient_of_set(variable_set, calculation_set=None):
logp_gradients = {}
for variable in variable_set:
logp_gradients[variable] = logp_gradient(variable, calculation_set)
return logp_gradients | [
"def",
"logp_gradient_of_set",
"(",
"variable_set",
",",
"calculation_set",
"=",
"None",
")",
":",
"logp_gradients",
"=",
"{",
"}",
"for",
"variable",
"in",
"variable_set",
":",
"logp_gradients",
"[",
"variable",
"]",
"=",
"logp_gradient",
"(",
"variable",
",",
... | Calculates the gradient of the joint log posterior with respect to all the variables in variable_set.
Calculation of the log posterior is restricted to the variables in calculation_set.
Returns a dictionary of the gradients. | [
"Calculates",
"the",
"gradient",
"of",
"the",
"joint",
"log",
"posterior",
"with",
"respect",
"to",
"all",
"the",
"variables",
"in",
"variable_set",
".",
"Calculation",
"of",
"the",
"log",
"posterior",
"is",
"restricted",
"to",
"the",
"variables",
"in",
"calcu... | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Node.py#L42-L54 |
239,247 | pymc-devs/pymc | pymc/Node.py | logp_gradient | def logp_gradient(variable, calculation_set=None):
"""
Calculates the gradient of the joint log posterior with respect to variable.
Calculation of the log posterior is restricted to the variables in calculation_set.
"""
return variable.logp_partial_gradient(variable, calculation_set) + sum(
[child.logp_partial_gradient(variable, calculation_set) for child in variable.children]) | python | def logp_gradient(variable, calculation_set=None):
return variable.logp_partial_gradient(variable, calculation_set) + sum(
[child.logp_partial_gradient(variable, calculation_set) for child in variable.children]) | [
"def",
"logp_gradient",
"(",
"variable",
",",
"calculation_set",
"=",
"None",
")",
":",
"return",
"variable",
".",
"logp_partial_gradient",
"(",
"variable",
",",
"calculation_set",
")",
"+",
"sum",
"(",
"[",
"child",
".",
"logp_partial_gradient",
"(",
"variable"... | Calculates the gradient of the joint log posterior with respect to variable.
Calculation of the log posterior is restricted to the variables in calculation_set. | [
"Calculates",
"the",
"gradient",
"of",
"the",
"joint",
"log",
"posterior",
"with",
"respect",
"to",
"variable",
".",
"Calculation",
"of",
"the",
"log",
"posterior",
"is",
"restricted",
"to",
"the",
"variables",
"in",
"calculation_set",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Node.py#L57-L63 |
239,248 | pymc-devs/pymc | pymc/Node.py | Variable.summary | def summary(self, alpha=0.05, start=0, batches=100, chain=None, roundto=3):
"""
Generate a pretty-printed summary of the node.
:Parameters:
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting index from which to summarize (each) chain. Defaults
to zero.
batches : int
Batch size for calculating standard deviation for non-independent
samples. Defaults to 100.
chain : int
The index for which chain to summarize. Defaults to None (all
chains).
roundto : int
The number of digits to round posterior statistics.
"""
# Calculate statistics for Node
statdict = self.stats(
alpha=alpha,
start=start,
batches=batches,
chain=chain)
size = np.size(statdict['mean'])
print_('\n%s:' % self.__name__)
print_(' ')
# Initialize buffer
buffer = []
# Index to interval label
iindex = [key.split()[-1] for key in statdict.keys()].index('interval')
interval = list(statdict.keys())[iindex]
# Print basic stats
buffer += [
'Mean SD MC Error %s' %
interval]
buffer += ['-' * len(buffer[-1])]
indices = range(size)
if len(indices) == 1:
indices = [None]
_format_str = lambda x, i=None, roundto=2: str(np.round(x.ravel()[i].squeeze(), roundto))
for index in indices:
# Extract statistics and convert to string
m = _format_str(statdict['mean'], index, roundto)
sd = _format_str(statdict['standard deviation'], index, roundto)
mce = _format_str(statdict['mc error'], index, roundto)
hpd = str(statdict[interval].reshape(
(2, size))[:,index].squeeze().round(roundto))
# Build up string buffer of values
valstr = m
valstr += ' ' * (17 - len(m)) + sd
valstr += ' ' * (17 - len(sd)) + mce
valstr += ' ' * (len(buffer[-1]) - len(valstr) - len(hpd)) + hpd
buffer += [valstr]
buffer += [''] * 2
# Print quantiles
buffer += ['Posterior quantiles:', '']
buffer += [
'2.5 25 50 75 97.5']
buffer += [
' |---------------|===============|===============|---------------|']
for index in indices:
quantile_str = ''
for i, q in enumerate((2.5, 25, 50, 75, 97.5)):
qstr = _format_str(statdict['quantiles'][q], index, roundto)
quantile_str += qstr + ' ' * (17 - i - len(qstr))
buffer += [quantile_str.strip()]
buffer += ['']
print_('\t' + '\n\t'.join(buffer)) | python | def summary(self, alpha=0.05, start=0, batches=100, chain=None, roundto=3):
# Calculate statistics for Node
statdict = self.stats(
alpha=alpha,
start=start,
batches=batches,
chain=chain)
size = np.size(statdict['mean'])
print_('\n%s:' % self.__name__)
print_(' ')
# Initialize buffer
buffer = []
# Index to interval label
iindex = [key.split()[-1] for key in statdict.keys()].index('interval')
interval = list(statdict.keys())[iindex]
# Print basic stats
buffer += [
'Mean SD MC Error %s' %
interval]
buffer += ['-' * len(buffer[-1])]
indices = range(size)
if len(indices) == 1:
indices = [None]
_format_str = lambda x, i=None, roundto=2: str(np.round(x.ravel()[i].squeeze(), roundto))
for index in indices:
# Extract statistics and convert to string
m = _format_str(statdict['mean'], index, roundto)
sd = _format_str(statdict['standard deviation'], index, roundto)
mce = _format_str(statdict['mc error'], index, roundto)
hpd = str(statdict[interval].reshape(
(2, size))[:,index].squeeze().round(roundto))
# Build up string buffer of values
valstr = m
valstr += ' ' * (17 - len(m)) + sd
valstr += ' ' * (17 - len(sd)) + mce
valstr += ' ' * (len(buffer[-1]) - len(valstr) - len(hpd)) + hpd
buffer += [valstr]
buffer += [''] * 2
# Print quantiles
buffer += ['Posterior quantiles:', '']
buffer += [
'2.5 25 50 75 97.5']
buffer += [
' |---------------|===============|===============|---------------|']
for index in indices:
quantile_str = ''
for i, q in enumerate((2.5, 25, 50, 75, 97.5)):
qstr = _format_str(statdict['quantiles'][q], index, roundto)
quantile_str += qstr + ' ' * (17 - i - len(qstr))
buffer += [quantile_str.strip()]
buffer += ['']
print_('\t' + '\n\t'.join(buffer)) | [
"def",
"summary",
"(",
"self",
",",
"alpha",
"=",
"0.05",
",",
"start",
"=",
"0",
",",
"batches",
"=",
"100",
",",
"chain",
"=",
"None",
",",
"roundto",
"=",
"3",
")",
":",
"# Calculate statistics for Node",
"statdict",
"=",
"self",
".",
"stats",
"(",
... | Generate a pretty-printed summary of the node.
:Parameters:
alpha : float
The alpha level for generating posterior intervals. Defaults to
0.05.
start : int
The starting index from which to summarize (each) chain. Defaults
to zero.
batches : int
Batch size for calculating standard deviation for non-independent
samples. Defaults to 100.
chain : int
The index for which chain to summarize. Defaults to None (all
chains).
roundto : int
The number of digits to round posterior statistics. | [
"Generate",
"a",
"pretty",
"-",
"printed",
"summary",
"of",
"the",
"node",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Node.py#L267-L358 |
239,249 | pymc-devs/pymc | pymc/Container.py | file_items | def file_items(container, iterable):
"""
Files away objects into the appropriate attributes of the container.
"""
# container._value = copy(iterable)
container.nodes = set()
container.variables = set()
container.deterministics = set()
container.stochastics = set()
container.potentials = set()
container.observed_stochastics = set()
# containers needs to be a list to hold unhashable items.
container.containers = []
i = -1
for item in iterable:
# If this is a dictionary, switch from key to item.
if isinstance(iterable, (dict, dict_proxy_type)):
key = item
item = iterable[key]
# Item counter
else:
i += 1
# If the item isn't iterable, file it away.
if isinstance(item, Variable):
container.variables.add(item)
if isinstance(item, StochasticBase):
if item.observed or not getattr(item, 'mask', None) is None:
container.observed_stochastics.add(item)
if not item.observed:
container.stochastics.add(item)
elif isinstance(item, DeterministicBase):
container.deterministics.add(item)
elif isinstance(item, PotentialBase):
container.potentials.add(item)
elif isinstance(item, ContainerBase):
container.assimilate(item)
container.containers.append(item)
# Wrap internal containers
elif hasattr(item, '__iter__'):
# If this is a non-object-valued ndarray, don't container-ize it.
if isinstance(item, ndarray):
if item.dtype != dtype('object'):
continue
# If the item is iterable, wrap it in a container. Replace the item
# with the wrapped version.
try:
new_container = Container(item)
except:
continue
# Update all of container's variables, potentials, etc. with the new wrapped
# iterable's. This process recursively unpacks nested iterables.
container.assimilate(new_container)
if isinstance(container, dict):
container.replace(key, new_container)
elif isinstance(container, tuple):
return container[:i] + (new_container,) + container[i + 1:]
else:
container.replace(item, new_container, i)
container.nodes = container.potentials | container.variables
# 'Freeze' markov blanket, moral neighbors, coparents of all constituent stochastics
# for future use
for attr in ['moral_neighbors', 'markov_blanket', 'coparents']:
setattr(container, attr, {})
for s in container.stochastics:
for attr in ['moral_neighbors', 'markov_blanket', 'coparents']:
getattr(container, attr)[s] = getattr(s, attr) | python | def file_items(container, iterable):
# container._value = copy(iterable)
container.nodes = set()
container.variables = set()
container.deterministics = set()
container.stochastics = set()
container.potentials = set()
container.observed_stochastics = set()
# containers needs to be a list to hold unhashable items.
container.containers = []
i = -1
for item in iterable:
# If this is a dictionary, switch from key to item.
if isinstance(iterable, (dict, dict_proxy_type)):
key = item
item = iterable[key]
# Item counter
else:
i += 1
# If the item isn't iterable, file it away.
if isinstance(item, Variable):
container.variables.add(item)
if isinstance(item, StochasticBase):
if item.observed or not getattr(item, 'mask', None) is None:
container.observed_stochastics.add(item)
if not item.observed:
container.stochastics.add(item)
elif isinstance(item, DeterministicBase):
container.deterministics.add(item)
elif isinstance(item, PotentialBase):
container.potentials.add(item)
elif isinstance(item, ContainerBase):
container.assimilate(item)
container.containers.append(item)
# Wrap internal containers
elif hasattr(item, '__iter__'):
# If this is a non-object-valued ndarray, don't container-ize it.
if isinstance(item, ndarray):
if item.dtype != dtype('object'):
continue
# If the item is iterable, wrap it in a container. Replace the item
# with the wrapped version.
try:
new_container = Container(item)
except:
continue
# Update all of container's variables, potentials, etc. with the new wrapped
# iterable's. This process recursively unpacks nested iterables.
container.assimilate(new_container)
if isinstance(container, dict):
container.replace(key, new_container)
elif isinstance(container, tuple):
return container[:i] + (new_container,) + container[i + 1:]
else:
container.replace(item, new_container, i)
container.nodes = container.potentials | container.variables
# 'Freeze' markov blanket, moral neighbors, coparents of all constituent stochastics
# for future use
for attr in ['moral_neighbors', 'markov_blanket', 'coparents']:
setattr(container, attr, {})
for s in container.stochastics:
for attr in ['moral_neighbors', 'markov_blanket', 'coparents']:
getattr(container, attr)[s] = getattr(s, attr) | [
"def",
"file_items",
"(",
"container",
",",
"iterable",
")",
":",
"# container._value = copy(iterable)",
"container",
".",
"nodes",
"=",
"set",
"(",
")",
"container",
".",
"variables",
"=",
"set",
"(",
")",
"container",
".",
"deterministics",
"=",
"set",
"(",
... | Files away objects into the appropriate attributes of the container. | [
"Files",
"away",
"objects",
"into",
"the",
"appropriate",
"attributes",
"of",
"the",
"container",
"."
] | c6e530210bff4c0d7189b35b2c971bc53f93f7cd | https://github.com/pymc-devs/pymc/blob/c6e530210bff4c0d7189b35b2c971bc53f93f7cd/pymc/Container.py#L168-L248 |
239,250 | ethereum/web3.py | web3/middleware/gas_price_strategy.py | gas_price_strategy_middleware | def gas_price_strategy_middleware(make_request, web3):
"""
Includes a gas price using the gas price strategy
"""
def middleware(method, params):
if method == 'eth_sendTransaction':
transaction = params[0]
if 'gasPrice' not in transaction:
generated_gas_price = web3.eth.generateGasPrice(transaction)
if generated_gas_price is not None:
transaction = assoc(transaction, 'gasPrice', generated_gas_price)
return make_request(method, [transaction])
return make_request(method, params)
return middleware | python | def gas_price_strategy_middleware(make_request, web3):
def middleware(method, params):
if method == 'eth_sendTransaction':
transaction = params[0]
if 'gasPrice' not in transaction:
generated_gas_price = web3.eth.generateGasPrice(transaction)
if generated_gas_price is not None:
transaction = assoc(transaction, 'gasPrice', generated_gas_price)
return make_request(method, [transaction])
return make_request(method, params)
return middleware | [
"def",
"gas_price_strategy_middleware",
"(",
"make_request",
",",
"web3",
")",
":",
"def",
"middleware",
"(",
"method",
",",
"params",
")",
":",
"if",
"method",
"==",
"'eth_sendTransaction'",
":",
"transaction",
"=",
"params",
"[",
"0",
"]",
"if",
"'gasPrice'"... | Includes a gas price using the gas price strategy | [
"Includes",
"a",
"gas",
"price",
"using",
"the",
"gas",
"price",
"strategy"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/gas_price_strategy.py#L6-L19 |
239,251 | ethereum/web3.py | web3/_utils/transactions.py | fill_transaction_defaults | def fill_transaction_defaults(web3, transaction):
"""
if web3 is None, fill as much as possible while offline
"""
defaults = {}
for key, default_getter in TRANSACTION_DEFAULTS.items():
if key not in transaction:
if callable(default_getter):
if web3 is not None:
default_val = default_getter(web3, transaction)
else:
raise ValueError("You must specify %s in the transaction" % key)
else:
default_val = default_getter
defaults[key] = default_val
return merge(defaults, transaction) | python | def fill_transaction_defaults(web3, transaction):
defaults = {}
for key, default_getter in TRANSACTION_DEFAULTS.items():
if key not in transaction:
if callable(default_getter):
if web3 is not None:
default_val = default_getter(web3, transaction)
else:
raise ValueError("You must specify %s in the transaction" % key)
else:
default_val = default_getter
defaults[key] = default_val
return merge(defaults, transaction) | [
"def",
"fill_transaction_defaults",
"(",
"web3",
",",
"transaction",
")",
":",
"defaults",
"=",
"{",
"}",
"for",
"key",
",",
"default_getter",
"in",
"TRANSACTION_DEFAULTS",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"transaction",
":",
"if",
"c... | if web3 is None, fill as much as possible while offline | [
"if",
"web3",
"is",
"None",
"fill",
"as",
"much",
"as",
"possible",
"while",
"offline"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/transactions.py#L49-L64 |
239,252 | ethereum/web3.py | web3/gas_strategies/time_based.py | _compute_probabilities | def _compute_probabilities(miner_data, wait_blocks, sample_size):
"""
Computes the probabilities that a txn will be accepted at each of the gas
prices accepted by the miners.
"""
miner_data_by_price = tuple(sorted(
miner_data,
key=operator.attrgetter('low_percentile_gas_price'),
reverse=True,
))
for idx in range(len(miner_data_by_price)):
low_percentile_gas_price = miner_data_by_price[idx].low_percentile_gas_price
num_blocks_accepting_price = sum(m.num_blocks for m in miner_data_by_price[idx:])
inv_prob_per_block = (sample_size - num_blocks_accepting_price) / sample_size
probability_accepted = 1 - inv_prob_per_block ** wait_blocks
yield Probability(low_percentile_gas_price, probability_accepted) | python | def _compute_probabilities(miner_data, wait_blocks, sample_size):
miner_data_by_price = tuple(sorted(
miner_data,
key=operator.attrgetter('low_percentile_gas_price'),
reverse=True,
))
for idx in range(len(miner_data_by_price)):
low_percentile_gas_price = miner_data_by_price[idx].low_percentile_gas_price
num_blocks_accepting_price = sum(m.num_blocks for m in miner_data_by_price[idx:])
inv_prob_per_block = (sample_size - num_blocks_accepting_price) / sample_size
probability_accepted = 1 - inv_prob_per_block ** wait_blocks
yield Probability(low_percentile_gas_price, probability_accepted) | [
"def",
"_compute_probabilities",
"(",
"miner_data",
",",
"wait_blocks",
",",
"sample_size",
")",
":",
"miner_data_by_price",
"=",
"tuple",
"(",
"sorted",
"(",
"miner_data",
",",
"key",
"=",
"operator",
".",
"attrgetter",
"(",
"'low_percentile_gas_price'",
")",
","... | Computes the probabilities that a txn will be accepted at each of the gas
prices accepted by the miners. | [
"Computes",
"the",
"probabilities",
"that",
"a",
"txn",
"will",
"be",
"accepted",
"at",
"each",
"of",
"the",
"gas",
"prices",
"accepted",
"by",
"the",
"miners",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/gas_strategies/time_based.py#L76-L91 |
239,253 | ethereum/web3.py | web3/gas_strategies/time_based.py | _compute_gas_price | def _compute_gas_price(probabilities, desired_probability):
"""
Given a sorted range of ``Probability`` named-tuples returns a gas price
computed based on where the ``desired_probability`` would fall within the
range.
:param probabilities: An iterable of `Probability` named-tuples sorted in reverse order.
:param desired_probability: An floating point representation of the desired
probability. (e.g. ``85% -> 0.85``)
"""
first = probabilities[0]
last = probabilities[-1]
if desired_probability >= first.prob:
return int(first.gas_price)
elif desired_probability <= last.prob:
return int(last.gas_price)
for left, right in sliding_window(2, probabilities):
if desired_probability < right.prob:
continue
elif desired_probability > left.prob:
# This code block should never be reachable as it would indicate
# that we already passed by the probability window in which our
# `desired_probability` is located.
raise Exception('Invariant')
adj_prob = desired_probability - right.prob
window_size = left.prob - right.prob
position = adj_prob / window_size
gas_window_size = left.gas_price - right.gas_price
gas_price = int(math.ceil(right.gas_price + gas_window_size * position))
return gas_price
else:
# The initial `if/else` clause in this function handles the case where
# the `desired_probability` is either above or below the min/max
# probability found in the `probabilities`.
#
# With these two cases handled, the only way this code block should be
# reachable would be if the `probabilities` were not sorted correctly.
# Otherwise, the `desired_probability` **must** fall between two of the
# values in the `probabilities``.
raise Exception('Invariant') | python | def _compute_gas_price(probabilities, desired_probability):
first = probabilities[0]
last = probabilities[-1]
if desired_probability >= first.prob:
return int(first.gas_price)
elif desired_probability <= last.prob:
return int(last.gas_price)
for left, right in sliding_window(2, probabilities):
if desired_probability < right.prob:
continue
elif desired_probability > left.prob:
# This code block should never be reachable as it would indicate
# that we already passed by the probability window in which our
# `desired_probability` is located.
raise Exception('Invariant')
adj_prob = desired_probability - right.prob
window_size = left.prob - right.prob
position = adj_prob / window_size
gas_window_size = left.gas_price - right.gas_price
gas_price = int(math.ceil(right.gas_price + gas_window_size * position))
return gas_price
else:
# The initial `if/else` clause in this function handles the case where
# the `desired_probability` is either above or below the min/max
# probability found in the `probabilities`.
#
# With these two cases handled, the only way this code block should be
# reachable would be if the `probabilities` were not sorted correctly.
# Otherwise, the `desired_probability` **must** fall between two of the
# values in the `probabilities``.
raise Exception('Invariant') | [
"def",
"_compute_gas_price",
"(",
"probabilities",
",",
"desired_probability",
")",
":",
"first",
"=",
"probabilities",
"[",
"0",
"]",
"last",
"=",
"probabilities",
"[",
"-",
"1",
"]",
"if",
"desired_probability",
">=",
"first",
".",
"prob",
":",
"return",
"... | Given a sorted range of ``Probability`` named-tuples returns a gas price
computed based on where the ``desired_probability`` would fall within the
range.
:param probabilities: An iterable of `Probability` named-tuples sorted in reverse order.
:param desired_probability: An floating point representation of the desired
probability. (e.g. ``85% -> 0.85``) | [
"Given",
"a",
"sorted",
"range",
"of",
"Probability",
"named",
"-",
"tuples",
"returns",
"a",
"gas",
"price",
"computed",
"based",
"on",
"where",
"the",
"desired_probability",
"would",
"fall",
"within",
"the",
"range",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/gas_strategies/time_based.py#L94-L136 |
239,254 | ethereum/web3.py | web3/gas_strategies/time_based.py | construct_time_based_gas_price_strategy | def construct_time_based_gas_price_strategy(max_wait_seconds,
sample_size=120,
probability=98):
"""
A gas pricing strategy that uses recently mined block data to derive a gas
price for which a transaction is likely to be mined within X seconds with
probability P.
:param max_wait_seconds: The desired maxiumum number of seconds the
transaction should take to mine.
:param sample_size: The number of recent blocks to sample
:param probability: An integer representation of the desired probability
that the transaction will be mined within ``max_wait_seconds``. 0 means 0%
and 100 means 100%.
"""
def time_based_gas_price_strategy(web3, transaction_params):
avg_block_time = _get_avg_block_time(web3, sample_size=sample_size)
wait_blocks = int(math.ceil(max_wait_seconds / avg_block_time))
raw_miner_data = _get_raw_miner_data(web3, sample_size=sample_size)
miner_data = _aggregate_miner_data(raw_miner_data)
probabilities = _compute_probabilities(
miner_data,
wait_blocks=wait_blocks,
sample_size=sample_size,
)
gas_price = _compute_gas_price(probabilities, probability / 100)
return gas_price
return time_based_gas_price_strategy | python | def construct_time_based_gas_price_strategy(max_wait_seconds,
sample_size=120,
probability=98):
def time_based_gas_price_strategy(web3, transaction_params):
avg_block_time = _get_avg_block_time(web3, sample_size=sample_size)
wait_blocks = int(math.ceil(max_wait_seconds / avg_block_time))
raw_miner_data = _get_raw_miner_data(web3, sample_size=sample_size)
miner_data = _aggregate_miner_data(raw_miner_data)
probabilities = _compute_probabilities(
miner_data,
wait_blocks=wait_blocks,
sample_size=sample_size,
)
gas_price = _compute_gas_price(probabilities, probability / 100)
return gas_price
return time_based_gas_price_strategy | [
"def",
"construct_time_based_gas_price_strategy",
"(",
"max_wait_seconds",
",",
"sample_size",
"=",
"120",
",",
"probability",
"=",
"98",
")",
":",
"def",
"time_based_gas_price_strategy",
"(",
"web3",
",",
"transaction_params",
")",
":",
"avg_block_time",
"=",
"_get_a... | A gas pricing strategy that uses recently mined block data to derive a gas
price for which a transaction is likely to be mined within X seconds with
probability P.
:param max_wait_seconds: The desired maxiumum number of seconds the
transaction should take to mine.
:param sample_size: The number of recent blocks to sample
:param probability: An integer representation of the desired probability
that the transaction will be mined within ``max_wait_seconds``. 0 means 0%
and 100 means 100%. | [
"A",
"gas",
"pricing",
"strategy",
"that",
"uses",
"recently",
"mined",
"block",
"data",
"to",
"derive",
"a",
"gas",
"price",
"for",
"which",
"a",
"transaction",
"is",
"likely",
"to",
"be",
"mined",
"within",
"X",
"seconds",
"with",
"probability",
"P",
"."... | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/gas_strategies/time_based.py#L140-L170 |
239,255 | ethereum/web3.py | web3/manager.py | RequestManager.default_middlewares | def default_middlewares(web3):
"""
List the default middlewares for the request manager.
Leaving ens unspecified will prevent the middleware from resolving names.
"""
return [
(request_parameter_normalizer, 'request_param_normalizer'),
(gas_price_strategy_middleware, 'gas_price_strategy'),
(name_to_address_middleware(web3), 'name_to_address'),
(attrdict_middleware, 'attrdict'),
(pythonic_middleware, 'pythonic'),
(normalize_errors_middleware, 'normalize_errors'),
(validation_middleware, 'validation'),
(abi_middleware, 'abi'),
] | python | def default_middlewares(web3):
return [
(request_parameter_normalizer, 'request_param_normalizer'),
(gas_price_strategy_middleware, 'gas_price_strategy'),
(name_to_address_middleware(web3), 'name_to_address'),
(attrdict_middleware, 'attrdict'),
(pythonic_middleware, 'pythonic'),
(normalize_errors_middleware, 'normalize_errors'),
(validation_middleware, 'validation'),
(abi_middleware, 'abi'),
] | [
"def",
"default_middlewares",
"(",
"web3",
")",
":",
"return",
"[",
"(",
"request_parameter_normalizer",
",",
"'request_param_normalizer'",
")",
",",
"(",
"gas_price_strategy_middleware",
",",
"'gas_price_strategy'",
")",
",",
"(",
"name_to_address_middleware",
"(",
"we... | List the default middlewares for the request manager.
Leaving ens unspecified will prevent the middleware from resolving names. | [
"List",
"the",
"default",
"middlewares",
"for",
"the",
"request",
"manager",
".",
"Leaving",
"ens",
"unspecified",
"will",
"prevent",
"the",
"middleware",
"from",
"resolving",
"names",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/manager.py#L57-L71 |
239,256 | ethereum/web3.py | web3/manager.py | RequestManager.request_blocking | def request_blocking(self, method, params):
"""
Make a synchronous request using the provider
"""
response = self._make_request(method, params)
if "error" in response:
raise ValueError(response["error"])
return response['result'] | python | def request_blocking(self, method, params):
response = self._make_request(method, params)
if "error" in response:
raise ValueError(response["error"])
return response['result'] | [
"def",
"request_blocking",
"(",
"self",
",",
"method",
",",
"params",
")",
":",
"response",
"=",
"self",
".",
"_make_request",
"(",
"method",
",",
"params",
")",
"if",
"\"error\"",
"in",
"response",
":",
"raise",
"ValueError",
"(",
"response",
"[",
"\"erro... | Make a synchronous request using the provider | [
"Make",
"a",
"synchronous",
"request",
"using",
"the",
"provider"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/manager.py#L90-L99 |
239,257 | ethereum/web3.py | web3/manager.py | RequestManager.coro_request | async def coro_request(self, method, params):
"""
Couroutine for making a request using the provider
"""
response = await self._coro_make_request(method, params)
if "error" in response:
raise ValueError(response["error"])
if response['result'] is None:
raise ValueError(f"The call to {method} did not return a value.")
return response['result'] | python | async def coro_request(self, method, params):
response = await self._coro_make_request(method, params)
if "error" in response:
raise ValueError(response["error"])
if response['result'] is None:
raise ValueError(f"The call to {method} did not return a value.")
return response['result'] | [
"async",
"def",
"coro_request",
"(",
"self",
",",
"method",
",",
"params",
")",
":",
"response",
"=",
"await",
"self",
".",
"_coro_make_request",
"(",
"method",
",",
"params",
")",
"if",
"\"error\"",
"in",
"response",
":",
"raise",
"ValueError",
"(",
"resp... | Couroutine for making a request using the provider | [
"Couroutine",
"for",
"making",
"a",
"request",
"using",
"the",
"provider"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/manager.py#L101-L113 |
239,258 | ethereum/web3.py | web3/middleware/fixture.py | construct_fixture_middleware | def construct_fixture_middleware(fixtures):
"""
Constructs a middleware which returns a static response for any method
which is found in the provided fixtures.
"""
def fixture_middleware(make_request, web3):
def middleware(method, params):
if method in fixtures:
result = fixtures[method]
return {'result': result}
else:
return make_request(method, params)
return middleware
return fixture_middleware | python | def construct_fixture_middleware(fixtures):
def fixture_middleware(make_request, web3):
def middleware(method, params):
if method in fixtures:
result = fixtures[method]
return {'result': result}
else:
return make_request(method, params)
return middleware
return fixture_middleware | [
"def",
"construct_fixture_middleware",
"(",
"fixtures",
")",
":",
"def",
"fixture_middleware",
"(",
"make_request",
",",
"web3",
")",
":",
"def",
"middleware",
"(",
"method",
",",
"params",
")",
":",
"if",
"method",
"in",
"fixtures",
":",
"result",
"=",
"fix... | Constructs a middleware which returns a static response for any method
which is found in the provided fixtures. | [
"Constructs",
"a",
"middleware",
"which",
"returns",
"a",
"static",
"response",
"for",
"any",
"method",
"which",
"is",
"found",
"in",
"the",
"provided",
"fixtures",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/fixture.py#L1-L14 |
239,259 | ethereum/web3.py | web3/middleware/__init__.py | combine_middlewares | def combine_middlewares(middlewares, web3, provider_request_fn):
"""
Returns a callable function which will call the provider.provider_request
function wrapped with all of the middlewares.
"""
return functools.reduce(
lambda request_fn, middleware: middleware(request_fn, web3),
reversed(middlewares),
provider_request_fn,
) | python | def combine_middlewares(middlewares, web3, provider_request_fn):
return functools.reduce(
lambda request_fn, middleware: middleware(request_fn, web3),
reversed(middlewares),
provider_request_fn,
) | [
"def",
"combine_middlewares",
"(",
"middlewares",
",",
"web3",
",",
"provider_request_fn",
")",
":",
"return",
"functools",
".",
"reduce",
"(",
"lambda",
"request_fn",
",",
"middleware",
":",
"middleware",
"(",
"request_fn",
",",
"web3",
")",
",",
"reversed",
... | Returns a callable function which will call the provider.provider_request
function wrapped with all of the middlewares. | [
"Returns",
"a",
"callable",
"function",
"which",
"will",
"call",
"the",
"provider",
".",
"provider_request",
"function",
"wrapped",
"with",
"all",
"of",
"the",
"middlewares",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/__init__.py#L67-L76 |
239,260 | ethereum/web3.py | web3/_utils/events.py | get_event_data | def get_event_data(event_abi, log_entry):
"""
Given an event ABI and a log entry for that event, return the decoded
event data
"""
if event_abi['anonymous']:
log_topics = log_entry['topics']
elif not log_entry['topics']:
raise MismatchedABI("Expected non-anonymous event to have 1 or more topics")
elif event_abi_to_log_topic(event_abi) != log_entry['topics'][0]:
raise MismatchedABI("The event signature did not match the provided ABI")
else:
log_topics = log_entry['topics'][1:]
log_topics_abi = get_indexed_event_inputs(event_abi)
log_topic_normalized_inputs = normalize_event_input_types(log_topics_abi)
log_topic_types = get_event_abi_types_for_decoding(log_topic_normalized_inputs)
log_topic_names = get_abi_input_names({'inputs': log_topics_abi})
if len(log_topics) != len(log_topic_types):
raise ValueError("Expected {0} log topics. Got {1}".format(
len(log_topic_types),
len(log_topics),
))
log_data = hexstr_if_str(to_bytes, log_entry['data'])
log_data_abi = exclude_indexed_event_inputs(event_abi)
log_data_normalized_inputs = normalize_event_input_types(log_data_abi)
log_data_types = get_event_abi_types_for_decoding(log_data_normalized_inputs)
log_data_names = get_abi_input_names({'inputs': log_data_abi})
# sanity check that there are not name intersections between the topic
# names and the data argument names.
duplicate_names = set(log_topic_names).intersection(log_data_names)
if duplicate_names:
raise ValueError(
"Invalid Event ABI: The following argument names are duplicated "
"between event inputs: '{0}'".format(', '.join(duplicate_names))
)
decoded_log_data = decode_abi(log_data_types, log_data)
normalized_log_data = map_abi_data(
BASE_RETURN_NORMALIZERS,
log_data_types,
decoded_log_data
)
decoded_topic_data = [
decode_single(topic_type, topic_data)
for topic_type, topic_data
in zip(log_topic_types, log_topics)
]
normalized_topic_data = map_abi_data(
BASE_RETURN_NORMALIZERS,
log_topic_types,
decoded_topic_data
)
event_args = dict(itertools.chain(
zip(log_topic_names, normalized_topic_data),
zip(log_data_names, normalized_log_data),
))
event_data = {
'args': event_args,
'event': event_abi['name'],
'logIndex': log_entry['logIndex'],
'transactionIndex': log_entry['transactionIndex'],
'transactionHash': log_entry['transactionHash'],
'address': log_entry['address'],
'blockHash': log_entry['blockHash'],
'blockNumber': log_entry['blockNumber'],
}
return AttributeDict.recursive(event_data) | python | def get_event_data(event_abi, log_entry):
if event_abi['anonymous']:
log_topics = log_entry['topics']
elif not log_entry['topics']:
raise MismatchedABI("Expected non-anonymous event to have 1 or more topics")
elif event_abi_to_log_topic(event_abi) != log_entry['topics'][0]:
raise MismatchedABI("The event signature did not match the provided ABI")
else:
log_topics = log_entry['topics'][1:]
log_topics_abi = get_indexed_event_inputs(event_abi)
log_topic_normalized_inputs = normalize_event_input_types(log_topics_abi)
log_topic_types = get_event_abi_types_for_decoding(log_topic_normalized_inputs)
log_topic_names = get_abi_input_names({'inputs': log_topics_abi})
if len(log_topics) != len(log_topic_types):
raise ValueError("Expected {0} log topics. Got {1}".format(
len(log_topic_types),
len(log_topics),
))
log_data = hexstr_if_str(to_bytes, log_entry['data'])
log_data_abi = exclude_indexed_event_inputs(event_abi)
log_data_normalized_inputs = normalize_event_input_types(log_data_abi)
log_data_types = get_event_abi_types_for_decoding(log_data_normalized_inputs)
log_data_names = get_abi_input_names({'inputs': log_data_abi})
# sanity check that there are not name intersections between the topic
# names and the data argument names.
duplicate_names = set(log_topic_names).intersection(log_data_names)
if duplicate_names:
raise ValueError(
"Invalid Event ABI: The following argument names are duplicated "
"between event inputs: '{0}'".format(', '.join(duplicate_names))
)
decoded_log_data = decode_abi(log_data_types, log_data)
normalized_log_data = map_abi_data(
BASE_RETURN_NORMALIZERS,
log_data_types,
decoded_log_data
)
decoded_topic_data = [
decode_single(topic_type, topic_data)
for topic_type, topic_data
in zip(log_topic_types, log_topics)
]
normalized_topic_data = map_abi_data(
BASE_RETURN_NORMALIZERS,
log_topic_types,
decoded_topic_data
)
event_args = dict(itertools.chain(
zip(log_topic_names, normalized_topic_data),
zip(log_data_names, normalized_log_data),
))
event_data = {
'args': event_args,
'event': event_abi['name'],
'logIndex': log_entry['logIndex'],
'transactionIndex': log_entry['transactionIndex'],
'transactionHash': log_entry['transactionHash'],
'address': log_entry['address'],
'blockHash': log_entry['blockHash'],
'blockNumber': log_entry['blockNumber'],
}
return AttributeDict.recursive(event_data) | [
"def",
"get_event_data",
"(",
"event_abi",
",",
"log_entry",
")",
":",
"if",
"event_abi",
"[",
"'anonymous'",
"]",
":",
"log_topics",
"=",
"log_entry",
"[",
"'topics'",
"]",
"elif",
"not",
"log_entry",
"[",
"'topics'",
"]",
":",
"raise",
"MismatchedABI",
"("... | Given an event ABI and a log entry for that event, return the decoded
event data | [
"Given",
"an",
"event",
"ABI",
"and",
"a",
"log",
"entry",
"for",
"that",
"event",
"return",
"the",
"decoded",
"event",
"data"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/events.py#L159-L233 |
239,261 | ethereum/web3.py | web3/middleware/exception_retry_request.py | exception_retry_middleware | def exception_retry_middleware(make_request, web3, errors, retries=5):
"""
Creates middleware that retries failed HTTP requests. Is a default
middleware for HTTPProvider.
"""
def middleware(method, params):
if check_if_retry_on_failure(method):
for i in range(retries):
try:
return make_request(method, params)
except errors:
if i < retries - 1:
continue
else:
raise
else:
return make_request(method, params)
return middleware | python | def exception_retry_middleware(make_request, web3, errors, retries=5):
def middleware(method, params):
if check_if_retry_on_failure(method):
for i in range(retries):
try:
return make_request(method, params)
except errors:
if i < retries - 1:
continue
else:
raise
else:
return make_request(method, params)
return middleware | [
"def",
"exception_retry_middleware",
"(",
"make_request",
",",
"web3",
",",
"errors",
",",
"retries",
"=",
"5",
")",
":",
"def",
"middleware",
"(",
"method",
",",
"params",
")",
":",
"if",
"check_if_retry_on_failure",
"(",
"method",
")",
":",
"for",
"i",
"... | Creates middleware that retries failed HTTP requests. Is a default
middleware for HTTPProvider. | [
"Creates",
"middleware",
"that",
"retries",
"failed",
"HTTP",
"requests",
".",
"Is",
"a",
"default",
"middleware",
"for",
"HTTPProvider",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/exception_retry_request.py#L71-L88 |
239,262 | ethereum/web3.py | web3/iban.py | mod9710 | def mod9710(iban):
"""
Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064.
@method mod9710
@param {String} iban
@returns {Number}
"""
remainder = iban
block = None
while len(remainder) > 2:
block = remainder[:9]
remainder = str(int(block) % 97) + remainder[len(block):]
return int(remainder) % 97 | python | def mod9710(iban):
remainder = iban
block = None
while len(remainder) > 2:
block = remainder[:9]
remainder = str(int(block) % 97) + remainder[len(block):]
return int(remainder) % 97 | [
"def",
"mod9710",
"(",
"iban",
")",
":",
"remainder",
"=",
"iban",
"block",
"=",
"None",
"while",
"len",
"(",
"remainder",
")",
">",
"2",
":",
"block",
"=",
"remainder",
"[",
":",
"9",
"]",
"remainder",
"=",
"str",
"(",
"int",
"(",
"block",
")",
... | Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064.
@method mod9710
@param {String} iban
@returns {Number} | [
"Calculates",
"the",
"MOD",
"97",
"10",
"of",
"the",
"passed",
"IBAN",
"as",
"specified",
"in",
"ISO7064",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/iban.py#L44-L59 |
239,263 | ethereum/web3.py | web3/iban.py | baseN | def baseN(num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
"""
This prototype should be used to create
an iban object from iban correct string
@param {String} iban
"""
return ((num == 0) and numerals[0]) or \
(baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b]) | python | def baseN(num, b, numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
return ((num == 0) and numerals[0]) or \
(baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b]) | [
"def",
"baseN",
"(",
"num",
",",
"b",
",",
"numerals",
"=",
"\"0123456789abcdefghijklmnopqrstuvwxyz\"",
")",
":",
"return",
"(",
"(",
"num",
"==",
"0",
")",
"and",
"numerals",
"[",
"0",
"]",
")",
"or",
"(",
"baseN",
"(",
"num",
"//",
"b",
",",
"b",
... | This prototype should be used to create
an iban object from iban correct string
@param {String} iban | [
"This",
"prototype",
"should",
"be",
"used",
"to",
"create",
"an",
"iban",
"object",
"from",
"iban",
"correct",
"string"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/iban.py#L62-L70 |
239,264 | ethereum/web3.py | web3/iban.py | Iban.fromAddress | def fromAddress(address):
"""
This method should be used to create
an iban object from ethereum address
@method fromAddress
@param {String} address
@return {Iban} the IBAN object
"""
validate_address(address)
address_as_integer = int(address, 16)
address_as_base36 = baseN(address_as_integer, 36)
padded = pad_left_hex(address_as_base36, 15)
return Iban.fromBban(padded.upper()) | python | def fromAddress(address):
validate_address(address)
address_as_integer = int(address, 16)
address_as_base36 = baseN(address_as_integer, 36)
padded = pad_left_hex(address_as_base36, 15)
return Iban.fromBban(padded.upper()) | [
"def",
"fromAddress",
"(",
"address",
")",
":",
"validate_address",
"(",
"address",
")",
"address_as_integer",
"=",
"int",
"(",
"address",
",",
"16",
")",
"address_as_base36",
"=",
"baseN",
"(",
"address_as_integer",
",",
"36",
")",
"padded",
"=",
"pad_left_he... | This method should be used to create
an iban object from ethereum address
@method fromAddress
@param {String} address
@return {Iban} the IBAN object | [
"This",
"method",
"should",
"be",
"used",
"to",
"create",
"an",
"iban",
"object",
"from",
"ethereum",
"address"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/iban.py#L105-L118 |
239,265 | ethereum/web3.py | web3/iban.py | Iban.address | def address(self):
"""
Should be called to get client direct address
@method address
@returns {String} client direct address
"""
if self.isDirect():
base36 = self._iban[4:]
asInt = int(base36, 36)
return to_checksum_address(pad_left_hex(baseN(asInt, 16), 20))
return "" | python | def address(self):
if self.isDirect():
base36 = self._iban[4:]
asInt = int(base36, 36)
return to_checksum_address(pad_left_hex(baseN(asInt, 16), 20))
return "" | [
"def",
"address",
"(",
"self",
")",
":",
"if",
"self",
".",
"isDirect",
"(",
")",
":",
"base36",
"=",
"self",
".",
"_iban",
"[",
"4",
":",
"]",
"asInt",
"=",
"int",
"(",
"base36",
",",
"36",
")",
"return",
"to_checksum_address",
"(",
"pad_left_hex",
... | Should be called to get client direct address
@method address
@returns {String} client direct address | [
"Should",
"be",
"called",
"to",
"get",
"client",
"direct",
"address"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/iban.py#L207-L219 |
239,266 | ethereum/web3.py | web3/middleware/filter.py | block_ranges | def block_ranges(start_block, last_block, step=5):
"""Returns 2-tuple ranges describing ranges of block from start_block to last_block
Ranges do not overlap to facilitate use as ``toBlock``, ``fromBlock``
json-rpc arguments, which are both inclusive.
"""
if last_block is not None and start_block > last_block:
raise TypeError(
"Incompatible start and stop arguments.",
"Start must be less than or equal to stop.")
return (
(from_block, to_block - 1)
for from_block, to_block
in segment_count(start_block, last_block + 1, step)
) | python | def block_ranges(start_block, last_block, step=5):
if last_block is not None and start_block > last_block:
raise TypeError(
"Incompatible start and stop arguments.",
"Start must be less than or equal to stop.")
return (
(from_block, to_block - 1)
for from_block, to_block
in segment_count(start_block, last_block + 1, step)
) | [
"def",
"block_ranges",
"(",
"start_block",
",",
"last_block",
",",
"step",
"=",
"5",
")",
":",
"if",
"last_block",
"is",
"not",
"None",
"and",
"start_block",
">",
"last_block",
":",
"raise",
"TypeError",
"(",
"\"Incompatible start and stop arguments.\"",
",",
"\... | Returns 2-tuple ranges describing ranges of block from start_block to last_block
Ranges do not overlap to facilitate use as ``toBlock``, ``fromBlock``
json-rpc arguments, which are both inclusive. | [
"Returns",
"2",
"-",
"tuple",
"ranges",
"describing",
"ranges",
"of",
"block",
"from",
"start_block",
"to",
"last_block"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/filter.py#L68-L84 |
239,267 | ethereum/web3.py | web3/middleware/filter.py | get_logs_multipart | def get_logs_multipart(
w3,
startBlock,
stopBlock,
address,
topics,
max_blocks):
"""Used to break up requests to ``eth_getLogs``
The getLog request is partitioned into multiple calls of the max number of blocks
``max_blocks``.
"""
_block_ranges = block_ranges(startBlock, stopBlock, max_blocks)
for from_block, to_block in _block_ranges:
params = {
'fromBlock': from_block,
'toBlock': to_block,
'address': address,
'topics': topics
}
yield w3.eth.getLogs(
drop_items_with_none_value(params)) | python | def get_logs_multipart(
w3,
startBlock,
stopBlock,
address,
topics,
max_blocks):
_block_ranges = block_ranges(startBlock, stopBlock, max_blocks)
for from_block, to_block in _block_ranges:
params = {
'fromBlock': from_block,
'toBlock': to_block,
'address': address,
'topics': topics
}
yield w3.eth.getLogs(
drop_items_with_none_value(params)) | [
"def",
"get_logs_multipart",
"(",
"w3",
",",
"startBlock",
",",
"stopBlock",
",",
"address",
",",
"topics",
",",
"max_blocks",
")",
":",
"_block_ranges",
"=",
"block_ranges",
"(",
"startBlock",
",",
"stopBlock",
",",
"max_blocks",
")",
"for",
"from_block",
","... | Used to break up requests to ``eth_getLogs``
The getLog request is partitioned into multiple calls of the max number of blocks
``max_blocks``. | [
"Used",
"to",
"break",
"up",
"requests",
"to",
"eth_getLogs"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/filter.py#L158-L179 |
239,268 | ethereum/web3.py | web3/method.py | Method.method_selector_fn | def method_selector_fn(self):
"""Gets the method selector from the config.
"""
if callable(self.json_rpc_method):
return self.json_rpc_method
elif isinstance(self.json_rpc_method, (str,)):
return lambda *_: self.json_rpc_method
raise ValueError("``json_rpc_method`` config invalid. May be a string or function") | python | def method_selector_fn(self):
if callable(self.json_rpc_method):
return self.json_rpc_method
elif isinstance(self.json_rpc_method, (str,)):
return lambda *_: self.json_rpc_method
raise ValueError("``json_rpc_method`` config invalid. May be a string or function") | [
"def",
"method_selector_fn",
"(",
"self",
")",
":",
"if",
"callable",
"(",
"self",
".",
"json_rpc_method",
")",
":",
"return",
"self",
".",
"json_rpc_method",
"elif",
"isinstance",
"(",
"self",
".",
"json_rpc_method",
",",
"(",
"str",
",",
")",
")",
":",
... | Gets the method selector from the config. | [
"Gets",
"the",
"method",
"selector",
"from",
"the",
"config",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/method.py#L97-L104 |
239,269 | ethereum/web3.py | web3/_utils/encoding.py | hex_encode_abi_type | def hex_encode_abi_type(abi_type, value, force_size=None):
"""
Encodes value into a hex string in format of abi_type
"""
validate_abi_type(abi_type)
validate_abi_value(abi_type, value)
data_size = force_size or size_of_type(abi_type)
if is_array_type(abi_type):
sub_type = sub_type_of_array_type(abi_type)
return "".join([remove_0x_prefix(hex_encode_abi_type(sub_type, v, 256)) for v in value])
elif is_bool_type(abi_type):
return to_hex_with_size(value, data_size)
elif is_uint_type(abi_type):
return to_hex_with_size(value, data_size)
elif is_int_type(abi_type):
return to_hex_twos_compliment(value, data_size)
elif is_address_type(abi_type):
return pad_hex(value, data_size)
elif is_bytes_type(abi_type):
if is_bytes(value):
return encode_hex(value)
else:
return value
elif is_string_type(abi_type):
return to_hex(text=value)
else:
raise ValueError(
"Unsupported ABI type: {0}".format(abi_type)
) | python | def hex_encode_abi_type(abi_type, value, force_size=None):
validate_abi_type(abi_type)
validate_abi_value(abi_type, value)
data_size = force_size or size_of_type(abi_type)
if is_array_type(abi_type):
sub_type = sub_type_of_array_type(abi_type)
return "".join([remove_0x_prefix(hex_encode_abi_type(sub_type, v, 256)) for v in value])
elif is_bool_type(abi_type):
return to_hex_with_size(value, data_size)
elif is_uint_type(abi_type):
return to_hex_with_size(value, data_size)
elif is_int_type(abi_type):
return to_hex_twos_compliment(value, data_size)
elif is_address_type(abi_type):
return pad_hex(value, data_size)
elif is_bytes_type(abi_type):
if is_bytes(value):
return encode_hex(value)
else:
return value
elif is_string_type(abi_type):
return to_hex(text=value)
else:
raise ValueError(
"Unsupported ABI type: {0}".format(abi_type)
) | [
"def",
"hex_encode_abi_type",
"(",
"abi_type",
",",
"value",
",",
"force_size",
"=",
"None",
")",
":",
"validate_abi_type",
"(",
"abi_type",
")",
"validate_abi_value",
"(",
"abi_type",
",",
"value",
")",
"data_size",
"=",
"force_size",
"or",
"size_of_type",
"(",... | Encodes value into a hex string in format of abi_type | [
"Encodes",
"value",
"into",
"a",
"hex",
"string",
"in",
"format",
"of",
"abi_type"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/encoding.py#L50-L79 |
239,270 | ethereum/web3.py | web3/_utils/encoding.py | to_hex_twos_compliment | def to_hex_twos_compliment(value, bit_size):
"""
Converts integer value to twos compliment hex representation with given bit_size
"""
if value >= 0:
return to_hex_with_size(value, bit_size)
value = (1 << bit_size) + value
hex_value = hex(value)
hex_value = hex_value.rstrip("L")
return hex_value | python | def to_hex_twos_compliment(value, bit_size):
if value >= 0:
return to_hex_with_size(value, bit_size)
value = (1 << bit_size) + value
hex_value = hex(value)
hex_value = hex_value.rstrip("L")
return hex_value | [
"def",
"to_hex_twos_compliment",
"(",
"value",
",",
"bit_size",
")",
":",
"if",
"value",
">=",
"0",
":",
"return",
"to_hex_with_size",
"(",
"value",
",",
"bit_size",
")",
"value",
"=",
"(",
"1",
"<<",
"bit_size",
")",
"+",
"value",
"hex_value",
"=",
"hex... | Converts integer value to twos compliment hex representation with given bit_size | [
"Converts",
"integer",
"value",
"to",
"twos",
"compliment",
"hex",
"representation",
"with",
"given",
"bit_size"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/encoding.py#L82-L92 |
239,271 | ethereum/web3.py | web3/_utils/encoding.py | pad_hex | def pad_hex(value, bit_size):
"""
Pads a hex string up to the given bit_size
"""
value = remove_0x_prefix(value)
return add_0x_prefix(value.zfill(int(bit_size / 4))) | python | def pad_hex(value, bit_size):
value = remove_0x_prefix(value)
return add_0x_prefix(value.zfill(int(bit_size / 4))) | [
"def",
"pad_hex",
"(",
"value",
",",
"bit_size",
")",
":",
"value",
"=",
"remove_0x_prefix",
"(",
"value",
")",
"return",
"add_0x_prefix",
"(",
"value",
".",
"zfill",
"(",
"int",
"(",
"bit_size",
"/",
"4",
")",
")",
")"
] | Pads a hex string up to the given bit_size | [
"Pads",
"a",
"hex",
"string",
"up",
"to",
"the",
"given",
"bit_size"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/encoding.py#L102-L107 |
239,272 | ethereum/web3.py | web3/_utils/encoding.py | to_int | def to_int(value=None, hexstr=None, text=None):
"""
Converts value to it's integer representation.
Values are converted this way:
* value:
* bytes: big-endian integer
* bool: True => 1, False => 0
* hexstr: interpret hex as integer
* text: interpret as string of digits, like '12' => 12
"""
assert_one_val(value, hexstr=hexstr, text=text)
if hexstr is not None:
return int(hexstr, 16)
elif text is not None:
return int(text)
elif isinstance(value, bytes):
return big_endian_to_int(value)
elif isinstance(value, str):
raise TypeError("Pass in strings with keyword hexstr or text")
else:
return int(value) | python | def to_int(value=None, hexstr=None, text=None):
assert_one_val(value, hexstr=hexstr, text=text)
if hexstr is not None:
return int(hexstr, 16)
elif text is not None:
return int(text)
elif isinstance(value, bytes):
return big_endian_to_int(value)
elif isinstance(value, str):
raise TypeError("Pass in strings with keyword hexstr or text")
else:
return int(value) | [
"def",
"to_int",
"(",
"value",
"=",
"None",
",",
"hexstr",
"=",
"None",
",",
"text",
"=",
"None",
")",
":",
"assert_one_val",
"(",
"value",
",",
"hexstr",
"=",
"hexstr",
",",
"text",
"=",
"text",
")",
"if",
"hexstr",
"is",
"not",
"None",
":",
"retu... | Converts value to it's integer representation.
Values are converted this way:
* value:
* bytes: big-endian integer
* bool: True => 1, False => 0
* hexstr: interpret hex as integer
* text: interpret as string of digits, like '12' => 12 | [
"Converts",
"value",
"to",
"it",
"s",
"integer",
"representation",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/encoding.py#L118-L141 |
239,273 | ethereum/web3.py | web3/pm.py | VyperReferenceRegistry.deploy_new_instance | def deploy_new_instance(cls, w3: Web3) -> "VyperReferenceRegistry":
"""
Returns a new instance of ```VyperReferenceRegistry`` representing a freshly deployed
instance on the given ``web3`` instance of the Vyper Reference Registry implementation.
"""
manifest = get_vyper_registry_manifest()
registry_package = Package(manifest, w3)
registry_factory = registry_package.get_contract_factory("registry")
tx_hash = registry_factory.constructor().transact()
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
registry_address = to_canonical_address(tx_receipt.contractAddress)
return cls(registry_address, w3) | python | def deploy_new_instance(cls, w3: Web3) -> "VyperReferenceRegistry":
manifest = get_vyper_registry_manifest()
registry_package = Package(manifest, w3)
registry_factory = registry_package.get_contract_factory("registry")
tx_hash = registry_factory.constructor().transact()
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
registry_address = to_canonical_address(tx_receipt.contractAddress)
return cls(registry_address, w3) | [
"def",
"deploy_new_instance",
"(",
"cls",
",",
"w3",
":",
"Web3",
")",
"->",
"\"VyperReferenceRegistry\"",
":",
"manifest",
"=",
"get_vyper_registry_manifest",
"(",
")",
"registry_package",
"=",
"Package",
"(",
"manifest",
",",
"w3",
")",
"registry_factory",
"=",
... | Returns a new instance of ```VyperReferenceRegistry`` representing a freshly deployed
instance on the given ``web3`` instance of the Vyper Reference Registry implementation. | [
"Returns",
"a",
"new",
"instance",
"of",
"VyperReferenceRegistry",
"representing",
"a",
"freshly",
"deployed",
"instance",
"on",
"the",
"given",
"web3",
"instance",
"of",
"the",
"Vyper",
"Reference",
"Registry",
"implementation",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L230-L241 |
239,274 | ethereum/web3.py | web3/pm.py | VyperReferenceRegistry.transfer_owner | def transfer_owner(self, new_owner: Address) -> TxReceipt:
"""
Transfers ownership of this registry instance to the given ``new_owner``. Only the
``owner`` is allowed to transfer ownership.
* Parameters:
* ``new_owner``: The address of the new owner.
"""
tx_hash = self.registry.functions.transferOwner(new_owner).transact()
return self.w3.eth.waitForTransactionReceipt(tx_hash) | python | def transfer_owner(self, new_owner: Address) -> TxReceipt:
tx_hash = self.registry.functions.transferOwner(new_owner).transact()
return self.w3.eth.waitForTransactionReceipt(tx_hash) | [
"def",
"transfer_owner",
"(",
"self",
",",
"new_owner",
":",
"Address",
")",
"->",
"TxReceipt",
":",
"tx_hash",
"=",
"self",
".",
"registry",
".",
"functions",
".",
"transferOwner",
"(",
"new_owner",
")",
".",
"transact",
"(",
")",
"return",
"self",
".",
... | Transfers ownership of this registry instance to the given ``new_owner``. Only the
``owner`` is allowed to transfer ownership.
* Parameters:
* ``new_owner``: The address of the new owner. | [
"Transfers",
"ownership",
"of",
"this",
"registry",
"instance",
"to",
"the",
"given",
"new_owner",
".",
"Only",
"the",
"owner",
"is",
"allowed",
"to",
"transfer",
"ownership",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L311-L320 |
239,275 | ethereum/web3.py | web3/pm.py | PM.release_package | def release_package(
self, package_name: str, version: str, manifest_uri: str
) -> bytes:
"""
Returns the release id generated by releasing a package on the current registry.
Requires ``web3.PM`` to have a registry set. Requires ``web3.eth.defaultAccount``
to be the registry owner.
* Parameters:
* ``package_name``: Must be a valid package name, matching the given manifest.
* ``version``: Must be a valid package version, matching the given manifest.
* ``manifest_uri``: Must be a valid content-addressed URI. Currently, only IPFS
and Github content-addressed URIs are supported.
"""
validate_is_supported_manifest_uri(manifest_uri)
raw_manifest = to_text(resolve_uri_contents(manifest_uri))
validate_raw_manifest_format(raw_manifest)
manifest = json.loads(raw_manifest)
validate_manifest_against_schema(manifest)
if package_name != manifest['package_name']:
raise ManifestValidationError(
f"Provided package name: {package_name} does not match the package name "
f"found in the manifest: {manifest['package_name']}."
)
if version != manifest['version']:
raise ManifestValidationError(
f"Provided package version: {version} does not match the package version "
f"found in the manifest: {manifest['version']}."
)
self._validate_set_registry()
return self.registry._release(package_name, version, manifest_uri) | python | def release_package(
self, package_name: str, version: str, manifest_uri: str
) -> bytes:
validate_is_supported_manifest_uri(manifest_uri)
raw_manifest = to_text(resolve_uri_contents(manifest_uri))
validate_raw_manifest_format(raw_manifest)
manifest = json.loads(raw_manifest)
validate_manifest_against_schema(manifest)
if package_name != manifest['package_name']:
raise ManifestValidationError(
f"Provided package name: {package_name} does not match the package name "
f"found in the manifest: {manifest['package_name']}."
)
if version != manifest['version']:
raise ManifestValidationError(
f"Provided package version: {version} does not match the package version "
f"found in the manifest: {manifest['version']}."
)
self._validate_set_registry()
return self.registry._release(package_name, version, manifest_uri) | [
"def",
"release_package",
"(",
"self",
",",
"package_name",
":",
"str",
",",
"version",
":",
"str",
",",
"manifest_uri",
":",
"str",
")",
"->",
"bytes",
":",
"validate_is_supported_manifest_uri",
"(",
"manifest_uri",
")",
"raw_manifest",
"=",
"to_text",
"(",
"... | Returns the release id generated by releasing a package on the current registry.
Requires ``web3.PM`` to have a registry set. Requires ``web3.eth.defaultAccount``
to be the registry owner.
* Parameters:
* ``package_name``: Must be a valid package name, matching the given manifest.
* ``version``: Must be a valid package version, matching the given manifest.
* ``manifest_uri``: Must be a valid content-addressed URI. Currently, only IPFS
and Github content-addressed URIs are supported. | [
"Returns",
"the",
"release",
"id",
"generated",
"by",
"releasing",
"a",
"package",
"on",
"the",
"current",
"registry",
".",
"Requires",
"web3",
".",
"PM",
"to",
"have",
"a",
"registry",
"set",
".",
"Requires",
"web3",
".",
"eth",
".",
"defaultAccount",
"to... | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L471-L504 |
239,276 | ethereum/web3.py | web3/pm.py | PM.get_all_package_names | def get_all_package_names(self) -> Iterable[str]:
"""
Returns a tuple containing all the package names available on the current registry.
"""
self._validate_set_registry()
package_ids = self.registry._get_all_package_ids()
for package_id in package_ids:
yield self.registry._get_package_name(package_id) | python | def get_all_package_names(self) -> Iterable[str]:
self._validate_set_registry()
package_ids = self.registry._get_all_package_ids()
for package_id in package_ids:
yield self.registry._get_package_name(package_id) | [
"def",
"get_all_package_names",
"(",
"self",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"self",
".",
"_validate_set_registry",
"(",
")",
"package_ids",
"=",
"self",
".",
"registry",
".",
"_get_all_package_ids",
"(",
")",
"for",
"package_id",
"in",
"package_i... | Returns a tuple containing all the package names available on the current registry. | [
"Returns",
"a",
"tuple",
"containing",
"all",
"the",
"package",
"names",
"available",
"on",
"the",
"current",
"registry",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L507-L514 |
239,277 | ethereum/web3.py | web3/pm.py | PM.get_release_count | def get_release_count(self, package_name: str) -> int:
"""
Returns the number of releases of the given package name available on the current registry.
"""
validate_package_name(package_name)
self._validate_set_registry()
return self.registry._num_release_ids(package_name) | python | def get_release_count(self, package_name: str) -> int:
validate_package_name(package_name)
self._validate_set_registry()
return self.registry._num_release_ids(package_name) | [
"def",
"get_release_count",
"(",
"self",
",",
"package_name",
":",
"str",
")",
"->",
"int",
":",
"validate_package_name",
"(",
"package_name",
")",
"self",
".",
"_validate_set_registry",
"(",
")",
"return",
"self",
".",
"registry",
".",
"_num_release_ids",
"(",
... | Returns the number of releases of the given package name available on the current registry. | [
"Returns",
"the",
"number",
"of",
"releases",
"of",
"the",
"given",
"package",
"name",
"available",
"on",
"the",
"current",
"registry",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L523-L529 |
239,278 | ethereum/web3.py | web3/pm.py | PM.get_release_id | def get_release_id(self, package_name: str, version: str) -> bytes:
"""
Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry.
"""
validate_package_name(package_name)
validate_package_version(version)
self._validate_set_registry()
return self.registry._get_release_id(package_name, version) | python | def get_release_id(self, package_name: str, version: str) -> bytes:
validate_package_name(package_name)
validate_package_version(version)
self._validate_set_registry()
return self.registry._get_release_id(package_name, version) | [
"def",
"get_release_id",
"(",
"self",
",",
"package_name",
":",
"str",
",",
"version",
":",
"str",
")",
"->",
"bytes",
":",
"validate_package_name",
"(",
"package_name",
")",
"validate_package_version",
"(",
"version",
")",
"self",
".",
"_validate_set_registry",
... | Returns the 32 byte identifier of a release for the given package name and version,
if they are available on the current registry. | [
"Returns",
"the",
"32",
"byte",
"identifier",
"of",
"a",
"release",
"for",
"the",
"given",
"package",
"name",
"and",
"version",
"if",
"they",
"are",
"available",
"on",
"the",
"current",
"registry",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L531-L539 |
239,279 | ethereum/web3.py | web3/pm.py | PM.get_package | def get_package(self, package_name: str, version: str) -> Package:
"""
Returns a ``Package`` instance, generated by the ``manifest_uri`` associated with the
given package name and version, if they are published to the currently set registry.
* Parameters:
* ``name``: Must be a valid package name.
* ``version``: Must be a valid package version.
"""
validate_package_name(package_name)
validate_package_version(version)
self._validate_set_registry()
_, _, release_uri = self.get_release_data(package_name, version)
return self.get_package_from_uri(release_uri) | python | def get_package(self, package_name: str, version: str) -> Package:
validate_package_name(package_name)
validate_package_version(version)
self._validate_set_registry()
_, _, release_uri = self.get_release_data(package_name, version)
return self.get_package_from_uri(release_uri) | [
"def",
"get_package",
"(",
"self",
",",
"package_name",
":",
"str",
",",
"version",
":",
"str",
")",
"->",
"Package",
":",
"validate_package_name",
"(",
"package_name",
")",
"validate_package_version",
"(",
"version",
")",
"self",
".",
"_validate_set_registry",
... | Returns a ``Package`` instance, generated by the ``manifest_uri`` associated with the
given package name and version, if they are published to the currently set registry.
* Parameters:
* ``name``: Must be a valid package name.
* ``version``: Must be a valid package version. | [
"Returns",
"a",
"Package",
"instance",
"generated",
"by",
"the",
"manifest_uri",
"associated",
"with",
"the",
"given",
"package",
"name",
"and",
"version",
"if",
"they",
"are",
"published",
"to",
"the",
"currently",
"set",
"registry",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/pm.py#L580-L593 |
239,280 | ethereum/web3.py | web3/_utils/filters.py | normalize_data_values | def normalize_data_values(type_string, data_value):
"""Decodes utf-8 bytes to strings for abi string values.
eth-abi v1 returns utf-8 bytes for string values.
This can be removed once eth-abi v2 is required.
"""
_type = parse_type_string(type_string)
if _type.base == "string":
if _type.arrlist is not None:
return tuple((normalize_to_text(value) for value in data_value))
else:
return normalize_to_text(data_value)
return data_value | python | def normalize_data_values(type_string, data_value):
_type = parse_type_string(type_string)
if _type.base == "string":
if _type.arrlist is not None:
return tuple((normalize_to_text(value) for value in data_value))
else:
return normalize_to_text(data_value)
return data_value | [
"def",
"normalize_data_values",
"(",
"type_string",
",",
"data_value",
")",
":",
"_type",
"=",
"parse_type_string",
"(",
"type_string",
")",
"if",
"_type",
".",
"base",
"==",
"\"string\"",
":",
"if",
"_type",
".",
"arrlist",
"is",
"not",
"None",
":",
"return... | Decodes utf-8 bytes to strings for abi string values.
eth-abi v1 returns utf-8 bytes for string values.
This can be removed once eth-abi v2 is required. | [
"Decodes",
"utf",
"-",
"8",
"bytes",
"to",
"strings",
"for",
"abi",
"string",
"values",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/filters.py#L192-L204 |
239,281 | ethereum/web3.py | web3/_utils/filters.py | match_fn | def match_fn(match_values_and_abi, data):
"""Match function used for filtering non-indexed event arguments.
Values provided through the match_values_and_abi parameter are
compared to the abi decoded log data.
"""
abi_types, all_match_values = zip(*match_values_and_abi)
decoded_values = decode_abi(abi_types, HexBytes(data))
for data_value, match_values, abi_type in zip(decoded_values, all_match_values, abi_types):
if match_values is None:
continue
normalized_data = normalize_data_values(abi_type, data_value)
for value in match_values:
if not is_encodable(abi_type, value):
raise ValueError(
"Value {0} is of the wrong abi type. "
"Expected {1} typed value.".format(value, abi_type))
if value == normalized_data:
break
else:
return False
return True | python | def match_fn(match_values_and_abi, data):
abi_types, all_match_values = zip(*match_values_and_abi)
decoded_values = decode_abi(abi_types, HexBytes(data))
for data_value, match_values, abi_type in zip(decoded_values, all_match_values, abi_types):
if match_values is None:
continue
normalized_data = normalize_data_values(abi_type, data_value)
for value in match_values:
if not is_encodable(abi_type, value):
raise ValueError(
"Value {0} is of the wrong abi type. "
"Expected {1} typed value.".format(value, abi_type))
if value == normalized_data:
break
else:
return False
return True | [
"def",
"match_fn",
"(",
"match_values_and_abi",
",",
"data",
")",
":",
"abi_types",
",",
"all_match_values",
"=",
"zip",
"(",
"*",
"match_values_and_abi",
")",
"decoded_values",
"=",
"decode_abi",
"(",
"abi_types",
",",
"HexBytes",
"(",
"data",
")",
")",
"for"... | Match function used for filtering non-indexed event arguments.
Values provided through the match_values_and_abi parameter are
compared to the abi decoded log data. | [
"Match",
"function",
"used",
"for",
"filtering",
"non",
"-",
"indexed",
"event",
"arguments",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/filters.py#L208-L230 |
239,282 | ethereum/web3.py | web3/middleware/attrdict.py | attrdict_middleware | def attrdict_middleware(make_request, web3):
"""
Converts any result which is a dictionary into an a
"""
def middleware(method, params):
response = make_request(method, params)
if 'result' in response:
result = response['result']
if is_dict(result) and not isinstance(result, AttributeDict):
return assoc(response, 'result', AttributeDict.recursive(result))
else:
return response
else:
return response
return middleware | python | def attrdict_middleware(make_request, web3):
def middleware(method, params):
response = make_request(method, params)
if 'result' in response:
result = response['result']
if is_dict(result) and not isinstance(result, AttributeDict):
return assoc(response, 'result', AttributeDict.recursive(result))
else:
return response
else:
return response
return middleware | [
"def",
"attrdict_middleware",
"(",
"make_request",
",",
"web3",
")",
":",
"def",
"middleware",
"(",
"method",
",",
"params",
")",
":",
"response",
"=",
"make_request",
"(",
"method",
",",
"params",
")",
"if",
"'result'",
"in",
"response",
":",
"result",
"=... | Converts any result which is a dictionary into an a | [
"Converts",
"any",
"result",
"which",
"is",
"a",
"dictionary",
"into",
"an",
"a"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/middleware/attrdict.py#L13-L28 |
239,283 | ethereum/web3.py | ens/main.py | ENS.fromWeb3 | def fromWeb3(cls, web3, addr=None):
"""
Generate an ENS instance with web3
:param `web3.Web3` web3: to infer connection information
:param hex-string addr: the address of the ENS registry on-chain. If not provided,
ENS.py will default to the mainnet ENS registry address.
"""
return cls(web3.manager.provider, addr=addr) | python | def fromWeb3(cls, web3, addr=None):
return cls(web3.manager.provider, addr=addr) | [
"def",
"fromWeb3",
"(",
"cls",
",",
"web3",
",",
"addr",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"web3",
".",
"manager",
".",
"provider",
",",
"addr",
"=",
"addr",
")"
] | Generate an ENS instance with web3
:param `web3.Web3` web3: to infer connection information
:param hex-string addr: the address of the ENS registry on-chain. If not provided,
ENS.py will default to the mainnet ENS registry address. | [
"Generate",
"an",
"ENS",
"instance",
"with",
"web3"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/ens/main.py#L65-L73 |
239,284 | ethereum/web3.py | ens/main.py | ENS.name | def name(self, address):
"""
Look up the name that the address points to, using a
reverse lookup. Reverse lookup is opt-in for name owners.
:param address:
:type address: hex-string
"""
reversed_domain = address_to_reverse_domain(address)
return self.resolve(reversed_domain, get='name') | python | def name(self, address):
reversed_domain = address_to_reverse_domain(address)
return self.resolve(reversed_domain, get='name') | [
"def",
"name",
"(",
"self",
",",
"address",
")",
":",
"reversed_domain",
"=",
"address_to_reverse_domain",
"(",
"address",
")",
"return",
"self",
".",
"resolve",
"(",
"reversed_domain",
",",
"get",
"=",
"'name'",
")"
] | Look up the name that the address points to, using a
reverse lookup. Reverse lookup is opt-in for name owners.
:param address:
:type address: hex-string | [
"Look",
"up",
"the",
"name",
"that",
"the",
"address",
"points",
"to",
"using",
"a",
"reverse",
"lookup",
".",
"Reverse",
"lookup",
"is",
"opt",
"-",
"in",
"for",
"name",
"owners",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/ens/main.py#L84-L93 |
239,285 | ethereum/web3.py | ens/main.py | ENS.setup_address | def setup_address(self, name, address=default, transact={}):
"""
Set up the name to point to the supplied address.
The sender of the transaction must own the name, or
its parent name.
Example: If the caller owns ``parentname.eth`` with no subdomains
and calls this method with ``sub.parentname.eth``,
then ``sub`` will be created as part of this call.
:param str name: ENS name to set up
:param str address: name will point to this address, in checksum format. If ``None``,
erase the record. If not specified, name will point to the owner's address.
:param dict transact: the transaction configuration, like in
:meth:`~web3.eth.Eth.sendTransaction`
:raises InvalidName: if ``name`` has invalid syntax
:raises UnauthorizedError: if ``'from'`` in `transact` does not own `name`
"""
owner = self.setup_owner(name, transact=transact)
self._assert_control(owner, name)
if is_none_or_zero_address(address):
address = None
elif address is default:
address = owner
elif is_binary_address(address):
address = to_checksum_address(address)
elif not is_checksum_address(address):
raise ValueError("You must supply the address in checksum format")
if self.address(name) == address:
return None
if address is None:
address = EMPTY_ADDR_HEX
transact['from'] = owner
resolver = self._set_resolver(name, transact=transact)
return resolver.functions.setAddr(raw_name_to_hash(name), address).transact(transact) | python | def setup_address(self, name, address=default, transact={}):
owner = self.setup_owner(name, transact=transact)
self._assert_control(owner, name)
if is_none_or_zero_address(address):
address = None
elif address is default:
address = owner
elif is_binary_address(address):
address = to_checksum_address(address)
elif not is_checksum_address(address):
raise ValueError("You must supply the address in checksum format")
if self.address(name) == address:
return None
if address is None:
address = EMPTY_ADDR_HEX
transact['from'] = owner
resolver = self._set_resolver(name, transact=transact)
return resolver.functions.setAddr(raw_name_to_hash(name), address).transact(transact) | [
"def",
"setup_address",
"(",
"self",
",",
"name",
",",
"address",
"=",
"default",
",",
"transact",
"=",
"{",
"}",
")",
":",
"owner",
"=",
"self",
".",
"setup_owner",
"(",
"name",
",",
"transact",
"=",
"transact",
")",
"self",
".",
"_assert_control",
"(... | Set up the name to point to the supplied address.
The sender of the transaction must own the name, or
its parent name.
Example: If the caller owns ``parentname.eth`` with no subdomains
and calls this method with ``sub.parentname.eth``,
then ``sub`` will be created as part of this call.
:param str name: ENS name to set up
:param str address: name will point to this address, in checksum format. If ``None``,
erase the record. If not specified, name will point to the owner's address.
:param dict transact: the transaction configuration, like in
:meth:`~web3.eth.Eth.sendTransaction`
:raises InvalidName: if ``name`` has invalid syntax
:raises UnauthorizedError: if ``'from'`` in `transact` does not own `name` | [
"Set",
"up",
"the",
"name",
"to",
"point",
"to",
"the",
"supplied",
"address",
".",
"The",
"sender",
"of",
"the",
"transaction",
"must",
"own",
"the",
"name",
"or",
"its",
"parent",
"name",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/ens/main.py#L96-L130 |
239,286 | ethereum/web3.py | ens/main.py | ENS.setup_owner | def setup_owner(self, name, new_owner=default, transact={}):
"""
Set the owner of the supplied name to `new_owner`.
For typical scenarios, you'll never need to call this method directly,
simply call :meth:`setup_name` or :meth:`setup_address`. This method does *not*
set up the name to point to an address.
If `new_owner` is not supplied, then this will assume you
want the same owner as the parent domain.
If the caller owns ``parentname.eth`` with no subdomains
and calls this method with ``sub.parentname.eth``,
then ``sub`` will be created as part of this call.
:param str name: ENS name to set up
:param new_owner: account that will own `name`. If ``None``, set owner to empty addr.
If not specified, name will point to the parent domain owner's address.
:param dict transact: the transaction configuration, like in
:meth:`~web3.eth.Eth.sendTransaction`
:raises InvalidName: if `name` has invalid syntax
:raises UnauthorizedError: if ``'from'`` in `transact` does not own `name`
:returns: the new owner's address
"""
(super_owner, unowned, owned) = self._first_owner(name)
if new_owner is default:
new_owner = super_owner
elif not new_owner:
new_owner = EMPTY_ADDR_HEX
else:
new_owner = to_checksum_address(new_owner)
current_owner = self.owner(name)
if new_owner == EMPTY_ADDR_HEX and not current_owner:
return None
elif current_owner == new_owner:
return current_owner
else:
self._assert_control(super_owner, name, owned)
self._claim_ownership(new_owner, unowned, owned, super_owner, transact=transact)
return new_owner | python | def setup_owner(self, name, new_owner=default, transact={}):
(super_owner, unowned, owned) = self._first_owner(name)
if new_owner is default:
new_owner = super_owner
elif not new_owner:
new_owner = EMPTY_ADDR_HEX
else:
new_owner = to_checksum_address(new_owner)
current_owner = self.owner(name)
if new_owner == EMPTY_ADDR_HEX and not current_owner:
return None
elif current_owner == new_owner:
return current_owner
else:
self._assert_control(super_owner, name, owned)
self._claim_ownership(new_owner, unowned, owned, super_owner, transact=transact)
return new_owner | [
"def",
"setup_owner",
"(",
"self",
",",
"name",
",",
"new_owner",
"=",
"default",
",",
"transact",
"=",
"{",
"}",
")",
":",
"(",
"super_owner",
",",
"unowned",
",",
"owned",
")",
"=",
"self",
".",
"_first_owner",
"(",
"name",
")",
"if",
"new_owner",
... | Set the owner of the supplied name to `new_owner`.
For typical scenarios, you'll never need to call this method directly,
simply call :meth:`setup_name` or :meth:`setup_address`. This method does *not*
set up the name to point to an address.
If `new_owner` is not supplied, then this will assume you
want the same owner as the parent domain.
If the caller owns ``parentname.eth`` with no subdomains
and calls this method with ``sub.parentname.eth``,
then ``sub`` will be created as part of this call.
:param str name: ENS name to set up
:param new_owner: account that will own `name`. If ``None``, set owner to empty addr.
If not specified, name will point to the parent domain owner's address.
:param dict transact: the transaction configuration, like in
:meth:`~web3.eth.Eth.sendTransaction`
:raises InvalidName: if `name` has invalid syntax
:raises UnauthorizedError: if ``'from'`` in `transact` does not own `name`
:returns: the new owner's address | [
"Set",
"the",
"owner",
"of",
"the",
"supplied",
"name",
"to",
"new_owner",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/ens/main.py#L213-L252 |
239,287 | ethereum/web3.py | ens/main.py | ENS._first_owner | def _first_owner(self, name):
"""
Takes a name, and returns the owner of the deepest subdomain that has an owner
:returns: (owner or None, list(unowned_subdomain_labels), first_owned_domain)
"""
owner = None
unowned = []
pieces = normalize_name(name).split('.')
while pieces and is_none_or_zero_address(owner):
name = '.'.join(pieces)
owner = self.owner(name)
if is_none_or_zero_address(owner):
unowned.append(pieces.pop(0))
return (owner, unowned, name) | python | def _first_owner(self, name):
owner = None
unowned = []
pieces = normalize_name(name).split('.')
while pieces and is_none_or_zero_address(owner):
name = '.'.join(pieces)
owner = self.owner(name)
if is_none_or_zero_address(owner):
unowned.append(pieces.pop(0))
return (owner, unowned, name) | [
"def",
"_first_owner",
"(",
"self",
",",
"name",
")",
":",
"owner",
"=",
"None",
"unowned",
"=",
"[",
"]",
"pieces",
"=",
"normalize_name",
"(",
"name",
")",
".",
"split",
"(",
"'.'",
")",
"while",
"pieces",
"and",
"is_none_or_zero_address",
"(",
"owner"... | Takes a name, and returns the owner of the deepest subdomain that has an owner
:returns: (owner or None, list(unowned_subdomain_labels), first_owned_domain) | [
"Takes",
"a",
"name",
"and",
"returns",
"the",
"owner",
"of",
"the",
"deepest",
"subdomain",
"that",
"has",
"an",
"owner"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/ens/main.py#L262-L276 |
239,288 | ethereum/web3.py | web3/contract.py | call_contract_function | def call_contract_function(
web3,
address,
normalizers,
function_identifier,
transaction,
block_id=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
"""
Helper function for interacting with a contract function using the
`eth_call` API.
"""
call_transaction = prepare_transaction(
address,
web3,
fn_identifier=function_identifier,
contract_abi=contract_abi,
fn_abi=fn_abi,
transaction=transaction,
fn_args=args,
fn_kwargs=kwargs,
)
if block_id is None:
return_data = web3.eth.call(call_transaction)
else:
return_data = web3.eth.call(call_transaction, block_identifier=block_id)
if fn_abi is None:
fn_abi = find_matching_fn_abi(contract_abi, function_identifier, args, kwargs)
output_types = get_abi_output_types(fn_abi)
try:
output_data = decode_abi(output_types, return_data)
except DecodingError as e:
# Provide a more helpful error message than the one provided by
# eth-abi-utils
is_missing_code_error = (
return_data in ACCEPTABLE_EMPTY_STRINGS and
web3.eth.getCode(address) in ACCEPTABLE_EMPTY_STRINGS
)
if is_missing_code_error:
msg = (
"Could not transact with/call contract function, is contract "
"deployed correctly and chain synced?"
)
else:
msg = (
"Could not decode contract function call {} return data {} for "
"output_types {}".format(
function_identifier,
return_data,
output_types
)
)
raise BadFunctionCallOutput(msg) from e
_normalizers = itertools.chain(
BASE_RETURN_NORMALIZERS,
normalizers,
)
normalized_data = map_abi_data(_normalizers, output_types, output_data)
if len(normalized_data) == 1:
return normalized_data[0]
else:
return normalized_data | python | def call_contract_function(
web3,
address,
normalizers,
function_identifier,
transaction,
block_id=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
call_transaction = prepare_transaction(
address,
web3,
fn_identifier=function_identifier,
contract_abi=contract_abi,
fn_abi=fn_abi,
transaction=transaction,
fn_args=args,
fn_kwargs=kwargs,
)
if block_id is None:
return_data = web3.eth.call(call_transaction)
else:
return_data = web3.eth.call(call_transaction, block_identifier=block_id)
if fn_abi is None:
fn_abi = find_matching_fn_abi(contract_abi, function_identifier, args, kwargs)
output_types = get_abi_output_types(fn_abi)
try:
output_data = decode_abi(output_types, return_data)
except DecodingError as e:
# Provide a more helpful error message than the one provided by
# eth-abi-utils
is_missing_code_error = (
return_data in ACCEPTABLE_EMPTY_STRINGS and
web3.eth.getCode(address) in ACCEPTABLE_EMPTY_STRINGS
)
if is_missing_code_error:
msg = (
"Could not transact with/call contract function, is contract "
"deployed correctly and chain synced?"
)
else:
msg = (
"Could not decode contract function call {} return data {} for "
"output_types {}".format(
function_identifier,
return_data,
output_types
)
)
raise BadFunctionCallOutput(msg) from e
_normalizers = itertools.chain(
BASE_RETURN_NORMALIZERS,
normalizers,
)
normalized_data = map_abi_data(_normalizers, output_types, output_data)
if len(normalized_data) == 1:
return normalized_data[0]
else:
return normalized_data | [
"def",
"call_contract_function",
"(",
"web3",
",",
"address",
",",
"normalizers",
",",
"function_identifier",
",",
"transaction",
",",
"block_id",
"=",
"None",
",",
"contract_abi",
"=",
"None",
",",
"fn_abi",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"... | Helper function for interacting with a contract function using the
`eth_call` API. | [
"Helper",
"function",
"for",
"interacting",
"with",
"a",
"contract",
"function",
"using",
"the",
"eth_call",
"API",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L1275-L1345 |
239,289 | ethereum/web3.py | web3/contract.py | transact_with_contract_function | def transact_with_contract_function(
address,
web3,
function_name=None,
transaction=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
"""
Helper function for interacting with a contract function by sending a
transaction.
"""
transact_transaction = prepare_transaction(
address,
web3,
fn_identifier=function_name,
contract_abi=contract_abi,
transaction=transaction,
fn_abi=fn_abi,
fn_args=args,
fn_kwargs=kwargs,
)
txn_hash = web3.eth.sendTransaction(transact_transaction)
return txn_hash | python | def transact_with_contract_function(
address,
web3,
function_name=None,
transaction=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
transact_transaction = prepare_transaction(
address,
web3,
fn_identifier=function_name,
contract_abi=contract_abi,
transaction=transaction,
fn_abi=fn_abi,
fn_args=args,
fn_kwargs=kwargs,
)
txn_hash = web3.eth.sendTransaction(transact_transaction)
return txn_hash | [
"def",
"transact_with_contract_function",
"(",
"address",
",",
"web3",
",",
"function_name",
"=",
"None",
",",
"transaction",
"=",
"None",
",",
"contract_abi",
"=",
"None",
",",
"fn_abi",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
... | Helper function for interacting with a contract function by sending a
transaction. | [
"Helper",
"function",
"for",
"interacting",
"with",
"a",
"contract",
"function",
"by",
"sending",
"a",
"transaction",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L1370-L1395 |
239,290 | ethereum/web3.py | web3/contract.py | estimate_gas_for_function | def estimate_gas_for_function(
address,
web3,
fn_identifier=None,
transaction=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
"""Estimates gas cost a function call would take.
Don't call this directly, instead use :meth:`Contract.estimateGas`
on your contract instance.
"""
estimate_transaction = prepare_transaction(
address,
web3,
fn_identifier=fn_identifier,
contract_abi=contract_abi,
fn_abi=fn_abi,
transaction=transaction,
fn_args=args,
fn_kwargs=kwargs,
)
gas_estimate = web3.eth.estimateGas(estimate_transaction)
return gas_estimate | python | def estimate_gas_for_function(
address,
web3,
fn_identifier=None,
transaction=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
estimate_transaction = prepare_transaction(
address,
web3,
fn_identifier=fn_identifier,
contract_abi=contract_abi,
fn_abi=fn_abi,
transaction=transaction,
fn_args=args,
fn_kwargs=kwargs,
)
gas_estimate = web3.eth.estimateGas(estimate_transaction)
return gas_estimate | [
"def",
"estimate_gas_for_function",
"(",
"address",
",",
"web3",
",",
"fn_identifier",
"=",
"None",
",",
"transaction",
"=",
"None",
",",
"contract_abi",
"=",
"None",
",",
"fn_abi",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"estim... | Estimates gas cost a function call would take.
Don't call this directly, instead use :meth:`Contract.estimateGas`
on your contract instance. | [
"Estimates",
"gas",
"cost",
"a",
"function",
"call",
"would",
"take",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L1398-L1424 |
239,291 | ethereum/web3.py | web3/contract.py | build_transaction_for_function | def build_transaction_for_function(
address,
web3,
function_name=None,
transaction=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
"""Builds a dictionary with the fields required to make the given transaction
Don't call this directly, instead use :meth:`Contract.buildTransaction`
on your contract instance.
"""
prepared_transaction = prepare_transaction(
address,
web3,
fn_identifier=function_name,
contract_abi=contract_abi,
fn_abi=fn_abi,
transaction=transaction,
fn_args=args,
fn_kwargs=kwargs,
)
prepared_transaction = fill_transaction_defaults(web3, prepared_transaction)
return prepared_transaction | python | def build_transaction_for_function(
address,
web3,
function_name=None,
transaction=None,
contract_abi=None,
fn_abi=None,
*args,
**kwargs):
prepared_transaction = prepare_transaction(
address,
web3,
fn_identifier=function_name,
contract_abi=contract_abi,
fn_abi=fn_abi,
transaction=transaction,
fn_args=args,
fn_kwargs=kwargs,
)
prepared_transaction = fill_transaction_defaults(web3, prepared_transaction)
return prepared_transaction | [
"def",
"build_transaction_for_function",
"(",
"address",
",",
"web3",
",",
"function_name",
"=",
"None",
",",
"transaction",
"=",
"None",
",",
"contract_abi",
"=",
"None",
",",
"fn_abi",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"... | Builds a dictionary with the fields required to make the given transaction
Don't call this directly, instead use :meth:`Contract.buildTransaction`
on your contract instance. | [
"Builds",
"a",
"dictionary",
"with",
"the",
"fields",
"required",
"to",
"make",
"the",
"given",
"transaction"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L1427-L1454 |
239,292 | ethereum/web3.py | web3/contract.py | Contract.encodeABI | def encodeABI(cls, fn_name, args=None, kwargs=None, data=None):
"""
Encodes the arguments using the Ethereum ABI for the contract function
that matches the given name and arguments..
:param data: defaults to function selector
"""
fn_abi, fn_selector, fn_arguments = get_function_info(
fn_name, contract_abi=cls.abi, args=args, kwargs=kwargs,
)
if data is None:
data = fn_selector
return encode_abi(cls.web3, fn_abi, fn_arguments, data) | python | def encodeABI(cls, fn_name, args=None, kwargs=None, data=None):
fn_abi, fn_selector, fn_arguments = get_function_info(
fn_name, contract_abi=cls.abi, args=args, kwargs=kwargs,
)
if data is None:
data = fn_selector
return encode_abi(cls.web3, fn_abi, fn_arguments, data) | [
"def",
"encodeABI",
"(",
"cls",
",",
"fn_name",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"fn_abi",
",",
"fn_selector",
",",
"fn_arguments",
"=",
"get_function_info",
"(",
"fn_name",
",",
"contract_abi",
"=... | Encodes the arguments using the Ethereum ABI for the contract function
that matches the given name and arguments..
:param data: defaults to function selector | [
"Encodes",
"the",
"arguments",
"using",
"the",
"Ethereum",
"ABI",
"for",
"the",
"contract",
"function",
"that",
"matches",
"the",
"given",
"name",
"and",
"arguments",
".."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L330-L344 |
239,293 | ethereum/web3.py | web3/contract.py | ContractFunction.call | def call(self, transaction=None, block_identifier='latest'):
"""
Execute a contract function call using the `eth_call` interface.
This method prepares a ``Caller`` object that exposes the contract
functions and public variables as callable Python functions.
Reading a public ``owner`` address variable example:
.. code-block:: python
ContractFactory = w3.eth.contract(
abi=wallet_contract_definition["abi"]
)
# Not a real contract address
contract = ContractFactory("0x2f70d3d26829e412A602E83FE8EeBF80255AEeA5")
# Read "owner" public variable
addr = contract.functions.owner().call()
:param transaction: Dictionary of transaction info for web3 interface
:return: ``Caller`` object that has contract public functions
and variables exposed as Python methods
"""
if transaction is None:
call_transaction = {}
else:
call_transaction = dict(**transaction)
if 'data' in call_transaction:
raise ValueError("Cannot set data in call transaction")
if self.address:
call_transaction.setdefault('to', self.address)
if self.web3.eth.defaultAccount is not empty:
call_transaction.setdefault('from', self.web3.eth.defaultAccount)
if 'to' not in call_transaction:
if isinstance(self, type):
raise ValueError(
"When using `Contract.[methodtype].[method].call()` from"
" a contract factory you "
"must provide a `to` address with the transaction"
)
else:
raise ValueError(
"Please ensure that this contract instance has an address."
)
block_id = parse_block_identifier(self.web3, block_identifier)
return call_contract_function(
self.web3,
self.address,
self._return_data_normalizers,
self.function_identifier,
call_transaction,
block_id,
self.contract_abi,
self.abi,
*self.args,
**self.kwargs
) | python | def call(self, transaction=None, block_identifier='latest'):
if transaction is None:
call_transaction = {}
else:
call_transaction = dict(**transaction)
if 'data' in call_transaction:
raise ValueError("Cannot set data in call transaction")
if self.address:
call_transaction.setdefault('to', self.address)
if self.web3.eth.defaultAccount is not empty:
call_transaction.setdefault('from', self.web3.eth.defaultAccount)
if 'to' not in call_transaction:
if isinstance(self, type):
raise ValueError(
"When using `Contract.[methodtype].[method].call()` from"
" a contract factory you "
"must provide a `to` address with the transaction"
)
else:
raise ValueError(
"Please ensure that this contract instance has an address."
)
block_id = parse_block_identifier(self.web3, block_identifier)
return call_contract_function(
self.web3,
self.address,
self._return_data_normalizers,
self.function_identifier,
call_transaction,
block_id,
self.contract_abi,
self.abi,
*self.args,
**self.kwargs
) | [
"def",
"call",
"(",
"self",
",",
"transaction",
"=",
"None",
",",
"block_identifier",
"=",
"'latest'",
")",
":",
"if",
"transaction",
"is",
"None",
":",
"call_transaction",
"=",
"{",
"}",
"else",
":",
"call_transaction",
"=",
"dict",
"(",
"*",
"*",
"tran... | Execute a contract function call using the `eth_call` interface.
This method prepares a ``Caller`` object that exposes the contract
functions and public variables as callable Python functions.
Reading a public ``owner`` address variable example:
.. code-block:: python
ContractFactory = w3.eth.contract(
abi=wallet_contract_definition["abi"]
)
# Not a real contract address
contract = ContractFactory("0x2f70d3d26829e412A602E83FE8EeBF80255AEeA5")
# Read "owner" public variable
addr = contract.functions.owner().call()
:param transaction: Dictionary of transaction info for web3 interface
:return: ``Caller`` object that has contract public functions
and variables exposed as Python methods | [
"Execute",
"a",
"contract",
"function",
"call",
"using",
"the",
"eth_call",
"interface",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L761-L824 |
239,294 | ethereum/web3.py | web3/contract.py | ContractEvent.getLogs | def getLogs(self,
argument_filters=None,
fromBlock=None,
toBlock=None,
blockHash=None):
"""Get events for this contract instance using eth_getLogs API.
This is a stateless method, as opposed to createFilter.
It can be safely called against nodes which do not provide
eth_newFilter API, like Infura nodes.
If there are many events,
like ``Transfer`` events for a popular token,
the Ethereum node might be overloaded and timeout
on the underlying JSON-RPC call.
Example - how to get all ERC-20 token transactions
for the latest 10 blocks:
.. code-block:: python
from = max(mycontract.web3.eth.blockNumber - 10, 1)
to = mycontract.web3.eth.blockNumber
events = mycontract.events.Transfer.getLogs(fromBlock=from, toBlock=to)
for e in events:
print(e["args"]["from"],
e["args"]["to"],
e["args"]["value"])
The returned processed log values will look like:
.. code-block:: python
(
AttributeDict({
'args': AttributeDict({}),
'event': 'LogNoArguments',
'logIndex': 0,
'transactionIndex': 0,
'transactionHash': HexBytes('...'),
'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b',
'blockHash': HexBytes('...'),
'blockNumber': 3
}),
AttributeDict(...),
...
)
See also: :func:`web3.middleware.filter.local_filter_middleware`.
:param argument_filters:
:param fromBlock: block number or "latest", defaults to "latest"
:param toBlock: block number or "latest". Defaults to "latest"
:param blockHash: block hash. blockHash cannot be set at the
same time as fromBlock or toBlock
:yield: Tuple of :class:`AttributeDict` instances
"""
if not self.address:
raise TypeError("This method can be only called on "
"an instated contract with an address")
abi = self._get_event_abi()
if argument_filters is None:
argument_filters = dict()
_filters = dict(**argument_filters)
blkhash_set = blockHash is not None
blknum_set = fromBlock is not None or toBlock is not None
if blkhash_set and blknum_set:
raise ValidationError(
'blockHash cannot be set at the same'
' time as fromBlock or toBlock')
# Construct JSON-RPC raw filter presentation based on human readable Python descriptions
# Namely, convert event names to their keccak signatures
data_filter_set, event_filter_params = construct_event_filter_params(
abi,
contract_address=self.address,
argument_filters=_filters,
fromBlock=fromBlock,
toBlock=toBlock,
address=self.address,
)
if blockHash is not None:
event_filter_params['blockHash'] = blockHash
# Call JSON-RPC API
logs = self.web3.eth.getLogs(event_filter_params)
# Convert raw binary data to Python proxy objects as described by ABI
return tuple(get_event_data(abi, entry) for entry in logs) | python | def getLogs(self,
argument_filters=None,
fromBlock=None,
toBlock=None,
blockHash=None):
if not self.address:
raise TypeError("This method can be only called on "
"an instated contract with an address")
abi = self._get_event_abi()
if argument_filters is None:
argument_filters = dict()
_filters = dict(**argument_filters)
blkhash_set = blockHash is not None
blknum_set = fromBlock is not None or toBlock is not None
if blkhash_set and blknum_set:
raise ValidationError(
'blockHash cannot be set at the same'
' time as fromBlock or toBlock')
# Construct JSON-RPC raw filter presentation based on human readable Python descriptions
# Namely, convert event names to their keccak signatures
data_filter_set, event_filter_params = construct_event_filter_params(
abi,
contract_address=self.address,
argument_filters=_filters,
fromBlock=fromBlock,
toBlock=toBlock,
address=self.address,
)
if blockHash is not None:
event_filter_params['blockHash'] = blockHash
# Call JSON-RPC API
logs = self.web3.eth.getLogs(event_filter_params)
# Convert raw binary data to Python proxy objects as described by ABI
return tuple(get_event_data(abi, entry) for entry in logs) | [
"def",
"getLogs",
"(",
"self",
",",
"argument_filters",
"=",
"None",
",",
"fromBlock",
"=",
"None",
",",
"toBlock",
"=",
"None",
",",
"blockHash",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"address",
":",
"raise",
"TypeError",
"(",
"\"This method ... | Get events for this contract instance using eth_getLogs API.
This is a stateless method, as opposed to createFilter.
It can be safely called against nodes which do not provide
eth_newFilter API, like Infura nodes.
If there are many events,
like ``Transfer`` events for a popular token,
the Ethereum node might be overloaded and timeout
on the underlying JSON-RPC call.
Example - how to get all ERC-20 token transactions
for the latest 10 blocks:
.. code-block:: python
from = max(mycontract.web3.eth.blockNumber - 10, 1)
to = mycontract.web3.eth.blockNumber
events = mycontract.events.Transfer.getLogs(fromBlock=from, toBlock=to)
for e in events:
print(e["args"]["from"],
e["args"]["to"],
e["args"]["value"])
The returned processed log values will look like:
.. code-block:: python
(
AttributeDict({
'args': AttributeDict({}),
'event': 'LogNoArguments',
'logIndex': 0,
'transactionIndex': 0,
'transactionHash': HexBytes('...'),
'address': '0xF2E246BB76DF876Cef8b38ae84130F4F55De395b',
'blockHash': HexBytes('...'),
'blockNumber': 3
}),
AttributeDict(...),
...
)
See also: :func:`web3.middleware.filter.local_filter_middleware`.
:param argument_filters:
:param fromBlock: block number or "latest", defaults to "latest"
:param toBlock: block number or "latest". Defaults to "latest"
:param blockHash: block hash. blockHash cannot be set at the
same time as fromBlock or toBlock
:yield: Tuple of :class:`AttributeDict` instances | [
"Get",
"events",
"for",
"this",
"contract",
"instance",
"using",
"eth_getLogs",
"API",
"."
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/contract.py#L1065-L1161 |
239,295 | ethereum/web3.py | ens/utils.py | dict_copy | def dict_copy(func):
"copy dict keyword args, to avoid modifying caller's copy"
@functools.wraps(func)
def wrapper(*args, **kwargs):
copied_kwargs = copy.deepcopy(kwargs)
return func(*args, **copied_kwargs)
return wrapper | python | def dict_copy(func):
"copy dict keyword args, to avoid modifying caller's copy"
@functools.wraps(func)
def wrapper(*args, **kwargs):
copied_kwargs = copy.deepcopy(kwargs)
return func(*args, **copied_kwargs)
return wrapper | [
"def",
"dict_copy",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"copied_kwargs",
"=",
"copy",
".",
"deepcopy",
"(",
"kwargs",
")",
"return",
"func",
... | copy dict keyword args, to avoid modifying caller's copy | [
"copy",
"dict",
"keyword",
"args",
"to",
"avoid",
"modifying",
"caller",
"s",
"copy"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/ens/utils.py#L33-L39 |
239,296 | ethereum/web3.py | ens/utils.py | dot_eth_label | def dot_eth_label(name):
"""
Convert from a name, like 'ethfinex.eth', to a label, like 'ethfinex'
If name is already a label, this should be a noop, except for converting to a string
and validating the name syntax.
"""
label = name_to_label(name, registrar='eth')
if len(label) < MIN_ETH_LABEL_LENGTH:
raise InvalidLabel('name %r is too short' % label)
else:
return label | python | def dot_eth_label(name):
label = name_to_label(name, registrar='eth')
if len(label) < MIN_ETH_LABEL_LENGTH:
raise InvalidLabel('name %r is too short' % label)
else:
return label | [
"def",
"dot_eth_label",
"(",
"name",
")",
":",
"label",
"=",
"name_to_label",
"(",
"name",
",",
"registrar",
"=",
"'eth'",
")",
"if",
"len",
"(",
"label",
")",
"<",
"MIN_ETH_LABEL_LENGTH",
":",
"raise",
"InvalidLabel",
"(",
"'name %r is too short'",
"%",
"la... | Convert from a name, like 'ethfinex.eth', to a label, like 'ethfinex'
If name is already a label, this should be a noop, except for converting to a string
and validating the name syntax. | [
"Convert",
"from",
"a",
"name",
"like",
"ethfinex",
".",
"eth",
"to",
"a",
"label",
"like",
"ethfinex",
"If",
"name",
"is",
"already",
"a",
"label",
"this",
"should",
"be",
"a",
"noop",
"except",
"for",
"converting",
"to",
"a",
"string",
"and",
"validati... | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/ens/utils.py#L125-L135 |
239,297 | ethereum/web3.py | web3/_utils/formatters.py | map_collection | def map_collection(func, collection):
"""
Apply func to each element of a collection, or value of a dictionary.
If the value is not a collection, return it unmodified
"""
datatype = type(collection)
if isinstance(collection, Mapping):
return datatype((key, func(val)) for key, val in collection.items())
if is_string(collection):
return collection
elif isinstance(collection, Iterable):
return datatype(map(func, collection))
else:
return collection | python | def map_collection(func, collection):
datatype = type(collection)
if isinstance(collection, Mapping):
return datatype((key, func(val)) for key, val in collection.items())
if is_string(collection):
return collection
elif isinstance(collection, Iterable):
return datatype(map(func, collection))
else:
return collection | [
"def",
"map_collection",
"(",
"func",
",",
"collection",
")",
":",
"datatype",
"=",
"type",
"(",
"collection",
")",
"if",
"isinstance",
"(",
"collection",
",",
"Mapping",
")",
":",
"return",
"datatype",
"(",
"(",
"key",
",",
"func",
"(",
"val",
")",
")... | Apply func to each element of a collection, or value of a dictionary.
If the value is not a collection, return it unmodified | [
"Apply",
"func",
"to",
"each",
"element",
"of",
"a",
"collection",
"or",
"value",
"of",
"a",
"dictionary",
".",
"If",
"the",
"value",
"is",
"not",
"a",
"collection",
"return",
"it",
"unmodified"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/formatters.py#L91-L104 |
239,298 | ethereum/web3.py | web3/_utils/math.py | percentile | def percentile(values=None, percentile=None):
"""Calculates a simplified weighted average percentile
"""
if values in [None, tuple(), []] or len(values) < 1:
raise InsufficientData(
"Expected a sequence of at least 1 integers, got {0!r}".format(values))
if percentile is None:
raise ValueError("Expected a percentile choice, got {0}".format(percentile))
sorted_values = sorted(values)
rank = len(values) * percentile / 100
if rank > 0:
index = rank - 1
if index < 0:
return sorted_values[0]
else:
index = rank
if index % 1 == 0:
return sorted_values[int(index)]
else:
fractional = index % 1
integer = int(index - fractional)
lower = sorted_values[integer]
higher = sorted_values[integer + 1]
return lower + fractional * (higher - lower) | python | def percentile(values=None, percentile=None):
if values in [None, tuple(), []] or len(values) < 1:
raise InsufficientData(
"Expected a sequence of at least 1 integers, got {0!r}".format(values))
if percentile is None:
raise ValueError("Expected a percentile choice, got {0}".format(percentile))
sorted_values = sorted(values)
rank = len(values) * percentile / 100
if rank > 0:
index = rank - 1
if index < 0:
return sorted_values[0]
else:
index = rank
if index % 1 == 0:
return sorted_values[int(index)]
else:
fractional = index % 1
integer = int(index - fractional)
lower = sorted_values[integer]
higher = sorted_values[integer + 1]
return lower + fractional * (higher - lower) | [
"def",
"percentile",
"(",
"values",
"=",
"None",
",",
"percentile",
"=",
"None",
")",
":",
"if",
"values",
"in",
"[",
"None",
",",
"tuple",
"(",
")",
",",
"[",
"]",
"]",
"or",
"len",
"(",
"values",
")",
"<",
"1",
":",
"raise",
"InsufficientData",
... | Calculates a simplified weighted average percentile | [
"Calculates",
"a",
"simplified",
"weighted",
"average",
"percentile"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/_utils/math.py#L6-L32 |
239,299 | ethereum/web3.py | web3/datastructures.py | ReadableAttributeDict._repr_pretty_ | def _repr_pretty_(self, builder, cycle):
"""
Custom pretty output for the IPython console
"""
builder.text(self.__class__.__name__ + "(")
if cycle:
builder.text("<cycle>")
else:
builder.pretty(self.__dict__)
builder.text(")") | python | def _repr_pretty_(self, builder, cycle):
builder.text(self.__class__.__name__ + "(")
if cycle:
builder.text("<cycle>")
else:
builder.pretty(self.__dict__)
builder.text(")") | [
"def",
"_repr_pretty_",
"(",
"self",
",",
"builder",
",",
"cycle",
")",
":",
"builder",
".",
"text",
"(",
"self",
".",
"__class__",
".",
"__name__",
"+",
"\"(\"",
")",
"if",
"cycle",
":",
"builder",
".",
"text",
"(",
"\"<cycle>\"",
")",
"else",
":",
... | Custom pretty output for the IPython console | [
"Custom",
"pretty",
"output",
"for",
"the",
"IPython",
"console"
] | 71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab | https://github.com/ethereum/web3.py/blob/71b8bf03dc6d332dd97d8902a38ffab6f8b5a5ab/web3/datastructures.py#L45-L54 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.