Liking cljdoc? Tell your friends :D

fastmath.calculus

Integration and derivatives

Integrate univariate and multivariate functions.

  • VEGAS / VEGAS+ - Monte Carlo integration of multivariate function
  • h-Cubature - h-adaptive integration of multivariate function
  • Guass-Kronrod and Gauss-Legendre - quadrature integration of univariate functions
  • Romberg, Simpson, MidPoint and Trapezoid

Integrant is substituted in case of improper integration bounds.

Derivatives (finite differences method):

  • derivatives of any degree and any order of accuracy
  • gradient and hessian for multivariate functions
Integration and derivatives

Integrate univariate and multivariate functions.

* VEGAS / VEGAS+ - Monte Carlo integration of multivariate function
* h-Cubature - h-adaptive integration of multivariate function
* Guass-Kronrod and Gauss-Legendre - quadrature integration of univariate functions
* Romberg, Simpson, MidPoint and Trapezoid

Integrant is substituted in case of improper integration bounds.

Derivatives (finite differences method):

* derivatives of any degree and any order of accuracy
* gradient and hessian for multivariate functions
raw docstring

fastmath.complex

Complex numbers operations.

Complex numbers are represented using the [[Vec2]] type defined in the fastmath.vector namespace. A complex number $z = a + bi$ corresponds to the vector (Vec2. a b).

To create a complex number, use complex, [[vec2]], or convert from sequences/arrays using functions like fastmath.vector/seq->vec2.

The implementation correctly handles floating-point special values such as ##Inf, ##NaN, and distinguishes between +0.0 and -0.0 where necessary.

This namespace provides standard complex number operations like arithmetic (+, -, *, /), exponentiation (pow, exp, log), trigonometric functions (sin, cos, tan, etc.), and their inverses, as well as utility functions like abs, arg, conjugate, etc.

Complex numbers operations.

Complex numbers are represented using the [[Vec2]] type defined in the `fastmath.vector` namespace.
A complex number $z = a + bi$ corresponds to the vector `(Vec2. a b)`.

To create a complex number, use [[complex]], [[vec2]], or convert from sequences/arrays using functions like [[fastmath.vector/seq->vec2]].

The implementation correctly handles floating-point special values such as `##Inf`, `##NaN`, and distinguishes between `+0.0` and `-0.0` where necessary.

This namespace provides standard complex number operations like arithmetic (+, -, *, /), exponentiation (pow, exp, log), trigonometric functions (sin, cos, tan, etc.), and their inverses, as well as utility functions like `abs`, `arg`, `conjugate`, etc.
raw docstring

fastmath.core

High-performance mathematical functions and constants for Clojure, optimized for primitive double and long types.

Key features:

  • Most functions are specialized for primitive types (double and long) and are inlined for performance.
  • Primarily backed by the FastMath library and custom primitive implementations.
  • Provides an option to replace clojure.core's standard numerical operators with primitive-specialized macros.

This namespace contains functions for:

  • Basic arithmetic (+, -, *, /, etc.)
  • Comparisons and predicates (==, <, zero?, pos?, etc.)
  • Bitwise operations
  • Trigonometric and hyperbolic functions
  • Exponents, logarithms, and powers
  • Floating-point specific operations (ulp, bits manipulation)
  • Combinatorics (factorial, combinations)
  • Distance calculations
  • Interpolation and mapping
  • Utility functions (gcd, lcm, error calculation, etc.)

Primitive Math Operators:

A set of inlined macros designed to replace selected clojure.core arithmetic, comparison, and bitwise operators for potential performance gains with primitive arguments. These macros operate on double and long primitives and generally return primitive values.

Replaced operators:

  • * + - / > < >= <= == rem quot mod
  • bit-or bit-and bit-xor bit-not bit-and-not
  • bit-shift-left bit-shift-right unsigned-bit-shift-right
  • bit-set bit-clear bit-flip bit-test
  • inc dec
  • zero? neg? pos? even? odd?
  • min max
  • abs
  • Additionally: << >> >>> not==

To enable these primitive operators in your namespace, call use-primitive-operators. To revert to the original clojure.core functions, call unuse-primitive-operators. Note that the fastmath.core versions are not a complete drop-in replacement due to their primitive-specific behavior (e.g., return types), and calling unuse-primitive-operators at the end of the namespace is recommended, especially in Clojure 1.12+.

High-performance mathematical functions and constants for Clojure,
optimized for primitive `double` and `long` types.

Key features:

- Most functions are specialized for primitive types (`double` and `long`) and are inlined for performance.
- Primarily backed by the [FastMath](https://github.com/jeffhain/jafama) library and custom primitive implementations.
- Provides an option to replace `clojure.core`'s standard numerical operators with primitive-specialized macros.

This namespace contains functions for:

- Basic arithmetic (`+`, `-`, `*`, `/`, etc.)
- Comparisons and predicates (`==`, `<`, `zero?`, `pos?`, etc.)
- Bitwise operations
- Trigonometric and hyperbolic functions
- Exponents, logarithms, and powers
- Floating-point specific operations (ulp, bits manipulation)
- Combinatorics (factorial, combinations)
- Distance calculations
- Interpolation and mapping
- Utility functions (gcd, lcm, error calculation, etc.)

Primitive Math Operators:

A set of inlined macros designed to replace selected `clojure.core` arithmetic, comparison, and bitwise operators for potential performance gains with primitive arguments. These macros operate on `double` and `long` primitives and generally return primitive values.

Replaced operators:

- `* + - / > < >= <= == rem quot mod`
- `bit-or bit-and bit-xor bit-not bit-and-not`
- `bit-shift-left bit-shift-right unsigned-bit-shift-right`
- `bit-set bit-clear bit-flip bit-test`
- `inc dec`
- `zero? neg? pos? even? odd?`
- `min max`
- `abs`
- Additionally: `<< >> >>> not==`

To enable these primitive operators in your namespace, call [[use-primitive-operators]].
To revert to the original `clojure.core` functions, call [[unuse-primitive-operators]].
Note that the `fastmath.core` versions are not a complete drop-in replacement due to their primitive-specific behavior (e.g., return types), and calling `unuse-primitive-operators` at the end of the namespace is recommended, especially in Clojure 1.12+.
raw docstring

fastmath.curves

Collection of parametric curves

Collection of parametric curves
raw docstring

fastmath.efloat

(re)Implementation of EFloat/Interval from pbrt-v3/pbrt-v4.

A floating point number structure which keeps a track of error caused by operations.

(re)Implementation of EFloat/Interval from pbrt-v3/pbrt-v4.

A floating point number structure which keeps a track of error caused by operations.
raw docstring

fastmath.fields

Vector field functions.

Vector fields are functions R^2->R^2.

Names are taken from fractal flames world where such fields are call variations. Most implementations are taken from JWildfire software.

Creation

To create vector field call field multimethod with name of the field as keyword.

Some of the vector fields require additional configuration as a map of parameters as keywords and values. Call parametrization to create random one or to merge with provided.

Additionally you can provide amount parameter which is scaling factor for vector field (default: 1.0).

Derived fields

You can use several method to derive new vector field from the other one(s). Possible options are:

  • derivative, grad-x, grad-y - directional derivative of the field
  • sum - sum of two fields
  • [[multiply]] - multiplication of the fields
  • composition - composition of the fields
  • [[angles]] - angles of the field vectors

Scalar fields

You can derive scalar fields from given vector field(s):

  • jacobian - determinant of jacobian matrix
  • divergence - divergence of the field
  • cross - cross product of the fields (as a determinant of the 2x2 matrix of vectors)
  • dot - dot product
  • angle-between - angle between vectors from fields.

Combinations

The other option is to create vector field using some of the above possibilities. Combination is a tree of field operations with parametrizations. Functions:

Vector field functions.

Vector fields are functions R^2->R^2.

Names are taken from fractal flames world where such fields are call `variations`. Most implementations are taken from [JWildfire](http://jwildfire.org/) software.

### Creation

To create vector field call [[field]] multimethod with name of the field as keyword.

Some of the vector fields require additional configuration as a map of parameters as keywords and values. Call [[parametrization]] to create random one or to merge with provided.

Additionally you can provide `amount` parameter which is scaling factor for vector field (default: `1.0`).

### Derived fields

You can use several method to derive new vector field from the other one(s). Possible options are:

* [[derivative]], [[grad-x]], [[grad-y]] - directional derivative of the field
* [[sum]] - sum of two fields
* [[multiply]] - multiplication of the fields
* [[composition]] - composition of the fields
* [[angles]] - angles of the field vectors

### Scalar fields

You can derive scalar fields from given vector field(s):

* [[jacobian]] - determinant of jacobian matrix
* [[divergence]] - divergence of the field
* [[cross]] - cross product of the fields (as a determinant of the 2x2 matrix of vectors)
* [[dot]] - dot product
* [[angle-between]] - angle between vectors from fields.

### Combinations

The other option is to create vector field using some of the above possibilities. Combination is a tree of field operations with parametrizations. Functions:

* [[combine]] - create vector field randomly of from given parametrization.
* [[random-configuration]] - returns random configuration as a map
* [[randomize-configuration]] - change parametrization for given configuration.
raw docstring

fastmath.grid

Grid calculation functions.

Convert 2d coordinates into various grid coordinates and back.

Terms used:

  • cell type - grid cell shape: square, triangular, hexagonal, rhomboidal
  • coords - 2d euclidean coordinates (x,y)
  • cell - cell coordinates (q,r)
  • anchor - cell position in 2d euclidean space
  • corners - shape vertices
  • size - size of the cell.

Grids

Each grid is defined by cell type and size. Optionally you can provide translating vector.

Each cell has it's own coordinates, mostly axial based (only square has offset).

For hexagonal cell size is a radius from midpoint to corner. For the rest it is the size of the side.

Cell types are:

  • :square
  • :shifted-square
  • :triangle
  • :rhombus
  • :flat-hex - flat topped
  • :pointy-hex - pointy topped

Notes

  • Hexagonal grids are based on https://www.redblobgames.com/grids/hexagons/
  • Only hexagonal cells have anchor at the center. For the rest the anchor is at the top left vertex.
    • Anchors for triangular grids are shared between two cells: even and odd q coordinate. Even q is pointy topped, odd q is flat topped which is marked in the third coordinate of anchor.
Grid calculation functions.

Convert 2d coordinates into various grid coordinates and back.

Terms used:

* cell type - grid cell shape: square, triangular, hexagonal, rhomboidal
* coords - 2d euclidean coordinates (x,y)
* cell - cell coordinates (q,r)
* anchor - cell position in 2d euclidean space
* corners - shape vertices
* size - size of the cell.

### Grids

Each grid is defined by cell type and size. Optionally you can provide translating vector.

Each cell has it's own coordinates, mostly axial based (only square has offset).

For hexagonal cell size is a radius from midpoint to corner. For the rest it is the size of the side.

Cell types are:

* `:square`
* `:shifted-square`
* `:triangle`
* `:rhombus`
* `:flat-hex` - flat topped
* `:pointy-hex` - pointy topped

### Notes

* Hexagonal grids are based on https://www.redblobgames.com/grids/hexagons/
* Only hexagonal cells have anchor at the center. For the rest the anchor is at the top left vertex.
    * Anchors for triangular grids are shared between two cells: even and odd `q` coordinate. Even `q` is pointy topped, odd `q` is flat topped which is marked in the third coordinate of anchor.
raw docstring

fastmath.interpolation.gp

Gaussian Processes

See more here

Gaussian Processes

See more [here](https://nextjournal.com/generateme/gaussian-processes#gp%2B)
raw docstring

fastmath.kernel

Various kernel functions.

  • RBF (double -> double functions)
  • vector kernels (vector x vector -> double function; may be positive definite, conditional positive definite, positive semi-definite, mercer)
  • density estimation
  • some kernel operations
Various kernel functions.

* RBF (double -> double functions)
* vector kernels (vector x vector -> double function; may be positive definite, conditional positive definite, positive semi-definite, mercer)
* density estimation
* some kernel operations
raw docstring

fastmath.kernel.rbf

Radial Basis Functions.

Collection of RBF kernels.

Each kernel supports scale parameter.

Radial Basis Functions.

Collection of RBF kernels.

Each kernel supports `scale` parameter.
raw docstring

fastmath.kernel.variogram

Semivariograms and empirical (experimental) estimators for kriging interpolation.

Semivariogram models are created using nugget, partial sill, range and in some cases beta (exponent) parameters. All models can be fit to the empirical (experimental) semivariogram which can be created by using a variety of the estimators.

Estimators calculate gamma semivariogram for given bin h (lag) (n - number of pairs, diffs - seq of differences).

Semivariograms and empirical (experimental) estimators for kriging interpolation.

Semivariogram models are created using `nugget`, `partial sill`, `range` and in some cases `beta` (exponent) parameters. All models can be fit to the `empirical` (experimental) semivariogram which can be created by using a variety of the estimators.

Estimators calculate `gamma` semivariogram for given bin `h` (lag) (`n` - number of pairs, `diffs` - seq of differences).
raw docstring

fastmath.matrix

Provides tools for working with various matrix types, including fixed-size (2x2, 3x3, 4x4), Java double[][] arrays, and Apache Commons Math RealMatrix.

It offers efficient mathematical operations for linear algebra, geometric transformations, and data manipulation, unifying different representations under a common protocol approach where appropriate.

Provides tools for working with various matrix types, including fixed-size (2x2, 3x3, 4x4), Java `double[][]` arrays, and Apache Commons Math `RealMatrix`.

It offers efficient mathematical operations for linear algebra, geometric transformations, and data manipulation, unifying different representations under a common protocol approach where appropriate.
raw docstring

fastmath.ml.regression.contrast

Categorical data manipulation and various encoding methods.

Categorical data manipulation and various encoding methods.
raw docstring

fastmath.ml.regression.terms

Builds mappings and penalties from list of additive terms.

Builds mappings and penalties from list of additive terms.
raw docstring

fastmath.optimization

Optimization.

Namespace provides various optimization methods.

  • Brent (1d functions)
  • Bobyqa (2d+ functions)
  • Powell
  • Nelder-Mead
  • Multidirectional simplex
  • CMAES
  • Gradient
  • L-BFGS-B
  • Bayesian Optimization (see below)
  • Linear optimization

All optimizers require bounds.

Optimizers

To optimize functions call one of the following functions:

  • minimize or maximize - to perform actual optimization
  • scan-and-minimize or scan-and-maximize - functions find initial point using brute force and then perform optimization paralelly for best initialization points. Brute force scan is done using jitter low discrepancy sequence generator.

You can also create optimizer (function which performs optimization) by calling minimizer or maximizer. Optimizer accepts initial point.

All above accept:

  • one of the optimization method, ie: :brent, :bobyqa, :nelder-mead, :multidirectional-simplex, :cmaes, :gradient, :bfgs and :lbfgsb
  • function to optimize
  • parameters as a map

For parameters meaning refer Optim package

Common parameters

  • :bounds (obligatory) - search ranges for each dimensions as a seqence of [low high] pairs
  • :initial - initial point other then mid of the bounds as vector
  • :max-evals - maximum number of function evaluations
  • :max-iters - maximum number of algorithm interations
  • :bounded? - should optimizer force to keep search within bounds (some algorithms go outside desired ranges)
  • :stats? - return number of iterations and evaluations along with result
  • :rel and :abs - relative and absolute accepted errors

For scan-and-... functions additionally you can provide:

  • :N - number of brute force iterations
  • :n - fraction of N which are used as initial points to parallel optimization
  • :jitter - jitter factor for sequence generator (for scanning domain)

Specific parameters

  • BOBYQA - :number-of-points, :initial-radius, :stopping-radius
  • Nelder-Mead - :rho, :khi, :gamma, :sigma, :side-length
  • Multidirectional simples - :khi, :gamma, :side-length
  • CMAES - :check-feasable-count, :diagonal-only, :stop-fitness, :active-cma?, :population-size
  • Gradient - :bracketing-range, :formula (:polak-ribiere or :fletcher-reeves), :gradient-h (finite differentiation step, default: 0.01)

Bayesian Optimization

Bayesian optimizer can be used for optimizing expensive to evaluate black box functions. Refer this article or this article

Linear optimization

Optimization.

Namespace provides various optimization methods.

* Brent (1d functions)
* Bobyqa (2d+ functions)
* Powell
* Nelder-Mead
* Multidirectional simplex
* CMAES
* Gradient
* L-BFGS-B
* Bayesian Optimization (see below)
* Linear optimization

All optimizers require bounds.

## Optimizers

To optimize functions call one of the following functions:

* [[minimize]] or [[maximize]] - to perform actual optimization
* [[scan-and-minimize]] or [[scan-and-maximize]] - functions find initial point using brute force and then perform optimization paralelly for best initialization points. Brute force scan is done using jitter low discrepancy sequence generator.

You can also create optimizer (function which performs optimization) by calling [[minimizer]] or [[maximizer]]. Optimizer accepts initial point.

All above accept:

* one of the optimization method, ie: `:brent`, `:bobyqa`, `:nelder-mead`, `:multidirectional-simplex`, `:cmaes`, `:gradient`, `:bfgs` and `:lbfgsb`
* function to optimize
* parameters as a map

For parameters meaning refer [Optim package](https://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/index.html?org/apache/commons/math3/optim/package-summary.html)

### Common parameters

* `:bounds` (obligatory) - search ranges for each dimensions as a seqence of [low high] pairs
* `:initial` - initial point other then mid of the bounds as vector
* `:max-evals` - maximum number of function evaluations
* `:max-iters` - maximum number of algorithm interations
* `:bounded?` - should optimizer force to keep search within bounds (some algorithms go outside desired ranges)
* `:stats?` - return number of iterations and evaluations along with result
* `:rel` and `:abs` - relative and absolute accepted errors

For `scan-and-...` functions additionally you can provide:

* `:N` - number of brute force iterations
* `:n` - fraction of N which are used as initial points to parallel optimization
* `:jitter` - jitter factor for sequence generator (for scanning domain)

### Specific parameters

* BOBYQA - `:number-of-points`, `:initial-radius`, `:stopping-radius`
* Nelder-Mead - `:rho`, `:khi`, `:gamma`, `:sigma`, `:side-length`
* Multidirectional simples - `:khi`, `:gamma`, `:side-length`
* CMAES - `:check-feasable-count`, `:diagonal-only`, `:stop-fitness`, `:active-cma?`, `:population-size`
* Gradient - `:bracketing-range`, `:formula` (`:polak-ribiere` or `:fletcher-reeves`), `:gradient-h` (finite differentiation step, default: `0.01`) 

## Bayesian Optimization

Bayesian optimizer can be used for optimizing expensive to evaluate black box functions. Refer this [article](http://krasserm.github.io/2018/03/21/bayesian-optimization/) or this [article](https://nextjournal.com/a/LKqpdDdxiggRyHhqDG5FH?token=Ss1Qq3MzHWN8ZyEt9UC1ZZ)

## Linear optimization 
raw docstring

fastmath.protocols

Set of protocols for fastmath.

Includes:

  • random generator protocol
  • distribution protocols
  • vector protocol
Set of protocols for fastmath.

Includes:

* random generator protocol
* distribution protocols
* vector protocol
raw docstring

fastmath.quaternion

Operations for quaternions.

Quaternions extend complex numbers and are widely used in fields like 3D graphics and physics for representing rotations.

In fastmath, quaternions are represented as 4-dimensional vectors ([[Vec4]]) where the components correspond to the scalar part and the three imaginary parts ($i$, $j$, $k$): $q = a + bi + cj + dk$ is (Vec4. a b c d).

The namespace provides functions for creating quaternions, accessing scalar and vector parts, predicates (e.g., real?, zero?, inf?, nan?), and fundamental properties (magnitude, argument, normalization).

A comprehensive set of operations is included:

  • Arithmetic: Addition, subtraction, multiplication, division, negation, square, reciprocal, scaling, conjugation.
  • Transcendental Functions: Extensions of standard complex functions like exponential, logarithm, power, trigonometric, hyperbolic functions, and their inverses.
  • Rotations: Functions for creating rotation quaternions, rotating 3D vectors (rotate), spherical linear interpolation (SLERP), and conversions between quaternions, Euler angles (ZYX body 3-2-1 and z-y'-x''), and rotation matrices.

The implementation correctly handles floating-point special values, including ##Inf and ##NaN.

Operations for quaternions.

Quaternions extend complex numbers and are widely used in fields like 3D graphics and physics for representing rotations.

In `fastmath`, quaternions are represented as 4-dimensional vectors ([[Vec4]]) where the components correspond to the scalar part and the three imaginary parts ($i$, $j$, $k$): $q = a + bi + cj + dk$ is `(Vec4. a b c d)`.

The namespace provides functions for creating quaternions, accessing scalar and vector parts, predicates (e.g., [[real?]], [[zero?]], [[inf?]], [[nan?]]), and fundamental properties (magnitude, argument, normalization).

A comprehensive set of operations is included:
- **Arithmetic:** Addition, subtraction, multiplication, division, negation, square, reciprocal, scaling, conjugation.
- **Transcendental Functions:** Extensions of standard complex functions like exponential, logarithm, power, trigonometric, hyperbolic functions, and their inverses.
- **Rotations:** Functions for creating rotation quaternions, rotating 3D vectors ([[rotate]]), spherical linear interpolation (SLERP), and conversions between quaternions, Euler angles (ZYX body 3-2-1 and z-y'-x''), and rotation matrices.

The implementation correctly handles floating-point special values, including `##Inf` and `##NaN`.
raw docstring

fastmath.random

Various random and noise functions.

Namespace defines various random number generators (RNGs), different types of random functions, sequence generators and noise functions.

RNGs

You can use a selection of various RNGs defined in Apache Commons Math library.

Currently supported RNGs:

  • :jdk - default java.util.Random
  • :mersenne - MersenneTwister
  • :isaac - ISAAC
  • :well512a, :well1024a, :well19937a, :well19937c, :well44497a, :well44497b - several WELL variants

To create your RNG use rng multimethod. Pass RNG name and (optional) seed. Returned RNG is equipped with [[RNGProto]] protocol with methods: irandom, lrandom, frandom drandom, grandom, brandom which return random primitive value with given RNG.

(let [rng (rng :isaac 1337)]
  (irandom rng))

For conveniency default RNG (:jdk) with following functions are created: irand, lrand, frand, drand, grand, brand.

Each prefix denotes returned type:

  • i - int
  • l - long
  • f - float
  • d - double
  • g - gaussian (double)
  • b - boolean

Check individual function for parameters description.

Random Vector Sequences

Couple of functions to generate sequences of numbers or vectors.

To create generator call sequence-generator with generator name and vector size. Following generators are available:

  • :halton - Halton low-discrepancy sequence; range [0,1]
  • :sobol - Sobol low-discrepancy sequence; range [0,1]
  • :r2 - R2 low-discrepancy sequence; range [0,1], more...
  • :sphere - uniformly random distributed on unit sphere
  • :ball - uniformly random distributed from unit ball
  • :gaussian - gaussian distributed (mean=0, stddev=1)
  • :default - uniformly random; range:[0,1]

:halton, :sobol and :r2 can be also randomly jittered according to this article. Call jittered-sequence-generator.

After creation you get lazy sequence

Noise

List of continuous noise functions (1d, 2d and 3d):

  • :value - value noise
  • :gradient - gradient noise (improved Ken Perlin version)
  • :simplex - simplex noise

First two (:value and :gradient) can use 4 different interpolation types: :none, :linear, :hermite (cubic) and :quintic.

All can be combined in following variants:

Noise creation requires detailed configuration which is simple map of following keys:

  • :seed - seed as integer
  • :noise-type - type of noise: :value, :gradient (default), :simplex
  • :interpolation - type of interpolation (for value and gradient): :none, :linear, :hermite (default) or :quintic
  • :octaves - number of octaves for combined noise (like FBM), default: 6
  • :lacunarity - scaling factor for combined noise, default: 2.00
  • :gain - amplitude scaling factor for combined noise, default: 0.5
  • :normalize? - should be normalized to [0,1] range (true, default) or to [-1,1] range (false)

For usage convenience 3 ready to use functions are prepared. Returning value from [0,1] range:

  • noise - Perlin Noise (gradient noise, 6 octaves, quintic interpolation)
  • vnoise - Value Noise (as in Processing, 6 octaves, hermite interpolation)
  • simplex - Simplex Noise (6 octaves)

For random noise generation you can use random-noise-cfg and random-noise-fn. Both can be feed with configuration. Additional configuration:

  • :generator can be set to one of the noise variants, defaults to :fbm
  • :warp-scale - 0.0 - do not warp, >0.0 warp
  • :warp-depth - depth for warp (default 1.0, if warp-scale is positive)

Discrete Noise

discrete-noise is a 1d or 2d hash function for given integers. Returns double from [0,1] range.

Distribution

Various real and integer distributions. See [[DistributionProto]] and [[RNGProto]] for functions.

To create distribution call distribution multimethod with name as a keyword and map as parameters.

Various random and noise functions.

Namespace defines various random number generators (RNGs), different types of random functions, sequence generators and noise functions.

### RNGs

You can use a selection of various RNGs defined in [Apache Commons Math](http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/random/package-summary.html) library.

Currently supported RNGs:

* `:jdk` - default java.util.Random
* `:mersenne` - MersenneTwister
* `:isaac` - ISAAC
* `:well512a`, `:well1024a`, `:well19937a`, `:well19937c`, `:well44497a`, `:well44497b` - several WELL variants

To create your RNG use [[rng]] multimethod. Pass RNG name and (optional) seed. Returned RNG is equipped with [[RNGProto]] protocol with methods: [[irandom]], [[lrandom]], [[frandom]] [[drandom]], [[grandom]], [[brandom]] which return random primitive value with given RNG.

```
(let [rng (rng :isaac 1337)]
  (irandom rng))
```

For conveniency default RNG (`:jdk`) with following functions are created: [[irand]], [[lrand]], [[frand]], [[drand]], [[grand]], [[brand]].

Each prefix denotes returned type:

* i - int
* l - long
* f - float
* d - double
* g - gaussian (double)
* b - boolean

Check individual function for parameters description.

### Random Vector Sequences

Couple of functions to generate sequences of numbers or vectors.

To create generator call [[sequence-generator]] with generator name and vector size.
Following generators are available:

* `:halton` - Halton low-discrepancy sequence; range [0,1]
* `:sobol` - Sobol low-discrepancy sequence; range [0,1]
* `:r2` - R2 low-discrepancy sequence; range [0,1], [more...](http://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/)
* `:sphere` - uniformly random distributed on unit sphere
* `:ball` - uniformly random distributed from unit ball
* `:gaussian` - gaussian distributed (mean=0, stddev=1)
* `:default` - uniformly random; range:[0,1]

`:halton`, `:sobol` and `:r2` can be also randomly jittered according to this [article](http://extremelearning.com.au/a-simple-method-to-construct-isotropic-quasirandom-blue-noise-point-sequences/). Call [[jittered-sequence-generator]].

After creation you get lazy sequence

### Noise

List of continuous noise functions (1d, 2d and 3d):

* `:value` - value noise
* `:gradient` - gradient noise (improved Ken Perlin version)
* `:simplex` - simplex noise

First two (`:value` and `:gradient`) can use 4 different interpolation types: `:none`, `:linear`, `:hermite` (cubic) and `:quintic`.

All can be combined in following variants:

* Noise - pure noise value, create with [[single-noise]]
* FBM - fractal brownian motion, create with [[fbm-noise]]
* Billow - billow noise, [[billow-noise]]
* RidgedMulti - ridged multi, [[ridgedmulti-noise]]

Noise creation requires detailed configuration which is simple map of following keys:

* `:seed` - seed as integer
* `:noise-type` - type of noise: `:value`, `:gradient` (default), `:simplex`
* `:interpolation` - type of interpolation (for value and gradient): `:none`, `:linear`, `:hermite` (default) or `:quintic`
* `:octaves` - number of octaves for combined noise (like FBM), default: 6
* `:lacunarity` - scaling factor for combined noise, default: 2.00
* `:gain` - amplitude scaling factor for combined noise, default: 0.5
* `:normalize?` - should be normalized to `[0,1]` range (true, default) or to `[-1,1]` range (false)

For usage convenience 3 ready to use functions are prepared. Returning value from `[0,1]` range:

* [[noise]] - Perlin Noise (gradient noise, 6 octaves, quintic interpolation)
* [[vnoise]] - Value Noise (as in Processing, 6 octaves, hermite interpolation)
* [[simplex]] - Simplex Noise (6 octaves)

For random noise generation you can use [[random-noise-cfg]] and [[random-noise-fn]]. Both can be feed with configuration. Additional configuration:

* `:generator` can be set to one of the noise variants, defaults to `:fbm`
* `:warp-scale` - 0.0 - do not warp, >0.0 warp
* `:warp-depth` - depth for warp (default 1.0, if warp-scale is positive)

#### Discrete Noise

[[discrete-noise]] is a 1d or 2d hash function for given integers. Returns double from `[0,1]` range.

### Distribution

Various real and integer distributions. See [[DistributionProto]] and [[RNGProto]] for functions.

To create distribution call [[distribution]] multimethod with name as a keyword and map as parameters.
raw docstring

fastmath.signal

Signal processing (effect) and generation (oscillators).

Singal is any sequence with double values.

Signal processing

To process signal use apply-effects or apply-effects-raw (operates on double-array only) function.

Effect is signal filter, created by effect multimethod. Effects can be composed with compose-effects. Effect can be treated as function and can be called for given sample.

Each effect has it's own parametrization which should be passed during creation.

List of all available effects is under effects-list value.

Effects parametrization

Each effect has its own parameters.

:simple-lowpass, :simple-highpass

  • :rate - sample rate (default 44100.0)
  • :cutoff - cutoff frequency (default 2000.0)

:biquad-eq

Biquad equalizer

  • :fc - center frequency
  • :gain - gain
  • :bw - bandwidth (default: 1.0)
  • :fs - sampling rate (defatult: 44100.0)

:biquad-hs, :biquad-ls

Biquad highpass and lowpass shelf filters

  • :fc - center frequency
  • :gain - gain
  • :slope - shelf slope (default 1.5)
  • :fs - sampling rate (default 44100.0)

:biquad-lp, :biquad-hp, :biquad-bp

Biquad lowpass, highpass and bandpass filters

  • :fc - cutoff/center frequency
  • :bw - bandwidth (default 1.0)
  • :fs - sampling rate (default 44100.0)

:dj-eq

  • :high - high frequency gain (10000Hz)
  • :mid - mid frequency gain (1000Hz)
  • :low - low frequency gain (100Hz)
  • :shelf-slope - shelf slope for high frequency (default 1.5)
  • :peak-bw - peak bandwidth for mid and low frequencies (default 1.0)
  • :rate - sampling rate (default 44100.0)

:phaser-allpass

  • :delay - delay factor (default: 0.5)

:divider

  • :denom (long, default 2.0)

:fm

Modulate and demodulate signal using frequency

  • :quant - quantization value (0.0 - if no quantization, default 10)
  • :omega - carrier factor (default 0.014)
  • :phase - deviation factor (default 0.00822)

:bandwidth-limit

https://searchcode.com/file/18573523/cmt/src/lofi.cpp#

  • :rate - sample rate (default 44100.0)
  • :freq - cutoff frequency (default 1000.0)

:distort

  • :factor - distortion factor (default 1.0)

:foverdrive

Fast overdrive

  • :drive - drive (default 2.0)

:decimator

  • :bits - bit depth (default 2)
  • :fs - decimator sample rate (default 4410.0)
  • :rate - input sample rate (default 44100.0)

:basstreble

  • :bass - bass gain (default 1.0)
  • :treble - treble gain (default 1.0)
  • :gain - gain (default 0.0)
  • :rate - sample rate (default 44100.0)
  • :slope - slope for both (default 0.4)
  • :bass-freq - bass freq (default 250.0)
  • :treble-freq - treble freq (default 4000.0)

:echo

  • :delay - delay time in seconds (default 0.5)
  • :decay - decay (amount echo in signal, default 0.5)
  • :rate - sample rate (default 44100.0)

Warning! Echo filter uses mutable array as a internal state, don't use the same filter in paraller processing.

:vcf303

  • :rate - sample rate (default 44100.0)
  • :trigger - boolean, trigger some action (default false), set true when you reset filter every line
  • :cutoff - cutoff frequency (values 0-1, default 0.8)
  • :resonance - resonance (values 0-1, default 0.8)
  • :env-mod - envelope modulation (values 0-1, default 0.5)
  • :decay - decay (values 0-1, default 1.0)
  • :gain - gain output signal (default: 1.0)

:slew-limit

http://git.drobilla.net/cgit.cgi/omins.lv2.git/tree/src/slew_limiter.c

  • :rate - sample rate
  • :maxrise - maximum change for rising signal (in terms of 1/rate steps, default 500)
  • :maxfall - maximum change for falling singal (default 500)

:mda-thru-zero

  • :rate - sample rate
  • :speed - effect rate
  • :depth
  • :mix
  • :depth-mod
  • :feedback

Warning: internal state is kept in doubles array.

Oscillators

oscillator creates function which generates signal value for given time.

To sample generated wave to signal, call oscillator->signal with following parameters:

  • f - oscillator
  • samplerate - sample rate (samples per second)
  • seconds - duration

To convert signal to oscillator (using interpolation) use signal->oscillator passing signal and duration.

Add oscillators using oscillators-sum.

Smoothing filter

Savitzky-Golay smoothing filter savgol-filter.

File operations

You can save-signal or load-signal. Representation is 16 bit signed, big endian. Use Audacity or SoX to convert to/from audio files.

Signal processing (effect) and generation (oscillators).

Singal is any sequence with double values.

## Signal processing

To process signal use [[apply-effects]] or [[apply-effects-raw]] (operates on `double-array` only) function.

Effect is signal filter, created by [[effect]] multimethod. Effects can be composed with [[compose-effects]]. Effect can be treated as function and can be called for given sample.

Each effect has it's own parametrization which should be passed during creation.

List of all available effects is under [[effects-list]] value.

### Effects parametrization

Each effect has its own parameters.

#### :simple-lowpass, :simple-highpass

* `:rate` - sample rate (default 44100.0)
* `:cutoff` - cutoff frequency (default 2000.0)

#### :biquad-eq

Biquad equalizer

* `:fc` - center frequency
* `:gain` - gain
* `:bw` - bandwidth (default: 1.0)
* `:fs` - sampling rate (defatult: 44100.0)

#### :biquad-hs, :biquad-ls

Biquad highpass and lowpass shelf filters

* `:fc` - center frequency
* `:gain` - gain
* `:slope` - shelf slope (default 1.5)
* `:fs` - sampling rate (default 44100.0)

#### :biquad-lp, :biquad-hp, :biquad-bp

Biquad lowpass, highpass and bandpass filters

* `:fc` - cutoff/center frequency
* `:bw` - bandwidth (default 1.0)
* `:fs` - sampling rate (default 44100.0)

#### :dj-eq

* `:high` - high frequency gain (10000Hz)
* `:mid` - mid frequency gain (1000Hz)
* `:low` - low frequency gain (100Hz)
* `:shelf-slope` - shelf slope for high frequency (default 1.5)
* `:peak-bw` - peak bandwidth for mid and low frequencies (default 1.0)
* `:rate` - sampling rate (default 44100.0)

#### :phaser-allpass

* `:delay` - delay factor (default: 0.5)

#### :divider

* `:denom` (long, default 2.0)

#### :fm

Modulate and demodulate signal using frequency

 * `:quant` - quantization value (0.0 - if no quantization, default 10)
 * `:omega` - carrier factor (default 0.014)
 * `:phase` - deviation factor (default 0.00822)

#### :bandwidth-limit

https://searchcode.com/file/18573523/cmt/src/lofi.cpp#

* `:rate` - sample rate (default 44100.0)
* `:freq` - cutoff frequency (default 1000.0)

#### :distort

* `:factor` - distortion factor (default 1.0)

#### :foverdrive

Fast overdrive

* `:drive` - drive (default 2.0)

#### :decimator

* `:bits` - bit depth (default 2)
* `:fs` - decimator sample rate (default 4410.0)
* `:rate` - input sample rate (default 44100.0)

#### :basstreble

* `:bass` - bass gain (default 1.0)
* `:treble` - treble gain (default 1.0)
* `:gain` - gain (default 0.0)
* `:rate` - sample rate (default 44100.0)
* `:slope` - slope for both (default 0.4)
* `:bass-freq` - bass freq (default 250.0)
* `:treble-freq` - treble freq (default 4000.0)

#### :echo

* `:delay` - delay time in seconds (default 0.5)
* `:decay` - decay (amount echo in signal, default 0.5)
* `:rate` - sample rate (default 44100.0)

_Warning! Echo filter uses mutable array as a internal state, don't use the same filter in paraller processing._

#### :vcf303

* `:rate` - sample rate (default 44100.0)
* `:trigger` - boolean, trigger some action (default `false`), set true when you reset filter every line
* `:cutoff` - cutoff frequency (values 0-1, default 0.8)
* `:resonance` - resonance (values 0-1, default 0.8)
* `:env-mod` - envelope modulation (values 0-1, default 0.5)
* `:decay` - decay (values 0-1, default 1.0)
* `:gain` - gain output signal (default: 1.0)

#### :slew-limit

http://git.drobilla.net/cgit.cgi/omins.lv2.git/tree/src/slew_limiter.c

* `:rate` - sample rate
* `:maxrise` - maximum change for rising signal (in terms of 1/rate steps, default 500)
* `:maxfall` - maximum change for falling singal (default 500)

#### :mda-thru-zero

* `:rate` - sample rate
* `:speed` - effect rate
* `:depth`
* `:mix`
* `:depth-mod`
* `:feedback`

_Warning: internal state is kept in doubles array._

## Oscillators

[[oscillator]] creates function which generates signal value for given time.

To sample generated wave to signal, call [[oscillator->signal]] with following parameters:

* `f` - oscillator
* `samplerate` - sample rate (samples per second)
* `seconds` - duration

To convert signal to oscillator (using interpolation) use [[signal->oscillator]] passing signal and duration.

Add oscillators using [[oscillators-sum]].

## Smoothing filter

Savitzky-Golay smoothing filter [[savgol-filter]].

## File operations

You can [[save-signal]] or [[load-signal]]. Representation is 16 bit signed, big endian. Use Audacity or SoX to convert to/from audio files.
raw docstring

fastmath.special

Special functions for real arguments and value.

  • Bessel J, Y, jinc
  • Modified Bessel I, K
  • Spherical Bessel j, y
  • Modified spherical Bessel i1, i2, k
  • Gamma, log, digamma, trigamma, polygamma, regularized, lower/upper incomplete
  • Beta, log, regularized, incomplete
  • Erf, inverse
  • Airy A, B with derivatives
  • Zeta (Riemann, Hurwitz), Eta (Dirichlet), Xi (Landau), Beta (Dirichlet)
  • Integrals: Si, Ci, li/Li, Ei, En, Ein
  • Hypergeometric 0F0, 0F1, 1F0, 1F1, 2F1, 2F0, 0F2, pFq, Kummers M, Tricomis U, Whittaker M and W
  • Lambert W (0 and -1)
  • Minkowski
  • Harmonic H
  • Owen's T
  • Complex: (log)Gamma, Hypergeometric pFq, Tricomis U
Special functions for real arguments and value.

* Bessel J, Y, jinc
* Modified Bessel I, K 
* Spherical Bessel j, y
* Modified spherical Bessel i1, i2, k
* Gamma, log, digamma, trigamma, polygamma, regularized, lower/upper incomplete
* Beta, log, regularized, incomplete
* Erf, inverse
* Airy A, B with derivatives
* Zeta (Riemann, Hurwitz), Eta (Dirichlet), Xi (Landau), Beta (Dirichlet)
* Integrals: Si, Ci, li/Li, Ei, En, Ein
* Hypergeometric 0F0, 0F1, 1F0, 1F1, 2F1, 2F0, 0F2, pFq, Kummers M, Tricomis U, Whittaker M and W
* Lambert W (0 and -1)
* Minkowski
* Harmonic H
* Owen's T
* Complex: (log)Gamma, Hypergeometric pFq, Tricomis U 
raw docstring

fastmath.stats

Namespace provides a comprehensive collection of functions for performing statistical analysis in Clojure. It focuses on providing efficient implementations for common statistical tasks, leveraging fastmath's underlying numerical capabilities.

This namespace covers a wide range of statistical methods, including:

  • Descriptive Statistics: Measures of central tendency (mean, median, mode, expectile), dispersion (variance, standard deviation, MAD, SEM), and shape (skewness, kurtosis, L-moments).
  • Quantiles and Percentiles: Functions for calculating percentiles, quantiles, and the median, including weighted versions and various estimation strategies.
  • Intervals and Extents: Methods for defining ranges within data, such as span, IQR, standard deviation/MAD/SEM extents, percentile/quantile intervals, prediction intervals (PI, HPDI), and fence boundaries for outlier detection.
  • Outlier Detection: Functions for identifying data points outside conventional fence boundaries.
  • Data Transformation: Utilities for scaling, centering, trimming, winsorizing, and applying power transformations (Box-Cox, Yeo-Johnson) to data.
  • Correlation and Covariance: Measures of the linear and monotonic relationship between two or more variables (Pearson, Spearman, Kendall), and functions for generating covariance and correlation matrices.
  • Distance and Similarity Metrics: Functions for quantifying differences or likeness between data sequences or distributions, including error metrics (MAE, MSE, RMSE), L-p norms, and various distribution dissimilarity/similarity measures.
  • Contingency Tables: Functions for creating, analyzing, and deriving measures of association and agreement (Cramer's V, Cohen's Kappa) from contingency tables, including specialized functions for 2x2 tables.
  • Binary Classification Metrics: Functions for generating confusion matrices and calculating a wide array of performance metrics (Accuracy, Precision, Recall, F1, MCC, etc.).
  • Effect Size: Measures quantifying the magnitude of statistical effects, including difference-based (Cohen's d, Hedges' g, Glass's delta), ratio-based, ordinal/non-parametric (Cliff's Delta, Vargha-Delaney A), and overlap-based (Cohen's U, p-overlap), as well as measures related to explained variance (Eta-squared, Omega-squared, Cohen's f²).
  • Statistical Tests: Functions for performing hypothesis tests, including:
    • Normality and Shape tests (Skewness, Kurtosis, D'Agostino-Pearson K², Jarque-Bera, Bonett-Seier).
    • Binomial tests and confidence intervals.
    • Location tests (one-sample and two-sample T/Z tests, paired/unpaired).
    • Variance tests (F-test, Levene's, Brown-Forsythe, Fligner-Killeen).
    • Goodness-of-Fit and Independence tests (Power Divergence family including Chi-squared, G-test; AD/KS tests).
    • ANOVA and Rank Sum tests (One-way ANOVA, Kruskal-Wallis).
    • Autocorrelation tests (Durbin-Watson).
  • Time Series Analysis: Functions for analyzing the dependence structure of time series data, such as Autocorrelation (ACF) and Partial Autocorrelation (PACF).
  • Histograms: Functions for computing histograms and estimating optimal binning strategies.

This namespace aims to provide a robust set of statistical tools for data analysis and modeling within the Clojure ecosystem.

Namespace provides a comprehensive collection of functions for
performing statistical analysis in Clojure. It focuses on providing efficient
implementations for common statistical tasks, leveraging fastmath's underlying
numerical capabilities.

This namespace covers a wide range of statistical methods, including:

*   **Descriptive Statistics**: Measures of central tendency (mean, median, mode, expectile),
    dispersion (variance, standard deviation, MAD, SEM), and shape (skewness, kurtosis, L-moments).
*   **Quantiles and Percentiles**: Functions for calculating percentiles, quantiles, and the median,
    including weighted versions and various estimation strategies.
*   **Intervals and Extents**: Methods for defining ranges within data, such as span, IQR,
    standard deviation/MAD/SEM extents, percentile/quantile intervals, prediction intervals (PI, HPDI),
    and fence boundaries for outlier detection.
*   **Outlier Detection**: Functions for identifying data points outside conventional fence boundaries.
*   **Data Transformation**: Utilities for scaling, centering, trimming, winsorizing,
    and applying power transformations (Box-Cox, Yeo-Johnson) to data.
*   **Correlation and Covariance**: Measures of the linear and monotonic relationship
    between two or more variables (Pearson, Spearman, Kendall), and functions for
    generating covariance and correlation matrices.
*   **Distance and Similarity Metrics**: Functions for quantifying differences or
    likeness between data sequences or distributions, including error metrics (MAE, MSE, RMSE),
    L-p norms, and various distribution dissimilarity/similarity measures.
*   **Contingency Tables**: Functions for creating, analyzing, and deriving measures
    of association and agreement (Cramer's V, Cohen's Kappa) from contingency tables,
    including specialized functions for 2x2 tables.
*   **Binary Classification Metrics**: Functions for generating confusion matrices
    and calculating a wide array of performance metrics (Accuracy, Precision, Recall, F1, MCC, etc.).
*   **Effect Size**: Measures quantifying the magnitude of statistical effects,
    including difference-based (Cohen's d, Hedges' g, Glass's delta), ratio-based,
    ordinal/non-parametric (Cliff's Delta, Vargha-Delaney A), and overlap-based (Cohen's U, p-overlap),
    as well as measures related to explained variance (Eta-squared, Omega-squared, Cohen's f²).
*   **Statistical Tests**: Functions for performing hypothesis tests, including:
    -   Normality and Shape tests (Skewness, Kurtosis, D'Agostino-Pearson K², Jarque-Bera, Bonett-Seier).
    -   Binomial tests and confidence intervals.
    -   Location tests (one-sample and two-sample T/Z tests, paired/unpaired).
    -   Variance tests (F-test, Levene's, Brown-Forsythe, Fligner-Killeen).
    -   Goodness-of-Fit and Independence tests (Power Divergence family including Chi-squared, G-test; AD/KS tests).
    -   ANOVA and Rank Sum tests (One-way ANOVA, Kruskal-Wallis).
    -   Autocorrelation tests (Durbin-Watson).
*   **Time Series Analysis**: Functions for analyzing the dependence structure of
    time series data, such as Autocorrelation (ACF) and Partial Autocorrelation (PACF).
*   **Histograms**: Functions for computing histograms and estimating optimal binning strategies.

This namespace aims to provide a robust set of statistical tools for data analysis
and modeling within the Clojure ecosystem.
raw docstring

fastmath.transform

Transforms.

See transformer and [[TransformProto]] for details.

Wavelet

Based on JWave library.

Be aware that some of the wavelet types doesn't work properly. :battle-23, :cdf-53, :cdf-97.

Cos/Sin/Hadamard

Orthogonal or standard fast sine/cosine/hadamard 1d transforms.

Fourier

DFT, FFT, DHT.

Transforms.

See [[transformer]] and [[TransformProto]] for details.

### Wavelet

Based on [JWave](https://github.com/cscheiblich/JWave/) library.

Be aware that some of the wavelet types doesn't work properly. `:battle-23`, `:cdf-53`, `:cdf-97`.

### Cos/Sin/Hadamard

Orthogonal or standard fast sine/cosine/hadamard 1d transforms.

### Fourier

DFT, FFT, DHT.
raw docstring

fastmath.vector

Provides mathematical vector operations for various vector types, inspired by libraries like Processing and openFrameworks.

Supported vector representations include:

  • Fixed-size custom types: Vec2 (2D), Vec3 (3D), Vec4 (4D), and ArrayVec (N-dimensional wrapper around double[]).
  • Built-in array type: double arrays ([D).
  • Variable-size Clojure collections: persistent vectors ([]) and sequences (ISeq).
  • Numbers: Treated as 1D vectors.

Most operations are defined via the [[VectorProto]] protocol, which is extended for all supported types.

These vector types also implement standard Clojure/Java protocols like Seqable, Indexed, IFn, Counted, Associative, IReduce, ILookup, etc., enabling them to be used flexibly as sequences, arrays, or functions.

Provides mathematical vector operations for various vector types, inspired by libraries like Processing and openFrameworks.

Supported vector representations include:

*   **Fixed-size custom types**: `Vec2` (2D), `Vec3` (3D), `Vec4` (4D), and `ArrayVec` (N-dimensional wrapper around `double[]`).
*   **Built-in array type**: `double` arrays (`[D`).
*   **Variable-size Clojure collections**: persistent vectors (`[]`) and sequences (`ISeq`).
*   **Numbers**: Treated as 1D vectors.

Most operations are defined via the [[VectorProto]] protocol, which is extended for all supported types.

These vector types also implement standard Clojure/Java protocols like `Seqable`, `Indexed`, `IFn`, `Counted`, `Associative`, `IReduce`, `ILookup`, etc., enabling them to be used flexibly as sequences, arrays, or functions.
raw docstring

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
Move to previous article
Move to next article
Ctrl+/Jump to the search field
× close