Unittest Utilities¶
Utility functions for unit test.
- unittest_utils.check_gradient(fcn, dfcn, N, x0=None, dx=None, delta=0.0001, m=0.01, M=10, raise_exception=True)[source]¶
Numerically check whether dfcn calculates the gradient of fcn.
More specifically, this function checks whether the following quantities are close to each other
- f(x) - f(x0)
- (x-x0) cdot f’(x0)
We consider them to be close enough if either one of the following is true
- the absolute difference is smaller than (m * ||x-x0||);
- the relative difference is smaller than (M * ||x-x0||).
Parameters: fcn: function handler
Takes a single (vector or scalar) as input and outputs a scalar.
dfcn: function handler
Takes a single (vector or scalar) as input and outputs a vector output for gradient of ‘fcn’. NOTE: Another option is to let dfcn=None (or something else that is not callable, e.g. []), and fcn return a 2-tuple for both fucntion value and its gradient.
N: int
The dimensionality of input to the fucntion, which is a Nx1 vector.
x0:
The initial input point evaluated by the function, with default {randn(N)}.
dx, delta:
The direction of evaluation point moves, such that:
x = x0 + delta*dx
with ‘dx’ a unit Nx1 vector and ‘delta’ a scalar.
m, M: float, optional
The thresholds described above.
- unittest_utils.check_jacobian(fcn, dfcn, N, x0=None, dx=None, delta=0.0001, m=0.01, M=10, raise_exception=True)[source]¶
Numerically check whether dfcn calculates the Jacobian of fcn.
More specifically, whether the following vectors are close to each other
- f(x) - f(x0)
- J(x0) cdot (x-x0)
We consider them to be close enough if either one of the following is true
- “absolutely” close with tolerance m*||x-x0|| (see check_near_abs);
- “relatively” close with tolerance M*||x-x0|| (see check_near_rel).
Parameters: fcn: function handler
Takes a single (vector or scalar) as input and outputs a vector.
dfcn: function handler
Takes a single (vector or scalar) as input and outputs a matrix for Jacobian of fcn. NOTE: Another option is to let dfcn=None (or something else that is not callable, e.g. []), and fcn return a 2-tuple for both fucntion value and its Jacobian.
The rest is the same as `check_gradient`.
- unittest_utils.check_near(v1, v2, tol, raise_exception=True)[source]¶
Check whether scalar/vector/matrix ‘v1’ and ‘v2’ are close to each other under tolerance tol, in the sense that:
(absolute) ||v1 - v2|| <= tol, **or** (relative) ||v1 - v2|| / max(||v1||, ||v2||, eps) <= tol,
where ||.|| is the Frobenius norm.