how to convert velocity map to fluid flow map - python

It may be a very simple question, if you have the answer please share.
Provided a series (say for t0..tn) of the matrices (2D arrays) of velocities in X and Y directions (UX,UY) by means of application of Lattice Boltzmann method (LBM) on the simulation of fluid flow in 2D, the question is how to make an animation of fluid flow.
We should be able to use velocities to find positions of (??) by applying: Position = Velocity x Time. Any ideas of what could be (??).
We think that we could have a same size of velocity matrix of particles for time t0 and find the next position matrix as mentioned above, so to move particles accordingly.
Please share your knowledge!
Is the chosen approach correct?
Any other methods etc etc.
For this problem tips in Python are more than welcome!
Pseudo-codes could be of more help!
To simplify the question the following is the velocity map at time tn, trying to have a fluid flow map based on that, How?

If the initial distribution of your particles is fairly regular (a grid, or uniformly random), you'll find that after a while all the particles tend to cluster together, leaving entire areas of your fluid empty and thus invisible.
I found that a good method is to have short-lived particles (on the order of seconds). When a particle dies, it is respawned in a random position. Also, because each particle traces only a short path, the accuracy of the integration method used doesn't matter so much: a midpoint method or even forward Euler does the job just fine.

Related

Verlet integration angular constraint in 3D

guys! I'm trying to code verlet physics from scratch with Python. I have already done it in two dimensional space and it works as expected. My code contains points and edges, which limit the distance between points. As you know, it's quite easy to achieve it with Verlet integration. And if we want some points to maintain certain angle between each other, we can easily add invisible edge between them and play with it's length.
Now lets imagine I have chain of 10 points in 3D, consecutively connected with edges. I need to maintain a specific angle between first and third point. And I can't figure out the way do this having three rotational axis, because as you can imagine, single invisible edge is not enough in this case. And, of course, adding two more lines from the same points will make no sense.
I also should NOT create invisible edges to non-adjastent points, because if we speak about angle between first and third point, it should not affect directly the middle or the end of the chain.

Drawing animation on torus with python?

I recently worked on a code that allowed to display a simulation of particles' motions in a periodical space. In concrete terms, it resulted in a 2D plot provided with N points (N ~ 10^4) initially gathered at the center, then spread out according to a matching velocity. As it is a periodical space, any points that would go beyond the upper limit is actually brought back to the lower limit, and vice versa. To illustrate, here are two images :
Initial positions
After a certain time
Each points are supposed to travel horizontally, either to the right or to the left (respectively positive or negative velocity).
I programmed it using Python, but now, in the scope of my project, I'd like to simulate the same thing but on a torus. To give you a good glimpse of how it looked like, please take a look at the following pic :
Transformation from a rectangle to a torus
(Imagine my initial 2D plan is the initial rectangle, which I'd like to transform into the final torus).
Therefore, in that case we would see every particle moving on the surface of the torus. The previous 1st picture would correspond to particles gathered on a "single" circus of the torus, and the previous 2nd picture would correspond to the "filling up" the entire surface of the torus.
Since my code for previous simulations was written in Python, I am wondering if I can still use it for this task. If so, I'd like to have some clues about how to do it, and otherwise, what would be the best language to use for this ?
I hope I have been clear. I apologize in advance for some mistakes I could have done with English.

Procedural generated 2D environment

screenshot1
screenshot2
This game has a 2D terrain viewed from a side on perspective. Every time you start a new round, the terrain is different, in a way that it has smooth curves/peaks, but still stays within bounds. Does anyone have an algorithm for the way these terrains/lines are generated?
This is the game link:
https://www.mathsisfun.com/games/tanks.html
Thanks in advance.
Might be that what you want to do is an example of interpolation, finding a curve that goes through a set of given points.
The points could then be randomly selected within your screen area, for example marking acceptable local maximum/minimum points, and a curve of desired smoothness going through these calculated. There are algorithms for all kinds of different curves, but probable simple polynomials would be enough for this.

Smallest circles enclosing points with minimized cost

I am trying to find the smallest circles enclosing points using a hierarchical search (in a tree). I searched a lot and I seem to only find smallest enclosing circle (singular) algorithms online. This is for a university class so I am asking for possible solutions and ideas more than actual code.
My problem is that I have a formula that involves two constants and the radius of a circle to compute its cost and I need to minimise the total cost. This means that for a set of points (x,y), I could find one circle enclosing all points, or multiples circles, each enclosing a part of the points, depending on the cost of each circle.
As an example, if the formulae is 1+2*radius**2, my answer will surely have multiple small circles. All points must be in a circle at the end.
My goal is to use a graph search algorithm like a*, branch and bound or breadth first and build a tree using a state and its possible actions.
I am currently trying to write my possible actions as adding a circle, removing a circle and change a circle's radius. To limit compute time, I decided to only try those actions on positions that are between two points or between two sets of points (where the center of my circles could be). But this algorithm seems to be far from optimal. If you have any ideas, it would really help me.
Thanks anyway for your help.
If the question is unclear, please tell me.
I'm going to focus on finding optimal solutions. You have a lot more options if you're open to approximate solutions, and I'm sure there will be other answers.
I would approach this problem by formulating it as an integer program. Abstractly, the program looks like
variable x_C: 1 if circle C is chosen; 0 if circle C is not chosen
minimize sum_C cost(C) * x_C
subject to
for all points p, sum_{C containing p} x_C >= 1
for all circles C, x_C in {0, 1}.
Now, there are of course infinitely many circles, but assuming that one circle that contains strictly more area than another costs more, there are O(n^3) circles that can reasonably be chosen, where n is the number of points. These are the degenerate circles covering exactly one point; the circles with two points forming a diameter; and the circles that pass through three points. You'll write code to expand the abstract integer program into a concrete one in a format accepted by an integer program solver (e.g., GLPK) and then run the solver.
The size of the integer program is O(n^4), which is prohibitively expensive for your larger instances. To get the cost down, you'll want to do column generation. This is where you'll need to figure out your solver's programmatic interface. You'll be looking for an option that, when solving the linear relaxation of the integer program, calls your code back with the current price of each point and expects an optional circle whose cost is less than the sum of the prices of the points that it encloses.
The naive algorithm to generate columns is still O(n^4), but if you switch to a sweep algorithm, the cost will be O(n^3 log n). Given a pair of points, imagine all of the circles passing by those points. All of the circle centers lie on the perpendicular bisector. For each other point, there is an interval of centers for which the circle encloses this point. Compute all of these event points, sort them, and then process the events in order, updating the current total price of the enclosed points as you go. (Since the circles are closed, process arrivals before departures.)
If you want to push this even further, look into branch and price. The high-level branching variables would be the decision to cover two points with the same circle or not.

Querying of a point is within a mesh maya python api

I'm trying to figure out a way of calculating if a world space point is inside of an arbitrary mesh.
I'm not quite sure of the math on how to calculate it if it's not a cube or sphere.
Any help would be great!
One can use a simple ray tracing trick to test if you are inside or outside of a shape. It turns out that 2D, 3D objects or possibly even higher dimension objects have a neat property. That is if you shoot an arbitrary ray in any direction you are inside the shape if, and only if you hit the boundaries of your shape and odd number of times. No need to know the normal direction or anything. Just know how many intersections you have. This is easy to visualize in 2D, and since 3D is just many 2D slices same applies to 3D too.
figure 1: Shooting a ray from a point in an arbitrary direction produces an odd number of hits if inside and an even if outside, So O1 is inside and O2 is not. As a special case glancing hits need to be tested for curves because they make 2 hits coincide in one place (O3).
figure 2: Meshed surfaces have a better boundary condition as only vertex hits are glancing However most tracing engines ignore glancing hits as totally perpendicular hits (O4) would be problematic so they behave right for purposes of this test. Maya tracer is no exception.
Please note this method does not need the surface to be closed, it works none the less it just closes the gap in direction of the ray and open surfaces can report weird results. But can be acceptable in some cases.
Admittedly ray tracing is pretty heavy operation without acceleration routines, however it becomes quite fast once acceleration is in place. Maya API provides a method for this. Note the accelerator is built first then each subsequent call is much cheaper. Here is a quickly written scaffold without acceleration see docs for MFnMesh for more info on how to accelerate:
import maya.cmds as cmd
import maya.OpenMaya as om
def test_if_inside_mesh(point=(0.0, 0.0, 0.0), dir=(0.0, 0.0, 1.0)):
sel = om.MSelectionList()
dag = om.MDagPath()
#replace torus with arbitrary shape name
sel.add("pTorusShape1")
sel.getDagPath(0,dag)
mesh = om.MFnMesh(dag)
point = om.MFloatPoint(*point)
dir = om.MFloatVector(*dir)
farray = om.MFloatPointArray()
mesh.allIntersections(
point, dir,
None, None,
False, om.MSpace.kWorld,
10000, False,
None, # replace none with a mesh look up accelerator if needed
False,
farray,
None, None,
None, None,
None
)
return farray.length()%2 == 1
#test
cmd.polyTorus()
print test_if_inside_mesh()
print test_if_inside_mesh((1,0,0))
In your specific case this may be overkill. I assume your doing some kind of rejection sampling. It is also possible to build the body out of prisms and randomize with barycentric like coordinates. This has the advantage of never wasting results. But the tracing code is much easier to generally use.
If you're attempting to solve this problem for any mesh, you'll have trouble, because not every arbitrary mesh is closed. If your mesh can be assumed closed and well-formed, then you might have to do something like a 3D flood-fill algorithm to determine whether there's a path to a point that can see outside the object from the point you're testing.
If you're willing to take a looser approach that gives you an approximate answer, and assumes that normals are all uniformly pointed outward, there's a code example on this page, written in MEL, that you might be able to convert to Python.
http://forums.cgsociety.org/archive/index.php/t-747732.html
Mark is correct, there's no guaranteed test that works for open meshes. Also, arbitrary mesh tests are going to be slow and expensive, so try the cheap tests (bounding sphere and or bounding box) first. You can also just tell the user 'sorry, no dice' if you have any open edges on your mesh -- that guarantees there is no solution for the concept of 'inside'
If you want an approximate answer that's better than a bounds test but not as expensive as something like a voxel test, you can use qHull or something similar to generate a convex hull for your mesh and test against the convex mesh. That will not handle serious concavities of meshes that twist inside out, but will catch oddly shaped objects with more grace than a bounds test.
If you really need speed or have complex objects, you probably want to voxelize the object and test the voxel data. This is typically too math-heavy for scripting (see this, for example) and it's not trivial to implement.
All that said, here's a very hacky approximation of voxels using the built-in nParticles:
If you have nParticles (maya 2011 + ) you can try filling your object (nParticles > createNParticles > Fill Object) with particles. You can then distance test your point against the positition of each particle in the particle set. If the distance to any particle is less than or equal to the particles' radius, you're 'inside' to within 1/2 particle radius accuracy. You'll note that some shapes can't be filled by nparticles - those are the kind of shapes you can't test 'insidedness' for anyway.

Categories