Example usage for java.util Random nextGaussian

List of usage examples for java.util Random nextGaussian

Introduction

In this page you can find the example usage for java.util Random nextGaussian.

Prototype

public synchronized double nextGaussian() 

Source Link

Document

Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.

Usage

From source file:com.rapidminer.gui.plotter.charts.MultipleScatterPlotter.java

private void prepareData() {
    idMap.clear();//from w ww  .  j  a v  a 2  s .  co m
    this.plotIndexToColumnIndexMap.clear();
    dataSet = new DefaultXYDataset();

    if (xAxis >= 0) {
        Map<String, List<double[]>> dataCollection = new LinkedHashMap<String, List<double[]>>();
        Map<String, List<String>> idCollection = new LinkedHashMap<String, List<String>>();

        synchronized (dataTable) {
            for (int column = 0; column < plotColumns.length; column++) {
                if (plotColumns[column]) {
                    plotIndexToColumnIndexMap.add(column);
                    String columnName = this.dataTable.getColumnName(column);
                    Iterator<DataTableRow> i = this.dataTable.iterator();
                    int index = 0;
                    while (i.hasNext()) {
                        DataTableRow row = i.next();

                        double xValue = row.getValue(xAxis);
                        double yValue = row.getValue(column);

                        if (!Double.isNaN(xValue) && !Double.isNaN(yValue)) {
                            addPoint(dataCollection, idCollection, row.getId(), xValue, yValue, columnName);
                        }
                        index++;
                    }
                }
            }
        }

        double minX = Double.POSITIVE_INFINITY;
        double maxX = Double.NEGATIVE_INFINITY;
        double minY = Double.POSITIVE_INFINITY;
        double maxY = Double.NEGATIVE_INFINITY;

        Iterator<Map.Entry<String, List<double[]>>> i = dataCollection.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<String, List<double[]>> entry = i.next();
            List<double[]> dataList = entry.getValue();
            Iterator<double[]> j = dataList.iterator();
            while (j.hasNext()) {
                double[] current = j.next();
                minX = Math.min(minX, current[0]);
                maxX = Math.max(maxX, current[0]);
                minY = Math.min(minY, current[1]);
                maxY = Math.max(maxY, current[1]);
            }
        }

        Random jitterRandom = new Random(2001);
        double oldXRange = maxX - minX;
        double oldYRange = maxY - minY;

        if (Double.isInfinite(oldXRange) || Double.isNaN(oldXRange)) {
            oldXRange = 0;
        }
        if (Double.isInfinite(oldYRange) || Double.isNaN(oldYRange)) {
            oldYRange = 0;
        }

        i = dataCollection.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<String, List<double[]>> entry = i.next();
            String seriesName = entry.getKey();
            List<double[]> dataList = entry.getValue();

            double[][] data = new double[2][dataList.size()];
            int listCounter = 0;
            Iterator<double[]> j = dataList.iterator();
            while (j.hasNext()) {
                double[] current = j.next();
                data[0][listCounter] = current[0];
                data[1][listCounter] = current[1];

                if (this.jitterAmount > 0) {
                    double pertX = oldXRange * (jitterAmount / 200.0d) * jitterRandom.nextGaussian();
                    double pertY = oldYRange * (jitterAmount / 200.0d) * jitterRandom.nextGaussian();
                    data[0][listCounter] += pertX;
                    data[1][listCounter] += pertY;
                }

                listCounter++;
            }
            ((DefaultXYDataset) dataSet).addSeries(seriesName, data);
        }

        int seriesCounter = 0;
        Iterator<List<String>> v = idCollection.values().iterator();
        while (v.hasNext()) {
            List<String> idList = v.next();
            int itemCounter = 0;
            Iterator<String> j = idList.iterator();
            while (j.hasNext()) {
                idMap.put(new SeriesAndItem(seriesCounter, itemCounter++), j.next());
            }
            seriesCounter++;
        }
    }
}

From source file:eu.crisis_economics.abm.fund.FundTest.java

/**
  * This test is in two parts./*from  ww w.  j a v a2  s  . c  o m*/
  * Part 1: a new fund is created with an initial deposit. This deposit is
  *         reserved as private equity. A collection of household stubs are
  *         created with ample starting deposits. For a number of business
  *         cycles, the households all withdraw or contribute random sums to
  *         the fund. The size of these sums is drawn from a Gaussian 
  *         distribution with custom mean and variance. After a fixed number
  *         of business cycles have elapsed, the total amount of cash owned
  *         by each household (be this in fund investments or bank deposits)
  *         is counted. Since the fund has no investment sources and cannot
  *         make a profit, it is expected that no household ever loses or 
  *         gains assets (cash plus fund account value). At every step, it is 
  *         further asserted that the equity of the fund is not significantly
  *         different to the private (constant) equity.
  * Part 2: the fund and all households are destroyed and respawned. Households
  *         begin with ample deposits. The test now continues as in Part 1, except
  *         that the fund deposit account is directly injected with exogenous
  *         profits during each business cycle. The size of these profits is 
  *         drawn from a Gaussian distribution with custom mean and variance.
  *         At the conclusion of Part 2, the amount of cash in the system
  *         is tallied. It is then asserted that the sum of all household deposits
  *         and fund account values is equal to the initial cash in the system 
  *         plus total exogenous profits.
  * Part 3: as Part 2, except the fund now makes exogenous losses as well as
  *         profits. In this test, the fund is deliberately taken to the edge of
  *         its private equity due to market losses.
  */
public void testPrivateEquityConstancyAndConservationOfCash() {

    /*
     * Test parameters
     */
    final int numberOfBusinessCycles = 1000;
    final double meanFundProfit = 1.e6, fundProfitVariance = 2.e5, meanHouseholdInvestment = 0.,
            householdInvestmentVariances = 1000., householdInitialDeposits = 1.e7, fundInitialDeposits = 0.;
    Random dice = new Random(12345);

    myFund = new MutualFund(myBank, new HomogeneousPortfolioWeighting(),
            new FundamentalistStockReturnExpectationFunction(), clearingHouse, new NoSmoothingAlgorithm()); // Fresh fund

    myFund.debit(fundInitialDeposits);
    final Contract exogenousReturns = myFund.mDepositor.depositAccount;
    Assert.assertEquals(myFund.getEquity(), fundInitialDeposits);
    for (int i = 0; i < myHouseholds.length; ++i) {
        myHouseholds[i] = // Ample household liquidity
                new HouseholdStub(myFund, myBank, householdInitialDeposits);
        Assert.assertEquals(myHouseholds[i].getTotalAssets(), householdInitialDeposits, 1.e-5);
    }

    /*
     * Part 1
     */

    for (int i = 0; i < numberOfBusinessCycles; ++i) {
        // Random household investments and withdrawals
        for (int j = 0; j < N_HOUSEHOLDS; ++j) {
            final double investment = dice.nextGaussian() * householdInvestmentVariances
                    + meanHouseholdInvestment;
            try {
                if (investment > 0.)
                    myFund.invest(myHouseholds[j], investment);
                else if (investment < 0.) {
                    final double maximumWithdrawal = myFund.getBalance(myHouseholds[j]);
                    if (maximumWithdrawal == 0.)
                        continue;
                    myFund.requestWithdrawal(myHouseholds[j], Math.min(-investment, maximumWithdrawal));
                }
            } catch (final InsufficientFundsException noFunds) {
                Assert.fail();
            }
        }
        myFund.preClearingProcessing();
        // No profits from fund investments.
        try {
            myFund.postClearingProcessing();
        } catch (final InsufficientFundsException unexpectedException) {
            Assert.fail();
        }
        System.out.printf("MutualFund assets:      %16.10g\n", myFund.getTotalAssets());
        System.out.printf("MutualFund liabilities: %16.10g\n", myFund.getTotalLiabilities());
        System.out.printf("MutualFund equity:      %16.10g\n", myFund.getEquity());

        // Assertions
        final double postClearingEquity = myFund.getEquity();
        Assert.assertEquals(postClearingEquity, fundInitialDeposits, 1.e-5);

        continue;
    }

    // Assert no cash has been created
    System.out.printf("household  deposits [open]  fund investments [open]"
            + "  deposits [close] fund investments [close] sum [close]\n");
    for (int i = 0; i < N_HOUSEHOLDS; ++i) { // Assert no money creation
        final double closingHouseholdDeposits = myHouseholds[i].bankAccount.getBalance(),
                closingFundAccountValue = myFund.getBalance(myHouseholds[i]);
        System.out.printf("%5d %16.10g %16.10g         %16.10g %16.10g         %16.10g\n", i,
                householdInitialDeposits, 0., closingHouseholdDeposits, closingFundAccountValue,
                closingHouseholdDeposits + closingFundAccountValue);
        Assert.assertEquals(closingHouseholdDeposits + closingFundAccountValue, householdInitialDeposits,
                1.e-6);
    }

    /*
     * Part 2
     */

    // Rerun with exogenous fund profits
    double totalFundProfits = 0.;
    for (int i = 0; i < numberOfBusinessCycles; ++i) {
        // Random household investments and withdrawals
        for (int j = 0; j < N_HOUSEHOLDS; ++j) {
            final double investment = dice.nextGaussian() * householdInvestmentVariances
                    + meanHouseholdInvestment;
            try {
                if (investment > 0.)
                    myFund.invest(myHouseholds[j], investment);
                else if (investment < 0.) {
                    final double maximumWithdrawal = myFund.getBalance(myHouseholds[j]);
                    if (maximumWithdrawal == 0.)
                        continue;
                    myFund.requestWithdrawal(myHouseholds[j], Math.min(-investment, maximumWithdrawal));
                }
            } catch (final InsufficientFundsException noFunds) {
                Assert.fail();
            }
        }
        myFund.preClearingProcessing();
        final double fundProfits = dice.nextGaussian() * fundProfitVariance + meanFundProfit;
        exogenousReturns.setValue(exogenousReturns.getValue() + fundProfits);
        totalFundProfits += fundProfits;
        try {
            myFund.postClearingProcessing();
        } catch (final InsufficientFundsException unexpectedException) {
            Assert.fail();
        }

        System.out.printf("MutualFund profits:     %16.10g\n", fundProfits);
        System.out.printf("MutualFund assets:      %16.10g\n", myFund.getTotalAssets());
        System.out.printf("MutualFund liabilities: %16.10g\n", myFund.getTotalLiabilities());
        System.out.printf("MutualFund equity:      %16.10g\n", myFund.getEquity());

        System.out.println("Number of shares: " + myFund.mInvestmentAccount.getNumberOfEmittedShares());

        // Assertions
        final double postClearingEquity = myFund.getEquity();
        Assert.assertEquals(postClearingEquity, fundInitialDeposits, 1.e-1);

        continue;
    }

    // Tally the total amount of cash in the system.
    double totalHouseholdProfits = 0.;
    System.out.printf("household  deposits [open]  fund investments [open]"
            + "  deposits [close] fund investments [close] sum [close]\n");
    for (int i = 0; i < N_HOUSEHOLDS; ++i) { // Assert no money creation
        final double closingHouseholdDeposits = myHouseholds[i].bankAccount.getBalance(),
                closingFundAccountValue = myFund.getBalance(myHouseholds[i]);
        System.out.printf("%5d %16.10g %16.10g         %16.10g %16.10g         %16.10g\n", i,
                householdInitialDeposits, 0., closingHouseholdDeposits, closingFundAccountValue,
                closingHouseholdDeposits + closingFundAccountValue);
        totalHouseholdProfits += (closingHouseholdDeposits + closingFundAccountValue)
                - householdInitialDeposits;
    }

    System.out.printf("Aggregate household profits: %16.10g. MutualFund profits: %16.10g\n",
            totalHouseholdProfits, totalFundProfits);
    Assert.assertEquals(totalHouseholdProfits / Math.pow(10., (int) Math.log10(totalHouseholdProfits)),
            totalFundProfits / Math.pow(10., (int) Math.log10(totalFundProfits)), 1.e-12);

    /*
     * Part 3
     */

    // Rerun with predetermined fund losses.
    UnivariateFunction forcedFundAssetPosition = new UnivariateFunction() {
        @Override
        public double value(double time) {
            return fundInitialDeposits + 1.e-5
                    + householdInvestmentVariances * (1. + Math.sin(2. * Math.PI * time / 50.));
        }
    };
    for (int i = 0; i < numberOfBusinessCycles; ++i) {
        // Random household investments and withdrawals
        for (int j = 0; j < N_HOUSEHOLDS; ++j) {
            final double investment = dice.nextGaussian() * householdInvestmentVariances
                    + meanHouseholdInvestment;
            try {
                if (investment > 0.) {
                    myFund.invest(myHouseholds[j], investment);
                } else if (investment < 0.) {
                    final double maximumWithdrawal = myFund.getBalance(myHouseholds[j]);
                    if (maximumWithdrawal == 0.)
                        continue;
                    double withdrawal = Math.min(-investment, maximumWithdrawal);
                    myFund.requestWithdrawal(myHouseholds[j], withdrawal);
                }
            } catch (final InsufficientFundsException noFunds) {
                Assert.fail();
            }
        }

        myFund.preClearingProcessing();
        final double profitsNow = forcedFundAssetPosition.value(i) - exogenousReturns.getValue();
        totalFundProfits += profitsNow;
        exogenousReturns.setValue(forcedFundAssetPosition.value(i));
        try {
            myFund.postClearingProcessing();
        } catch (final InsufficientFundsException unexpectedException) {
            Assert.fail();
        }

        System.out.printf("MutualFund profits:     %16.10g\n", profitsNow);
        System.out.printf("MutualFund assets:      %16.10g\n", myFund.getTotalAssets());
        System.out.printf("MutualFund liabilities: %16.10g\n", myFund.getTotalLiabilities());
        System.out.printf("MutualFund equity:      %16.10g\n", myFund.getEquity());

        System.out.println("Number of shares: " + myFund.mInvestmentAccount.getNumberOfEmittedShares());

        // Assertions
        final double postClearingEquity = myFund.getEquity();
        Assert.assertEquals(postClearingEquity, fundInitialDeposits, 1.e-1);

        continue;
    }

    // Tally the total amount of cash in the system.
    totalHouseholdProfits = 0.;
    System.out.printf("household  deposits [open]  fund investments [open]"
            + "  deposits [close] fund investments [close] sum [close]\n");
    for (int i = 0; i < N_HOUSEHOLDS; ++i) { // Assert no money creation
        final double closingHouseholdDeposits = myHouseholds[i].bankAccount.getBalance(),
                closingFundAccountValue = myFund.getBalance(myHouseholds[i]);
        System.out.printf("%5d %16.10g %16.10g         %16.10g %16.10g         %16.10g\n", i,
                householdInitialDeposits, 0., closingHouseholdDeposits, closingFundAccountValue,
                closingHouseholdDeposits + closingFundAccountValue);
        totalHouseholdProfits += (closingHouseholdDeposits + closingFundAccountValue)
                - householdInitialDeposits;
    }

    System.out.printf("Aggregate household profits: %16.10g. MutualFund profits: %16.10g\n",
            totalHouseholdProfits, totalFundProfits);
    Assert.assertEquals(
            totalHouseholdProfits / Math.pow(10., (int) Math.log10(Math.abs(totalHouseholdProfits))),
            totalFundProfits / Math.pow(10., (int) Math.log10(Math.abs(totalFundProfits))), 1.e-12);

    return;
}

From source file:com.rapidminer.gui.plotter.charts.Abstract2DChartPlotter.java

private void prepareNominalData() {
    this.nominal = true;
    dataSet = new DefaultXYDataset();

    if (axis[X_AXIS] >= 0 && axis[Y_AXIS] >= 0) {
        Map<String, List<double[]>> dataCollection = new LinkedHashMap<String, List<double[]>>();
        Map<String, List<String>> idCollection = new LinkedHashMap<String, List<String>>();

        synchronized (dataTable) {
            if (colorColumn >= 0) {
                for (int v = 0; v < dataTable.getNumberOfValues(colorColumn); v++) {
                    dataCollection.put(dataTable.mapIndex(colorColumn, v), new LinkedList<double[]>());
                    idCollection.put(dataTable.mapIndex(colorColumn, v), new LinkedList<String>());
                }/*from w w w.j a v a  2 s.  c  o m*/
            }

            Iterator<DataTableRow> i = this.dataTable.iterator();
            int index = 0;
            while (i.hasNext()) {
                DataTableRow row = i.next();

                double xValue = row.getValue(axis[X_AXIS]);
                double yValue = row.getValue(axis[Y_AXIS]);

                double colorValue = Double.NaN;
                if (colorColumn >= 0) {
                    colorValue = row.getValue(colorColumn);
                }

                // TM: removed check
                // if (!Double.isNaN(xValue) && !Double.isNaN(yValue)) {
                addPoint(dataCollection, idCollection, row.getId(), xValue, yValue, colorValue);
                // }
                index++;
            }
        }

        double minX = Double.POSITIVE_INFINITY;
        double maxX = Double.NEGATIVE_INFINITY;
        double minY = Double.POSITIVE_INFINITY;
        double maxY = Double.NEGATIVE_INFINITY;

        Iterator<Map.Entry<String, List<double[]>>> i = dataCollection.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<String, List<double[]>> entry = i.next();
            List<double[]> dataList = entry.getValue();
            Iterator<double[]> j = dataList.iterator();
            while (j.hasNext()) {
                double[] current = j.next();
                minX = MathFunctions.robustMin(minX, current[X_AXIS]);
                maxX = MathFunctions.robustMax(maxX, current[X_AXIS]);
                minY = MathFunctions.robustMin(minY, current[Y_AXIS]);
                maxY = MathFunctions.robustMax(maxY, current[Y_AXIS]);
            }
        }

        Random jitterRandom = new Random(2001);
        double oldXRange = maxX - minX;
        double oldYRange = maxY - minY;

        if (Double.isInfinite(oldXRange) || Double.isNaN(oldXRange)) {
            oldXRange = 0;
        }
        if (Double.isInfinite(oldYRange) || Double.isNaN(oldYRange)) {
            oldYRange = 0;
        }

        i = dataCollection.entrySet().iterator();
        while (i.hasNext()) {
            Map.Entry<String, List<double[]>> entry = i.next();
            String seriesName = entry.getKey();
            List<double[]> dataList = entry.getValue();

            double[][] data = new double[2][dataList.size()];
            int listCounter = 0;
            Iterator<double[]> j = dataList.iterator();
            while (j.hasNext()) {
                double[] current = j.next();
                data[X_AXIS][listCounter] = current[X_AXIS];
                data[Y_AXIS][listCounter] = current[Y_AXIS];

                if (this.jitterAmount > 0) {
                    double pertX = oldXRange * (jitterAmount / 200.0d) * jitterRandom.nextGaussian();
                    double pertY = oldYRange * (jitterAmount / 200.0d) * jitterRandom.nextGaussian();
                    data[X_AXIS][listCounter] += pertX;
                    data[Y_AXIS][listCounter] += pertY;
                }

                listCounter++;
            }

            ((DefaultXYDataset) dataSet).addSeries(seriesName, data);
        }

        int seriesCounter = 0;
        Iterator<List<String>> v = idCollection.values().iterator();
        while (v.hasNext()) {
            List<String> idList = v.next();
            int itemCounter = 0;
            Iterator<String> j = idList.iterator();
            while (j.hasNext()) {
                idMap.put(new SeriesAndItem(seriesCounter, itemCounter++), j.next());
            }
            seriesCounter++;
        }
    }
}

From source file:com.clust4j.algo.AffinityPropagation.java

/**
 * Remove this from scope of {@link #fit()} to avoid lots of large objects
 * left in memory. This is more space efficient and promotes easier testing.
 * @param X//w  w  w .j a  v a 2 s.  c  om
 * @param metric
 * @param seed
 * @param addNoise
 * @return the smoothed similarity matrix
 */
protected static double[][] computeSmoothedSimilarity(final double[][] X, GeometricallySeparable metric,
        Random seed, boolean addNoise) {
    /*
     * Originally, we computed similarity matrix, then refactored the diagonal vector, and
     * then computed the following portions. We can do this all at once and save lots of passes
     * (5?) on the order of O(M^2), condensing it all to one pass of O(M choose 2).
     * 
     * After the sim matrix is computed, we need to do three things:
     * 
     * 1. Create a matrix of very small values (tiny_scaled) to remove degeneracies in sim_mal
     * 2. Multiply tiny_scaled by an extremely small value (GlobalState.Mathematics.TINY*100)
     * 3. Create a noise matrix of random Gaussian values and add it to the similarity matrix.
     * 
     * The methods exist to build these in three to five separate O(M^2) passes, but that's 
     * extremely expensive, so we're going to do it in one giant, convoluted loop. If you're 
     * trying to debug this, sorry...
     * 
     * Total runtime: O(2M * M choose 2)
     */
    final int m = X.length;
    double[][] sim_mat = new double[m][m];

    int idx = 0;
    final double tiny_val = GlobalState.Mathematics.TINY * 100;
    final double[] vector = new double[m * m];
    double sim, noise;
    boolean last_iter = false;

    // Do this a little differently... set the diagonal FIRST.
    for (int i = 0; i < m; i++) {
        sim = -(metric.getPartialDistance(X[i], X[i]));
        sim_mat[i][i] = sim;
        vector[idx++] = sim;
    }

    for (int i = 0; i < m - 1; i++) {
        for (int j = i + 1; j < m; j++) { // Upper triangular
            sim = -(metric.getPartialDistance(X[i], X[j])); // similarity

            // Assign to upper and lower portion
            sim_mat[i][j] = sim;
            sim_mat[j][i] = sim;

            // Add to the vector (twice)
            for (int b = 0; b < 2; b++)
                vector[idx++] = sim;

            // Catch the last iteration, compute the pref:
            double median = 0.0;
            if (last_iter = (i == m - 2 && j == m - 1))
                median = VecUtils.median(vector);

            if (addNoise) {
                noise = (sim * GlobalState.Mathematics.EPS + tiny_val);
                sim_mat[i][j] += (noise * seed.nextGaussian());
                sim_mat[j][i] += (noise * seed.nextGaussian());

                if (last_iter) { // set diag and do the noise thing.
                    noise = (median * GlobalState.Mathematics.EPS + tiny_val);
                    for (int h = 0; h < m; h++)
                        sim_mat[h][h] = median + (noise * seed.nextGaussian());
                }
            } else if (last_iter) {
                // it's the last iter and no noise. Just set diag.
                for (int h = 0; h < m; h++)
                    sim_mat[h][h] = median;
            }
        }
    }

    return sim_mat;
}

From source file:jhplot.H1D.java

/** Fill the histogram with random numbers from Gaussian (Normal) distribution.
* Seed is taken from time. /* w  w w  .  j  a  va2  s . c  o m*/
* @param TotNumber  number generated events
* @param mean mean of the gaussian
* @param sd   standard deviation 
*/
public void fillGauss(int TotNumber, double mean, double sd) {
    java.util.Random random = new java.util.Random();
    for (int i = 0; i < TotNumber; i++)
        h1.fill(sd * random.nextGaussian() + mean);

}

From source file:org.onebusaway.nyc.vehicle_tracking.impl.VehicleLocationSimulationServiceImpl.java

@Override
public int addSimulationForBlockInstance(AgencyAndId blockId, long serviceDate, long actualTime,
        boolean bypassInference, boolean isRunBased, boolean realtime, boolean fillActual,
        boolean reportsOperatorId, boolean reportsRunId, boolean allowRunTransitions, Properties properties) {

    final Random random = new Random();

    final SimulatorTask task = new SimulatorTask();

    final String tag = generateBlockServiceDateTag(blockId, serviceDate);
    task.addTag(tag);//from   w w  w  .  ja  v  a 2 s .c o  m

    task.setPauseOnStart(false);
    task.setRunInRealtime(realtime);
    task.setBypassInference(bypassInference);
    task.setFillActualProperties(fillActual);

    final BlockInstance blockInstance = _blockCalendarService.getBlockInstance(blockId, serviceDate);
    final BlockConfigurationEntry block = blockInstance.getBlock();

    int scheduleTime = (int) ((actualTime - serviceDate) / 1000);
    final int shiftStartTime = getShiftStartTimeProperty(properties);
    scheduleTime -= shiftStartTime;

    final AgencyAndId vehicleId = getVehicleIdProperty(random, properties, blockId.getAgencyId());

    final double locationSigma = getLocationSigma(properties);
    final SortedMap<Double, Integer> scheduleDeviations = getScheduleDeviations(properties);

    if (isRunBased) {

        final RunTripEntry runTrip = _runService.getActiveRunTripEntryForBlockInstance(blockInstance,
                scheduleTime);

        if (runTrip == null) {
            _log.warn("no runTrip for blockInstance=" + blockInstance + " and scheduleTime=" + scheduleTime);
            return -1;
        }

        _log.info("Using runTrip=" + runTrip.toString());

        // TODO pass these along to run-simulation method
        // List<Double> transitionParams =
        // getRunTransitionParams(properties);

        // TODO create "config" object to hold this mess?
        generateRunSim(random, task, runTrip, serviceDate, scheduleTime, shiftStartTime, reportsOperatorId,
                reportsRunId, allowRunTransitions, scheduleDeviations, locationSigma, vehicleId);

        return addTask(task);
    }

    final List<BlockStopTimeEntry> stopTimes = block.getStopTimes();

    final BlockStopTimeEntry firstStopTime = stopTimes.get(0);
    final BlockStopTimeEntry lastStopTime = stopTimes.get(stopTimes.size() - 1);
    final int firstTime = firstStopTime.getStopTime().getArrivalTime();
    final int lastTime = lastStopTime.getStopTime().getDepartureTime();

    if (isIncludeStartTime(properties))
        scheduleTime = firstTime;

    scheduleTime = Math.max(firstTime, scheduleTime);

    while (scheduleTime <= lastTime) {

        final NycTestInferredLocationRecord record = new NycTestInferredLocationRecord();

        final ScheduledBlockLocation blockLocation = _scheduledBlockLocationService
                .getScheduledBlockLocationFromScheduledTime(block, scheduleTime);

        /**
         * Not in service?
         */
        if (blockLocation == null)
            return -1;

        final BlockTripEntry trip = blockLocation.getActiveTrip();

        final AgencyAndId tripId = trip.getTrip().getId();

        final CoordinatePoint location = blockLocation.getLocation();
        record.setActualBlockId(AgencyAndIdLibrary.convertToString(blockId));
        record.setActualDistanceAlongBlock(blockLocation.getDistanceAlongBlock());
        final int actualScheduleTime = blockLocation.getScheduledTime();

        String dsc = _destinationSignCodeService.getDestinationSignCodeForTripId(tripId);
        if (dsc == null)
            dsc = "0";

        int scheduleDeviation = 0;

        if (!scheduleDeviations.isEmpty()) {
            final double ratio = (scheduleTime - firstTime) / ((double) (lastTime - firstTime));
            scheduleDeviation = (int) InterpolationLibrary.interpolate(scheduleDeviations, ratio,
                    EOutOfRangeStrategy.LAST_VALUE);
        }

        final long timestamp = serviceDate + (scheduleTime + shiftStartTime + scheduleDeviation) * 1000;

        final CoordinatePoint p = applyLocationNoise(location.getLat(), location.getLon(), locationSigma,
                random);

        record.setDsc(dsc);
        record.setLat(p.getLat());
        record.setLon(p.getLon());
        record.setTimestamp(timestamp);
        record.setVehicleId(vehicleId);
        record.setActualServiceDate(serviceDate);
        record.setActualScheduleTime(actualScheduleTime);
        record.setActualDsc(dsc);
        record.setActualPhase(EVehiclePhase.IN_PROGRESS.toString());

        task.addRecord(record);

        scheduleTime += 60 + random.nextGaussian() * 10;
    }

    return addTask(task);
}

From source file:org.onebusaway.nyc.vehicle_tracking.impl.VehicleLocationSimulationServiceImpl.java

public void generateRunSim(Random random, SimulatorTask task, RunTripEntry runTrip, long serviceDate,
        int scheduleTime, int shiftStartTime, boolean reportsOperatorId, boolean reportsRunId,
        boolean allowRunTransitions, SortedMap<Double, Integer> scheduleDeviations, double locationSigma,
        AgencyAndId vehicleId) {/*w w w  .  j  a  v  a 2s  . co  m*/

    /*
     * here we format the runId to have a run-route that looks similar to what
     * an operator would enter.
     */
    final String runNumber = runTrip.getRunNumber();
    String runRoute = runTrip.getRunRoute();

    if (StringUtils.equals(runRoute, "MISC")) {
        // runRoute = "0" + random.nextInt(9) + random.nextInt(9);
        runRoute = "000";
    } else if (runRoute.length() >= 5) {
        final String firstPart = runRoute.substring(1, 3);
        final String lastPart = runRoute.substring(3);
        runRoute = "0" + (random.nextBoolean() ? firstPart : lastPart);
    } else {
        final String firstPart = runRoute.substring(1, 3);
        runRoute = "0" + firstPart;
    }

    final String reportedRunId = RunTripEntry.createId(runRoute, runNumber);

    if (reportsRunId)
        _log.info("using reported runId=" + reportedRunId);

    String lastBlockId = null;

    final List<RunTripEntry> rtes = new ArrayList<RunTripEntry>();
    for (final RunTripEntry rte : _runService.getRunTripEntriesForRun(runTrip.getRunId())) {
        if (_calendarService.isLocalizedServiceIdActiveOnDate(rte.getTripEntry().getServiceId(),
                new Date(serviceDate)))
            rtes.add(rte);
    }

    if (rtes.isEmpty()) {
        _log.error("no active runTrips for service date=" + new Date(serviceDate));
    }
    // TODO necessary?
    Collections.sort(rtes, new RunTripComparator(serviceDate, _blockCalendarService));

    // String agencyId = runTrip.getTripEntry().getId().getAgencyId();

    CoordinatePoint lastLocation = null;
    final RunTripEntry lastRunTrip = rtes.get(rtes.size() - 1);
    final int firstTime = runTrip.getStartTime();
    final int lastTime = lastRunTrip.getStopTime();
    int runningLastTime = runTrip.getStopTime();
    int currRunIdx = rtes.indexOf(runTrip);

    // We could go by run trip entry sequence or perturbed schedule-time
    // evolution. The latter is chosen, for now.
    while (scheduleTime <= lastTime) {

        final NycTestInferredLocationRecord record = new NycTestInferredLocationRecord();

        final long unperturbedTimestamp = serviceDate + (scheduleTime + shiftStartTime) * 1000;

        if (scheduleTime >= runningLastTime) {
            if (currRunIdx == rtes.size() - 1)
                break;
            currRunIdx += 1;
            runTrip = rtes.get(currRunIdx);
            // runTrip = _runService.getNextEntry(runTrip);

            runningLastTime = runTrip.getStopTime();

            // FIXME saw weird run setups like this. are these in error?
            if (scheduleTime >= runningLastTime) {
                _log.error("runs are ordered oddly:" + rtes.get(currRunIdx - 1) + " -> " + runTrip);
                break;
            }
        }

        /*
         * this could mean that the run has ended. We could reassign the driver?
         * for now we'll terminate the simulation
         */
        if (runTrip == null)
            break;

        final TripEntry trip = runTrip.getTripEntry();

        final AgencyAndId tripId = trip.getId();

        record.setActualTripId(AgencyAndIdLibrary.convertToString(tripId));

        // TODO dsc changes for new block/run?
        String dsc = _destinationSignCodeService.getDestinationSignCodeForTripId(tripId);

        if (StringUtils.isEmpty(dsc))
            dsc = "0";

        // FIXME straighten these out...
        if (scheduleTime < runTrip.getStartTime()) {
            record.setActualPhase(EVehiclePhase.DEADHEAD_BEFORE.toString());
            dsc = "0";
        } else {
            record.setActualPhase(EVehiclePhase.IN_PROGRESS.toString());
        }

        int scheduleDeviation = 0;

        if (!scheduleDeviations.isEmpty()) {
            final double ratio = (scheduleTime - firstTime) / ((double) (lastTime - firstTime));
            scheduleDeviation = (int) InterpolationLibrary.interpolate(scheduleDeviations, ratio,
                    EOutOfRangeStrategy.LAST_VALUE);
        }

        final long perterbedTimestamp = unperturbedTimestamp + scheduleDeviation * 1000;

        /*
         * sample runTrips active 30 minutes from now. TODO make the time range
         * less arbitrary?
         */
        if (allowRunTransitions) {
            final RunTripEntry newRun = sampleNearbyRunTrips(runTrip, unperturbedTimestamp + 30 * 60 * 1000);

            if (newRun != null) {
                // FIXME can we get to this trip in 30, or whatever minutes?
                // FIXME what geometry do we follow to get there?

                /*
                 * we need to simulate the dsc/headsign: could set it to 0 the new
                 * trip the current trip ... TODO should this be a user option?
                 */
                record.setActualPhase(EVehiclePhase.DEADHEAD_BEFORE.toString());
                dsc = "0";

                runTrip = newRun;

                /*
                 * similarly, do we reset the reportedRunId? TODO also a user option?
                 */
                // reportedRunId = runTrip.getRun();

            }
        }

        // TODO when are there multiples and which do we choose when there are?
        final ScheduledBlockLocation blockLocation = _runService.getSchedBlockLocForRunTripEntryAndTime(runTrip,
                unperturbedTimestamp);

        if (blockLocation == null)
            break;

        final BlockEntry blockEntry = blockLocation.getActiveTrip().getBlockConfiguration().getBlock();

        _log.debug("sim blockLocation: " + blockLocation.toString());
        CoordinatePoint location = blockLocation.getLocation();

        record.setActualRunId(runTrip.getRunId());

        final String currentBlockId = AgencyAndIdLibrary.convertToString(blockEntry.getId());
        // if (_log.isDebugEnabled())
        if (lastBlockId != null && !StringUtils.equals(currentBlockId, lastBlockId)) {
            _log.info("changed blocks: " + lastBlockId + " -> " + currentBlockId);
        }
        record.setActualBlockId(currentBlockId);
        lastBlockId = currentBlockId;
        record.setActualDistanceAlongBlock(blockLocation.getDistanceAlongBlock());

        /*
         * during block changes we get a weird null location. this is a
         * "work-around"...
         */
        if (location == null) {
            location = lastLocation;
        } else {
            lastLocation = location;
        }
        final CoordinatePoint p = applyLocationNoise(location.getLat(), location.getLon(), locationSigma,
                random);

        record.setDsc(dsc);
        record.setLat(p.getLat());
        record.setLon(p.getLon());
        record.setTimestamp(perterbedTimestamp);
        record.setVehicleId(vehicleId);
        // TODO options for whether these are reported or not?
        if (reportsOperatorId)
            record.setOperatorId("0000");

        if (reportsRunId) {
            record.setReportedRunId(reportedRunId);
        }

        record.setActualServiceDate(serviceDate);

        final int actualScheduleTime = blockLocation.getScheduledTime();
        record.setActualScheduleTime(actualScheduleTime);

        record.setActualDsc(dsc);
        record.setActualBlockLat(location.getLat());
        record.setActualBlockLon(location.getLon());
        // TODO setActualStatus?

        task.addRecord(record);

        scheduleTime += 30 + random.nextGaussian() * 2;
    }

}