Пример #1
0
    def test_counter_agent_history(self):
        """
        The evolution of the state should be recorded in the logging agent
        """
        config = {
            'name': 'CounterAgent',
            'network_params': {
                'path': join(ROOT, 'test.gexf')
            },
            'network_agents': [{
                'agent_type': 'AggregatedCounter',
                'weight': 1,
                'state': {'id': 0}

            }],
            'max_time': 10,
            'environment_params': {
            }
        }
        s = simulation.from_config(config)
        env = s.run_simulation(dry_run=True)[0]
        for agent in env.network_agents:
            last = 0
            assert len(agent[None, None]) == 10
            for step, total in sorted(agent['total', None]):
                assert total == last + 2
                last = total
Пример #2
0
 def test_counter_agent(self):
     """
     The initial states should be applied to the agent and the
     agent should be able to update its state."""
     config = {
         'name': 'CounterAgent',
         'dry_run': True,
         'network_params': {
             'path': join(ROOT, 'test.gexf')
         },
         'agent_type': 'CounterModel',
         'states': [{
             'times': 10
         }, {
             'times': 20
         }],
         'max_time': 2,
         'num_trials': 1,
         'environment_params': {}
     }
     s = simulation.from_config(config)
     env = s.run_simulation(dry_run=True)[0]
     assert env.get_agent(0)['times', 0] == 11
     assert env.get_agent(0)['times', 1] == 12
     assert env.get_agent(1)['times', 0] == 21
     assert env.get_agent(1)['times', 1] == 22
Пример #3
0
 def test_empty_simulation(self):
     """A simulation with a base behaviour should do nothing"""
     config = {
         'network_params': {
             'path': join(ROOT, 'test.gexf')
         },
         'agent_type': 'BaseAgent',
         'environment_params': {
         }
     }
     s = simulation.from_config(config)
     s.run_simulation(dry_run=True)
Пример #4
0
 def test_configuration_changes(self):
     """
     The configuration should not change after running
      the simulation.
     """
     config = serialization.load_file(join(EXAMPLES, 'complete.yml'))[0]
     s = simulation.from_config(config)
     for i in range(5):
         s.run_simulation(dry_run=True)
         nconfig = s.to_dict()
         del nconfig['topology']
         assert config == nconfig
Пример #5
0
 def wrapped(self):
     root = os.getcwd()
     os.chdir(os.path.dirname(path))
     s = simulation.from_config(config)
     envs = s.run_simulation(dry_run=True)
     assert envs
     for env in envs:
         assert env
         try:
             n = config['network_params']['n']
             assert len(env.get_agents()) == n
         except KeyError:
             pass
     os.chdir(root)
Пример #6
0
 def test_configuration_changes(self):
     """
     The configuration should not change after running
      the simulation.
     """
     config = utils.load_file('examples/complete.yml')[0]
     s = simulation.from_config(config)
     for i in range(5):
         s.run_simulation(dry_run=True)
         nconfig = s.to_dict()
         del nconfig['topology']
         del nconfig['dry_run']
         del nconfig['load_module']
         assert config == nconfig
Пример #7
0
 def test_yaml(self):
     """
     The YAML version of a newly created simulation
     should be equivalent to the configuration file used
     """
     with utils.timer('loading'):
         config = serialization.load_file(join(EXAMPLES, 'complete.yml'))[0]
         s = simulation.from_config(config)
     with utils.timer('serializing'):
         serial = s.to_yaml()
     with utils.timer('recovering'):
         recovered = yaml.load(serial)
     with utils.timer('deleting'):
         del recovered['topology']
     assert config == recovered
Пример #8
0
 def test_basic(self):
     config = {
         'name': 'exporter_sim',
         'network_params': {},
         'agent_type': 'CounterModel',
         'max_time': 2,
         'num_trials': 5,
         'environment_params': {}
     }
     s = simulation.from_config(config)
     s.run_simulation(exporters=[Dummy], dry_run=True)
     assert Dummy.started
     assert Dummy.ended
     assert Dummy.trials == 5
     assert Dummy.total_time == 2 * 5
Пример #9
0
    def test_writing(self):
        '''Try to write CSV, GEXF, sqlite and YAML (without dry_run)'''
        n_trials = 5
        config = {
            'name': 'exporter_sim',
            'network_params': {
                'generator': 'complete_graph',
                'n': 4
            },
            'agent_type': 'CounterModel',
            'max_time': 2,
            'num_trials': n_trials,
            'environment_params': {}
        }
        output = io.StringIO()
        s = simulation.from_config(config)
        tmpdir = tempfile.mkdtemp()
        envs = s.run_simulation(exporters=[
            exporters.default,
            exporters.csv,
            exporters.gexf,
            exporters.distribution,
        ],
                                outdir=tmpdir,
                                exporter_params={'copy_to': output})
        result = output.getvalue()

        simdir = os.path.join(tmpdir, s.group or '', s.name)
        with open(os.path.join(simdir, '{}.dumped.yml'.format(s.name))) as f:
            result = f.read()
            assert result

        try:
            for e in envs:
                with open(os.path.join(simdir, '{}.gexf'.format(e.name))) as f:
                    result = f.read()
                    assert result

                with open(os.path.join(simdir, '{}.csv'.format(e.name))) as f:
                    result = f.read()
                    assert result
        finally:
            shutil.rmtree(tmpdir)
Пример #10
0
 def test_torvalds_example(self):
     """A complete example from a documentation should work."""
     config = serialization.load_file(join(EXAMPLES, 'torvalds.yml'))[0]
     config['network_params']['path'] = join(EXAMPLES,
                                             config['network_params']['path'])
     s = simulation.from_config(config)
     env = s.run_simulation(dry_run=True)[0]
     for a in env.network_agents:
         skill_level = a.state['skill_level']
         if a.id == 'Torvalds':
             assert skill_level == 'God'
             assert a.state['total'] == 3
             assert a.state['neighbors'] == 2
         elif a.id == 'balkian':
             assert skill_level == 'developer'
             assert a.state['total'] == 3
             assert a.state['neighbors'] == 1
         else:
             assert skill_level == 'beginner'
             assert a.state['total'] == 3
             assert a.state['neighbors'] == 1
Пример #11
0
    def test_custom_agent(self):
        """Allow for search of neighbors with a certain state_id"""
        config = {
            'network_params': {
                'path': join(ROOT, 'test.gexf')
            },
            'network_agents': [{
                'agent_type': CustomAgent,
                'weight': 1

            }],
            'max_time': 10,
            'environment_params': {
            }
        }
        s = simulation.from_config(config)
        env = s.run_simulation(dry_run=True)[0]
        assert env.get_agent(0).state['neighbors'] == 1
        assert env.get_agent(0).state['neighbors'] == 1
        assert env.get_agent(1).count_agents(state_id='normal') == 2
        assert env.get_agent(1).count_agents(state_id='normal', limit_neighbors=True) == 1
Пример #12
0
 def test_distribution(self):
     '''The distribution exporter should write the number of agents in each state'''
     config = {
         'name': 'exporter_sim',
         'network_params': {
             'generator': 'complete_graph',
             'n': 4
         },
         'agent_type': 'CounterModel',
         'max_time': 2,
         'num_trials': 5,
         'environment_params': {}
     }
     output = io.StringIO()
     s = simulation.from_config(config)
     s.run_simulation(exporters=[exporters.distribution],
                      dry_run=True,
                      exporter_params={'copy_to': output})
     result = output.getvalue()
     assert 'count' in result
     assert 'SEED,Noneexporter_sim_trial_3,1,,1,1,1,1' in result
Пример #13
0
 def wrapped(self):
     root = os.getcwd()
     os.chdir(os.path.dirname(path))
     s = simulation.from_config(config)
     iterations = s.max_time * s.num_trials
     if iterations > 1000:
         s.max_time = 100
         s.num_trials = 1
     if config.get('skip_test', False) and not FORCE_TESTS:
         self.skipTest('Example ignored.')
     envs = s.run_simulation(dry_run=True)
     assert envs
     for env in envs:
         assert env
         try:
             n = config['network_params']['n']
             assert len(list(env.network_agents)) == n
             assert env.now > 2  # It has run
             assert env.now <= config['max_time']  # But not further than allowed
         except KeyError:
             pass
     os.chdir(root)
Пример #14
0
    def test_custom_agent(self):
        """Allow for search of neighbors with a certain state_id"""
        class CustomAgent(agents.BaseAgent):
            def step(self):
                self.state['neighbors'] = self.count_agents(state_id=0,
                                                            limit_neighbors=True)
        config = {
            'network_params': {
                'path': join(ROOT, 'test.gexf')
            },
            'network_agents': [{
                'agent_type': CustomAgent,
                'weight': 1,
                'state': {'id': 0}

            }],
            'max_time': 10,
            'environment_params': {
            }
        }
        s = simulation.from_config(config)
        env = s.run_simulation(dry_run=True)[0]
        assert env.get_agent(0).state['neighbors'] == 1
Пример #15
0
 def setUp(self):
     """
     The initial states should be applied to the agent and the
     agent should be able to update its state."""
     config = {
         'name': 'analysis',
         'seed': 'seed',
         'network_params': {
             'generator': 'complete_graph',
             'n': 2
         },
         'agent_type': Ping,
         'states': [{
             'interval': 1
         }, {
             'interval': 2
         }],
         'max_time': 30,
         'num_trials': 1,
         'environment_params': {}
     }
     s = simulation.from_config(config)
     self.env = s.run_simulation(dry_run=True)[0]