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/encoders.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Sequence features: MAP notation, dipeptide composition, flags, length.
|
|
2
|
+
|
|
3
|
+
A peptide reaches the sequence model as 407 numbers:
|
|
4
|
+
|
|
5
|
+
* 400 normalised dipeptide composition (DPC) frequencies, ``AA`` to ``YY``
|
|
6
|
+
* 6 binary modification flags: NT, CT, PTM, NNR, CYC, D
|
|
7
|
+
* the cleaned peptide length
|
|
8
|
+
|
|
9
|
+
The feature table used for training carried an ``ID`` column beside the
|
|
10
|
+
``ID`` dipeptide, so pandas renamed the dipeptide to ``ID.1``. That name
|
|
11
|
+
is kept here, and filled from the ``ID`` dipeptide, so the stored feature
|
|
12
|
+
order is reproduced exactly rather than guessed.
|
|
13
|
+
|
|
14
|
+
Modified peptides are written in MAP notation: the one-letter sequence
|
|
15
|
+
with annotations in curly braces where they occur, such as
|
|
16
|
+
``{nt:Acetyl}GRKK{nnr:Aib}RRQRRR{ct:Amide}``. A bare tag with no value,
|
|
17
|
+
such as ``R{d}R{d}R{d}``, is also accepted. Braces are removed before
|
|
18
|
+
the composition is counted, matching the trained model.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import re
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"AA20",
|
|
28
|
+
"DPC_FEATURES",
|
|
29
|
+
"FLAG_FEATURES",
|
|
30
|
+
"MODIFICATIONS",
|
|
31
|
+
"ParsedPeptide",
|
|
32
|
+
"parse_peptide",
|
|
33
|
+
"clean_sequence",
|
|
34
|
+
"encode",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
AA20 = "ACDEFGHIKLMNPQRSTVWY"
|
|
38
|
+
DPC_FEATURES = [first + second for first in AA20 for second in AA20]
|
|
39
|
+
|
|
40
|
+
#: Modification categories, in the order the model stores their flags.
|
|
41
|
+
MODIFICATIONS = ("nt", "ct", "ptm", "nnr", "cyc", "d")
|
|
42
|
+
|
|
43
|
+
#: Flag feature name for each category.
|
|
44
|
+
FLAG_FEATURES = {f"flag_{marker}": marker for marker in MODIFICATIONS}
|
|
45
|
+
|
|
46
|
+
_TAG = re.compile(r"\{([^{}]*)\}")
|
|
47
|
+
_NOISE = re.compile(r"[\s\-*./]")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class ParsedPeptide:
|
|
52
|
+
"""One peptide after MAP annotations have been read and removed."""
|
|
53
|
+
|
|
54
|
+
raw: str
|
|
55
|
+
sequence: str
|
|
56
|
+
modifications: set[str] = field(default_factory=set)
|
|
57
|
+
unknown_tags: list[str] = field(default_factory=list)
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def length(self) -> int:
|
|
61
|
+
return len(self.sequence)
|
|
62
|
+
|
|
63
|
+
def flag(self, marker: str) -> int:
|
|
64
|
+
return int(marker in self.modifications)
|
|
65
|
+
|
|
66
|
+
def modification_string(self) -> str:
|
|
67
|
+
"""Active categories in canonical order, upper case, semicolon-joined."""
|
|
68
|
+
active = [marker.upper() for marker in MODIFICATIONS if marker in self.modifications]
|
|
69
|
+
return ";".join(active)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def parse_peptide(
|
|
73
|
+
raw: str,
|
|
74
|
+
*,
|
|
75
|
+
extra_modifications: set[str] | None = None,
|
|
76
|
+
strict_tags: bool = False,
|
|
77
|
+
) -> ParsedPeptide:
|
|
78
|
+
"""Read one MAP or plain peptide into residues plus modification flags.
|
|
79
|
+
|
|
80
|
+
Parameters
|
|
81
|
+
----------
|
|
82
|
+
raw:
|
|
83
|
+
The peptide as written, with or without MAP annotations.
|
|
84
|
+
extra_modifications:
|
|
85
|
+
Categories to switch on regardless of the tags present. This is how
|
|
86
|
+
a plain sequence carries modifications that cannot be written as
|
|
87
|
+
tags, and it mirrors the checklist on the web form.
|
|
88
|
+
strict_tags:
|
|
89
|
+
Raise on a tag whose category is not one of NT, CT, PTM, NNR, CYC, D
|
|
90
|
+
instead of recording it and carrying on.
|
|
91
|
+
"""
|
|
92
|
+
text = str(raw).strip()
|
|
93
|
+
|
|
94
|
+
if not text:
|
|
95
|
+
raise ValueError("Empty peptide.")
|
|
96
|
+
|
|
97
|
+
if text.startswith(">"):
|
|
98
|
+
raise ValueError(
|
|
99
|
+
"FASTA header lines are not accepted. Give one peptide per line, "
|
|
100
|
+
"with no '>' line."
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
modifications: set[str] = set()
|
|
104
|
+
unknown: list[str] = []
|
|
105
|
+
|
|
106
|
+
for tag in _TAG.findall(text):
|
|
107
|
+
marker = tag.split(":", 1)[0].strip().lower()
|
|
108
|
+
|
|
109
|
+
if marker in MODIFICATIONS:
|
|
110
|
+
modifications.add(marker)
|
|
111
|
+
elif tag.strip():
|
|
112
|
+
unknown.append(tag.strip())
|
|
113
|
+
|
|
114
|
+
if unknown and strict_tags:
|
|
115
|
+
raise ValueError(
|
|
116
|
+
f"Unrecognised modification tag(s): {unknown}. "
|
|
117
|
+
f"Known categories are {', '.join(MODIFICATIONS)}."
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
if extra_modifications:
|
|
121
|
+
modifications |= {
|
|
122
|
+
marker.strip().lower()
|
|
123
|
+
for marker in extra_modifications
|
|
124
|
+
if marker.strip()
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
unsupported = sorted(modifications - set(MODIFICATIONS))
|
|
128
|
+
if unsupported:
|
|
129
|
+
raise ValueError(
|
|
130
|
+
f"Unsupported modification category: {unsupported}. "
|
|
131
|
+
f"Choose from {', '.join(MODIFICATIONS)}."
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
return ParsedPeptide(
|
|
135
|
+
raw=text,
|
|
136
|
+
sequence=clean_sequence(text),
|
|
137
|
+
modifications=modifications,
|
|
138
|
+
unknown_tags=unknown,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def clean_sequence(raw: str) -> str:
|
|
143
|
+
"""Strip MAP annotations and separators, leaving standard residues."""
|
|
144
|
+
sequence = _TAG.sub("", str(raw))
|
|
145
|
+
sequence = _NOISE.sub("", sequence).upper()
|
|
146
|
+
|
|
147
|
+
if not sequence:
|
|
148
|
+
raise ValueError(f"No amino-acid residues found in {raw!r}.")
|
|
149
|
+
|
|
150
|
+
invalid = sorted(set(sequence) - set(AA20))
|
|
151
|
+
|
|
152
|
+
if invalid:
|
|
153
|
+
raise ValueError(
|
|
154
|
+
f"Unsupported character(s) in {raw!r}: {invalid}. "
|
|
155
|
+
"Use standard one-letter amino-acid codes; modifications belong "
|
|
156
|
+
"in curly braces."
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
return sequence
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def dipeptide_composition(sequence: str) -> dict[str, float]:
|
|
163
|
+
"""Normalised frequency of each of the 400 dipeptides."""
|
|
164
|
+
counts = dict.fromkeys(DPC_FEATURES, 0)
|
|
165
|
+
pairs = len(sequence) - 1
|
|
166
|
+
|
|
167
|
+
if pairs <= 0:
|
|
168
|
+
return dict.fromkeys(DPC_FEATURES, 0.0)
|
|
169
|
+
|
|
170
|
+
for index in range(pairs):
|
|
171
|
+
counts[sequence[index : index + 2]] += 1
|
|
172
|
+
|
|
173
|
+
return {name: count / pairs for name, count in counts.items()}
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def encode(
|
|
177
|
+
sequence: str,
|
|
178
|
+
feature_names: list[str],
|
|
179
|
+
modifications: set[str] | tuple[str, ...] = (),
|
|
180
|
+
) -> dict[str, float]:
|
|
181
|
+
"""Build exactly the ordered features the model expects.
|
|
182
|
+
|
|
183
|
+
Raises when the model asks for a feature this encoder cannot produce,
|
|
184
|
+
rather than filling it with a zero that would silently change the score.
|
|
185
|
+
"""
|
|
186
|
+
composition = dipeptide_composition(sequence)
|
|
187
|
+
|
|
188
|
+
values: dict[str, float] = dict(composition)
|
|
189
|
+
values["Length"] = len(sequence)
|
|
190
|
+
values["length"] = len(sequence)
|
|
191
|
+
values["ID.1"] = composition["ID"]
|
|
192
|
+
|
|
193
|
+
active = {str(marker).lower() for marker in modifications}
|
|
194
|
+
|
|
195
|
+
for name in feature_names:
|
|
196
|
+
if name.startswith("MF_"):
|
|
197
|
+
values[name] = int(name[3:].lower() in active)
|
|
198
|
+
elif name in FLAG_FEATURES:
|
|
199
|
+
values[name] = int(FLAG_FEATURES[name] in active)
|
|
200
|
+
|
|
201
|
+
unsupported = [name for name in feature_names if name not in values]
|
|
202
|
+
|
|
203
|
+
if unsupported:
|
|
204
|
+
raise ValueError(
|
|
205
|
+
"The model requires features this encoder cannot generate: "
|
|
206
|
+
f"{unsupported[:25]}. Supported features are the 400 DPC names, "
|
|
207
|
+
"ID.1 as an alias for the ID dipeptide, Length/length, MF_<marker>, "
|
|
208
|
+
"and flag_nt/flag_ct/flag_ptm/flag_nnr/flag_cyc/flag_d."
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
return {name: values[name] for name in feature_names}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def infer_modification_names(feature_names: list[str]) -> list[str]:
|
|
215
|
+
"""Modification categories the model actually carries flags for."""
|
|
216
|
+
names: list[str] = []
|
|
217
|
+
|
|
218
|
+
for name in feature_names:
|
|
219
|
+
if name.startswith("MF_"):
|
|
220
|
+
names.append(name[3:].lower())
|
|
221
|
+
elif name in FLAG_FEATURES:
|
|
222
|
+
names.append(FLAG_FEATURES[name])
|
|
223
|
+
|
|
224
|
+
return list(dict.fromkeys(names))
|
cellppdmod2/padel.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Running PaDEL-Descriptor and reading back its fingerprint table.
|
|
2
|
+
|
|
3
|
+
PaDEL is a Java program: it reads a directory of molecule files and
|
|
4
|
+
writes one CSV of fingerprints. Both the chemical and the structure
|
|
5
|
+
module use it, with the same settings the models were trained under, so
|
|
6
|
+
the call lives here once.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import shutil
|
|
13
|
+
import subprocess
|
|
14
|
+
import tempfile
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Sequence
|
|
17
|
+
|
|
18
|
+
import pandas as pd
|
|
19
|
+
|
|
20
|
+
from . import paths
|
|
21
|
+
|
|
22
|
+
__all__ = ["java_executable", "obabel_executable", "run_padel", "read_fingerprints"]
|
|
23
|
+
|
|
24
|
+
_MOLECULE_SUFFIXES = {".smi", ".smiles", ".sdf", ".mol"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def java_executable(explicit: str | None = None) -> str:
|
|
28
|
+
"""Resolve the Java command, or raise with a readable message."""
|
|
29
|
+
java = explicit or os.environ.get(paths.ENV_JAVA) or "java"
|
|
30
|
+
|
|
31
|
+
if shutil.which(java) or Path(java).is_file():
|
|
32
|
+
return java
|
|
33
|
+
|
|
34
|
+
raise FileNotFoundError(
|
|
35
|
+
f"Java executable not found: {java}\n"
|
|
36
|
+
"PaDEL-Descriptor needs a Java runtime. Install one, or point to it "
|
|
37
|
+
f"with --java or the {paths.ENV_JAVA} environment variable."
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def obabel_executable(explicit: str | None = None) -> str:
|
|
42
|
+
"""Resolve the Open Babel command, or raise with a readable message."""
|
|
43
|
+
obabel = explicit or os.environ.get(paths.ENV_OBABEL) or "obabel"
|
|
44
|
+
|
|
45
|
+
if shutil.which(obabel) or Path(obabel).is_file():
|
|
46
|
+
return obabel
|
|
47
|
+
|
|
48
|
+
raise FileNotFoundError(
|
|
49
|
+
f"Open Babel executable not found: {obabel}\n"
|
|
50
|
+
"The structure module converts PDB to SDF with Open Babel. Install it "
|
|
51
|
+
"(conda install -c conda-forge openbabel, or apt install openbabel), "
|
|
52
|
+
f"or point to it with --obabel or the {paths.ENV_OBABEL} variable."
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def run_padel(
|
|
57
|
+
molecules: Path,
|
|
58
|
+
output_csv: Path,
|
|
59
|
+
*,
|
|
60
|
+
padel_jar: Path,
|
|
61
|
+
java: str = "java",
|
|
62
|
+
descriptor_types: Path | str | None = None,
|
|
63
|
+
extra_flags: Sequence[str] = (),
|
|
64
|
+
quiet: bool = False,
|
|
65
|
+
) -> Path:
|
|
66
|
+
"""Compute fingerprints for ``molecules`` into ``output_csv``.
|
|
67
|
+
|
|
68
|
+
``molecules`` may be a single file or a directory. It is copied into a
|
|
69
|
+
private temporary directory first, so that PaDEL never picks up unrelated
|
|
70
|
+
files left beside the input, and a ``.txt`` of SMILES is renamed to
|
|
71
|
+
``.smi`` because PaDEL selects its reader by extension.
|
|
72
|
+
|
|
73
|
+
``-descriptortypes`` is always passed, defaulting to the configuration
|
|
74
|
+
the models were trained under. PaDEL's bare ``-fingerprints`` flag
|
|
75
|
+
computes a far smaller default set, in which most of the selected
|
|
76
|
+
features are absent, so leaving it out makes prediction fail rather than
|
|
77
|
+
merely differ. Pass ``-descriptortypes`` yourself in ``extra_flags`` to
|
|
78
|
+
override, or ``descriptor_types=False`` to leave it off entirely.
|
|
79
|
+
"""
|
|
80
|
+
jar = Path(padel_jar)
|
|
81
|
+
|
|
82
|
+
if not jar.is_file():
|
|
83
|
+
raise FileNotFoundError(f"PaDEL JAR not found: {jar}")
|
|
84
|
+
|
|
85
|
+
output_csv = Path(output_csv).expanduser().resolve()
|
|
86
|
+
output_csv.parent.mkdir(parents=True, exist_ok=True)
|
|
87
|
+
|
|
88
|
+
with tempfile.TemporaryDirectory(prefix="cellppdmod2_padel_") as temporary:
|
|
89
|
+
staging = Path(temporary) / "input"
|
|
90
|
+
staging.mkdir()
|
|
91
|
+
|
|
92
|
+
_stage(molecules, staging)
|
|
93
|
+
|
|
94
|
+
command = [
|
|
95
|
+
java,
|
|
96
|
+
"-jar",
|
|
97
|
+
str(jar.resolve()),
|
|
98
|
+
"-dir",
|
|
99
|
+
str(staging),
|
|
100
|
+
"-file",
|
|
101
|
+
str(output_csv),
|
|
102
|
+
"-fingerprints",
|
|
103
|
+
*_descriptor_flags(descriptor_types, extra_flags),
|
|
104
|
+
*extra_flags,
|
|
105
|
+
]
|
|
106
|
+
|
|
107
|
+
if not quiet:
|
|
108
|
+
print("Running PaDEL:")
|
|
109
|
+
print(" " + " ".join(command))
|
|
110
|
+
|
|
111
|
+
completed = subprocess.run(
|
|
112
|
+
command,
|
|
113
|
+
stdout=subprocess.PIPE,
|
|
114
|
+
stderr=subprocess.STDOUT,
|
|
115
|
+
text=True,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
if completed.stdout and not quiet:
|
|
119
|
+
print(completed.stdout.rstrip())
|
|
120
|
+
|
|
121
|
+
if completed.returncode != 0:
|
|
122
|
+
raise RuntimeError(
|
|
123
|
+
f"PaDEL exited with status {completed.returncode}.\n"
|
|
124
|
+
f"{(completed.stdout or '').strip()[-2000:]}"
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
if not output_csv.is_file() or output_csv.stat().st_size == 0:
|
|
128
|
+
raise RuntimeError(
|
|
129
|
+
f"PaDEL produced no fingerprint table at {output_csv}. "
|
|
130
|
+
"Check that the input molecules are valid."
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
return output_csv
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def read_fingerprints(path: Path) -> pd.DataFrame:
|
|
137
|
+
"""Read a PaDEL CSV, with stripped headers and ``Name`` kept as-is."""
|
|
138
|
+
frame = pd.read_csv(path)
|
|
139
|
+
|
|
140
|
+
if frame.empty:
|
|
141
|
+
raise RuntimeError(f"{Path(path).name} contains no fingerprint rows.")
|
|
142
|
+
|
|
143
|
+
frame.columns = [str(column).strip() for column in frame.columns]
|
|
144
|
+
return frame
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _descriptor_flags(
|
|
148
|
+
descriptor_types: Path | str | bool | None, extra_flags: Sequence[str]
|
|
149
|
+
) -> list[str]:
|
|
150
|
+
"""The ``-descriptortypes`` pair to add, if it is not already there."""
|
|
151
|
+
if descriptor_types is False:
|
|
152
|
+
return []
|
|
153
|
+
|
|
154
|
+
if "-descriptortypes" in extra_flags:
|
|
155
|
+
# The caller is choosing the configuration; do not pass a second one.
|
|
156
|
+
return []
|
|
157
|
+
|
|
158
|
+
path = Path(descriptor_types) if descriptor_types else paths.DESCRIPTOR_TYPES
|
|
159
|
+
|
|
160
|
+
if not path.is_file():
|
|
161
|
+
raise FileNotFoundError(
|
|
162
|
+
f"PaDEL descriptor-type file not found: {path}\n"
|
|
163
|
+
"It records the fingerprinters the models were trained with. "
|
|
164
|
+
"Pass --descriptortypes with the descriptors.xml from the "
|
|
165
|
+
"repository's padel/ directory."
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
return ["-descriptortypes", str(path.resolve())]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _stage(source: Path, staging: Path) -> None:
|
|
172
|
+
source = Path(source)
|
|
173
|
+
|
|
174
|
+
if source.is_dir():
|
|
175
|
+
copied = 0
|
|
176
|
+
for item in sorted(source.iterdir()):
|
|
177
|
+
if item.is_file() and item.suffix.lower() in _MOLECULE_SUFFIXES:
|
|
178
|
+
shutil.copy2(item, staging / item.name)
|
|
179
|
+
copied += 1
|
|
180
|
+
|
|
181
|
+
if not copied:
|
|
182
|
+
raise ValueError(
|
|
183
|
+
f"No molecule files ({', '.join(sorted(_MOLECULE_SUFFIXES))}) "
|
|
184
|
+
f"found in {source}"
|
|
185
|
+
)
|
|
186
|
+
return
|
|
187
|
+
|
|
188
|
+
if not source.is_file():
|
|
189
|
+
raise FileNotFoundError(f"Input not found: {source}")
|
|
190
|
+
|
|
191
|
+
name = source.name
|
|
192
|
+
if source.suffix.lower() not in _MOLECULE_SUFFIXES:
|
|
193
|
+
# PaDEL chooses its reader from the extension; a .txt of SMILES is
|
|
194
|
+
# presented to it as .smi without touching the contents.
|
|
195
|
+
name = f"{source.stem}.smi"
|
|
196
|
+
|
|
197
|
+
shutil.copy2(source, staging / name)
|
cellppdmod2/paths.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""Location of the bundled models, feature lists and the PaDEL installation.
|
|
2
|
+
|
|
3
|
+
Every path can be overridden, in this order of precedence:
|
|
4
|
+
|
|
5
|
+
1. an explicit argument passed on the command line or to the Python API
|
|
6
|
+
2. an environment variable
|
|
7
|
+
3. the files shipped inside the installed package
|
|
8
|
+
4. a ``padel/`` directory next to the repository root (source checkouts)
|
|
9
|
+
|
|
10
|
+
The trained models and selected-feature lists travel inside the wheel, so
|
|
11
|
+
sequence prediction and design work straight after ``pip install``. The
|
|
12
|
+
PaDEL-Descriptor JAR and its Java libraries do not: they are third-party
|
|
13
|
+
LGPL software of about 20 MB, so they stay in the Git repository and are
|
|
14
|
+
located at run time.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"DATA_DIR",
|
|
24
|
+
"SEQUENCE_MODEL",
|
|
25
|
+
"CHEMICAL_MODEL",
|
|
26
|
+
"STRUCTURE_MODEL",
|
|
27
|
+
"CHEMICAL_FEATURES",
|
|
28
|
+
"STRUCTURE_FEATURES",
|
|
29
|
+
"ENV_PADEL_JAR",
|
|
30
|
+
"ENV_PADEL_HOME",
|
|
31
|
+
"ENV_JAVA",
|
|
32
|
+
"ENV_OBABEL",
|
|
33
|
+
"find_padel_jar",
|
|
34
|
+
"describe",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
DATA_DIR = Path(__file__).resolve().parent / "data"
|
|
38
|
+
|
|
39
|
+
SEQUENCE_MODEL = DATA_DIR / "sequence_model.joblib"
|
|
40
|
+
CHEMICAL_MODEL = DATA_DIR / "chemical_model.joblib"
|
|
41
|
+
STRUCTURE_MODEL = DATA_DIR / "structure_model.joblib"
|
|
42
|
+
CHEMICAL_FEATURES = DATA_DIR / "chemical_features.csv"
|
|
43
|
+
STRUCTURE_FEATURES = DATA_DIR / "structure_features.csv"
|
|
44
|
+
|
|
45
|
+
#: PaDEL descriptor-type configuration used when the models were trained.
|
|
46
|
+
#: It switches on the ten fingerprinters the selected features come from,
|
|
47
|
+
#: including the Klekota-Roth, substructure and graph-only counts. Without
|
|
48
|
+
#: it PaDEL computes a much smaller default set and most of the selected
|
|
49
|
+
#: features never appear in its output.
|
|
50
|
+
DESCRIPTOR_TYPES = DATA_DIR / "descriptors.xml"
|
|
51
|
+
|
|
52
|
+
ENV_PADEL_JAR = "CELLPPDMOD2_PADEL_JAR"
|
|
53
|
+
ENV_PADEL_HOME = "CELLPPDMOD2_PADEL_HOME"
|
|
54
|
+
ENV_JAVA = "CELLPPDMOD2_JAVA"
|
|
55
|
+
ENV_OBABEL = "CELLPPDMOD2_OBABEL"
|
|
56
|
+
|
|
57
|
+
_JAR_NAME = "PaDEL-Descriptor.jar"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _repository_root() -> Path:
|
|
61
|
+
"""Best guess at the checkout root when running from a source tree."""
|
|
62
|
+
# .../src/cellppdmod2/paths.py -> .../src/cellppdmod2 -> .../src -> repo
|
|
63
|
+
return Path(__file__).resolve().parents[2]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _from_environment() -> Path | None:
|
|
67
|
+
"""The JAR named by an environment variable, which must exist if set.
|
|
68
|
+
|
|
69
|
+
A variable pointing at a path that is not there is a mistake worth
|
|
70
|
+
reporting, not a reason to quietly use a different installation and
|
|
71
|
+
produce fingerprints from an unexpected PaDEL version.
|
|
72
|
+
"""
|
|
73
|
+
jar = os.environ.get(ENV_PADEL_JAR, "").strip()
|
|
74
|
+
if jar:
|
|
75
|
+
path = Path(jar).expanduser()
|
|
76
|
+
if not path.is_file():
|
|
77
|
+
raise FileNotFoundError(
|
|
78
|
+
f"{ENV_PADEL_JAR} points at {path}, which does not exist.\n"
|
|
79
|
+
"Correct the variable, or unset it to search the usual places."
|
|
80
|
+
)
|
|
81
|
+
return path.resolve()
|
|
82
|
+
|
|
83
|
+
home = os.environ.get(ENV_PADEL_HOME, "").strip()
|
|
84
|
+
if home:
|
|
85
|
+
path = Path(home).expanduser() / _JAR_NAME
|
|
86
|
+
if not path.is_file():
|
|
87
|
+
raise FileNotFoundError(
|
|
88
|
+
f"{ENV_PADEL_HOME} points at {Path(home).expanduser()}, which "
|
|
89
|
+
f"holds no {_JAR_NAME}.\n"
|
|
90
|
+
"Correct the variable, or unset it to search the usual places."
|
|
91
|
+
)
|
|
92
|
+
return path.resolve()
|
|
93
|
+
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _candidate_jars() -> list[Path]:
|
|
98
|
+
candidates: list[Path] = []
|
|
99
|
+
|
|
100
|
+
# Shipped alongside the package, when a site build chooses to include it.
|
|
101
|
+
candidates.append(DATA_DIR / "padel" / _JAR_NAME)
|
|
102
|
+
|
|
103
|
+
# Source checkout: <repo>/padel/PaDEL-Descriptor.jar
|
|
104
|
+
candidates.append(_repository_root() / "padel" / _JAR_NAME)
|
|
105
|
+
|
|
106
|
+
# Current working directory, which is how the original standalone ran.
|
|
107
|
+
candidates.append(Path.cwd() / "padel" / _JAR_NAME)
|
|
108
|
+
candidates.append(Path.cwd() / _JAR_NAME)
|
|
109
|
+
|
|
110
|
+
return candidates
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def find_padel_jar(explicit: str | os.PathLike[str] | None = None) -> Path:
|
|
114
|
+
"""Return the PaDEL-Descriptor JAR, or raise with instructions.
|
|
115
|
+
|
|
116
|
+
Parameters
|
|
117
|
+
----------
|
|
118
|
+
explicit:
|
|
119
|
+
A path given by the user. Checked first and reported verbatim when
|
|
120
|
+
it does not exist, so a typo is not silently replaced by a fallback.
|
|
121
|
+
"""
|
|
122
|
+
if explicit:
|
|
123
|
+
jar = Path(explicit).expanduser().resolve()
|
|
124
|
+
if not jar.is_file():
|
|
125
|
+
raise FileNotFoundError(f"PaDEL JAR not found: {jar}")
|
|
126
|
+
return jar
|
|
127
|
+
|
|
128
|
+
from_environment = _from_environment()
|
|
129
|
+
if from_environment is not None:
|
|
130
|
+
return from_environment
|
|
131
|
+
|
|
132
|
+
for candidate in _candidate_jars():
|
|
133
|
+
try:
|
|
134
|
+
if candidate.is_file():
|
|
135
|
+
return candidate.resolve()
|
|
136
|
+
except OSError: # pragma: no cover - unreadable path
|
|
137
|
+
continue
|
|
138
|
+
|
|
139
|
+
searched = "\n".join(f" {path}" for path in _candidate_jars())
|
|
140
|
+
raise FileNotFoundError(
|
|
141
|
+
"PaDEL-Descriptor.jar was not found.\n"
|
|
142
|
+
"The chemical and structure modules need it; the sequence and "
|
|
143
|
+
"design modules do not.\n\n"
|
|
144
|
+
"Give its location in one of these ways:\n"
|
|
145
|
+
" cellppdmod2 chemical ... --padel-jar /path/to/PaDEL-Descriptor.jar\n"
|
|
146
|
+
f" export {ENV_PADEL_JAR}=/path/to/PaDEL-Descriptor.jar\n"
|
|
147
|
+
f" export {ENV_PADEL_HOME}=/path/to/padel\n\n"
|
|
148
|
+
"The JAR ships in the padel/ directory of the CellPPD-MOD 2.0 "
|
|
149
|
+
"repository and in the standalone archive.\n\n"
|
|
150
|
+
f"Searched:\n{searched}"
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def describe() -> dict[str, str]:
|
|
155
|
+
"""Resolved locations, for ``cellppdmod2 info``."""
|
|
156
|
+
try:
|
|
157
|
+
padel = str(find_padel_jar())
|
|
158
|
+
except FileNotFoundError as error:
|
|
159
|
+
padel = "not found" if ENV_PADEL_JAR not in str(error) else str(error).splitlines()[0]
|
|
160
|
+
|
|
161
|
+
return {
|
|
162
|
+
"data directory": str(DATA_DIR),
|
|
163
|
+
"sequence model": _state(SEQUENCE_MODEL),
|
|
164
|
+
"chemical model": _state(CHEMICAL_MODEL),
|
|
165
|
+
"structure model": _state(STRUCTURE_MODEL),
|
|
166
|
+
"chemical features": _state(CHEMICAL_FEATURES),
|
|
167
|
+
"structure features": _state(STRUCTURE_FEATURES),
|
|
168
|
+
"descriptor types": _state(DESCRIPTOR_TYPES),
|
|
169
|
+
"PaDEL JAR": padel,
|
|
170
|
+
"java": os.environ.get(ENV_JAVA, "java"),
|
|
171
|
+
"obabel": os.environ.get(ENV_OBABEL, "obabel"),
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _state(path: Path) -> str:
|
|
176
|
+
return str(path) if path.is_file() else f"{path} (missing)"
|