-
Notifications
You must be signed in to change notification settings - Fork 0
/
LSDStatsTools.cpp
3023 lines (2610 loc) · 109 KB
/
LSDStatsTools.cpp
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
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// LSDStatsTools
// Land Surface Dynamics StatsTools
//
// A collection of statistical routines for use with the University
// of Edinburgh Land Surface Dynamics group topographic toolbox
//
// Developed by:
// Simon M. Mudd
// Martin D. Hurst
// David T. Milodowski
// Stuart W.D. Grieve
// Declan A. Valters
// Fiona Clubb
//
// Copyright (C) 2013 Simon M. Mudd 2013
//
// Developer can be contacted by simon.m.mudd _at_ ed.ac.uk
//
// Simon Mudd
// University of Edinburgh
// School of GeoSciences
// Drummond Street
// Edinburgh, EH8 9XP
// Scotland
// United Kingdom
//
// This program is free software;
// you can redistribute it and/or modify it under the terms of the
// GNU General Public License as published by the Free Software Foundation;
// either version 2 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY;
// without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// You should have received a copy of the
// GNU General Public License along with this program;
// if not, write to:
// Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301
// USA
//
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//-----------------------------------------------------------------
//DOCUMENTATION URL: http://www.geos.ed.ac.uk/~s0675405/LSD_Docs/
//-----------------------------------------------------------------
#include <vector>
#include <fstream>
#include <algorithm>
#include <math.h>
#include <time.h>
#include "TNT/tnt.h"
#include "TNT/jama_lu.h"
#include "LSDStatsTools.hpp"
using namespace std;
using namespace TNT;
using namespace JAMA;
#ifndef StatsTools_CPP
#define StatsTools_CPP
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/*********************************************************\
** ran3
**
** Random number generator from Numerical Recipes.
** Returns a uniform random number between 0.0 and 1.0.
** Set idum to any negative value to initialize or
** reinitialize the sequence.
**
** Parameters: idum - random seed
**
\*********************************************************/
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#define MBIG 990000000
#define MSEED 161803398
#define MZ 0
#define FAC (1.0/MBIG)
float ran3(long *idum)
{
//cout << &idum << endl;
static int inext,inextp;
static long ma[56];
static int iff=0;
long mj,mk;
int i,ii,k;
if (*idum < 0 || iff == 0) {
iff=1;
if(*idum>0)
*idum = - *idum;
mj=MSEED+ *idum;
if (mj<0)
mj = -mj;
mj %= MBIG;
ma[55]=mj;
mk=1;
for (i=1;i<=54;i++) {
ii=(21*i) % 55;
ma[ii]=mk;
mk=mj-mk;
if (mk < MZ) mk += MBIG;
mj=ma[ii];
}
for (k=1;k<=4;k++)
for (i=1;i<=55;i++) {
ma[i] -= ma[1+(i+30) % 55];
if (ma[i] < MZ) ma[i] += MBIG;
}
inext=0;
inextp=31;
*idum=1;
}
if (++inext == 56) inext=1;
if (++inextp == 56) inextp=1;
mj=ma[inext]-ma[inextp];
if (mj < MZ) mj += MBIG;
ma[inext]=mj;
return fabs(mj*FAC);
}
#undef MBIG
#undef MSEED
#undef MZ
#undef FAC
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// Randomly sample from a vector without replacement DTM 21/04/2014
//------------------------------------------------------------------------------
vector<float> sample_without_replacement(vector<float> population_vector, int N)
{
vector<float> sample_vector;
int Population = population_vector.size();
if(N > Population)
{
cout << "N>Population size, try again" << endl;
exit(EXIT_FAILURE);
}
int sample_count = 0;
float random_number,Population_remaining;
long seed;
int vector_ref;
while (sample_count < N)
{
Population_remaining = population_vector.size();
seed = time(NULL);
random_number = ran3(&seed);
vector_ref = floor(random_number*Population_remaining);
if(vector_ref = Population_remaining) vector_ref = Population_remaining - 1;
sample_vector.push_back(population_vector[vector_ref]);
population_vector.erase(population_vector.begin()+vector_ref);
++sample_count;
}
return sample_vector;
}
vector<int> sample_without_replacement(vector<int> population_vector, int N)
{
vector<int> sample_vector;
int Population = population_vector.size();
if(N > Population)
{
cout << "N>Population size, try again" << endl;
exit(EXIT_FAILURE);
}
int sample_count = 0;
float random_number,Population_remaining;
long seed;
int vector_ref;
while (sample_count < N)
{
Population_remaining = population_vector.size();
seed = time(NULL);
random_number = ran3(&seed);
vector_ref = floor(random_number*Population_remaining);
if(vector_ref = Population_remaining) vector_ref = Population_remaining - 1;
sample_vector.push_back(population_vector[vector_ref]);
population_vector.erase(population_vector.begin()+vector_ref);
++sample_count;
}
return sample_vector;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// gets the mean from a population of y_data
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
float get_mean(vector<float>& y_data)
{
int n_data_points = y_data.size();
float total = 0;
float mean;
for (int i = 0; i< n_data_points; i++)
{
total+=y_data[i];
}
mean = total/float(n_data_points);
return mean;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// gets the mean from a population of y_data
// This takes and array and ignores no data values
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
float get_mean_ignore_ndv(Array2D<float>& data, float ndv)
{
int NRows = data.dim1();
int NCols = data.dim2();
int count = 0;
float total = 0;
float mean;
for (int row = 0; row<NRows; row++)
{
for (int col = 0; col<NCols; col++)
{
if (data[row][col] != ndv)
{
total+= data[row][col];
count++;
}
}
}
mean = total/float(count);
return mean;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// gets the total sum of squares from a population of data
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
float get_SST(vector<float>& y_data, float mean)
{
int n_data_points = y_data.size();
float total = 0;
for (int i = 0; i< n_data_points; i++)
{
total+=(y_data[i]-mean)*(y_data[i]-mean);
}
return total;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// gets the total sum of squares from a population of data
// this uses and array and ignores no data values
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
float get_variance_ignore_ndv(Array2D<float>& data, float ndv, float mean)
{
int NRows = data.dim1();
int NCols = data.dim2();
int count = 0;
float total = 0;
float variance;
for (int row = 0; row<NRows; row++)
{
for (int col = 0; col<NCols; col++)
{
if (data[row][col] != ndv)
{
total+=(data[row][col]-mean)*(data[row][col]-mean);
count++;
}
}
}
variance = total/float(count);
return variance;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// gets the standard deviation from a population of data
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
float get_standard_deviation(vector<float>& y_data, float mean)
{
int n_data_points = y_data.size();
float total = 0;
for (int i = 0; i< n_data_points; i++)
{
total+=(y_data[i]-mean)*(y_data[i]-mean);
}
return sqrt(total/float(n_data_points));
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// gets the standard error from a population of data
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
float get_standard_error(vector<float>& y_data, float standard_deviation)
{
int n_data_points = y_data.size();
return standard_deviation/(sqrt(float(n_data_points)));
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// this function returns a vector with several common statistics
// the vector has the following elements
// 0 mean
// 1 sum of squares
// 2 standard deviation
// 3 standard error
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
vector<float> get_common_statistics(vector<float>& y_data)
{
int n_data_points = y_data.size();
float mean = get_mean(y_data);
float SST = get_SST(y_data, mean);
float standard_deviation = sqrt(SST/float(n_data_points));
float standard_error = standard_deviation/(sqrt(float(n_data_points)));
vector<float> common_statistics(4);
common_statistics[0] = mean;
common_statistics[1] = SST;
common_statistics[2] = standard_deviation;
common_statistics[3] = standard_error;
return common_statistics;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// gets specified percentile, from pre-sorted vector, following same method as MS Excel. Note
// that the percentile should be expressed as a percentage i.e. for median percentile = 50, NOT
// 0.5!
// DTM 14/04/2014
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
float get_percentile(vector<float>& data, float percentile)
{
int N = data.size();
float n = percentile*(float(N)-1)/100;
int k = int(floor(n));
float d = n - floor(n);
float percentile_value;
if(k>=N-1) percentile_value = data[k-1];
else if (k < 0) percentile_value = data[0];
else percentile_value = data[k] + d*(data[k+1]-data[k]);
return percentile_value;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// this function tests for autocorrelation between residuals
// if the number is less than 2 the residuals show autocorrelation
// if the number is less than 1 there is clear evidence for autocorrelation
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
float get_durbin_watson_statistic(vector<float> residuals)
{
int n_observations = residuals.size();
float top_term = 0;
float bottom_term = 0;
for (int i = 0; i<n_observations; i++)
{
if (i!=0)
{
top_term+=(residuals[i]-residuals[i-1])*(residuals[i]-residuals[i-1]);
}
bottom_term+=residuals[i]*residuals[i];
}
if(bottom_term == 0)
{
bottom_term = 1e-10;
}
return(top_term/bottom_term);
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// this gets a simple linear regression where the regression model is y = mx+b
// it returns a vector with the best fit values for m, b, r^2 and the durban_watson
// statistic (which is used to test if the residuals are autocorrelated
// it also replaces the residuals vector with the actual residuals from the
// best fit
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
vector<float> simple_linear_regression(vector<float>& x_data, vector<float>& y_data, vector<float>& residuals)
{
float rounding_cutoff = 1e-12;
int n_rows = x_data.size();
int n_cols = 2;
Array2D<float> A(n_rows,n_cols);
Array2D<float> b(n_rows,1);
Array2D<float> A_transpose(n_cols,n_rows);
// construct solution matrices
for(int i = 0; i<n_rows; i++)
{
A[i][0] = x_data[i];
A[i][1] = 1.0;
A_transpose[0][i] = x_data[i];
A_transpose[1][i] = 1.0;
b[i][0] = y_data[i];
}
// solve the system
Array2D<float> LHS = matmult(A_transpose,A);
Array2D<float> RHS = matmult(A_transpose,b);
LU<float> LU_mat(LHS);
Array2D<float> solution= LU_mat.solve(RHS);
vector<float> soln;
for(int i = 0; i<2; i++)
{
soln.push_back(solution[i][0]);
}
// get some statistics
float mean = get_mean(y_data);
float SST = get_SST(y_data, mean);
// now get the predictions
vector<float> predicted;
vector<float> temp_residuals;
// get predicted, residuals, etc
float SS_reg = 0;
float SS_err = 0;
//cout << endl;
for(int i = 0; i<n_rows; i++)
{
predicted.push_back(soln[0]*x_data[i] + soln[1]);
temp_residuals.push_back(predicted[i]-y_data[i]);
if (fabs(temp_residuals[i]) < rounding_cutoff)
{
temp_residuals[i] = 0;
}
SS_reg+=(predicted[i]-mean)*(predicted[i]-mean);
SS_err+=temp_residuals[i]*temp_residuals[i];
//cout << "RESIDUAL, i: " << i << " pred: " << predicted[i] << " data: " << y_data[i] << " resid: " << temp_residuals[i] << endl;
}
//cout << "SST: " << SST << " SS_reg: " << SS_reg << " SS_err " << SS_err << endl;
// now get R^2
soln.push_back(1 - SS_err/SST);
// now get the durbin_watson statistic
soln.push_back( get_durbin_watson_statistic(temp_residuals) );
residuals = temp_residuals;
return soln;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// this function drives the partitioning algorithms
// k is the number of elements in the partition
// minimum lenght is the minimum length of the segment
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void partition_driver_to_screen(int k, int minimum_length) // this just prints partitions to screen
{
int n = 2*k;
int t = 0;
vector<int> p(k,0);
partitions_with_minimum_length( n, k, t, minimum_length, p);
}
// this version returns the partition vecvecvec
vector< vector < vector<int> > > partition_driver_to_vecvecvec(int k, int minimum_length)
{
int n = 2*k;
int t = 0;
vector<int> p(k,0);
int max_segments = k/minimum_length;
vector< vector < vector<int> > > partitions(max_segments);
// run the partitioning code
cout << "partition_driver_to_vecvecvec, doing partitions" << endl;
partitions_with_minimum_length( n, k, t, minimum_length, p, partitions);
cout << "partition_driver_to_vecvecvec, finished partitions" << endl;
return partitions;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// an integer partition algorithm
// Algorithm and original Pascal implementation: Frank Ruskey, 1995.
// Translation to C: Joe Sawada, 1997
// grabbed from http://theory.cs.uvic.ca/inf/nump/NumPartition.html
// adapted smm 21/12/2012
// algorith described in
// http://mathworld.wolfram.com/PartitionFunctionP.html
// and
// Skiena, S. Implementing Discrete Mathematics: Combinatorics and Graph Theory with Mathematica. Reading, MA: Addison-Wesley, 1990.
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void integer_partition(int n, int k, int t, vector<int>& p)
{
int j;
p[t] = k;
if (n==k)
{
partition_print(t,p);
}
for (j=partitions_min(k,n-k); j>=1; j--)
{
integer_partition (n-k,j,t+1, p);
}
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// an integer partition algorithm
// Algorithm and original Pascal implementation: Frank Ruskey, 1995.
// Translation to C: Joe Sawada, 1997
// grabbed from http://theory.cs.uvic.ca/inf/nump/NumPartition.html
// adapted smm 21/12/2012
// algorith described in
// http://mathworld.wolfram.com/PartitionFunctionP.html
// and
// Skiena, S. Implementing Discrete Mathematics: Combinatorics and Graph Theory with Mathematica. Reading, MA: Addison-Wesley, 1990.
// this is a further adaptation that only presents solution to the partition
// with segments of a minimum length
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void partitions_with_minimum_length(int n, int k, int t, int min_length, vector<int>& p)
{
int j;
p[t] = k;
if (n==k)
{
partition_print(t,p);
}
for (j=partitions_min(k,n-k); j>=min_length; j--)
{
partitions_with_minimum_length(n-k,j,t+1,min_length,p);
}
}
// overloaded function that stores all the partitions
// http://www.codeguru.com/cpp/cpp/algorithms/article.php/c5123/Permutations-in-C.htm
// http://www.cplusplus.com/reference/algorithm/next_permutation/
// http://mdm4u1.wetpaint.com/page/4.3+Permutations+with+Some+Identical+Elements
void partitions_with_minimum_length(int n, int k, int t, int min_length, vector<int>& p,
vector< vector < vector<int> > >& partitions)
{
int j;
p[t] = k;
if (n==k)
{
partition_assign(t, p, partitions);
}
for (j=partitions_min(k,n-k); j>=min_length; j--)
{
partitions_with_minimum_length(n-k,j,t+1,min_length,p, partitions);
}
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// a function for use with the permutations
// gets the mininum of two values
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
int partitions_min( int x, int y)
{
if (x<y)
{
return x;
}
else
{
return y;
}
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// a function for use with the permutations
// this assigns values into the vecvecvec that contains all the partitioning information
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void partition_assign(int t, vector<int>& p, vector< vector < vector<int> > >& partitions)
{
vector< vector<int> > this_nsegments_vecvec = partitions[t-1];
vector<int> this_partitions_partitions;
for(int i=1; i<=t; i++)
{
this_partitions_partitions.push_back( p[i] );
}
this_nsegments_vecvec.push_back(this_partitions_partitions);
partitions[t-1] = this_nsegments_vecvec;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// a function for use with the permutations
// gets the mininum of two values
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void partition_print(int t, vector<int>& p)
{
for(int i=1; i<=t; i++)
{
cout << p[i] << " ";
}
cout << endl;
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// this function prints the elements in the vecvecvec of possible partitions
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void partition_vecvecvec_print(vector< vector < vector<int> > >& partitions)
{
cout << "n_possible_segments: " << partitions.size() << endl;
vector< vector <int> > partition_vecvec;
for (int i = 0; i< int(partitions.size()); i++)
{
partition_vecvec = partitions[i];
int n_partitions_this_nsegments = partition_vecvec.size();
//cout << "n_segments: " << i+1 << " and number of partitions of this n segments: " << n_partitions_this_nsegments << endl;
for (int j = 0; j< n_partitions_this_nsegments; j++)
{
vector<int> individual_partition = partition_vecvec[j];
int sz_ind_partition = individual_partition.size();
for(int k = 0; k<sz_ind_partition; k++)
{
cout << individual_partition[k] << " ";
}
cout << endl;
}
}
}
void partition_vecvecvec_print_with_permutation(vector< vector < vector<int> > >& partitions)
{
cout << "n_possible_segments: " << partitions.size() << endl;
vector< vector <int> > partition_vecvec;
for (int i = 0; i< int(partitions.size()); i++)
{
partition_vecvec = partitions[i];
int n_partitions_this_nsegments = partition_vecvec.size();
cout << "n_segments: " << i+1 << " and number of partitions of this n segments: " << n_partitions_this_nsegments << endl;
for (int j = 0; j< n_partitions_this_nsegments; j++)
{
vector<int> individual_partition = partition_vecvec[j];
permute_partitioned_integer_vector(individual_partition);
cout << endl;
}
}
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// this function permutes a partitioned integer vector
// the partitioning supplies vectors sorted in reverse order
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void permute_partitioned_integer_vector(vector<int> permute_vector)
{
int n_elements = permute_vector.size();
//for (int i = 0; i<n_elements; i++)
//{
// cout << permute_vector[i] << " ";
//}
//cout << endl;
do
{
for (int i = 0; i<n_elements; i++)
{
cout << permute_vector[i] << " ";
}
cout << endl;
} while ( prev_permutation (permute_vector.begin(),permute_vector.end()) );
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// this function is used to calcualte the slope, intercept, and likelihood of
// all possible linear segments along a series of data points.
// the function requires the data in x and y vectors, the maximum segment length
// and sigma, the standard deviation of the measured data. This will be approxamately
// the error in the surface elevation, although it might have to be increased simply because
// likelihood will tend to zero if this is too small. sigma should also be considered to
// contain the 'noise' inherent in channel incision so perhaps 1-5 metres is appropriate
// the maximum segment length is an integer: it is the number of data points used.
// these data points from raw chi data are irregularly spaced so two segments of the same
// 'length' can have different lengths in chi space. One remedey for this is a preprocessor that
// places the zeta vs chi data along evenly spaced points.
//
// The routine generates three matrices. The row of the matrix is the starting node of the segment.
// The column of the matrix is the ending node of the segment. Thus the routine will generate a
// matrix that is dimension n x n where n is the number of data points.
//
// One potential future development is to implement this using a sparse matrix from the boost mtl
// library to reduce the memory usage.
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void calculate_segment_matrices(vector<float>& all_x_data, vector<float>& all_y_data, int minimum_segment_length,
float sigma, Array2D<float>& like_array, Array2D<float>& m_array,
Array2D<float>& b_array, Array2D<float>& rsquared_array,
Array2D<float>& DW_array)
{
int n_data_points = all_x_data.size();
if (minimum_segment_length>n_data_points)
{
cout << "LSDStatsTools find_linear_segments: your segment length is greater than half the number of data points" << endl;
cout << "This means that there can only be overlapping segments. Changing segment length to maximum segment length "<< endl;
minimum_segment_length = n_data_points;
}
// set up the arrays
// in the future I might consider using sparse arrays but for now we'll just populate
// the empty spots with placeholders
float no_data_value = -9999;
Array2D<float> temp_array(n_data_points,n_data_points,no_data_value);
like_array = temp_array.copy();
m_array = temp_array.copy();
b_array = temp_array.copy();
rsquared_array = temp_array.copy();
DW_array = temp_array.copy();
int start_node = 0;
int end_node = n_data_points-1;
// populate the matrix.
// the get segment row function is recursive so it moves down through all the possible
// starting nodes
//cout << "LINE 518, sigma is: " << sigma << endl;
populate_segment_matrix(start_node, end_node, no_data_value, all_x_data, all_y_data, minimum_segment_length,
sigma, like_array, m_array,b_array, rsquared_array, DW_array);
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// this function popultes the matrices of liklihood, m and b values
// it is a recursive algorithm so in fact it deosn't just get one row
// but drills down through all the possible starting nodes to coplete the
// matrix
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void populate_segment_matrix(int start_node, int end_node, float no_data_value,
vector<float>& all_x_data, vector<float>& all_y_data, int minimum_segment_length,
float sigma, Array2D<float>& like_array, Array2D<float>& m_array,
Array2D<float>& b_array, Array2D<float>& rsquared_array, Array2D<float>& DW_array)
{
if (like_array[start_node][end_node] == no_data_value)
{
// create the two segments
vector<float> segment_x;
vector<float> segment_y;
vector<float> residuals;
vector<float> regression_results;
float this_MLE;
// now create iterators to deal with these segments
vector<float>::iterator vec_iter_start;
vector<float>::iterator vec_iter_end;
// the first step is to get the segment starting on the
// first node and ending on the last node
// find out how many nodes are in the segment
int n_nodes_in_segment = end_node - start_node+1;
// resize the vectors accordingly
segment_x.resize(n_nodes_in_segment);
segment_y.resize(n_nodes_in_segment);
// get the iterators for the start and end of the vectors
vec_iter_start = all_x_data.begin()+start_node;
vec_iter_end = vec_iter_start+n_nodes_in_segment;
segment_x.assign(vec_iter_start,vec_iter_end);
vec_iter_start = all_y_data.begin()+start_node;
vec_iter_end = vec_iter_start+n_nodes_in_segment;
segment_y.assign(vec_iter_start,vec_iter_end);
// do the least squares regression on this segment
// cout << "LINE 568, sigma is: " << sigma << endl;
regression_results = simple_linear_regression(segment_x, segment_y, residuals);
this_MLE = calculate_MLE_from_residuals( residuals, sigma);
//cout << "LINE 584 doing start: " << start_node << " end: " << end_node << endl;
like_array[start_node][end_node] = this_MLE;
m_array[start_node][end_node] = regression_results[0];
b_array[start_node][end_node] = regression_results[1];
rsquared_array[start_node][end_node] = regression_results[2];
DW_array[start_node][end_node] = regression_results[3];
// now loop through all the end nodes that are allowed that are not the final node.
// that is the first end node is first plus the maximum length -1 , and then
// the final end node before the end of the data is the last node minus the
// maximum length of the segment
for (int loop_end = start_node+minimum_segment_length-1; loop_end< end_node-minimum_segment_length+1; loop_end++)
{
if (like_array[start_node][loop_end] == no_data_value)
{
// get this segment and resize the vectors
n_nodes_in_segment = loop_end - start_node+1;
segment_x.resize(n_nodes_in_segment);
segment_y.resize(n_nodes_in_segment);
// get the iterators for the start and end of the vectors
vec_iter_start = all_x_data.begin()+start_node;
vec_iter_end = vec_iter_start+n_nodes_in_segment;
segment_x.assign(vec_iter_start,vec_iter_end);
vec_iter_start = all_y_data.begin()+start_node;
vec_iter_end = vec_iter_start+n_nodes_in_segment;
segment_y.assign(vec_iter_start,vec_iter_end);
// do the least squares regression on this segment
regression_results = simple_linear_regression(segment_x, segment_y, residuals);
this_MLE = calculate_MLE_from_residuals( residuals, sigma);
// fill in the matrices
like_array[start_node][loop_end] = this_MLE;
m_array[start_node][loop_end] = regression_results[0];
b_array[start_node][loop_end] = regression_results[1];
rsquared_array[start_node][loop_end] = regression_results[2];
DW_array[start_node][loop_end] = regression_results[3];
//cout << "LINE 612 doing start: " << start_node << " end: " << loop_end << endl;
// now get the row from the next segment
populate_segment_matrix(loop_end+1, end_node, no_data_value,
all_x_data, all_y_data, minimum_segment_length,
sigma, like_array, m_array,b_array, rsquared_array, DW_array);
}
}
}
}
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// this function drives the entire AIC engine
// it takes the minimum segment length
// and the x and y data
// and an estimate of the variability of the data
// It then overwrites a raft of data elements
// First, it returns
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void best_fit_driver_AIC_for_linear_segments(int minimum_segment_length, float sigma,
vector<float> all_x_data, vector<float> all_y_data,
vector<float>& max_MLE)
{
float norm_sigma = 1.0;
Array2D<float> like_array; // array holding the liklihood values
Array2D<float> m_array; // array holding the m values
Array2D<float> b_array; // array holding the b values
Array2D<float> rsquared_array; // array holding R2 of individual segments
Array2D<float> DW_array; // array holding the durbin-watson statistic of indiviudal segments
cout << "best_fit_driver_AIC_for_linear_segments, getting like data" <<endl;
calculate_segment_matrices(all_x_data, all_y_data, minimum_segment_length,
norm_sigma, like_array, m_array, b_array, rsquared_array,DW_array);
cout << "best_fit_driver_AIC_for_linear_segments, got like data" <<endl;
vector<float> one_sig_max_MLE;
vector<float> AIC_of_segments;
vector<float> AICc_of_segments;
vector< vector<int> > segments_for_each_n_segments;
find_max_like_of_segments(minimum_segment_length, like_array,
one_sig_max_MLE, segments_for_each_n_segments);
max_MLE = change_normalized_like_vector_to_new_sigma(sigma, one_sig_max_MLE);
//print_to_screen_most_likeley_segment_lengths( segments_for_each_n_segments,
// one_sig_max_MLE);
// now loop through a variety of sigma values to see what the minimum sigma is
float d_sigma = 0.01;
vector<float> sigma_values;
for(int i = 1; i<=10; i++)
{
sigma_values.push_back(d_sigma*float(i));
}
vector<int> best_fit_AIC;
vector<int> best_fit_AICc;
vector< vector<float> > AIC_for_each_n_segments;
vector< vector<float> > AICc_for_each_n_segments;
get_n_segments_for_various_sigma(sigma_values, one_sig_max_MLE, all_x_data,
best_fit_AIC, best_fit_AICc, AIC_for_each_n_segments,
AICc_for_each_n_segments);
print_AIC_and_AICc_to_screen(sigma_values, segments_for_each_n_segments,
best_fit_AIC, best_fit_AICc,
AIC_for_each_n_segments, AICc_for_each_n_segments);
vector<float> b_values;
vector<float> m_values;
vector<float> r2_values;
vector<float> DW_values;
// get the m, b, etc from the data
int n_sigma_for_printing = 2;
int bestfit_segments_node = best_fit_AICc[n_sigma_for_printing];
get_properties_of_best_fit_segments(bestfit_segments_node, segments_for_each_n_segments,
m_values, m_array, b_values, b_array,
r2_values, rsquared_array, DW_values, DW_array);
// now print this data
cout << "sigma is: " << sigma_values[n_sigma_for_printing]
<< " one_sig MLE: " << one_sig_max_MLE[ best_fit_AICc[n_sigma_for_printing] ]
<< " and the number of segments is: " << best_fit_AICc[n_sigma_for_printing]+1 << endl;
for (int i = 0; i< best_fit_AICc[n_sigma_for_printing]+1; i++)
{
cout << m_values[i] << " " << b_values[i] << " " << r2_values[i] << " " << DW_values[i] << endl;
}
}
// this function takes the normalized MLE values (normalized with sigma = 1) and returns the
// best fit number of segments from both the AIC and the AICc measures. It also returns
// two vector of vectors which are the AIC values for the varius values of sigma
// passed to the function in the sigma values vector
void get_n_segments_for_various_sigma(vector<float> sigma_values, vector<float> one_sig_max_MLE,
vector<float>& all_x_data,
vector<int>& best_fit_AIC, vector<int>& best_fit_AICc,
vector< vector<float> >& AIC_for_each_n_segments,
vector< vector<float> >& AICc_for_each_n_segments)
{
int n_sigma = sigma_values.size();
vector<float> empty_vec;
vector<float> AIC_of_segments;
vector<float> AICc_of_segments;
vector< vector<float> > AIC_for_each(n_sigma);
vector< vector<float> > AICc_for_each(n_sigma);
vector<int> bf_AIC(n_sigma);
vector<int> bf_AICc(n_sigma);
// loop through the sigma values collecting the AIC and AICc values
for (int i = 0; i< n_sigma; i++)
{
// calcualte the AIC values for this value of sigma
calculate_AIC_of_segments_with_normalized_sigma(sigma_values[i], one_sig_max_MLE, all_x_data,
AIC_of_segments,AICc_of_segments);
AIC_for_each[i] = AIC_of_segments;
AICc_for_each[i] = AICc_of_segments;
// now find the minimum AIC and AICc
float minimum_AIC = 10000;
int min_AIC_segments = 0;
float minimum_AICc = 10000;
int min_AICc_segments = 0;
int n_AIC = AIC_of_segments.size();
for (int n_seg = 0; n_seg<n_AIC; n_seg++)
{