extending_distributions.pyx 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #!/usr/bin/env python3
  2. #cython: language_level=3
  3. """
  4. This file shows how the to use a BitGenerator to create a distribution.
  5. """
  6. import numpy as np
  7. cimport numpy as np
  8. cimport cython
  9. from cpython.pycapsule cimport PyCapsule_IsValid, PyCapsule_GetPointer
  10. from libc.stdint cimport uint16_t, uint64_t
  11. from numpy.random cimport bitgen_t
  12. from numpy.random import PCG64
  13. from numpy.random.c_distributions cimport (
  14. random_standard_uniform_fill, random_standard_uniform_fill_f)
  15. @cython.boundscheck(False)
  16. @cython.wraparound(False)
  17. def uniforms(Py_ssize_t n):
  18. """
  19. Create an array of `n` uniformly distributed doubles.
  20. A 'real' distribution would want to process the values into
  21. some non-uniform distribution
  22. """
  23. cdef Py_ssize_t i
  24. cdef bitgen_t *rng
  25. cdef const char *capsule_name = "BitGenerator"
  26. cdef double[::1] random_values
  27. x = PCG64()
  28. capsule = x.capsule
  29. # Optional check that the capsule if from a BitGenerator
  30. if not PyCapsule_IsValid(capsule, capsule_name):
  31. raise ValueError("Invalid pointer to anon_func_state")
  32. # Cast the pointer
  33. rng = <bitgen_t *> PyCapsule_GetPointer(capsule, capsule_name)
  34. random_values = np.empty(n, dtype='float64')
  35. with x.lock, nogil:
  36. for i in range(n):
  37. # Call the function
  38. random_values[i] = rng.next_double(rng.state)
  39. randoms = np.asarray(random_values)
  40. return randoms
  41. # cython example 2
  42. @cython.boundscheck(False)
  43. @cython.wraparound(False)
  44. def uint10_uniforms(Py_ssize_t n):
  45. """Uniform 10 bit integers stored as 16-bit unsigned integers"""
  46. cdef Py_ssize_t i
  47. cdef bitgen_t *rng
  48. cdef const char *capsule_name = "BitGenerator"
  49. cdef uint16_t[::1] random_values
  50. cdef int bits_remaining
  51. cdef int width = 10
  52. cdef uint64_t buff, mask = 0x3FF
  53. x = PCG64()
  54. capsule = x.capsule
  55. if not PyCapsule_IsValid(capsule, capsule_name):
  56. raise ValueError("Invalid pointer to anon_func_state")
  57. rng = <bitgen_t *> PyCapsule_GetPointer(capsule, capsule_name)
  58. random_values = np.empty(n, dtype='uint16')
  59. # Best practice is to release GIL and acquire the lock
  60. bits_remaining = 0
  61. with x.lock, nogil:
  62. for i in range(n):
  63. if bits_remaining < width:
  64. buff = rng.next_uint64(rng.state)
  65. random_values[i] = buff & mask
  66. buff >>= width
  67. randoms = np.asarray(random_values)
  68. return randoms
  69. # cython example 3
  70. def uniforms_ex(bit_generator, Py_ssize_t n, dtype=np.float64):
  71. """
  72. Create an array of `n` uniformly distributed doubles via a "fill" function.
  73. A 'real' distribution would want to process the values into
  74. some non-uniform distribution
  75. Parameters
  76. ----------
  77. bit_generator: BitGenerator instance
  78. n: int
  79. Output vector length
  80. dtype: {str, dtype}, optional
  81. Desired dtype, either 'd' (or 'float64') or 'f' (or 'float32'). The
  82. default dtype value is 'd'
  83. """
  84. cdef Py_ssize_t i
  85. cdef bitgen_t *rng
  86. cdef const char *capsule_name = "BitGenerator"
  87. cdef np.ndarray randoms
  88. capsule = bit_generator.capsule
  89. # Optional check that the capsule if from a BitGenerator
  90. if not PyCapsule_IsValid(capsule, capsule_name):
  91. raise ValueError("Invalid pointer to anon_func_state")
  92. # Cast the pointer
  93. rng = <bitgen_t *> PyCapsule_GetPointer(capsule, capsule_name)
  94. _dtype = np.dtype(dtype)
  95. randoms = np.empty(n, dtype=_dtype)
  96. if _dtype == np.float32:
  97. with bit_generator.lock:
  98. random_standard_uniform_fill_f(rng, n, <float*>np.PyArray_DATA(randoms))
  99. elif _dtype == np.float64:
  100. with bit_generator.lock:
  101. random_standard_uniform_fill(rng, n, <double*>np.PyArray_DATA(randoms))
  102. else:
  103. raise TypeError('Unsupported dtype %r for random' % _dtype)
  104. return randoms