Example usage for java.lang Math signum

List of usage examples for java.lang Math signum

Introduction

In this page you can find the example usage for java.lang Math signum.

Prototype

public static float signum(float f) 

Source Link

Document

Returns the signum function of the argument; zero if the argument is zero, 1.0f if the argument is greater than zero, -1.0f if the argument is less than zero.

Usage

From source file:edu.jhuapl.bsp.detector.EWMASagesDetector.java

private void calculate(double omega) {
    UCL_R = new double[degFreedomRange];
    UCL_Y = new double[degFreedomRange];
    sigmaCoeff = new double[degFreedomRange];
    deltaSigma = new double[degFreedomRange];
    minSigma = new double[degFreedomRange];
    int[] degFreedom = new int[data.length];
    ////from w w  w. j  a  va 2 s .  com
    double term1 = omega / (2.0 - omega), term2, term3;
    for (int i = 0; i < degFreedomRange; i++) {
        TDistribution tdist = new TDistribution(i + 1);
        UCL_R[i] = tdist.inverseCumulativeProbability(1 - threshPValueR);
        UCL_Y[i] = tdist.inverseCumulativeProbability(1 - threshPValueY);
        int numBaseline = NUM_FIT_PARAMS + i;
        term2 = 1.0 / numBaseline;
        term3 = -2.0 * Math.pow((1 - omega), (numGuardBand + 1.0)) * (1.0 - Math.pow((1 - omega), numBaseline))
                / numBaseline;
        sigmaCoeff[i] = Math.sqrt(term1 + term2 + term3);
        deltaSigma[i] = (omega / UCL_Y[i])
                * (0.1289 - (0.2414 - 0.1826 * Math.pow((1 - omega), 4)) * Math.log(10.0 * threshPValueY));
        minSigma[i] = (omega / UCL_Y[i]) * (1.0 + 0.5 * Math.pow((1 - omega), 2));
    }
    //
    levels = new double[data.length];
    Arrays.fill(levels, 0.5);
    pvalues = new double[data.length];
    Arrays.fill(pvalues, 0.5);
    expectedData = new double[data.length];
    Arrays.fill(expectedData, 0);
    colors = new double[data.length];
    r2Levels = new double[data.length];
    Arrays.fill(r2Levels, 0);
    switchFlags = new double[data.length];
    Arrays.fill(switchFlags, 0);
    test_stat = new double[data.length];
    Arrays.fill(test_stat, 0);
    //
    FilterBaselineZeros3 zf = new FilterBaselineZeros3();
    //
    double smoothedData, sigma, testBase[], baselineData[];
    ArrayList<Integer> ndxBaseline = new ArrayList<Integer>();
    // initialize the smoothed data
    smoothedData = 0;
    for (int i = 1; i < minBaseline + numGuardBand && i < data.length; i++) {
        smoothedData = omega * data[i] + (1 - omega) * smoothedData;
    }
    // initialize the indices of the baseline period
    for (int i = 0; i < minBaseline - 1; i++) {
        ndxBaseline.add(new Integer(i));
    }
    // loop through the days on which to make predictions
    for (int i = minBaseline + numGuardBand; i < data.length; i++) {
        // smooth the data using an exponentially weighted moving average (EWMA)
        smoothedData = omega * data[i] + (1 - omega) * smoothedData;
        // lengthen and advance the baseline period
        if (ndxBaseline.isEmpty() || ndxBaseline.get(ndxBaseline.size() - 1) + 1 < maxBaseline) {
            ndxBaseline.add(0, -1);
        }
        // advance the indices of the baseline period
        arrayAdd(ndxBaseline, 1);
        // remove excess consecutive zeros from the baseline data
        testBase = dataInd(data, ndxBaseline);
        if (removeZeros && FilterBaselineZeros3.filterBaselineZerosTest(testBase)) {
            int[] ndxOK = zf.filterBaselineZeros(testBase);
            baselineData = dataInd(testBase, ndxOK);
        } else {
            baselineData = testBase;
        }
        // check the baseline period is filled with zeros; no prediction can be
        if (!any(baselineData)) {
            continue;
        }
        // the number of degrees of freedom
        degFreedom[i] = baselineData.length - NUM_FIT_PARAMS;
        // there are not enough data points in the baseline period; no prediction can be made
        if (degFreedom[i] < MIN_DEG_FREEDOM) {
            continue;
        }
        // the predicted current value of the data
        expectedData[i] = mean(baselineData);
        // calculate the test statistic
        // the adjusted standard deviation of the baseline data
        sigma = sigmaCoeff[degFreedom[i] - 1] * std(baselineData) + deltaSigma[degFreedom[i] - 1];
        // don't allow values smaller than MinSigma
        sigma = Math.max(sigma, minSigma[degFreedom[i] - 1]);
        // the test statistic
        test_stat[i] = (smoothedData - expectedData[i]) / sigma;
        if (Math.abs(test_stat[i]) > UCL_R[degFreedom[i] - 1]) {
            // the current value of the smoothed data is too extreme; adjust this value for the next iteration
            smoothedData = expectedData[i] + Math.signum(test_stat[i]) * UCL_R[degFreedom[i] - 1] * sigma;
        }
    }
    for (int i = 0; i < data.length; i++) {
        if (Math.abs(test_stat[i]) > 0.0) {
            TDistribution tdist = new TDistribution(degFreedom[i]);
            pvalues[i] = 1 - tdist.cumulativeProbability(test_stat[i]);
            levels[i] = pvalues[i];
        }
    }
}

From source file:org.opennms.features.topology.app.internal.jung.TopoFRLayout.java

protected void calcRepulsion(V v1) {
    FRVertexData fvd1 = getFRData(v1);/*www  .j a  v  a  2 s  . c om*/
    if (fvd1 == null)
        return;
    fvd1.setLocation(0, 0);

    try {
        for (V v2 : getGraph().getVertices()) {
            if (v1 != v2) {
                Point2D p1 = transform(v1);
                Point2D p2 = transform(v2);
                if (p1 == null || p2 == null)
                    continue;
                double xDelta = p1.getX() - p2.getX();
                double yDelta = p1.getY() - p2.getY();

                xDelta = Math.abs(xDelta) > EPSILON ? xDelta
                        : xDelta == 0 ? epsilon() : Math.signum(xDelta) * EPSILON;
                yDelta = Math.abs(yDelta) > EPSILON ? yDelta
                        : yDelta == 0 ? epsilon() : Math.signum(yDelta) * EPSILON;

                double deltaLength = Math.sqrt((xDelta * xDelta) + (yDelta * yDelta));

                double force = (repulsion_constant * repulsion_constant) / deltaLength;

                if (Double.isNaN(force)) {
                    throw new RuntimeException(
                            "Unexpected mathematical result in FRLayout:calcPositions [repulsion]");
                }
                fvd1.offset((xDelta / deltaLength) * force, (yDelta / deltaLength) * force);
            }
        }
    } catch (ConcurrentModificationException cme) {
        calcRepulsion(v1);
    }
}

From source file:com.opengamma.analytics.financial.interestrate.swaption.method.SwaptionBermudaFixedIborHullWhiteNumericalIntegrationMethod.java

/**
 * Computes the present value of the Physical delivery swaption.
 * @param swaption The swaption./* w  w  w.j  ava 2 s  .c o  m*/
 * @param hwData The Hull-White parameters and the curves.
 * @return The present value.
 */
public CurrencyAmount presentValue(final SwaptionBermudaFixedIbor swaption,
        final HullWhiteOneFactorPiecewiseConstantDataBundle hwData) {
    Validate.notNull(swaption);
    Validate.notNull(hwData);
    int nbExpiry = swaption.getExpiryTime().length;
    Validate.isTrue(nbExpiry > 1, "At least two expiry dates required for this method");

    double tmpdb;
    YieldAndDiscountCurve discountingCurve = hwData
            .getCurve(swaption.getUnderlyingSwap()[0].getFirstLeg().getDiscountCurve());

    double[] theta = new double[nbExpiry + 1]; // Extended expiry time (with 0).
    theta[0] = 0.0;
    System.arraycopy(swaption.getExpiryTime(), 0, theta, 1, nbExpiry);
    AnnuityPaymentFixed[] cashflow = new AnnuityPaymentFixed[nbExpiry];
    for (int loopexp = 0; loopexp < nbExpiry; loopexp++) {
        cashflow[loopexp] = CFEC.visit(swaption.getUnderlyingSwap()[loopexp], hwData);
    }
    int[] n = new int[nbExpiry];
    double[][][] alpha = new double[nbExpiry][][];
    double[][][] alpha2 = new double[nbExpiry][][]; // alpha^2

    for (int loopexp = 0; loopexp < nbExpiry; loopexp++) {
        n[loopexp] = cashflow[loopexp].getNumberOfPayments();
        alpha[loopexp] = new double[loopexp + 1][];
        alpha2[loopexp] = new double[loopexp + 1][];
        for (int k = 0; k <= loopexp; k++) {
            alpha[loopexp][k] = new double[n[loopexp]];
            alpha2[loopexp][k] = new double[n[loopexp]];
            for (int l = 0; l < alpha[loopexp][k].length; l++) {
                alpha[loopexp][k][l] = MODEL.alpha(hwData.getHullWhiteParameter(), theta[k], theta[k + 1],
                        theta[k + 1], cashflow[loopexp].getNthPayment(l).getPaymentTime());
                alpha2[loopexp][k][l] = alpha[loopexp][k][l] * alpha[loopexp][k][l];
            }
        }
    }

    int nbPoint2 = 2 * NB_POINT + 1;
    int[] startInt = new int[nbExpiry - 1];
    int[] endInt = new int[nbExpiry - 1];
    for (int i = 1; i < nbExpiry - 1; i++) {
        startInt[i] = 0;
        endInt[i] = nbPoint2 - 1;
    }
    startInt[0] = NB_POINT;
    endInt[0] = NB_POINT;

    double[][] t = new double[nbExpiry][]; // payment time
    double[][] dfS = new double[nbExpiry][]; // discount factor
    double[] beta = new double[nbExpiry];
    double[][] h = new double[nbExpiry][];
    double[][] sa2 = new double[nbExpiry][];

    for (int loopexp = 0; loopexp < nbExpiry; loopexp++) {
        beta[loopexp] = MODEL.beta(hwData.getHullWhiteParameter(), theta[loopexp], theta[loopexp + 1]);
        t[loopexp] = new double[n[loopexp]];
        dfS[loopexp] = new double[n[loopexp]];
        h[loopexp] = new double[n[loopexp]];
        sa2[loopexp] = new double[n[loopexp]];
        for (int loopcf = 0; loopcf < n[loopexp]; loopcf++) {
            t[loopexp][loopcf] = cashflow[loopexp].getNthPayment(loopcf).getPaymentTime();
            dfS[loopexp][loopcf] = discountingCurve.getDiscountFactor(t[loopexp][loopcf]);
            h[loopexp][loopcf] = (1
                    - Math.exp(-hwData.getHullWhiteParameter().getMeanReversion() * t[loopexp][loopcf]))
                    / hwData.getHullWhiteParameter().getMeanReversion();
            tmpdb = 0.0;
            for (int k = 0; k <= loopexp; k++) {
                tmpdb += alpha2[loopexp][k][loopcf];
            }
            sa2[loopexp][loopcf] = tmpdb;
        }
    }
    double[] discountedCashFlowN = new double[n[nbExpiry - 1]];
    for (int loopcf = 0; loopcf < n[nbExpiry - 1]; loopcf++) {
        discountedCashFlowN[loopcf] = dfS[nbExpiry - 1][loopcf]
                * cashflow[nbExpiry - 1].getNthPayment(loopcf).getAmount();
    }
    double lambda = MODEL.lambda(discountedCashFlowN, sa2[nbExpiry - 1], h[nbExpiry - 1]);
    double[] betaSort = new double[nbExpiry];
    System.arraycopy(beta, 0, betaSort, 0, nbExpiry);
    Arrays.sort(betaSort);
    double minbeta = betaSort[0];
    double maxbeta = betaSort[nbExpiry - 1];

    double b = Math.min(10 * minbeta, maxbeta);
    double epsilon = -2.0 / NB_POINT * NORMAL.getInverseCDF(1.0 / (200.0 * NB_POINT)) * b; // <-
    double[] bX = new double[nbPoint2];
    for (int looppt = 0; looppt < nbPoint2; looppt++) {
        bX[looppt] = -NB_POINT * epsilon + looppt * epsilon;
    }
    double[] bX2 = new double[4 * NB_POINT + 1];
    for (int looppt = 0; looppt < 4 * NB_POINT + 1; looppt++) {
        bX2[looppt] = -2 * NB_POINT * epsilon + looppt * epsilon;
    }
    double[] htheta = new double[nbExpiry];
    for (int loopexp = 0; loopexp < nbExpiry; loopexp++) {
        htheta[loopexp] = (1
                - Math.exp(-hwData.getHullWhiteParameter().getMeanReversion() * theta[loopexp + 1]))
                / hwData.getHullWhiteParameter().getMeanReversion();
    }

    double[][] vZ = new double[nbExpiry - 1][nbPoint2];
    for (int i = nbExpiry - 2; i >= 0; i--) {
        for (int looppt = 0; looppt < nbPoint2; looppt++) {
            vZ[i][looppt] = Math.exp(bX[looppt] * htheta[i]);
        }
    }

    double[][] vW = new double[nbExpiry][]; // Swaption
    double[][] vT = new double[nbExpiry - 1][]; // Swap

    double omega = -Math.signum(cashflow[nbExpiry - 1].getNthPayment(0).getAmount());
    double[] kappaL = new double[nbPoint2];
    for (int looppt = 0; looppt < nbPoint2; looppt++) {
        kappaL[looppt] = (lambda - bX[looppt]) / beta[nbExpiry - 1];
    }

    double[] sa2N1 = new double[n[nbExpiry - 1]];
    for (int i = 0; i < n[nbExpiry - 1]; i++) {
        tmpdb = 0;
        for (int k = 0; k <= nbExpiry - 2; k++) {
            tmpdb += alpha2[nbExpiry - 1][k][i];
        }
        sa2N1[i] = tmpdb;
    }

    vW[nbExpiry - 1] = new double[4 * NB_POINT + 1];
    for (int j = 0; j < n[nbExpiry - 1]; j++) {
        for (int looppt = 0; looppt < nbPoint2; looppt++) {
            vW[nbExpiry - 1][NB_POINT + looppt] += discountedCashFlowN[j]
                    * Math.exp(-sa2N1[j] / 2.0 - h[nbExpiry - 1][j] * bX[looppt])
                    * NORMAL.getCDF(omega * (kappaL[looppt] + alpha[nbExpiry - 1][nbExpiry - 1][j]));
        }
    }
    for (int looppt = 0; looppt < NB_POINT; looppt++) {
        vW[nbExpiry - 1][looppt] = vW[nbExpiry - 1][NB_POINT];
    }
    for (int looppt = 0; looppt < NB_POINT; looppt++) {
        vW[nbExpiry - 1][3 * NB_POINT + 1 + looppt] = vW[nbExpiry - 1][3 * NB_POINT];
    }

    double c1sqrt2pi = 1.0 / Math.sqrt(2 * Math.PI);
    double[][] pvcfT = new double[nbExpiry - 1][];
    double[] vL; // Left side of intersection
    double[] vR; // Right side of intersection
    double[][] labc;
    double[][] rabc;
    double[][] labcM = new double[3][4 * NB_POINT + 1];
    double[][] rabcM = new double[3][4 * NB_POINT + 1];

    double[] dabc = new double[3];
    int[] indSwap = new int[nbExpiry - 1]; // index of the intersection
    double xroot;
    double[][] xN = new double[nbExpiry - 1][nbPoint2];
    double ci;
    double coi;
    int is;
    double[] ncdf0 = new double[nbPoint2];
    double[] ncdf1 = new double[nbPoint2];
    double[] ncdf2 = new double[nbPoint2];
    double[] ncdf0X = new double[nbPoint2 + 1];
    double[] ncdf1X = new double[nbPoint2 + 1];
    double[] ncdf2X = new double[nbPoint2 + 1];
    double ncdf0x;
    double ncdf1x;
    double ncdf2x;
    double ncdfinit;

    // Main loop for the different expiry dates (except the last one)
    for (int i = nbExpiry - 2; i >= 0; i--) {
        vW[i] = new double[4 * NB_POINT + 1];
        vT[i] = new double[4 * NB_POINT + 1];
        // T: swap
        pvcfT[i] = new double[n[i]];
        for (int j = 0; j < n[i]; j++) {
            pvcfT[i][j] = cashflow[i].getNthPayment(j).getAmount() * dfS[i][j];
            for (int looppt = 0; looppt < 4 * NB_POINT + 1; looppt++) {
                vT[i][looppt] += pvcfT[i][j] * Math.exp(-sa2[i][j] / 2.0 - h[i][j] * bX2[looppt]);
            }
        }
        // Preparation
        for (int looppt = 0; looppt < nbPoint2; looppt++) {
            xN[i][looppt] = bX[looppt] / beta[i];
        }
        ci = htheta[i] * beta[i];
        coi = Math.exp(ci * ci / 2);

        // Left/Right
        if (omega < 0) {
            vL = vW[i + 1];
            vR = vT[i];
        } else {
            vR = vW[i + 1];
            vL = vT[i];
        }
        indSwap[i] = 0;
        while (vL[indSwap[i] + 1] >= vR[indSwap[i] + 1]) {
            indSwap[i]++;
        }
        // Parabola fit
        labc = parafit(epsilon / beta[i], vL);
        rabc = parafit(epsilon / beta[i], vR);
        for (int k = 0; k < 3; k++) {
            dabc[k] = labc[k][indSwap[i]] - rabc[k][indSwap[i]];
            System.arraycopy(labc[k], 0, labcM[k], 0, indSwap[i] + 1);
            System.arraycopy(labc[k], indSwap[i], labcM[k], indSwap[i] + 1, labc[k].length - indSwap[i]);
            System.arraycopy(rabc[k], 0, rabcM[k], 0, indSwap[i] + 1);
            System.arraycopy(rabc[k], indSwap[i], rabcM[k], indSwap[i] + 1, rabc[k].length - indSwap[i]);
        }

        for (int looppt = 0; looppt < 4 * NB_POINT + 1; looppt++) {
            labcM[1][looppt] = labcM[1][looppt] + labcM[0][looppt] * 2 * ci;
            labcM[2][looppt] = labcM[2][looppt] + labcM[1][looppt] * ci - labcM[0][looppt] * ci * ci;
            rabcM[1][looppt] = rabcM[1][looppt] + rabcM[0][looppt] * 2 * ci;
            rabcM[2][looppt] = rabcM[2][looppt] + rabcM[1][looppt] * ci - rabcM[0][looppt] * ci * ci;
        }
        xroot = (-dabc[1] - Math.sqrt(dabc[1] * dabc[1] - 4 * dabc[0] * dabc[2])) / (2 * dabc[0]);

        ncdfinit = NORMAL.getCDF(xN[i][0]);

        for (int looppt = 0; looppt < nbPoint2; looppt++) {
            ncdf0[looppt] = NORMAL.getCDF(xN[i][looppt] - ci);
            ncdf1[looppt] = -c1sqrt2pi * Math.exp(-(xN[i][looppt] - ci) * (xN[i][looppt] - ci) / 2.0);
            ncdf2[looppt] = ncdf1[looppt] * (xN[i][looppt] - ci) + ncdf0[looppt];
        }

        for (int j = startInt[i]; j <= endInt[i]; j++) {
            is = indSwap[i] - j + 1;
            // % all L
            if (j + 2 * NB_POINT <= indSwap[i]) {
                double[][] xabc = new double[3][2 * NB_POINT];
                for (int k = 0; k < 3; k++) {
                    System.arraycopy(labcM[k], j, xabc[k], 0, 2 * NB_POINT);
                }
                for (int looppt = 0; looppt < 2 * NB_POINT; looppt++) {
                    xabc[1][looppt] = xabc[1][looppt] + xabc[0][looppt] * 2 * xN[i][j];
                    xabc[2][looppt] = xabc[2][looppt] + xabc[1][looppt] * xN[i][j]
                            - xabc[0][looppt] * xN[i][j] * xN[i][j];
                }
                vW[i][j + NB_POINT] = 0;
                vW[i][j + NB_POINT] = vW[i][j + NB_POINT] + coi * ni2ncdf(ncdf2, ncdf1, ncdf0, xabc);
            } else if (j < indSwap[i]) {
                double[][] xabc = new double[3][2 * NB_POINT + 1];
                tmpdb = xroot - xN[i][j] - ci;
                ncdf0x = NORMAL.getCDF(tmpdb);
                ncdf1x = -Math.exp(-(tmpdb * tmpdb) / 2) * c1sqrt2pi;
                ncdf2x = ncdf1x * tmpdb + ncdf0x;
                for (int k = 0; k < 3; k++) {
                    //            System.arraycopy(rabcM[k], j, xabc[k], 0, 2 * _nbPoint + 1); // Swap
                    System.arraycopy(labcM[k], j, xabc[k], 0, 2 * NB_POINT + 1);
                    System.arraycopy(rabcM[k], indSwap[i] + 1, xabc[k], indSwap[i] + 1 - j,
                            j + 2 * NB_POINT - indSwap[i]);
                }
                for (int looppt = 0; looppt < 2 * NB_POINT; looppt++) {
                    xabc[1][looppt] = xabc[1][looppt] + xabc[0][looppt] * 2 * xN[i][j];
                    xabc[2][looppt] = xabc[2][looppt] + xabc[1][looppt] * xN[i][j]
                            - xabc[0][looppt] * xN[i][j] * xN[i][j];
                }
                System.arraycopy(ncdf0, 0, ncdf0X, 0, is);
                ncdf0X[is] = ncdf0x;
                System.arraycopy(ncdf0, is, ncdf0X, is + 1, ncdf0.length - is);
                System.arraycopy(ncdf1, 0, ncdf1X, 0, is);
                ncdf1X[is] = ncdf1x;
                System.arraycopy(ncdf1, is, ncdf1X, is + 1, ncdf1.length - is);
                System.arraycopy(ncdf2, 0, ncdf2X, 0, is);
                ncdf2X[is] = ncdf2x;
                System.arraycopy(ncdf2, is, ncdf2X, is + 1, ncdf2.length - is);
                vW[i][j + NB_POINT] = vL[j] * vZ[i][0] * ncdfinit;
                vW[i][j + NB_POINT] += coi * ni2ncdf(ncdf2X, ncdf1X, ncdf0X, xabc);
                vW[i][j + NB_POINT] += vR[j + 2 * NB_POINT] * vZ[i][vZ[i].length - 1] * ncdfinit;
            } else {
                double[][] xabc = new double[3][2 * NB_POINT];
                for (int k = 0; k < 3; k++) {
                    System.arraycopy(rabcM[k], j + 1, xabc[k], 0, 2 * NB_POINT);
                    //            System.arraycopy(labcM[k], j + 1, xabc[k], 0, 2 * _nbPoint); // Swaption
                }
                for (int looppt = 0; looppt < 2 * NB_POINT; looppt++) {
                    xabc[1][looppt] = xabc[1][looppt] + xabc[0][looppt] * 2 * xN[i][j];
                    xabc[2][looppt] = xabc[2][looppt] + xabc[1][looppt] * xN[i][j]
                            - xabc[0][looppt] * xN[i][j] * xN[i][j];
                }
                vW[i][j + NB_POINT] = vR[j] * vZ[i][0] * ncdfinit;
                vW[i][j + NB_POINT] += coi * ni2ncdf(ncdf2, ncdf1, ncdf0, xabc);
                vW[i][j + NB_POINT] += vR[j + 2 * NB_POINT] * vZ[i][vZ[i].length - 1] * ncdfinit;
            }
        }
        for (int j = 0; j < NB_POINT; j++) { // Flat extrapolation
            vW[i][j] = vW[i][NB_POINT];
            vW[i][3 * NB_POINT + 1 + j] = vW[i][3 * NB_POINT];
        }
    } // End main loop

    return CurrencyAmount.of(swaption.getUnderlyingSwap()[0].getFixedLeg().getCurrency(),
            vW[0][2 * NB_POINT] * (swaption.isLong() ? 1.0 : -1.0));
}

From source file:com.opengamma.analytics.financial.interestrate.swaption.provider.SwaptionBermudaFixedIborHullWhiteNumericalIntegrationMethod.java

/**
 * Computes the present value of the Physical delivery swaption.
 * @param swaption The swaption./*from   w w  w . jav a2 s . co m*/
 * @param hullWhite The Hull-White parameters and the curves.
 * @return The present value.
 */
public MultipleCurrencyAmount presentValue(final SwaptionBermudaFixedIbor swaption,
        final HullWhiteOneFactorProviderInterface hullWhite) {
    ArgumentChecker.notNull(swaption, "Swaption");
    ArgumentChecker.notNull(hullWhite, "Hull-White provider");
    MulticurveProviderInterface multicurves = hullWhite.getMulticurveProvider();
    HullWhiteOneFactorPiecewiseConstantParameters parameters = hullWhite.getHullWhiteParameters();
    Currency ccy = swaption.getCurrency();
    final int nbExpiry = swaption.getExpiryTime().length;
    Validate.isTrue(nbExpiry > 1, "At least two expiry dates required for this method");

    double tmpdb;

    final double[] theta = new double[nbExpiry + 1]; // Extended expiry time (with 0).
    theta[0] = 0.0;
    System.arraycopy(swaption.getExpiryTime(), 0, theta, 1, nbExpiry);
    final AnnuityPaymentFixed[] cashflow = new AnnuityPaymentFixed[nbExpiry];
    for (int loopexp = 0; loopexp < nbExpiry; loopexp++) {
        cashflow[loopexp] = swaption.getUnderlyingSwap()[loopexp].accept(CFEC, multicurves);
    }
    final int[] n = new int[nbExpiry];
    final double[][][] alpha = new double[nbExpiry][][];
    final double[][][] alpha2 = new double[nbExpiry][][]; // alpha^2

    for (int loopexp = 0; loopexp < nbExpiry; loopexp++) {
        n[loopexp] = cashflow[loopexp].getNumberOfPayments();
        alpha[loopexp] = new double[loopexp + 1][];
        alpha2[loopexp] = new double[loopexp + 1][];
        for (int k = 0; k <= loopexp; k++) {
            alpha[loopexp][k] = new double[n[loopexp]];
            alpha2[loopexp][k] = new double[n[loopexp]];
            for (int l = 0; l < alpha[loopexp][k].length; l++) {
                alpha[loopexp][k][l] = MODEL.alpha(parameters, theta[k], theta[k + 1], theta[k + 1],
                        cashflow[loopexp].getNthPayment(l).getPaymentTime());
                alpha2[loopexp][k][l] = alpha[loopexp][k][l] * alpha[loopexp][k][l];
            }
        }
    }

    final int nbPoint2 = 2 * NB_POINT + 1;
    final int[] startInt = new int[nbExpiry - 1];
    final int[] endInt = new int[nbExpiry - 1];
    for (int i = 1; i < nbExpiry - 1; i++) {
        startInt[i] = 0;
        endInt[i] = nbPoint2 - 1;
    }
    startInt[0] = NB_POINT;
    endInt[0] = NB_POINT;

    final double[][] t = new double[nbExpiry][]; // payment time
    final double[][] dfS = new double[nbExpiry][]; // discount factor
    final double[] beta = new double[nbExpiry];
    final double[][] h = new double[nbExpiry][];
    final double[][] sa2 = new double[nbExpiry][];

    for (int loopexp = 0; loopexp < nbExpiry; loopexp++) {
        beta[loopexp] = MODEL.beta(parameters, theta[loopexp], theta[loopexp + 1]);
        t[loopexp] = new double[n[loopexp]];
        dfS[loopexp] = new double[n[loopexp]];
        h[loopexp] = new double[n[loopexp]];
        sa2[loopexp] = new double[n[loopexp]];
        for (int loopcf = 0; loopcf < n[loopexp]; loopcf++) {
            t[loopexp][loopcf] = cashflow[loopexp].getNthPayment(loopcf).getPaymentTime();
            dfS[loopexp][loopcf] = multicurves.getDiscountFactor(ccy, t[loopexp][loopcf]);
            h[loopexp][loopcf] = (1 - Math.exp(-parameters.getMeanReversion() * t[loopexp][loopcf]))
                    / parameters.getMeanReversion();
            tmpdb = 0.0;
            for (int k = 0; k <= loopexp; k++) {
                tmpdb += alpha2[loopexp][k][loopcf];
            }
            sa2[loopexp][loopcf] = tmpdb;
        }
    }
    final double[] discountedCashFlowN = new double[n[nbExpiry - 1]];
    for (int loopcf = 0; loopcf < n[nbExpiry - 1]; loopcf++) {
        discountedCashFlowN[loopcf] = dfS[nbExpiry - 1][loopcf]
                * cashflow[nbExpiry - 1].getNthPayment(loopcf).getAmount();
    }
    final double lambda = MODEL.lambda(discountedCashFlowN, sa2[nbExpiry - 1], h[nbExpiry - 1]);
    final double[] betaSort = new double[nbExpiry];
    System.arraycopy(beta, 0, betaSort, 0, nbExpiry);
    Arrays.sort(betaSort);
    final double minbeta = betaSort[0];
    final double maxbeta = betaSort[nbExpiry - 1];

    final double b = Math.min(10 * minbeta, maxbeta);
    final double epsilon = -2.0 / NB_POINT * NORMAL.getInverseCDF(1.0 / (200.0 * NB_POINT)) * b; // <-
    final double[] bX = new double[nbPoint2];
    for (int looppt = 0; looppt < nbPoint2; looppt++) {
        bX[looppt] = -NB_POINT * epsilon + looppt * epsilon;
    }
    final double[] bX2 = new double[4 * NB_POINT + 1];
    for (int looppt = 0; looppt < 4 * NB_POINT + 1; looppt++) {
        bX2[looppt] = -2 * NB_POINT * epsilon + looppt * epsilon;
    }
    final double[] htheta = new double[nbExpiry];
    for (int loopexp = 0; loopexp < nbExpiry; loopexp++) {
        htheta[loopexp] = (1 - Math.exp(-parameters.getMeanReversion() * theta[loopexp + 1]))
                / parameters.getMeanReversion();
    }

    final double[][] vZ = new double[nbExpiry - 1][nbPoint2];
    for (int i = nbExpiry - 2; i >= 0; i--) {
        for (int looppt = 0; looppt < nbPoint2; looppt++) {
            vZ[i][looppt] = Math.exp(bX[looppt] * htheta[i]);
        }
    }

    final double[][] vW = new double[nbExpiry][]; // Swaption
    final double[][] vT = new double[nbExpiry - 1][]; // Swap

    final double omega = -Math.signum(cashflow[nbExpiry - 1].getNthPayment(0).getAmount());
    final double[] kappaL = new double[nbPoint2];
    for (int looppt = 0; looppt < nbPoint2; looppt++) {
        kappaL[looppt] = (lambda - bX[looppt]) / beta[nbExpiry - 1];
    }

    final double[] sa2N1 = new double[n[nbExpiry - 1]];
    for (int i = 0; i < n[nbExpiry - 1]; i++) {
        tmpdb = 0;
        for (int k = 0; k <= nbExpiry - 2; k++) {
            tmpdb += alpha2[nbExpiry - 1][k][i];
        }
        sa2N1[i] = tmpdb;
    }

    vW[nbExpiry - 1] = new double[4 * NB_POINT + 1];
    for (int j = 0; j < n[nbExpiry - 1]; j++) {
        for (int looppt = 0; looppt < nbPoint2; looppt++) {
            vW[nbExpiry - 1][NB_POINT + looppt] += discountedCashFlowN[j]
                    * Math.exp(-sa2N1[j] / 2.0 - h[nbExpiry - 1][j] * bX[looppt])
                    * NORMAL.getCDF(omega * (kappaL[looppt] + alpha[nbExpiry - 1][nbExpiry - 1][j]));
        }
    }
    for (int looppt = 0; looppt < NB_POINT; looppt++) {
        vW[nbExpiry - 1][looppt] = vW[nbExpiry - 1][NB_POINT];
    }
    for (int looppt = 0; looppt < NB_POINT; looppt++) {
        vW[nbExpiry - 1][3 * NB_POINT + 1 + looppt] = vW[nbExpiry - 1][3 * NB_POINT];
    }

    final double c1sqrt2pi = 1.0 / Math.sqrt(2 * Math.PI);
    final double[][] pvcfT = new double[nbExpiry - 1][];
    double[] vL; // Left side of intersection
    double[] vR; // Right side of intersection
    double[][] labc;
    double[][] rabc;
    final double[][] labcM = new double[3][4 * NB_POINT + 1];
    final double[][] rabcM = new double[3][4 * NB_POINT + 1];

    final double[] dabc = new double[3];
    final int[] indSwap = new int[nbExpiry - 1]; // index of the intersection
    double xroot;
    final double[][] xN = new double[nbExpiry - 1][nbPoint2];
    double ci;
    double coi;
    int is;
    final double[] ncdf0 = new double[nbPoint2];
    final double[] ncdf1 = new double[nbPoint2];
    final double[] ncdf2 = new double[nbPoint2];
    final double[] ncdf0X = new double[nbPoint2 + 1];
    final double[] ncdf1X = new double[nbPoint2 + 1];
    final double[] ncdf2X = new double[nbPoint2 + 1];
    double ncdf0x;
    double ncdf1x;
    double ncdf2x;
    double ncdfinit;

    // Main loop for the different expiry dates (except the last one)
    for (int i = nbExpiry - 2; i >= 0; i--) {
        vW[i] = new double[4 * NB_POINT + 1];
        vT[i] = new double[4 * NB_POINT + 1];
        // T: swap
        pvcfT[i] = new double[n[i]];
        for (int j = 0; j < n[i]; j++) {
            pvcfT[i][j] = cashflow[i].getNthPayment(j).getAmount() * dfS[i][j];
            for (int looppt = 0; looppt < 4 * NB_POINT + 1; looppt++) {
                vT[i][looppt] += pvcfT[i][j] * Math.exp(-sa2[i][j] / 2.0 - h[i][j] * bX2[looppt]);
            }
        }
        // Preparation
        for (int looppt = 0; looppt < nbPoint2; looppt++) {
            xN[i][looppt] = bX[looppt] / beta[i];
        }
        ci = htheta[i] * beta[i];
        coi = Math.exp(ci * ci / 2);

        // Left/Right
        if (omega < 0) {
            vL = vW[i + 1];
            vR = vT[i];
        } else {
            vR = vW[i + 1];
            vL = vT[i];
        }
        indSwap[i] = 0;
        while (vL[indSwap[i] + 1] >= vR[indSwap[i] + 1]) {
            indSwap[i]++;
        }
        // Parabola fit
        labc = parafit(epsilon / beta[i], vL);
        rabc = parafit(epsilon / beta[i], vR);
        for (int k = 0; k < 3; k++) {
            dabc[k] = labc[k][indSwap[i]] - rabc[k][indSwap[i]];
            System.arraycopy(labc[k], 0, labcM[k], 0, indSwap[i] + 1);
            System.arraycopy(labc[k], indSwap[i], labcM[k], indSwap[i] + 1, labc[k].length - indSwap[i]);
            System.arraycopy(rabc[k], 0, rabcM[k], 0, indSwap[i] + 1);
            System.arraycopy(rabc[k], indSwap[i], rabcM[k], indSwap[i] + 1, rabc[k].length - indSwap[i]);
        }

        for (int looppt = 0; looppt < 4 * NB_POINT + 1; looppt++) {
            labcM[1][looppt] = labcM[1][looppt] + labcM[0][looppt] * 2 * ci;
            labcM[2][looppt] = labcM[2][looppt] + labcM[1][looppt] * ci - labcM[0][looppt] * ci * ci;
            rabcM[1][looppt] = rabcM[1][looppt] + rabcM[0][looppt] * 2 * ci;
            rabcM[2][looppt] = rabcM[2][looppt] + rabcM[1][looppt] * ci - rabcM[0][looppt] * ci * ci;
        }
        xroot = (-dabc[1] - Math.sqrt(dabc[1] * dabc[1] - 4 * dabc[0] * dabc[2])) / (2 * dabc[0]);

        ncdfinit = NORMAL.getCDF(xN[i][0]);

        for (int looppt = 0; looppt < nbPoint2; looppt++) {
            ncdf0[looppt] = NORMAL.getCDF(xN[i][looppt] - ci);
            ncdf1[looppt] = -c1sqrt2pi * Math.exp(-(xN[i][looppt] - ci) * (xN[i][looppt] - ci) / 2.0);
            ncdf2[looppt] = ncdf1[looppt] * (xN[i][looppt] - ci) + ncdf0[looppt];
        }

        for (int j = startInt[i]; j <= endInt[i]; j++) {
            is = indSwap[i] - j + 1;
            // % all L
            if (j + 2 * NB_POINT <= indSwap[i]) {
                final double[][] xabc = new double[3][2 * NB_POINT];
                for (int k = 0; k < 3; k++) {
                    System.arraycopy(labcM[k], j, xabc[k], 0, 2 * NB_POINT);
                }
                for (int looppt = 0; looppt < 2 * NB_POINT; looppt++) {
                    xabc[1][looppt] = xabc[1][looppt] + xabc[0][looppt] * 2 * xN[i][j];
                    xabc[2][looppt] = xabc[2][looppt] + xabc[1][looppt] * xN[i][j]
                            - xabc[0][looppt] * xN[i][j] * xN[i][j];
                }
                vW[i][j + NB_POINT] = 0;
                vW[i][j + NB_POINT] = vW[i][j + NB_POINT] + coi * ni2ncdf(ncdf2, ncdf1, ncdf0, xabc);
            } else if (j < indSwap[i]) {
                final double[][] xabc = new double[3][2 * NB_POINT + 1];
                tmpdb = xroot - xN[i][j] - ci;
                ncdf0x = NORMAL.getCDF(tmpdb);
                ncdf1x = -Math.exp(-(tmpdb * tmpdb) / 2) * c1sqrt2pi;
                ncdf2x = ncdf1x * tmpdb + ncdf0x;
                for (int k = 0; k < 3; k++) {
                    //            System.arraycopy(rabcM[k], j, xabc[k], 0, 2 * _nbPoint + 1); // Swap
                    System.arraycopy(labcM[k], j, xabc[k], 0, 2 * NB_POINT + 1);
                    System.arraycopy(rabcM[k], indSwap[i] + 1, xabc[k], indSwap[i] + 1 - j,
                            j + 2 * NB_POINT - indSwap[i]);
                }
                for (int looppt = 0; looppt < 2 * NB_POINT; looppt++) {
                    xabc[1][looppt] = xabc[1][looppt] + xabc[0][looppt] * 2 * xN[i][j];
                    xabc[2][looppt] = xabc[2][looppt] + xabc[1][looppt] * xN[i][j]
                            - xabc[0][looppt] * xN[i][j] * xN[i][j];
                }
                System.arraycopy(ncdf0, 0, ncdf0X, 0, is);
                ncdf0X[is] = ncdf0x;
                System.arraycopy(ncdf0, is, ncdf0X, is + 1, ncdf0.length - is);
                System.arraycopy(ncdf1, 0, ncdf1X, 0, is);
                ncdf1X[is] = ncdf1x;
                System.arraycopy(ncdf1, is, ncdf1X, is + 1, ncdf1.length - is);
                System.arraycopy(ncdf2, 0, ncdf2X, 0, is);
                ncdf2X[is] = ncdf2x;
                System.arraycopy(ncdf2, is, ncdf2X, is + 1, ncdf2.length - is);
                vW[i][j + NB_POINT] = vL[j] * vZ[i][0] * ncdfinit;
                vW[i][j + NB_POINT] += coi * ni2ncdf(ncdf2X, ncdf1X, ncdf0X, xabc);
                vW[i][j + NB_POINT] += vR[j + 2 * NB_POINT] * vZ[i][vZ[i].length - 1] * ncdfinit;
            } else {
                final double[][] xabc = new double[3][2 * NB_POINT];
                for (int k = 0; k < 3; k++) {
                    System.arraycopy(rabcM[k], j + 1, xabc[k], 0, 2 * NB_POINT);
                    //            System.arraycopy(labcM[k], j + 1, xabc[k], 0, 2 * _nbPoint); // Swaption
                }
                for (int looppt = 0; looppt < 2 * NB_POINT; looppt++) {
                    xabc[1][looppt] = xabc[1][looppt] + xabc[0][looppt] * 2 * xN[i][j];
                    xabc[2][looppt] = xabc[2][looppt] + xabc[1][looppt] * xN[i][j]
                            - xabc[0][looppt] * xN[i][j] * xN[i][j];
                }
                vW[i][j + NB_POINT] = vR[j] * vZ[i][0] * ncdfinit;
                vW[i][j + NB_POINT] += coi * ni2ncdf(ncdf2, ncdf1, ncdf0, xabc);
                vW[i][j + NB_POINT] += vR[j + 2 * NB_POINT] * vZ[i][vZ[i].length - 1] * ncdfinit;
            }
        }
        for (int j = 0; j < NB_POINT; j++) { // Flat extrapolation
            vW[i][j] = vW[i][NB_POINT];
            vW[i][3 * NB_POINT + 1 + j] = vW[i][3 * NB_POINT];
        }
    } // End main loop

    return MultipleCurrencyAmount.of(swaption.getUnderlyingSwap()[0].getFixedLeg().getCurrency(),
            vW[0][2 * NB_POINT] * (swaption.isLong() ? 1.0 : -1.0));
}

From source file:com.aionemu.gameserver.spawnengine.WalkerGroup.java

private static WalkerGroupShift getShiftSigns(Point2D origin, Point2D destination) {
    float dx = Math.signum(destination.getX() - origin.getX());
    float dy = Math.signum(destination.getY() - origin.getY());
    return new WalkerGroupShift(dx, dy);
}

From source file:opendial.gui.utils.DistributionViewer.java

private List<XYSeries> extractSeries(DensityFunction function) {

    List<XYSeries> series = new ArrayList<XYSeries>();

    for (int i = 0; i < function.getDimensions(); i++) {
        series.add(new XYSeries("dimension " + i));
    }/*from   w w  w .  j  a  va  2  s.c o m*/

    Consumer<double[]> addToSeries = p -> {
        double density = function.getDensity(p);
        for (int d = 0; d < p.length; d++) {
            series.get(d).add(p[d], density);
        }
    };

    Set<double[]> points = function.discretise(500).keySet();
    points.stream().forEach(addToSeries);

    for (XYSeries serie : series) {
        boolean doSmoothing = (function instanceof KernelDensityFunction)
                || (function instanceof DirichletDensityFunction);
        while (doSmoothing) {
            int nbFluctuations = 0;
            double prevPrevY = serie.getY(0).doubleValue();
            double prevY = serie.getY(1).doubleValue();
            for (int i = 2; i < serie.getItemCount(); i++) {
                double currentY = serie.getY(i).doubleValue();
                if (Math.signum(prevY - prevPrevY) != Math.signum(currentY - prevY)) {
                    double avg = (prevPrevY + prevY + currentY) / 3.0;
                    serie.updateByIndex(i - 2, avg);
                    serie.updateByIndex(i - 1, avg);
                    serie.updateByIndex(i, avg);
                    nbFluctuations++;
                }
                prevPrevY = prevY;
                prevY = currentY;
            }
            doSmoothing = (nbFluctuations > points.size() / 2) ? true : false;
        }

    }
    return series;
}

From source file:org.janusgraph.graphdb.idmanagement.VariableLongTest.java

@Test
public void byteOrderPreservingPositiveBackward() {
    long[] scalingFactors = { Long.MAX_VALUE, 1000, 1000000000l };
    for (int t = 0; t < 10000000; t++) {
        StaticBuffer[] b = new StaticBuffer[2];
        long[] l = new long[2];
        for (int i = 0; i < 2; i++) {
            l[i] = randomPosLong(scalingFactors[random.nextInt(scalingFactors.length)]);
            WriteBuffer out = new WriteByteBuffer(11);
            VariableLong.writePositiveBackward(out, l[i]);
            b[i] = out.getStaticBuffer();
            ReadBuffer res = b[i].asReadBuffer();
            res.movePositionTo(res.length());
            assertEquals(l[i], VariableLong.readPositiveBackward(res));
        }// w  w w .ja v  a  2  s.co  m
        //            System.out.println(l[0] + " vs " + l[1]);
        assertEquals(Math.signum(Long.compare(l[0], l[1])), Math.signum(b[0].compareTo(b[1])), 0.01);
    }

}

From source file:org.netxilia.functions.MathFunctions.java

public double SIGN(double number) {
    return Math.signum(number);
}

From source file:opendial.gui.stateviewer.DistributionViewer.java

private List<XYSeries> extractSeries(DensityFunction function) throws DialException {

    List<XYSeries> series = new ArrayList<XYSeries>();

    for (int i = 0; i < function.getDimensionality(); i++) {
        series.add(new XYSeries("dimension " + i));
    }/*from  www  .  j a  v a  2 s .  c  om*/

    Consumer<double[]> addToSeries = p -> {
        double density = function.getDensity(p);
        for (int d = 0; d < p.length; d++) {
            series.get(d).add(p[d], density);
        }
    };

    Set<double[]> points = function.discretise(500).keySet();
    points.stream().forEach(addToSeries);

    for (XYSeries serie : series) {
        boolean doSmoothing = (function instanceof KernelDensityFunction)
                || (function instanceof DirichletDensityFunction);
        while (doSmoothing) {
            int nbFluctuations = 0;
            double prevPrevY = serie.getY(0).doubleValue();
            double prevY = serie.getY(1).doubleValue();
            for (int i = 2; i < serie.getItemCount(); i++) {
                double currentY = serie.getY(i).doubleValue();
                if (Math.signum(prevY - prevPrevY) != Math.signum(currentY - prevY)) {
                    double avg = (prevPrevY + prevY + currentY) / 3.0;
                    serie.updateByIndex(i - 2, avg);
                    serie.updateByIndex(i - 1, avg);
                    serie.updateByIndex(i, avg);
                    nbFluctuations++;
                }
                prevPrevY = prevY;
                prevY = currentY;
            }
            doSmoothing = (nbFluctuations > points.size() / 2) ? true : false;
        }

    }
    return series;
}

From source file:com.opengamma.analytics.financial.interestrate.ParRateCurveSensitivityCalculator.java

/**
 * Computes the sensitivity to the curve of swap convention-modified par rate for a fixed coupon swap with a PVBP externally provided.
 * <P>Reference: Swaption pricing - v 1.3, OpenGamma Quantitative Research, June 2012.
 * @param swap The swap./*w w  w. ja v  a2 s  . c  om*/
 * @param dayCount The day count convention to modify the swap rate.
 * @param curves The curves.
 * @return The modified rate.
 */
public Map<String, List<DoublesPair>> visitFixedCouponSwap(final SwapFixedCoupon<?> swap,
        final DayCount dayCount, final YieldCurveBundle curves) {
    final double pvSecond = PV_CALCULATOR.visit(swap.getSecondLeg(), curves)
            * Math.signum(swap.getSecondLeg().getNthPayment(0).getNotional());
    final double pvbp = METHOD_SWAP.presentValueBasisPoint(swap, dayCount, curves);
    final InterestRateCurveSensitivity pvbpDr = METHOD_SWAP.presentValueBasisPointCurveSensitivity(swap,
            dayCount, curves);
    final InterestRateCurveSensitivity pvSecondDr = new InterestRateCurveSensitivity(
            PV_SENSITIVITY_CALCULATOR.visit(swap.getSecondLeg(), curves))
                    .multiply(Math.signum(swap.getSecondLeg().getNthPayment(0).getNotional()));
    InterestRateCurveSensitivity result = pvSecondDr.multiply(1.0 / pvbp)
            .plus(pvbpDr.multiply(-pvSecond / (pvbp * pvbp)));
    return result.getSensitivities();
}