blib/lib/Weather/GHCN/StationTable.pm untested

filter: Statementstmt 0.0% 0 / 874 Branchbran 0.0% 0 / 344 Conditioncond 0.0% 0 / 215 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 20 Podpod n/a totaltotal 0.0% 0 / 1453 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 # Weather::GHCN::StationTable.pm - class for collecting station objects and weather data
2
3 ## no critic (Documentation::RequirePodAtEnd)
4
5 =head1 NAME
6
7 Weather::GHCN::StationTable - collect station objects and weather data
8  
9 =head1 VERSION
10  
11 version v0.0.003
12
13 =head1 SYNOPSIS
14
15 use Weather::GHCN::StationTable;
16
17 my $ghcn = Weather::GHCN::StationTable->new;
18
19 my ($opt, @errors) = $ghcn->set_options(
20 user_options => {
21 country => 'US',
22 state => 'NY',
23 location => 'New York',
24 report => 'yearly',
25 },
26 );
27 die @errors if @errors;
28
29 $ghcn->load_stations;
30
31 # generate a list of the stations that were selected
32 say $ghcn->get_stations( kept => 1 );
33
34 if ($opt->report) {
35 say $ghcn->get_header;
36
37 $ghcn->load_data();
38 $ghcn->summarize_data;
39
40 say $ghcn->get_summary_data;
41 say $ghcn->get_footer;
42 }
43
44
45 =head1 DESCRIPTION
46
47 The B<Weather::GHCN::StationTable> module provides a class that is used to
48 fetch stations information from the NOAA Global Historical Climatology
49 Network database, along with temperature and/or precipitation records
50 from the daily historical records.
51
52 For a more comprehensive example than the above Synopsis, see the
53 section EXAMPLE PROGRAM.
54
55 Caveat emptor: incompatible interface changes may occur on releases
56 prior to v1.00.000. (See VERSIONING and COMPATIBILITY.)
57
58 The module is primarily for use by modules Weather::GHCN::Fetch.
59
60 =cut
61
62 use v5.18; # minimum for Object::Pad
63 use Object::Pad 0.66 qw( :experimental(init_expr) );
64
65 package Weather::GHCN::StationTable;
66 class Weather::GHCN::StationTable;
67
68 our $VERSION = 'v0.0.003';
69
70 ## no critic [References::ProhibitDoubleSigils]
71
72 # directly used by this module
73 use Carp qw( carp croak );
74 use Const::Fast;
75 use Weather::GHCN::Common qw( :all );
76 use Weather::GHCN::TimingStats;
77 use HTML::Entities;
78 #use Hash::Wrap {-lvalue => 1, -defined => 1, -as => '_wrap_hash' };
79
80 # included so consumers of this module don't have to include these
81 use Cache::FileCache;
82 use Devel::Size;
83 use File::HomeDir;
84 use File::Spec;
85 use FindBin;
86 use Weather::GHCN::CountryCodes;
87 use Weather::GHCN::Measures;
88 use Weather::GHCN::Options;
89 use Weather::GHCN::Station;
90 use GIS::Distance;
91 use Try::Tiny;
92 use URI::Fetch;
93
94 const my $EMPTY => q(); # empty string
95 const my $SPACE => q( ); # space character
96 const my $DASH => q(-); # dash character
97 const my $TAB => qq(\t); # tab character
98 const my $NL => qq(\n); # perl platform-universal newline
99 const my $TRUE => 1; # perl's usual TRUE
100 const my $FALSE => not $TRUE; # a dual-var consisting of '' and 0
101
102 const my $CONFIG_FILE => '$HOME/.ghcn_fetch.yaml';
103
104 const my %MMM_TO_MM => (
105 Jan=>1, Feb=>2, Mar=>3, Apr=>4, May=>5, Jun=>6,
106 Jul=>7, Aug=>8, Sep=>9, Oct=>10, Nov=>11, Dec=>12,
107 );
108
109 const my $GHCN_DATA => 'https://www1.ncdc.noaa.gov/pub/data/ghcn/daily/all/';
110 const my $GHCN_STN_LIST_URL => 'https://www1.ncdc.noaa.gov/pub/data/ghcn/daily/ghcnd-stations.txt';
111 const my $GHCN_STN_INVEN_URL => 'https://www1.ncdc.noaa.gov/pub/data/ghcn/daily/ghcnd-inventory.txt';
112
113 const my $STN_ID_RE => qr{ [[:upper:]]{2} [[:alnum:]\_\-]{9} }xms;
114 const my $STN_LIST_RE => qr{ \A $STN_ID_RE ( [,] $STN_ID_RE )+ \Z }xms;
115
116 # station errors (rejected)
117 const my $ERR_FETCH => 1;
118 const my $ERR_METRICS => 2;
119 const my $ERR_NOT_ACTIVE => 3;
120 const my $ERR_RANGE_FULL => 4;
121 const my $ERR_NOT_PARTIAL => 5;
122 const my $ERR_NOACTIVE => 6;
123 const my $ERR_INSUFF => 7;
124 const my $ERR_NOT_GSN => 8;
125 const my $ERR_NO_GIS => 9;
126
127 # station warnings (not rejected)
128 const my $WARN_MISS_YA => 51;
129 const my $WARN_MISS_YF => 52;
130 const my $WARN_MISS_MO => 53;
131 const my $WARN_MISS_DY => 54;
132 const my $WARN_ANOM => 55;
133
134 my %NoteMsg = ( ## no critic [ProhibitMagicNumbers]
135 1 => q|*E* unable to fetch data from URL|,
136 2 => q|*E* station doesn't have any of the required measurements|,
137 3 => q|*E* station active range isn't a subset of the -active range|,
138 4 => q|*E* station active range doesn't fully intersect -range|,
139 5 => q|*E* station active range doesn't partially intersect -active|,
140 6 => q|*E* option -range or -active specified but station has no active range in the inventory|,
141 7 => q|*E* insufficient data to meet quality threshold|,
142 8 => q|*E* not a GSN station|,
143 9 => q|*E* -gps specified but station is without GIS coordinates|,
144
145 51 => q|*W* station missing data in years of the active range|,
146 52 => q|*W* station missing data in years of the filter range|,
147 53 => q|*W* station missing one or more entire months of data in a year|,
148 54 => q|*W* station missing one or more days of data in a year|,
149 55 => q|*W* station has insufficient baseline years - anomalies not calculated|,
150 );
151
152 # Global lexical option object, created by new()
153 my $Opt;
154
155 # private fields that are intialized by set_options()
156 field $_ghcn_opt_obj; # [0] Weather::GHCN::Options object providing filtering and other options
157 field $_stnid_filter { {} }; # [1] hashref of station id's to be loaded, or empty hash
158 field $_return_list { $FALSE }; # [2] return method results as tsv if true, a list if false
159
160 # private fields that are intialized by load()
161 field $_cache; # [3] Cache::FileCache object
162 field $_measures_obj; # [4] Measures object
163
164 # private fields that are intialized by get_header()
165 field $_measure_begin_idx {0}; # [5] column index where measures will go in the output
166
167 # private fields that are intialized by new() i.e. automatically or within sub BUILD
168 field %_hstats; # [6] Hash for capturing data field hash statistics
169 field $_tstats; # [7] TimingStats object (or undef)
170
171 # data fields
172 field %_station; # [8] loaded station objects, key station_id
173 field $_aggregate_href { {} } ; # [9] hashref of aggregated (summarized0 daily data
174 field $_flag_cnts_href { {} } ; # [10] hashref of flag counts
175 field $_daily_href { {} } ; # [11] hashref of most recent daily data loaded
176 field $_baseline_href { {} } ; # [12] hashref of baseline data
177
178 # readable fields that are populated set_options
179 field $opt_obj :reader; # [13] $ghcn_opt_obj->opt_obj (a Hash::Wrap of $ghcn_opt_obj->opt_href)
180 field $opt_href :reader; # [14] $ghcn_opt_obj->opt_href
181 field $config_file :reader; # [15]
182 field $config_href :reader; # [16] hash reference containing cache and alias options
183
184 # other fields with read methods
185 field $stn_count :reader; # [17]
186 field $stn_selected_count :reader; # [18]
187 field $stn_filtered_count :reader; # [19]
188 field $missing_href :reader { {} }; # [20]
189
190 =head1 FIELD ACCESSORS
191
192 =over 4
193
194 =item opt_obj
195
196 Returns a reference to the Options object created by set_options.
197
198 =item opt_href
199
200 Returns a reference to a hash of the Options created by set_options.
201
202 =item config_file
203
204 Returns the name of the configuration file, if one was passed to
205 set_options.
206
207 =item config_href
208
209 Returns a reference to a hash containing the configuration options
210 set by set_options (if any).
211
212 =item stn_count
213
214 Returns a count of the total number of stations found in the station
215 list.
216
217 =item stn_selected_count
218
219 Returns a count of the number of stations that were selected for
220 processng.
221
222 =item stn_filtered_count
223
224 Returns a count of the number of stations that were selected for
225 processing, excluding those rejected due to errors or other criteria.
226
227 =item missing_href
228
229 Returns a hash of the missing months and days for the selected
230 data.
231
232 =back
233
234 =cut
235
236 =head1 METHODS
237
238 =head2 new ()
239
240 Create a new StationTable object.
241
242 =cut
243
244 BUILD {
245 %_hstats = ();
246 $_tstats = Weather::GHCN::TimingStats->new();
247 }
248
249 =head2 export_kml( list => 0 )
250
251 Output the coordinates of the station collection as a KML file, for
252 import into Google Earth as placemarks. The active range of each
253 station will be included as timespans so that you can view the
254 placemarks across time.
255
256 =over 4
257
258 =item argument: list
259
260 If the argument list contains the 'list' keyword and a true value,
261 then export_kml will return a string with the kml output as lines of
262 text rather than writing it to the file specified by the kml option.
263
264 =item option: kml <filespec>
265
266 Write the kml output to the file designated by <filespec>. If <filespec>
267 is an empty string, no file is written.
268
269 =item option: color <str>
270
271 A color name, one of blue, green, azure, purple, red, white or yellow.
272 Only the first character is recognized, so 'b' and 'bob' both result
273 in blue. All colors are given an opacity of 50 (the range is 00 to ff).
274
275 =back
276
277 =cut
278
279 method export_kml ( %arg ) {
280 my $return_list = $arg{list} // $_return_list;
281 my $filespec = $Opt->kml;
282
283 my $kml_color = _get_kml_color( $Opt->color );
284 my @output;
285
286 push @output, '<?xml version="1.0" encoding="UTF-8"?>';
287 push @output, '<kml xmlns="http://www.opengps.net/kml/2.2">';
288 push @output, '<Document>';
289 push @output, ' <Style id="mypin">';
290 push @output, ' <IconStyle>';
291 push @output, ' <color>' . $kml_color . '</color>';
292 push @output, ' <Icon>';
293 # push @output, ' <href>http://maps.google.com/mapfiles/kml/pushpin/' . $color . '-pushpin.png</href>';
294 push @output, ' <href>http://maps.google.com/mapfiles/kml/shapes/donut.png</href>';
295 push @output, ' </Icon>';
296 push @output, ' </IconStyle>';
297 push @output, ' </Style>';
298
299 foreach my $stn ( values %_station ) {
300 next if $stn->error_count;
301 # TODO: use ->sets to get a list of spans and use the first span instead of splitting run_list
302 my ($start, $end) = split m{ [-] }xms, $stn->active;
303
304 my $desc = $stn->description();
305
306 push @output, ' <Placemark>';
307 push @output, ' <styleUrl>#mypin</styleUrl>';
308 push @output, sprintf ' <name>%s</name>', encode_entities($stn->name);
309 push @output, sprintf ' <description>%s</description>', encode_entities($desc);
310 push @output, ' <TimeSpan>';
311 push @output, sprintf ' <begin>%s-01-01T00:00:00Z</begin>', $start;
312 push @output, sprintf ' <end>%s-12-31T23:59:59Z</end>', $end;
313 push @output, ' </TimeSpan>';
314 push @output, sprintf ' <Point><coordinates>%f, %f, %f</coordinates></Point>', $stn->long, $stn->lat, $stn->elev;
315 push @output, ' </Placemark>';
316 }
317
318 push @output, '</Document>';
319 push @output, '</kml>';
320
321 if ($filespec) {
322 # uncoverable branch true
323 # uncoverable branch false
324 open my $fh, '>', $filespec
325 or croak "*E* unable to open $filespec for write\n";
326 say {$fh} join $NL, @output;
327 # uncoverable branch true
328 # uncoverable branch false
329 close $fh or croak "*E* unable to close kml output\n";;
330 }
331
332 return $return_list ? @output : tsv(\@output);
333 }
334
335 =head2 flag_counts ()
336
337 The load_stations() and load_data() methods may reject a station or a
338 particular data entry due to quality or other issues. These
339 decisions are kept in a hash field, and a reference to that hash is
340 returned by this method. The caller can then report the values.
341
342 =cut
343
344 method flag_counts () {
345 return $_flag_cnts_href;
346 }
347
348 =head2 get_flag_statistics ( list => 0, no_header => 0 )
349
350 Gets a header row and summary table of data points that were kept and rejected, along
351 with counts of QFLAGS (quality flags). Returns tab-separated
352 text, or a list if the list argument is true. A heading line
353 is provided unless no_header is true.
354
355 =over 4
356
357 =item argument: list => <bool>
358
359 If the arguments include the 'list' keyword and a true value, then a
360 list is returned rather than tab-separated lines of text. Defaults
361 to false.
362
363 =item argument: no_header => <bool>
364
365 If the arguments include the 'no_header' keyword and a true value,
366 then the return value will not include a header line. Default is
367 false.
368
369 =back
370
371 =cut
372
373 method get_flag_statistics ( %args ) {
374 my $return_list = $args{list} // $_return_list;
375
376 my @output;
377
378 # print summary of data points kept and rejected, with qflag counts
379 push @output, ['Values', 'Kept', 'Rejected', 'Flags']
380 unless $args{no_header};
381 foreach my $elem ( sort keys $_flag_cnts_href->%* ) {
382 next if $elem =~ m{ [[:lower:]] }xms;
383 next if $elem =~ m{ \A A_ }xms;
384 my $flag_info = _qflags_as_string( $_flag_cnts_href->{$elem}->{QFLAGS} );
385
386 push @output, [
387 $elem,
388 ( $_flag_cnts_href->{$elem}->{KEPT} // 0 ),
389 ( $_flag_cnts_href->{$elem}->{REJECTED} // 0 ),
390 $flag_info,
391 ];
392 }
393
394 return $return_list ? @output : tsv(\@output);
395 }
396
397 =head2 get_footer( list => 0 )
398
399 Get a footing section with explanatory notes about the output data
400 produced by detail and summary reports.
401
402 =over 4
403
404 =item argument: list => <bool>
405
406 If the arguments include the 'list' keyword and a true value, then a
407 list is returned rather than tab-separated lines of text. Defaults
408 to false.
409
410 =back
411
412 =cut
413
414 method get_footer ( %args ) {
415 my $return_list = $args{list} // $_return_list;
416
417 my @output;
418
419 push @output, 'Notes:';
420 push @output, ' 1. Data is obtained from the GHCN GHCN repository, specifically:';
421 push @output, $TAB . $GHCN_STN_LIST_URL;
422 push @output, $TAB . $GHCN_STN_INVEN_URL;
423 push @output, $TAB . $GHCN_DATA;
424 push @output, ' 2. Temperatures are in Celsius, precipitation in mm and snowfall/depth in cm.';
425 push @output, ' 3. TAVG is a daily average computed at each station; Tavg is the average of TMAX and TMIN.';
426 push @output, ' 4. Data is averaged at the daily level across multiple stations.';
427 push @output, ' 5. Data is summarized at the monthly or yearly level using different rules depending on the measure:';
428 push @output, $TAB . '- TMAX is aggregated by max(); TMIN is aggregated by min().';
429 push @output, $TAB . '- TAVG and Tavg are aggregated by average().';
430 push @output, $TAB . '- PRCP and SNOW are aggregated by sum().';
431 push @output, $TAB . '- SNWD is aggregated by max().';
432 push @output, ' 6. Decades begin on Jan 1 in calendar years ending in zero.';
433 push @output, ' 7. Seasonal decades/year/quarters begin Dec 1 of the previous calendar year.';
434
435 return $return_list ? @output : tsv(\@output);
436 }
437
438 =head2 get_hash_stats ( list => 0, no_header => 0 )
439
440 Gets the hash sizes collected during the execution of StationTable
441 methods, notably load_stations and load_data, as tab-separated
442 lines of text.
443
444 =over 4
445
446 =item argument: list => <bool>
447
448 If the arguments include the 'list' keyword and a true value, then a
449 list is returned rather than tab-separated lines of text. Defaults
450 to false.
451
452 =item argument: no_header => <bool>
453
454 If the arguments include the 'no_header' keyword and a true value,
455 then the return value will not include a header line. Default is
456 false.
457
458 =back
459
460 =cut
461
462 method get_hash_stats ( %args ) {
463 my $return_list = $args{list} // $_return_list;
464
465 my @output;
466
467 my @keys = sort keys %_hstats;
468
469 if ( @keys and not $args{no_header} ) {
470 push @output, [ 'Hash sizes:' ];
471 push @output, [ qw(Hash Subject Iteration Size) ];
472 }
473
474 foreach my $hash ( sort @keys ) {
475 foreach my $subject ( sort keys $_hstats{$hash}->%* ) {
476 foreach my $iter ( sort keys $_hstats{$hash}->{$subject}->%* ) {
477 my $sz = commify( $_hstats{$hash}->{$subject}->{$iter} );
478 push @output, [ $hash, $subject, $iter, $sz ];
479 }
480 }
481 }
482
483 return $return_list ? @output : tsv(\@output);
484 }
485
486 =head2 get_header ( list => 0 )
487
488 The weather data obtained by the laod_data() method is essentially a
489 table. Which columns are returned depends on various options. For
490 example, if report => monthly is given, then the key columns will be
491 year and month -- no day. If the precip option is given, then
492 extra columns are included for precipitation values.
493
494 This variabiliy makes it difficult for a consumer of these modules
495 to emit a heading that matches the underlying columns. The purpose of
496 this method is to return a set of column headings that will match
497 the data. The value returned is a tab-separated string.
498
499 =over 4
500
501 =item argument: list => <bool>
502
503 If the arguments include the 'list' keyword and a true value, then a
504 list is returned rather than tab-separated lines of text. Defaults
505 to false.
506
507 =back
508
509 =cut
510
511 method get_header ( %args ) {
512 my $return_list = $args{list} // $_return_list;
513
514 # if this is a summary report, then alter the measure column labels
515 if ( not $Opt->report eq 'id' ) {
516 foreach my $label ($_measures_obj->measures) {
517 $label =~ s{ \A TMAX }{TMAX max}xms;
518 $label =~ s{ \A TMIN }{TMIN min}xms;
519
520 $label =~ s{ \A TAVG }{TAVG avg}xms;
521 $label =~ s{ \A Tavg }{Tavg avg}xms;
522
523 $label =~ s{ \A PRCP }{PRCP sum}xms;
524 $label =~ s{ \A SNOW }{SNOW sum}xms;
525
526 $label =~ s{ \A SNWD }{SNWD max}xms;
527
528 $label =~ s{ \A A_ (\w+) }{$1 anom}xms;
529 }
530 }
531
532 my $includes_month =
533 $Opt->report eq 'id' ||
534 $Opt->report eq 'daily' ||
535 $Opt->report eq 'monthly';
536
537
538 # generate and print the header row
539 my @output;
540 push @output, 'Year';
541 push @output, 'Month' if $includes_month;
542 push @output, 'Day' if $Opt->report eq 'id' or $Opt->report eq 'daily';
543 push @output, 'Decade';
544 push @output, 'S_Decade' if $includes_month;
545 push @output, 'S_Year' if $includes_month;
546 push @output, 'S_Qtr' if $includes_month;
547
548 $_measure_begin_idx = @output;
549 push @output, $_measures_obj->measures;
550
551 push @output, 'QFLAGS' if $Opt->report eq 'id';
552 push @output, 'StationId' if $Opt->report eq 'id';
553 push @output, 'Location' if $Opt->report eq 'id';
554 push @output, 'StnIdx' if $Opt->report eq 'id';
555 push @output, 'Grid' if $Opt->report eq 'id';
556
557 return $return_list ? @output : join $TAB, @output;
558 }
559
560 =head2 get_missing_data_ranges( list => 0, no_header => 0 )
561
562 Gets a list, by station id and year, of any months or day ranges
563 when data was found to be missing. Missing data can lead to incorrect
564 interpretation and can cause a station to be rejected if the percent
565 of found data does not meet the -quality threshold (normally 90%).
566
567 Returns a heading line followed by lines of tab-separated strings.
568
569 =over 4
570
571 =item argument: list => <bool>
572
573 If the arguments include the 'list' keyword and a true value, then a
574 list of lists (stations containing years) is returned rather than
575 tab-separated lines of text. Defaults to false.
576
577 =item argument: no_header => <bool>
578
579 If the arguments include the 'no_header' keyword and a true value,
580 then the return value will not include a header line. Default is
581 false.
582
583 =item option: report <daily|monthly|yearly|id>
584
585 Determines the number and content of heading values.
586
587 =back
588
589 =cut
590
591 method get_missing_data_ranges ( %args ) {
592 my $return_list = $args{list} // $_return_list;
593
594 my @output;
595
596 push @output, ['Missing year, months and days by station id and year (for selected stations):']
597 unless $args{no_header};
598
599 foreach my $stnid ( sort keys $missing_href->%* ) {
600 my $stnobj = $_station{$stnid};
601 next if $stnobj->error_count > 0;
602 my $yyyy_href = $missing_href->{$stnid};
603
604 foreach my $yyyy ( sort keys $yyyy_href->%* ) {
605 my $values_href = $yyyy_href->{$yyyy};
606 foreach my $v ( keys $values_href->%* ) {
607 push @output, [ $stnid, $yyyy, $v ];
608 }
609 }
610 }
611
612 return $return_list ? @output : tsv(\@output);
613 }
614
615 =head2 datarow_as_hash ( $row_aref )
616
617 This is a convenience method that may be used to convert table rows
618 returned by the row_sub callback subroutine of load_data from a perl
619 list into a hash. It automatically calls get_header to get the
620 headers for the table data. When you pass it a reference to a data
621 row (obtained vis the row_sub callback routine given to load_data)
622 it combines the elements of the data row list with the column headings
623 and returns a hash.
624
625 =cut
626
627 method datarow_as_hash ( $row_aref ) {
628 my @header = $self->get_header( list => 1 );
629 my %h;
630
631 @h{@header} = $row_aref->@*;
632
633 return %h;
634 }
635
636 =head2 get_missing_rows( list => 0 )
637
638 In support of a -nogaps option, to generate detail output that does
639 not have any gaps due to missing data, this method gets a list of
640 rows for the months and days that had missing data for a given
641 station id in a given year.
642
643 Returns lines of tab-separated strings.
644
645 =over 4
646
647 =item argument: list => <bool>
648
649 If the arguments include the 'list' keyword and a true value, then a
650 list is returned rather than tab-separated lines of text. Defaults
651 to false.
652
653 =item option: nogaps
654
655 Emits extra rows after the detail data rows to make up for missing
656 months or days. This is primarily so that if the data is charted
657 by date, then the x-axis will have all the dates from start to finish.
658 Otherwise, the chart and any trends that are projected on it will
659 be distorted by the missing data.
660
661 =back
662
663 =cut
664
665 method get_missing_rows ( %args ) {
666 my $return_list = $args{list} // $_return_list;
667
668 my @output;
669
670 my %loc;
671 map { $loc{$_} = $_station{$_}->name } keys %_station;
672
673 foreach my $stnid ( sort keys $missing_href->%* ) {
674 my $yyyy_href = $missing_href->{$stnid};
675 foreach my $yyyy ( sort keys $yyyy_href->%* ) {
676 my $values_href = $yyyy_href->{$yyyy};
677 foreach my $v ( keys $values_href->%* ) {
678 my ($months_aref, $mmdd_aref) = _parse_missing_text($v);
679 foreach my $mm ( $months_aref->@* ) {
680 my $ndays = _days_in_month($yyyy, $mm);
681 foreach my $day (1..$ndays) {
682 push @output, [ $yyyy, $mm, $day, ($EMPTY) x 8, $stnid, $loc{$stnid} ];
683 }
684 }
685 foreach my $mmdd_aref ( $mmdd_aref->@* ) {
686 my ($mm,$dd) = $mmdd_aref->@*;
687 push @output, [ $yyyy, $mm, $dd, ($EMPTY) x 8, $stnid, $loc{$stnid} ];
688 }
689 }
690 }
691 }
692
693 return $return_list ? @output : tsv(\@output);
694 }
695
696 =head2 get_options ( list => 0, no_header => 0 )
697
698 Get text which shows the options that were in effect for this
699 processing run, in a Getopt style. Includes a heading and a
700 footing with explanatory notes. If argument 'list' is true, returns
701 the lines as a list. Line [1] contains the options string.
702
703 =over 4
704
705 =item argument: list => <bool>
706
707 If the arguments include the 'list' keyword and a true value, then a
708 list is returned rather than tab-separated lines of text. Defaults
709 to false.
710
711 =item argument: no_header => <bool>
712
713 If the arguments include the 'no_header' keyword and a true value,
714 then the return value will not include a header line or the explanatory
715 footing notes. Default is false.
716
717 =back
718
719 =cut
720
721 method get_options ( %args ) {
722 my $return_list = $args{list} // $_return_list;
723
724 my @output;
725
726 push @output, 'Options:'
727 unless $args{no_header};
728
729 push @output, $TAB . $_ghcn_opt_obj->options_as_string;
730
731 if ( not $args{no_header} ) {
732 push @output, $EMPTY;
733 push @output, $TAB . 'Note that quality is a percentage; radius in km';
734 push @output, $TAB . 'Note that nonetwork values mean the following:';
735 push @output, $TAB . ' -1 refresh the cache if last page not refreshed this year';
736 push @output, $TAB . ' 0 always check for a fresher copy of the page';
737 push @output, $TAB . ' 1 do not contact the server, just use what is cached';
738 }
739
740 return $return_list ? @output : tsv(\@output);
741 }
742
743 =head2 get_stations ( list => 0, kept => 1, no_header => 0 )
744
745 Return lines of text with tab-separated columns describing each of
746 the stations for stations that were found to meet the filtering
747 criteria specified in the user options.
748
749 =over 4
750
751 =item argument: kept => <bool>
752
753 If the argument kept => 0 is specified, and load_data has already
754 been invoked, then the stations which were rejected due to quality flags
755 or missing data will be returned. If kept => 1 is specified, then
756 the stations that were kept will be returned.
757
758 =item argument: list => <bool>
759
760 If the arguments include the 'list' keyword and a true value, then a
761 list is returned rather than tab-separated lines of text. Defaults
762 to false.
763
764 =item argument: no_header => <bool>
765
766 If the arguments include the 'no_header' keyword and a true value,
767 then the return value will not include a header line. Default is
768 false.
769
770 =back
771
772 =cut
773
774 method get_stations ( %args ) {
775 my $return_list = $args{list} // $_return_list;
776 my $kept = $args{kept};
777 my $no_header = $args{no_header};
778
779 my @output;
780
781 # no stations, so just return empty
782 return $return_list ? @output : tsv(\@output)
783 if $self->stn_filtered_count == 0;
784
785 push @output, scalar Weather::GHCN::Station::Headings
786 unless $no_header;
787
788 my $ii = 0;
789 foreach my $id ( sort keys %_station ) {
790 my $stn = $_station{$id};
791 $ii++;
792 if (not defined $kept
793 or $kept and $stn->error_count == 0
794 or not $kept and $stn->error_count > 0)
795 {
796 push @output, scalar $stn->row;
797 }
798 }
799
800 croak '*E* get_stations called before load_stations'
801 if $ii == 0;
802
803 return $return_list ? @output : tsv(\@output);
804 }
805
806 =head2 get_station_note_list ()
807
808 Return a list consisting of tab-separated code/description pairs that
809 rejected stations were flagged with; i.e. the reasons for their
810 rejection.
811
812 =cut
813
814 # TODO: consider removing this as it is no longer used anywere
815 method get_station_note_list () {
816 my @stn_notes;
817
818 my $notes_nrs = rng_new();
819
820 foreach my $id ( sort keys %_station ) {
821 my $stn = $_station{$id};
822 # combine all the notes
823 $notes_nrs->add( $stn->note_nrs->as_array );
824 }
825
826 if ( not $notes_nrs->is_empty ) {
827 foreach my $note_code ($notes_nrs->as_array) {
828 push @stn_notes, join $TAB, $note_code, $NoteMsg{$note_code};
829 }
830 }
831
832 return @stn_notes;
833 }
834
835 =head2 get_summary_data ( list => 0 )
836
837 Gets a list of summarized the temperature or precipitation data
838 by day, month or year depending on the report option.
839
840 Returns undef if the report option is 'id'.
841
842 The actual columns that are returned is dictated by the report option
843 and by the tavg and precip options provided when the object was
844 instantiated by new().
845
846 =over 4
847
848 =item argument: list => <bool>
849
850 If the arguments include the 'list' keyword and a true value, then a
851 list is returned rather than tab-separated lines of text. Defaults
852 to false.
853
854 =item option: report <daily|monthly|yearly>
855
856 Determines the level of summarization.
857
858 =item option: range <rangelist>
859
860 If the range option is provided, the output rows are restricted to
861 those years that are within the specified range(s).
862
863 =back
864
865 =cut
866
867 method get_summary_data ( %args ) {
868 my $return_list = $args{list} // $_return_list;
869
870 # when an 'id' report is requested, we generate detail data only
871 # so there is no summary data to print
872 return if $Opt->report eq 'id';
873
874 my @output;
875
876 # build hash of measure names and indices so measures can be
877 # inserted into the correct columns
878 my %measure_idx;
879 my $ii = 0;
880 foreach my $m ( $_measures_obj->measures ) {
881 $measure_idx{$m} = $_measure_begin_idx + $ii++;
882 }
883
884 my $opt_range_nrs = rng_new($Opt->range);
885
886 # generate and print the data rows
887 foreach my $key ( sort keys $_aggregate_href->%* ) {
888 my ($year, $month, $day) = unpack 'A4 A2 A2', $key;
889
890 next if $Opt->range and not $opt_range_nrs->contains($year);
891
892 my $row = $_aggregate_href->{$key};
893
894 my @row;
895 push @row, $year;
896 push @row, $month if $Opt->report eq 'daily' or $Opt->report eq 'monthly';
897 push @row, $day if $Opt->report eq 'daily';
898 push @row, int($year / 10) * 10; ## no critic [ProhibitMagicNumbers]
899 if ( not $Opt->report eq 'yearly' ) {
900 push @row, _seasonal_decade($year, $month);
901 push @row, _seasonal_year($year, $month);
902 push @row, _seasonal_qtr($year, $month);
903 }
904
905 foreach my $elem ( $_measures_obj->measures ) {
906 my $sum = $row->{$elem}->[0];
907 my $cnt = $row->{$elem}->[1];
908 $row[ $measure_idx{$elem} ] = $cnt ? sprintf '%.2f', ($sum // 0) / $cnt : $EMPTY;
909 }
910
911 push @output, \@row;
912 }
913
914 return $return_list ? @output : tsv(\@output);
915 }
916
917
918 =head2 get_timing_stats ( list => 0 )
919
920 Get a list of the timers, with durations and notes, in alphabetical
921 order by timer label.
922
923 =over 4
924
925 =item argument: list => <bool>
926
927 If the arguments include the 'list' keyword and a true value, then a
928 list is returned rather than tab-separated lines of text. Defaults
929 to false.
930
931 =back
932
933 =cut
934
935 method get_timing_stats ( %args ) {
936 my $return_list = $args{list} // $_return_list;
937
938 my @output;
939
940 foreach my $k ( $_tstats->get_timers() ) {
941 my $note = $_tstats->get_note($k) // $EMPTY;
942 ## no critic [ProhibitMagicNumbers]
943 my $dur = sprintf '%.1f', $_tstats->get_duration($k) * 1000.0;
944 my $label = $k . $SPACE . $note;
945 push @output, $args{rows_as_tsv}
946 ? [ $dur, $label ]
947 : join $TAB, $dur, $label;
948 }
949
950 return $return_list ? @output : tsv(\@output);
951 }
952
953 =head2 has_missing_data ()
954
955 Returns true if any missing data was detected amongst the stations
956 that were processed. The calling script can use this to decide
957 whether to issue a warning to the user. A list of missing data
958 specifics can be sent to the output by calling method
959 get_missing_data_ranges.
960
961 =cut
962
963 method has_missing_data () {
964 my $keycount = ( keys $missing_href->%* );
965 return $keycount ? $TRUE : $FALSE;
966 }
967
968 =head2 load_data ( progress_sub => undef, row_sub => sub { say @_ } )
969
970 Load the daily weather data for each of the stations that are were
971 loaded into the collection. Print the data if option report id is
972 given. Otherwise cache the data so it can be aggregated at a later
973 step.
974
975 =over 4
976
977 =item argument: progress_sub => undef
978
979 As fetching and parsing each daily data page can take some time, an
980 optional callback hook is provided so the caller can emit a
981 progress message before each station's data is loaded; e.g.
982 progress => sub{ say {STDERR} @_ }.
983
984 =item argument: row_sub => sub { say @_ }
985
986 Optional callback hook to allow the caller to provide their own
987 subroutine for printing (or collecting in a list, or both) the
988 row-level station data that is fetched when the report option is 'id'.
989 Defaults to printing via the 'say' operator.
990
991 =item option: report <id|daily|monthly|yearly>
992
993 When report id is specified, the weather data for each station is
994 printed immediately (via the row_sub callback hook).
995
996 For all other report options, the data is fetched from each station
997 and kept in a cache so that it can be aggregated by invoking
998 summarize_data(). The row_sub hook is not invoked.
999
1000 =back
1001
1002 =cut
1003
1004 method load_data ( %args ) {
1005 my $progress_callback = $args{progress_sub};
1006 my $row_callback = $args{row_sub};
1007
1008 my @station_objs =
1009 sort { $a->id cmp $b->id }
1010 grep { $_->error_count == 0 } values %_station;
1011
1012 my $stn_count = @station_objs;
1013
1014 my $ii = 0;
1015 foreach my $stn ( @station_objs ) {
1016 my $daily_url = $GHCN_DATA . $stn->id . '.dly';
1017 my $content = $self->_fetch_url($daily_url, $_cache, 'URI::Fetch_daily');
1018
1019 if ($progress_callback) {
1020 no strict 'refs'; ## no critic [ProhibitNoStrict]
1021 my $msg = sprintf 'processing station %d/%d %s %s', ++$ii, $stn_count, $stn->id, $stn->name;;
1022 $progress_callback->($msg);
1023 }
1024
1025 if (not $content) {
1026 $stn->add_note($ERR_FETCH, $stn->id . $TAB . 'fetch daily URL failed');
1027 next;
1028 }
1029
1030 my $insufficient_quality = $self->_load_daily_data($stn, $content);
1031
1032 if ( $Opt->report eq 'id' ) {
1033 $self->_print_detail_data( $_measure_begin_idx, $stn, $row_callback );
1034 } else {
1035 $self->_aggregate_station_data($stn)
1036 unless $insufficient_quality;
1037 }
1038
1039 $self->_clear_daily_data();
1040
1041 $self->_capture_data_hash_stats($stn->id, $ii);
1042 }
1043
1044 return;
1045 }
1046
1047 =head2 load_stations ()
1048
1049 Read the GHCN stations list and the stations inventory list and create
1050 a hash of Station objects, keyed on station id, filtered according
1051 to the options provided in set_options().
1052
1053 Returns a hash of Weather::GHCN::Station objects, keyed on station id.
1054
1055 =over 4
1056
1057 =item option: country <str>
1058
1059 Selects only those stations that match the 2-digit GEC (formerly
1060 FIPS) country code or that uniquely match the name or partial name
1061 given in <str>.
1062
1063 =item option: state <code>
1064
1065 Selects only those stations that match a US state or Canadian provinc
1066 code.
1067
1068 =item option: location <str>
1069
1070 Selects only those stations with a name that matches the specified
1071 pattern, which can be either a station id, or a comma-separated
1072 list of station id's, or a regex. If a regex, then it is anchored
1073 on the left and whitespace is NOT ignored.
1074
1075 =item option: gps <latitude,longitude>
1076
1077 This option selects stations within a certain radius of the designated
1078 latitude and longitude, expressed as positive and negative numbers
1079 (not using N, S, W, E designators).
1080
1081 =item option: radius <int>
1082
1083 In conjunction the gps options, determines the radius in kilometers
1084 for the search area. Defaults to 25 km.
1085
1086 =item option: gsn
1087
1088 Select only GCOS Surface Network stations, which is a baseline
1089 network comprising a subset of about 1000 stations chosen mainly to
1090 give a fairly uniform spatial coverage from places where there is a
1091 good length and quality of data record. See
1092 L<https://www.ncdc.noaa.gov/gosic/global-climate-observing-system-gcos/g
1093 cos-surface-network-gsn-program-overview>
1094
1095 =back
1096
1097 =cut
1098
1099 method load_stations () {
1100
1101 # get the caching configuration and use it to create a cache for URI::Fetch
1102 # if no cache config, then $_cache will be undef and fetches will be uncached
1103 if ($config_href and $config_href->{'cache'} ) {
1104 my $cache_opt = $config_href->{'cache'};
1105 my $namespace = $cache_opt->{'namespace'} // 'ghcn';
1106 my $root = $cache_opt->{'root'};
1107 my $root_abs = File::Spec->rel2abs( $root, $FindBin::Bin );
1108
1109 $_cache = Cache::FileCache->new(
1110 {
1111 cache_root => $root_abs,
1112 namespace => $namespace,
1113 }
1114 );
1115 }
1116
1117 my $stations_content = $self->_fetch_url( $GHCN_STN_LIST_URL, $_cache, 'URI::Fetch_stn');
1118
1119 if ( $stations_content =~ m{<title>(.*?)</title>}xms ) {
1120 croak '*E* unable to fetch data from ' . $GHCN_STN_LIST_URL . ': ' . $1;
1121 }
1122
1123 ## no critic [InputOutput::RequireBriefOpen]
1124 open my $stn_fh, '<', \$stations_content
1125 or croak '*E* unable to open stations_content string';
1126
1127 $_tstats->start('Parse_stn');
1128
1129 my %stnidx;
1130 my $gps = GIS::Distance->new;
1131
1132 # Scan the station table
1133 # - filtering on country, state, location and GIS distance according to options
1134 while ( my $line = <$stn_fh> ) {
1135 $stn_count++;
1136
1137 # |--- 0---|--- 10---|--- 20---|--- 30---|--- 40---|--- 50---|--- 60---
1138 # |123456789|123456789|123456789|123456789|123456789|123456789|123456789
1139 # (stationid).(latitu).(longitu).(elev).st.--name-----------------------
1140 # ACW00011604 17.1167 -61.7833 10.1 ST JOHNS COOLIDGE FLD
1141
1142 ## no critic [ProhibitMagicNumbers]
1143 my $id = substr $line, 0, 11;
1144
1145 next if $_stnid_filter->%* and not $_stnid_filter->{$id};
1146
1147 my $lat = 0 + substr $line, 12, 8; # coerce to number
1148 my $long = 0 + substr $line, 21, 9; # coerce to number
1149 my $elev = 0 + substr $line, 31, 6; # coerce to number
1150 my $state = substr $line, 38, 2;
1151 my $name = substr $line, 41, 30;
1152 my $gsn_flag = substr $line, 72, 3;
1153 # my $hcr_crn_flag = substr $line, 76, 3;
1154 # my $wmo_id = substr $line, 80, 5;
1155
1156 my $country = substr $id, 0, 2;
1157 $name =~ s{ \s+ \Z }{}xms;
1158
1159 ## use critic [ProhibitMagicNumbers]
1160
1161 ## no critic [RequireExtendedFormatting]
1162 my $opt_country = $Opt->country;
1163 next if $Opt->country and $country !~ m{\A$opt_country}msi;
1164
1165 my $opt_state = $Opt->state;
1166 next if $Opt->state and $state !~ m{\A$opt_state}msi;
1167
1168 ## use critic [RequireExtendedFormatting]
1169 next if $Opt->location and not _match_location($id, $name, $Opt->location);
1170
1171 if ( $Opt->gps ) {
1172 my ($opt_lat, $opt_long) = split m{[,;\s]}xms, $Opt->gps;
1173 my $distance = $gps->distance($opt_lat, $opt_long, $lat, $long);
1174 next if $distance->kilometers > $Opt->radius;
1175 }
1176
1177 my $gsn = $gsn_flag eq 'GSN' ? 'GSN' : $EMPTY;
1178
1179 next if $Opt->gsn and not $gsn;
1180
1181 $_station{$id} = Weather::GHCN::Station->new(
1182 id => $id,
1183 country => $country,
1184 state => $state,
1185 active => $EMPTY,
1186 lat => $lat,
1187 long => $long,
1188 elev => $elev,
1189 name => $name,
1190 gsn => $gsn
1191 );
1192
1193 $stnidx{$_station{$id}->coordinates}++;
1194 }
1195 close $stn_fh or croak '*E* unable to close stations_content string';
1196
1197 $_tstats->stop('Parse_stn');
1198
1199 $stn_selected_count = keys %_station;
1200
1201 # assign a unique index to each station with matching coordinates
1202 my $ii = 0;
1203 foreach my $coord (sort keys %stnidx) {
1204 $stnidx{$coord} = ++$ii;
1205 }
1206
1207 foreach my $stnid ( sort keys %_station ) {
1208 my $stn = $_station{$stnid};
1209 $stn->idx = $stnidx{$stn->coordinates};
1210 }
1211
1212 $stn_filtered_count = $self->_load_station_inventories();
1213
1214 return \%_station;
1215 }
1216
1217 =head2 ($opt, @errors) = set_options ( %args )
1218
1219 Set various options for this StationTable instance. These options
1220 will affect the processing and output by subsequent method calls.
1221
1222 Returns an Option object and a list of errors. It is advised you
1223 check @errors after calling set_options cease processing; e.g.
1224 I<die @errors if @errors>.
1225
1226 You may want to set up a file-scoped lexical variable to hold the
1227 options object. That way it is accessible throughout your code.
1228 The typical calling pattern would look like this:
1229
1230 my $Opt; # a file-scope lexical
1231
1232 sub run (@ARGV) {
1233 my $ghcn = Weather::GHCN::StationTable->new;
1234
1235 my @errors;
1236 ($Opt, @errors) = set_options(...);
1237 die @errors if @errors;
1238 ...
1239 }
1240
1241 =over 4
1242
1243 =item user_options => \%user_options
1244
1245 This optional argument provides a reference to a hash
1246 that contains a set of options that will control the filtering,
1247 processing and output of the GHCN modules. This hash is typically
1248 created by the caller using Getopt::Long.
1249
1250 The options provided can be any subset of the supported options. Any
1251 option not provided will be added with an appropriate default value.
1252 The resulting combined option collection will be available as both as
1253 hash reference in the instance, and as a Hash::Wrap object reference
1254 in the instance via methods.
1255
1256 If empty or undef, a list of all stations in the GHCN database will
1257 be generated, so it's best to at least provide some country or
1258 station id filtering, and absolutely necessary in order to produce
1259 other output such as daily or monthly weather data (by specifying
1260 -report).
1261
1262 See USER OPTIONS for a list of the options available.
1263
1264 =item config_file => $config_filespec
1265
1266 This optional argument specifies a file which will be used to set
1267 the configuration options. The file must contain YAML specifications
1268 that describe the hash structure defined in section CONFIGURATION
1269 OPTIONS.
1270
1271 This option is an alternative to config_options. (If both options
1272 are specifed, then config_options will take precedence.)
1273
1274 If config_filespec is an empty string, then the filespec will default
1275 to $HOME\.ghcn_fetch.yaml (%UserProfile% on Windows).
1276
1277 If config_filespec is undef, then an empty configuration will be
1278 used; i.e. there will be no cache and no aliases.
1279
1280 =item config_options => \%config_options
1281
1282 This optional argument is a reference to a hash containing
1283 configuration options as described in section CONFIGURATION OPTION.
1284 Alternatively, config_file can be used to specify a file containing
1285 the configuation specification in YAML format.
1286
1287 =item stnid_filter => \%stnid_filter
1288
1289 This optional argument should be a reference to a hash whose keys are
1290 the specific station id's which are to be fetched and processed.
1291 When this is used, many filtering options via %opt will be overridden
1292 (e.g. -country).
1293
1294 =item timing_stats => $TimingStats_obj
1295
1296 This optional argument should point to a TimingStats object that was
1297 created by the caller and will be used to collect timing statistics.
1298
1299 =item hash_stats => \%hash_stats
1300
1301 This optional argument should be a reference to a hash that was
1302 created by the caller and will be used to collect performance and
1303 memory statistics.
1304
1305 =item return_list => <bool>
1306
1307 By default, get methods return a tab-separated string of results.
1308 If return_list is set to true, then these methods will return a
1309 list (or list of lists).
1310
1311 =back
1312
1313 =cut
1314
1315 method set_options (%arg) {
1316 my $user_options;
1317 my $config_options;
1318
1319 my %valid;
1320
1321 if ( $arg{'user_options'} ) {
1322 $valid{'user_options'}++;
1323 $_ghcn_opt_obj //= Weather::GHCN::Options->new();
1324 $user_options = $arg{'user_options'};
1325 # combine user-specified options with the defaults
1326 ($opt_href, $opt_obj) = $_ghcn_opt_obj->combine_options($user_options);
1327 # update the combined options hash in the Options object
1328 $_ghcn_opt_obj->opt_href = $opt_href;
1329 # update the combined options object in the Options object
1330 $_ghcn_opt_obj->opt_obj = $opt_obj;
1331 # save the combined option object in a file-scoped lexical for use throughout this code
1332 $Opt = $opt_obj;
1333 }
1334
1335 if ( $arg{'config_file'} ) {
1336 $valid{'config_file'}++;
1337 $config_file = $arg{'config_file'};
1338 $config_href = _get_config_options($config_file);
1339 # update the config options hash in the Options object
1340 $_ghcn_opt_obj->config_href = $config_href;
1341 }
1342
1343 if ( $arg{'config_options'} ) {
1344 $valid{'config_options'}++;
1345 carp '*W* set_options: config_options override config_file'
1346 if $valid{'config_file'};
1347 $_ghcn_opt_obj //= Weather::GHCN::Options->new();
1348 $config_options = $arg{'config_options'};
1349 $config_href = $arg{'config_options'};
1350 # update the config options hash in the Options object
1351 $_ghcn_opt_obj->config_href = $config_href;
1352
1353 }
1354
1355 if ( $arg{'stnid_filter'} ) {
1356 $valid{'stnid_filter'}++;
1357 $_stnid_filter = $arg{'stnid_filter'} // {};
1358 }
1359
1360 if ( $arg{'return_list'} ) {
1361 $valid{'return_list'}++;
1362 $_return_list = $arg{'return_list'};
1363 }
1364
1365 foreach my $kw (keys %arg) {
1366 croak '*E* set_options unrecognized argument: ' . $kw
1367 unless exists $valid{$kw};
1368 }
1369
1370 $_measures_obj = Weather::GHCN::Measures->new($opt_href)
1371 if $user_options;
1372
1373 my @errors = $_ghcn_opt_obj->validate();
1374
1375 return ($opt_obj, @errors);
1376 }
1377
1378 =head2 summarize_data ()
1379
1380 Aggregate the daily weather data for the stations that were loaded,
1381 according to the report option.
1382
1383 =over 4
1384
1385 =item option: report => 'daily|monthly|yearly'
1386
1387 When the report option is 'id', no summarization is needed and the
1388 method immediately returns undef.
1389
1390 =back
1391
1392
1393 =cut
1394
1395 method summarize_data () {
1396
1397 # when an 'id' report is requested, we generate detail data only
1398 # so there is no need to summarize data.
1399 return if $Opt->report eq 'id';
1400
1401 # We'll be replacing $_aggregate_href with this hash after we're
1402 # done, but we can't loop over $_aggregate_href and be changing
1403 # it within the loop. Hence the need for another hash.
1404 my %summary;
1405
1406 $_tstats->start('Summarize_data');
1407
1408 while ( my ($k,$href) = each $_aggregate_href->%* ) {
1409 ## no critic [ProhibitMagicNumbers]
1410 my $year = substr $k, 0, 4;
1411 my $month = substr $k, 4, 2;
1412 my $day = substr $k, 6, 2;
1413 ## use critic [ProhibitMagicNumbers]
1414
1415 my $key = $year;
1416 $key .= $month if $Opt->report eq 'monthly' or $Opt->report eq 'daily';
1417 $key .= $day if $Opt->report eq 'daily';
1418
1419 foreach my $elem ( keys $href->%* ) {
1420 my $a = $_aggregate_href->{$k}->{$elem};
1421
1422 my $v = _ddivide( $a->[0], $a->[1] );
1423
1424 my $s = $summary{$key}{$elem} //= [undef, undef];
1425
1426 if ($elem eq 'TMIN') {
1427 # for TMIN we keep the minimum value
1428 $s->[0] = _dmin($s->[0], $v);
1429 $s->[1] = 1.0;
1430 }
1431 elsif ( $elem eq 'TMAX' or $elem eq 'SNWD' ) {
1432 # For TMAX SNOW SNWD PRCP we keep the maximum value
1433 $s->[0] = _dmax($s->[0], $v);
1434 $s->[1] = 1.0;
1435 }
1436 elsif ( $elem eq 'PRCP' or $elem eq 'SNOW' ) {
1437 # for PRCP and SNOW, sum and use a count of 1 so we sum across time
1438 $s->[0] = _dsum($s->[0], $v);
1439 $s->[1] = 1.0;
1440 }
1441 else {
1442 # for TAVG and Tavg and the anomaly values we keep the sum and count,
1443 # so we can calculate an average of them across time
1444 $s->[0] = _dsum($s->[0], $v);
1445 $s->[1] = _dcount($s->[1], $v);
1446 }
1447 }
1448 }
1449
1450 $_tstats->stop('Summarize_data', _memsize(\%summary, $Opt->performance));
1451
1452 $_aggregate_href = \%summary;
1453
1454 return;
1455 }
1456
1457 =head2 tstats ()
1458
1459 Provides access to the TimingStats object so the caller can start
1460 and stop script-level timers.
1461
1462 =cut
1463
1464 method tstats () {
1465 return $_tstats;
1466 }
1467
1468 =head2 DOES
1469
1470 Defined by Object::Pad. Included for POD::Coverage.
1471
1472 =head2 META
1473
1474 Defined by Object::Pad. Included for POD::Coverage.
1475
1476 =cut
1477
1478 #---------------------------------------------------------------------
1479 # Private Methods
1480 #---------------------------------------------------------------------
1481
1482 method _aggregate_station_data ($stn) {
1483
1484 $_tstats->start('Aggregate_station_data');
1485
1486
1487 while ( my ($yyyymmdd,$href) = each $_daily_href->%* ) {
1488 while ( my ($elem,$v) = each $href->%* ) {
1489 # autovivify the slot, initialize the array, and get a reference to the
1490 # slot to avoid the overhead of multiple key lookups later
1491 my $slot_href = $_aggregate_href->{$yyyymmdd}->{$elem} //= [undef, undef];
1492
1493 # We accumulate into two array elements. The first contains
1494 # the sum and the second the count so we can compute avg = sum/count.
1495 # _dsum and _dcount return the second arg if the first arg is undef
1496 # otherwise, _dsum returns the sum of the two args and _dcount returns the
1497 # value of the first arg incremented by 1
1498 $slot_href->[0] = _dsum($slot_href->[0], $v);
1499 $slot_href->[1] = _dcount($slot_href->[1], $v);
1500 }
1501 }
1502
1503 $_tstats->stop('Aggregate_station_data', _memsize($_aggregate_href, $Opt->performance));
1504
1505 return;
1506 }
1507
1508 method _capture_data_hash_stats ($subject, $iter) {
1509
1510 $_hstats{'aggregate'}{$subject}{$iter} = Devel::Size::total_size( $_aggregate_href );
1511 $_hstats{'flag_cnts'}{$subject}{$iter} = Devel::Size::total_size( $_flag_cnts_href );
1512 $_hstats{'daily'}{$subject}{$iter} = Devel::Size::total_size( $_daily_href );
1513 $_hstats{'baseline'}{$subject}{$iter} = Devel::Size::total_size( $_baseline_href );
1514
1515 return;
1516 }
1517
1518 method _clear_daily_data () {
1519
1520 $_daily_href = { };
1521
1522 return;
1523 }
1524
1525 method _compute_anomalies () {
1526
1527 $_tstats->start('Compute_anomalies');
1528
1529 while ( my ($k,$href) = each $_daily_href->%* ) {
1530 my ($year,$month,$day) = unpack 'A4 A2 A2', $k;
1531
1532 my $base_href = $_baseline_href->{ $month . $day };
1533
1534 foreach my $elem ( keys $href->%* ) {
1535 next if not exists $base_href->{$elem};
1536 $href->{'A_' . $elem} = $href->{$elem} - $base_href->{$elem};
1537 }
1538 }
1539
1540 $_tstats->stop('Compute_anomalies');
1541
1542 return;
1543 }
1544
1545 method _compute_baseline ($stn, $baseline) {
1546
1547 $_tstats->start('Compute_baseline');
1548
1549 my $baseline_nrs = rng_new($baseline);
1550
1551 my %baseline_data;
1552
1553 my $gap_nrs = rng_new( $baseline_nrs->as_string );
1554
1555 while ( my ($k,$href) = each $_daily_href->%* ) {
1556 my ($year,$month,$day) = unpack 'A4 A2 A2', $k;
1557
1558 next unless $baseline_nrs->contains($year);
1559
1560 $gap_nrs->remove($year) if $baseline_nrs->contains($year);
1561
1562 while ( my ($elem,$v) = each $href->%* ) {
1563 $baseline_data{ $month . $day }->{$elem}->[0] += $v // 0;
1564 $baseline_data{ $month . $day }->{$elem}->[1] ++;
1565 }
1566 }
1567
1568 if ($gap_nrs->cardinality > 0) {
1569 my $msg = sprintf "%s\tanomalies not calculated\tmissing %d years from the baseline (%s)",
1570 $stn->id, $gap_nrs->cardinality, $gap_nrs->as_string;
1571 $stn->add_note($WARN_ANOM, $msg);
1572 $_baseline_href = { };
1573 return;
1574 }
1575
1576 while ( my ($md,$elem_href) = each %baseline_data ) {
1577 while ( my ($elem, $aref) = each $elem_href->%* ) {
1578 my ($sum, $count) = $aref->@*;
1579 $baseline_data{$md}->{$elem} = $sum / $count;
1580 }
1581 }
1582
1583 $_baseline_href = \%baseline_data;
1584
1585 $_tstats->stop('Compute_baseline');
1586
1587 return;
1588 }
1589
1590 method _compute_mean_and_counts ($stn) {
1591
1592 $_tstats->start('Compute_mean');
1593
1594 # In this subroutine we loop through the daily min and max values that
1595 # were captured from the daily page and replace them with the calculated
1596 # mean. We replace in order to save on the memory and performance overhead
1597 # of creating a new hash table. Because the daily page has separate rows for
1598 # max and min, we have to scan the entire page in order to collect the max and
1599 # min for each day. It's possible there may be a day with one or both entries
1600 # missing, in which case we undef the corresponding entry since it's impossible
1601 # to calculate the mean in that case.
1602
1603 while ( my ($yyyymmdd, $href) = each $_daily_href->%* ) {
1604
1605 my $max = $href->{TMAX};
1606 my $min = $href->{TMIN};
1607
1608 if (defined $max and defined $min) {
1609 $href->{Tavg} = ($max + $min) / 2.0;
1610 }
1611 }
1612
1613 $_tstats->stop('Compute_mean');
1614
1615 return;
1616 }
1617
1618 method _compute_quality ($stn, $context_msg, $day_count, $range, $quality) {
1619
1620 $_tstats->start('Compute_quality');
1621
1622 my $expected_days = 0;
1623 my $insufficient_quality = 0;
1624
1625 map { $expected_days += _days_in_year($_) } rng_new($range)->as_array();
1626
1627 ## no critic [ProhibitMagicNumbers]
1628 my $data_quality = int(($day_count / $expected_days) * 1000 + 0.5) / 10.0;
1629
1630 if ( $data_quality < $quality ) {
1631 my $msg = sprintf "%s\tinsufficient data\tstation only has %d days in %s and needs %d (%0.1f%% < %d%%)",
1632 $stn->id, $day_count, $context_msg, $expected_days, $data_quality, $quality;
1633 $stn->add_note($ERR_INSUFF, $msg);
1634 $insufficient_quality++;
1635 }
1636
1637 $_tstats->stop('Compute_quality');
1638
1639 return $insufficient_quality;
1640 }
1641
1642 method _fetch_url ($url, $cache, $timer_label=$EMPTY) {
1643
1644 $_tstats->start($timer_label) if $timer_label;
1645
1646 # $cache is a Cache::FileCache object. URI::Fetch will use this
1647 # object to designate the location of its page cache.
1648
1649 # NoNetwork == 0:
1650 # If a page is in the cache, the origin HTTP server is always checked for
1651 # a fresher copy
1652
1653 # NoNetwork == 1:
1654 # The origin HTTP is never contacted, regardless of the page being in
1655 # cache or not. If the page is missing from cache, the fetch method will
1656 # return undef. If the page is in cache, that page will be returned, no
1657 # matter how old it is.
1658
1659 # NoNetwork > 1:
1660 # The origin HTTP server is not contacted if the page is in cache and the
1661 # cached page was inserted in the last N seconds.
1662 # If the cached copy is older than N seconds, a normal HTTP request (full
1663 # or cache check) is done.
1664
1665 # NoNetwork is set to the value of -nonetwork (when it was provided)
1666 # If the -nonetwork option is not given, then NoNetwork is set to the number
1667 # of seconds in the current year.
1668
1669 my $nonetwork = $Opt->nonetwork;
1670
1671 croak '*E* set_options must include cache options if the nonetwork option is > 0'
1672 if $nonetwork > 0 and not $cache;
1673
1674 if ( !$Opt->defined('nonetwork') || $Opt->nonetwork < 0 ) {
1675 ## no critic [ProhibitMagicNumbers]
1676 my @t = localtime;
1677 # set nonetwork to the number of seconds this year
1678 # $t[7] is the day of the year (0..364/365)
1679 $nonetwork = $t[7] * 24 * 60*60;
1680 }
1681
1682
1683 my %fetch_opt = ( NoNetwork => $nonetwork );
1684
1685 $fetch_opt{Cache} = $cache if $cache;
1686
1687 my $res = URI::Fetch->fetch( $url, %fetch_opt )
1688 or croak '*E* unable to fetch data from ' . $url . ': ' .
1689 ( URI::Fetch->errstr // 'unknown error' ). "\n";
1690
1691 $_tstats->stop($timer_label) if $timer_label;
1692
1693 my $content = $res->is_success ? $res->content : $EMPTY;
1694
1695 return $content;
1696 }
1697
1698 method _filter_stations ($stations_href) {
1699 $_tstats->start('Filter_stn');
1700
1701 my $opt_range_nrs = rng_new( $Opt->range );
1702 my $opt_active_nrs = rng_new( $Opt->active );
1703
1704 foreach my $stn (values $stations_href->%*) {
1705 my $stn_active_nrs = rng_new( $stn->active );
1706
1707 ##debug '=== station ', $stn->id, ' ', $stn->name;
1708
1709 $stn->add_note($ERR_METRICS)
1710 if not $stn->elems_href->%*;
1711
1712 $stn->add_note($ERR_RANGE_FULL)
1713 if $Opt->range and not $opt_range_nrs->subset($stn_active_nrs);
1714
1715 $stn->add_note($ERR_NO_GIS)
1716 if $Opt->gps and $stn->coordinates eq $EMPTY;
1717
1718 $stn->add_note($ERR_NOACTIVE)
1719 if $Opt->active and not $stn->active;
1720
1721 if ($stn->active) {
1722 if ($Opt->partial) {
1723 my $s = $opt_active_nrs->intersection($stn_active_nrs);
1724
1725 $stn->add_note($ERR_NOT_PARTIAL)
1726 if $Opt->active and $s->is_empty;
1727 } else {
1728 $stn->add_note($ERR_NOT_ACTIVE)
1729 if $Opt->active and not $opt_active_nrs->subset($stn_active_nrs);
1730 }
1731
1732 } else {
1733 $stn->add_note($ERR_NOACTIVE)
1734 if $Opt->range;
1735 }
1736 }
1737
1738 $_tstats->stop('Filter_stn');
1739
1740 my $count = grep { $_->error_count == 0 } values $stations_href->%*;
1741
1742 return $count;
1743 }
1744
1745 method _initialize_flag_cnts () {
1746
1747 # initialize KEPT flags for all metrics, so all get printed
1748 foreach my $elem ( $_measures_obj->measures ) {
1749 $_flag_cnts_href->{$elem}->{KEPT} //= 0;
1750 }
1751
1752 return;
1753 }
1754
1755 method _load_daily_data ($stn, $stn_content) {
1756
1757 my %gaps;
1758 my %baseline_days;
1759
1760 my $opt_range_nrs = rng_new($Opt->range);
1761 my $opt_baseline_nrs = rng_new($Opt->baseline);
1762 my $opt_fmonth_nrs = rng_new($Opt->fmonth);
1763 my $opt_fday_nrs = rng_new($Opt->fday);
1764
1765 $self->_initialize_flag_cnts();
1766
1767 ## no critic [ProhibitMagicNumbers]
1768
1769 $_tstats->start('Load_daily_data');
1770
1771 ## no critic [InputOutput::RequireBriefOpen]
1772 open my $stn_fh, '<', \$stn_content
1773 or croak '*E* unable to open station daily content';
1774
1775 while ( my $line = <$stn_fh> ) {
1776
1777 # |--- 0---|--- 10---|--- 20---|--- 30---|--- 40---|--- 50---|
1778 # |123456789|123456789|123456789|123456789|123456789|123456789|
1779 # iiiiiiiiiiiyyyymmeeee(dddddd)(dddddd)(dddddd)(dddddd)(dddddd) ...
1780 # CA006105976188911TMAX 39 C 122 C 144 C 83 C 28 C ...
1781
1782 my $id = substr $line, 0, 11;
1783 my $year = 0 + substr $line, 11, 4; # coerce to number
1784 my $month = 0 + substr $line, 15, 2; # coerce to number
1785 my $element = substr $line, 17, 4;
1786 my $data = substr $line, 21 ;
1787
1788 next unless $element =~ $_measures_obj->re;
1789
1790 next if $Opt->fmonth and not $opt_fmonth_nrs->contains($month);
1791
1792 my $need_baseline = $Opt->anomalies and $opt_baseline_nrs->contains($year);
1793 if ( $Opt->range ) {
1794 next unless $opt_range_nrs->contains($year)
1795 or $need_baseline;
1796 }
1797
1798 foreach my $ii ( 0 .. 30 ) {
1799 my $day = $ii + 1;
1800
1801 next if $Opt->fday and not $opt_fday_nrs->contains($day);
1802
1803 # |--- 0---|--- 10---|--- 20---|--- 30---|--- 40---|--- 50
1804 # |123456789|123456789|123456789|123456789|123456789|123456
1805 # 39 C 122 C 144 C 83 C 28 C 67 C 89 C ...
1806 my $daily = substr $data, $ii * 8, 8;
1807
1808 my $value = 0 + substr $daily, 0, 5;
1809 # my $mflag = substr $daily, 5, 1;
1810 my $qflag = substr $daily, 6, 1;
1811 # my $sflag = substr $daily, 7, 1;
1812
1813 $qflag =~ s{ \s+ \Z }{}xms;
1814
1815 my $key = sprintf '%04d%02d%02d', $year, $month, $day;
1816
1817 # keep track of all baseline days
1818 $baseline_days{$key}++
1819 if $need_baseline;
1820
1821 # skip over values that have quality flags
1822 if ( $qflag ne $EMPTY ) {
1823 $_flag_cnts_href->{$element}->{QFLAGS}->{$qflag}++;
1824 $_flag_cnts_href->{$element}->{REJECTED}++;
1825 $_daily_href->{$key}->{QFLAGS}->{$element}->{$qflag}++;
1826 next;
1827 }
1828
1829 # skip missing values
1830 next if $value == -9999;
1831
1832 $_flag_cnts_href->{$element}->{KEPT}++;
1833
1834 if ( $element =~ m{ \A ( TMAX | TMIN | TAVG | SNOW | SNWD | PRCP ) \Z }xms ) {
1835 # values are stored in 10th of a unit, so we divide by 10 to scale them to get:
1836 # - temperatures in °C
1837 # - PRCP in mm
1838 # - SNOW and SNWD in cm
1839 $_daily_href->{$key}->{$element} = $value / 10.0 if $value;
1840 $gaps{$year}->{$month} //= pack 'b30', 0;
1841 vec( $gaps{$year}->{$month}, $ii, 1) = 1;
1842 }
1843 }
1844 }
1845 close $stn_fh or croak '*E* unable to close';
1846
1847 $_tstats->stop('Load_daily_data');
1848
1849 # warn about missing years, months or days
1850 $self->_report_gaps( $stn, \%gaps );
1851
1852 my $insufficient_quality = 0;
1853
1854 # determine whether there's sufficient data within the -range, based on the -quality threshold
1855 if ( $Opt->range ) {
1856 my $day_count = keys $_daily_href->%*;
1857 $insufficient_quality += $self->_compute_quality( $stn, 'range', $day_count, $Opt->range, $Opt->quality );
1858 }
1859
1860 # determine whether there's sufficient data within the -baseline, based on the -quality threshold
1861 if ( $Opt->anomalies ) {
1862 my $day_count = keys %baseline_days;
1863 $insufficient_quality += $self->_compute_quality( $stn, 'baseline', $day_count, $Opt->baseline, $Opt->quality );
1864 }
1865
1866 $self->_compute_mean_and_counts( $stn );
1867
1868 if ($Opt->anomalies and $insufficient_quality == 0) {
1869 $self->_compute_baseline( $stn, $Opt->baseline );
1870 $self->_compute_anomalies();
1871 }
1872
1873 return $insufficient_quality;
1874 }
1875
1876 method _load_station_inventories () {
1877
1878 my $inv_content = $self->_fetch_url($GHCN_STN_INVEN_URL, $_cache, 'URI::Fetch_inv');
1879
1880 # Now scan the station inventory list, to get the active range for each station
1881 # - note there are multiple records, one for each element and active range combo
1882
1883 $_tstats->start('Parse_inv');
1884
1885 ## no critic [InputOutput::RequireBriefOpen]
1886 open my $inv_fh, '<', \$inv_content
1887 or croak '*E* unable to open inventory content';
1888
1889 while (my $inv = <$inv_fh>) {
1890 # |--- 0---|--- 10---|--- 20---|--- 30---|--- 40---
1891 # |123456789|123456789|123456789|123456789|123456789
1892 # (stationid)....................elem.from.(to)
1893 # ACW00011604 17.1167 -61.7833 TMAX 1949 1949
1894
1895 ## no critic [ProhibitMagicNumbers]
1896 my $id = substr $inv, 0, 11;
1897 # my $lat = substr $inc, 12, 8;
1898 # my $long = substr $inc, 21, 9;
1899 my $elem = substr $inv, 31, 4;
1900 my $firstyear = substr $inv, 36, 4;
1901 my $lastyear = substr $inv, 41, 4;
1902 ## use critic [ProhibitMagicNumbers]
1903
1904 # in case the inventory list contains a station id that isn't in
1905 # the station list, we'll skip it
1906 next if not exists $_station{$id};
1907
1908 next unless $elem =~ $_measures_obj->re;
1909
1910 my $stn = $_station{$id};
1911
1912 # combine the inventory active range set with the station active range
1913 $stn->active = rng_new( $stn->active, $firstyear . $DASH . $lastyear )->as_string();
1914
1915 $stn->elems_href->{$elem}++
1916 if $elem =~ $_measures_obj->re;
1917 }
1918 close $inv_fh or croak;
1919
1920 $_tstats->stop('Parse_inv');
1921
1922 my $count = $self->_filter_stations(\%_station);
1923
1924 return $count;
1925 }
1926
1927 # TODO: consider ways to let the caller decide on how to output the result
1928
1929 method _print_detail_data ($measure_begin_idx, $stn, $row_sub) {
1930
1931 return if not defined $row_sub;
1932
1933 $_tstats->start('Printing');
1934
1935 # build has of measure names and indices so measures can be
1936 # inserted into the correct columns
1937 my %measure_idx;
1938 my $ii = 0;
1939 foreach my $m ( $_measures_obj->measures ) {
1940 $measure_idx{$m} = $measure_begin_idx + $ii++;
1941 }
1942
1943 my $opt_range_nrs = rng_new($Opt->range);
1944
1945 # generate and print the data rows
1946 foreach my $key ( sort keys $_daily_href->%* ) {
1947 my ($year, $month, $day) = unpack 'A4 A2 A2', $key;
1948 my $flags = $EMPTY;
1949
1950 next unless ( $Opt->range ? $opt_range_nrs->contains($year) : $TRUE );
1951
1952 my $row = $_daily_href->{$key};
1953
1954 $flags = _qflags_as_string( $row->{QFLAGS} )
1955 if exists $row->{QFLAGS};
1956
1957 my @row;
1958 push @row, $year;
1959 push @row, $month;
1960 push @row, $day;
1961 push @row, int($year / 10) * 10; ## no critic [ProhibitMagicNumbers]
1962 push @row, _seasonal_decade($year, $month);
1963 push @row, _seasonal_year($year, $month);
1964 push @row, _seasonal_qtr($year, $month);
1965 foreach my $elem ( $_measures_obj->measures ) {
1966 $row[ $measure_idx{$elem} ] = sprintf '%.2f', $row->{$elem}
1967 if defined $row->{$elem};
1968 $row[ $measure_idx{$elem} ] //= $EMPTY;
1969 }
1970 push @row, $flags;
1971 push @row, $stn->id;
1972 push @row, $stn->name;
1973 push @row, $stn->idx;
1974 push @row, $stn->grid;
1975
1976 $row_sub->( \@row );
1977 }
1978
1979 $_tstats->stop('Printing');
1980
1981 return;
1982 }
1983
1984 method _report_gaps ($stn, $gaps_href) {
1985
1986 $_tstats->start('Report_gaps');
1987
1988 my @years = sort keys $gaps_href->%*;
1989
1990 if ( $Opt->active ) {
1991 my $active_nrs = rng_new( $Opt->active );
1992 my $years_nrs = rng_new( @years );
1993 my $gap_nrs = $active_nrs->diff( $years_nrs );
1994 if ($gap_nrs->cardinality) {
1995 my $msg = sprintf "%s\tmissing data in the active range\tyears %s", $stn->id, $gap_nrs->as_string;
1996 $stn->add_note($WARN_MISS_YA, $msg, $Opt->verbose);
1997 my $iter = $gap_nrs->iterate_runs();
1998 while (my ( $from, $to ) = $iter->()) {
1999 foreach my $yyyy ($from .. $to) {
2000 $missing_href->{$stn->id}{$yyyy}{$EMPTY}++;
2001 }
2002 }
2003 }
2004 }
2005
2006 my $opt_range_nrs = rng_new($Opt->range);
2007 my $opt_baseline_nrs = rng_new($Opt->baseline);
2008
2009 if ( $Opt->range ) {
2010 my $years_nrs = rng_new( @years );
2011 my $gap_nrs = $opt_range_nrs->diff( $years_nrs );
2012 if ($gap_nrs->cardinality) {
2013 my $msg = sprintf "%s\tmissing data in the filter range\tyears %s", $stn->id, $gap_nrs->as_string;
2014 $stn->add_note($WARN_MISS_YF, $msg, $Opt->verbose);
2015 my $iter = $gap_nrs->iterate_runs();
2016 while (my ( $from, $to ) = $iter->()) {
2017 foreach my $yyyy ($from .. $to) {
2018 $missing_href->{$stn->id}{$yyyy}{$EMPTY}++;
2019 }
2020 }
2021 }
2022 }
2023
2024 my ($this_yyyy, $this_mm) = _today();
2025
2026 foreach my $yyyy ( @years ) {
2027 # don't report gaps for years that aren't within -range (or -baseline if -anomalies)
2028 next if $Opt->range and
2029 ( $opt_range_nrs and not $opt_range_nrs->contains($yyyy)
2030 or
2031 $Opt->anomalies and not $opt_baseline_nrs->contains($yyyy) );
2032
2033 ## no critic [ProhibitMagicNumbers]
2034 my $end_month = $yyyy == $this_yyyy
2035 ? $this_mm
2036 : 12;
2037
2038 my $month_gap_nrs = $Opt->fmonth
2039 ? rng_new( $Opt->fmonth )
2040 : rng_new( 1 .. $end_month );
2041
2042 my @months = sort {$a<=>$b} keys $gaps_href->{$yyyy}->%*;
2043
2044 $month_gap_nrs->remove( @months );
2045
2046 if ($month_gap_nrs->cardinality) {
2047 my $gap_months = join $SPACE, _month_names($month_gap_nrs->as_array);
2048 my $msg = sprintf "%s\tmissing data: year %d months %s", $stn->id, $yyyy, $gap_months;
2049 $stn->add_note($WARN_MISS_MO, $msg, $Opt->verbose);
2050 $missing_href->{$stn->id}{$yyyy}{$gap_months}++;
2051 }
2052
2053 my $opt_fday_nrs = rng_new($Opt->fday);
2054 my $opt_fmonth_nrs = rng_new($Opt->fmonth);
2055
2056 ## no critic [ProhibitMagicNumbers]
2057 my $gap_text = $EMPTY;
2058 foreach my $mm ( 1 .. $end_month ) {
2059 # skip months that don't match -fmonth when -fmonth was given
2060 next if $Opt->fmonth and not $opt_fmonth_nrs->contains($mm);
2061
2062 my $day_vec = $gaps_href->{$yyyy}->{$mm};
2063
2064 next if not $day_vec;
2065
2066 my @days_with_data;
2067 my $mdays = _days_in_month($yyyy,$mm);
2068
2069 foreach my $day ( 1..31 ) {
2070 # skip days that don't match -fday when -fday was given
2071 next if $Opt->fday and not $opt_fday_nrs->contains($day);
2072
2073 next if $day > $mdays;
2074
2075 push @days_with_data, $day
2076 if vec($day_vec, $day - 1, 1) == 1;
2077 }
2078
2079 my $days_in_month_nrs = $Opt->fday
2080 ? $opt_fday_nrs
2081 : rng_new( 1 .. $mdays );
2082
2083 my $days_nrs = rng_new( @days_with_data );
2084
2085 my $day_gap_nrs = $days_in_month_nrs->diff($days_nrs);
2086
2087 $gap_text .= $SPACE . _month_names($mm) . '[' . $day_gap_nrs->as_string . ']'
2088 unless $day_gap_nrs->is_empty;
2089 }
2090
2091 if ( $gap_text !~ m{\A \s* \Z}xms ) {
2092 my $msg = sprintf "%s\tmissing data: %d days %s", $stn->id, $yyyy, $gap_text;
2093 $stn->add_note($WARN_MISS_DY, $msg, $Opt->verbose);
2094 $gap_text =~ s{\A \s+ }{}xms;
2095 $missing_href->{$stn->id}{$yyyy}{$gap_text}++;
2096 }
2097 }
2098
2099 $_tstats->stop('Report_gaps');
2100
2101 return;
2102 }
2103
2104 #----------------------------------------------------------------------
2105 # Configuration Helper functions
2106 #----------------------------------------------------------------------
2107
2108 sub _get_config_options ($config_file=$EMPTY) {
2109
2110 #debug# use DDP;
2111 #debug# use Log::Dispatch;
2112 #debug# my $log = Log::Dispatch->new(
2113 #debug# outputs => [
2114 #debug# [ 'File', min_level => 'debug', filename => 'c:/sandbox/log.log' ],
2115 #debug# [ 'Screen', min_level => 'debug' ],
2116 #debug#
2117 #debug# ]
2118 #debug# );
2119
2120 my $config_href = {};
2121
2122 # passing undef will result in an empty config
2123 return $config_href if not defined $config_file;
2124
2125 #debug# use FindBin;
2126 #debug# open my $fh, '>>', 'c:/sandbox/log.log' or die;
2127 #debug# $log->debug( 'program ' . $0 );
2128 #debug# $log->debug( 'caller ' . join(' | ', caller) );
2129 #debug# $log->debug( 'received config_file: ' . $config_file );
2130
2131 my $config_filespec = $config_file eq $EMPTY
2132 ? _get_default_config_filespec()
2133 : $config_file
2134 ;
2135
2136 my $yaml_struct;
2137 my $msg = $EMPTY;
2138
2139 # uncoverable branch false
2140 if (-e $config_filespec) {
2141 # uncoverable branch false
2142 try {
2143 $yaml_struct = YAML::Tiny->read($config_filespec);
2144 } catch {
2145 $msg = '*W* no cache or aliases: failed reading YAML in ' . $config_filespec;
2146 carp $msg;
2147 }
2148 } else {
2149 return $config_href;
2150 }
2151
2152 $config_href = $yaml_struct->[0]
2153 if $yaml_struct;
2154
2155 #debug# $log->( 'yaml_struct length = ' . length $yaml_struct );
2156 #debug# $log->( "\n" );
2157 #debug# $log->( 'config_filespec: ' . $config_filespec );
2158 #debug# $log->( 'carp ' . $msg );
2159 #debug# $log->( 'FindBin::Bin ' . $FindBin::Bin );
2160 #debug# $log->( "\n");
2161 #debug# $log->( 'config_href ' . np($config_href) );
2162 #debug# $log->( "\n" );
2163 #debug# $log->( "================" );
2164 #debug# $log->( "\n" );
2165 #debug# close $fh;
2166
2167 return $config_href;
2168 }
2169
2170 sub _get_default_config_filespec () {
2171
2172 # an EMPTY arg will default to $HOME/.ghcn_fetch.yaml
2173 my $config_file ||= $CONFIG_FILE;
2174
2175 my $homedir = File::HomeDir->my_home;
2176 #debug# say {$fh} 'homedir: ', $homedir;
2177
2178 my $config_filespec = File::Spec->canonpath($config_file);
2179 #debug# say {$fh} 'config_filespec (canon): ', $config_filespec;
2180
2181 $config_filespec =~ s{ \A \$HOME }{$homedir}xms;
2182 #debug# say {$fh} 'config_filespec (s/$HOME/): ', $config_filespec;
2183
2184 if ( not File::Spec->file_name_is_absolute($config_filespec) ) {
2185 $config_filespec = File::Spec->catfile( $homedir, $config_filespec );
2186 #debug# say {$fh} 'config_filespec wasnt absolute: ', $config_filespec;
2187 }
2188
2189 return $config_filespec;
2190 }
2191
2192 #----------------------------------------------------------------------
2193 # -kml Helper Functions
2194 #----------------------------------------------------------------------
2195
2196 # TODO: allow any KML hex colour code, format <opacity%><red><green><blue>
2197
2198 sub _get_kml_color ($color_opt) {
2199
2200 # From https://developers.google.com/kml/documentation/kmlreference#colorstyle
2201
2202 # Color and opacity (alpha) values are expressed in hexadecimal notation.
2203 # The range of values for any one color is 0 to 255 (00 to ff). For
2204 # alpha, 00 is fully transparent and ff is fully opaque. The order of
2205 # expression is aabbggrr, where:
2206 #
2207 # aa=alpha (00 to ff)
2208 # bb=blue (00 to ff)
2209 # gg=green (00 to ff)
2210 # rr=red (00 to ff).
2211 #
2212 # For example, if you want to apply a blue color with 50 percent opacity
2213 # to an overlay, you would specify the following:
2214 # <color>7fff0000</color>,
2215 # where alpha=0x7f, blue=0xff, green=0x00, and red=0x00.
2216
2217 my %kml_colors = (
2218 b => [ 'blue', 'ff780000' ],
2219 g => [ 'grn', 'ff147800' ],
2220 a => [ 'ltblu', 'ffF06414' ], # 'a' for azure
2221 p => [ 'purple','ff780078' ],
2222 r => [ 'red', 'ff1400FF' ],
2223 w => [ 'wht', 'ffFFFFFF' ],
2224 y => [ 'ylw', 'ff14F0FF' ],
2225 );
2226
2227 # just use the first character of whatever string we're given
2228 my $c = substr $color_opt, 0, 1;
2229
2230 return unless $kml_colors{$c};
2231
2232 return $kml_colors{$c}->[1];
2233 }
2234
2235 #----------------------------------------------------------------------
2236 # -location Helper Functions
2237 #----------------------------------------------------------------------
2238
2239 # Match -location <pattern> to the station id or name provided in the call.
2240 # If the pattern looks like a station id (e.g. 'CA006105887') then it matches
2241 # to the stn_id parameter; if it looks like a comma-separated list of station
2242 # id's, it returns success if any of them match the stn_id parameter. Otherwise,
2243 # it matches the <pattern> to the start of the stn_name parameter.
2244 sub _match_location ($stn_id, $stn_name, $pattern) {
2245
2246 my $result = $FALSE;
2247
2248 if ($pattern =~ m{ \A $STN_ID_RE \Z }xms) {
2249 $result = $stn_id eq $pattern;
2250 }
2251 elsif ($pattern =~ m{ \A $STN_ID_RE ( [,] $STN_ID_RE )+ \Z }xms) {
2252 my @patterns = split m{ [,] }xms, $pattern;
2253 my $multi_pattern = '\A(' . join(q(|), @patterns) . ')\Z';
2254
2255 $result = $stn_id =~ $multi_pattern;
2256 }
2257 else {
2258 ## no critic [RequireExtendedFormatting]
2259 $result = $stn_name =~ m{\A$pattern}msi;
2260 }
2261
2262 return $result;
2263 }
2264
2265 #----------------------------------------------------------------------
2266 # -nogaps Helper Functions
2267 #----------------------------------------------------------------------
2268
2269 # parse the missing values text, which looks like this:
2270 # month names: Jan Feb Mar Apr May Jun Jul Aug Sep Oct
2271 # or day ranges: May[2] Oct[3,11] Nov[1] Dec[2,5]
2272
2273 sub _parse_missing_text ( $s ) {
2274 my @months;
2275 my @mmdd;
2276 my @f = split m{ \s }xms, $s;
2277
2278 my $mmm_re = qr{ [A-Z][a-z][a-z] }xms;
2279 my $nbr_rng = qr{ \d+ ( [-] \d+)? }xms;
2280 my $rng_list = qr{ $nbr_rng (, $nbr_rng)* }xms;
2281
2282 foreach my $tok (@f) {
2283 if ( $tok =~ m{ \A $mmm_re \Z }xms ) {
2284 push @months, $MMM_TO_MM{$tok};
2285 }
2286 if ( $tok =~ m{ \A ($mmm_re) \[ ($rng_list) \] \Z }xms ) {
2287 my $mm = $MMM_TO_MM{$1};
2288 my @days = rng_new($2)->as_array;
2289 foreach my $day (@days) {
2290 push @mmdd, [$mm, $day];
2291 }
2292 }
2293 }
2294 return \@months, \@mmdd;
2295 }
2296
2297 #----------------------------------------------------------------------
2298 # Misc Functions
2299 #----------------------------------------------------------------------
2300
2301 # format qflags like this: I:1, N:9, S:4
2302 sub _qflags_as_string ( $qflags_href ) {
2303 return $EMPTY if not $qflags_href;
2304
2305 my @r;
2306 foreach my $qflag ( sort keys $qflags_href->%* ) {
2307 push @r, sprintf '%s:%d', $qflag, $qflags_href->{$qflag};
2308 }
2309
2310 return join ', ', @r;
2311 }
2312 #----------------------------------------------------------------------
2313 # Undef-safe Functions
2314 #----------------------------------------------------------------------
2315
2316 # defined max - return the maximum of the two arguments,
2317 # or the defined argument if one of the arguments is undef
2318 sub _dmax ($x, $y) {
2319
2320 return if not defined $x and not defined $y;
2321 return $y if not defined $x;
2322 return $x if not defined $y;
2323
2324 return $x > $y ? $x : $y;
2325 }
2326
2327 # defined min - return the minimum of the two arguments,
2328 # or the defined argument if one of the arguments is undef
2329 sub _dmin ($x, $y) {
2330
2331 return if not defined $x and not defined $y;
2332 return $y if not defined $x;
2333 return $x if not defined $y;
2334
2335 return $x < $y ? $x : $y;
2336 }
2337
2338 # defined sum - return the sum of the two arguments,
2339 # or the defined argument if one of the arguments is undef
2340 sub _dsum ($x, $y) {
2341
2342 return if not defined $x and not defined $y;
2343 return $y if not defined $x;
2344 return $x if not defined $y;
2345
2346 return $x + $y;
2347 }
2348
2349 # defined count - increment the value of the first argument by 1,
2350 # or return it unchanged if the second argument is undef
2351 sub _dcount ($x, $y) {
2352
2353 return $x if not defined $y;
2354
2355 return defined $x ? $x + 1 : 1;
2356 }
2357
2358 # defined divide - returns undef if either argument is undef
2359 # or if the denominator is zero
2360 sub _ddivide ($x, $y) {
2361
2362 return if not defined $x;
2363 return if not defined $y;
2364 return if not $y;
2365
2366 return $x / $y;
2367 }
2368
2369 #----------------------------------------------------------------------
2370 # Date and Time Helper Functions
2371 #----------------------------------------------------------------------
2372
2373 sub _days_in_month ($year, $month) {
2374
2375 # coerce to numbers
2376 $year += 0;
2377 $month += 0;
2378
2379 ## no critic [ProhibitMagicNumbers]
2380 my @mdays = (0, 31,28,31,30,31,30,31,31,30,31,30,31);
2381
2382 if ($month == 2) {
2383 return $mdays[$month] + _is_leap_year($year);
2384 }
2385
2386 return $mdays[$month];
2387 }
2388
2389 sub _days_in_year ($year) {
2390
2391 $year += 0; # coerce to number
2392
2393 ## no critic [ProhibitMagicNumbers]
2394 return 365 + _is_leap_year($year);
2395 }
2396
2397 sub _is_leap_year ($year) {
2398
2399 $year += 0; # coerce to number
2400
2401 ## no critic [ProhibitMagicNumbers]
2402 return 0 if $year % 4;
2403 return 1 if $year % 100;
2404 return 0 if $year % 400;
2405 return 1;
2406 }
2407
2408 sub _month_names (@mm) {
2409
2410 my @mnames = qw(xxx Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
2411
2412 my @result = ();
2413 return (@result) unless @mm;
2414
2415 ## no critic [ProhibitMagicNumbers]
2416 foreach my $mm (@mm) {
2417 if ($mm !~ m{ \A \d\d? \Z }xms) {
2418 push @result, '???';
2419 }
2420 elsif ($mm > 0 and $mm < 13) {
2421 push @result, $mnames[$mm];
2422 }
2423 else {
2424 push @result, '???';
2425 }
2426 }
2427
2428 return wantarray ? @result : shift @result;
2429 }
2430
2431 sub _now () {
2432
2433 my @_now = localtime time;
2434
2435 return wantarray
2436 ? iso_date_time(@_now)
2437 : scalar iso_date_time(@_now)
2438 ;
2439 }
2440
2441 sub _today () {
2442
2443 my @ymdhms = _now();
2444
2445 return wantarray
2446 ? @ymdhms[0..2]
2447 : sprintf '%4d-%02d-%02d', @ymdhms[0..2];
2448 }
2449
2450 # Seasonal decades are based on seasonal years.
2451 # However, decades are deemed to begin when the seasonal
2452 # year ends in 9. For example, seasonal decade 2010 begins
2453 # Dec 1 2009 and continues through Nov 30, 2019.
2454 sub _seasonal_decade ($year, $month) {
2455 ## no critic [ProhibitMagicNumbers]
2456 $year += 1 if $month == 12;
2457 return int($year / 10) * 10;
2458 }
2459
2460 # Seasonal quarter Q1 begins Dec 1 and ends Feb 28/29
2461 # For example, 2017 Q1 includes Dec 2017, Jan 2018 and Feb 2018.
2462 sub _seasonal_qtr ($year, $month) {
2463 my @seasonal_quarter = qw( Q0 Q1 Q1 Q2 Q2 Q2 Q3 Q3 Q3 Q4 Q4 Q4 Q1 );
2464
2465 return $seasonal_quarter[$month];
2466 }
2467
2468 # Seasonal years begin Dec 1 and continue through end of November
2469 # the following year. For example, Dec 15 2017 is in Q1 2017;
2470 # Jan 15 2018 is in Q1 2017 (not 2018!!!); Nov 15 2018 is in Q4 2017.
2471 # This is consistent with definition used by weatherstats.ca.
2472 sub _seasonal_year ($year, $month) {
2473 ## no critic [ProhibitMagicNumbers]
2474 $year -= 1 unless $month == 12;
2475 return $year;
2476 }
2477
2478 #----------------------------------------------------------------------
2479 # Performance Helper Functions
2480 #----------------------------------------------------------------------
2481
2482 # calculate the total size of a hash or other structure
2483 sub _memsize ( $ref, $opt_performance ) {
2484 return $EMPTY unless $opt_performance;
2485 return sprintf ' [%s]', commify( Devel::Size::total_size( $ref ) );
2486 }
2487
2488 =head1 EXAMPLE PROGRAM
2489
2490 use Weather::GHCN::StationTable;
2491
2492 my $ghcn = Weather::GHCN::StationTable->new;
2493
2494 my ($opt, @errors) = $ghcn->set_options(
2495 user_options => {
2496 country => 'US',
2497 state => 'NY',
2498 location => 'New York',
2499 active => '2000-2022',
2500 report => 'yearly',
2501 nonetwork => -1, # refresh cache if stale this year
2502 },
2503 config_options => {
2504 cache => {
2505 root => 'c:/ghcn_cache',
2506 namespace => 'ghcn',
2507 },
2508 },
2509 );
2510
2511 die @errors if @errors;
2512
2513 $ghcn->load_stations;
2514
2515 my @rows;
2516 if ($opt->report) {
2517 say $ghcn->get_header;
2518
2519 # this also prints detailed station data if $opt->report eq 'id'
2520 $ghcn->load_data(
2521 # set a callback routine for printing progress messages
2522 progress_sub => sub { say {*STDERR} @_ },
2523 # set a callback routine for capturing data rows when report => 'id'
2524 row_sub => sub { push @rows, $_[0] },
2525 );
2526
2527 # these only do something when $opt->report ne 'id'
2528 $ghcn->summarize_data;
2529 say $ghcn->get_summary_data;
2530
2531 say '';
2532 say $ghcn->get_footer;
2533
2534 say '';
2535 say $ghcn->get_flag_statistics;
2536 }
2537
2538 # print data rows collected by row_sub callback (when report => 'id')
2539 foreach my $row_aref (@rows) {
2540 say join "\t", $row_aref->@*;
2541 }
2542
2543 say '';
2544 say $ghcn->get_stations( kept => 1 );
2545
2546 say '';
2547 say 'Stations that failed to meet range or quality criteria:';
2548 say $ghcn->get_stations( kept => 0, no_header => 1 );
2549
2550 if ( $ghcn->has_missing_data ) {
2551 warn '*W* some data was missing for the stations and date range processed' . $NL;
2552 say '';
2553 say $ghcn->get_missing_data_ranges;
2554 }
2555
2556 say $ghcn->get_options;
2557
2558 say $ghcn->get_timing_stats;
2559
2560 say $ghcn->get_hash_stats;
2561
2562 $ghcn->export_kml if $opt->kml;
2563
2564 =head1 CONFIGURATION OPTIONS
2565
2566 StationTable supports two kinds of options: user and configuration.
2567 The main difference between the two is that configuration options
2568 are more suited to persistence; i.e. you'll most likely put them
2569 in a file that is used at every execution of StationTable.
2570
2571 =head2 Cache
2572
2573 Cache options are used internally by StationTable when it calls
2574 URI::Fetch to get pages of data from the GHCN web respository.
2575
2576 =over 4
2577
2578 =item root
2579
2580 This defines a path to a folder which will be used to cache web
2581 pages. See the nonetwork user option for ways to control caching.
2582
2583 =item namespace
2584
2585 This defines the subfolder of root within which the cache files will
2586 reside.
2587
2588 =back
2589
2590 =head2 Aliases
2591
2592 Aliases are a convenience feature that allow you to define mnemonic
2593 shortcuts for specific stations. GHCN station id's (like CA006106000)
2594 are difficult to remember and type, as can GHCN station names.
2595 Frequently-used station id's can be given easier alias names that
2596 can be use in the -location option for precise and reliable data
2597 retrieval.
2598
2599 The entries within the aliases hash are simply keyword/value pairs
2600 that represent the mnemonic alias name and the station id (or id's)
2601 that are to be retrieved when that alias is used in -location.
2602
2603 =head2 YAML Example
2604
2605 This is what the YAML content for a typical configuation file would
2606 look like:
2607
2608 ---
2609 cache:
2610 root: C:/ghcn_cache_new
2611 namespace: ghcn_new
2612
2613 aliases:
2614 yow: CA006106000,CA006106001 # Ottawa airport
2615 cda: CA006105976,CA006105978 # Ottawa (CDA and CDA RCS)
2616
2617 =head2 Hash Example
2618
2619 Here's what the typical config file would look like as a perl hash
2620 structure:
2621
2622 config_options => {
2623 cache => {
2624 root => 'C:/ghcn_cache_new',
2625 namespace => 'ghcn_new',
2626 }
2627 aliases => {
2628 yow => 'CA006106000,CA006106001', # Ottawa airport
2629 cda => 'CA006105976,CA006105978', # Ottawa (CDA and CDA RCS)
2630 }
2631 }
2632
2633 =head1 USER OPTIONS
2634
2635 See B<ghcn_fetch.pl -help> for a list of all user options in Getopts::Long
2636 format. Simply translate to a hash key/value pair. For example,
2637 B<-report id> becomes B<report => 'id'>.
2638
2639 =head1 VERSIONING and COMPATIBILITY
2640
2641 The version number scheme used for this module consists of a 3-part
2642 dot-delimited string such as v0.22.365. This format was chosen for
2643 compatibility with Dist::Zilla version support, so that all modules
2644 in GHCN will get the same version number upon release. See also
2645 L<https://metacpan.org/pod/version>.
2646
2647 The first digit of the string is a major release numbers. With the
2648 exception of v0 release, which should be considered experimental
2649 pre-production versions, the interface is intended to be upward
2650 compatible within a set of releases sharing the same major release
2651 number. If an incompatible change becomes necessary, the major
2652 release number will be incremented.
2653
2654 The other two strings are essentially the date of the release, in
2655 the format YY.DDD where YY is the year of the century and DDD is the
2656 day number within the year.
2657
2658 =head1 AUTHOR
2659
2660 Gary Puckering (jgpuckering@rogers.com)
2661
2662 =head1 LICENSE AND COPYRIGHT
2663
2664 Copyright 2022, Gary Puckering
2665
2666 =cut
2667
2668 1;