blib/lib/Weather/GHCN/App/Fetch.pm untested

filter: Statementstmt 0.0% 0 / 220 Branchbran 0.0% 0 / 74 Conditioncond 0.0% 0 / 44 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 6 totaltotal 0.0% 0 / 365 CC 36 SCAR 60.3
CC
36
Cov
0%
run
812.0
get_user_options_tk
72.0
get_user_options
6.0
CRAP 417.1
1 # Weather::GHCN::Fetch.pm - class for creating applications that fetch NOAA GHCN data
2
3 =head1 NAME
4
5 Weather::GHCN::App::Fetch - Fetch station and weather data from the NOAA GHCN repository
6  
7 =head1 VERSION
8  
9 version v0.0.003
10
11 =head1 SYNOPSIS
12
13 use Weather::GHCN::App::Fetch;
14
15 Weather::GHCN::App::Fetch->run( \@ARGV );
16
17 See ghcn_fetch.pl -help for details.
18
19 =cut
20
21 # Testing notes:
22 #
23 # The quickest way to spot check results from this script is to compare them
24 # to those obtained from:
25 #
26 # https://ottawa.weatherstats.ca/charts/
27 #
28 # Run the script with parameters such as -prov ON -loc "Ottawa Int" -range
29 # 2017-2018 -precip -tavg -o first with the -daily option, then again with
30 # -monthly and -yearly. You can then compare results to various charts you
31 # generate using the above link by selecting Ottawa (Kanata - Orleans),
32 # which I've verified corresponds to station CA006105976 (Ottawa Int'l).
33 #
34 # Charts to use include Temperature (TMAX, TMIN, TAVG, Avg), Snowfall
35 # (SNOW), Snow on Ground (SNWD) and Total Precipitation (PRCP). Annual and
36 # monthly charts work well, but you may need daily charts and some
37 # investigation of the NOAA source data if there are anomalies. Sometimes
38 # the NOAA data has missing data; e.g. station CA006105976 (Ottawa Int'l)
39 # is missing days 6-28 for 2018-02.
40
41 ########################################################################
42 # Pragmas
43 ########################################################################
44 use v5.18; # minimum for Object::Pad
45
46 package Weather::GHCN::App::Fetch;
47
48 our $VERSION = 'v0.0.003';
49
50 use feature 'signatures';
51 no warnings 'experimental::signatures';
52
53 ########################################################################
54 # Export
55 ########################################################################
56
57 require Exporter;
58
59 use base 'Exporter';
60
61 our @EXPORT = ( 'run' );
62
63 ########################################################################
64 # perlcritic rules
65 ########################################################################
66
67 ## no critic [ErrorHandling::RequireCarping]
68 ## no critic [InputOutput::RequireBriefOpen]
69 ## no critic [ProhibitSubroutinePrototypes]
70
71 # due to subroutine signatures, perlcritic can't seem to handle disabling
72 # the following warnings on the subs where they occur
73 ## no critic [Subroutines::ProhibitExcessComplexity]
74
75 # due to use of postfix dereferencing, we have to disable these warnings
76 ## no critic [References::ProhibitDoubleSigils]
77
78 ########################################################################
79 # Libraries and Features
80 ########################################################################
81 use Object::Pad 0.66 qw( :experimental(init_expr) );
82
83 use Getopt::Long;
84 use Pod::Usage;
85 use Const::Fast;
86 use English qw( -no_match_vars );
87
88 # cpan modules
89 use Text::Abbrev;
90
91 # modules for Windows only
92 use if $^O eq 'MSWin32', 'Win32::Clipboard';
93
94 # conditional modules
95 use Module::Load::Conditional qw( can_load check_install requires );
96
97 # custom modules
98 use Weather::GHCN::Common qw( :all );
99 use Weather::GHCN::StationTable;
100
101 ########################################################################
102 # Global delarations
103 ########################################################################
104
105 # is it ok to use Tk?
106 our $TK_MODULES = {
107 'Tk' => undef,
108 'Tk::Getopt' => undef,
109 };
110
111 # is it ok to use Win32::Clipboard?
112 our $USE_WINCLIP = $^O eq 'MSWin32';
113 our $USE_TK = can_load( modules => $TK_MODULES );
114
115 my $Opt; # options object, with property accessors for each user option
116
117 # options that relate to script execution, not GHCN processing and output
118 my $Opt_file; # file in which to save options from GUI dialog
119 my $Opt_gui; # launch the GUI dialog
120 my $Opt_help; # display POD documentation
121 my $Opt_readme; # launch a browser displaying the GHCN readme file
122 my $Opt_usage; # display a synopsis of the command line syntax
123 my $Opt_outclip; # send report output to the Windows clipboard instead of STDOUT
124
125 ########################################################################
126 # Constants
127 ########################################################################
128
129 const my $EMPTY => q(); # empty string
130 const my $SPACE => q( ); # space character
131 const my $DASH => q(-); # dash character
132 const my $TAB => qq(\t); # tab character
133 const my $NL => qq(\n); # perl universal newline (any platform)
134 const my $TRUE => 1; # perl's usual TRUE
135 const my $FALSE => not $TRUE; # a dual-var consisting of '' and 0
136
137 const my $CONFIG_FILE => '$HOME/.ghcn_fetch.yaml';
138
139 const my $STN_THRESHOLD => 100; # ask if number of selected stations exceeds this
140
141 const my $STN_ID_RE => qr{ [[:upper:]]{2} [[:alnum:]\_\-]{9} }xms;
142
143 ########################################################################
144 # Script Mainline
145 ########################################################################
146
147 __PACKAGE__->run( \@ARGV ) unless caller;
148
149 =head1 SUBROUTINES
150
151 =head2 run ( \@ARGV )
152
153 Invoke this subroutine, passing in a reference to @ARGV, in order to
154 fetch NOAA GHCN station data or daily weather data.
155
156 See ghnc_fetch.pl -help for details.
157
158 =cut
159
160 sub run ($progname, $argv_aref) {
161
162 local @ARGV = $argv_aref->@*;
163
164 warn "*W* -gui option unavailable -- try installing Tk and Tk::GetOptions"
165 if not $USE_TK;
166
167 my $ghcn = Weather::GHCN::StationTable->new;
168
169 $ghcn->tstats->start('_Overall');
170
171 Getopt::Long::Configure ('pass_through');
172
173 # If the first command line argument is a report_type, remove and save it
174 my $report_type;
175 if (@ARGV > 0 and $ARGV[0] =~ m{ \A [^-][[:alpha:]]+ \b }xms ) {
176 my $rt_arg = shift @ARGV;
177 my $rt = deabbrev_report_type( $rt_arg );
178 $report_type = $rt // $rt_arg;
179 }
180
181 # The -optfile option, which is preprocessed by GetOptions before
182 # we call Tk::Getopt, has an overlapping abbreviation with -outclip.
183 # To avoid GetOptions from stripping -o from @ARGV, we disambiguate
184 # -o by changing it to -outclip. This means that -optfile can
185 # only by abbreviated down to -op.
186 # Note: normally we shouldn't be changing @ARGV but in this case
187 # we do want to.
188
189 ## no critic [ProhibitCStyleForLoops]
190 ## no critic [RequireLocalizedPunctuationVars]
191 for (my $ii=0; $ii < @ARGV; $ii++) {
192 $ARGV[$ii] = '-outclip'
193 if $ARGV[$ii] eq '-o' and
194 ($ii == $#ARGV) # a lone -o at the end
195 or # a -o followed by an option
196 ($ii < $#ARGV - 1 and
197 $ARGV[$ii+1] =~ m{ /A [-]}xms);
198 }
199
200 # record the number of command line arguments before they are removed by GetOptions
201 my $argv_count = @ARGV;
202
203 my %script_args = (
204 'help' => \$Opt_help,
205 'usage|?' => \$Opt_usage,
206 'optfile:s' => \$Opt_file,
207 'readme' => \$Opt_readme,
208 );
209
210 $script_args{'gui'} = \$Opt_gui
211 if $USE_TK;
212
213 $script_args{'outclip|o'} = \$Opt_outclip
214 if $USE_WINCLIP;
215
216 GetOptions( %script_args );
217
218 if ( $Opt_help ) {
219 pod2usage(-verbose => 2);
220 exit;
221 }
222
223 if ( $Opt_usage ) {
224 pod2usage(1);
225 exit;
226 }
227
228 # launch the default browser with the NOAA Daily readme.txt file content
229 if ( $Opt_readme ) {
230 system 'start https://www1.ncdc.noaa.gov/pub/data/ghcn/daily/readme.txt';
231 exit;
232 }
233
234 # default to -gui if no command line arguments were provided and
235 # we aren't taking input from a pipe or file
236 $Opt_gui = 1 if $USE_TK and $argv_count == 0 and -t *STDIN;
237
238 my $user_opt_href = get_user_options($Opt_file);
239
240 $user_opt_href->{report} = $report_type
241 if $report_type;
242
243 my $config_file = $user_opt_href->{config} // $CONFIG_FILE;
244
245 die '*E* unrecognized options: ' . join $SPACE, @ARGV
246 if @ARGV;
247
248 my %stnid_filter;
249
250 my @errors;
251 ($Opt, @errors) = $ghcn->set_options(
252 user_options => $user_opt_href,
253 config_file => $config_file,
254 stnid_filter => \%stnid_filter,
255 );
256
257 die join qq(\n), @errors, qq(\n)
258 if @errors;
259
260 my ( $output, $new_fh, $old_fh );
261 if ( $Opt_outclip and $USE_WINCLIP ) {
262 open $new_fh, '>', \$output
263 or die 'Unable to open buffer for write';
264 $old_fh = select $new_fh; ## no critic (ProhibitOneArgSelect)
265 }
266
267 # get a list of station id's from stdin if it's a pipe or file
268 # (but not if stdin is pointing to the terminal)
269 if ( -p *STDIN || -f *STDIN ) {
270 my $ii;
271 while (<STDIN>) {
272 chomp;
273 my @id_list = $_ =~ m{ $STN_ID_RE }xmsg;
274 foreach my $id ( @id_list ) {
275 $stnid_filter{$id}++;
276 $ii++;
277 }
278 }
279 die "*E* no station id's found in the input"
280 unless $ii;
281 }
282
283 $ghcn->load_stations;
284
285 say {*STDERR} '*I* ', $ghcn->stn_count, ' stations found';
286 say {*STDERR} '*I* ', $ghcn->stn_selected_count, ' stations match location and GSN options';
287 say {*STDERR} '*I* ', $ghcn->stn_filtered_count, ' stations matched range and measurement options';
288
289 if ($ghcn->stn_filtered_count > $STN_THRESHOLD ) {
290 print {*STDERR} ">>>> There are a lot of stations to process. Continue (y/n)?\n>>>> ";
291 my $reply = <>;
292 chomp $reply;
293 exit if $reply =~ m{ \A ( n | no ) }xmsi;
294 }
295
296 if ($Opt->report) {
297 say $ghcn->get_header;
298
299 # this prints detailed station data if $Opt->report eq 'id'
300 $ghcn->load_data(
301 # set a callback routine for printing progress messages
302 progress_sub => sub { say {*STDERR} @_ },
303 # set a callback routine for printing rows when -report id
304 row_sub => sub { say join "\t", @{ $_[0] } },
305 );
306
307 if ($Opt->report eq 'id' and $Opt->nogaps) {
308 say $ghcn->get_missing_rows;
309 }
310
311 # these only do something when $Opt->report ne 'id'
312 $ghcn->summarize_data;
313 say $ghcn->get_summary_data;
314 say $EMPTY;
315
316 goto WRAP_UP if $Opt->dataonly;
317
318 say $EMPTY;
319 say $ghcn->get_footer;
320
321 say $EMPTY;
322 say $ghcn->get_flag_statistics;
323 }
324
325 if ( $Opt->defined('kml') ) {
326 if ($Opt->kml eq $EMPTY) {
327 say $ghcn->export_kml;
328 goto WRAP_UP;
329 } else {
330 $ghcn->export_kml;
331 }
332 }
333
334 say $EMPTY;
335 say $ghcn->get_stations( kept => 1 );
336
337 my @rejected = $ghcn->get_stations( list => 1, kept => 0, no_header => 1 );
338 if (@rejected) {
339 say $EMPTY;
340 say 'Stations that failed to meet range or quality criteria:';
341 say tsv(\@rejected);
342 }
343
344 if ( $ghcn->has_missing_data ) {
345 warn '*W* some data was missing for the stations and date range processed' . $NL;
346 say $EMPTY;
347 say $ghcn->get_missing_data_ranges;
348 }
349
350 $ghcn->tstats->stop('_Overall') ;
351 $ghcn->tstats->finish;
352
353 say $EMPTY;
354 say $ghcn->get_options;
355
356 say $EMPTY;
357 say 'Script:';
358 say $TAB, $PROGRAM_NAME;
359 say "\tWeather::GHCN::StationTable version " . $Weather::GHCN::StationTable::VERSION;
360 say $TAB, 'Config file: ' . $ghcn->config_file;
361
362 if ( $Opt->performance ) {
363 say $EMPTY;
364 say sprintf 'Timing statistics (ms)%s:', $Opt->performance ? ' and memory [bytes]' : $EMPTY;
365 say $ghcn->get_timing_stats;
366
367 say $EMPTY;
368 say $ghcn->get_hash_stats;
369 }
370
371 WRAP_UP:
372 # send output to the Windows clipboard
373 if ( $Opt_outclip and $USE_WINCLIP ) {
374 Win32::Clipboard->new()->Set( $output );
375 select $old_fh;
376 }
377
378 return;
379 }
380
381 ########################################################################
382 # Subroutines
383 ########################################################################
384
385 =head2 get_user_options ( $optfile=undef )
386
387 Fetch.pm uses B<get_user_options()> to either get user options
388 via B<Tk::GetOptions> -- if it is installed -- or via B<Getopt::Long>.
389
390 =cut
391
392 sub get_user_options ( $optfile=undef ) {
393
394 my $user_opt_href = $USE_TK
395 ? get_user_options_tk($optfile)
396 : get_user_options_no_tk($optfile)
397 ;
398
399 return $user_opt_href;
400 }
401
402 =head2 get_user_options_no_tk ( $optfile=undef )
403
404 This function obtains user options from @ARGV by calling B<Getopt::Long>
405 B<GetOptions> using a list of option definitions obtained by calling
406 B<Weather::GHCN::Options->get_getopt_list()>. The options (and their values)
407 are extracted from @ARGV and put in a hash, a reference to which is
408 then returned.
409
410 The $optfile argument is only used by B<get_user_options_no_tk>.
411
412 =cut
413
414 sub get_user_options_no_tk ( $optfile=undef ) {
415
416 my @options = ( Weather::GHCN::Options->get_getopt_list() );
417
418 my %opt;
419 GetOptions( \%opt, @options);
420
421 return \%opt;
422 }
423
424 =head2 get_user_options_tk ( $optfile=undef )
425
426 This function returns a reference to a hash of user options obtained
427 by calling B<Tk::Getopt>. This may launch a GUI dialog to collect
428 the options.
429
430 The optional $optfile argument specifies a filename which
431 B<Tk::GetOptions> can use to store or load options.
432
433 =cut
434
435 sub get_user_options_tk ( $optfile=undef ) {
436
437 if (not $USE_TK) {
438 warn "*E* Tk or Tk::Getopt not installed";
439 return;
440 }
441
442 my %opt;
443
444 ## no critic [ProhibitNoisyQuotes]
445 my @opttable = ( Weather::GHCN::Options->get_tk_options_table() );
446
447 my $optobj = Tk::Getopt->new(
448 -opttable => \@opttable,
449 -options => \%opt,
450 -filename => $optfile);
451
452 $optobj->set_defaults; # set default values
453
454 $optobj->load_options # configuration file
455 if defined $optfile and -e $optfile;
456
457 $optobj->get_options; # command line
458
459 # Because Tk::Getopt doesn't support option abbreviations for choice
460 # lists -- there's no need for the gui since choices are provided in a
461 # drop list -- we run into a problem when using Tk:Getopt without the
462 # gui. In that case, an abbrevation for a -report option will be caught
463 # during process_options call (just below), before our call to
464 # TableStation::set_options can expand the abbrevation by calling
465 # Options::validate. So, for the sake of this
466 # script we do an abbrevation substition right here, and then call our own
467 # validate_report_type sub which gets the valid report types from the
468 # options table. We do our own error report too, because Tk::Getopt
469 # reports choices as a list of ARRAY(<address>) rather than as values.
470
471 if ( $optobj->{options}->{report} ) {
472 my %report_abbrev = abbrev( qw(id daily monthly yearly) );
473 my $rt = deabbrev_report_type( $optobj->{options}->{report} );
474 $optobj->{options}->{report} = $rt
475 if $rt;
476 }
477 die '*E* invalid report option: ' . $optobj->{options}->{report} . "\n"
478 unless valid_report_type( $optobj->{options}->{report}, \@opttable );
479
480 $optobj->process_options; # process callbacks, check restrictions ...
481
482 if ($Opt_gui) {
483 my $top = MainWindow->new;
484 $top->geometry('500x300+300+200');
485 $top->title('GHCN Daily Parser');
486
487 my $retval = $optobj->option_dialog(
488 $top,
489 -toplevel => 'Frame',
490 -buttons => [qw/ok cancel save/], # not using cancel apply undo save defaults
491 -statusbar => 1,
492 -wait => 1,
493 -pack => [-fill => 'both', -expand => 1],
494 );
495
496 die "*I* action cancelled\n" if $retval and $retval eq 'cancel';
497 }
498
499 return \%opt;
500 }
501
502 =head2 valid_report_type ($rt, \@opttable)
503
504 This function is used to valid the report type. Valid values are
505 defined in the built-in Tk options table, which can be obtained by
506 calling:
507
508 my @opttable = ( Weather::GHCN::Options->get_tk_options_table() );
509
510 =cut
511
512 sub valid_report_type ($rt, $opttable_aref) {
513 my $choices_href = Weather::GHCN::Options->get_option_choices;
514 return $choices_href->{'report'}->{$rt};
515 }
516
517 =head2 deabbrev_report_type ($rt)
518
519 The report types supported by the -report option can be abbrevated,
520 so long as the abbrevation is unambiquous. For example, 'daily' can
521 be abbreviated to 'dail', 'dai', 'da', or even 'd'.
522
523 This function takes a (possibly abbreviated) report type and returns
524 an unabbreviated report type.
525
526 =cut
527
528 sub deabbrev_report_type ($rt) {
529 my %r_abbrev = abbrev( qw(id daily monthly yearly) );
530 my $deabbreved = $r_abbrev{ $rt };
531 return $deabbreved;
532 }
533
534 =head1 AUTHOR
535
536 Gary Puckering (jgpuckering@rogers.com)
537
538 =head1 LICENSE AND COPYRIGHT
539
540 Copyright 2022, Gary Puckering
541
542 =cut
543
544 1;