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

GFZ / EL_PASO / 45813377522

26 Nov 2026 11:45AM UTC coverage: 65.777% (-5.2%) from 70.958%
45813377522

Pull #254

github

web-flow
Merge 65384d0a8 into 99da20af7
Pull Request #254: Simplify the plot CLI: comma-separated option values

241 of 263 new or added lines in 4 files covered. (91.63%)

609 existing lines in 22 files now uncovered.

7200 of 10946 relevant lines covered (65.78%)

0.66 hits per line

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

97.91
/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 process <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 END`` and the recipe's own options (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
    split_comma_separated,
72
)
73

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

78
    from astropy import units as u
79

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

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

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

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

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

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

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

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

116

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

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

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

174

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

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

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

183

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

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

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

204

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

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

352

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

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

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

367
    return factory_defaults
1 ✔
368

369

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

374

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

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

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

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

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

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

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

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

428

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

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

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

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

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

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

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

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

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

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

518
        plot_options = _parse_plot_options(plot_options)
1 ✔
519

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

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

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

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

558

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

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

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

582

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

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

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

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

598
    energies = None
1 ✔
599
    if plot_options["energies"]:
1 ✔
600
        try:
1 ✔
601
            texts = split_comma_separated(plot_options["energies"], what="energy", example="470,1575")
1 ✔
602
        except typer.BadParameter as error:
1 ✔
603
            error.param_hint = "'--energy'"
1 ✔
604
            raise
1 ✔
605
        values = [_parse_energy(text) for text in texts]
1 ✔
606
        if any(value <= 0 for value in values):
1 ✔
607
            msg = f"must be positive, got {', '.join(texts)}."
1 ✔
608
            raise typer.BadParameter(msg, param_hint="'--energy'")
1 ✔
609
        energies = u.Quantity(values, u.keV)
1 ✔
610

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

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

623
    try:
1 ✔
624
        variables = split_comma_separated(plot_options["variables"], what="variable", example="FEDU,L_star")
1 ✔
NEW
625
    except typer.BadParameter as error:
×
NEW
626
        error.param_hint = "'--variable'"
×
NEW
627
        raise
×
628

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

634
    pitch_angle = None if plot_options["pitch_angle"] is None else plot_options["pitch_angle"] * u.deg
1 ✔
635
    return {
1 ✔
636
        **plot_options,
637
        "variables": variables or None,
638
        "energies": energies,
639
        "pitch_angle": pitch_angle,
640
        "along": along,
641
    }
642

643

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

648

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

654

655
def split_panels(panels: Sequence[str] | None) -> tuple[list[str], list[InternalName]]:
1 ✔
656
    """Split a panel list into space-weather indices (`INDEX_PANELS`) and dataset variables, keeping the order."""
657
    indices = [name for name in panels or [] if name in INDEX_PANELS]
1 ✔
658
    variables = [name for name in panels or [] if name not in INDEX_PANELS]
1 ✔
659
    return indices, cast("list[InternalName]", variables)
1 ✔
660

661

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

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

673

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

678

679
def _setting_overrides(request: PlotRequest) -> dict[str, Any]:
1 ✔
680
    """The settings given on the command line, which override those of every panel (layer 3)."""
681
    return {
1 ✔
682
        "energies": request.energies,
683
        "pitch_angle": request.pitch_angle,
684
        "vmin": request.vmin,
685
        "vmax": request.vmax,
686
    }
687

688

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

692
    Raises:
693
        typer.BadParameter: If the layered settings of a panel are invalid.
694
    """
695
    from el_paso.dataset.plot import resolve_panel_settings  # noqa: PLC0415
1 ✔
696

697
    try:
1 ✔
698
        resolve_panel_settings(panels, _recipe_settings(request), _setting_overrides(request))
1 ✔
699
    except (TypeError, ValueError) as error:
1 ✔
700
        msg = f"conflicts with the recipe's plot defaults: {error}"
1 ✔
701
        raise typer.BadParameter(msg, param_hint="'--vmin' / '--vmax'") from error
1 ✔
702

703

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

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

723
    panels = resolve_panels(request)
1 ✔
724
    if request.variables:
1 ✔
725
        table.add_row("variables", ", ".join(request.variables))
1 ✔
726
    elif panels:
1 ✔
727
        table.add_row("variables", f"{', '.join(panels)} (recipe defaults)")
1 ✔
728
    else:
729
        table.add_row("variables", "none given")
1 ✔
730

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

759

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

763
    The settings table already shows everything else, so a single set gets an empty label.
764
    """
765
    varying = [
1 ✔
766
        name
767
        for name in strategy_kwargs[0]
768
        if len({_format_value(name, kwargs[name]) for kwargs in strategy_kwargs}) > 1
769
    ]
770
    return [", ".join(f"{name}={_format_value(name, kwargs[name])}" for name in varying) for kwargs in strategy_kwargs]
1 ✔
771

772

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

776
    Returns:
777
        bool: ``True`` if the files could be determined for every set of arguments.
778
    """
779
    # Not checked against the data standard here; get_file_coverage rejects unknown names.
780
    names = _dataset_names(request)
1 ✔
781

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

794
        logger.info(f"Saving strategy{suffix}: {strategy!r}")
1 ✔
795
        logger.info("Expected files:")
1 ✔
796
        for entry in coverage:
1 ✔
797
            logger.info(f"  [{'found' if entry.exists else 'missing'}] {entry.path}")
1 ✔
798
        found = sum(entry.exists for entry in coverage)
1 ✔
799
        logger.info(f"{found} of {len(coverage)} expected files exist.")
1 ✔
800

801
    return ok
1 ✔
802

803

804
def _format_time_for_file_name(time: datetime) -> str:
1 ✔
805
    """Compact time stamp for file names: the date alone at midnight, otherwise date and time."""
806
    if (time.hour, time.minute, time.second, time.microsecond) == (0, 0, 0, 0):
1 ✔
807
        return time.strftime("%Y%m%d")
1 ✔
808
    return time.strftime("%Y%m%dT%H%M%S")
1 ✔
809

810

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

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

818
    Args:
819
        request (PlotRequest): The resolved plot request.
820

821
    Returns:
822
        str: The default file name.
823
    """
824
    recipe_name = _func_name(request.recipe).removeprefix("process_")
1 ✔
825
    satellites: list[str] = []
1 ✔
826
    for kwargs in request.strategy_kwargs:
1 ✔
827
        if "satellite" in kwargs:
1 ✔
828
            satellite = _format_value("satellite", kwargs["satellite"])
1 ✔
829
            if satellite not in satellites:
1 ✔
830
                satellites.append(satellite)
1 ✔
831

832
    parts = [recipe_name]
1 ✔
833
    if satellites:
1 ✔
834
        parts.append("-".join(satellites))
1 ✔
835
    parts += [_format_time_for_file_name(request.start_time), _format_time_for_file_name(request.end_time)]
1 ✔
836
    return "_".join(parts) + ".png"
1 ✔
837

838

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

842
    The figure is written if ``--filename`` or ``--output-dir`` is given, or if ``--show`` is not.
843
    """
844
    if request.filename is None and request.output_dir is None and request.show:
1 ✔
845
        return None
1 ✔
846
    return (request.output_dir or Path()) / (request.filename or default_filename(request))
1 ✔
847

848

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

852
    Importing pyplot resolves matplotlib's backend; without a display it falls back to Agg,
853
    which cannot show figures.
854
    """
855
    import matplotlib.pyplot as plt  # noqa: PLC0415
1 ✔
856
    from matplotlib.backends import BackendFilter, backend_registry  # noqa: PLC0415
1 ✔
857

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

867

868
def _format_time_for_cli(time: datetime) -> str:
1 ✔
869
    """A time as the command line accepts it: the date alone at midnight, otherwise date and time (UTC)."""
870
    if (time.hour, time.minute, time.second, time.microsecond) == (0, 0, 0, 0):
1 ✔
871
        return time.strftime("%Y-%m-%d")
1 ✔
872
    return time.strftime("%Y-%m-%dT%H:%M:%S")
1 ✔
873

874

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

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

881
    Args:
882
        request (PlotRequest): The resolved plot request.
883
        kwargs (dict[str, Any]): One set of factory arguments from ``request.strategy_kwargs``.
884

885
    Returns:
886
        str: The command line, quoted for a POSIX shell.
887
    """
888
    import shlex  # noqa: PLC0415
1 ✔
889

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

903

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

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

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

921

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

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

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

939

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

946

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

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

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

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

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

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

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

990

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

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

1009

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

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

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

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

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

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

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

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

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

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

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

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

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

1082
        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