solprop-gui 0.2.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.
Files changed (143) hide show
  1. solprop_gui/__init__.py +24 -0
  2. solprop_gui/__main__.py +11 -0
  3. solprop_gui/app.py +67 -0
  4. solprop_gui/classes/__init__.py +9 -0
  5. solprop_gui/classes/catalog.py +854 -0
  6. solprop_gui/classes/problem.py +868 -0
  7. solprop_gui/classes/workflow.py +139 -0
  8. solprop_gui/help/__init__.py +7 -0
  9. solprop_gui/help/figures/antiresonant.svg +70 -0
  10. solprop_gui/help/figures/capillary-averaged.svg +63 -0
  11. solprop_gui/help/figures/capillary-modal.svg +65 -0
  12. solprop_gui/help/figures/cartesian.svg +164 -0
  13. solprop_gui/help/figures/gnlse.svg +64 -0
  14. solprop_gui/help/figures/grin.svg +63 -0
  15. solprop_gui/help/figures/line.svg +84 -0
  16. solprop_gui/help/figures/radial.svg +68 -0
  17. solprop_gui/help/figures/rectangular.svg +63 -0
  18. solprop_gui/help/figures/slab.svg +68 -0
  19. solprop_gui/help/figures/step-index.svg +63 -0
  20. solprop_gui/help/figures.py +106 -0
  21. solprop_gui/help/guide/analysis.md +96 -0
  22. solprop_gui/help/guide/classes.md +94 -0
  23. solprop_gui/help/guide/design.md +59 -0
  24. solprop_gui/help/guide/first-run.md +101 -0
  25. solprop_gui/help/guide/images/capillary-along.png +0 -0
  26. solprop_gui/help/guide/images/capillary-overview.png +0 -0
  27. solprop_gui/help/guide/images/capillary-plane.png +0 -0
  28. solprop_gui/help/guide/images/capillary-run.png +0 -0
  29. solprop_gui/help/guide/images/capillary-sheet.png +0 -0
  30. solprop_gui/help/guide/images/capillary-target.png +0 -0
  31. solprop_gui/help/guide/images/design.png +0 -0
  32. solprop_gui/help/guide/images/filament-overview.png +0 -0
  33. solprop_gui/help/guide/images/filament-sheet.png +0 -0
  34. solprop_gui/help/guide/images/home.png +0 -0
  35. solprop_gui/help/guide/images/plot-menu.png +0 -0
  36. solprop_gui/help/guide/images/scan.png +0 -0
  37. solprop_gui/help/guide/index.md +104 -0
  38. solprop_gui/help/guide/scans.md +55 -0
  39. solprop_gui/help/guide.py +48 -0
  40. solprop_gui/help/manual.py +199 -0
  41. solprop_gui/model/__init__.py +12 -0
  42. solprop_gui/model/compressor.py +407 -0
  43. solprop_gui/model/display.py +501 -0
  44. solprop_gui/model/plot_options.py +343 -0
  45. solprop_gui/model/quantities.py +179 -0
  46. solprop_gui/model/recipe.py +473 -0
  47. solprop_gui/model/scans.py +288 -0
  48. solprop_gui/model/snippets.py +118 -0
  49. solprop_gui/model/stats_layout.py +115 -0
  50. solprop_gui/model/values.py +195 -0
  51. solprop_gui/model/workspace.py +151 -0
  52. solprop_gui/py.typed +0 -0
  53. solprop_gui/registry/__init__.py +12 -0
  54. solprop_gui/registry/explore.py +481 -0
  55. solprop_gui/registry/pages.py +273 -0
  56. solprop_gui/registry/routes.py +450 -0
  57. solprop_gui/registry/units.py +135 -0
  58. solprop_gui/service/__init__.py +12 -0
  59. solprop_gui/service/beam.py +226 -0
  60. solprop_gui/service/beams.py +257 -0
  61. solprop_gui/service/client.py +398 -0
  62. solprop_gui/service/design.py +362 -0
  63. solprop_gui/service/figures.py +106 -0
  64. solprop_gui/service/handlers.py +709 -0
  65. solprop_gui/service/kernel.py +187 -0
  66. solprop_gui/service/messages.py +210 -0
  67. solprop_gui/service/outbox.py +139 -0
  68. solprop_gui/service/postprocess.py +513 -0
  69. solprop_gui/service/reduce.py +368 -0
  70. solprop_gui/service/remote.py +513 -0
  71. solprop_gui/service/results.py +951 -0
  72. solprop_gui/service/run.py +648 -0
  73. solprop_gui/service/scan_reductions.py +261 -0
  74. solprop_gui/service/server.py +501 -0
  75. solprop_gui/service/sheet.py +1023 -0
  76. solprop_gui/service/states.py +146 -0
  77. solprop_gui/service/waveguide.py +320 -0
  78. solprop_gui/service/worker.py +97 -0
  79. solprop_gui/ui/__init__.py +11 -0
  80. solprop_gui/ui/analyse.py +808 -0
  81. solprop_gui/ui/analysis.py +338 -0
  82. solprop_gui/ui/analysis_pages.py +2954 -0
  83. solprop_gui/ui/assets/chevron.svg +6 -0
  84. solprop_gui/ui/assets/fonts/IBMPlexSans-Medium.ttf +0 -0
  85. solprop_gui/ui/assets/fonts/IBMPlexSans-Regular.ttf +0 -0
  86. solprop_gui/ui/assets/fonts/IBMPlexSans-SemiBold.ttf +0 -0
  87. solprop_gui/ui/assets/fonts/LICENSE.txt +93 -0
  88. solprop_gui/ui/assets/icon/solprop-1024.png +0 -0
  89. solprop_gui/ui/assets/icon/solprop-128.png +0 -0
  90. solprop_gui/ui/assets/icon/solprop-16.png +0 -0
  91. solprop_gui/ui/assets/icon/solprop-24.png +0 -0
  92. solprop_gui/ui/assets/icon/solprop-256.png +0 -0
  93. solprop_gui/ui/assets/icon/solprop-32.png +0 -0
  94. solprop_gui/ui/assets/icon/solprop-48.png +0 -0
  95. solprop_gui/ui/assets/icon/solprop-512.png +0 -0
  96. solprop_gui/ui/assets/icon/solprop-64.png +0 -0
  97. solprop_gui/ui/assets/icon/solprop-compact.svg +19 -0
  98. solprop_gui/ui/assets/icon/solprop.svg +20 -0
  99. solprop_gui/ui/betas.py +245 -0
  100. solprop_gui/ui/bridge.py +258 -0
  101. solprop_gui/ui/design_stage.py +956 -0
  102. solprop_gui/ui/document.py +693 -0
  103. solprop_gui/ui/fields.py +812 -0
  104. solprop_gui/ui/help_window.py +214 -0
  105. solprop_gui/ui/home.py +291 -0
  106. solprop_gui/ui/icons.py +191 -0
  107. solprop_gui/ui/identity.py +230 -0
  108. solprop_gui/ui/launch.py +261 -0
  109. solprop_gui/ui/objects.py +530 -0
  110. solprop_gui/ui/pages.py +436 -0
  111. solprop_gui/ui/pin.py +286 -0
  112. solprop_gui/ui/plot_options.py +439 -0
  113. solprop_gui/ui/postprocess.py +532 -0
  114. solprop_gui/ui/quantity.py +532 -0
  115. solprop_gui/ui/results.py +482 -0
  116. solprop_gui/ui/run_options.py +179 -0
  117. solprop_gui/ui/run_panel.py +767 -0
  118. solprop_gui/ui/scan_editor.py +421 -0
  119. solprop_gui/ui/scan_stage.py +724 -0
  120. solprop_gui/ui/sheet.py +1371 -0
  121. solprop_gui/ui/theme.py +247 -0
  122. solprop_gui/ui/tile_art.py +146 -0
  123. solprop_gui/ui/workflow_window.py +1332 -0
  124. solprop_gui/views/__init__.py +11 -0
  125. solprop_gui/views/compare.py +114 -0
  126. solprop_gui/views/compression.py +146 -0
  127. solprop_gui/views/controls.py +211 -0
  128. solprop_gui/views/cross_section.py +124 -0
  129. solprop_gui/views/live.py +704 -0
  130. solprop_gui/views/page_plots.py +1073 -0
  131. solprop_gui/views/plane.py +650 -0
  132. solprop_gui/views/plotting.py +381 -0
  133. solprop_gui/views/scan_browser.py +149 -0
  134. solprop_gui/views/sparkline.py +131 -0
  135. solprop_gui/views/splitter.py +141 -0
  136. solprop_gui/views/statistics.py +501 -0
  137. solprop_gui-0.2.0.dist-info/METADATA +92 -0
  138. solprop_gui-0.2.0.dist-info/RECORD +143 -0
  139. solprop_gui-0.2.0.dist-info/WHEEL +4 -0
  140. solprop_gui-0.2.0.dist-info/entry_points.txt +2 -0
  141. solprop_gui-0.2.0.dist-info/licenses/LICENSE +674 -0
  142. solprop_gui-0.2.0.dist-info/licenses/LICENSE-CC-BY-4.0.txt +156 -0
  143. solprop_gui-0.2.0.dist-info/licenses/src/solprop_gui/ui/assets/fonts/LICENSE.txt +93 -0
@@ -0,0 +1,868 @@
1
+ # SPDX-FileCopyrightText: 2026 John C. Travers and contributors
2
+ #
3
+ # SPDX-License-Identifier: GPL-3.0-or-later
4
+
5
+ """What a problem class declares, and the readings of it that hold for every class."""
6
+
7
+ import math
8
+ from collections.abc import Iterator, Mapping, Sequence
9
+ from copy import deepcopy
10
+ from dataclasses import dataclass, field
11
+
12
+ from solprop.recipe.errors import RecipeError
13
+ from solprop.recipe.paths import Attribute, Index, get_path, parse_path, set_path
14
+
15
+ from solprop_gui.model.quantities import split
16
+ from solprop_gui.model.recipe import MISSING
17
+ from solprop_gui.registry.units import si
18
+
19
+ __all__ = [
20
+ "AnalysisPage",
21
+ "Derived",
22
+ "Field",
23
+ "ProblemClass",
24
+ "Section",
25
+ "Target",
26
+ "derived_text",
27
+ "derived_value",
28
+ "even_planes",
29
+ "field_changes",
30
+ "field_meta",
31
+ "field_value",
32
+ "linked_paths",
33
+ "negated_value",
34
+ "other_keywords",
35
+ "page_refusal",
36
+ "pin_entry",
37
+ "sheet_paths",
38
+ "target_text",
39
+ ]
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class Field:
44
+ """One row of a sheet.
45
+
46
+ Attributes
47
+ ----------
48
+ path : str
49
+ Its recipe path in the ``[build]`` table.
50
+ label : str or None
51
+ What the row is called; ``None`` takes the front end's label of the keyword.
52
+ choices : str or None
53
+ The kernel's request that lists what the row offers, as ``"gases"`` does, in
54
+ place of free text.
55
+ also : tuple of str
56
+ Paths that hold the same value and move with this row, where the object routes
57
+ write it several times; ``[*]`` stands for every element of a list.
58
+ negated : bool
59
+ Whether the row shows the value with its sign changed, as a distance to a focus
60
+ is the launch's distance from it.
61
+ planes_over : str or None
62
+ Makes this a count of evenly spaced saved planes, over the length at this path.
63
+ moves_planes : str or None
64
+ The saved planes at this path, which this length respaces.
65
+ member : str or None
66
+ Makes this a switch: whether a list at the path holds an entry of this type.
67
+ goes_with : tuple of str
68
+ Paths the switch's entry needs set, taken from the class's example.
69
+ blank : str or None
70
+ What an empty row means, shown in it, as ``"fused silica"`` for a core glass
71
+ left to solprop.
72
+ """
73
+
74
+ path: str
75
+ label: str | None = None
76
+ choices: str | None = None
77
+ also: tuple[str, ...] = ()
78
+ negated: bool = False
79
+ planes_over: str | None = None
80
+ moves_planes: str | None = None
81
+ member: str | None = None
82
+ goes_with: tuple[str, ...] = ()
83
+ blank: str | None = None
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class Section:
88
+ """A titled group of a sheet's rows.
89
+
90
+ Attributes
91
+ ----------
92
+ title : str
93
+ Its title.
94
+ fields : tuple of Field
95
+ Its rows, in order.
96
+ folded : bool
97
+ Whether it starts folded, as a simulation window does.
98
+ """
99
+
100
+ title: str
101
+ fields: tuple[Field, ...]
102
+ folded: bool = False
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class Target:
107
+ """What typing into a derived number means: solprop's pin for it (design 7.5).
108
+
109
+ Attributes
110
+ ----------
111
+ kind : str
112
+ The pin's ``target``.
113
+ key : str
114
+ The pin's key that holds what was typed.
115
+ unit : str or None
116
+ The unit a typed number is in; ``None`` for a pure number.
117
+ moves : tuple of str
118
+ The keywords that can move to meet it, the first by default.
119
+ """
120
+
121
+ kind: str
122
+ key: str
123
+ unit: str | None
124
+ moves: tuple[str, ...]
125
+
126
+
127
+ @dataclass(frozen=True)
128
+ class Derived:
129
+ """A number a sheet shows, which solprop works out from the setup.
130
+
131
+ Attributes
132
+ ----------
133
+ key : str
134
+ Its name in the kernel's reply.
135
+ label : str
136
+ What it is called.
137
+ unit : str
138
+ Its unit, unprefixed where the number takes an SI prefix.
139
+ factor : float
140
+ What the reply's SI value is multiplied by to read in the unit.
141
+ prefixed : bool
142
+ Whether the number takes an SI prefix.
143
+ target : Target or None
144
+ What typing into it does; ``None`` when it can only be read.
145
+ """
146
+
147
+ key: str
148
+ label: str
149
+ unit: str = ""
150
+ factor: float = 1.0
151
+ prefixed: bool = True
152
+ target: Target | None = None
153
+
154
+
155
+ @dataclass(frozen=True)
156
+ class AnalysisPage:
157
+ """A page of the Analyse rail.
158
+
159
+ Attributes
160
+ ----------
161
+ key : str
162
+ Its identity.
163
+ title : str
164
+ Its name on the rail.
165
+ needs : tuple of str
166
+ What the file must hold for the page to be offered, each of ``"fields"``,
167
+ ``"statistics"``, ``"modes"`` and ``"ensemble"``.
168
+ operation : str or None
169
+ The operation of ``solprop.capabilities.output`` whose refusal disables the
170
+ page, with solprop's reason.
171
+ view : str or None
172
+ Which view draws it, where that is not the page's own key.
173
+ """
174
+
175
+ key: str
176
+ title: str
177
+ needs: tuple[str, ...] = ()
178
+ operation: str | None = None
179
+ view: str | None = None
180
+
181
+
182
+ @dataclass(frozen=True)
183
+ class ProblemClass:
184
+ """One problem class.
185
+
186
+ Attributes
187
+ ----------
188
+ key : str
189
+ Its identity.
190
+ title : str
191
+ Its name.
192
+ summary : str
193
+ One sentence for its tile on Home.
194
+ route : str
195
+ The solprop route it builds.
196
+ example : str
197
+ The solprop example a new sheet starts from (``Recipe.example``), so that the
198
+ front end holds no defaults of its own.
199
+ marker : tuple of str
200
+ Keywords whose presence in ``[build]`` makes a recipe of the route this class's
201
+ rather than another's: an antiresonant fibre is a capillary with a ``lattice``.
202
+ ``"keyword.type=Name"`` asks for an object of a type: a Cartesian beam is free
203
+ space on a ``FreeGrid``.
204
+ sections : tuple of Section
205
+ Its sheet.
206
+ derived : tuple of Derived
207
+ The numbers its sheet shows.
208
+ preview : str
209
+ What its sheet's plot shows.
210
+ pages : tuple of AnalysisPage
211
+ Its Analyse rail, in order; the first opens on a new file.
212
+ statistics : tuple of str
213
+ The statistics its pages need recorded.
214
+ numbers : str
215
+ The kernel's request for its derived numbers, asked at each edit where it is
216
+ quick enough; ``"summarise"`` follows solprop's check instead.
217
+ curve : str or None
218
+ The kernel's request for its preview's curve, if it has one yet.
219
+ lens : tuple of str or None
220
+ The waist, launch distance and wavelength paths a lens sets and reads, where the
221
+ sheet offers one.
222
+ examples : tuple of str
223
+ The solprop examples its sheet lists, the one it starts from first; empty lists
224
+ that one alone. A chosen few: solprop's other examples of the route are the
225
+ gallery's, for scripts.
226
+ home : bool
227
+ Whether Home offers it; a class off Home still opens the recipes and files it
228
+ fits.
229
+ """
230
+
231
+ key: str
232
+ title: str
233
+ summary: str
234
+ route: str
235
+ example: str
236
+ sections: tuple[Section, ...]
237
+ pages: tuple[AnalysisPage, ...]
238
+ preview: str
239
+ derived: tuple[Derived, ...] = ()
240
+ marker: tuple[str, ...] = field(default=())
241
+ statistics: tuple[str, ...] = ()
242
+ numbers: str = "summarise"
243
+ curve: str | None = None
244
+ lens: tuple[str, str, str] | None = None
245
+ examples: tuple[str, ...] = ()
246
+ home: bool = True
247
+
248
+
249
+ def derived_value(summary: Mapping[str, object] | None, key: str) -> float | None:
250
+ """Find a derived number in the kernel's summary.
251
+
252
+ Parameters
253
+ ----------
254
+ summary : Mapping or None
255
+ The kernel's ``summarise`` reply; ``None`` when it failed.
256
+ key : str
257
+ The number's key, in the summary or in its ``design`` table.
258
+
259
+ Returns
260
+ -------
261
+ float or None
262
+ The number, or ``None`` where solprop gave none.
263
+
264
+ Examples
265
+ --------
266
+ >>> derived_value({"peak_power": 2.0, "design": {"zdw": 3.0}}, "zdw")
267
+ 3.0
268
+ >>> derived_value({"peak_power": 2.0}, "peak_power")
269
+ 2.0
270
+ >>> derived_value({"design": None}, "zdw"), derived_value(None, "zdw")
271
+ (None, None)
272
+ """
273
+ if summary is None:
274
+ return None
275
+ design = summary.get("design")
276
+ tables = (summary, design) if isinstance(design, Mapping) else (summary,)
277
+ for table in tables:
278
+ value = table.get(key)
279
+ if isinstance(value, int | float):
280
+ return float(value)
281
+ return None
282
+
283
+
284
+ def derived_text(number: Derived, value: float | None) -> str:
285
+ """Write a derived number as its sheet shows it.
286
+
287
+ Parameters
288
+ ----------
289
+ number : Derived
290
+ What it is.
291
+ value : float or None
292
+ Its SI value; ``None`` when solprop gave none.
293
+
294
+ Returns
295
+ -------
296
+ str
297
+ The text: ``"—"`` for none, ``"none"`` for a number that does not exist, as
298
+ a zero-dispersion wavelength may not.
299
+
300
+ Examples
301
+ --------
302
+ >>> derived_text(Derived("zdw", "ZDW", "m"), 4.23e-7)
303
+ '423 nm'
304
+ >>> derived_text(Derived("i", "I", "W/cm²", 1e-4, prefixed=False), 3.7e18)
305
+ '3.7e+14 W/cm²'
306
+ >>> derived_text(Derived("n", "N", prefixed=False), 2.5)
307
+ '2.5'
308
+ >>> derived_text(Derived("n", "N"), None), derived_text(Derived("n", "N"), math.nan)
309
+ ('—', 'none')
310
+ """
311
+ if value is None:
312
+ return "—"
313
+ if not math.isfinite(value):
314
+ return "none"
315
+ scaled = value * number.factor
316
+ if number.prefixed:
317
+ return si(scaled, number.unit, digits=3)
318
+ return f"{scaled:.3g} {number.unit}".strip()
319
+
320
+
321
+ def pin_entry(
322
+ target: Target, value: str, search: Sequence[str] | None = None
323
+ ) -> dict[str, object]:
324
+ """Write what was typed into a derived number as a ``[pins]`` entry.
325
+
326
+ Parameters
327
+ ----------
328
+ target : Target
329
+ What it means.
330
+ value : str
331
+ The text typed, a number in the target's unit.
332
+ search : Sequence of str or None, optional
333
+ Where a pin on the guide or fill searches.
334
+
335
+ Returns
336
+ -------
337
+ dict
338
+ The entry.
339
+
340
+ Raises
341
+ ------
342
+ ValueError
343
+ If the text is not a number.
344
+
345
+ Examples
346
+ --------
347
+ >>> order = Target("soliton_order", "order", None, ("energy",))
348
+ >>> pin_entry(order, "3")
349
+ {'target': 'soliton_order', 'order': 3.0}
350
+ >>> zdw = Target("zdw", "wavelength", "nm", ("pressure",))
351
+ >>> pin_entry(zdw, "450", ["0.01 bar", "20 bar"])["wavelength"]
352
+ '450 nm'
353
+ """
354
+ number = float(value)
355
+ entry: dict[str, object] = {
356
+ "target": target.kind,
357
+ target.key: number if target.unit is None else f"{value.strip()} {target.unit}",
358
+ }
359
+ if search is not None:
360
+ entry["search"] = list(search)
361
+ return entry
362
+
363
+
364
+ def target_text(target: Target, entry: Mapping[str, object]) -> str:
365
+ """Write a pin's target as a sheet says it.
366
+
367
+ Parameters
368
+ ----------
369
+ target : Target
370
+ What it means.
371
+ entry : Mapping
372
+ The ``[pins]`` entry.
373
+
374
+ Returns
375
+ -------
376
+ str
377
+ What it holds.
378
+
379
+ Examples
380
+ --------
381
+ >>> target_text(Target("soliton_order", "order", None, ()), {"order": 3.0})
382
+ '3'
383
+ >>> target_text(Target("zdw", "wavelength", "nm", ()), {"wavelength": "450 nm"})
384
+ '450 nm'
385
+ """
386
+ held = entry.get(target.key)
387
+ return f"{held:g}" if isinstance(held, int | float) else str(held)
388
+
389
+
390
+ _NEEDS = {
391
+ "fields": "This run kept no fields, so this page has nothing to read.",
392
+ "statistics": "This run recorded no statistics.",
393
+ "modes": "This run has one mode.",
394
+ "ensemble": "This run is not a seeded ensemble.",
395
+ }
396
+ """Why a page is not offered, by what the file lacks."""
397
+
398
+
399
+ def page_refusal(page: AnalysisPage, capabilities: Mapping[str, object]) -> str | None:
400
+ """Say why a file cannot show a page.
401
+
402
+ Parameters
403
+ ----------
404
+ page : AnalysisPage
405
+ The page.
406
+ capabilities : Mapping
407
+ The kernel's ``describe_output`` reply on the file: its ``z``, ``field_planes``,
408
+ ``labels``, ``refused`` and ``ensemble``.
409
+
410
+ Returns
411
+ -------
412
+ str or None
413
+ The reason, solprop's own where it refuses; ``None`` when the page can be shown.
414
+
415
+ Examples
416
+ --------
417
+ >>> page = AnalysisPage("compress", "Compress", ("fields",), "compression")
418
+ >>> page_refusal(page, {"field_planes": [0], "refused": {}}) is None
419
+ True
420
+ >>> page_refusal(page, {"field_planes": [0], "refused": {"compression": "No."}})
421
+ 'No.'
422
+ >>> page_refusal(page, {})
423
+ 'This run kept no fields, so this page has nothing to read.'
424
+ """
425
+ held = {
426
+ "fields": bool(capabilities.get("field_planes")),
427
+ # Every saved plane has its statistics row, a field or not.
428
+ "statistics": bool(capabilities.get("z")),
429
+ "modes": len(capabilities.get("labels") or ()) > 1, # pyright: ignore[reportArgumentType]
430
+ "ensemble": bool(capabilities.get("ensemble")),
431
+ }
432
+ for need in page.needs:
433
+ if not held[need]:
434
+ return _NEEDS[need]
435
+ refused = capabilities.get("refused")
436
+ if page.operation is not None and isinstance(refused, Mapping):
437
+ reason = refused.get(page.operation)
438
+ return None if reason is None else str(reason)
439
+ return None
440
+
441
+
442
+ def sheet_paths(problem: ProblemClass) -> Iterator[str]:
443
+ """Yield every recipe path a class's sheet shows.
444
+
445
+ Parameters
446
+ ----------
447
+ problem : ProblemClass
448
+ The class.
449
+
450
+ Yields
451
+ ------
452
+ str
453
+ Each path, in the sheet's order.
454
+
455
+ Examples
456
+ --------
457
+ >>> rows = (Field("radius"), Field("length"))
458
+ >>> problem = ProblemClass(
459
+ ... "c", "C", "", "capillary", "rdw", (Section("S", rows),), (), "β₂"
460
+ ... )
461
+ >>> list(sheet_paths(problem))
462
+ ['radius', 'length']
463
+ """
464
+ for section in problem.sections:
465
+ for row in section.fields:
466
+ yield row.path
467
+
468
+
469
+ def field_meta(
470
+ path: str,
471
+ description: Mapping[str, object],
472
+ build: Mapping[str, object],
473
+ ) -> Mapping[str, object] | None:
474
+ """Return the metadata of a path, following the registered types the recipe names.
475
+
476
+ ``initial.temporal.fwhm`` is the ``fwhm`` of the type ``initial.temporal`` names in
477
+ this recipe, so a sheet's row is described by what the recipe holds. An index steps
478
+ into a list: into one of several objects, ``initial.beams[0].waist``, as into one
479
+ object; into a pair or array of numbers, ``displacement[0]``, to one number in the
480
+ pair's unit.
481
+
482
+ Parameters
483
+ ----------
484
+ path : str
485
+ The recipe path, of keywords and attributes.
486
+ description : Mapping
487
+ The kernel's ``describe`` reply on the route.
488
+ build : Mapping
489
+ The recipe's ``[build]`` table.
490
+
491
+ Returns
492
+ -------
493
+ Mapping or None
494
+ The keyword's metadata, or ``None`` when the route has no such path.
495
+
496
+ Examples
497
+ --------
498
+ >>> described = {
499
+ ... "parameters": [{"name": "initial"}],
500
+ ... "types": {"Beam": [{"name": "waist"}]},
501
+ ... }
502
+ >>> field_meta("initial.waist", described, {"initial": {"type": "Beam"}})
503
+ {'name': 'waist'}
504
+ >>> field_meta("initial", described, {}), field_meta("x", described, {})
505
+ ({'name': 'initial'}, None)
506
+ >>> field_meta("initial.waist", described, {})
507
+ >>> field_meta("initial[0]", described, {})
508
+ >>> described["types"]["Sum"] = [{"name": "beams"}]
509
+ >>> described["types"]["Beam"].append(
510
+ ... {"name": "shift", "forms": [{"kind": "pair", "unit": "m"}]})
511
+ >>> held = {"initial": {"type": "Sum", "beams": [{"type": "Beam"}]}}
512
+ >>> field_meta("initial.beams[0].waist", described, held)
513
+ {'name': 'waist'}
514
+ >>> held["initial"]["beams"][0]["shift"] = [0.0, 0.0]
515
+ >>> field_meta("initial.beams[0].shift[1]", described, held)["forms"]
516
+ [{'kind': 'number', 'unit': 'm'}]
517
+ >>> field_meta("initial.beams[5].waist", described, held)
518
+ """
519
+ try:
520
+ steps = parse_path(path)
521
+ except RecipeError:
522
+ return None
523
+ entries: Sequence[Mapping[str, object]] = description["parameters"] # pyright: ignore[reportAssignmentType]
524
+ catalog: Mapping[str, Sequence[Mapping[str, object]]] = description.get("types", {}) # pyright: ignore[reportAssignmentType]
525
+ holder: object = build
526
+ meta: Mapping[str, object] | None = None
527
+ for step in steps:
528
+ if isinstance(step, Index) and meta is not None and isinstance(holder, list):
529
+ if not 0 <= step.position < len(holder):
530
+ return None
531
+ holder = holder[step.position]
532
+ if isinstance(holder, Mapping):
533
+ entries = catalog.get(str(holder.get("type")), ())
534
+ continue
535
+ # One number of a pair or an array, in its unit.
536
+ forms: Sequence[Mapping[str, object]] = meta.get("forms") or () # pyright: ignore[reportAssignmentType]
537
+ meta = {
538
+ **meta,
539
+ "forms": [
540
+ {"kind": "number", "unit": form.get("unit")}
541
+ for form in forms
542
+ if form.get("kind") in ("pair", "array")
543
+ ],
544
+ }
545
+ entries = ()
546
+ continue
547
+ if not isinstance(step, Attribute) or not isinstance(holder, Mapping):
548
+ return None
549
+ meta = next((e for e in entries if e.get("name") == step.name), None)
550
+ if meta is None:
551
+ return None
552
+ holder = holder.get(step.name)
553
+ kind = holder.get("type") if isinstance(holder, Mapping) else None
554
+ entries = catalog.get(str(kind), ())
555
+ return meta
556
+
557
+
558
+ def _held(build: Mapping[str, object], path: str) -> object:
559
+ """Return what a path of ``[build]`` holds.
560
+
561
+ Parameters
562
+ ----------
563
+ build : Mapping
564
+ The table.
565
+ path : str
566
+ The path.
567
+
568
+ Returns
569
+ -------
570
+ object
571
+ The value, or :data:`MISSING`.
572
+ """
573
+ try:
574
+ return get_path(build, path)
575
+ except RecipeError:
576
+ return MISSING
577
+
578
+
579
+ def linked_paths(build: Mapping[str, object], pattern: str) -> list[str]:
580
+ """Return the paths a pattern names in a recipe, those that exist.
581
+
582
+ Parameters
583
+ ----------
584
+ build : Mapping
585
+ The recipe's ``[build]`` table.
586
+ pattern : str
587
+ A path, in which ``[*]`` stands for every element of a list.
588
+
589
+ Returns
590
+ -------
591
+ list of str
592
+ The paths.
593
+
594
+ Examples
595
+ --------
596
+ >>> build = {"responses": [{"gas": "Ar"}, {"thg": False}], "medium": {"gas": "Ar"}}
597
+ >>> linked_paths(build, "responses[*].gas"), linked_paths(build, "medium.gas")
598
+ (['responses[0].gas'], ['medium.gas'])
599
+ >>> linked_paths(build, "nothing[*].gas"), linked_paths(build, "medium.none")
600
+ ([], [])
601
+ """
602
+ if "[*]" not in pattern:
603
+ return [pattern] if _held(build, pattern) is not MISSING else []
604
+ head, tail = pattern.split("[*]", 1)
605
+ held = _held(build, head)
606
+ count = len(held) if isinstance(held, Sequence) and not isinstance(held, str) else 0
607
+ found = (f"{head}[{index}]{tail}" for index in range(count))
608
+ return [path for path in found if _held(build, path) is not MISSING]
609
+
610
+
611
+ def negated_value(value: object) -> object:
612
+ """Return a value with its sign changed.
613
+
614
+ Parameters
615
+ ----------
616
+ value : object
617
+ A number, a quantity string, or :data:`MISSING`.
618
+
619
+ Returns
620
+ -------
621
+ object
622
+ The value negated, in its own unit.
623
+
624
+ Examples
625
+ --------
626
+ >>> negated_value("10 cm"), negated_value("-10 cm"), negated_value(2.5)
627
+ ('-10 cm', '10 cm', -2.5)
628
+ >>> negated_value("0 mm")
629
+ '0 mm'
630
+ >>> negated_value(MISSING) is MISSING
631
+ True
632
+ """
633
+ if isinstance(value, bool) or value is MISSING:
634
+ return value
635
+ if isinstance(value, int | float):
636
+ return -value
637
+ number, unit = split(str(value))
638
+ if float(number) == 0:
639
+ return value
640
+ flipped = number[1:] if number.startswith("-") else f"-{number}"
641
+ return f"{flipped} {unit}".strip()
642
+
643
+
644
+ def even_planes(count: int, length: object) -> list[object]:
645
+ """Return evenly spaced saved planes along a length, ending at it.
646
+
647
+ Parameters
648
+ ----------
649
+ count : int
650
+ How many, the entrance not counted.
651
+ length : object
652
+ The length, a quantity string or a number.
653
+
654
+ Returns
655
+ -------
656
+ list
657
+ The positions, in the length's own unit.
658
+
659
+ Examples
660
+ --------
661
+ >>> even_planes(2, "25 cm")
662
+ ['12.5 cm', '25 cm']
663
+ >>> even_planes(2, 1.0)
664
+ [0.5, 1.0]
665
+ """
666
+ if isinstance(length, int | float):
667
+ return [float(length) * index / count for index in range(1, count + 1)]
668
+ number, unit = split(str(length))
669
+ total = float(number)
670
+ return [f"{total * index / count:.8g} {unit}" for index in range(1, count + 1)]
671
+
672
+
673
+ def field_value(row: Field, build: Mapping[str, object]) -> object:
674
+ """Return what a sheet's row shows of a recipe.
675
+
676
+ Parameters
677
+ ----------
678
+ row : Field
679
+ The row.
680
+ build : Mapping
681
+ The recipe's ``[build]`` table.
682
+
683
+ Returns
684
+ -------
685
+ object
686
+ The value as the row shows it; a switch's is whether its entry is there.
687
+
688
+ Examples
689
+ --------
690
+ >>> build = {"planes": ["1 m", "2 m"], "launch": "-5 cm", "list": [{"type": "A"}]}
691
+ >>> field_value(Field("planes", planes_over="length"), build)
692
+ 2
693
+ >>> field_value(Field("launch", negated=True), build)
694
+ '5 cm'
695
+ >>> field_value(Field("list", member="A"), build)
696
+ True
697
+ >>> field_value(Field("list", member="B"), build)
698
+ False
699
+ """
700
+ held = _held(build, row.path)
701
+ if row.member is not None:
702
+ entries = held if isinstance(held, Sequence) else ()
703
+ return any(
704
+ isinstance(entry, Mapping) and entry.get("type") == row.member
705
+ for entry in entries
706
+ )
707
+ if row.planes_over is not None:
708
+ return len(held) if isinstance(held, Sequence) else MISSING
709
+ return negated_value(held) if row.negated else held
710
+
711
+
712
+ def _switched(
713
+ problem: ProblemClass,
714
+ row: Field,
715
+ on: bool,
716
+ build: Mapping[str, object],
717
+ example: Mapping[str, object],
718
+ ) -> list[tuple[str, object]]:
719
+ """Return the changes that switch one entry of a list on or off.
720
+
721
+ An entry comes back from the class's example, which orders the list, with what the
722
+ sheet's linked rows hold now.
723
+
724
+ Parameters
725
+ ----------
726
+ problem : ProblemClass
727
+ The class.
728
+ row : Field
729
+ The switch.
730
+ on : bool
731
+ Whether its entry is wanted.
732
+ build : Mapping
733
+ The recipe's ``[build]`` table.
734
+ example : Mapping
735
+ The ``[build]`` table of the class's example.
736
+
737
+ Returns
738
+ -------
739
+ list of tuple
740
+ Each path and its value.
741
+ """
742
+ held = _held(build, row.path)
743
+ current = deepcopy(list(held)) if isinstance(held, Sequence) else []
744
+ wanted = _held(example, row.path)
745
+ source = list(wanted) if isinstance(wanted, Sequence) else []
746
+ kept = [e for e in current if e.get("type") != row.member]
747
+ if on:
748
+ kept += deepcopy([e for e in source if e.get("type") == row.member])
749
+ order = [e.get("type") for e in source]
750
+ kept.sort(
751
+ key=lambda e: order.index(e.get("type")) if e.get("type") in order else 99
752
+ )
753
+ # The list's own entries are written in place, so the rows' values reach them.
754
+ tree = {row.path: kept}
755
+ for section in problem.sections:
756
+ for linked in section.fields:
757
+ value = _held(build, linked.path)
758
+ for pattern in linked.also if value is not MISSING else ():
759
+ if pattern.startswith(f"{row.path}["):
760
+ for path in linked_paths(tree, pattern):
761
+ tree = set_path(tree, path, value)
762
+ kept = tree[row.path]
763
+ changes: list[tuple[str, object]] = [(row.path, kept)]
764
+ for path in row.goes_with:
765
+ changes.append((path, _held(example, path) if on else MISSING))
766
+ return changes
767
+
768
+
769
+ def field_changes(
770
+ problem: ProblemClass,
771
+ row: Field,
772
+ value: object,
773
+ build: Mapping[str, object],
774
+ example: Mapping[str, object] | None = None,
775
+ ) -> list[tuple[str, object]]:
776
+ """Return what a sheet's row changes in a recipe.
777
+
778
+ The object routes write some values several times, and a run's length as its last
779
+ saved plane (#533), so one row can move several paths.
780
+
781
+ Parameters
782
+ ----------
783
+ problem : ProblemClass
784
+ The class.
785
+ row : Field
786
+ The row.
787
+ value : object
788
+ What it now shows.
789
+ build : Mapping
790
+ The recipe's ``[build]`` table.
791
+ example : Mapping or None, optional
792
+ The ``[build]`` table of the class's example, where a switch's entry comes from.
793
+
794
+ Returns
795
+ -------
796
+ list of tuple
797
+ Each path and its value, or :data:`MISSING`.
798
+
799
+ Examples
800
+ --------
801
+ >>> problem = ProblemClass("c", "C", "", "radial", "e", (), (), "")
802
+ >>> build = {"gas": "Ar", "list": [{"gas": "Ar"}], "planes": ["1 m", "2 m"]}
803
+ >>> field_changes(problem, Field("gas", also=("list[*].gas",)), "He", build)
804
+ [('gas', 'He'), ('list[0].gas', 'He')]
805
+ >>> field_changes(problem, Field("length", moves_planes="planes"), "4 m", build)
806
+ [('length', '4 m'), ('planes', ['2 m', '4 m'])]
807
+ >>> build["length"] = "6 m"
808
+ >>> field_changes(problem, Field("planes", planes_over="length"), 3, build)
809
+ [('planes', ['2 m', '4 m', '6 m'])]
810
+ >>> field_changes(problem, Field("x", negated=True), "5 cm", build)
811
+ [('x', '-5 cm')]
812
+ """
813
+ if row.member is not None:
814
+ return _switched(problem, row, bool(value), build, example or {})
815
+ if row.planes_over is not None:
816
+ length = _held(build, row.planes_over)
817
+ return [(row.path, even_planes(int(value), length))] # pyright: ignore[reportArgumentType]
818
+ written = negated_value(value) if row.negated else value
819
+ changes: list[tuple[str, object]] = [(row.path, written)]
820
+ for pattern in row.also:
821
+ changes += [(path, written) for path in linked_paths(build, pattern)]
822
+ if row.moves_planes is not None and value is not MISSING:
823
+ held = _held(build, row.moves_planes)
824
+ count = len(held) if isinstance(held, Sequence) else 0
825
+ if count:
826
+ changes.append((row.moves_planes, even_planes(count, value)))
827
+ return changes
828
+
829
+
830
+ def other_keywords(
831
+ problem: ProblemClass, description: Mapping[str, object]
832
+ ) -> list[Mapping[str, object]]:
833
+ """Return the route's keywords a class's sheet does not show, for its Advanced.
834
+
835
+ A sheet row on a path inside a keyword (``initial.waist``) leaves the keyword itself
836
+ among these, since the rest of it is reachable only there.
837
+
838
+ Parameters
839
+ ----------
840
+ problem : ProblemClass
841
+ The class.
842
+ description : Mapping
843
+ The kernel's ``describe`` reply on its route.
844
+
845
+ Returns
846
+ -------
847
+ list of Mapping
848
+ The keywords' metadata, in the route's order.
849
+
850
+ Examples
851
+ --------
852
+ >>> rows = (Field("radius"),)
853
+ >>> problem = ProblemClass(
854
+ ... "c", "C", "", "capillary", "rdw", (Section("S", rows),), (), "β₂"
855
+ ... )
856
+ >>> described = {"parameters": [{"name": "radius"}, {"name": "rtol"}]}
857
+ >>> other_keywords(problem, described)
858
+ [{'name': 'rtol'}]
859
+ """
860
+ # A switch shows one entry of a list: the rest of the list is reachable only there.
861
+ shown = {
862
+ row.path
863
+ for section in problem.sections
864
+ for row in section.fields
865
+ if row.member is None
866
+ }
867
+ entries: Sequence[Mapping[str, object]] = description["parameters"] # pyright: ignore[reportAssignmentType]
868
+ return [entry for entry in entries if entry.get("name") not in shown]