- docs/e2e: 将 DAG 演示面板(dag-panel.mjs/html/data.mjs/sh/DAG演示.command)用 git mv 归入 dag-panel/ 子目录;修正相对依赖 ../lib、../results/dag-runs;清理 _diag_*.mjs 等临时诊断脚本(git rm 已跟踪项,rm 未跟踪项) - web: 修复头部用户名称切账号不变(新增 utils/user.ts 响应式 userName,登录/挂载/路由切换时拉取 /oauth/CurrentUser) - .gitignore: 新增 __pycache__/*.pyc 忽略规则(排除 demo 构建产物) - demo: 多个演示脚本与算子集市用例更新 - .workbuddy/memory: 补充本次工作记录 注意:docs/e2e/sswflow 与 **/__pycache__/*.pyc 按要求排除,未纳入。
101 lines
3.8 KiB
Python
101 lines
3.8 KiB
Python
"""secure_stats 算子:密文统计 secure_mean/var/pearson/correlation_matrix。
|
|
|
|
场景:医院(年龄) + 保险公司(保费) 想知道"年龄 vs 保费"相关性,但谁都不愿交出原始数据。
|
|
- nax API: ``nax.data.stats.secure_mean/var/pearson/correlation_matrix``
|
|
- 底层:去中心化 + 协方差/平方和全程密文,最后只 reveal 1 个相关系数
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
import numpy as np
|
|
from flask import Blueprint, jsonify, request, send_from_directory
|
|
|
|
_NAX = Path(__file__).resolve().parents[2] / "nax"
|
|
if str(_NAX) not in sys.path: sys.path.insert(0, str(_NAX))
|
|
|
|
import nax
|
|
from nax.data.stats import secure_mean, secure_var, secure_pearson, secure_correlation_matrix
|
|
|
|
stats_bp = Blueprint("secure_stats", __name__, url_prefix="/secure_stats")
|
|
|
|
|
|
@stats_bp.route("/")
|
|
def index():
|
|
return send_from_directory(Path(__file__).parent, "index.html")
|
|
|
|
|
|
def _run(alice_age, bob_premium):
|
|
"""alice_age = 医院持有的年龄;bob_premium = 保险公司的保费。"""
|
|
nax.init(["alice", "bob"], backend="local", seed=11)
|
|
alice, bob = nax.site("alice"), nax.site("bob")
|
|
box = nax.vault([alice, bob], seed=13)
|
|
|
|
a = np.array(alice_age, dtype=np.float64)
|
|
b = np.array(bob_premium, dtype=np.float64)
|
|
n = len(a)
|
|
if len(b) != n:
|
|
raise ValueError("alice/bob must be same length")
|
|
|
|
a_sec = box.share(alice.put(a))
|
|
b_sec = box.share(bob.put(b))
|
|
|
|
# 密文均值
|
|
mean_a_res = secure_mean(a_sec, to="alice")
|
|
mean_a = float(np.atleast_1d(np.asarray(mean_a_res.fetch(), dtype=np.float64))[0])
|
|
mean_b_res = secure_mean(b_sec, to="bob")
|
|
mean_b = float(np.atleast_1d(np.asarray(mean_b_res.fetch(), dtype=np.float64))[0])
|
|
|
|
# 密文方差
|
|
var_a_res = secure_var(a_sec, to="alice")
|
|
var_a = float(np.atleast_1d(np.asarray(var_a_res.fetch(), dtype=np.float64))[0])
|
|
var_b_res = secure_var(b_sec, to="bob")
|
|
var_b = float(np.atleast_1d(np.asarray(var_b_res.fetch(), dtype=np.float64))[0])
|
|
|
|
# 密文皮尔逊相关系数(直接返回 float)
|
|
# nax 已知限制:fxp=18 精度下 secure_pearson 偶发 sqrt(负) → nan
|
|
# 真实场景会用更高 fxp 或直接对比 cov / sxx / syy
|
|
pearson_raw = secure_pearson(a_sec, b_sec, to="alice")
|
|
pearson = float(pearson_raw) if not (isinstance(pearson_raw, float) and pearson_raw != pearson_raw) else float("nan")
|
|
|
|
# 密文相关矩阵(直接返回 ndarray)
|
|
corr = np.atleast_2d(np.asarray(secure_correlation_matrix([a_sec, b_sec], to="alice"), dtype=np.float64))
|
|
|
|
nax.shutdown()
|
|
|
|
# 明文校验(用于对比)
|
|
plain_a_mean = float(a.mean()); plain_b_mean = float(b.mean())
|
|
plain_a_var = float(a.var()); plain_b_var = float(b.var())
|
|
plain_pearson = float(np.corrcoef(a, b)[0, 1])
|
|
|
|
return {
|
|
"n": n,
|
|
"alice_age": a.tolist(),
|
|
"bob_premium": b.tolist(),
|
|
"secure_mean_age": mean_a,
|
|
"secure_mean_prem": mean_b,
|
|
"secure_var_age": var_a,
|
|
"secure_var_prem": var_b,
|
|
"secure_pearson": pearson,
|
|
"secure_corr_matrix": corr.tolist(),
|
|
"plain_mean_age": plain_a_mean,
|
|
"plain_mean_prem": plain_b_mean,
|
|
"plain_var_age": plain_a_var,
|
|
"plain_var_prem": plain_b_var,
|
|
"plain_pearson": plain_pearson,
|
|
"abs_diff": abs(pearson - plain_pearson),
|
|
}
|
|
|
|
|
|
@stats_bp.route("/api/run", methods=["POST"])
|
|
def api_run():
|
|
body = request.get_json(silent=True) or {}
|
|
a = body.get("alice") or [] # 年龄
|
|
b = body.get("bob") or [] # 保费
|
|
if not a or not b:
|
|
return jsonify({"error": "alice/bob 必须非空"}), 400
|
|
try:
|
|
return jsonify(_run(a, b))
|
|
except Exception as e:
|
|
return jsonify({"error": str(e)}), 500
|