equationnet 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- equationnet/__init__.py +15 -0
- equationnet/cli.py +124 -0
- equationnet/codegen.py +106 -0
- equationnet/data/spring.csv +41 -0
- equationnet/fit.py +994 -0
- equationnet/guide.py +777 -0
- equationnet/models.py +187 -0
- equationnet/parse.py +339 -0
- equationnet/table.py +161 -0
- equationnet/templates.py +1476 -0
- equationnet-1.0.0.dist-info/METADATA +468 -0
- equationnet-1.0.0.dist-info/RECORD +16 -0
- equationnet-1.0.0.dist-info/WHEEL +5 -0
- equationnet-1.0.0.dist-info/entry_points.txt +2 -0
- equationnet-1.0.0.dist-info/licenses/LICENSE +21 -0
- equationnet-1.0.0.dist-info/top_level.txt +1 -0
equationnet/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""equationnet: type an equation; six simple models are trained on your data and ranked on held-out points.
|
|
2
|
+
|
|
3
|
+
import equationnet as en
|
|
4
|
+
result = en.fit("u_tt + c*u_t + k*u = 0", "data.csv")
|
|
5
|
+
print(result.table())
|
|
6
|
+
result.best.save("best_model.py")
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from .fit import Candidate, Result, YourModel, custom, fit, generate
|
|
10
|
+
from .models import MODELS, VERSION, NotApplicable
|
|
11
|
+
from .parse import Equation, EquationError, parse_equation
|
|
12
|
+
|
|
13
|
+
__version__ = VERSION
|
|
14
|
+
__all__ = ["fit", "generate", "custom", "YourModel", "parse_equation", "Result", "Candidate", "Equation",
|
|
15
|
+
"EquationError", "NotApplicable", "MODELS", "__version__"]
|
equationnet/cli.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Command line:
|
|
2
|
+
|
|
3
|
+
equationnet (no arguments: a guided session, see guide.py)
|
|
4
|
+
equationnet start (the same)
|
|
5
|
+
equationnet fit "u_tt + c*u_t + k*u = 0" data.csv [--split forecast] [--out scripts/]
|
|
6
|
+
equationnet script "u_t = D*u_xx" --model pinn > train_pinn.py
|
|
7
|
+
equationnet models
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import sys
|
|
14
|
+
|
|
15
|
+
from .fit import fit, generate
|
|
16
|
+
from .models import MODELS, NotApplicable
|
|
17
|
+
from .parse import EquationError
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _known(items: list[str]) -> dict:
|
|
21
|
+
out = {}
|
|
22
|
+
for it in items or []:
|
|
23
|
+
k, eq, v = it.partition("=")
|
|
24
|
+
try:
|
|
25
|
+
out[k.strip()] = float(v)
|
|
26
|
+
except ValueError:
|
|
27
|
+
raise ValueError(f"--known takes NAME=NUMBER, e.g. k=4.0; got {it!r}") from None
|
|
28
|
+
if not eq:
|
|
29
|
+
raise ValueError(f"--known takes NAME=NUMBER, e.g. k=4.0; got {it!r}")
|
|
30
|
+
return out
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _cv(text: str):
|
|
34
|
+
if text == "auto":
|
|
35
|
+
return "auto"
|
|
36
|
+
try:
|
|
37
|
+
return int(text)
|
|
38
|
+
except ValueError:
|
|
39
|
+
raise ValueError(f"--cv takes 'auto' or a whole number of folds, not {text!r}") from None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def main(argv: list[str] | None = None) -> int:
|
|
43
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
44
|
+
if not argv or argv == ["start"]:
|
|
45
|
+
from .guide import run
|
|
46
|
+
return run()
|
|
47
|
+
p = argparse.ArgumentParser(
|
|
48
|
+
prog="equationnet",
|
|
49
|
+
description="Is your equation better than no equation? Type equationnet with no arguments "
|
|
50
|
+
"for a guided session, or use the commands below.")
|
|
51
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
52
|
+
sub.add_parser("start", help="a guided session: questions instead of options (same as no arguments)")
|
|
53
|
+
|
|
54
|
+
f = sub.add_parser("fit", help="train every model on your data and rank them")
|
|
55
|
+
f.add_argument("equation")
|
|
56
|
+
f.add_argument("data", help="CSV with one column per variable and one for the target")
|
|
57
|
+
f.add_argument("--target", default="u")
|
|
58
|
+
f.add_argument("--known", nargs="*", metavar="NAME=VALUE", help="constants you already know")
|
|
59
|
+
f.add_argument("--models", nargs="*", choices=list(MODELS), help="default: all")
|
|
60
|
+
f.add_argument("--split", choices=["random", "forecast"], default="random")
|
|
61
|
+
f.add_argument("--holdout", type=float, default=0.2)
|
|
62
|
+
f.add_argument("--seed", type=int, default=0)
|
|
63
|
+
f.add_argument("--cv", default="1",
|
|
64
|
+
help="1 = one held-out split (default); k = k-fold cross-validation; 'auto' = only under 50 points")
|
|
65
|
+
f.add_argument("--predict-at", help="CSV of locations you want predictions at (e.g. future times)")
|
|
66
|
+
f.add_argument("--pick", choices=["simplest", "lowest"], default="simplest",
|
|
67
|
+
help="simplest (default): among models tied within the noise, the one with the "
|
|
68
|
+
"one the equation constrains most; lowest: the lowest held-out error")
|
|
69
|
+
f.add_argument("--out", help="folder to write every model's script into")
|
|
70
|
+
|
|
71
|
+
s = sub.add_parser("script", help="print the training script for one model (no data needed)")
|
|
72
|
+
s.add_argument("equation")
|
|
73
|
+
s.add_argument("--model", choices=list(MODELS), default="pinn")
|
|
74
|
+
s.add_argument("--target", default="u")
|
|
75
|
+
s.add_argument("--vars", nargs="*", help="independent variables, in CSV column order")
|
|
76
|
+
s.add_argument("--known", nargs="*", metavar="NAME=VALUE")
|
|
77
|
+
|
|
78
|
+
sub.add_parser("models", help="list the models")
|
|
79
|
+
|
|
80
|
+
a = p.parse_args(argv)
|
|
81
|
+
try:
|
|
82
|
+
if a.cmd == "models":
|
|
83
|
+
for m in MODELS.values():
|
|
84
|
+
print(f"{m.name:<14}{m.title}\n{'':<14}" + m.doc.replace("\n", "\n" + " " * 14))
|
|
85
|
+
return 0
|
|
86
|
+
if a.cmd == "script":
|
|
87
|
+
print(generate(a.equation, a.model, target=a.target, indep=a.vars, known=_known(a.known)))
|
|
88
|
+
return 0
|
|
89
|
+
res = fit(a.equation, a.data, target=a.target, known=_known(a.known),
|
|
90
|
+
models=a.models or "all", split=a.split, holdout=a.holdout, seed=a.seed,
|
|
91
|
+
cv=_cv(a.cv), predict_at=a.predict_at, pick=a.pick)
|
|
92
|
+
print()
|
|
93
|
+
print(res.table())
|
|
94
|
+
if a.predict_at:
|
|
95
|
+
from pathlib import Path
|
|
96
|
+
|
|
97
|
+
import numpy as np
|
|
98
|
+
|
|
99
|
+
from .fit import _as_points
|
|
100
|
+
pts = _as_points(a.predict_at, res.equation.indep)
|
|
101
|
+
pred = res.best.predict(pts)
|
|
102
|
+
out = Path(a.predict_at).with_name(Path(a.predict_at).stem + f"_{res.best.name}_pred.csv")
|
|
103
|
+
np.savetxt(out, np.column_stack([pts, pred]), delimiter=",",
|
|
104
|
+
header=",".join(res.equation.indep + ["prediction"]), comments="")
|
|
105
|
+
print(f"\npredictions of {res.best.title} at {a.predict_at} written to {out}")
|
|
106
|
+
for row, p in list(zip(pts, pred))[:20]:
|
|
107
|
+
print(" " + ", ".join(f"{v:g}" for v in row) + f" -> {p:.6g}")
|
|
108
|
+
if a.out:
|
|
109
|
+
paths = res.save_scripts(a.out)
|
|
110
|
+
print(f"\nscripts written: {', '.join(str(x) for x in paths)}")
|
|
111
|
+
return 0
|
|
112
|
+
except EquationError as exc:
|
|
113
|
+
print(f"equation problem: {exc}", file=sys.stderr)
|
|
114
|
+
return 2
|
|
115
|
+
except (ValueError, OSError, NotApplicable) as exc: # input problems: say it in words
|
|
116
|
+
print(f"problem: {exc}", file=sys.stderr)
|
|
117
|
+
return 2
|
|
118
|
+
except KeyboardInterrupt:
|
|
119
|
+
print("stopped", file=sys.stderr)
|
|
120
|
+
return 130
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
if __name__ == "__main__":
|
|
124
|
+
sys.exit(main())
|
equationnet/codegen.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Print sympy expressions as plain Python for numpy or torch.
|
|
2
|
+
|
|
3
|
+
The generated scripts are the code that actually runs: equationnet renders a
|
|
4
|
+
script, executes it in-process, and hands the same text to the user.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import sympy as sp
|
|
10
|
+
from sympy.printing.numpy import NumPyPrinter
|
|
11
|
+
from sympy.printing.pycode import PythonCodePrinter
|
|
12
|
+
|
|
13
|
+
from .parse import Equation, EquationError
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class _TorchPrinter(PythonCodePrinter):
|
|
17
|
+
"""Python printer that uses torch.* for math functions."""
|
|
18
|
+
|
|
19
|
+
def __init__(self):
|
|
20
|
+
super().__init__({"fully_qualified_modules": True, "standard": "python3"})
|
|
21
|
+
|
|
22
|
+
def doprint(self, expr, assign_to=None):
|
|
23
|
+
return super().doprint(expr, assign_to).replace("math.", "torch.")
|
|
24
|
+
|
|
25
|
+
def _print_Abs(self, expr):
|
|
26
|
+
return f"torch.abs({self._print(expr.args[0])})"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def numpy_code(expr: sp.Expr) -> str:
|
|
30
|
+
return NumPyPrinter({"fully_qualified_modules": True}).doprint(expr).replace("numpy.", "np.")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _numbers_as_floats(expr: sp.Expr) -> sp.Expr:
|
|
34
|
+
"""log(2), sqrt(2), exp(-1), pi: torch functions reject plain Python numbers, so every
|
|
35
|
+
constant subexpression is evaluated to a float first."""
|
|
36
|
+
return expr.replace(lambda e: getattr(e, "is_number", False) and not e.is_Number,
|
|
37
|
+
lambda e: sp.Float(e.evalf(17)))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def torch_code(expr: sp.Expr) -> str:
|
|
41
|
+
return _TorchPrinter().doprint(_numbers_as_floats(expr))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# Names the generated code itself uses. A constant or column with one of these names
|
|
45
|
+
# keeps its name for the user (P["np"]) but gets a different name inside the script.
|
|
46
|
+
RESERVED = {"np", "torch", "math", "V", "P", "F", "residual", "sp", "scipy"}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _safe(name: str) -> str:
|
|
50
|
+
return f"{name}_eq" if name in RESERVED else name
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _safe_expr(expr: sp.Expr) -> sp.Expr:
|
|
54
|
+
return expr.xreplace({s: sp.Symbol(_safe(str(s))) for s in expr.free_symbols if str(s) in RESERVED})
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _unpack_lines(names: list[str], source: str, indent: str = " ") -> list[str]:
|
|
58
|
+
return [f'{indent}{_safe(n)} = {source}["{n}"]' for n in names]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def residual_function(eq: Equation, backend: str) -> str:
|
|
62
|
+
"""def residual(V, P, F): V = values (variables, target, derivatives),
|
|
63
|
+
P = fitted parameters, F = unknown functions (callables)."""
|
|
64
|
+
code = torch_code if backend == "torch" else numpy_code
|
|
65
|
+
names = [*eq.indep, eq.target, *eq.derivs]
|
|
66
|
+
used = {str(s) for s in eq.residual.free_symbols}
|
|
67
|
+
for u in eq.ufuncs:
|
|
68
|
+
used |= {str(s) for s in u.arg.free_symbols}
|
|
69
|
+
lines = ["def residual(V, P, F):",
|
|
70
|
+
f' """{eq.text} -> lhs - rhs (zero when the equation holds)."""']
|
|
71
|
+
lines += _unpack_lines([n for n in names if n in used], "V")
|
|
72
|
+
lines += _unpack_lines([p for p in eq.params if p in used], "P")
|
|
73
|
+
for u in eq.ufuncs:
|
|
74
|
+
lines.append(f' {u.placeholder} = F["{u.name}"]({code(_safe_expr(u.arg))})')
|
|
75
|
+
lines.append(f" return {code(_safe_expr(eq.residual))}")
|
|
76
|
+
return "\n".join(lines)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def solved_for(eq: Equation, name: str) -> sp.Expr:
|
|
80
|
+
"""Solve the residual for one derivative symbol (must be unique)."""
|
|
81
|
+
sym = sp.Symbol(name)
|
|
82
|
+
if not eq.residual.has(sym):
|
|
83
|
+
raise EquationError(f"{name} does not appear in the equation")
|
|
84
|
+
sols = sp.solve(eq.residual, sym, dict=False)
|
|
85
|
+
if len(sols) != 1:
|
|
86
|
+
raise EquationError(f"the equation cannot be solved uniquely for {name} "
|
|
87
|
+
f"({len(sols)} solutions)")
|
|
88
|
+
return sols[0]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def explicit_function(eq: Equation, fname: str, solve_for: str, args: list[str]) -> str:
|
|
92
|
+
"""def <fname>(<args>, P, F): return <solve_for> written explicitly (numpy)."""
|
|
93
|
+
expr = solved_for(eq, solve_for)
|
|
94
|
+
used = {str(s) for s in expr.free_symbols}
|
|
95
|
+
for u in eq.ufuncs:
|
|
96
|
+
used |= {str(s) for s in u.arg.free_symbols}
|
|
97
|
+
extra = sorted(used - set(args) - set(eq.params) - {u.placeholder for u in eq.ufuncs})
|
|
98
|
+
if extra:
|
|
99
|
+
raise EquationError(f"{solve_for} depends on {', '.join(extra)}, which this solver does not track")
|
|
100
|
+
lines = [f"def {fname}({', '.join(_safe(a) for a in args)}, P, F):",
|
|
101
|
+
f' """{solve_for} from the equation {eq.text}"""']
|
|
102
|
+
lines += _unpack_lines([p for p in eq.params if p in used], "P")
|
|
103
|
+
for u in eq.ufuncs:
|
|
104
|
+
lines.append(f' {u.placeholder} = F["{u.name}"]({numpy_code(_safe_expr(u.arg))})')
|
|
105
|
+
lines.append(f" return {numpy_code(_safe_expr(expr))}")
|
|
106
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
t,u
|
|
2
|
+
0,1.01728
|
|
3
|
+
0.25641,0.915667
|
|
4
|
+
0.512821,0.558409
|
|
5
|
+
0.769231,0.0344771
|
|
6
|
+
1.02564,-0.289277
|
|
7
|
+
1.28205,-0.631418
|
|
8
|
+
1.53846,-0.814261
|
|
9
|
+
1.79487,-0.687153
|
|
10
|
+
2.05128,-0.454696
|
|
11
|
+
2.30769,-0.115837
|
|
12
|
+
2.5641,0.220235
|
|
13
|
+
2.82051,0.515456
|
|
14
|
+
3.07692,0.579794
|
|
15
|
+
3.33333,0.574764
|
|
16
|
+
3.58974,0.383248
|
|
17
|
+
3.84615,0.173867
|
|
18
|
+
4.10256,-0.133654
|
|
19
|
+
4.35897,-0.375541
|
|
20
|
+
4.61538,-0.519239
|
|
21
|
+
4.87179,-0.484506
|
|
22
|
+
5.12821,-0.346579
|
|
23
|
+
5.38462,-0.159412
|
|
24
|
+
5.64103,0.141579
|
|
25
|
+
5.89744,0.314209
|
|
26
|
+
6.15385,0.236125
|
|
27
|
+
6.41026,0.285022
|
|
28
|
+
6.66667,0.28398
|
|
29
|
+
6.92308,0.118793
|
|
30
|
+
7.17949,-0.0255604
|
|
31
|
+
7.4359,-0.179505
|
|
32
|
+
7.69231,-0.180056
|
|
33
|
+
7.94872,-0.359241
|
|
34
|
+
8.20513,-0.263713
|
|
35
|
+
8.46154,-0.0276139
|
|
36
|
+
8.71795,0.0412725
|
|
37
|
+
8.97436,0.168299
|
|
38
|
+
9.23077,0.192844
|
|
39
|
+
9.48718,0.159247
|
|
40
|
+
9.74359,0.21158
|
|
41
|
+
10,0.122741
|