Computer Algebra System for Symbolic Computation for Combinatorics and Algebraic Number Theory for JavaScript and Python
version 2.0.0 in progress
Abacus
is a relatively small and versatile computer algebra and symbolic computation system containing methods and math utilities for fast combinatorial object computation and algebraic / number theoretic computation. It builds on, and extends, a deprecated previous project Simulacra
.
Abacus
uses mostly self-contained and standalone methods, so they can be easily copy-pasted in other projects, in case only a few methods are needed and not the whole library.
- Live Playground Example
- Features
- Combinatorial and Number Theory Examples
- Performance
- Credits and References
- Example API
- Todo
Supports: (see: test/test.bat
)
Combinatorics
-
Tensor
(test/tensors.js
) -
Tuple
(test/tuples.js
) -
Permutation
(test/permutations.js
,test/permutations-bigint.js
) -
CyclicPermutation
(test/cyclic_permutations.js
) -
MultisetPermutation
(test/multiset_permutations.js
) -
DerangementPermutation
(test/derangements.js
) -
InvolutionPermutation
(test/involutions.js
) supported order is LEX of swaps -
ConnectedPermutation
(test/connected_permutations.js
) supported order is LEX of cycle -
UnorderedCombination
/Combination
(test/combinations.js
) -
OrderedCombination
/Variation
/kPermutation
(test/ordered_combinations.js
) -
UnorderedRepeatedCombination
/RepeatedCombination
(test/combinations_repeats.js
) -
OrderedRepeatedCombination
/RepeatedVariation
/kTuple
(test/ordered_combinations_repeats.js
) -
Subset
(test/subsets.js
) -
Partition
(test/partitions.js
) partial support for COLEX -
Composition
(test/compositions.js
) partial support for COLEX -
RestrictedPartition
(test/restricted_partitions.js
) partial support for COLEX -
RestrictedComposition
(test/restricted_compositions.js
) partial support for COLEX -
SetPartition
(test/setpartitions.js
) rank/unrank methods missing, only LEX/REVLEX order -
RestrictedSetPartition
(test/setpartitions.js
) exactly K #parts, rank/unrank methods missing, only LEX/REVLEX order -
CatalanWord
(eg balanced parentheses) (test/paren.js
) rank/unrank methods missing -
LatinSquare
(test/latin_squares.js
) -
MagicSquare
(test/magic_squares.js
) -
algebraic composition and sequences of combinatorial objects to construct new combinatorial objects (eg
all combinations
=all permutations
OFall unique combinations
, seetest/permutations_of_combinations.js
andtest/permutations_of_permutations.js
,k-Derangements
=(n,k) Combinations
combined With(n-k) Derangements
, seetest/k-derangements.js
orall subsets
=(n,0)Combinations + (n,1)Combinations + .. + (n,n-1)Combinations + (n,n)Combinations
, seetest/combination_subsets.js
) -
custom and built-in filters which can select and generate any custom and complex combinatorial object from filtering other combinatorial objects as efficiently as possible (e.g see
test/filtered.js
,test/filtered_partitions.js
). Also algebraic / boolean composition of filters (i.e.NOT()
,.AND()
,.OR()
and so on..). Note that filtering should be used with caution and only if no other method is currently possible to generate the desired combinatorial object as filtering is equivalent to exhaustive search over the space of the original combinatorial object and as such can be an inefficient way to generate a combinatorial object (e.g seetest/filtered.js
). Note2 with filtering applied some methods like.total()
,.hasNext()
still return data of the original object not the filtered object since that would require to pre-generate all the data and filter them afterwards instead of doing it one-by-one on each generation and would be impractical and unachievable for very large combinatorial objects, so be careful when using, for example,.total()
with fitering applied -
multiple (combined) iterator orderings & traversals:
lex
,colex
,random
,reversed
,reflected
,minimal
(not implemented yet). For example:"revlex"
(equivalent to"lex,reversed"
),"refcolex"
(equivalent to"colex,reflected"
), and so on.. -
arbitrary range of combinatorial objects in a number of supported orderings (ie
lex
,colex
,random
,..) (and with filtering applied, if set). Noteunrank
methods have to be implemented for this feature to work -
efficient and unbiased generation, (un)ranking, succession & random methods for supported combinatorial objects (see below)
Symbolic Computations
-
Numbers, eg
fibonacci
,catalan
,bell
,factorial
,partition
,polygonal
, .. (test/numbers.js
) -
Number Theory Functions, eg
gcd
/xgcd
/polygcd
/polyxgcd
/groebner
,divisors
,moebius
,legendre
,jacobi
,isqrt
,ikthroot
, .. (test/number_theory.js
) -
Integer
(test/integers.js
),Rational
(test/rationals.js
),Complex
(test/complex.js
) supporting arbitrary precision arithmetic -
Polynomial
,MultiPolynomial
(test/polynomials.js
,test/multivariate.js
) univariate / multivariate with coefficients from a Ring/Field -
RationalFunc
(test/ratfuncs.js
) Rational functions as fractions of multivariate polynomials -
Algebraic
Rings
andFields
eg.Ring.Z(), Ring.Q(), Ring.C(), Ring.Q("x","y"), ..
(test/polynomials.js
,test/multivariate.js
,test/ratfuncs.js
) -
Matrix
(test/matrices.js
) with coefficients from a Ring/Field -
Expr
(test/expressions.js
) general Symbolic Expressions -
Progression
(Infinite, Arithmetic, Geometric) (test/progressions.js
) -
PrimeSieve
, Primality Tests, Prime Factorisation (test/primes.js
) -
Diophantine
, Linear Equations, Linear Congruences, Pythagorean n-Tuples (test/diophantine.js
) -
big-integer arithmetic
,PRNG
s and othermath
utilities are pluggable using external implementations, making the lib very flexible especialy with respect to handling big-integers & (pseudo-)random number generators (examples use the excellent BigInteger.js)
first
/last
,random
,rank
/unrank
methods use efficient linearO(n)
(or log-linearO(nlgn)
) time and space algorithms (note a couple of rank/unrank methods are ofO(n^2)
or higher order)random
methods are statistically unbiased (ie uniform sampling methods, see below as well)successor
methods use efficient CAT (ie constant amortized time) or Loopless (ie strictly constant time) algorithms to generate next/prev object from current object (supporting multiple combinatorial orderings along the way, see above) (note a couple of methods are linear time algorithms because the lib does not use extra space to store information between successive runs and also support static random access to successors so any extra is computed atrun-time
, but can easily be madeCAT
or evenLoopless
by storing extra information, eg current index position)- avoid big-integer arithmetic and computational overhead (except if explicit
ranking
/unranking
is needed and objects are large) - symbolic polynomials use efficient sparse representation
- number-theoretic/math computations support pluggable arithmetics (thus if used can compute with arbitrary precision arithmetic), algorithms implemented are efficient but not necessarily the most efficient version (theoretically) possible (eg default Euclidean algorithm for
gcd
used, although optimised), possible to implement even faster algorithms in future verions
Note that Abacus
can generate very large (and also randomised) combinatorial objects without ever using biginteger arithmetic due to design and implementation except if arbitrary random
, ranking
and unranking
have to be used (see above)
See the comments in the code for algorithms and references used.
- The Art of Computer Programming, Donald Knuth
- FXT library, Joerg Arndt and his PhD thesis
- Combinatorial Algorithms, Albert Nijenhuis, Herbert Wilf
- Combinatorial Generation, Frank Ruskey
- Generating Functionology, Herbert Wilf
- A unified setting for sequencing, ranking, and selection algorithms for combinatorial objects, Herbert Wilf
- Permutation Generation Methods, Robert Sedgewick
- A Versatile Algorithm to Generate Various Combinatorial Structures, Pramod Ganapathi, Rama B
- Generating All and Random Instances of a Combinatorial Object, Ivan Stojmenovic including the section on random generation without large integers & with only one
PRNG
call - Efficient Generation of Set Partitions, Michael Orlov
- Algorithms for Unranking Combinations and Other Related Choice Functions, Zbigniew Kokosinski
- Analytic Combinatorics, Philippe Flajolet, Robert Sedgewick can also be used to produce combinatorial generation algorithms instead of just generating functions for counting and statistics
- Gray Code, wikipedia
- A Survey of Combinatorial Gray Codes, Carla Savage
- Generalized Gray Codes with Applications, DAH-JYH GUAN
- A SIMPLE SEQUENCING AND RANKING METHOD THAT WORKS ON ALMOST ALL GRAY CODES, Timothy R. Walsh
- Gray Code Enumeration of Families of Integer Partitions, David Rasmussen, Carla D. Savage, Douglas B. West
- A GRAY CODE FOR SET PARTITIONS, Richard KAYE
- Combinatorial Generation by Fusing Loopless Algorithms, Tadao Takaoka, Stephen Violich
- Make good (Pseudo-)Random Number Generators
- Handbook of Applied Cryptography, Chapter 4
- The Quadratic Sieve Factoring Algorithm, Eric Landquist
- A Beginner’s Guide To The General Number Field Sieve, Michael Case
- Implementation of a New Primality Test, H. Cohen, A.K. Lenstra
- Integer Algorithms to solve Diophantine Linear Equations and Systems, Florentin Smarandache
- Linear Diophantine Equations, William J. Gilbert, Anu Pathria
- Chinese Remainder Theorem, wikipedia
- A multivariable Chinese remainder theorem, Oliver Knill
- Solving a System of Linear Diophantine Equations with Lower and Upper Bounds on the Variables, K. Aardal, C.A.J. Hurkens, A.K. Lenstra
- Integer Programming with a Fixed Number of Variables, H.W. Lenstra
- Integer Programming with 2-Variable Equations and 1-Variable Inequalities, Bodirsky, Nordh, Von Oertzen
- Fourier-Motzkin Elimination, wikipedia
- Fourier's Elimination: Which to Choose?, Jean-Louis Imbert
- Complexity Estimates for Fourier-Motzkin Elimination, Rui-Juan Jing, Marc Moreno-Maza, Delaram Talaashrafi
- Fourier-Motzkin Elimination Extension to Integer Programming Problems , H.P. Williams
- Fraction-free matrix factors: new forms for LU and QR factors, Wenqin ZHOU, David J. JEFFREY
- Fraction-Free Methods for Determinants, Deanna Richelle Leggett (MSc thesis)
- Moore-Penrose Generalised Inverse, wikipedia
- The Moore-Penrose Pseudoinverse. A Tutorial Review of the Theory, J.C.A. Barata, M.S. Hussein
- A general matrix eigenvalue algorithm, Charles F. Van Loan
- Algorithms and Data Structures for Sparse Polynomial Arithmetic, M. Asadi, A. Brandt, R. H. C. Moir, M. M. Maza
- High Performance Sparse Multivariate Polynomials: Fundamental Data Structures and Algorithms, Alex Brandt (MSc thesis)
- GCDHEU: Heuristic Polynomial GCD Algorithm Based On Integer GCD Computation, B. W. Char, K. O. Geddes and G. H. Gonnet
- An improved EZ-GCD algorithm for multivariate polynomials, Kuniaki Tsuji
- The EEZ-GCD algorithm, Paul S. Wang
- Non-modular computation of polynomial GCDS using trial division, Anthony C. Hearn
- Three new algorithms for multivariate polynomial GCD, T. Sasaki and M. Suzuki
- Greedy Algorithms for Optimizing Multivariate Horner Schemes, M. Ceberio and V. Kreinovich
- Resultant, wikipedia
- Discriminant, wikipedia
- Gröbner basis, wikipedia
- Buchberger's algorithm, wikipedia
- Faugère's F4 and F5 algorithms, wikipedia
- Partial Fraction Decomposition, wikipedia
- A Note on Multivariate Polynomial Division and Gröbner Bases, A. T. Lipkovski and S. Zeada
- Factorization of polynomials, wikipedia
- Rational root theorem, wikipedia
- Square-free Decomposition, wikipedia
- Factorization of polynomials over finite fields, wikipedia
- Symbolic factoring of polynomials in several variables, Dale E. Jordan, Lewis C. Clapp, Richard Y. Kain
- Aberth method, wikipedia
- Numerical computation of polynomial zeros by means of Aberth's method, D. A. Bini
- Newton's method, wikipedia
- Roots of multivariate polynomials, Chapter 11
- Geometrical properties of polynomial roots, wikipedia
- $olving Systems of Algebraic Equations by Using Gröbner Bases, Michael Kalkbrener
let o = Abacus.Permutation(4);
console.log(String(o.total()));
console.log('---');
for (let item of o)
{
console.log(item.join(','));
}
24
---
0,1,2,3
0,1,3,2
0,2,1,3
0,2,3,1
0,3,1,2
0,3,2,1
1,0,2,3
1,0,3,2
1,2,0,3
1,2,3,0
1,3,0,2
1,3,2,0
2,0,1,3
2,0,3,1
2,1,0,3
2,1,3,0
2,3,0,1
2,3,1,0
3,0,1,2
3,0,2,1
3,1,0,2
3,1,2,0
3,2,0,1
3,2,1,0
let o = Abacus.Partition(6);
console.log(String(o.total()));
console.log('---');
for (let item of o)
{
console.log(item.join('+'));
}
11
---
1+1+1+1+1+1
2+1+1+1+1
2+2+1+1
2+2+2
3+1+1+1
3+2+1
3+3
4+1+1
4+2
5+1
6
let field = Abacus.Ring.Q("x").associatedField();
let m = Abacus.Matrix(field, [
["x-1", "x^2-1"],
["x^2-1", "x-1"]
]);
console.log(m.toString());
console.log(m.inv().toString());
console.log(m.inv().mul(m).toString());
| x-1 x^2-1|
|x^2-1 x-1|
| -1/(x^3+x^2-2*x) (x+1)/(x^3+x^2-2*x)|
|(x+1)/(x^3+x^2-2*x) -1/(x^3+x^2-2*x)|
|1 0|
|0 1|
- apply built-in language
iterator
/iterable
patterns (ES6iterator
protocol). Combinatorial objects additionaly support adoubly-linked list
-like interface, i.eprev
/next
accessors [DONE] - support exact
biginteger
arithmetic computations e.g large factorials [DONE], arithmetic routines have been made pluggable and one can use an external implementation, see examples - support multiple combined custom iterator orderings, i.e
lex
,colex
,reversed
,reflected
,random
seamlessly and uniformly, both forward and backward [DONE],random
ordering may be optimised further - support multiple combinatorial orderings (ie
lex
,colex
,reflex
,refcolex
,minimal
, ..) directly in the successor methods instead of using post-transformations on object [DONE] - support efficient successor methods (preferably
CAT/Loopless
methods) to generate next/prev object from current object [DONE] - support efficient ranking / unranking algorithms and associated methods (preferably of
O(n)
orO(nlgn)
complexity) for supported orderings [DONE] - support unique and uniform random ordering traversals for all combinatorial objects, so that the space of a combinatorial object can be traversed in any random ordering uniquely and unbiasedly (useful in some applications, eg backtracking) [DONE], used as custom iterator ordering, may be optimised further
- make sure the
random()
methods uniformly and unbiasedly sample the combinatorial object space (methods use unbiased sampling algorithms, however results in certain cases might depend on quality of PRNGs) [DONE] - support algebraic composition/cascading of combinatorial objects to construct new combinatorial objects (eg
all combinations
=all permutations
OFall unique combinations
) [DONE] - support generation of supported combinatorial objects with additional user-defined patterns/templates of constraints to satisfy e.g "only combinatorial objects matching
'(n)(m)(1){2}(){3}(0)((n+1))((n+m)){4}'
" pattern.. [DONE] - add
LatinSquare
,MagicSquare
algorithms [DONE] - add run-time/lazy custom and/or built-in filtering support (with support for filter composition as well) to generate and select custom and complex combinatorial objects from filtering other combinatorial objects as efficiently as possible [DONE]
- support efficient primality tests and prime sieves [DONE PARTIALLY]
- support efficient integer factorization algorithms [DONE PARTIALLY]
- support general symbolic expressions and computations in
Expr
[DONE] - add
Rank Factorisation
[DONE] - implement
GINV
(Moore-Penrose Inverse) computation [DONE] - implement symbolic/numeric
EVD / SVD
computation (TODO) - support solutions of (systems of) linear diophantine and linear congruence equations (with one or many variables) [DONE]
- support general and least-squares solutions of arbitrary linear systems [DONE]
- support solutions of (systems of) linear diophantine and linear congruence inequalities (with one or many variables) [DONE PARTIALLY]
- use optimized sparse representation and computations for polynomials instead of the inefficient dense representation [DONE]
- support multivariate polynomial, multivariate operations [DONE]
- support (univariate) polynomial factorization over the integers, rational root finding [DONE]
- support (multivariate) polynomial factorization over the integers, rational root finding (eg
Kronecker
algorithm) (TODO) - support polynomial approximate root finding (eg
Aberth
algorithm) (TODO) - implement recursive multivariate polynomial
GCD
from univariate polynomialGCD
[DONE] - implement more efficient multivariate polynomial
GCD
(TODO) - implement
LLL
algorithm (TODO) - implement polynomial
Resultant
,Discriminant
computations [DONE] - implement
Groebner Basis
computations (Buchberger
algorithm) [DONE] - implement more efficient
Groebner Basis
computations (TODO) - support generic algebraic Rings and Fields (including rings of polynomials and fraction fields of polynomials) [DONE]
- support algebraic sub-Rings and sub-Fields (eg Q(y,z)(x) with coefficients from the subring Q(y,z)) [DONE]
- implement faster number-theoretic/integer algorithms (maybe fine-tuned further based on if BigInteger Arithmetic is used) if worth the trouble (eg
fibonacci
,factorial
,gcd
, ..) [DONE PARTIALLY] - full support for
colex
orderingComposition
&Partition
[DONE PARTIALLY] - add efficient
rank
/unrank
methods forComposition
&Partition
[DONE] - add efficient
rank
/unrank
methods forDerangementPermutation
[DONE] - add efficient
rank
/unrank
methods forConnectedPermutation
[DONE] - add efficient
rank
/unrank
methods forInvolutionPermutation
[DONE] (not very efficient) - support
minimal
/gray
ordering (and successor) for all supported combinatorial objects (TODO) - support graph combinatorial objects like
Graph
,Grammar
,.. (TODO?) (for regular grammars and expressions see RegexAnalyzer for an example)
see also:
- Abacus advanced Combinatorics and Algebraic Number Theory Symbolic Computation Library for JavaScript, Python
- TensorView view array data as multidimensional tensors of various shapes efficiently
- Geometrize Computational Geometry and Rendering Library for JavaScript
- Plot.js simple and small library which can plot graphs of functions and various simple charts and can render to Canvas, SVG and plain HTML
- CanvasLite a lite canvas implementation in pure JavaScript
- Rasterizer stroke and fill lines, rectangles, curves and paths, without canvas
- Gradient create linear, radial, conic and elliptic gradients and image patterns without canvas
- css-color simple class to parse and manipulate colors in various formats
- MOD3 3D Modifier Library in JavaScript
- HAAR.js image feature detection based on Haar Cascades in JavaScript (Viola-Jones-Lienhart et al Algorithm)
- HAARPHP image feature detection based on Haar Cascades in PHP (Viola-Jones-Lienhart et al Algorithm)
- FILTER.js video and image processing and computer vision Library in pure JavaScript (browser and node)
- Xpresion a simple and versatile eXpression parser engine (with custom functions and variables support), based on GrammarTemplate, for PHP, JavaScript, Python
- Regex Analyzer/Composer Regular Expression Analyzer and Composer for PHP, JavaScript, Python
- GrammarTemplate grammar-based templating for PHP, JavaScript, Python
- codemirror-grammar transform a formal grammar in JSON format into a syntax-highlight parser for CodeMirror editor
- ace-grammar transform a formal grammar in JSON format into a syntax-highlight parser for ACE editor
- prism-grammar transform a formal grammar in JSON format into a syntax-highlighter for Prism code highlighter
- highlightjs-grammar transform a formal grammar in JSON format into a syntax-highlight mode for Highlight.js code highlighter
- syntaxhighlighter-grammar transform a formal grammar in JSON format to a highlight brush for SyntaxHighlighter code highlighter
- SortingAlgorithms implementations of Sorting Algorithms in JavaScript
- PatternMatchingAlgorithms implementations of Pattern Matching Algorithms in JavaScript