Python 与 SQLite 线段相交实战:用整数精确区分穿越、接触与共线重叠
两条线段是否相交,看起来只是返回一个布尔值;真正写入业务系统后,问题却常常变成:它们在内部穿过,还是只碰到端点?两段共线道路共享了一段区间,是否应当与交叉路口放在同一类?如果导入的数据把一条线段的起点和终点写成同一点,又应该如何处理?本篇从整数坐标出发,把这些语义落实成四个稳定的分类值,再把它们与 Python 标准库 sqlite3 的存储、候选过滤和结果校验连接起来。
目标不是绘制一张看起来正确的图,而是建立可以反复运行的判定链。数据库保存原始端点,Python 整数负责几何谓词,包围盒只负责排除明显不可能相交的候选。全文有且只有九段 Python 程序,每段均可单独复制为一个脚本运行,无须下载前一段生成的文件,也不依赖第三方包。为了保持这种独立性,后半部分会重复核心函数;实际项目应把它提取为单独模块并统一测试。

本文将线段视为包含两个端点的闭集合。坐标输入限定为笛卡尔平面上的整数,不把经纬度直接当作平面距离,也不处理测量误差。示例实测环境为 Python 3.12.14、SQLite 3.53.1;使用 Python 3.12 或更高版本即可复现所用接口,具体 SQLite 版本由你的 Python 构建决定。所有程序都实际使用 python -X dev -W error 执行,并检查标准错误为空。
一、先约定输入,而不是先写叉积
每条线段使用一个业务编号和四个坐标列。存储约束与计算能力必须分开理解:Python 的整数拥有任意精度,但 SQLite 的 INTEGER 运算值采用有符号八字节整数。因此,下面在入库前检查每个值处于负二的六十三次方到二的六十三次方减一之间。端点在这个范围内,不代表后面的坐标差或叉积也在范围内。
这里故意使用 type(v) is int,拒绝浮点数与布尔值;布尔值虽然是 Python 整数的子类型,却不应悄悄充当道路坐标。数据库中的 typeof 检查保证最终存储类别,但 INTEGER 亲和性可能先把某些字符串或浮点值转换为整数,所以它不能替代应用层的原始类型检查。示例通过临时磁盘文件完成关闭后重读,证明读到的并非尚未持久化的内存对象。业务数据始终通过占位符绑定;构造列定义时插入的列名只来自程序内固定列表。
import sqlite3
from contextlib import closing
def create_segments(con):
names = ('x1', 'y1', 'x2', 'y2')
columns = ', '.join(
f"{name} INTEGER NOT NULL CHECK(typeof({name}) = 'integer')"
for name in names
)
con.execute('CREATE TABLE segments (id INTEGER PRIMARY KEY, '
+ columns + ')')
from pathlib import Path
from tempfile import TemporaryDirectory
def validate(row):
if len(row) != 5 or any(type(v) is not int for v in row):
raise TypeError('id and coordinates must be plain integers')
if any(not -(1 << 63) <= v < (1 << 63) for v in row):
raise ValueError('outside SQLite INTEGER range')
return row
with TemporaryDirectory() as folder:
path = Path(folder) / 'segments.db'
with closing(sqlite3.connect(path, isolation_level=None)) as con:
create_segments(con)
row = validate((1, 0, 0, 4, 4))
con.execute('INSERT INTO segments VALUES (?, ?, ?, ?, ?)', row)
with closing(sqlite3.connect(path)) as con:
print(con.execute('SELECT * FROM segments').fetchone())
print(con.execute('SELECT typeof(x1) FROM segments').fetchone()[0])
for bad in ((2, True, 0, 1, 1), (3, 1 << 63, 0, 1, 1)):
try:
validate(bad)
except (TypeError, ValueError) as exc:
print(type(exc).__name__)运行输出:
(1, 0, 0, 4, 4) integer TypeError ValueError
二、方向与点在线段上:只做整数运算
有向面积的两倍可写成 orient(a,b,c)。结果为正时,第三个点位于从 a 指向 b 的左侧;为负时在右侧;等于零只说明三点共线。判断一个点落在线段上,还需要同时检查横纵坐标都位于两个端点构成的闭区间里。只做共线检查会把线段延长线上的点错误地包含进来,这是最容易漏掉的边界之一。
这一步不需要平方根、斜率或除法,因此也没有竖直线斜率不存在的问题。例子把两个端点放到接近数据库整数极限的位置,叉积仍由 Python 完整保存。最后一行显示,在本次运行环境中,把二的六十次方附近两个相邻整数转为 float 后会失去区别。不能先把坐标变成浮点数,再期待一个很小的 epsilon 恢复已经丢掉的信息。这里的精确性仅指给定整数模型上的精确,不意味着输入测量本身没有误差。
def orient(a, b, c): return ((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])) def on_segment(p, a, b): return (orient(a, b, p) == 0 and min(a[0], b[0]) <= p[0] <= max(a[0], b[0]) and min(a[1], b[1]) <= p[1] <= max(a[1], b[1])) n = (1 << 63) - 1 value = orient((-n, -n), (n, -n), (-n, n)) print(value > (1 << 63) - 1) print(orient((0, 0), (4, 0), (2, 1))) print(on_segment((2, 0), (0, 0), (4, 0))) print(on_segment((5, 0), (0, 0), (4, 0))) print(float(1 << 60) == float((1 << 60) + 1)) assert value == 4 * n * n
运行输出:
True 4 True False True
三、四类互斥结果,以及退化点线段
分类值的含义需要在函数之前约定清楚。disjoint 表示交集为空;proper_crossing 表示两条非退化线段在双方内部形成一个交点;touch 表示只有一个交点,并且至少涉及某条线段的端点或退化点;collinear_overlap 表示共线且共享一段正长度区间。完全重合的非退化线段也归入最后一类。两个相同的点线段则只有一个交点,因此归入 touch,不视为长度为零的重叠。
处理顺序决定了边界是否可靠。首先显式处理起点等于终点的情况;之后检查四个方向值是否全部为零。如果共线,就选取第一条非退化线段会变化的那个坐标轴,求两个投影区间的交集:下界大于上界为空,相等为单点,小于上界为正长度重叠。由于已经排除了退化线段,竖直线会安全地选择纵轴。接下来才判断双方是否严格跨越对方所在直线,最后检查端点接触。
四个方向值的乘积在这里仍然是 Python 整数运算,不会受固定六十四位溢出限制。也可以改成符号比较以减少大整数乘法,但不能把严格小于零改成小于等于零,否则端点接触会被误报为内部交叉。下面的命名用例覆盖反向端点、竖直重叠、共线相离、点在线段内部、相同点和不同点;交换两段或同时反转端点,不应该改变分类。
def orient(a, b, c):
return ((b[0] - a[0]) * (c[1] - a[1])
- (b[1] - a[1]) * (c[0] - a[0]))
def on_segment(p, a, b):
return (orient(a, b, p) == 0
and min(a[0], b[0]) <= p[0] <= max(a[0], b[0])
and min(a[1], b[1]) <= p[1] <= max(a[1], b[1]))
def classify(a, b, c, d):
# Contract: every coordinate is a Python int, not a float.
if a == b:
return 'touch' if on_segment(a, c, d) else 'disjoint'
if c == d:
return 'touch' if on_segment(c, a, b) else 'disjoint'
o1, o2 = orient(a, b, c), orient(a, b, d)
o3, o4 = orient(c, d, a), orient(c, d, b)
if o1 == o2 == o3 == o4 == 0:
axis = 0 if a[0] != b[0] else 1
lo = max(min(a[axis], b[axis]), min(c[axis], d[axis]))
hi = min(max(a[axis], b[axis]), max(c[axis], d[axis]))
if lo > hi:
return 'disjoint'
return 'touch' if lo == hi else 'collinear_overlap'
if o1 * o2 < 0 and o3 * o4 < 0:
return 'proper_crossing'
if (on_segment(c, a, b) or on_segment(d, a, b)
or on_segment(a, c, d) or on_segment(b, c, d)):
return 'touch'
return 'disjoint'
cases = [
('proper_crossing', (0, 0), (4, 4), (0, 4), (4, 0)),
('touch', (0, 0), (4, 0), (2, 0), (2, 3)),
('touch', (0, 0), (2, 0), (2, 0), (4, 0)),
('collinear_overlap', (0, 0), (4, 0), (3, 0), (1, 0)),
('collinear_overlap', (0, 0), (0, 4), (0, 3), (0, 1)),
('disjoint', (0, 0), (1, 0), (2, 0), (3, 0)),
('touch', (1, 1), (1, 1), (0, 0), (2, 2)),
('touch', (1, 1), (1, 1), (1, 1), (1, 1)),
('disjoint', (1, 1), (1, 1), (2, 2), (2, 2)),
]
for expected, a, b, c, d in cases:
result = classify(a, b, c, d)
assert result == expected
assert classify(b, a, d, c) == result
assert classify(c, d, a, b) == result
print('named cases:', len(cases))
print('kinds:', ', '.join(sorted({row[0] for row in cases})))运行输出:
named cases: 9 kinds: collinear_overlap, disjoint, proper_crossing, touch
四、分类与交点坐标是两件事
完成分类并不要求求出交点。若下游还需要坐标,可对非平行的两条支撑直线求参数 t 与 u,并检验它们都位于零到一之间。整数端点的交点可能是分数,例如下面得到五分之六,也就是一又五分之一。不要为了把交点塞回 INTEGER 列而四舍五入,这会改变几何对象。
Fraction 支持由整数分子和分母构造有理数,适合这里的精确求交。这个小函数刻意拒绝平行与退化输入,因为它们需要前一节的分类语义:重叠时交集是线段,不是唯一坐标;两个相同的点虽然有唯一交点,却不能用非零行列式公式计算。若要持久化分数,应设计分子分母或规范字符串字段,并另行评估它们的大小,而不是沿用端点的六十四位整数假设。
from fractions import Fraction
def unique_intersection(a, b, c, d):
# Only nonparallel lines; return a point only if both closed segments contain it.
r = (b[0] - a[0], b[1] - a[1])
s = (d[0] - c[0], d[1] - c[1])
q = (c[0] - a[0], c[1] - a[1])
cross = lambda u, v: u[0] * v[1] - u[1] * v[0]
det = cross(r, s)
if det == 0:
raise ValueError('parallel or degenerate: classify separately')
t = Fraction(cross(q, s), det)
u = Fraction(cross(q, r), det)
if not (0 <= t <= 1 and 0 <= u <= 1):
return None
return tuple(Fraction(a[k]) + t * r[k] for k in (0, 1))
point = unique_intersection((0, 0), (3, 3), (0, 2), (3, 0))
assert point == (Fraction(6, 5), Fraction(6, 5))
print(tuple(str(v) for v in point))
print(unique_intersection((0, 0), (1, 0), (2, -1), (2, 1)))运行输出:
('6/5', '6/5')
None五、让 SQLite 过滤包围盒,让 Python 做最终判断
若两条闭线段存在交点,它们在横轴上的投影区间必然相交,纵轴也一样。反过来则不成立:两个矩形重叠,矩形内部的线段仍然可能错开。所以下面的 SQL 使用四个包含等号的比较筛选候选,再对候选调用精确分类器。这里等号不能省略,否则仅仅在边界接触的线段以及零宽、零高的点包围盒会被提前丢掉。
查询以编号一为目标,编号四会进入候选列表,却最终得到 disjoint;这是预期的假阳性,不是程序出错。编号六的包围盒完全远离目标,因此无需进入几何判断。SQL 中只比较原始整数以及 min、max 的结果,不在数据库里做差乘叉积。演示数据均为程序内的整数常量;真实导入通道仍要经过第一节的验证。筛选条件能够减少传给 Python 的数量,但本例没有建立空间索引,也没有承诺避免数据库扫描。
import sqlite3
from contextlib import closing
def create_segments(con):
names = ('x1', 'y1', 'x2', 'y2')
columns = ', '.join(
f"{name} INTEGER NOT NULL CHECK(typeof({name}) = 'integer')"
for name in names
)
con.execute('CREATE TABLE segments (id INTEGER PRIMARY KEY, '
+ columns + ')')
def orient(a, b, c):
return ((b[0] - a[0]) * (c[1] - a[1])
- (b[1] - a[1]) * (c[0] - a[0]))
def on_segment(p, a, b):
return (orient(a, b, p) == 0
and min(a[0], b[0]) <= p[0] <= max(a[0], b[0])
and min(a[1], b[1]) <= p[1] <= max(a[1], b[1]))
def classify(a, b, c, d):
# Contract: every coordinate is a Python int, not a float.
if a == b:
return 'touch' if on_segment(a, c, d) else 'disjoint'
if c == d:
return 'touch' if on_segment(c, a, b) else 'disjoint'
o1, o2 = orient(a, b, c), orient(a, b, d)
o3, o4 = orient(c, d, a), orient(c, d, b)
if o1 == o2 == o3 == o4 == 0:
axis = 0 if a[0] != b[0] else 1
lo = max(min(a[axis], b[axis]), min(c[axis], d[axis]))
hi = min(max(a[axis], b[axis]), max(c[axis], d[axis]))
if lo > hi:
return 'disjoint'
return 'touch' if lo == hi else 'collinear_overlap'
if o1 * o2 < 0 and o3 * o4 < 0:
return 'proper_crossing'
if (on_segment(c, a, b) or on_segment(d, a, b)
or on_segment(a, c, d) or on_segment(b, c, d)):
return 'touch'
return 'disjoint'
rows = [(1, 0, 0, 4, 4), (2, 0, 4, 4, 0),
(3, 4, 4, 7, 7), (4, 1, 2, 2, 3),
(5, 1, 1, 1, 1), (6, 20, 20, 21, 21)]
with closing(sqlite3.connect(':memory:', isolation_level=None)) as con:
create_segments(con)
con.executemany('INSERT INTO segments VALUES (?, ?, ?, ?, ?)', rows)
target_id, x1, y1, x2, y2 = rows[0]
candidates = con.execute("""
SELECT id, x1, y1, x2, y2 FROM segments
WHERE id != ? AND min(x1, x2) <= ? AND max(x1, x2) >= ?
AND min(y1, y2) <= ? AND max(y1, y2) >= ?
ORDER BY id
""", (target_id, max(x1, x2), min(x1, x2),
max(y1, y2), min(y1, y2))).fetchall()
for sid, cx, cy, dx, dy in candidates:
print(sid, classify((x1, y1), (x2, y2), (cx, cy), (dx, dy)))运行输出:
2 proper_crossing 3 touch 4 disjoint 5 touch
六、规范化线段对,并原子保存分类结果
一对线段的关系没有方向,结果表采用较小编号在前、较大编号在后的联合主键,避免同时保存一二与二一两条重复记录。下面的数据按编号递增排列,所以 combinations 直接产生规范顺序;如果业务输入没有排序,必须先排序或显式规范化两个编号。外键约束限制引用对象存在,分类值检查限制可写入的状态,编号大小检查拒绝自关联与反向编号。
所有计算完成后,再用一笔事务插入整批关系。程序随后故意执行一次失败的更新:先删除全部关系,再插入一条反向编号的记录;约束失败后回滚,六条旧记录依然存在。这个实验验证的是原子性,不是仅仅打印一次 commit。示例以 isolation_level=None 关闭隐式事务开启,显式发出 BEGIN,再明确提交或回滚;连接由 closing 关闭。官方文档说明连接的事务上下文管理器不会自动关闭连接,不能把资源生命周期与事务生命周期混为一谈。
此处保存全部六个线段对,包含不相交结果,便于审计。实际项目可以只保存非空交集,但需明确“没有记录”究竟表示尚未计算还是已经确认不相交。源线段发生修改后,已有关系可能失效;生产设计应记录计算版本,或者在同一更新流程中删除并重算受影响的关系。外键本身不能保证几何结果仍然新鲜。
import sqlite3
from contextlib import closing
def create_segments(con):
names = ('x1', 'y1', 'x2', 'y2')
columns = ', '.join(
f"{name} INTEGER NOT NULL CHECK(typeof({name}) = 'integer')"
for name in names
)
con.execute('CREATE TABLE segments (id INTEGER PRIMARY KEY, '
+ columns + ')')
def orient(a, b, c):
return ((b[0] - a[0]) * (c[1] - a[1])
- (b[1] - a[1]) * (c[0] - a[0]))
def on_segment(p, a, b):
return (orient(a, b, p) == 0
and min(a[0], b[0]) <= p[0] <= max(a[0], b[0])
and min(a[1], b[1]) <= p[1] <= max(a[1], b[1]))
def classify(a, b, c, d):
# Contract: every coordinate is a Python int, not a float.
if a == b:
return 'touch' if on_segment(a, c, d) else 'disjoint'
if c == d:
return 'touch' if on_segment(c, a, b) else 'disjoint'
o1, o2 = orient(a, b, c), orient(a, b, d)
o3, o4 = orient(c, d, a), orient(c, d, b)
if o1 == o2 == o3 == o4 == 0:
axis = 0 if a[0] != b[0] else 1
lo = max(min(a[axis], b[axis]), min(c[axis], d[axis]))
hi = min(max(a[axis], b[axis]), max(c[axis], d[axis]))
if lo > hi:
return 'disjoint'
return 'touch' if lo == hi else 'collinear_overlap'
if o1 * o2 < 0 and o3 * o4 < 0:
return 'proper_crossing'
if (on_segment(c, a, b) or on_segment(d, a, b)
or on_segment(a, c, d) or on_segment(b, c, d)):
return 'touch'
return 'disjoint'
from itertools import combinations
rows = [(1, 0, 0, 4, 4), (2, 0, 4, 4, 0),
(3, 1, 1, 1, 1), (4, 1, 1, 3, 3)]
with closing(sqlite3.connect(':memory:', isolation_level=None)) as con:
con.execute('PRAGMA foreign_keys = ON')
create_segments(con)
con.executemany('INSERT INTO segments VALUES (?, ?, ?, ?, ?)', rows)
con.execute("""CREATE TABLE relations (
a_id INTEGER NOT NULL REFERENCES segments(id),
b_id INTEGER NOT NULL REFERENCES segments(id),
kind TEXT NOT NULL CHECK(kind IN
('disjoint', 'proper_crossing', 'touch', 'collinear_overlap')),
PRIMARY KEY(a_id, b_id), CHECK(a_id < b_id))""")
records = []
for left, right in combinations(rows, 2):
aid, ax, ay, bx, by = left
bid, cx, cy, dx, dy = right
records.append((aid, bid, classify((ax, ay), (bx, by),
(cx, cy), (dx, dy))))
con.execute('BEGIN')
try:
con.executemany('INSERT INTO relations VALUES (?, ?, ?)', records)
con.commit()
except Exception:
con.rollback()
raise
before = con.execute('SELECT count(*) FROM relations').fetchone()[0]
con.execute('BEGIN')
try:
con.execute('DELETE FROM relations')
con.execute('INSERT INTO relations VALUES (4, 1, ?)', ('touch',))
con.commit()
except sqlite3.IntegrityError:
con.rollback()
after = con.execute('SELECT count(*) FROM relations').fetchone()[0]
assert before == after == 6
print('rows before/after rollback:', before, after)
for row in con.execute('SELECT * FROM relations ORDER BY a_id, b_id'):
print(row)运行输出:
rows before/after rollback: 6 6 (1, 2, 'proper_crossing') (1, 3, 'touch') (1, 4, 'collinear_overlap') (2, 3, 'disjoint') (2, 4, 'proper_crossing') (3, 4, 'touch')
七、需要 SQL 接口时,把分类器注册成函数
有时调用方只能执行 SQL,也可以把同一个分类器注册为用户定义函数。通过 create_function 传入的整数参数会在 Python 回调中参加运算,返回值是四种短字符串之一。这里把函数标记为 deterministic,表示相同参数必定得到相同结果;这个标记不是缓存承诺,更不代表查询只调用一次。连接关闭后注册也随之结束,新连接必须重新注册。
示例选取接近六十四位边界的两条对角线,仍能得到 proper_crossing。随后直接让 SQL 计算两个大整数的乘积,返回的类型却是 real。SQLite 表达式文档说明整数算术溢出时可能改用浮点运算,因此不要把 Python 版的叉积表达式原样搬进 SQL,再宣称保持了同样的精确性。回调只返回分类文本,也避免把巨大中间整数重新送回 SQLite INTEGER。
这个写法主要改善调用接口,不能改变全配对数量的二次增长。大量数据仍应先用可靠的候选机制缩小范围,并测量 Python 回调开销。外部输入须在入库时拒绝非整数;回调再次检查类型是防御措施,不建议依赖回调抛异常来提供友好的逐行数据清洗报告。
import sqlite3
from contextlib import closing
def create_segments(con):
names = ('x1', 'y1', 'x2', 'y2')
columns = ', '.join(
f"{name} INTEGER NOT NULL CHECK(typeof({name}) = 'integer')"
for name in names
)
con.execute('CREATE TABLE segments (id INTEGER PRIMARY KEY, '
+ columns + ')')
def orient(a, b, c):
return ((b[0] - a[0]) * (c[1] - a[1])
- (b[1] - a[1]) * (c[0] - a[0]))
def on_segment(p, a, b):
return (orient(a, b, p) == 0
and min(a[0], b[0]) <= p[0] <= max(a[0], b[0])
and min(a[1], b[1]) <= p[1] <= max(a[1], b[1]))
def classify(a, b, c, d):
# Contract: every coordinate is a Python int, not a float.
if a == b:
return 'touch' if on_segment(a, c, d) else 'disjoint'
if c == d:
return 'touch' if on_segment(c, a, b) else 'disjoint'
o1, o2 = orient(a, b, c), orient(a, b, d)
o3, o4 = orient(c, d, a), orient(c, d, b)
if o1 == o2 == o3 == o4 == 0:
axis = 0 if a[0] != b[0] else 1
lo = max(min(a[axis], b[axis]), min(c[axis], d[axis]))
hi = min(max(a[axis], b[axis]), max(c[axis], d[axis]))
if lo > hi:
return 'disjoint'
return 'touch' if lo == hi else 'collinear_overlap'
if o1 * o2 < 0 and o3 * o4 < 0:
return 'proper_crossing'
if (on_segment(c, a, b) or on_segment(d, a, b)
or on_segment(a, c, d) or on_segment(b, c, d)):
return 'touch'
return 'disjoint'
def sql_classify(ax, ay, bx, by, cx, cy, dx, dy):
values = (ax, ay, bx, by, cx, cy, dx, dy)
if any(type(v) is not int for v in values):
raise TypeError('integer coordinates required')
return classify((ax, ay), (bx, by), (cx, cy), (dx, dy))
n = (1 << 63) - 1
rows = [(1, -n, -n, n, n), (2, -n, n, n, -n)]
with closing(sqlite3.connect(':memory:', isolation_level=None)) as con:
create_segments(con)
con.executemany('INSERT INTO segments VALUES (?, ?, ?, ?, ?)', rows)
con.create_function('segment_kind', 8, sql_classify, deterministic=True)
result = con.execute("""
SELECT segment_kind(a.x1, a.y1, a.x2, a.y2,
b.x1, b.y1, b.x2, b.y2)
FROM segments AS a JOIN segments AS b ON a.id < b.id
""").fetchone()[0]
assert result == 'proper_crossing'
print(result)
print(con.execute('SELECT typeof(? * ?)', (n, n)).fetchone()[0])运行输出:
proper_crossing real
八、用参数方程参考实现交叉验证
仅用同一个函数计算预期值,再让它验证自己,并不能证明几何分支正确。下面增加一个实现路径不同的参考分类器:非平行情况使用 Fraction 求参数并检查开闭区间;平行情况寻找同时属于两段的不同端点。对于两个非退化共线闭区间,若它们有正长度公共部分,公共部分的两端必然来自输入端点,所以不同公共端点的数量能够区分单点接触和正长度重叠。点是否落在线段上也用参数方程检查,避免直接复用方向谓词。
先穷举三乘三整数网格上的四个有序端点,共六千五百六十一组,自动包含相同端点、相同线段、反向线段以及各种退化组合。再生成三千组固定随机种子的样本,交替使用小坐标和接近六十四位范围的大坐标,并主动制造点线段。每组还验证反转第一条线段、交换两条线段以及整体大幅平移后的分类不变。平移后的坐标可超出数据库范围,这一步专门验证纯 Python 算法,并不会把它们重新入库。
这些检查不是对无限输入空间的形式化证明,但比只画几张图更容易揭示遗漏的边界。参考实现仍与主实现共享基础代数事实,不应被描述为完全独立的数学证明。固定种子用于本次重现,生产测试可增加更多种子、纵横线密集数据和真实业务中容易出现的重复端点分布。
def orient(a, b, c):
return ((b[0] - a[0]) * (c[1] - a[1])
- (b[1] - a[1]) * (c[0] - a[0]))
def on_segment(p, a, b):
return (orient(a, b, p) == 0
and min(a[0], b[0]) <= p[0] <= max(a[0], b[0])
and min(a[1], b[1]) <= p[1] <= max(a[1], b[1]))
def classify(a, b, c, d):
# Contract: every coordinate is a Python int, not a float.
if a == b:
return 'touch' if on_segment(a, c, d) else 'disjoint'
if c == d:
return 'touch' if on_segment(c, a, b) else 'disjoint'
o1, o2 = orient(a, b, c), orient(a, b, d)
o3, o4 = orient(c, d, a), orient(c, d, b)
if o1 == o2 == o3 == o4 == 0:
axis = 0 if a[0] != b[0] else 1
lo = max(min(a[axis], b[axis]), min(c[axis], d[axis]))
hi = min(max(a[axis], b[axis]), max(c[axis], d[axis]))
if lo > hi:
return 'disjoint'
return 'touch' if lo == hi else 'collinear_overlap'
if o1 * o2 < 0 and o3 * o4 < 0:
return 'proper_crossing'
if (on_segment(c, a, b) or on_segment(d, a, b)
or on_segment(a, c, d) or on_segment(b, c, d)):
return 'touch'
return 'disjoint'
from fractions import Fraction
def reference(a, b, c, d):
# Independent parameter-equation oracle; no orientation predicate.
def sub(p, q):
return p[0] - q[0], p[1] - q[1]
def cross(u, v):
return u[0] * v[1] - u[1] * v[0]
def contains(p, u, v):
if u == v:
return p == u
axis = 0 if u[0] != v[0] else 1
t = Fraction(p[axis] - u[axis], v[axis] - u[axis])
return (0 <= t <= 1
and all(u[k] + t * (v[k] - u[k]) == p[k]
for k in (0, 1)))
if a == b:
return 'touch' if contains(a, c, d) else 'disjoint'
if c == d:
return 'touch' if contains(c, a, b) else 'disjoint'
r, s, q = sub(b, a), sub(d, c), sub(c, a)
det = cross(r, s)
if det:
t, u = Fraction(cross(q, s), det), Fraction(cross(q, r), det)
if not (0 <= t <= 1 and 0 <= u <= 1):
return 'disjoint'
return 'proper_crossing' if 0 < t < 1 and 0 < u < 1 else 'touch'
# Parallel: two distinct shared endpoints imply a nonzero overlap.
shared = {p for p in (a, b, c, d)
if contains(p, a, b) and contains(p, c, d)}
if not shared:
return 'disjoint'
return 'touch' if len(shared) == 1 else 'collinear_overlap'
from itertools import product
from random import Random
points = list(product(range(-1, 2), repeat=2))
counts = {'disjoint': 0, 'proper_crossing': 0,
'touch': 0, 'collinear_overlap': 0}
for a, b, c, d in product(points, repeat=4):
actual = classify(a, b, c, d)
assert actual == reference(a, b, c, d), (a, b, c, d)
counts[actual] += 1
assert all(counts.values())
print('exhaustive:', sum(counts.values()))
print('all four kinds:', all(counts.values()))
rng = Random(20261019)
for i in range(3000):
bound = 10 if i % 2 else (1 << 63) - 1
a, b, c, d = [tuple(rng.randint(-bound, bound) for _ in (0, 1))
for _ in range(4)]
if i % 5 == 0:
b = a
if i % 7 == 0:
d = c
actual = classify(a, b, c, d)
assert actual == reference(a, b, c, d)
assert actual == classify(b, a, c, d) == classify(c, d, a, b)
shifted = [tuple(v + 10**30 for v in p) for p in (a, b, c, d)]
assert actual == classify(*shifted)
print('random + reversal + swap + translation:', 3000)运行输出:
exhaustive: 6561 all four kinds: True random + reversal + swap + translation: 3000
九、最后验证候选筛选没有漏掉真交集
算法正确还不够,数据库筛选若写错一个比较方向,真正相交的线段可能根本到不了分类器。最后一段建立一百条线段,其中九十六条来自固定种子的随机输入,两条跨越大范围,另外两条退化成点。程序枚举全部四千九百五十个不同编号对,得到暴力真值集合,再比较 SQL 包围盒候选经过精确分类后得到的集合;比较内容包括编号对和分类值,不只是总数。
完整性断言通过,说明这批数据里候选过滤没有假阴性;随后确认候选中确实存在假阳性,避免把测试集误解为包围盒本身就能完成求交。这个验证方法可直接保留在回归测试里:以后增加索引、改写候选查询或替换存储布局时,只要数据量保持较小,就可以持续与暴力基线比较。它检查的是整个处理链,而非孤立的几何函数。
若有 n 条线段,全配对仍有 n 乘以 n 减一再除以二个组合;当前示例是正确性基线,不是百万级数据的性能方案。进入更大规模后,可考虑空间索引或扫描线算法,但要重新论证候选边界、坐标范围以及退化处理,尤其不能因性能优化悄悄把精确整数变成有限精度浮点。先固定语义和基线,再优化查询路径,问题会容易定位得多。
import sqlite3
from contextlib import closing
def create_segments(con):
names = ('x1', 'y1', 'x2', 'y2')
columns = ', '.join(
f"{name} INTEGER NOT NULL CHECK(typeof({name}) = 'integer')"
for name in names
)
con.execute('CREATE TABLE segments (id INTEGER PRIMARY KEY, '
+ columns + ')')
def orient(a, b, c):
return ((b[0] - a[0]) * (c[1] - a[1])
- (b[1] - a[1]) * (c[0] - a[0]))
def on_segment(p, a, b):
return (orient(a, b, p) == 0
and min(a[0], b[0]) <= p[0] <= max(a[0], b[0])
and min(a[1], b[1]) <= p[1] <= max(a[1], b[1]))
def classify(a, b, c, d):
# Contract: every coordinate is a Python int, not a float.
if a == b:
return 'touch' if on_segment(a, c, d) else 'disjoint'
if c == d:
return 'touch' if on_segment(c, a, b) else 'disjoint'
o1, o2 = orient(a, b, c), orient(a, b, d)
o3, o4 = orient(c, d, a), orient(c, d, b)
if o1 == o2 == o3 == o4 == 0:
axis = 0 if a[0] != b[0] else 1
lo = max(min(a[axis], b[axis]), min(c[axis], d[axis]))
hi = min(max(a[axis], b[axis]), max(c[axis], d[axis]))
if lo > hi:
return 'disjoint'
return 'touch' if lo == hi else 'collinear_overlap'
if o1 * o2 < 0 and o3 * o4 < 0:
return 'proper_crossing'
if (on_segment(c, a, b) or on_segment(d, a, b)
or on_segment(a, c, d) or on_segment(b, c, d)):
return 'touch'
return 'disjoint'
from itertools import combinations
from random import Random
rng = Random(92)
rows = [(sid, *(rng.randint(-50, 50) for _ in range(4)))
for sid in range(1, 97)]
n = (1 << 63) - 1
rows += [(97, -n, -n, n, n), (98, -n, n, n, -n),
(99, 0, 0, 0, 0), (100, 1, 1, 1, 1)]
with closing(sqlite3.connect(':memory:', isolation_level=None)) as con:
create_segments(con)
con.executemany('INSERT INTO segments VALUES (?, ?, ?, ?, ?)', rows)
pair_ids = set(con.execute("""
SELECT a.id, b.id FROM segments AS a
JOIN segments AS b ON a.id < b.id
WHERE min(a.x1, a.x2) <= max(b.x1, b.x2)
AND min(b.x1, b.x2) <= max(a.x1, a.x2)
AND min(a.y1, a.y2) <= max(b.y1, b.y2)
AND min(b.y1, b.y2) <= max(a.y1, a.y2)
"""))
truth, narrowed = {}, {}
for left, right in combinations(rows, 2):
aid, ax, ay, bx, by = left
bid, cx, cy, dx, dy = right
kind = classify((ax, ay), (bx, by), (cx, cy), (dx, dy))
if kind != 'disjoint':
truth[(aid, bid)] = kind
if (aid, bid) in pair_ids and kind != 'disjoint':
narrowed[(aid, bid)] = kind
assert narrowed == truth
print('segments:', len(rows))
print('all pairs:', len(rows) * (len(rows) - 1) // 2)
print('candidate completeness:', narrowed == truth)
print('false positives exist:', bool(pair_ids - truth.keys()))运行输出:
segments: 100 all pairs: 4950 candidate completeness: True false positives exist: True
收束:把精确性放在明确的边界内
这条流程的关键是职责清楚:导入层保证整数及存储范围,SQLite 保存数据并提供无假阴性的候选条件,Python 整数决定拓扑分类,Fraction 只在需要唯一交点或参考验证时参与。端点接触、共线正长度重叠、内部交叉与退化点各有独立含义,不让一个模糊的布尔值掩盖业务差异。
九个脚本的标准输出均由实际执行取得,参考测试、事务回滚测试和数据库候选完整性检查均已通过。本文实现与样例为原创;链接的官方资料用于核实整数类型、数据库绑定、事务资源管理和有理数接口,不把这些接口文档当作本文几何算法的现成实现。

