Skip to content
GitLab
Projects
Groups
Snippets
Help
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Open sidebar
NOCSurfaceProcesses
GeoSpatialTools
Commits
37edeb89
Commit
37edeb89
authored
5 months ago
by
Joseph Siddons
Browse files
Options
Download
Email Patches
Plain Diff
feat: add find_nearest function
parent
0bf11853
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
44 additions
and
0 deletions
+44
-0
GeoSpatialTools/neighbours.py
GeoSpatialTools/neighbours.py
+44
-0
No files found.
GeoSpatialTools/neighbours.py
0 → 100644
View file @
37edeb89
from
numpy
import
argmin
from
bisect
import
bisect
from
typing
import
TypeVar
from
datetime
import
date
,
datetime
Numeric
=
TypeVar
(
"Numeric"
,
int
,
float
,
datetime
,
date
)
def
_find_nearest
(
vals
:
list
[
Numeric
],
test
:
Numeric
)
->
int
:
i
=
bisect
(
vals
,
test
)
# Position that test would be inserted
# Handle edges
if
i
==
0
and
test
<=
vals
[
0
]:
return
0
elif
i
==
len
(
vals
)
and
test
>=
vals
[
-
1
]:
return
len
(
vals
)
-
1
test_idx
=
[
i
-
1
,
i
]
return
test_idx
[
argmin
([
abs
(
test
-
vals
[
j
])
for
j
in
test_idx
])]
def
find_nearest
(
vals
:
list
[
Numeric
],
test
:
list
[
Numeric
])
->
list
[
int
]:
"""
Find the nearest value in a list of values for each test value.
Uses bisection for speediness!
Arguments
=========
vals : list[Numeric]
List of values - this is the pool of values for which we are looking
for a nearest match. This list MUST be sorted. Sortedness is not
checked, nor is the list sorted. An error will be raised if the list
is not sorted.
test : list[Numeric]
List of query values
Returns
=======
A list containing the index of the nearest neighbour in vals for each value
in test.
"""
return
[
_find_nearest
(
vals
,
t
)
for
t
in
test
]
This diff is collapsed.
Click to expand it.
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment