/
scmi.py
1180 lines (1031 loc) · 50.1 KB
/
scmi.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 SCMI AWIPS 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. Sectorized Cloud and Moisture Imagery
(SCMI) is a netcdf format accepted by AWIPS to store one image broken up
in to one or more "tiles". Once AWIPS is configured for specific products
the SCMI NetCDF backend can be used to provide compatible products to the
system. The files created by this backend are compatible with AWIPS II (AWIPS I is no
longer supported).
The SCMI writer takes remapped binary image data and creates an
AWIPS-compatible NetCDF4 file. The SCMI writer and the AWIPS client may
need to be configured to make things appear the way the user wants in
the AWIPS client. The SCMI 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 SCMI writer.
Numbered versus Lettered Grids
------------------------------
By default the SCMI 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 `scmi.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
in to 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.
"""
import os
import logging
import string
import sys
from datetime import datetime, timedelta
from netCDF4 import Dataset
import numpy as np
from pyproj import Proj
import dask.array as da
from satpy.writers import Writer, DecisionTree, Enhancer, get_enhanced_image
from pyresample.geometry import AreaDefinition
from collections import namedtuple
try:
from pyresample.utils import proj4_radius_parameters
except ImportError:
raise ImportError("SCMI Writer requires pyresample>=1.7.0")
LOG = logging.getLogger(__name__)
# AWIPS 2 seems to not like data values under 0
AWIPS_USES_NEGATIVES = False
AWIPS_DATA_DTYPE = np.int16
DEFAULT_OUTPUT_PATTERN = '{source_name}_AII_{platform_name}_{sensor}_' \
'{name}_{sector_id}_{tile_id}_' \
'{start_time:%Y%m%d_%H%M}.nc'
# misc. global attributes
SCMI_GLOBAL_ATT = dict(
satellite_id=None, # GOES-H8
pixel_y_size=None, # km
start_date_time=None, # 2015181030000, # %Y%j%H%M%S
pixel_x_size=None, # km
product_name=None, # "HFD-010-B11-M1C01",
production_location=None, # "MSC",
)
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',
'x', 'y', 'tile_slices', 'data_slices'])
XYFactors = namedtuple('XYFactors', ['mx', 'bx', 'my', 'by'])
def fix_awips_file(fn):
# hack to get files created by new NetCDF library
# versions to be read by AWIPS buggy java version
# of NetCDF
LOG.info("Modifying SCMI 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):
def __init__(self, area_definition,
tile_shape=None, tile_count=None):
self.area_definition = area_definition
self._rows = self.area_definition.y_size
self._cols = self.area_definition.x_size
# 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):
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
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):
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[1] - gd.y_size),
gd.area_extent[2] + ps_x * (imaginary_data_size[0] - gd.x_size),
gd.area_extent[3])
imaginary_grid_def = AreaDefinition(
gd.area_id,
gd.name,
gd.proj_id,
gd.proj_dict,
imaginary_data_size[1],
imaginary_data_size[0],
new_extents,
)
x, y = imaginary_grid_def.get_proj_coords()
x = x[0].squeeze() # all rows should have the same coordinates
y = y[:, 0].squeeze() # all columns should have the same coordinates
# scale the X and Y arrays to fit in the file for 16-bit integers
# AWIPS is dumb and requires the integer values to be 0, 1, 2, 3, 4
# Max value of a signed 16-bit integer is 32767 meaning
# 32768 values.
if x.shape[0] > 2**15:
# awips uses 0, 1, 2, 3 so we can't use the negative end of the variable space
raise ValueError("X variable too large for AWIPS-version of 16-bit integer space")
if y.shape[0] > 2**15:
# awips uses 0, 1, 2, 3 so we can't use the negative end of the variable space
raise ValueError("Y variable too large for AWIPS-version of 16-bit integer space")
# NetCDF library doesn't handle numpy arrays nicely anymore for some
# reason and has been masking values that shouldn't be
return np.ma.masked_array(x), np.ma.masked_array(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.min()
my = -abs(gd.pixel_size_y)
return mx, bx, my, by
def _tile_number(self, ty, tx):
# e.g.
# 001 002 003 004
# 005 006 ...
return ty * self.tile_count[1] + tx + 1
def _tile_identifier(self, ty, tx):
return "T{:03d}".format(self._tile_number(ty, tx))
def _generate_tile_info(self):
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_info = TileInfo(
tc, self.image_shape, ts,
tile_row_offset, tile_column_offset, tile_id,
tmp_x, tmp_y, tile_slices, data_slices)
self._tile_cache.append(tile_info)
yield tile_info
def __call__(self, data):
if self._tile_cache:
tile_infos = self._tile_cache
else:
tile_infos = self._generate_tile_info()
for tile_info in tile_infos:
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, tile_data
class LetteredTileGenerator(NumberedTileGenerator):
def __init__(self, area_definition, extents,
cell_size=(2000000, 2000000),
num_subtiles=None):
# (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)
super(LetteredTileGenerator, self).__init__(area_definition)
def _get_tile_properties(self, tile_shape, tile_count):
# 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_coords()
x = x[0].squeeze() # all rows should have the same coordinates
y = y[:, 0].squeeze() # all columns should have the same coordinates
ll_xy = self.ll_extents
ur_xy = 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
LOG.debug("Adjusting lettered grid by ({}, {}) so it better matches data X/Y".format(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 alpha 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]
self.my = -ch
self.by = ul_xy[1]
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):
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):
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 '{}' doesn't have any data in it".format(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.ma.arange(x_left + cw / 2., x_right, cw)
tmp_y = np.ma.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_info = TileInfo(
self.tile_count, self.image_shape, ts,
gy * ts[0], gx * ts[1], tile_id, tmp_x, tmp_y, tile_slices, data_slices)
self._tile_cache.append(tile_info)
yield tile_info
class SCMIDatasetDecisionTree(DecisionTree):
# Fields used to match a product object to it's correct configuration
def __init__(self, decision_dicts, **kwargs):
attrs = kwargs.pop('attrs',
["name",
"standard_name",
"satellite",
"instrument",
"area_id",
"units",
"reader"]
)
super(SCMIDatasetDecisionTree, self).__init__(decision_dicts, attrs, **kwargs)
class AttributeHelper(object):
"""
helper object which wraps around a HimawariScene to provide SCMI attributes
"""
def __init__(self, ds_info):
self.ds_info = ds_info
def apply_attributes(self, nc, table, prefix=''):
"""
apply fixed attributes, or look up attributes needed and apply them
"""
for name, value in sorted(table.items()):
if name in nc.ncattrs():
LOG.debug('already have a value for %s' % name)
continue
if value is not None:
setattr(nc, name, value)
else:
funcname = prefix+name # _global_ + product_tile_height
func = getattr(self, funcname, None)
if func is not None:
value = func()
if value is not None:
setattr(nc, name, value)
else:
LOG.info('no routine matching %s' % funcname)
def _scene_time(self):
return self.ds_info["start_time"] + timedelta(minutes=int(os.environ.get("DEBUG_TIME_SHIFT", 0)))
def _product_name(self):
return self.ds_info["name"]
def _global_product_name(self):
return self._product_name()
def _global_pixel_x_size(self):
return self.ds_info["area"].pixel_size_x / 1000.
def _global_pixel_y_size(self):
return self.ds_info["area"].pixel_size_y / 1000.
def _global_start_date_time(self):
when = self._scene_time()
return when.strftime('%Y-%m-%dT%H:%M:%S')
def _global_production_location(self):
org = os.environ.get('ORGANIZATION', None)
if org is not None:
return org
else:
LOG.warning('environment ORGANIZATION not set for .production_location attribute, using hostname')
import socket
return socket.gethostname() # FUTURE: something more correct but this will do for now
class NetCDFWriter(object):
"""
Write a basic NetCDF4 file with header data mapped to global attributes, and BT/ALB/RAD variables
FUTURE: optionally add time dimension (CF)
FUTURE: optionally add zenith and azimuth angles
"""
_kind = None # 'albedo', 'brightness_temp'
_band = None
_include_fgf = True
_fill_value = 0
row_dim_name, col_dim_name = 'y', 'x'
y_var_name, x_var_name = 'y', 'x'
image_var_name = 'data'
fgf_y = None
fgf_x = None
projection = None
def __init__(self, filename, include_fgf=True, ds_info=None, compress=False):
self._nc = None
self.filename = filename
self._include_fgf = include_fgf
self._compress = compress
self.helper = AttributeHelper(ds_info)
self.image_data = None
@property
def nc(self):
if self._nc is None:
self._nc = Dataset(self.filename, 'w')
return self._nc
def create_dimensions(self, lines, columns):
# Create Dimensions
_nc = self.nc
_nc.createDimension(self.row_dim_name, lines)
_nc.createDimension(self.col_dim_name, columns)
def create_variables(self, bitdepth, fill_value, scale_factor=None, add_offset=None,
valid_min=None, valid_max=None):
fgf_coords = "%s %s" % (self.y_var_name, self.x_var_name)
self.image_data = self.nc.createVariable(self.image_var_name,
AWIPS_DATA_DTYPE,
dimensions=(self.row_dim_name, self.col_dim_name),
fill_value=fill_value,
zlib=self._compress)
self.image_data.coordinates = fgf_coords
self.apply_data_attributes(bitdepth, scale_factor, add_offset,
valid_min=valid_min, valid_max=valid_max)
if self._include_fgf:
self.fgf_y = self.nc.createVariable(
self.y_var_name, 'i2', dimensions=(self.row_dim_name,), zlib=self._compress)
self.fgf_x = self.nc.createVariable(
self.x_var_name, 'i2', dimensions=(self.col_dim_name,), zlib=self._compress)
def apply_data_attributes(self, bitdepth, scale_factor, add_offset,
valid_min=None, valid_max=None):
# NOTE: grid_mapping is set by `set_projection_attrs`
self.image_data.scale_factor = np.float32(scale_factor)
self.image_data.add_offset = np.float32(add_offset)
u = self.helper.ds_info.get('units', '1')
self.image_data.units = UNIT_CONV.get(u, u)
file_bitdepth = self.image_data.dtype.itemsize * 8
is_unsigned = self.image_data.dtype.kind == 'u'
if not AWIPS_USES_NEGATIVES and not is_unsigned:
file_bitdepth -= 1
is_unsigned = True
if bitdepth >= file_bitdepth:
bitdepth = file_bitdepth
num_fills = 1
else:
bitdepth = bitdepth
num_fills = 0
if valid_min is not None and valid_max is not None:
self.image_data.valid_min = valid_min
self.image_data.valid_max = valid_max
elif not is_unsigned:
# signed data type
self.image_data.valid_min = -2**(bitdepth - 1)
# 1 less for data type (65535), another 1 less for fill value (fill value = max file value)
self.image_data.valid_max = 2**(bitdepth - 1) - 1 - num_fills
else:
# unsigned data type
self.image_data.valid_min = 0
self.image_data.valid_max = 2**bitdepth - 1 - num_fills
if "standard_name" in self.helper.ds_info:
self.image_data.standard_name = self.helper.ds_info["standard_name"]
elif self.helper.ds_info.get("standard_name") in ["reflectance", "albedo"]:
self.image_data.standard_name = "toa_bidirectional_reflectance"
else:
self.image_data.standard_name = self.helper.ds_info.get("standard_name") or ''
def set_fgf(self, x, mx, bx, y, my, by, units='meters', downsample_factor=1):
# assign values before scale factors to avoid implicit scale reversal
LOG.debug('y variable shape is {}'.format(self.fgf_y.shape))
self.fgf_y.scale_factor = np.float64(my * float(downsample_factor))
self.fgf_y.add_offset = np.float64(by)
self.fgf_y.units = units
self.fgf_y.standard_name = "projection_y_coordinate"
self.fgf_y[:] = y
self.fgf_x.scale_factor = np.float64(mx * float(downsample_factor))
self.fgf_x.add_offset = np.float64(bx)
self.fgf_x.units = units
self.fgf_x.standard_name = "projection_x_coordinate"
self.fgf_x[:] = x
def set_image_data(self, data):
LOG.debug('writing image data')
if not hasattr(data, 'mask'):
data = np.ma.masked_array(data, np.isnan(data))
# note: autoscaling will be applied to make int16
self.image_data[:, :] = np.require(data, dtype=np.float32)
def set_projection_attrs(self, area_id, proj4_info):
"""Assign projection attributes per GRB standard"""
proj4_info['a'], proj4_info['b'] = proj4_radius_parameters(proj4_info)
if proj4_info["proj"] == "geos":
p = self.projection = self.nc.createVariable("fixedgrid_projection", 'i4')
self.image_data.grid_mapping = "fixedgrid_projection"
p.short_name = area_id
p.grid_mapping_name = "geostationary"
p.sweep_angle_axis = proj4_info.get("sweep", "y")
p.perspective_point_height = proj4_info['h']
p.latitude_of_projection_origin = np.float32(0.0)
p.longitude_of_projection_origin = np.float32(proj4_info.get('lon_0', 0.0)) # is the float32 needed?
elif proj4_info["proj"] == "lcc":
p = self.projection = self.nc.createVariable("lambert_projection", 'i4')
self.image_data.grid_mapping = "lambert_projection"
p.short_name = area_id
p.grid_mapping_name = "lambert_conformal_conic"
p.standard_parallel = proj4_info["lat_0"] # How do we specify two standard parallels?
p.longitude_of_central_meridian = proj4_info["lon_0"]
p.latitude_of_projection_origin = proj4_info.get('lat_1', proj4_info['lat_0']) # Correct?
elif proj4_info['proj'] == 'stere':
p = self.projection = self.nc.createVariable("polar_projection", 'i4')
self.image_data.grid_mapping = "polar_projection"
p.short_name = area_id
p.grid_mapping_name = "polar_stereographic"
p.standard_parallel = proj4_info["lat_ts"]
p.straight_vertical_longitude_from_pole = proj4_info.get("lon_0", 0.0)
p.latitude_of_projection_origin = proj4_info["lat_0"] # ?
elif proj4_info['proj'] == 'merc':
p = self.projection = self.nc.createVariable("mercator_projection", 'i4')
self.image_data.grid_mapping = "mercator_projection"
p.short_name = area_id
p.grid_mapping_name = "mercator"
p.standard_parallel = proj4_info.get('lat_ts', proj4_info.get('lat_0', 0.0))
p.longitude_of_projection_origin = proj4_info.get("lon_0", 0.0)
else:
raise ValueError("SCMI can not handle projection '{}'".format(proj4_info['proj']))
p.semi_major_axis = np.float64(proj4_info["a"])
p.semi_minor_axis = np.float64(proj4_info["b"])
p.false_easting = np.float32(proj4_info.get("x", 0.0))
p.false_northing = np.float32(proj4_info.get("y", 0.0))
def set_global_attrs(self, physical_element, awips_id, sector_id,
creating_entity, total_tiles, total_pixels,
tile_row, tile_column, tile_height, tile_width, creator=None):
self.nc.Conventions = "CF-1.7"
if creator is None:
from satpy import __version__
self.nc.creator = "Satpy Version {} - SCMI Writer".format(__version__)
else:
self.nc.creator = creator
self.nc.creation_time = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
# name as it shows in the product browser (physicalElement)
self.nc.physical_element = physical_element
self.nc.satellite_id = creating_entity
# identifying name to match against AWIPS common descriptions (ex. "AWIPS_product_name")
self.nc.awips_id = awips_id
self.nc.sector_id = sector_id
self.nc.tile_row_offset = tile_row
self.nc.tile_column_offset = tile_column
self.nc.product_tile_height = tile_height
self.nc.product_tile_width = tile_width
self.nc.number_product_tiles = total_tiles[0] * total_tiles[1]
self.nc.product_rows = total_pixels[0]
self.nc.product_columns = total_pixels[1]
self.helper.apply_attributes(self.nc, SCMI_GLOBAL_ATT, '_global_')
def close(self):
if self._nc is not None:
self._nc.sync()
self._nc.close()
self._nc = None
class NetCDFWrapper(object):
"""Object to wrap all NetCDF data-based operations in to a single call.
This makes it possible to do SCMI writing with dask's delayed `da.store` function.
"""
def __init__(self, filename, sector_id, ds_info, awips_info,
xy_factors, tile_info, compress=False, fix_awips=False):
self.filename = filename
self.sector_id = sector_id
self.ds_info = ds_info
self.awips_info = awips_info
self.tile_info = tile_info
self.xy_factors = xy_factors
self.compress = compress
self.fix_awips = fix_awips
def __setitem__(self, key, data):
"""Write an entire tile to a file."""
if np.isnan(data).all():
LOG.info("Tile {} contains all invalid data, skipping...".format(self.filename))
return
ds_info = self.ds_info
awips_info = self.awips_info
tile_info = self.tile_info
area_def = ds_info['area']
LOG.debug("Scaling %s data to fit in netcdf file...", ds_info["name"])
bit_depth = ds_info.get("bit_depth", 16)
valid_min = ds_info.get('valid_min')
if valid_min is None:
valid_min = np.nanmin(data)
valid_max = ds_info.get('valid_max')
if valid_max is None:
valid_max = np.nanmax(data)
LOG.debug("Using product valid min {} and valid max {}".format(valid_min, valid_max))
is_cat = 'flag_meanings' in ds_info
fills, factor, offset = self._calc_factor_offset(
data=data, bitdepth=bit_depth, min=valid_min, max=valid_max, dtype=AWIPS_DATA_DTYPE, flag_meanings=is_cat)
if is_cat:
data = data.astype(AWIPS_DATA_DTYPE)
tmp_tile = np.empty(tile_info.tile_shape, dtype=data.dtype)
tmp_tile[:] = np.nan
tmp_tile[tile_info.tile_slices] = data
LOG.info("Writing tile '%s' to '%s'", self.tile_info[2], self.filename)
nc = NetCDFWriter(self.filename, ds_info=self.ds_info, compress=self.compress)
LOG.debug("Creating dimensions...")
nc.create_dimensions(tmp_tile.shape[0], tmp_tile.shape[1])
LOG.debug("Creating variables...")
nc.create_variables(bit_depth, fills[0], factor, offset)
LOG.debug("Creating global attributes...")
nc.set_global_attrs(awips_info['physical_element'],
awips_info['awips_id'], self.sector_id,
awips_info['creating_entity'],
tile_info.tile_count, tile_info.image_shape,
tile_info.tile_row_offset, tile_info.tile_column_offset,
tmp_tile.shape[0], tmp_tile.shape[1])
LOG.debug("Creating projection attributes...")
nc.set_projection_attrs(area_def.area_id, area_def.proj_dict)
LOG.debug("Writing image data...")
np.clip(tmp_tile, valid_min, valid_max, out=tmp_tile)
nc.set_image_data(tmp_tile)
LOG.debug("Writing X/Y navigation data...")
mx, bx, my, by = self.xy_factors
nc.set_fgf(tile_info.x, mx, bx, tile_info.y, my, by, units='meters')
nc.close()
if self.fix_awips:
fix_awips_file(self.filename)
def _calc_factor_offset(self, data=None, dtype=np.int16, bitdepth=None,
min=None, max=None, num_fills=1, flag_meanings=False):
if num_fills > 1:
raise NotImplementedError("More than one fill value is not implemented yet")
dtype = np.dtype(dtype)
file_bitdepth = dtype.itemsize * 8
is_unsigned = dtype.kind == 'u'
if not AWIPS_USES_NEGATIVES and not is_unsigned:
file_bitdepth -= 1
is_unsigned = True
if bitdepth is None:
bitdepth = file_bitdepth
if bitdepth >= file_bitdepth:
bitdepth = file_bitdepth
else:
# don't take away from the data bitdepth if there is room in
# file data type to allow for extra fill values
num_fills = 0
if min is None:
min = data.min()
if max is None:
max = data.max()
if not is_unsigned:
# max value
fills = [2**(file_bitdepth - 1) - 1]
else:
# max value
fills = [2**file_bitdepth - 1]
if flag_meanings:
# AWIPS doesn't like Identity conversion so we can't have
# a factor of 1 and an offset of 0
mx = 0.5
bx = 0
else:
mx = float(max - min) / (2**bitdepth - 1 - num_fills)
bx = min
if not is_unsigned:
bx += 2**(bitdepth - 1) * mx
return fills, mx, bx
class SCMIWriter(Writer):
def __init__(self, compress=False, fix_awips=False, **kwargs):
super(SCMIWriter, self).__init__(default_config_filename="writers/scmi.yaml", **kwargs)
self.keep_intermediate = False
self.overwrite_existing = True
self.scmi_sectors = self.config['sectors']
self.scmi_datasets = SCMIDatasetDecisionTree([self.config['datasets']])
self.compress = compress
self.fix_awips = fix_awips
self._fill_sector_info()
self._enhancer = None
@property
def enhancer(self):
"""Lazy loading of enhancements only if needed."""
if self._enhancer is None:
self._enhancer = Enhancer(ppp_config_dir=self.ppp_config_dir)
return self._enhancer
@classmethod
def separate_init_kwargs(cls, kwargs):
# FUTURE: Don't pass Scene.save_datasets kwargs to init and here
init_kwargs, kwargs = super(SCMIWriter, cls).separate_init_kwargs(
kwargs)
for kw in ['compress', 'fix_awips']:
if kw in kwargs:
init_kwargs[kw] = kwargs.pop(kw)
return init_kwargs, kwargs
def _fill_sector_info(self):
for sector_info in self.scmi_sectors.values():
p = Proj(sector_info['projection'])
if 'lower_left_xy' in sector_info:
sector_info['lower_left_lonlat'] = p(*sector_info['lower_left_xy'], inverse=True)
else:
sector_info['lower_left_xy'] = p(*sector_info['lower_left_lonlat'])
if 'upper_right_xy' in sector_info:
sector_info['upper_right_lonlat'] = p(*sector_info['upper_right_xy'], inverse=True)
else:
sector_info['upper_right_xy'] = p(*sector_info['upper_right_lonlat'])
def _get_sector_info(self, sector_id, lettered_grid):
try:
sector_info = self.scmi_sectors[sector_id]
except KeyError:
if lettered_grid:
raise ValueError("Unknown sector '{}'".format(sector_id))
else:
sector_info = None
return sector_info
def _get_tile_generator(self, area_def, lettered_grid, sector_id, num_subtiles, tile_size, tile_count):
sector_info = self._get_sector_info(sector_id, lettered_grid)
# Create a tile generator for this grid definition
if lettered_grid:
tile_gen = LetteredTileGenerator(
area_def,
sector_info['lower_left_xy'] + sector_info['upper_right_xy'],
cell_size=sector_info['resolution'],
)
else:
tile_gen = NumberedTileGenerator(
area_def,
tile_shape=tile_size,
tile_count=tile_count,
)
return tile_gen
def _get_awips_info(self, ds_info, source_name=None, physical_element=None):
try:
awips_info = self.scmi_datasets.find_match(**ds_info).copy()
awips_info['awips_id'] = "AWIPS_" + ds_info['name']
if not physical_element:
physical_element = awips_info.get('physical_info')
if not physical_element:
physical_element = ds_info['name']
if "{" in physical_element:
physical_element = physical_element.format(**ds_info)
awips_info['physical_element'] = physical_element
if source_name:
awips_info['source_name'] = source_name
if awips_info['source_name'] is None:
raise TypeError("'source_name' keyword must be specified")
def_ce = "{}-{}".format(ds_info["platform_name"].upper(), ds_info["sensor"].upper())
awips_info.setdefault('creating_entity', def_ce)
return awips_info
except KeyError:
LOG.error("Could not get information on dataset from backend configuration file")
raise
def _group_by_area(self, datasets):
"""Group datasets by their area."""
def _area_id(area_def):
return area_def.name + str(area_def.area_extent) + str(area_def.shape)
# get all of the datasets stored by area
area_datasets = {}
for x in datasets:
area_id = _area_id(x.attrs['area'])
area, ds_list = area_datasets.setdefault(area_id, (x.attrs['area'], []))
ds_list.append(x)
return area_datasets
def _split_rgbs(self, ds):
for component in 'RGB':
band_data = ds.sel(bands=component)
band_data.attrs['name'] += '_{}'.format(component)
band_data.attrs['valid_min'] = 0.0
band_data.attrs['valid_max'] = 1.0
yield band_data
def _enhance_and_split_rgbs(self, datasets):
new_datasets = []
for ds in datasets:
if ds.ndim == 2:
new_datasets.append(ds)
continue
elif ds.ndim > 3 or ds.ndim < 1 or (ds.ndim == 3 and 'bands' not in ds.coords):
LOG.error("Can't save datasets with more or less than 2 dimensions "
"that aren't RGBs to SCMI format: {}".format(ds.name))
else:
# this is an RGB
img = get_enhanced_image(ds.squeeze(), enhance=self.enhancer)
res_data = img.finalize(fill_value=0, dtype=np.float32)[0]
new_datasets.extend(self._split_rgbs(res_data))
return new_datasets
def save_dataset(self, dataset, **kwargs):
LOG.warning("For best performance use `save_datasets`")
return self.save_datasets([dataset], **kwargs)
def get_filename(self, area_def, tile_info, sector_id, **kwargs):
# format the filename
kwargs["start_time"] += timedelta(minutes=int(os.environ.get("DEBUG_TIME_SHIFT", 0)))
return super(SCMIWriter, self).get_filename(
area_id=area_def.area_id,
rows=area_def.y_size,
columns=area_def.x_size,
sector_id=sector_id,
tile_id=tile_info.tile_id,
**kwargs)
def check_tile_exists(self, output_filename):
if os.path.isfile(output_filename):
if not self.overwrite_existing:
LOG.error("AWIPS file already exists: %s", output_filename)
raise RuntimeError("AWIPS file already exists: %s" % (output_filename,))
else:
LOG.warning("AWIPS file already exists, will overwrite: %s", output_filename)
def save_datasets(self, datasets, sector_id=None,
source_name=None, filename=None,
tile_count=(1, 1), tile_size=None,
lettered_grid=False, num_subtiles=None,
compute=True, **kwargs):
if sector_id is None:
raise TypeError("Keyword 'sector_id' is required")
area_datasets = self._group_by_area(datasets)
sources_targets = []
for area_id, (area_def, ds_list) in area_datasets.items():
tile_gen = self._get_tile_generator(area_def, lettered_grid, sector_id, num_subtiles, tile_size, tile_count)
for dataset in self._enhance_and_split_rgbs(ds_list):
LOG.info("Preparing product %s to be written to AWIPS SCMI NetCDF file", dataset.attrs["name"])
awips_info = self._get_awips_info(dataset.attrs, source_name=source_name)
for tile_info, tmp_tile in tile_gen(dataset):
# make sure this entire tile is loaded as one single array
tmp_tile.data = tmp_tile.data.rechunk(tmp_tile.shape)
output_filename = filename or self.get_filename(area_def, tile_info, sector_id,
source_name=awips_info['source_name'],
**dataset.attrs)
self.check_tile_exists(output_filename)
nc_wrapper = NetCDFWrapper(output_filename, sector_id, dataset.attrs, awips_info,
tile_gen.xy_factors, tile_info,
compress=self.compress, fix_awips=self.fix_awips)
sources_targets.append((tmp_tile.data, nc_wrapper))
if compute and sources_targets:
# the NetCDF creation is per-file so we don't need to lock