center-of-gravity class for a Java program - java

I will probably have to implement a center-of-gravity class but I will ask help in seeking such a Java class before I do. I suspect this has been implemented by others as part of a math library.
In a space of n-dimensions, suppose each dimension is discrete. So for example in 3 dimensions, you can have an X dimension with a range of [0..a]. You also have a Y dimension with a range of [0..b] and a Z dimension with a range of [0..c]. The implementation should be general so that the number of dimensions can be greater than 3 and also generally a not equal to b where a and b are the maximum coordinates of their respective dimensions.
Each point in the space is a double precision float (non-negative).
Find the coordinate of the center-of-gravity.

If you use a physics engine, you can easily get the centre of gravity -- try JBullet :) The centre of mass which you can get with the API is essentially the same thing, but with a slight difference:
The term center of mass is often used interchangeably with center of
gravity, but they are physically different concepts. They happen to
coincide in a uniform gravitational field, but where gravity is not
uniform, center of gravity refers to the mean location of the
gravitational force acting on a body. This results in small but
measurable gravitational torque that must be accounted for in the
operation of artificial satellites.
http://www.continuousphysics.com/Bullet/BulletFull/classbtRigidBody.html

Related

Moving circles elastic collision

I'm developing a very simple physical engine.
I have to calculate the final speed of a circle in an elastic collision against another circle. Each circle has a specific mass, radius and speed.
In order to calculate x and y speed I solve a system with conservation on momentum and conservation of kinetic energy equations.
By the way these equations don't consider the "shape" of circles.
So I calculate the rebound angle by finding the tangent where 2 circles intersect.
Now I have 2 different final speeds directions: the one calculated with momentum law and the one calculated with rebound.
I don't know how to combine the 2 speeds to get the final one
You'll need to calculate the speed in both the X and the Y direction.
Basically, what you do is calculate the results of the x component of the collision, the results of the collision in the y direction, and then combine them to find the resultant angles and speeds.
This is a common AP physics question, so you'll find lots of writeups on the internet about how to do it. This one looks like it should work for you:
http://spiff.rit.edu/classes/phys311.old/lectures/coll2d/coll2d.html
The solution I found is to consider normal and tangential components of my 2 circles velocities, and not their X and Y components.
This way I can apply law of conservation of momentum related to tangent and normal, and at the same time it considers the geometry of circles too.
The last part of this tutorial is very helpful, even if I used a different algorithm, with some different logics: https://www.youtube.com/watch?v=LPzyNOHY3A4

Global Raster over GPS Data

i want to build a global raster over all GPS coordinates.
The cells should be like 20x20 metres...
I want to write an java application and 'work with'/adjust that raster later on.
For example to get the cell for a single gps coordinate or maybe even combine two cells to a bigger one (not necessary).
Can anyone give me an advice for an API or something else that could help me?
As I already answered to a similar question, you cannot create a raster expressed in meters, without prior transforming all coordinates to a meter based x,y (= cartesian) coordinate system.
The GPS coordinates are spherical ones, the cell sizes (especially the y or latitudinal span) would vary from cell to cell, when going North or South.
So either express your raster size in decimal degrees (use an equivalent of your desired with (20m) expressed in meters at center of your area of interest).
Note: The Earth circumfence = 40.000 km, so 40.000 / 360 degrees give 111.111 km as length related to 1 degrees; use this factor to calculate the number of degrees related to 20m.
Or you transform all coordinates to UTM.
Having them in UTM you can then implement a raster expressed in meters.
Difficuties for UTM apporach: This projection is only valid at a longitudinal span of 3 degrees, you will get major problems when the location have to croiss this 3 degree limit.
There is no API for that, that I know, but you can implement that using a 2 dimensional array. (There are APIs for transfroming a lat/lon coordinate to UTM)
If the area of interest is larger then one country this approach may not work (well). The array could be to big.
In that case this task gets more complex, you would need a spatial index, like a quadtree, to limit the number of raster elements, by having an adaptive behaviour for dense locations.

How to fix circles overlap in collision response?

Since in the digital world a real collision almost never happens, we will always have a situation where the "colliding" balls overlap.
How to put back balls in situation where they collide perfectly without overlap?
I would solve this problem with a posteriori approach (in two dimensions).
In short I have to solve this equation for t:
Where:
is a number that answers to the question: how many frames ago
did the collision happen perfectly?
is the center of the first ball
is the center of the second ball
and are their velocities.
but the solution from WolframAlpha is too complicated (I changed the name of the velocities but essentially does not change anything).
It looks complicated because it's the full solution, not just the simplified polynomial form of it. Multiply everything out and gather the constant, t, and t^2 terms, and you'll find that it becomes just at^2 + bt + c = 0. From there you can just use the quadratic formula.
Also, if you want to keep things simple, do them with vector math. There's no reason here to separate out the x and y coordinates; vector addition and dot products are all you need.
Finally, all that matters is the relative position and relative velocity. Pretend one circle is at the origin and stationary, and apply the difference to the other ball. That doesn't change the answer, but it does reduce the number of variables you're wrangling.

Particle Swarm Optimization

I'm using Particle Swarm Optimization(PSO) in java. I am having little knowledge about what we do. Since, I am applying for multiple sequence alignment in bioinformatics.
We need to find position and velocity for aligning those sequences. I need detailed explanation and references about PSO and the need for calculating velocity and position in PSO. If possible I need simple example explaining PSO in java. Actually, I need to understand how it optimizes a problem.
public class Position {
private double x;
private double y;
public Position(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
}
Here is the class for representing the position of the particle with getters and setters
Like wise other classes are available here
Particle Swarm Optimization:
randomly initialize a set of particles at random positions in the
search space;
evaluate all positions and update the global best
position and the personal best positions;
update each velocity
based on the relative position of the global best position, the
current velocity of the particle, the personal best position of the
particle and some random vector;
goto 2.
General Overview
Particle Swarm Optimization (PSO) is a population-based, stochastic search method. The position of each individual or particle in the population represents a possible solution to the optimization problem.
The goodness/score of a given position in the search space is measured by the objective function, which is the function being optimized.
The particles move through the search space in search of the optimal solution.
The way in which the particles move through the search is where the magic happens. Assuming that you're using the inertia weight model, this is governed by three different factors: the inertia component, the social component and the cognitive component.
The inertia component essentially introduces a form of momentum so that the particle's movement isn't too erratic from one iteration to the next. The cognitive component allows a particle's memory of where it has previously found good solutions to influence its movement direction. The social component allows the knowledge of other swarm members (i.e. where other members of the swarm have found good solutions) to influence a particle's movement.
The Update Equations
At iteration t a given particle's position is denoted by x(t). Its new position for the next iteration is calculated according to:
x(t+1) = x(t) + v(t+1)
where v(t+1) denotes the particle's velocity for the next iteration. Note that each of the values above are vectors. The length of these vectors will be equal to the problem dimensionality/the number of input variables to the objective function. (Apologies for my terrible notation; I don't have enough reputation to post pretty equations). The particle's velocity is calculated according to:
v(t+1) = w*v(t) + c1*r1*(pBest(t) - x(t)) + c2*r2*(gBest(t) - x(t))
The three different components described previously (inertia, cognitive and social) are each represented by one of the three terms in the equation above.
w is called the inertia weight and regulates the effect of the momentum component. c1 and c2 are the cognitive and social acceleration coefficients and they regulate the importance of the cognitive and social components (respectively). r1 and r2 are vectors of random numbers (sampled from a unifrom distribution between 0 and 1) that are used to scale each component of the difference vectors.
The first difference vector (pBest(t) - x(t)) allows the particle to move towards its personal best/pBest - the best position that the particle has encountered thus far. (In order to implement the algorithm, it is thus necessary for a particle to examine every position it encounters and save it if it is the best so far).
The second difference vector (gBest(t) - x(t)) allows the particle to use information from other particles in the swarm. In this expression, gBest(t) denotes the best position found by the swarm thus far. (So for implementation, after every iteration, the scores of all the particles should be examined so that the very best one can be saved for future use).
The particles move around the search space based on these equations for a number of iterations until hopefully, they all converge to the same point. The global best can then be taken as the final solution produced by the algorithm.
Hopefully this makes the inner workings of PSO more clear. With every iteration, every particle moves in a direction that is determined by its personal best and the global best. Assuming that the objective function's optimum is somewhere near these two points, it is likely that the particle will eventually encounter better and better solutions.
Other Considerations
Note that there are many different variations on the process described above. For example, it is possible to only allow knowledge sharing amongst a subset of the swarm's particles. The subset of particles with which a given particle can communicate is known as its neighbourhood. The particle will then move in the direction of the best solution found in its neighbourhood, the "local best" instead of the global best.
Also, there are a number of other possible pitfalls such as the values for w, c1, and c2. Although it is possible to do fancy things here, the general rule of thumb is to set:
w = 0.729844
c1 = c2 = 1.49618
as suggested by http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=870279&tag=1 to lead to convergent behaviour (i.e. so that all the particles will eventually converge to roughly the same point).
Usually, the particles are randomly initialized throughout the search space. Although it is possible to initialize their velocities randomly as well, this isn't necessary and may lead to divergent behaviour, so it's fine to just start the velocities as 0-vectors.
Some parties also advise making use of velocity clamping (where every velocity component is bounded above and below by some maximum and minimum value; if a particle's velocity exceeds that, it is clamped to the maximum/minimum). This is usually not necessary if w, c1 and c2 are chosen correctly and the gBest and pBest are only updated if they are within the bounds of the search space.

Finding a coordinate in a circle

I am doing a mashup using Google Maps under Grails where users can create geofences by selecting a point on the map and a radius. This get stored on my database and the application receives constantly a set of coordinates from a GPS device.
I would like to compare the received coordinates with the area stored in the circles. If the point is inside (or outside) the circle the program will fire an action. However, I would like to know how I can find out if the coordinates are located inside/outside the circle. There is a Javascript library which allows doing this but I need to do this on the server.
Is there a Java (or even Groovy) library for this?
How would you implement it?
if distance from point to center of circle is <= radius of circle then it is inside the circle.
if the area is made of more than one circle than compare to all the circles... it won't take that long.
java.awt.geom.Point2D.Double is perfect for this.
Well, if it doesn't need to be "perfect", you don't need to worry about plotting circles or anything like that. You can just take the two locations (the location you want to test, and the center of the circle) and use Pythagorus to find the distance. If that distance is less than the radius of the circle, it's inside.
There is a caveat to take into consideration, however: the reason this wouldn't be perfect is that that for your points, you're probably going to get a latitude and longitude...and the Earth is a sphere. So near the poles of the Earth this will kind of fall apart. But it may well be good enough for what you're doing.
Sadly, most of the responses here won't work for you conveniently, because GPS coordinates are in units of degrees. You will need something to convert from two points in Degrees of latitude and longitude to a great circle distance, which simple Pythagorean theorem falls short of.
If you're using Google maps API, you can probably do everything you need using GLatLng. As other posters have noted, You can determine the distance between two points is less than the radius of the specified circle. Specifically GLatLng.distance(other:GLatLng) returns the meters distance between too GPS locations.
To actually display the circles requires a bit more finesse. You will need to create a GPolygon to draw the circumference of the circle. You can find a number of free JavaScript functions that can do this for you.
Victor and Beska have the correct answer. That is, if the distance between the point and the center is less than the radius, then it's in the circle.
For the great circle distance between two points, you can use GeoTools' GeodeticCalculator. In particular you set the point and radius using setStartingGeographicPoint and setDestinationGeographicPoint followed by calling getOrthodromicDistance which will return the distance.
You want to find the vector that is the distance between the selected coordinate and the center of the circle, then compute the square distance between the selected coordinate and the center of the circle by squaring the components of the vector and adding them together; if that scalar (the squared distance) is less than the square of the radius, the point is within the circle.
This method avoids having to take a square root, and is just as accurate as normal distance comparison.
One possibility is to calculate the distance from the centerpoint and compare it to the radius.
Depending on you application you may be have to take into account that the world is a sphere and not 2Dimensional. To calcualte a distance on earth you can use this formula.
Since you are using Google Maps and for geographical distances spherical geometry holds rather than euclidean geometry. However if it is relativley smaller distance like a parking lot etc. then you can use euclidean distance formula (http://en.wikipedia.org/wiki/Distance) to find out whether the point is inside or outside the circle.
I presume you know the coordinates of the circle's center C(xc, yc) and its radius, R. Then for a given point P(x1, y1) find the euclidean distance, D as
square-root((x1-xc)^2 + (y1-yc)^2)). If D > R, the point lies outside the circle. If D < R, the point lies inside the circle. If D = R, the point lies on the circumference of the circle.
In case you are doing your measurements over larger distances then you should rather look for Geodesics (please check this http://en.wikipedia.org/wiki/Great-circle_distance).
I hope it helps.
cheers

Categories

Resources