aboutsummaryrefslogtreecommitdiffstats
path: root/examples/readme.py
blob: 8cf626c7450505a7b494820209e6b444cd302673 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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"{str(p) = }")

# 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)