blib/script/bufralter.pl untested

filter: Statementstmt 0.0% 0 / 175 Branchbran 0.0% 0 / 104 Conditioncond 0.0% 0 / 16 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 311 CC 39 SCAR 54.9
CC
39
Cov
0%
set_section1_data
462.0
alter
156.0
set_bufr_edition
72.0
CRAP 243.4
1 #!/usr/local/bin/perl
2  
3 # (C) Copyright 2010-2025 MET Norway
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18 # 02110-1301, USA.
19  
20 # pod included at end of file
21  
22 use strict;
23 use warnings;
24 use Getopt::Long;
25 use Pod::Usage qw(pod2usage);
26 use Geo::BUFR;
27  
28 # This is actually default in BUFR.pm, but provided here to make it
29 # easier for users to change to 'ECCODES' if preferred
30 use constant DEFAULT_TABLE_FORMAT => 'BUFRDC';
31  
32 # Will be used if neither --tablepath nor $ENV{BUFR_TABLES} is set
33 use constant DEFAULT_TABLE_PATH_BUFRDC => '/usr/local/lib/bufrtables';
34 use constant DEFAULT_TABLE_PATH_ECCODES => '/usr/local/share/eccodes/definitions/bufr/tables';
35  
36 # Parse command line options
37 our %option = ();
38 GetOptions(
39 \%option,
40 'bufr_edition=i',
41 'category=i',
42 'centre=i',
43 'compress=i',
44 'data=s%',
45 'day=i',
46 'help',
47 'hour=i',
48 'int_subcategory=i',
49 'loc_subcategory=i',
50 'local_table_version=i',
51 'master_table_version=i',
52 'minute=i',
53 'month=i',
54 'observed=i',
55 'outfile=s',
56 'remove_qc',
57 'remove_sec2',
58 'second=i',
59 'strict_checking=i',
60 'subcategory=i',
61 'subcentre=i',
62 'tableformat=s',
63 'tablepath=s',
64 'update_number=i',
65 'verbose=i',
66 'year=i',
67 'year_of_century=i',
68 ) or pod2usage(-verbose => 0);
69  
70 # User asked for help
71 pod2usage(-verbose => 1) if $option{help};
72  
73 # Make sure there is an input file
74 pod2usage(-verbose => 0) unless @ARGV == 1;
75  
76 my $infile = $ARGV[0];
77 open(my $IN, '<',$infile)
78 or die "Cannot open $infile: $!";
79  
80 # Default is to ignore 'recoverable' errors found in decoded or
81 # encoded BUFR format. This can be changed by setting strict_checking,
82 # which will then apply both to decoding and encoding.
83 my $strict_checking = defined $option{strict_checking}
84 ? $option{strict_checking} : 0;
85 Geo::BUFR->set_strict_checking($strict_checking);
86  
87 # Set verbosity level
88 Geo::BUFR->set_verbose($option{verbose}) if $option{verbose};
89  
90 # Set BUFR table format
91 my $tableformat = (defined $option{tableformat}) ? uc $option{tableformat} : DEFAULT_TABLE_FORMAT;
92 Geo::BUFR->set_tableformat($tableformat);
93  
94 # Set BUFR table path
95 if ($option{tablepath}) {
96 # Command line option --tablepath overrides all
97 Geo::BUFR->set_tablepath($option{tablepath});
98 } elsif ($ENV{BUFR_TABLES}) {
99 # If no --tablepath option, use the BUFR_TABLES environment variable
100 Geo::BUFR->set_tablepath($ENV{BUFR_TABLES});
101 } else {
102 # If all else fails, use the default tablepath in BUFRDC/ECCODES
103 if ($tableformat eq 'BUFRDC') {
104 Geo::BUFR->set_tablepath(DEFAULT_TABLE_PATH_BUFRDC);
105 } elsif ($tableformat eq 'ECCODES') {
106 Geo::BUFR->set_tablepath(DEFAULT_TABLE_PATH_ECCODES);
107 }
108 }
109  
110 # Where to print the altered BUFR message(s)
111 my $OUT;
112 if ($option{outfile}) {
113 open($OUT, '>', $option{outfile})
114 or die "Cannot open $option{outfile} for writing: $!";
115 } else {
116 $OUT = *STDOUT;
117 }
118 binmode($OUT);
119  
120 # Change input separator to 'BUFR'
121 my $oldeol = $/;
122 $/ = 'BUFR';
123  
124 # Read in everything before first 'BUFR'
125 my $out = <$IN>;
126  
127 while (my $msg = <$IN>) {
128 # Leave input unaltered if 'BUFR' is not start of a BUFR message
129 if (length($msg) < 4) {
130 $out .= $msg;
131 next;
132 }
133 my $len = unpack 'N', "\0$msg";
134 if ($len < 8 || $len > length($msg) + 4) {
135 $out .= $msg;
136 next;
137 }
138 if (substr($msg,$len-8,4) != '7777') {
139 $out .= $msg;
140 next;
141 }
142  
143 # 'BUFR' is quite probably start of a valid BUFR message, so
144 # transfer 'BUFR' from $out to $msg, transfer text following BUFR
145 # message from $msg to $out, and try to alter $msg. Input
146 # separator must be reverted before calling Geo::BUFR routines
147 chomp $out;
148 my $rest = substr($msg,$len-4);
149 $msg = 'BUFR' . substr($msg,0,$len-4);
150  
151 $/ = $oldeol;
152 my $bufr = Geo::BUFR->new($msg);
153  
154 $out .= alter($bufr);
155 $out .= $rest;
156  
157 $bufr->fclose();
158 $/ = 'BUFR';
159 }
160  
161 print $OUT $out if $out;
162  
163  
164 # Extract data from BUFR file, possibly alter the data, and write the
165 # new messages to STDOUT.
166 sub alter {
167 my $bufr = shift; # BUFR object
168  
169 if ($option{remove_qc}) {
170 Geo::BUFR->set_noqc();
171 }
172  
173 my $new_bufr = Geo::BUFR->new();
174 my @subset_data; # Will contain data values for subset 1,2...
175 my @subset_desc; # Will contain the set of descriptors for subset 1,2...
176  
177 READLOOP:
178 while (not $bufr->eof()) {
179  
180 # Read (and decode) next observation
181 my ($data, $descriptors) = $bufr->next_observation();
182 my $isub = $bufr->get_current_subset_number();
183 my $nsubsets = $bufr->get_number_of_subsets();
184  
185 if ($isub == 1) {
186 $new_bufr->copy_from($bufr,'metadata');
187 @subset_data = ();
188 @subset_desc = ();
189  
190 set_section1_data($bufr, $new_bufr);
191  
192 if (defined $option{observed}) {
193 $new_bufr->set_observed_data($option{observed});
194 }
195 if (defined $option{compress}) {
196 $new_bufr->set_compressed_data($option{compress});
197 }
198 if ($option{remove_sec2}) {
199 $new_bufr->set_optional_section(0);
200 }
201 if ($option{remove_qc}) {
202 remove_qc_from_unexpanded($new_bufr);
203 }
204 }
205  
206 if (defined $option{data}) {
207 DESCRIPTOR: while (my ($desc, $value) = each %{$option{data}}) {
208 for (my $i=0; $i < @$descriptors; $i++) {
209 if ($descriptors->[$i] == $desc) {
210 if ($value =~ /(.*)\+$/) {
211 $data->[$i] += $1;
212 } elsif ($value eq 'missing') {
213 $data->[$i] = undef;
214 } else {
215 $data->[$i] = $value;
216 }
217 next DESCRIPTOR;
218 }
219 }
220 }
221 }
222 $subset_data[$isub] = $data;
223 $subset_desc[$isub] = $descriptors;
224  
225 if ($isub == $nsubsets) {
226 return $new_bufr->encode_message(\@subset_data, \@subset_desc);
227 }
228 }
229 }
230  
231 sub set_section1_data {
232 my ($bufr, $new_bufr) = @_;
233  
234 if (defined $option{centre}) {
235 $new_bufr->set_centre($option{centre});
236 }
237 if (defined $option{subcentre}) {
238 $new_bufr->set_subcentre($option{subcentre});
239 }
240 if (defined $option{update_number}) {
241 if ($option{update_number} >= 0) {
242 $new_bufr->set_update_sequence_number($option{update_number});
243 } else {
244 my $old_number = $bufr->get_update_sequence_number();
245 my $update_number = $option{update_number};
246 if ($option{update_number} == -1) {
247 $new_bufr->set_update_sequence_number($old_number + 1);
248 } elsif ($option{update_number} == -2) {
249 $new_bufr->set_update_sequence_number($old_number - 1);
250 } else {
251 pod2usage(-verbose => 1);
252 }
253 }
254 }
255 if (defined $option{category}) {
256 $new_bufr->set_data_category($option{category});
257 }
258 if (defined $option{subcategory}) {
259 $new_bufr->set_data_subcategory($option{subcategory});
260 }
261 if (defined $option{int_subcategory}) {
262 $new_bufr->set_int_data_subcategory($option{int_subcategory});
263 }
264 if (defined $option{loc_subcategory}) {
265 $new_bufr->set_loc_data_subcategory($option{loc_subcategory});
266 }
267 if (defined $option{master_table_version}) {
268 $new_bufr->set_master_table_version($option{master_table_version});
269 }
270 if (defined $option{local_table_version}) {
271 $new_bufr->set_local_table_version($option{local_table_version});
272 }
273 if (defined $option{year}) {
274 $new_bufr->set_year($option{year});
275 }
276 if (defined $option{year_of_century}) {
277 $new_bufr->set_year_of_century($option{year_of_century});
278 }
279 if (defined $option{month}) {
280 $new_bufr->set_month($option{month});
281 }
282 if (defined $option{day}) {
283 $new_bufr->set_day($option{day});
284 }
285 if (defined $option{hour}) {
286 $new_bufr->set_hour($option{hour});
287 }
288 if (defined $option{minute}) {
289 $new_bufr->set_minute($option{minute});
290 }
291 if (defined $option{second}) {
292 $new_bufr->set_second($option{second});
293 }
294 # Should be processed last of the change metadata options,
295 # because setting of BUFR edition may depend on other
296 # metadata which user has opted to set
297 if (defined $option{bufr_edition}) {
298 set_bufr_edition($option{bufr_edition}, $bufr, $new_bufr);
299 }
300 return;
301 }
302  
303 sub remove_qc_from_unexpanded {
304 my $bufr = shift;
305 my $desc = $bufr->get_descriptors_unexpanded();
306 $desc =~ s/ 222000.*//;
307 $bufr->set_descriptors_unexpanded($desc);
308 }
309  
310 # If user hasn't provided the new metadata required for the new bufr
311 # edition, we make some educated guesses of these new metadata.
312 sub set_bufr_edition {
313 my ($new_bufr_edition, $bufr, $new_bufr) = @_;
314  
315 my $old_bufr_edition = $bufr->get_bufr_edition();
316  
317 if ($old_bufr_edition == 4 and $new_bufr_edition < 4) {
318 if (!defined $new_bufr->get_data_subcategory()) {
319 $new_bufr->set_data_subcategory($bufr->get_loc_data_subcategory());
320 }
321 # get_year_of_century() fetches from YEAR if YEAR_OF_CENTURY isn't set
322 $new_bufr->set_year_of_century($new_bufr->get_year_of_century());
323 } elsif ($old_bufr_edition < 4 and $new_bufr_edition == 4) {
324 if (!defined $new_bufr->get_loc_data_subcategory()) {
325 $new_bufr->set_loc_data_subcategory($bufr->get_data_subcategory());
326 }
327 if (!defined $new_bufr->get_int_data_subcategory()) {
328 $new_bufr->set_int_data_subcategory(255); # Undefined value
329 }
330 if (!defined $new_bufr->get_year()) {
331 # Should work most of the time
332 $new_bufr->set_year($bufr->get_year_of_century() + 2000);
333 }
334 if (!defined $new_bufr->get_second()) {
335 $new_bufr->set_second(0);
336 }
337 }
338  
339 $new_bufr->set_bufr_edition($new_bufr_edition);
340 }
341  
342 =pod
343  
344 =encoding utf8
345  
346 =head1 SYNOPSIS
347  
348 bufralter.pl <bufr file>
349 [--data <descriptor=value[+]>]
350 [--bufr_edition <value>]
351 [--centre <value>]
352 [--subcentre <value>]
353 [--update_number <value>]
354 [--category <value>]
355 [--subcategory <value>]
356 [--int_subcategory <value>]
357 [--loc_subcategory <value>]
358 [--master_table_version <value>]
359 [--local_table_version <value>]
360 [--year <value>]
361 [--year_of_century <value>]
362 [--month <value>]
363 [--day <value>]
364 [--hour <value>]
365 [--minute <value>]
366 [--second <value>]
367 [--observed 0|1]
368 [--compress 0|1]
369 [--remove_sec2]
370 [--remove_qc]
371 [--outfile <file>]
372 [--strict_checking n]
373 [--tableformat <BUFRDC|ECCODES>]
374 [--tablepath <path to BUFR tables>]
375 [--verbose n]
376 [--help]
377  
378 =head1 DESCRIPTION
379  
380 Will alter the BUFR messages in <bufr file> according to what is
381 specified by the options provided. The modified file (text surrounding
382 the BUFR messages will not be affected) will be printed to STDOUT
383 (unless C<--outfile> is set).
384  
385 Execute without arguments for Usage, with option C<--help> for some
386 additional info.
387  
388 =head1 OPTIONS
389  
390 --data <descriptor=value[+]> Set (first) data value in section 4 for
391 descriptor. A trailing '+' means that the value
392 should be added to existing value. Use 'missing'
393 to set a missing value. Repeat the option if more
394 sequence descriptors are to be set. Example:
395 --data 004004=-1+ --data 004005=50 --data
396 012101=missing This will set the data value for
397 first (and only first!) occurrence of these 3
398 descriptors in every subset and every message in
399 <bufr file> to the given value (subtracting 1 from
400 the existing value for 004004)
401 --bufr_edition <value> Set BUFR edition to <value>. If the new edition
402 involves some metadata not present in the old edition,
403 some educated guesses for these new metadata are made,
404 but you should also consider setting these new metadata
405 explicitely
406 --centre <value> Set originating centre to <value>
407 --subcentre <value>
408 Set originating subcentre to <value>
409 --update_number <value>
410 Set update sequence number to <value>. Use the special
411 value -1 to increment existing update sequence number,
412 -2 to decrement it
413 --category <value> Set data category to <value>
414 --subcategory <value> Set data sub-category to <value>
415 --int_subcategory <value> Set international data sub-category to <value>
416 --loc_subcategory <value> Set local data sub-category to <value>
417 --master_table_version <value>
418 Set master table version number to <value>
419 --local_table_version <value>
420 Set local table version number to <value>
421 --<time_var> <value> Set <time_var> (= year | year_of_century | month |
422 day | hour | minute | second) in section 1 to <value>
423 --observed 0|1 Set observed data in section 3 to 0 or 1
424 --compress 0|1 Set compression in section 3 to 0 or 1
425 --remove_sec2 Remove optional section 2 if present
426 --remove_qc Remove all quality control information,
427 i.e. remove all descriptors from 222000 on
428 --outfile <filename>
429 Will print to <filename> instead of STDOUT
430 --strict_checking n n=0 (default) Disable strict checking of BUFR format
431 n=1 Issue warning if (recoverable) error in
432 BUFR format
433 n=2 Croak if (recoverable) error in BUFR format.
434 Nothing more in this message will be
435 decoded/encoded.
436 --tableformat Currently supported are BUFRDC and ECCODES (default is BUFRDC)
437 --tablepath <path to BUFR tables>
438 Set path to BUFR tables (overrides $ENV{BUFR_TABLES})
439 --verbose n Set verbose level to n, 0<=n<=6 (default 0). Verbose
440 output is sent to STDOUT, so ought to be combined with
441 option --outfile
442 --help Display Usage and explain the options used. Almost
443 the same as consulting perldoc bufralter.pl
444  
445 Options may be abbreviated, e.g. C<--he> or C<-he> for C<--help>.
446  
447 To avoid having to use the C<--tablepath> option, you are adviced to
448 set the environment variable BUFR_TABLES to the directory where your
449 BUFR tables are located (unless the default path provided by
450 bufralter.pl works for you). For tableformat ECCODES, se
451 L<http://search.cpan.org/dist/Geo-BUFR/lib/Geo/BUFR.pm#BUFR-TABLE-FILES>
452 for more info on how to set C<--tablepath> (or BUFR_TABLES).
453  
454 =head1 AUTHOR
455  
456 Pål Sannes E<lt>pal.sannes@met.noE<gt>
457  
458 =head1 COPYRIGHT
459  
460 Copyright (C) 2010-2025 MET Norway
461  
462 =cut