| 1 | # Weather::GHCN::Extremes.pm - analyze of extremes from Weather::GHCN::Fetch.pm output | ||
| 2 | |||
| 3 | =head1 NAME | ||
| 4 | |||
| 5 | Weather::GHCN::App::Extremes - Report temperature extremes from Weather::GHCN::Fetch output | ||
| 6 | |||
| 7 | =head1 VERSION | ||
| 8 | |||
| 9 | version v0.0.003 | ||
| 10 | |||
| 11 | =head1 SYNOPSIS | ||
| 12 | |||
| 13 | use Weather::GHCN::App::Extremes; | ||
| 14 | |||
| 15 | Weather::GHCN::App::Extremes->run( \@ARGV ); | ||
| 16 | |||
| 17 | See ghcn_extremes -help for details. | ||
| 18 | |||
| 19 | =cut | ||
| 20 | |||
| 21 | ######################################################################## | ||
| 22 | # Pragmas | ||
| 23 | ######################################################################## | ||
| 24 | use v5.18; | ||
| 25 | |||
| 26 | package Weather::GHCN::App::Extremes; | ||
| 27 | |||
| 28 | our $VERSION = 'v0.0.003'; | ||
| 29 | |||
| 30 | use feature 'signatures'; | ||
| 31 | no warnings 'experimental::signatures'; | ||
| 32 | |||
| 33 | ######################################################################## | ||
| 34 | # Export | ||
| 35 | ######################################################################## | ||
| 36 | |||
| 37 | require Exporter; | ||
| 38 | |||
| 39 | use base 'Exporter'; | ||
| 40 | |||
| 41 | our @EXPORT = ( 'run' ); | ||
| 42 | |||
| 43 | ######################################################################## | ||
| 44 | # perlcritic rules | ||
| 45 | ######################################################################## | ||
| 46 | |||
| 47 | ## no critic [Subroutines::ProhibitSubroutinePrototypes] | ||
| 48 | ## no critic [References::ProhibitDoubleSigils]; | ||
| 49 | ## no critic [ErrorHandling::RequireCarping] | ||
| 50 | |||
| 51 | ######################################################################## | ||
| 52 | # Libraries | ||
| 53 | ######################################################################## | ||
| 54 | use Getopt::Long qw( GetOptionsFromArray ); | ||
| 55 | use Pod::Usage; | ||
| 56 | use Const::Fast; | ||
| 57 | use Hash::Wrap {-lvalue => 1, -defined => 1, -as => '_wrap_hash'}; | ||
| 58 | |||
| 59 | use ControlBreak; | ||
| 60 | use List::Util qw(max min sum); | ||
| 61 | use Set::IntSpan::Fast; | ||
| 62 | |||
| 63 | # modules for Windows only | ||
| 64 | use if $^O eq 'MSWin32', 'Win32::Clipboard'; | ||
| 65 | |||
| 66 | ######################################################################## | ||
| 67 | # Global delarations | ||
| 68 | ######################################################################## | ||
| 69 | |||
| 70 | # is it ok to use Win32::Clipboard? | ||
| 71 | our $USE_WINCLIP = $^O eq 'MSWin32'; | ||
| 72 | |||
| 73 | my $Opt; | ||
| 74 | |||
| 75 | my @ExtremeWaves; | ||
| 76 | my %Location; | ||
| 77 | |||
| 78 | ######################################################################## | ||
| 79 | # Constants | ||
| 80 | ######################################################################## | ||
| 81 | |||
| 82 | const my $EMPTY => q(); # empty string | ||
| 83 | const my $SPACE => q( ); # space character | ||
| 84 | const my $TAB => qq(\t); # tab character | ||
| 85 | const my $DASH => q(-); # dash character | ||
| 86 | const my $TRUE => 1; # perl's usual TRUE | ||
| 87 | const my $FALSE => not $TRUE; # a dual-var consisting of '' and 0 | ||
| 88 | |||
| 89 | const my $DEFAULT_HOT_LIMIT => 30; | ||
| 90 | const my $DEFAULT_COLD_LIMIT => -20; | ||
| 91 | const my $DEFAULT_NDAYS => 5; | ||
| 92 | |||
| 93 | ######################################################################## | ||
| 94 | # Script Mainline | ||
| 95 | ######################################################################## | ||
| 96 | |||
| 97 | __PACKAGE__->run( \@ARGV ) unless caller; | ||
| 98 | |||
| 99 | #----------------------------------------------------------------------- | ||
| 100 | =head1 SUBROUTINES | ||
| 101 | |||
| 102 | =head2 run ( \@ARGV ) | ||
| 103 | |||
| 104 | Invoke this subroutine, passing in a reference to @ARGV, in order to | ||
| 105 | perform an analysis of the heat or cold waves in the input data. | ||
| 106 | |||
| 107 | Input is from stdin, or from the files listed in @ARGV. Data should | ||
| 108 | contain tab-separated output if the format generated by: | ||
| 109 | |||
| 110 | ghcn_fetch -report id | ||
| 111 | |||
| 112 | The following columns are expected: | ||
| 113 | |||
| 114 | Year, Month, Day, Decade, S_Decade, S_Year, S_Qtr, | ||
| 115 | TMAX, TMIN, Tavg, Qflags, StationId, Location | ||
| 116 | |||
| 117 | Any other columns are ignored. | ||
| 118 | |||
| 119 | See ghnc_extremes.pl -help for details. | ||
| 120 | |||
| 121 | =cut | ||
| 122 | |||
| 123 | sub run ($progname, $argv_aref) { | ||
| 124 | |||
| 125 | $Opt = get_options($argv_aref); | ||
| 126 | |||
| 127 | my @files = $argv_aref->@*; | ||
| 128 | |||
| 129 | my $limit = $Opt->limit // | ||
| 130 | ( $Opt->cold ? $DEFAULT_COLD_LIMIT | ||
| 131 | : $DEFAULT_HOT_LIMIT | ||
| 132 | ); | ||
| 133 | |||
| 134 | my $ndays = $Opt->ndays // $DEFAULT_NDAYS; | ||
| 135 | |||
| 136 | my $cmp_op = $Opt->cold ? '<=' : '>='; | ||
| 137 | |||
| 138 | my $years_set = Set::IntSpan::Fast->new; | ||
| 139 | |||
| 140 | my ( $output, $new_fh, $old_fh ); | ||
| 141 | if ( $Opt->outclip and $USE_WINCLIP ) { | ||
| 142 | open $new_fh, '>', \$output | ||
| 143 | or die 'Unable to open buffer for write'; | ||
| 144 | $old_fh = select $new_fh; ## no critic (ProhibitOneArgSelect) | ||
| 145 | } | ||
| 146 | |||
| 147 | my @files = $argv_aref->@*; | ||
| 148 | @files = ('-') unless @files; | ||
| 149 | |||
| 150 | foreach my $file (@files) { | ||
| 151 | my $fh; | ||
| 152 | if ($file eq '-') { | ||
| 153 | $fh = *STDIN; | ||
| 154 | } else { | ||
| 155 | open ($fh, '<', $file) or die; | ||
| 156 | } | ||
| 157 | |||
| 158 | @ExtremeWaves = (); | ||
| 159 | %Location = (); | ||
| 160 | |||
| 161 | # controlling on bool is_extreme and alpha stnid, minor to major | ||
| 162 | my $cb = ControlBreak->new( '+XT', 'STNID', 'EOF' ); | ||
| 163 | |||
| 164 | read_data( $fh, $cb, $limit ); | ||
| 165 | } | ||
| 166 | |||
| 167 | my $years_href; | ||
| 168 | if ( $Opt->peryear ) { | ||
| 169 | $years_href = report_extremes_per_year($limit, $ndays, $cmp_op); | ||
| 170 | } else { | ||
| 171 | $years_href = report_extremes_daycounts($limit, $ndays, $cmp_op) | ||
| 172 | } | ||
| 173 | |||
| 174 | # generate lines for each year that was missing | ||
| 175 | if ($Opt->nogaps) { | ||
| 176 | foreach my $stnid (keys $years_href->%*) { | ||
| 177 | my @years = sort keys $years_href->{$stnid}->%*; | ||
| 178 | |||
| 179 | my $s = Set::IntSpan::Fast->new( min(@years) .. max(@years) ); | ||
| 180 | my $t = Set::IntSpan::Fast->new( @years ); | ||
| 181 | my $gaps = $s->diff($t); | ||
| 182 | my $iter = $gaps->iterate_runs(); | ||
| 183 | |||
| 184 | while ( my ( $from, $to ) = $iter->() ) { | ||
| 185 | foreach my $yr ($from .. $to) { | ||
| 186 | say join $TAB, $stnid, $Location{$stnid}, $yr; | ||
| 187 | } | ||
| 188 | } | ||
| 189 | } | ||
| 190 | } | ||
| 191 | |||
| 192 | WRAP_UP: | ||
| 193 | # send output to the Windows clipboard | ||
| 194 | if ( $Opt->outclip and $USE_WINCLIP ) { | ||
| 195 | Win32::Clipboard->new()->Set( $output ); | ||
| 196 | select $old_fh; | ||
| 197 | } | ||
| 198 | |||
| 199 | return; | ||
| 200 | } | ||
| 201 | |||
| 202 | ######################################################################## | ||
| 203 | # Script-specific Subroutines | ||
| 204 | ######################################################################## | ||
| 205 | |||
| 206 | =head2 read_data ( $fh, $cb, $limit ) | ||
| 207 | |||
| 208 | Read weather data from the filehandle and collect extreme waves | ||
| 209 | according to $limit and $Opt->cold (true for cold waves, false for | ||
| 210 | heat waves). | ||
| 211 | |||
| 212 | =cut | ||
| 213 | |||
| 214 | sub read_data ( $fh, $cb, $limit ) { | ||
| 215 | |||
| 216 | my $extremes_begins; | ||
| 217 | my @extreme_days; | ||
| 218 | my $lineno; | ||
| 219 | |||
| 220 | while ( my $data = <$fh> ) { | ||
| 221 | chomp $data; | ||
| 222 | next if $data eq $EMPTY; | ||
| 223 | last if $data =~ m{ \A Notes: }xms; | ||
| 224 | |||
| 225 | my ($year,$month,$day,$decade,$s_decade,$s_year,$s_qtr,$tmax,$tmin,$tavg,$qflags,$stnid,$loc ) = split $TAB, $data; | ||
| 226 | |||
| 227 | $lineno++; | ||
| 228 | if ($lineno == 1) { | ||
| 229 | die '*E* invalid input data: ' . $data | ||
| 230 | unless $year eq 'Year' and $tmax =~ m{ \A TMAX }xms and $tmin =~ m{ \A TMIN }xms; | ||
| 231 | next; | ||
| 232 | } | ||
| 233 | |||
| 234 | last unless $year =~ m{ \A \d{4} \Z }xms; | ||
| 235 | |||
| 236 | my $ymd = sprintf '%04d-%02d-%02d', $year, $month, $day; | ||
| 237 | |||
| 238 | my $value = $Opt->cold ? $tmin : $tmax; | ||
| 239 | |||
| 240 | next if not defined $value or $value eq $EMPTY; | ||
| 241 | |||
| 242 | $Location{$stnid} = $loc; | ||
| 243 | |||
| 244 | my $is_extreme = $Opt->cold | ||
| 245 | ? $value <= $limit | ||
| 246 | : $value >= $limit | ||
| 247 | ; | ||
| 248 | |||
| 249 | my $on_break = sub { | ||
| 250 | if ( $is_extreme ) { | ||
| 251 | $extremes_begins = $ymd if $cb->break('XT'); | ||
| 252 | push @extreme_days, [$ymd, $value, $stnid, $loc]; | ||
| 253 | } elsif ($cb->break('XT')) { | ||
| 254 | push @ExtremeWaves, [$extremes_begins, [@extreme_days], $stnid, $loc ]; | ||
| 255 | $extremes_begins = undef; | ||
| 256 | @extreme_days = (); | ||
| 257 | } | ||
| 258 | if ($cb->break('STNID')) { | ||
| 259 | $extremes_begins = undef; | ||
| 260 | @extreme_days = (); | ||
| 261 | } | ||
| 262 | }; | ||
| 263 | |||
| 264 | $cb->test_and_do($is_extreme, $stnid, eof, $on_break); | ||
| 265 | } | ||
| 266 | |||
| 267 | return; | ||
| 268 | } | ||
| 269 | |||
| 270 | =head2 report_extremes_daycounts ($limit, $ndays, $cmp_op) | ||
| 271 | |||
| 272 | Analyzes the input data lookin for $ndays consecutive days when | ||
| 273 | the temperature is beyond $limit. By default, heatwaves are examined. | ||
| 274 | If the option -cold is given, then cold waves are examined. | ||
| 275 | |||
| 276 | Returns a reference to a hash keyed on year, and which contains a | ||
| 277 | tab_separated line of text that includes the station id, location, | ||
| 278 | year, ymd the wave began, the number of days the wave lasted, | ||
| 279 | the average temperature during the wave, and the most extreme (hot | ||
| 280 | or cold) temperature during the wave. | ||
| 281 | |||
| 282 | =cut | ||
| 283 | |||
| 284 | sub report_extremes_daycounts ($limit, $ndays, $cmp_op) { | ||
| 285 | my %years; | ||
| 286 | my %location; | ||
| 287 | |||
| 288 | my $daycount_col_head = sprintf '%d-day waves %s %dC', $ndays, $cmp_op, $limit; | ||
| 289 | say join $TAB, 'StnId', 'Location', 'Year', 'YMD', $daycount_col_head, 'Avg C', 'Max C'; | ||
| 290 | |||
| 291 | foreach my $xw_aref (@ExtremeWaves) { | ||
| 292 | my ($xw_begin, $xdays_aref, $stnid, $loc) = $xw_aref->@*; | ||
| 293 | |||
| 294 | $stnid //= $EMPTY; | ||
| 295 | $loc //= $EMPTY; | ||
| 296 | |||
| 297 | my $count = scalar $xdays_aref->@*; | ||
| 298 | |||
| 299 | next if $count < $ndays; | ||
| 300 | |||
| 301 | my $year = substr $xw_begin, 0, 4; ## no critic [ProhibitMagicNumbers] | ||
| 302 | |||
| 303 | my @temps = map { $_->[1] } $xdays_aref->@*; | ||
| 304 | my $sum = sum(@temps); | ||
| 305 | my $extreme = $Opt->cold ? min(@temps) : max(@temps); | ||
| 306 | my $avg = sprintf '%0.1f', $sum / $count; | ||
| 307 | say join $TAB, | ||
| 308 | $stnid, $Location{$stnid}, $year, $xw_begin, $count, $avg, $extreme; | ||
| 309 | $years{$stnid}{$year}++; | ||
| 310 | } | ||
| 311 | |||
| 312 | return \%years; | ||
| 313 | } | ||
| 314 | |||
| 315 | =head2 report_extremes_per_year ($limit, $ndays, $cmp_op) | ||
| 316 | |||
| 317 | Analyzes the input data lookin for $ndays consecutive days when | ||
| 318 | the temperature is beyond $limit. By default, heatwaves are examined. | ||
| 319 | If the option -cold is given, then cold waves are examined. | ||
| 320 | |||
| 321 | Returns a reference to a hash keyed on year, and which contains a | ||
| 322 | tab_separated line of text that includes the station id, location, | ||
| 323 | year, and a count of the number of waves detected during that year. | ||
| 324 | |||
| 325 | =cut | ||
| 326 | |||
| 327 | sub report_extremes_per_year ($limit, $ndays, $cmp_op) { | ||
| 328 | my $type = $Opt->cold ? 'Coldwaves' : 'Heatwaves'; | ||
| 329 | my $title = sprintf '%d-day waves %s %dC', $ndays, $cmp_op, $limit; | ||
| 330 | say join $TAB, 'StnId', 'Location', 'Year', $title; | ||
| 331 | |||
| 332 | my %years; | ||
| 333 | |||
| 334 | foreach my $xw_aref (@ExtremeWaves) { | ||
| 335 | my ($xw_begin, $xdays_aref, $stnid, $loc) = $xw_aref->@*; | ||
| 336 | $stnid //= $EMPTY; | ||
| 337 | $loc //= $EMPTY; | ||
| 338 | my ($year) = split $DASH, $xw_begin; | ||
| 339 | my $count = scalar $xdays_aref->@*; | ||
| 340 | next if $count < $ndays; | ||
| 341 | $years{$stnid}{$year}++; | ||
| 342 | } | ||
| 343 | |||
| 344 | foreach my $stnid ( sort keys %years ) { | ||
| 345 | foreach my $yr ( sort keys $years{$stnid}->%* ) { | ||
| 346 | say join $TAB, $stnid, $Location{$stnid}, $yr, $years{$stnid}{$yr}; | ||
| 347 | } | ||
| 348 | } | ||
| 349 | |||
| 350 | return \%years; | ||
| 351 | } | ||
| 352 | |||
| 353 | ######################################################################## | ||
| 354 | # Script-standard Subroutines | ||
| 355 | ######################################################################## | ||
| 356 | |||
| 357 | =head2 get_options ( \@ARGV ) | ||
| 358 | |||
| 359 | B<get_options> encapsulates everything we need to process command line | ||
| 360 | options, or to set options when invoking this script from a test script. | ||
| 361 | |||
| 362 | Normally it's called by passing a reference to @ARGV; from a test script | ||
| 363 | you'd set up a local array variable to specify the options. | ||
| 364 | |||
| 365 | By convention, you should set up a file-scoped lexical variable named | ||
| 366 | $Opt and set it in the mainline using the return value from this function. | ||
| 367 | Then all options can be accessed used $Opt->option notation. | ||
| 368 | |||
| 369 | =cut | ||
| 370 | |||
| 371 | sub get_options ($argv_aref) { | ||
| 372 | |||
| 373 | my @options = ( | ||
| 374 | 'limit=i', # lower bound of extremes daily temperature | ||
| 375 | 'ndays=i', # number of consecutive days needed to be a extremes | ||
| 376 | 'peryear', # report number of heatwaves per year | ||
| 377 | 'cold', # report coldwaves instead of heatwaves | ||
| 378 | 'nogaps', # generate a line for missing years (for charting) | ||
| 379 | 'outclip', # output data to the Windows clipboard | ||
| 380 | 'help','usage|?', # help | ||
| 381 | ); | ||
| 382 | |||
| 383 | my %opt; | ||
| 384 | |||
| 385 | # create a list of option key names by stripping the various adornments | ||
| 386 | my @keys = map { (split m{ [!+=:|] }xms)[0] } grep { !ref } @options; | ||
| 387 | # initialize all possible options to undef | ||
| 388 | @opt{ @keys } = ( undef ) x @keys; | ||
| 389 | |||
| 390 | GetOptionsFromArray($argv_aref, \%opt, @options) | ||
| 391 | or pod2usage(2); | ||
| 392 | |||
| 393 | # Make %opt into an object and name it the same as what we usually | ||
| 394 | # call the global options object. Note that this doesn't set the | ||
| 395 | # global -- the script will have to do that using the return value | ||
| 396 | # from this function. But, what this does is allow us to call | ||
| 397 | # $Opt->help and other option within this function using the same | ||
| 398 | # syntax as what we use in the script. This is handy if you need | ||
| 399 | # to rename option '-foo' to '-bar' because you can do a find/replace | ||
| 400 | # on '$Opt->foo' and you'll get any instances of it here as well as | ||
| 401 | # in the script. | ||
| 402 | |||
| 403 | ## no critic [Capitalization] | ||
| 404 | ## no critic [ProhibitReusedNames] | ||
| 405 | my $Opt = _wrap_hash \%opt; | ||
| 406 | |||
| 407 | pod2usage(1) if $Opt->usage; | ||
| 408 | pod2usage(-verbose => 2) if $Opt->help; | ||
| 409 | |||
| 410 | return $Opt; | ||
| 411 | } | ||
| 412 | |||
| 413 | 1; # needed in case we import this as a module (e.g. for testing) | ||
| 414 | |||
| 415 | =head1 AUTHOR | ||
| 416 | |||
| 417 | Gary Puckering (jgpuckering@rogers.com) | ||
| 418 | |||
| 419 | =head1 LICENSE AND COPYRIGHT | ||
| 420 | |||
| 421 | Copyright 2022, Gary Puckering | ||
| 422 | |||
| 423 | =cut |