-
Notifications
You must be signed in to change notification settings - Fork 70
/
execution_engine.py
1418 lines (1188 loc) · 49.2 KB
/
execution_engine.py
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""The reference implementation of the MDF execution engine; allows for executing :class:`~modeci.mdf.Graph`
objects in Python.
This module implements a set of classes for executing loaded MDF models in Python.
The implementation is organized such that each class present in :mod:`~modeci_mdf.mdf`
has a corresponding :code:`Evaluable` version of the class. Each of these classes implements
the execution of these components and tracks their state during execution. The organization of the entire execution of
the model is implemented at the top-level :func:`~modeci_mdf.execution_engine.EvaluableGraph.evaluate` method
of the :class:`EvaluableGraph` class. The external library `graph-scheduler
<https://pypi.org/project/graph-scheduler/>`_ is used to implement the scheduling of nodes under declarative
conditional constraints.
"""
import ast
import builtins
import copy
import functools
import inspect
import itertools
import os
import re
import sys
import math
import attr
import numpy as np
import graph_scheduler
import onnxruntime
from modeci_mdf.functions.standard import mdf_functions, create_python_expression
from modelspec.utils import evaluate as evaluate_params_modelspec
from modelspec.utils import _params_info, _val_info
from modelspec.utils import FORMAT_NUMPY
from collections import OrderedDict
from typing import Union, List, Dict, Optional, Any, Tuple
from modeci_mdf.mdf import (
Function,
Graph,
Condition,
Edge,
OutputPort,
InputPort,
Node,
Parameter,
)
import modeci_mdf.functions.onnx as onnx_ops
import modeci_mdf.functions.actr as actr_funcs
import modeci_mdf.functions.ddm as ddm_funcs
FORMAT_DEFAULT = FORMAT_NUMPY
KNOWN_PARAMETERS = ["constant", "math", "numpy"] + dir(builtins)
time_scale_str_regex = r"(TimeScale)?\.(.*)"
def evaluate_expr(
expr: Union[str, List[str], np.ndarray, "tf.tensor"] = None,
func_params: Dict[str, Any] = None,
array_format: str = FORMAT_DEFAULT,
allow_strings_returned: Optional[bool] = False,
verbose: Optional[bool] = False,
) -> np.ndarray:
"""Evaluates an expression given in string format and a :code:`dict` of parameters.
Args:
expr: Expression or list of expressions to be evaluated
func_params: A dict of parameters (e.g. :code:`{'weight': 2}`)
array_format: It can be a n-dimensional array or a tensor
allow_strings_returned: Don't throw an error if the expression evaluates to a string
verbose: If set to True provides in-depth information else verbose message is not displayed
Returns:
n-dimensional array
"""
e = evaluate_params_modelspec(
expr, func_params, array_format=array_format, verbose=verbose
)
if type(e) == str and e not in KNOWN_PARAMETERS and not allow_strings_returned:
raise Exception(
"Error! Could not evaluate expression [%s] with params %s, returned [%s] which is a %s"
% (expr, _params_info(func_params, multiline=True), e, type(e))
)
return e
def evaluate_onnx_expr(
expr: str,
base_parameters: Dict[str, Any],
evaluated_parameters: Dict,
verbose: bool = False,
) -> Any:
"""Evaluates a simple expression in string format representing an
ONNX function call
Args:
expr (str): Expression to be evaluated
base_parameters (Dict[str, Any]): A dict of parameters that may contain variables
evaluated_parameters (Dict): A dict mapping variables used in **base_parameters** to actual values
verbose (bool, optional): If set to True provides in-depth information else verbose message is not displayed. Defaults to False.
Returns:
Any: the return value of **expr**
"""
# Get the ONNX function
onnx_name = expr.split("(")[0].split(".")[-1]
onnx_function = getattr(onnx_ops, onnx_name)
onnx_schema = onnx_ops.get_onnx_schema(onnx_name)
onnx_arguments = set(
list(onnx_schema.attributes.keys()) + [i.name for i in onnx_schema.inputs]
)
# used to attempt to match inputs to expected onnx input types
onnx_typecast_mappings = {
onnx_schema.AttrType.INT: int,
onnx_schema.AttrType.FLOAT: float,
onnx_schema.AttrType.STRING: str,
onnx_schema.AttrType.INTS: functools.partial(np.array, dtype=int),
onnx_schema.AttrType.FLOATS: functools.partial(np.array, dtype=float),
onnx_schema.AttrType.STRINGS: functools.partial(np.array, dtype=str),
# TODO: add tensor and graph types?
}
try:
has_variadic = (
onnx_schema.inputs[0].option == onnx_schema.FormalParameterOption.Variadic
)
except IndexError:
has_variadic = False
# ONNX functions expect input args or kwargs first, followed by parameters (called attributes in ONNX) as
# kwargs. Lets construct this.
kwargs_for_onnx = {}
for kw, arg_expr in base_parameters.items():
if isinstance(arg_expr, str):
arg_expr_list = get_required_variables_from_expression(arg_expr)
for a in arg_expr_list:
try:
kwargs_for_onnx[a] = evaluated_parameters[a]
except KeyError:
pass
try:
if arg_expr[0] == "[" and arg_expr[-1] == "]":
# matches previous behavior
continue
except IndexError:
pass
kwargs_for_onnx[kw] = evaluated_parameters[kw]
kwargs_for_onnx = {
k: v
for k, v in kwargs_for_onnx.items()
if (
(k in onnx_arguments or has_variadic)
and "onnx_" not in k # filter Evaluable__ class names
)
}
# attempt to cast attributes to what onnx_function expects
for k, v in kwargs_for_onnx.items():
try:
onnx_attr = onnx_schema.attributes[k]
except KeyError:
continue
try:
cast_type = onnx_typecast_mappings[onnx_attr.type]
except KeyError:
continue
try:
kwargs_for_onnx[k] = cast_type(v)
except (TypeError, ValueError):
pass
if verbose:
print(f"Evaluating ONNX function {onnx_name} with {kwargs_for_onnx}")
try:
result = onnx_function(**kwargs_for_onnx)
except (
onnxruntime.capi.onnxruntime_pybind11_state.NotImplemented,
onnxruntime.capi.onnxruntime_pybind11_state.Fail,
) as e:
err = str(e)
if (
"bound to different types (tensor(double) and tensor(float)" not in err
and "Could not find an implementation for the node" not in err
):
raise
# assume this is related to lack of support for float64/double
# for Cos, Relu (and likely others) on onnx CPUExecutionProvider
result = onnx_function(
**{
k: v.astype(np.float32)
if hasattr(v, "dtype") and v.dtype == np.float64
else v
for k, v in kwargs_for_onnx.items()
}
)
try:
if result.dtype == np.float32:
result = result.astype(np.float64)
except AttributeError:
pass
return result
def get_required_variables_from_expression(expr: str) -> List[str]:
"""Produces a list containing variable symbols in **expr**"""
def recursively_extract_subscripted_values(s):
res = []
subscript_indices = []
depth = 0
len_s = len(s)
for i in range(len_s):
if s[i] == "[":
if depth == 0:
subscript_indices.append([i, None])
depth += 1
if s[i] == "]":
depth -= 1
if depth == 0:
subscript_indices[-1][1] = i
# s contains no subscripts, so it won't be added in below loop
if len(subscript_indices) == 0 and len_s > 0:
res.append(s)
last = 0
for start, end in subscript_indices:
if end is None:
end = len_s
res.extend(recursively_extract_subscripted_values(s[start + 1 : end]))
# add expression being subscripted
if last != start:
res.append(s[last:start])
last = end + 1
return res
if not isinstance(expr, str):
return []
result = []
for e in recursively_extract_subscripted_values(expr):
result.extend(
[
str(elem.id)
for elem in ast.walk(
ast.parse(e.strip(" ,+-*/%^&").lstrip("])").rstrip("[("))
)
if isinstance(elem, ast.Name)
]
)
return result
class EvaluableFunction:
"""Evaluates a :class:`~modeci_mdf.mdf.Function` value during MDF graph execution.
Args:
function: :func:`~modeci_mdf.mdf.Function` to be evaluated e.g. mdf standard function
verbose: If set to True Provides in-depth information else verbose message is not displayed
"""
def __init__(self, function: Function = False, verbose: Optional[bool] = False):
self.verbose = verbose
self.function = function
def evaluate(
self,
parameters: Dict[str, Any] = None,
array_format: str = FORMAT_DEFAULT,
) -> Dict[str, Any]:
r"""Performs evaluation on the basis of given parameters and array_format
Args:
parameters: A dictionary of function parameters,e.g.logistic, parameters={'gain': 2,"bias": 3,"offset": 1}
array_format: It can be a n-dimensional array or a tensor
Returns:
value of function after evaluation in Dictionary
"""
expr = None
# print("functions value and function>>>", self.function.value, self.function.function)
# func_val = self.function.value
if self.function.function:
for f in mdf_functions:
if f == self.function.function:
expr = create_python_expression(
mdf_functions[f]["expression_string"]
)
break
if expr is None:
expr = self.function.value
# #raise "Unknown function: {}. Known functions: {}".format(
# # self.function.function,
# # mdf_functions.keys,
# #)
func_params = {}
func_params.update(parameters)
if self.verbose:
print(
" Evaluating %s with %s, i.e. [%s]"
% (self.function, _params_info(func_params), expr)
)
if self.function.args is not None:
for arg in self.function.args:
func_params[arg] = evaluate_expr(
self.function.args[arg],
func_params,
verbose=False,
array_format=array_format,
)
if self.verbose:
print(
" Arg: {} became: {}".format(
arg, _val_info(func_params[arg])
)
)
# If this is an ONNX operation, evaluate it without modelspec.
if "onnx_ops." in expr:
if self.verbose:
print(f"{self.function.id} is evaluating ONNX function {expr}")
self.curr_value = evaluate_onnx_expr(
expr,
# parameters get overridden by self.function.args
{**parameters, **self.function.args},
func_params,
self.verbose,
)
elif "actr." in expr:
actr_function = getattr(actr_funcs, expr.split("(")[0].split(".")[-1])
self.curr_value = actr_function(
*[func_params[arg] for arg in self.function.args]
)
elif "ddm." in expr:
actr_function = getattr(ddm_funcs, expr.split("(")[0].split(".")[-1])
self.curr_value = ddm_function(
*[func_params[arg] for arg in self.function.args]
)
else:
self.curr_value = evaluate_expr(
expr, func_params, verbose=self.verbose, array_format=array_format
)
if self.verbose:
print(
" Evaluated %s with %s =\t%s"
% (self.function, _params_info(func_params), _val_info(self.curr_value))
)
return self.curr_value
class EvaluableParameter:
"""
Evaluates the current value of a :class:`~modeci_mdf.mdf.Parameter` during the MDF graph execution.
Args:
parameter: The parameter to evaluate during execution.
verbose: Whether to print output of parameter calculations.
"""
DEFAULT_INIT_VALUE = 0.0 # Temporary!
def __init__(self, parameter: Parameter, verbose: bool = False):
self.verbose = verbose
self.parameter = parameter
self.curr_value = None
def get_current_value(
self, parameters: Dict[str, Any], array_format: str = FORMAT_DEFAULT
) -> Any:
"""
Get the current value of the parameter; evaluates the expression if the current value has not yet been set. Note:
this is different from :code:`'evaluate'`, as calling that method multiple times can change the state of the parameter,
but calling this should not reevaluate the parameter if it has a current value.
Args:
parameters: a dictionary of parameters and their values that may or may not be needed to evaluate this
parameter.
array_format: The array format to use (either :code:`'numpy'` or :code:`tensorflow'`).
Returns:
The evaluated value of the parameter.
"""
# FIXME: Shouldn't this just call self.evaluate, seems like there is redundant code here?
if self.curr_value is None:
if (
self.parameter.value is not None
or self.parameter.default_initial_value is not None
):
if self.parameter.is_stateful():
if self.verbose:
print(f" Initial eval of <{self.parameter.summary()}> ")
if self.parameter.default_initial_value is not None:
return evaluate_expr(
self.parameter.default_initial_value,
parameters,
verbose=self.verbose,
array_format=array_format,
)
else:
return self.DEFAULT_INIT_VALUE
else:
ips = {}
ips.update(parameters)
ips[self.parameter.id] = self.DEFAULT_INIT_VALUE
self.curr_value = evaluate_expr(
self.parameter.value,
ips,
verbose=self.verbose,
array_format=array_format,
)
if self.verbose:
print(
" Initial eval of <{}> = {} ".format(
self.parameter, self.curr_value
)
)
return self.curr_value
def evaluate(
self,
parameters: Dict[str, Any],
time_increment: Optional[float] = None,
array_format: str = FORMAT_DEFAULT,
) -> Any:
"""
Evaluate the parameter and store the result in the :code:`curr_value` attribute.
Args:
parameters: a dictionary of parameters and their values that may or may not be needed to evaluate this
parameter.
time_increment: a floating point value specifying the timestep size, only used for :code:`time_derivative`
parameters
array_format: The array format to use (either :code:`'numpy'` or :code:`tensorflow'`).
Returns:
The current value of the parameter.
"""
if self.verbose:
print(
" Evaluating {} with {} ".format(
self.parameter.summary(), _params_info(parameters)
)
)
if self.parameter.value is not None:
self.curr_value = evaluate_expr(
self.parameter.value,
parameters,
verbose=False,
array_format=array_format,
)
elif self.parameter.function:
expr = None
for f in mdf_functions:
if self.parameter.function == f:
expr = create_python_expression(
mdf_functions[f]["expression_string"]
)
if not expr:
expr = self.parameter.function
# raise "Unknown function: {}. Known functions: {}".format(
# self.parameter.function,
# mdf_functions.keys,
# )
func_params = {}
func_params.update(parameters)
if self.verbose:
print(
" Evaluating %s with %s, i.e. [%s]"
% (self.parameter, _params_info(func_params), expr)
)
for arg in self.parameter.args:
func_params[arg] = evaluate_expr(
self.parameter.args[arg],
func_params,
verbose=False,
array_format=array_format,
)
if self.verbose:
print(
" Arg: {} became: {}".format(
arg, _val_info(func_params[arg])
)
)
# If this is an ONNX operation, evaluate it without modelspec.
if "onnx_ops." in expr:
if self.verbose:
print(f"{self.parameter.id} is evaluating ONNX function {expr}")
self.curr_value = evaluate_onnx_expr(
expr,
# parameters get overridden by self.parameter.args
{**parameters, **self.parameter.args},
func_params,
self.verbose,
)
elif "actr." in expr:
actr_function = getattr(actr_funcs, expr.split("(")[0].split(".")[-1])
self.curr_value = actr_function(
*[func_params[arg] for arg in self.parameter.args]
)
else:
self.curr_value = evaluate_expr(
expr,
func_params,
verbose=self.verbose,
array_format=array_format,
)
elif self.parameter.time_derivative is not None:
if time_increment == None:
self.curr_value = evaluate_expr(
self.parameter.default_initial_value,
parameters,
verbose=self.verbose,
array_format=array_format,
)
else:
td = evaluate_expr(
self.parameter.time_derivative,
parameters,
verbose=self.verbose,
array_format=array_format,
)
if self.verbose:
print(
f"Incrementing {self.parameter.id} from {self.curr_value} by {td} over time {time_increment}"
)
self.curr_value = np.add(
self.curr_value, td * time_increment, casting="safe"
)
cond_mask = None
val_if_true = None
if len(self.parameter.conditions) > 0:
for condition in self.parameter.conditions:
cond_mask = evaluate_expr(
condition.test,
parameters,
verbose=False,
array_format=array_format,
)
val_if_true = evaluate_expr(
condition.value,
parameters,
verbose=False,
array_format=array_format,
)
if self.verbose:
print(
" --- Condition: %s: %s = %s: true? %s"
% (condition.id, condition.test, val_if_true, cond_mask)
)
# e.g. if the parameter value is set only by a set of conditions...
if self.curr_value is None:
self.curr_value = self.DEFAULT_INIT_VALUE
self.curr_value = np.where(cond_mask, val_if_true, self.curr_value)
if self.verbose:
print(
" Evaluated this: %s with %s \n =\t%s"
% (
self.parameter.summary(),
_params_info(parameters),
_val_info(self.curr_value),
)
)
return self.curr_value
class EvaluableOutput:
r"""Evaluates the current value of an :class:`~modeci_mdf.mdf.OutputPort` during MDF graph execution.
Args:
output_port: Attribute of a Node which exports information to the dependent Node object
verbose: If set to True Provides in-depth information else verbose message is not displayed
"""
def __init__(self, output_port: OutputPort, verbose: Optional[bool] = False):
self.verbose = verbose
self.output_port = output_port
self.curr_value = None
def evaluate(
self,
parameters: Dict[str, Any] = None,
array_format: str = FORMAT_DEFAULT,
) -> Union[int, np.ndarray]:
"""Evaluate the value at the output port on the basis of parameters and array_format
Args:
parameters: Dictionary of global parameters of the Output Port
array_format: It is a n-dimensional array
Returns:
value at output port
"""
if self.verbose:
print(
" Evaluating %s with %s "
% (self.output_port, _params_info(parameters))
)
self.curr_value = evaluate_expr(
self.output_port.value, parameters, verbose=False, array_format=array_format
)
if self.verbose:
print(
" Evaluated %s with %s \n =\t%s"
% (
self.output_port,
_params_info(parameters),
_val_info(self.curr_value),
)
)
return self.curr_value
class EvaluableInput:
"""Evaluates input value at the :class:`~modeci_mdf.mdf.InputPort` of the node during MDF graph execution.
Args:
input_port: The :class:`~modeci_mdf.mdf.InputPort` is an attribute of a Node which imports information to the
:class:`~modeci_mdf.mdf.Node`
verbose: If set to True Provides in-depth information else verbose message is not displayed
"""
def __init__(self, input_port: InputPort, verbose: Optional[bool] = False):
self.verbose = verbose
self.input_port = input_port
default = 0
if input_port.type and "float" in input_port.type:
default = 0.0
self.curr_value = np.full(input_port.shape, default)
def set_input_value(self, value: Union[str, int, np.ndarray]):
"""Set a new value at input port
Args:
value: Value to be set at Input Port
"""
if self.verbose:
print(f" Input value in {self.input_port.id} set to {_val_info(value)}")
self.curr_value = value
def evaluate(
self, parameters: Dict[str, Any] = None, array_format: str = FORMAT_DEFAULT
) -> Union[int, np.ndarray]:
"""Evaluates value at Input port based on parameters and array_format
Args:
parameters: Dictionary of parameters
array_format: It is a n-dimensional array
Returns:
value at Input port
"""
if self.verbose:
print(
" Evaluated %s with params %s =\t%s"
% (
self.input_port,
_params_info(parameters),
_val_info(self.curr_value),
)
)
return self.curr_value
class EvaluableNode:
r"""Evaluates a :class:`~modeci_mdf.mdf.Node` during MDF graph execution.
Args:
node: A self contained unit of evaluation receiving input from other :class:`~modeci_mdf.mdf.Node`\(s) on
:class:`~modeci_mdf.mdf.InputPort`\(s).
verbose: If set to True Provides in-depth information else verbose message is not displayed
"""
def __init__(self, node: Node, verbose: Optional[bool] = False):
self.verbose = verbose
self.node = node
self.evaluable_inputs = {}
self.evaluable_parameters = OrderedDict()
self.evaluable_functions = OrderedDict()
self.evaluable_outputs = {}
all_known_vars = []
all_known_vars += KNOWN_PARAMETERS
for ip in node.input_ports:
rip = EvaluableInput(ip, self.verbose)
self.evaluable_inputs[ip.id] = rip
all_known_vars.append(ip.id)
# params_init[ip] = ip.curr_value
for p in node.parameters:
all_known_vars.append(p.id)
"""
for p in node.parameters:
ep = EvaluableParameter(p, self.verbose)
self.evaluable_parameters[p.id] = ep
all_known_vars.append(p.id)
# params_init[s] = s.curr_value"""
# TODO: the below checks for evaluability of functions and
# parameters using known variables are very similar and could be
# simplified with a function
all_funcs = [f for f in node.functions]
num_funcs_remaining = {f.id: None for f in node.functions}
func_missing_vars = {f.id: [] for f in node.functions}
# Order the functions into the correct sequence
while len(all_funcs) > 0:
f = all_funcs.pop(0) # pop first off list
if verbose:
print(
" Checking whether function: %s with args %s is sufficiently determined by known vars %s"
% (f.id, f.args, all_known_vars)
)
all_req_vars = []
if f.args:
for arg in f.args:
arg_expr = f.args[arg]
# If we are dealing with a list of symbols, each must treated separately
all_req_vars.extend(
[
v
for v in get_required_variables_from_expression(arg_expr)
if v not in f.args
]
)
if f.value is not None:
all_req_vars.extend(
[
v
for v in get_required_variables_from_expression(f.value)
if f.args is None or v not in f.args
]
)
all_present = [v in all_known_vars for v in all_req_vars]
func_missing_vars[f.id] = {
v for v in all_req_vars if v not in all_known_vars
}
if verbose:
print(
" Are all of %s in %s? %s"
% (all_req_vars, all_known_vars, all_present)
)
if all(all_present):
rf = EvaluableFunction(f, self.verbose)
self.evaluable_functions[f.id] = rf
all_known_vars.append(f.id)
# params_init[f] = self.evaluable_functions[f.id].evaluate(
# params_init, array_format=FORMAT_DEFAULT
# )
else:
# track the number of remaining functions each time f
# is examined. If it's the same as last time, we know
# every function was examined and nothing changed, so
# we can stop because otherwise it will just infinitely
# loop
if num_funcs_remaining[f.id] == len(all_funcs):
func_missing_vars = {
f: ", ".join(v) for f, v in func_missing_vars.items()
}
raise ValueError(
"Error! Could not evaluate functions using known vars. The following vars are missing:\n\t"
+ "\n\t".join(
f"{f}: {v}"
for f, v in func_missing_vars.items()
if len(v) > 0
)
)
else:
num_funcs_remaining[f.id] = len(all_funcs)
all_funcs.append(f)
all_params_to_check = [p for p in node.parameters]
num_params_remaining = {p.id: None for p in node.parameters}
param_missing_vars = {f.id: [] for f in node.parameters}
if self.verbose:
print("all_params_to_check: %s" % all_params_to_check)
# Order the parameters into the correct sequence
while len(all_params_to_check) > 0:
p = all_params_to_check.pop(0) # pop first off list
if verbose:
print(
" Checking whether parameter: %s with args: %s, value: %s (%s) is sufficiently determined by known vars %s"
% (p.id, p.args, p.value, type(p.value), all_known_vars)
)
all_req_vars = []
if p.value is not None and type(p.value) == str:
all_req_vars.extend(
[
v
for v in get_required_variables_from_expression(p.value)
if p.args is None or v not in p.args
]
)
if p.args is not None:
for arg in p.args:
arg_expr = p.args[arg]
if isinstance(arg_expr, str):
all_req_vars.extend(
[
v
for v in get_required_variables_from_expression(
arg_expr
)
if v not in p.args
]
)
all_known_vars_plus_this = all_known_vars + [p.id]
all_present = [v in all_known_vars_plus_this for v in all_req_vars]
param_missing_vars[p.id] = {
v for v in all_req_vars if v not in all_known_vars
}
if verbose:
print(
" Are all of %s in %s? %s, i.e. %s"
% (
all_req_vars,
all_known_vars_plus_this,
all_present,
all(all_present),
)
)
if all(all_present):
ep = EvaluableParameter(p, self.verbose)
self.evaluable_parameters[p.id] = ep
all_known_vars.append(p.id)
else:
if num_params_remaining[p.id] == len(all_params_to_check):
param_missing_vars = {
p: ", ".join(v) for p, v in param_missing_vars.items()
}
raise ValueError(
"Error! Could not evaluate parameters using known vars. The following vars are missing:\n\t"
+ "\n\t".join(
f"{p}: {v}"
for p, v in param_missing_vars.items()
if len(v) > 0
)
)
else:
num_params_remaining[p.id] = len(all_params_to_check)
all_params_to_check.append(p) # Add back to end of list...
for op in node.output_ports:
rop = EvaluableOutput(op, self.verbose)
self.evaluable_outputs[op.id] = rop
def evaluate(
self,
time_increment: Union[int, float] = None,
array_format: str = FORMAT_DEFAULT,
):
"""
Evaluate the Node for one time-step
Args:
time_increment: The time-increment to use for this evaluation.
array_format: The format to use for arrays.
"""
if self.verbose:
print(
"\n ---------------\n Evaluating Node: %s with %s"
% (self.node.id, [p.id for p in self.node.parameters])
)
curr_params = {}
for eip in self.evaluable_inputs:
i = self.evaluable_inputs[eip].evaluate(
curr_params, array_format=array_format
)
curr_params[eip] = i
# First set params to previous parameter values for use in funcs and states...
for ep in self.evaluable_parameters:
curr_params[ep] = self.evaluable_parameters[ep].get_current_value(
curr_params, array_format=array_format
)
for ef in self.evaluable_functions:
curr_params[ef] = self.evaluable_functions[ef].evaluate(
curr_params, array_format=array_format
)
# Now evaluate and set params to new parameter values for use in output...
for ep in self.evaluable_parameters:
curr_params[ep] = self.evaluable_parameters[ep].evaluate(
curr_params, time_increment=time_increment, array_format=array_format
)
for eop in self.evaluable_outputs:
self.evaluable_outputs[eop].evaluate(curr_params, array_format=array_format)
def get_output(self, id: str = None) -> Union[int, np.ndarray, Tuple]:
"""Get value at output port for given output port's id
Args:
id: Unique identifier of the output port. If None, return a tuple for all output ports.
Returns:
value at the output port. If id is None, return all outputs as a tuple. If there is only
one output, return just its value.
"""
if id is not None:
for rop in self.evaluable_outputs:
if rop == id:
return self.evaluable_outputs[rop].curr_value
else:
outputs = tuple(
self.evaluable_outputs[rop].curr_value for rop in self.evaluable_outputs
)
if len(outputs) == 1:
return outputs[0]
else:
return outputs
class EvaluableGraph:
r"""