Algorithm Search⌘K

Algorithmresearch

Morris's dynamic controllability algorithm

Also called Morris-Muscettola-Vidal algorithm.

Morris's 2006 check of dynamic controllability for an STNU. It runs K rounds of shortest-path propagation from the lower-case edges and tests the AllMax projection, in O(N^4) time.

Time
O(N^4) worst
Space
O(N^2) extra
Where
K = the number of contingent links; N = the number of time points after the normal form
Properties
deterministicexactnot in placeofflineiterative
Origin
Paul Morris, 2006

Morris's algorithm decides whether a simple temporal network with uncertainty is dynamically controllable: whether an agent that sees each contingent duration when it ends can always schedule its own time points so that every constraint holds. This page gives the version of Morris (CP 2006), which runs in O(N4)O(N^4) time. It finds negative cycles of a special kind, called semi-reducible, by KK rounds of shortest-path propagation from the lower-case edges, where KK is the number of contingent links. It does not compute an execution strategy; Morris's paper gives separate steps for that.

In plain words

Some durations in a plan are set by the world. A truck trip takes between 1 and 3 hours, and you only learn the real time when the truck arrives. Your own actions can wait for what you have seen so far, but not for the future.

The plan is drawn as a graph of distances between moments. A plain cycle with a negative total means the plan is impossible. With uncertain durations, some negative cycles are harmless, because they assume that you know an arrival time before it happens. The algorithm finds the cycles that are really a problem. Starting from the end of each uncertain trip, it looks for the first place where the path goes below zero, adds a shortcut edge for that piece, and repeats. After at most one round for each uncertain trip, a bad cycle shows up as a plain negative cycle.

The problem

An STNU has time points 0,…,n−10, \ldots, n-1, requirement links lo≤tv−tu≤hilo \le t_v - t_u \le hi (either bound may be missing), and KK contingent links A⇒CA \Rightarrow C with integer bounds 0≤x≤y0 \le x \le y: the agent executes the activation point AA, and nature then chooses tC−tA∈[x,y]t_C - t_A \in [x, y]. The contingent points CC are distinct, and every other point is executed by the agent. The question is whether a dynamic execution strategy exists. We use the semantics of Morris (2006): the decision to execute a point at time tt may depend on the contingent durations that ended before or at tt. The input is the list of links; the output is true or false.

Cost is counted on a word-RAM with N=n+KN = n + K nodes, since the normal form adds at most one node for each contingent link.

The algorithm

The algorithm works on the labelled distance graph. A requirement lo≤tv−tu≤hilo \le t_v - t_u \le hi gives the ordinary edges u→hivu \xrightarrow{hi} v and v→−louv \xrightarrow{-lo} u. A contingent link A⇒CA \Rightarrow C with bounds [0,y][0, y] gives the ordinary edges A→yCA \xrightarrow{y} C and C→0AC \xrightarrow{0} A, the lower-case edge A→c:0CA \xrightarrow{c:0} C (nature may choose the smallest duration) and the upper-case edge C→C:−yAC \xrightarrow{C:-y} A (nature may choose the largest one). The AllMax projection is the simple temporal problem made of the ordinary and the upper-case edges, with the labels dropped.

  1. MORRIS-DC(STNU)
  2. 1put the network in normal form: each A ⇒ C in [x, y] with x > 0 becomes A → A' in [x, x] and A' ⇒ C in [0, y - x]
  3. 2build the labelled distance graph G; K ← the number of contingent links
  4. 3for round ← 0 to K do
  5. 4h ← Bellman-Ford potential of the AllMax projection of G
  6. 5if the AllMax projection has a negative cycle then return false
  7. 6if round = K then return true
  8. 7for each lower-case edge e = A --c:0--> C do
  9. 8from C, find shortest paths over ordinary edges and over upper-case edges not labelled C, expanding only nodes at distance ≥ 0
  10. 9for each node v first reached at distance d < 0 by an edge with label ℓ, record the edge A → v with weight d and label ℓ
  11. 10add the recorded edges to G

Line L1 moves each positive lower bound onto a new requirement link. Morris (2006, Section 3.1) shows that this keeps dynamic controllability, and it makes every lower-case edge have weight 0. Line L2 builds the graph as above.

Lines L4 and L5 test the AllMax projection with Bellman-Ford. A negative cycle there is a contradiction that holds even if the agent knew every duration in advance. If there is no such cycle, hh is a feasible potential.

Lines L7 to L9 are one round of propagation. For a lower-case edge ee from AA to CC, line L8 runs Dijkstra's algorithm from CC on the weights w+hu−hvw + h_u - h_v, which are non-negative, as in Johnson's algorithm. It skips lower-case edges and the upper-case edge of the same link, and it stops at the first node of each path whose true distance from CC is negative. That node ends the extension of ee, and the last edge is its moat edge. Line L9 records the edge from AA that the reductions of Morris derive from ee followed by the extension: its weight is the distance dd and its label is the label of the moat edge, ordinary or upper-case.

Line L10 adds the new edges only after the round, so the potential hh stays valid during the round. Line L6 makes the last check after round K−1K - 1: the loop tests the AllMax projection K+1K + 1 times.

Example

Take one contingent link A⇒CA \Rightarrow C with bounds [1,3][1, 3] and a free point BB with the requirement tC−tB=1t_C - t_B = 1. Every single duration has a schedule (tB=tC−1t_B = t_C - 1), so the network is weakly controllable. But BB must be executed one unit before CC, so the agent must fix tBt_B before it sees tCt_C, and no choice works for both tC=tA+1t_C = t_A + 1 and tC=tA+3t_C = t_A + 3. Line L1 adds A′A' with tA′=tA+1t_{A'} = t_A + 1 and the link A′⇒CA' \Rightarrow C with bounds [0,2][0, 2]. The table shows the run, with the nodes AA, CC, BB, A′A'.

Step State
L2 ordinary edges A→1A′A \xrightarrow{1} A', A′→−1AA' \xrightarrow{-1} A, A′→2CA' \xrightarrow{2} C, C→0A′C \xrightarrow{0} A', B→1CB \xrightarrow{1} C, C→−1BC \xrightarrow{-1} B; upper-case edge C→C:−2A′C \xrightarrow{C:-2} A'; lower-case edge A′→c:0CA' \xrightarrow{c:0} C; K=1K = 1
L4, round 0 the AllMax projection is consistent; h=(−3,0,−1,−2)h = (-3, 0, -1, -2) for (A,C,B,A′)(A, C, B, A')
L8 from CC C→BC \to B gives −1-1, a moat end; C→A′C \to A' gives 00, expanded; A′→AA' \to A gives −1-1, a moat end
L9 record A′→−1BA' \xrightarrow{-1} B and A′→−1AA' \xrightarrow{-1} A (the second is already in GG)
L10 add A′→−1BA' \xrightarrow{-1} B
L4, round 1 the cycle A′→−1B→1C→C:−2A′A' \xrightarrow{-1} B \xrightarrow{1} C \xrightarrow{C:-2} A' has weight −2-2
L5 return false

The new edge says that BB must come at least 1 after A′A', because nature may end the link at once. Together with the case where nature waits the full 2 units, this is a contradiction. If the requirement is instead 0≤tB−tC≤10 \le t_B - t_C \le 1, the round from CC finds only the moat end AA at distance −1-1, which adds nothing new, and the check of round 1 returns true: the agent waits for CC and then executes BB. That network is dynamically controllable but not strongly controllable, since no fixed time for BB works for every duration.

Correctness

The method rests on Theorem 1 of Morris (2006): an STNU is dynamically controllable if and only if its labelled distance graph has no semi-reducible negative cycle, that is, a negative cycle that the reductions of Morris can turn into a cycle without lower-case edges. Every edge that line L9 records is derived by those reductions, so the added edges never change the answer, and a negative cycle in the AllMax projection proves that the network is not controllable.

For the other direction, Theorem 3 of Morris (2006) says that a network with a semi-reducible negative cycle also has one whose extensions nest to depth at most KK. Each round replaces every innermost extension by one edge, so the depth drops by one in each round, and after at most KK rounds the cycle has no lower-case edges. The check at line L4 then finds it. The proof, with the reason for the K+1K + 1 checks, is in proofs/correctness.md.

Proof: The K-round propagation decides dynamic controllabilityfull

This proof follows Morris (CP 2006, Sections 3.1 to 3.3). It uses three results of that paper, which we quote with their numbers: the reductions are sound and keep reduced distance (Section 3.1), Theorem 1 and Theorem 2 (Section 3.2) and Theorem 3 (Section 3.3). The semantics is the one of that paper: an execution decision at time tt may depend on the contingent durations that finished before or at tt.

Setting

Line L1 puts the network in normal form: each contingent link A⇒CA \Rightarrow C with bounds [x,y][x, y] and x>0x > 0 becomes a requirement link A→A′A \to A' with bounds [x,x][x, x] and a contingent link A′⇒CA' \Rightarrow C with bounds [0,y−x][0, y - x]. Morris (Section 3.1) shows that a network is dynamically controllable (DC) exactly when its normal form is DC: the new point A′A' is executed exactly xx after AA, so a strategy for one network is a strategy for the other. After L1 every contingent link has the bounds [0,y][0, y], and KK is the number of contingent links.

Line L2 builds the labelled distance graph. A requirement lo≤tv−tu≤hilo \le t_v - t_u \le hi gives the ordinary edges u→hivu \xrightarrow{hi} v and v→−louv \xrightarrow{-lo} u. A contingent link A⇒CA \Rightarrow C with [0,y][0, y] gives the ordinary edges A→yCA \xrightarrow{y} C and C→0AC \xrightarrow{0} A, the lower-case edge A→c:0CA \xrightarrow{c:0} C and the upper-case edge C→C:−yAC \xrightarrow{C:-y} A. The reduced distance of a path is the sum of its weights with the labels ignored. The AllMax projection is the STN with the ordinary edges and the upper-case edges, labels dropped. In the code, a lower-case edge is the triple (a, c, i) of the list lower, an upper-case edge is the key (c, a, i), and an ordinary edge is the key (u, v, None).

The reductions of Morris (2006) are the No-case, Upper-case, Lower-case and Cross-case reductions and Label removal. Each one adds an edge that every dynamic strategy satisfies, and each new edge has the reduced distance of the two edges it replaces. A path is semi-reducible if a sequence of reductions turns it into a path without lower-case edges.

  • Theorem 1 (Morris 2006). The network is DC if and only if its labelled distance graph has no semi-reducible cycle of negative reduced distance.

For a lower-case edge ee in a path PP, an edge e′e' after ee is a drop edge if the reduced distance in PP from the end of ee to the end of e′e' is negative. The first drop edge is the moat edge, and the subpath from the end of ee to the end of the moat edge is the extension of ee. Every proper prefix of an extension has non-negative reduced distance. The moat edge is usable unless it is the upper-case edge of the same contingent link as ee. An extension has a breach if it contains the upper-case edge of the link of ee.

  • Theorem 2 (Morris 2006). A path is semi-reducible if and only if every lower-case edge in it has a usable moat edge. In the proof, an innermost extension with a usable moat edge e′e' reduces to one edge with the reduced distance of the extension, labelled as e′e' (the interior labels are removed by Label removal, because all proper prefixes are non-negative), and then a Lower-case or Cross-case reduction with ee gives one edge from the start of ee with the same label as e′e'.
  • Theorem 3 (Morris 2006). If there is a semi-reducible negative cycle, then there is one that is breach-free and in which all repetitions of a lower-case edge are flat. In such a cycle the extensions nest to depth at most KK.

Soundness of the added edges

Lemma 1. Every edge that line L10 adds is an edge that a sequence of reductions derives from the current graph. So the added edges do not change whether the network is DC.

Proof. Line L8 runs from CC, the end of the lower-case edge e=A→c:0Ce = A \xrightarrow{c:0} C. It uses ordinary edges and upper-case edges whose label is not the link ii of ee (the test lab != own in _propagate), and it never uses a lower-case edge, because lower-case edges are not in edges. A node is expanded only when its true distance from CC is non-negative (the test du < 0 skips it). So every path that the search follows to record a value moats[(C, v, lab)] = d with d<0d < 0 is a breach-free, lower-case-free path from CC whose proper prefixes all have non-negative reduced distance and whose last edge has the label lab. That last edge is the moat edge of ee on the path ee followed by this path, and it is usable because its label is not ii. By the proof of Theorem 2 the path ee followed by the extension reduces to one edge A→vA \to v with weight 0+d0 + d and the label lab. Line L9 keeps the smallest such weight and line L10 adds it. Reductions are sound and keep DC. □\square

The search uses the potential hh of line L4 to run Dijkstra's method on the weights w+hu−hv≥0w + h_u - h_v \ge 0; du recovers the true distance redu+hu−hstart\text{red}_u + h_u - h_{\text{start}}. Since hh is a feasible potential for all edges present during the round, and the new edges are added only after the round (line L10), these reweighted weights stay non-negative during the round, so each distance is a shortest distance over the allowed paths.

Lemma 2. If line L5 returns false, the network is not DC.

Proof. By Lemma 1 the current graph is the original graph plus edges that every dynamic strategy must satisfy. Line L4 found a negative cycle among ordinary and upper-case edges. A negative cycle without lower-case edges is semi-reducible (no reduction is needed), so by Theorem 1 the extended network, and by Lemma 1 the original network, is not DC. □\square

Completeness

Lemma 3. Suppose the graph at the start of a round has a breach-free semi-reducible negative cycle PP with flat repetitions whose extensions nest to depth m≥1m \ge 1. Then the graph at the end of the round has a semi-reducible negative cycle whose extensions nest to depth at most m−1m - 1.

Proof. Take an innermost extension QQ of a lower-case edge e=A→c:0Ce = A \xrightarrow{c:0} C in PP, with moat edge e′e' ending at vv. QQ has no lower-case edge (it is innermost), no upper-case edge with the label of ee (breach-free), all proper prefixes non-negative and a negative total. So QQ is one of the paths that line L8 may follow from CC, and the search finds a value d≤D(Q)d \le D(Q) for some key (C,u,lab)(C, u, \text{lab}) on its way. Two cases.

  • The search reaches vv through the last edge of QQ or a shorter allowed path with the same last label, and line L10 adds A→vA \to v with weight at most D(Q)<0D(Q) < 0 and the label of e′e'.
  • The search stops at an earlier node uu of QQ with a negative distance, so it adds A→uA \to u with a negative weight dud_u. The prefix of QQ up to uu has non-negative reduced distance, so dud_u is smaller than it, and the rest of QQ after uu keeps the cycle negative. This is Morris's remark in Section 3.3: propagating over shortest allowed paths only finds tighter edges earlier.

In both cases replace ee and the covered part of QQ in PP by the new edge. The reduced distance does not grow, so the cycle is still negative. The new edge is ordinary or upper-case with a label different from every lower-case edge that it can be the moat of in PP, because the old moat edges of the outer extensions are kept (the new edge lies inside an extension, and the prefix/postfix property of the outer extensions is kept since the new weight is at most the weight of the part it replaces). By Theorem 2 the cycle is still semi-reducible. Every innermost extension is removed in the same round, since line L7 runs over every lower-case edge, so the depth drops by one. Theorem 3 applied to the new cycle gives again a breach-free cycle with flat repetitions and depth at most m−1m - 1. □\square

Lemma 4. If the network is not DC, line L5 returns false in one of the K+1K + 1 checks.

Proof. By Theorem 1 and Theorem 3 the graph has a breach-free semi-reducible negative cycle with flat repetitions and nesting depth m≤Km \le K. By Lemma 3 after mm rounds there is a negative cycle of depth 0, which is a cycle without lower-case edges, so it is a negative cycle of the AllMax projection. The check of line L4 at the start of round mm finds it. Since m≤Km \le K and the loop of line L3 runs the checks for the rounds 0,1,…,K0, 1, \ldots, K, the check happens. □\square

The check after the last round matters. If the check runs only at the start of each of KK rounds, the edges added in the last round are never tested. The example with one contingent link A⇒CA \Rightarrow C in [1,3][1, 3] and the requirement tB−tC=−1t_B - t_C = -1 (point BB one unit before CC) needs exactly one round of edges and then a check: with K=1K = 1 and no final check, it is accepted, which is wrong.

Theorem. morris_dc returns true if and only if the network is DC.

Proof. If it returns false, then by Lemma 2 the network is not DC. If the network is not DC, then by Lemma 4 it returns false. □\square

Termination

The loop of line L3 runs at most K+1K + 1 times. In each round, line L7 runs over KK lower-case edges, and each call of line L8 is one Dijkstra run over at most NN nodes, where NN is the number of nodes after line L1. Bellman-Ford in line L4 makes at most NN passes. All loops are finite, so the algorithm stops. ■\blacksquare

Complexity

Line L1 adds at most KK nodes, so N≤n+KN \le n + K. Every edge that line L10 adds starts at the start of a lower-case edge, and an upper-case edge labelled with a link always ends at the activation point of that link, because the reductions keep the target of an upper-case edge. So there are at most N2N^2 ordinary edges and at most NKN K upper-case edges at any time, and the graph has E=O(N2)E = O(N^2) edges. This is also the space bound.

Morris (2006) counts K+1K + 1 Bellman-Ford runs of O(EN)O(E N) each and KK Dijkstra runs per round of O(E+Nlog⁡N)O(E + N \log N) each with a heap. With E≤E0+KNE \le E_0 + K N this gives O(KE0N+K2N2+K2Nlog⁡N)O(K E_0 N + K^2 N^2 + K^2 N \log N), and with K≤NK \le N and E0≤N2E_0 \le N^2 it is O(N4)O(N^4) in the worst case. The implementation here uses the array form of Dijkstra's algorithm, O(N2)O(N^2) per run, so a round costs O(N3)O(N^3) for Bellman-Ford and O(KN2)O(K N^2) for the searches, and the total is O(KN3)O(K N^3), which is also O(N4)O(N^4).

Properties

  • Exact. It decides dynamic controllability under the semantics of Morris (2006), with no approximation and no dependence on the size of the bounds.
  • Strongly polynomial. The running time does not depend on the numbers in the bounds, unlike the algorithm of Morris, Muscettola and Vidal (2001).
  • A decision only. It does not return a strategy. To execute the network, Morris (2006, Section 4) adds the wait edges and the lower-case consequences in post-processing steps of the same cost.
  • Integer bounds are not needed. The method works with real bounds; the tests use integers so that the results can be compared exactly.

Variants and improvements

  • Morris, Muscettola and Vidal (2001). The first check, with reductions that create waits, is pseudo-polynomial in the size of the bounds.
  • Morris and Muscettola (2005). A labelled distance graph, the AllMax projection and a cutoff on the number of passes give the first strongly polynomial check, O(N5)O(N^5).
  • Morris (2014). Processing one negative node at a time, with a backward search from each negative node, gives an O(N3)O(N^3) check.
  • Cairo, Hunsberger and Rizzi (2018). The RUL- algorithm runs in O(mn+k2n+knlog⁡n)O(mn + k^2 n + kn \log n) time for nn points, mm edges and kk contingent links.
  • Semantics. Hunsberger (2009) made the meaning of dynamic strategies precise. Some later work uses a stricter semantics in which a reaction must come strictly after the event it reacts to; a check for one semantics is not a check for the other.

When to use it

Use it to test a plan with uncertain durations before it runs, when the agent will see each duration as it ends: in temporal planning, scheduling for robots and space missions, and workflow systems. For large networks, the O(N3)O(N^3) algorithm of Morris (2014) or the RUL- algorithm is faster. If there are no contingent links, the question is consistency of a simple temporal problem, which Bellman-Ford answers in O(NE)O(N E). If the agent cannot observe durations at all, test strong controllability, which is one STP check after a rewrite of the bounds. This page is the 2006 version; it is easier to prove than the 2014 one and has a published pseudocode.

Pitfalls

  • Testing only at the start of each round. If line L6 is moved before line L4, or the loop of line L3 runs only KK times, the edges from the last round are never tested. The example above has K=1K = 1 and needs one round and then a check; with only KK checks it is accepted. Line L3 must run K+1K + 1 checks, with line L6 after line L5.
  • Adding edges during the round. If line L10 is merged into line L9, the potential hh of line L4 is no longer feasible for the new negative edges, and the Dijkstra run of line L8 can give wrong distances. Add the edges after all lower-case edges are done.
  • Using the upper-case edge of the same link. If line L8 also follows C→C:−yAC \xrightarrow{C:-y} A, then a single contingent link, which is always controllable, is reported as not controllable, because the path C→AC \to A is a drop at once. Line L8 must skip the upper-case edge labelled with the same link.
  • Expanding negative nodes. If line L8 goes on past a node at negative distance, it records edges for paths that are not extensions, and the edges that line L9 adds are not derived by the reductions.
  • Skipping the normal form. Line L9 assumes that the lower-case edge has weight 0. Without line L1 the weight xx of the edge must be added to dd, and the label removal rule changes. The normal form keeps both simple.

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.

morris_dynamic_controllability.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/morris-dynamic-controllability/. The authors are listed in prov/KN0N0A.jsonl.

"""Morris's 2006 O(N^4) dynamic controllability check for STNUs.

An STNU has time points 0 .. n - 1. A requirement link (u, v, lo, hi)
asks lo <= t[v] - t[u] <= hi; lo may be None (no lower bound) and hi may
be None (no upper bound). A contingent link (a, c, x, y) says that
t[c] - t[a] is chosen by nature in [x, y], with 0 <= x <= y. The
contingent points must be distinct.

The semantics is the one of Morris (CP 2006): a decision may depend on
the contingent durations observed in the past or at the present instant.
"""

from typing import Dict, List, Optional, Tuple

Req = Tuple[int, int, Optional[int], Optional[int]]
Cont = Tuple[int, int, int, int]
# Edge key (source, target, label). label is None for an ordinary edge,
# or the index of a contingent link for an upper-case edge.
Key = Tuple[int, int, Optional[int]]


def _tighten(edges: Dict[Key, int], key: Key, w: int) -> bool:
    old = edges.get(key)
    if old is None or w < old:
        edges[key] = w
        return True
    return False


def _bellman_ford(n: int, edges: Dict[Key, int]) -> Optional[List[int]]:
    """Potential h with h[v] <= h[u] + w for every edge, or None on a negative cycle."""
    h = [0] * n
    arcs = [(u, v, w) for (u, v, _), w in edges.items()]
    for _ in range(n):
        changed = False
        for u, v, w in arcs:
            if h[u] + w < h[v]:
                h[v] = h[u] + w
                changed = True
        if not changed:
            return h
    return None


def _propagate(n: int, edges: Dict[Key, int], h: List[int], start: int,
               own: int) -> Dict[Key, int]:
    """Shortest allowed paths from start; return the moat ends.

    Allowed edges are ordinary edges and upper-case edges whose label is not
    own. A node is expanded only if its distance is non-negative. The result
    maps (node, label of last edge) to a negative distance.
    """
    out: Dict[int, List[Tuple[int, Optional[int], int]]] = {v: [] for v in range(n)}
    for (u, v, lab), w in edges.items():
        if lab != own:
            out[u].append((v, lab, w))
    inf = float("inf")
    red = [inf] * n  # distance in the reweighted graph
    red[start] = 0
    done = [False] * n
    moats: Dict[Key, int] = {}
    for _ in range(n):
        u = -1
        for v in range(n):
            if not done[v] and red[v] < inf and (u < 0 or red[v] < red[u]):
                u = v
        if u < 0:
            break
        done[u] = True
        du = red[u] + h[u] - h[start]  # true distance from start
        if du < 0:
            continue  # a moat end: the path stops here
        for v, lab, w in out[u]:
            dv = du + w
            if dv < 0:
                key = (start, v, lab)
                if key not in moats or dv < moats[key]:
                    moats[key] = dv
            r = red[u] + w + h[u] - h[v]
            if r < red[v]:
                red[v] = r
    return moats


def morris_dc(n: int, reqs: List[Req], conts: List[Cont]) -> bool:
    """Return True if the STNU is dynamically controllable.

    Precondition: integer bounds, 0 <= x <= y for each contingent link, and
    distinct contingent points. Cost: O(K * N^3) time with N = n + K nodes
    after the normal form, O(N^2 + K * N) space for the edges.
    """
    # @line L1 normal form: move each lower bound x > 0 onto a new executable point
    reqs = list(reqs)
    norm: List[Cont] = []
    for a, c, x, y in conts:
        if x > 0:
            a2 = n
            n += 1
            reqs.append((a, a2, x, x))
            norm.append((a2, c, 0, y - x))
        else:
            norm.append((a, c, 0, y))
    k = len(norm)
    # @line L2 labelled distance graph
    edges: Dict[Key, int] = {}
    for u, v, lo, hi in reqs:
        if hi is not None:
            _tighten(edges, (u, v, None), hi)
        if lo is not None:
            _tighten(edges, (v, u, None), -lo)
    lower: List[Tuple[int, int, int]] = []  # (a, c, index of the link)
    for i, (a, c, _, y) in enumerate(norm):
        _tighten(edges, (a, c, None), y)
        _tighten(edges, (c, a, None), 0)
        lower.append((a, c, i))
        _tighten(edges, (c, a, i), -y)
    # @line L3 rounds
    for rnd in range(k + 1):
        # @line L4 AllMax projection: ordinary and upper-case edges, labels dropped
        h = _bellman_ford(n, edges)
        # @line L5
        if h is None:
            return False
        # @line L6
        if rnd == k:
            return True
        found: Dict[Key, int] = {}
        # @line L7 each lower-case edge a --c:0--> c
        for a, c, i in lower:
            # @line L8 forward over breach-free, lower-case-free paths, stop at the first drop
            for (_, v, lab), d in _propagate(n, edges, h, c, i).items():
                # @line L9 the reduced edge from a, labelled as the moat edge
                _tighten(found, (a, v, lab), d)
        # @line L10 add the new edges after the round
        for key, w in found.items():
            if key[0] != key[1] or w < 0:
                _tighten(edges, key, w)
    return True
test_morris_dynamic_controllability.py 194 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/morris-dynamic-controllability/. The authors are listed in prov/KN0N0A.jsonl.

import random
from itertools import product

from morris_dynamic_controllability import morris_dc


def stn_consistent(n, edges):
    """Bellman-Ford on (u, v, w) edges meaning t[v] - t[u] <= w."""
    h = [0] * n
    for _ in range(n + 1):
        changed = False
        for u, v, w in edges:
            if h[u] + w < h[v]:
                h[v] = h[u] + w
                changed = True
        if not changed:
            return True
    return False


def req_edges(reqs):
    out = []
    for u, v, lo, hi in reqs:
        if hi is not None:
            out.append((u, v, hi))
        if lo is not None:
            out.append((v, u, -lo))
    return out


def weakly_controllable(n, reqs, conts):
    """Every projection is consistent. The set of good duration vectors is
    convex, so it is enough to test the vectors with each duration at x or y."""
    for pick in product(*[(x, y) for _, _, x, y in conts]):
        es = req_edges(reqs)
        for (a, c, _, _), d in zip(conts, pick):
            es += [(a, c, d), (c, a, -d)]
        if not stn_consistent(n, es):
            return False
    return True


def strongly_controllable(n, reqs, conts):
    """Vidal and Fargier: rewrite each bound on a contingent point as a bound
    on its activation point for the worst duration. Activation points must be
    executable."""
    act = {c: (a, x, y) for a, c, x, y in conts}
    es = []
    for u, v, w in req_edges(reqs):
        # t[v] - t[u] <= w for every duration.
        if v in act:  # t[v] = t[a] + d, worst d = y
            a, _, y = act[v]
            v, w = a, w - y
        if u in act:  # t[u] = t[a] + d, worst d = x
            a, x, _ = act[u]
            u, w = a, w + x
        es.append((u, v, w))
    return stn_consistent(n, es)


def dc_by_reductions(n, reqs, conts):
    """Morris and Muscettola (2005) style check, with the reductions of
    Morris (2006): apply the five reductions to the labelled distance graph
    of the original network until nothing changes, and test the AllMax
    projection before each pass. Needs a bounded network to stop."""
    ordinary = {}
    upper = {}
    lower = []
    act = {}

    def tight(d, key, w):
        if key not in d or w < d[key]:
            d[key] = w
            return True
        return False

    for u, v, w in req_edges(reqs):
        tight(ordinary, (u, v), w)
    for i, (a, c, x, y) in enumerate(conts):
        tight(ordinary, (a, c), y)
        tight(ordinary, (c, a), -x)
        lower.append((a, c, x, i))
        tight(upper, (c, a, i), -y)
        act[i] = (a, x)
    while True:
        allmax = [(u, v, w) for (u, v), w in ordinary.items()]
        allmax += [(u, v, w) for (u, v, _), w in upper.items()]
        if not stn_consistent(n, allmax):
            return False
        changed = False
        ords = list(ordinary.items())
        ups = list(upper.items())
        for (p, q), v in ords:
            for (q2, r), w in ords:  # no-case
                if q2 == q and (p != r or v + w < 0):
                    changed |= tight(ordinary, (p, r), v + w)
            for (q2, r, b), w in ups:  # upper-case
                if q2 == q:
                    changed |= tight(upper, (p, r, b), v + w)
        for a, c, x, i in lower:
            for (c2, d), w in ords:  # lower-case
                if c2 == c and w < 0:
                    changed |= tight(ordinary, (a, d), x + w)
            for (c2, d, b), w in ups:  # cross-case
                if c2 == c and w < 0 and b != i:
                    changed |= tight(upper, (a, d, b), x + w)
        for (q, r, b), z in ups:  # label removal
            if z >= -act[b][1]:
                changed |= tight(ordinary, (q, r), z)
        if not changed:
            return True


def random_stnu(rng, horizon=8):
    """Origin 0, k contingent links with executable activation points, and
    some free points. Every point lies in [0, horizon] after the origin."""
    k = rng.randint(1, 2)
    free = rng.randint(0, 2)
    n = 1 + 2 * k + free
    conts = []
    for i in range(k):
        x = rng.randint(1, 3)
        conts.append((1 + 2 * i, 2 + 2 * i, x, x + rng.randint(1, 3)))
    reqs = [(0, v, 0, horizon) for v in range(1, n)]
    for _ in range(rng.randint(1, 4)):
        u, v = rng.sample(range(1, n), 2)
        lo = rng.randint(-4, 3)
        reqs.append((u, v, lo, lo + rng.randint(0, 3)))
    return n, reqs, conts


def test_single_link():
    # A contingent link alone is dynamically controllable.
    assert morris_dc(2, [], [(0, 1, 1, 3)])
    assert morris_dc(2, [], [(0, 1, 0, 5)])


def test_dc_but_not_strong():
    # B must come 0 to 1 after C: wait for C, then execute B.
    n, reqs, conts = 3, [(1, 2, 0, 1)], [(0, 1, 1, 3)]
    assert not strongly_controllable(n, reqs, conts)
    assert morris_dc(n, reqs, conts)
    assert weakly_controllable(n, reqs, conts)


def test_weak_but_not_dc():
    # B must come exactly 1 before C, so B is fixed before C is seen.
    n, reqs, conts = 3, [(2, 1, 1, 1)], [(0, 1, 1, 3)]
    assert weakly_controllable(n, reqs, conts)
    assert not morris_dc(n, reqs, conts)


def test_wait_example():
    # Morris (2006), example 3: C within 1 of B, contingent link [0, 3].
    # C must wait until A + 2 or until B occurs.
    n, reqs, conts = 3, [(1, 2, -1, 1)], [(0, 1, 0, 3)]
    assert morris_dc(n, reqs, conts)
    assert not strongly_controllable(n, reqs, conts)


def test_inconsistent_requirements():
    assert not morris_dc(2, [(0, 1, 2, 1)], [])
    assert morris_dc(2, [(0, 1, 1, 2)], [])


def test_squeezed_link():
    # The requirement 2 <= C - A <= 3 squeezes the contingent link [1, 3].
    assert not morris_dc(2, [(0, 1, 2, 3)], [(0, 1, 1, 3)])


def test_two_links_cross_case():
    # C2 must not be more than 1 after C1. Both links start at the origin.
    n = 3
    conts = [(0, 1, 1, 4), (0, 2, 2, 3)]
    assert not morris_dc(n, [(1, 2, None, 1)], conts)
    assert morris_dc(n, [(1, 2, None, 3)], conts)


def test_random_against_reductions_and_sandwich():
    rng = random.Random(20061)
    counts = {True: 0, False: 0}
    for _ in range(700):
        n, reqs, conts = random_stnu(rng)
        got = morris_dc(n, reqs, conts)
        assert got == dc_by_reductions(n, reqs, conts)
        if strongly_controllable(n, reqs, conts):
            assert got
        if got:
            assert weakly_controllable(n, reqs, conts)
        counts[got] += 1
    assert counts[True] > 100 and counts[False] > 100

History

Vidal and Fargier (1999) defined strong, weak and dynamic controllability for networks with contingent durations. Morris, Muscettola and Vidal (2001) gave the first check for dynamic controllability, which is pseudo-polynomial. Morris and Muscettola (2005) introduced the labelled distance graph and the first strongly polynomial check, in O(N5)O(N^5). Morris (2006) characterised dynamic controllability by semi-reducible negative cycles, proved the nesting depth bound and gave the O(N4)O(N^4) algorithm on this page. Morris (2014) reduced the bound to O(N3)O(N^3), and Cairo, Hunsberger and Rizzi (2018) gave the RUL- algorithm.

References

  1. Paul Morris, A structural characterization of temporal dynamic controllability, CP 2006, Lecture Notes in Computer Science 4204, Springer, 2006, pages 375 to 389 (Section 3.1 the reductions and the normal form, Section 3.2 Theorems 1 and 2 on semi-reducible paths and moat edges, Section 3.3 Theorem 3 and the procedure fastDCcheck with its O(N^4) bound, Section 4 execution)
  2. Paul Morris and Nicola Muscettola, Temporal dynamic controllability revisited, Proceedings of AAAI-05, AAAI Press, 2005, pages 1193 to 1198 (the labelled distance graph, the AllMax projection and the first strongly polynomial check, in O(N^5) time)
  3. Paul Morris, Nicola Muscettola and Thierry Vidal, Dynamic control of plans with temporal uncertainty, Proceedings of IJCAI-01, Morgan Kaufmann, 2001, pages 494 to 502 in dblp (the definition of dynamic controllability, the reductions with waits, and a pseudo-polynomial check)
  4. Paul Morris, Dynamic controllability and dispatchability relationships, CPAIOR 2014, Lecture Notes in Computer Science 8451, Springer, 2014, pages 464 to 479 (an O(N^3) check that processes the negative nodes one at a time)
  5. Massimo Cairo, Luke Hunsberger and Romeo Rizzi, Faster dynamic controllability checking for simple temporal networks with uncertainty, TIME 2018, LIPIcs 120, 2018, pages 8:1 to 8:16 (the RUL- algorithm, in O(mn + k^2 n + kn log n) time)
  6. Luke Hunsberger, Fixing the semantics for dynamic controllability and providing a more practical characterization of dynamic execution strategies, TIME 2009, IEEE, 2009, pages 155 to 162 (a precise definition of dynamic execution strategies and the instantaneous reaction semantics)
  7. Thierry Vidal and Hélène Fargier, Handling contingency in temporal constraint networks, from consistency to controllabilities, Journal of Experimental and Theoretical Artificial Intelligence 11(1), 1999, pages 23 to 45 (strong, weak and dynamic controllability, used here for the reference checks)

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 time.worst
  • a full proof of space.extra
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