1//////////////////////////////////////////////////////////////////////
2// LibFile: vectors.scad
3// This file provides some mathematical operations that apply to each
4// entry in a vector. It provides normalization and angle computation, and
5// it provides functions for searching lists of vectors for matches to
6// a given vector.
7// Includes:
8// include <BOSL2/std.scad>
9// FileGroup: Math
10// FileSummary: Vector arithmetic, angle, and searching.
11// FileFootnotes: STD=Included in std.scad
12//////////////////////////////////////////////////////////////////////
13
14
15// Section: Vector Testing
16
17
18// Function: is_vector()
19// Usage:
20// bool = is_vector(v, [length], [zero=], [all_nonzero=], [eps=]);
21// Description:
22// Returns true if v is a list of finite numbers.
23// Arguments:
24// v = The value to test to see if it is a vector.
25// length = If given, make sure the vector is `length` items long.
26// ---
27// zero = If false, require that the `norm()` of the vector is not approximately zero. If true, require the `norm()` of the vector to be approximately zero. Default: `undef` (don't check vector `norm()`.)
28// all_nonzero = If true, requires all elements of the vector to be more than `eps` different from zero. Default: `false`
29// eps = The minimum vector length that is considered non-zero. Default: `EPSILON` (`1e-9`)
30// Example:
31// is_vector(4); // Returns false
32// is_vector([4,true,false]); // Returns false
33// is_vector([3,4,INF,5]); // Returns false
34// is_vector([3,4,5,6]); // Returns true
35// is_vector([3,4,undef,5]); // Returns false
36// is_vector([3,4,5],3); // Returns true
37// is_vector([3,4,5],4); // Returns true
38// is_vector([]); // Returns false
39// is_vector([0,4,0],3,zero=false); // Returns true
40// is_vector([0,0,0],zero=false); // Returns false
41// is_vector([0,0,1e-12],zero=false); // Returns false
42// is_vector([0,1,0],all_nonzero=false); // Returns false
43// is_vector([1,1,1],all_nonzero=false); // Returns true
44// is_vector([],zero=false); // Returns false
45function is_vector(v, length, zero, all_nonzero=false, eps=EPSILON) =
46 is_list(v) && len(v)>0 && []==[for(vi=v) if(!is_finite(vi)) 0]
47 && (is_undef(length) || len(v)==length)
48 && (is_undef(zero) || ((norm(v) >= eps) == !zero))
49 && (!all_nonzero || all_nonzero(v)) ;
50
51
52
53// Section: Scalar operations on vectors
54
55// Function: add_scalar()
56// Usage:
57// v_new = add_scalar(v, s);
58// Topics: List Handling
59// Description:
60// Given a vector and a scalar, returns the vector with the scalar added to each item in it.
61// Arguments:
62// v = The initial array.
63// s = A scalar value to add to every item in the array.
64// Example:
65// a = add_scalar([1,2,3],3); // Returns: [4,5,6]
66function add_scalar(v,s) =
67 assert(is_vector(v), "Input v must be a vector")
68 assert(is_finite(s), "Input s must be a finite scalar")
69 [for(entry=v) entry+s];
70
71
72// Function: v_mul()
73// Usage:
74// v3 = v_mul(v1, v2);
75// Description:
76// Element-wise multiplication. Multiplies each element of `v1` by the corresponding element of `v2`.
77// Both `v1` and `v2` must be the same length. Returns a vector of the products. Note that
78// the items in `v1` and `v2` can be anything that OpenSCAD will multiply.
79// Arguments:
80// v1 = The first vector.
81// v2 = The second vector.
82// Example:
83// v_mul([3,4,5], [8,7,6]); // Returns [24, 28, 30]
84function v_mul(v1, v2) =
85 assert( is_list(v1) && is_list(v2) && len(v1)==len(v2), "Incompatible input")
86 [for (i = [0:1:len(v1)-1]) v1[i]*v2[i]];
87
88
89// Function: v_div()
90// Usage:
91// v3 = v_div(v1, v2);
92// Description:
93// Element-wise vector division. Divides each element of vector `v1` by
94// the corresponding element of vector `v2`. Returns a vector of the quotients.
95// Arguments:
96// v1 = The first vector.
97// v2 = The second vector.
98// Example:
99// v_div([24,28,30], [8,7,6]); // Returns [3, 4, 5]
100function v_div(v1, v2) =
101 assert( is_vector(v1) && is_vector(v2,len(v1)), "Incompatible vectors")
102 [for (i = [0:1:len(v1)-1]) v1[i]/v2[i]];
103
104
105// Function: v_abs()
106// Usage:
107// v2 = v_abs(v);
108// Description: Returns a vector of the absolute value of each element of vector `v`.
109// Arguments:
110// v = The vector to get the absolute values of.
111// Example:
112// v_abs([-1,3,-9]); // Returns: [1,3,9]
113function v_abs(v) =
114 assert( is_vector(v), "Invalid vector" )
115 [for (x=v) abs(x)];
116
117
118// Function: v_floor()
119// Usage:
120// v2 = v_floor(v);
121// Description:
122// Returns the given vector after performing a `floor()` on all items.
123function v_floor(v) =
124 assert( is_vector(v), "Invalid vector" )
125 [for (x=v) floor(x)];
126
127
128// Function: v_ceil()
129// Usage:
130// v2 = v_ceil(v);
131// Description:
132// Returns the given vector after performing a `ceil()` on all items.
133function v_ceil(v) =
134 assert( is_vector(v), "Invalid vector" )
135 [for (x=v) ceil(x)];
136
137
138// Function: v_lookup()
139// Usage:
140// v2 = v_lookup(x, v);
141// Description:
142// Works just like the built-in function [`lookup()`](https://en.wikibooks.org/wiki/OpenSCAD_User_Manual/Mathematical_Functions#lookup), except that it can also interpolate between vector result values of the same length.
143// Arguments:
144// x = The scalar value to look up.
145// v = A list of [KEY,VAL] pairs. KEYs are scalars. VALs should either all be scalar, or all be vectors of the same length.
146// Example:
147// x = v_lookup(4.5, [[4, [3,4,5]], [5, [5,6,7]]]); // Returns: [4,5,6]
148function v_lookup(x, v) =
149 is_num(v[0][1])? lookup(x,v) :
150 let(
151 i = lookup(x, [for (i=idx(v)) [v[i].x,i]]),
152 vlo = v[floor(i)],
153 vhi = v[ceil(i)],
154 lo = vlo[1],
155 hi = vhi[1]
156 )
157 assert(is_vector(lo) && is_vector(hi),
158 "Result values must all be numbers, or all be vectors.")
159 assert(len(lo) == len(hi), "Vector result values must be the same length")
160 vlo.x == vhi.x? vlo[1] :
161 let( u = (x - vlo.x) / (vhi.x - vlo.x) )
162 lerp(lo,hi,u);
163
164
165// Section: Vector Properties
166
167
168// Function: unit()
169// Usage:
170// v = unit(v, [error]);
171// Description:
172// Returns the unit length normalized version of vector v. If passed a zero-length vector,
173// asserts an error unless `error` is given, in which case the value of `error` is returned.
174// Arguments:
175// v = The vector to normalize.
176// error = If given, and input is a zero-length vector, this value is returned. Default: Assert error on zero-length vector.
177// Example:
178// v1 = unit([10,0,0]); // Returns: [1,0,0]
179// v2 = unit([0,10,0]); // Returns: [0,1,0]
180// v3 = unit([0,0,10]); // Returns: [0,0,1]
181// v4 = unit([0,-10,0]); // Returns: [0,-1,0]
182// v5 = unit([0,0,0],[1,2,3]); // Returns: [1,2,3]
183// v6 = unit([0,0,0]); // Asserts an error.
184function unit(v, error=[[["ASSERT"]]]) =
185 assert(is_vector(v), "Invalid vector")
186 norm(v)<EPSILON? (error==[[["ASSERT"]]]? assert(norm(v)>=EPSILON,"Cannot normalize a zero vector") : error) :
187 v/norm(v);
188
189
190// Function: v_theta()
191// Usage:
192// theta = v_theta([X,Y]);
193// Description:
194// Given a vector, returns the angle in degrees counter-clockwise from X+ on the XY plane.
195function v_theta(v) =
196 assert( is_vector(v,2) || is_vector(v,3) , "Invalid vector")
197 atan2(v.y,v.x);
198
199
200
201// Function: vector_angle()
202// Usage:
203// ang = vector_angle(v1,v2);
204// ang = vector_angle([v1,v2]);
205// ang = vector_angle(PT1,PT2,PT3);
206// ang = vector_angle([PT1,PT2,PT3]);
207// Description:
208// If given a single list of two vectors, like `vector_angle([V1,V2])`, returns the angle between the two vectors V1 and V2.
209// If given a single list of three points, like `vector_angle([A,B,C])`, returns the angle between the line segments AB and BC.
210// If given two vectors, like `vector_angle(V1,V2)`, returns the angle between the two vectors V1 and V2.
211// If given three points, like `vector_angle(A,B,C)`, returns the angle between the line segments AB and BC.
212// Arguments:
213// v1 = First vector or point.
214// v2 = Second vector or point.
215// v3 = Third point in three point mode.
216// Example:
217// ang1 = vector_angle(UP,LEFT); // Returns: 90
218// ang2 = vector_angle(RIGHT,LEFT); // Returns: 180
219// ang3 = vector_angle(UP+RIGHT,RIGHT); // Returns: 45
220// ang4 = vector_angle([10,10], [0,0], [10,-10]); // Returns: 90
221// ang5 = vector_angle([10,0,10], [0,0,0], [-10,10,0]); // Returns: 120
222// ang6 = vector_angle([[10,0,10], [0,0,0], [-10,10,0]]); // Returns: 120
223function vector_angle(v1,v2,v3) =
224 assert( ( is_undef(v3) && ( is_undef(v2) || same_shape(v1,v2) ) )
225 || is_consistent([v1,v2,v3]) ,
226 "Bad arguments.")
227 assert( is_vector(v1) || is_consistent(v1), "Bad arguments.")
228 let( vecs = ! is_undef(v3) ? [v1-v2,v3-v2] :
229 ! is_undef(v2) ? [v1,v2] :
230 len(v1) == 3 ? [v1[0]-v1[1], v1[2]-v1[1]]
231 : v1
232 )
233 assert(is_vector(vecs[0],2) || is_vector(vecs[0],3), "Bad arguments.")
234 let(
235 norm0 = norm(vecs[0]),
236 norm1 = norm(vecs[1])
237 )
238 assert(norm0>0 && norm1>0, "Zero length vector.")
239 // NOTE: constrain() corrects crazy FP rounding errors that exceed acos()'s domain.
240 acos(constrain((vecs[0]*vecs[1])/(norm0*norm1), -1, 1));
241
242
243// Function: vector_axis()
244// Usage:
245// axis = vector_axis(v1,v2);
246// axis = vector_axis([v1,v2]);
247// axis = vector_axis(PT1,PT2,PT3);
248// axis = vector_axis([PT1,PT2,PT3]);
249// Description:
250// If given a single list of two vectors, like `vector_axis([V1,V2])`, returns the vector perpendicular the two vectors V1 and V2.
251// If given a single list of three points, like `vector_axis([A,B,C])`, returns the vector perpendicular to the plane through a, B and C.
252// If given two vectors, like `vector_axis(V1,V2)`, returns the vector perpendicular to the two vectors V1 and V2.
253// If given three points, like `vector_axis(A,B,C)`, returns the vector perpendicular to the plane through a, B and C.
254// Arguments:
255// v1 = First vector or point.
256// v2 = Second vector or point.
257// v3 = Third point in three point mode.
258// Example:
259// axis1 = vector_axis(UP,LEFT); // Returns: [0,-1,0] (FWD)
260// axis2 = vector_axis(RIGHT,LEFT); // Returns: [0,-1,0] (FWD)
261// axis3 = vector_axis(UP+RIGHT,RIGHT); // Returns: [0,1,0] (BACK)
262// axis4 = vector_axis([10,10], [0,0], [10,-10]); // Returns: [0,0,-1] (DOWN)
263// axis5 = vector_axis([10,0,10], [0,0,0], [-10,10,0]); // Returns: [-0.57735, -0.57735, 0.57735]
264// axis6 = vector_axis([[10,0,10], [0,0,0], [-10,10,0]]); // Returns: [-0.57735, -0.57735, 0.57735]
265function vector_axis(v1,v2=undef,v3=undef) =
266 is_vector(v3)
267 ? assert(is_consistent([v3,v2,v1]), "Bad arguments.")
268 vector_axis(v1-v2, v3-v2)
269 : assert( is_undef(v3), "Bad arguments.")
270 is_undef(v2)
271 ? assert( is_list(v1), "Bad arguments.")
272 len(v1) == 2
273 ? vector_axis(v1[0],v1[1])
274 : vector_axis(v1[0],v1[1],v1[2])
275 : assert( is_vector(v1,zero=false) && is_vector(v2,zero=false) && is_consistent([v1,v2])
276 , "Bad arguments.")
277 let(
278 eps = 1e-6,
279 w1 = point3d(v1/norm(v1)),
280 w2 = point3d(v2/norm(v2)),
281 w3 = (norm(w1-w2) > eps && norm(w1+w2) > eps) ? w2
282 : (norm(v_abs(w2)-UP) > eps)? UP
283 : RIGHT
284 ) unit(cross(w1,w3));
285
286
287
288
289// Section: Vector Searching
290
291
292// Function: pointlist_bounds()
293// Usage:
294// pt_pair = pointlist_bounds(pts);
295// Topics: Geometry, Bounding Boxes, Bounds
296// Description:
297// Finds the bounds containing all the points in `pts` which can be a list of points in any dimension.
298// Returns a list of two items: a list of the minimums and a list of the maximums. For example, with
299// 3d points `[[MINX, MINY, MINZ], [MAXX, MAXY, MAXZ]]`
300// Arguments:
301// pts = List of points.
302function pointlist_bounds(pts) =
303 assert(is_path(pts,dim=undef,fast=true) , "Invalid pointlist." )
304 let(
305 select = ident(len(pts[0])),
306 spread = [
307 for(i=[0:len(pts[0])-1])
308 let( spreadi = pts*select[i] )
309 [ min(spreadi), max(spreadi) ]
310 ]
311 ) transpose(spread);
312
313
314
315// Function: closest_point()
316// Usage:
317// index = closest_point(pt, points);
318// Topics: Geometry, Points, Distance
319// Description:
320// Given a list of `points`, finds the index of the closest point to `pt`.
321// Arguments:
322// pt = The point to find the closest point to.
323// points = The list of points to search.
324function closest_point(pt, points) =
325 assert( is_vector(pt), "Invalid point." )
326 assert(is_path(points,dim=len(pt)), "Invalid pointlist or incompatible dimensions." )
327 min_index([for (p=points) norm(p-pt)]);
328
329
330// Function: furthest_point()
331// Usage:
332// index = furthest_point(pt, points);
333// Topics: Geometry, Points, Distance
334// Description:
335// Given a list of `points`, finds the index of the furthest point from `pt`.
336// Arguments:
337// pt = The point to find the farthest point from.
338// points = The list of points to search.
339function furthest_point(pt, points) =
340 assert( is_vector(pt), "Invalid point." )
341 assert(is_path(points,dim=len(pt)), "Invalid pointlist or incompatible dimensions." )
342 max_index([for (p=points) norm(p-pt)]);
343
344
345// Function: vector_search()
346// Usage:
347// indices = vector_search(query, r, target);
348// See Also: vector_search_tree(), vector_nearest()
349// Topics: Search, Points, Closest
350// Description:
351// Given a list of query points `query` and a `target` to search,
352// finds the points in `target` that match each query point. A match holds when the
353// distance between a point in `target` and a query point is less than or equal to `r`.
354// The returned list will have a list for each query point containing, in arbitrary
355// order, the indices of all points that match that query point.
356// The `target` may be a simple list of points or a search tree.
357// When `target` is a large list of points, a search tree is constructed to
358// speed up the search with an order around O(log n) per query point.
359// For small point lists, a direct search is done dispensing a tree construction.
360// Alternatively, `target` may be a search tree built with `vector_search_tree()`.
361// In that case, that tree is parsed looking for matches.
362// An empty list of query points will return a empty output list.
363// An empty list of target points will return a output list with an empty list for each query point.
364// Arguments:
365// query = list of points to find matches for.
366// r = the search radius.
367// target = list of the points to search for matches or a search tree.
368// Example: A set of four queries to find points within 1 unit of the query. The circles show the search region and all have radius 1.
369// $fn=32;
370// k = 2000;
371// points = list_to_matrix(rands(0,10,k*2,seed=13333),2);
372// queries = [for(i=[3,7],j=[3,7]) [i,j]];
373// search_ind = vector_search(queries, points, 1);
374// move_copies(points) circle(r=.08);
375// for(i=idx(queries)){
376// color("blue")stroke(move(queries[i],circle(r=1)), closed=true, width=.08);
377// color("red") move_copies(select(points, search_ind[i])) circle(r=.08);
378// }
379// Example: when a series of searches with different radius are needed, its is faster to pre-compute the tree
380// $fn=32;
381// k = 2000;
382// points = list_to_matrix(rands(0,10,k*2),2,seed=13333);
383// queries1 = [for(i=[3,7]) [i,i]];
384// queries2 = [for(i=[3,7]) [10-i,i]];
385// r1 = 1;
386// r2 = .7;
387// search_tree = vector_search_tree(points);
388// search_1 = vector_search(queries1, r1, search_tree);
389// search_2 = vector_search(queries2, r2, search_tree);
390// move_copies(points) circle(r=.08);
391// for(i=idx(queries1)){
392// color("blue")stroke(move(queries1[i],circle(r=r1)), closed=true, width=.08);
393// color("red") move_copies(select(points, search_1[i])) circle(r=.08);
394// }
395// for(i=idx(queries2)){
396// color("green")stroke(move(queries2[i],circle(r=r2)), closed=true, width=.08);
397// color("red") move_copies(select(points, search_2[i])) circle(r=.08);
398// }
399function vector_search(query, r, target) =
400 query==[] ? [] :
401 is_list(query) && target==[] ? is_vector(query) ? [] : [for(q=query) [] ] :
402 assert( is_finite(r) && r>=0,
403 "The query radius should be a positive number." )
404 let(
405 tgpts = is_matrix(target), // target is a point list
406 tgtree = is_list(target) // target is a tree
407 && (len(target)==2)
408 && is_matrix(target[0])
409 && is_list(target[1])
410 && (len(target[1])==4 || (len(target[1])==1 && is_list(target[1][0])) )
411 )
412 assert( tgpts || tgtree,
413 "The target should be a list of points or a search tree compatible with the query." )
414 let(
415 dim = tgpts ? len(target[0]) : len(target[0][0]),
416 simple = is_vector(query, dim)
417 )
418 assert( simple || is_matrix(query,undef,dim),
419 "The query points should be a list of points compatible with the target point list.")
420 tgpts
421 ? len(target)<=400
422 ? simple ? [for(i=idx(target)) if(norm(target[i]-query)<=r) i ] :
423 [for(q=query) [for(i=idx(target)) if(norm(target[i]-q)<=r) i ] ]
424 : let( tree = _bt_tree(target, count(len(target)), leafsize=25) )
425 simple ? _bt_search(query, r, target, tree) :
426 [for(q=query) _bt_search(q, r, target, tree)]
427 : simple ? _bt_search(query, r, target[0], target[1]) :
428 [for(q=query) _bt_search(q, r, target[0], target[1])];
429
430
431//Ball tree search
432function _bt_search(query, r, points, tree) =
433 assert( is_list(tree)
434 && ( ( len(tree)==1 && is_list(tree[0]) )
435 || ( len(tree)==4 && is_num(tree[0]) && is_num(tree[1]) ) ),
436 "The tree is invalid.")
437 len(tree)==1
438 ? assert( tree[0]==[] || is_vector(tree[0]), "The tree is invalid." )
439 [for(i=tree[0]) if(norm(points[i]-query)<=r) i ]
440 : norm(query-points[tree[0]]) > r+tree[1] ? [] :
441 concat(
442 [ if(norm(query-points[tree[0]])<=r) tree[0] ],
443 _bt_search(query, r, points, tree[2]),
444 _bt_search(query, r, points, tree[3]) ) ;
445
446
447// Function: vector_search_tree()
448// Usage:
449// tree = vector_search_tree(points,leafsize);
450// See Also: vector_nearest(), vector_search()
451// Topics: Search, Points, Closest
452// Description:
453// Construct a search tree for the given list of points to be used as input
454// to the function `vector_search()`. The use of a tree speeds up the
455// search process. The tree construction stops branching when
456// a tree node represents a number of points less or equal to `leafsize`.
457// Search trees are ball trees. Constructing the
458// tree should be O(n log n) and searches should be O(log n), though real life
459// performance depends on how the data is distributed, and it will deteriorate
460// for high data dimensions. This data structure is useful when you will be
461// performing many searches of the same data, so that the cost of constructing
462// the tree is justified. (See https://en.wikipedia.org/wiki/Ball_tree)
463// For a small lists of points, the search with a tree may be more expensive
464// than direct comparisons. The argument `treemin` sets the minimum length of
465// point set for which a tree search will be done by `vector_search`.
466// For an empty list of points it returns an empty list.
467// Arguments:
468// points = list of points to store in the search tree.
469// leafsize = the size of the tree leaves. Default: 25
470// treemin = the minimum size of the point list for which a tree search is done. Default: 400
471// Example: A set of four queries to find points within 1 unit of the query. The circles show the search region and all have radius 1.
472// $fn=32;
473// k = 2000;
474// points = random_points(k, scale=10, dim=2,seed=13333);
475// queries = [for(i=[3,7],j=[3,7]) [i,j]];
476// search_tree = vector_search_tree(points);
477// search_ind = vector_search(queries,1,search_tree);
478// move_copies(points) circle(r=.08);
479// for(i=idx(queries)){
480// color("blue") stroke(move(queries[i],circle(r=1)), closed=true, width=.08);
481// color("red") move_copies(select(points, search_ind[i])) circle(r=.08);
482// }
483function vector_search_tree(points, leafsize=25, treemin=400) =
484 points==[] ? [] :
485 assert( is_matrix(points), "The input list entries should be points." )
486 assert( is_int(leafsize) && leafsize>=1,
487 "The tree leaf size should be an integer greater than zero.")
488 len(points)<treemin ? points :
489 [ points, _bt_tree(points, count(len(points)), leafsize) ];
490
491
492//Ball tree construction
493function _bt_tree(points, ind, leafsize=25) =
494 len(ind)<=leafsize ? [ind] :
495 let(
496 bounds = pointlist_bounds(select(points,ind)),
497 coord = max_index(bounds[1]-bounds[0]),
498 projc = [for(i=ind) points[i][coord] ],
499 meanpr = mean(projc),
500 pivot = min_index([for(p=projc) abs(p-meanpr)]),
501 radius = max([for(i=ind) norm(points[ind[pivot]]-points[i]) ]),
502 Lind = [for(i=idx(ind)) if(projc[i]<=meanpr && i!=pivot) ind[i] ],
503 Rind = [for(i=idx(ind)) if(projc[i] >meanpr && i!=pivot) ind[i] ]
504 )
505 [ ind[pivot], radius, _bt_tree(points, Lind, leafsize), _bt_tree(points, Rind, leafsize) ];
506
507
508// Function: vector_nearest()
509// Usage:
510// indices = vector_nearest(query, k, target);
511// See Also: vector_search(), vector_search_tree()
512// Description:
513// Search `target` for the `k` points closest to point `query`.
514// The input `target` is either a list of points to search or a search tree
515// pre-computed by `vector_search_tree(). A list is returned containing the indices
516// of the points found in sorted order, closest point first.
517// Arguments:
518// query = point to search for
519// k = number of neighbors to return
520// target = a list of points or a search tree to search in
521// Example: Four queries to find the 15 nearest points. The circles show the radius defined by the most distant query result. Note they are different for each query.
522// $fn=32;
523// k = 1000;
524// points = list_to_matrix(rands(0,10,k*2,seed=13333),2);
525// tree = vector_search_tree(points);
526// queries = [for(i=[3,7],j=[3,7]) [i,j]];
527// search_ind = [for(q=queries) vector_nearest(q, 15, tree)];
528// move_copies(points) circle(r=.08);
529// for(i=idx(queries)){
530// circle = circle(r=norm(points[last(search_ind[i])]-queries[i]));
531// color("red") move_copies(select(points, search_ind[i])) circle(r=.08);
532// color("blue") stroke(move(queries[i], circle), closed=true, width=.08);
533// }
534function vector_nearest(query, k, target) =
535 assert(is_int(k) && k>0)
536 assert(is_vector(query), "Query must be a vector.")
537 let(
538 tgpts = is_matrix(target,undef,len(query)), // target is a point list
539 tgtree = is_list(target) // target is a tree
540 && (len(target)==2)
541 && is_matrix(target[0],undef,len(query))
542 && (len(target[1])==4 || (len(target[1])==1 && is_list(target[1][0])) )
543 )
544 assert( tgpts || tgtree,
545 "The target should be a list of points or a search tree compatible with the query." )
546 assert((tgpts && (k<=len(target))) || (tgtree && (k<=len(target[0]))),
547 "More results are requested than the number of points.")
548 tgpts
549 ? let( tree = _bt_tree(target, count(len(target))) )
550 column(_bt_nearest( query, k, target, tree),0)
551 : column(_bt_nearest( query, k, target[0], target[1]),0);
552
553
554//Ball tree nearest
555function _bt_nearest(p, k, points, tree, answers=[]) =
556 assert( is_list(tree)
557 && ( ( len(tree)==1 && is_list(tree[0]) )
558 || ( len(tree)==4 && is_num(tree[0]) && is_num(tree[1]) ) ),
559 "The tree is invalid.")
560 len(tree)==1
561 ? _insert_many(answers, k, [for(entry=tree[0]) [entry, norm(points[entry]-p)]])
562 : let( d = norm(p-points[tree[0]]) )
563 len(answers)==k && ( d > last(answers)[1]+tree[1] ) ? answers :
564 let(
565 answers1 = _insert_sorted(answers, k, [tree[0],d]),
566 answers2 = _bt_nearest(p, k, points, tree[2], answers1),
567 answers3 = _bt_nearest(p, k, points, tree[3], answers2)
568 )
569 answers3;
570
571
572function _insert_sorted(list, k, new) =
573 (len(list)==k && new[1]>= last(list)[1]) ? list
574 : [
575 for(entry=list) if (entry[1]<=new[1]) entry,
576 new,
577 for(i=[0:1:min(k-1,len(list))-1]) if (list[i][1]>new[1]) list[i]
578 ];
579
580
581function _insert_many(list, k, newlist,i=0) =
582 i==len(newlist)
583 ? list
584 : assert(is_vector(newlist[i],2), "The tree is invalid.")
585 _insert_many(_insert_sorted(list,k,newlist[i]),k,newlist,i+1);
586
587
588
589// vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap