Skip to content

Simulation Dynamic

Bases: object

recalculate_algebraic - set to "True" in order to recalculate initial algebraic values "z0" Use this option, if optimizer runs into IDAS_CALC_IC problems and is not able to find "z0" by itself

Source code in src/mopeds/simulation_dynamic.py
 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
class Simulator(object):
    """recalculate_algebraic - set to "True" in order to recalculate initial algebraic values "z0"
    Use this option, if optimizer runs into IDAS_CALC_IC problems and is not able to find "z0" by itself
    """

    supported_integrators = ["idas", "cvodes", "collocation"]

    def __init__(  # noqa: C901
        self,
        model: Model,
        input_time_grid: np.ndarray,
        variable_list: VariableList,
        integrator_name: str = "idas",
        integrator_settings: dict | None = None,
        *,
        use_idas_constraints: bool = None,
        simulate_jac: bool = False,
        recalculate_algebraic: bool = False,
    ) -> None:

        self.logger: logging.Logger = logging.getLogger(__name__)
        self.logger.debug(
            "Creating Simulator object: \n timegrid \n {0} \n".format(input_time_grid)
        )
        if use_idas_constraints is not None:
            warn("IDAS constraints are deprecated", FutureWarning, 2)
        self._created_with_options = get_options()

        self._input_variable_list: VariableList = copy.deepcopy(variable_list)
        self.model: Model = model
        self.model.subsitute_casadi_symbols(self._input_variable_list)

        if integrator_name not in self.supported_integrators:
            raise TypeError(
                f"Provided integrator name {integrator_name} is not supported. Only theese are: {self.supported_integrators}."
            )
        self.__integrator_name: str = integrator_name

        self.__setup_time_grid(input_time_grid)

        scaled_equations_diff = ca.substitute(
            self.model.equations_differential,
            self._input_variable_list.get_casadi_variables(),
            self._input_variable_list.get_scaled_casadi_variables(),
        )
        scaled_equations_diff = ca.cse(
            scaled_equations_diff
            / self._input_variable_list.get_state()._get_scaling_constants()[0]
        )

        if self.model.DAE:
            scaled_equations_alg = ca.cse(
                ca.substitute(
                    self.model.equations_algebraic,
                    self._input_variable_list.get_casadi_variables(),
                    self._input_variable_list.get_scaled_casadi_variables(),
                )
            )

        self.ode_system: dict[str, ca.MX] = {
            "x": self.model.varlist_state(
                self._input_variable_list
            ).get_casadi_variables(),
            "p": ca.vertcat(
                self.model.varlist_independent(
                    self._input_variable_list
                ).get_casadi_variables()
            ),
            "ode": scaled_equations_diff,
        }

        # Tau variable is used to specify a length of iteration step externally, via tau variable
        self.tau: ca.MX = ca.MX.sym("tau")
        self.ode_system_tau: dict[str, ca.MX] = {
            "x": self.model.varlist_state(
                self._input_variable_list
            ).get_casadi_variables(),
            "p": ca.vertcat(
                self.tau,
                self.model.varlist_independent(
                    self._input_variable_list
                ).get_casadi_variables(),
            ),
            "ode": scaled_equations_diff * self.tau,
        }

        if self.model.DAE:
            self.ode_system["alg"] = scaled_equations_alg
            self.ode_system_tau["alg"] = scaled_equations_alg
            self.ode_system["z"] = self.model.varlist_algebraic(
                self._input_variable_list
            ).get_casadi_variables()
            self.ode_system_tau["z"] = self.model.varlist_algebraic(
                self._input_variable_list
            ).get_casadi_variables()

        if self.model.DAE:
            self.function_algebraic_equations = ca.Function(
                "alg_eq_sys",
                [
                    self.ode_system["z"],
                    ca.vertcat(self.ode_system["x"], self.ode_system["p"]),
                ],
                [self.ode_system["alg"]],
                ["x", "p"],
                ["alg"],
            )
            self.rootfinder = ca.rootfinder(
                "DAE_zf_init", "newton", self.function_algebraic_equations
            )

        if integrator_settings is not None:
            self.__integrator_settings = integrator_settings
        else:
            self.__integrator_settings = self.get_default_simulator_settings()

        self.integrator_tau: ca.Function = ca.integrator(
            "integrator_tau",
            self.__integrator_name,
            self.ode_system_tau,
            0,
            1,
            self.__integrator_settings,
        )

        # This integrator is used to output values of algebraic variables at time 0
        # and should be run first to get algebraic variables at time 0 for whole simulation
        self.integrator_tau_with_t0: ca.Function = ca.integrator(
            "integrator_tau_with_t0",
            self.__integrator_name,
            self.ode_system_tau,
            0,
            [0, 1],
            self.__integrator_settings,
        )

        # This list is used for utility functions, like finding steady state
        self._guess_or_value_of_independent_variables: list[float] = []

        # Here all lists from above are initialized
        self.__setup_variables()

        # .factory() method is very expensive so should be requested externally
        if simulate_jac:
            if self.model.DAE is True:
                factory_names = [
                    "xf",
                    "qf",
                    "zf",
                    "adj_x0",
                    "adj_p",
                    "adj_z0",
                    "jac:xf:p",
                ]
            else:
                factory_names = ["xf", "qf", "adj_x0", "adj_p", "jac:xf:p"]

            self.integrator_tau_jac = self.integrator_tau.factory(
                "integrator_tau_jacobian",
                self.integrator_tau.name_in(),
                factory_names,
            )

        # This code is moved here, so this if statement shouldn't be called every simulation
        if self.model.DAE is True:
            if recalculate_algebraic:
                self._call_simulator = self._simulate_dae_calculate_algebraic
            else:
                self._call_simulator = self._simulate_dae_casadi

            self._call_jacobian = self._simulate_jac_dae
        else:
            self._call_simulator = self._simulate_ode
            self._call_jacobian = self._simulate_jac_ode

    @_consistent_scaling_decorator
    def simulate_jac(self) -> dict[str, ca.MX | ca.DM]:
        """Should be used internally for fast calculations. Output of the solution is not scaled"""
        return self._call_jacobian()

    @_consistent_scaling_decorator
    def simulate_fast(self) -> dict[str, ca.MX | ca.DM]:
        """Should be used internally for fast calculations. Output of the solution is not scaled"""
        return self._call_simulator()

    def simulate_sym(self) -> dict[str, ca.MX | ca.DM]:
        warn("simulate_sym is deprecated, use simulate_fast", FutureWarning)
        return self.simulate_fast()

    def select_simulation_result(
        self, result: dict[str, ca.DM], return_var_names: list[str] | None
    ) -> ca.DM | ca.MX:
        """Take result from self.simulate_fast() and return only a subset of results, defined by
        list of variable names"""
        if self.model.DAE:
            offset = len(self.mapping_state_variables)
            result_merged = ca.vcat([result["xf"], result["zf"]])
        else:
            result_merged = result["xf"]

        if return_var_names is not None:
            return_var_index = []
            for var_name in return_var_names:
                try:
                    variable_index = self.mapping_state_variables[var_name]
                except KeyError:
                    variable_index = offset + self.mapping_algebraic_variables[var_name]
                return_var_index.append(variable_index)

            res_selected = result_merged.get(False, return_var_index, ca.Slice())
        else:
            res_selected = None

        return res_selected

    @_consistent_scaling_decorator
    def simulate(
        self,
        *,
        return_var_names: list[str] | None = None,
        unfixed_variables: dict[str, float] | None = None,
        return_varlist: bool = True,
        algebraic: bool = False,
        recalculate_algebraic: bool = True,
    ) -> (dict(str, ca.MX), ca.MX | None, VariableList | None):
        """Wrapper for simulate_fast, that returns scaled results."""
        if recalculate_algebraic and self.model.DAE:
            self.calculate_algebraic_initials(apply_intials=True)

        if return_var_names is not None:
            if self.model.DAE:
                for var_name in self._input_variable_list.get_algebraic().keys():
                    if var_name in return_var_names:
                        algebraic = True
                        break

        res_without0 = self.simulate_fast()
        result_initial = self._simulate_t0()

        res = {"xf": ca.horzcat(result_initial["xf0"], res_without0["xf"])}
        if self.model.DAE:
            res["zf"] = ca.horzcat(result_initial["zf0"], res_without0["zf"])

        if not isinstance(res["xf"], ca.DM):
            if unfixed_variables is None:
                raise ValueError("You need to supply values for unfixed variables")
            else:
                unfixed_symbols = ca.symvar(res["xf"])
                values = []
                for symbol in unfixed_symbols:
                    var_name = symbol.name()
                    values.append(
                        self._input_variable_list[var_name].scale_from_original(
                            unfixed_variables[var_name]
                        )
                    )

                return_values = [res["xf"]]
                if self.model.DAE:
                    return_values.append(res["zf"])

                function = ca.Function("f", unfixed_symbols, return_values)
                final_res = function(*values)
                res_dict = {"xf": final_res[0]}
                if self.model.DAE:
                    res_dict["zf"] = final_res[1]
        else:
            res_dict = res

        res_selected = self.select_simulation_result(res_dict, return_var_names)

        if return_varlist:
            final_varlist = VariableList()
            all_variables = [copy.deepcopy(self._input_variable_list.get_state())]
            res_names = ["xf"]
            if algebraic and self.model.DAE:
                all_variables.append(
                    copy.deepcopy(self._input_variable_list.get_algebraic())
                )
                res_names.append("zf")

            for varlist, res_name in zip(all_variables, res_names):
                for var_name, res_var in zip(
                    self.model.varlist(varlist).keys(), res_dict[res_name].toarray()
                ):
                    if return_var_names is not None:
                        if var_name not in return_var_names:
                            continue

                    var = self._input_variable_list[var_name]
                    new_var = copy.deepcopy(var)
                    new_var.casadi_var = None

                    value = var.scale_to_original(res_var)
                    new_var.set_dataframe_from_value_and_time(
                        value, self.time_grid_relative, self.origin_ts
                    )

                    final_varlist.add_variable(new_var)

            for var in self.model.varlist_independent(
                self._input_variable_list
            ).values():
                if isinstance(var, VariableControlPiecewiseConstant):
                    new_var = copy.deepcopy(self._input_variable_list[var.name])
                    final_varlist.add_variable(new_var)
        else:
            final_varlist = None

        return res_dict, res_selected, final_varlist

    @_consistent_scaling_decorator
    def simulate_sym_unfixed(
        self, unfixed_variables: dict[str, float] = None
    ) -> dict[str, ca.DM]:
        warn(
            "simulate_sym_unfixed is deprecated. Use simulate(unfixed_variables=unfixed_variables))",
            FutureWarning,
        )
        return self.simulate(
            unfixed_variables=unfixed_variables, return_varlist=False, algebraic=True
        )[0]

    @_consistent_scaling_decorator
    def __setup_variables(self) -> None:
        """Setup all important lists for simulator"""
        mapping_independent_variables = {}
        mapping_algebraic_variables = {}
        mapping_state_variables = {}
        index_algebraic = 0
        index_state = 0
        index_independent = 0
        num_time_steps = self.time_grid_relative.shape[0] - 1
        independent_variables = []
        initial_algebraic = []
        initial_state = []

        for var in self.model.varlist(self._input_variable_list).values():
            if isinstance(var, VariableState):
                mapping_state_variables[var.name] = index_state
                index_state += 1
                try:
                    initial_state.append(var.get_value_or_casadi())
                except Exception as e:
                    raise (BadVariableError(var)) from e

            elif isinstance(var, VariableAlgebraic):
                cast(VariableAlgebraic, var)
                mapping_algebraic_variables[var.name] = index_algebraic
                index_algebraic += 1
                initial_algebraic.append(var.scale_from_original(var.guess))

            elif isinstance(var, VariableParameter):
                mapping_independent_variables[var.name] = index_independent
                index_independent += 1
                independent_variable = []
                independent_variable.extend(
                    [var.get_value_or_casadi()] * num_time_steps
                )
                self._guess_or_value_of_independent_variables.append(
                    var.get_value_or_guess()
                )
                independent_variables.append(independent_variable)
            elif isinstance(var, VariableControl):
                mapping_independent_variables[var.name] = index_independent
                index_independent += 1
                if isinstance(var, VariableControlPiecewiseConstant):
                    var_t0 = var.get_variable_at_time_relative(0)
                    self._guess_or_value_of_independent_variables.append(
                        var_t0.get_value_or_guess()
                    )
                    independent_variable = var.get_value_or_casadi(
                        self.time_grid_relative
                    )
                else:
                    independent_variable = []
                    self._guess_or_value_of_independent_variables.append(
                        var.get_value_or_guess()
                    )
                    independent_variable.extend(
                        [var.get_value_or_casadi()] * num_time_steps
                    )

                independent_variables.append(independent_variable)

        self.mapping_independent_variables: dict[str, int] = (
            mapping_independent_variables
        )
        self.mapping_algebraic_variables: dict[str, int] = mapping_algebraic_variables
        self.mapping_state_variables: dict[str, int] = mapping_state_variables
        """ This nested list holds either a value or a casadi variable of
        each independent variable at every timestamp in time_grid.  First it has form:
        [[var1_t0, var1_t1 ...], [var2_t0, var2_t1 ...], [...]]
        Than it's reformed to:
        [[var1_t0, var2_t0 ...], [var1_t1, var2_t1 ...], [...]]
        And finally nested lists are changed to casadi.MX or DM vectors
        [ca.MX(var1_t0, var2_t0 ...), ca.MX(var1_t1, var2_t1 ...), [...]]
        """
        self._independent_variables: list[ca.MX | ca.DM] = list(
            map(list, zip(*independent_variables))
        )
        # List of values of State Variables at time 0
        self._initial_state: list[float] = ca.vcat(initial_state)

        # List of expected or recalculated values of Algebraic Variables at time 0
        # This list is further used in calculations
        self._initial_algebraic: list[float] = initial_algebraic

        # Groups nested lists by time_stamp
        self._initial_algebraic_original = copy.deepcopy(self._initial_algebraic)

        # Transforms nested lists in ca.MX or ca.DM array
        self.contains_unfixed = False
        for index, column in enumerate(self._independent_variables):
            casadi_mx = ca.vcat(column)
            if self.contains_unfixed is False:
                if isinstance(casadi_mx, ca.MX):
                    self.contains_unfixed = True
            self._independent_variables[index] = casadi_mx

    @_consistent_scaling_decorator
    def change_independent_variables(self, ind_variables: dict[str, float]):
        """Use this method to change either Controls or Parameters of the Simulation. ind_variables is a dictionary
        with VariableNames as dict.keys(), and their respective values, as dict.values(). Example:
        {"e0_T": 373, "e0_p": 1e5}"""
        if self.contains_unfixed:
            raise NotImplementedError(
                "All variables should be fixed, to use this method"
            )
        for var_name, var_value in ind_variables.items():
            var = self._input_variable_list[var_name]
            index_var = self.mapping_independent_variables[var_name]
            for index in range(len(self._independent_variables)):
                self._independent_variables[index][index_var] = var.scale_from_original(
                    var_value
                )

    def get_default_simulator_settings(self) -> None:
        """Sane default settings for integrators"""
        if self.__integrator_name == "idas":
            integrator_settings = {
                "expand": True,
                # "calc_ic": False,
                # 'abstol': 1,
                # "reltol": 1,
                # "monitor": "jacF",
                # "print_in": True,
                # "print_out": True,
                # "verbose": True,
                # "print_stats": True,
            }
        elif self.__integrator_name == "cvodes":
            integrator_settings = {
                "expand": True,
                # "linear_multistep_method": "adams",# was used for CVODES
                # "output_t0": False,
                # "use_preconditioner": False,
                # "calc_ic": False,
                # 'abstol': 1e-5,
                # "reltol": 1e-5,
                # "monitor": "jacF",
                # "print_in": True,
                # "print_out": True,
                # "verbose": True,
                # "print_stats": True,
            }
        elif self.__integrator_name == "collocation":
            integrator_settings = {
                "number_of_finite_elements": 3,
                "simplify": True,
                "expand": True,
                "rootfinder": "fast_newton",
                # "monitor": "jacF",
                # "print_in": True,
                # "print_out": True,
                # "verbose": True,
                # "print_stats": True,
            }

        return integrator_settings

    @_consistent_scaling_decorator
    def calculate_steady_state(self) -> dict[str, ca.DM]:
        if self.model.DAE:
            steady_state_rootfinder = ca.Function(
                "steadystate_eq_sys",
                [
                    ca.vertcat(self.ode_system["x"], self.ode_system["z"]),
                    self.ode_system["p"],
                ],
                [ca.vertcat(self.ode_system["ode"], self.ode_system["alg"])],
                ["x", "p"],
                ["ode_alg"],
            )
        else:
            steady_state_rootfinder = ca.Function(
                "steadystate_eq_sys",
                [
                    self.ode_system["x"],
                    self.ode_system["p"],
                ],
                [self.ode_system["ode"]],
                ["x", "p"],
                ["ode"],
            )

        # rf_settings = {
        #     # "calc_ic": False,
        #     # 'abstol': 1,
        #     # "reltol": 1,
        #     # "monitor": "jacF",
        #     # "print_in": True,
        #     # "nlpsol": "ipopt",
        #     # "print_out": True,
        #     # "verbose": True,
        #     # "print_stats": True,
        #     }
        # rf_settings["nlpsol"] = "ipopt"
        # rf_steadystate = ca.rootfinder("stea_state", "nlpsol", steady_state_rootfinder, rf_settings)
        rf_steadystate = ca.rootfinder("stea_state", "newton", steady_state_rootfinder)

        if self.model.DAE:
            res_steadystate = rf_steadystate(
                ca.vertcat(self._initial_state, self._initial_algebraic_original),
                self._guess_or_value_of_independent_variables,
            )
        else:
            res_steadystate = rf_steadystate(
                self._initial_state,
                self._guess_or_value_of_independent_variables,
            )
        return res_steadystate

    @_consistent_scaling_decorator
    def calculate_algebraic_initials(
        self, *, apply_intials: bool = False, analyze: bool = False
    ) -> None:
        if self.model.DAE:
            function = ca.Function(
                "eq_sys",
                [self.ode_system["x"], self.ode_system["z"], self.ode_system["p"]],
                [self.ode_system["ode"], self.ode_system["alg"]],
                ["x", "z", "p"],
                ["ode", "alg"],
            )

            res = self.rootfinder(
                self._initial_algebraic_original,
                ca.vertcat(
                    self._initial_state, self._guess_or_value_of_independent_variables
                ),
            )

            residual_original = function(
                x=self._initial_state,
                z=self._initial_algebraic_original,
                p=self._guess_or_value_of_independent_variables,
            )
            residual_calculated = function(
                x=self._initial_state,
                z=res,
                p=self._guess_or_value_of_independent_variables,
            )

            if analyze:
                abs_diff = self._initial_algebraic_original - res
                rel_diff = ca.fabs(abs_diff) / ca.fabs(self._initial_algebraic_original)

                print("Prints Algebraic Variables, that we changed more than 50%")
                for i in range(abs_diff.shape[0]):
                    if rel_diff[i] > 0.50:
                        print(self.ode_system["z"][i])
                        print(f"Value After {res[i]}")
                        print(f"Value Before {self._initial_algebraic_original[i]}")

                residual_sum_original = ca.sum1(residual_original["alg"])
                residual_sum_calculated = ca.sum1(residual_calculated["alg"])
                print(
                    f"Residual before {residual_sum_original}, after {residual_sum_calculated}."
                )

                # import pandas as pd

                # jac_func = function.jacobian()
                # jac = jac_func(
                #     x=self._initial_state,
                #     z=res,
                #     p=self._guess_or_value_of_independent_variables,
                # )

                # row_names = str(self.ode_system["ode"]).split()
                # row_names.extend(str(self.ode_system["alg"]).split())

                # col_names = str(self.ode_system["x"]).split()
                # col_names.extend(str(self.ode_system["z"]).split())
                # col_names.extend(str(self.ode_system["p"]).split())

                # jac = jac["jac"]
                # df = pd.DataFrame(jac.toarray(), index=row_names, columns=col_names)

            if apply_intials:
                self.logger.debug("Fixed algebraic intials")
                self._initial_algebraic = res

    @_consistent_scaling_decorator
    def analyze_WIP(
        self, state_value: list[float] = None
    ) -> list[dict[str, ca.DM] | list[float]]:
        import mopeds.tools as tools  # noqa: F401

        """ This function was working for previous version of the module."""
        function = ca.Function(
            "eq_sys",
            [self.ode_system["x"], self.ode_system["z"], self.ode_system["p"]],
            [self.ode_system["ode"], self.ode_system["alg"]],
            ["x", "z", "p"],
            ["ode", "alg"],
        )

        algebraic_eqsys = ca.Function(
            "alg_eq_sys",
            [self.ode_system["x"], self.ode_system["z"], self.ode_system["p"]],
            [self.ode_system["alg"]],
            ["x", "z", "p"],
            ["alg"],
        )

        check_initials = function(  # noqa: F841
            x=self._initial_state,
            z=self._initial_algebraic,
            p=self._independent_variables[0],
        )
        jacobian = function.factory(
            "jac_alg",
            function.name_in(),
            ["jac:alg:z", "jac:alg:x", "jac:ode:x", "jac:ode:z"],
        )
        check_jacobian = jacobian(
            x=self._initial_state,
            z=self._initial_algebraic,
            p=self._independent_variables[0],
        )

        check_alg = algebraic_eqsys(
            x=self._initial_state,
            z=self._initial_algebraic,
            p=self._independent_variables[0],
        )

        # should fail by DAE index > 1
        ca.inv(check_jacobian["jac_alg_z"])
        # tools.plot_array(check_jacobian["jac_alg_z"], self.model.varlist_algebraic)
        # tools.plot_array(check_jacobian["jac_ode_z"], self.model.varlist_algebraic)
        # tools.plot_array(check_jacobian["jac_alg_x"], self.model.varlist_state)
        # tools.plot_array(check_jacobian["jac_ode_x"], self.model.varlist_state)

        algebraic_eqsys_rootfinder = ca.Function(
            "alg_eq_sys",
            [
                self.ode_system["z"],
                ca.vertcat(self.ode_system["x"], self.ode_system["p"]),
            ],
            [self.ode_system["alg"]],
            ["x", "p"],
            ["alg"],
        )

        rf = ca.rootfinder("inits", "newton", algebraic_eqsys_rootfinder)
        if state_value is not None:
            res = rf(
                self._initial_algebraic,
                ca.vertcat(state_value, self._independent_variables[0]),
            )
        else:
            res = rf(
                self._initial_algebraic,
                ca.vertcat(self._initial_state, self._independent_variables[0]),
            )

            check_alg = function(  # noqa: 841
                x=self._initial_state, z=res, p=self._independent_variables[0]
            )
        old_initial = self._initial_algebraic
        # self._initial_algebraic = res
        return [res, old_initial]
        # return check_initials, check_jacobian

    @_consistent_scaling_decorator
    def _simulate_jac_dae(self) -> dict[str, ca.DM | ca.MX]:
        """Return dictionary with results "xf" - state,
        "zf" - algebraic, "jac_xf_p" - derivatives.
        """
        prev_time_step = 0
        res_states = []
        res_algebraic = []
        res_jacobian = []
        x_init = self._initial_state
        alg_init = self._initial_algebraic

        for time_step, independent_variables in zip(
            self.time_grid_relative[1:], self._independent_variables
        ):
            res_integration = self.integrator_tau_jac(
                x0=x_init,
                z0=alg_init,
                p=ca.vertcat(time_step - prev_time_step, independent_variables),
            )

            prev_time_step = time_step
            x_init = res_integration["xf"]
            alg_init = res_integration["zf"]

            res_states.append(res_integration["xf"])
            res_algebraic.append(res_integration["zf"])
            res_jacobian.append(res_integration["jac_xf_p"])

        res_states = ca.hcat(res_states)
        res_algebraic = ca.hcat(res_algebraic)
        res_jacobian = ca.hcat(res_jacobian)

        res = {"xf": res_states, "zf": res_algebraic, "jac_xf_p": res_jacobian}
        return res

    @_consistent_scaling_decorator
    def _simulate_jac_ode(self) -> dict[str, ca.DM | ca.MX]:
        """Return dictionary with results "xf" - state,
        "zf" - algebraic, "jac_xf_p" - derivatives.
        """
        prev_time_step = 0
        res_states = []
        res_jacobian = []
        x_init = self._initial_state

        for time_step, independent_variables in zip(
            self.time_grid_relative[1:], self._independent_variables
        ):
            res_integration = self.integrator_tau_jac(
                x0=x_init,
                p=ca.vertcat(time_step - prev_time_step, independent_variables),
            )

            prev_time_step = time_step
            x_init = res_integration["xf"]

            res_states.append(res_integration["xf"])
            res_jacobian.append(res_integration["jac_xf_p"])

        res_states = ca.hcat(res_states)
        res_jacobian = ca.hcat(res_jacobian)

        res = {"xf": res_states, "jac_xf_p": res_jacobian}
        return res

    @_consistent_scaling_decorator
    def _simulate_dae_calculate_algebraic(self) -> dict[str, ca.DM | ca.MX]:
        """Return dictionary with results "xf" - state,
        "zf" - algebraic
        """
        alg_init = self.rootfinder(
            self._initial_algebraic_original,
            ca.vertcat(
                self._initial_state,
                self._independent_variables[0],
            ),
        )
        self._initial_algebraic = alg_init
        res = self._simulate_dae()

        return res

    @_consistent_scaling_decorator
    def _simulate_t0(self) -> dict[str, ca.DM | ca.MX]:
        """Return dictionary with results "xf0" and "zf0" for state and
        algebraic variables at time 0"""
        res = {"xf0": self._initial_state}

        if self.model.DAE:
            prev_time_step = self.time_grid_relative[1]
            res_integration = self.integrator_tau_with_t0(
                x0=self._initial_state,
                z0=self._initial_algebraic,
                p=ca.vertcat(
                    prev_time_step,
                    self._independent_variables[0],
                ),
            )
            init_algebraic = res_integration["zf"][:, 0]
            res["zf0"] = init_algebraic

        return res

    @_consistent_scaling_decorator
    def _simulate_dae_casadi(self) -> dict[str, ca.DM | ca.MX]:
        """Return dictionary with results "xf" - state,
        "zf" - algebraic
        """
        prev_time_step = 0
        res_states = []
        res_algebraic = []
        x_init = self._initial_state
        alg_init = self._initial_algebraic

        num_steps = self.time_grid_relative[1:].shape[0] - 1

        for time_index in range(num_steps + 1):
            time_step = self.time_grid_relative[time_index + 1]
            independent_variables = self._independent_variables[time_index]
            res_integration = self.integrator_tau(
                x0=x_init,
                z0=alg_init,
                p=ca.vertcat(time_step - prev_time_step, independent_variables),
            )

            prev_time_step = time_step
            x_init = res_integration["xf"]
            alg_init = res_integration["zf"]

            res_states.append(res_integration["xf"])
            res_algebraic.append(res_integration["zf"])

        res_states = ca.hcat(res_states)
        res_algebraic = ca.hcat(res_algebraic)

        res = {"xf": res_states, "zf": res_algebraic}
        return res

    @_consistent_scaling_decorator
    def _simulate_ode(self) -> dict[str, ca.DM | ca.MX]:
        """Return dictionary with results "xf" - state,
        "zf" - algebraic
        """
        prev_time_step = 0
        res_states = []
        x_init = self._initial_state

        num_steps = self.time_grid_relative[1:].shape[0] - 1

        for time_index in range(num_steps + 1):
            time_step = self.time_grid_relative[time_index + 1]
            independent_variables = self._independent_variables[time_index]
            res_integration = self.integrator_tau(
                x0=x_init,
                p=ca.vertcat(time_step - prev_time_step, independent_variables),
            )

            prev_time_step = time_step
            x_init = res_integration["xf"]

            res_states.append(res_integration["xf"])

        res_states = ca.hcat(res_states)

        res = {"xf": res_states}
        return res

    @_consistent_scaling_decorator
    def generate_exp_data(
        self,
        algebraic: bool = False,
        recalculate_algebraic: bool = True,
        unfixed_variables: dict[str, float] | None = None,
    ) -> VariableList:
        warn("generate_exp_data deprecated, use simulate()", FutureWarning)
        return self.simulate(
            algebraic=algebraic,
            recalculate_algebraic=recalculate_algebraic,
            unfixed_variables=unfixed_variables,
        )[2]

    def __setup_time_grid(self, time_grid: ArrayLike) -> None:
        """Time_grid provided by user may not take into account piecewise controls.
        Thus it might be needed to expand a time grid."""
        if isinstance(time_grid, ca.MX):
            self.time_grid_relative: np.ndarray = time_grid
        else:
            time_grid = np.asarray(time_grid, dtype=np.float64)
            for var in self._input_variable_list.values():
                if isinstance(var, VariableControlPiecewiseConstant):
                    time_grid = np.append(time_grid, var.time_relative)

            # Values of provided time_grid are rounded to milisecconds
            # in order to avoid timestamps that are very close to each other
            self.time_grid_relative: np.ndarray = np.unique(time_grid)
        self.origin_ts = self._input_variable_list.get_common_origin()
        self.logger.debug(
            "Timegrid modified: \n self.timegrid \n {0} \n".format(
                self.time_grid_relative
            )
        )

__setup_time_grid

__setup_time_grid(time_grid: ArrayLike) -> None

Time_grid provided by user may not take into account piecewise controls. Thus it might be needed to expand a time grid.

Source code in src/mopeds/simulation_dynamic.py
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
def __setup_time_grid(self, time_grid: ArrayLike) -> None:
    """Time_grid provided by user may not take into account piecewise controls.
    Thus it might be needed to expand a time grid."""
    if isinstance(time_grid, ca.MX):
        self.time_grid_relative: np.ndarray = time_grid
    else:
        time_grid = np.asarray(time_grid, dtype=np.float64)
        for var in self._input_variable_list.values():
            if isinstance(var, VariableControlPiecewiseConstant):
                time_grid = np.append(time_grid, var.time_relative)

        # Values of provided time_grid are rounded to milisecconds
        # in order to avoid timestamps that are very close to each other
        self.time_grid_relative: np.ndarray = np.unique(time_grid)
    self.origin_ts = self._input_variable_list.get_common_origin()
    self.logger.debug(
        "Timegrid modified: \n self.timegrid \n {0} \n".format(
            self.time_grid_relative
        )
    )

__setup_variables

__setup_variables() -> None

Setup all important lists for simulator

Source code in src/mopeds/simulation_dynamic.py
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
@_consistent_scaling_decorator
def __setup_variables(self) -> None:
    """Setup all important lists for simulator"""
    mapping_independent_variables = {}
    mapping_algebraic_variables = {}
    mapping_state_variables = {}
    index_algebraic = 0
    index_state = 0
    index_independent = 0
    num_time_steps = self.time_grid_relative.shape[0] - 1
    independent_variables = []
    initial_algebraic = []
    initial_state = []

    for var in self.model.varlist(self._input_variable_list).values():
        if isinstance(var, VariableState):
            mapping_state_variables[var.name] = index_state
            index_state += 1
            try:
                initial_state.append(var.get_value_or_casadi())
            except Exception as e:
                raise (BadVariableError(var)) from e

        elif isinstance(var, VariableAlgebraic):
            cast(VariableAlgebraic, var)
            mapping_algebraic_variables[var.name] = index_algebraic
            index_algebraic += 1
            initial_algebraic.append(var.scale_from_original(var.guess))

        elif isinstance(var, VariableParameter):
            mapping_independent_variables[var.name] = index_independent
            index_independent += 1
            independent_variable = []
            independent_variable.extend(
                [var.get_value_or_casadi()] * num_time_steps
            )
            self._guess_or_value_of_independent_variables.append(
                var.get_value_or_guess()
            )
            independent_variables.append(independent_variable)
        elif isinstance(var, VariableControl):
            mapping_independent_variables[var.name] = index_independent
            index_independent += 1
            if isinstance(var, VariableControlPiecewiseConstant):
                var_t0 = var.get_variable_at_time_relative(0)
                self._guess_or_value_of_independent_variables.append(
                    var_t0.get_value_or_guess()
                )
                independent_variable = var.get_value_or_casadi(
                    self.time_grid_relative
                )
            else:
                independent_variable = []
                self._guess_or_value_of_independent_variables.append(
                    var.get_value_or_guess()
                )
                independent_variable.extend(
                    [var.get_value_or_casadi()] * num_time_steps
                )

            independent_variables.append(independent_variable)

    self.mapping_independent_variables: dict[str, int] = (
        mapping_independent_variables
    )
    self.mapping_algebraic_variables: dict[str, int] = mapping_algebraic_variables
    self.mapping_state_variables: dict[str, int] = mapping_state_variables
    """ This nested list holds either a value or a casadi variable of
    each independent variable at every timestamp in time_grid.  First it has form:
    [[var1_t0, var1_t1 ...], [var2_t0, var2_t1 ...], [...]]
    Than it's reformed to:
    [[var1_t0, var2_t0 ...], [var1_t1, var2_t1 ...], [...]]
    And finally nested lists are changed to casadi.MX or DM vectors
    [ca.MX(var1_t0, var2_t0 ...), ca.MX(var1_t1, var2_t1 ...), [...]]
    """
    self._independent_variables: list[ca.MX | ca.DM] = list(
        map(list, zip(*independent_variables))
    )
    # List of values of State Variables at time 0
    self._initial_state: list[float] = ca.vcat(initial_state)

    # List of expected or recalculated values of Algebraic Variables at time 0
    # This list is further used in calculations
    self._initial_algebraic: list[float] = initial_algebraic

    # Groups nested lists by time_stamp
    self._initial_algebraic_original = copy.deepcopy(self._initial_algebraic)

    # Transforms nested lists in ca.MX or ca.DM array
    self.contains_unfixed = False
    for index, column in enumerate(self._independent_variables):
        casadi_mx = ca.vcat(column)
        if self.contains_unfixed is False:
            if isinstance(casadi_mx, ca.MX):
                self.contains_unfixed = True
        self._independent_variables[index] = casadi_mx

change_independent_variables

change_independent_variables(ind_variables: dict[str, float])

Use this method to change either Controls or Parameters of the Simulation. ind_variables is a dictionary with VariableNames as dict.keys(), and their respective values, as dict.values(). Example:

Source code in src/mopeds/simulation_dynamic.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
@_consistent_scaling_decorator
def change_independent_variables(self, ind_variables: dict[str, float]):
    """Use this method to change either Controls or Parameters of the Simulation. ind_variables is a dictionary
    with VariableNames as dict.keys(), and their respective values, as dict.values(). Example:
    {"e0_T": 373, "e0_p": 1e5}"""
    if self.contains_unfixed:
        raise NotImplementedError(
            "All variables should be fixed, to use this method"
        )
    for var_name, var_value in ind_variables.items():
        var = self._input_variable_list[var_name]
        index_var = self.mapping_independent_variables[var_name]
        for index in range(len(self._independent_variables)):
            self._independent_variables[index][index_var] = var.scale_from_original(
                var_value
            )

get_default_simulator_settings

get_default_simulator_settings() -> None

Sane default settings for integrators

Source code in src/mopeds/simulation_dynamic.py
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
def get_default_simulator_settings(self) -> None:
    """Sane default settings for integrators"""
    if self.__integrator_name == "idas":
        integrator_settings = {
            "expand": True,
            # "calc_ic": False,
            # 'abstol': 1,
            # "reltol": 1,
            # "monitor": "jacF",
            # "print_in": True,
            # "print_out": True,
            # "verbose": True,
            # "print_stats": True,
        }
    elif self.__integrator_name == "cvodes":
        integrator_settings = {
            "expand": True,
            # "linear_multistep_method": "adams",# was used for CVODES
            # "output_t0": False,
            # "use_preconditioner": False,
            # "calc_ic": False,
            # 'abstol': 1e-5,
            # "reltol": 1e-5,
            # "monitor": "jacF",
            # "print_in": True,
            # "print_out": True,
            # "verbose": True,
            # "print_stats": True,
        }
    elif self.__integrator_name == "collocation":
        integrator_settings = {
            "number_of_finite_elements": 3,
            "simplify": True,
            "expand": True,
            "rootfinder": "fast_newton",
            # "monitor": "jacF",
            # "print_in": True,
            # "print_out": True,
            # "verbose": True,
            # "print_stats": True,
        }

    return integrator_settings

select_simulation_result

select_simulation_result(result: dict[str, DM], return_var_names: list[str] | None) -> ca.DM | ca.MX

Take result from self.simulate_fast() and return only a subset of results, defined by list of variable names

Source code in src/mopeds/simulation_dynamic.py
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
def select_simulation_result(
    self, result: dict[str, ca.DM], return_var_names: list[str] | None
) -> ca.DM | ca.MX:
    """Take result from self.simulate_fast() and return only a subset of results, defined by
    list of variable names"""
    if self.model.DAE:
        offset = len(self.mapping_state_variables)
        result_merged = ca.vcat([result["xf"], result["zf"]])
    else:
        result_merged = result["xf"]

    if return_var_names is not None:
        return_var_index = []
        for var_name in return_var_names:
            try:
                variable_index = self.mapping_state_variables[var_name]
            except KeyError:
                variable_index = offset + self.mapping_algebraic_variables[var_name]
            return_var_index.append(variable_index)

        res_selected = result_merged.get(False, return_var_index, ca.Slice())
    else:
        res_selected = None

    return res_selected

simulate

simulate(*, return_var_names: list[str] | None = None, unfixed_variables: dict[str, float] | None = None, return_varlist: bool = True, algebraic: bool = False, recalculate_algebraic: bool = True) -> (dict(str, ca.MX), ca.MX | None, VariableList | None)

Wrapper for simulate_fast, that returns scaled results.

Source code in src/mopeds/simulation_dynamic.py
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
@_consistent_scaling_decorator
def simulate(
    self,
    *,
    return_var_names: list[str] | None = None,
    unfixed_variables: dict[str, float] | None = None,
    return_varlist: bool = True,
    algebraic: bool = False,
    recalculate_algebraic: bool = True,
) -> (dict(str, ca.MX), ca.MX | None, VariableList | None):
    """Wrapper for simulate_fast, that returns scaled results."""
    if recalculate_algebraic and self.model.DAE:
        self.calculate_algebraic_initials(apply_intials=True)

    if return_var_names is not None:
        if self.model.DAE:
            for var_name in self._input_variable_list.get_algebraic().keys():
                if var_name in return_var_names:
                    algebraic = True
                    break

    res_without0 = self.simulate_fast()
    result_initial = self._simulate_t0()

    res = {"xf": ca.horzcat(result_initial["xf0"], res_without0["xf"])}
    if self.model.DAE:
        res["zf"] = ca.horzcat(result_initial["zf0"], res_without0["zf"])

    if not isinstance(res["xf"], ca.DM):
        if unfixed_variables is None:
            raise ValueError("You need to supply values for unfixed variables")
        else:
            unfixed_symbols = ca.symvar(res["xf"])
            values = []
            for symbol in unfixed_symbols:
                var_name = symbol.name()
                values.append(
                    self._input_variable_list[var_name].scale_from_original(
                        unfixed_variables[var_name]
                    )
                )

            return_values = [res["xf"]]
            if self.model.DAE:
                return_values.append(res["zf"])

            function = ca.Function("f", unfixed_symbols, return_values)
            final_res = function(*values)
            res_dict = {"xf": final_res[0]}
            if self.model.DAE:
                res_dict["zf"] = final_res[1]
    else:
        res_dict = res

    res_selected = self.select_simulation_result(res_dict, return_var_names)

    if return_varlist:
        final_varlist = VariableList()
        all_variables = [copy.deepcopy(self._input_variable_list.get_state())]
        res_names = ["xf"]
        if algebraic and self.model.DAE:
            all_variables.append(
                copy.deepcopy(self._input_variable_list.get_algebraic())
            )
            res_names.append("zf")

        for varlist, res_name in zip(all_variables, res_names):
            for var_name, res_var in zip(
                self.model.varlist(varlist).keys(), res_dict[res_name].toarray()
            ):
                if return_var_names is not None:
                    if var_name not in return_var_names:
                        continue

                var = self._input_variable_list[var_name]
                new_var = copy.deepcopy(var)
                new_var.casadi_var = None

                value = var.scale_to_original(res_var)
                new_var.set_dataframe_from_value_and_time(
                    value, self.time_grid_relative, self.origin_ts
                )

                final_varlist.add_variable(new_var)

        for var in self.model.varlist_independent(
            self._input_variable_list
        ).values():
            if isinstance(var, VariableControlPiecewiseConstant):
                new_var = copy.deepcopy(self._input_variable_list[var.name])
                final_varlist.add_variable(new_var)
    else:
        final_varlist = None

    return res_dict, res_selected, final_varlist

simulate_fast

simulate_fast() -> dict[str, ca.MX | ca.DM]

Should be used internally for fast calculations. Output of the solution is not scaled

Source code in src/mopeds/simulation_dynamic.py
206
207
208
209
@_consistent_scaling_decorator
def simulate_fast(self) -> dict[str, ca.MX | ca.DM]:
    """Should be used internally for fast calculations. Output of the solution is not scaled"""
    return self._call_simulator()

simulate_jac

simulate_jac() -> dict[str, ca.MX | ca.DM]

Should be used internally for fast calculations. Output of the solution is not scaled

Source code in src/mopeds/simulation_dynamic.py
201
202
203
204
@_consistent_scaling_decorator
def simulate_jac(self) -> dict[str, ca.MX | ca.DM]:
    """Should be used internally for fast calculations. Output of the solution is not scaled"""
    return self._call_jacobian()