123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- #!/usr/bin/env python
- import numpy as np
- import pandas as pd
- def voss(nrows, ncols=16):
- """Generates pink noise using the Voss-McCartney algorithm.
- nrows: number of values to generate
- rcols: number of random sources to add
- returns: NumPy array
- """
- array = np.empty((nrows, ncols))
- array.fill(np.nan)
- array[0, :] = np.random.random(ncols)
- array[:, 0] = np.random.random(nrows)
- # the total number of changes is nrows
- n = nrows
- cols = np.random.geometric(0.5, n)
- cols[cols >= ncols] = 0
- rows = np.random.randint(nrows, size=n)
- array[rows, cols] = np.random.random(n)
- df = pd.DataFrame(array)
- df.fillna(method='ffill', axis=0, inplace=True)
- total = df.sum(axis=1)
- return total.values
- def print_array(ys):
- print '{\n%s\n}' % (',\n'.join([ ', '.join([ '0x%02x' % (y,) for y in ys[i:(i+16)] ]) for i in range(0, N, 16) ]),)
- N = 512
- # Sine
- xs = np.linspace(0, 2 * np.pi, N)
- ys = np.uint8(np.clip((np.sin(xs) + 1) * 255. / 2, 0, 255))
- print_array(ys)
- # Square
- xs = np.linspace(0, 1, N)
- ys = np.uint8([ 0 if x <= 0.5 else 255 for x in xs ])
- print_array(ys)
- # Triangle
- xs = np.linspace(0, 1, N)
- ys = (np.array([ 2 * x if x <= 0.5 else 2 - 2 * x for x in xs ]) * 255).astype(np.uint8)
- print_array(ys)
- # Pink Noise
- #fn = 64
- #xs = np.linspace(0, 1, N)
- #ys = (np.repeat(voss(fn) * 255, len(xs) / fn)).astype(np.uint8)
- # White Noise
- xs = np.linspace(0, 1, N)
- ys = np.random.randint(0, N, len(xs)).astype(np.uint8)
- print_array(ys)
- import matplotlib.pyplot as plt
- plt.plot(xs, ys)
- plt.show()
|