Table of Contents

Class SeedSequence

Namespace
NumSharp
Assembly
NumSharp.dll

Mixes sources of entropy into a high-quality initial state for a bit generator, and spawns independent children for parallel streams (NumPy's numpy.random.SeedSequence).

public sealed class SeedSequence : ISpawnableSeedSequence, ISeedSequence
Inheritance
SeedSequence
Implements
Inherited Members

Remarks

Port of NumPy 2.4.2's SeedSequence (numpy/random/bit_generator.pyx). The entropy coercion (_coerce_to_uint32_array), the spawn-key assembly, the hash-mixing pool and generate_state(long, DType) are byte-for-byte NumPy's, so a PCG64/MT19937/… seeded from the same entropy — or from the same position in a spawn(int) tree — reproduces NumPy's exact stream.

Constructors

SeedSequence()

Constructs a sequence from fresh, unpredictable OS entropy (NumPy's SeedSequence()).

public SeedSequence()

SeedSequence(int[])

Constructs a sequence from a sequence of non-negative integers.

public SeedSequence(int[] entropy)

Parameters

entropy int[]

The seed words (a value of 2**32 or more spans several words, as in NumPy); null is NumPy's None — fresh OS entropy, never the empty list (an empty array is [], a fixed seed).

Remarks

A null array used to become [], so a "no seed" array seeded every run with the SAME stream (NumPy's SeedSequence([])) — silently, since an entropy-seeded result is not reproducible to begin with. It now forwards null to the dynamically-typed overload, which reads OS entropy like SeedSequence().

Exceptions

ValueError

An element is negative.

SeedSequence(long)

Constructs a sequence from a single non-negative integer seed.

public SeedSequence(long entropy)

Parameters

entropy long

The seed.

Exceptions

ValueError

entropy is negative (expected non-negative integer).

SeedSequence(long[])

Constructs a sequence from a sequence of non-negative integers.

public SeedSequence(long[] entropy)

Parameters

entropy long[]

The seed words (a value of 2**32 or more spans several words, as in NumPy); null is NumPy's None — fresh OS entropy, never the empty list.

Exceptions

ValueError

An element is negative.

SeedSequence(BigInteger)

Constructs a sequence from a single non-negative integer seed of arbitrary size.

public SeedSequence(BigInteger entropy)

Parameters

entropy BigInteger

The seed.

Exceptions

ValueError

entropy is negative.

SeedSequence(object, object, long, uint)

Constructs a sequence with NumPy's full signature: SeedSequence(entropy=None, *, spawn_key=(), pool_size=4, n_children_spawned=0).

public SeedSequence(object entropy, object spawn_key = null, long pool_size = 4, uint n_children_spawned = 0)

Parameters

entropy object

null for fresh OS entropy; a non-negative integer (any C# integer type, BigInteger, or a bool as 0/1); a flat sequence of them — a C# array or IList whose string elements parse NumPy's way (ParseSeedString(string, bool): a "0x…" string through int(x, 16), a string that starts with a decimal digit through int(x), anything else unrecognized seed string); or a 1-D integer or text NDArray (a uint32 array passes through as-is, a uint[] standing for one). A NESTED sequence is refused since NumPy 2.5 (see HasPythonLen(object)).

spawn_key object

This sequence's position in a spawn tree (mixed in as extra entropy); null or empty for a root. Any iterable — NumPy's tuple(spawn_key) — such as a long[], int[], uint[], BigInteger[], a list or a 1-D integer NDArray; string elements parse with the entropy's string rule (a string key is itself a sequence of one-character strings, as tuple("12") is). Nested elements are refused, as for the entropy (see ToSpawnKey(object)).

pool_size long

The pool size in uint32 words (at least 4; 8 gives a 256-bit pool) — NumPy's Py_ssize_t.

n_children_spawned uint

The number of children already spawned — only when rebuilding a serialized sequence. NumPy stores it as a uint32_t, so the parameter is one.

Exceptions

ValueError

pool_size is below 4; an entropy or spawn-key value is negative (expected non-negative integer); a string that is not a seed literal (unrecognized seed string, or Python's invalid literal for int() … for one that starts like a number).

TypeError

entropy is not an integer or a sequence of integers (a float, a string, a float/bool array, a 0-d array, a null element); either holds a nested sequence — a sequence, array or fixed-width bytes element, or a multi-dimensional array (NumPy 2.5's SeedSequence does not accept nested sequences.); spawn_key is not iterable (NumPy's 'int' object is not iterable), is a 0-d array (iteration over a 0-d array) or holds an element the coercion refuses (a float: seed must be integer; null: object of type 'NoneType' has no len()). The checks run in NumPy's order: the key's iterability, then the entropy, then the key's elements.

ArrayMemoryError

pool_size is larger than an array can hold (NumPy's MemoryError from np.zeros(pool_size)).

SeedSequence(uint[])

Constructs a sequence directly from uint32 words (NumPy's uint32-ndarray pass-through).

public SeedSequence(uint[] entropy)

Parameters

entropy uint[]

The seed words; null is NumPy's None — fresh OS entropy, never the empty list.

Remarks

The overload a bare null literal binds (new SeedSequence(null), NumPy's SeedSequence(None)): the int[]/long[]/uint[] overloads are equally good targets for it under plain C# rules, so this one carries the higher System.Runtime.CompilerServices.OverloadResolutionPriorityAttribute — harmless for every non-null argument, since no other array converts to uint[].

SeedSequence(ulong)

Constructs a sequence from a single non-negative integer seed.

public SeedSequence(ulong entropy)

Parameters

entropy ulong

The seed.

Properties

entropy

The entropy this sequence was built from (NumPy's SeedSequence.entropy): the integer or sequence as given, or — for a sequence built without entropy — the 128-bit (pool_size * 32-bit) random BigInteger drawn from the OS, which is what to log for reproducibility (new SeedSequence(seq.entropy) rebuilds the same pool).

public object entropy { get; }

Property Value

object

n_children_spawned

The number of children already spawned — the next child's index (NumPy's n_children_spawned, stored as a uint32_t: spawn(int) refuses to pass 2**32 - 1).

public uint n_children_spawned { get; }

Property Value

uint

pool

The mixed uint32 entropy pool (NumPy's SeedSequence.pool, a uint32 ndarray of pool_size words), as a fresh copy.

public NDArray pool { get; }

Property Value

NDArray

Remarks

NumPy hands out the pool array itself, so writing into it there changes every later generate_state(long, DType); the copy keeps this sequence immutable, as its documentation promises.

pool_size

The number of uint32 words in the entropy pool (NumPy's pool_size, a Py_ssize_t; at least 4).

public long pool_size { get; }

Property Value

long

spawn_key

The position of this sequence in its spawn tree (NumPy's spawn_key tuple): empty for a root, and the parent's key plus the child index for a spawned child. It is mixed in as additional entropy.

public BigInteger[] spawn_key { get; }

Property Value

BigInteger[]

Remarks

Python ints, so BigIntegers: a key element of any size is legal (NumPy coerces a large one into several uint32 words), where a 64-bit type would cap it. A key given to the constructor with string elements or nested sequences is stored as the flat ints NumPy's coercion reads (the same pool, a plainer repr). A copy; changing it changes nothing here.

state

NumPy's SeedSequence.state: the constructor arguments that rebuild this sequence — {'entropy', 'spawn_key', 'pool_size', 'n_children_spawned'}, in NumPy's key order.

public Dictionary<string, object> state { get; }

Property Value

Dictionary<string, object>

Methods

ToString()

NumPy's repr(SeedSequence): the entropy, plus spawn_key / pool_size / n_children_spawned when they differ from their defaults, one per line.

public override string ToString()

Returns

string

E.g. SeedSequence(\n entropy=42,\n).

generate_state(long, DType)

Return the requested number of words for PRNG seeding (NumPy generate_state(n_words, dtype=np.uint32)): a 1-D uint32 (the default) or uint64 NDArray of n_words words — NumPy's ndarray return, not a CLR array.

public NDArray generate_state(long n_words, DType dtype = null)

Parameters

n_words long

The number of words to produce (0 gives an empty result) — a Python int in NumPy, allocated as np.zeros(n_words), so any 64-bit count the allocator accepts.

dtype DType

uint32 (default) or uint64; a uint64 word consumes two uint32 words of the stream.

Returns

NDArray

The seeding words — the same words for the same pool every call (the sequence is not consumed).

Remarks

NumPy fills np.zeros(n_words * (2 if uint64 else 1), uint32) from the hash cycle and views a uint64 request little-endian (astype('<u4').view('<u8')); the uint64 array here is written through the same uint32 words, which on this little-endian runtime ARE that view. The words live in unmanaged storage, so the count is not capped at a managed array's length.

Exceptions

ValueError

n_words is negative (NumPy's np.zeros(n_words) error) or too big to address (array is too big; ...) — for uint64 the DOUBLED count is what NumPy allocates, so one that leaves int64 is Maximum allowed dimension exceeded — or dtype is not the NATIVE uint32/uint64 (NumPy compares with ==, so a byte-swapped '>u4' is rejected too).

MemoryError

A valid count that cannot be allocated (NumPy's MemoryError).

spawn(int)

Spawn n_children child sequences by extending spawn_key (NumPy's SeedSequence.spawn): child i gets this sequence's entropy and pool size and the key spawn_key + (n_children_spawned + i,), and n_children_spawned advances, so later calls continue the numbering and never repeat a child.

public SeedSequence[] spawn(int n_children)

Parameters

n_children int

The number of children (a C# int: the result is an array, which cannot hold more).

Returns

SeedSequence[]

The children (empty for 0).

Remarks

The overflow is refused BEFORE any child is built, which is where NumPy 2.5.4 diverges: its loop counter is a uint32_t compared against a wider bound, so a spawn that would reach 232 children wraps the counter to 0 and never ends — it appends children until MemoryError (probed: both SeedSequence(1, n_children_spawned=232 - 1).spawn(1) and spawn(2**32)). The OverflowError raised here is the one NumPy's n_children_spawned += n_children would raise if its loop terminated; below the limit the children and the advanced count are NumPy's exactly.

Exceptions

ValueError

n_children is negative: NumPy 2.5's n_children must be non-negative, raised before anything changes (NumPy 2.4 ran an empty loop and raised the uint32 OverflowError from its count update).

OverflowError

The child count would leave the uint32 range NumPy stores it in.