junidude14 commited on
Commit
45b7387
·
verified ·
1 Parent(s): 0aa992a

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261015T131236Z-corpus-five-marker-codetection/diffusion/dataset/server_1/model8/plans/corpus_macrophage_markers_20261015/RESULT.json ADDED
The diff for this file is too large to render. See raw diff
 
paper-releases/pbisc-diffusion/updates/20261015T131236Z-corpus-five-marker-codetection/diffusion/dataset/server_1/model8/plans/corpus_macrophage_markers_20261015/candidate_marker_counts.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ca6ad59fb6d2d291e77ea360ad81a1f53a697d828c8a07408c3ab2663267cd5f
3
+ size 750374
paper-releases/pbisc-diffusion/updates/20261015T131236Z-corpus-five-marker-codetection/diffusion/dataset/server_1/model8/plans/corpus_macrophage_markers_20261015/check_candidates.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Five-marker raw-count audit in exactly defined training-source candidates.
3
+
4
+ CPU only. Metadata selection is followed by a small-column sparse extraction;
5
+ no full expression matrix or corpus-wide expression search is constructed.
6
+ """
7
+ from __future__ import annotations
8
+ import argparse
9
+ from collections import defaultdict
10
+ import hashlib
11
+ import json
12
+ from pathlib import Path
13
+ import time
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+ import pyarrow.parquet as pq
18
+ import zarr
19
+
20
+ ROOT = Path(__file__).resolve().parent
21
+ M7 = Path('/home/sj_server_1/PBISC/immun-pbmc-fm/model_7_no_annotation_sh_hwang/data')
22
+ E2 = M7 / 'e2_full_source'
23
+ BLOCK = Path('/home/sj_server_1/PBISC/PBISC-data/single-cell-data-block-blood')
24
+ KEY = ['dataset_id', 'donor_id', 'sample_id']
25
+ LABELS = {'C1Q+ CD16 monocyte', 'CD16+_Monocyte_C1QAhi', 'flagged_intermediate_monocyte_C1QAhi'}
26
+ LABEL_COLS = ['label_original', 'label_original_raw_rebuilt'] + [f'source_celltype_l{i}' for i in range(1, 5)]
27
+ GENES = ['C1QA', 'CD163', 'CD68', 'WARS1', 'LGALS3']
28
+ IDS = ['ENSG00000173372', 'ENSG00000177575', 'ENSG00000129226', 'ENSG00000140105', 'ENSG00000131981']
29
+ COLS = np.array([291, 11665, 15192, 13485, 13194])
30
+ zarr.config.set({'async.concurrency': 2, 'threading.max_workers': 2})
31
+
32
+ def sha(p):
33
+ h = hashlib.sha256()
34
+ with Path(p).open('rb') as f:
35
+ for b in iter(lambda: f.read(1 << 20), b''): h.update(b)
36
+ return h.hexdigest()
37
+
38
+ def receipt(p):
39
+ p = Path(p)
40
+ return {'path': str(p), 'bytes': p.stat().st_size, 'sha256': sha(p)}
41
+
42
+ def write_json(p, x):
43
+ Path(p).write_text(json.dumps(x, indent=2) + '\n')
44
+
45
+ def prepare():
46
+ records, selected, shards = [], [], []
47
+ sp = M7 / 'e2_full_index/metadata/sample_index.parquet'
48
+ si = pd.read_parquet(sp)
49
+ records.append(receipt(sp))
50
+ for k in KEY: si[k] = si[k].astype(str)
51
+ assert not si.duplicated(KEY).any()
52
+ files = [p for p in sorted((E2 / 'metadata/obs_sc.parquet').glob('*.parquet'))
53
+ if p.name[:4] in ['006_', '009_', '065_', '200_'] and not p.name.endswith('__strict_overlay.parquet')]
54
+ assert len(files) == 89
55
+ total_rows = 0
56
+ for i, ep in enumerate(files):
57
+ bp = BLOCK / 'metadata/obs_sc.parquet' / ep.name
58
+ eq, bq = pq.ParquetFile(ep), pq.ParquetFile(bp)
59
+ assert eq.metadata.num_rows == bq.metadata.num_rows
60
+ cols = [c for c in LABEL_COLS if c in bq.schema.names]
61
+ bi = iter(bq.iter_batches(batch_size=32768, columns=['source_row_index'] + cols, use_threads=False))
62
+ offset = 0
63
+ local = []
64
+ for eb in eq.iter_batches(batch_size=32768, columns=KEY + ['source_row_index'], use_threads=False):
65
+ e, b = eb.to_pandas(), next(bi).to_pandas()
66
+ assert len(e) == len(b) and np.array_equal(e.source_row_index, b.source_row_index)
67
+ hits = b[cols].isin(LABELS)
68
+ keep = hits.any(axis=1).to_numpy()
69
+ if keep.any():
70
+ v = e.loc[keep].copy()
71
+ for k in KEY: v[k] = v[k].astype(str)
72
+ v['shard_row'] = np.flatnonzero(keep) + offset
73
+ v['source_label'] = b.loc[keep, cols].where(hits.loc[keep]).bfill(axis=1).iloc[:, 0].to_numpy()
74
+ v = v.merge(si[KEY + ['split', 'sample_key']], on=KEY, how='left', validate='many_to_one')
75
+ assert v.split.notna().all()
76
+ v = v[v.split == 'train'].copy()
77
+ v['shard_id'] = ep.stem
78
+ v['flagged'] = v.source_label.str.startswith('flagged_')
79
+ local.append(v)
80
+ offset += len(e)
81
+ assert next(bi, None) is None and offset == eq.metadata.num_rows
82
+ total_rows += offset
83
+ if local: selected.extend(local)
84
+ records.extend([receipt(ep), receipt(bp)])
85
+ shards.append({'shard_id': ep.stem, 'rows': offset})
86
+ print(f'metadata {i+1}/{len(files)}', flush=True)
87
+ v = pd.concat(selected, ignore_index=True)
88
+ assert len(v) == 34122 and int(v.flagged.sum()) == 903
89
+ assert not v.duplicated(['shard_id', 'shard_row']).any()
90
+ assert total_rows == 20609391
91
+ expected = {'006': 2726, '009': 3058, '065': 25268, '200': 2167}
92
+ assert v[~v.flagged].groupby(v.dataset_id.str[:3]).size().to_dict() == expected
93
+ v.to_parquet(ROOT / 'selected_training_candidates.parquet', index=False)
94
+ plans = []
95
+ for sid, d in v.groupby('shard_id', sort=True):
96
+ zp = BLOCK / 'counts/sc_counts' / (sid + '.zarr')
97
+ g = zarr.open_group(str(zp), mode='r')
98
+ for f in sorted(zp.glob('**/zarr.json')): records.append(receipt(f))
99
+ attrs = dict(g.attrs)
100
+ assert attrs['shape'][0] == next(s['rows'] for s in shards if s['shard_id'] == sid)
101
+ mask = np.asarray(g['measurement_mask'][:])[COLS]
102
+ assert mask.shape == (5,) and mask.sum() == 5
103
+ ptr = np.asarray(g['indptr'][:], dtype=np.int64)
104
+ rows = d.shard_row.to_numpy()
105
+ chunk = g['indices'].chunks[0]
106
+ assert chunk == g['data'].chunks[0] == 1000000
107
+ chunks = sorted(set(c for r in rows for c in range(int(ptr[r]) // chunk, (int(ptr[r+1]) - 1) // chunk + 1)))
108
+ paths = [zp / a / 'c' / str(c) for c in chunks for a in ['indices', 'data']]
109
+ comp = sum(p.stat().st_size for p in paths if p.exists())
110
+ plans.append({'shard_id': sid, 'candidate_cells': len(d), 'chunks': chunks,
111
+ 'compressed_bytes_to_read': comp, 'decompressed_bytes_upper_bound': len(chunks) * chunk * 12,
112
+ 'candidate_nnz': int((ptr[rows+1] - ptr[rows]).sum()),
113
+ 'measured': mask.tolist(), 'count_source': attrs['source_count_matrix']})
114
+ write_json(ROOT / 'extraction_plan.json', {'candidate_cells': len(v), 'unflagged': int((~v.flagged).sum()),
115
+ 'flagged': int(v.flagged.sum()), 'source_rows_metadata_only': total_rows,
116
+ 'compressed_bytes_to_read': sum(p['compressed_bytes_to_read'] for p in plans),
117
+ 'decompressed_bytes_upper_bound': sum(p['decompressed_bytes_upper_bound'] for p in plans),
118
+ 'plans': plans, 'metadata_sources': records})
119
+ print(json.dumps({'candidate_cells': len(v), 'compressed_GiB': sum(p['compressed_bytes_to_read'] for p in plans)/2**30,
120
+ 'decoded_GiB': sum(p['decompressed_bytes_upper_bound'] for p in plans)/2**30}), flush=True)
121
+
122
+ def extract():
123
+ plan = json.loads((ROOT / 'extraction_plan.json').read_text())
124
+ v = pd.read_parquet(ROOT / 'selected_training_candidates.parquet')
125
+ out = np.zeros((len(v), 5), dtype=np.int64)
126
+ row_sum = np.zeros(len(v), dtype=np.int64)
127
+ chunk_receipts, checks = [], []
128
+ for i, pp in enumerate(plan['plans']):
129
+ sid = pp['shard_id']
130
+ d = v[v.shard_id == sid].sort_values('shard_row')
131
+ zp = BLOCK / 'counts/sc_counts' / (sid + '.zarr')
132
+ g = zarr.open_group(str(zp), mode='r')
133
+ assert np.array_equal(np.asarray(g['measurement_mask'][:])[COLS], np.ones(5))
134
+ ptr = np.asarray(g['indptr'][:], dtype=np.int64)
135
+ segs = defaultdict(list)
136
+ size = 1000000
137
+ for oi, r in zip(d.index, d.shard_row):
138
+ start, end = int(ptr[r]), int(ptr[r+1])
139
+ while start < end:
140
+ c = start // size
141
+ stop = min(end, (c+1)*size)
142
+ segs[c].append((int(oi), start-c*size, stop-c*size))
143
+ start = stop
144
+ assert sorted(segs) == pp['chunks']
145
+ source_nnz = 0
146
+ for c, sections in sorted(segs.items()):
147
+ start, end = c*size, min((c+1)*size, g['indices'].shape[0])
148
+ ids = np.asarray(g['indices'][start:end], dtype=np.int32)
149
+ values = np.asarray(g['data'][start:end], dtype=np.int64)
150
+ assert len(ids) == len(values) and (values >= 0).all()
151
+ for oi, a, b in sections:
152
+ ix, vals = ids[a:b], values[a:b]
153
+ source_nnz += b-a
154
+ row_sum[oi] += vals.sum()
155
+ for j, col in enumerate(COLS): out[oi, j] += vals[ix == col].sum()
156
+ for arr in ['indices', 'data']:
157
+ fp = zp / arr / 'c' / str(c)
158
+ if fp.exists(): chunk_receipts.append(receipt(fp))
159
+ assert source_nnz == pp['candidate_nnz']
160
+ checks.append({'shard_id': sid, 'candidate_cells': len(d), 'selected_nnz': source_nnz,
161
+ 'unique_chunks': len(segs), 'all_markers_measured': True})
162
+ print(f'expression {i+1}/{len(plan["plans"])} {sid[:3]} n={len(d)}', flush=True)
163
+ assert (out >= 0).all() and (row_sum > 0).all()
164
+ for i, gene in enumerate(GENES): v[gene] = out[:, i]
165
+ v['total_counts_20097'] = row_sum
166
+ v['markers_detected'] = (out > 0).sum(axis=1)
167
+ v['all_five_detected'] = (out > 0).all(axis=1)
168
+ v['c1qa_plus_at_least_three_others'] = (out[:, 0] > 0) & ((out[:, 1:] > 0).sum(axis=1) >= 3)
169
+ v.to_parquet(ROOT / 'candidate_marker_counts.parquet', index=False)
170
+ summarize(v, plan, checks, chunk_receipts)
171
+
172
+ def summarize(v, plan, checks, chunk_receipts):
173
+ groups = []
174
+ for flag, fs in v.groupby('flagged'):
175
+ for name, d in [('ALL', fs)] + list(fs.groupby(fs.dataset_id.str[:3], sort=True)):
176
+ base = {'dataset': name, 'flagged': bool(flag), 'cells': len(d),
177
+ 'samples': d.sample_key.nunique(), 'dataset_scoped_donors': len(d[KEY[:2]].drop_duplicates())}
178
+ for gene in GENES:
179
+ base[gene + '_detected'] = int((d[gene] > 0).sum())
180
+ base[gene + '_fraction'] = float((d[gene] > 0).mean())
181
+ base[gene + '_mean_raw_counts'] = float(d[gene].mean())
182
+ for k in range(6): base[f'exactly_{k}_detected'] = int((d.markers_detected == k).sum())
183
+ for name2 in ['all_five_detected', 'c1qa_plus_at_least_three_others']:
184
+ q = d[d[name2]]
185
+ base[name2] = len(q)
186
+ base[name2 + '_samples'] = q.sample_key.nunique()
187
+ base[name2 + '_dataset_scoped_donors'] = len(q[KEY[:2]].drop_duplicates())
188
+ groups.append(base)
189
+ pd.DataFrame(groups).to_csv(ROOT / 'summary.csv', index=False)
190
+ sample = v.groupby(KEY + ['sample_key', 'flagged'], dropna=False).agg(
191
+ candidate_cells=('shard_row', 'size'), all_five=('all_five_detected', 'sum'),
192
+ c1qa_plus_three_others=('c1qa_plus_at_least_three_others', 'sum')).reset_index()
193
+ sample.to_csv(ROOT / 'sample_support.csv', index=False)
194
+ labels = v.groupby(['dataset_id', 'source_label']).agg(cells=('shard_row', 'size'),
195
+ all_five=('all_five_detected', 'sum'), c1qa_plus_three_others=('c1qa_plus_at_least_three_others', 'sum')).reset_index()
196
+ labels.to_csv(ROOT / 'source_label_summary.csv', index=False)
197
+ write_json(ROOT / 'expression_source_receipts.json', chunk_receipts)
198
+ result = {'status': 'verified', 'selection_scope': 'source-annotated C1Q-high candidates in exact registered train split; not all training cells',
199
+ 'detection_rule': 'raw count > 0; descriptive co-detection, not macrophage identity or high-expression gate',
200
+ 'genes': dict(zip(GENES, IDS)), 'WARS1_stored_symbol': 'WARS',
201
+ 'all_markers_measured_in_all_candidate_shards': True, 'counts': groups,
202
+ 'shard_checks': checks, 'input_metadata': plan['metadata_sources'],
203
+ 'input_expression_chunk_receipt': receipt(ROOT / 'expression_source_receipts.json'),
204
+ 'limitations': ['Candidate selection is conditioned on existing C1Q source labels.',
205
+ 'This does not estimate whole-training-corpus macrophage or marker-positive prevalence.',
206
+ 'Zero counts are finite-sampling non-detection despite measured gene availability.',
207
+ 'Co-detection does not establish macrophage rather than monocyte identity.',
208
+ 'Donor IDs are dataset scoped; cross-dataset person duplication is not resolved.',
209
+ 'AIDA flagged source annotations remain separate.'],
210
+ 'outputs': [receipt(ROOT / n) for n in ['selected_training_candidates.parquet', 'candidate_marker_counts.parquet',
211
+ 'summary.csv', 'sample_support.csv', 'source_label_summary.csv']]}
212
+ write_json(ROOT / 'RESULT.json', result)
213
+ print(pd.DataFrame(groups)[['dataset', 'flagged', 'cells', 'all_five_detected', 'c1qa_plus_at_least_three_others']].to_string(index=False), flush=True)
214
+
215
+ if __name__ == '__main__':
216
+ parser = argparse.ArgumentParser()
217
+ parser.add_argument('stage', choices=['prepare', 'extract'])
218
+ args = parser.parse_args()
219
+ globals()[args.stage]()
paper-releases/pbisc-diffusion/updates/20261015T131236Z-corpus-five-marker-codetection/diffusion/dataset/server_1/model8/plans/corpus_macrophage_markers_20261015/expression_source_receipts.json ADDED
The diff for this file is too large to render. See raw diff