How can I get the index of the Nearest Point when I use CGAL::K_neighbor_search to do the Nearest Neighbor Search? - cgal

I am using CGAL's K_neighbor_search module to do the nearest neighbor search problem. It's nice and easily to use. The example code shows that given a query point, it can find the nearest neighbor point from a set of points as well as the distance. However, I can only get the nearest neighbor point itself. I don't know how to get the index of the point found by the algorithm.
For example, I use the following code,
std::list<Point_d> points;
Tree tree(points.begin(), points.end());
Neighbor_search search(tree, query, N);
for(Neighbor_search::iterator it = search.begin(); it != search.end(); ++it)
{
std::cout << "Point: " << it->first << "\n";
std::cout << "Distance: " << std::sqrt(it->second) << "\n";
}
the result is as follows:
Point: 222 129 161
Distance: 189.307
But how can I get the index of the result point? As for the reason of this question, I want to get the normal of the nearest neighbor point, so I need to reference the point.
Could anybody help me?

If you want to use indices directly in the kd-tree you can look at this example.
Points are sorted in an external vector and the kd-tree uses indices to refer to the points internally store.

Related

How to test if a facet of a periodic c3t3 is on the boundary

I'm trying to extract the boundary facets of a periodic c3t3, i.e. all boundary facets including those at the periodic boundaries. My current approach is to try to iterate trough all the tetrahedra and test one by one its facets with "is_infinite" (see the code snipped bellow), but "is_infinite" is always returning false.
for(Cell_iterator cit = c3t3P.cells_begin(); cit !=c3t3P.cells_end(); ++cit) {
for(int l=0; l<4; ++l) {
const int id = V[cit->vertex(l)];
CGAL_assertion(1 <= id && id <= medit_number_of_vertices);
t[l] = id - 1;
if( tr.is_infinite(cit, l) )
std::cout << "is true!" << std::endl ;//Facet_boundary.push_back(points[t[l]]);
}
}
Here is a way you could go at your problem given the clarification in the comments above:
Start from a point on your surface
Use the locate() function of the periodic triangulation . This gives you a cell and an offset such that the point is in the tetrahedron of this cell translated by the offset parameter.
You can qualify whether a vertex of the periodic triangulation is contained in the interior, on the boundary, or in the exterior of the 3D closed shape using the class Side_of_triangle_mesh.
Walk from cell to cell (using cell->neighbor(0...3)). Note that as you walk, you will eventually reach the border of the internal representation and will need to shift offset when going to its neighboring cell: that's the purpose of the neighbor_offset() function that I mentioned in the comments.
For a given visited cell, qualify the position of its vertices as in (Side_of_triangle_mesh returns on boundary or on bounded side) or out (Side_of_triangle_mesh returns on unbounded side) of the shape. The position canonical position is given by Periodic_triangulation::point(Cell_handle, index) and you can shift it using Periodic_triangulation::construct_point(Point, Offset).
Do not explore the neighbors of a cell whose vertices are all out.
Cells whose vertices are all in are directly in your output.
For cells that have some vertices in and some vertices out, you could create a surface mesh from the tetrahedron (for example with make_tetrahedron) and compute the intersection with the shape using the corefine_and_compute_intersection.

C++ Program that adds positive odd numbers from keyboard, ignores even and stops when negative number or zero are entered - sum odd numbers

So technically I have done what the assignment says because this works:
#include <iostream>
using namespace std;
int main()
{
int number = 0;
int sum = 0;
cout << "Please enter an odd positive integer: " << endl;
cout << "This program will end if number is <= 0 or decimal" << endl;
cin >> number;
while (number > 0)
{
if (number % 2 != 0)
sum = sum + number;
else
cout << "That number was even - please enter odd number \n";
cin >> number;
}
cout << "Sum of odd numbers = " << sum << endl;
return 0;
}
However - it dawned on me that the program quits when someone enters a double or enters a character, rather than just warning that this will happen - I would love to write this in. I have tried using else if statements and I am not getting the desired results. I am not asking for someone to solve this for me per se but if I could just get sent in the right direction. We are currently working on while and for loops and increments (which don't seem to apply here at all)
First off, you'd have to change your number variable to a string to take in "anything", deal with garbage input, and finally convert it to an int if it fit your requirements. This usually isn't too hard, but can get tricky at times. Google is usually your friend here. It's bee a while since I did C++, so I'd have to consult it, too, to get things correct.
And when you say "double", is that the number is 2 digits or is too long to be an int? That little bit of ambiguity is throwing me off. If it's just too big a number being an actual double datatype, the string should help with that, as would a problem a 2 digit number.
And for an increment being useful, you could use sum += number;, depending on your version of C++. Older versions don't allow that, but newer versions do. I'd be surprised of a gcc or other compiler wasn't new enough to have it available, at this point.
Side note
Thank you for not being the "typical homework question". It's good that you are just asking for advice, not for someone to write your code for you.
While I've got you, you should think about reading the How To Ask A Question and Tour pages. The Tour gets you another badge, and the other is just good advice to keep people from downvoting or closing your future questions. You already have a good idea on how to ask a homework question, but reading that page is a good idea, too.
But I digress.
Good luck and I hope I put you on the right path.

CGAL: Access to Results of find_conflicts()

So I am very confused about the find_conflicts function in CGAL. I thought I knew std::pair, and I thought I knew what was going on in find_conflicts(), but for the life of me, I am not sure how to access the results. I thought that the iterator that is passed to find_conflicts would be enough to then access the values directly. (i.e., I want to get at those facets that I put in the "vector facets,") and it appears as if I'm doing that because I can successfully
typedef std::pair<std::vector<Facet>, std::vector<Cell> > FacetAndCell;
* * *
Cell_handle cell = T.locate(curr_point);
std::vector<Facet> facets;
T.find_conflicts(curr_point, cell, std::back_inserter(facets), CGAL::Emptyset_iterator());
CGAL::First_of_pair_property_map<FacetAndCell> my_p_map();
Delaunay::Finite_facets_iterator ff_iter;
std::vector<Facet>::iterator facet_iter;
// Here, what I'm trying to achieve is figuring out which of the facets
// in conflict are finite. I had wanted to use some kind of test like
// "is_infinite()" on the facet at hand, but this isn't available for
// a facet out of context of the triangulation it's part of.
for(facet_iter = facets.begin(); facet_iter != facets.end(); facet_iter++){
for(ff_iter = T.finite_facets_begin(); ff_iter != T.finite_facets_end(); ff_iter++){
// Since I get an error that facet_iter is actually of type pair, I thought this would work, but it doesn't.
// ERROR!
cout << facet_iter->first << endl;
// This works, which is what led me to believe I was comparing one facet to another facet.
/*
if(*facet_iter == *ff_iter){
cout << "Finite facet!" << endl;
break;
}*/
}
}
In summary:
1) Overall, I want to know which facets from the result of find_conflicts() were finite. If there is an easier way to do this, feel free to let me know.
2) Otherwise, the more specific problem here is that I need to get at that vector of facets that results from find_conflicts() and then get at the vertices of each facet. Am I supposed to be working with the returned "pair" of cells and facets or can I access the vector directly, like I'm trying to do?
Help, please, thanks.
For finiteness testing, use is_infinite(). See http://doc.cgal.org/latest/Triangulation_3/classCGAL_1_1Triangulation__3.html#af024721d3ae4b9327ffe442fb828935c
Otherwise, maybe you are confused because the Facet type is a typedef to a pair (unfortunately).
PS: alternatively, you can use Marc Glisse's suggestion in your other question (using locate(midpoint(p, sphere center))). It might be easier. CGAL Using Locate() to Find Cell on Triangulation Surface

How to 'checksum' an array of noisy floating point numbers?

What is a quick and easy way to 'checksum' an array of floating point numbers, while allowing for a specified small amount of inaccuracy?
e.g. I have two algorithms which should (in theory, with infinite precision) output the same array. But they work differently, and so floating point errors will accumulate differently, though the array lengths should be exactly the same. I'd like a quick and easy way to test if the arrays seem to be the same. I could of course compare the numbers pairwise, and report the maximum error; but one algorithm is in C++ and the other is in Mathematica and I don't want the bother of writing out the numbers to a file or pasting them from one system to another. That's why I want a simple checksum.
I could simply add up all the numbers in the array. If the array length is N, and I can tolerate an error of 0.0001 in each number, then I would check if abs(sum1-sum2)<0.0001*N. But this simplistic 'checksum' is not robust, e.g. to an error of +10 in one entry and -10 in another. (And anyway, probability theory says that the error probably grows like sqrt(N), not like N.) Of course, any checksum is a low-dimensional summary of a chunk of data so it will miss some errors, if not most... but simple checksums are nonetheless useful for finding non-malicious bug-type errors.
Or I could create a two-dimensional checksum, [sum(x[n]), sum(abs(x[n]))]. But is the best I can do, i.e. is there a different function I might use that would be "more orthogonal" to the sum(x[n])? And if I used some arbitrary functions, e.g. [sum(f1(x[n])), sum(f2(x[n]))], then how should my 'raw error tolerance' translate into 'checksum error tolerance'?
I'm programming in C++, but I'm happy to see answers in any language.
i have a feeling that what you want may be possible via something like gray codes. if you could translate your values into gray codes and use some kind of checksum that was able to correct n bits you could detect whether or not the two arrays were the same except for n-1 bits of error, right? (each bit of error means a number is "off by one", where the mapping would be such that this was a variation in the least significant digit).
but the exact details are beyond me - particularly for floating point values.
i don't know if it helps, but what gray codes solve is the problem of pathological rounding. rounding sounds like it will solve the problem - a naive solution might round and then checksum. but simple rounding always has pathological cases - for example, if we use floor, then 0.9999999 and 1 are distinct. a gray code approach seems to address that, since neighbouring values are always single bit away, so a bit-based checksum will accurately reflect "distance".
[update:] more exactly, what you want is a checksum that gives an estimate of the hamming distance between your gray-encoded sequences (and the gray encoded part is easy if you just care about 0.0001 since you can multiple everything by 10000 and use integers).
and it seems like such checksums do exist: Any error-correcting code can be used for error detection. A code with minimum Hamming distance, d, can detect up to d − 1 errors in a code word. Using minimum-distance-based error-correcting codes for error detection can be suitable if a strict limit on the minimum number of errors to be detected is desired.
so, just in case it's not clear:
multiple by minimum error to get integers
convert to gray code equivalent
use an error detecting code with a minimum hamming distance larger than the error you can tolerate.
but i am still not sure that's right. you still get the pathological rounding in the conversion from float to integer. so it seems like you need a minimum hamming distance that is 1 + len(data) (worst case, with a rounding error on each value). is that feasible? probably not for large arrays.
maybe ask again with better tags/description now that a general direction is possible? or just add tags now? we need someone who does this for a living. [i added a couple of tags]
I've spent a while looking for a deterministic answer, and been unable to find one. If there is a good answer, it's likely to require heavy-duty mathematical skills (functional analysis).
I'm pretty sure there is no solution based on "discretize in some cunning way, then apply a discrete checksum", e.g. "discretize into strings of 0/1/?, where ? means wildcard". Any discretization will have the property that two floating-point numbers very close to each other can end up with different discrete codes, and then the discrete checksum won't tell us what we want to know.
However, a very simple randomized scheme should work fine. Generate a pseudorandom string S from the alphabet {+1,-1}, and compute csx=sum(X_i*S_i) and csy=sum(Y_i*S_i), where X and Y are my original arrays of floating point numbers. If we model the errors as independent Normal random variables with mean 0, then it's easy to compute the distribution of csx-csy. We could do this for several strings S, and then do a hypothesis test that the mean error is 0. The number of strings S needed for the test is fixed, it doesn't grow linearly in the size of the arrays, so it satisfies my need for a "low-dimensional summary". This method also gives an estimate of the standard deviation of the error, which may be handy.
Try this:
#include <complex>
#include <cmath>
#include <iostream>
// PARAMETERS
const size_t no_freqs = 3;
const double freqs[no_freqs] = {0.05, 0.16, 0.39}; // (for example)
int main() {
std::complex<double> spectral_amplitude[no_freqs];
for (size_t i = 0; i < no_freqs; ++i) spectral_amplitude[i] = 0.0;
size_t n_data = 0;
{
std::complex<double> datum;
while (std::cin >> datum) {
for (size_t i = 0; i < no_freqs; ++i) {
spectral_amplitude[i] += datum * std::exp(
std::complex<double>(0.0, 1.0) * freqs[i] * double(n_data)
);
}
++n_data;
}
}
std::cout << "Fuzzy checksum:\n";
for (size_t i = 0; i < no_freqs; ++i) {
std::cout << real(spectral_amplitude[i]) << "\n";
std::cout << imag(spectral_amplitude[i]) << "\n";
}
std::cout << "\n";
return 0;
}
It returns just a few, arbitrary points of a Fourier transform of the entire data set. These make a fuzzy checksum, so to speak.
How about computing a standard integer checksum on the data obtained by zeroing the least significant digits of the data, the ones that you don't care about?

How to do numerical integration with quantum harmonic oscillator wavefunction?

How to do numerical integration (what numerical method, and what tricks to use) for one-dimensional integration over infinite range, where one or more functions in the integrand are 1d quantum harmonic oscillator wave functions. Among others I want to calculate matrix elements of some function in the harmonic oscillator basis:
phin(x) = Nn Hn(x) exp(-x2/2)
where Hn(x) is Hermite polynomial
Vm,n = \int_{-infinity}^{infinity} phim(x) V(x) phin(x) dx
Also in the case where there are quantum harmonic wavefunctions with different widths.
The problem is that wavefunctions phin(x) have oscillatory behaviour, which is a problem for large n, and algorithm like adaptive Gauss-Kronrod quadrature from GSL (GNU Scientific Library) take long to calculate, and have large errors.
An incomplete answer, since I'm a little short on time at the moment; if others can't complete the picture, I can supply more details later.
Apply orthogonality of the wavefunctions whenever and wherever possible. This should significantly cut down the amount of computation.
Do analytically whatever you can. Lift constants, split integrals by parts, whatever. Isolate the region of interest; most wavefunctions are band-limited, and reducing the area of interest will do a lot to save work.
For the quadrature itself, you probably want to split the wavefunctions into three pieces and integrate each separately: the oscillatory bit in the center plus the exponentially-decaying tails on either side. If the wavefunction is odd, you get lucky and the tails will cancel each other, meaning you only have to worry about the center. For even wavefunctions, you only have to integrate one and double it (hooray for symmetry!). Otherwise, integrate the tails using a high order Gauss-Laguerre quadrature rule. You might have to calculate the rules yourself; I don't know if tables list good Gauss-Laguerre rules, as they're not used too often. You probably also want to check the error behavior as the number of nodes in the rule goes up; it's been a long time since I used Gauss-Laguerre rules and I don't remember if they exhibit Runge's phenomenon. Integrate the center part using whatever method you like; Gauss-Kronrod is a solid choice, of course, but there's also Fejer quadrature (which sometimes scales better to high numbers of nodes, which might work nicer on an oscillatory integrand) and even the trapezoidal rule (which exhibits stunning accuracy with certain oscillatory functions). Pick one and try it out; if results are poor, give another method a shot.
Hardest question ever on SO? Hardly :)
I'd recommend a few other things:
Try transforming the function onto a finite domain to make the integration more manageable.
Use symmetry where possible - break it up into the sum of two integrals from negative infinity to zero and zero to infinity and see if the function is symmetry or anti-symmetric. It could make your computing easier.
Look into Gauss-Laguerre quadrature and see if it can help you.
The WKB approximation?
I am not going to explain or qualify any of this right now. This code is written as is and probably incorrect. I am not even sure if it is the code I was looking for, I just remember that years ago I did this problem and upon searching my archives I found this. You will need to plot the output yourself, some instruction is provided. I will say that the integration over infinite range is a problem that I addressed and upon execution of the code it states the round off error at 'infinity' (which numerically just means large).
// compile g++ base.cc -lm
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <math.h>
using namespace std;
int main ()
{
double xmax,dfx,dx,x,hbar,k,dE,E,E_0,m,psi_0,psi_1,psi_2;
double w,num;
int n,temp,parity,order;
double last;
double propogator(double E,int parity);
double eigen(double E,int parity);
double f(double x, double psi, double dpsi);
double g(double x, double psi, double dpsi);
double rk4(double x, double psi, double dpsi, double E);
ofstream datas ("test.dat");
E_0= 1.602189*pow(10.0,-19.0);// ev joules conversion
dE=E_0*.001;
//w^2=k/m v=1/2 k x^2 V=??? = E_0/xmax x^2 k-->
//w=sqrt( (2*E_0)/(m*xmax) );
//E=(0+.5)*hbar*w;
cout << "Enter what energy level your looking for, as an (0,1,2...) INTEGER: ";
cin >> order;
E=0;
for (n=0; n<=order; n++)
{
parity=0;
//if its even parity is 1 (true)
temp=n;
if ( (n%2)==0 ) {parity=1; }
cout << "Energy " << n << " has these parameters: ";
E=eigen(E,parity);
if (n==order)
{
propogator(E,parity);
cout <<" The postive values of the wave function were written to sho.dat \n";
cout <<" In order to plot the data should be reflected about the y-axis \n";
cout <<" evenly for even energy levels and oddly for odd energy levels\n";
}
E=E+dE;
}
}
double propogator(double E,int parity)
{
ofstream datas ("sho.dat") ;
double hbar =1.054*pow(10.0,-34.0);
double m =9.109534*pow(10.0,-31.0);
double E_0= 1.602189*pow(10.0,-19.0);
double dx =pow(10.0,-10);
double xmax= 100*pow(10.0,-10.0)+dx;
double dE=E_0*.001;
double last=1;
double x=dx;
double psi_2=0.0;
double psi_0=0.0;
double psi_1=1.0;
// cout <<parity << " parity passsed \n";
psi_0=0.0;
psi_1=1.0;
if (parity==1)
{
psi_0=1.0;
psi_1=m*(1.0/(hbar*hbar))* dx*dx*(0-E)+1 ;
}
do
{
datas << x << "\t" << psi_0 << "\n";
psi_2=(2.0*m*(dx/hbar)*(dx/hbar)*(E_0*(x/xmax)*(x/xmax)-E)+2.0)*psi_1-psi_0;
//cout << psi_1 << "=psi_1\n";
psi_0=psi_1;
psi_1=psi_2;
x=x+dx;
} while ( x<= xmax);
//I return 666 as a dummy value sometimes to check the function has run
return 666;
}
double eigen(double E,int parity)
{
double hbar =1.054*pow(10.0,-34.0);
double m =9.109534*pow(10.0,-31.0);
double E_0= 1.602189*pow(10.0,-19.0);
double dx =pow(10.0,-10);
double xmax= 100*pow(10.0,-10.0)+dx;
double dE=E_0*.001;
double last=1;
double x=dx;
double psi_2=0.0;
double psi_0=0.0;
double psi_1=1.0;
do
{
psi_0=0.0;
psi_1=1.0;
if (parity==1)
{double psi_0=1.0; double psi_1=m*(1.0/(hbar*hbar))* dx*dx*(0-E)+1 ;}
x=dx;
do
{
psi_2=(2.0*m*(dx/hbar)*(dx/hbar)*(E_0*(x/xmax)*(x/xmax)-E)+2.0)*psi_1-psi_0;
psi_0=psi_1;
psi_1=psi_2;
x=x+dx;
} while ( x<= xmax);
if ( sqrt(psi_2*psi_2)<=1.0*pow(10.0,-3.0))
{
cout << E << " is an eigen energy and " << psi_2 << " is psi of 'infinity' \n";
return E;
}
else
{
if ( (last >0.0 && psi_2<0.0) ||( psi_2>0.0 && last<0.0) )
{
E=E-dE;
dE=dE/10.0;
}
}
last=psi_2;
E=E+dE;
} while (E<=E_0);
}
If this code seems correct, wrong, interesting or you do have specific questions ask and I will answer them.
I am a student majoring in physics, and I also encountered the problem. These days I keep thinking about this question and get my own answer. I think it may help you solve this question.
1.In gsl, there are functions can help you integrate the oscillatory function--qawo & qawf. Maybe you can set a value, a. And the integration can be separated into tow parts, [0,a] and [a,pos_infinity]. In the first interval, you can use any gsl integration function you want, and in the second interval, you can use qawo or qawf.
2.Or you can integrate the function to a upper limit, b, that is integrated in [0,b]. So the integration can be calculated using a gauss legendry method, and this is provided in gsl. Although there maybe some difference between the real value and the computed value, but if you set b properly, the difference can be neglected. As long as the difference is less than the accuracy you want. And this method using the gsl function is only called once and can use many times, because the return value is point and its corresponding weight, and integration is only the sum of f(xi)*wi, for more details you can search gauss legendre quadrature on wikipedia. Multiple and addition operation is much faster than integration.
3.There is also a function which can calculate the infinity area integration--qagi, you can search it in the gsl-user's guide. But this is called everytime you need to calculate the integration, and this may cause some time consuming, but I'm not sure how long will it use in you program.
I suggest NO.2 choice I offered.
If you are going to work with Harmonic oscillator functions less than n = 100 you might want to try:
http://www.mymathlib.com/quadrature/gauss_hermite.html
The program computes an integral via gauss-hermite quadrature with 100 zeroes and weights (the zeroes of H_100). Once you go over Hermite_100 the integrals are not as accurate.
Using this integration method I wrote a program calculating exactly what you want to calculate and it works fairly well. Also, there might be a way to go beyond n=100 by using the asymptotic form of the Hermite-polynomial zeroes but I haven't looked into it.