Algorithmadvanced
QSIM
Also called Kuipers qualitative simulation.
Kuipers's 1986 qualitative simulation. From a qualitative differential equation it builds a tree of possible behaviors by Table 1 transitions and constraint filtering. Sound, not complete.
- Time
- O(b (c^3 + c n 4^n)) worst
- Space
- O(b (n L + c m)) extra
- Where
- L = the largest number of landmarks of a variable; b = the number of states in the behavior tree; c = the number of constraints; m = the bound on the length of a behavior; n = the number of variables
- Model
- Word RAM
- Properties
- deterministicnot exactnot in placeofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Benjamin Kuipers, 1986
QSIM predicts how a physical system can change over time when its laws are known only qualitatively, for example "the force grows with the stretch of the spring" with no number for the stiffness. It reasons about continuous systems that a differential equation describes, not about temporal or spatial relations between events or regions as the other calculi in this area do. From a qualitative differential equation and an initial state, it builds a tree whose branches are the possible behaviors. Kuipers (1986) proved that QSIM is sound but not complete: every real behavior is in the tree, but the tree can also contain behaviors that no real system has.
In plain words
Throw a ball up. You do not know its speed or the strength of gravity, but you know that the height grows while the speed is positive and that the speed falls all the time. From that alone you can say what happens: the ball goes up, stops at some highest point, falls back to where it started and goes on down.
QSIM does this step by step. Each quantity is described only by where it is among a few named values, such as zero or the starting speed, and by whether it goes up, stays, or goes down. For each quantity it lists the few ways that this description can change next. It keeps only the combinations that agree with the laws, and each surviving combination starts a new branch. When a quantity stops between two named values, that point gets a new name, such as "highest point".
The problem
A qualitative differential equation has a list of variables, a quantity space for each variable (a finite ordered list of landmark names from to that contains 0), and constraints between variables: DERIV for , and for with strictly increasing or strictly decreasing, ADD for , MINUS for , and CONSTANT. A monotonic or ADD constraint can carry corresponding values, tuples of landmarks that the functions take at the same time, such as . Many ordinary differential equations with unknown functions and constants give the same qualitative equation.
The qualitative state of a variable is a pair: its value, which is a landmark or an open interval between two adjacent landmarks, and its direction, inc, std or dec. The input is a qualitative differential equation, the qualitative state of every variable at the time point , and a bound on the length of a behavior. The output is the tree of behaviors: sequences of states that alternate between time points and the open intervals between them, each with a status (cycle, quiescent, end or cut).
The algorithm
QSIM(variables, quantity spaces, constraints, initial state, max)- 1
S0 ← the initial state at the time point t0, with the corresponding values that it shows - 2
ACTIVE ← {S0} - 3
while ACTIVE is not empty do take a state S from ACTIVE; if its depth is max then record the behavior of S as cut and continue - 4
for each variable, list its transitions from Table 1: P rules if S is a time point, I rules if S is an interval; drop the moves to minus or plus infinity - 5
for each constraint, keep the tuples of transitions of its arguments that the constraint accepts - 6
Waltz filtering: remove a tuple if a constraint that shares a variable with it has no tuple with the same transition for that variable; repeat until nothing changes - 7
find every global interpretation by depth-first search: one transition per variable, so that each constraint gets one of its kept tuples - 8
build one successor for each interpretation; an I8 or I9 move adds a new landmark, and arguments that are all at landmarks add corresponding values - 9
No Change: if S is an interval, drop a successor in which every variable takes I1, I4 or I7 - 10
Cycle: if a time-point successor equals an earlier time-point state on its path, record its behavior as a cycle - 11
Quiescence: else if every direction of a time-point successor is std, record its behavior as quiescent - 12
else push the successor onto ACTIVE - 13
if no successor of S is left after line L9, record the behavior of S as end
Line L4 uses Table 1 of Kuipers (1986). From a time point, a variable at a landmark with direction std can stay (P1) or move into the interval above (P2) or below (P3); with direction inc or dec it moves into the next interval (P4, P6); inside an interval it stays there (P5, P7). From an interval, a variable that increases in can reach and stop (I2) or go on (I3), stay inside the interval (I4), or stop inside it at a new landmark (I8); I5, I6, I7 and I9 are the decreasing cases, and I1 keeps a variable constant at a landmark. So each variable has at most four candidates.
Line L5 tests each tuple against the meaning of the constraint. For DERIV the direction of must be the sign of . For the two directions must be equal, and for each pair of corresponding values the sign of must equal the sign of . For ADD the signs must be possible for a sum of reals. Line L6 is arc consistency between constraints that share a variable, the method that Waltz used for line drawings. Line L7 then solves the remaining constraint satisfaction problem exactly. Lines L9 to L11 are the global filters of Kuipers (1986, Section 4.8), and line L4 also removes moves to , so the implementation predicts only finite behaviors.
Example
The ball of Kuipers (1986, Section 4.3) has the variables (height), (velocity) and (acceleration), the constraints DERIV, DERIV and CONSTANT, and the quantity spaces : ; : ; : , with . The initial state is inc, dec and std.
| State | Transitions | |||
|---|---|---|---|---|
| , inc | , dec | , std | initial | |
| , inc | , dec | , std | P4, P6, P1 | |
| , std | , dec | , std | I8, I6, I1 | |
| , dec | , dec | , std | P3, P6, P1 | |
| , dec | , dec | , std | I6, I7, I1 | |
| , dec | , dec | , std | P6, P7, P1 |
At the state on , line L4 gives the candidates I4 and I8 (I2 and I3 would go to ), the candidates I5, I6, I7 and I9, and only I1. Line L5 keeps for DERIV the pairs (I4, I7), (I4, I9), (I8, I5) and (I8, I6): goes on rising only while is positive. For DERIV it keeps (I6, I1) and (I7, I1), since must decrease. Line L6 removes (I4, I9) and (I8, I5), and line L7 gives two interpretations. The interpretation (I4, I7, I1) changes nothing and is removed by line L9. The other one, (I8, I6, I1), is the top of the flight: reaches 0 and stops at the new landmark . In the last state every candidate of and except I7 and I9 goes to , the only interpretation is (I7, I7, I1), and line L9 removes it, so the behavior ends with the ball falling below its start.
A spurious behavior. Take the spring without friction: DERIV, DERIV and with the corresponding values , starting at inc, std, dec. With a bound of 10 states QSIM returns three behaviors. One is a cycle: the spring stretches to , comes back to with speed , compresses to and returns to , . In the two others, after one swing the spring comes back to with a new speed landmark , or reaches while is not 0. Every real spring keeps the energy , so it must pass with speed again, and these two behaviors are impossible. This is Theorem 5.3 of Kuipers (1986): the constraints do not express the energy law, so QSIM cannot rule them out.
Correctness
QSIM is sound: if a real system with reasonable functions (continuous, continuously differentiable, with finitely many critical points in a bounded interval) satisfies the qualitative equation and starts in the initial state, its qualitative behavior is a branch of the tree, up to the names of new landmarks (Kuipers 1986, Theorem 5.2). The proof goes step by step. Table 1 lists every change that one reasonable function can make between adjacent distinguished time points (Appendix A). Each constraint test of line L5 is a consequence of the real relation, so it accepts the true tuple (Appendix B). Waltz filtering removes only tuples that cannot be part of any global interpretation, the search of line L7 finds every global interpretation, and the filters of lines L9 to L11 remove only states that add nothing new.
QSIM is not complete: a branch need not be the behavior of any real system, as the spring shows. The constraints are tested locally, one time step at a time, and facts that link distant states, such as conservation of energy, are lost. The full proof for this implementation is in proofs/correctness.md. The tests also check soundness against numeric solutions: they integrate a ball and a damped spring with the Euler method for random constants and check that each sampled trajectory, read qualitatively, is a prefix of a branch.
Proof: QSIM is sound but not completefull
This proof follows Kuipers (Artificial Intelligence 29(3), 1986): Section 2 for the qualitative description of a function, Appendix A for the transitions of Table 1, Appendix B for the constraints, and Section 5 for Theorem 5.2 (soundness) and Theorem 5.3 (spurious behaviors). It checks that each step of the implementation keeps what Kuipers's argument needs.
Setting
A reasonable function is continuous, continuously differentiable on , has finitely many critical points in each bounded interval, and has one-sided limits of at and (Kuipers, Definition 2.1). Each variable has a quantity space: a finite ordered list of landmark values that contains , and . The qualitative state of at a time is the pair , where is the landmark if is a landmark, and else the open interval between two adjacent landmarks that contains , and is inc, std or dec as is positive, zero or negative. The distinguished time points of a system are the times where some variable reaches a landmark or has a critical point; between two adjacent distinguished time points every qualitative state is constant (Kuipers, Section 2). A solution is a tuple of reasonable functions that satisfies the constraints at every time. Its qualitative behavior is the alternating sequence of the qualitative states of the system at the distinguished time points and on the open intervals between them.
Lemma 1 (Table 1 lists every successor of one function)
Let be reasonable, let be adjacent distinguished time points, and let stay finite. If has state at , its state on is one of the P transitions of Table 1 for . If has state on , its state at is one of the I transitions of Table 1 for , where a value strictly inside the interval is a new landmark (I8 and I9).
Proof. This is Kuipers, Propositions A.1, A.2, A.4 and A.5. For the point to interval step: if and , then increases just after , so it lies in and is increasing on the interval (P4); the case is P6. If , then on the next interval is constant (P1), or increasing (P2), or decreasing (P3), since has no zero inside the interval. If is inside an interval, stays in it on the open interval after and keeps the sign of there (P5 and P7; a zero derivative is P1 on a landmark only, since a constant value inside an interval is not a landmark). For the interval to point step: an increasing in reaches at either , with derivative zero (I2) or positive (I3), or stays inside the interval, with positive derivative (I4) or with derivative zero at a new critical value (I8), which becomes a landmark. The decreasing cases I5, I6, I7 and I9 are symmetric, and a constant stays constant (I1).
The function transitions returns exactly these lists, and the test test_table1_counts checks their sizes. It then removes the moves whose value is or (a No Divergence restriction; Kuipers discusses divergence to infinity in Appendix A). This removes nothing for a solution whose values stay finite.
Lemma 2 (the constraint test accepts every real tuple)
Let a solution be at a time , and let the arguments of a constraint have the states there. Then constraint_ok accepts these states, with the corresponding values recorded so far.
Proof. For each kind, the test is a consequence of the real relation.
- DERIV(f, g), : the sign of is the sign of , that is, the direction of equals the sign of the value of against the landmark 0. This is the test
ds[0] == s(1, "0")(Kuipers, Definition 3.4). - CONSTANT(f): , so the direction is std.
- M+(f, g), with continuously differentiable and : has the sign of , so the directions are equal. For a pair of corresponding values, , and has the sign of because is strictly increasing (Kuipers, Definition 3.5 and Proposition B.6 to B.8). M- and MINUS are the same with the signs reversed.
- ADD(f, g, h), : , and for corresponding values with we have (Kuipers, Proposition B.3). Two reals with signs and have a sum whose sign is if or , is if , and is any sign if . The function
_add_okaccepts exactly these triples, so it accepts the true signs.
A new landmark lies strictly inside the interval of its placeholder, and _as_interval tests it as that interval. Its sign against every old landmark is then the true sign. Corresponding values are added only when all arguments are at landmarks (initial_state and line L8), and then they are true values of the solution, so later tests use only true facts.
Lemma 3 (Waltz filtering and the search lose no global interpretation)
Call a choice of one candidate per variable a global interpretation if, for each constraint, the tuple of its arguments is accepted by line L5. Then lines L6 and L7 return exactly the global interpretations.
Proof. Let be a global interpretation. Its tuple for a constraint is in the set of after line L5. Line L6 removes a tuple from the set of only when some other constraint shares a variable with and no tuple of has the same candidate for . The tuple of for has the same candidate for as the tuple of for , so by induction over the removals no tuple of is ever removed. Line L7 is a depth-first search over all choices; it rejects a partial choice only when a constraint with all its arguments chosen has a tuple outside its set. It therefore returns every choice whose tuples are all in the filtered sets, which includes every global interpretation, and every returned choice is a global interpretation since the filtered sets are subsets of the sets of line L5. A variable that appears in no constraint is free and is kept by the search. The test test_waltz_and_search_lose_nothing compares the result with a brute-force product on 500 states.
Lemma 4 (the global filters)
Line L9 (No Change) removes a successor of an interval state in which every variable takes I1, I4 or I7. Such a successor has the same values and directions as the interval state, so it is not a new distinguished time point; the solution is still described by the interval state and the other successors (Kuipers, Section 4.8). Line L10 (Cycle) stops a branch when a time-point state repeats an earlier one on the same branch, and records it; the continuation of the solution is described by the earlier part of the branch. Line L11 (Quiescence) stops a branch at a time point where every variable is std. In the models used here every variable is a state variable or a function of the state variables, so all directions std means that the state is an equilibrium of the differential equation, and by uniqueness of solutions it stays there.
Theorem (soundness)
Let a solution of the differential equation stay finite, start in the initial state, and match the constraints. Then its qualitative behavior, cut after max_states states, is a prefix of one of the behaviors that qsim returns, after each new landmark is replaced by the old interval that contains it.
Proof. By induction on the number of states. The initial state is the root (line L1). Suppose the first states of the behavior of the solution are the path of a state in the tree. By Lemma 1 the next state of each variable is among the candidates of line L4. By Lemma 2 each constraint accepts the tuple of the true next states, so these tuples survive line L5. By Lemma 3 the true next state is among the successors of line L7, and line L8 builds it, with a new landmark for each I8 or I9 move. By Lemma 4 the filters of lines L9 to L11 either keep it, or stop the branch at a point after which the behavior is already described. So the first states are a path in the tree, or the behavior is described by a branch that was stopped and recorded.
This is Theorem 5.2 of Kuipers (1986). The tests check it on numeric solutions: 40 runs of the ball thrown upward and 20 runs of a damped spring, with the Euler method, where the sign changes of each sampled trajectory give its qualitative behavior.
Theorem (incompleteness)
QSIM can return behaviors that no solution has. This is Theorem 5.3 of Kuipers (1986), proved with the frictionless spring , with in : the energy is constant on every solution, so when returns to 0 the speed must be the starting speed . The constraints DERIV(X, V), DERIV(V, A) and M-(A, X) do not express this, and QSIM gives three behaviors from , : a cycle that comes back to , one that reaches with a new speed landmark different from , and one that reaches again while is not 0. The test test_spring_three_branches_and_spurious finds these three branches and checks that two of them break the energy law, so they are spurious.
Termination
Each call of successors is finite: at most four candidates per variable, a finite set of tuples per constraint, a filtering loop that only removes tuples, and a finite search. The main loop only pushes a state with depth below max_states, and every state has finitely many successors, so the tree is finite and the loop stops. Without the bound the tree can be infinite, since each I8 or I9 move creates a new landmark.
Complexity
Each variable has at most four candidates, so line L5 tests at most tuples per constraint, tests in total. Each pass of line L6 compares every pair of constraints, pairs with at most tuples each, and every pass except the last removes a tuple, so there are passes and work. Line L7 can visit up to choices and check constraints at each of levels, which is . One state therefore costs , and the whole run costs for states. Each state stores the quantity spaces, at most landmarks for each of the variables, and the corresponding values, at most tuples per constraint for a bound on the length of a behavior, which gives the space bound.
The real cost is the size of the tree, which can grow exponentially with the length bound. For the damped spring of the tests, the number of behaviors is 1, 7, 29, 123 and 535 for the bounds 4, 6, 8, 10 and 12. Most of this growth comes from branching on variables whose direction is not fixed by the equation, so that every order of their changes becomes a separate branch.
Properties
- Sound. No real behavior is missing from the tree (Kuipers 1986, Theorem 5.2).
- Not complete. The tree can contain spurious behaviors (Kuipers 1986, Theorem 5.3).
- Deterministic. The tree depends only on the input; the order of the branches depends on the order of the variables.
- Makes new landmarks. Lines L4 and L8 add a landmark each time a variable stops inside an interval, such as the top of the ball's flight, so the quantity spaces grow along a branch.
- Needs no numbers. It uses only signs and order. A model with unknown constants describes every system with any values of those constants.
Variants and improvements
- Global filters. Kuipers's pure algorithm has the No Change and Cycle filters and the treatment of infinite values. Later work added filters that use energy, higher-order derivatives and the shape of phase space to remove many spurious behaviors.
- Numeric ranges. Q2 and its successors attach real intervals to the landmarks and remove behaviors whose ranges become empty, so that the tree mixes qualitative and partial numeric knowledge.
- Model building. Qualitative process theory writes the model in terms of processes and influences; its models can be compiled into qualitative differential equations for QSIM.
- Confluences. De Kleer and Brown's qualitative physics uses sign equations between derivatives, called confluences, in place of the constraint types of QSIM.
When to use it
Use QSIM when the structure of a system is known but its parameters are not, and you want every behavior that the structure allows: diagnosis, monitoring, design checks, teaching physics. When a few numbers are known, use one of the variants with numeric ranges. When all parameters are known, a numeric method for the initial value problem gives one exact behavior and is much cheaper. Because the result can contain spurious behaviors, a branch that QSIM predicts is a possibility to check, not a proof that the system can do it; a property that holds on every branch does hold for every real system.
Pitfalls
- No No Change filter. If line L9 is left out, an interval state has a successor that repeats it with I1, I4 or I7 for every variable, and the tree fills with copies of the same interval. In the ball example, (I4, I7, I1) would follow every interval. Line L9 must drop that successor when is an interval.
- Taking the product after Waltz filtering. If line L7 is replaced by every combination of the candidates that survive line L6, the result can contain combinations that break a constraint, because arc consistency is a local test. Line L7 must check each constraint against the full choice.
- Mixing up the P and I rules. If line L4 applies the I rules at a time point, a variable at 0 with direction inc can stay at 0, which no differentiable function does. Line L4 must use the P rules after a time point and the I rules after an interval, so that states alternate.
- Testing a new landmark as an old one. A landmark found by I8 or I9 lies strictly inside the interval. If line L5 compares it as equal to the end of the interval, DERIV can reject the top of the ball's flight. Line L5 must treat it as the open interval until line L8 puts it into the quantity space.
- Reading a branch as a guarantee. If the behaviors that line L12 and lines L10 and L11 record are reported as real, spurious branches such as the two of the spring are reported too. A recorded branch is only a possible behavior; check it with more knowledge, such as energy, before you report it as real.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/qsim/. The authors are listed in prov/9H896N.jsonl.
"""QSIM qualitative simulation (Kuipers 1986), pure algorithm plus the
No Divergence and Quiescence heuristics of its footnote.
A model has variables, a quantity space for each variable (a list of
landmark names from "minf" to "inf" that contains "0"), and constraints:
("DERIV", f, g) g is the time derivative of f
("M+", f, g, corr) f = H(g) with H strictly increasing
("M-", f, g, corr) f = H(g) with H strictly decreasing
("ADD", f, g, h, corr) f + g = h
("MINUS", f, g, corr) f = -g
("CONSTANT", f) f does not change
corr is a list of tuples of corresponding landmark names. A qualitative
value is a landmark name or a pair (lo, hi) of adjacent landmarks; a
direction is "inc", "std" or "dec".
"""
from itertools import product
from typing import Dict, List, Optional, Tuple
QVal = object # a landmark name (str) or a pair (lo, hi)
QState = Tuple[QVal, str]
SIGN = {"inc": 1, "std": 0, "dec": -1}
NEW = "*new*" # placeholder for a landmark found by I8 or I9
class State:
"""One qualitative state of the whole system."""
def __init__(self, values: Dict[str, QState], qspace: Dict[str, Tuple[str, ...]],
corr: Dict[int, frozenset], at_point: bool,
parent: Optional["State"] = None, via: Tuple[str, ...] = ()):
self.values = values
self.qspace = qspace
self.corr = corr
self.at_point = at_point
self.parent = parent
self.via = via
def key(self):
return tuple(sorted(self.values.items(), key=lambda kv: kv[0]))
def _pos(qs: Tuple[str, ...], v) -> float:
"""Position of a value in the quantity space; intervals get half steps."""
if isinstance(v, tuple):
return qs.index(v[0]) + 0.5
return float(qs.index(v))
def _sign_vs(qs: Tuple[str, ...], v, landmark: str) -> int:
d = _pos(qs, v) - qs.index(landmark)
return (d > 0) - (d < 0)
def _add_ok(a: int, b: int, c: int) -> bool:
"""Some reals x, y have sign x = a, sign y = b and sign (x + y) = c."""
if a == b:
return c == a
if a == 0:
return c == b
if b == 0:
return c == a
return True
def transitions(qs: Tuple[str, ...], qval, qdir: str, at_point: bool) -> List[Tuple[str, QVal, str]]:
"""Table 1 of Kuipers (1986): the successors of one variable."""
out = []
if at_point:
if not isinstance(qval, tuple):
j = qs.index(qval)
if qdir == "std":
out.append(("P1", qval, "std"))
if j + 1 < len(qs):
out.append(("P2", (qs[j], qs[j + 1]), "inc"))
if j > 0:
out.append(("P3", (qs[j - 1], qs[j]), "dec"))
elif qdir == "inc":
out.append(("P4", (qs[j], qs[j + 1]), "inc"))
else:
out.append(("P6", (qs[j - 1], qs[j]), "dec"))
elif qdir == "inc":
out.append(("P5", qval, "inc"))
else:
out.append(("P7", qval, "dec"))
else:
if not isinstance(qval, tuple):
out.append(("I1", qval, "std"))
elif qdir == "inc":
lo, hi = qval
out += [("I2", hi, "std"), ("I3", hi, "inc"), ("I4", qval, "inc"),
("I8", (NEW, lo, hi), "std")]
else:
lo, hi = qval
out += [("I5", lo, "std"), ("I6", lo, "dec"), ("I7", qval, "dec"),
("I9", (NEW, lo, hi), "std")]
# No Divergence: never move to an infinite landmark.
return [t for t in out if t[1] not in ("minf", "inf")]
def _as_interval(v):
"""A new landmark sits strictly inside (lo, hi)."""
if isinstance(v, tuple) and v[0] == NEW:
return (v[1], v[2])
return v
def constraint_ok(con, qspace, corr: frozenset, vals: List[QState]) -> bool:
"""Directions of change and magnitudes after a transition (Appendix B)."""
kind = con[0]
args = con[1:1 + len(vals)]
vs = [_as_interval(v) for v, _ in vals]
ds = [SIGN[d] for _, d in vals]
sg = [[_sign_vs(qspace[a], v, lm) for lm in qspace[a]] for a, v in zip(args, vs)]
def s(i, lm):
return sg[i][qspace[args[i]].index(lm)]
if kind == "DERIV":
return ds[0] == s(1, "0")
if kind == "CONSTANT":
return ds[0] == 0
if kind == "M+":
return ds[0] == ds[1] and all(s(0, p) == s(1, q) for p, q in corr)
if kind in ("M-", "MINUS"):
return ds[0] == -ds[1] and all(s(0, p) == -s(1, q) for p, q in corr)
if kind == "ADD":
return _add_ok(*ds) and all(_add_ok(s(0, p), s(1, q), s(2, r)) for p, q, r in corr)
raise ValueError(kind)
def _arity(con) -> int:
return {"DERIV": 2, "CONSTANT": 1, "M+": 2, "M-": 2, "MINUS": 2, "ADD": 3}[con[0]]
def initial_state(variables, qspace, constraints, values) -> State:
qs = {v: tuple(qspace[v]) for v in variables}
corr = {}
for i, con in enumerate(constraints):
base = set(tuple(x) for x in (con[1 + _arity(con)] if len(con) > 1 + _arity(con) else []))
args = con[1:1 + _arity(con)]
if con[0] not in ("DERIV", "CONSTANT") and all(not isinstance(values[a][0], tuple) for a in args):
base.add(tuple(values[a][0] for a in args))
corr[i] = frozenset(base)
return State(dict(values), qs, corr, True)
def successors(variables, constraints, st: State) -> List[State]:
"""One QSIM cycle: Steps 2 to 5 of Kuipers (1986), Section 4.2."""
# @line L4 Table 1 transitions for each variable
cand = {v: transitions(st.qspace[v], st.values[v][0], st.values[v][1], st.at_point)
for v in variables}
# @line L5 constraint filtering of the tuples of each constraint
tuples = []
for i, con in enumerate(constraints):
args = con[1:1 + _arity(con)]
keep = set()
for combo in product(*[range(len(cand[a])) for a in args]):
vals = [(cand[a][c][1], cand[a][c][2]) for a, c in zip(args, combo)]
if constraint_ok(con, st.qspace, st.corr[i], vals):
keep.add(combo)
tuples.append((args, keep))
# @line L6 Waltz filtering: neighbours must agree on shared variables
changed = True
while changed:
changed = False
for i, (args, keep) in enumerate(tuples):
for j, (args2, keep2) in enumerate(tuples):
if i == j:
continue
for pos, a in enumerate(args):
if a not in args2:
continue
pos2 = args2.index(a)
allowed = {t[pos2] for t in keep2}
bad = {t for t in keep if t[pos] not in allowed}
if bad:
keep -= bad
changed = True
# @line L7 global interpretations by depth-first search
order = list(variables)
interps: List[Dict[str, int]] = []
def dfs(k: int, chosen: Dict[str, int]) -> None:
if k == len(order):
interps.append(dict(chosen))
return
v = order[k]
for c in range(len(cand[v])):
chosen[v] = c
ok = True
for args, keep in tuples:
if v in args and all(a in chosen for a in args):
if tuple(chosen[a] for a in args) not in keep:
ok = False
break
if ok:
dfs(k + 1, chosen)
del chosen[v]
dfs(0, {})
# @line L8 build the new states, with new landmarks and corresponding values
out = []
for it in interps:
qspace = dict(st.qspace)
values = {}
for v in variables:
name, qv, qd = cand[v][it[v]]
if isinstance(qv, tuple) and qv[0] == NEW:
lm = v + str(len(qspace[v]))
qs = list(qspace[v])
qs.insert(qs.index(qv[2]), lm)
qspace[v] = tuple(qs)
qv = lm
values[v] = (qv, qd)
corr = {}
for i, con in enumerate(constraints):
args = con[1:1 + _arity(con)]
c = st.corr[i]
if con[0] not in ("DERIV", "CONSTANT") and all(not isinstance(values[a][0], tuple) for a in args):
c = c | {tuple(values[a][0] for a in args)}
corr[i] = c
via = tuple(cand[v][it[v]][0] for v in variables)
out.append(State(values, qspace, corr, not st.at_point, st, via))
return out
def qsim(variables: List[str], qspace: Dict[str, List[str]], constraints: list,
init: Dict[str, QState], max_states: int = 20) -> List[Tuple[List[State], str]]:
"""Return every behavior as (states, status). status is "cycle",
"quiescent", "end" (no consistent successor) or "cut" (length limit).
Precondition: the initial values are landmarks or intervals of their
quantity spaces and satisfy the constraints. Cost: each cycle is
O(c * 4^3) for the tuples plus the interpretations, which can be
exponential in the number of variables (Kuipers 1986, Section 4.9).
"""
# @line L1 the initial state at time-point t0
root = initial_state(variables, qspace, constraints, init)
behaviors = []
# @line L2
active = [(root, 1)]
while active:
# @line L3
st, depth = active.pop()
if depth >= max_states:
behaviors.append((_path(st), "cut"))
continue
kids = []
for nxt in successors(variables, constraints, st):
# @line L9 No Change filter
if not st.at_point and all(t in ("I1", "I4", "I7") for t in nxt.via):
continue
# @line L10 Cycle filter
if nxt.at_point and _repeats(nxt):
behaviors.append((_path(nxt), "cycle"))
kids.append(nxt)
continue
# @line L11 Quiescence
if nxt.at_point and all(d == "std" for _, d in nxt.values.values()):
behaviors.append((_path(nxt), "quiescent"))
kids.append(nxt)
continue
# @line L12
kids.append(nxt)
active.append((nxt, depth + 1))
# @line L13
if not kids:
behaviors.append((_path(st), "end"))
return behaviors
def _repeats(st: State) -> bool:
k = st.key()
p = st.parent
while p is not None:
if p.at_point and p.key() == k:
return True
p = p.parent
return False
def _path(st: State) -> List[State]:
out = []
while st is not None:
out.append(st)
st = st.parent
return out[::-1]
test_qsim.py 215 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/qsim/. The authors are listed in prov/9H896N.jsonl.
import random
from itertools import product
from qsim import _arity, constraint_ok, qsim, successors, transitions
BALL_VARS = ["Y", "V", "A"]
BALL_QS = {"Y": ["minf", "0", "inf"], "V": ["minf", "0", "v0", "inf"], "A": ["minf", "g", "0", "inf"]}
BALL_CONS = [("DERIV", "Y", "V"), ("DERIV", "V", "A"), ("CONSTANT", "A")]
BALL_INIT = {"Y": ("0", "inc"), "V": ("v0", "dec"), "A": ("g", "std")}
SPRING_VARS = ["X", "V", "A"]
SPRING_QS = {"X": ["minf", "0", "inf"], "V": ["minf", "0", "v0", "inf"], "A": ["minf", "0", "inf"]}
SPRING_CONS = [("DERIV", "X", "V"), ("DERIV", "V", "A"), ("M-", "A", "X", [("0", "0")])]
SPRING_INIT = {"X": ("0", "inc"), "V": ("v0", "std"), "A": ("0", "dec")}
# Damped spring: F = -k X, D = -c V, A = F + D.
DAMP_VARS = ["X", "V", "A", "F", "D"]
DAMP_QS = {"X": ["minf", "0", "x0", "inf"], "V": ["minf", "0", "inf"],
"A": ["minf", "a0", "0", "inf"], "F": ["minf", "f0", "0", "inf"],
"D": ["minf", "0", "inf"]}
DAMP_CONS = [("DERIV", "X", "V"), ("DERIV", "V", "A"), ("M-", "X", "F", [("0", "0")]),
("M-", "V", "D", [("0", "0")]), ("ADD", "F", "D", "A", [("0", "0", "0")])]
DAMP_INIT = {"X": ("x0", "std"), "V": ("0", "dec"), "A": ("a0", "inc"),
"F": ("f0", "std"), "D": ("0", "inc")}
def project(qs_initial, qs, value):
"""Map a value to the initial landmarks: a new landmark becomes the
initial interval that contains it."""
if isinstance(value, tuple):
lo, hi = value
elif value in qs_initial:
return value
else:
lo = hi = value
i = qs.index(lo)
while qs[i] not in qs_initial:
i -= 1
j = qs.index(hi)
while qs[j] not in qs_initial:
j += 1
return (qs[i], qs[j])
def compress(seq):
out = []
for s in seq:
if not out or out[-1] != s:
out.append(s)
return out
def qsim_runs(variables, qs0, behaviors):
"""Projected, compressed sequences of interval states of each behavior."""
runs = []
for states, status in behaviors:
seq = []
for st in states:
if not st.at_point:
seq.append(tuple((project(qs0[v], st.qspace[v], st.values[v][0]), st.values[v][1])
for v in variables))
runs.append((compress(seq), status))
return runs
def sgn(x):
return (x > 0) - (x < 0)
def qual(landmarks, x):
"""Qualitative value of a number against named numeric landmarks."""
names = [n for n, _ in landmarks]
vals = [v for _, v in landmarks]
for n, v in landmarks:
if x == v:
return n
i = sum(1 for v in vals if v < x)
return (names[i - 1], names[i])
DIR = {1: "inc", 0: "std", -1: "dec"}
def euler_run(lms, rhs, x, h, steps, variables):
"""Simple Euler; the qualitative state of each sample after t0."""
seq = []
for _ in range(steps):
dx = rhs(x)
x = [a + h * b for a, b in zip(x, dx)]
full, dirs = rhs(x, full=True)
st = tuple((qual(lms[v], val), DIR[sgn(d)]) for v, val, d in zip(variables, full, dirs))
# A sample that sits on a landmark while moving is a time point, not an interval.
if any(not isinstance(q, tuple) and d != "std" for q, d in st):
continue
seq.append(st)
return compress(seq)
def matches(num, runs, m):
"""The first m numeric interval states are a prefix of some behavior."""
num = num[:m]
return any(seq[:len(num)] == num for seq, _ in runs)
def test_ball_trace():
(states, status), = qsim(BALL_VARS, BALL_QS, BALL_CONS, BALL_INIT, max_states=12)
assert status == "end"
assert [s.via for s in states[1:]] == [("P4", "P6", "P1"), ("I8", "I6", "I1"),
("P3", "P6", "P1"), ("I6", "I7", "I1"),
("P6", "P7", "P1")]
top = states[2]
assert top.values["Y"] == ("Y3", "std") and top.values["V"] == ("0", "dec")
assert top.qspace["Y"] == ("minf", "0", "Y3", "inf")
def test_table1_counts():
qs = ("minf", "0", "l", "inf")
assert len(transitions(qs, "0", "std", True)) == 3
assert [t[0] for t in transitions(qs, ("0", "l"), "inc", False)] == ["I2", "I3", "I4", "I8"]
assert [t[0] for t in transitions(qs, ("0", "l"), "dec", False)] == ["I5", "I6", "I7", "I9"]
# No Divergence removes the moves to infinity.
assert [t[0] for t in transitions(qs, ("l", "inf"), "inc", False)] == ["I4", "I8"]
def test_spring_three_branches_and_spurious():
bs = qsim(SPRING_VARS, SPRING_QS, SPRING_CONS, SPRING_INIT, max_states=10)
assert len(bs) == 3
statuses = sorted(s for _, s in bs)
assert statuses == ["cut", "cut", "cycle"]
spurious = 0
for states, _ in bs:
for st in states[1:]:
if not st.at_point:
continue
x, v = st.values["X"][0], st.values["V"][0]
qv = st.qspace["V"]
low = v[0] if isinstance(v, tuple) else v
pos_v = qv.index(low) >= qv.index("0") and v != "0"
# Energy is conserved: X = 0 with V > 0 forces V = v0, and V = v0 forces X = 0.
if (x == "0" and pos_v and v != "v0") or (v == "v0" and x != "0"):
spurious += 1
break
assert spurious == 2
def brute_successors(variables, constraints, st):
cand = {v: transitions(st.qspace[v], st.values[v][0], st.values[v][1], st.at_point) for v in variables}
out = set()
for combo in product(*[range(len(cand[v])) for v in variables]):
pick = dict(zip(variables, combo))
ok = True
for i, con in enumerate(constraints):
args = con[1:1 + _arity(con)]
vals = [(cand[a][pick[a]][1], cand[a][pick[a]][2]) for a in args]
if not constraint_ok(con, st.qspace, st.corr[i], vals):
ok = False
break
if ok:
out.add(tuple(cand[v][pick[v]][0] for v in variables))
return out
def test_waltz_and_search_lose_nothing():
rng = random.Random(1986)
behaviors = qsim(DAMP_VARS, DAMP_QS, DAMP_CONS, DAMP_INIT, max_states=10)
states = [st for b, _ in behaviors for st in b]
rng.shuffle(states)
for st in states[:500]:
got = {s.via for s in successors(DAMP_VARS, DAMP_CONS, st)}
assert got == brute_successors(DAMP_VARS, DAMP_CONS, st)
def test_soundness_ball():
rng = random.Random(7)
runs = qsim_runs(BALL_VARS, BALL_QS, qsim(BALL_VARS, BALL_QS, BALL_CONS, BALL_INIT, max_states=12))
for _ in range(40):
v0 = rng.uniform(1.0, 5.0)
g = -rng.uniform(1.0, 10.0)
lms = {"Y": [("0", 0.0)], "V": [("0", 0.0), ("v0", v0)], "A": [("g", g), ("0", 0.0)]}
lms = {v: [("minf", float("-inf"))] + lms[v] + [("inf", float("inf"))] for v in lms}
def rhs(s, full=False, g=g):
y, v = s
if full:
return [y, v, g], [v, g, 0.0]
return [v, g]
num = euler_run(lms, rhs, [0.0, v0], 1e-3, int(3 * v0 / -g / 1e-3), BALL_VARS)
assert len(num) == 3
assert matches(num, runs, len(num))
def test_soundness_damped_spring():
rng = random.Random(11)
runs = qsim_runs(DAMP_VARS, DAMP_QS, qsim(DAMP_VARS, DAMP_QS, DAMP_CONS, DAMP_INIT, max_states=12))
for _ in range(20):
k = rng.uniform(0.5, 4.0)
c = rng.uniform(0.2, 5.0)
x0 = rng.uniform(0.5, 2.0)
lms = {"X": [("0", 0.0), ("x0", x0)], "V": [("0", 0.0)], "A": [("a0", -k * x0), ("0", 0.0)],
"F": [("f0", -k * x0), ("0", 0.0)], "D": [("0", 0.0)]}
lms = {v: [("minf", float("-inf"))] + lms[v] + [("inf", float("inf"))] for v in lms}
def rhs(s, full=False, k=k, c=c):
x, v = s
a = -k * x - c * v
if full:
return [x, v, a, -k * x, -c * v], [v, a, -k * v - c * a, -k * v, -c * a]
return [v, a]
num = euler_run(lms, rhs, [x0, 0.0], 2e-3, 3000, DAMP_VARS)
assert matches(num, runs, 6)
History
Kuipers (1986) defined qualitative differential equations and the QSIM algorithm, gave the ball and the spring as examples, and proved Theorems 5.2 and 5.3 on soundness and spurious behaviors. Earlier qualitative physics, such as the confluences of de Kleer and Brown (1984) and the qualitative process theory of Forbus (1984), had the same aim with different representations. Kuipers's book (1994) collects QSIM and its later filters and numeric extensions.
References
- Benjamin Kuipers, Qualitative simulation, Artificial Intelligence 29(3), 1986, pages 289 to 338 (Section 2 reasonable functions and qualitative states, Section 3 the constraints, Section 4.2 the algorithm, Table 1 the transitions, Section 4.3 the ball thrown upward, Section 4.8 the global filters, Theorem 5.2 soundness, Theorem 5.3 spurious behaviors of the spring, Appendices A and B the proofs)
- Benjamin Kuipers, Qualitative Reasoning: Modeling and Simulation with Incomplete Knowledge, MIT Press, 1994, the book account of qualitative differential equations, QSIM and its later filters
- Kenneth D. Forbus, Qualitative process theory, Artificial Intelligence 24, 1984, pages 85 to 168 (quantity spaces and influences, the modelling language that QSIM models are often compiled from)
- Johan de Kleer and John Seely Brown, A qualitative physics based on confluences, Artificial Intelligence 24, 1984, pages 7 to 83 (confluences, an earlier qualitative physics with sign equations)
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 9H896N Edit this page History Report an error Markdown