Example usage for java.lang Double MAX_VALUE

List of usage examples for java.lang Double MAX_VALUE

Introduction

In this page you can find the example usage for java.lang Double MAX_VALUE.

Prototype

double MAX_VALUE

To view the source code for java.lang Double MAX_VALUE.

Click Source Link

Document

A constant holding the largest positive finite value of type double , (2-2-52)·21023.

Usage

From source file:org.jfree.data.statistics.HistogramDataset.java

/**
 * Returns the minimum value in an array of values.
 *
 * @param values  the values (<code>null</code> not permitted and
 *                zero-length array not permitted).
 *
 * @return The minimum value.//  w ww . j  a va 2 s.  c  om
 */
private double getMinimum(double[] values) {
    if (values == null || values.length < 1) {
        throw new IllegalArgumentException("Null or zero length 'values' argument.");
    }
    double min = Double.MAX_VALUE;
    for (int i = 0; i < values.length; i++) {
        if (values[i] < min) {
            min = values[i];
        }
    }
    return min;
}

From source file:edu.oregonstate.eecs.mcplan.Controller.java

private ActionNode selectAction(final StateNode sn, final ActionGenerator<S, ? extends A> actions) {
     assert (actions.size() > 0);
     double max_value = -Double.MAX_VALUE;
     ActionNode max_sa = null;/*from w  ww .  j  ava  2s  .  co  m*/
     while (actions.hasNext()) {
         final A a = actions.next();
         final ActionNode sa = sn.action(a);
         if (sa.n == 0) {
             max_sa = sa;
             break;
         } else {
             final double exploit = sa.q();
             final double explore = c_ * Math.sqrt(Math.log(sn.n) / sa.n);
             final double v = explore + exploit;
             if (v > max_value) {
                 max_sa = sa;
                 max_value = v;
             }
         }
     }
     return max_sa;
 }

From source file:com.talkdesk.geo.GeoCodeResolver.java

/**
 * Get the minimum distance/*from ww  w.j a  v a 2  s  .c o  m*/
 * @param numberList
 * @return
 * @throws GeoResolverException
 */
public String getClosestNumber(Hashtable<String, Double> numberList) throws GeoResolverException {
    String closest = "";
    Double lowestDistance = Double.MAX_VALUE;

    for (String key : numberList.keySet()) {
        Double currentDistance = numberList.get(key);
        if (currentDistance < lowestDistance) {
            lowestDistance = currentDistance;
            closest = key;
        }
    }
    return !closest.isEmpty() ? getTownFromNumber(closest) + " - " + closest : null;
}

From source file:eu.crisis_economics.abm.firm.TestExogenousFirm.java

/**
  * Test whether an instance of {@link ExogenousFirm} behaves as expected. This
  * test operates as follows:<br><br>
  * // w  ww.  ja  v a2  s  . co m
  * {@code (a)}
  *   One {@link StockTradingBank} is created, to serve as a {@link StockHolder}
  *   and {@link DepositHolder} for an {@link ExogenousFirm};<br>
  * {@code (b)}
  *   One {@link ExogenousFirm} is created, as well as one goods market and one
  *   labour market;<br>
  * {@code (c)}
  *   {@link UnivariateFunction}{@code s} are created for every decision on which
  *   the {@link ExogenousFirm} depends;<br>
  * {@code (d)}
  *   One {@link ExogenousGoodsBuyer} and one {@link ExogenousEmployee} are 
  *   created. Both are connected to the relevant markets;<br>
  * {@code (e)}
  *   The {@link ExogenousGoodsBuyer} is credited and debited several times, 
  *   and made subject to cash injections. It is asserted that the financial
  *   state of the {@link DepositHolder} is unchanged;<br>
  * {@code (f)}
  *   Several simulation cycles elapse. In each cycle, it is asserted that the
  *   balance sheet of the {@link ExogenousFirm} is as expected and that the
  *   {@link ExogenousFirm} has interacted with the markets as expected.
  */
@Test
public void testExogenousFirmBehaviour() {
    final StockTradingBank bank = new StockTradingBank(1.0); // 1 to pay for initial shares

    final Map<String, Pair<Double, Double>> goodsTypes = // One durable good,
            new HashMap<String, Pair<Double, Double>>(); //  one non-durable good.
    goodsTypes.put("type 1", Pair.create(1.0, 1.0)); // 100% time/use decay
    goodsTypes.put("type 2", Pair.create(0.1, 0.2)); // 10% time decay, 20% use decay.

    final SimpleGoodsMarket goodsMarket = new SimpleGoodsMarket(new ManualGoodsClassifier(goodsTypes),
            new ForagerMatchingAlgorithm(new HomogeneousRationingAlgorithm()));
    goodsMarket.addInstrument("type 1");
    goodsMarket.addInstrument("type 2");

    final SimpleLabourMarket labourMarket = new SimpleLabourMarket(
            new ForagerMatchingAlgorithm(new HomogeneousRationingAlgorithm()));

    final Random dice = new Random(1L);

    final class TestFunction implements UnivariateFunction {
        private final double grad;

        private TestFunction(Random dice) {
            grad = dice.nextDouble() + 1.;
        }

        @Override
        public double value(final double t) {
            return grad * (Math.floor(t) + 1.);
        }
    }

    final TimeseriesParameter<Double> deposits = createParameterFromUnivariateFunction(new TestFunction(dice)),
            commercialLoanDemand = createParameterFromUnivariateFunction(new TestFunction(dice)),
            desiredLabour = createParameterFromUnivariateFunction(new TestFunction(dice)),
            wageBidPrice = createParameterFromUnivariateFunction(new TestFunction(dice)),
            productionYield = createParameterFromUnivariateFunction(new TestFunction(dice)),
            sellingPrice = createParameterFromUnivariateFunction(new TestFunction(dice)),
            dividendPayment = createParameterFromUnivariateFunction(new TestFunction(dice)),
            maximumLendingRate = createParameterFromUnivariateFunction(new TestFunction(dice));

    final ExogenousFirm firm = new ExogenousFirm(bank, bank, 1., // 1.0 shares emitted
            1., // 1.0 per share
            "type 1", labourMarket, goodsMarket, deposits, commercialLoanDemand, desiredLabour, wageBidPrice,
            productionYield, sellingPrice, dividendPayment, maximumLendingRate,
            new CreditDemandFunction.RiskNeutralCreditDemandFunction(), new InstanceIDAgentNameFactory());

    // Check whether debits, credits and cash flow injections are exogenous:

    {
        final double startingBankCashReserve = bank.getCashReserveValue(),
                startingFirmEquity = firm.getEquity();

        firm.debit(Double.MAX_VALUE);
        firm.debit(-1.);

        try {
            firm.credit(Double.MAX_VALUE / 2.);
            firm.credit(-1.);
        } catch (InsufficientFundsException e) {
            Assert.fail();
        }

        firm.cashFlowInjection(Double.MAX_VALUE / 4.);
        firm.cashFlowInjection(-1.);

        Assert.assertEquals(bank.getCashReserveValue(), startingBankCashReserve, 1.e-12);
        Assert.assertEquals(firm.getEquity(), startingFirmEquity, 1.e-12);
    }

    // Check whether cash allocation has memory:

    firm.allocateCash(100.);
    Assert.assertEquals(firm.getAllocatedCash(), 100., 1.e-12);
    firm.allocateCash(50.);
    Assert.assertEquals(firm.getAllocatedCash(), 150., 1.e-12);
    firm.disallocateCash(151.);
    Assert.assertEquals(firm.getAllocatedCash(), 0., 1.e-12);

    final ExogenousEmployee employee = new ExogenousEmployee(labourMarket);
    final ExogenousGoodsBuyer goodsBuyer = new ExogenousGoodsBuyer(goodsMarket);

    advanceTimeByOneCycle();

    double productionYieldLastValue = 0.;

    for (int i = 0; i < 10; ++i) {
        employee.setLabourSupply(100., 1.);
        goodsBuyer.setGoodsDemand("type 1", 100.);

        advanceUntilJustAfterTime(NamedEventOrderings.GOODS_INPUT_MARKET_MATCHING);

        final double depositsValueProvided = deposits.get(), desiredLabourValueProvided = desiredLabour.get(),
                wageBidPriceValueProvided = wageBidPrice.get(),
                productionYieldValueProvided = productionYield.get(),
                sellingPriceValueProvided = sellingPrice.get(),
                dividendPaymentValueProvided = dividendPayment.get();

        if (i != 0) // No trade in the first
            Assert.assertEquals( //  simulation cycle, as
                    goodsMarket.getInstrument("type 1") //  goods are yet to
                            .getWorstAskPriceAmongSellers(), //  appear in inventory.
                    sellingPriceValueProvided, 1.e-12);
        Assert.assertEquals(goodsMarket.getInstrument("type 1").getTotalSupply(), productionYieldLastValue,
                1.e-12);

        advanceUntilJustAfterTime(NamedEventOrderings.AFTER_ALL);

        Assert.assertEquals(firm.getDepositValue(), depositsValueProvided, 1.e-12);
        Assert.assertEquals(firm.getAllocatedCash(), 0., 1.e-12);

        Assert.assertEquals(labourMarket.getLastLabourTotalDemand(), desiredLabourValueProvided, 1.e-12);
        Assert.assertEquals(firm.getCurrentDividend(), dividendPaymentValueProvided, 1.e-12);
        Assert.assertEquals(labourMarket.getInstrument(1).getDemandWeightedBidWage(), wageBidPriceValueProvided,
                1.e-12);

        productionYieldLastValue = productionYieldValueProvided;
    }
}

From source file:org.alfresco.bm.test.prop.TestPropertyFactoryTest.java

@Test
public void testDefinitions() {
    List<TestProperty> testProps = TestPropertyFactory.getTestProperties(INHERITANCE, rawProperties);
    Map<String, TestProperty> mapProps = TestPropertyFactory.groupByName(testProps);
    assertEquals("Incorrect number of properties", 13, mapProps.size());

    TestProperty prop;//from w  ww  .  ja va2  s  .  c  o  m
    StringTestProperty strProp;
    IntTestProperty intProp;
    DecimalTestProperty decProp;
    BooleanTestProperty booleanProp;

    prop = mapProps.get("one.str");
    strProp = (StringTestProperty) prop;
    {
        Properties strPropProperties = strProp.toProperties();
        strProp = new StringTestProperty("one.str", strPropProperties);
    }
    assertEquals(TestPropertyType.STRING, prop.getType());
    assertEquals("GROUP A", prop.getGroup());
    assertEquals("One Title (String)", prop.getTitle());
    assertEquals("One description (String)", prop.getDescription());
    assertEquals(false, prop.isHide());
    assertEquals("ONE DEFAULT", strProp.getDefault());
    assertEquals(0, strProp.getMin());
    assertEquals(256, strProp.getMax());
    assertEquals(".*", strProp.getRegex());
    assertEquals(true, strProp.isMask());

    prop = mapProps.get("one.int");
    intProp = (IntTestProperty) prop;
    {
        Properties intPropProperties = intProp.toProperties();
        intProp = new IntTestProperty("one.int", intPropProperties);
    }
    assertEquals(TestPropertyType.INT, prop.getType());
    assertEquals("GROUP A", prop.getGroup());
    assertEquals("One Title (Integer)", prop.getTitle());
    assertEquals("One description (Integer)", prop.getDescription());
    assertEquals(false, prop.isHide());
    assertEquals("123", intProp.getDefault());
    assertEquals(0, intProp.getMin());
    assertEquals(256, intProp.getMax());

    prop = mapProps.get("one.dec");
    decProp = (DecimalTestProperty) prop;
    {
        Properties decPropProperties = decProp.toProperties();
        decProp = new DecimalTestProperty("one.dec", decPropProperties);
    }
    assertEquals(TestPropertyType.DECIMAL, prop.getType());
    assertEquals("GROUP A", prop.getGroup());
    assertEquals("One Title (Decimal)", prop.getTitle());
    assertEquals("One description (Decimal)", prop.getDescription());
    assertEquals(false, prop.isHide());
    assertEquals("123.456", decProp.getDefault());
    assertEquals(-5.4, decProp.getMin(), 0.01);
    assertEquals(+5.4, decProp.getMax(), 0.01);

    prop = mapProps.get("one.boolean");
    booleanProp = (BooleanTestProperty) prop;
    {
        Properties booleanPropProperties = booleanProp.toProperties();
        booleanProp = new BooleanTestProperty("one.boolean", booleanPropProperties);
    }
    assertEquals(TestPropertyType.BOOLEAN, prop.getType());
    assertEquals("GROUP A", prop.getGroup());
    assertEquals("One Title (Boolean)", prop.getTitle());
    assertEquals("One description (Boolean)", prop.getDescription());
    assertEquals(false, prop.isHide());
    assertEquals("true", booleanProp.getDefault());

    // Test defaults i.e. where ONLY the default and type is provided

    prop = mapProps.get("two.str");
    strProp = (StringTestProperty) prop;
    assertEquals(TestPropertyType.STRING, prop.getType());
    assertEquals("two.str", prop.getName());
    assertEquals("", prop.getGroup());
    assertEquals("two.str", prop.getTitle());
    assertEquals("", prop.getDescription());
    assertEquals(false, prop.isHide());
    assertEquals("${one.str}", strProp.getDefault());
    assertEquals(0, strProp.getMin());
    assertEquals(128, strProp.getMax());
    assertEquals(".*", strProp.getRegex());
    assertEquals(false, strProp.isMask());

    prop = mapProps.get("two.int");
    intProp = (IntTestProperty) prop;
    assertEquals(TestPropertyType.INT, prop.getType());
    assertEquals("two.int", prop.getName());
    assertEquals("", prop.getGroup());
    assertEquals("two.int", prop.getTitle());
    assertEquals("", prop.getDescription());
    assertEquals(false, prop.isHide());
    assertEquals("${one.int}", intProp.getDefault());
    assertEquals(0, intProp.getMin());
    assertEquals(Integer.MAX_VALUE, intProp.getMax());

    prop = mapProps.get("two.dec");
    decProp = (DecimalTestProperty) prop;
    assertEquals(TestPropertyType.DECIMAL, prop.getType());
    assertEquals("two.dec", prop.getName());
    assertEquals("", prop.getGroup());
    assertEquals("two.dec", prop.getTitle());
    assertEquals("", prop.getDescription());
    assertEquals(false, prop.isHide());
    assertEquals("${one.dec}", decProp.getDefault());
    assertEquals(0.0, decProp.getMin(), 0.01);
    assertEquals(Double.MAX_VALUE, decProp.getMax(), 0.01);

    prop = mapProps.get("two.boolean");
    booleanProp = (BooleanTestProperty) prop;
    assertEquals(TestPropertyType.BOOLEAN, prop.getType());
    assertEquals("two.boolean", prop.getName());
    assertEquals("", prop.getGroup());
    assertEquals("two.boolean", prop.getTitle());
    assertEquals("", prop.getDescription());
    assertEquals(false, prop.isHide());
    assertEquals("${one.boolean}", booleanProp.getDefault());

    // Test # Ignored if the '.default' value is not present
    assertEquals("No '.default' should mean no property", null, mapProps.get("three"));

    // Test inheritance and overriding

    prop = mapProps.get("four");
    intProp = (IntTestProperty) prop;
    assertEquals(TestPropertyType.INT, prop.getType());
    assertEquals("GROUP B", prop.getGroup());
    assertEquals("Four Title", prop.getTitle());
    assertEquals("Four description", prop.getDescription());
    assertEquals(true, prop.isHide());
    assertEquals("0", intProp.getDefault());
    assertEquals(0, intProp.getMin());
    assertEquals(65535, intProp.getMax());
}

From source file:Imputers.KnniLDProb.java

private double[] dist(int s, int p, byte[][] values, int[][] sim) {
    //Simply loops round the other samples, catching the case where it's
    //the current sample
    double[] ret = new double[values.length];
    for (int i = 0; i < values.length; i++) {
        if (i != s) {
            ret[i] = sdist(values[s], values[i], sim[p]);
        } else {//w ww. ja  va  2s  .  c o m
            ret[i] = Double.MAX_VALUE;
        }
    }
    return ret;
}

From source file:Demo3D.java

/**
 * This run method allows to launch the computation of all frames per second
 * for the framemeter./*from  ww w  . j a  va2s.  c o  m*/
 */
public void run() {
    long lastFrameTime;
    double fps;
    double min = Double.MAX_VALUE;
    double max = Double.MIN_VALUE;
    long count = 0;
    double sum = 0;
    double mean = 0;

    while (true) {
        lastFrameTime = viewBr.view.getLastFrameDuration();

        if (lastFrameTime > 0) {
            fps = 1000 / (double) lastFrameTime;
            count += 1;
            sum += fps;
            mean = sum / count;

            // To format all fps-informations.
            NumberFormat numbForm;
            numbForm = NumberFormat.getInstance();
            numbForm.setMaximumFractionDigits(decimalForAllFps);

            if (min > fps && fps != 0 && count > 4)
                min = fps;
            if (max < fps)
                max = fps;

            jLabel.setText("Frames/sec = " + numbForm.format(fps) + "  ;    minFrames/sec = "
                    + numbForm.format(min) + "  ;    maxFrames/sec = " + numbForm.format(max)
                    + "  ;    meanFrames/sec = " + numbForm.format(mean));

            // System.out.println("Frames per second = " + fps);
        }

        try {
            Thread.sleep(sleepDuration);
        } catch (InterruptedException e) {
        }
    }
}

From source file:ml.shifu.shifu.core.alg.NNTrainer.java

@Override
public double train() throws IOException {
    if (toLoggingProcess)
        LOG.info("Using neural network algorithm...");

    if (toLoggingProcess) {
        if (this.dryRun) {
            LOG.info("Start Training(Dry Run)... Model #" + this.trainerID);
        } else {//from   ww w. ja v  a 2s .  c  o  m
            LOG.info("Start Training... Model #" + this.trainerID);
        }

        LOG.info("    - Input Size: " + trainSet.getInputSize());
        LOG.info("    - Ideal Size: " + trainSet.getIdealSize());
        LOG.info("    - Training Records Count: " + trainSet.getRecordCount());
        LOG.info("    - Validation Records Count: " + validSet.getRecordCount());
    }

    // set up the model
    buildNetwork();

    Propagation mlTrain = getMLTrain();
    mlTrain.setThreadCount(0);

    if (this.dryRun) {
        return 0.0;
    }

    int epochs = this.modelConfig.getNumTrainEpochs();
    int factor = Math.max(epochs / 50, 10);

    // Get convergence threshold from modelConfig.
    double threshold = modelConfig.getTrain().getConvergenceThreshold() == null ? 0.0
            : modelConfig.getTrain().getConvergenceThreshold().doubleValue();
    String formatedThreshold = df.format(threshold);

    setBaseMSE(Double.MAX_VALUE);

    for (int i = 0; i < epochs; i++) {
        mlTrain.iteration();

        if (i % factor == 0) {
            this.saveTmpNN(i);
        }

        double validMSE = (this.validSet.getRecordCount() > 0) ? getValidSetError() : mlTrain.getError();

        String extra = "";
        if (validMSE < getBaseMSE()) {
            setBaseMSE(validMSE);
            saveNN();
            extra = " <-- NN saved: ./models/model" + this.trainerID + ".nn";
        }

        if (toLoggingProcess)
            LOG.info("  Trainer-" + trainerID + "> Epoch #" + (i + 1) + " Train Error: "
                    + df.format(mlTrain.getError()) + " Validation Error: "
                    + ((this.validSet.getRecordCount() > 0) ? df.format(validMSE) : "N/A") + " " + extra);

        // Convergence judging.
        double avgErr = (mlTrain.getError() + validMSE) / 2;

        if (judger.judge(avgErr, threshold)) {
            LOG.info("Trainer-{}> Epoch #{} converged! Average Error: {}, Threshold: {}", trainerID, (i + 1),
                    df.format(avgErr), formatedThreshold);
            break;
        } else {
            if (toLoggingProcess) {
                LOG.info("Trainer-{}> Epoch #{} Average Error: {}, Threshold: {}", trainerID, (i + 1),
                        df.format(avgErr), formatedThreshold);
            }
        }
    }

    mlTrain.finishTraining();
    if (toLoggingProcess)
        LOG.info("Trainer #" + this.trainerID + " is Finished!");
    return getBaseMSE();
}

From source file:MetaFramework.Bayesian.java

/**
 * Computes the bayesian statistics for enrichment for all the relevant pathways and it prints the results to a
 * file./* ww w.ja  va 2s  .  co  m*/
 *
 * @param bicluster Bicluster for which the enrichment analysis will be done
 * @param engine    Engine/Parser with the geneToPathway and pathToGene hashsets.
 * @param dataset   Dataset from which biclusters are computed
 * @param colChoice Column on which differentiation will be done. -1 Means diff expressed genes will be computed over columns
 */
public void compute(Bicluster bicluster, AbstractPathwayAnalysis<E, T, G> engine, Dataset dataset,
        int colChoice) throws Exception {
    // Idea is to compute Bayesian statistics for the given gene list/cluster and term
    ArrayList<String> geneNames = new ArrayList<String>();
    //        System.out.println(bicluster.getGenes().length);
    for (int i = 0; i < bicluster.getGenes().length; i++) {
        geneNames.add(dataset.getGeneName(bicluster.getGenes()[i]));
    }
    //        System.out.println(geneNames.size());
    Set<String> allPathways = getAllPath(geneNames, engine);
    ArrayList<String> diffGenes = new ArrayList<String>();
    if (colChoice == -1) {
        // Diff expression
        diffGenes = calculateDiff(bicluster, colChoice, dataset, -1.0); // Threshold does not matter here
        //            System.out.println("Number of differentially expressed genes : " + diffGenes.size());
    } else {
        // Column based differentiation
        // Make sure it is binary (0/1 or false/true)
        // And 1 basically means differentiated
        String threshold = Double.toString(Double.MAX_VALUE);
        if (!checkForBinary(dataset, colChoice)) {
            // If not binary, then ask for a threshold (smaller -> notDiff, higher -> Diff)
            threshold = JOptionPane.showInputDialog(null,
                    "Column values are not binary! Please input a threshold for differentiation:");
        }
        // Now that we know the threshold, we should be fine
        diffGenes = calculateDiff(bicluster, colChoice, dataset, Double.parseDouble(threshold));
    }
    //        System.out.println("Some debug results : ");
    //        System.out.println("Number of diff genes : " + diffGenes.size());

    //        for (String dTm : diffGenes)
    //            System.out.println("Diff gene : " + dTm);
    Set<String> notDiffGenes = MatrixFunctions.setDifference(geneNames, new HashSet<String>(diffGenes));
    //        System.out.println("Amount of pathways : " + allPathways);
    //        if (diffGenes.size() != 0)
    //        {
    //            System.out.println(notDiffGenes.size());
    //        }
    for (String tmp : allPathways) {
        G pathTmp = pathClass.newInstance();
        pathTmp.setInteractions(null);
        pathTmp.setId(0);
        pathTmp.setMolList(null);
        pathTmp.setName(tmp);
        ArrayList<E> molecules = engine.getPathToGene().get(pathTmp);
        ArrayList<String> genesInPathway = new ArrayList<String>();
        for (E mol : molecules)
            genesInPathway.add(mol.getName());
        int nMin = (int) (1); // At least 20 percent of input genes should be part of the pathway
        int xMin = 1; // Let's say at least 1 gene should be diff expressed
        Set<String> genesInOther = new HashSet<String>();
        // Getting all the genes from other pathways.
        for (String tmp2 : allPathways) {
            if (!tmp.equalsIgnoreCase(tmp2)) {
                G pathTmp2 = pathClass.newInstance();
                pathTmp2.setInteractions(null);
                pathTmp2.setId(0);
                pathTmp2.setMolList(null);
                pathTmp2.setName(tmp2);
                ArrayList<E> mols = engine.getPathToGene().get(pathTmp2);
                ArrayList<String> molNames = new ArrayList<String>();
                for (Molecule molT : mols)
                    molNames.add(molT.getName());
                genesInOther.addAll(molNames);
            }
        }

        Set<String> genesOnlyPathway = MatrixFunctions.setDifference(genesInPathway, genesInOther);
        Set<String> genesNotPathway = MatrixFunctions.setDifference(genesInOther, genesInPathway);

        // Computation of relevant terms
        int x1OnlyPathway = MatrixFunctions.intersection(genesOnlyPathway, diffGenes).size();
        //            x1OnlyPathway = 0;
        int x0OnlyPathway = MatrixFunctions.intersection(genesOnlyPathway, notDiffGenes).size();
        //            x0OnlyPathway = 0;
        int nOnlyPath = genesOnlyPathway.size();
        //            nOnlyPath = 0;
        int x1PathAnd = MatrixFunctions.intersection(genesInPathway, diffGenes).size() - x1OnlyPathway;
        //            x1PathAnd = 4;
        int x0PathAnd = MatrixFunctions.intersection(genesInPathway, notDiffGenes).size() - x0OnlyPathway;
        //            x0PathAnd = 2;
        int nAnd = MatrixFunctions.setDifference(genesInPathway, genesOnlyPathway).size();
        //            nAnd = 6;
        int x1NoPathway = MatrixFunctions.intersection(genesNotPathway, diffGenes).size();
        //            x1NoPathway = 380;
        int x0NoPathway = MatrixFunctions.intersection(genesNotPathway, notDiffGenes).size();
        //            x0NoPathway = 3590;
        int nNoPath = genesNotPathway.size();
        //            nNoPath = 380 + 3590;
        double gHat = GScore(x1OnlyPathway, x1PathAnd, x1NoPathway, x0OnlyPathway, x0PathAnd, x0NoPathway);
        //            if (gHat != 0)
        //                System.out.println("Ghat is : " + gHat);
        int x1Path = x1OnlyPathway + x1PathAnd;

        //            System.out.println("Genes in Pathways : " + genesInPathway.size() + " , x1Path : " + x1Path);
        if (!(genesInPathway.size() < nMin) && !(x1Path < xMin) && !(gHat <= 0)) {
            //                System.out.println("Not skipping");
            double[] gObs = new double[nSim];
            // Do not skip the loop, still continue
            if (genesInPathway.size() > (x1OnlyPathway + x0OnlyPathway + x1PathAnd + x0PathAnd)) {
                ArrayList<Double> X1onlyPath = RPosterior(nSim, x1OnlyPathway, x1OnlyPathway + x0OnlyPathway,
                        nOnlyPath);

                double[] X0onlyPath = MatrixFunctions.constantMinusVector(nOnlyPath, X1onlyPath);
                ArrayList<Double> X1andPath = RPosterior(nSim, x1PathAnd, x1PathAnd + x0PathAnd, nAnd);
                double[] X0andPath = MatrixFunctions.constantMinusVector(nAnd, X1andPath);
                ArrayList<Double> X1noPath = RPosterior(nSim, x1NoPathway, x1NoPathway + x0NoPathway, nNoPath);
                double[] X0noPath = MatrixFunctions.constantMinusVector(nNoPath, X1noPath);
                // gObs will be used for the comparison vs simulation results
                gObs = GScoreMatrix(X1onlyPath, X1andPath, X1noPath, X0onlyPath, X0andPath, X0noPath);
                //                    System.out.println("For debug");
            } else {
                double X1onlyPath = x1OnlyPathway;
                double X0onlyPath = nOnlyPath - X1onlyPath;
                double X1andPath = x1OnlyPathway;
                double X0andPath = nAnd - X1andPath;
                double X1noPath = x1NoPathway;
                double X0noPath = nNoPath - X1noPath;
                for (int k = 0; k < nSim; k++)
                    gObs[k] = gHat;
            }
            double[] gRand = new double[nSim];
            // Random simulations loop.
            // NOTE: As you will see in the comments in the loop, some of the variables actually should be replaced
            // in case there is an existence of knowledge about observability of certain genes
            for (int j = 0; j < nSim; j++) {
                // Simulation loop
                int n = Math.min(poisson(diffGenes.size()), geneNames.size()); // 2nd argument is actually number of observed genes

                Set<String> diffRandom = new HashSet<String>();
                Random random = new Random();
                for (int i = 0; i < n; i++) {
                    diffRandom.add(geneNames.get(random.nextInt(geneNames.size())));
                }
                Set<String> notDiffRandom = MatrixFunctions.setDifference(geneNames, diffRandom);
                int x1OnlyPathR = MatrixFunctions.intersection(genesOnlyPathway, diffRandom).size();
                int x0OnlyPathR = MatrixFunctions.intersection(genesOnlyPathway, notDiffRandom).size();
                int nOnlyPathR = genesOnlyPathway.size();

                int x1AndPathR = MatrixFunctions.intersection(genesInPathway, diffRandom).size() - x1OnlyPathR;
                int x0AndPathR = MatrixFunctions.intersection(genesInPathway, notDiffRandom).size()
                        - x0OnlyPathR;
                int nPathAndR = MatrixFunctions.setDifference(genesInPathway, genesOnlyPathway).size();

                int x1NoPathR = MatrixFunctions.intersection(genesNotPathway, diffRandom).size();
                int x0NoPathR = MatrixFunctions.intersection(genesNotPathway, notDiffRandom).size();
                int nNoPathR = genesNotPathway.size();

                ArrayList<Double> X1onlyPathR = RPosterior(1, x1OnlyPathR, x1OnlyPathR + x0OnlyPathR,
                        nOnlyPathR);
                double[] X0onlyPathR = new double[X1onlyPathR.size()];
                for (int k = 0; k < X0onlyPathR.length; k++) {
                    X0onlyPathR[k] = nOnlyPathR - X1onlyPathR.get(k);
                }
                ArrayList<Double> X1andPathR = RPosterior(1, x1AndPathR, x1AndPathR + x0AndPathR, nPathAndR);
                double[] X0andPathR = new double[X1andPathR.size()];
                for (int k = 0; k < X0andPathR.length; k++) {
                    X0andPathR[k] = nPathAndR - X1andPathR.get(k);
                }
                ArrayList<Double> X1noPathR = RPosterior(1, x1NoPathR, x1NoPathR + x0NoPathR, nNoPathR);
                double[] X0noPathR = new double[X1noPathR.size()];
                for (int k = 0; k < X1noPathR.size(); k++) {
                    X0noPathR[k] = nNoPathR - X1noPathR.get(k);
                }
                gRand[j] = GScoreMatrix(X1onlyPathR, X1andPathR, X1noPathR, X0onlyPathR, X0andPathR,
                        X0noPathR)[0];
            }
            // Simulations are done, so let's start comparing the results
            int cnt = 0;
            for (int j = 0; j < nSim; j++)
                if (gRand[j] >= gObs[j])
                    cnt++;
            outFile.println("Results for : " + tmp);
            double result = (cnt + 0.0) / (nSim + 0.0); // 0.0 is needed to push for the double division
            if (result <= 0.05)
                outFile.println("Pathway with name : " + tmp + " has p-value of : " + result);

            // computing error bars
            double errorLeft = Math.min(quantile(gObs, 0.05), gHat);
            double errorRight = Math.max(quantile(gObs, 0.95), gHat);
            outFile.println("G hat : " + gHat);
            outFile.println("Errorbar : [" + errorLeft + ", " + errorRight + "]");
            outFile.println("There were " + bicluster.getGenes().length + " genes. " + diffGenes.size()
                    + " were diff expressed. Pathway has " + genesInPathway.size() + " genes");
            outFile.println(
                    "From the diff expressed genes, " + (x1PathAnd + x1OnlyPathway) + " were in the pathway");
        } else {
            outFile.println("Results for : " + tmp);
            outFile.println("GHat : " + gHat);
            outFile.println("There were " + bicluster.getGenes().length + " genes. " + diffGenes.size()
                    + " were diff expressed. Pathway has " + genesInPathway.size() + " genes");
            outFile.println(
                    "From the diff expressed genes, " + (x1PathAnd + x1OnlyPathway) + " were in the pathway");

        }
        outFile.println("-------------------------------");
    }

}

From source file:dr.evomodel.continuous.ContinuousDiffusionStatistic.java

public double getStatisticValue(int dim) {

    double treeLength = 0;
    double treeDistance = 0;
    double totalMaxDistanceFromRoot = 0;
    double maxDistanceFromRootCumulative = 0; // can only be used when cumulative and not associated with discrete state (not based on the distances on the branches from the root up that point)
    double maxBranchDistanceFromRoot = 0;
    double maxDistanceOverTimeFromRootWA = 0; // can only be used when cumulative and not associated with discrete state (not based on the distances on the branches from the root up that point)
    double maxBranchDistanceOverTimeFromRootWA = 0;
    List<Double> rates = new ArrayList<Double>();
    List<Double> distances = new ArrayList<Double>();
    List<Double> times = new ArrayList<Double>();
    List<Double> traits = new ArrayList<Double>();
    List<double[]> traits2D = new ArrayList<double[]>();
    //double[] diffusionCoefficients =  null;
    List<Double> diffusionCoefficients = new ArrayList<Double>();
    double waDiffusionCoefficient = 0;

    double lowerHeight = heightLowers[dim];
    double upperHeight = Double.MAX_VALUE;
    if (heightLowers.length == 1) {
        upperHeight = heightUpper;//w  w  w . ja  v  a 2 s. c  o m
    } else {
        if (dim > 0) {
            if (!cumulative) {
                upperHeight = heightLowers[dim - 1];
            }
        }
    }

    for (AbstractMultivariateTraitLikelihood traitLikelihood : traitLikelihoods) {
        MutableTreeModel tree = traitLikelihood.getTreeModel();
        BranchRateModel branchRates = traitLikelihood.getBranchRateModel();

        String traitName = traitLikelihood.getTraitName();

        for (int i = 0; i < tree.getNodeCount(); i++) {
            NodeRef node = tree.getNode(i);

            if (node != tree.getRoot()) {

                NodeRef parentNode = tree.getParent(node);

                boolean testNode = true;
                if (branchset.equals(BranchSet.CLADE)) {
                    try {
                        testNode = inClade(tree, node, taxonList);
                    } catch (TreeUtils.MissingTaxonException mte) {
                        throw new RuntimeException(mte.toString());
                    }
                } else if (branchset.equals(BranchSet.BACKBONE)) {
                    if (backboneTime > 0) {
                        testNode = onAncestralPathTime(tree, node, backboneTime);
                    } else {
                        try {
                            testNode = onAncestralPathTaxa(tree, node, taxonList);
                        } catch (TreeUtils.MissingTaxonException mte) {
                            throw new RuntimeException(mte.toString());
                        }
                    }
                }

                if (testNode) {

                    if ((tree.getNodeHeight(parentNode) > lowerHeight)
                            && (tree.getNodeHeight(node) < upperHeight)) {

                        double[] trait = traitLikelihood.getTraitForNode(tree, node, traitName);
                        double[] parentTrait = traitLikelihood.getTraitForNode(tree, parentNode, traitName);

                        double[] traitUp = parentTrait;
                        double[] traitLow = trait;

                        double timeUp = tree.getNodeHeight(parentNode);
                        double timeLow = tree.getNodeHeight(node);

                        double rate = (branchRates != null ? branchRates.getBranchRate(tree, node) : 1.0);
                        //                        System.out.println(rate);
                        MultivariateDiffusionModel diffModel = traitLikelihood.diffusionModel;
                        double[] precision = diffModel.getPrecisionParameter().getParameterValues();

                        History history = null;
                        if (stateString != null) {
                            history = setUpHistory(markovJumpLikelihood.getHistoryForNode(tree, node, SITE),
                                    markovJumpLikelihood.getStatesForNode(tree, node)[SITE],
                                    markovJumpLikelihood.getStatesForNode(tree, parentNode)[SITE], timeLow,
                                    timeUp);
                        }

                        if (tree.getNodeHeight(parentNode) > upperHeight) {
                            timeUp = upperHeight;
                            traitUp = imputeValue(trait, parentTrait, upperHeight, tree.getNodeHeight(node),
                                    tree.getNodeHeight(parentNode), precision, rate, trueNoise);
                            if (stateString != null) {
                                history.truncateUpper(timeUp);
                            }
                        }

                        if (tree.getNodeHeight(node) < lowerHeight) {
                            timeLow = lowerHeight;
                            traitLow = imputeValue(trait, parentTrait, lowerHeight, tree.getNodeHeight(node),
                                    tree.getNodeHeight(parentNode), precision, rate, trueNoise);
                            if (stateString != null) {
                                history.truncateLower(timeLow);
                            }
                        }

                        if (dimension > traitLow.length) {
                            System.err.println("specified trait dimension for continuous trait summary, "
                                    + dimension + ", is > dimensionality of trait, " + traitLow.length
                                    + ". No trait summarized.");
                        } else {
                            traits.add(traitLow[(dimension - 1)]);
                        }

                        if (traitLow.length == 2) {
                            traits2D.add(traitLow);
                        }

                        double time;
                        if (stateString != null) {
                            if (!history.returnMismatch()) {
                                time = history.getStateTime(stateString);
                            } else {
                                time = NaN;
                            }
                            //System.out.println("time before = "+(timeUp - timeLow)+", time after= "+time);
                        } else {
                            time = timeUp - timeLow;
                        }
                        treeLength += time;
                        times.add(time);

                        //setting up continuous trait values for heights in discrete trait history
                        if (stateString != null) {
                            history.setTraitsforHeights(traitUp, traitLow, precision, rate, trueNoise);
                        }

                        double[] rootTrait = traitLikelihood.getTraitForNode(tree, tree.getRoot(), traitName);
                        double timeFromRoot = (tree.getNodeHeight(tree.getRoot()) - timeLow);

                        if (useGreatCircleDistances && (trait.length == 2)) { // Great Circle distance
                            double distance;
                            if (stateString != null) {
                                if (!history.returnMismatch()) {
                                    distance = history.getStateGreatCircleDistance(stateString);
                                } else {
                                    distance = NaN;
                                }
                            } else {
                                distance = getGreatCircleDistance(traitLow, traitUp);
                            }
                            distances.add(distance);

                            if (time > 0) {
                                treeDistance += distance;
                                double dc = Math.pow(distance, 2) / (4 * time);
                                diffusionCoefficients.add(dc);
                                waDiffusionCoefficient += (dc * time);
                                rates.add(distance / time);
                            }

                            SphericalPolarCoordinates rootCoord = new SphericalPolarCoordinates(rootTrait[0],
                                    rootTrait[1]);
                            double tempDistanceFromRootLow = rootCoord
                                    .distance(new SphericalPolarCoordinates(traitUp[0], traitUp[1]));

                            if (tempDistanceFromRootLow > totalMaxDistanceFromRoot) {
                                totalMaxDistanceFromRoot = tempDistanceFromRootLow;
                                if (stateString != null) {
                                    double[] stateTimeDistance = getStateTimeAndDistanceFromRoot(tree, node,
                                            timeLow, traitLikelihood, traitName, traitLow, precision,
                                            branchRates, true);
                                    if (stateTimeDistance[0] > 0) {
                                        if (!history.returnMismatch()) {
                                            maxDistanceFromRootCumulative = tempDistanceFromRootLow
                                                    * (stateTimeDistance[0] / timeFromRoot);
                                            maxDistanceOverTimeFromRootWA = maxDistanceFromRootCumulative
                                                    / stateTimeDistance[0];
                                            maxBranchDistanceFromRoot = stateTimeDistance[1];
                                            maxBranchDistanceOverTimeFromRootWA = stateTimeDistance[1]
                                                    / stateTimeDistance[0];
                                        } else {
                                            maxDistanceFromRootCumulative = NaN;
                                            maxDistanceOverTimeFromRootWA = NaN;
                                            maxBranchDistanceFromRoot = NaN;
                                            maxBranchDistanceOverTimeFromRootWA = NaN;
                                        }
                                    }
                                } else {
                                    maxDistanceFromRootCumulative = tempDistanceFromRootLow;
                                    maxDistanceOverTimeFromRootWA = tempDistanceFromRootLow / timeFromRoot;
                                    double[] timeDistance = getTimeAndDistanceFromRoot(tree, node, timeLow,
                                            traitLikelihood, traitName, traitLow, true);
                                    maxBranchDistanceFromRoot = timeDistance[1];
                                    maxBranchDistanceOverTimeFromRootWA = timeDistance[1] / timeDistance[0];

                                }
                                //distance between traitLow and traitUp for maxDistanceFromRootCumulative
                                if (timeUp == upperHeight) {
                                    if (time > 0) {
                                        maxDistanceFromRootCumulative = distance;
                                        maxDistanceOverTimeFromRootWA = distance / time;
                                        maxBranchDistanceFromRoot = distance;
                                        maxBranchDistanceOverTimeFromRootWA = distance / time;
                                    }
                                }
                            }

                        } else {
                            double distance;
                            if (stateString != null) {
                                if (!history.returnMismatch()) {
                                    distance = history.getStateNativeDistance(stateString);
                                } else {
                                    distance = NaN;
                                }
                            } else {
                                distance = getNativeDistance(traitLow, traitUp);
                            }
                            distances.add(distance);

                            if (time > 0) {
                                treeDistance += distance;
                                double dc = Math.pow(distance, 2) / (4 * time);
                                diffusionCoefficients.add(dc);
                                waDiffusionCoefficient += dc * time;
                                rates.add(distance / time);
                            }

                            double tempDistanceFromRoot = getNativeDistance(traitLow, rootTrait);
                            if (tempDistanceFromRoot > totalMaxDistanceFromRoot) {
                                totalMaxDistanceFromRoot = tempDistanceFromRoot;
                                if (stateString != null) {
                                    double[] stateTimeDistance = getStateTimeAndDistanceFromRoot(tree, node,
                                            timeLow, traitLikelihood, traitName, traitLow, precision,
                                            branchRates, false);
                                    if (stateTimeDistance[0] > 0) {
                                        if (!history.returnMismatch()) {
                                            maxDistanceFromRootCumulative = tempDistanceFromRoot
                                                    * (stateTimeDistance[0] / timeFromRoot);
                                            maxDistanceOverTimeFromRootWA = maxDistanceFromRootCumulative
                                                    / stateTimeDistance[0];
                                            maxBranchDistanceFromRoot = stateTimeDistance[1];
                                            maxBranchDistanceOverTimeFromRootWA = stateTimeDistance[1]
                                                    / stateTimeDistance[0];
                                        } else {
                                            maxDistanceFromRootCumulative = NaN;
                                            maxDistanceOverTimeFromRootWA = NaN;
                                            maxBranchDistanceFromRoot = NaN;
                                            maxBranchDistanceOverTimeFromRootWA = NaN;
                                        }
                                    }
                                } else {
                                    maxDistanceFromRootCumulative = tempDistanceFromRoot;
                                    maxDistanceOverTimeFromRootWA = tempDistanceFromRoot / timeFromRoot;
                                    double[] timeDistance = getTimeAndDistanceFromRoot(tree, node, timeLow,
                                            traitLikelihood, traitName, traitLow, false);
                                    maxBranchDistanceFromRoot = timeDistance[1];
                                    maxBranchDistanceOverTimeFromRootWA = timeDistance[1] / timeDistance[0];
                                }
                                //distance between traitLow and traitUp for maxDistanceFromRootCumulative
                                if (timeUp == upperHeight) {
                                    if (time > 0) {
                                        maxDistanceFromRootCumulative = distance;
                                        maxDistanceOverTimeFromRootWA = distance / time;
                                        maxBranchDistanceFromRoot = distance;
                                        maxBranchDistanceOverTimeFromRootWA = distance / time;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    if (summaryStat == summaryStatistic.DIFFUSION_RATE) {
        if (summaryMode == Mode.AVERAGE) {
            return DiscreteStatistics.mean(toArray(rates));
        } else if (summaryMode == Mode.MEDIAN) {
            return DiscreteStatistics.median(toArray(rates));
        } else if (summaryMode == Mode.COEFFICIENT_OF_VARIATION) {
            final double mean = DiscreteStatistics.mean(toArray(rates));
            return Math.sqrt(DiscreteStatistics.variance(toArray(rates), mean)) / mean;
            //weighted average
        } else {
            return treeDistance / treeLength;
        }
    } else if (summaryStat == summaryStatistic.TRAIT) {
        if (summaryMode == Mode.MEDIAN) {
            return DiscreteStatistics.median(toArray(traits));
        } else if (summaryMode == Mode.COEFFICIENT_OF_VARIATION) {
            // don't compute mean twice
            final double mean = DiscreteStatistics.mean(toArray(traits));
            return Math.sqrt(DiscreteStatistics.variance(toArray(traits), mean)) / mean;
            // default is average. A warning is thrown by the parser when trying to use WEIGHTED_AVERAGE
        } else {
            return DiscreteStatistics.mean(toArray(traits));
        }
    } else if (summaryStat == summaryStatistic.TRAIT2DAREA) {
        double area = getAreaFrom2Dtraits(traits2D, 0.99);
        return area;
    } else if (summaryStat == summaryStatistic.DIFFUSION_COEFFICIENT) {
        if (summaryMode == Mode.AVERAGE) {
            return DiscreteStatistics.mean(toArray(diffusionCoefficients));
        } else if (summaryMode == Mode.MEDIAN) {
            return DiscreteStatistics.median(toArray(diffusionCoefficients));
        } else if (summaryMode == Mode.COEFFICIENT_OF_VARIATION) {
            // don't compute mean twice
            final double mean = DiscreteStatistics.mean(toArray(diffusionCoefficients));
            return Math.sqrt(DiscreteStatistics.variance(toArray(diffusionCoefficients), mean)) / mean;
        } else {
            return waDiffusionCoefficient / treeLength;
        }
        //wavefront distance
        //TODO: restrict to non state-specific wavefrontDistance/rate
    } else if (summaryStat == summaryStatistic.WAVEFRONT_DISTANCE) {
        return maxDistanceFromRootCumulative;
        //            return maxBranchDistanceFromRoot;
    } else if (summaryStat == summaryStatistic.WAVEFRONT_DISTANCE_PHYLO) {
        return maxBranchDistanceFromRoot;
        //wavefront rate, only weighted average TODO: extend for average, median, COEFFICIENT_OF_VARIATION?
    } else if (summaryStat == summaryStatistic.WAVEFRONT_RATE) {
        return maxDistanceOverTimeFromRootWA;
        //            return maxBranchDistanceOverTimeFromRootWA;
    } else if (summaryStat == summaryStatistic.DIFFUSION_DISTANCE) {
        return treeDistance;
        //DIFFUSION_TIME
    } else if (summaryStat == summaryStatistic.DISTANCE_TIME_CORRELATION) {
        if (summaryMode == Mode.SPEARMAN) {
            return getSpearmanRho(convertDoubles(times), convertDoubles(distances));
        } else if (summaryMode == Mode.R_SQUARED) {
            Regression r = new Regression(convertDoubles(times), convertDoubles(distances));
            return r.getRSquared();
        } else {
            Regression r = new Regression(convertDoubles(times), convertDoubles(distances));
            return r.getCorrelationCoefficient();
        }
    } else {
        return treeLength;
    }
}