Math sub-package

py:
  • __init__.py

  • basics.py

  • minimizebnd.py

  • mupolymodel.py

  • Pyswarms_particleswarm.py

  • pymoo_nsga_ii.py

namespace:

luxpy.math

Module with useful math functions

normalize_3x3_matrix():

Normalize 3x3 matrix M to xyz0 – > [1,1,1]

line_intersect():
Line intersections of series of two line segments a and b.
positive_arctan():

Calculates the positive angle (0°-360° or 0 - 2*pi rad.) from x and y.

dot23():

Dot product of a 2-d ndarray with a (N x K x L) 3-d ndarray using einsum().

check_symmetric():

Checks if A is symmetric.

check_posdef():

Checks positive definiteness of a matrix via Cholesky.

symmM_to_posdefM():
Converts a symmetric matrix to a positive definite one.
Two methods are supported:
* ‘make’: A Python/Numpy port of Muhammad Asim Mubeen’s
* ‘nearest’: A Python/Numpy port of John D’Errico’s
bvgpdf():

Evaluate bivariate Gaussian probability density function (BVGPDF) at (x,y) with center mu and inverse covariance matric, sigmainv.

mahalanobis2():

Evaluate the squared mahalanobis distance with center mu and shape and orientation determined by sigmainv.

rms():

Calculates root-mean-square along axis.

geomean():

Calculates geometric mean along axis.

polyarea():
Calculates area of polygon.
(First coordinate should also be last)
erf(), erfinv():

erf-function and its inverse, imported from scipy.special

cart2pol():

Converts Cartesian to polar coordinates.

pol2cart():

Converts polar to Cartesian coordinates.

cart2spher():

Converts Cartesian to spherical coordinates.

spher2cart():

Converts spherical to Cartesian coordinates.

magnitude_v():

Calculates magnitude of vector.

angle_v1v2():

Calculates angle between two vectors.

histogram():
Histogram function that can take as bins either the center
(cfr. matlab hist) or bin-edges.
v_to_cik():

Calculate 2x2 ‘(covariance matrix)^-1’ elements cik from v-format ellipse descriptor.

cik_to_v():

Calculate v-format ellipse descriptor from 2x2 ‘covariance matrix’^-1 cik.

minimizebnd():

scipy.minimize() that allows contrained parameters on unconstrained methods(port of Matlab’s fminsearchbnd). Starting, lower and upper bounds values can also be provided as a dict.

DEMO:

Module for Differential Evolutionary Multi-objective Optimization (DEMO).

vec3:

Module for spherical vector coordinates.

fmod():

Floating point modulus, e.g.: fmod(theta, np.pi * 2) would keep an angle in [0, 2pi]b

fit_ellipse():

Fit an ellipse to supplied data points.

fit_cov_ellipse():

Fit an covariance ellipse to supplied data points.

interp1_sprague5():

Perform a 1-dimensional 5th order Sprague interpolation.

linterp():

Perform a 1-dimensional linear interpolation (wrapper around numpy.interp1 with added linear extrapolation).

interp1():

Perform a 1-dimensional linear interpolation (wrapper around scipy.interpolate.InterpolatedUnivariateSpline, scipy.interpolate.interp1d and numpy based linterp).

ndinterp1():

Perform n-dimensional interpolation using Delaunay triangulation.

ndinterp1_scipy():

Perform n-dimensional interpolation using Delaunay triangulation (wrapper around scipy.interpolate.LinearNDInterpolator)

box_m():

Performs a Box M test on covariance matrices.

pitman_morgan():

Pitman-Morgan Test for the difference between correlated variances with paired samples.

mupolymod:

Module for Multivariate Polynomial Model Optimization (2D, 3D)

NOT IMPORTED in math-namespace (to minimize dependencies)

pyswarms_particleswarm:

Module with particleswarm() function for global minimization using particle swarms (wrapper around pyswarms.single.GlobalBestPSO))

pymoo_nsga_ii:

Module with nsga_ii() function for pareto-optimal boundary minimization using Non-Dominated-Sort-Genetic-Algorithm NSGA-II (wrapper around pymoo.NSGAII))


luxpy.math.normalize_3x3_matrix(M, xyz0=array([[1.0000e+00, 1.0000e+00, 1.0000e+00]]))[source]

Normalize 3x3 matrix M to xyz0 – > [1,1,1]

If M.shape == (1,9): M is reshaped to (3,3)
Args:
M:
ndarray((3,3) or ndarray((1,9))
xyz0:
2darray, optional
Returns:
returns:
normalized matrix such that M*xyz0 = [1,1,1]
luxpy.math.symmM_to_posdefM(A=None, atol=1e-09, rtol=1e-09, method='make', forcesymm=True)[source]

Convert a symmetric matrix to a positive definite one.

Args:
A:
ndarray
atol:
float, optional
The absolute tolerance parameter (see Notes of numpy.allclose())
rtol:
float, optional
The relative tolerance parameter (see Notes of numpy.allclose())
method:
‘make’ or ‘nearest’, optional (see notes for more info)
forcesymm:
True or False, optional
If A is not symmetric, force symmetry using:
A = numpy.triu(A) + numpy.triu(A).T - numpy.diag(numpy.diag(A))
Returns:
returns:
ndarray with positive-definite matrix.
Notes on supported methods:

1. ‘make’: A Python/Numpy port of Muhammad Asim Mubeen’s matlab function Spd_Mat.m 2. ‘nearest’: A Python/Numpy port of John D’Errico’s `nearestSPD MATLAB code. <https://stackoverflow.com/questions/43238173/python-convert-matrix-to-positive-semi-definite>`_

luxpy.math.check_symmetric(A, atol=1e-09, rtol=1e-09)[source]

Check if A is symmetric.

Args:
A:
ndarray
atol:
float, optional
The absolute tolerance parameter (see Notes of numpy.allclose())
rtol:
float, optional
The relative tolerance parameter (see Notes of numpy.allclose())
Returns:
returns:
Bool
True: the array is symmetric within the given tolerance
luxpy.math.in_hull(p, hull)[source]

Test if points in p are in hull

Args:
p:
NxK coordinates of N points in K dimensions
hull:
Either a scipy.spatial.Delaunay object or the MxK array of the
coordinates of M points in K dimensions for which Delaunay
triangulation will be computed
Returns:
bool:
boolean ndarray with True for in-gamut and False for out-of-gamut points
luxpy.math.check_posdef(A, atol=1e-09, rtol=1e-09)[source]

Checks positive definiteness of a matrix via Cholesky.

Args:
A:
ndarray
atol:
float, optional
The absolute tolerance parameter (see Notes of numpy.allclose())
rtol:
float, optional
The relative tolerance parameter (see Notes of numpy.allclose())
Returns:
returns:
Bool
True: the array is positive-definite within the given tolerance
luxpy.math.positive_arctan(x, y, htype='deg')[source]

Calculate positive angle (0°-360° or 0 - 2*pi rad.) from x and y.

Args:
x:
ndarray of x-coordinates
y:
ndarray of y-coordinates
htype:
‘deg’ or ‘rad’, optional
- ‘deg’: hue angle between 0° and 360°
- ‘rad’: hue angle between 0 and 2pi radians
Returns:
returns:
ndarray of positive angles.
luxpy.math.line_intersect(a1, a2, b1, b2)[source]

Line intersections of series of two line segments a and b.

Args:
a1:
ndarray (.shape = (N,2)) specifying end-point 1 of line a
a2:
ndarray (.shape = (N,2)) specifying end-point 2 of line a
b1:
ndarray (.shape = (N,2)) specifying end-point 1 of line b
b2:
ndarray (.shape = (N,2)) specifying end-point 2 of line b
Note:

N is the number of line segments a and b.

Returns:
returns:
ndarray with line-intersections (.shape = (N,2))
References:
  1. https://stackoverflow.com/questions/3252194/numpy-and-line-intersections

luxpy.math.erf(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])[source]

erf(z) Returns the error function of complex argument.

It is defined as 2/sqrt(pi)*integral(exp(-t**2), t=0..z). Args:

x:
ndarray
Input array.
Returns:
res:
ndarray
The values of the error function at the given points x.
See Also:
nerfc, erfinv, erfcinv, wofz, erfcx, erfi
Notes:

1. The cumulative of the unit normal distribution is given by Phi(z) = 1/2[1 + erf(z/sqrt(2))].

References:
  1. https://en.wikipedia.org/wiki/Error_function

2. Milton Abramowitz and Irene A. Stegun, eds. Handbook of Mathematical Functions with Formulas, Graphs, and Mathematical Tables. µ New York: Dover, 1972. http://www.math.sfu.ca/~cbm/aands/page_297.htm 3. Steven G. Johnson, Faddeeva W function implementation. http://ab-initio.mit.edu/Faddeeva

Examples:
>>> from scipy import special
>>> import matplotlib.pyplot as plt
>>> x = np.linspace(-3, 3)
>>> plt.plot(x, special.erf(x))
>>> plt.xlabel('$x$')
>>> plt.ylabel('$erf(x)$')
>>> plt.show()
luxpy.math.erfinv(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])[source]

Inverse of the error function. Computes the inverse of the error function.

In the complex domain, there is no unique complex number w satisfying erf(w)=z. This indicates a true inverse function would have multi-value. When the domain restricts to the real, -1 < x < 1, there is a unique real number satisfying erf(erfinv(x)) = x.

Args:
y:
ndarray
Argument at which to evaluate. Domain: [-1, 1]
Returns:
erfinv:
ndarray
The inverse of erf of y, element-wise)
See Also:
  • erf : Error function of a complex argument

  • erfc : Complementary error function, 1 - erf(x)

  • erfcinv : Inverse of the complementary error function

Examples:
  1. evaluating a float number
    >>> from scipy import special
    >>> special.erfinv(0.5)
    0.4769362762044698
    
  2. evaluating an ndarray
    >>> from scipy import special
    >>> y = np.linspace(-1.0, 1.0, num=10)
    >>> special.erfinv(y)
    array([       -inf, -0.86312307, -0.5407314 , -0.30457019, -0.0987901 ,
           0.0987901 ,  0.30457019,  0.5407314 ,  0.86312307,         inf])
    
luxpy.math.histogram(a, bins=10, bin_center=False, range=None, weights=None, density=False)[source]

Histogram function that can take as bins either the center (cfr. matlab hist) or bin-edges.

Args:
bin_center:
False, optional
False: if :bins: int, str or sequence of scalars:
default to numpy.histogram (uses bin edges).
True: if :bins: is a sequence of scalars:
bins (containing centers) are transformed to edges
and nump.histogram is run.
Mimicks matlab hist (uses bin centers).
Note:

For other armuments and output, see ?numpy.histogram

Returns:
returns:
ndarray with histogram
luxpy.math.pol2cart(theta, r=None, htype='deg')[source]

Convert Cartesion to polar coordinates.

Args:
theta:
float or ndarray with theta-coordinates
r:
None or float or ndarray with r-coordinates, optional
If None, r-coordinates are assumed to be in :theta:.
htype:
‘deg’ or ‘rad, optional
Intput type of :theta:.
Returns:
returns:
(float or ndarray of x, float or ndarray of y) coordinates
luxpy.math.cart2pol(x, y=None, htype='deg')[source]

Convert Cartesion to polar coordinates.

Args:
x:
float or ndarray with x-coordinates
y:
None or float or ndarray with x-coordinates, optional
If None, y-coordinates are assumed to be in :x:.
htype:
‘deg’ or ‘rad, optional
Output type of theta.
Returns:
returns:
(float or ndarray of theta, float or ndarray of r) values
luxpy.math.spher2cart(theta, phi, r=1.0, deg=True)[source]

Convert spherical to cartesian coordinates.

Args:
theta:
Float, int or ndarray
Angle with positive z-axis.
phi:
Float, int or ndarray
Angle around positive z-axis starting from x-axis.
r:
1, optional
Float, int or ndarray
radius
Returns:
x, y, z:
tuple of floats, ints or ndarrays
Cartesian coordinates
luxpy.math.cart2spher(x, y, z, deg=True)[source]

Convert cartesian to spherical coordinates.

Args:
x, y, z:
tuple of floats, ints or ndarrays
Cartesian coordinates
Returns:
theta:
Float, int or ndarray
Angle with positive z-axis.
phi:
Float, int or ndarray
Angle around positive z-axis starting from x-axis.
r:
1, optional
Float, int or ndarray
radius
luxpy.math.bvgpdf(x, y=None, mu=None, sigmainv=None)[source]

Evaluate bivariate Gaussian probability density function (BVGPDF)

Args:
x:
scalar or list or ndarray (.ndim = 1 or 2) with
x(y)-coordinates at which to evaluate bivariate Gaussian PD.
y:
None or scalar or list or ndarray (.ndim = 1) with
y-coordinates at which to evaluate bivariate Gaussian PD, optional.
If :y: is None, :x: should be a 2d array.
mu:
None or ndarray (.ndim = 2) with center coordinates of
bivariate Gaussian PD, optional.
None defaults to ndarray([0,0]).
sigmainv:
None or ndarray with ‘inverse covariance matrix’, optional
Determines the shape and orientation of the PD.
None default to numpy.eye(2).
Returns:
returns:
ndarray with magnitude of BVGPDF(x,y)
luxpy.math.mahalanobis2(x, y=None, z=None, mu=None, sigmainv=None)[source]

Evaluate the squared mahalanobis distance

Args:
x:
scalar or list or ndarray (.ndim = 1 or 2) with x(y)-coordinates at which to evaluate the mahalanobis distance squared.
y:
None or scalar or list or ndarray (.ndim = 1) with y-coordinates at which to evaluate the mahalanobis distance squared, optional.
If :y: is None, :x: should be a 2d array.
z:
None or scalar or list or ndarray (.ndim = 1) with z-coordinates at which to evaluate the mahalanobis distance squared, optional.
If :z: is None & :y: is None, then :x: should be a 2d array.
mu:
None or ndarray (.ndim = 1) with center coordinates of the mahalanobis ellipse, optional.
None defaults to zeros(2) or zeros(3).
sigmainv:
None or ndarray with ‘inverse covariance matrix’, optional
Determines the shape and orientation of the PD.
None default to np.eye(2) or eye(3).
Returns:
returns:
ndarray with magnitude of mahalanobis2(x,y[,z])
luxpy.math.dot23(A, B, keepdims=False)[source]

Dot product of a 2-d ndarray with a (N x K x L) 3-d ndarray using einsum().

Args:
A:
ndarray (.shape = (M,N))
B:
ndarray (.shape = (N,K,L))
Returns:
returns:
ndarray (.shape = (M,K,L))
luxpy.math.rms(data, axis=0, keepdims=False)[source]

Calculate root-mean-square along axis.

Args:
data:
list of values or ndarray
axis:
0, optional
Axis along which to calculate rms.
keepdims:
False or True, optional
Keep original dimensions of array.
Returns:
returns:
ndarray with rms values.
luxpy.math.geomean(data, axis=0, keepdims=False)[source]

Calculate geometric mean along axis.

Args:
data:
list of values or ndarray
axis:
0, optional
Axis along which to calculate geomean.
keepdims:
False or True, optional
Keep original dimensions of array.
Returns:
returns:
ndarray with geomean values.
luxpy.math.polyarea(x, y)[source]

Calculates area of polygon.

First coordinate should also be last.
Args:
x:
ndarray of x-coordinates of polygon vertices.
y:
ndarray of x-coordinates of polygon vertices.
Returns:
returns:
float (area or polygon)
luxpy.math.magnitude_v(v)[source]

Calculates magnitude of vector.

Args:
v:
ndarray with vector
Returns:
magnitude:
ndarray
luxpy.math.angle_v1v2(v1, v2, htype='deg')[source]

Calculates angle between two vectors.

Args:
v1:
ndarray with vector 1
v2:
ndarray with vector 2
htype:
‘deg’ or ‘rad’, optional
Requested angle type.
Returns:
ang:
ndarray
luxpy.math.v_to_cik(v, inverse=False)[source]

Calculate 2x2 ‘(covariance matrix)^-1’ elements cik

Args:
v:
(Nx5) np.ndarray
ellipse parameters [Rmax,Rmin,xc,yc,theta]
inverse:
If True: return inverse of cik.
Returns:
cik:
‘Nx2x2’ (covariance matrix)^-1
Notes:
cik is not actually a covariance matrix,
only for a Gaussian or normal distribution!
luxpy.math.cik_to_v(cik, xyc=None, inverse=False)[source]

Calculate v-format ellipse descriptor from 2x2 ‘covariance matrix’^-1 cik

Args:
cik:
‘Nx2x2’ (covariance matrix)^-1
inverse:
If True: input is inverse of cik.
Returns:
v:
(Nx5) np.ndarray
ellipse parameters [Rmax,Rmin,xc,yc,theta]
Notes:
cik is not actually the inverse covariance matrix,
only for a Gaussian or normal distribution!
luxpy.math.fmod(x, y)[source]

Floating point modulus

e.g., fmod(theta, np.pi * 2) would keep an angle in [0, 2pi]
Args:
x:
angle to restrict
y:
end of interval [0, y] to restrict to
Returns:
r:

floating point modulus

luxpy.math.remove_outliers(data, alpha=0.01)[source]

Remove multivariate outliers from data when outside of alpha-level confidence ellipsoid.

Args:
data:
Nxp ndarray with multivariate data (N samples, p variables)
alpha:
0.01, optional
Significance level of confidence ellipsoid marking the boundary for outliers.
Return:
data:
(N-… x p) ndarray with multivariate data; outliers removed.
luxpy.math.fit_ellipse(xy, center_on_mean_xy=False)[source]

Fit an ellipse to supplied data points.

Args:
xy:
coordinates of points to fit (Nx2 array)
center_on_mean_xy:
False, optional
Center ellipse on mean of xy
(otherwise it might be offset due to solving
the contrained minization problem: aT*S*a, see ref below.)
Returns:
v:
vector with ellipse parameters [Rmax,Rmin, xc,yc, theta (rad.)]
Reference:

1. Fitzgibbon, A.W., Pilu, M., and Fischer R.B., Direct least squares fitting of ellipsees, Proc. of the 13th Internation Conference on Pattern Recognition, pp 253–257, Vienna, 1996.

luxpy.math.fit_cov_ellipse(xy, alpha=0.05, pdf='chi2', SE=False, robust=False, robust_alpha=0.01)[source]

Fit covariance ellipse to xy data.

Args:
xy:
coordinates of points to fit (Nx2 array)
alpha:
0.05, optional
alpha significance level
(e.g alpha = 0.05 for 95% confidence ellipse)
pdf:
chi2, optional
- ‘chi2’: Rescale using Chi2-distribution
- ‘t’: Rescale using Student t-distribution
- ‘norm’: Rescale using normal-distribution
- None: don’t rescale using pdf, use alpha as scalefactor (cfr. alpha* 1SD or alpha * 1SE)
SE:
False, optional
If false, fit standard error ellipse at alpha significance level
If true, fit standard deviation ellipse at alpha significance level
robust:
False, optional
If True: remove outliers beyond the confidence ellipsoid before calculating
the covariances.
robust_alpha:
0.01, optional
Significance level of confidence ellipsoid marking the boundary for outliers.
Returns:
v:
vector with ellipse parameters [Rmax,Rmin, xc,yc, theta (rad.)]
luxpy.math.linterp(X, Y, Xnew, left='ext', right='ext', interp_log=False, extrap_log=False)[source]

Perform linear 1-D interpolation (with linear or constant extrapolation). (wrapper around np.interp)

Args:
X:
ndarray with n-dimensional coordinates (last axis represents dimension)
Y:
ndarray with values at coordinates in X
Xnew:
ndarray of new coordinates (last axis represents dimension)
left:
‘ext’, optional float corresponding to Y.
Value to return for Xnew < X[0], None is Y[0].
If ‘ext’: perform linear extrapolation
right:
‘ext’, optional float corresponding to Y.
Value to return for Xnew > X[-1], None is Y[-1].
If ‘ext’: perform linear extrapolation
interp_log:
Perform interpolation method (‘linear’, ‘quadratic’, or ‘cubic’) in log space.
extrap_log:
Perform extrapolation method (‘linear’, ‘quadratic’, or ‘cubic’) in log space.
Returns:
Ynew:
ndarray with new values at coordinates in Xnew
luxpy.math.interpolatedunivariatespline(X, Y, Xnew, kind='linear', ext='extrapolate', fill_value='extrapolate', w=None, bbox=[None, None], check_finite=False, interp_log=False, extrap_log=False)[source]

Perform a 1-dimensional interpolation (with extrapolation) (wrapper around scipy.interpolate.InterpolatedUnivariateSpline).

Args:
X:
ndarray with n-dimensional coordinates (last axis represents dimension)
Y:
ndarray with values at coordinates in X
Xnew:
ndarray of new coordinates (last axis represents dimension)
kind:
str, optional
supported options for str: ‘linear’, ‘quadratic’, ‘cubic’
ext:
‘extrapolate’, optional
options:
- ‘extrapolate’
- ‘zeros’: out-of-bounds values are filled with zeros
- ‘const’: out-of-bounds values are filled with nearest value
- ‘fill_value’: value of tuple (2,) of values is used to fill out-of-bounds values
fill_value:
‘extrapolate’ or float or int or tupple, optional
If ext == ‘fill_value’: use fill_value to set lower- and upper-out-of-bounds values when extrapolating
w,bbox,check_finite:
see scipy.interpolate.InterpolatedUnivariateSpline()
interp_log:
Perform interpolation method (‘linear’, ‘quadratic’, or ‘cubic’) in log space.
extrap_log:
Perform extrapolation method (‘linear’, ‘quadratic’, or ‘cubic’) in log space.
Returns:
Ynew:
ndarray with new values at coordinates in Xnew
luxpy.math.interp1_sprague5(X, Y, Xnew, extrap='linear', force_scipy_interpolator=False, scipy_interpolator='InterpolatedUnivariateSpline', delete_nans=True, choose_most_efficient_interpolator=False, verbosity=0)[source]

Perform a 1-dimensional 5th order Sprague interpolation.

Args:
X:
ndarray with n-dimensional coordinates.
Y:
ndarray with values at coordinates in X.
Xnew:
ndarray of new coordinates.
extrap:
(np.nan, np.nan) or string, optional
If tuple: fill with values in tuple (<X[0],>X[-1])
If string: (‘linear’, ‘quadratic’, ‘cubic’, ‘zeros’, ‘const’)
force_scipy_interpolator:
False, optional
If False: numpy.interp function is used for linear interpolation when no or linear extrapolation is used/required (fast!).
scipy_interpolator:
‘InterpolatedUnivariateSpline’, optional
options: ‘InterpolatedUnivariateSpline’, ‘interp1d’
delete_nans:
True, optional
If NaNs are present, remove them and (and try to) interpolate without them.
Returns:
Yn:
ndarray with values at new coordinates in Xnew.
luxpy.math.interp1_sprague_cie224_2017(X, Y, Xnew, extrap='linear', force_scipy_interpolator=False, scipy_interpolator='InterpolatedUnivariateSpline', delete_nans=True, choose_most_efficient_interpolator=False, verbosity=0)[source]

Perform a 1-dimensional Sprague interpolation according to CIE-224-2017.

Args:
X:
ndarray with n-dimensional coordinates.
Y:
ndarray with values at coordinates in X.
Xnew:
ndarray of new coordinates.
extrap:
(np.nan, np.nan) or string, optional
If tuple: fill with values in tuple (<X[0],>X[-1])
If string: (‘linear’, ‘quadratic’, ‘cubic’, ‘zeros’, ‘const’)
force_scipy_interpolator:
False, optional
If False: numpy.interp function is used for linear interpolation when no or linear extrapolation is used/required (fast!).
scipy_interpolator:
‘InterpolatedUnivariateSpline’, optional
options: ‘InterpolatedUnivariateSpline’, ‘interp1d’
delete_nans:
True, optional
If NaNs are present, remove them and (and try to) interpolate without them.
Returns:
Yn:
ndarray with values at new coordinates in Xnew.
luxpy.math.interp1_lagrange(X, Y, Xnew, k=5, extrap='linear', force_scipy_interpolator=False, scipy_interpolator='InterpolatedUnivariateSpline', delete_nans=True, choose_most_efficient_interpolator=False, verbosity=0)[source]

Perform a 1-dimensional k-th order Lagrange interpolation.

Args:
X:
ndarray with n-dimensional coordinates.
Y:
ndarray with values at coordinates in X.
Xnew:
ndarray of new coordinates.
k:
5 or int, optional
Order of Lagrange interpolation
extrap:
(np.nan, np.nan) or string, optional
If tuple: fill with values in tuple (<X[0],>X[-1])
If string: (‘linear’, ‘quadratic’, ‘cubic’, ‘zeros’, ‘const’)
force_scipy_interpolator:
False, optional
If False: numpy.interp function is used for linear interpolation when no or linear extrapolation is used/required (fast!).
scipy_interpolator:
‘InterpolatedUnivariateSpline’, optional
options: ‘InterpolatedUnivariateSpline’, ‘interp1d’
delete_nans:
True, optional
If NaNs are present, remove them and (and try to) interpolate without them.
Returns:
Yn:
ndarray with values at new coordinates in Xnew.
luxpy.math.interp1(X, Y, Xnew, kind='linear', ext='extrapolate', fill_value='extrapolate', force_scipy_interpolator=False, scipy_interpolator='InterpolatedUnivariateSpline', delete_nans=True, w=None, bbox=[None, None], check_finite=False, interp_log=False, extrap_log=False, choose_most_efficient_interpolator=False, verbosity=0)[source]

Perform a 1-dimensional interpolation (wrapper around linterp, interpolatedunivariatespline, interp1d).

Args:
X:
ndarray with n-dimensional coordinates (last axis represents dimension)
Y:
ndarray with values at coordinates in X
Xnew:
ndarray of new coordinates (last axis represents dimension)
kind:
str, optional
supported options for str: ‘linear’, ‘quadratic’, ‘cubic’
ext:
‘extrapolate’, optional
options:
- ‘extrapolate’, ‘ext’: use method specified in :kind: to extrapolate.
- ‘linear’, ‘quadratic’, ‘cubic’ extrapolation
- ‘zeros’: out-of-bounds values are filled with zeros
- ‘const’,’flat’,’nearest’: out-of-bounds values are filled with nearest value
- ‘fill_value’: value of tuple (2,) of values is used to fill out-of-bounds values
fill_value:
‘extrapolate’ or float or int or tupple, optional
If ext == ‘fill_value’: use fill_value to set lower- and upper-out-of-bounds values when extrapolating
force_scipy_interpolator:
False, optional
If False: numpy.interp function is used for linear interpolation when no or linear extrapolation is used/required (fast!).
scipy_interpolator:
‘InterpolatedUnivariateSpline’, optional
options: ‘InterpolatedUnivariateSpline’, ‘interp1d’
delete_nans:
True, optional
If NaNs are present, remove them and (and try to) interpolate without them.
w,bbox,check_finite:
see scipy.interpolate.InterpolatedUnivariateSpline()
interp_log:
Perform interpolation method (‘linear’, ‘quadratic’, or ‘cubic’) in log space.
extrap_log:
Perform extrapolation method (‘linear’, ‘quadratic’, or ‘cubic’) in log space.
Returns:
Ynew:
ndarray with new values at coordinates in Xnew
Note:
  1. ‘numpy.interp’ is fastest (but only works for linear interpolation and linear or no extrapolation)

  2. For linear interpolation: ‘interp1d’ is faster for Y (N,…) with N > 1, else ‘InterpolatedUnivariateSpline’ is faster

  3. For ‘cubic’ interpolation: ‘InterpolatedUnivariateSpline’ is faster for Y (N,…) with N > 1, else ‘interp1d’ is faster

luxpy.math.ndinterp1(X, Y, Xnew)[source]

Perform nd-dimensional linear interpolation using Delaunay triangulation.

Args:
X:
ndarray with n-dimensional coordinates (last axis represents dimension).
Y:
ndarray with values at coordinates in X.
Xnew:
ndarray of new coordinates (last axis represents dimension).
When outside of the convex hull of X, then a best estimate is
given based on the closest vertices.
Returns:
Ynew:
ndarray with new values at coordinates in Xnew.
luxpy.math.ndinterp1_scipy(X, Y, Xnew, fill_value=nan, rescale=False)[source]

Perform a n-dimensional linear interpolation (wrapper around scipy.interpolate.LinearNDInterpolator).

Args:
X:
ndarray with n-dimensional coordinates (last axis represents dimension)
Y:
ndarray with values at coordinates in X
Xnew:
ndarray of new coordinates (last axis represents dimension)
fill_value:
float, optional
Value used to fill in for requested points outside of the
convex hull of the input points. If not provided, then
the default is nan.
rescale:
bool, optional
Rescale points to unit cube before performing interpolation.
This is useful if some of the input dimensions have
incommensurable units and differ by many orders of magnitude.
Returns:
Ynew:
ndarray with new values at coordinates in Xnew
luxpy.math.box_m(*X, ni=None, verbosity=0, robust=False, robust_alpha=0.01)[source]

Perform Box’s M test (p>=2) to check equality of covariance matrices or Bartlett’s test (p==1) for equality of variances.

Args:
X:
A number (k groups) or list of 2d-ndarrays (rows: samples, cols: variables) with data.
or a number of 2d-ndarrays with covariance matrices (supply ni!)
ni:
None, optional
If None: X contains data, else, X contains covariance matrices.
verbosity:
0, optional
If 1: print results.
robust:
False, optional
If True: remove outliers beyond the confidence ellipsoid before calculating
the covariances.
robust_alpha:
0.01, optional
Significance level of confidence ellipsoid marking the boundary for outliers.
Returns:
statistic:
F or chi2 value (see len(dfs))
pval:
p-value
df:
degrees of freedom.
if len(dfs) == 2: F-test was used.
if len(dfs) == 1: chi2 approx. was used.
Notes:
  1. If p==1: Reduces to Bartlett’s test for equal variances.

  2. If (ni>20).all() & (p<6) & (k<6): then a more appropriate chi2 test is used in a some cases.

luxpy.math.pitman_morgan(X, Y, verbosity=0)[source]

Pitman-Morgan Test for the difference between correlated variances with paired samples.

Args:
X,Y:
ndarrays with data.
verbosity:
0, optional
If 1: print results.
Returns:
tval:
statistic
pval:
p-value
df:
degree of freedom.
ratio:
variance ratio var1/var2 (with var1 > var2).
Note:
  1. Based on Gardner, R.C. (2001). Psychological Statistics Using SPSS for Windows. New Jersey, Prentice Hall.

  2. Python port from matlab code by Janne Kauttonen (https://nl.mathworks.com/matlabcentral/fileexchange/67910-pitmanmorgantest-x-y; accessed Sep 26, 2019)

luxpy.math.stress(DE, DV, axis=0, max_scale=100)[source]

Calculate STandardize-Residual-Sum-of-Squares (STRESS).

Args:
DE, DV:
ndarrays of data to be compared.
axis:
0, optional
axis with samples
max_scale:
100, optional
Maximum of scale.
Returns:
stress:
nadarray with stress value(s).
Reference:

1. Melgosa, M., García, P. A., Gómez-Robledo, L., Shamey, R., Hinks, D., Cui, G., & Luo, M. R. (2011). Notes on the application of the standardized residual sum of squares index for the assessment of intra- and inter-observer variability in color-difference experiments. Journal of the Optical Society of America A, 28(5), 949–953.

luxpy.math.stress_F_test(stressA, stressB, N, alpha=0.05)[source]

Perform F-test on significance of difference between STRESS A and STRESS B.

Args:
stressA, stressB:
ndarray with stress(es) values for A and B
N:
int or ndarray with number of samples used to determine stress values.
alpha:
0.05, optional
significance level
Returns:
Fstats:
Dictionary with keys:
- ‘p’: p-values
- ‘F’: F-values
- ‘Fc’: critcal values
- ‘H’: string reporting on significance of A compared to B.
luxpy.math.mean_distance_weighted(x, axis=0, keepdims=False, center_x=False, rtol=0.001, max_iter=100, cnt=0, mu=None, mu0=0)[source]

Recursively calculate distance weighted mean.

Args:
x:
ndarray with data
axis:
dimension along which to take mean
keepdims:
False, optional
If True: keep dimension of original ndarray
center_x:
True, optional
Center data first.
rtol:
1e-3, optional
Relative tolerance on recursive mean values. If two sequential
mean values differ less than this amount, the recursion stops.
max_iter:
100, optional
Maximum amount of recursions. If this number is reached the
recursion stops, even when rtol is not yet achieved. (to avoid
getting stuck in an infinite loop when the recursion doesn’t converge)
cnt,mu,mu0:
Needed for passing values across recursions to be able to stop them.
DO NOT CHANGE.
Returns:
mu_dw:
distance weighted mean of the array
luxpy.math.round(x, n=None)[source]

Round x (int, float, ndarray or tuple) to n significant digits, or n decimals (‘to nearest even’ or ‘halfway from zero’).

Args:
x:
int, float, ndarray or tuple to be rounded.
n:
int or tuple
Number of significant digits, or n decimals.
If int: round to nearest even using numpy’s round() function
if Tuple: first element specifies the number of digits, the second element is a string specifying the method:
- ‘sigfig’: round to n significant digits (uses luxpy.math.round_sigfig function).
- ‘dec’ or ‘nearesteven’ or ‘numpy’ or ‘np’: round to nearest even using numpy’s round function.
- ‘halfwayfromzero’: rounds halfway from zero (uses luxpy.math.round_awayfromzero function).
Returns:
y:
rounded value(s).
Notes:
  1. ‘sigfig’ from: https://stackoverflow.com/questions/18915378/rounding-to-significant-figures-in-numpy

  2. ‘halfwayfromzero’ from: CIETC1-97: https://github.com/ifarup/ciefunctions

luxpy.math._interpolate_with_nans(fintp, X, Y, Xnew, delete_nans=True, nan_indices=None)[source]

Deal with possible NaNs in Y

luxpy.math._extrap_y(x, y, xn, extrap='linear', force_scipy_interpolator=False, scipy_interpolator='InterpolatedUnivariateSpline', delete_nans=True, choose_most_efficient_interpolator=False)[source]

Extrapolate y if needed

luxpy.math.minimizebnd(fun, x0, args=(), method='Nelder-Mead', use_bnd=True, bounds=(None, None), options=None, x0_vsize=None, x0_keys=None, **kwargs)[source]
Minimization function that allows for bounds on any type of method in
SciPy’s minimize function by transforming the parameters values
(see Matlab’s fminsearchbnd).
Starting values, and lower and upper bounds can also be provided as a dict.
Args:
x0:
parameter starting values
If x0_keys is None then :x0: is vector else, :x0: is dict and
x0_size should be provided with length/size of values for each of
the keys in :x0: to convert it to a vector.
use_bnd:
True, optional
False: omits bounds and defaults to regular minimize function.
bounds:
(lower, upper), optional
Tuple of lists or dicts (x0_keys is None) of lower and upper bounds
for each of the parameters values.
kwargs:
allows input for other type of arguments (e.g. in OutputFcn)
Note:

For other input arguments, see ?scipy.optimize.minimize()

Returns:
res:
dict with minimize() output.
Additionally, function value, fval, of solution is also in :res:,
as well as a vector or dict (if x0 was dict)
with final solutions (res[‘x’])

vec3/

py:
  • __init__.py

  • vec3.py

namespace:

luxpy.math

DEMO/

py:
  • __init__.py

  • DEMO.py

  • demo_opt.py

namespace:

luxpy.math