scipy/query-per-point
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| SciPy | warning | unsafe, with xpd check --fix --unsafe-fixes |
All versions |
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]What the rule reports
Section titled “What the rule reports”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.
How to fix it
Section titled “How to fix it”xpd check --fix --unsafe-fixes rewrites np.array([tree.query(q)[i] for q in queries]) to tree.query(queries)[i]. Other loop and comprehension forms remain manual.
Diagnostic message
Section titled “Diagnostic message”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.See all rules in the SciPy pack.