Ejemplo n.º 1
0
def run_agent_generated_trial(args: Tuple[Disease, AgentBehavior, int, Any])\
        -> Optional[Tuple[float, float, float]]:
    """
    args: (disease to use in the simulation,
           the behavior agents have when generating the network,
           the number of agents in the network,
           an instance of np.random.default_rng)
    """
    disease, agent_behavior, N, rand = args
    sim_len = 200
    sims_per_trial = 150
    net = make_agent_generated_network(N, agent_behavior)
    if net is None:
        return None

    to_flicker = partitioning.fluidc_partition(net.G, 50)
    proportion_flickering = len(to_flicker) / net.E
    social_good = rate_social_good(net)

    network_behavior = StaticFlickerBehavior(net.M, to_flicker, (True, False),
                                             "Probs don't change this")
    avg_sus = np.mean([
        np.sum(
            simulate(net.M, make_starting_sir(net.N, 1), disease,
                     network_behavior, sim_len, None, rand)[-1][0] > 0)
        for _ in range(sims_per_trial)
    ]) / net.N

    return proportion_flickering, avg_sus, social_good
Ejemplo n.º 2
0
def run_social_circles_trial(
    args: Tuple[Dict[networkgen.Agent, int], Tuple[int, int], Disease, Any]
) -> Optional[Tuple[float, float, float]]:
    agent_to_quantity, grid_dims, disease, rand = args
    sim_len = 200
    sims_per_trial = 150
    target_communities = 25

    sc_results = networkgen.make_social_circles_network(agent_to_quantity,
                                                        grid_dims,
                                                        rand=rand)
    if sc_results is None:
        return None
    net, _, = sc_results
    if nx.number_connected_components(net.G) > target_communities:
        return None

    to_flicker = partitioning.fluidc_partition(net.G, target_communities)
    proportion_flickering = len(to_flicker) / net.E
    social_good_score = rate_social_good(net)

    network_behavior = StaticFlickerBehavior(net.M, to_flicker, (True, False),
                                             "Probs don't change this")
    avg_sus = np.mean([
        np.sum(
            simulate(net.M, make_starting_sir(net.N, 1), disease,
                     network_behavior, sim_len, None, rand)[-1][0] > 0)
        for _ in range(sims_per_trial)
    ]) / net.N

    return proportion_flickering, avg_sus, social_good_score
def run_connected_community_trial(args: Tuple[ConnectedCommunityConfiguration, Disease, Any])\
        -> Optional[Tuple[float, float, float]]:
    """
    args: (ConnectedCommunityConfiguration to use,
           disease to use,
           default_rng instance)
    return: (proportion of edges that flicker, the average number of remaining susceptible agents)
            or None on failure.
    """
    sim_len = 200
    sims_per_trial = 150
    configuration, disease, rand = args

    inner_degrees = configuration.make_inner_degrees()
    outer_degrees = configuration.make_outer_degrees()
    net = networkgen.make_connected_community_network(inner_degrees, outer_degrees, rand)
    # If a network couldn't be successfully generated, return None to signal the failure
    if net is None:
        return None
    to_flicker = {(u, v) for u, v in net.edges if net.communities[u] != net.communities[v]}
    proportion_flickering = len(to_flicker) / net.E
    social_good = rate_social_good(net)

    behavior = StaticFlickerBehavior(net.M, to_flicker, (True, False), "Probs don't change this")
    avg_sus = np.mean([np.sum(simulate(net.M, make_starting_sir(net.N, 1),
                                       disease, behavior, sim_len, None, rand)[-1][0] > 0)
                       for _ in range(sims_per_trial)]) / net.N

    return proportion_flickering, avg_sus, social_good
Ejemplo n.º 4
0
def show_social_good():
    if len(sys.argv) < 2:
        print(f'Usage {sys.argv[1]} <network>')
        return

    net = fio.read_network(sys.argv[1])
    for k in np.linspace(.5, 1.5, 5):
        sg_score = socialgood.rate_social_good(net,
                                               socialgood.DecayFunction(k))
        print(f'{k:<6.3f}: {sg_score}')
Ejemplo n.º 5
0
 def __call__(self, encoding: np.ndarray) -> float:
     net = self._enc_to_G(encoding)
     M = net.M
     to_flicker = fluidc_partition(net.G, net.N//20)
     flicker_behavior = StaticFlickerBehavior(M, to_flicker, (True, False), '')
     avg_sus = np.mean([np.sum(simulate(M, make_starting_sir(len(M), 1),
                                        self._disease, flicker_behavior, self._sim_len,
                                        None, self._rand)[-1][0] > 0)
                        for _ in range(self._n_sims)]) / len(M)
     cost = 2-avg_sus-rate_social_good(net, self._decay_func)
     return cost
Ejemplo n.º 6
0
def social_good_giant_component_barabasi_albert():
    social_goods = []
    giant_comp_sizes = []
    for i in range(1, 100):
        print(i)
        g = nx.barabasi_albert_graph(100, i)
        social_good = sg.rate_social_good(g)
        social_goods.append(social_good)
        giant_comp_size = analyzer.get_giant_component_size(g, 0.9, 10)
        giant_comp_sizes.append(giant_comp_size / 100)
    plt.xlabel('Number of Edges')
    plt.ylabel('Social Good')
    plt.title('Barabasi-Albert Social Good Analysis')
    plt.plot(range(1, 100), social_goods, 'o', color='blue')
    plt.plot(range(1, 100), giant_comp_sizes, 'o', color='red')
    plt.show()
Ejemplo n.º 7
0
def social_good_giant_component_connected_community():
    RAND = np.random.default_rng()

    num_nodes = 200
    social_goods = []
    giant_comp_sizes = []

    x = tuple(range(10))
    y = tuple(range(20))

    for i in y:
        for j in x:
            print(f'i: {i} j: {j}')
            for _ in range(100):
                inner_degrees = np.round(RAND.poisson(i, 10))
                outer_degrees = np.round(RAND.poisson(j, 20))
                if np.sum(inner_degrees) % 2 == 1:
                    inner_degrees[np.argmin(inner_degrees)] += 1
                if np.sum(outer_degrees) % 2 == 1:
                    outer_degrees[np.argmin(outer_degrees)] += 1

                g, _ = cc.make_connected_community_network(inner_degrees, outer_degrees, RAND)
                social_good = sg.rate_social_good(Network(g))
                social_goods.append((i, j, social_good))
                giant_comp_size = analyzer.get_giant_component_size(g, 0.75, 10)
                giant_comp_sizes.append((i, j, giant_comp_size / num_nodes))

    plt.figure()
    ax = plt.axes(projection='3d')

    p_list = social_goods
    x_ = [x for x, y, z in p_list]
    y_ = [y for x, y, z in p_list]
    z_ = [z for x, y, z in p_list]
    ax.scatter3D(x_, y_, z_, color='blue')

    p_list = giant_comp_sizes
    x_ = [x for x, y, z in p_list]
    y_ = [y for x, y, z in p_list]
    z_ = [z for x, y, z in p_list]
    ax.scatter3D(x_, y_, z_, color='red')
    
    plt.xlabel('Number of Neighbors Connected Too')
    plt.ylabel('Probability of Rewiring')
    plt.title('Connected Community Social Good Analysis')
    plt.show()
Ejemplo n.º 8
0
def main():
    n_trials = 100
    max_steps = 100
    rng = np.random.default_rng(0)
    disease = Disease(4, .2)
    names = ('elitist-500', 'cavemen-50-10', 'spatial-network', 'cgg-500',
             'watts-strogatz-500-4-.1')
    paths = fio.network_names_to_paths(names)
    behavior_configs = (RandomFlickerConfig(.5, 'Random .5', rng),
                        StaticFlickerConfig((True, False), 'Static .5'))

    for net_name, path in zip(names, paths):
        net = fio.read_network(path)
        to_flicker = tuple((u, v) for u, v in net.edges
                           if net.communities[u] != net.communities[v])
        proportion_flickering = len(to_flicker) / net.E
        social_good = rate_social_good(net)
        trial_to_pf = tuple(proportion_flickering for _ in range(n_trials))
        trial_to_sg = tuple(social_good for _ in range(n_trials))
        print(f'Running simulations for {net_name}.')
        for config in behavior_configs:
            behavior = config.make_behavior(net.M, to_flicker)
            sim_results = [
                get_final_stats(
                    simulate(net.M,
                             make_starting_sir(net.N, 1, rng),
                             disease,
                             behavior,
                             max_steps,
                             None,
                             rng=rng)) for _ in tqdm(range(n_trials))
            ]
            results = BasicExperimentResult(f'{net_name} {config.name}',
                                            sim_results, trial_to_pf,
                                            trial_to_sg)
            results.save_csv(RESULTS_DIR)
            results.save_box_plots(RESULTS_DIR)
            results.save_perc_sus_vs_social_good(RESULTS_DIR)
Ejemplo n.º 9
0
def social_good_giant_component_watts_strogatz():
    num_nodes = 100
    social_goods = []
    giant_comp_sizes = []

    x = tuple(range(2, num_nodes, 1))
    y = (i/100 for i in range(0, 100, 5))

    for p in y:
        for k in x:
            print(f'k: {k} p: {p}')
            g = nx.watts_strogatz_graph(num_nodes, k, p)
            social_good = sg.rate_social_good(g)
            social_goods.append((k, p, social_good))
            giant_comp_size = analyzer.get_giant_component_size(g, 0.95, 100)
            giant_comp_sizes.append((k, p, giant_comp_size / num_nodes))

    plt.figure()
    ax = plt.axes(projection='3d')

    p_list = social_goods
    x_ = [x for x, y, z in p_list]
    y_ = [y for x, y, z in p_list]
    z_ = [z for x, y, z in p_list]
    ax.scatter3D(x_, y_, z_, color='blue')

    p_list = giant_comp_sizes
    x_ = [x for x, y, z in p_list]
    y_ = [y for x, y, z in p_list]
    z_ = [z for x, y, z in p_list]
    ax.scatter3D(x_, y_, z_, color='red')

    plt.xlabel('Number of Neighbors Connected Too')
    plt.ylabel('Probability of Rewiring')
    plt.title('Watts-Strogatz Social Good Analysis')
    plt.show()
Ejemplo n.º 10
0
 def __call__(self, encoding: np.ndarray) -> float:
     """Expects an edgeset style encoding."""
     net = lib.edge_set_to_network(encoding)
     return 1 - rate_social_good(net, self._decay_func)
Ejemplo n.º 11
0
def rate_sg(args: Tuple[Network, DecayFunction])\
        -> float:
    net, decay = args
    return rate_social_good(net, decay)