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.
Files changed (66) hide show
  1. eosquality/__init__.py +100 -0
  2. eosquality/_artifacts.py +263 -0
  3. eosquality/_reference_modality.py +278 -0
  4. eosquality/_registry.py +97 -0
  5. eosquality/_training_modality.py +306 -0
  6. eosquality/cli/__init__.py +133 -0
  7. eosquality/cli/_common.py +144 -0
  8. eosquality/cli/build.py +252 -0
  9. eosquality/cli/fit.py +234 -0
  10. eosquality/cli/run.py +238 -0
  11. eosquality/cli/setup.py +86 -0
  12. eosquality/exceptions.py +28 -0
  13. eosquality/library/__init__.py +20 -0
  14. eosquality/library/download.py +182 -0
  15. eosquality/library/identity.py +178 -0
  16. eosquality/library/physchem.py +241 -0
  17. eosquality/library/physchem_cache.py +210 -0
  18. eosquality/library/physchem_scaler.json +880 -0
  19. eosquality/library/reference.py +190 -0
  20. eosquality/preprocess.py +146 -0
  21. eosquality/py.typed +0 -0
  22. eosquality/quality.py +548 -0
  23. eosquality/results.py +40 -0
  24. eosquality/schema/__init__.py +1 -0
  25. eosquality/schema/infer.py +89 -0
  26. eosquality/schema/models.py +28 -0
  27. eosquality/scores/__init__.py +19 -0
  28. eosquality/scores/_base.py +247 -0
  29. eosquality/scores/_helpers.py +305 -0
  30. eosquality/scores/_match_keys.py +170 -0
  31. eosquality/scores/_percentile_score.py +232 -0
  32. eosquality/scores/_physchem_domain.py +315 -0
  33. eosquality/scores/_training_helpers.py +162 -0
  34. eosquality/scores/extremity.py +159 -0
  35. eosquality/scores/reference_match.py +207 -0
  36. eosquality/scores/training_distance.py +319 -0
  37. eosquality/scores/training_match.py +187 -0
  38. eosquality/scores/training_physchem.py +237 -0
  39. eosquality/scores/typicality.py +315 -0
  40. eosquality/shared/__init__.py +13 -0
  41. eosquality/shared/feature_selection.py +168 -0
  42. eosquality/shared/fit.py +84 -0
  43. eosquality/shared/load.py +71 -0
  44. eosquality/shared/metadata.py +72 -0
  45. eosquality/shared/save.py +55 -0
  46. eosquality/shared/state.py +72 -0
  47. eosquality/training/__init__.py +27 -0
  48. eosquality/training/data.py +284 -0
  49. eosquality/training/state.py +220 -0
  50. eosquality/utils/__init__.py +1 -0
  51. eosquality/utils/console/__init__.py +82 -0
  52. eosquality/utils/console/_core.py +135 -0
  53. eosquality/utils/console/bars.py +78 -0
  54. eosquality/utils/console/display.py +161 -0
  55. eosquality/utils/console/fmt.py +143 -0
  56. eosquality/utils/console/steps.py +116 -0
  57. eosquality/utils/identifiers.py +127 -0
  58. eosquality/utils/logging.py +300 -0
  59. eosquality/utils/parallel.py +160 -0
  60. eosquality/vectorindex.py +304 -0
  61. eosquality-0.2.1.dist-info/METADATA +132 -0
  62. eosquality-0.2.1.dist-info/RECORD +66 -0
  63. eosquality-0.2.1.dist-info/WHEEL +5 -0
  64. eosquality-0.2.1.dist-info/entry_points.txt +2 -0
  65. eosquality-0.2.1.dist-info/licenses/LICENSE +674 -0
  66. eosquality-0.2.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,97 @@
1
+ """Score names, canonical order and constants shared by the orchestrator and the CLI.
2
+
3
+ Constants only, with no heavy imports: the CLI reads them to build its help
4
+ text, so importing this module must stay cheap (see ``tests/test_startup.py``).
5
+ The component classes are mapped in :mod:`eosquality._artifacts`.
6
+
7
+ Every score has an internal **component** name (the attribute on
8
+ :class:`~eosquality.quality.ErsiliaQuality` and the artifacts subfolder) and a
9
+ public **score** name, prefixed by modality: ``ref_`` for scores fitted on
10
+ the reference library predictions, ``trn_`` for scores fitted on the
11
+ training sets. Public names are the output columns and the values accepted
12
+ by ``exclude`` (``--exclude`` in the CLI).
13
+ """
14
+
15
+ # Feature-selection cap of the shared state (``fit_shared``).
16
+ DEFAULT_MAX_FEATURES = 10
17
+
18
+ # Canonical component order: fit, run, save, output columns and metadata.
19
+ SCORE_ORDER: tuple[str, ...] = (
20
+ "typicality",
21
+ "extremity",
22
+ "match",
23
+ )
24
+ # Training-modality components (present iff training sets were fit).
25
+ TRAINING_ORDER: tuple[str, ...] = (
26
+ "training_distance",
27
+ "training_physchem",
28
+ "training_match",
29
+ )
30
+
31
+ # Component → public score name (and output column prefix).
32
+ SCORE_NAMES: dict[str, str] = {
33
+ "typicality": "ref_typicality",
34
+ "extremity": "ref_extremity",
35
+ "match": "ref_match",
36
+ "training_distance": "trn_tanimoto",
37
+ "training_physchem": "trn_physchem",
38
+ "training_match": "trn_match",
39
+ }
40
+ # Scores that emit a second output column of their own, for display: the match
41
+ # scores also write the scaffold flag.
42
+ ALSO_EMITS: dict[str, tuple[str, ...]] = {
43
+ "ref_match": ("ref_scaffold",),
44
+ "trn_match": ("trn_scaffold",),
45
+ }
46
+ COMPONENTS: dict[str, str] = {score: comp for comp, score in SCORE_NAMES.items()}
47
+ REFERENCE_SCORES: tuple[str, ...] = tuple(SCORE_NAMES[c] for c in SCORE_ORDER)
48
+ TRAINING_SCORES: tuple[str, ...] = tuple(SCORE_NAMES[c] for c in TRAINING_ORDER)
49
+ ALL_SCORES: tuple[str, ...] = REFERENCE_SCORES + TRAINING_SCORES
50
+
51
+ # Scores that read the reference library at fit and run time.
52
+ LIBRARY_USERS = frozenset({"match"})
53
+
54
+
55
+ def score_name(component: str) -> str:
56
+ """Public, modality-prefixed score name of a component.
57
+
58
+ Parameters
59
+ ----------
60
+ component : str
61
+ Internal component name, e.g. ``"match"``.
62
+
63
+ Returns
64
+ -------
65
+ str
66
+ e.g. ``"ref_match"``.
67
+ """
68
+ return SCORE_NAMES[component]
69
+
70
+
71
+ def split_exclude(exclude) -> tuple[set[str], set[str]]:
72
+ """Validate excluded score names; return the excluded components per modality.
73
+
74
+ Parameters
75
+ ----------
76
+ exclude : iterable of str
77
+ Public score names (``ALL_SCORES``).
78
+
79
+ Returns
80
+ -------
81
+ tuple of (set of str, set of str)
82
+ Excluded reference components and excluded training components.
83
+
84
+ Raises
85
+ ------
86
+ ValueError
87
+ If a name is not a score.
88
+ """
89
+ names = set(exclude or ())
90
+ unknown = sorted(names - set(ALL_SCORES))
91
+ if unknown:
92
+ raise ValueError(
93
+ f"Unknown score(s) {unknown}; choose from: {', '.join(ALL_SCORES)} "
94
+ "(`ref_match` and `trn_match` also control their `_scaffold` flags)."
95
+ )
96
+ components = {COMPONENTS[n] for n in names}
97
+ return components & set(SCORE_ORDER), components & set(TRAINING_ORDER)
@@ -0,0 +1,306 @@
1
+ """Training modality of :class:`~eosquality.quality.ErsiliaQuality`: fit and run.
2
+
3
+ Module-level functions taking the orchestrator instance ``eq``, like
4
+ ``_reference_modality.py``, so that ``quality.py`` stays a readable façade.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+
14
+ from eosquality._registry import TRAINING_ORDER, score_name
15
+ from eosquality.scores._helpers import query_keys
16
+ from eosquality.scores._training_helpers import QueryFeatures
17
+ from eosquality.scores.training_distance import TrainingDistance
18
+ from eosquality.scores.training_match import TrainingMatch
19
+ from eosquality.scores.training_physchem import TrainingPhyschem
20
+ from eosquality.shared.feature_selection import select_by_shared_molecules
21
+ from eosquality.training.data import load_training
22
+ from eosquality.training.state import fit_training
23
+ from eosquality.utils import console
24
+ from eosquality.utils.logging import logger
25
+
26
+ # Column order of the training details table; columns of an unfitted score are
27
+ # simply absent. The scores CSV carries the pct / raw pairs and the two flags;
28
+ # the nearest-neighbour table stays in this table.
29
+ _DETAILS_ORDER = (
30
+ "key",
31
+ "input",
32
+ "trn_tanimoto_pct",
33
+ "trn_tanimoto_raw",
34
+ "trn_physchem_pct",
35
+ "trn_physchem_raw",
36
+ "trn_physchem_dist",
37
+ "trn_match",
38
+ "trn_scaffold",
39
+ "trn_in_training",
40
+ "nn1_similarity",
41
+ "nn_smiles",
42
+ "nn_keys",
43
+ "nn_similarities",
44
+ "nn_columns",
45
+ )
46
+
47
+
48
+ # The scores fitted the same way: from the training state alone, in run order.
49
+ _PLAIN_SCORES = {
50
+ "training_distance": TrainingDistance,
51
+ "training_physchem": TrainingPhyschem,
52
+ "training_match": TrainingMatch,
53
+ }
54
+
55
+
56
+ def load_training_sets(training_sets, output_columns=None) -> dict:
57
+ """Load the training sets, in their own console section.
58
+
59
+ Parameters
60
+ ----------
61
+ training_sets : str or pathlib.Path
62
+ Folder with one ``<output_column>.csv`` per column.
63
+ output_columns : list of str, optional
64
+ The reference's output columns; every file must name one of them.
65
+
66
+ Returns
67
+ -------
68
+ dict of str to TrainingColumn
69
+ The usable columns (at least ``MIN_TRAINING_MOLECULES`` molecules).
70
+ """
71
+ steps = console.Steps(1)
72
+ with console.section("Training sets") as section:
73
+ with steps("Load and standardise the training sets") as st:
74
+ columns = load_training(training_sets, output_columns)
75
+ st.summary = console.plural(len(columns), "column")
76
+ console.table(
77
+ ("column", "molecules", "unparsable"),
78
+ [
79
+ (c.name, f"{c.n:,}", f"{c.n_unparsable:,}" if c.n_unparsable else "")
80
+ for c in columns.values()
81
+ ],
82
+ )
83
+ _warn_data_issues(columns)
84
+ if output_columns is not None and len(columns) < len(output_columns):
85
+ console.detail(
86
+ [
87
+ (
88
+ "reference",
89
+ f"restricted to these {len(columns)} of "
90
+ f"{len(output_columns)} output columns",
91
+ )
92
+ ]
93
+ )
94
+ section.summary = console.plural(len(columns), "column")
95
+ return columns
96
+
97
+
98
+ def select_training_columns(columns: dict, shared, max_features) -> dict:
99
+ """The training columns to fit: at most ``max_features`` of them.
100
+
101
+ With a reference modality they are the reference's selected columns (its
102
+ feature selection ran on the columns with a training set). Training-only,
103
+ the largest training set of each overlap cluster is kept
104
+ (:func:`~eosquality.shared.feature_selection.select_by_shared_molecules`).
105
+
106
+ Parameters
107
+ ----------
108
+ columns : dict of str to TrainingColumn
109
+ The usable training sets.
110
+ shared : SharedFitState or None
111
+ The fitted reference shared state, if any.
112
+ max_features : int, optional
113
+ Column cap; ``None`` disables it (training-only fits).
114
+
115
+ Returns
116
+ -------
117
+ dict of str to TrainingColumn
118
+ The kept columns, in input order.
119
+ """
120
+ if shared is not None:
121
+ keep = set(shared.selected_columns)
122
+ names = [n for n in columns if n in keep]
123
+ else:
124
+ names = select_by_shared_molecules(
125
+ {n: set(c.all_smiles) for n, c in columns.items()}, max_features
126
+ )
127
+ if len(names) < len(columns):
128
+ logger.info(
129
+ f"training | {len(names)} of {len(columns)} columns selected: "
130
+ + ", ".join(names)
131
+ )
132
+ return {n: columns[n] for n in names}
133
+
134
+
135
+ def _warn_data_issues(columns: dict) -> None:
136
+ """One warning for the rows the training-set cleaning dropped."""
137
+ bad = sum(c.n_unparsable for c in columns.values())
138
+ if bad:
139
+ logger.warning(
140
+ f"training sets | {bad:,} unparsable SMILES dropped; per column in the "
141
+ "table above and the log"
142
+ )
143
+
144
+
145
+ def fit_training_modality(
146
+ eq,
147
+ columns: dict,
148
+ *,
149
+ eos_id: str,
150
+ version: str,
151
+ skip: set[str] = frozenset(),
152
+ n_loaded: int | None = None,
153
+ ) -> None:
154
+ """Fit the training components of ``eq`` on loaded training sets.
155
+
156
+ Parameters
157
+ ----------
158
+ eq : ErsiliaQuality
159
+ The orchestrator; its training state and components are replaced.
160
+ columns : dict of str to TrainingColumn
161
+ Training sets from :func:`load_training_sets`.
162
+ eos_id, version : str
163
+ Model id and version.
164
+ skip : set of str, optional
165
+ Training components not to fit (``TRAINING_ORDER`` names).
166
+ n_loaded : int, optional
167
+ Number of usable columns before selection, for the console.
168
+ """
169
+ scores = {name: cls for name, cls in _PLAIN_SCORES.items() if name not in skip}
170
+ steps = console.Steps(1 + len(scores))
171
+ with console.section("Training modality") as section:
172
+ if n_loaded is not None and n_loaded > len(columns):
173
+ console.detail(
174
+ [
175
+ (
176
+ "columns",
177
+ f"{len(columns)} of {n_loaded} selected: {', '.join(columns)}",
178
+ )
179
+ ]
180
+ )
181
+ with steps("Build a Morgan index per distinct training set") as st:
182
+ eq._training = fit_training(columns, eos_id=eos_id, version=version)
183
+ st.summary = (
184
+ f"{len({id(v) for v in eq._training.indices.values()})} index(es)"
185
+ )
186
+ for name in _PLAIN_SCORES:
187
+ setattr(eq, name, None)
188
+ for name, cls in scores.items():
189
+ with steps(f"Score: {score_name(name)}") as st:
190
+ component = cls().fit(training=eq._training, shared=eq._shared)
191
+ setattr(eq, name, component)
192
+ st.summary = component.fit_summary
193
+ section.summary = console.plural(len(columns), "column")
194
+
195
+
196
+ def _assemble_details(
197
+ query: pd.DataFrame, details: pd.DataFrame | None, extras: dict[str, Any]
198
+ ) -> pd.DataFrame | None:
199
+ """Add the per-query values kept out of the scores CSV to the details table.
200
+
201
+ Parameters
202
+ ----------
203
+ query : pandas.DataFrame
204
+ The query, in row order (used for ``key`` / ``input`` when training
205
+ distance, which normally supplies them, is not fitted).
206
+ details : pandas.DataFrame or None
207
+ The training distance details, or None when it is not fitted.
208
+ extras : dict
209
+ Column name to per-query values (aligned with ``query``).
210
+
211
+ Returns
212
+ -------
213
+ pandas.DataFrame or None
214
+ The table in ``_DETAILS_ORDER``; None when there is nothing to report.
215
+ """
216
+ if details is None:
217
+ if not extras:
218
+ return None
219
+ details = pd.DataFrame(
220
+ {"key": query_keys(query), "input": query["input"].tolist()}
221
+ )
222
+ for name, values in extras.items():
223
+ details[name] = np.asarray(values)
224
+ ordered = [c for c in _DETAILS_ORDER if c in details.columns]
225
+ return details[ordered + [c for c in details.columns if c not in ordered]]
226
+
227
+
228
+ def _emit(columns: dict, extras: dict, *series: pd.Series) -> None:
229
+ """Put each Series in the scores columns and in the details extras."""
230
+ for ser in series:
231
+ columns[ser.name] = ser
232
+ extras[ser.name] = ser.to_numpy()
233
+
234
+
235
+ def run_training(
236
+ eq,
237
+ query: pd.DataFrame,
238
+ columns: dict[str, pd.Series],
239
+ metadata: dict[str, Any],
240
+ features: QueryFeatures | None = None,
241
+ ) -> pd.DataFrame | None:
242
+ """Run the fitted training components, filling ``columns`` and ``metadata``.
243
+
244
+ ``columns`` receives ``trn_tanimoto_pct`` / ``_raw``, ``trn_physchem_pct`` /
245
+ ``_raw``, ``trn_match`` and ``trn_scaffold``. The returned details table
246
+ repeats them, and adds ``trn_physchem_dist``, the nearest training
247
+ molecules and ``trn_in_training``.
248
+
249
+ Parameters
250
+ ----------
251
+ eq : ErsiliaQuality
252
+ The orchestrator.
253
+ query : pandas.DataFrame
254
+ Query with an ``input`` SMILES column.
255
+ columns : dict of str to pandas.Series
256
+ Score columns, updated in place.
257
+ metadata : dict
258
+ Run metadata, updated in place.
259
+ features : QueryFeatures, optional
260
+ The query's features, shared with the reference match (built from
261
+ ``query`` when omitted).
262
+
263
+ Returns
264
+ -------
265
+ pandas.DataFrame or None
266
+ The training details table (one row per query), or None when no
267
+ training score is fitted.
268
+ """
269
+ fitted = [
270
+ (name, getattr(eq, name))
271
+ for name in TRAINING_ORDER
272
+ if getattr(eq, name) is not None
273
+ ]
274
+ if not fitted:
275
+ return None
276
+ steps = console.Steps(len(fitted))
277
+ details = None
278
+ extras: dict[str, Any] = {}
279
+ if features is None:
280
+ features = QueryFeatures.from_frame(query)
281
+ n_bad = features.n_rows - len(features.smiles)
282
+ if n_bad and eq._shared is None: # the reference modality already warned
283
+ logger.warning(
284
+ f"{n_bad:,} query row(s) have a missing or unparsable SMILES; their "
285
+ "training scores are NaN."
286
+ )
287
+ with console.section("Training modality"):
288
+ for component, instance in fitted:
289
+ name = score_name(component)
290
+ with steps(f"Score: {name}") as st:
291
+ result = instance.run(query, features)
292
+ st.summary = (
293
+ console.share_summary(result.match)
294
+ if component == "training_match"
295
+ else console.median_summary(result.score)
296
+ )
297
+ metadata.update({f"{name}_{k}": v for k, v in result.metadata.items()})
298
+ if component == "training_match":
299
+ _emit(columns, extras, result.match, result.scaffold)
300
+ elif component == "training_physchem":
301
+ _emit(columns, extras, result.score, result.score_raw)
302
+ extras[result.distance.name] = result.distance.to_numpy()
303
+ else:
304
+ _emit(columns, extras, result.score, result.score_raw)
305
+ details = result.details
306
+ return _assemble_details(query, details, extras)
@@ -0,0 +1,133 @@
1
+ """Top-level command-line interface for eosquality.
2
+
3
+ Each subcommand lives in its own module under this package:
4
+
5
+ - :mod:`eosquality.cli.build` defines ``build``.
6
+ - :mod:`eosquality.cli.setup` defines ``setup``.
7
+ - :mod:`eosquality.cli.fit` defines ``fit``.
8
+ - :mod:`eosquality.cli.run` defines ``run``.
9
+
10
+ This module is the Click group that dispatches to them.
11
+
12
+ End-user workflow
13
+ -----------------
14
+ Each release is pinned to a canonical reference library, resolved locally
15
+ from ``$EOSQUALITY_REFERENCE_LIBRARY_PATH`` → ``./data/indices/<library>/``
16
+ → ``~/.eosquality/indices/<library>/``. Fetch it once with
17
+ ``eosquality setup``; after that the usual path is fit then run::
18
+
19
+ eosquality fit -r reference_eos4e40_v1.csv -a artifacts_eos4e40_v1/ [-t training_eos4e40_v1/]
20
+ eosquality run -i query_eos4e40_v1.csv -a artifacts_eos4e40_v1/ -o quality_eos4e40_v1.csv
21
+
22
+ File and folder names carry the model: ``[prefix_]<eos_id>_<version>``.
23
+
24
+ Fetch the library explicitly (useful for CI or airgapped setups)::
25
+
26
+ eosquality setup [--force]
27
+
28
+ For maintainers / advanced use
29
+ ------------------------------
30
+ ``eosquality build`` prepares a reference-library folder (the SMILES, a
31
+ metadata file and the connectivity keys of ``ref_match``) from a SMILES
32
+ library CSV. It is a release tool — ordinary users should not need to run it.
33
+ Use it to produce a new canonical library for the next major release, or to
34
+ build a non-canonical library for internal testing and fit against it::
35
+
36
+ eosquality build --input library.csv --output /tmp/lib/ --name my_test_library
37
+ EOSQUALITY_REFERENCE_LIBRARY_PATH=/tmp/lib/ eosquality fit -r reference_eos4e40_v1.csv -a artifacts_eos4e40_v1/
38
+ """
39
+
40
+ import importlib.metadata
41
+
42
+ import click
43
+
44
+ from eosquality.cli.build import build
45
+ from eosquality.cli.fit import fit
46
+ from eosquality.cli.run import run
47
+ from eosquality.cli.setup import setup
48
+
49
+ try:
50
+ _VERSION = importlib.metadata.version("eosquality")
51
+ except importlib.metadata.PackageNotFoundError:
52
+ _VERSION = "unknown"
53
+
54
+
55
+ # Commands for maintainers, listed in their own help block.
56
+ DEVELOPER_COMMANDS = ("build",)
57
+
58
+
59
+ class _SectionedGroup(click.Group):
60
+ """Click group whose help lists user and developer commands separately."""
61
+
62
+ def list_commands(self, ctx: click.Context) -> list[str]:
63
+ """Commands in the order they were added.
64
+
65
+ Parameters
66
+ ----------
67
+ ctx : click.Context
68
+ Current context.
69
+
70
+ Returns
71
+ -------
72
+ list of str
73
+ Command names.
74
+ """
75
+ return list(self.commands)
76
+
77
+ def format_commands(
78
+ self, ctx: click.Context, formatter: click.HelpFormatter
79
+ ) -> None:
80
+ """Write the "Commands" and "Developer commands" help blocks.
81
+
82
+ Parameters
83
+ ----------
84
+ ctx : click.Context
85
+ Current context.
86
+ formatter : click.HelpFormatter
87
+ Help formatter to write into.
88
+ """
89
+ rows = {
90
+ name: (name, cmd.get_short_help_str(limit=formatter.width))
91
+ for name, cmd in self.commands.items()
92
+ if not cmd.hidden
93
+ }
94
+ user = [r for n, r in rows.items() if n not in DEVELOPER_COMMANDS]
95
+ dev = [r for n, r in rows.items() if n in DEVELOPER_COMMANDS]
96
+ if user:
97
+ with formatter.section("Commands"):
98
+ formatter.write_dl(user)
99
+ if dev:
100
+ with formatter.section("Developer commands (maintainers only)"):
101
+ formatter.write_dl(dev)
102
+
103
+
104
+ @click.group(
105
+ cls=_SectionedGroup,
106
+ help="Assess the quality of Ersilia model predictions.",
107
+ context_settings={"help_option_names": ["-h", "--help"]},
108
+ )
109
+ @click.version_option(_VERSION, prog_name="eosquality")
110
+ def cli() -> None:
111
+ """Every subcommand prints curated progress (``-v`` adds DEBUG logs)."""
112
+
113
+
114
+ # In workflow order: setup once, then fit per model, then run per query set.
115
+ cli.add_command(setup)
116
+ cli.add_command(fit)
117
+ cli.add_command(run)
118
+ cli.add_command(build)
119
+
120
+
121
+ def main(argv: list[str] | None = None) -> None:
122
+ """Run the CLI on ``argv`` (default ``sys.argv[1:]``) and exit with its status.
123
+
124
+ Parameters
125
+ ----------
126
+ argv : list of str, optional
127
+ Command-line arguments, without the program name.
128
+ """
129
+ cli.main(args=argv, prog_name="eosquality")
130
+
131
+
132
+ if __name__ == "__main__":
133
+ main()
@@ -0,0 +1,144 @@
1
+ """Helpers shared by the CLI commands: curated output, log files, failure handling."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import pathlib
7
+ import shutil
8
+ import tempfile
9
+ from contextlib import contextmanager
10
+
11
+ import click
12
+
13
+ from eosquality import set_verbosity
14
+ from eosquality.utils import console, parallel
15
+ from eosquality.utils.logging import logger
16
+
17
+
18
+ class CliError(Exception):
19
+ """A user-facing error: printed as ``✖ error: <message>`` and exit status 1."""
20
+
21
+
22
+ def require_new_path(path: str, what: str = "output path") -> None:
23
+ """Raise :class:`CliError` if ``path`` already exists.
24
+
25
+ Parameters
26
+ ----------
27
+ path : str
28
+ Path that must not exist yet.
29
+ what : str, optional
30
+ How to name the path in the error message.
31
+ """
32
+ if os.path.exists(path):
33
+ raise CliError(
34
+ f"{what} '{path}' already exists; delete or move it before re-running."
35
+ )
36
+
37
+
38
+ def run_command(fn, *, verbose: bool, command: str, jobs: int | None = None) -> None:
39
+ """Run a command body with curated output; failures become ``✖ error:`` lines.
40
+
41
+ Turns the curated console on in the command's accent colour, and restores
42
+ the previous console and verbosity state on exit. With ``verbose``, DEBUG
43
+ logs and full tracebacks also go to the terminal; otherwise tracebacks
44
+ only reach the command's log file (see ``Logger.log_file``).
45
+
46
+ Parameters
47
+ ----------
48
+ fn : callable
49
+ Zero-argument function holding the command's work.
50
+ verbose : bool
51
+ Enable DEBUG logging and on-screen tracebacks.
52
+ command : str
53
+ Command name, for its accent colour (``console.STEP_COLORS``).
54
+ jobs : int, optional
55
+ Worker processes for the per-molecule RDKit work (``-1``: every core).
56
+ The CLI is a proper entry point, so it may start a pool (see
57
+ :mod:`eosquality.utils.parallel`).
58
+ """
59
+ # Global output state is restored on exit, so calling the CLI in-process
60
+ # (tests, notebooks) leaves library use silent again.
61
+ previous = (console.enabled(), console.active_color(), logger.verbose, logger.level)
62
+ console.enable(True)
63
+ console.set_active_color(console.STEP_COLORS.get(command, "cyan"))
64
+ if verbose:
65
+ set_verbosity(True)
66
+ ctx = click.get_current_context()
67
+ try:
68
+ with parallel.workers(jobs):
69
+ fn()
70
+ except CliError as exc:
71
+ console.echo(f"[bold red]error:[/] {console.plain(exc)}", "error")
72
+ ctx.exit(1)
73
+ except KeyboardInterrupt:
74
+ console.echo("[bold red]interrupted[/]", "error")
75
+ ctx.exit(130)
76
+ except Exception as exc: # anything unexpected still exits cleanly with status 1
77
+ console.echo(f"[bold red]error:[/] {console.plain(exc)}", "error")
78
+ if verbose:
79
+ console.console.print_exception()
80
+ ctx.exit(1)
81
+ finally:
82
+ set_verbosity(previous[2])
83
+ logger.set_level(previous[3])
84
+ console.enable(previous[0])
85
+ console.set_active_color(previous[1])
86
+
87
+
88
+ @contextmanager
89
+ def staged_log(final_path: pathlib.Path):
90
+ """Log to a temporary file, then append it to ``final_path`` on success.
91
+
92
+ For ``fit``, whose artifacts folder only exists once saved. On failure
93
+ the temporary log is kept and its path printed.
94
+
95
+ Parameters
96
+ ----------
97
+ final_path : pathlib.Path
98
+ Where the log belongs once the command succeeds.
99
+
100
+ Yields
101
+ ------
102
+ pathlib.Path
103
+ ``final_path``.
104
+ """
105
+ handle, tmp = tempfile.mkstemp(prefix="eosquality_", suffix=".log")
106
+ os.close(handle)
107
+ ok = False
108
+ try:
109
+ with logger.log_file(tmp):
110
+ yield final_path
111
+ ok = True
112
+ finally:
113
+ if ok and final_path.parent.is_dir():
114
+ with open(final_path, "a") as out, open(tmp) as src:
115
+ shutil.copyfileobj(src, out)
116
+ os.remove(tmp)
117
+ else:
118
+ console.echo(f"[dim]log →[/] {console.path(tmp)}")
119
+
120
+
121
+ def _check_jobs(ctx, param, value: int) -> int:
122
+ """Accept ``-1`` (every core) or a positive worker count."""
123
+ if value == 0:
124
+ raise click.BadParameter("use -1 for every core or a positive number.")
125
+ return value
126
+
127
+
128
+ jobs_option = click.option(
129
+ "--jobs",
130
+ "-j",
131
+ type=click.IntRange(min=-1),
132
+ callback=_check_jobs,
133
+ default=-1,
134
+ show_default=True,
135
+ metavar="N",
136
+ help="Worker processes for the RDKit descriptors (-1: every core, up to 16; 1: none).",
137
+ )
138
+
139
+ verbose_option = click.option(
140
+ "--verbose",
141
+ "-v",
142
+ is_flag=True,
143
+ help="Show debug messages and tracebacks.",
144
+ )