ModECI / MDF

This repository contains the source for the MDF specification and Python API
https://mdf.readthedocs.io
Apache License 2.0
36 stars 70 forks source link

Exp in expressions #236

Open FatimaArshad-DS opened 2 years ago

FatimaArshad-DS commented 2 years ago

I have written this piece of code:

exp_node = Node(id="exp_node")

exp_node.parameters.append(Parameter(id="period", value=3.14))

s1 = Parameter(
    id="level", default_initial_value=1, time_derivative="1.27  * period * rate"
)
exp_node.parameters.append(s1)

s2 = Parameter(
    id="rate",
    default_initial_value=1,
    time_derivative="level * 2",
)
exp_node.parameters.append(s2)
p2 = Parameter(
    id="exp",
    value=  "level",

)
exp_node.parameters.append(p2)
op1 = OutputPort(id="out_port", value="exponential")
exp_node.output_ports.append(op1)

mod_graph.nodes.append(exp_node)

new_file = mod.to_json_file("%s.json" % mod.id)
new_file = mod.to_yaml_file("%s.yaml" % mod.id)

verbose = True
from modeci_mdf.utils import load_mdf, print_summary

from modeci_mdf.execution_engine import EvaluableGraph

eg = EvaluableGraph(mod_graph, verbose)
dt = 0.01

duration = 2
t = 0
recorded = {}
times = []
s = []
while t <= duration:
    times.append(t)
    print("======   Evaluating at t = %s  ======" % (t))
    if t == 0:
        eg.evaluate()  # replace with initialize?
    else:
        eg.evaluate(time_increment=dt)

    s.append(eg.enodes["exp_node"].evaluable_outputs["out_port"].curr_value)
    t += dt

This resulted in this error: Exception: Error! Could not evaluate expression [exponential] with params [period=3.14, level=1, rate=1, exp=1], returned [exponential] which is a <class 'str'>

Sometimes even adding some parentheses gives this error. There should be a mechanism to display what caused an error to aid in troubleshooting process.

pgleeson commented 2 years ago

Thanks for reporting this @FatimaArshad-DS. The error message is indeed obscure, but basically it comes down to the fact that the execution engine can't determine how to evaluate the expression exponential. There is no other parameter/input port with that value. Did you mean to call it exp, which is defined as a parameter?

Note when the execution engine gets a string expression it can't evaluate, it returns it as a string (as opposed to filling in the values for the parameters etc and evaluating it with Python, and returning a numerical value). This is the default fallback since sometimes parameters will need to be actual strings.

See also the comment here: https://github.com/ModECI/MDF/discussions/235 about using an expression like a + exp(b) in the value of parameters.