signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
@njit<EOL>def func_two_prime(x): | return <NUM_LIT:4>*np.cos(<NUM_LIT:4>*(x - <NUM_LIT:1>/<NUM_LIT:4>)) + <NUM_LIT:20>*x**<NUM_LIT> + <NUM_LIT:1><EOL> | Derivative for func_two. | f5112:m4 |
@njit<EOL>def func_two_prime2(x): | return <NUM_LIT>*x**<NUM_LIT> - <NUM_LIT:16>*np.sin(<NUM_LIT:4>*(x - <NUM_LIT:1>/<NUM_LIT:4>))<EOL> | Second order derivative for func_two | f5112:m5 |
@njit<EOL>def f(x): | return -(x + <NUM_LIT>)**<NUM_LIT:2> + <NUM_LIT:1.0><EOL> | A function for testing on. | f5113:m0 |
@njit<EOL>def g(x, y): | return -x**<NUM_LIT:2> + y<EOL> | A multivariate function for testing on. | f5113:m2 |
@njit<EOL>def brent_max(func, a, b, args=(), xtol=<NUM_LIT>, maxiter=<NUM_LIT>): | if not np.isfinite(a):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not np.isfinite(b):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not a < b:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>maxfun = maxiter<EOL>status_flag = <NUM_LIT:0><EOL>sqrt_eps = np.sqrt(<NUM_LIT>)<EOL>golden_mean =... | Uses a jitted version of the maximization routine from SciPy's fminbound.
The algorithm is identical except that it's been switched to maximization
rather than minimization, and the tests for convergence have been stripped
out to allow for jit compilation.
Note that the input function `func` must be jitted or the call... | f5115:m0 |
@njit<EOL>def nelder_mead(fun, x0, bounds=np.array([[], []]).T, args=(), tol_f=<NUM_LIT>,<EOL>tol_x=<NUM_LIT>, max_iter=<NUM_LIT:1000>): | vertices = _initialize_simplex(x0, bounds)<EOL>results = _nelder_mead_algorithm(fun, vertices, bounds, args=args,<EOL>tol_f=tol_f, tol_x=tol_x,<EOL>max_iter=max_iter)<EOL>return results<EOL> | .. highlight:: none
Maximize a scalar-valued function with one or more variables using the
Nelder-Mead method.
This function is JIT-compiled in `nopython` mode using Numba.
Parameters
----------
fun : callable
The objective function to be maximized: `fun(x, *args) -> float`
where x is an 1-D array with shape... | f5117:m0 |
@njit<EOL>def _nelder_mead_algorithm(fun, vertices, bounds=np.array([[], []]).T,<EOL>args=(), ρ=<NUM_LIT:1.>, χ=<NUM_LIT>, γ=<NUM_LIT:0.5>, σ=<NUM_LIT:0.5>, tol_f=<NUM_LIT>,<EOL>tol_x=<NUM_LIT>, max_iter=<NUM_LIT:1000>): | n = vertices.shape[<NUM_LIT:1>]<EOL>_check_params(ρ, χ, γ, σ, bounds, n)<EOL>nit = <NUM_LIT:0><EOL>ργ = ρ * γ<EOL>ρχ = ρ * χ<EOL>σ_n = σ ** n<EOL>f_val = np.empty(n+<NUM_LIT:1>, dtype=np.float64)<EOL>for i in range(n+<NUM_LIT:1>):<EOL><INDENT>f_val[i] = _neg_bounded_fun(fun, bounds, vertices[i], args=args)<EOL><DEDENT>... | .. highlight:: none
Implements the Nelder-Mead algorithm described in Lagarias et al. (1998)
modified to maximize instead of minimizing. JIT-compiled in `nopython`
mode using Numba.
Parameters
----------
fun : callable
The objective function to be maximized.
`fun(x, *args) -> float`
where x is an 1-D ... | f5117:m1 |
@njit<EOL>def _initialize_simplex(x0, bounds): | n = x0.size<EOL>vertices = np.empty((n + <NUM_LIT:1>, n), dtype=np.float64)<EOL>vertices[:] = x0<EOL>nonzdelt = <NUM_LIT><EOL>zdelt = <NUM_LIT><EOL>for i in range(n):<EOL><INDENT>if vertices[i + <NUM_LIT:1>, i] != <NUM_LIT:0.>:<EOL><INDENT>vertices[i + <NUM_LIT:1>, i] *= (<NUM_LIT:1> + nonzdelt)<EOL><DEDENT>else:<EOL><... | Generates an initial simplex for the Nelder-Mead method. JIT-compiled in
`nopython` mode using Numba.
Parameters
----------
x0 : ndarray(float, ndim=1)
Initial guess. Array of real elements of size (n,), where ‘n’ is the
number of independent variables.
bounds: ndarray(float, ndim=2)
Sequence of (min, max... | f5117:m2 |
@njit<EOL>def _check_params(ρ, χ, γ, σ, bounds, n): | if ρ < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if χ < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if χ < ρ:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if γ < <NUM_LIT:0> or γ > <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if σ < <NUM_LIT... | Checks whether the parameters for the Nelder-Mead algorithm are valid.
JIT-compiled in `nopython` mode using Numba.
Parameters
----------
ρ : scalar(float)
Reflection parameter. Must be strictly greater than 0.
χ : scalar(float)
Expansion parameter. Must be strictly greater than max(1, ρ).
γ : scalar(float)
... | f5117:m3 |
@njit<EOL>def _check_bounds(x, bounds): | if bounds.shape == (<NUM_LIT:0>, <NUM_LIT:2>):<EOL><INDENT>return True<EOL><DEDENT>else:<EOL><INDENT>return ((np.atleast_2d(bounds)[:, <NUM_LIT:0>] <= x).all() and<EOL>(x <= np.atleast_2d(bounds)[:, <NUM_LIT:1>]).all())<EOL><DEDENT> | Checks whether `x` is within `bounds`. JIT-compiled in `nopython` mode
using Numba.
Parameters
----------
x : ndarray(float, ndim=1)
1-D array with shape (n,) of independent variables.
bounds: ndarray(float, ndim=2)
Sequence of (min, max) pairs for each element in x.
Returns
----------
bool
`True` if `x`... | f5117:m4 |
@njit<EOL>def _neg_bounded_fun(fun, bounds, x, args=()): | if _check_bounds(x, bounds):<EOL><INDENT>return -fun(x, *args)<EOL><DEDENT>else:<EOL><INDENT>return np.inf<EOL><DEDENT> | Wrapper for bounding and taking the negative of `fun` for the
Nelder-Mead algorithm. JIT-compiled in `nopython` mode using Numba.
Parameters
----------
fun : callable
The objective function to be minimized.
`fun(x, *args) -> float`
where x is an 1-D array with shape (n,) and args is a tuple of the
... | f5117:m5 |
@njit<EOL>def _results(r): | x, funcalls, iterations, flag = r<EOL>return results(x, funcalls, iterations, flag == <NUM_LIT:0>)<EOL> | r"""Select from a tuple of(root, funccalls, iterations, flag) | f5118:m0 |
@njit<EOL>def newton(func, x0, fprime, args=(), tol=<NUM_LIT>, maxiter=<NUM_LIT:50>,<EOL>disp=True): | if tol <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if maxiter < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>p0 = <NUM_LIT:1.0> * x0<EOL>funcalls = <NUM_LIT:0><EOL>status = _ECONVERR<EOL>for itr in range(maxiter):<EOL><INDENT>fval = func(p0, *args)<EOL>funcalls += <NUM_LI... | Find a zero from the Newton-Raphson method using the jitted version of
Scipy's newton for scalars. Note that this does not provide an alternative
method such as secant. Thus, it is important that `fprime` can be provided.
Note that `func` and `fprime` must be jitted via Numba.
They are recommended to be `njit` for per... | f5118:m1 |
@njit<EOL>def newton_halley(func, x0, fprime, fprime2, args=(), tol=<NUM_LIT>,<EOL>maxiter=<NUM_LIT:50>, disp=True): | if tol <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if maxiter < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>p0 = <NUM_LIT:1.0> * x0<EOL>funcalls = <NUM_LIT:0><EOL>status = _ECONVERR<EOL>for itr in range(maxiter):<EOL><INDENT>fval = func(p0, *args)<EOL>funcalls += <NUM_LI... | Find a zero from Halley's method using the jitted version of
Scipy's.
`func`, `fprime`, `fprime2` must be jitted via Numba.
Parameters
----------
func : callable and jitted
The function whose zero is wanted. It must be a function of a
single variable of the form f(x,a,b,c...), where a,b,c... are extra
arg... | f5118:m2 |
@njit<EOL>def newton_secant(func, x0, args=(), tol=<NUM_LIT>, maxiter=<NUM_LIT:50>,<EOL>disp=True): | if tol <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if maxiter < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>p0 = <NUM_LIT:1.0> * x0<EOL>funcalls = <NUM_LIT:0><EOL>status = _ECONVERR<EOL>if x0 >= <NUM_LIT:0>:<EOL><INDENT>p1 = x0 * (<NUM_LIT:1> + <NUM_LIT>) + <NUM_LIT><EOL... | Find a zero from the secant method using the jitted version of
Scipy's secant method.
Note that `func` must be jitted via Numba.
Parameters
----------
func : callable and jitted
The function whose zero is wanted. It must be a function of a
single variable of the form f(x,a,b,c...), where a,b,c... are extra
... | f5118:m3 |
@njit<EOL>def _bisect_interval(a, b, fa, fb): | if fa*fb > <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>root = <NUM_LIT:0.0><EOL>status = _ECONVERR<EOL>if fa == <NUM_LIT:0>:<EOL><INDENT>root = a<EOL>status = _ECONVERGED<EOL><DEDENT>if fb == <NUM_LIT:0>:<EOL><INDENT>root = b<EOL>status = _ECONVERGED<EOL><DEDENT>return root, status<EOL> | Conditional checks for intervals in methods involving bisection | f5118:m4 |
@njit<EOL>def bisect(f, a, b, args=(), xtol=_xtol,<EOL>rtol=_rtol, maxiter=_iter, disp=True): | if xtol <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if maxiter < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>xa = a * <NUM_LIT:1.0><EOL>xb = b * <NUM_LIT:1.0><EOL>fa = f(xa, *args)<EOL>fb = f(xb, *args)<EOL>funcalls = <NUM_LIT:2><EOL>root, status = _bisect_interval(xa, x... | Find root of a function within an interval adapted from Scipy's bisect.
Basic bisection routine to find a zero of the function `f` between the
arguments `a` and `b`. `f(a)` and `f(b)` cannot have the same signs.
`f` must be jitted via numba.
Parameters
----------
f : jitted and callable
Python function returning... | f5118:m5 |
@njit<EOL>def brentq(f, a, b, args=(), xtol=_xtol,<EOL>rtol=_rtol, maxiter=_iter, disp=True): | if xtol <= <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if maxiter < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>xpre = a * <NUM_LIT:1.0><EOL>xcur = b * <NUM_LIT:1.0><EOL>fpre = f(xpre, *args)<EOL>fcur = f(xcur, *args)<EOL>funcalls = <NUM_LIT:2><EOL>root, status = _bisect_in... | Find a root of a function in a bracketing interval using Brent's method
adapted from Scipy's brentq.
Uses the classic Brent's method to find a zero of the function `f` on
the sign changing interval [a , b].
`f` must be jitted via numba.
Parameters
----------
f : jitted and callable
Python function returning a nu... | f5118:m6 |
def set_params(self): | <EOL>ma_poly = np.asarray(self._theta)<EOL>self.ma_poly = np.insert(ma_poly, <NUM_LIT:0>, <NUM_LIT:1>) <EOL>if np.isscalar(self._phi):<EOL><INDENT>ar_poly = np.array(-self._phi)<EOL><DEDENT>else:<EOL><INDENT>ar_poly = -np.asarray(self._phi)<EOL><DEDENT>self.ar_poly = np.insert(ar_poly, <NUM_LIT:0>, <NUM_LIT:1>) <EOL>... | r"""
Internally, scipy.signal works with systems of the form
.. math::
ar_{poly}(L) X_t = ma_{poly}(L) \epsilon_t
where L is the lag operator. To match this, we set
.. math::
ar_{poly} = (1, -\phi_1, -\phi_2,..., -\phi_p)
ma_{poly} = (1, \theta_1... | f5119:c0:m8 |
def impulse_response(self, impulse_length=<NUM_LIT:30>): | from scipy.signal import dimpulse<EOL>sys = self.ma_poly, self.ar_poly, <NUM_LIT:1><EOL>times, psi = dimpulse(sys, n=impulse_length)<EOL>psi = psi[<NUM_LIT:0>].flatten() <EOL>return psi<EOL> | Get the impulse response corresponding to our model.
Returns
-------
psi : array_like(float)
psi[j] is the response at lag j of the impulse response.
We take psi[0] as unity. | f5119:c0:m9 |
def spectral_density(self, two_pi=True, res=<NUM_LIT>): | from scipy.signal import freqz<EOL>w, h = freqz(self.ma_poly, self.ar_poly, worN=res, whole=two_pi)<EOL>spect = h * conj(h) * self.sigma**<NUM_LIT:2><EOL>return w, spect<EOL> | r"""
Compute the spectral density function. The spectral density is
the discrete time Fourier transform of the autocovariance
function. In particular,
.. math::
f(w) = \sum_k \gamma(k) \exp(-ikw)
where gamma is the autocovariance function and the sum is over
... | f5119:c0:m10 |
def autocovariance(self, num_autocov=<NUM_LIT:16>): | spect = self.spectral_density()[<NUM_LIT:1>]<EOL>acov = np.fft.ifft(spect).real<EOL>return acov[:num_autocov]<EOL> | Compute the autocovariance function from the ARMA parameters
over the integers range(num_autocov) using the spectral density
and the inverse Fourier transform.
Parameters
----------
num_autocov : scalar(int), optional(default=16)
The number of autocovariances to calculate | f5119:c0:m11 |
def simulation(self, ts_length=<NUM_LIT>, random_state=None): | from scipy.signal import dlsim<EOL>random_state = check_random_state(random_state)<EOL>sys = self.ma_poly, self.ar_poly, <NUM_LIT:1><EOL>u = random_state.randn(ts_length, <NUM_LIT:1>) * self.sigma<EOL>vals = dlsim(sys, u)[<NUM_LIT:1>]<EOL>return vals.flatten()<EOL> | Compute a simulated sample path assuming Gaussian shocks.
Parameters
----------
ts_length : scalar(int), optional(default=90)
Number of periods to simulate for
random_state : int or np.random.RandomState, optional
Random seed (integer) or np.random.RandomState instance to set
the initial state of the rand... | f5119:c0:m12 |
def _integrate_fixed_trajectory(self, h, T, step, relax): | <EOL>solution = np.hstack((self.t, self.y))<EOL>while self.successful():<EOL><INDENT>self.integrate(self.t + h, step, relax)<EOL>current_step = np.hstack((self.t, self.y))<EOL>solution = np.vstack((solution, current_step))<EOL>if (h > <NUM_LIT:0>) and (self.t >= T):<EOL><INDENT>break<EOL><DEDENT>elif (h < <NUM_LIT:0>) ... | Generates a solution trajectory of fixed length. | f5120:c0:m1 |
def _integrate_variable_trajectory(self, h, g, tol, step, relax): | <EOL>solution = np.hstack((self.t, self.y))<EOL>while self.successful():<EOL><INDENT>self.integrate(self.t + h, step, relax)<EOL>current_step = np.hstack((self.t, self.y))<EOL>solution = np.vstack((solution, current_step))<EOL>if g(self.t, self.y, *self.f_params) < tol:<EOL><INDENT>break<EOL><DEDENT>else:<EOL><INDENT>c... | Generates a solution trajectory of variable length. | f5120:c0:m2 |
def _initialize_integrator(self, t0, y0, integrator, **kwargs): | <EOL>self.set_initial_value(y0, t0)<EOL>self.set_integrator(integrator, **kwargs)<EOL> | Initializes the integrator prior to integration. | f5120:c0:m3 |
def compute_residual(self, traj, ti, k=<NUM_LIT:3>, ext=<NUM_LIT:2>): | <EOL>soln = self.interpolate(traj, ti, k, <NUM_LIT:0>, ext)<EOL>deriv = self.interpolate(traj, ti, k, <NUM_LIT:1>, ext)<EOL>T = ti.size<EOL>rhs_ode = np.vstack(self.f(ti[i], soln[i, <NUM_LIT:1>:], *self.f_params)<EOL>for i in range(T))<EOL>rhs_ode = np.hstack((ti[:, np.newaxis], rhs_ode))<EOL>residual = deriv - rhs_ode... | r"""
The residual is the difference between the derivative of the B-spline
approximation of the solution trajectory and the right-hand side of the
original ODE evaluated along the approximated solution trajectory.
Parameters
----------
traj : array_like (float)
... | f5120:c0:m4 |
def solve(self, t0, y0, h=<NUM_LIT:1.0>, T=None, g=None, tol=None,<EOL>integrator='<STR_LIT>', step=False, relax=False, **kwargs): | self._initialize_integrator(t0, y0, integrator, **kwargs)<EOL>if (g is not None) and (tol is not None):<EOL><INDENT>soln = self._integrate_variable_trajectory(h, g, tol, step, relax)<EOL><DEDENT>elif T is not None:<EOL><INDENT>soln = self._integrate_fixed_trajectory(h, T, step, relax)<EOL><DEDENT>else:<EOL><INDENT>mesg... | r"""
Solve the IVP by integrating the ODE given some initial condition.
Parameters
----------
t0 : float
Initial condition for the independent variable.
y0 : array_like (float, shape=(n,))
Initial condition for the dependent variables.
h : float, ... | f5120:c0:m5 |
def interpolate(self, traj, ti, k=<NUM_LIT:3>, der=<NUM_LIT:0>, ext=<NUM_LIT:2>): | <EOL>u = traj[:, <NUM_LIT:0>]<EOL>n = traj.shape[<NUM_LIT:1>]<EOL>x = [traj[:, i] for i in range(<NUM_LIT:1>, n)]<EOL>tck, t = interpolate.splprep(x, u=u, k=k, s=<NUM_LIT:0>)<EOL>out = interpolate.splev(ti, tck, der, ext)<EOL>interp_traj = np.hstack((ti[:, np.newaxis], np.array(out).T))<EOL>return interp_traj<EOL> | r"""
Parametric B-spline interpolation in N-dimensions.
Parameters
----------
traj : array_like (float)
Solution trajectory providing the data points for constructing the
B-spline representation.
ti : array_like (float)
Array of values for the... | f5120:c0:m6 |
def whitener_lss(self): | K = self.K_infinity<EOL>n, k, m, l = self.ss.n, self.ss.k, self.ss.m, self.ss.l<EOL>A, C, G, H = self.ss.A, self.ss.C, self.ss.G, self.ss.H<EOL>Atil = np.vstack([np.hstack([A, np.zeros((n, n)), np.zeros((n, l))]),<EOL>np.hstack([dot(K, G), A-dot(K, G), dot(K, H)]),<EOL>np.zeros((l, <NUM_LIT:2>*n + l))])<EOL>Ctil = np.v... | r"""
This function takes the linear state space system
that is an input to the Kalman class and it converts
that system to the time-invariant whitener represenation
given by
.. math::
\tilde{x}_{t+1}^* = \tilde{A} \tilde{x} + \tilde{C} v
a = \tilde{G} \t... | f5121:c0:m6 |
def prior_to_filtered(self, y): | <EOL>G, H = self.ss.G, self.ss.H<EOL>R = np.dot(H, H.T)<EOL>y = np.atleast_2d(y)<EOL>y.shape = self.ss.k, <NUM_LIT:1><EOL>E = dot(self.Sigma, G.T)<EOL>F = dot(dot(G, self.Sigma), G.T) + R<EOL>M = dot(E, inv(F))<EOL>self.x_hat = self.x_hat + dot(M, (y - dot(G, self.x_hat)))<EOL>self.Sigma = self.Sigma - dot(M, dot(G, s... | r"""
Updates the moments (x_hat, Sigma) of the time t prior to the
time t filtering distribution, using current measurement :math:`y_t`.
The updates are according to
.. math::
\hat{x}^F = \hat{x} + \Sigma G' (G \Sigma G' + R)^{-1}
(y - G \hat{x})
... | f5121:c0:m7 |
def filtered_to_forecast(self): | <EOL>A, C = self.ss.A, self.ss.C<EOL>Q = np.dot(C, C.T)<EOL>self.x_hat = dot(A, self.x_hat)<EOL>self.Sigma = dot(A, dot(self.Sigma, A.T)) + Q<EOL> | Updates the moments of the time t filtering distribution to the
moments of the predictive distribution, which becomes the time
t+1 prior | f5121:c0:m8 |
def update(self, y): | self.prior_to_filtered(y)<EOL>self.filtered_to_forecast()<EOL> | Updates x_hat and Sigma given k x 1 ndarray y. The full
update, from one period to the next
Parameters
----------
y : np.ndarray
A k x 1 ndarray y representing the current measurement | f5121:c0:m9 |
def stationary_values(self, method='<STR_LIT>'): | <EOL>A, C, G, H = self.ss.A, self.ss.C, self.ss.G, self.ss.H<EOL>Q, R = np.dot(C, C.T), np.dot(H, H.T)<EOL>Sigma_infinity = solve_discrete_riccati(A.T, G.T, Q, R, method=method)<EOL>temp1 = dot(dot(A, Sigma_infinity), G.T)<EOL>temp2 = inv(dot(G, dot(Sigma_infinity, G.T)) + R)<EOL>K_infinity = dot(temp1, temp2)<EOL>self... | Computes the limit of :math:`\Sigma_t` as t goes to infinity by
solving the associated Riccati equation. The outputs are stored in the
attributes `K_infinity` and `Sigma_infinity`. Computation is via the
doubling algorithm (default) or a QZ decomposition method (see the
documentation in `matrix_eqn.solve_discrete_ricca... | f5121:c0:m10 |
def stationary_coefficients(self, j, coeff_type='<STR_LIT>'): | <EOL>A, G = self.ss.A, self.ss.G<EOL>K_infinity = self.K_infinity<EOL>coeffs = []<EOL>i = <NUM_LIT:1><EOL>if coeff_type == '<STR_LIT>':<EOL><INDENT>coeffs.append(np.identity(self.ss.k))<EOL>P_mat = A<EOL>P = np.identity(self.ss.n) <EOL><DEDENT>elif coeff_type == '<STR_LIT>':<EOL><INDENT>coeffs.append(dot(G, K_infinity... | Wold representation moving average or VAR coefficients for the
steady state Kalman filter.
Parameters
----------
j : int
The lag length
coeff_type : string, either 'ma' or 'var' (default='ma')
The type of coefficent sequence to compute. Either 'ma' for
moving average or 'var' for VAR. | f5121:c0:m11 |
def hamilton_filter(data, h, *args): | <EOL>y = np.asarray(data, float)<EOL>T = len(y)<EOL>if len(args) == <NUM_LIT:1>: <EOL><INDENT>p = args[<NUM_LIT:0>]<EOL>X = np.ones((T-p-h+<NUM_LIT:1>, p+<NUM_LIT:1>))<EOL>for j in range(<NUM_LIT:1>, p+<NUM_LIT:1>):<EOL><INDENT>X[:, j] = y[p-j:T-h-j+<NUM_LIT:1>:<NUM_LIT:1>]<EOL><DEDENT>b = np.linalg.solve(X.transpose()... | r"""
This function applies "Hamilton filter" to the data
http://econweb.ucsd.edu/~jhamilto/hp.pdf
Parameters
----------
data : arrray or dataframe
h : integer
Time horizon that we are likely to predict incorrectly.
Original paper recommends 2 for annual data, 8 for quarterly da... | f5122:m0 |
@generated_jit(nopython=True, cache=True)<EOL>def _numba_linalg_solve(a, b): | numba_xgesv = _LAPACK().numba_xgesv(a.dtype)<EOL>kind = ord(_blas_kinds[a.dtype])<EOL>def _numba_linalg_solve_impl(a, b): <EOL><INDENT>n = a.shape[-<NUM_LIT:1>]<EOL>if b.ndim == <NUM_LIT:1>:<EOL><INDENT>nrhs = <NUM_LIT:1><EOL><DEDENT>else: <EOL><INDENT>nrhs = b.shape[-<NUM_LIT:1>]<EOL><DEDENT>F_INT_nptype = np.int32<... | Solve the linear equation ax = b directly calling a Numba internal
function. The data in `a` and `b` are interpreted in Fortran order,
and dtype of `a` and `b` must be the same, one of {float32, float64,
complex64, complex128}. `a` and `b` are modified in place, and the
solution is stored in `b`. *No error check is mad... | f5123:m0 |
@jit(types.intp(types.intp, types.intp), nopython=True, cache=True)<EOL>def comb_jit(N, k): | <EOL>INTP_MAX = np.iinfo(np.intp).max<EOL>if N < <NUM_LIT:0> or k < <NUM_LIT:0> or k > N:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>if k == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>if k == <NUM_LIT:1>:<EOL><INDENT>return N<EOL><DEDENT>if N == INTP_MAX:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>M = N + ... | Numba jitted function that computes N choose k. Return `0` if the
outcome exceeds the maximum value of `np.intp` or if N < 0, k < 0,
or k > N.
Parameters
----------
N : scalar(int)
k : scalar(int)
Returns
-------
val : scalar(int) | f5123:m1 |
@jit(nopython=True, cache=True)<EOL>def next_k_array(a): | <EOL>k = len(a)<EOL>if k == <NUM_LIT:1> or a[<NUM_LIT:0>] + <NUM_LIT:1> < a[<NUM_LIT:1>]:<EOL><INDENT>a[<NUM_LIT:0>] += <NUM_LIT:1><EOL>return a<EOL><DEDENT>a[<NUM_LIT:0>] = <NUM_LIT:0><EOL>i = <NUM_LIT:1><EOL>x = a[i] + <NUM_LIT:1><EOL>while i < k-<NUM_LIT:1> and x == a[i+<NUM_LIT:1>]:<EOL><INDENT>i += <NUM_LIT:1><EOL... | Given an array `a` of k distinct nonnegative integers, sorted in
ascending order, return the next k-array in the lexicographic
ordering of the descending sequences of the elements [1]_. `a` is
modified in place.
Parameters
----------
a : ndarray(int, ndim=1)
Array of length k.
Returns
-------
a : ndarray(int, ndi... | f5130:m0 |
def k_array_rank(a): | k = len(a)<EOL>idx = int(a[<NUM_LIT:0>]) <EOL>for i in range(<NUM_LIT:1>, k):<EOL><INDENT>idx += comb(a[i], i+<NUM_LIT:1>, exact=True)<EOL><DEDENT>return idx<EOL> | Given an array `a` of k distinct nonnegative integers, sorted in
ascending order, return its ranking in the lexicographic ordering of
the descending sequences of the elements [1]_.
Parameters
----------
a : ndarray(int, ndim=1)
Array of length k.
Returns
-------
idx : scalar(int)
Ranking of `a`.
References
-... | f5130:m1 |
@jit(nopython=True, cache=True)<EOL>def k_array_rank_jit(a): | k = len(a)<EOL>idx = a[<NUM_LIT:0>]<EOL>for i in range(<NUM_LIT:1>, k):<EOL><INDENT>idx += comb_jit(a[i], i+<NUM_LIT:1>)<EOL><DEDENT>return idx<EOL> | Numba jit version of `k_array_rank`.
Notes
-----
An incorrect value will be returned without warning or error if
overflow occurs during the computation. It is the user's
responsibility to ensure that the rank of the input array fits
within the range of possible values of `np.intp`; a sufficient
condition for it is `sc... | f5130:m2 |
def tic(self): | t = time.time()<EOL>self.start = t<EOL>self.last = t<EOL> | Save time for future use with `tac()` or `toc()`. | f5131:c0:m0 |
def tac(self, verbose=True, digits=<NUM_LIT:2>): | if self.start is None:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>t = time.time()<EOL>elapsed = t-self.last<EOL>self.last = t<EOL>if verbose:<EOL><INDENT>m, s = divmod(elapsed, <NUM_LIT>)<EOL>h, m = divmod(m, <NUM_LIT>)<EOL>print("<STR_LIT>" %<EOL>(h, m, s, digits, (s % <NUM_LIT:1>)*(<NUM_LIT:10>**digits)))<E... | Return and print elapsed time since last `tic()`, `tac()`, or
`toc()`.
Parameters
----------
verbose : bool, optional(default=True)
If True, then prints time.
digits : scalar(int), optional(default=2)
Number of digits printed for time elapsed.
Returns
-------
elapsed : scalar(float)
Time elapsed since la... | f5131:c0:m1 |
def toc(self, verbose=True, digits=<NUM_LIT:2>): | if self.start is None:<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT>t = time.time()<EOL>self.last = t<EOL>elapsed = t-self.start<EOL>if verbose:<EOL><INDENT>m, s = divmod(elapsed, <NUM_LIT>)<EOL>h, m = divmod(m, <NUM_LIT>)<EOL>print("<STR_LIT>" %<EOL>(h, m, s, digits, (s % <NUM_LIT:1>)*(<NUM_LIT:10>**digits)))<... | Return and print time elapsed since last `tic()`.
Parameters
----------
verbose : bool, optional(default=True)
If True, then prints time.
digits : scalar(int), optional(default=2)
Number of digits printed for time elapsed.
Returns
-------
elapsed : scalar(float)
Time elapsed since last `tic()`. | f5131:c0:m2 |
def loop_timer(self, n, function, args=None, verbose=True, digits=<NUM_LIT:2>,<EOL>best_of=<NUM_LIT:3>): | tic()<EOL>all_times = np.empty(n)<EOL>for run in range(n):<EOL><INDENT>if hasattr(args, '<STR_LIT>'):<EOL><INDENT>function(*args)<EOL><DEDENT>elif args is None:<EOL><INDENT>function()<EOL><DEDENT>else:<EOL><INDENT>function(args)<EOL><DEDENT>all_times[run] = tac(verbose=False, digits=digits)<EOL><DEDENT>elapsed = toc(ve... | Return and print the total and average time elapsed for n runs
of function.
Parameters
----------
n : scalar(int)
Number of runs.
function : function
Function to be timed.
args : list, optional(default=None)
Arguments of the function.
verbose : bool, optional(default=True)
If True, then prints avera... | f5131:c0:m3 |
def fetch_nb_dependencies(files, repo=REPO, raw=RAW, branch=BRANCH, folder=FOLDER, overwrite=False, verbose=True): | import requests<EOL>if type(files) == list:<EOL><INDENT>files = {"<STR_LIT>" : files}<EOL><DEDENT>status = []<EOL>for directory in files.keys():<EOL><INDENT>if directory != "<STR_LIT>":<EOL><INDENT>if verbose: print("<STR_LIT>"%directory)<EOL><DEDENT>for fl in files[directory]:<EOL><INDENT>if directory != "<STR_LIT>":<... | Retrieve raw files from QuantEcon.notebooks or other Github repo
Parameters
----------
file_list list or dict
A list of files to specify a collection of filenames
A dict of dir : list(files) to specify a directory
repo str, optional(default=REPO)
raw str, optional(defualt=RAW)
... | f5133:m0 |
def check_random_state(seed): | if seed is None or seed is np.random:<EOL><INDENT>return np.random.mtrand._rand<EOL><DEDENT>if isinstance(seed, (numbers.Integral, np.integer)):<EOL><INDENT>return np.random.RandomState(seed)<EOL><DEDENT>if isinstance(seed, np.random.RandomState):<EOL><INDENT>return seed<EOL><DEDENT>raise ValueError('<STR_LIT>'<EOL>'<S... | Check the random state of a given seed.
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a new RandomState instance seeded with seed.
If seed is already a RandomState instance, return it.
Otherwise raise ValueError.
.. Note
----
1. This code was sourced from sciki... | f5134:m0 |
@jit(nopython=True)<EOL>def searchsorted(a, v): | lo = -<NUM_LIT:1><EOL>hi = len(a)<EOL>while(lo < hi-<NUM_LIT:1>):<EOL><INDENT>m = (lo + hi) // <NUM_LIT:2><EOL>if v < a[m]:<EOL><INDENT>hi = m<EOL><DEDENT>else:<EOL><INDENT>lo = m<EOL><DEDENT><DEDENT>return hi<EOL> | Custom version of np.searchsorted. Return the largest index `i` such
that `a[i-1] <= v < a[i]` (for `i = 0`, `v < a[0]`); if `v[n-1] <=
v`, return `n`, where `n = len(a)`.
Parameters
----------
a : ndarray(float, ndim=1)
Input array. Must be sorted in ascending order.
v : scalar(float)
Value to be compared wi... | f5135:m0 |
def __call__(self, x): | return np.mean(self.observations <= x)<EOL> | Evaluates the ecdf at x
Parameters
----------
x : scalar(float)
The x at which the ecdf is evaluated
Returns
-------
scalar(float)
Fraction of the sample less than x | f5137:c0:m3 |
def rank_est(A, atol=<NUM_LIT>, rtol=<NUM_LIT:0>): | A = np.atleast_2d(A)<EOL>s = svd(A, compute_uv=False)<EOL>tol = max(atol, rtol * s[<NUM_LIT:0>])<EOL>rank = int((s >= tol).sum())<EOL>return rank<EOL> | Estimate the rank (i.e. the dimension of the nullspace) of a matrix.
The algorithm used by this function is based on the singular value
decomposition of `A`.
Parameters
----------
A : array_like(float, ndim=1 or 2)
A should be at most 2-D. A 1-D array with length n will be
treated as a 2-D with shape (1, n)
... | f5138:m0 |
def nullspace(A, atol=<NUM_LIT>, rtol=<NUM_LIT:0>): | A = np.atleast_2d(A)<EOL>u, s, vh = svd(A)<EOL>tol = max(atol, rtol * s[<NUM_LIT:0>])<EOL>nnz = (s >= tol).sum()<EOL>ns = vh[nnz:].conj().T<EOL>return ns<EOL> | Compute an approximate basis for the nullspace of A.
The algorithm used by this function is based on the singular value
decomposition of `A`.
Parameters
----------
A : array_like(float, ndim=1 or 2)
A should be at most 2-D. A 1-D array with length k will be
treated as a 2-D with shape (1, k)
atol : scalar(fl... | f5138:m1 |
def smooth(x, window_len=<NUM_LIT:7>, window='<STR_LIT>'): | if len(x) < window_len:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if window_len < <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not window_len % <NUM_LIT:2>: <EOL><INDENT>window_len += <NUM_LIT:1><EOL>print("<STR_LIT>".format(window_len))<EOL><DEDENT>windows = {'<STR_LIT>': np.hanni... | Smooth the data in x using convolution with a window of requested
size and type.
Parameters
----------
x : array_like(float)
A flat NumPy array containing the data to smooth
window_len : scalar(int), optional
An odd integer giving the length of the window. Defaults to 7.
window : string
A string giving th... | f5139:m0 |
def periodogram(x, window=None, window_len=<NUM_LIT:7>): | n = len(x)<EOL>I_w = np.abs(fft(x))**<NUM_LIT:2> / n<EOL>w = <NUM_LIT:2> * np.pi * np.arange(n) / n <EOL>w, I_w = w[:int(n/<NUM_LIT:2>)+<NUM_LIT:1>], I_w[:int(n/<NUM_LIT:2>)+<NUM_LIT:1>] <EOL>if window:<EOL><INDENT>I_w = smooth(I_w, window_len=window_len, window=window)<EOL><DEDENT>return w, I_w<EOL> | r"""
Computes the periodogram
.. math::
I(w) = \frac{1}{n} \Big[ \sum_{t=0}^{n-1} x_t e^{itw} \Big] ^2
at the Fourier frequences :math:`w_j := \frac{2 \pi j}{n}`,
:math:`j = 0, \dots, n - 1`, using the fast Fourier transform. Only the
frequences :math:`w_j` in :math:`[0, \pi]` and corresp... | f5139:m1 |
def ar_periodogram(x, window='<STR_LIT>', window_len=<NUM_LIT:7>): | <EOL>x_lag = x[:-<NUM_LIT:1>] <EOL>X = np.array([np.ones(len(x_lag)), x_lag]).T <EOL>y = np.array(x[<NUM_LIT:1>:]) <EOL>beta_hat = np.linalg.solve(X.T @ X, X.T @ y) <EOL>e_hat = y - X @ beta_hat <EOL>phi = beta_hat[<NUM_LIT:1>] <EOL>w, I_w = periodogram(e_hat, window=window, window_len=window_len)<EOL>I_w = I_w /... | Compute periodogram from data x, using prewhitening, smoothing and
recoloring. The data is fitted to an AR(1) model for prewhitening,
and the residuals are used to compute a first-pass periodogram with
smoothing. The fitted coefficients are then used for recoloring.
Parameters
----------
x : array_like(float)
A ... | f5139:m2 |
@jit<EOL>def simulate_linear_model(A, x0, v, ts_length): | A = np.asarray(A)<EOL>n = A.shape[<NUM_LIT:0>]<EOL>x = np.empty((n, ts_length))<EOL>x[:, <NUM_LIT:0>] = x0<EOL>for t in range(ts_length-<NUM_LIT:1>):<EOL><INDENT>for i in range(n):<EOL><INDENT>x[i, t+<NUM_LIT:1>] = v[i, t] <EOL>for j in range(n):<EOL><INDENT>x[i, t+<NUM_LIT:1>] += A[i, j] * x[j, t] ... | r"""
This is a separate function for simulating a vector linear system of
the form
.. math::
x_{t+1} = A x_t + v_t
given :math:`x_0` = x0
Here :math:`x_t` and :math:`v_t` are both n x 1 and :math:`A` is n x n.
The purpose of separating this functionality out is to target it for
... | f5140:m0 |
def convert(self, x): | return np.atleast_2d(np.asarray(x, dtype='<STR_LIT:float>'))<EOL> | Convert array_like objects (lists of lists, floats, etc.) into
well formed 2D NumPy arrays | f5140:c0:m3 |
def simulate(self, ts_length=<NUM_LIT:100>, random_state=None): | random_state = check_random_state(random_state)<EOL>x0 = multivariate_normal(self.mu_0.flatten(), self.Sigma_0)<EOL>w = random_state.randn(self.m, ts_length-<NUM_LIT:1>)<EOL>v = self.C.dot(w) <EOL>x = simulate_linear_model(self.A, x0, v, ts_length)<EOL>if self.H is not None:<EOL><INDENT>v = random_state.randn(self.l, ... | r"""
Simulate a time series of length ts_length, first drawing
.. math::
x_0 \sim N(\mu_0, \Sigma_0)
Parameters
----------
ts_length : scalar(int), optional(default=100)
The length of the simulation
random_state : int or np.random.RandomState, o... | f5140:c0:m4 |
def replicate(self, T=<NUM_LIT:10>, num_reps=<NUM_LIT:100>, random_state=None): | random_state = check_random_state(random_state)<EOL>x = np.empty((self.n, num_reps))<EOL>for j in range(num_reps):<EOL><INDENT>x_T, _ = self.simulate(ts_length=T+<NUM_LIT:1>, random_state=random_state)<EOL>x[:, j] = x_T[:, -<NUM_LIT:1>]<EOL><DEDENT>if self.H is not None:<EOL><INDENT>v = random_state.randn(self.l, num_r... | r"""
Simulate num_reps observations of :math:`x_T` and :math:`y_T` given
:math:`x_0 \sim N(\mu_0, \Sigma_0)`.
Parameters
----------
T : scalar(int), optional(default=10)
The period that we want to replicate values for
num_reps : scalar(int), optional(default=... | f5140:c0:m5 |
def moment_sequence(self): | <EOL>A, C, G, H = self.A, self.C, self.G, self.H<EOL>mu_x, Sigma_x = self.mu_0, self.Sigma_0<EOL>while <NUM_LIT:1>:<EOL><INDENT>mu_y = G.dot(mu_x)<EOL>if H is None:<EOL><INDENT>Sigma_y = G.dot(Sigma_x).dot(G.T)<EOL><DEDENT>else:<EOL><INDENT>Sigma_y = G.dot(Sigma_x).dot(G.T) + H.dot(H.T)<EOL><DEDENT>yield mu_x, mu_y, Si... | r"""
Create a generator to calculate the population mean and
variance-convariance matrix for both :math:`x_t` and :math:`y_t`
starting at the initial condition (self.mu_0, self.Sigma_0).
Each iteration produces a 4-tuple of items (mu_x, mu_y, Sigma_x,
Sigma_y) for the next period... | f5140:c0:m6 |
def stationary_distributions(self, max_iter=<NUM_LIT:200>, tol=<NUM_LIT>): | <EOL>m = self.moment_sequence()<EOL>mu_x, mu_y, Sigma_x, Sigma_y = next(m)<EOL>i = <NUM_LIT:0><EOL>error = tol + <NUM_LIT:1><EOL>while error > tol:<EOL><INDENT>if i > max_iter:<EOL><INDENT>fail_message = '<STR_LIT>'<EOL>raise ValueError(fail_message.format(max_iter))<EOL><DEDENT>else:<EOL><INDENT>i += <NUM_LIT:1><EOL>m... | r"""
Compute the moments of the stationary distributions of :math:`x_t` and
:math:`y_t` if possible. Computation is by iteration, starting from
the initial conditions self.mu_0 and self.Sigma_0
Parameters
----------
max_iter : scalar(int), optional(default=200)
... | f5140:c0:m7 |
def geometric_sums(self, beta, x_t): | I = np.identity(self.n)<EOL>S_x = solve(I - beta * self.A, x_t)<EOL>S_y = self.G.dot(S_x)<EOL>return S_x, S_y<EOL> | r"""
Forecast the geometric sums
.. math::
S_x := E \Big[ \sum_{j=0}^{\infty} \beta^j x_{t+j} | x_t \Big]
S_y := E \Big[ \sum_{j=0}^{\infty} \beta^j y_{t+j} | x_t \Big]
Parameters
----------
beta : scalar(float)
Discount factor, in [0, 1)
... | f5140:c0:m8 |
def impulse_response(self, j=<NUM_LIT:5>): | <EOL>A, C, G, H = self.A, self.C, self.G, self.H<EOL>Apower = np.copy(A)<EOL>xcoef = [C]<EOL>ycoef = [np.dot(G, C)]<EOL>for i in range(j):<EOL><INDENT>xcoef.append(np.dot(Apower, C))<EOL>ycoef.append(np.dot(G, np.dot(Apower, C)))<EOL>Apower = np.dot(Apower, A)<EOL><DEDENT>return xcoef, ycoef<EOL> | r"""
Pulls off the imuplse response coefficients to a shock
in :math:`w_{t}` for :math:`x` and :math:`y`
Important to note: We are uninterested in the shocks to
v for this method
* :math:`x` coefficients are :math:`C, AC, A^2 C...`
* :math:`y` coefficients are :math:`GC... | f5140:c0:m9 |
def ckron(*arrays): | return reduce(np.kron, arrays)<EOL> | Repeatedly applies the np.kron function to an arbitrary number of
input arrays
Parameters
----------
*arrays : tuple/list of np.ndarray
Returns
-------
out : np.ndarray
The result of repeated kronecker products.
Notes
-----
Based of original function `ckron` in CompEcon toolbox by Miranda
and Fackler.
Referen... | f5141:m0 |
def gridmake(*arrays): | if all([i.ndim == <NUM_LIT:1> for i in arrays]):<EOL><INDENT>d = len(arrays)<EOL>if d == <NUM_LIT:2>:<EOL><INDENT>out = _gridmake2(*arrays)<EOL><DEDENT>else:<EOL><INDENT>out = _gridmake2(arrays[<NUM_LIT:0>], arrays[<NUM_LIT:1>])<EOL>for arr in arrays[<NUM_LIT:2>:]:<EOL><INDENT>out = _gridmake2(out, arr)<EOL><DEDENT><DE... | Expands one or more vectors (or matrices) into a matrix where rows span the
cartesian product of combinations of the input arrays. Each column of the
input arrays will correspond to one column of the output matrix.
Parameters
----------
*arrays : tuple/list of np.ndarray
Tuple/list of vectors to be expanded.... | f5141:m1 |
def _gridmake2(x1, x2): | if x1.ndim == <NUM_LIT:1> and x2.ndim == <NUM_LIT:1>:<EOL><INDENT>return np.column_stack([np.tile(x1, x2.shape[<NUM_LIT:0>]),<EOL>np.repeat(x2, x1.shape[<NUM_LIT:0>])])<EOL><DEDENT>elif x1.ndim > <NUM_LIT:1> and x2.ndim == <NUM_LIT:1>:<EOL><INDENT>first = np.tile(x1, (x2.shape[<NUM_LIT:0>], <NUM_LIT:1>))<EOL>second = n... | Expands two vectors (or matrices) into a matrix where rows span the
cartesian product of combinations of the input arrays. Each column of the
input arrays will correspond to one column of the output matrix.
Parameters
----------
x1 : np.ndarray
First vector to be expanded.
x2 : np.ndarray
Second vector to b... | f5141:m2 |
def _csr_matrix_indices(S): | m, n = S.shape<EOL>for i in range(m):<EOL><INDENT>for j in range(S.indptr[i], S.indptr[i+<NUM_LIT:1>]):<EOL><INDENT>row_index, col_index = i, S.indices[j]<EOL>yield row_index, col_index<EOL><DEDENT><DEDENT> | Generate the indices of nonzero entries of a csr_matrix S | f5142:m1 |
def random_tournament_graph(n, random_state=None): | random_state = check_random_state(random_state)<EOL>num_edges = n * (n-<NUM_LIT:1>) // <NUM_LIT:2><EOL>r = random_state.random_sample(num_edges)<EOL>row = np.empty(num_edges, dtype=int)<EOL>col = np.empty(num_edges, dtype=int)<EOL>_populate_random_tournament_row_col(n, r, row, col)<EOL>data = np.ones(num_edges, dtype=b... | Return a random tournament graph [1]_ with n nodes.
Parameters
----------
n : scalar(int)
Number of nodes.
random_state : int or np.random.RandomState, optional
Random seed (integer) or np.random.RandomState instance to set
the initial state of the random number generator for
reproducibility. If None,... | f5142:m2 |
@jit(nopython=True, cache=True)<EOL>def _populate_random_tournament_row_col(n, r, row, col): | k = <NUM_LIT:0><EOL>for i in range(n):<EOL><INDENT>for j in range(i+<NUM_LIT:1>, n):<EOL><INDENT>if r[k] < <NUM_LIT:0.5>:<EOL><INDENT>row[k], col[k] = i, j<EOL><DEDENT>else:<EOL><INDENT>row[k], col[k] = j, i<EOL><DEDENT>k += <NUM_LIT:1><EOL><DEDENT><DEDENT> | Populate ndarrays `row` and `col` with directed edge indices
determined by random numbers in `r` for a tournament graph with n
nodes, which has num_edges = n * (n-1) // 2 edges.
Parameters
----------
n : scalar(int)
Number of nodes.
r : ndarray(float, ndim=1)
ndarray of length num_edges containing random numb... | f5142:m3 |
def _find_scc(self): | <EOL>self._num_scc, self._scc_proj =csgraph.connected_components(self.csgraph, connection='<STR_LIT>')<EOL> | Set ``self._num_scc`` and ``self._scc_proj``
by calling ``scipy.sparse.csgraph.connected_components``:
* docs.scipy.org/doc/scipy/reference/sparse.csgraph.html
* github.com/scipy/scipy/blob/master/scipy/sparse/csgraph/_traversal.pyx
``self._scc_proj`` is a list of length `n` that assigns to each node
the label of the ... | f5142:c0:m5 |
def _condensation_lil(self): | condensation_lil = sparse.lil_matrix(<EOL>(self.num_strongly_connected_components,<EOL>self.num_strongly_connected_components), dtype=bool<EOL>)<EOL>scc_proj = self.scc_proj<EOL>for node_from, node_to in _csr_matrix_indices(self.csgraph):<EOL><INDENT>scc_from, scc_to = scc_proj[node_from], scc_proj[node_to]<EOL>if scc_... | Return the sparse matrix representation of the condensation digraph
in lil format. | f5142:c0:m9 |
def _find_sink_scc(self): | condensation_lil = self._condensation_lil()<EOL>self._sink_scc_labels =np.where(np.logical_not(condensation_lil.rows))[<NUM_LIT:0>]<EOL> | Set self._sink_scc_labels, which is a list containing the labels of
the strongly connected components. | f5142:c0:m10 |
def _compute_period(self): | <EOL>if self.n == <NUM_LIT:1>:<EOL><INDENT>if self.csgraph[<NUM_LIT:0>, <NUM_LIT:0>] == <NUM_LIT:0>: <EOL><INDENT>self._period = <NUM_LIT:1> <EOL>self._cyclic_components_proj = np.zeros(self.n, dtype=int)<EOL>return None<EOL><DEDENT>else: <EOL><INDENT>self._period = <NUM_LIT:1><EOL>self._cyclic_components_proj = np.... | Set ``self._period`` and ``self._cyclic_components_proj``.
Use the algorithm described in:
J. P. Jarvis and D. R. Shier,
"Graph-Theoretic Analysis of Finite Markov Chains," 1996. | f5142:c0:m17 |
def subgraph(self, nodes): | adj_matrix = self.csgraph[np.ix_(nodes, nodes)]<EOL>weighted = True <EOL>if self.node_labels is not None:<EOL><INDENT>node_labels = self.node_labels[nodes]<EOL><DEDENT>else:<EOL><INDENT>node_labels = None<EOL><DEDENT>return DiGraph(adj_matrix, weighted=weighted, node_labels=node_labels)<EOL> | Return the subgraph consisting of the given nodes and edges
between thses nodes.
Parameters
----------
nodes : array_like(int, ndim=1)
Array of node indices.
Returns
-------
DiGraph
A DiGraph representing the subgraph. | f5142:c0:m22 |
def compute_fixed_point(T, v, error_tol=<NUM_LIT>, max_iter=<NUM_LIT:50>, verbose=<NUM_LIT:2>,<EOL>print_skip=<NUM_LIT:5>, method='<STR_LIT>', *args, **kwargs): | if max_iter < <NUM_LIT:1>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if verbose not in (<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:2>):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if method not in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if method == '<STR_LIT>':<E... | r"""
Computes and returns an approximate fixed point of the function `T`.
The default method `'iteration'` simply iterates the function given
an initial condition `v` and returns :math:`T^k v` when the
condition :math:`\lVert T^k v - T^{k-1} v\rVert \leq
\mathrm{error\_tol}` is satisfied or the num... | f5143:m2 |
def _compute_fixed_point_ig(T, v, max_iter, verbose, print_skip, is_approx_fp,<EOL>*args, **kwargs): | if verbose == <NUM_LIT:2>:<EOL><INDENT>start_time = time.time()<EOL>_print_after_skip(print_skip, it=None)<EOL><DEDENT>x_new = v<EOL>y_new = T(x_new, *args, **kwargs)<EOL>iterate = <NUM_LIT:1><EOL>converged = is_approx_fp(x_new)<EOL>if converged or iterate >= max_iter:<EOL><INDENT>if verbose == <NUM_LIT:2>:<EOL><INDENT... | Implement the imitation game algorithm by McLennan and Tourky (2006)
for computing an approximate fixed point of `T`.
Parameters
----------
is_approx_fp : callable
A callable with signature `is_approx_fp(v)` which determines
whether `v` is an approximate fixed point with a bool return
value (i.e., True or ... | f5143:m3 |
@jit(nopython=True)<EOL>def _initialize_tableaux_ig(X, Y, tableaux, bases): | m = X.shape[<NUM_LIT:0>]<EOL>min_ = np.zeros(m)<EOL>for i in range(m):<EOL><INDENT>for j in range(<NUM_LIT:2>*m):<EOL><INDENT>if j == i or j == i + m:<EOL><INDENT>tableaux[<NUM_LIT:0>][i, j] = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>tableaux[<NUM_LIT:0>][i, j] = <NUM_LIT:0><EOL><DEDENT><DEDENT>tableaux[<NUM_LIT:0>][i... | Given sequences `X` and `Y` of ndarrays, initialize the tableau and
basis arrays in place for the "geometric" imitation game as defined
in McLennan and Tourky (2006), to be passed to `_lemke_howson_tbl`.
Parameters
----------
X, Y : ndarray(float)
Arrays of the same shape (m, n).
tableaux : tuple(ndarray(float, n... | f5143:m4 |
def d_operator(self, P): | C, theta = self.C, self.theta<EOL>I = np.identity(self.j)<EOL>S1 = dot(P, C)<EOL>S2 = dot(C.T, S1)<EOL>dP = P + dot(S1, solve(theta * I - S2, S1.T))<EOL>return dP<EOL> | r"""
The D operator, mapping P into
.. math::
D(P) := P + PC(\theta I - C'PC)^{-1} C'P.
Parameters
----------
P : array_like(float, ndim=2)
A matrix that should be n x n
Returns
-------
dP : array_like(float, ndim=2)
... | f5144:c0:m3 |
def b_operator(self, P): | A, B, Q, R, beta = self.A, self.B, self.Q, self.R, self.beta<EOL>S1 = Q + beta * dot(B.T, dot(P, B))<EOL>S2 = beta * dot(B.T, dot(P, A))<EOL>S3 = beta * dot(A.T, dot(P, A))<EOL>F = solve(S1, S2) if not self.pure_forecasting else np.zeros(<EOL>(self.k, self.n))<EOL>new_P = R - dot(S2.T, F) + S3<EOL>return F, new_P<EOL> | r"""
The B operator, mapping P into
.. math::
B(P) := R - \beta^2 A'PB(Q + \beta B'PB)^{-1}B'PA + \beta A'PA
and also returning
.. math::
F := (Q + \beta B'PB)^{-1} \beta B'PA
Parameters
----------
P : array_like(float, ndim=2)
... | f5144:c0:m4 |
def robust_rule(self, method='<STR_LIT>'): | <EOL>A, B, C, Q, R = self.A, self.B, self.C, self.Q, self.R<EOL>beta, theta = self.beta, self.theta<EOL>k, j = self.k, self.j<EOL>I = identity(j)<EOL>Z = np.zeros((k, j))<EOL>if self.pure_forecasting:<EOL><INDENT>lq = LQ(-beta*I*theta, R, A, C, beta=beta)<EOL>P, f, d = lq.stationary_values(method=method)<EOL>F = np.zer... | This method solves the robust control problem by tricking it
into a stacked LQ problem, as described in chapter 2 of Hansen-
Sargent's text "Robustness." The optimal control with observed
state is
.. math::
u_t = - F x_t
And the value function is :math:`-x'Px`
Parameters
----------
method : str, optional(defau... | f5144:c0:m5 |
def robust_rule_simple(self, P_init=None, max_iter=<NUM_LIT>, tol=<NUM_LIT>): | <EOL>A, B, C, Q, R = self.A, self.B, self.C, self.Q, self.R<EOL>beta, theta = self.beta, self.theta<EOL>P = np.zeros((self.n, self.n)) if P_init is None else P_init<EOL>iterate, e = <NUM_LIT:0>, tol + <NUM_LIT:1><EOL>while iterate < max_iter and e > tol:<EOL><INDENT>F, new_P = self.b_operator(self.d_operator(P))<EOL>e ... | A simple algorithm for computing the robust policy F and the
corresponding value function P, based around straightforward
iteration with the robust Bellman operator. This function is
easier to understand but one or two orders of magnitude slower
than self.robust_rule(). For more information see the docstring
of that ... | f5144:c0:m6 |
def F_to_K(self, F, method='<STR_LIT>'): | Q2 = self.beta * self.theta<EOL>R2 = - self.R - dot(F.T, dot(self.Q, F))<EOL>A2 = self.A - dot(self.B, F)<EOL>B2 = self.C<EOL>lq = LQ(Q2, R2, A2, B2, beta=self.beta)<EOL>neg_P, neg_K, d = lq.stationary_values(method=method)<EOL>return -neg_K, -neg_P<EOL> | Compute agent 2's best cost-minimizing response K, given F.
Parameters
----------
F : array_like(float, ndim=2)
A k x n array
method : str, optional(default='doubling')
Solution method used in solving the associated Riccati
equation, str in {'doubling', 'qz'}.
Returns
-------
K : array_like(float, ndim=2)... | f5144:c0:m7 |
def K_to_F(self, K, method='<STR_LIT>'): | A1 = self.A + dot(self.C, K)<EOL>B1 = self.B<EOL>Q1 = self.Q<EOL>R1 = self.R - self.beta * self.theta * dot(K.T, K)<EOL>lq = LQ(Q1, R1, A1, B1, beta=self.beta)<EOL>P, F, d = lq.stationary_values(method=method)<EOL>return F, P<EOL> | Compute agent 1's best value-maximizing response F, given K.
Parameters
----------
K : array_like(float, ndim=2)
A j x n array
method : str, optional(default='doubling')
Solution method used in solving the associated Riccati
equation, str in {'doubling', 'qz'}.
Returns
-------
F : array_like(float, ndim=2... | f5144:c0:m8 |
def compute_deterministic_entropy(self, F, K, x0): | H0 = dot(K.T, K)<EOL>C0 = np.zeros((self.n, <NUM_LIT:1>))<EOL>A0 = self.A - dot(self.B, F) + dot(self.C, K)<EOL>e = var_quadratic_sum(A0, C0, H0, self.beta, x0)<EOL>return e<EOL> | r"""
Given K and F, compute the value of deterministic entropy, which
is
.. math::
\sum_t \beta^t x_t' K'K x_t`
with
.. math::
x_{t+1} = (A - BF + CK) x_t
Parameters
----------
F : array_like(float, ndim=2)
The po... | f5144:c0:m9 |
def evaluate_F(self, F): | <EOL>Q, R, A, B, C = self.Q, self.R, self.A, self.B, self.C<EOL>beta, theta = self.beta, self.theta<EOL>K_F, P_F = self.F_to_K(F)<EOL>I = np.identity(self.j)<EOL>H = inv(I - C.T.dot(P_F.dot(C)) / theta)<EOL>d_F = log(det(H))<EOL>sig = -<NUM_LIT:1.0> / theta<EOL>AO = sqrt(beta) * (A - dot(B, F) + dot(C, K_F))<EOL>O_F = ... | Given a fixed policy F, with the interpretation :math:`u = -F x`, this
function computes the matrix :math:`P_F` and constant :math:`d_F`
associated with discounted cost :math:`J_F(x) = x' P_F x + d_F`
Parameters
----------
F : array_like(float, ndim=2)
The policy function, a k x n array
Returns
-------
P_F : arra... | f5144:c0:m10 |
@njit<EOL>def lorenz_curve(y): | n = len(y)<EOL>y = np.sort(y)<EOL>s = np.zeros(n + <NUM_LIT:1>)<EOL>s[<NUM_LIT:1>:] = np.cumsum(y)<EOL>cum_people = np.zeros(n + <NUM_LIT:1>)<EOL>cum_income = np.zeros(n + <NUM_LIT:1>)<EOL>for i in range(<NUM_LIT:1>, n + <NUM_LIT:1>):<EOL><INDENT>cum_people[i] = i / n<EOL>cum_income[i] = s[i] / s[n]<EOL><DEDENT>return ... | Calculates the Lorenz Curve, a graphical representation of the distribution of income
or wealth.
It returns the cumulative share of people (x-axis) and the cumulative share of income earned
Parameters
----------
y : array_like(float or int, ndim=1)
Array of income/wealth for each individual. Unordered or ordered ... | f5145:m0 |
@njit(parallel=True)<EOL>def gini_coefficient(y): | n = len(y)<EOL>i_sum = np.zeros(n)<EOL>for i in prange(n):<EOL><INDENT>for j in range(n):<EOL><INDENT>i_sum[i] += abs(y[i] - y[j])<EOL><DEDENT><DEDENT>return np.sum(i_sum) / (<NUM_LIT:2> * n * np.sum(y))<EOL> | r"""
Implements the Gini inequality index
Parameters
-----------
y : array_like(float)
Array of income/wealth for each individual. Ordered or unordered is fine
Returns
-------
Gini index: float
The gini index describing the inequality of the array of income/wealth
Refe... | f5145:m1 |
def shorrocks_index(A): | A = np.asarray(A) <EOL>m, n = A.shape<EOL>if m != n:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>diag_sum = np.diag(A).sum()<EOL>return (m - diag_sum) / (m - <NUM_LIT:1>)<EOL> | r"""
Implements Shorrocks mobility index
Parameters
-----------
A : array_like(float)
Square matrix with transition probabilities (mobility matrix) of
dimension m
Returns
--------
Shorrocks index: float
The Shorrocks mobility index calculated as
.. math::
... | f5145:m2 |
@property<EOL><INDENT>def mean(self):<DEDENT> | n, a, b = self.n, self.a, self.b<EOL>return n * a / (a + b)<EOL> | mean | f5146:c0:m1 |
@property<EOL><INDENT>def std(self):<DEDENT> | return sqrt(self.var)<EOL> | standard deviation | f5146:c0:m2 |
@property<EOL><INDENT>def var(self):<DEDENT> | n, a, b = self.n, self.a, self.b<EOL>top = n*a*b * (a + b + n)<EOL>btm = (a+b)**<NUM_LIT> * (a+b+<NUM_LIT:1.0>)<EOL>return top / btm<EOL> | Variance | f5146:c0:m3 |
@property<EOL><INDENT>def skew(self):<DEDENT> | n, a, b = self.n, self.a, self.b<EOL>t1 = (a+b+<NUM_LIT:2>*n) * (b - a) / (a+b+<NUM_LIT:2>)<EOL>t2 = sqrt((<NUM_LIT:1>+a+b) / (n*a*b * (n+a+b)))<EOL>return t1 * t2<EOL> | skewness | f5146:c0:m4 |
def pdf(self): | n, a, b = self.n, self.a, self.b<EOL>k = np.arange(n + <NUM_LIT:1>)<EOL>probs = binom(n, k) * beta(k + a, n - k + b) / beta(a, b)<EOL>return probs<EOL> | r"""
Generate the vector of probabilities for the Beta-binomial
(n, a, b) distribution.
The Beta-binomial distribution takes the form
.. math::
p(k \,|\, n, a, b) =
{n \choose k} \frac{B(k + a, n - k + b)}{B(a, b)},
\qquad k = 0, \ldots, n,
... | f5146:c0:m5 |
def nnash(A, B1, B2, R1, R2, Q1, Q2, S1, S2, W1, W2, M1, M2,<EOL>beta=<NUM_LIT:1.0>, tol=<NUM_LIT>, max_iter=<NUM_LIT:1000>, random_state=None): | <EOL>params = A, B1, B2, R1, R2, Q1, Q2, S1, S2, W1, W2, M1, M2<EOL>params = map(np.asarray, params)<EOL>A, B1, B2, R1, R2, Q1, Q2, S1, S2, W1, W2, M1, M2 = params<EOL>A, B1, B2 = [np.sqrt(beta) * x for x in (A, B1, B2)]<EOL>n = A.shape[<NUM_LIT:0>]<EOL>if B1.ndim == <NUM_LIT:1>:<EOL><INDENT>k_1 = <NUM_LIT:1><EOL>B1 = ... | r"""
Compute the limit of a Nash linear quadratic dynamic game. In this
problem, player i minimizes
.. math::
\sum_{t=0}^{\infty}
\left\{
x_t' r_i x_t + 2 x_t' w_i
u_{it} +u_{it}' q_i u_{it} + u_{jt}' s_i u_{jt} + 2 u_{jt}'
m_i u_{it}
\right\}
... | f5147:m0 |
def write_version_py(filename=None): | doc = "<STR_LIT>"<EOL>doc += "<STR_LIT>" % VERSION<EOL>if not filename:<EOL><INDENT>filename = os.path.join(os.path.dirname(__file__), '<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>fl = open(filename, '<STR_LIT:w>')<EOL>try:<EOL><INDENT>fl.write(doc)<EOL><DEDENT>finally:<EOL><INDENT>fl.close()<EOL><DEDENT> | This constructs a version file for the project | f5148:m0 |
def block_parser(part, rgxin, rgxout, fmtin, fmtout): | block = []<EOL>lines = part.split('<STR_LIT:\n>')<EOL>N = len(lines)<EOL>i = <NUM_LIT:0><EOL>decorator = None<EOL>while <NUM_LIT:1>:<EOL><INDENT>if i==N:<EOL><INDENT>break<EOL><DEDENT>line = lines[i]<EOL>i += <NUM_LIT:1><EOL>line_stripped = line.strip()<EOL>if line_stripped.startswith('<STR_LIT:#>'):<EOL><INDENT>block.... | part is a string of ipython text, comprised of at most one
input, one ouput, comments, and blank lines. The block parser
parses the text into a list of::
blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...]
where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and
data is, depending on the type of token::
COMMENT : th... | f5151:m0 |
def process_input_line(self, line, store_history=True): | <EOL>stdout = sys.stdout<EOL>splitter = self.IP.input_splitter<EOL>try:<EOL><INDENT>sys.stdout = self.cout<EOL>splitter.push(line)<EOL>more = splitter.push_accepts_more()<EOL>if not more:<EOL><INDENT>source_raw = splitter.source_raw_reset()[<NUM_LIT:1>]<EOL>self.IP.run_cell(source_raw, store_history=store_history)<EOL>... | process the input, capturing stdout | f5151:c0:m2 |
def process_image(self, decorator): | savefig_dir = self.savefig_dir<EOL>source_dir = self.source_dir<EOL>saveargs = decorator.split('<STR_LIT:U+0020>')<EOL>filename = saveargs[<NUM_LIT:1>]<EOL>outfile = os.path.relpath(os.path.join(savefig_dir,filename),<EOL>source_dir)<EOL>imagerows = ['<STR_LIT>'%outfile]<EOL>for kwarg in saveargs[<NUM_LIT:2>:]:<EOL><IN... | # build out an image directive like
# .. image:: somefile.png
# :width 4in
#
# from an input like
# savefig somefile.png width=4in | f5151:c0:m3 |
def process_input(self, data, input_prompt, lineno): | decorator, input, rest = data<EOL>image_file = None<EOL>image_directive = None<EOL>is_verbatim = decorator=='<STR_LIT>' or self.is_verbatim<EOL>is_doctest = decorator=='<STR_LIT>' or self.is_doctest<EOL>is_suppress = decorator=='<STR_LIT>' or self.is_suppress<EOL>is_okexcept = decorator=='<STR_LIT>' or self.is_okexcept... | Process data block for INPUT token. | f5151:c0:m4 |
def process_comment(self, data): | if not self.is_suppress:<EOL><INDENT>return [data]<EOL><DEDENT> | Process data fPblock for COMMENT token. | f5151:c0:m6 |
def save_image(self, image_file): | self.ensure_pyplot()<EOL>command = ('<STR_LIT>'<EOL>'<STR_LIT>' % image_file)<EOL>self.process_input_line('<STR_LIT>', store_history=False)<EOL>self.process_input_line('<STR_LIT>', store_history=False)<EOL>self.process_input_line(command, store_history=False)<EOL>self.process_input_line('<STR_LIT>', store_history=False... | Saves the image file to disk. | f5151:c0:m7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.