Metadata-Version: 2.4
Name: phasepred
Version: 0.9.0
Summary: Paper-faithful re-implementation of the PhaSePred phase-separation predictor (Chen et al. 2022, PNAS).
Author: Tingting Li Lab, Department of Biochemistry and Molecular Biology, School of Basic Medical Sciences, Peking University
License-Expression: MIT
Project-URL: Homepage, https://www.pnas.org/doi/10.1073/pnas.2115369119
Project-URL: Documentation, https://github.com/NotWhiteBlank/PhaSePred
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: <3.13,>=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: biopython>=1.85
Requires-Dist: catgranule<2,>=1.0
Requires-Dist: joblib>=1.5
Requires-Dist: localcider>=0.1.21
Requires-Dist: matplotlib>=3.8
Requires-Dist: numpy<3,>=1.26
Requires-Dist: openpyxl>=3.1
Requires-Dist: pandas>=2.2
Requires-Dist: pydantic>=2.11
Requires-Dist: pyarrow>=20.0
Requires-Dist: python-calamine>=0.3
Requires-Dist: requests>=2.32
Requires-Dist: scikit-learn>=1.5
Requires-Dist: scipy>=1.13
Requires-Dist: shap>=0.46
Requires-Dist: tqdm>=4.67
Requires-Dist: typer>=0.15
Requires-Dist: xgboost<4,>=3.2
Dynamic: license-file

# PhaSePred

> 输入蛋白质氨基酸序列，预测其相分离倾向。
> 本仓库由北京大学李婷婷实验室（Tingting Li Lab）维护，是 [Chen et al. 2022 *PNAS*](https://doi.org/10.1073/pnas.2115369119)（本实验室前期工作）的**论文忠实重建**——`v2022` 特征定义 + 单一产物（Product A）。

[English](README-en.md)

## 背景

**相分离（phase separation）** 是蛋白质在细胞内自发凝聚成液滴状区室的过程——像油滴在水中形成。这些"无膜细胞器"（应激颗粒、核仁、Cajal小体等）无需膜结构就能组织细胞内的生化反应。相分离失调与神经退行性疾病（ALS、阿尔茨海默病）和癌症密切相关。

本工具预测蛋白质参与相分离的倾向，区分两种机制：

| 模式 | 含义 | 适用物种 |
|------|------|---------|
| **SaPS** | 自驱动相分离——蛋白自己就能凝聚 | 任意物种（8 个特征） |
| **PdPS** | 伴侣依赖相分离——需要结合伙伴蛋白 | 任意物种（8 个特征） |
| **hSaPS** | 人类自驱动相分离 | 人类蛋白（10 个特征） |
| **hPdPS** | 人类伴侣依赖相分离 | 人类蛋白（10 个特征） |

输出是 0 到 1 之间的分数。分数不是校准概率，而是该模式内的相对排序（分数越高，蛋白属于该模式的可能性越大）。

## 单一产物（Product A）

仓库只提供 **一套模型**：**Product A**（`products/A_paper_split_recomputed/`）——按论文 S2/S3 划分、以论文协议（XGBoost 10 模型集成、2:1 负样本子抽样）训练。Product B（扩充数据重训）已按重建决策 D8 删除。

**特征定义**统一按 `docs/FEATURES.md` 的 **v2022 权威定义**逐项落地，关键判定（S1 审计结论）：

- **DeepCoil**：0.82 阈值**二值化**（`max(raw_cc) ≥ 0.82 → 1 else 0`），不再是连续均值。
- **ESpritz IDR**：DisProt 模型 `D`、`sw 0`(5% FPR)，只统计两列残基行（横幅/许可行不计入）。
- **catGRANULE**：独立 `catgranule` 包提供（论文公式 + mmc1 Table S4 尺度表 + Z 归一），旧权重原样标记 `provenance: legacy-unaudited`。
- **IUPred3**：论文不用，已移除（D17）；IDR 一律用 ESpritz。
- Hydropathy、FCR、PLAAC(NLLR)、PScore、Phos、DeepPhase 判定"一致"，数值逻辑保留。

> **stale 警告**：当前 Product A 工件训练时未绑定 `feature_definitions_version`（v2022），因此 `predict` 会输出显著的 stale 警告并在 CSV 附 `stale=True` 列。S5 按论文协议重训后该警告自动消失（机制保留）。

## 快速开始

```bash
# 1. 克隆并准备 Python 环境
git clone https://github.com/notwhiteblank/PhaSePred.git && cd PhaSePred
pixi install

# 2. 安装外部特征工具（详见下一节）
bash tools/SEG/install.sh          # 或按各工具自带的 install.sh
bash tools/PLAAC/install.sh
bash tools/PScore/install.sh
bash tools/ESpritz/install.sh      # 交互式（学术许可，需自行下载）
bash tools/DeepCoil/install.sh
bash tools/LocalCIDER/install.sh

# 3. 校验所有工具就绪
pixi run phasepred check-tools

# 4. 预测
pixi run phasepred predict --fasta my.fasta --mode SaPS --output scores.csv
```

输出 CSV 包含 `UniprotEntry, score, length, Hydropathy, FCR, IDR, LCR, PScore, PLAAC, catGRANULE, DeepCoil[, Phos freq, DeepPhase], stale`，所有特征数值都有，便于核查。

## 工具安装（必读）

PhaSePred 调用 **5 个外部特征工具 + LocalCIDER 库**（catGRANULE 由 `catgranule` 包提供，作为 Python 依赖安装）。从 S3 起，每个工具是一个**自包含工具包契约** `tools/<TOOL>/`（统一入口 `run` + 机器可读 `manifest.toml` + 幂等 `install.sh` + `README.md`）。phasepred 经 `src/phasepred/tool_paths.py` 的 manifest 注册表定位工具，按 `PHASEPRED_<TOOL>_DIR → tools/<TOOL>/ → PATH` 级联解析。安装后请执行 `phasepred check-tools` 验证。

| 工具 | License | 安装方式 | 可再分发 |
|---|---|---|---|
| **SEG** | NCBI 公共域惯例 | `bash tools/SEG/install.sh`（源码已 vendored，本地编译） | 是 |
| **PScore** | CC-BY 4.0 | 代码已 vendored；`DBS/` 数据 gitignored，`bash tools/PScore/install.sh` | 代码是（需署名） |
| **PLAAC** | MIT | 预编译 jar 已 vendored；需要 Java 11+ | 是 |
| **ESpritz** | 学术许可 | `bash tools/ESpritz/install.sh`（交互式，自行下载） | **否** |
| **DeepCoil** | 上游无 LICENSE | `bash tools/DeepCoil/install.sh`（隔离 Python 3.8 conda env） | **否** |
| **LocalCIDER** | GPL-2.0 | `bash tools/LocalCIDER/install.sh`（pip 安装，不 vendored） | 是（经 PyPI） |
| **catGRANULE** | MIT（独立包） | `pixi install` 自动安装 `catgranule`（`packages/catgranule/`） | 是 |

> 历史工具 **IUPred3**（ELTE 学术许可，论文不用，D17）已归档至 `tools/_archive/IUPred3/`，不在 predict 路径，不入契约清单。catGRANULE v2 归档至 `tools/_archive/catGRANULE_v2/`（53/82 scales 缺陷，仅实验）。

第三方的授权限制部分必须本地下载，license 审计明细见 [docs/TOOL_LICENSES.md](docs/TOOL_LICENSES.md)。

### 路径解析器如何工作

源码里**没有任何 `Tools/<X>/<bin>` 形式的硬编码路径**。每个工具契约的 `manifest.toml` 声明 `name/kind/entry/license/redistributable/runtime/install` 等字段；`src/phasepred/tool_paths.py` 扫描 `tools/*/manifest.toml` 建注册表，按三级级联解析：

1. **环境变量**：`PHASEPRED_<TOOL>_DIR=/path/to/tools/ESpritz`（目录须含该契约的 `run`）
2. **仓库内契约包**：`tools/<TOOL>/run`
3. **PATH**：`shutil.which`（仅 manifest `path_executables` 声明的工具，如 SEG→`seg`、DeepCoil→`deepcoil`）
4. **报错**：抛出 `PhaSePredToolNotFound`，并附该工具的 `install.sh` 指引

工具执行统一走 `src/phasepred/tools.py` 的 Runner（定位 → 执行 → 解析 → 降级；工具缺失时对应特征列退化为 NaN，predict 在读取输入前通过 `assert_predict_requirements` 预先失败）。`check-tools` 会额外调用每个契约的 `./run --check`，反映"运行时是否可用"（二进制已编译 / 数据已解压 / 环境已安装）。

### check-tools 检查表

安装完成后跑：

```bash
pixi run phasepred check-tools
```

输出示例（S3 起含 LICENSE / REDISTRIBUTABLE 两列）：

```
TOOL        STATUS  REQUIRED  SOURCE    PATH                                 LICENSE                        REDISTRIBUTABLE
----------  ------  --------  --------  -----------------------------------  -----------------------------  ---------------
SEG         OK      yes       vendored  /repo/tools/SEG/run                   ncbi-public-domain-convention  yes
PLAAC       OK      yes       vendored  /repo/tools/PLAAC/run                 MIT                            yes
PScore      OK      yes       vendored  /repo/tools/PScore/run                CC-BY-4.0                      yes
ESpritz     OK      yes       vendored  /repo/tools/ESpritz/run               Tosatto-academic-1.1           no
DeepCoil    OK      yes       vendored  /repo/tools/DeepCoil/run              none                           no
LocalCIDER  OK      yes       vendored  /repo/tools/LocalCIDER/run            GPL-2.0                        yes
catGRANULE  OK      yes       package   /repo/packages/catgranule/src/catgranule  MIT                         yes

7 OK  ·  0 MISSING  ·  0 required-but-missing
```

任何 `required-but-missing > 0`，`phasepred predict` 会在读 FASTA **之前** 就退出并提示具体安装命令。

### 工具故障排查

| 症状 | 通常原因 | 修复 |
|---|---|---|
| `SEG not found` | 没编译 SEG | `bash tools/SEG/install.sh` |
| `PLAAC not found` | 没装 Java 运行时 | `sudo apt install openjdk-11-jre-headless` 或 `brew install openjdk` |
| `ESpritz not found` | 没解压学术许可归档 | `bash tools/ESpritz/install.sh`；或 `PHASEPRED_ESPRITZ_DIR` 指到含 `run` 的契约目录 |
| `DeepCoil env not found` | 没装隔离 conda env | `bash tools/DeepCoil/install.sh` |
| `LocalCIDER not found` | 环境内没 pip 装 localcider | `bash tools/LocalCIDER/install.sh`；或用 `PHASEPRED_PYTHON` 指向含 localcider 的解释器 |

## 可选：人类模型额外数据（hSaPS / hPdPS 需要）

`SaPS` 和 `PdPS` 用 8 个特征，完全从序列计算，不需要额外文件。

`hSaPS` 和 `hPdPS` 多用 2 个特征——`Phos freq`（磷酸化位点密度）和 `DeepPhase`（显微图像评分）。这两个不是可以"装一个工具跑出来"的特征：它们来自上游论文/数据库提供的**查找表**，因此 PhaSePred **不能从序列重新算**。两份数据必须由用户自己下载：

| 特征 | 数据来源 | License | 期望路径 |
|---|---|---|---|
| Phos freq | [PhosphoSitePlus](https://www.phosphosite.org/) `Phosphorylation_site_dataset.gz` | 需要注册下载，禁止再分发 | `data/raw/external/phosphositeplus/Phosphorylation_site_dataset.gz` |
| DeepPhase | [DeepPhase 论文 supplement](https://github.com/PEILab/DeepPhase) `tableS3.xlsx` | 学术使用，参见上游 | `data/raw/external/deepphase/extracted/tableS3.xlsx` |

**没有这两个文件会怎样？** `phasepred predict --mode hSaPS|hPdPS` **仍然能跑**，但会在 stderr 输出 `PhaSePredMissingDataWarning`，明确告诉你哪几个蛋白用了中位数填充（即"分数仅供参考，不是基于完整特征的判断"）。

## 使用

### 预测（FASTA → 分数）

```bash
# 8 特征模型（任意物种）
pixi run phasepred predict --fasta proteins.fasta --mode SaPS  --output scores.csv
pixi run phasepred predict --fasta proteins.fasta --mode PdPS  --output scores.csv

# 10 特征模型（人类蛋白）
pixi run phasepred predict --fasta proteins.fasta --mode hSaPS --output scores.csv
pixi run phasepred predict --fasta proteins.fasta --mode hPdPS --output scores.csv

# 用 UniProt ID 直接预测（三种输入形式都支持）
pixi run phasepred predict --ids "P35637,Q9Y2W1" --mode SaPS --output scores.csv      # 内联
pixi run phasepred predict --ids my_ids.txt --mode SaPS --output scores.csv           # 文件（每行一个 ID）
cat my_ids.txt | pixi run phasepred predict --ids - --mode SaPS --output scores.csv   # stdin

# FASTA 和 IDs 可以混用（去重后合并）
pixi run phasepred predict --fasta my.fasta --ids "P35637" --mode SaPS --output scores.csv
```

> `--models-dir` 可覆盖模型目录；`--product` 已随 Product B 一起移除。

ID 输入会调 `https://rest.uniprot.org` 拉序列，结果缓存到 `data/interim/uniprot_cache.jsonl`，下次同样的 ID 不再请求网络。用 `--cache PATH` 可以指定别的缓存位置。

### v2022 特征计算

```bash
# 只算 8/10 个特征（FASTA → 特征表）
pixi run phasepred features-from-fasta --input my.fasta --output features.csv
#   输出含 native 特征 + espritz-idr-fraction（ESpritz 域 IDR）+ lcr-fraction（SEG 域）

# 完整 8/10 特征重算（requires --deepcoil-features；catGRANULE 走 catgranule 包）
pixi run phasepred features-recomputed \
    --sequences data/interim/sequences.csv \
    --output data/interim/recomputed_features_full.csv \
    --espritz-cache data/interim/espritz_idr_cache.jsonl \
    --deepcoil-features data/interim/deepcoil_features.csv
```

### 复现 Product A

```bash
# 按论文协议重训 Product A（默认 XGBoost，5-fold×10 负集×2:1，SEED=42）
pixi run retrain
```

## 仓库结构

```
src/phasepred/             共享库 + CLI（模块边界:features/tools/models/cli/data）
  cli.py                   predict / check-tools / features-from-fasta / ...
  predictor.py             FASTA → 特征 → 预测全流程（单产物，stale 检测）
  tools.py                 外部工具 Runner（定位→执行→解析→降级）
  features.py              纯计算：native 特征 + v2022 残基对齐工具
  models.py                训练/加载/预测 + feature_definitions_version 机制
  data.py                  REPO_ROOT / PHASEPRED_DATA_ROOT 解析
  tool_paths.py             manifest 注册表路径解析（PHASEPRED_<TOOL>_DIR → tools/<TOOL>/ → PATH）

packages/catgranule/       独立 catgranule 包（0.1.0,由 phasepred path 依赖）
  src/catgranule/          scoring / weights / cli（catgranule CLI）
  weights/                 catgranule_v1_weights.json（含 provenance: legacy-unaudited）

products/
  A_paper_split_recomputed/  论文划分 + Optuna 调优 XGBoost（唯一产物）
    models/<task>/8f_model_{0..9}.joblib              （10 模型集成 × 4 任务）

tools/                     外部工具包契约（S3 标准工具包，每工具一个目录）
  <TOOL>/run                统一入口:./run <in.fasta> [原生参数] → stdout 标准格式
  <TOOL>/manifest.toml      机器可读契约:name/kind/license/redistributable/runtime/install/...
  <TOOL>/install.sh        幂等安装(含 --check);README.md 用法/出处/许可/署名
  SEG/ PLAAC/ PScore/ ESpritz/ DeepCoil/ LocalCIDER/  六契约
  _archive/                 catGRANULE_v2/（实验） + IUPred3/（D17 归档）

docs/                      FEATURES.md / RETRAIN_PROTOCOL.md / CATGRANULE_SPEC.md
                           / TOOL_LICENSES.md / ENVIRONMENT.md / migration/
tests/                     pytest 测试套件（含 packages/catgranule/ 独立测试）
```

## 探索过程与关键结论

项目从重建实验室 2022 年发表的 PhaSePred 起步（Chen et al. 2022, *PNAS*）。重建中最重要的审计结论已经落在 `docs/FEATURES.md`（v2022 特征定义权威对照）：**唯一重大定义偏差是 DeepCoil 二值化**（论文 = 0.82 阈值 0/1，早期重建误用均值），已在 S2 修复；ESpritz 横幅行解析小瑕疵也已修复。详细实施记录见 `docs/migration/PLAN.md` 与 `docs/migration/work-log/`。

性能历史数字（0.x 重建版，Optuna 调优 + S3 测试集）见旧版 README 与 `products/A_paper_split_recomputed/metrics.json`；S5 将按论文默认参数重训并记录论文层 AUC 对照。

## 引用

如使用本工具，请引用原始论文：

> Chen, Z., Hou, C., Wang, L., Yu, C., Chen, T., Shen, B., Hou, Y.,
> Li, P., Li, T. (2022). Screening membraneless organelle participants
> with machine-learning models that integrate multimodal features.
> *Proceedings of the National Academy of Sciences* 119(24), e2115369119.
> https://doi.org/10.1073/pnas.2115369119

catGRANULE 打分实现源自 Bolognesi et al. 2016（*Cell Reports* 16:222-231）。外部特征工具的引用见 [docs/TOOL_LICENSES.md](docs/TOOL_LICENSES.md)。

## License

PhaSePred 本仓库（代码、模型、文档）采用 **MIT License** 发布。详见根目录 [LICENSE](LICENSE)。

> Copyright (c) 2026 Tingting Li Lab, Department of Biochemistry and Molecular Biology,
> School of Basic Medical Sciences, Peking University.

仓库内 vendored 的第三方组件（PLAAC、PScore、SEG）保留各自的上游 license——见
[docs/TOOL_LICENSES.md](docs/TOOL_LICENSES.md) 的完整审计。用户自行安装的工具
（ESpritz、DeepCoil）遵循各自上游条款。
