示例#1
0
    def __init__(self, parameters, output_layer=None, fileobj=None):
        import py_paddle.swig_paddle as api

        if output_layer is not None:
            topo = topology.Topology(output_layer)
            gm = api.GradientMachine.createFromConfigProto(
                topo.proto(), api.CREATE_MODE_TESTING, [api.PARAMETER_VALUE])
            self.__data_types__ = topo.data_type()
        elif fileobj is not None:
            tmp = cPickle.load(fileobj)
            gm = api.GradientMachine.createByConfigProtoStr(
                tmp['protobin'], api.CREATE_MODE_TESTING,
                [api.PARAMETER_VALUE])
            self.__data_types__ = tmp['data_type']
        else:
            raise ValueError("Either output_layer or fileobj must be set")

        for param in gm.getParameters():
            val = param.getBuf(api.PARAMETER_VALUE)
            name = param.getName()
            assert isinstance(val, api.Vector)
            val.copyFromNumpyArray(parameters.get(name).flatten())
            # the setValueUpdated function is called in randomize, zeroMem,
            # load function in paddle/parameter/Parameter.cpp. But in the
            # inference mode, the setValueUpdated is never called, it will
            # cause the parameter will not be dispatched
            # in MultiGradientMachine for multi-GPU. So setValueUpdated is
            # called here, but it's better to call this function in one place.
            param.setValueUpdated()
        self.__gradient_machine__ = gm
    def start_simulation(self):
        self.topology = topology.Topology(self.adversary, self,
                                          self.topology_model,
                                          self.guard_lifetime_type)

        # Handle node compromises here so that we can handle early Sybils.
        self.topology.handle_node_compromises()
示例#3
0
def getTopology(topologyFileName):
    TOPOLOGY_FILE_NAME = "topology_20.txt"
    topo = topology.Topology()
    try:
        topo.importFromFile(TOPOLOGY_FILE_NAME)
    except:
        print "could not read topology file", TOPOLOGY_FILE_NAME
    return topo
示例#4
0
 def __init__(self, output_layer, parameters):
     topo = topology.Topology(output_layer)
     gm = api.GradientMachine.createFromConfigProto(
         topo.proto(), api.CREATE_MODE_TESTING, [api.PARAMETER_VALUE])
     for param in gm.getParameters():
         val = param.getBuf(api.PARAMETER_VALUE)
         name = param.getName()
         assert isinstance(val, api.Vector)
         val.copyFromNumpyArray(parameters.get(name).flatten())
     self.__gradient_machine__ = gm
     self.__data_types__ = topo.data_type()
示例#5
0
 def __init__(
         self,
         name="",
         h=1,
         N=25,
         m=14,
         topology=tp.Topology(name="AT_System"),
 ):
     self.name = name
     self.topology = topology
     self.h = h
     self.N = N
     self.m = m
     self.z = np.empty((M, M, N), np.complex128)
示例#6
0
    def test(self):
        import topology
        t = topology.Topology()
        v0 = topology.Vertex(t)
        v1 = topology.Vertex(t)
        v2 = topology.Vertex(t)
        v3 = topology.Vertex(t)

        assert (v0.block.index is None)
        assert (v1.block.index is None)
        assert (v2.block.index is None)
        assert (v3.block.index is None)

        v1.block.index = 1
        assert (v1.block.leftBlock is None)
        assert (v1.block.rightBlock is None)

        v3.block.index = 3
        assert (v1.block.leftBlock is None)
        assert (v1.block.rightBlock == v3.block)
        assert (v3.block.leftBlock == v1.block)
        assert (v3.block.rightBlock is None)

        v2.block.index = 0
        assert (v1.block.leftBlock == v2.block)
        assert (v1.block.rightBlock == v3.block)
        assert (v2.block.leftBlock is None)
        assert (v2.block.rightBlock == v1.block)
        assert (v3.block.leftBlock == v1.block)
        assert (v3.block.rightBlock is None)

        v2.block.index = 2
        assert (v1.block.leftBlock is None)
        assert (v1.block.rightBlock == v2.block)
        assert (v2.block.leftBlock == v1.block)
        assert (v2.block.rightBlock == v3.block)
        assert (v3.block.leftBlock == v2.block)
        assert (v3.block.rightBlock is None)

        v0.block.index = 0
        assert (v0.block.leftBlock is None)
        assert (v0.block.rightBlock == v1.block)
        assert (v1.block.leftBlock == v0.block)
        assert (v1.block.rightBlock == v2.block)
        assert (v2.block.leftBlock == v1.block)
        assert (v2.block.rightBlock == v3.block)
        assert (v3.block.leftBlock == v2.block)
        assert (v3.block.rightBlock is None)
示例#7
0
def parser(filename=None):
    """
    Function created for parsing init file.
    In init file are written agents and their
    initial states of energy, as well as deltat (this
    is discrete time : how often energies are updated).

    :param: filename : str (name of the init file)
    :return: topology.Topology() class instance
    """
    if filename is None:
        filename = os.path.join(os.getcwd(), "..", "init_files", "init.txt")
    else:
        filename = os.path.join(os.getcwd(), "..", "init_files", filename)
    with open(filename, "r") as init:
        agents = []
        for line in init:
            line.rstrip(os.linesep)
            if "deltat" in line:
                deltat = float(line.split(":")[-1])
            else:
                agent, data = line.split(":")
                energy, x, y = data.split(",")
                energy = float(energy)
                x = float(x)
                y = float(y)
                if agent == "amussel":
                    new_mussel = data_structures.aMussel(energy)
                    new_mussel.coordinates = (x, y)
                    agents.append(new_mussel)
                elif agent == "apad":
                    new_apad = data_structures.aPad(energy)
                    new_apad.coordinates = (x, y)
                    agents.append(new_apad)

    system = topology.Topology()
    system.all_agents = agents
    system.mussels = [agent for agent in agents if isinstance(agent, data_structures.aMussel)]
    system.pads = [agent for agent in agents if isinstance(agent, data_structures.aPad)]
    system.deltat = deltat

    return system
示例#8
0
def test():
	topo = topology.Topology()
	node1 = topology.Node("1")
	node2 = topology.Node("2")
	node3 = topology.Node("3")
	node4 = topology.Node("4")
	node5 = topology.Node("5")
	node6 = topology.Node("6")

	edge1 = topology.Edge(node1, node2)
	edge2 = topology.Edge(node3, node2)
	edge3 = topology.Edge(node4, node2)
	edge4 = topology.Edge(node4, node5)
	edge5 = topology.Edge(node2, node6)
	edge6 = topology.Edge(node5, node1)

	topo.addNode(node1)
	topo.addNode(node2)
	topo.addNode(node3)
	topo.addNode(node4)
	topo.addNode(node5)
	topo.addNode(node6)

	topo.addEdge(edge1)
	topo.addEdge(edge2)
	topo.addEdge(edge3)
	topo.addEdge(edge4)
	topo.addEdge(edge5)
	topo.addEdge(edge6)

	#print topo.edges

	intmat = topo.getInterconnectivityMatrix()
	print intmat
	
	#topo.exportToFile("topology.txt")

	print "=============="
	print "importing topology_20.txt file"
	topo.importFromFile("topology_20.txt")
	print topo.getInterconnectivityMatrix()
示例#9
0
def testDivisonOfGrid():
    topo = topology.Topology()
    topoFile = "topology_200.txt"
    try:
        topo.importFromFile(topoFile)
    except:
        print "could not read topology file", topoFile

    habNM = simulation.makeNeighConnMap(topo)
    sects = simulation.divideGridToSection(habNM, GRID_SIZE, GRID_SIZE)
    print "sects ", sects
    k = 0
    for habs in sects.values():
        k = k + 1
        X = pylab.ones((10, 10, 3)) * float(k * 0.4)
        print "habs", habs
        for hab in habs:
            hab = hab - 1
            xo = int(hab % GRID_SIZE) * 2
            yo = int(hab / GRID_SIZE) * 2
            print "X ", xo
            print "Y ", yo
            plt.figimage(X, xo, yo, origin='lower')
    plt.show()
示例#10
0
#    S1 ---- S2
#   / | \     |
#  H1 H2 H3  H4
#
import topology, switch, host, port

topo = topology.Topology()

s1 = switch.Switch("s1")
topo.addSwitch(s1)

s2 = switch.Switch("s2")
topo.addSwitch(s2)

s3 = switch.Switch("s3")
topo.addSwitch(s3)
#s3.chassi=100

s4 = switch.Switch("s4")
topo.addSwitch(s4)

h1 = host.Host('h1')
h1.addPort(port.Port('AA:AA:AA:CC:CC:CC'))
h1.addPort(port.Port('AA:AA:AA:AC:CC:CC'))

h2 = host.Host('h2')
h2.addPort(port.Port('AA:AA:AA:CC:CC:CD'))

h3 = host.Host('h3')
h3.addPort(port.Port('AA:AA:AA:CC:CC:CE'))
示例#11
0
def test():

    logWriter = csv.writer(open(OUTPUT_FILE_NAME + ".csv", 'w'),
                           delimiter='\t',
                           quotechar='|',
                           quoting=csv.QUOTE_MINIMAL)

    topo = topology.Topology()
    topoFile = "topology_200.txt"
    try:
        topo.importFromFile(topoFile)
    except:
        print "could not read topology file", topoFile
    habitatNeighMap = {}
    for edge in topo.getInterconnMatInt():
        if edge[0] not in habitatNeighMap:
            habitatNeighMap[edge[0]] = []
        if edge[1] not in habitatNeighMap[edge[0]]:
            habitatNeighMap[edge[0]].append(edge[1])

        if edge[1] not in habitatNeighMap:
            habitatNeighMap[edge[1]] = []
        if edge[0] not in habitatNeighMap[edge[1]]:
            habitatNeighMap[edge[1]].append(edge[0])

    habitatids = [int(node.label) for node in topo.nodes]
    #print habitatids
    #print habitatNeighMap
    #print topo.getInterconnMatInt()

    exit()

    sim = simulation.Simulation(habitatNeighMap)
    print "============"
    #print "Diversity for 1. , 2. , 3. , ",sim.getNextDiversity(), sim.getNextDiversity(), sim.getNextDiversity()
    print " diversity for cell i=0, j=0", sim.getNextDiversity(0, 0)
    print " diversity for cell i=10, j=10", sim.getNextDiversity(10, 10)
    print " diversity for cell i=20, j=20", sim.getNextDiversity(20, 20)

    #print "selected habitat %d from %s"(habitat.id,str(neighbors))
    print "============"

    agents = sim.createAgents(20)

    print "============"
    print "agents strategy"
    for agent in agents:
        print agent.strategy

    print "============"
    sfdmat = []
    for i in range(200):
        sfdmat.append([])
        for j in range(200):
            sfdmat[i].append(sim.getNextDiversity())

    habitats = sim.createHabitats(200, 200, sfdmat, 10, habitatids)

    habitat = habitats[1]

    neighbors = [habitats[x] for x in habitatNeighMap[habitat.id]]

    print "============"
    neighborids = [neigh.id for neigh in neighbors]
    print "habitat id", habitat.id
    print "neighbors ", neighborids
    aneigh = sim.selectANeighborHabitat(habitat, neighbors)
    print "selected habitat", aneigh
    aneigh = sim.selectANeighborHabitat(habitat, neighbors)
    print "selected habitat", aneigh
    aneigh = sim.selectANeighborHabitat(habitat, neighbors)
    print "selected habitat", aneigh
    aneigh = sim.selectANeighborHabitat(habitat, neighbors)
    print "selected habitat", aneigh

    print "============"
    prob = []
    totalDegree = float(habitat.totalOutDegree)
    prob.append(float(habitat.agents[0].outdegree) / totalDegree)

    for i in range(1, len(habitat.agents)):
        prob.append(prob[i - 1] +
                    float(habitat.agents[i].outdegree) / totalDegree)

    print " outdegree of agents"
    for agent in habitat.agents:
        print agent.outdegree
    for ed in habitat.intmat:
        print ed
    print prob
    sel = sim.selectProb(habitat.agentnum, prob)
    print "selected id", sel
    print "============"
    print " agents number, coop num, def num ", habitat.agentnum, habitat.coopnum, habitat.defnum
    print "after adding a agent to habitat ;id ,strategy", agents[
        0].id, agents[0].strategy
    sim.addAgentIntoHabitat(agents[0], habitat, 10)
    print "intmat ", habitat.intmat
    ids = [agent.id for agent in habitat.agents]
    print "agents", ids
    print " agents number, coop num, def num ", habitat.agentnum, habitat.coopnum, habitat.defnum

    print "============"

    print "after removing a agent to habitat ;id ,strategy", habitat.agents[
        0].id, habitat.agents[0].strategy
    sim.removeAgentFromHabitat(habitat.agents[0], habitat)
    print "intmat ", habitat.intmat
    ids = [agent.id for agent in habitat.agents]
    print "agents", ids
    print " agents number, coop num, def num ", habitat.agentnum, habitat.coopnum, habitat.defnum

    print "after removing a agent to habitat ;id ,strategy", habitat.agents[
        1].id, habitat.agents[1].strategy
    sim.removeAgentFromHabitat(habitat.agents[1], habitat)
    print "intmat ", habitat.intmat
    ids = [agent.id for agent in habitat.agents]
    print "agents", ids
    print " agents number, coop num, def num ", habitat.agentnum, habitat.coopnum, habitat.defnum

    print "after removing a agent to habitat ;id ,strategy", habitat.agents[
        3].id, habitat.agents[3].strategy
    sim.removeAgentFromHabitat(habitat.agents[3], habitat)
    print "intmat ", habitat.intmat
    ids = [agent.id for agent in habitat.agents]
    print "agents", ids
    print " agents number, coop num, def num ", habitat.agentnum, habitat.coopnum, habitat.defnum
    sim.createRandomEdge(len(agents), agents, habitats[1].agents[1], prob,
                         totalDegree)

    #for k,hab in habitats.items():
    #	print hab.agentnum

    sim.startSimulation(logWriter)
示例#12
0
def worker(stimulus, stimulus_type):

    # Neuron imports hoc and does a  nrn = hoc.HocObject()
    nrn = neuron.h
    # To avoid Neuron displaying messages
    copystdout = sys.stdout
    # Print info of process
    print("Rank = %s, Stimulus = %s, Experiment = %s" %
          (rank, stimulus, stimulus_type))

    comb = 0
    for stim in stimulus:
        # Reset PSTHs
        PST_IN_ON = np.zeros((int(N * N * INratio), int(tsim / binsize)))
        PST_IN_OFF = np.zeros((int(N * N * INratio), int(tsim / binsize)))
        PST_RC_ON = np.zeros((int(N * N), int(tsim / binsize)))
        PST_RC_OFF = np.zeros((int(N * N), int(tsim / binsize)))
        PST_CXPY_h_ON = np.zeros((int(N * N), int(tsim / binsize)))
        PST_CXPY_v_ON = np.zeros((int(N * N), int(tsim / binsize)))
        PST_CXPY_h_OFF = np.zeros((int(N * N), int(tsim / binsize)))
        PST_CXPY_v_OFF = np.zeros((int(N * N), int(tsim / binsize)))

        for trial in np.arange(0, numbertrials):
            # Remove all sections and set temperature
            nrn("forall delete_section()")
            nrn.celsius = 36.0

            # To avoid Neuron displaying messages
            f = open('/dev/null', 'w')
            sys.stdout = f

            # Simulation and topology modules
            sim = simulation.Simulation()
            tp = topology.Topology()

            # Reset spike counters
            spikes_IN_ON = []
            spikes_IN_OFF = []
            spikes_RC_ON = []
            spikes_RC_OFF = []
            spikes_CXPY_h_ON = []
            spikes_CXPY_v_ON = []
            spikes_CXPY_h_OFF = []
            spikes_CXPY_v_OFF = []

            # to store Neuron cells
            NEURON_cells_to_sim = []

            # to remember positions of IN's dendrites
            IN_dend_dict = np.zeros([int(N * N), 2], dtype=int)

            #################################
            ### Creation of neuron models ###
            #################################

            #### Retina ####
            retina = ganglionCell.Retina()
            spikes_ON = retina.loadSpikes(stim, trial, N, type_ret + "/ON")
            spikes_OFF = retina.loadSpikes(stim, trial, N, type_ret + "/OFF")

            ### Interneuron ###
            INs_ON = []
            INs_OFF = []
            template1 = interneuron.InterneuronTemplate()

            n = 0
            for x in np.arange(0, N * np.sqrt(INratio)):
                for y in np.arange(0, N * np.sqrt(INratio)):
                    INs_ON.append(template1.return_cell())
                    NEURON_cells_to_sim.append(INs_ON[n])
                    INs_OFF.append(template1.return_cell())
                    NEURON_cells_to_sim.append(INs_OFF[n])

                    INs_ON[n].tstop = tsim
                    INs_ON[n].tstart = 0.0
                    INs_ON[n].dt = dt
                    INs_ON[n].dt = dt
                    INs_OFF[n].tstop = tsim
                    INs_OFF[n].tstart = 0.0
                    INs_OFF[n].dt = dt
                    INs_OFF[n].dt = dt

                    # spike counter
                    for sec in INs_ON[n].allseclist:
                        soma = sec
                        break
                    # exec( 'apc_IN_ON%s = nrn.APCount(INs_ON[n].soma(0.5))' % n)
                    exec('apc_IN_ON%s = nrn.APCount(soma(0.5))' % n)
                    exec('apc_IN_ON%s.thresh = -10.0' % n)
                    exec('apc_IN_count_ON%s = nrn.Vector(1)' % n)
                    exec('apc_IN_ON%s.record(apc_IN_count_ON%s)' % (n, n))
                    exec('spikes_IN_ON.append(apc_IN_count_ON%s)' % n)
                    for sec in INs_OFF[n].allseclist:
                        soma = sec
                        break
                    # exec( 'apc_IN_OFF%s = nrn.APCount(INs_OFF[n].cell.soma(0.5))' % n)
                    exec('apc_IN_OFF%s = nrn.APCount(soma(0.5))' % n)
                    exec('apc_IN_OFF%s.thresh = -10.0' % n)
                    exec('apc_IN_count_OFF%s = nrn.Vector(1)' % n)
                    exec('apc_IN_OFF%s.record(apc_IN_count_OFF%s)' % (n, n))
                    exec('spikes_IN_OFF.append(apc_IN_count_OFF%s)' % n)

                    syns = tp.fitSquare(
                        N, IN_RC_mask,
                        int(x / np.sqrt(INratio)) * N +
                        int(y / np.sqrt(INratio)))

                    # Retina inputs
                    count = 0
                    for sn in syns:
                        template1.createSynapse(INs_ON[n],
                                                syn_comps_dist[count], True,
                                                np.array(spikes_ON[int(sn)]))
                        template1.createSynapse(INs_ON[n],
                                                syn_comps_prox[count], False,
                                                np.array(spikes_ON[int(sn)]))
                        template1.createSynapse(INs_OFF[n],
                                                syn_comps_dist[count], True,
                                                np.array(spikes_OFF[int(sn)]))
                        template1.createSynapse(INs_OFF[n],
                                                syn_comps_prox[count], False,
                                                np.array(spikes_OFF[int(sn)]))
                        # Keep position of dendrite and corresponding IN
                        IN_dend_dict[int(sn), :] = [n, count]
                        count += 1

                    n += 1

            #### Relay cell ####
            RCs_ON = []
            RCs_OFF = []
            template2 = relayCell.RCTemplate()

            n = 0
            for x in np.arange(0, N):
                for y in np.arange(0, N):
                    RCs_ON.append(template2.return_cell())
                    NEURON_cells_to_sim.append(RCs_ON[n])
                    RCs_OFF.append(template2.return_cell())
                    NEURON_cells_to_sim.append(RCs_OFF[n])

                    RCs_ON[n].tstop = tsim
                    RCs_ON[n].tstart = 0.0
                    RCs_ON[n].dt = dt
                    RCs_ON[n].dt = dt
                    RCs_OFF[n].tstop = tsim
                    RCs_OFF[n].tstart = 0.0
                    RCs_OFF[n].dt = dt
                    RCs_OFF[n].dt = dt

                    # spike counter
                    for sec in RCs_ON[n].allseclist:
                        soma = sec
                        break
                    # exec( 'apc_RC_ON%s = nrn.APCount(RCs_ON[n].cell.soma[0](0.5))' % n)
                    exec('apc_RC_ON%s = nrn.APCount(soma(0.5))' % n)
                    exec('apc_RC_ON%s.thresh = -10.0' % n)
                    exec('apc_RC_count_ON%s = nrn.Vector(1)' % n)
                    exec('apc_RC_ON%s.record(apc_RC_count_ON%s)' % (n, n))
                    exec('spikes_RC_ON.append(apc_RC_count_ON%s)' % n)
                    for sec in RCs_OFF[n].allseclist:
                        soma = sec
                        break
                    # exec( 'apc_RC_OFF%s = nrn.APCount(RCs_OFF[n].cell.soma[0](0.5))' % n)
                    exec('apc_RC_OFF%s = nrn.APCount(soma(0.5))' % n)
                    exec('apc_RC_OFF%s.thresh = -10.0' % n)
                    exec('apc_RC_count_OFF%s = nrn.Vector(1)' % n)
                    exec('apc_RC_OFF%s.record(apc_RC_count_OFF%s)' % (n, n))
                    exec('spikes_RC_OFF.append(apc_RC_count_OFF%s)' % n)

                    # Retina inputs
                    template2.createSynapse(RCs_ON[n], 0, False,
                                            np.array(spikes_ON[n]), 1.0)
                    template2.createSynapse(RCs_OFF[n], 0, False,
                                            np.array(spikes_OFF[n]), 1.0)

                    n += 1

            #### Cortical pyramidal cell ####
            PYs_h_ON = []
            PYs_v_ON = []
            PYs_h_OFF = []
            PYs_v_OFF = []
            template3 = cortex_PY.CorticalPyramidalTemplate()

            n = 0
            for x in np.arange(0, N):
                for y in np.arange(0, N):
                    PYs_h_ON.append(template3.return_cell())
                    PYs_v_ON.append(template3.return_cell())
                    NEURON_cells_to_sim.append(PYs_h_ON[n])
                    NEURON_cells_to_sim.append(PYs_v_ON[n])
                    PYs_h_OFF.append(template3.return_cell())
                    PYs_v_OFF.append(template3.return_cell())
                    NEURON_cells_to_sim.append(PYs_h_OFF[n])
                    NEURON_cells_to_sim.append(PYs_v_OFF[n])

                    PYs_h_ON[n].tstop = tsim
                    PYs_h_ON[n].tstart = 0.0
                    PYs_h_ON[n].dt = dt
                    PYs_h_ON[n].dt = dt

                    PYs_v_ON[n].tstop = tsim
                    PYs_v_ON[n].tstart = 0.0
                    PYs_v_ON[n].dt = dt
                    PYs_v_ON[n].dt = dt

                    PYs_h_OFF[n].tstop = tsim
                    PYs_h_OFF[n].tstart = 0.0
                    PYs_h_OFF[n].dt = dt
                    PYs_h_OFF[n].dt = dt

                    PYs_v_OFF[n].tstop = tsim
                    PYs_v_OFF[n].tstart = 0.0
                    PYs_v_OFF[n].dt = dt
                    PYs_v_OFF[n].dt = dt

                    # spike counter
                    for sec in PYs_h_ON[n].allseclist:
                        soma = sec
                        break
                    # exec( 'apc_PYs_h_ON%s = nrn.APCount(PYs_h_ON[n].cell.soma[0](0.5))' % n)
                    exec('apc_PYs_h_ON%s = nrn.APCount(soma(0.5))' % n)
                    exec('apc_PYs_h_ON%s.thresh = -10.0' % n)
                    exec('apc_PYs_h_count_ON%s = nrn.Vector(1)' % n)
                    exec('apc_PYs_h_ON%s.record(apc_PYs_h_count_ON%s)' %
                         (n, n))
                    exec('spikes_CXPY_h_ON.append(apc_PYs_h_count_ON%s)' % n)
                    for sec in PYs_v_ON[n].allseclist:
                        soma = sec
                        break
                    # exec( 'apc_PYs_v_ON%s = nrn.APCount(PYs_v_ON[n].cell.soma[0](0.5))' % n)
                    exec('apc_PYs_v_ON%s = nrn.APCount(soma(0.5))' % n)
                    exec('apc_PYs_v_ON%s.thresh = -10.0' % n)
                    exec('apc_PYs_v_count_ON%s = nrn.Vector(1)' % n)
                    exec('apc_PYs_v_ON%s.record(apc_PYs_v_count_ON%s)' %
                         (n, n))
                    exec('spikes_CXPY_v_ON.append(apc_PYs_v_count_ON%s)' % n)
                    for sec in PYs_h_OFF[n].allseclist:
                        soma = sec
                        break
                    # exec( 'apc_PYs_h_OFF%s = nrn.APCount(PYs_h_OFF[n].cell.soma[0](0.5))' % n)
                    exec('apc_PYs_h_OFF%s = nrn.APCount(soma(0.5))' % n)
                    exec('apc_PYs_h_OFF%s.thresh = -10.0' % n)
                    exec('apc_PYs_h_count_OFF%s = nrn.Vector(1)' % n)
                    exec('apc_PYs_h_OFF%s.record(apc_PYs_h_count_OFF%s)' %
                         (n, n))
                    exec('spikes_CXPY_h_OFF.append(apc_PYs_h_count_OFF%s)' % n)
                    for sec in PYs_v_OFF[n].allseclist:
                        soma = sec
                        break
                    # exec( 'apc_PYs_v_OFF%s = nrn.APCount(PYs_v_OFF[n].cell.soma[0](0.5))' % n)
                    exec('apc_PYs_v_OFF%s = nrn.APCount(soma(0.5))' % n)
                    exec('apc_PYs_v_OFF%s.thresh = -10.0' % n)
                    exec('apc_PYs_v_count_OFF%s = nrn.Vector(1)' % n)
                    exec('apc_PYs_v_OFF%s.record(apc_PYs_v_count_OFF%s)' %
                         (n, n))
                    exec('spikes_CXPY_v_OFF.append(apc_PYs_v_count_OFF%s)' % n)

                    n += 1

            ############################
            ### Synaptic connections ###
            ############################

            general_counter = 0

            #### Interneuron -> RC connection
            n = 0
            for x in np.arange(0, N * np.sqrt(INratio)):
                for y in np.arange(0, N * np.sqrt(INratio)):

                    syns = tp.fitSquare(
                        N, IN_RC_mask,
                        int(x / np.sqrt(INratio)) * N +
                        int(y / np.sqrt(INratio)))
                    #                    print(syns)
                    #                    tp.showConn(N,syns)
                    count = 0

                    for sn in syns:
                        # triadic synapse
                        exec(
                            'syn_ON%s = template2.triadSynapse(RCs_ON[int(sn)])'
                            % str(general_counter))
                        exec( 'netcon_ON%s = template1.triadCon(cell=INs_ON[n], syn=syn_ON%s, '\
                        'syn_loc=syn_comps_dist[count])' % (str(general_counter),str(general_counter)))

                        # soma connection
                        exec(
                            'syn_ON%s = template2.somaInhibition(RCs_ON[int(sn)])'
                            % str(general_counter + 1))
                        exec( 'netcon_ON%s = template1.somaCon(cell=INs_ON[n], '\
                        'syn=syn_ON%s)' % (str(general_counter+1),str(general_counter+1)))

                        # triadic synapse
                        exec(
                            'syn_OFF%s = template2.triadSynapse(RCs_OFF[int(sn)])'
                            % str(general_counter))
                        exec( 'netcon_OFF%s = template1.triadCon(cell=INs_OFF[n], syn=syn_OFF%s, '\
                        'syn_loc=syn_comps_dist[count])' % (str(general_counter),str(general_counter)))

                        # soma connection
                        exec(
                            'syn_OFF%s = template2.somaInhibition(RCs_OFF[int(sn)])'
                            % str(general_counter + 1))
                        exec( 'netcon_OFF%s = template1.somaCon(cell=INs_OFF[n], '\
                        'syn=syn_OFF%s)' % (str(general_counter+1),str(general_counter+1)))

                        count += 1
                        general_counter += 2

                    n += 1

            #### RC connection -> PY cells (Receptive-field center)
            n = 0
            for x in np.arange(0, N):
                for y in np.arange(0, N):

                    synsh = tp.rectMask(N, RC_PY_mask_h, n)
                    #                    print(synsh)
                    #                    tp.showConn(N,synsh)

                    count = 0

                    for sn in synsh:
                        exec('syn_ON%s = template3.TCConn(PYs_h_ON[int(n)])' %
                             str(general_counter))
                        exec( 'netcon_ON%s = template2.somaCon(cell=RCs_ON[int(sn)], '\
                        'syn=syn_ON%s,weight=0.05)' % (str(general_counter),str(general_counter)))
                        exec(
                            'syn_OFF%s = template3.TCConn(PYs_h_OFF[int(n)])' %
                            str(general_counter))
                        exec( 'netcon_OFF%s = template2.somaCon(cell=RCs_OFF[int(sn)], '\
                        'syn=syn_OFF%s,weight=0.05)' % (str(general_counter),str(general_counter)))

                        count += 1
                        general_counter += 1

                    synsv = tp.rectMask(N, RC_PY_mask_v, n)
                    #                    print(synsv)
                    #                    tp.showConn(N,synsv)

                    count = 0

                    for sn in synsv:
                        exec('syn_ON%s = template3.TCConn(PYs_v_ON[int(n)])' %
                             str(general_counter))
                        exec( 'netcon_ON%s = template2.somaCon(cell=RCs_ON[int(sn)], '\
                        'syn=syn_ON%s,weight=0.05)' % (str(general_counter),str(general_counter)))
                        exec(
                            'syn_OFF%s = template3.TCConn(PYs_v_OFF[int(n)])' %
                            str(general_counter))
                        exec( 'netcon_OFF%s = template2.somaCon(cell=RCs_OFF[int(sn)], '\
                        'syn=syn_OFF%s,weight=0.05)' % (str(general_counter),str(general_counter)))

                        count += 1
                        general_counter += 1

                    n += 1

            #### RC connection -> PY cells (Receptive-field surround)
            n = 0
            for x in np.arange(0, N):
                for y in np.arange(0, N):

                    synsh = tp.rectMask(N, RC_PY_s_mask_h, n + N)
                    #                    print(synsh)
                    #                    tp.showConn(N,synsh)

                    count = 0

                    for sn in synsh:
                        exec('syn_ON%s = template3.TCConn(PYs_h_OFF[int(n)])' %
                             str(general_counter))
                        exec( 'netcon_ON%s = template2.somaCon(cell=RCs_ON[int(sn)], '\
                        'syn=syn_ON%s,weight=0.02)' % (str(general_counter),str(general_counter)))
                        exec('syn_OFF%s = template3.TCConn(PYs_h_ON[int(n)])' %
                             str(general_counter))
                        exec( 'netcon_OFF%s = template2.somaCon(cell=RCs_OFF[int(sn)], '\
                        'syn=syn_OFF%s,weight=0.02)' % (str(general_counter),str(general_counter)))

                        count += 1
                        general_counter += 1

                    synsv = tp.rectMask(N, RC_PY_s_mask_v, n + 1)
                    #                    print(synsv)
                    #                    tp.showConn(N,synsv)

                    count = 0

                    for sn in synsv:
                        exec('syn_ON%s = template3.TCConn(PYs_v_OFF[int(n)])' %
                             str(general_counter))
                        exec( 'netcon_ON%s = template2.somaCon(cell=RCs_ON[int(sn)], '\
                        'syn=syn_ON%s,weight=0.02)' % (str(general_counter),str(general_counter)))
                        exec('syn_OFF%s = template3.TCConn(PYs_v_ON[int(n)])' %
                             str(general_counter))
                        exec( 'netcon_OFF%s = template2.somaCon(cell=RCs_OFF[int(sn)], '\
                        'syn=syn_OFF%s,weight=0.02)' % (str(general_counter),str(general_counter)))

                        count += 1
                        general_counter += 1

                    n += 1

            #### Feedback: PY cells -> RC cells

            if (feedback_type < 2):

                n = 0
                for x in np.arange(0, N):
                    for y in np.arange(0, N):

                        synRC = tp.rectMask(N, PY_RC_mask, n)
                        #                    print(synRC)
                        #                    tp.showConn(N,synRC)

                        count = 0

                        for sn in synRC:

                            ## Phase-reversed feedback
                            if (feedback_type == 0):

                                exec(
                                    'syn_ON%s = template2.somaExcitation(RCs_ON[int(sn)])'
                                    % str(general_counter))
                                exec( 'netcon_ON%s = template3.somaCon(cell=PYs_h_OFF[int(n)], '\
                                'syn=syn_ON%s,weight=p1_ext[stimulus_type[comb]])'
                                 % (str(general_counter),str(general_counter)))

                                exec(
                                    'syn_ON%s = template2.somaExcitation(RCs_ON[int(sn)])'
                                    % str(general_counter + 1))
                                exec( 'netcon_ON%s = template3.somaCon(cell=PYs_v_OFF[int(n)], '\
                                'syn=syn_ON%s,weight=p1_ext[stimulus_type[comb]])'
                                 % (str(general_counter+1),str(general_counter+1)))

                                exec(
                                    'syn_OFF%s = template2.somaExcitation(RCs_OFF[int(sn)])'
                                    % str(general_counter))
                                exec(
                                    'netcon_OFF%s = template3.somaCon(cell=PYs_h_ON[int(n)], '
                                    'syn=syn_OFF%s,weight=p1_ext[stimulus_type[comb]])'
                                    % (str(general_counter),
                                       str(general_counter)))

                                exec(
                                    'syn_OFF%s = template2.somaExcitation(RCs_OFF[int(sn)])'
                                    % str(general_counter + 1))
                                exec( 'netcon_OFF%s = template3.somaCon(cell=PYs_v_ON[int(n)], '\
                                'syn=syn_OFF%s,weight=p1_ext[stimulus_type[comb]])'
                                % (str(general_counter+1),str(general_counter+1)))

                            ## Phase-matched feedback
                            else:
                                exec(
                                    'syn_ON%s = template2.somaExcitation(RCs_ON[int(sn)])'
                                    % str(general_counter))
                                exec( 'netcon_ON%s = template3.somaCon(cell=PYs_h_ON[int(n)], '\
                                'syn=syn_ON%s,weight=p1_ext[stimulus_type[comb]])'
                                 % (str(general_counter),str(general_counter)))

                                exec(
                                    'syn_ON%s = template2.somaExcitation(RCs_ON[int(sn)])'
                                    % str(general_counter + 1))
                                exec( 'netcon_ON%s = template3.somaCon(cell=PYs_v_ON[int(n)], '\
                                'syn=syn_ON%s,weight=p1_ext[stimulus_type[comb]])'
                                 % (str(general_counter+1),str(general_counter+1)))

                                exec(
                                    'syn_OFF%s = template2.somaExcitation(RCs_OFF[int(sn)])'
                                    % str(general_counter))
                                exec( 'netcon_OFF%s = template3.somaCon(cell=PYs_h_OFF[int(n)], '\
                                'syn=syn_OFF%s,weight=p1_ext[stimulus_type[comb]])'
                                 % (str(general_counter),str(general_counter)))

                                exec(
                                    'syn_OFF%s = template2.somaExcitation(RCs_OFF[int(sn)])'
                                    % str(general_counter + 1))
                                exec( 'netcon_OFF%s = template3.somaCon(cell=PYs_v_OFF[int(n)], '\
                                'syn=syn_OFF%s,weight=p1_ext[stimulus_type[comb]])'
                                 % (str(general_counter+1),str(general_counter+1)))

                            count += 1
                            general_counter += 2

                        n += 1

            #### Feedback: PY cells -> INs

            if (feedback_type < 2):

                n = 0
                for x in np.arange(0, N):
                    for y in np.arange(0, N):

                        synRC = tp.rectMask(N, PY_RC_mask, n)
                        #                    print(synRC)
                        #                    tp.showConn(N,synRC)

                        for sn in synRC:
                            exec( 'synd_ON%s = template1.cortexCon(INs_ON[IN_dend_dict[sn,0]], '\
                            'syn_comps_int[IN_dend_dict[sn,1]])' % str(general_counter))
                            exec( 'netcon_ON%s = template3.somaCon(cell=PYs_h_ON[int(n)], '\
                            'syn=synd_ON%s,weight=p2_ext[stimulus_type[comb]])' % (str(general_counter),str(general_counter)))

                            exec( 'synd_ON%s = template1.cortexCon(INs_ON[IN_dend_dict[sn,0]], '\
                            'syn_comps_int[IN_dend_dict[sn,1]])' % str(general_counter+1))
                            exec( 'netcon_ON%s = template3.somaCon(cell=PYs_v_ON[int(n)], syn=synd_ON%s, '\
                            'weight=p2_ext[stimulus_type[comb]])' % (str(general_counter+2),str(general_counter+1)))

                            exec( 'synd_OFF%s = template1.cortexCon(INs_OFF[IN_dend_dict[sn,0]], '\
                            'syn_comps_int[IN_dend_dict[sn,1]])' % str(general_counter))
                            exec( 'netcon_OFF%s = template3.somaCon(cell=PYs_h_OFF[int(n)], syn=synd_OFF%s, '\
                            'weight=p2_ext[stimulus_type[comb]])' % (str(general_counter),str(general_counter)))

                            exec( 'synd_OFF%s = template1.cortexCon(INs_OFF[IN_dend_dict[sn,0]], '\
                            'syn_comps_int[IN_dend_dict[sn,1]])' % str(general_counter+1))
                            exec( 'netcon_OFF%s = template3.somaCon(cell=PYs_v_OFF[int(n)], syn=synd_OFF%s, '\
                            'weight=p2_ext[stimulus_type[comb]])' % (str(general_counter+2),str(general_counter+1)))

                            general_counter += 4

                        n += 1

            #### Simulation
            sim.simulateCells(NEURON_cells_to_sim)
            sys.stdout = copystdout

            # update PSTHs
            for n in np.arange(0, len(INs_ON)):
                h, e = np.histogram(np.array(spikes_IN_ON[n]),
                                    bins=np.arange(0., tsim + binsize,
                                                   binsize))
                PST_IN_ON[n, :] += h * (1000. / binsize)
            for n in np.arange(0, len(INs_OFF)):
                h, e = np.histogram(np.array(spikes_IN_OFF[n]),
                                    bins=np.arange(0., tsim + binsize,
                                                   binsize))
                PST_IN_OFF[n, :] += h * (1000. / binsize)

            for n in np.arange(0, len(RCs_ON)):
                h, e = np.histogram(np.array(spikes_RC_ON[n]),
                                    bins=np.arange(0., tsim + binsize,
                                                   binsize))
                PST_RC_ON[n, :] += h * (1000. / binsize)
            for n in np.arange(0, len(RCs_OFF)):
                h, e = np.histogram(np.array(spikes_RC_OFF[n]),
                                    bins=np.arange(0., tsim + binsize,
                                                   binsize))
                PST_RC_OFF[n, :] += h * (1000. / binsize)

            for n in np.arange(0, len(PYs_h_ON)):
                h, e = np.histogram(np.array(spikes_CXPY_h_ON[n]),
                                    bins=np.arange(0., tsim + binsize,
                                                   binsize))
                PST_CXPY_h_ON[n, :] += h * (1000. / binsize)
            for n in np.arange(0, len(PYs_h_OFF)):
                h, e = np.histogram(np.array(spikes_CXPY_h_OFF[n]),
                                    bins=np.arange(0., tsim + binsize,
                                                   binsize))
                PST_CXPY_h_OFF[n, :] += h * (1000. / binsize)

            for n in np.arange(0, len(PYs_v_ON)):
                h, e = np.histogram(np.array(spikes_CXPY_v_ON[n]),
                                    bins=np.arange(0., tsim + binsize,
                                                   binsize))
                PST_CXPY_v_ON[n, :] += h * (1000. / binsize)
            for n in np.arange(0, len(PYs_v_OFF)):
                h, e = np.histogram(np.array(spikes_CXPY_v_OFF[n]),
                                    bins=np.arange(0., tsim + binsize,
                                                   binsize))
                PST_CXPY_v_OFF[n, :] += h * (1000. / binsize)

#            # Save membrane potentials
#            if stim == stim_to_plot:

#                times = [INs_ON[cell_number_IN].tvec,INs_ON[cell_number_IN].tvec,RCs_ON[cell_number].tvec,
#                PYs_h_ON[cell_number].tvec,PYs_v_ON[cell_number].tvec]
#                potentials = [INs_ON[cell_number_IN].vmem[0, :],INs_ON[cell_number_IN].vmem[syn_comps_dist[3], :],
#                RCs_ON[cell_number].vmem[0, :],
#                PYs_h_ON[cell_number].vmem[0, :],PYs_v_ON[cell_number].vmem[0, :]]
#                spikes_arriving = [spikes_ON[cell_number],spikes_ON[cell_number],spikes_ON[cell_number],[0.0],[0.0]]
#                labels = ["IN-ON","IN-ON-distal dendrite[3]","RC-ON","PY-horizontal-ON","PY-vertical-ON"]

#                sim.saveMemPotential(str(stim)+"ON",times,potentials,spikes_arriving,labels)

#                times = [INs_OFF[cell_number_IN].tvec,INs_OFF[cell_number_IN].tvec,RCs_OFF[cell_number].tvec,
#                PYs_h_OFF[cell_number].tvec,PYs_v_OFF[cell_number].tvec]
#                potentials = [INs_OFF[cell_number_IN].vmem[0, :],INs_OFF[cell_number_IN].vmem[syn_comps_dist[3], :],
#                RCs_OFF[cell_number].vmem[0, :],
#                PYs_h_OFF[cell_number].vmem[0, :],PYs_v_OFF[cell_number].vmem[0, :]]
#                spikes_arriving = [spikes_OFF[cell_number],spikes_OFF[cell_number],spikes_OFF[cell_number],[0.0],[0.0]]
#                labels = ["IN-OFF","IN-OFF-distal dendrite[3]","RC-OFF","PY-horizontal-OFF","PY-vertical-OFF"]

#                sim.saveMemPotential(str(stim)+"OFF",times,potentials,spikes_arriving,labels)

# Release memory
            sim.deleteAll(NEURON_cells_to_sim)
            del NEURON_cells_to_sim

        # Save PSTH matrix (for each stimuli)
        sim.savePST(stim, "IN-ON", PST_IN_ON, type + str(stimulus_type[comb]))
        sim.savePST(stim, "IN-OFF", PST_IN_OFF,
                    type + str(stimulus_type[comb]))
        sim.savePST(stim, "RC-ON", PST_RC_ON, type + str(stimulus_type[comb]))
        sim.savePST(stim, "RC-OFF", PST_RC_OFF,
                    type + str(stimulus_type[comb]))
        sim.savePST(stim, "PY_h-ON", PST_CXPY_h_ON,
                    type + str(stimulus_type[comb]))
        sim.savePST(stim, "PY_h-OFF", PST_CXPY_h_OFF,
                    type + str(stimulus_type[comb]))
        sim.savePST(stim, "PY_v-ON", PST_CXPY_v_ON,
                    type + str(stimulus_type[comb]))
        sim.savePST(stim, "PY_v-OFF", PST_CXPY_v_OFF,
                    type + str(stimulus_type[comb]))

        comb += 1

    return 1
示例#13
0
    def run_optimization(self):
        
        # Prepare variables:
        self.topy_dict['PASV_ELEM'] = np.array(self.passive)
        self.topy_dict['ACTV_ELEM'] = np.array(self.active)
        
        # Set up ToPy for the different load cases:
        
        topy_cases = []
        for load_case in self.load_cases:
            topy_cases.append(topology.Topology())
            topy_dict = self.topy_dict.copy()
            topy_dict['LOAD_DOF'] = self.loaded_dof[load_case]
            topy_dict['LOAD_VAL'] = self.loads[load_case]           
            topy_cases[-1].topydict = topy_dict
            topy_cases[-1].set_top_params()

        etas_avg = []
        t1 = topy_cases[0]

        # Optimising function:
        def optimise():
            
            # Perform analysis for the different load cases:
            for topy_case in topy_cases:            
                topy_case.fea()
                topy_case.sens_analysis()
            
            # Update design variables:
            for i in xrange(1,len(topy_cases)):
                topy_cases[0].df += topy_cases[i].df*self.case_weights[self.load_cases[i]]       
            topy_cases[0].filter_sens_sigmund()
            topy_cases[0].update_desvars_oc()
            for i in xrange(1,len(topy_cases)):
                topy_cases[i].desvars = topy_cases[0].desvars
                topy_cases[i].p = topy_cases[0].p
            # Below this line we print and create images:
            create_3d_geom(t1.desvars, prefix=t1.probname, \
            iternum=t1.itercount, time='none')
            print '%4i  | %3.6e | %3.3f | %3.4e | %3.3f | %3.3f |  %1.3f  |  %3.3f '\
            % (t1.itercount, t1.objfval, t1.desvars.sum()/(self.total_elements), \
            t1.change, t1.p, t1.q, t1.eta.mean(), t1.svtfrac)
            # Build a list of average etas:
            etas_avg.append(t1.eta.mean())

        # Start optimisation runs, create rest of design domains:
        print '%5s | %11s | %5s | %10s | %5s | %5s | %7s | %5s ' % ('Iter', \
        'Obj. func.  ', 'Vol. ', 'Change    ', 'P_FAC', 'Q_FAC', 'Ave ETA', 'S-V frac.')
        print '-' * 79
        ti = time()

        n = 0
        while n < self.max_iterations:
            n += 1
            optimise()
    
        te = time()
    
        # Print solid-void ratio info:
        print '\nSolid plus void to total elements fraction = %3.5f' % (t1.svtfrac)
        # Print iteration info:
        print t1.itercount, 'iterations took %3.3f minutes (%3.3f min/iter. \
        or %3.3f sec/iter.)'\
        %((te - ti) / 60, (te - ti) / 60 / t1.itercount, (te - ti) / t1.itercount)
        print 'Average of all ETA\'s = %3.3f (average of all a\'s = %3.3f)' \
        % (np.array(etas_avg).mean(), 1/np.array(etas_avg).mean() - 1)
 def start_simulation(self):
     self.topology = topology.Topology(self.adversary, self,
                                       self.topology_model)
示例#15
0
        gs_ci_robots[n] = GS_CI(n, initial.copy())
        # gs_sci_robots[n] = GS_SCI(n, initial.copy())

    landmarks = [None] * M
    for m in range(M):
        landmarks[m] = sim_env.Landmark(
            m,
            np.matrix(sim_env.landmark_position, dtype=float).getT())

    # N = 5
    topology.generate_topology(N, sim_env.observ_prob, sim_env.comm_prob)

    ### Network Topology
    topo_file = open('topology/output.txt', 'r')

    observ_topology = topology.Topology(N)
    comm_topology = topology.Topology(N)

    edge_num_str = topo_file.readline()

    for i in range(int(edge_num_str)):
        line = topo_file.readline()
        edge = line.split(", ")

        observ_topology.add_edge(int(edge[0]), int(edge[1]))

    edge_num_str = topo_file.readline()
    for i in range(int(edge_num_str)):
        line = topo_file.readline()
        edge = line.split(", ")