Python 与 SQLite 精确离散概率卷积:从 Fraction 到事务存储

10-19 5阅读

把几个小任务的耗时分布加起来,看上去只需要两层循环;真正容易出错的地方,却是重复结果、非法概率、独立性假设,以及保存时悄悄发生的精度损失。本文用 Python 标准库 Fraction 与 sqlite3,建立一条从输入验证、精确卷积、独立测试到事务持久化的完整路线。所有任务时长都是教学用玩具模型,不代表任何真实系统的测量结果。

运行环境要求 Python 3.12 或更新版本,使用自带 sqlite3,无第三方运行依赖。每个示例都包含自己的导入和函数定义,不依赖前一段执行留下的变量。精确指的是对给定有理数模型的算术精确,并不意味着假设或输入概率已经得到现实验证。

Python 与 SQLite 精确离散概率卷积:从 Fraction 到事务存储
AI 生成概念配图:离散分布经过合并后进入精确存储。柱形仅作视觉示意,不对应正文的具体概率值。

一、先定义输入契约,再谈概率计算

假设一个玩具任务的执行时间只有一秒、两秒和四秒三种可能,记录里允许同一时长出现多次。我们要回答的不是某次执行究竟用了多久,而是若干次独立执行的总时长分布。有限离散分布可以表示为字典,键是整数结果,值是精确概率。字典便于卷积累加,但原始输入必须先用二元组序列接收,否则重复键会在进入函数前被覆盖,丢失的质量再也无法恢复。

这里刻意区分两种语义。默认模式接收已经归一化的概率,要求总和严格等于一;只有明确传入 normalize=True,才把非负权重除以总权重。这样,调用方把四分之一误写成二分之一时,程序不会悄悄改成另一份看似合理的分布。空输入、全零权重、负权重都要报错,而且负数必须在聚合之前检查,不能让正负条目互相抵消。

权重只接受整数、字符串或 Fraction,拒绝浮点数和布尔值。字符串 0.1 表示精确的十分之一,而先构造二进制浮点数再交给 Fraction,并不会自动恢复十进制输入者的意图。分数在内部约分,分母保持正数;这些行为可以在 Python 的 Fraction 文档中核对。数学核心允许任意整数结果;本文的任务时长样本只使用非负整数,真实业务还应在入口增加非负时长约束。

from fractions import Fraction


def pmf(rows, *, normalize=False):
    if type(normalize) is not bool:
        raise TypeError("normalize must be bool")
    result = {}
    for outcome, weight in rows:
        if type(outcome) is not int:
            raise TypeError("outcome must be int, not bool")
        if type(weight) not in (int, str, Fraction):
            raise TypeError("weight must be int, str or Fraction")
        probability = Fraction(weight)
        if probability < 0:
            raise ValueError("negative weight")
        result[outcome] = result.get(outcome, Fraction(0)) + probability
    total = sum(result.values(), Fraction(0))
    if total <= 0:
        raise ValueError("empty or zero-mass distribution")
    if not normalize and total != 1:
        raise ValueError("probabilities must sum exactly to one")
    return {x: p / total for x, p in result.items() if p}


def display(distribution):
    return [(x, str(p)) for x, p in sorted(distribution.items())]

rows = [(1, "1/4"), (1, "1/4"), (2, "1/3"), (4, "1/6"), (8, 0)]
print(display(pmf(rows)))
print(display(pmf([(1, 2), (2, 1)], normalize=True)))
rejected = 0
for bad in ([], [(1, 0)], [(1, "1/2")],
            [(1, "-1/4"), (1, "5/4")], [(True, 1)], [(1, 0.5)]):
    try:
        pmf(bad)
    except (TypeError, ValueError):
        rejected += 1
assert rejected == 6
print("rejected:", rejected)

运行输出:

[(1, '1/2'), (2, '1/3'), (4, '1/6')]
[(1, '2/3'), (2, '1/3')]
rejected: 6

第一行中的一秒结果最终拥有二分之一概率,八秒的零质量条目被清除。请注意,规范化不是修复任意坏数据的万能开关:负权重在两种模式下都非法,零总量也永远无法成为概率分布。输入契约固定以后,后续函数就可以围绕同一组不变量展开。

二、两份分布怎样做精确卷积

现在把两段先后完成的玩具任务接起来。第一段耗时为 x,第二段耗时为 y,总时长就是 x+y。若两段独立,联合概率等于两份边缘概率的乘积;所有得到相同总时长的组合,再把这些乘积加起来。这个双层循环就是离散卷积,代码没有抽样误差,也不需要设置任何浮点容差。

独立性是模型假设,不是代码检验出来的事实。如果两段任务共享一个会影响速度的隐藏状态,直接相乘通常不成立,需要先给出联合分布或按状态进行条件计算。另一个常见误区是把同一字典的键和值分别排序:它会破坏配对关系。这里始终遍历 items,且最后按数值键排序只为稳定展示,不参与概率运算。

from fractions import Fraction


def pmf(rows, *, normalize=False):
    if type(normalize) is not bool:
        raise TypeError("normalize must be bool")
    result = {}
    for outcome, weight in rows:
        if type(outcome) is not int:
            raise TypeError("outcome must be int, not bool")
        if type(weight) not in (int, str, Fraction):
            raise TypeError("weight must be int, str or Fraction")
        probability = Fraction(weight)
        if probability < 0:
            raise ValueError("negative weight")
        result[outcome] = result.get(outcome, Fraction(0)) + probability
    total = sum(result.values(), Fraction(0))
    if total <= 0:
        raise ValueError("empty or zero-mass distribution")
    if not normalize and total != 1:
        raise ValueError("probabilities must sum exactly to one")
    return {x: p / total for x, p in result.items() if p}


def convolve(left, right):
    left = pmf(left.items())
    right = pmf(right.items())
    result = {}
    for x, px in left.items():
        for y, py in right.items():
            key = x + y
            result[key] = result.get(key, Fraction(0)) + px * py
    return pmf(result.items())


def display(distribution):
    return [(x, str(p)) for x, p in sorted(distribution.items())]

a = pmf([(1, "1/2"), (2, "1/2")])
b = pmf([(1, "1/3"), (3, "2/3")])
result = convolve(a, b)
assert result == {2: Fraction(1, 6), 3: Fraction(1, 6),
                  4: Fraction(1, 3), 5: Fraction(1, 3)}
assert sum(result.values(), Fraction(0)) == 1
print(display(result))

运行输出:

[(2, '1/6'), (3, '1/6'), (4, '1/3'), (5, '1/3')]

从循环可以直接看出质量守恒:把所有输出概率相加,等于左侧概率总和乘右侧概率总和,结果仍然是一。实现仍在返回前调用验证函数,因为检查不变量比依赖读者记住推导更稳妥。对于支持集大小分别为 m 和 k 的输入,朴素算法要做 m×k 次分数乘加;这里的次数不等同于机器运算耗时,因为分子、分母位数也会增长。

三、重复组合与零次执行的单位分布

同一种任务独立执行三次,可以从单位分布开始,连续卷积三次。零次执行并非空分布,而是总时长为零、概率为一。这个约定和空和为零一致,也让循环无需额外处理第一次迭代。空分布表示没有合法概率模型,不能拿来代替零次执行的确定结果。

重复次数必须是非负整数,布尔值虽然在 Python 的类型体系中与整数有关系,这里仍然明确拒绝。函数还会先验证基础分布,所以零次执行不会成为绕过非法输入的特殊通道。为了让每一段都能单独复制运行,下文保留必要函数定义;生产代码应抽成模块,并让测试导入同一份正式实现。

from fractions import Fraction


def pmf(rows, *, normalize=False):
    if type(normalize) is not bool:
        raise TypeError("normalize must be bool")
    result = {}
    for outcome, weight in rows:
        if type(outcome) is not int:
            raise TypeError("outcome must be int, not bool")
        if type(weight) not in (int, str, Fraction):
            raise TypeError("weight must be int, str or Fraction")
        probability = Fraction(weight)
        if probability < 0:
            raise ValueError("negative weight")
        result[outcome] = result.get(outcome, Fraction(0)) + probability
    total = sum(result.values(), Fraction(0))
    if total <= 0:
        raise ValueError("empty or zero-mass distribution")
    if not normalize and total != 1:
        raise ValueError("probabilities must sum exactly to one")
    return {x: p / total for x, p in result.items() if p}


def convolve(left, right):
    left = pmf(left.items())
    right = pmf(right.items())
    result = {}
    for x, px in left.items():
        for y, py in right.items():
            key = x + y
            result[key] = result.get(key, Fraction(0)) + px * py
    return pmf(result.items())


def repeated(base, count):
    if type(count) is not int or count < 0:
        raise ValueError("count must be a nonnegative int")
    base = pmf(base.items())
    result = {0: Fraction(1)}
    for _ in range(count):
        result = convolve(result, base)
    return result


def display(distribution):
    return [(x, str(p)) for x, p in sorted(distribution.items())]

base = pmf([(1, "1/2"), (2, "1/2")])
assert repeated(base, 0) == {0: Fraction(1)}
assert repeated(base, 1) == base
print("zero:", display(repeated(base, 0)))
print("three:", display(repeated(base, 3)))
for count in (-1, True, 1.5):
    try:
        repeated(base, count)
    except ValueError:
        pass
    else:
        raise AssertionError("bad count accepted")

运行输出:

zero: [(0, '1')]
three: [(3, '1/8'), (4, '3/8'), (5, '3/8'), (6, '1/8')]

当每次只可能花一秒或两秒时,三次执行得到三秒到六秒四个结果,中间结果更常见,因为到达它们的有序路径更多。重复卷积会在每一步合并相同总时长,因此通常比完整枚举所有路径更省空间,但稀疏整数结果的支持集仍可能急剧膨胀,不能把有限输入误当成小输入。

四、用不调用卷积的穷举程序做对照

单靠几个期望输出,很容易让重复相同错误的实现互相证明。这里另写一个小规模对照器:直接枚举原始条目的有序笛卡尔积,逐路径求总时长与概率乘积,再聚合终点。它不调用 convolve 或 repeated,也不复用规范化函数来处理输入,而是只接收测试中明确构造的合法 Fraction 条目,从而降低共同缺陷带来的盲区。

为什么必须保留顺序?一次快、一次慢与一次慢、一次快是不同的执行路径,虽然总时长一样,概率都要累计。不能直接用无序组合函数替代笛卡尔积,否则需要额外计算多重排列数。itertools.product 的官方说明明确给出了重复笛卡尔积的语义。零次枚举会产生一个空元组,正好对应单位分布。

from fractions import Fraction


def pmf(rows, *, normalize=False):
    if type(normalize) is not bool:
        raise TypeError("normalize must be bool")
    result = {}
    for outcome, weight in rows:
        if type(outcome) is not int:
            raise TypeError("outcome must be int, not bool")
        if type(weight) not in (int, str, Fraction):
            raise TypeError("weight must be int, str or Fraction")
        probability = Fraction(weight)
        if probability < 0:
            raise ValueError("negative weight")
        result[outcome] = result.get(outcome, Fraction(0)) + probability
    total = sum(result.values(), Fraction(0))
    if total <= 0:
        raise ValueError("empty or zero-mass distribution")
    if not normalize and total != 1:
        raise ValueError("probabilities must sum exactly to one")
    return {x: p / total for x, p in result.items() if p}


def convolve(left, right):
    left = pmf(left.items())
    right = pmf(right.items())
    result = {}
    for x, px in left.items():
        for y, py in right.items():
            key = x + y
            result[key] = result.get(key, Fraction(0)) + px * py
    return pmf(result.items())


def repeated(base, count):
    if type(count) is not int or count < 0:
        raise ValueError("count must be a nonnegative int")
    base = pmf(base.items())
    result = {0: Fraction(1)}
    for _ in range(count):
        result = convolve(result, base)
    return result

from itertools import product
from random import Random


def oracle(rows, count):
    answer = {}
    for path in product(rows, repeat=count):
        total_time = sum(item[0] for item in path)
        probability = Fraction(1)
        for _, weight in path:
            probability *= weight
        answer[total_time] = answer.get(total_time, Fraction(0)) + probability
    return {x: p for x, p in answer.items() if p}


rng = Random(20261019)
for _ in range(120):
    size = rng.randint(1, 4)
    weights = [rng.randint(1, 5) for _ in range(size)]
    total = sum(weights)
    rows = [(rng.randint(0, 4), Fraction(w, total)) for w in weights]
    count = rng.randint(0, 4)
    actual = repeated(pmf(rows), count)
    assert actual == oracle(rows, count)
# Duplicate outcomes stay separate in the oracle's raw paths.
rows = [(1, Fraction(1, 4)), (1, Fraction(1, 4)), (3, Fraction(1, 2))]
assert repeated(pmf(rows), 4) == oracle(rows, 4)
print("oracle comparisons:", 121)

运行输出:

oracle comparisons: 121

固定随机种子用于复现测试,不代表随机测试已经覆盖全部输入。对照器的成本按原始条目数的重复次数次方增长,因此只用于小规模验证。让它在几百条路径上做得直白,比把它优化成另一个卷积实现更有价值;大规模正确性还需要输入校验、代数性质以及持久化往返测试共同支撑。

五、把数学性质变成可执行断言

卷积的交换律与结合律适合检查循环和聚合逻辑,单位分布适合检查边界,期望与方差则提供另一条验证路线。在独立求和模型下,总期望和总方差分别等于各项之和;前者实际上不要求独立,后者通常要求协方差项为零。这里的核心运算和统计量都保持 Fraction,不提前转成浮点数。

查询某个时长以内完成的概率,也只需把相应结果的质量相加。阈值边界要写清楚:小于五秒与至多五秒不是同一个事件。本例使用包含五秒的条件,输出有理数而不是经过四舍五入的百分比。若界面需要百分比,可以在最终展示层近似,但保存和判断仍使用原始分数。

from fractions import Fraction


def pmf(rows, *, normalize=False):
    if type(normalize) is not bool:
        raise TypeError("normalize must be bool")
    result = {}
    for outcome, weight in rows:
        if type(outcome) is not int:
            raise TypeError("outcome must be int, not bool")
        if type(weight) not in (int, str, Fraction):
            raise TypeError("weight must be int, str or Fraction")
        probability = Fraction(weight)
        if probability < 0:
            raise ValueError("negative weight")
        result[outcome] = result.get(outcome, Fraction(0)) + probability
    total = sum(result.values(), Fraction(0))
    if total <= 0:
        raise ValueError("empty or zero-mass distribution")
    if not normalize and total != 1:
        raise ValueError("probabilities must sum exactly to one")
    return {x: p / total for x, p in result.items() if p}


def convolve(left, right):
    left = pmf(left.items())
    right = pmf(right.items())
    result = {}
    for x, px in left.items():
        for y, py in right.items():
            key = x + y
            result[key] = result.get(key, Fraction(0)) + px * py
    return pmf(result.items())


def repeated(base, count):
    if type(count) is not int or count < 0:
        raise ValueError("count must be a nonnegative int")
    base = pmf(base.items())
    result = {0: Fraction(1)}
    for _ in range(count):
        result = convolve(result, base)
    return result


def moments(distribution):
    mean = sum((x * p for x, p in distribution.items()), Fraction(0))
    variance = sum(((x - mean) ** 2 * p
                    for x, p in distribution.items()), Fraction(0))
    return mean, variance


a = pmf([(1, "1/2"), (2, "1/2")])
b = pmf([(0, "1/3"), (3, "2/3")])
c = pmf([(2, "1/4"), (4, "3/4")])
unit = {0: Fraction(1)}
assert convolve(a, b) == convolve(b, a)
assert convolve(convolve(a, b), c) == convolve(a, convolve(b, c))
assert convolve(a, unit) == a
result = repeated(a, 3)
mean, variance = moments(result)
assert (mean, variance) == (Fraction(9, 2), Fraction(3, 4))
assert moments(a) == (Fraction(3, 2), Fraction(1, 4))
within = sum((p for x, p in result.items() if x <= 5), Fraction(0))
assert within == Fraction(7, 8)
print("mean:", mean, "variance:", variance, "at_most_5:", within)

运行输出:

mean: 9/2 variance: 3/4 at_most_5: 7/8

这些性质不能取代穷举对照。例如,错误地返回某个单位分布可能依然满足归一化,某些错误也会巧合地保留均值。因此测试的目标是建立互相补充的证据,而不是寻找一条万能断言。对于新优化,先让朴素版本充当基准,再把同样的性质测试和小规模枚举比较保留下来。

六、把分子、分母和结果保存为规范文本

精确计算之后,持久化不能再把概率变成 REAL。SQLite 的整数存储有固定范围,而 Python 整数和 Fraction 的分子分母可以更大。本文把结果、分子和分母都保存成十进制 TEXT,让数据库负责键约束与事务,让 Python 负责整数和有理数语义。结果也用文本,是为了保持数学核心支持大整数的契约,而不是因为普通秒数一定需要这么大。

这里的表不是任意字符串都合法。写入前先完成归一化校验,读取时要求整数文本等于重新编码后的字符串,拒绝前导加号、多余前导零或空白;分母必须为正,分子必须为正,分数必须约分,整份分布总和必须恰好为一。零质量条目不落库。SQLite 的 数据类型与亲和性文档解释了 TEXT、INTEGER 和 REAL 的区别;仅仅声明 TEXT 并不能替代这些应用层语义检查。

from fractions import Fraction


def pmf(rows, *, normalize=False):
    if type(normalize) is not bool:
        raise TypeError("normalize must be bool")
    result = {}
    for outcome, weight in rows:
        if type(outcome) is not int:
            raise TypeError("outcome must be int, not bool")
        if type(weight) not in (int, str, Fraction):
            raise TypeError("weight must be int, str or Fraction")
        probability = Fraction(weight)
        if probability < 0:
            raise ValueError("negative weight")
        result[outcome] = result.get(outcome, Fraction(0)) + probability
    total = sum(result.values(), Fraction(0))
    if total <= 0:
        raise ValueError("empty or zero-mass distribution")
    if not normalize and total != 1:
        raise ValueError("probabilities must sum exactly to one")
    return {x: p / total for x, p in result.items() if p}

import sqlite3
from contextlib import closing

big = 10 ** 30 + 57
model = pmf([(10 ** 25, Fraction(1, big)),
             (10 ** 25 + 1, Fraction(big - 1, big))])
encoded = [(str(x), str(p.numerator), str(p.denominator))
           for x, p in sorted(model.items())]
with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    con.execute("CREATE TABLE exact_mass(x TEXT PRIMARY KEY, n TEXT, d TEXT)")
    con.execute("BEGIN IMMEDIATE")
    try:
        con.executemany("INSERT INTO exact_mass VALUES (?, ?, ?)", encoded)
        con.execute("COMMIT")
    except BaseException:
        if con.in_transaction:
            con.execute("ROLLBACK")
        raise
    stored = con.execute("SELECT x, n, d FROM exact_mass").fetchall()
    restored = {int(x): Fraction(int(n), int(d)) for x, n, d in stored}
    assert restored == model
    types = con.execute("SELECT typeof(x), typeof(n), typeof(d) FROM exact_mass").fetchall()
    assert all(row == ("text", "text", "text") for row in types)
    print("exact roundtrip:", restored == model)
    print("cell types:", types[0])

运行输出:

exact roundtrip: True
cell types: ('text', 'text', 'text')

这一段先展示编码与存储类型的最小闭环,只读取自己刚写入的可信样本;下一段加入正式的严格解码器。不要在 SQL 里把这些列 CAST 成 REAL 后再计算概率,也不要把文本排序当数值排序:字符串 10 会排在字符串 2 前面。读取后先恢复 Python 整数,再按整数排序。对于外部不可信输入,还应限制条目数与文本长度;任意精度并不意味着可以无限制消耗资源。

七、替换一整份分布必须是一个事务

更新分布通常包含删除旧行和插入新行两步。如果每句都各自提交,中途失败会把完整旧版本变成空表或半份新版本。这里先在事务外校验并编码,再用 BEGIN IMMEDIATE 包住删除和批量插入。所有 SQL 值都通过占位符绑定,不把名称和分数字符串拼接进 SQL。事务成功才执行 COMMIT,任何中途异常都尝试回滚并重新抛出。

示例要求 Python 3.12 或更新版本,显式使用 autocommit=True,再完全通过 SQL 的 BEGIN、COMMIT 和 ROLLBACK 控制事务;此模式下不要误用连接对象的 commit 或 rollback 方法。Python sqlite3 的事务控制说明对此有明确区分。连接用 closing 保证关闭,因为事务上下文管理器本身不负责关闭连接。replace 要求独占当前事务边界,不在已有事务里悄悄提交调用者的其他修改。

from fractions import Fraction


def pmf(rows, *, normalize=False):
    if type(normalize) is not bool:
        raise TypeError("normalize must be bool")
    result = {}
    for outcome, weight in rows:
        if type(outcome) is not int:
            raise TypeError("outcome must be int, not bool")
        if type(weight) not in (int, str, Fraction):
            raise TypeError("weight must be int, str or Fraction")
        probability = Fraction(weight)
        if probability < 0:
            raise ValueError("negative weight")
        result[outcome] = result.get(outcome, Fraction(0)) + probability
    total = sum(result.values(), Fraction(0))
    if total <= 0:
        raise ValueError("empty or zero-mass distribution")
    if not normalize and total != 1:
        raise ValueError("probabilities must sum exactly to one")
    return {x: p / total for x, p in result.items() if p}

import sqlite3
from contextlib import closing

SCHEMA = """
CREATE TABLE distribution (
    name TEXT NOT NULL,
    outcome TEXT NOT NULL CHECK(typeof(outcome) = 'text'),
    numerator TEXT NOT NULL CHECK(typeof(numerator) = 'text'),
    denominator TEXT NOT NULL CHECK(typeof(denominator) = 'text'),
    PRIMARY KEY(name, outcome)
)
"""


def name_check(name):
    if type(name) is not str or not name or len(name) > 128:
        raise ValueError("invalid distribution name")


def encode(name, distribution):
    name_check(name)
    clean = pmf(distribution.items())
    return [(name, str(x), str(p.numerator), str(p.denominator))
            for x, p in sorted(clean.items())]


def canonical_int(text):
    if type(text) is not str:
        raise ValueError("integer cell must be text")
    value = int(text)
    if str(value) != text:
        raise ValueError("noncanonical integer text")
    return value


def load(con, name):
    name_check(name)
    rows = con.execute(
        "SELECT outcome, numerator, denominator "
        "FROM distribution WHERE name = ?", (name,)
    ).fetchall()
    if not rows:
        raise KeyError(name)
    result = {}
    for sx, sn, sd in rows:
        x, n, d = map(canonical_int, (sx, sn, sd))
        if n <= 0 or d <= 0:
            raise ValueError("stored mass must be positive")
        p = Fraction(n, d)
        if (p.numerator, p.denominator) != (n, d):
            raise ValueError("stored fraction is not reduced")
        if x in result:
            raise ValueError("duplicate decoded outcome")
        result[x] = p
    return pmf(result.items())


def replace(con, name, distribution, *, inject_failure=False):
    rows = encode(name, distribution)
    if con.in_transaction:
        raise RuntimeError("replace requires its own transaction")
    con.execute("BEGIN IMMEDIATE")
    try:
        con.execute("DELETE FROM distribution WHERE name = ?", (name,))
        con.executemany("INSERT INTO distribution VALUES (?, ?, ?, ?)", rows)
        if inject_failure:
            con.execute("INSERT INTO distribution VALUES (?, ?, ?, ?)", rows[0])
        con.execute("COMMIT")
    except BaseException:
        if con.in_transaction:
            con.execute("ROLLBACK")
        raise

old = pmf([(1, "1/2"), (2, "1/2")])
new = pmf([(3, "1/4"), (4, "3/4")])
with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    con.execute(SCHEMA)
    replace(con, "task", old)
    try:
        replace(con, "task", new, inject_failure=True)
    except sqlite3.IntegrityError:
        pass
    else:
        raise AssertionError("failure injection did not fail")
    assert not con.in_transaction
    assert load(con, "task") == old
    print("rollback kept old:", True)
    replace(con, "task", new)
    assert load(con, "task") == new
    print("replacement committed:", True)

运行输出:

rollback kept old: True
replacement committed: True

故障注入会在新行已插入后,再插入一条相同主键,真正触发数据库约束错误,而不是只在事务开始前抛出异常。随后读取旧分布并逐项比较,才能证明回滚覆盖了删除与新插入两部分。BEGIN IMMEDIATE 会提前尝试取得写事务,其他写入者存在时可能返回忙错误;这不等于并发问题被消除,生产环境仍要设计合理超时和有界重试。相关细节见 SQLite 官方事务文档。

八、关闭连接以后,重新打开数据库核对结果

内存里的字典相等,并不能证明磁盘数据已经完整保存。下面在临时目录创建真实数据库文件,计算三次独立执行的分布,事务写入后关闭连接,再打开第二个连接读取。两次连接之间没有共享 Python 字典缓存,比较的是从数据库文本重新构造出来的精确结果。

这个例子同时提醒我们,把计算结果持久化和把推导背景记录完整是两件事。正式系统最好另存模型版本、时长单位、输入分布标识、重复次数以及独立性假设。否则,数值即使精确,也可能被误读为另一套任务配置的结果。为突出核心机制,本文表结构只保存一份命名分布,不冒充完整模型注册系统。

from fractions import Fraction


def pmf(rows, *, normalize=False):
    if type(normalize) is not bool:
        raise TypeError("normalize must be bool")
    result = {}
    for outcome, weight in rows:
        if type(outcome) is not int:
            raise TypeError("outcome must be int, not bool")
        if type(weight) not in (int, str, Fraction):
            raise TypeError("weight must be int, str or Fraction")
        probability = Fraction(weight)
        if probability < 0:
            raise ValueError("negative weight")
        result[outcome] = result.get(outcome, Fraction(0)) + probability
    total = sum(result.values(), Fraction(0))
    if total <= 0:
        raise ValueError("empty or zero-mass distribution")
    if not normalize and total != 1:
        raise ValueError("probabilities must sum exactly to one")
    return {x: p / total for x, p in result.items() if p}


def convolve(left, right):
    left = pmf(left.items())
    right = pmf(right.items())
    result = {}
    for x, px in left.items():
        for y, py in right.items():
            key = x + y
            result[key] = result.get(key, Fraction(0)) + px * py
    return pmf(result.items())


def repeated(base, count):
    if type(count) is not int or count < 0:
        raise ValueError("count must be a nonnegative int")
    base = pmf(base.items())
    result = {0: Fraction(1)}
    for _ in range(count):
        result = convolve(result, base)
    return result


def display(distribution):
    return [(x, str(p)) for x, p in sorted(distribution.items())]

import sqlite3
from contextlib import closing

SCHEMA = """
CREATE TABLE distribution (
    name TEXT NOT NULL,
    outcome TEXT NOT NULL CHECK(typeof(outcome) = 'text'),
    numerator TEXT NOT NULL CHECK(typeof(numerator) = 'text'),
    denominator TEXT NOT NULL CHECK(typeof(denominator) = 'text'),
    PRIMARY KEY(name, outcome)
)
"""


def name_check(name):
    if type(name) is not str or not name or len(name) > 128:
        raise ValueError("invalid distribution name")


def encode(name, distribution):
    name_check(name)
    clean = pmf(distribution.items())
    return [(name, str(x), str(p.numerator), str(p.denominator))
            for x, p in sorted(clean.items())]


def canonical_int(text):
    if type(text) is not str:
        raise ValueError("integer cell must be text")
    value = int(text)
    if str(value) != text:
        raise ValueError("noncanonical integer text")
    return value


def load(con, name):
    name_check(name)
    rows = con.execute(
        "SELECT outcome, numerator, denominator "
        "FROM distribution WHERE name = ?", (name,)
    ).fetchall()
    if not rows:
        raise KeyError(name)
    result = {}
    for sx, sn, sd in rows:
        x, n, d = map(canonical_int, (sx, sn, sd))
        if n <= 0 or d <= 0:
            raise ValueError("stored mass must be positive")
        p = Fraction(n, d)
        if (p.numerator, p.denominator) != (n, d):
            raise ValueError("stored fraction is not reduced")
        if x in result:
            raise ValueError("duplicate decoded outcome")
        result[x] = p
    return pmf(result.items())


def replace(con, name, distribution, *, inject_failure=False):
    rows = encode(name, distribution)
    if con.in_transaction:
        raise RuntimeError("replace requires its own transaction")
    con.execute("BEGIN IMMEDIATE")
    try:
        con.execute("DELETE FROM distribution WHERE name = ?", (name,))
        con.executemany("INSERT INTO distribution VALUES (?, ?, ?, ?)", rows)
        if inject_failure:
            con.execute("INSERT INTO distribution VALUES (?, ?, ?, ?)", rows[0])
        con.execute("COMMIT")
    except BaseException:
        if con.in_transaction:
            con.execute("ROLLBACK")
        raise

from pathlib import Path
from tempfile import TemporaryDirectory

base = pmf([(1, "1/2"), (2, "1/2")])
expected = repeated(base, 3)
with TemporaryDirectory() as directory:
    path = Path(directory) / "durations.sqlite3"
    with closing(sqlite3.connect(path, autocommit=True)) as writer:
        writer.execute(SCHEMA)
        replace(writer, "three_runs", expected)
    with closing(sqlite3.connect(path, autocommit=True)) as reader:
        actual = load(reader, "three_runs")
        assert actual == expected
        assert reader.execute("PRAGMA integrity_check").fetchone() == ("ok",)
        print("reopened:", display(actual))
        print("integrity_check:", "ok")

运行输出:

reopened: [(3, '1/8'), (4, '3/8'), (5, '3/8'), (6, '1/8')]
integrity_check: ok

integrity_check 用来检查数据库结构完整性,不能替代业务约束:一份总概率为二的分布依然可能是结构完全正常的 SQLite 文件。因此回读后的精确校验必须保留。临时目录使示例可重复执行且不污染工作目录;实际项目换成应用专用路径时,需要另外考虑备份策略、权限和异常中断恢复。

九、最后一关:坏输入、坏存储和正常写入一起验收

最后把边界测试放到同一份独立脚本里。输入测试覆盖归一化缺失、负权重抵消、全零、浮点数、布尔结果和零分母;存储测试主动写入尚未约分的分数、非规范整数文本、非法分母和总质量错误。测试故意绕过正式写入函数,模拟数据来自旧程序或手工修改的情况,读取函数必须拒绝把这些行当成正常概率。

测试还检查大分母往返以及事务失败后旧版本不变。不要把异常捕获写得过宽后只打印通过:每个无效样本必须确实抛出预期类别的异常,否则主动抛出 AssertionError。示例中的 assert 是开发验证工具,运行命令不使用会移除断言的优化选项。所有九段代码均可分别保存成 Python 文件,以 python -X dev -W error 文件名.py 执行;标准输出紧跟在对应代码下面,便于读者逐项核对。

from fractions import Fraction


def pmf(rows, *, normalize=False):
    if type(normalize) is not bool:
        raise TypeError("normalize must be bool")
    result = {}
    for outcome, weight in rows:
        if type(outcome) is not int:
            raise TypeError("outcome must be int, not bool")
        if type(weight) not in (int, str, Fraction):
            raise TypeError("weight must be int, str or Fraction")
        probability = Fraction(weight)
        if probability < 0:
            raise ValueError("negative weight")
        result[outcome] = result.get(outcome, Fraction(0)) + probability
    total = sum(result.values(), Fraction(0))
    if total <= 0:
        raise ValueError("empty or zero-mass distribution")
    if not normalize and total != 1:
        raise ValueError("probabilities must sum exactly to one")
    return {x: p / total for x, p in result.items() if p}


def convolve(left, right):
    left = pmf(left.items())
    right = pmf(right.items())
    result = {}
    for x, px in left.items():
        for y, py in right.items():
            key = x + y
            result[key] = result.get(key, Fraction(0)) + px * py
    return pmf(result.items())


def repeated(base, count):
    if type(count) is not int or count < 0:
        raise ValueError("count must be a nonnegative int")
    base = pmf(base.items())
    result = {0: Fraction(1)}
    for _ in range(count):
        result = convolve(result, base)
    return result

import sqlite3
from contextlib import closing

SCHEMA = """
CREATE TABLE distribution (
    name TEXT NOT NULL,
    outcome TEXT NOT NULL CHECK(typeof(outcome) = 'text'),
    numerator TEXT NOT NULL CHECK(typeof(numerator) = 'text'),
    denominator TEXT NOT NULL CHECK(typeof(denominator) = 'text'),
    PRIMARY KEY(name, outcome)
)
"""


def name_check(name):
    if type(name) is not str or not name or len(name) > 128:
        raise ValueError("invalid distribution name")


def encode(name, distribution):
    name_check(name)
    clean = pmf(distribution.items())
    return [(name, str(x), str(p.numerator), str(p.denominator))
            for x, p in sorted(clean.items())]


def canonical_int(text):
    if type(text) is not str:
        raise ValueError("integer cell must be text")
    value = int(text)
    if str(value) != text:
        raise ValueError("noncanonical integer text")
    return value


def load(con, name):
    name_check(name)
    rows = con.execute(
        "SELECT outcome, numerator, denominator "
        "FROM distribution WHERE name = ?", (name,)
    ).fetchall()
    if not rows:
        raise KeyError(name)
    result = {}
    for sx, sn, sd in rows:
        x, n, d = map(canonical_int, (sx, sn, sd))
        if n <= 0 or d <= 0:
            raise ValueError("stored mass must be positive")
        p = Fraction(n, d)
        if (p.numerator, p.denominator) != (n, d):
            raise ValueError("stored fraction is not reduced")
        if x in result:
            raise ValueError("duplicate decoded outcome")
        result[x] = p
    return pmf(result.items())


def replace(con, name, distribution, *, inject_failure=False):
    rows = encode(name, distribution)
    if con.in_transaction:
        raise RuntimeError("replace requires its own transaction")
    con.execute("BEGIN IMMEDIATE")
    try:
        con.execute("DELETE FROM distribution WHERE name = ?", (name,))
        con.executemany("INSERT INTO distribution VALUES (?, ?, ?, ?)", rows)
        if inject_failure:
            con.execute("INSERT INTO distribution VALUES (?, ?, ?, ?)", rows[0])
        con.execute("COMMIT")
    except BaseException:
        if con.in_transaction:
            con.execute("ROLLBACK")
        raise


def must_raise(expected, operation):
    try:
        operation()
    except expected:
        return
    raise AssertionError("expected exception was not raised")


bad_inputs = [([], ValueError), ([(1, 0)], ValueError),
              ([(1, "1/2")], ValueError),
              ([(1, "-1/4"), (1, "5/4")], ValueError),
              ([(1, 0.5)], TypeError), ([(True, 1)], TypeError),
              ([(1, "1/0")], ZeroDivisionError)]
for rows, expected_error in bad_inputs:
    must_raise(expected_error, lambda rows=rows: pmf(rows))
assert pmf([(1, 2), (1, 1)], normalize=True) == {1: Fraction(1)}
assert repeated({2: Fraction(1)}, 0) == {0: Fraction(1)}

bad_storage = [("1", "2", "2"), ("01", "1", "1"),
               ("1", "1", "0"), ("1", "-1", "1"),
               ("1", "1", "2"), ("1", "1", "-1")]
with closing(sqlite3.connect(":memory:", autocommit=True)) as con:
    con.execute(SCHEMA)
    for cells in bad_storage:
        con.execute("DELETE FROM distribution")
        con.execute("INSERT INTO distribution VALUES (?, ?, ?, ?)", ("bad", *cells))
        must_raise(ValueError, lambda: load(con, "bad"))
    con.execute("DELETE FROM distribution")
    huge = 10 ** 40 + 39
    good = pmf([(1, Fraction(1, huge)), (2, Fraction(huge - 1, huge))])
    replace(con, "good", good)
    assert load(con, "good") == good
    must_raise(sqlite3.IntegrityError,
               lambda: replace(con, "good", {9: Fraction(1)}, inject_failure=True))
    assert load(con, "good") == good
    must_raise(KeyError, lambda: load(con, "missing"))
    assert not con.in_transaction
print("input rejection cases:", len(bad_inputs))
print("storage rejection cases:", len(bad_storage))
print("exact storage and rollback:", "PASS")

运行输出:

input rejection cases: 7
storage rejection cases: 6
exact storage and rollback: PASS

到这里,完整链路已经形成:保留原始重复条目,严格建立概率分布,按独立假设做精确卷积,用不同结构的枚举算法对照,再通过规范文本与事务保存。最重要的分工是让数学语义停留在 Python 的整数与 Fraction 世界,让 SQLite 提供可靠的行存储与原子替换,而不是强迫数据库的普通数值类型承担任意精度分数运算。

实际扩展时,先测量支持集数量、最大整数位数和卷积步数,再决定是否采用稀疏优化或重复平方。不要仅按循环层数判断性能,也不要为了提速偷偷裁剪小概率项;裁剪会改变模型,必须单独说明误差和归一化策略。本文实现适合可控规模的有限分布,提供的是一个可验证的精确基线,而不是对所有规模都高效的承诺。

官方参考与复现说明

本文示例与解释为独立编写,官方链接用于核对库接口和存储行为。概率卷积、质量守恒及测试设计均在正文中给出可执行推导和验证;参考文档不是对本文业务模型的背书。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。