Skip to content

scipy/query-per-point

Rule query-per-point
Pack SciPy
Severity warning
Fix none, edit by hand
Library versions every version

Querying a KD tree once for every point makes one call for each point. Pass all points to query in one call, which was 16 times faster.

def nearest_points(points, queries):
tree = KDTree(points)
return [tree.query(q)[1] for q in queries]
return tree.query(queries)[1]

The rule reports tree.query(q) inside a comprehension or a for loop, where q is the loop name or a row indexed by it. tree must come from a KDTree or cKDTree call in the same function. For 1,000,000 points on a tree of 10,000 points, one query of all points ran 16 to 17 times faster.

xpd has no automatic fix, so make the change by hand.

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

This queries $T once per point. Pass all the points to $T.query in one call, as an array of shape (n, k), which ran 16 to 17 times faster on 1,000,000 points.

Browse the other rules of the SciPy pack.