Cephes Mathematical Functions Library, wrapped for Torch
Provides and wraps the mathematical functions from the Cephes mathematical library, developed by Stephen L. Moshier. This C library provides a lot of mathematical functions. It is used, among many other places, at the heart of SciPy.
Example
Simple call on a number
The wrapped functions can be called from Lua with the same synopsis as their C coutnerpart, and will then return a number, for example:
require 'cephes'
x = cephes.igam(2, 3) -- returns a number
Calling on tensors
Our wrappers for cephes functions are vectorized, meaning they can
- take tensors as arguments, evaluating the function for each element of the arguments, and return the result into a vector.
- mix tensors and numbers as arguments, numbers are automatically expanded
- shape does not matter, only the number of elements.
Like most torch functions, they also accept an optional Tensor as first argument to store the result into.
require 'cephes'
-- Call over a whole tensor of parameters
result = cephes.ndtr(torch.randn(10)) -- returns a new tensor
-- of 10 elements
-- Several tensor arguments, pairing them map-like
-- Below returns a vector of 100 elements
x = torch.rand(100)
y = torch.rand(100)
result = cephes.igam(x, y)
-- Mix number and tensors: numbers are automatically expanded
-- Below returns a vector of 100 elements
result = cephes.igam(4, y)
-- Can also use matrices: only the number of elements matters
-- Below with a 3D array and a vector, return a vector of 100 elts
z = torch.rand(2,5,10)
result = cephes.igam(z, y)
-- And of course you can store the result into an
-- existing tensor of the right number of elements
-- Below stores into an existing 3D tensors of 100 elements
result = torch.Tensor(2,5,10)
cephes.igam(result, x, y)
Installation
From a terminal:
torch-rocks install cephes
Error Handling
By default, Torch-Cephes does not signal any error (domain, singularity, overflow, underflow, precision). It is as non-intrusive as possible and tries to return a value which is hopefully usable: it might be NaN, it might be inf.
However, the user can ask Cephes to generate lua errors with the following functions.
cephes.setErrorLevel(level)
Sets the level of error reporting.
Input: level : can be any of
- 'off'/0 to be entirely quiet
- 'error'/1 to issue Lua errors with stack trace
- 'warning'/2 to print a warning on stdout
Returns: None
cephes.getErrorLevel()
Returns the current level of error reporting, for example to save and restore later.
Input: None
Returns: integer 0, 1, or 2, representing the current error reporting level, see setErrorLevel()
List of Cephes functions
See the full list of Cephes double-precision functions. The Torch wrappers respect the same prototypes.
Note: a few features of the original library have not been wrapped:
- single-precision functions: due to a few name clashes with their double counterparts, they require a slightly larger effort to wrap. Please fill a feature request if you need them.
- polynomials with rational coefficients: their names clash with the polynomials with double coefficients. We wrapped the latter, which seem more generally useful, but please raise an issue.
- linear algebra functions: torch already has those.
So, here goes the whole list, click for details:
- acosh, Inverse hyperbolic cosine
- airy, Airy functions
- asin, Inverse circular sine
- acos, Inverse circular cosine
- asinh, Inverse hyperbolic sine
- atan, Inverse circular tangent
- atan2, Quadrant correct inverse circular tangent
- atanh, Inverse hyperbolic tangent
- bdtr, Binomial distribution
- bdtrc, Complemented binomial distribution
- bdtri, Inverse binomial distribution
- beta, Beta function
- btdtr, Beta distribution
- cbrt, Cube root
- chbevl, Evaluate Chebyshev series
- chdtr, Chi-square distribution
- chdtrc, Complemented Chi-square distribution
- chdtri, Inverse of complemented Chi-square distribution
- cheby, Find Chebyshev coefficients
- clog, Complex natural logarithm
- cexp, Complex exponential function
- csin, Complex circular sine
- ccos, Complex circular cosine
- ctan, Complex circular tangent
- ccot, Complex circular cotangent
- casin, Complex circular arc sine
- cacos, Complex circular arc cosine
- catan, Complex circular arc tangent
- csinh, Complex hyperbolic sine
- casinh, Complex inverse hyperbolic sine
- ccosh, Complex hyperbolic cosine
- cacosh, Complex inverse hyperbolic cosine
- ctanh, Complex hyperbolic tangent
- catanh, Complex inverse hyperbolic tangent
- cpow, Complex power function
- cmplx, Complex number arithmetic
- cabs, Complex absolute value
- csqrt, Complex square root
- const, Globally declared constants
- cosh, Hyperbolic cosine
- dawsn, Dawson's Integral
- drand, Pseudorandom number generator
- ei, Exponential Integral
- eigens, Eigenvalues and eigenvectors of a real symmetric matrix
- ellie, Incomplete elliptic integral of the second kind
- ellik, Incomplete elliptic integral of the first kind
- ellpe, Complete elliptic integral of the second kind
- ellpj, Jacobian elliptic functions
- ellpk, Complete elliptic integral of the first kind
- euclid, Rational arithmetic routines
- exp, Exponential function
- exp10, Base 10 exponential function
- exp2, Base 2 exponential function
- expn, Exponential integral En
- expx2, Exponential of squared argument
- fabs, Absolute value
- fac, Factorial function
- fdtr, F distribution
- fdtrc, Complemented F distribution
- fdtri, Inverse of complemented F distribution
- fftr, Fast Fourier transform
- floor, Floor function
- ceil, Ceil function
- frexp, Extract exponent
- ldexp, Apply exponent
- fresnl, Fresnel integral
- gamma, Gamma function
- lgam, Natural logarithm of gamma function
- gdtr, Gamma distribution function
- gdtrc, Complemented gamma distribution function
- gels, Linear system with symmetric coefficient matrix
- hyp2f1, Gauss hypergeometric function
- hyperg, Confluent hypergeometric function
- i0, Modified Bessel function of order zero
- i0e, Exponentially scaled modified Bessel function of order zero
- i1, Modified Bessel function of order one
- i1e, Exponentially scaled modified Bessel function of order one
- igam, Incomplete gamma integral
- igamc, Complemented incomplete gamma integral
- igami, Inverse of complemented imcomplete gamma integral
- incbet, Incomplete beta integral
- incbi, Inverse of imcomplete beta integral
- isnan, Test for not a number
- isfinite, Test for infinity
- signbit, Extract sign
- iv, Modified Bessel function of noninteger order
- j0, Bessel function of order zero
- y0, Bessel function of the second kind, order zero
- j1, Bessel function of order one
- y1, Bessel function of the second kind, order one
- jn, Bessel function of integer order
- jv, Bessel function of noninteger order
- k0, Modified Bessel function, third kind, order zero
- k0e, Modified Bessel function, third kind, order zero, exponentially scaled
- k1, Modified Bessel function, third kind, order one
- k1e, Modified Bessel function, third kind, order one, exponentially scaled
- kn, Modified Bessel function, third kind, integer order
- kolmogorov, Kolmogorov, Smirnov distributions
- levnsn, Linear predictive coding
- lmdif, Levenberg-Marquardt algorithm
- log, Natural logarithm
- log10, Common logarithm
- log2, Base 2 logarithm
- lrand, Pseudorandom integer number generator
- lsqrt, Integer square root
- minv, Matrix inversion
- mtransp, Matrix transpose
- nbdtr, Negative binomial distribution
- nbdtrc, Complemented negative binomial distribution
- nbdtri, Functional inverse of negative binomial distribution
- ndtr, Normal distribution function
- erf, Error function
- erfc, Complementary error function
- ndtri, Inverse of normal distribution function
- pdtr, Poisson distribution function
- pdtrc, Complemented Poisson distribution function
- pdtri, Inverse of Poisson distribution function
- planck, Integral of Planck's black body radiation formula
- polevl, Evaluate polynomial
- p1evl, Evaluate polynomial
- polmisc, Functions of a polynomial
- polrt, Roots of a polynomial
- polylog, Polylogarithms
- polyn, Arithmetic operations on polynomials
- pow, Power function
- powi, Integer power function
- psi, Psi (digamma) function
- revers, Reversion of power series
- rgamma, Reciprocal gamma function
- round, Round to nearest or even integer
- shichi, Hyperbolic sine and cosine integrals
- sici, Sine and cosine integrals
- simpsn, Numerical integration of tabulated function
- simq, Simultaneous linear equations
- sin, Circular sine
- cos, Circular cosine
- sincos, Sine and cosine by interpolation
- sindg, Circular sine of angle in degrees
- cosdg, Circular cosine of angle in degrees
- sinh, Hyperbolic sine
- spence, Dilogarithm
- sqrt, Square root
- stdtr, Student's t distribution
- stdtri, Functional inverse of Student's t distribution
- struve, Struve function
- tan, Circular tangent
- cot, Circular cotangent
- tandg, Circular tangent of argument in degrees
- cotdg, Circular cotangent of argument in degrees
- tanh, Hyperbolic tangent
- log1p, Relative error logarithm
- expm1, Relative error exponential
- cosm1, Relative error cosine
- yn, Bessel function of second kind of integer order
- zeta, Zeta function of two arguments
- zetac, Riemann zeta function of two arguments
List of Torch-only functions
Those functions are not part of the original Cephes library
cephes.digamma(x)
Alias for cephes.psi(x)
cephes.polygamma(m, x)
The (m+1)-th derivative of the logarithm of the gamma function (see MathWorld definition).
Input:
m : non-negative integer
x : real number
Returns: (m+1)-th derivative of the logarithm of the gamma function, evaluated at x
cephes.betagrad(x, y)
The partial-derivative of the beta function, with respect to the first variable.
Input:
x : positive real number
y : positive real number
Returns: Partial-derivative of the beta function with respect to the first variable, evaluated at (x, y)
Limits
Convenience functions to check for finiteness.
cephes.nan
Stands for not a number, clearer alias for 0/0
cephes.isnan(x)
Checks if x is not a number.
Input: x : any number
Returns: true if x is cephes.nan, false otherwise
cephes.isinf(x)
Checks is a number is infinite.
Input: x : any number
Returns:** true if x is math.huge or -math.huge or cephes.nan, false otherwise.
cephes.isfinite(x)
Checks if a number is finite.
Input: x : any number
Returns: not cephes.isinf(x) and not cephes.isnan(x)
Complex numbers
cephes.new_cmplx(re, im)
Input:
re : any number, to initialize the real part
im : any number, to initalize the imaginary part
Returns: a pointer to a new Cephes FFI complex number with real part r and imaginary part im.
Unit Tests
Last but not least, the unit tests are in the folder
luasrc/tests. You can run them from your local clone of the repostiory with:
git clone https://www.github.com/jucor/torch-cephes
find torch-cephes/luasrc/tests -name "test*lua" -exec torch {} \;
Those tests will soone be automatically installed with the package, once I sort out a bit of CMake resistance.
Direct access to FFI
cephes.ffi.*
Functions directly accessible at the top of the cephes table are Lua wrappers to the actual C functions from Cephes, with extra error checking. If, for any reason, you want to get rid of this error checking and of a possible overhead, the FFI-wrapper functions can be called directly via cephes.ffi.myfunction() instead of cephes.myfunction().