samplekit 1.0.0rc2__cp315-cp315-win_amd64.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.
samplekit/_figure.py ADDED
@@ -0,0 +1,173 @@
1
+ """The command line's figure.
2
+
3
+ ``samplekit plot`` starts this module in the project's environment, writes one
4
+ JSON request on its standard input, and waits: the window, or the file, and
5
+ every diagnostic are this process's. The exit code is the command's.
6
+
7
+ {"figure": "vfi", "model": false, "samples": [...], "output": null}
8
+ {"axes": {"kind": "scatter", "x": "period", "y": "vfi", "group": null}, ...}
9
+ """
10
+
11
+ import contextlib
12
+ import json
13
+ import sys
14
+ import traceback
15
+ import warnings
16
+
17
+ REFUSED, FAILED, UNWRITTEN, INTERRUPTED = 1, 2, 3, 130
18
+
19
+
20
+ def main():
21
+ request = json.loads(sys.stdin.read())
22
+ warnings.showwarning = _said
23
+ try:
24
+ return _run(request)
25
+ except KeyboardInterrupt:
26
+ return INTERRUPTED
27
+ except ModuleNotFoundError as error:
28
+ return refuse(
29
+ f"this environment ({sys.executable}) has no {error.name}: a figure is drawn by "
30
+ "matplotlib, installed with samplekit",
31
+ code=UNWRITTEN,
32
+ )
33
+
34
+
35
+ def _run(request):
36
+ import samplekit
37
+ from samplekit import _figures
38
+
39
+ if request.get("version") not in (None, samplekit.__version__):
40
+ return refuse(
41
+ f"this environment holds samplekit {samplekit.__version__}, and the command "
42
+ f"is {request['version']}: install the same version in both"
43
+ )
44
+ model = None if request.get("model") else False
45
+ # What the model prints as it loads is not a figure's name.
46
+ with contextlib.redirect_stdout(sys.stderr):
47
+ try:
48
+ samples = samplekit.SampleList(
49
+ [samplekit.Sample(path, model=model) for path in request["samples"]]
50
+ )
51
+ except Exception:
52
+ traceback.print_exc()
53
+ return FAILED
54
+
55
+ if model is None:
56
+ _describe(samples)
57
+
58
+ axes = request.get("axes")
59
+ output = request.get("output")
60
+ # What the history says wrote a file drawn here: the command line.
61
+ _figures.SAID = request.get("said")
62
+ # A refusal names the command's options, `-o`, rather than `output=`.
63
+ _figures.COMMAND_LINE = True
64
+ # From the workbench, `w` writes a file, not `-o`.
65
+ _figures.WORKBENCH = bool(request.get("workbench"))
66
+ # Drawn from the project as it was: the snapshot it carries.
67
+ _figures.CARRY = request.get("snapshot")
68
+ overrides = {key: value for key, value in (request.get("overrides") or {}).items()
69
+ if value is not None}
70
+ overrides["project_style"] = request.get("project_style", True)
71
+ try:
72
+ if axes is not None:
73
+ # Given axes carry their group and kind; the overrides say the rest.
74
+ overrides.update(
75
+ {key: axes[key] for key in ("group", "kind") if axes.get(key) is not None}
76
+ )
77
+ _figures.plot(samples, x=axes["x"], y=axes["y"], output=output, overwrite=True,
78
+ **overrides)
79
+ else:
80
+ _figures.plot(samples, request["figure"], output=output, overwrite=True,
81
+ **overrides)
82
+ except KeyboardInterrupt:
83
+ raise
84
+ except Exception as error:
85
+ if isinstance(error, ModuleNotFoundError) and not _figures.raised_by_the_figure(error):
86
+ raise
87
+ if _figures.raised_by_the_figure(error):
88
+ traceback.print_exc()
89
+ return FAILED
90
+ if isinstance(error, OSError):
91
+ return refuse(f"the figure could not be written: {error}", code=UNWRITTEN)
92
+ if isinstance(error, RuntimeError) and "LaTeX" in str(error):
93
+ # LaTeX's whole log said nothing a reader could use: its errors,
94
+ # the lines starting with `!`, and the label they were in.
95
+ lines = str(error).splitlines()
96
+ said = [line for line in lines if line.startswith("!")] or lines[:1]
97
+ return refuse("LaTeX could not typeset a label: " + " ".join(said[:3]))
98
+ # The samples disagreeing — two units on one axis, two bars at one x —
99
+ # is a data error, 2, as the table's column of two units is; a name or
100
+ # an option the command does not know is a refusal, 1.
101
+ if isinstance(error, (RuntimeError, ValueError)) and _figures.raised_by_the_data(error):
102
+ return refuse(error.args[0] if error.args else str(error), code=FAILED)
103
+ if isinstance(error, (KeyError, RuntimeError, ValueError)):
104
+ return refuse(error.args[0] if error.args else str(error))
105
+ if isinstance(error, TypeError):
106
+ return refuse(str(error), code=FAILED)
107
+ traceback.print_exc()
108
+ return FAILED
109
+ # Drawn from values not current: written, and a failure all the same, as
110
+ # an export's, unless the command accepts them.
111
+ if _figures.STALE_SAID and not request.get("accept_outdated"):
112
+ return refuse(
113
+ "the figure is drawn from values not current — --accept outdated exits 0 for it",
114
+ code=FAILED,
115
+ )
116
+ return 0
117
+
118
+
119
+ def _describe(samples):
120
+ """Writes the description of each model drawn from, as the worker does
121
+ when it imports one. A figure is not refused for it: a model that
122
+ loaded its samples draws, and the next command that needs the description
123
+ has it written."""
124
+ from samplekit import _native, _worker
125
+
126
+ seen = set()
127
+ for sample in samples:
128
+ model = type(sample)
129
+ if model in seen or model.__name__ == "Sample" and model.__module__ == "samplekit":
130
+ continue
131
+ seen.add(model)
132
+ try:
133
+ project = sample.project
134
+ declared = project.model
135
+ if declared is None or project.root is None:
136
+ continue
137
+ _worker.describe(model, str(declared.path), str(project.root), _native)
138
+ except Exception:
139
+ continue
140
+
141
+
142
+ def _said(message, category, filename, lineno, file=None, line=None):
143
+ """A warning as the command line says one: its words, without the source
144
+ line of this package it was raised on."""
145
+ text = str(message).replace("compute() runs it", "samplekit compute runs it")
146
+ print(_painted("warning:", text), file=sys.stderr)
147
+
148
+
149
+ def refuse(message, code=REFUSED):
150
+ print(_painted("error:", message), file=sys.stderr)
151
+ return code
152
+
153
+ def _painted(prefix, text):
154
+ """`prefix` and `text` as the command line paints them where it gave its
155
+ colours: the prefix in its own, advice at the end muted."""
156
+ import os
157
+ reset = os.environ.get("SAMPLEKIT_PAINT_RESET")
158
+ if not reset:
159
+ return f"{prefix} {text}"
160
+ style = os.environ.get(
161
+ "SAMPLEKIT_PAINT_WARNING" if prefix == "warning:" else "SAMPLEKIT_PAINT_ERROR", ""
162
+ )
163
+ muted = os.environ.get("SAMPLEKIT_PAINT_MUTED", "")
164
+ fact, mark, tip = text.rpartition(" — ")
165
+ if mark and ("samplekit " in tip or any(
166
+ word.startswith("--") and len(word) > 2 and word[2].isalpha() for word in tip.split()
167
+ )):
168
+ text = f"{fact} — {muted}{tip}{reset}"
169
+ return f"{style}{prefix}{reset} {text}"
170
+
171
+
172
+ if __name__ == "__main__":
173
+ sys.exit(main())