eosquality 0.2.1__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.
- eosquality/__init__.py +100 -0
- eosquality/_artifacts.py +263 -0
- eosquality/_reference_modality.py +278 -0
- eosquality/_registry.py +97 -0
- eosquality/_training_modality.py +306 -0
- eosquality/cli/__init__.py +133 -0
- eosquality/cli/_common.py +144 -0
- eosquality/cli/build.py +252 -0
- eosquality/cli/fit.py +234 -0
- eosquality/cli/run.py +238 -0
- eosquality/cli/setup.py +86 -0
- eosquality/exceptions.py +28 -0
- eosquality/library/__init__.py +20 -0
- eosquality/library/download.py +182 -0
- eosquality/library/identity.py +178 -0
- eosquality/library/physchem.py +241 -0
- eosquality/library/physchem_cache.py +210 -0
- eosquality/library/physchem_scaler.json +880 -0
- eosquality/library/reference.py +190 -0
- eosquality/preprocess.py +146 -0
- eosquality/py.typed +0 -0
- eosquality/quality.py +548 -0
- eosquality/results.py +40 -0
- eosquality/schema/__init__.py +1 -0
- eosquality/schema/infer.py +89 -0
- eosquality/schema/models.py +28 -0
- eosquality/scores/__init__.py +19 -0
- eosquality/scores/_base.py +247 -0
- eosquality/scores/_helpers.py +305 -0
- eosquality/scores/_match_keys.py +170 -0
- eosquality/scores/_percentile_score.py +232 -0
- eosquality/scores/_physchem_domain.py +315 -0
- eosquality/scores/_training_helpers.py +162 -0
- eosquality/scores/extremity.py +159 -0
- eosquality/scores/reference_match.py +207 -0
- eosquality/scores/training_distance.py +319 -0
- eosquality/scores/training_match.py +187 -0
- eosquality/scores/training_physchem.py +237 -0
- eosquality/scores/typicality.py +315 -0
- eosquality/shared/__init__.py +13 -0
- eosquality/shared/feature_selection.py +168 -0
- eosquality/shared/fit.py +84 -0
- eosquality/shared/load.py +71 -0
- eosquality/shared/metadata.py +72 -0
- eosquality/shared/save.py +55 -0
- eosquality/shared/state.py +72 -0
- eosquality/training/__init__.py +27 -0
- eosquality/training/data.py +284 -0
- eosquality/training/state.py +220 -0
- eosquality/utils/__init__.py +1 -0
- eosquality/utils/console/__init__.py +82 -0
- eosquality/utils/console/_core.py +135 -0
- eosquality/utils/console/bars.py +78 -0
- eosquality/utils/console/display.py +161 -0
- eosquality/utils/console/fmt.py +143 -0
- eosquality/utils/console/steps.py +116 -0
- eosquality/utils/identifiers.py +127 -0
- eosquality/utils/logging.py +300 -0
- eosquality/utils/parallel.py +160 -0
- eosquality/vectorindex.py +304 -0
- eosquality-0.2.1.dist-info/METADATA +132 -0
- eosquality-0.2.1.dist-info/RECORD +66 -0
- eosquality-0.2.1.dist-info/WHEEL +5 -0
- eosquality-0.2.1.dist-info/entry_points.txt +2 -0
- eosquality-0.2.1.dist-info/licenses/LICENSE +674 -0
- eosquality-0.2.1.dist-info/top_level.txt +1 -0
eosquality/__init__.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""eosquality: assess the quality of query data against a fitted reference population."""
|
|
2
|
+
|
|
3
|
+
from eosquality._registry import ALL_SCORES
|
|
4
|
+
|
|
5
|
+
# The public classes are resolved on first access (PEP 562): importing them
|
|
6
|
+
# eagerly pulls in pandas, scikit-learn, SciPy and RDKit (about 2 s), which
|
|
7
|
+
# the CLI must not pay just to parse its arguments.
|
|
8
|
+
_LAZY = {
|
|
9
|
+
"ErsiliaQuality": "eosquality.quality",
|
|
10
|
+
"RunResult": "eosquality.results",
|
|
11
|
+
**{
|
|
12
|
+
name: "eosquality.scores"
|
|
13
|
+
for name in (
|
|
14
|
+
"Extremity",
|
|
15
|
+
"PercentileRunResult",
|
|
16
|
+
"ReferenceMatch",
|
|
17
|
+
"ReferenceMatchRunResult",
|
|
18
|
+
"Typicality",
|
|
19
|
+
)
|
|
20
|
+
},
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def __getattr__(name: str):
|
|
25
|
+
"""Import a public class on first access.
|
|
26
|
+
|
|
27
|
+
Parameters
|
|
28
|
+
----------
|
|
29
|
+
name : str
|
|
30
|
+
Attribute name.
|
|
31
|
+
|
|
32
|
+
Returns
|
|
33
|
+
-------
|
|
34
|
+
object
|
|
35
|
+
The class.
|
|
36
|
+
|
|
37
|
+
Raises
|
|
38
|
+
------
|
|
39
|
+
AttributeError
|
|
40
|
+
If ``name`` is not a public attribute.
|
|
41
|
+
"""
|
|
42
|
+
module = _LAZY.get(name)
|
|
43
|
+
if module is None:
|
|
44
|
+
raise AttributeError(f"module 'eosquality' has no attribute {name!r}")
|
|
45
|
+
import importlib
|
|
46
|
+
|
|
47
|
+
value = getattr(importlib.import_module(module), name)
|
|
48
|
+
globals()[name] = value
|
|
49
|
+
return value
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def __dir__() -> list[str]:
|
|
53
|
+
"""Module attributes, including the lazily imported classes.
|
|
54
|
+
|
|
55
|
+
Returns
|
|
56
|
+
-------
|
|
57
|
+
list of str
|
|
58
|
+
"""
|
|
59
|
+
return sorted(set(globals()) | set(_LAZY))
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def set_verbosity(verbose: bool) -> None:
|
|
63
|
+
"""Turn the step-by-step output and DEBUG logs on, or back to warnings only.
|
|
64
|
+
|
|
65
|
+
Parameters
|
|
66
|
+
----------
|
|
67
|
+
verbose : bool
|
|
68
|
+
``True`` for the curated step output (as in the CLI) and DEBUG
|
|
69
|
+
messages; ``False`` for warnings only.
|
|
70
|
+
"""
|
|
71
|
+
from eosquality.utils.logging import logger
|
|
72
|
+
|
|
73
|
+
logger.set_verbosity(verbose)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def set_log_level(level: str) -> None:
|
|
77
|
+
"""Set the package log level (e.g. ``"INFO"`` to see progress messages).
|
|
78
|
+
|
|
79
|
+
Parameters
|
|
80
|
+
----------
|
|
81
|
+
level : str
|
|
82
|
+
A loguru level name such as ``"DEBUG"``, ``"INFO"`` or ``"WARNING"``.
|
|
83
|
+
"""
|
|
84
|
+
from eosquality.utils.logging import logger
|
|
85
|
+
|
|
86
|
+
logger.set_level(level)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
__all__ = [
|
|
90
|
+
"ALL_SCORES",
|
|
91
|
+
"ErsiliaQuality",
|
|
92
|
+
"RunResult",
|
|
93
|
+
"Typicality",
|
|
94
|
+
"Extremity",
|
|
95
|
+
"ReferenceMatch",
|
|
96
|
+
"PercentileRunResult",
|
|
97
|
+
"ReferenceMatchRunResult",
|
|
98
|
+
"set_log_level",
|
|
99
|
+
"set_verbosity",
|
|
100
|
+
]
|
eosquality/_artifacts.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""Saving and loading :class:`~eosquality.quality.ErsiliaQuality` artifacts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import pathlib
|
|
7
|
+
from typing import TYPE_CHECKING, Any
|
|
8
|
+
|
|
9
|
+
from eosquality._registry import LIBRARY_USERS, SCORE_ORDER
|
|
10
|
+
from eosquality.exceptions import ArtifactVersionError, IncompatibleArtifactsError
|
|
11
|
+
from eosquality.library.identity import LIBRARY_ID
|
|
12
|
+
from eosquality.scores.extremity import Extremity
|
|
13
|
+
from eosquality.scores.reference_match import ReferenceMatch
|
|
14
|
+
from eosquality.scores.training_distance import TrainingDistance
|
|
15
|
+
from eosquality.scores.training_match import TrainingMatch
|
|
16
|
+
from eosquality.scores.training_physchem import TrainingPhyschem
|
|
17
|
+
from eosquality.scores.typicality import Typicality
|
|
18
|
+
from eosquality.shared.load import load_shared
|
|
19
|
+
from eosquality.shared.save import save_shared
|
|
20
|
+
from eosquality.shared.state import SharedFitState
|
|
21
|
+
from eosquality.training import load_training_state, save_training_state
|
|
22
|
+
from eosquality.utils.logging import logger
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from eosquality.quality import ErsiliaQuality
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
SCORE_CLASSES = {
|
|
29
|
+
"typicality": Typicality,
|
|
30
|
+
"extremity": Extremity,
|
|
31
|
+
"match": ReferenceMatch,
|
|
32
|
+
}
|
|
33
|
+
# Artifacts layout: one subfolder per modality, either or both present.
|
|
34
|
+
REFERENCE_DIR = "reference_mode"
|
|
35
|
+
TRAINING_DIR = "training_mode"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def save(eq, path: str | pathlib.Path) -> pathlib.Path:
|
|
39
|
+
"""Write fitted artifacts to a folder, one subfolder per modality.
|
|
40
|
+
|
|
41
|
+
``reference_mode/`` holds ``shared/`` and each reference score's subfolder;
|
|
42
|
+
``training_mode/`` holds ``training_sets/`` and each training score's
|
|
43
|
+
subfolder. ``manifest.json`` at the top is informational only.
|
|
44
|
+
|
|
45
|
+
Parameters
|
|
46
|
+
----------
|
|
47
|
+
eq : ErsiliaQuality
|
|
48
|
+
A fitted orchestrator.
|
|
49
|
+
path : str or pathlib.Path
|
|
50
|
+
Artifacts folder (created if needed). It must not already hold
|
|
51
|
+
artifacts: saving over them would mix the old and the new fit.
|
|
52
|
+
|
|
53
|
+
Returns
|
|
54
|
+
-------
|
|
55
|
+
pathlib.Path
|
|
56
|
+
The artifacts folder.
|
|
57
|
+
|
|
58
|
+
Raises
|
|
59
|
+
------
|
|
60
|
+
FileExistsError
|
|
61
|
+
If ``path`` already holds a ``reference_mode/`` or ``training_mode/``.
|
|
62
|
+
"""
|
|
63
|
+
eq._check_fitted()
|
|
64
|
+
folder = pathlib.Path(path)
|
|
65
|
+
for mode in (REFERENCE_DIR, TRAINING_DIR):
|
|
66
|
+
if (folder / mode).exists():
|
|
67
|
+
raise FileExistsError(
|
|
68
|
+
f"{folder} already holds artifacts ({mode}/); delete it or save "
|
|
69
|
+
"to a new folder."
|
|
70
|
+
)
|
|
71
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
if eq._shared is not None:
|
|
73
|
+
root = folder / REFERENCE_DIR
|
|
74
|
+
save_shared(eq._shared, root)
|
|
75
|
+
for component in eq._components().values():
|
|
76
|
+
component.save_component(root)
|
|
77
|
+
save_training(eq, folder)
|
|
78
|
+
write_manifest(eq, folder)
|
|
79
|
+
logger.info(f"Artifacts saved → {folder}")
|
|
80
|
+
return folder
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def save_training(eq, folder: pathlib.Path) -> None:
|
|
84
|
+
"""Write ``<folder>/training_mode/`` if the training modality is fitted.
|
|
85
|
+
|
|
86
|
+
Parameters
|
|
87
|
+
----------
|
|
88
|
+
eq : ErsiliaQuality
|
|
89
|
+
The orchestrator.
|
|
90
|
+
folder : pathlib.Path
|
|
91
|
+
Artifacts folder.
|
|
92
|
+
"""
|
|
93
|
+
if eq._training is None:
|
|
94
|
+
return
|
|
95
|
+
root = folder / TRAINING_DIR
|
|
96
|
+
save_training_state(eq._training, root)
|
|
97
|
+
for component in eq._training_components().values():
|
|
98
|
+
component.save_component(root)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def write_manifest(eq, folder: pathlib.Path) -> None:
|
|
102
|
+
"""Write the top-level ``manifest.json`` summary.
|
|
103
|
+
|
|
104
|
+
Parameters
|
|
105
|
+
----------
|
|
106
|
+
eq : ErsiliaQuality
|
|
107
|
+
The fitted orchestrator.
|
|
108
|
+
folder : pathlib.Path
|
|
109
|
+
Artifacts folder.
|
|
110
|
+
"""
|
|
111
|
+
eos_id, version = eq._model_id()
|
|
112
|
+
manifest: dict[str, Any] = {
|
|
113
|
+
"eos_id": eos_id,
|
|
114
|
+
"version": version,
|
|
115
|
+
"modalities": [
|
|
116
|
+
m
|
|
117
|
+
for m, present in (
|
|
118
|
+
("reference", eq._shared is not None),
|
|
119
|
+
("training", eq._training is not None),
|
|
120
|
+
)
|
|
121
|
+
if present
|
|
122
|
+
],
|
|
123
|
+
"scores": list(eq._components()) + list(eq._training_components()),
|
|
124
|
+
}
|
|
125
|
+
if eq._shared is not None:
|
|
126
|
+
meta = eq._shared.metadata
|
|
127
|
+
manifest["reference"] = {
|
|
128
|
+
"format_version": meta.format_version,
|
|
129
|
+
"n_samples": meta.n_samples,
|
|
130
|
+
"n_features": meta.n_features,
|
|
131
|
+
"n_features_selected": len(eq._shared.selected_columns),
|
|
132
|
+
"library_id": meta.library_id,
|
|
133
|
+
"fit_timestamp": meta.fit_timestamp,
|
|
134
|
+
"eosquality_version": meta.eosquality_version,
|
|
135
|
+
}
|
|
136
|
+
if eq._training is not None:
|
|
137
|
+
from eosquality.training.state import TRAINING_FORMAT_VERSION
|
|
138
|
+
|
|
139
|
+
manifest["training"] = {
|
|
140
|
+
"format_version": TRAINING_FORMAT_VERSION,
|
|
141
|
+
"columns": {
|
|
142
|
+
name: {"n": col.n} for name, col in eq._training.columns.items()
|
|
143
|
+
},
|
|
144
|
+
}
|
|
145
|
+
with open(folder / "manifest.json", "w") as f:
|
|
146
|
+
json.dump(manifest, f, indent=2)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def load(eq_cls, path: str | pathlib.Path) -> ErsiliaQuality:
|
|
150
|
+
"""Reconstruct an orchestrator from a saved artifacts folder.
|
|
151
|
+
|
|
152
|
+
Loads ``reference_mode/`` and/or ``training_mode/``, whichever exist.
|
|
153
|
+
|
|
154
|
+
Parameters
|
|
155
|
+
----------
|
|
156
|
+
eq_cls : type
|
|
157
|
+
:class:`ErsiliaQuality` (or a subclass).
|
|
158
|
+
path : str or pathlib.Path
|
|
159
|
+
Artifacts folder.
|
|
160
|
+
|
|
161
|
+
Returns
|
|
162
|
+
-------
|
|
163
|
+
ErsiliaQuality
|
|
164
|
+
A fitted instance with every component found.
|
|
165
|
+
"""
|
|
166
|
+
folder = pathlib.Path(path)
|
|
167
|
+
if not folder.exists():
|
|
168
|
+
raise FileNotFoundError(f"No artifacts folder found at: {folder}")
|
|
169
|
+
if not folder.is_dir():
|
|
170
|
+
raise ValueError(
|
|
171
|
+
f"Expected a directory, got a file: {folder}. "
|
|
172
|
+
"Artifacts are stored as a folder — pass the folder path."
|
|
173
|
+
)
|
|
174
|
+
if (folder / "shared").is_dir() or (folder / "training").is_dir():
|
|
175
|
+
raise ArtifactVersionError(
|
|
176
|
+
f"Artifacts at {folder} use the old flat layout; this eosquality "
|
|
177
|
+
f"install expects {REFERENCE_DIR}/ and {TRAINING_DIR}/ subfolders. Refit."
|
|
178
|
+
)
|
|
179
|
+
has_reference = (folder / REFERENCE_DIR).is_dir()
|
|
180
|
+
has_training = (folder / TRAINING_DIR).is_dir()
|
|
181
|
+
if not has_reference and not has_training:
|
|
182
|
+
raise FileNotFoundError(
|
|
183
|
+
f"No {REFERENCE_DIR}/ or {TRAINING_DIR}/ under {folder} — nothing to load."
|
|
184
|
+
)
|
|
185
|
+
instance = eq_cls()
|
|
186
|
+
if has_reference:
|
|
187
|
+
_load_reference(instance, folder / REFERENCE_DIR)
|
|
188
|
+
if has_training:
|
|
189
|
+
_load_training(instance, folder / TRAINING_DIR)
|
|
190
|
+
instance.is_fitted_ = True
|
|
191
|
+
logger.success(
|
|
192
|
+
f"Artifacts loaded from {folder} | modalities={instance.modalities_}"
|
|
193
|
+
)
|
|
194
|
+
return instance
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _load_training(instance, root: pathlib.Path) -> None:
|
|
198
|
+
"""Fill ``instance`` with the training modality stored under ``root``."""
|
|
199
|
+
instance._training = load_training_state(root)
|
|
200
|
+
for cls in (TrainingDistance, TrainingPhyschem, TrainingMatch):
|
|
201
|
+
if (root / cls.NAME).is_dir():
|
|
202
|
+
component = cls.load(
|
|
203
|
+
root, shared=instance._shared, training=instance._training
|
|
204
|
+
)
|
|
205
|
+
setattr(instance, cls.NAME, component)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _load_reference(instance, root: pathlib.Path) -> None:
|
|
209
|
+
"""Fill ``instance`` with the reference modality stored under ``root``."""
|
|
210
|
+
present = [n for n in SCORE_ORDER if (root / n).is_dir()]
|
|
211
|
+
if not present:
|
|
212
|
+
raise FileNotFoundError(f"No reference score subfolders under {root}.")
|
|
213
|
+
shared = load_shared(root)
|
|
214
|
+
check_artifacts_compatibility(
|
|
215
|
+
shared, has_library_scores=bool(set(present) & LIBRARY_USERS)
|
|
216
|
+
)
|
|
217
|
+
instance._shared = shared
|
|
218
|
+
for name in present:
|
|
219
|
+
setattr(instance, name, SCORE_CLASSES[name].load(root, shared=shared))
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def check_artifacts_compatibility(
|
|
223
|
+
shared: SharedFitState, has_library_scores: bool
|
|
224
|
+
) -> None:
|
|
225
|
+
"""Reject artifacts fit against a different reference library or major.
|
|
226
|
+
|
|
227
|
+
Only artifacts with a library-reading score (``ref_match``) are checked.
|
|
228
|
+
Artifacts fit on the canonical library must match this install's
|
|
229
|
+
:data:`LIBRARY_ID`; those fit on a custom library must record its path.
|
|
230
|
+
The package major version must also match.
|
|
231
|
+
|
|
232
|
+
Parameters
|
|
233
|
+
----------
|
|
234
|
+
shared : SharedFitState
|
|
235
|
+
Loaded shared state of the reference modality.
|
|
236
|
+
has_library_scores : bool
|
|
237
|
+
Whether any loaded reference score reads the reference library.
|
|
238
|
+
"""
|
|
239
|
+
if not has_library_scores:
|
|
240
|
+
return
|
|
241
|
+
import importlib.metadata as _md
|
|
242
|
+
|
|
243
|
+
from packaging.version import InvalidVersion, Version
|
|
244
|
+
|
|
245
|
+
library_id = shared.metadata.library_id
|
|
246
|
+
if library_id != LIBRARY_ID and not shared.metadata.library_path:
|
|
247
|
+
raise IncompatibleArtifactsError(
|
|
248
|
+
f"Artifacts were fit against reference library {library_id!r} but "
|
|
249
|
+
f"this install ships {LIBRARY_ID!r}. Install a compatible "
|
|
250
|
+
"eosquality release or refit against the current library."
|
|
251
|
+
)
|
|
252
|
+
try:
|
|
253
|
+
current = _md.version("eosquality")
|
|
254
|
+
saved_major = Version(shared.metadata.eosquality_version).major
|
|
255
|
+
current_major = Version(current).major
|
|
256
|
+
except (_md.PackageNotFoundError, InvalidVersion):
|
|
257
|
+
return
|
|
258
|
+
if saved_major != current_major:
|
|
259
|
+
raise IncompatibleArtifactsError(
|
|
260
|
+
f"Artifacts were fit with eosquality {shared.metadata.eosquality_version} "
|
|
261
|
+
f"(major={saved_major}) but this install is {current} "
|
|
262
|
+
f"(major={current_major}). Install a matching eosquality release or refit."
|
|
263
|
+
)
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"""Reference modality of :class:`~eosquality.quality.ErsiliaQuality`: fit and run.
|
|
2
|
+
|
|
3
|
+
Module-level functions taking the orchestrator instance ``eq``; the class
|
|
4
|
+
delegates to them so that ``quality.py`` stays a readable façade.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import pathlib
|
|
10
|
+
from collections.abc import Iterable
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
from eosquality._registry import SCORE_ORDER, score_name
|
|
16
|
+
from eosquality.exceptions import SchemaError
|
|
17
|
+
from eosquality.library.identity import LIBRARY_ID
|
|
18
|
+
from eosquality.library.reference import ReferenceLibrary
|
|
19
|
+
from eosquality.schema.infer import validate_against_schema
|
|
20
|
+
from eosquality.scores._helpers import _make_query_repr, query_keys
|
|
21
|
+
from eosquality.scores._training_helpers import QueryFeatures
|
|
22
|
+
from eosquality.scores.extremity import Extremity
|
|
23
|
+
from eosquality.scores.reference_match import ReferenceMatch
|
|
24
|
+
from eosquality.scores.typicality import Typicality
|
|
25
|
+
from eosquality.shared.fit import fit_shared
|
|
26
|
+
from eosquality.utils import console
|
|
27
|
+
from eosquality.utils.logging import logger
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def fit_reference(
|
|
31
|
+
eq,
|
|
32
|
+
reference: pd.DataFrame,
|
|
33
|
+
*,
|
|
34
|
+
eos_id: str,
|
|
35
|
+
version: str,
|
|
36
|
+
library: str | pathlib.Path | None,
|
|
37
|
+
scores: Iterable[str],
|
|
38
|
+
max_features: int | None,
|
|
39
|
+
) -> None:
|
|
40
|
+
"""Fit the reference-modality components of ``eq`` on the reference predictions.
|
|
41
|
+
|
|
42
|
+
Parameters
|
|
43
|
+
----------
|
|
44
|
+
eq : ErsiliaQuality
|
|
45
|
+
The orchestrator to fill (``_shared``, the score attributes).
|
|
46
|
+
reference : pandas.DataFrame
|
|
47
|
+
Predictions on the reference library, in library order.
|
|
48
|
+
eos_id, version : str
|
|
49
|
+
Model identifier and dataset version.
|
|
50
|
+
library : str, pathlib.Path or None
|
|
51
|
+
Custom reference-library folder, or ``None`` for the resolved
|
|
52
|
+
canonical library.
|
|
53
|
+
scores : iterable of str
|
|
54
|
+
Reference components to fit (``SCORE_ORDER`` names).
|
|
55
|
+
max_features : int or None
|
|
56
|
+
Feature-selection cap.
|
|
57
|
+
"""
|
|
58
|
+
scores_set = set(scores)
|
|
59
|
+
requested = [n for n in SCORE_ORDER if n in scores_set]
|
|
60
|
+
steps = console.Steps(3 + len(requested))
|
|
61
|
+
with console.section("Reference modality") as section:
|
|
62
|
+
with steps("Validate reference predictions") as st:
|
|
63
|
+
_validate_reference(reference)
|
|
64
|
+
st.summary = f"{len(reference):,} molecules · {console.plural(len(requested), 'score')}"
|
|
65
|
+
logger.info(
|
|
66
|
+
f"fit | eos_id={eos_id} version={version} scores=[{', '.join(requested)}]"
|
|
67
|
+
)
|
|
68
|
+
with steps("Load the reference library") as st:
|
|
69
|
+
lib = ReferenceLibrary.load(library)
|
|
70
|
+
lib.validate_smiles(list(reference["input"]))
|
|
71
|
+
st.summary = (
|
|
72
|
+
f"{console.plain(lib.library_name or 'custom library')} · "
|
|
73
|
+
f"{lib.n_reference:,} molecules match the reference"
|
|
74
|
+
)
|
|
75
|
+
with steps("Shared state: schema, scaling, feature selection") as st:
|
|
76
|
+
shared = fit_shared(
|
|
77
|
+
reference,
|
|
78
|
+
eos_id=eos_id,
|
|
79
|
+
version=version,
|
|
80
|
+
library_id=lib.library_name,
|
|
81
|
+
library_path=""
|
|
82
|
+
if _is_canonical(lib, library)
|
|
83
|
+
else str(lib.path.resolve()),
|
|
84
|
+
max_features=max_features,
|
|
85
|
+
)
|
|
86
|
+
st.summary = (
|
|
87
|
+
f"{console.plural(len(shared.schema.columns), 'output')} → "
|
|
88
|
+
f"{len(shared.selected_columns)} selected"
|
|
89
|
+
)
|
|
90
|
+
eq._shared = shared
|
|
91
|
+
fitters = _fitters(reference, shared, lib)
|
|
92
|
+
for name in requested:
|
|
93
|
+
with steps(f"Score: {score_name(name)}") as st:
|
|
94
|
+
setattr(eq, name, fitters[name]())
|
|
95
|
+
st.summary = getattr(getattr(eq, name), "fit_summary", None)
|
|
96
|
+
anchor = getattr(getattr(eq, name), "anchor_", None)
|
|
97
|
+
logger.info(f"score {name!r} | fitted | reference={anchor}")
|
|
98
|
+
section.summary = f"{console.plural(len(requested), 'score')} fitted"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _is_canonical(lib: ReferenceLibrary, requested) -> bool:
|
|
102
|
+
"""Whether ``lib`` is this install's canonical library, found by its identity.
|
|
103
|
+
|
|
104
|
+
A library passed explicitly, or one of another name (an environment-variable
|
|
105
|
+
override), is recorded by its path instead, so ``run`` finds it again.
|
|
106
|
+
"""
|
|
107
|
+
return requested is None and lib.library_name == LIBRARY_ID
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _fitters(reference, shared, library):
|
|
111
|
+
"""Zero-argument fitters for each reference score."""
|
|
112
|
+
return {
|
|
113
|
+
"typicality": lambda: Typicality().fit(reference, shared=shared),
|
|
114
|
+
"extremity": lambda: Extremity().fit(reference, shared=shared),
|
|
115
|
+
"match": lambda: ReferenceMatch().fit(
|
|
116
|
+
reference, shared=shared, library=library
|
|
117
|
+
),
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _validate_reference(reference: pd.DataFrame) -> None:
|
|
122
|
+
"""Check the reference table: non-empty, SMILES input column, unique keys."""
|
|
123
|
+
if reference.empty:
|
|
124
|
+
raise SchemaError("Reference DataFrame is empty.")
|
|
125
|
+
validate_input_column(reference)
|
|
126
|
+
check_unique_keys(reference)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def run_reference(
|
|
130
|
+
eq,
|
|
131
|
+
query: pd.DataFrame,
|
|
132
|
+
components: dict[str, Any],
|
|
133
|
+
columns: dict[str, pd.Series],
|
|
134
|
+
metadata: dict[str, Any],
|
|
135
|
+
features: QueryFeatures | None = None,
|
|
136
|
+
) -> pd.DataFrame | None:
|
|
137
|
+
"""Run the reference-modality components, filling ``columns``/``metadata``.
|
|
138
|
+
|
|
139
|
+
Parameters
|
|
140
|
+
----------
|
|
141
|
+
eq : ErsiliaQuality
|
|
142
|
+
The fitted orchestrator.
|
|
143
|
+
query : pandas.DataFrame
|
|
144
|
+
Query predictions.
|
|
145
|
+
components : dict
|
|
146
|
+
Fitted reference components, by name, in canonical order.
|
|
147
|
+
columns : dict of str to pandas.Series
|
|
148
|
+
Output score columns; filled in place.
|
|
149
|
+
metadata : dict
|
|
150
|
+
Run metadata; filled in place.
|
|
151
|
+
features : QueryFeatures, optional
|
|
152
|
+
The query's SMILES features, shared with the training scores.
|
|
153
|
+
|
|
154
|
+
Returns
|
|
155
|
+
-------
|
|
156
|
+
pandas.DataFrame or None
|
|
157
|
+
The reference details table (per-column typicality and extremity, one
|
|
158
|
+
row per query), or None when neither is fitted.
|
|
159
|
+
"""
|
|
160
|
+
assert eq._shared is not None
|
|
161
|
+
results: dict[str, Any] = {}
|
|
162
|
+
steps = console.Steps(1 + len(components))
|
|
163
|
+
with console.section("Reference modality") as section:
|
|
164
|
+
with steps("Validate and scale the query") as st:
|
|
165
|
+
validate_against_schema(query, eq._shared.schema)
|
|
166
|
+
query_repr = _make_query_repr(eq._shared, query)
|
|
167
|
+
st.summary = (
|
|
168
|
+
f"{query_repr.shape[0]:,} molecules · "
|
|
169
|
+
f"{console.plural(query_repr.shape[1], 'feature')}"
|
|
170
|
+
)
|
|
171
|
+
metadata["n_reference"] = eq._shared.metadata.n_samples
|
|
172
|
+
for name, component in components.items():
|
|
173
|
+
column = score_name(name)
|
|
174
|
+
with steps(f"Score: {column}") as st:
|
|
175
|
+
result = _run_component(name, component, query, query_repr, features)
|
|
176
|
+
st.summary = (
|
|
177
|
+
console.share_summary(result.match)
|
|
178
|
+
if name == "match"
|
|
179
|
+
else console.median_summary(result.score)
|
|
180
|
+
)
|
|
181
|
+
if name == "match":
|
|
182
|
+
columns[result.match.name] = result.match
|
|
183
|
+
columns[result.scaffold.name] = result.scaffold
|
|
184
|
+
else:
|
|
185
|
+
columns[result.score.name] = result.score
|
|
186
|
+
columns[result.score_raw.name] = result.score_raw
|
|
187
|
+
results[name] = result
|
|
188
|
+
logger.info(
|
|
189
|
+
f"score {name!r} | mean={float(result.score.mean()):.4f} "
|
|
190
|
+
f"raw mean={float(result.score_raw.mean()):.4f}"
|
|
191
|
+
)
|
|
192
|
+
metadata.update({f"{column}_{k}": v for k, v in result.metadata.items()})
|
|
193
|
+
section.summary = console.plural(len(components), "score")
|
|
194
|
+
return _reference_details(query, results) if results else None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _reference_details(query: pd.DataFrame, results: dict[str, Any]) -> pd.DataFrame:
|
|
198
|
+
"""Per-column values of each query, ``<column>_<score>_raw`` / ``_pct``.
|
|
199
|
+
|
|
200
|
+
Parameters
|
|
201
|
+
----------
|
|
202
|
+
query : pandas.DataFrame
|
|
203
|
+
Query predictions.
|
|
204
|
+
results : dict
|
|
205
|
+
Typicality and/or extremity run results, by component name.
|
|
206
|
+
|
|
207
|
+
Returns
|
|
208
|
+
-------
|
|
209
|
+
pandas.DataFrame
|
|
210
|
+
``key``, ``input`` (when given), then per score and column the raw
|
|
211
|
+
value and the percentile on that column's reference distribution.
|
|
212
|
+
"""
|
|
213
|
+
parts = {"key": query_keys(query)}
|
|
214
|
+
if "input" in query.columns:
|
|
215
|
+
parts["input"] = query["input"].tolist()
|
|
216
|
+
for name, result in results.items():
|
|
217
|
+
for column in result.per_feature.columns:
|
|
218
|
+
parts[f"{column}_{name}_raw"] = result.per_feature[column].to_numpy()
|
|
219
|
+
parts[f"{column}_{name}_pct"] = result.per_feature_pct[column].to_numpy()
|
|
220
|
+
return pd.DataFrame(parts)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _run_component(name, component, query, query_repr, features):
|
|
224
|
+
"""Run one reference component with the precomputed shared inputs."""
|
|
225
|
+
if name in ("typicality", "extremity"):
|
|
226
|
+
return component.run(query, query_repr=query_repr)
|
|
227
|
+
return component.run(query, features)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def validate_input_column(reference: pd.DataFrame) -> None:
|
|
231
|
+
"""Require a non-empty ``input`` SMILES column without NaN.
|
|
232
|
+
|
|
233
|
+
Parameters
|
|
234
|
+
----------
|
|
235
|
+
reference : pandas.DataFrame
|
|
236
|
+
The reference predictions.
|
|
237
|
+
"""
|
|
238
|
+
if "input" not in reference.columns:
|
|
239
|
+
raise SchemaError(
|
|
240
|
+
"Reference DataFrame must contain an 'input' column with SMILES "
|
|
241
|
+
"strings, to check it against the reference library."
|
|
242
|
+
)
|
|
243
|
+
null_smiles = reference["input"].isna()
|
|
244
|
+
if null_smiles.any():
|
|
245
|
+
raise SchemaError(
|
|
246
|
+
f"Reference 'input' column has {int(null_smiles.sum())} NaN value(s). "
|
|
247
|
+
"All SMILES must be valid strings."
|
|
248
|
+
)
|
|
249
|
+
empty_smiles = reference["input"] == ""
|
|
250
|
+
if empty_smiles.any():
|
|
251
|
+
raise SchemaError(
|
|
252
|
+
f"Reference 'input' column has {int(empty_smiles.sum())} empty string(s). "
|
|
253
|
+
"All SMILES must be non-empty."
|
|
254
|
+
)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def check_unique_keys(reference: pd.DataFrame) -> None:
|
|
258
|
+
"""Require unique values in the ``key`` column, if present.
|
|
259
|
+
|
|
260
|
+
Parameters
|
|
261
|
+
----------
|
|
262
|
+
reference : pandas.DataFrame
|
|
263
|
+
The reference predictions.
|
|
264
|
+
"""
|
|
265
|
+
if "key" not in reference.columns:
|
|
266
|
+
return
|
|
267
|
+
keys = reference["key"].astype(str)
|
|
268
|
+
dupes = keys[keys.duplicated()]
|
|
269
|
+
if len(dupes):
|
|
270
|
+
n_shown = min(5, len(dupes))
|
|
271
|
+
examples = ", ".join(
|
|
272
|
+
f"row {i}: {k!r}" for i, k in list(dupes.items())[:n_shown]
|
|
273
|
+
)
|
|
274
|
+
raise ValueError(
|
|
275
|
+
f"Duplicate keys in reference: {len(dupes)} duplicate(s). "
|
|
276
|
+
f"First {n_shown}: [{examples}]. "
|
|
277
|
+
"The 'key' column must be unique across rows."
|
|
278
|
+
)
|