Just a quick note before you read on: The code that's behind most of this post is balancers.py and it's an interactive Marimo (Python) notebook so you can easily explore and tweak parameters.
I recently came across a challenge, inspired by the 2020 game Factorio, someone posted on the internet. Here's a little description of the problem and the (partial) solution I came up with. If it sounds fun, I highly recommend trying out the problem for yourself!
An N-M balancer is something that has N inputs and M outputs. Whatever goes into 1 input is evenly balanced among the M outputs. What's the minimum number of 2-2 balancers needed to make an N-M balancer?
For reference, here's an example of a 2-4 balancer:
graph LR
n0("2-2 balancer")
n2("2-2 balancer")
n3("2-2 balancer")
inputs --> n0
inputs --> n0
n0 --> n2
n0 --> n3
n2 --> outputs
n2 --> outputs
n3 --> outputs
n3 --> outputs
Here's an example of a 1-3 balancer:
graph LR
n0("2-2 balancer")
n2("2-2 balancer")
n3("2-2 balancer")
inputs --> n0
n0 --> n2
n0 --> n3
n2 --> outputs
n2 --> outputs
n3 --> outputs
n3 -- backwards edge --> n0
My intitial thought was to brute-force it: generate all matrix representations of graphs where the 2-2 balancer nodes have at most 2 inputs and outputs. For example, a 2-2 balancer can be represented as $\begin{pmatrix} \frac{1}{2} & \frac{1}{2} \\ \frac{1}{2} & \frac{1}{2} \end{pmatrix}$ where each row represents an input and each column represents an output.
However! The representation I actually used is redundant with 1 row/column for each input, 1 row/colum for each output, and 1 row/column for each 2-2 balancer. So the 2-2 balancer would be represented as
$\begin{pmatrix} 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & \frac{1}{2} & \frac{1}{2} \\ 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 1 \end{pmatrix}$
Looking at each row, we see the first input (row number 0) takes all of its inputs and redirects it to the 2-2 balancer (row 2) which then redirects half of it's input to each output (the last rows: rows 3 and 4).
The 1-3 balancer graph above would be represented with this matrix (with 1+3+3 rows/columns):
$G = \begin{pmatrix} 0 & 1 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & \frac{1}{2} & \frac{1}{2} & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & \frac{1}{2} & \frac{1}{2} & 0 \\ 0 & \frac{1}{2} & 0 & 0 & 0 & 0 & \frac{1}{2} \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 \end{pmatrix}$
Each row of the matrix tells you where anything on that input/node/output will go in 1 step. If you multiply the matrix by itself once, then each row tells you where anything on that input/node/output will go in 2 steps. By exponentiating the matrix with itself $K$ times, you can see where the things go in 1, 2, 4, 8, 16, ..., $2^K$ steps.
$G^{1} \times G^{1} = G^{2} \approx\begin{pmatrix} 0 & 0 & 0.125 & 0.125 & 0.25 & 0.25 & 0.25 \\ 0 & 0.0625 & 0 & 0 & 0.3125 & 0.3125 & 0.3125 \\ 0 & 0 & 0 & 0 & 0.5 & 0.5 & 0 \\ 0 & 0 & 0.0625 & 0.0625 & 0.125 & 0.125 & 0.625 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 \end{pmatrix}$
$G^{2} \times G^{2} = G^{4} \approx\begin{pmatrix} 0 & 0 & 0.0078 & 0.0078 & 0.3281 & 0.3281 & 0.3281 \\ 0 & 0.0039 & 0 & 0 & 0.332 & 0.332 & 0.332 \\ 0 & 0 & 0 & 0 & 0.5 & 0.5 & 0 \\ 0 & 0 & 0.0039 & 0.0039 & 0.1641 & 0.1641 & 0.6641 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 \end{pmatrix}$
$G^{4} \times G^{4} = G^{8} \approx\begin{pmatrix} 0 & 0 & 0.0 & 0.0 & 0.3333 & 0.3333 & 0.3333 \\ 0 & 0.0 & 0 & 0 & 0.3333 & 0.3333 & 0.3333 \\ 0 & 0 & 0 & 0 & 0.5 & 0.5 & 0 \\ 0 & 0 & 0.0 & 0.0 & 0.1667 & 0.1667 & 0.6667 \\ 0 & 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 \end{pmatrix}$
Looking at $G^{2^k}$, we can see that anything that goes to the first (and only input at row 0), gets evenly distributed to the 3 outputs (last 3 columns).
The strategy of matrix exponentiation is a little fraught because there's always a small amount that isn't sent to any of the 3 outputs after $2^k$ steps but it's small enough that I think it's safe to just choose a large $k$.
The real issue with this approach is the number of matrices we have to check. Even for a relatively small number of 2-2 balancers, e.g. 10, we would need to generate all matrices with 10x10 matrices where each row/column has 1 or 2 non-zero entries.
import sys
sys.setrecursionlimit(999_999)
MWMS_CACHE = {}
MAX_CELL_VALUE = 1
def matrices_with_max_sums(
col_max_sums: tuple[int, ...],
row_max_sums: tuple[int, ...],
col: int=0) -> int:
if not row_max_sums or not col_max_sums:
return 1
if col >= len(col_max_sums) or not row_max_sums[0]:
return matrices_with_max_sums(col_max_sums, row_max_sums[1:], 0)
while not col_max_sums[col]:
col_max_sums = col_max_sums[:col] + col_max_sums[col + 1:]
if col >= len(col_max_sums):
return matrices_with_max_sums(col_max_sums, row_max_sums[1:], 0)
col_max_sums = tuple(sorted(col_max_sums[:col])) + (col_max_sums[col],) + tuple(sorted(col_max_sums[col + 1:]))
if col == 0:
row_max_sums = tuple(sorted(row_max_sums))
if len(row_max_sums) < len(col_max_sums):
row_max_sums, col_max_sums = col_max_sums, row_max_sums
cache_key = (col_max_sums, row_max_sums, col)
if not cache_key in MWMS_CACHE:
MWMS_CACHE[cache_key] = sum(
matrices_with_max_sums(
col_max_sums[:col] + (col_max_sums[col] - delta,) + col_max_sums[col + 1:],
(row_max_sums[0] - delta,) + row_max_sums[1:],
col + 1)
for delta in range(min(col_max_sums[col], row_max_sums[0], MAX_CELL_VALUE) + 1)
)
return MWMS_CACHE[cache_key]
def print_table_md():
print("N | lower bound of NxN graphs where nodes have <= 2 incoming or outgoing edges | upper bound")
print("--|-----------------------------------------------------------------------------------|-------------")
for n in list(range(1, 16)) + [30]:
# Note: Dividing by n! is meant to account for reordering nodes in the graph *but* that will
# discount some graphs that are unique, such as graphs where 2 nodes have identical connections.
upper_bound = matrices_with_max_sums(tuple([2]*n), tuple([2]*n))
lower_bound = upper_bound // math.factorial(n)
print(f"{n} | {lower_bound} ({math.ceil(math.log10(lower_bound))} digits) | {upper_bound}")
print_table_md()
| N | lower bound of NxN graphs where nodes have <= 2 in/out edges | upper bound |
|---|---|---|
| 1 | 2 (1 digits) | 2 |
| 2 | 8 (1 digits) | 16 |
| 3 | 44 (2 digits) | 265 |
| 4 | 305 (3 digits) | 7343 |
| 5 | 2534 (4 digits) | 304186 |
| 6 | 24341 (5 digits) | 17525812 |
| 7 | 265123 (6 digits) | 1336221251 |
| 8 | 3223713 (7 digits) | 129980132305 |
| 9 | 43227524 (8 digits) | 15686404067098 |
| 10 | 633055041 (9 digits) | 2297230134084416 |
| 11 | 10045335555 (11 digits) | 400977650310256537 |
| 12 | 171583167860 (12 digits) | 82188611938415464231 |
| 13 | 3137333991152 (13 digits) | 19536244019455339261970 |
| 14 | 61116361676012 (14 digits) | 5328019975275896220786388 |
| 15 | 1263210013724401 (16 digits) | 1651867356348327784988233291 |
| 30 | 14354092992263813327303007636788625296 (38 digits) | 3807464216208107350460188990059785315093779975514127912651027922402036 |
So... maybe 633,055,041 isn't so many 10-node graphs if we don't need to calculate a number closer to the upper bound of 2,297,230,134,084,416.
However 171,583,167,860 is definitely too much for 12-node graphs and there are probably many many times more than that. So this might be a workable strategy for small graphs but not for large ones. The lower bound appears to grow super-exponentially.
What if we strictly build N-M balancers out of smaller balancers? We might not find the minimal graphs for building N-M balancers out of 2-2 balancers but we should be able to get relatively small balancers.
As far as I can tell there are three ways to make a new balancer out of existing balances.
If you simply ignore an input, then an N-M balancer becomes an (N-1)-M balancer.
If you take one of the outputs and put it back as an input, then an N-M balancer becomes a (N-1)-(M-1) balancer.
Start with X copies of an A-B balancer and B copies of an X-Y balancer. Then take each output from each A-B balancer and feed it to a different X-Y balancer. Now you have an AX-BY balancer.
For example, below we take 2 1-3 balancers and feed them into 3 2-3 balancers to create a (1*2)-(3*3) = 2-9 balancer.
graph LR
n0("1-3")
n1("1-3")
n2("2-3")
n3("2-3")
n4("2-3")
n0 --> n2
n0 --> n3
n0 --> n4
n1 --> n2
n1 --> n3
n1 --> n4
n2 --> outputs
n2 --> outputs
n2 --> outputs
n3 --> outputs
n3 --> outputs
n3 --> outputs
n4 --> outputs
n4 --> outputs
n4 --> outputs
inputs --> n0
inputs --> n1
Implementing those rules plus a little extra code, we can now look at low-level graphs of 2-2 balancers or high-level graphs showing how larger balancers are composed of smaller ones:
Note that the 2-2 balancers are labeled as 0,1,2, ..., etc.
Minimum number of nodes for a 3 to 7 balancer: 8
The graph can be reconstructed in code via:
infeed_one(multiplex(balancer_2_2(), multiplex(balancer_2_2(), ignore_one_input(balancer_2_2()), 1, 2), 2, 2))
graph LR
n0("0")
n1("1")
n2("2")
n3("3")
n4("4")
n5("5")
n6("6")
n7("7")
n0 --> n2
n0 --> n5
n2 --> n3
n2 --> n4
n5 --> n6
n5 --> n7
n1 --> n2
n1 --> n5
inputs --> n0
inputs --> n0
inputs --> n1
n3 --> outputs
n3 --> outputs
n4 --> outputs
n4 --> outputs
n6 --> outputs
n6 --> outputs
n7 --> outputs
n7 --> n1
And here's a high level representation of the 3-7 balancer:
graph LR
subgraph x0["3-7 infeed_one"]
x1
end
subgraph x1["4-8 multiplex"]
x2
x3
x8((input))
end
subgraph x3["2-4 multiplex"]
x4
x5
x7((input))
end
subgraph x5["1-2 ignore_one_input"]
x6
end
x2("2-2")
x4("2-2")
x6("2-2")
x7 -- 1 --> x4
x4 -- 2 --> x5
x8 -- 2 --> x2
x2 -- 2 --> x3
Of course it's also a good idea to double check and make sure make sure that these larger balancers actually balance. I also think it's interesting to see how long it takes for balances to reach an equilibrium. For example, when you have a 1-3 balancer (that is a 2-2 balancer with one of its outputs fed to one of its inputs), there's a certain number of edges/hops/steps that some input must go through before it gets from the first 2-2 balancer to the output. Since some of the output as sent in back as input, there will be some proportion of the original input that does not get to the output until many steps later.
In the graphs below we turn the graph into its matrix form, then for a subset of the inputs, we see how much of that input goes to each output after T steps. We can also measure the "error" by looking at how much of the input has gone to each output versus how much is expected in an N-M balancer.
Every balancer with multiple layers will take at least as many steps as there are layers for input to go to the output.
def simulate(n, m, num_steps):
g = graph_for_nm(n, m)
mat = graph_to_matrix(g)
data = []
expected_steady_state = 1 / n / m
for input_index in range(n):
v = np.zeros(len(mat))
v[input_index] = 1 / n
for steps in range(num_steps):
v @= mat
for output_index in range(m):
value = v[len(mat) - m + output_index]
data.append(dict(
steps=steps,
in_out=f"{input_index}:{output_index}",
expected=expected_steady_state,
error=abs(value - expected_steady_state),
value=value
))
df = pd.DataFrame.from_records(data)
return df

And now after all that, we can look a heatmap showing the minimum number of 2-2 balancers that it (probably) takes to create an N-M balancer.

And if we want to look at the heatmap much more zoomed out, you get beautiful heatmap below, showing (probably) all the N-M balancers that can be made with 1,000 or fewer 2-2 balances.
The color scheme is a little custom hack because I like how it looks. In general, the minimum number of nodes you need to make an N-M balancer (N is y-axis and M is x-axis) goes up the further right and down you go (as N or M increase).

COMMENTS
You can comment on this post by replying to infosec.exchange/@mikelmcdaniel/117630463852535363 on Mastodon.
Don't have a Mastodon account? JoinMastodon.org.