예제 #1
0
    def test_pso_model(self):
        m = PSOModelAutoSetup("../examples/particleSwarmOptimization/xmlSetup/setup.xml", "xml")
        m.setup()

        optionalParams = m.optionalParameters

        self.assertEqual(50, optionalParams["food location x"])
        self.assertEqual(60, optionalParams["food location y"])

        self.assertEqual(m.foodLocation, Coordinates2D(50,60))

        grid = m.getGridFromName("psogrid")

        self.assertEqual(True, isinstance(grid, ObjectGrid2D))

        self.assertEqual((100,100), grid.getSize())

        agentListA = grid.getAtPos(Coordinates2D(10,10))
        self.assertEqual(1, len(agentListA))

        agent = agentListA[0]
        self.assertEqual(True, isinstance(agent, PSOAgent))

        helper = m.schedule.helpers[0]

        self.assertEqual(True, isinstance(helper, ParticleSwarmOptimizationRenderer))
        self.assertEqual("psogrid", grid.gridName)
예제 #2
0
    def test_load_numerical_grid(self):
        m = EmptyModel("../examples/misc/xmlSetup/setupB.xml", "xml")
        m.setup()

        grid = m.getGridFromName("gridC")

        self.assertEqual(True, isinstance(grid, NumericalGrid2D))

        self.assertEqual((123,456), grid.getSize())
        self.assertEqual(12, grid.getGridValue(Coordinates2D(1,1)))
        self.assertEqual(15, grid.getGridValue(Coordinates2D(9,10)))
        self.assertEqual(12, grid.getGridValue(Coordinates2D(1,1)))
예제 #3
0
    def renderGrid(self, grid):

        self.C.create_rectangle(0,
                                self.gridSize[1] * self.multiplier,
                                0,
                                self.gridSize[0] * self.multiplier,
                                fill="black")

        for x in range(0, self.gridSize[1]):
            for y in range(0, self.gridSize[0]):

                agent = grid.getAtPos(Coordinates2D(x, y))
                agent = agent[0]

                mx = x * self.multiplier
                my = y * self.multiplier

                if (agent.state == 1):
                    p = self.C.create_rectangle(mx,
                                                my,
                                                mx + self.multiplier,
                                                my + self.multiplier,
                                                fill="red",
                                                width=3)
                else:
                    p = self.C.create_rectangle(mx,
                                                my,
                                                mx + self.multiplier,
                                                my + self.multiplier,
                                                fill="darkblue",
                                                width=3)

        self.C.update()
        self.C.pack()
예제 #4
0
    def setup(self, *args):

        self.optionalParameters = {}

        epochs = 100

        self.setEpochs(epochs)

        size = 20
        grid = ObjectGrid2D(size, size, "golgrid")
        s = Schedule()

        s.addHelper(GameOfLifeRenderer(grid))

        for x in range(size):
            for y in range(size):

                if (random.random() <= 0.5):
                    state = 1
                else:
                    state = 0

                h = GOLCell([1, state])
                grid.moveAgent(Coordinates2D(x, y), h)
                s.addAgent(h)

        self.addSchedule(s)

        self.addGrid(grid)
예제 #5
0
    def test_model_setup(self):
        golModel = GOLModelAutoSetup("../examples/gameOfLife/xmlSetup/golSetupSimpleTest.xml", "xml")
        golModel.setup()

        g = golModel.getGridFromName("golgrid")
        gSize = g.getSize()
        self.assertEqual((100,100), gSize)

        agents = g.getAtPos(Coordinates2D(5,7))

        self.assertEqual(1, len(agents))

        agent = agents[0]

        self.assertEqual(1, agent.getRadius())
        self.assertEqual(0, agent.state)
예제 #6
0
    def test_model_setup_ext(self):
        golModel = GOLModelAutoSetup("../examples/gameOfLife/xmlSetup/setupSmallModel.xml", "xml")
        golModel.setup()

        g = golModel.getGridFromName("golgrid")
        gSize = g.getSize()
        self.assertEqual((3,3), gSize)

        center = Coordinates2D(1,1)
        centerNeigh = g.getMooreNeigh(center)

        for n in centerNeigh:
            tempAgentList = n[1]
            self.assertEqual(1, len(tempAgentList))

            tempAgent = tempAgentList[0]
            self.assertEqual(1, tempAgent.getRadius())
예제 #7
0
    def test_model_setup_A(self):

        m = EmptyModel("../examples/misc/xmlSetup/setupA.xml", "xml")
        m.setup()

        grids = m.grids

        self.assertEqual(2, len(grids))

        gA = m.getGridFromName("gridA")
        self.assertEqual((123,321),gA.getSize())

        gB = m.getGridFromName("gridB")
        self.assertEqual((200,250), gB.getSize())

        agentListA = gA.getAtPos(Coordinates2D(0,0))
        agentListB = gA.getAtPos(Coordinates2D(1,1))

        self.assertEqual(1, len(agentListA))
        self.assertEqual(0, len(agentListB))

        agentListC = gB.getAtPos(Coordinates2D(2,3))
        self.assertEqual(1, len(agentListC))

        idleAgentA = agentListC[0]

        self.assertEqual(1, idleAgentA.radius)
        self.assertEqual("tagA", idleAgentA.tag)

        agentListD = gA.getAtPos(Coordinates2D(1,5))
        self.assertEqual(2, len(agentListD))

        idleAgentB = agentListD[0]

        retrievedPosB = gB.getAtPos(Coordinates2D(7,8))
        self.assertEqual(idleAgentB, retrievedPosB[0])

        self.assertEqual(idleAgentB.tag, "tagB")

        idleAgentC = agentListD[1]

        retrievedPosC = gB.getAtPos(Coordinates2D(9,10))

        self.assertEqual(idleAgentC, retrievedPosC[0])

        self.assertEqual(idleAgentC.tag, "tagC")

        # checking that the helper has actually been added
        helpers = m.schedule.helpers

        self.assertEqual(1, len(helpers))

        helper = helpers[0]

        self.assertEqual("IdleHelper", helper.__class__.__name__)
        self.assertEqual("lorem", helper.initDummyVar)
        helper.stepPrologue(m)
        self.assertEqual("dummy", helper.dummyVar)

        self.assertEqual("dummy", helper.argOne)
        self.assertEqual("anotherDummy", helper.argTwo)
예제 #8
0
    def setupFromExternal(self, xmlPath, model):
        tree = ET.parse(xmlPath)
        root = tree.getroot()

        modelProperties = root.attrib

        # setting epochs
        model.setEpochs(int(modelProperties["epochs"]))

        modelParameters = root.findall("modelParameters/*")

        for m in modelParameters:
            model.addOptionalParameter(m.attrib)

        # grid index, that is all possible types of grids
        gridIndex = root.findall("grids/gridIndex/*")

        # getting all grids which are actually instantiated
        modelGrid = root.findall("grids/modelGrids/*")

        # looping through all grids
        for m in modelGrid:
            # getting the reference to the actual grid class which we will instantiate
            g = filter(lambda x: x.attrib["ref"] == m.attrib["type"],
                       gridIndex)[0].attrib

            # getting parameters for this specific instance
            instanceParameters = m.findall("parameters/*")

            parameters = []

            for p in instanceParameters:
                parameters.append(p.attrib["value"])

            # And finally actually instantiating the class
            module = importlib.import_module(g["module"])
            my_class = getattr(module, g["class"])
            grid = my_class(parameters)

            model.addGrid(grid)

            # NumericalGrid2D objects can have coordinate values
            # defined in xml
            if (g["class"] == "NumericalGrid2D"):
                coordinateValues = m.findall("coordinateValues/*")

                for cv in coordinateValues:
                    cv = cv.attrib

                    grid.setGridValue(
                        Coordinates2D(int(cv["x"]), int(cv["y"])),
                        float(cv["value"]))

        schedule = Schedule()

        # helper index, that is all possible types of helpers
        helperIndex = root.findall("helpers/helperIndex/*")

        # getting all the helpers which are actually instantiated
        modelHelpers = root.findall("helpers/modelHelpers/*")

        #looping through all helpers
        for m in modelHelpers:
            # getting reference to the actual helper class
            h = filter(lambda x: x.attrib["ref"] == m.attrib["type"],
                       helperIndex)[0].attrib

            # getting parameters for this specific instance
            instanceParameters = m.findall("parameters/*")

            parameters = []

            for p in instanceParameters:
                parameters.append(p.attrib["value"])

            # And finally actually instantiating the class
            module = importlib.import_module(h["module"])
            my_class = getattr(module, h["class"])
            helper = my_class(parameters)

            schedule.addHelper(helper)

        # agent index, that is all possible types of agents
        agentIndex = root.findall("agents/agentIndex/*")

        # getting all agents which are actually instantiated
        modelAgents = root.findall("agents/modelAgents/*")

        # looping through agents
        for m in modelAgents:
            # getting reference to the actual agent class
            a = filter(lambda x: x.attrib["ref"] == m.attrib["type"],
                       agentIndex)[0].attrib

            # getting parameters for this specific instance
            instanceParameters = m.findall("parameters/*")

            parameters = []

            for p in instanceParameters:
                parameters.append(p.attrib["value"])

            # And finally actually instantiating the class
            module = importlib.import_module(a["module"])
            my_class = getattr(module, a["class"])
            agent = my_class(parameters)

            schedule.addAgent(agent)

            # Now we have to add the agent to the appropriate grids
            gridPositions = m.findall("gridPositions/*")

            for g in gridPositions:

                # getting the grid
                gridName = g.attrib["grid"]
                grid = model.getGridFromName(gridName)

                # now we get the agent's coordinates for this grid
                coords = g.findall("coordinate")

                # and add them
                if (len(coords) == 2):
                    c = Coordinates2D(int(coords[0].attrib["value"]),
                                      int(coords[1].attrib["value"]))
                else:
                    c = Coordinates3D(int(coords[0].attrib["value"]),
                                      int(coords[1].attrib["value"]),
                                      int(coords[2].attrib["value"]))

                grid.moveAgent(c, agent)

        model.addSchedule(schedule)
예제 #9
0
    def moveAgent(self, coordinates, agent):
        """ Moves an agent to a certain position on the grid. If the agent wasn't on the grid, it is added.

         Args:
             coordinates (Coordinates2D): The coordinates we want to move the agent to.
             agent (Agent): The agent we want to move.
        """

        # The actual x/y tuple representing the coordinates we want to move our agent to
        coordinatesTuple = coordinates.getCoordinates()

        # We first check if the agent is known to the grid
        matching = [agent_coords for agent_coords in self.gridAgents if agent_coords[1] == agent]

        # Storing the agent's position for this grid in the agent itself too
        agent.gridPositions[self.gridName] = coordinates

        if (len(matching) == 0):
            # The agent is not known to the system, let's make them known
            self.gridAgents.append((coordinates, agent))

            # And we add them to the grid
            self.grid[coordinatesTuple[0]][coordinatesTuple[1]].append(agent)

        else:

            x = coordinatesTuple[0]
            y = coordinatesTuple[1]


            # preventing an agent from moving off the grid
            if(x < 0):
                x = 0

            if(x > self.xsize-1):
                x = self.xsize-1

            if(y < 0):
                y = 0

            if(y > self.ysize-1):
                y = self.ysize-1

            coordinates = Coordinates2D(x,y)

            # getting the tuple representing the current location
            listTuple = matching[0]

            # from it, we get its current position
            coordinatesOld = listTuple[0].getCoordinates()

            # creating a new tuple representing the new coordinates
            newTuple = (coordinates, agent)

            # and registering it
            loc = self.gridAgents.index(listTuple)
            self.gridAgents[loc] = newTuple

            # physically removing the agent from the old position on the grid
            self.grid[coordinatesOld[0]][coordinatesOld[1]].remove(agent)




            # ...and physically adding it to the new position on the grid
            self.grid[x][y].append(agent)