forked from PyDMD/PyDMD
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathpidmd_utils.py
More file actions
367 lines (317 loc) · 12.5 KB
/
pidmd_utils.py
File metadata and controls
367 lines (317 loc) · 12.5 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
"""
PiDMD utilities module.
References:
- Peter J. Baddoo, Benjamin Herrmann, Beverley J. McKeon, J. Nathan Kutz, and
Steven L. Brunton. Physics-informed dynamic mode decomposition (pidmd). 2021.
arXiv:2112.04307.
"""
import numpy as np
from numpy.fft import fft, fft2, ifft
from scipy import sparse
from scipy.linalg import block_diag, rq
from .utils import compute_rank, compute_svd
def compute_unitary(X, Y, svd_rank):
"""
Given the data matrices X and Y and the rank truncation svd_rank, solves
for the best-fit unitary operator A that solves the relationship Y = AX.
Returns a dictionary containing the corresponding reduced operator atilde.
"""
Ux = compute_svd(X, svd_rank)[0]
Yproj = Ux.conj().T.dot(Y)
Xproj = Ux.conj().T.dot(X)
Uyx, _, Vyx = compute_svd(Yproj.dot(Xproj.conj().T), -1)
atilde = Uyx.dot(Vyx.conj().T)
return {"atilde": atilde}
def compute_uppertriangular(X, Y):
"""
Given the data matrices X and Y, solves for the best-fit
uppertriangular matrix A that solves the relationship Y = AX.
Returns a dictionary containing A.
"""
R, Q = rq(X, mode="economic")
Ut = np.triu(Y.dot(Q.conj().T))
A = np.linalg.lstsq(R.T, Ut.T, rcond=None)[0].T
return {"A": A}
def compute_diagonal(X, Y, svd_rank, manifold_opt, compute_A):
"""
Given the data matrices X and Y and the rank truncation svd_rank, solves
for the best-fit matrix A that solves the relationship Y = AX and has
diagonal entries specified by manifold_opt. Only the eigenvalues and
eigenvectors of A are computed if the compute_A flag is not True.
Returns a dictionary of computed values.
"""
# Specify the index matrix for the diagonals of A.
nx = len(X)
if manifold_opt is None:
ind_mat = np.ones((nx, 2), dtype=int)
elif isinstance(manifold_opt, int) and manifold_opt > 0:
ind_mat = manifold_opt * np.ones((nx, 2), dtype=int)
elif (
isinstance(manifold_opt, tuple)
and len(manifold_opt) == 2
and np.all(np.array(manifold_opt) > 0)
):
ind_mat = np.ones((nx, 2))
ind_mat[:, 0] *= manifold_opt[0]
ind_mat[:, 1] *= manifold_opt[1]
elif (
isinstance(manifold_opt, np.ndarray)
and manifold_opt.shape == (nx, 2)
and np.all(manifold_opt > 0)
):
ind_mat = manifold_opt
else:
raise ValueError("manifold_opt is not in an allowable format.")
# Keep track of info for building A as a sparse coordinate matrix.
I = []
J = []
R = []
# Solve min||Cx-b|| along each row.
nxs = np.arange(nx)
l1s = (nxs - ind_mat[:, 0] + 1).clip(min=0).astype(int)
l2s = (nxs + ind_mat[:, 1]).clip(max=nx).astype(int)
for j in range(nx):
l1, l2 = l1s[j], l2s[j]
C = X[l1:l2].T
b = Y[j].T
I.append(j * np.ones(l2 - l1))
J.append(np.arange(l1, l2))
R.append(np.linalg.lstsq(C, b, rcond=None)[0].T)
# Build A as a sparse matrix.
A_sparse = sparse.coo_matrix(
(np.hstack(R), (np.hstack(I), np.hstack(J))), shape=(nx, nx)
)
if compute_A:
return {"A": A_sparse.toarray()}
r = compute_rank(X, svd_rank)
eigenvalues, modes = sparse.linalg.eigs(A_sparse, k=r)
return {"eigenvalues": eigenvalues, "modes": modes}
def compute_symmetric(X, Y, svd_rank, skew_symmetric=False):
"""
Given the data matrices X and Y and the rank truncation svd_rank, solves
for the best-fit symmetric (or skew-symmetric) operator A that solves the
relationship Y = AX. Returns a dictionary containing the corresponding
reduced operator atilde.
"""
U, s, V = compute_svd(X, -1)
C = np.linalg.multi_dot([U.conj().T, Y, V])
r = compute_rank(X, svd_rank)
if skew_symmetric:
atilde = 1j * np.diag(np.diagonal(C).imag / s)[:r, :r]
for i in range(r):
for j in range(i + 1, r):
atilde[i, j] = -s[i] * np.conj(C[j, i]) + s[j] * C[i, j]
atilde[i, j] /= s[i] ** 2 + s[j] ** 2
atilde += -atilde.conj().T - 1j * np.diag(np.diag(atilde.imag))
else: # symmetric
atilde = np.diag(np.diagonal(C).real / s)[:r, :r]
for i in range(r):
for j in range(i + 1, r):
atilde[i, j] = s[i] * np.conj(C[j, i]) + s[j] * C[i, j]
atilde[i, j] /= s[i] ** 2 + s[j] ** 2
atilde += atilde.conj().T - np.diag(np.diag(atilde.real))
return {"atilde": atilde}
def compute_toeplitz(X, Y, flipped=False):
"""
Given the data matrices X and Y, solves for the best-fit toeplitz operator
A (or hankel operator if flipped = True) that solves the relationship
Y = AX. Returns a dictionary containing A.
"""
nx, nt = X.shape
if flipped: # hankel
J = np.fliplr(np.eye(nx))
else: # toeplitz
J = np.eye(nx)
# Define left and right matrices.
Am = fft(np.hstack([np.eye(nx), np.zeros((nx, nx))]).T, axis=0)
Am = Am.conj().T / np.sqrt(2 * nx)
B = fft(np.hstack([J.dot(X).conj().T, np.zeros((nt, nx))]).T, axis=0)
B = B.conj().T / np.sqrt(2 * nx)
# Compute AA* and B*B (fast computation of AA*).
AAt = ifft(
fft(
np.vstack(
[
np.hstack([np.eye(nx), np.zeros((nx, nx))]),
np.zeros((nx, 2 * nx)),
]
),
axis=0,
).T,
axis=0,
).T
# Solve linear system y = dL.
y = np.diag(np.linalg.multi_dot([Am.conj().T, Y.conj(), B])).conj().T
L = np.multiply(AAt, B.conj().T.dot(B).T).conj().T
eigenvalues = np.linalg.lstsq(L[:-1, :-1].T, y[:-1], rcond=None)[0]
eigenvalues = np.append(eigenvalues, 0)
# Convert eigenvalues into circulant matrix.
new_A = ifft(fft(np.diag(eigenvalues), axis=0).T, axis=0).T
# Extract toeplitz matrix from the circulant matrix.
A = new_A[:nx, :nx].dot(J)
return {"A": A}
def compute_circulant(X, Y, circulant_opt, svd_rank, compute_A):
"""
Given the data matrices X and Y and the rank truncation svd_rank, solves
for the best-fit circulant matrix A that solves the relationship Y = AX and
satisfies any additional conditions set by circulant_opt. Only the
eigenvalues and eigenvectors of A are computed if the compute_A
flag is not True. Returns a dictionary of computed values.
"""
nx = len(X)
fX = fft(X, axis=0)
fY = fft(Y.conj(), axis=0)
fX_norm = np.linalg.norm(fX, axis=1)
eigenvalues = np.divide(np.diag(fX.dot(fY.conj().T)), fX_norm**2)
if circulant_opt == "unitary":
eigenvalues = np.exp(1j * np.angle(eigenvalues))
elif circulant_opt == "symmetric":
eigenvalues = eigenvalues.real
elif circulant_opt == "skewsymmetric":
eigenvalues = 1j * eigenvalues.imag
# Remove the least important eigenvalues.
r = compute_rank(X, svd_rank)
res = np.divide(
np.diag(np.abs(fX.dot(fY.conj().T))),
np.linalg.norm(fX.conj().T, 2, axis=0).T,
)
ind_exclude = np.argpartition(res, nx - r)[: nx - r]
eigenvalues[ind_exclude] = 0
if compute_A:
A = fft(np.multiply(eigenvalues, ifft(np.eye(nx), axis=0).T).T, axis=0)
return {"A": A}
eigenvalues = np.delete(eigenvalues, ind_exclude)
modes = np.delete(fft(np.eye(nx), axis=0), ind_exclude, axis=1)
return {"eigenvalues": eigenvalues, "modes": modes}
def compute_symtridiagonal(X, Y, svd_rank, compute_A):
"""
Given the data matrices X and Y and the rank truncation svd_rank, solves
for the best-fit symmetric tridiagonal matrix A that solves Y = AX.
Only the eigenvalues and eigenvectors of A are computed if the compute_A
flag is not True. Returns a dictionary of computed values.
"""
# Form the leading block.
nx = len(X)
T1e = np.linalg.norm(X, axis=1) ** 2
T1 = sparse.diags(T1e)
# Form the second and third blocks.
T2e = np.diag(X[1:].dot(X[:-1].T))
T2 = sparse.spdiags([T2e, T2e], diags=[-1, 0], m=nx, n=nx - 1)
# Form the final block.
T3e = np.insert(np.diag(X[2:].dot(X[:-2].T)), 0, 0)
T3_offdiag = sparse.spdiags(T3e, diags=1, m=nx - 1, n=nx - 1)
T3 = (
sparse.spdiags(T1e[:-1] + T1e[1:], diags=0, m=nx - 1, n=nx - 1)
+ T3_offdiag
+ T3_offdiag.conj().T
)
# Form the symmetric block-tridiagonal matrix T = [T1 T2; T2* T3].
T = sparse.vstack(
[sparse.hstack([T1, T2]), sparse.hstack([T2.conj().T, T3])]
)
# Solve for c in the system Tc = d.
d = np.concatenate(
(
np.diag(X.dot(Y.T)),
np.diag(X[:-1].dot(Y[1:].T)) + np.diag(X[1:].dot(Y[:-1].T)),
),
axis=None,
)
c = sparse.linalg.lsqr(T.real, d.real)[0]
# Form the solution matrix A.
A_sparse = (
sparse.diags(c[:nx])
+ sparse.spdiags(np.insert(c[nx:], 0, 0), diags=1, m=nx, n=nx)
+ sparse.spdiags(np.append(c[nx:], 0), diags=-1, m=nx, n=nx)
)
if compute_A:
return {"A": A_sparse.toarray()}
r = compute_rank(X, svd_rank)
eigenvalues, modes = sparse.linalg.eigs(A_sparse, k=r)
return {"eigenvalues": eigenvalues, "modes": modes}
def compute_BCCB(X, Y, block_shape, bccb_opt, svd_rank):
"""
Given the data matrices X and Y and the rank truncation svd_rank, solves
for the best-fit BCCB (block circulant with circulant blocks) matrix A that
solves the relationship Y = AX. The blocks of A will have the shape
block_shape and A will have the additional matrix property given by
bccb_opt. Returns a dictionary containing A.
"""
def fft_block2d(X):
"""
Helper method that, given a 2D numpy array X, reshapes the
columns of X into arrays of shape block_shape, computes the
2D discrete Fourier Transform, and returns the resulting
FFT matrix restored to the original X shape and scaled
according to the length of the columns of X.
"""
m, n = X.shape
Y = X.reshape(*block_shape, n, order="F")
Y_fft2 = fft2(Y, axes=(0, 1))
return Y_fft2.reshape(m, n, order="F") / np.sqrt(m)
nx = len(X)
fX = fft_block2d(X.conj())
fY = fft_block2d(Y.conj())
d = np.zeros(nx, dtype="complex")
if not bccb_opt:
for j in range(nx):
d[j] = np.dot(fX[j], fY[j].conj()).conj()
d[j] /= np.linalg.norm(fX[j].conj(), 2) ** 2
else:
for j in range(nx):
dp = np.linalg.lstsq(fX[j, :, None], fY[j, :, None], rcond=None)[0][
0
][0]
if bccb_opt == "unitary":
d[j] = np.exp(1j * np.angle(dp))
elif bccb_opt == "symmetric":
d[j] = dp.real
else: # skewsymmetric
d[j] = 1j * dp.imag
# Remove the least important eigenvalues.
r = compute_rank(X, svd_rank)
res = np.divide(
np.diag(np.abs(fX.dot(fY.conj().T))),
np.linalg.norm(fX.conj().T, 2, axis=0).T,
)
d[np.argpartition(res, nx - r)[: nx - r]] = 0
A = fft_block2d(np.multiply(d.conj(), fft_block2d(np.eye(nx)).conj().T).T)
return {"A": A}
def compute_BC(X, Y, block_shape, tridiagonal_blocks=False):
"""
Given the data matrices X and Y, solves for the best-fit block circulant
matrix A that solves the relationship Y = AX. The blocks of A will have the
shape block_shape and will be tridiagonal if tridiagonal_blocks is True.
Returns a dictionary containing A.
"""
def fft_block(X):
"""
Helper method that, given a 2D numpy array X, reshapes the
columns of X into arrays of shape block_shape, computes the
1D discrete Fourier Transform, and returns the resulting
FFT matrix restored to the original X shape and scaled
according to the number of columns per block.
"""
m, n = X.shape
Y = X.reshape(*block_shape, n, order="F")
Y_fft = fft(Y, axis=1)
return Y_fft.reshape(m, n, order="F") / np.sqrt(block_shape[1])
nx = len(X)
fX = fft_block(X)
fY = fft_block(Y)
d = []
for j in range(block_shape[1]):
ls = (j * block_shape[0]) + np.arange(block_shape[0])
if tridiagonal_blocks:
d.append(
compute_diagonal(
fX[ls], fY[ls], svd_rank=-1, manifold_opt=2, compute_A=True
)["A"]
)
else:
d.append(np.linalg.lstsq(fX[ls].T, fY[ls].T, rcond=None)[0].T)
# Update self._A to be the full block circulant matrix.
BD = block_diag(*d)
fI = fft_block(np.eye(nx))
A = fft_block(BD.dot(fI).conj()).conj()
return {"A": A}