Ejemplo n.º 1
0
def sample_runs(n_runs, single_steps, N, link_density, rewiring_prob, update_timescale, adj_mats):
    n = 0
    n_fails = 0
    while n < n_runs:
        print "Run:", n + 1

        # Agent's parameters
        MaxStocks = np.ones(N)
        Stocks = np.random.rand(N) * MaxStocks
        GrowthRates = np.ones(N)
        Rationalities = np.ones(N)
        Strategies = np.random.randint(2, size=N)

        # Running the model
        t0 = time()
        m = Exploit(
            adj_mats[n], Strategies, Stocks, MaxStocks, GrowthRates, Rationalities, rewiring_prob, update_timescale
        )
        if single_steps == -1:
            fail = m.run() == 0
            print "Runtime: {0} min".format((time() - t0) / 60.0)
            if fail:
                print "No conv., in run", n + 1
                n_fails += 1
            elif not fail:
                print "<sus>: {}".format(m.get_strategies().mean())
                n += 1
        else:
            m.run(steps=single_steps)
            n += 1
            print "Runtime: {0} min".format((time() - t0) / 60.0)

    print "Done!"
Ejemplo n.º 2
0
def sample_runs(n_runs, single_steps, N, link_density, rewiring_prob,
                update_timescale, adj_mats):
    n = 0
    n_fails = 0
    while n < n_runs:
        print "Run:", n + 1

        # Agent's parameters
        MaxStocks = np.ones(N)
        Stocks = np.random.rand(N) * MaxStocks
        GrowthRates = np.ones(N)
        Rationalities = np.ones(N)
        Strategies = np.random.randint(2, size=N)

        # Running the model
        t0 = time()
        m = Exploit(adj_mats[n], Strategies, Stocks, MaxStocks, GrowthRates,
                    Rationalities, rewiring_prob, update_timescale)
        if single_steps == -1:
            fail = (m.run() == 0)
            print "Runtime: {0} min".format((time() - t0) / 60.)
            if fail:
                print "No conv., in run", n + 1
                n_fails += 1
            elif not fail:
                print "<sus>: {}".format(m.get_strategies().mean())
                n += 1
        else:
            m.run(steps=single_steps)
            n += 1
            print "Runtime: {0} min".format((time() - t0) / 60.)

    print "Done!"
Ejemplo n.º 3
0
def test_consensus():
    """
    Test the consensus method (and that it is properly called in the __init__)
    for extremely simple cases.
    """

    A = np.zeros((3, 3), dtype=int)  # Dummy empty adjaceny matrix
    ones = np.ones(3)  # Dummy variable for stock, groth_rates etc.

    # Two unconnected network components with different strategies
    A[0, 1] = A[1, 0] = 1
    S = np.array([1, 1, 0])
    m = ExploitCore(A, S, ones, ones, ones, ones, 0.5, 2.0)
    assert m.get_consensus() == True

    # Both strategies in the same component
    S = np.array([1, 0, 1])
    m = ExploitCore(A, S, ones, ones, ones, ones, 0.5, 2.0)
    assert m.get_consensus() == False

    # One component with one strategy
    A[0, 2] = A[2, 0] = 1
    S = np.array([1, 1, 1])
    m = ExploitCore(A, S, ones, ones, ones, ones, 0.5, 2.0)
    assert m.get_consensus() == True
Ejemplo n.º 4
0
def test_getters():
    """
    Test if the assignement and return of the adjacency matrix works
    """

    A = np.random.randint(2, size=(10, 10))
    S = np.random.randint(2, size=10)
    stocks = np.random.rand(10)
    ones = np.ones(10)
    # Dummy values
    m = ExploitCore(A, S, stocks, ones, ones, ones, 0.5, 2.0)
    assert (m.get_adjacency() == A).all()
    assert (m.get_strategies() == S).all()
    assert (m.get_stocks() == stocks).all()
    assert m.get_time() == 0
Ejemplo n.º 5
0
def test_update():
    """
    Test if one update process changes either the adjacency matrix or the
    strategies.
    """
    A = nx.adj_matrix(nx.erdos_renyi_graph(10, 0.3)).toarray()
    S = np.random.randint(2, size=10)
    stocks = np.ones(10)
    ones = np.ones(10)

    # If rewire (phi=1) A has to change
    m = ExploitCore(A.copy(), S, stocks.copy(), ones, ones, ones, 1.0, 2.0)
    m.run(steps=1)
    assert np.sum(np.abs(m.get_adjacency() - A)) == 4
    # Stocks decreased
    assert (m.get_stocks() < stocks).all()

    # If no rewirte (phi=0) S has to change
    m = ExploitCore(A, S.copy(), stocks.copy(), ones, ones, ones, 0.0, 2.0)
    m.run(steps=1)
    assert np.sum(np.abs(m.get_strategies() - S)) == 1
    # Stocks decreased
    assert (m.get_stocks() < stocks).all()
Ejemplo n.º 6
0
def RUN_FUNC(tau, phi, sigma, mu, N, link_density, g, gamma, filename):
    """
    Setting up the model with various parameters and determine what and how to
    save the outcome. This is done with a pickeld dictionary including the
    inital values, some parameters (for double checking) and the consensous
    state and time - if the model reached consensus.

    Parameters
    ----------
    tau : float
        the social update timescale
    phi : float
        the rewiring probability (between 0 and 1)
    sigma : float
        the standard deviation of the normal distribution for the capacities
    mu : float
        the mean of the normal distribution for the capacities
    N : int
        the number of agents/resources
    link_density : float
        the link density of the erdoes-renyi network
    g : float
        the (homogenous) growth rate of all resources
    gamma : float
        the (homogenous) rationality of all agents
    filename : string
        the filename where to pickle - passed from "experiment_handling"
        This needs to be the last parameter of the RUN_FUNC
    """
    MaxStocks = np.abs(np.random.normal(mu, sigma, size=N))  # normal
    Stocks = np.random.rand(N) * MaxStocks  # Random inital stocks
    Strategies = np.random.randint(2, size=N)  # Random inital strategies
    GrowthRates = g * np.ones(N)  # Homogenous growth rates g
    Rationalities = gamma * np.ones(N)  # Homogenous rationalities gamma

    # Connected adjacnecy matrix
    net = nx.erdos_renyi_graph(N, link_density)
    while len(list(nx.connected_components(net))) > 1:
        print "Network has isolated components. Try again!"
        net = nx.erdos_renyi_graph(N, link_density)
    A = nx.adj_matrix(net).toarray()

    # Prepare storing inititals
    res = {}
    res["initials"] = pd.DataFrame({
        "MaxStocks": MaxStocks,
        "Stocks": Stocks,
        "Strategies": Strategies
    })
    # Prpare storing parameters
    res["parameters"] = pd.Series({
        "N": N,
        "link_density": link_density,
        "growth_rate": g,
        "rationality": gamma,
        "mu_lognorm": mu,
        "sigma_lognorm": sigma,
        "rewiring_prob": phi,
        "update_timescale": tau
    })

    # Running the model
    m = Exploit(A, Strategies, Stocks, MaxStocks, GrowthRates, Rationalities,
                phi, tau)
    exit_status = m.run()

    if exit_status == 1:
        # Prepare storing consensus state
        res["consensus"] = pd.DataFrame({
            "Strategies": m.get_strategies(),
            "Stocks": m.get_stocks()
        })
        res["consensus_time"] = m.get_time()

    cPickle.dump(res, open(filename, "wb"))
    return exit_status
Ejemplo n.º 7
0
def RUN_FUNC(tau, phi, sigma, C, N, link_density, g, gamma, filename):
    """
    Setting up the model with various parameters and determine what and how to
    save the outcome. This is done with a pickeld dictionary including the
    inital values, some parameters (for double checking) and the consensous
    state and time - if the model reached consensus.

    Parameters
    ----------
    tau : float
        the social update timescale
    phi : float
        the rewiring probability (between 0 and 1)
    sigma : float
        the sigma parameter of the lognormal distribution for the capacities
    C : float
        C = mu + sigma^2/2 of the lognormal distribution. By that the
        distributions of the resouces have equal mean
    N : int
        the number of agents/resources
    link_density : float
        the link density of the erdoes-renyi network
    g : float
        the (homogenous) growth rate of all resources
    gamma : float
        the (homogenous) rationality of all agents
    filename : string
        the filename where to pickle - passed from "experiment_handling"
        This needs to be the last parameter of the RUN_FUNC
    """
    mu = float(C) - sigma**2/2.
    MaxStocks = np.random.lognormal(mu, sigma, size=N)  # log-normal
    Stocks = np.random.rand(N) * MaxStocks  # Random inital stocks
    Strategies = np.random.randint(2, size=N)  # Random inital strategies
    GrowthRates = g * np.ones(N)  # Homogenous growth rates g
    Rationalities = gamma * np.ones(N)  # Homogenous rationalities gamma

    # Connected adjacnecy matrix
    net = nx.erdos_renyi_graph(N, link_density)
    while len(list(nx.connected_components(net))) > 1:
        print "Network has isolated components. Try again!"
        net = nx.erdos_renyi_graph(N, link_density)
    A = nx.adj_matrix(net).toarray()

    # Prepare storing inititals
    res = {}
    res["initials"] = pd.DataFrame({"MaxStocks": MaxStocks,
                                    "Stocks": Stocks,
                                    "Strategies": Strategies})
    # Prpare storing parameters
    res["parameters"] = pd.Series({"N": N,
                                   "link_density": link_density,
                                   "growth_rate": g,
                                   "rationality": gamma,
                                   "mu_lognorm": mu,
                                   "sigma_lognorm": sigma,
                                   "rewiring_prob": phi,
                                   "update_timescale": tau})

    # Running the model
    m = Exploit(A, Strategies, Stocks, MaxStocks, GrowthRates,
                Rationalities, phi, tau)
    exit_status = m.run()

    if exit_status == 1:
        # Prepare storing consensus state
        res["consensus"] = pd.DataFrame({"Strategies": m.get_strategies(),
                                         "Stocks": m.get_stocks()})
        res["consensus_time"] = m.get_time()

    cPickle.dump(res, open(filename, "wb"))
    return exit_status