extending.py 880 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. """
  2. Use cffi to access any of the underlying C functions from distributions.h
  3. """
  4. import os
  5. import numpy as np
  6. import cffi
  7. from .parse import parse_distributions_h
  8. ffi = cffi.FFI()
  9. inc_dir = os.path.join(np.get_include(), 'numpy')
  10. # Basic numpy types
  11. ffi.cdef('''
  12. typedef intptr_t npy_intp;
  13. typedef unsigned char npy_bool;
  14. ''')
  15. parse_distributions_h(ffi, inc_dir)
  16. lib = ffi.dlopen(np.random._generator.__file__)
  17. # Compare the distributions.h random_standard_normal_fill to
  18. # Generator.standard_random
  19. bit_gen = np.random.PCG64()
  20. rng = np.random.Generator(bit_gen)
  21. state = bit_gen.state
  22. interface = rng.bit_generator.cffi
  23. n = 100
  24. vals_cffi = ffi.new('double[%d]' % n)
  25. lib.random_standard_normal_fill(interface.bit_generator, n, vals_cffi)
  26. # reset the state
  27. bit_gen.state = state
  28. vals = rng.standard_normal(n)
  29. for i in range(n):
  30. assert vals[i] == vals_cffi[i]