lomath.js

basics

combinatorics

composition

initialization

matrices

native-Math

plotting

properties

regexp

signature

statistics

timing

transformation

trend

vector

Methods

Properties

npm version Build Status Coverage Status Dependency Status

Lomath is a tensorial math library extended from lodash, with performant math functions applicable to tensors(multi-arrays). It also has a standalone plotting module that using HighCharts and BrowserSync.

See the API documentation. For the included functions, see the lodash API documentation.

Community

Join the chat at https://gitter.im/kengz/lomath

Installation

Installation:

npm install lomath

To use the plotting module, do:

// in the terminal at your project's root, do:
cd node_modules/lomath
npm install

Usage

See the API documentation and lodash API documentation for example usage.

Lomath comes with the latest version of lodash, and more. Use it as you would normally use lodash or underscore, and it has many math functions familiar to users of the R language.

For clearer terminology, we call tensors the generic data structures:

data structure terminology
0 scalar = rank-0 tensor
[1, 2, 3] vector = rank-1 tensor
[[1, 2], [3, 4]] matrix = rank-2 tensor
...and so on rank-n tensor

You can also extend lomath and define your own function that applies to tensors, using the function composition module such as _.distribute, _.asso, etc.

Plotting Module

Sample plot

lomath comes with a standalone plotting module that using HighCharts and BrowserSync. Just run your JS file normally when you plot (example below), and it will automatically pull up a browser showing you the charts; you can save them!

Demo: see demo/demo.js for magic.

var _ = require('lomath');

// use lodash as usual
var v = _.range(10);

// lomath: generalized math functions applicable to multi-array
var vv = _.square(v);

console.log(v);
console.log(vv);

// prints all the functions in lomath
// console.log(_.functions(_));


// data visualization: highcharts plotter
// call contructor of highcharts plotter. Note the ()
var hc = _.hc();

// first, list all you wish to plot.
hc.plot(
    [{
        name: "linear",
        data: v
    }, {
        name: "square",
        data: vv
    }],
    "Title 1"
    )

hc.plot(
    [{
        name: "log",
        data: _.log(v)
    }],
    "Title 2"
    )

//optionally you can use the original HighCharts plot options object by:
hc.advPlot(HighChartsOptions);

// Magic here! Finally, the command to render all the plots above.
// Pulls up a browser (default to chrome for better support) with the charts.
// calling hc.render(true) will autosave all plots to your downloads folder.
hc.render();

Roadmap

API documentation

“basics” Methods

add([...X])

#

Adds tensors using _.assodist.

Arguments

  1. [...X] (...tensors): tensors.

Returns

(tensor): A tensor.

Example

_.add(1, 2, 3)
// → 6

_.add(1, [1, 2, 3])
// → [2, 3, 4]

_.add(1, [[1, 2], [3, 4]])
// → [[2, 3], [4, 5]]

_.add([10, 20], [[1, 2], [3, 4]])
// → [[11, 12], [23, 24]]

c([...X])

#

Concatenates all arguments into single vector by _.flattenDeep.

Arguments

  1. [...X] (...tensors): tensors.

Returns

(vector): A vector with the scalars from all tensors.

Example

_.c('a', 'b', 'c')
// → ['a', 'b', 'c']

_.c(1, ['a', 'b', 'c'], 2)
// → [1, 'a', 'b', 'c', 2]

_.c([[1, 2], [3, 4])
// → [1, 2, 3, 4]

divide([...X])

#

Divides tensors using _.assodist.

Arguments

  1. [...X] (...tensors): tensors.

Returns

(tensor): A tensor.

Example

_.divide(3, 2, 1)
// → 1.5

_.divide([1, 2, 3], 2)
// → [0.5, 1, 1.5]

_.divide([[1, 2], [3, 4]], 2)
// → [[0.5, 1], [1.5, 2]]

_.divide([[1, 2], [3, 4]], [1, 2])
// → [[1, 2], [1.5, 2]]

fsum(T, fn)

#

Functional sum, Basically Sigma_i fn(T[i]) with fn(T, i), where T is a tensor, i is first level index.

Arguments

  1. T (tensor): A tensor.
  2. fn (function): A function fn(T, i) applied to the i-th term of T for the sum. Note the function can access the whole T for any term i for greater generality.

Returns

(scalar): A scalar summed from all the terms from the mapped T fn(T, i).

Example

// sum of the elements multiplied by indices in a sequence, i.e. Sigma_i i*(x_i)
_.fsum([1,1,1], function(T, i){
  return T[i] * i;
})
// → 0+1+2

log(T, [n=e])

#

Takes the log of tensor T to base n (defaulted to e) element-wise using _.distribute.

Arguments

  1. T (tensor): A tensor.
  2. [n=e] (number): The optional base; defaulted to e.

Returns

(tensor): A tensor.

Example

_.log([1, Math.E])
// → [0, 1]

logistic(T)

#

Applies the logistic (sigmoid) function to tensor T element-wise.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): A tensor.

Example

_.logistic([-10, 0, 10])
// → [ 0.00004539786870243441, 0.5, 0.9999546021312976 ]

multiply([...X])

#

Multiplies tensors using _.assodist.

Arguments

  1. [...X] (...tensors): tensors.

Returns

(tensor): A tensor.

Example

_.multiply(1, 2, 3)
// → 6

_.multiply(1, [1, 2, 3])
// → [1, 2, 3]

_.multiply(1, [[1, 2], [3, 4]])
// → [[1, 2], [3, 4]]

_.multiply([10, 20], [[1, 2], [3, 4]])
// → [[10, 20], [60, 80]]

prod([...X])

#

Multiplies together all scalars in all argument tensors.

Arguments

  1. [...X] (...tensors): tensors.

Returns

(scalar): A product scalar from all scalars in the tensors.

Example

_.prod(1, 2, 3)
// → 6

_.prod([1, 2, 3])
// → 6

_.prod(1, [1, 2, 3], [[1, 2], [3, 4]])
// → 144

root(T, [n=2])

#

Takes the n-th root (defaulted to 2) of tensor T element-wise using _.distribute.

Arguments

  1. T (tensor): A tensor.
  2. [n=2] (number): The optional base; defaulted to 2 for squareroot.

Returns

(tensor): A tensor.

Example

_.root([1, 4])
// → [1, 2]

_.root([-1, -8], 3)
// → [-1, -2]

square(T)

#

Squares a tensor element-wise using _.distributeSingle.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): A tensor.

Example

_.square([1, 2])
// → [1, 4]

subtract([...X])

#

Subtracts tensors using _.assodist.

Arguments

  1. [...X] (...tensors): tensors.

Returns

(tensor): A tensor.

Example

_.subtract(1, 2, 3)
// → -5

_.subtract(1, [1, 2, 3])
// → [0, -1, -2]

_.subtract(1, [[1, 2], [3, 4]])
// → [[0, -1], [-2, -3]]

_.subtract([10, 20], [[1, 2], [3, 4]])
// → [[9, 8], [17, 16]]

sum([...X])

#

Sums all scalars in all argument tensors.

Arguments

  1. [...X] (...tensors): tensors.

Returns

(scalar): A scalar summed from all scalars in the tensors.

Example

_.sum('a', 'b', 'c')
// → 'abc'

_.sum(0, [1, 2, 3], [[1, 2], [3, 4])
// → 16

“combinatorics” Methods

combList(n, r)

#

Generates the indices of n-choose-r. Calls _.subset internally, chooses the array with string length r, and converts to numbers.

Arguments

  1. n (number): The number of items to choose.
  2. r (number): The number of items chosen.

Returns

(Array): T The array of index arrays specifying the subset indices.

Example

_.combList(3, 2)
// → [ [ 0, 1 ], [ 0, 2 ], [ 1, 2 ] ]

combination(n, r)

#

Returns n-choose-r.

Arguments

  1. n (number): The integer.
  2. r (number): The integer.

Returns

(number): nCr

Example

_.combination(1000, 1)
// → 1000

_.combination(1000, 1000) // No integer overflow; uses symmetry.
// → 1

_.combination(1000, 500) // Inevitable overflow.
// → NaN

factorial(n)

#

Returns n!.

Arguments

  1. n (number): The integer.

Returns

(number): n!

Example

_.factorial(5)
// → 120

genAry(length, N)

#

Generates all the strings of N-nary numbers up to length.

Arguments

  1. length (number): The length of the N-nary numbers.
  2. N (number): The number base.

Returns

(Array): T The array of strings of the N-nary numbers.

Example

_.genAry(3, 2) // binary, length 3
// → ['000', '001', '010', '011', '100', '101', '110', '111']

_.genAry(2, 3) // ternary, length 2
// → ['00', '01', '02', '10', '11', '12', '20', '21', '22']

pSubset(n)

#

Generates all the permutation subset indices of n items.

Arguments

  1. n (number): The number of items to permute.

Returns

(Array): T The array of strings of length n, specifying the permutation indices.

Example

_.pSubset(3)
// → [
// ['0', '1', '2'],
// ['01', '02', '10', '12', '20', '21'],
// ['012', '021', '102', '120', '201', '210']
// ]

permList(n, r)

#

Generates the indices of n-permute-r. Calls _.pSubset internally, chooses the array with string length r, and converts to numbers.

Arguments

  1. n (number): The number of items to permute.
  2. r (number): The number of items chosen.

Returns

(Array): T The array of index arrays specifying the permutation indices.

Example

_.permList(3, 2)
// → [ [ 0, 1 ], [ 0, 2 ], [ 1, 0 ], [ 1, 2 ], [ 2, 0 ], [ 2, 1 ] ]

permutation(n, r)

#

Returns n-permute-r.

Arguments

  1. n (number): The integer.
  2. r (number): The integer.

Returns

(number): nPr

Example

_.permutation(5, 5)
// → 120

_.permutation(1000, 1)
// → 1000

permute(n)

#

Generates the permutation indices of n items in lexicographical order.

Arguments

  1. n (number): The number of items to permute.

Returns

(Array): T The array of index arrays specifying the permutation indices.

Example

_.permute(3)
// → [
// [ 0, 1, 2 ],
// [ 0, 2, 1 ],
// [ 1, 0, 2 ],
// [ 1, 2, 0 ],
// [ 2, 0, 1 ],
// [ 2, 1, 0 ]
// ]

subset(n)

#

Generates all the (combination) subset indices of n items.

Arguments

  1. n (number): The number of items to choose.

Returns

(Array): T The array of strings of length n, specifying the subset indices.

Example

_.subset(3)
// → [
// ['0', '1', '2'],
// ['01', '02', '12'],
// ['012']
// ]

toNumArr(strings)

#

Converts an array of strings to array of array of numbers. Used with _.genAry and related number/subset-generating functions.

Arguments

  1. strings (Array): The strings of numbers to convert into arrays.

Returns

(Array): T The array of array of numbers from the strings.

Example

_.toNumArr(['00', '01', '10', '11']) // binary, length 2
// → [[0, 0], [0, 1], [1, 0], [1, 1]]

“composition” Methods

asso(fn, [...x])

#

Generic association: take the arguments object or array and apply atomic function (with scalar arguments) from left to right.

Arguments

  1. fn (Function): An atomic binary function (both arguments must be scalars).
  2. [...x] (...number): Scalars; can be grouped in a single array.

Returns

(number): A scalar from the function applied to all arguments in order.

Example

_.asso(_.op, 'a', 'b', 'c')
// where _.op is used to show the order of composition
// → 'a*b*c'

_.asso(_.op, ['a', 'b', 'c'])
// → 'a*b*c'

assodist(fn, [...X])

#

Generic association with distributivity: Similar to _.asso but is for tensor functions; apply atomic fn distributively in order using _.distribute. Usage: for applying fn on tensors element-wise if they have compatible dimensions.

Arguments

  1. fn (Function): An atomic binary function (both arguments must be scalars).
  2. [...X] (...tensors): tensors.

Returns

(tensor): A tensor from the function applied to all arguments in order.

Example

_.assodist(_.op, 'a', 'b', 'c')
// where _.op is used to show the order of composition
// → 'a*b*c'

_.assodist(_.op, 'a', [1, 2, 3], 'b')
// → ['a*1*b', 'a*2*b', 'a*3*b']

_.assodist(_.op, 'a', [[1, 2], [3, 4]])
// → [['a*1', 'a*2'], ['a*3', 'a*4']]

_.assodist(_.op, ['a', 'b'], [[1, 2], [3, 4]])
// → [['a*1', 'a*2'], ['b*3', 'b*4']]

distribute(fn, X, Y)

#

Generic Distribution: Distribute fn between left tensor X and right tensor Y, while preserving the argument-ordering (vital for non-commutative functions). Pairs up the tensors term-wise while descending down the depths recursively using _.distributeBoth, until finding a scalar to _.distributeLeft/Right.

Arguments

  1. fn (Function): A binary function.
  2. X (tensor): A tensor.
  3. Y (tensor): A tensor.

Returns

(tensor): A tensor from the function applied element-wise between X and Y.

Example

_.distribute(_.op, 'a', [1, 2, 3])
// where _.op is used to show the order of composition
// → ['a*1', 'a*2', 'a*3']

_.distribute(_.op, 'a', [[1, 2], [3, 4])
// → [ [ 'a*1', 'a*2' ], [ 'a*3', 'a*4' ] ]

_.distribute(_.op, ['a', 'b', 'c'], [1, 2, 3])
// → [ 'a*1', 'b*2', 'c*3' ]

_.distribute(_.op, ['a', 'b', 'c'], [1, 2, 3, 4, 5, 6])
// → [ 'a*1', 'b*2', 'c*3' , 'a*4', 'b*5', 'c*6']

_.distribute(_.op, ['a', 'b', 'c'], [[1, 2], [3, 4], [5, 6]])
// → [ [ 'a*1', 'a*2' ], [ 'b*3', 'b*4' ], [ 'c*5', 'c*6' ] ]

distributeBoth(fn, X, Y)

#

Distributes a binary function between non-scalar tensors X, Y: pair them up term-wise and calling _.distribute recursively. Perserves the order of arguments. If at any depth X and Y have different lengths, recycle if the mod of lengths is 0.

Arguments

  1. fn (Function): A binary function.
  2. X (tensor): A non-scalar tensor.
  3. Y (tensor): A non-scalar tensor.

Returns

(tensor): A tensor from the function applied element-wise between X and Y.

Example

_.distributeBoth(_.op, ['a', 'b', 'c'], [1, 2, 3])
// where _.op is used to show the order of composition
// → [ 'a*1', 'b*2', 'c*3' ]

_.distributeBoth(_.op, ['a', 'b', 'c'], [1, 2, 3, 4, 5, 6])
// → [ 'a*1', 'b*2', 'c*3' , 'a*4', 'b*5', 'c*6']

_.distributeBoth(_.op, ['a', 'b', 'c'], [[1, 2], [3, 4], [5, 6]])
// → [ [ 'a*1', 'a*2' ], [ 'b*3', 'b*4' ], [ 'c*5', 'c*6' ] ]

distributeLeft(fn, X, y)

#

Distributes a binary function with left tensor X over right scalar y. Preserves the order of arguments.

Arguments

  1. fn (Function): A binary function.
  2. X (tensor): A non-scalar tensor.
  3. y (number): A scalar.

Returns

(tensor): A tensor from the function applied element-wise between X and y.

Example

_.distributeLeft(_.op([1, 2, 3, 4], 5))
// where _.op is used to show the order of composition
// → [ '1*5', '2*5', '3*5', '4*5' ]

_.distributeLeft(_.op, [[1, 2], [3, 4]], 5)
// → [ [ '1*5', '2*5' ], [ '3*5', '4*5' ] ]

distributeRight(fn, x, Y)

#

Distributes a binary function with left scalar x over right tensor Y. Preserves the order of arguments.

Arguments

  1. fn (Function): A binary function.
  2. x (number): A scalar.
  3. Y (tensor): A non-scalar tensor.

Returns

(tensor): A tensor from the function applied element-wise between x and Y.

Example

_.distributeRight(_.op, 5, [1, 2, 3, 4])
// where _.op is used to show the order of composition
// → [ '5*1', '5*2', '5*3', '5*4' ]

_.distributeRight(_.op, 5, [[1, 2], [3, 4]])
// → [ [ '5*1', '5*2' ], [ '5*3', '5*4' ] ]

distributeSingle(fn, Y)

#

Distributes a unary function over every scalar in tensor Y.

Arguments

  1. fn (Function): A unary function.
  2. Y (tensor): A non-scalar tensor.

Returns

(tensor): A tensor from the function applied element-wise to Y.

Example

_.distributeSingle(_.square, [1, 2, 3, 4])
// → [ 1, 4, 9, 16 ]

_.distributeSingle(_.square, [[1, 2], [3, 4]])
// → [ [ 1, 4 ], [ 9, 16 ] ]

op(x, y)

#

Sample operation to demonstrate function composition.

Arguments

  1. x (*): An argument.
  2. y (*): An argument.

Example

_.op('a', 'b')
// → 'a*b'

“initialization” Methods

numeric(N, [val=0])

#

Returns an initialized array of length N filled with the value (defaulted to 0). Reminiscent of numeric() of R.

Arguments

  1. N (number): The length of array.
  2. [val=0] (*): The value to fill array with.

Returns

(Array): filled An array initialized to the value.

Example

_.numeric(3)
// → [0, 0, 0]

_.numeric(3, 'a')
// → ['a', 'a', 'a']

seq([start=0], end, [step=1])

#

Returns a sequence of numbers from start to end, with interval. Similar to lodash's _.range but the default starts from 1; this is for R users who are familiar with seq().

Arguments

  1. [start=0] (number): The start value.
  2. end (number): The end value.
  3. [step=1] (number): The interval step.

Returns

(Array): seq An array initialized to the sequence.

Example

_.seq(3)
// → [1, 2, 3]

_.seq(2, 4)
// → [2, 3, 4]

_.seq(1, 9, 2)
[ 1, 3, 5, 7, 9 ]

“matrices” Methods

adj(M)

#

Returns the adjugate matrix, i.e. the transpose of the comatrix.

Arguments

  1. M (tensor): The original matrix.

Returns

(tensor): A The adj matrix.

Example

_.adj([[1,2,3],[4,5,6],[11,13,17]])
// → [ [ 7, 5, -3 ], [ -2, -16, 6 ], [ -3, 9, -3 ] ]

coMatrix(M)

#

Returns the comatrix, i.e. the minor matrix or matrix of cofactors, of M.

Arguments

  1. M (tensor): The original matrix.

Returns

(tensor): C The comatrix.

Example

_.coMatrix([[1,2,3],[4,5,6],[11,13,17]])
// → [ [ 7, -2, -3 ], [ 5, -16, 9 ], [ -3, 6, -3 ] ]

coSubMatrix(M, [r=0], [c=0])

#

Returns the submatrix for calculating cofactor, i.e. by taking out row r, col c from M.

Arguments

  1. M (tensor): The original matrix.
  2. [r=0] (number): The cofactor row.
  3. [c=0] (number): The cofactor col.

Returns

(tensor): F The submatrix.

Example

_.coSubMatrix([[1,2,3],[4,5,6],[7,8,9]])
// → [ [ 5, 6 ], [ 8, 9 ] ]

_.coSubMatrix([[1,2,3],[4,5,6],[7,8,9]], 0, 1)
// → [ [ 4, 6 ], [ 7, 9 ] ]

det(M)

#

Returns the determinant of a matrix.

Arguments

  1. M (tensor): The matrix.

Returns

(number): det The determinant.

Example

_.det([[1,2,3],[4,5,6],[11,13,17]])
// → -6

detSum(M, i)

#

Helper function for determinant, used with _.fsum. Sums all the cofactors multiplied with the comatrices.

Arguments

  1. M (tensor): The original matrix.
  2. i (number): The index of cofactor, needed for parity.

Returns

(number): recursive-sub-determinant Parity * cofactor * det(coSubMatrix)

Example

_.detSum([[1,2,3],[4,5,6],[11,13,17]], 0)
// → 7

inv(M)

#

Returns the inverse of a matrix, or null if non-invertible.

Arguments

  1. M (tensor): The matrix.

Returns

(tensor): Inv The inverse matrix, or null.

Example

_.inv([[1,4,7],[3,0,5],[-1,9,11]])
// → [ [ 5.625, -2.375, -2.5 ],
// [ 4.75, -2.25, -2 ],
// [ -3.375, 1.625, 1.5 ] ]

_.inv([[1,1],[1,1]])
// → null

matMultiply(A, B)

#

Multiply two matrices.

Arguments

  1. A (tensor): The first matrix.
  2. B (tensor): The second matrix.

Returns

(tensor): AB The two matrices multiplied together.

Example

_.matMultiply([[1,2],[3,4]], [[1,2],[3,4]])
// → [ [ 7, 10 ], [ 15, 22 ] ]

trace(M)

#

Returns the trace of a square matrix.

Arguments

  1. M (tensor): The matrix.

Returns

(number): trM The trace of the matrix.

Example

_.trace([[1, 2], [3, 4]])
// → 5

transpose(M)

#

Returns a copy of a matrix transposed.

Arguments

  1. M (tensor): The original matrix.

Returns

(tensor): M' The copy transposed matrix.

Example

_.transpose([[1, 2], [3, 4]])
// → [[ 1, 3 ], [ 2, 4 ]]

“native-Math” Methods

abs(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.

Example

_.abs([-1, -2, -3])
// → [1, 2, 3]

acos(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


acosh(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


asin(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


asinh(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


atan(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


atanh(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


ceil(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


cos(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


cosh(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


exp(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


floor(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


log10(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


log1p(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


log2(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


pow(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


round(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


sign(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


sin(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


sinh(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


sqrt(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


tan(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


tanh(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


trunc(T)

#

Generalized JS Math applicable to tensor using function composition.

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T A tensor.


“plotting” Methods

advPlot(options)

#

Method of the constructed hc object. Advanced plotting for users familiar with HighCharts (see http://www.highcharts.com). This is a highcharts wrapper; takes in a complete HighCharts plot options object.

Arguments

  1. options (Object): The HighCharts options object.

Returns

(Object): options The options passed, for reference.

Example

// Plots using the highcharts options
hc.advPlot({
   chart: {
        type: 'column'
    },
    title: {
        text: 'Monthly Average Rainfall'
    },
    subtitle: {
        text: 'Source: WorldClimate.com'
    },
    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
        crosshair: true
    },
    yAxis: {
        min: 0,
        title: {
            text: 'Rainfall (mm)'
        }
    },
    plotOptions: {
        column: {
            pointPadding: 0.2,
            borderWidth: 0
        }
    },
    series: [{
        name: 'Tokyo',
        data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0]

    }, {
        name: 'New York',
        data: [83.6, 78.8, 98.5, 93.4, 106.0, 84.5]

    }, {
        name: 'London',
        data: [48.9, 38.8, 39.3, 41.4, 47.0, 48.3]

    }, {
        name: 'Berlin',
        data: [42.4, 33.2, 34.5, 39.7, 52.6, 75.5]

    }]
       })
// renders the plot
hc.render()

hc()

#

The plotting module constructor. Uses HighCharts to plot and browserSync. Pulls up browser directly showing your charts like magic! To use this, go into node_modules/lomath and do npm install there to install the dev dependencies.

Returns

(Object): hc The plotting module of lomath.

Example

// in the terminal at your project's root, do:
cd node_modules/lomath
npm install

// Go back to your project .js file
var _ = require('lomath');

var v = _.range(10);
var vv = _.square(v);

// Construct the plotting modules
var hc = _.hc();

// first, list all you wish to plot.
hc.plot(
       [{
           name: "linear",
           data: v
       }, {
           name: "square",
           data: vv
       }],
       "Title 1"
       )
hc.plot(
       [{
           name: "log",
           data: _.log(v)
       }],
       "Title 2"
       )

// Finally, the command to render all the plots above.
// Pulls up a browser (default to chrome for better support) with the charts.
// calling hc.render(true) will autosave all plots to your downloads folder.
hc.render();

// Magical, eh?

plot(seriesArr, [title=""], [yLabel=""], [xLabel=""])

#

Method of the constructed hc object. A simplified wrapper of the HighCharts plot options object. Allows one to use simple data plot by specifying data sets in objects consisting of data name and data. The data specified can be array of y-values, or array of x-y values.

Arguments

  1. seriesArr (Array): The array of data series, i.e. the series objects in the HighCharts options.
  2. [title=""] (string): The title of this plot.
  3. [yLabel=""] (string): The y-axis label.
  4. [xLabel=""] (string): The x-axis label.

Returns

(Object): options The options passed, for reference.

Example

// Plots two data sets using y-values (x-values start from 0).
hc.plot(
       [{
           name: "linear",
           data: [1, 2, 3, 4, 5, 6]
       }, {
           name: "square",
           data: [1, 4, 9, 16, 25, 36]
       }],
       "Title 1"
       )

// Plots a data set using x-y values.
hc.plot(
       [{
           name: "square",
           data: [[3, 9], [4, 16], [5, 25], [6, 36]]
       }],
       "Title 2"
       )
// renders the plot
hc.render()

render([autosave])

#

Method of the constructed hc object. Renders the plots: Launches a browser with all the plots listed before this line. Uses a gulp task and browserSync. Pass argument true will auto save all the plots to downloads.

Arguments

  1. [autosave] (boolean): If true, will autosave all the plots to downloads.

Returns

(*): browser Pulls up a browser.

Example

hc.plot(...)
// renders the plot in a browser
hc.render()

// hc.render(true) will autosave all plots.

“properties” Methods

depth(T)

#

Returns the depth of an (nested) array, i.e. the rank of a tensor. Scalar = rank-0, vector = rank-1, matrix = rank-2, ... so on. Note that a tensor has homogenous depth, that is, there cannot tensors of different ranks in the same vector, e.g. [1, [2,3], 4] is prohibited.

Arguments

  1. T (tensor): The tensor.

Returns

(number): depth The depth of the array.

Example

_.depth(0)
// → 0

_.depth([1, 2, 3])
// → 1

_.depth([[1, 2], [3, 4]])
// → 2

dim(T)

#

Returns the "dimension" of a tensor. Note that a tensor has homogenous depth, that is, there cannot tensors of different ranks in the same vector, e.g. [1, [2,3], 4] is prohibited.

Arguments

  1. T (tensor): The tensor.

Returns

(Array): dim The dimension the tensor.

Example

_.dim(0)
// → []

_.dim([1, 2, 3])
// → [3]

_.dim([[1, 2, 3], [4, 5, 6]])
// → [2, 3]

_.dim([
     [[1,1,1,1],[2,2,2,2],[3,3,3,3]],
     [[4,4,4,4],[5,5,5,5],[6,6,6,6]]
   ])
// → [2, 3, 4]

isFlat(T)

#

Checks if a tensor is "flat", i.e. all entries are scalars.

Arguments

  1. T (tensor): The tensor.

Returns

(boolean): true If tensor is flat.

Example

_.isFlat(0)
// → true

_.isFlat([1, 2, 3])
// → true

_.isFlat([[1, 2], [3, 4]])
// → false

maxDeepestLength(T)

#

Returns the maximum length of the deepest array in (non-scalar) tensor T. Useful for probing the data structure and ensuring tensor is rectangular.

Arguments

  1. T (tensor): The tensor.

Returns

(number): length The maximum length of the deepest array in T.

Example

_.maxDeepestLength(0)
// → 0

_.maxDeepestLength([1, 2, 3])
// → 3

_.maxDeepestLength([[1, 2], [3, 4]])
// → 2

volume(T)

#

Returns the "volume" of a tensor, i.e. the totaly number of scalars in it.

Arguments

  1. T (tensor): The tensor.

Returns

(number): volume The number of scalar entries in the tensor.

Example

_.volume(0)
// → 0

_.volume([1, 2, 3])
// → 3

_.volume([[1, 2], [3, 4]])
// → 4

“regexp” Methods

reAnd(regexs)

#

Returns a single regex as the "AND" conjunction of all input regexs. This picks up as MANY adjacent substrings that satisfy all the regexs in order.

Arguments

  1. regexs (...RegExp): All the regexs to conjunct together.

Returns

(RegExp): regex The conjuncted regex of the form (?:re1)...(?:reN)

Example

var reg1 = _.reAnd('foo', /\d+/)
// → /(?:foo)(?:\d+)/
_.reGet(reg1)('Mayfoo1995')
// → 'foo1995'

var reg2 = _.reAnd(/\d+/, 'foo') // order matters here
// → /(?:\d+)(?:foo)/
_.reGet(reg2)('Mayfoo1995')
// → null

reAndMatch(regexs)

#

Returns a boolean function that matches all the regexs conjuncted in the specified order.

Arguments

  1. regexs (...RegExp): All the regexs to conjunct together.

Returns

(Function): fn A boolean function used for matching the conjuncted regexs.

Example

_.reAndMatch('foo', /\d+/)('Mayfoo1995')
// → true

_.reAndMatch(/\d+/, 'foo')('Mayfoo1995') // order matters
// → false

reGet(regex)

#

Returns a function that returns the first string portion matching the regex.

Arguments

  1. regex (RegExp): A RegExp to match.

Returns

(Function): fn A function that returns the string matching the regex.

Example

var getBar = _.reGet('bar') // using a string
getBar('foobarbaz')
// → 'bar'

var getNum = _.reGet(/\d+/) // using a regex
getNum('May 1995')
// → '1995'
getNum('May')
// → null

reMatch(regex)

#

Returns a boolean function that matches the regex.

Arguments

  1. regex (RegExp): A RegExp.

Returns

(Function): fn A boolean function used for matching the regex.

Example

var matcher1 = _.reMatch('foo') // using a string
matcher1('foobarbaz')
// → true

var matcher2 = _.reMatch(/\d+/) // using a regexp
matcher2('May 1995')
// → true

reNotMatch(regex)

#

Returns a boolean function that dis-matches the regex.

Arguments

  1. regex (RegExp): A RegExp to NOT match.

Returns

(Function): fn A boolean function used for dis-matching the regex.

Example

var matcher1 = _.reNotMatch('foo') // using a string
matcher1('barbaz')
// → true

var matcher2 = _.reNotMatch(/\d+/) // using a regexp
matcher2('foobar')
// → true

reOr(regexs)

#

Returns a single regex as the "OR" union of all input regexs. This picks up the FIRST substring that satisfies any of the regexs in any order.

Arguments

  1. regexs (...RegExp): All the regexs to union together.

Returns

(RegExp): regex The unioned regex of the form (?:re1)|...|(?:reN)

Example

var reg1 = _.reOr('foo', /\d+/)
// → /(?:foo)|(?:\d+)/
_.reGet(reg1)('Mayfoo1995')
// → 'foo'

var reg2 = _.reOr(/\d+/, 'foo') // order doesn't matter here
// → /(?:\d+)|(?:foo)/
_.reGet(reg2)('Mayfoo1995')
// → 'foo'

reOrMatch(regexs)

#

Returns a boolean function that matches any of the regexs in any order.

Arguments

  1. regexs (...RegExp): All the regexs to try to match.

Returns

(Function): fn A boolean function used for matching the regexs.

Example

_.reOrMatch('foo', /\d+/)('Mayfoo1995')
// → true

_.reOrMatch(\d+/, 'foo')('Mayfoo1995') // order doesn't matter
// → true

reString(regexp)

#

Converts a regexp into a string that can be used to reconstruct the same regex from 'new RegExp()'. This is a way to store a regexp as string. Note that the flags are excluded, and thus must be provided during regexp reconstruction.

Arguments

  1. regexp (RegExp): To be stored as string.

Returns

(string): reStr The regex as string, to be used in the RegExp() constructor with a supplied flag.

Example

var reStr = _.reString(/\d+|\s+/ig)
// → '\d+|\s+'

new RegExp(reStr, "gi")
// → /\d+|\s+/gi

reWrap(regex)

#

Wraps a regex into string for regex set operation.

Arguments

  1. regex (RegExp): A RegExp to wrap.

Returns

(string): wrapped The regex wrapped into the form (?:regex)

Example

_.reWrap('foo')
// → '(?:foo)'

“signature” Methods

deepEqual(T, S)

#

Checks if two tensors have identifcal entries.

Arguments

  1. T (tensor): A tensor
  2. S (tensor): Another tensor

Returns

(boolean): match True if tensors are identical, false otherwise.

Example

_.deepEqual([[1,2],[3,4]], [[1,2],[3,4]])
// → true
_.deepEqual([1,2,3], [1,2,3])
// → true
_.deepEqual([1,2,3], [1,2,3,4])
// → false
_.deepEqual([1,2,3], [1,2,0])
// → false

inRange(left, right, x)

#

Checks if x is in range, i.e. left ≤ x ≤ right.

Arguments

  1. left (number): The lower bound.
  2. right (number): The upper bound.
  3. x (number): The value to check.

Returns

(boolean): true If x is in range.

Example

_.inRange(0, 3, 3)
// → true

_.inRange.bind(null, 0, 3)(3)
// → true

isDouble(x)

#

Checks if x is a double-precision number/non-Integer.

Arguments

  1. x (number): The value to check.

Returns

(boolean): true If so.


isInteger(x)

#

Checks if x is an integer.

Arguments

  1. x (number): The value to check.

Returns

(boolean): true If so.


isNegative(x)

#

Checks if x < 0.

Arguments

  1. x (number): The value to check.

Returns

(boolean): true If so.


isPositive(x)

#

Checks if x > 0.

Arguments

  1. x (number): The value to check.

Returns

(boolean): true If so.


isZero(x)

#

Checks if x == 0.

Arguments

  1. x (number): The value to check.

Returns

(boolean): true If so.


nonNegative(x)

#

Checks if x ≥ 0.

Arguments

  1. x (number): The value to check.

Returns

(boolean): true If so.


nonPositive(x)

#

Checks if x ≤ 0.

Arguments

  1. x (number): The value to check.

Returns

(boolean): true If so.


nonZero(x)

#

Checks if x != 0.

Arguments

  1. x (number): The value to check.

Returns

(boolean): true If so.


parity(x)

#

Checks the parity (even/odd) of x. Useful for when doing the sum with alternating sign.

Arguments

  1. x (number): The value to check.

Returns

(number): n -1 if odd, +1 if even.


sameSig(T, sigFn)

#

Checks if signature function is true for all scalars of a tensor.

Arguments

  1. T (tensor): The tensor whose values to check.
  2. sigFn (Function): The signature function.

Returns

(boolean): true If all scalars of the tensor return true.

Example

_.sameSig([1, 2, 3], _.isPositive)
// → true

“statistics” Methods

expGRate(m_f, m_i, t)

#

Returns the rate of return r in % of an exponential growth, given final value m_f, initial value m_i, and time interval t. Formula: 100 * (Math.exp(Math.log(m_f / m_i) / t) - 1)

Arguments

  1. m_f (number): The final value.
  2. m_i (number): The initial value.
  3. t (number): The time interval between m_f, m_i.

Returns

(number): r The growth rate in %.

Example

_.expGRate(8, 2, 2) // 100% growth rate over 2 years
// → 100

expVal(X, [P], [fn])

#

Returns the expectation value E(fn(X)) of a random variable vector, optionally with the corresponding probability vector, using the random variable function (defaulted to identity).

Arguments

  1. X (Array): The random variable vector.
  2. [P] (Array): The corresponding probability vector.
  3. [fn] (Function): The random variable function.

Returns

(number): E(fn(X))

Example

var X = [-1, 0, 1, 2]
var Y = [-1,0,0,1,1,1,2,2,2,2]
var P = [0.1, 0.2, 0.3, 0.4]

_.expVal(Y) // using a raw data array, E(X)
// → ((-1) * 0.1 + 0 + 1 * 0.3 + 2 * 0.4)
_.expVal(X, P) // equivalent to Y, but using X and P: E(X)
// → ((-1) * 0.1 + 0 + 1 * 0.3 + 2 * 0.4)

_.expVal(Y, _.square) // using raw data array, E(X^2)
// → (1 * 0.1 + 0 + 1 * 0.3 + 4 * 0.4)
_.expVal(X, P, _.square) // equivalent to Y, but using X and P: E(X^2)
// → (1 * 0.1 + 0 + 1 * 0.3 + 4 * 0.4)

mean(T)

#

Returns the mean/average of a tensor.

Arguments

  1. T (tensor): A tensor.

Returns

(number): mean

Example

_.mean([1, 2, 3])
// → 2

_.mean([[1, 2], [3, 4]])
// → 5

stdev(X, [P], [fn])

#

Returns the standard deviation sigma(fn(X)) of a random variable vector, with the corresponding probability vector, using the random variable function (defaulted to identity). Simply calles _.variance internally and returns its square root.

Arguments

  1. X (Array): The corresponding random variable vector.
  2. [P] (Array): The corresponding probability vector.
  3. [fn] (Function): The random variable function.

Returns

(number): sigma(fn(X))

Example

var X = [-1, 0, 1, 2]
var Y = [-1,0,0,1,1,1,2,2,2,2]
var P = [0.1, 0.2, 0.3, 0.4]

_.stdev(Y) // using a raw data array, sigma(X)
// → 1
_.stdev(X, P) // equivalent to Y, but using X and P: sigma(X)
// → ((-1) * 0.1 + 0 + 1 * 0.3 + 2 * 0.4)

_.stdev(Y, _.square) // using raw data array, sigma(X^2)
// → 1.673
_.stdev(X, P, _.square) // equivalent to Y, but using X and P: sigma(X^2)
// → 1.673

trailExpGRate(v, t)

#

Returns the trailing exponential rate of return in the last t years given a vector. Calls _.expGRate internally.

Arguments

  1. v (Array): The time series vector.
  2. t (number): The time interval.

Returns

(number): r The growth rate in %.

Example

var v = [1, 2, 4, 8]
_.trailExpGRate(v, 1)
// → 100

_.trailExpGRate(v, 2)
// → 100

_.trailExpGRate(v, 3)
// → 100

variance(X, [P], [fn])

#

Returns the variance Var(fn(X)) of a random variable vector, with the corresponding probability vector, using the random variable function (defaulted to identity).

Arguments

  1. X (Array): The random variable vector.
  2. [P] (Array): The corresponding probability vector.
  3. [fn] (Function): The random variable function.

Returns

(number): Var(fn(X))

Example

var X = [-1, 0, 1, 2]
var Y = [-1,0,0,1,1,1,2,2,2,2]
var P = [0.1, 0.2, 0.3, 0.4]

_.variance(Y) // using a raw data array, Var(X)
// → 1
_.variance(X, P) // equivalent to Y, but using X and P: Var(X)
// → ((-1) * 0.1 + 0 + 1 * 0.3 + 2 * 0.4)

_.variance(Y, _.square) // using raw data array, Var(X^2)
// → 2.8
_.variance(X, P, _.square) // equivalent to Y, but using X and P: Var(X^2)
// → 2.8

“timing” Methods

p()

#

Ends a started timer (unique to the whole _ object). Needs to be called after tick. If called again, will give the next lap (starting from the last tick).

Returns

(number): ms Difference between now and the last _.tick() in milliseconds.

Example

_.tick()
// ... run some functions here, use promise for better flow control.
someTaskwithPromise().then(tock())
// → Returns some time elapsed in ms.

tick()

#

Starts a timer (unique to the whole _ object). Needs to be called before tock. If called again, will restart the timer.

Returns

(number): ms Result from _.now(), in milliseconds.


tock()

#

Ends a started timer (unique to the whole _ object). Needs to be called after tick. If called again, will give the next lap (starting from the last tick).

Returns

(number): ms Difference between now and the last _.tick() in milliseconds.

Example

_.tick()
// ... run some functions here, use promise for better flow control.
someTaskwithPromise().then(tock())
// → Returns some time elapsed in ms.

“transformation” Methods

batchIndexOf(T, fields)

#

Searches the array in batch by applying _.indexOf in batch; returns the indices of the results in order. Useful for grabbing the headers in a data set.

Arguments

  1. T (Array): The array.
  2. fields (Array): The array of fields to search for in T.

Returns

(Array): inds The indices returned by applying _.indexOf to fields.

Example

_.batchIndexOf(['a','b','c','d','e','f'], [1, 'b', 'a', 'a'])
// → [-1, 1, 0, 0]

cbind(M, indArr)

#

Returns a new matrix with the selected columns from a matrix. Same as cbind() from R. Useful for picking columns from a data matrix/tensor with specified header indices.

Arguments

  1. M (tensor): The original matrix.
  2. indArr (Array): The array of indices specifying the columns of M to pick.

Returns

(tensor): M' The matrix with the selected columns from the indices.

Example

_.cbind([['a','b','c'],[1,2,3],[-1,-2,-3]], [1, 1, 2])
// → [ [ 'b', 'b', 'c' ], [ 2, 2, 3 ], [ -2, -2, -3 ] ]

var M = [['a','b','c'],[1,2,3],[-1,-2,-3]]; // using on a dataset
var titles = M[0];
_.cbind(M, _.batchIndexOf(titles, ['b', 'b', 'c']))
// → [ [ 'b', 'b', 'c' ], [ 2, 2, 3 ], [ -2, -2, -3 ] ]

cbindByField(M, fields)

#

Returns a new matrix with the selected columns from a matrix. Short for _.cbind(M, _.batchIndexOf()) Useful for picking columns from a data matrix by directly specifying the header titles.

Arguments

  1. M (tensor): The original matrix.
  2. fields (Array): The array of fields of the columns of M to pick.

Returns

(tensor): M' The matrix with the selected columns from the fields.

Example

var M = [['a','b','c'],[1,2,3],[-1,-2,-3]]; // using on a dataset
_.cbindByField(M, ['b', 'b', 'c'])
// → [ [ 'b', 'b', 'c' ], [ 2, 2, 3 ], [ -2, -2, -3 ] ]

extend(T, toLen, [val=0])

#

Extends an array till toLen by prepending with val. Mutates the array.

Arguments

  1. T (Array): The array.
  2. toLen (number): The new length of the array. Must be longer than T.length.
  3. [val=0] (number): The value to prepend with.

Returns

(Array): T The mutated array after extending.

Example

_.extend([1, 2, 3], 6)
// → [1, 2, 3, 0, 0, 0]

_.extend([1, 2, 3], 6, 'a')
// → [1, 2, 3, 'a', 'a', 'a']

flattenJSON(obj)

#

Flattens a JSON object into depth 1, using an optional delimiter.

Arguments

  1. obj (JSON): The original JSON object.

Returns

(JSON): flat_obj The flattened (unnested) object.

Example

formData = {
   'level1': {
     'level2': {
       'level3': 0,
       'level3b': 1
     },
     'level2b': {
       'level3': [2,3,4]
     }
   }
 }

_.flattenJSON(formData)
// → { 'level1.level2.level3': 0,
//  'level1.level2.level3b': 1,
//  'level1.level2b.level3.0': 2,
//  'level1.level2b.level3.1': 3,
//  'level1.level2b.level3.2': 4 }
// The deepest values are not flattened (not stringified)

_.flattenJSON(formData, '_')
// → { level1_level2_level3: 0,
//  level1_level2_level3b: 1,
//  level1_level2b_level3_0: 2,
//  level1_level2b_level3_1: 3,
//  level1_level2b_level3_2: 4 }
// The deepest values are not flattened (not stringified)

rbind(M, indArr)

#

Returns a new matrix with the selected rows from a matrix. Same as rbind() from R. Useful for picking certain rows from a matrix/tensor.

Arguments

  1. M (tensor): The original matrix.
  2. indArr (Array): The array of indices specifying the rows of M to pick.

Returns

(tensor): M' The matrix with the selected rows from the indices.

Example

_.rbind([[1,2,3],[4,5,6],[7,8,9]], [1, 1, 2])
// → [[4, 5, 6], [4, 5, 6], [7, 8, 9]]

rectangularize(T)

#

Makes a tensor rectangular by filling with val (defaulted to 0). Mutates the tensor.

Arguments

  1. T (tensor): The original tensor.

Returns

(tensor): T The mutated tensor that is now rectangular.

Example

_.rectangularize([
     [1, 2, 3],
     [4]
   ])
// → [[ 1, 2, 3 ], [ 4, 0, 0 ]]

_.rectangularize([
     [1, 2, 3],
     [4]
   ], 'a')
// → [[ 1, 2, 3 ], [ 4, 'a', 'a' ]]

reshape(A, dimArr)

#

Reshapes an array into a multi-dimensional tensor. Applies _.chunk using a dimension array in sequence.

Arguments

  1. A (Array): The original flat array.
  2. dimArr (Array): The array specifying the dimensions.

Returns

(tensor): T The tensor reshaped from the copied array.

Example

_.reshape([1, 2, 3, 4, 5, 6], [2, 3])
// → [[ 1, 2, 3 ], [ 4, 5, 6 ]]

_.reshape([1, 2, 3, 4], [2, 3])
// → [[ 1, 2, 3 ], [ 4 ]]

reverse(T, [i=0], [j=T.length-1])

#

Returns a copy of the array reversed, optionally from index i to j inclusive.

Arguments

  1. T (Array): The array.
  2. [i=0] (number): The from-index.
  3. [j=T.length-1] (number): The to-index.

Returns

(Array): R The reversed copy of the array.

Example

_.reverse([0, 1, 2, 3, 4, 5])
// → [5, 4, 3, 2, 1, 0]

_.reverse([0, 1, 2, 3, 4, 5], 2) // reverse from index 2
// → [0, 1, 5, 4, 3, 2]

_.reverse([0, 1, 2, 3, 4, 5], null, 2) // reverse to index 2
// → [2, 1, 0, 3, 4, 5]

_.reverse([0, 1, 2, 3, 4, 5], 2, 4) // reverse from index 2 to 4
// → [0, 1, 4, 3, 2, 5]

swap(T, i, j)

#

Swaps entries at indices i,j. Mutates the array.

Arguments

  1. T (Array): The array.
  2. i (number): The swap-index.
  3. j (number): The swap-index.

Returns

(Array): T The mutated array after swapping.

Example

_.swap([1, 2, 3], 0, 2)
// → [3, 2, 1]

unflattenJSON(obj)

#

Unflattens a JSON object into depth, using an optional delimiter. The inverse of flattenJSON.

Arguments

  1. obj (JSON): The original JSON object.

Returns

(JSON): unflat_obj The unflattened (nested) object.

Example

formData = {
   'level1': {
     'level2': {
       'level3': 0,
       'level3b': 1
     },
     'level2b': {
       'level3': [2,3,4]
     }
   }
 }

_.unflattenJSON(_.flattenJSON(formData))
// → {
//   'level1': {
//     'level2': {
//       'level3': 0,
//       'level3b': 1
//     },
//     'level2b': {
//       'level3': [2,3,4]
//     }
//   }
// }
// JSON is restored

_.unflattenJSON(_.flattenJSON(formData, '_'), '_')
// → (formData)
// Note that the supplied delimiters must match to restore

validInds(T, maxLen)

#

Filters out the invalid indices (negatives) in an array of indices. Basically keeps x where 0 ≤ x ≤ maxLen. Used with _.batchIndexOf.

Arguments

  1. T (Array): The array of indices, can be from _.batchIndexOf.
  2. maxLen (number): The max value the indices can have.

Returns

(Array): inds A copy of the array with only valid indices.

Example

_.validInds([-2, 4, 0, 2, -1], 2)
// → [0, 2]

“trend” Methods

decreasing(T)

#

Shorthand for _.stairsTrend. Checks if a vector v is decreasing.

Arguments

  1. T (Array): An array of values.

Returns

(boolean): true If stairs of T match the sigFn.


increasing(T)

#

Shorthand for _.stairsTrend. Checks if a vector v is increasing.

Arguments

  1. T (Array): An array of values.

Returns

(boolean): true If stairs of T match the sigFn.


nonDecreasing(T)

#

Shorthand for _.stairsTrend. Checks if a vector v is non-decreasing.

Arguments

  1. T (Array): An array of values.

Returns

(boolean): true If stairs of T match the sigFn.


nonIncreasing(T)

#

Shorthand for _.stairsTrend. Checks if a vector v is non-increasing.

Arguments

  1. T (Array): An array of values.

Returns

(boolean): true If stairs of T match the sigFn.


stairs(T)

#

Returns the stair, i.e. the adjacent differences in the vector.

Arguments

  1. T (Array): An array of values.

Returns

(Array): S The array showing adjacent differences.

Example

_.stairs([1, 2, 3, 5, 8])
// → [1, 1, 2, 3]

stairsTrend(T, sigFn)

#

Check the trend of the array using a signature function. Useful for checking if array entries are increasing.

Arguments

  1. T (Array): An array of values.
  2. sigFn (Function): A signature function.

Returns

(boolean): true If stairs of T match the sigFn.

Example

_.stairsTrend([1, 2, 3, 4, 5], _.isPositive) // Array increasing
// → true

“vector” Methods

dot(X, Y)

#

Returns the dot product between two vectors. If lengths mismatch, recycles the shorter vector.

Arguments

  1. X (Array): A flat array.
  2. Y (Array): A flat array.

Returns

(number): X.Y The dot product.

Example

_.dot([1, 2, 3], [1, 2, 3])
// → 14

_.dot([1, 2, 3, 4, 5, 6], [1, 2, 3]) // recycle
// → 46

norm(T, [n=2])

#

Returns the L-n norm of a vector, default to L-2 (Euclidean) metric.

Arguments

  1. T (tensor): A tensor.
  2. [n=2] (number): The metric.

Returns

(number): num The norm in L-n metric space.

Example

_.norm([3, 4]) // Euclidean triangle
// → 5

_.norm([3, 4], 1) // taxicab metric
// → 7

normalize(T, [n=2])

#

Returns a copy of the vector normalized using L-n metric (defaulted to L-2).

Arguments

  1. T (tensor): A tensor.
  2. [n=2] (number): The metric.

Returns

(tensor): T' The normalized tensor.

Example

_.normalize([3, 4]) // Euclidean triangle
// → [0.6, 0.8]

_.normalize([3, 4], 1) // taxicab metric
// → [3/7, 4/7]

powSum(T, [n=2])

#

Returns the sums of n-powers (defaulted to 2) of a tensor, i.e. the square of the generalized hypotenuse of a tensor. Useful for doing sums of squares/other L-n metrics.

Arguments

  1. T (tensor): A tensor.
  2. [n=2] (number): The power base.

Returns

(number): num The power sum.

Example

_.powSum([1, 2, 3])
// → 14

_.powSum([1, 2, 3], 3)
// → 36

_.dot([[1, 2], [3, 4]], 3) // applicable to a tensor
// → 100

rescale(T)

#

Returns a copy of the vector rescaled to unit length; is the shorthand for _.normalize(v, 1).

Arguments

  1. T (tensor): A tensor.

Returns

(tensor): T' The rescaled tensor.

Example

_.rescale([3, 4])
// → [3/7, 4/7]

Methods

histogram(data, [fn], [pair])

#

Returns a histogram/distribution from the data. This internally calls _.countBy to group data by bins, using the function if specified. Returns the object containing values, frequencies and probabilities as separate array for ease of using them with the statistics methods.

Arguments

  1. data (Array): An array of data.
  2. [fn] (Function): An optional function to group the data by.
  3. [pair] (boolean): If true, will return an array of [value, freq].

Returns

(Object|Array): histogram {value, freq, prob} or array of [value, freq].

Example

// called with data
var hist = _.histogram(['a', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'd']);
hist.value
// → ['a', 'b', 'c', 'd']
hist.freq
// → [1, 2, 3, 4]
hist.prob // normalized freq as probabiltiy distribution
// → [0.1, 0.2, 0.3, 0.4]

// called with data and pair
_.histogram(['a', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'd'], true);
// → [['a',1], ['b',2], ['c',3], ['d',4]

// called with data and fn
var histfloor = _.histogram([1.1, 2.1, 2.2, 3.1, 3.2, 3.3, 4.1, 4.2, 4.3, 4.4], Math.floor);
histfloor.value
// → [ '1', '2', '3', '4' ] // Note the keys from _.countBy are strings
hist.freq
// → [1, 2, 3, 4]
histfloor.prob
// → [0.1, 0.2, 0.3, 0.4]

// called with data, fn and pair
_.histogram([1.1, 2.1, 2.2, 3.1, 3.2, 3.3, 4.1, 4.2, 4.3, 4.4], Math.floor, true);
// → [['1',1], ['2',2], ['3',3], ['4',4] ]

Properties