-
Notifications
You must be signed in to change notification settings - Fork 284
/
awips_tiled.py
1851 lines (1614 loc) · 83 KB
/
awips_tiled.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2017-2018 Satpy developers
#
# This file is part of satpy.
#
# satpy is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# satpy is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# satpy. If not, see <http://www.gnu.org/licenses/>.
"""The AWIPS Tiled writer is used to create AWIPS-compatible tiled NetCDF4 files.
The Advanced Weather Interactive Processing System (AWIPS) is a
program used by the United States National Weather Service (NWS) and others
to view
different forms of weather imagery. The original Sectorized Cloud and Moisture
Imagery (SCMI) functionality in AWIPS was a NetCDF4 format supported by AWIPS
to store one image broken up in to one or more "tiles". This format has since
been expanded to support many other products and so the writer for this format
in Satpy is generically called the "AWIPS Tiled" writer. You may still see
SCMI referenced in this documentation or in the source code for the writer.
Once AWIPS is configured for specific products this writer can be used to
provide compatible products to the system.
The AWIPS Tiled writer takes 2D (y, x) geolocated data and creates one or more
AWIPS-compatible NetCDF4 files. The writer and the AWIPS client may
need to be configured to make things appear the way the user wants in
the AWIPS client. The writer can only produce files for datasets mapped
to areas with specific projections:
- lcc
- geos
- merc
- stere
This is a limitation of the AWIPS client and not of the writer. In the case
where AWIPS has been updated to support additional projections, this writer
may also need to be updated to support those projections.
AWIPS Configuration
-------------------
Depending on how this writer is used and the data it is provided, AWIPS may
need additional configuration on the server side to properly ingest the files
produced. This will require administrator privileges to the ingest server(s)
and is not something that can be configured on the client. Note that any
changes required must be done on all servers that you wish to ingest your data
files. The generic "polar" template this writer defaults to should limit the
number of modifications needed for any new data fields that AWIPS previously
was unaware of. Once the data is ingested, the client can be used to customize
how the data looks on screen.
AWIPS requires files to follow a specific naming scheme so they can be routed
to specific "decoders". For the files produced by this writer, this typically
means editing the "goesr" decoder configuration in a directory like::
/awips2/edex/data/utility/common_static/site/<site>/distribution/goesr.xml
The "goesr" decoder is a subclass of the "satellite" decoder. You may see
either name show up in the AWIPS ingest logs. With the correct
regular expression in the above file, your files should be passed to the
right decoder, opened, and parsed for data.
To tell AWIPS exactly what attributes and variables mean in your file, you'll
need to create or configure an XML file in::
/awips2/edex/data/utility/common_static/site/<site>/satellite/goesr/descriptions/
See the existing files in this directory for examples. The "polar" template
(see below) that this writer uses by default is already configured in the
"Polar" subdirectory assuming that the TOWR-S RPM package has been installed
on your AWIPS ingest server.
Templates
---------
This writer allows for a "template" to be specified to control how the output
files are structured and created. Templates can be configured in the writer
YAML file (``awips_tiled.yaml``) or passed as a dictionary to the ``template``
keyword argument. Templates have three main sections:
1. global_attributes
2. coordinates
3. variables
Additionally, you can specify whether a template should produce files with
one variable per file by specifying ``single_variable: true`` or multiple
variables per file by specifying ``single_variable: false``. You can also
specify the output filename for a template using a Python format string.
See ``awips_tiled.yaml`` for examples. Lastly, a ``add_sector_id_global``
boolean parameter can be specified to add the user-provided ``sector_id``
keyword argument as a global attribute to the file.
The ``global_attributes`` section takes names of global attributes and
then a series of options to "render" that attribute from the metadata
provided when creating files. For example::
product_name:
value: "{name}"
For more information see the
:meth:`satpy.writers.awips_tiled.NetCDFTemplate.get_attr_value` method.
The ``coordinates`` and ``variables`` are similar to each other in that they
define how a variable should be created, the attributes it should have, and
the encoding to write to the file. Coordinates typically don't need to be
modified as tiled files usually have only ``x`` and ``y`` dimension variables.
The Variables on the other hand use a decision tree to determine what section
applies for a particular DataArray being saved. The basic structure is::
variables:
arbitrary_section_name:
<decision tree matching parameters>
var_name: "output_netcdf_variable_name"
attributes:
<attributes similar to global attributes>
encoding:
<xarray encoding parameters>
The "decision tree matching parameters" can be one or more of "name",
"standard_name', "satellite", "sensor", "area_id', "units", or "reader".
The writer will choose the best section for the DataArray being saved
(the most matches). If none of these parameters are specified in a section
then it will be used when no other matches are found (the "default" section).
The "encoding" parameters can be anything accepted by xarray's ``to_netcdf``
method. See :meth:`xarray.Dataset.to_netcdf` for more information on the
`encoding`` keyword argument.
For more examples see the existing builtin templates defined in
``awips_tiled.yaml``.
Builtin Templates
^^^^^^^^^^^^^^^^^
There are only a few templates provided in Sapty currently.
* **polar**: A custom format developed for the CSPP Polar2Grid project at the
University of Wisconsin - Madison Space Science and Engineering Center
(SSEC). This format is made available through the TOWR-S package that can be
installed for GOES-R support in AWIPS. This format is meant to be very
generic and should theoretically allow any variable to get ingested into
AWIPS.
* **glm_l2_radc**: This format is used to produce standard files for the gridded
GLM products produced by the CSPP Geo Gridded GLM package. Support for this
format is also available in the TOWR-S package on an AWIPS ingest server.
This format is specific to gridded GLM on the CONUS sector and is not meant
to work for other data.
* **glm_l2_radf**: This format is used to produce standard files for the gridded
GLM productes produced by the CSPP Geo Gridded GLM package. Support for this
format is also available in the TOWR-S package on an AWIPS ingest server.
This format is specific to gridded GLM on the Full Disk sector and is not
meant to work for other data.
Numbered versus Lettered Grids
------------------------------
By default this writer will save tiles by number starting with '1'
representing the upper-left image tile. Tile numbers then increase
along the column and then on to the next row.
By specifying `lettered_grid` as `True` tiles can be designated with a
letter. Lettered grids or sectors are preconfigured in the `awips_tiled.yaml`
configuration file. The lettered tile locations are static and will not
change with the data being written to them. Each lettered tile is split
into a certain number of subtiles (`num_subtiles`), default 2 rows by
2 columns. Lettered tiles are meant to make it easier for receiving
AWIPS clients/stations to filter what tiles they receive; saving time,
bandwidth, and space.
Any tiles (numbered or lettered) not containing any valid data are not
created.
Updating tiles
--------------
There are some input data cases where we want to put new data in a tile
file written by a previous execution. An example is a pre-tiled input dataset
that is processed one tile at a time. One input tile may map to one or more
output AWIPS tiles, but may not perfectly aligned, leaving
empty/unused space in the output tile. The next input tile may be able to fill
in that empty space and should be allowed to write the "new" data to the file.
This is the default behavior of the AWIPS tiled writer. In cases where data
overlaps the existing data in the tile, the newer data has priority.
Shifting Lettered Grids
-----------------------
Due to the static nature of the lettered grids, there is sometimes a
need to shift the locations of where these tiles are by up to 0.5 pixels in
each dimension to align with the data being processed. This means that the
tiles for a 1000m resolution grid may be shifted up to 500m in each direction
from the original definition of the lettered "sector". This can cause
differences in the location of the tiles between executions depending on the
locations of the input data. In the worst case tile A01 from one execution
could be shifted up to 1 grid cell from tile A01 in another execution (one
is shifted 0.5 pixels to the left, the other is shifted 0.5 to the right).
This shifting makes the calculations for generating tiles easier and
more accurate. By default, the lettered tile locations are changed to match
the location of the data. This works well when output tiles will not be
updated (see above) in future processing. In cases where output tiles will be
filled in or updated with more data the ``use_sector_reference`` keyword
argument can be set to ``True`` to tell the writer to shift the data's
geolocation by up to 0.5 pixels in each dimension instead of shifting the
lettered tile locations.
"""
import logging
import os
import string
import sys
import warnings
from collections import namedtuple
from datetime import datetime, timedelta
import dask
import dask.array as da
import numpy as np
import xarray as xr
from pyproj import CRS, Proj, Transformer
from pyresample.geometry import AreaDefinition
from trollsift.parser import Parser, StringFormatter
from satpy import __version__
from satpy.writers import DecisionTree, Enhancer, Writer, get_enhanced_image
LOG = logging.getLogger(__name__)
DEFAULT_OUTPUT_PATTERN = "{source_name}_AII_{platform_name}_{sensor}_" \
"{name}_{sector_id}_{tile_id}_" \
"{start_time:%Y%m%d_%H%M}.nc"
UNIT_CONV = {
"micron": "microm",
"mm h-1": "mm/h",
"1": "*1",
"none": "*1",
"percent": "%",
"Kelvin": "kelvin",
"K": "kelvin",
}
TileInfo = namedtuple("TileInfo", ["tile_count", "image_shape", "tile_shape",
"tile_row_offset", "tile_column_offset", "tile_id",
"tile_number",
"x", "y", "xy_factors", "tile_slices", "data_slices"])
XYFactors = namedtuple("XYFactors", ["mx", "bx", "my", "by"])
def fix_awips_file(fn):
"""Hack the NetCDF4 files to workaround NetCDF-Java bugs used by AWIPS.
This should not be needed for new versions of AWIPS.
"""
# hack to get files created by new NetCDF library
# versions to be read by AWIPS buggy java version
# of NetCDF
LOG.info("Modifying output NetCDF file to work with AWIPS")
import h5py
h = h5py.File(fn, "a")
if "_NCProperties" in h.attrs:
del h.attrs["_NCProperties"]
h.close()
class NumberedTileGenerator(object):
"""Helper class to generate per-tile metadata for numbered tiles."""
def __init__(self, area_definition,
tile_shape=None, tile_count=None):
"""Initialize and generate tile information for this sector/grid for later use."""
self.area_definition = area_definition
self._rows = self.area_definition.height
self._cols = self.area_definition.width
# get tile shape, number of tiles, etc.
self._get_tile_properties(tile_shape, tile_count)
# scaling parameters for the overall images X and Y coordinates
# they must be the same for all X and Y variables for all tiles
# and must be stored in the file as 0, 1, 2, 3, ...
# (X factor, X offset, Y factor, Y offset)
self.mx, self.bx, self.my, self.by = self._get_xy_scaling_parameters()
self.xy_factors = XYFactors(self.mx, self.bx, self.my, self.by)
self._tile_cache = []
def _get_tile_properties(self, tile_shape, tile_count):
"""Generate tile information for numbered tiles."""
if tile_shape is not None:
tile_shape = (int(min(tile_shape[0], self._rows)), int(min(tile_shape[1], self._cols)))
tile_count = (int(np.ceil(self._rows / float(tile_shape[0]))),
int(np.ceil(self._cols / float(tile_shape[1]))))
elif tile_count:
tile_shape = (int(np.ceil(self._rows / float(tile_count[0]))),
int(np.ceil(self._cols / float(tile_count[1]))))
else:
raise ValueError("Either 'tile_count' or 'tile_shape' must be provided")
# number of pixels per each tile (rows, cols)
self.tile_shape = tile_shape
# number of tiles in each direction (rows, columns)
self.tile_count = tile_count
# number of tiles in the entire image
self.total_tiles = tile_count[0] * tile_count[1]
# number of pixels in the whole image (rows, columns)
self.image_shape = (self.tile_shape[0] * self.tile_count[0],
self.tile_shape[1] * self.tile_count[1])
# X and Y coordinates of the whole image
self.x, self.y = self._get_xy_arrays()
def _get_xy_arrays(self):
"""Get the overall X/Y coordinate variable arrays."""
gd = self.area_definition
ts = self.tile_shape
tc = self.tile_count
# Since our tiles may go over the edge of the original "grid" we
# need to make sure we calculate X/Y to the edge of all of the tiles
imaginary_data_size = (ts[0] * tc[0], ts[1] * tc[1])
ps_x = gd.pixel_size_x
ps_y = gd.pixel_size_y
# tiles start from upper-left
new_extents = (
gd.area_extent[0],
gd.area_extent[1] - ps_y * (imaginary_data_size[0] - gd.height),
gd.area_extent[2] + ps_x * (imaginary_data_size[1] - gd.width),
gd.area_extent[3])
imaginary_grid_def = AreaDefinition(
gd.area_id,
gd.description,
gd.proj_id,
gd.crs,
imaginary_data_size[1],
imaginary_data_size[0],
new_extents,
)
x, y = imaginary_grid_def.get_proj_vectors()
return x, y
def _get_xy_scaling_parameters(self):
"""Get the X/Y coordinate limits for the full resulting image."""
gd = self.area_definition
bx = self.x.min()
mx = gd.pixel_size_x
by = self.y.max()
my = -abs(gd.pixel_size_y)
return mx, bx, my, by
def _tile_number(self, ty, tx):
"""Get tile number from tile row/column."""
# e.g.
# 001 002 003 004
# 005 006 ...
return ty * self.tile_count[1] + tx + 1
def _tile_identifier(self, ty, tx):
"""Get tile identifier for numbered tiles."""
return "T{:03d}".format(self._tile_number(ty, tx))
def _generate_tile_info(self):
"""Get numbered tile metadata."""
x = self.x
y = self.y
ts = self.tile_shape
tc = self.tile_count
if self._tile_cache:
for tile_info in self._tile_cache:
yield tile_info
for ty in range(tc[0]):
for tx in range(tc[1]):
tile_id = self._tile_identifier(ty, tx)
tile_row_offset = ty * ts[0]
tile_column_offset = tx * ts[1]
# store tile data to an intermediate array
# the tile may be larger than the remaining data, handle that:
max_row_idx = min((ty + 1) * ts[0], self._rows) - (ty * ts[0])
max_col_idx = min((tx + 1) * ts[1], self._cols) - (tx * ts[1])
tile_slices = (slice(0, max_row_idx), slice(0, max_col_idx))
data_slices = (slice(ty * ts[0], (ty + 1) * ts[0]),
slice(tx * ts[1], (tx + 1) * ts[1]))
tmp_x = x[data_slices[1]]
tmp_y = y[data_slices[0]]
tile_number = self._tile_number(ty, tx)
tile_info = TileInfo(
tc, self.image_shape, ts,
tile_row_offset, tile_column_offset, tile_id,
tile_number,
tmp_x, tmp_y, self.xy_factors, tile_slices, data_slices)
self._tile_cache.append(tile_info)
yield tile_info
def __call__(self):
"""Provide simple call interface for getting tile metadata."""
if self._tile_cache:
tile_infos = self._tile_cache
else:
tile_infos = self._generate_tile_info()
for tile_info in tile_infos:
# TODO: Return the slice instead of the actual data array
# Use the slicing start/end to determine if it is empty
# tile_data = data[tile_info.data_slices]
# if not tile_data.size:
# LOG.info("Tile {} is empty, skipping...".format(tile_info[2]))
# continue
yield tile_info
class LetteredTileGenerator(NumberedTileGenerator):
"""Helper class to generate per-tile metadata for lettered tiles."""
def __init__(self, area_definition, extents, sector_crs, # noqa: D417
cell_size=(2000000, 2000000),
num_subtiles=None, use_sector_reference=False):
"""Initialize tile information for later generation.
Args:
area_definition (AreaDefinition): Area of the data being saved.
extents (tuple): Four element tuple of the configured lettered
area.
sector_crs (pyproj.CRS): CRS of the configured lettered sector
area.
cell_size (tuple): Two element tuple of resolution of each tile
in sector projection units (y, x).
"""
# (row subtiles, col subtiles)
self.num_subtiles = num_subtiles or (2, 2)
self.cell_size = cell_size # (row tile height, col tile width)
# x/y
self.ll_extents = extents[:2] # (x min, y min)
self.ur_extents = extents[2:] # (x max, y max)
self.use_sector_reference = use_sector_reference
self._transformer = Transformer.from_crs(sector_crs, area_definition.crs)
super().__init__(area_definition)
def _get_tile_properties(self, tile_shape, tile_count):
"""Calculate tile information for this particular sector/grid."""
# ignore tile_shape and tile_count
# they come from the base class, but aren't used here
del tile_shape, tile_count
# get original image's X/Y
ad = self.area_definition
x, y = ad.get_proj_vectors()
ll_xy = self._transformer.transform(*self.ll_extents)
ur_xy = self._transformer.transform(*self.ur_extents)
cw = abs(ad.pixel_size_x)
ch = abs(ad.pixel_size_y)
st = self.num_subtiles
cs = self.cell_size # row height, column width
# make sure the number of total tiles is a factor of the subtiles
# meaning each letter has the full number of subtiles
# Tile numbering/naming starts from the upper left corner
ul_xy = (ll_xy[0], ur_xy[1])
# Adjust the upper-left corner to 'perfectly' match the data
# X/Y are center of pixels, adjust by half a pixels to get upper-left pixel corner
shift_x = float(ul_xy[0] - (x.min() - cw / 2.)) % cw # could be negative
shift_y = float(ul_xy[1] - (y.max() + ch / 2.)) % ch # could be negative
# if we're really close to 0 then don't worry about it
if abs(shift_x) < 1e-10 or abs(shift_x - cw) < 1e-10:
shift_x = 0
if abs(shift_y) < 1e-10 or abs(shift_y - ch) < 1e-10:
shift_y = 0
if self.use_sector_reference:
LOG.debug("Adjusting X/Y by (%f, %f) so it better matches lettered grid", shift_x, shift_y)
x = x + shift_x
y = y + shift_y
else:
LOG.debug("Adjusting lettered grid by (%f, %f) so it better matches data X/Y", shift_x, shift_y)
ul_xy = (ul_xy[0] - shift_x, ul_xy[1] - shift_y) # outer edge of grid
# always keep the same distance between the extents
ll_xy = (ul_xy[0], ll_xy[1] - shift_y)
ur_xy = (ur_xy[0] - shift_x, ul_xy[1])
fcs_y, fcs_x = (np.ceil(float(cs[0]) / st[0]), np.ceil(float(cs[1]) / st[1]))
# need X/Y for *whole* tiles
max_cols = np.ceil((ur_xy[0] - ul_xy[0]) / fcs_x)
max_rows = np.ceil((ul_xy[1] - ll_xy[1]) / fcs_y)
# don't create partial alpha-tiles
max_cols = int(np.ceil(max_cols / st[1]) * st[1])
max_rows = int(np.ceil(max_rows / st[0]) * st[0])
# make tile cell size a factor of pixel size
num_pixels_x = int(np.floor(fcs_x / cw))
num_pixels_y = int(np.floor(fcs_y / ch))
# NOTE: this does not change the *total* number of columns/rows that
# will be produced. This is important because otherwise the number
# of lettered tiles could depend on the input data which is not what we
# want
fcs_x = num_pixels_x * cw
fcs_y = num_pixels_y * ch
# NOTE: this takes the center of the pixel relative to the upper-left outer edge:
min_col = max(int(np.floor((x.min() - ul_xy[0]) / fcs_x)), 0)
max_col = min(int(np.floor((x.max() - ul_xy[0]) / fcs_x)), max_cols - 1)
min_row = max(int(np.floor((ul_xy[1] - y.max()) / fcs_y)), 0)
max_row = min(int(np.floor((ul_xy[1] - y.min()) / fcs_y)), max_rows - 1)
num_cols = max_col - min_col + 1
num_rows = max_row - min_row + 1
total_alphas = (max_cols * max_rows) / (st[0] * st[1])
if total_alphas > 26:
raise ValueError("Too many lettered grid cells '{}' (sector cell size too small). "
"Maximum of 26".format(total_alphas))
self.tile_shape = (num_pixels_y, num_pixels_x)
self.total_tile_count = (max_rows, max_cols)
self.tile_count = (num_rows, num_cols)
self.total_tiles = num_rows * num_cols
self.image_shape = (num_pixels_y * num_rows, num_pixels_x * num_cols)
self.min_col = min_col
self.max_col = max_col
self.min_row = min_row
self.max_row = max_row
self.ul_xy = ul_xy
self.mx = cw
self.bx = ul_xy[0] + cw / 2.0 # X represents the center of the pixel
self.my = -ch
self.by = ul_xy[1] - ch / 2.0 # Y represents the center of the pixel
self.x = x
self.y = y
def _get_xy_scaling_parameters(self):
"""Get the X/Y coordinate limits for the full resulting image."""
return self.mx, self.bx, self.my, self.by
def _tile_identifier(self, ty, tx):
"""Get tile identifier (name) for a particular tile row/column."""
st = self.num_subtiles
ttc = self.total_tile_count
alpha_num = int((ty // st[0]) * (ttc[1] // st[1]) + (tx // st[1]))
alpha = string.ascii_uppercase[alpha_num]
tile_num = int((ty % st[0]) * st[1] + (tx % st[1])) + 1
return "T{}{:02d}".format(alpha, tile_num)
def _generate_tile_info(self):
"""Create generator of individual tile metadata."""
if self._tile_cache:
for tile_info in self._tile_cache:
yield tile_info
ts = self.tile_shape
ul_xy = self.ul_xy
x, y = self.x, self.y
cw = abs(float(self.area_definition.pixel_size_x))
ch = abs(float(self.area_definition.pixel_size_y))
# where does the data fall in our lettered grid
for gy in range(self.min_row, self.max_row + 1):
for gx in range(self.min_col, self.max_col + 1):
tile_id = self._tile_identifier(gy, gx)
# ul_xy is outer-edge of upper-left corner
# x/y are center of each data pixel
x_left = ul_xy[0] + gx * ts[1] * cw
x_right = x_left + ts[1] * cw
y_top = ul_xy[1] - gy * ts[0] * ch
y_bot = y_top - ts[0] * ch
x_mask = np.nonzero((x >= x_left) & (x < x_right))[0]
y_mask = np.nonzero((y > y_bot) & (y <= y_top))[0]
if not x_mask.any() or not y_mask.any():
# no data in this tile
LOG.debug("Tile '%s' doesn't have any data in it", tile_id)
continue
x_slice = slice(x_mask[0], x_mask[-1] + 1) # assume it's continuous
y_slice = slice(y_mask[0], y_mask[-1] + 1)
# theoretically we can precompute the X/Y now
# instead of taking the x/y data and mapping it
# to the tile
tmp_x = np.arange(x_left + cw / 2., x_right, cw)
tmp_y = np.arange(y_top - ch / 2., y_bot, -ch)
data_x_idx_min = np.nonzero(np.isclose(tmp_x, x[x_slice.start]))[0][0]
data_x_idx_max = np.nonzero(np.isclose(tmp_x, x[x_slice.stop - 1]))[0][0]
# I have a half pixel error some where
data_y_idx_min = np.nonzero(np.isclose(tmp_y, y[y_slice.start]))[0][0]
data_y_idx_max = np.nonzero(np.isclose(tmp_y, y[y_slice.stop - 1]))[0][0]
# now put the data in the grid tile
tile_slices = (slice(data_y_idx_min, data_y_idx_max + 1),
slice(data_x_idx_min, data_x_idx_max + 1))
data_slices = (y_slice, x_slice)
tile_number = self._tile_number(gy, gx)
tile_info = TileInfo(
self.tile_count, self.image_shape, ts,
gy * ts[0], gx * ts[1], tile_id, tile_number,
tmp_x, tmp_y, self.xy_factors, tile_slices, data_slices)
self._tile_cache.append(tile_info)
yield tile_info
def _get_factor_offset_fill(input_data_arr, vmin, vmax, encoding):
dtype_str = encoding["dtype"]
dtype = np.dtype(getattr(np, dtype_str))
file_bit_depth = dtype.itemsize * 8
unsigned_in_signed = encoding.get("_Unsigned") == "true"
is_unsigned = dtype.kind == "u"
bit_depth = input_data_arr.attrs.get("bit_depth", file_bit_depth)
num_fills = 1 # future: possibly support more than one fill value
if bit_depth is None:
bit_depth = file_bit_depth
if bit_depth >= file_bit_depth:
bit_depth = file_bit_depth
else:
# don't take away from the data bit depth if there is room in
# file data type to allow for extra fill values
num_fills = 0
if is_unsigned:
# max value
fills = [2 ** file_bit_depth - 1]
elif unsigned_in_signed:
# max unsigned value is -1 as a signed int
fills = [-1]
else:
# max value
fills = [2 ** (file_bit_depth - 1) - 1]
# NOTE: AWIPS is buggy and does not properly handle both
# halves an integers data space. The below code limits
# unsigned integers to the positive half and this seems
# to work better with current AWIPS.
mx = (vmax - vmin) / (2 ** (bit_depth - 1) - 1 - num_fills)
# NOTE: This is what the line should look like if AWIPS wasn't buggy:
# mx = (vmax - vmin) / (2 ** bit_depth - 1 - num_fills)
bx = vmin
if not is_unsigned and not unsigned_in_signed:
bx += 2 ** (bit_depth - 1) * mx
return mx, bx, fills[0]
def _get_data_vmin_vmax(input_data_arr):
input_metadata = input_data_arr.attrs
valid_range = input_metadata.get("valid_range")
if valid_range:
valid_min, valid_max = valid_range
else:
valid_min = input_metadata.get("valid_min")
valid_max = input_metadata.get("valid_max")
return valid_min, valid_max
def _add_valid_ranges(data_arrs):
"""Add 'valid_range' metadata if not present.
If valid_range or valid_min/valid_max are not present in a DataArrays
metadata (``.attrs``), then lazily compute it with dask so it can be
computed later when we write tiles out.
AWIPS requires that scale_factor/add_offset/_FillValue be the **same**
for all tiles. We must do this calculation before splitting the data into
tiles otherwise the values will be different.
"""
for data_arr in data_arrs:
vmin, vmax = _get_data_vmin_vmax(data_arr)
if vmin is None:
# XXX: Do we need to handle category products here?
vmin = data_arr.min(skipna=True).data
vmax = data_arr.max(skipna=True).data
# we don't want to effect the original attrs
data_arr = data_arr.copy(deep=False)
# these are dask arrays, they need to get computed later
data_arr.attrs["valid_range"] = (vmin, vmax)
yield data_arr
class AWIPSTiledVariableDecisionTree(DecisionTree):
"""Load AWIPS-specific metadata from YAML configuration."""
def __init__(self, decision_dicts, **kwargs):
"""Initialize decision tree with specific keys to look for."""
# Fields used to match a product object to it's correct configuration
attrs = kwargs.pop("attrs",
["name",
"standard_name",
"satellite",
"sensor",
"area_id",
"units",
"reader"]
)
super(AWIPSTiledVariableDecisionTree, self).__init__(decision_dicts, attrs, **kwargs)
class NetCDFTemplate:
"""Helper class to convert a dictionary-based NetCDF template to an :class:`xarray.Dataset`."""
def __init__(self, template_dict):
"""Parse template dictionary and prepare for rendering."""
self.is_single_variable = template_dict.get("single_variable", False)
self.global_attributes = template_dict.get("global_attributes", {})
default_var_config = {
"default": {
"encoding": {"dtype": "uint16"},
}
}
self.variables = template_dict.get("variables", default_var_config)
default_coord_config = {
"default": {
"encoding": {"dtype": "uint16"},
}
}
self.coordinates = template_dict.get("coordinates", default_coord_config)
self._var_tree = AWIPSTiledVariableDecisionTree([self.variables])
self._coord_tree = AWIPSTiledVariableDecisionTree([self.coordinates])
self._filename_format_str = template_dict.get("filename")
self._str_formatter = StringFormatter()
self._template_dict = template_dict
def get_filename(self, base_dir="", **kwargs):
"""Generate output NetCDF file from metadata."""
# format the filename
if self._filename_format_str is None:
raise ValueError("Template does not have a configured "
"'filename' pattern.")
fn_format_str = os.path.join(base_dir, self._filename_format_str)
filename_parser = Parser(fn_format_str)
output_filename = filename_parser.compose(kwargs)
dirname = os.path.dirname(output_filename)
if dirname and not os.path.isdir(dirname):
LOG.info("Creating output directory: %s", dirname)
os.makedirs(dirname)
return output_filename
def get_attr_value(self, attr_name, input_metadata, value=None, raw_key=None, raw_value=None, prefix="_"):
"""Determine attribute value using the provided configuration information.
If `value` and `raw_key` are not provided, this method will search
for a method named ``<prefix><attr_name>``, which will be called with
one argument (`input_metadata`) to get the value to return. See
the documentation for the `prefix` keyword argument below for more
information.
Args:
attr_name (str): Name of the attribute whose value we are
generating.
input_metadata (dict): Dictionary of metadata from the input
DataArray and other context information. Used to provide
information to `value` or access data from using `raw_key`
if provided.
value (Any): Value to assign to this attribute. If a string, it
may be a python format string which will be provided the data
from `input_metadata`. For example, ``{name}`` will be filled
with the value for the ``"name"`` in `input_metadata`. It can
also include environment variables (ex. ``"${MY_ENV_VAR}"``)
which will be expanded. String formatting is accomplished by
the special :class:`trollsift.parser.StringFormatter` which
allows for special common conversions.
raw_key (str): Key to access value from `input_metadata`, but
without any string formatting applied to it. This allows for
metadata of non-string types to be requested.
raw_value (Any): Static hardcoded value to set this attribute
to. Overrides all other options.
prefix (str): Prefix to use when `value` and `raw_key` are
both ``None``. Default is ``"_"``. This will be used to find
custom attribute handlers in subclasses. For example, if
`value` and `raw_key` are both ``None`` and `attr_name`
is ``"my_attr"``, then the method ``self._my_attr`` will be
called as ``return self._my_attr(input_metadata)``.
See :meth:`NetCDFTemplate.render_global_attributes` for
additional information (prefix is ``"_global_"``).
"""
if raw_value is not None:
return raw_value
if raw_key is not None and raw_key in input_metadata:
value = input_metadata[raw_key]
return value
if isinstance(value, str):
try:
value = os.path.expandvars(value)
value = self._str_formatter.format(value, **input_metadata)
except (KeyError, ValueError):
LOG.debug("Can't format string '%s' with provided "
"input metadata.", value)
value = None
# raise ValueError("Can't format string '{}' with provided "
# "input metadata.".format(value))
if value is not None:
return value
meth_name = prefix + attr_name
func = getattr(self, meth_name, None)
if func is not None:
value = func(input_metadata)
if value is None:
LOG.debug("no routine matching %s", meth_name)
return value
def _render_attrs(self, attr_configs, input_metadata, prefix="_"):
attrs = {}
for attr_name, attr_config_dict in attr_configs.items():
val = self.get_attr_value(attr_name, input_metadata,
prefix=prefix, **attr_config_dict)
if val is None:
# NetCDF attributes can't have a None value
continue
attrs[attr_name] = val
return attrs
def _render_global_attributes(self, input_metadata):
attr_configs = self.global_attributes
return self._render_attrs(attr_configs, input_metadata,
prefix="_global_")
def _render_variable_attributes(self, var_config, input_metadata):
attr_configs = var_config["attributes"]
var_attrs = self._render_attrs(attr_configs, input_metadata, prefix="_data_")
return var_attrs
def _render_coordinate_attributes(self, coord_config, input_metadata):
attr_configs = coord_config["attributes"]
coord_attrs = self._render_attrs(attr_configs, input_metadata, prefix="_coord_")
return coord_attrs
def _render_variable_encoding(self, var_config, input_data_arr):
new_encoding = input_data_arr.encoding.copy()
# determine fill value and
if "encoding" in var_config:
new_encoding.update(var_config["encoding"])
if "dtype" not in new_encoding:
new_encoding["dtype"] = "int16"
new_encoding["_Unsigned"] = "true"
return new_encoding
def _render_variable(self, data_arr):
var_config = self._var_tree.find_match(**data_arr.attrs)
new_var_name = var_config.get("var_name", data_arr.attrs["name"])
new_data_arr = data_arr.copy()
# remove coords which may cause issues later on
new_data_arr = new_data_arr.reset_coords(drop=True)
var_encoding = self._render_variable_encoding(var_config, data_arr)
new_data_arr.encoding = var_encoding
var_attrs = self._render_variable_attributes(var_config, data_arr.attrs)
new_data_arr.attrs = var_attrs
return new_var_name, new_data_arr
def _get_matchable_coordinate_metadata(self, coord_name, coord_attrs):
match_kwargs = {}
if "name" not in coord_attrs:
match_kwargs["name"] = coord_name
match_kwargs.update(coord_attrs)
return match_kwargs
def _render_coordinates(self, ds):
new_coords = {}
for coord_name, coord_arr in ds.coords.items():
match_kwargs = self._get_matchable_coordinate_metadata(coord_name, coord_arr.attrs)
coord_config = self._coord_tree.find_match(**match_kwargs)
coord_attrs = self._render_coordinate_attributes(coord_config, coord_arr.attrs)
coord_encoding = self._render_variable_encoding(coord_config, coord_arr)
new_coords[coord_name] = ds.coords[coord_name].copy()
new_coords[coord_name].attrs = coord_attrs
new_coords[coord_name].encoding = coord_encoding
return new_coords
def render(self, dataset_or_data_arrays, shared_attrs=None):
"""Create :class:`xarray.Dataset` from provided data."""
data_arrays = dataset_or_data_arrays
if isinstance(data_arrays, xr.Dataset):
data_arrays = data_arrays.data_vars.values()
new_ds = xr.Dataset()
for data_arr in data_arrays:
new_var_name, new_data_arr = self._render_variable(data_arr)
new_ds[new_var_name] = new_data_arr
new_coords = self._render_coordinates(new_ds)
new_ds.coords.update(new_coords)
# use first data array as "representative" for global attributes
# XXX: Should we use global attributes if dataset_or_data_arrays is a Dataset
if shared_attrs is None:
shared_attrs = data_arrays[0].attrs
new_ds.attrs = self._render_global_attributes(shared_attrs)
return new_ds
class AWIPSNetCDFTemplate(NetCDFTemplate):
"""NetCDF template renderer specifically for tiled AWIPS files."""
def __init__(self, template_dict, swap_end_time=False):
"""Handle AWIPS special cases and initialize template helpers."""
self._swap_end_time = swap_end_time
if swap_end_time:
self._swap_attributes_end_time(template_dict)
super().__init__(template_dict)
def _swap_attributes_end_time(self, template_dict):
"""Swap every use of 'start_time' to use 'end_time' instead."""
variable_attributes = [var_section["attributes"] for var_section in template_dict.get("variables", {}).values()]
global_attributes = template_dict.get("global_attributes", {})
for attr_section in variable_attributes + [global_attributes]:
for attr_name in attr_section:
attr_config = attr_section[attr_name]
if "{start_time" in attr_config.get("value", ""):
attr_config["value"] = attr_config["value"].replace("{start_time", "{end_time")
if attr_config.get("raw_key", "") == "start_time":
attr_config["raw_key"] = "end_time"
def _data_units(self, input_metadata):
units = input_metadata.get("units", "1")
# we *know* AWIPS can't handle some units
return UNIT_CONV.get(units, units)
def _global_start_date_time(self, input_metadata):
start_time = input_metadata["start_time"]
if self._swap_end_time:
start_time = input_metadata["end_time"]
return start_time.strftime("%Y-%m-%dT%H:%M:%S")
def _global_awips_id(self, input_metadata):
return "AWIPS_" + input_metadata["name"]
def _global_physical_element(self, input_metadata):
var_config = self._var_tree.find_match(**input_metadata)
attr_config = {"physical_element": var_config["attributes"]["physical_element"]}
result = self._render_attrs(attr_config, input_metadata, prefix="_data_")
return result["physical_element"]
def _global_production_location(self, input_metadata):
"""Get default global production_location attribute."""
del input_metadata
org = os.environ.get("ORGANIZATION", None)
if org is not None:
prod_location = org
else:
LOG.warning("environment ORGANIZATION not set for .production_location attribute, using hostname")
import socket
prod_location = socket.gethostname() # FUTURE: something more correct but this will do for now
if len(prod_location) > 31:
warnings.warn(
"Production location attribute is longer than 31 "
"characters (AWIPS limit). Set it to a smaller "
"value with the 'ORGANIZATION' environment "
"variable. Defaults to hostname and is currently "
"set to '{}'.".format(prod_location),
stacklevel=2
)
prod_location = prod_location[:31]
return prod_location
_global_production_site = _global_production_location
@staticmethod
def _get_vmin_vmax(var_config, input_data_arr):
if "valid_range" in var_config:
return var_config["valid_range"]
data_vmin, data_vmax = _get_data_vmin_vmax(input_data_arr)
return data_vmin, data_vmax
def _render_variable_encoding(self, var_config, input_data_arr):
new_encoding = super()._render_variable_encoding(var_config, input_data_arr)
vmin, vmax = self._get_vmin_vmax(var_config, input_data_arr)
has_flag_meanings = "flag_meanings" in input_data_arr.attrs
is_int = np.issubdtype(input_data_arr.dtype, np.integer)
is_cat = has_flag_meanings or is_int
has_sf = new_encoding.get("scale_factor") is not None
if not has_sf and is_cat:
# AWIPS doesn't like Identity conversion so we can't have
# a factor of 1 and an offset of 0
# new_encoding['scale_factor'] = None
# new_encoding['add_offset'] = None
if "_FillValue" in input_data_arr.attrs:
new_encoding["_FillValue"] = input_data_arr.attrs["_FillValue"]
elif not has_sf and vmin is not None and vmax is not None:
# calculate scale_factor and add_offset
sf, ao, fill = _get_factor_offset_fill(
input_data_arr, vmin, vmax, new_encoding
)
# NOTE: These could be dask arrays that will be computed later
# when we go to write the files.
new_encoding["scale_factor"] = sf
new_encoding["add_offset"] = ao
new_encoding["_FillValue"] = fill
new_encoding["coordinates"] = " ".join([ele for ele in input_data_arr.dims])
return new_encoding
def _get_projection_attrs(self, area_def):
"""Assign projection attributes per CF standard."""
proj_attrs = area_def.crs.to_cf()