Skip to content

Commit

Permalink
CLI: print more helpful errors
Browse files Browse the repository at this point in the history
  • Loading branch information
nilsvu committed Jun 12, 2024
1 parent 27b319a commit 5dbc0a7
Show file tree
Hide file tree
Showing 18 changed files with 170 additions and 87 deletions.
12 changes: 8 additions & 4 deletions src/IO/H5/Python/CombineH5.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

import spectre.IO.H5 as spectre_h5
from spectre.IO.H5.CombineH5Dat import combine_h5_dat_command
from spectre.support.CliExceptions import RequiredChoiceError


@click.group(name="combine-h5")
Expand Down Expand Up @@ -70,10 +71,13 @@ def combine_h5_vol_command(h5files, subfile_name, output, check_src):
# Print available subfile names and exit
if not subfile_name:
spectre_file = spectre_h5.H5File(h5files[0], "r")
import rich.columns

rich.print(rich.columns.Columns(spectre_file.all_vol_files()))
return
raise RequiredChoiceError(
(
"Specify '--subfile-name' / '-d' to select a"
" subfile containing volume data."
),
choices=spectre_file.all_vol_files(),
)

if not output.endswith(".h5"):
output += ".h5"
Expand Down
12 changes: 8 additions & 4 deletions src/Visualization/Python/GenerateXdmf.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import numpy as np
import rich

from spectre.support.CliExceptions import RequiredChoiceError
from spectre.Visualization.ReadH5 import available_subfiles

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -306,8 +307,6 @@ def generate_xdmf(
h5files = [(h5py.File(filename, "r"), filename) for filename in h5files]

if not subfile_name:
import rich.columns

subfiles = available_subfiles(
(h5file for h5file, _ in h5files), extension=".vol"
)
Expand All @@ -317,8 +316,13 @@ def generate_xdmf(
f"Selected subfile {subfile_name} (the only available one)."
)
else:
rich.print(rich.columns.Columns(subfiles))
return
raise RequiredChoiceError(
(
"Specify '--subfile-name' / '-d' to select a"
" subfile containing volume data."
),
choices=subfiles,
)

if not subfile_name.endswith(".vol"):
subfile_name += ".vol"
Expand Down
25 changes: 17 additions & 8 deletions src/Visualization/Python/OpenVolfiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import rich

import spectre.IO.H5 as spectre_h5
from spectre.support.CliExceptions import RequiredChoiceError
from spectre.Visualization.ReadH5 import list_observations, select_observation

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -161,8 +162,6 @@ def command(
):
# Print available subfile names and exit
if not subfile_name:
import rich.columns

with spectre_h5.H5File(h5_files[0], "r") as open_h5_file:
available_subfiles = open_h5_file.all_vol_files()
if len(available_subfiles) == 1:
Expand All @@ -172,8 +171,13 @@ def command(
" (the only available one)."
)
else:
rich.print(rich.columns.Columns(available_subfiles))
return
raise RequiredChoiceError(
(
"Specify '--subfile-name' / '-d' to select a"
" subfile containing volume data."
),
choices=available_subfiles,
)

# Print available observations/times and exit
if list_times:
Expand Down Expand Up @@ -219,21 +223,26 @@ def command(
obs_id or volfile.list_observation_ids()[0]
)
break
if list_vars or (vars_required and not vars_patterns):
if list_vars:
import rich.columns

rich.print(rich.columns.Columns(all_vars))
return
elif vars_required and not vars_patterns:
raise RequiredChoiceError(
"Specify '--var' / '-y' to select a variable to plot.",
choices=all_vars,
)
# Expand globs in vars
vars = []
if not multiple_vars:
vars_patterns = [vars_patterns] if vars_patterns else []
for var_pattern in vars_patterns:
matched_vars = fnmatch.filter(all_vars, var_pattern)
if not matched_vars:
raise click.UsageError(
f"The pattern '{var_pattern}' matches no variables. "
f"Available variables are: {all_vars}"
raise RequiredChoiceError(
f"The pattern '{var_pattern}' matches no variables.",
choices=all_vars,
)
vars.extend(matched_vars)
# Remove duplicates. Ordering is lost, but that's not important here.
Expand Down
11 changes: 7 additions & 4 deletions src/Visualization/Python/PlotCce.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import matplotlib.pyplot as plt
import pandas as pd

from spectre.support.CliExceptions import RequiredChoiceError
from spectre.Visualization.Plot import (
apply_stylesheet_command,
show_or_save_plot_command,
Expand Down Expand Up @@ -205,10 +206,12 @@ def plot_cce_command(
)
cce_subfile = h5file.get(cce_subfile_name)
if cce_subfile is None:
raise click.UsageError(
f"Could not find Cce subfile {cce_subfile} in H5 file"
f" {h5_filename}. Available subfiles"
f" are:\n{available_subfiles(h5file, extension='cce')}"
raise RequiredChoiceError(
(
f"Could not find Cce subfile {cce_subfile} in H5 file"
f" {h5_filename}."
),
choices=cce_subfiles,
)

suffix = ".dat" if backward_cce_group is not None else ""
Expand Down
21 changes: 13 additions & 8 deletions src/Visualization/Python/PlotControlSystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import numpy as np
import pandas as pd

from spectre.support.CliExceptions import RequiredChoiceError
from spectre.Visualization.Plot import (
apply_stylesheet_command,
show_or_save_plot_command,
Expand Down Expand Up @@ -106,10 +107,12 @@ def check_control_system_dir(h5_filename: str):
h5file = h5py.File(h5_filename, "r")
control_system_dir = h5file.get("ControlSystems")
if control_system_dir is None:
raise click.UsageError(
"Unable to open group 'ControlSystems' from h5 file"
f" {h5_filename}. Available subfiles are:\n"
f" {available_subfiles(h5file, extension='.dat')}"
raise RequiredChoiceError(
(
"Unable to open group 'ControlSystems' from h5 file"
f" {h5_filename}."
),
choices=available_subfiles(h5file, extension=".dat"),
)

# No size control
Expand All @@ -129,10 +132,12 @@ def check_control_system_file(
)
subfile = h5file.get(subfile_path)
if subfile_path is None:
raise click.UsageError(
f"Unable to open control system file '{subfile_path}'"
f" from h5 file {h5_filename}. Available subfiles are:\n"
f" {available_subfiles(h5file, extension='.dat')}"
raise RequiredChoiceError(
(
f"Unable to open control system subfile '{subfile_path}'"
f" from h5 file {h5_filename}."
),
choices=available_subfiles(h5file, extension=".dat"),
)

return to_dataframe(subfile).set_index("Time")
Expand Down
36 changes: 16 additions & 20 deletions src/Visualization/Python/PlotDatFile.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import numpy as np
import rich

from spectre.support.CliExceptions import RequiredChoiceError
from spectre.Visualization.Plot import (
apply_stylesheet_command,
show_or_save_plot_command,
Expand Down Expand Up @@ -54,10 +55,7 @@ def parse_functions(ctx, param, all_values):
@click.option(
"--subfile-name",
"-d",
help=(
"The dat subfile to read. "
"If unspecified, all available dat subfiles will be printed."
),
help="The dat subfile to read. [required]",
)
@click.option(
"--legend-only",
Expand Down Expand Up @@ -134,24 +132,23 @@ def plot_dat_command(
"""Plot columns in '.dat' datasets in H5 files"""
with h5py.File(h5_file, "r") as h5file:
# Print available subfiles and exit
if subfile_name is None:
import rich.columns

rich.print(
rich.columns.Columns(
available_subfiles(h5file, extension=".dat")
)
if not subfile_name:
raise RequiredChoiceError(
(
"Specify '--subfile-name' / '-d' to select a"
" subfile containing data to plot."
),
choices=available_subfiles(h5file, extension=".dat"),
)
return

# Open subfile
if not subfile_name.endswith(".dat"):
subfile_name += ".dat"
dat_file = h5file.get(subfile_name)
if dat_file is None:
raise click.UsageError(
f"Unable to open dat file '{subfile_name}'. Available "
f"files are:\n {available_subfiles(h5file, extension='.dat')}"
raise RequiredChoiceError(
f"Unable to open dat subfile '{subfile_name}'.",
choices=available_subfiles(h5file, extension=".dat"),
)

# Read legend from subfile
Expand All @@ -161,8 +158,8 @@ def plot_dat_command(
if x_axis is None:
x_axis = legend[0]
elif x_axis not in legend:
raise click.UsageError(
f"Unknown x-axis '{x_axis}'. Available columns are: {legend}"
raise RequiredChoiceError(
f"Unknown x-axis '{x_axis}'.", choices=legend
)

# Print legend and exit if requested
Expand Down Expand Up @@ -203,9 +200,8 @@ def plot_dat_command(
# Plot the selected quantities
for function, label in functions.items():
if function not in legend:
raise click.UsageError(
f"Unknown function '{function}'. "
f"Available functions are: {legend}"
raise RequiredChoiceError(
f"Unknown function '{function}'.", choices=legend
)

plt.plot(
Expand Down
21 changes: 13 additions & 8 deletions src/Visualization/Python/PlotMemoryMonitors.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import numpy as np
import pandas as pd

from spectre.support.CliExceptions import RequiredChoiceError
from spectre.Visualization.Plot import (
apply_stylesheet_command,
show_or_save_plot_command,
Expand Down Expand Up @@ -75,10 +76,12 @@ def check_memory_monitor_dir(h5_filename: str):
h5file = h5py.File(h5_filename, "r")
memory_monitor_dir = h5file.get("MemoryMonitors")
if memory_monitor_dir is None:
raise click.UsageError(
"Unable to open group 'MemoryMonitors' from h5 file"
f" {h5_filename}. Available subfiles are:\n"
f" {available_subfiles(h5file, extension='.dat')}"
raise RequiredChoiceError(
(
"Unable to open group 'MemoryMonitors' from h5 file"
f" {h5_filename}."
),
choices=available_subfiles(h5file, extension=".dat"),
)

return list(memory_monitor_dir.keys())
Expand All @@ -92,10 +95,12 @@ def check_memory_monitor_file(
subfile_path = f"/MemoryMonitors/{subfile_name}"
subfile = h5file.get(subfile_path)
if subfile_path is None:
raise click.UsageError(
f"Unable to open memory file '{subfile_path}'"
f" from h5 file {h5_filename}. Available subfiles are:\n"
f" {available_subfiles(h5file, extension='.dat')}"
raise RequiredChoiceError(
(
f"Unable to open memory subfile '{subfile_path}'"
f" from h5 file {h5_filename}."
),
choices=available_subfiles(h5file, extension=".dat"),
)

return to_dataframe(subfile).set_index("Time")
Expand Down
17 changes: 13 additions & 4 deletions src/Visualization/Python/PlotPowerMonitors.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from spectre.IO.H5.IterElements import iter_elements, stripped_element_name
from spectre.NumericalAlgorithms.LinearOperators import power_monitors
from spectre.Spectral import Basis
from spectre.support.CliExceptions import RequiredChoiceError
from spectre.Visualization.OpenVolfiles import (
open_volfiles,
open_volfiles_command,
Expand Down Expand Up @@ -362,17 +363,25 @@ def plot_power_monitors_command(
domain = deserialize_domain[dim](volfile.get_domain(any_obs_id))
all_block_groups = list(domain.block_groups.keys())
all_block_names = [block.name for block in domain.blocks]
if list_blocks or not block_or_group_names:
if list_blocks:
import rich.columns

rich.print(rich.columns.Columns(all_block_groups + all_block_names))
return
elif not block_or_group_names:
raise RequiredChoiceError(
(
"Specify '--block' / '-b' to select (possibly multiple) blocks"
" or block groups to analyze."
),
choices=all_block_groups + all_block_names,
)
# Validate block and group names
for name in block_or_group_names:
if not (name in all_block_groups or name in all_block_names):
raise click.UsageError(
f"'{name}' matches no block or group name. "
f"Available names are: {all_block_groups + all_block_names}"
raise RequiredChoiceError(
f"'{name}' matches no block or block group.",
choices=all_block_groups + all_block_names,
)

# Print available elements IDs
Expand Down
12 changes: 8 additions & 4 deletions src/Visualization/Python/PlotSizeControl.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import numpy as np
import pandas as pd

from spectre.support.CliExceptions import RequiredChoiceError
from spectre.Visualization.Plot import (
apply_stylesheet_command,
show_or_save_plot_command,
Expand Down Expand Up @@ -81,10 +82,13 @@ def check_diagnostics_file(h5_filename):
)
diagnostics_data = h5file.get(diagnostics_file_name)
if diagnostics_data is None:
raise click.UsageError(
f"Unable to open diagnostic file '{diagnostics_file_name}'"
f" from h5 file {h5_filename}. Available subfiles are:\n"
f" {available_subfiles(h5file, extension='.dat')}"
raise RequiredChoiceError(
(
"Unable to open diagnostic file"
f" '{diagnostics_file_name}' from h5 file"
f" {h5_filename}."
),
choices=available_subfiles(h5file, extension=".dat"),
)

return to_dataframe(diagnostics_data)
Expand Down
Loading

0 comments on commit 5dbc0a7

Please sign in to comment.