ssb-sgis 1.1.17__py3-none-any.whl → 1.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,7 +6,6 @@ from collections.abc import Hashable
6
6
  from collections.abc import Iterable
7
7
  from typing import Any
8
8
 
9
- import joblib
10
9
  import numpy as np
11
10
  import pandas as pd
12
11
  import pyproj
@@ -22,8 +21,6 @@ from shapely import get_coordinates
22
21
  from shapely import get_parts
23
22
  from shapely import linestrings
24
23
  from shapely import make_valid
25
- from shapely import points as shapely_points
26
- from shapely import union_all
27
24
  from shapely.geometry import LineString
28
25
  from shapely.geometry import MultiPoint
29
26
  from shapely.geometry import Point
@@ -36,6 +33,7 @@ from .geometry_types import get_geom_type
36
33
  from .geometry_types import make_all_singlepart
37
34
  from .geometry_types import to_single_geom_type
38
35
  from .neighbors import get_k_nearest_neighbors
36
+ from .sfilter import sfilter
39
37
  from .sfilter import sfilter_split
40
38
 
41
39
 
@@ -333,7 +331,7 @@ def sort_large_first(gdf: GeoDataFrame | GeoSeries) -> GeoDataFrame | GeoSeries:
333
331
  # using enumerate, then iloc on the sorted dict keys.
334
332
  # to avoid creating a temporary area column (which doesn't work for GeoSeries).
335
333
  area_mapper = dict(enumerate(gdf.area.values))
336
- sorted_areas = dict(reversed(sorted(area_mapper.items(), key=lambda item: item[1])))
334
+ sorted_areas = dict(reversed(sorted(area_mapper.items(), key=_get_dict_value)))
337
335
  return gdf.iloc[list(sorted_areas)]
338
336
 
339
337
 
@@ -349,9 +347,7 @@ def sort_long_first(gdf: GeoDataFrame | GeoSeries) -> GeoDataFrame | GeoSeries:
349
347
  # using enumerate, then iloc on the sorted dict keys.
350
348
  # to avoid creating a temporary area column (which doesn't work for GeoSeries).
351
349
  length_mapper = dict(enumerate(gdf.length.values))
352
- sorted_lengths = dict(
353
- reversed(sorted(length_mapper.items(), key=lambda item: item[1]))
354
- )
350
+ sorted_lengths = dict(reversed(sorted(length_mapper.items(), key=_get_dict_value)))
355
351
  return gdf.iloc[list(sorted_lengths)]
356
352
 
357
353
 
@@ -367,7 +363,7 @@ def sort_short_first(gdf: GeoDataFrame | GeoSeries) -> GeoDataFrame | GeoSeries:
367
363
  # using enumerate, then iloc on the sorted dict keys.
368
364
  # to avoid creating a temporary area column (which doesn't work for GeoSeries).
369
365
  length_mapper = dict(enumerate(gdf.length.values))
370
- sorted_lengths = dict(sorted(length_mapper.items(), key=lambda item: item[1]))
366
+ sorted_lengths = dict(sorted(length_mapper.items(), key=_get_dict_value))
371
367
  return gdf.iloc[list(sorted_lengths)]
372
368
 
373
369
 
@@ -384,10 +380,14 @@ def sort_small_first(gdf: GeoDataFrame | GeoSeries) -> GeoDataFrame | GeoSeries:
384
380
  # using enumerate, then iloc on the sorted dict keys.
385
381
  # to avoid creating a temporary area column (which doesn't work for GeoSeries).
386
382
  area_mapper = dict(enumerate(gdf.area.values))
387
- sorted_areas = dict(sorted(area_mapper.items(), key=lambda item: item[1]))
383
+ sorted_areas = dict(sorted(area_mapper.items(), key=_get_dict_value))
388
384
  return gdf.iloc[list(sorted_areas)]
389
385
 
390
386
 
387
+ def _get_dict_value(item: tuple[Hashable, Any]) -> Any:
388
+ return item[1]
389
+
390
+
391
391
  def make_lines_between_points(
392
392
  *arrs: NDArray[Point] | GeometryArray | GeoSeries,
393
393
  ) -> NDArray[LineString]:
@@ -416,7 +416,7 @@ def random_points(n: int, loc: float | int = 0.5) -> GeoDataFrame:
416
416
  """Creates a GeoDataFrame with n random points.
417
417
 
418
418
  Args:
419
- n: Number of points/rows to create.
419
+ n: Number of points to create.
420
420
  loc: Mean ('centre') of the distribution.
421
421
 
422
422
  Returns:
@@ -459,47 +459,78 @@ def random_points(n: int, loc: float | int = 0.5) -> GeoDataFrame:
459
459
  9999 POINT (134.503 168.155)
460
460
  [10000 rows x 1 columns]
461
461
  """
462
- if isinstance(n, (str, float)):
463
- n = int(n)
464
-
465
462
  x = np.random.rand(n) * float(loc) * 2
466
463
  y = np.random.rand(n) * float(loc) * 2
464
+ return GeoDataFrame(shapely.points(x, y=y), columns=["geometry"])
467
465
 
468
- return GeoDataFrame(
469
- (Point(x, y) for x, y in zip(x, y, strict=True)), columns=["geometry"]
470
- )
471
466
 
467
+ def random_points_norway(size: int, *, seed: int | None = None) -> GeoDataFrame:
468
+ """Creates a GeoDataFrame with crs=25833 n random points aprox. within the borders of mainland Norway.
469
+
470
+ Args:
471
+ size: Number of points to create.
472
+ seed: Optional random seed.
472
473
 
473
- def random_points_in_polygons(gdf: GeoDataFrame, n: int, seed=None) -> GeoDataFrame:
474
+ Returns:
475
+ A GeoDataFrame of points with n rows.
476
+ """
477
+ return random_points_in_polygons(
478
+ [
479
+ shapely.wkt.loads(x)
480
+ for x in [
481
+ "POLYGON ((546192 7586393, 546191 7586393, 526598 7592425, 526597 7592425, 526596 7592425, 526595 7592426, 526594 7592426, 525831 7593004, 525830 7593005, 525327 7593495, 525326 7593496, 525326 7593497, 525325 7593498, 525325 7593499, 525324 7593500, 525192 7594183, 525192 7594184, 524157 7606517, 524157 7606518, 524157 7606519, 524157 7606520, 524157 7606521, 526235 7613535, 526236 7613536, 559423 7676952, 559424 7676953, 559511 7677088, 579978 7708379, 636963 7792940, 636963 7792941, 636964 7792942, 636965 7792943, 641013 7795664, 823514 7912323, 823515 7912323, 823516 7912323, 882519 7931958, 882520 7931959, 882521 7931959, 953896 7939985, 953897 7939985, 973544 7939988, 973545 7939988, 973546 7939988, 975510 7939467, 1051029 7913762, 1051030 7913762, 1055067 7912225, 1055068 7912224, 1056725 7911491, 1098379 7890321, 1098380 7890320, 1098381 7890320, 1099197 7889670, 1099198 7889669, 1099442 7889429, 1099443 7889429, 1099444 7889428, 1099444 7889427, 1099445 7889426, 1099445 7889425, 1099445 7889424, 1099446 7889423, 1114954 7799458, 1115106 7797736, 1115106 7797735, 1115106 7797734, 1115106 7797733, 1115106 7797732, 1115105 7797731, 1115105 7797730, 1114774 7797199, 1112876 7794451, 1057595 7720320, 1057112 7719702, 1057112 7719701, 1057111 7719701, 1057110 7719700, 1057109 7719699, 902599 7637176, 902598 7637176, 902597 7637175, 902596 7637175, 702394 7590633, 702393 7590633, 702392 7590633, 546193 7586393, 546192 7586393))",
482
+ "POLYGON ((60672 6448410, 60671 6448411, 57185 6448783, 39229 6451077, 39228 6451077, 39227 6451077, 27839 6454916, 27838 6454916, 27808 6454929, 27807 6454929, 8939 6465625, 8938 6465626, 7449 6466699, 7448 6466700, 6876 6467215, 6876 6467216, -31966 6512038, -31968 6512040, -32554 6512779, -32554 6512780, -40259 6524877, -42041 6527698, -42217 6528008, -42546 6528677, -42547 6528678, -77251 6614452, -77252 6614453, -77252 6614454, -77252 6614455, -77252 6614456, -77206 6615751, -77206 6615752, -65669 6811422, -65669 6811423, -65608 6812139, -65608 6812140, -65608 6812141, -50907 6879624, -50907 6879625, -50907 6879626, -50906 6879627, -50889 6879658, -50889 6879659, -16217 6934790, -16217 6934791, -16216 6934792, -2958 6949589, -2957 6949590, 55128 6995098, 144915 7064393, 144915 7064394, 144916 7064395, 144958 7064418, 144959 7064418, 144960 7064418, 144961 7064419, 144962 7064419, 144963 7064419, 150493 7064408, 150494 7064408, 150495 7064408, 150770 7064370, 150771 7064370, 150772 7064370, 188559 7048106, 188560 7048105, 188664 7048054, 188665 7048054, 188666 7048053, 357806 6914084, 357807 6914083, 357808 6914082, 357809 6914081, 357809 6914080, 357810 6914079, 357810 6914078, 359829 6906908, 386160 6804356, 386160 6804355, 386160 6804354, 386160 6804353, 386160 6804352, 386160 6804351, 368140 6699014, 368140 6699013, 363725 6675483, 363725 6675482, 361041 6665071, 361040 6665070, 361040 6665069, 308721 6537573, 308720 6537572, 307187 6534433, 307187 6534432, 307186 6534431, 307185 6534430, 307184 6534429, 307183 6534429, 307182 6534428, 303562 6532881, 300420 6531558, 99437 6459510, 99436 6459510, 67654 6449332, 65417 6448682, 65416 6448682, 65415 6448682, 60673 6448410, 60672 6448410))",
483
+ "POLYGON ((219870 6914350, 219869 6914350, 219868 6914351, 219867 6914351, 194827 6928565, 194826 6928566, 193100 6929790, 193099 6929790, 193098 6929791, 193098 6929792, 193097 6929793, 157353 7006877, 157353 7006878, 154402 7017846, 154402 7017847, 154392 7017923, 154392 7017924, 154392 7017925, 154392 7017926, 166616 7077346, 166617 7077347, 169164 7087256, 169165 7087257, 170277 7089848, 173146 7096147, 173147 7096148, 174684 7098179, 174685 7098180, 314514 7253805, 314515 7253805, 314515 7253806, 314516 7253806, 314517 7253807, 314518 7253807, 314519 7253808, 314520 7253808, 314521 7253808, 314522 7253808, 314523 7253808, 314524 7253808, 332374.8847495829 7250200.016409928, 327615 7280207, 327615 7280208, 327615 7280209, 327615 7280210, 328471 7285637, 364549 7480637, 364549 7480638, 367030 7488919, 367030 7488920, 367045 7488948, 367045 7488949, 367046 7488950, 419493 7560257, 472291 7626092, 506326 7665544, 506327 7665545, 506328 7665546, 541847 7692387, 541848 7692388, 541849 7692388, 541850 7692389, 541851 7692389, 541852 7692389, 545852 7692619, 546265 7692617, 546266 7692617, 546267 7692617, 546268 7692617, 546269 7692616, 546270 7692616, 546270 7692615, 546271 7692615, 546272 7692614, 623027 7613734, 623028 7613733, 623029 7613732, 627609 7605928, 627610 7605928, 627610 7605927, 627610 7605926, 627611 7605925, 627611 7605924, 630573 7568363, 630573 7568362, 630573 7568361, 630573 7568360, 630573 7568359, 628567 7562381, 621356 7542293, 621356 7542292, 468368 7221876.188770507, 468368 7221876, 459071 7119021, 459071 7119020, 459071 7119019, 459070 7119018, 459070 7119017, 454728 7109371, 451784 7102984, 449525 7098307, 357809 6914071, 357808 6914070, 357808 6914069, 357807 6914068, 357806 6914068, 357806 6914067, 357805 6914067, 357804 6914066, 353158 6912240, 353157 6912239, 353156 6912239, 351669 6911974, 351668 6911974, 351667 6911974, 219871 6914350, 219870 6914350))",
484
+ ]
485
+ ],
486
+ size=size,
487
+ crs=25833,
488
+ seed=seed,
489
+ ).sample(size)
490
+
491
+
492
+ def random_points_in_polygons(
493
+ polygons: Geometry | GeoDataFrame | GeoSeries,
494
+ size: int,
495
+ *,
496
+ seed: int | None = None,
497
+ crs: Any = 25833,
498
+ ) -> GeoDataFrame:
474
499
  """Creates a GeoDataFrame with n random points within the geometries of 'gdf'.
475
500
 
476
501
  Args:
477
- gdf: A GeoDataFrame.
478
- n: Number of points/rows to create.
479
- seed: Optional random seet.
502
+ polygons: A GeoDataFrame or GeoSeries of polygons. Or a single polygon.
503
+ size: Number of points to create.
504
+ seed: Optional random seed.
505
+ crs: Optional crs of the output GeoDataFrame if input is shapely.Geometry.
480
506
 
481
507
  Returns:
482
508
  A GeoDataFrame of points with n rows.
483
509
  """
484
- all_points = []
485
-
510
+ if crs is None:
511
+ try:
512
+ crs = polygons.crs
513
+ except AttributeError:
514
+ pass
486
515
  rng = np.random.default_rng(seed)
487
-
488
- for i, geom in enumerate(gdf.geometry):
489
- minx, miny, maxx, maxy = geom.bounds
490
-
491
- xs = rng.uniform(minx, maxx, size=n * 500)
492
- ys = rng.uniform(miny, maxy, size=n * 500)
493
-
494
- points = GeoSeries(shapely_points(xs, y=ys), index=[i] * len(xs))
495
- all_points.append(points)
496
-
497
- return (
498
- pd.concat(all_points)
499
- .loc[lambda x: x.intersects(gdf.geometry)]
500
- .groupby(level=0)
501
- .head(n)
502
- )
516
+ polygons = to_gdf(polygons, crs=crs).geometry
517
+ bounds = polygons.bounds
518
+ minx = np.repeat(bounds["minx"].values, size)
519
+ maxx = np.repeat(bounds["maxx"].values, size)
520
+ miny = np.repeat(bounds["miny"].values, size)
521
+ maxy = np.repeat(bounds["maxy"].values, size)
522
+ index = np.repeat(np.arange(len(polygons)), size)
523
+ length = len(index)
524
+ out = []
525
+ while sum(len(df) for df in out) < size * len(polygons):
526
+ xs = rng.uniform(low=minx, high=maxx, size=length)
527
+ ys = rng.uniform(low=miny, high=maxy, size=length)
528
+ out.append(
529
+ GeoDataFrame(
530
+ shapely.points(xs, y=ys), index=index, columns=["geometry"], crs=crs
531
+ ).pipe(sfilter, polygons)
532
+ )
533
+ return pd.concat(out).groupby(level=0).sample(size, replace=True).sort_index()
503
534
 
504
535
 
505
536
  def polygons_to_lines(
@@ -1121,79 +1152,3 @@ def _determine_geom_type_args(
1121
1152
  if geom_type == "mixed":
1122
1153
  raise ValueError("Cannot set keep_geom_type=True with mixed geometries")
1123
1154
  return gdf, geom_type, keep_geom_type
1124
-
1125
-
1126
- def _unary_union_for_notna(geoms, **kwargs):
1127
- try:
1128
- return make_valid(union_all(geoms, **kwargs))
1129
- except TypeError:
1130
- return union_all([geom for geom in geoms.dropna().values], **kwargs)
1131
-
1132
-
1133
- def _grouped_unary_union(
1134
- df: GeoDataFrame | GeoSeries | pd.DataFrame | pd.Series,
1135
- by: str | list[str] | None = None,
1136
- level: int | None = None,
1137
- as_index: bool = True,
1138
- grid_size: float | int | None = None,
1139
- dropna: bool = False,
1140
- **kwargs,
1141
- ) -> GeoSeries | GeoDataFrame:
1142
- """Vectorized unary_union for groups.
1143
-
1144
- Experimental. Messy code.
1145
- """
1146
- try:
1147
- geom_col = df._geometry_column_name
1148
- except AttributeError:
1149
- try:
1150
- geom_col = df.name
1151
- if geom_col is None:
1152
- geom_col = "geometry"
1153
- except AttributeError:
1154
- geom_col = "geometry"
1155
-
1156
- if isinstance(df, pd.Series):
1157
- return GeoSeries(
1158
- df.groupby(level=level, as_index=as_index, **kwargs).agg(
1159
- lambda x: _unary_union_for_notna(x, grid_size=grid_size)
1160
- )
1161
- )
1162
-
1163
- return GeoSeries(
1164
- df.groupby(by, level=level, as_index=as_index, **kwargs)[geom_col].agg(
1165
- lambda x: _unary_union_for_notna(x, grid_size=grid_size)
1166
- )
1167
- )
1168
-
1169
-
1170
- def _parallel_unary_union(
1171
- gdf: GeoDataFrame, n_jobs: int = 1, by=None, grid_size=None, **kwargs
1172
- ) -> list[Geometry]:
1173
- try:
1174
- geom_col = gdf._geometry_column_name
1175
- except AttributeError:
1176
- geom_col = "geometry"
1177
-
1178
- with joblib.Parallel(n_jobs=n_jobs, backend="threading") as parallel:
1179
- delayed_operations = []
1180
- for _, geoms in gdf.groupby(by, **kwargs)[geom_col]:
1181
- delayed_operations.append(
1182
- joblib.delayed(_unary_union_for_notna)(geoms, grid_size=grid_size)
1183
- )
1184
-
1185
- return parallel(delayed_operations)
1186
-
1187
-
1188
- def _parallel_unary_union_geoseries(
1189
- ser: GeoSeries, n_jobs: int = 1, grid_size=None, **kwargs
1190
- ) -> list[Geometry]:
1191
-
1192
- with joblib.Parallel(n_jobs=n_jobs, backend="threading") as parallel:
1193
- delayed_operations = []
1194
- for _, geoms in ser.groupby(**kwargs):
1195
- delayed_operations.append(
1196
- joblib.delayed(_unary_union_for_notna)(geoms, grid_size=grid_size)
1197
- )
1198
-
1199
- return parallel(delayed_operations)
@@ -17,8 +17,11 @@ from pandas import MultiIndex
17
17
  from pandas import Series
18
18
  from sklearn.neighbors import NearestNeighbors
19
19
 
20
+ from ..conf import _get_instance
21
+ from ..conf import config
20
22
  from .conversion import coordinate_array
21
23
  from .geometry_types import get_geom_type
24
+ from .runners import RTreeQueryRunner
22
25
 
23
26
 
24
27
  def get_neighbor_indices(
@@ -26,6 +29,8 @@ def get_neighbor_indices(
26
29
  neighbors: GeoDataFrame | GeoSeries,
27
30
  max_distance: int = 0,
28
31
  predicate: str = "intersects",
32
+ rtree_runner: RTreeQueryRunner | None = None,
33
+ n_jobs: int | None = None,
29
34
  ) -> Series:
30
35
  """Creates a pandas Series with the index of 'gdf' and values of 'neighbors'.
31
36
 
@@ -41,6 +46,9 @@ def get_neighbor_indices(
41
46
  predicate: Spatial predicate to use in sjoin. Defaults to "intersects", meaning
42
47
  the geometry itself and geometries within will be considered neighbors if
43
48
  they are part of the 'neighbors' GeoDataFrame.
49
+ rtree_runner: Optionally debug/manipulate the spatial indexing operations.
50
+ See the 'runners' module for example implementations.
51
+ n_jobs: Number of workers.
44
52
 
45
53
  Returns:
46
54
  A pandas Series with values of the intersecting 'neighbors' indices.
@@ -103,6 +111,9 @@ def get_neighbor_indices(
103
111
  if gdf.crs != neighbors.crs:
104
112
  raise ValueError(f"'crs' mismatch. Got {gdf.crs} and {neighbors.crs}")
105
113
 
114
+ if rtree_runner is None:
115
+ rtree_runner = _get_instance(config, "rtree_runner", n_jobs=n_jobs)
116
+
106
117
  if isinstance(neighbors, GeoSeries):
107
118
  neighbors = neighbors.to_frame()
108
119
  else:
@@ -119,11 +130,21 @@ def get_neighbor_indices(
119
130
 
120
131
  if predicate == "nearest":
121
132
  max_distance = None if max_distance == 0 else max_distance
122
- joined = gdf.sjoin_nearest(neighbors, how="inner", max_distance=max_distance)
133
+ left, right = rtree_runner.run(
134
+ gdf.geometry.values,
135
+ neighbors.geometry.values,
136
+ method="query_nearest",
137
+ max_distance=max_distance,
138
+ )
123
139
  else:
124
- joined = gdf.sjoin(neighbors, how="inner", predicate=predicate)
125
-
126
- return joined.rename(columns={"index_right": "neighbor_index"})["neighbor_index"]
140
+ left, right = rtree_runner.run(
141
+ gdf.geometry.values, neighbors.geometry.values, predicate=predicate
142
+ )
143
+ index_mapper1 = {i: x for i, x in enumerate(gdf.index)}
144
+ left = np.array([index_mapper1[i] for i in left])
145
+ index_mapper2 = {i: x for i, x in enumerate(neighbors.index)}
146
+ right = np.array([index_mapper2[i] for i in right])
147
+ return Series(right, index=left, name="neighbor_index")
127
148
 
128
149
 
129
150
  def get_neighbor_dfs(