forked from SebastianPeitz/QuaSiModO
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuaSiModO.py
1596 lines (1258 loc) · 61.8 KB
/
QuaSiModO.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from helpers import hypercube
from scipy import interpolate
from scipy import sparse
from scipy.optimize import minimize
from scipy.optimize import Bounds
from scipy.optimize import LinearConstraint
from scipy.io import savemat
from sys import exit
from os import path
import importlib
import itertools
import numpy as np
import pickle
class ClassModel:
"""ClassModel
This class contains
- handle to the model
- call to the model integrator
- routine for computing observables in space (xObs)
- parameters for the numerical solution (initial time, lag time)
- function to construct a control grid
Input
1) model in form of
- py-file placed in "models"
- ClassOpenFOAM object
2) h: step length
3) Reynolds number: inverse of the viscosity
4) iObs: Indices of states to observe in a finite-dimensional system (if None, then all are used)
5) y0 (default = None): Initial condition of the full state
6) uMin: array of lower bounds for the control input
7) uMax: array of upper bounds for the control input
8) dimZ: dimension of the observable
9) typeUGrid: type of control grid that is created from uMin and uMax in the routine createControlGrid
10) nGridU: number of sections the control input is divided into between uMin and uMax (component-wise)
11) uGrid: pass the grid of controls directly to the model
12) writeY: flag whether the full state should be written or not
Author: Sebastian Peitz, Paderborn University, [email protected]
First created: 05/2020
"""
y0 = [] # initial condition of full state
grid = [] # container for a numerical grid, if required
h = [] # step length of the integrator or - when using an external integrator - the step length in the time series
Re = [] # Reynolds number (used as the inverse viscosity in many PDE problems)
iObs = [] # array of indices of grid points at which the full state y is observed: z = y[iObs]
dimZ = []
dimU = []
uGrid = []
uC = []
nU = []
typeUGrid = []
def __init__(self, modelFileOrClass, uMin, uMax, h, dimZ, params=None, iObs=None, y0=None,
typeUGrid=None, nGridU=1, uGrid=None, writeY=True, SigY=None, SigZ=None):
print('Creating ClassModel with uMin = ' + str(uMin) + '; uMax = ' + str(uMax) + '; h = ' + str(h) +
'; dimZ = ' + str(dimZ) + '; iObs = ' + str(iObs) + '; y0 = ' + str(y0) +
'; typeUGrid = ' + str(typeUGrid) + '; nGridU = ' + str(nGridU))
self.dimZ = dimZ
self.h = h
self.uMin = np.array(uMin)
self.uMax = np.array(uMax)
self.dimU = len(uMin)
if uGrid is not None:
self.nU = uGrid.shape[0]
self.uC = uGrid[0]
self.uGrid = uGrid
else:
if typeUGrid is not None:
self.createControlGrid(self.uMin, self.uMax, typeUGrid, nGridU)
if y0 is not None:
self.y0 = y0
if params is not None:
self.params = params
if iObs is not None:
self.iObs = iObs
if SigY is not None:
self.SigY = SigY
if SigZ is not None:
self.SigZ = SigZ
self.writeY = writeY
# set the model structure depending on the input type in "modelFileOrClass"
# self.model calls the integrator that yields the trajectories for y and z
# self.observable is a function that -- given y and model -- yields z
#
# Type of "modelFileOrClass":
# 1) the right-hand side of an ODE
if callable(modelFileOrClass):
self.rhs = modelFileOrClass
if SigY is None:
self.model = self.simulateODE
else:
self.model = self.simulateSDE
if SigZ is None:
self.observable = self.observeODE
else:
self.observable = self.observeSDE
self.calcJ = None
else:
# 2) the name of a python file placed in the "models" folder
if isinstance(modelFileOrClass, str):
modelName = modelFileOrClass[:-3]
# 3) an OpenFOAM class variable
else:
self.OF = modelFileOrClass
modelName = self.OF.modelFile[:-3]
moduleModel = importlib.import_module("models." + modelName, package="simulateModel")
self.model = moduleModel.simulateModel
if hasattr(moduleModel, 'observable'):
self.observable = moduleModel.observable
else:
self.observable = None
if hasattr(moduleModel, 'calcJ'):
self.calcJ = moduleModel.calcJ
else:
self.calcJ = None
# calls the model that has been set up in __init__
def integrate(self, y0, u, t0):
return self.model(y0, t0, u, self)
# integrator
def RK4(self, y0, t0, u):
nt = u.shape[0]
T = (nt - 1) * self.h
t = np.linspace(0.0, T, nt) + t0
y = np.empty([nt, len(y0)], dtype=float)
y[0, :] = y0
for i in range(nt - 1):
k1 = self.rhs(y[i, :], u[i, :])
k2 = self.rhs(y[i, :] + 0.5 * self.h * k1, u[i, :])
k3 = self.rhs(y[i, :] + 0.5 * self.h * k2, u[i, :])
k4 = self.rhs(y[i, :] + self.h * k3, u[i, :])
y[i + 1, :] = y[i, :] + self.h / 6.0 * (k1 + 2.0 * (k2 + k3) + k4)
return y, t
def EulerMaruyama(self, y0, t0, u):
nt = u.shape[0]
T = (nt - 1) * self.h
t = np.linspace(0.0, T, nt) + t0
y = np.empty([nt, len(y0)], dtype=float)
y[0, :] = y0
for i in range(nt - 1):
y[i + 1, :] = y[i, :] + self.h * self.rhs(y[i, :], u[i, :]) + \
self.SigY * np.random.normal(loc=0.0, scale=np.sqrt(self.h), size=(1, len(y0)))
return y, t
# simulation model for ODEs
def simulateODE(self, y0, t0, u, model):
# Solve
y, t = self.RK4(y0, t0, u)
# Observation
z = self.observable(y)
return y, z, t, model
# simulation model for SDEs
def simulateSDE(self, y0, t0, u, model):
# Solve
y, t = self.EulerMaruyama(y0, t0, u)
# Observation
z = self.observable(y)
return y, z, t, model
# observable for ODEs
def observeODE(self, y):
if len(self.iObs) > 0:
z = y[:, self.iObs]
else:
z = y
return z
# observable for ODEs
def observeSDE(self, y):
if len(self.iObs) > 0:
nObs = len(self.iObs)
else:
nObs = y.shape[1]
z = np.zeros([y.shape[0], nObs], dtype=float)
if len(self.iObs) > 0:
for i in range(y.shape[0]):
z[i, :] = y[i, self.iObs] + np.sqrt(self.SigZ) * np.random.normal(size=(1, nObs))
else:
for i in range(y.shape[0]):
z[i, :] = y[i, :] + self.SigZ * np.random.normal(loc=0.0, scale=np.sqrt(self.h), size=(1, nObs))
return z
# computes a 1D grid using the domain length L and a step size dx
def setGrid1D(self, L, dx, xObs=None):
self.grid = Class1DGrid(L, dx, xObs)
def createControlGrid(self, uMin=None, uMax=None, typeUGrid='cube', nGridU=1):
"""
Creates a grid (uGrid) of controls for which the system can be evaluated, depending on typeUGrid.
The different controls are accessed via the first index, the second index then provides access to the individual
entries of the respective control
typeUGrid =
1) 'cube': Hypercube with uMin and uMax as corners
2) 'cubeCenter': Hypercube with uMin and uMax as corners and the center uC = 0.5 * (uMin + uMax) in addition
3) 'centerStar': Finite-difference-like star of controls, including the center uC = 0.5 * (uMin + uMax)
4) 'oneSidedStar': Half of a finite-difference-like star of controls, including the center uC = uMin
nGridU determines the number of segments along each dimension where control grid points are placed (default = 1)
"""
print('Creating control grid with uMin = ' + str(uMin) + '; uMax = ' + str(uMax) + '; typeUGrid = ' +
str(typeUGrid) + '; nGridU = ' + str(nGridU))
if uMin is None:
uMin = self.uMin
if uMax is None:
uMax = self.uMax
self.typeUGrid = typeUGrid
if (typeUGrid == 'cube') or (typeUGrid == 'cubeCenter'):
self.uC = 0.5 * (uMin + uMax)
self.nU = (1 + nGridU) ** self.dimU
uGrid = np.fliplr(np.array(
hypercube.hypercube_grid_points(self.dimU, self.nU, (1 + nGridU) * np.ones(self.dimU, dtype=int),
np.flip(uMin),
np.flip(uMax), np.ones(self.dimU, dtype=int))).T)
for i in range(self.dimU):
uGrid[:, i] = uGrid[:, i] + uMin[i] - uGrid[0, i] # 0.5 * (uMax[i] - uMin[i])
if typeUGrid == 'cubeCenter':
uGrid2 = np.zeros([uGrid.shape[0] + 1, uGrid.shape[1]], dtype=float)
uGrid2[:-1, :] = uGrid
uGrid2[-1, :] = self.uC
uGrid = uGrid2
self.nU += 1
elif typeUGrid == 'centerStar':
self.uC = 0.5 * (uMin + uMax)
self.nU = 2 * self.dimU + 1
uGrid = np.zeros([self.nU, self.dimU], dtype=float)
uGrid[0, :] = self.uC
for i in range(self.dimU):
uGrid[2 * i + 1, :] = self.uC
uGrid[2 * i + 1, i] = uMin[i]
uGrid[2 * i + 2, :] = self.uC
uGrid[2 * i + 2, i] = uMax[i]
elif typeUGrid == 'oneSidedStar':
self.uC = uMin
self.nU = self.dimU + 1
uGrid = np.zeros([self.nU, self.dimU], dtype=float)
uGrid[0, :] = self.uC
for i in range(self.dimU):
uGrid[i + 1, :] = uMin
uGrid[i + 1, i] = uMax[i]
else:
print('Error in "ClassModel.__init__.createControlGrid": Please specify "typeUGrid" as "cube", "centerStar"'
' or "oneSidedStar"')
exit(1)
self.uGrid = uGrid
return uGrid
def mapAlphaToU(self, alpha):
u = np.zeros([alpha.shape[0], self.dimU], dtype=float)
for i in range(alpha.shape[0]):
for iu in range(self.nU - 1):
u[i, :] += alpha[i, iu] * self.uGrid[iu, :]
u[i, :] += (1.0 - np.sum(alpha[i, :])) * self.uGrid[-1, :]
return u
class Class1DGrid:
"""Class1DGrid
This class creates a 1D grid and potentially the indices of observed grid points
Input
1) L = length of domain
2) dx = grid size
3) xObs = array of positions where the state is observed
Author: Sebastian Peitz, Paderborn University, [email protected]
First created: 05/2020
"""
xObs = []
def __init__(self, L, dx, xObs=None):
print('Creating 1D grid with L = ' + str(L) + '; dx = ' + str(dx) + '; xObs = ' + str(xObs))
self.L = L
self.dx = dx
self.x = np.arange(0, L + dx, dx)
if xObs is not None:
self.xObs = xObs
self.nz = len(xObs)
self.iObs = np.zeros(len(xObs), dtype=int)
xTmp = np.zeros(len(self.x), dtype=float)
for i in range(len(xObs)):
xTmp[:] = xObs[i]
self.iObs[i] = int(np.argmin(np.absolute(self.x - xTmp)))
class ClassControlDataSet:
"""ClassControlDataSet
This class contains routines for creating control sequences for data sampling and for the construction of raw data
sets which can be used for the surrogate modeling later
Inputs (optional, can also be specified in createControlSequence or createData, respectively)
1) h: time step for the control sequence. u is constant over each time step
2) T: final time of control sequence
3) y0: a (set of) initial condition(s) for which the simulation is performed
Output
1) Control trajectory
Author: Sebastian Peitz, Paderborn University, [email protected]
First created: 05/2020
"""
t = []
T = []
rawData = []
nDelay = []
dimZ = []
def __init__(self, h=None, T=None, y0=None):
"""
Creates the time step array and set y0 if given
"""
print('Creating ClassControlDataSet with h = ' + str(h) + '; T = ' + str(T) + '; y0 = ' + str(y0))
if h is not None and T is not None:
self.h = h
self.T = T
self.t = np.linspace(0, T, int(T / h + 1))
if y0 is not None:
self.y0 = np.array(y0)
def createControlSequence(self, model, h=None, T=None, uGrid=None, nhMin=1, nhMax=10,
typeSequence='piecewiseConstant', u=None, iu=None, periodicParameters=None):
"""
Creates a control sequence based on the sequence type and the uGrid specified in 'ClassModel.createControlGrid'
via the variable typeUGrid. The structure of the output is a 3-dimensional array, where the third index
indicates the number of the control trajectory that needs to be simulated
Inputs:
1) model: ClassModel type model
2) h: time step for the control sequence. u is constant over each time step
3) T: final time of control sequence
4) uGrid: array of inputs. The different controls are indexed via the first index
5) nhMin: minimal number of time steps over which the control is constant
6) nhMax: maximal number of time steps over which the control is constant
7) typeSequence =
a) 'piecewiseConstant': piecewise constant control, selected randomly from self.uGrid.
Random length of intervals bounded by nhMin and nhMax.
b) 'piecewiseLinear': piecewise linear interpolation between inputs selected randomly from self.uGrid.
Random length of intervals bounded by nhMin and nhMax.
c) 'spline': Spline interpolation between inputs selected randomly from self.uGrid.
Random length of intervals bounded by nhMin and nhMax.
d) Numerical value: Constant control input over the entire trajectory
e) 'sine': Sine function u(t) = a * sin(2 * pi * b * (t - c)). In that case, the input
periodicParameters = [a, b, c] needs to be specified
8) u: Previously created sequence
9) iu: index of controls to input 8)
10) periodicParameters = [a, b, c]: parameter in the case of sine input u(t) = a * sin(2 * pi * b * (t - c))
"""
if T is None:
T = self.T
if h is None:
h = self.h
nt = int(T / h + 1)
self.t = np.linspace(0, T, nt)
if uGrid is None:
if len(model.uGrid) == 0:
print('Error in "ClassControlDataSet.createControlSequence": Please specify control grid first via '
'"createControlGrid" or provide variable "uGrid" directly')
exit(1)
else:
uGrid = model.uGrid
print('Creating control sequence with h = ' + str(h) + '; T = ' + str(T) + '; uGrid = ' + str(uGrid) +
'; nhMin = ' + str(nhMin) + '; nhMax = ' + str(nhMax) + '; typeSequence = ' + str(typeSequence))
if u is None:
if iu is not None:
print('Error in "ClassControlDataSet.createControlSequence": Please specify either both u and iu or '
'none.')
exit(1)
else:
u = list()
iu = list()
else:
if iu is None:
print('Error in "ClassControlDataSet.createControlSequence": Please specify either both u and iu or '
'none.')
exit(1)
u_ = np.zeros([nt, model.dimU], dtype=float)
iu_ = np.zeros([nt, 1], dtype=int)
if isinstance(typeSequence, str):
if typeSequence == 'piecewiseConstant':
i1, i2 = 0, 0
while i2 < nt:
i2 = np.minimum(i1 + np.random.randint(nhMin, nhMax + 1), nt)
iu1 = np.random.randint(model.nU)
for j in range(i1, i2):
iu_[j, 0] = iu1
u_[j, :] = uGrid[iu1, :]
i1 = i2
elif typeSequence == 'piecewiseLinear':
i1, i2 = 0, 0
iu1 = 0
iu_[i1, 0] = iu1
u_[i1, :] = uGrid[iu1, :]
while i2 < nt:
i2 = np.minimum(i1 + np.random.randint(nhMin, nhMax + 1), nt)
iu2 = np.random.randint(model.nU)
if i2 - i1 < 2:
u_[i1, :] = uGrid[iu1, :]
else:
for j in range(i1, i2):
iu_[j, 0] = iu2
u_[j, :] = uGrid[iu1, :] + (uGrid[iu2, :] - uGrid[iu1, :]) * (j - i1) / (i2 - i1 - 1)
i1 = i2
elif typeSequence == 'spline':
i1, i2 = 0, 0
iSupport = np.zeros(nt, dtype=int)
uSupport = np.zeros([nt, model.dimU], dtype=float)
iSupport[0] = 0
uSupport[0, :] = uGrid[0, :]
s = 0
while i2 < nt - 1:
s += 1
i2 = np.minimum(i1 + np.random.randint(nhMin, nhMax + 1), nt - 1)
iSupport[s] = i2
uSupport[s, :] = uGrid[np.random.randint(model.nU), :]
i1 = i2
iSupport = iSupport[:s + 1]
uSupport = uSupport[:s + 1, :]
for i in range(model.dimU):
tck = interpolate.splrep(self.t[iSupport], uSupport[:, i], s=0)
u_[:, i] = interpolate.splev(self.t, tck, der=0)
iu_ = []
elif typeSequence == 'sine':
if periodicParameters is None:
print('Error in "ClassControlDataSet.createControlSequence": Please specify '
'typeSequence = [a, b, c] if you set typeSequence to "sine".')
exit(1)
u_[:, 0] = periodicParameters[0] * np.sin(2 * np.pi * periodicParameters[1] * (self.t - periodicParameters[2]))
else:
uConst = np.zeros([1, model.dimU], dtype=float)
uConst[0, :] = typeSequence
iu_[:] = mapUToIu(uConst, model.uGrid)
u_ = mapIuToU(iu_, model.uGrid)
u.append(u_)
iu.append(iu_)
return u, iu
def createData(self, model=None, y0=None, u=None, savePath=None, loadPath=None):
"""
Creates the corresponding data structure, depending on the model reduction method.
If simulate=True, then the data is created by simulating the model.
Saving and loading the raw data can be realized by providing the corresponding paths (savePath or loadPath)
Inputs:
1) model: ClassModel type model
2) y0: a (set of) initial condition(s) for which the simulation is performed
3) u: a (set of) control(s) for which the simulation is performed
4) savePath: path + filename to which the raw data should be stored
5) loadPath: path + filename from which the raw data should be obtained. If specified, the data is just loaded
and the routine ended prematurely
Output (also stored directly in self.rawData)
1) rawData structure consisting of the variables (y, z, t, u, iu)
"""
print('Creating rawData by simulation with savePath = ' + str(savePath) + '; loadPath = ' + str(loadPath))
if loadPath is not None:
self.rawData = ClassRawData(loadPath=loadPath)
return
if model is None:
print('Error in "ClassControlDataSet.createData": Please specify model for simulation')
exit(1)
if u is None:
print('Error in "ClassControlDataSet.createData": Please specify control u')
exit(1)
if y0 is None:
y0 = list()
y0.append(model.y0)
else:
if isinstance(y0[0], float):
y0_ = list()
y0_.append(y0)
y0 = y0_
nIC = len(y0)
nU = len(u)
yAll, zAll, tAll, uAll, iuAll = list(), list(), list(), list(), list()
for i in range(nU):
for j in range(nIC):
[y, z, t, _] = model.integrate(y0[j], u[i], 0.0)
yAll.append(y)
zAll.append(z)
tAll.append(t)
uAll.append(u[i])
iuAll.append(mapUToIu(u[i], model.uGrid))
self.rawData = ClassRawData(y=yAll, z=zAll, t=tAll, u=uAll, iu=iuAll)
if savePath is not None:
self.rawData.save(savePath=savePath)
def prepareData(self, model, method='None', rawData=None, nLag=1, nDelay=0, typeDer='FD'):
"""
Takes in the rawData (either passed directly or stored in the class) and creates structured data according to
the selected method. For each of the (model.nU) entries in the control grid, a list entry is created:
X[i] corresponds to the input uGrid[i, :] for i in {0, 1, ... model.nU - 1}
Inputs
1) model (type ClassModel)
2) method (type string): Depending on which entries the string contains, different types of output data are
created:
a) 'Y': X shifted forward in time by nLag entries
b) 'dX': Calculates the derivative of X (depending on typeDer, either using the model or finite differences)
c) 'XU': Creates the product of states times controls (e.g., for Koopman generator models with inputs)
d) 'YU': Creates the time shift of XU by nLag entries (e.g., for a Koopman operator approximation for c))
e) 'dXU': Creates the time derivative of 'XU'
3) rawData (type ClassRawData): Collected data. Can alternatively be accessed from self.rawData
4) nLag (type int): Number of time steps the time-shifted data matrices are shifted forward in time
5) nDelay (type int, default = 0): Number of time delayed observations
6) typeDer (type string): Method for the numerical computation of derivatives ('FD': forward differences or
'CD': central differences). If the model possesses a right-hand side description (model.rhs), then the
derivative is computed by evaluating the model)
Output
1) data structure containing the prepared data matrices ({'X': X, 'Y': Y, 'dX': dX, 'XU': XU, 'dXU': dXU})
"""
if rawData is None:
rawData = self.rawData
self.dimZ = rawData.z[0].shape[1]
self.nDelay = nDelay
print('Creating ClassModel with method = ' + str(method) + '; rawData = ' + str(rawData) + '; nLag = ' +
str(nLag) + '; nDelay = ' + str(nDelay) + '; typeDer = ' + str(typeDer))
flagY = (str.find(method, 'Y') >= 0)
flagDX = (str.find(method, 'dX') >= 0)
flagXU = (str.find(method, 'XU') >= 0)
flagYU = (str.find(method, 'YU') >= 0)
flagDXU = (str.find(method, 'dXU') >= 0)
X, Y, dX, XU, YU, dXU, u = list(), list(), list(), list(), list(), list(), list()
for i in range(model.nU):
X.append(list())
Y.append(list())
dX.append(list())
XU.append(list())
YU.append(list())
dXU.append(list())
u.append(model.uGrid[i, :])
if flagDX or flagDXU:
if hasattr(model, 'rhs'):
dy = list()
dz = list()
for i in range(len(rawData.z)):
dy.append(calcDerivative(rawData.y[i], model, typeDer, U=rawData.u[i]))
dz.append(model.observable(dy[-1]))
else:
dz = list()
for i in range(len(rawData.z)):
dz.append(calcDerivative(rawData.z[i], model, typeDer))
for i in range(len(rawData.z)):
if flagY or flagYU:
for j in range(rawData.z[i].shape[0] - (self.nDelay + 1) * nLag):
if self.nDelay == 0:
if not any(rawData.iu[i][j: j + nLag, 0] != rawData.iu[i][j, 0]):
X[rawData.iu[i][j, 0]].append(rawData.z[i][j, :])
Y[rawData.iu[i][j, 0]].append(rawData.z[i][j + nLag, :])
if flagDX:
dX[rawData.iu[i][j, 0]].append(dz[i][j, :])
if flagXU:
pass
if flagYU:
pass
if flagDXU:
pass
else:
if not any(rawData.iu[i][j + nDelay * nLag: j + (1 + nDelay) * nLag, 0] != rawData.iu[i][j + nDelay * nLag, 0]):
X[rawData.iu[i][j + nDelay * nLag, 0]].append(self.stackZ(rawData.z[i][j: j + self.nDelay * nLag + 1, :], nLag))
Y[rawData.iu[i][j + nDelay * nLag, 0]].append(self.stackZ(rawData.z[i][j + nLag: j + (self.nDelay + 1) * nLag + 1, :], nLag))
else:
for j in range(rawData.z[i].shape[0]):
X[rawData.iu[i][j, 0]].append(rawData.z[i][j, :])
if flagDX:
dX[rawData.iu[i][j, 0]].append(dz[i][j, :])
if flagXU:
pass
if flagYU:
pass
if flagDXU:
pass
for i in range(model.nU):
X[i] = np.array(X[i])
Y[i] = np.array(Y[i])
dX[i] = np.array(dX[i])
XU[i] = np.array(XU[i])
YU[i] = np.array(YU[i])
dXU[i] = np.array(dXU[i])
data = {'X': X, 'Y': Y, 'dX': dX, 'XU': XU, 'dXU': dXU, 'u': u}
return data
def stackZ(self, z, hShM):
zOut = np.zeros([self.dimZ * (1 + self.nDelay)], dtype=float)
for i in range(self.nDelay + 1):
zOut[i * self.dimZ: (i + 1) * self.dimZ] = z[-(i * hShM + 1), :]
return zOut
def calcDerivative(X, model, typeDer=None, U=None):
dX = np.zeros(X.shape, dtype=float)
if hasattr(model, 'rhs') and (U is not None):
for i in range(X.shape[0]):
dX[i, :] = model.rhs(X[i, :], U[i, :])
else:
if typeDer is None:
typeDer = 'FD'
if typeDer == 'CD':
dX[0, :] = (X[1, :] - X[0, :]) / model.h
dX[-1, :] = (X[-1, :] - X[-2, :]) / model.h
for i in range(1, X.shape[0] - 1):
dX[i, :] = (X[i + 1, :] - X[i - 1, :]) / (2.0 * model.h)
elif typeDer == 'FD':
dX[-1, :] = (X[-1, :] - X[-2, :]) / model.h
for i in range(X.shape[0] - 1):
dX[i, :] = (X[i + 1, :] - X[i, :]) / model.h
return dX
class ClassRawData:
"""ClassRawData
This class contains raw simulation data and functions for saving and loading the data
Author: Sebastian Peitz, Paderborn University, [email protected]
First created: 05/2020
"""
y, z, t, u, iu = [], [], [], [], []
def __init__(self, y=None, z=None, t=None, u=None, iu=None, savePath=None, loadPath=None):
if loadPath is not None:
self.load(loadPath)
return
if y is not None:
self.y = y
if z is not None:
self.z = z
if t is not None:
self.t = t
if u is not None:
self.u = u
if iu is not None:
self.iu = iu
if savePath is not None:
self.save(savePath)
def save(self, savePath):
np.savez(savePath, y=self.y, z=self.z, t=self.t, u=self.u, iu=self.iu, allow_pickle=True)
def load(self, loadPath):
if loadPath[-4:] != '.npz':
loadPath = loadPath + '.npz'
dataIn = np.load(loadPath, allow_pickle=True)
self.y = arrayToList(dataIn['y'])
self.z = arrayToList(dataIn['z'])
self.t = arrayToList(dataIn['t'])
self.u = arrayToList(dataIn['u'])
self.iu = arrayToList(dataIn['iu'])
def arrayToList(x):
if type(x) != type(list()):
y = list()
if x[0,...].shape == ():
for i in range(x.shape[0]):
y.append(x[i, ...].item())
else:
for i in range(x.shape[0]):
y.append(x[i, ...])
return y
else:
return x
class ClassModelData(object):
pass
class ClassSurrogateModel:
"""ClassSurrogateModel
This class contains functions for the preparation of data, the integration of the relaxed surrogate model and
some additional help functions. The "surrogateModelFile" should contain the following functions:
1) timeTMap(z0, t0, iu, surrogateModel) -> z, t, surrogateModel
Discrete mapping over one time step surrogateModel.h using the i-th input (contained in iu). The time step and
the control grid are stored in surrogateModel.h and surrogateModel.uGrid, respectively. All additional data
required for the surrogate model (including memory terms for the next time step) can be accessed via
surrogateModel.modelData, which is first created in the function "createSurrogateModel"
2) createSurrogateModel(modelData, X, Y) -> modelData
Creates a data-driven surrogate model using X and Y. Additional options can be stored in modelData
3) updateSurrogateModel(modelData, X, Y) -> modelData
Inputs
1) surrogateModelFile: name of the .py file stored in surrogateModels
2) uGrid: grid of fixed controls
3) h: step size of the surrogate model
4) z0: initial condition (can also be left blank if specified later in the MPC class)
5) dimZ: dimension of the observable z
6) nDelay (type int, default = 0): Number of time delayed observations
7) Arbitrary additional parameters required for the surrogate model: These are stored as a dictionary in .modelData
Author: Sebastian Peitz, Paderborn University, [email protected]
First created: 05/2020
"""
z0 = None
dimZ = None
modelData = ClassModelData()
integrate = None
timeTMap = None
createSurrogateModel = None
saveSurrogateModel = None
updateSurrogateModel = None
loadSurrogateModel = None
calcJ = None
uGrid = None
nU = None
dimU = None
hShM = 1
X, Y = [], []
def __init__(self, surrogateModelFile, uGrid, h, z0=None, dimZ=None, nDelay=0, **kwargs):
stringOut = 'Creating ClassSurrogateModel with surrogateModelFile = ' + str(surrogateModelFile) + '; uGrid = ' \
+ str(uGrid) + '; h = ' + str(h) + '; z0 = ' + str(z0) + '; dimZ = ' + str(dimZ)
if len(kwargs) > 0:
stringOut += ' and free parameter(s) '
for key, value in kwargs.items():
stringOut += str(key) + ' = ' + str(value) + ';'
print(stringOut[:-1])
# Set parameters that have been passed to the class
if z0 is not None:
self.z0 = np.array(z0)
if dimZ is None:
self.dimZ = len(z0)
if dimZ is not None:
self.dimZ = dimZ
self.nDelay = nDelay
self.h = h
if uGrid is None:
print('Error in "ClassSurrogateModel.__init__": please provide uGrid')
exit(1)
else:
self.uGrid = uGrid
self.nU = uGrid.shape[0]
self.dimU = uGrid.shape[1]
if surrogateModelFile[-3:] == '.py':
surrogateModelFile = surrogateModelFile[:-3]
moduleSurrogateModel = importlib.import_module("surrogateModels." + surrogateModelFile)
if hasattr(moduleSurrogateModel, 'timeTMap'):
self.timeTMap = moduleSurrogateModel.timeTMap
if hasattr(moduleSurrogateModel, 'createSurrogateModel'):
self.createSurrogateModel = moduleSurrogateModel.createSurrogateModel
if hasattr(moduleSurrogateModel, 'updateSurrogateModel'):
self.updateSurrogateModel = moduleSurrogateModel.updateSurrogateModel
if hasattr(moduleSurrogateModel, 'calcJ'):
self.calcJ = moduleSurrogateModel.calcJ
if hasattr(moduleSurrogateModel, 'saveSurrogateModel'):
self.saveSurrogateModel = moduleSurrogateModel.saveSurrogateModel
if hasattr(moduleSurrogateModel, 'loadSurrogateModel'):
self.loadSurrogateModel = moduleSurrogateModel.loadSurrogateModel
setattr(self.modelData, 'h', self.h)
setattr(self.modelData, 'uGrid', self.uGrid)
setattr(self.modelData, 'nDelay', self.nDelay)
for key, value in kwargs.items():
setattr(self.modelData, key, value)
def createROM(self, data, savePath=None, loadPath=None):
if loadPath is not None:
fIn = open(loadPath + '.pkl', 'rb')
selfLoad = pickle.load(fIn)
self.X = selfLoad.X
self.Y = selfLoad.Y
self.dimU = selfLoad.dimU
self.dimZ = selfLoad.dimZ
self.h = selfLoad.h
self.hShM = selfLoad.hShM
self.integrate = selfLoad.integrate
self.nDelay = selfLoad.nDelay
self.nU = selfLoad.nU
self.uGrid = selfLoad.uGrid
self.z0 = selfLoad.z0
if self.loadSurrogateModel is not None:
self.modelData = self.loadSurrogateModel(loadPath)
else:
setattr(self, 'modelData', selfLoad.modelData)
return
if self.createSurrogateModel is not None:
self.modelData = self.createSurrogateModel(self.modelData, data)
if savePath is not None:
if self.saveSurrogateModel is not None:
self.saveSurrogateModel(self.modelData, savePath)
modelData_temp = self.modelData
self.modelData = []
with open(savePath + '.pkl', 'wb') as fOut:
pickle.dump(self, fOut)
if self.saveSurrogateModel is not None:
self.modelData = modelData_temp
else:
print('Error in "ClassSurrogateModel.createROM": No function "createSurrogateModel(modelData, data)" '
'defined in the .py file containing the model')
exit(1)
def updateROM(self, data):
if self.updateSurrogateModel is not None:
self.modelData = self.updateSurrogateModel(self.modelData, data)
else:
print('Error in "ClassSurrogateModel.updateROM": No function "updateSurrogateModel(modelData, data)" '
'defined in the .py file containing the model')
exit(1)
def integrateRelaxedTimeTMap(self, z0, t0, alpha):
z = np.zeros([alpha.shape[0], self.dimZ * (1 + self.nDelay)], dtype=float)
z[0, :] = z0
zPlus = np.zeros([self.dimZ * (1 + self.nDelay)], dtype=float)
time = t0
for i in range(alpha.shape[0] - 1):
zPlus[:] = 0.0
for iu in range(self.nU - 1):
ziu, _, _ = self.timeTMap(z[i, :], time, iu, self.modelData)
zPlus += alpha[i, iu] * ziu
ziu, _, _ = self.timeTMap(z[i, :], time, self.nU - 1, self.modelData)
zPlus += (1.0 - np.sum(alpha[i, :])) * ziu
z[i + 1, :] = zPlus
time = time + self.h
return z
def integrateDiscreteInput(self, z0, t0, iu):
z = np.zeros([iu.shape[0], self.dimZ * (1 + self.nDelay)], dtype=float)
t = np.linspace(0.0, (iu.shape[0] - 1) * self.h, iu.shape[0]) + t0
z[0, :] = z0
ti = t0
for i in range(iu.shape[0] - 1):
z[i + 1, :], ti, self.modelData = self.timeTMap(z[i, :], ti, iu[i, 0], self.modelData)
return z, t
def mapAlphaToU(self, alpha):
u = np.zeros([alpha.shape[0], self.dimU], dtype=float)
for i in range(alpha.shape[0]):
for iu in range(self.nU - 1):
u[i, :] += alpha[i, iu] * self.uGrid[iu, :]
u[i, :] += (1.0 - np.sum(alpha[i, :])) * self.uGrid[-1, :]
return u
class ClassReferenceTrajectory:
"""ClassReferenceTrajectory
This class contains the reference trajectory for the MPC problem as well as methods for its computation
Author: Sebastian Peitz, Paderborn University, [email protected]
First created: 05/2020
"""
zSurrogate = []
iRefSurrogate = []
def __init__(self, model, zRef, T=None, iRef=None):
print('Creating ClassReferenceTrajectory with T = ' + str(T) + '; iRef = ' +
str(iRef))
zRef = np.asarray(zRef)
if model.dimZ is None:
print('Error in "ClassReferenceTrajectory.__init__": Please specify dimZ in ClassModel file')
exit(1)
if T is None:
self.T = int((zRef.shape[0] - 1) / model.h)
else:
self.T = T
if iRef is None:
self.iRef = np.array(range(model.dimZ))
else:
self.iRef = np.asarray(iRef)
n = int(self.T / model.h) + 1
self.z = np.zeros([n, model.dimZ], dtype=float)