Skip to content

Commit

Permalink
Merge pull request #374 from bashtage/restore-mode
Browse files Browse the repository at this point in the history
Restore mode
  • Loading branch information
bashtage committed Sep 23, 2024
2 parents 434e3da + a4f2509 commit 2f25051
Show file tree
Hide file tree
Showing 38 changed files with 405 additions and 168 deletions.
7 changes: 6 additions & 1 deletion .pep8speaks.yml
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
scanner:
diff_only: False
linter: flake8 # Other option is flake8
linter: pycodestyle # Other option is flake8

pycodestyle: # Same as scanner.linter value. Other option is flake8
max-line-length: 99 # Default is 79 in PEP 8
ignore: # Errors and warnings to ignore
- E203 # Whitespace before ':'
- W503 # Line break occurred before a binary operator (W503)
- E301
- E302
- E305
- E501
- E701

no_blank_comment: False # If True, no comment is made on PR without any errors.
22 changes: 22 additions & 0 deletions randomgen/_deprecated_value.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class _DeprecatedValueType:
"""Special keyword value for deprecated arguments..
The instance of this class may be used as the default value assigned to a
keyword if the parameter is deprecated.
"""

__instance = None

def __new__(cls):
# ensure that only one instance exists
if not cls.__instance:
cls.__instance = super().__new__(cls)
return cls.__instance

def __repr__(self):
return "<deprecated>"


_DeprecatedValue = _DeprecatedValueType()

__all__ = ["_DeprecatedValue"]
2 changes: 1 addition & 1 deletion randomgen/_seed_sequence.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ except ImportError:
randbits = SystemRandom().getrandbits

import numpy as np
cimport numpy as np

cimport numpy as np
from libc.stdint cimport uint32_t

__all__ = ["SeedSequence", "SeedlessSeedSequence", "ISeedSequence",
Expand Down
14 changes: 10 additions & 4 deletions randomgen/aes.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import numpy as np

from randomgen.common cimport *

from randomgen._deprecated_value import _DeprecatedValue

__all__ = ["AESCounter"]

Expand All @@ -17,7 +17,7 @@ cdef double aes_double(void* st) noexcept nogil:

cdef class AESCounter(BitGenerator):
"""
AESCounter(seed=None, *, counter=None, key=None)
AESCounter(seed=None, *, counter=None, key=None, mode=<deprecated>)
Container for the AES Counter pseudo-random number generator.
Expand All @@ -38,6 +38,12 @@ cdef class AESCounter(BitGenerator):
another RNG before use, the value in key is directly set. Can be either
a Python int in [0, 2**128) or a 2-element uint64 array.
key and seed cannot both be used.
mode : {None, "sequence"}
Deprecated parameter. Do not use.
.. deprecated: 2.0.0
Starting in version 2, only seed sequences are supported.
Attributes
----------
Expand Down Expand Up @@ -123,8 +129,8 @@ cdef class AESCounter(BitGenerator):
.. [1] Advanced Encryption Standard. (n.d.). In Wikipedia. Retrieved
June 1, 2019, from https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
"""
def __init__(self, seed=None, *, counter=None, key=None):
BitGenerator.__init__(self, seed)
def __init__(self, seed=None, *, counter=None, key=None, mode=_DeprecatedValue):
BitGenerator.__init__(self, seed, mode=mode)
# Calloc since ctr needs to be 0
self.rng_state = <aesctr_state_t *>PyArray_calloc_aligned(
sizeof(aesctr_state_t), 1
Expand Down
14 changes: 11 additions & 3 deletions randomgen/chacha.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import numpy as np

from randomgen.common cimport *

from randomgen._deprecated_value import _DeprecatedValue

__all__ = ["ChaCha"]

cdef uint64_t chacha_uint64(void* st) noexcept nogil:
Expand All @@ -16,7 +18,7 @@ cdef double chacha_double(void* st) noexcept nogil:

cdef class ChaCha(BitGenerator):
"""
ChaCha(seed=None, *, counter=None, key=None, rounds=20)
ChaCha(seed=None, *, counter=None, key=None, rounds=20, mode=<deprecated>)

Container for the ChaCha family of Counter pseudo-random number generators

Expand All @@ -43,6 +45,12 @@ cdef class ChaCha(BitGenerator):
The standard number of rounds in 20. Smaller values, usually 8 or
more, can be used to reduce security properties of the random stream
while improving performance.
mode : {None, "sequence"}
Deprecated parameter. Do not use.

.. deprecated: 2.0.0

Starting in version 2, only seed sequences are supported.

Attributes
----------
Expand Down Expand Up @@ -127,8 +135,8 @@ cdef class ChaCha(BitGenerator):
.. [1] Bernstein, D. J.. ChaCha, a variant of Salsa20.
http://cr.yp.to/papers.html#chacha. 2008.01.28.
"""
def __init__(self, seed=None, *, counter=None, key=None, rounds=20):
BitGenerator.__init__(self, seed)
def __init__(self, seed=None, *, counter=None, key=None, rounds=20, mode=_DeprecatedValue):
BitGenerator.__init__(self, seed, mode=mode)
self.rng_state = <chacha_state_t *>PyArray_malloc_aligned(
sizeof(chacha_state_t)
)
Expand Down
28 changes: 21 additions & 7 deletions randomgen/common.pyx
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
#!python
import sys
from collections import namedtuple
import sys
import warnings

try:
from threading import Lock
except ImportError:
from dummy_threading import Lock

import numpy as np
from numpy.random.bit_generator cimport BitGenerator as _BitGenerator
from cpython cimport PyFloat_AsDouble

cimport numpy as np
from cpython cimport PyFloat_AsDouble
from numpy.random.bit_generator cimport BitGenerator as _BitGenerator

from randomgen.common cimport *
from randomgen cimport api
from randomgen.common cimport *

from randomgen._deprecated_value import _DeprecatedValue
from randomgen.seed_sequence import ISeedSequence

ISEED_SEQUENCES = (ISeedSequence,)
Expand Down Expand Up @@ -43,14 +48,23 @@ cdef class BitGenerator(_BitGenerator):
"""
Abstract class for all BitGenerators
"""
def __init__(self, seed, mode="sequence"):
if mode is not None and (not isinstance(mode, str) or mode.lower() not in self._supported_modes()):
def __init__(self, seed, *, numpy_seed=False, mode=_DeprecatedValue):
if mode is not _DeprecatedValue:
msg = ("mode is deprecated and will be removed in a future version. "
"Seeding defaults to a numpy.random.SeedSequence instance.")
if "numpy" in self._supported_modes():
msg += " Use numpy_seed=True to enforce numpy-compatible seeding."
warnings.warn(msg, FutureWarning)
if mode is not _DeprecatedValue and (
not isinstance(mode, str) or mode.lower() not in self._supported_modes()
):
if len(self._supported_modes()) == 1:
msg = f"mode must be {self._supported_modes()[0]}"
else:
modes = ", ".join(f"\"{mode}\"" for mode in self._supported_modes())
raise ValueError(f"mode must be one of: {modes}.")
self.mode = mode.lower()
mode = mode.lower() if isinstance(mode, str) else mode
self.mode = "numpy" if (numpy_seed or mode == "numpy") else "sequence"
super().__init__(seed)

def _supported_modes(self):
Expand Down
14 changes: 10 additions & 4 deletions randomgen/dsfmt.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import operator

import numpy as np
cimport numpy as np

from randomgen._deprecated_value import _DeprecatedValue
from randomgen.common cimport *

__all__ = ["DSFMT"]
Expand All @@ -27,7 +27,7 @@ cdef uint64_t dsfmt_raw(void *st) noexcept nogil:

cdef class DSFMT(BitGenerator):
"""
DSFMT(seed=None)
DSFMT(seed=None, *, mode=<deprecated>)

Container for the SIMD-based Mersenne Twister pseudo RNG.

Expand All @@ -40,6 +40,12 @@ cdef class DSFMT(BitGenerator):
``None`` (the default). If `seed` is ``None``, then 764 32-bit unsigned
integers are read from ``/dev/urandom`` (or the Windows analog) if
available. If unavailable, a hash of the time and process ID is used.
mode : {None, "sequence"}
Deprecated parameter. Do not use.

.. deprecated: 2.0.0

Starting in version 2, only seed sequences are supported.

Attributes
----------
Expand Down Expand Up @@ -110,8 +116,8 @@ cdef class DSFMT(BitGenerator):
Sequences and Their Applications - SETA, 290--298, 2008.
"""

def __init__(self, seed=None):
BitGenerator.__init__(self, seed)
def __init__(self, seed=None, *, mode=_DeprecatedValue):
BitGenerator.__init__(self, seed, mode=mode)
self.rng_state.state = <dsfmt_t *>PyArray_malloc_aligned(sizeof(dsfmt_t))
self.rng_state.buffered_uniforms = <double *>PyArray_calloc_aligned(
DSFMT_N64, sizeof(double)
Expand Down
6 changes: 4 additions & 2 deletions randomgen/examples/cython/extending.pyx
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
#cython: language_level=3
from cpython.pycapsule cimport PyCapsule_GetPointer, PyCapsule_IsValid
from libc.stdint cimport uint32_t
from cpython.pycapsule cimport PyCapsule_IsValid, PyCapsule_GetPointer

import numpy as np
cimport numpy as np

cimport cython
cimport numpy as np

from randomgen.common cimport bitgen_t

from randomgen.xoroshiro128 import Xoroshiro128

np.import_array()
Expand Down
7 changes: 5 additions & 2 deletions randomgen/examples/cython/extending_distributions.pyx
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
#cython: language_level=3
import numpy as np
cimport numpy as np

cimport cython
from cpython.pycapsule cimport PyCapsule_IsValid, PyCapsule_GetPointer
cimport numpy as np
from cpython.pycapsule cimport PyCapsule_GetPointer, PyCapsule_IsValid

from randomgen.common cimport *
from randomgen.distributions cimport random_gauss_zig

from randomgen.xoroshiro128 import Xoroshiro128


Expand Down
6 changes: 4 additions & 2 deletions randomgen/examples/cython/low_level.pyx
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
#cython: language_level=3, boundscheck=False, wraparound=False
from cpython.pycapsule cimport PyCapsule_GetPointer, PyCapsule_IsValid
from libc.stdint cimport uint32_t
from cpython.pycapsule cimport PyCapsule_IsValid, PyCapsule_GetPointer

import numpy as np
cimport numpy as np

cimport cython
cimport numpy as np

from randomgen.common cimport bitgen_t, uint64_to_double
from randomgen.xoshiro256 cimport Xoshiro256, xoshiro256_next64

from randomgen.xoshiro256 import Xoshiro256

np.import_array()
Expand Down
42 changes: 29 additions & 13 deletions randomgen/generator.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,41 @@
import warnings

from libc.math cimport sqrt
from libc.stdint cimport (
int64_t,
uint32_t,
uint64_t,
)
from libc.stdint cimport int64_t, uint32_t, uint64_t

import numpy as np

cimport numpy as np

from randomgen.pcg64 import PCG64
from cpython.pycapsule cimport PyCapsule_IsValid, PyCapsule_GetPointer
from cpython cimport (PyComplex_FromDoubles,
PyComplex_ImagAsDouble, PyComplex_RealAsDouble,
)

from randomgen cimport api
from cpython cimport (
PyComplex_FromDoubles,
PyComplex_ImagAsDouble,
PyComplex_RealAsDouble,
)
from cpython.pycapsule cimport PyCapsule_GetPointer, PyCapsule_IsValid
from numpy.random cimport bitgen_t
from numpy.random.c_distributions cimport random_standard_normal, random_standard_normal_fill
from randomgen.distributions cimport random_double_fill, random_float, random_long_double_size, random_long_double_fill, random_wishart_large_df
from randomgen.common cimport double_fill, float_fill, check_output, compute_complex, validate_output_shape
from numpy.random.c_distributions cimport (
random_standard_normal,
random_standard_normal_fill,
)

from randomgen cimport api
from randomgen.common cimport (
check_output,
compute_complex,
double_fill,
float_fill,
validate_output_shape,
)
from randomgen.distributions cimport (
random_double_fill,
random_float,
random_long_double_fill,
random_long_double_size,
random_wishart_large_df,
)

__all__ = ["ExtendedGenerator"]

Expand Down
13 changes: 10 additions & 3 deletions randomgen/hc128.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import numpy as np
cimport numpy as np

from randomgen.common cimport *
from randomgen._deprecated_value import _DeprecatedValue

__all__ = ["HC128"]

Expand All @@ -19,7 +20,7 @@ cdef double hc128_double(void* st) noexcept nogil:

cdef class HC128(BitGenerator):
"""
HC128(seed=None, *, key=None)
HC128(seed=None, *, key=None, mode=<deprecated>)

Container for the HC-128 cipher-based pseudo-random number generator

Expand All @@ -36,6 +37,12 @@ cdef class HC128(BitGenerator):
Key for HC128. The key is a 256-bit integer that contains both the
key (lower 128 bits) and initial values (upper 128-bits) for the
HC-128 cipher. key and seed cannot both be used.
mode : {None, "sequence"}
Deprecated parameter. Do not use.

.. deprecated: 2.0.0

Starting in version 2, only seed sequences are supported.

Attributes
----------
Expand Down Expand Up @@ -106,8 +113,8 @@ cdef class HC128(BitGenerator):
.. [2] Wu, Hongjun, "Stream Ciphers HC-128 and HC-256".
https://www.ntu.edu.sg/home/wuhj/research/hc/index.html)
"""
def __init__(self, seed=None, *, key=None):
BitGenerator.__init__(self, seed)
def __init__(self, seed=None, *, key=None, mode=_DeprecatedValue):
BitGenerator.__init__(self, seed, mode=mode)
self.seed(seed, key)

self._bitgen.state = <void *>&self.rng_state
Expand Down
Loading

0 comments on commit 2f25051

Please sign in to comment.