Random Number Generators

Last updated on 16th July 2024

The Simudyne SDK provides a SeededRandom class which allows you to create prngs with specific seeds.

Creating a SeededRandom instance

A SeededRandom instance can be created from anywhere in the model using a seed. The recomended way of getting a seed is using the config. This seed can be controlled through the console.

public class MyModel extends AgentBasedModel<GlobalState> {
    // Use getOrSetLong if using this method before setup. (There might not be a seed value before setup.)
    public long seed = this.getConfig().getOrSetLong("core.prng-seed", System.nanoTime());
    public  SeededRandom random = SeededRandom.create(seed);
}

If using this method from outside of a Model, retrieve the config with InternalModelConfig.get().

Using a SeededRandom instance

The SeededRandom class is a wrapper around Apache Commons Math3 PRNG functions. An Apache Commons RandomGenerator implementation exists on the SeededRandom instance at the field generator.

    public  SeededRandom random = SeededRandom.create(seed);
    random.generator.nextInt();

The SeededRandom instance can also be used to create common distributions. Refer to the SeededRandom Javadoc for a full list of distributions.

    public  SeededRandom random = SeededRandom.create(seed);
    NormalDistribution normalDistribution = random.gaussian(1, 1);
    normalDistribution.sample();

Empirical distribution

As well as common distribution, the SeededRandom instance can create an empirical distribution based on a histogram as an input. This histogram should be represented as a Source, like a CSVSource or JDBCSource.

    CSVSource histogram = new CSVSource("/path/to/myDistribution.csv");
    EmpiricalDistribution distribution = SeededRandom.empiricalFromSource(histogram);

The source fields should be named lower, upper and weight. They respectively represents the lower and upper bound of a histogram bucket and the weight of that bucket.

Weights are normalised. Consequently if the sum of the weights is not equal to one, they will be adjusted to do so.

Each bucket of the histogram will be sampled in order to build a smoothed distribution based on the provided values.

Model prng

A RandomGenerator can be retrived inside an AgentBasedModel class for generating random numbers, using the configured seed.

public class MyModel extends AgentBasedModel<GlobalState> {
    public  RandomGenerator random = this.getContext().getPRNG();
}

Agent prng

When running an agent based model, every agent has its own random number generator, each with its own seed built using the root seed. This means that if the root seed is constant, the agent seeds will stay the same.

public class MyAgent extends Agent<GlobalState> {
    this.getPrng().nextDouble;
}