-
Notifications
You must be signed in to change notification settings - Fork 435
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added n-dimensional arrays / matrix and their operations Supported eq, apply funciton for all dimensions Added matrix multiplicaiton and transposition
- Loading branch information
1 parent
fb7e75e
commit 8a4e8e3
Showing
5 changed files
with
550 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2024 Pablo | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
## Numty | ||
|
||
### Numeric Typst | ||
|
||
A library for performing mathematical operations on n-dimensional matrices, vectors/arrays, and numbers in Typst, with support for broadcasting and handling NaN values. Numty’s broadcasting rules and API are inspired by NumPy. | ||
|
||
```typ | ||
#import "numty.typ" as nt | ||
// Define vectors and matrices | ||
#let a = (1, 2, 3) | ||
#let b = 2 | ||
#let m = ((1, 2), (1, 3)) | ||
// Element-wise operations with broadcasting | ||
#nt.mult(a, b) // Multiply vector 'a' by scalar 'b': (2, 4, 6) | ||
#nt.add(a, a) // Add two vectors: (2, 4, 6) | ||
#nt.add(2, a) // Add scalar '2' to each element of vector 'a': (3, 4, 5) | ||
#nt.add(m, 1) // Add scalar '1' to each element of matrix 'm': ((2, 3), (2, 4)) | ||
// Dot product of vectors | ||
#nt.dot(a, a) // Dot product of vector 'a' with itself: 14 | ||
// Handling NaN cases in mathematical functions | ||
#calc.sin((3, 4)) // Fails, as Typst does not support vector operations directly | ||
#nt.sin((3.4)) // Sine of each element in vector: (0.14411, 0.90929) | ||
// Generate equally spaced values and vectorized functions | ||
#let x = nt.linspace(0, 10, 3) // Generate 3 equally spaced values between 0 and 10: (0, 5, 10) | ||
#let y = nt.sin(x) // Apply sine function to each element: (0, -0.95, -0.54) | ||
// Logical operations | ||
#nt.eq(a, b) // Compare each element in 'a' to 'b': (false, true, false) | ||
#nt.any(nt.eq(a, b)) // Check if any element in 'a' equals 'b': true | ||
#nt.all(nt.eq(a, b)) // Check if all elements in 'a' equal 'b': false | ||
// Handling special cases like division by zero | ||
#nt.div((1, 3), (2, 0)) // Element-wise division, with NaN for division by zero: (0.5, float.nan) | ||
// Matrix operations (element-wise) | ||
#nt.add(m, 1) // Add scalar to matrix elements: ((2, 3), (2, 4)) | ||
// matrix | ||
#nt.transpose(m) // transposition | ||
#nt.matmul(m,m) // matrix multipliation | ||
``` | ||
|
||
Since vesion 0.0.4 n-dim matrices are supported as well in most operations. | ||
|
||
## Supported Features: | ||
|
||
### Logic Operations: | ||
```typ | ||
#import "numty.typ" as nt | ||
#let a = (1,2,3) | ||
#let b = 2 | ||
#nt.eq(a,b) // (false, true, false) | ||
#nt.all(nt.eq(a,b)) // false | ||
#nt.any(nt.eq(a,b)) // true | ||
``` | ||
|
||
### Math operators: | ||
|
||
All operators are element-wise, | ||
traditional matrix multiplication is not yet supported. | ||
|
||
```typ | ||
#nt.add((0,1,3), 1) // (1,2,4) | ||
#nt.mult((1,3),(2,2)) // (2,6) | ||
#nt.div((1,3), (2,0)) // (0.5,float.nan) | ||
``` | ||
|
||
### Algebra with Nan handling: | ||
|
||
```typ | ||
#nt.log((0,1,3)) // (float.nan, 0 , 0.47...) | ||
#nt.sin((1,3)) // (0.84.. , 0.14...) | ||
``` | ||
|
||
### Vector operations: | ||
|
||
Basic vector operations | ||
|
||
```typ | ||
#nt.dot((1,2),(2,4)) // 9 | ||
#nt.normalize((1,4), l:1) // (1/5,4/5) | ||
``` | ||
|
||
### Others: | ||
|
||
Functions for creating equally spaced indexes in linear and logspace, usefull for log plots | ||
|
||
```typ | ||
#nt.linspace(0,10,3) // (0,5,10) | ||
#nt.logspace(1,3,3) | ||
#nt.geomspace(1,3,3) | ||
``` | ||
|
||
### Printing | ||
|
||
```typ | ||
#nt.print((1,2),(4,2))) // to display in the pdf | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,204 @@ | ||
// == types == | ||
|
||
#let arrarr(a,b) = (type(a) == array and type(b) == array) | ||
#let arrflt(a,b) = (type(a) == array and type(b) != array) | ||
#let fltarr(a,b) = (type(a) != array and type(b) == array) | ||
#let fltflt(a,b) = (type(a) != array and type(b) != array) | ||
#let is-arr(a) = (type(a) == array) | ||
#let is-mat(m) = (is-arr(m) and is-arr(m.at(0))) | ||
#let matmat(m,n) = is-mat(m) and is-mat(n) | ||
#let matflt(m,n) = is-mat(m) and type(n) != array | ||
#let fltmat(m,n) = is-mat(n) and type(m) != array | ||
|
||
// == boolean == | ||
|
||
#let isna(v) = { | ||
if is-arr(v){ | ||
v.map(i => if (type(i)==float){i.is-nan()} else {false}) | ||
} | ||
else{ | ||
if (type(v)==float){v.is-nan()} else {false} | ||
} | ||
} | ||
|
||
#let all(v) ={ | ||
if is-arr(v){ | ||
v.flatten().all(a => a == true or a ==1) | ||
} | ||
else{ | ||
v == true or v == 1 | ||
} | ||
} | ||
|
||
#let op(a,b, fun) ={ | ||
// generic operator with broacasting | ||
if matmat(a,b) { | ||
a.zip(b).map(((a,b)) => op(a,b, fun)) | ||
} | ||
else if matflt(a,b){ // supports n-dim matrices | ||
a.map(v=> op(v,b, fun)) | ||
} | ||
else if fltmat(a,b){ | ||
b.map(v=> op(a,v, fun)) | ||
} | ||
else if arrarr(a,b) { | ||
a.zip(b).map(((i,j)) => fun(i,j)) | ||
} | ||
else if arrflt(a,b) { | ||
a.map(a => fun(a,b)) | ||
} | ||
else if fltarr(a,b) { | ||
b.map(i => fun(a,i)) | ||
} | ||
else { | ||
fun(a,b) | ||
} | ||
} | ||
|
||
#let _eq(i,j, equal-nan) ={ | ||
i==j or (all(isna((i,j))) and equal-nan) | ||
} | ||
|
||
#let eq(u,v, equal-nan: false) = { | ||
// Checks for equality element wise | ||
// eq((1,2,3), (1,2,3)) = (true, true, true) | ||
// eq((1,2,3), 1) = (true, false, false) | ||
let _eqf(i,j)={_eq(i,j, equal-nan)} | ||
op(u,v, _eqf) | ||
} | ||
|
||
|
||
#let any(v) ={ | ||
// check if any item is true after iterating everything | ||
if is-arr(v){ | ||
v.flatten().any(a => a == true or a ==1) | ||
} | ||
else{ | ||
v == true or v == 1 | ||
} | ||
} | ||
|
||
#let all-eq(u,v) = all(eq(u,v)) | ||
|
||
#let apply(a, fun) ={ | ||
// vectorize | ||
// consider returnding a function of a instead? | ||
if is-arr(a){ //recursion exploted for n-dim | ||
a.map(v=>apply(v, fun)) | ||
} | ||
else{ | ||
fun(a) | ||
} | ||
} | ||
|
||
#let abs(a)= apply(a, calc.abs) | ||
|
||
// == Operators == | ||
|
||
#let _add(a,b)=(a + b) | ||
#let _sub(a,b)=(a - b) | ||
#let _mul(a,b)=(a * b) | ||
#let _div(a,b)= if (b!=0) {a/b} else {float.nan} | ||
|
||
|
||
|
||
#let add(u,v) = op(u,v, _add) | ||
#let sub(u, v) = op(u,v, _sub) | ||
#let mult(u, v) = op(u,v, _mul) | ||
#let div(u, v) = op(u,v, _div) | ||
#let pow(u, v) = op(u,v, calc.pow) | ||
|
||
// == vectorial == | ||
|
||
#let normalize(a, l:2) = { | ||
// normalize a vector, defaults to L2 normalization | ||
let aux = pow(pow(abs(a),l).sum(),1/l) | ||
a.map(b => b/aux) | ||
} | ||
|
||
// dot product | ||
|
||
#let dot(a,b) = mult(a,b).sum() | ||
|
||
// == Algebra, trigonometry == | ||
|
||
|
||
#let sin(a) = apply(a,calc.sin) | ||
#let cos(a) = apply(a,calc.cos) | ||
#let tan(a) = apply(a,calc.tan) | ||
#let log(a) = apply(a, j => if (j>0) {calc.log(j)} else {float.nan} ) | ||
|
||
// matrix | ||
|
||
#let transpose(m) = { | ||
// Get dimensions of the matrix | ||
let rows = m.len() | ||
let cols = m.at(0).len() | ||
range(0, cols).map(c => range(0, rows).map(r => m.at(r).at(c))) | ||
} | ||
|
||
#let matmul(a,b) = { | ||
let bt = transpose(b) | ||
a.map(a_row => bt.map(b_col => dot(a_row,b_col))) | ||
} | ||
|
||
// others: | ||
|
||
#let linspace = (start, stop, num) => { | ||
// mimics numpy linspace | ||
let step = (stop - start) / (num - 1) | ||
range(0, num).map(v => start + v * step) | ||
} | ||
|
||
#let logspace = (start, stop, num, base: 10) => { | ||
// mimics numpy logspace | ||
let step = (stop - start) / (num - 1) | ||
range(0, num).map(v => calc.pow(base, (start + v * step))) | ||
} | ||
|
||
#let geomspace = (start, stop, num) => { | ||
// mimics numpy geomspace | ||
let step = calc.pow( stop / start, 1 / (num - 1)) | ||
range(0, num).map(v => start * calc.pow(step,v)) | ||
} | ||
|
||
#let to-str(a) = { | ||
if (type(a) == bool){ | ||
if(a){ | ||
"value1" | ||
} | ||
else { | ||
"value2" | ||
} | ||
} | ||
else{ | ||
str(a) | ||
} | ||
} | ||
|
||
#let print(M) = { | ||
if is-mat(M) { | ||
eval("$ mat(" + M.map(v => v.map(j=>to-str(j)).join(",")).join(";")+ ") $") | ||
} | ||
else if is-arr(M){ | ||
eval("$ vec(" + M.map(v => str(v)).join(",")+ ") $") | ||
} | ||
else{ | ||
eval(" $"+str(M)+"$ ") | ||
} | ||
} | ||
|
||
|
||
|
||
#let p(M) = { | ||
let scope = (value1: "true", value2: "false") | ||
if is-mat(M) { | ||
eval("$mat(" + M.map(v => v.map(j=>to-str(j)).join(",")).join(";")+ ")$", scope: scope) | ||
} | ||
else if is-arr(M){ | ||
eval("$vec(" + M.map(v => str(v)).join(",")+ ")$") | ||
} | ||
else{ | ||
eval("$"+str(M)+"$") | ||
} | ||
} |
Oops, something went wrong.