Skip to content

Commit

Permalink
eqalc:0.1.1 (#1700)
Browse files Browse the repository at this point in the history
  • Loading branch information
7ijme authored Feb 11, 2025
1 parent a1cf59a commit cb80330
Show file tree
Hide file tree
Showing 7 changed files with 358 additions and 0 deletions.
21 changes: 21 additions & 0 deletions packages/preview/eqalc/0.1.1/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# v0.1.1
features:

- added ability to use labels

bug fixes:

- the variable will now be in math mode in v13
- expressions (without a left side) would cause an error

# v0.1.0
features:

- e, pi and tau work now
- sin, cos, etc. works now
- fixed a bug where top part of exponent couldn't be a sequence
- cleaned up some code
- dynamic table naming
- multiple variable support
- made the docs readable
- added math-to-data
21 changes: 21 additions & 0 deletions packages/preview/eqalc/0.1.1/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Tijme

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.
79 changes: 79 additions & 0 deletions packages/preview/eqalc/0.1.1/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Eqalc

Convert your [Typst](https://typst.app/home) math equations to functions in order to graph or plot them.
So you only have to write your equation out ONCE!

[![MIT License](https://img.shields.io/badge/license-MIT-blue)](https://github.com/7ijme/eqalc/blob/main/LICENSE)

## Installing

Install eqalc by cloning it and then importing like this:

```typ
#import "@preview/eqalc:0.1.1": math-to-func, math-to-code, math-to-table
#let f = $g(t)=2t dot sqrt(e^t)+ln(t)+2pi$
#f\
#math-to-code(f)
#math-to-table(f, min: 1, max: 5, step: 1)
// `math-to-func` will return a function that can be used to map over values
// You can also use labels:
$ g(t) = 2t dot sqrt(e^t) + ln(t) + 2pi $ <eq>
#context math-to-code(<eq>)
#context math-to-table(<eq>, min: 1, max: 5, step: 1)
```

![image](https://github.com/user-attachments/assets/0cde46d3-e9d6-42f6-a536-f681f6b9091c)

Available functions at the moment:

- `math-to-func`
- `math-to-code`
- `math-to-table`
- `math-to-data`

More on these functions in the [manual](https://github.com/7ijme/eqalc/blob/main/docs/manual.pdf).

## How it works

Eqalc parses your equations by recursively going through the math expressions.

```typ
// Let's take #f from the example above
#repr(f)
// This will return a tree representation of the equation
equation(
block: false,
body: sequence(
sequence([g], lr(body: sequence([(], [t], [)]))),
[=],
[2],
[t],
[ ],
[⋅],
[ ],
root(radicand: attach(base: [e], t: [t])),
[+],
sequence(
op(text: [ln], limits: false),
lr(body: sequence([(], [t], [)])),
),
[+],
[2],
[π],
),
)
#math-to-str(f)
// This will return the equation as a string
// `2*t*calc.root(calc.pow(calc.e, t), 2)+calc.ln(t)+2*calc.pi`
```

If the given math expression is an equation, the left hand side will be turned into the name of the function, and the right hand side will be the body of the function.

Only one variable is allowed in the right hand side of the equation.

## Contributing
Any contributions are welcome! Just fork the repository and make a pull request.
Binary file added packages/preview/eqalc/0.1.1/docs/manual.pdf
Binary file not shown.
110 changes: 110 additions & 0 deletions packages/preview/eqalc/0.1.1/lib.typ
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
#import "util.typ": math-to-str, get-variable, label-to-math

/// Creates a function from a math expression.
///
///
/// Example:
/// `#math-to-func($x^2$)` will output `#(x => calc.pow(x,2))`.
/// -> function
#let math-to-func(
/// The math expression.
/// -> content | label
math,
) = {
let string = math-to-str(math)
let var = get-variable(string)
x => eval("let " + var + "= " + str(x) + "; " + string)
}

/// Math to any data you might need.
///
/// Example:
/// `#math-to-data($f(x)=x^2$)` will output:
/// ```typ
/// #(
/// func: (x => calc.pow(x,2)),
/// str: "calc.pow(x,2)",
/// x: "x",
/// x-math: $x$,
/// fx: "f(x)",
/// fx-math: $f(x)$,
///)```
/// -> (func: function, str: string, x: string, x-math: content, fx: string, fx-math: content)
#let math-to-data(
/// The math expression.
/// -> content | label
math,
) = {
let f = math-to-func(math)
let str = math-to-str(math)
let var = get-variable(str)
let fx = math-to-str(math, get-first-part: true)
(
func: f,
str: str,
x: var,
x-math: eval(var, mode: "math"),
fx: fx,
fx-math: eval(fx, mode: "math"),
)
}

/// Creates a table of function values.
///
/// Example:
/// `#math-to-table($x^2$, min: 1, max: 5, step: 1)` will output:
/// ```table
/// x | 1 | 2 | 3 | 4 | 5 |
/// --------------------------
/// f(x) | 1 | 4 | 9 | 16| 25|
/// ```
/// But in an actual table.
/// -> content
#let math-to-table(
/// The function to evaluate.
/// -> content | label
math,
/// The minimum value of the domain.
/// -> integer
min: 0,
/// The maximum value of the domain.
/// -> integer
max: 5,
/// The step size.
/// -> integer
step: 1,
/// The integer of decimal places to round to.
/// -> integer
round: 2,
/// The name of the function. Defaults to the first part of the math expression.
/// -> content
name: none,
) = {
assert(min < max, message: "min must be less than max")
assert(step > 0, message: "step must be greater than 0")
let (x-math, fx-math, func) = math-to-data(math)
let name = if name != none { name } else { fx-math }
table(
columns: calc.ceil((max - min) / step) + 2,
x-math, ..range(min, max + step, step: step).map(x => [$#x$]),
name, ..range(
min,
max + step,
step: step,
).map(x => [#calc.round(func(x), digits: round)]),
)
}

/// Converts a math expression to code.
///
/// Example:
/// `#math-to-code($x^2$)` will output `calc.pow(x,2)`.
/// -> content
#let math-to-code(
/// The math expression.
/// -> content | label
math,
) = {
let f = math-to-str(math)
raw(lang: "typst", f)
}
9 changes: 9 additions & 0 deletions packages/preview/eqalc/0.1.1/typst.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
[package]
name = "eqalc"
version = "0.1.1"
entrypoint = "lib.typ"
authors = ["Tijme"]
license = "MIT"
description = "Convert math equations to functions."
repository = "https://github.com/7ijme/eqalc"
categories = ["utility", "visualization"]
118 changes: 118 additions & 0 deletions packages/preview/eqalc/0.1.1/util.typ
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/// Converts a label to a math expression.
/// -> content
#let label-to-math(
/// A label representing a math expression.
/// -> label
label,
) = {
query(label).first()
}

/// Converts math equations to strings.
/// -> string
#let math-to-str(
/// The math expression.
/// -> content | label
eq,
/// Get the part before the equals sign. This is used to get the function name.
/// -> boolean
get-first-part: false,
/// The depth of the recursion. This is used for debugging.
/// -> integer
depth: 0,
) = {
let map-math(n) = {
// Operators like sin, cos, etc.
if n.func() == math.op {
"calc." + n.fields().text.text
// Parentheses
} else if n.func() == math.lr {
math-to-str(n.body, depth: depth + 1)
// Powers
} else if n.has("base") and n.has("t") {
"calc.pow(" + math-to-str(n.base) + ", " + math-to-str(n.t) + ")"
// Roots
} else if n.func() == math.root {
(
"calc.root("
+ math-to-str(n.radicand, depth: depth + 1)
+ ", "
+ n.at("index", default: "2")
+ ")"
)
// Fractions
} else if n.func() == math.frac {
(
"("
+ math-to-str(n.num, depth: depth + 1)
+ ")/("
+ math-to-str(n.denom, depth: depth + 1)
+ ")"
)
// Default case
} else if n == [ ] { } else if n.has("text") {
if n.text == "e" {
"calc.e"
} else if n.text == $pi$.body.text {
"calc.pi"
} else if n.text == $tau$.body.text {
"calc.tau"
} else {
n.text
}
// This is still a sequence.
} else {
math-to-str(n, depth: depth + 1)
}
}

if type(eq) == "label" {
eq = label-to-math(eq)
}

if not type(eq) == "string" and eq.has("body") {
eq = eq.body
}
// Adding `[]` to make it a sequence if it isn't already.
let string = (eq + [])
.fields()
.children
.map(map-math)
.join()
.replace(
regex("(\d)\s*([a-zA-Z]\b|calc|\()"),
((captures,)) => captures.first() + "*" + captures.last(),
)
.replace(math.dot, "*")

if depth == 0 {
let reg = if get-first-part {
if string.contains("=") {
regex("=.+")
} else {
regex(".+")
}
} else {
regex(".+=")
}
string.replace(reg, "")
} else {
string
}
}

/// Gets the main variable from a math expression.
/// -> string
#let get-variable(
/// The math expression.
/// -> string
math-str,
) = {
let reg = regex("\b([A-Za-z--e])\b")
let match = math-str.match(reg)
if match != none {
match.text
} else {
"x"
}
}

0 comments on commit cb80330

Please sign in to comment.