-
Notifications
You must be signed in to change notification settings - Fork 43
/
_load_convert.py
2593 lines (2030 loc) · 94.3 KB
/
_load_convert.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
# Copyright iris-grib contributors
#
# This file is part of iris-grib and is released under the LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
"""
Module to support the loading and convertion of a GRIB2 message into
cube metadata.
"""
from argparse import Namespace
from collections import namedtuple, OrderedDict
from collections.abc import Iterable
from datetime import datetime, timedelta
import math
import warnings
import cartopy.crs as ccrs
from cf_units import CALENDAR_GREGORIAN, date2num, Unit
import numpy as np
import numpy.ma as ma
from iris.aux_factory import HybridPressureFactory, HybridHeightFactory
import iris.coord_systems as icoord_systems
from iris.coords import AuxCoord, DimCoord, CellMethod
from iris.exceptions import TranslationError
from . import grib_phenom_translation as itranslation
from .grib_phenom_translation import GRIBCode
from iris.fileformats.rules import ConversionMetadata, Factory, Reference, \
ReferenceTarget
from iris.util import _is_circular
from ._iris_mercator_support import confirm_extended_mercator_supported
from ._grib1_load_rules import grib1_convert
# Restrict the names imported from this namespace.
__all__ = ['convert']
options = Namespace(warn_on_unsupported=False,
support_hindcast_values=True)
ScanningMode = namedtuple('ScanningMode', ['i_negative',
'j_positive',
'j_consecutive',
'i_alternative'])
ProjectionCentre = namedtuple('ProjectionCentre',
['south_pole_on_projection_plane',
'bipolar_and_symmetric'])
ResolutionFlags = namedtuple('ResolutionFlags',
['i_increments_given',
'j_increments_given',
'uv_resolved'])
FixedSurface = namedtuple('FixedSurface', ['standard_name',
'long_name',
'units'])
InterpolationParameters = namedtuple('InterpolationParameters',
['interpolation_type',
'statistical_process',
'number_of_points_used'])
# Regulations 92.1.6.
_GRID_ACCURACY_IN_DEGREES = 1e-6 # 1/1,000,000 of a degree
# Reference Common Code Table C-1.
_CENTRES = {
'ecmf': 'European Centre for Medium Range Weather Forecasts'
}
# Reference Code Table 1.0
_CODE_TABLES_MISSING = 255
# UDUNITS-2 units time string. Reference GRIB2 Code Table 4.4.
_TIME_RANGE_UNITS = {
0: 'minutes',
1: 'hours',
2: 'days',
# 3: 'months', Unsupported
# 4: 'years', Unsupported
# 5: '10 years', Unsupported
# 6: '30 years', Unsupported
# 7: '100 years', Unsupported
# 8-9 Reserved
10: '3 hours',
11: '6 hours',
12: '12 hours',
13: 'seconds'
}
# Reference Code Table 4.5.
_FIXED_SURFACE = {
100: FixedSurface(None, 'pressure', 'Pa'), # Isobaric surface
103: FixedSurface(None, 'height', 'm') # Height level above ground
}
_TYPE_OF_FIXED_SURFACE_MISSING = 255
# Reference Code Table 6.0
_BITMAP_CODE_PRESENT = 0
_BITMAP_CODE_NONE = 255
# Reference Code Table 4.10.
_STATISTIC_TYPE_NAMES = {
0: 'mean',
1: 'sum',
2: 'maximum',
3: 'minimum',
6: 'standard_deviation'
}
# Reference Code Table 4.11.
_STATISTIC_TYPE_OF_TIME_INTERVAL = {
2: 'same start time of forecast, forecast time is incremented'
}
# NOTE: Our test data contains the value 2, which is all we currently support.
# The exact interpretation of this is still unclear.
# See Code Table 4.15 for full spatial processing type descriptors:
# http://apps.ecmwf.int/codes/grib/format/grib2/ctables/4/15
# InterpolationParameters(spatial process descriptor, statistical process
# (octet 35), number of points used in interpolation (octet 37))
_SPATIAL_PROCESSING_TYPES = {
0: InterpolationParameters('No interpolation', 'cell_method', 0),
1: InterpolationParameters('Bilinear interpolation', None, 4),
2: InterpolationParameters('Bicubic interpolation', None, 4),
3: InterpolationParameters('Nearest neighbour interpolation', None, 1),
4: InterpolationParameters('Budget interpolation', None, 4),
5: InterpolationParameters('Spectral interpolation', None, 4),
6: InterpolationParameters('Neighbour-budget interpolation', None, 4)
}
# Class containing details of a probability analysis.
Probability = namedtuple('Probability',
('probability_type_name', 'threshold'))
# List of grid definition template numbers which use either (i,j) or (x,y)
# for (lat,lon)
_IJGRIDLENGTH_GDT_NUMBERS = (10,)
_XYGRIDLENGTH_GDT_NUMBERS = (20, 30, 31, 110, 140)
# Regulation 92.1.12
def unscale(value, factor):
"""
Implements Regulation 92.1.12.
Args:
* value:
Scaled value or sequence of scaled values.
* factor:
Scale factor or sequence of scale factors.
Returns:
For scalar value and factor, the unscaled floating point
result is returned. If either value and/or factor are
MDI, then :data:`numpy.ma.masked` is returned.
For sequence value and factor, the unscaled floating point
:class:`numpy.ndarray` is returned. If either value and/or
factor contain MDI, then :class:`numpy.ma.core.MaskedArray`
is returned.
"""
def _unscale(v, f):
return v / 10.0 ** f
if isinstance(value, Iterable) or isinstance(factor, Iterable):
def _masker(item):
# This is a small work around for an edge case, which is not
# evident in any of our sample GRIB2 messages, where an array
# of header elements contains missing values.
# iris.fileformats.grib.message returns these as None, but they
# are wanted as a numerical masked array, so a temporary mdi
# value is used, selected from a legacy implementation of iris,
# to construct the masked array. The valure is transient, only in
# scope for this function.
numerical_mdi = 2 ** 32 - 1
item = [numerical_mdi if i is None else i for i in item]
result = ma.masked_equal(item, numerical_mdi)
if ma.count_masked(result):
# Circumvent downstream NumPy "RuntimeWarning"
# of "overflow encountered in power" in _unscale
# for data containing _MDI. Remove transient _MDI value.
result.data[result.mask] = 0
return result
value = _masker(value)
factor = _masker(factor)
result = _unscale(value, factor)
if ma.count_masked(result) == 0:
result = result.data
else:
result = ma.masked
if value != _MDI and factor != _MDI:
result = _unscale(value, factor)
return result
# Use ECCodes gribapi to recognise missing value
_MDI = None
# Non-standardised usage for negative forecast times.
def _hindcast_fix(forecast_time):
"""Return a forecast time interpreted as a possibly negative value."""
uft = np.uint32(forecast_time)
HIGHBIT = 2**30
# Workaround grib api's assumption that forecast time is positive.
# Handles correctly encoded -ve forecast times up to one -1 billion.
if 2 * HIGHBIT < uft < 3 * HIGHBIT:
original_forecast_time = forecast_time
forecast_time = -(uft - 2 * HIGHBIT)
if options.warn_on_unsupported:
msg = ('Re-interpreting large grib forecastTime '
'from {} to {}.'.format(original_forecast_time,
forecast_time))
warnings.warn(msg)
return forecast_time
def fixup_float32_from_int32(value):
"""
Workaround for use when reading an IEEE 32-bit floating-point value
which the ECMWF GRIB API has erroneously treated as a 4-byte signed
integer.
"""
# Convert from two's complement to sign-and-magnitude.
# NB. The bit patterns 0x00000000 and 0x80000000 will both be
# returned by the ECMWF GRIB API as an integer 0. Because they
# correspond to positive and negative zero respectively it is safe
# to treat an integer 0 as a positive zero.
if value < 0:
value = 0x80000000 - value
value_as_uint32 = np.array(value, dtype='u4')
value_as_float32 = value_as_uint32.view(dtype='f4')
return float(value_as_float32)
def fixup_int32_from_uint32(value):
"""
Workaround for use when reading a signed, 4-byte integer which the
ECMWF GRIB API has erroneously treated as an unsigned, 4-byte
integer.
NB. This workaround is safe to use with values which are already
treated as signed, 4-byte integers.
"""
if value >= 0x80000000:
value = 0x80000000 - value
return value
###############################################################################
#
# Identification Section 1
#
###############################################################################
def reference_time_coord(section):
"""
Translate section 1 reference time according to its significance.
Reference section 1, year octets 13-14, month octet 15, day octet 16,
hour octet 17, minute octet 18, second octet 19.
Returns:
The scalar reference time :class:`iris.coords.DimCoord`.
"""
# Look-up standard name by significanceOfReferenceTime.
_lookup = {0: 'forecast_reference_time',
1: 'forecast_reference_time',
2: 'time',
3: 'time'}
# Calculate the reference time and units.
dt = datetime(section['year'], section['month'], section['day'],
section['hour'], section['minute'], section['second'])
# XXX Defaulting to a Gregorian calendar.
# Current GRIBAPI does not cover GRIB Section 1 - Octets 22-nn (optional)
# which are part of GRIB spec v12.
unit = Unit('hours since epoch', calendar=CALENDAR_GREGORIAN)
point = unit.date2num(dt)
# Reference Code Table 1.2.
significanceOfReferenceTime = section['significanceOfReferenceTime']
standard_name = _lookup.get(significanceOfReferenceTime)
if standard_name is None:
msg = 'Identificaton section 1 contains an unsupported significance ' \
'of reference time [{}]'.format(significanceOfReferenceTime)
raise TranslationError(msg)
# Create the associated reference time of data coordinate.
coord = DimCoord(point, standard_name=standard_name, units=unit)
return coord
###############################################################################
#
# Grid Definition Section 3
#
###############################################################################
def projection_centre(projectionCentreFlag):
"""
Translate the projection centre flag bitmask.
Reference GRIB2 Flag Table 3.5.
Args:
* projectionCentreFlag
Message section 3, coded key value.
Returns:
A :class:`collections.namedtuple` representation.
"""
south_pole_on_projection_plane = bool(projectionCentreFlag & 0x80)
bipolar_and_symmetric = bool(projectionCentreFlag & 0x40)
return ProjectionCentre(south_pole_on_projection_plane,
bipolar_and_symmetric)
def scanning_mode(scanningMode):
"""
Translate the scanning mode bitmask.
Reference GRIB2 Flag Table 3.4.
Args:
* scanningMode:
Message section 3, coded key value.
Returns:
A :class:`collections.namedtuple` representation.
"""
i_negative = bool(scanningMode & 0x80)
j_positive = bool(scanningMode & 0x40)
j_consecutive = bool(scanningMode & 0x20)
i_alternative = bool(scanningMode & 0x10)
if i_alternative:
msg = 'Grid definition section 3 contains unsupported ' \
'alternative row scanning mode'
raise TranslationError(msg)
return ScanningMode(i_negative, j_positive,
j_consecutive, i_alternative)
def resolution_flags(resolutionAndComponentFlags):
"""
Translate the resolution and component bitmask.
Reference GRIB2 Flag Table 3.3.
Args:
* resolutionAndComponentFlags:
Message section 3, coded key value.
Returns:
A :class:`collections.namedtuple` representation.
"""
i_inc_given = bool(resolutionAndComponentFlags & 0x20)
j_inc_given = bool(resolutionAndComponentFlags & 0x10)
uv_resolved = bool(resolutionAndComponentFlags & 0x08)
return ResolutionFlags(i_inc_given, j_inc_given, uv_resolved)
def ellipsoid(shapeOfTheEarth, major, minor, radius):
"""
Translate the shape of the earth to an appropriate coordinate
reference system.
For MDI set either major and minor or radius to :data:`numpy.ma.masked`
Reference GRIB2 Code Table 3.2.
Args:
* shapeOfTheEarth:
Message section 3, octet 15.
* major:
Semi-major axis of the oblate spheroid in units determined by
the shapeOfTheEarth.
* minor:
Semi-minor axis of the oblate spheroid in units determined by
the shapeOfTheEarth.
* radius:
Radius of sphere (in m).
Returns:
:class:`iris.coord_systems.CoordSystem`
"""
# Supported shapeOfTheEarth values.
if shapeOfTheEarth not in (0, 1, 2, 3, 4, 5, 6, 7):
msg = 'Grid definition section 3 contains an unsupported ' \
'shape of the earth [{}]'.format(shapeOfTheEarth)
raise TranslationError(msg)
if shapeOfTheEarth == 0:
# Earth assumed spherical with radius of 6 367 470.0m
result = icoord_systems.GeogCS(6367470)
elif shapeOfTheEarth == 1:
# Earth assumed spherical with radius specified (in m) by
# data producer.
if ma.is_masked(radius):
msg = 'Ellipsoid for shape of the earth {} requires a' \
'radius to be specified.'.format(shapeOfTheEarth)
raise ValueError(msg)
result = icoord_systems.GeogCS(radius)
elif shapeOfTheEarth == 2:
# Earth assumed oblate spheroid with size as determined by IAU in 1965.
result = icoord_systems.GeogCS(6378160, inverse_flattening=297.0)
elif shapeOfTheEarth in [3, 7]:
# Earth assumed oblate spheroid with major and minor axes
# specified (in km)/(in m) by data producer.
emsg_oblate = 'Ellipsoid for shape of the earth [{}] requires a' \
'semi-{} axis to be specified.'
if ma.is_masked(major):
raise ValueError(emsg_oblate.format(shapeOfTheEarth, 'major'))
if ma.is_masked(minor):
raise ValueError(emsg_oblate.format(shapeOfTheEarth, 'minor'))
# Check whether to convert from km to m.
if shapeOfTheEarth == 3:
major *= 1000
minor *= 1000
result = icoord_systems.GeogCS(major, minor)
elif shapeOfTheEarth == 4:
# Earth assumed oblate spheroid as defined in IAG-GRS80 model.
result = icoord_systems.GeogCS(6378137,
inverse_flattening=298.257222101)
elif shapeOfTheEarth == 5:
# Earth assumed represented by WGS84 (as used by ICAO since 1998).
result = icoord_systems.GeogCS(6378137,
inverse_flattening=298.257223563)
elif shapeOfTheEarth == 6:
# Earth assumed spherical with radius of 6 371 229.0m
result = icoord_systems.GeogCS(6371229)
return result
def ellipsoid_geometry(section):
"""
Calculated the unscaled ellipsoid major-axis, minor-axis and radius.
Args:
* section:
Dictionary of coded key/value pairs from section 3 of the message.
Returns:
Tuple containing the major-axis, minor-axis and radius.
"""
major = unscale(section['scaledValueOfEarthMajorAxis'],
section['scaleFactorOfEarthMajorAxis'])
minor = unscale(section['scaledValueOfEarthMinorAxis'],
section['scaleFactorOfEarthMinorAxis'])
radius = unscale(section['scaledValueOfRadiusOfSphericalEarth'],
section['scaleFactorOfRadiusOfSphericalEarth'])
return major, minor, radius
def _calculate_increment(first_grid_point, last_grid_point, num_intervals):
# Calculates the directional increment from the difference between
# the grid point values divided by the total number of intervals.
# Required by template 0 & 40 when no increment values are provided.
return math.fabs(last_grid_point - first_grid_point) / num_intervals
def grid_definition_template_0_and_1(section, metadata, y_name, x_name, cs):
"""
Translate templates representing regularly spaced latitude/longitude
on either a standard or rotated grid.
Updates the metadata in-place with the translations.
Args:
* section:
Dictionary of coded key/value pairs from section 3 of the message
* metadata:
:class:`collections.OrderedDict` of metadata.
* y_name:
Name of the Y coordinate, e.g. latitude or grid_latitude.
* x_name:
Name of the X coordinate, e.g. longitude or grid_longitude.
* cs:
The :class:`iris.coord_systems.CoordSystem` to use when creating
the X and Y coordinates.
"""
# Abort if this is a reduced grid, that case isn't handled yet.
if section['numberOfOctectsForNumberOfPoints'] != 0 or \
section['interpretationOfNumberOfPoints'] != 0:
msg = 'Grid definition section 3 contains unsupported ' \
'quasi-regular grid'
raise TranslationError(msg)
scan = scanning_mode(section['scanningMode'])
# Set resoultion flags
res_flags = resolution_flags(section['resolutionAndComponentFlags'])
# Calculate longitude points.
x_inc = (section['iDirectionIncrement']
if res_flags.i_increments_given
else _calculate_increment(section['longitudeOfFirstGridPoint'],
section['longitudeOfLastGridPoint'],
section['Ni'] - 1))
x_inc *= _GRID_ACCURACY_IN_DEGREES
x_offset = section['longitudeOfFirstGridPoint'] * _GRID_ACCURACY_IN_DEGREES
x_direction = -1 if scan.i_negative else 1
Ni = section['Ni']
x_points = np.arange(Ni, dtype=np.float64) * x_inc * x_direction + x_offset
# Determine whether the x-points (in degrees) are circular.
circular = _is_circular(x_points, 360.0)
# Calculate latitude points.
y_inc = (section['jDirectionIncrement']
if res_flags.j_increments_given
else _calculate_increment(section['latitudeOfFirstGridPoint'],
section['latitudeOfLastGridPoint'],
section['Nj'] - 1))
y_inc *= _GRID_ACCURACY_IN_DEGREES
y_offset = section['latitudeOfFirstGridPoint'] * _GRID_ACCURACY_IN_DEGREES
y_direction = 1 if scan.j_positive else -1
Nj = section['Nj']
y_points = np.arange(Nj, dtype=np.float64) * y_inc * y_direction + y_offset
# Create the lat/lon coordinates.
y_coord = DimCoord(y_points, standard_name=y_name, units='degrees',
coord_system=cs)
x_coord = DimCoord(x_points, standard_name=x_name, units='degrees',
coord_system=cs, circular=circular)
# Determine the lat/lon dimensions.
y_dim, x_dim = 0, 1
if scan.j_consecutive:
y_dim, x_dim = 1, 0
# Add the lat/lon coordinates to the metadata dim coords.
metadata['dim_coords_and_dims'].append((y_coord, y_dim))
metadata['dim_coords_and_dims'].append((x_coord, x_dim))
def grid_definition_template_0(section, metadata):
"""
Translate template representing regular latitude/longitude
grid (regular_ll).
Updates the metadata in-place with the translations.
Args:
* section:
Dictionary of coded key/value pairs from section 3 of the message
* metadata:
:class:`collections.OrderedDict` of metadata.
"""
# Determine the coordinate system.
major, minor, radius = ellipsoid_geometry(section)
cs = ellipsoid(section['shapeOfTheEarth'], major, minor, radius)
grid_definition_template_0_and_1(section, metadata,
'latitude', 'longitude', cs)
def grid_definition_template_1(section, metadata):
"""
Translate template representing rotated latitude/longitude grid.
Updates the metadata in-place with the translations.
Args:
* section:
Dictionary of coded key/value pairs from section 3 of the message
* metadata:
:class:`collections.OrderedDict` of metadata.
"""
# Determine the coordinate system.
major, minor, radius = ellipsoid_geometry(section)
south_pole_lat = (section['latitudeOfSouthernPole'] *
_GRID_ACCURACY_IN_DEGREES)
south_pole_lon = (section['longitudeOfSouthernPole'] *
_GRID_ACCURACY_IN_DEGREES)
cs = icoord_systems.RotatedGeogCS(-south_pole_lat,
math.fmod(south_pole_lon + 180, 360),
section['angleOfRotation'],
ellipsoid(section['shapeOfTheEarth'],
major, minor, radius))
grid_definition_template_0_and_1(section, metadata,
'grid_latitude', 'grid_longitude', cs)
def grid_definition_template_4_and_5(section, metadata, y_name, x_name, cs):
"""
Translate template representing variable resolution latitude/longitude
and common variable resolution rotated latitude/longitude.
Updates the metadata in-place with the translations.
Args:
* section:
Dictionary of coded key/value pairs from section 3 of the message.
* metadata:
:class:`collections.OrderedDict` of metadata.
* y_name:
Name of the Y coordinate, e.g. 'latitude' or 'grid_latitude'.
* x_name:
Name of the X coordinate, e.g. 'longitude' or 'grid_longitude'.
* cs:
The :class:`iris.coord_systems.CoordSystem` to use when createing
the X and Y coordinates.
"""
# Determine the (variable) units of resolution.
key = 'basicAngleOfTheInitialProductionDomain'
basicAngleOfTheInitialProductDomain = section[key]
subdivisionsOfBasicAngle = section['subdivisionsOfBasicAngle']
if basicAngleOfTheInitialProductDomain in [0, _MDI]:
basicAngleOfTheInitialProductDomain = 1.
if subdivisionsOfBasicAngle in [0, _MDI]:
subdivisionsOfBasicAngle = 1. / _GRID_ACCURACY_IN_DEGREES
resolution = np.float64(basicAngleOfTheInitialProductDomain)
resolution /= subdivisionsOfBasicAngle
flags = resolution_flags(section['resolutionAndComponentFlags'])
# Grid Definition Template 3.4. Notes (2).
# Flag bits 3-4 are not applicable for this template.
if flags.uv_resolved and options.warn_on_unsupported:
msg = 'Unable to translate resolution and component flags.'
warnings.warn(msg)
# Calculate the latitude and longitude points.
x_points = np.array(section['longitudes'], dtype=np.float64) * resolution
y_points = np.array(section['latitudes'], dtype=np.float64) * resolution
# Determine whether the x-points (in degrees) are circular.
circular = _is_circular(x_points, 360.0)
# Create the lat/lon coordinates.
y_coord = DimCoord(y_points, standard_name=y_name, units='degrees',
coord_system=cs)
x_coord = DimCoord(x_points, standard_name=x_name, units='degrees',
coord_system=cs, circular=circular)
scan = scanning_mode(section['scanningMode'])
# Determine the lat/lon dimensions.
y_dim, x_dim = 0, 1
if scan.j_consecutive:
y_dim, x_dim = 1, 0
# Add the lat/lon coordinates to the metadata dim coords.
metadata['dim_coords_and_dims'].append((y_coord, y_dim))
metadata['dim_coords_and_dims'].append((x_coord, x_dim))
def grid_definition_template_4(section, metadata):
"""
Translate template representing variable resolution latitude/longitude.
Updates the metadata in-place with the translations.
Args:
* section:
Dictionary of coded key/value pairs from section 3 of the message.
* metadata:
:class:`collections.OrderedDict` of metadata.
"""
# Determine the coordinate system.
major, minor, radius = ellipsoid_geometry(section)
cs = ellipsoid(section['shapeOfTheEarth'], major, minor, radius)
grid_definition_template_4_and_5(section, metadata,
'latitude', 'longitude', cs)
def grid_definition_template_5(section, metadata):
"""
Translate template representing variable resolution rotated
latitude/longitude.
Updates the metadata in-place with the translations.
Args:
* section:
Dictionary of coded key/value pairs from section 3 of the message.
* metadata:
:class:`collections.OrderedDict` of metadata.
"""
# Determine the coordinate system.
major, minor, radius = ellipsoid_geometry(section)
south_pole_lat = (section['latitudeOfSouthernPole'] *
_GRID_ACCURACY_IN_DEGREES)
south_pole_lon = (section['longitudeOfSouthernPole'] *
_GRID_ACCURACY_IN_DEGREES)
cs = icoord_systems.RotatedGeogCS(-south_pole_lat,
math.fmod(south_pole_lon + 180, 360),
section['angleOfRotation'],
ellipsoid(section['shapeOfTheEarth'],
major, minor, radius))
grid_definition_template_4_and_5(section, metadata,
'grid_latitude', 'grid_longitude', cs)
def grid_definition_template_10(section, metadata):
"""
Translate template representing a Mercator grid.
Updates the metadata in-place with the translations.
Args:
* section:
Dictionary of coded key/value pairs from section 3 of the message.
* metadata:
:class:`collections.OrderedDict` of metadata.
"""
major, minor, radius = ellipsoid_geometry(section)
geog_cs = ellipsoid(section['shapeOfTheEarth'], major, minor, radius)
# standard_parallel is the latitude at which the Mercator projection
# intersects the Earth
standard_parallel = section['LaD'] * _GRID_ACCURACY_IN_DEGREES
# Check and raise a more intelligible error, if the Iris version is too old
# to support the Mercator 'standard_parallel' keyword.
confirm_extended_mercator_supported()
cs = icoord_systems.Mercator(standard_parallel=standard_parallel,
ellipsoid=geog_cs)
# Create the X and Y coordinates.
x_coord, y_coord, scan = _calculate_proj_coords_from_grid_lengths(section,
cs)
# Determine the lat/lon dimensions.
y_dim, x_dim = 0, 1
if scan.j_consecutive:
y_dim, x_dim = 1, 0
# Add the X and Y coordinates to the metadata dim coords.
metadata['dim_coords_and_dims'].append((y_coord, y_dim))
metadata['dim_coords_and_dims'].append((x_coord, x_dim))
def grid_definition_template_12(section, metadata):
"""
Translate template representing transverse Mercator.
Updates the metadata in-place with the translations.
Args:
* section:
Dictionary of coded key/value pairs from section 3 of the message.
* metadata:
:class:`collections.OrderedDict` of metadata.
"""
major, minor, radius = ellipsoid_geometry(section)
geog_cs = ellipsoid(section['shapeOfTheEarth'], major, minor, radius)
lat = section['latitudeOfReferencePoint'] * _GRID_ACCURACY_IN_DEGREES
lon = section['longitudeOfReferencePoint'] * _GRID_ACCURACY_IN_DEGREES
scale = section['scaleFactorAtReferencePoint']
# Catch bug in ECMWF GRIB API (present at 1.12.1) where the scale
# is treated as a signed, 4-byte integer.
if isinstance(scale, int):
scale = fixup_float32_from_int32(scale)
CM_TO_M = 0.01
easting = section['XR'] * CM_TO_M
northing = section['YR'] * CM_TO_M
cs = icoord_systems.TransverseMercator(lat, lon, easting, northing,
scale, geog_cs)
# Deal with bug in ECMWF GRIB API (present at 1.12.1) where these
# values are treated as unsigned, 4-byte integers.
x1 = fixup_int32_from_uint32(section['X1'])
y1 = fixup_int32_from_uint32(section['Y1'])
x2 = fixup_int32_from_uint32(section['X2'])
y2 = fixup_int32_from_uint32(section['Y2'])
# Rather unhelpfully this grid definition template seems to be
# overspecified, and thus open to inconsistency. But for determining
# the extents the X1, Y1, X2, and Y2 points have the highest
# precision, as opposed to using Di and Dj.
# Check whether Di and Dj are as consistent as possible with that
# interpretation - i.e. they are within 1cm.
def check_range(v1, v2, n, d):
min_last = v1 + (n - 1) * (d - 1)
max_last = v1 + (n - 1) * (d + 1)
if not (min_last < v2 < max_last):
raise TranslationError('Inconsistent grid definition')
check_range(x1, x2, section['Ni'], section['Di'])
check_range(y1, y2, section['Nj'], section['Dj'])
x_points = np.linspace(x1 * CM_TO_M, x2 * CM_TO_M, section['Ni'])
y_points = np.linspace(y1 * CM_TO_M, y2 * CM_TO_M, section['Nj'])
# This has only been tested with +x/+y scanning, so raise an error
# for other permutations.
scan = scanning_mode(section['scanningMode'])
if scan.i_negative:
raise TranslationError('Unsupported -x scanning')
if not scan.j_positive:
raise TranslationError('Unsupported -y scanning')
# Create the X and Y coordinates.
y_coord = DimCoord(y_points, 'projection_y_coordinate', units='m',
coord_system=cs)
x_coord = DimCoord(x_points, 'projection_x_coordinate', units='m',
coord_system=cs)
# Determine the lat/lon dimensions.
y_dim, x_dim = 0, 1
if scan.j_consecutive:
y_dim, x_dim = 1, 0
# Add the X and Y coordinates to the metadata dim coords.
metadata['dim_coords_and_dims'].append((y_coord, y_dim))
metadata['dim_coords_and_dims'].append((x_coord, x_dim))
def grid_definition_template_20(section, metadata):
"""
Translate template representing a Polar Stereographic grid.
Updates the metadata in-place with the translations.
Args:
* section:
Dictionary of coded key/value pairs from section 3 of the message.
* metadata:
:class:`collections.OrderedDict` of metadata.
"""
major, minor, radius = ellipsoid_geometry(section)
geog_cs = ellipsoid(section['shapeOfTheEarth'], major, minor, radius)
proj_centre = projection_centre(section['projectionCentreFlag'])
if proj_centre.bipolar_and_symmetric:
raise TranslationError('Bipolar and symmetric polar stereo projections'
' are not supported by the '
'grid_definition_template_20 translation.')
if proj_centre.south_pole_on_projection_plane:
central_lat = -90.
else:
central_lat = 90.
central_lon = section['orientationOfTheGrid'] * _GRID_ACCURACY_IN_DEGREES
true_scale_lat = section['LaD'] * _GRID_ACCURACY_IN_DEGREES
cs = icoord_systems.Stereographic(central_lat=central_lat,
central_lon=central_lon,
true_scale_lat=true_scale_lat,
ellipsoid=geog_cs)
x_coord, y_coord, scan = _calculate_proj_coords_from_grid_lengths(section,
cs)
# Determine the order of the dimensions.
y_dim, x_dim = 0, 1
if scan.j_consecutive:
y_dim, x_dim = 1, 0
# Add the projection coordinates to the metadata dim coords.
metadata['dim_coords_and_dims'].append((y_coord, y_dim))
metadata['dim_coords_and_dims'].append((x_coord, x_dim))
def _calculate_proj_coords_from_grid_lengths(section, cs):
# Construct the coordinate points, the start point is given in millidegrees
# but the distance measurement is in 10-3 m, so a conversion is necessary
# to find the origin in m.
# Conversion factor millimetres to metres
mm_to_m = 1e-3
if section['gridDefinitionTemplateNumber'] in _XYGRIDLENGTH_GDT_NUMBERS:
dx = section['Dx']
dy = section['Dy']
nx = section['Nx']
ny = section['Ny']
elif section['gridDefinitionTemplateNumber'] in _IJGRIDLENGTH_GDT_NUMBERS:
dx = section['Di']
dy = section['Dj']
nx = section['Ni']
ny = section['Nj']
else:
raise TranslationError('Unsupported lat-lon point parameters')
scan = scanning_mode(section['scanningMode'])
lon_0 = section['longitudeOfFirstGridPoint'] * _GRID_ACCURACY_IN_DEGREES
lat_0 = section['latitudeOfFirstGridPoint'] * _GRID_ACCURACY_IN_DEGREES
x0_m, y0_m = cs.as_cartopy_crs().transform_point(
lon_0, lat_0, ccrs.Geodetic())
dx_m = dx * mm_to_m
dy_m = dy * mm_to_m
x_dir = -1 if scan.i_negative else 1
y_dir = 1 if scan.j_positive else -1
x_points = x0_m + dx_m * x_dir * np.arange(nx, dtype=np.float64)
y_points = y0_m + dy_m * y_dir * np.arange(ny, dtype=np.float64)
# Create the dimension coordinates.
x_coord = DimCoord(x_points, standard_name='projection_x_coordinate',
units='m', coord_system=cs)
y_coord = DimCoord(y_points, standard_name='projection_y_coordinate',
units='m', coord_system=cs)
return x_coord, y_coord, scan
def grid_definition_template_30(section, metadata):
"""
Translate template representing a Lambert Conformal grid.
Updates the metadata in-place with the translations.
Args:
* section:
Dictionary of coded key/value pairs from section 3 of the message.
* metadata:
:class:`collections.OrderedDict` of metadata.
"""
major, minor, radius = ellipsoid_geometry(section)
geog_cs = ellipsoid(section['shapeOfTheEarth'], major, minor, radius)
central_latitude = section['LaD'] * _GRID_ACCURACY_IN_DEGREES
central_longitude = section['LoV'] * _GRID_ACCURACY_IN_DEGREES
false_easting = 0
false_northing = 0
secant_latitudes = (section['Latin1'] * _GRID_ACCURACY_IN_DEGREES,
section['Latin2'] * _GRID_ACCURACY_IN_DEGREES)
cs = icoord_systems.LambertConformal(central_latitude,
central_longitude,
false_easting,
false_northing,
secant_latitudes=secant_latitudes,
ellipsoid=geog_cs)
# A projection centre flag is defined for GDT30. However, we don't need to
# know which pole is in the projection plane as Cartopy handles that. The
# Other component of the projection centre flag determines if there are
# multiple projection centres. There is no support for this in Proj4 or
# Cartopy so a translation error is raised if this flag is set.
proj_centre = projection_centre(section['projectionCentreFlag'])