Fourier–Motzkin消元实战:消掉一个变量后,为什么每个下界都要与每个上界配对
未知数出现在等式里,可以尝试用一行消掉另一行;出现在不等式里,还必须保住大小方向。Fourier–Motzkin先把某个变量的条件分成上界和下界,再要求所有下界都不超过所有上界,从而把这个变量暂时投影出去。
本文处理系数为整数或Fraction的非严格线性不等式,返回一个精确有理解,或者None表示无解。消元后还会逐层回代,恢复真正满足原系统的坐标;不是只返回一份较少变量的条件表。
AI模型生成的概念插图:上下透明约束板投到低维带状区域,金色点从投影带回到板间,表达投影与回代;不是精确可行域、比例图或运行截图。
完整程序与实际输出
把下列完整源码保存为demo.py,执行python3 demo.py。本次在Linux、CPython 3.12.14实际运行,退出码为0,标准错误为空。程序只使用标准库与固定教学数据,在本地内存中运行。
from fractions import Fraction as F
from itertools import combinations
from random import Random
def feasible(dimension, constraints):
if type(dimension) is not int or not 0 <= dimension <= 4:
raise ValueError("dimension must be an integer from zero to four")
if not isinstance(constraints, (tuple, list)) or len(constraints) > 32:
raise ValueError("at most 32 input constraints required")
rows = []
for row in constraints:
if not isinstance(row, (tuple, list)) or len(row) != 2:
raise ValueError("a constraint is (coefficients, bound)")
coefficients, bound = row
if not isinstance(coefficients, (tuple, list)) or len(coefficients) != dimension:
raise ValueError("coefficient width mismatch")
values = (*coefficients, bound)
if any(type(x) not in (int, F) or abs(x) > 10**6 for x in values):
raise ValueError("bounded exact integers or Fractions required")
rows.append((tuple(map(F, coefficients)), F(bound)))
stages = []
def eliminate(current, size):
# Remove true constants and duplicate rows, retaining contradictions.
if any(not any(a) and b < 0 for a, b in current):
return None
current = list(dict.fromkeys((a, b) for a, b in current if any(a)))
if size == 0:
return ()
positive = [(a, b) for a, b in current if a[-1] > 0]
negative = [(a, b) for a, b in current if a[-1] < 0]
projected = [(a[:-1], b) for a, b in current if a[-1] == 0]
candidates = len(projected) + len(positive) * len(negative)
if candidates > 4096:
raise RuntimeError("projection pair budget exceeded")
for p, bp in positive:
for q, bq in negative:
ap, aq = p[-1], -q[-1]
projected.append((tuple(p[j] / ap + q[j] / aq for j in range(size - 1)),
bp / ap + bq / aq))
stages.append((size, len(current), len(projected)))
partial = eliminate(projected, size - 1)
if partial is None:
return None
lower, upper = [], []
for a, b in current:
remainder = b - sum((c * x for c, x in zip(a[:-1], partial)), F(0))
if a[-1] > 0:
upper.append(remainder / a[-1])
elif a[-1] < 0:
lower.append(remainder / a[-1])
lo, hi = max(lower, default=None), min(upper, default=None)
assert lo is None or hi is None or lo <= hi
value = lo if lo is not None else hi if hi is not None else F(0)
return partial + (value,)
point = eliminate(rows, dimension)
if point is not None:
assert all(sum((c * x for c, x in zip(a, point)), F(0)) <= b for a, b in rows)
return point, stages
def vertex_reference(rows):
# Only used for 2D tests that explicitly include a bounded box.
for (a, b), (c, d) in combinations(rows, 2):
determinant = a[0] * c[1] - a[1] * c[0]
if determinant == 0:
continue
x = F(b * c[1] - a[1] * d, determinant)
y = F(a[0] * d - b * c[0], determinant)
if all(u * x + v * y <= limit for (u, v), limit in rows):
return True
return False
sample = (((1, 1), 4), ((1, -1), 0), ((-2, 0), -3), ((0, -1), 0))
point, stages = feasible(2, sample)
print("point:", tuple(map(str, point)))
print("(dimension, input rows, projected rows):", stages)
print("zero-coefficient contradiction:", feasible(2, (((1, 0), -1), ((-1, 0), 0)))[0])
print("only lower bound:", tuple(map(str, feasible(1, (((-1,), -5),))[0])))
print("unconstrained:", tuple(map(str, feasible(3, ())[0])))
print("half-integer forced:", tuple(map(str, feasible(1, (((2,), 1), ((-2,), -1)))[0])))
assert feasible(0, (((), -1),))[0] is None
assert feasible(0, (((), 0),))[0] == ()
rng = Random(6706)
box = [((1, 0), 3), ((-1, 0), 3), ((0, 1), 3), ((0, -1), 3)]
for _ in range(800):
rows = box + [((rng.randrange(-3, 4), rng.randrange(-3, 4)), rng.randrange(-6, 7))
for _ in range(rng.randrange(7))]
point, unused = feasible(2, rows)
assert (point is not None) == vertex_reference(rows)
if point is not None:
assert all(sum(a[i] * point[i] for i in range(2)) <= b for a, b in rows)
print("independent bounded-polytope comparisons:", 800)
crowded = [((i, i * i, i - 8, 1), 1) for i in range(16)]
crowded += [((100 + j, j**3 + 1, j - 8, -1), 1) for j in range(16)]
try:
feasible(4, crowded)
except RuntimeError as error:
print("budget stop, not infeasible:", error)
else:
raise AssertionError("expected projection budget stop")
for args in ((1, (((1.0,), 2),)), (1, (((True,), 2),)), (2, (((1,), 2),))):
try:
feasible(*args)
except ValueError as error:
print("rejected:", error)
else:
raise AssertionError("invalid system accepted")以下为上述完整程序的实际标准输出,与可执行源码分开列出:
point: ('3/2', '3/2')
(dimension, input rows, projected rows): [(2, 4, 3), (1, 3, 2)]
zero-coefficient contradiction: None
only lower bound: ('5',)
unconstrained: ('0', '0', '0')
half-integer forced: ('1/2',)
independent bounded-polytope comparisons: 800
budget stop, not infeasible: projection pair budget exceeded
rejected: bounded exact integers or Fractions required
rejected: bounded exact integers or Fractions required
rejected: coefficient width mismatch统一成系数点积不超过右侧
每条约束表示为(coefficients,bound),含义是系数与变量逐项相乘求和不超过bound。变量默认可以取任意实数,不自动要求非负;下界x≥3应显式写成−x≤−3。
等式可以拆成相反方向的两条非严格不等式。输入不支持严格小于、整数变量或非线性项,也拒绝浮点数;要表达二分之一,应使用Fraction(1,2),避免把二进制浮点近似悄悄当成精确系数。
按最后一列系数的符号分三组
当前消去最后一个变量x。正系数行可以整理成x的上界,负系数行可以整理成x的下界,零系数行完全不含x,必须原封不动地保留其余系数与右侧。
负数除法会反转不等号,所以不能把所有行都按同一个方向比较。源码在配对时使用正数ap=p最后一项与aq=负q最后一项,分别对上下界原行进行正倍缩放,再相加让x系数正好抵消。
配对条件同时是必要条件与充分条件
固定剩下的坐标后,每个负系数行给出一个下界,每个正系数行给出一个上界。存在x满足全部条件,当且仅当最大的下界不超过最小的上界;这又等价于每一个下界都不超过每一个上界。
因此必须生成正组与负组的全部两两配对。随手挑一条最像瓶颈的上界并不可靠,因为上界本身还依赖未求出的其他变量,换一个剩余坐标后,限制最紧的那一行可能改变。
配对公式只做正倍相加
设正行是p·y+ap·x≤bp,负行是q·y−aq·x≤bq,其中ap与aq都为正。第一行除以ap,第二行除以aq,相加得到(p/ap+q/aq)·y≤bp/ap+bq/aq,最后变量便消失。
程序对每个剩余系数和右侧使用同一公式,没有把右侧符号单独凭感觉调整。所有计算用Fraction完成,因而零系数与相等边界是精确判定,不需要选择一个浮点容差。
只有一侧限制时,不应凭空制造矛盾
如果x只有下界而没有上界,任意固定剩余坐标都可以选一个足够大的x;只有上界时同理可以选足够小的x。因此这两种情况不会产生配对条件,但仍必须保留不含x的零系数行。
测试中的单变量条件x≥5最终回代为5。没有任何约束的三维系统返回三个零。另一个例子同时要求x≤−1与x≥0,即使正在先消去根本没有出现的y,也必须保留这两条限制并判断无解。
零变量时,只剩真常量与假常量
一条全部系数为零的行变成0≤b。b非负时恒真,可以删除;b为负时立即证明当前系统无解。这个检查在每层递归入口执行,因此无需等到所有维度都消完才发现已经出现的矛盾。
完全相同的约束行也会去重,但程序没有声称删除了所有冗余约束。比如一条限制可能被几条其他限制共同蕴含,这需要额外工作;当前去重只针对精确相等的系数元组与右侧。
回代从投影点重新求上下界交集
递归先找到剩余坐标partial。回到当前层,把这些坐标代入本层保存的原约束,对最后变量重新计算所有数值上下界。投影条件已经保证下界最大值不超过上界最小值,所以交集一定非空。
本实现有下界就选最大下界;没有下界而有上界就选最小上界;两边都没有则选零。这里没有优化目标,返回的是一份可行见证,不承诺坐标最小、离原点最近或业务成本最低。
一份二元算例怎样找回两个坐标
算例实际要求x+y≤4、x≤y、x≥3/2与y≥0。先消去y,上下界配对得到2x≤4与x≤4,再保留x≥3/2。于是x可以选择3/2,回代后的y落在[3/2,5/2],程序也选择3/2。
输出为(3/2,3/2),而不是浮点1.5的格式。最外层还把返回点代入每条原始约束作精确断言,核对消元后的结果确实能回到原系统,而不是只有投影条件表看起来合理。
二维顶点裁判不使用消元配对
测试先给系统加入−3≤x≤3与−3≤y≤3的方框,再加入随机整数半平面。独立裁判枚举每两条边界直线的交点,使用二阶行列式精确求坐标,并直接检查它是否满足全部原约束。
因为测试系统被方框限制,非空可行域必有极点;二维极点可由两条独立的紧约束确定,即使可行域退化成线段或一个点也能覆盖。这个裁判只用于这样的有界二维样本,不能拿它去判一个没有顶点的无界平面。
有理解不等于整数解
条件2x≤1与−2x≤−1精确地要求x=1/2,在本文变量域中有解。若另外要求x是整数,这个系统却无解;代码没有整数性输入,不能把返回分数简单舍入后继续宣称满足原条件。
对有理系数与非严格线性不等式,投影和回代只需有理运算,因此存在实数解时也能构造一份有理解。这个结论不自动推广到严格不等式、非线性约束或额外的离散选择。
约束膨胀需要单独的停止结果
一层投影候选数等于零组大小加正组大小乘负组大小,可能接近当前约束数的平方。连续消去几个变量,记录数就会迅速增长,Fraction的分子分母也可能变长;精确不等于便宜。
程序最多接收四维、32条初始约束,若某层预计产生超过4096条配对候选,抛RuntimeError。代码构造了一份原点显然可行的拥挤系统来触发预算停止,明确说明它不是无解证据。800个方框内的随机系统则全部与独立顶点裁判一致。
参考资料
一手资料与本地运行核查日期:2026年10月7日。正文程序、测试与例子独立编写;有限样本核对不代表生产环境性能评测。


