Table of Contents

Class BitGenerator

Namespace
NumSharp
Assembly
NumSharp.dll

Base class for the pseudo-random bit generators that drive Generator and the legacy NumPyRandom (RandomState).

public abstract class BitGenerator
Inheritance
BitGenerator
Derived
Inherited Members

Remarks

Mirrors NumPy 2.4.2's numpy.random.BitGenerator (bit_generator.pyx): a source of uniform 64-/32-bit words plus the [0,1) float conversions the distribution kernels are built on, with NumPy's public surface — random_raw(Shape?, bool), state, seed_seq and lock. The per-draw primitives (NextUInt64 …) are NumPy's bitgen_t function pointers, public so a generator can be written outside NumSharp.dll (NumPy takes user bit generators through the same contract): a subclass implements NextUInt64(), NextUInt32(), Name, CreateFromSeed(ISeedSequence), GetStateCore() and SetStateCore(BitGeneratorState), and may override the conversions and bulk fills for speed. Concrete generators: PCG64 (the default_rng default), PCG64DXSM (NumPy's recommendation for massively parallel work), Philox (a counter-based generator addressable by key/counter), SFC64 (Chris Doty-Humphrey's small fast chaotic generator) and MT19937 (the legacy RandomState's engine). Each is seeded through an ISeedSequence (normally a SeedSequence) and spawn(int)s independent children from it.

Constructors

BitGenerator(ISeedSequence)

Initializes the shared state of a bit generator.

protected BitGenerator(ISeedSequence seedSeq)

Parameters

seedSeq ISeedSequence

The seed sequence the subclass seeds itself from (null for a generator seeded without one).

Remarks

A subclass passes the sequence it seeds from and then draws its initial state from it (SeedWords32(ISeedSequence, int) / SeedWords64(ISeedSequence, int)). Passing null makes spawn(int) refuse (NumPy's _seed_seq = None), so a generator that wants a fresh entropy default passes new SeedSequence() itself, as the built-in parameterless constructors do.

Properties

Name

The bit generator's class name, e.g. "PCG64". Drives Generator's repr and the state checks.

public abstract string Name { get; }

Property Value

string

Remarks

A subclass returns its own NumPy-style class name: Generator prints it as Generator(NAME). Its own state refusal (in SetStateCore(BitGeneratorState)) should name the same class, as the built-in generators' NumPy texts do.

lock

The lock every draw from this bit generator holds (NumPy's BitGenerator.lock).

public object @lock { get; }

Property Value

object

Remarks

A Generator holds this monitor for the whole of a fill, exactly as NumPy's with self.lock: does. The engine state (PCG64's two 128-bit words plus its buffered 32-bit half, MT19937's 624-word key and position) is updated non-atomically, so two threads drawing at once tear it and emit values that belong to no seed's stream — measured at 72–99% foreign values for four threads before the lock existed. Generators built over the SAME bit generator share this object, so their draws serialize together, as NumPy's Generator.lock = bit_generator.lock makes them. The monitor is re-entrant (like NumPy's RLock), so a draw that goes through another public method (e.g. choice calling integers) re-acquires it without deadlock. Code that calls the primitives (NextUInt64(), the fills, GetStateCore() …) directly must hold it too - they are not synchronized.

seed_seq

The seed sequence used to initialize the bit generator (NumPy's BitGenerator.seed_seq) — normally a SeedSequence (cast to read its entropy / spawn_key).

public ISeedSequence seed_seq { get; }

Property Value

ISeedSequence

Remarks

Null for a bit generator re-seeded with _legacy_seeding() or built from an explicit Philox key (NumPy then reports None too). A jumped() copy carries a FRESH OS-entropy sequence, as NumPy's self.class() construction gives it — not the parent's.

state

Gets or sets the bit generator's state (NumPy's bit_generator.state dict, as a typed BitGeneratorState whose members are named after the dict's keys).

public BitGeneratorState state { get; set; }

Property Value

BitGeneratorState

Remarks

The getter returns a fresh snapshot; setting it copies the snapshot's values in, so a snapshot can be restored any number of times. Each concrete generator also exposes a typed state property of its own state class. Reading or writing holds lock.

Exceptions

TypeError

Setting null (NumPy: state must be a dict).

ValueError

Setting another generator's state (NumPy: state must be for a <name> RNG/PRNG).

Methods

CreateFromSeed(ISeedSequence)

Constructs a new instance of this bit generator's concrete type seeded from seed (NumPy's type(self)(seed=seed)).

public abstract BitGenerator CreateFromSeed(ISeedSequence seed)

Parameters

seed ISeedSequence

The seed sequence.

Returns

BitGenerator

The new, independently seeded generator.

Remarks

spawn(int) builds every child through it, so a subclass returns its OWN type here - a subclass of a built-in generator that does not override it spawns instances of the built-in class.

FillDouble(double*, long)

Fills n next_double draws in [0, 1) (the stream NextDouble() yields).

public virtual void FillDouble(double* dst, long n)

Parameters

dst double*

The destination (at least n doubles).

n long

The number of draws (non-positive: nothing).

Remarks

The caller holds lock.

FillDoubleFrom64(double*, long)

FillDouble(double*, long) for engines whose next_double is uint64_to_double(next_uint64) (PCG64, PCG64DXSM, Philox, SFC64): the destination is filled with raw words a chunk at a time and each word is converted IN PLACE to (w >> 11) * 2**-53.

public void FillDoubleFrom64(double* dst, long n)

Parameters

dst double*

The destination.

n long

The number of draws.

Remarks

Reinterpreting the double slots as words is safe (same size, each word read before its slot is rewritten), and w >> 11 < 2**53 converts exactly through the signed conversion. A custom 64-bit engine returns it from its FillDouble(double*, long) override; the caller holds lock.

FillFloat(float*, long)

Fills n next_float draws in [0, 1) (the stream NextFloat() yields).

public virtual void FillFloat(float* dst, long n)

Parameters

dst float*

The destination (at least n floats).

n long

The number of draws (non-positive: nothing).

Remarks

The caller holds lock.

FillFloatFrom64(float*, long, ref int, ref uint)

FillFloat(float*, long) for the split-word engines: FillUInt32From64(uint*, long, ref int, ref uint) into the float slots a chunk at a time, then each word converted in place to (u >> 8) * 2**-24 (NumPy's next_float).

public void FillFloatFrom64(float* dst, long n, ref int hasUint32, ref uint uinteger)

Parameters

dst float*

The destination.

n long

The number of draws.

hasUint32 int

The engine's pending-half flag (read and updated).

uinteger uint

The engine's pending half (read and updated).

Remarks

Pass the engine's own pending-half fields by reference, as for FillUInt32From64(uint*, long, ref int, ref uint); the caller holds lock.

FillRaw(ulong*, long)

Fills n raw words (next_raw, widened to 64 bits) — the stream NextRaw() yields.

public virtual void FillRaw(ulong* dst, long n)

Parameters

dst ulong*

The destination (at least n words).

n long

The number of words (non-positive: nothing).

Remarks

The caller holds lock.

FillUInt32(uint*, long)

Fills n words of next_uint32, buffered halves included (the stream NextUInt32() yields).

public virtual void FillUInt32(uint* dst, long n)

Parameters

dst uint*

The destination (at least n words).

n long

The number of words (non-positive: nothing).

Remarks

The caller holds lock.

FillUInt32From64(uint*, long, ref int, ref uint)

FillUInt32(uint*, long) for engines whose next_uint32 splits a next_uint64 word — low half returned, high half buffered (PCG64, PCG64DXSM, Philox, SFC64): a pending half is served first, whole words then land straight in the destination (little-endian, so word k's low/high halves ARE the next two uint32 slots), and an odd final draw splits one more word and buffers its high half.

public void FillUInt32From64(uint* dst, long n, ref int hasUint32, ref uint uinteger)

Parameters

dst uint*

The destination (any 4-byte alignment; the word stores may be unaligned).

n long

The number of draws.

hasUint32 int

The engine's pending-half flag (read and updated).

uinteger uint

The engine's pending half (read and updated).

Remarks

A custom split-word engine passes its OWN pending-half fields by reference from its FillUInt32(uint*, long) override (the caller holds lock); passing copies loses the half a later NextUInt32() must serve, and the stream diverges from the per-draw one.

FillUInt64(ulong*, long)

Fills n words of next_uint64 (the stream NextUInt64() yields).

public virtual void FillUInt64(ulong* dst, long n)

Parameters

dst ulong*

The destination (at least n words; may be unaligned).

n long

The number of words (non-positive: nothing).

Remarks

The caller holds lock.

GetStateCore()

Snapshots the engine state.

public abstract BitGeneratorState GetStateCore()

Returns

BitGeneratorState

A fresh state object of the concrete generator's state type.

Remarks

The unlocked half of state's getter, which a subclass implements. Callers read state instead: called directly this skips lock, so a concurrent draw can tear the snapshot.

NextDouble()

A random double in [0, 1) with 53-bit precision (NumPy's next_double).

public virtual double NextDouble()

Returns

double

The top 53 bits of one 64-bit word scaled by 2**-53 (engines with their own formula override).

Remarks

An override must stay consistent with UnitToDouble(ulong): the read-ahead buffer converts NextUInt64() words through it and expects this method's stream.

NextFloat()

A random float in [0, 1) with 24-bit precision (NumPy's next_float).

public virtual float NextFloat()

Returns

float

The top 24 bits of one 32-bit word scaled by 2**-24.

Remarks

Not synchronized, as NextUInt64().

NextRaw()

The engine's raw output word (NumPy's next_raw), widened to 64 bits.

public virtual ulong NextRaw()

Returns

ulong

A full 64-bit word for 64-bit engines; the 32-bit word for MT19937.

Remarks

What random_raw(Shape?, bool) returns; an engine whose raw word is narrower than 64 bits overrides it.

NextUInt32()

The next uniform 32-bit word (NumPy's next_uint32).

public abstract uint NextUInt32()

Returns

uint

A uniformly distributed 32-bit value; advances (or consumes a buffered half of) the engine state.

Remarks

Not synchronized, as NextUInt64(). A 64-bit engine returns the low half of a word and buffers the high half for the next call (NumPy's has_uint32 / uinteger), which its state must carry.

NextUInt64()

The next uniform 64-bit word (NumPy's next_uint64).

public abstract ulong NextUInt64()

Returns

ulong

A uniformly distributed 64-bit value; advances the engine state.

Remarks

Not synchronized: a caller outside Generator holds lock around its draws, or two threads tear the state and emit values of no seed's stream.

SeedWords32(ISeedSequence, int)

Reads n_words uint32 seeding words from any ISeedSequence (the fast path for SeedSequence, the interface contract — a uint32 NDArray — otherwise).

public static uint[] SeedWords32(ISeedSequence seed, int n_words)

Parameters

seed ISeedSequence

The seed sequence.

n_words int

The word count.

Returns

uint[]

The words.

Remarks

NumPy's seed_seq.generate_state(n_words, np.uint32): the way a generator turns its seed sequence into its initial state words, so a custom generator seeds exactly as NumPy's would.

Exceptions

ArgumentNullException

seed is null.

TypeError

A custom sequence returned something other than a uint32 array of at least n_words words.

SeedWords64(ISeedSequence, int)

Reads n_words uint64 seeding words from any ISeedSequence (the fast path for SeedSequence, the interface contract — a uint64 NDArray — otherwise).

public static ulong[] SeedWords64(ISeedSequence seed, int n_words)

Parameters

seed ISeedSequence

The seed sequence.

n_words int

The word count.

Returns

ulong[]

The words.

Remarks

NumPy's seed_seq.generate_state(n_words, np.uint64), for generators with 64-bit state words.

Exceptions

ArgumentNullException

seed is null.

TypeError

A custom sequence returned something other than a uint64 array of at least n_words words.

SetStateCore(BitGeneratorState)

Restores the engine state from a snapshot (validated against this generator's type).

public abstract void SetStateCore(BitGeneratorState value)

Parameters

value BitGeneratorState

The non-null snapshot.

Remarks

The unlocked half of state's setter, which a subclass implements (and which must refuse a snapshot of another type). Callers assign state instead: called directly this skips the null check and lock.

Exceptions

ValueError

The snapshot belongs to another bit generator type.

UnitToDouble(ulong)

Converts one next_uint64 draw to the next_double the same stream position would have produced — the contract that lets NumSharp.DrawBuffer64 serve both kinds of draw from one read-ahead buffer.

public virtual double UnitToDouble(ulong unit)

Parameters

unit ulong

A word from NextUInt64() / FillUInt64(ulong*, long).

Returns

double

(unit >> 11) * 2**-53 — uint64_to_double, the next_double of every 64-bit engine (MT19937 overrides it: its double is built from the two 32-bit words its 64-bit draw concatenates).

Remarks

Pure (no state change); an engine whose NextDouble() is not uint64_to_double(next_uint64) overrides both together.

random_raw(Shape?, bool)

Return randoms as generated by the underlying bit generator (NumPy's BitGenerator.random_raw).

public NDArray random_raw(Shape? size = null, bool output = true)

Parameters

size Shape?

Output shape; null (NumPy's None, the default) returns a single value as a 0-d array.

output bool

When false the draws are made but discarded and null is returned (NumPy's benchmark switch).

Returns

NDArray

The raw words as uint64 — a 0-d array for size=None, else an array of size; null when output is false. Every raw value is widened to 64 bits irrespective of the number of bits the engine produces (MT19937's raw words are 32-bit).

Remarks

With output false NumPy draws np.asarray(size).sum() values — the SUM of the dimensions, not their product ((3, 4) draws 7, (0, 3) draws 3, -1 draws none). That quirk decides how far the stream advances, so it is reproduced. The whole call holds lock.

Exceptions

ValueError

size has a negative dimension (with output true).

TypeError

size is () with output false — NumPy sums an empty float array and cannot use the float as a count.

spawn(int)

Create new independent child bit generators of this generator's type (NumPy's BitGenerator.spawn), each seeded from a child of seed_seq — the recommended way to get non-overlapping streams for parallel work.

public BitGenerator[] spawn(int n_children)

Parameters

n_children int

The number of children.

Returns

BitGenerator[]

The children, of this bit generator's concrete type (NumPy's type(self)(seed=s)).

Remarks

Spawning advances the parent seed sequence's n_children_spawned, so repeated calls never repeat a child.

Exceptions

ValueError

n_children is negative: NumPy 2.5's n_children must be non-negative, raised before the seed sequence is looked at (so a legacy-seeded MT19937 reports it, not the TypeError below).

TypeError

The seed sequence cannot spawn — e.g. none (legacy-seeded MT19937, keyed Philox): NumPy's The underlying SeedSequence does not implement spawning.

OverflowError

The seed sequence's child count would leave its uint32 range.