Example usage for org.apache.commons.math3.stat.descriptive SummaryStatistics addValue

List of usage examples for org.apache.commons.math3.stat.descriptive SummaryStatistics addValue

Introduction

In this page you can find the example usage for org.apache.commons.math3.stat.descriptive SummaryStatistics addValue.

Prototype

public void addValue(double value) 

Source Link

Document

Add a value to the data

Usage

From source file:model.experiments.stickyprices.StickyPricesCSVPrinter.java

private static void woodMonopolistSweep(final BigDecimal minimumP, final BigDecimal maximumP,
        final BigDecimal minimumI, final BigDecimal maximumI, final BigDecimal increment,
        final int runsPerParameterCombination) throws IOException {

    CSVWriter writer = new CSVWriter(new FileWriter(Paths.get("runs", "rawdata", "monoSweep.csv").toFile()));
    writer.writeNext(new String[] { "P", "I", "distance", "variance", "success" });

    BigDecimal currentP = minimumP;
    while (currentP.compareTo(maximumP) <= 0) {
        BigDecimal currentI = minimumI;

        while (currentI.compareTo(maximumI) <= 0) {

            SummaryStatistics averageSquaredDistance = new SummaryStatistics();
            SummaryStatistics averageVariance = new SummaryStatistics();
            int successes = 0;

            for (int run = 0; run < runsPerParameterCombination; run++) {

                //create the run
                MacroII macroII = new MacroII(run);
                MonopolistScenario scenario = new MonopolistScenario(macroII);
                macroII.setScenario(scenario);
                //set the demand
                scenario.setDemandIntercept(102);
                scenario.setDemandSlope(2);
                scenario.setDailyWageSlope(1);
                scenario.setDailyWageIntercept(0);
                scenario.setAskPricingStrategy(SimpleFlowSellerPID.class);
                scenario.setWorkersToBeRehiredEveryDay(true);
                scenario.setControlType(
                        MonopolistScenario.MonopolistScenarioIntegratedControlEnum.MARGINAL_PLANT_CONTROL);
                scenario.setBuyerDelay(0);

                //start it and have one step
                macroII.start();/*w  w  w . j a va2s  . c  o m*/
                macroII.schedule.step(macroII);

                //now set the right parameters
                final SalesDepartment salesDepartment = scenario.getMonopolist()
                        .getSalesDepartment(UndifferentiatedGoodType.GENERIC);
                final SimpleFlowSellerPID strategy = new SimpleFlowSellerPID(salesDepartment,
                        currentP.floatValue(), currentI.floatValue(), 0f, 0, salesDepartment.getMarket(),
                        salesDepartment.getRandom().nextInt(100), salesDepartment.getFirm().getModel());
                //  strategy.setInitialPrice(102);
                //start them all at the same price, otherwise you advantage the slow by being so slow initially that they end up being right later

                salesDepartment.setAskPricingStrategy(strategy);

                //and make it learned!
                salesDepartment.setPredictorStrategy(new FixedDecreaseSalesPredictor(2));
                final HumanResources hr = scenario.getMonopolist().getHRs().iterator().next();
                hr.setPredictor(new FixedIncreasePurchasesPredictor(1));

                float totalDistance = 0;
                SummaryStatistics prices = new SummaryStatistics();
                //run the model
                double price = 0;
                double quantity = 0;
                for (int i = 0; i < 1000; i++) {
                    macroII.schedule.step(macroII);
                    price = strategy.getTargetPrice();
                    quantity = salesDepartment.getTodayInflow();
                    totalDistance += Math
                            .pow(Math.min(price - (102 - 2 * quantity), price - (102 - 2 * quantity - 1)), 2);
                    prices.addValue(price);
                }

                //Model over, now compute statistics

                averageSquaredDistance.addValue(Math.sqrt(totalDistance));
                averageVariance.addValue(prices.getVariance());
                if (price <= 68 && price >= 67)
                    successes++;

                //            System.out.println(salesDepartment.getLatestObservation(SalesDataType.LAST_ASKED_PRICE));
                macroII.finish();

            }

            String[] csvLine = new String[5];
            csvLine[0] = currentP.toString();
            csvLine[1] = currentI.toString();
            csvLine[2] = String.valueOf(averageSquaredDistance.getMean());
            csvLine[3] = String.valueOf(averageVariance.getMean());
            csvLine[4] = String.valueOf(successes);
            writer.writeNext(csvLine);
            writer.flush();
            System.out.println(Arrays.toString(csvLine));

            currentI = currentI.add(increment).setScale(2);
            System.out.println();

        }

        currentP = currentP.add(increment).setScale(2);

    }

}

From source file:gdsc.smlm.ij.plugins.DensityImage.java

/**
 * Output a log message of the results including the average density for localisations and the expected average.
 * /*from  ww w . ja  v a2  s  .  c  om*/
 * @param results
 * @param density
 * @param radius
 * @param filtered
 * @return
 */
private SummaryStatistics logDensityResults(MemoryPeakResults results, int[] density, float radius,
        int filtered) {
    float region = (float) (radius * radius * ((useSquareApproximation) ? 4 : Math.PI));

    Rectangle bounds = results.getBounds();
    float area = bounds.width * bounds.height;
    float expected = results.size() * region / area;
    SummaryStatistics summary = new SummaryStatistics();

    for (int i = 0; i < results.size(); i++) {
        summary.addValue(density[i]);
    }

    DensityManager dm = new DensityManager(results);

    // Compute this using the input density scores since the radius is the same.
    final double l = (useSquareApproximation) ? dm.ripleysLFunction(radius)
            : dm.ripleysLFunction(density, radius);

    String msg = String.format("Density %s : N=%d, %.0fpx : Radius=%s : L(r) - r = %s : E = %s, Obs = %s (%sx)",
            results.getName(), summary.getN(), area, rounded(radius), rounded(l - radius), rounded(expected),
            rounded(summary.getMean()), rounded(summary.getMean() / expected));
    if (filterLocalisations)
        msg += String.format(" : Filtered=%d (%s%%)", filtered, rounded(filtered * 100.0 / density.length));
    IJ.log(msg);

    return summary;
}

From source file:model.utilities.pid.decorator.AutotunerTest.java

private PIDAutotuner runLearningExperimentWithUnknownDeadTime(MersenneTwisterFast random,
        float proportionalParameter, float integrativeParameter, Supplier<Double> noiseMaker,
        DynamicProcess systemDynamic) throws FileNotFoundException {
    PIDAutotuner controller = new PIDAutotuner(
            new PIDController(proportionalParameter, integrativeParameter, 0));
    controller.setAfterHowManyDaysShouldTune(1001);
    int target = 10;
    if (noiseMaker != null)
        systemDynamic.setRandomNoise(noiseMaker);

    //create the regression too

    //output starts at intercept
    float output = 0;
    //delayed input, useful for learning

    SummaryStatistics errorBeforeTuning = new SummaryStatistics();

    SummaryStatistics errorAfterTuning = new SummaryStatistics();
    SummaryStatistics finalError = new SummaryStatistics();

    for (int step = 0; step < 2000; step++) {

        //PID step
        controller.adjust(new ControllerInput(target, output), true, mock(MacroII.class), null,
                ActionOrder.DAWN);/* ww  w . j a v  a2  s  . c  o  m*/

        //process reacts
        float input = controller.getCurrentMV();
        assert !Float.isNaN(input);
        assert !Float.isInfinite(input);
        output = (float) systemDynamic.newStep(input);

        if (step <= 1000)
            errorBeforeTuning.addValue(Math.pow(target - output, 2));
        else
            errorAfterTuning.addValue(Math.pow(target - output, 2));
        if (step > 1900)
            finalError.addValue(Math.pow(target - output, 2));

        //shock target with 10%
        if (random.nextBoolean(.10)) {
            if (random.nextBoolean())
                target++;
            else
                target = Math.max(target - 1, 0);
        }

    }
    System.out.println("errors: " + errorBeforeTuning.getMean() + " --- " + errorAfterTuning.getMean());
    System.out.println("final error: " + finalError.getMean());
    System.out.println("regression: " + controller.getRegression());

    RegressionStatics.tracksAcceptably(controller.getRegression(), systemDynamic,
            RegressionStatics.MAXIMUM_ABS_ERROR, 100,
            Math.max(controller.getCurrentMV(), RegressionStatics.FIXED_INPUT));
    Assert.assertTrue(errorAfterTuning.getMean() < errorBeforeTuning.getMean());
    //either have a very low error, or at least have improved by a factor of over 100
    Assert.assertTrue(finalError.getMean() < 10 || finalError.getMean() < errorBeforeTuning.getMean() / 100);

    return controller;

}

From source file:com.itemanalysis.psychometrics.irt.estimation.MarginalMaximumLikelihoodEstimation.java

/**
 *
 *///from w  w w.  ja va  2  s  . com
public void computeG2ItemFit(int nbins, int minExpectedCount) {
    IrtExaminee irtExaminee = new IrtExaminee("", irm);
    double[] eapEstimate = new double[responseVector.length];
    SummaryStatistics stats = new SummaryStatistics();

    //First loop over response vectors
    for (int i = 0; i < responseVector.length; i++) {
        //EAP estimate of ability
        irtExaminee.setResponseVector(responseVector[i]);
        eapEstimate[i] = irtExaminee.eapEstimate(latentDistribution);

        for (int N = 0; N < responseVector[i].getFrequency(); N++) {//Expand response vectors
            stats.addValue(eapEstimate[i]);
        }
    }

    DefaultLinearTransformation linearTransformation = new DefaultLinearTransformation(stats.getMean(),
            latentDistribution.getMean(), stats.getStandardDeviation(),
            latentDistribution.getStandardDeviation());

    //Create fit statistic objects
    itemFit = new ItemFitG2[nItems];

    double lower = linearTransformation.transform(stats.getMin()) - .01;//Subtract a small number to ensure lowest theta is counted
    double upper = linearTransformation.transform(stats.getMax()) + .01;//Add a small number to ensure largest theta is counted
    Cut thetaCut = new Cut(lower, upper, nbins);

    for (int j = 0; j < nItems; j++) {
        itemFit[j] = new ItemFitG2(irm[j], thetaCut, minExpectedCount);
    }

    //Second loop over response vectors
    //Increment fit statistics
    double A = linearTransformation.getScale();
    for (int i = 0; i < responseVector.length; i++) {
        //Estimate EAP standard deviation should be the same as the standard deviation
        //of the latent distribution used to estimate the item parameters.
        eapEstimate[i] = eapEstimate[i] * A;

        for (int N = 0; N < responseVector[i].getFrequency(); N++) {//Expand table
            for (int j = 0; j < nItems; j++) {
                ((ItemFitG2) itemFit[j]).increment(eapEstimate[i], responseVector[i].getResponseAt(j));
            }
        }
    }

    //        System.out.println(thetaCut.toString());

    //Compute Item Fit
    for (int j = 0; j < nItems; j++) {
        itemFit[j].compute();
    }

}

From source file:gov.llnl.lc.infiniband.opensm.plugin.data.RT_NodeBalance.java

private SummaryStatistics calculateStatistics(BinList<RT_Port> caBins) {
    // sort these by the # of CA paths
    BinList<RT_Port> CA_Bins = RT_Balance.sortBinsByKeys(caBins);
    SummaryStatistics RouteStats = new SummaryStatistics();

    int k = 0;// w  w  w .  ja va  2s .c  o  m
    for (ArrayList<RT_Port> caList : CA_Bins) {
        if (caList != null) {
            String key = (CA_Bins.getKey(k)).trim();
            NumPortsRoutes += caList.size();

            for (int i = 0; i < caList.size(); i++) {
                RouteStats.addValue(Double.parseDouble(key));
            }

            //        // excluding single paths (switch to leaf nodes), calculate the
            //        // statistics
            //        if ("1".equalsIgnoreCase(key))
            //        {
            //          // sanity check, these are ports connected directly to CAs, so
            //          // should match # of CAs
            //          NumSingleRoutes = caList.size();
            //        }
            //        else
            //        {
            //          // include these in the stats, the ports connected to compute
            //          // (leaf or CA) nodes will throw off stats
            //          for (int i = 0; i < caList.size(); i++)
            //          {
            //            RouteStats.addValue(Double.parseDouble(key));
            //          }
            //        }
        }
        k++;
    }
    return RouteStats;
}

From source file:ca.mcgill.cs.creco.logic.ScoredAttribute.java

private void setNumericStats(ArrayList<TypedValue> pValues) {
    SummaryStatistics ss = new SummaryStatistics();
    double min = DEFAULT_MIN;
    double max = DEFAULT_MAX;
    ArrayList<Double> values = new ArrayList<Double>(pValues.size());
    for (TypedValue tv : pValues) {
        if (tv.isNumeric()) {
            ss.addValue(tv.getNumeric());
            if (tv.getNumeric() < min) {
                min = tv.getNumeric();//  w  w w  . ja  v  a 2 s. co  m

            }
            if (tv.getNumeric() > max) {
                max = tv.getNumeric();
            }
            values.add(tv.getNumeric());
        }

    }
    //Set bounds
    if (Double.isNaN(min)) {
        LOG.error("Min value is NaN: " + aAttributeID + ", " + aAttributeName + ", " + aCategory.getId());
    }
    if (Double.isNaN(max)) {
        LOG.error("Max value is NaN: " + aAttributeID + ", " + aAttributeName + ", " + aCategory.getId());
    }
    aMin = new TypedValue(min);
    aMax = new TypedValue(max);
    double mean = ss.getGeometricMean();
    double variance = ss.getStandardDeviation() * ss.getStandardDeviation();
    //Calculate Entropy
    double entropy = 0;
    for (TypedValue tv : pValues) {
        if (tv.isNumeric()) {
            double prob = computeNormalProbability(tv, mean, variance);
            entropy = entropy - prob * (Math.log(prob));
        }
    }
    aDefaultValue = new TypedValue(mean);
    if (!Double.isNaN(entropy)) {
        aEntropy = entropy;
    } else {
        aEntropy = 0;
    }

    //Get the correlation
    NumericCorrelator ac = new NumericCorrelator(aCategory);
    aCorrelation = ac.computeCorrelation(aAttributeID, CONSIDERATION_THRESHOLD);

    if (aIsPrice) {
        aDirection = Direction.LESS_IS_BETTER;
    } else {
        aDirection = ac.computeAttributeDirection(aAttributeID, CONSIDERATION_THRESHOLD);
    }
    //Calculate Ranking
    if (aDirection == Direction.LESS_IS_BETTER) {
        Collections.sort(values);
    } else {
        Collections.sort(values, Collections.reverseOrder());
    }
    setRank(values);
}

From source file:model.scenario.CompetitiveScenarioTest.java

@Test
public void rightPriceAndQuantityLearningInventory() {

    for (int competitors = 4; competitors <= 7; competitors++) {
        System.out.println("FORCED COMPETITIVE FIRMS: " + (competitors + 1));
        for (int i = 0; i < 5; i++) {

            final MacroII macroII = new MacroII(System.currentTimeMillis());
            final TripolistScenario scenario1 = new TripolistScenario(macroII);
            scenario1.setSalesDepartmentType(SalesDepartmentOneAtATime.class);
            scenario1.setAskPricingStrategy(SalesControlWithFixedInventoryAndPID.class);
            scenario1.setControlType(//  w  w  w  . j  av a  2  s  .  c  om
                    MonopolistScenario.MonopolistScenarioIntegratedControlEnum.MARGINAL_PLANT_CONTROL);
            scenario1.setAdditionalCompetitors(competitors);
            scenario1.setWorkersToBeRehiredEveryDay(true);
            scenario1.setDemandIntercept(102);

            //assign scenario
            macroII.setScenario(scenario1);

            macroII.start();

            while (macroII.schedule.getTime() < 8000) {
                macroII.schedule.step(macroII);
                /*      System.out.println("sales: " + scenario1.getCompetitors().get(0).getSalesDepartment(GoodType.GENERIC).
                    getLatestObservation(SalesDataType.OUTFLOW) +","
                    + scenario1.getCompetitors().get(1).getSalesDepartment(GoodType.GENERIC).
                    getLatestObservation(SalesDataType.OUTFLOW));
                  */

            }
            SummaryStatistics prices = new SummaryStatistics();
            SummaryStatistics quantities = new SummaryStatistics();
            SummaryStatistics target = new SummaryStatistics();
            for (int j = 0; j < 500; j++) {
                macroII.schedule.step(macroII);
                assert !Float.isNaN(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayAveragePrice());
                prices.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayAveragePrice());
                quantities.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayVolume());

                for (EconomicAgent agent : macroII.getMarket(UndifferentiatedGoodType.GENERIC).getSellers()) {
                    SalesDepartment department = ((Firm) agent)
                            .getSalesDepartment(UndifferentiatedGoodType.GENERIC);
                    target.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayVolume());
                }

            }

            System.out.println(prices.getMean() + " - " + quantities.getMean() + "/" + target.getMean() + "----"
                    + macroII.seed() + " | "
                    + macroII.getMarket(UndifferentiatedGoodType.GENERIC).getLastDaysAveragePrice());
            System.out.println("standard deviations: price : " + prices.getStandardDeviation() + " , quantity: "
                    + quantities.getStandardDeviation());
            OneSectorStatics.printSlopes(scenario1);
            if (competitors >= 4) {
                assertEquals(prices.getMean(), 58, 5);
                //                    assertTrue(prices.getStandardDeviation() < 5.5);
                assertEquals(quantities.getMean(), 44, 5);
                //                  assertTrue(quantities.getStandardDeviation() < 5.5);
            }
            macroII.finish();
        }

    }

}

From source file:model.scenario.CompetitiveScenarioTest.java

@Test
public void rightPriceAndQuantityTestAsMarginalNoPIDAlreadyLearnedFlows() {

    for (int competitors = 4; competitors <= 7; competitors++) {
        //  System.out.println("FORCED COMPETITIVE FIRMS: " + (competitors+1));

        for (int i = 0; i < 5; i++) {

            final MacroII macroII = new MacroII(System.currentTimeMillis());
            final TripolistScenario scenario1 = new TripolistScenario(macroII);
            scenario1.setSalesDepartmentType(SalesDepartmentOneAtATime.class);
            scenario1.setAskPricingStrategy(InventoryBufferSalesControl.class);
            scenario1.setControlType(/*from   w ww  .jav  a  2  s.  c  o m*/
                    MonopolistScenario.MonopolistScenarioIntegratedControlEnum.MARGINAL_PLANT_CONTROL);
            scenario1.setAdditionalCompetitors(competitors);
            scenario1.setWorkersToBeRehiredEveryDay(true);
            scenario1.setDemandIntercept(102);

            scenario1.setSalesPricePreditorStrategy(FixedDecreaseSalesPredictor.class);

            //assign scenario
            macroII.setScenario(scenario1);

            macroII.start();

            macroII.schedule.step(macroII);
            for (Firm firm : scenario1.getCompetitors()) {
                for (HumanResources hr : firm.getHRs())
                    hr.setPredictor(new FixedIncreasePurchasesPredictor(0));

                firm.getSalesDepartment(UndifferentiatedGoodType.GENERIC)
                        .setPredictorStrategy(new FixedDecreaseSalesPredictor(0));
            }

            while (macroII.schedule.getTime() < 5000) {
                macroII.schedule.step(macroII);

            }

            SummaryStatistics prices = new SummaryStatistics();
            SummaryStatistics quantities = new SummaryStatistics();
            SummaryStatistics target = new SummaryStatistics();
            for (int j = 0; j < 500; j++) {
                macroII.schedule.step(macroII);
                assert !Float.isNaN(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayAveragePrice());
                prices.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayAveragePrice());
                quantities.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayVolume());

                for (EconomicAgent agent : macroII.getMarket(UndifferentiatedGoodType.GENERIC).getSellers()) {
                    SalesDepartment department = ((Firm) agent)
                            .getSalesDepartment(UndifferentiatedGoodType.GENERIC);
                    target.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayVolume());
                }

            }

            System.out.println(prices.getMean() + " - " + quantities.getMean() + "/" + target.getMean() + "----"
                    + macroII.seed() + " | "
                    + macroII.getMarket(UndifferentiatedGoodType.GENERIC).getLastDaysAveragePrice());
            System.out.println("standard deviations: price : " + prices.getStandardDeviation() + " , quantity: "
                    + quantities.getStandardDeviation());

            assertEquals(prices.getMean(), 58, 5);
            assertTrue(prices.getStandardDeviation() < 5.5);
            assertEquals(quantities.getMean(), 44, 5);
            assertTrue(quantities.getStandardDeviation() < 5.5);
        }

    }

}

From source file:model.scenario.CompetitiveScenarioTest.java

@Test
public void rightPriceAndQuantityLearningFlows() {

    for (int competitors = 4; competitors <= 7; competitors++) {
        System.out.println("FORCED COMPETITIVE FIRMS: " + (competitors + 1));
        for (int i = 0; i < 5; i++) {

            final MacroII macroII = new MacroII(System.currentTimeMillis());
            final TripolistScenario scenario1 = new TripolistScenario(macroII);
            scenario1.setSalesDepartmentType(SalesDepartmentOneAtATime.class);
            scenario1.setAskPricingStrategy(InventoryBufferSalesControl.class);
            scenario1.setControlType(/*w w w .j  a v a 2s  .  co m*/
                    MonopolistScenario.MonopolistScenarioIntegratedControlEnum.MARGINAL_PLANT_CONTROL);
            scenario1.setAdditionalCompetitors(competitors);
            scenario1.setWorkersToBeRehiredEveryDay(true);
            scenario1.setDemandIntercept(102);

            //assign scenario
            macroII.setScenario(scenario1);

            macroII.start();
            macroII.schedule.step(macroII);

            try {
                final HumanResources hr = scenario1.getMonopolist().getHRs().iterator().next();
                final ErrorCorrectingPurchasePredictor predictor = new ErrorCorrectingPurchasePredictor(macroII,
                        hr);
                hr.setPredictor(predictor);

                predictor.setDebugWriter(Paths.get("runs", "tmp.csv"));
            } catch (IOException e) {
                e.printStackTrace();
            }

            while (macroII.schedule.getTime() < 8000) {
                macroII.schedule.step(macroII);
                /*      System.out.println("sales: " + scenario1.getCompetitors().get(0).getSalesDepartment(GoodType.GENERIC).
                    getLatestObservation(SalesDataType.OUTFLOW) +","
                    + scenario1.getCompetitors().get(1).getSalesDepartment(GoodType.GENERIC).
                    getLatestObservation(SalesDataType.OUTFLOW));
                  */

            }
            SummaryStatistics prices = new SummaryStatistics();
            SummaryStatistics quantities = new SummaryStatistics();
            SummaryStatistics target = new SummaryStatistics();
            for (int j = 0; j < 500; j++) {
                macroII.schedule.step(macroII);
                assert !Float.isNaN(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayAveragePrice());
                prices.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayAveragePrice());
                quantities.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayVolume());

                for (EconomicAgent agent : macroII.getMarket(UndifferentiatedGoodType.GENERIC).getSellers()) {
                    SalesDepartment department = ((Firm) agent)
                            .getSalesDepartment(UndifferentiatedGoodType.GENERIC);
                    target.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayVolume());
                }

            }

            System.out.println(prices.getMean() + " - " + quantities.getMean() + "/" + target.getMean() + "----"
                    + macroII.seed() + " | "
                    + macroII.getMarket(UndifferentiatedGoodType.GENERIC).getLastDaysAveragePrice());
            System.out.println("standard deviations: price : " + prices.getStandardDeviation() + " , quantity: "
                    + quantities.getStandardDeviation());
            OneSectorStatics.printSlopes(scenario1);

            if (competitors >= 4) {
                assertEquals(prices.getMean(), 58, 5);
                assertTrue(prices.getStandardDeviation() < 5.5);
                assertEquals(quantities.getMean(), 44, 5);
                assertTrue(quantities.getStandardDeviation() < 5.5);
            }
            macroII.finish();
        }

    }

}

From source file:model.scenario.CompetitiveScenarioTest.java

@Test
public void rightPriceAndQuantityTestAsMarginalNoPIDStickyLearned() {

    for (int competitors = 4; competitors <= 7; competitors++) {
        System.out.println("FORCED COMPETITIVE FIRMS: " + (competitors + 1));
        float averageResultingPrice = 0;
        float averageResultingQuantity = 0;
        for (int i = 0; i < 5; i++) {

            final MacroII macroII = new MacroII(System.currentTimeMillis());
            final TripolistScenario scenario1 = new TripolistScenario(macroII);
            scenario1.setSalesDepartmentType(SalesDepartmentOneAtATime.class);
            scenario1.setAskPricingStrategy(InventoryBufferSalesControl.class);
            scenario1.setControlType(/*  ww  w.j a  v a2 s. c o m*/
                    MonopolistScenario.MonopolistScenarioIntegratedControlEnum.MARGINAL_PLANT_CONTROL);
            scenario1.setAdditionalCompetitors(competitors);
            scenario1.setWorkersToBeRehiredEveryDay(true);
            scenario1.setDemandIntercept(102);
            scenario1.setBuyerDelay(50);

            //assign scenario
            macroII.setScenario(scenario1);

            macroII.start();
            macroII.schedule.step(macroII);
            for (Firm firm : scenario1.getCompetitors()) {
                SalesDepartment department = firm.getSalesDepartment(UndifferentiatedGoodType.GENERIC);
                final SimpleFlowSellerPID askPricingStrategy = new SimpleFlowSellerPID(department);
                // askPricingStrategy.setTargetInventory(1000);
                askPricingStrategy.setSpeed(0); //stickiness!
                department.setAskPricingStrategy(askPricingStrategy);
                department.setPredictorStrategy(new FixedDecreaseSalesPredictor(0));
            }

            while (macroII.schedule.getTime() < 8000) {
                macroII.schedule.step(macroII);

            }
            SummaryStatistics prices = new SummaryStatistics();
            SummaryStatistics quantities = new SummaryStatistics();
            SummaryStatistics target = new SummaryStatistics();
            for (int j = 0; j < 3000; j++) {
                macroII.schedule.step(macroII);
                //                   assert !Float.isNaN(macroII.getMarket(GoodType.GENERIC).getTodayAveragePrice());
                prices.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getLastPrice());
                quantities.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayVolume());

                for (EconomicAgent agent : macroII.getMarket(UndifferentiatedGoodType.GENERIC).getSellers()) {
                    SalesDepartment department = ((Firm) agent)
                            .getSalesDepartment(UndifferentiatedGoodType.GENERIC);
                    target.addValue(macroII.getMarket(UndifferentiatedGoodType.GENERIC).getTodayVolume());
                }

            }

            System.out.println(prices.getMean() + " - " + quantities.getMean() + "/" + target.getMean() + "----"
                    + macroII.seed() + " | "
                    + macroII.getMarket(UndifferentiatedGoodType.GENERIC).getLastDaysAveragePrice());
            System.out.println("standard deviations: price : " + prices.getStandardDeviation()
                    + " , quantity deviation: " + quantities.getStandardDeviation());
            OneSectorStatics.printSlopes(scenario1);

            if (competitors >= 4) {
                assertEquals(prices.getMean(), 58, 5);
                //                    assertTrue(prices.getStandardDeviation() < 5.5);         these are probably a lot higher with stickiness
                assertEquals(quantities.getMean(), 44, 5);
                //         assertTrue(quantities.getStandardDeviation() < 5.5);
            }
        }

    }

}