pysnapping 0.1.2__tar.gz → 0.2.0__tar.gz

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.
Files changed (35) hide show
  1. {pysnapping-0.1.2 → pysnapping-0.2.0}/.pre-commit-config.yaml +8 -23
  2. {pysnapping-0.1.2 → pysnapping-0.2.0}/PKG-INFO +36 -19
  3. {pysnapping-0.1.2 → pysnapping-0.2.0}/README.md +30 -16
  4. {pysnapping-0.1.2 → pysnapping-0.2.0}/dev-requirements.in +1 -0
  5. {pysnapping-0.1.2 → pysnapping-0.2.0}/dev-requirements.txt +25 -21
  6. {pysnapping-0.1.2 → pysnapping-0.2.0}/pyproject.toml +43 -3
  7. {pysnapping-0.1.2 → pysnapping-0.2.0}/pysnapping/__init__.py +1 -6
  8. {pysnapping-0.1.2 → pysnapping-0.2.0}/pysnapping/linear_referencing.py +191 -1
  9. pysnapping-0.2.0/pysnapping/snap.py +875 -0
  10. {pysnapping-0.1.2 → pysnapping-0.2.0}/pysnapping/test/test_linear_referencing.py +114 -6
  11. {pysnapping-0.1.2 → pysnapping-0.2.0}/pysnapping/test/test_snap.py +143 -158
  12. pysnapping-0.2.0/pysnapping/test/test_util.py +20 -0
  13. {pysnapping-0.1.2 → pysnapping-0.2.0}/pysnapping/util.py +8 -14
  14. {pysnapping-0.1.2 → pysnapping-0.2.0}/pysnapping.egg-info/PKG-INFO +36 -19
  15. {pysnapping-0.1.2 → pysnapping-0.2.0}/pysnapping.egg-info/SOURCES.txt +0 -3
  16. {pysnapping-0.1.2 → pysnapping-0.2.0}/pysnapping.egg-info/requires.txt +0 -1
  17. pysnapping-0.2.0/requirements.txt +16 -0
  18. pysnapping-0.2.0/setup.cfg +4 -0
  19. pysnapping-0.1.2/pysnapping/ordering.py +0 -192
  20. pysnapping-0.1.2/pysnapping/snap.py +0 -1451
  21. pysnapping-0.1.2/pysnapping/test/test_ordering.py +0 -95
  22. pysnapping-0.1.2/pysnapping/test/test_util.py +0 -21
  23. pysnapping-0.1.2/requirements.txt +0 -42
  24. pysnapping-0.1.2/setup.cfg +0 -25
  25. {pysnapping-0.1.2 → pysnapping-0.2.0}/.editorconfig +0 -0
  26. {pysnapping-0.1.2 → pysnapping-0.2.0}/.gitignore +0 -0
  27. {pysnapping-0.1.2 → pysnapping-0.2.0}/.gitlab-ci.yml +0 -0
  28. {pysnapping-0.1.2 → pysnapping-0.2.0}/LICENSE +0 -0
  29. {pysnapping-0.1.2 → pysnapping-0.2.0}/MANIFEST.in +0 -0
  30. {pysnapping-0.1.2 → pysnapping-0.2.0}/pysnapping/py.typed +0 -0
  31. {pysnapping-0.1.2 → pysnapping-0.2.0}/pysnapping/test/__init__.py +0 -0
  32. {pysnapping-0.1.2 → pysnapping-0.2.0}/pysnapping/test/complex_trip.geojson +0 -0
  33. {pysnapping-0.1.2 → pysnapping-0.2.0}/pysnapping/test/conftest.py +0 -0
  34. {pysnapping-0.1.2 → pysnapping-0.2.0}/pysnapping.egg-info/dependency_links.txt +0 -0
  35. {pysnapping-0.1.2 → pysnapping-0.2.0}/pysnapping.egg-info/top_level.txt +0 -0
@@ -1,7 +1,7 @@
1
1
  fail_fast: false
2
2
  repos:
3
3
  - repo: https://github.com/pre-commit/pre-commit-hooks
4
- rev: v4.4.0
4
+ rev: v4.5.0
5
5
  hooks:
6
6
  - id: no-commit-to-branch
7
7
  - id: check-merge-conflict
@@ -12,28 +12,12 @@ repos:
12
12
  - id: check-builtin-literals
13
13
  - id: check-case-conflict
14
14
  - id: check-docstring-first
15
- - repo: https://github.com/pycqa/flake8
16
- rev: 6.1.0
15
+ - repo: https://github.com/astral-sh/ruff-pre-commit
16
+ rev: v0.1.14
17
17
  hooks:
18
- - id: flake8
19
- name: flake8
20
- entry: flake8
21
- language: python
22
- files: '.*\.py$'
23
- pass_filenames: false
24
- - repo: https://github.com/psf/black
25
- rev: 23.7.0
26
- hooks:
27
- - id: black
28
- name: black
29
- entry: black
30
- language: python
31
- files: '.*\.py$'
32
- - repo: https://github.com/asottile/pyupgrade
33
- rev: v3.10.1
34
- hooks:
35
- - id: pyupgrade
36
- args: [--py39-plus]
18
+ - id: ruff
19
+ args: [ --fix ]
20
+ - id: ruff-format
37
21
  - repo: local
38
22
  hooks:
39
23
  - id: mypy
@@ -41,7 +25,8 @@ repos:
41
25
  entry: mypy
42
26
  language: python
43
27
  pass_filenames: false
44
- files: '.*\.py$'
28
+ always_run: true
29
+ args: ["-p", "pysnapping"]
45
30
  - id: pip-compile
46
31
  name: pip-compile
47
32
  entry: pip-compile pyproject.toml
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pysnapping
3
- Version: 0.1.2
4
- Summary: Snap points to a line string keeping a given order intact
3
+ Version: 0.2.0
4
+ Summary: Snap points to a line string keeping a given order or spacing intact
5
5
  Author-email: Alexander Held | geOps <alexander.held@geops.com>
6
6
  Maintainer-email: Alexander Held | geOps <alexander.held@geops.com>
7
7
  License: MIT License
@@ -28,7 +28,7 @@ License: MIT License
28
28
 
29
29
  Project-URL: homepage, https://github.com/geops/pysnapping
30
30
  Project-URL: geOps, https://geops.com/en
31
- Keywords: snapping,projecting,linear referencing,order,linestring,GIS,quadratic programming,GTFS
31
+ Keywords: snapping,projecting,linear referencing,order,linestring,GIS,GTFS,kilometrage,DAG,shortest path
32
32
  Classifier: Development Status :: 4 - Beta
33
33
  Classifier: Programming Language :: Python :: 3
34
34
  Classifier: Intended Audience :: Developers
@@ -39,6 +39,9 @@ Classifier: Typing :: Typed
39
39
  Requires-Python: >=3.9
40
40
  Description-Content-Type: text/markdown
41
41
  License-File: LICENSE
42
+ Requires-Dist: shapely
43
+ Requires-Dist: numpy
44
+ Requires-Dist: pyproj>=3.2.0
42
45
 
43
46
  # PySnapping
44
47
 
@@ -54,11 +57,11 @@ In order to be able to work with metric parameters and to treat data with large
54
57
  anywhere on the world, we use the [EPSG:4978](https://epsg.io/4978) Cartesian 3D geocentric coordinate system
55
58
  for the internal representation.
56
59
 
57
- The library aims to automatically classify kilometrage information as trusted or untrusted and fills missing
58
- data and corrects bogus data by interpolation/extrapolation if possible.
59
- Trusted points are always snapped as given by the kilometrage.
60
- In between trusted points, an approximate iterative scheme is used to snap all untrusted points such that
61
- the order or minimum spacing conditions are not violated.
60
+ The library aims to automatically classify kilometrage information as trusted or
61
+ untrusted. Trusted points are always snapped as given by the kilometrage. In between
62
+ trusted points, untrusted points are snapped by minimizing the sum of square snapping
63
+ distances among all admissible solutions within certain radii. Admissible solutions are
64
+ those that respect the order and minimum spacing between points.
62
65
 
63
66
  ## Installation
64
67
 
@@ -76,11 +79,6 @@ The `pysnapping.linear_referencing` module contains low-level classes and functi
76
79
  linear features in N-dimensions built on top of `numpy`. This contains interpolation/extrapolation along a line string
77
80
  and data structures optimized for projecting points to substrings of a line string.
78
81
 
79
- ### Ordering
80
-
81
- The `pysnapping.ordering` module contains functions to check and fix the order of a sequence of floats,
82
- respecting certain boundary conditions and spacings using the method of quadratic programming with the `cvxpy` library.
83
-
84
82
  ### Utils
85
83
 
86
84
  The `pysnapping.util` module contains common helper functions used in other parts of the library.
@@ -94,14 +92,16 @@ provides the classes needed to use the library.
94
92
 
95
93
  The typical usage pattern is to create a `pysnapping.snap.DubiousTrajectory` instance which represents
96
94
  a vehicle trajectory with dubious kilometrage and a `pysnapping.snap.DubiousTrajectoryTrip` `dtrip` which represents
97
- a trip along such a trajectory with dubious kilometrage for the stops and dubious timing information.
95
+ a trip along such a trajectory with dubious kilometrage for the stops.
98
96
  Then `dtrip.to_trajectory_trip` can be used to get a `pysnapping.snap.TrajectorTrip` `trip` with well defined
99
97
  metric kilometrage. `trip.trajectory` then refers to a `pysnapping.snap.Trajectory` instance with well defined metric
100
- kilometrage. The conversion can be controlled with parameters given by a `pysnapping.snap.SnappingParams` instance.
98
+ kilometrage.
101
99
 
102
- The `trip.snap_trip_points` method can be used to snap the trip points onto the trajectory, resulting in
103
- a `pysnapping.snap.SnappedTripPoints` instance `snapped`. Then you can e.g. split the trajectory at the stops
104
- using the `snapped.get_inter_point_ls_coords_in_travel_direction` method.
100
+ The `trip.snap_trip_points` method can be used to snap the trip points onto the
101
+ trajectory, resulting in a `pysnapping.snap.SnappedTripPoints` instance `snapped`. Then
102
+ you can e.g. split the trajectory at the stops using the
103
+ `snapped.get_inter_point_ls_coords_in_travel_direction` method. Snapping can be
104
+ controlled with parameters given by a `pysnapping.snap.SnappingParams` instance.
105
105
 
106
106
  A more detailed usage example (e.g. how to process GTFS input) is planned but not available yet.
107
107
  Until then, please also check the docstrings and source code for additional usage hints/possibilities.
@@ -149,10 +149,27 @@ pre-commit autoupdate
149
149
 
150
150
  to update frozen revs.
151
151
 
152
- ### Run tests
152
+ ### Run Tests
153
153
 
154
154
  Run tests and analyze code coverage:
155
155
 
156
156
  ```bash
157
157
  pytest --cov=pysnapping --cov-report term --cov-fail-under=85 pysnapping
158
158
  ```
159
+
160
+ ## Changelog
161
+
162
+ ### v0.2.0
163
+
164
+ #### Breaking Changes
165
+
166
+ * Snapping for untrusted points is now done by an exact algorithm instead of the
167
+ iterative approximate solution. This implies breaking changes to the parameters in
168
+ `snap.SnappingParams` as well as to parts of the API of the classes in the `snap`
169
+ module. For example: Timing information to guide the initial conditions of the
170
+ iterative solution is not necessary and thus not supported any more.
171
+ * The `ordering` module has been removed since it is not needed any more.
172
+
173
+ #### Other Changes:
174
+
175
+ * The development toolchain now uses ruff where possible.
@@ -12,11 +12,11 @@ In order to be able to work with metric parameters and to treat data with large
12
12
  anywhere on the world, we use the [EPSG:4978](https://epsg.io/4978) Cartesian 3D geocentric coordinate system
13
13
  for the internal representation.
14
14
 
15
- The library aims to automatically classify kilometrage information as trusted or untrusted and fills missing
16
- data and corrects bogus data by interpolation/extrapolation if possible.
17
- Trusted points are always snapped as given by the kilometrage.
18
- In between trusted points, an approximate iterative scheme is used to snap all untrusted points such that
19
- the order or minimum spacing conditions are not violated.
15
+ The library aims to automatically classify kilometrage information as trusted or
16
+ untrusted. Trusted points are always snapped as given by the kilometrage. In between
17
+ trusted points, untrusted points are snapped by minimizing the sum of square snapping
18
+ distances among all admissible solutions within certain radii. Admissible solutions are
19
+ those that respect the order and minimum spacing between points.
20
20
 
21
21
  ## Installation
22
22
 
@@ -34,11 +34,6 @@ The `pysnapping.linear_referencing` module contains low-level classes and functi
34
34
  linear features in N-dimensions built on top of `numpy`. This contains interpolation/extrapolation along a line string
35
35
  and data structures optimized for projecting points to substrings of a line string.
36
36
 
37
- ### Ordering
38
-
39
- The `pysnapping.ordering` module contains functions to check and fix the order of a sequence of floats,
40
- respecting certain boundary conditions and spacings using the method of quadratic programming with the `cvxpy` library.
41
-
42
37
  ### Utils
43
38
 
44
39
  The `pysnapping.util` module contains common helper functions used in other parts of the library.
@@ -52,14 +47,16 @@ provides the classes needed to use the library.
52
47
 
53
48
  The typical usage pattern is to create a `pysnapping.snap.DubiousTrajectory` instance which represents
54
49
  a vehicle trajectory with dubious kilometrage and a `pysnapping.snap.DubiousTrajectoryTrip` `dtrip` which represents
55
- a trip along such a trajectory with dubious kilometrage for the stops and dubious timing information.
50
+ a trip along such a trajectory with dubious kilometrage for the stops.
56
51
  Then `dtrip.to_trajectory_trip` can be used to get a `pysnapping.snap.TrajectorTrip` `trip` with well defined
57
52
  metric kilometrage. `trip.trajectory` then refers to a `pysnapping.snap.Trajectory` instance with well defined metric
58
- kilometrage. The conversion can be controlled with parameters given by a `pysnapping.snap.SnappingParams` instance.
53
+ kilometrage.
59
54
 
60
- The `trip.snap_trip_points` method can be used to snap the trip points onto the trajectory, resulting in
61
- a `pysnapping.snap.SnappedTripPoints` instance `snapped`. Then you can e.g. split the trajectory at the stops
62
- using the `snapped.get_inter_point_ls_coords_in_travel_direction` method.
55
+ The `trip.snap_trip_points` method can be used to snap the trip points onto the
56
+ trajectory, resulting in a `pysnapping.snap.SnappedTripPoints` instance `snapped`. Then
57
+ you can e.g. split the trajectory at the stops using the
58
+ `snapped.get_inter_point_ls_coords_in_travel_direction` method. Snapping can be
59
+ controlled with parameters given by a `pysnapping.snap.SnappingParams` instance.
63
60
 
64
61
  A more detailed usage example (e.g. how to process GTFS input) is planned but not available yet.
65
62
  Until then, please also check the docstrings and source code for additional usage hints/possibilities.
@@ -107,10 +104,27 @@ pre-commit autoupdate
107
104
 
108
105
  to update frozen revs.
109
106
 
110
- ### Run tests
107
+ ### Run Tests
111
108
 
112
109
  Run tests and analyze code coverage:
113
110
 
114
111
  ```bash
115
112
  pytest --cov=pysnapping --cov-report term --cov-fail-under=85 pysnapping
116
113
  ```
114
+
115
+ ## Changelog
116
+
117
+ ### v0.2.0
118
+
119
+ #### Breaking Changes
120
+
121
+ * Snapping for untrusted points is now done by an exact algorithm instead of the
122
+ iterative approximate solution. This implies breaking changes to the parameters in
123
+ `snap.SnappingParams` as well as to parts of the API of the classes in the `snap`
124
+ module. For example: Timing information to guide the initial conditions of the
125
+ iterative solution is not necessary and thus not supported any more.
126
+ * The `ordering` module has been removed since it is not needed any more.
127
+
128
+ #### Other Changes:
129
+
130
+ * The development toolchain now uses ruff where possible.
@@ -4,3 +4,4 @@ pytest-cov
4
4
  pre-commit
5
5
  pip-tools
6
6
  mypy
7
+ numpy
@@ -4,47 +4,53 @@
4
4
  #
5
5
  # pip-compile dev-requirements.in
6
6
  #
7
- build==1.0.0
7
+ build==1.0.3
8
8
  # via pip-tools
9
9
  cfgv==3.4.0
10
10
  # via pre-commit
11
11
  click==8.1.7
12
12
  # via pip-tools
13
- coverage[toml]==7.3.0
14
- # via pytest-cov
15
- distlib==0.3.7
13
+ coverage[toml]==7.4.1
14
+ # via
15
+ # coverage
16
+ # pytest-cov
17
+ distlib==0.3.8
16
18
  # via virtualenv
17
- exceptiongroup==1.1.3
19
+ exceptiongroup==1.2.0
18
20
  # via pytest
19
- filelock==3.12.3
21
+ filelock==3.13.1
20
22
  # via virtualenv
21
- identify==2.5.27
23
+ identify==2.5.33
22
24
  # via pre-commit
23
- importlib-metadata==6.8.0
25
+ importlib-metadata==7.0.1
24
26
  # via build
25
27
  iniconfig==2.0.0
26
28
  # via pytest
27
- mypy==1.5.1
29
+ mypy==1.8.0
28
30
  # via -r dev-requirements.in
29
31
  mypy-extensions==1.0.0
30
32
  # via mypy
31
33
  nodeenv==1.8.0
32
34
  # via pre-commit
33
- packaging==23.1
35
+ numpy==1.26.3
36
+ # via
37
+ # -c requirements.txt
38
+ # -r dev-requirements.in
39
+ packaging==23.2
34
40
  # via
35
41
  # build
36
42
  # pytest
37
43
  pip-tools==7.3.0
38
44
  # via -r dev-requirements.in
39
- platformdirs==3.10.0
45
+ platformdirs==4.1.0
40
46
  # via virtualenv
41
- pluggy==1.3.0
47
+ pluggy==1.4.0
42
48
  # via pytest
43
- pre-commit==3.4.0
49
+ pre-commit==3.6.0
44
50
  # via -r dev-requirements.in
45
51
  pyproject-hooks==1.0.0
46
52
  # via build
47
- pytest==7.4.1
53
+ pytest==8.0.0
48
54
  # via
49
55
  # -r dev-requirements.in
50
56
  # pytest-cov
@@ -60,15 +66,13 @@ tomli==2.0.1
60
66
  # pip-tools
61
67
  # pyproject-hooks
62
68
  # pytest
63
- typing-extensions==4.7.1
64
- # via
65
- # filelock
66
- # mypy
67
- virtualenv==20.24.4
69
+ typing-extensions==4.9.0
70
+ # via mypy
71
+ virtualenv==20.25.0
68
72
  # via pre-commit
69
- wheel==0.41.2
73
+ wheel==0.42.0
70
74
  # via pip-tools
71
- zipp==3.16.2
75
+ zipp==3.17.0
72
76
  # via importlib-metadata
73
77
 
74
78
  # The following packages are considered to be unsafe in a requirements file:
@@ -1,12 +1,11 @@
1
1
  [project]
2
2
  name = "pysnapping"
3
- description = "Snap points to a line string keeping a given order intact"
3
+ description = "Snap points to a line string keeping a given order or spacing intact"
4
4
  readme = "README.md"
5
5
  dependencies = [
6
6
  "shapely",
7
7
  "numpy",
8
8
  "pyproj>=3.2.0", # for defining custom CRS
9
- "cvxpy",
10
9
  ]
11
10
  requires-python = ">=3.9"
12
11
  license = {file = "LICENSE"}
@@ -19,8 +18,10 @@ keywords = [
19
18
  "order",
20
19
  "linestring",
21
20
  "GIS",
22
- "quadratic programming",
23
21
  "GTFS",
22
+ "kilometrage",
23
+ "DAG",
24
+ "shortest path",
24
25
  ]
25
26
  classifiers = [
26
27
  "Development Status :: 4 - Beta",
@@ -45,3 +46,42 @@ build-backend = "setuptools.build_meta"
45
46
 
46
47
  [tool.setuptools.packages.find]
47
48
  include = ["pysnapping", "pysnapping.*"]
49
+
50
+ [tool.ruff]
51
+ select = [
52
+ "F", # pyflakes
53
+ "E", # pycodestyle
54
+ "W", # pycodestyle
55
+ "UP", # pyupgrade
56
+ "C901", # mccabe
57
+ "YTT", # no sys.version tuple comparisons
58
+ "ASYNC", # no obviously blocking io in corotine
59
+ "G", # flake8-logging-format
60
+ "PIE", # unnecessary statements
61
+ "SLOT", # str, tuple, namedtuple subclasses need __slots__
62
+ "FIX003", # line contains XXX
63
+ ]
64
+ ignore = [
65
+ "E501", # line too long
66
+ "UP038", # see https://github.com/astral-sh/ruff/issues/7871
67
+ ]
68
+
69
+ [tool.ruff.lint.mccabe]
70
+ max-complexity = 12
71
+
72
+ [tool.mypy]
73
+ ignore_missing_imports = true
74
+ plugins = [
75
+ "numpy.typing.mypy_plugin",
76
+ ]
77
+ install_types = true
78
+ non_interactive = true
79
+
80
+ [tool.coverage.run]
81
+ branch = true
82
+ source = [
83
+ "pysnapping"
84
+ ]
85
+ omit = [
86
+ "pysnapping/test/*",
87
+ ]
@@ -25,16 +25,11 @@ class SnappingError(ValueError):
25
25
  pass
26
26
 
27
27
 
28
- class NoSolution(ValueError):
29
- pass
30
-
31
-
32
28
  class ExtrapolationError(ValueError):
33
29
  pass
34
30
 
35
31
 
36
32
  class SnappingMethod(Enum):
37
33
  trusted = "trusted"
38
- projected = "projected"
39
- iterative = "iterative"
34
+ routed = "routed"
40
35
  fallback = "fallback"
@@ -1,6 +1,6 @@
1
1
  """Linear referencing for arbitrary dimensions.
2
2
 
3
- An alternative to the very limited shapely linear referencing tools.
3
+ An alternative to shapely linear referencing tools in N dimensions.
4
4
  Also suitable as an alternative to scipy.interp.interp1d when dealing with repeated x values.
5
5
 
6
6
  The vertex index axis is always expected at axis 0.
@@ -20,6 +20,14 @@ from numpy.core.umath import clip # type: ignore
20
20
  from . import ExtrapolationError
21
21
 
22
22
 
23
+ def get_square_dists(
24
+ a: np.ndarray, b: np.ndarray, cartesian_axis: int = -1
25
+ ) -> np.ndarray:
26
+ tmp = a - b
27
+ np.square(tmp, out=tmp)
28
+ return tmp.sum(cartesian_axis)
29
+
30
+
23
31
  class Locations:
24
32
  """Multiple locations along a linear feature.
25
33
 
@@ -458,6 +466,188 @@ class LineFractions:
458
466
  out,
459
467
  )
460
468
 
469
+ def select_balls(self, square_radii: np.ndarray) -> list["SlicedLineFractions"]:
470
+ """Select parts of the linestring intersecting a ball around each point."""
471
+
472
+ # we can safely ignore short segments except when all segments are short (the
473
+ # linestring is point-like)
474
+ n_short = len(self.target.short_segments)
475
+ if n_short and n_short == len(self.target.segment_starts):
476
+ ls_point = self.target.segment_starts[0, np.newaxis]
477
+ square_distances = get_square_dists(self.point_coords, ls_point)
478
+ mask = square_distances <= square_radii
479
+ return [
480
+ SlicedLineFractions(
481
+ self,
482
+ i,
483
+ # empty array if m is False
484
+ np.array(bool(m) * [0], dtype=int),
485
+ np.array(bool(m) * [0.0]),
486
+ np.array(bool(m) * [0.5]),
487
+ np.array(bool(m) * [1.0]),
488
+ )
489
+ for i, m in enumerate(mask)
490
+ ]
491
+
492
+ long_segments = np.nonzero(np.logical_not(self.target.short_segment_mask))[0]
493
+ sm2 = self.target.inv_norm_segment_dirs_squared[np.newaxis, long_segments]
494
+ a = self.fractions[:, long_segments]
495
+ q2 = get_square_dists(
496
+ self.target.segment_starts[np.newaxis, long_segments],
497
+ self.point_coords[:, np.newaxis],
498
+ )
499
+ d1 = sm2 * square_radii[:, np.newaxis]
500
+ d2 = sm2 * q2
501
+ d2 -= a**2
502
+ discriminant = d1 - d2
503
+
504
+ # checks where the ball intersects the line running through each segment for
505
+ # each point
506
+ mask = discriminant >= 0
507
+
508
+ ball_slices: list[SlicedLineFractions] = []
509
+ for i in range(len(self.point_coords)):
510
+ point_mask = mask[i]
511
+
512
+ closest_fractions = a[i, point_mask]
513
+ # min_fractions and max_fractions are the solutions for the reduced
514
+ # quadratic equations of intersecting the balls with the lines running
515
+ # through each segment for each point
516
+ sqrt_discriminant = discriminant[i, point_mask] ** 0.5
517
+ min_fractions = closest_fractions - sqrt_discriminant
518
+ max_fractions = closest_fractions + sqrt_discriminant
519
+ segment_indices = long_segments[point_mask]
520
+
521
+ # if the intersection of the ball with the line running through the segment
522
+ # lies completely outside the segment, we have to skip it
523
+ keep = np.nonzero(np.logical_and(max_fractions >= 0, min_fractions <= 1))[0]
524
+
525
+ slfs = SlicedLineFractions(
526
+ self,
527
+ i,
528
+ segment_indices[keep],
529
+ # clip to segments
530
+ clip(min_fractions[keep], 0, 1),
531
+ clip(closest_fractions[keep], 0, 1),
532
+ clip(max_fractions[keep], 0, 1),
533
+ )
534
+ ball_slices.append(slfs)
535
+ return ball_slices
536
+
537
+
538
+ class SlicedLineFractions:
539
+ """Filtered and sliced LineFractions."""
540
+
541
+ __slots__ = (
542
+ "line_fractions",
543
+ "point_index",
544
+ "segment_indices",
545
+ "min_fractions",
546
+ "closest_fractions",
547
+ "max_fractions",
548
+ )
549
+
550
+ line_fractions: LineFractions
551
+ point_index: int
552
+ segment_indices: np.ndarray
553
+ min_fractions: np.ndarray
554
+ closest_fractions: np.ndarray
555
+ max_fractions: np.ndarray
556
+
557
+ def __init__(
558
+ self,
559
+ line_fractions: LineFractions,
560
+ point_index: int,
561
+ segment_indices: np.ndarray,
562
+ min_fractions: np.ndarray,
563
+ closest_fractions: np.ndarray,
564
+ max_fractions,
565
+ ) -> None:
566
+ self.line_fractions = line_fractions
567
+ self.point_index = point_index
568
+ self.segment_indices = segment_indices
569
+ self.min_fractions = min_fractions
570
+ self.closest_fractions = closest_fractions
571
+ self.max_fractions = max_fractions
572
+
573
+ def __len__(self) -> int:
574
+ return len(self.segment_indices)
575
+
576
+ def discretize(
577
+ self, segment_lengths: np.ndarray, sampling_step: float
578
+ ) -> "ProjectedPoints":
579
+ """Discretize the selection.
580
+
581
+ A `ProjectedPoints` object with the discretization is returned. The minimum
582
+ fraction, closest fraction and maximum fraction is guaranteed to be included in
583
+ the discretization for each segment. Between those, points are added to the
584
+ discretization, ensuring that consecutive points of the discretization for the
585
+ same segment are spaced at most `sampling_step` apart.
586
+
587
+ Duplicate points (if two neighboring segments are part of the selection) are
588
+ included in the discretization.
589
+
590
+ `segment_lengths` are the lenghts of the linestring segments in the same unit as
591
+ `sampling_step`. Zero segment length is only allowed for segments that are
592
+ considered short by the underlying target.
593
+ """
594
+
595
+ selected_segment_lengths = segment_lengths[self.segment_indices]
596
+
597
+ if np.any(selected_segment_lengths <= 0):
598
+ raise ValueError("length for non-short segments has to be > 0")
599
+
600
+ fraction_steps = sampling_step / selected_segment_lengths
601
+
602
+ left_fraction_deltas = self.closest_fractions - self.min_fractions
603
+ right_fraction_deltas = self.max_fractions - self.closest_fractions
604
+
605
+ n_left_samples = np.maximum(
606
+ np.ceil(left_fraction_deltas / fraction_steps).astype(int), 2
607
+ )
608
+ n_right_samples = np.maximum(
609
+ np.ceil(right_fraction_deltas / fraction_steps).astype(int), 2
610
+ )
611
+ # common sample at the closest fraction thus - 1
612
+ n_samples = n_left_samples + n_right_samples - 1
613
+ n_total_samples = n_samples.sum()
614
+
615
+ locations = Locations.empty(n_total_samples)
616
+
617
+ index_offset = 0
618
+ for i in range(len(self.segment_indices)):
619
+ left_fractions = np.linspace(
620
+ self.min_fractions[i], self.closest_fractions[i], n_left_samples[i]
621
+ )
622
+ right_fractions = np.linspace(
623
+ self.closest_fractions[i], self.max_fractions[i], n_right_samples[i]
624
+ )
625
+ locations.from_vertices[
626
+ index_offset : index_offset + n_samples[i]
627
+ ] = self.segment_indices[i]
628
+ locations.to_vertices[index_offset : index_offset + n_samples[i]] = (
629
+ self.segment_indices[i] + 1
630
+ )
631
+ locations.fractions[
632
+ index_offset : index_offset + n_left_samples[i]
633
+ ] = left_fractions
634
+ # 1 sample overlap thus - 1
635
+ locations.fractions[
636
+ index_offset + n_left_samples[i] - 1 : index_offset + n_samples[i]
637
+ ] = right_fractions
638
+ index_offset += n_samples[i]
639
+
640
+ coords = (
641
+ locations.fractions[:, np.newaxis]
642
+ * self.line_fractions.target.segment_dirs[locations.from_vertices]
643
+ )
644
+ coords += self.line_fractions.target.segment_starts[locations.from_vertices]
645
+ cartesian_distances = np.linalg.norm(
646
+ coords - self.line_fractions.point_coords[self.point_index, np.newaxis],
647
+ axis=-1,
648
+ )
649
+ return ProjectedPoints(coords, locations, cartesian_distances)
650
+
461
651
 
462
652
  def interpolate(data: np.ndarray, locations: Locations) -> np.ndarray:
463
653
  """Interpolate data interpreted as a tensor-valued linestring.