BoHuangLab commited on
Commit
b52b2a8
·
verified ·
1 Parent(s): a46a831

Drop the top-level copies; they live in cell_fm/apps/condenseq now

Browse files
Files changed (2) hide show
  1. metrics.py +0 -135
  2. pipeline.py +0 -338
metrics.py DELETED
@@ -1,135 +0,0 @@
1
- """Curve metrics for the condensate titration analysis.
2
-
3
- Port of cell_diff/tasks/analysis/utils.py from CELL-Diff2-Dev, restricted to the
4
- three quantities this demo reports:
5
-
6
- AUC area under the moving-averaged condensate-probability curve
7
- NR the same curve with everything past its maximum held flat ("no reentrant")
8
- AAC NR - AUC, i.e. the area *above* the curve that reentrant dissolution opens up
9
-
10
- All three integrate against log10(intensity) by default and are normalised by the
11
- width of the integration domain, so they live in [0, 1] and are comparable across
12
- sequences.
13
- """
14
-
15
- import numpy as np
16
- import pandas as pd
17
-
18
-
19
- def moving_average(y, window: int) -> np.ndarray:
20
- """Centred rolling mean, shrinking the window at the edges rather than padding."""
21
- y = np.asarray(y, dtype=float)
22
- window = int(max(1, min(window, len(y))))
23
- return (
24
- pd.Series(y)
25
- .rolling(window=window, center=True, min_periods=1)
26
- .mean()
27
- .to_numpy()
28
- )
29
-
30
-
31
- def integral(xs: np.ndarray, ys: np.ndarray) -> float:
32
- xs = np.asarray(xs, dtype=float)
33
- ys = np.asarray(ys, dtype=float)
34
-
35
- if xs.ndim != 1 or ys.ndim != 1:
36
- raise ValueError("xs and ys must be 1D arrays")
37
- if xs.shape[0] != ys.shape[0]:
38
- raise ValueError("xs and ys must have the same length")
39
- if xs.shape[0] < 2:
40
- return 0.0
41
-
42
- return float(np.trapz(ys, xs))
43
-
44
-
45
- def _prepare(df: pd.DataFrame, window_size: int, use_log_scale: bool):
46
- """Return (x, curve) sorted by x, with x log10-scaled when requested.
47
-
48
- Sorting happens once, before the moving average is taken, so the smoothing
49
- always runs along increasing intensity.
50
- """
51
- intensity_levels = df["protein_intensity_level"].to_numpy(dtype=float)
52
- predicted_classes = df["predicted_class"].to_numpy(dtype=float)
53
-
54
- order = np.argsort(intensity_levels)
55
- intensity_levels = intensity_levels[order]
56
- predicted_classes = predicted_classes[order]
57
-
58
- curve = moving_average(predicted_classes, window_size)
59
-
60
- if use_log_scale:
61
- # clip at 1.0 so that intensities below 1 do not send log10 negative/-inf
62
- x = np.log10(np.clip(intensity_levels, a_min=1.0, a_max=None))
63
- else:
64
- x = intensity_levels
65
-
66
- return x, curve
67
-
68
-
69
- def _normalise(area: float, x: np.ndarray, normalize: bool) -> float:
70
- if not normalize:
71
- return area
72
- total_area = (x[-1] - x[0]) * 1.0
73
- return area / total_area
74
-
75
-
76
- def compute_area_under_curve(
77
- df: pd.DataFrame, window_size: int, normalize: bool = True, use_log_scale: bool = True
78
- ) -> float:
79
- """AUC: how much of the intensity range this sequence spends in the condensed state."""
80
- x, curve = _prepare(df, window_size, use_log_scale)
81
- return _normalise(integral(x, curve), x, normalize)
82
-
83
-
84
- def no_reentrant_curve(curve: np.ndarray) -> np.ndarray:
85
- """The curve it would have been without reentrant dissolution.
86
-
87
- Everything past the maximum is held at the maximum, so the difference against
88
- the real curve is exactly the dissolution that happens at high concentration.
89
- """
90
- max_index = int(np.argmax(curve))
91
- out = curve.copy()
92
- out[max_index:] = float(np.max(curve))
93
- return out
94
-
95
-
96
- def compute_area_if_no_reentrant(
97
- df: pd.DataFrame, window_size: int, normalize: bool = True, use_log_scale: bool = True
98
- ) -> float:
99
- """Area under the curve after flattening everything past its maximum."""
100
- x, curve = _prepare(df, window_size, use_log_scale)
101
- return _normalise(integral(x, no_reentrant_curve(curve)), x, normalize)
102
-
103
-
104
- def compute_area_if_no_reentrant_minus_auc(
105
- df: pd.DataFrame, window_size: int, normalize: bool = True, use_log_scale: bool = True
106
- ) -> float:
107
- """AAC, the area *above* the curve: no-reentrant area minus the real area.
108
-
109
- Zero when the curve never comes back down; larger the more the sequence
110
- dissolves again at high concentration.
111
- """
112
- x, curve = _prepare(df, window_size, use_log_scale)
113
- return _normalise(integral(x, no_reentrant_curve(curve) - curve), x, normalize)
114
-
115
-
116
- # the paper's name for compute_area_if_no_reentrant_minus_auc
117
- compute_area_above_curve = compute_area_if_no_reentrant_minus_auc
118
-
119
-
120
- def compute_concentration(
121
- df: pd.DataFrame, window_size: int, threshold_prob: float = 0.8
122
- ) -> float:
123
- """c_sat: the first intensity at which the smoothed curve reaches threshold_prob.
124
-
125
- inf when the sequence never condenses over the scanned range.
126
- """
127
- intensity_levels = df["protein_intensity_level"].to_numpy(dtype=float)
128
- predicted_classes = df["predicted_class"].to_numpy(dtype=float)
129
-
130
- order = np.argsort(intensity_levels)
131
- intensity_levels = intensity_levels[order]
132
- curve = moving_average(predicted_classes[order], window_size)
133
-
134
- hits = np.flatnonzero(curve >= threshold_prob)
135
- return float(intensity_levels[hits[0]]) if hits.size else float("inf")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
pipeline.py DELETED
@@ -1,338 +0,0 @@
1
- """CELL-FM CondenSeq: sequence -> condensate titration curve.
2
-
3
- The demo runs the same three stages as the offline analysis, in memory:
4
-
5
- 1. generate CELL-FM CS samples one image per protein-intensity level, over a
6
- log-spaced concentration ladder (evaluate_seq2img_dict.py)
7
- 2. classify a ViT labels each image condensed / diffuse (evaluate_single_img.py)
8
- 3. summarise a centred moving average over the binary calls gives the condensate
9
- probability curve (ma_plot.py), and AUC / AAC integrate it
10
- (analysis/ana_all_mutation_log_scale.py)
11
-
12
- Weights come from a HF model repo by default; set CELLFM_LOCAL_WEIGHTS to a
13
- directory holding the three .bin files to run against a local copy instead.
14
- """
15
-
16
- import os
17
- from dataclasses import dataclass, field
18
- from functools import lru_cache
19
-
20
- import numpy as np
21
- import pandas as pd
22
- import torch
23
-
24
- from cell_fm.criterions.cell_fm.unidiffuser import UniDiffCriterions
25
- from cell_fm.models.cell_fm.cell_fm_cs_config import CELLFMConfig
26
- from cell_fm.models.cell_fm.cell_fm_cs_model import CELLFMCSModel
27
- from cell_fm.models.vit_cls_condenseq_img.config import ViTConfig
28
- from cell_fm.models.vit_cls_condenseq_img.model import ViTModel
29
-
30
- import metrics
31
-
32
- HERE = os.path.dirname(os.path.abspath(__file__))
33
-
34
- MODEL_REPO = os.environ.get("CELLFM_MODEL_REPO", "BoHuangLab/CELL-FM")
35
- LOCAL_WEIGHTS = os.environ.get("CELLFM_LOCAL_WEIGHTS", "")
36
-
37
- # The weight repo holds one subfolder per model family, so paths are prefixed.
38
- # CELLFM_LOCAL_WEIGHTS points at a flat directory, hence the basename() below.
39
- GENERATOR_WEIGHTS = "condenseq/cellfm_seq2img.bin"
40
- VAE_WEIGHTS = "condenseq/vae.bin"
41
- CLASSIFIER_WEIGHTS = "condenseq/vit_cls.bin"
42
-
43
- # The concentration ladder. The offline runs scanned 4096 levels; the demo scans
44
- # fewer for latency, and the moving-average window scales with it (see WINDOW_DIVISOR).
45
- MIN_INTENSITY = 20.0
46
- MAX_INTENSITY = 2048.0
47
- WINDOW_DIVISOR = 8 # window = num_images // 8, matching ana_all_mutation_log_scale.py
48
-
49
- VALID_AA = set("ACDEFGHIKLMNPQRSTVWY")
50
-
51
- # CondenSeq is a fixed-length library: all 14,578 training sequences are exactly
52
- # 66 residues. Anything else is off-distribution, so the demo requires this length
53
- # rather than silently padding or cropping.
54
- SEQUENCE_LENGTH = 66
55
-
56
- # Generation starts from a random latent, so the curve moves a little between runs.
57
- # The offline scripts fixed this at 6; keeping the same default makes the demo's
58
- # numbers repeatable and comparable to them.
59
- DEFAULT_SEED = 6
60
-
61
- # Fixed sampling settings. The concentration ladder length and ODE step count match
62
- # the offline runs, so demo numbers stay comparable to the published ones.
63
- NUM_IMAGES = 512
64
- NUM_STEPS = 100
65
- BATCH_SIZE = 64
66
-
67
-
68
- def resolve_weights(filename: str) -> str:
69
- """Local directory if CELLFM_LOCAL_WEIGHTS is set, else pull from the model repo."""
70
- if LOCAL_WEIGHTS:
71
- path = os.path.join(LOCAL_WEIGHTS, os.path.basename(filename))
72
- if not os.path.exists(path):
73
- raise FileNotFoundError(f"{path} not found (CELLFM_LOCAL_WEIGHTS={LOCAL_WEIGHTS})")
74
- return path
75
-
76
- from huggingface_hub import hf_hub_download
77
-
78
- return hf_hub_download(repo_id=MODEL_REPO, filename=filename)
79
-
80
-
81
- def generator_config() -> CELLFMConfig:
82
- """Hyperparameters from scripts/cell_fm_cs/evaluate_seq2img.sh."""
83
- return CELLFMConfig(
84
- img_resize=160,
85
- img_crop_size=160,
86
- img_type="GFP",
87
- cell_image="nucl",
88
- seq_zero_mask_ratio=0.0,
89
- path_type="Linear",
90
- prediction="velocity",
91
- # VAE
92
- num_down_blocks=3,
93
- latent_channels=4,
94
- vae_block_out_channels="128,256,512",
95
- # CELL-FM
96
- img_mask_ratio=0,
97
- cond_out_channels="32,64",
98
- sample_size=40,
99
- esm_embedding="esmc_600m",
100
- encoder_hidden_size=1152,
101
- max_protein_sequence_len=2048,
102
- encoder_num_hidden_layers=4,
103
- num_heads=8,
104
- dim_head=64,
105
- dropout=0,
106
- final_dropout=0,
107
- encoder_patch_size=4,
108
- # image generator
109
- img_generator_num_layers=4,
110
- img_generator_patch_size=2,
111
- attention_head_dim=64,
112
- num_attention_heads=8,
113
- # image decoder
114
- img_decoder_num_hidden_layers=2,
115
- img_decoder_hidden_size=512,
116
- img_decoder_num_heads=8,
117
- img_decoder_dim_head=64,
118
- cell_image_ratio=0.5,
119
- # checkpoints
120
- vae_loadcheck_path=resolve_weights(VAE_WEIGHTS),
121
- loadcheck_path=resolve_weights(GENERATOR_WEIGHTS),
122
- infer=True,
123
- )
124
-
125
-
126
- def classifier_config() -> ViTConfig:
127
- """Hyperparameters from scripts/vit_cls_condenseq_img/pretrain.sh."""
128
- return ViTConfig(
129
- image_size=160,
130
- in_channels=2,
131
- patch_size=4,
132
- num_layers=8,
133
- num_heads=8,
134
- hidden_dim=512,
135
- mlp_dim=2048,
136
- num_classes=2,
137
- loadcheck_path=resolve_weights(CLASSIFIER_WEIGHTS),
138
- infer=True,
139
- )
140
-
141
-
142
- def get_device() -> torch.device:
143
- return torch.device("cuda" if torch.cuda.is_available() else "cpu")
144
-
145
-
146
- @lru_cache(maxsize=1)
147
- def load_models():
148
- """Download the weights and build both models, on CPU.
149
-
150
- Kept off the GPU deliberately: under ZeroGPU a CUDA device only exists inside a
151
- @spaces.GPU call, and the 2.1 GB download plus model construction would eat that
152
- budget. Call this once at startup, then models_on(device) inside the GPU call.
153
- """
154
- generator = CELLFMCSModel(config=generator_config(), loss_fn=UniDiffCriterions)
155
- generator.eval()
156
-
157
- classifier = ViTModel(config=classifier_config())
158
- classifier.eval()
159
-
160
- from esm.tokenization.sequence_tokenizer import EsmSequenceTokenizer
161
-
162
- return generator, classifier, EsmSequenceTokenizer()
163
-
164
-
165
- def models_on(device):
166
- """Move the cached models to device. A no-op once they are already there."""
167
- generator, classifier, vocab = load_models()
168
- return generator.to(device), classifier.to(device), vocab
169
-
170
-
171
- @lru_cache(maxsize=1)
172
- def reference_nucleus() -> torch.Tensor:
173
- """The DAPI channel every generated image is conditioned on, as (1, 1, 160, 160) in [-1, 1].
174
-
175
- Taken from CondenSeq protein index 12626, image 0 -- the same one the offline
176
- seq2img runs used, so demo curves are comparable to the published ones.
177
- """
178
- arr = np.load(os.path.join(HERE, "assets", "reference_nucleus.npy"))
179
- return torch.from_numpy(arr).float().unsqueeze(0)
180
-
181
-
182
- def intensity_ladder(num_images: int) -> torch.Tensor:
183
- """Log-spaced protein intensity levels, the x axis of the titration curve."""
184
- return torch.logspace(
185
- start=float(np.log10(MIN_INTENSITY)),
186
- end=float(np.log10(MAX_INTENSITY)),
187
- steps=num_images,
188
- )
189
-
190
-
191
- def clean_sequence(sequence: str) -> str:
192
- """Strip FASTA headers, whitespace and case; reject anything not a standard residue."""
193
- lines = [ln for ln in str(sequence).splitlines() if not ln.startswith(">")]
194
- seq = "".join(lines).strip().upper()
195
- seq = "".join(seq.split())
196
-
197
- if not seq:
198
- raise ValueError("Enter a protein sequence.")
199
- bad = sorted(set(seq) - VALID_AA)
200
- if bad:
201
- raise ValueError(
202
- f"Sequence contains non-standard residues: {', '.join(bad)}. "
203
- "Use the 20 standard amino acids."
204
- )
205
- if len(seq) != SEQUENCE_LENGTH:
206
- raise ValueError(
207
- f"Sequence is {len(seq)} residues; CELL-FM CondenSeq takes exactly "
208
- f"{SEQUENCE_LENGTH}. The whole training library is {SEQUENCE_LENGTH}-mers, "
209
- "so other lengths are outside what the model has seen."
210
- )
211
- return seq
212
-
213
-
214
- @dataclass
215
- class Result:
216
- sequence: str
217
- intensities: np.ndarray # (N,) protein intensity levels
218
- predictions: np.ndarray # (N,) 0 = diffuse, 1 = condensed
219
- curve: np.ndarray # (N,) moving-averaged condensate probability
220
- window: int
221
- auc: float # area under the curve
222
- aac: float # area above the curve (reentrant dissolution)
223
- no_reentrant_auc: float
224
- c_sat: float
225
- images: np.ndarray = field(repr=False, default=None) # (K, 160, 160) sample panel
226
- image_intensities: np.ndarray = field(repr=False, default=None)
227
-
228
-
229
- @torch.no_grad()
230
- def generate_images(sequence, num_images, num_steps, batch_size, seed=DEFAULT_SEED, progress=None):
231
- """Stage 1: one generated image per intensity level, returned as uint16 (N, 2, 160, 160).
232
-
233
- uint16 is not incidental -- the offline pipeline wrote a TIFF between generation
234
- and classification, so the classifier saw quantised pixels. Keeping the same
235
- round-trip here keeps demo numbers comparable to the published ones.
236
- """
237
- device = get_device()
238
- generator, _, vocab = models_on(device)
239
-
240
- from esm.utils import encoding
241
-
242
- if seed is not None:
243
- torch.manual_seed(int(seed))
244
- if torch.cuda.is_available():
245
- torch.cuda.manual_seed_all(int(seed))
246
-
247
- tokens = encoding.tokenize_sequence(sequence, vocab, True).unsqueeze(0).to(device)
248
- nucleus = reference_nucleus().to(device)
249
- levels = intensity_ladder(num_images).to(device)
250
-
251
- out = []
252
- for start in range(0, num_images, batch_size):
253
- end = min(start + batch_size, num_images)
254
- n = end - start
255
-
256
- if progress is not None:
257
- progress(start / num_images, desc=f"Generating images {start}-{end} of {num_images}")
258
-
259
- sample = generator.sequence_to_image(
260
- tokens.repeat(n, 1),
261
- nucleus.repeat(n, 1, 1, 1),
262
- levels[start:end].unsqueeze(1),
263
- num_steps=num_steps,
264
- )
265
-
266
- # channel 0 = nucleus (conditioning), channel 1 = generated protein
267
- combined = torch.cat([nucleus.repeat(n, 1, 1, 1), sample], dim=1)
268
- combined = ((combined + 1) / 2.0).clamp(0.0, 1.0)
269
- out.append((combined * 65535).cpu().numpy().astype(np.uint16))
270
-
271
- return np.concatenate(out, axis=0)
272
-
273
-
274
- @torch.no_grad()
275
- def classify_images(images, batch_size, progress=None):
276
- """Stage 2: condensed (1) vs diffuse (0) for each generated image."""
277
- device = get_device()
278
- _, classifier, _ = models_on(device)
279
-
280
- preds = []
281
- for start in range(0, images.shape[0], batch_size):
282
- end = min(start + batch_size, images.shape[0])
283
-
284
- if progress is not None:
285
- progress(start / images.shape[0], desc=f"Classifying {start}-{end} of {images.shape[0]}")
286
-
287
- batch = torch.from_numpy(images[start:end].astype(np.float32)).to(device)
288
- batch = batch / 65535.0 * 2.0 - 1.0 # back to [-1, 1]
289
- logits = classifier.predict(batch)
290
- preds.append(torch.argmax(logits, dim=1).cpu().numpy())
291
-
292
- return np.concatenate(preds).astype(int)
293
-
294
-
295
- def summarise(intensities, predictions, num_images):
296
- """Stage 3: moving average, then AUC / AAC / c_sat over the smoothed curve."""
297
- df = pd.DataFrame(
298
- {"protein_intensity_level": intensities, "predicted_class": predictions}
299
- )
300
- window = max(1, num_images // WINDOW_DIVISOR)
301
- kw = dict(window_size=window, use_log_scale=True)
302
-
303
- return df, window, dict(
304
- curve=metrics.moving_average(predictions, window),
305
- auc=metrics.compute_area_under_curve(df, **kw),
306
- aac=metrics.compute_area_above_curve(df, **kw),
307
- no_reentrant_auc=metrics.compute_area_if_no_reentrant(df, **kw),
308
- c_sat=metrics.compute_concentration(df, window_size=window),
309
- )
310
-
311
-
312
- def sample_panel(images, intensities, k=6):
313
- """Pick k images spread evenly along the ladder, for the strip shown under the curve."""
314
- idx = np.linspace(0, len(intensities) - 1, k).astype(int)
315
- return images[idx, 1].astype(np.float32) / 65535.0, intensities[idx]
316
-
317
-
318
- def run(sequence, num_images=NUM_IMAGES, num_steps=NUM_STEPS, batch_size=BATCH_SIZE,
319
- seed=DEFAULT_SEED, progress=None) -> Result:
320
- """The whole pipeline: sequence in, titration curve and its areas out."""
321
- sequence = clean_sequence(sequence)
322
-
323
- images = generate_images(sequence, num_images, num_steps, batch_size, seed, progress)
324
- predictions = classify_images(images, batch_size, progress)
325
-
326
- intensities = intensity_ladder(num_images).numpy()
327
- _, window, stats = summarise(intensities, predictions, num_images)
328
- panel, panel_x = sample_panel(images, intensities)
329
-
330
- return Result(
331
- sequence=sequence,
332
- intensities=intensities,
333
- predictions=predictions,
334
- window=window,
335
- images=panel,
336
- image_intensities=panel_x,
337
- **stats,
338
- )