Rng

Rng(*args, **kwargs)

The seeded random number generator a corehydro callback is handed.

Draw from this, not from random or numpy.random, for every random number a callback needs: it is the same Mersenne Twister the core seeded, so the run stays reproducible from its seed and agrees value for value with the identical run in R.

The handle borrows the generator for the duration of the one call it was given to. It is not an object to keep. Storing it and drawing from it after your callback has returned raises RuntimeError, which is deliberate: the generator it pointed at no longer exists, and reading it would crash the interpreter rather than merely misbehave.

Examples

The Gibbs proposal of :func:corehydropy.mcmc_posterior is the verb that hands you one. This model’s full conditional really is uniform: with x_i ~ Uniform(mu - 1, mu + 1) and a flat prior, mu given the data is Uniform(max(x) - 1, min(x) + 1), so one uniform draw IS the Gibbs step.

>>> import corehydropy as ch
>>> x = [4.9, 5.1, 5.0, 5.2, 4.8]
>>> def ll(p):
...     return 0.0 if all(abs(xi - p[0]) <= 1.0 for xi in x) else float("-inf")
>>> def proposal(parameters, rng):
...     lo, hi = max(x) - 1.0, min(x) + 1.0
...     return [lo + rng.uniform(1)[0] * (hi - lo)]
>>> fit = ch.mcmc_posterior(ll, ch.Distribution("Uniform", [0.0, 10.0]),
...                         sampler="Gibbs", proposal=proposal,
...                         iterations=200, seed=12345, initialize="Randomize")
>>> round(float(fit["posterior_mean"][0]), 1)
5.0

rng.integers(n, min, max) draws whole numbers on [min, max) off the same stream – a resampling proposal, say, picking one of the observations by index.

>>> def pick_one(parameters, rng):
...     return [x[rng.integers(1, 0, len(x))[0]]]

Methods

Name Description
integers integers(self: corehydropy._core.Rng, n: object, min: object, max: object) -> list[int]
uniform uniform(self: corehydropy._core.Rng, n: object) -> list[float]

integers

Rng.integers()

integers(self: corehydropy._core.Rng, n: object, min: object, max: object) -> list[int]

n draws on [min, max) – the upper bound is EXCLUDED, as in the ported C# MersenneTwister.Next(minInclusive, maxExclusive). min and max must be whole numbers no more than 2147483647 apart (the ported generator draws an int32 span, and C# throws for a wider one).

uniform

Rng.uniform()

uniform(self: corehydropy._core.Rng, n: object) -> list[float]

n draws on [0, 1) (the ported C# MersenneTwister.NextDouble).