forked from PyDMD/PyDMD
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathmrdmd.py
More file actions
522 lines (422 loc) · 17.6 KB
/
mrdmd.py
File metadata and controls
522 lines (422 loc) · 17.6 KB
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
"""
Derived module from dmdbase.py for multi-resolution dmd.
Reference:
- Kutz, J. Nathan, Xing Fu, and Steven L. Brunton. Multiresolution Dynamic Mode
Decomposition. SIAM Journal on Applied Dynamical Systems 15.2 (2016): 713-735.
"""
from copy import deepcopy
from functools import partial
import numpy as np
from scipy.linalg import block_diag
from .dmd_modes_tuner import select_modes
from .dmdbase import DMDBase
from .snapshots import Snapshots
class BinaryTree:
"""Simple Binary tree"""
def __init__(self, depth):
self.depth = depth
self.tree = [None] * len(self)
def __len__(self):
return 2 ** (self.depth + 1) - 1
def __getitem__(self, val):
level_, bin_ = val
if level_ > self.depth:
raise ValueError(
"""The level input parameter ({}) has to be less or equal than
the max_level ({}). Remember that the starting
index is 0""".format(
level_, self.depth
)
)
if bin_ >= 2**level_:
raise ValueError("Invalid node")
return self.tree[2**level_ + bin_ - 1]
def __setitem__(self, val, item):
level_, bin_ = val
self.tree[2**level_ + bin_ - 1] = item
def __iter__(self):
return self.tree.__iter__()
@property
def levels(self):
return range(self.depth + 1)
def index_leaves(self, level):
return range(0, 2**level)
class MrDMD(DMDBase):
"""
Multi-resolution Dynamic Mode Decomposition
:param dmd: DMD instance(s) used to analyze the snapshots provided. See also
the documentation for :meth:`_dmd_builder`.
:type dmd: DMDBase or list or tuple or function
:param int max_cycles: the maximum number of mode oscillations in any given
time scale. Default is 1.
:param int max_level: the maximum level (inclusive). For instance,
`max_level=4` means that we are going to have levels `0`, `1`, `2`, `3`
and `4`. Default is 2.
"""
def __init__(self, dmd, max_level=2, max_cycles=1):
self.dmd = dmd
self.max_cycles = max_cycles
self.max_level = max_level
self._build_tree()
def __iter__(self):
return self.dmd_tree.__iter__()
@property
def modes(self):
"""
Get the matrix containing the DMD modes, stored by column.
:return: the matrix containing the DMD modes.
:rtype: numpy.ndarray
"""
return np.hstack(
[self.partial_modes(i) for i in range(self.max_level + 1)]
)
@property
def dynamics(self):
"""
Get the time evolution of each mode.
:return: the matrix that contains all the time evolution, stored by
row.
:rtype: numpy.ndarray
"""
return np.vstack(
[self.partial_dynamics(i) for i in range(self.max_level + 1)]
)
@property
def eigs(self):
"""
Get the eigenvalues of A tilde.
:return: the eigenvalues from the eigendecomposition of `atilde`.
:rtype: numpy.ndarray
"""
return np.concatenate([dmd.eigs for dmd in self])
@property
def modes_activation_bitmask(self):
raise RuntimeError("This feature has not been implemented yet.")
@modes_activation_bitmask.setter
def modes_activation_bitmask(self, value):
raise RuntimeError("This feature has not been implemented yet.")
@property
def reconstructed_data(self):
"""
Get the reconstructed data.
:return: the matrix that contains the reconstructed snapshots.
:rtype: numpy.ndarray
"""
return np.sum(
np.array(
[
np.hstack(
[
self.dmd_tree[level, leaf].reconstructed_data
for leaf in self.dmd_tree.index_leaves(level)
]
)
for level in self.dmd_tree.levels
]
),
axis=0,
)
def _dmd_builder(self):
"""
Builds a function which takes in input a level and a leaf count
(i.e. coordinates inside the binary tree) and produces an appropriate
DMD instance according to the criteria specified in `self.dmd`.
Criteria supported:
- A function which takes two parameters `level` and `leaf`;
- List/tuple of DMD instances (length must be equal to `max_level+1`);
- A DMD instance (which is used for all the levels and leaves).
Example 0 (one DMD):
.. code-block:: python
>>> # this SpDMD is used for all the levels, for all the leaves
>>> MrDMD(dmd=SpDMD(), max_level=5).fit(X)
Example 1 (simple function which adapts the parameter d of HankelDMD
to the current level of the tree):
.. code-block:: python
>>> def build_dmds(level, leaf):
... d = 30 - 2*level
... return HankelDMD(d=d)
>>> MrDMD(dmd=build_dmds, max_level=5).fit(X)
Example 2 (we use a different kind of DMD if we are near the middle part
of the time window):
.. code-block:: python
>>> # you can name the function however you prefer
>>> def my_dmds(level, leaf):
... level_size = pow(2,level)
... distance_from_middle = abs(leaf - level_size // 2)
... # we choose 2 as a random threshold
... if distance_from_middle < 2:
... return HankelDMD(d=5)
... else:
... return DMD(svd_rank=3)
>>> MrDMD(dmd=my_dmds, max_level=5).fit(X)
Example 3 (tuple of DMDs):
.. code-block:: python
>>> dmds_list = [DMD(svd_rank=10) for i in range(6) if i < 3
else DMD(svd_rank=2)]
>>> MrDMD(dmd=dmds_list, max_level=5).fit(X)
:return: A function which can be used to spawn DMD instances according
to the level and leaf.
:rtype: func
"""
if callable(self.dmd):
builder_func = self.dmd
elif isinstance(self.dmd, (list, tuple)):
if len(self.dmd) != self.max_level + 1:
raise ValueError(
"""
Expected one item per level, got {} out of {} levels.""".format(
len(self.dmd), self.max_level
)
)
def builder_func(level, *args):
return deepcopy(self.dmd[level])
elif isinstance(self.dmd, DMDBase):
def builder_func(*args):
return deepcopy(self.dmd)
return builder_func
def _build_tree(self):
"""
Build the internal binary tree that contain the DMD subclasses.
"""
self.dmd_tree = BinaryTree(self.max_level)
# we build a function which takes the level and leaf and returns a DMD
builder_func = self._dmd_builder()
# Empty init
for level in self.dmd_tree.levels:
for leaf in self.dmd_tree.index_leaves(level):
# we construct the dmd before in order to trigger a better
# exception in case the function fails (otherwise it would
# be an IndexError)
dmd = builder_func(level, leaf)
self.dmd_tree[level, leaf] = dmd
def time_window_bins(self, t0, tend):
"""
Find which bins are embedded (partially or totally) in a given
time window.
:param float t0: start time of the window.
:param float tend: end time of the window.
:return: indexes of the bins seen by the time window.
:rtype: numpy.ndarray
"""
indexes = []
for level in self.dmd_tree.levels:
for leaf in self.dmd_tree.index_leaves(level):
local_times = self.partial_time_interval(level, leaf)
if (
local_times["t0"] <= t0 < local_times["tend"]
or local_times["t0"] < tend <= local_times["tend"]
or (t0 <= local_times["t0"] and tend >= local_times["tend"])
):
indexes.append((level, leaf))
indexes = np.unique(indexes, axis=0)
return indexes
def time_window_eigs(self, t0, tend):
"""
Get the eigenvalues relative to the modes of the bins embedded
(partially or totally) in a given time window.
:param float t0: start time of the window.
:param float tend: end time of the window.
:return: the eigenvalues for that time window.
:rtype: numpy.ndarray
"""
indexes = self.time_window_bins(t0, tend)
return np.concatenate([self.dmd_tree[idx].eigs for idx in indexes])
def time_window_frequency(self, t0, tend):
"""
Get the frequencies relative to the modes of the bins embedded
(partially or totally) in a given time window.
:param float t0: start time of the window.
:param float tend: end time of the window.
:return: the frequencies for that time window.
:rtype: numpy.ndarray
"""
indexes = self.time_window_bins(t0, tend)
return np.concatenate([self.dmd_tree[idx].frequency for idx in indexes])
def time_window_growth_rate(self, t0, tend):
"""
Get the growth rate values relative to the modes of the bins embedded
(partially or totally) in a given time window.
:param float t0: start time of the window.
:param float tend: end time of the window.
:return: the Floquet values for that time window.
:rtype: numpy.ndarray
"""
indexes = self.time_window_bins(t0, tend)
return np.concatenate(
[self.dmd_tree[idx].growth_rate for idx in indexes]
)
def time_window_amplitudes(self, t0, tend):
"""
Get the amplitudes relative to the modes of the bins embedded
(partially or totally) in a given time window.
:param float t0: start time of the window.
:param float tend: end time of the window.
:return: the amplitude of the modes for that time window.
:rtype: numpy.ndarray
"""
indexes = self.time_window_bins(t0, tend)
return np.concatenate(
[self.dmd_tree[idx].amplitudes for idx in indexes]
)
def partial_modes(self, level, node=None):
"""
Return the modes at the specific `level` and at the specific `node`; if
`node` is not specified, the method returns all the modes of the given
`level` (all the nodes).
:param int level: the index of the level from where the modes are
extracted.
:param int node: the index of the node from where the modes are
extracted; if None, the modes are extracted from all the nodes of
the given level. Default is None.
:return: the selected modes stored by columns
:rtype: numpy.ndarray
"""
leaves = self.dmd_tree.index_leaves(level) if node is None else [node]
return np.hstack([self.dmd_tree[level, leaf].modes for leaf in leaves])
def partial_dynamics(self, level, node=None):
"""
Return the time evolution of the specific `level` and of the specific
`node`; if `node` is not specified, the method returns the time
evolution of the given `level` (all the nodes). The dynamics are always
reported to the original time window.
:param int level: the index of the level from where the time evolution
is extracted.
:param int node: the index of the node from where the time evolution is
extracted; if None, the time evolution is extracted from all the
nodes of the given level. Default is None.
:return: the selected dynamics stored by row
:rtype: numpy.ndarray
"""
leaves = self.dmd_tree.index_leaves(level) if node is None else [node]
dynamics = block_diag(
*tuple(
dmd.dynamics
for dmd in map(lambda leaf: self.dmd_tree[level, leaf], leaves)
)
)
return dynamics
def partial_eigs(self, level, node=None):
"""
Return the eigenvalues of the specific `level` and of the specific
`node`; if `node` is not specified, the method returns the eigenvalues
of the given `level` (all the nodes).
:param int level: the index of the level from where the eigenvalues is
extracted.
:param int node: the index of the node from where the eigenvalues is
extracted; if None, the time evolution is extracted from all the
nodes of the given level. Default is None.
:return: the selected eigs
:rtype: numpy.ndarray
"""
leaves = self.dmd_tree.index_leaves(level) if node is None else [node]
return np.concatenate(
[self.dmd_tree[level, leaf].eigs for leaf in leaves]
)
def partial_amplitudes(self, level, node=None):
"""
Return the amplitudes of the specific `level` and of the specific
`node`; if `node` is not specified, the method returns the amplitudes
of the given `level` (all the nodes).
:param int level: the index of the level from where the amplitudes are
extracted.
:param int node: the index of the node from where the amplitudes are
extracted; if None, the amplitudes are extracted from all the
nodes of the given level. Default is None.
:return: the selected eigs
:rtype: numpy.ndarray
"""
leaves = self.dmd_tree.index_leaves(level) if node is None else [node]
return np.concatenate(
[self.dmd_tree[level, leaf].amplitudes for leaf in leaves]
)
def partial_reconstructed_data(self, level, node=None):
"""
Return the reconstructed data computed using the modes and the time
evolution at the specific `level` and at the specific `node`; if `node`
is not specified, the method returns the reconstructed data
of the given `level` (all the nodes).
:param int level: the index of the level.
:param int node: the index of the node from where the time evolution is
extracted; if None, the time evolution is extracted from all the
nodes of the given level. Default is None.
:return: the selected reconstruction from dmd operators
:rtype: numpy.ndarray
"""
modes = self.partial_modes(level, node)
dynamics = self.partial_dynamics(level, node)
return modes.dot(dynamics)
def partial_time_interval(self, level, leaf):
"""
Evaluate the start and end time and the period of a given bin.
:param int level: the level in the binary tree.
:param int node: the node id.
:return: the start and end time and the period of the bin
:rtype: dictionary
"""
if level > self.max_level:
raise ValueError(
"The level input parameter ({}) has to be less than the "
"max_level ({}). Remember that the starting index is 0".format(
level, self.max_level
)
)
if leaf >= 2**level:
raise ValueError("Invalid node")
full_period = self.original_time["tend"] - self.original_time["t0"]
period = full_period / 2**level
t0 = self.original_time["t0"] + period * leaf
tend = t0 + period
return {"t0": t0, "tend": tend, "delta": period}
def enumerate(self):
"""
Example:
>>> mrdmd = MrDMD(DMD())
>>> mrdmd.fit(X)
>>> for level, leaf, dmd in mrdmd:
>>> print(level, leaf, dmd.eigs)
"""
for level in self.dmd_tree.levels:
for leaf in self.dmd_tree.index_leaves(level):
yield level, leaf, self.dmd_tree[level, leaf]
def fit(self, X):
"""
Compute the Dynamic Modes Decomposition to the input data.
:param X: the input snapshots.
:type X: numpy.ndarray or iterable
"""
self._reset()
self._snapshots_holder = Snapshots(X)
# Redefine max level if it is too big.
lvl_threshold = (
int(np.log(self.snapshots.shape[1] / 4.0) / np.log(2.0)) + 1
)
if self.max_level > lvl_threshold:
self.max_level = lvl_threshold
self._build_tree()
print(
"Too many levels... "
"Redefining `max_level` to {}".format(self.max_level)
)
def slow_modes(dmd, rho):
return np.abs(np.log(dmd.eigs)) < rho * 2 * np.pi
X = self.snapshots.copy()
for level in self.dmd_tree.levels:
n_leaf = 2**level
Xs = np.array_split(X, n_leaf, axis=1)
for leaf, x in enumerate(Xs):
current_dmd = self.dmd_tree[level, leaf]
current_dmd.fit(x)
rho = self.max_cycles / x.shape[1]
slow_modes_selector = partial(slow_modes, rho=rho)
select_modes(current_dmd, slow_modes_selector)
newX = np.hstack(
[
self.dmd_tree[level, leaf].reconstructed_data
for leaf in self.dmd_tree.index_leaves(level)
]
).astype(X.dtype)
X -= newX
self._set_initial_time_dictionary(
dict(t0=0, tend=self.snapshots.shape[1], dt=1)
)
return self