def test_run_simulation(self): # test whether its possible to pass custom classes attribute_component = RandomCategoricalInitializer.RandomCategoricalInitializer() focal_agent_component = RandomSelector.RandomSelector() neighbor_component = RandomNeighborSelector.RandomNeighborSelector() influence_component = SimilarityAdoption.SimilarityAdoption(regime="one-to-many") dissimilarity_measure = dissimilarity_calculator.select_calculator("hamming") simulation = Simulation(attributes_initializer=attribute_component, focal_agent_selector=focal_agent_component, neighbor_selector=neighbor_component, influence_function=influence_component, dissimilarity_measure=dissimilarity_measure, communication_regime="one-to-many") pdf = simulation.run() print(pdf)
def create_and_run_simulation(self, parameter_dict): simulation = Simulation( network=self.network, topology=self.topology, attributes_initializer=self.initialization, focal_agent_selector=self.focal_agent_selector, neighbor_selector=self.neighbor_selector, influence_function=self.influence_function, influenceable_attributes=self.influencable_attributes, stop_condition=self.stop_condition, max_iterations=self.max_iterations, network_modifier=self.network_modifier, dissimilarity_measure=self.dissimilarity_measure, communication_regime=parameter_dict["communication_regime"], parameter_dict=parameter_dict) return simulation.run()
def _create_and_run_simulation(self, parameter_dict): simulation = Simulation( network=self.network.copy() if isinstance(self.network, nx.Graph) else self.network, topology=self.topology, network_modifiers=self.network_modifiers, attributes_initializer=self.attributes_initializer, focal_agent_selector=self.focal_agent_selector, neighbor_selector=self.neighbor_selector, influence_function=self.influence_function, influenceable_attributes=self.influenceable_attributes, stop_condition=self.stop_condition, max_iterations=self.max_iterations, communication_regime=parameter_dict["communication_regime"], parameter_dict=parameter_dict, dissimilarity_measure=self.dissimilarity_measure, output_realizations=self.output_realizations, tickwise=self.tickwise, seed=parameter_dict['seed']) return simulation.run(show_progress=False)
class TestConvergence(TestCase): simulation = Simulation(attributes_initializer="random_continuous", influence_function="bounded_confidence", dissimilarity_measure="euclidean", communication_regime="one-to-many", parameter_dict = {'confidence_bound': 0.5}) def test_max_iterations(self): self.simulation.max_iterations = 10 self.simulation.stop_condition = 'max_iteration' results = self.simulation.run() print(results) def test_pragmatic_convergence(self): self.simulation.max_iterations = 4000 self.simulation.stop_condition = 'pragmatic_convergence' results = self.simulation.run() print(results) assert(results['Ticks'][0] < self.simulation.max_iterations) def test_opinion_distance_convergence(self): self.simulation.max_iterations = 4000 self.simulation.stop_condition = 'strict_convergence' self.simulation.parameter_dict['threshold'] = 0.5 results = self.simulation.run() print(results) assert(results['Ticks'][0] < self.simulation.max_iterations) def test_convergence_instance(self): self.simulation.max_iterations = 4000 self.simulation.stop_condition = OpinionDistanceConvergenceCheck(maximum= 0.5) self.simulation.parameter_dict = {'confidence_bound': 0.5} results = self.simulation.run() print(results) assert(results['Ticks'][0] < self.simulation.max_iterations)
def estimate_runtime(self, sample_runs: int = None, sample_steps: int = 10): """ If simulations are specified, this function infers the experiment runtime from sampled runs/steps. If no simulations are specified, function creates the parameterDictList if that hasn't happened already and then infers from sampled runs the runtime of the whole experiment. Runtime estimates are for running on a single core. :param int=None sample_runs: The number of entries in the parameterDictList to sample in order to estimate the runtime. :param int=10 sample_steps: The number of iterations executed in each simulation run to base the estimated runtime on. :returns: estimated time of simulation in seconds """ if self.simulations is not None: # make copy to prevent modifying simulations which must be run later simulations_copy = copy.deepcopy(self.simulations) # Select parameter combinations to test (subset of all simulations in the experiment) if sample_runs is not None and sample_runs < len(simulations_copy): simulations_to_run = random.sample(simulations_copy, sample_runs) else: simulations_to_run = simulations_copy if sample_runs is not None and sample_runs > len( simulations_copy): warnings.warn( "Reducing number of sampled simulations to total number of simulations in the experiment." ) else: if self.stop_condition != "max_iteration": warnings.warn( "Runtime estimates are based on max number of iterations. Runtime estimates for simulations with different stop conditions are highly unreliable." ) if sample_steps > self.max_iterations: warnings.warn( "Number of sample steps greater than max iterations of the simulations." ) # Create parameter_dict_list if not set yet if len(self.parameter_dict_list) == 0: self.parameter_dict_list = self._create_parameter_dictionaries( ) # Select parameter combinations to test (subset of all simulations in the experiment) if sample_runs is not None and sample_runs < len( self.parameter_dict_list): selected_parameter_combinations = random.sample( self.parameter_dict_list, sample_runs) else: selected_parameter_combinations = self.parameter_dict_list if sample_runs is not None and sample_runs > len( self.parameter_dict_list): warnings.warn( "Reducing number of sampled simulations to total number of simulations in the experiment." ) # Set up simulations simulations_to_run = [] for parameter_combination in selected_parameter_combinations: simulations_to_run.append( Simulation( network=self.network.copy() if self.network is not None else self.network, topology=self.topology, network_modifiers=self.network_modifiers, attributes_initializer=self.attributes_initializer, focal_agent_selector=self.focal_agent_selector, neighbor_selector=self.neighbor_selector, influence_function=self.influence_function, influenceable_attributes=self.influenceable_attributes, stop_condition=self.stop_condition, max_iterations=self.max_iterations, communication_regime=parameter_combination[ "communication_regime"], parameter_dict=parameter_combination, dissimilarity_measure=self.dissimilarity_measure, output_realizations=self.output_realizations, tickwise=self.tickwise, seed=parameter_combination["seed"])) # Setup each simulation and record mean setup time sampled_setup_times = [ timeit.timeit(lambda: sim.initialize(), number=1) for sim in simulations_to_run ] mean_setup_time = np.mean(sampled_setup_times) # Execute single steps of each simulation (sample_steps times per simulation) and record mean time per step sampled_execution_times = [ timeit.timeit(lambda: sim.run_step(), number=sample_steps) for sim in simulations_to_run ] mean_execution_time = np.mean(sampled_execution_times) / sample_steps if self.simulations is not None: num_simulations = len(self.simulations) warnings.warn( "Runtime estimates are based on {} iterations because true maximum iterations for user-defined simulations are unknown." .format(self.max_iterations)) else: num_simulations = len(self.parameter_dict_list) # Estimated time in seconds based on number of simulations, setup time and step time # Assumes that simulations run until max iterations return num_simulations * mean_setup_time + ( num_simulations * mean_execution_time * self.max_iterations)
from defSim.Experiment import Experiment from defSim.tools.CreateOutputTable import OutputTableCreator import pandas as pd import numpy as np import timeit import os class TestCustomOutput(OutputTableCreator): @staticmethod def create_output(**kwargs): return "CustomOutput" ## Standard output simulation = Simulation(topology="grid", influence_function="axelrod", stop_condition="strict_convergence", communication_regime="one-to-one", parameter_dict={"num_agents": 225, "neighborhood": "von_neumann", "num_features": 7, "num_traits": 15}, max_iterations=100) results = simulation.run() with open("output_test.csv", "w+") as output_file: results.to_csv(output_file, sep=";", index=False) print("results written to: %s" % os.path.abspath("output_test.csv")) ## Tickwise output simulation = Simulation(topology="grid", influence_function="axelrod", stop_condition="strict_convergence", communication_regime="one-to-one", parameter_dict={"num_agents": 225, "neighborhood": "von_neumann", "num_features": 7, "num_traits": 15}, tickwise = ['Isolates', TestCustomOutput, 'f02'], max_iterations=100)
:param network: A networkx graph on which to calculate polarization :return: A single value for polarization, between 0 and 1. """ distances = list(nx.get_edge_attributes(network, 'dist').values()) return np.var(distances) simulation = Simulation(topology='grid', attributes_initializer="random_continuous", focal_agent_selector='random', neighbor_selector='random', influence_function='weighted_linear', dissimilarity_measure="euclidean", stop_condition='max_iteration', max_iterations=25000, communication_regime='one-to-one', parameter_dict={'homophily': 2}, output_realizations=[PolarizationReporter]) print(simulation.run()) experiment = Experiment(topology='grid', attributes_initializer="random_continuous", focal_agent_selector='random', neighbor_selector='random', influence_function='weighted_linear', dissimilarity_measure="euclidean", stop_condition='max_iteration',
def test_spread_influence(self): simulation = Simulation(influence_function="persuasion", max_iterations=100, communication_regime="one-to-one") simulation.run()
random.seed("random") for i in range(2000000): agentid = focal_agent_sim.select_focal_agent(network, "random", agents5000) neighborsid = neighbor_selector_sim.select_neighbors( network, "random", agentid, "one-to-many") influence_sim.spread_influence(network, "axelrod", [agentid], neighborsid, list(all_attributes), "one-to-many") #print("2000000 simulation steps in a network with 5000 agents and one-to-one communication take %f seconds" %(timeit.timeit(timeIterationStepOneToOne5000, number=1))) #print("2000000 simulation steps in a network with 5000 agents and one-to-many communication take %f seconds" %(timeit.timeit(timeIterationStepOneToMany5000, number=1))) simulation49 = Simulation(topology="grid", influence_function="axelrod", stop_condition="max_iteration") random.seed("random") def timeSimulationOneToOne49(): for i in range(100): simulation49.run() simulation5000 = Simulation(topology="grid", influence_function="axelrod", stop_condition="max_iteration", parameter_dict={"num_agents": 5000})