-
Notifications
You must be signed in to change notification settings - Fork 304
/
gridintersect.py
1693 lines (1495 loc) · 56 KB
/
gridintersect.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
import numpy as np
try:
import matplotlib.pyplot as plt
except (ImportError, RuntimeError):
plt = None
from .geometry import transform
from .geospatial_utils import GeoSpatialUtil
try:
from shapely.geometry import (
MultiPoint,
Point,
Polygon,
box,
GeometryCollection,
MultiPolygon,
)
from shapely.strtree import STRtree
from shapely.affinity import translate, rotate
from shapely.prepared import prep
shply = True
except:
shply = False
import contextlib
import warnings
from distutils.version import LooseVersion
try:
import shapely
SHAPELY_GE_20 = str(shapely.__version__) >= LooseVersion("2.0")
except:
shapely = None
SHAPELY_GE_20 = False
try:
from shapely.errors import ShapelyDeprecationWarning as shapely_warning
except:
shapely_warning = None
if shapely_warning is not None and not SHAPELY_GE_20:
@contextlib.contextmanager
def ignore_shapely_warnings_for_object_array():
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=shapely_warning)
yield
else:
@contextlib.contextmanager
def ignore_shapely_warnings_for_object_array():
yield
def parse_shapely_ix_result(collection, ix_result, shptyps=None):
"""Recursive function for parsing shapely intersection results. Returns a
list of shapely shapes matching shptyp.
Parameters
----------
collection : list
state variable for storing result, generally
an empty list
ix_result : shapely.geometry type
any shapely intersection result
shptyp : str, list of str, or None, optional
if None (default), return all types of shapes.
if str, return shapes of that type, if list of str,
return all types in list
Returns
-------
collection : list
list containing shapely geometries of type shptyp
"""
# convert shptyps to list if needed
if isinstance(shptyps, str):
shptyps = [shptyps]
elif shptyps is None:
shptyps = [None]
# if empty
if ix_result.is_empty:
return collection
# base case: geom_type is partial or exact match to shptyp
elif ix_result.geom_type in shptyps:
collection.append(ix_result)
return collection
# recursion for collections
elif hasattr(ix_result, "geoms"):
for ishp in ix_result.geoms:
parse_shapely_ix_result(collection, ishp, shptyps=shptyps)
# if collecting all types
elif shptyps[0] is None:
return collection.append(ix_result)
return collection
class GridIntersect:
"""Class for intersecting shapely shapes (Point, Linestring, Polygon, or
their Multi variants) with MODFLOW grids. Contains optimized search
routines for structured grids.
Notes
-----
- The STR-tree query is based on the bounding box of the shape or
collection, if the bounding box of the shape covers nearly the entire
grid, the query won't be able to limit the search space much, resulting
in slower performance. Therefore, it can sometimes be faster to
intersect each individual shape in a collection than it is to intersect
with the whole collection at once.
- Building the STR-tree can take a while for large grids. Once built the
intersect routines (for individual shapes) should be pretty fast. It
is possible to perform intersects without building the STR-tree by
setting `rtree=False`.
- The optimized routines for structured grids will often outperform
the shapely routines because of the reduced overhead of building and
parsing the STR-tree. However, for polygons the STR-tree implementation
is often faster than the optimized structured routines, especially
for larger grids.
"""
def __init__(self, mfgrid, method=None, rtree=True):
"""Intersect shapes (Point, Linestring, Polygon) with a modflow grid.
Parameters
----------
mfgrid : flopy modflowgrid
MODFLOW grid as implemented in flopy
method : str, optional
default is None, which determines intersection method based on
the grid type. Options are either 'vertex' which uses shapely
interesection operations or 'structured' which uses optimized
methods that only work for structured grids
rtree : bool, optional
whether to build an STR-Tree, default is True. If False no
STR-tree is built (which saves some time), but intersects will
loop through all model gridcells (which is generally slower).
Only read when `method='vertex'`.
"""
if not shply:
msg = (
"Shapely is needed for grid intersect operations! "
"Please install shapely if you need to use grid intersect "
"functionality."
)
raise ModuleNotFoundError(msg)
self.mfgrid = mfgrid
if method is None:
# determine method from grid_type
self.method = self.mfgrid.grid_type
else:
# set method
self.method = method
self.rtree = rtree
if self.method == "vertex":
# set method to get gridshapes depending on grid type
self._set_method_get_gridshapes()
# build STR-tree if specified
if self.rtree:
self.strtree = STRtree(self._get_gridshapes())
elif self.method == "structured" and mfgrid.grid_type == "structured":
pass
else:
raise ValueError(
"Method '{0}' not recognized or "
"not supported "
"for grid_type '{1}'!".format(
self.method, self.mfgrid.grid_type
)
)
def intersect(self, shp, **kwargs):
"""
Method to intersect a shape with a model grid
Parameters
----------
shp : shapely.geometry, geojson object, shapefile.Shape,
or flopy geomerty object
sort_by_cellid : bool
Sort results by cellid
keepzerolengths : bool
boolean method to keep zero length intersections for
linestring intersection
Returns
-------
numpy.recarray
a record array containing information about the intersection
"""
gu = GeoSpatialUtil(shp)
shp = gu.shapely
sort_by_cellid = kwargs.pop("sort_by_cellid", True)
keepzerolengths = kwargs.pop("keepzerolengths", False)
if gu.shapetype in ("Point", "MultiPoint"):
if (
self.method == "structured"
and self.mfgrid.grid_type == "structured"
):
rec = self._intersect_point_structured(shp)
else:
rec = self._intersect_point_shapely(shp, sort_by_cellid)
elif gu.shapetype in ("LineString", "MultiLineString"):
if (
self.method == "structured"
and self.mfgrid.grid_type == "structured"
):
rec = self._intersect_linestring_structured(
shp, keepzerolengths
)
else:
rec = self._intersect_linestring_shapely(
shp, keepzerolengths, sort_by_cellid
)
elif gu.shapetype in ("Polygon", "MultiPolygon"):
if (
self.method == "structured"
and self.mfgrid.grid_type == "structured"
):
rec = self._intersect_polygon_structured(shp)
else:
rec = self._intersect_polygon_shapely(shp, sort_by_cellid)
else:
err = "Shapetype {} is not supported".format(gu.shapetype)
raise TypeError(err)
return rec
def _set_method_get_gridshapes(self):
"""internal method, set self._get_gridshapes to the certain method for
obtaining gridcells."""
# Set method for obtaining grid shapes
if self.mfgrid.grid_type == "structured":
self._get_gridshapes = self._rect_grid_to_shape_generator
elif self.mfgrid.grid_type == "vertex":
self._get_gridshapes = self._vtx_grid_to_shape_generator
elif self.mfgrid.grid_type == "unstructured":
raise NotImplementedError()
def _rect_grid_to_shape_generator(self):
"""internal method, generator yielding shapely polygons for structured
grid cells.
Returns
-------
generator :
generator of shapely Polygons
"""
for i in range(self.mfgrid.nrow):
for j in range(self.mfgrid.ncol):
xy = self.mfgrid.get_cell_vertices(i, j)
p = Polygon(xy)
p.name = (i, j)
yield p
def _usg_grid_to_shape_generator(self):
"""internal method, convert unstructred grid to list of shapely
polygons.
Returns
-------
list
list of shapely Polygons
"""
raise NotImplementedError()
def _vtx_grid_to_shape_generator(self):
"""internal method, generator yielding shapely polygons for vertex
grids.
Returns
-------
generator :
generator of shapely Polygons
"""
# for cell2d rec-arrays
if isinstance(self.mfgrid._cell2d, np.recarray):
for icell in self.mfgrid._cell2d.icell2d:
points = []
icverts = [
"icvert_{}".format(i)
for i in range(self.mfgrid._cell2d["ncvert"][icell])
]
for iv in self.mfgrid._cell2d[icverts][icell]:
points.append(
(
self.mfgrid._vertices.xv[iv],
self.mfgrid._vertices.yv[iv],
)
)
# close the polygon, if necessary
if points[0] != points[-1]:
points.append(points[0])
p = Polygon(points)
p.name = icell
yield p
# for cell2d lists
elif isinstance(self.mfgrid._cell2d, list):
for icell in range(len(self.mfgrid._cell2d)):
points = []
for iv in self.mfgrid._cell2d[icell][4:]:
points.append(
(
self.mfgrid._vertices[iv][1],
self.mfgrid._vertices[iv][2],
)
)
# close the polygon, if necessary
if points[0] != points[-1]:
points.append(points[0])
p = Polygon(points)
p.name = icell
yield p
def _rect_grid_to_shape_list(self):
"""internal method, list of shapely polygons for structured grid cells.
Returns
-------
list :
list of shapely Polygons
"""
return list(self._rect_grid_to_shape_generator())
def _usg_grid_to_shape_list(self):
"""internal method, convert unstructred grid to list of shapely
polygons.
Returns
-------
list
list of shapely Polygons
"""
raise NotImplementedError()
def _vtx_grid_to_shape_list(self):
"""internal method, list of shapely polygons for vertex grids.
Returns
-------
list :
list of shapely Polygons
"""
return list(self._vtx_grid_to_shape_generator())
def query_grid(self, shp):
"""Perform spatial query on grid with shapely geometry. If no spatial
query is possible returns all grid cells.
Parameters
----------
shp : shapely.geometry
shapely geometry
Returns
-------
list or generator expression
list or generator containing grid cells in query result
"""
if self.rtree:
result = self.strtree.query(shp)
else:
# no spatial query
result = self._get_gridshapes()
return result
@staticmethod
def filter_query_result(qresult, shp):
"""Filter query result to obtain grid cells that intersect with shape.
Used to (further) reduce query result to cells that definitely
intersect with shape.
Parameters
----------
qresult : iterable
query result, iterable of polygons
shp : shapely.geometry
shapely geometry that is prepared and used to filter
query result
Returns
-------
qfiltered
filter or generator containing polygons that intersect with shape
"""
# prepare shape for efficient batch intersection check
prepshp = prep(shp)
# get only gridcells that intersect
qfiltered = filter(prepshp.intersects, qresult)
return qfiltered
@staticmethod
def sort_gridshapes(shape_iter):
"""Sort query result by node id.
Parameters
----------
shape_iter : iterable
list or iterable of gridcells
Returns
-------
list
sorted list of gridcells
"""
if not isinstance(shape_iter, list):
shapelist = list(shape_iter)
else:
shapelist = shape_iter
def sort_key(o):
return o.name
shapelist.sort(key=sort_key)
return shapelist
def _intersect_point_shapely(self, shp, sort_by_cellid=True):
"""intersect grid with Point or MultiPoint.
Parameters
----------
shp : Point or MultiPoint
shapely Point or MultiPoint to intersect with grid. Note,
it is generally faster to loop over a MultiPoint and intersect
per point than to intersect a MultiPoint directly.
sort_by_cellid : bool, optional
flag whether to sort cells by id, used to ensure node
with lowest id is returned, by default True
Returns
-------
numpy.recarray
a record array containing information about the intersection
"""
# query grid
qresult = self.query_grid(shp)
# prepare shape for efficient batch intersection check
prepshp = prep(shp)
# get only gridcells that intersect
qfiltered = filter(prepshp.intersects, qresult)
# sort cells to ensure lowest cell ids are returned
if sort_by_cellid:
qfiltered = self.sort_gridshapes(qfiltered)
isectshp = []
cellids = []
vertices = []
parsed_points = [] # for keeping track of points
# loop over cells returned by filtered spatial query
for r in qfiltered:
name = r.name
# do intersection
intersect = shp.intersection(r)
# parse result per Point
collection = parse_shapely_ix_result(
[], intersect, shptyps=["Point"]
)
# loop over intersection result and store information
cell_verts = []
cell_shps = []
for c in collection:
verts = c.__geo_interface__["coordinates"]
# avoid returning multiple cells for points on boundaries
if verts in parsed_points:
continue
parsed_points.append(verts)
cell_shps.append(c) # collect only new points
cell_verts.append(verts)
# if any new ix found
if len(cell_shps) > 0:
# combine new points in MultiPoint
isectshp.append(
MultiPoint(cell_shps)
if len(cell_shps) > 1
else cell_shps[0]
)
vertices.append(tuple(cell_verts))
cellids.append(name)
rec = np.recarray(
len(isectshp),
names=["cellids", "vertices", "ixshapes"],
formats=["O", "O", "O"],
)
with ignore_shapely_warnings_for_object_array():
rec.ixshapes = isectshp
rec.vertices = vertices
rec.cellids = cellids
return rec
def _intersect_linestring_shapely(
self, shp, keepzerolengths=False, sort_by_cellid=True
):
"""intersect with LineString or MultiLineString.
Parameters
----------
shp : shapely.geometry.LineString or MultiLineString
LineString to intersect with the grid
keepzerolengths : bool, optional
keep linestrings with length zero, default is False
sort_by_cellid : bool, optional
flag whether to sort cells by id, used to ensure node
with lowest id is returned, by default True
Returns
-------
numpy.recarray
a record array containing information about the intersection
"""
# query grid
qresult = self.query_grid(shp)
# filter result further if possible (only strtree and filter methods)
qfiltered = self.filter_query_result(qresult, shp)
# sort cells to ensure lowest cell ids are returned
if sort_by_cellid:
qfiltered = self.sort_gridshapes(qfiltered)
# initialize empty lists for storing results
isectshp = []
cellids = []
vertices = []
lengths = []
# loop over cells returned by filtered spatial query
for r in qfiltered:
name = r.name
# do intersection
intersect = shp.intersection(r)
# parse result
collection = parse_shapely_ix_result(
[], intersect, shptyps=["LineString", "MultiLineString"]
)
# loop over intersection result and store information
for c in collection:
verts = c.__geo_interface__["coordinates"]
# test if linestring was already processed (if on boundary)
if verts in vertices:
continue
# if keep zero don't check length
if not keepzerolengths:
if c.length == 0.0:
continue
isectshp.append(c)
lengths.append(c.length)
vertices.append(verts)
cellids.append(name)
rec = np.recarray(
len(isectshp),
names=["cellids", "vertices", "lengths", "ixshapes"],
formats=["O", "O", "f8", "O"],
)
with ignore_shapely_warnings_for_object_array():
rec.ixshapes = isectshp
rec.vertices = vertices
rec.lengths = lengths
rec.cellids = cellids
return rec
def _intersect_polygon_shapely(self, shp, sort_by_cellid=True):
"""intersect with Polygon or MultiPolygon.
Parameters
----------
shp : shapely.geometry.Polygon or MultiPolygon
shape to intersect with the grid
sort_by_cellid : bool, optional
flag whether to sort cells by id, used to ensure node
with lowest id is returned, by default True
Returns
-------
numpy.recarray
a record array containing information about the intersection
"""
# query grid
qresult = self.query_grid(shp)
# filter result further if possible (only strtree and filter methods)
qfiltered = self.filter_query_result(qresult, shp)
# sort cells to ensure lowest cell ids are returned
if sort_by_cellid:
qfiltered = self.sort_gridshapes(qfiltered)
isectshp = []
cellids = []
vertices = []
areas = []
# loop over cells returned by filtered spatial query
for r in qfiltered:
name = r.name
# do intersection
intersect = shp.intersection(r)
# parse result
collection = parse_shapely_ix_result(
[], intersect, shptyps=["Polygon", "MultiPolygon"]
)
if len(collection) > 1:
collection = [MultiPolygon(collection)]
# loop over intersection result and store information
for c in collection:
# don't store intersections with 0 area
if c.area == 0.0:
continue
verts = c.__geo_interface__["coordinates"]
isectshp.append(c)
areas.append(c.area)
vertices.append(verts)
cellids.append(name)
rec = np.recarray(
len(isectshp),
names=["cellids", "vertices", "areas", "ixshapes"],
formats=["O", "O", "f8", "O"],
)
with ignore_shapely_warnings_for_object_array():
rec.ixshapes = isectshp
rec.vertices = vertices
rec.areas = areas
rec.cellids = cellids
return rec
def intersects(self, shp):
"""Return cellIDs for shapes that intersect with shape.
Parameters
----------
shp : shapely.geometry, geojson geometry, shapefile.shape,
or flopy geometry object
shape to intersect with the grid
Returns
-------
rec : numpy.recarray
a record array containing cell IDs of the gridcells
the shape intersects with
"""
# query grid
shp = GeoSpatialUtil(shp).shapely
qresult = self.query_grid(shp)
# filter result further if possible (only strtree and filter methods)
qfiltered = self.filter_query_result(qresult, shp)
# get cellids
cids = [cell.name for cell in qfiltered]
# build rec-array
rec = np.recarray(len(cids), names=["cellids"], formats=["O"])
rec.cellids = cids
return rec
def _intersect_point_structured(self, shp):
"""intersection method for intersecting points with structured grids.
Parameters
----------
shp : shapely.geometry.Point or MultiPoint
point shape to intersect with grid
Returns
-------
numpy.recarray
a record array containing information about the intersection
"""
nodelist = []
Xe, Ye = self.mfgrid.xyedges
if isinstance(shp, Point):
shp = [shp]
elif isinstance(shp, MultiPoint):
shp = list(shp.geoms)
else:
raise ValueError("expected Point or MultiPoint")
ixshapes = []
for p in shp:
# if grid is rotated or offset transform point to local coords
if (
self.mfgrid.angrot != 0.0
or self.mfgrid.xoffset != 0.0
or self.mfgrid.yoffset != 0.0
):
rx, ry = transform(
p.x,
p.y,
self.mfgrid.xoffset,
self.mfgrid.yoffset,
self.mfgrid.angrot_radians,
inverse=True,
)
else:
rx = p.x
ry = p.y
# two dimensional point
jpos = ModflowGridIndices.find_position_in_array(Xe, rx)
ipos = ModflowGridIndices.find_position_in_array(Ye, ry)
if jpos is not None and ipos is not None:
# three dimensional point
if p._ndim == 3:
# find k
kpos = ModflowGridIndices.find_position_in_array(
self.mfgrid.botm[:, ipos, jpos], p.z
)
if kpos is not None:
nodelist.append((kpos, ipos, jpos))
ixshapes.append(p)
else:
nodelist.append((ipos, jpos))
ixshapes.append(p)
# remove duplicates
tempnodes = []
tempshapes = []
for node, ixs in zip(nodelist, ixshapes):
if node not in tempnodes:
tempnodes.append(node)
tempshapes.append(ixs)
else:
# TODO: not sure if this is correct
tempshapes[-1] = MultiPoint([tempshapes[-1], ixs])
ixshapes = tempshapes
nodelist = tempnodes
rec = np.recarray(
len(nodelist), names=["cellids", "ixshapes"], formats=["O", "O"]
)
rec.cellids = nodelist
with ignore_shapely_warnings_for_object_array():
rec.ixshapes = ixshapes
return rec
def _intersect_linestring_structured(self, shp, keepzerolengths=False):
"""method for intersecting linestrings with structured grids.
Parameters
----------
shp : shapely.geometry.Linestring or MultiLineString
linestring to intersect with grid
keepzerolengths : bool, optional
if True keep intersection results with length=0, in
other words, grid cells the linestring does not cross
but does touch, by default False
Returns
-------
numpy.recarray
a record array containing information about the intersection
"""
# get local extent of grid
if (
self.mfgrid.angrot != 0.0
or self.mfgrid.xoffset != 0.0
or self.mfgrid.yoffset != 0.0
):
xmin = np.min(self.mfgrid.xyedges[0])
xmax = np.max(self.mfgrid.xyedges[0])
ymin = np.min(self.mfgrid.xyedges[1])
ymax = np.max(self.mfgrid.xyedges[1])
else:
xmin, xmax, ymin, ymax = self.mfgrid.extent
pl = box(xmin, ymin, xmax, ymax)
# rotate and translate linestring to local coords
if self.mfgrid.xoffset != 0.0 or self.mfgrid.yoffset != 0.0:
shp = translate(
shp, xoff=-self.mfgrid.xoffset, yoff=-self.mfgrid.yoffset
)
if self.mfgrid.angrot != 0.0:
shp = rotate(shp, -self.mfgrid.angrot, origin=(0.0, 0.0))
# clip line to mfgrid bbox
lineclip = shp.intersection(pl)
if lineclip.length == 0.0: # linestring does not intersect modelgrid
return np.recarray(
0,
names=["cellids", "vertices", "lengths", "ixshapes"],
formats=["O", "O", "f8", "O"],
)
if lineclip.geom_type == "MultiLineString": # there are multiple lines
nodelist, lengths, vertices = [], [], []
ixshapes = []
for ls in lineclip.geoms:
n, l, v, ixs = self._get_nodes_intersecting_linestring(ls)
nodelist += n
lengths += l
# if necessary, transform coordinates back to real
# world coordinates
if (
self.mfgrid.angrot != 0.0
or self.mfgrid.xoffset != 0.0
or self.mfgrid.yoffset != 0.0
):
v_realworld = []
for pt in v:
pt = np.array(pt)
rx, ry = transform(
pt[:, 0],
pt[:, 1],
self.mfgrid.xoffset,
self.mfgrid.yoffset,
self.mfgrid.angrot_radians,
inverse=False,
)
v_realworld.append(list(zip(rx, ry)))
ixs_realworld = []
for ix in ixs:
ix_realworld = rotate(
ix, self.mfgrid.angrot, origin=(0.0, 0.0)
)
ix_realworld = translate(
ix_realworld,
self.mfgrid.xoffset,
self.mfgrid.yoffset,
)
ixs_realworld.append(ix_realworld)
else:
v_realworld = v
ixs_realworld = ixs
vertices += v_realworld
ixshapes += ixs_realworld
else: # linestring is fully within grid
(
nodelist,
lengths,
vertices,
ixshapes,
) = self._get_nodes_intersecting_linestring(lineclip)
# if necessary, transform coordinates back to real
# world coordinates
if (
self.mfgrid.angrot != 0.0
or self.mfgrid.xoffset != 0.0
or self.mfgrid.yoffset != 0.0
):
v_realworld = []
for pt in vertices:
pt = np.array(pt)
rx, ry = transform(
pt[:, 0],
pt[:, 1],
self.mfgrid.xoffset,
self.mfgrid.yoffset,
self.mfgrid.angrot_radians,
inverse=False,
)
v_realworld.append(list(zip(rx, ry)))
vertices = v_realworld
ix_shapes_realworld = []
for ixs in ixshapes:
ixs = rotate(ixs, self.mfgrid.angrot, origin=(0.0, 0.0))
ixs = translate(
ixs, self.mfgrid.xoffset, self.mfgrid.yoffset
)
ix_shapes_realworld.append(ixs)
ixshapes = ix_shapes_realworld
# bundle linestrings in same cell
tempnodes = []
templengths = []
tempverts = []
tempshapes = []
unique_nodes = list(set(nodelist))
if len(unique_nodes) < len(nodelist):
for inode in unique_nodes:
templengths.append(
sum([l for l, i in zip(lengths, nodelist) if i == inode])
)
tempverts.append(
[v for v, i in zip(vertices, nodelist) if i == inode]
)
tempshapes.append(
[ix for ix, i in zip(ixshapes, nodelist) if i == inode]
)
nodelist = unique_nodes
lengths = templengths
vertices = tempverts
ixshapes = tempshapes
# eliminate any nodes that have a zero length
if not keepzerolengths:
tempnodes = []
templengths = []
tempverts = []
tempshapes = []
for i, _ in enumerate(nodelist):
if lengths[i] > 0:
tempnodes.append(nodelist[i])
templengths.append(lengths[i])
tempverts.append(vertices[i])
tempshapes.append(ixshapes[i])
nodelist = tempnodes
lengths = templengths
vertices = tempverts
ixshapes = tempshapes
rec = np.recarray(
len(nodelist),
names=["cellids", "vertices", "lengths", "ixshapes"],
formats=["O", "O", "f8", "O"],
)
rec.vertices = vertices
rec.lengths = lengths
rec.cellids = nodelist
with ignore_shapely_warnings_for_object_array():
rec.ixshapes = ixshapes
return rec
def _get_nodes_intersecting_linestring(self, linestring):
"""helper function, intersect the linestring with the a structured grid
and return a list of node indices and the length of the line in that
node.
Parameters
----------
linestring: shapely.geometry.LineString or MultiLineString
shape to intersect with the grid
Returns
-------
nodelist, lengths, vertices: lists
lists containing node ids, lengths of intersects and the
start and end points of the intersects
"""
nodelist = []
lengths = []
vertices = []
ixshapes = []
# start at the beginning of the line
x, y = linestring.xy
# linestring already in local coords but
# because intersect_point does transform again
# we transform back to real world here if necessary
if (
self.mfgrid.angrot != 0.0
or self.mfgrid.xoffset != 0.0
or self.mfgrid.yoffset != 0.0
):
x0, y0 = transform(
[x[0]],
[y[0]],
self.mfgrid.xoffset,
self.mfgrid.yoffset,
self.mfgrid.angrot_radians,
inverse=False,
)
else:
x0 = [x[0]]
y0 = [y[0]]
(i, j) = self.intersect(Point(x0[0], y0[0])).cellids[0]
Xe, Ye = self.mfgrid.xyedges
xmin = Xe[j]
xmax = Xe[j + 1]
ymax = Ye[i]
ymin = Ye[i + 1]
pl = box(xmin, ymin, xmax, ymax)
intersect = linestring.intersection(pl)
# if linestring starts in cell, exits, and re-enters
# a MultiLineString is returned.
ixshapes.append(intersect)
length = intersect.length
lengths.append(length)
if hasattr(intersect, "geoms"):
x, y = [], []
for igeom in intersect.geoms:
x.append(igeom.xy[0])
y.append(igeom.xy[1])
x = np.concatenate(x)
y = np.concatenate(y)
else:
x = intersect.xy[0]
y = intersect.xy[1]