signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def VRF_prediction(self):
g = self.g<EOL>h = self.h<EOL>return (<NUM_LIT:2>*g**<NUM_LIT:2> + <NUM_LIT:2>*h + g*h) / (g*(<NUM_LIT:4> - <NUM_LIT:2>*g - h))<EOL>
Returns the Variance Reduction Factor of the prediction step of the filter. The VRF is the normalized variance for the filter, as given in the equation below. .. math:: VRF(\hat{x}_{n+1,n}) = \\frac{VAR(\hat{x}_{n+1,n})}{\sigma^2_x} References ---------- Asquith, "Weight Selection in First Order Linear Filters" Report No RG-TR-69-12, U.S. Army Missle Command. Redstone Arsenal, Al. November 24, 1970.
f691:c1:m3
def VRF(self):
g = self.g<EOL>h = self.h<EOL>den = g*(<NUM_LIT:4> - <NUM_LIT:2>*g - h)<EOL>vx = (<NUM_LIT:2>*g**<NUM_LIT:2> + <NUM_LIT:2>*h - <NUM_LIT:3>*g*h) / den<EOL>vdx = <NUM_LIT:2>*h**<NUM_LIT:2> / (self.dt**<NUM_LIT:2> * den)<EOL>return (vx, vdx)<EOL>
Returns the Variance Reduction Factor (VRF) of the state variable of the filter (x) and its derivatives (dx, ddx). The VRF is the normalized variance for the filter, as given in the equations below. .. math:: VRF(\hat{x}_{n,n}) = \\frac{VAR(\hat{x}_{n,n})}{\sigma^2_x} VRF(\hat{\dot{x}}_{n,n}) = \\frac{VAR(\hat{\dot{x}}_{n,n})}{\sigma^2_x} VRF(\hat{\ddot{x}}_{n,n}) = \\frac{VAR(\hat{\ddot{x}}_{n,n})}{\sigma^2_x} Returns ------- vrf_x VRF of x state variable vrf_dx VRF of the dx state variable (derivative of x)
f691:c1:m4
def update(self, z, g=None, h=None, k=None):
if g is None:<EOL><INDENT>g = self.g<EOL><DEDENT>if h is None:<EOL><INDENT>h = self.h<EOL><DEDENT>if k is None:<EOL><INDENT>k = self.k<EOL><DEDENT>dt = self.dt<EOL>dt_sqr = dt**<NUM_LIT:2><EOL>self.ddx_prediction = self.ddx<EOL>self.dx_prediction = self.dx + self.ddx*dt<EOL>self.x_prediction = self.x + self.dx*dt + <NUM_LIT>*self.ddx*(dt_sqr)<EOL>self.y = z - self.x_prediction<EOL>self.ddx = self.ddx_prediction + <NUM_LIT:2>*k*self.y / dt_sqr<EOL>self.dx = self.dx_prediction + h * self.y / dt<EOL>self.x = self.x_prediction + g * self.y<EOL>return (self.x, self.dx)<EOL>
Performs the g-h filter predict and update step on the measurement z. On return, self.x, self.dx, self.y, and self.x_prediction will have been updated with the results of the computation. For convienence, self.x and self.dx are returned in a tuple. Parameters ---------- z : scalar the measurement g : scalar (optional) Override the fixed self.g value for this update h : scalar (optional) Override the fixed self.h value for this update k : scalar (optional) Override the fixed self.k value for this update Returns ------- x filter output for x dx filter output for dx (derivative of x
f691:c2:m1
def batch_filter(self, data, save_predictions=False):
x = self.x<EOL>dx = self.dx<EOL>n = len(data)<EOL>results = np.zeros((n+<NUM_LIT:1>, <NUM_LIT:2>))<EOL>results[<NUM_LIT:0>, <NUM_LIT:0>] = x<EOL>results[<NUM_LIT:0>, <NUM_LIT:1>] = dx<EOL>if save_predictions:<EOL><INDENT>predictions = np.zeros(n)<EOL><DEDENT>h_dt = self.h / self.dt<EOL>for i, z in enumerate(data):<EOL><INDENT>x_est = x + (dx*self.dt)<EOL>residual = z - x_est<EOL>dx = dx + h_dt * residual <EOL>x = x_est + self.g * residual<EOL>results[i+<NUM_LIT:1>, <NUM_LIT:0>] = x<EOL>results[i+<NUM_LIT:1>, <NUM_LIT:1>] = dx<EOL>if save_predictions:<EOL><INDENT>predictions[i] = x_est<EOL><DEDENT><DEDENT>if save_predictions:<EOL><INDENT>return results, predictions<EOL><DEDENT>return results<EOL>
Performs g-h filter with a fixed g and h. Uses self.x and self.dx to initialize the filter, but DOES NOT alter self.x and self.dx during execution, allowing you to use this class multiple times without reseting self.x and self.dx. I'm not sure how often you would need to do that, but the capability is there. More exactly, none of the class member variables are modified by this function. Parameters ---------- data : list_like contains the data to be filtered. save_predictions : boolean The predictions will be saved and returned if this is true Returns ------- results : np.array shape (n+1, 2), where n=len(data) contains the results of the filter, where results[i,0] is x , and results[i,1] is dx (derivative of x) First entry is the initial values of x and dx as set by __init__. predictions : np.array shape(n), or None the predictions for each step in the filter. Only returned if save_predictions == True
f691:c2:m2
def VRF_prediction(self):
g = self.g<EOL>h = self.h<EOL>k = self.k<EOL>gh2 = <NUM_LIT:2>*g + h<EOL>return ((g*k*(gh2-<NUM_LIT:4>)+ h*(g*gh2+<NUM_LIT:2>*h)) /<EOL>(<NUM_LIT:2>*k - (g*(h+k)*(gh2-<NUM_LIT:4>))))<EOL>
Returns the Variance Reduction Factor for x of the prediction step of the filter. This implements the equation .. math:: VRF(\hat{x}_{n+1,n}) = \\frac{VAR(\hat{x}_{n+1,n})}{\sigma^2_x} References ---------- Asquith and Woods, "Total Error Minimization in First and Second Order Prediction Filters" Report No RE-TR-70-17, U.S. Army Missle Command. Redstone Arsenal, Al. November 24, 1970.
f691:c2:m3
def bias_error(self, dddx):
return -self.dt**<NUM_LIT:3> * dddx / (<NUM_LIT:2>*self.k)<EOL>
Returns the bias error given the specified constant jerk(dddx) Parameters ---------- dddx : type(self.x) 3rd derivative (jerk) of the state variable x. References ---------- Asquith and Woods, "Total Error Minimization in First and Second Order Prediction Filters" Report No RE-TR-70-17, U.S. Army Missle Command. Redstone Arsenal, Al. November 24, 1970.
f691:c2:m4
def VRF(self):
g = self.g<EOL>h = self.h<EOL>k = self.k<EOL>hg4 = <NUM_LIT:4>- <NUM_LIT:2>*g - h<EOL>ghk = g*h + g*k - <NUM_LIT:2>*k<EOL>vx = (<NUM_LIT:2>*h*(<NUM_LIT:2>*(g**<NUM_LIT:2>) + <NUM_LIT:2>*h - <NUM_LIT:3>*g*h) - <NUM_LIT:2>*g*k*hg4) / (<NUM_LIT:2>*k - g*(h+k) * hg4)<EOL>vdx = (<NUM_LIT:2>*(h**<NUM_LIT:3>) - <NUM_LIT:4>*(h**<NUM_LIT:2>)*k + <NUM_LIT:4>*(k**<NUM_LIT:2>)*(<NUM_LIT:2>-g)) / (<NUM_LIT:2>*hg4*ghk)<EOL>vddx = <NUM_LIT:8>*h*(k**<NUM_LIT:2>) / ((self.dt**<NUM_LIT:4>)*hg4*ghk)<EOL>return (vx, vdx, vddx)<EOL>
Returns the Variance Reduction Factor (VRF) of the state variable of the filter (x) and its derivatives (dx, ddx). The VRF is the normalized variance for the filter, as given in the equations below. .. math:: VRF(\hat{x}_{n,n}) = \\frac{VAR(\hat{x}_{n,n})}{\sigma^2_x} VRF(\hat{\dot{x}}_{n,n}) = \\frac{VAR(\hat{\dot{x}}_{n,n})}{\sigma^2_x} VRF(\hat{\ddot{x}}_{n,n}) = \\frac{VAR(\hat{\ddot{x}}_{n,n})}{\sigma^2_x} Returns ------- vrf_x : type(x) VRF of x state variable vrf_dx : type(x) VRF of the dx state variable (derivative of x) vrf_ddx : type(x) VRF of the ddx state variable (second derivative of x)
f691:c2:m5
def __init__(self, dt, order, noise_variance=<NUM_LIT:0.>):
assert order >= <NUM_LIT:0><EOL>assert order <= <NUM_LIT:2><EOL>self.reset()<EOL>self.dt = dt<EOL>self.dt2 = dt**<NUM_LIT:2><EOL>self.sigma = noise_variance<EOL>self._order = order<EOL>
Least Squares filter of order 0 to 2. Parameters ---------- dt : float time step per update order : int order of filter 0..2 noise_variance : float variance in x. This allows us to calculate the error of the filter, it does not influence the filter output.
f692:c1:m0
def reset(self):
self.n = <NUM_LIT:0> <EOL>self.x = <NUM_LIT:0.><EOL>self.error = <NUM_LIT:0.><EOL>self.derror = <NUM_LIT:0.><EOL>self.dderror = <NUM_LIT:0.><EOL>self.dx = <NUM_LIT:0.><EOL>self.ddx = <NUM_LIT:0.><EOL>self.K1 = <NUM_LIT:0><EOL>self.K2 = <NUM_LIT:0><EOL>self.K3 = <NUM_LIT:0><EOL>
reset filter back to state at time of construction
f692:c1:m1
def reset(self):
self.n = <NUM_LIT:0> <EOL>self.x = np.zeros(self._order + <NUM_LIT:1>)<EOL>self.K = np.zeros(self._order + <NUM_LIT:1>)<EOL>self.y = <NUM_LIT:0><EOL>
reset filter back to state at time of construction
f694:c0:m1
def update(self, z):
self.n += <NUM_LIT:1><EOL>n = self.n<EOL>dt = self.dt<EOL>x = self.x<EOL>K = self.K<EOL>y = self.y<EOL>if self._order == <NUM_LIT:0>:<EOL><INDENT>K[<NUM_LIT:0>] = <NUM_LIT:1.> / n<EOL>y = z - x<EOL>x[<NUM_LIT:0>] += K[<NUM_LIT:0>] * y<EOL><DEDENT>elif self._order == <NUM_LIT:1>:<EOL><INDENT>K[<NUM_LIT:0>] = <NUM_LIT> * (<NUM_LIT:2>*n - <NUM_LIT:1>) / (n*(n + <NUM_LIT:1>))<EOL>K[<NUM_LIT:1>] = <NUM_LIT> / (n*(n + <NUM_LIT:1>)*dt)<EOL>y = z - x[<NUM_LIT:0>] - (dt * x[<NUM_LIT:1>])<EOL>x[<NUM_LIT:0>] += (K[<NUM_LIT:0>] * y) + (dt * x[<NUM_LIT:1>])<EOL>x[<NUM_LIT:1>] += (K[<NUM_LIT:1>] * y)<EOL><DEDENT>else:<EOL><INDENT>den = n * (n+<NUM_LIT:1>) * (n+<NUM_LIT:2>)<EOL>K[<NUM_LIT:0>] = <NUM_LIT> * (<NUM_LIT:3>*n**<NUM_LIT:2> - <NUM_LIT:3>*n + <NUM_LIT:2>) / den<EOL>K[<NUM_LIT:1>] = <NUM_LIT> * (<NUM_LIT:2>*n-<NUM_LIT:1>) / (den*dt)<EOL>K[<NUM_LIT:2>] = <NUM_LIT> / (den*dt**<NUM_LIT:2>)<EOL>y = z - x[<NUM_LIT:0>] - (dt * x[<NUM_LIT:1>]) - (<NUM_LIT:0.5> * dt**<NUM_LIT:2> * x[<NUM_LIT:2>])<EOL>x[<NUM_LIT:0>] += (K[<NUM_LIT:0>] * y) + (x[<NUM_LIT:1>] * dt) + (<NUM_LIT> * dt**<NUM_LIT:2> * x[<NUM_LIT:2>])<EOL>x[<NUM_LIT:1>] += (K[<NUM_LIT:1>] * y) + (x[<NUM_LIT:2>] * dt)<EOL>x[<NUM_LIT:2>] += (K[<NUM_LIT:2>] * y)<EOL><DEDENT>return self.x<EOL>
Update filter with new measurement `z` Returns ------- x : np.array estimate for this time step (same as self.x)
f694:c0:m2
def errors(self):
n = self.n<EOL>dt = self.dt<EOL>order = self._order<EOL>sigma = self.sigma<EOL>error = np.zeros(order + <NUM_LIT:1>)<EOL>std = np.zeros(order + <NUM_LIT:1>)<EOL>if n == <NUM_LIT:0>:<EOL><INDENT>return (error, std)<EOL><DEDENT>if order == <NUM_LIT:0>:<EOL><INDENT>error[<NUM_LIT:0>] = sigma/sqrt(n)<EOL>std[<NUM_LIT:0>] = sigma/sqrt(n)<EOL><DEDENT>elif order == <NUM_LIT:1>:<EOL><INDENT>if n > <NUM_LIT:1>:<EOL><INDENT>error[<NUM_LIT:0>] = sigma * sqrt(<NUM_LIT:2>*(<NUM_LIT:2>*n-<NUM_LIT:1>) / (n*(n+<NUM_LIT:1>)))<EOL>error[<NUM_LIT:1>] = sigma * sqrt(<NUM_LIT> / (n*(n*n-<NUM_LIT:1>)*dt*dt))<EOL><DEDENT>std[<NUM_LIT:0>] = sigma * sqrt((<NUM_LIT:2>*(<NUM_LIT:2>*n-<NUM_LIT:1>)) / (n*(n+<NUM_LIT:1>)))<EOL>std[<NUM_LIT:1>] = (sigma/dt) * sqrt(<NUM_LIT> / (n*(n*n-<NUM_LIT:1>)))<EOL><DEDENT>elif order == <NUM_LIT:2>:<EOL><INDENT>dt2 = dt * dt<EOL>if n >= <NUM_LIT:3>:<EOL><INDENT>error[<NUM_LIT:0>] = sigma * sqrt(<NUM_LIT:3>*(<NUM_LIT:3>*n*n-<NUM_LIT:3>*n+<NUM_LIT:2>) / (n*(n+<NUM_LIT:1>)*(n+<NUM_LIT:2>)))<EOL>error[<NUM_LIT:1>] = sigma * sqrt(<NUM_LIT:12>*(<NUM_LIT:16>*n*n-<NUM_LIT:30>*n+<NUM_LIT:11>) /<EOL>(n*(n*n-<NUM_LIT:1>)*(n*n-<NUM_LIT:4>)*dt2))<EOL>error[<NUM_LIT:2>] = sigma * sqrt(<NUM_LIT>/(n*(n*n-<NUM_LIT:1>)*(n*n-<NUM_LIT:4>)*dt2*dt2))<EOL><DEDENT>std[<NUM_LIT:0>] = sigma * sqrt((<NUM_LIT:3>*(<NUM_LIT:3>*n*n - <NUM_LIT:3>*n + <NUM_LIT:2>)) / (n*(n+<NUM_LIT:1>)*(n+<NUM_LIT:2>)))<EOL>std[<NUM_LIT:1>] = (sigma/dt) * sqrt((<NUM_LIT:12>*(<NUM_LIT:16>*n*n - <NUM_LIT:30>*n + <NUM_LIT:11>)) /<EOL>(n*(n*n - <NUM_LIT:1>)*(n*n - <NUM_LIT:4>)))<EOL>std[<NUM_LIT:2>] = (sigma/dt2) * sqrt(<NUM_LIT> / (n*(n*n-<NUM_LIT:1>)*(n*n-<NUM_LIT:4>)))<EOL><DEDENT>return error, std<EOL>
Computes and returns the error and standard deviation of the filter at this time step. Returns ------- error : np.array size 1xorder+1 std : np.array size 1xorder+1
f694:c0:m3
def get_radar(dt):
if not hasattr(get_radar, "<STR_LIT>"):<EOL><INDENT>get_radar.posp = <NUM_LIT:0><EOL><DEDENT>vel = <NUM_LIT:100> + <NUM_LIT> * randn()<EOL>alt = <NUM_LIT:1000> + <NUM_LIT:10> * randn()<EOL>pos = get_radar.posp + vel*dt<EOL>v = <NUM_LIT:0> + pos* <NUM_LIT>*randn()<EOL>slant_range = math.sqrt(pos**<NUM_LIT:2> + alt**<NUM_LIT:2>) + v<EOL>get_radar.posp = pos<EOL>return slant_range<EOL>
Simulate radar range to object at 1K altidue and moving at 100m/s. Adds about 5% measurement noise. Returns slant range to the object. Call once for each new measurement at dt time from last call.
f695:m0
def fx(x, dt):
F = np.array([[<NUM_LIT:1.>, dt, <NUM_LIT:0.>],<EOL>[<NUM_LIT:0.>, <NUM_LIT:1.>, <NUM_LIT:0.>],<EOL>[<NUM_LIT:0.>, <NUM_LIT:0.>, <NUM_LIT:1.>]])<EOL>return np.dot(F, x)<EOL>
state transition function for sstate [downrange, vel, altitude]
f697:m0
def hx(x):
return (x[<NUM_LIT:0>]**<NUM_LIT:2> + x[<NUM_LIT:2>]**<NUM_LIT:2>)**<NUM_LIT><EOL>
returns slant range based on downrange distance and altitude
f697:m1
def get_range(self, process_err_pct=<NUM_LIT>):
vel = self.vel + <NUM_LIT:5> * randn()<EOL>alt = self.alt + <NUM_LIT:10> * randn()<EOL>self.pos += vel*self.dt<EOL>err = (self.pos * process_err_pct) * randn()<EOL>slant_range = (self.pos**<NUM_LIT:2> + alt**<NUM_LIT:2>)**<NUM_LIT> + err<EOL>return slant_range<EOL>
Returns slant range to the object. Call once for each new measurement at dt time from last call.
f698:c0:m1
def fx(x,dt):
<EOL>return array([x[<NUM_LIT:0>]+x[<NUM_LIT:1>], x[<NUM_LIT:1>]])<EOL>
state transition function
f699:m0
def hx(x):
return math.atan2(platform_pos[<NUM_LIT:1>],x[<NUM_LIT:0>]-platform_pos[<NUM_LIT:0>])<EOL>
measurement function - convert position to bearing
f699:m1
def mahalanobis(x, mean, cov):
x = _validate_vector(x)<EOL>mean = _validate_vector(mean)<EOL>if x.shape != mean.shape:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>y = x - mean<EOL>S = np.atleast_2d(cov)<EOL>dist = float(np.dot(np.dot(y.T, inv(S)), y))<EOL>return math.sqrt(dist)<EOL>
Computes the Mahalanobis distance between the state vector x from the Gaussian `mean` with covariance `cov`. This can be thought as the number of standard deviations x is from the mean, i.e. a return value of 3 means x is 3 std from mean. Parameters ---------- x : (N,) array_like, or float Input state vector mean : (N,) array_like, or float mean of multivariate Gaussian cov : (N, N) array_like or float covariance of the multivariate Gaussian Returns ------- mahalanobis : double The Mahalanobis distance between vectors `x` and `mean` Examples -------- >>> mahalanobis(x=3., mean=3.5, cov=4.**2) # univariate case 0.125 >>> mahalanobis(x=3., mean=6, cov=1) # univariate, 3 std away 3.0 >>> mahalanobis([1., 2], [1.1, 3.5], [[1., .1],[.1, 13]]) 0.42533327058913922
f702:m1
def log_likelihood(z, x, P, H, R):
S = np.dot(H, np.dot(P, H.T)) + R<EOL>return logpdf(z, np.dot(H, x), S)<EOL>
Returns log-likelihood of the measurement z given the Gaussian posterior (x, P) using measurement function H and measurement covariance error R
f702:m2
def likelihood(z, x, P, H, R):
return np.exp(log_likelihood(z, x, P, H, R))<EOL>
Returns likelihood of the measurement z given the Gaussian posterior (x, P) using measurement function H and measurement covariance error R
f702:m3
def logpdf(x, mean=None, cov=<NUM_LIT:1>, allow_singular=True):
if mean is not None:<EOL><INDENT>flat_mean = np.asarray(mean).flatten()<EOL><DEDENT>else:<EOL><INDENT>flat_mean = None<EOL><DEDENT>flat_x = np.asarray(x).flatten()<EOL>if _support_singular:<EOL><INDENT>return multivariate_normal.logpdf(flat_x, flat_mean, cov, allow_singular)<EOL><DEDENT>return multivariate_normal.logpdf(flat_x, flat_mean, cov)<EOL>
Computes the log of the probability density function of the normal N(mean, cov) for the data x. The normal may be univariate or multivariate. Wrapper for older versions of scipy.multivariate_normal.logpdf which don't support support the allow_singular keyword prior to verion 0.15.0. If it is not supported, and cov is singular or not PSD you may get an exception. `x` and `mean` may be column vectors, row vectors, or lists.
f702:m4
def gaussian(x, mean, var, normed=True):
g = ((<NUM_LIT:2>*math.pi*var)**-<NUM_LIT>) * np.exp((-<NUM_LIT:0.5>*(np.asarray(x)-mean)**<NUM_LIT>) / var)<EOL>if normed and len(np.shape(g)) > <NUM_LIT:0>:<EOL><INDENT>g = g / sum(g)<EOL><DEDENT>return g<EOL>
returns normal distribution (pdf) for x given a Gaussian with the specified mean and variance. All must be scalars. gaussian (1,2,3) is equivalent to scipy.stats.norm(2,math.sqrt(3)).pdf(1) It is quite a bit faster albeit much less flexible than the latter. Parameters ---------- x : scalar or array-like The value for which we compute the probability mean : scalar Mean of the Gaussian var : scalar Variance of the Gaussian norm : bool, default True Normalize the output if the input is an array of values. Returns ------- probability : float probability of x for the Gaussian (mean, var). E.g. 0.101 denotes 10.1%. Examples -------- >>> gaussian(8, 1, 2) 1.3498566943461957e-06 >>> gaussian([8, 7, 9], 1, 2) array([1.34985669e-06, 3.48132630e-05, 3.17455867e-08])
f702:m5
def mul(mean1, var1, mean2, var2):
mean = (var1*mean2 + var2*mean1) / (var1 + var2)<EOL>var = <NUM_LIT:1> / (<NUM_LIT:1>/var1 + <NUM_LIT:1>/var2)<EOL>return (mean, var)<EOL>
Multiply Gaussian (mean1, var1) with (mean2, var2) and return the results as a tuple (mean, var). Strictly speaking the product of two Gaussian PDFs is a Gaussian function, not Gaussian PDF. It is, however, proportional to a Gaussian PDF, so it is safe to treat the output as a PDF for any filter using Bayes equation, which normalizes the result anyway. Parameters ---------- mean1 : scalar mean of first Gaussian var1 : scalar variance of first Gaussian mean2 : scalar mean of second Gaussian var2 : scalar variance of second Gaussian Returns ------- mean : scalar mean of product var : scalar variance of product Examples -------- >>> mul(1, 2, 3, 4) (1.6666666666666667, 1.3333333333333333) References ---------- Bromily. "Products and Convolutions of Gaussian Probability Functions", Tina Memo No. 2003-003. http://www.tina-vision.net/docs/memos/2003-003.pdf
f702:m6
def mul_pdf(mean1, var1, mean2, var2):
mean = (var1*mean2 + var2*mean1) / (var1 + var2)<EOL>var = <NUM_LIT:1.> / (<NUM_LIT:1.>/var1 + <NUM_LIT:1.>/var2)<EOL>S = math.exp(-(mean1 - mean2)**<NUM_LIT:2> / (<NUM_LIT:2>*(var1 + var2))) /math.sqrt(<NUM_LIT:2> * math.pi * (var1 + var2))<EOL>return mean, var, S<EOL>
Multiply Gaussian (mean1, var1) with (mean2, var2) and return the results as a tuple (mean, var, scale_factor). Strictly speaking the product of two Gaussian PDFs is a Gaussian function, not Gaussian PDF. It is, however, proportional to a Gaussian PDF. `scale_factor` provides this proportionality constant Parameters ---------- mean1 : scalar mean of first Gaussian var1 : scalar variance of first Gaussian mean2 : scalar mean of second Gaussian var2 : scalar variance of second Gaussian Returns ------- mean : scalar mean of product var : scalar variance of product scale_factor : scalar proportionality constant Examples -------- >>> mul(1, 2, 3, 4) (1.6666666666666667, 1.3333333333333333) References ---------- Bromily. "Products and Convolutions of Gaussian Probability Functions", Tina Memo No. 2003-003. http://www.tina-vision.net/docs/memos/2003-003.pdf
f702:m7
def add(mean1, var1, mean2, var2):
return (mean1+mean2, var1+var2)<EOL>
Add the Gaussians (mean1, var1) with (mean2, var2) and return the results as a tuple (mean,var). var1 and var2 are variances - sigma squared in the usual parlance.
f702:m8
def multivariate_gaussian(x, mu, cov):
warnings.warn(<EOL>("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"), DeprecationWarning)<EOL>x = np.array(x, copy=False, ndmin=<NUM_LIT:1>).flatten()<EOL>mu = np.array(mu, copy=False, ndmin=<NUM_LIT:1>).flatten()<EOL>nx = len(mu)<EOL>cov = _to_cov(cov, nx)<EOL>norm_coeff = nx*math.log(<NUM_LIT:2>*math.pi) + np.linalg.slogdet(cov)[<NUM_LIT:1>]<EOL>err = x - mu<EOL>if sp.issparse(cov):<EOL><INDENT>numerator = spln.spsolve(cov, err).T.dot(err)<EOL><DEDENT>else:<EOL><INDENT>numerator = np.linalg.solve(cov, err).T.dot(err)<EOL><DEDENT>return math.exp(-<NUM_LIT:0.5>*(norm_coeff + numerator))<EOL>
This is designed to replace scipy.stats.multivariate_normal which is not available before version 0.14. You may either pass in a multivariate set of data: .. code-block:: Python multivariate_gaussian (array([1,1]), array([3,4]), eye(2)*1.4) multivariate_gaussian (array([1,1,1]), array([3,4,5]), 1.4) or unidimensional data: .. code-block:: Python multivariate_gaussian(1, 3, 1.4) In the multivariate case if cov is a scalar it is interpreted as eye(n)*cov The function gaussian() implements the 1D (univariate)case, and is much faster than this function. equivalent calls: .. code-block:: Python multivariate_gaussian(1, 2, 3) scipy.stats.multivariate_normal(2,3).pdf(1) Parameters ---------- x : float, or np.array-like Value to compute the probability for. May be a scalar if univariate, or any type that can be converted to an np.array (list, tuple, etc). np.array is best for speed. mu : float, or np.array-like mean for the Gaussian . May be a scalar if univariate, or any type that can be converted to an np.array (list, tuple, etc).np.array is best for speed. cov : float, or np.array-like Covariance for the Gaussian . May be a scalar if univariate, or any type that can be converted to an np.array (list, tuple, etc).np.array is best for speed. Returns ------- probability : float probability for x for the Gaussian (mu,cov)
f702:m9
def multivariate_multiply(m1, c1, m2, c2):
C1 = np.asarray(c1)<EOL>C2 = np.asarray(c2)<EOL>M1 = np.asarray(m1)<EOL>M2 = np.asarray(m2)<EOL>sum_inv = np.linalg.inv(C1+C2)<EOL>C3 = np.dot(C1, sum_inv).dot(C2)<EOL>M3 = (np.dot(C2, sum_inv).dot(M1) +<EOL>np.dot(C1, sum_inv).dot(M2))<EOL>return M3, C3<EOL>
Multiplies the two multivariate Gaussians together and returns the results as the tuple (mean, covariance). Examples -------- .. code-block:: Python m, c = multivariate_multiply([7.0, 2], [[1.0, 2.0], [2.0, 1.0]], [3.2, 0], [[8.0, 1.1], [1.1,8.0]]) Parameters ---------- m1 : array-like Mean of first Gaussian. Must be convertable to an 1D array via numpy.asarray(), For example 6, [6], [6, 5], np.array([3, 4, 5, 6]) are all valid. c1 : matrix-like Covariance of first Gaussian. Must be convertable to an 2D array via numpy.asarray(). m2 : array-like Mean of second Gaussian. Must be convertable to an 1D array via numpy.asarray(), For example 6, [6], [6, 5], np.array([3, 4, 5, 6]) are all valid. c2 : matrix-like Covariance of second Gaussian. Must be convertable to an 2D array via numpy.asarray(). Returns ------- m : ndarray mean of the result c : ndarray covariance of the result
f702:m10
def plot_discrete_cdf(xs, ys, ax=None, xlabel=None, ylabel=None,<EOL>label=None):
import matplotlib.pyplot as plt<EOL>if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>if xs is None:<EOL><INDENT>xs = range(len(ys))<EOL><DEDENT>ys = np.cumsum(ys)<EOL>ax.plot(xs, ys, label=label)<EOL>ax.set_xlabel(xlabel)<EOL>ax.set_ylabel(ylabel)<EOL>return ax<EOL>
Plots a normal distribution CDF with the given mean and variance. x-axis contains the mean, the y-axis shows the cumulative probability. Parameters ---------- xs : list-like of scalars x values corresponding to the values in `y`s. Can be `None`, in which case range(len(ys)) will be used. ys : list-like of scalars list of probabilities to be plotted which should sum to 1. ax : matplotlib axes object, optional If provided, the axes to draw on, otherwise plt.gca() is used. xlim, ylim: (float,float), optional specify the limits for the x or y axis as tuple (low,high). If not specified, limits will be automatically chosen to be 'nice' xlabel : str,optional label for the x-axis ylabel : str, optional label for the y-axis label : str, optional label for the legend Returns ------- axis of plot
f702:m11
def plot_gaussian_cdf(mean=<NUM_LIT:0.>, variance=<NUM_LIT:1.>,<EOL>ax=None,<EOL>xlim=None, ylim=(<NUM_LIT:0.>, <NUM_LIT:1.>),<EOL>xlabel=None, ylabel=None,<EOL>label=None):
import matplotlib.pyplot as plt<EOL>if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>sigma = math.sqrt(variance)<EOL>n = norm(mean, sigma)<EOL>if xlim is None:<EOL><INDENT>xlim = [n.ppf(<NUM_LIT>), n.ppf(<NUM_LIT>)]<EOL><DEDENT>xs = np.arange(xlim[<NUM_LIT:0>], xlim[<NUM_LIT:1>], (xlim[<NUM_LIT:1>] - xlim[<NUM_LIT:0>]) / <NUM_LIT>)<EOL>cdf = n.cdf(xs)<EOL>ax.plot(xs, cdf, label=label)<EOL>ax.set_xlim(xlim)<EOL>ax.set_ylim(ylim)<EOL>ax.set_xlabel(xlabel)<EOL>ax.set_ylabel(ylabel)<EOL>return ax<EOL>
Plots a normal distribution CDF with the given mean and variance. x-axis contains the mean, the y-axis shows the cumulative probability. Parameters ---------- mean : scalar, default 0. mean for the normal distribution. variance : scalar, default 0. variance for the normal distribution. ax : matplotlib axes object, optional If provided, the axes to draw on, otherwise plt.gca() is used. xlim, ylim: (float,float), optional specify the limits for the x or y axis as tuple (low,high). If not specified, limits will be automatically chosen to be 'nice' xlabel : str,optional label for the x-axis ylabel : str, optional label for the y-axis label : str, optional label for the legend Returns ------- axis of plot
f702:m12
def plot_gaussian_pdf(mean=<NUM_LIT:0.>,<EOL>variance=<NUM_LIT:1.>,<EOL>std=None,<EOL>ax=None,<EOL>mean_line=False,<EOL>xlim=None, ylim=None,<EOL>xlabel=None, ylabel=None,<EOL>label=None):
import matplotlib.pyplot as plt<EOL>if ax is None:<EOL><INDENT>ax = plt.gca()<EOL><DEDENT>if variance is not None and std is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if variance is None and std is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if variance is not None:<EOL><INDENT>std = math.sqrt(variance)<EOL><DEDENT>n = norm(mean, std)<EOL>if xlim is None:<EOL><INDENT>xlim = [n.ppf(<NUM_LIT>), n.ppf(<NUM_LIT>)]<EOL><DEDENT>xs = np.arange(xlim[<NUM_LIT:0>], xlim[<NUM_LIT:1>], (xlim[<NUM_LIT:1>] - xlim[<NUM_LIT:0>]) / <NUM_LIT>)<EOL>ax.plot(xs, n.pdf(xs), label=label)<EOL>ax.set_xlim(xlim)<EOL>if ylim is not None:<EOL><INDENT>ax.set_ylim(ylim)<EOL><DEDENT>if mean_line:<EOL><INDENT>plt.axvline(mean)<EOL><DEDENT>if xlabel is not None:<EOL><INDENT>ax.set_xlabel(xlabel)<EOL><DEDENT>if ylabel is not None:<EOL><INDENT>ax.set_ylabel(ylabel)<EOL><DEDENT>return ax<EOL>
Plots a normal distribution PDF with the given mean and variance. x-axis contains the mean, the y-axis shows the probability density. Parameters ---------- mean : scalar, default 0. mean for the normal distribution. variance : scalar, default 1., optional variance for the normal distribution. std: scalar, default=None, optional standard deviation of the normal distribution. Use instead of `variance` if desired ax : matplotlib axes object, optional If provided, the axes to draw on, otherwise plt.gca() is used. mean_line : boolean draws a line at x=mean xlim, ylim: (float,float), optional specify the limits for the x or y axis as tuple (low,high). If not specified, limits will be automatically chosen to be 'nice' xlabel : str,optional label for the x-axis ylabel : str, optional label for the y-axis label : str, optional label for the legend Returns ------- axis of plot
f702:m13
def plot_gaussian(mean=<NUM_LIT:0.>, variance=<NUM_LIT:1.>,<EOL>ax=None,<EOL>mean_line=False,<EOL>xlim=None,<EOL>ylim=None,<EOL>xlabel=None,<EOL>ylabel=None,<EOL>label=None):
warnings.warn('<STR_LIT>''<STR_LIT>''<STR_LIT>',<EOL>DeprecationWarning)<EOL>return plot_gaussian_pdf(mean, variance, ax, mean_line, xlim, ylim, xlabel,<EOL>ylabel, label)<EOL>
DEPRECATED. Use plot_gaussian_pdf() instead. This is poorly named, as there are multiple ways to plot a Gaussian.
f702:m14
def covariance_ellipse(P, deviations=<NUM_LIT:1>):
U, s, _ = linalg.svd(P)<EOL>orientation = math.atan2(U[<NUM_LIT:1>, <NUM_LIT:0>], U[<NUM_LIT:0>, <NUM_LIT:0>])<EOL>width = deviations * math.sqrt(s[<NUM_LIT:0>])<EOL>height = deviations * math.sqrt(s[<NUM_LIT:1>])<EOL>if height > width:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return (orientation, width, height)<EOL>
Returns a tuple defining the ellipse representing the 2 dimensional covariance matrix P. Parameters ---------- P : nd.array shape (2,2) covariance matrix deviations : int (optional, default = 1) # of standard deviations. Default is 1. Returns (angle_radians, width_radius, height_radius)
f702:m15
def _eigsorted(cov, asc=True):
eigval, eigvec = np.linalg.eigh(cov)<EOL>order = eigval.argsort()<EOL>if not asc:<EOL><INDENT>order = order[::-<NUM_LIT:1>]<EOL><DEDENT>return eigval[order], eigvec[:, order]<EOL>
Computes eigenvalues and eigenvectors of a covariance matrix and returns them sorted by eigenvalue. Parameters ---------- cov : ndarray covariance matrix asc : bool, default=True determines whether we are sorted smallest to largest (asc=True), or largest to smallest (asc=False) Returns ------- eigval : 1D ndarray eigenvalues of covariance ordered largest to smallest eigvec : 2D ndarray eigenvectors of covariance matrix ordered to match `eigval` ordering. I.e eigvec[:, 0] is the rotation vector for eigval[0]
f702:m16
def plot_3d_covariance(mean, cov, std=<NUM_LIT:1.>,<EOL>ax=None, title=None,<EOL>color=None, alpha=<NUM_LIT:1.>,<EOL>label_xyz=True,<EOL>N=<NUM_LIT>,<EOL>shade=True,<EOL>limit_xyz=True,<EOL>**kwargs):
from mpl_toolkits.mplot3d import Axes3D<EOL>import matplotlib.pyplot as plt<EOL>mean = np.atleast_2d(mean)<EOL>if mean.shape[<NUM_LIT:1>] == <NUM_LIT:1>:<EOL><INDENT>mean = mean.T<EOL><DEDENT>if not(mean.shape[<NUM_LIT:0>] == <NUM_LIT:1> and mean.shape[<NUM_LIT:1>] == <NUM_LIT:3>):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>mean = mean[<NUM_LIT:0>]<EOL>cov = np.asarray(cov)<EOL>if cov.shape[<NUM_LIT:0>] != <NUM_LIT:3> or cov.shape[<NUM_LIT:1>] != <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>eigval, eigvec = _eigsorted(cov, asc=True)<EOL>radii = std * np.sqrt(np.real(eigval))<EOL>if eigval[<NUM_LIT:0>] < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>u = np.linspace(<NUM_LIT:0.0>, <NUM_LIT> * np.pi, N)<EOL>v = np.linspace(<NUM_LIT:0.0>, np.pi, N)<EOL>x = np.outer(np.cos(u), np.sin(v)) * radii[<NUM_LIT:0>]<EOL>y = np.outer(np.sin(u), np.sin(v)) * radii[<NUM_LIT:1>]<EOL>z = np.outer(np.ones_like(u), np.cos(v)) * radii[<NUM_LIT:2>]<EOL>a = np.kron(eigvec[:, <NUM_LIT:0>], x)<EOL>b = np.kron(eigvec[:, <NUM_LIT:1>], y)<EOL>c = np.kron(eigvec[:, <NUM_LIT:2>], z)<EOL>data = a + b + c<EOL>N = data.shape[<NUM_LIT:0>]<EOL>x = data[:, <NUM_LIT:0>:N] + mean[<NUM_LIT:0>]<EOL>y = data[:, N:N*<NUM_LIT:2>] + mean[<NUM_LIT:1>]<EOL>z = data[:, N*<NUM_LIT:2>:] + mean[<NUM_LIT:2>]<EOL>fig = plt.gcf()<EOL>if ax is None:<EOL><INDENT>ax = fig.add_subplot(<NUM_LIT>, projection='<STR_LIT>')<EOL><DEDENT>ax.plot_surface(x, y, z,<EOL>rstride=<NUM_LIT:3>, cstride=<NUM_LIT:3>, linewidth=<NUM_LIT:0.1>, alpha=alpha,<EOL>shade=shade, color=color, **kwargs)<EOL>if label_xyz:<EOL><INDENT>ax.set_xlabel('<STR_LIT:X>')<EOL>ax.set_ylabel('<STR_LIT:Y>')<EOL>ax.set_zlabel('<STR_LIT>')<EOL><DEDENT>if limit_xyz:<EOL><INDENT>r = radii.max()<EOL>ax.set_xlim(-r + mean[<NUM_LIT:0>], r + mean[<NUM_LIT:0>])<EOL>ax.set_ylim(-r + mean[<NUM_LIT:1>], r + mean[<NUM_LIT:1>])<EOL>ax.set_zlim(-r + mean[<NUM_LIT:2>], r + mean[<NUM_LIT:2>])<EOL><DEDENT>if title is not None:<EOL><INDENT>plt.title(title)<EOL><DEDENT>Axes3D <EOL>return ax<EOL>
Plots a covariance matrix `cov` as a 3D ellipsoid centered around the `mean`. Parameters ---------- mean : 3-vector mean in x, y, z. Can be any type convertable to a row vector. cov : ndarray 3x3 covariance matrix std : double, default=1 standard deviation of ellipsoid ax : matplotlib.axes._subplots.Axes3DSubplot, optional Axis to draw on. If not provided, a new 3d axis will be generated for the current figure title : str, optional If provided, specifies the title for the plot color : any value convertible to a color if specified, color of the ellipsoid. alpha : float, default 1. Alpha value of the ellipsoid. <1 makes is semi-transparent. label_xyz: bool, default True Gives labels 'X', 'Y', and 'Z' to the axis. N : int, default=60 Number of segments to compute ellipsoid in u,v space. Large numbers can take a very long time to plot. Default looks nice. shade : bool, default=True Use shading to draw the ellipse limit_xyz : bool, default=True Limit the axis range to fit the ellipse **kwargs : optional keyword arguments to supply to the call to plot_surface()
f702:m17
def plot_covariance_ellipse(<EOL>mean, cov=None, variance=<NUM_LIT:1.0>, std=None,<EOL>ellipse=None, title=None, axis_equal=True, show_semiaxis=False,<EOL>facecolor=None, edgecolor=None,<EOL>fc='<STR_LIT:none>', ec='<STR_LIT>',<EOL>alpha=<NUM_LIT:1.0>, xlim=None, ylim=None,<EOL>ls='<STR_LIT>'):
warnings.warn("<STR_LIT>", DeprecationWarning)<EOL>plot_covariance(mean=mean, cov=cov, variance=variance, std=std,<EOL>ellipse=ellipse, title=title, axis_equal=axis_equal,<EOL>show_semiaxis=show_semiaxis, facecolor=facecolor,<EOL>edgecolor=edgecolor, fc=fc, ec=ec, alpha=alpha,<EOL>xlim=xlim, ylim=ylim, ls=ls)<EOL>
Deprecated function to plot a covariance ellipse. Use plot_covariance instead. See Also -------- plot_covariance
f702:m18
def _std_tuple_of(var=None, std=None, interval=None):
if std is not None:<EOL><INDENT>if np.isscalar(std):<EOL><INDENT>std = (std,)<EOL><DEDENT>return std<EOL><DEDENT>if interval is not None:<EOL><INDENT>if np.isscalar(interval):<EOL><INDENT>interval = (interval,)<EOL><DEDENT>return norm.interval(interval)[<NUM_LIT:1>]<EOL><DEDENT>if var is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if np.isscalar(var):<EOL><INDENT>var = (var,)<EOL><DEDENT>return np.sqrt(var)<EOL>
Convienence function for plotting. Given one of var, standard deviation, or interval, return the std. Any of the three can be an iterable list. Examples -------- >>>_std_tuple_of(var=[1, 3, 9]) (1, 2, 3)
f702:m19
def plot_covariance(<EOL>mean, cov=None, variance=<NUM_LIT:1.0>, std=None, interval=None,<EOL>ellipse=None, title=None, axis_equal=True,<EOL>show_semiaxis=False, show_center=True,<EOL>facecolor=None, edgecolor=None,<EOL>fc='<STR_LIT:none>', ec='<STR_LIT>',<EOL>alpha=<NUM_LIT:1.0>, xlim=None, ylim=None,<EOL>ls='<STR_LIT>'):
from matplotlib.patches import Ellipse<EOL>import matplotlib.pyplot as plt<EOL>if cov is not None and ellipse is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if cov is None and ellipse is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if facecolor is None:<EOL><INDENT>facecolor = fc<EOL><DEDENT>if edgecolor is None:<EOL><INDENT>edgecolor = ec<EOL><DEDENT>if cov is not None:<EOL><INDENT>ellipse = covariance_ellipse(cov)<EOL><DEDENT>if axis_equal:<EOL><INDENT>plt.axis('<STR_LIT>')<EOL><DEDENT>if title is not None:<EOL><INDENT>plt.title(title)<EOL><DEDENT>ax = plt.gca()<EOL>angle = np.degrees(ellipse[<NUM_LIT:0>])<EOL>width = ellipse[<NUM_LIT:1>] * <NUM_LIT><EOL>height = ellipse[<NUM_LIT:2>] * <NUM_LIT><EOL>std = _std_tuple_of(variance, std, interval)<EOL>for sd in std:<EOL><INDENT>e = Ellipse(xy=mean, width=sd*width, height=sd*height, angle=angle,<EOL>facecolor=facecolor,<EOL>edgecolor=edgecolor,<EOL>alpha=alpha,<EOL>lw=<NUM_LIT:2>, ls=ls)<EOL>ax.add_patch(e)<EOL><DEDENT>x, y = mean<EOL>if show_center:<EOL><INDENT>plt.scatter(x, y, marker='<STR_LIT:+>', color=edgecolor)<EOL><DEDENT>if xlim is not None:<EOL><INDENT>ax.set_xlim(xlim)<EOL><DEDENT>if ylim is not None:<EOL><INDENT>ax.set_ylim(ylim)<EOL><DEDENT>if show_semiaxis:<EOL><INDENT>a = ellipse[<NUM_LIT:0>]<EOL>h, w = height/<NUM_LIT:4>, width/<NUM_LIT:4><EOL>plt.plot([x, x+ h*cos(a+np.pi/<NUM_LIT:2>)], [y, y + h*sin(a+np.pi/<NUM_LIT:2>)])<EOL>plt.plot([x, x+ w*cos(a)], [y, y + w*sin(a)])<EOL><DEDENT>
Plots the covariance ellipse for the 2D normal defined by (mean, cov) `variance` is the normal sigma^2 that we want to plot. If list-like, ellipses for all ellipses will be ploted. E.g. [1,2] will plot the sigma^2 = 1 and sigma^2 = 2 ellipses. Alternatively, use std for the standard deviation, in which case `variance` will be ignored. ellipse is a (angle,width,height) tuple containing the angle in radians, and width and height radii. You may provide either cov or ellipse, but not both. Parameters ---------- mean : row vector like (2x1) The mean of the normal cov : ndarray-like 2x2 covariance matrix variance : float, default 1, or iterable float, optional Variance of the plotted ellipse. May specify std or interval instead. If iterable, such as (1, 2**2, 3**2), then ellipses will be drawn for all in the list. std : float, or iterable float, optional Standard deviation of the plotted ellipse. If specified, variance is ignored, and interval must be `None`. If iterable, such as (1, 2, 3), then ellipses will be drawn for all in the list. interval : float range [0,1), or iterable float, optional Confidence interval for the plotted ellipse. For example, .68 (for 68%) gives roughly 1 standand deviation. If specified, variance is ignored and `std` must be `None` If iterable, such as (.68, .95), then ellipses will be drawn for all in the list. ellipse: (float, float, float) Instead of a covariance, plots an ellipse described by (angle, width, height), where angle is in radians, and the width and height are the minor and major sub-axis radii. `cov` must be `None`. title: str, optional title for the plot axis_equal: bool, default=True Use the same scale for the x-axis and y-axis to ensure the aspect ratio is correct. show_semiaxis: bool, default=False Draw the semiaxis of the ellipse show_center: bool, default=True Mark the center of the ellipse with a cross facecolor, fc: color, default=None If specified, fills the ellipse with the specified color. `fc` is an allowed abbreviation edgecolor, ec: color, default=None If specified, overrides the default color sequence for the edge color of the ellipse. `ec` is an allowed abbreviation alpha: float range [0,1], default=1. alpha value for the ellipse xlim: float or (float,float), default=None specifies the limits for the x-axis ylim: float or (float,float), default=None specifies the limits for the y-axis ls: str, default='solid': line style for the edge of the ellipse
f702:m20
def norm_cdf(x_range, mu, var=<NUM_LIT:1>, std=None):
if std is None:<EOL><INDENT>std = math.sqrt(var)<EOL><DEDENT>return abs(norm.cdf(x_range[<NUM_LIT:0>], loc=mu, scale=std) -<EOL>norm.cdf(x_range[<NUM_LIT:1>], loc=mu, scale=std))<EOL>
Computes the probability that a Gaussian distribution lies within a range of values. Parameters ---------- x_range : (float, float) tuple of range to compute probability for mu : float mean of the Gaussian var : float, optional variance of the Gaussian. Ignored if `std` is provided std : float, optional standard deviation of the Gaussian. This overrides the `var` parameter Returns ------- probability : float probability that Gaussian is within x_range. E.g. .1 means 10%.
f702:m21
def _to_cov(x, n):
if np.isscalar(x):<EOL><INDENT>if x < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return np.eye(n) * x<EOL><DEDENT>x = np.atleast_2d(x)<EOL>try:<EOL><INDENT>np.linalg.cholesky(x)<EOL><DEDENT>except:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return x<EOL>
If x is a scalar, returns a covariance matrix generated from it as the identity matrix multiplied by x. The dimension will be nxn. If x is already a 2D numpy array then it is returned unchanged. Raises ValueError if not positive definite
f702:m22
def rand_student_t(df, mu=<NUM_LIT:0>, std=<NUM_LIT:1>):
x = random.gauss(<NUM_LIT:0>, std)<EOL>y = <NUM_LIT>*random.gammavariate(<NUM_LIT:0.5> * df, <NUM_LIT>)<EOL>return x / (math.sqrt(y / df)) + mu<EOL>
return random number distributed by student's t distribution with `df` degrees of freedom with the specified mean and standard deviation.
f702:m23
def NESS(xs, est_xs, ps):
est_err = xs - est_xs<EOL>ness = []<EOL>for x, p in zip(est_err, ps):<EOL><INDENT>ness.append(np.dot(x.T, linalg.inv(p)).dot(x))<EOL><DEDENT>return ness<EOL>
Computes the normalized estimated error squared test on a sequence of estimates. The estimates are optimal if the mean error is zero and the covariance matches the Kalman filter's covariance. If this holds, then the mean of the NESS should be equal to or less than the dimension of x. Examples -------- .. code-block: Python xs = ground_truth() est_xs, ps, _, _ = kf.batch_filter(zs) NESS(xs, est_xs, ps) Parameters ---------- xs : list-like sequence of true values for the state x est_xs : list-like sequence of estimates from an estimator (such as Kalman filter) ps : list-like sequence of covariance matrices from the estimator Returns ------- ness : list of floats list of NESS computed for each estimate
f702:m24
def update(self, z):
if self.order == <NUM_LIT:0>:<EOL><INDENT>G = <NUM_LIT:1> - self.beta<EOL>self.x = self.x + dot(G, (z - self.x))<EOL><DEDENT>elif self.order == <NUM_LIT:1>:<EOL><INDENT>G = <NUM_LIT:1> - self.beta**<NUM_LIT:2><EOL>H = (<NUM_LIT:1>-self.beta)**<NUM_LIT:2><EOL>x = self.x[<NUM_LIT:0>]<EOL>dx = self.x[<NUM_LIT:1>]<EOL>dxdt = dot(dx, self.dt)<EOL>residual = z - (x+dxdt)<EOL>self.x[<NUM_LIT:0>] = x + dxdt + G*residual<EOL>self.x[<NUM_LIT:1>] = dx + (H / self.dt)*residual<EOL><DEDENT>else: <EOL><INDENT>G = <NUM_LIT:1>-self.beta**<NUM_LIT:3><EOL>H = <NUM_LIT>*(<NUM_LIT:1>+self.beta)*(<NUM_LIT:1>-self.beta)**<NUM_LIT:2><EOL>K = <NUM_LIT:0.5>*(<NUM_LIT:1>-self.beta)**<NUM_LIT:3><EOL>x = self.x[<NUM_LIT:0>]<EOL>dx = self.x[<NUM_LIT:1>]<EOL>ddx = self.x[<NUM_LIT:2>]<EOL>dxdt = dot(dx, self.dt)<EOL>T2 = self.dt**<NUM_LIT><EOL>residual = z - (x + dxdt + <NUM_LIT:0.5>*ddx*T2)<EOL>self.x[<NUM_LIT:0>] = x + dxdt + <NUM_LIT:0.5>*ddx*T2 + G*residual<EOL>self.x[<NUM_LIT:1>] = dx + ddx*self.dt + (H/self.dt)*residual<EOL>self.x[<NUM_LIT:2>] = ddx + (<NUM_LIT:2>*K/(self.dt**<NUM_LIT:2>))*residual<EOL><DEDENT>
update the filter with measurement z. z must be the same type (or treatable as the same type) as self.x[0].
f706:c0:m2
def kinematic_state_transition(order, dt):
if not(order >= <NUM_LIT:0> and int(order) == order):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if order == <NUM_LIT:0>:<EOL><INDENT>return np.array([[<NUM_LIT:1.>]])<EOL><DEDENT>if order == <NUM_LIT:1>:<EOL><INDENT>return np.array([[<NUM_LIT:1.>, dt],<EOL>[<NUM_LIT:0.>, <NUM_LIT:1.>]])<EOL><DEDENT>if order == <NUM_LIT:2>:<EOL><INDENT>return np.array([[<NUM_LIT:1.>, dt, <NUM_LIT:0.5>*dt*dt],<EOL>[<NUM_LIT:0.>, <NUM_LIT:1.>, dt],<EOL>[<NUM_LIT:0.>, <NUM_LIT:0.>, <NUM_LIT:1.>]])<EOL><DEDENT>N = order + <NUM_LIT:1><EOL>F = np.zeros((N, N))<EOL>for n in range(N):<EOL><INDENT>F[<NUM_LIT:0>, n] = float(dt**n) / math.factorial(n)<EOL><DEDENT>for j in range(<NUM_LIT:1>, N):<EOL><INDENT>F[j, j:] = F[<NUM_LIT:0>, <NUM_LIT:0>:-j]<EOL><DEDENT>return F<EOL>
create a state transition matrix of a given order for a given time step `dt`.
f709:m0
def kinematic_kf(dim, order, dt=<NUM_LIT:1.>, dim_z=<NUM_LIT:1>, order_by_dim=True):
from filterpy.kalman import KalmanFilter<EOL>if dim < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if order < <NUM_LIT:0>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if dim_z < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>dim_x = order + <NUM_LIT:1><EOL>kf = KalmanFilter(dim_x=dim * dim_x, dim_z=dim)<EOL>F = kinematic_state_transition(order, dt)<EOL>if order_by_dim:<EOL><INDENT>diag = [F] * dim<EOL>kf.F = block_diag(*diag)<EOL><DEDENT>else:<EOL><INDENT>kf.F.fill(<NUM_LIT:0.0>)<EOL>for i, x in enumerate(F.ravel()):<EOL><INDENT>f = np.eye(dim) * x<EOL>ix, iy = (i // dim_x) * dim, (i % dim_x) * dim<EOL>kf.F[ix:ix+dim, iy:iy+dim] = f<EOL><DEDENT><DEDENT>if order_by_dim:<EOL><INDENT>for i in range(dim):<EOL><INDENT>kf.H[i, i * dim_x] = <NUM_LIT:1.><EOL><DEDENT><DEDENT>else:<EOL><INDENT>for i in range(dim):<EOL><INDENT>kf.H[i, i] = <NUM_LIT:1.><EOL><DEDENT><DEDENT>return kf<EOL>
Returns a KalmanFilter using newtonian kinematics of arbitrary order for any number of dimensions. For example, a constant velocity filter in 3D space would have order 1 dimension 3. Examples -------- A constant velocity filter in 3D space with delta time = .2 seconds would be created with >>> kf = kinematic_kf(dim=3, order=1, dt=.2) >>> kf.F >>> array([[1. , 0.2, 0. , 0. , 0. , 0. ], [0. , 1. , 0. , 0. , 0. , 0. ], [0. , 0. , 1. , 0.2, 0. , 0. ], [0. , 0. , 0. , 1. , 0. , 0. ], [0. , 0. , 0. , 0. , 1. , 0.2], [0. , 0. , 0. , 0. , 0. , 1. ]]) which will set the state `x` to be interpreted as [x, x', y, y', z, z'].T If you set `order_by_dim` to False, then `x` is ordered as [x y z x' y' z'].T As another example, a 2D constant jerk is created with >> kinematic_kf(2, 3) Assumes that the measurement z is position in each dimension. If this is not true you will have to alter the H matrix by hand. P, Q, R are all set to the Identity matrix. H is assigned assuming the measurement is position, one per dimension `dim`. >>> kf = kinematic_kf(2, 1, dt=3.0) >>> kf.F array([[1., 3., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 3.], [0., 0., 0., 1.]]) Parameters ---------- dim : int, >= 1 number of dimensions (2D space would be dim=2) order : int, >= 0 order of the filter. 2 would be a const acceleration model with a stat dim_z : int, default 1 size of z vector *per* dimension `dim`. Normally should be 1 dt : float, default 1.0 Time step. Used to create the state transition matrix order_by_dim : bool, default=True Defines ordering of variables in the state vector. `True` orders by keeping all derivatives of each dimensions) [x x' x'' y y' y''] whereas `False` interleaves the dimensions [x y z x' y' z' x'' y'' z'']
f709:m1
def order_by_derivative(Q, dim, block_size):
N = dim * block_size<EOL>D = zeros((N, N))<EOL>Q = array(Q)<EOL>for i, x in enumerate(Q.ravel()):<EOL><INDENT>f = eye(block_size) * x<EOL>ix, iy = (i // dim) * block_size, (i % dim) * block_size<EOL>D[ix:ix+block_size, iy:iy+block_size] = f<EOL><DEDENT>return D<EOL>
Given a matrix Q, ordered assuming state space [x y z x' y' z' x'' y'' z''...] return a reordered matrix assuming an ordering of [ x x' x'' y y' y'' z z' y''] This works for any covariance matrix or state transition function Parameters ---------- Q : np.array, square The matrix to reorder dim : int >= 1 number of independent state variables. 3 for x, y, z block_size : int >= 0 Size of derivatives. Second derivative would be a block size of 3 (x, x', x'')
f710:m0
def Q_discrete_white_noise(dim, dt=<NUM_LIT:1.>, var=<NUM_LIT:1.>, block_size=<NUM_LIT:1>, order_by_dim=True):
if not (dim == <NUM_LIT:2> or dim == <NUM_LIT:3> or dim == <NUM_LIT:4>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if dim == <NUM_LIT:2>:<EOL><INDENT>Q = [[<NUM_LIT>*dt**<NUM_LIT:4>, <NUM_LIT>*dt**<NUM_LIT:3>],<EOL>[ <NUM_LIT>*dt**<NUM_LIT:3>, dt**<NUM_LIT:2>]]<EOL><DEDENT>elif dim == <NUM_LIT:3>:<EOL><INDENT>Q = [[<NUM_LIT>*dt**<NUM_LIT:4>, <NUM_LIT>*dt**<NUM_LIT:3>, <NUM_LIT>*dt**<NUM_LIT:2>],<EOL>[ <NUM_LIT>*dt**<NUM_LIT:3>, dt**<NUM_LIT:2>, dt],<EOL>[ <NUM_LIT>*dt**<NUM_LIT:2>, dt, <NUM_LIT:1>]]<EOL><DEDENT>else:<EOL><INDENT>Q = [[(dt**<NUM_LIT:6>)/<NUM_LIT>, (dt**<NUM_LIT:5>)/<NUM_LIT:12>, (dt**<NUM_LIT:4>)/<NUM_LIT:6>, (dt**<NUM_LIT:3>)/<NUM_LIT:6>],<EOL>[(dt**<NUM_LIT:5>)/<NUM_LIT:12>, (dt**<NUM_LIT:4>)/<NUM_LIT:4>, (dt**<NUM_LIT:3>)/<NUM_LIT:2>, (dt**<NUM_LIT:2>)/<NUM_LIT:2>],<EOL>[(dt**<NUM_LIT:4>)/<NUM_LIT:6>, (dt**<NUM_LIT:3>)/<NUM_LIT:2>, dt**<NUM_LIT:2>, dt],<EOL>[(dt**<NUM_LIT:3>)/<NUM_LIT:6>, (dt**<NUM_LIT:2>)/<NUM_LIT:2> , dt, <NUM_LIT:1.>]]<EOL><DEDENT>if order_by_dim:<EOL><INDENT>return block_diag(*[Q]*block_size) * var<EOL><DEDENT>return order_by_derivative(array(Q), dim, block_size) * var<EOL>
Returns the Q matrix for the Discrete Constant White Noise Model. dim may be either 2, 3, or 4 dt is the time step, and sigma is the variance in the noise. Q is computed as the G * G^T * variance, where G is the process noise per time step. In other words, G = [[.5dt^2][dt]]^T for the constant velocity model. Parameters ----------- dim : int (2, 3, or 4) dimension for Q, where the final dimension is (dim x dim) dt : float, default=1.0 time step in whatever units your filter is using for time. i.e. the amount of time between innovations var : float, default=1.0 variance in the noise block_size : int >= 1 If your state variable contains more than one dimension, such as a 3d constant velocity model [x x' y y' z z']^T, then Q must be a block diagonal matrix. order_by_dim : bool, default=True Defines ordering of variables in the state vector. `True` orders by keeping all derivatives of each dimensions) [x x' x'' y y' y''] whereas `False` interleaves the dimensions [x y z x' y' z' x'' y'' z''] Examples -------- >>> # constant velocity model in a 3D world with a 10 Hz update rate >>> Q_discrete_white_noise(2, dt=0.1, var=1., block_size=3) array([[0.000025, 0.0005 , 0. , 0. , 0. , 0. ], [0.0005 , 0.01 , 0. , 0. , 0. , 0. ], [0. , 0. , 0.000025, 0.0005 , 0. , 0. ], [0. , 0. , 0.0005 , 0.01 , 0. , 0. ], [0. , 0. , 0. , 0. , 0.000025, 0.0005 ], [0. , 0. , 0. , 0. , 0.0005 , 0.01 ]]) References ---------- Bar-Shalom. "Estimation with Applications To Tracking and Navigation". John Wiley & Sons, 2001. Page 274.
f710:m1
def Q_continuous_white_noise(dim, dt=<NUM_LIT:1.>, spectral_density=<NUM_LIT:1.>,<EOL>block_size=<NUM_LIT:1>, order_by_dim=True):
if not (dim == <NUM_LIT:2> or dim == <NUM_LIT:3> or dim == <NUM_LIT:4>):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if dim == <NUM_LIT:2>:<EOL><INDENT>Q = [[(dt**<NUM_LIT:3>)/<NUM_LIT>, (dt**<NUM_LIT:2>)/<NUM_LIT>],<EOL>[(dt**<NUM_LIT:2>)/<NUM_LIT>, dt]]<EOL><DEDENT>elif dim == <NUM_LIT:3>:<EOL><INDENT>Q = [[(dt**<NUM_LIT:5>)/<NUM_LIT>, (dt**<NUM_LIT:4>)/<NUM_LIT>, (dt**<NUM_LIT:3>)/<NUM_LIT>],<EOL>[ (dt**<NUM_LIT:4>)/<NUM_LIT>, (dt**<NUM_LIT:3>)/<NUM_LIT>, (dt**<NUM_LIT:2>)/<NUM_LIT>],<EOL>[ (dt**<NUM_LIT:3>)/<NUM_LIT>, (dt**<NUM_LIT:2>)/<NUM_LIT>, dt]]<EOL><DEDENT>else:<EOL><INDENT>Q = [[(dt**<NUM_LIT:7>)/<NUM_LIT>, (dt**<NUM_LIT:6>)/<NUM_LIT>, (dt**<NUM_LIT:5>)/<NUM_LIT>, (dt**<NUM_LIT:4>)/<NUM_LIT>],<EOL>[(dt**<NUM_LIT:6>)/<NUM_LIT>, (dt**<NUM_LIT:5>)/<NUM_LIT>, (dt**<NUM_LIT:4>)/<NUM_LIT>, (dt**<NUM_LIT:3>)/<NUM_LIT>],<EOL>[(dt**<NUM_LIT:5>)/<NUM_LIT>, (dt**<NUM_LIT:4>)/<NUM_LIT>, (dt**<NUM_LIT:3>)/<NUM_LIT>, (dt**<NUM_LIT:2>)/<NUM_LIT>],<EOL>[(dt**<NUM_LIT:4>)/<NUM_LIT>, (dt**<NUM_LIT:3>)/<NUM_LIT>, (dt**<NUM_LIT:2>/<NUM_LIT>), dt]]<EOL><DEDENT>if order_by_dim:<EOL><INDENT>return block_diag(*[Q]*block_size) * spectral_density<EOL><DEDENT>return order_by_derivative(array(Q), dim, block_size) * spectral_density<EOL>
Returns the Q matrix for the Discretized Continuous White Noise Model. dim may be either 2, 3, 4, dt is the time step, and sigma is the variance in the noise. Parameters ---------- dim : int (2 or 3 or 4) dimension for Q, where the final dimension is (dim x dim) 2 is constant velocity, 3 is constant acceleration, 4 is constant jerk dt : float, default=1.0 time step in whatever units your filter is using for time. i.e. the amount of time between innovations spectral_density : float, default=1.0 spectral density for the continuous process block_size : int >= 1 If your state variable contains more than one dimension, such as a 3d constant velocity model [x x' y y' z z']^T, then Q must be a block diagonal matrix. order_by_dim : bool, default=True Defines ordering of variables in the state vector. `True` orders by keeping all derivatives of each dimensions) [x x' x'' y y' y''] whereas `False` interleaves the dimensions [x y z x' y' z' x'' y'' z''] Examples -------- >>> # constant velocity model in a 3D world with a 10 Hz update rate >>> Q_continuous_white_noise(2, dt=0.1, block_size=3) array([[0.00033333, 0.005 , 0. , 0. , 0. , 0. ], [0.005 , 0.1 , 0. , 0. , 0. , 0. ], [0. , 0. , 0.00033333, 0.005 , 0. , 0. ], [0. , 0. , 0.005 , 0.1 , 0. , 0. ], [0. , 0. , 0. , 0. , 0.00033333, 0.005 ], [0. , 0. , 0. , 0. , 0.005 , 0.1 ]])
f710:m2
def van_loan_discretization(F, G, dt):
n = F.shape[<NUM_LIT:0>]<EOL>A = zeros((<NUM_LIT:2>*n, <NUM_LIT:2>*n))<EOL>A[<NUM_LIT:0>:n, <NUM_LIT:0>:n] = -F.dot(dt)<EOL>A[<NUM_LIT:0>:n, n:<NUM_LIT:2>*n] = G.dot(G.T).dot(dt)<EOL>A[n:<NUM_LIT:2>*n, n:<NUM_LIT:2>*n] = F.T.dot(dt)<EOL>B=expm(A)<EOL>sigma = B[n:<NUM_LIT:2>*n, n:<NUM_LIT:2>*n].T<EOL>Q = sigma.dot(B[<NUM_LIT:0>:n, n:<NUM_LIT:2>*n])<EOL>return (sigma, Q)<EOL>
Discretizes a linear differential equation which includes white noise according to the method of C. F. van Loan [1]. Given the continuous model x' = Fx + Gu where u is the unity white noise, we compute and return the sigma and Q_k that discretizes that equation. Examples -------- Given y'' + y = 2u(t), we create the continuous state model of x' = [ 0 1] * x + [0]*u(t) [-1 0] [2] and a time step of 0.1: >>> F = np.array([[0,1],[-1,0]], dtype=float) >>> G = np.array([[0.],[2.]]) >>> phi, Q = van_loan_discretization(F, G, 0.1) >>> phi array([[ 0.99500417, 0.09983342], [-0.09983342, 0.99500417]]) >>> Q array([[ 0.00133067, 0.01993342], [ 0.01993342, 0.39866933]]) (example taken from Brown[2]) References ---------- [1] C. F. van Loan. "Computing Integrals Involving the Matrix Exponential." IEEE Trans. Automomatic Control, AC-23 (3): 395-404 (June 1978) [2] Robert Grover Brown. "Introduction to Random Signals and Applied Kalman Filtering." Forth edition. John Wiley & Sons. p. 126-7. (2012)
f710:m3
def runge_kutta4(y, x, dx, f):
k1 = dx * f(y, x)<EOL>k2 = dx * f(y + <NUM_LIT:0.5>*k1, x + <NUM_LIT:0.5>*dx)<EOL>k3 = dx * f(y + <NUM_LIT:0.5>*k2, x + <NUM_LIT:0.5>*dx)<EOL>k4 = dx * f(y + k3, x + dx)<EOL>return y + (k1 + <NUM_LIT:2>*k2 + <NUM_LIT:2>*k3 + k4) / <NUM_LIT><EOL>
computes 4th order Runge-Kutta for dy/dx. Parameters ---------- y : scalar Initial/current value for y x : scalar Initial/current value for x dx : scalar difference in x (e.g. the time step) f : ufunc(y,x) Callable function (y, x) that you supply to compute dy/dx for the specified values.
f712:m0
def pretty_str(label, arr):
def is_col(a):<EOL><INDENT>"""<STR_LIT>"""<EOL>try:<EOL><INDENT>return a.shape[<NUM_LIT:0>] > <NUM_LIT:1> and a.shape[<NUM_LIT:1>] == <NUM_LIT:1><EOL><DEDENT>except (AttributeError, IndexError):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>if label is None:<EOL><INDENT>label = '<STR_LIT>'<EOL><DEDENT>if label:<EOL><INDENT>label += '<STR_LIT>'<EOL><DEDENT>if is_col(arr):<EOL><INDENT>return label + str(arr.T).replace('<STR_LIT:\n>', '<STR_LIT>') + '<STR_LIT>'<EOL><DEDENT>rows = str(arr).split('<STR_LIT:\n>')<EOL>if not rows:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>s = label + rows[<NUM_LIT:0>]<EOL>pad = '<STR_LIT:U+0020>' * len(label)<EOL>for line in rows[<NUM_LIT:1>:]:<EOL><INDENT>s = s + '<STR_LIT:\n>' + pad + line<EOL><DEDENT>return s<EOL>
Generates a pretty printed NumPy array with an assignment. Optionally transposes column vectors so they are drawn on one line. Strictly speaking arr can be any time convertible by `str(arr)`, but the output may not be what you want if the type of the variable is not a scalar or an ndarray. Examples -------- >>> pprint('cov', np.array([[4., .1], [.1, 5]])) cov = [[4. 0.1] [0.1 5. ]] >>> print(pretty_str('x', np.array([[1], [2], [3]]))) x = [[1 2 3]].T
f712:m1
def pprint(label, arr, **kwargs):
print(pretty_str(label, arr), **kwargs)<EOL>
pretty prints an NumPy array using the function pretty_str. Keyword arguments are passed to the print() function. See Also -------- pretty_str Examples -------- >>> pprint('cov', np.array([[4., .1], [.1, 5]])) cov = [[4. 0.1] [0.1 5. ]]
f712:m2
def reshape_z(z, dim_z, ndim):
z = np.atleast_2d(z)<EOL>if z.shape[<NUM_LIT:1>] == dim_z:<EOL><INDENT>z = z.T<EOL><DEDENT>if z.shape != (dim_z, <NUM_LIT:1>):<EOL><INDENT>raise ValueError('<STR_LIT>'.format(dim_z))<EOL><DEDENT>if ndim == <NUM_LIT:1>:<EOL><INDENT>z = z[:, <NUM_LIT:0>]<EOL><DEDENT>if ndim == <NUM_LIT:0>:<EOL><INDENT>z = z[<NUM_LIT:0>, <NUM_LIT:0>]<EOL><DEDENT>return z<EOL>
ensure z is a (dim_z, 1) shaped vector
f712:m3
def inv_diagonal(S):
S = np.asarray(S)<EOL>if S.ndim != <NUM_LIT:2> or S.shape[<NUM_LIT:0>] != S.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>si = np.zeros(S.shape)<EOL>for i in range(len(S)):<EOL><INDENT>si[i, i] = <NUM_LIT:1.> / S[i, i]<EOL><DEDENT>return si<EOL>
Computes the inverse of a diagonal NxN np.array S. In general this will be much faster than calling np.linalg.inv(). However, does NOT check if the off diagonal elements are non-zero. So long as S is truly diagonal, the output is identical to np.linalg.inv(). Parameters ---------- S : np.array diagonal NxN array to take inverse of Returns ------- S_inv : np.array inverse of S Examples -------- This is meant to be used as a replacement inverse function for the KalmanFilter class when you know the system covariance S is diagonal. It just makes the filter run faster, there is >>> kf = KalmanFilter(dim_x=3, dim_z=1) >>> kf.inv = inv_diagonal # S is 1x1, so safely diagonal
f712:m4
def outer_product_sum(A, B=None):
if B is None:<EOL><INDENT>B = A<EOL><DEDENT>outer = np.einsum('<STR_LIT>', A, B)<EOL>return np.sum(outer, axis=<NUM_LIT:0>)<EOL>
Computes the sum of the outer products of the rows in A and B P = \Sum {A[i] B[i].T} for i in 0..N Notionally: P = 0 for y in A: P += np.outer(y, y) This is a standard computation for sigma points used in the UKF, ensemble Kalman filter, etc., where A would be the residual of the sigma points and the filter's state or measurement. The computation is vectorized, so it is much faster than the for loop for large A. Parameters ---------- A : np.array, shape (M, N) rows of N-vectors to have the outer product summed B : np.array, shape (M, N) rows of N-vectors to have the outer product summed If it is `None`, it is set to A. Returns ------- P : np.array, shape(N, N) sum of the outer product of the rows of A and B Examples -------- Here sigmas is of shape (M, N), and x is of shape (N). The two sets of code compute the same thing. >>> P = outer_product_sum(sigmas - x) >>> >>> P = 0 >>> for s in sigmas: >>> y = s - x >>> P += np.outer(y, y)
f712:m5
def __init__(self, kf, save_current=False,<EOL>skip_private=False,<EOL>skip_callable=False,<EOL>ignore=()):
<EOL>self._kf = kf<EOL>self._DL = defaultdict(list)<EOL>self._skip_private = skip_private<EOL>self._skip_callable = skip_callable<EOL>self._ignore = ignore<EOL>self._len = <NUM_LIT:0><EOL>self.properties = inspect.getmembers(<EOL>type(kf), lambda o: isinstance(o, property))<EOL>if save_current:<EOL><INDENT>self.save()<EOL><DEDENT>
Construct the save object, optionally saving the current state of the filter
f712:c0:m0
def save(self):
kf = self._kf<EOL>for prop in self.properties:<EOL><INDENT>self._DL[prop[<NUM_LIT:0>]].append(getattr(kf, prop[<NUM_LIT:0>]))<EOL><DEDENT>v = copy.deepcopy(kf.__dict__)<EOL>if self._skip_private:<EOL><INDENT>for key in list(v.keys()):<EOL><INDENT>if key.startswith('<STR_LIT:_>'):<EOL><INDENT>print('<STR_LIT>', key)<EOL>del v[key]<EOL><DEDENT><DEDENT><DEDENT>if self._skip_callable:<EOL><INDENT>for key in list(v.keys()):<EOL><INDENT>if callable(v[key]):<EOL><INDENT>del v[key]<EOL><DEDENT><DEDENT><DEDENT>for ig in self._ignore:<EOL><INDENT>if ig in v:<EOL><INDENT>del v[ig]<EOL><DEDENT><DEDENT>for key in list(v.keys()):<EOL><INDENT>self._DL[key].append(v[key])<EOL><DEDENT>self.__dict__.update(self._DL)<EOL>self._len += <NUM_LIT:1><EOL>
save the current state of the Kalman filter
f712:c0:m1
@property<EOL><INDENT>def keys(self):<DEDENT>
return list(self._DL.keys())<EOL>
list of all keys
f712:c0:m4
def to_array(self):
for key in self.keys:<EOL><INDENT>try:<EOL><INDENT>self.__dict__[key] = np.array(self._DL[key])<EOL><DEDENT>except:<EOL><INDENT>self.__dict__.update(self._DL)<EOL>raise ValueError(<EOL>"<STR_LIT>".format(key))<EOL><DEDENT><DEDENT>
Convert all saved attributes from a list to np.array. This may or may not work - every saved attribute must have the same shape for every instance. i.e., if `K` changes shape due to `z` changing shape then the call will raise an exception. This can also happen if the default initialization in __init__ gives the variable a different shape then it becomes after a predict/update cycle.
f712:c0:m5
def flatten(self):
for key in self.keys:<EOL><INDENT>try:<EOL><INDENT>arr = self.__dict__[key]<EOL>shape = arr.shape<EOL>if shape[<NUM_LIT:2>] == <NUM_LIT:1>:<EOL><INDENT>self.__dict__[key] = arr.reshape(shape[<NUM_LIT:0>], shape[<NUM_LIT:1>])<EOL><DEDENT><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>
Flattens any np.array of column vectors into 1D arrays. Basically, this makes data readable for humans if you are just inspecting via the REPL. For example, if you have saved a KalmanFilter object with 89 epochs, self.x will be shape (89, 9, 1) (for example). After flatten is run, self.x.shape == (89, 9), which displays nicely from the REPL. There is no way to unflatten, so it's a one way trip.
f712:c0:m6
def __init__(self,dsn,dbtype='<STR_LIT>',debug=False):
self.hdr = "<STR_LIT>"<EOL>self.debug = debug<EOL>self.dbtype = dbtype<EOL>self.noclose = False<EOL>self.dsn = dsn<EOL>self.conn = None<EOL>try:<EOL><INDENT>if dbtype == '<STR_LIT>':<EOL><INDENT>import sqlite3 as dbmodule<EOL>self.conn = dbmodule.connect(dsn)<EOL>self.conn.row_factory = dbmodule.Row<EOL><DEDENT>elif dbtype == '<STR_LIT>':<EOL><INDENT>import psycopg2 as dbmodule<EOL>import psycopg2.extras<EOL>self.conn = dbmodule.connect(dsn, cursor_factory=psycopg2.extras.DictCursor)<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % dbtype);<EOL>self.noclose = True<EOL>sys.exit()<EOL><DEDENT><DEDENT>except:<EOL><INDENT>print("<STR_LIT>");<EOL>sys.exit()<EOL><DEDENT>self.dbmodule = dbmodule<EOL>self.debug = debug<EOL>self.dsn = re.sub( r"<STR_LIT>", "<STR_LIT>", self.dsn)<EOL>if dbtype == '<STR_LIT>':<EOL><INDENT>try:<EOL><INDENT>cur = self.conn.cursor()<EOL>cur.execute("<STR_LIT>")<EOL>cur.close()<EOL><DEDENT>except self.dbmodule.Error as e:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT><DEDENT>self.create_tables()<EOL>return<EOL>
accepted options for dbtype: sqlite3 and pg (for postgres)
f717:c0:m0
def create_tables(self):
cdir = os.path.dirname( os.path.realpath(__file__) )<EOL>schema = os.path.join(cdir,"<STR_LIT:data>","<STR_LIT>")<EOL>if self.debug:<EOL><INDENT>print(self.hdr,"<STR_LIT>",schema)<EOL><DEDENT>self.populate(schema)<EOL>schema = os.path.join(cdir,"<STR_LIT:data>","<STR_LIT>")<EOL>if self.debug:<EOL><INDENT>print(self.hdr,"<STR_LIT>",schema)<EOL><DEDENT>self.populate(schema)<EOL>schema = os.path.join(cdir,"<STR_LIT:data>","<STR_LIT>")<EOL>if self.debug:<EOL><INDENT>print(self.hdr,"<STR_LIT>",schema)<EOL><DEDENT>self.populate(schema)<EOL>schema = os.path.join(cdir,"<STR_LIT:data>","<STR_LIT>")<EOL>if self.debug:<EOL><INDENT>print(self.hdr,"<STR_LIT>",schema)<EOL><DEDENT>self.populate(schema)<EOL>return<EOL>
create tables in database (if they don't already exist)
f717:c0:m1
def assertFuncValue(self, func, param, expected, funcname='<STR_LIT>', extra_msg='<STR_LIT>', **kwargs):
value = func(param)<EOL>if extra_msg:<EOL><INDENT>extra_msg = '<STR_LIT:U+0020>' + extra_msg<EOL><DEDENT>self.assertAlmostEqual(<EOL>value, expected,<EOL>msg='<STR_LIT>'.format(funcname, param, expected, value, extra_msg),<EOL>**kwargs)<EOL>
Asserts that func(param) == expected. Optionally receives the function name, used in the error message
f722:c0:m0
def getLine(x1, y1, x2, y2):
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)<EOL>points = []<EOL>issteep = abs(y2-y1) > abs(x2-x1)<EOL>if issteep:<EOL><INDENT>x1, y1 = y1, x1<EOL>x2, y2 = y2, x2<EOL><DEDENT>rev = False<EOL>if x1 > x2:<EOL><INDENT>x1, x2 = x2, x1<EOL>y1, y2 = y2, y1<EOL>rev = True<EOL><DEDENT>deltax = x2 - x1<EOL>deltay = abs(y2-y1)<EOL>error = int(deltax / <NUM_LIT:2>)<EOL>y = y1<EOL>ystep = None<EOL>if y1 < y2:<EOL><INDENT>ystep = <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>ystep = -<NUM_LIT:1><EOL><DEDENT>for x in range(x1, x2 + <NUM_LIT:1>):<EOL><INDENT>if issteep:<EOL><INDENT>points.append((y, x))<EOL><DEDENT>else:<EOL><INDENT>points.append((x, y))<EOL><DEDENT>error -= deltay<EOL>if error < <NUM_LIT:0>:<EOL><INDENT>y += ystep<EOL>error += deltax<EOL><DEDENT><DEDENT>if rev:<EOL><INDENT>points.reverse()<EOL><DEDENT>return points<EOL>
Returns a list of (x, y) tuples of every point on a line between (x1, y1) and (x2, y2). The x and y values inside the tuple are integers. Line generated with the Bresenham algorithm. Args: x1 (int, float): The x coordinate of the line's start point. y1 (int, float): The y coordinate of the line's start point. x2 (int, float): The x coordinate of the line's end point. y2 (int, float): The y coordiante of the line's end point. Returns: [(x1, y1), (x2, y2), (x3, y3), ...] Example: >>> getLine(0, 0, 6, 6) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6)] >>> getLine(0, 0, 3, 6) [(0, 0), (0, 1), (1, 2), (1, 3), (2, 4), (2, 5), (3, 6)] >>> getLine(3, 3, -3, -3) [(3, 3), (2, 2), (1, 1), (0, 0), (-1, -1), (-2, -2), (-3, -3)]
f725:m0
def getPointOnLine(x1, y1, x2, y2, n):
x = ((x2 - x1) * n) + x1<EOL>y = ((y2 - y1) * n) + y1<EOL>return (x, y)<EOL>
Returns the (x, y) tuple of the point that has progressed a proportion n along the line defined by the two x, y coordinates. Args: x1 (int, float): The x coordinate of the line's start point. y1 (int, float): The y coordinate of the line's start point. x2 (int, float): The x coordinate of the line's end point. y2 (int, float): The y coordiante of the line's end point. n (float): Progress along the line. 0.0 is the start point, 1.0 is the end point. 0.5 is the midpoint. This value can be less than 0.0 or greater than 1.0. Returns: Tuple of floats for the x, y coordinate of the point. Example: >>> getPointOnLine(0, 0, 6, 6, 0) (0, 0) >>> getPointOnLine(0, 0, 6, 6, 1) (6, 6) >>> getPointOnLine(0, 0, 6, 6, 0.5) (3.0, 3.0) >>> getPointOnLine(0, 0, 6, 6, 0.75) (4.5, 4.5) >>> getPointOnLine(3, 3, -3, -3, 0.5) (0.0, 0.0) >>> getPointOnLine(3, 3, -3, -3, 0.25) (1.5, 1.5) >>> getPointOnLine(3, 3, -3, -3, 0.75) (-1.5, -1.5)
f725:m1
def _checkRange(n):
if not <NUM_LIT:0.0> <= n <= <NUM_LIT:1.0>:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>
Raises ValueError if the argument is not between 0.0 and 1.0.
f725:m2
def linear(n):
_checkRange(n)<EOL>return n<EOL>
A linear tween function Example: >>> linear(0.0) 0.0 >>> linear(0.2) 0.2 >>> linear(0.4) 0.4 >>> linear(0.6) 0.6 >>> linear(0.8) 0.8 >>> linear(1.0) 1.0
f725:m3
def easeInQuad(n):
_checkRange(n)<EOL>return n**<NUM_LIT:2><EOL>
A quadratic tween function that begins slow and then accelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m4
def easeOutQuad(n):
_checkRange(n)<EOL>return -n * (n-<NUM_LIT:2>)<EOL>
A quadratic tween function that begins fast and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m5
def easeInOutQuad(n):
_checkRange(n)<EOL>if n < <NUM_LIT:0.5>:<EOL><INDENT>return <NUM_LIT:2> * n**<NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>n = n * <NUM_LIT:2> - <NUM_LIT:1><EOL>return -<NUM_LIT:0.5> * (n*(n-<NUM_LIT:2>) - <NUM_LIT:1>)<EOL><DEDENT>
A quadratic tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m6
def easeInCubic(n):
_checkRange(n)<EOL>return n**<NUM_LIT:3><EOL>
A cubic tween function that begins slow and then accelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m7
def easeOutCubic(n):
_checkRange(n)<EOL>n = n - <NUM_LIT:1><EOL>return n**<NUM_LIT:3> + <NUM_LIT:1><EOL>
A cubic tween function that begins fast and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m8
def easeInOutCubic(n):
_checkRange(n)<EOL>n = <NUM_LIT:2> * n<EOL>if n < <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:0.5> * n**<NUM_LIT:3><EOL><DEDENT>else:<EOL><INDENT>n = n - <NUM_LIT:2><EOL>return <NUM_LIT:0.5> * (n**<NUM_LIT:3> + <NUM_LIT:2>)<EOL><DEDENT>
A cubic tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m9
def easeInQuart(n):
_checkRange(n)<EOL>return n**<NUM_LIT:4><EOL>
A quartic tween function that begins slow and then accelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m10
def easeOutQuart(n):
_checkRange(n)<EOL>n = n - <NUM_LIT:1><EOL>return -(n**<NUM_LIT:4> - <NUM_LIT:1>)<EOL>
A quartic tween function that begins fast and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m11
def easeInOutQuart(n):
_checkRange(n)<EOL>n = <NUM_LIT:2> * n<EOL>if n < <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:0.5> * n**<NUM_LIT:4><EOL><DEDENT>else:<EOL><INDENT>n = n - <NUM_LIT:2><EOL>return -<NUM_LIT:0.5> * (n**<NUM_LIT:4> - <NUM_LIT:2>)<EOL><DEDENT>
A quartic tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m12
def easeInQuint(n):
_checkRange(n)<EOL>return n**<NUM_LIT:5><EOL>
A quintic tween function that begins slow and then accelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m13
def easeOutQuint(n):
_checkRange(n)<EOL>n = n - <NUM_LIT:1><EOL>return n**<NUM_LIT:5> + <NUM_LIT:1><EOL>
A quintic tween function that begins fast and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m14
def easeInOutQuint(n):
_checkRange(n)<EOL>n = <NUM_LIT:2> * n<EOL>if n < <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:0.5> * n**<NUM_LIT:5><EOL><DEDENT>else:<EOL><INDENT>n = n - <NUM_LIT:2><EOL>return <NUM_LIT:0.5> * (n**<NUM_LIT:5> + <NUM_LIT:2>)<EOL><DEDENT>
A quintic tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m15
def easeInSine(n):
_checkRange(n)<EOL>return -<NUM_LIT:1> * math.cos(n * math.pi / <NUM_LIT:2>) + <NUM_LIT:1><EOL>
A sinusoidal tween function that begins slow and then accelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m16
def easeOutSine(n):
_checkRange(n)<EOL>return math.sin(n * math.pi / <NUM_LIT:2>)<EOL>
A sinusoidal tween function that begins fast and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m17
def easeInOutSine(n):
_checkRange(n)<EOL>return -<NUM_LIT:0.5> * (math.cos(math.pi * n) - <NUM_LIT:1>)<EOL>
A sinusoidal tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m18
def easeInExpo(n):
_checkRange(n)<EOL>if n == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>return <NUM_LIT:2>**(<NUM_LIT:10> * (n - <NUM_LIT:1>))<EOL><DEDENT>
An exponential tween function that begins slow and then accelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m19
def easeOutExpo(n):
_checkRange(n)<EOL>if n == <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>return -(<NUM_LIT:2> ** (-<NUM_LIT:10> * n)) + <NUM_LIT:1><EOL><DEDENT>
An exponential tween function that begins fast and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m20
def easeInOutExpo(n):
_checkRange(n)<EOL>if n == <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>elif n == <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>n = n * <NUM_LIT:2><EOL>if n < <NUM_LIT:1>:<EOL><INDENT>return <NUM_LIT:0.5> * <NUM_LIT:2>**(<NUM_LIT:10> * (n - <NUM_LIT:1>))<EOL><DEDENT>else:<EOL><INDENT>n -= <NUM_LIT:1><EOL>return <NUM_LIT:0.5> * (-<NUM_LIT:1> * (<NUM_LIT:2> ** (-<NUM_LIT:10> * n)) + <NUM_LIT:2>)<EOL><DEDENT><DEDENT>
An exponential tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m21
def easeInCirc(n):
_checkRange(n)<EOL>return -<NUM_LIT:1> * (math.sqrt(<NUM_LIT:1> - n * n) - <NUM_LIT:1>)<EOL>
A circular tween function that begins slow and then accelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m22
def easeOutCirc(n):
_checkRange(n)<EOL>n -= <NUM_LIT:1><EOL>return math.sqrt(<NUM_LIT:1> - (n * n))<EOL>
A circular tween function that begins fast and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m23
def easeInOutCirc(n):
_checkRange(n)<EOL>n = n * <NUM_LIT:2><EOL>if n < <NUM_LIT:1>:<EOL><INDENT>return -<NUM_LIT:0.5> * (math.sqrt(<NUM_LIT:1> - n**<NUM_LIT:2>) - <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>n = n - <NUM_LIT:2><EOL>return <NUM_LIT:0.5> * (math.sqrt(<NUM_LIT:1> - n**<NUM_LIT:2>) + <NUM_LIT:1>)<EOL><DEDENT>
A circular tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m24
def easeInElastic(n, amplitude=<NUM_LIT:1>, period=<NUM_LIT>):
_checkRange(n)<EOL>return <NUM_LIT:1> - easeOutElastic(<NUM_LIT:1>-n, amplitude=amplitude, period=period)<EOL>
An elastic tween function that begins with an increasing wobble and then snaps into the destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m25
def easeOutElastic(n, amplitude=<NUM_LIT:1>, period=<NUM_LIT>):
_checkRange(n)<EOL>if amplitude < <NUM_LIT:1>:<EOL><INDENT>amplitude = <NUM_LIT:1><EOL>s = period / <NUM_LIT:4><EOL><DEDENT>else:<EOL><INDENT>s = period / (<NUM_LIT:2> * math.pi) * math.asin(<NUM_LIT:1> / amplitude)<EOL><DEDENT>return amplitude * <NUM_LIT:2>**(-<NUM_LIT:10>*n) * math.sin((n-s)*(<NUM_LIT:2>*math.pi / period)) + <NUM_LIT:1><EOL>
An elastic tween function that overshoots the destination and then "rubber bands" into the destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m26
def easeInOutElastic(n, amplitude=<NUM_LIT:1>, period=<NUM_LIT:0.5>):
_checkRange(n)<EOL>n *= <NUM_LIT:2><EOL>if n < <NUM_LIT:1>:<EOL><INDENT>return easeInElastic(n, amplitude=amplitude, period=period) / <NUM_LIT:2><EOL><DEDENT>else:<EOL><INDENT>return easeOutElastic(n-<NUM_LIT:1>, amplitude=amplitude, period=period) / <NUM_LIT:2> + <NUM_LIT:0.5><EOL><DEDENT>
An elastic tween function wobbles towards the midpoint. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m27
def easeInBack(n, s=<NUM_LIT>):
_checkRange(n)<EOL>return n * n * ((s + <NUM_LIT:1>) * n - s)<EOL>
A tween function that backs up first at the start and then goes to the destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m28
def easeOutBack(n, s=<NUM_LIT>):
_checkRange(n)<EOL>n = n - <NUM_LIT:1><EOL>return n * n * ((s + <NUM_LIT:1>) * n + s) + <NUM_LIT:1><EOL>
A tween function that overshoots the destination a little and then backs into the destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m29
def easeInOutBack(n, s=<NUM_LIT>):
_checkRange(n)<EOL>n = n * <NUM_LIT:2><EOL>if n < <NUM_LIT:1>:<EOL><INDENT>s *= <NUM_LIT><EOL>return <NUM_LIT:0.5> * (n * n * ((s + <NUM_LIT:1>) * n - s))<EOL><DEDENT>else:<EOL><INDENT>n -= <NUM_LIT:2><EOL>s *= <NUM_LIT><EOL>return <NUM_LIT:0.5> * (n * n * ((s + <NUM_LIT:1>) * n + s) + <NUM_LIT:2>)<EOL><DEDENT>
A "back-in" tween function that overshoots both the start and destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m30
def easeInBounce(n):
_checkRange(n)<EOL>return <NUM_LIT:1> - easeOutBounce(<NUM_LIT:1> - n)<EOL>
A bouncing tween function that begins bouncing and then jumps to the destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m31
def easeOutBounce(n):
_checkRange(n)<EOL>if n < (<NUM_LIT:1>/<NUM_LIT>):<EOL><INDENT>return <NUM_LIT> * n * n<EOL><DEDENT>elif n < (<NUM_LIT:2>/<NUM_LIT>):<EOL><INDENT>n -= (<NUM_LIT>/<NUM_LIT>)<EOL>return <NUM_LIT> * n * n + <NUM_LIT><EOL><DEDENT>elif n < (<NUM_LIT>/<NUM_LIT>):<EOL><INDENT>n -= (<NUM_LIT>/<NUM_LIT>)<EOL>return <NUM_LIT> * n * n + <NUM_LIT><EOL><DEDENT>else:<EOL><INDENT>n -= (<NUM_LIT>/<NUM_LIT>)<EOL>return <NUM_LIT> * n * n + <NUM_LIT><EOL><DEDENT>
A bouncing tween function that hits the destination and then bounces to rest. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m32
def easeInOutBounce(n):
_checkRange(n)<EOL>if n < <NUM_LIT:0.5>:<EOL><INDENT>return easeInBounce(n * <NUM_LIT:2>) * <NUM_LIT:0.5><EOL><DEDENT>else:<EOL><INDENT>return easeOutBounce(n * <NUM_LIT:2> - <NUM_LIT:1>) * <NUM_LIT:0.5> + <NUM_LIT:0.5><EOL><DEDENT>
A bouncing tween function that bounces at the start and end. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
f725:m33
def check_in(request, action):
if not request:<EOL><INDENT>req_str = "<STR_LIT>"<EOL>for idx, val in enumerate(actions[action]):<EOL><INDENT>req_str += "<STR_LIT:\n>" + val<EOL><DEDENT>erstr = "<STR_LIT>""<STR_LIT>" % req_str<EOL>raise ValueError(erstr)<EOL><DEDENT>required_fields = actions[action]<EOL>missing = []<EOL>for field in required_fields:<EOL><INDENT>if not is_key_present(request, field):<EOL><INDENT>missing.append(field)<EOL><DEDENT><DEDENT>if missing:<EOL><INDENT>missing_string = "<STR_LIT>"<EOL>for idx, val in enumerate(missing):<EOL><INDENT>missing_string += "<STR_LIT:\n>" + val<EOL><DEDENT>erstr = "<STR_LIT>""<STR_LIT>" % missing_string<EOL>raise ValueError(erstr)<EOL><DEDENT>return True<EOL>
This function checks for missing properties in the request dict for the corresponding action.
f728:m0
def _determine_api_url(self, platform, service, action):
base_uri = settings.BASE_PAL_URL.format(platform)<EOL>if service == "<STR_LIT>":<EOL><INDENT>api_version = settings.API_RECURRING_VERSION<EOL><DEDENT>elif service == "<STR_LIT>":<EOL><INDENT>api_version = settings.API_PAYOUT_VERSION<EOL><DEDENT>else:<EOL><INDENT>api_version = settings.API_PAYMENT_VERSION<EOL><DEDENT>return '<STR_LIT:/>'.join([base_uri, service, api_version, action])<EOL>
This returns the Adyen API endpoint based on the provided platform, service and action. Args: platform (str): Adyen platform, ie 'live' or 'test'. service (str): API service to place request through. action (str): the API action to perform.
f729:c1:m1
def _determine_hpp_url(self, platform, action):
base_uri = settings.BASE_HPP_URL.format(platform)<EOL>service = action + '<STR_LIT>'<EOL>result = '<STR_LIT:/>'.join([base_uri, service])<EOL>return result<EOL>
This returns the Adyen HPP endpoint based on the provided platform, and action. Args: platform (str): Adyen platform, ie 'live' or 'test'. action (str): the HPP action to perform. possible actions: select, pay, skipDetails, directory
f729:c1:m2