Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
- fix: `python -m chipstream.cli` failed with ModuleNotFoundError
- fix: `chipstream-cli --recursive` silently did nothing when PATH_IN is a file
- fix: malformed `-ks`/`-kb`/`-kf`/`-kg` arguments of `chipstream-cli` caused tracebacks; values could not contain "=" and "None" was not accepted
- fix: `chipstream-cli --recursive` stopped at the first file that failed and aborted when an output file already existed; now it continues, reports failed files, and skips files with existing output
0.11.1
- enh: don't show rounded 100% in CLI progress
- setup: bump dcnum to 0.31.2
Expand Down
48 changes: 39 additions & 9 deletions chipstream/cli/cli_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import multiprocessing as mp
import pathlib
import sys
import traceback

import click
import dcnum
Expand Down Expand Up @@ -225,26 +226,55 @@ def chipstream_cli(
f"to process a single file.", fg="red")
exit_code = 1
elif recursive:
failed = 0 # keeps track of files that failed to process
failed = [] # files that failed to process
skipped = [] # files for which the output file already exists
for pi in sorted(path_in.rglob("*.rtdc")):
if pi.name.endswith("_dcn.rtdc"):
continue
if path_out is not None:
poi = path_out / pi.relative_to(path_in)
po = poi.with_name(poi.stem + "_dcn.rtdc")
po.parent.mkdir(parents=True, exist_ok=True)
else:
po = None
poi = pi
po = poi.with_name(poi.stem + "_dcn.rtdc")
if po.exists() and not dry_run:
# Skip files that have already been processed, so a
# batch can be resumed. dcnum only creates the output
# file once the pipeline completed successfully.
click.secho(f"\nSkipping {pi}, because the output file "
f"'{po}' exists", fg="yellow")
skipped.append(pi)
continue
click.secho(f"\nProcessing {pi}")
failed += process_dataset(path_in=pi,
path_out=po,
**process_kwargs)
try:
failed_i = process_dataset(path_in=pi,
path_out=po,
**process_kwargs)
except click.UsageError:
# invalid command-line arguments apply to all files
raise
except click.ClickException as e:
click.secho(f"Failed to process {pi}: {e.format_message()}",
fg="red")
failed_i = 1
except Exception:
click.secho(f"Failed to process {pi}:\n"
f"{traceback.format_exc()}",
fg="red")
failed_i = 1
if failed_i:
failed.append(pi)
if dry_run:
click.secho("Stopping dry run after one iteration")
break
if skipped:
click.secho(f"\nSkipped {len(skipped)} file(s) with existing "
f"output", fg="yellow")
if failed:
click.secho(f"Could not process {failed} files", fg="red")
exit_code = bool(failed)
click.secho(f"\nCould not process {len(failed)} file(s):",
fg="red")
for pf in failed:
click.secho(f" - {pf}", fg="red")
exit_code = int(bool(failed))
else:
if path_in.is_dir():
click.secho(f"PATH_IN must be a file, but '{path_in}' "
Expand Down
73 changes: 73 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import shutil
import subprocess
import sys

Expand Down Expand Up @@ -273,6 +274,78 @@ def test_cli_python_m():
assert chipstream.__version__ in result.stdout


@pytest.mark.parametrize("use_path_out", [True, False])
def test_cli_recursive_continue_after_failure(cli_runner, tmp_path,
use_path_out):
"""A file that fails must not stop the other files from processing"""
path = retrieve_data(
"fmt-hdf5_cytoshot_full-features_legacy_allev_2023.zip")
dir_in = tmp_path / "in"
dir_in.mkdir()
# sorted before the valid file
(dir_in / "a_bad.rtdc").write_text("hello world")
shutil.copy2(path, dir_in / "b_good.rtdc")
dir_out = tmp_path / "out" if use_path_out else dir_in

args = [str(dir_in), "--recursive", "--debug"]
if use_path_out:
args.append(str(dir_out))
result = cli_runner.invoke(cli_main.chipstream_cli, args)
assert result.exit_code == 1
assert result.stdout.count("Failed to process")
assert result.stdout.count("Not a valid input file")
assert result.stdout.count("Could not process 1 file(s)")
assert not (dir_out / "a_bad_dcn.rtdc").exists()
assert (dir_out / "b_good_dcn.rtdc").exists()


@pytest.mark.parametrize("use_path_out", [True, False])
def test_cli_recursive_skip_existing_output(cli_runner, tmp_path,
use_path_out):
"""Files with an existing output file are skipped (resume a batch)"""
path = retrieve_data(
"fmt-hdf5_cytoshot_full-features_legacy_allev_2023.zip")
dir_in = tmp_path / "in"
dir_in.mkdir()
shutil.copy2(path, dir_in / "a.rtdc")
shutil.copy2(path, dir_in / "b.rtdc")
dir_out = tmp_path / "out" if use_path_out else dir_in
dir_out.mkdir(exist_ok=True)
# output of a previous (interrupted) run
(dir_out / "a_dcn.rtdc").write_text("previous output")

args = [str(dir_in), "--recursive", "--debug"]
if use_path_out:
args.append(str(dir_out))
result = cli_runner.invoke(cli_main.chipstream_cli, args)
assert result.exit_code == 0
assert result.stdout.count("Skipping")
assert result.stdout.count("Skipped 1 file(s) with existing output")
# existing output is not touched
assert (dir_out / "a_dcn.rtdc").read_text() == "previous output"
with h5py.File(dir_out / "b_dcn.rtdc") as h5:
assert "deform" in h5["events"]


def test_cli_recursive_invalid_kwargs(cli_runner, tmp_path):
"""Invalid command-line arguments abort the batch"""
path = retrieve_data(
"fmt-hdf5_cytoshot_full-features_legacy_allev_2023.zip")
dir_in = tmp_path / "in"
dir_in.mkdir()
shutil.copy2(path, dir_in / "a.rtdc")
shutil.copy2(path, dir_in / "b.rtdc")
result = cli_runner.invoke(cli_main.chipstream_cli,
[str(dir_in), "--recursive", "--debug",
"-ks", "peter=3"])
assert result.exit_code == 2
assert result.stderr.count("Invalid keyword 'peter' for 'thresh'")
# the batch is aborted at the first file
assert not result.stdout.count("b.rtdc")
assert not (dir_in / "a_dcn.rtdc").exists()
assert not (dir_in / "b_dcn.rtdc").exists()


def test_cli_recursive_with_file(cli_runner):
"""Recursive mode requires a directory as input"""
path = retrieve_data(
Expand Down
Loading