-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRLS.h
635 lines (579 loc) · 16.1 KB
/
RLS.h
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
#ifndef RLS_H_
#define RLS_H_
#include <vector>
#include <cmath>
#include <cstring>
namespace RLS
{
enum UpdateType : int { CovarianceUpdate=1, SquareRootUpdate=2 };
/**
* @brief Base class for RLS estimators
*
* @tparam T Real number type (float, double, long double)
*/
template < typename T >
class RlsEstimatorBase
{
public:
typedef T ScalarType;
typedef typename std::vector<T> MatrixType;
typedef typename std::vector<T> VectorType;
protected:
int np_; // number of parameters
T cost_; // current cost funtion value
VectorType theta_; // current parameter vector
unsigned long long iter_; // # iterations
public:
explicit RlsEstimatorBase(int n) : np_(n), theta_(n)
{
reset();
}
int np() const { return np_; }
const VectorType& estimatedPar() const { return theta_; }
T cost() const { return cost_; }
void setPar(const VectorType &v) { theta_ = v; }
const unsigned long long & iter() const { return iter_; }
T estimatedOutput(const VectorType &phi) const {
T v = 0;
for(int i=0; i<np_; ++i) v += theta_[i]*phi[i];
return v;
}
void reset() {
iter_ = 0;
cost_ = 0;
std::fill(theta_.begin(), theta_.end(), T(0) );
}
// UpdateType updateType() const { return (UpdateType)Upd_; }
};
template<typename T, class Estimator_>
struct rls_upd_impl;
/**
* @brief Exp weighted RLS estimator with forgetting factor
*
* @tparam T Real number type (float, double, long double)
*/
template <typename T, int Upd_ = CovarianceUpdate>
class ExpWeightedRLS : public RlsEstimatorBase<T>
{
public:
using MatrixType = typename RlsEstimatorBase<T>::MatrixType;
using VectorType = typename RlsEstimatorBase<T>::VectorType;
protected:
T ff_; // Forgetting Factor
T invsqrtff_; // 1/sqrt(ff)
MatrixType P; // Covariance Matrix
VectorType k; // Gain Vector
VectorType u; // temp Vector
using RlsEstimatorBase<T>::theta_;
using RlsEstimatorBase<T>::cost_;
using RlsEstimatorBase<T>::np_;
using RlsEstimatorBase<T>::iter_;
typedef ExpWeightedRLS<T, Upd_> MyT_;
friend struct rls_upd_impl<T, MyT_>;
public:
explicit ExpWeightedRLS(int n, T ff = 0.98, T init_covar = 1)
: RlsEstimatorBase<T>(n), ff_(ff), P(n*n), k(n), u(n)
{
reset(init_covar);
setff(ff);
}
// Update of Parameters with New data (data)
template<typename Vector_>
void update(const Vector_& phi, const T& data)
{
rls_upd_impl<T, MyT_>::update(*this, &phi[0], data);
// Update number of iterations
iter_++;
};
//"Set" Functions//
int setff(T ff)
{
if ((ff > 0) && (ff <= 1.0))
{
ff_ = ff;
invsqrtff_ = 1/std::sqrt(ff_);
return 1;
}
return 0;
};
T ff() { return ff_; }
//"Get" Functions//
const MatrixType &covar() const noexcept { return P; }
const VectorType &gain() const noexcept { return k; }
// Reset Function
void reset(T init_covar = 1) noexcept
{
iter_ = 0;
cost_ = 0;
std::fill(theta_.begin(), theta_.end(), T(0) );
std::fill(k.begin(), k.end(), T(0) );
std::fill(P.begin(), P.end(), T(0) );
for(int i=0; i<np_; ++i)
P[i*(np_+1)] = Upd_==CovarianceUpdate ? init_covar : std::sqrt(init_covar); // P(i,i)=1
};
};
template<typename T>
struct rls_upd_impl<T, ExpWeightedRLS<T, CovarianceUpdate> >
{
typedef ExpWeightedRLS<T, CovarianceUpdate> EstimatorType;
static void update(EstimatorType& E, const T* phi, const T& data) {
const T& ff_ = E.ff_; // Forgetting Factor
typename EstimatorType::MatrixType& P = E.P; // Covariance Matrix
typename EstimatorType::VectorType& k = E.k; // Gain Vector
typename EstimatorType::VectorType& u = E.u; // temp Vector
typename EstimatorType::VectorType& theta_ = E.theta_;
T& cost_ = E.cost_;
const int& np_ = E.np_;
T b = ff_, error = data;
for(int i=0; i<np_; ++i)
{
// u = P * phi
T* p = P.data() + i*np_; // P(i,1)
u[i] = *p * phi[0];
for(int j=1; j<np_; ++j) {
p++;
u[i] += *p * phi[j];
}
// b = ff + phi*u
b += u[i]*phi[i];
// e = y - theta*phi
error -= theta_[i]*phi[i];
}
for(int i=0; i<np_; ++i) {
// Set gain vector
// k = u / (phi.dot(u) + ff_);
k[i] = u[i] / b;
// Calculation of new parameters//
theta_[i] += k[i]*error;
// Calculation of new covariance//
T* p = P.data() + i*(np_ + 1); // P(i,i)
*p -= k[i] * u[i];
*p /= ff_;
for(int j=i-1; j>=0; --j) {
p--;
*p -= k[i] * u[j]; // P(i,j). j<i
*p /= ff_;
P[i+j*np_] = *p; // P(j,i) = P(i,j)
}
}
// calc cost function
cost_ = ff_ * cost_ + error * error;
}
};
template<typename T>
struct rls_upd_impl<T, ExpWeightedRLS<T, SquareRootUpdate> >
{
typedef ExpWeightedRLS<T, SquareRootUpdate> EstimatorType;
static void update(EstimatorType& E, const T* phi, const T& data) {
const T& ff_ = E.ff_; // Forgetting Factor
const T& invsqrtff_ = E.invsqrtff_; // 1/sqrt(ff)
typename EstimatorType::MatrixType& Q = E.P; // square root Covariance Matrix
typename EstimatorType::VectorType& k = E.k; // Gain Vector
typename EstimatorType::VectorType& u = E.u; // temp Vector
typename EstimatorType::VectorType& theta_ = E.theta_;
T& cost_ = E.cost_;
const int& np_ = E.np_;
// algorithm from Ljung & Soederstoem (1987) p. 328
T b = ff_, error = data;
for (int i = 0; i < np_; ++i) {
// u = Q^T*phi
T* q = Q.data() + i; // Q(0,i)
u[i] = *q * phi[0];
for (int j = 1; j < np_; ++j) {
q += np_;
u[i] += *q * phi[j]; // Q(j,i)*phi(j)
}
// b = ff + u^T*u
b += u[i]*u[i];
// e = y - theta*phi
error -= theta_[i]*phi[i];
}
// k = Q*u
for (int i = 0; i < np_; ++i) {
T* q = Q.data() + i*np_; // Q(i,1)
k[i] = *q * u[0];
for (int j = 1; j < np_; ++j) {
q++;
k[i] += *q * u[j];
}
}
// calc cost function
cost_ = ff_ * cost_ + error * error;
// Calculation of new covariance and theta//
T a = 1/(b + std::sqrt(b*ff_));
error /= b;
for (int i = 0; i < np_; i++)
{
// Update parameters//
theta_[i] += k[i]*error;
// Update square root of covariance //
// Q = (Q - a*k*u^T) / sqrt(ff)
T* q = Q.data() + i*np_; // Q(i,1)
k[i] *= a;
*q -= k[i] * u[0];
*q *= invsqrtff_;
for (int j = 1; j < np_; ++j) {
q++;
*q -= k[i] * u[j];
*q *= invsqrtff_;
}
}
}
};
//----------------------------------------------------------------------------//
/**
* @brief Ring buffer object
*
* @tparam T Real number type (float, double, long double)
*/
template <typename T>
class RingBuffer
{
public:
/**
* @brief Construct a new Ring Buffer object
*
* @param n : number of vectors in buffer
* @param w : size of each vector
*/
RingBuffer(int n, int w) : sz_(n), w_(w), buff_(n*w)
{
reset();
}
int size() const { return sz_; }
int width() const { return w_; }
void resize(int n, int w) {
sz_ = n;
w_ = w;
buff_.resize(n*w);
reset();
}
const T* data() const { return buff_.data(); }
void push(const T* v, int n) {
std::memcpy(buff_.data() + i_*w_, v, std::min(width(), n)*sizeof(T));
i_++;
i_ %= size();
}
void push(const T& v) {
buff_[i_*w_] = v;
i_++;
i_ %= size();
}
const T* first() const {
return data() + i_*w_; // i_ points to the first element in the buffer
}
const T* last() const {
return data() + (i_ ? i_ - 1 : size() - 1)*w_; // i_-1 points to the last
}
const T* at(int i) const
{
int j = (i_ + i) % size();
return data() + j*w_;
}
void reset()
{
std::fill(buff_.begin(), buff_.end(), T(0));
i_ = 0;
}
private:
int sz_;
int w_;
std::vector<T> buff_;
int i_;
};
//----------------------------------------------------------------------------//
/**
* @brief Block RLS estimator
*
* RLS estimation is employed on a fixed-size, rolling block of data
*
* @tparam T Real number type (float, double, long double)
*/
template <typename T, int Upd_ = CovarianceUpdate>
class BlockRLS : public RlsEstimatorBase<T>
{
public:
using MatrixType = typename RlsEstimatorBase<T>::MatrixType;
using VectorType = typename RlsEstimatorBase<T>::VectorType;
protected:
RingBuffer<T> phi_buff_, data_buff_; // window storage buffers
MatrixType P; // Covariance Matrix
VectorType k; // Gain Vector
VectorType u; // temporary buffer
using RlsEstimatorBase<T>::theta_;
using RlsEstimatorBase<T>::cost_;
using RlsEstimatorBase<T>::np_;
using RlsEstimatorBase<T>::iter_;
int failedDowndate_;
typedef BlockRLS<T, Upd_> MyT_;
friend struct rls_upd_impl<T, MyT_>;
public:
explicit BlockRLS(int n, int w = 10, T init_covar = 1)
: RlsEstimatorBase<T>(n), phi_buff_(w, n), data_buff_(1, n),
P(n*n), k(n), u(n)
{
reset(init_covar);
setSize(w);
}
template<typename Vector_>
void update(const Vector_& phi, const T& data)
{
rls_upd_impl<T, MyT_>::update(*this, &phi[0], data);
failedDowndate_ = 0;
if (rls_upd_impl<T, MyT_>::downdate(*this,
phi_buff_.first(), *(data_buff_.first())) < 0) {
// TODO
// What happens if downdate fails?
// Which means that the updated P is not positive-definite
failedDowndate_ = 1;
}
// store phi, data in window buffers
phi_buff_.push(phi.data(),np_);
data_buff_.push(data);
iter_++; // Update number of iterations
};
int failedDowndate() const { return failedDowndate_; }
int size() const { return phi_buff_.size(); }
void setSize(int w) {
phi_buff_.resize(w, np_);
data_buff_.resize(w, 1);
VectorType th = theta_;
T c = cost_;
MatrixType P0 = P;
reset();
theta_ = th;
P = P0;
cost_ = c;
}
// Reset Function
void reset(T init_covar = 1) noexcept
{
iter_ = 0;
cost_ = 0;
std::fill(theta_.begin(), theta_.end(), T(0) );
std::fill(k.begin(), k.end(), T(0) );
std::fill(P.begin(), P.end(), T(0) );
for(int i=0; i<np_; ++i)
P[i*(np_+1)] = Upd_==CovarianceUpdate ?
init_covar : std::sqrt(init_covar);
phi_buff_.reset();
data_buff_.reset();
// initialize regressors according to Zhang 2004
VectorType p(np_, T(0));
int i = 0;
for (; i < size() - np_; ++i) phi_buff_.push(p.data(),np_);
for (i = 0; i < np_; ++i)
{
VectorType p1(np_, T(0));
p1[i] = 1 / std::sqrt(init_covar);
phi_buff_.push(p1.data(),np_);
}
};
};
template<typename T>
struct rls_upd_impl<T, BlockRLS<T, CovarianceUpdate> >
{
typedef BlockRLS<T, CovarianceUpdate> EstimatorType;
static void update(EstimatorType& E, const T* phi, const T& data) {
typename EstimatorType::MatrixType& P = E.P; // Covariance Matrix
typename EstimatorType::VectorType& k = E.k; // Gain Vector
typename EstimatorType::VectorType& u = E.u; // temp Vector
typename EstimatorType::VectorType& theta_ = E.theta_;
T& cost_ = E.cost_;
const int& np_ = E.np_;
T b(1), error(data), error2(data);
for(int i=0; i<np_; ++i)
{
// u = P * phi
T* p = P.data() + i*np_; // P(i,1)
u[i] = *p * phi[0];
for(int j=1; j<np_; ++j) {
p++;
u[i] += *p * phi[j];
}
// b = 1 + phi*u
b += u[i]*phi[i];
// e = y - theta*phi
error -= theta_[i]*phi[i];
}
b = 1/b;
cost_ += error*error*b*(1-b);
for(int i=0; i<np_; ++i) {
// Set gain vector
// k = u / (phi.dot(u) + 1);
k[i] = u[i] * b;
// Calculation of new parameters//
theta_[i] += k[i]*error;
// e = y - theta*phi
error2 -= theta_[i]*phi[i];
// Calculation of new covariance//
T* p = P.data() + i*(np_ + 1); // P(i,i)
*p -= k[i] * u[i];
for(int j=i-1; j>=0; --j) {
p--;
*p -= k[i] * u[j]; // P(i,j). j<i
P[i+j*np_] = *p; // P(j,i) = P(i,j)
}
}
cost_ += error2*error2;
}
static int downdate(EstimatorType& E, const T* phn, const T& data) {
typename EstimatorType::MatrixType& P = E.P; // Covariance Matrix
typename EstimatorType::VectorType& k = E.k; // Gain Vector
typename EstimatorType::VectorType& u = E.u; // temp Vector
typename EstimatorType::VectorType& theta_ = E.theta_;
T& cost_ = E.cost_;
const int& np_ = E.np_;
T b(1), error(data), error2(data);
for(int i=0; i<np_; ++i)
{
// u = P * phi
T* p = P.data() + i*np_; // P(i,1)
u[i] = *p * phn[0];
for(int j=1; j<np_; ++j) {
p++;
u[i] += *p * phn[j];
}
// b = 1 - phi*u
b -= u[i]*phn[i];
// e = y - theta*phi
error -= theta_[i]*phn[i];
}
if (b==T(0)) return -1;
b = 1/b;
cost_ -= error*error*b*(1-b);
for(int i=0; i<np_; ++i) {
// Set gain vector
// k = u / (phi.dot(u) + 1);
k[i] = u[i] * b;
// Calculation of new parameters//
theta_[i] -= k[i]*error;
// e = y - theta*phi
error2 -= theta_[i]*phn[i];
// Calculation of new covariance//
T* p = P.data() + i*(np_ + 1); // P(i,i)
*p += k[i] * u[i];
for(int j=i-1; j>=0; --j) {
p--;
*p += k[i] * u[j]; // P(i,j). j<i
P[i+j*np_] = *p; // P(j,i) = P(i,j)
}
}
cost_ -= error2*error2;
return 0;
}
};
template<typename T>
struct rls_upd_impl<T, BlockRLS<T, SquareRootUpdate> >
{
typedef BlockRLS<T, SquareRootUpdate> EstimatorType;
static void update(EstimatorType& E, const T* phi, const T& data) {
typename EstimatorType::MatrixType& Q = E.P; // Square roor Covariance Matrix
typename EstimatorType::VectorType& k = E.k; // Gain Vector
typename EstimatorType::VectorType& u = E.u; // temp Vector
typename EstimatorType::VectorType& theta_ = E.theta_;
T& cost_ = E.cost_;
const int& np_ = E.np_;
T b(1), error(data), error2(data);
for(int i=0; i<np_; ++i)
{
// u = Q^T*phi
T* q = Q.data() + i; // Q(0,i)
u[i] = *q * phi[0];
for (int j = 1; j < np_; ++j) {
q += np_;
u[i] += *q * phi[j]; // Q(j,i)*phi(j)
}
// b = 1 + u^T*u
b += u[i]*u[i];
// e = y - theta*phi
error -= theta_[i]*phi[i];
}
// k = Q*u
for (int i = 0; i < np_; ++i) {
T* q = Q.data() + i*np_; // Q(i,1)
k[i] = *q * u[0];
for (int j = 1; j < np_; ++j) {
q++;
k[i] += *q * u[j];
}
}
b = 1/b;
cost_ += error*error*b*(1-b);
T a = b/(1 + std::sqrt(b));
error *= b;
for(int i=0; i<np_; ++i) {
// Calculation of new parameters//
theta_[i] += k[i]*error;
// e = y - theta*phi
error2 -= theta_[i]*phi[i];
// Update square root of covariance //
// Q = (Q - a*k*u^T)
T* q = Q.data() + i*np_; // Q(i,1)
k[i] *= a;
*q -= k[i] * u[0];
for (int j = 1; j < np_; ++j) {
q++;
*q -= k[i] * u[j];
}
}
cost_ += error2*error2;
}
static int downdate(EstimatorType& E, const T* phi, const T& data) {
typename EstimatorType::MatrixType& Q = E.P; // Square roor Covariance Matrix
typename EstimatorType::VectorType& k = E.k; // Gain Vector
typename EstimatorType::VectorType& u = E.u; // temp Vector
typename EstimatorType::VectorType& theta_ = E.theta_;
T& cost_ = E.cost_;
const int& np_ = E.np_;
T b(1), error(data), error2(data);
for(int i=0; i<np_; ++i)
{
// u = Q^T*phi
T* q = Q.data() + i; // Q(0,i)
u[i] = *q * phi[0];
for (int j = 1; j < np_; ++j) {
q += np_;
u[i] += *q * phi[j]; // Q(j,i)*phi(j)
}
// b = 1 - u^T*u
b -= u[i]*u[i];
// e = y - theta*phi
error -= theta_[i]*phi[i];
}
if (b <= T(0)) return -1;
// k = Q*u
for (int i = 0; i < np_; ++i) {
T* q = Q.data() + i*np_; // Q(i,1)
k[i] = *q * u[0];
for (int j = 1; j < np_; ++j) {
q++;
k[i] += *q * u[j];
}
}
b = 1/b;
cost_ -= error*error*b*(1-b);
T a = b/(1 + std::sqrt(b));
error *= b;
for(int i=0; i<np_; ++i) {
// Calculation of new parameters//
theta_[i] -= k[i]*error;
// e = y - theta*phi
error2 -= theta_[i]*phi[i];
// Update square root of covariance //
// Q = (Q - a*k*u^T)
T* q = Q.data() + i*np_; // Q(i,1)
k[i] *= a;
*q += k[i] * u[0];
for (int j = 1; j < np_; ++j) {
q++;
*q += k[i] * u[j];
}
}
cost_ -= error2*error2;
return 0;
}
};
//----------------------------------------------------------------------------//
} // namespace RLS
#endif