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

The following examples show how to use org.apache.commons.math3.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: ComplexFFT_1D.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
public static Complex[] convolve(final Complex[] x, final Complex[] y) {
    final Complex ZERO = new Complex(0, 0);

    final Complex[] a = new Complex[2 * x.length];
    for (int i = 0; i < x.length; i++) {
        a[i] = x[i];
    }
    for (int i = x.length; i < 2 * x.length; i++) {
        a[i] = ZERO;
    }

    final Complex[] b = new Complex[2 * y.length];
    for (int i = 0; i < y.length; i++) {
        b[i] = y[i];
    }
    for (int i = y.length; i < 2 * y.length; i++) {
        b[i] = ZERO;
    }

    return cconvolve(a, b);
}
 
Example #2
Source File: TransformUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Builds a new array of {@link Complex} from the specified two dimensional
 * array of real and imaginary parts. In the returned array {@code dataC},
 * the data is laid out as follows
 * <ul>
 * <li>{@code dataC[i].getReal() = dataRI[0][i]},</li>
 * <li>{@code dataC[i].getImaginary() = dataRI[1][i]}.</li>
 * </ul>
 *
 * @param dataRI the array of real and imaginary parts to be transformed
 * @return an array of {@link Complex} with specified real and imaginary parts.
 * @throws DimensionMismatchException if the number of rows of the specified
 *   array is not two, or the array is not rectangular
 */
public static Complex[] createComplexArray(final double[][] dataRI)
    throws DimensionMismatchException{

    if (dataRI.length != 2) {
        throw new DimensionMismatchException(dataRI.length, 2);
    }
    final double[] dataR = dataRI[0];
    final double[] dataI = dataRI[1];
    if (dataR.length != dataI.length) {
        throw new DimensionMismatchException(dataI.length, dataR.length);
    }

    final int n = dataR.length;
    final Complex[] c = new Complex[n];
    for (int i = 0; i < n; i++) {
        c[i] = new Complex(dataR[i], dataI[i]);
    }
    return c;
}
 
Example #3
Source File: ZernikeMoments.java    From cineast with MIT License 6 votes vote down vote up
/**
 * Compute Zernike moments at specified order.
 *
 * @param w Width of the bounding box of the shape.
 * @param h Height of the bounding box of the shape.
 * @param n 1st order of the moment.
 * @param m 2nd order of the moment.
 *
 * @return Zernike moment of data in f[][].
 */
public static Complex calculateZernikeMoment(double[][] f, int w, int h, int n, int m){
    int diff = n-Math.abs(m);
    if ((n<0) || (Math.abs(m) > n) || (diff%2!=0)){
        throw new IllegalArgumentException("zer_mom: n="+n+", m="+m+", n-|m|="+diff);
    }

    final double c = -1;
    final double d = 1;


    ZernikeBasisFunction zernike = new ZernikeBasisFunction(n,m);
    Complex res = new Complex(0.0, 0.0);
    for (int i=0;i<w;i++){
        for (int j=0;j<h;j++) {
            Complex v = new Complex(c+(i*(d-c))/(w-1), d-(j*(d-c))/(h-1));
            res = res.add(zernike.value(v).conjugate().multiply(f[i][j]));
        }
    }

    return res.multiply((n+1)/Math.PI);
}
 
Example #4
Source File: AbstractFourierTransformProduct.java    From finmath-lib with Apache License 2.0 6 votes vote down vote up
@Override
public double getValue(final CharacteristicFunctionModel model) throws CalculationException {

	final CharacteristicFunction modelCF = model.apply(getMaturity());

	final double lineOfIntegration = 0.5 * getIntegrationDomainImagUpperBound()+getIntegrationDomainImagLowerBound();
	final DoubleUnaryOperator integrand = new DoubleUnaryOperator() {
		@Override
		public double applyAsDouble(final double real) {
			final Complex z = new Complex(real,lineOfIntegration);
			return modelCF.apply(z.negate()).multiply(AbstractFourierTransformProduct.this.apply(z)).getReal();
		}
	};

	final RealIntegral integrator = new SimpsonRealIntegrator(-100.0, 100.0, 20000, true);

	return integrator.integrate(integrand) / 2.0 / Math.PI;
}
 
Example #5
Source File: LoadFlowGenerator.java    From DeepMachineLearning with Apache License 2.0 6 votes vote down vote up
public LoadFlowGenerator(RefInfo refInfo) {
	super(refInfo);
	long startTime = System.currentTimeMillis();
	this.methodName = NAME;
	System.out.print("[REPORT] new "+methodName+"...");
	
	this.noBus = ref.getNoBus();
	this.yc = new Complex[noBus][noBus];
	
	Complex[][] y = ref.getY();
	for (int i=0; i<noBus; ++i)
		for (int j=0; j<noBus; ++j) 
			this.yc[i][j] = new Complex(y[i][j].getReal(), 0 - y[i][j].getImaginary());//ȡ����
	
	AclfCase.init(this);
	//report
	System.out.println(" ...ready. Need to input parameter: "+PARA_NEEDED);
	addInitTime(startTime);
}
 
Example #6
Source File: Autocorrelation.java    From macrobase with Apache License 2.0 6 votes vote down vote up
public void evaluate(List<Datum> data) {
    double[] values = formatData(data);
    // FFT
    Complex[] fft = fftTran.transform(values, TransformType.FORWARD);
    // Multiply by complex conjugate
    for (int i = 0; i < fft.length; i ++) {
        fft[i] = fft[i].multiply(fft[i].conjugate());
    }
    // Inverse transform
    fft = fftTran.transform(fft, TransformType.INVERSE);

    correlations = new double[maxLag];
    for (int i = 1; i < maxLag; i++) {
        correlations[i] = fft[i].getReal() / fft[0].getReal();
    }
}
 
Example #7
Source File: Biquad.java    From iirj with Apache License 2.0 6 votes vote down vote up
public Complex response(double normalizedFrequency) {
    double a0 = getA0();
    double a1 = getA1();
    double a2 = getA2();
    double b0 = getB0();
    double b1 = getB1();
    double b2 = getB2();

    double w = 2 * Math.PI * normalizedFrequency;
    Complex czn1 = ComplexUtils.polar2Complex(1., -w);
    Complex czn2 = ComplexUtils.polar2Complex(1., -2 * w);
    Complex ch = new Complex(1);
    Complex cbot = new Complex(1);

    Complex ct = new Complex(b0 / a0);
    Complex cb = new Complex(1);
    ct = MathSupplement.addmul(ct, b1 / a0, czn1);
    ct = MathSupplement.addmul(ct, b2 / a0, czn2);
    cb = MathSupplement.addmul(cb, a1 / a0, czn1);
    cb = MathSupplement.addmul(cb, a2 / a0, czn2);
    ch = ch.multiply(ct);
    cbot = cbot.multiply(cb);

    return ch.divide(cbot);
}
 
Example #8
Source File: DTypeUtils.java    From january with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @param b
 * @return length of object
 */
public static final int getLength(final Object b) {
	if (b instanceof Number) {
		return 1;
	} else if (b instanceof Complex) {
		return 1;
	} else if (b instanceof List<?>) {
		List<?> jl = (List<?>) b;
		return jl.size();
	} else if (b.getClass().isArray()) {
		return Array.getLength(b);
	} else if (b instanceof IDataset) {
		IDataset db = (Dataset) b;
		return db.getSize();
	}

	throw new IllegalArgumentException("Cannot find length as object not supported");
}
 
Example #9
Source File: BandPassTransform.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
private static ComplexPair transform(final Complex in, final double a, final double b) {
    if (in.isInfinite()) {
        return new ComplexPair(new Complex(-1), new Complex(1));
    }

    final Complex c = new Complex(1).add(in).divide(new Complex(1).subtract(in)); // bilinear

    final double a2 = a * a;
    final double b2 = b * b;
    final double ab = a * b;
    final double ab2 = 2 * ab;
    Complex v = new Complex(0).add(c.multiply(4 * (b2 * (a2 - 1) + 1)));
    v = v.add(8 * (b2 * (a2 - 1) - 1));
    v = v.multiply(c);
    v = v.add(4 * (b2 * (a2 - 1) + 1));
    v = v.sqrt();

    final Complex u = v.multiply(-1).add(c.multiply(ab2)).add(ab2);

    v = v.add(c.multiply(ab2)).add(ab2);

    final Complex d = new Complex(0).add(c.multiply(2 * (b - 1))).add(2 * (1 + b));

    return new ComplexPair(u.divide(d), v.divide(d));
}
 
Example #10
Source File: Bessel.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
public void design() {
    reset();

    for (int i = 0; i < degree + 1; ++i) {
        mA[i] = reversebessel(i, degree);
    }

    final LaguerreSolver laguerreSolver = new LaguerreSolver();

    mRoot = laguerreSolver.solveAllComplex(mA, 0.0);

    final Complex inf = Complex.INF;
    final int pairs = degree / 2;
    for (int i = 0; i < pairs; ++i) {
        final Complex c = mRoot[i];
        addPoleZeroConjugatePairs(c, inf);
    }

    if ((degree & 1) == 1) {
        add(new Complex(mRoot[pairs].getReal()), inf);
    }
}
 
Example #11
Source File: ChebyshevI.java    From chart-fx with Apache License 2.0 6 votes vote down vote up
public void design(final double rippleDb) {
    reset();

    final double eps = Math.sqrt(1. / Math.exp(-rippleDb * 0.1 * Math.log(10)) - 1);
    final double v0 = FastMath.asinh(1 / eps) / nPoles;
    final double sinhv0 = -Math.sinh(v0);
    final double coshv0 = Math.cosh(v0);

    final double n2 = 2.0 * nPoles;
    final int pairs = nPoles / 2;
    for (int i = 0; i < pairs; ++i) {
        final int k = 2 * i + 1 - nPoles;
        final double a = sinhv0 * Math.cos(k * Math.PI / n2);
        final double b = coshv0 * Math.sin(k * Math.PI / n2);

        addPoleZeroConjugatePairs(new Complex(a, b), new Complex(Double.POSITIVE_INFINITY)); // NOPMD
    }

    if ((nPoles & 1) == 1) {
        add(new Complex(sinhv0, 0), new Complex(Double.POSITIVE_INFINITY));
        setNormal(0, 1);
    } else {
        setNormal(0, Math.pow(10, -rippleDb / 20.));
    }
}
 
Example #12
Source File: AbstractFourierTransformProduct.java    From finmath-lib with Apache License 2.0 6 votes vote down vote up
@Override
public double getValue(final CharacteristicFunctionModel model) throws CalculationException {

	final CharacteristicFunction modelCF = model.apply(getMaturity());

	final double lineOfIntegration = 0.5 * getIntegrationDomainImagUpperBound()+getIntegrationDomainImagLowerBound();
	final DoubleUnaryOperator integrand = new DoubleUnaryOperator() {
		@Override
		public double applyAsDouble(final double real) {
			final Complex z = new Complex(real,lineOfIntegration);
			return modelCF.apply(z.negate()).multiply(AbstractFourierTransformProduct.this.apply(z)).getReal();
		}
	};

	final RealIntegral integrator = new SimpsonRealIntegrator(-100.0, 100.0, 20000, true);

	return integrator.integrate(integrand) / 2.0 / Math.PI;
}
 
Example #13
Source File: Matrix.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
  * Forward or Inverse *squared* fast fourier transform onto a particular axis
  *
* N.B. returns the squared complex fourier component!
*
  * @param axis      the axis (0 is rows, 1 is columns)
  * @param direction TransformType.FORWARD or TransformType.INVERSE
  * @return The new matrix with a fft or ifft applied to each row or column
  */
 public Matrix fft2(int axis, TransformType direction) {
     ParameterChecker.checkAxis(axis);

     FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD);
     double[][] ft = new double[this.getRowDimension()][this.getColumnDimension()];
     if (axis == 0) {
         for (int c = 0; c < this.getColumnDimension(); c++) {
             Complex[] complexResult = fft.transform(this.getColumn(c), direction);
             for (int i = 0; i < complexResult.length; i++)
                 ft[i][c] = complexResult[i].abs()*complexResult[i].abs();
         }
     } else {
	// TODO: This is inefficient....
         return this.transpose().fft2(0, direction).transpose();
     }
     return new Matrix(ft);
 }
 
Example #14
Source File: TransformUtils.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Builds a new array of {@link Complex} from the specified two dimensional
 * array of real and imaginary parts. In the returned array {@code dataC},
 * the data is laid out as follows
 * <ul>
 * <li>{@code dataC[i].getReal() = dataRI[0][i]},</li>
 * <li>{@code dataC[i].getImaginary() = dataRI[1][i]}.</li>
 * </ul>
 *
 * @param dataRI the array of real and imaginary parts to be transformed
 * @return an array of {@link Complex} with specified real and imaginary
 * parts.
 * @throws DimensionMismatchException if the number of rows of the specified
 * array is not two, or the array is not rectangular
 */
public static Complex[] createComplexArray(final double[][] dataRI)
    throws DimensionMismatchException{

    if (dataRI.length != 2) {
        throw new DimensionMismatchException(dataRI.length, 2);
    }
    final double[] dataR = dataRI[0];
    final double[] dataI = dataRI[1];
    if (dataR.length != dataI.length) {
        throw new DimensionMismatchException(dataI.length, dataR.length);
    }

    final int n = dataR.length;
    final Complex[] c = new Complex[n];
    for (int i = 0; i < n; i++) {
        c[i] = new Complex(dataR[i], dataI[i]);
    }
    return c;
}
 
Example #15
Source File: VoltageGenCondition.java    From DeepMachineLearning with Apache License 2.0 6 votes vote down vote up
private void BuildCondition(boolean isThVMethod, double[] p, boolean pIsFactor, double[] v, boolean vIsFactor, boolean isThV, int bitState, boolean isBit) {
	if (p != null) 
		this.p = p;
	else
		this.p = new double[ref.getNoBus()];
	this.pIsFactor = pIsFactor;
	if (v != null)
		this.v = v;
	else
		this.v = new double[ref.getNoBus()];
	this.voltage = new Complex[ref.getNoBus()];
	this.vIsFactor = vIsFactor;
	this.isThVMethod = isThVMethod;
	this.bitState = bitState;
	this.isBit = isBit;
}
 
Example #16
Source File: LfAdjust.java    From DeepMachineLearning with Apache License 2.0 6 votes vote down vote up
protected void go(double a) throws InterpssException{
	long startTime = System.currentTimeMillis();
	
	Complex[] voltage = genVoltage(a);
	AclfCase aclfCase = new AclfCase(voltage);
	
	specialBusChecker.correct(aclfCase);
	reportCase("After SBC", aclfCase);
	
	boolean successGen = true;
	while (!qChecker.correct(aclfCase)) {
		reportCase("After QC", aclfCase);
		specialBusChecker.correct(aclfCase);
		reportCase("After QC and SBC", aclfCase);
	}
	if (successGen) {
		successGenReaction(aclfCase);
	}
}
 
Example #17
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the (forward, inverse) transform of the specified real data set.
 *
 * @param f the real data array to be transformed
 * @param type the type of transform (forward, inverse) to be performed
 * @return the complex transformed array
 * @throws MathIllegalArgumentException if the length of the data array is not a power of two
 */
public Complex[] transform(final double[] f, final TransformType type) {
    final double[][] dataRI = new double[][] {
        MathArrays.copyOf(f, f.length), new double[f.length]
    };

    transformInPlace(dataRI, normalization, type);

    return TransformUtils.createComplexArray(dataRI);
}
 
Example #18
Source File: MertonModel.java    From finmath-lib with Apache License 2.0 5 votes vote down vote up
@Override
public CharacteristicFunction apply(final double time) {
	final double logDiscountFactorForForward		= this.getLogDiscountFactorForForward(time);
	final double logDiscountFactorForDiscounting	= this.getLogDiscountFactorForDiscounting(time);
	final double transformedMean =  jumpSizeMean - 0.5 * jumpSizeStdDev*jumpSizeStdDev;
	return new CharacteristicFunction() {
		@Override
		public Complex apply(final Complex argument) {
			final Complex iargument = argument.multiply(Complex.I);

			final Complex exponent = (iargument.multiply(transformedMean))
					.add(iargument.multiply(iargument.multiply(jumpSizeStdDev*jumpSizeStdDev/2.0)));

			final Complex jumpTransform = ((exponent.exp()).subtract(1.0)).multiply(jumpIntensity*time);

			final double jumpTransformCompensator = jumpIntensity*time*(Math.exp(transformedMean+jumpSizeStdDev*jumpSizeStdDev/2.0)-1.0);

			return	iargument
					.multiply(
							iargument
							.multiply(0.5*volatility*volatility*time)
							.add(Math.log(initialValue)-0.5*volatility*volatility*time-logDiscountFactorForForward))
					.add(logDiscountFactorForDiscounting).add(jumpTransform.subtract(jumpTransformCompensator))
					.exp();
		}
	};

}
 
Example #19
Source File: TwtData.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
private Complex calculateOneConnectedLegFlow(double u, double theta,
    LinkData.BranchAdmittanceMatrix admittanceMatrixLeg, LinkData.BranchAdmittanceMatrix admittanceMatrixFirstOpenLeg,
    LinkData.BranchAdmittanceMatrix admittanceMatrixSecondOpenLeg) {

    Complex ysh = calculateOneConnectedLegShunt(admittanceMatrixLeg,
        admittanceMatrixFirstOpenLeg, admittanceMatrixSecondOpenLeg);

    return LinkData.flowYshunt(ysh, u, theta);
}
 
Example #20
Source File: FastFourierTransformerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Naive implementation of DFT, for reference. */
private static Complex[] dft(final Complex[] x, final int sgn) {
    final int n = x.length;
    final double[] cos = new double[n];
    final double[] sin = new double[n];
    final Complex[] y = new Complex[n];
    for (int i = 0; i < n; i++) {
        final double arg = 2.0 * FastMath.PI * i / n;
        cos[i] = FastMath.cos(arg);
        sin[i] = FastMath.sin(arg);
    }
    for (int i = 0; i < n; i++) {
        double yr = 0.0;
        double yi = 0.0;
        for (int j = 0; j < n; j++) {
            final int index = (i * j) % n;
            final double c = cos[index];
            final double s = sin[index];
            final double xr = x[j].getReal();
            final double xi = x[j].getImaginary();
            yr += c * xr - sgn * s * xi;
            yi += sgn * s * xr + c * xi;
        }
        y[i] = new Complex(yr, yi);
    }
    return y;
}
 
Example #21
Source File: CpfCaseBuilder14.java    From DeepMachineLearning with Apache License 2.0 5 votes vote down vote up
public CpfCaseBuilder14(String baseCasePath) throws InterpssException {
	super(baseCasePath);
	long startTime = System.currentTimeMillis();
	platformName = NAME;
	nameInShort = NAME_IN_SHORT;
	System.out.print("[REPORT] new "+platformName+"...");
	
	timeUse = 0;
	initTimeUse = 0;
	callTimes = 0;
	totalIterTimes = 0;
	
	IpssCorePlugin.init();
	net = CorePluginFactory
			.getFileAdapter(IpssFileAdapter.FileFormat.IEEECDF)
			.load(baseCasePath)
			.getAclfNet();

	AclfNetwork net2 = CorePluginFactory
			.getFileAdapter(IpssFileAdapter.FileFormat.IEEECDF)
			.load(baseCasePath)
			.getAclfNet();
	k = gotoLimit2(net2);

	this.branchY = new Complex[5];
	Complex[][] y = refInfo.getY();
	this.branchY[0] = new Complex(y[0][1].getReal(), y[0][1].getImaginary());
	this.branchY[1] = new Complex(y[0][4].getReal(), y[0][4].getImaginary());
	this.branchY[2] = new Complex(y[1][2].getReal(), y[1][2].getImaginary());
	this.branchY[3] = new Complex(y[1][3].getReal(), y[1][3].getImaginary());
	this.branchY[4] = new Complex(y[1][4].getReal(), y[1][4].getImaginary());
	//report
	System.out.println(" ...ready.");
	addInitTime(startTime);
}
 
Example #22
Source File: FastFourierTransformerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private static Complex[] createComplexData(final int n) {
    final Random random = new Random(SEED);
    final Complex[] data = new Complex[n];
    for (int i = 0; i < n; i++) {
        final double re = 2.0 * random.nextDouble() - 1.0;
        final double im = 2.0 * random.nextDouble() - 1.0;
        data[i] = new Complex(re, im);
    }
    return data;
}
 
Example #23
Source File: VarianceGammaTest.java    From finmath-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void testCharacteristicFunction() {
	// The parameters
	final int seed			= 53252;
	final int numberOfFactors = 1;
	final int numberOfPaths	= 10000;
	final double lastTime		= 10;
	final double dt			= 0.1;

	// Create the time discretization
	final TimeDiscretization timeDiscretization = new TimeDiscretizationFromArray(0.0, (int)(lastTime/dt), dt);

	final double sigma = 0.25;
	final double nu = 0.1;
	final double theta = 0.4;

	final VarianceGammaProcess varianceGamma = new VarianceGammaProcess(sigma, nu, theta, timeDiscretization,
			numberOfFactors, numberOfPaths, seed);

	//Initialize process
	RandomVariable process = varianceGamma.getIncrement(0, 0).mult(0.0);

	final Complex z = new Complex(1.0,-1.0);

	//Sum over increments to construct the process path
	for(int i = 0; i< timeDiscretization.getNumberOfTimeSteps()-1; i++) {
		final Complex monteCarloCF = characteristicFunctionByMonteCarlo(z, process);

		final RandomVariable increment = varianceGamma.getIncrement(i, 0);
		process = process.add(increment);

		final Complex exactCF = getCharacteristicFunction(timeDiscretization.getTime(i),z,varianceGamma);

		System.out.println(formatterReal2.format(exactCF.getReal()) + "\t" +formatterReal2.format(exactCF.getImaginary())
		+ "\t" + "\t" + formatterReal2.format(monteCarloCF.getReal()) + "\t" +formatterReal2.format(monteCarloCF.getImaginary()));

	}
}
 
Example #24
Source File: FastFourierTransformerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private static void doTestTransformFunction(final UnivariateFunction f,
    final double min, final double max, int n, final double tol,
    final DftNormalization normalization,
    final TransformType type) {
    final FastFourierTransformer fft;
    fft = new FastFourierTransformer(normalization);
    final Complex[] x = new Complex[n];
    for (int i = 0; i < n; i++) {
        final double t = min + i * (max - min) / n;
        x[i] = new Complex(f.value(t));
    }
    final Complex[] expected;
    final double s;
    if (type == TransformType.FORWARD) {
        expected = dft(x, -1);
        if (normalization == DftNormalization.STANDARD) {
            s = 1.0;
        } else {
            s = 1.0 / FastMath.sqrt(n);
        }
    } else {
        expected = dft(x, 1);
        if (normalization == DftNormalization.STANDARD) {
            s = 1.0 / n;
        } else {
            s = 1.0 / FastMath.sqrt(n);
        }
    }
    final Complex[] actual = fft.transform(f, min, max, n, type);
    for (int i = 0; i < n; i++) {
        final String msg = String.format("%d, %d", n, i);
        final double re = s * expected[i].getReal();
        Assert.assertEquals(msg, re, actual[i].getReal(),
            tol * FastMath.abs(re));
        final double im = s * expected[i].getImaginary();
        Assert.assertEquals(msg, im, actual[i].getImaginary(), tol *
            FastMath.abs(re));
    }
}
 
Example #25
Source File: FastFourierTransformer.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Performs one dimension of a multi-dimensional Fourier transform.
 *
 * @param mdcm input matrix
 * @param type the type of transform (forward, inverse) to be performed
 * @param d index of the dimension to process
 * @param subVector recursion subvector
 * @throws IllegalArgumentException if any dimension is not a power of two
 * @deprecated see MATH-736
 */
@Deprecated
private void mdfft(MultiDimensionalComplexMatrix mdcm,
        TransformType type, int d, int[] subVector) {

    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);
        }

        temp = transform(temp, type);

        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, type, d, vector);
        } else {
            for (int i = 0; i < dimensionSize[subVector.length]; i++) {
                vector[subVector.length] = i;
                //further split along the next dimension
                mdfft(mdcm, type, d, vector);
            }
        }
    }
}
 
Example #26
Source File: TapChangerConversion.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Equivalent impedance / admittance after moving a complex ratio from one end to the other
 */
private static RatioConversion moveRatio(double a, double angle, double r, double x, double g1,
    double b1, double g2, double b2) {
    Complex ratio = new Complex(a * Math.cos(Math.toRadians(angle)),
        a * Math.sin(Math.toRadians(angle)));
    return moveRatio(ratio, r, x, g1, b1, g2, b2);
}
 
Example #27
Source File: ZernikePolynomialsTest.java    From cineast with MIT License 5 votes vote down vote up
/**
 * Test Z_00, which must be equal to 1.0 + 0.0i for all values ofs r
 * and theta.
 */
@Test
@DisplayName("Test Z_00")
void testZ00() {
    final ZernikeBasisFunction ZF1 = new ZernikeBasisFunction(0, 0);
    final double increment = 1e-3;
    for (double r = 0.0; r <= 1.0f; r += increment) {
        for (double theta = 0; theta <= 2*Math.PI; theta += increment) {
            Complex v = new Complex(r * FastMath.cos(theta), r * FastMath.sin(theta));
            assertEquals(1.0, ZF1.value(v).abs(), 1e-8);
            assertEquals(0.0, ZF1.value(v).getArgument(), 1e-8);
        }
    }
}
 
Example #28
Source File: Operations.java    From january with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void complexOperate(double[] out, double ra, double ia, double rb, double ib) {
	Complex c = new Complex(ra, ia);
	c = ib == 0 ? c.pow(rb) : c.pow(new Complex(rb, ib));
	out[0] = c.getReal();
	out[1] = c.getImaginary();
}
 
Example #29
Source File: FastFourierTransformerTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test2DDataUnitary() {
    FastFourierTransformer transformer;
    transformer = new FastFourierTransformer(DftNormalization.UNITARY);
    double tolerance = 1E-12;
    Complex[][] input = new Complex[][] {new Complex[] {new Complex(1, 0),
                                                        new Complex(2, 0)},
                                         new Complex[] {new Complex(3, 1),
                                                        new Complex(4, 2)}};
    Complex[][] goodOutput = new Complex[][] {new Complex[] {new Complex(5,
            1.5), new Complex(-1, -.5)}, new Complex[] {new Complex(-2,
            -1.5), new Complex(0, .5)}};
    Complex[][] output = (Complex[][])transformer.mdfft(input, TransformType.FORWARD);
    Complex[][] output2 = (Complex[][])transformer.mdfft(output, TransformType.INVERSE);

    Assert.assertEquals(input.length, output.length);
    Assert.assertEquals(input.length, output2.length);
    Assert.assertEquals(input[0].length, output[0].length);
    Assert.assertEquals(input[0].length, output2[0].length);
    Assert.assertEquals(input[1].length, output[1].length);
    Assert.assertEquals(input[1].length, output2[1].length);

    for (int i = 0; i < input.length; i++) {
        for (int j = 0; j < input[0].length; j++) {
            Assert.assertEquals(input[i][j].getImaginary(), output2[i][j].getImaginary(),
                         tolerance);
            Assert.assertEquals(input[i][j].getReal(), output2[i][j].getReal(), tolerance);
            Assert.assertEquals(goodOutput[i][j].getImaginary(), output[i][j].getImaginary(),
                         tolerance);
            Assert.assertEquals(goodOutput[i][j].getReal(), output[i][j].getReal(), tolerance);
        }
    }
}
 
Example #30
Source File: LFTest.java    From DeepMachineLearning with Apache License 2.0 5 votes vote down vote up
public void seeBase() throws InterpssException {

		String baseCasePath = "testdata/cases/ieee14.ieee";
		
		IpssCorePlugin.init();
		
		AclfNetwork net = CorePluginFactory
							.getFileAdapter(IpssFileAdapter.FileFormat.IEEECDF)
							.load(baseCasePath)
							.getAclfNet();

		System.out.println(" Base kVA = "+net.getBaseKva());
		System.out.println(" Base MVA = "+net.getBaseMva());
		
		for (int i=0; i<net.getNoBus(); ++i) {
			System.out.println(" Base V in bus "+i+" = "+net.getBusList().get(i).getBaseVoltage());
		}
		
		ISparseEqnComplex yeqn = net.formYMatrix();
		//get y matrix
		Complex[][] y = new Complex[net.getNoBus()][net.getNoBus()];
		for (int i=0; i<net.getNoBus(); ++i)
			for (int j=0; j<net.getNoBus(); ++j) {
				y[i][j] = new Complex(0, 0);
				y[i][j] = yeqn.getA(i, j);
			}

		//debug
		System.out.println(" Y: ");
		for (int i=0; i<net.getNoBus(); ++i) {
			for (int j=0; j<net.getNoBus(); ++j) {
				System.out.print(y[i][j]+"\t");
			}
			System.out.println();
		}
	}