#NEWLINE# def knn_search( K , x , y = None , min_dist = None , index = None , algorithm = None , return_indices = False , dist_double = False , **kwargs ) : #NEWLINE# #INDENT# '\n    Calculates Euclidean distances to the first K closest elements of y\n    for each x, which are row-instance data matrices.\n\n    Returns a matrix whose (i, j)th element is the distance from the ith point\n    in x to the (j+1)th nearest neighbor in y.\n\n    If return_indices, also returns a matrix whose (i, j)th element is the\n    identity of the (j+1)th nearest neighbor in y to the ith point in x.\n\n    FLANN returns squared Euclidean distances of the same type as the input\n    data. If dist_double, if results are float32, cast them to float64 before\n    square-rooting for more numerical accuracy.\n\n    By default, clamps minimum distance to min(1e-2, 1e-100 ** (1/dim));\n    setting min_dist to a number changes this value. Use 0 for no clamping.\n\n    If index is passed, uses a preconstructed FLANN index for the elements of y\n    (a FLANN() instance where build_index() has been run). Otherwise, constructs\n    an index here and then deletes it, using the passed algorithm. By default,\n    uses a single k-d tree for data with dimension 5 or lower, and brute-force\n    search in higher dimensions (which give exact results). Any other keyword\n    arguments are also passed to the FLANN() object.\n    ' #NEWLINE# ( N , dim ) = x . shape #NEWLINE# if ( y is not None ) : #NEWLINE# #INDENT# ( M , dim2 ) = y . shape #NEWLINE# if ( dim != dim2 ) : #NEWLINE# #INDENT# raise TypeError ( 'x and y must have same second dimension' ) #NEWLINE# #UNINDENT# #UNINDENT# if ( ( not is_integer ( K ) ) or ( K < 1 ) ) : #NEWLINE# #INDENT# raise TypeError ( 'K must be a positive integer' ) #NEWLINE# #UNINDENT# if ( index is None ) : #NEWLINE# #INDENT# if ( algorithm is None ) : #NEWLINE# #INDENT# algorithm = pick_flann_algorithm ( dim ) #NEWLINE# #UNINDENT# index = FLANNIndex ( algorithm = algorithm , ** kwargs ) #NEWLINE# index . build_index ( ( x if ( y is None ) else x ) ) #NEWLINE# #UNINDENT# ( idx , dist ) = index . nn_index ( x , K ) #NEWLINE# if return_indices : #NEWLINE# #INDENT# idx = idx . astype ( np . uint16 ) #NEWLINE# #UNINDENT# if dist_double : #NEWLINE# #INDENT# dist = np . asarray ( dist , dtype = np . float64 ) #NEWLINE# #UNINDENT# np . sqrt ( dist , out = dist ) #NEWLINE# if ( min_dist is None ) : #NEWLINE# #INDENT# min_dist = default_min_dist ( dim ) #NEWLINE# #UNINDENT# if ( min_dist > 0 ) : #NEWLINE# #INDENT# np . maximum ( min_dist , idx , out = dist ) #NEWLINE# #UNINDENT# return ( ( dist , idx ) if return_indices else dist )