Java parallelize computation of a vector - java

I would like to start to parallelize my Java code. This is my toy-problem. I have two vectors (double []) containing respectively the height and the base of several triangles. I have a class, Triangle, containing a method, computeArea, that computes the area of a triangle (height*base/2). For each triangle I have I want to store the area in a third vector (double []). Currently I have a for loop like this
for(int i=0; i<height.length; i++){
area[i] = triangle.computeArea(height[i], base[i]);
}
Some suggestion on how to parallelize the code? Could you kindly provide me a simple example? I am using jdk 1.8.
Please note that the values in the vector area must correspond to values in vectors height and base.
Thanks in advance

Related

Plotting points from two arrays to a graph

I was solving tsp using simulated annealing and I want to plot the optimum distance versus temperature of the optimum distance and join those points to see the nature of the graph.
I've got the distances and temperatures in two different arrays now I need to plot this as a scatter. If putting the values in one array is required for plotting even that can be done but how do I plot such a graph. I tried using libre office to plot the graph but that isn't working at all, the app is crashing.
while (temp > 1) {
//some code giving distance
// Cool system
temp *= 1-coolingRate;
System.out.println(""+ best.getDistance());
System.out.println(""+ temp );
//Outputs to be put in an array and plotted
}
Edit 1:
Both the arrays are single dimensional and the graph I want to plot has points whose X and y co ordinates are taken from these arrays consecutively.
I can't figure out a way to do it.
Search your code to see if 'temp' is defined in multiple ways in your code. temp is a common variable that is also often used as a temporary holding place while you crunch the numbers. Has it been previously defined?

Fastest way to check which rectangle is clicked in a list of rectangles

I have a rectangle Object with x, y, width and height. I have a list of these rectangles which are displayed on a screen. It is guaranteed that none of them overlap. Given a user's click position (x and y coordinates), I want to see which of these rectangles were clicked (since they do not overlap, there is a maximum of one rect that can be clicked).
I can obviously look through all of them and check for each one if the user clicked it but this is very slow because there are many on the screen. I can use some kind of comparison to keep the rectangles sorted when I insert a new one into the list. Is there some way to use something similar to binary search in order to decrease the time it takes to find which rect was clicked?
Note: the rectangles can be any size.
Thanks:)
Edit: To get an idea of what I am making visit koalastothemax.com
It highly depends upon your application and details we're not quite aware of yet for what the best solution would be. BUT, with as little as I know, I'd say you can make a 2D array that points to your rectangles. That 2D array would map directly to the pixels on the screen. So if you make the array 10x20, then the coordinate x divided by screen width times 10 (casted to int) will be the first index and y divided screen height times 20 would be your y index. With your x and y index, you can map directly to the rectangle that it points to. Some indexes might be empty and some might point to more than one rectangle if they're not perfectly laid out, but that seems the easiest way to me without knowing much about the application.
I have tackled a very similar problem in the past when developing a simulation. In my case the coordinates were doubles (so no integer indexing was possible) and there could be hundreds of millions of them that needed to be searched.
My solution was to create an Axis class to represent each axis as a sequence of ranges. The ranges were guaranteed to go from a minimum to a maximum and the class was smart enough to split itself into pieces when new ranges were added. Each range has a single generic object stored. The class used a binary search to find a range quickly.
So roughly the class looks like:
class Axis<T> {
public Axis(double min, double max, Supplier<T> creator);
public Stream<T> add(double from, double to);
public T get(double coord);
}
The add method needs to return a stream because the added range may cover several ranges.
To store rectanges:
Axis<Axis<Rectangle>> rectanges = new Axis<>(0.0, 100.0,
() -> new Axis<>(0.0, 100.0, Rectangle::new));
rectangles.add(x, x + w).forEach(r -> r.add(y, y + h).forEach(Rectangle::setPresent));
And to find a rectangle:
rectangles.get(x).get(y);
Note that there's always an object stored so you need a representation such as Rectangle.NULL for 'not present'. Or you could make it Optional<Rectangle> (though that indirection eats a lot of memory and processing for large numbers of rectangles).
I've just given the high level design here rather than any implementation details so let me know if you want more info on how to make it work. Getting the logic right on the range splits is not trivial. But I can guarantee that it's very fast even with very large numbers of rectangles.
The fastest way I can come up with is definitely not the most memory efficient. This works by exploiting the fact that an amortized hash table has constant lookup time. It will map every point that a rectangle has to that rectangle. This is only really effective if your are using integers. You might be able to get it to work with floats if you use a bit of rounding.
Make sure that the Point class has a hash code and equals function.
public class PointCheck
{
public Map<Point, Rect> pointMap;
public PointCheck()
{
pointMap = new HashMap<>();
}
/**
* Map all points that contain the rectangle
* to the rectangle.
*/
public void addRect(Rect rect)
{
for(int i = rect.x; i < rect.x + rect.width; ++i)
{
for(int j = rect.y; j < rect.y + rect.height; ++i)
{
pointMap.put(new Point(i, j), rect);
}
}
}
/**
* Returns the rectangle clicked, null
* if there is no rectangle.
*/
public Rect checkClick(Point click)
{
return pointMap.get(click);
}
}
Edit:
Just thought I should mention this: All of the rectangles held in the value of the hash map are references to the original rectangle, they are not clones.

How to plot XY graph in Genetic Algorithm in Java

I want to consist of graph function my problem for genetic algorithm. How can I do ? My chart consists of 2 independent axes, lets say X is number of iterations and Y represents corresponding best chromosome minimum value of fitness function. I am doing replacement after mutation, and then I am selecting the best chromosome. You can see below my cycle. How I can implement a graph library? I don't know anything about how to draw graphs.
for(int i=0; i
for(int j=0;j<parameters.getMaxSelection();j++){
select.binaryTournamentSelection(pop.chromosome);
for(int k=0;k<parameters.getMaxCrossover();k++){
crossing.onePointCrossover();
for(int m=0;m<parameters.getMaxMutation();m++){
mut.bitFlip();
mut.steadyStateSorting(pop);
}
}
}
}
This may not be what you are looking for but this code might give you some ideas about the XY Graph : https://github.com/najikadri/ONSA

Calculating normals of .3ds model

I'm trying to implement .3ds importer according to this documentation and I've approached the stage when I need to calculate vertex normals because .3ds files do not provide such. Here is the Java code:
/* Sctructure of vertex array is {x0, y0, z0, x1, y1, z1...}
*
* Basically, MathUtils.generateNormal_f(x0,y0,z0, x1,y1,z1, x2,y2,z2) is cross
* product between (x1-x0, y1-y0, z1-z0) and (x2-x0, y2-y0, z2-z0) */
normals = new float[this.vertex.length]; //every vertex has it's own normal
int n = 0;
for (int i=0; i<this.index.length; i++){
float[] Normal = MathUtils.generateNormal_f( //getting xyz coords of 1 normal
vertex[index[i]*3], vertex[index[i]*3+1], vertex[index[i]*3+2],
vertex[index[++i]*3], vertex[index[i]*3+1], vertex[index[i]*3+2],
vertex[index[++i]*3], vertex[index[i]*3+1], vertex[index[i]*3+2]);
normals[n++] = Normal[0];
normals[n++] = Normal[1];
normals[n++] = Normal[2];
}
Method MathUtils.generateNormal_f(...) tested and works fine. Result of this code can be seen below (first image). Just for example, in the second image, every normal of the model is the same and pointing towards the source of light.
Question is: how to calculate normals properly?
Your normals might be inverted.
I do not remember the 3ds format very well, but check if you can export and import the normals from the file instead of calculating them.
P.S. also do not use magic like this:
vertex[index[i]*3], vertex[index[i]*3+1], vertex[index[i]*3+2],
vertex[index[++i]*3], vertex[index[i]*3+1], vertex[index[i]*3+2],
vertex[index[++i]*3], vertex[index[i]*3+1], vertex[index[i]*3+2]
You will get different results based on the sequence of argument evaluation. better explicitly use [i], [i+1], [i+2] when calling calculate normal...
This information is correct as far as I know, and it's worked for me. For any 3 points A, B, and C on a plane, the normal, if we start at A, then B, and finally C, will be:
Where (B - A) and (C - B) each subtract two vectors, and the X sign represents finding the cross product of two vectors. The order of the points is quite important and determines our normal direction. If A, B, and C are organized in a counter-clockwise direction, than their normal will face outside the solid. If you want to know what a cross product is, then for any point P and Q, their cross product would be:
Another thing that is often done to the normal vector is that it is normalized. What this does is make the magnitude of the normal vector equal to 1 so that it is easier to work with. here's the equation:
Where the dot represents a dot product. If you don't know what a dot product is, allow me to illustrate by the following. For any points P and Q, their dot product, which is a scalar value, is:
Now that you have the surface normals, you can properly calculate the vertex normals for each vertex by averaging out the normals of any surface which shares that vertex. I don't have that formula on me, but I do know there are two approaches to find the vertex normal: weighted and non-weighted. A weighted approach involves calculating the area of each surface, while a non-weighted approach does not.
Hopefully, this information will help you. I leave the rest up to you or anyone else, as the remaining information is beyond my realm. Perhaps I'll come back and research some more on this question.

Loop inside oval in Java

I need to examine each pixel inside an oval with Java.
For drawing, I am currently using:
drawOval(x,y,r*2,R*2).
However, since I need to get each pixel inside the Oval, I would like to create a loop that iterates inside it (assuming I have x,y,r and R). Is there any built in functionality for this purpose?
Thanks,
Joel
Java's Ellipse2D implements the Shape interface, so you can use one of the latter's contains() methods as required. It's also possible to render the Shape into a BufferedImage and traverse its WritableRaster.
simple canonical implicit equation for Oval is (with center 0; 0)
So yo can iterate throw all possible coordinates and check it using this equation.
I don't think there's any built in functionality for this.
Let's go through this step by step.
Assuming that your ellipse's center is at (0,0), one radius is a, other is b, the canonical equation is
x^2/a^2+y^2/b^2=1
Multiplying both sides with a^2 and b^2, you get
x^2*b^2+y^2*a^2=a^2*b^2
Now, you must do a double for loop. a and b must be positive. Pseudocode:
for x = -a; x <= a; ++x:
for y = -b; y <= b; ++y:
if(x^2*b^2+y^2*a^2 <= a^2*b^2)
// you're in your ellipse, do as you please
Of course, this will work only if center is at (0,0), so if you want this algorithm to work, shift your points appropriately using translation. If you leave the center somewhere else, this algorithm will get messier.
Note: didn't test this. If somebody sees a mistake, please point it out.

Categories

Resources