genwts.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env python
  2. import numpy as np
  3. import pandas as pd
  4. def voss(nrows, ncols=16):
  5. """Generates pink noise using the Voss-McCartney algorithm.
  6. nrows: number of values to generate
  7. rcols: number of random sources to add
  8. returns: NumPy array
  9. """
  10. array = np.empty((nrows, ncols))
  11. array.fill(np.nan)
  12. array[0, :] = np.random.random(ncols)
  13. array[:, 0] = np.random.random(nrows)
  14. # the total number of changes is nrows
  15. n = nrows
  16. cols = np.random.geometric(0.5, n)
  17. cols[cols >= ncols] = 0
  18. rows = np.random.randint(nrows, size=n)
  19. array[rows, cols] = np.random.random(n)
  20. df = pd.DataFrame(array)
  21. df.fillna(method='ffill', axis=0, inplace=True)
  22. total = df.sum(axis=1)
  23. return total.values
  24. def print_array(ys):
  25. print '{\n%s\n}' % (',\n'.join([ ', '.join([ '0x%02x' % (y,) for y in ys[i:(i+16)] ]) for i in range(0, N, 16) ]),)
  26. N = 512
  27. # Sine
  28. xs = np.linspace(0, 2 * np.pi, N)
  29. ys = np.uint8(np.clip((np.sin(xs) + 1) * 255. / 2, 0, 255))
  30. print_array(ys)
  31. # Square
  32. xs = np.linspace(0, 1, N)
  33. ys = np.uint8([ 0 if x <= 0.5 else 255 for x in xs ])
  34. print_array(ys)
  35. # Triangle
  36. xs = np.linspace(0, 1, N)
  37. ys = (np.array([ 2 * x if x <= 0.5 else 2 - 2 * x for x in xs ]) * 255).astype(np.uint8)
  38. print_array(ys)
  39. # Pink Noise
  40. #fn = 64
  41. #xs = np.linspace(0, 1, N)
  42. #ys = (np.repeat(voss(fn) * 255, len(xs) / fn)).astype(np.uint8)
  43. # White Noise
  44. xs = np.linspace(0, 1, N)
  45. ys = np.random.randint(0, N, len(xs)).astype(np.uint8)
  46. print_array(ys)
  47. import matplotlib.pyplot as plt
  48. plt.plot(xs, ys)
  49. plt.show()