Esempio n. 1
0
    def test_network_list(self):
        network1 = network_init.generate_network("grid")
        network2 = network_init.generate_network("ring")

        experiment = Experiment(
            network = 'list',
            attributes_initializer = 'random_continuous',
            influence_function = 'bounded_confidence',
            network_parameters = {
                'network': [network1, network2]
            }
            )

        print(experiment.run())
class TestDissimilarityCalculator(TestCase):
    networkTest = network_init.generate_network("grid")
    networkCategorical = network_init.generate_network("grid")
    networkContinuous = network_init.generate_network("grid")

    def test_HammingDistance_calculate_dissimilarity(self):
        self.networkTest.nodes[0]["a"] = 0.5
        self.networkTest.nodes[0]["b"] = 0.6
        self.networkTest.nodes[1]["a"] = 0.3
        self.networkTest.nodes[1]["b"] = 0.6
        self.assertEqual(
            HammingDistance().calculate_dissimilarity(self.networkTest, 0, 1),
            0.5)

    def test_HammingDistance_calculate_dissimilarity_networkwide(self):
        agents_init.initialize_attributes(self.networkCategorical,
                                          "random_categorical")
        agents_init.initialize_attributes(self.networkContinuous,
                                          "random_continuous")
        HammingDistance().calculate_dissimilarity_networkwide(
            self.networkContinuous)
        HammingDistance().calculate_dissimilarity_networkwide(
            self.networkCategorical)

    networkCategorical2 = network_init.generate_network("grid")
    networkContinuous2 = network_init.generate_network("grid")

    def test_EuclideanDistance_calculate_dissimilarity(self):
        self.networkTest.nodes[0]["a"] = 0.5
        self.networkTest.nodes[1]["a"] = 0.3
        self.assertEqual(
            EuclideanDistance().calculate_dissimilarity(
                self.networkTest, 0, 1), 0.2)
        self.networkTest.nodes[0]["b"] = 0.2
        self.networkTest.nodes[1]["c"] = 0.8
        self.assertEqual(
            EuclideanDistance().calculate_dissimilarity(
                self.networkTest, 0, 1),
            math.sqrt((0.5 - 0.3)**2 + (0.2 - 0.8)**2) / math.sqrt(2))

    def test_EuclideanDistance_calculate_dissimilarity_networkwide(self):
        agents_init.initialize_attributes(self.networkCategorical2,
                                          "random_categorical")
        agents_init.initialize_attributes(self.networkContinuous2,
                                          "random_continuous")
        EuclideanDistance().calculate_dissimilarity_networkwide(
            self.networkContinuous2)
        EuclideanDistance().calculate_dissimilarity_networkwide(
            self.networkCategorical2)
Esempio n. 3
0
    def test_spread_influence(self):
        network1 = network_init.generate_network("grid", **{"num_agents": 4})
        agents_init.initialize_attributes(network1, "random_continuous",
                                          **{"num_features": 1})
        EuclideanDistance().calculate_dissimilarity_networkwide(network1)

        # run one instance to see if it doesn't break (most simple test)
        WeightedLinear.WeightedLinear(
            regime="one-to-many",
            **{
                "convergence_rate": 0.5,
                "homophily": 1,
                "bi_directional": False
            }).spread_influence(network1,
                                0, [neighbor for neighbor in network1[0]],
                                attributes=None,
                                dissimilarity_measure=EuclideanDistance())

        # with bi-directional influence, let two agents find agreement
        WeightedLinear.WeightedLinear(
            regime="one-to-one",
            **{
                "convergence_rate": 0.5,
                "homophily": 0,
                "bi_directional": True
            }).spread_influence(
                network1,
                1,  #sending agent
                0,  #receiving agent
                attributes=None,
                dissimilarity_measure=EuclideanDistance())
        self.assertEqual(network1.nodes[1]['f01'], network1.nodes[0]['f01'])
Esempio n. 4
0
class TestNetworkRewiring(TestCase):

    network = network_init.generate_network("grid")

    def test_rewire_network(self):
        initial_edges = list(self.network.edges)
        network_evolution_sim.rewire_network(network=self.network,
                                             realization='maslov_sneppen',
                                             **{"rewiring_prop": 0.1})
        self.assertNotEqual(initial_edges, list(self.network.edges))

    @unittest.expectedFailure
    def test_rewire_network_bad_realization(self):
        network_evolution_sim.rewire_network(network=self.network,
                                             realization='thisisnotreal')

    def test_MaslovSneppen(self):
        initial_edges = list(self.network.edges)
        MaslovSneppenModifier(rewiring_prop=0.1).rewire_network(
            network=self.network)
        self.assertNotEqual(initial_edges, list(self.network.edges))

        initial_edges = list(self.network.edges)
        MaslovSneppenModifier(rewiring_exact=4).rewire_network(
            network=self.network)
        self.assertNotEqual(initial_edges, list(self.network.edges))

        initial_edges = list(self.network.edges)
        MaslovSneppenModifier(
            rewiring_prop=0.1,
            rewiring_exact=10).rewire_network(network=self.network)
        self.assertNotEqual(initial_edges, list(self.network.edges))
Esempio n. 5
0
def test_spatial_random_graph():
    graph = network_init.generate_network(
        "spatial_random_graph", **{
            "num_agents": 16,
            "min_neighbors": 8
        })

    assert type(graph) is nx.Graph
Esempio n. 6
0
def timeIterationStepOneToOne9():
    network = network_init.generate_network("grid", **{"num_agents": 9})
    agents_init.initialize_attributes(network, "random")
    all_attributes = network.nodes[1].keys()
    random.seed("random")
    for i in range(2000000):
        agentid = focal_agent_sim.select_focal_agent(network, "random")
        neighborsid = neighbor_selector_sim.select_neighbors(
            network, "random", agentid, "one-to-one")
        influence_sim.spread_influence(network, "axelrod",
                                       [agentid], neighborsid,
                                       list(all_attributes), "one-to-one")
Esempio n. 7
0
def timeIterationStepOneToMany49Overlap():
    network = network_init.generate_network("grid")
    agents_init.initialize_attributes(network, "random")
    all_attributes = network.nodes[1].keys()
    random.seed("random")
    for i in range(2000000):
        agentid = focal_agent_sim.select_focal_agent(network, "random")
        neighborsid = neighbor_selector_sim.select_neighbors(
            network, "random", agentid, "one-to-many")
        influence_sim.spread_influence(network, "stochasticOverlap",
                                       agentid, neighborsid,
                                       list(all_attributes), "one-to-many")
Esempio n. 8
0
    def initialize(self):
        """
        This method initializes the network if none is given, applies network modifiers, initializes the attributes of the agents, 
        and also computes and sets the distances between each neighbor.
        """

        # reset steps
        self.time_steps = 0
        self.influence_steps = 0

        # reset tickwise output
        self.initialize_tickwise_output()

        if self.seed is None:
            self.seed = random.randint(10000, 99999)
        random.seed(self.seed)
        self.parameter_dict['np_random_generator'] = np.random.default_rng(self.seed)

        ## if deprecated ms_rewiring parameter is set in parameter dict, replace with network modifier
        if 'ms_rewiring' in list(self.parameter_dict.keys()):
            warnings.warn(
                "Setting ms_rewiring in parameter dict is deprecated. Pass an instance of MaslovSneppenModifier in network_modifiers instead.",
                DeprecationWarning)
            if self.network_modifiers is None:
                self.network_modifiers = [MaslovSneppenModifier(rewiring_prop=self.parameter_dict['ms_rewiring'])]
            else:
                self.network_modifiers.append(MaslovSneppenModifier(rewiring_prop=self.parameter_dict['ms_rewiring']))

                # read or generate network if no nx.Graph was provided, apply network modifiers
        if self.network_provided:
            if self.network == 'list':
                self.network = self.parameter_dict.pop('network')
            if not isinstance(self.network, nx.Graph) and self.network is not None:
                self.network = network_init.read_network(self.network)

            ## apply network modifiers
            if self.network_modifiers is not None:
                for modifier in self.network_modifiers:
                    modifier.rewire_network(network)
        else:
            self.network = network_init.generate_network(self.topology, network_modifiers=self.network_modifiers,
                                                         **self.parameter_dict)

            # storing the indices of the agents to access them quicker
        self.agentIDs = list(self.network)

        # initialize agent attributes (accepts string realizations and instances of AttributesInitializer classes)
        agents_init.initialize_attributes(self.network, self.attributes_initializer, **self.parameter_dict)

        # initialization of distances between neighbors
        self.dissimilarity_calculator.calculate_dissimilarity_networkwide(self.network)
Esempio n. 9
0
 def test_random_continuous(self):
     network1 = network_init.generate_network("grid", **{"num_agents": 4})
     # default values
     agents_init.initialize_attributes(network1, "random_continuous")
     # more features
     agents_init.initialize_attributes(network1, "random_continuous",
                                       **{"num_features": 3})
     # non-implemented distribution
     with self.assertRaises(NotImplementedError):
         agents_init.initialize_attributes(
             network1, "random_continuous", **{
                 "distribution": "notimplemented",
                 "num_features": 1
             })
Esempio n. 10
0
from defSim.network_init import network_init
from defSim.agents_init import agents_init
from defSim.dissimilarity_component.HammingDistance import HammingDistance
from defSim.tools import NetworkDistanceUpdater
import networkx.algorithms.isomorphism as iso
import timeit
import random

random.seed("random")
network = network_init.generate_network("grid")
agents_init.initialize_attributes(network, "random_categorical")
network_comparison = network.copy()
HammingDistance().calculate_dissimilarity_networkwide(network)

all_attributes = network.nodes[1].keys()
def test_isomorphic():
    for i in range(10000):
        nm = iso.categorical_node_match(all_attributes, [0 for i in range(len(all_attributes))])

print("10000 isomorphism checks")
print("Time: "+str(timeit.timeit(test_isomorphic, number=1)))

def test_dissimilarity_check():
    for i in range(10000):
        NetworkDistanceUpdater.check_dissimilarity(network,1)

print("10000 dissimilarity checks")
print("Time: "+str(timeit.timeit(test_dissimilarity_check, number=1)))
Esempio n. 11
0
 def test_from_network_init(self):
     network_init.generate_network(
         "grid",
         network_modifiers=[MaslovSneppenModifier(rewiring_prop=0.1)])
Esempio n. 12
0
    def test_generate_network(self):
        graph = network_init.generate_network("spatial_random_graph")
        self.assertEqual(type(graph), nx.Graph)

        graph = network_init.generate_network("cycle_graph", **{"n": 30})
        self.assertEqual(type(graph), nx.Graph)
Esempio n. 13
0
def test100():
    for i in range(1000000):
        random.choice(list100)


def test5000():
    for i in range(1000000):
        random.choise(list5000)


print("2000000 choices from list of length 100 take %f seconds" %
      (timeit.timeit(test100, number=1)))
print("2000000 choices from list of length 5000 take %f seconds" %
      (timeit.timeit(test100, number=1)))

network49 = network_init.generate_network("grid")
for item, thingy in network49.nodes.items():
    print(item)
    print(thingy)
network5000 = network_init.generate_network("grid", **{"num_agents": 5000})
print(network49.edges().toList())


# checking whether the access to a single node takes longer in big networks
def testAccessSmall():
    for i in range(10000000):
        a = network49[1]


def testAccessLarge():
    for i in range(10000000):
Esempio n. 14
0
def timeAttributeInitialization49():
    network = network_init.generate_network("grid")
    for i in range(100):
        agents_init.initialize_attributes(network, "random")
Esempio n. 15
0
def timeNetworkCreation1000():
    network = network_init.generate_network(
        "grid", **{
            "num_agents": 1000000,
            "neighborhood": "von_neumann"
        })
Esempio n. 16
0
def timeNetworkCreation49():
    for i in range(100):
        network = network_init.generate_network(
            "grid", **{**{
                "neighborhood": "von_neumann"
            }})