Value interpolation in 2d from scattered data [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
I'm looking for a way to interpolate values from some 2D scattered data. I have a 3d points that represent a terrain from which I want to interpolate intermediate points. For input (X,Y) coordinates I need Z (height) value.
This article on wikipedia may also help you understand my wishes. There is a library in matlab called triscateredinterp that I think it does what I want.
What is a lightweight way to accomplish this interpolation in C++?

I don't think you need 3D interpolation (triscateredinterp). You have data based on 2D inputs; the 3rd dimension is your output. If I understand correctly you want to provide a point in 2D (something between the original points, and interpolate the value.
Light weight? nearest neighbor!; then bi-linear interpolation; then bi-cubic (and others). The first is simple, the others require an increasing amount of math.
Bi-linear: For each point to be interpolated, find the nearest 3 points to your X and Y:
lat long Altitude
X1 Y1 A1
X2 Y2 A2
X3 Y3 A3
Make these matrices:
X1 Y1 1 A1
X = X2 Y2 1 Y = A2
X3 Y3 1 A3
B is the interpolation coefficients we will calculate for those three nearest points (and can be re-used for all points in the area)
B1
B = B2
B3
The matrix equation is: X*B = Y
You could use brut force:
Multiply both sides by XT: XT*X*B = XT*Y
Take the inverse of XT*X: B = (XT*X)^-1 *XT*Y.
Yes 3x3 matrix inversion. Tying this back to a C++ question, you might use Boost for your matrix operations.
Here is another similar C++ question: Solving a system of equations programmably?
One problem that can arise from the bi-linear technique is that as your interpolated point becomes closer to a different set of 3 values you can get some jumps (how would you interpolate 4 points in a saddle configuration?)

One good method for scattered points is Natural Neighbor Interpolation.
You can check the implementation available in CGAL for example : http://doc.cgal.org/latest/Interpolation/index.html

Related

Generating normal distribution weighing constants in a range [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have some results whose relevance decreases with distance. I want to weight the result array elements with constants whose distribution is close to normal or folded normal. At start I want to generate an array with N constants starting from 1 to 0.01 by a function.
The result should be something like the following, ending with a number close to 0.01.
const double normalDistWeight[] = {
1.000, 0.997, 0.994, 0.989, 0.984, 0.977, 0.970, 0.961, 0.951, 0.939,
0.926, 0.910, 0.893, 0.874, 0.853, 0.830, 0.805, 0.778, 0.750, 0.719,
0.687, 0.654, 0.619, 0.584, 0.548, 0.512, 0.476, 0.440, 0.405, 0.370,
0.337, 0.305, 0.274, 0.246, 0.219, 0.194, 0.171, 0.150, 0.131, 0.114,
0.098, 0.085, 0.073, 0.063, 0.054, 0.047, 0.040, 0.035, 0.030, 0.027
};
Unfortunately I can't use any third party libraries or C++11 features, only plain C++.
Edit: Oh, I was over-thinking it... It's just a simple Gaussian error, so exp(-x^2) should work.
It appears to me that all you want is an array of values of the Gaussian function corresponding to uniformly spaced points on the positive half-axis, up to a point where the value is about 0.01.
This is straight-forward. The Gaussian function is f(x) = exp(−x2), like this:
In the chosen expression, we already have f(0) = 1, so all that remains is to find the final point x where we have f(x) = 0.01. Invert: x = √−log(0.01) ≈ 2.15.
So all you need to do is evaluate f on uniformly spaced points on the interval [0, 2.15].

Least Squares Solution of Overdetermined Linear Algebraic Equation Ax = By

I have a linear algebraic equation of the form Ax=By. Where A is a matrix of 6x5, x is vector of size 5, B a matrix of 6x6 and y vector of size 6. A, B and y are known variables and their values are accessed in real time coming from the sensors. x is unknown and has to find. One solution is to find Least Square Estimation that is x = [(A^T*A)^-1]*(A^T)B*y. This is conventional solution of linear algebraic equations. I used Eigen QR Decomposition to solve this as below
matrixA = getMatrixA();
matrixB = getMatrixB();
vectorY = getVectorY();
//LSE Solution
Eigen::ColPivHouseholderQR<Eigen::MatrixXd> dec1(matrixA);
vectorX = dec1.solve(matrixB*vectorY);//
Everything is fine until now. But when I check the errore = Ax-By, its not zero always. Error is not very big but even not ignorable. Is there any other type of decomposition which is more reliable? I have gone through one of the page but could not understand the meaning or how to implement this. Below are lines from the reference how to solve the problem. Could anybody suggest me how to implement this?
The solution of such equations Ax = Byis obtained by forming the error vector e = Ax-By and the finding the unknown vector x that minimizes the weighted error (e^T*W*e), where W is a weighting matrix. For simplicity, this weighting matrix is chosen to be of the form W = K*S, where S is a constant diagonal scaling matrix, and K is scalar weight. Hence the solution to the equation becomes
x = [(A^T*W*A)^-1]*(A^T)*W*B*y
I did not understand how to form the matrix W.
Your statement " But when I check the error e = Ax-By, its not zero always. " almost always will be true, regardless of your technique, or what weighting you choose. When you have an over-described system, you are basically trying to fit a straight line to a slew of points. Unless, by chance, all the points can be placed exactly on a single perfectly straight line, there will be some error. So no matter what technique you use to choose the line, (weights and so on) you will always have some error if the points are not colinear. The alternative would be to use some kind of spline, or in higher dimensions to allow for warping. In those cases, you can choose to fit all the points exactly to a more complicated shape, and hence result with 0 error.
So the choice of a weight matrix simply changes which straight line you will use by giving each point a slightly different weight. So it will not ever completely remove the error. But if you had a few particular points that you care more about than the others, you can give the error on those points higher weight when choosing the least square error fit.
For spline fitting see:
http://en.wikipedia.org/wiki/Spline_interpolation
For the really nicest spline curve interpolation you can use Centripital Catmull-Rom, which in addition to finding a curve to fit all the points, will prevent unnecessary loops and self intersections that can sometimes come up during abrupt changes in the data direction.
Catmull-rom curve with no cusps and no self-intersections

Computing slope in cusps in C++

it's been a while since I've handled some math stuff and I'm a bit rusty, please be nice if I ask a stupid question.
Problem: I have n couples of lines, which are saved in memory as an array of 2D points, therefore no explicit functions. I have to check if the lines on couples are parallel, and this is a pretty easy task because it's sufficient to check if their derivatives are the same.
To do this in an algorithm, I have to check the slope of the line between two points of the function (which I have) and since I don't need an extreme accuracy, I can use the easy formula:
m = (y2-y1)/(x2-x1)
But obviously this lead me to the big problem of x2 = x1. I can't give a default value for this case... how can I workaround it?
Another way to compare slopes in 2D is the following:
m1 = (y2-y1)/(x2-x1)
m2 = (y4-y3)/(x4-x3)
as m1 = m2
(y2-y1)*(x4-x3) = (y4-y3)*(x2-x1) if lines are parallel
This doesn't give divide by zero & is more efficient as it avoids floating point division.

OpenGL: Draw line with point and directon vector [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I had seen OpenGL statement to draw a line using two points. However, my requirement is to draw a line using the following detail
a point on a line
Direction Vector
Im developing function in c++ using openGL library.
Any help is most appreciated.
The answer depends on the semantics of what you've termed a direction vector.
In the computer graphics context I would normally take that term to mean a unit vector facing in the specified direction. Whereas in a mathematics context you might simply mean the relative vector that results from subtracting the two points' coordinates.
[Using P1 and P2 to represent the required two points, and V for the vector].
In the former case, you also need a specify a length for the vector, so you'll need:
P2 = P1 + n * V
whereas in the latter case, it's just trivially
P2 = P1 + V
Just make that two-point line a very long one, say 10000 to each direction from your point-on-a-line:
void drawLinePointDirection(Point P, Vector D) {
Point A = P + 10000*D;
Point B = P - 10000*D
drawLineTwoPoints(A, B);
}
assuming D is unit length.

Solving floating-point rounding issues C++

I develop a scientific application (simulation of chromosomes moving in a cell nucleus). The chromosomes are divided in small fragments that rotate around a random axis using 4x4 rotation matrices.
The problem is that the simulation performs hundreds of billions of rotations, therefore the floating-point rounding errors stack up and grow exponentially, so the fragments tend to "float away" and detach from the rest of the chromosome as time passes.
I use double precision with C++. The soft runs on CPU for the moment but will be ported for CUDA, and simulations can last for 1 month at most.
I have no idea how I could somehow renormalize the chromosome, because all fragments are chained together (you can see it as a doubly linked-list), but I think that would be the best idea, if possible.
Do you have any suggestions ? I feel a bit lost.
Thank you very much,
H.
EDIT:
Added a simplified sample code.
You can assume all matrix math are classical implementations.
// Rotate 1000000 times
for (int i = 0; i < 1000000; ++i)
{
// Pick a random section start
int istart = rand() % chromosome->length;
// Pick the end 20 segments further (cyclic)
int iend = (istart + 20) % chromosome->length;
// Build rotation axis
Vector4 axis = chromosome->segments[istart].position - chromosome->segments[iend].position;
axis.normalize();
// Build rotation matrix and translation vector
Matrix4 rotm(axis, rand() / float(RAND_MAX));
Vector4 oldpos = chromosome->segments[istart].position;
// Rotate each segment between istart and iend using rotm
for (int j = (istart + 1) % chromosome->length; j != iend; ++j, j %= chromosome->length)
{
chromosome->segments[j].position -= oldpos;
chromosome->segments[j].position.transform(rotm);
chromosome->segments[j].position += oldpos;
}
}
You need to find some constraint for your system and work to keep that within some reasonable bounds. I've done a bunch of molecular collision simulations and in those systems the total energy is conserved, so every step I double check the total energy of the system and if it varies by some threshold, then I know that my time step was poorly chosen (too big or too small) and I pick a new time step and rerun it. That way I can keep track of what's happening to the system in real time.
For this simulation, I don't know what conserved quantity you have, but if you have one, you can try to keep that constant. Remember, making your time step smaller doesn't always increase the accuracy, you need to optimize the step size with the amount of precision you have. I've had numerical simulations run for weeks of CPU time and conserved quantities were always within 1 part in 10^8, so it is possible, you just need to play around some.
Also, as Tomalak said, maybe try to always reference your system to the start time rather than to the previous step. So rather than always moving your chromosomes keep the chromosomes at their start place and store with them a transformation matrix that gets you to the current location. When you compute your new rotation, just modify the transformation matrix. It may seem silly, but sometimes this works well because the errors average out to 0.
For example, lets say I have a particle that sits at (x,y) and every step I calculate (dx, dy) and move the particle. The step-wise way would do this
t0 (x0,y0)
t1 (x0,y0) + (dx,dy) -> (x1, y1)
t2 (x1,y1) + (dx,dy) -> (x2, y2)
t3 (x2,y2) + (dx,dy) -> (x3, y3)
t4 (x3,30) + (dx,dy) -> (x4, y4)
...
If you always reference to t0, you could do this
t0 (x0, y0) (0, 0)
t1 (x0, y0) (0, 0) + (dx, dy) -> (x0, y0) (dx1, dy1)
t2 (x0, y0) (dx1, dy1) + (dx, dy) -> (x0, y0) (dx2, dy2)
t3 (x0, y0) (dx2, dy2) + (dx, dy) -> (x0, y0) (dx3, dy3)
So at any time, tn, to get your real position you have to do (x0, y0) + (dxn, dyn)
Now for simple translation like my example, you're probably not going to win very much. But for rotation, this can be a life saver. Just keep a matrix with the Euler angles associated with each chromosome and update that rather than the actual position of the chromosome. At least this way they won't float away.
Write your formulae so that the data for timestep T does not derive solely from the floating-point data in timestep T-1. Try to ensure that the production of floating-point errors is limited to a single timestep.
It's hard to say anything more specific here without a more specific problem to solve.
The problem description is rather vague, so here are some rather vague suggestions.
Option 1:
Find some set of constraints such that (1) they should always hold, (2) if they fail, but only just, it's easy to tweak the system so that they do, (3) if they do all hold then your simulation isn't going badly crazy, and (4) when the system starts to go crazy the constraints start failing but only slightly. For instance, perhaps the distance between adjacent bits of chromosome should be at most d, for some d, and if a few of the distances are just slightly greater than d then you can (e.g.) walk along the chromosome from one end, fixing up any distances that are too big by moving the next fragment towards its predecessor, along with all its successors. Or something.
Then check the constraints often enough to be sure that any violation will still be small when caught; and when you catch a violation, fix things up. (You should probably arrange that when you fix things up, you "more than satisfy" the constraints.)
If it's cheap to check the constraints all the time, then of course you can do that. (Doing so may also enable you to do the fixup more cheaply, e.g. if it means that any violations are always tiny.)
Option 2:
Find a new way of describing the state of the system that makes it impossible for the problem to arise. For instance, maybe (I doubt this) you can just store a rotation matrix for each adjacent pair of fragments, and force it always to be an orthogonal matrix, and then let the positions of the fragments be implicitly determined by those rotation matrices.
Option 3:
Instead of thinking of your constraints as constraints, supply some small "restoring forces" so that when something gets out of line it tends to get pulled back towards the way it should be. Take care that when nothing is wrong the restoring forces are zero or at least very negligible, so that they don't perturb your results more badly than the original numeric errors did.
I think it depends on the compiler you are using.
Visual Studio compiler support the /fp switch which tells the behavior of the floating point operations
you can read more about it. Basically, /fp:strict is the harshest mode
I guess it depends on the required precision, but you could use 'integer' based floating point numbers. With this approach, you use an integer and provide your own offset for the number of decimals.
For example, with a precision of 4 decimal points, you would have
float value -> int value
1.0000 -> 10000
1.0001 -> 10001
0.9999 -> 09999
You have to be careful when you do your multiply and divide and be careful when you apply your precision offsets. Other wise you can quickly get overflow errors.
1.0001 * 1.0001 becomes 10001 * 10001 / 10000
If I read this code correctly, at no time is the distance between any two adjacent chromosome segments supposed to change. In that case, before the main loop compute the distance between each pair of adjacent points, and after the main loop, move each point if necessary to have the proper distance from the previous point.
You may need to enforce this constraint several times during the main loop, depending on circumstances.
Basically, you need to avoid the accumulation of error from these (inexact) matrix operators and there are two major ways of doing so in most applications.
Instead of writing the position as some initial position operated on many times, you can write out what the operator would be explicitly after N operations. For instance, imagine you had a position x and you were adding a value e (that you couldn't represent exactly.) Much better than computing x += e; a large amount of times would be to compute x + EN; where EN is some more accurate way of representing what happens with the operation after N times. You should think whether you have some way of representing the action of many rotations more accurately.
Slightly more artificial is to take your newly found point and project off any discrepancies from the expected radius from your center of rotation. This will guarantee that it doesn't drift off (but won't necessarily guarantee that the rotation angle is accurate.)