Skip to content

Linear network herding

Agents whose linear choices herd on the past choices of linked agents.

  • Class: NetworkHerdingSystem
  • Import: from skcomplex.systems.economics.macroeconomics import NetworkHerdingSystem
  • Field: economics/macroeconomics
  • Topics: herding, network, aggregation, agents, linear map
  • References:
    • Caiani et al. 2016 §1.1.6

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.economics.macroeconomics import NetworkHerdingSystem

trajectory = NetworkHerdingSystem().prepare().simulate()

Parameters

The model parameters take these defaults, and set_params changes them.

Parameter Default
theta None
x None
gamma 1.0
sigma 0.1
n_agents 50
density 0.1
herding 0.5
random_state 0
solver 'auto'
backend 'auto'

Tags

The system with its default parameters has these capability tags, which solvers and analyses check.

Tag Values
Time discrete
Space none
Laws update
Randomness stochastic
Domains real
Structure fixed

Class

The source of the class shows how it builds its components from its model parameters.

class NetworkHerdingSystem(BaseSystem):
    """Agents whose linear choices herd on the past choices of linked agents.

    They herd on the agents they are linked to. The choice of agent `i` is `c_it = sum_j theta_ij c_j,t-1 + gamma x_it`,
    so the choices follow `c_t = Theta c_t-1 + gamma x_t` on the weighted network `Theta`, without self-links, Eqs. 1.10
    and 1.11 of Caiani et al. (2016, Section 1.1.6). The individual characteristic is `x_it = x_i + sigma eps_it`, with
    a standard normal shock `eps_it`. The mean choice follows `c_t = (1/N) sum_i d_i c_i,t-1 + gamma x_t` (Eq. 1.12),
    where the out-degree `d_i` of agent `i`, the sum of column `i` of `Theta`, measures how much its choice moves the
    others, so the persistence of the aggregate depends on the out-degrees and on how they correlate with the choices.
    Without shocks the choices settle at `(I - Theta)^-1 gamma x` when the spectral radius of `Theta` is below 1.

    The system has the group `agents` of the choices `agents.c` and the herding `herding`. The observable of the system
    is the mean choice `mean_choice`.

    Args:
        theta:
            The weights, `theta[i][j]` the weight of the past choice of `j` in the choice of `i`, or `None` for a random
            network of `n_agents` agents.

        x:
            The means of the individual characteristics, or `None` for standard lognormal draws.

        gamma:
            The weight of the individual characteristic.

        sigma:
            The standard deviation of the shocks of the individual characteristics.

        n_agents:
            The number of agents of a random network.

        density:
            The probability of a link from one agent to another in a random network.

        herding:
            The sum of the weights of every agent with links in a random network, below 1 for stable choices.

        random_state:
            The seed or generator of the random network and characteristics.

        label:
            The label of the system, which names it when it is nested in another one.

        solver:
            The solver of the problem, or `'auto'` for the one the system chooses.

        backend:
            The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.

    Examples:
        >>> from skcomplex.systems.economics.macroeconomics import NetworkHerdingSystem
        >>> NetworkHerdingSystem([[0.0, 0.5], [0.5, 0.0]], [1.0, 1.0]).prepare().system_.elements[0].size
        2
    """

    draws = True

    field = 'economics/macroeconomics'
    topics = ('herding', 'network', 'aggregation', 'agents', 'linear map')
    references = ('Caiani et al. 2016 §1.1.6',)
    until = 50
    observables = (Observable('mean_choice', group='agents', variable='c', reduce='mean'),)

    def __init__(
        self,
        theta: Sequence[Sequence[float]] | None = None,
        x: Sequence[float] | None = None,
        *,
        gamma: float = 1.0,
        sigma: float = 0.1,
        n_agents: int = 50,
        density: float = 0.1,
        herding: float = 0.5,
        random_state: int | np.random.Generator | None = 0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.theta = theta
        self.x = x
        self.gamma = gamma
        self.sigma = sigma
        self.n_agents = n_agents
        self.density = density
        self.herding = herding
        self.random_state = random_state

    @staticmethod
    def _get_random_links(n_agents: int, density: float, herding: float, rng: np.random.Generator) -> Array:
        """Return random directed weights with no self-links.

        Every row sums to `herding`.
        """
        links = (rng.random((n_agents, n_agents)) < density) * rng.random((n_agents, n_agents))
        np.fill_diagonal(links, 0.0)
        rows = links.sum(axis=1, keepdims=True)
        return np.divide(herding * links, rows, out=np.zeros_like(links), where=rows > 0)

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of the components built from the model parameters."""
        super()._prepare(context)
        rng = np.random.default_rng(self.random_state)
        weights = (
            self._get_random_links(self.n_agents, self.density, self.herding, rng)
            if self.theta is None
            else np.asarray(self.theta, dtype=float)
        )
        size = len(weights)
        means = rng.lognormal(0.0, 1.0, size) if self.x is None else np.asarray(self.x, dtype=float)
        agents = HerdingAgentElement(
            'agents',
            c=self.gamma * means,
            x=means,
            gamma=self.gamma,
            sigma=self.sigma,
            size=size,
        )
        herding_map = HerdingInteraction('herding', target='agents', weights=tuple(map(tuple, weights.tolist())))
        self.system_ = System(self.label, elements=[agents], interactions=[herding_map])

Components

The system uses these element and interaction classes, each with its nearest class of the core.

Elements:

  • HerdingAgentElement, from Element

Interactions:

  • HerdingInteraction, from Interaction
class HerdingAgentElement(Element):
    """Agent whose choice `c` is a weighted sum of the past choices of others.

    It adds its individual characteristic.

    Args:
        label:
            The label of the agent or group.

        c:
            The choice of the agent, such as its consumption.

        x:
            The mean of the individual characteristic of the agent.

        gamma:
            The weight `gamma` of the individual characteristic in the choice.

        sigma:
            The standard deviation of the shocks of the individual characteristic.

        size:
            The number of members, or `None` for one.

    Examples:
        >>> from skcomplex.systems.economics.macroeconomics import HerdingAgentElement
        >>> HerdingAgentElement('agents', x=[1.0, 2.0, 3.0], size=3).size
        3
    """

    def __init__(
        self,
        label: str,
        *,
        c: object = 0.0,
        x: object = 1.0,
        gamma: object = 1.0,
        sigma: object = 0.0,
        size: int | None = None,
    ) -> None:
        super().__init__(label, size=size)
        self.c = c
        self.x = x
        self.gamma = gamma
        self.sigma = sigma

class HerdingInteraction(Interaction):
    """Herding of agents on the past choices of the agents they are linked to.

    The next choice of agent `i` is `c_i = sum_j theta_ij c_j + gamma (x_i + sigma eps_i)`, the past choices of the
    others weighted by the links `theta`, plus `gamma` times its individual characteristic shocked by a standard normal
    `eps_i`.

    Args:
        label:
            The label of the interaction.

        target:
            The path of the group of agents.

        weights:
            The weight `theta_ij` of the link from agent `i` to agent `j`, one row per agent.

    Examples:
        >>> from skcomplex.systems.economics.macroeconomics import HerdingInteraction
        >>> HerdingInteraction('herding', target='agents', weights=((0.0, 0.5), (0.5, 0.0))).weights
        ((0.0, 0.5), (0.5, 0.0))
    """

    law_classes = (UpdateLaw,)

    def __init__(self, label: str, *, target: Role, weights: tuple[tuple[float, ...], ...] = ()) -> None:
        super().__init__(label)
        self.target = target
        self.weights = weights

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the update of the choice of every agent as the law.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        agent = context.target
        herding = total(agent.other.c, over=agent.other, weights=np.asarray(self.weights, dtype=float))
        choice = herding + agent.gamma * (agent.x + agent.sigma * normal('shock', 0, 1))
        self.laws_: list[BaseLaw] = [UpdateLaw(agent.c, choice)]

Equations

The equations are those that symbolic returns for the system with its default parameters.

agents.c[i]: c_agents(t + 1) == (normal_shock_herding*sigma_agents + x_agents)*gamma_agents + _reduced_0