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,202 @@
1
+ """Sequence-based prediction: peptide in, cell-penetrating potential out.
2
+
3
+ Accepts MAP notation (modifications in curly braces inside the sequence)
4
+ or plain one-letter peptides, with the modification categories supplied
5
+ separately. Each peptide becomes 407 features and is scored by the
6
+ Extra Trees sequence model.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+ from typing import Iterable, Sequence
13
+
14
+ import pandas as pd
15
+
16
+ from . import encoders, paths
17
+ from .core import ModelBundle, load_bundle
18
+
19
+ __all__ = ["predict_sequences", "read_peptides", "DEFAULT_COLUMNS"]
20
+
21
+ DEFAULT_COLUMNS = [
22
+ "ID",
23
+ "Sequence",
24
+ "Cleaned_sequence",
25
+ "Length",
26
+ "Modifications",
27
+ "CPP_score",
28
+ "Threshold",
29
+ "Predicted_label",
30
+ "Prediction",
31
+ ]
32
+
33
+
34
+ def read_peptides(source: str | Path) -> list[tuple[str, str]]:
35
+ """Read ``(identifier, peptide)`` pairs from a text or CSV file.
36
+
37
+ A plain text file holds one peptide per line, optionally followed by
38
+ whitespace and an identifier. A CSV must carry a sequence-like column
39
+ and may carry an identifier column. Blank lines and ``#`` comments are
40
+ skipped; a FASTA header line is an error, matching the web form.
41
+ """
42
+ path = Path(source).expanduser().resolve()
43
+
44
+ if not path.is_file():
45
+ raise FileNotFoundError(f"Input file not found: {path}")
46
+
47
+ if path.suffix.lower() == ".csv":
48
+ frame = pd.read_csv(path)
49
+
50
+ sequence_column = _pick(
51
+ frame.columns, {"sequence", "peptide", "seq", "map", "peptides"}
52
+ )
53
+ if sequence_column is None:
54
+ raise ValueError(
55
+ f"{path.name} must contain a 'sequence' or 'peptide' column."
56
+ )
57
+
58
+ id_column = _pick(frame.columns, {"id", "name", "identifier", "peptide_id"})
59
+
60
+ records = []
61
+ for position, value in enumerate(frame[sequence_column].astype(str), start=1):
62
+ if not value.strip() or value.strip().lower() == "nan":
63
+ continue
64
+ identifier = (
65
+ str(frame[id_column].iloc[position - 1])
66
+ if id_column
67
+ else f"peptide_{position}"
68
+ )
69
+ records.append((identifier, value.strip()))
70
+
71
+ if not records:
72
+ raise ValueError(f"No peptides found in {path}.")
73
+
74
+ return records
75
+
76
+ records = []
77
+ for number, line in enumerate(
78
+ path.read_text(encoding="utf-8").splitlines(), start=1
79
+ ):
80
+ line = line.strip()
81
+
82
+ if not line or line.startswith("#"):
83
+ continue
84
+
85
+ if line.startswith(">"):
86
+ raise ValueError(
87
+ f"{path.name} line {number} is a FASTA header. Give one peptide "
88
+ "per line, with no '>' lines."
89
+ )
90
+
91
+ parts = line.split()
92
+ identifier = parts[1] if len(parts) > 1 else f"peptide_{number}"
93
+ records.append((identifier, parts[0]))
94
+
95
+ if not records:
96
+ raise ValueError(f"No peptides found in {path}.")
97
+
98
+ return records
99
+
100
+
101
+ def predict_sequences(
102
+ peptides: Iterable[str] | Iterable[tuple[str, str]],
103
+ *,
104
+ model: str | Path | ModelBundle | None = None,
105
+ threshold: float | None = None,
106
+ modifications: Sequence[str] | None = None,
107
+ strict_tags: bool = False,
108
+ ) -> pd.DataFrame:
109
+ """Score peptides and return one row per peptide.
110
+
111
+ Parameters
112
+ ----------
113
+ peptides:
114
+ Peptide strings, or ``(identifier, peptide)`` pairs.
115
+ model:
116
+ A loaded bundle, a path to one, or ``None`` for the packaged
117
+ sequence model.
118
+ threshold:
119
+ Overrides the threshold stored in the bundle (0.54 for the
120
+ released sequence model).
121
+ modifications:
122
+ Categories applied to every peptide in the batch, for plain
123
+ sequences whose modifications are not written as tags.
124
+ strict_tags:
125
+ Reject tags outside NT, CT, PTM, NNR, CYC and D instead of
126
+ recording them in the result.
127
+ """
128
+ bundle = _as_bundle(model, threshold)
129
+
130
+ records = _as_records(peptides)
131
+ extra = {marker.strip().lower() for marker in (modifications or ()) if marker.strip()}
132
+
133
+ rows: list[dict] = []
134
+ features: list[dict] = []
135
+
136
+ for identifier, raw in records:
137
+ parsed = encoders.parse_peptide(
138
+ raw, extra_modifications=extra, strict_tags=strict_tags
139
+ )
140
+
141
+ features.append(
142
+ encoders.encode(parsed.sequence, bundle.features, parsed.modifications)
143
+ )
144
+
145
+ rows.append(
146
+ {
147
+ "ID": identifier,
148
+ "Sequence": parsed.raw,
149
+ "Cleaned_sequence": parsed.sequence,
150
+ "Length": parsed.length,
151
+ "Modifications": parsed.modification_string(),
152
+ "Unrecognised_tags": ";".join(parsed.unknown_tags),
153
+ **{
154
+ marker.upper(): ("Yes" if marker in parsed.modifications else "No")
155
+ for marker in encoders.MODIFICATIONS
156
+ },
157
+ }
158
+ )
159
+
160
+ frame = pd.DataFrame(features, columns=bundle.features)
161
+ scores = bundle.score(frame)
162
+
163
+ results = pd.DataFrame(rows)
164
+ results["CPP_score"] = scores
165
+ results["Threshold"] = bundle.threshold
166
+ results["Predicted_label"] = (results["CPP_score"] >= bundle.threshold).astype(int)
167
+ results["Prediction"] = results["Predicted_label"].map({1: "CPP", 0: "Non-CPP"})
168
+
169
+ return results
170
+
171
+
172
+ def _as_bundle(
173
+ model: str | Path | ModelBundle | None, threshold: float | None
174
+ ) -> ModelBundle:
175
+ if isinstance(model, ModelBundle):
176
+ if threshold is not None:
177
+ model.threshold = float(threshold)
178
+ return model
179
+
180
+ return load_bundle(model or paths.SEQUENCE_MODEL, threshold=threshold)
181
+
182
+
183
+ def _as_records(peptides) -> list[tuple[str, str]]:
184
+ records: list[tuple[str, str]] = []
185
+
186
+ for position, item in enumerate(peptides, start=1):
187
+ if isinstance(item, (tuple, list)):
188
+ identifier, raw = item[0], item[1]
189
+ else:
190
+ identifier, raw = f"peptide_{position}", item
191
+ records.append((str(identifier), str(raw)))
192
+
193
+ if not records:
194
+ raise ValueError("No peptides were given.")
195
+
196
+ return records
197
+
198
+
199
+ def _pick(columns, wanted: set[str]) -> str | None:
200
+ return next(
201
+ (name for name in columns if str(name).strip().lower() in wanted), None
202
+ )
@@ -0,0 +1,201 @@
1
+ """Tertiary structure-based prediction: PDB to CPP score.
2
+
3
+ Each structure is converted to SDF with Open Babel, PaDEL computes
4
+ fingerprints from the converted files, and the XGBoost structure model
5
+ scores the bits it was trained on. Modified and non-standard residues
6
+ survive the conversion, so structures from PEPstrMOD can be used
7
+ directly.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import subprocess
13
+ import sys
14
+ import tempfile
15
+ from pathlib import Path
16
+ from typing import Sequence
17
+
18
+ import pandas as pd
19
+
20
+ from . import padel, paths
21
+ from .core import ModelBundle, load_bundle
22
+
23
+ __all__ = ["predict_structures", "find_pdb_files"]
24
+
25
+ PDB_SUFFIXES = {".pdb", ".ent"}
26
+
27
+
28
+ def find_pdb_files(source: str | Path) -> list[Path]:
29
+ """List the PDB files named by a file or directory path."""
30
+ path = Path(source).expanduser().resolve()
31
+
32
+ if path.is_file():
33
+ if path.suffix.lower() not in PDB_SUFFIXES:
34
+ raise ValueError(f"Expected a .pdb or .ent file: {path}")
35
+ return [path]
36
+
37
+ if path.is_dir():
38
+ files = sorted(
39
+ item
40
+ for item in path.iterdir()
41
+ if item.is_file() and item.suffix.lower() in PDB_SUFFIXES
42
+ )
43
+ if not files:
44
+ raise ValueError(f"No .pdb or .ent files found in {path}")
45
+ return files
46
+
47
+ raise FileNotFoundError(f"Input path does not exist: {path}")
48
+
49
+
50
+ def predict_structures(
51
+ source: str | Path,
52
+ *,
53
+ model: str | Path | ModelBundle | None = None,
54
+ feature_list: str | Path | None = None,
55
+ threshold: float | None = None,
56
+ padel_jar: str | Path | None = None,
57
+ java: str | None = None,
58
+ obabel: str | None = None,
59
+ descriptor_types: str | Path | None = None,
60
+ padel_extra: Sequence[str] = (),
61
+ sdf_dir: str | Path | None = None,
62
+ fingerprints_out: str | Path | None = None,
63
+ quiet: bool = False,
64
+ ) -> pd.DataFrame:
65
+ """Score one PDB file, or every PDB file in a directory."""
66
+ # Resolve the external tools first: they are the cheapest checks and the
67
+ # likeliest thing to be missing, so a bad setup is reported before any
68
+ # structure is converted or the model is unpickled.
69
+ jar = paths.find_padel_jar(padel_jar)
70
+ java_command = padel.java_executable(java)
71
+ obabel_command = padel.obabel_executable(obabel)
72
+
73
+ if isinstance(model, ModelBundle):
74
+ bundle = model
75
+ if threshold is not None:
76
+ bundle.threshold = float(threshold)
77
+ else:
78
+ bundle = load_bundle(
79
+ model or paths.STRUCTURE_MODEL,
80
+ feature_list if feature_list is not None else paths.STRUCTURE_FEATURES,
81
+ threshold=threshold,
82
+ )
83
+
84
+ pdb_files = find_pdb_files(source)
85
+
86
+ if not quiet:
87
+ print(f"Found {len(pdb_files)} PDB file(s).")
88
+
89
+ with tempfile.TemporaryDirectory(prefix="cellppdmod2_structure_") as temporary:
90
+ converted_dir = (
91
+ Path(sdf_dir).expanduser().resolve()
92
+ if sdf_dir
93
+ else Path(temporary) / "sdf"
94
+ )
95
+ converted_dir.mkdir(parents=True, exist_ok=True)
96
+
97
+ converted: list[tuple[Path, Path]] = []
98
+ failures: list[tuple[str, str]] = []
99
+
100
+ for pdb in pdb_files:
101
+ sdf = converted_dir / f"{_safe_stem(pdb)}.sdf"
102
+
103
+ try:
104
+ _convert(pdb, sdf, obabel_command)
105
+ except Exception as error: # one bad file must not stop the batch
106
+ failures.append((pdb.name, str(error)))
107
+ print(f"WARNING: {pdb.name}: {error}", file=sys.stderr)
108
+ continue
109
+
110
+ converted.append((pdb, sdf))
111
+ if not quiet:
112
+ print(f"Converted {pdb.name} -> {sdf.name}")
113
+
114
+ if not converted:
115
+ raise RuntimeError(
116
+ "No PDB file could be converted. Check the structures and the "
117
+ "Open Babel installation."
118
+ )
119
+
120
+ staging = Path(temporary) / "staged"
121
+ staging.mkdir()
122
+ for _, sdf in converted:
123
+ (staging / sdf.name).write_bytes(sdf.read_bytes())
124
+
125
+ fingerprint_csv = Path(temporary) / "padel_fingerprints.csv"
126
+
127
+ padel.run_padel(
128
+ staging,
129
+ fingerprint_csv,
130
+ padel_jar=jar,
131
+ java=java_command,
132
+ descriptor_types=descriptor_types,
133
+ extra_flags=padel_extra,
134
+ quiet=quiet,
135
+ )
136
+
137
+ fingerprints = padel.read_fingerprints(fingerprint_csv)
138
+
139
+ if fingerprints_out:
140
+ destination = Path(fingerprints_out).expanduser().resolve()
141
+ destination.parent.mkdir(parents=True, exist_ok=True)
142
+ fingerprints.to_csv(destination, index=False)
143
+ if not quiet:
144
+ print(f"Full fingerprint table saved to {destination}")
145
+
146
+ # Map PaDEL's molecule names back to the PDB files they came from.
147
+ origin = {sdf.stem: pdb.name for pdb, sdf in converted}
148
+
149
+ if "Name" in fingerprints.columns:
150
+ labels = (
151
+ fingerprints["Name"]
152
+ .astype(str)
153
+ .map(lambda name: origin.get(Path(name).stem, name))
154
+ )
155
+ else:
156
+ names = [pdb.name for pdb, _ in converted]
157
+ labels = pd.Series(
158
+ names[: len(fingerprints)]
159
+ + ["UNKNOWN"] * max(0, len(fingerprints) - len(names))
160
+ )
161
+
162
+ scores = bundle.score(fingerprints)
163
+
164
+ results = pd.DataFrame(
165
+ {
166
+ "Input_PDB": labels.reset_index(drop=True).astype(str),
167
+ "CPP_score": scores,
168
+ "Threshold": bundle.threshold,
169
+ }
170
+ )
171
+
172
+ results["Predicted_label"] = (results["CPP_score"] >= bundle.threshold).astype(int)
173
+ results["Prediction"] = results["Predicted_label"].map({1: "CPP", 0: "Non-CPP"})
174
+
175
+ if failures and not quiet:
176
+ print(f"\nConversion failures ({len(failures)}):", file=sys.stderr)
177
+ for name, error in failures:
178
+ print(f" - {name}: {error}", file=sys.stderr)
179
+
180
+ return results
181
+
182
+
183
+ def _convert(pdb: Path, sdf: Path, obabel: str) -> None:
184
+ completed = subprocess.run(
185
+ [obabel, str(pdb), "-O", str(sdf)],
186
+ capture_output=True,
187
+ text=True,
188
+ )
189
+
190
+ if completed.returncode != 0 or not sdf.exists() or sdf.stat().st_size == 0:
191
+ detail = (completed.stderr or completed.stdout or "").strip()
192
+ raise RuntimeError(
193
+ f"Open Babel failed for {pdb.name}" + (f": {detail}" if detail else "")
194
+ )
195
+
196
+
197
+ def _safe_stem(path: Path) -> str:
198
+ return "".join(
199
+ character if character.isalnum() or character in "._-" else "_"
200
+ for character in path.stem
201
+ )