Skip to content

afmslicer.run_modules

Run modules in parallel.

completion_message(config, img_files, images_processed)

Print a completion message summarising images processed.

Parameters:

Name Type Description Default
config dict

Configuration dictionary.

required
img_files list

List of found image paths.

required
images_processed int

Pandas DataFrame of results.

required
Source code in src/afmslicer/run_modules.py
def completion_message(
    config: dict, img_files: dict[str, Any], images_processed: int
) -> None:
    """
    Print a completion message summarising images processed.

    Parameters
    ----------
    config : dict
        Configuration dictionary.
    img_files : list
        List of found image paths.
    images_processed : int
        Pandas DataFrame of results.
    """
    logger.info(
        "\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"
    )
    tprint("AFMSlicer", font="twisted")
    logger.info(
        f"\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ COMPLETE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"
        f"  AFMSlicer Version           : {AFMSLICER_BASE_VERSION}\n"
        f"  AFMSlicer Commit            : {AFMSLICER_COMMIT}\n"
        f"  Base Directory              : {config['base_dir']}\n"
        f"  File Extension              : {config['file_ext']}\n"
        f"  Files Found                 : {len(img_files)}\n"
        f"  Successfully Processed^1    : {images_processed} ({(images_processed * 100) / len(img_files)}%)\n"
        f"  All statistics              : {config['output_dir']!s}/statistics.csv\n"
        f"  Configuration               : {config['output_dir']}/config.yaml\n\n"
        f"  Email                       : afmslicer@sheffield.ac.uk\n"
        f"  Documentation               : https://afm-spm.github.io/afmslicer/\n"
        f"  Source Code                 : https://github.com/AFM-SPM/AFMSlicer/\n"
        f"  Bug Reports/Feature Request : https://github.com/AFM-SPM/AFMSlicer/issues/new/choose\n"
        f"  Citation File Format        : https://github.com/AFM-SPM/AFMSlicer/blob/main/CITATION.cff\n\n"
        f"  ^1 Successful processing of an image is slicing an image, calculating and plotting\n"
        f"     statistics. If these have been disabled the percentage will be 0.\n\n"
        f"  If you encounter bugs/issues or have feature requests please report them at the above URL\n"
        f"  or email us.\n\n"
        f"  If you have found AFMSlicer useful please consider citing it. A Citation File Format is\n"
        f"  linked above and available from the Source Code page.\n"
        f"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n"
    )

filter(args=None)

Filter/flatten images in parallel.

Parameters:

Name Type Description Default
args Namespace

Arguments to process images with.

None
Source code in src/afmslicer/run_modules.py
def filter(args: argparse.Namespace | None = None) -> None:  # pylint: disable=redefined-builtin
    """
    Filter/flatten images in parallel.

    Parameters
    ----------
    args : argparse.Namespace
        Arguments to process images with.
    """
    config, img_files = _parse_configuration(args)
    processing_function = partial(processing.filter_scan, config=config)

    # Get a dictionary of all the image data dictionaries.
    scan_data_dict = _load_scans(img_files, config)

    with Pool(processes=config["cores"]) as pool:
        images_processed = 0
        success = 0
        with tqdm(
            total=len(img_files),
            desc=f"Filtering images from {config['base_dir']}, results are under {config['output_dir']}",
        ) as pbar:
            for filename, processed in pool.imap_unordered(
                processing_function,
                scan_data_dict.values(),
            ):
                images_processed += 1
                if processed:
                    success += 1
                pbar.update()
                # Display completion message for the image
                logger.info(f"[{filename}] Processing completed.")
    # Write config to file
    write_yaml(config, output_dir=config["output_dir"], header_message=HEADER_MESSAGE)
    completion_message(config, img_files, images_processed)

process(args=None)

Process images in parallel.

Parameters:

Name Type Description Default
args Namespace

Arguments to process images with.

None
Source code in src/afmslicer/run_modules.py
def process(args: argparse.Namespace | None = None) -> None:
    """
    Process images in parallel.

    Parameters
    ----------
    args : argparse.Namespace
        Arguments to process images with.
    """
    config, img_files = _parse_configuration(args)
    processing_function = partial(processing.process_scan, config=config)

    # ns-rse 2026-02-18 Bump number of slices up in config need to fix this, should get directly from config within
    #                   AFMSlicer.config["slicing"]["slices"] when needed
    config["slices"] = config["slicing"]["slices"]

    # Get a dictionary of all the image data dictionaries.
    scan_data_dict = _load_scans(img_files, config)

    with Pool(processes=config["cores"]) as pool:
        processed_all = defaultdict()
        with tqdm(
            total=len(img_files),
            desc=f"Processing images from {config['base_dir']}, results are under {config['output_dir']}",
        ) as pbar:
            for (
                filename,
                processed_image,
            ) in pool.imap_unordered(
                processing_function,
                scan_data_dict.values(),
            ):
                # Append each images returned dataframes to the dictionaries
                if processed_image is not None:
                    processed_all[str(filename)] = processed_image

                pbar.update()
                # Display completion message for the image
                logger.info(f"[{filename}] Processing completed.")
                # Concatenate all the dictionary's values into a dataframe. Ignore the keys since
                # the dataframes have the file names in them already.
    statistics_all_df = pd.concat(
        {image_name: image.statistics for image_name, image in processed_all.items()}
    )
    # Classify pores into color
    statistics_all_df = statistics.classify_pore_size(
        df=statistics_all_df,
        area_thresholds=config["slicing"]["area_thresholds"],
        pore_colors=config["slicing"]["pore_colors"],
        area_val="area",
    )
    statistics_all_df = statistics_all_df.sort_values(by=["image", "layer", "pore"])
    statistics_all_df.to_csv(config["output_dir"] / "all_statistics.csv", index=False)
    # Aggregate HCFA statistics
    hcfa_all_df = pd.concat(
        {image_name: image.hcfa for image_name, image in processed_all.items()}
    )
    hcfa_all_df = hcfa_all_df.sort_values(by=["image", "layer"])
    hcfa_all_df.to_csv(config["output_dir"] / "all_hcfa.csv", index=False)
    # Aggregate counts by image, layer and pore color, reshape and sum
    color_count_df = statistics.summarise_pores(
        df=statistics_all_df, pore_colors=config["slicing"]["pore_colors"]
    )
    color_count_df = color_count_df.sort_values(by=["image", "layer"])
    color_count_df.to_csv(config["output_dir"] / "all_color_count.csv", index=False)
    # Write config to file
    write_yaml(config, output_dir=config["output_dir"], header_message=HEADER_MESSAGE)
    images_processed = len(processed_all)
    completion_message(config, img_files, images_processed)

slicer(args=None)

Slice images in parallel.

Parameters:

Name Type Description Default
args Namespace

Arguments to process images with.

None
Source code in src/afmslicer/run_modules.py
def slicer(args: argparse.Namespace | None = None) -> None:
    """
    Slice images in parallel.

    Parameters
    ----------
    args : argparse.Namespace
        Arguments to process images with.
    """
    config, img_files = _parse_configuration(args)
    processing_function = partial(processing.slicer_scan, config=config)

    # Get a dictionary of all the image data dictionaries.
    scan_data_dict = _load_scans(img_files, config)

    # ns-rse 2026-02-18 Bump number of slices up in config need to fix this, should get directly from config within
    #                   AFMSlicer.config["slicing"]["slices"] when needed
    config["slices"] = config["slicing"]["slices"]
    images_processed = 0
    with Pool(processes=config["cores"]) as pool:
        processed_all = defaultdict()
        with tqdm(
            total=len(img_files),
            desc=f"Slicing images from {config['base_dir']}, results are under {config['output_dir']}",
        ) as pbar:
            for filename, processed_object in pool.imap_unordered(
                processing_function,
                scan_data_dict.values(),
            ):
                # Append each images returned dataframes to the dictionaries
                if processed_object is not None:
                    processed_all[str(filename)] = processed_object
                pbar.update()
                # Display completion message for the image
                logger.info(f"[{filename}] Processing completed.")
    # Write config to file
    write_yaml(config, output_dir=config["output_dir"], header_message=HEADER_MESSAGE)
    images_processed = len(processed_all)
    completion_message(config, img_files, images_processed)