Source: bactoscoop/imagecollection.pyΒΆ

   1# -*- coding: utf-8 -*-
   2"""
   3Created on Wed Apr 12 16:47:19 2023
   4
   5@author: Bart Steemans. Govers Lab.
   6"""
   7
   8import os
   9import pickle
  10import cv2 as cv
  11import numpy as np
  12import tifffile
  13from . import utilities as u
  14from .logging_utils import get_bactoscoop_logger, tqdm_if_verbose
  15from .image import Image
  16import pandas as pd
  17from itertools import combinations
  18
  19import logging, sys, datetime, traceback
  20import gc
  21import tempfile
  22
  23
  24bactoscoop_logger = get_bactoscoop_logger()
  25# # Change following to DEBUG to see more information
  26# bactoscoop_logger.setLevel(logging.INFO)
  27
  28
  29class ImageCollection:
  30    """ """
  31
  32    def __init__(
  33        self, image_folder_path=None, px=0.065, error_policy="continue",
  34        log_cell_errors=False,
  35    ):
  36        """Create a collection.
  37
  38        ``error_policy="continue"`` records item-level errors and proceeds with
  39        independent fields. ``error_policy="raise"`` raises on the first one.
  40        Required-stage failures still stop dependent work in either mode.
  41        Cell feature failures are recorded separately and do not make a run
  42        partial in continue mode. Set ``log_cell_errors=True`` to print each one.
  43        """
  44        if error_policy not in {"continue", "raise"}:
  45            raise ValueError("error_policy must be either 'continue' or 'raise'.")
  46        self.error_policy = error_policy
  47        self.log_cell_errors = log_cell_errors
  48        self.processing_errors = []
  49        self.cell_errors = []
  50        self.completed_stages = set()
  51
  52        self.px = px  # microns per pixel
  53        self.images = None
  54        self.masks = None
  55        self.channel_images = {}
  56        self.channel_image_filenames = {}
  57        self.channel_images_by_field = {}
  58        self.inverted_image = None
  59        self.channel_list = None
  60        self.image_filenames = None
  61        self.mask_filenames = None
  62        self.phase_channel = ""
  63        self.segmentation_failed = False
  64
  65        self.image_folder_path = image_folder_path  # Path to the folder to be processed
  66        self.name = (
  67            os.path.basename(os.path.normpath(self.image_folder_path))
  68            if self.image_folder_path is not None
  69            else None
  70        )
  71
  72        self.image_objects = []  # Array that will be populated with objects
  73
  74        self.mesh_df_collection = pd.DataFrame()
  75
  76        self.feature_dataframes = {}
  77        self.merged_features = None
  78        self.mesh_prefilter_stats = pd.DataFrame()
  79
  80    def _require_image_folder_path(self):
  81        if self.image_folder_path is None:
  82            raise ValueError("image_folder_path must be set before loading image data.")
  83
  84    def _require_loaded_images(self):
  85        if not self.image_objects:
  86            raise ValueError(
  87                "No image objects are available. Run create_image_objects() or load mesh data first."
  88            )
  89
  90    def _record_processing_error(
  91        self, stage, error, image_name=None, channel=None, cell_id=None
  92    ):
  93        record = {
  94            "stage": stage,
  95            "image_name": image_name,
  96            "channel": channel,
  97            "cell_id": cell_id,
  98            "error_type": type(error).__name__,
  99            "error": str(error),
 100        }
 101        self.processing_errors.append(record)
 102        bactoscoop_logger.error(
 103            "Processing error at %s (image=%s, channel=%s, cell_id=%s): %s",
 104            stage,
 105            image_name,
 106            channel,
 107            cell_id,
 108            error,
 109        )
 110        if self.error_policy == "raise":
 111            raise error
 112        return record
 113
 114    def _record_cell_error(
 115        self, stage, error, image_name, channel, cell_id, error_type=None
 116    ):
 117        record = {
 118            "stage": stage,
 119            "image_name": image_name,
 120            "channel": channel,
 121            "cell_id": cell_id,
 122            "error_type": error_type or type(error).__name__,
 123            "error": str(error),
 124        }
 125        self.cell_errors.append(record)
 126        if self.log_cell_errors:
 127            bactoscoop_logger.warning(
 128                "Cell processing error at %s (image=%s, channel=%s, cell_id=%s): %s",
 129                stage, image_name, channel, cell_id, error,
 130            )
 131        if self.error_policy == "raise":
 132            raise error
 133        return record
 134
 135    def processing_summary(self):
 136        """Return recorded stages and accumulated processing and cell errors.
 137
 138        ``completed`` means at least one stage finished and no processing
 139        errors were recorded. Inspect ``completed_stages`` to see which stages
 140        ran and ``cell_error_count`` for individual cell failures. Cell errors
 141        alone do not change the status. Returns a new summary dictionary.
 142        """
 143        if self.processing_errors:
 144            status = "completed_with_errors"
 145        elif self.completed_stages:
 146            status = "completed"
 147        else:
 148            status = "not_started"
 149        return {
 150            "status": status,
 151            "completed_stages": sorted(self.completed_stages),
 152            "error_count": len(self.processing_errors),
 153            "errors": list(self.processing_errors),
 154            "cell_error_count": len(self.cell_errors),
 155            "cell_errors": list(self.cell_errors),
 156        }
 157
 158    def _record_stage_success(self, stage):
 159        self.completed_stages.add(stage)
 160
 161    def _validate_phase_image_state(self):
 162        if self.images is None or self.image_filenames is None:
 163            raise ValueError(
 164                "Phase images are not loaded. Run load_phase_images() before creating image objects."
 165            )
 166        if self.masks is None:
 167            raise ValueError(
 168                "Masks are not loaded. Run load_masks() before creating image objects."
 169            )
 170        if len(self.image_filenames) != len(self.images):
 171            raise ValueError(
 172                f"Loaded {len(self.image_filenames)} image names but {len(self.images)} phase images."
 173            )
 174        if self.mask_filenames is None or len(self.mask_filenames) != len(self.masks):
 175            raise ValueError("Mask arrays and mask filenames are not aligned.")
 176
 177        phase_by_key = {}
 178        for index, filename in enumerate(self.image_filenames):
 179            key = u.image_field_key(filename, suffix=self.phase_channel)
 180            if key in phase_by_key:
 181                self._record_processing_error(
 182                    "phase_mask_matching",
 183                    ValueError(f"Duplicate phase field identity '{key}'."),
 184                    image_name=filename,
 185                )
 186                continue
 187            phase_by_key[key] = (index, filename, self.images[index])
 188
 189        masks_by_key = {}
 190        for index, filename in enumerate(self.mask_filenames):
 191            key = u.image_field_key(
 192                filename, suffix=self.phase_channel, is_mask=True
 193            )
 194            if key in masks_by_key:
 195                self._record_processing_error(
 196                    "phase_mask_matching",
 197                    ValueError(f"Duplicate mask field identity '{key}'."),
 198                    image_name=filename,
 199                )
 200                continue
 201            masks_by_key[key] = (filename, self.masks[index])
 202
 203        matched = []
 204        for key, (frame, image_name, image) in phase_by_key.items():
 205            mask_entry = masks_by_key.get(key)
 206            if mask_entry is None:
 207                self._record_processing_error(
 208                    "phase_mask_matching",
 209                    ValueError(f"No mask matches phase field '{image_name}'."),
 210                    image_name=image_name,
 211                )
 212                continue
 213            mask_name, mask = mask_entry
 214            if image.ndim != 2 or mask.ndim != 2:
 215                self._record_processing_error(
 216                    "phase_mask_matching",
 217                    ValueError(
 218                        f"Phase and mask images must be 2D; got phase shape "
 219                        f"{image.shape} and mask '{mask_name}' shape {mask.shape}."
 220                    ),
 221                    image_name=image_name,
 222                )
 223                continue
 224            if image.shape != mask.shape:
 225                self._record_processing_error(
 226                    "phase_mask_matching",
 227                    ValueError(
 228                        f"Phase shape {image.shape} does not match mask "
 229                        f"'{mask_name}' shape {mask.shape}."
 230                    ),
 231                    image_name=image_name,
 232                )
 233                continue
 234            matched.append((frame, image_name, image, mask))
 235
 236        for key, (mask_name, _) in masks_by_key.items():
 237            if key not in phase_by_key:
 238                self._record_processing_error(
 239                    "phase_mask_matching",
 240                    ValueError(f"No phase image matches mask '{mask_name}'."),
 241                    image_name=mask_name,
 242                )
 243        if not matched:
 244            raise ValueError("No phase images have matching masks and dimensions.")
 245        return matched
 246    def _normalize_channel_list(self, channel_list, argument_name="channel_list"):
 247        if channel_list is None:
 248            raise ValueError(
 249                f"No {argument_name} provided. It should be of format ['channelname1', 'channelname2']."
 250            )
 251        if isinstance(channel_list, str):
 252            raise TypeError(
 253                f"{argument_name} must be an iterable of channel names, not a single string."
 254            )
 255        normalized_channels = list(channel_list)
 256        if not normalized_channels:
 257            raise ValueError(f"{argument_name} must contain at least one channel name.")
 258        return normalized_channels
 259
 260    def _iter_processing_targets(self, object_list, phase_channel):
 261        if isinstance(object_list, Image):
 262            return [object_list]
 263        if object_list is None:
 264            self.create_image_objects(phase_channel=phase_channel)
 265            return self.image_objects
 266        if isinstance(object_list, (list, tuple)):
 267            return list(object_list)
 268        raise TypeError(
 269            "object_list must be None, a single Image instance, or a list/tuple of Image instances."
 270        )
 271
 272    def _get_mesh_dataframe_lookup(self):
 273        """Build an image-name lookup from the current mesh dataframe.
 274
 275        Do not retain this lookup across calls: callers can replace or mutate
 276        ``mesh_df_collection``, and a cached lookup could then return stale
 277        meshes for newly loaded data.
 278        """
 279        if not isinstance(self.mesh_df_collection, pd.DataFrame) or self.mesh_df_collection.empty:
 280            return None
 281        return {
 282            image_name: group.reset_index(drop=True)
 283            for image_name, group in self.mesh_df_collection.groupby(
 284                "image_name", sort=False
 285            )
 286        }
 287
 288
 289    def load_masks(self):
 290        """
 291        Read masks from the ``/masks`` subfolder.
 292
 293        Mutates ``self.masks`` and ``self.mask_filenames``.
 294
 295        """
 296        self._require_image_folder_path()
 297        self.masks, self.mask_filenames = u.read_tiff_folder(
 298            self.image_folder_path + "/masks"
 299        )
 300        self._record_stage_success("load_masks")
 301
 302    def load_phase_images(self, phase_channel=""):
 303        """
 304        This method loads phase contrast images from the specified image folder path, based on the characters before the file-extension,
 305        and stores them in the 'self.images' array.
 306
 307        Parameters
 308        ----------
 309        phase_channel : str, optional
 310            Characters before the file-extension (e.g., "c1", "phase") to look for when using this function. (default is an empty string)
 311
 312        Mutates ``self.images``, ``self.image_filenames`` and ``self.paths``.
 313
 314        """
 315        self._require_image_folder_path()
 316        self.phase_channel = phase_channel or ""
 317        try:
 318            self.images, self.image_filenames, self.paths = u.read_tiff_folder(
 319                self.image_folder_path, phase_channel, include_paths=True
 320            )
 321        except Exception as e:
 322            raise type(e)(
 323                f"Failed to load phase contrast images from '{self.image_folder_path}' "
 324                f"with phase_channel='{phase_channel}': {e}"
 325            ) from e
 326        self._record_stage_success("load_phase_images")
 327
 328    def load_channel_images(self, channel_list):
 329        """
 330        This method loads channel images from the image folder path based on the specified characters before the file-extension and stores them in
 331        the 'self.channel_images' dictionary, where the channel name is used as the key.
 332
 333        Parameters
 334        ----------
 335        channel_list : List of str
 336            Characters before the extension (e.g., ["c2", "c3"]) to look for when using this function.
 337
 338        Mutates ``self.channel_images``.
 339
 340        """
 341        self._require_image_folder_path()
 342        self.channel_list = self._normalize_channel_list(channel_list)
 343        for channel in self.channel_list:
 344            # A failed read must not leave arrays from an earlier folder/load in place.
 345            self.channel_images.pop(channel, None)
 346            self.channel_image_filenames.pop(channel, None)
 347            self.channel_images_by_field.pop(channel, None)
 348            try:
 349                images, filenames = u.read_tiff_folder(
 350                    self.image_folder_path, suffix=channel
 351                )
 352            except Exception as e:
 353                self._record_processing_error(
 354                    "load_channel_images", e, channel=channel
 355                )
 356                continue
 357
 358            self.channel_images[channel] = list(images)
 359            self.channel_image_filenames[channel] = list(filenames)
 360            keyed_images = {}
 361            for filename, image in zip(filenames, images):
 362                key = u.image_field_key(filename, suffix=channel)
 363                if key in keyed_images:
 364                    self._record_processing_error(
 365                        "load_channel_images",
 366                        ValueError(f"Duplicate channel field identity '{key}'."),
 367                        image_name=filename,
 368                        channel=channel,
 369                    )
 370                    continue
 371                keyed_images[key] = image
 372            self.channel_images_by_field[channel] = keyed_images
 373        self._record_stage_success("load_channel_images")
 374
 375    def create_image_objects(self, phase_channel=""):
 376        """
 377        Create ``Image`` objects from the loaded masks and phase images.
 378
 379        Invalid collection-level setup raises immediately. Failures while creating
 380        a single image object are logged and skipped so the rest of the batch can continue.
 381        """
 382        if self.segmentation_failed:
 383            raise RuntimeError(
 384                "Segmentation failed in this collection; refusing to load masks "
 385                "from disk because they may belong to an earlier run."
 386            )
 387        if self.masks is None:
 388            self.load_masks()
 389        if self.images is None or self.image_filenames is None:
 390            self.load_phase_images(phase_channel)
 391
 392        matched_images = self._validate_phase_image_state()
 393
 394        # Feature tables and merged output belong to the previous image/cell set.
 395        self.feature_dataframes = {}
 396        self.merged_features = None
 397        self.image_objects = []
 398        mesh_lookup = self._get_mesh_dataframe_lookup()
 399
 400        for i, image_name, image, mask in matched_images:
 401            try:
 402                mesh_df = mesh_lookup.get(image_name) if mesh_lookup is not None else None
 403
 404                img_obj = self.create_image_object(
 405                    image, image_name, i, mask, mesh_df, self.px
 406                )
 407                self.image_objects.append(img_obj)
 408            except Exception as e:
 409                bactoscoop_logger.debug(traceback.format_exc())
 410                self._record_processing_error(
 411                    "create_image_objects", e, image_name=image_name
 412                )
 413        self._record_stage_success("create_image_objects")
 414
 415    def add_channels(self, img_objects, channel_list, load_data=True):
 416        """
 417        This method loads channel images based on the provided channel list and adds them to the individual image objects.
 418
 419        Parameters
 420        ----------
 421        img_objects : List
 422            List of image objects.
 423        channel_list : List
 424            List of channel names.
 425
 426        """
 427        channel_list = self._normalize_channel_list(channel_list)
 428        if img_objects is None or len(img_objects) == 0:
 429            raise ValueError("img_objects must contain at least one image object.")
 430
 431        # Load requested channels while keeping field identity beside each array.
 432        if load_data:
 433            self.load_channel_images(channel_list)
 434
 435        expected_fields = {
 436            u.image_field_key(obj.image_name, suffix=self.phase_channel)
 437            for obj in img_objects
 438        }
 439        for channel in channel_list:
 440            for extra_field in self.channel_images_by_field.get(channel, {}):
 441                if extra_field not in expected_fields:
 442                    self._record_processing_error(
 443                        "match_channel_image",
 444                        ValueError(
 445                            f"No phase image object matches {channel} field '{extra_field}'."
 446                        ),
 447                        image_name=extra_field,
 448                        channel=channel,
 449                    )
 450
 451        for img_obj in img_objects:
 452            channel_single_image_dict = dict(getattr(img_obj, "channels", None) or {})
 453            field_key = u.image_field_key(
 454                img_obj.image_name, suffix=self.phase_channel
 455            )
 456            for channel in channel_list:
 457                # Never retain an earlier image or derived interpolation for a
 458                # requested channel if its current file is missing or invalid.
 459                channel_single_image_dict.pop(channel, None)
 460                for cache_name in ("bg_channels", "chann_interp2d"):
 461                    cache = getattr(img_obj, cache_name, None)
 462                    if isinstance(cache, dict):
 463                        cache.pop(channel, None)
 464                channel_fields = self.channel_images_by_field.get(channel, {})
 465                channel_image = channel_fields.get(field_key)
 466                if channel_image is None:
 467                    self._record_processing_error(
 468                        "match_channel_image",
 469                        ValueError(
 470                            f"No {channel} image matches field '{img_obj.image_name}'."
 471                        ),
 472                        image_name=img_obj.image_name,
 473                        channel=channel,
 474                    )
 475                    continue
 476                if channel_image.ndim != 2 or img_obj.image.ndim != 2:
 477                    self._record_processing_error(
 478                        "match_channel_image",
 479                        ValueError(
 480                            f"{channel} and phase images must be 2D; got channel "
 481                            f"shape {channel_image.shape} and phase shape {img_obj.image.shape}."
 482                        ),
 483                        image_name=img_obj.image_name,
 484                        channel=channel,
 485                    )
 486                    continue
 487                if channel_image.shape != img_obj.image.shape:
 488                    self._record_processing_error(
 489                        "match_channel_image",
 490                        ValueError(
 491                            f"{channel} image shape {channel_image.shape} does not "
 492                            f"match phase shape {img_obj.image.shape}."
 493                        ),
 494                        image_name=img_obj.image_name,
 495                        channel=channel,
 496                    )
 497                    continue
 498                channel_single_image_dict[channel] = channel_image
 499            img_obj.channels = channel_single_image_dict or None
 500        self._record_stage_success("add_channels")
 501
 502    def get_mesh_dataframe(self, image_name):
 503        """
 504        This method returns the mesh dataframe associated with the specified image name.
 505
 506        Parameters
 507        ----------
 508        image_name : str
 509            The name or identifier of the image.
 510
 511        """
 512
 513        mesh_lookup = self._get_mesh_dataframe_lookup()
 514        if mesh_lookup is None:
 515            return None
 516        return mesh_lookup.get(image_name)
 517
 518    def create_image_object(self, image, image_name, index, mask, mesh_df, px):
 519        """
 520        This method creates a single Image object using the provided image, image name, index, mask, mesh dataframe, and pixel size (px).
 521        If mesh data is present, it also creates associated Cell objects.
 522
 523        Parameters
 524        ----------
 525        image : phase contrast image
 526            The phase contrast image for the Image object.
 527        image_name : str
 528            The name or identifier of the image.
 529        index : int
 530            The index or position of the image.
 531        mask : mask or None
 532            The mask or region of interest associated with the image.
 533        mesh_df : pd.DataFrame or None
 534            The mesh dataframe associated with the image, if available, or None.
 535        px : float
 536        The pixel size in micrometers.
 537        """
 538
 539        img_obj = Image(image, image_name, index, mask, mesh_df, px=px)
 540
 541        if mesh_df is not None:
 542            img_obj.create_cell_object(verbose=False)
 543        return img_obj
 544
 545    # Methods for batch processing of images ----------------------------------------------
 546    def segment_images(self, mask_thresh, minsize, n, model_name="bact_phase_omni"):
 547        self.segmentation_failed = False
 548        self.masks = None
 549        self.mask_filenames = None
 550        try:
 551            from .omni import Omnipose
 552            import torch
 553
 554            omni = Omnipose(self.images, self.paths)
 555            omni.load_models(model_name)
 556
 557            omni.compiled_process(n, mask_thresh, minsize)
 558            torch.cuda.empty_cache()
 559
 560            del omni
 561            gc.collect()
 562            self._record_stage_success("segment_images")
 563            return True
 564        except Exception as e:
 565            self.segmentation_failed = True
 566            bactoscoop_logger.debug(traceback.format_exc())
 567            self._record_processing_error("segment_images", e)
 568            return False
 569
 570    def batch_detect_objects(
 571        self,
 572        channels=None,
 573        reset_channels=True,
 574        align=False,
 575        smoothing=0.1,
 576        log_sigma=3,
 577        kernel_width=4,
 578        min_overlap_ratio=0.01,
 579        max_external_ratio=0.1,
 580    ):
 581        """
 582        Detect objects within the contour of the cell.
 583
 584        Parameters
 585        ----------
 586        channels : List of strings, optional
 587            The channel names of the channels to perform object detection on.
 588
 589        log_sigma : int, optional
 590            The sigma parameter of the Laplacian of Gaussian filter used in object detection. (default is 3)
 591
 592        kernel_width : int, optional
 593            The kernel width of the kernel used for dilating the object masks.
 594            Decreasing results in smaller masks, while increasing results in larger masks. (default is 4)
 595
 596        min_overlap_ratio : float, optional
 597            Minimum overlap between the object and cell required for the object to be kept. (default is 0.01)
 598
 599        max_external_ratio : float, optional
 600            The maximum ratio an object is allowed to lie outside the cell contour. (default is 0.1)
 601
 602        Returns
 603        -------
 604        pd.DataFrame
 605            A DataFrame containing cell_id, object_contours, and frame information.
 606
 607        """
 608        self._require_loaded_images()
 609        channels = self._normalize_channel_list(channels, argument_name="channels")
 610
 611        if reset_channels:
 612            self.channel_images = {}
 613            self.channel_image_filenames = {}
 614            self.channel_images_by_field = {}
 615            for image in self.image_objects:
 616                image.channels = None
 617                for cache_name in ("bg_channels", "chann_interp2d"):
 618                    cache = getattr(image, cache_name, None)
 619                    if isinstance(cache, dict):
 620                        cache.clear()
 621
 622        channels_to_load = [
 623            channel for channel in channels
 624            if channel not in self.channel_images_by_field
 625        ]
 626        if channels_to_load:
 627            self.load_channel_images(channels_to_load)
 628        self.add_channels(self.image_objects, channels, load_data=False)
 629
 630        bactoscoop_logger.info("Detecting objects within cell ...")
 631
 632        dfs = []
 633        for image in tqdm_if_verbose(self.image_objects):
 634            for cell in getattr(image, "cells", []):
 635                for channel in channels:
 636                    cell.object_meshdata.pop(channel, None)
 637            if image.channels is None or any(
 638                channel not in image.channels for channel in channels
 639            ):
 640                # The missing field has already been recorded by add_channels.
 641                continue
 642            try:
 643                detection_df = image.object_detection(
 644                    channels,
 645                    smoothing,
 646                    align,
 647                    log_sigma,
 648                    kernel_width,
 649                    min_overlap_ratio,
 650                    max_external_ratio,
 651                )
 652            except Exception as e:
 653                bactoscoop_logger.debug(traceback.format_exc())
 654                self._record_processing_error(
 655                    "object_detection", e, image_name=image.image_name
 656                )
 657                continue
 658            dfs.append(detection_df)
 659            cell_errors = getattr(image, "object_detection_errors", [])
 660            for cell_error in cell_errors:
 661                self._record_cell_error(
 662                    "cell_object_detection",
 663                    RuntimeError(cell_error["error"]),
 664                    image_name=image.image_name,
 665                    channel=cell_error.get("channel"),
 666                    cell_id=cell_error.get("cell_id"),
 667                    error_type=cell_error.get("error_type"),
 668                )
 669            cell_count = len(getattr(image, "cells", []))
 670            failed_attempts = sum(
 671                not error.get("recovered", False) for error in cell_errors
 672            )
 673            if cell_count and failed_attempts >= cell_count * len(channels):
 674                self._record_processing_error(
 675                    "object_detection",
 676                    ValueError(
 677                        f"All cell object-detection attempts failed for '{image.image_name}'."
 678                    ),
 679                    image_name=image.image_name,
 680                )
 681
 682        self.object_detection_df = (
 683            pd.concat(dfs, axis=0, ignore_index=True) if dfs else pd.DataFrame()
 684        )
 685
 686        if not self.object_detection_df.empty and "channel" in self.object_detection_df:
 687            bactoscoop_logger.info(self.object_detection_df["channel"].value_counts())
 688        else:
 689            bactoscoop_logger.info("No objects were detected.")
 690
 691        self._record_stage_success("batch_detect_objects")
 692        return self.object_detection_df
 693
 694    def batch_process_mesh(
 695        self,
 696        pkl_name=None,
 697        object_list=None,
 698        save_data=True,
 699        phase_channel="",
 700        join_thresh=4,
 701        split_thresh=0.35,
 702        CD_width=False,
 703        smoothing=0.1,
 704        neighbor_filter_max_neighbors=None,
 705        neighbor_filter_connectivity=1,
 706        max_daughter_cell_mesh_rows=800,
 707    ):
 708        """
 709        Process cellular meshes from segmented masks and store the data in Cell objects.
 710
 711        After segmentation, this method can process the resulting masks and create cellular meshes from them.
 712        It first joins cells with a pole-pole distance (px) at or below 'join_thresh'.
 713        Subsequently, meshes of all cells are created and cells can be split again if the constriction degree exceeds the 'split_thresh'.
 714        The data is then stored in Cell objects and can be exported in a pickle file.
 715
 716        Parameters
 717        ----------
 718        pkl_name : str, optional
 719            Name of the pickle file to save the mesh data. If None, the file will be saved as 'folder_name_meshdata.pkl'.
 720
 721        object_list : List, optional
 722            Specify a list of Image objects to be processed. If 'object_list' is None, all Image instances in 'image_objects' are processed.
 723
 724        phase_channel : str, optional
 725            Characters before the file-extension (.tif, .tiff) that the algorithm looks for when using this function (e.g., "c1", "phase").
 726
 727        join_thresh : int, optional
 728            Join cell masks when their nearest poles are at most join_thresh
 729            pixels apart. For example, 4 means up to four pixels. (default is 4)
 730
 731        split_thresh : float, optional
 732            The constriction degree threshold for splitting cells. Cells with a constriction degree exceeding this threshold will be split. (default is 0.35)
 733
 734        max_daughter_cell_mesh_rows : int, optional
 735            Maximum rebuilt daughter mesh rows (default 800, minimum 4).
 736            Oversized resampling is rejected before allocation; both final
 737            daughters must have between 4 and max_daughter_cell_mesh_rows mesh
 738            rows, inclusive. Each row pairs points on the two mesh sides.
 739            This is separate from the feature
 740            extraction max_mesh_size parameter and does not limit unsplit parents.
 741
 742        """
 743        max_daughter_cell_mesh_rows = u._validate_max_daughter_cell_mesh_rows(
 744            max_daughter_cell_mesh_rows
 745        )
 746        self.mesh_df_collection = pd.DataFrame()
 747        self.mesh_prefilter_stats = pd.DataFrame()
 748        object_list = self._iter_processing_targets(object_list, phase_channel)
 749        mesh_frames = []
 750        prefilter_stats = []
 751
 752        for img_obj in object_list:
 753            bactoscoop_logger.info(f"PROCESSING IMAGE: {img_obj.image_name}")
 754            try:
 755                img_obj.join_split_pipeline(
 756                    join_thresh,
 757                    split_thresh,
 758                    CD_width,
 759                    smoothing,
 760                    neighbor_filter_max_neighbors=neighbor_filter_max_neighbors,
 761                    neighbor_filter_connectivity=neighbor_filter_connectivity,
 762                    max_daughter_cell_mesh_rows=max_daughter_cell_mesh_rows,
 763                )
 764                mesh_df = getattr(img_obj, "processed_mesh_dataframe", None)
 765                if mesh_df is None:
 766                    raise ValueError(
 767                        f"Image '{img_obj.image_name}' did not produce a processed mesh dataframe."
 768                    )
 769                mesh_frames.append(mesh_df)
 770                if getattr(img_obj, "prefilter_summary", None) is not None:
 771                    prefilter_stats.append(
 772                        {
 773                            "image_name": img_obj.image_name,
 774                            **img_obj.prefilter_summary,
 775                        }
 776                    )
 777                img_obj.create_cell_object(verbose=False)
 778            except Exception as e:
 779                bactoscoop_logger.debug(traceback.format_exc())
 780                self._record_processing_error(
 781                    "mesh_processing", e, image_name=img_obj.image_name
 782                )
 783
 784        self.mesh_df_collection = (
 785            pd.concat(mesh_frames, ignore_index=True) if mesh_frames else pd.DataFrame()
 786        )
 787        self.mesh_prefilter_stats = (
 788            pd.DataFrame(prefilter_stats) if prefilter_stats else pd.DataFrame()
 789        )
 790
 791        if save_data:
 792            if pkl_name is not None:
 793                self._to_pickle(pkl_name, self.mesh_df_collection)
 794
 795            self._to_pickle(f"{self.name}_meshdata.pkl", self.mesh_df_collection)
 796
 797        self._record_stage_success("batch_process_mesh")
 798
 799
 800    def batch_load_mesh(self, pkl_name, pkl_path=None, phase_channel=""):
 801        """
 802        Load mesh data from a pickle-file and create image objects from the data.
 803
 804        Parameters
 805        ----------
 806        pkl_name : str
 807            Name of the pickle file where the mesh data is stored (e.g., 'Ecoli_meshdata.pkl').
 808
 809        pkl_path : str, optional
 810            Path to the file where the mesh data is stored. If not provided, the method will look in the image folder path.
 811
 812        phase_channel : str, optional
 813            Characters before the file-extension (.tif, .tiff) that the algorithm looks for when using this function (e.g., "c1", "phase").
 814
 815        """
 816        self.mesh_df_collection = None
 817        if pkl_path is None:
 818            pkl_path = self.image_folder_path
 819
 820        full_path = os.path.join(pkl_path, pkl_name)
 821        if not os.path.isfile(full_path):
 822            raise FileNotFoundError(f"Pickle file not found: {full_path}")
 823
 824        if full_path.lower().endswith(".parquet"):
 825            mesh_df = pd.read_parquet(full_path, engine="pyarrow")
 826            for column in ("contour", "mesh", "midline"):
 827                if column not in mesh_df:
 828                    raise ValueError(f"Mesh Parquet file is missing '{column}'.")
 829                mesh_df[column] = mesh_df[column].map(
 830                    lambda value: np.asarray(value.tolist(), dtype=float)
 831                )
 832            self.mesh_df_collection = mesh_df
 833        else:
 834            with open(full_path, "rb") as f:
 835                self.mesh_df_collection = pickle.load(f)
 836
 837        bactoscoop_logger.info("Meshes loaded from file: %s", pkl_name)
 838        self.create_image_objects(phase_channel=phase_channel)
 839
 840    def batch_mask2mesh(
 841        self,
 842        pkl_name=None,
 843        object_list=None,
 844        save_data=True,
 845        phase_channel="",
 846        smoothing=0.1,
 847    ):
 848        """
 849        Create meshes from masks without the joining or splitting as in the batch_process_mesh method.
 850
 851        Parameters
 852        ----------
 853        pkl_name : str, optional
 854            Name of the pickle file to save the mesh data. If None, the file will be saved as 'folder_name_meshdata.pkl'.
 855        object_list : List, optional
 856            Specify a list of Image objects to be processed. If 'object_list' is None, all Image instances in 'image_objects' are processed.
 857        phase_channel : str, optional
 858            Characters before the file-extension (.tif, .tiff) that the algorithm looks for when using this function (e.g., "c1", "phase").
 859        """
 860        self.mesh_df_collection = pd.DataFrame()
 861        mesh_frames = []
 862
 863        if isinstance(object_list, Image):
 864            print("\n")
 865            bactoscoop_logger.info(f"PROCESSING IMAGE: {object_list.image_name}")
 866
 867            object_list.mask2mesh(smoothing)
 868            mesh_frames.append(getattr(object_list, "mesh_dataframe"))
 869            object_list.create_cell_object(verbose=False)
 870        else:
 871
 872            if object_list is None:
 873                self.create_image_objects(phase_channel=phase_channel)
 874                object_list = self.image_objects
 875
 876            for img_obj in object_list:
 877
 878                bactoscoop_logger.info(f"PROCESSING IMAGE: {img_obj.image_name}")
 879
 880                img_obj.mask2mesh()
 881                mesh_frames.append(getattr(img_obj, "mesh_dataframe"))
 882
 883                img_obj.create_cell_object(verbose=False)
 884
 885        self.mesh_df_collection = (
 886            pd.concat(mesh_frames, ignore_index=True) if mesh_frames else pd.DataFrame()
 887        )
 888
 889        if save_data:
 890            if pkl_name is not None:
 891                self._to_pickle(pkl_name, self.mesh_df_collection)
 892
 893            self._to_pickle(
 894                "{}_meshdata.pkl".format(self.name), self.mesh_df_collection
 895            )
 896
 897    def batch_shift_correction(
 898        self,
 899        shifted_channel,
 900        reset_channels=False,
 901        log_sigma=1.5,
 902        kernel_width=3,
 903        min_overlap_ratio=0.1,
 904        max_external_ratio=1,
 905        phase_log_sigma=0.5,
 906        phase_closing_level=2,
 907        signal_closing_level=12,
 908        max_shift_correction=15,
 909    ):
 910        self._require_loaded_images()
 911        shifted_channel = self._normalize_channel_list(
 912            shifted_channel, argument_name="shifted_channel"
 913        )
 914
 915        if reset_channels:
 916            self.channel_images = {}
 917            self.channel_image_filenames = {}
 918            self.channel_images_by_field = {}
 919            for image in self.image_objects:
 920                image.channels = None
 921                for cache_name in ("bg_channels", "chann_interp2d"):
 922                    cache = getattr(image, cache_name, None)
 923                    if isinstance(cache, dict):
 924                        cache.clear()
 925
 926        channels_to_load = [
 927            channel for channel in shifted_channel
 928            if channel not in self.channel_images_by_field
 929        ]
 930        if channels_to_load:
 931            self.load_channel_images(channels_to_load)
 932        self.add_channels(self.image_objects, shifted_channel, load_data=False)
 933
 934        success_percentage_list = []
 935        bactoscoop_logger.info("Aligning contour, mesh and midline to channel image ...")
 936        for image_obj in tqdm_if_verbose(self.image_objects):
 937            if image_obj.channels is None or any(
 938                channel not in image_obj.channels for channel in shifted_channel
 939            ):
 940                # Missing channels were recorded by add_channels.
 941                continue
 942            try:
 943                success_percentage = image_obj.shift_correction(
 944                    shifted_channel,
 945                    log_sigma,
 946                    kernel_width,
 947                    min_overlap_ratio,
 948                    max_external_ratio,
 949                    phase_log_sigma,
 950                    phase_closing_level,
 951                    signal_closing_level,
 952                    max_shift_correction,
 953                )
 954            except Exception as e:
 955                bactoscoop_logger.debug(traceback.format_exc())
 956                self._record_processing_error(
 957                    "shift_correction", e, image_name=image_obj.image_name
 958                )
 959                continue
 960            success_percentage_list.append(success_percentage)
 961            cell_errors = getattr(image_obj, "shift_errors", [])
 962            for cell_error in cell_errors:
 963                self._record_cell_error(
 964                    "cell_shift_correction",
 965                    RuntimeError(cell_error["error"]),
 966                    image_name=image_obj.image_name,
 967                    channel=cell_error.get("channel"),
 968                    cell_id=cell_error.get("cell_id"),
 969                    error_type=cell_error.get("error_type"),
 970                )
 971            cell_count = len(getattr(image_obj, "cells", []))
 972            if cell_count and len(cell_errors) >= cell_count * len(shifted_channel):
 973                self._record_processing_error(
 974                    "shift_correction",
 975                    ValueError(
 976                        f"All cell shift-correction attempts failed for '{image_obj.image_name}'."
 977                    ),
 978                    image_name=image_obj.image_name,
 979                )
 980        if not success_percentage_list:
 981            bactoscoop_logger.warning("No shift-correction results were produced.")
 982            return 0.0
 983
 984        average_success_percentage = sum(success_percentage_list) / len(
 985            success_percentage_list
 986        )
 987
 988        bactoscoop_logger.info(f"Shift succes rate: {average_success_percentage}")
 989        return average_success_percentage
 990
 991    def batch_calculate_features(
 992        self,
 993        channel_method_pairs,
 994        all_data=True,
 995        reset=True,
 996        use_shifted_contours=False,
 997        shift_signal=False,
 998        max_mesh_size=600,
 999        retain_contour_on_object_mesh_failure_channels=None,
1000    ):
1001        """
1002        Calculate features of all image objects for specified channels and methods.
1003
1004        This method calculates features for all image objects based on the specified channel-method pairs. It takes a list of tuples, where each tuple contains channel names and the feature calculation method. The resulting feature dataframes are stored in a dictionary.
1005
1006        Parameters
1007        ----------
1008        channel_method_pairs : List[Tuple[List[str], str]]
1009            A list of tuples where each tuple contains the channel names and feature calculation method.
1010            Example of channel_method_pairs: [(['c1'], 'profiling'), (['c2', 'c3'], 'objects'), ([None], 'svm')].
1011            With the example pairs, this method will analyze c1 using the profiling method,
1012            then c2 and c3 using the objects method, and finally the phase contrast channel using the svm method.
1013
1014        add_profiling_data : bool, optional
1015            Whether to include profiling data in the feature calculation. (default is True)
1016
1017        reset : bool, optional
1018            If True, the dictionary storing the dataframes will be reset. If False, dataframes are added to the existing dictionary. (default is True)
1019        retain_contour_on_object_mesh_failure_channels : list[str] or None, optional
1020            Channels whose objects features retain contour-based measurements
1021            when any detected object mesh is invalid. Other channels omit that
1022            cell's objects feature row. None is equivalent to an empty list.
1023            This option does not affect other feature methods.
1024
1025        Returns
1026        -------
1027        Dict
1028            A dictionary containing dataframes with calculated features.
1029
1030        """
1031        self._require_loaded_images()
1032        if channel_method_pairs is None:
1033            raise ValueError("channel_method_pairs must be provided.")
1034        if retain_contour_on_object_mesh_failure_channels is None:
1035            retained_channels = frozenset()
1036        elif isinstance(retain_contour_on_object_mesh_failure_channels, str):
1037            raise TypeError(
1038                "retain_contour_on_object_mesh_failure_channels must be a list "
1039                "of channel names, not a string."
1040            )
1041        else:
1042            retained_channels = frozenset(
1043                retain_contour_on_object_mesh_failure_channels
1044            )
1045        if not all(isinstance(channel, str) for channel in retained_channels):
1046            raise TypeError(
1047                "retain_contour_on_object_mesh_failure_channels must contain "
1048                "only channel names."
1049            )
1050
1051        self.merged_features = None
1052        if reset:
1053            self.feature_dataframes = {}
1054
1055        for channels, method in channel_method_pairs:
1056            normalized_channels = (
1057                [None]
1058                if channels == [None]
1059                else self._normalize_channel_list(channels, argument_name="channels")
1060            )
1061            for channel in normalized_channels:
1062                key = f"{method}_{channel}_features"
1063                self.feature_dataframes.pop(key, None)
1064                bactoscoop_logger.info(
1065                    f"PROCESSING CHANNEL: {channel}, method: {method}"
1066                )
1067                feature_dfs = []
1068
1069                for img_obj in tqdm_if_verbose(self.image_objects):
1070                    if channel is not None and (
1071                        img_obj.channels is None or channel not in img_obj.channels
1072                    ):
1073                        self._record_processing_error(
1074                            "image_feature_calculation",
1075                            ValueError(
1076                                f"Channel {channel} is not loaded for image '{img_obj.image_name}'."
1077                            ),
1078                            image_name=img_obj.image_name,
1079                            channel=channel,
1080                        )
1081                        continue
1082                    try:
1083                        result_df = img_obj.calculate_features(
1084                            method,
1085                            channel,
1086                            all_data,
1087                            use_shifted_contours,
1088                            shift_signal,
1089                            max_mesh_size,
1090                            retained_channels,
1091                        )
1092                    except Exception as e:
1093                        bactoscoop_logger.debug(traceback.format_exc())
1094                        self._record_processing_error(
1095                            "image_feature_calculation",
1096                            e,
1097                            image_name=img_obj.image_name,
1098                            channel=channel,
1099                        )
1100                        continue
1101                    if result_df is not None:
1102                        feature_dfs.append(result_df)
1103                    for feature_error in getattr(img_obj, "feature_errors", []):
1104                        self._record_cell_error(
1105                            "cell_feature_calculation",
1106                            RuntimeError(feature_error["error"]),
1107                            image_name=img_obj.image_name,
1108                            channel=channel,
1109                            cell_id=feature_error.get("cell_id"),
1110                            error_type=feature_error.get("error_type"),
1111                        )
1112
1113                if feature_dfs:
1114                    concatenated_df = pd.concat(feature_dfs, axis=0)
1115                    concatenated_df.reset_index(drop=True, inplace=True)
1116                    self.feature_dataframes[key] = concatenated_df
1117                    has_rows = not concatenated_df.empty
1118                else:
1119                    has_rows = False
1120                if not has_rows:
1121                    self._record_processing_error(
1122                        "batch_calculate_features",
1123                        ValueError(
1124                            f"No feature rows were produced for channel {channel}, method {method}."
1125                        ),
1126                        channel=channel,
1127                    )
1128
1129        self._record_stage_success("batch_calculate_features")
1130        return self.feature_dataframes
1131
1132    def batch_calculate_signal_correlation_features(
1133        self, df, channels, feature_method_tuples
1134    ):
1135        from .signalcorrelation import SignalCorrelation
1136
1137        # Generate all unique pairs of channels
1138        channel_pairs = combinations(channels, 2)
1139
1140        for channel1, channel2 in channel_pairs:
1141            for features, method_names in feature_method_tuples:
1142                bactoscoop_logger.info(
1143                    f"Processing channel {channel1} vs {channel2} and features {features} from {self.image_folder_path}:"
1144                )
1145                for feature in tqdm_if_verbose(features):
1146                    prepared_feature = SignalCorrelation.prepare_feature_pair(
1147                        df, channel1, channel2, feature
1148                    )
1149
1150                    for method_name in method_names:
1151                        sc = SignalCorrelation(
1152                            df,
1153                            channel1,
1154                            channel2,
1155                            feature,
1156                            method_name,
1157                            prepared_feature=prepared_feature,
1158                        )
1159                        sc.calculate()
1160                        del sc
1161        return df
1162
1163    def _apply_curation_labels(self):
1164        """Apply curation labels by stable image identity, with frame fallback."""
1165        image_objects_by_name = {}
1166        image_objects_by_frame = {}
1167        for image in self.image_objects:
1168            image_objects_by_name.setdefault(image.image_name, []).append(image)
1169            image_objects_by_frame.setdefault(image.frame, []).append(image)
1170
1171        for _, row in self.curated_df.iterrows():
1172            image_name = row.get("image_name")
1173            cell_id = row["cell_id"]
1174            label = row["label"]
1175            image = None
1176
1177            if pd.notna(image_name):
1178                matches = image_objects_by_name.get(image_name, [])
1179                if len(matches) == 1:
1180                    image = matches[0]
1181                else:
1182                    reason = (
1183                        f"Image name '{image_name}' is not unique."
1184                        if len(matches) > 1
1185                        else f"No image object matches image name '{image_name}'."
1186                    )
1187                    self._record_processing_error(
1188                        "curation_mapping",
1189                        ValueError(reason),
1190                        image_name=image_name,
1191                        cell_id=cell_id,
1192                    )
1193                    continue
1194
1195            if image is None:
1196                frame = row.get("frame")
1197                matches = image_objects_by_frame.get(frame, [])
1198                if len(matches) == 1:
1199                    image = matches[0]
1200                else:
1201                    self._record_processing_error(
1202                        "curation_mapping",
1203                        ValueError(
1204                            f"Could not uniquely map curated cell {cell_id} to image "
1205                            f"(image_name={image_name!r}, frame={frame!r})."
1206                        ),
1207                        image_name=image_name if pd.notna(image_name) else None,
1208                        cell_id=cell_id,
1209                    )
1210                    continue
1211
1212            frame = row.get("frame")
1213            if pd.notna(frame) and image.frame != frame:
1214                self._record_processing_error(
1215                    "curation_mapping",
1216                    ValueError(
1217                        f"Curated cell {cell_id} names image '{image.image_name}' "
1218                        f"but has frame {frame}; expected {image.frame}."
1219                    ),
1220                    image_name=image.image_name,
1221                    cell_id=cell_id,
1222                )
1223                continue
1224
1225            cells = [cell for cell in image.cells if cell.cell_id == cell_id]
1226            if len(cells) != 1:
1227                reason = (
1228                    f"Cell ID {cell_id} was not found in image '{image.image_name}'."
1229                    if not cells
1230                    else f"Cell ID {cell_id} is not unique in image '{image.image_name}'."
1231                )
1232                self._record_processing_error(
1233                    "curation_mapping",
1234                    ValueError(reason),
1235                    image_name=image.image_name,
1236                    cell_id=cell_id,
1237                )
1238                continue
1239            if label == 0:
1240                image.cells.remove(cells[0])
1241
1242        self._record_stage_success("curate_dataset")
1243
1244    def curate_dataset(
1245        self, path_to_model, cols=4, control=False, save_curated_data=True
1246    ):
1247        """
1248        Optionally curate the dataset with a trained support vector machine.
1249
1250        This method calculates SVM features and uses a trained SVM model to classify cells based on these features.
1251        It discards cells classified as label 0 (rejected) and retains label 1.
1252        Optionally, it can include positive and negative control cells.
1253        Skip this method to extract features without an SVM. The resulting
1254        feature table can be filtered using measured values afterwards.
1255
1256        Parameters:
1257            path_to_model (str): Path to the trained SVM model.
1258
1259            cols (int): Retained for backward compatibility; currently unused.
1260
1261            control (bool): Whether to include positive and negative control cells.
1262
1263            save_curated_data (bool): Whether to write the curated mesh pickle.
1264                The in-memory mesh dataframe is updated either way.
1265
1266        Returns:
1267            None
1268        """
1269        self.batch_calculate_features(
1270            channel_method_pairs=[([None], "svm")], all_data=True, reset=True, max_mesh_size=800
1271        )
1272
1273        from .curation import Curation
1274
1275        cur = Curation(self.feature_dataframes["svm_None_features"])
1276
1277        self.curated_df = cur.compiled_curation(path_to_model, cols)
1278
1279        p1, p0 = cur.get_label_proportions()
1280        bactoscoop_logger.info(
1281            f"\nProportion of label 1: {p1}\nProportion of label 0: {p0}"
1282        )
1283
1284        if control:
1285            import bactoscoop.plot as plotting
1286
1287            self.pos, self.neg = cur.get_control(5, 5)
1288            if self.pos and self.neg is not None:
1289                bactoscoop_logger.info(
1290                    f"\nCell IDs and Frames for positive control are {self.pos}\nFrame and Cell IDs for negative control are {self.neg}"
1291                )
1292                plotting.plot_svm_controls(
1293                    self.pos, self.image_objects, message="Positive"
1294                )
1295                plotting.plot_svm_controls(
1296                    self.neg, self.image_objects, message="Negative"
1297                )
1298
1299        self._apply_curation_labels()
1300
1301
1302        # The in-memory mesh population follows the curated cells even when
1303        # the caller is only testing and does not want a file overwritten.
1304        self.add_meshdata_to_dataframe()
1305        if save_curated_data:
1306            self._to_pickle(
1307                "{}_curated_meshdata.pkl".format(self.name), self.mesh_df_collection
1308            )
1309
1310        del cur
1311
1312    def add_meshdata_to_dataframe(self):
1313        data = []
1314
1315        # Iterate over each image object
1316        for image in self.image_objects:
1317            # Iterate over each cell in the current image
1318            for cell in image.cells:
1319                # Extract the required attributes from the cell and image
1320                cell_id = cell.cell_id
1321                contour = cell.contour
1322                midline = cell.midline
1323                mesh = cell.mesh
1324                frame = image.frame
1325                image_name = image.image_name
1326
1327                # Append the data as a dictionary to the list
1328                data.append(
1329                    {
1330                        "image_name": image_name,
1331                        "frame": frame,
1332                        "cell_id": cell_id,
1333                        "contour": contour,
1334                        "midline": midline,
1335                        "mesh": mesh,
1336                    }
1337                )
1338
1339        # Create DataFrame from the collected data
1340        self.mesh_df_collection = pd.DataFrame(data)
1341
1342    def export_curated_masks(self, output_subfolder="curated_masks", overwrite=True):
1343        """Write one label mask per image from the SVM-curated cell contours.
1344
1345        This method is intended to be run after :meth:`curate_dataset`. It never
1346        changes the original Omnipose masks in ``masks``. Instead, it writes new
1347        masks to ``output_subfolder`` and records how every curated label overlaps
1348        the original labels, so the output can be used directly by BactoFeatures.
1349
1350        Parameters
1351        ----------
1352        output_subfolder : str, optional
1353            Folder below ``image_folder_path`` for the exported label TIFFs.
1354        overwrite : bool, optional
1355            If ``False``, fail before replacing an existing curated-mask TIFF.
1356
1357        Returns
1358        -------
1359        tuple[list[str], pandas.DataFrame]
1360            Paths to the exported masks and a provenance table with one row per
1361            curated cell.
1362        """
1363        self._require_image_folder_path()
1364        if not self.image_objects:
1365            raise ValueError(
1366                "No image objects are available. Load curated mesh data or run "
1367                "curate_dataset() before exporting curated masks."
1368            )
1369
1370        output_dir = os.path.join(self.image_folder_path, output_subfolder)
1371        os.makedirs(output_dir, exist_ok=True)
1372        mask_paths = []
1373        provenance_rows = []
1374
1375        for image in self.image_objects:
1376            if image.mask is None:
1377                raise ValueError(f"Original mask is not loaded for {image.image_name}.")
1378
1379            max_label = len(image.cells)
1380            output_dtype = np.uint16 if max_label <= np.iinfo(np.uint16).max else np.uint32
1381            curated_mask = np.zeros(image.mask.shape, dtype=output_dtype)
1382            stem = os.path.splitext(image.image_name)[0]
1383            output_path = os.path.join(output_dir, f"{stem}_curated_masks.tif")
1384            if os.path.exists(output_path) and not overwrite:
1385                raise FileExistsError(
1386                    f"Curated mask already exists: {output_path}. Set overwrite=True to replace it."
1387                )
1388
1389            for curated_label, cell in enumerate(image.cells, start=1):
1390                contour = np.asarray(cell.contour, dtype=float)
1391                if contour.ndim != 2 or contour.shape[1] != 2 or len(contour) < 3:
1392                    bactoscoop_logger.warning(
1393                        "Skipping curated cell %s in %s: invalid contour.",
1394                        cell.cell_id,
1395                        image.image_name,
1396                    )
1397                    continue
1398
1399                cell_mask = np.zeros(image.mask.shape, dtype=np.uint8)
1400                # Cell contours are (row, column); OpenCV expects (x, y).
1401                polygon = np.rint(contour[:, ::-1]).astype(np.int32).reshape(-1, 1, 2)
1402                cv.fillPoly(cell_mask, [polygon], color=1)
1403                cell_pixels = cell_mask.astype(bool)
1404                if not cell_pixels.any():
1405                    bactoscoop_logger.warning(
1406                        "Skipping curated cell %s in %s: contour has no in-image pixels.",
1407                        cell.cell_id,
1408                        image.image_name,
1409                    )
1410                    continue
1411
1412                curated_mask[cell_pixels] = curated_label
1413                source_labels = np.unique(image.mask[cell_pixels])
1414                source_labels = source_labels[source_labels != 0].astype(int).tolist()
1415                rows, columns = np.nonzero(cell_pixels)
1416                provenance_rows.append(
1417                    {
1418                        "image_name": image.image_name,
1419                        "frame": image.frame,
1420                        "curated_label": curated_label,
1421                        "bactoscoop_cell_id": cell.cell_id,
1422                        "centroid_x_px": float(columns.mean()),
1423                        "centroid_y_px": float(rows.mean()),
1424                        "area_px": int(cell_pixels.sum()),
1425                        "original_mask_path": os.path.join(
1426                            self.image_folder_path, "masks", f"{stem}_cp_masks.tif"
1427                        ),
1428                        "original_mask_labels": ";".join(map(str, source_labels)),
1429                        "curated_mask_path": output_path,
1430                    }
1431                )
1432
1433            tifffile.imwrite(output_path, curated_mask)
1434            mask_paths.append(output_path)
1435
1436        provenance = pd.DataFrame(provenance_rows)
1437        provenance_path = os.path.join(output_dir, "curated_mask_provenance.csv")
1438        provenance.to_csv(provenance_path, index=False)
1439        bactoscoop_logger.info(
1440            "Exported %s curated masks and %s curated cells to %s",
1441            len(mask_paths),
1442            len(provenance),
1443            output_dir,
1444        )
1445        return mask_paths, provenance
1446
1447    def merge_dataframes(self, include_metadata_tag=False, discard_morphological_nan=False):
1448        """
1449        Merge feature dataframes into a single dataframe.
1450    
1451        Merges multiple feature dataframes into a single dataframe, ensuring that columns are properly renamed
1452        to identify the channel and removes duplicates based on specific columns.
1453    
1454        Args:
1455            include_metadata_tag (bool): Whether to rename 'image_name', 'cell_id', and 'frame' to 'Metadata_*'.
1456            discard_nan (bool): Whether to discard rows with NaN in 'cell_area' and 'cell_length'.
1457    
1458        Returns:
1459            pd.DataFrame: The merged feature dataframe.
1460        """
1461        if not self.feature_dataframes:
1462            raise ValueError("No feature dataframes are available to merge.")
1463
1464        merged_dataframes = []
1465
1466        for key, df in self.feature_dataframes.items():
1467            # Keys are "method_channel_features"; channel names may contain underscores.
1468            if not key.endswith("_features"):
1469                raise ValueError(f"Invalid feature dataframe key: {key!r}")
1470            method_and_channel = key[: -len("_features")]
1471            method, separator, channel = method_and_channel.partition("_")
1472            if not separator or not method or not channel:
1473                raise ValueError(f"Invalid feature dataframe key: {key!r}")
1474
1475            # Set a prefix to identify the channel in column names if the channel is not None
1476            if channel != "None":
1477                df = df.rename(
1478                    columns={
1479                        col: f"{channel}_{col}"
1480                        for col in df.columns
1481                        if col not in ["image_name", "cell_id", "frame"]
1482                    }
1483                )
1484
1485            # Append the modified dataframe to the list
1486            merged_dataframes.append(df)
1487
1488        # Concatenate the dataframes vertically
1489        merged_data = pd.concat(merged_dataframes)
1490
1491        # Merge the dataframes based on 'image_name', 'cell_id', and 'frame'
1492        result = merged_data.pivot_table(
1493            index=["image_name", "cell_id", "frame"], aggfunc="first"
1494        ).reset_index()
1495
1496        # Discard rows with NaN in 'cell_area' and 'cell_length' if discard_nan is True
1497        if discard_morphological_nan:
1498            result = result.dropna(subset=["cell_area", "cell_length"])
1499
1500        if include_metadata_tag:
1501            # Rename 'image_name', 'cell_id', and 'frame' to 'Metadata_*'
1502            result = result.rename(
1503                columns={
1504                    "image_name": "Metadata_image_name",
1505                    "cell_id": "Metadata_cell_id",
1506                    "frame": "Metadata_frame"
1507                }
1508            )
1509
1510        # Reset the index to make it look like the final result
1511        self.merged_features = result.reset_index(drop=True)
1512
1513        return self.merged_features
1514
1515    def dataframe_to_pkl(self, pkl_name=None):
1516        """Save merged features in the image folder and return the pickle path.
1517
1518        A suffixless ``pkl_name`` is a legacy tag appended to the dataset name;
1519        a name ending in ``.pkl`` is used as the exact filename.
1520        """
1521        if self.merged_features is None:
1522            raise ValueError("Merge feature dataframes before saving them.")
1523        if pkl_name is None:
1524            filename = f"{self.name}_features.pkl"
1525        elif str(pkl_name).endswith(".pkl"):
1526            filename = str(pkl_name)
1527        else:
1528            filename = f"{self.name}_{pkl_name}.pkl"
1529        self._to_pickle(filename, self.merged_features)
1530        return os.path.join(self.image_folder_path, filename)
1531
1532    def meshdata_to_parquet(self, parquet_name=None):
1533        """Save the current mesh dataframe as reloadable Parquet in the image folder.
1534
1535        Geometry arrays become nested numeric lists in Parquet. Reload with
1536        ``batch_load_mesh("name.parquet", phase_channel=...)``.
1537        Requires the optional ``pyarrow`` package.
1538        """
1539        if self.mesh_df_collection is None or self.mesh_df_collection.empty:
1540            raise ValueError("No mesh data is available to save.")
1541        name = parquet_name or f"{self.name}_meshdata.parquet"
1542        self._to_parquet(name, self.mesh_df_collection, mesh_data=True)
1543
1544    def dataframe_to_parquet(self, parquet_name=None):
1545        """Save merged features as Parquet in the image folder (requires pyarrow)."""
1546        if self.merged_features is None:
1547            raise ValueError("Merge feature dataframes before saving them.")
1548        name = parquet_name or f"{self.name}_features.parquet"
1549        self._to_parquet(name, self.merged_features)
1550
1551    def _atomic_write(self, filename, writer):
1552        self._require_image_folder_path()
1553        if os.path.basename(filename) != filename or filename in {"", ".", ".."}:
1554            raise ValueError("Output filename must be a name within the image folder.")
1555        file_path = os.path.join(self.image_folder_path, filename)
1556        descriptor, temporary_path = tempfile.mkstemp(
1557            prefix=f".{filename}.", suffix=".tmp", dir=self.image_folder_path
1558        )
1559        os.close(descriptor)
1560        try:
1561            writer(temporary_path)
1562            with open(temporary_path, "rb+") as temporary_file:
1563                os.fsync(temporary_file.fileno())
1564            os.replace(temporary_path, file_path)
1565        finally:
1566            if os.path.exists(temporary_path):
1567                os.unlink(temporary_path)
1568
1569    def _to_parquet(self, filename, data, mesh_data=False):
1570        if not filename.lower().endswith(".parquet"):
1571            raise ValueError("Parquet filename must end in .parquet")
1572        output = data.copy()
1573        if mesh_data:
1574            for column in ("contour", "mesh", "midline"):
1575                if column not in output:
1576                    raise ValueError(f"Mesh dataframe is missing '{column}'.")
1577                output[column] = output[column].map(
1578                    lambda value: np.asarray(value).tolist()
1579                )
1580        self._atomic_write(
1581            filename,
1582            lambda path: output.to_parquet(
1583                path, engine="pyarrow", compression="zstd", index=False
1584            ),
1585        )
1586
1587    def _to_pickle(self, pkl_name, data):
1588        """
1589        Save data to a pkl file.
1590
1591        """
1592        self._atomic_write(
1593            pkl_name,
1594            lambda path: self._write_pickle_file(path, data),
1595        )
1596
1597    @staticmethod
1598    def _write_pickle_file(path, data):
1599        with open(path, "wb") as file:
1600            pickle.dump(data, file, protocol=pickle.HIGHEST_PROTOCOL)