Beispiel #1
0
    def __init__(self, N, width, height, grid=10, iter=100000, seed=None):
        """Initialize the attributes."""
        if seed is None:
            super(EnvironmentModel, self).__init__(seed=None)
        else:
            super(EnvironmentModel, self).__init__(seed)

        self.runid = datetime.datetime.now().strftime("%s") + str(
            self.random.randint(1, 1000, 1)[0])
        self.pname = os.getcwd() + '/' + self.runid + "SForagingComm"

        self.stepcnt = 1
        self.iter = iter
        self.top = None
        # Create db connection
        connect = Connect('swarm', 'swarm', 'swarm', 'localhost')
        self.connect = connect.tns_connect()

        # Fill out the experiment table
        self.experiment = Experiment(self.connect, self.runid, N, seed,
                                     'SForaging Communication', iter, width,
                                     height, grid)
        self.experiment.insert_experiment()

        self.sn = self.experiment.sn

        # Create a folder to store results
        os.mkdir(self.pname)

        self.num_agents = N

        self.grid = Grid(width, height, grid)

        self.schedule = SimultaneousActivation(self)

        # self.site = Sites(id=1, location=(5, 5), radius=11, q_value=0.5)

        # self.grid.add_object_to_grid(self.site.location, self.site)

        # self.hub = Hub(id=1, location=(0, 0), radius=11)

        # self.grid.add_object_to_grid(self.hub.location, self.hub)

        self.agents = []

        # Create agents
        for i in range(self.num_agents):
            a = SwarmAgent(i, self)
            self.schedule.add(a)
            # Add the agent to a random grid cell
            x = self.random.randint(-self.grid.width / 2, self.grid.width / 2)
            # x = 0
            y = self.random.randint(-self.grid.height / 2,
                                    self.grid.height / 2)
            # y = 0

            a.location = (x, y)
            self.grid.add_object_to_grid((x, y), a)
            a.operation_threshold = 2  # self.num_agents // 10
            self.agents.append(a)
Beispiel #2
0
    def __init__(
            self, N, width, height, grid=10, iter=100000,
            seed=None, name='CTForaging', viewer=False,
            parent=None, ratio=1.0):
        """Initialize the attributes."""
        if seed is None:
            super(CTModel, self).__init__(seed=None)
        else:
            super(CTModel, self).__init__(seed)

        # Create a unique experiment id
        self.runid = datetime.datetime.now().timestamp()
        self.runid = str(self.runid).replace('.', '')

        # Create the experiment folder
        # If parent folder exits create inside it

        if parent is not None and pathlib.Path(parent).is_dir():
            self.pname = parent + '/' + self.runid + '-' + str(ratio) + name
        else:
            self.pname = '/'.join(
                os.getcwd().split('/')[:-2]
                ) + '/results/' + self.runid + '-' + str(iter) + name

        # Define some parameters to count the step
        self.stepcnt = 1
        self.iter = iter

        # UI
        self.viewer = viewer

        # Create db connection
        connect = Connect('swarm', 'swarm', 'swarm', 'localhost')
        self.connect = connect.tns_connect()

        # Fill out the experiment table
        self.experiment = Experiment(
            self.connect, self.runid, N, seed, name,
            iter, width, height, grid)
        self.experiment.insert_experiment()

        # Get the primary key of the experiment table for future use
        self.sn = self.experiment.sn

        # Create a folder to store results
        os.mkdir(self.pname)

        # Number of agents
        self.num_agents = N
        # Environmental grid size
        self.grid = Grid(width, height, grid)
        # Schedular to active agents
        self.schedule = SimultaneousActivation(self)
        # Empty list of hold the agents
        self.agents = []
Beispiel #3
0
    def __init__(
            self, N, width, height, grid=10, iter=100000,
            xmlstrings=None, seed=None, viewer=False, pname=None,
            expname='MSFSimulation', agent='SimAgent'):
        """Initialize the attributes."""
        if seed is None:
            super(SimModel, self).__init__(seed=None)
        else:
            super(SimModel, self).__init__(seed)

        self.runid = datetime.datetime.now().strftime(
            "%s") + str(self.random.randint(1, 1000, 1)[0])

        if pname is None:
            self.pname = os.getcwd() + '/' + self.runid + expname
        else:
            self.pname = pname + '/' + self.runid + expname

        self.width = width
        self.height = height
        self.stepcnt = 1
        self.iter = iter
        self.xmlstrings = xmlstrings

        self.viewer = viewer

        # Create db connection
        connect = Connect('swarm', 'swarm', 'swarm', 'localhost')
        self.connect = connect.tns_connect()

        # Fill out the experiment table
        self.experiment = Experiment(
            self.connect, self.runid, N, seed, expname,
            iter, width, height, grid, phenotype=xmlstrings[0])

        self.experiment.insert_experiment_simulation()

        self.sn = self.experiment.sn

        # Create a folder to store results
        os.mkdir(self.pname)

        self.num_agents = N

        self.grid = Grid(width, height, grid)

        self.schedule = SimultaneousActivation(self)

        self.agents = []

        bound = np.ceil((self.num_agents * 1.0) / len(self.xmlstrings))

        j = 0
        # Create agents
        for i in range(self.num_agents):
            # print (i, j, self.xmlstrings[j])
            a = eval(agent)(i, self, xmlstring=self.xmlstrings[j])
            self.schedule.add(a)
            # Add the agent to a random grid cell
            # x = self.random.randint(
            #    -self.grid.width / 2, self.grid.width / 2)
            x = 0
            # y = self.random.randint(
            #    -self.grid.height / 2, self.grid.height / 2)
            y = 0

            a.location = (x, y)
            self.grid.add_object_to_grid((x, y), a)
            a.operation_threshold = 2  # self.num_agents // 10
            self.agents.append(a)

            if (i + 1) % bound == 0:
                j += 1
Beispiel #4
0
    def __init__(self,
                 N,
                 width,
                 height,
                 grid=10,
                 iter=100000,
                 seed=None,
                 expname='COT',
                 agent='EvolAgent',
                 parm='swarm_mcarry.txt'):
        """Initialize the attributes."""
        if seed is None:
            super(EvolModel, self).__init__(seed=None)
        else:
            super(EvolModel, self).__init__(seed)

        self.runid = datetime.datetime.now().strftime("%s") + str(
            self.random.randint(1, 1000, 1)[0])

        self.pname = '/'.join(os.getcwd().split('/')[:-2]) + '/results/' \
            + self.runid + expname

        self.stepcnt = 1
        self.iter = iter
        self.top = None
        # Create db connection
        connect = Connect('swarm', 'swarm', 'swarm', 'localhost')
        self.connect = connect.tns_connect()

        # Fill out the experiment table
        self.experiment = Experiment(self.connect, self.runid, N, seed,
                                     expname, iter, width, height, grid)
        self.experiment.insert_experiment()

        self.sn = self.experiment.sn

        # Create a folder to store results
        os.mkdir(self.pname)

        self.num_agents = N

        self.grid = Grid(width, height, grid)

        self.schedule = SimultaneousActivation(self)

        self.agents = []
        self.parm = parm

        # Create agents
        for i in range(self.num_agents):
            a = eval(agent)(i, self)
            self.schedule.add(a)
            # Add the agent to a random grid cell
            x = self.random.randint(-self.grid.width / 2, self.grid.width / 2)
            # x = 0
            y = self.random.randint(-self.grid.height / 2,
                                    self.grid.height / 2)
            # y = 0

            a.location = (x, y)
            self.grid.add_object_to_grid((x, y), a)
            a.operation_threshold = 2  # self.num_agents // 10
            self.agents.append(a)
Beispiel #5
0
class TestGrid(unittest.TestCase):
    """Test calss for database."""
    def setUp(self):
        """Set up required stuffs."""
        self.dbname = 'swarm'
        self.username = '******'
        self.passwd = 'swarm'
        self.hostname = 'localhost'
        self.connect = Connect(self.dbname, self.username, self.passwd,
                               self.hostname)

    def test_connection(self):
        """Test connection to db."""
        # This will return connection object
        tnsconnect = self.connect.tns_connect()

        # Check if the connection is valid
        self.assertEqual(1, tnsconnect.status)

        # Check if its connected to the right db with right parameters
        tns_parms = {
            'host': 'localhost',
            'krbsrvname': 'postgres',
            'options': '',
            'tty': '',
            'dbname': 'swarm',
            'target_session_attrs': 'any',
            'sslmode': 'prefer',
            'port': '5432',
            'user': '******',
            'sslcompression': '1'
        }

        self.assertDictEqual(tns_parms, tnsconnect.get_dsn_parameters())

    def test_insert_experiment(self):
        """Test insert statement to db."""
        tnsconnect = self.connect.tns_connect()
        dbexec = Dbexecute(tnsconnect)
        sn = dbexec.insert_experiment(20150101024)
        self.assertEqual('int', type(sn).__name__)

        # After insertion is done need to delete the values as well
        retval = dbexec.execute_query("DELETE from experiment where sn=" +
                                      str(sn))
        self.assertEqual(True, retval)

    def test_insert_experiment_details(self):
        """Test insert statement for experiment details table.

        Since this table has a foreign key from experiment table. First
        we need to populate experiment table.
        """
        tnsconnect = self.connect.tns_connect()
        dbexec = Dbexecute(tnsconnect)
        sn = dbexec.insert_experiment(20150101025)
        data_list = [
            sn, 1, 45, 7, 0.99, 80, 78, 45, 2, 5, '[1, 0, 1 ,1, 0]', '<xml>',
            'none'
        ]
        retval = dbexec.insert_experiment_details(data_list)

        self.assertEqual(True, retval)

        # After insertion is done first need to delete in child table
        retval = dbexec.execute_query(
            "DELETE from experiment_details where exp_id=" + str(sn))

        self.assertEqual(True, retval)
        # After child records deleted, safely delete parent

        retval = dbexec.execute_query("DELETE from experiment where sn=" +
                                      str(sn))

        self.assertEqual(True, retval)

    def test_insert_experiment_best(self):
        """Test insert statement for experiment best table.

        Since this table has a foreign key from experiment table. First
        we need to populate experiment table.
        """
        tnsconnect = self.connect.tns_connect()
        dbexec = Dbexecute(tnsconnect)
        sn = dbexec.insert_experiment(20150101025)
        data_list = [sn, 1, 'MEAN', 7, 0.99, 80, 78, 45, 2, '<xml>']
        retval = dbexec.insert_experiment_best(data_list)

        self.assertEqual(True, retval)

        # After insertion is done first need to delete in child table
        retval = dbexec.execute_query(
            "DELETE from experiment_best where exp_id=" + str(sn))

        self.assertEqual(True, retval)
        # After child records deleted, safely delete parent

        retval = dbexec.execute_query("DELETE from experiment where sn=" +
                                      str(sn))

        self.assertEqual(True, retval)

    def test_update_experiment(self):
        """Test update statement for experiment table.

        Since this table to update the end time we first need to
        populate the values.
        """
        tnsconnect = self.connect.tns_connect()
        dbexec = Dbexecute(tnsconnect)
        sn = dbexec.insert_experiment(20150101025)

        # Update end time
        retval = dbexec.execute_query("UPDATE experiment \
            set end_date=timezone('utc'::text, now()) where sn=" + str(sn))

        self.assertEqual(True, retval)

        retval = dbexec.execute_query("DELETE from experiment where sn=" +
                                      str(sn))

        self.assertEqual(True, retval)
Beispiel #6
0
    def __init__(self,
                 N,
                 width,
                 height,
                 grid=10,
                 iter=100000,
                 xmlstrings=None,
                 seed=None,
                 viewer=False,
                 pname=None):
        """Initialize the attributes."""
        if seed is None:
            super(SimModelComm, self).__init__(seed=None)
        else:
            super(SimModelComm, self).__init__(seed)

        self.runid = datetime.datetime.now().timestamp()
        self.runid = str(self.runid).replace(
            '.', '') + '-' + str(prob).replace('.', '')

        #self.runid = datetime.datetime.now().strftime(
        #    "%s") + str(self.random.randint(1, 1000, 1)[0])

        if pname is None:
            self.pname = os.getcwd() + '/' + self.runid + "SForagingSimulation"
        else:
            self.pname = pname + '/' + self.runid + "SForagingSimulation"
        # self.pname = os.getcwd() + '/' + self.runid + "SFCommSimulation"

        self.width = width
        self.height = height
        self.stepcnt = 1
        self.iter = iter
        self.xmlstrings = xmlstrings

        self.viewer = viewer

        # Create db connection
        connect = Connect('swarm', 'swarm', 'swarm', 'localhost')
        self.connect = connect.tns_connect()

        # Fill out the experiment table
        self.experiment = Experiment(self.connect,
                                     self.runid,
                                     N,
                                     seed,
                                     'Simuation SFComm',
                                     iter,
                                     width,
                                     height,
                                     grid,
                                     phenotype=xmlstrings[0])

        self.experiment.insert_experiment_simulation()

        self.sn = self.experiment.sn

        # Create a folder to store results
        os.mkdir(self.pname)

        self.num_agents = N

        self.grid = Grid(width, height, grid)

        self.schedule = SimultaneousActivation(self)

        # self.site = Sites(id=1, location=(5, 5), radius=11, q_value=0.5)

        # self.grid.add_object_to_grid(self.site.location, self.site)

        # self.hub = Hub(id=1, location=(0, 0), radius=11)

        # self.grid.add_object_to_grid(self.hub.location, self.hub)

        self.agents = []

        bound = np.ceil((self.num_agents * 1.0) / len(self.xmlstrings))

        j = 0
        # Create agents
        for i in range(self.num_agents):
            # print (i, j, self.xmlstrings[j])
            a = SimAgent(i, self, xmlstring=self.xmlstrings[j])
            self.schedule.add(a)
            # Add the agent to a random grid cell
            # x = self.random.randint(
            #    -self.grid.width / 2, self.grid.width / 2)
            x = 0
            # y = self.random.randint(
            #    -self.grid.height / 2, self.grid.height / 2)
            y = 0

            a.location = (x, y)
            self.grid.add_object_to_grid((x, y), a)
            a.operation_threshold = 2  # self.num_agents // 10
            self.agents.append(a)

            if (i + 1) % bound == 0:
                j += 1