Skip to content

Sampling States

Listed below are functions that help to sample states of different types. These can, for instance, be used to generate initial conditions for model simulations.

sample_states_uniform(num_agents, num_opinions, num_states=1, rng=default_rng(), unique=True)

Sample uniformly random states.

In each state, each agent's opinion is uniform in {0, ..., num_opinions - 1}.

Parameters:

  • num_agents (int) –
  • num_opinions (int) –
  • num_states (int, default: 1 ) –

    Default: 1.

  • rng (Generator, default: default_rng() ) –

    Random number generator.

  • unique (bool, default: True ) –

    Whether states should be unique. Default: True.

Returns:

  • NDArray

    shape = (num_states, num_agents) or shape = (num_agents,) if num_states = 1.

Source code in sponet/states.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def sample_states_uniform(
    num_agents: int,
    num_opinions: int,
    num_states: int = 1,
    rng: Generator = default_rng(),
    unique: bool = True,
) -> NDArray:
    """
    Sample uniformly random states.

    In each state, each agent's opinion is uniform in {0, ..., num_opinions - 1}.

    Parameters
    ----------
    num_agents : int
    num_opinions : int
    num_states : int, optional
        Default: 1.
    rng : Generator, optional
        Random number generator.
    unique : bool, optional
        Whether states should be unique. Default: True.

    Returns
    -------
    NDArray
        shape = (num_states, num_agents) or shape = (num_agents,) if num_states = 1.
    """

    def _sample(n: int) -> NDArray:
        return rng.integers(num_opinions, size=(n, num_agents))

    return _sample_states(_sample, num_states, unique)

sample_states_uniform_shares(num_agents, num_opinions, num_states=1, rng=default_rng(), unique=True)

Sample random states with uniform opinion shares.

The states are such that the shares of each opinion are uniform on the simplex of opinion shares. Each state is randomly shuffled.

Parameters:

  • num_agents (int) –
  • num_opinions (int) –
  • num_states (int, default: 1 ) –

    Default: 1.

  • rng (Generator, default: default_rng() ) –

    Random number generator.

  • unique (bool, default: True ) –

    Whether states should be unique. Default: True.

Returns:

  • NDArray

    shape = (num_states, num_agents) or shape = (num_agents,) if num_states = 1.

Source code in sponet/states.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def sample_states_uniform_shares(
    num_agents: int,
    num_opinions: int,
    num_states: int = 1,
    rng: Generator = default_rng(),
    unique: bool = True,
) -> NDArray:
    """
    Sample random states with uniform opinion shares.

    The states are such that the shares of each opinion are uniform
    on the simplex of opinion shares.
    Each state is randomly shuffled.

    Parameters
    ----------
    num_agents : int
    num_opinions : int
    num_states : int, optional
        Default: 1.
    rng : Generator, optional
        Random number generator.
    unique : bool, optional
        Whether states should be unique. Default: True.

    Returns
    -------
    NDArray
        shape = (num_states, num_agents) or shape = (num_agents,) if num_states = 1.
    """
    alpha = np.ones(num_opinions)
    opinion_indices = np.arange(num_opinions)

    def _sample(n: int) -> NDArray:
        x = np.zeros((n, num_agents), dtype=int)
        shares = rng.dirichlet(alpha, n)
        counts = counts_from_shares(shares, num_agents)
        for i in range(n):
            x[i, :] = np.repeat(opinion_indices, counts[i])
        rng.shuffle(x, axis=1)
        return x

    return _sample_states(_sample, num_states, unique)

sample_states_target_shares(num_agents, target_shares, num_states=1, rng=default_rng(), unique=True)

Sample random states with target opinion shares.

Each state respects the given target_shares of each opinion and is randomly shuffled. The target_shares have to be non-negative with sum(target_shares) = 1.

Parameters:

  • num_agents (int) –
  • target_shares (ArrayLike) –

    shape = (num_opinions,)

  • num_states (int, default: 1 ) –

    Default: 1.

  • rng (Generator, default: default_rng() ) –

    Random number Generator.

  • unique (bool, default: True ) –

    Whether states should be unique. Default: True.

Returns:

  • NDArray

    shape = (num_states, num_agents) or shape = (num_agents,) if num_states = 1.

Source code in sponet/states.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def sample_states_target_shares(
    num_agents: int,
    target_shares: ArrayLike,
    num_states: int = 1,
    rng: Generator = default_rng(),
    unique: bool = True,
) -> NDArray:
    """
    Sample random states with target opinion shares.

    Each state respects the given target_shares of each opinion and is randomly shuffled.
    The target_shares have to be non-negative with sum(target_shares) = 1.

    Parameters
    ----------
    num_agents : int
    target_shares : ArrayLike
        shape = (num_opinions,)
    num_states : int, optional
        Default: 1.
    rng : Generator, optional
        Random number Generator.
    unique : bool, optional
        Whether states should be unique. Default: True.

    Returns
    -------
    NDArray
        shape = (num_states, num_agents) or shape = (num_agents,) if num_states = 1.
    """
    target_counts = counts_from_shares(target_shares, num_agents)
    num_opinions = target_counts.shape[0]
    x_ordered = np.repeat(np.arange(num_opinions), target_counts)

    def _sample(n: int) -> NDArray:
        x = np.tile(x_ordered, (n, 1))
        rng.shuffle(x, axis=1)
        return x

    return _sample_states(_sample, num_states, unique)

sample_states_local_clusters(network, num_opinions, num_states=1, max_num_seeds=1, min_num_seeds=1, rng=default_rng(), unique=True)

Create states by the following procedure: 1) Pick uniformly random opinion shares 2) Pick num_seeds random seeds on the graph for each opinion (num_seeds is uniformly random between min_num_seeds and max_num_seeds) 3) Propagate the opinions outward from each seed to neighboring nodes until the shares are reached

Parameters:

  • network (Graph) –
  • num_opinions (int) –
  • num_states (int, default: 1 ) –

    Default: 1.

  • max_num_seeds (int, default: 1 ) –
  • min_num_seeds (int, default: 1 ) –
  • rng (Generator, default: default_rng() ) –

    random number generator

  • unique (bool, default: True ) –

    Whether states should be unique. Default: True.

Returns:

  • NDArray

    shape = (num_states, num_agents) or shape = (num_agents,) if num_states = 1.

Source code in sponet/states.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def sample_states_local_clusters(
    network: nx.Graph,
    num_opinions: int,
    num_states: int = 1,
    max_num_seeds: int = 1,
    min_num_seeds: int = 1,
    rng: Generator = default_rng(),
    unique: bool = True,
) -> NDArray:
    """
    Create states by the following procedure:
    1) Pick uniformly random opinion shares
    2) Pick num_seeds random seeds on the graph for each opinion
    (num_seeds is uniformly random between min_num_seeds and max_num_seeds)
    3) Propagate the opinions outward from each seed to neighboring nodes until the shares are reached

    Parameters
    ----------
    network : nx.Graph
    num_opinions : int
    num_states : int, optional
        Default: 1.
    max_num_seeds : int, optional
    min_num_seeds : int, optional
    rng : Generator, optional
        random number generator
    unique : bool, optional
        Whether states should be unique. Default: True.

    Returns
    -------
    NDArray
        shape = (num_states, num_agents) or shape = (num_agents,) if num_states = 1.
    """
    num_agents = network.number_of_nodes()
    alpha = np.ones(num_opinions)

    def _sample(n: int) -> NDArray:
        x = np.zeros((n, num_agents), dtype=int)
        target_shares = rng.dirichlet(alpha, n)
        target_counts = counts_from_shares(target_shares, num_agents)
        num_seeds = rng.integers(min_num_seeds, max_num_seeds + 1, size=n)

        for i in range(n):
            seeds = rng.choice(
                num_agents, size=num_seeds[i] * num_opinions, replace=False
            )
            rng.shuffle(seeds)
            seeds = list(seeds.reshape((num_opinions, num_seeds[i])))
            x[i] = _state_local_clusters(
                target_counts[i],
                seeds,
                network,
                rng,
            )
        return x

    return _sample_states(_sample, num_states, unique)

build_state_by_degree(network, opinion_shares, opinion_order)

Construct a state where the largest degree nodes have a certain opinion.

Example

opinion_shares = [0.2, 0.5, 0.3], opinion_order = [1, 2, 0] means that the 20% of nodes with the largest degree get opinion 1, the subsequent 50% of nodes with the largest degree get opinion 2, and the remaining 30% of nodes (which will have the smallest degrees) get opinion 0.

Parameters:

  • network (Graph) –
  • opinion_shares (ArrayLike) –

    shape = (num_opinions,), has to sum to 1

  • opinion_order (ArrayLike) –

    shape = (num_opinions,), permutation of {0, ..., num_opinions - 1}

Returns:

  • NDArray
Source code in sponet/states.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def build_state_by_degree(
    network: nx.Graph,
    opinion_shares: ArrayLike,
    opinion_order: ArrayLike,
) -> NDArray:
    """
    Construct a state where the largest degree nodes have a certain opinion.

    Example
    ----------
    opinion_shares = [0.2, 0.5, 0.3], opinion_order = [1, 2, 0]
    means that the 20% of nodes with the largest degree get opinion 1,
    the subsequent 50% of nodes with the largest degree get opinion 2,
    and the remaining 30% of nodes (which will have the smallest degrees) get opinion 0.

    Parameters
    ----------
    network : nx.Graph
    opinion_shares : ArrayLike
        shape = (num_opinions,), has to sum to 1
    opinion_order : ArrayLike
        shape = (num_opinions,), permutation of {0, ..., num_opinions - 1}

    Returns
    -------
    NDArray
    """
    num_nodes = network.number_of_nodes()
    x = np.zeros(num_nodes, dtype=int)
    degrees = [d for _, d in network.degree()]  # type: ignore
    degrees_sorted_idx = np.argsort(degrees)[::-1]
    opinion_counts = counts_from_shares(opinion_shares, num_nodes)

    i = 0
    for opinion, opinion_count in zip(np.array(opinion_order), opinion_counts):
        x[degrees_sorted_idx[i : i + opinion_count]] = opinion
        i += opinion_count

    return x

sample_states_target_cvs(num_agents, num_opinions, col_var, target_cv_value, num_states=1, rtol=0.0001, rng=default_rng(), max_sample_time_per_state=10, unique=True)

Sample states with target collective variable value.

Samples a state x such that approximately cv(x) = target_cv_value via MCMC.

Since the relative tolerance rtol is used, this function does not work if ||target_cv_value||=0.

Parameters:

  • num_agents (int) –
  • num_opinions (int) –
  • col_var (CollectiveVariable) –
  • target_cv_value (ArrayLike) –

    Shape = (cv_dim,).

  • num_states (int, default: 1 ) –

    Default: 1.

  • rtol (float, default: 0.0001 ) –

    Relative tolerance.

  • rng (Generator, default: default_rng() ) –

    Random number generator.

  • max_sample_time_per_state (float, default: 10 ) –

    In seconds. Raises RuntimeError if no state could be found in that time.

  • unique (bool, default: True ) –

    Whether states should be unique. Default: True.

Returns:

  • NDArray

    shape = (num_states, num_agents) or shape = (num_agents,) if num_states = 1.

Source code in sponet/states.py
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def sample_states_target_cvs(
    num_agents: int,
    num_opinions: int,
    col_var: CollectiveVariable,
    target_cv_value: ArrayLike,
    num_states: int = 1,
    rtol: float = 1e-4,
    rng: Generator = default_rng(),
    max_sample_time_per_state: float = 10,
    unique: bool = True,
) -> NDArray:
    """
    Sample states with target collective variable value.

    Samples a state x such that approximately
    cv(x) = target_cv_value
    via MCMC.

    Since the relative tolerance rtol is used, this function does not work
    if ||target_cv_value||=0.

    Parameters
    ----------
    num_agents : int
    num_opinions : int
    col_var : CollectiveVariable
    target_cv_value : ArrayLike
        Shape = (cv_dim,).
    num_states : int, optional
        Default: 1.
    rtol : float, optional
        Relative tolerance.
    rng : Generator, optional
        Random number generator.
    max_sample_time_per_state : float, optional
        In seconds. Raises RuntimeError if no state could be found in that time.
    unique : bool, optional
        Whether states should be unique. Default: True.

    Returns
    -------
    NDArray
        shape = (num_states, num_agents) or shape = (num_agents,) if num_states = 1.
    """
    target_cv_value = np.array(target_cv_value, ndmin=1)

    # set temperature in relation to num_agents
    base_temperature = -2.0 / num_agents / np.log(0.5)
    temperature_decay_factor = 0.1 ** (1.0 / num_agents)
    iterations_until_temperature_reset = num_agents

    def _sample(n: int) -> NDArray:
        x = np.zeros((n, num_agents), dtype=int)
        for i in range(n):
            initial_guess = _initial_guess_target_cvs(
                num_agents, num_opinions, col_var, target_cv_value, rng
            )
            x[i] = _sample_state_target_cvs(
                num_opinions,
                col_var,
                target_cv_value,
                initial_guess,
                rtol,
                base_temperature,
                temperature_decay_factor,
                iterations_until_temperature_reset,
                max_sample_time_per_state,
                rng,
            )
        return x

    return _sample_states(_sample, num_states, unique)