-
Notifications
You must be signed in to change notification settings - Fork 7
/
ugrid2d.py
2013 lines (1776 loc) · 67.3 KB
/
ugrid2d.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 itertools import chain
from typing import Any, Dict, Optional, Sequence, Tuple, Union
import numpy as np
import pandas as pd
import xarray as xr
from numba_celltree import CellTree2d
from scipy.sparse import coo_matrix, csr_matrix
from scipy.sparse.csgraph import reverse_cuthill_mckee
import xugrid
from xugrid import conversion
from xugrid import meshkernel_utils as mku
from xugrid.constants import (
BoolArray,
FloatArray,
FloatDType,
IntArray,
IntDType,
SparseMatrix,
)
from xugrid.core.utils import either_dict_or_kwargs
from xugrid.ugrid import connectivity, conventions
from xugrid.ugrid.ugridbase import AbstractUgrid, as_pandas_index
from xugrid.ugrid.voronoi import voronoi_topology
def section_coordinates(
edges: FloatArray, xy: FloatArray, dim: str, index: IntArray, name: str
) -> Tuple[IntArray, dict]:
# TODO: add boundaries xy[:, 0] and xy[:, 1]
xy_mid = 0.5 * (xy[:, 0, :] + xy[:, 1, :])
s = np.linalg.norm(xy_mid - edges[0, 0], axis=1)
order = np.argsort(s)
coords = {
f"{name}_x": (dim, xy_mid[order, 0]),
f"{name}_y": (dim, xy_mid[order, 1]),
f"{name}_s": (dim, s[order]),
}
return coords, index[order]
def numeric_bound(v: Union[float, None], other: float):
if v is None:
return other
else:
return v
class Ugrid2d(AbstractUgrid):
"""
This class stores the topological data of a 2-D unstructured grid.
Parameters
----------
node_x: ndarray of floats
node_y: ndarray of floats
fill_value: int
face_node_connectivity: ndarray of integers
name: string, optional
Mesh name. Defaults to "mesh2d".
edge_node_connectivity: ndarray of integers, optional
dataset: xr.Dataset, optional
indexes: Dict[str, str], optional
When a dataset is provided, a mapping from the UGRID role to the dataset
variable name. E.g. {"face_x": "mesh2d_face_lon"}.
projected: bool, optional
Whether node_x and node_y are longitude and latitude or projected x and
y coordinates. Used to write the appropriate standard_name in the
coordinate attributes.
crs: Any, optional
Coordinate Reference System of the geometry objects. Can be anything accepted by
:meth:`pyproj.CRS.from_user_input() <pyproj.crs.CRS.from_user_input>`,
such as an authority string (eg "EPSG:4326") or a WKT string.
attrs: Dict[str, str], optional
UGRID topology attributes. Should not be provided together with
dataset: if other names are required, update the dataset instead.
A name entry is ignored, as name is given explicitly.
"""
def __init__(
self,
node_x: FloatArray,
node_y: FloatArray,
fill_value: int,
face_node_connectivity: Union[IntArray, SparseMatrix],
name: str = "mesh2d",
edge_node_connectivity: IntArray = None,
dataset: xr.Dataset = None,
indexes: Dict[str, str] = None,
projected: bool = True,
crs: Any = None,
attrs: Dict[str, str] = None,
):
self.node_x = np.ascontiguousarray(node_x)
self.node_y = np.ascontiguousarray(node_y)
self.fill_value = fill_value
self.name = name
self.projected = projected
if isinstance(face_node_connectivity, np.ndarray):
face_node_connectivity = face_node_connectivity
elif isinstance(face_node_connectivity, (coo_matrix, csr_matrix)):
face_node_connectivity = connectivity.to_dense(
face_node_connectivity, fill_value
)
else:
raise TypeError(
"face_node_connectivity should be an array of integers or a sparse matrix"
)
self.face_node_connectivity = face_node_connectivity
# TODO: do this in validation instead. While UGRID conventions demand it,
# where does it go wrong?
# self.face_node_connectivity = connectivity.counterclockwise(
# face_node_connectivity, self.fill_value, self.node_coordinates
# )
self._initialize_indexes_attrs(name, dataset, indexes, attrs)
self._dataset = dataset
# Optional attributes, deferred initialization
# Meshkernel
self._mesh = None
self._meshkernel = None
# Celltree
self._celltree = None
# Perimeter
self._perimeter = None
# Area
self._area = None
# Centroids
self._centroids = None
self._circumcenters = None
# Bounds
self._xmin = None
self._xmax = None
self._ymin = None
self._ymax = None
# Edges
self._edge_x = None
self._edge_y = None
# Connectivity
self.edge_node_connectivity = edge_node_connectivity
self._edge_face_connectivity = None
self._node_node_connectivity = None
self._node_edge_connectivity = None
self._node_face_connectivity = None
self._face_edge_connectivity = None
self._face_face_connectivity = None
self._boundary_node_connectivity = None
# Derived topology
self._triangulation = None
self._voronoi_topology = None
self._centroid_triangulation = None
# crs
if crs is None:
self.crs = None
else:
import pyproj
self.crs = pyproj.CRS.from_user_input(crs)
def _clear_geometry_properties(self):
"""Clear all properties that may have been invalidated"""
# Meshkernel
self._mesh = None
self._meshkernel = None
# Celltree
self._celltree = None
# Perimeter
self._perimeter = None
# Area
self._area = None
# Centroids
self._centroids = None
self._circumcenters = None
# Bounds
self._xmin = None
self._xmax = None
self._ymin = None
self._ymax = None
# Edges
self._edge_x = None
self._edge_y = None
# Derived topology
self._triangulation = None
self._voronoi_topology = None
self._centroid_triangulation = None
@classmethod
def from_meshkernel(
cls,
mesh,
name: str = "mesh2d",
projected: bool = True,
crs: Any = None,
):
"""
Create a 2D UGRID topology from a MeshKernel Mesh2d object.
Parameters
----------
mesh: MeshKernel.Mesh2d
name: str
Mesh name. Defaults to "mesh2d".
projected: bool
Whether node_x and node_y are longitude and latitude or projected x and
y coordinates. Used to write the appropriate standard_name in the
coordinate attributes.
crs: Any, optional
Coordinate Reference System of the geometry objects. Can be anything accepted by
:meth:`pyproj.CRS.from_user_input() <pyproj.crs.CRS.from_user_input>`,
such as an authority string (eg "EPSG:4326") or a WKT string.
Returns
-------
grid: Ugrid2d
"""
n_face = len(mesh.nodes_per_face)
n_max_node = mesh.nodes_per_face.max()
fill_value = -1
face_node_connectivity = np.full((n_face, n_max_node), fill_value)
isnode = connectivity.ragged_index(n_face, n_max_node, mesh.nodes_per_face)
face_node_connectivity[isnode] = mesh.face_nodes
return cls(
mesh.node_x,
mesh.node_y,
fill_value=fill_value,
face_node_connectivity=face_node_connectivity,
name=name,
projected=projected,
crs=crs,
)
@classmethod
def from_dataset(cls, dataset: xr.Dataset, topology: str = None):
"""
Extract the 2D UGRID topology information from an xarray Dataset.
Parameters
----------
dataset: xr.Dataset
Dataset containing topology information stored according to UGRID conventions.
Returns
-------
grid: Ugrid1dAdapter
"""
ds = dataset
if not isinstance(ds, xr.Dataset):
raise TypeError(
"Ugrid should be initialized with xarray.Dataset. "
f"Received instead: {type(ds)}"
)
if topology is None:
topology = cls._single_topology(ds)
indexes = {}
# Collect names
connectivity = ds.ugrid_roles.connectivity[topology]
coordinates = ds.ugrid_roles.coordinates[topology]
ugrid_vars = (
[topology]
+ list(connectivity.values())
+ list(chain.from_iterable(chain.from_iterable(coordinates.values())))
)
x_index = coordinates["node_coordinates"][0][0]
y_index = coordinates["node_coordinates"][1][0]
node_x_coordinates = ds[x_index].astype(FloatDType).to_numpy()
node_y_coordinates = ds[y_index].astype(FloatDType).to_numpy()
face_nodes = connectivity["face_node_connectivity"]
fill_value = ds[face_nodes].encoding.get("_FillValue", -1)
face_node_connectivity = cls._prepare_connectivity(
ds[face_nodes], fill_value, dtype=IntDType
).to_numpy()
edge_nodes = connectivity.get("edge_node_connectivity")
if edge_nodes:
edge_node_connectivity = cls._prepare_connectivity(
ds[edge_nodes], fill_value, dtype=IntDType
).to_numpy()
else:
edge_node_connectivity = None
indexes["node_x"] = x_index
indexes["node_y"] = y_index
projected = False # TODO
return cls(
node_x_coordinates,
node_y_coordinates,
fill_value,
face_node_connectivity,
name=topology,
edge_node_connectivity=edge_node_connectivity,
dataset=ds[ugrid_vars],
indexes=indexes,
projected=projected,
crs=None,
)
def _get_name_and_attrs(self, name: str):
key = f"{name}_connectivity"
attrs = conventions.DEFAULT_ATTRS[key]
if "_FillValue" in attrs:
attrs["_FillValue"] = self.fill_value
return self._attrs[key], attrs
def to_dataset(
self, other: xr.Dataset = None, optional_attributes: bool = False
) -> xr.Dataset:
node_x = self._indexes["node_x"]
node_y = self._indexes["node_y"]
face_nodes, face_nodes_attrs = self._get_name_and_attrs("face_node")
nmax_node_dim = self._attrs["max_face_nodes_dimension"]
edge_nodes, edge_nodes_attrs = self._get_name_and_attrs("edge_node")
data_vars = {
self.name: 0,
face_nodes: xr.DataArray(
data=self.face_node_connectivity,
attrs=face_nodes_attrs,
dims=(self.face_dimension, nmax_node_dim),
),
}
if self.edge_node_connectivity is not None or optional_attributes:
data_vars[edge_nodes] = xr.DataArray(
data=self.edge_node_connectivity,
attrs=edge_nodes_attrs,
dims=(self.edge_dimension, "two"),
)
if optional_attributes:
face_edges, face_edges_attrs = self._get_name_and_attrs("face_edge")
face_faces, face_faces_attrs = self._get_name_and_attrs("face_face")
edge_faces, edge_faces_attrs = self._get_name_and_attrs("edge_face")
bound_nodes, bound_nodes_attrs = self._get_name_and_attrs("boundary_node")
fill_value = self.fill_value
boundary_edge_dim = self._attrs["boundary_edge_dimension"]
data_vars[face_edges] = xr.DataArray(
data=self.face_edge_connectivity,
attrs=face_edges_attrs,
dims=(self.face_dimension, nmax_node_dim),
)
data_vars[face_faces] = xr.DataArray(
data=connectivity.to_dense(
self.face_face_connectivity, fill_value, self.n_max_node_per_face
),
attrs=face_faces_attrs,
dims=(self.face_dimension, nmax_node_dim),
)
data_vars[edge_faces] = xr.DataArray(
data=self.edge_face_connectivity,
attrs=edge_faces_attrs,
dims=(self.edge_dimension, "two"),
)
data_vars[bound_nodes] = xr.DataArray(
data=self.boundary_node_connectivity,
attrs=bound_nodes_attrs,
dims=(boundary_edge_dim, "two"),
)
attrs = {"Conventions": "CF-1.9 UGRID-1.0"}
if other is not None:
attrs.update(other.attrs)
dataset = xr.Dataset(data_vars, attrs=attrs)
if self._dataset:
dataset.update(self._dataset)
if other is not None:
dataset = dataset.merge(other)
if node_x not in dataset or node_y not in dataset:
dataset = self.assign_node_coords(dataset)
if optional_attributes:
dataset = self.assign_face_coords(dataset)
dataset = self.assign_edge_coords(dataset)
dataset[self.name].attrs = self._filtered_attrs(dataset)
return dataset
# These are all optional/derived UGRID attributes. They are not computed by
# default, only when called upon.
@property
def n_face(self) -> int:
"""Return the number of faces in the UGRID2D topology."""
return self.face_node_connectivity.shape[0]
@property
def n_max_node_per_face(self) -> int:
"""
Return the maximum number of nodes that a face can contain in the
UGRID2D topology.
"""
return self.face_node_connectivity.shape[1]
@property
def n_node_per_face(self) -> IntArray:
return (self.face_node_connectivity != self.fill_value).sum(axis=1)
@property
def core_dimension(self):
return self.face_dimension
@property
def dimensions(self):
return {
self.node_dimension: self.n_node,
self.edge_dimension: self.n_edge,
self.face_dimension: self.n_face,
}
@property
def topology_dimension(self):
"""Highest dimensionality of the geometric elements: 2"""
return 2
@property
def face_dimension(self):
"""Return the name of the face dimension."""
return self._attrs["face_dimension"]
def _edge_connectivity(self):
(
self._edge_node_connectivity,
self._face_edge_connectivity,
) = connectivity.edge_connectivity(
self.face_node_connectivity,
self.fill_value,
self._edge_node_connectivity,
)
@property
def edge_node_connectivity(self) -> IntArray:
"""
Edge to node connectivity. Every edge consists of a connection between
two nodes.
Returns
-------
connectivity: ndarray of integers with shape ``(n_edge, 2)``.
"""
if self._edge_node_connectivity is None:
self._edge_connectivity()
return self._edge_node_connectivity
@edge_node_connectivity.setter
def edge_node_connectivity(self, value):
self._edge_node_connectivity = value
@property
def face_edge_connectivity(self) -> csr_matrix:
"""
Face to edge connectivity.
Returns
-------
connectivity: csr_matrix
"""
if self._face_edge_connectivity is None:
self._edge_connectivity()
return self._face_edge_connectivity
@property
def boundary_node_connectivity(self) -> IntArray:
"""
Boundary node connectivity
Returns
-------
connectivity: ndarray of integers with shape ``(n_boundary_edge, 2)``
"""
if self._boundary_node_connectivity is None:
self._boundary_node_connectivity = connectivity.boundary_node_connectivity(
self.edge_face_connectivity,
self.fill_value,
self.edge_node_connectivity,
)
return self._boundary_node_connectivity
@property
def centroids(self) -> FloatArray:
"""
Centroid (x, y) of every face.
Returns
-------
centroids: ndarray of floats with shape ``(n_face, 2)``
"""
if self._centroids is None:
self._centroids = connectivity.centroids(
self.face_node_connectivity,
self.fill_value,
self.node_x,
self.node_y,
)
return self._centroids
@property
def circumcenters(self):
"""
Circumenter (x, y) of every face; only works for fully triangular
grids.
"""
if self._circumcenters is None:
self._circumcenters = connectivity.circumcenters(
self.face_node_connectivity,
self.fill_value,
self.node_x,
self.node_y,
)
return self._circumcenters
@property
def area(self) -> FloatArray:
"""Area of every face."""
if self._area is None:
self._area = connectivity.area(
self.face_node_connectivity,
self.fill_value,
self.node_x,
self.node_y,
)
return self._area
@property
def perimeter(self) -> FloatArray:
"""Perimeter length of every face."""
if self._perimeter is None:
self._perimeter = connectivity.perimeter(
self.face_node_connectivity,
self.fill_value,
self.node_x,
self.node_y,
)
return self._perimeter
@property
def face_bounds(self):
"""
Returns a numpy array with columns ``minx, miny, maxx, maxy``,
describing the bounds of every face in the grid.
Returns
-------
face_bounds: np.ndarray of shape (n_face, 4)
"""
x = self.node_x[self.face_node_connectivity]
y = self.node_y[self.face_node_connectivity]
isfill = self.face_node_connectivity == self.fill_value
x[isfill] = np.nan
y[isfill] = np.nan
return np.column_stack(
[
np.nanmin(x, axis=1),
np.nanmin(y, axis=1),
np.nanmax(x, axis=1),
np.nanmax(y, axis=1),
]
)
@property
def face_x(self):
"""x-coordinate of centroid of every face"""
return self.centroids[:, 0]
@property
def face_y(self):
"""y-coordinate of centroid of every face"""
return self.centroids[:, 1]
@property
def face_coordinates(self) -> FloatArray:
"""
Centroid (x, y) of every face.
Returns
-------
centroids: ndarray of floats with shape ``(n_face, 2)``
"""
return self.centroids
@property
def face_node_coordinates(self) -> FloatArray:
"""
Node coordinates of every face.
"Fill node" coordinates are set as NaN.
Returns
-------
face_node_coordinates: ndarray of floats with shape ``(n_face, n_max_node_per_face, 2)``
"""
coords = np.full(
(self.n_face, self.n_max_node_per_face, 2), np.nan, dtype=FloatDType
)
is_node = self.face_node_connectivity != self.fill_value
index = self.face_node_connectivity[is_node]
coords[is_node, :] = self.node_coordinates[index]
return coords
@property
def edge_face_connectivity(self) -> IntArray:
"""
Edge to face connectivity. An edge may belong to a single face
(exterior edge), or it may be shared by two faces (interior edge).
An exterior edge will contain a ``fill_value`` for the second column.
Returns
-------
connectivity: ndarray of integers with shape ``(n_edge, 2)``.
"""
if self._edge_face_connectivity is None:
self._edge_face_connectivity = connectivity.invert_dense(
self.face_edge_connectivity, self.fill_value
)
return self._edge_face_connectivity
@property
def face_face_connectivity(self) -> csr_matrix:
"""
Face to face connectivity. Derived from shared edges.
The connectivity is represented as an adjacency matrix in CSR format,
with the row and column indices as a (0-based) face index. The data of
the matrix contains the edge index as every connection is formed by a
shared edge.
Returns
-------
connectivity: csr_matrix
"""
if self._face_face_connectivity is None:
self._face_face_connectivity = connectivity.face_face_connectivity(
self.edge_face_connectivity, self.fill_value
)
return self._face_face_connectivity
@property
def node_face_connectivity(self):
"""
Node to face connectivity. Inverted from face node connectivity.
Returns
-------
connectivity: csr_matrix
"""
if self._node_face_connectivity is None:
self._node_face_connectivity = connectivity.invert_dense_to_sparse(
self.face_node_connectivity, self.fill_value
)
return self._node_face_connectivity
@property
def mesh(self) -> "mk.Mesh2d": # type: ignore # noqa
"""
Create if needed, and return meshkernel Mesh2d object.
Returns
-------
mesh: meshkernel.Mesh2d
"""
import meshkernel as mk
edge_nodes = self.edge_node_connectivity.ravel().astype(np.int32)
is_node = self.face_node_connectivity != self.fill_value
nodes_per_face = is_node.sum(axis=1).astype(np.int32)
face_nodes = self.face_node_connectivity[is_node].ravel().astype(np.int32)
if self._mesh is None:
self._mesh = mk.Mesh2d(
node_x=self.node_x,
node_y=self.node_y,
edge_nodes=edge_nodes,
face_nodes=face_nodes,
nodes_per_face=nodes_per_face,
)
return self._mesh
@property
def meshkernel(self) -> "mk.MeshKernel": # type: ignore # noqa
"""
Create if needed, and return meshkernel MeshKernel instance.
Returns
-------
meshkernel: meshkernel.MeshKernel
"""
import meshkernel as mk
if self._meshkernel is None:
self._meshkernel = mk.MeshKernel()
self._meshkernel.mesh2d_set(self.mesh)
return self._meshkernel
@property
def voronoi_topology(self):
"""
Centroidal Voronoi tesselation of this UGRID2D topology.
Returns
-------
vertices: ndarray of floats with shape ``(n_centroids, 2)``
face_node_connectivity: csr_matrix
Describes face node connectivity of voronoi topology.
face_index: 1d array of integers
"""
if self._voronoi_topology is None:
vertices, faces, face_index = voronoi_topology(
self.node_face_connectivity,
self.node_coordinates,
self.centroids,
self.edge_face_connectivity,
self.edge_node_connectivity,
self.fill_value,
add_exterior=True,
add_vertices=False,
)
self._voronoi_topology = vertices, faces, face_index
return self._voronoi_topology
@property
def centroid_triangulation(self):
"""
Triangulation of centroidal voronoi tesselation.
Required for e.g. contouring face data, which takes triangles and
associated values at the triangle vertices.
Returns
-------
vertices: ndarray of floats with shape ``(n_centroids, 2)``
face_node_connectivity: ndarray of integers with shape ``(n_triangle, 3)``
Describes face node connectivity of triangle topology.
face_index: 1d array of integers
"""
if self._centroid_triangulation is None:
nodes, faces, face_index = self.voronoi_topology
triangles, _ = connectivity.triangulate(faces, self.fill_value)
triangulation = (nodes[:, 0].copy(), nodes[:, 1].copy(), triangles)
self._centroid_triangulation = (triangulation, face_index)
return self._centroid_triangulation
@property
def triangulation(self):
"""
Triangulation of the UGRID2D topology.
Returns
-------
triangulation: tuple
Contains node_x, node_y, triangle face_node_connectivity.
triangle_face_connectivity: 1d array of integers
Identifies the original face for every triangle.
"""
if self._triangulation is None:
triangles, triangle_face_connectivity = connectivity.triangulate(
self.face_node_connectivity, self.fill_value
)
triangulation = (self.node_x, self.node_y, triangles)
self._triangulation = (triangulation, triangle_face_connectivity)
return self._triangulation
@property
def exterior_edges(self) -> IntArray:
"""
Get all exterior edges, i.e. edges with no other face.
Returns
-------
edge_index: 1d array of integers
"""
# Numpy argwhere doesn't return a 1D array
return np.nonzero(self.edge_face_connectivity[:, 1] == self.fill_value)[0]
@property
def exterior_faces(self) -> IntArray:
"""
Get all exterior faces, i.e. faces with an unshared edge.
Returns
-------
face_index: 1d array of integers
"""
exterior_edges = self.exterior_edges
exterior_faces = self.edge_face_connectivity[exterior_edges].ravel()
return np.unique(exterior_faces[exterior_faces != self.fill_value])
@property
def celltree(self):
"""
Initializes the celltree if needed, and returns celltree.
A celltree is a search structure for spatial lookups in unstructured grids.
"""
if self._celltree is None:
self._celltree = CellTree2d(
self.node_coordinates, self.face_node_connectivity, self.fill_value
)
return self._celltree
def validate_edge_node_connectivity(self):
"""
Mark valid edges, by comparing face_node_connectivity and
edge_node_connectivity. Edges that are not part of a face, as well as
duplicate edges are marked ``False``.
An error is raised if the face_node_connectivity defines more unique
edges than the edge_node_connectivity.
Returns
-------
valid: np.ndarray of bool
Marks for every edge whether it is valid.
Examples
--------
To purge invalid edges and associated data from a dataset that contains
un-associated or duplicate edges:
>>> uds = xugrid.open_dataset("example.nc")
>>> valid = uds.ugrid.grid.validate_edge_node_connectivity()
>>> purged = uds.isel({grid.edge_dimension: valid})
"""
return connectivity.validate_edge_node_connectivity(
self.face_node_connectivity,
self.fill_value,
self.edge_node_connectivity,
)
def assign_face_coords(
self,
obj: Union[xr.DataArray, xr.Dataset],
) -> Union[xr.DataArray, xr.Dataset]:
"""
Assign face coordinates from the grid to the object.
Returns a new object with all the original data in addition to the new
node coordinates of the grid.
Parameters
----------
obj: xr.DataArray or xr.Dataset
Returns
-------
assigned (same type as obj)
"""
xname = self._indexes.get("face_x", f"{self.name}_face_x")
yname = self._indexes.get("face_y", f"{self.name}_face_y")
x_attrs = conventions.DEFAULT_ATTRS["face_x"][self.projected]
y_attrs = conventions.DEFAULT_ATTRS["face_y"][self.projected]
coords = {
xname: xr.DataArray(
data=self.face_x,
dims=(self.face_dimension,),
attrs=x_attrs,
),
yname: xr.DataArray(
data=self.face_y,
dims=(self.face_dimension,),
attrs=y_attrs,
),
}
return obj.assign_coords(coords)
def locate_points(self, points: FloatArray):
"""
Find in which face points are located.
Parameters
----------
points: ndarray of floats with shape ``(n_point, 2)``
Returns
-------
face_index: ndarray of integers with shape ``(n_points,)``
"""
return self.celltree.locate_points(points)
def intersect_edges(self, edges: FloatArray):
"""
Find in which face edges are located and compute the intersection with
the face edges.
Parameters
----------
edges: ndarray of floats with shape ``(n_edge, 2, 2)``
The first dimensions represents the different edges.
The second dimensions represents the start and end of every edge.
The third dimensions reresent the x and y coordinate of every vertex.
Returns
-------
edge_index: ndarray of integers with shape ``(n_intersection,)``
face_index: ndarray of integers with shape ``(n_intersection,)``
intersections: ndarray of float with shape ``(n_intersection, 2, 2)``
"""
return self.celltree.intersect_edges(edges)
def locate_bounding_box(
self, xmin: float, ymin: float, xmax: float, ymax: float
) -> IntArray:
"""
Find which faces are located in the bounding box. The centroids of the
faces are used.
Parameters
----------
xmin: float,
ymin: float,
xmax: float,
ymax: float
Returns
-------
face_index: ndarray of bools with shape ``(n_face,)``
"""
return np.nonzero(
(self.face_x >= xmin)
& (self.face_x < xmax)
& (self.face_y >= ymin)
& (self.face_y < ymax)
)[0]
def compute_barycentric_weights(
self, points: FloatArray
) -> Tuple[IntArray, FloatArray]:
"""
Find in which face the points are located, and compute the barycentric
weight for every vertex of the face.
Parameters
----------
points: ndarray of floats with shape ``(n_point, 2)``
Returns
-------
face_index: ndarray of integers with shape ``(n_points,)``
weights: ndarray of floats with shape ```(n_points, n_max_node)``
"""
return self.celltree.compute_barycentric_weights(points)
def rasterize_like(
self, x: FloatArray, y: FloatArray
) -> Tuple[FloatArray, FloatArray, IntArray]:
"""
Rasterize unstructured grid by sampling on the x and y coordinates.
Parameters
----------
x: 1d array of floats with shape ``(ncol,)``
y: 1d array of floats with shape ``(nrow,)``
Returns
-------
x: 1d array of floats with shape ``(ncol,)``
y: 1d array of floats with shape ``(nrow,)``
face_index: 1d array of integers with shape ``(nrow * ncol,)``
"""
yy, xx = np.meshgrid(y, x, indexing="ij")
nodes = np.column_stack([xx.ravel(), yy.ravel()])
index = self.celltree.locate_points(nodes).reshape((y.size, x.size))
return x, y, index
def rasterize(
self,
resolution: float,
bounds: Optional[Tuple[float, float, float, float]] = None,
) -> Tuple[FloatArray, FloatArray, IntArray]:
"""
Rasterize unstructured grid by sampling.
x and y coordinates are generated from the bounds of the UGRID2D
topology and the provided resolution.
Parameters
----------
resolution: float
Spacing in x and y.
bounds: tuple of four floats, optional
xmin, ymin, xmax, ymax
Returns
-------
x: 1d array of floats with shape ``(ncol,)``
y: 1d array of floats with shape ``(nrow,)``
face_index: 1d array of integers with shape ``(nrow * ncol,)``
"""
if bounds is None:
bounds = self.bounds
xmin, ymin, xmax, ymax = bounds
d = abs(resolution)
xmin = np.floor(xmin / d) * d
xmax = np.ceil(xmax / d) * d