from contextlib import AbstractContextManager, nullcontext
from datetime import datetime
from os import PathLike
from pathlib import Path, PurePath
import sys
from typing import List, Optional, TextIO, Union, Any
import yaml
import click
import h5py
import shutil
from mpi4py import MPI
from loguru import logger
import httomo.globals
from httomo.cli_utils import is_sweep_pipeline
from httomo.logger import setup_logger
from httomo.monitors import MONITORS_MAP, make_monitors
from httomo.runner.dataset_store_backing import estimate_section_memory
from httomo.runner.pipeline import Pipeline
from httomo.runner.section import sectionize
from httomo.sweep_runner.param_sweep_runner import ParamSweepRunner
from httomo.transform_layer import TransformLayer
from httomo.transform_loader_params import parse_config, parse_preview
from httomo.utils import log_exception, log_once, mpi_abort_excepthook
from httomo.yaml_checker import (
validate_yaml_config,
_get_template_yaml_conf,
PipelineConfig,
)
from httomo.runner.task_runner import TaskRunner
from httomo.ui_layer import UiLayer, PipelineFormat, yaml_loader
try:
from . import __version__
except:
__version__ = "0.0.1" # temporary version for sphinx build
pass
[docs]
class PipelineFilePathOrString(click.ParamType):
"""
Parameter that is either a pipeline filepath or a string containing pipeline data in an
external format (for example, YAML or JSON).
"""
name = "pipeline_filepath_or_string"
def __init__(self, types) -> None:
self.types = types
[docs]
def convert(self, value: Any, param, ctx) -> Union[Path, str]:
"""
Attempts to convert given value to either a valid `Path` or a `str`, and returns an
error otherwise.
"""
for possible_type in self.types:
try:
return possible_type.convert(value, param, ctx)
except click.BadParameter:
continue
self.fail(
f"Value '{value}' didn't match any of the accepted types: {self.types}"
)
@click.group
@click.version_option(version=__version__, message="%(version)s")
def main():
"""httomo: Software for High Throughput Tomography in parallel beam.
Use `python -m httomo run --help` for more help on the runner.
"""
pass
@main.command()
@click.argument(
"in_data_file",
type=click.Path(exists=True, dir_okay=False, path_type=Path),
)
@click.argument(
"pipeline",
type=PipelineFilePathOrString(
types=[click.Path(exists=True, dir_okay=False, path_type=Path), click.STRING]
),
)
@click.argument(
"nprocs",
type=click.IntRange(1),
)
def memory_check(in_data_file: Path, pipeline: Union[Path, str], nprocs: int):
"""
Estimate CPU memory requirements for processing input data with a given pipeline and number
of processes
"""
memory_peak = estimate_cpu_memory(in_data_file, pipeline, nprocs)
print(
f"Estimated peak CPU memory usage for {nprocs} process run: {(memory_peak * nprocs) / (1024 ** 3):.3f} GB"
)
@main.command()
@click.argument(
"pipeline",
type=PipelineFilePathOrString(
types=[click.Path(exists=True, dir_okay=False, path_type=Path), click.STRING]
),
)
@click.argument(
"in_data_file",
type=click.Path(exists=True, dir_okay=False, path_type=Path),
required=False,
default=None,
)
def check(pipeline: Union[Path, str], in_data_file: Optional[Path] = None):
"""Check a YAML pipeline file for errors."""
in_data = in_data_file if isinstance(in_data_file, PurePath) else None
# Handle file path case
if isinstance(pipeline, Path):
return validate_yaml_config(pipeline, in_data)
else: # Handle the string(JSON) case
raise ValueError("Checking Pipeline in string format is not supported yet.")
@main.command()
@click.argument(
"in_data_file", type=click.Path(exists=True, dir_okay=False, path_type=Path)
)
@click.argument(
"pipeline",
type=PipelineFilePathOrString(
types=[click.Path(exists=True, dir_okay=False, path_type=Path), click.STRING]
),
)
@click.argument(
"out_dir",
type=click.Path(file_okay=False, writable=True, path_type=Path),
)
@click.option(
"--output-folder-name",
type=click.Path(exists=False, file_okay=False, writable=True, path_type=Path),
default=None,
help="Define the name of the output folder created by HTTomo",
)
@click.option(
"--save-all",
type=click.BOOL,
is_flag=True,
help="Save intermediate datasets for all tasks in the pipeline. Set to True or False.",
)
@click.option(
"--gpu-id",
type=click.INT,
default=-1,
help="The GPU ID of the device to use.",
)
@click.option(
"--reslice-dir",
type=click.Path(exists=True, file_okay=False, writable=True, path_type=Path),
default=None,
help="Directory for temporary files potentially needed for reslicing (defaults to output dir)",
)
@click.option(
"--max-cpu-slices",
type=click.INT,
default=64,
help="Maximum number of slices to use for a block for CPU-only sections (default: 64)",
)
@click.option(
"--max-memory",
type=click.STRING,
default="0",
help=(
"Per-process memory ceiling used to select in-memory or disk-backed "
"storage and to cap GPU block sizing (supports values such as 3.2G or "
"bytes; 0 disables the user ceiling)"
),
)
@click.option(
"--save-snapshots",
type=click.BOOL,
is_flag=True,
help="Save intermediate images (snapshots) from some methods in the pipeline. Set to True or False.",
)
@click.option(
"--bits-sweep-images",
type=click.INT,
default=32,
help="Change the bit depth of saved tiff images in the sweep run from default 32 bit to 16 or 8 bit tiffs.",
)
@click.option(
"--monitor",
type=click.STRING,
multiple=True,
default=[],
help=(
"Add monitor to the runner (can be given multiple times). "
+ f"Available monitors: {', '.join(MONITORS_MAP.keys())}"
),
)
@click.option(
"--monitor-output",
type=click.File("w"),
default=sys.stdout,
help="File to store the monitoring output. Defaults to '-', which denotes stdout",
)
@click.option(
"--intermediate-format",
type=click.Choice(["hdf5"], case_sensitive=False),
default="hdf5",
help="Write intermediate data in hdf5 format",
)
@click.option(
"--compress-intermediate",
is_flag=True,
help="Write intermediate data in chunked format with BLOSC compression applied",
)
@click.option(
"--syslog-host",
type=click.STRING,
default="localhost",
help="Host of the syslog server",
)
@click.option(
"--syslog-port",
type=click.INT,
default=514,
help="Port on the host the syslog server is running on",
)
@click.option(
"--frames-per-chunk",
type=click.IntRange(-1),
default=-1,
help=(
"Number of frames per-chunk in intermediate data "
"(0 = write as contiguous, -1 = decide automatically)"
),
)
@click.option(
"--recon-filename-stem",
type=click.STRING,
default=None,
help="Name of output recon file without file extension (assumes `.h5`)",
)
@click.option(
"--pipeline-format",
type=click.Choice(["Yaml", "Json"], case_sensitive=False),
default="Yaml",
help="Format of the pipeline input (YAML or JSON)",
)
@click.option(
"--mpi-abort-hook",
is_flag=True,
help="Enable hook that invokes MPI abort if an unhandled exception is encountered",
)
@click.option(
"--continuous-scan-subset",
nargs=2,
type=click.INT,
default=None,
help="Start and stop indices for selecting subset of projections along angular dimension",
)
def run(
in_data_file: Path,
pipeline: Union[Path, str],
out_dir: Path,
output_folder_name: Optional[Path],
gpu_id: int,
save_all: bool,
bits_sweep_images: int,
reslice_dir: Union[Path, None],
max_cpu_slices: int,
max_memory: str,
save_snapshots: bool,
monitor: List[str],
pipeline_format: str,
monitor_output: TextIO,
intermediate_format: str,
compress_intermediate: bool,
syslog_host: str,
syslog_port: int,
frames_per_chunk: int,
recon_filename_stem: Optional[str],
mpi_abort_hook: bool,
continuous_scan_subset: Optional[tuple[int, int]],
):
"""Run a pipeline on input data."""
if mpi_abort_hook:
sys.excepthook = mpi_abort_excepthook
set_global_constants(
out_dir,
intermediate_format,
compress_intermediate,
frames_per_chunk,
max_cpu_slices,
syslog_host,
syslog_port,
(
output_folder_name
if output_folder_name is not None
else Path(f"{datetime.now().strftime('%d-%m-%Y_%H_%M_%S')}_output")
),
recon_filename_stem,
continuous_scan_subset,
)
global_comm = MPI.COMM_WORLD
if output_folder_name is None:
httomo.globals.run_out_dir = global_comm.bcast(httomo.globals.run_out_dir, 0)
does_contain_sweep = is_sweep_pipeline(pipeline)
method_wrapper_comm = global_comm if not does_contain_sweep else MPI.COMM_SELF
if global_comm.rank == 0:
initialise_output_dir_copy_files_inject_defaults(pipeline, does_contain_sweep)
global_comm.Barrier()
setup_logger(Path(httomo.globals.run_out_dir))
# Convert string to enum
format_enum = (
PipelineFormat.Json if pipeline_format == "Json" else PipelineFormat.Yaml
)
pipeline_object = generate_pipeline(
in_data_file,
(
httomo.globals.run_out_dir / pipeline.name
if format_enum == PipelineFormat.Yaml
else pipeline
),
save_all,
bits_sweep_images,
method_wrapper_comm,
format_enum,
)
for wrapper in pipeline_object:
wrapper.check()
wrapper.prep()
if not does_contain_sweep:
execute_high_throughput_run(
pipeline_object,
global_comm,
gpu_id,
max_memory,
monitor,
monitor_output,
reslice_dir if reslice_dir is not None else httomo.globals.run_out_dir,
save_snapshots,
)
else:
execute_sweep_run(pipeline_object, global_comm)
if mpi_abort_hook:
sys.excepthook = sys.__excepthook__
def _set_gpu_id(gpu_id: int):
try:
import cupy as cp
if cp.cuda.is_available():
gpu_count = cp.cuda.runtime.getDeviceCount()
if gpu_id != -1:
if gpu_id not in range(0, gpu_count):
raise ValueError(
f"GPU Device not available for access. Use a GPU ID in the range: 0 to {gpu_count} (exclusive)"
)
cp.cuda.Device(gpu_id).use()
else:
log_once(
"CuPy is installed but the GPU device is inaccessible. Only CPU pipelines would work."
)
httomo.globals.gpu_id = gpu_id
except ImportError as e:
log_exception(f"CuPy is not installed {e}. Only CPU pipelines would work.")
[docs]
def set_global_constants(
out_dir: Path,
intermediate_format: str,
compress_intermediate: bool,
frames_per_chunk: int,
max_cpu_slices: int,
syslog_host: str,
syslog_port: int,
output_folder_name: Path,
recon_filename_stem: Optional[str],
continuous_scan_subset: Optional[tuple[int, int]],
) -> None:
if compress_intermediate and frames_per_chunk == 0:
# 0 means write contiguously but compression must have chunk
# storage, so decide automatically in this case
frames_per_chunk = -1
httomo.globals.INTERMEDIATE_FORMAT = intermediate_format
httomo.globals.COMPRESS_INTERMEDIATE = compress_intermediate
httomo.globals.FRAMES_PER_CHUNK = frames_per_chunk
httomo.globals.SYSLOG_SERVER = syslog_host
httomo.globals.SYSLOG_PORT = syslog_port
httomo.globals.RECON_FILENAME_STEM = recon_filename_stem
httomo.globals.CONTINUOUS_SCAN_SUBSET = continuous_scan_subset
httomo.globals.run_out_dir = out_dir.joinpath(output_folder_name)
if max_cpu_slices < 1:
raise ValueError("max-cpu-slices must be greater or equal to 1")
httomo.globals.MAX_CPU_SLICES = max_cpu_slices
[docs]
def initialise_output_dir_copy_files_inject_defaults(
pipeline: Union[Path, str], does_contain_sweep: bool
) -> None:
"""This function does the following:
- creates output folder
- if distortion coefficient file is provided copies all parameters to yaml pipeline
- injects omitted default parameters into the pipeline file
- copies the YAML or JSON pipeline file
"""
try:
Path.mkdir(httomo.globals.run_out_dir, parents=True, exist_ok=True)
except PermissionError as e:
log_exception(f"PermissionError when creating output directory: {e}")
sys.exit(1)
# If pipeline is a file path, copy it to output directory
if isinstance(pipeline, Path):
pipeline_conf = yaml_loader(pipeline)
_inject_distortion_coeff_values_into_method(pipeline_conf)
path_to_pipeline = pipeline
path_to_saved_pipeline = Path(httomo.globals.run_out_dir) / pipeline.name
# if does_contain_sweep do not inject default parameters due to issue around "sweep" aliases in yaml
if not does_contain_sweep:
path_to_pipeline = path_to_saved_pipeline
pipeline_updated = _substitute_omitted_default_values(pipeline_conf)
with open(path_to_saved_pipeline, "w") as file_descriptor:
yaml.dump(
pipeline_updated,
file_descriptor,
default_flow_style=False,
sort_keys=False,
)
with open(path_to_pipeline, "r") as input:
pipeline_contents = input.read()
with open(path_to_saved_pipeline, "w") as output:
output.write(f"# Created with HTTomo version {__version__}\n")
output.write(pipeline_contents)
# If pipeline is a JSON string, write it to a file in the output directory
else:
with open(httomo.globals.run_out_dir / "pipeline.json", "w") as f:
f.write(pipeline)
def _substitute_omitted_default_values(
pipeline_conf: PipelineConfig,
) -> PipelineConfig:
templates_conf = _get_template_yaml_conf(pipeline_conf)
for i, (method, template) in enumerate(zip(pipeline_conf, templates_conf)):
template_param_dict = template["parameters"]
method_params = set(method.get("parameters", {}).keys())
template_params = set(template_param_dict.keys())
omitted_params = template_params - method_params
for param in omitted_params:
# insert ommited parameter into the pipeline
pipeline_conf[i]["parameters"][param] = template["parameters"][param]
return pipeline_conf
def _inject_distortion_coeff_values_into_method(
pipeline_conf: PipelineConfig,
) -> PipelineConfig:
for method in pipeline_conf:
if "distortion_correction" in method["method"]:
distortion_coeff_path = method["parameters"]["metadata_path"]
if distortion_coeff_path is not None:
# inject values from the text file into parameters of the method
with open(distortion_coeff_path) as f:
xcenter, ycenter, *list_fact = (
float(line.split()[-1]) for line in f
)
method["parameters"]["metadata_path"] = None
method["parameters"]["xcenter"] = xcenter
method["parameters"]["ycenter"] = ycenter
method["parameters"]["list_fact"] = list_fact
return pipeline_conf
[docs]
def generate_pipeline(
in_data_file: Path,
pipeline: Union[Path, str],
save_all: bool,
bits_sweep_images: int,
method_wrapper_comm: MPI.Comm,
pipeline_format: PipelineFormat,
) -> Pipeline:
# instantiate UiLayer class for pipeline build
init_UiLayer = UiLayer(
pipeline,
in_data_file,
comm=method_wrapper_comm,
pipeline_format=pipeline_format,
)
pipeline_object = init_UiLayer.build_pipeline()
# perform transformations on pipeline
tr = TransformLayer(
comm=method_wrapper_comm, save_all=save_all, bits_sweep_images=bits_sweep_images
)
pipeline_object = tr.transform(pipeline_object)
return pipeline_object
[docs]
def execute_high_throughput_run(
pipeline: Pipeline,
global_comm: MPI.Comm,
gpu_id: int,
max_memory: str,
monitor: List[str],
monitor_output: TextIO,
reslice_dir: PathLike,
save_snapshots: bool,
) -> None:
_set_gpu_id(gpu_id)
# Run the pipeline using Taskrunner, with temp dir or reslice dir
mon = make_monitors(monitor, global_comm)
ctx: AbstractContextManager = nullcontext(reslice_dir)
with ctx as tmp_dir:
runner = TaskRunner(
pipeline,
Path(tmp_dir),
global_comm,
monitor=mon,
memory_limit_bytes=transform_limit_str_to_bytes(max_memory),
save_snapshots=save_snapshots,
)
runner.execute()
if mon is not None:
mon.write_results(monitor_output)
[docs]
def execute_sweep_run(pipeline: Pipeline, global_comm: MPI.Comm) -> None:
ParamSweepRunner(pipeline, global_comm).execute()
[docs]
def estimate_cpu_memory(
in_data_file: Path,
pipeline_file: Path,
nprocs: int,
shape: Optional[tuple[int, int, int]] = None,
) -> int:
pipeline = generate_pipeline(
in_data_file, pipeline_file, False, 32, MPI.COMM_WORLD, PipelineFormat.Yaml
)
sections = sectionize(pipeline)
config = yaml_loader(pipeline_file)
data_config, _, _, _, _ = parse_config(in_data_file, config[0]["parameters"])
with h5py.File(in_data_file, "r") as f:
dataset = f[data_config.data_path]
dtype = dataset.dtype
full_shape = dataset.shape
if shape is None:
preview_config = parse_preview(
config[0]["parameters"].get("preview", None), full_shape
)
previewed_shape = (
preview_config.angles.stop - preview_config.angles.start,
preview_config.detector_y.stop - preview_config.detector_y.start,
preview_config.detector_x.stop - preview_config.detector_x.start,
)
else:
previewed_shape = shape
section_memory_peak = 0
for idx in range(len(sections)):
mem, previewed_shape = estimate_section_memory(
nprocs,
0,
None,
dtype,
previewed_shape,
sections,
idx,
)
section_memory_peak = max(
section_memory_peak,
mem,
)
return section_memory_peak