cellppdmod2 2.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cellppdmod2/__init__.py +49 -0
- cellppdmod2/__main__.py +6 -0
- cellppdmod2/chemical.py +262 -0
- cellppdmod2/cli.py +425 -0
- cellppdmod2/core.py +255 -0
- cellppdmod2/data/chemical_features.csv +428 -0
- cellppdmod2/data/chemical_model.joblib +0 -0
- cellppdmod2/data/descriptors.xml +78 -0
- cellppdmod2/data/sequence_model.joblib +0 -0
- cellppdmod2/data/structure_features.csv +428 -0
- cellppdmod2/data/structure_model.joblib +0 -0
- cellppdmod2/design.py +211 -0
- cellppdmod2/encoders.py +224 -0
- cellppdmod2/padel.py +197 -0
- cellppdmod2/paths.py +176 -0
- cellppdmod2/sequence.py +202 -0
- cellppdmod2/structure.py +201 -0
- cellppdmod2-2.0.0.dist-info/METADATA +403 -0
- cellppdmod2-2.0.0.dist-info/RECORD +23 -0
- cellppdmod2-2.0.0.dist-info/WHEEL +5 -0
- cellppdmod2-2.0.0.dist-info/entry_points.txt +6 -0
- cellppdmod2-2.0.0.dist-info/licenses/LICENSE +42 -0
- cellppdmod2-2.0.0.dist-info/top_level.txt +1 -0
cellppdmod2/cli.py
ADDED
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
"""Command-line interface for CellPPD-MOD 2.0.
|
|
2
|
+
|
|
3
|
+
One command with four prediction and design subcommands::
|
|
4
|
+
|
|
5
|
+
cellppdmod2 sequence -i peptides.txt -o out.csv
|
|
6
|
+
cellppdmod2 chemical -i molecules.smi -o out.csv
|
|
7
|
+
cellppdmod2 structure -i peptide.pdb -o out.csv
|
|
8
|
+
cellppdmod2 design -s GRKKRRQRRRPPQ -o out.csv --mode seq
|
|
9
|
+
cellppdmod2 info
|
|
10
|
+
|
|
11
|
+
Each subcommand is also installed under its own name, so
|
|
12
|
+
``cellppdmod2-sequence`` and the rest behave like the scripts in the
|
|
13
|
+
original standalone archive.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import sys
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
import pandas as pd
|
|
23
|
+
|
|
24
|
+
from . import __version__, chemical, encoders, paths, sequence, structure
|
|
25
|
+
|
|
26
|
+
# ``cellppdmod2.design`` is the design *function* at package level, because
|
|
27
|
+
# that is the documented API. The module is imported under its own name here.
|
|
28
|
+
from .design import MODES as DESIGN_MODES
|
|
29
|
+
from .design import design as run_design
|
|
30
|
+
|
|
31
|
+
MAX_PREVIEW_ROWS = 15
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
# ----------------------------------------------------------------------
|
|
35
|
+
# shared arguments
|
|
36
|
+
# ----------------------------------------------------------------------
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _add_common(parser: argparse.ArgumentParser, default_output: str) -> None:
|
|
40
|
+
parser.add_argument(
|
|
41
|
+
"-o",
|
|
42
|
+
"--output",
|
|
43
|
+
default=default_output,
|
|
44
|
+
help=f"Output CSV (default: {default_output}).",
|
|
45
|
+
)
|
|
46
|
+
parser.add_argument(
|
|
47
|
+
"--model",
|
|
48
|
+
default=None,
|
|
49
|
+
help="Trained .joblib model. Defaults to the model shipped with the package.",
|
|
50
|
+
)
|
|
51
|
+
parser.add_argument(
|
|
52
|
+
"-t",
|
|
53
|
+
"--threshold",
|
|
54
|
+
type=float,
|
|
55
|
+
default=None,
|
|
56
|
+
help=(
|
|
57
|
+
"Classification threshold. Defaults to the value stored in the "
|
|
58
|
+
"model (0.54 for the sequence model)."
|
|
59
|
+
),
|
|
60
|
+
)
|
|
61
|
+
parser.add_argument(
|
|
62
|
+
"-q",
|
|
63
|
+
"--quiet",
|
|
64
|
+
action="store_true",
|
|
65
|
+
help="Write the CSV without printing progress or a result preview.",
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _add_padel(parser: argparse.ArgumentParser) -> None:
|
|
70
|
+
parser.add_argument(
|
|
71
|
+
"--padel-jar",
|
|
72
|
+
default=None,
|
|
73
|
+
help=(
|
|
74
|
+
"PaDEL-Descriptor.jar. Defaults to the padel/ directory of the "
|
|
75
|
+
f"repository or ${paths.ENV_PADEL_JAR}."
|
|
76
|
+
),
|
|
77
|
+
)
|
|
78
|
+
parser.add_argument("--java", default=None, help="Java executable (default: java).")
|
|
79
|
+
parser.add_argument(
|
|
80
|
+
"--descriptortypes",
|
|
81
|
+
default=None,
|
|
82
|
+
help=(
|
|
83
|
+
"PaDEL descriptor-type XML. Defaults to the configuration the "
|
|
84
|
+
"models were trained with; change it only to reproduce a "
|
|
85
|
+
"different training set-up."
|
|
86
|
+
),
|
|
87
|
+
)
|
|
88
|
+
parser.add_argument(
|
|
89
|
+
"--feature-list",
|
|
90
|
+
default=None,
|
|
91
|
+
help="CSV of selected feature names, overriding the packaged list.",
|
|
92
|
+
)
|
|
93
|
+
parser.add_argument(
|
|
94
|
+
"--fingerprints-out",
|
|
95
|
+
default=None,
|
|
96
|
+
help="Also write the full PaDEL fingerprint table here.",
|
|
97
|
+
)
|
|
98
|
+
parser.add_argument(
|
|
99
|
+
"--padel-extra",
|
|
100
|
+
nargs="*",
|
|
101
|
+
default=[],
|
|
102
|
+
help="Extra PaDEL flags. Use only settings matching the trained model.",
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
# ----------------------------------------------------------------------
|
|
107
|
+
# parser
|
|
108
|
+
# ----------------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
112
|
+
parser = argparse.ArgumentParser(
|
|
113
|
+
prog="cellppdmod2",
|
|
114
|
+
description=(
|
|
115
|
+
"CellPPD-MOD 2.0: predict the cell-penetrating potential of "
|
|
116
|
+
"peptides containing natural, chemically modified and "
|
|
117
|
+
"non-natural residues."
|
|
118
|
+
),
|
|
119
|
+
epilog="Raghava's Group, Department of Computational Biology, IIIT-Delhi.",
|
|
120
|
+
)
|
|
121
|
+
parser.add_argument("-v", "--version", action="version", version=f"cellppdmod2 {__version__}")
|
|
122
|
+
|
|
123
|
+
subparsers = parser.add_subparsers(dest="command", metavar="<command>")
|
|
124
|
+
|
|
125
|
+
# ---- sequence ----
|
|
126
|
+
seq = subparsers.add_parser(
|
|
127
|
+
"sequence",
|
|
128
|
+
help="Predict from peptide sequences (MAP or natural one-letter).",
|
|
129
|
+
description=(
|
|
130
|
+
"Sequence-based prediction. Each peptide becomes 400 dipeptide "
|
|
131
|
+
"frequencies, six modification flags and its length, and is "
|
|
132
|
+
"scored by the Extra Trees sequence model."
|
|
133
|
+
),
|
|
134
|
+
)
|
|
135
|
+
source = seq.add_mutually_exclusive_group(required=True)
|
|
136
|
+
source.add_argument(
|
|
137
|
+
"-i", "--input", help="Text file of peptides, one per line, or a CSV."
|
|
138
|
+
)
|
|
139
|
+
source.add_argument(
|
|
140
|
+
"-s", "--sequence", nargs="+", help="One or more peptides given on the command line."
|
|
141
|
+
)
|
|
142
|
+
seq.add_argument(
|
|
143
|
+
"-m",
|
|
144
|
+
"--modifications",
|
|
145
|
+
default="",
|
|
146
|
+
help=(
|
|
147
|
+
"Comma-separated categories applied to every peptide in the run "
|
|
148
|
+
f"({', '.join(encoders.MODIFICATIONS)}). Use this for plain "
|
|
149
|
+
"sequences whose modifications are not written as tags."
|
|
150
|
+
),
|
|
151
|
+
)
|
|
152
|
+
seq.add_argument(
|
|
153
|
+
"--strict-tags",
|
|
154
|
+
action="store_true",
|
|
155
|
+
help="Fail on a brace tag outside the six known categories.",
|
|
156
|
+
)
|
|
157
|
+
seq.add_argument(
|
|
158
|
+
"--full",
|
|
159
|
+
action="store_true",
|
|
160
|
+
help="Keep every column, including the per-category Yes/No flags.",
|
|
161
|
+
)
|
|
162
|
+
_add_common(seq, "sequence_predictions.csv")
|
|
163
|
+
seq.set_defaults(handler=_run_sequence)
|
|
164
|
+
|
|
165
|
+
# ---- chemical ----
|
|
166
|
+
chem = subparsers.add_parser(
|
|
167
|
+
"chemical",
|
|
168
|
+
help="Predict from SMILES, via PaDEL fingerprints.",
|
|
169
|
+
description=(
|
|
170
|
+
"Chemical structure-based prediction. PaDEL-Descriptor computes "
|
|
171
|
+
"molecular fingerprints from SMILES and the XGBoost chemical "
|
|
172
|
+
"model scores the selected bits."
|
|
173
|
+
),
|
|
174
|
+
)
|
|
175
|
+
chem_source = chem.add_mutually_exclusive_group(required=True)
|
|
176
|
+
chem_source.add_argument(
|
|
177
|
+
"-i", "--input", help=".smi, .smiles, .txt, CSV, or a directory of .smi files."
|
|
178
|
+
)
|
|
179
|
+
chem_source.add_argument(
|
|
180
|
+
"-s", "--smiles", nargs="+", help="One or more SMILES given on the command line."
|
|
181
|
+
)
|
|
182
|
+
_add_common(chem, "chemical_predictions.csv")
|
|
183
|
+
_add_padel(chem)
|
|
184
|
+
chem.set_defaults(handler=_run_chemical)
|
|
185
|
+
|
|
186
|
+
# ---- structure ----
|
|
187
|
+
struct = subparsers.add_parser(
|
|
188
|
+
"structure",
|
|
189
|
+
help="Predict from PDB structures, via Open Babel and PaDEL.",
|
|
190
|
+
description=(
|
|
191
|
+
"Tertiary structure-based prediction. Structures are converted "
|
|
192
|
+
"to SDF with Open Babel, PaDEL computes fingerprints, and the "
|
|
193
|
+
"XGBoost structure model scores the selected bits."
|
|
194
|
+
),
|
|
195
|
+
)
|
|
196
|
+
struct.add_argument(
|
|
197
|
+
"-i",
|
|
198
|
+
"--input",
|
|
199
|
+
required=True,
|
|
200
|
+
help="A .pdb/.ent file or a directory of them.",
|
|
201
|
+
)
|
|
202
|
+
struct.add_argument(
|
|
203
|
+
"--obabel", default=None, help="Open Babel executable (default: obabel)."
|
|
204
|
+
)
|
|
205
|
+
struct.add_argument(
|
|
206
|
+
"--sdf-dir",
|
|
207
|
+
default=None,
|
|
208
|
+
help="Keep the converted SDF files here instead of discarding them.",
|
|
209
|
+
)
|
|
210
|
+
_add_common(struct, "structure_predictions.csv")
|
|
211
|
+
_add_padel(struct)
|
|
212
|
+
struct.set_defaults(handler=_run_structure)
|
|
213
|
+
|
|
214
|
+
# ---- design ----
|
|
215
|
+
des = subparsers.add_parser(
|
|
216
|
+
"design",
|
|
217
|
+
help="Generate and rank analogues of one peptide.",
|
|
218
|
+
description=(
|
|
219
|
+
"Peptide design. seq generates every single-amino-acid "
|
|
220
|
+
"substitution (19 x L + 1 candidates); mod generates all 64 "
|
|
221
|
+
"combinations of the six modification flags."
|
|
222
|
+
),
|
|
223
|
+
)
|
|
224
|
+
des.add_argument(
|
|
225
|
+
"-s", "--sequence", required=True, help="One natural peptide, 2 to 50 residues."
|
|
226
|
+
)
|
|
227
|
+
des.add_argument(
|
|
228
|
+
"--mode",
|
|
229
|
+
default="seq",
|
|
230
|
+
choices=list(DESIGN_MODES),
|
|
231
|
+
help="seq for substitutions, mod for modification combinations.",
|
|
232
|
+
)
|
|
233
|
+
_add_common(des, "design_results.csv")
|
|
234
|
+
des.set_defaults(handler=_run_design)
|
|
235
|
+
|
|
236
|
+
# ---- info ----
|
|
237
|
+
info = subparsers.add_parser(
|
|
238
|
+
"info",
|
|
239
|
+
help="Show the resolved model, data and PaDEL locations.",
|
|
240
|
+
description="Report where the package is reading its models and tools from.",
|
|
241
|
+
)
|
|
242
|
+
info.set_defaults(handler=_run_info)
|
|
243
|
+
|
|
244
|
+
return parser
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
# ----------------------------------------------------------------------
|
|
248
|
+
# handlers
|
|
249
|
+
# ----------------------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _run_sequence(args: argparse.Namespace) -> int:
|
|
253
|
+
modifications = [
|
|
254
|
+
item.strip().lower() for item in args.modifications.split(",") if item.strip()
|
|
255
|
+
]
|
|
256
|
+
|
|
257
|
+
peptides = (
|
|
258
|
+
sequence.read_peptides(args.input)
|
|
259
|
+
if args.input
|
|
260
|
+
else [(f"peptide_{i}", text) for i, text in enumerate(args.sequence, start=1)]
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
results = sequence.predict_sequences(
|
|
264
|
+
peptides,
|
|
265
|
+
model=args.model,
|
|
266
|
+
threshold=args.threshold,
|
|
267
|
+
modifications=modifications,
|
|
268
|
+
strict_tags=args.strict_tags,
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
if not args.full:
|
|
272
|
+
keep = [name for name in sequence.DEFAULT_COLUMNS if name in results.columns]
|
|
273
|
+
unknown = results.get("Unrecognised_tags")
|
|
274
|
+
if unknown is not None and unknown.astype(str).str.strip().any():
|
|
275
|
+
keep.insert(len(keep) - 4, "Unrecognised_tags")
|
|
276
|
+
results = results[keep]
|
|
277
|
+
|
|
278
|
+
return _finish(results, args, "Sequence prediction")
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _run_chemical(args: argparse.Namespace) -> int:
|
|
282
|
+
common = dict(
|
|
283
|
+
model=args.model,
|
|
284
|
+
feature_list=args.feature_list,
|
|
285
|
+
threshold=args.threshold,
|
|
286
|
+
padel_jar=args.padel_jar,
|
|
287
|
+
java=args.java,
|
|
288
|
+
descriptor_types=args.descriptortypes,
|
|
289
|
+
padel_extra=args.padel_extra,
|
|
290
|
+
fingerprints_out=args.fingerprints_out,
|
|
291
|
+
quiet=args.quiet,
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
if args.input:
|
|
295
|
+
results = chemical.predict_smiles_file(args.input, **common)
|
|
296
|
+
else:
|
|
297
|
+
results = chemical.predict_smiles(args.smiles, **common)
|
|
298
|
+
|
|
299
|
+
return _finish(results, args, "Chemical prediction")
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _run_structure(args: argparse.Namespace) -> int:
|
|
303
|
+
results = structure.predict_structures(
|
|
304
|
+
args.input,
|
|
305
|
+
model=args.model,
|
|
306
|
+
feature_list=args.feature_list,
|
|
307
|
+
threshold=args.threshold,
|
|
308
|
+
padel_jar=args.padel_jar,
|
|
309
|
+
java=args.java,
|
|
310
|
+
obabel=args.obabel,
|
|
311
|
+
descriptor_types=args.descriptortypes,
|
|
312
|
+
padel_extra=args.padel_extra,
|
|
313
|
+
sdf_dir=args.sdf_dir,
|
|
314
|
+
fingerprints_out=args.fingerprints_out,
|
|
315
|
+
quiet=args.quiet,
|
|
316
|
+
)
|
|
317
|
+
|
|
318
|
+
return _finish(results, args, "Structure prediction")
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _run_design(args: argparse.Namespace) -> int:
|
|
322
|
+
results = run_design(
|
|
323
|
+
args.sequence,
|
|
324
|
+
args.mode,
|
|
325
|
+
model=args.model,
|
|
326
|
+
threshold=args.threshold,
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
return _finish(results, args, f"Design ({args.mode})")
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _run_info(args: argparse.Namespace) -> int:
|
|
333
|
+
print(f"cellppdmod2 {__version__}\n")
|
|
334
|
+
|
|
335
|
+
for label, value in paths.describe().items():
|
|
336
|
+
print(f" {label:<20} {value}")
|
|
337
|
+
|
|
338
|
+
print("\n dependencies")
|
|
339
|
+
for module in ("numpy", "pandas", "sklearn", "joblib", "xgboost"):
|
|
340
|
+
try:
|
|
341
|
+
imported = __import__(module)
|
|
342
|
+
print(f" {module:<20} {getattr(imported, '__version__', 'unknown')}")
|
|
343
|
+
except ImportError:
|
|
344
|
+
note = " (needed for chemical and structure prediction)" if module == "xgboost" else ""
|
|
345
|
+
print(f" {module:<20} not installed{note}")
|
|
346
|
+
|
|
347
|
+
return 0
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
# ----------------------------------------------------------------------
|
|
351
|
+
# output
|
|
352
|
+
# ----------------------------------------------------------------------
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _finish(results: pd.DataFrame, args: argparse.Namespace, title: str) -> int:
|
|
356
|
+
output = Path(args.output).expanduser().resolve()
|
|
357
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
358
|
+
results.to_csv(output, index=False)
|
|
359
|
+
|
|
360
|
+
if args.quiet:
|
|
361
|
+
return 0
|
|
362
|
+
|
|
363
|
+
print(f"\n{title}: {len(results)} row(s)")
|
|
364
|
+
|
|
365
|
+
if "Prediction" in results.columns:
|
|
366
|
+
positives = int((results["Prediction"] == "CPP").sum())
|
|
367
|
+
print(f"Predicted CPP: {positives} of {len(results)}")
|
|
368
|
+
|
|
369
|
+
if "Threshold" in results.columns and len(results):
|
|
370
|
+
print(f"Threshold: {results['Threshold'].iloc[0]}")
|
|
371
|
+
|
|
372
|
+
preview = results.head(MAX_PREVIEW_ROWS)
|
|
373
|
+
formatters = (
|
|
374
|
+
{"CPP_score": "{:.4f}".format} if "CPP_score" in results.columns else None
|
|
375
|
+
)
|
|
376
|
+
print()
|
|
377
|
+
print(preview.to_string(index=False, formatters=formatters))
|
|
378
|
+
|
|
379
|
+
if len(results) > MAX_PREVIEW_ROWS:
|
|
380
|
+
print(f"... {len(results) - MAX_PREVIEW_ROWS} more row(s) in the CSV")
|
|
381
|
+
|
|
382
|
+
print(f"\nSaved to {output}")
|
|
383
|
+
return 0
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
# ----------------------------------------------------------------------
|
|
387
|
+
# entry points
|
|
388
|
+
# ----------------------------------------------------------------------
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def main(argv: list[str] | None = None) -> int:
|
|
392
|
+
parser = build_parser()
|
|
393
|
+
args = parser.parse_args(argv)
|
|
394
|
+
|
|
395
|
+
if not getattr(args, "handler", None):
|
|
396
|
+
parser.print_help()
|
|
397
|
+
return 1
|
|
398
|
+
|
|
399
|
+
try:
|
|
400
|
+
return args.handler(args)
|
|
401
|
+
except KeyboardInterrupt:
|
|
402
|
+
print("\nInterrupted.", file=sys.stderr)
|
|
403
|
+
return 130
|
|
404
|
+
except Exception as error:
|
|
405
|
+
print(f"ERROR: {error}", file=sys.stderr)
|
|
406
|
+
return 1
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _subcommand(name: str):
|
|
410
|
+
def run(argv: list[str] | None = None) -> int:
|
|
411
|
+
return main([name, *(argv if argv is not None else sys.argv[1:])])
|
|
412
|
+
|
|
413
|
+
run.__name__ = f"main_{name}"
|
|
414
|
+
run.__doc__ = f"Entry point for the cellppdmod2-{name} command."
|
|
415
|
+
return run
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
main_sequence = _subcommand("sequence")
|
|
419
|
+
main_chemical = _subcommand("chemical")
|
|
420
|
+
main_structure = _subcommand("structure")
|
|
421
|
+
main_design = _subcommand("design")
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
if __name__ == "__main__":
|
|
425
|
+
raise SystemExit(main())
|
cellppdmod2/core.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""Model loading and scoring shared by every CellPPD-MOD 2.0 module.
|
|
2
|
+
|
|
3
|
+
The three trained models are stored as joblib bundles::
|
|
4
|
+
|
|
5
|
+
{"model": estimator, "features": [...], "threshold": float,
|
|
6
|
+
"scaler": optional, "standardize": bool, "model_name": str}
|
|
7
|
+
|
|
8
|
+
The sequence model is an Extra Trees classifier over 407 sequence
|
|
9
|
+
features; the chemical and structure models are XGBoost classifiers over
|
|
10
|
+
selected PaDEL fingerprint bits. This module hides those differences
|
|
11
|
+
behind one loader and one scoring function.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import warnings
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Sequence
|
|
20
|
+
|
|
21
|
+
import joblib
|
|
22
|
+
import numpy as np
|
|
23
|
+
import pandas as pd
|
|
24
|
+
|
|
25
|
+
__all__ = ["ModelBundle", "load_bundle", "read_feature_list", "positive_scores", "label_for"]
|
|
26
|
+
|
|
27
|
+
DEFAULT_THRESHOLD = 0.5
|
|
28
|
+
|
|
29
|
+
_FEATURE_KEYS = ("features", "feature_names", "selected_features", "feature_list")
|
|
30
|
+
_MODEL_KEYS = ("model", "estimator", "classifier")
|
|
31
|
+
_FEATURE_COLUMNS = {"feature", "features", "column", "columns", "feature_name"}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass
|
|
35
|
+
class ModelBundle:
|
|
36
|
+
"""A trained estimator together with everything needed to use it."""
|
|
37
|
+
|
|
38
|
+
model: Any
|
|
39
|
+
features: list[str]
|
|
40
|
+
threshold: float
|
|
41
|
+
scaler: Any = None
|
|
42
|
+
standardize: bool = False
|
|
43
|
+
name: str = ""
|
|
44
|
+
source: Path | None = None
|
|
45
|
+
|
|
46
|
+
def prepare(self, frame: pd.DataFrame) -> Any:
|
|
47
|
+
"""Order, validate and optionally scale a feature table."""
|
|
48
|
+
missing = [name for name in self.features if name not in frame.columns]
|
|
49
|
+
if missing:
|
|
50
|
+
raise ValueError(
|
|
51
|
+
f"{len(missing)} feature(s) required by the model are missing "
|
|
52
|
+
f"from the input table.\nExamples: {missing[:15]}"
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
ordered = frame.loc[:, self.features].apply(pd.to_numeric, errors="coerce")
|
|
56
|
+
|
|
57
|
+
if ordered.isna().any().any():
|
|
58
|
+
bad = ordered.columns[ordered.isna().any()].tolist()
|
|
59
|
+
raise ValueError(
|
|
60
|
+
f"Missing or non-numeric values in features: {bad[:20]}"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
if self.standardize or self.scaler is not None:
|
|
64
|
+
if self.scaler is None:
|
|
65
|
+
raise ValueError(
|
|
66
|
+
"The bundle asks for standardisation but carries no scaler."
|
|
67
|
+
)
|
|
68
|
+
return pd.DataFrame(
|
|
69
|
+
self.scaler.transform(ordered),
|
|
70
|
+
columns=self.features,
|
|
71
|
+
index=ordered.index,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
return ordered
|
|
75
|
+
|
|
76
|
+
def score(self, frame: pd.DataFrame) -> np.ndarray:
|
|
77
|
+
"""Positive-class probability for each row of ``frame``."""
|
|
78
|
+
return positive_scores(self.model, self.prepare(frame))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def load_bundle(
|
|
82
|
+
model_path: str | Path,
|
|
83
|
+
feature_list: str | Path | None = None,
|
|
84
|
+
*,
|
|
85
|
+
threshold: float | None = None,
|
|
86
|
+
) -> ModelBundle:
|
|
87
|
+
"""Load a joblib model bundle, or a bare estimator, into a ModelBundle."""
|
|
88
|
+
path = Path(model_path).expanduser().resolve()
|
|
89
|
+
|
|
90
|
+
if not path.is_file():
|
|
91
|
+
raise FileNotFoundError(f"Model file not found: {path}")
|
|
92
|
+
|
|
93
|
+
try:
|
|
94
|
+
with warnings.catch_warnings():
|
|
95
|
+
# scikit-learn warns loudly when the pickling version differs. The
|
|
96
|
+
# message is reported once, in readable form, not per estimator.
|
|
97
|
+
warnings.simplefilter("ignore")
|
|
98
|
+
bundle = joblib.load(path)
|
|
99
|
+
except ModuleNotFoundError as error:
|
|
100
|
+
missing = error.name or "a package"
|
|
101
|
+
|
|
102
|
+
if missing.split(".")[0] == "xgboost":
|
|
103
|
+
raise ModuleNotFoundError(
|
|
104
|
+
f"{path.name} is an XGBoost model, and xgboost is not installed.\n"
|
|
105
|
+
"The chemical and structure models need it; the sequence and "
|
|
106
|
+
"design models do not.\n\n"
|
|
107
|
+
' pip install "cellppdmod2[chem]"'
|
|
108
|
+
) from error
|
|
109
|
+
|
|
110
|
+
raise ModuleNotFoundError(
|
|
111
|
+
f"{path.name} was saved with {missing}, which is not installed here.\n"
|
|
112
|
+
f"Install it, then load the model again."
|
|
113
|
+
) from error
|
|
114
|
+
|
|
115
|
+
if isinstance(bundle, dict):
|
|
116
|
+
model = _first(bundle, _MODEL_KEYS)
|
|
117
|
+
features = _first(bundle, _FEATURE_KEYS)
|
|
118
|
+
scaler = bundle.get("scaler")
|
|
119
|
+
standardize = bool(bundle.get("standardize", scaler is not None))
|
|
120
|
+
stored_threshold = float(bundle.get("threshold", DEFAULT_THRESHOLD))
|
|
121
|
+
name = str(bundle.get("model_name", "") or "")
|
|
122
|
+
else:
|
|
123
|
+
model = bundle
|
|
124
|
+
features = getattr(bundle, "feature_names_in_", None)
|
|
125
|
+
scaler = None
|
|
126
|
+
standardize = False
|
|
127
|
+
stored_threshold = DEFAULT_THRESHOLD
|
|
128
|
+
name = type(bundle).__name__
|
|
129
|
+
|
|
130
|
+
if model is None:
|
|
131
|
+
raise ValueError(
|
|
132
|
+
f"{path.name} contains no estimator under "
|
|
133
|
+
"'model', 'estimator' or 'classifier'."
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
if feature_list is not None:
|
|
137
|
+
features = read_feature_list(feature_list)
|
|
138
|
+
elif features is None:
|
|
139
|
+
features = getattr(model, "feature_names_in_", None)
|
|
140
|
+
|
|
141
|
+
features = _normalise_features(features, path)
|
|
142
|
+
|
|
143
|
+
return ModelBundle(
|
|
144
|
+
model=model,
|
|
145
|
+
features=features,
|
|
146
|
+
threshold=stored_threshold if threshold is None else float(threshold),
|
|
147
|
+
scaler=scaler,
|
|
148
|
+
standardize=standardize,
|
|
149
|
+
name=name or type(model).__name__,
|
|
150
|
+
source=path,
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def read_feature_list(path: str | Path) -> list[str]:
|
|
155
|
+
"""Read selected feature names from a CSV.
|
|
156
|
+
|
|
157
|
+
Accepts a one-column file, or any file carrying a ``Feature`` column
|
|
158
|
+
(the format written by the model-selection step, which also stores the
|
|
159
|
+
mutual-information score beside each name).
|
|
160
|
+
"""
|
|
161
|
+
csv_path = Path(path).expanduser().resolve()
|
|
162
|
+
|
|
163
|
+
if not csv_path.is_file():
|
|
164
|
+
raise FileNotFoundError(f"Feature list not found: {csv_path}")
|
|
165
|
+
|
|
166
|
+
frame = pd.read_csv(csv_path)
|
|
167
|
+
|
|
168
|
+
column = next(
|
|
169
|
+
(name for name in frame.columns if str(name).strip().lower() in _FEATURE_COLUMNS),
|
|
170
|
+
None,
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
if column is None:
|
|
174
|
+
if frame.shape[1] != 1:
|
|
175
|
+
raise ValueError(
|
|
176
|
+
f"{csv_path.name} must have a 'Feature' column or exactly one column."
|
|
177
|
+
)
|
|
178
|
+
column = frame.columns[0]
|
|
179
|
+
|
|
180
|
+
names = frame[column].dropna().astype(str).str.strip().tolist()
|
|
181
|
+
|
|
182
|
+
if not names:
|
|
183
|
+
raise ValueError(f"{csv_path.name} lists no feature names.")
|
|
184
|
+
|
|
185
|
+
return names
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def positive_scores(model: Any, X: Any) -> np.ndarray:
|
|
189
|
+
"""Probability of the positive (CPP) class, whatever the estimator type."""
|
|
190
|
+
if hasattr(model, "predict_proba"):
|
|
191
|
+
probabilities = np.asarray(model.predict_proba(X))
|
|
192
|
+
|
|
193
|
+
if probabilities.ndim == 2 and probabilities.shape[1] >= 2:
|
|
194
|
+
classes = list(getattr(model, "classes_", []))
|
|
195
|
+
|
|
196
|
+
for positive in (1, "1", True):
|
|
197
|
+
if positive in classes:
|
|
198
|
+
return probabilities[:, classes.index(positive)]
|
|
199
|
+
|
|
200
|
+
return probabilities[:, 1]
|
|
201
|
+
|
|
202
|
+
return probabilities.reshape(-1)
|
|
203
|
+
|
|
204
|
+
if hasattr(model, "decision_function"):
|
|
205
|
+
decision = np.asarray(model.decision_function(X), dtype=float).reshape(-1)
|
|
206
|
+
decision = np.clip(decision, -700, 700)
|
|
207
|
+
return 1.0 / (1.0 + np.exp(-decision))
|
|
208
|
+
|
|
209
|
+
raise ValueError(
|
|
210
|
+
"The loaded model supports neither predict_proba() nor decision_function()."
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def label_for(scores: Sequence[float], threshold: float) -> np.ndarray:
|
|
215
|
+
"""CPP / Non-CPP labels for a vector of scores."""
|
|
216
|
+
scores = np.asarray(scores, dtype=float)
|
|
217
|
+
return np.where(scores >= threshold, "CPP", "Non-CPP")
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _first(bundle: dict, keys: tuple[str, ...]) -> Any:
|
|
221
|
+
for key in keys:
|
|
222
|
+
value = bundle.get(key)
|
|
223
|
+
if value is not None:
|
|
224
|
+
return value
|
|
225
|
+
return None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _normalise_features(features: Any, path: Path) -> list[str]:
|
|
229
|
+
if features is None:
|
|
230
|
+
raise ValueError(
|
|
231
|
+
f"{path.name} does not record its feature names, and no "
|
|
232
|
+
"--feature-list was given. The feature order cannot be guessed."
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
if isinstance(features, pd.DataFrame):
|
|
236
|
+
features = features.iloc[:, 0].tolist()
|
|
237
|
+
elif isinstance(features, pd.Series):
|
|
238
|
+
features = features.tolist()
|
|
239
|
+
elif isinstance(features, str):
|
|
240
|
+
raise ValueError(
|
|
241
|
+
f"{path.name} stores its feature list as a single string, not a list."
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
names = [str(name).strip() for name in list(features)]
|
|
245
|
+
|
|
246
|
+
if not names or any(not name for name in names):
|
|
247
|
+
raise ValueError(f"{path.name} contains an empty or invalid feature name.")
|
|
248
|
+
|
|
249
|
+
if len(names) != len(set(names)):
|
|
250
|
+
duplicates = sorted({name for name in names if names.count(name) > 1})
|
|
251
|
+
raise ValueError(
|
|
252
|
+
f"{path.name} lists duplicate feature names: {duplicates[:10]}"
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
return names
|