Coloring concepts#

Note

Tinto uses a lot of words:

  • configs,

  • graphs,

  • schedulers,

  • colorers,

  • solvers,

  • starters,

  • runners,

  • experiments,

  • estimators,

  • …

At first it can be hard to navigate between all these concepts. In particular:

  • The vocabulary comes from the theory of self-stabilizing coloring;

  • The way these concepts are implemented is designed for practical flexibility and efficiency.

This notebook proposes a gentle tour.

If you find the notebook too slow for your taste, don’t hesitate to skip to the other ones.

TL;DR#

  • A Config class is defined from a guard: tinto.configs.make(guard=tinto.guards.color_clash) -> Config (jitclass).

  • Config(graph) -> config instance: manages colors, guarded nodes, and ids (if required).

  • A scheduler selects a subset of enabled nodes. First build a factory (facto=shuffled(), facto=bernoulli(p=2/3), …), then apply it to a config (sched=facto(config)), then draw (selection=sched.draw(config)).

  • A solver is a function solver(config, decisions) that modifies the configuration in place. It is built with solvers.make(coloring_function). A few coloring functions are provided.

  • runners.simple(config, scheduler, solver) runs one specific scenario (# steps & # activations).

  • runners.mc(config_factory, scheduler_factory, solver, n_trials=1000) runs many scenarios (first moments of steps and activations). starters.from_graph(Config, color=None)(graph) is a typical factory.

  • An Experiment (built from one or more Iterator sweeps) runs runners.mc across a parameter grid and gathers the results: Experiment(name, iterator=Iterator("starter", values, process=...), scheduler=..., solver=..., n_trials=...).run(), then .series() / .plot() / .to_csv().

  • Estimators read a behavior law off a sweep: Experiment.fit (affine or custom basis, with \(\chi^2\) diagnostics) and Experiment.fit_fractions (exact fractions). They wrap the estimate module.

Graphs#

Tinto graphs are jitted. The one method you really need is neighbors(i); a graph also knows its size n and its max_degree, and can spell out its full adjacency matrix with to_adja().

Graphs are handled by the graphs module. Beyond the deterministic line and ring, it ships two random generators, cayley and erdos_renyi.

[1]:
from tinto import graphs

Line#

[2]:
n = 5
line = graphs.line(n=n)
for i in range(n):
    print(f"Neighbors of {i}: {line.neighbors(i)}")
Neighbors of 0: [1]
Neighbors of 1: [0 2]
Neighbors of 2: [1 3]
Neighbors of 3: [2 4]
Neighbors of 4: [3]

Ring#

[3]:
n = 5
ring = graphs.ring(n=n)
for i in range(n):
    print(f"Neighbors of {i}: {ring.neighbors(i)}")
Neighbors of 0: [1 4]
Neighbors of 1: [0 2]
Neighbors of 2: [1 3]
Neighbors of 3: [2 4]
Neighbors of 4: [0 3]

Random rooted tree (Cayley)#

graphs.cayley(n) draws a uniform random labelled tree on n nodes, via the bijection behind Cayley’s formula (\(n^{n-2}\) labelled trees, each equally likely). A tree is connected and acyclic, so it has exactly n - 1 edges.

The random generators honor the global seed (set_seed), which we fix for reproducibility.

[4]:
from tinto.io import set_seed

set_seed(42)
tree = graphs.cayley(n=7)
for i in range(tree.n):
    print(f"Neighbors of {i}: {tree.neighbors(i)}")

n_edges = sum(len(tree.neighbors(i)) for i in range(tree.n)) // 2
print(f"\n{tree.n} nodes, {n_edges} edges (a tree always has n - 1)")
Neighbors of 0: [4]
Neighbors of 1: [2]
Neighbors of 2: [1 6]
Neighbors of 3: [4 6]
Neighbors of 4: [0 3 5]
Neighbors of 5: [4]
Neighbors of 6: [2 3]

7 nodes, 6 edges (a tree always has n - 1)

Erdős-Rényi#

graphs.erdos_renyi(n, p) is the classic \(G(n, p)\) model: each of the \(\binom{n}{2}\) possible undirected edges appears independently with probability p. Its max_degree is therefore random – and since a Config derives its default number of colors from the max degree (see below), that palette size varies from one draw to the next.

[5]:
set_seed(42)
er = graphs.erdos_renyi(n=7, p=0.4)
for i in range(er.n):
    print(f"Neighbors of {i}: {er.neighbors(i)}")

print(f"\nmax_degree = {er.max_degree} (random, unlike line/ring/tree)")
Neighbors of 0: [1 5 6]
Neighbors of 1: [0 2 6]
Neighbors of 2: [1 5 6]
Neighbors of 3: [4 5]
Neighbors of 4: [3 6]
Neighbors of 5: [0 2 3]
Neighbors of 6: [0 1 2 4]

max_degree = 4 (random, unlike line/ring/tree)

Guards#

A guard is a function guard(config, i) -> bool that takes a configuration (see below) and a node index, and tells whether the considered node can be selected. Some guards may require node ids. Examples of guards:

  • color_clash (no node id required): at least one neighbor has my color.

  • color_clash_tie (node id required): at least one neighbor has my color, and my ID is lower than the IDs of the clashing nodes I see.

  • color_min (no node id required): my color index is not the lowest one absent from my neighborhood.

  • color_min_tie (node id required): my color index is not the lowest one absent from my neighborhood, and neighbors that share my color have a higher ID than me.

Guards are handled by the guards module.

[6]:
from tinto import guards

{k: v for k, v in guards.__dict__.items() if not k.startswith("_")}
[6]:
{'njit': <function numba.core.decorators.njit(*args, **kws)>,
 'color_clash': CPUDispatcher(<function color_clash at 0x0000012EEEA93060>),
 'color_clash_tie': CPUDispatcher(<function color_clash_tie at 0x0000012EEEB5FE20>),
 'color_min': CPUDispatcher(<function color_min at 0x0000012EEFC24180>),
 'color_min_tie': CPUDispatcher(<function color_min_tie at 0x0000012EEFC24040>)}

Configurations#

For a given graph, a coloring associates to each node a color (represented by its index).

A Configuration is a numba jitclass that glues together a graph, a guard, and a coloring. In particular, it keeps track of the guarded nodes.

In practice, to avoid redundant JIT compilation, the building process is as follows:

  • Using the tinto.configs.make function (input: a guard, defaults to color_clash), one creates a Config class.

  • Actual configurations are instantiated by providing a graph (and optionally a number of colors).

  • Post-processing functions are available to alter colors or ids.

Color clash#

Example: we start with the default color_clash. We also set up a seed for reproducibility.

[7]:
from tinto.configs import make
from tinto.io import set_seed

set_seed(42)
ClashConfig = make()
clashconfig = ClashConfig(ring)

No ID.

[8]:
clashconfig.ids
[8]:
array([], dtype=int64)

For a max-degree-2 graph, the configuration defaults to 3 colors.

[9]:
clashconfig.k
[9]:
3

By default, everyone has color 0.

[10]:
clashconfig.colors
[10]:
array([0, 0, 0, 0, 0])

Meaning that every connected node is enabled by the guard.

[11]:
clashconfig.enabled
[11]:
array([ True,  True,  True,  True,  True])
[12]:
clashconfig.total
[12]:
5

If one shuffles the colors, the guarded nodes are not the same.

[13]:
clashconfig.color_randomize()
[14]:
clashconfig.colors
[14]:
array([2, 0, 2, 2, 0])
[15]:
clashconfig.enabled
[15]:
array([False, False,  True,  True, False])

In the example above, nodes 2 and 3 clash with each other.

[16]:
clashconfig.total
[16]:
2

Min Tie#

One could play with all the guards, but let’s just pick another one.

[17]:
MinTieConfig = make(guards.color_min_tie)
config = MinTieConfig(ring, k=4)

IDs are required by the guard.

[18]:
config.ids
[18]:
array([3, 0, 1, 2, 4])

For a max-degree-2 graph, the configuration defaults to 3 colors, but we set up 4 colors.

[19]:
config.k
[19]:
4

By default, everyone has color 0.

[20]:
config.colors
[20]:
array([0, 0, 0, 0, 0])

Meaning that every node with locally minimal ID is enabled by the guard.

[21]:
config.enabled
[21]:
array([False,  True, False, False, False])
[22]:
config.total
[22]:
1

In the example above, 1 is the only local minimum (all other nodes have a neighbor with lower ID).

If one shuffles the colors, the guarded nodes are not the same.

[23]:
config.color_randomize()
[24]:
config.colors
[24]:
array([2, 2, 2, 3, 0])
[25]:
config.enabled
[25]:
array([False,  True, False,  True, False])
[26]:
config.total
[26]:
2

Node 1 is still enabled (it can switch to 0 and is a local minimum among its neighbors of color 2). Node 3 is enabled (current color is 3; can go to 1; no neighbor with color 3).

Starters#

Starters are objects with a draw() method that returns configurations. They define the initial state (possibly randomized) of a simulation.

Currently, the main entry point is from_graph, which, as the name says, will use a fixed graph. As for Configuration, the starter is built in multiple stages:

  • Using a Config class (not an instance), one creates a Starter class; the initial coloring can be random (default) or uniform if one gives a color;

  • The starter is instantiated with a graph;

  • The instance can use its method draw().

[27]:
from tinto.starters import from_graph

Starter = from_graph(make())
starter = Starter(ring)
[28]:
for _ in range(3):
    c = starter.draw()
    print(c.colors)
[2 1 0 1 1]
[1 1 0 0 1]
[1 0 0 0 2]
[29]:
Starter = from_graph(make(guard=guards.color_clash_tie), color=2)
starter = Starter(ring)
[30]:
for _ in range(3):
    c = starter.draw()
    print(f"Ids: {c.ids}")
    print(f"Cls: {c.colors}")
    print(f"Guards: {c.enabled}")
Ids: [0 3 1 4 2]
Cls: [2 2 2 2 2]
Guards: [ True False  True False False]
Ids: [0 1 2 4 3]
Cls: [2 2 2 2 2]
Guards: [ True False False False False]
Ids: [0 1 4 3 2]
Cls: [2 2 2 2 2]
Guards: [ True False False False False]

Schedulers (a.k.a. Daemons)#

Schedulers are functions that, for a given config, return a subset of the enabled nodes through a draw(config) method. The current schedulers are:

Important

By convention, we allow a scheduler to return nothing even if some nodes are enabled, but this does not count as an actual step.

Shuffled#

A random permutation is drawn and a cursor cycles through it. Yields the current node if it is enabled. Shuffled is a sequential, a.k.a. central scheduler (one node at a time).

Note

Currently, the permutation is static. This is 100% OK for one-pass algorithms.

[31]:
from tinto import schedulers

config = make()(ring)
s = schedulers.shuffled()(config)
print(", ".join(str(s.draw(config)) for _ in range(10)))
[1], [3], [4], [2], [0], [1], [3], [4], [2], [0]

Ordered#

Exactly like shuffled but uses np.arange as its unique permutation. Designed for controlled edge-case exploration.

[32]:
s = schedulers.ordered()(config)
print(", ".join(str(s.draw(config)) for _ in range(10)))
[0], [1], [2], [3], [4], [0], [1], [2], [3], [4]

Bernoulli#

Selects each enabled node with probability \(p\).

[33]:
s = schedulers.bernoulli(p=1 / 3)(config)
print("\n".join(str(s.draw(config)) for _ in range(5)))
[2]
[1 2 3]
[2 4]
[2 4]
[]
[34]:
s = schedulers.bernoulli(p=1)(config)
print("\n".join(str(s.draw(config)) for _ in range(5)))
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[35]:
s = schedulers.bernoulli(p=1 / 5)(config)
print("\n".join(str(s.draw(config)) for _ in range(5)))
[2]
[]
[]
[0 2]
[4]

Independent / local#

Same as Bernoulli with a twist: you build your selection one node at a time, and whenever you pick up a node adjacent to another node already selected, you skip the selection. This ensures that the result is always an independent set, avoiding the re-creation of conflicts.

[36]:
s = schedulers.independent(p=1 / 3)(config)
print("\n".join(str(s.draw(config)) for _ in range(5)))
[1 3]
[0]
[3]
[2 4]
[1]
[37]:
s = schedulers.independent(p=1)(config)
print("\n".join(str(s.draw(config)) for _ in range(5)))
[2 4]
[1 3]
[1 4]
[1 3]
[0 3]
[38]:
s = schedulers.independent(p=1 / 5)(config)
print("\n".join(str(s.draw(config)) for _ in range(5)))
[4]
[3]
[]
[0 2]
[]

Solvers / Coloring#

A solver takes as input a configuration and a set of nodes (typically the output of a scheduler) and applies a coloring function to each of the nodes.

  • All colors are decided as a function of the input configuration (not taking into account the possible changes from other nodes);

  • You instantiate a solver through the solvers.make(colorer) function, where the colorer is a (config, node) -> color function.

A few colorers are proposed by default.

Lowest#

Selects the lowest available color. Can cause trouble for non-independent schedulers. To see that, let us write a function that shows the evolution of a configuration.

[39]:
from tinto import solvers

lowest = solvers.make(solvers.colorer_lowest)


def verbose_run(config, scheduler, solver, max_steps=5):
    print(f"Colors: {config.colors}")
    for _ in range(max_steps):
        if config.total == 0:
            print("Done!")
            break
        select = scheduler.draw(config)
        print(f"Selection: {select}")
        solver(config, select)
        print(f"Colors: {config.colors}")
[40]:
config = make()(ring)
s = schedulers.bernoulli(p=1)(config)
verbose_run(config, s, lowest)
Colors: [0 0 0 0 0]
Selection: [0 1 2 3 4]
Colors: [1 1 1 1 1]
Selection: [0 1 2 3 4]
Colors: [0 0 0 0 0]
Selection: [0 1 2 3 4]
Colors: [1 1 1 1 1]
Selection: [0 1 2 3 4]
Colors: [0 0 0 0 0]
Selection: [0 1 2 3 4]
Colors: [1 1 1 1 1]
[41]:
config = make()(ring)
s = schedulers.independent(p=1)(config)
verbose_run(config, s, lowest)
Colors: [0 0 0 0 0]
Selection: [0 3]
Colors: [1 0 0 1 0]
Selection: [1]
Colors: [1 2 0 1 0]
Done!

Next#

Selects the next free color (cyclic). Avoids too much concentration around the lowest color(s), but stays sensitive to non-independent schedulers.

[42]:
nexter = solvers.make(solvers.colorer_next)
config = make()(ring)
s = schedulers.bernoulli(p=1)(config)
verbose_run(config, s, nexter)
Colors: [0 0 0 0 0]
Selection: [0 1 2 3 4]
Colors: [1 1 1 1 1]
Selection: [0 1 2 3 4]
Colors: [2 2 2 2 2]
Selection: [0 1 2 3 4]
Colors: [0 0 0 0 0]
Selection: [0 1 2 3 4]
Colors: [1 1 1 1 1]
Selection: [0 1 2 3 4]
Colors: [2 2 2 2 2]
[43]:
config = make()(ring)
s = schedulers.independent(p=1)(config)
verbose_run(config, s, nexter)
Colors: [0 0 0 0 0]
Selection: [1 4]
Colors: [0 1 0 0 1]
Selection: [2]
Colors: [0 1 2 0 1]
Done!

Next blind#

Returns the next color (cyclic) without checking availability. Models scenarios where you can detect a conflict without a proper view of what’s available. Combining a deterministic step with the absence of a check is a recipe for failure unless a properly randomized scheduler is used.

[44]:
nexter = solvers.make(solvers.colorer_next_blind)
config = make()(ring)
s = schedulers.independent(p=1)(config)
verbose_run(config, s, nexter)
Colors: [0 0 0 0 0]
Selection: [1 4]
Colors: [0 1 0 0 1]
Selection: [2]
Colors: [0 1 1 0 1]
Selection: [2]
Colors: [0 1 2 0 1]
Done!

Random#

Selects a random available color. Designed to destroy unwanted synchrony, but the design can fail. In particular, it can happen that two adjacent nodes always see a single free color, making them loop forever.

[45]:
rand = solvers.make(solvers.colorer_random)
config = make()(ring)
s = schedulers.bernoulli(p=1)(config)
verbose_run(config, s, rand)
Colors: [0 0 0 0 0]
Selection: [0 1 2 3 4]
Colors: [1 1 2 1 1]
Selection: [0 1 3 4]
Colors: [2 0 2 0 0]
Selection: [3 4]
Colors: [2 0 2 1 1]
Selection: [3 4]
Colors: [2 0 2 0 0]
Selection: [3 4]
Colors: [2 0 2 1 1]

Random blind#

Selects another random color, free or not. Models scenarios where you can detect a conflict without a proper view of what’s available. Chaotic by nature.

[46]:
rand = solvers.make(solvers.colorer_random_blind)
config = make()(ring)
s = schedulers.bernoulli(p=1)(config)
verbose_run(config, s, rand)
Colors: [0 0 0 0 0]
Selection: [0 1 2 3 4]
Colors: [2 2 1 1 1]
Selection: [0 1 2 3 4]
Colors: [0 0 2 0 2]
Selection: [0 1]
Colors: [2 2 2 0 2]
Selection: [0 1 2 4]
Colors: [1 1 0 0 1]
Selection: [0 1 2 3 4]
Colors: [2 2 1 2 2]

Runners#

Runners are there to compute the convergence of a coloring problem. Two runners are provided: simple and Monte-Carlo.

Simple runner#

Remember the verbose_run function we defined to monitor the evolution of a configuration? The simple runner is similar, taking as input a configuration, a scheduler, and a solver. The main differences:

  • simple is very fast (JIT);

  • it outputs two integers: the number of (true) steps and the number of activations to convergence.

[47]:
from tinto import runners

rand = solvers.make(solvers.colorer_random_blind)
config = make()(ring)
s = schedulers.bernoulli(p=1)(config)
runners.simple(config, s, rand)
[47]:
(10, 37)

Monte-Carlo#

Runs a bunch of colorings. Compared to simple:

  • You need a starter (e.g. a producer of starting configurations) instead of a single configuration;

  • You can define the number of trials (defaults to 1000 but you should aim higher);

  • Out-of-the-box parallelism;

  • Output is a dictionary with the first 3 moments of # of steps and # of activations.

[48]:
starter = from_graph(make())(graphs.ring(n=100))
rand = solvers.make(solvers.colorer_random_blind)
dict(runners.mc(starter, schedulers.bernoulli(p=1), rand, n_trials=100000))
[48]:
{'steps': (137.42364, 5352.781929150398, 585202.3897595722),
 'activations': (2444.13777, 1178516.4887694279, 1479517014.6305733)}

Important

The runners currently have no time-out whatsoever. That means that if you enter a combination that does not converge, the program will run forever.

Experiments & estimators#

The pieces above answer one question at a time: given this graph, scheduler and solver, how long until convergence? To study a coloring rule you sweep a parameter, average over many random trials, and read off a trend. Tinto wraps that loop in two layers, both exposed at the top level (from tinto import Experiment, Iterator):

  • ``Experiment`` (with Iterator): a parameter sweep glued to runners.mc. It stores the first moments of the # of steps / activations in a tidy structure and offers .series(), .plot(), .to_csv().

  • the ``estimate`` module, reached through Experiment.fit and Experiment.fit_fractions: estimators of behavior. From the swept means and their error bars they fit a law, test for a hidden term, and even recover the exact fractions behind the coefficients.

Here is the whole pipeline at a glance – sweep the size n of a uniformly-started line under the sequential shuffled daemon and the lowest colorer.

[49]:
import numpy as np

from tinto import Experiment, Iterator

set_seed(42)
uniform = from_graph(make(), color=0)  # everyone starts at color 0

exp = Experiment(
    "line",
    iterator=Iterator(
        "starter",
        np.arange(5, 55, 5),
        name="n",
        process=lambda n: uniform(graphs.line(n=n)),
    ),
    scheduler=schedulers.shuffled(),
    solver=solvers.make(),  # lowest
    n_trials=200000,
)
exp.run(progress=False)
exp.series(metric="steps")
[49]:
{'line': ([np.int64(5),
   np.int64(10),
   np.int64(15),
   np.int64(20),
   np.int64(25),
   np.int64(30),
   np.int64(35),
   np.int64(40),
   np.int64(45),
   np.int64(50)],
  [3.001085,
   6.33106,
   9.66647,
   12.99707,
   16.33331,
   19.669665,
   23.000415,
   26.333035,
   29.67011,
   33.00306])}

series returns the measured means; fit turns them into an affine law a*n + b together with goodness-of-fit diagnostics.

[50]:
result = exp.fit(metric="steps")["line"]
print(f"steps(n) ~= {result['beta'][1]:.4f} * n + {result['beta'][0]:.4f}")
print(f"reduced chi2 = {result['chi2_red']:.2f} (p = {result['pvalue']:.2f})")
steps(n) ~= 0.6667 * n + -0.3340
reduced chi2 = 0.92 (p = 0.50)

A reduced \(\chi^2\) near 1 says the affine law fits. The final step asks for the exact fractions hiding in those coefficients:

[51]:
exp.fit_fractions(metric="steps")["line"]["fractions"]
[51]:
[Fraction(-1, 3), Fraction(2, 3)]

The estimator recovers steps(n) = (2n - 1) / 3 – slope 2/3, intercept -1/3 – directly from the simulated data, closing the loop from a coloring rule to its exact convergence law.

That is the end of the tour. From here:

  • basics – your first campaigns, comparing simulation with theory, saving results;

  • advanced – multi-dimensional sweeps, alternative topologies, varying the palette;

  • estimation – hidden-term tests, inverse-power laws, and the fraction machinery in depth.