diff --git a/packages/preview/numty/0.1.0/LICENSE b/packages/preview/numty/0.1.0/LICENSE new file mode 100644 index 0000000000..4b7df6069d --- /dev/null +++ b/packages/preview/numty/0.1.0/LICENSE @@ -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. diff --git a/packages/preview/numty/0.1.0/README.md b/packages/preview/numty/0.1.0/README.md new file mode 100644 index 0000000000..7727eef47f --- /dev/null +++ b/packages/preview/numty/0.1.0/README.md @@ -0,0 +1,139 @@ +## 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 +#nt.matmul(c(1,2), r(2,3)) // colum vector times row vector multiplication. +#np.trace(m) // trace +#np.det(m) // nxn determinant + +// printing +#nt.print(m, " != " , (1,2)) // long dollar print, see in pdf +#nt.p(m, " != " , (1,2)) // short long print print, see in pdf +``` + +## Supported Features: + +### Dimensions: + +Numty uses standard typst list as a base type, most 1d operations like dot are suported directly for them. + +For matrix specific operations we use 2d arrays / nested arrays, that are also the standard typst list, but nested like in: ((1,2), (1,1)). + +For convenience you can create column or row vectors with the #nt.c and #nt.r functions. + +```typ +#import "numty.typ" as nt +#import "numty.typ": c, r + +#let a = (1,2,3) +#let b = (3,2,1) +#c(..a) // ((1,),(2,),(3,)) +#r(..b) // ((3,2,1),) +#nt.matmul(c(..a), r(..b)) // column @ row + +``` + +### Logic Operations: +```typ +#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, + +```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, to sample in acordance to the logarithmic space. + +```typ +#nt.linspace(0,10,3) // (0,5,10) +#nt.logspace(1,3,3) +#nt.geomspace(1,3,3) +``` + +### Matrix + +```typ +#nt.matmul(m,m) // matrix multiplication +#nt.det(((1,3), (3,4))) // nxn matrix determinant +#nt.trace(((1,3), (3,4))) // trace of square matrix +#nt.transpose(((1,3), (3,4))) // matrix transposition +``` + +### Printing + +Numty supports $ printing to the pdf of numerical matrices, both long and short format. + +```typ +#nt.print((1,2),(4,2))) // to display in the pdf +#nt.p((1,2),(4,2)), " random string ") // to display in the pdf +``` \ No newline at end of file diff --git a/packages/preview/numty/0.1.0/lib.typ b/packages/preview/numty/0.1.0/lib.typ new file mode 100644 index 0000000000..fbf2ba1845 --- /dev/null +++ b/packages/preview/numty/0.1.0/lib.typ @@ -0,0 +1,281 @@ +// == 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 +#let is-str(s) = (type(a) == str) + +#let is-1d-arr(arr) ={ + if is-arr(arr){if is-arr(arr.at(0)) {false} else {true}} else {false} +} + +#let is-1d(arr) ={ + if is-arr(arr){ // arrays anda mats + if is-arr(arr.at(0)) and arr.at(0).len() > 1 { + if arr.len() == 1 {true} else {false} // row mat else full mat + } + else {true} // col mat + } + else {false} // no array +} + +// == reshapers == + +#let r(..v) = { + (v.pos(),) +} + +#let c(..v) = { + v.pos().map(r => (r,),) +} + +#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 t(m) = transpose(m) + +// == 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 matmul(a,b) = { + let bt = transpose(b) + a.map(a_row => bt.map(b_col => dot(a_row,b_col))) +} + +#let det(m) = { + let n = m.len() + if n == 0 { + panic("cannot take determinant of empty matrix!") + } + + if m.len() == 2 and m.at(0).len() == 2 { + return m.at(0).at(0) * m.at(1).at(1) - m.at(1).at(0) * m.at(0).at(1) + } + + /// using https://en.wikipedia.org/wiki/Bareiss_algorithm + + let sign = 1 + + for k in range(n - 1) { + if m.at(k).at(k) == 0 { + let swapped = false + for i in range(k + 1, n) { + if m.at(i, k) != 0 { + let tmp = m.row(k) + m.set_row(k, m.row(i)) + m.set_row(i, tmp) + sign = -sign + swapped = true + break + } + } + if not swapped { + return 0 + } + } + + let pivot = m.at(k).at(k) + let prev = if k > 0 { m.at(k - 1).at(k - 1) } else { 1 } + + for i in range(k + 1, n) { + for j in range(k + 1, n) { + let num = m.at(i).at(j) * pivot - m.at(i).at(k) * m.at(k).at(j) + m.at(i).at(j) = num / prev + } + m.at(i).at(k) = 0 + } + } + + sign * m.at(n - 1).at(n - 1) +} + +#let trace(m) ={ + m.enumerate().map( ((i,_ )) => m.at(i).at(i)).sum() +} + +// 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 _p(m) = { + if is-mat(m) { + "mat(" + m.map(v => v.map(j=>to-str(j)).join(",")).join(";")+ ")" + } + else if is-arr(m){ + "vec(" + m.map(v => str(v)).join(",")+ ")" + } + else if is-arr(m){ + is-str(m) + } + else{ + str(m) + } +} + +#let print(..m) = { + let scope = (value1: "true", value2: "false") + eval("$ " + m.pos().map(r => _p(r)).join(" ") + " $", scope: scope) +} + +#let p(..m) = { + let scope = (value1: "true", value2: "false") + eval("$" + m.pos().map(r => _p(r)).join(" ") + "$", scope: scope) +} + diff --git a/packages/preview/numty/0.1.0/test.typ b/packages/preview/numty/0.1.0/test.typ new file mode 100644 index 0000000000..891e803543 --- /dev/null +++ b/packages/preview/numty/0.1.0/test.typ @@ -0,0 +1,318 @@ +#import "lib.typ" as nt +#import "lib.typ": r,c + + +#let M = ((1,3), (3,4)) +#let N = ((1,5), (1,4)) +#let n-DimM = (M,N) + +#let u = (1,2,3) +#let v = (3,2,1) +#let a = 1 +#let b = 2 + +#let testf(name, f, ..args, assertion: none) = { + // unfortunatelly f is not aware of his own name, + // and eval scope is out of nt, not sure how to include it + assert(f(..args) == assertion) + [#name ( #nt.p(..args, "= ", assertion) ] +} + += Automatic Tests + +== Test data: + +$ M = #M \ N =#N \ u = #u \ v = #v \ a = #a \ b = #b $ + + +== Print + + For now print default to col vectors, that may change, as it is still an experimental API, but be mindful that 1d is considered col by default use nt.c and nt.r to convert them. + + Small print + + #let u = (1,2,3) + #let v = (3,2,1) + + // matrix + #nt.p("N M = ",N, M , nt.matmul(N,M)) + + #nt.p((N,M,M).reduce(nt.matmul)) + + + #let S = ((1,2, 4), (3,4, 5) ) + #let K = ((1,2), (3,4), (4,2) ) + + #nt.p("S K = ", S, K , nt.matmul(S, K) ) + #nt.p("K S = ", K, S , nt.matmul(K, S) ) + + // matrix + #nt.p("u_c v_r = ", c(..v), r(..u), " = ", nt.matmul(c(..v), r(..u))) + + Big print: + + #nt.print("N M = ", N, M , nt.matmul(N,M)) + +=== Logic + === eq(u,v) + Checks element wise equality: + + // mat mat + eq(#nt.p(M,N, " = ", nt.eq(M,N)) + + // arr arr + eq#nt.p(u,v) #nt.eq(u,v) // + + #assert(nt.eq(u,v) == (false, true, false)) + #assert(nt.eq(u,u) == (true, true, true)) + + // arr float + #assert(nt.eq(u,a) == (true, false, false)) + #assert(nt.eq(a,u) == (true, false, false)) + + // flt flt + #assert(nt.eq(a,b) == false) + #assert(nt.eq(a,a) == true) + + // with nan + #assert(nt.eq((float.nan,1),(float.nan,1), equal-nan:true) == (true,true)) + #assert(nt.eq((float.nan,1),(float.nan,1)) == (false,true)) + + === all(u) + Check if array only contains true or 1 + + //mat + all#nt.p(((true, true),(true,true))) = #nt.all(((true, true),(true,true))) + + // arr + #assert(nt.all((false, true, false)) == false) + #assert(nt.all((true, true, true)) == true) + #assert(nt.all((1, 1, 1)) == true) + #assert(nt.all((0, 0, 0)) == false) + + // flt + #assert(nt.all(true) == true) + #assert(nt.all(false) == false) + #assert(nt.all(1) == true) + + === all-eq(u) + Checks all element wise equality: + //arr + #assert(nt.all-eq(u,v) == false) + #assert(nt.all-eq(u,u) == true) + + //flt + #assert(nt.all-eq(3,3) == true) + + === any(u) + Checks if any element is true or 1 + // arr + + nt.any(#(false, true, false)) -> #true + #assert(nt.any((false, true, false)) == true) + #assert(nt.any((false, false, false)) == false) + #assert(nt.any((0, 0, 1)) == true) + + === isna(u) + Check if the value is float.na + //arr + #assert(nt.isna((1,2)) == (false, false)) + #assert(nt.isna((1,float.nan)) == (false, true)) + + === apply(a) + Applies a function element-wise without changing the shape + + === abs(a) + Takes the abs of the mat, array, value + #assert(nt.abs(((1,-1),(1,-4))) == ((1,1),(1,4))) + +== Types + //arrarr(a,b) + === arrarr(u,v) + Check if a,b are arrays + + #assert(nt.arrarr(u,v) == true) + #assert(nt.arrarr(a,b) == false) + + === arrflt(u,a) + + check if u is array and a is float + #assert(nt.arrflt(u,b) == true) + #assert(nt.arrflt(b,u) == false) + #assert(nt.fltarr(b,u) == true) + #assert(nt.fltarr(b,b) == false) + #assert(nt.fltflt(b,b) == true) + + === is-1d + Checks if u is normal array or 1d mat + + #assert(nt.is-1d( (1,2) ) == true) + #assert(nt.is-1d( r(1,2) ) == true) + #assert(nt.is-1d( c(1,2) ) == true) + #assert(nt.is-1d( ((1,2), (2,3)) ) == false) + + === is-1d-arr + Check if is a typst 1d array, no nested + + #assert(nt.is-1d-arr( (1,2) ) == true) + #assert(nt.is-1d-arr( r(1,2) ) == false) + #assert(nt.is-1d-arr( c(1,2) ) == false) + #assert(nt.is-1d-arr( ((1,2), (2,3)) ) == false) + + +== Operators + === add(u,v) + Adds matrices vectors numbers: + + #let A = ((1,3),(1,3)) + #let B = ((1,3),(1,5)) + // mat mat + #nt.p(A,B) = #nt.p(nt.add(A, B)) + + #testf("add", nt.add, A,B, assertion: nt.add(A, B)) + + #testf("add", nt.add, u,v, assertion: (4,4,4)) + // mat flt + #assert(nt.add( ((1,3),(1,3)), 2 ) == ((3,5),(3,5))) + // arr arr + #assert(nt.add((1,3),(1,3)) == (2,6)) + + // arr float + #assert(nt.add((1,3),1) == (2,4)) + #assert(nt.add(1,(1,3)) == (2,4)) + + // float float + #assert(nt.add(1,2) == 3) + + === sub(u,v) + Substracts matrices + + // arr arr + #assert(nt.sub((1,3),(1,3)) == (0,0)) + // arr flt + #assert(nt.sub((1,3),2) == (-1,1)) + //#assert(nt.sub(2,(1,3)) == (1,-1)) + #nt.sub(2,(1,3)) + // flt flt + #assert(nt.sub(2,3) == -1) + + === mult(u,v) + Multiply two matrices + // arr arr + #assert(nt.mult((1,3),(1,3)) == (1,9)) + // arr flt + #assert(nt.mult((1,3),2) == (2,6)) + #assert(nt.mult(2,(1,3)) == (2,6)) + // flt flt + #assert(nt.mult(2,3) == 6) + + === div(u,v) + divide two matrices + // ndimmat num + #assert(nt.div((((4,2),(4,2)), ((4,2),(4,2))), 2) == (((2,1),(2,1)), ((2,1),(2,1)))) + + // num ndimmat + #assert(nt.div(2, (((1,2),(1,2)), ((1,2),(1,2)) )) == (((2,1),(2,1)), ((2,1),(2,1)) )) + + // arr arr + #assert(nt.div((1,3),(1,3)) == (1,1)) + #assert(nt.div((1,3),(1,0)).at(0) ==1) + #assert(nt.div((1,3),(1,0)).at(1).is-nan()) + // arr flt + #assert(nt.div((1,3),2) == (1/2,3/2)) + #assert(nt.div(2,(1,3)) == (2,2/3)) + + // flt flt + #assert(nt.div(2,3) == 2/3) + + === pow(u,v) + exponentiation of matrices + // arr arr + #assert(nt.pow((1,3),(1,3)) == (1,27)) + // arr flt + #assert(nt.pow((1,3),2) == (1,9)) + #assert(nt.pow(2,(1,3)) == (2,8)) + // flt flt + #assert(nt.pow(2,3) == 8) + +== Algebra + // arr + #assert(nt.log((1,10, 100)) == (0,1,2)) + //#assert(nt.log((0,10, 100)) == (float.nan,1,2)) + #nt.sin(n-DimM) + + // others: + #assert(nt.linspace(0,10,3) == (0,5,10)) + #assert(nt.geomspace(1,100,3) == (1,10,100)) + #assert(nt.logspace(1,3,3) == (10,100,1000)) + +== Matrix + // matrix + === transpose + + #nt.p(N) + + #assert(nt.transpose(N) == ((1,1),(5,4))) + + === matmul + + Tests: + + #nt.p(N) #nt.p(M) = #nt.p(nt.matmul(N,M)) + #assert(nt.matmul(N,M) == ((16,23),(13,19))) + + #nt.p( (1,3), )) #nt.p( ((16,23),(13,19)) ) + #nt.p( nt.matmul( ((1,3)), ((16,23),(13,19)) )) + + #nt.matmul(((16,23),(13,19)), ((1,), (2,))) + //#nt.transpose(((1,3))) + #( (1,), (2, )) + + #((1,2,),) + + #nt.r(1,2) + #nt.c(1,2) + + transpose: + #nt.r(1,2) + + #nt.p(r(1,2)) + //#nt.p(r(1,2)) + + #nt.p( ((1,2),(3,4)) ) #nt.p(c(1,2) ) + #nt.p(nt.matmul( ((1,2),(3,4)), c(1,2) )) + + #nt.p(r(1,2)) + #nt.p(nt.matmul(c(1,2), ((1,2),(3,4)) )) + + #nt.transpose(c(1,2)) + + == det + + #let M3 = ((1,2,3),(0,1,4),(5,6,0)) + #let M4 = ((1,0,0,0),(0,2,0,0),(0,0,3,0),(0,0,0,4)) + #let M5 = ((1,1,1,1,1),(0,1,1,1,1),(0,0,1,1,1),(0,0,0,1,1),(0,0,0,0,1)) + + === 2x2 + + #nt.p("det", M) = #nt.det(M) + #assert(nt.det(M) == -5) + + === 3x3 + #nt.p("det", M3) = #nt.det(M3) + #assert(nt.det(M3) == 1) + + === 4x4 + #nt.p("det", M4) = #nt.det(M4) + #assert(nt.det(M4) == 24) + + === 5x5 + #nt.p("det", M5) = #nt.det(M5) + #assert(nt.det(M5) == 1) + + == trace + + #nt.trace(M) + + +#pagebreak() \ No newline at end of file diff --git a/packages/preview/numty/0.1.0/typst.toml b/packages/preview/numty/0.1.0/typst.toml new file mode 100644 index 0000000000..133bbe6308 --- /dev/null +++ b/packages/preview/numty/0.1.0/typst.toml @@ -0,0 +1,11 @@ +[package] +name = "numty" +version = "0.1.0" +entrypoint = "lib.typ" +authors = ["Pablo Ruiz Cuevas"] +license = "MIT" +description = "Numeric Typst" +exclude = ["test.typ"] +repository = "https://github.com/PabloRuizCuevas/numty" +categories = ["utility","scripting"] +keywords = ["matrix", "array", "matrices", "math", "numpy", "vector"]