def test_simulation_random_vacancy_picker(self):
        # array = [
        # 	np.array([
        # 		[0, 0, 0, 0],
        # 		[1, 1, 1, 1],
        # 		[1, 1, 1, 1],
        # 		[1, 1, 2, 2]
        # 	]),
        # ]

        possible_states = [
            np.array([[1, 0, 0, 0], [1, 1, 1, 1], [1, 1, 0, 1], [1, 1, 2, 2]]),
            np.array([[0, 1, 0, 0], [1, 1, 1, 1], [1, 1, 0, 1], [1, 1, 2, 2]]),
            np.array([[0, 0, 1, 0], [1, 1, 1, 1], [1, 1, 0, 1], [1, 1, 2, 2]]),
            np.array([[0, 0, 0, 1], [1, 1, 1, 1], [1, 1, 0, 1], [1, 1, 2, 2]]),
        ]

        possible_states_reached = set()

        def callback(array, result, iteration):
            if iteration == 1:
                with self.subTest(out=np.copy(array)):
                    is_possible_state = False
                    for i, state in enumerate(possible_states):
                        if np.array_equal(array, state):
                            is_possible_state = True
                            possible_states_reached.add(i)
                            break
                    self.assertTrue(is_possible_state)

        settings = SimulationSettings(grid_size=4,
                                      vacancy_proportion=0.25,
                                      agent_proportions=(10 / 12, 2 / 12),
                                      initial_random_allocation=False,
                                      utility_function=create_flat_utility(1 /
                                                                           8),
                                      satisficers=False,
                                      agent_picking_regime='first',
                                      vacancy_picking_regime='random',
                                      radius=1,
                                      iterations=2,
                                      save_period=1)

        # Assume all states should be reached in 30 tries
        for i in range(30):
            run_simulation(settings, callback)

        with self.subTest():
            self.assertEqual(len(possible_states_reached),
                             len(possible_states))
    def test_run_simulation_vacancies_counted(self):
        iteration_states = [
            np.array([
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [1, 1, 1, 1],
                [2, 2, 2, 2],
            ]),
            np.array([
                [2, 0, 0, 0],
                [0, 0, 0, 0],
                [1, 1, 1, 1],
                [0, 2, 2, 2],
            ]),
            np.array([
                [2, 2, 0, 0],
                [0, 0, 0, 0],
                [1, 1, 1, 1],
                [0, 0, 2, 2],
            ]),
            np.array([
                [2, 2, 2, 0],
                [0, 0, 0, 0],
                [1, 1, 1, 1],
                [0, 0, 0, 2],
            ]),
            np.array([
                [2, 2, 2, 2],
                [0, 0, 0, 0],
                [1, 1, 1, 1],
                [0, 0, 0, 0],
            ]), None
        ]  # simulation halted, should not fail at none

        def callback(array, result, iteration):
            expected_output = iteration_states[iteration]
            with self.subTest(i=iteration, out=array,
                              expected=expected_output):
                self.assertTrue(np.array_equal(array, expected_output))

        settings = SimulationSettings(
            grid_size=4,
            vacancy_proportion=0.5,
            agent_proportions=(0.5, 0.5),
            initial_random_allocation=False,
            utility_function=create_flat_utility(0.5),
            satisficers=False,
            agent_picking_regime='first',
            vacancy_picking_regime='first',
            count_vacancies=True,
            radius=1,
            iterations=len(iteration_states),
            save_period=1)

        result = run_simulation(settings, callback)

        clusters = [2, 3, 3, 3, 2]
        with self.subTest():
            self.assertEqual(result.get_measures()['clusters'], clusters)
Esempio n. 3
0
def simulation(grid_size, vacancy_proportion, agent_proportion,
               initial_random_allocation, utility_function, satisficers,
               agent_picking_regime, vacancy_picking_regime,
               agent_roulette_base_weight, vacancy_roulette_base_weight,
               radius, absolute_unf, segregation_measure, iterations, save_to,
               save_period, verbose):
    """Command line interface for the Schelling simulation."""

    ut_name = utility_function[0]
    ut_arg = utility_function[1]

    create_utility = _utility_function_creators[ut_name]

    utility = create_utility(ut_arg)

    if agent_picking_regime != 'roulette':
        agent_roulette_base_weight = None
    if vacancy_picking_regime != 'roulette':
        vacancy_roulette_base_weight = None

    settings = SimulationSettings(
        grid_size=grid_size,
        vacancy_proportion=vacancy_proportion,
        agent_proportions=agent_proportion,
        initial_random_allocation=initial_random_allocation,
        utility_function=utility,
        satisficers=satisficers,
        agent_picking_regime=agent_picking_regime,
        vacancy_picking_regime=vacancy_picking_regime,
        agent_roulette_base_weight=agent_roulette_base_weight,
        vacancy_roulette_base_weight=vacancy_roulette_base_weight,
        radius=radius,
        count_vacancies=absolute_unf,
        segregation_measure_names=list(segregation_measure),
        iterations=iterations,
        save_period=save_period)

    if os.path.exists(save_to):
        if not os.path.isdir(save_to):
            print("Not a directory: " + save_to)
            sys.exit(1)
    else:
        os.mkdir(save_to)

    save_callback = get_save_state_callback(save_to, iterations, verbose)

    result = run_simulation(settings, save_callback)

    result.save_JSON(os.path.join(save_to, 'result.json'))

    if verbose:
        print("done!")
    def test_simulation_satisficers(self):
        iteration_states = [
            np.array([
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [1, 1, 1, 1],
                [1, 1, 1, 1],
            ]),
        ] + ([
            np.array([
                [1, 0, 0, 0],
                [0, 0, 0, 0],
                [0, 1, 1, 1],
                [1, 1, 1, 1],
            ]),
            np.array([
                [0, 1, 0, 0],
                [0, 0, 0, 0],
                [0, 1, 1, 1],
                [1, 1, 1, 1],
            ]),
        ] * 100)  # oscillates forever

        def callback(array, result, iteration):
            expected_output = iteration_states[iteration]
            with self.subTest(i=iteration, out=array,
                              expected=expected_output):
                self.assertTrue(np.array_equal(array, expected_output))

        settings = SimulationSettings(
            grid_size=4,
            vacancy_proportion=0.5,
            agent_proportions=(1.0, ),
            initial_random_allocation=False,
            utility_function=create_flat_utility(0.5),
            satisficers=True,
            agent_picking_regime='first',
            vacancy_picking_regime='first',
            radius=1,
            iterations=len(iteration_states),
            save_period=1)

        result = run_simulation(settings, callback)

        clusters = [1] + ([2, 2] * 100)
        with self.subTest():
            self.assertEqual(result.get_measures()['clusters'], clusters)
    def test_simulation_halted(self):
        all_satisfied_array = np.array([
            [0, 0, 0, 0],
            [0, 0, 0, 0],
            [1, 1, 1, 1],
            [1, 1, 1, 1],
        ])

        callback_count = [0]
        expected_callback_count = 1

        def callback(array, result, iteration):
            expected_output = all_satisfied_array
            with self.subTest():
                self.assertTrue(np.array_equal(array, expected_output))
            callback_count[0] += 1

        settings = SimulationSettings(
            grid_size=4,
            vacancy_proportion=0.5,
            agent_proportions=(1.0, ),
            initial_random_allocation=False,
            utility_function=create_flat_utility(0.5),
            satisficers=False,
            agent_picking_regime='first',
            vacancy_picking_regime='first',
            radius=1,
            iterations=100,
            save_period=1)

        result = run_simulation(settings, callback)

        clusters = [1]
        with self.subTest():
            self.assertEqual(result.get_measures()['clusters'], clusters)

        with self.subTest():
            self.assertEqual(callback_count[0], expected_callback_count)
Esempio n. 6
0
if __name__ == '__main__': # pragma: no cover
	"""
	This will run the Schelling Model simulation for 10000 iterations.
	Every 100 iterations the state will be printed to console  and the array 
	will be saved as an image.
	The simulation result, containing segregation measures for each iteration
	will be saved as JSON and a plot will be shown.
	"""
	from schelling.simulation import run_simulation, get_save_state_callback
	from schelling.utility_functions import create_flat_utility
	from schelling.arr_to_img import image_save, to_image
	from schelling.simulation_settings import SimulationSettings
	import os

	settings = SimulationSettings(
			grid_size=40,
			vacancy_proportion=0.2,
			agent_proportions=(0.5, 0.5),
			utility_function=create_flat_utility(5/8),
			iterations=10000,
			save_period=100
		)

	# assuming ./image/ directory exists
	save_callback = get_save_state_callback('./image/', settings.iterations, 
		verbose=True)

	simulation_result = run_simulation(settings, callback=save_callback)
	simulation_result.save_JSON('result.json')
	simulation_result.plot_measures()