-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdiff_tvr.py
More file actions
202 lines (156 loc) · 5.9 KB
/
Copy pathdiff_tvr.py
File metadata and controls
202 lines (156 loc) · 5.9 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
import numpy as np
from scipy.linalg import solve
from typing import Tuple
class DiffTVR:
def __init__(self, n: int, dx: float):
"""Differentiate with TVR.
Args:
n (int): Number of points in data.
dx (float): Spacing of data.
"""
self.n = n
self.dx = dx
self.d_mat = self._make_d_mat()
self.a_mat = self._make_a_mat()
self.a_mat_t = self._make_a_mat_t()
def _make_d_mat(self) -> np.array:
"""Make differentiation matrix with central differences. NOTE: not efficient!
Returns:
np.array: N x N+1
"""
arr = np.zeros((self.n,self.n+1))
for i in range(0,self.n):
arr[i,i] = -1.0
arr[i,i+1] = 1.0
return arr / self.dx
# TODO: improve these matrix constructors
def _make_a_mat(self) -> np.array:
"""Make integration matrix with trapezoidal rule. NOTE: not efficient!
Returns:
np.array: N x N+1
"""
arr = np.zeros((self.n+1,self.n+1))
for i in range(0,self.n+1):
if i==0:
continue
for j in range(0,self.n+1):
if j==0:
arr[i,j] = 0.5
elif j<i:
arr[i,j] = 1.0
elif i==j:
arr[i,j] = 0.5
return arr[1:] * self.dx
def _make_a_mat_t(self) -> np.array:
"""Transpose of the integration matirx with trapezoidal rule. NOTE: not efficient!
Returns:
np.array: N+1 x N
"""
smat = np.ones((self.n+1,self.n))
cmat = np.zeros((self.n,self.n))
li = np.tril_indices(self.n)
cmat[li] = 1.0
dmat = np.diag(np.full(self.n,0.5))
vec = np.array([np.full(self.n,0.5)])
combmat = np.concatenate((vec, cmat - dmat))
return (smat - combmat) * self.dx
def make_en_mat(self, deriv_curr : np.array) -> np.array:
"""Diffusion matrix
Args:
deriv_curr (np.array): Current derivative of length N+1
Returns:
np.array: N x N
"""
eps = pow(10,-6)
vec = 1.0/np.sqrt(pow(self.d_mat @ deriv_curr,2) + eps)
return np.diag(vec)
def make_ln_mat(self, en_mat : np.array) -> np.array:
"""Diffusivity term
Args:
en_mat (np.array): Result from make_en_mat
Returns:
np.array: N+1 x N+1
"""
return self.dx * np.transpose(self.d_mat) @ en_mat @ self.d_mat
def make_gn_vec(self, deriv_curr : np.array, data : np.array, alpha : float, ln_mat : np.array) -> np.array:
"""Negative right hand side of linear problem
Args:
deriv_curr (np.array): Current derivative of size N+1
data (np.array): Data of size N
alpha (float): Regularization parameter
ln_mat (np.array): Diffusivity term from make_ln_mat
Returns:
np.array: Vector of length N+1
"""
return self.a_mat_t @ self.a_mat @ deriv_curr - self.a_mat_t @ (data - data[0]) + alpha * ln_mat @ deriv_curr
def make_hn_mat(self, alpha : float, ln_mat : np.array) -> np.array:
"""Matrix in linear problem
Args:
alpha (float): Regularization parameter
ln_mat (np.array): Diffusivity term from make_ln_mat
Returns:
np.array: N+1 x N+1
"""
return self.a_mat_t @ self.a_mat + alpha * ln_mat
def get_deriv_tvr_update(self, data : np.array, deriv_curr : np.array, alpha : float) -> np.array:
"""Get the TVR update
Args:
data (np.array): Data of size N
deriv_curr (np.array): Current deriv of size N+1
alpha (float): Regularization parameter
Returns:
np.array: Update vector of size N+1
"""
n = len(data)
en_mat = self.make_en_mat(
deriv_curr=deriv_curr
)
ln_mat = self.make_ln_mat(
en_mat=en_mat
)
hn_mat = self.make_hn_mat(
alpha=alpha,
ln_mat=ln_mat
)
gn_vec = self.make_gn_vec(
deriv_curr=deriv_curr,
data=data,
alpha=alpha,
ln_mat=ln_mat
)
return solve(hn_mat, -gn_vec)
def get_deriv_tvr(self,
data : np.array,
deriv_guess : np.array,
alpha : float,
no_opt_steps : int,
return_progress : bool = False,
return_interval : int = 1
) -> Tuple[np.array,np.array]:
"""Get derivative via TVR over optimization steps
Args:
data (np.array): Data of size N
deriv_guess (np.array): Guess for derivative of size N+1
alpha (float): Regularization parameter
no_opt_steps (int): No. opt steps to run
return_progress (bool, optional): True to return derivative progress during optimization. Defaults to False.
return_interval (int, optional): Interval at which to store derivative if returning. Defaults to 1.
Returns:
Tuple[np.array,np.array]: First is the final derivative of size N+1, second is the stored derivatives if return_progress=True of size no_opt_steps+1 x N+1, else [].
"""
deriv_curr = deriv_guess
if return_progress:
deriv_st = np.full((no_opt_steps+1, len(deriv_guess)), 0)
else:
deriv_st = np.array([])
for opt_step in range(0,no_opt_steps):
update = self.get_deriv_tvr_update(
data=data,
deriv_curr=deriv_curr,
alpha=alpha
)
deriv_curr += update
if return_progress:
if opt_step % return_interval == 0:
deriv_st[int(opt_step / return_interval)] = deriv_curr
return (deriv_curr, deriv_st)