New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

mathjslab

Package Overview
Dependencies
Maintainers
1
Versions
89
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mathjslab - npm Package Compare versions

Comparing version 1.1.27 to 1.1.28

lib/src/core-functions.d.ts

8

CHANGES.md

@@ -5,2 +5,6 @@ # Release notes

## 1.2.0
- The MultiArray class now supports multidimensional arrays. More integration tests are needed. Several methods have been renamed to express their functions more clearly. Methods related to linear algebra in MultiArray class have been moved to the LinearAlgebra class in linear-algebra.ts file.
- The core-functions.ts file and its corresponding test file were created. Functions in MultiArray class have been moved to the CoreFunctions class in core-functions.ts file. The generalized methods have been left in MultiArray class and the user functions have been moved to the CoreFunctions class. The linearizedFunctions in MultiArray class have been removed (and corresponding methods and code in Evaluator class removed too).
## 1.1.27

@@ -44,6 +48,6 @@ - The linear-algebra.ts file and its corresponding test file were created. The relevant methods of the MultiArray class will be moved to this file as support for multidimensional arrays evolves in the MultiArray class. Some methods moved.

## 1.1.19
- Fix parser parenthsis node.
- Fix parser parenthesis node.
## 1.1.18
- `end` in ranges implemented in parser rule `colon_item`. To do this it was necessary to track the context creating the `parent` property in each node, set during `Evaluator`, and also the `index` property in the 'LIST' and 'ARG' type nodes. This can be useful in `Unparse` and `UnparseML`, to eliminate unnecessary parentheses.
- `end` in ranges implemented in parser rule `colon_item`. To do this it was necessary to track the context creating the `parent` property in each node, set during `Evaluator`, and also the `index` property in the 'LIST' and 'ARG' type nodes. This can be useful in `Unparse` and `UnparseMathML`, to eliminate unnecessary parentheses.

@@ -50,0 +54,0 @@ ## 1.1.17

@@ -94,8 +94,6 @@ # Contributing to MathJSLab

* Only 2-dimensional arrays (matrix) is supported. Extend to multidimensional
arrays. To do this is need a complete reestructuration of MultiArray class.
* Only one single ComplexDecimal type based on Decimal.js is implemented.
Extend to support ComplexDecimal type based on common javascript number type.
It is necessary for faster and more efficient computing.
* Use Web Workers and WebAssembly for more efficient computing. The complete
* Use Web Workers and/or WebAssembly for more efficient computing. The complete
evaluator can reside in a Web Worker.

@@ -102,0 +100,0 @@ * Parser is designed to scan a line. Need to code a parser that scan multiple

@@ -9,4 +9,4 @@ export declare class CharString {

static unparse(value: CharString): string;
static unparseML(value: CharString): string;
static unparseMathML(value: CharString): string;
static removeQuotes(value: CharString): CharString;
}

@@ -5,3 +5,3 @@ import { Decimal } from 'decimal.js';

*/
export type TBinaryOperationName = 'add' | 'sub' | 'mul' | 'rdiv' | 'ldiv' | 'power' | 'lt' | 'le' | 'eq' | 'ge' | 'gt' | 'ne' | 'and' | 'or' | 'xor' | 'mod' | 'rem';
export type TBinaryOperationName = 'add' | 'sub' | 'mul' | 'rdiv' | 'ldiv' | 'power' | 'lt' | 'le' | 'eq' | 'ge' | 'gt' | 'ne' | 'and' | 'or' | 'xor' | 'mod' | 'rem' | 'minWise' | 'maxWise';
/**

@@ -31,5 +31,5 @@ * Unary operations name type.

*/
static numberClass: Record<string, number>;
static readonly numberClass: Record<string, number>;
/**
* Real, imaginary and class properties.
* Real, imaginary and type properties.
*/

@@ -109,3 +109,3 @@ re: Decimal;

*/
static unparseML(value: ComplexDecimal): string;
static unparseMathML(value: ComplexDecimal): string;
/**

@@ -166,8 +166,2 @@ * Creates a copy of the value.

/**
* Gets the highest number type.
* @param args ComplexDecimal values.
* @returns Highest number type.
*/
static maxNumberType(...args: ComplexDecimal[]): number;
/**
* Gets the maximum or minimum of an array of ComplexDecimal using real comparison.

@@ -179,2 +173,3 @@ * @param cmp 'lt' for minimum or 'gt' for maximum.

static minMaxArrayReal(cmp: 'lt' | 'gt', ...args: ComplexDecimal[]): ComplexDecimal;
static minMaxArrayRealWithIndex(cmp: 'lt' | 'gt', ...args: ComplexDecimal[]): [ComplexDecimal, number];
/**

@@ -190,2 +185,3 @@ * Gets the maximum or minimum of an array of ComplexDecimal using complex

static minMaxArrayComplex(cmp: 'lt' | 'gt', ...args: ComplexDecimal[]): ComplexDecimal;
static minMaxArrayComplexWithIndex(cmp: 'lt' | 'gt', ...args: ComplexDecimal[]): [ComplexDecimal, number];
/**

@@ -200,2 +196,3 @@ * Returns the minimum of arguments. The arguments are in polar

static min(left: ComplexDecimal, right: ComplexDecimal): ComplexDecimal;
static minWise(left: ComplexDecimal, right: ComplexDecimal): ComplexDecimal;
/**

@@ -210,2 +207,3 @@ * Returns the maximum of arguments. The arguments are in polar

static max(left: ComplexDecimal, right: ComplexDecimal): ComplexDecimal;
static maxWise(left: ComplexDecimal, right: ComplexDecimal): ComplexDecimal;
/**

@@ -212,0 +210,0 @@ * Less than comparison (lexicographical ordering).

@@ -18,3 +18,3 @@ /**

func: Function;
unparserML?: (tree: any) => string;
unparserMathML?: (tree: any) => string;
};

@@ -211,2 +211,3 @@ export type TBaseFunctionTable = Record<string, TBaseFunctionTableEntry>;

private readonly opTable;
private readonly functions;
/**

@@ -218,3 +219,3 @@ * Parser AST (Abstract Syntax Tree) constructor methods.

readonly unparseString: typeof CharString.unparse;
readonly unparseStringML: typeof CharString.unparseML;
readonly unparseStringMathML: typeof CharString.unparseMathML;
readonly removeQuotes: typeof CharString.removeQuotes;

@@ -225,21 +226,21 @@ readonly nodeNumber: typeof ComplexDecimal.parse;

readonly unparseNumber: typeof ComplexDecimal.unparse;
readonly unparseNumberML: typeof ComplexDecimal.unparseML;
readonly unparseNumberMathML: typeof ComplexDecimal.unparseMathML;
readonly isTensor: typeof MultiArray.isThis;
readonly unparseTensor: typeof MultiArray.unparse;
readonly unparseTensorML: typeof MultiArray.unparseML;
readonly unparseTensorMathML: typeof MultiArray.unparseMathML;
readonly evaluateTensor: typeof MultiArray.evaluate;
readonly mapTensor: typeof MultiArray.map;
readonly getItems: typeof MultiArray.getItems;
readonly getItemsLogical: typeof MultiArray.getItemsLogical;
readonly setItems: typeof MultiArray.setItems;
readonly setItemsLogical: typeof MultiArray.setItemsLogical;
readonly getElements: typeof MultiArray.getElements;
readonly getElementsLogical: typeof MultiArray.getElementsLogical;
readonly setElements: typeof MultiArray.setElements;
readonly setElementsLogical: typeof MultiArray.setElementsLogical;
readonly expandRange: typeof MultiArray.expandRange;
readonly firstRow: typeof MultiArray.firstRow;
readonly appendRow: typeof MultiArray.appendRow;
readonly tensor0x0: typeof MultiArray.mat_0x0;
readonly tensor0x0: typeof MultiArray.array_0x0;
readonly linearize: typeof MultiArray.linearize;
readonly toTensor: typeof MultiArray.numberToMatrix;
readonly toTensor: typeof MultiArray.scalarToMultiArray;
readonly linearLength: typeof MultiArray.linearLength;
readonly getDimension: typeof MultiArray.getDimension;
private readonly unparseMLFunctions;
private readonly unparseMathMLFunctions;
/**

@@ -385,9 +386,2 @@ * Evaluator object constructor

/**
* Define function with matrix linearization.
* @param name Function name.
* @param func Function body.
* @param linearize boolean[ ] indicating wich argument is linearized.
*/
private DefLinearizedFunction;
/**
* Expression tree recursive evaluator.

@@ -417,3 +411,3 @@ * @param tree Expression to evaluate.

*/
unparserML(tree: any): string;
unparserMathML(tree: any): string;
/**

@@ -424,5 +418,5 @@ * Unparse Expression tree in MathML.

*/
UnparseML(tree: any, display?: 'inline' | 'block'): string;
UnparseMathML(tree: any, display?: 'inline' | 'block'): string;
toMathML(text: string, display?: 'inline' | 'block'): string;
}
export {};

@@ -5,3 +5,5 @@ export { CharString } from './char-string';

export { MultiArray } from './multi-array';
export { CoreFunctions } from './core-functions';
export { LinearAlgebra } from './linear-algebra';
export { MathObject } from './math-object';
export { TEvaluatorConfig, TBaseFunctionTable, NodeName, NodeExpr, Evaluator, TAliasNameTable } from './evaluator';

@@ -16,3 +16,3 @@ import { ComplexDecimal } from './complex-decimal';

/**
* LinearAlgebra class methods.
* LinearAlgebra functions.
*/

@@ -23,2 +23,11 @@ static functions: {

/**
* Identity matrix
* @param args
* * `eye(N)` - create identity N x N
* * `eye(N,M)` - create identity N x M
* * `eye([N,M])` - create identity N x M
* @returns Identity matrix
*/
static eye(...args: any): MultiArray | ComplexDecimal;
/**
* Sum of diagonal elements.

@@ -55,2 +64,9 @@ * @param M Matrix.

/**
* Matrix power (multiple multiplication).
* @param left
* @param right
* @returns
*/
static power(left: MultiArray, right: ComplexDecimal): MultiArray;
/**
* Matrix determinant.

@@ -57,0 +73,0 @@ * @param M Matrix.

@@ -1,2 +0,1 @@

import { MultiArray } from './multi-array';
export declare abstract class MathObject {

@@ -12,6 +11,5 @@ static unaryOpFunction: {

};
static readonly linearize: typeof MultiArray.linearize;
static copy(right: any): any;
static ewiseOp(op: 'add' | 'sub' | 'mul' | 'rdiv' | 'ldiv' | 'power' | 'lt' | 'le' | 'eq' | 'ge' | 'gt' | 'ne' | 'and' | 'or' | 'xor' | 'mod' | 'rem', left: any, right: any): any;
static leftOp(op: 'copy' | 'neg' | 'not', right: any): any;
static elementWiseOperation(op: 'add' | 'sub' | 'mul' | 'rdiv' | 'ldiv' | 'power' | 'lt' | 'le' | 'eq' | 'ge' | 'gt' | 'ne' | 'and' | 'or' | 'xor' | 'mod' | 'rem', left: any, right: any): any;
static leftOperation(op: 'copy' | 'neg' | 'not', right: any): any;
static plus(left: any, right: any): any;

@@ -18,0 +16,0 @@ static minus(left: any, right: any): any;

import { ComplexDecimal, TBinaryOperationName, TUnaryOperationLeftName } from './complex-decimal';
import { Evaluator, NodeReturnList } from './evaluator';
/**
* External reference for Evaluator instance initialized.
*/
export type Evaluator = any;
/**
* nameTable type (same in evaluator).

@@ -14,43 +11,19 @@ */

/**
* Evaluator.Evaluator method type (same in evaluator).
*/
export type TEvaluator = (tree: any, local: boolean, fname: string) => any;
/**
* Evaluator.Unparse and Evaluator.unparserML methods type (same in evaluator).
*/
export type TUnparse = (tree: any) => string;
/**
* # MultiArray
*
* An arbitrary precision Linear Algebra library.
*
* ## References
* * https://mathworld.wolfram.com/LinearAlgebra.html
* A multimensional array library.
*/
export declare class MultiArray {
/**
* Functions
* Dimensions property ([lines, columns, pages, blocks, ...]).
*/
static functions: {
[name: string]: Function;
};
dim: number[];
/**
* Linearized functions
* Dimensions excluding columns getter ([lines, pages, blocks, ...]).
*/
static linearizedFunctions: {
[name: string]: {
func: Function;
lin: boolean[];
};
};
get dimensionR(): number[];
/**
* Dimension property.
*/
dim: number[];
column: number;
dimension: number[];
/**
* Array property.
*/
array: ComplexDecimal[][];
array: (ComplexDecimal | any)[][];
/**

@@ -61,65 +34,96 @@ * Type property.

/**
* Set type property with maximum value of array items type.
*/
setType(): void;
/**
* Parent node property.
*/
parent: number;
parent: any;
/**
* MultiArray constructor.
* @param shape
* @param fill
* @param shape Array<number> of dimensions ([rows, columns, pages, blocks, ...]).
* @param fill Data to fill MultiArray. The same object will be put in all elements of MultiArray.
*/
constructor(shape?: number[], fill?: any);
/**
* MultiArray constructor.
* @param rows
* @param columns
* @param trailing
* @param fill
* Check if object is a MultiArray.
* @param obj Any object.
* @returns true if object is a MultiArray. false otherwise.
*/
constructor(rows: number, columns: number, trailing?: number[], fill?: any);
/**
* MultiArray constructor.
* @param columns
* @param dimension
* @param fill
*/
constructor(columns: number, dimension: number[], fill?: any);
/**
* Check if object is MultiArray compatible.
* @param obj
* @returns
*/
static isThis(obj: any): boolean;
/**
* Test if two array of numbers are equals.
* @param left
* @param right
* @returns
* @param left Array<number>.
* @param right Array<number>.
* @returns true if two arrays are equals. false otherwise.
*/
static arrayEqual(left: number[], right: number[]): boolean;
static arrayEquals(a: any[], b: any[]): boolean;
/**
* Remove tail of ones in array dimension in place.
* @param dimension
* Returns a range array ([1, 2, ..., length]).
* @param length Length or last value of range array.
* @returns Range array.
*/
static removeSingletonTail(dimension: number[]): void;
static rangeArray(length: number): number[];
/**
* Converts linear index to subscripts.
* @param dimension Dimensions of tensor ([line, page, block, ...]).
* Converts linear index to subscript.
* @param dimension Dimensions of multidimensional array ([line, column, page, block, ...]).
* @param index Zero-based linear index.
* @returns One-based subscript.
* @returns One-based subscript ([line, column, page, block, ...]).
*/
static linearIndexToSubscript(dimension: number[], index: number): number[];
/**
* Converts subscripts to linear index.
* @param dimension Dimensions of tensor ([line, page, block, ...]).
* @param subscript One-based subscript.
* Converts subscript to linear index.
* @param dimension Dimensions of multidimensional array ([line, column, page, block, ...]).
* @param subscript One-based subscript ([line, column, page, block, ...]).
* @returns Zero-based linear index.
*/
static subscriptToLinearIndex(dimension: number[], subscript: number[]): number;
static getDimension(M: MultiArray, n: number): number;
static getDimensionTensor(M: MultiArray, n: number): number;
/**
* Converts linear index to Multiarray.array subscript.
* @param row Row dimension.
* @param column Column dimension.
* @param index Zero-based linear index.
* @returns Multiarray.array subscript ([row, column]).
*/
static linearIndexToMultiArrayRowColumn(row: number, column: number, index: number): number[];
/**
* Converts MultiArray subscript to Multiarray.array subscript.
* @param dimension MultiArray dimension.
* @param subscript Subscript.
* @returns Multiarray.array subscript ([row, column]).
*/
static subscriptToMultiArrayRowColumn(dimension: number[], subscript: number[]): number[];
/**
* Base method of the ind2sub function. Returns dimension.length + 1
* dimensions. If the index exceeds the dimensions, the last dimension
* will contain the multiplier of the other dimensions. Otherwise it will
* be 1.
* @param dimension Array of dimensions.
* @param index One-base linear index.
* @returns One-based subscript ([line, column, page, block, ...]).
*/
static ind2subNumber(dimension: number[], index: number): number[];
/**
* Get dimension at index d of MultiArray M
* @param M Multiarray.
* @param d Zero-based dimension index.
* @returns Dimension d.
*/
static getDimension(M: MultiArray, d: number): number;
/**
* Remove singleton tail of dimension array in place.
* @param dimension Dimension array.
*/
static removeSingletonTail(dimension: number[]): void;
/**
* Append singleton tail of dimension array in place.
* @param dimension Dimension array.
* @param length Resulting length of dimension array.
*/
static appendSingletonTail(dimension: number[], length: number): void;
/**
* Creates a MultiArray object from the first row of elements (for
* parsing purposes).
* @param row
* @returns
* @param row Array of objects.
* @returns MultiArray with `row` parameter as first line.
*/

@@ -130,5 +134,5 @@ static firstRow(row: any[]): MultiArray;

* purposes).
* @param M
* @param row
* @returns
* @param M MultiArray.
* @param row Array of objects to append as row of MultiArray.
* @returns MultiArray with row appended.
*/

@@ -145,54 +149,93 @@ static appendRow(M: MultiArray, row: any[]): MultiArray;

* Unparse MultiArray.
* @param M MultiArray matrix object.
* @param M MultiArray object.
* @param that Evaluator.
* @returns String of unparsed matrix.
* @returns String of unparsed MultiArray.
*/
static unparse(M: MultiArray, that: Evaluator): string;
static unparseTensor(M: MultiArray, that: Evaluator): string;
/**
* Unparse MultiArray as MathML language.
* @param M MultiArray matrix object.
* @param M MultiArray object.
* @param that Evaluator.
* @returns String of unparsed matrix.
* @returns String of unparsed MultiArray in MathML language.
*/
static unparseML(M: MultiArray, that: Evaluator): string;
static unparseMLTensor(M: MultiArray, that: Evaluator): string;
static unparseMathML(M: MultiArray, that: Evaluator): string;
/**
* Evaluate MultiArray object. Calls `that.Evaluator` function for each element of
* Matrix
* @param tree MultiArray matrix object.
* @param that Evaluator reference.
* @param local Local context (function).
* Evaluate array. Calls `that.Evaluator` function for each element of page (matrix row-ordered)
* @param array Matrix.
* @param that Evaluator
* @param local `local` Evaluator parameter.
* @param fname `fname` Evaluator parameter.
* @param parent Parent node of items in page.
* @returns Evaluated matrix.
*/
private static evaluatePage;
/**
* Evaluate MultiArray object. Calls `MultiArray.evaluatePage` method for each page of
* multidimensional array.
* @param M MultiArray object.
* @param that Evaluator class reference.
* @param local Local context (function evaluation).
* @param fname Function name (context).
* @returns MultiArray object evaluated.
* @returns Evaluated MultiArray object.
*/
static evaluate(tree: MultiArray, that: Evaluator, local?: boolean, fname?: string): MultiArray;
static evaluate(M: MultiArray, that: Evaluator, local?: boolean, fname?: string): MultiArray;
/**
* Linearize MultiArray in an array of ComplexDecimal using row-major
* Linearize MultiArray in an array of any using column-major
* order.
* @param M
* @returns
* @param M Multidimensional array.
* @returns `any[]` of multidimensional array `M` linearized.
*/
static linearize(M: MultiArray | ComplexDecimal): ComplexDecimal[];
static linearizeTensor(M: MultiArray | ComplexDecimal): ComplexDecimal[];
static linearize(M: MultiArray | any): any[];
/**
* Null matrix (0x0 matrix).
* @returns
* Returns a null array (0x0 matrix).
* @returns Null array (0x0 matrix).
*/
static mat_0x0(): MultiArray;
static array_0x0(): MultiArray;
/**
* Convert a ComplexDecimal to 1x1 MultiArray.
* Convert a scalar value to 1x1 MultiArray.
* @param value MultiArray or scalar.
* @returns MultiArray 1x1 if value is scalar.
*/
static scalarToMultiArray(value: MultiArray | any): MultiArray;
/**
* If `value` parameter is a MultiArray of size 1x1 then returns as scalar.
* @param value MultiArray or scalar.
* @returns Scalar value if `value` parameter has all dimensions as singular.
*/
static MultiArrayToScalar(value: MultiArray | any): MultiArray | any;
/**
* If `value` parameter is a MultiArray returns it's first element.
* Otherwise returns `value` parameter.
* @param value
* @returns
*/
static numberToMatrix(value: ComplexDecimal | MultiArray): MultiArray;
static matrixToNumber(value: ComplexDecimal | MultiArray): MultiArray | ComplexDecimal;
static matrixToNumberTensor(value: ComplexDecimal | MultiArray): MultiArray | ComplexDecimal;
static firstElement(value: MultiArray | any): any;
/**
* Copy of MultiArray.
* Converts a ComplexDecimal array or a single line MultiArray to an array
* or number.
* @param M
* @returns
*/
static oneRowToDim(M: ComplexDecimal[] | MultiArray): number[];
/**
* Create MultiArray with all elements equals `fill` parameter.
* @param fill Value to fill MultiArray.
* @param dimension Dimensions of created MultiArray.
* @returns MultiArray filled with `fill` parameter.
*/
static newFilled(fill: any, ...dimension: any): MultiArray | ComplexDecimal;
/**
* Create MultiArray with all elements filled with `fillFunction` result.
* The parameter passed to `fillFunction` is a linear index of element.
* @param fillFunction Function to be called and the result fills element of MultiArray created.
* @param dimension Dimensions of created MultiArray.
* @returns MultiArray filled with `fillFunction` results for each element.
*/
static newFilledEach(fillFunction: (index: number) => any, ...dimension: any): MultiArray | ComplexDecimal;
/**
* Copy of MultiArray.
* @param M MultiArray.
* @returns Copy of MultiArray.
*/
static copy(M: MultiArray): MultiArray;
static copyTensor(M: MultiArray): MultiArray;
/**

@@ -205,3 +248,2 @@ * Convert MultiArray to logical value. It's true if all elements is

static toLogical(M: MultiArray): ComplexDecimal;
static toLogicalTensor(M: MultiArray): ComplexDecimal;
/**

@@ -215,22 +257,22 @@ * Calls a defined callback function on each element of an MultiArray,

static map(M: MultiArray, f: Function): MultiArray;
static mapTensor(M: MultiArray, f: Function): MultiArray;
/**
* Expand matrix dimensions if dimensions in `dim` is greater than dimensions of `M`.
* Expand Multidimensional array dimensions if dimensions in `dim` is greater than dimensions of `M`.
* If a dimension of `M` is greater than corresponding dimension in `dim` it's unchanged.
* The matrix is filled with zeros.
* The matrix is expanded in place.
* @param M Matrix.
* The array is filled with zeros and is expanded in place.
* @param M Multidimensional array.
* @param dim New dimensions.
* @returns Matrix `M` with dimensions expanded.
*/
static expand(M: MultiArray, dim: number[]): MultiArray;
static expandTensor(M: MultiArray, dim: number[]): MultiArray;
static expand(M: MultiArray, dim: number[]): void;
/**
* Returns the number of elements in M.
* @param M Multidimensional array.
* @returns Number of elements in M.
*/
static linearLength(M: MultiArray): number;
static linearLengthTensor(M: MultiArray): number;
/**
* Expand range
* @param startNode
* @param stopNode
* @param strideNode
* @returns
* Expand range.
* @param startNode Start of range.
* @param stopNode Stop of range.
* @param strideNode Optional stride value.
* @returns MultiArray of range expanded.
*/

@@ -249,23 +291,18 @@ static expandRange(startNode: ComplexDecimal, stopNode: ComplexDecimal, strideNode?: ComplexDecimal | null): MultiArray;

* number, then check if it's less than bound.
* @param k
* @param bound
* @param dim
* @param input
* @returns
* @param k Index as ComplexDecimal.
* @param bound Maximum acceptable value for the index
* @param dim Dimensions (to generate error message)
* @param input Optional string to generate error message.
* @returns Index as number.
*/
static testIndexBound(k: ComplexDecimal, bound: number, dim: number[], input?: string): number;
/**
* Check if two dimensions are compatible.
* @param leftDim
* @param rightDim
* @returns
* Converts subscript to linear index. Performs checks and throws
* comprehensive errors if dimension bounds are exceeded.
* @param dimension Dimension of multidimensional array ([line, column, page, block, ...]) as number[].
* @param subscript Subscript ([line, column, page, block, ...]) as a ComplexDecimal[].
* @param input Input string to generate error messages (the id of array).
* @returns linear index.
*/
static testDimension(leftDim: number[], rightDim: number[]): boolean;
static testDimensionTensor(leftDim: {
column: number;
dimension: number[];
}, rightDim: {
column: number;
dimension: number[];
}): boolean;
static parseSubscript(dimension: number[], subscript: ComplexDecimal[], input?: string, that?: Evaluator): number;
/**

@@ -277,12 +314,4 @@ * Find first non-single dimension.

static firstNonSingleDimension(M: MultiArray): number;
static firstNonSingleDimensionTensor(M: MultiArray): number;
/**
* Converts a ComplexDecimal array or a single line MultiArray to an array
* or number.
* @param M
* @returns
*/
static oneRowToDim(M: ComplexDecimal[] | MultiArray): number[];
/**
* Operation scalar _ matrix.
* Operation scalar op matrix.
* @param op

@@ -294,5 +323,4 @@ * @param left

static scalarOpMultiArray(op: TBinaryOperationName, left: ComplexDecimal, right: MultiArray): MultiArray;
static scalarOpMultiArrayTensor(op: TBinaryOperationName, left: ComplexDecimal, right: MultiArray): MultiArray;
/**
* Operation matrix _ scalar.
* Operation matrix op scalar.
* @param op

@@ -310,28 +338,49 @@ * @param left

*/
static leftOp(op: TUnaryOperationLeftName, right: MultiArray): MultiArray;
static leftOperation(op: TUnaryOperationLeftName, right: MultiArray): MultiArray;
/**
* Element-wise operation
* @param op
* @param left
* @param right
* @returns
* Binary element-wise operatior.
* @param op Binary operatior.
* @param left Left operator.
* @param right Right operator.
* @returns Binary element-wise result.
*/
static ewiseOp(op: TBinaryOperationName, left: MultiArray, right: MultiArray): MultiArray;
static elementWiseOperation(op: TBinaryOperationName, left: MultiArray, right: MultiArray): MultiArray;
/**
* Set selected items from MultiArray by linear index or subscripts.
* @param nameTable Name Table.
* @param id Identifier.
* @param args Linear indices or subscripts.
* @param right Value to assign.
* Contract MultiArray along `dimension` calling callback. This method is
* analogous to the JavaScript Array.reduce function.
* @param dimension Dimension to operate callback and contract.
* @param M Multidimensional array.
* @param callback Reduce function.
* @param initial Optional initial value to set as previous in the first
* call of callback. If not set the previous will be set to the first
* element of dimension.
* @returns Multiarray with `dimension` reduced using `callback`.
*/
static setItems(nameTable: TNameTable, id: string, args: any[], right: MultiArray): void;
static reduce(dimension: number, M: MultiArray, callback: (previous: any, current: any, index: number) => any, initial?: any): MultiArray | ComplexDecimal;
/**
* Set selected items from MultiArray by logical indexing.
* @param nameTable Name Table.
* @param id Identifier.
* @param arg Logical index.
* @param right Value to assign.
* Reduce one dimension of MultiArray putting entire dimension in one
* element of resulting MultiArray as an Array. The resulting MultiArray
* cannot be unparsed and used as argument of any other method of
* MultiArray class.
* @param dimension Dimension to reduce to Array
* @param M MultiArray to be reduced.
* @returns MultiArray reduced.
*/
static setItemsLogical(nameTable: TNameTable, id: string, arg: ComplexDecimal[], right: MultiArray): void;
static reduceToArray(dimension: number, M: MultiArray): MultiArray;
/**
* Return the concatenation of N-D array objects, ARRAY1, ARRAY2, ...,
* ARRAYN along `dimension` parameter (zero-based).
* @param dimension Dimension of concatenation.
* @param fname Function name (for error messages).
* @param ARRAY Arrays to concatenate.
* @returns Concatenated arrays along `dimension` parameter.
*/
static concatenate(dimension: number, fname: string, ...ARRAY: MultiArray[]): MultiArray;
/**
* Converts an MultiArray of logical to a number[] with corresponding true indices.
* @param M MultiArray
* @returns `number[]` with corresponding `true` indices (zero-based).
*/
static logicalToIndex(M: MultiArray): number[];
/**
* Get selected items from MultiArray by linear indices or subscripts.

@@ -343,3 +392,3 @@ * @param M Matrix.

*/
static getItems(M: MultiArray, id: string, indexList: (ComplexDecimal | MultiArray)[]): MultiArray | ComplexDecimal;
static getElements(M: MultiArray, id: string, indexList: (ComplexDecimal | MultiArray)[]): MultiArray | ComplexDecimal;
/**

@@ -352,189 +401,26 @@ * Get selected items from MultiArray by logical indexing.

*/
static getItemsLogical(M: MultiArray, id: string, items: MultiArray): MultiArray;
static getElementsLogical(M: MultiArray, id: string, items: MultiArray): MultiArray | ComplexDecimal;
/**
* Create array of all zeros.
* @param args
* @returns
* Set selected items from MultiArray by linear index or subscripts.
* @param nameTable Name Table.
* @param id Identifier.
* @param args Linear indices or subscripts.
* @param right Value to assign.
*/
static zeros(...args: any): MultiArray | ComplexDecimal;
static setElements(nameTable: TNameTable, id: string, indexList: (ComplexDecimal | MultiArray)[], right: MultiArray, input?: string, that?: Evaluator): void;
/**
* Create array of all ones.
* @param args
* @returns
* Set selected items from MultiArray by logical indexing.
* @param nameTable Name Table.
* @param id Identifier.
* @param arg Logical index.
* @param right Value to assign.
*/
static ones(...args: any): MultiArray | ComplexDecimal;
static setElementsLogical(nameTable: TNameTable, id: string, arg: ComplexDecimal[], right: MultiArray): void;
/**
* Identity matrix
* @param args
* * `eye(N)` - create identity N x N
* * `eye(N,M)` - create identity N x M
* * `eye([N,M])` - create identity N x M
* @returns Identity matrix
* Base method of min and max user functions.
* @param op 'min' or 'max'
* @param args One to three arguments like user function.
* @returns Return like user function.
*/
static eye(...args: any): MultiArray | ComplexDecimal;
/**
* Uniformly distributed random numbers.
* @param args
* @returns
*/
static rand(...args: any): MultiArray | ComplexDecimal;
/**
* Uniformly distributed pseudorandom integers.
* @param imax
* @param args
* @returns
*/
static randi(imax: ComplexDecimal, ...args: any): MultiArray | ComplexDecimal;
/**
* Matrix product.
* @param left Matrix.
* @param right Matrix.
* @returns left * right
*/
static mul(left: MultiArray, right: MultiArray): MultiArray;
/**
* Matrix power (multiple multiplication).
* @param left
* @param right
* @returns
*/
static power(left: MultiArray, right: ComplexDecimal): MultiArray;
/**
* Transpose.
* @param left
* @returns
*/
static transpose(left: MultiArray): MultiArray;
/**
* Complex conjugate transpose.
* @param left
* @returns
*/
static ctranspose(left: MultiArray): MultiArray;
/**
* Concatenate arrays horizontally.
* @param L
* @param R
* @returns
*/
static horzcat(L: MultiArray, R: MultiArray): MultiArray;
/**
* Concatenate arrays vertically.
* @param U
* @param D
* @returns
*/
static vertcat(U: MultiArray, D: MultiArray): MultiArray;
/**
* Convert subscripts to linear indices.
* @param DIMS
* @param S
* @returns
*/
static sub2ind(DIMS: any, ...S: any): ComplexDecimal;
/**
* Convert linear indices to subscripts.
* @param DIMS
* @param IND
* @returns
*/
static ind2sub(DIMS: any, IND: any): any;
/**
* Array size.
* @param M Matrix
* @param DIM
* @returns
*/
static size(M: MultiArray, ...DIM: ComplexDecimal[] | ComplexDecimal[][]): MultiArray | ComplexDecimal;
/**
* Minimum (lt) or maximum (gt) elements of array.
* @param M
* @returns
*/
static minMax(cmp: 'lt' | 'gt', M: MultiArray | ComplexDecimal): MultiArray | ComplexDecimal;
/**
* Minimum elements of array.
* @param M
* @returns
*/
static min(...args: any[]): MultiArray | ComplexDecimal;
/**
* Maximum elements of array.
* @param M
* @returns
*/
static max(...args: any[]): MultiArray | ComplexDecimal;
/**
* Average or mean value of array.
* @param M
* @returns
*/
static mean(M: MultiArray | ComplexDecimal): MultiArray | ComplexDecimal;
/**
* Calculate sum or product of elements along dimension DIM.
* @param op 'add' for sum or 'mul' for product
* @param mapper function to apply in each element
* @param M Matrix
* @param DIM Dimension
* @returns One dimensional matrix with sum or product of elements along dimension DIM.
*/
private static sumprod;
/**
* Calculate sum of elements along dimension DIM.
* @param M Matrix
* @param DIM Dimension
* @returns One dimensional matrix with sum of elements along dimension DIM.
*/
static sum(M: MultiArray, DIM?: ComplexDecimal): MultiArray | ComplexDecimal;
/**
* Calculate sum of squares of elements along dimension DIM.
* @param M Matrix
* @param DIM Dimension
* @returns One dimensional matrix with sum of squares of elements along dimension DIM.
*/
static sumsq(M: MultiArray, DIM?: ComplexDecimal): MultiArray | ComplexDecimal;
/**
* Calculate product of elements along dimension DIM.
* @param M Matrix
* @param DIM Dimension
* @returns One dimensional matrix with product of elements along dimension DIM.
*/
static prod(M: MultiArray, DIM?: ComplexDecimal): MultiArray | ComplexDecimal;
/**
* Sum of diagonal elements.
* @param M
* @returns
*/
static trace(M: MultiArray): ComplexDecimal;
/**
* Matrix determinant.
* @param M
* @returns
*/
static det(M: MultiArray): ComplexDecimal;
/**
* Matrix inverse.
* @param M
* @returns
*/
static inv(M: MultiArray): MultiArray;
/**
* Gaussian elimination algorithm for solving systems of linear equations.
* Adapted from: https://github.com/itsravenous/gaussian-elimination
* ## References
* * https://mathworld.wolfram.com/GaussianElimination.html
* @param M
* @param x
* @returns
*/
static gauss(M: MultiArray, x: MultiArray): MultiArray | undefined;
/**
* PLU matrix factorization
* @param M Matrix
* @returns L, U and P matrices as multiple output.
* ## References
* * https://www.codeproject.com/Articles/1203224/A-Note-on-PA-equals-LU-in-Javascript
* * https://rosettacode.org/wiki/LU_decomposition#JavaScript
*/
static lu(M: MultiArray): any;
static minMax(op: 'min' | 'max', ...args: any[]): MultiArray | NodeReturnList;
}
{
"name": "mathjslab",
"version": "1.1.27",
"version": "1.1.28",
"description": "MathJSLab - An interpreter with language syntax like MATLAB®/Octave. ISBN 978-65-00-82338-7",

@@ -59,8 +59,8 @@ "main": "lib/mathjslab.js",

"@types/debug": "^4.1.12",
"@types/jest": "29.5.8",
"@types/node": "^20.9.0",
"@types/jest": "29.5.9",
"@types/node": "^20.9.3",
"@types/supertest": "^2.0.16",
"@types/webpack": "^5.28.5",
"@typescript-eslint/eslint-plugin": "^6.10.0",
"eslint": "^8.53.0",
"@typescript-eslint/eslint-plugin": "^6.12.0",
"eslint": "^8.54.0",
"eslint-config-prettier": "^9.0.0",

@@ -72,8 +72,8 @@ "eslint-plugin-import": "^2.29.0",

"lint-staged": "^15.1.0",
"prettier": "^3.0.3",
"prettier": "^3.1.0",
"rimraf": "^5.0.5",
"ts-jest": "29.1.1",
"ts-loader": "^9.5.0",
"ts-loader": "^9.5.1",
"ts-node": "^10.9.1",
"typescript": "^5.2.2",
"typescript": "^5.3.2",
"webpack": "^5.89.0",

@@ -80,0 +80,0 @@ "webpack-cli": "^5.1.4"

@@ -96,3 +96,3 @@ # MathJSLab

```typescript
let mathml = evaluator.UnparseML(tree);
let mathml = evaluator.UnparseMathML(tree);
```

@@ -151,3 +151,2 @@

* The comma is mandatory inside arrays (MATLAB&reg;/Octave supports space too).
* Only two dimensional arrays can be defined (only Matrix, no Tensors).
* Defining functions is done simply using:

@@ -158,3 +157,3 @@ ```

* Parsing is executed line-by-line.
* There are only one complex numeric type. Other implemented types is boolean and character string;
* There are only one a complex numeric type. Other implemented types is boolean and character string;

@@ -161,0 +160,0 @@ ## License

@@ -19,3 +19,3 @@ export class CharString {

}
static unparseML(value: CharString): string {
static unparseMathML(value: CharString): string {
return '<mn>' + value.str + '</mn>';

@@ -22,0 +22,0 @@ }

import { Decimal } from 'decimal.js';
import { type } from 'os';

@@ -52,3 +51,22 @@ /**

*/
export type TBinaryOperationName = 'add' | 'sub' | 'mul' | 'rdiv' | 'ldiv' | 'power' | 'lt' | 'le' | 'eq' | 'ge' | 'gt' | 'ne' | 'and' | 'or' | 'xor' | 'mod' | 'rem';
export type TBinaryOperationName =
| 'add'
| 'sub'
| 'mul'
| 'rdiv'
| 'ldiv'
| 'power'
| 'lt'
| 'le'
| 'eq'
| 'ge'
| 'gt'
| 'ne'
| 'and'
| 'or'
| 'xor'
| 'mod'
| 'rem'
| 'minWise'
| 'maxWise';

@@ -144,3 +162,3 @@ /**

*/
public static numberClass: Record<string, number> = {
public static readonly numberClass: Record<string, number> = {
logical: 0,

@@ -152,3 +170,3 @@ real: 1,

/**
* Real, imaginary and class properties.
* Real, imaginary and type properties.
*/

@@ -326,3 +344,3 @@ public re: Decimal;

*/
public static unparseML(value: ComplexDecimal): string {
public static unparseMathML(value: ComplexDecimal): string {
if (value.type !== ComplexDecimal.numberClass.logical) {

@@ -453,11 +471,2 @@ const value_prec = ComplexDecimal.toMaxPrecision(value);

/**
* Gets the highest number type.
* @param args ComplexDecimal values.
* @returns Highest number type.
*/
public static maxNumberType(...args: ComplexDecimal[]): number {
return Math.max(...args.map((arg) => arg.type));
}
/**
* Gets the maximum or minimum of an array of ComplexDecimal using real comparison.

@@ -472,2 +481,18 @@ * @param cmp 'lt' for minimum or 'gt' for maximum.

public static minMaxArrayRealWithIndex(cmp: 'lt' | 'gt', ...args: ComplexDecimal[]): [ComplexDecimal, number] {
let index: number = 0;
const result = args.reverse().reduce(
(previous: ComplexDecimal, current: ComplexDecimal, i: number): ComplexDecimal => {
if (previous.re[cmp](current.re)) {
return previous;
} else {
index = args.length - 1 - i;
return current;
}
},
args[args.length - 1],
);
return [result, index];
}
/**

@@ -494,2 +519,29 @@ * Gets the maximum or minimum of an array of ComplexDecimal using complex

public static minMaxArrayComplexWithIndex(cmp: 'lt' | 'gt', ...args: ComplexDecimal[]): [ComplexDecimal, number] {
let index: number = 0;
const result = args.reverse().reduce(
(previous: ComplexDecimal, current: ComplexDecimal, i: number): ComplexDecimal => {
const previous_abs = ComplexDecimal.abs(previous).re;
const current_abs = ComplexDecimal.abs(current).re;
if (previous_abs.eq(current_abs)) {
if (ComplexDecimal.arg(previous).re[cmp](ComplexDecimal.arg(current).re)) {
return previous;
} else {
index = args.length - 1 - i;
return current;
}
} else {
if (previous_abs[cmp](current_abs)) {
return previous;
} else {
index = args.length - 1 - i;
return current;
}
}
},
args[args.length - 1],
);
return [result, index];
}
/**

@@ -517,2 +569,16 @@ * Returns the minimum of arguments. The arguments are in polar

public static minWise(left: ComplexDecimal, right: ComplexDecimal): ComplexDecimal {
if (left.type <= ComplexDecimal.numberClass.real && left.type <= ComplexDecimal.numberClass.real) {
return left.re.lt(right.re) ? left : right;
} else {
const left_abs = ComplexDecimal.abs(left).re;
const right_abs = ComplexDecimal.abs(right).re;
if (left_abs.eq(right_abs)) {
return ComplexDecimal.arg(left).re.lt(ComplexDecimal.arg(right).re) ? left : right;
} else {
return left_abs.lt(right_abs) ? left : right;
}
}
}
/**

@@ -540,2 +606,16 @@ * Returns the maximum of arguments. The arguments are in polar

public static maxWise(left: ComplexDecimal, right: ComplexDecimal): ComplexDecimal {
if (left.type <= ComplexDecimal.numberClass.real && left.type <= ComplexDecimal.numberClass.real) {
return left.re.gte(right.re) ? left : right;
} else {
const left_abs = ComplexDecimal.abs(left).re;
const right_abs = ComplexDecimal.abs(right).re;
if (left_abs.eq(right_abs)) {
return ComplexDecimal.arg(left).re.gte(ComplexDecimal.arg(right).re) ? left : right;
} else {
return left_abs.gte(right_abs) ? left : right;
}
}
}
/**

@@ -542,0 +622,0 @@ * Less than comparison (lexicographical ordering).

@@ -5,3 +5,5 @@ export { CharString } from './char-string';

export { MultiArray } from './multi-array';
export { CoreFunctions } from './core-functions';
export { LinearAlgebra } from './linear-algebra';
export { MathObject } from './math-object';
export { TEvaluatorConfig, TBaseFunctionTable, NodeName, NodeExpr, Evaluator, TAliasNameTable } from './evaluator';

@@ -17,9 +17,7 @@ import { ComplexDecimal } from './complex-decimal';

/**
* LinearAlgebra class methods.
* LinearAlgebra functions.
*/
public static functions: { [name: string]: Function } = {
eye: LinearAlgebra.eye,
trace: LinearAlgebra.trace,
transpose: LinearAlgebra.transpose,
ctranspose: LinearAlgebra.ctranspose,
mul: LinearAlgebra.mul,
det: LinearAlgebra.det,

@@ -32,2 +30,51 @@ inv: LinearAlgebra.inv,

/**
* Identity matrix
* @param args
* * `eye(N)` - create identity N x N
* * `eye(N,M)` - create identity N x M
* * `eye([N,M])` - create identity N x M
* @returns Identity matrix
*/
public static eye(...args: any): MultiArray | ComplexDecimal {
let rows: number = 0;
let columns: number = 0;
if (args.length === 0) {
return ComplexDecimal.one();
} else if (args.length === 1) {
if (MultiArray.isThis(args[0])) {
const linear = MultiArray.linearize(args[0]);
if (linear.length === 0) {
throw new SyntaxError('eye (A): use eye (size (A)) instead');
} else if (linear.length === 1) {
rows = MultiArray.testIndex(linear[0]);
columns = rows;
} else if (linear.length === 2) {
rows = MultiArray.testIndex(linear[0]);
columns = MultiArray.testIndex(linear[1]);
} else {
throw new SyntaxError('eye (A): use eye (size (A)) instead');
}
} else {
rows = MultiArray.testIndex(args[0]);
columns = rows;
}
} else if (args.length === 2) {
if (ComplexDecimal.isThis(args[0]) && ComplexDecimal.isThis(args[1])) {
rows = MultiArray.testIndex(args[0]);
columns = MultiArray.testIndex(args[1]);
} else {
throw new SyntaxError(`Invalid call to eye. Type 'help eye' to see correct usage.`);
}
} else {
throw new SyntaxError(`Invalid call to eye. Type 'help eye' to see correct usage.`);
}
//result = MultiArray.zeros(new ComplexDecimal(rows), new ComplexDecimal(columns)) as MultiArray;
const result = new MultiArray([rows, columns], ComplexDecimal.zero());
for (let n = 0; n < Math.min((result as MultiArray).dim[0], (result as MultiArray).dim[1]); n++) {
(result as MultiArray).array[n][n] = ComplexDecimal.one();
}
return result;
}
/**
* Sum of diagonal elements.

@@ -38,3 +85,3 @@ * @param M Matrix.

public static trace(M: MultiArray): ComplexDecimal {
if (M.dimension.length === 1) {
if (M.dim.length === 2) {
return M.array.map((row, i) => (row[i] ? row[i] : ComplexDecimal.zero())).reduce((p, c) => ComplexDecimal.add(p, c), ComplexDecimal.zero());

@@ -52,11 +99,11 @@ } else {

private static applyTranspose(M: MultiArray, func: Function = (value: any) => value): MultiArray {
if (M.dimension.length === 1) {
const result = new MultiArray([M.column, M.dimension[0]]);
for (let i = 0; i < M.column; i++) {
result.array[i] = new Array(M.dimension[0]);
for (let j = 0; j < M.dimension[0]; j++) {
if (M.dim.length === 2) {
const result = new MultiArray([M.dim[1], M.dim[0]]);
for (let i = 0; i < M.dim[1]; i++) {
result.array[i] = new Array(M.dim[0]);
for (let j = 0; j < M.dim[0]; j++) {
result.array[i][j] = Object.assign({}, func(M.array[j][i]));
}
}
result.type = Math.max(...result.array.map((row) => ComplexDecimal.maxNumberType(...row)));
result.setType();
return result;

@@ -93,10 +140,10 @@ } else {

public static mul(left: MultiArray, right: MultiArray): MultiArray {
if (left.column !== right.dimension[0] && left.dimension.length === 1 && right.dimension.length === 1) {
throw new Error(`operator *: nonconformant arguments (op1 is ${left.dimension[0]}x${left.column}, op2 is ${right.dimension[0]}x${right.column}).`);
if (left.dim[1] !== right.dim[0] && left.dim.length === 2 && right.dim.length === 2) {
throw new Error(`operator *: nonconformant arguments (op1 is ${left.dim[0]}x${left.dim[1]}, op2 is ${right.dim[0]}x${right.dim[1]}).`);
} else {
const result = new MultiArray([left.dimension[0], right.column]);
for (let i = 0; i < left.dimension[0]; i++) {
result.array[i] = new Array(right.column).fill(ComplexDecimal.zero());
for (let j = 0; j < right.column; j++) {
for (let n = 0; n < left.column; n++) {
const result = new MultiArray([left.dim[0], right.dim[1]]);
for (let i = 0; i < left.dim[0]; i++) {
result.array[i] = new Array(right.dim[1]).fill(ComplexDecimal.zero());
for (let j = 0; j < right.dim[1]; j++) {
for (let n = 0; n < left.dim[1]; n++) {
result.array[i][j] = ComplexDecimal.add(result.array[i][j], ComplexDecimal.mul(left.array[i][n], right.array[n][j]));

@@ -106,3 +153,3 @@ }

}
result.type = Math.max(...result.array.map((row) => ComplexDecimal.maxNumberType(...row)));
result.setType();
return result;

@@ -113,2 +160,31 @@ }

/**
* Matrix power (multiple multiplication).
* @param left
* @param right
* @returns
*/
public static power(left: MultiArray, right: ComplexDecimal): MultiArray {
let temp1;
if (right.re.isInteger() && right.im.eq(0)) {
if (right.re.eq(0)) {
temp1 = LinearAlgebra.eye(new ComplexDecimal(left.dim[0], 0)) as MultiArray;
} else if (right.re.gt(0)) {
temp1 = MultiArray.copy(left);
} else {
temp1 = LinearAlgebra.inv(left);
}
if (Math.abs(right.re.toNumber()) != 1) {
let temp2 = MultiArray.copy(temp1);
for (let i = 1; i < Math.abs(right.re.toNumber()); i++) {
temp2 = LinearAlgebra.mul(temp2, temp1);
}
temp1 = temp2;
}
return temp1;
} else {
throw new Error(`exponent must be integer real in matrix '^'.`);
}
}
/**
* Matrix determinant.

@@ -119,4 +195,4 @@ * @param M Matrix.

public static det(M: MultiArray): ComplexDecimal {
if (M.dimension[0] === M.column && M.dimension.length === 1) {
const n = M.column;
if (M.dim.length === 2 && M.dim[0] === M.dim[1]) {
const n = M.dim[1];
let det = ComplexDecimal.zero();

@@ -137,3 +213,3 @@ if (n === 1) det = M.array[0][0];

}
det = ComplexDecimal.add(det, ComplexDecimal.mul(new ComplexDecimal(Math.pow(-1, 2.0 + j1), 0), ComplexDecimal.mul(M.array[0][j1], MultiArray.det(m))));
det = ComplexDecimal.add(det, ComplexDecimal.mul(new ComplexDecimal(Math.pow(-1, 2.0 + j1), 0), ComplexDecimal.mul(M.array[0][j1], LinearAlgebra.det(m))));
}

@@ -163,3 +239,3 @@ }

// if the matrix isn't square: exit (error)
if (M.dimension[0] === M.column && M.dimension.length === 1) {
if (M.dim.length === 2 && M.dim[0] === M.dim[1]) {
// create the identity matrix (I), and a copy (C) of the original

@@ -170,3 +246,3 @@ let i = 0,

e = ComplexDecimal.zero();
const numRows = M.dimension[0];
const numRows = M.dim[0];
const I: ComplexDecimal[][] = [],

@@ -218,3 +294,3 @@ C: any[][] = [];

if (e.re.eq(0) && e.im.eq(0)) {
return new MultiArray([M.dimension[0], M.column], ComplexDecimal.inf_0());
return new MultiArray([M.dim[0], M.dim[1]], ComplexDecimal.inf_0());
}

@@ -254,5 +330,5 @@ }

// matrix I should be the inverse:
const result = new MultiArray([M.dimension[0], M.column]);
const result = new MultiArray([M.dim[0], M.dim[1]]);
result.array = I;
result.type = Math.max(...result.array.map((row) => ComplexDecimal.maxNumberType(...row)));
result.setType();
return result;

@@ -274,15 +350,17 @@ } else {

public static gauss(M: MultiArray, m: MultiArray): MultiArray {
if (M.dimension[0] !== M.column || M.dimension.length !== 1) throw new Error(`invalid dimensions in function gauss.`);
if (M.dim.length > 2 || M.dim[0] !== M.dim[1]) {
throw new Error(`invalid dimensions in function gauss.`);
}
const A: MultiArray = MultiArray.copy(M);
let i: number, k: number, j: number;
const DMin = Math.min(m.dimension[0], m.column);
if (DMin === m.column) {
m = MultiArray.transpose(m);
const DMin = Math.min(m.dim[0], m.dim[1]);
if (DMin === m.dim[1]) {
m = LinearAlgebra.transpose(m);
}
// Just make a single matrix
for (i = 0; i < A.dimension[0]; i++) {
for (i = 0; i < A.dim[0]; i++) {
A.array[i].push(m.array[0][i]);
}
const n = A.dimension[0];
const n = A.dim[0];

@@ -328,3 +406,3 @@ for (i = 0; i < n; i++) {

}
X.type = Math.max(...X.array.map((row) => ComplexDecimal.maxNumberType(...row)));
X.setType();
return X;

@@ -342,13 +420,13 @@ }

public static lu(M: MultiArray): any {
if (M.dimension[0] !== M.column) {
if (M.dim[0] !== M.dim[1]) {
throw new Error(`PLU decomposition can only be applied to square matrices.`);
}
const n = M.dimension[0]; // Size of the square matrix
const n = M.dim[0]; // Size of the square matrix
// Initialize P as an identity matrix with the appropriate dimensions
const P = MultiArray.eye(new ComplexDecimal(n)) as MultiArray;
const P = LinearAlgebra.eye(new ComplexDecimal(n)) as MultiArray;
// Initialize L as an identity matrix with the same dimensions as the input matrix
const L = MultiArray.eye(new ComplexDecimal(n)) as MultiArray;
const L = LinearAlgebra.eye(new ComplexDecimal(n)) as MultiArray;

@@ -393,3 +471,3 @@ // Initialize U as a copy of the input matrix

}
return EvaluatorPointer.nodeReturnList((length: number, index: number): any => {
return global.EvaluatorPointer.nodeReturnList((length: number, index: number): any => {
if (length === 1) {

@@ -396,0 +474,0 @@ return U;

@@ -6,6 +6,5 @@ import { MathObject } from './math-object';

expect(MathObject).toBeDefined();
expect(MathObject.linearize).toBeDefined();
expect(MathObject.copy).toBeDefined();
expect(MathObject.ewiseOp).toBeDefined();
expect(MathObject.leftOp).toBeDefined();
expect(MathObject.elementWiseOperation).toBeDefined();
expect(MathObject.leftOperation).toBeDefined();
expect(MathObject.mand).toBeDefined();

@@ -12,0 +11,0 @@ expect(MathObject.mor).toBeDefined();

import { ComplexDecimal } from './complex-decimal';
import { MultiArray } from './multi-array';
import { LinearAlgebra } from './linear-algebra';

@@ -39,4 +40,2 @@ export abstract class MathObject {

public static readonly linearize = MultiArray.linearize;
public static copy(right: any): any {

@@ -50,3 +49,3 @@ if ('re' in right) {

public static ewiseOp(
public static elementWiseOperation(
op: 'add' | 'sub' | 'mul' | 'rdiv' | 'ldiv' | 'power' | 'lt' | 'le' | 'eq' | 'ge' | 'gt' | 'ne' | 'and' | 'or' | 'xor' | 'mod' | 'rem',

@@ -63,11 +62,11 @@ left: any,

} else if ('array' in left && 'array' in right) {
return MultiArray.ewiseOp(op, left, right);
return MultiArray.elementWiseOperation(op, left, right);
}
}
public static leftOp(op: 'copy' | 'neg' | 'not', right: any): any {
public static leftOperation(op: 'copy' | 'neg' | 'not', right: any): any {
if ('re' in right) {
return ComplexDecimal[op](right);
} else if ('array' in right) {
return MultiArray.leftOp(op, right);
return MultiArray.leftOperation(op, right);
}

@@ -77,19 +76,19 @@ }

public static plus(left: any, right: any): any {
return MathObject.ewiseOp('add', left, right);
return MathObject.elementWiseOperation('add', left, right);
}
public static minus(left: any, right: any): any {
return MathObject.ewiseOp('sub', left, right);
return MathObject.elementWiseOperation('sub', left, right);
}
public static mod(left: any, right: any): any {
return MathObject.ewiseOp('mod', left, right);
return MathObject.elementWiseOperation('mod', left, right);
}
public static rem(left: any, right: any): any {
return MathObject.ewiseOp('rem', left, right);
return MathObject.elementWiseOperation('rem', left, right);
}
public static times(left: any, right: any): any {
return MathObject.ewiseOp('mul', left, right);
return MathObject.elementWiseOperation('mul', left, right);
}

@@ -105,3 +104,3 @@

} else if ('array' in left && 'array' in right) {
return MultiArray.mul(left, right);
return LinearAlgebra.mul(left, right);
}

@@ -111,3 +110,3 @@ }

public static rdivide(left: any, right: any): any {
return MathObject.ewiseOp('rdiv', left, right);
return MathObject.elementWiseOperation('rdiv', left, right);
}

@@ -119,7 +118,7 @@

} else if ('re' in left && 'array' in right) {
return MultiArray.scalarOpMultiArray('mul', left, MultiArray.inv(right));
return MultiArray.scalarOpMultiArray('mul', left, LinearAlgebra.inv(right));
} else if ('array' in left && 're' in right) {
return MultiArray.scalarOpMultiArray('mul', ComplexDecimal.inv(right), left);
} else if ('array' in left && 'array' in right) {
return MultiArray.mul(left, MultiArray.inv(right));
return LinearAlgebra.mul(left, LinearAlgebra.inv(right));
}

@@ -129,3 +128,3 @@ }

public static ldivide(left: any, right: any): any {
return MathObject.ewiseOp('ldiv', left, right);
return MathObject.elementWiseOperation('ldiv', left, right);
}

@@ -136,3 +135,3 @@

public static power(left: any, right: any): any {
return MathObject.ewiseOp('power', left, right);
return MathObject.elementWiseOperation('power', left, right);
}

@@ -144,3 +143,3 @@

} else if ('array' in left && 're' in right) {
return MultiArray.power(left, right);
return LinearAlgebra.power(left, right);
} else {

@@ -152,7 +151,7 @@ throw new Error("invalid exponent in '^'.");

public static uplus(right: any): any {
return MathObject.leftOp('copy', right);
return MathObject.leftOperation('copy', right);
}
public static uminus(right: any): any {
return MathObject.leftOp('neg', right);
return MathObject.leftOperation('neg', right);
}

@@ -164,3 +163,3 @@

} else if ('array' in left) {
return MultiArray.transpose(left);
return LinearAlgebra.transpose(left);
}

@@ -173,3 +172,3 @@ }

} else if ('array' in left) {
return MultiArray.ctranspose(left);
return LinearAlgebra.ctranspose(left);
}

@@ -179,23 +178,23 @@ }

public static lt(left: any, right: any): any {
return MathObject.ewiseOp('lt', left, right);
return MathObject.elementWiseOperation('lt', left, right);
}
public static le(left: any, right: any): any {
return MathObject.ewiseOp('le', left, right);
return MathObject.elementWiseOperation('le', left, right);
}
public static eq(left: any, right: any): any {
return MathObject.ewiseOp('eq', left, right);
return MathObject.elementWiseOperation('eq', left, right);
}
public static ge(left: any, right: any): any {
return MathObject.ewiseOp('ge', left, right);
return MathObject.elementWiseOperation('ge', left, right);
}
public static gt(left: any, right: any): any {
return MathObject.ewiseOp('gt', left, right);
return MathObject.elementWiseOperation('gt', left, right);
}
public static ne(left: any, right: any): any {
return MathObject.ewiseOp('ne', left, right);
return MathObject.elementWiseOperation('ne', left, right);
}

@@ -236,12 +235,12 @@

public static and(left: any, right: any): any {
return MathObject.ewiseOp('and', left, right);
return MathObject.elementWiseOperation('and', left, right);
}
public static or(left: any, right: any): any {
return MathObject.ewiseOp('or', left, right);
return MathObject.elementWiseOperation('or', left, right);
}
public static xor(left: any, right: any): any {
return MathObject.ewiseOp('xor', left, right);
return MathObject.elementWiseOperation('xor', left, right);
}
}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc