Library for generating cubic spline trajectories (not interpolation)? - algorithm

A little background. I have a simulation that uses cubic splines for 1D trajectories. In this context, a cubic spline specifies an object's position, velocity, acceleration, and jerk as a function of time.
If you have:
initial and final values for
position, velocity, acceleration, and
time
constant-value constraints on
the maximum and minimum velocity,
acceleration, and jerk
then there is a unique spline. If you don't specify the final time, but instead want the minimum-time trajectory, then there is also a unique spline.
Actually finding these splines can be a royal pain, though. In the case where time is specified, a spline will consist of up to 7 polynomials, and the knots (transition points between polynomials) aren't known ahead of time.
This is not the usual case of fitting a spline to a set of data, it's creating splines from the boundary conditions and some additional constraints. I've read papers where people have used similar arrangements and have had similar needs, but I've never found any libraries (or even source code) that tackles generating splines of this sort. I've written some code that handles most cases, but it isn't terribly robust or fast. I'm not very worried about it being fast, but more robust would be great.
Are there any libraries that can do this available? Open source code, even if not built as a library? C, C++, Java, or Python preferred, but if it's open source other languages would still be useful as a reference.

There is a boost library for C++ that is open source and might get you half-way there.
It has all the basic building blocks you need I think (Legrendre/Laguerre/Hermite polynomials, root finding, etc...), though it comes short of actually calculating splines.
The library documentation is here so you can check for yourself: http://www.boost.org/doc/libs/1_45_0/libs/math/doc/html/index.html

The problem with splines is that you have to solve simultaneous linear equations to solve the conditions. If your situation has any more information about some of those derivatives, you may be able to use Piecewise Cubic Hermite Interpolation (PCHIP).
For example, instead of defining that jerk must be zero, you could come up with a different constraint, use PCHIP, and solve your problem greedily. Anyway, it's something to remember even if you can't use it this time.
http://www.mathworks.com/moler/interp.pdf

SciPy's interpolation functions might help... Plus you can get the derivatives or integrals of those splines easily... I'm not sure why you say "not interpolation"... It seems to me like that is what you are trying to accomplish.

Related

Fitting a curve while staying on the same side of the points

What are strategies I can use to fit a curve while making sure that I stay on one side of the points? For context, I'm using numpy.polyfit() to find the curve today, but this doesn't satisfy the constraint of staying "inside" a region or on one side.
If I had to take a guess, it sounds like you want your function's output values to be strictly larger or smaller than the datapoints. I would check out scipy's fitters and optimizers and especially scipy's curve_fit. A good fitting library is also lmfit.

Identify Geometric Constructions

I'm looking for some methodology/algorithm to identify geometry constructions doing with compass and straightedge.
In more sophisticated tools, constructing a perpendicular bisector, could be done with a specific tool.
In my case I will get a sequence of lines and arcs (drawn by compass) only, via a computer-based drawing tool. How is it possible to identify that whether there's a perpendicular bisector constructed using that tool? Is there an existing algorithm or methodology for that?
In research literature I found one way of achieving this is to record mouse events and inspecting that (no concrete methodology described).
In my case, I need identify that perpendicular bisector by the sequence of lines and arcs.
PS: perpendicular bisector is one of the constructions I need to identify. There are several others such as angle bisector, Perpendicular across a point on line etc.
Appreciate your answers on this!
If you have a sufficiently advanced description of your construction sequence, you can do randomized proving: take the construction sequence, wriggle some of the input points and check whether the result fits with the angular bisector or whatever, up to small numeric errors. If this is the case for a large number of randomized input positions, you can be reasonably sure that the constructed result is what you think it is.
An SVG description of the resulting construction (as mentioned in some comments) will not be sufficient for this goal, though. At least unless the SVG contains additional data in excess to what the spec requires. If you have an arc in SVG, that doesn't tell you how the arc was constructed.
I know Cinderella does randomized proving internally. If you draw the angle bisector using the built-in tool for it, and then do a ruler-and-compass construction of that same angle bisector, Cinderella will not add a second line, as it can prove internally that the two lines are identical.
I'm currently working on Cinderella internals as part of my job. Actually I'm improving its suitability for certain e-learning environments. So if you have e-learning environments in mind, I suggest you check out Cinderella and its browser-friendly child project CindyJS. The latter doesn't have randomized proving yet, put work towards that goal is underway.

Indefinitely move objects around randomly without collision

I have an application where I need to move a number of objects around on the screen in a random fashion and they can not bump into each other. I'm looking for an algorithm that will allow me to generate the paths that don't create collisions and can continue for an indefinite time (i.e.: the objects keep moving around until a user driven event removes them from the program).
I'm not a game programmer but I think this looks like an AI problem and you guys probably solve it with your eyes closed. From what I've read A* seems to be the recommended 'basic idea' but I don't really want to invest a lot of time into it without some confirmation.
Can anyone shed some light on an approach? Anti-gravity movement maybe?
This is to be implemented on iOS, if that is important
New paths need to be generated at the end of each path
There is no visible 'grid'. Movement is completely free in 2D space
The objects are insects that walk around the screen until they are killed
A* is an algorithm to find the shortest path between a start and a goal configuration (in terms of whatever you define as short: common are e.g. euclidean distance, cost or time, angular distance...). Your insects seem not to have a specific goal, they don't even need a shortest path. I would certainly not go for A*. (By the way, since you are having a dynamic environment, D* would have been an idea - still it's meant to find a path from A to B).
I would tackle the problem as follows:
Random Paths and following them
For the random paths I see two methods. The first would be a simple random walk (click here to see a nice 2D animation with explanations), which can suffer from jittering and doesn't look too nice. The second one needs a little bit more detailed explanations.
For each insect generate four random points around them, maybe starting on a sinusoid. With a spline interpolation generate a smooth curve between those points. Take care of having C1 (in 2D) or C2 (in 3D) continuity. (Suggestion: Hermite splines)
With Catmull-Rom splines you can find your configurations while moving along the curve.
An application of a similar approach can be found in this blog post about procedural racetracks, also a more technical (but still not too technical) explanation can be found in these old slides (pdf) from a computer animations course.
When an insect starts moving, it can constantly move between the second and third point, when you always remove the first and append a new point when the insect reaches the third, thus making that the second point.
If third point is reached
Remove first
Append new point
Recalculate spline
End if
For a smoother curve add more points in total and move somewhere in the middle, the principle stays the same. (Personally I only used this in fixed environments, it should work in dynamic ones as well though.)
This can, if your random point generation is good (maybe you can use an approach similar to the one provided in the above linked blog post, or have a look at algorithms on the PCG Wiki), lead to smooth paths all over the screen.
Avoid other insects
To avoid other insects, three different methods come to my mind.
Bug algorithms
Braitenberg vehicles
An application of potential fields
For the potential fields I recommend reading this paper about dynamic motion planning (pdf). It's from robotics, but fairly easy to apply to your problem as well. You can just use the robots next spline point as the goal and set its velocity to 0 to apply this approach. However, it might be a bit too much for your simple game.
A discussion of Braitenberg vehicles can be found here (pdf). The original idea was more of a technical method (drive towards or away from a light source depending on how your motor is coupled with the photo receptor) and is often used to show how we apply emotional concepts like fear and attraction to other objects. The "fear" behaviour is an approach used for obstacle avoidance in robotics as well.
The third and probably simplest method are bug algorithms (pdf). I always have problems with the boundary following, which is a bit tricky. But to avoid another insect, these algorithms - no matter which one you use (I suggest Bug 1 or Tangent Bug) - should do the trick. They are very simple: Move towards your goal (in this application with the catmull-rom splines) until you have an obstacle in front. If the obstacle is close, change the insect's state to "obstacle avoidance" and run your bug algorithm. If you give both "colliding" insects the same turn direction, they will automatically go around each other and follow their original path.
As a variation you could just let them turn and recalculate a new spline from that point on.
Conclusion
Path finding and random path generation are different things. You have to experiment around what looks best for your insects. A* is definitely meant for finding shortest paths, not for creating random paths and following them.
You cannot plan the trajectories ahead of time for an indefinite duration !
I suggest a simpler approach where you just predict the next collision (knowing the positions and speeds of the objects allows you to tell if they will collide and when), and resolve it by changing the speed or direction of either objects (bounce before objects touch).
Make sure to redo a check for collisions in case you created an even earlier collision !
The real challenge in your case is to efficiently predict collisions among numerous objects, a priori an O(N²) task. You will accelerate that by superimposing a coarse grid on the play field and look at objects in neighboring cells only.
It may also be possible to maintain a list of object pairs that "might interfere in some future" (i.e. considering their distance and relative speed) and keep it updated. Checking that a pair may leave the list is relatively easy; efficiently checking for new pairs needing to enter the list is not.
Look at this and this Which described an AI program to auto - play Mario game.
So in this link, what the author did was using a A* star algorithm to guide Mario Get to the right border of the screen as fast as possible. Avoid being hurt.
So the idea is for each time frame, he will have an Environment which described the current position of other objects in the scene and for each action (up, down left, right and do nothing) , he calculate its cost function and made a decision of the next movement based on this.
Source: http://www.quora.com/What-are-the-coolest-algorithms
For A* you would need a 2D-Grid even if it is not visible. If I get your idea right you could do the following.
Implement a pathfinding (e.g. A*) then just generate random destination points on the screen and calculate the path. Once your insect reaches the destination, generate another destination point/grid-cell and proceed until the insect dies.
As I see it A* would only make sence if you have obstacles on the screen the insect should navigate around, otherwise it would be enough to just calculate a straight vector path and maybe handle collision with other insects/objects.
Note: I implemented A* once, later I found out that Lee's Algorithm
pretty much does the same but was easier to implement.
Consider a Hamiltonian cycle - the idea is a route that visits all the positions on a grid once (and only once). If you construct the cycle in advance (i.e. precalculate it), and set your insects off with some offset between them, they will never collide, simply because the path never intersects itself.
Also, for bonus points, Hamiltonian paths tend to 'wiggle about', and because it's a loop you can predict (and precalculate) the path into the indefinite future.
You can always use the nodes of the grid as knot points for a spline to smooth the movement, or even randomly shift all the points away from their strict 2d grid positions, until you have the desired motion.
Example Hamiltonian cycle from Wikimedia:
On a side note, if you want to generate such a path, consider constructing a loop through many points and just moving the points around in such a manner that they never intersect an existing edge. With some encouragement to move into gaps and away from each other, they should settle into some long, never-intersecting path. Store the result and use for your loop.

SVG convert polygon to curves conversion in Javascript

How can I convert a polygon shape to a curve in JS/SVG?
I have seen this solution: http://jsdraw2d.jsfiction.com/ but this seems to be dealing with VML and not SVG.
Is there something out-of-the-box that can be used to accurately convert a polygon to a path without ANY loss of quality?
When I say path I don't mean a path with >4000 nodes. I mean a path with curves instead of many nodes. Which in turn means reducing the node count since the polygons would be converted into curves.
I assume, that while polygonizing, you sampled points on the curve, and joined them with straight lines.
The reverse process is curve fitting.
You want to do a "Hermite fitting of curve through a set of points". A little search will help you out.
There are more such fitting algorithms. This is maths based and the under the hood solution to what you want. This is also how most such problems are solved.
If you want a quick solution, you would have to find a library that does it for you. i.e take a set of points, and fits a curve through them.
Note: I assume that fitting a curve through more than 4000 nodes is going to be costly. You could try it and see the performance for yourself, as I am not sure how costly would this be. But, I would suggest that if you needed to maintain the accuracy of your boolean operation. You should not have polygonized them at first. It is just redundancy of efforts to lose accuracy only to gain it back. Boolean set operations can be be done, and are done, without polygonizing the curve data.
Links for reference, and demos
http://en.wikipedia.org/wiki/Spline_interpolation
http://www.math.ucla.edu/~baker/java/hoefer/Spline.htm
http://www.math.ucla.edu/~baker/java/hoefer/Lagrange.htm

What does RiBasis which is described in RenderMan mean?

I'm working on a plugin of 3ds Max. In this plugin, I export the geometry information into a .rib file which can be rendered by a RenderMan renderer. When I export a nubrs curve's data into .rib file described by RiBasis and RiCurve. I use the RtBsplineBasis in RiBasis, but I get the wrong result that the rendered curve is short than the result of 3ds Max's renderer. Then I reprint the first and the last control vertex, the curve is long enough, but its shape is a little different.Who can tell me how I get wrong result or what does RiBasis mean? How can get correct RiBasis? Thank u very much!
RiCurve draws a cubic spline. The control points do not uniquely determine the curve; you also need the basis, which is expressed as a 4x4 matrix -- one matrix give the coefficients you need for a B-spline, Bezier, Catmull-Rom, and so on, and of course you can also supply the matrix yourself for some kind of hybrid interpolant that isn't quite one of the standard 3 or 4. The basis determines the character of the spline -- whether the curve is guaranteed to go through the control points or is merely approximating, the degree of continuity, the "tension", and so on.
There is a great discussion in one of the appendices of "The RenderMan Companion," including numeric examples of how different basis matrices affect the interpolation.
It sounds like you requested a B-spline basis, which is approximating (not interpolating) and continuous in both 1st and 2nd derivatives. Maybe that's not what you had in mind. It's hard to tell, since you didn't describe the properties of the spline that you were hoping for.
As an aside, approximating an arbitrary NURBS curve with a nonrational cubic is not always going to give you an exact match. Something else to keep in mind.

Resources