/** * main entry * * Input * 1: the reference points to construct the kd-tree (d x n double matrix) * 2: the query points (d x nq double matrix) * 3: the option struct * Output * 1: the nearest neighbor index matrix (k x nq int32 matrix) * 2: the distance matrix (k x nq double matrix) * Here, * d - the point dimension * n - the number of reference points * nq - the number of query points * k - the number of maximum neighbors for each point * Note, * The responsibility of checking the validity of the input arguments * is with the invoker. The annsearch.m does the checking. * The mex-function in itself does not conduct the checking again. */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // take inputs const mxArray *mxRefPts = prhs[0]; const mxArray *mxQuery = prhs[1]; const mxArray *mxOpts = prhs[2]; // parse options AnnBuildOptions opts_build; AnnSearchOptions opts_search; parse_tree_building_options(mxOpts, opts_build); parse_search_options(mxOpts, opts_search); // construct the tree int d = 0; int n = 0; ANNpointArray pts = createPointArray(mxRefPts, d, n); ANNkd_tree *kd_tree = createKdTree(d, n, pts, opts_build); // perform the search mxArray *mxInds = NULL; mxArray *mxDists = NULL; performAnnkSearch(kd_tree, mxQuery, opts_search, mxInds, mxDists); // release the kd-tree delete kd_tree; annDeallocPts(pts); annClose(); // set outputs plhs[0] = mxInds; plhs[1] = mxDists; }
/////////////////////////////////////////////////////////////////////////////// // // the main entry for Matlab binary // Input: // nrhs = 6 // prhs[0]: the points for building the KD Tree [d x n0 matrix] // prhs[1]: the points whose neighbors are queried [d x n matrix] // prhs[2]: the size of each neighborhood // prhs[3]: the error bound // prhs[4]: the index of the split rule to use (follow the ANN Library) // - 0: ANN_KD_STD (the optimized kd-splitting rule) // - 1: ANN_KD_MIDPT (midpoint split) // - 2: ANN_KD_FAIR (fair split) // - 3: ANN_KD_SL_MIDPT (sliding midpoint splitting) // - 4: ANN_KD_SL_FAIR (sliding fair splitting) // - 5: ANN_KD_SUGGEST (the authors' suggestion for best) // prhs[5]: the index of search method // - 0: Normal approximate KNN search // - 1: Priority K near neighbor search // Output: // nlhs <= 2 // plhs[0]: the array of indices for query points [k x n matrix] // plhs[1]: the array of distance values [k x n matrix] // // Remarks: // No pre-condition checking is performed. If the condition is violated, // the behavior of the program is undefined. It is the responsible of the // invoker to guarantee that the pre-conditions are all satisfied. // /////////////////////////////////////////////////////////////////////////////// void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { // name the input variables const mxArray *MP0 = prhs[0]; // the matrix of base points const mxArray *MP = prhs[1]; // the matrix of query points const mxArray *MNNSize = prhs[2]; // the scalar for K value const mxArray *MErrBound = prhs[3]; // the scalar for error bound const mxArray *MISplitRule = prhs[4]; // the scalar for split rule const mxArray *MISearchWay = prhs[5]; // the scalar for search method // get basic information int d = mxGetM(MP0); // point vector dimension int n0 = mxGetN(MP0); // the number of base points int n = mxGetN(MP); // the number of query points int k = (int)mxGetScalar(MNNSize); // the K value (neighborhood size) double errbound = (double)mxGetScalar(MErrBound); // the error bound int iSplitRule = (int)mxGetScalar(MISplitRule); // the index of split rule int iSearchMethod = (int)mxGetScalar(MISearchWay); // the index of search method // prepare the point arrays for ANN Library ANNpointArray pts0 = CreateANNPointArray(d, n0, MP0); ANNpointArray pts = CreateANNPointArray(d, n, MP); // build the KD Tree (with bucket size using default value 1) ANNkd_tree *kdtr = new ANNkd_tree(pts0, n0, d, 1, (ANNsplitRule)iSplitRule); // prepare the ANN output ANNidxArray nn_idx = new ANNidx[k * n]; ANNdistArray dists = new ANNdist[k * n]; // conduct KNN search knnSearchFunc fs = SelectSearchFunc(iSearchMethod); fs(kdtr, pts, n, k, nn_idx, dists, errbound); // set Matlab outputs if (nlhs >= 1) // output indices { plhs[0] = GetMxArrayFromIntArray(k, n, nn_idx); } if (nlhs >= 2) // output distances { plhs[1] = GetMxArrayFromDoubleArray(k, n, dists); } // release the KD Tree delete kdtr; // release ANN outputs delete[] nn_idx; delete[] dists; // release the point arrays ReleaseANNPointArray(pts0); ReleaseANNPointArray(pts); // finalize the ANN library annClose(); }
//destruction d'une instance de annUse annUse::~annUse() { //destruction des ressources utilisées par l'ann annDeallocPts(dataPts); delete [] nnIdx; delete [] dists; delete kdTree; annClose(); }
AnnPairAssignment::~AnnPairAssignment() { if(_tree) { delete _tree; _tree = NULL; annClose(); } }
void CANNObject::CleanUp() { delete [] nnIdx; delete [] dists; delete kdTree; // done with ANN annClose(); }
//***************************************************** // Function: distANN_XY //***************************************************** void distANN_XY( const ANNpointArray dataX, const ANNpointArray dataY, double* distsXY, unsigned int dimX, unsigned int dimY, unsigned int xN, unsigned int yN, unsigned int k, double eps ) { ANNkd_tree* kdTree; ANNdistArray nnDist; ANNidxArray nnIdx; // Allocate memory nnIdx = new ANNidx[ k+1 ]; nnDist = new ANNdist[ k+1 ]; kdTree = new ANNkd_tree( dataY, yN, dimY ); // Get the distances to all the points for( unsigned int i = 0; i < xN ; i++ ) { kdTree->annkSearch( dataX[ i ], k+1, nnIdx, nnDist, eps ); double my_dist = nnDist[ k ]; // check to see if the dist is zero (query point same as the kNN) // if so find the next k that gives the next positive distance if( my_dist == 0.0 ) { ANNdistArray nnDist_tmp = new ANNdist[ yN ]; ANNidxArray nnIdx_tmp = new ANNidx[ yN ]; kdTree->annkSearch( dataX[ i ], yN, nnIdx_tmp, nnDist_tmp, eps ); for( unsigned int my_k = k + 1; my_k < yN; ++my_k ) if( nnDist_tmp[ my_k ] > 0.0 ) { my_dist = nnDist_tmp[ my_k ]; break; } delete [] nnIdx_tmp; delete [] nnDist_tmp; } distsXY[ i ] = my_dist; } // Deallocate memory delete [] nnIdx; delete [] nnDist; delete kdTree; annClose(); return; }
arlCore::ICP::~ICP( void ) { #ifdef ANN if(m_ANNtree) delete m_ANNtree; if(m_modelPoints) annDeallocPts( m_modelPoints ); if(m_cloudPoints) annDeallocPts( m_cloudPoints ); if(m_Pk) annDeallocPts( m_Pk ); if(m_Yk) annDeallocPts( m_Yk ); if(m_Pi) annDeallocPts( m_Pi ); if(m_nn_idx) delete[] m_nn_idx; if(m_squaredDists) delete[] m_squaredDists; annClose(); #endif // ANN }
void ANNWrapper::Free() { if(!m_anything_to_free) return ; delete [] m_nnidx ; // clean things up delete [] m_dists; delete m_kdtree; annDeallocPts(m_data_pts); annClose(); // done with ANN m_anything_to_free = false; }
void CKNearestNeighbor::ResetTree() { if (m_pDataPts) { annDeallocPts(m_pDataPts); m_pDataPts = NULL; } if (m_pTreeRoot) { delete m_pTreeRoot; m_pTreeRoot = NULL; annClose();//delete global variable } }
bool arlCore::Mesh::simplify( void ) { #ifndef ANN return false; #else // ANN unsigned int i, j; const unsigned int Size = m_pointList->visibleSize(); const unsigned int Dimension = m_pointList->getDimension(); ANNpointArray ANNPoints = annAllocPts( Size, Dimension ); for( i=0 ; i<m_pointList->size() ; ++i ) for( j=0 ; j<Dimension ; ++j ) ANNPoints[i][j]=(*m_pointList)[i]->get(j); const int BucketSize = 1; ANNkd_tree* ANNtree = new ANNkd_tree( ANNPoints, Size, Dimension, BucketSize, ANN_KD_SL_MIDPT ); const double Epsilon = 1e-8;// Error bound const double SquaredEpsilon = Epsilon*Epsilon; ANNpoint ANNPt = annAllocPt(Dimension); // Query point const unsigned int NbNeighbors = 20; ANNidxArray Nn_idx = new ANNidx[NbNeighbors]; // near neighbor indices ANNdistArray SquaredDists = new ANNdist[NbNeighbors]; // near neighbor distances for( i=0 ; i<m_pointList->size() ; ++i ) if((*m_pointList)[i]->isVisible()) { std::vector<unsigned int> oldIndex; for( j=0 ; j<Dimension; ++j ) ANNPt[j] = (*m_pointList)[i]->get(j); ANNtree->annkSearch( ANNPt, NbNeighbors, Nn_idx, SquaredDists, Epsilon ); // Cherche points les plus proches for( j=0 ; j<NbNeighbors ; ++j ) if(SquaredDists[j]<=SquaredEpsilon) { releasePoint(Nn_idx[j]); oldIndex.push_back(Nn_idx[j]); } replacePointIndex(oldIndex, i); } delete ANNtree; annDeallocPt( ANNPt ); annDeallocPts( ANNPoints ); delete[] Nn_idx; delete[] SquaredDists; annClose(); return true; #endif // ANN }
void SaveAndExit(int param) { StopCapture(); AppendToStateFile(); if(Config::Inst()->GetIsDmEnabled()) { if(system("sudo iptables -F") == -1) { LOG(WARNING, "Failed to flush iptables rules", "Command sudo iptables -F failed"); } if(system("sudo iptables -t nat -F") == -1) { LOG(WARNING, "Failed to flush nat table rules", "Command sudo iptables -t nat -F failed"); } if(system("sudo iptables -t nat -X DOPP") == -1) { LOG(WARNING, "Failed to delete chain DOPP in nat table", "Command sudo iptables -t nat -X DOPP failed"); } if(system(std::string("sudo route del " + Config::Inst()->GetDoppelIp()).c_str()) == -1) { LOG(WARNING, "Failed to delete Doppelganger route", "Command sudo route del " + (string)Config::Inst()->GetDoppelIp() + " failed"); } } if(engine != NULL) { { Lock lock(&shutdownClassificationMutex); shutdownClassification = true; } pthread_cond_signal(&shutdownClassificationCond); pthread_cond_destroy(&shutdownClassificationCond); pthread_mutex_destroy(&shutdownClassificationMutex); delete engine; } annClose(); LOG(ALERT, "Novad is exiting cleanly.", ""); exit(EXIT_SUCCESS); }
// Driver program int main(int argc, char **argv) { int num_points = 0; // Actual number of data points ANNpointArray data_points; // Data points ANNpoint query_point; // Query point ANNidxArray near_neighbor_idx; // Near neighbor indices ANNdistArray near_neighbor_distances;// Near neighbor distances ANNkd_tree * kd_tree_adt; // ADT search structure UserInterface UI; // Read command-line arguments UI.getArgs(argc, argv); // Allocate query point query_point = annAllocPt(UI.dimension); // Allocate data points data_points = annAllocPts(UI.max_points, UI.dimension); // Allocate near neighbor indices near_neighbor_idx = new ANNidx[UI.k]; // Allocate near neighbor distances near_neighbor_distances = new ANNdist[UI.k]; // Echo data points cout << "Data Points: \n"; if (UI.results_out != NULL) *(UI.results_out) << "Data points: \n"; while (num_points < UI.max_points && UI.readPoint(*(UI.data_in), data_points[num_points])) { UI.printPoint(cout, data_points[num_points], num_points); if (UI.results_out != NULL) { UI.printPoint(*(UI.results_out), data_points[num_points], num_points); } num_points++; } // Construct k-d tree abstract data type search structure // Params: data points, number of points, dimension of space kd_tree_adt = new ANNkd_tree(data_points, num_points, UI.dimension); // Echo query point(s) cout << "\n\nQuery points: \n"; if (UI.results_out != NULL) *(UI.results_out) << "\n\nQuery points: \n"; // Read query points while (UI.readPoint(*(UI.query_in), query_point)) { UI.printPoint(cout, query_point, UI.dimension); if (UI.results_out != NULL) { UI.printPoint(*(UI.results_out), query_point, UI.dimension); } // Perform the search // Params: query point, number of near neighbors, nearest neighbors (returned), distance (returned), error bound kd_tree_adt->annkSearch(query_point, UI.k, near_neighbor_idx, near_neighbor_distances, UI.eps); UI.printSummary(cout, &near_neighbor_idx, &near_neighbor_distances); if (UI.results_out != NULL) UI.printSummary(*(UI.results_out), &near_neighbor_idx, &near_neighbor_distances); } // Perform house cleaning tasks delete kd_tree_adt; delete [] near_neighbor_idx; delete [] near_neighbor_distances; annClose(); cin.get(); return EXIT_SUCCESS; }
// cd L:\ann_mwrapper; Untitled2 void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mwSize dims[3]; char command[1024]; int strlen = mxGetN(prhs[0]); strlen = strlen < mxGetM(prhs[0]) ? mxGetN(prhs[0]) : strlen; strlen += 1; mxGetString (prhs[0], command, strlen); // Initialize tree if (nrhs > 0 && !strcmp(command, "createKdTree")) { const mxArray *mxRefPts = prhs[1]; const mxArray *mxOpts = prhs[2]; // parse options AnnBuildOptions opts_build; parse_tree_building_options(mxOpts, opts_build); // construct the tree int d = 0; int n = 0; ANNpointArray *pts = createPointArray(mxRefPts, d, n); ANNkd_tree *kd_tree = createKdTree(d, n, pts[0], opts_build); //mexPrintf("%lld\n", kd_tree); //mexPrintf("dim = %d\n", kd_tree->theDim()); dims[0] = 2; dims[1] = 1; plhs[0] = mxCreateNumericArray(2,dims,mxUINT64_CLASS,mxREAL); ((unsigned long long *)(mxGetData( plhs[0])))[0] = (unsigned long long)kd_tree; ((unsigned long long *)(mxGetData( plhs[0])))[1] = (unsigned long long)pts; // mexPrintf("Creating:\n"); // mexPrintf("Pts: "); // for (int i =0;i<MEX_DEBUG_WND;++i){ // mexPrintf("%x",pts[i]); // } // mexPrintf("\n"); // mexPrintf("kdTree: "); // for (int i =0;i<10;++i){ // mexPrintf("%x",((char *)kd_tree)[i]); // } // mexPrintf("\n"); } // Search else if (nrhs > 0 && !strcmp(command, "performAnnkSearch")) { // take inputs const mxArray *mxQuery = prhs[2]; const mxArray *mxOpts = prhs[3]; // parse options AnnSearchOptions opts_search; parse_search_options(mxOpts, opts_search); // get pointer to tree ANNkd_tree *kd_tree = (ANNkd_tree *)(((unsigned long long *)mxGetData( prhs[1]))[0]); // mexPrintf("%lld\n", kd_tree); // mexPrintf("dim = %d\n", kd_tree->theDim()); // perform the search mxArray *mxInds = NULL; mxArray *mxDists = NULL; // mexPrintf("Pts: "); // for (int i =0;i<MEX_DEBUG_WND;++i){ // mexPrintf("%x",pts[i]); // } // mexPrintf("\n"); // mexPrintf("kdTree: "); // for (int i =0;i<10;++i){ // mexPrintf("%x",((char *)kd_tree)[i]); // } // mexPrintf("\n"); // performAnnkSearch(kd_tree, mxQuery, opts_search, mxInds, mxDists); // set outputs plhs[0] = mxInds; plhs[1] = mxDists; } // Deinitialize tree else if (nrhs > 0 && !strcmp(command, "deleteKdTree")) { ANNkd_tree *kd_tree = (ANNkd_tree *)(((unsigned long long *)mxGetData( prhs[1]))[0]); ANNpointArray *pts = (ANNpointArray *)(((unsigned long long *)mxGetData( prhs[1]))[1]); // mexPrintf("Deleting:\n"); // mexPrintf("Pts: "); // for (int i =0;i<MEX_DEBUG_WND;++i){ // mexPrintf("%x",pts[i]); // } // mexPrintf("\n"); // mexPrintf("kdTree: "); // for (int i =0;i<10;++i){ // mexPrintf("%x",((char *)kd_tree)[i]); // } // mexPrintf("\n"); // release the kd-tree delete kd_tree; annDeallocPts(pts[0]); delete pts; } // Close else if (nrhs > 0 && !strcmp(command, "annClose")) { annClose(); } else { mexPrintf("INVALID COMMAND %s\n", command); return; } }
int main(int argc, char **argv) { if (argc < 2) { std::cout << "usage: knn <pts> [queries] [nn] [epsilon]" << std::endl; exit(1); } int pt_count, dim; ANNpointArray pts = read_points(argv[1], pt_count, dim); ANNkd_tree kt(pts, pt_count, dim); if (argc < 3) return 1; //read queries int q_count; int q_dim; ANNpointArray queries = read_points(argv[2], q_count, q_dim); if (dim != q_dim) { std::cerr << "error: query dim: " << q_dim; std::cerr << " does not match point dim: " << dim << std::endl; exit(1); } //how many nearest neighbours to retrieve int nn = 5; if (argc >= 4) nn = atoi(argv[3]); //read query epsilon double epsilon = 0.0; if (argc == 5) epsilon = atof(argv[4]); //run queries ANNidx *nn_idx = new ANNidx[nn]; ANNdist *dists = new ANNdist[nn]; for (int i = 0; i < q_count; ++i) { kt.annkSearch(queries[i], nn, nn_idx, dists, epsilon); std::cout << "query " << i << ": ("; for (int d = 0; d < dim; ++d) { std::cout << queries[i][d]; if (d + 1 < dim) std::cout << ", "; } std::cout << ")\n"; for (int j = 0; j < nn; ++j) { std::cout << "("; for (int d = 0; d < dim; ++d) { std::cout << pts[nn_idx[j]][d]; if (d + 1 < dim) std::cout << ", "; } std::cout << ") " << dists[j] << "\n"; } } std::cout << "done." << std::endl; delete[] nn_idx; delete[] dists; annClose(); return 0; }
mitk::ContourElement::VertexType* mitk::ContourElement::OptimizedGetVertexAt(const mitk::Point3D &point, float eps) { if( (eps > 0) && (this->m_Vertices->size()>0) ) { int k = 1; int dim = 3; int nPoints = this->m_Vertices->size(); ANNpointArray pointsArray; ANNpoint queryPoint; ANNidxArray indexArray; ANNdistArray distanceArray; ANNkd_tree* kdTree; queryPoint = annAllocPt(dim); pointsArray = annAllocPts(nPoints, dim); indexArray = new ANNidx[k]; distanceArray = new ANNdist[k]; int i = 0; //fill points array with our control points for(VertexIterator it = this->m_Vertices->begin(); it != this->m_Vertices->end(); it++, i++) { mitk::Point3D cur = (*it)->Coordinates; pointsArray[i][0]= cur[0]; pointsArray[i][1]= cur[1]; pointsArray[i][2]= cur[2]; } //create the kd tree kdTree = new ANNkd_tree(pointsArray,nPoints, dim); //fill mitk::Point3D into ANN query point queryPoint[0] = point[0]; queryPoint[1] = point[1]; queryPoint[2] = point[2]; //k nearest neighbour search kdTree->annkSearch(queryPoint, k, indexArray, distanceArray, eps); VertexType* ret = NULL; try { ret = this->m_Vertices->at(indexArray[0]); } catch(std::out_of_range ex) { //ret stays NULL return ret; } //clean up ANN delete [] indexArray; delete [] distanceArray; delete kdTree; annClose(); return ret; } return NULL; }
KNNClassifier::~KNNClassifier() { annDeallocPts(dataPts); delete kdTree; annClose(); }