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.
@@ -0,0 +1,49 @@
1
+ """CellPPD-MOD 2.0 — cell-penetrating potential of modified peptides.
2
+
3
+ Four ways in, one import:
4
+
5
+ >>> from cellppdmod2 import predict_sequences, design
6
+ >>> predict_sequences(["GRKKRRQRRRPPQ", "{nt:Acetyl}GRKK{nnr:Aib}RRQRRR{ct:Amide}"])
7
+ >>> design("GRKKRRQRRRPPQ", mode="seq")
8
+
9
+ The sequence and design modules run on the models shipped with the
10
+ package. The chemical and structure modules additionally need a
11
+ PaDEL-Descriptor installation, and the structure module needs Open Babel;
12
+ see ``cellppdmod2 info`` for what the package has found.
13
+
14
+ Developed by Raghava's Group, Department of Computational Biology,
15
+ IIIT-Delhi.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ __version__ = "2.0.0"
21
+ __author__ = "Raghava's Group, IIIT-Delhi"
22
+
23
+ from .chemical import predict_smiles, predict_smiles_file, read_smiles
24
+ from .core import ModelBundle, load_bundle, read_feature_list
25
+ from .design import design, design_modifications, design_substitutions
26
+ from .encoders import MODIFICATIONS, clean_sequence, encode, parse_peptide
27
+ from .sequence import predict_sequences, read_peptides
28
+ from .structure import find_pdb_files, predict_structures
29
+
30
+ __all__ = [
31
+ "__version__",
32
+ "ModelBundle",
33
+ "MODIFICATIONS",
34
+ "clean_sequence",
35
+ "design",
36
+ "design_modifications",
37
+ "design_substitutions",
38
+ "encode",
39
+ "find_pdb_files",
40
+ "load_bundle",
41
+ "parse_peptide",
42
+ "predict_sequences",
43
+ "predict_smiles",
44
+ "predict_smiles_file",
45
+ "predict_structures",
46
+ "read_feature_list",
47
+ "read_peptides",
48
+ "read_smiles",
49
+ ]
@@ -0,0 +1,6 @@
1
+ """Allow ``python -m cellppdmod2`` to run the command-line interface."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
@@ -0,0 +1,262 @@
1
+ """Chemical structure-based prediction: SMILES to CPP score.
2
+
3
+ The molecule is handed to PaDEL-Descriptor, the fingerprint bits the
4
+ model was trained on are selected from its output, and the XGBoost
5
+ chemical model scores them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import tempfile
11
+ from pathlib import Path
12
+ from typing import Iterable, Sequence
13
+
14
+ import pandas as pd
15
+
16
+ from . import padel, paths
17
+ from .core import ModelBundle, load_bundle
18
+
19
+ __all__ = ["predict_smiles", "predict_smiles_file", "read_smiles"]
20
+
21
+
22
+ def read_smiles(source: str | Path) -> pd.DataFrame:
23
+ """Read ``Input_ID`` / ``SMILES`` records from a file or directory.
24
+
25
+ Text, ``.smi`` and ``.smiles`` files hold one SMILES per line,
26
+ optionally followed by whitespace and a name. A CSV must carry a
27
+ SMILES column and may carry an identifier column.
28
+ """
29
+ path = Path(source).expanduser().resolve()
30
+
31
+ if path.is_dir():
32
+ files = sorted(path.glob("*.smi")) + sorted(path.glob("*.smiles"))
33
+
34
+ if not files:
35
+ raise ValueError(f"No .smi or .smiles files found in {path}")
36
+
37
+ records = []
38
+ for file_path in files:
39
+ records.extend(_read_lines(file_path, stem=file_path.stem))
40
+
41
+ if not records:
42
+ raise ValueError(f"No SMILES records found in {path}")
43
+
44
+ return pd.DataFrame(records)
45
+
46
+ if not path.is_file():
47
+ raise FileNotFoundError(f"Input file not found: {path}")
48
+
49
+ suffix = path.suffix.lower()
50
+
51
+ if suffix == ".csv":
52
+ frame = pd.read_csv(path)
53
+
54
+ smiles_column = _pick(frame.columns, {"smiles", "smi", "canonical_smiles"})
55
+ if smiles_column is None:
56
+ raise ValueError(f"{path.name} must contain a SMILES column.")
57
+
58
+ id_column = _pick(frame.columns, {"id", "name", "molecule", "molecule_id"})
59
+
60
+ return pd.DataFrame(
61
+ {
62
+ "Input_ID": (
63
+ frame[id_column].astype(str)
64
+ if id_column
65
+ else [f"mol_{i + 1}" for i in range(len(frame))]
66
+ ),
67
+ "SMILES": frame[smiles_column].astype(str),
68
+ }
69
+ )
70
+
71
+ if suffix not in {".txt", ".smi", ".smiles"}:
72
+ raise ValueError(
73
+ "Input must be .txt, .smi, .smiles, a CSV with a SMILES column, "
74
+ "or a directory of .smi files."
75
+ )
76
+
77
+ records = _read_lines(path, stem="mol")
78
+
79
+ if not records:
80
+ raise ValueError(f"No SMILES records found in {path}")
81
+
82
+ return pd.DataFrame(records)
83
+
84
+
85
+ def predict_smiles(
86
+ smiles: Iterable[str] | Iterable[tuple[str, str]],
87
+ *,
88
+ model: str | Path | ModelBundle | None = None,
89
+ feature_list: str | Path | None = None,
90
+ threshold: float | None = None,
91
+ padel_jar: str | Path | None = None,
92
+ java: str | None = None,
93
+ descriptor_types: str | Path | None = None,
94
+ padel_extra: Sequence[str] = (),
95
+ fingerprints_out: str | Path | None = None,
96
+ quiet: bool = False,
97
+ ) -> pd.DataFrame:
98
+ """Score SMILES strings given in memory."""
99
+ records = []
100
+
101
+ for position, item in enumerate(smiles, start=1):
102
+ if isinstance(item, (tuple, list)):
103
+ identifier, text = str(item[0]), str(item[1])
104
+ else:
105
+ identifier, text = f"mol_{position}", str(item)
106
+ records.append({"Input_ID": identifier, "SMILES": text.strip()})
107
+
108
+ if not records:
109
+ raise ValueError("No SMILES were given.")
110
+
111
+ frame = pd.DataFrame(records)
112
+
113
+ with tempfile.TemporaryDirectory(prefix="cellppdmod2_smiles_") as temporary:
114
+ smi_path = Path(temporary) / "input.smi"
115
+ smi_path.write_text(
116
+ "\n".join(
117
+ f"{row.SMILES}\t{row.Input_ID}" for row in frame.itertuples()
118
+ )
119
+ + "\n",
120
+ encoding="utf-8",
121
+ )
122
+
123
+ return _predict(
124
+ molecules=smi_path,
125
+ metadata=frame,
126
+ model=model,
127
+ feature_list=feature_list,
128
+ threshold=threshold,
129
+ padel_jar=padel_jar,
130
+ java=java,
131
+ descriptor_types=descriptor_types,
132
+ padel_extra=padel_extra,
133
+ fingerprints_out=fingerprints_out,
134
+ quiet=quiet,
135
+ )
136
+
137
+
138
+ def predict_smiles_file(
139
+ source: str | Path,
140
+ **kwargs,
141
+ ) -> pd.DataFrame:
142
+ """Score every SMILES in a file or directory."""
143
+ metadata = read_smiles(source)
144
+ return _predict(molecules=Path(source), metadata=metadata, **kwargs)
145
+
146
+
147
+ def _predict(
148
+ *,
149
+ molecules: Path,
150
+ metadata: pd.DataFrame,
151
+ model: str | Path | ModelBundle | None = None,
152
+ feature_list: str | Path | None = None,
153
+ threshold: float | None = None,
154
+ padel_jar: str | Path | None = None,
155
+ java: str | None = None,
156
+ descriptor_types: str | Path | None = None,
157
+ padel_extra: Sequence[str] = (),
158
+ fingerprints_out: str | Path | None = None,
159
+ quiet: bool = False,
160
+ ) -> pd.DataFrame:
161
+ # Resolve the external tools first: they are the cheapest checks and the
162
+ # likeliest thing to be missing, so a bad setup is reported before the
163
+ # model is unpickled.
164
+ jar = paths.find_padel_jar(padel_jar)
165
+ java_command = padel.java_executable(java)
166
+
167
+ if isinstance(model, ModelBundle):
168
+ bundle = model
169
+ if threshold is not None:
170
+ bundle.threshold = float(threshold)
171
+ else:
172
+ bundle = load_bundle(
173
+ model or paths.CHEMICAL_MODEL,
174
+ feature_list if feature_list is not None else paths.CHEMICAL_FEATURES,
175
+ threshold=threshold,
176
+ )
177
+
178
+ with tempfile.TemporaryDirectory(prefix="cellppdmod2_fp_") as temporary:
179
+ fingerprint_csv = Path(temporary) / "padel_fingerprints.csv"
180
+
181
+ padel.run_padel(
182
+ molecules,
183
+ fingerprint_csv,
184
+ padel_jar=jar,
185
+ java=java_command,
186
+ descriptor_types=descriptor_types,
187
+ extra_flags=padel_extra,
188
+ quiet=quiet,
189
+ )
190
+
191
+ fingerprints = padel.read_fingerprints(fingerprint_csv)
192
+
193
+ if fingerprints_out:
194
+ destination = Path(fingerprints_out).expanduser().resolve()
195
+ destination.parent.mkdir(parents=True, exist_ok=True)
196
+ fingerprints.to_csv(destination, index=False)
197
+ if not quiet:
198
+ print(f"Full fingerprint table saved to {destination}")
199
+
200
+ if "Name" in fingerprints.columns:
201
+ fingerprints = fingerprints.rename(columns={"Name": "Input_ID"})
202
+
203
+ scores = bundle.score(fingerprints)
204
+
205
+ identifiers = (
206
+ fingerprints["Input_ID"].astype(str)
207
+ if "Input_ID" in fingerprints.columns
208
+ else pd.Series([f"mol_{i + 1}" for i in range(len(fingerprints))])
209
+ )
210
+
211
+ results = pd.DataFrame(
212
+ {
213
+ "Input_ID": identifiers.reset_index(drop=True),
214
+ "CPP_score": scores,
215
+ "Threshold": bundle.threshold,
216
+ }
217
+ )
218
+
219
+ results["Predicted_label"] = (results["CPP_score"] >= bundle.threshold).astype(int)
220
+ results["Prediction"] = results["Predicted_label"].map({1: "CPP", 0: "Non-CPP"})
221
+
222
+ if not metadata.empty and {"Input_ID", "SMILES"} <= set(metadata.columns):
223
+ results = results.merge(
224
+ metadata.drop_duplicates("Input_ID"), on="Input_ID", how="left"
225
+ )
226
+ order = [
227
+ "Input_ID",
228
+ "SMILES",
229
+ "CPP_score",
230
+ "Threshold",
231
+ "Predicted_label",
232
+ "Prediction",
233
+ ]
234
+ results = results[[name for name in order if name in results.columns]]
235
+
236
+ return results
237
+
238
+
239
+ def _read_lines(path: Path, stem: str) -> list[dict]:
240
+ records = []
241
+
242
+ for number, line in enumerate(
243
+ path.read_text(encoding="utf-8").splitlines(), start=1
244
+ ):
245
+ line = line.strip()
246
+
247
+ if not line or line.startswith("#"):
248
+ continue
249
+
250
+ parts = line.split()
251
+ records.append(
252
+ {
253
+ "Input_ID": parts[1] if len(parts) > 1 else f"{stem}_{number}",
254
+ "SMILES": parts[0],
255
+ }
256
+ )
257
+
258
+ return records
259
+
260
+
261
+ def _pick(columns, wanted: set[str]) -> str | None:
262
+ return next((name for name in columns if str(name).strip().lower() in wanted), None)