-
Notifications
You must be signed in to change notification settings - Fork 279
/
saver.py
2797 lines (2428 loc) · 115 KB
/
saver.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 contributors
#
# This file is part of Iris and is released under the BSD license.
# See LICENSE in the root of the repository for full licensing details.
"""Module to support the saving of Iris cubes to a NetCDF file.
Module to support the saving of Iris cubes to a NetCDF file, also using the CF
conventions for metadata interpretation.
See : `NetCDF User's Guide <https://docs.unidata.ucar.edu/nug/current/>`_
and `netCDF4 python module <https://github.com/Unidata/netcdf4-python>`_.
Also : `CF Conventions <https://cfconventions.org/>`_.
"""
import collections
from itertools import repeat, zip_longest
import os
import os.path
import re
import string
import typing
import warnings
import cf_units
import dask
import dask.array as da
from dask.delayed import Delayed
import numpy as np
from iris._deprecation import warn_deprecated
from iris._lazy_data import _co_realise_lazy_arrays, is_lazy_data
from iris.aux_factory import (
AtmosphereSigmaFactory,
HybridHeightFactory,
HybridPressureFactory,
OceanSFactory,
OceanSg1Factory,
OceanSg2Factory,
OceanSigmaFactory,
OceanSigmaZFactory,
)
import iris.config
import iris.coord_systems
import iris.coords
from iris.coords import AncillaryVariable, AuxCoord, CellMeasure, DimCoord
import iris.exceptions
import iris.fileformats.cf
from iris.fileformats.netcdf import _dask_locks, _thread_safe_nc
import iris.io
import iris.util
import iris.warnings
# Get the logger : shared logger for all in 'iris.fileformats.netcdf'.
from . import logger
# Avoid warning about unused import.
# We could use an __all__, but we don't want to maintain one here
logger
# Standard CML spatio-temporal axis names.
SPATIO_TEMPORAL_AXES = ["t", "z", "y", "x"]
# The CF-meaningful attributes which may appear on a data variable.
_CF_ATTRS = [
"add_offset",
"ancillary_variables",
"axis",
"bounds",
"calendar",
"cell_measures",
"cell_methods",
"climatology",
"compress",
"coordinates",
"_FillValue",
"formula_terms",
"grid_mapping",
"leap_month",
"leap_year",
"long_name",
"missing_value",
"month_lengths",
"scale_factor",
"standard_error_multiplier",
"standard_name",
"units",
]
# CF attributes that should not be global.
_CF_DATA_ATTRS = [
"flag_masks",
"flag_meanings",
"flag_values",
"instance_dimension",
"missing_value",
"sample_dimension",
"standard_error_multiplier",
]
# CF attributes that should only be global.
_CF_GLOBAL_ATTRS = ["conventions", "featureType", "history", "title"]
# UKMO specific attributes that should not be global.
_UKMO_DATA_ATTRS = ["STASH", "um_stash_source", "ukmo__process_flags"]
# TODO: whenever we advance to CF-1.11 we should then discuss a completion date
# for the deprecation of Rotated Mercator in coord_systems.py and
# _nc_load_rules/helpers.py .
CF_CONVENTIONS_VERSION = "CF-1.7"
_FactoryDefn = collections.namedtuple(
"_FactoryDefn", ("primary", "std_name", "formula_terms_format")
)
_FACTORY_DEFNS = {
AtmosphereSigmaFactory: _FactoryDefn(
primary="sigma",
std_name="atmosphere_sigma_coordinate",
formula_terms_format="ptop: {pressure_at_top} sigma: {sigma} "
"ps: {surface_air_pressure}",
),
HybridHeightFactory: _FactoryDefn(
primary="delta",
std_name="atmosphere_hybrid_height_coordinate",
formula_terms_format="a: {delta} b: {sigma} orog: {orography}",
),
HybridPressureFactory: _FactoryDefn(
primary="delta",
std_name="atmosphere_hybrid_sigma_pressure_coordinate",
formula_terms_format="ap: {delta} b: {sigma} ps: {surface_air_pressure}",
),
OceanSigmaZFactory: _FactoryDefn(
primary="zlev",
std_name="ocean_sigma_z_coordinate",
formula_terms_format="sigma: {sigma} eta: {eta} depth: {depth} "
"depth_c: {depth_c} nsigma: {nsigma} zlev: {zlev}",
),
OceanSigmaFactory: _FactoryDefn(
primary="sigma",
std_name="ocean_sigma_coordinate",
formula_terms_format="sigma: {sigma} eta: {eta} depth: {depth}",
),
OceanSFactory: _FactoryDefn(
primary="s",
std_name="ocean_s_coordinate",
formula_terms_format="s: {s} eta: {eta} depth: {depth} a: {a} b: {b} "
"depth_c: {depth_c}",
),
OceanSg1Factory: _FactoryDefn(
primary="s",
std_name="ocean_s_coordinate_g1",
formula_terms_format="s: {s} c: {c} eta: {eta} depth: {depth} "
"depth_c: {depth_c}",
),
OceanSg2Factory: _FactoryDefn(
primary="s",
std_name="ocean_s_coordinate_g2",
formula_terms_format="s: {s} c: {c} eta: {eta} depth: {depth} "
"depth_c: {depth_c}",
),
}
class CFNameCoordMap:
"""Provide a simple CF name to CF coordinate mapping."""
_Map = collections.namedtuple("_Map", ["name", "coord"])
def __init__(self):
self._map = []
def append(self, name, coord):
"""Append the given name and coordinate pair to the mapping.
Parameters
----------
name :
CF name of the associated coordinate.
coord :
The coordinate of the associated CF name.
Returns
-------
None.
"""
self._map.append(CFNameCoordMap._Map(name, coord))
@property
def names(self):
"""Return all the CF names."""
return [pair.name for pair in self._map]
@property
def coords(self):
"""Return all the coordinates."""
return [pair.coord for pair in self._map]
def name(self, coord):
"""Return the CF name, given a coordinate, or None if not recognised.
Parameters
----------
coord :
The coordinate of the associated CF name.
Returns
-------
Coordinate or None.
"""
result = None
for pair in self._map:
if coord == pair.coord:
result = pair.name
break
return result
def coord(self, name):
"""Return the coordinate, given a CF name, or None if not recognised.
Parameters
----------
name :
CF name of the associated coordinate, or None if not recognised.
Returns
-------
CF name or None.
"""
result = None
for pair in self._map:
if name == pair.name:
result = pair.coord
break
return result
def _bytes_if_ascii(string):
"""Convert string to a byte string (str in py2k, bytes in py3k).
Convert the given string to a byte string (str in py2k, bytes in py3k)
if the given string can be encoded to ascii, else maintain the type
of the inputted string.
Note: passing objects without an `encode` method (such as None) will
be returned by the function unchanged.
"""
if isinstance(string, str):
try:
return string.encode(encoding="ascii")
except (AttributeError, UnicodeEncodeError):
pass
return string
def _setncattr(variable, name, attribute):
"""Put the given attribute on the given netCDF4 Data type.
Put the given attribute on the given netCDF4 Data type, casting
attributes as we go to bytes rather than unicode.
NOTE: variable needs to be a _thread_safe_nc._ThreadSafeWrapper subclass.
"""
assert hasattr(variable, "THREAD_SAFE_FLAG")
attribute = _bytes_if_ascii(attribute)
return variable.setncattr(name, attribute)
# NOTE : this matches :class:`iris.experimental.ugrid.mesh.Mesh.ELEMENTS`,
# but in the preferred order for coord/connectivity variables in the file.
MESH_ELEMENTS = ("node", "edge", "face")
class SaverFillValueWarning(iris.warnings.IrisSaverFillValueWarning):
"""Backwards compatible form of :class:`iris.warnings.IrisSaverFillValueWarning`."""
# TODO: remove at the next major release.
pass
class VariableEmulator(typing.Protocol):
"""Duck-type-hinting for a ncdata object.
https://github.com/pp-mo/ncdata
"""
_data_array: np.typing.ArrayLike
CFVariable = typing.Union[_thread_safe_nc.VariableWrapper, VariableEmulator]
class Saver:
"""A manager for saving netcdf files."""
def __init__(self, filename, netcdf_format, compute=True):
"""Manage saving netcdf files.
Parameters
----------
filename : str or netCDF4.Dataset
Name of the netCDF file to save the cube.
OR a writeable object supporting the :class:`netCF4.Dataset` api.
netcdf_format : str
Underlying netCDF file format, one of 'NETCDF4', 'NETCDF4_CLASSIC',
'NETCDF3_CLASSIC' or 'NETCDF3_64BIT'. Default is 'NETCDF4' format.
compute : bool, default=True
If ``True``, delayed variable saves will be completed on exit from the Saver
context (after first closing the target file), equivalent to
:meth:`complete()`.
If ``False``, the file is created and closed without writing the data of
variables for which the source data was lazy. These writes can be
completed later, see :meth:`delayed_completion`.
.. note::
If ``filename`` is an open dataset, rather than a filepath, then the
caller must specify ``compute=False``, **close the dataset**, and
complete delayed saving afterwards.
If ``compute`` is ``True`` in this case, an error is raised.
This is because lazy content must be written by delayed save operations,
which will only succeed if the dataset can be (re-)opened for writing.
See :func:`save`.
Returns
-------
None
Example
-------
>>> import iris
>>> from iris.fileformats.netcdf.saver import Saver
>>> cubes = iris.load(iris.sample_data_path('atlantic_profiles.nc'))
>>> with Saver("tmp.nc", "NETCDF4") as sman:
... # Iterate through the cubelist.
... for cube in cubes:
... sman.write(cube)
"""
if netcdf_format not in [
"NETCDF4",
"NETCDF4_CLASSIC",
"NETCDF3_CLASSIC",
"NETCDF3_64BIT",
]:
raise ValueError("Unknown netCDF file format, got %r" % netcdf_format)
# All persistent variables
#: CF name mapping with iris coordinates
self._name_coord_map = CFNameCoordMap()
#: Map of dimensions to characteristic coordinates with which they are identified
self._dim_names_and_coords = CFNameCoordMap()
#: List of grid mappings added to the file
self._coord_systems = []
#: A dictionary, listing dimension names and corresponding length
self._existing_dim = {}
#: A map from meshes to their actual file dimensions (names).
# NB: might not match those of the mesh, if they were 'incremented'.
self._mesh_dims = {}
#: A dictionary, mapping formula terms to owner cf variable name
self._formula_terms_cache = {}
#: Target filepath
self.filepath = None # this line just for the API page -- value is set later
#: Whether to complete delayed saves on exit.
self.compute = compute
# N.B. the file-write-lock *type* actually depends on the dask scheduler type.
#: A per-file write lock to prevent dask attempting overlapping writes.
self.file_write_lock = (
None # this line just for the API page -- value is set later
)
# A list of delayed writes for lazy saving
# a list of couples (source, target).
self._delayed_writes = []
# Detect if we were passed a pre-opened dataset (or something like one)
self._to_open_dataset = hasattr(filename, "createVariable")
if self._to_open_dataset:
# We were passed a *dataset*, so we don't open (or close) one of our own.
self._dataset = filename
if compute:
msg = (
"Cannot save to a user-provided dataset with 'compute=True'. "
"Please use 'compute=False' and complete delayed saving in the "
"calling code after the file is closed."
)
raise ValueError(msg)
# Put it inside a _thread_safe_nc wrapper to ensure thread-safety.
# Except if it already is one, since they forbid "re-wrapping".
if not hasattr(self._dataset, "THREAD_SAFE_FLAG"):
self._dataset = _thread_safe_nc.DatasetWrapper.from_existing(
self._dataset
)
# In this case the dataset gives a filepath, not the other way around.
self.filepath = self._dataset.filepath()
else:
# Given a filepath string/path : create a dataset from that
try:
self.filepath = os.path.abspath(filename)
self._dataset = _thread_safe_nc.DatasetWrapper(
self.filepath, mode="w", format=netcdf_format
)
except RuntimeError:
dir_name = os.path.dirname(self.filepath)
if not os.path.isdir(dir_name):
msg = "No such file or directory: {}".format(dir_name)
raise IOError(msg)
if not os.access(dir_name, os.R_OK | os.W_OK):
msg = "Permission denied: {}".format(self.filepath)
raise IOError(msg)
else:
raise
self.file_write_lock = _dask_locks.get_worker_lock(self.filepath)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
"""Flush any buffered data to the CF-netCDF file before closing."""
self._dataset.sync()
if not self._to_open_dataset:
# Only close if the Saver created it.
self._dataset.close()
# Complete after closing, if required
if self.compute:
self.complete()
def write(
self,
cube,
local_keys=None,
unlimited_dimensions=None,
zlib=False,
complevel=4,
shuffle=True,
fletcher32=False,
contiguous=False,
chunksizes=None,
endian="native",
least_significant_digit=None,
packing=None,
fill_value=None,
):
"""Wrap for saving cubes to a NetCDF file.
Parameters
----------
cube : :class:`iris.cube.Cube`
A :class:`iris.cube.Cube` to be saved to a netCDF file.
local_keys : iterable of str, optional
An iterable of cube attribute keys. Any cube attributes with
matching keys will become attributes on the data variable rather
than global attributes.
.. note::
Has no effect if :attr:`iris.FUTURE.save_split_attrs` is ``True``.
unlimited_dimensions : iterable of str and/or :class:`iris.coords.Coord`, optional
List of coordinate names (or coordinate objects)
corresponding to coordinate dimensions of `cube` to save with the
NetCDF dimension variable length 'UNLIMITED'. By default, no
unlimited dimensions are saved. Only the 'NETCDF4' format
supports multiple 'UNLIMITED' dimensions.
zlib : bool, default=False
If `True`, the data will be compressed in the netCDF file using
gzip compression (default `False`).
complevel : int, default=4
An integer between 1 and 9 describing the level of compression
desired (default 4). Ignored if `zlib=False`.
shuffle : bool, default=True
If `True`, the HDF5 shuffle filter will be applied before
compressing the data (default `True`). This significantly improves
compression. Ignored if `zlib=False`.
fletcher32 : bool, default=False
If `True`, the Fletcher32 HDF5 checksum algorithm is activated to
detect errors. Default `False`.
contiguous : bool, default=False
If `True`, the variable data is stored contiguously on disk.
Default `False`. Setting to `True` for a variable with an unlimited
dimension will trigger an error.
chunksizes : tuple of int, optional
Used to manually specify the HDF5 chunksizes for each dimension of
the variable. A detailed discussion of HDF chunking and I/O
performance is available
`here <https://www.unidata.ucar.edu/software/netcdf/documentation/NUG/netcdf_perf_chunking.html>`__.
Basically, you want the chunk size for each dimension to match
as closely as possible the size of the data block that users will
read from the file. `chunksizes` cannot be set if `contiguous=True`.
endian : str, default="native"
Used to control whether the data is stored in little or big endian
format on disk. Possible values are 'little', 'big' or 'native'
(default). The library will automatically handle endian conversions
when the data is read, but if the data is always going to be read
on a computer with the opposite format as the one used to create
the file, there may be some performance advantage to be gained by
setting the endian-ness.
least_significant_digit : int, optional
If `least_significant_digit` is specified, variable data will be
truncated (quantized). In conjunction with `zlib=True` this
produces 'lossy', but significantly more efficient compression. For
example, if `least_significant_digit=1`, data will be quantized
using `numpy.around(scale*data)/scale`, where `scale = 2**bits`,
and `bits` is determined so that a precision of 0.1 is retained (in
this case `bits=4`). From
`here <https://www.esrl.noaa.gov/psd/data/gridded/conventions/cdc_netcdf_standard.shtml>`__:
"least_significant_digit -- power of ten of the smallest decimal
place in unpacked data that is a reliable value". Default is
`None`, or no quantization, or 'lossless' compression.
packing : type or str or dict or list, optional
A numpy integer datatype (signed or unsigned) or a string that
describes a numpy integer dtype(i.e. 'i2', 'short', 'u4') or a
dict of packing parameters as described below. This provides
support for netCDF data packing as described
`here <https://www.unidata.ucar.edu/software/netcdf/documentation/NUG/best_practices.html#bp_Packed-Data-Values>`__.
If this argument is a type (or type string), appropriate values of
scale_factor and add_offset will be automatically calculated based
on `cube.data` and possible masking. For more control, pass a dict
with one or more of the following keys: `dtype` (required),
`scale_factor` and `add_offset`. Note that automatic calculation of
packing parameters will trigger loading of lazy data; set them
manually using a dict to avoid this. The default is `None`, in
which case the datatype is determined from the cube and no packing
will occur.
fill_value : optional
The value to use for the `_FillValue` attribute on the netCDF
variable. If `packing` is specified the value of `fill_value`
should be in the domain of the packed data.
Returns
-------
None.
Notes
-----
The `zlib`, `complevel`, `shuffle`, `fletcher32`, `contiguous`,
`chunksizes` and `endian` keywords are silently ignored for netCDF
3 files that do not use HDF5.
"""
# TODO: when iris.FUTURE.save_split_attrs defaults to True, we can deprecate the
# "local_keys" arg, and finally remove it when we finally remove the
# save_split_attrs switch.
if unlimited_dimensions is None:
unlimited_dimensions = []
cf_profile_available = iris.site_configuration.get("cf_profile") not in [
None,
False,
]
if cf_profile_available:
# Perform a CF profile of the cube. This may result in an exception
# being raised if mandatory requirements are not satisfied.
profile = iris.site_configuration["cf_profile"](cube)
# Ensure that attributes are CF compliant and if possible to make them
# compliant.
self.check_attribute_compliance(cube, cube.dtype)
for coord in cube.coords():
self.check_attribute_compliance(coord, coord.dtype)
# Get suitable dimension names.
mesh_dimensions, cube_dimensions = self._get_dim_names(cube)
# Create all the CF-netCDF data dimensions.
# Put mesh dims first, then non-mesh dims in cube-occurring order.
nonmesh_dimensions = [
dim for dim in cube_dimensions if dim not in mesh_dimensions
]
all_dimensions = mesh_dimensions + nonmesh_dimensions
self._create_cf_dimensions(cube, all_dimensions, unlimited_dimensions)
# Create the mesh components, if there is a mesh.
# We do this before creating the data-var, so that mesh vars precede
# data-vars in the file.
cf_mesh_name = self._add_mesh(cube)
# Create the associated cube CF-netCDF data variable.
cf_var_cube = self._create_cf_data_variable(
cube,
cube_dimensions,
local_keys,
zlib=zlib,
complevel=complevel,
shuffle=shuffle,
fletcher32=fletcher32,
contiguous=contiguous,
chunksizes=chunksizes,
endian=endian,
least_significant_digit=least_significant_digit,
packing=packing,
fill_value=fill_value,
)
# Associate any mesh with the data-variable.
# N.B. _add_mesh cannot do this, as we want to put mesh variables
# before data-variables in the file.
if cf_mesh_name is not None:
_setncattr(cf_var_cube, "mesh", cf_mesh_name)
_setncattr(cf_var_cube, "location", cube.location)
# Add coordinate variables.
self._add_dim_coords(cube, cube_dimensions)
# Add the auxiliary coordinate variables and associate the data
# variable to them
self._add_aux_coords(cube, cf_var_cube, cube_dimensions)
# Add the cell_measures variables and associate the data
# variable to them
self._add_cell_measures(cube, cf_var_cube, cube_dimensions)
# Add the ancillary_variables variables and associate the data variable
# to them
self._add_ancillary_variables(cube, cf_var_cube, cube_dimensions)
# Add the formula terms to the appropriate cf variables for each
# aux factory in the cube.
self._add_aux_factories(cube, cf_var_cube, cube_dimensions)
if not iris.FUTURE.save_split_attrs:
# In the "old" way, we update global attributes as we go.
# Add data variable-only attribute names to local_keys.
if local_keys is None:
local_keys = set()
else:
local_keys = set(local_keys)
local_keys.update(_CF_DATA_ATTRS, _UKMO_DATA_ATTRS)
# Add global attributes taking into account local_keys.
cube_attributes = cube.attributes
global_attributes = {
k: v
for k, v in cube_attributes.items()
if (k not in local_keys and k.lower() != "conventions")
}
self.update_global_attributes(global_attributes)
if cf_profile_available:
cf_patch = iris.site_configuration.get("cf_patch")
if cf_patch is not None:
# Perform a CF patch of the dataset.
cf_patch(profile, self._dataset, cf_var_cube)
else:
msg = "cf_profile is available but no {} defined.".format("cf_patch")
warnings.warn(msg, category=iris.warnings.IrisCfSaveWarning)
@staticmethod
def check_attribute_compliance(container, data_dtype):
"""Check attributte complliance."""
def _coerce_value(val_attr, val_attr_value, data_dtype):
val_attr_tmp = np.array(val_attr_value, dtype=data_dtype)
if (val_attr_tmp != val_attr_value).any():
msg = '"{}" is not of a suitable value ({})'
raise ValueError(msg.format(val_attr, val_attr_value))
return val_attr_tmp
# Ensure that conflicting attributes are not provided.
if (
container.attributes.get("valid_min") is not None
or container.attributes.get("valid_max") is not None
) and container.attributes.get("valid_range") is not None:
msg = (
'Both "valid_range" and "valid_min" or "valid_max" '
"attributes present."
)
raise ValueError(msg)
# Ensure correct datatype
for val_attr in ["valid_range", "valid_min", "valid_max"]:
val_attr_value = container.attributes.get(val_attr)
if val_attr_value is not None:
val_attr_value = np.asarray(val_attr_value)
if data_dtype.itemsize == 1:
# Allow signed integral type
if val_attr_value.dtype.kind == "i":
continue
new_val = _coerce_value(val_attr, val_attr_value, data_dtype)
container.attributes[val_attr] = new_val
def update_global_attributes(self, attributes=None, **kwargs):
"""Update the CF global attributes.
Update the CF global attributes based on the provided
iterable/dictionary and/or keyword arguments.
Parameters
----------
attributes : dict or iterable of key, value pairs, optional
CF global attributes to be updated.
"""
# TODO: when when iris.FUTURE.save_split_attrs is removed, this routine will
# only be called once: it can reasonably be renamed "_set_global_attributes",
# and the 'kwargs' argument can be removed.
if attributes is not None:
# Handle sequence e.g. [('fruit', 'apple'), ...].
if not hasattr(attributes, "keys"):
attributes = dict(attributes)
for attr_name in sorted(attributes):
_setncattr(self._dataset, attr_name, attributes[attr_name])
for attr_name in sorted(kwargs):
_setncattr(self._dataset, attr_name, kwargs[attr_name])
def _create_cf_dimensions(self, cube, dimension_names, unlimited_dimensions=None):
"""Create the CF-netCDF data dimensions.
Parameters
----------
cube : :class:`iris.cube.Cube`
A :class:`iris.cube.Cube` in which to lookup coordinates.
dimension_names :
unlimited_dimensions : iterable of strings and/or :class:`iris.coords.Coord` objects):
List of coordinates to make unlimited (None by default).
Returns
-------
None.
"""
unlimited_dim_names = []
if unlimited_dimensions is not None:
for coord in unlimited_dimensions:
try:
coord = cube.coord(name_or_coord=coord, dim_coords=True)
except iris.exceptions.CoordinateNotFoundError:
# coordinate isn't used for this cube, but it might be
# used for a different one
pass
else:
dim_name = self._get_coord_variable_name(cube, coord)
unlimited_dim_names.append(dim_name)
for dim_name in dimension_names:
# NOTE: these dim-names have been chosen by _get_dim_names, and
# were already checked+fixed to avoid any name collisions.
if dim_name not in self._dataset.dimensions:
if dim_name in unlimited_dim_names:
size = None
else:
size = self._existing_dim[dim_name]
self._dataset.createDimension(dim_name, size)
def _add_mesh(self, cube_or_mesh):
"""Add the cube's mesh, and all related variables to the dataset.
Add the cube's mesh, and all related variables to the dataset.
Includes all the mesh-element coordinate and connectivity variables.
.. note::
Here, we do *not* add the relevant referencing attributes to the
data-variable, because we want to create the data-variable later.
Parameters
----------
cube_or_mesh : :class:`iris.cube.Cube` or :class:`iris.experimental.ugrid.Mesh`
The Cube or Mesh being saved to the netCDF file.
Returns
-------
str or None
The name of the mesh variable created, or None if the cube does not
have a mesh.
"""
cf_mesh_name = None
# Do cube- or -mesh-based save
from iris.cube import Cube
if isinstance(cube_or_mesh, Cube):
cube = cube_or_mesh
mesh = cube.mesh
else:
cube = None # The underlying routines must support this !
mesh = cube_or_mesh
if mesh:
cf_mesh_name = self._name_coord_map.name(mesh)
if cf_mesh_name is None:
# Not already present : create it
cf_mesh_name = self._create_mesh(mesh)
self._name_coord_map.append(cf_mesh_name, mesh)
cf_mesh_var = self._dataset.variables[cf_mesh_name]
# Get the mesh-element dim names.
mesh_dims = self._mesh_dims[mesh]
# Add all the element coordinate variables.
for location in MESH_ELEMENTS:
coords_meshobj_attr = f"{location}_coords"
coords_file_attr = f"{location}_coordinates"
mesh_coords = getattr(mesh, coords_meshobj_attr, None)
if mesh_coords:
coord_names = []
for coord in mesh_coords:
if coord is None:
continue # an awkward thing that mesh.coords does
coord_name = self._create_generic_cf_array_var(
cube_or_mesh,
[],
coord,
element_dims=(mesh_dims[location],),
)
# Only created once per file, but need to fetch the
# name later in _add_inner_related_vars().
self._name_coord_map.append(coord_name, coord)
coord_names.append(coord_name)
# Record the coordinates (if any) on the mesh variable.
if coord_names:
coord_names = " ".join(coord_names)
_setncattr(cf_mesh_var, coords_file_attr, coord_names)
# Add all the connectivity variables.
# pre-fetch the set + ignore "None"s, which are empty slots.
conns = [conn for conn in mesh.all_connectivities if conn is not None]
for conn in conns:
# Get the connectivity role, = "{loc1}_{loc2}_connectivity".
cf_conn_attr_name = conn.cf_role
loc_from, loc_to, _ = cf_conn_attr_name.split("_")
# Construct a trailing dimension name.
last_dim = f"{cf_mesh_name}_{loc_from}_N_{loc_to}s"
# Create if it does not already exist.
if last_dim not in self._dataset.dimensions:
while last_dim in self._dataset.variables:
# Also avoid collision with variable names.
# See '_get_dim_names' for reason.
last_dim = self._increment_name(last_dim)
length = conn.shape[1 - conn.location_axis]
self._dataset.createDimension(last_dim, length)
# Create variable.
# NOTE: for connectivities *with missing points*, this will use a
# fixed standard fill-value of -1. In that case, we create the
# variable with a '_FillValue' property, which can only be done
# when it is first created.
loc_dim_name = mesh_dims[loc_from]
conn_dims = (loc_dim_name, last_dim)
if conn.location_axis == 1:
# Has the 'other' dimension order, =reversed
conn_dims = conn_dims[::-1]
if iris.util.is_masked(conn.core_indices()):
# Flexible mesh.
fill_value = -1
else:
fill_value = None
cf_conn_name = self._create_generic_cf_array_var(
cube_or_mesh,
[],
conn,
element_dims=conn_dims,
fill_value=fill_value,
)
# Add essential attributes to the Connectivity variable.
cf_conn_var = self._dataset.variables[cf_conn_name]
_setncattr(cf_conn_var, "cf_role", cf_conn_attr_name)
_setncattr(cf_conn_var, "start_index", conn.start_index)
# Record the connectivity on the parent mesh var.
_setncattr(cf_mesh_var, cf_conn_attr_name, cf_conn_name)
# If the connectivity had the 'alternate' dimension order, add the
# relevant dimension property
if conn.location_axis == 1:
loc_dim_attr = f"{loc_from}_dimension"
# Should only get here once.
assert loc_dim_attr not in cf_mesh_var.ncattrs()
_setncattr(cf_mesh_var, loc_dim_attr, loc_dim_name)
return cf_mesh_name
def _add_inner_related_vars(
self, cube, cf_var_cube, dimension_names, coordlike_elements
):
"""Create a set of variables for aux-coords, ancillaries or cell-measures.
Create a set of variables for aux-coords, ancillaries or cell-measures,
and attach them to the parent data variable.
"""
if coordlike_elements:
# Choose the appropriate parent attribute
elem_type = type(coordlike_elements[0])
if elem_type in (AuxCoord, DimCoord):
role_attribute_name = "coordinates"
elif elem_type == AncillaryVariable:
role_attribute_name = "ancillary_variables"
else:
# We *only* handle aux-coords, cell-measures and ancillaries
assert elem_type == CellMeasure
role_attribute_name = "cell_measures"
# Add CF-netCDF variables for the given cube components.
element_names = []
for element in sorted(
coordlike_elements, key=lambda element: element.name()
):
# Reuse, or create, the associated CF-netCDF variable.
cf_name = self._name_coord_map.name(element)
if cf_name is None:
# Not already present : create it
cf_name = self._create_generic_cf_array_var(
cube, dimension_names, element
)
self._name_coord_map.append(cf_name, element)
if role_attribute_name == "cell_measures":
# In the case of cell-measures, the attribute entries are not just
# a var_name, but each have the form "<measure>: <varname>".
cf_name = "{}: {}".format(element.measure, cf_name)
element_names.append(cf_name)
# Add CF-netCDF references to the primary data variable.
if element_names:
variable_names = " ".join(sorted(element_names))
_setncattr(cf_var_cube, role_attribute_name, variable_names)
def _add_aux_coords(self, cube, cf_var_cube, dimension_names):
"""Add aux. coordinate to the dataset and associate with the data variable.
Parameters
----------
cube : :class:`iris.cube.Cube`
A :class:`iris.cube.Cube` to be saved to a netCDF file.
cf_var_cube : :class:`netcdf.netcdf_variable`
A cf variable cube representation.
dimension_names : list
Names associated with the dimensions of the cube.
"""
from iris.experimental.ugrid.mesh import (
Mesh,
MeshEdgeCoords,
MeshFaceCoords,
MeshNodeCoords,
)
# Exclude any mesh coords, which are bundled in with the aux-coords.
coords_to_add = [
coord for coord in cube.aux_coords if not hasattr(coord, "mesh")
]
# Include any relevant mesh location coordinates.
mesh: Mesh = getattr(cube, "mesh")
mesh_location: str = getattr(cube, "location")
if mesh and mesh_location:
location_coords: MeshNodeCoords | MeshEdgeCoords | MeshFaceCoords = getattr(
mesh, f"{mesh_location}_coords"
)
coords_to_add.extend(list(location_coords))
return self._add_inner_related_vars(
cube,
cf_var_cube,
dimension_names,
coords_to_add,
)
def _add_cell_measures(self, cube, cf_var_cube, dimension_names):
"""Add cell measures to the dataset and associate with the data variable.
Parameters
----------
cube : :class:`iris.cube.Cube`
A :class:`iris.cube.Cube` to be saved to a netCDF file.
cf_var_cube : :class:`netcdf.netcdf_variable`
A cf variable cube representation.
dimension_names : list
Names associated with the dimensions of the cube.
"""
return self._add_inner_related_vars(
cube,
cf_var_cube,
dimension_names,
cube.cell_measures(),
)
def _add_ancillary_variables(self, cube, cf_var_cube, dimension_names):
"""Add ancillary variables measures to the dataset and associate with the data variable.
Parameters
----------
cube : :class:`iris.cube.Cube`
A :class:`iris.cube.Cube` to be saved to a netCDF file.
cf_var_cube : :class:`netcdf.netcdf_variable`
A cf variable cube representation.
dimension_names : list
Names associated with the dimensions of the cube.