diff options
author | Nao Pross <np@0hm.ch> | 2024-03-08 00:26:31 +0100 |
---|---|---|
committer | Nao Pross <np@0hm.ch> | 2024-03-08 00:26:43 +0100 |
commit | 4b41360359121ac906bc41292b4aefa1219ac6b3 (patch) | |
tree | 91178bfdb2ec7dca2c601040e480ccf722a8a22f /examples | |
parent | Update README (diff) | |
download | mdpoly-4b41360359121ac906bc41292b4aefa1219ac6b3.tar.gz mdpoly-4b41360359121ac906bc41292b4aefa1219ac6b3.zip |
Create directory for examples
Diffstat (limited to 'examples')
-rw-r--r-- | examples/readme.py | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/examples/readme.py b/examples/readme.py new file mode 100644 index 0000000..82a27d8 --- /dev/null +++ b/examples/readme.py @@ -0,0 +1,43 @@ +try: + import mdpoly +except ModuleNotFoundError: + import sys + import pathlib + parent = pathlib.Path(__file__).resolve().parent.parent + sys.path.append(str(parent)) + +from mdpoly import State, Variable, Parameter +from mdpoly.representations import SparseRepr + +# Construct an expression +x, y = Variable.from_names("x, y") # or just Variable("x") +k = Parameter("k") + +p = (x + 2 * y) ** 3 + y ** 2 + k +print(f"{p = }") + +# Expressions can be easily reparametrized +w = Parameter("w") +q = p.replace(y, w).replace(k, k ** 2) +print(f"{q = }") + +# Make a concrete representation +state = State(parameters={k: 3.14}) # try to replace with empty dict +sparse, state = p.to_repr(SparseRepr, state) + +# Look inside the representation +for entry in sparse.entries(): + print(f"at (row, col) = {entry.row, entry.col} there is a polynomial:") + for term in sparse.terms(entry): + monomial_str = "" + for idx in term: + var = state.from_index(idx) + monomial_str += f"{var}^{idx.power} " + + # Get the coefficient + coeff = sparse.at(entry, term) + print(" - the monomial", monomial_str, "has coefficient", coeff) + +# You can also simply iterate over it +for entry, term, coeff in sparse: + print(entry, term, coeff) |