forked from RhysU/ar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ar.hpp
2764 lines (2468 loc) · 96 KB
/
ar.hpp
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) 2012, 2013 Rhys Ulerich
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef AR_HPP
#define AR_HPP
#ifndef AR_SUPPRESS_DOXYGEN_MAINPAGE
/**
* @mainpage
*
* \ref ar implements \ref ar "modeling tools" for autoregressive processes in
* header-only C++.
*
* See the current <a
* href="https://github.com/RhysU/ar/blob/master/README.rst"> README</a> for a
* more detailed overview and http://github.com/RhysU/ar for project
* information.
*
* If you find these tools useful towards publishing research, please consider
* citing:
* \li Todd A. Oliver, Nicholas Malaya, Rhys Ulerich, and Robert D. Moser.
* "Estimating uncertainties in statistics computed from direct numerical
* simulation." Physics of Fluids 26 (March 2014): 035101+.
* http://dx.doi.org/10.1063/1.4866813
*/
#endif /* AR_SUPPRESS_DOXYGEN_MAINPAGE */
/** @file
* Autoregressive process modeling tools in header-only C++.
*/
#include <algorithm>
#include <cassert>
#include <cmath>
#include <functional>
#include <iterator>
#include <limits>
#include <numeric>
#include <stdexcept>
#include <string>
#include <vector>
/**
* Autoregressive process modeling tools in header-only C++.
*
* All routines estimate and/or evaluate autoregressive models of the form
* \f{align}{
* x_n + a_1 x_{n - 1} + \dots + a_p x_{n - p} &= \epsilon_n
* &
* \epsilon_n &\sim{} N\left(0, \sigma^2_\epsilon\right)
* \\
* \sigma^2_x \left(
* \rho_0 + a_1 \rho_{1} + \dots + a_p \rho_{p}
* \right) &= \sigma^2_\epsilon
* &
* \rho_0 &= 1
* \\
* \rho_k + a_1 \rho_{k-1} + \dots + a_p \rho_{k-p} &= 0
* &
* k &\geq{} p
* \f}
* where \f$x_i\f$ are the process values, \f$a_i\f$ are the model parameters,
* and \f$\rho_i\f$ are the lag \f$i\f$ autocorrelations. The white noise
* input process \f$\epsilon_n\f$ has variance \f$\sigma^2_\epsilon\f$. The
* model has output variance \f$\sigma^2_x\f$ and therefore a gain equal to
* \f$\sigma^2_x / \sigma^2_\epsilon\f$.
*/
namespace ar
{
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/**
* Preprocessor macros to simplify implementation.
*
* @{
*/
/** Helper for defining GCC version checks. */
#define AR_GCC_VERSION \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
/** Helper macro for implementing \ref AR_STRINGIFY. */
#define AR_STRINGIFY_HELPER(x) #x
/** Expand and stringify the provided argument. */
#define AR_STRINGIFY(x) AR_STRINGIFY_HELPER(x)
/**
* Ensure that \c expr evaluates to boolean \c true at runtime. If \c expr
* evaluates to boolean \c false, then an exception \c except is thrown with
* message \c msg.
*
* This macro is intended for <tt>assert</tt>-like checks which should always
* be performed regardless of whether or not \c NDEBUG is <tt>#define</tt>d.
*/
#define AR_ENSURE_MSGEXCEPT(expr, msg, except) \
if (!(expr)) throw except(msg)
/**
* Ensure that \c expr evaluates to boolean \c true at runtime. If \c expr
* evaluates to boolean \c false, then a <tt>std::logic_error</tt> is thrown
* with message \c msg.
*
* This macro is intended for <tt>assert</tt>-like checks which should always
* be performed regardless of whether or not \c NDEBUG is <tt>#define</tt>d.
*/
#define AR_ENSURE_MSG(expr, msg) \
AR_ENSURE_MSGEXCEPT(expr, msg, std::logic_error)
/**
* Ensure that \c expr evaluates to boolean \c true at runtime. If \c expr
* evaluates to boolean \c false, then a <tt>std::logic_error</tt> is thrown.
*
* This macro is intended for <tt>assert</tt>-like checks which should always
* be performed regardless of whether or not \c NDEBUG is <tt>#define</tt>d.
*/
#define AR_ENSURE(expr) \
AR_ENSURE_MSG(expr, AR_STRINGIFY(expr)" false")
/**
* Ensure that the argument-related \c expr evaluates to boolean \c true at
* runtime. If \c expr evaluates to boolean \c false, then a
* <tt>std::invalid_argument</tt> is thrown.
*
* This macro is intended for <tt>assert</tt>-like checks which should always
* be performed regardless of whether or not \c NDEBUG is <tt>#define</tt>d.
*/
#define AR_ENSURE_ARG(expr) \
AR_ENSURE_MSGEXCEPT(expr, AR_STRINGIFY(expr)" false", std::invalid_argument)
/**
* Ensure that \c expr evaluates to boolean \c true at runtime. If \c expr
* evaluates to boolean \c false, then an exception \c except is thrown.
*
* This macro is intended for <tt>assert</tt>-like checks which should always
* be performed regardless of whether or not \c NDEBUG is <tt>#define</tt>d.
*/
#define AR_ENSURE_EXCEPT(expr, except) \
AR_ENSURE_MSGEXCEPT(expr, AR_STRINGIFY(expr)" false", except)
/**
* @}
*/
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/**
* Stable, one-pass algorithms for computing variances and covariances.
*
* @{
*/
/**
* Compute the mean and the number of samples, N, times the population variance
* using Welford's algorithm. The latter quantity is effectively the centered
* sum of squares. The algorithm is found in Knuth's TAOCP volume 2 section
* 4.2.2.A on page 232. The implementation follows
* http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance.
*
* @param[in] first Beginning of the input data range.
* @param[in] last Exclusive end of the input data range.
* @param[out] mean Mean of the data in <tt>[first, last)</tt>.
* @param[out] nvar N times the variance of the data.
*
* @returns the number data values processed within <tt>[first, last)</tt>.
*/
template <typename InputIterator,
typename OutputType1,
typename OutputType2>
std::size_t welford_nvariance(InputIterator first,
InputIterator last,
OutputType1& mean,
OutputType2& nvar)
{
using std::iterator_traits;
using std::size_t;
typedef typename iterator_traits<InputIterator>::value_type value;
size_t N = 1; // Running next sample number
value m = 0; // Running mean of data thus far
value nv = 0; // Running variance times the number of samples
while (first != last)
{
value x = *first++;
value d = x - m;
m += d / N++;
nv += d*(x - m);
}
mean = m;
nvar = nv;
return N-1;
}
/**
* Compute the mean and population variance using Welford's algorithm.
*
* @param[in] first Beginning of the input data range.
* @param[in] last Exclusive end of the input data range.
* @param[out] mean Mean of the data in <tt>[first, last)</tt>.
* @param[out] var The population variance of the data.
*
* @returns N, the number data values processed within <tt>[first, last)</tt>.
*/
template <typename InputIterator,
typename OutputType1,
typename OutputType2>
std::size_t welford_variance_population(InputIterator first,
InputIterator last,
OutputType1& mean,
OutputType2& var)
{
using std::size_t;
size_t N = welford_nvariance(first, last, mean, var);
var /= N;
return N;
}
/**
* Compute the mean and sample variance using Welford's algorithm.
*
* @param[in] first Beginning of the input data range.
* @param[in] last Exclusive end of the input data range.
* @param[out] mean Mean of the data in <tt>[first, last)</tt>.
* @param[out] var The sample variance of the data.
*
* @returns N, the number data values processed within <tt>[first, last)</tt>.
*/
template <typename InputIterator,
typename OutputType1,
typename OutputType2>
std::size_t welford_variance_sample(InputIterator first,
InputIterator last,
OutputType1& mean,
OutputType2& var)
{
using std::size_t;
size_t N = welford_nvariance(first, last, mean, var);
var /= (N - 1);
return N;
}
/**
* Compute means and the number of samples, N, times the population covariance
* using Welford's algorithm. The implementation follows the covariance
* section of http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance.
*
* @param[in] first1 Beginning of the first input range.
* @param[in] last1 Exclusive end of first input range.
* @param[in] first2 Beginning of the second input range.
* @param[out] mean1 Mean of the first data set.
* @param[out] mean2 Mean of the second data set.
* @param[out] ncovar N times the covariance of the two sets.
*
* @returns the number data values processed within <tt>[first1, last1)</tt>.
*/
template <typename InputIterator1,
typename InputIterator2,
typename OutputType1,
typename OutputType2,
typename OutputType3>
std::size_t welford_ncovariance(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
OutputType1& mean1,
OutputType2& mean2,
OutputType3& ncovar)
{
using std::iterator_traits;
using std::size_t;
typedef typename iterator_traits<InputIterator1>::value_type value1;
typedef typename iterator_traits<InputIterator2>::value_type value2;
size_t N = 1; // Running next sample number
value1 m1 = 0; // Running mean of first data set thus far
value2 m2 = 0; // Running mean of second data set thus far
OutputType3 nc = 0; // Running covariance times the number of samples
while (first1 != last1)
{
value1 x1 = *first1++;
value1 d1 = x1 - m1;
m1 += d1 / N;
value2 x2 = *first2++;
value2 d2 = x2 - m2;
m2 += d2 / N;
nc += d1*(x2 - m2);
++N;
}
mean1 = m1;
mean2 = m2;
ncovar = nc;
return N-1;
}
/**
* Compute means and the population covariance using Welford's algorithm.
*
* @param[in] first1 Beginning of the first input range.
* @param[in] last1 Exclusive end of first input range.
* @param[in] first2 Beginning of the second input range.
* @param[out] mean1 Mean of the first data set.
* @param[out] mean2 Mean of the second data set.
* @param[out] covar The covariance of the two sets.
*
* @returns the number data values processed within <tt>[first1, last1)</tt>.
*/
template <typename InputIterator1,
typename InputIterator2,
typename OutputType1,
typename OutputType2,
typename OutputType3>
std::size_t welford_covariance_population(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
OutputType1& mean1,
OutputType2& mean2,
OutputType3& covar)
{
using std::size_t;
size_t N = welford_ncovariance(first1, last1, first2, mean1, mean2, covar);
covar /= N;
return N;
}
/**
* Compute means and the sample covariance using Welford's algorithm.
*
* @param[in] first1 Beginning of the first input range.
* @param[in] last1 Exclusive end of first input range.
* @param[in] first2 Beginning of the second input range.
* @param[out] mean1 Mean of the first data set.
* @param[out] mean2 Mean of the second data set.
* @param[out] covar The covariance of the two sets.
*
* @returns the number data values processed within <tt>[first1, last1)</tt>.
*/
template <typename InputIterator1,
typename InputIterator2,
typename OutputType1,
typename OutputType2,
typename OutputType3>
std::size_t welford_covariance_sample(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
OutputType1& mean1,
OutputType2& mean2,
OutputType3& covar)
{
using std::size_t;
size_t N = welford_ncovariance(first1, last1, first2, mean1, mean2, covar);
covar /= (N - 1);
return N;
}
/**
* Compute the inner product of <tt>[first, last)</tt> with itself using \ref
* welford_nvariance. Welford's algorithm is combined with the linearity of
* the expectation operator to compute a more expensive but also more
* numerically stable result than can be had using <tt>std::inner_product</tt>.
*
* @param[in] first Beginning of the input data range.
* @param[in] last Exclusive end of the input data range.
* @param[in] init Initial value, often zero, establishing the result type.
*
* @returns The inner product of <tt>[first, last)</tt> with itself.
*/
template <typename InputIterator,
typename ValueType>
ValueType welford_inner_product(InputIterator first,
InputIterator last,
ValueType init)
{
typename std::iterator_traits<InputIterator>::value_type mean;
ValueType nvar;
const std::size_t N = welford_nvariance(first, last, mean, nvar);
return init + (nvar + N*(mean*mean));
}
/**
* Compute the inner product of <tt>[first1, last1)</tt> against <tt>[first2,
* ...)</tt> using \ref welford_ncovariance. Welford's algorithm is combined
* with the linearity of the expectation operator to compute a more expensive
* but also numerically stable result than can be had using
* <tt>std::inner_product</tt>.
*
* @param[in] first1 Beginning of the first input range.
* @param[in] last1 Exclusive end of first input range.
* @param[in] first2 Beginning of the second input range.
* @param[in] init Initial value, often zero, establishing the result type.
*
* @returns The inner product of <tt>[first1, last1)</tt> against
* <tt>[first2, ...)</tt>.
*/
template <typename InputIterator1,
typename InputIterator2,
typename ValueType>
ValueType welford_inner_product(InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
ValueType init)
{
typename std::iterator_traits<InputIterator1>::value_type mean1;
typename std::iterator_traits<InputIterator2>::value_type mean2;
ValueType ncovar;
const std::size_t N = welford_ncovariance(
first1, last1, first2, mean1, mean2, ncovar);
return init + (ncovar + N*(mean1*mean2));
}
/**
* @}
*/
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/**
* Algorithms for autoregressive parameter estimation and manipulation.
*
* @{
*/
#if _MSC_VER > 1400
# pragma float_control(push)
# pragma float_control(precise, on)
#endif
/**
* Robustly compute negative one half the reflection coefficient assuming
* \f$\vec{a}\f$ and \f$\vec{b}\f$ contain real-valued backward and forward
* prediction error sequences, respectively. Zero is returned whenever the
* reflection coefficient numerator is identically zero, as otherwise
* constant zero signals produce undesired NaN reflection coefficients.
* The constant zero special case does not defeat NaN detection as any data
* introducing NaN into the denominator must introduce NaN into the numerator.
*
* @param[in] a_first Beginning of the first input range \f$\vec{a}\f$.
* @param[in] a_last Exclusive end of first input range \f$\vec{a}\f$.
* @param[in] b_first Beginning of the second input range \f$\vec{b}\f$.
*
* @return \f$\frac{\vec{a}\cdot\vec{b}}
* {\vec{a}\cdot\vec{a} + \vec{b}\cdot\vec{b}}\f$
* when that numerator is nonzero, else zero.
*
* @see Wikipedia's article on <a href="">Kahan summation</a> for
* background on how the accumulation error is reduced in the result.
*/
template <typename ValueType,
typename InputIterator1,
typename InputIterator2>
ValueType
#if (AR_GCC_VERSION > 40305)
__attribute__((__optimize__("no-associative-math")))
#endif
negative_half_reflection_coefficient(InputIterator1 a_first,
InputIterator1 a_last,
InputIterator2 b_first)
#if (AR_GCC_VERSION > 40305) || (_MSC_VER > 1400)
{
ValueType ns = 0, nt, nc = 0, ny; // Kahan numerator accumulation
ValueType ds = 0, dt, dc = 0, dy; // Kahan denominator accumulation
while (a_first != a_last)
{
ValueType xa = *a_first++; // Denominator: \vec{a}\cdot\vec{a}
dy = (xa * xa) - dc;
dt = ds + dy;
dc = (dt - ds) - dy;
ds = dt;
ValueType xb = *b_first++; // Denominator: \vec{b}\cdot\vec{b}
dy = (xb * xb) - dc;
dt = ds + dy;
dc = (dt - ds) - dy;
ds = dt;
ny = (xa * xb) - nc; // Numerator: \vec{a}\cdot\vec{b}
nt = ns + ny;
nc = (nt - ns) - ny;
ns = nt;
}
return ns + nc == 0 // Does special zero case apply?
? 0 // Yes, to avoid NaN from 0 / 0
: (ns + nc) / (ds + dc); // No, correct final sums and form ratio
}
#else
#warning Using Non-Kahan version of ar::negative_half_reflection_coefficient.
{
ValueType ns = 0;
ValueType ds = 0;
while (a_first != a_last)
{
ValueType xa = *a_first++;
ValueType xb = *b_first++;
ns += xa * xb; // Numerator
ds += xa * xa + xb * xb; // Denominator
}
return ns == 0 // Does special zero case apply?
? 0 // Yes, to avoid NaN from 0 / 0
: ns / ds; // No, form ratio
}
#endif
#if _MSC_VER > 1400
# pragma float_control(pop)
#endif
/**
* Fit an autoregressive model to stationary time series data using %Burg's
* method. That is, find coefficients \f$a_i\f$ such that the sum of the
* squared errors in the forward predictions \f$x_n = -a_1 x_{n-1} - \dots -
* a_p x_{n-p}\f$ and backward predictions \f$x_n = -a_1 x_{n+1} - \dots - a_p
* x_{n+p}\f$ are both minimized. Either a single model of given order or a
* hierarchy of models up to and including a maximum order may fit.
*
* The input data \f$\vec{x}\f$ are read from <tt>[data_first, data_last)</tt>
* in a single pass. The mean is computed, returned in \c mean, and \e
* removed from further consideration whenever \c subtract_mean is true.
* The estimated model parameters \f$a_i\f$ are output using \c params_first
* with the behavior determined by the amount of data read, <tt>maxorder</tt>,
* and the \c hierarchy flag:
* <ul>
* <li>If \c hierarchy is \c false, only the \f$a_1, \dots,
* a_\text{maxorder}\f$ parameters for an AR(<tt>maxorder</tt>) process
* are output.</li>
* <li>If \c hierarchy is \c true, the <tt>maxorder*(maxorder+1)/2</tt>
* parameters \f$a_1, \dots, a_m\f$ for models AR(0), AR(1), AR(2),
* ..., AR(maxorder) are output. Notice AR(0) has no parameters.
* </li>
* </ul>
* Note that the latter case is \e always computed; the \c hierarchy flag
* merely controls what is output. In both cases, the maximum order is limited
* by the number of data samples provided and is output to \c maxorder.
*
* One mean squared discrepancy \f$\sigma^2_\epsilon\f$, also called the
* innovation variance, and gain, defined as \f$\sigma^2_x /
* \sigma^2_\epsilon\f$, are output for each model, including the trivial
* zeroth order model when \c maxorder is zero or \c hierarchy is \c true,
* using \c sigma2e_first and \c gain_first. The autocorrelations for lags
* <tt>[0,k]</tt> are output using \c autocor_first. When \c hierarchy is \c
* true, only lags <tt>[0,m]</tt> should be applied for some AR(<tt>m</tt>)
* model. Outputting the lag \c k autocorrelation is technically redundant as
* it may be computed from \f$a_i\f$ and lags <tt>0, ..., k-1</tt>.
* Autocovariances may be computed by multiplying the autocorrelations by the
* gain times \f$\sigma^2_\epsilon\f$.
*
* The software aspects of the implementation differs from many other sources.
* In particular,
* <ul>
* <li>iterators are employed,</li>
* <li>the working precision is selectable using \c mean,</li>
* <li>the mean squared discrepancy calculation has been added,</li>
* <li>some loop index transformations have been performed,</li>
* <li>working storage may be passed into the method to reduce allocations
* across many invocations, and</li>
* <li>and all lower order models may be output during the recursion using
* \c hierarchy.</li>
* </ul>
* Gain and autocorrelation calculations have been added based on sections 5.2
* and 5.3 of Broersen, P. M. T. Automatic autocorrelation and spectral
* analysis. Springer, 2006. http://dx.doi.org/10.1007/1-84628-329-9. The
* classical algorithm, rather than the variant using denominator recursion due
* to Andersen (http://dx.doi.org/10.1109/PROC.1978.11160), has been chosen as
* the latter can be numerically unstable.
*
* @param[in] data_first Beginning of the input data range.
* @param[in] data_last Exclusive end of the input data range.
* @param[out] mean Mean of data.
* @param[in,out] maxorder On input, the maximum model order desired.
* On output, the maximum model order computed.
* @param[out] params_first Model parameters for a single model or
* for an entire hierarchy of models. At most
* <tt>!hierarchy ? maxorder :
* maxorder*(maxorder+1)/2</tt> values will be
* output.
* @param[out] sigma2e_first The mean squared discrepancy for only
* AR(<tt>maxorder</tt>) or for an entire
* hierarchy. Either one or at most
* <tt>maxorder + 1</tt> values will be output.
* @param[out] gain_first The model gain for only AR(<tt>maxorder</tt>)
* or an entire hierarchy. Either one or at most
* <tt>maxorder + 1</tt> values will be output.
* @param[out] autocor_first Lag one through lag maxorder autocorrelations.
* At most <tt>maxorder + 1</tt> values will be
* output.
* @param[in] subtract_mean Should \c mean be subtracted from the data?
* @param[in] hierarchy Should the entire hierarchy of estimated
* models be output?
* @param[in] f Working storage. Reuse across invocations
* may speed execution by avoiding allocations.
* @param[in] b Working storage similar to \c f.
* @param[in] Ak Working storage similar to \c f.
* @param[in] ac Working storage similar to \c f.
*
* @returns the number data values processed within
* <tt>[data_first, data_last)</tt>.
*/
template <class InputIterator,
class Value,
class OutputIterator1,
class OutputIterator2,
class OutputIterator3,
class OutputIterator4,
class Vector>
std::size_t burg_method(InputIterator data_first,
InputIterator data_last,
Value& mean,
std::size_t& maxorder,
OutputIterator1 params_first,
OutputIterator2 sigma2e_first,
OutputIterator3 gain_first,
OutputIterator4 autocor_first,
const bool subtract_mean,
const bool hierarchy,
Vector& f,
Vector& b,
Vector& Ak,
Vector& ac)
{
using std::bind2nd;
using std::copy;
using std::distance;
using std::fill;
using std::inner_product;
using std::min;
using std::minus;
using std::size_t;
// Initialize f from [data_first, data_last) and fix number of samples
f.assign(data_first, data_last);
const size_t N = f.size();
// Stably compute the incoming data's mean and population variance
mean = 0;
Value sigma2e = 0;
welford_variance_population(f.begin(), f.end(), mean, sigma2e);
// When requested, subtract the just-computed mean from the data.
// Adjust, if necessary, to make sigma2e the second moment.
if (subtract_mean)
{
transform(f.begin(), f.end(), f.begin(), bind2nd(minus<Value>(), mean));
}
else
{
sigma2e += mean*mean;
}
// At most maxorder N-1 can be fit from N samples. Beware N is unsigned.
maxorder = (N == 0) ? 0 : min(static_cast<size_t>(maxorder), N-1);
// Output sigma2e and gain for a zeroth order model, if requested.
Value gain = 1;
if (hierarchy || maxorder == 0)
{
*sigma2e_first++ = sigma2e;
*gain_first++ = gain;
}
// Initialize and perform Burg recursion
if (maxorder) b = f; // Copy iff non-trivial work required
Ak.assign(maxorder + 1, Value(0));
Ak[0] = 1;
ac.clear();
ac.reserve(maxorder);
for (size_t kp1 = 1; kp1 <= maxorder; ++kp1)
{
// Compute mu from f, b, and Dk and then update sigma2e and Ak using mu
// Afterwards, Ak[1:kp1] contains AR(k) coefficients by the recurrence
// Must treat mu result of 0 / 0 as 0 to avoid NaNs on constant signals
// By the recurrence, Ak[kp1] will also be the reflection coefficient
Value mu = -2 * negative_half_reflection_coefficient<Value>(
f.begin() + kp1, f.end(), b.begin());
sigma2e *= (1 - mu*mu);
for (size_t n = 0; n <= kp1/2; ++n)
{
Value t1 = Ak[n] + mu*Ak[kp1 - n];
Value t2 = Ak[kp1 - n] + mu*Ak[n];
Ak[n] = t1;
Ak[kp1 - n] = t2;
}
// Update the gain per Broersen 2006 equation (5.25)
gain *= 1 / (1 - Ak[kp1]*Ak[kp1]);
// Compute and output the next autocorrelation coefficient
// See Broersen 2006 equations (5.28) and (5.31) for details
ac.push_back(-inner_product(ac.rbegin(), ac.rend(),
Ak.begin() + 1, Ak[kp1]));
// Output parameters and the input and output variances when requested
if (hierarchy || kp1 == maxorder)
{
params_first = copy(Ak.begin() + 1, Ak.begin() + kp1 + 1,
params_first);
*sigma2e_first++ = sigma2e;
*gain_first++ = gain;
}
// Update f and b for the next iteration if another remains
if (kp1 < maxorder)
{
for (size_t n = 0; n < N - kp1; ++n)
{
Value t1 = f[n + kp1] + mu*b[n];
Value t2 = b[n] + mu*f[n + kp1];
f[n + kp1] = t1;
b[n] = t2;
}
}
}
// Output the lag [0,maxorder] autocorrelation coefficients in single pass
*autocor_first++ = 1;
copy(ac.begin(), ac.end(), autocor_first);
// Return the number of values processed in [data_first, data_last)
return N;
}
/** \copydoc burg_method(InputIterator,InputIterator,Value&,std::size_t&,OutputIterator1,OutputIterator2,OutputIterator3,OutputIterator4,const bool,const bool,Vector&,Vector&,Vector&,Vector&) */
template <class InputIterator,
class Value,
class OutputIterator1,
class OutputIterator2,
class OutputIterator3,
class OutputIterator4>
std::size_t burg_method(InputIterator data_first,
InputIterator data_last,
Value& mean,
std::size_t& maxorder,
OutputIterator1 params_first,
OutputIterator2 sigma2e_first,
OutputIterator3 gain_first,
OutputIterator4 autocor_first,
const bool subtract_mean = false,
const bool hierarchy = false)
{
using std::vector;
vector<Value> f, b, Ak, ac; // Working storage
return burg_method(data_first, data_last, mean, maxorder,
params_first, sigma2e_first, gain_first,
autocor_first, subtract_mean, hierarchy,
f, b, Ak, ac);
}
// Type erasure for NoiseGenerator parameters within predictor.
// Either std::tr1::function or boost::function would better provide the
// desired capability but both add additional, undesired dependencies.
namespace
{
/** Abstract base class for NoiseGenerator-related type erasure. */
template <typename Value>
struct nullary
{
virtual ~nullary() {}
virtual Value operator()() = 0;
virtual nullary* clone() = 0;
};
/** A nullary function always returning zero. */
template<typename Value>
struct nullary_impl0 : public nullary<Value>
{
Value operator()()
{
return 0;
}
nullary_impl0* clone()
{
return new nullary_impl0();
}
};
/** A nullary function always invoking t(). */
template<typename Value, class T>
struct nullary_impl1 : public nullary<Value>
{
nullary_impl1(T t) : t(t) {}
Value operator()()
{
return t();
}
nullary_impl1* clone()
{
return new nullary_impl1(t);
}
T t;
};
}
/**
* Simulate an autoregressive model process with an InputIterator interface.
*/
template <typename Value, typename Index = std::size_t>
class predictor
: public std::iterator<std::input_iterator_tag, Value,
std::ptrdiff_t, const Value*, const Value&>
{
private:
typedef std::iterator<std::input_iterator_tag, Value,
std::ptrdiff_t, const Value*, const Value&> base;
public:
typedef typename base::difference_type difference_type;
typedef typename base::iterator_category iterator_category;
typedef typename base::pointer pointer;
typedef typename base::reference reference;
typedef typename base::value_type value_type;
/** Singular instance marking prediction index \c n. */
explicit predictor(Index n = 0) : n(n), d(), g(0), xn()
{
#ifndef NDEBUG
using std::numeric_limits;
if (numeric_limits<Value>::has_quiet_NaN)
xn = numeric_limits<Value>::quiet_NaN();
#endif
}
/**
* Iterate on the process \f$x_n + a_1 x_{n - 1} + \dots + a_p x_{n - p} =
* 0\f$. Presumably \ref initial_conditions will be used to specify some
* initial state as otherwise the process is identically zero. The process
* order \f$p\f$ is set by <tt>std::distance(params_first,
* params_last)</tt>.
*
* @param params_first Beginning of the process parameter range
* starting with \f$a_1\f$.
* @param params_last End of the process parameter range.
*/
template <class RandomAccessIterator>
predictor(RandomAccessIterator params_first,
RandomAccessIterator params_last)
: n(0),
d(2*std::distance(params_first, params_last), 0),
g(new nullary_impl0<Value>()),
xn((*g)())
{
// Finish preparing d = [ a_p, ..., a_1, 0, ..., 0 ]
using std::vector;
typename vector<Value>::size_type i = d.size() / 2;
while (i --> 0) d[i] = *params_first++;
// Now x_n = 0 because x_{n-p} = ... = x_{n-1} = 0 by construction.
}
/**
* Iterate on the process \f$x_n + a_1 x_{n - 1} + \dots + a_p x_{n - p} =
* \epsilon_n\f$ given zero initial conditions. The process order \f$p\f$
* is set by <tt>std::distance(params_first,params_last)</tt>. The class
* <tt>std::tr1::variate_generator</tt> may be helpful in constructing
* normally distributed input.
*
* @param params_first Beginning of the process parameter range
* starting with \f$a_1\f$.
* @param params_last End of the process parameter range.
* @param generator A nullary callback for generating \f$\epsilon_n\f$.
* For example, a random number generator distributed
* like \f$N\left(0, \sigma^2_\epsilon\right)\f$.
*/
template <class RandomAccessIterator,
class NoiseGenerator>
predictor(RandomAccessIterator params_first,
RandomAccessIterator params_last,
NoiseGenerator generator)
: n(0),
d(2*std::distance(params_first, params_last), 0),
g(new nullary_impl1<Value,NoiseGenerator>(generator)),
xn((*g)())
{
// Finish preparing d = [ a_p, ..., a_1, 0, ..., 0 ]
using std::vector;
typename vector<Value>::size_type i = d.size() / 2;
while (i --> 0) d[i] = *params_first++;
// Here x_0 = \epsilon_0 because x_{0-p} = ... = x_{0-1} = 0.
}
/** Copy constructor */
predictor(const predictor& other)
: n(other.n),
d(other.d),
g(other.g ? other.g->clone() : 0),
xn(other.xn)
{}
/** Assignment operator */
predictor& operator=(const predictor& other)
{
if (this != &other)
{
nullary<Value> *tmp = 0;
try
{
tmp = other.g ? other.g->clone() : 0;
}
catch (...)
{
delete tmp;
throw;
}
base::operator=(other);
n = other.n;
d = other.d;
delete g;
g = tmp;
xn = other.xn;
}
return *this;
}
/** Destructor */
~predictor()
{
delete g;
}
/**
* Specify process initial conditions \f$x_{n-1}, \dots, x_{n-p}\f$ where
* \f$p\f$ is the process order fixed by the constructor. The simulation
* index \f$n\f$ is reset to zero and, optionally, \f$x_0\f$ is additively
* adjusted by \c x0adjust.
*
* @param initial_first Beginning of the initial condition range
* \f$x_{n-1}, \dots, x_{n-p}\f$
* which must contain \f$p\f$ values.
* @param x0adjust An additive adjustment made to \f$\epsilon_0\f$.
*/
template <class InputIterator>
predictor& initial_conditions(InputIterator initial_first,
const Value x0adjust = 0)
{
// Zero the simulation time.
n = 0;
// Set d = [ a_p, ..., a_1, x_{n-p}, ..., x_{n-1} ]
using std::vector;
typename vector<Value>::size_type i = d.size();
typename vector<Value>::size_type p = i / 2;
while (i --> p) d[i] = *initial_first++;
// Make x_n := - a_p*x_{n-p} - ... - a_1*x_{n-1} + x_n + x0adjust.
// By design, x_n was whatever it happened to be.
using std::inner_product;
xn += x0adjust;
xn = -inner_product(d.begin(), d.begin() + p, d.begin() + p, -xn);
return *this;
}
// Concept: InputIterator
/** Prefix increment. */
predictor& operator++()
{
using std::distance;
using std::inner_product;
using std::vector;
if (g)
{
typename vector<Value>::size_type p = d.size() / 2;
if (p)
{
// Make x_n = - a_p*x_{n-p} - ... - a_1*x_{n-1} + \epsilon_n
// by (conceptually) storing previously computed x_n into
// circular buffer, updating ++n, and computing x_{n+1}.
typename vector<Value>::iterator ab = d.begin();
typename vector<Value>::iterator xb = ab + p;
typename vector<Value>::iterator c = xb + n % p;
typename vector<Value>::iterator xe = d.end();
*c++ = xn;
xn = inner_product(c, xe, ab, -(*g)());
xn = -inner_product(xb, c, ab + distance(c, xe), xn );
}
else
{