typst-sympy-calculator


Nametypst-sympy-calculator JSON
Version 0.6.2 PyPI version JSON
download
home_pagehttps://github.com/OrangeX4/typst-sympy-calculator
SummaryConvert typst math expressions to sympy form with ANTLR and support matrix, calculous and custom functions.
upload_time2024-01-28 08:22:13
maintainer
docs_urlNone
authorOrangeX4
requires_python
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ![Logo](https://picgo-1258602555.cos.ap-nanjing.myqcloud.com/icon.png)



# [Typst Sympy Calculator](https://github.com/OrangeX4/typst-sympy-calculator)



## About



`Typst Sympy Calculator` parses **Typst Math Expressions** and converts it into the equivalent **SymPy form**. Then, **calculate it** and convert to typst math text. 



It is designed for providing **people writing in typst** a ability to calculate something when writing math expression. It is based on `Sympy` module in `Python`.



The `typst-sympy-calculator` python package is a backend for a VS Code extension [`Typst Sympy Calculator`](https://github.com/OrangeX4/vscode-typst-sympy-calculator), and you also can use it just for parse typst math expression to sympy form in order to do things for yourself.





## Features



![Demo](https://picgo-1258602555.cos.ap-nanjing.myqcloud.com/typst-sympy-calculator.gif)



- **Default Math:**

    - [x] **Arithmetic:** Add (`+`), Sub (`-`), Dot Mul (`dot`), Cross Mul (`times`), Frac (`/`), Power (`^`), Abs (`|x|`), Sqrt (`sqrt`), etc...

    - [x] **Alphabet:** `a - z`, `A - Z`, `alpha - omega`, Subscript (`x_1`), Accent Bar(`hat(x)`), etc...

    - [x] **Common Functions:** `gcd`, `lcm`, `floor`, `ceil`, `max`, `min`, `log`, `ln`, `exp`, `sin`, `cos`, `tan`, `csc`, `sec`, `cot`, `arcsin`, `sinh`, `arsinh`, etc...

    - [x] **Funcion Symbol:** `f(x)`, `f(x-1,)`, `g(x,y)`, etc...

    - [x] **Calculous:** Limit `lim_(x -> oo) 1/x`, Integration `integral_1^2 x dif x`, etc...

    - [x] **Calculous:** Derivation (`dif/(dif x) (x^2 + 1)` is not supported, but you can use `derivative(expr, var)` instead), etc...

    - [x] **Reduce:** Sum `sum_(k=1)^oo (1/2)^k`, Product `product_(k=1)^oo (1/2)^k`, etc...

    - [x] **Eval At:** Evalat `x^2 bar_(x = 2)`, `x^2 "|"_(x = 2)`, etc...

    - [x] **Linear Algebra:** Matrix to raw echelon form `rref`, Determinant `det`, Transpose `^T`, Inverse `^(-1)`, etc...

    - [x] **Relations:** `==`, `>`, `>=`, `<`, `<=`, etc...

    - [x] **Solve Equation:** Single Equation `x + 1 = 2`, Multiple Equations `cases(x + y = 1, x - y = 2)`, etc...

    - [ ] **Logical:** `and`, `or`, `not`, etc...

    - [ ] **Set Theory:** `in`, `sect`, `union`, `subset`, etc...

    - [x] **Other:** Binomial `binom(n, k)` ...

- **Custom Math (in typst file):**

    - [x] **Define Accents:** `#let acc(x) = math.accent(x, math.grave)`

    - [x] **Define Operators:** `#let add = math.op("add")`

    - [x] **Define Symbols:** `#let xy = math.italic("xy")` or `#let mail = symbol("🖂", ("stamped", "🖃"),)`

    - [x] **Define Functions:**

        ```py

        # typst-calculator

        @func()

        def convert_add(a, b):

            return a + b

        ```

- **Typst Math Printer:**

    - [x] Complete `TypstMathPrinter` in `TypstConverter.py`

    - [ ] Custom Printer for `TypstCalculator.py` and `TypstCalculatorServer.py`

- **VS Code Extension:**

    - [x] Develop a VS Code Extension for `Typst Calculator`





## Install



```bash

pip install typst-sympy-calculator

```





## Usage



### Difference Between `parse`, `converter`, `calculator`, `server`



- `TypstParser.py`: parse typst math expression to ANTLR abstract syntax tree with `TypstGrammar.g4`;

- `TypstConverter.py`:

    - convert typst math expression to sympy expression via `TypstMathConverter`;

    - convert sympy expression to typst math expression via `TypstMathPrinter`;

    - has `decorators` for defining custom functions, operators;

    - has `define_accent`, `define_symbol_base` and `define_function` for defining custom accents, symbols and functions;

- `TypstCalculator.py`:

    - calculate sympy expression and convert to typst math expression;

    - has `subs`, `simplify`, `evalf` methods;

    - has `set_variance` and `unset_variance` for calculating with variance;

- `DefaultTypstCalculator`: define many useful functions, operators, accents, symbols;

    - Accents, Alphabet, Greeks, Arithmetic, Common Functions, Calculous, Linear Algebra, etc...

- `TypstCalculatorServer`:

    - has `init` method for initializing `TypstCalculator` with a typst file;

    - **can define your custom functions on your typst file**;

    - has `simplify`, `subs`, `evalf` methods for calculating with typst file;



It is a top-down design, so you can use `TypstCalculatorServer` directly, or use `TypstCalculator` with `TypstConverter`.



**RECOMMEND: see the usage of decorators like `@func()` in [DefaultTypstCalculator.py](https://github.com/OrangeX4/typst-sympy-calculator/blob/main/DefaultTypstCalculator.py).**



For the usage, you can see the unit test part `if __name__ == '__main__':` in each files.





### Sympy Expressions and Typst Math Text



```python

from TypstCalculatorServer import TypstCalculatorServer



server = TypstCalculatorServer()

typst_math = r'1 + 1'

expr = server.sympy(typst_math)

print(server.typst(expr))

```



```python

from TypstCalculator import TypstCalculator



calculator = TypstCalculator()

typst_math = r'1 + 1'

expr = calculator.sympy(typst_math)

print(calculator.typst(expr))

```



```python

from TypstConverter import TypstMathConverter



converter = TypstMathConverter()

typst_math = r'1 + 1'

expr = converter.sympy(typst_math)

print(converter.typst(expr))

```





### Typst Calculator Server



The simplest way to use it is just like `TypstCalculatorServer.py`:



```python

from TypstCalculatorServer import TypstCalculatorServer



server = TypstCalculatorServer()

typst_file = os.path.abspath(r'./tests/test.typ')

server.init(typst_file)

server.return_text = True  # otherwise just return sympy form

expr = server.simplify('1 + 1', typst_file)

print(expr)  # 2

server.enable_subs = False

expr = server.simplify('a + 1', typst_file)

print(expr)  # a + 1

server.enable_subs = True

expr = server.simplify('a + 1', typst_file)

print(expr)  # 2

expr = server.simplify('b + 1', typst_file)

print(expr)  # a + 2

expr = server.simplify('cmat(1, 2)', typst_file)

print(expr)  # mat(1; 2)

expr = server.simplify('f(1) + f(1)', typst_file)

print(expr)  # 2 f(1)

expr = server.simplify('xy + mail + mail.stamped', typst_file)

print(expr)  # mail + mail.stamped + xy

expr = server.solve('x + y + z = 1')

print(expr)  # y = -x - z + 1, z = -x - y + 1, x = -y - z + 1

expr = server.solve('cases(x + y + z = 1, x = 2)')

print(expr)  # cases(x = 2, z = -y - 1), cases(y = -z - 1, x = 2), y = -x - z + 1, z = -x - y + 1

expr = server.solve('cases(x^2 + y = 4, y = 2)')

print(expr)  # x = sqrt(4 - y), cases(y = 2, x = sqrt(2)), cases(y = 2, x = -sqrt(2)), x = -sqrt(4 - y)

expr = server.solve('cases(x < 2, x > 1)')

print(expr)  # 1 < x and x < 2

```



and the typst files `tests/test.typ`



```typst

#import "cal.typ": *



// set variances

#let a = 1

#let b = $a + 1$

```



and `tests/cal.typ` just like:



```typst

// define accents

#let acc(x) = math.accent(x, math.grave)



// define operators

#let add = math.op("add")

#let f = math.op("f")



// define symbols

#let xy = math.italic("xy")

#let mail = symbol("🖂", ("stamped", "🖃"),)

```





### Default Typst Calculator



If you have not a typst file, you can use `DefaultTypstCalculator.py`, it define many useful functions and symbols just like:



```python

# Symbols

abc = 'abcdefghijklmnopqrstuvwxyz'

for c in abc:

    calculator.define_symbol_base(c)

    calculator.define_symbol_base(c.upper())



# Functions

@func()

def convert_sin(expr):

    return sympy.sin(expr)

```



So you can use it by:



```python

from DefaultTypstCalculator import get_default_calculator



calculator = get_default_calculator(complex_number=True)

calculator.return_text = True

operator, relation_op, additive_op, mp_op, postfix_op, \

    reduce_op, func, func_mat, constant = calculator.get_decorators()

expr = calculator.simplify('1 + 1')

assert expr == '2'

expr = calculator.evalf('1/2', n=3)

assert expr == '0.500'

calculator.set_variance('a', '1/2')

expr = calculator.simplify('a + 1')

assert expr == '3/2'

calculator.unset_variance('a')

expr = calculator.simplify('a + 1')

assert expr == 'a + 1' or expr == '1 + a'

expr = calculator.evalf('pi', n=3)

assert expr == '3.14'

expr = calculator.simplify('max(1, 2)')

assert expr == '2'

calculator.define_function('f')

expr = calculator.simplify('f(1) + f(1) - f(1)')

assert expr == 'f(1)'

expr = calculator.simplify('lim_(x -> oo) 1/x')

assert expr == '0'

```



### Variances



You can **ASSIGN** variance a value using same assignment form in typst:



```typst

#let x = 1



// Before

$ x $



// Shift + Ctrl + E

// After

$ x = 1 $

```



PS: You can use grammar like `y == x + 1` to describe the relation of equality.



If you want to see the bonding of variances, you can press `Shift + Ctrl + P`, and input `typst-sympy-calculator: Show Current variances`, then you will get data like:



```typst

y = x + 1

z = 2 x

```



### Functions



You can **DEFINE** a function using same form in typst:



```typst

#let f = math.op("f")



// Before

$ f(1) + f(1) $



// Shift + Ctrl + E

// After

$ f(1) + f(1) = 2 f(1) $

```



### Symbols



You can **DEFINE** a symbol using same form in typst:



```typst

#let xy = math.italic("xy")

#let email = symbol("🖂", ("stamped", "🖃"),)



$ xy + email + email.stamped $

```



### Accents



You can **DEFINE** a accent using same form in typst:



```typst

#let acc(x) = math.accent(x, math.grave)



$ acc(x) $

```



### Decorators for Operators



You can **DEFINE** a operator using same form in typst:



```typst

#let add = math.op("+")



'''typst-calculator

@additive_op()

def convert_add(a, b):

    return a + b

'''



// Before

$ 1 add 1 $



// Shift + Ctrl + E

// After

$ 1 add 1 = 2 $

```



Or just use `'''typst-sympy-calculator` or `'''python \n # typst-calculator` to define a operator.



there are some decorators you can use:



- `@operator(type='ADDITIVE_OP', convert_ast=convert_ast, name=name, ast=False)`: Define a common operator;

- `@func()`: Define a function, receive args list; 

- `@func_mat()`: Define a matrix function, receive single arg `matrix`;

- `@constant()`: Define a constant, receive no args but only return a constant value;

- `@relation_op()`: Define a relation operator, receive args `a` and `b`;

- `@additive_op()`: Define a additive operator, receive args `a` and `b`;

- `@mp_op()`: Define a multiplicative operator, receive args `a` and `b`;

- `@postfix_op()`: Define a postfix operator, receive args `a`;

- `@reduce_op()`: Define a reduce operator, receive args `expr` and `args = (symbol, sub, sup)`;



It is important that the function name MUST be `def convert_{operator_name}`, or you can use decorator arg `@func(name='operator_name')`, and the substring `_dot_` will be replaced by `.`.



There are some examples (from [DefaultTypstCalculator.py](https://github.com/OrangeX4/typst-sympy-calculator/blob/main/DefaultTypstCalculator.py)):



```python

# Functions

@func()

def convert_binom(n, k):

    return sympy.binomial(n, k)



# Matrix

@func_mat()

def convert_mat(mat):

    return sympy.Matrix(mat)



# Constants

@constant()

def convert_oo():

    return sympy.oo



# Relation Operators

@relation_op()

def convert_eq(a, b):

    return sympy.Eq(a, b)



# Additive Operators

@additive_op()

def convert_plus(a, b):

    return a + b



# Mp Operators

@mp_op()

def convert_times(a, b):

    return a * b



# Postfix Operators

@postfix_op()

def convert_degree(expr):

    return expr / 180 * sympy.pi



# Reduces

@reduce_op()

def convert_sum(expr, args):

    # symbol, sub, sup = args

    return sympy.Sum(expr, args)

```





## Contributing



1. Clone it by `git clone https://github.com/OrangeX4/typst-calculator.git`

2. Install dependencies by `pip install -r requirements.txt`

3. Compile ANTLR grammar by `python ./scripts/compile.py`

4. Debug or add your code with `TypstCalculatorServer.py` or `TypstCalculator.py`, etc...



It is welcome to create an issue or pull request.





## Thanks



- [augustt198 / latex2sympy](https://github.com/augustt198/latex2sympy)

- [purdue-tlt / latex2sympy](https://github.com/purdue-tlt/latex2sympy)

- [ANTLR](https://www.antlr.org/)

- [Sympy](https://www.sympy.org/en/index.html)





## License



This project is licensed under the MIT License.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/OrangeX4/typst-sympy-calculator",
    "name": "typst-sympy-calculator",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "OrangeX4",
    "author_email": "orangex4@qq.com",
    "download_url": "",
    "platform": null,
    "description": "![Logo](https://picgo-1258602555.cos.ap-nanjing.myqcloud.com/icon.png)\n\n\n\n# [Typst Sympy Calculator](https://github.com/OrangeX4/typst-sympy-calculator)\n\n\n\n## About\n\n\n\n`Typst Sympy Calculator` parses **Typst Math Expressions** and converts it into the equivalent **SymPy form**. Then, **calculate it** and convert to typst math text. \n\n\n\nIt is designed for providing **people writing in typst** a ability to calculate something when writing math expression. It is based on `Sympy` module in `Python`.\n\n\n\nThe `typst-sympy-calculator` python package is a backend for a VS Code extension [`Typst Sympy Calculator`](https://github.com/OrangeX4/vscode-typst-sympy-calculator), and you also can use it just for parse typst math expression to sympy form in order to do things for yourself.\n\n\n\n\n\n## Features\n\n\n\n![Demo](https://picgo-1258602555.cos.ap-nanjing.myqcloud.com/typst-sympy-calculator.gif)\n\n\n\n- **Default Math:**\n\n    - [x] **Arithmetic:** Add (`+`), Sub (`-`), Dot Mul (`dot`), Cross Mul (`times`), Frac (`/`), Power (`^`), Abs (`|x|`), Sqrt (`sqrt`), etc...\n\n    - [x] **Alphabet:** `a - z`, `A - Z`, `alpha - omega`, Subscript (`x_1`), Accent Bar(`hat(x)`), etc...\n\n    - [x] **Common Functions:** `gcd`, `lcm`, `floor`, `ceil`, `max`, `min`, `log`, `ln`, `exp`, `sin`, `cos`, `tan`, `csc`, `sec`, `cot`, `arcsin`, `sinh`, `arsinh`, etc...\n\n    - [x] **Funcion Symbol:** `f(x)`, `f(x-1,)`, `g(x,y)`, etc...\n\n    - [x] **Calculous:** Limit `lim_(x -> oo) 1/x`, Integration `integral_1^2 x dif x`, etc...\n\n    - [x] **Calculous:** Derivation (`dif/(dif x) (x^2 + 1)` is not supported, but you can use `derivative(expr, var)` instead), etc...\n\n    - [x] **Reduce:** Sum `sum_(k=1)^oo (1/2)^k`, Product `product_(k=1)^oo (1/2)^k`, etc...\n\n    - [x] **Eval At:** Evalat `x^2 bar_(x = 2)`, `x^2 \"|\"_(x = 2)`, etc...\n\n    - [x] **Linear Algebra:** Matrix to raw echelon form `rref`, Determinant `det`, Transpose `^T`, Inverse `^(-1)`, etc...\n\n    - [x] **Relations:** `==`, `>`, `>=`, `<`, `<=`, etc...\n\n    - [x] **Solve Equation:** Single Equation `x + 1 = 2`, Multiple Equations `cases(x + y = 1, x - y = 2)`, etc...\n\n    - [ ] **Logical:** `and`, `or`, `not`, etc...\n\n    - [ ] **Set Theory:** `in`, `sect`, `union`, `subset`, etc...\n\n    - [x] **Other:** Binomial `binom(n, k)` ...\n\n- **Custom Math (in typst file):**\n\n    - [x] **Define Accents:** `#let acc(x) = math.accent(x, math.grave)`\n\n    - [x] **Define Operators:** `#let add = math.op(\"add\")`\n\n    - [x] **Define Symbols:** `#let xy = math.italic(\"xy\")` or `#let mail = symbol(\"\ud83d\udd82\", (\"stamped\", \"\ud83d\udd83\"),)`\n\n    - [x] **Define Functions:**\n\n        ```py\n\n        # typst-calculator\n\n        @func()\n\n        def convert_add(a, b):\n\n            return a + b\n\n        ```\n\n- **Typst Math Printer:**\n\n    - [x] Complete `TypstMathPrinter` in `TypstConverter.py`\n\n    - [ ] Custom Printer for `TypstCalculator.py` and `TypstCalculatorServer.py`\n\n- **VS Code Extension:**\n\n    - [x] Develop a VS Code Extension for `Typst Calculator`\n\n\n\n\n\n## Install\n\n\n\n```bash\n\npip install typst-sympy-calculator\n\n```\n\n\n\n\n\n## Usage\n\n\n\n### Difference Between `parse`, `converter`, `calculator`, `server`\n\n\n\n- `TypstParser.py`: parse typst math expression to ANTLR abstract syntax tree with `TypstGrammar.g4`;\n\n- `TypstConverter.py`:\n\n    - convert typst math expression to sympy expression via `TypstMathConverter`;\n\n    - convert sympy expression to typst math expression via `TypstMathPrinter`;\n\n    - has `decorators` for defining custom functions, operators;\n\n    - has `define_accent`, `define_symbol_base` and `define_function` for defining custom accents, symbols and functions;\n\n- `TypstCalculator.py`:\n\n    - calculate sympy expression and convert to typst math expression;\n\n    - has `subs`, `simplify`, `evalf` methods;\n\n    - has `set_variance` and `unset_variance` for calculating with variance;\n\n- `DefaultTypstCalculator`: define many useful functions, operators, accents, symbols;\n\n    - Accents, Alphabet, Greeks, Arithmetic, Common Functions, Calculous, Linear Algebra, etc...\n\n- `TypstCalculatorServer`:\n\n    - has `init` method for initializing `TypstCalculator` with a typst file;\n\n    - **can define your custom functions on your typst file**;\n\n    - has `simplify`, `subs`, `evalf` methods for calculating with typst file;\n\n\n\nIt is a top-down design, so you can use `TypstCalculatorServer` directly, or use `TypstCalculator` with `TypstConverter`.\n\n\n\n**RECOMMEND: see the usage of decorators like `@func()` in [DefaultTypstCalculator.py](https://github.com/OrangeX4/typst-sympy-calculator/blob/main/DefaultTypstCalculator.py).**\n\n\n\nFor the usage, you can see the unit test part `if __name__ == '__main__':` in each files.\n\n\n\n\n\n### Sympy Expressions and Typst Math Text\n\n\n\n```python\n\nfrom TypstCalculatorServer import TypstCalculatorServer\n\n\n\nserver = TypstCalculatorServer()\n\ntypst_math = r'1 + 1'\n\nexpr = server.sympy(typst_math)\n\nprint(server.typst(expr))\n\n```\n\n\n\n```python\n\nfrom TypstCalculator import TypstCalculator\n\n\n\ncalculator = TypstCalculator()\n\ntypst_math = r'1 + 1'\n\nexpr = calculator.sympy(typst_math)\n\nprint(calculator.typst(expr))\n\n```\n\n\n\n```python\n\nfrom TypstConverter import TypstMathConverter\n\n\n\nconverter = TypstMathConverter()\n\ntypst_math = r'1 + 1'\n\nexpr = converter.sympy(typst_math)\n\nprint(converter.typst(expr))\n\n```\n\n\n\n\n\n### Typst Calculator Server\n\n\n\nThe simplest way to use it is just like `TypstCalculatorServer.py`:\n\n\n\n```python\n\nfrom TypstCalculatorServer import TypstCalculatorServer\n\n\n\nserver = TypstCalculatorServer()\n\ntypst_file = os.path.abspath(r'./tests/test.typ')\n\nserver.init(typst_file)\n\nserver.return_text = True  # otherwise just return sympy form\n\nexpr = server.simplify('1 + 1', typst_file)\n\nprint(expr)  # 2\n\nserver.enable_subs = False\n\nexpr = server.simplify('a + 1', typst_file)\n\nprint(expr)  # a + 1\n\nserver.enable_subs = True\n\nexpr = server.simplify('a + 1', typst_file)\n\nprint(expr)  # 2\n\nexpr = server.simplify('b + 1', typst_file)\n\nprint(expr)  # a + 2\n\nexpr = server.simplify('cmat(1, 2)', typst_file)\n\nprint(expr)  # mat(1; 2)\n\nexpr = server.simplify('f(1) + f(1)', typst_file)\n\nprint(expr)  # 2 f(1)\n\nexpr = server.simplify('xy + mail + mail.stamped', typst_file)\n\nprint(expr)  # mail + mail.stamped + xy\n\nexpr = server.solve('x + y + z = 1')\n\nprint(expr)  # y = -x - z + 1, z = -x - y + 1, x = -y - z + 1\n\nexpr = server.solve('cases(x + y + z = 1, x = 2)')\n\nprint(expr)  # cases(x = 2, z = -y - 1), cases(y = -z - 1, x = 2), y = -x - z + 1, z = -x - y + 1\n\nexpr = server.solve('cases(x^2 + y = 4, y = 2)')\n\nprint(expr)  # x = sqrt(4 - y), cases(y = 2, x = sqrt(2)), cases(y = 2, x = -sqrt(2)), x = -sqrt(4 - y)\n\nexpr = server.solve('cases(x < 2, x > 1)')\n\nprint(expr)  # 1 < x and x < 2\n\n```\n\n\n\nand the typst files `tests/test.typ`\n\n\n\n```typst\n\n#import \"cal.typ\": *\n\n\n\n// set variances\n\n#let a = 1\n\n#let b = $a + 1$\n\n```\n\n\n\nand `tests/cal.typ` just like:\n\n\n\n```typst\n\n// define accents\n\n#let acc(x) = math.accent(x, math.grave)\n\n\n\n// define operators\n\n#let add = math.op(\"add\")\n\n#let f = math.op(\"f\")\n\n\n\n// define symbols\n\n#let xy = math.italic(\"xy\")\n\n#let mail = symbol(\"\ud83d\udd82\", (\"stamped\", \"\ud83d\udd83\"),)\n\n```\n\n\n\n\n\n### Default Typst Calculator\n\n\n\nIf you have not a typst file, you can use `DefaultTypstCalculator.py`, it define many useful functions and symbols just like:\n\n\n\n```python\n\n# Symbols\n\nabc = 'abcdefghijklmnopqrstuvwxyz'\n\nfor c in abc:\n\n    calculator.define_symbol_base(c)\n\n    calculator.define_symbol_base(c.upper())\n\n\n\n# Functions\n\n@func()\n\ndef convert_sin(expr):\n\n    return sympy.sin(expr)\n\n```\n\n\n\nSo you can use it by:\n\n\n\n```python\n\nfrom DefaultTypstCalculator import get_default_calculator\n\n\n\ncalculator = get_default_calculator(complex_number=True)\n\ncalculator.return_text = True\n\noperator, relation_op, additive_op, mp_op, postfix_op, \\\n\n    reduce_op, func, func_mat, constant = calculator.get_decorators()\n\nexpr = calculator.simplify('1 + 1')\n\nassert expr == '2'\n\nexpr = calculator.evalf('1/2', n=3)\n\nassert expr == '0.500'\n\ncalculator.set_variance('a', '1/2')\n\nexpr = calculator.simplify('a + 1')\n\nassert expr == '3/2'\n\ncalculator.unset_variance('a')\n\nexpr = calculator.simplify('a + 1')\n\nassert expr == 'a + 1' or expr == '1 + a'\n\nexpr = calculator.evalf('pi', n=3)\n\nassert expr == '3.14'\n\nexpr = calculator.simplify('max(1, 2)')\n\nassert expr == '2'\n\ncalculator.define_function('f')\n\nexpr = calculator.simplify('f(1) + f(1) - f(1)')\n\nassert expr == 'f(1)'\n\nexpr = calculator.simplify('lim_(x -> oo) 1/x')\n\nassert expr == '0'\n\n```\n\n\n\n### Variances\n\n\n\nYou can **ASSIGN** variance a value using same assignment form in typst:\n\n\n\n```typst\n\n#let x = 1\n\n\n\n// Before\n\n$ x $\n\n\n\n// Shift + Ctrl + E\n\n// After\n\n$ x = 1 $\n\n```\n\n\n\nPS: You can use grammar like `y == x + 1` to describe the relation of equality.\n\n\n\nIf you want to see the bonding of variances, you can press `Shift + Ctrl + P`, and input `typst-sympy-calculator: Show Current variances`, then you will get data like:\n\n\n\n```typst\n\ny = x + 1\n\nz = 2 x\n\n```\n\n\n\n### Functions\n\n\n\nYou can **DEFINE** a function using same form in typst:\n\n\n\n```typst\n\n#let f = math.op(\"f\")\n\n\n\n// Before\n\n$ f(1) + f(1) $\n\n\n\n// Shift + Ctrl + E\n\n// After\n\n$ f(1) + f(1) = 2 f(1) $\n\n```\n\n\n\n### Symbols\n\n\n\nYou can **DEFINE** a symbol using same form in typst:\n\n\n\n```typst\n\n#let xy = math.italic(\"xy\")\n\n#let email = symbol(\"\ud83d\udd82\", (\"stamped\", \"\ud83d\udd83\"),)\n\n\n\n$ xy + email + email.stamped $\n\n```\n\n\n\n### Accents\n\n\n\nYou can **DEFINE** a accent using same form in typst:\n\n\n\n```typst\n\n#let acc(x) = math.accent(x, math.grave)\n\n\n\n$ acc(x) $\n\n```\n\n\n\n### Decorators for Operators\n\n\n\nYou can **DEFINE** a operator using same form in typst:\n\n\n\n```typst\n\n#let add = math.op(\"+\")\n\n\n\n'''typst-calculator\n\n@additive_op()\n\ndef convert_add(a, b):\n\n    return a + b\n\n'''\n\n\n\n// Before\n\n$ 1 add 1 $\n\n\n\n// Shift + Ctrl + E\n\n// After\n\n$ 1 add 1 = 2 $\n\n```\n\n\n\nOr just use `'''typst-sympy-calculator` or `'''python \\n # typst-calculator` to define a operator.\n\n\n\nthere are some decorators you can use:\n\n\n\n- `@operator(type='ADDITIVE_OP', convert_ast=convert_ast, name=name, ast=False)`: Define a common operator;\n\n- `@func()`: Define a function, receive args list; \n\n- `@func_mat()`: Define a matrix function, receive single arg `matrix`;\n\n- `@constant()`: Define a constant, receive no args but only return a constant value;\n\n- `@relation_op()`: Define a relation operator, receive args `a` and `b`;\n\n- `@additive_op()`: Define a additive operator, receive args `a` and `b`;\n\n- `@mp_op()`: Define a multiplicative operator, receive args `a` and `b`;\n\n- `@postfix_op()`: Define a postfix operator, receive args `a`;\n\n- `@reduce_op()`: Define a reduce operator, receive args `expr` and `args = (symbol, sub, sup)`;\n\n\n\nIt is important that the function name MUST be `def convert_{operator_name}`, or you can use decorator arg `@func(name='operator_name')`, and the substring `_dot_` will be replaced by `.`.\n\n\n\nThere are some examples (from [DefaultTypstCalculator.py](https://github.com/OrangeX4/typst-sympy-calculator/blob/main/DefaultTypstCalculator.py)):\n\n\n\n```python\n\n# Functions\n\n@func()\n\ndef convert_binom(n, k):\n\n    return sympy.binomial(n, k)\n\n\n\n# Matrix\n\n@func_mat()\n\ndef convert_mat(mat):\n\n    return sympy.Matrix(mat)\n\n\n\n# Constants\n\n@constant()\n\ndef convert_oo():\n\n    return sympy.oo\n\n\n\n# Relation Operators\n\n@relation_op()\n\ndef convert_eq(a, b):\n\n    return sympy.Eq(a, b)\n\n\n\n# Additive Operators\n\n@additive_op()\n\ndef convert_plus(a, b):\n\n    return a + b\n\n\n\n# Mp Operators\n\n@mp_op()\n\ndef convert_times(a, b):\n\n    return a * b\n\n\n\n# Postfix Operators\n\n@postfix_op()\n\ndef convert_degree(expr):\n\n    return expr / 180 * sympy.pi\n\n\n\n# Reduces\n\n@reduce_op()\n\ndef convert_sum(expr, args):\n\n    # symbol, sub, sup = args\n\n    return sympy.Sum(expr, args)\n\n```\n\n\n\n\n\n## Contributing\n\n\n\n1. Clone it by `git clone https://github.com/OrangeX4/typst-calculator.git`\n\n2. Install dependencies by `pip install -r requirements.txt`\n\n3. Compile ANTLR grammar by `python ./scripts/compile.py`\n\n4. Debug or add your code with `TypstCalculatorServer.py` or `TypstCalculator.py`, etc...\n\n\n\nIt is welcome to create an issue or pull request.\n\n\n\n\n\n## Thanks\n\n\n\n- [augustt198 / latex2sympy](https://github.com/augustt198/latex2sympy)\n\n- [purdue-tlt / latex2sympy](https://github.com/purdue-tlt/latex2sympy)\n\n- [ANTLR](https://www.antlr.org/)\n\n- [Sympy](https://www.sympy.org/en/index.html)\n\n\n\n\n\n## License\n\n\n\nThis project is licensed under the MIT License.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Convert typst math expressions to sympy form with ANTLR and support matrix, calculous and custom functions.",
    "version": "0.6.2",
    "project_urls": {
        "Homepage": "https://github.com/OrangeX4/typst-sympy-calculator"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7d954eb2e50e127d02c21f3702d5cec9b96d68bacde53c17d11d25e38a958c4a",
                "md5": "b1db5d521c07a1957dfeea68aecd8d2a",
                "sha256": "4ed01543822e78fb4cf39fc9c2ebb58b411a10c12cf1c9a0f8fbded4a8aa2c2e"
            },
            "downloads": -1,
            "filename": "typst_sympy_calculator-0.6.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "b1db5d521c07a1957dfeea68aecd8d2a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 35305,
            "upload_time": "2024-01-28T08:22:13",
            "upload_time_iso_8601": "2024-01-28T08:22:13.405454Z",
            "url": "https://files.pythonhosted.org/packages/7d/95/4eb2e50e127d02c21f3702d5cec9b96d68bacde53c17d11d25e38a958c4a/typst_sympy_calculator-0.6.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-01-28 08:22:13",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "OrangeX4",
    "github_project": "typst-sympy-calculator",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [],
    "lcname": "typst-sympy-calculator"
}
        
Elapsed time: 0.58768s