Example usage for java.util Arrays binarySearch

List of usage examples for java.util Arrays binarySearch

Introduction

In this page you can find the example usage for java.util Arrays binarySearch.

Prototype

public static int binarySearch(Object[] a, Object key) 

Source Link

Document

Searches the specified array for the specified object using the binary search algorithm.

Usage

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

/**
 * Computes the present value curve sensitivity of the Physical delivery swaption.
 * @param swaption The swaption.//from  ww  w  .  ja  v  a2s . co m
 * @param lmmData The LMM and multi-curves provider.
 * @return The present value.
 */
public MultipleCurrencyMulticurveSensitivity presentValueCurveSensitivity(
        final SwaptionPhysicalFixedIbor swaption, //CSIGNORE
        final LiborMarketModelDisplacedDiffusionProviderInterface lmmData) {
    ArgumentChecker.notNull(swaption, "Swaption");
    ArgumentChecker.notNull(lmmData, "LMM provider");
    final Currency ccy = swaption.getCurrency();
    final MulticurveProviderInterface multicurves = lmmData.getMulticurveProvider();
    final LiborMarketModelDisplacedDiffusionParameters parameters = lmmData.getLMMParameters();
    // 1. Swaption CFE preparation
    final AnnuityPaymentFixed cfe = swaption.getUnderlyingSwap().accept(CFEC, multicurves);
    final int nbCFInit = cfe.getNumberOfPayments();
    final double multFact = Math.signum(cfe.getNthPayment(0).getAmount());
    final boolean isCall = (cfe.getNthPayment(0).getAmount() < 0);
    final double[] cftInit = new double[nbCFInit];
    final double[] cfaInit = new double[nbCFInit];
    for (int loopcf = 0; loopcf < nbCFInit; loopcf++) {
        cftInit[loopcf] = cfe.getNthPayment(loopcf).getPaymentTime();
        cfaInit[loopcf] = cfe.getNthPayment(loopcf).getAmount() * -multFact;
    }
    final double timeToExpiry = swaption.getTimeToExpiry();
    // 2. Model data
    final int nbFactor = parameters.getNbFactor();
    final double[][] volLMM = parameters.getVolatility();
    final double[] timeLMM = parameters.getIborTime();
    // 3. Link cfe dates to lmm
    final int[] indCFDate = new int[nbCFInit];
    int indStart = nbCFInit - 1;
    int indEnd = 0;
    for (int loopcf = 0; loopcf < nbCFInit; loopcf++) {
        indCFDate[loopcf] = Arrays.binarySearch(timeLMM, cftInit[loopcf]);
        if (indCFDate[loopcf] < 0) {
            if (timeLMM[-indCFDate[loopcf] - 1] - cftInit[loopcf] < TIME_TOLERANCE) {
                indCFDate[loopcf] = -indCFDate[loopcf] - 1;
            } else {
                if (cftInit[loopcf] - timeLMM[-indCFDate[loopcf] - 2] < TIME_TOLERANCE) {
                    indCFDate[loopcf] = -indCFDate[loopcf] - 2;
                } else {
                    Validate.isTrue(true, "Instrument time incompatible with LMM");
                }
            }
        }
        if (indCFDate[loopcf] < indStart) {
            indStart = indCFDate[loopcf];
        }
        if (indCFDate[loopcf] > indEnd) {
            indEnd = indCFDate[loopcf];
        }
    }
    final int nbCF = indEnd - indStart + 1;
    final double[] cfa = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCFInit; loopcf++) {
        cfa[indCFDate[loopcf] - indStart] = cfaInit[loopcf];
    }
    final double[] cft = new double[nbCF];
    System.arraycopy(timeLMM, indStart, cft, 0, nbCF);
    final double[] dfLMM = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        dfLMM[loopcf] = multicurves.getDiscountFactor(ccy, cft[loopcf]);
    }
    final double[][] gammaLMM = new double[nbCF - 1][nbFactor];
    final double[] deltaLMM = new double[nbCF - 1];
    System.arraycopy(parameters.getAccrualFactor(), indStart, deltaLMM, 0, nbCF - 1);
    final double[] aLMM = new double[nbCF - 1];
    System.arraycopy(parameters.getDisplacement(), indStart, aLMM, 0, nbCF - 1);
    final double[] liborLMM = new double[nbCF - 1];
    final double amr = parameters.getMeanReversion();
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        gammaLMM[loopcf] = volLMM[indStart + loopcf];
        liborLMM[loopcf] = (dfLMM[loopcf] / dfLMM[loopcf + 1] - 1.0d) / deltaLMM[loopcf];
    }
    final double[] cfaMod = new double[nbCF + 1];
    final double cfaMod0 = cfa[0];
    cfaMod[0] = cfaMod0; // modified strike
    cfaMod[1] = 0.0; // TODO: 4. cfe modification (for roller coasters)
    System.arraycopy(cfa, 1, cfaMod, 2, nbCF - 1);
    // 5. Pricing algorithm
    final double[] p0 = new double[nbCF];
    final double[] dP = new double[nbCF];
    double b0 = 0;
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        p0[loopcf] = dfLMM[loopcf] / dfLMM[0];
        dP[loopcf] = cfaMod[loopcf + 1] * p0[loopcf];
        b0 += dP[loopcf];
    }
    final double bK = -cfaMod[0];
    final double bM = (b0 + bK) / 2.0d;
    final double[] rate0Ratio = new double[nbCF - 1];
    final double[][] mu0 = new double[nbCF - 1][nbFactor];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        rate0Ratio[loopcf] = (liborLMM[loopcf] + aLMM[loopcf]) / (liborLMM[loopcf] + 1 / deltaLMM[loopcf]);
    }
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        mu0[0][loopfact] = rate0Ratio[0] * gammaLMM[0][loopfact];
    }
    for (int loopcf = 1; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            mu0[loopcf][loopfact] = mu0[loopcf - 1][loopfact] + rate0Ratio[loopcf] * gammaLMM[loopcf][loopfact];
        }
    }
    final double meanReversionImpact = (Math.exp(2.0d * amr * timeToExpiry) - 1.0d) / (2.0d * amr);
    final double[] tau = new double[nbCF];
    final double[] tau2 = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            tau2[loopcf + 1] += mu0[loopcf][loopfact] * mu0[loopcf][loopfact];
        }
        tau2[loopcf + 1] = tau2[loopcf + 1] * meanReversionImpact;
        tau[loopcf + 1] = Math.sqrt(tau2[loopcf + 1]);
    }
    double sumNum = -bM;
    double sumDen = 0;
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        sumNum += dP[loopcf] - dP[loopcf] * tau2[loopcf] / 2.0;
        sumDen += dP[loopcf] * tau[loopcf];
    }
    final double xBar = sumNum / sumDen;
    final double[] pM = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        pM[loopcf] = p0[loopcf] * (1 - xBar * tau[loopcf] - tau2[loopcf] / 2.0);
    }
    final double[] liborM = new double[nbCF - 1];
    final double[] alphaM = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        liborM[loopcf] = (pM[loopcf] / pM[loopcf + 1] - 1.0d) / deltaLMM[loopcf];
    }
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        alphaM[loopcf] = cfaMod[loopcf + 1] * pM[loopcf] / bM;
    }
    final double[] rateMRatio = new double[nbCF - 1];
    final double[][] muM = new double[nbCF - 1][nbFactor];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        rateMRatio[loopcf] = (liborM[loopcf] + aLMM[loopcf]) / (liborM[loopcf] + 1 / deltaLMM[loopcf]);
    }
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        muM[0][loopfact] = rateMRatio[0] * gammaLMM[0][loopfact];
    }
    for (int loopcf = 1; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            muM[loopcf][loopfact] = muM[loopcf - 1][loopfact] + rateMRatio[loopcf] * gammaLMM[loopcf][loopfact];
        }
    }
    double normSigmaM = 0;
    final double[] sigmaM = new double[nbFactor];
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
            sigmaM[loopfact] += alphaM[loopcf + 1] * muM[loopcf][loopfact];
        }
        normSigmaM += sigmaM[loopfact] * sigmaM[loopfact];
    }
    final double impliedBlackVol = Math.sqrt(normSigmaM * meanReversionImpact);
    final EuropeanVanillaOption option = new EuropeanVanillaOption(bK, 1, isCall);
    final BlackPriceFunction blackFunction = new BlackPriceFunction();
    final BlackFunctionData dataBlack = new BlackFunctionData(b0, 1.0, impliedBlackVol);
    final double[] blkAdjoint = blackFunction.getPriceAdjoint(option, dataBlack);
    // Backward sweep
    final double pvBar = 1.0;
    final double impliedBlackVolBar = dfLMM[0] * blkAdjoint[2] * (swaption.isLong() ? 1.0 : -1.0) * pvBar;
    final double normSigmaMBar = meanReversionImpact / (2.0 * impliedBlackVol) * impliedBlackVolBar;
    final double[] sigmaMBar = new double[nbFactor];
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        sigmaMBar[loopfact] = 2 * sigmaM[loopfact] * normSigmaMBar;
    }
    final double[][] muMBar = new double[nbCF - 1][nbFactor];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            muMBar[loopcf][loopfact] = alphaM[loopcf + 1] * sigmaMBar[loopfact];
        }
    }
    for (int loopcf = nbCF - 3; loopcf >= 0; loopcf--) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            muMBar[loopcf][loopfact] += muMBar[loopcf + 1][loopfact];
        }
    }
    final double[] rateMRatioBar = new double[nbCF - 1];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            rateMRatioBar[loopcf] += gammaLMM[loopcf][loopfact] * muMBar[loopcf][loopfact];
        }
    }
    final double[] alphaMBar = new double[nbCF];
    for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
        for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
            alphaMBar[loopcf + 1] += muM[loopcf][loopfact] * sigmaMBar[loopfact];
        }
    }
    final double[] liborMBar = new double[nbCF - 1];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        liborMBar[loopcf] = ((liborM[loopcf] + 1 / deltaLMM[loopcf]) - (liborM[loopcf] + aLMM[loopcf]))
                / ((liborM[loopcf] + 1 / deltaLMM[loopcf]) * (liborM[loopcf] + 1 / deltaLMM[loopcf]))
                * rateMRatioBar[loopcf];
    }
    final double[] pMBar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        pMBar[loopcf] += 1.0 / pM[loopcf + 1] / deltaLMM[loopcf] * liborMBar[loopcf];
        pMBar[loopcf + 1] += -pM[loopcf] / (pM[loopcf + 1] * pM[loopcf + 1]) / deltaLMM[loopcf]
                * liborMBar[loopcf];
    }
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        pMBar[loopcf] += cfaMod[loopcf + 1] / bM * alphaMBar[loopcf];
    }
    double xBarBar = 0.0;
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        xBarBar += -p0[loopcf] * tau[loopcf] * pMBar[loopcf];
    }
    final double sumNumBar = 1.0 / sumDen * xBarBar;
    final double sumDenBar = -sumNum / (sumDen * sumDen) * xBarBar;
    final double[] tauBar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        tauBar[loopcf] = -p0[loopcf] * xBar * pMBar[loopcf];
    }
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        tauBar[loopcf] += dP[loopcf] * sumDenBar;
    }
    final double[] tau2Bar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        tau2Bar[loopcf] = -p0[loopcf] / 2.0 * pMBar[loopcf];
    }
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        tau2Bar[loopcf] += -dP[loopcf] / 2.0 * sumNumBar;
    }
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        tau2Bar[loopcf + 1] += 1.0 / tau[loopcf + 1] / 2.0 * tauBar[loopcf + 1];
    }
    final double[][] mu0Bar = new double[nbCF - 1][nbFactor];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            mu0Bar[loopcf][loopfact] = 2.0 * mu0[loopcf][loopfact] * meanReversionImpact * tau2Bar[loopcf + 1];
        }
    }
    for (int loopcf = nbCF - 3; loopcf >= 0; loopcf--) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            mu0Bar[loopcf][loopfact] += mu0Bar[loopcf + 1][loopfact];
        }
    }
    final double[] rate0RatioBar = new double[nbCF - 1];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        for (int loopfact = 0; loopfact < nbFactor; loopfact++) {
            rate0RatioBar[loopcf] += gammaLMM[loopcf][loopfact] * mu0Bar[loopcf][loopfact];
        }
    }
    double bMBar = -sumNumBar;
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        bMBar += -cfaMod[loopcf + 1] * pM[loopcf] / (bM * bM) * alphaMBar[loopcf];
    }
    double bKBar = bMBar / 2.0;
    bKBar += dfLMM[0] * blkAdjoint[3] * (swaption.isLong() ? 1.0 : -1.0) * pvBar;
    double b0Bar = bMBar / 2.0;
    b0Bar += dfLMM[0] * blkAdjoint[1] * (swaption.isLong() ? 1.0 : -1.0) * pvBar;
    final double[] dPBar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        dPBar[loopcf] = b0Bar + tau[loopcf] * sumDenBar + (1.0 - tau2[loopcf] / 2.0) * sumNumBar;
    }
    final double[] p0Bar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        p0Bar[loopcf] = cfaMod[loopcf + 1] * dPBar[loopcf]
                + (1 - xBar * tau[loopcf] - tau2[loopcf] / 2.0) * pMBar[loopcf];
    }

    final double[] cfaModBar = new double[nbCF + 1];
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        cfaModBar[loopcf + 1] = p0[loopcf] * dPBar[loopcf] + pM[loopcf] / bM * alphaMBar[loopcf];
    }
    cfaModBar[0] += -bKBar;

    final double[] liborLMMBar = new double[nbCF - 1];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        liborLMMBar[loopcf] = (1.0 / (liborLMM[loopcf] + 1 / deltaLMM[loopcf])
                - (liborLMM[loopcf] + aLMM[loopcf]) / ((liborLMM[loopcf] + 1 / deltaLMM[loopcf])
                        * (liborLMM[loopcf] + 1 / deltaLMM[loopcf])))
                * rate0RatioBar[loopcf];
    }
    final double[] dfLMMBar = new double[nbCF];
    for (int loopcf = 0; loopcf < nbCF - 1; loopcf++) {
        dfLMMBar[loopcf] += (1.0 / dfLMM[loopcf + 1]) / deltaLMM[loopcf] * liborLMMBar[loopcf];
        dfLMMBar[loopcf + 1] += -dfLMM[loopcf] / (dfLMM[loopcf + 1] * dfLMM[loopcf + 1]) / deltaLMM[loopcf]
                * liborLMMBar[loopcf];
    }
    for (int loopcf = 1; loopcf < nbCF; loopcf++) {
        dfLMMBar[loopcf] += 1.0 / dfLMM[0] * p0Bar[loopcf];
        dfLMMBar[0] += -dfLMM[loopcf] / (dfLMM[0] * dfLMM[0]) * p0Bar[loopcf];
    }
    dfLMMBar[0] += blkAdjoint[0] * (swaption.isLong() ? 1.0 : -1.0) * pvBar;
    final double[] cfaBar = new double[nbCF];
    cfaBar[0] = cfaModBar[0];
    System.arraycopy(cfaModBar, 2, cfaBar, 1, nbCF - 1);
    final double[] cfaInitBar = new double[nbCFInit];
    for (int loopcf = 0; loopcf < nbCFInit; loopcf++) {
        cfaInitBar[loopcf] = cfaBar[indCFDate[loopcf] - indStart];
    }

    final List<DoublesPair> listDfSensi = new ArrayList<>();
    for (int loopcf = 0; loopcf < nbCF; loopcf++) {
        final DoublesPair dfSensi = new DoublesPair(cft[loopcf],
                -cft[loopcf] * dfLMM[loopcf] * dfLMMBar[loopcf]);
        listDfSensi.add(dfSensi);
    }
    final Map<String, List<DoublesPair>> pvsDF = new HashMap<>();
    pvsDF.put(multicurves.getName(ccy), listDfSensi);
    MulticurveSensitivity sensitivity = MulticurveSensitivity.ofYieldDiscounting(pvsDF);

    final Map<Double, MulticurveSensitivity> cfeCurveSensi = swaption.getUnderlyingSwap().accept(CFECSC,
            multicurves);
    for (int loopcf = 0; loopcf < cfe.getNumberOfPayments(); loopcf++) {
        final MulticurveSensitivity sensiCfe = cfeCurveSensi.get(cfe.getNthPayment(loopcf).getPaymentTime());
        if (!(sensiCfe == null)) { // There is some sensitivity to that cfe.
            sensitivity = sensitivity.plus(sensiCfe.multipliedBy(-multFact * cfaInitBar[loopcf]));
        }
    }
    return MultipleCurrencyMulticurveSensitivity.of(ccy, sensitivity);
}

From source file:fastcall.FastCallSNP.java

private void updateTaxaBamPathMap(String bamListFileS) {
    Table t = new Table(bamListFileS);
    String[] existingBam = new String[t.getRowNumber()];
    for (int i = 0; i < t.getRowNumber(); i++)
        existingBam[i] = t.content[i][0];
    Arrays.sort(existingBam);/*w ww  .ja  v  a 2 s.c o m*/
    HashSet<String> existingTaxaSet = new HashSet();
    HashMap<String, String[]> updatedTaxaBamMap = new HashMap();
    ArrayList<String> pathList = new ArrayList();
    int cnt = 0;
    for (int i = 0; i < taxaNames.length; i++) {
        String[] bamNames = taxaBamPathMap.get(taxaNames[i]);
        ArrayList<String> bamList = new ArrayList();
        for (int j = 0; j < bamNames.length; j++) {
            int index = Arrays.binarySearch(existingBam, bamNames[j]);
            if (index < 0)
                continue;
            bamList.add(bamNames[j]);
            existingTaxaSet.add(taxaNames[i]);
            pathList.add(bamNames[j]);
        }
        if (bamList.isEmpty())
            continue;
        bamNames = bamList.toArray(new String[bamList.size()]);
        Arrays.sort(bamNames);
        updatedTaxaBamMap.put(taxaNames[i], bamNames);
        cnt += bamNames.length;
    }
    String[] updatedTaxaNames = existingTaxaSet.toArray(new String[existingTaxaSet.size()]);
    Arrays.sort(updatedTaxaNames);
    taxaNames = updatedTaxaNames;
    taxaBamPathMap = updatedTaxaBamMap;
    this.bamPaths = pathList.toArray(new String[pathList.size()]);
    Arrays.sort(bamPaths);
    System.out.println("Actual taxa number:\t" + String.valueOf(taxaNames.length));
    System.out.println("Actual bam file number:\t" + String.valueOf(cnt));
    System.out.println();
}

From source file:com.sidekickApp.analytics.LocalyticsSession.java

/**
 * Sorts an int value into a predefined, pre-sorted set of intervals, returning a string representing the new expected value.
 * The array must be sorted in ascending order, with the first element representing the inclusive lower bound and the last
 * element representing the exclusive upper bound. For instance, the array [0,1,3,10] will provide the following buckets: less
 * than 0, 0, 1-2, 3-9, 10 or greater./*from  ww w .j  av  a  2 s . c o m*/
 *
 * @param actualValue The int value to be bucketed.
 * @param steps The sorted int array representing the bucketing intervals.
 * @return String representation of {@code actualValue} that has been bucketed into the range provided by {@code steps}.
 * @throws IllegalArgumentException if {@code steps} is null.
 * @throws IllegalArgumentException if {@code steps} has length 0.
 */
public static String createRangedAttribute(final int actualValue, final int[] steps) {
    if (null == steps) {
        throw new IllegalArgumentException("steps cannot be null"); //$NON-NLS-1$
    }

    if (steps.length == 0) {
        throw new IllegalArgumentException("steps length must be greater than 0"); //$NON-NLS-1$
    }

    String bucket = null;

    // if less than smallest value
    if (actualValue < steps[0]) {
        bucket = "less than " + steps[0];
    }
    // if greater than largest value
    else if (actualValue >= steps[steps.length - 1]) {
        bucket = steps[steps.length - 1] + " and above";
    } else {
        // binarySearch returns the index of the value, or (-(insertion point) - 1) if not found
        int bucketIndex = Arrays.binarySearch(steps, actualValue);
        if (bucketIndex < 0) {
            // if the index wasn't found, then we want the value before the insertion point as the lower end
            // the special case where the insertion point is 0 is covered above, so we don't have to worry about it here
            bucketIndex = (-bucketIndex) - 2;
        }
        if (steps[bucketIndex] == (steps[bucketIndex + 1] - 1)) {
            bucket = Integer.toString(steps[bucketIndex]);
        } else {
            bucket = steps[bucketIndex] + "-" + (steps[bucketIndex + 1] - 1); //$NON-NLS-1$
        }
    }
    return bucket;
}

From source file:net.sf.maltcms.chromaui.charts.Chromatogram1DChartProvider.java

/**
 *
 * @param f//ww  w. java2  s  . co m
 * @param useScanAcquisitionTime
 * @param outline
 * @param fill
 * @param valueVar
 * @return
 */
public static List<XYAnnotation> generatePeakShapes(IFileFragment f, boolean useScanAcquisitionTime,
        Color outline, Color fill, String valueVar) {
    List<XYAnnotation> l = new ArrayList<>();
    try {
        IVariableFragment peakNames = f.getChild("peak_name");
        IVariableFragment peakRT = f.getChild("peak_retention_time");
        IVariableFragment peakStartRT = f.getChild("peak_start_time");
        IVariableFragment peakStopRT = f.getChild("peak_end_time");

        int peaks = peakRT.getArray().getShape()[0];

        boolean baselineAvailable = true;

        IVariableFragment blStartRT = null;
        IVariableFragment blStopRT = null;
        IVariableFragment blStartValue = null;
        IVariableFragment blStopValue = null;

        try {
            blStartRT = f.getChild("baseline_start_time");
            blStopRT = f.getChild("baseline_stop_time");
            blStartValue = f.getChild("baseline_start_value");
            blStopValue = f.getChild("baseline_stop_value");
        } catch (ResourceNotAvailableException e) {
            baselineAvailable = false;
        }

        boolean andichromMode = valueVar.equals("ordinate_values");

        Array ordinateValues = null;
        try {
            ordinateValues = f.getChild(valueVar).getArray();
        } catch (ResourceNotAvailableException rne) {
            ordinateValues = f.getChild("total_intensity").getArray();
            andichromMode = false;
        }

        Collection<String> peaknames = ArrayTools.getStringsFromArray(peakNames.getArray());
        IndexIterator ii = peakRT.getArray().getIndexIterator();

        Iterator<String> peaknamesIter = peaknames.iterator();

        for (int i = 0; i < peaks; i++) {
            double sat = ii.getDoubleNext();
            double peakStartTime = peakStartRT.getArray().getDouble(i);
            double peakStopTime = peakStopRT.getArray().getDouble(i);
            int scan = 0;
            int startIdx, stopIdx;
            if (andichromMode) {
                double delay = f.getChild("actual_delay_time").getArray().getDouble(0);
                double samplingRate = f.getChild("actual_sampling_interval").getArray().getDouble(0);
                scan = (int) (Math.floor(((sat - delay) / samplingRate)));
                startIdx = (int) (Math.floor(((peakStartTime - delay) / samplingRate)));
                stopIdx = (int) (Math.floor(((peakStopTime - delay) / samplingRate)));
            } else {
                Array satA = f.getChild("scan_acquisition_time").getArray();
                double[] d = (double[]) satA.get1DJavaArray(double.class);
                scan = Arrays.binarySearch(d, sat);
                if (scan < 0) {
                    scan = ((-1) * (scan + 1));
                }
                startIdx = Arrays.binarySearch(d, peakStartTime);
                stopIdx = Arrays.binarySearch(d, peakStopTime);
                if (startIdx < 0) {
                    startIdx = ((-1) * (startIdx + 1));
                }
                if (stopIdx < 0) {
                    stopIdx = ((-1) * (stopIdx + 1));
                }
            }
            String name = peaknamesIter.next();
            double blStartTime, blStopTime, blStartVal, blStopVal;
            if (baselineAvailable) {
                blStartTime = blStartRT.getArray().getDouble(i);
                blStopTime = blStopRT.getArray().getDouble(i);
                blStartVal = blStartValue.getArray().getDouble(i);
                blStopVal = blStopValue.getArray().getDouble(i);
            } else {
                blStartTime = peakStartTime;
                blStopTime = peakStopTime;
                blStartVal = ordinateValues.getDouble(startIdx);
                blStopVal = ordinateValues.getDouble(stopIdx);
            }

            if (name.trim().isEmpty()) {
                name = "NN";
            }

            GeneralPath gp = new GeneralPath();
            if (useScanAcquisitionTime) {
                Array sat2 = f.getChild("scan_acquisition_time").getArray();
                gp.moveTo(peakStartTime, ordinateValues.getDouble(startIdx));
                for (int j = startIdx + 1; j <= stopIdx + 1; j++) {
                    gp.lineTo(sat2.getDouble(j), ordinateValues.getDouble(j));
                }
                gp.lineTo(Math.max(blStopTime, peakStopTime), blStopVal);
                gp.lineTo(Math.min(blStartTime, peakStartTime), blStartVal);
                gp.closePath();
                //gp.closePath();
                Rectangle2D.Double bbox = new Rectangle2D.Double(peakStartTime, 0, peakStopTime - peakStartTime,
                        ordinateValues.getDouble(scan));
                Area a = new Area(bbox);
                a.intersect(new Area(gp));
                XYShapeAnnotation xypa = new XYShapeAnnotation(a, new BasicStroke(), outline, fill);
                XYLineAnnotation xyla = new XYLineAnnotation(blStartTime, blStartVal, blStopTime, blStopVal,
                        new BasicStroke(), Color.BLACK);
                l.add(xypa);
                l.add(xyla);
                //                    XYLineAnnotation baseline = new XYLineAnnotation();
            } else {
                gp.moveTo(startIdx, ordinateValues.getDouble(startIdx));
                for (int j = startIdx + 1; j <= stopIdx + 1; j++) {
                    gp.lineTo(j, ordinateValues.getDouble(j));
                }
                gp.closePath();
                XYShapeAnnotation xypa = new XYShapeAnnotation(gp, new BasicStroke(), outline, fill);
                l.add(xypa);
            }
        }
    } catch (ResourceNotAvailableException rnae) {
        Logger.getLogger(Chromatogram1DChartProvider.class.getName()).info(rnae.getLocalizedMessage());
    }
    return l;
}

From source file:edu.cornell.med.icb.goby.alignments.AlignmentCollectionHandler.java

private int[] frequencies(final IntList list, final int[] symbolValues) {
    final int[] freqs = new int[symbolValues.length];
    for (final int value : list) {
        final int index = Arrays.binarySearch(symbolValues, value);
        freqs[index] += 1;// w w w .  j ava  2  s  .c  o m
    }
    return freqs;
}

From source file:Main.java

/**
 * @param symbol encoded symbol to translate to a codeword
 * @return the codeword corresponding to the symbol.
 *//*from   www .j ava 2s.  c o m*/
public static int getCodeword(int symbol) {
    int i = Arrays.binarySearch(SYMBOL_TABLE, symbol & 0x3FFFF);
    if (i < 0) {
        return -1;
    }
    return (CODEWORD_TABLE[i] - 1) % NUMBER_OF_CODEWORDS;
}

From source file:cn.pholance.datamanager.common.components.JRViewer.java

void btnZoomInActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnZoomInActionPerformed
{//GEN-HEADEREND:event_btnZoomInActionPerformed
 // Add your handling code here:
    btnActualSize.setSelected(false);/*  w ww. ja  v  a  2 s  .com*/
    btnFitPage.setSelected(false);
    btnFitWidth.setSelected(false);

    int newZoomInt = (int) (100 * getZoomRatio());
    int index = Arrays.binarySearch(zooms, newZoomInt);
    if (index < 0) {
        setZoomRatio(zooms[-index - 1] / 100f);
    } else if (index < cmbZoom.getModel().getSize() - 1) {
        setZoomRatio(zooms[index + 1] / 100f);
    }
}

From source file:net.sf.firemox.clickable.target.card.MCard.java

/**
 * Refresh the properties of this card, and raise an event if the value has
 * been changed. NOTE : there is no cache for properties.
 * //from  w  ww . j a  va 2  s  .  c o  m
 * @param property
 *          the property to refresh.
 */
public void refreshProperties(int property) {
    final CardModel cardModel = getCardModel();
    boolean raised = false;
    if (property == IdConst.ALL) {
        // All properties have to be refreshed
        java.util.Set<Integer> oldProperties = new HashSet<Integer>(cachedProperties);
        cachedProperties.clear();
        for (int initProperty : cardModel.getProperties()) {
            cachedProperties.add(initProperty);
        }
        if (propertyModifier != null) {
            propertyModifier.fillProperties(cachedProperties);
        }
        for (Integer cacheProperty : cachedProperties) {
            if (!oldProperties.contains(cacheProperty)) {
                ModifiedProperty.dispatchEvent(this, cacheProperty);
                raised = true;
            }
        }
        for (Integer oldProperty : oldProperties) {
            if (!cachedProperties.contains(oldProperty)) {
                ModifiedProperty.dispatchEvent(this, oldProperty);
                raised = true;
            }
        }
    } else {
        final boolean oldFound = cachedProperties.contains(property);
        int[] properties = cardModel.getProperties();
        boolean found = properties != null && Arrays.binarySearch(properties, property) >= 0;
        if (propertyModifier != null) {
            found = propertyModifier.hasProperty(property, found);
        }
        if (oldFound != found) {
            if (found) {
                cachedProperties.add(property);
            } else {
                cachedProperties.remove(property);
            }
            ModifiedProperty.dispatchEvent(this, property);
            raised = true;
        }
    }
    if (raised) {
        ui.resetCachedData();
        repaint();
    }
}

From source file:cn.pholance.datamanager.common.components.JRViewer.java

void btnZoomOutActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnZoomOutActionPerformed
{//GEN-HEADEREND:event_btnZoomOutActionPerformed
 // Add your handling code here:
    btnActualSize.setSelected(false);// ww  w .  j a v  a2 s. co  m
    btnFitPage.setSelected(false);
    btnFitWidth.setSelected(false);

    int newZoomInt = (int) (100 * getZoomRatio());
    int index = Arrays.binarySearch(zooms, newZoomInt);
    if (index > 0) {
        setZoomRatio(zooms[index - 1] / 100f);
    } else if (index < -1) {
        setZoomRatio(zooms[-index - 2] / 100f);
    }
}

From source file:net.rptools.maptool.launcher.MapToolLauncher.java

private void parseCfgValues(Map<String, String> values, List<String> errors) {
    String dir;/*from   w w  w  .j a  v  a2s.  c  om*/
    File f;

    // This must be done before calling any methods of CopiedFromOtherJars or the LOCALE setting won't work.
    dir = values.get("LOCALE");
    if (dir != null) {
        dir = dir.trim();
        String prop = System.getProperty("user.language").trim();
        if (prop.isEmpty() || !dir.isEmpty()) {
            if (CopiedFromOtherJars.setLanguage(dir))
                mapToolLocale = dir;
        }
    }
    maxMemVal = CopiedFromOtherJars.parseInteger(values.get("MAXMEM"), DEFAULT_MAXMEM); //$NON-NLS-1$
    minMemVal = CopiedFromOtherJars.parseInteger(values.get("MINMEM"), DEFAULT_MINMEM); //$NON-NLS-1$
    stackSizeVal = CopiedFromOtherJars.parseInteger(values.get("STACKSIZE"), DEFAULT_STACKSIZE); //$NON-NLS-1$
    startConsole = CopiedFromOtherJars.parseBoolean(values.get("CONSOLE"), false); //$NON-NLS-1$
    promptUser = CopiedFromOtherJars.parseBoolean(values.get("PROMPT"), false); //$NON-NLS-1$
    jcbRelativePath.setSelected(CopiedFromOtherJars.parseBoolean(values.get("RELATIVE_PATHS"), false)); //$NON-NLS-1$

    // For the directory fields, they may be stored as either relative or absolute pathnames.
    // We keep only absolute pathnames internally and decide when writing out the config
    // file which type to save...
    dir = values.get("MAPTOOL_DIRECTORY"); //$NON-NLS-1$
    if (dir != null && !dir.isEmpty()) {
        // Returns 'null' when a relative name is passed in
        String normalDir = PathUtils.normalizeNoEndSeparator(dir);
        if (normalDir == null || normalDir.isEmpty()) {
            normalDir = PathUtils.normalizeNoEndSeparator(currentDir + File.separator + dir);
        }
        f = new File(normalDir);
        if (f.isDirectory()) {
            mapToolJarDir = f;
            logMsg(Level.INFO, "MAPTOOL_DIRECTORY={0}", null, f.toString());
        } else {
            String msg = CopiedFromOtherJars.getText("msg.error.bad.MAPTOOL_DIRECTORY", normalDir); //$NON-NLS-1$
            logMsg(Level.INFO, "Invalid directory for MAPTOOL_DIRECTORY: {0}\n{1}", null, dir, msg);
            errors.add(msg);
        }
    }
    dir = values.get("JAVA_DIRECTORY"); //$NON-NLS-1$
    if (dir != null && !dir.isEmpty()) {
        jbPathText = CopiedFromOtherJars.getText("msg.info.resetToDefaultJava"); //$NON-NLS-1$
        // Returns 'null' when a relative name is passed in
        String normalDir = PathUtils.normalizeNoEndSeparator(dir);
        if (normalDir == null || normalDir.isEmpty()) {
            normalDir = PathUtils.normalizeNoEndSeparator(mapToolJarDir + File.separator + dir);
        }
        f = new File(normalDir);
        if (f.isDirectory()) {
            javaDir = f.getAbsolutePath();
            logMsg(Level.INFO, "JAVA_DIRECTORY={0}", null, javaDir);
        } else {
            String msg = CopiedFromOtherJars.getText("msg.error.bad.JAVA_DIRECTORY", normalDir); //$NON-NLS-1$
            errors.add(msg);
        }
    }
    // For the data directory field allow multiple values.  They are, in increasing precedence:
    //   ~/.maptool
    //   DATA_DIRECTORY
    //   MAPTOOL_DATADIR
    //   MAPTOOL_DATADIR system property (from command line)
    dir = values.get("MAPTOOL_DATADIR"); //$NON-NLS-1$
    if (dir == null || dir.isEmpty()) {
        dir = values.get("DATA_DIRECTORY"); //$NON-NLS-1$
    }
    // If overridden on the command line, use that one in preference to what is currently in the file.
    // Note that this new value will be written back to the config file if/when the config file is saved.
    if (System.getProperty("MAPTOOL_DATADIR") != null) {
        dir = System.getProperty("MAPTOOL_DATADIR"); //$NON-NLS-1$
    }
    // If still no value, create one based on the user's home directory and the ".maptool" subdirectory.
    if (dir == null || dir.isEmpty()) {
        dir = System.getProperty("user.home") + File.separatorChar + ".maptool"; //$NON-NLS-1$ //$NON-NLS-2$
    }

    // Returns 'null' when a relative name is passed in
    String normalDir = PathUtils.normalizeNoEndSeparator(dir);
    if (normalDir == null || normalDir.isEmpty()) {
        normalDir = PathUtils.normalizeNoEndSeparator(mapToolJarDir + File.separator + dir);
    }
    f = new File(normalDir);
    mapToolDataDir = f.getAbsolutePath();
    if (f.isDirectory()) {
        logMsg(Level.INFO, "MAPTOOL_DATADIR={0}", null, f.getPath());
    } else {
        String msg = CopiedFromOtherJars.getText("msg.error.bad.MAPTOOL_DATADIR", normalDir); //$NON-NLS-1$
        errors.add(msg);
    }

    extraArgs = values.get("ARGS"); //$NON-NLS-1$
    if (extraArgs != null) {
        extraArgs = cleanExtraArgs(extraArgs);
        // This doesn't really work since we're not enforcing a word boundary on either side...
        jcbEnableAssertions.setSelected(extraArgs.contains(ASSERTIONS_OPTION));
    } else {
        extraArgs = EMPTY;
    }

    String[] logFiles;
    final String logging = values.get("LOGGING"); //$NON-NLS-1$
    if (logging != null && !logging.isEmpty()) {
        logFiles = logging.split("\\s*,\\s*"); //$NON-NLS-1$
        Arrays.sort(logFiles);
        for (final LoggingConfig config : logConfigs) {
            final int on = Arrays.binarySearch(logFiles, config.fname.getName());
            config.chkbox.setSelected(on >= 0);
        }
    }
    String jar = values.get("EXECUTABLE"); //$NON-NLS-1$
    if (jar != null) {
        // If specified, make sure it really exists.
        f = new File(mapToolJarDir, jar);
        if (f.isFile()) {
            mapToolJarName = f.getName();
        } else {
            String msg = CopiedFromOtherJars.getText("msg.error.bad.EXECUTABLE", f.toString()); //$NON-NLS-1$
            errors.add(msg);
            jar = null; // reset, so the next chunk can try to find a JAR file
        }
    }
    if (jar == null && mapToolJarDir != null) {
        // If there is no EXECUTABLE field (or it failed the above tests) but there is a
        // MAPTOOL_DIRECTORY field,
        // we want to search the MAPTOOL_DIRECTORY directory looking for a valid
        // matching MapTool jar and auto-select it if it's the only one.  Just trying to
        // save the user a little trouble.  Note that it will be written out later when
        // saving the config file.  Maybe we shouldn't do that?  That's a discussion for
        // the forums, I think.
        String[] names = mapToolJarDir.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                // Directory doesn't matter.  Just compare the filename.  We ignore case when
                // comparing, but we shouldn't need to.  MapTool is distributed with the JAR
                // filename in all lowercase, but what if the user decides to rename it to make
                // it look good?  (I've done that myself sometimes, in rare cases.)
                String n = name.toLowerCase();
                return n.startsWith("maptool-") && n.endsWith(".jar");
            }
        });
        if (names.length == 1)
            mapToolJarName = new File(mapToolJarDir, names[0]).getName();
    }
    if (mapToolJarName != null) {
        logMsg(Level.INFO, "EXECUTABLE={0}", null, mapToolJarName);
        jbMTJarText = mapToolJarName.replace(".jar", EMPTY); //$NON-NLS-1$
        if (mapToolJarName.toLowerCase().startsWith("maptool-")) { //$NON-NLS-1$
            // We expect the name matches 'maptool-1.3.b89.jar'
            mapToolVersion = " " + mapToolJarName.substring(8, 11); //$NON-NLS-1$
        } else {
            logMsg(Level.WARNING, "Cannot determine MapTool version number from JAR filename: {0}", null, f); //$NON-NLS-1$
            mapToolVersion = EMPTY;
        }
    }
}