org.apache.commons.math.complex.Complex Java Examples

The following examples show how to use org.apache.commons.math.complex.Complex. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set a matrix element.
 * @param magnitude magnitude of the element
 * @param vector indices of the element
 * @return the previous value
 * @exception IllegalArgumentException if dimensions do not match
 */
public Complex set(Complex magnitude, int... vector)
    throws IllegalArgumentException {
    if (vector == null) {
        if (dimensionSize.length > 0) {
            throw MathRuntimeException.createIllegalArgumentException(
                    DIMENSION_MISMATCH_MESSAGE, 0, dimensionSize.length);
        }
        return null;
    }
    if (vector.length != dimensionSize.length) {
        throw MathRuntimeException.createIllegalArgumentException(
                DIMENSION_MISMATCH_MESSAGE, vector.length,dimensionSize.length);
    }

    Object[] lastDimension = (Object[]) multiDimensionalComplexArray;
    for (int i = 0; i < dimensionSize.length - 1; i++) {
        lastDimension = (Object[]) lastDimension[vector[i]];
    }

    Complex lastValue = (Complex) lastDimension[vector[dimensionSize.length - 1]];
    lastDimension[vector[dimensionSize.length - 1]] = magnitude;

    return lastValue;
}
 
Example #2
Source File: TestUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Fails iff values does not contain a number within epsilon of z.
 *
 * @param msg  message to return with failure
 * @param values complex array to search
 * @param z  value sought
 * @param epsilon  tolerance
 */
public static void assertContains(String msg, Complex[] values,
        Complex z, double epsilon) {
    int i = 0;
    boolean found = false;
    while (!found && i < values.length) {
        try {
            assertEquals(values[i], z, epsilon);
            found = true;
        } catch (AssertionFailedError er) {
            // no match
        }
        i++;
    }
    if (!found) {
        Assert.fail(msg +
            " Unable to find " + ComplexFormat.formatComplex(z));
    }
}
 
Example #3
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get a matrix element.
 * @param vector indices of the element
 * @return matrix element
 * @exception IllegalArgumentException if dimensions do not match
 */
public Complex get(int... vector)
    throws IllegalArgumentException {
    if (vector == null) {
        if (dimensionSize.length > 0) {
            throw MathRuntimeException.createIllegalArgumentException(
                    DIMENSION_MISMATCH_MESSAGE, 0, dimensionSize.length);
        }
        return null;
    }
    if (vector.length != dimensionSize.length) {
        throw MathRuntimeException.createIllegalArgumentException(
                DIMENSION_MISMATCH_MESSAGE, vector.length, dimensionSize.length);
    }

    Object lastDimension = multiDimensionalComplexArray;

    for (int i = 0; i < dimensionSize.length; i++) {
        lastDimension = ((Object[]) lastDimension)[vector[i]];
    }
    return (Complex) lastDimension;
}
 
Example #4
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get a matrix element.
 * @param vector indices of the element
 * @return matrix element
 * @exception IllegalArgumentException if dimensions do not match
 */
public Complex get(int... vector)
    throws IllegalArgumentException {
    if (vector == null) {
        if (dimensionSize.length > 0) {
            throw MathRuntimeException.createIllegalArgumentException(
                    DIMENSION_MISMATCH_MESSAGE, 0, dimensionSize.length);
        }
        return null;
    }
    if (vector.length != dimensionSize.length) {
        throw MathRuntimeException.createIllegalArgumentException(
                DIMENSION_MISMATCH_MESSAGE, vector.length, dimensionSize.length);
    }

    Object lastDimension = multiDimensionalComplexArray;

    for (int i = 0; i < dimensionSize.length; i++) {
        lastDimension = ((Object[]) lastDimension)[vector[i]];
    }
    return (Complex) lastDimension;
}
 
Example #5
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set a matrix element.
 * @param magnitude magnitude of the element
 * @param vector indices of the element
 * @return the previous value
 * @exception IllegalArgumentException if dimensions do not match
 */
public Complex set(Complex magnitude, int... vector)
    throws IllegalArgumentException {
    if (vector == null) {
        if (dimensionSize.length > 0) {
            throw MathRuntimeException.createIllegalArgumentException(
                    DIMENSION_MISMATCH_MESSAGE, 0, dimensionSize.length);
        }
        return null;
    }
    if (vector.length != dimensionSize.length) {
        throw MathRuntimeException.createIllegalArgumentException(
                DIMENSION_MISMATCH_MESSAGE, vector.length,dimensionSize.length);
    }

    Object[] lastDimension = (Object[]) multiDimensionalComplexArray;
    for (int i = 0; i < dimensionSize.length - 1; i++) {
        lastDimension = (Object[]) lastDimension[vector[i]];
    }

    Complex lastValue = (Complex) lastDimension[vector[dimensionSize.length - 1]];
    lastDimension[vector[dimensionSize.length - 1]] = magnitude;

    return lastValue;
}
 
Example #6
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set a matrix element.
 * @param magnitude magnitude of the element
 * @param vector indices of the element
 * @return the previous value
 * @exception IllegalArgumentException if dimensions do not match
 */
public Complex set(Complex magnitude, int... vector)
    throws IllegalArgumentException {
    if (vector == null) {
        if (dimensionSize.length > 0) {
            throw MathRuntimeException.createIllegalArgumentException(
                    DIMENSION_MISMATCH_MESSAGE, 0, dimensionSize.length);
        }
        return null;
    }
    if (vector.length != dimensionSize.length) {
        throw MathRuntimeException.createIllegalArgumentException(
                DIMENSION_MISMATCH_MESSAGE, vector.length,dimensionSize.length);
    }

    Object[] lastDimension = (Object[]) multiDimensionalComplexArray;
    for (int i = 0; i < dimensionSize.length - 1; i++) {
        lastDimension = (Object[]) lastDimension[vector[i]];
    }

    Complex lastValue = (Complex) lastDimension[vector[dimensionSize.length - 1]];
    lastDimension[vector[dimensionSize.length - 1]] = magnitude;

    return lastValue;
}
 
Example #7
Source File: TestUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Fails iff values does not contain a number within epsilon of z.
 *
 * @param msg  message to return with failure
 * @param values complex array to search
 * @param z  value sought
 * @param epsilon  tolerance
 */
public static void assertContains(String msg, Complex[] values,
        Complex z, double epsilon) {
    int i = 0;
    boolean found = false;
    while (!found && i < values.length) {
        try {
            assertEquals(values[i], z, epsilon);
            found = true;
        } catch (AssertionFailedError er) {
            // no match
        }
        i++;
    }
    if (!found) {
        Assert.fail(msg +
            " Unable to find " + ComplexFormat.formatComplex(z));
    }
}
 
Example #8
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get a matrix element.
 * @param vector indices of the element
 * @return matrix element
 * @exception IllegalArgumentException if dimensions do not match
 */
public Complex get(int... vector)
    throws IllegalArgumentException {
    if (vector == null) {
        if (dimensionSize.length > 0) {
            throw MathRuntimeException.createIllegalArgumentException(
                    DIMENSION_MISMATCH_MESSAGE, 0, dimensionSize.length);
        }
        return null;
    }
    if (vector.length != dimensionSize.length) {
        throw MathRuntimeException.createIllegalArgumentException(
                DIMENSION_MISMATCH_MESSAGE, vector.length, dimensionSize.length);
    }

    Object lastDimension = multiDimensionalComplexArray;

    for (int i = 0; i < dimensionSize.length; i++) {
        lastDimension = ((Object[]) lastDimension)[vector[i]];
    }
    return (Complex) lastDimension;
}
 
Example #9
Source File: TestUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Fails iff values does not contain a number within epsilon of z.
 * 
 * @param msg  message to return with failure
 * @param values complex array to search
 * @param z  value sought
 * @param epsilon  tolerance
 */
public static void assertContains(String msg, Complex[] values,
        Complex z, double epsilon) {
    int i = 0;
    boolean found = false;
    while (!found && i < values.length) {
        try {
            assertEquals(values[i], z, epsilon);
            found = true; 
        } catch (AssertionFailedError er) {
            // no match
        }
        i++;
    }
    if (!found) {
        Assert.fail(msg + 
            " Unable to find " + ComplexFormat.formatComplex(z));
    }
}
 
Example #10
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set a matrix element.
 * @param magnitude magnitude of the element
 * @param vector indices of the element
 * @return the previous value
 * @exception IllegalArgumentException if dimensions do not match
 */
public Complex set(Complex magnitude, int... vector)
    throws IllegalArgumentException {
    if (vector == null) {
        if (dimensionSize.length > 0) {
            throw MathRuntimeException.createIllegalArgumentException(
                    LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE, 0, dimensionSize.length);
        }
        return null;
    }
    if (vector.length != dimensionSize.length) {
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE, vector.length,dimensionSize.length);
    }

    Object[] lastDimension = (Object[]) multiDimensionalComplexArray;
    for (int i = 0; i < dimensionSize.length - 1; i++) {
        lastDimension = (Object[]) lastDimension[vector[i]];
    }

    Complex lastValue = (Complex) lastDimension[vector[dimensionSize.length - 1]];
    lastDimension[vector[dimensionSize.length - 1]] = magnitude;

    return lastValue;
}
 
Example #11
Source File: TestUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Fails iff values does not contain a number within epsilon of z.
 * 
 * @param msg  message to return with failure
 * @param values complex array to search
 * @param z  value sought
 * @param epsilon  tolerance
 */
public static void assertContains(String msg, Complex[] values,
        Complex z, double epsilon) {
    int i = 0;
    boolean found = false;
    while (!found && i < values.length) {
        try {
            assertEquals(values[i], z, epsilon);
            found = true; 
        } catch (AssertionFailedError er) {
            // no match
        }
        i++;
    }
    if (!found) {
        Assert.fail(msg + 
            " Unable to find " + ComplexFormat.formatComplex(z));
    }
}
 
Example #12
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Set a matrix element.
 * @param magnitude magnitude of the element
 * @param vector indices of the element
 * @return the previous value
 * @exception IllegalArgumentException if dimensions do not match
 */
public Complex set(Complex magnitude, int... vector)
    throws IllegalArgumentException {
    if (vector == null) {
        if (dimensionSize.length > 0) {
            throw MathRuntimeException.createIllegalArgumentException(
                    LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE, 0, dimensionSize.length);
        }
        return null;
    }
    if (vector.length != dimensionSize.length) {
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.DIMENSIONS_MISMATCH_SIMPLE, vector.length,dimensionSize.length);
    }

    Object[] lastDimension = (Object[]) multiDimensionalComplexArray;
    for (int i = 0; i < dimensionSize.length - 1; i++) {
        lastDimension = (Object[]) lastDimension[vector[i]];
    }

    Complex lastValue = (Complex) lastDimension[vector[dimensionSize.length - 1]];
    lastDimension[vector[dimensionSize.length - 1]] = magnitude;

    return lastValue;
}
 
Example #13
Source File: LaguerreSolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find all complex roots for the polynomial with the given coefficients,
 * starting from the given initial value.
 *
 * @param coefficients the polynomial coefficients array
 * @param initial the start value to use
 * @return the point at which the function value is zero
 * @throws MaxIterationsExceededException if the maximum iteration count is exceeded
 * or the solver detects convergence problems otherwise
 * @throws FunctionEvaluationException if an error occurs evaluating the
 * function
 * @throws IllegalArgumentException if any parameters are invalid
 */
public Complex[] solveAll(Complex coefficients[], Complex initial) throws
    MaxIterationsExceededException, FunctionEvaluationException {

    int n = coefficients.length - 1;
    int iterationCount = 0;
    if (n < 1) {
        throw MathRuntimeException.createIllegalArgumentException(
              LocalizedFormats.NON_POSITIVE_POLYNOMIAL_DEGREE, n);
    }
    Complex c[] = new Complex[n+1];    // coefficients for deflated polynomial
    for (int i = 0; i <= n; i++) {
        c[i] = coefficients[i];
    }

    // solve individual root successively
    Complex root[] = new Complex[n];
    for (int i = 0; i < n; i++) {
        Complex subarray[] = new Complex[n-i+1];
        System.arraycopy(c, 0, subarray, 0, subarray.length);
        root[i] = solve(subarray, initial);
        // polynomial deflation using synthetic division
        Complex newc = c[n-i];
        Complex oldc = null;
        for (int j = n-i-1; j >= 0; j--) {
            oldc = c[j];
            c[j] = newc;
            newc = oldc.add(newc.multiply(root[i]));
        }
        iterationCount += this.iterationCount;
    }

    resultComputed = true;
    this.iterationCount = iterationCount;
    return root;
}
 
Example #14
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Object clone() {
    MultiDimensionalComplexMatrix mdcm =
            new MultiDimensionalComplexMatrix(Array.newInstance(
            Complex.class, dimensionSize));
    clone(mdcm);
    return mdcm;
}
 
Example #15
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Object clone() {
    MultiDimensionalComplexMatrix mdcm =
            new MultiDimensionalComplexMatrix(Array.newInstance(
            Complex.class, dimensionSize));
    clone(mdcm);
    return mdcm;
}
 
Example #16
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform the base-4 Cooley-Tukey FFT algorithm (including inverse).
 *
 * @param f the real data array to be transformed
 * @param isInverse the indicator of forward or inverse transform
 * @return the complex transformed array
 * @throws IllegalArgumentException if any parameters are invalid
 */
protected Complex[] fft(double f[], boolean isInverse)
    throws IllegalArgumentException {

    verifyDataSet(f);
    Complex F[] = new Complex[f.length];
    if (f.length == 1) {
        F[0] = new Complex(f[0], 0.0);
        return F;
    }

    // Rather than the naive real to complex conversion, pack 2N
    // real numbers into N complex numbers for better performance.
    int N = f.length >> 1;
    Complex c[] = new Complex[N];
    for (int i = 0; i < N; i++) {
        c[i] = new Complex(f[2*i], f[2*i+1]);
    }
    roots.computeOmega(isInverse ? -N : N);
    Complex z[] = fft(c);

    // reconstruct the FFT result for the original array
    roots.computeOmega(isInverse ? -2*N : 2*N);
    F[0] = new Complex(2 * (z[0].getReal() + z[0].getImaginary()), 0.0);
    F[N] = new Complex(2 * (z[0].getReal() - z[0].getImaginary()), 0.0);
    for (int i = 1; i < N; i++) {
        Complex A = z[N-i].conjugate();
        Complex B = z[i].add(A);
        Complex C = z[i].subtract(A);
        //Complex D = roots.getOmega(i).multiply(Complex.I);
        Complex D = new Complex(-roots.getOmegaImaginary(i),
                                roots.getOmegaReal(i));
        F[i] = B.subtract(C.multiply(D));
        F[2*N-i] = F[i].conjugate();
    }

    return scaleArray(F, 0.5);
}
 
Example #17
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Object clone() {
    MultiDimensionalComplexMatrix mdcm =
            new MultiDimensionalComplexMatrix(Array.newInstance(
            Complex.class, dimensionSize));
    clone(mdcm);
    return mdcm;
}
 
Example #18
Source File: LaguerreSolver.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find a real root in the given interval.
 * <p>
 * Despite the bracketing condition, the root returned by solve(Complex[],
 * Complex) may not be a real zero inside [min, max]. For example,
 * p(x) = x^3 + 1, min = -2, max = 2, initial = 0. We can either try
 * another initial value, or, as we did here, call solveAll() to obtain
 * all roots and pick up the one that we're looking for.</p>
 *
 * @param f the function to solve
 * @param min the lower bound for the interval
 * @param max the upper bound for the interval
 * @return the point at which the function value is zero
 * @throws ConvergenceException if the maximum iteration count is exceeded
 * or the solver detects convergence problems otherwise
 * @throws FunctionEvaluationException if an error occurs evaluating the
 * function 
 * @throws IllegalArgumentException if any parameters are invalid
 */
public double solve(final UnivariateRealFunction f,
                    final double min, final double max)
    throws ConvergenceException, FunctionEvaluationException {

    // check function type
    if (!(f instanceof PolynomialFunction)) {
        throw MathRuntimeException.createIllegalArgumentException("function is not polynomial");
    }

    // check for zeros before verifying bracketing
    if (f.value(min) == 0.0) { return min; }
    if (f.value(max) == 0.0) { return max; }
    verifyBracketing(min, max, f);

    double coefficients[] = ((PolynomialFunction) f).getCoefficients();
    Complex c[] = new Complex[coefficients.length];
    for (int i = 0; i < coefficients.length; i++) {
        c[i] = new Complex(coefficients[i], 0.0);
    }
    Complex initial = new Complex(0.5 * (min + max), 0.0);
    Complex z = solve(c, initial);
    if (isRootOK(min, max, z)) {
        setResult(z.getReal(), iterationCount);
        return result;
    }

    // solve all roots and select the one we're seeking
    Complex[] root = solveAll(c, initial);
    for (int i = 0; i < root.length; i++) {
        if (isRootOK(min, max, root[i])) {
            setResult(root[i].getReal(), iterationCount);
            return result;
        }
    }

    // should never happen
    throw new ConvergenceException();
}
 
Example #19
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Object clone() {
    MultiDimensionalComplexMatrix mdcm =
            new MultiDimensionalComplexMatrix(Array.newInstance(
            Complex.class, dimensionSize));
    clone(mdcm);
    return mdcm;
}
 
Example #20
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform the base-4 Cooley-Tukey FFT algorithm (including inverse).
 *
 * @param f the real data array to be transformed
 * @param isInverse the indicator of forward or inverse transform
 * @return the complex transformed array
 * @throws IllegalArgumentException if any parameters are invalid
 */
protected Complex[] fft(double f[], boolean isInverse)
    throws IllegalArgumentException {

    verifyDataSet(f);
    Complex F[] = new Complex[f.length];
    if (f.length == 1) {
        F[0] = new Complex(f[0], 0.0);
        return F;
    }

    // Rather than the naive real to complex conversion, pack 2N
    // real numbers into N complex numbers for better performance.
    int N = f.length >> 1;
    Complex c[] = new Complex[N];
    for (int i = 0; i < N; i++) {
        c[i] = new Complex(f[2*i], f[2*i+1]);
    }
    roots.computeOmega(isInverse ? -N : N);
    Complex z[] = fft(c);

    // reconstruct the FFT result for the original array
    roots.computeOmega(isInverse ? -2*N : 2*N);
    F[0] = new Complex(2 * (z[0].getReal() + z[0].getImaginary()), 0.0);
    F[N] = new Complex(2 * (z[0].getReal() - z[0].getImaginary()), 0.0);
    for (int i = 1; i < N; i++) {
        Complex A = z[N-i].conjugate();
        Complex B = z[i].add(A);
        Complex C = z[i].subtract(A);
        //Complex D = roots.getOmega(i).multiply(Complex.I);
        Complex D = new Complex(-roots.getOmegaImaginary(i),
                                roots.getOmegaReal(i));
        F[i] = B.subtract(C.multiply(D));
        F[2*N-i] = F[i].conjugate();
    }

    return scaleArray(F, 0.5);
}
 
Example #21
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Object clone() {
    MultiDimensionalComplexMatrix mdcm =
            new MultiDimensionalComplexMatrix(Array.newInstance(
            Complex.class, dimensionSize));
    clone(mdcm);
    return mdcm;
}
 
Example #22
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Object clone() {
    MultiDimensionalComplexMatrix mdcm =
            new MultiDimensionalComplexMatrix(Array.newInstance(
            Complex.class, dimensionSize));
    clone(mdcm);
    return mdcm;
}
 
Example #23
Source File: TestUtils.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Fails iff values does not contain a number within epsilon of z.
 *
 * @param msg  message to return with failure
 * @param values complex array to search
 * @param z  value sought
 * @param epsilon  tolerance
 */
public static void assertContains(String msg, Complex[] values,
                                  Complex z, double epsilon) {
    for (Complex value : values) {
        if (MathUtils.equals(value.getReal(), z.getReal(), epsilon) &&
            MathUtils.equals(value.getImaginary(), z.getImaginary(), epsilon)) {
            return;
        }
    }
    Assert.fail(msg + " Unable to find " + (new ComplexFormat()).format(z));
}
 
Example #24
Source File: FastSineTransformer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform the FST algorithm (including inverse).
 *
 * @param f the real data array to be transformed
 * @return the real transformed array
 * @throws IllegalArgumentException if any parameters are invalid
 */
protected double[] fst(double f[]) throws IllegalArgumentException {

    final double transformed[] = new double[f.length];

    FastFourierTransformer.verifyDataSet(f);
    if (f[0] != 0.0) {
        throw MathRuntimeException.createIllegalArgumentException(
                "first element is not 0: {0}",
                f[0]);
    }
    final int n = f.length;
    if (n == 1) {       // trivial case
        transformed[0] = 0.0;
        return transformed;
    }

    // construct a new array and perform FFT on it
    final double[] x = new double[n];
    x[0] = 0.0;
    x[n >> 1] = 2.0 * f[n >> 1];
    for (int i = 1; i < (n >> 1); i++) {
        final double a = Math.sin(i * Math.PI / n) * (f[i] + f[n-i]);
        final double b = 0.5 * (f[i] - f[n-i]);
        x[i]     = a + b;
        x[n - i] = a - b;
    }
    FastFourierTransformer transformer = new FastFourierTransformer();
    Complex y[] = transformer.transform(x);

    // reconstruct the FST result for the original array
    transformed[0] = 0.0;
    transformed[1] = 0.5 * y[0].getReal();
    for (int i = 1; i < (n >> 1); i++) {
        transformed[2 * i]     = -y[i].getImaginary();
        transformed[2 * i + 1] = y[i].getReal() + transformed[2 * i - 1];
    }

    return transformed;
}
 
Example #25
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Perform the base-4 Cooley-Tukey FFT algorithm (including inverse).
 *
 * @param data the complex data array to be transformed
 * @return the complex transformed array
 * @throws IllegalArgumentException if any parameters are invalid
 */
protected Complex[] fft(Complex data[])
    throws IllegalArgumentException {

    final int n = data.length;
    final Complex f[] = new Complex[n];

    // initial simple cases
    verifyDataSet(data);
    if (n == 1) {
        f[0] = data[0];
        return f;
    }
    if (n == 2) {
        f[0] = data[0].add(data[1]);
        f[1] = data[0].subtract(data[1]);
        return f;
    }

    // permute original data array in bit-reversal order
    int ii = 0;
    for (int i = 0; i < n; i++) {
        f[i] = data[ii];
        int k = n >> 1;
        while (ii >= k && k > 0) {
            ii -= k; k >>= 1;
        }
        ii += k;
    }

    // the bottom base-4 round
    for (int i = 0; i < n; i += 4) {
        final Complex a = f[i].add(f[i+1]);
        final Complex b = f[i+2].add(f[i+3]);
        final Complex c = f[i].subtract(f[i+1]);
        final Complex d = f[i+2].subtract(f[i+3]);
        final Complex e1 = c.add(d.multiply(Complex.I));
        final Complex e2 = c.subtract(d.multiply(Complex.I));
        f[i] = a.add(b);
        f[i+2] = a.subtract(b);
        // omegaCount indicates forward or inverse transform
        f[i+1] = roots.isForward() ? e2 : e1;
        f[i+3] = roots.isForward() ? e1 : e2;
    }

    // iterations from bottom to top take O(N*logN) time
    for (int i = 4; i < n; i <<= 1) {
        final int m = n / (i<<1);
        for (int j = 0; j < n; j += i<<1) {
            for (int k = 0; k < i; k++) {
                //z = f[i+j+k].multiply(roots.getOmega(k*m));
                final int k_times_m = k*m;
                final double omega_k_times_m_real = roots.getOmegaReal(k_times_m);
                final double omega_k_times_m_imaginary = roots.getOmegaImaginary(k_times_m);
                //z = f[i+j+k].multiply(omega[k*m]);
                final Complex z = new Complex(
                    f[i+j+k].getReal() * omega_k_times_m_real -
                    f[i+j+k].getImaginary() * omega_k_times_m_imaginary,
                    f[i+j+k].getReal() * omega_k_times_m_imaginary +
                    f[i+j+k].getImaginary() * omega_k_times_m_real);

                f[i+j+k] = f[j+k].subtract(z);
                f[j+k] = f[j+k].add(z);
            }
        }
    }
    return f;
}
 
Example #26
Source File: TestUtils.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Verifies that real and imaginary parts of the two complex arguments
 * differ by at most delta.  Also ensures that NaN / infinite components match.
 */
public static void assertEquals(Complex expected, Complex actual, double delta) {
    assertEquals(expected.getReal(), actual.getReal(), delta);
    assertEquals(expected.getImaginary(), actual.getImaginary(), delta);
}
 
Example #27
Source File: TestUtils.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Verifies that real and imaginary parts of the two complex arguments
 * differ by at most delta.  Also ensures that NaN / infinite components match.
 */
public static void assertEquals(Complex expected, Complex actual, double delta) {
    assertEquals(expected.getReal(), actual.getReal(), delta);
    assertEquals(expected.getImaginary(), actual.getImaginary(), delta);
}
 
Example #28
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Performs one dimension of a multi-dimensional Fourier transform.
 *
 * @param mdcm input matrix
 * @param forward inverseTransform2 is preformed if this is false
 * @param d index of the dimension to process
 * @param subVector recursion subvector
 * @throws IllegalArgumentException if any dimension is not a power of two
 */
private void mdfft(MultiDimensionalComplexMatrix mdcm, boolean forward,
                   int d, int[] subVector)
    throws IllegalArgumentException {
    int[] dimensionSize = mdcm.getDimensionSizes();
    //if done
    if (subVector.length == dimensionSize.length) {
        Complex[] temp = new Complex[dimensionSize[d]];
        for (int i = 0; i < dimensionSize[d]; i++) {
            //fft along dimension d
            subVector[d] = i;
            temp[i] = mdcm.get(subVector);
        }
        
        if (forward)
            temp = transform2(temp);
        else
            temp = inversetransform2(temp);
        
        for (int i = 0; i < dimensionSize[d]; i++) {
            subVector[d] = i;
            mdcm.set(temp[i], subVector);
        }
    } else {
        int[] vector = new int[subVector.length + 1];
        System.arraycopy(subVector, 0, vector, 0, subVector.length);
        if (subVector.length == d) {
            //value is not important once the recursion is done.
            //then an fft will be applied along the dimension d.
            vector[d] = 0;
            mdfft(mdcm, forward, d, vector);
        } else {
            for (int i = 0; i < dimensionSize[subVector.length]; i++) {
                vector[subVector.length] = i;
                //further split along the next dimension
                mdfft(mdcm, forward, d, vector);
            }
        }
    }
    return;
}
 
Example #29
Source File: FastCosineTransformer.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Perform the FCT algorithm (including inverse).
 *
 * @param f the real data array to be transformed
 * @return the real transformed array
 * @throws IllegalArgumentException if any parameters are invalid
 */
protected double[] fct(double f[])
    throws IllegalArgumentException {

    final double transformed[] = new double[f.length];

    final int n = f.length - 1;
    if (!FastFourierTransformer.isPowerOf2(n)) {
        throw MathRuntimeException.createIllegalArgumentException(
                "{0} is not a power of 2 plus one",
                f.length);
    }
    if (n == 1) {       // trivial case
        transformed[0] = 0.5 * (f[0] + f[1]);
        transformed[1] = 0.5 * (f[0] - f[1]);
        return transformed;
    }

    // construct a new array and perform FFT on it
    final double[] x = new double[n];
    x[0] = 0.5 * (f[0] + f[n]);
    x[n >> 1] = f[n >> 1];
    double t1 = 0.5 * (f[0] - f[n]);   // temporary variable for transformed[1]
    for (int i = 1; i < (n >> 1); i++) {
        final double a = 0.5 * (f[i] + f[n-i]);
        final double b = Math.sin(i * Math.PI / n) * (f[i] - f[n-i]);
        final double c = Math.cos(i * Math.PI / n) * (f[i] - f[n-i]);
        x[i] = a - b;
        x[n-i] = a + b;
        t1 += c;
    }
    FastFourierTransformer transformer = new FastFourierTransformer();
    Complex y[] = transformer.transform(x);

    // reconstruct the FCT result for the original array
    transformed[0] = y[0].getReal();
    transformed[1] = t1;
    for (int i = 1; i < (n >> 1); i++) {
        transformed[2 * i]     = y[i].getReal();
        transformed[2 * i + 1] = transformed[2 * i - 1] - y[i].getImaginary();
    }
    transformed[n] = y[n >> 1].getReal();

    return transformed;
}
 
Example #30
Source File: FastCosineTransformer.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Perform the FCT algorithm (including inverse).
 *
 * @param f the real data array to be transformed
 * @return the real transformed array
 * @throws IllegalArgumentException if any parameters are invalid
 */
protected double[] fct(double f[])
    throws IllegalArgumentException {

    final double transformed[] = new double[f.length];

    final int n = f.length - 1;
    if (!FastFourierTransformer.isPowerOf2(n)) {
        throw MathRuntimeException.createIllegalArgumentException(
                LocalizedFormats.NOT_POWER_OF_TWO_PLUS_ONE,
                f.length);
    }
    if (n == 1) {       // trivial case
        transformed[0] = 0.5 * (f[0] + f[1]);
        transformed[1] = 0.5 * (f[0] - f[1]);
        return transformed;
    }

    // construct a new array and perform FFT on it
    final double[] x = new double[n];
    x[0] = 0.5 * (f[0] + f[n]);
    x[n >> 1] = f[n >> 1];
    double t1 = 0.5 * (f[0] - f[n]);   // temporary variable for transformed[1]
    for (int i = 1; i < (n >> 1); i++) {
        final double a = 0.5 * (f[i] + f[n-i]);
        final double b = FastMath.sin(i * FastMath.PI / n) * (f[i] - f[n-i]);
        final double c = FastMath.cos(i * FastMath.PI / n) * (f[i] - f[n-i]);
        x[i] = a - b;
        x[n-i] = a + b;
        t1 += c;
    }
    FastFourierTransformer transformer = new FastFourierTransformer();
    Complex y[] = transformer.transform(x);

    // reconstruct the FCT result for the original array
    transformed[0] = y[0].getReal();
    transformed[1] = t1;
    for (int i = 1; i < (n >> 1); i++) {
        transformed[2 * i]     = y[i].getReal();
        transformed[2 * i + 1] = transformed[2 * i - 1] - y[i].getImaginary();
    }
    transformed[n] = y[n >> 1].getReal();

    return transformed;
}