def test_add(): assert np.allclose((stimulus([2, 3, 4]) + 1).run(1, 1).squeeze(axis=(0, )), [3, 4, 5]) assert np.allclose( ([2, 3, 4] + stimulus([1, 2, 3])).run(1, 1).squeeze(axis=(0, )), [3, 5, 7]) a = stimulus(1) assert a + 0 is 0 + a is a
def test_foldable(): valid = (stimulus(1), stimulus(2)) assert Fold.is_foldable(valid) invalid = Fold(valid) assert not Fold.is_foldable(invalid) with pytest.raises(TypeError, match="and not be a Fold"): Fold(invalid)
def test_multiply_invalid(): a = stimulus(np.zeros(2)) b = stimulus(np.zeros(3)) with pytest.raises(ValueError, match="multiply operator size_out"): a * b with pytest.raises(TypeError, match="multiply size mismatch"): a * [0, 1, 2] with pytest.raises(TypeError, match="all returned NotImplemented"): a * np.eye(2)
def test_broadcast_scalar(): stim = fold([ [stimulus(np.zeros(2)), stimulus(np.zeros(3))], [stimulus(np.zeros(4)), stimulus(np.zeros(1))], ]) assert np.all(stim.size_out == [[2, 3], [4, 1]]) (a11, a12), (a21, a22) = broadcast_scalar(2, stim.size_out).run(1, 1) assert np.all(a11 == [[2, 2]]) assert np.all(a12 == [[2, 2, 2]]) assert np.all(a21 == [[2, 2, 2, 2]]) assert np.all(a22 == [[2]]) with pytest.raises(TypeError, match="expected scalar, but got array"): broadcast_scalar(np.eye(3), size_out=(3, 3, 3))
def test_convolve_direct(rng): dims = 64 a = rng.randn(dims) b = rng.randn(dims) input_a = stimulus(a).configure(neuron_type=nengo.Direct()) input_b = stimulus(b) y = convolve(input_a, input_b) assert y.size_out == dims out = y.run(1, 1).squeeze(axis=0) assert out.shape == (dims, ) assert np.allclose(out, _numpy_convolve(a, b))
def test_vectorize_kwargs(): @vectorize("F") def f(node_a, node_b, *, tr=1): """f docstring""" assert node_a.size_out == node_b.size_out out = nengo.Node(size_in=node_a.size_out) nengo.Connection(node_a, out, transform=tr, synapse=None) nengo.Connection(node_b, out, transform=tr, synapse=None) return out op = f(stimulus(1), node_b=stimulus(2), tr=3) assert type(op).__name__ == "F" assert type(op).__doc__ == "f docstring" assert op.run(1, 1).squeeze(axis=1) == 9
def test_integrate_synapse(): synapse = 0.1 stim = stimulus(0.5) x1 = stim.integrate(synapse=synapse) x2 = stim.filter(synapse=synapse) assert np.allclose(x1.run(1), x2.run(1))
def test_elementwise_multiply(): d = 64 a = np.linspace(-1, 1, d) b = a**2 op_a = stimulus(a) assert op_a.size_out == d ab = op_a * b assert ab.size_out == d y = np.asarray(ab.run(1, 1)).squeeze(axis=0) assert y.shape == (d, ) a2ab = fold([op_a, 2 * op_a]).transform(b) y2 = np.asarray(a2ab.run(1, 1)).squeeze(axis=1) assert np.allclose(y2[0], y) assert np.allclose(y2[1], 2 * y2[0]) y3 = np.asarray((b * op_a).run(1, 1)).squeeze(axis=0) assert np.allclose(y3, y) y_check = a**3 assert np.allclose(y, y_check) # Test multiplying vector with a scalar constant. a10 = np.asarray((op_a * 10).run(1, 1)).squeeze(axis=0) assert np.allclose(a10, a * 10)
def test_lower_folds(): @lower_folds def f(a, b=0): assert not isinstance(a, Fold) assert not isinstance(b, Fold) return a f(stimuli(np.ones((3, 1)))) f(stimulus(0), b=stimuli(np.ones((3, 1))))
def test_transform_invalid(): with pytest.raises(TypeError, match="must be a Fold"): Transforms(stimulus(0), [1]) with pytest.raises( ValueError, match= r"input operators \(2\) must equal the number of transforms \(3\)", ): Transforms(stimuli([2, 2]), np.ones(3)) with pytest.raises(ValueError, match="expected a Fold with only a single axis"): Transforms(stimuli(np.eye(2)), np.ones(2)) with pytest.raises(ValueError, match="input_ops must have all the same size"): Transforms(fold([stimulus(1), stimulus([1, 1])]), np.ones(2))
def test_integrand_invalid(): u = stimulus(0) with pytest.raises(TypeError, match="expected integrand to generate a single Node"): u.integrate(integrand=lambda x: fold([x, x])) with pytest.raises(TypeError, match="integrand returned Node with size_out=2"): u.integrate(integrand=lambda x: fold([x, x]).bundle())
def test_scalar_input_op_attributes(): stim = stimulus(np.ones(3)) op = stim.decode() assert op.input_ops == (stim, ) assert op.ndim == 0 assert op.shape == () assert op.size_out == 3 assert str(op) == "Decode(Stimulus())" assert repr(op) == "Decode([Stimulus([])])"
def test_transform_associativity(): a = stimulus(1) b = stimulus(2) c = stimulus(3) out = 2 * (3 * a + 4 * (b + 5 * c)) # == 6 * a + 8 * b + 40 * c with nengo.Network() as model: p = nengo.Probe(out.make()) with nengo.Simulator(model) as sim: sim.step() assert sim.data[p].squeeze(axis=-1) == 6 * 1 + 8 * 2 + 40 * 3 transforms = [] for conn in model.all_connections: if conn.transform is not nengo.params.Default: transforms.append(conn.transform.init) assert np.all(transforms == [6, 8, 40])
def test_add_invalid(): a = stimulus(np.ones(2)) with pytest.raises(TypeError, match="add size mismatch"): a + [0, 1, 2] with pytest.raises(TypeError, match="all returned NotImplemented"): a + np.eye(2) with pytest.raises(TypeError, match="all returned NotImplemented"): a + "b"
def test_str(): assert str(stimuli(np.ones((1, 2)))) == "Fold(Fold(Stimuli(), Stimuli()))" assert str(stimuli(np.ones((1, 1, 1)))) == "Fold(Fold(Fold(Stimuli())))" assert str(stimuli(np.ones( (1, 1, 2)))) == "Fold(Fold(Fold(Stimuli(), Stimuli())))" assert str(stimuli(np.ones((1, 1, 1, 1)))) == "Fold(Fold(Fold(Fold(...))))" assert (stimuli(np.ones(3)).bundle().__str__( max_width=2) == "Bundle1D(Stimuli(), Stimuli(), ...)") assert (stimulus(np.ones(2)).unbundle().__str__( max_depth=2, max_width=2) == "Fold(Slice(...), Slice(...))")
def test_tensornode(): nengo_dl = pytest.importorskip("nengo_dl") import tensorflow as tf # required by nengo_dl u = np.linspace(-1, 1, 1000) x = stimulus(u) y = x.tensor_node(tf.exp, pass_time=False) with tf.device("/cpu:0"): out = y.run(1, 1, simulator=nengo_dl.Simulator) assert np.allclose(out.squeeze(axis=0), np.exp(u))
def test_layer(): nengo_dl = pytest.importorskip("nengo_dl") import tensorflow as tf # required by nengo_dl u = np.linspace(-1, 1, 1000) x = stimulus(u) y = x.layer(tf.exp, shape_in=u.shape) with tf.device("/cpu:0"): out = y.run(1, 1, simulator=nengo_dl.Simulator) assert np.allclose(out.squeeze(axis=0), np.exp(u))
def test_make_cache_basic(): a = stimulus(0.5) b = a + a.filter(0.1)**2 - (0.5 * a)**3 with nengo.Network() as model: b.make() roots = [] for node in model.all_nodes: if node.size_in == 0: roots.append(node) # a should only be made once assert len(roots) == 1 and roots[0].output == 0.5
def test_neurons(): a = stimulus(1).configure(seed=0) tr = nengo.dists.Uniform(-1, 1) x = a.neurons(transform=tr) y = x.run(1) with nengo.Network() as model: stim = nengo.Node(1) ens = nengo.Ensemble(100, 1, seed=0) nengo.Connection(stim, ens.neurons, transform=tr, seed=0, synapse=None) p = nengo.Probe(ens.neurons) with nengo.Simulator(model) as sim: sim.run(1) assert np.allclose(y, sim.data[p])
def test_lti_invalid(): u = stimulus(np.ones(3)) A = -np.eye(2) B = np.ones((2, 3)) x = u.lti(system=(A, B)) with pytest.raises(ValueError, match="must be a square matrix"): u.lti(system=(B, B)) with pytest.raises(ValueError, match="must be 1D or 2D"): u.lti(system=(A, 0)) with pytest.raises(ValueError, match="must be an array of length 2"): u.lti(system=(A, B.T)) with pytest.raises(ValueError, match="to have size_in=3, not size_in=2"): u.lti(system=(A, A))
def test_multiply_fold_op(rng): a = rng.randn(4, 3) b = rng.randn(1) op_a = stimuli(a).configure(neuron_type=nengo.Direct()) op_b = stimulus(b) assert isinstance(op_a, Fold) assert not isinstance(op_b, Fold) y1 = op_a * op_b out1 = np.asarray(y1.run(1, 1)).squeeze(axis=(-2, -1)) y2 = op_b * op_a out2 = np.asarray(y2.run(1, 1)).squeeze(axis=(-2, -1)) assert np.allclose(a * b, out1) assert np.allclose(a * b, out2)
def test_add_fold_op(rng): a = rng.randn(4, 3) b = rng.randn(1) op_a = stimuli(a) op_b = stimulus(b) assert isinstance(op_a, Fold) assert not isinstance(op_b, Fold) y1 = op_a + op_b out1 = np.asarray(y1.run(1, 1)).squeeze(axis=(-2, -1)) y2 = op_b + op_a out2 = np.asarray(y2.run(1, 1)).squeeze(axis=(-2, -1)) assert np.allclose(a + b, out1) assert np.allclose(a + b, out2)
def test_convolution(): shape = (3, 3, 2, 4) tr = nengo.Convolution( n_filters=4, input_shape=(5, 5, 2), init=np.arange(np.prod(shape)).reshape(shape), ) inp = np.arange(tr.size_in) stim = stimulus(inp) out = stim.transform(tr).run(1, 1) with nengo.Network() as model: stim = nengo.Node(output=inp) x = nengo.Node(size_in=tr.size_out) nengo.Connection(stim, x, transform=tr, synapse=None) p = nengo.Probe(x) with nengo.Simulator(model) as sim: sim.step() assert np.allclose(sim.data[p], out)
def test_missing_ufunc(): op = stimulus(6) with pytest.raises(TypeError, match="all returned NotImplemented"): np.gcd(op, 9)
def test_run_context(): a = stimulus(0) with nengo.Network() as model: with pytest.raises(RuntimeError, match="run method is not meant to be"): a.run(1)
def test_rpow(): a = stimulus(0) with pytest.raises(TypeError, match="all returned NotImplemented"): 2**a
def test_rtruediv(): a = stimulus(0) with pytest.raises(TypeError, match="all returned NotImplemented"): 1 / a
def test_label(): assert stimulus(1).label == "Stimulus()" assert (2 * (stimuli(np.ones(2)) * stimuli(np.ones(2))) ).label == "Fold(Transforms(...), ...)" assert stimuli(1).integrate().label == "Integrate(Stimuli())"
def test_convolve_invalid(): a = stimulus(np.zeros(2)) b = stimulus(np.zeros(3)) with pytest.raises(ValueError, match="convolve operator size_out"): a.convolve(b)
def subnetwork(x): return (stimulus(x)**2).filter(synapse=0.005)