-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpdsi.cpp
4868 lines (4517 loc) · 150 KB
/
pdsi.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
#include "pdsi.h"
//#include <stdlib.h>
#include <math.h>
#include <cstring>
//#include <stdio.h>
#include <ctype.h>
// # nocov start
//=============================================================================
//pdsi.cpp University of Nebraska - Lincoln Jul 15 2003
//=============================================================================
//
// Current Version: 2.0
//
//Calculates the Palmer Drought Severity Index for a given station.
//
//Recent modifications:
// - Implemented user-defined calibration interval (Jun 5 2006)--goddard
// - A more intuitive format for the parameter file is accepted:
// AWC Latitude
// The '-n' flag was added to facilitate the old format:
// AWC TLA
// (Jul 15 2003)
// - Calculates the Weekly CMI (Jul 1 2003)
// - Works in with southern latitude (Apr 1 2003)
// - Works with the metric flag (Mar 12 2003)
//
//Self-calibrating, multiple time scale version. Based upon weekly_pdsi.cpp
//which is a self-calibrating, weekly PDSI program developed by Nathan Wells.
//This version is capable of calculating a self-calibrating weekly PDSI,
//a self-calibrating monthly PDSI, and the original monthly PDSI.
//
//Most recently translated to C++ from FORTRAN by Rob Reed and Nate Wells,
//University of Nebraska - Lincoln, advised by Dr. Steve Goddard - July 2001.
//
//Methodology based on Research Paper No. 45; Meteorological Drought; by
//Wayne C. Palmer for the U.S. Weather Bureau, February 1965.
//
//Based mostly on the source code of pdsi.f, a FORTRAN program that calculates
//monthly PDSI values. The source code came from NCDC, originally written by
//Tom Karl, and revised by Roger Winchell, Alan McNab, and Richard Heim.
//
//Slight modifications in the algorithm were made based on the source of
//palmcode.f, a FORTRAN program that calculates weekly PDSI values, received
//from Tom Heddinghaus at NCEP, who is also the original author of that
//particular code.
//
//Additional modifications were made to adapt the algorithm to a weekly time
//scale based on recalculations of several constants as described in Palmer's
//paper.
//
//Additional modifications were made to attempt to make this program
//completely independent of emperically derived formulas. This will allow the
//program to perform accurately in any enviroment. Most changes came in the
//addition of the Calibrate() function. These changes were made in order to
//make comparisions between stations more accurate. --August 2001
//
//The incorporation of a self-calibrating monthly and the oringal monthly PDSI
// -- May 2002
//
//Changed the calibration method to calibrate the climatic characteristic based
//on the quartiles instead of the max and min. -- Jun 2002.
//-----------------------------------------------------------------------------
//
// 4 input files for weekly PDSI calculations:
//
//weekly_T and weekly_P:
// Weekly temperature and precipitation files; each line starts with the year
// and is followed by 52 data entries. It is important to note that only 52
// weeks are on each line, even though 52 weeks is only 364 days. This data
// must be gathered in such a way that the kth week of the year always
// represents the same calendar interval. For example, the first week should
// always represent Jan 1 through Jan 7.
//
//wk_T_normal:
// The average weekly temperature for each week of the year. One line, 52
// data entries.
//
//parameter:
// contains two numbers specific to each station: the underlying soil water
// capacity - Su (in inches), and the negative of the tangent of the latitude
// of the station - TLA.
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//
// 4 input files for monthly PDSI calculations:
//
//monthly_T and monthly_P:
// Monthly temperature and precipitation files; each line starts with the year
// and is followed by 12 data entries.
//
//mon_T_normal:
// The average monthly temperature for each week of the year. One line, 12
// data entries.
//
//parameter:
// same as above.
//
//-----------------------------------------------------------------------------
//Extra notes on input files:
// The format of these files matches the format of the original FORTRAN
// program. There is no precise need for this format to be used.
//
// The program is able to calculate the weekly PDSI, the original monthly PDSI
// and the monthly self-calibrating PDSI if all the data is in the same
// directory.
//
// It is possible to use the filename T_normal in place of either mon_T_normal
// or wk_T_normal. For example, the program will try to open mon_T_normal
// first, and then T_normal. If T_normal is opened, it will check to make
// sure it is the right format by counting the number of entries in the file.
// This was done to allow the program to work on the exact same input data as
// the original FORTRAN program, allowing comparisons.
//-----------------------------------------------------------------------------
//
//------ Output Files:
//
//There are two formats of output, table and column, which are selected by
//command line options. The table output files end with .tbl and the column
//output files end with .clm. The table files list a whole year's worth of
//resultsing values on each line while the column files list the year and week
//followed by the resulting value on each line.
//
//PDSI.tbl and/or PDSI.clm:
// The Palmer Drought Severity Index values
//
//PHDI.tbl and/or PHDI.clm:
// The Palmer Hydrological Drought Index values.
//
//WPLM.tbl and/or WPLM.clm:
// The "Weighted" Palmer Index. An average of either X1 and X3, or X1 and X2
// weighted by the probability of the current spell ending. For more
// information, see how the WPLM is calculated in the pdsi::write() function.
//
//ZIND.tbl and/or ZIND.clm:
// The Z Index, or the moisture anomaly
//
//------ Other possible output files, depending on certain flags:
//
//WB.tbl
// The water ballance coefficients (Alpha, Beta, Gamma, & Delta) for each
// week/month.
//
//bigTable.tbl
// Z, % Prob(end), X1, X2, and X3 for every week/month.
//
//potentials
// P, PE, PR, PRO, PL, and P - PE for every week/month.
//
//dvalue
// The moisture departure, d, for every week/month.
//
//=============================================================================
// end of introductory comments
//=============================================================================
//
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
//********** MAIN PROGRAM *********
//-----------------------------------------------------------------------------
// The main program takes in command line arguments and passes them to the
// constructor of a pdsi variable tester. It then calls Calcpdsi to calculate
// the pdsi values. Finally it calls write to output these values to file.
//-----------------------------------------------------------------------------
/*
int main(int argc,char *argv[]) {
pdsi PDSI;
PDSI.set_flags(argc,argv); // Sets the flags of PDSI
PDSI.WeeklyPDSI(); // Calculates the weekly pdsi values for PDSI
PDSI.Write((char *)"weekly/1");
PDSI.WeeklyPDSI(2);
PDSI.Write((char *)"weekly/2");
PDSI.WeeklyPDSI(4);
PDSI.Write((char *)"weekly/4");
PDSI.WeeklyPDSI(13);
PDSI.Write((char *)"weekly/13");
PDSI.MonthlyPDSI();
PDSI.Write((char *)"monthly/original");
PDSI.SCMonthlyPDSI();
PDSI.Write((char *)"monthly/self_cal");
PDSI.WeeklyCMI();
PDSI.Write((char *)"weekly/CMI");
return 0;
}
*/
//-----------------------------------------------------------------------------
//********** PROGRAMS END *********
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//********** START OF FUNCTION DEFINITIONS FOR CLASS: llist *********
//-----------------------------------------------------------------------------
// The pdsi constructor sets all flags to default, scans the temperature file
// to get the starting and ending years of the data, and reads in the values
// from the parameter file.
//-----------------------------------------------------------------------------
pdsi::pdsi() {
strcpy(input_dir,"./");
strcpy(output_dir,"./");
//set several parameters to their defaults
period_length = 1;
num_of_periods = 52;
verbose=1;
bug=0;
output_mode=0;
tolerance=0.00001;
metric=0;
nadss=0;
setCalibrationStartYear=0;
setCalibrationEndYear=0;
}
//-----------------------------------------------------------------------------
// The destructor deletes the temporary files used in storing various items
//-----------------------------------------------------------------------------
pdsi::~pdsi() {
if(extra != 3 && extra != 9){
remove("potentials"); // Used for storing potential values for later use
remove("dvalue"); // Used to store the d values for use after summing them
}
remove("bigTable.tbl");
/*
if(verbose > 0)
printf("Calculations Complete\n");
*/
}
//-----------------------------------------------------------------------------
// The check_input function will check to make sure there is enough data in
// file represented by the file pointer in. The basic requirement is that
// there should be 25 years of data, which means 300 months or 1300 weeks that
// are not MISSING.
// returns -1 if the file doesn't exist (in == NULL)
// returns 0 if the file doesn't have enough data
// reutrns 1 if the file is okay
//-----------------------------------------------------------------------------
int pdsi::check_input(FILE *in){
float temp;
int count = 0;
int min_years = 25;
if(in == NULL)
return -1;
while(fscanf(in, "%f",&temp) != EOF){
//if temp is either MISSING, or a year, don't count it.
if(temp != MISSING && temp <= 999)
count++;
}
if(Weekly){
if(count < (min_years * 52) )
return 0;
else
return 1;
}
else{
if(count < (min_years * 12) )
return 0;
else
return 1;
}
}
//-----------------------------------------------------------------------------
// The initialize function clears all arrays and linked lists.
// it also checks to make sure all the necessary input files exist.
// returns 1 if they do, and -1 if they do not.
// returns 0 if there is too much missing data.
// -- there should be 25 years worth of data. (300 months or 1300 weeks)
//-----------------------------------------------------------------------------
int pdsi::initialize() {
/*
char filename[170], base[170];
FILE* test;
while(!Xlist.is_empty())
Xlist.tail_remove();
while(!altX1.is_empty())
altX1.tail_remove();
while(!altX2.is_empty())
altX2.tail_remove();
while(!XL1.is_empty())
XL1.tail_remove();
while(!XL2.is_empty())
XL2.tail_remove();
while(!XL3.is_empty())
XL3.tail_remove();
while(!ProbL.is_empty())
ProbL.tail_remove();
while(!ZIND.is_empty())
ZIND.tail_remove();
while(!PeriodList.is_empty())
PeriodList.tail_remove();
while(!YearList.is_empty())
YearList.tail_remove();
while(!CMIList.is_empty())
CMIList.tail_remove();
//check to make sure the necessary input files exist
if(strlen(input_dir) > 1)
strcpy(base, input_dir);
else
strcpy(base,"./");
if(Weekly){
strcpy(filename, base);
strcat(filename, "wk_T_normal");
if((test = fopen(filename,"r"))==NULL){
sprintf(filename,"%s%s",base,"T_normal");
if((test = fopen(filename,"r"))==NULL)
return -1;
else if(numEntries(test) != 52){
fclose(test);
if(verbose){
printf("Error: T_normal not in correct format ");
printf("for Weekly calculations\n");
}
return -1;
}
}
fclose(test);
strcpy(filename,base);
strcat(filename,"parameter");
if((test = fopen(filename,"r"))==NULL)
return -1;
fclose(test);
strcpy(filename,base);
strcat(filename,"weekly_P");
if((test = fopen(filename,"r"))==NULL)
return -1;
else {
switch(check_input(test)){
case -1:
fclose(test);
return -1;
break;
case 0:
if(verbose > 0)
printf("Error: too much missing data.\n");
if(verbose > 1)
printf(" 1300 weeks (25 yrs) of good data.\n");
fclose(test);
return 0;
break;
}
fclose(test);
}
strcpy(filename,base);
strcat(filename,"weekly_T");
if((test = fopen(filename,"r"))==NULL)
return -1;
else {
switch(check_input(test)){
case -1:
fclose(test);
return -1;
break;
case 0:
if(verbose > 0)
printf("Error: too much missing data.\n");
if(verbose > 1)
printf(" 1300 weeks (25 yrs) of good data.\n");
fclose(test);
return 0;
break;
}
fclose(test);
}
}
else if(Monthly || SCMonthly){
strcpy(filename,base);
strcat(filename,"mon_T_normal");
if((test = fopen(filename,"r"))==NULL){
sprintf(filename,"%s%s",base,"T_normal");
if((test = fopen(filename,"r"))==NULL)
return -1;
else if(numEntries(test) != 12){
if(verbose){
printf("Error: T_normal not in correct format ");
printf("for Monthly calculations\n");
}
fclose(test);
return -1;
}
}
fclose(test);
strcpy(filename,base);
strcat(filename,"parameter");
if((test = fopen(filename,"r"))==NULL)
return -1;
fclose(test);
strcpy(filename,base);
strcat(filename,"monthly_P");
if((test = fopen(filename,"r"))==NULL)
return -1;
else {
switch(check_input(test)){
case -1:
fclose(test);
return -1;
break;
case 0:
if(verbose > 0)
printf("Error: too much missing precip data.\n");
if(verbose > 1)
printf(" 300 months (25 yrs) of good data.\n");
fclose(test);
return 0;
break;
}
fclose(test);
}
strcpy(filename,base);
strcat(filename,"monthly_T");
if((test = fopen(filename,"r"))==NULL)
return -1;
else {
switch(check_input(test)){
case -1:
fclose(test);
return -1;
break;
case 0:
if(verbose > 0)
printf("Error: too much missing temp data.\n");
if(verbose > 1)
printf(" 300 months (25 yrs) of good data.\n");
fclose(test);
return 0;
break;
}
fclose(test);
}
}
else{
if(verbose){
printf("Error. Invalid type of PDSI calculation\n");
printf("Either the 'Weekly', 'Monthly', or 'SCMonthly' ");
printf("flags must be set.\n");
}
exit(1);
}
return 1;
*/
return 0;
}
//-----------------------------------------------------------------------------
// The set_flags function takes an argument list (flags) and a number of
// arguments (num_flags). It then sets the various pdsi flags accordingly
//-----------------------------------------------------------------------------
void pdsi::set_flags(int num_flags,char *flags[]) {
/*
int read_from =1;
unsigned int n;
// These flags are used for two argument flags
flag week=0, year=0, both=0, out=0, e_flag=0, t_year=0;
flag in_dir = -1, out_dir = -1;
// Initializes the output years flags to 0
s_year=0;
e_year=0;
// This loop checks all strings in flags to make sure they are valid flags
for(int i=read_from; i<num_flags; i++) {
// This checks for the various single letter flags that are started with
// the '-' character. Note: multiply flags can be specified after the -
if(strncmp(flags[i],"-",1)==0) {
for(unsigned int j=1; j<strlen(flags[i]); j++) {
switch (flags[i][j]) {
case 'm':
// A m flags means all input in metric units
metric=1;
break;
case 'v':
// A v flag sets the verbosity to maximum
verbose=2;
break;
case 's':
// A s flag sets the verbosity to minimum
verbose=0;
break;
case 'e':
// An e flag shows that totalyears should be counted from the
// e_year flag or that a given year is meant to be the e_year
e_flag=1;
break;
case 'b':
// A b flag causes the program to reproduce an error in the
// FORTRAN code for easy comparison
bug=1;
break;
case 'c':
j++;
if (flags[i][j] == 's') {
setCalibrationStartYear = 1;
i++;
if (is_int(flags[i], strlen(flags[i]))) {
calibrationStartYear = atoi(flags[i]);
} else {
printf("INVALID CALIBRATION START YEAR: %s, must be of the form: yyyy (Ex: 1956)\n",flags[i]);
printf("pdsi --help for usage.\n");
exit(1);
}
calibrationStartYear = atoi(flags[i]);
} else if (flags[i][j] == 'e') {
setCalibrationEndYear = 1;
i++;
if (is_int(flags[i], strlen(flags[i]))) {
calibrationEndYear = atoi(flags[i]);
} else {
printf("INVALID CALIBRATION END YEAR: %s, must be of the form: yyyy (Ex: 2005)\n",flags[i]);
printf("pdsi --help for usage.\n");
exit(1);
}
} else {
printf("INVALID FLAG: %s\n",flags[i]);
printf("pdsi --help for usage.\n");
exit(1);
}
j = strlen(flags[i]);
break;
case 'f':
// An o flag is used to set the output format of the pdsi
out=1;
break;
case 'x':
// An x flag is used to output extra data, such as the water
// balance coefficients or PE
extra = 0;
break;
case 'i':
// A i flag is used to signify the directory location of
// the input data
// the flag must be in the form of: -iInputDir/sub/
// so the rest of the string flags[i] is the
// directory
for(n = j+1; n < strlen(flags[i]); n++)
input_dir[n-(j+1)]=flags[i][n];
input_dir[n-2] = '\0';
j = n;
break;
case 'o':
// A o flag is used to signify the directory location where
// the output files should be placed.
// the flag must be in the form of: -oOnputDir/sub/
// so the rest of the string flags[i] is the
// directory
for(n = j+1; n < strlen(flags[i]); n++)
output_dir[n-(j+1)]=flags[i][n];
output_dir[n-2] = '\0';
j = n;
break;
case 'n':
// this is the nadss flag. Any options that are
// unique to our implemenation should be controled
// but it. Currently, this only affects the way
// the parameter file is read.
nadss = 1;
break;
case '-':
// A string starting with '--' is a special flag such as
// the help flag.
if(strcmp(flags[i],"--help")==0) {
printf("pdsi <flags> <Total Years>\n");
printf(" -b Causes pdsi to reproduce the bug found in ");
printf("the FORTRAN program\n");
printf(" -v Verbose mode outputs all text to the screen that ");
printf("the FORTRAN program did\n");
printf(" -e Specifies the given year is an end year and not");
printf(" a beginning year\n");
printf(" -cs <yyyy> Specifies the calibration start year\n");
printf(" -ce <yyyy> Specifies the calibration end year\n");
printf(" -s Silent mode turns off all error outputs\n");
printf(" -f [table|column|both] Sets the output mode used.\n");
printf(" table - Create only files in a table format\n");
printf(" column - Create only files in a column format\n");
printf(" both - Create both table and column files\n");
printf(" -x [wb|Xtable|potentials|all] generates extra output ");
printf("files.\n");
printf(" wb - Outputs water balance coefficients to ");
printf("\"WB.tbl\" and to the screen.\n");
printf(" Xtable - Outputs Year, Month/Week, Z, Prob(end), X1, ");
printf("X2, and X3 to\n \"bigTable.tbl\".\n");
printf(" potentials - Outputs P, PE, PR, PRO, PL and P-PE");
printf(" to \"potentials\".\n");
printf(" all - Outputs to \"WB.tbl\", \"bigTable.tbl\" ");
printf("and \"potentials\".\n");
printf("\n");
exit(1);
} else {
printf("INVALID FLAG: %s.\n",flags[i]);
printf("pdsi --help for usage.\n");
exit(1);
}
break;
default:
// If it is none of the above then the flag is invalid.
printf("INVALID FLAG: %s.\n",flags[i]);
printf("pdsi --help for usage.\n");
exit(1);
break;
}// End switch (argv[i][j])
}// End for(int j=1; j<strlen(argv[i]); j++)
}// End if(strncmp(argv[i],"-",1)==0)
else if(is_int(flags[i],strlen(flags[i]))) {
// If the argument is an integer it is either a starting/ending year
// specifier or a total year specifier for the output function. It is
// also possible for the argument to be the tolerance specifier of 0.
int temp;
temp=atoi(flags[i]);
if(temp > 9999) {
// If the number is more than 4 digits it is invalid
printf("INVALID YEAR SPECIFIER: %d",temp);
printf("pdsi --help for usage.\n");
exit(1);
}// End if(temp>9999 || temp<0)
else if(temp > 999) {
// Otherwise if it is 4 digits then it must be a year specifier
if(s_year==0) {
// If this is the first year specifier store it in s_year
s_year=temp;
}// End if(s_year==0)
else if(s_year>0 && e_year==0) {
// If this is the second year specifier decide which should be start
// year and which should be end year.
if(temp<s_year) {
e_year=s_year;
s_year=temp;
}// End if(temp<s_year)
else
e_year=temp;
}// End else if(s_year>0&&e_year==0)
else {
// If two year specifiers have already been given then there must be
// an invalid flag.
printf("Confused by $d. Start year and end year already specified.\n",temp);
printf("pdsi --help for usage.\n");
exit(1);
}// End else
}// End else if(temp > 999)
else if(temp > 0) {
// If temp is not a year and it is not zero then it must be a total
// specifier.
t_year=temp;
}// End else if(temp>0)
else if(temp==0)
// Otherwise it is a tolerance specifier of 0
tolerance=0;
}// End else if(is_int(argv[i],strlen(argv[i])))
else if(is_flt(flags[i],strlen(flags[i]))) {
// If the flag is a floating point number then it is probably meant as a
// tolerance specifier.
float tol;
tol=float(atof(flags[i]));
// A tolerance of much more than 0.005 will have drastic results on the
// PDSI and is not a very likely want
if(tol<1)
tolerance=tol;
else {
printf("Unsure of %f. Tolerance specifier should be < 1.\n",tol);
printf("pdsi --help for usage.\n");
exit(1);
}
}//end of else if(is_flt...)
// If the flag is year then it is an output mode specifier
else if(strcmp(flags[i],"table")==0) {
// This checks that there have been no other output mode specifiers
if(!week && !both && out == 1)
year=1; // Okay to set the output mode to year
else if(out == 0){
printf("Confused by \"table\". No -f flag detected.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
else{
printf("Confused by \"table\". Output mode already specified.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
}
// If the flag is week then it is an output mode specifier
else if(strcmp(flags[i],"column")==0) {
// This checks that there have been no other output mode specifiers
if(!year && !both && out == 1)
week=1; // Okay to set the ouput mode to week
else if(out == 0){
printf("Confused by \"column\". No -f flag detected.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
else {
printf("Confused by \"column\". Output mode already specified.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
}
// If the flag is year then it is an output mode specifier
else if(strcmp(flags[i],"both")==0) {
// This checks that there have been no other output mode specifiers
if(!year && !week && out == 1)
both=1; // Okay to set the ouput mode to both
else if(out == 0){
printf("Confused by \"both\". No -f flag detected.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
else {
printf("Confused by \"both\". Output mode already specified.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
}
//check for extra output.... wb, Xtable, potentials, or all
else if(strcmp(flags[i], "wb")==0){
if(extra == 0)
extra = 1; //this will output the water balance coefficients to a file.
else if(extra < 0){
printf("Confused by \"wb\". No -x flag detected.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
else{
printf("Confused by \"wb\". Extra output already set.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
}
else if(strcmp(flags[i], "Xtable")==0){
if(extra == 0){
//this will output Z, Prob, X1, X2, X3 and PDSI in a table.
extra = 2;
}
else if(extra < 0){
printf("Confused by \"Xtable\". No -x flag detected.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
else{
printf("Confused by \"Xtable\". Extra output already set.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
}
else if(strcmp(flags[i], "potentials")==0){
if(extra == 0)
extra = 3; //don't delete the potentials file in destructor
else if(extra < 0){
printf("Confused by \"potentials\". No -x flag detected.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
else{
printf("Confused by \"potentials\". Extra output already set.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
}
else if(strcmp(flags[i], "all")==0){
if(extra == 0){
extra = 9; //don't delete the potentials file, and write
//to both bigTable.tbl and WB.tbl
}
else if(extra < 0){
printf("Confused by \"all\". No -x flag detected.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
else{
printf("Confused by \"all\". Extra output already set.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
}
}// End for(int i=1; i<argc; i++) -->done checking all flags
// check input_dir and output_dir for correct format
//make sure last character is a slash '/'
//and make sure the input directory exists
if(strlen(input_dir)>1){
if(input_dir[strlen(input_dir)-1] != '/')
strcat(input_dir, "/");
if(dir_exists(input_dir) == -1){
if(verbose)
printf("Input directory does not exist: %s\n\n",input_dir);
exit(1);
}
}
else
strcpy(input_dir,"./");
if(strlen(output_dir)>1){
if(output_dir[strlen(output_dir)-1] != '/')
strcat(output_dir,"/");
}
else
strcpy(output_dir,"./");
if(verbose > 1){
printf("Input Directory is: %s\n",input_dir);
printf("Output Directory is: %s\n\n",output_dir);
}
// This block opens weekly_T to scan for the start and end year of the data
// If weekly_T is not present, tries to open monthly_T
float t;
FILE * scn;
char filename[170];
if(strlen(input_dir)>1){
strcpy(filename,input_dir);
strcat(filename,"weekly_T");
}
else
strcpy(filename,"weekly_T");
if((scn=fopen(filename,"r"))==NULL) {
if(verbose > 1)
printf("Error opening %s... trying for %smonthly_T\n",filename,input_dir);
if(strlen(input_dir)>1){
strcpy(filename,input_dir);
strcat(filename,"monthly_T");
}
else
strcpy(filename,"monthly_T");
strcpy(filename,input_dir);
strcat(filename,"monthly_T");
if((scn=fopen(filename,"r"))==NULL) {
printf("error opening file to get startyear\n");
printf("tried both %sweekly_T and %s\n",input_dir,filename);
exit(1);
}
else{
//scan monthly_T for start and end year
fscanf(scn,"%d",&startyear);
while((fscanf(scn,"%f",&t))!=EOF){
if(t>999)
endyear=(int)t;
}
}
}
else {
//scan weekly_T for start and end year
fscanf(scn,"%d",&startyear);
while((fscanf(scn,"%f",&t))!=EOF){
if(t>999)
endyear=(int)t;
}
}
fclose(scn);
totalyears=endyear-startyear+1;
if(t_year>totalyears) {
printf("Span given is greater than span of input data.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
//check to see if s_year is a valid year according to data
if(s_year != 0 && (s_year<startyear || s_year>endyear)) {
printf("The data files only contain data from %d to %d\n",startyear,endyear);
printf("%d falls outside that range.\n",s_year);
exit(1);
}
//check to see if e_year is a valid year according to data
if(e_year != 0 && (e_year<startyear || e_year>endyear)) {
printf("The data files only contain data from %d to %d\n",startyear,endyear);
printf("%d falls outside that range.\n",e_year);
exit(1);
}
// This checks to see if calculations should be done from end year
if(e_flag) {
// If they are, then set e_year to the specified year
if(s_year==0) e_year=endyear;
else if(e_year==0) e_year=s_year;
// Set s_year to the start year
s_year=startyear;
// If t_year has been specified and keeps the output within the range of
// the input then reset s_year accordingly
if(t_year>0 && (e_year-t_year+1)>startyear){
s_year=e_year-t_year+1;
}
}
else {
// Otherwise calculations are done from s_year.
if(s_year==0) s_year=startyear;
if(e_year==0) e_year=endyear;
if(t_year>0 && (s_year+t_year-1)<endyear){
e_year=s_year+t_year-1;
}
}
if (setCalibrationStartYear == 1) {
if (calibrationStartYear < startyear || calibrationStartYear > endyear) {
printf("Warning: invalid calibration start year: %d.\n", calibrationStartYear);
calibrationStartYear = startyear;
}
} else {
calibrationStartYear = startyear;
}
currentCalibrationStartYear = calibrationStartYear;
if (setCalibrationEndYear == 1) {
if (calibrationEndYear < calibrationStartYear || calibrationEndYear > endyear) {
printf("Warning: invalid calibration end year: %d.\n", calibrationEndYear);
calibrationEndYear = endyear;
}
} else {
calibrationEndYear = endyear;
}
currentCalibrationEndYear = calibrationEndYear;
nStartYearsToSkip = currentCalibrationStartYear - startyear;
nEndYearsToSkip = endyear - currentCalibrationEndYear;
nCalibrationYears = currentCalibrationEndYear - currentCalibrationStartYear + 1;
nStartPeriodsToSkip = nStartYearsToSkip * num_of_periods;
nEndPeriodsToSkip = nEndYearsToSkip * num_of_periods;
nCalibrationPeriods = nCalibrationYears * num_of_periods;
// If out then set the output_mode flag according to the output specifier
if(year && out)
output_mode=0;
else if(week && out)
output_mode=1;
else if(both && out)
output_mode=2;
else if(out) {
printf("Missing output specifier with -o flag.\n");
printf("pdsi --help for usage.\n");
exit(1);
}
*/
}// End set_flags
//-----------------------------------------------------------------------------
//WeeklyCMI calls the functions necessary to compute the Crop Moisture Index
//(CMI). The CMI is based on subcalculation of the PDSI. It is only done
//on a 1-week time scale.
//-----------------------------------------------------------------------------
void pdsi::WeeklyCMI() {
/*
FILE * param;
char filename[170];
int i;
period_length = 1;
num_of_periods = 52;
// SG 6/5/06: The WeeklyCMI does not (yet) support a calibration interval, so clear the vars
currentCalibrationStartYear = startyear;
currentCalibrationEndYear = endyear;
nEndYearsToSkip = 0;
nStartYearsToSkip = 0;
nCalibrationYears = totalyears;
nStartPeriodsToSkip = 0;
nEndPeriodsToSkip = 0;
nCalibrationPeriods = nCalibrationYears * num_of_periods;
// SG 6/5/06: end addition
Weekly = true;
Monthly = false; SCMonthly = false;
extra = 1;
if(initialize()<1){
if(verbose > 0)
printf("%4s Cannot calculate the weekly CMI.\n", "*");
if(verbose > 1){
printf("The necessary input files ");
printf("were not found in the directory %s\n",input_dir);
printf("The following files are required:\n");
printf("weekly_T \nweekly_P\nparameter\nwk_T_normal\n\n");
}
return;
}
// This block opens the parameter file and sets the initial Su and TLA values
// must be called after the variable period_length is determined in the
// set_flags function