• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

GFZ / EL_PASO / 45597149727

25 Nov 2026 10:33AM UTC coverage: 71.298% (+0.1%) from 71.188%
45597149727

Pull #254

github

web-flow
Merge bbd2a73f9 into e0f4ca176
Pull Request #254: Simplify the plot CLI: comma-separated option values

67 of 73 new or added lines in 3 files covered. (91.78%)

39 existing lines in 4 files now uncovered.

7651 of 10731 relevant lines covered (71.3%)

0.71 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.59
/el_paso/cli/plot_cli.py
1
# SPDX-FileCopyrightText: 2026 GFZ Helmholtz Centre for Geosciences
2
# SPDX-FileContributor: Bernhard Haas
3
# SPDX-FileContributor: Sahil Jhawar
4
#
5
# SPDX-License-Identifier: Apache-2.0
6

7
"""The ``el-paso plot`` command: quick-look plots of data a recipe has already processed.
8

9
``el-paso plot <mission> <recipe>`` takes the same arguments as ``el-paso <mission> <recipe>``.
10
It never processes or downloads anything; it finds the processed files through the strategy
11
factory the recipe registers, so file names are worked out in one place. Its options come from
12
three sources:
13

14
- shared with processing: ``--start-time``/``--end-time`` (from the recipe signature),
15
  ``-v``/``--quiet`` and ``--dry-run``;
16
- the strategy factory's signature, e.g. ``--satellite``, ``--mag-field``,
17
  ``--processed-data-path``, with the recipe's defaults, so that the same arguments find the
18
  files a processing run wrote;
19
- plot-only options: ``--variable``, ``--energy``, ``--pitch-angle``, ``--vmin``, ``--vmax``,
20
  ``--along``, ``--output-dir``, ``--filename``,
21
  ``--show`` and ``--export-script``.
22

23
Processing-only options such as ``--num-cores`` or ``--raw-data-path`` are not part of the
24
factory's signature and so are rejected.
25

26
Plot settings come in layers: the defaults of each variable's plot type (in `DataSet.plot`), then
27
the recipe's ``PLOT_DEFAULTS``, then the plot-only options. ``PLOT_DEFAULTS`` is a dict with an
28
optional ``"panels"`` list of internal names, used when ``--variable`` is not given, and settings per
29
internal name with keys from :data:`el_paso.dataset.plot.PANEL_SETTING_NAMES`::
30

31
    PLOT_DEFAULTS = {
32
        "panels": ["FEDU", "L_star", "MLT"],
33
        "FEDU": {"pitch_angle": 90 * u.deg, "energies": [470, 1575] * u.keV, "vmin": 1e0, "vmax": 1e6},
34
    }
35

36
``--variable`` replaces the panel list and ignores ``PLOT_DEFAULTS`` entirely (the variable-type defaults
37
still apply); ``--energy``, ``--pitch-angle``, ``--vmin``, ``--vmax`` and ``--along`` override the
38
matching setting of every panel. A variable's ``"along"`` setting (``"L_star"``, ``"L_m"`` or ``"R_Eq"``)
39
draws it as scatter panels over time with that coordinate on the y axis.
40
"""
41

42
from __future__ import annotations
1 ✔
43

44
import dataclasses
1 ✔
45
import inspect
1 ✔
46
import logging
1 ✔
47
import re
1 ✔
48
from pathlib import Path
1 ✔
49
from typing import TYPE_CHECKING, Annotated, Any, cast
1 ✔
50

51
import typer
1 ✔
52
from rich.table import Table
1 ✔
53

54
import el_paso as ep
1 ✔
55
from el_paso.cli._logging import _log_level, _log_table
1 ✔
56
from el_paso.cli._parsing import _expand_loops, _format_value, _func_name, parse_docstring
1 ✔
57
from el_paso.cli.availability import AVAILABILITY_PARAMETER, load_availability_table
1 ✔
58
from el_paso.cli.plot_figure import DEFAULT_COLORMAP, INDEX_PANELS, build_figure
1 ✔
59
from el_paso.cli.plot_script import write_plot_script
1 ✔
60
from el_paso.cli.recipe_cli import (
1 ✔
61
    FACTORY_ONLY_PARAMETERS,
62
    _apply_availability,
63
    _attach_signature,
64
    _build_parameter_specs,
65
    _coverage_text,
66
    _has_availability_parameters,
67
    _restore_parsed_values,
68
    _spec_parameters,
69
    _universal_parameters,
70
    check_strategy_factory,
71
)
72

73
if TYPE_CHECKING:
74
    from collections.abc import Callable, Mapping, Sequence
75
    from datetime import datetime
76

77
    from astropy import units as u
78

79
    from el_paso.cli.availability import AvailabilitySource, DateInterval
80
    from el_paso.dataset import DataSet
81
    from el_paso.typing import InternalName, Recipe, SavingStrategy
82

83
logger = logging.getLogger("el_paso.cli")
1 ✔
84

85
TIME_PARAMETER_NAMES = ("start_time", "end_time")
1 ✔
86
"""Recipe parameters the plot command takes over from the recipe, next to the factory's parameters."""
1 ✔
87

88
_SHARED_PARAMETER_NAMES = ("verbose", "quiet")
1 ✔
89
"""Universal recipe-command options the plot command shares; see `recipe_cli._universal_parameters`."""
1 ✔
90

91
PANELS_KEY = "panels"
1 ✔
92
"""Key of the default panel list in a recipe's ``PLOT_DEFAULTS``; every other key is a variable's settings."""
1 ✔
93

94
ALONG_CHOICES: tuple[InternalName, ...] = ("L_star", "L_m", "R_Eq")
1 ✔
95
"""The coordinates ``--along`` accepts, which it puts on the y axis of the panels.
1 ✔
96

97
They are those of :data:`el_paso.dataset.plot.ALONG_COORDINATES`."""
98

99
_PLOT_PARAMETER_NAMES = (
1 ✔
100
    "dry_run",
101
    "variables",
102
    "energies",
103
    "pitch_angle",
104
    "vmin",
105
    "vmax",
106
    "colormap",
107
    "along",
108
    "output_dir",
109
    "filename",
110
    "show",
111
    "export_script",
112
)
113
"""Options defined here: ``--dry-run`` is shared with processing in name only, the rest are plot-only."""
1 ✔
114

115

116
@dataclasses.dataclass(frozen=True)
1 ✔
117
class PlotRequest:
1 ✔
118
    """Everything a plot run needs, resolved from the command line.
119

120
    Attributes:
121
        recipe: The recipe that processed the data.
122
        factory: The recipe's strategy factory.
123
        start_time: Start of the time range to plot.
124
        end_time: End of the time range to plot.
125
        strategy_kwargs: Arguments for `factory`, one set per value of a looped parameter
126
            (one per satellite).
127
        variables: Internal names of the variables given with ``--variable``, or ``None`` for the
128
            recipe's default panels (see `resolve_panels`).
129
        output_dir: Directory to write the figure to, or ``None`` for the current directory.
130
        filename: Name of the figure's file, or ``None`` for the default name (see `default_filename`).
131
        show: Open an interactive window.
132
        dry_run: Only report what would be plotted.
133
        verbose: Log every file that is loaded.
134
        plot_defaults: The recipe's ``PLOT_DEFAULTS``.
135
        processing_command: The command that runs the recipe, e.g. ``el-paso rbsp mageis-electrons``,
136
            suggested when processed files are missing. ``None`` for ``python -m <recipe module>``.
137
        energies: Energies to show for variables with an energy dimension (``--energy``), or
138
            ``None`` for the defaults.
139
        pitch_angle: Pitch angle at which variables with an energy and a pitch-angle dimension are
140
            cut (``--pitch-angle``), or ``None`` for the defaults.
141
        vmin: Lower colour limit of spectrograms (``--vmin``), in the plotted variable's unit.
142
        vmax: Upper colour limit of spectrograms (``--vmax``), in the plotted variable's unit.
143
        along: Coordinate on the y axis of scatter panels (``--along``), or ``None`` for the usual plot types.
144
        colormap: Colormap of spectrograms and scatter panels (``--colormap``).
145
        export_script: File to write a standalone Python script that makes the figure to, instead of
146
            plotting (``--export-script``), or ``None`` to plot.
147
        availability: The satellites the recipe's availability table has data for in the time range,
148
            with their overlapping intervals, or ``None`` if the recipe has no table.
149
    """
150

151
    recipe: Recipe
1 ✔
152
    factory: Callable[..., SavingStrategy]
1 ✔
153
    start_time: datetime
1 ✔
154
    end_time: datetime
1 ✔
155
    strategy_kwargs: list[dict[str, Any]]
1 ✔
156
    variables: list[str] | None
1 ✔
157
    output_dir: Path | None
1 ✔
158
    filename: str | None
1 ✔
159
    show: bool
1 ✔
160
    dry_run: bool
1 ✔
161
    verbose: bool
1 ✔
162
    plot_defaults: dict[str, Any]
1 ✔
163
    processing_command: str | None = None
1 ✔
164
    energies: u.Quantity | None = None
1 ✔
165
    pitch_angle: u.Quantity | None = None
1 ✔
166
    vmin: float | None = None
1 ✔
167
    vmax: float | None = None
1 ✔
168
    along: InternalName | None = None
1 ✔
169
    colormap: str = DEFAULT_COLORMAP
1 ✔
170
    export_script: Path | None = None
1 ✔
171
    availability: dict[str, list[DateInterval]] | None = None
1 ✔
172

173

174
def _internal_names() -> tuple[str, ...]:
1 ✔
175
    """Every internal variable name of the data standard, in the order of `el_paso.typing.InternalName`."""
176
    from typing import get_args  # noqa: PLC0415
1 ✔
177

178
    from el_paso.typing import InternalName  # noqa: PLC0415
1 ✔
179

180
    return tuple(name for group in get_args(InternalName) for name in get_args(group))
1 ✔
181

182

183
def list_variables() -> None:
1 ✔
184
    """List the internal variable names that ``--variable`` accepts."""
185
    from rich.console import Console  # noqa: PLC0415
1 ✔
186

187
    from el_paso.data_standards import GFZStandard  # noqa: PLC0415
1 ✔
188

189
    infos = GFZStandard().variable_infos
1 ✔
190
    table = Table(title="Internal variable names for --variable")
1 ✔
191
    table.add_column("Name", style="bold cyan", no_wrap=True)
1 ✔
192
    table.add_column("Kind")
1 ✔
193
    table.add_column("Description")
1 ✔
194
    for name in sorted(_internal_names(), key=str.lower):
1 ✔
195
        info = infos.get(name)
1 ✔
196
        table.add_row(
1 ✔
197
            name,
198
            "space-weather index" if name in INDEX_PANELS else "dataset variable",
199
            info.description if info is not None else "",
200
        )
201
    Console().print(table)
1 ✔
202

203

204
def _plot_parameters() -> list[inspect.Parameter]:
1 ✔
205
    """Options defined by the plot command itself, independent of the recipe."""
206
    definitions: list[tuple[str, Any, Any]] = [
1 ✔
207
        (
208
            "dry_run",
209
            Annotated[
210
                bool,
211
                typer.Option(
212
                    "--dry-run",
213
                    help="Print the saving strategy and the expected files, and which of them exist, "
214
                    "then exit without plotting.",
215
                ),
216
            ],
217
            False,
218
        ),
219
        (
220
            "variables",
221
            Annotated[
222
                list[str] | None,
223
                typer.Option(
224
                    "--variable",
225
                    help="Comma-separated internal names of the variables to plot, each in its own panel, "
226
                    "e.g. --variable FEDU,L_star. Required unless the recipe defines quick-look panels. "
227
                    "Run 'el-paso plot variables' for the list of internal names.",
228
                ),
229
            ],
230
            None,
231
        ),
232
        (
233
            "energies",
234
            Annotated[
235
                list[str] | None,
236
                typer.Option(
237
                    "--energy",
238
                    metavar="ENERGY",
239
                    help="Comma-separated energies to show for variables with an energy dimension (e.g. FEDU), "
240
                    "e.g. --energy 470,1575. Bare numbers are in keV; a unit may be added, e.g. 1MeV.",
241
                ),
242
            ],
243
            None,
244
        ),
245
        (
246
            "pitch_angle",
247
            Annotated[
248
                float | None,
249
                typer.Option(
250
                    "--pitch-angle",
251
                    metavar="DEG",
252
                    min=0.0,
253
                    max=180.0,
254
                    help="Pitch angle in degrees at which variables with an energy and a pitch-angle "
255
                    "dimension (e.g. FEDU) are shown, defaulting to 90. If given, variables that only depend on "
256
                    "pitch angle (e.g. L_star) are drawn as a line at this pitch angle.",
257
                ),
258
            ],
259
            None,
260
        ),
261
        *(
262
            (
263
                bound,
264
                Annotated[
265
                    float | None,
266
                    typer.Option(
267
                        f"--{bound}",
268
                        help=f"{limit} colour limit of spectrograms and --along scatter panels (y-limit of "
269
                        "--energy line panels), in the unit of the plotted variable. "
270
                        f"Defaults to the {percentile}th percentile of the data.",
271
                    ),
272
                ],
273
                None,
274
            )
275
            for bound, limit, percentile in (("vmin", "Lower", 5), ("vmax", "Upper", 95))
276
        ),
277
        (
278
            "colormap",
279
            Annotated[
280
                str,
281
                typer.Option(
282
                    "--colormap",
283
                    help="Colormap of spectrograms and --along scatter panels: a colorcet name "
284
                    "(e.g. rainbow4, fire, CET_L17) or a matplotlib colormap name (e.g. viridis).",
285
                ),
286
            ],
287
            DEFAULT_COLORMAP,
288
        ),
289
        (
290
            "along",
291
            Annotated[
292
                str | None,
293
                typer.Option(
294
                    "--along",
295
                    metavar="|".join(ALONG_CHOICES),
296
                    help="Draw every variable as a scatter plot over time with this coordinate on the y axis "
297
                    "and the value as colour. Variables with an energy dimension get one panel per --energy, "
298
                    "or per channel without --energy; pitch angles are cut at --pitch-angle (default 90).",
299
                ),
300
            ],
301
            None,
302
        ),
303
        (
304
            "output_dir",
305
            Annotated[
306
                Path | None,
307
                typer.Option(
308
                    "--output-dir",
309
                    help="Directory to write the figure to, created if missing. Defaults to the current directory.",
310
                ),
311
            ],
312
            None,
313
        ),
314
        (
315
            "filename",
316
            Annotated[
317
                str | None,
318
                typer.Option(
319
                    "--filename",
320
                    help="Name of the figure's file; the format follows its suffix. "
321
                    "Defaults to <recipe>_<satellite>_<start>_<end>.png. "
322
                    "The figure is only written if this or --output-dir is given, or if --show is not.",
323
                ),
324
            ],
325
            None,
326
        ),
327
        (
328
            "show",
329
            Annotated[bool, typer.Option("--show", help="Open the figure in an interactive window.")],
330
            False,
331
        ),
332
        (
333
            "export_script",
334
            Annotated[
335
                Path | None,
336
                typer.Option(
337
                    "--export-script",
338
                    help="Write a standalone Python script that makes this figure to this file, instead of "
339
                    "plotting. Edit the script to customise the figure.",
340
                ),
341
            ],
342
            None,
343
        ),
344
    ]
345

346
    return [
1 ✔
347
        inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, default=default, annotation=annotation)
348
        for name, annotation, default in definitions
349
    ]
350

351

352
def _factory_defaults(recipe: Recipe, factory: Callable[..., Any], defaults: dict[str, Any]) -> dict[str, Any]:
1 ✔
353
    """Defaults for the factory's options: the recipe's, so that plot finds what processing wrote.
354

355
    The recipe's CLI defaults take precedence over its signature, as in the processing command.
356
    """
357
    recipe_parameters = inspect.signature(recipe).parameters
1 ✔
358
    factory_defaults: dict[str, Any] = {}
1 ✔
359

360
    for name in inspect.signature(factory).parameters:
1 ✔
361
        if name in defaults:
1 ✔
362
            factory_defaults[name] = defaults[name]
1 ✔
363
        elif name in recipe_parameters and recipe_parameters[name].default is not inspect.Parameter.empty:
1 ✔
364
            factory_defaults[name] = recipe_parameters[name].default
1 ✔
365

366
    return factory_defaults
1 ✔
367

368

369
def panel_settings(plot_defaults: Mapping[str, Any]) -> dict[str, Any]:
1 ✔
370
    """The per-variable settings of a recipe's ``PLOT_DEFAULTS``: everything but the panel list."""
371
    return {name: settings for name, settings in plot_defaults.items() if name != PANELS_KEY}
1 ✔
372

373

374
def check_plot_defaults(plot_defaults: Mapping[str, Any]) -> None:
1 ✔
375
    """Validate a recipe's ``PLOT_DEFAULTS``, so that a mistake fails when the command is built.
376

377
    Args:
378
        plot_defaults (Mapping[str, Any]): The recipe's ``PLOT_DEFAULTS``: an optional ``"panels"``
379
            list of internal names and settings per internal name (see
380
            :func:`el_paso.dataset.plot.check_panel_settings`).
381

382
    Raises:
383
        TypeError: If ``PLOT_DEFAULTS`` is not a dict, its panel list is not a non-empty list of names,
384
            or a setting is unknown or has the wrong type.
385
        ValueError: If a setting is out of range, a variable's `vmin` is not below its `vmax`, or settings
386
            are given for a variable that is not in the panel list (they would never be used, since
387
            ``--variable`` switches ``PLOT_DEFAULTS`` off).
388
    """
389
    if not isinstance(plot_defaults, dict):
1 ✔
UNCOV
390
        msg = f"PLOT_DEFAULTS must be a dict, got {type(plot_defaults).__name__}."
×
391
        raise TypeError(msg)
×
392

393
    panels = plot_defaults.get(PANELS_KEY)
1 ✔
394
    if panels is not None and (
1 ✔
395
        not isinstance(panels, (list, tuple))
396
        or not panels
397
        or not all(isinstance(name, str) and name for name in panels)
398
    ):
399
        msg = f"PLOT_DEFAULTS[{PANELS_KEY!r}] must be a non-empty list of internal variable names, got {panels!r}."
1 ✔
400
        raise TypeError(msg)
1 ✔
401

402
    settings = panel_settings(plot_defaults)
1 ✔
403
    try:
1 ✔
404
        from el_paso.dataset.plot import check_panel_settings  # noqa: PLC0415
1 ✔
405

406
        check_panel_settings(settings)
1 ✔
407
    except (TypeError, ValueError) as error:
1 ✔
408
        msg = f"Invalid PLOT_DEFAULTS: {error}"
1 ✔
409
        raise type(error)(msg) from error
1 ✔
410

411
    unused = [name for name in settings if name not in (panels or ())]
1 ✔
412
    if unused:
1 ✔
413
        import difflib  # noqa: PLC0415
1 ✔
414

415
        hints = [
1 ✔
416
            f"{name!r} (did you mean {matches[0]!r}?)"
417
            if (matches := difflib.get_close_matches(name, panels or (), n=1))
418
            else repr(name)
419
            for name in unused
420
        ]
421
        msg = (
1 ✔
422
            f"Invalid PLOT_DEFAULTS: settings for {', '.join(hints)}, which is not in "
423
            f"PLOT_DEFAULTS[{PANELS_KEY!r}] = {list(panels or ())!r}; they would never be used."
424
        )
425
        raise ValueError(msg)
1 ✔
426

427

428
def build_plot_command(
1 ✔
429
    recipe: Recipe,
430
    factory: Callable[..., SavingStrategy],
431
    *,
432
    defaults: dict[str, Any] | None = None,
433
    loop_over: Sequence[str] | None = None,
434
    plot_defaults: dict[str, Any] | None = None,
435
    processing_command: str | None = None,
436
    availability: AvailabilitySource | None = None,
437
) -> Callable[..., None]:
438
    """Build the Typer-compatible ``el-paso plot`` command for one recipe.
439

440
    The command's options are the recipe's time range, the strategy factory's parameters and
441
    the plot-only options, built by the same machinery as the processing command (see
442
    :func:`el_paso.cli.recipe_cli.build_recipe_command`).
443

444
    Args:
445
        recipe (Recipe): The recipe whose output is plotted.
446
        factory (Callable[..., SavingStrategy]): The recipe's strategy factory. It is checked against
447
            the recipe with :func:`el_paso.cli.recipe_cli.check_strategy_factory`.
448
        defaults (dict[str, Any] | None): The recipe's CLI defaults, which override the defaults of
449
            its signature exactly as in the processing command.
450
        loop_over (Sequence[str] | None): Parameters that accept several values. Defaults to any
451
            parameter named in :data:`el_paso.cli.recipe_cli.LOOP_PARAMETER_NAMES`.
452
        plot_defaults (dict[str, Any] | None): The recipe's ``PLOT_DEFAULTS``, checked with
453
            :func:`check_plot_defaults`.
454
        processing_command (str | None): The command that runs the recipe, e.g.
455
            ``el-paso rbsp mageis-electrons``, suggested when processed files are missing.
456
            Defaults to ``python -m <recipe module>``.
457
        availability (AvailabilitySource | None): The recipe's satellite availability table. With it,
458
            ``--satellite all`` only plots the satellites that have data in the time range, exactly as
459
            in the processing command, and ``--dry-run`` says whether each satellite has data.
460

461
    Returns:
462
        Callable[..., None]: A callable ready to be registered with ``app.command()``.
463

464
    Raises:
465
        TypeError: If the factory does not match the recipe, if a factory parameter has the
466
            same name as a shared or plot-only option, or if `plot_defaults` is malformed.
467
        ValueError: If a setting in `plot_defaults` is out of range.
468
    """
469
    defaults = dict(defaults or {})
1 ✔
470
    plot_defaults = dict(plot_defaults or {})
1 ✔
471
    check_strategy_factory(recipe, factory, loop_over=loop_over)
1 ✔
472
    check_plot_defaults(plot_defaults)
1 ✔
473

474
    _, recipe_help = parse_docstring(recipe.__doc__)
1 ✔
475
    _, factory_help = parse_docstring(factory.__doc__)
1 ✔
476

477
    time_specs, _ = _build_parameter_specs(
1 ✔
478
        recipe,
479
        defaults=defaults,
480
        names=TIME_PARAMETER_NAMES,
481
        arg_help={"start_time": "Start of the time range to plot.", "end_time": "End of the time range to plot."},
482
    )
483
    factory_specs, _ = _build_parameter_specs(
1 ✔
484
        factory,
485
        defaults=_factory_defaults(recipe, factory, defaults),
486
        loop_over=loop_over,
487
        # the factory describes its parameters as the data to find, the recipe as the data to write
488
        arg_help={**recipe_help, **{name: text for name, text in factory_help.items() if text}},
489
    )
490
    specs = [*time_specs, *factory_specs]
1 ✔
491
    loop_names = [spec.name for spec in factory_specs if spec.is_loop]
1 ✔
492
    with_availability = availability is not None and _has_availability_parameters(specs)
1 ✔
493

494
    def command(**kwargs: Any) -> None:  # noqa: ANN401
1 ✔
495
        shared = {name: kwargs.pop(name) for name in _SHARED_PARAMETER_NAMES}
1 ✔
496
        plot_options = {name: kwargs.pop(name) for name in _PLOT_PARAMETER_NAMES}
1 ✔
497

498
        expanded_all = _restore_parsed_values(kwargs, specs)
1 ✔
499
        start_time = kwargs.pop("start_time")
1 ✔
500
        end_time = kwargs.pop("end_time")
1 ✔
501
        if end_time <= start_time:
1 ✔
502
            msg = f"must be after --start-time ({start_time.isoformat()}), got {end_time.isoformat()}."
1 ✔
503
            raise typer.BadParameter(msg, param_hint="'--end-time'")
1 ✔
504

505
        coverage = None
1 ✔
506
        notices: list[tuple[int, str]] = []
1 ✔
507
        if with_availability:
1 ✔
508
            coverage, notices = _apply_availability(
1 ✔
509
                kwargs,
510
                load_availability_table(availability),  # ty: ignore[invalid-argument-type]
511
                start_time,
512
                end_time,
513
                expanded_all=expanded_all,
514
                label=_func_name(recipe),
515
            )
516

517
        plot_options = _parse_plot_options(plot_options)
1 ✔
518

519
        strategy_kwargs = _expand_loops(kwargs, loop_names)
1 ✔
520
        for call_kwargs in strategy_kwargs:
1 ✔
521
            # Fails loudly if the generated command ever drifts from the factory signature.
522
            inspect.signature(factory).bind(**call_kwargs)
1 ✔
523

524
        # The dry-run report is logged at INFO, and printing it is the whole point of --dry-run.
525
        quiet = shared["quiet"] and not plot_options["dry_run"]
1 ✔
526
        ep.setup_logging(_log_level(verbose=shared["verbose"], quiet=quiet))
1 ✔
527
        for level, message in notices:
1 ✔
528
            logger.log(level, message)
1 ✔
529

530
        _run_plot(
1 ✔
531
            PlotRequest(
532
                recipe=recipe,
533
                factory=factory,
534
                start_time=start_time,
535
                end_time=end_time,
536
                strategy_kwargs=strategy_kwargs,
537
                verbose=shared["verbose"] >= 1,
538
                plot_defaults=plot_defaults,
539
                processing_command=processing_command,
540
                availability=coverage,
541
                **plot_options,
542
            )
543
        )
544

545
    command.__name__ = f"plot_{_func_name(recipe)}"
1 ✔
546
    _attach_signature(
1 ✔
547
        command,
548
        [*_spec_parameters(specs), *_universal_parameters(_SHARED_PARAMETER_NAMES), *_plot_parameters()],
549
    )
550
    command.__doc__ = (
1 ✔
551
        f"Plot data processed by {_func_name(recipe)}.\n\n"
552
        "Takes the same arguments as the processing command; nothing is processed. Only space-weather\n"
553
        "indices and solar wind parameters (Kp, Dst, Vsw, ...) are downloaded if missing."
554
    )
555
    return command
1 ✔
556

557

558
def _parse_energy(text: str) -> float:
1 ✔
559
    """Parse an ``--energy`` value such as ``470``, ``100keV`` or ``1 MeV`` to keV; a bare number is in keV.
560

561
    Raises:
562
        typer.BadParameter: If the text is not a number with an optional energy unit.
563
    """
564
    match = re.fullmatch(r"\s*([-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?)\s*([^\d\s].*?)?\s*", text)
1 ✔
565
    if match is None:
1 ✔
566
        msg = f"{text!r} is not an energy; use a number with an optional unit, e.g. 470 or 1MeV."
1 ✔
567
        raise typer.BadParameter(msg, param_hint="'--energy'")
1 ✔
568
    number, unit_text = match.groups()
1 ✔
569
    from astropy import units as u  # noqa: PLC0415
1 ✔
570

571
    try:
1 ✔
572
        unit = u.Unit(unit_text) if unit_text else u.keV
1 ✔
573
    except ValueError as error:
1 ✔
574
        msg = f"unknown unit {unit_text!r} in {text!r}."
1 ✔
575
        raise typer.BadParameter(msg, param_hint="'--energy'") from error
1 ✔
576
    if not unit.is_equivalent(u.keV):
1 ✔
577
        msg = f"{text!r} is not an energy (unit {unit_text!r})."
1 ✔
578
        raise typer.BadParameter(msg, param_hint="'--energy'")
1 ✔
579
    return float((float(number) * unit).to_value(u.keV))
1 ✔
580

581

582
def _parse_plot_options(plot_options: dict[str, Any]) -> dict[str, Any]:
1 ✔
583
    """Validate the plot options and resolve them into the corresponding `PlotRequest` fields.
584

585
    Checks ``--variable``, ``--energy``, ``--pitch-angle``, ``--vmin``, ``--vmax`` and ``--along``.
586

587
    Returns:
588
        dict[str, Any]: The options as `PlotRequest` fields: the energies in keV, the pitch angle in
589
            degrees and the ``--along`` coordinate (``None`` where not given).
590

591
    Raises:
592
        typer.BadParameter: If an energy is not positive, ``--vmin`` is not below ``--vmax``, or ``--along`` is
593
            not a known coordinate.
594
    """
595
    from astropy import units as u  # noqa: PLC0415
1 ✔
596

597
    energies = None
1 ✔
598
    if plot_options["energies"]:
1 ✔
599
        texts = [part for item in plot_options["energies"] for part in item.split(",") if part.strip()]
1 ✔
600
        if not texts:
1 ✔
601
            msg = "no energy given; use a comma-separated list, e.g. 470,1575."
1 ✔
602
            raise typer.BadParameter(msg, param_hint="'--energy'")
1 ✔
603
        values = [_parse_energy(text) for text in texts]
1 ✔
604
        if any(value <= 0 for value in values):
1 ✔
605
            msg = f"must be positive, got {', '.join(texts)}."
1 ✔
606
            raise typer.BadParameter(msg, param_hint="'--energy'")
1 ✔
607
        energies = u.Quantity(values, u.keV)
1 ✔
608

609
    vmin, vmax = plot_options["vmin"], plot_options["vmax"]
1 ✔
610
    if vmin is not None and vmax is not None and not vmin < vmax:
1 ✔
611
        msg = f"must be below --vmax ({vmax:g}), got {vmin:g}."
1 ✔
612
        raise typer.BadParameter(msg, param_hint="'--vmin'")
1 ✔
613

614
    along = None
1 ✔
615
    if plot_options["along"] is not None:
1 ✔
616
        along = next((name for name in ALONG_CHOICES if name.lower() == plot_options["along"].lower()), None)
1 ✔
617
        if along is None:
1 ✔
618
            msg = f"{plot_options['along']!r} is not a coordinate; choose from {', '.join(ALONG_CHOICES)}."
1 ✔
619
            raise typer.BadParameter(msg, param_hint="'--along'")
1 ✔
620

621
    variables = [part for item in plot_options["variables"] or [] for part in map(str.strip, item.split(",")) if part]
1 ✔
622

623
    filename = plot_options["filename"]
1 ✔
624
    if filename is not None and Path(filename).name != filename:
1 ✔
625
        msg = f"must be a file name without a directory, got {filename!r}. Use --output-dir for the directory."
1 ✔
626
        raise typer.BadParameter(msg, param_hint="'--filename'")
1 ✔
627

628
    pitch_angle = None if plot_options["pitch_angle"] is None else plot_options["pitch_angle"] * u.deg
1 ✔
629
    return {
1 ✔
630
        **plot_options,
631
        "variables": variables or None,
632
        "energies": energies,
633
        "pitch_angle": pitch_angle,
634
        "along": along,
635
    }
636

637

638
def _format_quantity(value: u.Quantity) -> str:
1 ✔
639
    """A quantity for the settings table, e.g. ``470, 1000 keV``."""
640
    return f"{', '.join(f'{item:g}' for item in value.value.ravel())} {value.unit}"
1 ✔
641

642

643
def resolve_panels(request: PlotRequest) -> list[InternalName] | None:
1 ✔
644
    """The panel list: ``--variable`` if given, otherwise the recipe's default panels, otherwise ``None``."""
645
    panels = request.variables or request.plot_defaults.get(PANELS_KEY)
1 ✔
646
    return cast("list[InternalName]", list(panels)) if panels else None
1 ✔
647

648

649
def split_panels(panels: Sequence[str] | None) -> tuple[list[str], list[InternalName]]:
1 ✔
650
    """Split a panel list into space-weather indices (`INDEX_PANELS`) and dataset variables, keeping the order."""
651
    indices = [name for name in panels or [] if name in INDEX_PANELS]
1 ✔
652
    variables = [name for name in panels or [] if name not in INDEX_PANELS]
1 ✔
653
    return indices, cast("list[InternalName]", variables)
1 ✔
654

655

656
def _dataset_names(request: PlotRequest) -> list[InternalName] | None:
1 ✔
657
    """Dataset variables a request reads: the non-index panels and the ``--along`` coordinate.
658

659
    ``None`` if there are none, which `DataSet.get_file_coverage` takes as every output file.
660
    """
661
    names = split_panels(resolve_panels(request))[1]
1 ✔
662
    recipe_settings = _recipe_settings(request)
1 ✔
663
    coordinates = {request.along} if request.along else {recipe_settings.get(name, {}).get("along") for name in names}
1 ✔
664
    names.extend(sorted(c for c in coordinates if c and c not in names))
1 ✔
665
    return names or None
1 ✔
666

667

668
def _recipe_settings(request: PlotRequest) -> dict[str, Any]:
1 ✔
669
    """The recipe's per-variable settings: none if ``--variable`` is given, which ignores ``PLOT_DEFAULTS``."""
670
    return {} if request.variables else panel_settings(request.plot_defaults)
1 ✔
671

672

673
def _setting_overrides(request: PlotRequest) -> dict[str, Any]:
1 ✔
674
    """The settings given on the command line, which override those of every panel (layer 3)."""
675
    return {
1 ✔
676
        "energies": request.energies,
677
        "pitch_angle": request.pitch_angle,
678
        "vmin": request.vmin,
679
        "vmax": request.vmax,
680
    }
681

682

683
def _check_panel_settings(request: PlotRequest, panels: Sequence[str]) -> None:
1 ✔
684
    """Fail early if the command-line settings clash with the recipe's (e.g. ``--vmin`` above its vmax).
685

686
    Raises:
687
        typer.BadParameter: If the layered settings of a panel are invalid.
688
    """
689
    from el_paso.dataset.plot import resolve_panel_settings  # noqa: PLC0415
1 ✔
690

691
    try:
1 ✔
692
        resolve_panel_settings(panels, _recipe_settings(request), _setting_overrides(request))
1 ✔
693
    except (TypeError, ValueError) as error:
1 ✔
694
        msg = f"conflicts with the recipe's plot defaults: {error}"
1 ✔
695
        raise typer.BadParameter(msg, param_hint="'--vmin' / '--vmax'") from error
1 ✔
696

697

698
def _report_settings(request: PlotRequest) -> None:
1 ✔
699
    """Show the resolved settings of a plot run, as processing runs do for their arguments."""
700
    prefix = "Would plot" if request.dry_run else "Plotting"
1 ✔
701
    table = Table("Parameter", "Value", title=f"{prefix} {_func_name(request.recipe)}", padding=(0, 2, 0, 0))
1 ✔
702

703
    table.add_row("start time", _format_value("start_time", request.start_time))
1 ✔
704
    table.add_row("end time", _format_value("end_time", request.end_time))
1 ✔
705
    loop_values: dict[str, list[Any]] = {}
1 ✔
706
    for kwargs in request.strategy_kwargs:
1 ✔
707
        for name, value in kwargs.items():
1 ✔
708
            values = loop_values.setdefault(name, [])
1 ✔
709
            if value not in values:
1 ✔
710
                values.append(value)
1 ✔
711
    for name, values in loop_values.items():
1 ✔
712
        table.add_row(name.replace("_", " "), ", ".join(_format_value(name, value) for value in values))
1 ✔
713
    if request.dry_run and request.availability is not None:
1 ✔
714
        for satellite in loop_values.get(AVAILABILITY_PARAMETER, []):
1 ✔
715
            table.add_row(f"availability {satellite}", _coverage_text(request.availability, satellite))
1 ✔
716

717
    panels = resolve_panels(request)
1 ✔
718
    if request.variables:
1 ✔
719
        table.add_row("variables", ", ".join(request.variables))
1 ✔
720
    elif panels:
1 ✔
721
        table.add_row("variables", f"{', '.join(panels)} (recipe defaults)")
1 ✔
722
    else:
723
        table.add_row("variables", "none given")
1 ✔
724

725
    # a setting not given on the command line comes from the recipe if it sets it for any panel
726
    recipe_settings = _recipe_settings(request)
1 ✔
727
    for key, value in _setting_overrides(request).items():
1 ✔
728
        if value is not None:
1 ✔
729
            text = _format_quantity(value) if hasattr(value, "unit") else f"{value:g}"
1 ✔
730
        elif any(key in recipe_settings.get(name, {}) for name in panels or []):
1 ✔
731
            text = "recipe defaults"
1 ✔
732
        else:
733
            text = "default"
1 ✔
734
        table.add_row(key.replace("_", " "), text)
1 ✔
735
    if request.along:
1 ✔
736
        along_text = request.along
1 ✔
737
    elif any("along" in recipe_settings.get(name, {}) for name in panels or []):
1 ✔
738
        along_text = "recipe defaults"
1 ✔
739
    else:
740
        along_text = "none (plot types by dimensions)"
1 ✔
741
    table.add_row("along", along_text)
1 ✔
742
    output_path = _output_path(request)
1 ✔
743
    if request.export_script:
1 ✔
744
        table.add_row("export script", str(request.export_script))
1 ✔
745
    if output_path is None:
1 ✔
746
        table.add_row("output", "none (shown only)")
1 ✔
747
    else:
748
        table.add_row("output dir", str(output_path.parent.resolve()))
1 ✔
749
        table.add_row("filename", output_path.name)
1 ✔
750
    table.add_row("show", str(request.show))
1 ✔
751
    _log_table(table)
1 ✔
752

753

754
def _call_labels(strategy_kwargs: list[dict[str, Any]]) -> list[str]:
1 ✔
755
    """Label each set of factory arguments by the values that differ between the sets (e.g. ``satellite=a``).
756

757
    The settings table already shows everything else, so a single set gets an empty label.
758
    """
759
    varying = [
1 ✔
760
        name
761
        for name in strategy_kwargs[0]
762
        if len({_format_value(name, kwargs[name]) for kwargs in strategy_kwargs}) > 1
763
    ]
764
    return [", ".join(f"{name}={_format_value(name, kwargs[name])}" for name in varying) for kwargs in strategy_kwargs]
1 ✔
765

766

767
def _report_expected_files(request: PlotRequest) -> bool:
1 ✔
768
    """Print the saving strategy and expected files of every set of factory arguments.
769

770
    Returns:
771
        bool: ``True`` if the files could be determined for every set of arguments.
772
    """
773
    # Not checked against the data standard here; get_file_coverage rejects unknown names.
774
    names = _dataset_names(request)
1 ✔
775

776
    ok = True
1 ✔
777
    for kwargs, label in zip(request.strategy_kwargs, _call_labels(request.strategy_kwargs), strict=True):
1 ✔
778
        suffix = f" ({label})" if label else ""
1 ✔
779
        try:
1 ✔
780
            strategy = request.factory(**kwargs)
1 ✔
781
            dataset = ep.DataSet(strategy, request.start_time, request.end_time, verbose=False)
1 ✔
782
            coverage = dataset.get_file_coverage(names)
1 ✔
783
        except ValueError as error:
1 ✔
784
            logger.error(f"{error}{suffix}")  # noqa: TRY400
1 ✔
785
            ok = False
1 ✔
786
            continue
1 ✔
787

788
        logger.info(f"Saving strategy{suffix}: {strategy!r}")
1 ✔
789
        logger.info("Expected files:")
1 ✔
790
        for entry in coverage:
1 ✔
791
            logger.info(f"  [{'found' if entry.exists else 'missing'}] {entry.path}")
1 ✔
792
        found = sum(entry.exists for entry in coverage)
1 ✔
793
        logger.info(f"{found} of {len(coverage)} expected files exist.")
1 ✔
794

795
    return ok
1 ✔
796

797

798
def _format_time_for_file_name(time: datetime) -> str:
1 ✔
799
    """Compact time stamp for file names: the date alone at midnight, otherwise date and time."""
800
    if (time.hour, time.minute, time.second, time.microsecond) == (0, 0, 0, 0):
1 ✔
801
        return time.strftime("%Y%m%d")
1 ✔
802
    return time.strftime("%Y%m%dT%H%M%S")
1 ✔
803

804

805
def default_filename(request: PlotRequest) -> str:
1 ✔
806
    """File name of the figure when ``--filename`` is not given.
807

808
    The name is ``<recipe>_<satellite>_<start>_<end>.png``, where
809
    ``<recipe>`` is the recipe function's name without its ``process_`` prefix and ``<satellite>``
810
    joins all plotted satellites with ``-``. Recipes without a ``satellite`` parameter leave it out.
811

812
    Args:
813
        request (PlotRequest): The resolved plot request.
814

815
    Returns:
816
        str: The default file name.
817
    """
818
    recipe_name = _func_name(request.recipe).removeprefix("process_")
1 ✔
819
    satellites: list[str] = []
1 ✔
820
    for kwargs in request.strategy_kwargs:
1 ✔
821
        if "satellite" in kwargs:
1 ✔
822
            satellite = _format_value("satellite", kwargs["satellite"])
1 ✔
823
            if satellite not in satellites:
1 ✔
824
                satellites.append(satellite)
1 ✔
825

826
    parts = [recipe_name]
1 ✔
827
    if satellites:
1 ✔
828
        parts.append("-".join(satellites))
1 ✔
829
    parts += [_format_time_for_file_name(request.start_time), _format_time_for_file_name(request.end_time)]
1 ✔
830
    return "_".join(parts) + ".png"
1 ✔
831

832

833
def _output_path(request: PlotRequest) -> Path | None:
1 ✔
834
    """File the figure is written to, or ``None`` if it is only shown.
835

836
    The figure is written if ``--filename`` or ``--output-dir`` is given, or if ``--show`` is not.
837
    """
838
    if request.filename is None and request.output_dir is None and request.show:
1 ✔
839
        return None
1 ✔
840
    return (request.output_dir or Path()) / (request.filename or default_filename(request))
1 ✔
841

842

843
def _interactive_backend_error() -> str | None:
1 ✔
844
    """Explain why ``--show`` cannot open a window, or return ``None`` if it can.
845

846
    Importing pyplot resolves matplotlib's backend; without a display it falls back to Agg,
847
    which cannot show figures.
848
    """
849
    import matplotlib.pyplot as plt  # noqa: PLC0415
1 ✔
850
    from matplotlib.backends import BackendFilter, backend_registry  # noqa: PLC0415
1 ✔
851

852
    backend = plt.get_backend()
1 ✔
853
    if backend.lower() in backend_registry.list_builtin(BackendFilter.NON_INTERACTIVE):
1 ✔
854
        return (
1 ✔
855
            f"--show needs an interactive matplotlib backend, but '{backend}' is in use "
856
            "(no display available?). Use --output-dir or --filename to write the figure to a file instead, "
857
            "or set MPLBACKEND to an interactive backend."
858
        )
UNCOV
859
    return None
×
860

861

862
def _format_time_for_cli(time: datetime) -> str:
1 ✔
863
    """A time as the command line accepts it: the date alone at midnight, otherwise date and time (UTC)."""
864
    if (time.hour, time.minute, time.second, time.microsecond) == (0, 0, 0, 0):
1 ✔
865
        return time.strftime("%Y-%m-%d")
1 ✔
866
    return time.strftime("%Y-%m-%dT%H:%M:%S")
1 ✔
867

868

869
def processing_command_line(request: PlotRequest, kwargs: dict[str, Any]) -> str:
1 ✔
870
    """The processing command that writes the files one set of factory arguments expects.
871

872
    It runs the recipe for the plotted time range with every factory argument spelled out, so it
873
    writes exactly the files the plot command looks for.
874

875
    Args:
876
        request (PlotRequest): The resolved plot request.
877
        kwargs (dict[str, Any]): One set of factory arguments from ``request.strategy_kwargs``.
878

879
    Returns:
880
        str: The command line, quoted for a POSIX shell.
881
    """
882
    import shlex  # noqa: PLC0415
1 ✔
883

884
    command = request.processing_command or f"python -m {request.recipe.__module__}"
1 ✔
885
    arguments = [
1 ✔
886
        "--start-time",
887
        _format_time_for_cli(request.start_time),
888
        "--end-time",
889
        _format_time_for_cli(request.end_time),
890
    ]
891
    for name, value in kwargs.items():
1 ✔
892
        if name in FACTORY_ONLY_PARAMETERS:
1 ✔
893
            continue
1 ✔
894
        option = "--" + name.replace("_", "-")
1 ✔
895
        if isinstance(value, bool):
1 ✔
896
            arguments.append(option if value else f"--no-{option.removeprefix('--')}")
1 ✔
897
            continue
1 ✔
898
        for item in value if isinstance(value, list) else [value]:
1 ✔
899
            arguments += [option, _format_value(name, item)]
1 ✔
900
    return " ".join([command, *(shlex.quote(argument) for argument in arguments)])
1 ✔
901

902

903
def _format_interval(start: datetime, end: datetime) -> str:
1 ✔
904
    """Name a time interval as briefly as possible: a month (``2017-10``), a day, or a range."""
905
    from datetime import timedelta  # noqa: PLC0415
1 ✔
906

907
    def is_midnight(time: datetime) -> bool:
1 ✔
908
        return (time.hour, time.minute, time.second, time.microsecond) == (0, 0, 0, 0)
1 ✔
909

910
    at_midnight = is_midnight(start)
1 ✔
911
    # interval ends are inclusive (23:59:59) or exclusive (the next midnight); compare as exclusive
912
    stop = end + timedelta(seconds=1) if is_midnight(end + timedelta(seconds=1)) else end
1 ✔
913
    next_month = (start.replace(day=28) + timedelta(days=4)).replace(day=1)
1 ✔
914
    if at_midnight and start.day == 1 and stop == next_month:
1 ✔
915
        return start.strftime("%Y-%m")
1 ✔
916
    if at_midnight and stop == start + timedelta(days=1):
1 ✔
917
        return start.strftime("%Y-%m-%d")
1 ✔
918
    return f"{_format_time_for_cli(start)} to {_format_time_for_cli(end)}"
1 ✔
919

920

921
def _format_intervals(intervals: Sequence[tuple[datetime, datetime]]) -> str:
1 ✔
922
    """Name a list of intervals, merging consecutive ones into ranges (``2017-10 to 2017-12``)."""
923
    from datetime import timedelta  # noqa: PLC0415
1 ✔
924

925
    runs: list[list[tuple[datetime, datetime]]] = []
1 ✔
926
    for interval in intervals:
1 ✔
927
        if runs and interval[0] - runs[-1][-1][1] <= timedelta(seconds=1):
1 ✔
928
            runs[-1].append(interval)
1 ✔
929
        else:
930
            runs.append([interval])
1 ✔
931

932
    names: list[str] = []
1 ✔
933
    for run in runs:
1 ✔
934
        first, last = _format_interval(*run[0]), _format_interval(*run[-1])
1 ✔
935
        names.append(first if len(run) == 1 else f"{first} to {last}")
1 ✔
936
    return ", ".join(names)
1 ✔
937

938

939
def _data_label(dataset: DataSet) -> str:
1 ✔
940
    """Name the data of one dataset for messages, e.g. ``rbspa mageis (TS04)``."""
941
    mag_field = getattr(dataset.saving_strategy, "mag_field", None)
1 ✔
942
    name = dataset.get_print_name()
1 ✔
943
    return f"{name} ({mag_field})" if mag_field else name
1 ✔
944

945

946
def _check_coverage(request: PlotRequest, kwargs: dict[str, Any], dataset: DataSet) -> bool:
1 ✔
947
    """Report missing processed files for one dataset.
948

949
    Partial coverage is a warning naming the missing intervals; the gaps stay blank in the plot.
950
    No files at all is an error with the expected path of the first file and the processing
951
    command that would create them.
952

953
    Returns:
954
        bool: ``True`` if at least one expected file exists, so that there is something to plot.
955
    """
956
    coverage = dataset.get_file_coverage(_dataset_names(request))
1 ✔
957

958
    found: list[tuple[datetime, datetime]] = []
1 ✔
959
    missing: list[tuple[datetime, datetime]] = []
1 ✔
960
    # an interval with several output files counts as covered only if all of them exist
961
    for entry in coverage:
1 ✔
962
        interval = (entry.interval_start, entry.interval_end)
1 ✔
963
        if not entry.exists:
1 ✔
964
            if interval in found:
1 ✔
UNCOV
965
                found.remove(interval)
×
966
            if interval not in missing:
1 ✔
967
                missing.append(interval)
1 ✔
968
        elif interval not in found and interval not in missing:
1 ✔
969
            found.append(interval)
1 ✔
970

971
    if not missing:
1 ✔
972
        return True
1 ✔
973

974
    label = _data_label(dataset)
1 ✔
975
    if any(entry.exists for entry in coverage):
1 ✔
976
        covered = f"plotting {_format_intervals(found)} only" if found else "plotting the files that exist"
1 ✔
977
        logger.warning(f"No processed files for {label} in {_format_intervals(missing)}; {covered}.")
1 ✔
978
        return True
1 ✔
979

980
    first_missing = next(entry.path for entry in coverage if not entry.exists)
1 ✔
981
    logger.error(
1 ✔
982
        f"No processed files for {label} between {_format_time_for_cli(request.start_time)} "
983
        f"and {_format_time_for_cli(request.end_time)}.\n"
984
        f"Expected: {first_missing}\n"
985
        f"To create them: {processing_command_line(request, kwargs)}"
986
    )
987
    return False
1 ✔
988

989

990
def _load_datasets(request: PlotRequest) -> list[DataSet]:
1 ✔
991
    """Build one `DataSet` per set of factory arguments (one per satellite) that has processed files.
992

993
    A satellite without any files, or whose files cannot be determined, is reported and left out,
994
    so that the others are still plotted.
995
    """
996
    datasets: list[DataSet] = []
1 ✔
997
    for kwargs, label in zip(request.strategy_kwargs, _call_labels(request.strategy_kwargs), strict=True):
1 ✔
998
        suffix = f" ({label})" if label else ""
1 ✔
999
        try:
1 ✔
1000
            strategy = request.factory(**kwargs)
1 ✔
1001
            dataset = ep.DataSet(strategy, request.start_time, request.end_time, verbose=request.verbose)
1 ✔
1002
            if _check_coverage(request, kwargs, dataset):
1 ✔
1003
                datasets.append(dataset)
1 ✔
UNCOV
1004
        except ValueError as error:
×
1005
            logger.error(f"{error}{suffix}")  # noqa: TRY400
×
1006
    return datasets
1 ✔
1007

1008

1009
def _run_plot(request: PlotRequest) -> None:
1 ✔
1010
    """Plot the processed data a request describes.
1011

1012
    The figure is written to ``--output-dir``/``--filename``, or shown with ``--show``, or both. With
1013
    neither, it is written to the current directory under :func:`default_filename`.
1014

1015
    Satellites with only some of the expected files are plotted with gaps; satellites without
1016
    any are left out (see `_check_coverage`).
1017

1018
    With ``--export-script``, a script that makes the figure is written instead, and nothing is loaded.
1019

1020
    Raises:
1021
        typer.BadParameter: If no variables are given and the recipe has no default panels, or if
1022
            the command-line settings clash with the recipe's.
1023
        typer.Exit: With code 1 if the expected files cannot be determined, if ``--show`` is
1024
            given without an interactive backend, or if no satellite has any processed files.
1025
    """
1026
    _report_settings(request)
1 ✔
1027
    panels = resolve_panels(request)
1 ✔
1028
    indices, variables = split_panels(panels)
1 ✔
1029
    if panels:
1 ✔
1030
        _check_panel_settings(request, variables)
1 ✔
1031

1032
    if request.dry_run:
1 ✔
1033
        if not _report_expected_files(request):
1 ✔
1034
            raise typer.Exit(code=1)
1 ✔
1035
        return
1 ✔
1036

1037
    if not panels:
1 ✔
1038
        msg = f"is required: {_func_name(request.recipe)} defines no default panels."
1 ✔
1039
        raise typer.BadParameter(msg, param_hint="'--variable'")
1 ✔
1040

1041
    if request.export_script:
1 ✔
1042
        request.export_script.parent.mkdir(parents=True, exist_ok=True)
1 ✔
1043
        request.export_script.write_text(write_plot_script(request), encoding="utf-8")
1 ✔
1044
        logger.info(f"Wrote the plot script to {request.export_script}. Run it with python.")
1 ✔
1045
        return
1 ✔
1046

1047
    if request.show and (error := _interactive_backend_error()):
1 ✔
1048
        logger.error(error)
1 ✔
1049
        raise typer.Exit(code=1)
1 ✔
1050

1051
    datasets = _load_datasets(request) if variables else []
1 ✔
1052
    if variables and not datasets:
1 ✔
1053
        raise typer.Exit(code=1)
1 ✔
1054

1055
    try:
1 ✔
1056
        figure = build_figure(
1 ✔
1057
            datasets,
1058
            variables,
1059
            request.start_time,
1060
            request.end_time,
1061
            indices=indices,
1062
            show=request.show,
1063
            panel_settings=_recipe_settings(request),
1064
            **_setting_overrides(request),
1065
            along=request.along,
1066
            colormap=request.colormap,
1067
        )
1068
    except ValueError as error:
1 ✔
1069
        logger.error(str(error))  # noqa: TRY400
1 ✔
1070
        raise typer.Exit(code=1) from error
1 ✔
1071

1072
    output = _output_path(request)
1 ✔
1073
    if output is not None:
1 ✔
1074
        output.parent.mkdir(parents=True, exist_ok=True)
1 ✔
1075
        figure.savefig(output)
1 ✔
1076
        logger.info(f"Saved the figure to {output}.")
1 ✔
1077

1078
    if request.show:
1 ✔
1079
        import matplotlib.pyplot as plt  # noqa: PLC0415
1 ✔
1080

1081
        plt.show()
1 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc