def test_fixed_diff(): a = np.random.randn(2, 3, 4) da = fixed_diff(a, axis=1, initial_value=0) assert np.array_equal(da[:, 1:, :], np.diff(a, axis=1)) assert np.array_equal(da[:, 0, :], a[:, 0, :]) da = fixed_diff(a, axis=1, initial_value='first') assert np.array_equal(da[:, 1:, :], np.diff(a, axis=1)) assert np.array_equal(da[:, 0, :], np.zeros_like(da[:, 0, :])) assert np.allclose(a, np.cumsum(fixed_diff(a, axis=1), axis=1))
def sequential_quantize(v, n_steps = None, method='herd', rng = None): """ :param v: A (..., n_samples, n_units, ) array :param n_steps: The number of steps to spike for :return: An (..., n_steps, n_units) array of quantized values """ rng = get_rng(rng) assert v.ndim>=2 if n_steps is None: n_steps = v.shape[-2] else: assert n_steps == v.shape[-2] if method=='herd': result = fixed_diff(np.round(np.cumsum(v, axis=-2)), axis=-2) elif method=='herd2': result = fixed_diff(fixed_diff(np.round(np.cumsum(np.cumsum(v, axis=-2), axis=-2)), axis=-2), axis=-2) elif method=='round': result = np.round(v) elif method == 'slippery.9': result = slippery_round(v, slip=0.9) elif method == 'slippery.5': result = slippery_round(v, slip=0.5) elif method == 'randn': result = v + rng.randn(*v.shape) elif method=='uniform': result = v + rng.uniform(-.5, .5, size=v.shape) elif method=='surrogate-noise': result = v + (12**.5)*((v%1)-(v%1)**2)*rng.uniform(low=-.5, high=.5, size=v.shape) elif method == 'surrogate-sqrt': result = v + np.sqrt((12**.5)*((v%1)-(v%1)**2)*rng.uniform(low=-.5, high=.5, size=v.shape)) elif method is None: result = v else: raise NotImplementedError("Don't have quantization method '%s' implemented" % (method, )) return result