Exemple #1
0
def test_contains():
    class A:
        pass

    cfg = nengo.Config(A)
    with pytest.raises(TypeError):
        A in cfg
Exemple #2
0
def test_instance_fallthrough():
    """If the class default is set, instances should use that."""

    class A:
        pass

    inst1 = A()
    inst2 = A()
    config = nengo.Config(A)
    config[A].set_param("amount", Parameter("amount", default=1))
    assert config[A].amount == 1
    assert config[inst1].amount == 1
    assert config[inst2].amount == 1
    # Value can change for instance
    config[inst1].amount = 2
    assert config[A].amount == 1
    assert config[inst1].amount == 2
    assert config[inst2].amount == 1
    # If value to A is changed, unset instances should also change
    config[A].amount = 3
    assert config[A].amount == 3
    assert config[inst1].amount == 2
    assert config[inst2].amount == 3
    # If class default is deleted, unset instances go back
    del config[A].amount
    assert config[A].amount == 1
    assert config[inst1].amount == 2
    assert config[inst2].amount == 1
Exemple #3
0
def test_direct_mode_with_single_neuron(Simulator, plt, seed):
    radius = 2
    dim = 5

    config = nengo.Config(nengo.Ensemble)
    config[nengo.Ensemble].neuron_type = nengo.Direct()
    with config:
        product = nengo_extras.networks.Product(
            1, dim, radius, net=nengo.Network(seed=seed))

    func_A = lambda t: np.sqrt(radius)*np.sin(np.arange(1, dim+1)*2*np.pi*t)
    func_B = lambda t: np.sqrt(radius)*np.sin(np.arange(dim, 0, -1)*2*np.pi*t)
    with product:
        input_A = nengo.Node(func_A)
        input_B = nengo.Node(func_B)
        nengo.Connection(input_A, product.A)
        nengo.Connection(input_B, product.B)
        p = nengo.Probe(product.output, synapse=0.005)

    with Simulator(product) as sim:
        sim.run(1.0)

    t = sim.trange()
    AB = np.asarray(list(map(func_A, t))) * np.asarray(list(map(func_B, t)))
    delay = 0.013
    offset = np.where(t >= delay)[0]

    for i in range(dim):
        plt.subplot(dim+1, 1, i+1)
        plt.plot(t + delay, AB[:, i])
        plt.plot(t, sim.data[p][:, i])
        plt.xlim(right=t[-1])
        plt.yticks((-2, 0, 2))

    assert rmse(AB[:len(offset), :], sim.data[p][offset, :]) < 0.2
Exemple #4
0
    def __init__(self, vocab=Default, neurons_per_dimension=Default, **kwargs):
        super(Compare, self).__init__(**kwargs)

        self.vocab = vocab
        self.neurons_per_dimension = neurons_per_dimension

        with self:
            with nengo.Config(nengo.Ensemble) as cfg:
                cfg[nengo.Ensemble].eval_points = nengo.dists.CosineSimilarity(
                    self.vocab.dimensions + 2)
                cfg[nengo.Ensemble].intercepts = nengo.dists.CosineSimilarity(
                    self.vocab.dimensions + 2)
                self.product = nengo.networks.Product(
                    self.neurons_per_dimension, self.vocab.dimensions)
            self.output = nengo.Node(size_in=1, label="output")
            nengo.Connection(
                self.product.output,
                self.output,
                transform=np.ones((1, self.vocab.dimensions)),
            )

        self.input_a = self.product.input_a
        self.input_b = self.product.input_b

        self.declare_input(self.input_a, self.vocab)
        self.declare_input(self.input_b, self.vocab)
        self.declare_output(self.output, None)
Exemple #5
0
def Product_2D_ens(n_neurons,
                   dimensions,
                   input_magnitude=1,
                   config=None,
                   net=None):
    """Computes the element-wise product of two equally sized vectors."""
    if net is None:
        net = nengo.Network(label="Product")

    if config is None:
        config = nengo.Config(nengo.Ensemble)
        config[nengo.Ensemble].encoders = Choice([[1, 1], [1, -1], [-1, 1],
                                                  [-1, -1]])

    with net, config:
        net.A = nengo.Node(size_in=dimensions, label="A")
        net.B = nengo.Node(size_in=dimensions, label="B")
        net.output = nengo.Node(size_in=dimensions, label="output")

        net.product = EnsembleArray(n_neurons,
                                    n_ensembles=dimensions,
                                    ens_dimensions=2,
                                    radius=input_magnitude * np.sqrt(2))
        nengo.Connection(net.A, net.product.input[::2], synapse=None)
        nengo.Connection(net.B, net.product.input[1::2], synapse=None)
        net.output = net.product.add_output('product', lambda x: x[0] * x[1])
    return net
def test_matrix_mult(Simulator, rng, nl, plt):
    shape_left = (2, 2)
    shape_right = (2, 2)

    left_mat = rng.rand(*shape_left)
    right_mat = rng.rand(*shape_right)

    with nengo.Network("Matrix multiplication test") as model:
        node_left = nengo.Node(left_mat.ravel())
        node_right = nengo.Node(right_mat.ravel())

        with nengo.Config(nengo.Ensemble) as cfg:
            cfg[nengo.Ensemble].neuron_type = nl()
            mult_net = nengo_extras.networks.MatrixMult(
                100, shape_left, shape_right)

        p = nengo.Probe(mult_net.output, synapse=0.01)

        nengo.Connection(node_left, mult_net.input_left)
        nengo.Connection(node_right, mult_net.input_right)

    dt = 0.001
    sim = Simulator(model, dt=dt)
    sim.run(1)

    t = sim.trange()
    plt.plot(t, sim.data[p])
    for d in np.dot(left_mat, right_mat).flatten():
        plt.axhline(d, color='k')

    atol, rtol = .2, .01
    ideal = np.dot(left_mat, right_mat).ravel()
    assert np.allclose(sim.data[p][-1], ideal, atol=atol, rtol=rtol)
Exemple #7
0
def test_matrix_mult(Simulator, seed, rng, AnyNeuronType, plt, allclose):
    shape_left = (2, 2)
    shape_right = (2, 2)

    left_mat = rng.uniform(-1, 1, size=shape_left)
    right_mat = rng.uniform(-1, 1, size=shape_right)

    with nengo.Network("Matrix multiplication test", seed=seed) as model:
        node_left = nengo.Node(left_mat.ravel())
        node_right = nengo.Node(right_mat.ravel())

        with nengo.Config(nengo.Ensemble) as cfg:
            cfg[nengo.Ensemble].neuron_type = AnyNeuronType()
            mult_net = nengo_extras.networks.MatrixMult(
                200, shape_left, shape_right)

        p = nengo.Probe(mult_net.output, synapse=0.01)

        nengo.Connection(node_left, mult_net.input_left)
        nengo.Connection(node_right, mult_net.input_right)

    dt = 0.001
    with Simulator(model, dt=dt) as sim:
        sim.run(1)

    t = sim.trange()
    plt.plot(t, sim.data[p])
    for d in np.dot(left_mat, right_mat).flatten():
        plt.axhline(d, color="k")

    atol, rtol = 0.15, 0.01
    if AnyNeuronType.__name__ == "SpikingTanh":
        atol = 0.2
    ideal = np.dot(left_mat, right_mat).ravel()
    assert allclose(sim.data[p][-1], ideal, atol=atol, rtol=rtol)
Exemple #8
0
def config_with_default_synapse(config, synapse):
    if config is None:
        config = nengo.Config(nengo.Connection)
        config[nengo.Connection].synapse = synapse
    override = "synapse" not in config[nengo.Connection]
    if override:
        config[nengo.Connection].synapse = synapse
    return config, override
Exemple #9
0
 def __init__(self):
     self.config = nengo.Config(nengo.Ensemble, nengo.Connection,
                                nengo.Probe)
     self.mfcc = MFCCParams()
     self.periphery = PeripheryParams()
     self.cepstra = CepstraParams()
     self.derivatives = []
     # Set dummy audio so that pickling doesn't fail
     self.audio = np.zeros(1)
Exemple #10
0
def generate(net=None, n_neurons=200, alpha=1000.0, beta=1000.0/4.0,
             dt=0.001, analog=False):
    tau = 0.1  # synaptic time constant
    synapse = nengo.Lowpass(tau)

    # the A matrix for our point attractor
    A = np.array([[0.0, 1.0],
                  [-alpha*beta, -alpha]])

    # the B matrix for our point attractor
    B = np.array([[0.0], [alpha*beta]])

    # if you have the nengolib library you can do it this way
    # from nengolib.synapses import ss2sim
    # C = np.eye(2)
    # D = np.zeros((2, 2))
    # linsys = ss2sim((A, B, C, D), synapse=synapse, dt=None if analog else dt)
    # A = linsys.A
    # B = linsys.B

    if analog:
        # account for continuous lowpass filter
        A = tau * A + np.eye(2)
        B = tau * B
    else:
        # discretize state matrices
        Ad = expm(A*dt)
        Bd = np.dot(np.linalg.inv(A), np.dot((Ad - np.eye(2)), B))
        # account for discrete lowpass filter
        a = np.exp(-dt/tau)
        A = 1.0 / (1.0 - a) * (Ad - a * np.eye(2))
        B = 1.0 / (1.0 - a) * Bd

    if net is None:
        net = nengo.Network(label='Point Attractor')
    config = nengo.Config(nengo.Connection, nengo.Ensemble)
    config[nengo.Connection].synapse = nengo.Lowpass(tau)

    with config, net:
        net.ydy = nengo.Ensemble(n_neurons=n_neurons, dimensions=2,
            # set it up so neurons are tuned to one dimensions only
            encoders=nengo.dists.Choice([[1, 0], [-1, 0], [0, 1], [0, -1]]))
        # set up Ax part of point attractor
        nengo.Connection(net.ydy, net.ydy, transform=A)

        # hook up input
        net.input = nengo.Node(size_in=1, size_out=1)
        # set up Bu part of point attractor
        nengo.Connection(net.input, net.ydy, transform=B)

        # hook up output
        net.output = nengo.Node(size_in=1, size_out=1)
        # add in forcing function
        nengo.Connection(net.ydy[0], net.output, synapse=None)

    return net
Exemple #11
0
 def __init__(self):
     self.config = nengo.Config(nengo.Ensemble, nengo.Connection,
                                nengo.Probe)
     self.syllable = RecogSyllableParams()
     self.syllables = []
     self.syllable_dict = {}
     self.cleanup = CleanupParams()
     self.memory = MemoryParams()
     self.classifier = ClassifierParams()
     self.trial = RecognitionTrialParams()
Exemple #12
0
 def __init__(self):
     self.config = nengo.Config(nengo.Ensemble, nengo.Connection,
                                nengo.Probe)
     self.sequence = SyllableSequenceParams()
     self.sequencer = SequencerParams()
     self.syllable = ProdSyllableParams()
     self.syllables = []
     self.syllable_dict = {}
     self.production_info = ProductionInfoParams()
     self.trial = ProductionTrialParams()
Exemple #13
0
 def thresh_ens_config(self):
     cfg = nengo.Config(nengo.Ensemble)
     cfg[nengo.Ensemble].update({
         'radius': 1,
         'intercepts': Uniform(0.5, 1.0),
         'encoders': Choice([[1]]),
         'eval_points': Uniform(0.75, 1.1),
         'n_eval_points': self.n_eval_points,
     })
     return cfg
Exemple #14
0
    def __init__( self, seed=1, label="KerNengo", cats=None ):
        """
        build the nengo network
        there will be as many input and Keras node objects as the categories to be searched
        in the image. The categories can be given in a list as cats argoments, otherwise the
        global categories is used
        """
        self.probes = {}
        self.nodes  = {}
        self.states = {}
        self.prob   = {}
        self.v_dim  = list(lg.n_coords.values())[ 0 ][ 0 ]
        self.voc    = spa.Vocabulary( self.v_dim )
        self.dl     = nengo.Network( seed=seed, label='DL'+label )
        self.spa    = spa.Network( seed=seed+1, label='SPA'+label )

        if cats is None:
            self.categories = lg.categories
        else:
            self.categories = cats

        # initialize probabilities
        for c in self.categories:
            self.prob[ c ]  = numpy.zeros( ( self.v_dim, ) )

        """
        this is the part intended for using a vocabolary, but I have found no ways to use it
        (see NOTE in state())
        n_cat       = len( self.categories )
        parse_str   = (n_cat - 1 ) * "WHERE{}; " + "WHERE{}" 
        spointers   = parse_str.format( *self.categories )
        self.voc.populate( spointers )
        """

        with self.dl:
            net = 'dl'
            for c in self.categories:
                inp     = "input_" + c
                self.inode( c, net=net )
                self.knode( c )
                nengo.Connection( self.get_node( inp, net=net ), self.get_node( c, net=net ), synapse=None )
                self.probe( self.get_node( c, net=net ), c, net=net )

        with self.spa:
            net = 'spa'
            cfg = nengo.Config( nengo.Ensemble )
            cfg[ nengo.Ensemble ].neuron_type   = nengo.Direct()
            with cfg:
                for c in self.categories:
                    inp     = "input_" + c
                    self.inode( c, net=net )
                    where   = c + "_where"
                    self.state( c )
                    nengo.Connection( self.get_node( inp, net=net ), self.states[ c ].input )
                    self.probe( self.states[ c ].output, where, net=net )
Exemple #15
0
 def default_ens_config(self):
     """(Config) Defaults for other ensemble creation."""
     cfg = nengo.Config(nengo.Ensemble)
     cfg[nengo.Ensemble].update({
         'radius': 1,
         'intercepts': Exponential(self.exp_scale, 0.0, 1.0),
         'encoders': Choice([[1]]),
         'eval_points': Uniform(0.0, 1.0),
         'n_eval_points': self.n_eval_points,
     })
     return cfg
Exemple #16
0
 def thresh_ens_config(self):
     """(Config) Defaults for threshold ensemble creation."""
     cfg = nengo.Config(nengo.Ensemble)
     cfg[nengo.Ensemble].update({
         "radius": 1,
         "intercepts": Uniform(0.5, 1.0),
         "encoders": Choice([[1]]),
         "eval_points": Uniform(0.75, 1.1),
         "n_eval_points": self.n_eval_points,
     })
     return cfg
Exemple #17
0
 def am_ens_config(self):
     """(Config) Defaults for associative memory ensemble creation."""
     cfg = nengo.Config(nengo.Ensemble, nengo.Connection)
     cfg[nengo.Ensemble].update({
         'radius': 1,
         'intercepts': Exponential(self.exp_scale, 0.0, 1.0),
         'encoders': Choice([[1]]),
         'eval_points': Uniform(0.0, 1.0),
         'n_eval_points': self.n_eval_points,
     })
     cfg[nengo.Connection].synapse = None
     return cfg
Exemple #18
0
def generate(
    net=None,  # define PMC, M1, CB, S1 inside net
    probes_on=False):  # set True to record data
    """ Connect up the PMC, M1, CB, and S1 sub-networks up for
    the REACH model.
    """

    config = nengo.Config(nengo.Connection, nengo.Ensemble)
    with net, config:

        dim = net.dim  # the number of DOF of the arm
        net.probes_on = probes_on

        relay = nengo.Node(size_in=dim, label='relay')
        # connect the control signal summed from M1 and CB to the arm
        nengo.Connection(relay, net.arm_node[:2])
        # send in (x, y) of target for plotting
        nengo.Connection(net.xy, net.arm_node[2:])

        if getattr(net, "M1", False):
            # project control signal into output relay
            nengo.Connection(net.M1.output, relay)
            # send in x_des signal to M1
            nengo.Connection(net.error[:dim], net.M1.input[dim:])

        if getattr(net, "S1", False):
            nengo.Connection(net.arm_node, net.S1.input)
            if getattr(net, "M1", False):
                # connect up sensory feedback
                nengo.Connection(net.S1.output[:dim], net.M1.input[:dim])

        if getattr(net, "CB", False):
            # connect up sensory feedback
            nengo.Connection(net.arm_node[:dim * 2], net.CB.input[:dim * 2])
            # send in target for context
            nengo.Connection(net.PMC.output, net.CB.input[dim * 2 + 2:])

            # send in training signal
            nengo.Connection(relay, net.CB.input[dim * 2:dim * 2 + 2])

            # project dynamics compensation term into relay
            # to be included in the training signal for u_adapt
            nengo.Connection(net.CB.output[:dim], relay)

            # send u_adapt output directly to arm
            nengo.Connection(net.CB.output[dim:], net.arm_node[:2])

        if probes_on:
            net.probe_S1 = nengo.Probe(net.S1.output)
            net.probe_M1 = nengo.Probe(net.M1.output)
            net.probe_CB = nengo.Probe(net.CB.output)

    return net
Exemple #19
0
def generate(net=None,
             n_neurons=200,
             alpha=1000.0,
             beta=1000.0 / 4.0,
             dt=0.001,
             analog=False):
    tau = 0.1  # synaptic time constant

    # the A matrix for our point attractor
    A = np.array([[0.0, 1.0], [-alpha * beta, -alpha]])

    # the B matrix for our point attractor
    B = np.array([[0.0, 0.0], [alpha * beta, 1.0]])

    # discretize
    Ad = expm(A * dt)
    Bd = np.dot(np.linalg.inv(A), np.dot((Ad - np.eye(2)), B))
    # account for discrete lowpass filter
    a = np.exp(-dt / tau)
    if analog:
        A = tau * A + np.eye(2)
        B = tau * B
    else:
        A = 1.0 / (1.0 - a) * (Ad - a * np.eye(2))
        B = 1.0 / (1.0 - a) * Bd

    if net is None:
        net = nengo.Network(label='Point Attractor')
    config = nengo.Config(nengo.Connection, nengo.Ensemble)
    config[nengo.Connection].synapse = nengo.Lowpass(tau)
    # config[nengo.Ensemble].neuron_type = nengo.Direct()

    with config, net:
        net.ydy = nengo.Ensemble(
            n_neurons=n_neurons,
            dimensions=2,
            # set it up so neurons are tuned to one dimensions only
            encoders=nengo.dists.Choice([[1, 0], [-1, 0], [0, 1], [0, -1]]))
        # set up Ax part of point attractor
        nengo.Connection(net.ydy, net.ydy, transform=A)

        # hook up input
        net.input = nengo.Node(size_in=2)
        # set up Bu part of point attractor
        nengo.Connection(net.input, net.ydy, transform=B)

        # hook up output
        net.output = nengo.Node(size_in=1)
        # add in forcing function
        nengo.Connection(net.ydy[0], net.output, synapse=None)

    return net
 def rsvr_ens_config(self):
     """(Config) Defaults for reservoir ensemble creation."""
     cfg = nengo.Config(nengo.Ensemble, nengo.Connection)
     cfg[nengo.Ensemble].update({
         "radius":
         1,
         "intercepts":
         nengo.dists.Choice([0] * self.dimensions),
         "n_eval_points":
         self.n_eval_points,
     })
     cfg[nengo.Connection].synapse = None
     return cfg
Exemple #21
0
def test_configstack():
    """Test that setting defaults with bare configs works."""
    with nengo.Network() as net:
        net.config[nengo.Connection].transform = -1
        e1 = nengo.Ensemble(5, dimensions=1)
        e2 = nengo.Ensemble(6, dimensions=1)
        excite = nengo.Connection(e1, e2)
        with nengo.Config(nengo.Connection) as inhib:
            inhib[nengo.Connection].synapse = nengo.synapses.Lowpass(0.00848)
            inhibit = nengo.Connection(e1, e2)
    assert excite.synapse == nengo.Connection.synapse.default
    assert excite.transform.init == -1
    assert inhibit.synapse == inhib[nengo.Connection].synapse
    assert inhibit.transform.init == -1
def Integrator(n_neurons, dimensions, recurrent_config=None, net=None):
    if net is None:
        net = nengo.Network()
    if recurrent_config is None:
        recurrent_config = nengo.Config(nengo.Connection)
        recurrent_config[nengo.Connection].synapse = nengo.Lowpass(0.1)
    with net:
        net.input = nengo.Node(size_in=dimensions)
        net.ensemble = nengo.Ensemble(n_neurons, dimensions=dimensions)
        with recurrent_config:
            nengo.Connection(net.ensemble, net.ensemble)
            tau = nengo.Config.default(nengo.Connection, 'synapse').tau
        nengo.Connection(net.input, net.ensemble, synapse=None, transform=tau)
    return net
Exemple #23
0
def pulvinar(size_in, net=None):
    """"""
    if net is None:
        net = nengo.Network()

    with net:
        S_input = nengo.Node(size_in=size_in, label='S_input')
        # Ensemble with 100 LIF neurons which represents a 2-dimensional signal
        pulv = nengo.Ensemble(100,
                              dimensions=size_in,
                              max_rates=Uniform(100, 200))

        pulv = nengo.Ensemble(n_neurons=size_in, label='pulvinar')
        nengo.Config(S_input, pulv.neurons, transform=np.ones())
Exemple #24
0
def test_contains():
    class A:
        pass

    cfg = nengo.Config(A)
    with pytest.raises(TypeError, match="Cannot check if .* is in a config"):
        A in cfg

    net = nengo.Network()

    net.config[nengo.Ensemble].set_param("test", Parameter("test", None))
    assert "test" not in net.config[nengo.Ensemble]

    net.config[nengo.Ensemble].test = "testval"
    assert "test" in net.config[nengo.Ensemble]
Exemple #25
0
def test_external_class():
    class A:
        thing = Parameter("thing", default="hey")

    inst = A()
    config = nengo.Config(A)
    config[A].set_param("amount", Parameter("amount", default=1))

    # Extra param
    assert config[inst].amount == 1

    # Default still works like Nengo object
    assert inst.thing == "hey"
    with pytest.raises(ConfigError):
        config[inst].thing
Exemple #26
0
def test_external_class():
    class A(object):
        thing = Parameter(default='hey')

    inst = A()
    config = nengo.Config(A)
    config[A].set_param('amount', Parameter(default=1))

    # Extra param
    assert config[inst].amount == 1

    # Default still works like Nengo object
    assert inst.thing == 'hey'
    with pytest.raises(AttributeError):
        config[inst].thing
Exemple #27
0
def test_configstack():
    """Test that setting defaults with bare configs works."""
    inhib = nengo.Config(nengo.Connection)
    inhib[nengo.Connection].synapse = nengo.synapses.Lowpass(0.00848)
    with nengo.Network() as net:
        net.config[nengo.Connection].modulatory = True
        e1 = nengo.Ensemble(5, dimensions=1)
        e2 = nengo.Ensemble(6, dimensions=1)
        excite = nengo.Connection(e1, e2)
        with inhib:
            inhibit = nengo.Connection(e1, e2)
    assert excite.synapse == nengo.Connection.synapse.default
    assert excite.modulatory
    assert inhibit.synapse == inhib[nengo.Connection].synapse
    assert inhibit.modulatory
Exemple #28
0
 def inh_ens_config(self):
     """(Config) Defaults for inhibitory input ensemble creation."""
     cfg = nengo.Config(nengo.Ensemble, nengo.Connection)
     cfg[nengo.Ensemble].update({
         "neuron_type":
         nengo.LIF(tau_ref=0.002),
         "radius":
         1,
         "intercepts":
         nengo.dists.Choice([0.1] * self.dimensions),
         "max_rates":
         nengo.dists.Choice([100])
     })
     cfg[nengo.Connection].synapse = None
     return cfg
def motor_cortex(command_threshold,
                 n_neurons_per_command=30,
                 ens_config=None,
                 net=None):
    if net is None:
        net = nengo.Network()
    if ens_config is None:
        ens_config = nengo.Config(nengo.Ensemble)
        ens_config[nengo.Ensemble].encoders = Choice([[1]])
        ens_config[nengo.Ensemble].intercepts = Choice([command_threshold])
    with net:
        with ens_config:
            net.press = nengo.Ensemble(n_neurons_per_command, dimensions=1)
            net.release = nengo.Ensemble(n_neurons_per_command, dimensions=1)
    return net
def controlled_integrator(n_neurons,
                          dimensions,
                          recurrent_config=None,
                          net=None):
    if net is None:
        net = nengo.Network()
    if recurrent_config is None:
        recurrent_config = nengo.Config(nengo.Connection)
        recurrent_config[nengo.Connection].synapse = nengo.Lowpass(0.1)
    with net:
        net.ensemble = nengo.Ensemble(n_neurons, dimensions=dimensions + 1)
        with recurrent_config:
            nengo.Connection(net.ensemble,
                             net.ensemble[:dimensions],
                             function=lambda x: x[:-1] * (1.0 - x[-1]))
    return net