forked from SciTools/iris
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathugrid.py
More file actions
2012 lines (1676 loc) · 60.7 KB
/
Copy pathugrid.py
File metadata and controls
2012 lines (1676 loc) · 60.7 KB
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 LGPL license.
# See COPYING and COPYING.LESSER in the root of the repository for full
# licensing details.
"""
Infra-structure for unstructured mesh support, based on
CF UGRID Conventions (v1.0), https://ugrid-conventions.github.io/ugrid-conventions/
"""
from abc import ABC, abstractmethod
from collections import Iterable, namedtuple
from functools import wraps
import dask.array as da
import numpy as np
from .. import _lazy_data as _lazy
from ..common.metadata import (
BaseMetadata,
metadata_filter,
metadata_manager_factory,
SERVICES,
SERVICES_COMBINE,
SERVICES_EQUAL,
SERVICES_DIFFERENCE,
)
from ..common.lenient import _lenient_service as lenient_service
from ..common.mixin import CFVariableMixin
from ..config import get_logger
from ..coords import _DimensionalMetadata, AuxCoord
from ..exceptions import ConnectivityNotFoundError, CoordinateNotFoundError
from ..util import guess_coord_axis
__all__ = [
"Connectivity",
"ConnectivityMetadata",
"Mesh1DConnectivities",
"Mesh1DCoords",
"Mesh2DConnectivities",
"Mesh2DCoords",
"MeshEdgeCoords",
"MeshFaceCoords",
"MeshNodeCoords",
"MeshMetadata",
]
# Configure the logger.
logger = get_logger(__name__, fmt="[%(cls)s.%(funcName)s]")
# Mesh dimension names namedtuples.
Mesh1DNames = namedtuple("Mesh1DNames", ["node_dimension", "edge_dimension"])
Mesh2DNames = namedtuple(
"Mesh2DNames", ["node_dimension", "edge_dimension", "face_dimension"]
)
# Mesh coordinate manager namedtuples.
Mesh1DCoords = namedtuple(
"Mesh1DCoords", ["node_x", "node_y", "edge_x", "edge_y"]
)
Mesh2DCoords = namedtuple(
"Mesh2DCoords",
["node_x", "node_y", "edge_x", "edge_y", "face_x", "face_y"],
)
MeshNodeCoords = namedtuple("MeshNodeCoords", ["node_x", "node_y"])
MeshEdgeCoords = namedtuple("MeshEdgeCoords", ["edge_x", "edge_y"])
MeshFaceCoords = namedtuple("MeshFaceCoords", ["face_x", "face_y"])
# Mesh connectivity manager namedtuples.
Mesh1DConnectivities = namedtuple("Mesh1DConnectivities", ["edge_node"])
Mesh2DConnectivities = namedtuple(
"Mesh2DConnectivities",
[
"face_node",
"edge_node",
"face_edge",
"face_face",
"edge_face",
"boundary_node",
],
)
class Connectivity(_DimensionalMetadata):
"""
A CF-UGRID topology connectivity, describing the topological relationship
between two lists of dimensional locations. One or more connectivities
make up a CF-UGRID topology - a constituent of a CF-UGRID mesh.
See: https://ugrid-conventions.github.io/ugrid-conventions
"""
UGRID_CF_ROLES = [
"edge_node_connectivity",
"face_node_connectivity",
"face_edge_connectivity",
"face_face_connectivity",
"edge_face_connectivity",
"boundary_node_connectivity",
"volume_node_connectivity",
"volume_edge_connectivity",
"volume_face_connectivity",
"volume_volume_connectivity",
]
def __init__(
self,
indices,
cf_role,
standard_name=None,
long_name=None,
var_name=None,
units=None,
attributes=None,
start_index=0,
src_dim=0,
):
"""
Constructs a single connectivity.
Args:
* indices (numpy.ndarray or numpy.ma.core.MaskedArray or dask.array.Array):
The index values describing a topological relationship. Constructed
of 2 dimensions - the list of locations, and within each location:
the indices of the 'target locations' it relates to.
Use a :class:`numpy.ma.core.MaskedArray` if :attr:`src_location`
lengths vary - mask unused index 'slots' within each
:attr:`src_location`. Use a :class:`dask.array.Array` to keep
indices 'lazy'.
* cf_role (str):
Denotes the topological relationship that this connectivity
describes. Made up of this array's locations, and the indexed
'target location' within each location.
See :attr:`UGRID_CF_ROLES` for valid arguments.
Kwargs:
* standard_name (str):
CF standard name of the connectivity.
(NOTE: this is not expected by the UGRID conventions, but will be
handled in Iris' standard way if provided).
* long_name (str):
Descriptive name of the connectivity.
* var_name (str):
The netCDF variable name for the connectivity.
* units (cf_units.Unit):
The :class:`~cf_units.Unit` of the connectivity's values.
Can be a string, which will be converted to a Unit object.
(NOTE: this is not expected by the UGRID conventions, but will be
handled in Iris' standard way if provided).
* attributes (dict):
A dictionary containing other cf and user-defined attributes.
* start_index (int):
Either ``0`` or ``1``. Default is ``0``. Denotes whether
:attr:`indices` uses 0-based or 1-based indexing (allows support
for Fortran and legacy NetCDF files).
* src_dim (int):
Either ``0`` or ``1``. Default is ``0``. Denotes which dimension
of :attr:`indices` varies over the :attr:`src_location`'s (the
alternate dimension therefore varying within individual
:attr:`src_location`'s). (This parameter allows support for fastest varying index being
either first or last).
E.g. for ``face_node_connectivity``, for 10 faces:
``indices.shape[src_dim] = 10``.
"""
def validate_arg_vs_list(arg_name, arg, valid_list):
if arg not in valid_list:
error_msg = (
f"Invalid {arg_name} . Got: {arg} . Must be one of: "
f"{valid_list} ."
)
raise ValueError(error_msg)
# Configure the metadata manager.
self._metadata_manager = metadata_manager_factory(ConnectivityMetadata)
validate_arg_vs_list("start_index", start_index, [0, 1])
# indices array will be 2-dimensional, so must be either 0 or 1.
validate_arg_vs_list("src_dim", src_dim, [0, 1])
validate_arg_vs_list("cf_role", cf_role, Connectivity.UGRID_CF_ROLES)
self._metadata_manager.start_index = start_index
self._metadata_manager.src_dim = src_dim
self._metadata_manager.cf_role = cf_role
self._tgt_dim = 1 - src_dim
self._src_location, self._tgt_location = cf_role.split("_")[:2]
super().__init__(
values=indices,
standard_name=standard_name,
long_name=long_name,
var_name=var_name,
units=units,
attributes=attributes,
)
@property
def _values(self):
# Overridden just to allow .setter override.
return super()._values
@_values.setter
def _values(self, values):
self._validate_indices(values, shapes_only=True)
# The recommended way of using the setter in super().
super(Connectivity, self.__class__)._values.fset(self, values)
@property
def cf_role(self):
"""
The category of topological relationship that this connectivity
describes.
**Read-only** - validity of :attr:`indices` is dependent on
:attr:`cf_role`. A new :class:`Connectivity` must therefore be defined
if a different :attr:`cf_role` is needed.
"""
return self._metadata_manager.cf_role
@property
def src_location(self):
"""
Derived from the connectivity's :attr:`cf_role` - the first part, e.g.
``face`` in ``face_node_connectivity``. Refers to the locations
listed by the :attr:`src_dim` of the connectivity's :attr:`indices`
array.
"""
return self._src_location
@property
def tgt_location(self):
"""
Derived from the connectivity's :attr:`cf_role` - the second part, e.g.
``node`` in ``face_node_connectivity``. Refers to the locations indexed
by the values in the connectivity's :attr:`indices` array.
"""
return self._tgt_location
@property
def start_index(self):
"""
The base value of the connectivity's :attr:`indices` array; either
``0`` or ``1``.
**Read-only** - validity of :attr:`indices` is dependent on
:attr:`start_index`. A new :class:`Connectivity` must therefore be
defined if a different :attr:`start_index` is needed.
"""
return self._metadata_manager.start_index
@property
def src_dim(self):
"""
The dimension of the connectivity's :attr:`indices` array that varies
over the connectivity's :attr:`src_location`'s. Either ``0`` or ``1``.
**Read-only** - validity of :attr:`indices` is dependent on
:attr:`src_dim`. Use :meth:`transpose` to create a new, transposed
:class:`Connectivity` if a different :attr:`src_dim` is needed.
"""
return self._metadata_manager.src_dim
@property
def tgt_dim(self):
"""
Derived as the alternate value of :attr:`src_dim` - each must equal
either ``0`` or ``1``.
The dimension of the connectivity's :attr:`indices` array that varies
within the connectivity's individual :attr:`src_location`'s.
"""
return self._tgt_dim
@property
def indices(self):
"""
The index values describing the topological relationship of the
connectivity, as a NumPy array. Masked points indicate a
:attr:`src_location` shorter than the longest :attr:`src_location`
described in this array - unused index 'slots' are masked.
**Read-only** - index values are only meaningful when combined with
an appropriate :attr:`cf_role`, :attr:`start_index` and
:attr:`src_dim`. A new :class:`Connectivity` must therefore be
defined if different indices are needed.
"""
return self._values
def indices_by_src(self, indices=None):
"""
Return a view of the indices array with :attr:`src_dim` **always** as
the first index - transposed if necessary. Can optionally pass in an
identically shaped array on which to perform this operation (e.g. the
output from :meth:`core_indices` or :meth:`lazy_indices`).
Kwargs:
* indices (array):
The array on which to operate. If ``None``, will operate on
:attr:`indices`. Default is ``None``.
Returns:
A view of the indices array, transposed - if necessary - to put
:attr:`src_dim` first.
"""
if indices is None:
indices = self.indices
if indices.shape != self.shape:
raise ValueError(
f"Invalid indices provided. Must be shape={self.shape} , "
f"got shape={indices.shape} ."
)
if self.src_dim == 0:
result = indices
elif self.src_dim == 1:
result = indices.transpose()
else:
raise ValueError("Invalid src_dim.")
return result
def _validate_indices(self, indices, shapes_only=False):
# Use shapes_only=True for a lower resource, less thorough validation
# of indices by just inspecting the array shape instead of inspecting
# individual masks. So will not catch individual src_locations being
# unacceptably small.
def indices_error(message):
raise ValueError("Invalid indices provided. " + message)
indices = self._sanitise_array(indices, 0)
indices_dtype = indices.dtype
if not np.issubdtype(indices_dtype, np.integer):
indices_error(
f"dtype must be numpy integer subtype, got: {indices_dtype} ."
)
indices_min = indices.min()
if _lazy.is_lazy_data(indices_min):
indices_min = indices_min.compute()
if indices_min < self.start_index:
indices_error(
f"Lowest index: {indices_min} < start_index: {self.start_index} ."
)
indices_shape = indices.shape
if len(indices_shape) != 2:
indices_error(
f"Expected 2-dimensional shape, got: shape={indices_shape} ."
)
len_req_fail = False
if shapes_only:
src_shape = indices_shape[self.tgt_dim]
# Wrap as lazy to allow use of the same operations below
# regardless of shapes_only.
src_lengths = _lazy.as_lazy_data(np.asarray(src_shape))
else:
# Wouldn't be safe to use during __init__ validation, since
# lazy_src_lengths requires self.indices to exist. Safe here since
# shapes_only==False is only called manually, i.e. after
# initialisation.
src_lengths = self.lazy_src_lengths()
if self.src_location in ("edge", "boundary"):
if (src_lengths != 2).any().compute():
len_req_fail = "len=2"
else:
if self.src_location == "face":
min_size = 3
elif self.src_location == "volume":
if self.tgt_location == "edge":
min_size = 6
else:
min_size = 4
else:
raise NotImplementedError
if (src_lengths < min_size).any().compute():
len_req_fail = f"len>={min_size}"
if len_req_fail:
indices_error(
f"Not all src_locations meet requirement: {len_req_fail} - "
f"needed to describe '{self.cf_role}' ."
)
def validate_indices(self):
"""
Perform a thorough validity check of this connectivity's
:attr:`indices`. Includes checking the sizes of individual
:attr:`src_location`'s (specified using masks on the
:attr:`indices` array) against the :attr:`cf_role`.
Raises a ``ValueError`` if any problems are encountered, otherwise
passes silently.
.. note::
While this uses lazy computation, it will still be a high
resource demand for a large :attr:`indices` array.
"""
self._validate_indices(self.indices, shapes_only=False)
def __eq__(self, other):
eq = NotImplemented
if isinstance(other, Connectivity):
# Account for the fact that other could be the transposed equivalent
# of self, which we consider 'safe' since the recommended
# interaction with the indices array is via indices_by_src, which
# corrects for this difference. (To enable this, src_dim does
# not participate in ConnectivityMetadata to ConnectivityMetadata
# equivalence).
if hasattr(other, "metadata"):
# metadata comparison
eq = self.metadata == other.metadata
if eq:
eq = (
self.indices_by_src() == other.indices_by_src()
).all()
return eq
def transpose(self):
"""
Create a new :class:`Connectivity`, identical to this one but with the
:attr:`indices` array transposed and the :attr:`src_dim` value flipped.
Returns:
A new :class:`Connectivity` that is the transposed equivalent of
the original.
"""
new_connectivity = Connectivity(
indices=self.indices.transpose().copy(),
cf_role=self.cf_role,
standard_name=self.standard_name,
long_name=self.long_name,
var_name=self.var_name,
units=self.units,
attributes=self.attributes,
start_index=self.start_index,
src_dim=self.tgt_dim,
)
return new_connectivity
def lazy_indices(self):
"""
Return a lazy array representing the connectivity's indices.
Accessing this method will never cause the :attr:`indices` values to be
loaded. Similarly, calling methods on, or indexing, the returned Array
will not cause the connectivity to have loaded :attr:`indices`.
If the :attr:`indices` have already been loaded for the connectivity,
the returned Array will be a new lazy array wrapper.
Returns:
A lazy array, representing the connectivity indices array.
"""
return super()._lazy_values()
def core_indices(self):
"""
The indices array at the core of this connectivity, which may be a
NumPy array or a Dask array.
Returns:
numpy.ndarray or numpy.ma.core.MaskedArray or dask.array.Array
"""
return super()._core_values()
def has_lazy_indices(self):
"""
Return a boolean indicating whether the connectivity's :attr:`indices`
array is a lazy Dask array or not.
Returns:
boolean
"""
return super()._has_lazy_values()
def lazy_src_lengths(self):
"""
Return a lazy array representing the lengths of each
:attr:`src_location` in the :attr:`src_dim` of the connectivity's
:attr:`indices` array, accounting for masks if present.
Accessing this method will never cause the :attr:`indices` values to be
loaded. Similarly, calling methods on, or indexing, the returned Array
will not cause the connectivity to have loaded :attr:`indices`.
The returned Array will be lazy regardless of whether the
:attr:`indices` have already been loaded.
Returns:
A lazy array, representing the lengths of each :attr:`src_location`.
"""
src_mask_counts = da.sum(
da.ma.getmaskarray(self.indices), axis=self.tgt_dim
)
max_src_size = self.indices.shape[self.tgt_dim]
return max_src_size - src_mask_counts
def src_lengths(self):
"""
Return a NumPy array representing the lengths of each
:attr:`src_location` in the :attr:`src_dim` of the connectivity's
:attr:`indices` array, accounting for masks if present.
Returns:
A NumPy array, representing the lengths of each :attr:`src_location`.
"""
return self.lazy_src_lengths().compute()
def cube_dims(self, cube):
"""Not available on :class:`Connectivity`."""
raise NotImplementedError
def xml_element(self, doc):
# Create the XML element as the camelCaseEquivalent of the
# class name
element = super().xml_element(doc)
element.setAttribute("cf_role", self.cf_role)
element.setAttribute("start_index", self.start_index)
element.setAttribute("src_dim", self.src_dim)
return element
class ConnectivityMetadata(BaseMetadata):
"""
Metadata container for a :class:`~iris.experimental.ugrid.Connectivity`.
"""
# The "src_dim" member is stateful only, and does not participate in
# lenient/strict equivalence.
_members = ("cf_role", "start_index", "src_dim")
__slots__ = ()
@wraps(BaseMetadata.__eq__, assigned=("__doc__",), updated=())
@lenient_service
def __eq__(self, other):
return super().__eq__(other)
def _combine_lenient(self, other):
"""
Perform lenient combination of metadata members for connectivities.
Args:
* other (ConnectivityMetadata):
The other connectivity metadata participating in the lenient
combination.
Returns:
A list of combined metadata member values.
"""
# Perform "strict" combination for "cf_role", "start_index", "src_dim".
def func(field):
left = getattr(self, field)
right = getattr(other, field)
return left if left == right else None
# Note that, we use "_members" not "_fields".
values = [func(field) for field in ConnectivityMetadata._members]
# Perform lenient combination of the other parent members.
result = super()._combine_lenient(other)
result.extend(values)
return result
def _compare_lenient(self, other):
"""
Perform lenient equality of metadata members for connectivities.
Args:
* other (ConnectivityMetadata):
The other connectivity metadata participating in the lenient
comparison.
Returns:
Boolean.
"""
# Perform "strict" comparison for "cf_role", "start_index".
# The "src_dim" member is not part of lenient equivalence.
members = filter(
lambda member: member != "src_dim", ConnectivityMetadata._members
)
result = all(
[
getattr(self, field) == getattr(other, field)
for field in members
]
)
if result:
# Perform lenient comparison of the other parent members.
result = super()._compare_lenient(other)
return result
def _difference_lenient(self, other):
"""
Perform lenient difference of metadata members for connectivities.
Args:
* other (ConnectivityMetadata):
The other connectivity metadata participating in the lenient
difference.
Returns:
A list of difference metadata member values.
"""
# Perform "strict" difference for "cf_role", "start_index", "src_dim".
def func(field):
left = getattr(self, field)
right = getattr(other, field)
return None if left == right else (left, right)
# Note that, we use "_members" not "_fields".
values = [func(field) for field in ConnectivityMetadata._members]
# Perform lenient difference of the other parent members.
result = super()._difference_lenient(other)
result.extend(values)
return result
@wraps(BaseMetadata.combine, assigned=("__doc__",), updated=())
@lenient_service
def combine(self, other, lenient=None):
return super().combine(other, lenient=lenient)
@wraps(BaseMetadata.difference, assigned=("__doc__",), updated=())
@lenient_service
def difference(self, other, lenient=None):
return super().difference(other, lenient=lenient)
@wraps(BaseMetadata.equal, assigned=("__doc__",), updated=())
@lenient_service
def equal(self, other, lenient=None):
return super().equal(other, lenient=lenient)
class MeshMetadata(BaseMetadata):
"""
Metadata container for a :class:`~iris.experimental.ugrid.Mesh`.
"""
# The node_dimension", "edge_dimension" and "face_dimension" members are
# stateful only; they not participate in lenient/strict equivalence.
_members = (
"topology_dimension",
"node_dimension",
"edge_dimension",
"face_dimension",
)
__slots__ = ()
@wraps(BaseMetadata.__eq__, assigned=("__doc__",), updated=())
@lenient_service
def __eq__(self, other):
return super().__eq__(other)
def _combine_lenient(self, other):
"""
Perform lenient combination of metadata members for meshes.
Args:
* other (MeshMetadata):
The other mesh metadata participating in the lenient
combination.
Returns:
A list of combined metadata member values.
"""
# Perform "strict" combination for "topology_dimension",
# "node_dimension", "edge_dimension" and "face_dimension".
def func(field):
left = getattr(self, field)
right = getattr(other, field)
return left if left == right else None
# Note that, we use "_members" not "_fields".
values = [func(field) for field in MeshMetadata._members]
# Perform lenient combination of the other parent members.
result = super()._combine_lenient(other)
result.extend(values)
return result
def _compare_lenient(self, other):
"""
Perform lenient equality of metadata members for meshes.
Args:
* other (MeshMetadata):
The other mesh metadata participating in the lenient
comparison.
Returns:
Boolean.
"""
# Perform "strict" comparison for "topology_dimension".
# "node_dimension", "edge_dimension" and "face_dimension" are not part
# of lenient equivalence at all.
result = self.topology_dimension == other.topology_dimension
if result:
# Perform lenient comparison of the other parent members.
result = super()._compare_lenient(other)
return result
def _difference_lenient(self, other):
"""
Perform lenient difference of metadata members for meshes.
Args:
* other (MeshMetadata):
The other mesh metadata participating in the lenient
difference.
Returns:
A list of difference metadata member values.
"""
# Perform "strict" difference for "topology_dimension",
# "node_dimension", "edge_dimension" and "face_dimension".
def func(field):
left = getattr(self, field)
right = getattr(other, field)
return None if left == right else (left, right)
# Note that, we use "_members" not "_fields".
values = [func(field) for field in MeshMetadata._members]
# Perform lenient difference of the other parent members.
result = super()._difference_lenient(other)
result.extend(values)
return result
@wraps(BaseMetadata.combine, assigned=("__doc__",), updated=())
@lenient_service
def combine(self, other, lenient=None):
return super().combine(other, lenient=lenient)
@wraps(BaseMetadata.difference, assigned=("__doc__",), updated=())
@lenient_service
def difference(self, other, lenient=None):
return super().difference(other, lenient=lenient)
@wraps(BaseMetadata.equal, assigned=("__doc__",), updated=())
@lenient_service
def equal(self, other, lenient=None):
return super().equal(other, lenient=lenient)
class Mesh(CFVariableMixin):
"""
.. todo::
.. questions::
- decide on the verbose/succinct version of __str__ vs __repr__
.. notes::
- the mesh is location agnostic
- no need to support volume at mesh level, yet
- topology_dimension
- use for fast equality between Mesh instances
- checking connectivity dimensionality, specifically the highest dimensonality of the
"geometric element" being added i.e., reference the src_location/tgt_location
- used to honour and enforce the minimum UGRID connectivity contract
- support pickling
- copy is off the table!!
- MeshCoord.guess_points()
- MeshCoord.to_AuxCoord()
- don't provide public methods to return the coordinate and connectivity
managers
- validate both managers contents e.g., shape? more...?
"""
# TBD: for volume and/or z-axis support include axis "z" and/or dimension "3"
AXES = ("x", "y")
TOPOLOGY_DIMENSIONS = (1, 2)
def __init__(
self,
topology_dimension,
node_coords_and_axes,
connectivities,
standard_name=None,
long_name=None,
var_name=None,
units=None,
attributes=None,
edge_coords_and_axes=None,
face_coords_and_axes=None,
node_dimension=None,
edge_dimension=None,
face_dimension=None,
):
# TODO: support volumes.
# TODO: support (coord, "z")
self._metadata_manager = metadata_manager_factory(MeshMetadata)
# topology_dimension is read-only, so assign directly to the metadata manager
if topology_dimension not in self.TOPOLOGY_DIMENSIONS:
emsg = f"Expected 'topology_dimension' in range {self.TOPOLOGY_DIMENSIONS!r}, got {topology_dimension!r}."
raise ValueError(emsg)
self._metadata_manager.topology_dimension = topology_dimension
# TBD: these are strings, if None is provided then assign the default string.
self.node_dimension = node_dimension
self.edge_dimension = edge_dimension
self.face_dimension = face_dimension
# assign the metadata to the metadata manager
self.standard_name = standard_name
self.long_name = long_name
self.var_name = var_name
self.units = units
self.attributes = attributes
# based on the topology_dimension, create the appropriate coordinate manager
def normalise(location, axis):
result = str(axis).lower()
if result not in self.AXES:
emsg = f"Invalid axis specified for {location} coordinate {coord.name()!r}, got {axis!r}."
raise ValueError(emsg)
return f"{location}_{axis}"
if not isinstance(node_coords_and_axes, Iterable):
node_coords_and_axes = [node_coords_and_axes]
if not isinstance(connectivities, Iterable):
connectivities = [connectivities]
kwargs = {}
for coord, axis in node_coords_and_axes:
kwargs[normalise("node", axis)] = coord
if edge_coords_and_axes is not None:
for coord, axis in edge_coords_and_axes:
kwargs[normalise("edge", axis)] = coord
if face_coords_and_axes is not None:
for coord, axis in face_coords_and_axes:
kwargs[normalise("face", axis)] = coord
# check the UGRID minimum requirement for coordinates
if "node_x" not in kwargs:
emsg = (
"Require a node coordinate that is x-axis like to be provided."
)
raise ValueError(emsg)
if "node_y" not in kwargs:
emsg = (
"Require a node coordinate that is y-axis like to be provided."
)
raise ValueError(emsg)
if self.topology_dimension == 1:
self._coord_manager = _Mesh1DCoordinateManager(**kwargs)
self._connectivity_manager = _Mesh1DConnectivityManager(
*connectivities
)
elif self.topology_dimension == 2:
self._coord_manager = _Mesh2DCoordinateManager(**kwargs)
self._connectivity_manager = _Mesh2DConnectivityManager(
*connectivities
)
else:
emsg = f"Unsupported 'topology_dimension', got {topology_dimension!r}."
raise NotImplementedError(emsg)
def __eq__(self, other):
# TBD
return NotImplemented
def __getstate__(self):
# TBD
pass
def __ne__(self, other):
# TBD
return NotImplemented
def __repr__(self):
# TBD
args = []
return f"{self.__class__.__name__}({', '.join(args)})"
def __setstate__(self, state):
# TBD
pass
def __str__(self):
# TBD
args = []
return f"{self.__class__.__name__}({', '.join(args)})"
def _set_dimension_names(self, node, edge, face, reset=False):
args = (node, edge, face)
currents = (
self.node_dimension,
self.edge_dimension,
self.face_dimension,
)
zipped = zip(args, currents)
if reset:
node, edge, face = [
None if arg else current for arg, current in zipped
]
else:
node, edge, face = [arg or current for arg, current in zipped]
self.node_dimension = node
self.edge_dimension = edge
self.face_dimension = face
if self.topology_dimension == 1:
result = Mesh1DNames(self.node_dimension, self.edge_dimension)
elif self.topology_dimension == 2:
result = Mesh2DNames(
self.node_dimension, self.edge_dimension, self.face_dimension
)
else:
message = (
f"Unsupported topology_dimension: {self.topology_dimension} ."
)
raise NotImplementedError(message)
return result
@property
def all_coords(self):
return self._coord_manager.all_members
@property
def edge_dimension(self):
return self._metadata_manager.edge_dimension
@edge_dimension.setter
def edge_dimension(self, name):
if not name or not isinstance(name, str):
edge_dimension = f"Mesh{self.topology_dimension}d_edge"
else:
edge_dimension = name
self._metadata_manager.edge_dimension = edge_dimension
@property
def edge_coords(self):
return self._coord_manager.edge_coords
@property
def face_dimension(self):
return self._metadata_manager.face_dimension