Algorithm Search⌘K

Algorithmresearch

Consensus-based bundle algorithm

Also called CBBA.

A decentralized auction in which each robot builds a bundle of tasks greedily and neighbors agree on the winners by message passing, giving a conflict-free assignment.

Time
O(r L t + m (t + r)) per_roundO(min(t, L r) D) rounds
Space
O(r (t + r)) extra
Counts
messages O(m) per_roundmessages O(t + r) size
Where
D = the diameter of the communication graph; L = the largest bundle; m = the number of edges; r = the number of robots; t = the number of tasks
Properties
deterministicofflinenot randomized
Origin
Han Lim Choi, Luc Brunet, Jonathan P. How, 2009

The consensus-based bundle algorithm (CBBA) assigns tasks to a robot team without a central auctioneer. Each robot greedily builds a bundle of tasks it bids on, then it exchanges its list of winning bids with its neighbors and drops the tasks it has lost, and the rounds repeat until all robots agree. Unlike the contract net protocol, where a manager collects bids for one task, every robot here acts as bidder and auctioneer at once, and robots may hold several tasks. Under diminishing marginal gain it reaches a conflict-free assignment in at most min⁡(t,Lr)D\min(t, L r) D rounds, and the assignment is at least half of the optimum.

In plain words

Each robot looks at the list of jobs and writes down the best ones it can still win, one after the other, until its list is full or no job is worth more to it than to the robot that holds it now. Then it tells its neighbors: "this is who I think wins each job, and for how much." When a robot hears that someone else bids more on a job in its list, it gives the job up, and it also gives up every job it added after that one, because those bids counted on the lost job.

The robots repeat this. The news of the best bids travels one neighbor per round, so after enough rounds every robot has the same table and no job has two owners. Nobody ever needs to see the whole team at once.

The problem

The model. There are rr robots and tt tasks. Robot ii can hold at most LL tasks. A task jj added to a bundle that already holds nn tasks is worth aijγna_{ij} \gamma^n to robot ii, with scores aij>0a_{ij} > 0 and a discount 0<γ≤10 < \gamma \le 1. This score has diminishing marginal gain (DMG): a task is never worth more to a robot after the robot has added other tasks. Each task goes to at most one robot. The communication graph is fixed, undirected and connected, with mm edges and diameter DD. Time is synchronous: in each round every robot runs its bundle phase, then sends one message to each neighbor, then runs the consensus phase on what it received.

Input. The scores aija_{ij}, the discount γ\gamma, the bundle limit LL, and the neighbor lists.

Output. For each robot its bundle; for each robot and task the winner it believes and the winning bid. At the end all robots hold the same winners.

How it differs from close pages. Multi-robot task allocation is the problem, and market-based task allocation is the family of auction methods; CBBA is the member that needs no auctioneer and no complete graph. The contract net protocol gives one task per robot through managers that hear every bid. The auction algorithm of Bertsekas raises prices until an optimal assignment within ε\varepsilon is reached, but it assumes one task per robot and a shared price list. CBBA trades optimality for local messages and gets a 50 percent bound instead. The consensus phase is a max-consensus on the bids, close to flooding, and not the averaging of the Laplacian consensus protocol.

The algorithm

Each robot ii keeps its bundle bib_i, a winning bid yijy_{ij} and a winner zijz_{ij} for each task, and a timestamp siks_{ik} for each robot kk: the last round in which it had news from kk. A bid (y,z)(y, z) beats (y′,z′)(y', z') when y>y′y > y', or y=y′y = y' and zz has the smaller index.

  1. CBBA(a, gamma, L, neighbors)
  2. 1b_i ← empty; y_ij ← 0; z_ij ← none; s_ik ← 0 for all i, j, k
  3. 2for round = 1, 2, ... do
  4. 3for each robot i do ▷ bundle phase
  5. 4while |b_i| < L do
  6. 5c_ij ← a_ij · gamma^|b_i| for each task j not in b_i
  7. 6J ← the tasks j where (c_ij, i) beats (y_ij, z_ij)
  8. 7if J is empty then break
  9. 8j ← the task in J with the largest c_ij; append j to b_i; y_ij ← c_ij; z_ij ← i
  10. 9each robot i sends (y_i, z_i, s_i) to every neighbor
  11. 10for each robot i and each neighbor k do ▷ consensus phase
  12. 11for each task j: update, reset or leave (y_ij, z_ij) by the decision table, using y_kj, z_kj and the timestamps
  13. 12each robot i sets s_ik ← round for its neighbors and takes the newer timestamps of the others
  14. 13each robot i finds the first task in b_i it no longer wins, removes it and every later task, and withdraws its own bids on the later tasks
  15. 14stop when nothing has changed for r rounds
  16. 15return b, y, z

Lines L4 to L8 are the greedy bundle phase: the robot adds the task with the best marginal score as long as that score beats the winner it knows. Line L11 is the decision table of Choi, Brunet and How (2009). It has one row for each case of "who the sender thinks wins" and "who the receiver thinks wins": the robot itself, the other robot, a third robot, or none. A receiver takes the sender's bid when the sender wins with a better bid, and it takes the sender's view of a third robot when the sender's timestamp for that robot is newer. Line L13 is the release rule: bids added after a lost task were computed with the lost task in the bundle, so they are no longer true.

The code changes one detail of line L13. The paper resets every later task of the bundle. The code removes these tasks from the bundle, but it keeps a record that another robot wins one of them, and it resets only the entries where the robot itself was the winner. With the paper's rule the code fell into a cycle on about one random instance in three thousand (measurement), because the reset erased the news about the true winner of a later task in every round.

Example

Three robots on the path 0−1−20 - 1 - 2, two tasks, L=1L = 1 and γ=1\gamma = 1. The scores, in any unit of value, are:

task 0 task 1
robot 0 10 9
robot 1 4 6
robot 2 8 1

Round 1. In the bundle phase robot 0 claims task 0 with 10, robot 1 claims task 1 with 6, and robot 2 claims task 0 with 8. Robot 1 hears robots 0 and 2 and learns that robot 0 wins task 0 with 10. Robot 0 hears robot 1 and learns that robot 1 wins task 1 with 6. Robot 2 hears only robot 1, which did not know about task 0 at the end of the last round, so robot 2 keeps its claim.

Round 2. Robot 2 hears from robot 1 that robot 0 wins task 0 with 10, and it releases task 0. Robot 2 then bids 1 on task 1, which does not beat 6.

The result after 2 rounds is task 0 to robot 0 and task 1 to robot 1, with value 10+6=1610 + 6 = 16. This is also the sequential greedy assignment (SGA): take the largest score, 10, then the largest among the rest, 6. The optimum, found by brute force, gives task 1 to robot 0 and task 0 to robot 2, value 9+8=179 + 8 = 17. So 16≥17/216 \ge 17 / 2 as Theorem 1 of the proof says, and the gap is real. The bound of Theorem 2 is min⁡(t,Lr)D=2⋅2=4\min(t, L r) D = 2 \cdot 2 = 4 rounds, and 2 were used.

Correctness

The proof has three parts. Theorem 1, a full proof: the score of each robot is monotone and submodular, the rule "one robot per task" is a partition matroid, and SGA is the greedy algorithm for this function, so by the argument of Fisher, Nemhauser and Wolsey (1978) its value is at least half of the optimum. Theorem 2 is the theorem of Choi, Brunet and How (2009): under DMG, on a fixed connected graph with synchronous rounds and the paper's decision table, all robots agree on a conflict-free assignment equal to SGA within min⁡(t,Lr)D\min(t, L r) D rounds. It is stated with a proof sketch, and the changed release rule of the code is checked by measurement on 300 random instances. Theorem 3, a full proof: on a path with one task, DD rounds are needed.

Proof: Under diminishing marginal gain the sequential greedy assignment that CBBA reaches is at least half of the optimum, and agreement needs at least as many rounds as the distance to the winnerpartial

There are rr agents and tt tasks, with scores aij>0a_{ij} > 0. Agent ii can hold at most LL tasks. The score of a bundle is the one of the code on the CBBA page: if agent ii already holds nn tasks, a new task jj is worth aijγna_{ij} \gamma^n, with 0<γ≤10 < \gamma \le 1. The communication graph is fixed, undirected and connected, with diameter DD, and time is synchronous. Lines L1 to L15 refer to the pseudocode on the page.

The proof has three parts. Theorem 1 is a full proof that the sequential greedy assignment (SGA) is at least half of the optimum under this score. Theorem 2, that CBBA reaches the SGA assignment without conflicts within NminDN_{min} D rounds, is the theorem of Choi, Brunet and How (2009); here it is stated with its hypotheses and a proof sketch, and the tests check it on random instances. Theorem 3 is a full proof that DD rounds can be needed.

The team score

For a set SS of tasks given to agent ii, let fi(S)=∑n=0min⁡(∣S∣,L)−1γnx(n)f_i(S) = \sum_{n=0}^{\min(|S|, L) - 1} \gamma^n x_{(n)}, where x(0)≥x(1)≥…x_{(0)} \ge x_{(1)} \ge \dots are the values aija_{ij}, j∈Sj \in S, in decreasing order. This is the best score of the bundle when the agent does its best tasks first and ignores tasks beyond LL. The team score of an assignment, which gives each task to at most one agent, is F=∑ifi(Si)F = \sum_i f_i(S_i). The test helper assignment_value computes FF, and the brute force optimum maximizes it.

Lemma 1 (diminishing marginal gain). Each fif_i is monotone and submodular: for S⊆TS \subseteq T and a task j∉Tj \notin T, fi(S∪{j})−fi(S)≥fi(T∪{j})−fi(T)≥0f_i(S \cup \{j\}) - f_i(S) \ge f_i(T \cup \{j\}) - f_i(T) \ge 0.

Proof. Let topk(S)\mathrm{top}_k(S) be the sum of the kk largest values in SS, or of all of them if ∣S∣<k|S| < k. It is the weighted rank function of the uniform matroid of rank kk, which is monotone and submodular. The weights wn=γnw_n = \gamma^n for n<Ln < L and wn=0w_n = 0 for n≥Ln \ge L do not increase in nn, so by summation by parts fi=∑k≥1(wk−1−wk)topkf_i = \sum_{k \ge 1} (w_{k-1} - w_k) \mathrm{top}_k, a combination of these functions with coefficients ≥0\ge 0. Such a combination is monotone and submodular. □\square

FF is then a monotone submodular function of the set of agent-task pairs, and the rule "each task goes to at most one agent" is a partition matroid on these pairs.

Lemma 2 (SGA is the greedy algorithm for FF). SGA repeatedly takes the agent-task pair (i,j)(i, j) with the largest value aijγ∣Si∣a_{ij} \gamma^{|S_i|} among free tasks and agents with ∣Si∣<L|S_i| < L. Each such value is the true marginal gain F(G+(i,j))−F(G)F(G + (i, j)) - F(G), and every pair that SGA does not consider has marginal gain 00.

Proof. When SGA gives task j′j' to agent ii with value aij′γna_{ij'} \gamma^{n}, the value of every free task jj for the same agent was at most this, so aij≤aij′a_{ij} \le a_{ij'}. So the tasks of each agent arrive in decreasing order of aija_{ij}, and every free task has a value at most the smallest value in SiS_i. Adding such a task to SiS_i puts it at position ∣Si∣|S_i| in the sorted order, so the gain is aijγ∣Si∣a_{ij} \gamma^{|S_i|} if ∣Si∣<L|S_i| < L and 00 if ∣Si∣=L|S_i| = L. □\square

Theorem 1 (half of the optimum). Let GG be the SGA assignment and OO an optimal one. Then F(G)≥12F(O)F(G) \ge \frac12 F(O).

Proof. Let g1,…,gkg_1, \dots, g_k be the pairs that SGA picks, in order, with gains δ1,…,δk\delta_1, \dots, \delta_k, so F(G)=∑τδτF(G) = \sum_\tau \delta_\tau, and let Gτ={g1,…,gτ}G_\tau = \{ g_1, \dots, g_\tau \}. By monotonicity and submodularity, F(O)≤F(O∪G)≤F(G)+∑e∈O∖GΔ(e∣G)F(O) \le F(O \cup G) \le F(G) + \sum_{e \in O \setminus G} \Delta(e \mid G), where Δ(e∣X)=F(X+e)−F(X)\Delta(e \mid X) = F(X + e) - F(X). Take e=(i,j)∈O∖Ge = (i, j) \in O \setminus G. If SGA gave task jj to some agent at step τ\tau, then ee was a feasible pair before step τ\tau, because task jj was free, so Δ(e∣Gτ−1)≤δτ\Delta(e \mid G_{\tau - 1}) \le \delta_\tau by Lemma 2 and the greedy choice, and Δ(e∣G)≤Δ(e∣Gτ−1)\Delta(e \mid G) \le \Delta(e \mid G_{\tau - 1}) by submodularity. Each step τ\tau takes one task, and OO gives each task to one agent, so each δτ\delta_\tau is used at most once. If SGA never gave task jj away, then when SGA stopped, agent ii was full, since otherwise the pair (i,j)(i, j) was still available; so Δ(e∣G)=0\Delta(e \mid G) = 0 by Lemma 2. Summing, F(O)≤F(G)+∑τδτ=2F(G)F(O) \le F(G) + \sum_\tau \delta_\tau = 2 F(G). □\square

This is the argument of Fisher, Nemhauser and Wolsey (1978) for greedy maximization of a monotone submodular function over a matroid, applied to this score. The test test_half_of_optimum_under_dmg checks 2F≥F(O)2 F \ge F(O) against brute force and finds instances with F<F(O)F < F(O), so the bound is not an equality. On the three-agent example of the page, SGA gives 1616 and the optimum is 1717.

Convergence to the SGA assignment

Theorem 2 (Choi, Brunet and How 2009). Suppose the score has diminishing marginal gain, the network is fixed and connected with diameter DD, the rounds are synchronous, and the consensus phase uses the decision table of the paper. Then after at most NminDN_{min} D rounds, where Nmin=min⁡(t,Lr)N_{min} = \min(t, L r), all agents hold the same winners and winning bids, no task has two winners, and the assignment is the SGA assignment.

Proof sketch. Induction on the SGA steps. Suppose all agents agree on the first kk SGA pairs. The pair (i∗,j∗)(i^*, j^*) of step k+1k + 1 has the largest value among the rest. Under diminishing marginal gain no agent can bid more than this value on j∗j^* once its bundle holds its first SGA tasks, so agent i∗i^* adds j∗j^* in its bundle phase, and no other bid on j∗j^* beats it. The table makes a receiver update to a bid that the sender wins with a better bid, and the timestamps make newer information win over older information about a third agent. So the claim of i∗i^* on j∗j^* spreads one hop per round, is never reset, and reaches every agent within DD rounds. Each SGA step adds one pair, and there are at most NminN_{min} steps. The full proof, with the cases of the table, is in the paper. □\square

What the code changes, and how it is checked. The release rule of line L13 in the paper resets every task after the first task the agent has lost. The code removes these tasks from the bundle, but it keeps a record that another agent wins such a task, and it resets only the entries where the agent itself was the winner. With the paper's rule, the code ran into a cycle of period one on about one random instance in three thousand, because the reset erased the information about the true winner of a later task in every round. The test test_agreement_and_equal_to_sequential_greedy checks on 300 random instances, with up to 6 agents and 7 tasks on random connected graphs, that all agents agree, that no task has two winners, that the result equals SGA, and that the number of rounds is at most NminDN_{min} D. These are measurements, not a proof for the changed rule.

A lower bound on the rounds

Theorem 3 (DD rounds can be needed). On a path of rr agents with one task, L=1L = 1, and ai0=i+1a_{i0} = i + 1, every agent must end with winner r−1r - 1, and agent 00 cannot know it before round r−1=Dr - 1 = D.

Proof. The best agent is r−1r - 1, so by Theorem 2 and Lemma 2 all agents end with winner r−1r - 1. In round 1, agent 0 claims the task for itself, since it knows no other bid. In a synchronous round an agent receives only the values its neighbors held at the end of the round before, so information that starts at agent r−1r - 1 reaches agent r−1−kr - 1 - k at the earliest in round kk. So agent 0 learns of agent r−1r - 1's bid at the earliest in round r−1r - 1, and before that its winner is wrong. □\square

The test test_line_needs_diameter_rounds measures exactly r−1r - 1 rounds for r=2,…,7r = 2, \dots, 7, so the bound of Theorem 2 is reached for Nmin=1N_{min} = 1.

Complexity

  • Rounds (theorem). At most NminDN_{min} D with Nmin=min⁡(t,Lr)N_{min} = \min(t, L r), by Theorem 2, and at least DD in the worst case, by Theorem 3. On a path of rr robots with one task the tests measure exactly r−1=Dr - 1 = D rounds.
  • Messages (theorem). Every round sends one message along each edge in each direction, 2m2 m messages, each with tt bids, tt winners and rr timestamps.
  • Work per round. The bundle phase of one robot scans tt tasks for each of at most LL additions, O(Lt)O(L t), so O(rLt)O(r L t) for the team. The consensus phase costs O(t+r)O(t + r) per message, O(m(t+r))O(m (t + r)) in total, in the real RAM model.
  • Memory. Each robot stores O(t+r)O(t + r) numbers, and the team O(r(t+r))O(r (t + r)).

Properties

  • Conflict-free at convergence (theorem, under DMG). No task has two winners.
  • Half of the optimum (theorem, under DMG). The value is at least 1/21/2 of the best assignment; the example shows 1616 against 1717.
  • Local messages. Robots talk only to neighbors, and the graph need not be complete. A message has a fixed size.
  • Needs DMG. The convergence theorem assumes it. If a task can be worth more after other tasks are added, for example because it lies on the way, a robot can outbid itself later and the robots may not agree (heuristic warning, no bound).
  • Deterministic with the tie rule on robot indices.

Variants and improvements

  • CBAA. The consensus-based auction algorithm of the same paper is the case L=1L = 1: one task per robot, and the same 50 percent bound.
  • Path scores. In the paper the score of a task is its gain when it is inserted at the best place in the robot's path. Many path scores break DMG, and later work changed the score to restore it.
  • Asynchronous versions. Later work from the same group replaced the synchronous rounds by message rules for asynchronous networks and changing graphs. The bound of Theorem 2 does not carry over directly.
  • Coupled constraints. Extensions add time windows and tasks that need several robots.
  • Centralized greedy. If one server can collect all scores, it can run SGA directly: at most min⁡(t,Lr)\min(t, L r) steps, each a scan of rtr t pairs, so O(min⁡(t,Lr) rt)O(\min(t, L r) \, r t) time, with the same assignment and no rounds.

When to use it

Use CBBA when a team of a few to a few tens of robots must split many tasks, each robot may take several, the network is not complete, and no robot should be a single point of failure. It fits search, surveillance and delivery missions where a task is worth less as the robot gets busier. Do not use it when the scores have no diminishing gain, when an optimal assignment is needed, or when one reliable server can run an exact solver.

Pitfalls

  • Scores without DMG. Bundle scores that grow with the bundle make the consensus cycle. Check the score, or use a discount like γn\gamma^n.
  • Release rule details. Resetting too much in line L13 can erase news about other winners and cause cycles; resetting too little leaves stale bids. Test the release rule on many random instances.
  • Stopping too early. A round with no change does not mean the robots agree, because news may still be on its way. Wait at least DD quiet rounds; the code waits rr.
  • Timestamps. Without timestamps, old news about a third robot can overwrite new news, and the table cannot decide between them.
  • Changing graphs. The bound of Theorem 2 assumes a fixed connected graph. If links drop, rounds can be lost and the bound no longer holds.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

consensus_based_bundle_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/consensus-based-bundle-algorithm/. The authors are listed in prov/FENCPV.jsonl.

"""Consensus-based bundle algorithm (CBBA) of Choi, Brunet and How (2009).

Agents are 0..u-1 and tasks are 0..t-1. Each agent i keeps
  b[i]  its bundle, the tasks it has claimed, in the order it added them,
  y[i]  its list of winning bids, y[i][j] is the best bid on task j it knows,
  z[i]  its list of winners, z[i][j] is the agent it believes wins task j (or None),
  s[i]  its timestamps, s[i][k] is the round of the latest information from agent k.

The score is the one used for diminishing marginal gain (DMG) in this file:
agent i that already holds n tasks gains a[i][j] * gamma**n from task j, with
0 < gamma <= 1, and holds at most cap tasks. The marginal gain never grows when
the bundle grows, which is the DMG condition that the convergence proof needs.

The network is a fixed undirected graph, and time is synchronous: in each round
every agent runs the bundle phase, sends (y, z, s) to its neighbors, and then
runs the consensus phase on the messages of that round.
"""

from typing import Optional, Sequence

UPDATE, RESET, LEAVE = "update", "reset", "leave"


def beats(y1: float, z1: Optional[int], y2: float, z2: Optional[int]) -> bool:
    """True if bid y1 of agent z1 is better than bid y2 of agent z2.

    Equal bids go to the agent with the smaller index; any bid beats no bid.
    """
    if z1 is None:
        return False
    if z2 is None:
        return y1 > 0 or y2 <= 0
    return y1 > y2 or (y1 == y2 and z1 < z2)


def decide(i, k, yk, zk, sk, yi, zi, si) -> str:
    """The action rule of CBBA for one task, when agent i receives from agent k.

    yk, zk are the winning bid and winner that sender k reports, and sk its
    timestamps; yi, zi, si are the values of receiver i. This is the decision
    table of Choi, Brunet and How (2009) for the sender's view (k, i, another
    agent m, or nobody) against the receiver's view.
    """
    if zk == k:
        if zi == i:
            return UPDATE if beats(yk, k, yi, i) else LEAVE
        if zi == k or zi is None:
            return UPDATE
        m = zi
        if sk[m] > si[m] or beats(yk, k, yi, m):
            return UPDATE
        return LEAVE
    if zk == i:
        if zi == i or zi is None:
            return LEAVE
        if zi == k:
            return RESET
        m = zi
        return RESET if sk[m] > si[m] else LEAVE
    if zk is None:
        if zi == i or zi is None:
            return LEAVE
        if zi == k:
            return UPDATE
        m = zi
        return UPDATE if sk[m] > si[m] else LEAVE
    m = zk  # the sender thinks a third agent m wins
    if zi == i:
        return UPDATE if sk[m] > si[m] and beats(yk, m, yi, i) else LEAVE
    if zi == k:
        return UPDATE if sk[m] > si[m] else RESET
    if zi == m or zi is None:
        return UPDATE if sk[m] > si[m] else LEAVE
    n = zi  # the receiver thinks a fourth agent n wins
    if sk[m] > si[m] and sk[n] > si[n]:
        return UPDATE
    if sk[m] > si[m] and beats(yk, m, yi, n):
        return UPDATE
    if sk[n] > si[n] and si[m] > sk[m]:
        return RESET
    return LEAVE


def bundle_phase(i, b, y, z, a, gamma, cap) -> None:
    """Agent i adds tasks greedily while it can outbid the winner it knows."""
    while len(b) < cap:  # @line L4
        best = None
        for j in range(len(a[i])):
            if j in b:
                continue
            c = a[i][j] * gamma ** len(b)  # @line L5
            if beats(c, i, y[j], z[j]):  # @line L6
                if best is None or c > best[0]:
                    best = (c, j)
        if best is None:  # @line L7
            break
        c, j = best
        b.append(j)  # @line L8
        y[j] = c
        z[j] = i


def cbba(
    a: Sequence[Sequence[float]],
    neighbors: Sequence[Sequence[int]],
    gamma: float = 1.0,
    cap: Optional[int] = None,
    max_rounds: int = 10000,
) -> dict:
    """Run CBBA on scores a[i][j] > 0 over the graph given by neighbor lists.

    Returns the final bundles, winners and winning bids of every agent, and the
    number of rounds until the last change.
    """
    u = len(a)
    t = len(a[0]) if u else 0
    cap = t if cap is None else cap
    b = [[] for _ in range(u)]  # @line L1
    y = [[0] * t for _ in range(u)]
    z = [[None] * t for _ in range(u)]
    s = [[0] * u for _ in range(u)]
    last_change = 0
    for rnd in range(1, max_rounds + 1):  # @line L2
        before = ([list(v) for v in b], [list(v) for v in y], [list(v) for v in z])
        for i in range(u):  # @line L3
            bundle_phase(i, b[i], y[i], z[i], a, gamma, cap)
        sent = [(list(y[k]), list(z[k]), list(s[k])) for k in range(u)]  # @line L9
        for i in range(u):
            si = list(s[i])
            for k in sorted(neighbors[i]):  # @line L10
                yk, zk, sk = sent[k]
                for j in range(t):
                    act = decide(i, k, yk[j], zk[j], sk, y[i][j], z[i][j], si)  # @line L11
                    if act == UPDATE:
                        y[i][j], z[i][j] = yk[j], zk[j]
                    elif act == RESET:
                        y[i][j], z[i][j] = 0, None
        for i in range(u):  # @line L12
            new = list(s[i])
            for k in neighbors[i]:
                new[k] = rnd
                for m in range(u):
                    if m != i and m not in neighbors[i]:
                        new[m] = max(new[m], sent[k][2][m])
            new[i] = rnd
            s[i] = new
        for i in range(u):  # @line L13
            lost = [n for n, j in enumerate(b[i]) if z[i][j] != i]
            if lost:
                first = lost[0]
                for j in b[i][first + 1:]:
                    # The bid on j assumed the lost task, so it is withdrawn.
                    # Information that another agent wins j is kept.
                    if z[i][j] == i:
                        y[i][j], z[i][j] = 0, None
                del b[i][first:]
        after = (b, y, z)
        if before != after:
            last_change = rnd
        elif rnd - last_change > u:  # @line L14
            break
    return {"bundles": b, "winners": z, "bids": y, "rounds": last_change}  # @line L15


def sequential_greedy(a, gamma=1.0, cap=None) -> dict:
    """The sequential greedy algorithm (SGA): take the best agent-task pair, repeat."""
    u = len(a)
    t = len(a[0]) if u else 0
    cap = t if cap is None else cap
    bundles = [[] for _ in range(u)]
    winner = [None] * t
    while True:
        best = None
        for i in range(u):
            if len(bundles[i]) >= cap:
                continue
            for j in range(t):
                if winner[j] is None:
                    c = a[i][j] * gamma ** len(bundles[i])
                    if best is None or c > best[0]:
                        best = (c, i, j)
        if best is None:
            break
        c, i, j = best
        bundles[i].append(j)
        winner[j] = i
    return {"bundles": bundles, "winners": winner}


def assignment_value(a, bundles, gamma=1.0) -> float:
    """Team score of the bundles, with each bundle in its best order."""
    total = 0
    for i, bundle in enumerate(bundles):
        vals = sorted((a[i][j] for j in bundle), reverse=True)
        total += sum(v * gamma ** n for n, v in enumerate(vals))
    return total
test_consensus_based_bundle_algorithm.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/consensus-based-bundle-algorithm/. The authors are listed in prov/FENCPV.jsonl.

import itertools
import random
from collections import deque

from consensus_based_bundle_algorithm import (
    assignment_value,
    cbba,
    decide,
    sequential_greedy,
)


def path_graph(u):
    return [[k for k in (i - 1, i + 1) if 0 <= k < u] for i in range(u)]


def random_graph(rng, u):
    nb = [set() for _ in range(u)]
    for i in range(1, u):
        k = rng.randrange(i)
        nb[i].add(k)
        nb[k].add(i)
    for _ in range(rng.randint(0, u)):
        if u > 1:
            i, k = rng.sample(range(u), 2)
            nb[i].add(k)
            nb[k].add(i)
    return [sorted(v) for v in nb]


def diameter(nb):
    best = 0
    for src in range(len(nb)):
        dist = {src: 0}
        queue = deque([src])
        while queue:
            x = queue.popleft()
            for w in nb[x]:
                if w not in dist:
                    dist[w] = dist[x] + 1
                    queue.append(w)
        best = max(best, max(dist.values()))
    return best


def brute_optimum(a, gamma, cap):
    """Brute force over every way to give each task to one agent or to nobody."""
    u, t = len(a), len(a[0])
    best = 0
    for choice in itertools.product(range(-1, u), repeat=t):
        bundles = [[j for j in range(t) if choice[j] == i] for i in range(u)]
        if any(len(bd) > cap for bd in bundles):
            continue
        best = max(best, assignment_value(a, bundles, gamma))
    return best


def check_consistent(res, u, t, cap):
    z = res["winners"]
    for i in range(u):
        assert z[i] == z[0]
        assert res["bids"][i] == res["bids"][0]
    for i in range(u):
        assert len(res["bundles"][i]) <= cap
        for j in res["bundles"][i]:
            assert z[0][j] == i
    owners = [j for i in range(u) for j in res["bundles"][i]]
    assert len(owners) == len(set(owners))
    assert sorted(owners) == sorted(j for j in range(t) if z[0][j] is not None)


def test_three_agents_on_a_path():
    a = [[10, 9], [4, 6], [8, 1]]
    res = cbba(a, path_graph(3), gamma=1.0, cap=1)
    check_consistent(res, 3, 2, 1)
    assert res["bundles"] == [[0], [1], []]
    assert res["winners"][0] == [0, 1]
    assert res["bids"][0] == [10, 6]
    assert res["rounds"] == 2
    assert assignment_value(a, res["bundles"]) == 16
    assert brute_optimum(a, 1.0, 1) == 17


def test_decision_table_cases():
    s_old, s_new = [0, 0, 0, 0], [1, 1, 1, 1]
    # sender 1 says it wins with a better bid than receiver 0
    assert decide(0, 1, 5, 1, s_old, 3, 0, s_old) == "update"
    assert decide(0, 1, 2, 1, s_old, 3, 0, s_old) == "leave"
    # sender says the receiver wins, receiver thinks the sender wins
    assert decide(0, 1, 3, 0, s_old, 4, 1, s_old) == "reset"
    # sender reports a third agent 2 with newer information
    assert decide(0, 1, 7, 2, s_new, 4, 3, s_old) == "update"
    assert decide(0, 1, 7, 2, s_old, 4, None, s_old) == "leave"
    # sender has no winner and the receiver thinks the sender wins
    assert decide(0, 1, 0, None, s_old, 4, 1, s_old) == "update"


def test_agreement_and_equal_to_sequential_greedy():
    rng = random.Random(2024)
    for _ in range(300):
        u = rng.randint(1, 6)
        t = rng.randint(1, 7)
        nb = random_graph(rng, u)
        a = [[rng.random() for _ in range(t)] for _ in range(u)]
        gamma = rng.choice([1.0, 0.9, 0.5])
        cap = rng.randint(1, t)
        res = cbba(a, nb, gamma, cap)
        check_consistent(res, u, t, cap)
        sga = sequential_greedy(a, gamma, cap)
        assert res["winners"][0] == sga["winners"]
        n_min = min(t, cap * u)
        assert res["rounds"] <= n_min * max(1, diameter(nb))


def test_ties_still_agree():
    rng = random.Random(17)
    for _ in range(200):
        u = rng.randint(2, 5)
        t = rng.randint(1, 6)
        nb = random_graph(rng, u)
        a = [[rng.randint(1, 3) for _ in range(t)] for _ in range(u)]
        cap = rng.randint(1, t)
        res = cbba(a, nb, 1.0, cap)
        check_consistent(res, u, t, cap)


def test_half_of_optimum_under_dmg():
    rng = random.Random(99)
    worst = 1.0
    for _ in range(60):
        u = rng.randint(1, 3)
        t = rng.randint(1, 5)
        nb = random_graph(rng, u)
        a = [[rng.uniform(0.1, 1.0) for _ in range(t)] for _ in range(u)]
        gamma = rng.choice([1.0, 0.8, 0.5])
        cap = rng.randint(1, t)
        res = cbba(a, nb, gamma, cap)
        got = assignment_value(a, res["bundles"], gamma)
        assert abs(got - sum(v for v in res["bids"][0] if v)) < 1e-12
        opt = brute_optimum(a, gamma, cap)
        assert got <= opt + 1e-12
        assert 2 * got >= opt - 1e-12
        worst = min(worst, got / opt)
    assert worst < 1.0


def test_line_needs_diameter_rounds():
    # One task that every agent wants; the best agent sits at one end.
    for u in range(2, 8):
        a = [[float(i + 1)] for i in range(u)]
        res = cbba(a, path_graph(u), cap=1)
        assert res["winners"][0] == [u - 1]
        assert res["rounds"] == u - 1

History

Brunet, Choi and How presented consensus-based auctions at the AIAA Guidance, Navigation and Control Conference in 2008. Choi, Brunet and How published CBAA and CBBA in the IEEE Transactions on Robotics in 2009, with the decision table, the convergence theorem and the 50 percent bound under diminishing marginal gain. The bound comes from the classic result of Fisher, Nemhauser and Wolsey (1978) on greedy maximization of submodular functions over a matroid. Later work from the same group added asynchronous messages and coupled constraints.

References

  1. Han-Lim Choi, Luc Brunet and Jonathan P. How, Consensus-based decentralized auctions for robust task allocation, IEEE Transactions on Robotics 25(4), 2009, pages 912 to 926 (CBAA and CBBA, the decision table of the consensus phase, diminishing marginal gain, convergence and the 50 percent bound)
  2. Luc Brunet, Han-Lim Choi and Jonathan P. How, Consensus-based auction approaches for decentralized task assignment, AIAA Guidance, Navigation and Control Conference, 2008, the paper as a whole (the first version of the consensus-based auctions)
  3. G. Ayorkor Korsah, Anthony Stentz and M. Bernardine Dias, A comprehensive taxonomy for multi-robot task allocation, International Journal of Robotics Research 32(12), 2013, pages 1495 to 1512 (the classes of task allocation with dependent costs)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of correctness
  • a full proof of time.per_round
  • a full proof of time.rounds
  • a full proof of space.extra
  • a full proof of messages.per_round
  • a full proof of messages.size
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example