File size: 25,304 Bytes
71ce2b1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
"""Prepare compact perturbation datasets from pinned scPerturb H5AD releases.

Only unassignable conditions, zero-count rows and explicit author QC failures
are excluded. Counts in retained rows and the original gene axis are validated
in full before committing. No normalization or inferred cell types are added.
"""
from __future__ import annotations
import argparse
import gc
import gzip
import hashlib
import io
import json
from pathlib import Path
import re
import shutil
import tempfile
from urllib.request import Request, urlopen

import anndata as ad
from anndata.io import read_elem, write_elem
import h5py
import numpy as np
import pandas as pd
import scipy.sparse as sp

ROOT = Path(__file__).resolve().parents[1]
RELEASE = 'https://zenodo.org/records/10044268'
SCIPLEX_CODE = 'https://github.com/cole-trapnell-lab/sci-plex/blob/master/'
SPECS = {
 'AissaBenevolenskaya': {'file':'AissaBenevolenskaya2021.h5ad','md5':'c1ee47cc82052c1eed78f3a2e3eea30c','shape':[119071,17820], 'source':'https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE160244', 'title':'PC9 异种移植的单药与联合处理', 'obs':['cell_line','perturbation','chembl_id'], 'var':[]},
 'ChangYe': {'file':'ChangYe2021.h5ad','md5':'9c68660b093ebb3611d114893766fc97','shape':[42277,45066], 'source':'https://www.ebi.ac.uk/biostudies/arrayexpress/studies/E-MTAB-10698', 'title':'PC9 药物处理', 'obs':['cell_line','perturbation','dose_uM','chembl_id'], 'var':['ensembl_gene_id']},
 'McFarlandTsherniak': {'file':'McFarlandTsherniak2020.h5ad','md5':'03204a96b7b5dd96fc3cf33418222cd9','shape':[182875,32738], 'source':'https://pmc.ncbi.nlm.nih.gov/articles/PMC7453022/', 'title':'多细胞系药物与 GPX4 CRISPR 敲除', 'obs':['cell_line','DepMap_ID','perturbation','perturbation_type','dose_uM','timepoint','chembl_id'], 'var':['ensembl_id']},
 'sciplex2': {'file':'SrivatsanTrapnell2020_sciplex2.h5ad','md5':'12a48293a166a859f994551653a2ad8c','shape':[24262,58347], 'source':'https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM4150377', 'title':'A549 四种药物的剂量实验', 'obs':['cell_line','perturbation','dose_uM','control','chembl_id'], 'var':['ensembl_id']},
 'sciplex4': {'file':'SrivatsanTrapnell2020_sciplex4.h5ad','md5':'9335b581baba2df02ecf92eed4b56ad7','shape':[98437,58347], 'source':'https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSM4150379', 'title':'A549/MCF7 代谢条件与 HDAC 抑制剂组合', 'obs':['cell_line','perturbation','dose_value','dose_unit','perturbation_2','dose_uM_2','chembl_id'], 'var':['ensembl_id']},
 'ZhaoSims': {'file':'ZhaoSims2021.h5ad','md5':'2034fe859694fb5458a35cc37a8753c5','shape':[165748,60725], 'source':'https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE148842', 'title':'胶质母细胞瘤患者样本药物处理', 'obs':['patient','tissue','perturbation','dose_uM','chembl_id'], 'var':[]},
}
GENE_URLS = {
 'sciplex2':'https://ftp.ncbi.nlm.nih.gov/geo/samples/GSM4150nnn/GSM4150377/suppl/GSM4150377_sciPlex2_A549_Transcription_Modulators_gene.annotations.txt.gz',
 'sciplex4':'https://ftp.ncbi.nlm.nih.gov/geo/samples/GSM4150nnn/GSM4150379/suppl/GSM4150379_sciPlex4_A549_MCF7_HDACi_gene.annotations.txt.gz',
}
NOTES = {
 'AissaBenevolenskaya': '本文件仅含 GSE160244 的 PC9_xenograft 子实验,固定 72 h;保留单药/联合标签及 ChEMBL。删除全零表达观测,其他 QC 不设新阈值。nperts 的源常量不用于判断联合处理。',
 'ChangYe': '四个源 sample 均在 ArrayExpress SDRF 标为 PC9;补入 cell_line。dose_value 的 micromolar 改为 dose_uM,control 为 0。保留原基因映射及其缺失,不猜测补齐。',
 'McFarlandTsherniak': '仅保留作者 cell_quality=normal;时间序列还须有单一明确 hash_tag。用 DMSO/Tram/Untreated 标签恢复 control/Trametinib/untreated 及具体小时,DMSO 和 untreated 剂量设为 0,并清除不适用的 Trametinib ChEMBL。BRD3379/AZD5591 的源剂量 0 与药物条件冲突,改为缺失,未凭猜测补数值。CRISPR 保留 sgGPX4-1/2 及 sgLACZ/sgOR2J2 对照;timepoint=72,96 表示源采样时间集合,非单细胞确定时点。KO 未套用其他 CRISPRi 数据的敲低阈值。',
 'sciplex2': '删除无 top_oligo 的 529 个观测:源脚本误将未分样细胞设为 control。真正对照为 dose_uM=0,保留原药物标签并新增 control。Dex 的 vehicle 为乙醇,其他药物为 DMSO,比较基线时按药物匹配。固定处理 24 h;未新增 hash 纯度阈值。',
 'sciplex4': '删除缺少细胞系/双通道条件的 40 个观测。两个 perturbation 与剂量通道分别保留;第一通道代谢物为 mM,酶抑制剂为 uM,Chloride 的单位未在已核对来源中明确,dose_unit 留缺失,原数值保留。第二通道为 HDAC 抑制剂,剂量为 uM。固定 24 h;零剂量条件保留,不用源 nperts 代替真实剂量。ChEMBL 仅对应第一通道。',
 'ZhaoSims': 'sample 的 PWxxx 改名 patient;tissue 区分活体切片培养与手术活检。uM/nM 统一为 dose_uM;control 原剂量缺失按无药物记 0。原 celltype=unknown 不作生物学推断;保留原药物拼写,包括 Ispenisib。',
}


def get_bytes(url: str) -> bytes:
    with urlopen(Request(url,headers={'User-Agent':'dataset-curation/1.0'}),timeout=90) as r:
        return r.read()


def text(s):
    return s.astype('string').str.strip()


def compact_strings(frame):
    out=frame.copy();out.attrs.clear()
    for c in out:
        s=out[c]
        if isinstance(s.dtype,pd.CategoricalDtype):out[c]=s.cat.remove_unused_categories()
        elif pd.api.types.is_string_dtype(s.dtype) or s.dtype==object:out[c]=pd.Categorical(s.astype(object))
    return out


def map_annotations(ds, o):
    out=pd.DataFrame(index=o.index.copy());keep=np.ones(len(o),dtype=bool);why={}
    if ds=='AissaBenevolenskaya':
        for c in ['cell_line','perturbation']:out[c]=o[c]
        assert set(text(o['time']))=={'72'}
    elif ds=='ChangYe':
        sample_map={'SAMb6ba60b525':'PC9','SAM6fab2193f0':'PC9','SAMba72f77788':'PC9','SAM4e026f0a8a':'PC9'}
        out['cell_line']=text(o['sample']).map(sample_map)
        out['perturbation']=o['perturbation']
        assert set(text(o['dose_unit']))=={'micromolar'}
        out['dose_uM']=pd.to_numeric(o['dose_value'],errors='raise').astype(float)
    elif ds=='McFarlandTsherniak':
        for c in ['cell_line','DepMap_ID','perturbation','perturbation_type']:out[c]=text(o[c])
        out['dose_uM']=pd.to_numeric(o['dose_value'],errors='raise').astype(float)
        out['timepoint']=text(o['time']).str.replace(', ', ',',regex=False)
        normal=text(o['cell_quality']).eq('normal').to_numpy(dtype=bool)
        why['author_quality_not_normal']=int((~normal).sum());keep &= normal
        tc=text(o['time']).eq('3, 6, 12, 24, 48')
        tag=text(o['hash_tag']).str.extract(r'^(DMSO|Tram|Untreated)_(\d+)hr$')
        ambiguous=tc & tag[0].isna()
        why['unassigned_or_multiplet_timecourse_after_quality']=int((keep & ambiguous.to_numpy()).sum())
        keep &= ~ambiguous.to_numpy()
        good=tc & tag[0].notna()
        out.loc[good,'timepoint']=tag.loc[good,1]
        out.loc[good,'perturbation']=tag.loc[good,0].map({'Tram':'Trametinib','DMSO':'control','Untreated':'untreated'})
        solvent=good & tag[0].isin(['DMSO','Untreated'])
        out.loc[solvent,'dose_uM']=0.0
        active=good & tag[0].eq('Tram')
        out.loc[active,'dose_uM']=0.1
        bad_dose=out['perturbation'].isin(['BRD3379','AZD5591']) & out['dose_uM'].eq(0)
        why['dose_zero_to_missing']=int((keep & bad_dose.to_numpy()).sum())
        out.loc[bad_dose,'dose_uM']=np.nan
        why['timecourse_final_cells']=int((keep & tc.to_numpy()).sum())
        if len(o)==182875:assert why['timecourse_final_cells']==13713
        why['timecourse_control_relabels']=int((keep & solvent.to_numpy()).sum())
        chem=text(o['chembl-ID']);chem.loc[solvent]=pd.NA
        out['chembl_id']=chem
    elif ds=='sciplex2':
        for c in ['cell_line','perturbation']:out[c]=o[c]
        out['dose_uM']=pd.to_numeric(o['dose_value'],errors='raise').astype(float)
        out['control']=out['dose_uM'].eq(0)
        keep &= o['top_oligo'].notna().to_numpy()
        why['unassigned_hash']=int((~keep).sum())
    elif ds=='sciplex4':
        for c in ['cell_line','perturbation','perturbation_2']:out[c]=o[c]
        out['dose_value']=pd.to_numeric(o['dose_value'],errors='raise').astype(float)
        out['dose_uM_2']=pd.to_numeric(o['dose_value_2'],errors='raise').astype(float)
        units={'Acetate':'mM','Citrate':'mM','Pyruvate':'mM','ACLY.inhibitor':'uM','ACSS2.inhibitor':'uM','PDH.inhibitor':'uM','control':'uM'}
        out['dose_unit']=text(o['perturbation']).map(units)
        keep &= out[['cell_line','perturbation','perturbation_2','dose_value','dose_uM_2']].notna().all(axis=1).to_numpy()
        why['missing_combination_annotations']=int((~keep).sum())
    elif ds=='ZhaoSims':
        out['patient']=o['sample'];out['tissue']=o['tissue'];out['perturbation']=o['perturbation']
        doses=pd.to_numeric(o['dose_value'],errors='raise').astype(float)
        units=text(o['dose_unit']);factor=units.map({'uM':1.0,'nM':0.001})
        out['dose_uM']=doses*factor
        control=text(o['perturbation']).eq('control');out.loc[control,'dose_uM']=0.0
        assert out.loc[~control,'dose_uM'].notna().all()
    else:raise ValueError(ds)
    if 'chembl_id' not in out:out['chembl_id']=o['chembl-ID']
    # Dose is intentionally absent for CRISPR, while unsupported Chloride units
    # remain unknown. All other defining condition fields must be present.
    required=[c for c in SPECS[ds]['obs'] if c not in ['chembl_id','dose_unit','dose_uM']]
    complete=out[required].notna().all(axis=1).to_numpy()
    why['other_missing_core_conditions']=int((keep & ~complete).sum());keep &= complete
    out=compact_strings(out[SPECS[ds]['obs']])
    return out,keep,why


def var_annotations(ds, old, cache):
    v=old[SPECS[ds]['var']].copy();proof={}
    if ds in GENE_URLS:
        cache_names={'sciplex2':'GSM4150377_genes.txt.gz','sciplex4':'GSM4150379_genes.txt.gz'}
        cached=cache/cache_names[ds] if cache else None
        data=cached.read_bytes() if cached and cached.exists() else get_bytes(GENE_URLS[ds])
        source=pd.read_csv(io.BytesIO(data),compression='gzip',sep='\t',header=None,names=['id','symbol'])
        assert len(source)==len(v)
        np.testing.assert_array_equal(source['id'].str.split('.').str[0].to_numpy(),old['ensembl_id'].astype(str).to_numpy())
        assert source['id'].is_unique
        v['ensembl_id']=source['id'].to_numpy()
        proof={'gene_annotation_url':GENE_URLS[ds],'gene_annotation_sha256':hashlib.sha256(data).hexdigest(),'full_ensembl_ids_unique':True}
    v=compact_strings(v)
    return v,proof


def digest(matrix):
    h=hashlib.sha256()
    for array in [matrix.data,matrix.indices,matrix.indptr]:
        view=memoryview(np.ascontiguousarray(array)).cast('B')
        for p in range(0,len(view),32*1024**2):h.update(view[p:p+32*1024**2])
    return h.hexdigest()


def statistics(frame):
    result={}
    for c in frame:
        s=frame[c];counts=s.value_counts(dropna=False);counts=counts[counts>0]
        result[c]={'n_unique':int(s.nunique()),'missing':int(s.isna().sum()),'values':[{'value':None if pd.isna(k) else k.item() if isinstance(k,np.generic) else k,'cells':int(n)} for k,n in counts.items()]}
    return result


def export_obs_statistics(path):
    with h5py.File(path,'r') as f:result=statistics(read_elem(f['obs']))
    dest=path.parent.parent/'docs/obs_unique.json';dest.parent.mkdir(exist_ok=True)
    dest.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n');return dest


def describe(ds,path):
    d=path.parent.parent/'docs';d.mkdir(exist_ok=True)
    with h5py.File(path,'r') as f:
        o,v=read_elem(f['obs']),read_elem(f['var']);stats=statistics(o)
        lines=['# '+SPECS[ds]['title'],'',f'`data/{path.name}`:{len(o):,} 个观测 × {len(v):,} 个基因;X 为 `{f["X/data"].dtype}` CSR counts。','', '| obs | 唯一值 | 缺失 |','|---|---:|---:|']
        for c,s in stats.items():lines.append(f'| `{c}` | {s["n_unique"]:,} | {s["missing"]:,} |')
        lines+=['','var:'+('、'.join('`'+c+'`' for c in v) if len(v.columns) else '仅原基因索引')+';其余槽为空,无 raw。','']
        for c in ['perturbation','perturbation_2','timepoint','tissue','control','dose_unit']:
            if c in stats and stats[c]['n_unique']<=20:
                values=[f'`{s["value"]}` ({s["cells"]:,})' for s in stats[c]['values'] if s['value'] is not None]
                lines.append('- `'+c+'`:'+';'.join(values)+'。')
        lines+=['','取值见 [obs_unique.json](obs_unique.json),来源与处理见 [DOWNLOAD.md](DOWNLOAD.md)、[PROCESS.md](PROCESS.md)。','']
    (d/'DETAILS.md').write_text('\n'.join(lines));export_obs_statistics(path)


def document(ds,path,record):
    d=path.parent.parent/'docs';d.mkdir(exist_ok=True);s=SPECS[ds]
    links={
      'AissaBenevolenskaya':'https://github.com/sanderlab/scPerturb/blob/master/dataset_processing/scripts/AissaBenevolenskaya2021.py',
      'ChangYe':'https://www.ebi.ac.uk/biostudies/files/E-MTAB-10698/E-MTAB-10698.sdrf.txt',
      'McFarlandTsherniak':'https://github.com/broadinstitute/mix_seq_ms/blob/master/src/expt_meta_data.R',
      'sciplex2':SCIPLEX_CODE+'small_screen/Notebook_1_small_screen_analysis.R',
      'sciplex4':SCIPLEX_CODE+'large_screen/NotebookX_Rescue_Phenocopy_analysis.R',
      'ZhaoSims':'https://github.com/sanderlab/scPerturb/blob/master/dataset_processing/scripts/ZhaoSims2021.py'}
    download=f'''# {ds} 下载

来源:[scPerturb / Zenodo 10044268]({RELEASE});[原研究]({s['source']})。

```bash
python ../../scripts/prepare.py --dataset {ds} --download
```

从当前数据集的 data/ 目录运行以上命令,或在 several_datasets/ 使用 `python scripts/prepare.py --dataset {ds} --download`。已有成品不会覆盖。

原文件:`{s['file']}`;MD5:`{s['md5']}`。Python:anndata、h5py、numpy、pandas、scipy。
'''
    # One clear command, explicitly relative to the collection root.
    download=download.replace(f'python ../../scripts/prepare.py --dataset {ds} --download',f'python several_datasets/scripts/prepare.py --dataset {ds} --download')
    download=download.replace(f'从当前数据集的 data/ 目录运行以上命令,或在 several_datasets/ 使用 `python scripts/prepare.py --dataset {ds} --download`。已有成品不会覆盖。','从 datasets/ 运行;已有成品只校验结构,不覆盖。也可用 `--input-dir` 指定原始 H5AD 目录。')
    (d/'DOWNLOAD.md').write_text(download)
    labels={'author_quality_not_normal':'作者标注非 normal','unassigned_or_multiplet_timecourse_after_quality':'质量筛选后仍未明确分样','unassigned_hash':'未分样','missing_combination_annotations':'双通道注释缺失','other_missing_core_conditions':'其他核心条件缺失','zero_counts_after_annotation_filter':'全零表达'}
    why=record['excluded'];reason=';'.join(f'{labels[k]} {n:,}' for k,n in why.items() if n)
    proc=['# '+ds+' 处理','',NOTES[ds],'',f'观测 {record["shape_before"][0]:,} → {record["shape_after"][0]:,};基因 {record["shape_after"][1]:,},原索引及顺序保留。排除规则计数:{reason or "无排除"}。','',f'obs {len(record["obs_before"])} → {len(s["obs"])} 列;保留字段见 [DETAILS.md](DETAILS.md)。删除 QC、技术批次、复合标签及冗余常量。','',f'[注释依据]({links[ds]})。']
    if ds in GENE_URLS:
        proc += ['',f'按 [GEO 基因原表]({GENE_URLS[ds]}) 恢复 Ensembl 版本号和 _PAR_Y;全部截断 ID 逐列匹配。gene symbol 索引不变;45 对同 ID 副本不合并。基因原表 SHA-256:`{record["var_proof"]["gene_annotation_sha256"]}`。']
    if ds=='sciplex4':proc+=['','单位不明的 Chloride 保留原剂量数值;dose_unit 缺失不是无药物。两通道均为零剂量才是双零剂量基线。']
    if ds=='McFarlandTsherniak':proc+=['',f'明确时间序列 {record["annotation_fixes"]["timecourse_final_cells"]:,} 个细胞;有 {record["annotation_fixes"]["timecourse_control_relabels"]:,} 个 DMSO/untreated 观测纠正了源 Trametinib 标签。时间序列总数与[原论文]({s["source"]})的清晰分样细胞数一致;{record["annotation_fixes"]["dose_zero_to_missing"]:,} 个不可信零剂量改为缺失。']
    proc += ['', '保留行的 counts、完整基因轴、细胞 ID 和顺序已全量核对;通过 AnnData 回读后写入成品。未归一化、补表达或筛选基因。', '',f'源输入 X:{record["source_encoding"]};成品 X:CSR,`{record["X_dtype"]}`。', '', 'CSR SHA-256(依次连接 data、indices、indptr 的原 dtype 字节):', '',f'- 源全量转为 CSR:`{record["source_csr_sha256"]}`',f'- 源保留行 / 成品:`{record["X_sha256"]}`','']
    (d/'PROCESS.md').write_text('\n'.join(proc));describe(ds,path)


def is_prepared(ds,path):
    with h5py.File(path,'r') as f:
        return (list(f['obs'].attrs['column-order'])==SPECS[ds]['obs'] and list(f['var'].attrs['column-order'])==SPECS[ds]['var'] and 'raw' not in f and all(s in f and not len(f[s]) for s in ['uns','obsm','layers','obsp','varm','varp']))


def prepare(ds,source,path,cache,work):
    print(ds+': checking original file',flush=True)
    with source.open('rb') as handle:source_md5=hashlib.file_digest(handle,'md5').hexdigest()
    if source_md5!=SPECS[ds]['md5']:raise ValueError('Unexpected input MD5: '+str(source))
    with h5py.File(source,'r') as f:
        o,v=read_elem(f['obs']),read_elem(f['var'])
        assert [len(o),len(v)]==SPECS[ds]['shape']
        assert o.index.is_unique and v.index.is_unique
        out,keep,why=map_annotations(ds,o)
        new_var,var_proof=var_annotations(ds,v,cache)
        print(ds+': reading and validating full counts',flush=True)
        encoding=str(f['X'].attrs['encoding-type'])
        matrix=read_elem(f['X']);matrix=matrix.tocsr(copy=False)
    for start in range(0,len(matrix.data),4_000_000):
        a=matrix.data[start:start+4_000_000]
        if not (np.isfinite(a).all() and (a>=0).all() and np.equal(a,np.floor(a)).all()):
            raise ValueError(ds+': X is not finite nonnegative integer counts')
    zero=np.asarray(matrix.sum(axis=1)).ravel()==0
    why['zero_counts_after_annotation_filter']=int((keep & zero).sum());keep &= ~zero
    source_sha=digest(matrix)
    selected=matrix[keep].tocsr(copy=False) if not keep.all() else matrix
    expected=out.iloc[np.flatnonzero(keep)].copy();expected=compact_strings(expected)
    expected_sha=digest(selected)
    print(ds+f': {len(o):,} -> {len(expected):,} observations; writing verified CSR',flush=True)
    path.parent.mkdir(parents=True,exist_ok=True)
    temporary=path.with_suffix('.writing.h5ad')
    if temporary.exists():raise FileExistsError(temporary)
    try:
        with h5py.File(temporary,'w') as f:
            f.attrs['encoding-type']='anndata';f.attrs['encoding-version']='0.1.0'
            for loc,value in [('X',selected),('obs',expected),('var',new_var)]:write_elem(f,loc,value,dataset_kwargs={'compression':'gzip','compression_opts':4})
            for loc in ['uns','obsm','layers','obsp','varm','varp']:write_elem(f,loc,{})
        with h5py.File(temporary,'r') as f:
            for name,array in [('data',selected.data),('indices',selected.indices),('indptr',selected.indptr)]:
                stored=f['X/'+name]
                assert stored.dtype==array.dtype and stored.shape==array.shape
                for start in range(0,len(array),4_000_000):np.testing.assert_array_equal(stored[start:start+4_000_000],array[start:start+4_000_000])
            np.testing.assert_array_equal(f['X'].attrs['shape'],selected.shape)
            pd.testing.assert_frame_equal(read_elem(f['obs']),expected,check_categorical=False,check_column_type=False)
            pd.testing.assert_frame_equal(read_elem(f['var']),new_var,check_categorical=False,check_column_type=False)
        check=ad.read_h5ad(temporary,backed='r')
        try:
            assert check.shape==selected.shape and check.raw is None
            pd.testing.assert_frame_equal(check.obs,expected,check_categorical=False,check_column_type=False)
            pd.testing.assert_frame_equal(check.var,new_var,check_categorical=False,check_column_type=False)
            for loc in ['uns','obsm','layers','obsp','varm','varp']:
                assert not [k for k in getattr(check,loc).keys() if not(loc=='layers' and k is None)]
            for row in sorted({0,len(expected)//2,len(expected)-1}):np.testing.assert_array_equal(check.X[row:row+1].toarray(),selected[row:row+1].toarray())
        finally:check.file.close()
        assert is_prepared(ds,temporary)
        filter_keys={'author_quality_not_normal','unassigned_or_multiplet_timecourse_after_quality','unassigned_hash','missing_combination_annotations','other_missing_core_conditions','zero_counts_after_annotation_filter'}
        record={'dataset':ds,'source_md5':source_md5,'source_bytes':source.stat().st_size,'source_encoding':encoding,'shape_before':[len(o),len(v)],'shape_after':list(selected.shape),'obs_before':list(o.columns),'var_before':list(v.columns),'excluded':{k:n for k,n in why.items() if k in filter_keys},'annotation_fixes':{k:n for k,n in why.items() if k not in filter_keys},'source_csr_sha256':source_sha,'X_sha256':expected_sha,'X_dtype':str(selected.dtype),'var_proof':var_proof,'new_bytes':temporary.stat().st_size,'validated':True}
        (work/(ds+'.json')).write_text(json.dumps(record,ensure_ascii=False,indent=2)+'\n')
        temporary.replace(path)
        document(ds,path,record)
        print(ds+': complete',flush=True)
        return record
    finally:
        temporary.unlink(missing_ok=True)


def write_index():
    lines=['# 其他扰动数据','','| 数据集 | 观测 × 基因 | 内容 |','|---|---:|---|']
    observed=0;prepared=0
    for ds,s in SPECS.items():
        path=ROOT/ds/'data'/(ds+'.h5ad')
        if not path.exists():continue
        with h5py.File(path,'r') as f:n,g=map(int,f['X'].attrs['shape'])
        observed+=n;prepared+=1
        lines.append(f'| [{ds}]({ds}/docs/DETAILS.md) | {n:,} × {g:,} | {s["title"]} |')
    lines[2:2]=[f'{prepared} 个数据集,共 {observed:,} 个观测。','']
    lines += ['','`data/`:精简 H5AD;`docs/`:下载、处理、字段与取值;`scripts/`:处理与统计。','', '```bash','python scripts/prepare.py','python scripts/summarize_obs_unique.py','```','']
    (ROOT/'README.md').write_text('\n'.join(lines))
    (ROOT/'DOWNLOAD.md').write_text('# 数据来源\n\n六份文件来自 [scPerturb / Zenodo 10044268]('+RELEASE+'),原始文件 MD5 已逐份核对。各数据集 docs/DOWNLOAD.md 提供来源及重建命令。\n\n```bash\npython scripts/prepare.py --download\n```\n')


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--dataset',choices=list(SPECS))
    parser.add_argument('--download',action='store_true')
    parser.add_argument('--input-dir',type=Path)
    parser.add_argument('--source-cache',type=Path,help='Optional previously fetched GEO gene annotation files')
    parser.add_argument('--describe',action='store_true')
    parser.add_argument('--keep-work',action='store_true',help='Keep temporary validation checkpoints for an active preparation session')
    args=parser.parse_args();datasets=[args.dataset] if args.dataset else list(SPECS)
    work=ROOT/'.processing/results';work.mkdir(parents=True,exist_ok=True)
    for ds in datasets:
        path=ROOT/ds/'data'/(ds+'.h5ad')
        if path.exists():
            if not is_prepared(ds,path):raise ValueError('Existing output has unexpected schema: '+str(path))
            describe(ds,path);print(ds+': already prepared',flush=True);continue
        if args.describe:raise FileNotFoundError(path)
        source=ROOT/ds/(ds+'.h5ad')
        if args.input_dir:
            options=[args.input_dir/SPECS[ds]['file'],args.input_dir/(ds+'.h5ad'),args.input_dir/ds/(ds+'.h5ad')]
            source=next((p for p in options if p.is_file()),options[0])
        if not source.exists() and not args.download:raise FileNotFoundError(str(source)+'; use --download or --input-dir')
        if source.exists():prepare(ds,source,path,args.source_cache,work)
        else:
            with tempfile.TemporaryDirectory(prefix='scperturb-input-') as tmp:
                source=Path(tmp)/SPECS[ds]['file'];url=RELEASE+'/files/'+SPECS[ds]['file']+'?download=1'
                print('Downloading '+url,flush=True)
                with urlopen(Request(url,headers={'User-Agent':'dataset-curation/1.0'}),timeout=120) as inp,source.open('wb') as out:shutil.copyfileobj(inp,out,16*1024**2)
                prepare(ds,source,path,args.source_cache,work)
        gc.collect()
    write_index()
    if not args.keep_work:
        for ds in datasets:
            (work/(ds+'.json')).unlink(missing_ok=True)
        if work.exists() and not any(work.iterdir()):work.rmdir()
        parent=ROOT/'.processing'
        if parent.exists() and not any(parent.iterdir()):parent.rmdir()


if __name__=='__main__':main()