forked from SciTools/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpp.py
2326 lines (1914 loc) · 81.5 KB
/
pp.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
# (C) British Crown Copyright 2010 - 2019, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Provides UK Met Office Post Process (PP) format specific capabilities.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
import six
import abc
import collections
from copy import deepcopy
import operator
import os
import re
import struct
import warnings
import cf_units
import numpy as np
import numpy.ma as ma
import cftime
import dask
import dask.array as da
from iris._deprecation import warn_deprecated
from iris._lazy_data import as_concrete_data, as_lazy_data, is_lazy_data
import iris.config
import iris.fileformats.pp_load_rules
from iris.fileformats.pp_save_rules import verify
# NOTE: this is for backwards-compatitibility *ONLY*
# We could simply remove it for v2.0 ?
from iris.fileformats._pp_lbproc_pairs import (LBPROC_PAIRS,
LBPROC_MAP as lbproc_map)
import iris.fileformats.rules
import iris.coord_systems
try:
import mo_pack
except ImportError:
mo_pack = None
__all__ = ['load', 'save', 'load_cubes', 'PPField', 'as_fields',
'load_pairs_from_fields', 'save_pairs_from_cube', 'save_fields',
'STASH', 'EARTH_RADIUS']
EARTH_RADIUS = 6371229.0
PP_HEADER_DEPTH = 256
PP_WORD_DEPTH = 4
NUM_LONG_HEADERS = 45
NUM_FLOAT_HEADERS = 19
# The header definition for header release 2.
#: A list of (header_name, position_in_header(tuple of)) pairs for
#: header release 2 - using the one-based UM/FORTRAN indexing convention.
UM_HEADER_2 = [
('lbyr', (1, )),
('lbmon', (2, )),
('lbdat', (3, )),
('lbhr', (4, )),
('lbmin', (5, )),
('lbday', (6, )),
('lbyrd', (7, )),
('lbmond', (8, )),
('lbdatd', (9, )),
('lbhrd', (10, )),
('lbmind', (11, )),
('lbdayd', (12, )),
('lbtim', (13, )),
('lbft', (14, )),
('lblrec', (15, )),
('lbcode', (16, )),
('lbhem', (17, )),
('lbrow', (18, )),
('lbnpt', (19, )),
('lbext', (20, )),
('lbpack', (21, )),
('lbrel', (22, )),
('lbfc', (23, )),
('lbcfc', (24, )),
('lbproc', (25, )),
('lbvc', (26, )),
('lbrvc', (27, )),
('lbexp', (28, )),
('lbegin', (29, )),
('lbnrec', (30, )),
('lbproj', (31, )),
('lbtyp', (32, )),
('lblev', (33, )),
('lbrsvd', (34, 35, 36, 37, )),
('lbsrce', (38, )),
('lbuser', (39, 40, 41, 42, 43, 44, 45, )),
('brsvd', (46, 47, 48, 49, )),
('bdatum', (50, )),
('bacc', (51, )),
('blev', (52, )),
('brlev', (53, )),
('bhlev', (54, )),
('bhrlev', (55, )),
('bplat', (56, )),
('bplon', (57, )),
('bgor', (58, )),
('bzy', (59, )),
('bdy', (60, )),
('bzx', (61, )),
('bdx', (62, )),
('bmdi', (63, )),
('bmks', (64, )),
]
# The header definition for header release 3.
#: A list of (header_name, position_in_header(tuple of)) pairs for
#: header release 3 - using the one-based UM/FORTRAN indexing convention.
UM_HEADER_3 = [
('lbyr', (1, )),
('lbmon', (2, )),
('lbdat', (3, )),
('lbhr', (4, )),
('lbmin', (5, )),
('lbsec', (6, )),
('lbyrd', (7, )),
('lbmond', (8, )),
('lbdatd', (9, )),
('lbhrd', (10, )),
('lbmind', (11, )),
('lbsecd', (12, )),
('lbtim', (13, )),
('lbft', (14, )),
('lblrec', (15, )),
('lbcode', (16, )),
('lbhem', (17, )),
('lbrow', (18, )),
('lbnpt', (19, )),
('lbext', (20, )),
('lbpack', (21, )),
('lbrel', (22, )),
('lbfc', (23, )),
('lbcfc', (24, )),
('lbproc', (25, )),
('lbvc', (26, )),
('lbrvc', (27, )),
('lbexp', (28, )),
('lbegin', (29, )),
('lbnrec', (30, )),
('lbproj', (31, )),
('lbtyp', (32, )),
('lblev', (33, )),
('lbrsvd', (34, 35, 36, 37, )),
('lbsrce', (38, )),
('lbuser', (39, 40, 41, 42, 43, 44, 45, )),
('brsvd', (46, 47, 48, 49, )),
('bdatum', (50, )),
('bacc', (51, )),
('blev', (52, )),
('brlev', (53, )),
('bhlev', (54, )),
('bhrlev', (55, )),
('bplat', (56, )),
('bplon', (57, )),
('bgor', (58, )),
('bzy', (59, )),
('bdy', (60, )),
('bzx', (61, )),
('bdx', (62, )),
('bmdi', (63, )),
('bmks', (64, )),
]
# A map from header-release-number to header definition
UM_HEADERS = {2: UM_HEADER_2, 3: UM_HEADER_3}
# Offset value to convert from UM_HEADER positions to PP_HEADER offsets.
UM_TO_PP_HEADER_OFFSET = 1
#: A dictionary mapping IB values to their names.
EXTRA_DATA = {
1: 'x',
2: 'y',
3: 'lower_y_domain',
4: 'lower_x_domain',
5: 'upper_y_domain',
6: 'upper_x_domain',
7: 'lower_z_domain',
8: 'upper_z_domain',
10: 'field_title',
11: 'domain_title',
12: 'x_lower_bound',
13: 'x_upper_bound',
14: 'y_lower_bound',
15: 'y_upper_bound',
}
#: Maps lbuser[0] to numpy data type. "default" will be interpreted if
#: no match is found, providing a warning in such a case.
LBUSER_DTYPE_LOOKUP = {1: np.dtype('>f4'),
2: np.dtype('>i4'),
3: np.dtype('>i4'),
-1: np.dtype('>f4'),
-2: np.dtype('>i4'),
-3: np.dtype('>i4'),
'default': np.dtype('>f4'),
}
class STASH(collections.namedtuple('STASH', 'model section item')):
"""
A class to hold a single STASH code.
Create instances using:
>>> model = 1
>>> section = 2
>>> item = 3
>>> my_stash = iris.fileformats.pp.STASH(model, section, item)
Access the sub-components via:
>>> my_stash.model
1
>>> my_stash.section
2
>>> my_stash.item
3
String conversion results in the MSI format:
>>> print(iris.fileformats.pp.STASH(1, 16, 203))
m01s16i203
A stash object can be compared directly
to its string representation:
>>> iris.fileformats.pp.STASH(1, 0, 4) == 'm01s0i004'
True
"""
__slots__ = ()
def __new__(cls, model, section, item):
"""
Args:
* model
A positive integer less than 100, or None.
* section
A non-negative integer less than 100, or None.
* item
A positive integer less than 1000, or None.
"""
model = cls._validate_member('model', model, 1, 99)
section = cls._validate_member('section', section, 0, 99)
item = cls._validate_member('item', item, 1, 999)
return super(STASH, cls).__new__(cls, model, section, item)
@staticmethod
def from_msi(msi):
"""Convert a STASH code MSI string to a STASH instance."""
if not isinstance(msi, six.string_types):
raise TypeError('Expected STASH code MSI string, got %r' % (msi,))
msi_match = re.match(
'^\s*m(\d+|\?+)s(\d+|\?+)i(\d+|\?+)\s*$', msi,
re.IGNORECASE)
if msi_match is None:
raise ValueError('Expected STASH code MSI string "mXXsXXiXXX", '
'got %r' % (msi,))
return STASH(*msi_match.groups())
@staticmethod
def _validate_member(name, value, lower_limit, upper_limit):
# Returns a valid integer or None.
try:
value = int(value)
if not lower_limit <= value <= upper_limit:
value = None
except (TypeError, ValueError):
value = None
return value
def __str__(self):
model = self._format_member(self.model, 2)
section = self._format_member(self.section, 2)
item = self._format_member(self.item, 3)
return 'm{}s{}i{}'.format(model, section, item)
def _format_member(self, value, num_digits):
if value is None:
result = '?' * num_digits
else:
format_spec = '0' + str(num_digits)
result = format(value, format_spec)
return result
def lbuser3(self):
"""Return the lbuser[3] value that this stash represents."""
return (self.section or 0) * 1000 + (self.item or 0)
def lbuser6(self):
"""Return the lbuser[6] value that this stash represents."""
return self.model or 0
@property
def is_valid(self):
return '?' not in str(self)
def __hash__(self):
return super(STASH, self).__hash__()
def __eq__(self, other):
if isinstance(other, six.string_types):
return super(STASH, self).__eq__(STASH.from_msi(other))
else:
return super(STASH, self).__eq__(other)
def __ne__(self, other):
return not self.__eq__(other)
class SplittableInt(object):
"""
A class to hold integers which can easily get each decimal digit
individually.
>>> three_six_two = SplittableInt(362)
>>> print(three_six_two)
362
>>> print(three_six_two[0])
2
>>> print(three_six_two[2])
3
.. note:: No support for negative numbers
"""
def __init__(self, value, name_mapping_dict=None):
"""
Build a SplittableInt given the positive integer value provided.
Kwargs:
* name_mapping_dict - (dict)
A special mapping to provide name based access to specific integer
positions:
>>> a = SplittableInt(1234, {'hundreds': 2})
>>> print(a.hundreds)
2
>>> a.hundreds = 9
>>> print(a.hundreds)
9
>>> print(a)
1934
"""
if value < 0:
raise ValueError('Negative numbers not supported with splittable'
' integers object')
# define the name lookup first (as this is the way __setattr__ is
# plumbed)
#: A dictionary mapping special attribute names on this object
#: to the slices/indices required to access them.
self._name_lookup = name_mapping_dict or {}
self._value = value
self._calculate_str_value_from_value()
def __int__(self):
return int(self._value)
def _calculate_str_value_from_value(self):
# Reverse the string to get the appropriate index when getting the
# sliced value
self._strvalue = [int(c) for c in str(self._value)[::-1]]
# Associate the names in the lookup table to attributes
for name, index in self._name_lookup.items():
object.__setattr__(self, name, self[index])
def _calculate_value_from_str_value(self):
self._value = np.sum([10**i * val for
i, val in enumerate(self._strvalue)])
def __len__(self):
return len(self._strvalue)
def __getitem__(self, key):
try:
val = self._strvalue[key]
except IndexError:
val = 0
# if the key returns a list of values, then combine them together
# to an integer
if isinstance(val, list):
val = sum([10**i * val for i, val in enumerate(val)])
return val
def __setitem__(self, key, value):
# The setitem method has been overridden so that assignment using
# ``val[0] = 1`` style syntax updates
# the entire object appropriately.
if (not isinstance(value, int) or value < 0):
raise ValueError('Can only set %s as a positive integer value.'
% key)
if isinstance(key, slice):
if ((key.start is not None and key.start < 0) or
(key.step is not None and key.step < 0) or
(key.stop is not None and key.stop < 0)):
raise ValueError('Cannot assign a value with slice objects'
' containing negative indices.')
# calculate the current length of the value of this string
current_length = len(range(*key.indices(len(self))))
# get indices for as many digits as have been requested. Putting
# the upper limit on the number of digits at 100.
indices = range(*key.indices(100))
if len(indices) < len(str(value)):
raise ValueError('Cannot put %s into %s as it has too many'
' digits.' % (value, key))
# Iterate over each of the indices in the slice,
# zipping them together with the associated digit
for index, digit in zip(indices,
str(value).zfill(current_length)[::-1]):
# assign each digit to the associated index
self.__setitem__(index, int(digit))
else:
# If we are trying to set to an index which does not currently
# exist in _strvalue then extend it to the
# appropriate length
if (key + 1) > len(self):
new_str_value = [0] * (key + 1)
new_str_value[:len(self)] = self._strvalue
self._strvalue = new_str_value
self._strvalue[key] = value
for name, index in self._name_lookup.items():
if index == key:
object.__setattr__(self, name, value)
self._calculate_value_from_str_value()
def __setattr__(self, name, value):
# if the attribute is a special value, update the index value which
# will in turn update the attribute value
if name != '_name_lookup' and name in self._name_lookup:
self[self._name_lookup[name]] = value
else:
object.__setattr__(self, name, value)
def __str__(self):
return str(self._value)
def __repr__(self):
return 'SplittableInt(%r, name_mapping_dict=%r)' % (self._value,
self._name_lookup)
def __eq__(self, other):
result = NotImplemented
if isinstance(other, SplittableInt):
result = self._value == other._value
elif isinstance(other, int):
result = self._value == other
return result
def __ne__(self, other):
result = self.__eq__(other)
if result is not NotImplemented:
result = not result
return result
def _compare(self, other, op):
result = NotImplemented
if isinstance(other, SplittableInt):
result = op(self._value, other._value)
elif isinstance(other, int):
result = op(self._value, other)
return result
def __lt__(self, other):
return self._compare(other, operator.lt)
def __le__(self, other):
return self._compare(other, operator.le)
def __gt__(self, other):
return self._compare(other, operator.gt)
def __ge__(self, other):
return self._compare(other, operator.ge)
def _make_flag_getter(value):
def getter(self):
warn_deprecated('The `flag` attributes are deprecated - please use '
'integer bitwise operators instead.')
return int(bool(self._value & value))
return getter
def _make_flag_setter(value):
def setter(self, flag):
warn_deprecated('The `flag` attributes are deprecated - please use '
'integer bitwise operators instead.')
if not isinstance(flag, bool):
raise TypeError('Can only set bits to True or False')
if flag:
self._value |= value
else:
self._value &= ~value
return setter
class _FlagMetaclass(type):
NUM_BITS = 18
def __new__(cls, classname, bases, class_dict):
for i in range(cls.NUM_BITS):
value = 2 ** i
name = 'flag{}'.format(value)
class_dict[name] = property(_make_flag_getter(value),
_make_flag_setter(value))
class_dict['NUM_BITS'] = cls.NUM_BITS
return type.__new__(cls, classname, bases, class_dict)
class _LBProc(six.with_metaclass(_FlagMetaclass, SplittableInt)):
# Use a metaclass to define the `flag1`, `flag2`, `flag4, etc.
# properties.
def __init__(self, value):
"""
Args:
* value (int):
The initial value which will determine the flags.
"""
value = int(value)
if value < 0:
raise ValueError('Negative numbers not supported with '
'splittable integers object')
self._value = value
def __setattr__(self, name, value):
object.__setattr__(self, name, value)
def __iadd__(self, value):
self._value += value
return self
def __and__(self, value):
return self._value & value
def __iand__(self, value):
self._value &= value
return self
def __ior__(self, value):
self._value |= value
return self
def __int__(self):
return self._value
def __repr__(self):
return '_LBProc({})'.format(self._value)
def __str__(self):
return str(self._value)
class PPDataProxy(object):
"""A reference to the data payload of a single PP field."""
__slots__ = ('shape', 'src_dtype', 'path', 'offset', 'data_len',
'_lbpack', 'boundary_packing', 'mdi')
def __init__(self, shape, src_dtype, path, offset, data_len,
lbpack, boundary_packing, mdi):
self.shape = shape
self.src_dtype = src_dtype
self.path = path
self.offset = offset
self.data_len = data_len
self.lbpack = lbpack
self.boundary_packing = boundary_packing
self.mdi = mdi
# lbpack
@property
def lbpack(self):
value = self._lbpack
if not isinstance(self._lbpack, SplittableInt):
mapping = dict(n5=slice(4, None), n4=3, n3=2, n2=1, n1=0)
value = SplittableInt(self._lbpack, mapping)
return value
@lbpack.setter
def lbpack(self, value):
self._lbpack = value
@property
def dtype(self):
return self.src_dtype.newbyteorder('=')
@property
def fill_value(self):
return self.mdi
@property
def ndim(self):
return len(self.shape)
def __getitem__(self, keys):
def is_emptyslice(key):
return (isinstance(key, slice)
and isinstance(key.start, int)
and key.start == key.stop)
if any(is_emptyslice(key) for key in keys):
# Fake the result for an 'empty' slice : do not open + read the file !!
# Since "dask.array.from_array" fetches a no-data slice to 'snapshot'
# the array metadata.
target_shape = list(self.shape)
for i_dim, key in enumerate(keys):
if is_emptyslice(key):
target_shape[i_dim] = 0
data = np.zeros((1,), dtype=self.dtype)
data = np.broadcast_to(data, target_shape)
else:
with open(self.path, 'rb') as pp_file:
pp_file.seek(self.offset, os.SEEK_SET)
data_bytes = pp_file.read(self.data_len)
data = _data_bytes_to_shaped_array(data_bytes,
self.lbpack,
self.boundary_packing,
self.shape, self.src_dtype,
self.mdi)
data = data.__getitem__(keys)
return np.asanyarray(data, dtype=self.dtype)
def __repr__(self):
fmt = '<{self.__class__.__name__} shape={self.shape}' \
' src_dtype={self.dtype!r} path={self.path!r}' \
' offset={self.offset}>'
return fmt.format(self=self)
def __getstate__(self):
# Because we have __slots__, this is needed to support Pickle.dump()
return [(name, getattr(self, name)) for name in self.__slots__]
def __setstate__(self, state):
# Because we have __slots__, this is needed to support Pickle.load()
# (Use setattr, as there is no object dictionary.)
for (key, value) in state:
setattr(self, key, value)
def __eq__(self, other):
result = NotImplemented
if isinstance(other, PPDataProxy):
result = True
for attr in self.__slots__:
if getattr(self, attr) != getattr(other, attr):
result = False
break
return result
def __ne__(self, other):
result = self.__eq__(other)
if result is not NotImplemented:
result = not result
return result
def _data_bytes_to_shaped_array(data_bytes, lbpack, boundary_packing,
data_shape, data_type, mdi,
mask=None):
"""
Convert the already read binary data payload into a numpy array, unpacking
and decompressing as per the F3 specification.
"""
if lbpack.n1 in (0, 2):
data = np.frombuffer(data_bytes, dtype=data_type)
elif lbpack.n1 == 1:
if mo_pack is not None:
try:
decompress_wgdos = mo_pack.decompress_wgdos
except AttributeError:
decompress_wgdos = mo_pack.unpack_wgdos
else:
msg = 'Unpacking PP fields with LBPACK of {} ' \
'requires mo_pack to be installed'.format(lbpack.n1)
raise ValueError(msg)
data = decompress_wgdos(data_bytes, data_shape[0], data_shape[1], mdi)
elif lbpack.n1 == 4:
if mo_pack is not None and hasattr(mo_pack, 'decompress_rle'):
decompress_rle = mo_pack.decompress_rle
else:
msg = 'Unpacking PP fields with LBPACK of {} ' \
'requires mo_pack to be installed'.format(lbpack.n1)
raise ValueError(msg)
data = decompress_rle(data_bytes, data_shape[0], data_shape[1], mdi)
else:
raise iris.exceptions.NotYetImplementedError(
'PP fields with LBPACK of %s are not yet supported.' % lbpack)
# Ensure we have a writeable data buffer.
# NOTE: "data.setflags(write=True)" is not valid for numpy >= 1.16.0.
if not data.flags['WRITEABLE']:
data = data.copy()
# Ensure the data is in the native byte order
if not data.dtype.isnative:
data.byteswap(True)
data.dtype = data.dtype.newbyteorder('=')
if boundary_packing is not None:
# Convert a long string of numbers into a "lateral boundary
# condition" array, which is split into 4 quartiles, North
# East, South, West and where North and South contain the corners.
compressed_data = data
data = np.ma.masked_all(data_shape)
data.fill_value = mdi
boundary_height = boundary_packing.y_halo + boundary_packing.rim_width
boundary_width = boundary_packing.x_halo + boundary_packing.rim_width
y_height, x_width = data_shape
# The height of the east and west components.
mid_height = y_height - 2 * boundary_height
n_s_shape = boundary_height, x_width
e_w_shape = mid_height, boundary_width
# Keep track of our current position in the array.
current_posn = 0
north = compressed_data[:boundary_height*x_width]
current_posn += len(north)
data[-boundary_height:, :] = north.reshape(*n_s_shape)
east = compressed_data[current_posn:
current_posn + boundary_width * mid_height]
current_posn += len(east)
data[boundary_height:-boundary_height,
-boundary_width:] = east.reshape(*e_w_shape)
south = compressed_data[current_posn:
current_posn + boundary_height * x_width]
current_posn += len(south)
data[:boundary_height, :] = south.reshape(*n_s_shape)
west = compressed_data[current_posn:
current_posn + boundary_width * mid_height]
current_posn += len(west)
data[boundary_height:-boundary_height,
:boundary_width] = west.reshape(*e_w_shape)
elif lbpack.n2 == 2:
if mask is None:
# If we are given no mask to apply, then just return raw data, even
# though it does not have the correct shape.
# For dask-delayed loading, this means that mask, data and the
# combination can be properly handled within a dask graph.
# However, we still mask any MDI values in the array (below).
pass
else:
land_mask = mask.data.astype(np.bool)
sea_mask = ~land_mask
new_data = np.ma.masked_all(land_mask.shape)
new_data.fill_value = mdi
if lbpack.n3 == 1:
# Land mask packed data.
# Sometimes the data comes in longer than it should be (i.e. it
# looks like the compressed data is compressed, but the
# trailing data hasn't been clipped off!).
new_data[land_mask] = data[:land_mask.sum()]
elif lbpack.n3 == 2:
# Sea mask packed data.
new_data[sea_mask] = data[:sea_mask.sum()]
else:
raise ValueError('Unsupported mask compression.')
data = new_data
else:
# Reform in row-column order
data.shape = data_shape
# Mask the array
if mdi in data:
data = ma.masked_values(data, mdi, copy=False)
return data
# The special headers of the PPField classes which get some improved
# functionality
_SPECIAL_HEADERS = ('lbtim', 'lbcode', 'lbpack', 'lbproc', 'data', 'stash',
't1', 't2')
def _header_defn(release_number):
"""
Returns the zero-indexed header definition for a particular release of
a PPField.
"""
um_header = UM_HEADERS[release_number]
offset = UM_TO_PP_HEADER_OFFSET
return [(name, tuple(position - offset for position in positions))
for name, positions in um_header]
def _pp_attribute_names(header_defn):
"""
Returns the allowed attributes of a PPField:
all of the normal headers (i.e. not the _SPECIAL_HEADERS),
the _SPECIAL_HEADERS with '_' prefixed,
the possible extra data headers.
"""
normal_headers = list(name for name, positions in header_defn
if name not in _SPECIAL_HEADERS)
special_headers = list('_' + name for name in _SPECIAL_HEADERS)
extra_data = list(EXTRA_DATA.values())
special_attributes = ['_raw_header', 'raw_lbtim', 'raw_lbpack',
'boundary_packing', '_index_in_structured_load_file']
return normal_headers + special_headers + extra_data + special_attributes
class PPField(six.with_metaclass(abc.ABCMeta, object)):
"""
A generic class for PP fields - not specific to a particular
header release number.
A PPField instance can easily access the PP header "words" as attributes
with some added useful capabilities::
for field in iris.fileformats.pp.load(filename):
print(field.lbyr)
print(field.lbuser)
print(field.lbuser[0])
print(field.lbtim)
print(field.lbtim.ia)
print(field.t1)
"""
# NB. Subclasses must define the attribute HEADER_DEFN to be their
# zero-based header definition. See PPField2 and PPField3 for examples.
__slots__ = ()
def __init__(self, header=None):
# Combined header longs and floats data cache.
self._raw_header = header
self.raw_lbtim = None
self.raw_lbpack = None
self.boundary_packing = None
self._index_in_structured_load_file = None
if header is not None:
self.raw_lbtim = header[self.HEADER_DICT['lbtim'][0]]
self.raw_lbpack = header[self.HEADER_DICT['lbpack'][0]]
def __getattr__(self, key):
"""
This method supports deferred attribute creation, which offers a
significant loading optimisation, particularly when not all attributes
are referenced and therefore created on the instance.
When an 'ordinary' HEADER_DICT attribute is required, its associated
header offset is used to lookup the data value/s from the combined
header longs and floats data cache. The attribute is then set with this
value/s on the instance. Thus future lookups for this attribute will be
optimised, avoiding the __getattr__ lookup mechanism again.
When a 'special' HEADER_DICT attribute (leading underscore) is
required, its associated 'ordinary' (no leading underscore) header
offset is used to lookup the data value/s from the combined header
longs and floats data cache. The 'ordinary' attribute is then set
with this value/s on the instance. This is required as 'special'
attributes have supporting property convenience functionality base on
the attribute value e.g. see 'lbpack' and 'lbtim'. Note that, for
'special' attributes the interface is via the 'ordinary' attribute but
the underlying attribute value is stored within the 'special'
attribute.
"""
try:
loc = self.HEADER_DICT[key]
except KeyError:
if key[0] == '_' and key[1:] in self.HEADER_DICT:
# Must be a special attribute.
loc = self.HEADER_DICT[key[1:]]
else:
cls = self.__class__.__name__
msg = '{!r} object has no attribute {!r}'.format(cls, key)
raise AttributeError(msg)
if len(loc) == 1:
value = self._raw_header[loc[0]]
else:
start = loc[0]
stop = loc[-1] + 1
value = tuple(self._raw_header[start:stop])
# Now cache the attribute value on the instance.
if key[0] == '_':
# First we need to assign to the attribute so that the
# special attribute is calculated, then we retrieve it.
setattr(self, key[1:], value)
value = getattr(self, key)
else:
setattr(self, key, value)
return value
@abc.abstractproperty
def t1(self):
pass
@abc.abstractproperty
def t2(self):
pass
def __repr__(self):
"""Return a string representation of the PP field."""
# Define an ordering on the basic header names
attribute_priority_lookup = {name: loc[0] for name, loc
in self.HEADER_DEFN}
# With the attributes sorted the order will remain stable if extra
# attributes are added.
public_attribute_names = list(attribute_priority_lookup.keys()) + \
list(EXTRA_DATA.values())
self_attrs = [(name, getattr(self, name, None))
for name in public_attribute_names]
self_attrs = [pair for pair in self_attrs if pair[1] is not None]
self_attrs.append(('data', self.data))
# sort the attributes by position in the pp header followed,
# then by alphabetical order.
attributes = sorted(self_attrs, key=lambda pair:
(attribute_priority_lookup.get(pair[0], 999),
pair[0]))
return 'PP Field' + ''.join(['\n %s: %s' % (k, v)
for k, v in attributes]) + '\n'
@property
def stash(self):
"""
A stash property giving access to the associated STASH object,
now supporting __eq__
"""
if (not hasattr(self, '_stash') or
self.lbuser[6] != self._stash.lbuser6() or
self.lbuser[3] != self._stash.lbuser3()):
self._stash = STASH(self.lbuser[6], self.lbuser[3] // 1000,
self.lbuser[3] % 1000)
return self._stash
@stash.setter
def stash(self, stash):
if isinstance(stash, six.string_types):
self._stash = STASH.from_msi(stash)