-
Notifications
You must be signed in to change notification settings - Fork 375
/
Copy pathgmtregress.c
1485 lines (1369 loc) · 72.3 KB
/
gmtregress.c
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) 1991-2025 by the GMT Team (https://www.generic-mapping-tools.org/team.html)
* See LICENSE.TXT file for copying and redistribution conditions.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; version 3 or 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 Lesser General Public License for more details.
*
* Contact info: www.generic-mapping-tools.org
*--------------------------------------------------------------------*/
/*
* Brief synopsis: gmtregress fits y = a + bx linear regression to x,y[,w] data
* using a variety of misfit norms and regression modes.
*
* Author: Paul Wessel
* Date: 5-JAN-2015
* Version: 6 API
*/
#include "gmt_dev.h"
#include "longopt/gmtregress_inc.h"
#define THIS_MODULE_CLASSIC_NAME "gmtregress"
#define THIS_MODULE_MODERN_NAME "gmtregress"
#define THIS_MODULE_LIB "core"
#define THIS_MODULE_PURPOSE "Linear regression of 1-D data sets"
#define THIS_MODULE_KEYS "<D{,>D}"
#define THIS_MODULE_NEEDS ""
#define THIS_MODULE_OPTIONS "-:>Vabdefghioqsw"
/* Various integer constants for flags and modes */
enum GMT_enum_regress {
GMTREGRESS_N_FARGS = 7,
GMTREGRESS_X = 0,
GMTREGRESS_Y = 1,
GMTREGRESS_XY = 2,
GMTREGRESS_RMA = 3,
GMTREGRESS_NORM_L1 = 0,
GMTREGRESS_NORM_L2 = 1,
GMTREGRESS_NORM_LMS = 2,
GMTREGRESS_NORM_RLS = 3,
GMTREGRESS_ANGLE = 0,
GMTREGRESS_MISFT = 1,
GMTREGRESS_SLOPE = 2,
GMTREGRESS_ICEPT = 3,
GMTREGRESS_SIGSL = 4,
GMTREGRESS_SIGIC = 5,
GMTREGRESS_XMEAN = 6,
GMTREGRESS_YMEAN = 7,
GMTREGRESS_R = 8,
GMTREGRESS_CORR = 9,
GMTREGRESS_MISFTY = 10,
GMTREGRESS_N_EFF = 11,
GMTREGRESS_NPAR = 12,
GMTREGRESS_NPAR_MAIN = 4,
GMTREGRESS_OUTPUT_GOOD = 1,
GMTREGRESS_OUTPUT_BAD = 2};
#define GMTREGRESS_FARGS "xymrczw" /* Default -F setting */
#define GMTREGRESS_ZSCORE_LIMIT 2.5 /* z-scores higher than this are outliers */
/* Control structure for gmtregress */
struct GMTREGRESS_CTRL {
struct GMTREGRESS_Out { /* ->[<outfile>] */
bool active;
char *file;
} Out;
struct GMTREGRESS_A { /* -A[<min>/<max>/<inc>][+f[n|p]] */
bool active;
bool force;
double min, max, inc;
} A;
struct GMTREGRESS_C { /* -C<confidence> */
bool active;
double value;
} C;
struct GMTREGRESS_E { /* -Ex|y|o|r */
bool active;
unsigned int mode;
} E;
struct GMTREGRESS_F { /* -Fxymrcsw */
bool active;
bool band; /* True if c was given */
bool param; /* True if only -Fp was given */
unsigned int n_cols;
char col[GMTREGRESS_N_FARGS]; /* Character codes for desired output in the right order */
} F;
struct GMTREGRESS_N { /* -N1|2|r|w */
bool active;
unsigned int mode;
} N;
struct GMTREGRESS_S { /* -S[r] */
bool active;
unsigned int mode;
} S;
struct GMTREGRESS_T { /* -T[<min>/<max>/]<inc>[+n] */
bool active;
bool no_eval;
struct GMT_ARRAY T;
} T;
struct GMTREGRESS_W { /* -W[s]x|y|r */
bool active;
unsigned int type; /* 0 for weights, 1 if sigmas */
unsigned int n_weights; /* 1-3 if any weights are selected */
unsigned int col[3]; /* Column numbers >=2 if weights are present */
} W;
struct GMTREGRESS_Z { /* -Z<limit> */
bool active;
int mode; /* if leading sign we only look for negative or positive outliers [both] */
double limit;
} Z;
};
static void *New_Ctrl (struct GMT_CTRL *GMT) { /* Allocate and initialize a new control structure */
struct GMTREGRESS_CTRL *C;
C = gmt_M_memory (GMT, NULL, 1, struct GMTREGRESS_CTRL);
C->A.min = -90.0; C->A.max = 90.0; C->A.inc = 1.0;
C->C.value = 0.95;
C->E.mode = GMTREGRESS_Y;
C->N.mode = GMTREGRESS_NORM_L2;
C->Z.limit = GMTREGRESS_ZSCORE_LIMIT;
return ((void *)C);
}
static void Free_Ctrl (struct GMT_CTRL *GMT, struct GMTREGRESS_CTRL *C) { /* Deallocate control structure */
if (!C) return;
gmt_M_str_free (C->Out.file);
gmt_free_array (GMT, &(C->T.T));
gmt_M_free (GMT, C);
}
static int usage (struct GMTAPI_CTRL *API, int level) {
const char *name = gmt_show_name_and_purpose (API, THIS_MODULE_LIB, THIS_MODULE_CLASSIC_NAME, THIS_MODULE_PURPOSE);
if (level == GMT_MODULE_PURPOSE) return (GMT_NOERROR);
GMT_Usage (API, 0, "usage: %s [<table>] [-A[<min>/<max>/<inc>][+f[n|p]]] [-C<level>] [-Ex|y|o|r] [-F<flags>] "
"[-N1|2|r|w] [-S[r]] [-T[<min>/<max>/]<inc>[+i|n]] [%s] [-W[w][x][y][r]] [-Z<limit>] [%s] "
"[%s] [%s] [%s] [%s] [%s] [%s] [%s] [%s] [%s] [%s]\n",
name, GMT_V_OPT, GMT_a_OPT, GMT_b_OPT, GMT_d_OPT, GMT_e_OPT, GMT_g_OPT, GMT_h_OPT, GMT_i_OPT,
GMT_o_OPT, GMT_q_OPT, GMT_w_OPT, GMT_PAR_OPT);
if (level == GMT_SYNOPSIS) return (GMT_MODULE_SYNOPSIS);
GMT_Message (API, GMT_TIME_NONE, " REQUIRED ARGUMENTS:\n");
GMT_Option (API, "<");
GMT_Message (API, GMT_TIME_NONE, "\n OPTIONAL ARGUMENTS:\n");
GMT_Usage (API, 1, "\n-A[<min>/<max>/<inc>][+f[n|p]]");
GMT_Usage (API, -2, "Examine misfit E as function of line slope; give angle range and increment [-90/+90/1]. "
"Option -F is not required as no model will be returned; instead we return "
"records of (angle, E, slope, intercept) for all angles specified. Optional modifier:");
GMT_Usage (API, 3, "+f Force LMS regressions to only search in the given angle range. "
"Optionally, append n or p for negative or positive slopes only [both].");
GMT_Usage (API, 1, "\n-C<level>");
GMT_Usage (API, -2, "Select level (in %%) to use in confidence band calculations (see -Fc) [95].");
GMT_Usage (API, 1, "\n-Ex|y|o|r");
GMT_Usage (API, -2, "Regression type. Select how misfit should be measured:");
GMT_Usage (API, 3, "x: Horizontally from data point to regression line.");
GMT_Usage (API, 3, "y: Vertically from data point to regression line [Default].");
GMT_Usage (API, 3, "o: Orthogonally from data point to regression line.");
GMT_Usage (API, 3, "r: Use Reduced Major Axis area misfit.");
GMT_Usage (API, 1, "\n-F<flags>");
GMT_Usage (API, -2, "Append desired output columns in any order; choose from:");
GMT_Usage (API, 3, "x: The x observations.");
GMT_Usage (API, 3, "y: The y observations.");
GMT_Usage (API, 3, "m: The estimated model values.");
GMT_Usage (API, 3, "r: The estimated residuals.");
GMT_Usage (API, 3, "c: The confidence limits (to add/subtract from m).");
GMT_Usage (API, 3, "z: The standardized residuals (z-scores).");
GMT_Usage (API, 3, "w: The outlier flags (1 or 0), or Reweighted Least Squares weights (for -Nw). "
"A value of 0 identifies an outlier.");
GMT_Usage (API, -2, "Note: Cannot use y|r|z|w with -T. With -T, x means locations implied by -T "
"Default is %s].", GMTREGRESS_FARGS);
GMT_Usage (API, -2, "Alternatively, choose -Fp to output only the model parameters: "
"N meanX meanY angle misfit slope icept sigma_slope sigma_icept r R N_effective");
GMT_Usage (API, 1, "\n-N1|2|r|w");
GMT_Usage (API, -2, "Append desired misfit norm; choose from:");
GMT_Usage (API, 3, "1: L-1 measure (mean absolute residuals).");
GMT_Usage (API, 3, "2: L-2 measure (mean squared residuals) [Default].");
GMT_Usage (API, 3, "r: LMS robust measure (median of squared residuals).");
GMT_Usage (API, 3, "w: RLS Reweighted L-2 measure (r followed by 2 after excluding outliers.");
GMT_Usage (API, 1, "\n-S[r]");
GMT_Usage (API, -2, "Skip records identified as outliers on output. Append r to reverse mode and "
"only output the outlier records. Cannot be used with -T [output all records].");
GMT_Usage (API, 1, "\n-T[<min>/<max>/]<inc>[+i|n]");
GMT_Usage (API, -2, "Evaluate model at the equidistant points implied by the arguments. "
"If only -T<inc>[+i|n] is given we reset <min> and <max> to the extreme x-values "
"for each segment.");
GMT_Usage (API, 3, "+n Note that <inc> is the number of t-values to produce instead of increment.");
GMT_Usage (API, 3, "+i Indicate <inc> is the reciprocal of desired <inc> (e.g., 3 for 0.3333.....).");
GMT_Usage (API, -2, "For absolute time data, append a valid time unit (%s) to the increment. "
"Alternatively, give a file with output times in the first column, or a comma-separated list. "
"Use -T0 to bypass model evaluation entirely "
"[Default uses locations of input data to evaluate the model].", GMT_TIME_UNITS_DISPLAY);
GMT_Option (API, "V");
GMT_Usage (API, 1, "\n-W[w][x][y][r]");
GMT_Usage (API, -2, "Supply individual 1-sigma uncertainties for data points [no weights]; append corresponding directives:");
GMT_Usage (API, 3, "x: Read sigma_x uncertainties.");
GMT_Usage (API, 3, "y: Read sigma_y uncertainties.");
GMT_Usage (API, 3, "r: Read r for x-y correlations.");
GMT_Usage (API, -2, "We then expect 1-3 extra columns with these data in the given order. "
"Given a sigma, the weight will be computed via weight = 1/sigma. "
"Use -Ww if weights are precomputed and not given as 1-sigma values. "
"Except for -N1 we square the weights when computing misfits.");
GMT_Usage (API, 1, "\n-Z<limit>");
GMT_Usage (API, -2, "Set z-score absolute value cutoff for outlier detection [%g]. "
"To only flag negative or positive outliers, specify a leading sign.", GMTREGRESS_ZSCORE_LIMIT);
GMT_Option (API, "a,bi,bo,d,e,g,h,i,o,q,w,.");
return (GMT_MODULE_USAGE);
}
static int parse (struct GMT_CTRL *GMT, struct GMTREGRESS_CTRL *Ctrl, struct GMT_OPTION *options) {
/* This parses the options provided to gmtregress and sets parameters in CTRL.
* Any GMT common options will override values set previously by other commands.
* It also replaces any file names specified as input or output with the data ID
* returned when registering these sources/destinations with the API.
*/
char *c = NULL;
bool scan_slopes = false;
unsigned int n_errors = 0, j, k, n, col;
struct GMT_OPTION *opt = NULL;
struct GMTAPI_CTRL *API = GMT->parent;
for (opt = options; opt; opt = opt->next) {
switch (opt->option) {
case '<': /* Skip input files after checking they exist */
if (GMT_Get_FilePath (API, GMT_IS_DATASET, GMT_IN, GMT_FILE_REMOTE, &(opt->arg))) n_errors++;
break;
case '>': /* Got named output file */
n_errors += gmt_M_repeated_module_option (API, Ctrl->Out.active);
n_errors += gmt_get_required_file (GMT, opt->arg, opt->option, 0, GMT_IS_DATASET, GMT_OUT, GMT_FILE_LOCAL, &(Ctrl->Out.file));
break;
/* Processes program-specific parameters */
case 'A': /* Explore E vs slope or force a limited angle range */
n_errors += gmt_M_repeated_module_option (API, Ctrl->A.active);
if ((c = strstr (opt->arg, "+f"))) {
Ctrl->A.force = true;
if (c[2] == 'n') Ctrl->A.max = 0.0; /* -90 to 0 */
if (c[2] == 'p') Ctrl->A.min = 0.0; /* 0 to +90 */
}
else
scan_slopes = true;
if (strchr (opt->arg, '/')) {
n = sscanf (opt->arg, "%lf/%lf/%lf", &Ctrl->A.min, &Ctrl->A.max, &Ctrl->A.inc);
n_errors += gmt_M_check_condition (GMT, n < 2, "Option -A: Must specify min/max/inc\n");
}
break;
case 'C': /* Set confidence level in %, convert to fraction */
n_errors += gmt_M_repeated_module_option (API, Ctrl->C.active);
n_errors += gmt_get_required_double (GMT, opt->arg, opt->option, 0, &Ctrl->C.value);
Ctrl->C.value *= 0.01;
break;
case 'E': /* Select regression type */
n_errors += gmt_M_repeated_module_option (API, Ctrl->E.active);
switch (opt->arg[0]) {
case 'x': Ctrl->E.mode = GMTREGRESS_X; break; /* Regress on x */
case 'y': Ctrl->E.mode = GMTREGRESS_Y; break; /* Regress on y */
case 'o': Ctrl->E.mode = GMTREGRESS_XY; break; /* Orthogonal Regression*/
case 'r': Ctrl->E.mode = GMTREGRESS_RMA; break; /* RMA Regression*/
default:
GMT_Report (API, GMT_MSG_ERROR, "Option -E: Unrecognized type %c\n", opt->arg[0]);
n_errors++;
break;
}
break;
case 'F': /* Select output columns */
n_errors += gmt_M_repeated_module_option (API, Ctrl->F.active);
if (!strcmp (opt->arg, "p")) { /* Just want to return model parameters */
Ctrl->F.param = true;
break;
}
for (j = 0, k = 0; opt->arg[j]; j++, k++) {
if (k < GMTREGRESS_N_FARGS) {
Ctrl->F.col[k] = opt->arg[j];
if (!strchr (GMTREGRESS_FARGS, opt->arg[j])) {
GMT_Report (API, GMT_MSG_ERROR, "Option -F: Choose from -F%s\n", GMTREGRESS_FARGS);
n_errors++;
}
Ctrl->F.n_cols++;
if (opt->arg[j] == 'c') Ctrl->F.band = true;
}
else {
n_errors++;
GMT_Report (API, GMT_MSG_ERROR, "Option -F: Too many output columns selected\n");
}
}
break;
case 'N': /* Select Norm for misfit calculations */
n_errors += gmt_M_repeated_module_option (API, Ctrl->N.active);
switch (opt->arg[0]) {
case '1': Ctrl->N.mode = GMTREGRESS_NORM_L1; break;
case '2': Ctrl->N.mode = GMTREGRESS_NORM_L2; break;
case 'r': Ctrl->N.mode = GMTREGRESS_NORM_LMS; break;
case 'w': Ctrl->N.mode = GMTREGRESS_NORM_RLS; break;
default:
GMT_Report (API, GMT_MSG_ERROR, "Option -N: Unrecognized norm %c\n", opt->arg[0]);
n_errors++;
break;
}
break;
case 'S': /* Restrict output records */
n_errors += gmt_M_repeated_module_option (API, Ctrl->S.active);
Ctrl->S.mode = (opt->arg[0] == 'r') ? GMTREGRESS_OUTPUT_BAD : GMTREGRESS_OUTPUT_GOOD;
break;
case 'T': /* Output lattice or length */
n_errors += gmt_M_repeated_module_option (API, Ctrl->T.active);
if (!strcmp (opt->arg, "0")) /* -T0 means no model evaluation */
Ctrl->T.no_eval = true;
else
n_errors += gmt_parse_array (GMT, 'T', opt->arg, &(Ctrl->T.T), GMT_ARRAY_TIME | GMT_ARRAY_DIST | GMT_ARRAY_UNIQUE, 0);
break;
case 'W': /* Weights or not */
n_errors += gmt_M_repeated_module_option (API, Ctrl->W.active);
if (opt->arg[0] == 'w') Ctrl->W.type = 1; /* Got weights; determine their column position */
for (k = Ctrl->W.type, col = GMT_Z; opt->arg[k]; k++) {
if (opt->arg[k] == 'x') Ctrl->W.col[GMT_X] = col++;
else if (opt->arg[k] == 'y') Ctrl->W.col[GMT_Y] = col++;
else if (opt->arg[k] == 'r') Ctrl->W.col[GMT_Z] = col++;
else {
GMT_Report (API, GMT_MSG_ERROR, "Option -W: Specify -W[w][x][y][r]\n");
n_errors++;
}
Ctrl->W.n_weights++;
}
if (Ctrl->W.n_weights > 3) {
GMT_Report (API, GMT_MSG_ERROR, "Option -W: Gave more than 3 uncertainty types\n");
n_errors++;
}
break;
case 'Z': /* Set new zscore limit */
n_errors += gmt_M_repeated_module_option (API, Ctrl->Z.active);
Ctrl->Z.limit = fabs (atof (opt->arg));
switch (opt->arg[0]) { /* Look for one-sided outliers */
case '-': Ctrl->Z.mode = -1; break;
case '+': Ctrl->Z.mode = +1; break;
default: Ctrl->Z.mode = 0; break;
}
break;
default: /* Report bad options */
n_errors += gmt_default_option_error (GMT, opt);
break;
}
}
n_errors += gmt_M_check_condition (GMT, Ctrl->A.force && Ctrl->N.mode == GMTREGRESS_NORM_L2, "Option -A: Cannot force limited angle range for -N2 norm.\n");
n_errors += gmt_M_check_condition (GMT, Ctrl->S.active && Ctrl->T.active, "Option -S: Cannot simultaneously specify -T.\n");
n_errors += gmt_M_check_condition (GMT, Ctrl->E.mode == GMTREGRESS_XY && Ctrl->W.n_weights == 1, "Option -Eo: Needs errors in both x,y or neither.\n");
n_errors += gmt_M_check_condition (GMT, Ctrl->E.mode == GMTREGRESS_RMA && Ctrl->W.n_weights == 1, "Option -Er: Needs errors in both x,y or neither.\n");
n_errors += gmt_M_check_condition (GMT, Ctrl->E.mode == GMTREGRESS_X && Ctrl->W.col[GMT_Y] > 0, "Option -Ex: Cannot specify errors in y.\n");
n_errors += gmt_M_check_condition (GMT, Ctrl->E.mode == GMTREGRESS_X && Ctrl->W.col[GMT_Z] > 0, "Option -Ex: Cannot specify x-y correlations\n");
n_errors += gmt_M_check_condition (GMT, Ctrl->E.mode == GMTREGRESS_Y && Ctrl->W.col[GMT_X] > 0, "Option -Ey: Cannot specify errors in x.\n");
n_errors += gmt_M_check_condition (GMT, Ctrl->E.mode == GMTREGRESS_Y && Ctrl->W.col[GMT_Z] > 0, "Option -Ey: Cannot specify x-y correlations\n");
n_errors += gmt_M_check_condition (GMT, (Ctrl->E.mode == GMTREGRESS_Y || Ctrl->E.mode == GMTREGRESS_X) && Ctrl->W.n_weights == 2,
"Option -Ex|y: Cannot specify errors in both x and y.\n");
n_errors += gmt_M_check_condition (GMT, Ctrl->C.value < 0.0 || Ctrl->C.value >= 1.0, "Option -C: Level must be in 0-100%% range.\n");
n_errors += gmt_M_check_condition (GMT, Ctrl->T.active && scan_slopes, "Option -A: Cannot simultaneously specify -T.\n");
n_errors += gmt_M_check_condition (GMT, scan_slopes && Ctrl->F.active, "Option -A: Cannot simultaneously specify -F.\n");
n_errors += gmt_M_check_condition (GMT, scan_slopes && Ctrl->C.active, "Option -A: Cannot simultaneously specify -C.\n");
n_errors += gmt_M_check_condition (GMT, Ctrl->C.active && Ctrl->F.param, "Option -Fp: Cannot simultaneously specify -C.\n");
n_errors += gmt_M_check_condition (GMT, Ctrl->T.active && Ctrl->F.param, "Option -Fp: Cannot simultaneously specify -T.\n");
n_errors += gmt_M_check_condition (GMT, Ctrl->Z.active && Ctrl->Z.limit == 0.0, "Option -Z: Give a non-zero limit.\n");
if (GMT->common.b.active[GMT_IN] && GMT->common.b.ncol[GMT_IN] == 0) GMT->common.b.ncol[GMT_IN] = 2;
n_errors += gmt_M_check_condition (GMT, GMT->common.b.active[GMT_IN] && GMT->common.b.ncol[GMT_IN] < 2,
"Binary input data (-bi) must have at least 2 columns.\n");
return (n_errors ? GMT_PARSE_ERROR : GMT_NOERROR);
}
/* Some of the inspiration for this module came from the following two papers:
*
* Hartmann, C., P. Venkeerberghen, J. Smeyers-Verbeke, and D. L. Massart (1997),
* Robust orthogonal regression for the outlier detection when comparing two
* serious of measurement results, Analytica Chimica Acta, 344, 17-28.
* York, D., N. M. Evensen, M. L. Martinez, and J. De Basebe Delgado (2004),
* Unified equations for the slope, intercept, and standard errors of the
* best straight line, Am. J. Phys., 72(3), 367-375.
*
* as well as the standard book on regular and robust regression:
*
* Draper, N. R., and H. Smith (1998), Applied regression analysis,
* 3rd ed., 736 pp., John Wiley and Sons, New York.
*
* Rousseeuw, P. J., and A. M. Leroy (1987), Robust regression and outlier
* detection, 329 pp., John Wiley and Sons, New York.
*/
GMT_LOCAL double gmtregress_model (double x, double *par) {
/* Evaluate the model given the parameters in par */
return (par[GMTREGRESS_SLOPE] * x + par[GMTREGRESS_ICEPT]);
}
GMT_LOCAL double gmtregress_gmt_sum (double *x, uint64_t n) {
/* Return sum of values in the array x */
uint64_t k;
double S = 0.0;
for (k = 0; k < n; k++) S += x[k];
return (S);
}
GMT_LOCAL double gmtregress_icept_basic (struct GMT_CTRL *GMT, double *e, uint64_t n, unsigned int norm) {
/* Return the proper "average" intercept given the chosen norm */
unsigned int GMT_n_multiples = 0;
double intercept = 0.0, *ee = NULL;
if (norm != GMTREGRESS_NORM_L2) { /* Need temporary space for scaled residuals */
ee = gmt_M_memory (GMT, NULL, n, double);
gmt_M_memcpy (ee, e, n, double);
gmt_sort_array (GMT, ee, n, GMT_DOUBLE);
}
switch (norm) {
case GMTREGRESS_NORM_L1: /* Return median */
intercept = (n%2) ? ee[n/2] : 0.5 * (e[(n-1)/2] + ee[n/2]);
break;
case GMTREGRESS_NORM_L2: /* Return mean */
intercept = gmtregress_gmt_sum (e, n) / n;
break;
case GMTREGRESS_NORM_LMS: /* Return mode */
gmt_mode (GMT, ee, n, n/2, 0, -1, &GMT_n_multiples, &intercept);
break;
}
if (norm != GMTREGRESS_NORM_L2) gmt_M_free (GMT, ee);
return (intercept);
}
GMT_LOCAL double gmtregress_icept_weighted (struct GMT_CTRL *GMT, double *e, double *W, uint64_t n, unsigned int norm) {
/* Return the proper "weighted average" intercept given chosen norm */
double intercept = 0.0;
struct GMT_OBSERVATION *ee = NULL;
if (norm != GMTREGRESS_NORM_L2) { /* Need temporary space for scaled residuals */
uint64_t k;
ee = gmt_M_memory (GMT, NULL, n, struct GMT_OBSERVATION);
for (k = 0; k < n; k++) {
ee[k].weight = (gmt_grdfloat)W[k];
ee[k].value = (gmt_grdfloat)e[k];
}
}
switch (norm) {
case GMTREGRESS_NORM_L1: /* Return weighted median */
intercept = gmt_median_weighted (GMT, ee, n);
break;
case GMTREGRESS_NORM_L2: /* Return weighted mean */
intercept = gmt_mean_weighted (GMT, e, W, n);
break;
case GMTREGRESS_NORM_LMS: /* Return weighted mode */
intercept = gmt_mode_weighted (GMT, ee, n);
break;
}
if (norm != GMTREGRESS_NORM_L2) gmt_M_free (GMT, ee);
return (intercept);
}
GMT_LOCAL double gmtregress_intercept (struct GMT_CTRL *GMT, double *e, double *W, uint64_t n, bool weighted, unsigned int norm) {
/* Return the weighted or unweighted intercept given chosen norm */
double a = (weighted) ? gmtregress_icept_weighted (GMT, e, W, n, norm) : gmtregress_icept_basic (GMT, e, n, norm);
return (a);
}
GMT_LOCAL double gmtregress_get_scale_factor (unsigned int regression, double slope) {
/* Scale that turns a y-misfit into another misfit measures given regression slope */
double f = 1.0; /* To please gcc */
slope = fabs (slope);
switch (regression) {
case GMTREGRESS_X: f = 1.0 / slope; break;
case GMTREGRESS_Y: f = 1.0; break;
case GMTREGRESS_XY: f = sqrt (1.0 / (1.0 + slope * slope)); break;
case GMTREGRESS_RMA: f = sqrt (1.0 / slope); break;
}
return (f);
}
GMT_LOCAL double gmtregress_n_effective (double *W, uint64_t n) {
/* Determine the effective number of measurements from W [Bevington, 1969] */
uint64_t k;
double W_sum1 = 0.0, W_sum2 = 0.0;
for (k = 0; k < n; k++) {
W_sum1 += W[k];
W_sum2 += W[k] * W[k];
}
return (W_sum1 * W_sum2 / W_sum2);
}
GMT_LOCAL double gmtregress_L1_misfit (struct GMT_CTRL *GMT, double *ey, double *W, uint64_t n, unsigned int regression, double slope, double n_eff) {
/* Compute L1 misfit from y-residuals ey and weights W for regression x|y|o|r.
* Since W contains squared weights and we use a linear sum we take sqrt(W) below */
uint64_t k;
double f, wi, E = 0.0, W_sum = 0.0;
gmt_M_unused(GMT);
f = gmtregress_get_scale_factor (regression, slope);
for (k = 0; k < n; k++) {
wi = sqrt (W[k]);
E += fabs (wi * ey[k]);
W_sum += wi;
}
return (f * E / (W_sum * (n_eff - 2) / n_eff));
}
GMT_LOCAL double gmtregress_L2_misfit (struct GMT_CTRL *GMT, double *ey, double *W, uint64_t n, unsigned int regression, double slope, double n_eff) {
/* Compute L2 misfit from y-residuals ey and weights W for regression x|y|o|r */
uint64_t k;
double f, E = 0.0, W_sum;
gmt_M_unused(GMT);
f = gmtregress_get_scale_factor (regression, slope);
W_sum = gmtregress_gmt_sum (W, n);
for (k = 0; k < n; k++)
E += W[k] * ey[k] * ey[k]; /* Basically a chi-squared sum */
return (f * f * E / (W_sum * (n_eff - 2) / n_eff)); /* f^2 since E was computed from squared misfits */
}
GMT_LOCAL double gmtregress_LMS_misfit (struct GMT_CTRL *GMT, double *ey, double *W, uint64_t n, unsigned int regression, double slope, double n_eff) {
/* Compute LMS misfit from y-residuals ey and weights W for regression x|y|o|r */
uint64_t k;
double f, E, *ee = gmt_M_memory (GMT, NULL, n, double);
gmt_M_unused(n_eff);
f = gmtregress_get_scale_factor (regression, slope);
for (k = 0; k < n; k++) ee[k] = W[k] * ey[k] * ey[k];
gmt_sort_array (GMT, ee, n, GMT_DOUBLE);
E = (n%2) ? ee[n/2] : 0.5 * (ee[(n-1)/2] + ee[n/2]);
gmt_M_free (GMT, ee);
return (f * f * E); /* f^2 since E was computed from squared misfits */
}
GMT_LOCAL double gmtregress_L1_scale (struct GMT_CTRL *GMT, double *ey, double *W, uint64_t n, double *par) {
/* L1 regression scale estimate is weighted median absolute residual */
uint64_t k;
double MAD;
struct GMT_OBSERVATION *ee = NULL;
gmt_M_unused(GMT); gmt_M_unused(par);
/* Compute the (weighted) MAD */
ee = gmt_M_memory (GMT, NULL, n, struct GMT_OBSERVATION);
for (k = 0; k < n; k++) {
ee[k].weight = (gmt_grdfloat)W[k];
ee[k].value = (gmt_grdfloat)fabs (ey[k]);
}
MAD = gmt_median_weighted (GMT, ee, n);
gmt_M_free (GMT, ee);
return (MAD);
}
GMT_LOCAL double gmtregress_L2_scale (struct GMT_CTRL *GMT, double *ey, double *W, uint64_t n, double *par) {
/* LS scale estimate as weighted average residual */
double W_sum, scale;
gmt_M_unused(GMT); gmt_M_unused(ey);
W_sum = gmtregress_gmt_sum (W, n);
scale = sqrt ((par[GMTREGRESS_N_EFF] - 2)*par[GMTREGRESS_MISFT] / par[GMTREGRESS_N_EFF]); /* Undo the previous (n_eff-2)/n_eff division */
GMT_Report (GMT->parent, GMT_MSG_DEBUG, "gmtregress_L2_scale: W_sum = %lg scale = %lg\n", W_sum, scale);
return (scale);
}
GMT_LOCAL double gmtregress_LMS_scale (struct GMT_CTRL *GMT, double *ey, double *W, uint64_t n, double *par) {
/* LMS scale estimate as per Rousseuuw & Leroy [1987] */
double scale;
gmt_M_unused(GMT); gmt_M_unused(ey); gmt_M_unused(W);
scale = MAD_NORMALIZE * (1.0 + 5.0 / (n - 2.0)) * sqrt (par[GMTREGRESS_MISFT]);
return (scale);
}
GMT_LOCAL void gmtregress_eval_product (double *x, double *y, double *xy, uint64_t n) {
/* Compute new array xy[i] = x[i] * y[i] */
uint64_t k;
for (k = 0; k < n; k++) xy[k] = x[k] * y[k];
}
GMT_LOCAL double gmtregress_eval_sumprod2 (double *x, double *y, uint64_t n) {
/* Sum up the product of x * y */
uint64_t k;
double sum = 0.0;
for (k = 0; k < n; k++) sum += x[k] * y[k];
return (sum);
}
GMT_LOCAL double gmtregress_eval_sumprod3 (double *x, double *y, double *z, uint64_t n) {
/* Sum up the product of x * y * z */
uint64_t k;
double sum = 0.0;
for (k = 0; k < n; k++) sum += x[k] * y[k] * z[k];
return (sum);
}
GMT_LOCAL void gmtregress_eval_add (double *x, double c, double *out, uint64_t n) {
/* Compute array out[i] = x[i] + c */
uint64_t k;
for (k = 0; k < n; k++) out[k] = x[k] + c;
}
GMT_LOCAL void gmtregress_ones (double *x, uint64_t n) {
/* Set a unitary vector */
uint64_t k;
for (k = 0; k < n; k++) x[k] = 1.0;
}
GMT_LOCAL void gmtregress_get_correlation (struct GMT_CTRL *GMT, double *X, double *Y, double *w[], uint64_t n, double *par) {
/* standard r = s_xy / (s_x * s_y), using the weighted expressions for these terms.
* Currently only set up to do standard y on x only (REGRESS_Y).
*/
uint64_t k;
double sx = 0.0, sy = 0.0, sxy = 0.0, wx = 1.0, wy = 1.0, swx = 0.0, swy = 0.0, swxy = 0.0;
gmt_M_unused(GMT);
for (k = 0; k < n; k++) {
if (w[GMT_X]) wx = w[GMT_X][k]; /* Was given x-weights */
if (w[GMT_Y]) wy = w[GMT_Y][k]; /* Was given y-weights */
sx += wx * pow (X[k] - par[GMTREGRESS_XMEAN], 2.0);
sy += wy * pow (Y[k] - par[GMTREGRESS_YMEAN], 2.0);
sxy += wx * wy * (X[k] - par[GMTREGRESS_XMEAN]) * (Y[k] - par[GMTREGRESS_YMEAN]);
swx += wx; swy += wy; swxy += wx * wy;
}
par[GMTREGRESS_CORR] = (sxy / swxy) / sqrt ((sx / swx) * (sy / swy));
}
GMT_LOCAL void gmtregress_get_coeffR (struct GMT_CTRL *GMT, double *X, double *Y, double *w[], uint64_t n, unsigned int regression, double *par) {
/* Compute coefficient of determination, R ( = r^2 for LSY Pearsonian correlation).
* Currently only set up to do standard y on x (weights on y) only (REGRESS_Y).
* Compute both coefficient of determination (R) and the correlation coefficient (r).
* R = 1 - SSR/SST, with
* SSR is the sum of squared residuals: sum (y_i - y(x_i))^2
* and SST is the sum of total variance of the model : sum (y_i - mean(y))^2
* We augment these with weights w_i as well, if given.
*/
uint64_t k;
double SSR = 0.0, SST = 0.0, y_hat, ww = 1.0, f;
gmt_M_unused(GMT);
f = gmtregress_get_scale_factor (regression, par[GMTREGRESS_SLOPE]);
f *= f; /* Since working on squared misfits */
for (k = 0; k < n; k++) {
if (w[GMT_Y]) ww = w[GMT_Y][k]; /* Was given weights */
y_hat = par[GMTREGRESS_SLOPE] * X[k] + par[GMTREGRESS_ICEPT];
SSR += ww * pow (Y[k] - y_hat, 2.0);
SST += ww * pow (Y[k] - par[GMTREGRESS_YMEAN], 2.0);
}
par[GMTREGRESS_R] = 1.0 - f * SSR / SST;
}
GMT_LOCAL double gmtregress_demeaning (struct GMT_CTRL *GMT, double *X, double *Y, double *w[], uint64_t n, double *par, double *U, double *V, double *W, double *alpha, double *beta) {
/* Compute weighted X and Y means, return these via par, and calculate residuals U and V and weights W
* (and alpha, beta if orthogonal). If orthogonal regression we expect a preliminary estimate of the
* slope to be present in par[GMTREGRESS_SLOPE]. Return weight sum S. This function carries out many of
* the steps in York et al [2004]. */
double S;
gmt_M_unused(GMT);
if (w && w[GMT_X] && w[GMT_Y]) { /* Orthogonal regression with x/y weights [and optionally x-y correlations] requested */
double corr_i = 0.0, alpha_i, w_xy;
uint64_t i;
/* Compute Wi from w(X_i), w(Y_i), r_i and best estimate of slope placed in par[GMTREGRESS_SLOPE]. */
for (i = 0; i < n; i++) {
w_xy = w[GMT_X][i] * w[GMT_Y][i];
alpha_i = sqrt (w_xy);
if (w[GMT_Z]) corr_i = w[GMT_Z][i];
W[i] = (w_xy > 0.0) ? w_xy / (w[GMT_X][i] + par[GMTREGRESS_SLOPE] * par[GMTREGRESS_SLOPE] * w[GMT_Y][i] - 2 * par[GMTREGRESS_SLOPE] * corr_i * alpha_i) : 0.0;
if (alpha) alpha[i] = alpha_i;
}
par[GMTREGRESS_N_EFF] = gmtregress_n_effective (W, n); /* Effective number of measurements */
/* Step 4: Compute weighted X_mean, Y_mean, then U, V, and beta */
S = gmtregress_gmt_sum (W, n); /* Get sum of weights */
par[GMTREGRESS_XMEAN] = gmtregress_eval_sumprod2 (W, X, n) / S; /* Compute weighted X_mean */
par[GMTREGRESS_YMEAN] = gmtregress_eval_sumprod2 (W, Y, n) / S; /* Compute weighted Y_mean */
gmtregress_eval_add (X, -par[GMTREGRESS_XMEAN], U, n); /* Compute U */
gmtregress_eval_add (Y, -par[GMTREGRESS_YMEAN], V, n); /* Compute V */
if (beta && alpha) { /* Compute beta (as alpha above) which is needed for weighted orthogonal regression */
for (i = 0; i < n; i++) {
if (w[GMT_Z]) corr_i = w[GMT_Z][i];
beta[i] = W[i] * (U[i] / w[GMT_Y][i] + par[GMTREGRESS_SLOPE] * V[i] / w[GMT_X][i] - (par[GMTREGRESS_SLOPE] * U[i] + V[i]) * corr_i / alpha[i]);
if (gmt_M_is_dnan (beta[i])) beta[i] = 0.0; /* Prevent division by zero */
}
}
GMT_Report (GMT->parent, GMT_MSG_DEBUG, "Computed single weights from separate x- and y-weights %s\n",
(w[GMT_Z]) ? " and x-y correlations" : "only");
}
else if (w && (w[GMT_X] || w[GMT_Y])) { /* Not orthogonal regression, and have weights in x or y */
double *pW = (w[GMT_X]) ? w[GMT_X] : w[GMT_Y]; /* Shorthand for the (squared) weights */
gmt_M_memcpy (W, pW, n, double); /* Duplicate the chosen weight array to W */
S = gmtregress_gmt_sum (W, n); /* Get sum of weights */
par[GMTREGRESS_XMEAN] = gmtregress_eval_sumprod2 (W, X, n) / S; /* Compute weighted X_mean */
par[GMTREGRESS_YMEAN] = gmtregress_eval_sumprod2 (W, Y, n) / S; /* Compute weighted Y_mean */
gmtregress_eval_add (X, -par[GMTREGRESS_XMEAN], U, n); /* Compute U */
gmtregress_eval_add (Y, -par[GMTREGRESS_YMEAN], V, n); /* Compute V */
par[GMTREGRESS_N_EFF] = gmtregress_n_effective (W, n); /* Effective number of measurements */
GMT_Report (GMT->parent, GMT_MSG_DEBUG, "Computed weights from given %c-weights\n", (w[GMT_X]) ? 'x' : 'y');
}
else { /* No weights, create unit array */
gmtregress_ones (W, n); /* Unit weights */
par[GMTREGRESS_XMEAN] = gmtregress_gmt_sum (X, n) / n; /* Compute X_mean */
par[GMTREGRESS_YMEAN] = gmtregress_gmt_sum (Y, n) / n; /* Compute X_mean */
gmtregress_eval_add (X, -par[GMTREGRESS_XMEAN], U, n); /* Compute U */
gmtregress_eval_add (Y, -par[GMTREGRESS_YMEAN], V, n); /* Compute V */
S = (double)n; /* Trivial sum of weights */
par[GMTREGRESS_N_EFF] = n; /* Effective = actual number of measurements */
GMT_Report (GMT->parent, GMT_MSG_DEBUG, "Computed unit weights in the absence of actual weights\n");
}
return (S); /* Returning the weight sum */
}
GMT_LOCAL double gmtregress_LSy_regress1D (struct GMT_CTRL *GMT, double *x, double *y, double *w[], uint64_t n, double *par) {
/* Basic LS y-regression on x, only uses w[GMT_Y] weights if not NULL */
uint64_t k;
double *Q = gmt_M_memory (GMT, NULL, n, double), *W = gmt_M_memory (GMT, NULL, n, double);
double *U = gmt_M_memory (GMT, NULL, n, double), *V = gmt_M_memory (GMT, NULL, n, double);
double S, S_xx, S_xy, D, scale;
gmt_M_memset (par, GMTREGRESS_NPAR, double); /* Reset all regression parameters */
S = gmtregress_demeaning (GMT, x, y, w, n, par, U, V, W, NULL, NULL); /* alpha, beta not used here so passing NULL */
/* Because we operate on U and V, the terms S_x = S_y == 0 and are thus ignored in the equations below */
if (w && w[GMT_Y]) { /* Weighted regression */
double *P = gmt_M_memory (GMT, NULL, n, double);
gmtregress_eval_product (U, W, P, n); /* Form P[i] = W[i] * U[i] */
gmtregress_eval_product (P, U, Q, n); /* Form Q[i] = P[i] * U[i] = W[i] * U[i] * U[i] */
S_xx = gmtregress_gmt_sum (Q, n); /* The weighted sum of U^2 */
gmtregress_eval_product (P, V, Q, n); /* Form Q[i] = P[i] * V[i] = W[i] * U[i] * V[i] */
S_xy = gmtregress_gmt_sum (Q, n); /* The weighted sum of U*V */
gmt_M_free (GMT, P);
}
else { /* No weights supplied */
gmtregress_eval_product (U, U, Q, n); /* Form Q[i] = U[i] * U[i] */
S_xx = gmtregress_gmt_sum (Q, n); /* The sum of U^2 */
gmtregress_eval_product (U, V, Q, n); /* Form Q[i] = U[i] * V[i] */
S_xy = gmtregress_gmt_sum (Q, n); /* The sum of U*V */
}
D = 1.0 / (S * S_xx);
par[GMTREGRESS_SLOPE] = (S * S_xy) * D;
par[GMTREGRESS_ICEPT] = par[GMTREGRESS_YMEAN] - par[GMTREGRESS_SLOPE] * par[GMTREGRESS_XMEAN];
par[GMTREGRESS_SIGSL] = sqrt (S * D);
par[GMTREGRESS_SIGIC] = sqrt (S_xx * D);
for (k = 0; k < n; k++) /* Here we recycle Q to hold y-residual e */
Q[k] = y[k] - gmtregress_model (x[k], par);
par[GMTREGRESS_MISFT] = par[GMTREGRESS_MISFTY] = gmtregress_L2_misfit (GMT, Q, W, n, GMTREGRESS_Y, 0.0, par[GMTREGRESS_N_EFF]);
par[GMTREGRESS_ANGLE] = atand (par[GMTREGRESS_SLOPE]);
scale = gmtregress_L2_scale (GMT, NULL, W, n, par);
gmt_M_free (GMT, Q);
gmt_M_free (GMT, U);
gmt_M_free (GMT, V);
gmt_M_free (GMT, W);
return (scale);
}
GMT_LOCAL void gmtregress_yorkRMA_error (struct GMT_CTRL *GMT, double *U, double *V, uint64_t n, double sx, double sy, double *par) {
uint64_t k;
double *u = gmt_M_memory (GMT, NULL, n, double), *x = gmt_M_memory (GMT, NULL, n, double);
double v, sum_u2, mean_x;
gmt_M_unused (GMT);
/* From York et al [2004] for RMA case when w(Xi) = 1/sx^2 and w(Yi) = 1/sy2 */
sx *= sx; sy *= sy; /* Get variances */
v = sy + par[GMTREGRESS_SLOPE] * par[GMTREGRESS_SLOPE] * sx;
for (k = 0; k < n; k++)
x[k] = par[GMTREGRESS_XMEAN] + (U[k] * sy + par[GMTREGRESS_SLOPE] * V[k] * sx) / v;
mean_x = gmtregress_gmt_sum (x, n) / n; /* Get sum of x divided by n */
for (k = 0; k < n; k++) /* compute u */
u[k] = x[k] - mean_x;
gmtregress_eval_product (u, u, x, n); /* Compute x[i] = u[i] * u[i] */
sum_u2 = gmtregress_gmt_sum (x, n); /* Get sum of u^2 */
par[GMTREGRESS_SIGSL] = 1 / sum_u2;
par[GMTREGRESS_SIGIC] = (1 / n + mean_x * mean_x / sum_u2);
par[GMTREGRESS_SIGSL] = sqrt (par[GMTREGRESS_SIGSL]);
par[GMTREGRESS_SIGIC] = sqrt (par[GMTREGRESS_SIGIC]);
gmt_M_free (GMT, x);
gmt_M_free (GMT, u);
}
GMT_LOCAL double gmtregress_LSxy_regress1D_basic (struct GMT_CTRL *GMT, double *x, double *y, uint64_t n, double *par) {
/* Basic LS xy orthogonal regression, with no data errors. See York [1966] and York et al [2004] */
uint64_t k;
unsigned int p;
double *u = gmt_M_memory (GMT, NULL, n, double), *v = gmt_M_memory (GMT, NULL, n, double);
double *W = gmt_M_memory (GMT, NULL, n, double), *Q = gmt_M_memory (GMT, NULL, n, double);
double mean_x, mean_y, sig_x, sig_y, sum_u2, sum_v2, sum_uv, part1, part2, r, scale, a[2], b[2], E[2];
mean_x = gmt_mean_and_std (GMT, x, n, &sig_x);
mean_y = gmt_mean_and_std (GMT, y, n, &sig_y);
/* Normalize the data */
gmtregress_eval_add (x, -mean_x, u, n); /* Get reduced x-coordinates u */
gmtregress_eval_add (y, -mean_y, v, n); /* Get reduced y-coordinates v */
gmtregress_eval_product (u, u, Q, n); /* Compute Q[i] = u[i] * u[i] */
sum_u2 = gmtregress_gmt_sum (Q, n); /* Get sum of u*u */
gmtregress_eval_product (v, v, Q, n); /* Compute Q[i] = v[i] * v[i] */
sum_v2 = gmtregress_gmt_sum (Q, n); /* Get sum of v*v */
gmtregress_eval_product (u, v, Q, n); /* Compute Q[i] = u[i] * v[i] */
sum_uv = gmtregress_gmt_sum (Q, n); /* Get sum of u*v */
part1 = sum_v2 - sum_u2;
part2 = sqrt (pow (sum_u2 - sum_v2, 2.0) + 4.0 * sum_uv * sum_uv);
b[0] = (part1 + part2) / (2.0 * sum_uv);
b[1] = (part1 - part2) / (2.0 * sum_uv);
r = sum_uv / sqrt (sum_u2 * sum_v2);
GMT_Report (GMT->parent, GMT_MSG_DEBUG, "gmtregress_LSxy_regress1D_basic: r = %lg\n", r);
gmtregress_ones (W, n); /* Unit weights */
for (p = 0; p < 2; p++) { /* Compute E from vertical y-residuals for both solutions to the slope */
a[p] = mean_y - b[p] * mean_x; /* Trial intercept */
for (k = 0; k < n; k++) Q[k] = y[k] - b[p] * x[k] - a[p];
E[p] = gmtregress_L2_misfit (GMT, Q, W, n, GMTREGRESS_XY, b[p], par[GMTREGRESS_N_EFF]);
}
p = (E[0] < E[1]) ? 0 : 1; /* Determine the solution with the smallest misfit and copy to par array: */
par[GMTREGRESS_SLOPE] = b[p];
par[GMTREGRESS_ICEPT] = a[p];
gmtregress_yorkRMA_error (GMT, u, v, n, sig_x, sig_y, par);
par[GMTREGRESS_MISFT] = E[p];
/* Compute regular y LS misfit to use with confidence band */
for (k = 0; k < n; k++) Q[k] = y[k] - b[p] * x[k] - a[p];
par[GMTREGRESS_MISFTY] = gmtregress_L2_misfit (GMT, Q, W, n, GMTREGRESS_Y, 0.0, par[GMTREGRESS_N_EFF]);
par[GMTREGRESS_ANGLE] = atand (par[GMTREGRESS_SLOPE]);
par[GMTREGRESS_XMEAN] = mean_x;
par[GMTREGRESS_YMEAN] = mean_y;
scale = gmtregress_L2_scale (GMT, NULL, W, n, par);
gmt_M_free (GMT, Q);
gmt_M_free (GMT, W);
gmt_M_free (GMT, u);
gmt_M_free (GMT, v);
return (scale);
}
GMT_LOCAL double gmtregress_LSRMA_regress1D (struct GMT_CTRL *GMT, double *x, double *y, double *w[], uint64_t n, double *par) {
/* Basic LS RMA orthogonal regression with no weights [York et al, 2004] */
uint64_t k;
double sx, sy, scale, r, sum_u2;
double *U = gmt_M_memory (GMT, NULL, n, double), *V = gmt_M_memory (GMT, NULL, n, double), *Q = gmt_M_memory (GMT, NULL, n, double), *W = gmt_M_memory (GMT, NULL, n, double);
gmt_M_memset (par, GMTREGRESS_NPAR, double);
(void)gmtregress_demeaning (GMT, x, y, w, n, par, U, V, W, NULL, NULL);
r = gmt_corrcoeff (GMT, U, V, n, 1);
sx = gmt_std_weighted (GMT, U, w[GMT_X], 0.0, n);
sy = gmt_std_weighted (GMT, V, w[GMT_Y], 0.0, n);
gmtregress_eval_product (U, U, Q, n); /* Compute Q[i] = u[i] * u[i] */
sum_u2 = gmtregress_gmt_sum (Q, n); /* Get sum of u*u */
GMT_Report (GMT->parent, GMT_MSG_DEBUG, "gmtregress_LSRMA_regress1D: sum_u2 = %lg\n", sum_u2);
par[GMTREGRESS_SLOPE] = sy / sx;
if (r < 0.0) par[GMTREGRESS_SLOPE] = -par[GMTREGRESS_SLOPE]; /* Negative correlation means negative slope */
par[GMTREGRESS_ICEPT] = par[GMTREGRESS_YMEAN] - par[GMTREGRESS_SLOPE] * par[GMTREGRESS_XMEAN];
par[GMTREGRESS_ANGLE] = atand (par[GMTREGRESS_SLOPE]);
gmtregress_yorkRMA_error (GMT, U, V, n, sx, sy, par);
for (k = 0; k < n; k++) /* Here we recycle U as y-residual e */
U[k] = y[k] - gmtregress_model (x[k], par);
/* Report RMA misfit but use L2 y-misfit in calculations for confidence band */
par[GMTREGRESS_MISFT] = gmtregress_L2_misfit (GMT, U, W, n, GMTREGRESS_RMA, par[GMTREGRESS_SLOPE], par[GMTREGRESS_N_EFF]);
par[GMTREGRESS_MISFTY] = gmtregress_L2_misfit (GMT, U, W, n, GMTREGRESS_Y, par[GMTREGRESS_SLOPE], par[GMTREGRESS_N_EFF]);
scale = gmtregress_L2_scale (GMT, NULL, W, n, par);
gmt_M_free (GMT, U);
gmt_M_free (GMT, V);
gmt_M_free (GMT, Q);
gmt_M_free (GMT, W);
return (scale);
}
GMT_LOCAL void gmtregress_gmtregress_regress1D_sub (struct GMT_CTRL *GMT, double *x, double *y, double *W, double *e, uint64_t n, unsigned int regression, unsigned int norm, bool weighted, double angle, double *par) {
/* Solve the linear regression problem for a given slope angle and chosen misfit and norm to give a unique intercept */
/* x, y here are actually the reduced coordinates U, V */
uint64_t k;
double a, b, E;
double (*misfit) (struct GMT_CTRL *GMT, double *ey, double *W, uint64_t n, unsigned int regression, double slope, double n_eff);
switch (norm) { /* Set misfit function pointer */
case GMTREGRESS_NORM_L1: misfit = gmtregress_L1_misfit; break;
case GMTREGRESS_NORM_L2: misfit = gmtregress_L2_misfit; break;
case GMTREGRESS_NORM_LMS: misfit = gmtregress_LMS_misfit; break;
default:
GMT_Report (GMT->parent, GMT_MSG_WARNING, "Misfit norm not specified? - set to L2\n");
misfit = gmtregress_L2_misfit;
break;
}
if (gmt_M_is_zero (fabs (angle) - 90.0)) { /* Vertical line is a special case since slope is infinity */
b = GMT->session.d_NaN; /* Slope is undefined */
a = gmtregress_intercept (GMT, x, W, n, weighted, norm); /* Determine best x-intercept */
for (k = 0; k < n; k++) e[k] = x[k] - a; /* Final x-residuals */
/* For GMTREGRESS_Y|GMTREGRESS_RMA a vertical line gives Inf misfit; the others are measured horizontally so always finite.
* We obtain E by passing e as ex but giving the mode Gas MTREGRESS_Y instead and pass 0 as slope. */
E = (regression == GMTREGRESS_Y || regression == GMTREGRESS_RMA) ? DBL_MAX : misfit (GMT, e, W, n, GMTREGRESS_Y, 0.0, par[GMTREGRESS_N_EFF]);
}
else if (gmt_M_is_zero (angle)) { /* Horizontal line is also a special case since X and RMA regressions give infinite misfits */
b = 0.0; /* Slope is straightforward */
a = gmtregress_intercept (GMT, y, W, n, weighted, norm); /* Determine best y-intercept */
/* For GMTREGRESS_X|GMTREGRESS_RMA a horizontal line gives Inf misfit; the others are measured vertically so always finite.
* We obtain E by passing e as ey but giving mode GMTREGRESS_Y instead and pass 0 as slope. */
for (k = 0; k < n; k++) e[k] = y[k] - a; /* Final y-residuals */
E = (regression == GMTREGRESS_X || regression == GMTREGRESS_RMA) ? DBL_MAX : misfit (GMT, e, W, n, GMTREGRESS_Y, 0.0, par[GMTREGRESS_N_EFF]);
}
else { /* Neither vertical|horizontal, we can measure any misfit and need to pass the slope b */
b = tand (angle); /* Regression slope */
for (k = 0; k < n; k++) e[k] = y[k] - b * x[k]; /* The y-residuals after removing sloping trend */
a = gmtregress_intercept (GMT, e, W, n, weighted, norm); /* Determine best y-intercept */
for (k = 0; k < n; k++) e[k] -= a; /* Final y-residuals */
E = misfit (GMT, e, W, n, regression, b, par[GMTREGRESS_N_EFF]); /* The representative misfit */
}
if (gmt_M_is_dnan (E)) E = DBL_MAX; /* If anything goes crazy, set E to huge, but this should not happen */
/* Update the new best solution; we do not change entries for U and W as well as the sigmas for slope and intercept */
par[GMTREGRESS_ANGLE] = angle; par[GMTREGRESS_MISFT] = E; par[GMTREGRESS_SLOPE] = b; par[GMTREGRESS_ICEPT] = a;
}
#define N_ANGLE_SELECTIONS 90 /* Fixed number of slope angles to try between min/max slope limits */
GMT_LOCAL double gmtregress_regress1D (struct GMT_CTRL *GMT, double *x, double *y, double *w[], uint64_t n, unsigned int regression, unsigned int norm, double *range, double *par) {
/* Solve the linear regression problem for chosen misfit and norm by an iterative approach */
uint64_t k;
unsigned int n_iter = 0;
bool done = false, weighted = false;
char buffer[GMT_LEN256] = {""};
double a_min = range[0], a_max = range[1], angle, r_a, d_a, f, last_E = DBL_MAX, scale, tpar[GMTREGRESS_NPAR];
double *U = gmt_M_memory (GMT, NULL, n, double), *V = gmt_M_memory (GMT, NULL, n, double);
double *W = gmt_M_memory (GMT, NULL, n, double), *e = gmt_M_memory (GMT, NULL, n, double);
double (*scl_func) (struct GMT_CTRL *GMT, double *ey, double *W, uint64_t n, double *par);
switch (norm) { /* Set regression residual scale function pointer */
case GMTREGRESS_NORM_L1: scl_func = gmtregress_L1_scale; break;
case GMTREGRESS_NORM_L2: scl_func = gmtregress_L2_scale; break;
case GMTREGRESS_NORM_LMS: scl_func = gmtregress_LMS_scale; break;
default:
GMT_Report (GMT->parent, GMT_MSG_WARNING, "Misfit norm not specified? - set to L2\n");
scl_func = gmtregress_L2_scale;
break;
}
gmt_M_memset (par, GMTREGRESS_NPAR, double); /* Reset all regression parameters */
gmt_M_memset (tpar, GMTREGRESS_NPAR, double); /* Reset all test regression parameters */
if (regression != GMTREGRESS_XY) (void)gmtregress_demeaning (GMT, x, y, w, n, tpar, U, V, W, NULL, NULL); /* Do this once except for orthogonal */
par[GMTREGRESS_MISFT] = DBL_MAX; /* Initially we have no fit */
weighted = (regression == GMTREGRESS_X) ? (w && w[GMT_X]) : (w && w[GMT_Y]); /* true if weights were provided */
while (!done) { /* Keep iterating and zooming in on smaller angle-ranges until misfit is very small */
r_a = a_max - a_min; /* Range of angles */
d_a = r_a / (double)N_ANGLE_SELECTIONS; /* Angle increment */
for (k = 0; k <= N_ANGLE_SELECTIONS; k++) { /* Try all slopes in current angle range */
angle = a_min + d_a * k; /* This is the current slope angle */
if (regression == GMTREGRESS_XY) { /* Since W depends on slope we must recompute W each time in this loop */
tpar[GMTREGRESS_SLOPE] = tand (angle);
(void)gmtregress_demeaning (GMT, x, y, w, n, tpar, U, V, W, NULL, NULL);
}
gmtregress_gmtregress_regress1D_sub (GMT, U, V, W, e, n, regression, norm, weighted, angle, tpar); /* Solve for best intercept given this slope */
if (tpar[GMTREGRESS_MISFT] < par[GMTREGRESS_MISFT])
gmt_M_memcpy (par, tpar, GMTREGRESS_NPAR, double); /* Update best fit so far without stepping on the means and sigmas */
}
if (d_a < 0.05 && par[GMTREGRESS_MISFT] <= last_E && (f = (last_E - par[GMTREGRESS_MISFT])/par[GMTREGRESS_MISFT]) < GMT_CONV15_LIMIT)
done = true; /* Change is tiny so we are done, or d_a is too big to make a decision for yet */
else { /* Gradually zoom in on the angles with smallest misfit but allow some slack */
a_min = MAX (range[0], par[GMTREGRESS_ANGLE] - 0.25 * r_a); /* Get a range that is ~-/+ 25% of previous range */
a_max = MIN (range[1], par[GMTREGRESS_ANGLE] + 0.25 * r_a); /* Get a range that is ~-/+ 25% of previous range */
last_E = par[GMTREGRESS_MISFT];
}
/* Adjust intercept from U,V -> (x,y) */
n_iter++;
if (gmt_M_is_verbose (GMT, GMT_MSG_WARNING)) {
double a = par[GMTREGRESS_ICEPT] + (par[GMTREGRESS_YMEAN] - par[GMTREGRESS_SLOPE] * par[GMTREGRESS_XMEAN]);
snprintf (buffer, GMT_LEN256, "Robust iteration %u: N: %" PRIu64 " x0: %g y0: %g angle: %g E: %g slope: %g icept: %g sig_slope: --N/A-- sig_icept: --N/A--",
n_iter, n, par[GMTREGRESS_XMEAN], par[GMTREGRESS_YMEAN], par[GMTREGRESS_ANGLE], par[GMTREGRESS_MISFT], par[GMTREGRESS_SLOPE], a);
GMT_Report (GMT->parent, GMT_MSG_INFORMATION, "%s\n", buffer);
}
}
par[GMTREGRESS_ICEPT] += (par[GMTREGRESS_YMEAN] - par[GMTREGRESS_SLOPE] * par[GMTREGRESS_XMEAN]);
GMT_Report (GMT->parent, GMT_MSG_INFORMATION, "Robust regression algorithm convergence required %d iterations\n", n_iter);
scale = scl_func (GMT, e, W, n, par); /* Get final regression-scale for residuals */
gmt_M_free (GMT, U);
gmt_M_free (GMT, V);
gmt_M_free (GMT, W);
gmt_M_free (GMT, e);
return (scale);
}
#define GMTREGRESS_MAX_YORK_ITERATIONS 1000 /* Gotta have a stopper in case of bad data? */
GMT_LOCAL double gmtregress_LSxy_regress1D_york (struct GMT_CTRL *GMT, double *X, double *Y, double *w[], uint64_t n, double *par) {
/* Solution to general LS orthogonal regression with weights, per York et al. [2004] */
uint64_t i;
unsigned int n_iter = 0;
double *W = NULL, *U = NULL, *V = NULL, *x = NULL, *u = NULL, *alpha = NULL, *beta = NULL;
double b, b_old, a, W_sum, x_mean, sigma_a, sigma_b, misfit, scale;
char buffer[GMT_LEN256] = {""};
/* Allocate temporary vectors */
W = gmt_M_memory (GMT, NULL, n, double);
U = gmt_M_memory (GMT, NULL, n, double);
V = gmt_M_memory (GMT, NULL, n, double);
x = gmt_M_memory (GMT, NULL, n, double);
u = gmt_M_memory (GMT, NULL, n, double);
alpha = gmt_M_memory (GMT, NULL, n, double);
beta = gmt_M_memory (GMT, NULL, n, double);
/* Step 1: Get initial slope from basic LS y on x with no weights (and ignore scale on return) */
(void)gmtregress_LSy_regress1D (GMT, X, Y, NULL, n, par);
b = par[GMTREGRESS_SLOPE]; /* This is our initial slope value */
gmt_M_memset (par, GMTREGRESS_NPAR, double); /* Reset all regression parameters */
/* Step 2: Weights w(X_i) and w(Y_i) are already set in the main program */
do { /* Keep iterating until converged [Step 6 in York et al, 2004 recipe] */
b_old = b; /* Previous best slope */
/* Step 3+4: Compute single weights Wi from w(X_i), w(Y_i), r_i and weighted X_mean, Y_mean, then U, V, alpha, and beta */
par[GMTREGRESS_SLOPE] = b_old; /* Pass in previous best-fitting slope needed to update W */