How to align an object to match path - java

I am animating an object along a spline path in OpenGL. I am using some code I found to generate the spline. Sadly, I don't yet understand the mechanics of it. I want my object to align to match the tangent of path so that it looks like its following the path.
Two questions.
How do I find a vector that is tangent to the path at a given point?
Secondly, given that vector and a vector pointing up, how do rotate the object to align?
Here is my spline code.
public Spline(Vector Path[])
{
ControlPoints = Path;
// Flatten out the control points array.
int len = ControlPoints.length;
float[] controlsX = new float[len];
float[] controlsY = new float[len];
float[] controlsZ = new float[len];
for (int i = 0; i < len; ++i)
{
controlsX[i] = ControlPoints[i].x;
controlsY[i] = ControlPoints[i].y;
controlsZ[i] = ControlPoints[i].z;
}
// Calculate the gamma values just once.
final int n = ControlPoints.length - 1;
float[] gamma = new float[n + 1];
gamma[0] = 1.0f / 2.0f;
for (int i = 1; i < n; ++i) gamma[i] = 1 / (4 - gamma[i - 1]);
gamma[n] = 1 / (2 - gamma[n - 1]);
// Calculate the cubic segments.
cubicX = calcNaturalCubic(n, controlsX, gamma);
cubicY = calcNaturalCubic(n, controlsY, gamma);
cubicZ = calcNaturalCubic(n, controlsZ, gamma);
}
private Cubic[] calcNaturalCubic(int n, float[] x, float[] gamma)
{
float[] delta = new float[n + 1];
delta[0] = 3 * (x[1] - x[0]) * gamma[0];
for (int i = 1; i < n; ++i)
{
delta[i] = (3 * (x[i + 1] - x[i - 1]) - delta[i - 1]) * gamma[i];
}
delta[n] = (3 * (x[n] - x[n - 1])-delta[n - 1]) * gamma[n];
float[] D = new float[n + 1];
D[n] = delta[n];
for (int i = n - 1; i >= 0; --i)
{
D[i] = delta[i] - gamma[i] * D[i + 1];
}
// Calculate the cubic segments.
Cubic[] C = new Cubic[n];
for (int i = 0; i < n; i++) {
final float a = x[i];
final float b = D[i];
final float c = 3 * (x[i + 1] - x[i]) - 2 * D[i] - D[i + 1];
final float d = 2 * (x[i] - x[i + 1]) + D[i] + D[i + 1];
C[i] = new Cubic(a, b, c, d);
}
return C;
}
final public Vector GetPoint(float Position)
{
if(Position >= 1) { return ControlPoints[ControlPoints.length - 1]; }
float position = Position * cubicX.length;
int splineIndex = (int)Math.floor(position);
float splinePosition = position - splineIndex;
return new Vector(cubicX[splineIndex].eval(splinePosition), cubicY[splineIndex].eval(splinePosition), cubicZ[splineIndex].eval(splinePosition));
}

First question:
If you keep track of the previous position of your object as well as the new position, you can find out the facing direction without finding the tangent of the spline, like so:
facing = newPosition - previousPosition
Second question:
You can use the answers described here for rotating an object to face a particular direction: What is the easiest way to align the Z axis with a vector?

Related

Find Path with maximum value where T squares value can be doubled

Given a square matrix of size N*N, where each cell is associated with a specific cost. A path is defined as a specific sequence of cells which starts from top left cell move only right or down and ends on bottom right cell. We want to find the path with maximum value. Now to make things even more interesting: you also have T tokens. You can use the tokens to double the value on the current square. You can only use one token on any given square.
This is how I have solved the first part of the problem.
public static long pathWithMaxCost(int[][] n, int tokens) {
int[][] arr = new int[n.length][n[0].length];
// starting position
arr[arr.length - 1][0] = n[arr.length - 1][0];
// first column
for (int i = arr.length - 2; i >= 0; i--) {
arr[i][0] = arr[i + 1][0] + n[i][0];
}
// last row
for (int i = 1; i < arr[0].length; i++) {
arr[arr.length - 1][i] = arr[arr.length - 1][i - 1] + n[arr.length - 1][i];
}
for (int i = arr.length - 2; i >= 0; i--) {
for (int j = 1; j < arr[0].length; j++) {
arr[i][j] = Math.max(arr[i][j - 1], arr[i + 1][j]) + n[i][j];
}
}
return arr[0][arr[0].length - 1];
}
Now how can I handle the token part, T square values can be doubled?
static long pathWithMaxCostHash(int[][] n, int x, int y, int tokkens) {
if (x < 0 || x >= n.length || y < 0 || y >= n[0].length)
return -1;
String key = x + ":" + y + ":" + tokkens;
if (map.containsKey(key))
return map.get(key);
if(x==n.length-1&&y==0) {
if (tokkens > 0 && n[x][y] > 0) {
map.put(key,(long)n[n.length-1][0]*2);
return 2*n[n.length-1][0];
}
map.put(key,(long)n[n.length-1][0]);
return n[n.length-1][0];
}
//without picking double
long val = n[x][y]
+ Math.max(pathWithMaxCostHash(n, x + 1, y, tokkens), pathWithMaxCostHash(n, x, y - 1, tokkens));
//with picking double
if (tokkens > 0 && n[x][y] > 0) {
long val2 = 2 * n[x][y] + Math.max(pathWithMaxCostHash(n, x + 1, y, tokkens - 1),
pathWithMaxCostHash(n, x, y - 1, tokkens - 1));
val2 = Math.max(val, val2);
map.put(key, val2);
return val2;
}
map.put(key, val);
return val;
}
I'll give you a recursive approach, guess you can figure out dynamic programming based solution with this.
Initialize your dp 2d array with 0's
function: pathWithMaxCost(int x,int y,int tokens, int arr[][],int dp[][])
if(dp[x][y]) return dp[x][y];
few boundary conditions here...
return dp[x][y]=max(arr[x][y]+pathWithMaxCost(x,y+1,tokens,arr), arr[x][y]+pathWithMaxCost(x+1,y,tokens,arr), (arr[x][y]*2)+pathWithMaxCost(x,y+1,tokens-1,arr), (arr[x][y]*2)+pathWithMaxCost(x+1,y,tokens-1,arr))
Add another dimension for T, so the general check for a cell would be:
m[y][x][t] = max(
2 * n[y][x] + m[y-1][x][t-1],
2 * n[y][x] + m[y][x-1][t-1],
n[y][x] + m[y-1][x][t],
n[y][x] + m[y][x-1][t]
)
for all y,x,t
Let's consider the edge cases:
// first element
if x + y == 0:
m[y][x][0] = n[y][x]
m[y][x][1] = 2 * n[y][x]
m[y][x][t] = -Infinity, for t > 1
// first row
if y == 0:
m[y][x][t] = max(
2 * n[y][x] + m[y][x-1][t-1],
n[y][x] + m[y][x-1][t]
)
// first column
if x == 0:
m[y][x][t] = max(
2 * n[y][x] + m[y-1][x][t-1],
n[y][x] + m[y-1][x][t]
)

Implementing Strassen's Algorithm

I would like to multiply matrices very fast on a single core. I have looked around of the web and came across a few algorithms and found out Strassen's algorithm is the only one, that is actually implemented by people. I have looked on a few examples and came to the solution below. I made a simple benchmark which generates two randomly filled 500x500 matrices. Strassen's algorithm took 18 seconds, where the high school algorithm was done in 0.4 seconds. Other people where very promising after implementing the algorithm, so what is wrong with mine, how can I make it quicker?
// return C = A * B
private Matrix strassenTimes(Matrix B, int LEAFSIZE) {
Matrix A = this;
if (B.M != A.M || B.N != A.N) throw new RuntimeException("Illegal matrix dimensions.");
if (N <= LEAFSIZE || M <= LEAFSIZE) {
return A.times(B);
}
// make new sub-matrices
int newAcols = (A.N + 1) / 2;
int newArows = (A.M + 1) / 2;
Matrix a11 = new Matrix(newArows, newAcols);
Matrix a12 = new Matrix(newArows, newAcols);
Matrix a21 = new Matrix(newArows, newAcols);
Matrix a22 = new Matrix(newArows, newAcols);
int newBcols = (B.N + 1) / 2;
int newBrows = (B.M + 1) / 2;
Matrix b11 = new Matrix(newBrows, newBcols);
Matrix b12 = new Matrix(newBrows, newBcols);
Matrix b21 = new Matrix(newBrows, newBcols);
Matrix b22 = new Matrix(newBrows, newBcols);
for (int i = 1; i <= newArows; i++) {
for (int j = 1; j <= newAcols; j++) {
a11.setElement(i, j, A.saveGet(i, j)); // top left
a12.setElement(i, j, A.saveGet(i, j + newAcols)); // top right
a21.setElement(i, j, A.saveGet(i + newArows, j)); // bottom left
a22.setElement(i, j, A.saveGet(i + newArows, j + newAcols)); // bottom right
}
}
for (int i = 1; i <= newBrows; i++) {
for (int j = 1; j <= newBcols; j++) {
b11.setElement(i, j, B.saveGet(i, j)); // top left
b12.setElement(i, j, B.saveGet(i, j + newBcols)); // top right
b21.setElement(i, j, B.saveGet(i + newBrows, j)); // bottom left
b22.setElement(i, j, B.saveGet(i + newBrows, j + newBcols)); // bottom right
}
}
Matrix aResult;
Matrix bResult;
aResult = a11.add(a22);
bResult = b11.add(b22);
Matrix p1 = aResult.strassenTimes(bResult, LEAFSIZE);
aResult = a21.add(a22);
Matrix p2 = aResult.strassenTimes(b11, LEAFSIZE);
bResult = b12.minus(b22); // b12 - b22
Matrix p3 = a11.strassenTimes(bResult, LEAFSIZE);
bResult = b21.minus(b11); // b21 - b11
Matrix p4 = a22.strassenTimes(bResult, LEAFSIZE);
aResult = a11.add(a12); // a11 + a12
Matrix p5 = aResult.strassenTimes(b22, LEAFSIZE);
aResult = a21.minus(a11); // a21 - a11
bResult = b11.add(b12); // b11 + b12
Matrix p6 = aResult.strassenTimes(bResult, LEAFSIZE);
aResult = a12.minus(a22); // a12 - a22
bResult = b21.add(b22); // b21 + b22
Matrix p7 = aResult.strassenTimes(bResult, LEAFSIZE);
Matrix c12 = p3.add(p5); // c12 = p3 + p5
Matrix c21 = p2.add(p4); // c21 = p2 + p4
aResult = p1.add(p4); // p1 + p4
bResult = aResult.add(p7); // p1 + p4 + p7
Matrix c11 = bResult.minus(p5);
aResult = p1.add(p3); // p1 + p3
bResult = aResult.add(p6); // p1 + p3 + p6
Matrix c22 = bResult.minus(p2);
// Grouping the results obtained in a single matrix:
int rows = c11.nrRows();
int cols = c11.nrColumns();
Matrix C = new Matrix(A.M, B.N);
for (int i = 1; i <= A.M; i++) {
for (int j = 1; j <= B.N; j++) {
int el;
if (i <= rows) {
if (j <= cols) {
el = c11.get(i, j);
} else {
el = c12.get(i, j - cols);
}
} else {
if (j <= cols) {
el = c21.get(i - rows, j);
} else {
el = c22.get(i - rows, j - rows);
}
}
C.setElement(i, j, el);
}
}
return C;
}
The little benchmark has the following code:
int AM, AN, BM, BN;
AM = 500;
AN = BM = 500;
BN = 500;
Matrix a = new Matrix(AM, AN);
Matrix b = new Matrix(BM, BN);
Random random = new Random();
for (int i = 1; i <= AM; i++) {
for (int j = 1; j <= AN; j++) {
a.setElement(i, j, random.nextInt(20));
}
}
for (int i = 1; i <= BM; i++) {
for (int j = 1; j <= BN; j++) {
b.setElement(i, j, random.nextInt(20));
}
}
System.out.println("strassen: A x B");
long tijd = System.currentTimeMillis();
Matrix c = a.strassenTimes(b);
System.out.println("time = " + (System.currentTimeMillis() - tijd));
System.out.println("normal: A x B");
tijd = System.currentTimeMillis();
Matrix d = a.times(b);
System.out.println("time = " + (System.currentTimeMillis() - tijd));
System.out.println("nr of different elements = " + c.compare(d));
With the following results:
strassen: A x B
time = 18372
normal: A x B
time = 308
nr of different elements = 0
I know it's a low of code, but I would be very happy if you guys help me out ;)
EDIT 1:
For the sake of completeness I add some methods that is used by the above code.
public int get(int r, int c) {
if (c > nrColumns() || r > nrRows() || c <= 0 || r <= 0) {
throw new ArrayIndexOutOfBoundsException("matrix is of size (" +
nrRows() + ", " + nrColumns() + "), but tries to set element(" + r + ", " + c + ")");
}
return content[r - 1][c - 1];
}
private int saveGet(int r, int c) {
if (c > nrColumns() || r > nrRows() || c <= 0 || r <= 0) {
return 0;
}
return content[r - 1][c - 1];
}
public void setElement(int r, int c, int n) {
if (c > nrColumns() || r > nrRows() || c <= 0 || r <= 0) {
throw new ArrayIndexOutOfBoundsException("matrix is of size (" +
nrRows() + ", " + nrColumns() + "), but tries to set element(" + r + ", " + c + ")");
}
content[r - 1][c - 1] = n;
}
// return C = A + B
public Matrix add(Matrix B) {
Matrix A = this;
if (B.M != A.M || B.N != A.N) throw new RuntimeException("Illegal matrix dimensions.");
Matrix C = new Matrix(M, N);
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
C.content[i][j] = A.content[i][j] + B.content[i][j];
}
}
return C;
}
I should have choosen another leaf size for Strassen´s algorithm. Therefore I did a little experiment. It seems that leaf size 256 works best with the code included in the question. Below a plot with different leaf sizes with each time a random matrix of size 1025 x 1025.
I have compared Strassen´s algorithm with leaf size 256 with the trivial algorithm for matrix multiplication, to see if it´s actually an improvement. It turned out to be an improvement, see below the results on random matrices of different sizes (in steps of 10 and repeated 50 times for each size).
Below the code for the trivial algorithm for matrix multiplication:
// return C = A * B
public Matrix times(Matrix B) {
Matrix A = this;
if (A.N != B.M) throw new RuntimeException("Illegal matrix dimensions.");
Matrix C = new Matrix(A.M, B.N);
for (int i = 0; i < C.M; i++) {
for (int j = 0; j < C.N; j++) {
for (int k = 0; k < A.N; k++) {
C.content[i][j] += (A.content[i][k] * B.content[k][j]);
}
}
}
return C;
}
It still think there can be done other improvements on the implementation, but it turned out that the leaf size is a very important factor. All experiments are done with a machine running on Ubuntu 14.04 with the following specifications:
CPU: Intel(R) Core(TM) i7-2600K CPU # 3.40GHz
Memory: 2 x 4GB DDR3 1333 MHz

Java optimized Cramers rule function

Recently learned about Cramers rule in precalculus, and decided to make an algorithm in Java to help me understand it better.
The following code works 100% correctly, however it does not use any sort of for loop to do what it does in a much simpler fashion.
Question: Is there a more elegant implementation of Cramers Rule in Java?
I'm thinking that making a basic determinant method, and then doing some column swapping for when I need to take the determinant of Dx, Dy, and Dz. (for Dx, swap column 4 with column 1 of the original matrix, then take determinant and divide by original determinant.)
This sound good?
public static void main(String[] args) {
int[][] matrix = new int[3][3];
matrix[0] = new int[] { 3, 5, -1, -2 };
matrix[1] = new int[] { 1, -4, 2, 13 };
matrix[2] = new int[] { 2, 4, 3, 1 };
int[] r = crame(matrix);
info("x: " + r[0] + ", y: " + r[1] + ", z: " + r[2]);
for(int i = 0; i < matrix.length; i++) {
int[] base = matrix[i];
if(check(base, r, base[3])) {
info("System " + (i+1) + " checks!");
} else {
info("System " + (i+1) + " fails check!");
}
}
}
public static int[] crame(int[][] m) {
int[] result;
if (m.length == 2) {
result = new int[2];
int D = (m[0][0] * m[1][1]) - (m[1][0] * m[0][1]);
int Dx = (m[0][2] * m[1][1]) - (m[1][2] * m[0][1]);
int Dy = (m[0][0] * m[1][2]) - (m[1][0] * m[0][2]);
result[0] = (int) (Dx / D);
result[1] = (int) (Dy / D);
} else if (m.length == 3) {
result = new int[3];
int D = (((m[0][2] * m[1][1] * m[0][2]) + (m[2][1] * m[1][2] * m[0][0]) + (m[2][2]
* m[1][0] * m[0][2])) - ((m[0][0] * m[1][1] * m[2][2])
+ (m[0][1] * m[1][2] * m[0][2]) + (m[0][2] * m[1][0] * m[2][1])));
int Dx = (((m[2][3] * m[1][1] * m[0][2]) + (m[2][1] * m[1][2] * m[0][3]) + (m[2][2]
* m[1][3] * m[0][1])) - ((m[0][3] * m[1][1] * m[2][2])
+ (m[0][1] * m[1][2] * m[2][3]) + (m[0][2] * m[1][3] * m[2][1])));
int Dy = (((m[2][0] * m[1][3] * m[0][2]) + (m[2][3] * m[1][2] * m[0][3]) + (m[2][2]
* m[1][0] * m[0][3])) - ((m[0][0] * m[1][3] * m[2][2])
+ (m[0][3] * m[1][2] * m[2][0]) + (m[0][2] * m[1][0] * m[2][3])));
int Dz = (((m[2][0] * m[1][1] * m[0][3]) + (m[2][1] * m[1][3] * m[0][0]) + (m[2][3]
* m[1][0] * m[0][1])) - ((m[0][0] * m[1][1] * m[2][3])
+ (m[0][1] * m[1][3] * m[2][0]) + (m[0][3] * m[1][0] * m[2][1])));
result[0] = (int) (Dx / D);
result[1] = (int) (Dy / D);
result[2] = (int) (Dz / D);
} else {
return new int[] {};
}
return result;
}
public static int product(int[] a, int[] b) {
int p = 0;
int[] fin = new int[(a.length -1)];
for(int x = 0; x < fin.length; x++) {
fin[x] = a[x] * b[x];
}
for (int f : fin) {
p += f;
}
return p;
}
public static boolean check(int[] a, int[] b, int z) {
return product(a, b) == z;
}
public static void info(String log) {
System.out.println(log);
}
My question pertains to the specific algorithm that can be used to solve systems of equations using Cramers rule only, is there any algorithm that is more elegant? The function is only designed for square matrices.
This is not a homework assignment, after HS I will be studying CS and I've been working on developing algorithms as preliminary practice.
Thank you for checking this out
First of, there is one way in which Cramers rule is perfect: It gives the algebraic solution of a linear system as a rational function in its coefficients.
However, practically, it has its limits. While the most perfect formula for a 2x2 system, and still good for a 3x3 system, its performance, if implemented in the straightforward way, deteriorates with each additional dimension.
An almost literal implementation of Cramers rule can be achieved with the Leverrier-Faddeev algorithm a b. It only requires the computation of matrix products and matrix traces, and manipulations of the matrix diagonal. Not only does it compute the determinant of the matrix A (along with the other coefficients of the characteristic polynomial), it also has the adjugate or co-factor matrix A# in its iteration matrix. The interesting fact about this matrix is that it allows to write the solution of A*x=b as (A#*b)/det(A), that is, the entries of A#*b already are the other determinants required by Cramers rule.
Leverrier-Faddeev requires n4+O(n3) operations. The same results can be obtained by the more complicated Samuelson-Berkowitz algorith, which has one third of that complexity, that is n4/3+O(n3).
The computation of the determinants required in Cramers rule becomes downright trivial if the system (A|b) is first transformed into triangular form. That can be achieved by Gauß elimination, aka LU decomposition (with pivoting for numerical stability) or the QR decomposition (easiest to debug should be the variant with Givens rotations). The efficient application of Cramers rule is then backward substitution in the triangular system.
Your method sounds good to me at least; however, I just may not be aware of any more efficient methods. The not-fun part may be figuring out how to best implement the determinant-calculating method, as apparently it's not an inexpensive operation.
But once you know that that's working, the rest sounds pretty OK to me. Cache the determinant of the original matrix, substitute in columns, etc.
Figured out exactly how to do this effectively.
http://sandsduchon.org/duchon/math/determinantJava.html
Provides a method for seamless determinants, and mentions matrix decomposition. I have not learned this yet as it's not a HS level concept however I did some problems using it and it's a solid method.
Final Code:
public static void main(String[] args) {
int[][] matrix = new int[3][3];
matrix[0] = new int[] { 3, 5, -1, -2 };
matrix[1] = new int[] { 1, -4, 2, 13 };
matrix[2] = new int[] { 2, 4, 3, 1 };
int[] r = crame(matrix);
info("x: " + r[0] + ", y: " + r[1] + ", z: " + r[2]);
for (int i = 0; i < matrix.length; i++) {
int[] base = matrix[i];
if (check(base, r, base[3])) {
info("System " + (i + 1) + " checks!");
} else {
info("System " + (i + 1) + " fails check!");
}
}
}
public static int getDet(int[][] a) {
int n = a.length - 1;
if (n < 0)
return 0;
int M[][][] = new int[n + 1][][];
M[n] = a; // init first, largest, M to a
// create working arrays
for (int i = 0; i < n; i++)
M[i] = new int[i + 1][i + 1];
return getDet(M, n);
} // end method getDecDet double [][] parameter
public static int getDet(int[][][] M, int m) {
if (m == 0)
return M[0][0][0];
int e = 1;
// init subarray to upper left mxm submatrix
for (int i = 0; i < m; i++)
for (int j = 0; j < m; j++)
M[m - 1][i][j] = M[m][i][j];
int sum = M[m][m][m] * getDet(M, m - 1);
// walk through rest of rows of M
for (int i = m - 1; i >= 0; i--) {
for (int j = 0; j < m; j++)
M[m - 1][i][j] = M[m][i + 1][j];
e = -e;
sum += e * M[m][i][m] * getDet(M, m - 1);
} // end for each row of matrix
return sum;
} // end getDecDet double [][][], int
public static int[] crame(int[][] m) {
int[] result;
if (m.length == 2) {
result = new int[m.length];
int D = getDet(m);
for (int i = 0; i < m.length; i++) {
result[i] = getDet(slide(m, i, m.length)) / D;
}
} else if (m.length == 3) {
result = new int[m.length];
int D = getDet(m);
for (int i = 0; i < m.length; i++) {
result[i] = (getDet(slide(m, i, m.length)) / D);
}
} else {
return new int[] {};
}
return result;
}
public static int[][] slide(int[][] base, int col, int fin) {
int[][] copy = new int[base.length][];
for (int i = 0; i < base.length; i++) {
int[] aMatrix = base[i];
int aLength = aMatrix.length;
copy[i] = new int[aLength];
System.arraycopy(aMatrix, 0, copy[i], 0, aLength);
}
for (int i = 0; i < base.length; i++) {
copy[i][col] = base[i][fin];
}
return copy;
}
public static int product(int[] a, int[] b) {
int p = 0;
int[] fin = new int[(a.length - 1)];
for (int x = 0; x < fin.length; x++) {
fin[x] = a[x] * b[x];
}
for (int f : fin) {
p += f;
}
return p;
}
public static boolean check(int[] a, int[] b, int z) {
return product(a, b) == z;
}
public static void info(String log) {
System.out.println(log);
}

ANSI C pointers to java

Since some weeks ago I have been trying to convert this c and other c function to java language (i'm a newbie on it).
My first problem is how-to convert to java code, the pointers on lines like:
q = fdata + ind;
datend = fdata + buff_size;
For example when "ind" has a negative position (-220 for example) the pointer will be on "ind" position before "fdata" values, also the same occur with datend var.
I figured out that can be solved on isolated way by creating an index var for each pointer to know where there are pointing at. The real problem for me comes a few line after that, when i trying to not run over end of frame of "fdata" array.
Can some body with more experiences help me please?
Thank.
static Stat *stat = NULL;
static float *mem = NULL;
static Stat*
get_stationarity(fdata, freq, buff_size, nframes, frame_step, first_time)
float *fdata;
double freq;
int buff_size, nframes, frame_step, first_time;
{
static int nframes_old = 0, memsize;
float preemp = 0.4f, stab = 30.0f;
float *p, *q, *r, *datend;
int ind, i, j, m, size, order, agap, w_type = 3;
agap = (int) (STAT_AINT * freq);
size = (int) (STAT_WSIZE * freq);
ind = (agap - size) / 2;
if (nframes_old < nframes || !stat || first_time) {
/* move this to init_dp_f0() later */
nframes_old = nframes;
if (stat) {
ckfree((char *) stat->stat);
ckfree((char *) stat->rms);
ckfree((char *) stat->rms_ratio);
ckfree((char *) stat);
}
if (mem) ckfree((void *) mem);
stat = (Stat *) ckalloc(sizeof (Stat));
stat->stat = (float*) ckalloc(sizeof (float) *nframes);
stat->rms = (float*) ckalloc(sizeof (float) *nframes);
stat->rms_ratio = (float*) ckalloc(sizeof (float) *nframes);
memsize = (int) (STAT_WSIZE * freq) + (int) (STAT_AINT * freq);
mem = (float *) ckalloc(sizeof (float) * memsize);
for (j = 0; j < memsize; j++) mem[j] = 0;
}
if (nframes == 0) return (stat);
q = fdata + ind;
datend = fdata + buff_size;
if ((order = (int) (2.0 + (freq / 1000.0))) > BIGSORD) {
fprintf(stderr,
"exceeds that allowable (%d); reduce Fs\n", BIGSORD);
order = BIGSORD;
}
/* prepare for the first frame */
for (j = memsize / 2, i = 0; j < memsize; j++, i++) mem[j] = fdata[i];
/* do not run over end of frame */
for (j = 0, p = q - agap; j < nframes; j++, p += frame_step, q += frame_step) {
if ((p >= fdata) && (q >= fdata) && (q + size <= datend))
stat->stat[j] = get_similarity(order, size, p, q,
&(stat->rms[j]),
&(stat->rms_ratio[j]), preemp,
stab, w_type, 0);
else {
if (first_time) {
if ((p < fdata) && (q >= fdata) && (q + size <= datend))
stat->stat[j] = get_similarity(order, size, NULL, q,
&(stat->rms[j]),
&(stat->rms_ratio[j]),
preemp, stab, w_type, 1);
else {
stat->rms[j] = 0.0;
stat->stat[j] = 0.01f * 0.2f; /* a big transition */
stat->rms_ratio[j] = 1.0; /* no amplitude change */
}
} else {
if ((p < fdata) && (q + size <= datend)) {
stat->stat[j] = get_similarity(order, size, mem,
mem + (memsize / 2) + ind,
&(stat->rms[j]),
&(stat->rms_ratio[j]),
preemp, stab, w_type, 0);
/* prepare for the next frame_step if needed */
if (p + frame_step < fdata) {
for (m = 0; m < (memsize - frame_step); m++)
mem[m] = mem[m + frame_step];
r = q + size;
for (m = 0; m < frame_step; m++)
mem[memsize - frame_step + m] = *r++;
}
}
}
}
}
/* last frame, prepare for next call */
for (j = (memsize / 2) - 1, p = fdata + (nframes * frame_step) - 1; j >= 0 && p >= fdata; j--)
mem[j] = *p--;
return (stat);
}
This code is easier rewritten than ported. The reason is, that it uses a large number of pointer-arithmetic and casting.
It looks to me like this code combines a sliding window and averaging functions over the data. You can easily do this in Java, just place each time-series in an array, use an index (instead of a pointer) to point at the array's entries. In the case where the C-code uses a pointer and then a (possibly negative) offset as a second pointer just use two indices into the time-series-array.
It is easier to do this if you have the formula (math-notation. sliding-window plus averaging functions) that this code is supposed to compute and translate the formula to java.

How does this code for delaunay triangulation work?

I have this Java code that with a set of Point in input return a set of graph's edge that represent a Delaunay triangulation.
I would like to know what strategy was used to do this, if exist, the name of algorithm used.
In this code GraphEdge contains two awt Point and represent an edge in the triangulation, GraphPoint extends Awt Point, and the edges of final triangulation are returned in a TreeSet object.
My purpose is to understand how this method works:
public TreeSet getEdges(int n, int[] x, int[] y, int[] z)
below the complete source code of this triangulation :
import java.awt.Point;
import java.util.Iterator;
import java.util.TreeSet;
public class DelaunayTriangulation
{
int[][] adjMatrix;
DelaunayTriangulation(int size)
{
this.adjMatrix = new int[size][size];
}
public int[][] getAdj() {
return this.adjMatrix;
}
public TreeSet getEdges(int n, int[] x, int[] y, int[] z)
{
TreeSet result = new TreeSet();
if (n == 2)
{
this.adjMatrix[0][1] = 1;
this.adjMatrix[1][0] = 1;
result.add(new GraphEdge(new GraphPoint(x[0], y[0]), new GraphPoint(x[1], y[1])));
return result;
}
for (int i = 0; i < n - 2; i++) {
for (int j = i + 1; j < n; j++) {
for (int k = i + 1; k < n; k++)
{
if (j == k) {
continue;
}
int xn = (y[j] - y[i]) * (z[k] - z[i]) - (y[k] - y[i]) * (z[j] - z[i]);
int yn = (x[k] - x[i]) * (z[j] - z[i]) - (x[j] - x[i]) * (z[k] - z[i]);
int zn = (x[j] - x[i]) * (y[k] - y[i]) - (x[k] - x[i]) * (y[j] - y[i]);
boolean flag;
if (flag = (zn < 0 ? 1 : 0) != 0) {
for (int m = 0; m < n; m++) {
flag = (flag) && ((x[m] - x[i]) * xn + (y[m] - y[i]) * yn + (z[m] - z[i]) * zn <= 0);
}
}
if (!flag)
{
continue;
}
result.add(new GraphEdge(new GraphPoint(x[i], y[i]), new GraphPoint(x[j], y[j])));
//System.out.println("----------");
//System.out.println(x[i]+" "+ y[i] +"----"+x[j]+" "+y[j]);
result.add(new GraphEdge(new GraphPoint(x[j], y[j]), new GraphPoint(x[k], y[k])));
//System.out.println(x[j]+" "+ y[j] +"----"+x[k]+" "+y[k]);
result.add(new GraphEdge(new GraphPoint(x[k], y[k]), new GraphPoint(x[i], y[i])));
//System.out.println(x[k]+" "+ y[k] +"----"+x[i]+" "+y[i]);
this.adjMatrix[i][j] = 1;
this.adjMatrix[j][i] = 1;
this.adjMatrix[k][i] = 1;
this.adjMatrix[i][k] = 1;
this.adjMatrix[j][k] = 1;
this.adjMatrix[k][j] = 1;
}
}
}
return result;
}
public TreeSet getEdges(TreeSet pointsSet)
{
if ((pointsSet != null) && (pointsSet.size() > 0))
{
int n = pointsSet.size();
int[] x = new int[n];
int[] y = new int[n];
int[] z = new int[n];
int i = 0;
Iterator iterator = pointsSet.iterator();
while (iterator.hasNext())
{
Point point = (Point)iterator.next();
x[i] = (int)point.getX();
y[i] = (int)point.getY();
z[i] = (x[i] * x[i] + y[i] * y[i]);
i++;
}
return getEdges(n, x, y, z);
}
return null;
}
}
Looks like what is described here http://en.wikipedia.org/wiki/Delaunay_triangulation :
The problem of finding the Delaunay triangulation of a set of points in d-dimensional Euclidean space can be converted to the problem of finding the convex hull of a set of points in (d + 1)-dimensional space, by giving each point p an extra coordinate equal to |p|2, taking the bottom side of the convex hull, and mapping back to d-dimensional space by deleting the last coordinate.
In your example d is 2.
The vector (xn,yn,zn) is the cross product of the vectors (point i -> point j) and (point i -> point k) or in other words a vector perpendicular to the triangle (point i, point j, point k).
The calculation of flag checks whether the normal of this triangle points towards the negative z direction and whether all other points are on the side opposite to the normal of the triangle (opposite because the other points need to be above the triangle's plane because we're interested in the bottom side of the convex hull). If this is the case, the triangle (i,j,k) is part of the 3D convex hull and therefore the x and y components (the projection of the 3D triangle onto the x,y plane) is part of the (2D) Delaunay triangulation.

Categories