open-working-hours/dp-group-stats
GitHub: open-working-hours/dp-group-stats
为工作时长等小群体数据提供差分隐私分组统计的纯Python实现,包含多种隐私机制和预算追踪功能。
Stars: 0 | Forks: 0
# dp-group-stats
工作时长数据的差分隐私分组统计。纯 Python 实现,零运行时依赖。
**状态:Alpha** — API 可能会变更。从 [Open Working Hours](https://openworkinghours.org) 项目中提取。
## 功能特性
- **Laplace 机制**,支持配置 ε(隐私预算)和敏感度
- **发布状态机**(预热中 / 已发布 / 冷却中 / 已屏蔽),防止阈值穿越泄露
- **贡献截断**,支持配置边界(计划时长、实际时长)
- **K-匿名性** + 支配规则(最高1浓度检查)
- **时间粗化** — 按周、双周或月聚合
- **自适应 ε 调度** — 永不超出年度隐私预算上限
- **置信区间** — 用于 Laplace 噪声均值
- **隐私账本协议** — 可插拔的预算追踪(包含内存引用实现)
## 安装
```
pip install git+https://github.com/open-working-hours/dp-group-stats.git
```
开发环境安装:
```
git clone https://github.com/open-working-hours/dp-group-stats.git
cd dp-group-stats
pip install -e ".[dev]"
pytest -v
```
## 快速示例
```
from datetime import date
from dp_group_stats import (
DPGroupStatsV1Config,
laplace_noise,
get_publication_status,
compute_adaptive_epsilon,
InMemoryPrivacyLedger,
)
# 配置 DP pipeline
config = DPGroupStatsV1Config() # defaults: K_MIN=5, eps=1.0, weekly
# 向总和添加校准噪声
sensitivity = config.bounds.actual_weekly_max # 120h
noise = laplace_noise(epsilon=config.epsilon_split.actual_sum, sensitivity=sensitivity)
noisy_sum = 342.5 + noise
# 检查发布资格
status = get_publication_status(
was_active=False, consecutive_eligible=3, consecutive_ineligible=0,
activation_weeks=config.release_policy.activation_weeks,
deactivation_grace_weeks=config.release_policy.deactivation_grace_weeks,
)
print(status) # PublicationStatus.published
# 跟踪隐私预算
ledger = InMemoryPrivacyLedger()
ledger.record(user_id="u1", family="state_specialty", cell="DE/BY/cardiology",
period=date(2026, 3, 16), epsilon=1.0)
print(ledger.user_spent("u1", since=date(2026, 1, 1))) # 1.0
```
## 模块
| 模块 | 内容 |
|--------|----------|
| `config` | `DPGroupStatsV1Config`、`ContributionBounds`、`EpsilonSplit`、`ReleasePolicyConfig`、`PeriodType` |
| `mechanisms` | `laplace_noise`、`laplace_ci_half_width` |
| `policy` | `PublicationStatus`、`get_publication_status` |
| `periods` | `get_period_bounds`、`period_before`、`compute_period_index` |
| `accounting` | `EpsilonLedger`、`compute_adaptive_epsilon`、`PrivacyLedger`(协议)、`InMemoryPrivacyLedger` |
| `simulation` | `run_scenario`、`ScenarioResult` — 在合成数据上进行参数扫描 |
## 模拟
该包包含一个模拟模块,用于在具有用户流失的真实合成数据上验证参数选择(ε、K_MIN、分割比例、支配阈值)。
```
# 单个场景
dp-group-stats-sim --users 2000 --epsilon 1.0 --k-min 5
# 全国参数扫描(96 种组合)
dp-group-stats-sim --sweep --csv > results.csv
# 试点医院场景(柏林,小组)
dp-group-stats-sim --sweep-pilot
# 比较静态与动态时间表
dp-group-stats-sim --sweep-dynamic
```
或以编程方式使用:
```
from dp_group_stats.simulation import run_scenario
result = run_scenario(n_users=2000, epsilon=1.0, split_planned_ratio=0.2,
dominance_threshold=0.30, seed=42, k_min=5)
print(f"Published: {result.pub_pct_end:.0f}%, MAE actual: {result.mae_actual_end:.1f}h")
```
## 许可证
Apache 2.0。参见 [LICENSE](LICENSE)。
标签:K匿名, Laplace机制, meg, Python, 信息安全, 安全规则引擎, 密码学, 小组统计, 工作时长, 差分隐私, 手动系统调用, 敏感度, 数据统计, 数据脱敏, 无后门, 端口扫描, 网络安全, 置信区间, 聚合统计, 逆向工具, 隐私保护, 隐私预算, 零依赖