-
Notifications
You must be signed in to change notification settings - Fork 40
8000
/
Copy pathmaster.pyx
1854 lines (1553 loc) · 88.9 KB
/
master.pyx
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2010 Modelon AB
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# distutils: define_macros=NPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION
import fnmatch
import sys
import time
import warnings
from collections import OrderedDict
from timeit import default_timer as timer
from cpython cimport bool
from cython.parallel import prange, parallel
import numpy as np
cimport numpy as np
import scipy as sp
import scipy.sparse as sps
import scipy.optimize as spopt
from pyfmi.common.algorithm_drivers import OptionBase, InvalidAlgorithmOptionException, AssimuloSimResult
from pyfmi.common.io import get_result_handler, ResultHandler
from pyfmi.common.core import TrajectoryLinearInterpolation, TrajectoryUserFunction
cimport pyfmi.fmil_import as FMIL
cimport pyfmi.fmil2_import as FMIL2
cimport pyfmi.fmi2 as FMI2
from pyfmi.fmi2 import FMI2_CONTINUOUS, FMI2_INPUT, FMI2_OUTPUT
from pyfmi.fmi_util import Graph
from pyfmi.exceptions import FMUException, InvalidFMUException
IF WITH_OPENMP:
cimport openmp
DEF SERIAL = 0
DEF PARALLEL = 1
cdef reset_models(list models):
for model in models:
model.reset()
cdef perform_do_step(list models, dict time_spent, FMIL2.fmi2_import_t** model_addresses, double cur_time, double step_size, bool new_step, int setting):
if setting == SERIAL:
perform_do_step_serial(models, time_spent, cur_time, step_size, new_step)
else:
perform_do_step_parallel(models, model_addresses, len(models), cur_time, step_size, new_step)
cdef perform_do_step_serial(list models, dict time_spent, double cur_time, double step_size, bool new_step):
"""
Perform a do step on all the models.
"""
cdef double time_start = 0.0
cdef int status = 0
for model in models:
time_start = timer()
status = model.do_step(cur_time, step_size, new_step)
time_spent[model] += timer() - time_start
if status != 0:
raise FMUException("The step failed for model %s at time %f. See the log for more information. Return flag %d."%(model.get_name(), cur_time, status))
cdef perform_do_step_parallel(list models, FMIL2.fmi2_import_t** model_addresses, int n, double cur_time, double step_size, int new_step):
"""
Perform a do step on all the models.
"""
cdef int i, status = 0
# cdef int num_threads
# cdef int id
# cdef double time
for i in prange(n, nogil=True, schedule="dynamic", chunksize=1):
#for i in prange(n, nogil=True, schedule="dynamic"):
#num_threads = openmp.omp_get_num_threads()
#id = openmp.omp_get_thread_num()
#time = openmp.omp_get_wtime()
status |= FMIL2.fmi2_import_do_step(model_addresses[i], cur_time, step_size, new_step)
#time = openmp.omp_get_wtime() -time
#printf("Time: %f (%d), %d, %d, Elapsed Time: %f \n",cur_time, i, num_threads, id, time)
if status != 0:
raise FMUException("The simulation failed. See the log for more information. Return flag %d."%status)
#Update local times in models
for model in models:
model.time = cur_time + step_size
cdef enter_initialization_mode(list models, double start_time, double final_time, object opts, dict time_spent):
cdef int status
for model in models:
time_start = timer()
model.setup_experiment(tolerance=opts["local_rtol"], start_time=start_time, stop_time=final_time)
try:
status = model.enter_initialization_mode()
time_spent[model] += timer() - time_start
except FMUException:
print("The model, '" + model.get_name() + "' failed to enter initialization mode. ")
cdef exit_initialization_mode(list models, dict time_spent):
for model in models:
time_start = timer()
model.exit_initialization_mode()
time_spent[model] += timer() - time_start
"""
cdef perform_initialize(list models, double start_time, double final_time, object opts):
#
Initialize all the models.
#
for model in models:
model.setup_experiment(tolerance=opts["local_rtol"], start_time=start_time, stop_time=final_time)
model.initialize()
"""
#cdef get_fmu_states(list models):
cdef get_fmu_states(list models, dict states_dict = None):
"""
Get the FMU states for all the models
"""
if states_dict is None:
return {model: model.get_fmu_state() for model in models}
else:
for model in states_dict.keys():
states_dict[model] = model.get_fmu_state(states_dict[model])
return states_dict
cdef set_fmu_states(dict states_dict):
"""
Sets the FMU states for all the models
"""
for model in states_dict.keys():
model.set_fmu_state(states_dict[model])
cdef free_fmu_states(dict states_dict):
"""
Free the FMU states for all the models
"""
for model in states_dict.keys():
model.free_fmu_state(states_dict[model])
cdef store_communication_point(object models_dict):
for model in models_dict.keys():
models_dict[model]["result"].integration_point()
cdef finalize_result_objects(object models_dict):
for model in models_dict.keys():
models_dict[model]["result"].simulation_end()
def init_f(y, master):
y = y.reshape(-1, 1)
u = master.L.dot(y)
master.set_connection_inputs(u)
temp_y = y - master.get_connection_outputs()
return temp_y.flatten()
def init_f_block(ylocal, master, block):
y = np.zeros((master._len_outputs))
y[block["global_outputs_mask"]] = ylocal
y = y.reshape(-1,1)
ytmp = np.zeros((master._len_outputs))
u = master.L.dot(y.reshape(-1,1))
for model in block["inputs"].keys(): #Set the inputs
master.set_specific_connection_inputs(model, block["inputs_mask"][model], u)
for model in block["outputs"].keys(): #Get the outputs
master.get_specific_connection_outputs(model, block["outputs_mask"][model], ytmp)
res = y - ytmp.reshape(-1,1)
return res.flatten()[block["global_outputs_mask"]]
def init_jac(y, master):
y = y.reshape(-1, 1)
u = master.L.dot(y)
master.set_connection_inputs(u)
D = master.compute_global_D()
DL = D.dot(master.L)
return np.eye(*DL.shape) - DL
class MasterAlgOptions(OptionBase):
"""
Options for solving coupled FMI 2 CS FMUs.
Options::
step_size --
Specfies the global step-size to be used for simulating
the coupled system.
Default: 0.01
initialize --
If set to True, the initializing algorithm defined in the FMU models
are invoked, otherwise it is assumed the user have manually initialized
all models.
Default is True.
block_initialization --
If set to True, the initialization algorithm computes the evaluation
order of the FMUs and tries to resolve algebraic loops by this
evaluation order.
Default is False.
extrapolation_order --
Defines the extrapolation used in the simulation.
Default is 0 (constant extrapolation).
smooth_coupling --
Defines if the extrapolation should be smoothen, i.e. the input
values are adapted so that they are C^0 instead of C^(-1) in case
extrapolation_order is > 0.
Default is True
linear_correction --
Defines if linear correction should be used during the simulation.
Note that this increases the simulation robustness in case of
algebraic loops.
Default is False
execution --
Defines if the models are to be evaluated in parallel (note that it
is not an algorithm change, just an evaluation execution within
the same algorithm). Note that it requires that PyFMI has been
installed with OpenMP.
Default is serial
num_threads --
Defines the number of threads used when the execution is set
to parallel.
Default: Number of cores / OpenMP environment variable
error_controlled --
Defines if the algorithm should adapt the step-size during
the simulation. Note requires that all FMUs support save/get
state.
Default: False
atol --
Defines the absolute tolerance used when an error controlled
simulation is performed.
Default: 1e-4
rtol --
Defines the relative tolerance used when an error controlled
simulation is performed.
Default: 1e-4
maxh --
Defines the maximum step-size allowed to be used together
with an error controlled simulation.
Default: 0.0 (i.e. inactive)
local_rtol --
Defines the relative tolerance that will be provided to the
connected FMUs during initialization of the underlying
models. Note, only have an effect if 'initialize' is set to
True.
Default: 1e-6
result_file_name --
Specifies the name of the file where the simulation result is
written. Note that there should be one name for each model and
the names of the files should be provided in a dict with the
model as 'key' and the name of the file as 'value' in the
dict.
Default: Model name + "_result." + filetype
result_max_size --
Maximum size of the stored result (in bytes). This is not a hard limit, the
actual size will be slightly larger to account for that the result need to
be consistent. Note that the maximum size is per result file.
Default: 2e9 (2GB)
result_handling --
Specifies how the result should be handled. Either stored to
file or stored in memory. One can also use custom handlers.
Available options: "file", "binary", "memory", "csv", "custom"
Default: "binary"
result_handler --
The handler for the result. Depending on the option in
result_handling this either defaults to ResultHandlerFile
or ResultHandlerMemory. If result_handling custom is chosen
This MUST be provided and be a dictionary with model name as 'key'
and the ResultHandler instance for that model as 'value'.
Default: None
filter --
A filter for choosing which model variables to actually store
result for. The syntax can be found in
http://en.wikipedia.org/wiki/Glob_%28programming%29 . An
example is filter = "*der" , stor all variables ending with
'der'. Can also be a list. Note that there should be one
filter for each model.
Default: None
logging --
If True, store additional debug data during the simulation.
The option is currently only useful for internal purposes.
Default: False
store_step_before_update --
If True, store additionally the values in the underlying
FMUs to the result file before data has been exchange
between the connected models. The values will always be
stored after data has been exchanged between the connected
models.
Default: False
block_initialization_type --
Specifies which algorithm should be used to find the best
grouping of input/outputs. This only has an effect when the
option 'block_initialization' is set to True. The available
values are: "greedy", "simply", "grouping". Each has their
pros and cons, for best performance, please test.
Default: "greedy"
force_finite_difference_outputs --
If set, forces the use of finite difference (first order)
between communication points. I.e. instead of using the
underlying models capabilities to compute derivatives of
outputs, finite differences between communication points
will be used.
Default: False
result_downsampling_factor --
int > 0, only save solution to result every
<result_downsampling_factor>-th communication point.
Start & end point are always included.
Affects results storing from the 'store_step_before_update' option.
Usage with 'error_controlled' = True is not supported.
Example: If set to 2: Result contains only every other communication point.
Default: 1 (no downsampling)
"""
def __init__(self, master, *args, **kw):
_defaults= {
"initialize" : True,
"local_rtol" : 1e-6,
"rtol" : 1e-4,
"atol" : 1e-4,
"step_size" : 0.01,
"maxh" : 0.0,
"filter" : dict((model,None) for model in master.models),
"result_file_name" : dict((model,None) for model in master.models),
"result_handling" : "binary",
"result_handler" : None,
"result_max_size" : 2*10**9,
"linear_correction" : False,
"error_controlled"
10000
; : False if master.support_storing_fmu_states else False,
"logging" : False,
"extrapolation_order" : 0, #Constant
"store_step_before_update" : False,
"smooth_coupling" : True,
"execution" : "serial",
"block_initialization" : False,
"block_initialization_type" : "greedy",
"experimental_block_initialization_order" : None,
"experimental_output_derivative": False,
"experimental_finite_difference_D": False,
"experimental_output_solve":False,
"force_finite_difference_outputs": False,
"num_threads":None,
'result_downsampling_factor': 1
}
super(MasterAlgOptions,self).__init__(_defaults)
self._update_keep_dict_defaults(*args, **kw)
cdef class Master:
cdef public list connections, models
cdef public dict statistics, models_id_mapping
cdef public object opts
cdef public object models_dict, L, L_discrete
cdef public object _ident_matrix
cdef public object y_prev, yd_prev, input_traj
cdef public object DL_prev
cdef public int algebraic_loops, storing_fmu_state
cdef public int error_controlled, linear_correction
cdef public int _support_directional_derivatives, _support_storing_fmu_states, _support_interpolate_inputs, _max_output_derivative_order
cdef double rtol, atol, current_step_size
cdef public object y_m1, yd_m1, u_m1, ud_m1, udd_m1
cdef FMIL2.fmi2_import_t** fmu_adresses
cdef public int _len_inputs, _len_inputs_discrete, _len_outputs, _len_outputs_discrete
cdef public int _len_derivatives
cdef public list _storedDrow, _storedDcol
cdef public np.ndarray _array_one
cdef public object _D
cdef public dict elapsed_time
cdef public dict elapsed_time_init
cdef public dict _error_data
cdef public int _display_counter
cdef public object _display_progress
cdef public double _time_integration_start
cdef public int result_downsampling_factor
cdef public int _step_number
cdef public bool _last_step
def __init__(self, models, connections):
"""
Initializes the master algorithm.
Parameters::
models
- A list of models that are to be simulated.
Needs to be a subclass of FMUModelCS.
connection
- Specifies the connection between the models.
- model_begin.variable -> model_accept.variable
[(model_source,"beta",model_destination,"y"),(...)]
"""
if not isinstance(models, list):
raise FMUException("The models should be provided as a list.")
for model in models:
if not isinstance(model, FMI2.FMUModelCS2):
# TODO: Should be a "not supported" Exception instead?
raise InvalidFMUException("The Master algorithm currently only supports CS 2.0 FMUs.")
self.fmu_adresses = <FMIL2.fmi2_import_t**>FMIL.malloc(len(models)*sizeof(FMIL2.fmi2_import_t*))
self.connections = connections
self.models = models
self.models_dict = OrderedDict((model,{"model": model, "result": None, "external_input": None,
"local_input": [], "local_input_vref": [], "local_input_len": 0,
"local_input_discrete": [], "local_input_discrete_vref": [], "local_input_discrete_len": 0,
"local_state": [], "local_state_vref": [],
"local_derivative": [], "local_derivative_vref": [],
"local_output": [], "local_output_vref": [], "local_output_len": 0,
"local_output_discrete": [], "local_output_discrete_vref": [], "local_output_discrete_len": 0,
"local_output_range_array": None,
"direct_dependence": []}) for model in models)
self.models_id_mapping = {str(id(model)): model for model in models}
self.elapsed_time = {model: 0.0 for model in models}
self.elapsed_time_init = {model: 0.0 for model in models}
self.elapsed_time["result_handling"] = 0.0
self._display_counter = 1
self._display_progress = True
self.statistics = {}
self.statistics["nsteps"] = 0
self.statistics["nreject"] = 0
#Initialize internal variables
self._support_directional_derivatives = -1
self._support_storing_fmu_states = -1
self._support_interpolate_inputs = -1
self._max_output_derivative_order = -1
self._len_inputs = 0
self._len_outputs = 0
self._len_inputs_discrete = 0
self._len_outputs_discrete = 0
self._len_derivatives = 0
self._array_one = np.array([1.0])
self._D = None
self.error_controlled = 0
self.linear_correction = 1
self.check_support_storing_fmu_state()
self.connection_setup(connections)
self.verify_connection_variables()
self.check_algebraic_loops()
self.set_model_order()
self.define_connection_matrix()
self.y_prev = None
self.input_traj = None
self._ident_matrix = sps.eye(self._len_inputs, self._len_outputs, format="csr") #y = Cx + Du , u = Ly -> DLy DL[inputsXoutputs]
self._error_data = {"time":[], "error":[], "step-size":[], "rejected":[]}
def __del__(self):
FMIL.free(self.fmu_adresses)
cdef set_last_y(self, np.ndarray y):
self.y_m1 = y.copy()
cdef get_last_y(self):
return self.y_m1
cdef set_last_yd(self, np.ndarray yd):
self.yd_m1 = yd.copy() if yd is not None else None
cdef get_last_yd(self):
return self.yd_m1
cdef set_last_us(self, np.ndarray u, np.ndarray ud=None, np.ndarray udd=None):
self.u_m1 = u.copy()
self.ud_m1 = ud.copy() if ud is not None else None
self.udd_m1 = udd.copy() if udd is not None else None
cdef get_last_us(self):
return self.u_m1, self.ud_m1, self.udd_m1
cdef set_current_step_size(self, double step_size):
self.current_step_size = step_size
cdef double get_current_step_size(self):
return self.current_step_size
def report_solution(self, double cur_time):
if self.error_controlled:
store_communication_point(self.models_dict)
else:
# _step_number starts at 0
if ((self._step_number + 1) % self.result_downsampling_factor == 0) or self._last_step:
store_communication_point(self.models_dict)
if self._display_progress:
if ( timer() - self._time_integration_start) > self._display_counter*10:
self._display_counter += 1
sys.stdout.write(" Simulation time: %e" % cur_time)
sys.stdout.write('\r')
sys.stdout.flush()
def set_model_order(self):
i = 0
for model in self.models_dict.keys():
self.models_dict[model]["order"] = i
i = i+1
for model in self.models_dict.keys():
self.models[self.models_dict[model]["order"]] = model
def copy_fmu_addresses(self):
for model in self.models_dict.keys():
self.fmu_adresses[self.models_dict[model]["order"]] = (<FMI2.FMUModelCS2>model)._fmu
def define_connection_matrix(self):
cdef list data = []
cdef list row = []
cdef list col = []
cdef list data_discrete = []
cdef list row_discrete = []
cdef list col_discrete = []
cdef int len_connections = 0
cdef int len_connections_discrete = 0
start_index_inputs = 0
start_index_outputs = 0
start_index_inputs_discrete = 0
start_index_outputs_discrete = 0
start_index_states = 0
start_index_derivatives = 0
for model in self.models_dict.keys():
self.models_dict[model]["global_index_inputs"] = start_index_inputs
self.models_dict[model]["global_index_outputs"] = start_index_outputs
self.models_dict[model]["global_index_inputs_discrete"] = start_index_inputs_discrete
self.models_dict[model]["global_index_outputs_discrete"] = start_index_outputs_discrete
self.models_dict[model]["global_index_states"] = start_index_states
self.models_dict[model]["global_index_derivatives"] = start_index_derivatives
start_index_inputs += len(self.models_dict[model]["local_input"])
start_index_outputs += len(self.models_dict[model]["local_output"])
start_index_inputs_discrete += len(self.models_dict[model]["local_input_discrete"])
start_index_outputs_discrete += len(self.models_dict[model]["local_output_discrete"])
start_index_states += len(self.models_dict[model]["local_state"])
start_index_derivatives += len(self.models_dict[model]["local_derivative"])
for connection in self.connections:
src = connection[0]; src_var = connection[1]
dst = connection[2]; dst_var = connection[3]
if connection[0].get_variable_variability(connection[1]) == FMI2_CONTINUOUS and \
connection[2].get_variable_variability(connection[3]) == FMI2_CONTINUOUS:
data.append(1)
row.append(self.models_dict[dst]["global_index_inputs"]+self.models_dict[dst]["local_input"].index(dst_var))
col.append(self.models_dict[src]["global_index_outputs"]+self.models_dict[src]["local_output"].index(src_var))
len_connections = len_connections + 1
else:
data_discrete.append(1)
row_discrete.append(self.models_dict[dst]["global_index_inputs_discrete"]+self.models_dict[dst]["local_input_discrete"].index(dst_var))
col_discrete.append(self.models_dict[src]["global_index_outputs_discrete"]+self.models_dict[src]["local_output_discrete"].index(src_var))
len_connections_discrete = len_connections_discrete + 1
self.L = sps.csr_matrix((data, (row, col)), (len_connections,len_connections), dtype=np.float64)
self.L_discrete = sps.csr_matrix((data_discrete, (row_discrete, col_discrete)), (len_connections_discrete,len_connections_discrete), dtype=np.float64)
cpdef compute_global_D(self):
cdef list data = []
cdef list row = []
cdef list col = []
cdef int i, nlocal, status
for model in self.models_dict.keys():
nlocal = self.models_dict[model]["local_input_len"]
#v = [0.0]*nlocal
for i in range(nlocal):
#local_D = model.get_directional_derivative([self.models_dict[model]["local_input_vref"][i]],self.models_dict[model]["local_output_vref"], [1.0])
local_D = np.empty(self.models_dict[model]["local_output_len"])
#status = (<FMI2.FMUModelCS2>model)._get_directional_derivative(np.array([self.models_dict[model]["local_input_vref"][i]]),self.models_dict[model]["local_output_vref_array"], self._array_one, local_D)
if self.opts["experimental_finite_difference_D"]:
up = (<FMI2.FMUModelCS2>model).get_real(self.models_dict[model]["local_input_vref_array"][i:i+1])
eps = max(abs(up), 1.0)
yp = (<FMI2.FMUModelCS2>model).get_real(self.models_dict[model]["local_output_vref_array"])
(<FMI2.FMUModelCS2>model).set_real(self.models_dict[model]["local_input_vref_array"][i:i+1], up+eps)
local_D = ((<FMI2.FMUModelCS2>model).get_real(self.models_dict[model]["local_output_vref_array"]) - yp)/eps
(<FMI2.FMUModelCS2>model).set_real(self.models_dict[model]["local_input_vref_array"][i:i+1], up)
else:
status = (<FMI2.FMUModelCS2>model)._get_directional_derivative(self.models_dict[model]["local_input_vref_array"][i:i+1],self.models_dict[model]["local_output_vref_array"], self._array_one, local_D)
if status != 0: raise FMUException("Failed to get the directional derivatives while computing the global D matrix.")
data.extend(local_D)
if self._storedDrow is None and self._storedDcol is None:
col.extend([self.models_dict[model]["global_index_inputs"]+i]*len(local_D))
#row.extend(np.array([self.models_dict[model]["global_index_outputs"]]*self.models_dict[model]["local_output_len"])+np.array(range(self.models_dict[model]["local_output_len"])))
row.extend(np.array([self.models_dict[model]["global_index_outputs"]]*self.models_dict[model]["local_output_len"])+self.models_dict[model]["local_output_range_array"])
if self._storedDrow is None and self._storedDcol is None:
self._storedDrow = row
self._storedDcol = col
else:
row = self._storedDrow
col = self._storedDcol
if self._D is None:
self._D = sps.csr_matrix((data, (row, col)))#, (len(col),len(row)))
else:
self._D.data = np.array(data, dtype=np.float64)
return self._D
def compute_global_C(self):
cdef list data = []
cdef list row = []
cdef list col = []
for model in self.models_dict.keys():
if model.get_generation_tool() != "JModelica.org":
return None
v = [0.0]*len(self.models_dict[model]["local_state_vref"])
for i in range(len(v)):
local_C = model.get_directional_derivative([self.models_dict[model]["local_state_vref"][i]],self.models_dict[model]["local_output_vref"], [1.0])
data.extend(local_C)
col.extend([self.models_dict[model]["global_index_states"]+i]*len(local_C))
row.extend(np.array([self.models_dict[model]["global_index_outputs"]]*len(self.models_dict[model]["local_output_vref"]))+np.array(range(len(self.models_dict[model]["local_output_vref"]))))
return sps.csr_matrix((data, (row, col)))
def compute_global_A(self):
cdef list data = []
cdef list row = []
cdef list col = []
for model in self.models_dict.keys():
if model.get_generation_tool() != "JModelica.org":
return None
v = [0.0]*len(self.models_dict[model]["local_state_vref"])
for i in range(len(v)):
local_A = model.get_directional_derivative([self.models_dict[model]["local_state_vref"][i]],self.models_dict[model]["local_derivative_vref"], [1.0])
data.extend(local_A)
col.extend([self.models_dict[model]["global_index_states"]+i]*len(local_A))
row.extend(np.array([self.models_dict[model]["global_index_derivatives"]]*len(self.models_dict[model]["local_derivative_vref"]))+np.array(range(len(self.models_dict[model]["local_derivative_vref"]))))
return sps.csr_matrix((data, (row, col)))
def compute_global_B(self):
cdef list data = []
cdef list row = []
cdef list col = []
for model in self.models_dict.keys():
if model.get_generation_tool() != "JModelica.org":
return None
v = [0.0]*len(self.models_dict[model]["local_input_vref"])
for i in range(len(v)):
local_B = model.get_directional_derivative([self.models_dict[model]["local_input_vref"][i]],self.models_dict[model]["local_derivative_vref"], [1.0])
data.extend(local_B)
col.extend([self.models_dict[model]["global_index_inputs"]+i]*len(local_B))
row.extend(np.array([self.models_dict[model]["global_index_derivatives"]]*len(self.models_dict[model]["local_derivative_vref"]))+np.array(range(len(self.models_dict[model]["local_derivative_vref"]))))
return sps.csr_matrix((data, (row, col)))
def connection_setup(self, connections):
for connection in connections:
if connection[0].get_variable_variability(connection[1]) == FMI2_CONTINUOUS and \
connection[2].get_variable_variability(connection[3]) == FMI2_CONTINUOUS:
self.models_dict[connection[0]]["local_output"].append(connection[1])
self.models_dict[connection[0]]["local_output_vref"].append(connection[0].get_variable_valueref(connection[1]))
self.models_dict[connection[2]]["local_input"].append(connection[3])
self.models_dict[connection[2]]["local_input_vref"].append(connection[2].get_variable_valueref(connection[3]))
else:
self.models_dict[connection[0]]["local_output_discrete"].append(connection[1])
self.models_dict[connection[0]]["local_output_discrete_vref"].append(connection[0].get_variable_valueref(connection[1]))
self.models_dict[connection[2]]["local_input_discrete"].append(connection[3])
self.models_dict[connection[2]]["local_input_discrete_vref"].append(connection[2].get_variable_valueref(connection[3]))
for model in self.models_dict.keys():
self.models_dict[model]["local_input_len"] = len(self.models_dict[model]["local_input"])
self.models_dict[model]["local_output_len"] = len(self.models_dict[model]["local_output"])
self.models_dict[model]["local_input_discrete_len"] = len(self.models_dict[model]["local_input_discrete"])
self.models_dict[model]["local_output_discrete_len"] = len(self.models_dict[model]["local_output_discrete"])
self.models_dict[model]["local_output_range_array"] = np.array(range(self.models_dict[model]["local_output_len"]))
self.models_dict[model]["local_output_vref_array"] = np.array(self.models_dict[model]["local_output_vref"], dtype=np.uint32)
self.models_dict[model]["local_input_vref_array"] = np.array(self.models_dict[model]["local_input_vref"], dtype=np.uint32)
self.models_dict[model]["local_input_vref_ones"] = np.ones(self.models_dict[model]["local_input_len"], dtype=np.int32)
self.models_dict[model]["local_input_vref_twos"] = 2*np.ones(self.models_dict[model]["local_input_len"], dtype=np.int32)
self.models_dict[model]["local_output_vref_ones"] = np.ones(self.models_dict[model]["local_output_len"], dtype=np.int32)
self._len_inputs += self.models_dict[model]["local_input_len"]
self._len_outputs += self.models_dict[model]["local_output_len"]
self._len_inputs_discrete += self.models_dict[model]["local_input_discrete_len"]
self._len_outputs_discrete += self.models_dict[model]["local_output_discrete_len"]
if model.get_generation_tool() == "JModelica.org":
self.models_dict[model]["local_state"] = model.get_states_list().keys()
self.models_dict[model]["local_state_vref"] = [var.value_reference for var in model.get_states_list().values()]
self.models_dict[model]["local_derivative"] = model.get_derivatives_list().keys()
self.models_dict[model]["local_derivative_vref"] = [var.value_reference for var in model.get_derivatives_list().values()]
self.models_dict[model]["local_derivative_vref_array"] = np.array(self.models_dict[model]["local_derivative_vref"], dtype=np.uint32)
self.models_dict[model]["local_derivative_len"] = len(self.models_dict[model]["local_derivative"])
self._len_derivatives += self.models_dict[model]["local_derivative_len"]
def verify_connection_variables(self):
for model in self.models_dict.keys():
for output in self.models_dict[model]["local_output"]:
if model.get_variable_causality(output) != FMI2_OUTPUT:
raise FMUException("The connection variable " + output + " in model " + model.get_name() + " is not an output. ")
for output in self.models_dict[model]["local_output_discrete"]:
if model.get_variable_causality(output) != FMI2_OUTPUT:
raise FMUException("The connection variable " + output + " in model " + model.get_name() + " is not an output. ")
for input in self.models_dict[model]["local_input"]:
if model.get_variable_causality(input) != FMI2_INPUT:
raise FMUException("The connection variable " + input + " in model " + model.get_name() + " is not an input. ")
for input in self.models_dict[model]["local_input_discrete"]:
if model.get_variable_causality(input) != FMI2_INPUT:
raise FMUException("The connection variable " + input + " in model " + model.get_name() + " is not an input. ")
def check_algebraic_loops(self):
"""
Simplified check for algebraic loops in simulation mode due to
the limited capacity of solving the loops
"""
self.algebraic_loops = 0
for model in self.models_dict.keys():
output_state_dep, output_input_dep = model.get_output_dependencies()
for local_output in self.models_dict[model]["local_output"]:
output_input_dep_dict = {key: i for i, key in enumerate(output_input_dep[local_output])}
for local_input in self.models_dict[model]["local_input"]:
if local_input in output_input_dep_dict:
self.models_dict[model]["direct_dependence"].append((local_input, local_output))
self.algebraic_loops = 1
#break
if self.algebraic_loops:
pass
#break
if self.algebraic_loops:
pass
#break
if self.algebraic_loops:
for model in self.models_dict.keys():
if model.get_capability_flags()["providesDirectionalDerivatives"] is False:
warnings.warn("The model, " + model.get_name() + ", does not support "
"directional derivatives which is necessary in-case of an algebraic loop. The simulation might become unstable...")
return self.algebraic_loops
def check_support_storing_fmu_state(self):
self.storing_fmu_state = 1
for model in self.models_dict.keys():
if model.get_capability_flags()["canGetAndSetFMUstate"] is False:
self.storing_fmu_state= 0
break
return self.storing_fmu_state
cpdef np.ndarray get_connection_outputs(self):
cdef int i, index, index_start, index_end
cdef np.ndarray y = np.empty((self._len_outputs))
for model in self.models:
index_start = self.models_dict[model]["global_index_outputs"]
index_end = index_start + self.models_dict[model]["local_output_len"]
local_output_vref_array = (<FMI2.FMUModelCS2>model).get_real(self.models_dict[model]["local_output_vref_array"])
for i, index in enumerate(range(index_start, index_end)):
y[index] = local_output_vref_array[i].item()
return y.reshape(-1,1)
cpdef np.ndarray get_connection_outputs_discrete(self):
cdef int i, index, index_start, index_end
cdef np.ndarray y = np.empty((self._len_outputs_discrete))
for model in self.models:
index_start = self.models_dict[model]["global_index_outputs_discrete"]
index_end = index_start + self.models_dict[model]["local_output_discrete_len"]
local_output_discrete = model.get(self.models_dict[model]["local_output_discrete"])
for i, index in enumerate(range(index_start, index_end)):
y[index] = local_output_discrete[i].item()
return y.reshape(-1,1)
cpdef np.ndarray _get_derivatives(self):
cdef int i, index, index_start, index_end
cdef np.ndarray xd = np.empty((self._len_derivatives))
for model in self.models_dict.keys():
if model.get_generation_tool() != "JModelica.org":
return None
for model in self.models:
index_start = self.models_dict[model]["global_index_derivatives"]
index_end = index_start + self.models_dict[model]["local_derivative_len"]
local_derivative_vref_array = (<FMI2.FMUModelCS2>model).get_real(self.models_dict[model]["local_derivative_vref_array"])
for i, index in enumerate(range(index_start, index_end)):
xd[index] = local_derivative_vref_array[i].item()
return xd.reshape(-1,1)
cpdef np.ndarray get_specific_connection_outputs_discrete(self, model, np.ndarray mask, np.ndarray yout):
cdef int j = 0
ytmp = model.get(np.array(self.models_dict[model]["local_output_discrete"])[mask])
for i, flag in enumerate(mask):
if flag:
yout[i+self.models_dict[model]["global_index_outputs_discrete"]] = ytmp[j].item()
j = j + 1
cpdef np.ndarray get_specific_connection_outputs(self, model, np.ndarray mask, np.ndarray yout):
cdef int j = 0
cdef np.ndarray ytmp = (<FMI2.FMUModelCS2>model).get_real(self.models_dict[model]["local_output_vref_array"][mask])
for i, flag in enumerate(mask):
if flag:
yout[i+self.models_dict[model]["global_index_outputs"]] = ytmp[j].item()
j = j + 1
cpdef get_connection_derivatives(self, np.ndarray y_cur):
#cdef list yd = []
cdef int i = 0, inext = 0, status = 0
cdef np.ndarray[FMIL2.fmi2_real_t, ndim=1, mode='c'] yd = np.empty((self._len_outputs))
cdef np.ndarray[FMIL2.fmi2_real_t, ndim=1, mode='c'] ydtmp = np.empty((self._len_outputs))
cdef np.ndarray y_last = None
if self.opts["extrapolation_order"] > 0:
if self.max_output_derivative_order > 0 and not self.opts["force_finite_difference_outputs"]:
for model in self.models_dict.keys():
#yd.extend(model.get_output_derivatives(self.models_dict[model]["local_output"], 1))
inext = i + self.models_dict[model]["local_output_len"]
status = (<FMI2.FMUModelCS2>model)._get_output_derivatives(self.models_dict[model]["local_output_vref_array"], ydtmp, self.models_dict[model]["local_output_vref_ones"])
if status != 0: raise FMUException("Failed to get the output derivatives.")
yd[i:inext] = ydtmp[:inext-i]
i = inext
return self.correct_output_derivative(yd.reshape(-1,1))
#return yd.reshape(-1,1)
else:
if self.opts["experimental_output_derivative"]:
JM_FMUS = True
for model in self.models_dict.keys():
if model.get_generation_tool() != "JModelica.org":
JM_FMUS = False
break
if JM_FMUS:
C = self.compute_global_C()
D = self.compute_global_D()
u,ud,udd = self.get_last_us()
xd = self._get_derivatives()
if ud is not None:
if udd is not None:
return C.dot(xd)+D.dot(ud+self.get_current_step_size()*udd)
else:
return C.dot(xd)+D.dot(ud)
else: #First step
return sps.linalg.spsolve((self._ident_matrix-D.dot(self.L)),C.dot(xd)).reshape((-1,1))
y_last = self.get_last_y()
if y_last is not None:
return (y_cur - y_last)/self.get_current_step_size()
else:
return None
else:
return None
cpdef get_connection_second_derivatives(self, np.ndarray yd_cur):
cdef int i = 0, inext = 0, status = 0
cdef np.ndarray[FMIL2.fmi2_real_t, ndim=1, mode='c'] ydd = np.empty((self._len_outputs))
cdef np.ndarray[FMIL2.fmi2_real_t, ndim=1, mode='c'] yddtmp = np.empty((self._len_outputs))
cdef np.ndarray yd_last = None
if self.opts["extrapolation_order"] > 1:
if self.max_output_derivative_order > 1 and not self.opts["force_finite_difference_outputs"]:
for model in self.models_dict.keys():
inext = i + self.models_dict[model]["local_output_len"]
status = (<FMI2.FMUModelCS2>model)._get_output_derivatives(self.models_dict[model]["local_output_vref_array"], yddtmp, self.models_dict[model]["local_output_vref_twos"])
if status != 0: raise FMUException("Failed to get the output derivatives of second order.")
ydd[i:inext] = yddtmp[:inext-i]
i = inext
return self.correct_output_second_derivative(ydd.reshape(-1,1))
else:
if self.opts["experimental_output_derivative"]:
JM_FMUS = True
for model in self.models_dict.keys():
if model.get_generation_tool() != "JModelica.org":
JM_FMUS = False
break
if JM_FMUS:
A = self.compute_global_A()
B = self.compute_global_B()
C = self.compute_global_C()
D = self.compute_global_D()
u,ud,udd = self.get_last_us()
xd = self._get_derivatives()
if ud is not None and udd is not None:
return C.dot(A.dot(xd))+C.dot(B.dot(ud+self.get_current_step_size()*udd))+D.dot(udd)
else: #First step
return sps.linalg.spsolve((self._ident_matrix-D.dot(self.L)),C.dot(A.dot(xd)+B.dot(self.L.dot(yd_cur)))).reshape((-1,1))
yd_last = self.get_last_yd()
if yd_last is not None:
return (yd_cur - yd_last)/self.get_current_step_size()
else:
return None
else:
return None
cpdef set_connection_inputs(self, np.ndarray u, np.ndarray ud=None, np.ndarray udd=None):
cdef int i = 0, inext, status
u = u.ravel()
for model in self.models:
i = self.models_dict[model]["global_index_inputs"] #MIGHT BE WRONG
inext = i + self.models_dict[model]["local_input_len"]
#model.set(self.models_dict[model]["local_input"], u[i:inext])
(<FMI2.FMUModelCS2>model).set_real(self.models_dict[model]["local_input_vref_array"], u[i:inext])
if ud is not None: #Set the input derivatives
ud = ud.ravel()
#model.set_input_derivatives(self.models_dict[model]["local_input"], ud[i:inext], 1)
status = (<FMI2.FMUModelCS2>model)._set_input_derivatives(self.models_dict[model]["local_input_vref_array"], ud[i:inext], self.models_dict[model]["local_input_vref_ones"])
if status != 0: raise FMUException("Failed to set the first order input derivatives.")
if udd is not None: #Set the input derivatives
udd = udd.ravel()
status = (<FMI2.FMUModelCS2>model)._set_input_derivatives(self.models_dict[model]["local_input_vref_array"], udd[i:inext], self.models_dict[model]["local_input_vref_twos"])
if status != 0: raise FMUException("Failed to set the second order input derivatives.")
i = inext
cpdef set_connection_inputs_discrete(self, np.ndarray u):
cdef int i = 0, inext, status
u = u.ravel()
for model in self.models:
i = self.models_dict[model]["global_index_inputs_discrete"] #MIGHT BE WRONG
inext = i + self.models_dict[model]["local_input_discrete_len"]
model.set(self.models_dict[model]["local_input_discrete"], u[i:inext])
cpdef set_specific_connection_inputs(self, model, np.ndarray mask, np.ndarray u):
cdef int i = self.models_dict[model]["global_index_inputs"]
cdef int inext = i + self.models_dict[model]["local_input_len"]
cdef np.ndarray usliced = u.ravel()[i:inext]
(<FMI2.FMUModelCS2>model).set_real(self.models_dict[model]["local_input_vref_array"][mask], usliced[mask])
cpdef set_specific_connection_inputs_discrete(self, model, np.ndarray mask, np.ndarray u):
cdef int i = self.models_dict[model]["global_index_inputs_discrete"]
cdef int inext = i + self.models_dict[model]["local_input_discrete_len"]
cdef np.ndarray usliced = u.ravel()[i:inext]
model.set(np.array(self.models_dict[model]["local_input_discrete"])[mask], usliced[mask])
cpdef correct_output_second_derivative(self, np.ndarray ydd):
if self.linear_correction and self.algebraic_loops and self.support_directional_derivatives:
raise NotImplementedError
"""
D = self.compute_global_D()
DL = D.dot(self.L)
if self.opts["extrapolation_order"] > 0:
uold, udold = self.get_last_us()
uhat = udold if udold is not None else np.zeros(np.array(yd).shape)
z = yd - D.dot(uhat)
yd = sps.linalg.spsolve((self._ident_matrix-DL),z).reshape((-1,1))
"""
return ydd
cpdef correct_output_derivative(self, np.ndarray yd):
if self.linear_correction and self.algebraic_loops and self.support_directional_derivatives:
D = self.compute_global_D()
DL = D.dot(self.L)
if self.opts["extrapolation_order"] > 0:
uold, udold, uddold = self.get_last_us()
uhat = udold if udold is not None else np.zeros(np.array(yd).shape)