/
netcdfread.py
5227 lines (4076 loc) · 189 KB
/
netcdfread.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
from __future__ import print_function
from builtins import (map, range, str)
from past.builtins import basestring
import logging
import operator
import os
import re
import struct
import subprocess
import tempfile
from ast import literal_eval
from collections import OrderedDict
from copy import deepcopy
from distutils.version import LooseVersion
from functools import reduce
from pprint import pformat
import numpy
import netCDF4
from ...decorators import _manage_log_level_via_verbosity
from .. import IORead
from . import constants
_cached_temporary_files = {}
logger = logging.getLogger(__name__)
class NetCDFRead(IORead):
'''
'''
_code0 = {
# Physically meaningful and corresponding to constructs
'Cell measures variable' : 100,
'cell_measures attribute': 101,
'Bounds variable' : 200,
'bounds attribute' : 201,
'Ancillary variable': 120,
'ancillary_variables attribute': 121,
'Formula terms variable': 130,
'formula_terms attribute': 131,
'Bounds formula terms variable': 132,
'Bounds formula_terms attribute': 133,
'Auxiliary/scalar coordinate variable': 140,
'coordinates attribute': 141,
'grid mapping variable': 150,
'grid_mapping attribute' : 151,
'Grid mapping coordinate variable': 152,
'Cell method interval': 160,
'External variable': 170,
# Purely structural
'Compressed dimension': 300,
'compress attribute': 301,
'Instance dimension':310,
'instance_dimension attribute':311,
'Count dimension': 320,
'count_dimension attribute': 321,
}
_code1 = {
'is incorrectly formatted': 2,
'is not in file': 3,
'spans incorrect dimensions': 4,
'is not in file nor referenced by the external_variables global attribute': 5,
'has incompatible terms': 6,
'that spans the vertical dimension has no bounds': 7,
'that does not span the vertical dimension is inconsistent with the formula_terms of the parametric coordinate variable': 8,
'is not referenced in file': 9,
}
def cf_datum_parameters(self):
'''Datum-defining parameters names
'''
return ('earth_radius',
'geographic_crs_name',
'geoid_name',
'geopotential_datum_name',
'horizontal_datum_name',
'inverse_flattening',
'longitude_of_prime_meridian',
'prime_meridian_name',
'reference_ellipsoid_name',
'semi_major_axis',
'semi_minor_axis',
'towgs84',
)
def cf_coordinate_reference_coordinates(self):
'''Mapping of each coordinate reference canonical name to the
coordinates to which it applies. The coordinates are defined by
their standard names.
A coordinate reference canonical name is either the value of the
grid_mapping_name attribute of a grid mapping variable
(e.g. 'lambert_azimuthal_equal_area'), or the standard name of a
vertical coordinate variable with a formula_terms attribute
(e.g. ocean_sigma_coordinate').
'''
return {
'albers_conical_equal_area' : ('projection_x_coordinate',
'projection_y_coordinate',
'latitude',
'longitude',),
'azimuthal_equidistant' : ('projection_x_coordinate',
'projection_y_coordinate',
'latitude',
'longitude',),
'geostationary' : ('projection_x_coordinate',
'projection_y_coordinate',
'latitude',
'longitude',),
'lambert_azimuthal_equal_area' : ('projection_x_coordinate',
'projection_y_coordinate',
'latitude',
'longitude',),
'lambert_conformal_conic' : ('projection_x_coordinate',
'projection_y_coordinate',
'latitude',
'longitude',),
'lambert_cylindrical_equal_area' : ('projection_x_coordinate',
'projection_y_coordinate',
'latitude',
'longitude',),
'latitude_longitude' : ('latitude',
'longitude',),
'mercator' : ('projection_x_coordinate',
'projection_y_coordinate',
'latitude',
'longitude',),
'orthographic' : ('projection_x_coordinate',
'projection_y_coordinate',
'latitude',
'longitude',),
'polar_stereographic' : ('projection_x_coordinate',
'projection_y_coordinate',
'latitude',
'longitude',),
'rotated_latitude_longitude' : ('grid_latitude',
'grid_longitude',
'latitude',
'longitude',),
'sinusoidal' : ('projection_x_coordinate',
'projection_y_coordinate',
'latitude',
'longitude',),
'stereographic' : ('projection_x_coordinate',
'projection_y_coordinate',
'latitude',
'longitude',),
'transverse_mercator' : ('projection_x_coordinate',
'projection_y_coordinate',
'latitude',
'longitude',),
'vertical_perspective' : ('projection_x_coordinate',
'projection_y_coordinate',
'latitude',
'longitude',),
'atmosphere_ln_pressure_coordinate' : ('atmosphere_ln_pressure_coordinate',),
'atmosphere_sigma_coordinate' : ('atmosphere_sigma_coordinate',),
'atmosphere_hybrid_sigma_pressure_coordinate': ('atmosphere_hybrid_sigma_pressure_coordinate',),
'atmosphere_hybrid_height_coordinate' : ('atmosphere_hybrid_height_coordinate',),
'atmosphere_sleve_coordinate' : ('atmosphere_sleve_coordinate',),
'ocean_sigma_coordinate' : ('ocean_sigma_coordinate',),
'ocean_s_coordinate' : ('ocean_s_coordinate',),
'ocean_sigma_z_coordinate' : ('ocean_sigma_z_coordinate',),
'ocean_double_sigma_coordinate' : ('ocean_double_sigma_coordinate',),
}
def _is_unreferenced(self, ncvar):
'''Return True if the netCDF variable is not referenced by any other
netCDF variable.
:Parameters:
ncvar: `str`
The netCDF variable name.
:Returns:
`bool`
**Examples:**
>>> x = r._is_unreferenced('tas')
'''
return self.read_vars['references'].get(ncvar, 0) <= 0
def _reference(self, ncvar):
'''Increment by one the reference count to a netCDF variable.
:Parameters:
ncvar: `str`
The netCDF variable name.
:Returns:
`int`
The new reference count.
**Examples:**
>>> r._reference('longitude')
'''
count = self.read_vars['references'].setdefault(ncvar, 0)
count += 1
self.read_vars['references'][ncvar] = count
return count
def file_close(self):
'''Close the netCDF files that have been read.
:Returns:
`None`
'''
for nc in self.read_vars['datasets']:
nc.close()
def file_open(self, filename):
'''Open the netCDf file for reading.
:Paramters:
filename: `str`
As for the *filename* parameter for initialising a
`netCDF.Dataset` instance.
:Returns:
`netCDF4.Dataset`
A `netCDF4.Dataset` object for the file.
'''
try:
nc = netCDF4.Dataset(filename, 'r')
except RuntimeError as error:
raise RuntimeError("{}: {}".format(error, filename))
return nc
@classmethod
def cdl_to_netcdf(cls, filename):
'''TODO
'''
x = tempfile.NamedTemporaryFile(mode='wb', dir=tempfile.gettempdir(),
prefix='cfdm_', suffix='.nc')
tmpfile = x.name
# ----------------------------------------------------------------
# Need to cache the TemporaryFile object so that it doesn't get
# deleted too soon
# ----------------------------------------------------------------
_cached_temporary_files[tmpfile] = x
subprocess.run(['ncgen', '-v3', '-o', tmpfile, filename], check=True)
return tmpfile
@classmethod
def is_netcdf_file(cls, filename):
'''Return `True` if the file is a netCDF file.
Note that the file type is determined by inspecting the file's
contents and any file suffix is not not considered.
:Parameters:
filename: `str`
The name of the file.
:Returns:
`bool`
`True` if the file is netCDF, otherwise `False`
**Examples:**
>>> if NetCDFRead.is_netcdf_file(filename):
... return 'netCDF'
'''
# Assume that URLs are in netCDF format
if filename.startswith('http://'):
return True
# Read the magic number
try:
fh = open(filename, 'rb')
magic_number = struct.unpack('=L', fh.read(4))[0]
except:
magic_number = None
try:
fh.close()
except:
pass
if magic_number in (21382211, 1128547841, 1178880137,
38159427, 88491075):
return True
else:
return False
def is_cdl_file(cls, filename):
'''Return True if the file is a CDL text representation of a netCDF
file.
Note that the file type is determined by inspecting the file's
contents and any file suffix is not not considered. The file is
assumed to be a CDL file if it is a text file that starts with
"netcdf ".
.. versionaddedd:: 1.7.8
:Parameters:
filename: `str`
The name of the file.
:Returns:
`bool`
`True` if the file is CDL, otherwise `False`
**Examples:**
>>> if NetCDFRead.is_cdl_file(filename):
... return 'CDL'
'''
# Read the magic number
cdl = False
try:
fh = open(filename, 'rt')
except UnicodeDecodeError:
pass
except:
pass
else:
try:
line = fh.readline()
# Match comment and blank lines at the top of the file
while re.match('^\s*//|^\s*$', line):
line = fh.readline()
if line.startswith('netcdf '):
cdl = True
except UnicodeDecodeError:
pass
# --- End: try
try:
fh.close()
except:
pass
return cdl
def default_netCDF_fill_value(self, ncvar):
'''The default netCDF fill value for a variable.
:Parameters:
ncvar: `str`
The netCDF variable name of the variable.
:Returns:
The default fill value for the netCDF variable.
**Examples:**
>>> n.default_netCDF_fill_value('ua')
9.969209968386869e+36
'''
data_type = self.read_vars['variables'][ncvar].dtype.str[-2:]
return netCDF4.default_fillvals[data_type]
@_manage_log_level_via_verbosity
def read(self, filename, extra=None, default_version=None,
external=None, extra_read_vars=None, _scan_only=False,
verbose=None, mask=True, warnings=True,
warn_valid=False):
'''Read fields from a netCDF file on disk or from an OPeNDAP server
location.
The file may be big or little endian.
NetCDF dimension names are stored in the `ncdim` attributes of the
field's DomainAxis objects and netCDF variable names are stored in
the `ncvar` attributes of the field and its components
(coordinates, coordinate bounds, cell measures and coordinate
references, domain ancillaries, field ancillaries).
:Parameters:
filename: `str`
The file name or OPenDAP URL of the dataset.
Relative paths are allowed, and standard tilde and shell
parameter expansions are applied to the string.
*Parameter example:*
The file ``file.nc`` in the user's home directory could
be described by any of the following:
``'$HOME/file.nc'``, ``'${HOME}/file.nc'``,
``'~/file.nc'``, ``'~/tmp/../file.nc'``.
extra: sequence of `str`, optional
Create extra, independent fields from the particular types
of metadata constructs. The *extra* parameter may be one,
or a sequence, of:
========================== ================================
*extra* Metadata constructs
========================== ================================
``'field_ancillary'`` Field ancillary constructs
``'domain_ancillary'`` Domain ancillary constructs
``'dimension_coordinate'`` Dimension coordinate constructs
``'auxiliary_coordinate'`` Auxiliary coordinate constructs
``'cell_measure'`` Cell measure constructs
========================== ================================
*Parameter example:*
To create fields from auxiliary coordinate constructs:
``extra='auxiliary_coordinate'`` or
``extra=['auxiliary_coordinate']``.
*Parameter example:*
To create fields from domain ancillary and cell measure
constructs: ``extra=['domain_ancillary',
'cell_measure']``.
warnings: `bool`, optional
If False then do not print warnings when an output field
construct is incomplete due to "structural
non-CF-compliance" of the dataset. By default such
warnings are displayed.
Structural non-CF-compliance occurs when it is not
possible to unambiguously map an element of the netCDF
dataset to an element of the CF data model. Other type on
non-CF-compliance are not checked, for example, whether or
not controlled vocabularies have been adhered to is not
checked.
mask: `bool`, optional
If False then do not mask by convention when reading the
data of field or metadata constructs from disk. By default
data is masked by convention.
The masking by convention of a netCDF array depends on the
values of any of the netCDF variable attributes
``_FillValue`` and ``missing_value``,``valid_min``,
``valid_max``, ``valid_range``. See the CF conventions for
details.
.. versionadded:: 1.8.2
warn_valid: `bool`, optional
If True then print a warning for the presence of
``valid_min``, ``valid_max`` or ``valid_range`` properties
on field contructs and metadata constructs that have
data. By default no such warning is printed
"Out-of-range" data values in the file, as defined by any
of these properties, are by default automatically masked,
which may not be as intended. See the *mask* parameter for
turning off all automatic masking.
.. versionadded:: 1.8.3
:Returns:
`list`
The fields in the file.
**Examples:**
TODO
'''
# ------------------------------------------------------------
# Initialise netCDF read parameters
# ------------------------------------------------------------
self.read_vars = {
'new_dimensions': {},
'formula_terms': {},
'compression': {},
# Verbose?
'verbose': verbose,
# Warnings?
'warnings': warnings,
'dataset_compliance': {None: {'non-compliance': {}}},
'component_report' : {},
'auxiliary_coordinate' : {},
'cell_measure' : {},
'dimension_coordinate' : {},
'domain_ancillary' : {},
'domain_ancillary_key' : None,
'field_ancillary' : {},
'coordinates' : {},
'bounds': {},
# --------------------------------------------------------
# Geometry containers, keyed by their netCDF geometry
# container variable names.
# --------------------------------------------------------
'geometries': {},
'do_not_create_field': set(),
'references': {},
# --------------------------------------------------------
# External variables
# --------------------------------------------------------
# Variables listed by the global external_variables
# attribute
'external_variables': set(),
# External variables that are actually referenced from
# within the parent file
'referenced_external_variables': set(),
# --------------------------------------------------------
# Coordinate references
# --------------------------------------------------------
# Grid mapping attributes that describe horizontal datum
'datum_parameters': self.cf_datum_parameters(),
# Vertical coordinate reference constructs, keyed by the
# netCDF variable name of their parent parametric vertical
# coordinate variable.
#
# E.g. {'ocean_s_coordinate':
# <CoordinateReference: ocean_s_coordinate>}
'vertical_crs': {},
#
'version': {},
# Auto mask?
'mask': bool(mask),
# Warn for the presence of valid_[min|max|range]
# attributes?
'warn_valid': bool(warn_valid),
'valid_properties': set(('valid_min', 'valid_max', 'valid_range')),
}
g = self.read_vars
# Set versions
for version in ('1.6', '1.7', '1.8', '1.9'):
g['version'][version] = LooseVersion(version)
# ------------------------------------------------------------
# Add custom read vars
# ------------------------------------------------------------
if extra_read_vars:
g.update(deepcopy(extra_read_vars))
compression = {}
# ----------------------------------------------------------------
# Parse field parameter
# ----------------------------------------------------------------
g['get_constructs'] = {
'auxiliary_coordinate': self.implementation.get_auxiliary_coordinates,
'cell_measure' : self.implementation.get_cell_measures,
'dimension_coordinate': self.implementation.get_dimension_coordinates,
'domain_ancillary' : self.implementation.get_domain_ancillaries,
'field_ancillary' : self.implementation.get_field_ancillaries,
}
# Parse external parameter
if external:
if isinstance(external, basestring):
external = (external,)
else:
external = ()
g['external_files'] = set(external)
# Parse extra parameter
if extra:
if isinstance(extra, basestring):
field = (extra,)
for f in extra:
if f not in g['get_constructs']:
raise ValueError(
"Can't read: Bad parameter value: extra={!r}".format(
extra))
# --- End: if
g['extra'] = extra
filename = os.path.expanduser(os.path.expandvars(filename))
if os.path.isdir(filename):
raise IOError("Can't read directory {}".format(filename))
if not os.path.isfile(filename):
raise IOError("Can't read non-existent file {}".format(filename))
g['filename'] = filename
# ------------------------------------------------------------
# Open the netCDF file to be read
# ------------------------------------------------------------
nc = self.file_open(filename)
g['nc'] = nc
logger.info(
"Reading netCDF file: {}".format(filename)
) # pragma: no cover
logger.info(
" Input netCDF dataset = {}".format(nc)
) # pragma: no cover
# ----------------------------------------------------------------
# Put the file's global attributes into the global
# 'global_attributes' dictionary
# ----------------------------------------------------------------
global_attributes = {}
for attr in map(str, nc.ncattrs()):
try:
value = nc.getncattr(attr)
if isinstance(value, basestring):
try:
global_attributes[attr] = str(value)
except UnicodeEncodeError:
global_attributes[attr] = (
value.encode(errors='ignore'))
else:
global_attributes[attr] = value
except UnicodeDecodeError:
pass
# --- End: for
g['global_attributes'] = global_attributes
logger.detail(
" Global attributes:\n" +
pformat(g['global_attributes'], indent=4)
) # pragma: no cover
# ------------------------------------------------------------
# Find the CF version for the file
# ------------------------------------------------------------
# DCH ALERT: haven't yet dealt with multiple conventions! TODO
file_version = g['global_attributes'].get('Conventions', '').replace(
'CF-', '', 1)
if not file_version:
if default_version is not None:
# Assume the default version provided by the user
file_version = default_version
else:
# Assume the file has the same version of the CFDM
# implementation
file_version = self.implementation.get_cf_version()
# --- End: if
g['file_version'] = LooseVersion(file_version)
# Set minimum versions
for vn in ('1.6', '1.7', '1.8', '1.9'):
g['CF>='+vn] = (g['file_version'] >= g['version'][vn])
# ------------------------------------------------------------
# Create a dictionary keyed by netCDF variable names where
# each key's value is a dictionary of that variable's netCDF
# attributes. E.g. attributes['tas']['units']='K'
# ------------------------------------------------------------
variable_attributes = {}
variable_dimensions = {}
variable_dataset = {}
variable_filename = {}
variables = {}
for ncvar in nc.variables:
variable = nc.variables[ncvar]
variable_attributes[ncvar] = {}
for attr in map(str, variable.ncattrs()):
try:
variable_attributes[ncvar][attr] = variable.getncattr(attr)
if isinstance(variable_attributes[ncvar][attr],
basestring):
try:
variable_attributes[ncvar][attr] = (
str(variable_attributes[ncvar][attr])
)
except UnicodeEncodeError:
variable_attributes[ncvar][attr] = (
variable_attributes[ncvar][attr].encode(errors='ignore')
)
except UnicodeDecodeError:
pass
# --- End: for
variable_dimensions[ncvar] = tuple(variable.dimensions)
variable_dataset[ncvar] = nc
variable_filename[ncvar] = g['filename']
variables[ncvar] = variable
# The netCDF attributes for each variable
#
# E.g. {'grid_lon': {'standard_name': 'grid_longitude'}}
g['variable_attributes'] = variable_attributes
# The netCDF dimensions for each variable
#
# E.g. {'grid_lon_bounds': ('grid_longitude', 'bounds2')}
g['variable_dimensions'] = variable_dimensions
# The netCDF4 dataset object for each variable
g['variable_dataset'] = variable_dataset
# The name of the file containing the each variable
g['variable_filename'] = variable_filename
# The netCDF4 variable object for each variable
g['variables'] = variables
# The netCDF4 dataset objects that have been opened (i.e. the
# for parent file and any external files)
g['datasets'] = [nc]
# The names of the variable in the parent files
# (i.e. excluding any external variables)
g['internal_variables'] = set(variables)
# The netCDF dimensions of the parent file
internal_dimension_sizes = {}
for name, dimension in nc.dimensions.items():
internal_dimension_sizes[name] = dimension.size
g['internal_dimension_sizes'] = internal_dimension_sizes
logger.detail(
" netCDF dimensions:\n" +
pformat(internal_dimension_sizes, indent=4)
) # pragma: no cover
# ------------------------------------------------------------
# List variables
#
# Identify and parse all list variables
# ------------------------------------------------------------
for ncvar, dimensions in variable_dimensions.items():
if dimensions != (ncvar,):
continue
# This variable is a Unidata coordinate variable
compress = variable_attributes[ncvar].get('compress')
if compress is None:
continue
# This variable is a list variable for gathering
# arrays
self._parse_compression_gathered(ncvar, compress)
# Do not attempt to create a field from a list
# variable
g['do_not_create_field'].add(ncvar)
# ------------------------------------------------------------
# DSG variables (CF>=1.6)
#
# Identify and parse all DSG count and DSG index variables
# ------------------------------------------------------------
if g['CF>=1.6']:
featureType = g['global_attributes'].get('featureType')
if featureType is not None:
g['featureType'] = featureType
sample_dimension = None
for ncvar, attributes in variable_attributes.items():
if 'sample_dimension' not in attributes:
continue
# ------------------------------------------------
# This variable is a count variable for DSG
# contiguous ragged arrays
# ------------------------------------------------
sample_dimension = attributes['sample_dimension']
cf_compliant = self._check_sample_dimension(
ncvar,
sample_dimension)
if not cf_compliant:
sample_dimension = None
else:
element_dimension_2 = (
self._parse_ragged_contiguous_compression(
ncvar, sample_dimension))
# Do not attempt to create a field from a
# count variable
g['do_not_create_field'].add(ncvar)
# --- End: for
instance_dimension = None
for ncvar, attributes in variable_attributes.items():
if 'instance_dimension' not in attributes:
continue
# ------------------------------------------------
# This variable is an index variable for DSG
# indexed ragged arrays
# ------------------------------------------------
instance_dimension = attributes['instance_dimension']
cf_compliant = self._check_instance_dimension(
ncvar,
instance_dimension)
if not cf_compliant:
instance_dimension = None
else:
element_dimension_1 = self._parse_indexed_compression(
ncvar, instance_dimension)
# Do not attempt to create a field from a
# index variable
g['do_not_create_field'].add(ncvar)
# --- End: for
if (sample_dimension is not None and
instance_dimension is not None):
# ------------------------------------------------
# There are DSG indexed contiguous ragged arrays
# ------------------------------------------------
self._parse_indexed_contiguous_compression(
sample_dimension,
instance_dimension)
# --- End: if
# ------------------------------------------------------------
# Geometry container variables (CF>=1.8)
#
# Identify and parse all geometry container variables
# ------------------------------------------------------------
if g['CF>=1.8']:
for ncvar, attributes in variable_attributes.items():
if 'geometry' not in attributes:
continue
geometry_ncvar = attributes['geometry']
self._parse_geometry(ncvar, geometry_ncvar,
variable_attributes)
# Do not attempt to create a field construct from a
# geometry container variable
g['do_not_create_field'].add(geometry_ncvar)
# --- End: if
# ------------------------------------------------------------
# Parse external variables (CF>=1.7)
# ------------------------------------------------------------
if g['CF>=1.7']:
netcdf_external_variables = global_attributes.pop(
'external_variables', None)
parsed_external_variables = self._split_string_by_white_space(
None, netcdf_external_variables)
parsed_external_variables = self._check_external_variables(
netcdf_external_variables, parsed_external_variables)
g['external_variables'] = set(parsed_external_variables)
# Now that all of the variables have been scanned, customize
# the read parameters.
self._customize_read_vars()
if _scan_only:
return self.read_vars
# ------------------------------------------------------------
# Get external variables (CF>=1.7)
# ------------------------------------------------------------
if g['CF>=1.7']:
logger.info(
" External variables: {}".format(
sorted(g['external_variables']))
) # pragma: no cover
logger.info(
" External files : {}".format(g['external_files']),
) # pragma: no cover
if g['external_files'] and g['external_variables']:
self._get_variables_from_external_files(
netcdf_external_variables)
# --- End: if
# ------------------------------------------------------------
# Create a field from every netCDF variable (apart from
# special variables that have already been identified as such)
# ------------------------------------------------------------
all_fields = OrderedDict()
for ncvar in g['variables']:
if ncvar not in g['do_not_create_field']:
all_fields[ncvar] = self._create_field(ncvar)
# --- End: for
# ------------------------------------------------------------
# Check for unreferenced external variables (CF>=1.7)
# ------------------------------------------------------------
if g['CF>=1.7']:
unreferenced_external_variables = (
g['external_variables'].difference(
g['referenced_external_variables']))
for ncvar in unreferenced_external_variables:
self._add_message(
None, ncvar,
message=('External variable',
'is not referenced in file'),
attribute={
'external_variables': netcdf_external_variables}
)
# --- End: if
# ------------------------------------------------------------
# Discard fields created from netCDF variables that are
# referenced by other netCDF variables
# ------------------------------------------------------------
fields = OrderedDict()
for ncvar, f in all_fields.items():
if self._is_unreferenced(ncvar):
fields[ncvar] = f
# --- End: for
logger.detail(
"Referenced netCDF variables:\n " +
"\n ".join(
[ncvar for ncvar in all_fields
if not self._is_unreferenced(ncvar)]
)
) # pragma: no cover
logger.detail(
"Unreferenced netCDF variables:\n " +
"\n ".join(
[ncvar for ncvar in all_fields
if self._is_unreferenced(ncvar)]
)
) # pragma: no cover
# ------------------------------------------------------------
# If requested, reinstate fields created from netCDF variables
# that are referenced by other netCDF variables.
# ------------------------------------------------------------
if g['extra']:
fields0 = list(fields.values())
for construct_type in g['extra']:
for f in fields0:
for construct in (
g['get_constructs'][construct_type](f).values()):
ncvar = self.implementation.nc_get_variable(construct)
if ncvar not in all_fields:
continue
fields[ncvar] = all_fields[ncvar]
# --- End: if
out = [x[1] for x in sorted(fields.items())]
if warnings:
for x in out:
qq = x.dataset_compliance()
if qq:
logger.warning(
"WARNING: Field incomplete due to "
"non-CF-compliant dataset: {!s}".format(x)
)
logger.warning("Report:")
x.dataset_compliance(display=True)
# --- End: if