Different nengo ensembles to create a function

Thanks in Advance for the help. I have a small module with multiple nengo ensemble which needed to be used multiple time in a project. When I tried to convert the module into a function and call with the nengo.connection in the project I got the following error.
“nengo.exceptions.ValidationError: Connection.pre: ‘0’ is not a Nengo object”

Is it possible to make a module with multiple ensembles into one function?

Yes, it is! :smiley:
What you want to do is to create a Nengo network to contain all of the code that you want to reuse. There are two ways to achieve this, the first way is to create a sub-class of the nengo.Networks class, similar to how the built-in Nengo networks are constructed (see here). Alternatively, you can put the network code within a function and use the with context block to define a nengo.Network, like so:

def my_net(...):
    with nengo.Network() as net:
        # Network code goes here
    return net

Within the network code, any thing that you want accessible to the “outside” (i.e., external to your custom network), you’ll have to prefix with the net. attribute. As an example, the following code defines some input and output nodes for my custom network:

def my_net(...):
    with nengo.Network() as net:
        net.inp = nengo.Node(size_in=1)
        net.out = nengo.Node(size_in=1)
    return net

You can then use this network and connect to it. Note that the network object itself is just a container, so when you make a nengo.Connection, you’ll want to connect to an object within the network, and not to the network itself:

with nengo.Network() as model:
    ens = nengo.Ensemble(100, 1)
    net1 = my_net()

    # Make connection to input of the custom network
    nengo.Connection(ens, net1.inp)

    # Probe the output of the custom network
    p1 = nengo.Probe(net1.out)

Here is some example code [test_nengo_subnet.py (981 Bytes)]
that puts all of the code snippets described above into a functional network. The network consists of a sine-wave input, connected to two custom networks, each using the same code to do something a little different. If you run the code, you should see the following output: