-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvrft_algo.py
256 lines (209 loc) · 7.75 KB
/
vrft_algo.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
# vrft_algo.py - VRFT algorithm implementation
#
# Code author: [Alessio Russo - alessior@kth.se]
# Last update: 10th January 2021, by alessior@kth.se
#
# Copyright (c) [2017-2021] Alessio Russo [alessior@kth.se]. All rights reserved.
# This file is part of PythonVRFT.
# PythonVRFT is free software: you can redistribute it and/or modify
# it under the terms of the MIT License. You should have received a copy of
# the MIT License along with PythonVRFT.
# If not, see <https://opensource.org/licenses/MIT>.
#
from typing import overload
import numpy as np
import scipy as sp
import scipy.signal as scipysig
from vrft.iddata import iddata
from vrft.utils import system_order, check_system, \
filter_signal
@overload
def virtual_reference(data: iddata, L: scipysig.dlti) -> np.ndarray:
"""Compute virtual reference signal by performing signal deconvolution
Parameters
----------
data : iddata
iddata object containing data from experiments
L : scipy.signal.dlti
Discrete transfer function
Returns
-------
r : np.ndarray
virtual reference signal
"""
return virtual_reference(data, L.num, L.den)
def virtual_reference(data: iddata, num: np.ndarray, den: np.ndarray) -> np.ndarray:
"""Compute virtual reference signal by performing signal deconvolution
Parameters
----------
data : iddata
iddata object containing data from experiments
num : np.ndarray
numerator of a discrete transfer function
phi2 : np.ndarray
denominator of a discrete transfer function
Returns
-------
r : np.ndarray
virtual reference signal
"""
try:
check_system(num, den)
except ValueError:
raise ValueError('Error in check system')
M, N = system_order(num, den)
if (N == 0) and (M == 0):
raise ValueError("The reference model can not be a constant.")
data.check()
offset_M = len(num) - M - 1
offset_N = len(den) - N - 1
lag = N - M # number of initial conditions
y0 = data.y0
if y0 is None:
y0 = [0.] * lag
if y0 is not None and (lag != len(y0)):
raise ValueError("Wrong initial condition size.")
reference = np.zeros_like(data.y)
L = len(data.y)
for k in range(0, len(data.y) + lag):
left_side = 0
r = 0
start_i = 0 if k >= M else M - k
start_j = 0 if k >= N else N - k
for i in range(start_i, N + 1):
index = k + i - N
if (index < 0):
left_side += den[offset_N +
abs(i - N)] * y0[abs(index) - 1]
else:
left_side += den[offset_N + abs(i - N)] * (
data.y[index] if index < L else 0)
for j in range(start_j, M + 1):
index = k + j - N
if (start_j != M):
left_side += -num[offset_M + abs(j - M)] * reference[index]
else:
r = num[offset_M]
if (np.isclose(r, 0.0) != True):
reference[k - lag] = left_side / r
else:
reference[k - lag] = 0.0
#add missing data..just copy last N-M points
#for i in range(lag):
# reference[len(self.data.y)+i-lag] =0 #reference[len(self.data.y)+i-1-lag]
return reference[:-lag], len(reference[:-lag])
def compute_vrft_loss(data: iddata, phi: np.ndarray, theta: np.ndarray) -> float:
z = np.dot(phi, theta.T).flatten()
return np.linalg.norm(data.u[:z.size] - z) ** 2 / z.size
def calc_minimum(u: np.ndarray, phi1: np.ndarray,
phi2: np.ndarray = None) -> np.ndarray:
"""Compute least squares minimum
Parameters
----------
u : np.ndarray
Input signal
phi1 : np.ndarray
Regressor
phi2 : np.ndarray, optional
Second regressor (used only with instrumental variables)
Returns
-------
theta : np.ndarray
Coefficients computed for the control basis
"""
phi2 = phi1 if phi2 is None else phi2
return sp.linalg.solve(phi2.T @ phi1, phi2.T.dot(u))
def control_response(data: iddata, error: np.ndarray, control: list) -> np.ndarray:
t_step = data.ts
t = [i * t_step for i in range(len(error))]
phi = [None] * len(control)
for i, c in enumerate(control):
_, y = scipysig.dlsim(c, error, t)
phi[i] = y.flatten()
phi = np.vstack(phi).T
return phi
def compute_vrft(data: iddata, refModel: scipysig.dlti,
control: list, prefilter: scipysig.dlti = None,
iv: bool = False):
"""Compute VRFT Controller
Parameters
----------
data : iddata or list of iddata objects
Data used to identify theta. If iv is set to true,
then the algorithm expects a list of 2 iddata objects
refModel : scipy.signal.dlti
Discrete Transfer Function representing the reference model
control : list
list of discrete transfer functions, representing the control basis
prefilter : scipy.signal.dlti, optional
Filter used to pre-filter the data
iv : bool, optiona;
Instrumental variable option. If true, the instrumental variable will
be constructed based on two iddata objets
Returns
-------
theta : np.ndarray
Coefficients computed for the control basis
r : np.ndarray
Virtual reference signal
loss: float
VRFT loss
final_control: scipy.signal.dlti
Final controller
"""
# Check the data
if not isinstance(data, iddata):
if not isinstance(data, list):
raise ValueError('data should be an iddata object or a list of iddata objects')
else:
if iv and len(data) != 2:
raise ValueError('data should be a list of 2 iddata objects')
for d in data:
if not isinstance(d, iddata):
raise ValueError('data should be a list of iddata objects')
# Prefilter the data
if prefilter is not None and isinstance(prefilter, scipysig.dlti):
if isinstance(data, list):
for i, d in enumerate(data):
data[i] = d.copy().filter(prefilter)
else:
data = data.copy().filter(prefilter)
if not iv:
# No instrumental variable routine
if isinstance(data, list):
data = data[0]
data.check()
# Compute virtual reference
r, n = virtual_reference(data, refModel.num, refModel.den)
# Compute control response given the virtual reference
phi = control_response(data, np.subtract(r, data.y[:n]), control)
# Compute MSE minimizer
theta = calc_minimum(data.u[:n], phi)
else:
# Instrumental variable routine
# Retrieve the two datasets
if isinstance(data, list):
d1 = data[0]
d2 = data[1]
# check if the two datasets have same size
if d1.y.size != d2.y.size:
raise ValueError('The two datasets should have same size!')
else:
raise ValueError('To use IV the data should be a list of iddata objects')
# Compute virtual reference
r1, n1 = virtual_reference(d1, refModel.num, refModel.den)
r2, n2 = virtual_reference(d2, refModel.num, refModel.den)
# Compute control response
phi1 = control_response(d1, np.subtract(r1, d1.y[:n1]), control)
phi2 = control_response(d2, np.subtract(r2, d2.y[:n2]), control)
# We use the first dataset to compute statistics (e.g. VRFT Loss)
phi = phi1
data = data[0]
r = r1
# Compute MSE minimizer
theta = calc_minimum(data.u[:n1], phi1, phi2)
# Compute VRFT loss
loss = compute_vrft_loss(data, phi, theta)
# Final controller
final_control = np.dot(theta, control)
return theta, r, loss, final_control