Source code for cops.analysis

# analysis.py
#--------------------------------------
# mamba install opencv -c conda-forge
# or
# pip install opencv-contrib-python
#--------------------------------------
from __future__ import annotations
from typing import Callable
import logging
import os
import shutil
import copy
import json
import threading
import multiprocessing
import warnings
from configparser import ConfigParser
from datetime import datetime, timedelta, timezone

import cv2
import numpy as np
import pandas as pd
import xarray as xr
from netCDF4 import Dataset, date2num
from scipy import ndimage
from scipy.spatial import ConvexHull
from scipy.stats import binned_statistic, binned_statistic_2d
from skimage.segmentation import find_boundaries
from tqdm import tqdm # Import tqdm for the progress bar

from . import io
from .__version__ import __version__
from ._logging import configure_worker_logging, process_pool_logging
from .variables import IAT_MF_COMPONENT_SCORES, LEVEL_1_VARIABLES, LEVEL_2_VARIABLES
from .constants import (
    SA_METHODS, DIAMETER_CATEGORIES, PROBE_CATEGORIES,
    BAKER_LAWSON_COEFF, BAKER_LAWSON_EXP,
    DEFAULT_PRESSURE, DEFAULT_TEMPERATURE,
    REJECT_CODE_DOF_FAILURE, REJECT_CODE_NEGATIVE_IAT,
    REJECT_CODE_LOW_AREA_RATIO, REJECT_CODE_SHATTERING,
    REJECT_CODE_REACCEPTED, AREA_RATIO_MIN, ACCEPTED_CODES,
    SODA2_TINY_AREA_RATIO_THRESHOLD
)
from .config import (
    load_probe_config, ProbeProcessingConfig, ensure_probe_config,
    resolve_dof_constant, resolve_probe_config_name, SizeDistributionConfig
)
# Optional ML products (cops.ml): size correction (cops.ml.sizing, [ml_sizing]) and source
# category/phase classification (cops.ml.classification, [ml_classification]).  These
# imports load neither scikit-learn nor models; bundles are read only when a section
# enables them.  Model calls happen in three places below: _preflight_ml_groups (bundle
# and routing checks before any output is written), the Level-1 hook add_level1_ml_outputs,
# and the Level-1/Level-2 diameter and phase selection that consume the stored ML outputs.
from .ml.sizing.pipeline import preflight_ml_sizing, requested_ml_sizing_records
from .ml.combined import add_level1_ml_outputs
from .ml.classification.pipeline import (
    preflight_ml_classification,
    requested_ml_classification_records, has_ml_classification_provenance,
    check_existing_ml_classification, check_ml_classification_level2_inputs,
    check_cached_phase, selected_ml_phase, phase_record, phase_record_from_attrs,
    phase_attrs, ML_PHASE_METHODS, OUTPUTS_ATTR as ML_CLASSIFICATION_OUTPUTS_ATTR,
)
from .ml.routing import InstrumentIdentity
from .ml.metadata import canonical_ml_attributes, read_ml_attribute
from .ml.sizing.selection import (
    bulk_selection_record, check_cached_bulk, check_existing_level1, check_existing_level2,
    check_level2_inputs, check_persisted_selected_diameter, selected_ml_diameter, has_ml_provenance,
    ml_selection_key,
    provenance_attrs, resolve_particle_diameter_um,
)
from .ml.errors import StaleOutputError
from .ml.schema import SOURCE_MEANINGS

logger = logging.getLogger(__name__)

_TRANSIENT_LEVEL2_ATTRS = frozenset({'bin_edges', 'bin_width'})
_DMT_COUNTER_PROBE_TYPES = frozenset((5, 6, 7, 8))
_PMS_BUFFER_GAP_PROBE_TYPES = frozenset((9,))

# ==============================================================================
# MARK: SECTION 1: PARTICLE IMAGE GEOMETRY & MORPHOLOGY
# ==============================================================================
# region SECTION 1: PARTICLE IMAGE GEOMETRY & MORPHOLOGY
# Core 2D geometric measurements for OAP particle images, from bounding shapes
# through perimeter and morphology descriptors.
# Functions: min_enclosing_circle, max_interior_circle, get_circle_diameters,
#            min_enclosing_rotated_rectangle, min_volume_ellipse, min_enclosing_ellipse,
#            fit_ellipse, particle_perimeter, calculate_particle_morphology
# ==============================================================================

[docs] def min_enclosing_circle(image_buffer: xr.DataArray | np.ndarray, particle_mask: int = 0, tas_ratio: float = 1.0) -> tuple[float, float, float]: """ Computes the minimum enclosing circle around a specified particle or shape within an image buffer, considering the TAS ratio. This function identifies all pixels matching a specific value (`particle_mask`), representing a particle or shape within the image, and calculates the smallest circle that can completely enclose these pixels. Parameters: ----------- - image_buffer (xarray.DataArray or numpy.ndarray): A 2D array representing the image from which the shape's minimum enclosing circle is to be calculated. Typically, this would be a binary image where the shapes of interest are marked by a specific pixel value. If an xarray DataArray is provided, it is explicitly transposed to ('slice', 'diode') order. - particle_mask (int, optional): The pixel value that represents the particle or shape within the image buffer. Pixels with this value will be considered as part of the shape. Defaults to 0, which is commonly used for binary images. - tas_ratio (float, optional): The True Air Speed ratio between the probe and the air, which affects the scale of the slice (time/along-track) coordinates. Defaults to 1.0. Returns: -------- - center_x (float): The x-coordinate of the center of the minimum enclosing circle (slice index). - center_y (float): The y-coordinate of the center of the minimum enclosing circle (diode index). - radius (float): The radius of the minimum enclosing circle. Note: ----- - `np.where` produces points in (row, col) = (slice, diode) order. OpenCV's `cv2.minEnclosingCircle` treats points[:, 0] as the x direction and points[:, 1] as the y direction. Therefore, `center_x` corresponds to the slice dimension and `center_y` corresponds to the diode dimension. - `tas_ratio` is correctly applied to `points[:, 0]` (the slice/time dimension). History: -------- - 2024-02-26: Yongjie Huang (huangynj@gmail.com), first created. - 2024-04-17: Yongjie Huang, added support for TAS ratio. - 2026-06-24: Clarified axis definitions for slice (center_x) and diode (center_y). Added xarray transpose support. """ if isinstance(image_buffer, xr.DataArray): # Ensure dimensions are strictly in ('slice', 'diode') order before extracting values image_data = image_buffer.transpose('slice', 'diode').values else: image_data = image_buffer # Find the coordinates of all pixels that are particle_mask (the irregular shape) # Note: np.where returns (row, col) which corresponds to (slice, diode). points = np.column_stack(np.where(image_data == particle_mask)) if points.size == 0: logger.warning("No points found matching the particle mask") return 0, 0, 0 # Convert points to the correct format for minEnclosingCircle points = points.astype(np.float32) # Adjust slice (time) coordinates according to the TAS ratio. # points[:, 0] represents the slice index, which is the dimension affected by airspeed. points[:, 0] /= tas_ratio # Compute the minimum enclosing circle for the points. # OpenCV treats points[:, 0] (slice) as x and points[:, 1] (diode) as y. (center_x, center_y), radius = cv2.minEnclosingCircle(points) return center_x, center_y, radius
[docs] def max_interior_circle(image_buffer: xr.DataArray | np.ndarray, particle_mask: int = 0, tas_ratio: float = 1.0) -> tuple[float, float, float]: """ Computes the maximum interior circle (largest circle fitting in the hollow opening) of a non-closed particle shape like a crescent or arc. For particles with an open shape (like a crescent, horseshoe, or arc), this function finds the largest circle that fits in the interior/hollow region bounded by the particle. This is the circle that would touch the inner edge of the arc. Parameters: ----------- - image_buffer (xarray.DataArray or numpy.ndarray): A 2D array representing the image from which the interior circle is to be calculated. Typically, this would be a binary image where the shapes of interest are marked by a specific pixel value. If an xarray DataArray is provided, it is explicitly transposed to ('slice', 'diode') order. - particle_mask (int, optional): The pixel value that represents the particle or shape within the image buffer. Pixels with this value will be considered as part of the shape. Defaults to 0, which is commonly used for binary images. - tas_ratio (float, optional): The True Air Speed ratio between the probe and the air, which affects the scale of the x-coordinates (slice direction). A tas_ratio > 1 means the particle is stretched in the slice direction, < 1 means compressed. Defaults to 1.0. Returns: -------- - center_x (float): The x-coordinate of the center of the interior circle (slice index). - center_y (float): The y-coordinate of the center of the interior circle (diode index). - radius (float): The radius of the interior circle in pixels (in the original image scale). Note: ----- - The function works by: 1. Scaling the image by TAS ratio to correct for airspeed effects 2. Finding the convex hull of the particle to identify the "enclosed" interior region 3. Identifying the interior region (inside convex hull but not particle) 4. Applying distance transform to find the largest circle in that interior region 5. Converting results back to original image coordinates - For non-closed particles (e.g., crescent or arc shapes), this finds the largest circle that fits in the opening/hollow area bounded by the particle's inner curve. - If the particle is solid (no interior hole), returns (0, 0, 0). History: -------- - 2026-01-13: Yongjie Huang (huangynj@gmail.com), first created. - 2026-01-13: Added TAS ratio support. - 2026-06-26: Added xarray DataArray support and explicit transpose to ('slice', 'diode') order. """ if isinstance(image_buffer, xr.DataArray): # Ensure dimensions are strictly in ('slice', 'diode') order before extracting values image_data = image_buffer.transpose('slice', 'diode').values else: image_data = image_buffer # Create binary image where particle = 255 (white), background = 0 particle_binary = np.where(image_data == particle_mask, 255, 0).astype(np.uint8) # Check if there are any particle pixels if np.sum(particle_binary) == 0: logger.warning("No points found matching the particle mask") return 0.0, 0.0, 0.0 # Apply TAS ratio by resizing the image if needed # TAS ratio affects the slice (x/row) direction original_shape = particle_binary.shape if tas_ratio != 1.0 and tas_ratio > 0: # Scale the height (slice direction) by 1/tas_ratio to correct for airspeed new_height = int(original_shape[0] / tas_ratio) if new_height > 0: particle_binary_scaled = cv2.resize( particle_binary, (original_shape[1], new_height), # (width, height) interpolation=cv2.INTER_NEAREST ) else: particle_binary_scaled = particle_binary else: particle_binary_scaled = particle_binary # Find contours of the particle contours, _ = cv2.findContours(particle_binary_scaled, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) if len(contours) == 0: logger.warning("No contours found") return 0.0, 0.0, 0.0 # Combine all contours to get all particle points all_points = np.vstack(contours).squeeze() if all_points.ndim == 1: all_points = all_points.reshape(-1, 2) # Compute convex hull of the particle hull = cv2.convexHull(all_points) # Create a filled convex hull mask hull_mask = np.zeros_like(particle_binary_scaled) cv2.fillPoly(hull_mask, [hull], 255) # The interior region is: inside convex hull but NOT part of the particle # This is where we want to find the largest inscribed circle interior_region = cv2.bitwise_and(hull_mask, cv2.bitwise_not(particle_binary_scaled)) # Check if there's any interior region if np.sum(interior_region) == 0: # No interior region - particle might be solid return 0.0, 0.0, 0.0 # Apply distance transform to the interior region # This finds the distance from each interior pixel to the nearest non-interior pixel dist_transform = cv2.distanceTransform(interior_region, cv2.DIST_L2, cv2.DIST_MASK_PRECISE) # Find the location of maximum distance (center of interior circle) radius_scaled = np.max(dist_transform) if radius_scaled == 0: return 0.0, 0.0, 0.0 # Find the coordinates of the maximum value (in scaled image) max_loc = np.where(dist_transform == radius_scaled) # If there are multiple maximum locations, take the first one center_x_scaled = float(max_loc[0][0]) # slice index (row) center_y = float(max_loc[1][0]) # diode index (column) - not affected by TAS # Convert back to original image coordinates if tas_ratio != 1.0 and tas_ratio > 0: center_x = center_x_scaled * tas_ratio # For a true circle in scaled space, the radius in original space depends on direction # We return the radius as measured in the corrected (scaled) space radius = float(radius_scaled) else: center_x = center_x_scaled radius = float(radius_scaled) return center_x, center_y, radius
[docs] def get_circle_diameters(image_buffer: xr.DataArray | np.ndarray, particle_mask: int = 0, tas_ratio: float = 1.0) -> dict: """ Computes both inner interior and outer enclosing circle diameters for a particle. This is a convenience function that calculates both the maximum interior circle (largest circle that fits in the hollow opening of the particle) and the minimum enclosing circle (smallest circle that completely contains the particle). Parameters: ----------- - image_buffer (xarray.DataArray or numpy.ndarray): A 2D array representing the image from which the circle diameters are to be calculated. Typically, this would be a binary image where the shapes of interest are marked by a specific pixel value. If an xarray DataArray is provided, it is explicitly transposed to ('slice', 'diode') order in the underlying circle functions. - particle_mask (int, optional): The pixel value that represents the particle or shape within the image buffer. Defaults to 0. - tas_ratio (float, optional): The True Air Speed ratio. Defaults to 1.0. Returns: -------- - dict: A dictionary containing: - 'inner_diameter' (float): Diameter of the max interior circle (in the hollow opening) - 'outer_diameter' (float): Diameter of the minimum enclosing circle (in pixels) - 'inner_center' (tuple): (x, y) center coordinates of interior circle - 'outer_center' (tuple): (x, y) center coordinates of enclosing circle - 'inner_radius' (float): Radius of the maximum interior circle - 'outer_radius' (float): Radius of the minimum enclosing circle - 'diameter_ratio' (float): inner/outer diameter ratio (0-1) Note: ----- - For non-closed particles (e.g., crescent or horseshoe shapes), the inner circle represents the largest circle fitting in the hollow interior region bounded by the particle's inner curve. - If the particle is solid (no interior hole), inner_diameter will be 0. History: -------- - 2026-01-13: Yongjie Huang (huangynj@gmail.com), first created. - 2026-06-26: Added xarray DataArray support. """ # Compute maximum interior circle (inner - in the hollow opening) inner_cx, inner_cy, inner_radius = max_interior_circle( image_buffer, particle_mask=particle_mask, tas_ratio=tas_ratio ) # Compute minimum enclosing circle (outer) outer_cx, outer_cy, outer_radius = min_enclosing_circle( image_buffer, particle_mask=particle_mask, tas_ratio=tas_ratio ) # Calculate diameters inner_diameter = 2.0 * inner_radius + 1 if inner_radius > 0 else 0.0 # add 1 for the boundary outer_diameter = 2.0 * outer_radius + 1 if outer_radius > 0 else 0.0 # add 1 for the boundary # Calculate diameter ratio (circularity measure) if outer_diameter > 0: diameter_ratio = inner_diameter / outer_diameter else: diameter_ratio = 0.0 return { 'inner_diameter': inner_diameter, 'outer_diameter': outer_diameter, 'inner_center': (inner_cx, inner_cy), 'outer_center': (outer_cx, outer_cy), 'inner_radius': inner_radius, 'outer_radius': outer_radius, 'diameter_ratio': diameter_ratio }
[docs] def min_enclosing_rotated_rectangle(image_buffer: xr.DataArray | np.ndarray, particle_mask: int = 0) -> tuple[tuple[float, float], tuple[float, float], float]: """ Computes the minimum area enclosing rotated rectangle for a specified particle or shape within an image buffer. This function finds all pixels matching a specific value (`particle_mask`), representing a particle or shape within the image, and calculates the smallest rotated rectangle that can completely enclose these pixels. Parameters: ----------- - image_buffer (xarray.DataArray or numpy.ndarray): A 2D array representing the image from which the shape's minimum area enclosing rotated rectangle is to be calculated. Typically, this would be a binary image where the shapes of interest are marked by a specific pixel value. If an xarray DataArray is provided, it is explicitly transposed to ('slice', 'diode') order. - particle_mask (int, optional): The pixel value that represents the particle or shape within the image buffer. Pixels with this value are considered as part of the shape. Defaults to 0, commonly used in binary images for representing the foreground. Returns: -------- - rect (tuple): A tuple containing: - The center coordinates (x, y) of the rectangle. - The dimensions (width, height) of the rectangle. - The angle of rotation of the rectangle in degrees. The angle is measured from the X-axis in a clockwise direction (following OpenCV's convention). Note: ----- - The function utilizes OpenCV's `cv2.minAreaRect` method, which requires the points to be in a specific format (np.float32). Hence, the conversion of points before computation. - The returned rotation angle can be used to understand the orientation of the shape within the image, which is particularly valuable for analyzing objects with directional properties. History: -------- - 2024-02-26: Created by Yongjie Huang (huangynj@gmail.com) - 2026-06-26: Added xarray DataArray support and explicit transpose to ('slice', 'diode') order. """ if isinstance(image_buffer, xr.DataArray): image_data = image_buffer.transpose('slice', 'diode').values else: image_data = image_buffer # Find the coordinates of all pixels that are particle_mask (the irregular shape) points = np.column_stack(np.where(image_data == particle_mask)) # Convert points to the correct format for minAreaRect points = points.astype(np.float32) # Compute the minimum enclosing Rotated Rectangle for the points rect = cv2.minAreaRect(points) # return center (x,y), (width, height), angle of rotation (rect_cen_x, rect_cen_y), (rect_width, rect_height), rect_rotation_angle_deg = rect # TODO # # Normalize so that width is always the major axis # # And convert angle from Transposed (Row-based) to Standard (Col-based) # # Transposed Angle 0 means aligned with Row (Vertical). # # Standard Angle 0 means aligned with Col (Horizontal). # # Conversion: angle_std = 90 - angle_transposed # rect_rotation_angle_deg = 90.0 - rect_rotation_angle_deg # if rect_width < rect_height: # rect_width, rect_height = rect_height, rect_width # rect_rotation_angle_deg += 90.0 # # Normalize angle to [0, 180) # rect_rotation_angle_deg = rect_rotation_angle_deg % 180.0 # rect = ((rect_cen_x, rect_cen_y), (rect_width, rect_height), rect_rotation_angle_deg) # # box = np.intp(cv2.boxPoints(rect)) return rect
[docs] def min_volume_ellipse(P: np.ndarray, tolerance: float = 0.01, use_convex_hull: bool = True) -> tuple[np.ndarray, np.ndarray]: """ Finds the minimum volume enclosing ellipsoid (MVEE) of a set of data points stored in matrix P. The following optimization problem is solved: minimize log(det(A)) subject to (P_i - c)' * A * (P_i - c) <= 1 in variables A and c, where P_i is the i-th column of the matrix P. The solver is based on Khachiyan Algorithm, and the final solution is different from the optimal value by the pre-specified amount of 'tolerance'. Parameters: ----------- - P : numpy.ndarray A (d x N) dimensional matrix containing N points in R^d, where 'd' is the dimensionality of each point and 'N' is the number of points. - tolerance : float Error in the solution with respect to the optimal value. - use_convex_hull : bool If True, computes the convex hull of the points first to reduce the number of points. This significantly improves performance for large datasets. Returns: -------- - A : numpy.ndarray A (d x d) matrix of the ellipse equation in the 'center form': (x-c)' * A * (x-c) = 1. - c : numpy.ndarray A 'd' dimensional vector representing the center of the ellipse. Example Usage: -------------- .. code-block:: python import numpy as np P = np.random.rand(5, 100) # 5 dimensions, 100 points A, c = min_volume_ellipse(P, tolerance=0.01) print("A:", A) print("c:", c) # To reduce the computation time, work with the boundary points only: from scipy.spatial import ConvexHull hull = ConvexHull(P.T) # Compute the convex hull of the points K = np.unique(hull.vertices) # Get the unique indices of the hull vertices Q = P[:, K] # Select points that are vertices of the convex hull (A, c) = min_volume_ellipse(Q, tolerance=0.01) print("A:", A) print("c:", c) Reference: ---------- Nima Moshtagh (2024). Minimum Volume Enclosing Ellipsoid (https://www.mathworks.com/matlabcentral/fileexchange/9542-minimum-volume-enclosing-ellipsoid), MATLAB Central File Exchange. Retrieved February 26, 2024. History: -------- - 2024-02-26: Created by Yongjie Huang (huangynj@gmail.com) """ # Optional: Use Convex Hull to reduce points if use_convex_hull and P.shape[1] > P.shape[0] + 1: try: hull = ConvexHull(P.T) K = np.unique(hull.vertices) P = P[:, K] except Exception: # Fallback if ConvexHull fails (e.g., points are collinear or insufficient) pass (d, N) = np.shape(P) Q = np.vstack([P, np.ones(N)]) # Add a row of ones for affine transformation u = np.ones(N) / N # 1st iteration err = 1 + tolerance # Khachiyan Algorithm # ----------------------------------- while err > tolerance: X = Q @ np.diag(u) @ Q.T # X = \sum_i ( u_i * q_i * q_i') is a (d+1)x(d+1) matrix try: M = np.diag(Q.T @ np.linalg.inv(X) @ Q) # M the diagonal vector of an NxN matrix except np.linalg.LinAlgError: # Handle singular matrix case break j = np.argmax(M) maximum = M[j] step_size = (maximum - d - 1) / ((d + 1) * (maximum - 1)) new_u = (1 - step_size) * u new_u[j] += step_size err = np.linalg.norm(new_u - u) u = new_u # Computing the Ellipse parameters # ----------------------------------- # Finds the ellipse equation in the 'center form': # (x-c)' * A * (x-c) = 1 # It computes a dxd matrix 'A' and a d dimensional vector 'c' as the center # of the ellipse. U = np.diag(u) c = P @ u try: A = (1 / d) * np.linalg.inv(P @ U @ P.T - np.outer(c, c)) except np.linalg.LinAlgError: A = np.eye(d) # Fallback to identity matrix return A, c
[docs] def min_enclosing_ellipse(image_buffer: xr.DataArray | np.ndarray, particle_mask: int = 0, tolerance: float = 0.01) -> tuple[tuple[float, float], tuple[float, float], float]: """ Calculates the minimum enclosing ellipse for pixels matching a specific mask in an image. This function identifies pixels within `image_buffer` that match `particle_mask` and computes the minimum volume enclosing ellipse (MVEE) that encompasses these points. The algorithm employs the Khachiyan Algorithm by solving an optimization problem to find the ellipse that completely surrounds these pixels. Parameters: ----------- - image_buffer (xarray.DataArray or numpy.ndarray): A 2D array representing the image from which the shape's minimum enclosing ellipse is to be calculated. This is typically a binary image where the shapes of interest are distinguished by a specific pixel value. If an xarray DataArray is provided, it is explicitly transposed to ('slice', 'diode') order. - particle_mask (int, optional): The pixel value that represents the particle or shape within the image buffer. Pixels with this value are considered part of the shape. Defaults to 0, which is commonly used in binary images to represent foreground objects. - tolerance (float, optional): The tolerance for the optimization process in calculating the MVEE. Lower values result in more accurate ellipses but may require more computation. Default is 0.01. Returns: -------- - ellipse (tuple): A tuple containing the following elements: - The center of the ellipse (center_x, center_y) as floating-point values. - The size of the ellipse (width, height), where width is the major axis and height is the minor axis, also as floating-point values. The dimensions are in pixels. - The rotation angle of the ellipse in degrees, indicating the orientation of the major axis with respect to the image horizontal. Note: ----- - The function `min_volume_ellipse` used within needs to be defined in the script or imported from a module where it's implemented. This function should accept points in a (2 x N) NumPy array format and a tolerance level, then return the matrix `A` and center `c` describing the MVEE in center-form. - The function's output, particularly the orientation and dimensions of the ellipse, can be used for detailed analysis of particle shapes, including aspect ratio calculations and orientation measurements. History: -------- - 2024-02-26: Created by Yongjie Huang (huangynj@gmail.com) - 2026-06-26: Added xarray DataArray support and explicit transpose to ('slice', 'diode') order. """ if isinstance(image_buffer, xr.DataArray): image_data = image_buffer.transpose('slice', 'diode').values else: image_data = image_buffer # Extract coordinates of pixels that match the particle_mask # points = np.column_stack(np.where(image_data == particle_mask)).transpose() # 2 x N dimensions # or points = np.vstack(np.where(image_data == particle_mask)) # Calculate the minimum volume enclosing ellipse for the extracted points try: A, c = min_volume_ellipse(points, tolerance=tolerance) except Exception as e: logger.warning("Could not calculate the minimum enclosing ellipse: %s", e) return (0,0), (0, 0), 0 # Compute ellipse parameters from the resulting 'A' matrix vals, vecs = np.linalg.eigh(A) # Eigenvalue decomposition to find orientation and axes lengths order = vals.argsort()[::-1] # Ensure eigenvalues are in descending order for proper axes lengths vals, vecs = vals[order], vecs[:, order] angle_deg = np.degrees(np.arctan2(*vecs[:, 0][::-1])) # Calculate orientation angle in degrees width, height = 2 / np.sqrt(vals) # Calculate axes lengths from eigenvalues # Determine the center of the ellipse center_x, center_y = c # Package the ellipse parameters into a single tuple for return ellipse = (center_x, center_y), (width, height), angle_deg return ellipse
[docs] def fit_ellipse(image_buffer: xr.DataArray | np.ndarray, particle_mask: int = 0, method: str = None) -> tuple[tuple[float, float], tuple[float, float], float]: """ Computes the best fitting ellipse for a specified particle or shape within an image buffer. This function identifies all pixels matching a specific value (`particle_mask`), representing a particle or shape within the image, and calculates the best fitting ellipse for these pixels using the specified method. It leverages OpenCV's ellipse fitting algorithms: `cv2.fitEllipse`, `cv2.fitEllipseAMS`, or `cv2.fitEllipseDirect`. Parameters: ----------- - image_buffer (xarray.DataArray or numpy.ndarray): A 2D array representing the image from which the shape's fitting ellipse is to be calculated. This is typically a binary or grayscale image where the shapes of interest are distinguished by a specific pixel value. If an xarray DataArray is provided, it is explicitly transposed to ('slice', 'diode') order. - particle_mask (int, optional): The pixel value that represents the particle or shape within the image buffer. Pixels with this value are considered part of the shape. Defaults to 0, which is commonly used in binary images to represent foreground objects. - method (str, optional): The method used to fit the ellipse: - None (default): Uses the standard `cv2.fitEllipse` method. - 'AMS': Uses the `cv2.fitEllipseAMS` method. - 'Direct': Uses the `cv2.fitEllipseDirect` method. Returns: -------- - ellipse (tuple): A tuple containing the following elements: - (center_x, center_y): The center of the ellipse as a tuple of floating-point values. - (width, height): The size of the ellipse where width is the major axis and height is the minor axis, represented as floating-point values in pixels. - angle_deg: The rotation angle of the ellipse in degrees, indicating the orientation of the major axis with respect to the image horizontal. The angle is measured in a clockwise direction following OpenCV's convention. Note: ----- - The function relies on OpenCV's `cv2.fitEllipse`, `cv2.fitEllipseAMS`, and `cv2.fitEllipseDirect` method, which requires at least five points to fit an ellipse. If fewer than five points are found matching `particle_mask`, this function logs a warning and returns ((0, 0), (0, 0), 0). - The accuracy and applicability of the fitting method may vary based on the shape and distribution of the points. - The function's output, particularly the orientation and dimensions of the ellipse, can be used for detailed analysis of particle shapes, including aspect ratio calculations and orientation measurements. History: -------- - 2024-02-26: Created by Yongjie Huang (huangynj@gmail.com) - 2026-06-26: Added xarray DataArray support and explicit transpose to ('slice', 'diode') order. """ if isinstance(image_buffer, xr.DataArray): image_data = image_buffer.transpose('slice', 'diode').values else: image_data = image_buffer # Find the coordinates of all pixels that are particle_mask (the irregular shape) points = np.column_stack(np.where(image_data == particle_mask)) # Convert points to the correct format for fitEllipse points = points.astype(np.float32) # Ensure there are enough points for fitting an ellipse if points.shape[0] < 5: # raise ValueError("Insufficient points to fit an ellipse. At least five points are required.") logger.warning( "Insufficient points to fit an ellipse; at least five are required. Returning zeros" ) return (0,0), (0, 0), 0 # Fit the ellipse using the chosen method if method=='AMS': ellipse = cv2.fitEllipseAMS(points) elif method=='Direct': ellipse = cv2.fitEllipseDirect(points) else: ellipse = cv2.fitEllipse(points) (center_x, center_y), (width, height), angle_deg = ellipse # print(ellipse) return ellipse
[docs] def particle_perimeter(image_buffer: xr.DataArray, particle_mask: int = 0, boundary: str = 'all', method: str = 'morphology') -> int: """ Calculate the perimeter of a particle in an image buffer by checking each pixel to determine if it's an edge pixel of the particle. This function pads the image to handle particles at the boundaries of the image, ensuring an accurate perimeter calculation even for particles that touch the image edges. Parameters: ----------- - image_buffer (xarray.DataArray): A 2D DataArray representing the image from which the particle's perimeter is to be calculated. It expects the particle to be identified by a specific pixel value given by 'particle_mask'. - particle_mask (int): The pixel value that represents the particle. Pixels with this value are considered part of the particle. Defaults to 0. - boundary (str): Specifies whether to consider 'all' boundaries or just the 'outer' boundary of the particle. Defaults to 'all'. - method (str): The method to use for calculating the perimeter, can be 'loop', 'morphology', or 'skimage'. Note: 'loop' is significantly slower and is kept for legacy/educational purposes. Returns: -------- - perimeter (int): The perimeter of the particle in pixels, calculated as the count of particle pixels that have at least one non-particle neighbor. Notes: ------ - The function pads the 'slice' and 'diode' dimensions by 1 with a value different from the particle_mask to ensure that edge pixels of particles touching the image boundary are correctly identified as edge pixels. This is critical for particles that are not completely enclosed within the field of view of the image. History: -------- - 2024-04-24: Yongjie Huang (huangynj@gmail.com), first implemented. """ # Pad the image to prevent issues with particles that touch the boundary of the image # The padding value is set to particle_mask + 1 to clearly differentiate it from the particle pixels image_buffer_padded = image_buffer.pad(slice=(1, 1), diode=(1, 1), constant_values=particle_mask + 1) # Set particle pixels to 1 and backgroud to 0 #image_buffer_padded = (image_buffer_padded == particle_mask).astype(image_buffer.dtype) # or image_buffer_padded = xr.where(image_buffer_padded == particle_mask, 1, 0) # Access the numpy array from the padded DataArray for processing padded_image = image_buffer_padded.values if boundary == 'outer': # Fill internal holes to only consider the outer perimeter padded_image = ndimage.binary_fill_holes(padded_image).astype(int) # Calculate particle edge perimeter based on the specified method if method == 'loop': # Initialize perimeter count perimeter = 0 # Iterate through the image excluding the padded border to calculate perimeter for i in range(1, padded_image.shape[0] - 1): for j in range(1, padded_image.shape[1] - 1): # Check if the current pixel is part of the particle if padded_image[i, j] == 1: # Check the neighboring pixels to see if it's an edge pixel if (padded_image[i - 1, j] != 1 or padded_image[i + 1, j] != 1 or padded_image[i, j - 1] != 1 or padded_image[i, j + 1] != 1): perimeter += 1 elif method == 'morphology': # Edge detection using a morphological operation # Erosion: In a binary image, a pixel is set to 0 if any of the neighboring pixels have the value 0. # Here boundaries will be set to 0 eroded_image = ndimage.binary_erosion(padded_image).astype(int) boundaries = padded_image - eroded_image perimeter = np.sum(boundaries) elif method == 'skimage': # Find boundaries using function skimage.segmentation.find_boundaries boundaries = find_boundaries(padded_image, mode='inner', background=0).astype(int) perimeter = np.sum(boundaries) else: error_message = "'method' should be set to one of ('loop', 'morphology', 'skimage'), got '{}'".format(method) # print(error_message) raise ValueError(error_message) # Raise a ValueError with a specific message return perimeter
# from skimage.measure import find_contours # Deprecated: we use cv2.findContours instead. def _find_particle_contours(image_buffer, particle_mask=0): """Return padded particle contours and hierarchy in OpenCV coordinates.""" image_data = image_buffer.values if hasattr(image_buffer, 'values') else image_buffer # Convert the selected particle value to a binary uint8 image before # contour detection. This is equivalent to the previous logical inversion # for particle_mask=0, while also supporting arbitrary particle-mask values. # OpenCV findContours accepts only CV_8UC1 or CV_32SC1 input; passing the # original int64/float64 image would raise OpenCV error -210. # # Pad both the slice and diode dimensions by one background pixel. The # padding closes contours for particles touching an image boundary and # prevents the outer image boundary from being interpreted as a particle. particle_image = np.pad( (np.asarray(image_data) == particle_mask).astype(np.uint8), pad_width=1, mode='constant', constant_values=0, ) # Transpose from (slice, diode) to OpenCV image coordinates so contour x # corresponds to slice and contour y corresponds to diode. RETR_TREE keeps # the parent-child hierarchy required to distinguish particles from holes; # CHAIN_APPROX_NONE retains every boundary pixel for perimeter/hole metrics. return cv2.findContours( particle_image.transpose(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE, )
[docs] def calculate_particle_morphology(image_buffer: xr.DataArray, n_slices: int, diode_num: int, particle_mask: int = 0, print_result: bool = False, plot: bool = False, _contour_data=None) -> tuple[int, int, int, int, float, int, float, float, float]: """ Calculates statistical and geometric properties of a particle based on its image representation. This function extracts the coordinates of pixels corresponding to a particle, computes the minimum and maximum extents, area, slope, correlation, angle, lengths along principal axes, perimeter, fine detail coefficient, and the ratio of fully illuminated slices to partially illuminated slices. Parameters: ----------- - image_buffer (xarray.DataArray): A 2D array representing the particle image, where particle pixels are marked with a specific value (particle_mask). - n_slices (int): The number of slices in the image buffer. - diode_num (int): The number of diodes in the image buffer. - particle_mask (int, optional): The pixel value that identifies the particle within the image buffer. Defaults to 0. - print_result (bool, optional): If True, prints the calculated statistical and geometric properties to the console. Defaults to False. - plot (bool, optional): If True, generates a plot illustrating the particle, the fit line, and the particle's contour. Defaults to False. Returns: -------- - x_length (int): The particle's length along the x-axis. - y_length (int): The particle's length along the y-axis. - d_length (int): The length of the particle projected onto the fit line. - w_width (int): The width of the particle perpendicular to the fit line. - angle_deg (float): The angle of orientation of the particle in degrees. - area (int): The area covered by the particle pixels in the image. - r2_correlation (float): The squared correlation coefficient of the fit line. - F_fine_detail (float): A fine detail coefficient calculated as the product of the perimeter and d_length divided by the area. - S_ratio (float): The ratio of fully illuminated slices to partially illuminated slices. Note: ----- - The angle calculation ensures that the resulting angle is between 0 and 180 degrees. - The perimeter is computed based on the contours found in the transposed image buffer, which may affect the orientation of the plotted contours if the image is displayed. - The function optionally visualizes the particle points, the linear fit, and the particle contour if plotting is enabled. This requires matplotlib to be imported and available in the environment. History: -------- - 2024-02-27: Created by Yongjie Huang (huangynj@gmail.com) - 2026-06-26: Renamed from calc_stat to calculate_particle_morphology. """ # Step 1: Extract particle coordinates x_coords, y_coords = np.where(image_buffer.values == particle_mask) if len(x_coords) == 0: return 0, 0, 0, 0, 0.0, 0, 0.0, 0.0, 0.0 x_length = x_coords.max() - x_coords.min() + 1 y_length = y_coords.max() - y_coords.min() + 1 area = np.sum(image_buffer.values == particle_mask) # Step 2: Perform a least-squares fit # X = x_coords.reshape(-1, 1) # y = y_coords # model = LinearRegression().fit(X, y) # slope = model.coef_[0] # intercept = model.intercept_ # print(intercept) # print(np.polyfit(x_coords, y_coords, 1)) # Set NumPy to raise exceptions on numerical issues for debugging # np.seterr(divide='raise', invalid='raise') try: # Check if the variance of x_coords is zero to avoid warning, Yongjie Huang, 2024-04-17. if np.var(x_coords) == 0: # Single-slice particle (perfectly vertical line) slope, intercept = np.nan, np.mean(y_coords) r2_correlation = 1.0 angle_rad = np.pi / 2.0 angle_deg = 90.0 d_length = float(y_length) w_width = float(x_length) else: # Fit a polynomial of degree 1 (linear fit) slope, intercept = np.polyfit(x_coords, y_coords, 1) # Check if the variance of y_coords is zero to avoid warning, Yongjie Huang, 2024-04-17. if np.var(y_coords) == 0: r2_correlation = 1.0 if np.allclose(y_coords, np.polyval([slope, intercept], x_coords)) else np.nan else: # Calculate correlation coefficient and then R^2 r2_correlation = (np.corrcoef(x_coords, y_coords)[0, 1])**2 # Step 3: Calculate the angle # Calculate angle in radians. atan2 does not require division by zero handling. angle_rad = np.arctan2(slope, 1) # The second argument is "1" because we're considering the unit step in x angle_deg = np.degrees(angle_rad) if angle_deg < 0: # Ensure the angle is between 0 and 180 degrees angle_deg = angle_deg + 180.0 angle_rad = angle_rad + np.pi # Step 4: Project particle pixel to the fit line to calculate d and w x_new = x_coords * np.cos(angle_rad) + y_coords * np.sin(angle_rad) y_new = y_coords * np.cos(angle_rad) - x_coords * np.sin(angle_rad) d_length = x_new.max() - x_new.min() + 1 w_width = y_new.max() - y_new.min() + 1 except Exception as e: logger.exception("Particle morphology calculation failed: %s", e) logger.error( "Shadowed pixels=%s, variance(x)=%s, variance(y)=%s", area, np.var(x_coords), np.var(y_coords), ) # Note: Swallowing exceptions here and setting r2_correlation = 0 causes holroyd habit # classification to fall through r2 >= 0.4 and angle checks, classifying malformed or # numerically failed particles via F_fine_detail/S_ratio branches (e.g., 'g', 'a', 's'). slope, intercept, r2_correlation = 0, 0, 0 angle_rad, angle_deg = 0.0, 0.0 d_length, w_width = float(x_length), float(y_length) # Step 5: Calculate perimeter and F_fine_detail # Deprecated: contours = find_contours(image_buffer.values.transpose(), level=0.5) # Here use cv2.findContours, which returns more information about the image topology if _contour_data is None: contours, hierarchy = _find_particle_contours(image_buffer, particle_mask) else: contours, hierarchy = _contour_data perimeter = sum([cv2.arcLength(cnt.astype(np.float32), True) for cnt in contours]) F_fine_detail = perimeter * d_length/area # Calculate S ratio count_each_slice = np.sum(image_buffer.values == particle_mask, axis=1) # count of each slice partial_on_count = np.sum(count_each_slice > 0) fully_on_count = np.sum(count_each_slice == diode_num) if partial_on_count!=0: S_ratio = fully_on_count/partial_on_count else: S_ratio = 0.0 if print_result: print("x_length:", x_length) print("y_length:", y_length) print("d_length:", d_length) print("w_width:", w_width) print("area:", area) print("Slope:", slope) print("r2_correlation", r2_correlation) print("Angle (radians):", angle_rad) print("Angle (degrees):", angle_deg) print("Perimeter:", perimeter) print("F_fine_detail:", F_fine_detail) print("S_ratio:", S_ratio) #------------- Visualization (optional) ------------- if plot: import matplotlib.pyplot as plt if np.var(x_coords) == 0: x_fit = np.full(1000, x_coords[0]) y_fit = np.linspace(0, diode_num, 1000) else: x_fit = np.linspace(0, n_slices, 1000) y_fit = slope * x_fit + intercept #plt.imshow(image, cmap='gray') plt.plot(x_fit, y_fit, color='red') # Fit line plt.scatter(x_coords, y_coords, s=10, color='blue', marker='s', label='Particle points') # Particle points # Plot contours from cv2.findContours for i in range(len(contours)): contour = contours[i][:, 0, :] # Close the contour by appending the first point at the end if it's not already closed if not np.array_equal(contour[0], contour[-1]): contour = np.vstack((contour, contour[0])) # Adjust for the padding contour = contour - 1 # minus 1 here due to the pad of 1 to the original image if hierarchy[0, i, 3] == -1: plt.plot(contour[:, 0], contour[:, 1], 'g-', linewidth=2, label='Contour (outer)') else: plt.plot(contour[:, 0], contour[:, 1], 'r-', linewidth=2, label='Contour (inner)') plt.gca().set_aspect('equal', adjustable='box') plt.legend() plt.show() #------------- Visualization (optional) ------------- return x_length, y_length, d_length, w_width, \ angle_deg, area, r2_correlation, F_fine_detail, S_ratio
# endregion # ============================================================================== # MARK: SECTION 2: PARTICLE CLASSIFICATION & IMAGE QC # ============================================================================== # region SECTION 2: PARTICLE CLASSIFICATION & IMAGE QC # Holroyd habit classification, hollow-particle detection, Poisson-spot correction, # and per-particle parameter aggregation for Level-1 image products. # Functions: holroyd, scan_slice, mask_start_end, is_it_hollow, _find_hole_max_dy_with_same_x, # _find_particle_max_dy_for_x, correct_spherical_poisson_spot, # get_particle_parameters # ==============================================================================
[docs] def holroyd(image_buffer: xr.DataArray, diode_size: float, diode_num: int, particle_mask: int = 0, print_result: bool = False, plot: bool = False, _contour_data=None) -> dict: """ Classifies the habit of particles in an image buffer according to the methodology outlined by Holroyd (1987). This classification is based on geometric and statistical analyses of the particle images, including their size, shape, and orientation. Parameters: ----------- - image_buffer (xarray.DataArray): The particle image data in an xarray DataArray format. - diode_size (float): The size of one diode in millimeters, indicating the probe's resolution. - diode_num (int): The total number of diodes in each slice. - particle_mask (int, optional): Pixel value that identifies the particle (default 0). - print_result (bool, optional): If True, prints the calculated statistical and geometric properties to the console. Defaults to False. - plot (bool, optional): If True, generates a plot illustrating the particle, the fit line, and the particle's contour. Defaults to False. Returns: -------- - holroyd_habit : str A character code representing the classified particle habit (Reference: Holroyd , E. W., 1987: Some Techniques and Uses of 2D-C Habit Classification Software for Snow Particles. J. Atmos. Oceanic Technol., 4, 498–511, https://doi.org/10.1175/1520-0426(1987)004%3C0498:STAUOC%3E2.0.CO;2). Possible values: - 'M' : not calculated, zero image - 't' : tiny - 'o' : oriented - 'l' : linear - 'a' : aggregate - 'g' : graupel - 's' : spherel - 'h' : hexagonal - 'i' : irregular - 'd' : dendrite - F_fine_detail : float A calculated value representing the fine detail of the particle, used in determining certain habit classifications. History: -------- - 2026-06-26: Added particle_mask parameter and forwarding, Yongjie Huang - 2024-09-09: Added more variables return with dict type, Yongjie Huang - 2024-02-27: Created by Yongjie Huang (huangynj@gmail.com) based on the Matlab version """ probe_resolution = diode_size # [mm] n_slices = image_buffer.sizes['slice'] if n_slices == 0: holroyd_habit = 'M' # F_fine_detail = 0.0 # return holroyd_habit, F_fine_detail x_length, y_length, d_length, w_width, \ angle_deg, area, r2_correlation, \ F_fine_detail, S_ratio = tuple([0.0] * 9) else: x_length, y_length, d_length, w_width, \ angle_deg, area, r2_correlation, \ F_fine_detail, S_ratio = calculate_particle_morphology( image_buffer, n_slices, diode_num, particle_mask=particle_mask, print_result=print_result, plot=plot, _contour_data=_contour_data, ) if area == 0: holroyd_habit = 'M' elif area < 25: holroyd_habit = 't' elif r2_correlation >= 0.4 or ((d_length * probe_resolution < 1.6) and (x_length >= 4 * y_length or y_length >= 4 * x_length)): if 30.0 < angle_deg < 60.0: holroyd_habit = 'o' else: holroyd_habit = 'l' elif d_length * probe_resolution > 4.0: holroyd_habit = 'a' elif S_ratio >= 0.7: holroyd_habit = 'g' elif d_length * probe_resolution >= 1.6: if F_fine_detail <= 13: holroyd_habit = 'g' else: holroyd_habit = 'a' elif F_fine_detail < 5.5: holroyd_habit = 's' elif F_fine_detail < 10.0: if d_length * probe_resolution >= 0.8: holroyd_habit = 'g' else: holroyd_habit = 'h' elif F_fine_detail < 16.0 or x_length * probe_resolution <= 0.175: holroyd_habit = 'i' else: holroyd_habit = 'd' # return holroyd_habit, F_fine_detail return_dict = { 'holroyd_habit':holroyd_habit, 'fit_maj_axis':d_length, 'fit_min_axis':w_width, 'fit_angle':np.radians(angle_deg), 'fit_r2':r2_correlation, 'F_fine_detail':F_fine_detail, 'S_ratio':S_ratio, } return return_dict
[docs] def scan_slice(image_slice: np.ndarray) -> tuple[int, int, int]: """ Scan an image slice to find the first and last position of '0' pixels and their count. This function analyzes a single-dimensional slice of an image, identifying the positions of pixels that have a value of '0', which typically represent a certain feature or absence thereof in image processing tasks. It calculates the positions of the first and last '0' pixel and counts the total number of '0' pixels within the slice. Parameters: ----------- - image_slice (numpy.ndarray): The 1-D image slice as a NumPy array. This slice is scanned to identify '0' pixels, which are of interest for further analysis or processing. Returns: -------- - min_pos_lite (int): Position of the first '0' pixel in the slice. If no '0' pixels are found, this value is returned as 0. - max_pos_lite (int): Position of the last '0' pixel in the slice. If no '0' pixels are found, this value is returned as 0. - n_lite (int): Total count of '0' pixels within the slice. If no '0' pixels are found, this value is 0. Note: ----- - The function is useful in contexts where the presence or distribution of certain pixel values (e.g., '0' pixels) within a slice of an image carries specific significance, such as in the analysis of segmented images or features within images. History: -------- - 2024-02-27: Created by Yongjie Huang (huangynj@gmail.com) based on the Matlab version """ # Find indices of '0' pixels zeros = np.where(image_slice.flatten() == 0)[0] n_lite = len(zeros) if n_lite == 0: min_pos_lite = max_pos_lite = 0 else: min_pos_lite = zeros.min() max_pos_lite = zeros.max() return min_pos_lite, max_pos_lite, n_lite
[docs] def mask_start_end(end_mask: int, start_mask: int, to_mask: np.ndarray) -> np.ndarray: """ Applies a mask to an input array based on specified start and end positions. This function creates a mask where only the values between the start and end positions (inclusive) are retained from the original input array, and values outside this range are set to '0'. This can be particularly useful for isolating specific segments of data within an array for further analysis or processing. Parameters: ----------- - end_mask (int): The end position (inclusive) of the mask. This specifies the last index in the `to_mask` array that should retain its original value. - start_mask (int): The start position of the mask. This specifies the first index in the `to_mask` array that should retain its original value. - to_mask (numpy.ndarray): The input array to which the mask is applied. This array will be masked based on the start and end positions, with values outside this range set to '0'. Returns: -------- - numpy.ndarray: A masked version of the `to_mask` array where values outside the specified start and end range are set to '0', and values within this range retain their original values. Note: ----- - If both `start_mask` and `end_mask` are set to 0, it is assumed that no masking is desired, and the original `to_mask` array is returned unchanged. This special case allows for easy handling of conditions where masking may not be needed. History: -------- - 2024-02-27: Created by Yongjie Huang (huangynj@gmail.com) based on the Matlab version """ # Initialize the result array with '0's result = np.zeros_like(to_mask) # Apply the mask if start and end positions are specified if not (start_mask == 0 and end_mask == 0): result[start_mask:end_mask+1] = to_mask[start_mask:end_mask+1] else: # If no masking is required, return the original array result = to_mask return result
[docs] def is_it_hollow(image_buffer: xr.DataArray, particle_mask: int = 0, method: str = 'bounding_box', _contour_data=None) -> tuple[int, int, int]: """ Determines if a particle in a binary image is hollow, solid, or split, based on analysis of its contours and hierarchy. Uses OpenCV's ``cv2.findContours`` with ``cv2.RETR_TREE`` to detect contours and their hierarchy. The hierarchy distinguishes external contours (particles) from internal contours (holes). Two methods are available for measuring the hole and edge diameters. Parameters ---------- - image_buffer : xr.DataArray A 2-D xarray DataArray representing the binary image. Pixels equal to *particle_mask* are treated as particle; all other pixels are background. Dimensions must be labelled ``'slice'`` and ``'diode'``. - particle_mask : int, optional Pixel value that identifies the particle (default 0). method : {'bounding_box', 'contour_max_dy'}, optional Method used to calculate the hole and edge diameters when a hollow is detected (default ``'bounding_box'``). * ``'bounding_box'`` – Uses the Y (diode-direction) bounding box of each inner contour and its parent contour. Simple and fast. * ``'contour_max_dy'`` – For each inner contour, finds the X coordinate where the vertical span of the hole is largest, and returns the parent contour's thickness at that same X. More precise for irregular contours. Returns ------- - is_hollow : int * 0 – solid (no holes detected). * 1 – hollow (at least one internal void). * 2 – split particle (multiple disjoint external contours, no internal voids). - max_edge_diameter : int Maximum thickness (diode direction, in pixels) of the particle edge at the location of the largest hole. - max_hole_diameter : int Maximum diameter (diode direction, in pixels) of the largest internal void. Notes ----- - The image is padded by 1 pixel on all sides (with background value) before contour detection so that particles touching the image boundary still produce closed contours. - When *method* is ``'bounding_box'``, the hole diameter is calculated as ``max(Y) - min(Y) - 1`` for the inner contour (the contour sits on the shadowed boundary pixels, so the open interior is 1 px smaller on each side). History ------- - 2026-06-24 Unified v1–v4 into single function (refactored) – Yongjie Huang - 2024-09-01 Added particle_mask support – Yongjie Huang - 2024-08-30 v4 created (scipy binary_fill_holes) – Yongjie Huang - 2024-08-30 v3 created (contour bounding-box) – Yongjie Huang - 2024-02-28 v2 created (contour max-dy approach) – Yongjie Huang - 2024-02-27 v1 created (slice-scan approach) – Yongjie Huang """ if method not in ('bounding_box', 'contour_max_dy'): raise ValueError( f"Unknown method '{method}'. " "Choose 'bounding_box' or 'contour_max_dy'." ) if _contour_data is None: contours, hierarchy = _find_particle_contours(image_buffer, particle_mask) else: contours, hierarchy = _contour_data # ------------------------------------------------------------------ # # Classify: solid / hollow / split # ------------------------------------------------------------------ # is_hollow = 0 if len(contours) > 1: if any(hierarchy[0, :, 3] >= 0): # at least one child contour is_hollow = 1 else: # multiple top-level, no children is_hollow = 2 # ------------------------------------------------------------------ # # Measure hole and edge sizes # ------------------------------------------------------------------ # max_edge_diameter = 0 max_hole_diameter = 0 if is_hollow == 1: if method == 'bounding_box': # ----- bounding-box approach (from v3, bug-fixed) ----- # for i in range(len(contours)): parent_idx = hierarchy[0, i, 3] if parent_idx >= 0: # inner contour → hole edge_d = (max(contours[parent_idx][:, 0, 1]) - min(contours[parent_idx][:, 0, 1]) + 1) hole_d = (max(contours[i][:, 0, 1]) - min(contours[i][:, 0, 1]) - 1) # Net -1: the contour sits on the shadowed boundary pixels, # so the open interior is 1 pixel smaller on each side # (i.e., inclusive span +1, minus 2 boundary pixels = -1). # Clamp hole_d to at least 1 so thin hollows are not silently suppressed. hole_d = max(1, hole_d) if hole_d > max_hole_diameter: max_hole_diameter = hole_d max_edge_diameter = edge_d else: # method == 'contour_max_dy' # ----- per-contour max-dy approach (from v2) ----- # for i in range(len(contours)): parent_idx = hierarchy[0, i, 3] if parent_idx >= 0: # inner contour → hole x, max_dy = _find_hole_max_dy_with_same_x( contours[i][:, 0, :] ) if max_dy > max_hole_diameter: max_hole_diameter = max_dy max_edge_diameter = _find_particle_max_dy_for_x( contours[parent_idx][:, 0, :], x ) return is_hollow, max_edge_diameter, max_hole_diameter
# ------------------------------------------------------------------ # # Private helpers for the 'contour_max_dy' method # ------------------------------------------------------------------ # def _find_hole_max_dy_with_same_x(points: np.ndarray) -> tuple: """Return (x, max_dy) for the X with the largest vertical hole span. Parameters ---------- - points : np.ndarray, shape (N, 2) Contour points (x, y) outlining the hole. Returns ------- - max_dy_x : int or None X coordinate at which the vertical span is largest. - max_dy : int The largest vertical span (minus 1 to exclude the boundary pixels). """ unique_xs, counts = np.unique(points[:, 0], return_counts=True) max_dy = -1 max_dy_x = None for x in unique_xs[counts == 2]: y_values = points[points[:, 0] == x, 1] dy = np.abs(y_values[1] - y_values[0]) - 1 # hole distance if dy > max_dy: max_dy = dy max_dy_x = x return max_dy_x, max_dy def _find_particle_max_dy_for_x(points: np.ndarray, specified_x: int) -> int: """Return the vertical thickness of the particle contour at *specified_x*. Parameters ---------- - points : np.ndarray, shape (N, 2) Contour points (x, y) of the parent (particle) contour. - specified_x : int The X coordinate to measure thickness at. Returns ------- - int Vertical thickness in pixels (max_y − min_y + 1), or 0 if fewer than two points exist at the given X. """ y_values = points[points[:, 0] == specified_x, 1] if len(y_values) == 0: if len(points) > 0: nearest_x = points[np.argmin(np.abs(points[:, 0] - specified_x)), 0] y_values = points[points[:, 0] == nearest_x, 1] return int(np.max(y_values) - np.min(y_values) + 1) return 0 return int(np.max(y_values) - np.min(y_values) + 1) ''' def calculate_reject_unified(image_buffer: xr.DataArray, habit: str, ihollow: int = 0) -> tuple[int, int, int, int, int, int, str, str, int, float, float, float, float, int, int, int]: """ Analyze a particle image to determine if it should be rejected based on its physical characteristics and other criteria. The analysis includes measurements of particle dimensions, area, presence of hollow sections, and comparison against criteria for rejecting particles based on their habit and other factors. Parameters: ----------- - image_buffer (xarray.DataArray): The 2D array representing the particle image, where '0' pixels indicate the particle or opaque areas, and '1' pixels represent empty or transparent areas. - habit (str): The classified habit of the particle, determined from prior analysis. - ihollow (int): Indicator of whether the particle is considered hollow (1 for hollow, 0 for not hollow). Returns: -------- - A tuple containing various metrics and flags related to the particle and the analysis, including: - p_length (int): The length of the particle along its longest dimension. - width (int): The width of the particle perpendicular to its length. - area (int): The total area covered by the particle in the image. - longest_y (int): The longest dimension of the particle in the y-direction. - max_top, max_bottom (int): Maximum dimensions at the top and bottom of the particle. - touching_edge (str): Flag indicating if the particle is touching the edge of the image ('t' if touching, '0' if not). - reject_status (str): A code indicating the reason for rejection ('0' if not rejected, other codes for specific rejection reasons). - is_hollow (int): Flag indicating if the particle is considered hollow (based on analysis). - percent_shadow_area (float): Percentage of the particle area that is shadowed. - part_z (float): Some z-dimension measure of the particle, related to its depth or thickness. - size_factor (float): A factor related to the particle's size. - area_hole_ratio (float): The ratio of the particle's area to the area of holes within it. - max_hole_diameter (int): The diameter of the largest hole within the particle. - edge_at_max_hole (int): Indicates if the largest hole is at the edge of the particle (1 if at the edge, 0 if not). - center_in (int): Some measure related to the particle's center. The function evaluates the particle against several criteria to determine if it should be rejected for analysis. These criteria include checks for the particle's aspect ratio, shadowed area percentage, and whether the particle appears to be hollow, split, or touching the image edge. Specific rejection codes are assigned based on these criteria. Reject_status code: - '0' = not rejected - 'a' = reject max. aspect ratio - 't' = reject max. aspect ratio touch edg - 'p' = reject percent shadowed area - 'h' = reject Hollow image - 's' = reject split image - 'z' = reject 0 area image - 'f' = reject fake 0 area image History: -------- - 2024-02-28: Created by Yongjie Huang (huangynj@gmail.com) based on the Matlab version """ part_z = -1 size_factor = 1 # probe_resolution = diode_size # [mm] n_slices = image_buffer.sizes['slice'] diode_num = image_buffer.sizes['diode'] rej_zero_area = 1 rej_split = 1 rej_hollow = 1 shadowed_area = 25 max_edge_img_ar = 5 max_comp_img_ar = 6 max_hole_diameter = 0 edge_at_max_hole = 0 min_length = -1 max_length = -1 max_width = 0 min_width = diode_num-1 total_area = 0 touch = 0 width = 0 ndrops = 0 split = 0 met_image = 0 is_hollow = 0 aspect_ratio = 0 percent_shadow_area = 0 area_hole_ratio = 0 area = 0 max_top = 0 max_bottom = 0 longest_y = 0 touching_edge = '0' top_min_x = -1 top_max_x = -1 bottom_min_x = -1 bottom_max_x = -1 center_in = -1 # return_tuple = (p_length, width, area, longest_y, max_top, max_bottom, touching_edge, # reject_status, is_hollow, percent_shadow_area, part_z, size_factor, # area_hole_ratio, max_hole_diameter, edge_at_max_hole, center_in) if n_slices==0: p_length = 0 area = 0 if rej_zero_area==1: reject_status='z' return (p_length, width, area, longest_y, max_top, max_bottom, touching_edge, reject_status, is_hollow, percent_shadow_area, part_z, size_factor, area_hole_ratio, max_hole_diameter, edge_at_max_hole, center_in) # return_tuple else: reject_status='0' else: for i in range(n_slices): min_pos_lite, max_pos_lite, n_lite = scan_slice(image_buffer.values[i,:]) longest_y = max(longest_y, n_lite) # Logical AND across slices to find vertical splits - initializing vertical_split for the first slice if i == 0: vertical_split = image_buffer[i, :].values else: vertical_split = vertical_split & image_buffer[i, :].values if n_lite > 0: if touch == 0 and (max_pos_lite==diode_num-1 or min_pos_lite==0): touch = 1 if min_pos_lite == 0: bottom_min_x = i if bottom_min_x == -1 else bottom_min_x bottom_max_x = max(bottom_max_x, i) if max_pos_lite == diode_num-1: top_min_x = i if top_min_x == -1 else top_min_x top_max_x = max(top_max_x, i) max_width = max(max_width, max_pos_lite) min_width = min(min_width, min_pos_lite) min_length = i if min_length == -1 else min_length max_length = i total_area += n_lite if met_image == 0 and n_lite > 0: met_image = 1 ndrops += 1 if ndrops > 1 and rej_split == 1: split = 1 elif met_image == 1 and n_lite == 0: met_image = 0 area = total_area # Calculating max_top and max_bottom max_top = 0 if top_min_x == -1 else (top_max_x - top_min_x + 1) max_bottom = 0 if bottom_min_x == -1 else (bottom_max_x - bottom_min_x + 1) # Setting touching_edge touching_edge = 't' if touch == 1 else '0' # Setting p_length and width if total_area == 0: p_length = 0 width = 0 else: p_length = max_length - min_length + 1 width = max_width - min_width + 1 # Checking if the center is in center_in = 1 if p_length > max(max_bottom, max_top) else 0 # Reject conditions if total_area > 0.8 * diode_num * n_slices: reject_status = 'A' return (p_length, width, area, longest_y, max_top, max_bottom, touching_edge, reject_status, is_hollow, percent_shadow_area, part_z, size_factor, area_hole_ratio, max_hole_diameter, edge_at_max_hole, center_in) # return_tuple if split == 1: reject_status = 's' return (p_length, width, area, longest_y, max_top, max_bottom, touching_edge, reject_status, is_hollow, percent_shadow_area, part_z, size_factor, area_hole_ratio, max_hole_diameter, edge_at_max_hole, center_in) # return_tuple # Check for vertical_split existence if 'vertical_split' in locals(): min_pos_lite, max_pos_lite, n_lite = scan_slice(vertical_split) else: min_pos_lite = 0 max_pos_lite = 0 n_lite = 0 ##### Seems something wrong here !!!! Yongjie Huang, 2024-02-23. !!! # if n_lite==1 and (n_lite!=max_pos_lite-min_pos_lite+1) and rej_split==0: # Should be: if n_lite>0 and (n_lite!=max_pos_lite-min_pos_lite+1) and rej_split==1: reject_status = 's' return (p_length, width, area, longest_y, max_top, max_bottom, touching_edge, reject_status, is_hollow, percent_shadow_area, part_z, size_factor, area_hole_ratio, max_hole_diameter, edge_at_max_hole, center_in) # return_tuple # Calculate aspect_ratio and percent_shadow_area if applicable # Note on Aspect Ratio definition: Here aspect_ratio represents the ratio of the bounding box # dimensions along the slice (time) direction vs diode (array) direction (p_length / width). if total_area > 0: if p_length > 0 and width > 0: aspect_ratio = 1.0*p_length/width percent_shadow_area = (1.0*total_area/(p_length * width)) * 100 else: aspect_ratio = 0 percent_shadow_area = 0 if total_area == 0 and rej_zero_area == 1: reject_status = 'z' return (p_length, width, area, longest_y, max_top, max_bottom, touching_edge, reject_status, is_hollow, percent_shadow_area, part_z, size_factor, area_hole_ratio, max_hole_diameter, edge_at_max_hole, center_in) # return_tuple elif total_area == 0 and rej_zero_area == 0: reject_status = '0' return (p_length, width, area, longest_y, max_top, max_bottom, touching_edge, reject_status, is_hollow, percent_shadow_area, part_z, size_factor, area_hole_ratio, max_hole_diameter, edge_at_max_hole, center_in) # return_tuple elif touch == 1 and (aspect_ratio > max_edge_img_ar or aspect_ratio < 1./max_edge_img_ar): reject_status = 't' return (p_length, width, area, longest_y, max_top, max_bottom, touching_edge, reject_status, is_hollow, percent_shadow_area, part_z, size_factor, area_hole_ratio, max_hole_diameter, edge_at_max_hole, center_in) # return_tuple elif aspect_ratio > max_comp_img_ar or aspect_ratio < 1./max_comp_img_ar: reject_status = 'a' return (p_length, width, area, longest_y, max_top, max_bottom, touching_edge, reject_status, is_hollow, percent_shadow_area, part_z, size_factor, area_hole_ratio, max_hole_diameter, edge_at_max_hole, center_in) # return_tuple elif percent_shadow_area < shadowed_area: reject_status = 'p' return (p_length, width, area, longest_y, max_top, max_bottom, touching_edge, reject_status, is_hollow, percent_shadow_area, part_z, size_factor, area_hole_ratio, max_hole_diameter, edge_at_max_hole, center_in) # return_tuple elif rej_hollow == 1: hollow_status, edge_at_max_hole, max_hole_diameter = \ is_it_hollow(image_buffer, method='contour_max_dy') is_hollow = hollow_status if center_in == 1 and touching_edge != '0' and is_hollow == 1: # Transpose image_buffer for is_it_hollow call and adapt parameters as needed hollow_status_side1, edge_at_max_hole_side1, max_hole_diameter_side1 = \ is_it_hollow(image_buffer.transpose(), method='contour_max_dy') # Only overwrite if side-view is also hollow if hollow_status_side1 == 1: edge_at_max_hole = edge_at_max_hole_side1 max_hole_diameter = max_hole_diameter_side1 if hollow_status == 1: ratio = 0 if edge_at_max_hole <= 0 else 1.0*max_hole_diameter/edge_at_max_hole if ratio == 0: part_z = 0 size_factor = 1 reject_status = 'h' area_hole_ratio = 0 elif max_hole_diameter <= 1: part_z = 0 size_factor = 1 area_hole_ratio = 0 reject_status = '0' else: diameter_correction_factor, _ = correct_spherical_poisson_spot(max_hole_diameter, edge_at_max_hole) size_factor = 1.0 / diameter_correction_factor part_z = 0 reject_status = 'H' area_hole_ratio = 1.0*area/max_hole_diameter if max_hole_diameter != 0 else 0 # Conditional checks based on area_hole_ratio and habit if area_hole_ratio > 20 and habit == 'i': part_z = 0 size_factor = 1 reject_status = 'u' elif area_hole_ratio > 35 and habit == 'h': part_z = 0 size_factor = 1 reject_status = 'u' elif area_hole_ratio > 40 and habit != 's': part_z = 0 size_factor = 1 reject_status = 'u' else: part_z = -1 size_factor = 1 area_hole_ratio = 0 reject_status = '0' else: reject_status = '0' # Return all the calculated metrics and flags return (p_length, width, area, longest_y, max_top, max_bottom, touching_edge, reject_status, is_hollow, percent_shadow_area, part_z, size_factor, area_hole_ratio, max_hole_diameter, edge_at_max_hole, center_in) # return_tuple '''
[docs] def correct_spherical_poisson_spot(Dspot: float, Dedge: float) -> tuple[float, float]: """ Corrects the diameter of spherical particles in shadow images affected by Poisson Spots, using a method based on Korolev (2007). Poisson Spots (or Arago spots) occur due to diffraction effects in shadow imaging, leading to a bright spot at the center of the particle shadow that can distort diameter measurements. Parameters: ----------- Dspot (float): The diameter of the Poisson spot (the bright spot seen at the center of a shadow image of a particle), which results from diffraction around the spherical particle. Dedge (float): The diameter of the entire shadow image of the particle, encompassing the region affected by diffraction, including the Poisson spot. Returns: -------- tuple: - diameter_correction_factor (float): The factor by which the observed particle diameter (Dedge) should be multiplied to correct for the Poisson Spot effect. This factor is derived through interpolation from a lookup table based on Korolev (2007). - corrected_diameter (float): The corrected diameter of the particle after applying the correction factor to account for the Poisson Spot effect. Method: ------- The function employs a lookup table from Korolev (2007) that correlates the ratio of the Poisson spot diameter to the particle shadow diameter (Dspot/Dedge) with a correction factor (Dedge/D0), where D0 is the actual particle diameter without diffraction effects. The correct diameter is obtained by finding the two closest values in the lookup table to the ratio x (Dspot/Dedge) and linearly interpolating between them. Steps: ------ 1. Compute the ratio x = Dspot / Dedge. 2. Use numpy's searchsorted function to locate where this ratio fits in the predefined lookup tables (`Dspot_Dedge` and `Dedge_D0`). 3. Depending on the position of x, either directly use the closest table value or perform linear interpolation between the two nearest values. 4. Compute the correction factor as the inverse of the interpolated value. 5. Apply this correction factor to Dedge to obtain the corrected diameter. Reference: ---------- Korolev, A., 2007: Reconstruction of the Sizes of Spherical Particles from Their Shadow Images. Part I: Theoretical Considerations. J. Atmos. Oceanic Technol., 24, 376–389, https://doi.org/10.1175/JTECH1980.1. History: -------- - 2024-08-31: Add diameter_correction_factor output, Yongjie Huang (huangynj@gmail.com). - 2024-08-30: First created by Yongjie Huang (huangynj@gmail.com). """ # Lookup Table for Retrieval of Sizes of Spherical Particles (Korolev 2007) Dedge_D0 = np.array([ 1.000, 1.054, 1.083, 1.101, 1.095, 1.110, 1.148, 1.162, 1.155, 1.123, 1.182, 1.121, 1.162, 1.210, 1.242, 1.134, 1.166, 1.202, 1.238, 1.270, 1.294, 1.278, 1.130, 1.148, 1.170, 1.194, 1.218, 1.242, 1.265, 1.288, 1.310, 1.331, 1.351, 1.369, 1.386, 1.400, 1.411, 1.416, 1.407, 1.074, 1.080, 1.087, 1.096, 1.106, 1.117, 1.127, 1.139, 1.150, 1.162, 1.173, 1.185, 1.197, 1.208, 1.220, 1.232, 1.243, 1.255, 1.266, 1.277, 1.289, 1.300, 1.311, 1.322, 1.333, 1.344, 1.355, 1.366, 1.376, 1.387, 1.397, 1.407, 1.418, 1.428, 1.438, 1.448, 1.458, 1.467, 1.477, 1.486, 1.496, 1.505, 1.515, 1.524, 1.533, 1.542, 1.551, 1.559, 1.568, 1.577, 1.585, 1.594, 1.602, 1.610, 1.618, 1.626, 1.634, 1.642, 1.650, 1.657, 1.665, 1.673, 1.680, 1.687, 1.694, 1.702, 1.709, 1.716, 1.722, 1.729, 1.736, 1.742, 1.749, 1.755, 1.761, 1.768, 1.774, 1.780, 1.786, 1.791, 1.797, 1.803, 1.808, 1.813, 1.819, 1.824, 1.829, 1.834, 1.839, 1.843, 1.848, 1.852, 1.857, 1.861, 1.865, 1.869, 1.872, 1.876, 1.880, 1.883, 1.886, 1.889, 1.892, 1.895, 1.897, 1.899, 1.901, 1.903, 1.905, 1.906, 1.907, 1.908, 1.908, 1.908, 1.908, 1.907, 1.905, 1.903, 1.900, 1.897, 1.892, 1.885, 1.877, 1.865, 1.845 ]) Dspot_Dedge = np.array([ 0.003, 0.008, 0.017, 0.024, 0.033, 0.040, 0.047, 0.054, 0.062, 0.072, 0.076, 0.088, 0.093, 0.096, 0.101, 0.119, 0.123, 0.127, 0.130, 0.134, 0.139, 0.148, 0.175, 0.180, 0.184, 0.188, 0.192, 0.195, 0.199, 0.202, 0.206, 0.209, 0.213, 0.217, 0.221, 0.225, 0.230, 0.235, 0.243, 0.327, 0.334, 0.340, 0.345, 0.351, 0.355, 0.360, 0.365, 0.369, 0.373, 0.377, 0.381, 0.385, 0.389, 0.393, 0.397, 0.400, 0.404, 0.408, 0.411, 0.415, 0.419, 0.422, 0.426, 0.429, 0.433, 0.436, 0.439, 0.443, 0.446, 0.450, 0.453, 0.457, 0.460, 0.463, 0.467, 0.470, 0.473, 0.477, 0.480, 0.484, 0.487, 0.490, 0.494, 0.497, 0.501, 0.504, 0.507, 0.511, 0.514, 0.518, 0.521, 0.525, 0.528, 0.532, 0.535, 0.539, 0.543, 0.547, 0.550, 0.554, 0.558, 0.562, 0.566, 0.569, 0.572, 0.575, 0.578, 0.581, 0.584, 0.587, 0.590, 0.593, 0.596, 0.598, 0.601, 0.605, 0.610, 0.614, 0.618, 0.623, 0.627, 0.631, 0.635, 0.640, 0.644, 0.648, 0.653, 0.657, 0.662, 0.666, 0.671, 0.676, 0.680, 0.685, 0.690, 0.695, 0.700, 0.705, 0.711, 0.716, 0.721, 0.727, 0.733, 0.738, 0.744, 0.751, 0.757, 0.763, 0.770, 0.777, 0.784, 0.792, 0.800, 0.808, 0.817, 0.826, 0.836, 0.846, 0.858, 0.870, 0.884, 0.901, 0.921, 0.950 ]) if Dedge == 0: return 1.0, 0.0 # Ratio of the Poisson spot diameter to the entire image diameter x = Dspot / Dedge # Find indices of the closest values in dspot_dedge idx = np.searchsorted(Dspot_Dedge, x, side="left") # a[i-1] < v <= a[i] return i if idx == 0: # x is smaller than the smallest value in Dspot_Dedge diameter_correction_factor = 1 / Dedge_D0[0] elif idx == len(Dspot_Dedge): # x is larger than the largest value in Dspot_Dedge diameter_correction_factor = 1 / Dedge_D0[-1] else: # x is between two values in Dspot_Dedge, conduct linear interpolation x0, x1 = Dspot_Dedge[idx-1], Dspot_Dedge[idx] y0, y1 = Dedge_D0[idx-1], Dedge_D0[idx] # Linear interpolation to find the corresponding dedge_d0 for x dedge_d0_interpolated = y0 + (y1 - y0) * (x - x0) / (x1 - x0) # Calculate the corrected diameter using the interpolated dedge_d0 diameter_correction_factor = 1 / dedge_d0_interpolated corrected_diameter = Dedge * diameter_correction_factor return diameter_correction_factor, corrected_diameter
[docs] def get_particle_parameters(image_buffer: xr.DataArray, diode_size: float, particle_mask: int = 0, **kwargs) -> dict: """ Extracts various parameters related to particles detected in an image buffer. These parameters include the particle's length, width, total shadowed pixels, whether the particle touches the image edge, whether its center is inside the image bounds, and certain metrics for quality control and rejection. Parameters: ----------- image_buffer: xarray.DataArray A 2D array representing the particle image where specific pixels are marked to indicate the presence of a particle. The array should have dimensions labeled as 'slice' (time direction) and 'diode' (spatial direction). diode_size: float The size of one diode in millimeters, indicating the probe's resolution. particle_mask: int, optional The value in the image buffer that represents the particle (default is 0). Returns: -------- dict: A dictionary containing the following elements: - count_each_diode (np.ndarray): The count of particle pixels along each diode column. - slice_length (int): The length of the particle along the time (slice) axis. - diode_length (int): The width of the particle along the diode axis. - shadowed_area (int): The total number of pixels marked as 'particle' within the image buffer. - touching_image_edge (np.int8): 0 if no touch, 1 if touching one edge, 2 if touching both edges. - center_in (int): 1 if the particle's center is inside the image bounds, 0 otherwise. - all_in (int): 1 if the particle does not touch any image edge, 0 otherwise. - hollow_status (int): 0 for solid, 1 for hollow, 2 for split particle. - holroyd_habit (str): Habit classification string from Holroyd algorithm. - diameter_correction_factor (float): Correction factor for Poisson spot effect in spherical hollow particles. - area_hole_ratio (float): Ratio of shadowed area to maximum hole diameter. - edge_at_max_hole (int): Edge thickness at the maximum hole location. - max_hole_diameter (int): Maximum diameter of the internal void. - aspect_ratio (float): Bounding box slice length divided by diode length. - percent_shadow_area (float): Percentage of bounding box covered by shadowed pixels. - reject_status (str): A code indicating the rejection status of the particle: - '0': Not rejected. - 'A': Rejected due to excessive shadowed pixels covering the image (>80%). - 't': Rejected due to touching the image edge with an extreme aspect ratio (>5 or <0.2). - 'a': Rejected due to an aspect ratio that exceeds allowed limits (>6 or <0.167). - 'p': Rejected due to a low percentage of shadowed area (<25%). - 'h': Rejected as a hollow image without valid edge. - 'H': Hollow particle with valid hole (reaccepted or flagged). - 's': Rejected due to a split image. - 'z': Rejected as a zero-area image. - 'u': Rejected based on area hole ratio and habit criteria. - (Additional keys from holroyd fit such as fit_maj_axis, fit_min_axis, fit_angle, fit_r2, F_fine_detail, S_ratio) Notes: ------ The function also calls several helper functions to determine additional characteristics of the particle, such as 'holroyd' for habit classification and 'is_it_hollow' to check for hollow status and calculate maximum hole diameter. History: -------- - 2026-06-26: Updated docstrings to correctly describe return dictionary and keys, Yongjie Huang - 2024-08-31: Updated quality control and rejection, Yongjie Huang (huangynj@gmail.com) - 2024-08-30: First created, Yongjie Huang (huangynj@gmail.com) """ # image_buffer(slice, diode) n_slices = image_buffer.sizes['slice'] # axis = 0 diode_num = image_buffer.sizes['diode'] # axis = 1 particle_pixels = image_buffer.values == particle_mask shadowed_pixel = np.count_nonzero(particle_pixels) contour_data = ( _find_particle_contours(image_buffer, particle_mask) if shadowed_pixel != 0 else None ) # Determine the Particle Habit using the Holroyd algorithm holroyd_dict = holroyd( image_buffer, diode_size, diode_num, particle_mask=particle_mask, _contour_data=contour_data, ) holroyd_habit = holroyd_dict['holroyd_habit'] # return_dict = { # 'holroyd_habit':holroyd_habit, # 'fit_maj_axis':d_length, # 'fit_min_axis':w_width, # 'fit_angle':np.radians(angle_deg), # 'fit_r2':r2_correlation, # 'F_fine_detail':F_fine_detail, # 'S_ratio':S_ratio, # } diameter_correction_factor = 1.0 reject_status = '0' area_hole_ratio = 0 hollow_status = -1 # default: not evaluated (overwritten by is_it_hollow or zero-area branch) if shadowed_pixel != 0: count_each_slice = np.sum(particle_pixels, axis=1) # count of each slice count_each_diode = np.sum(particle_pixels, axis=0) # count of each diode # Get non-zero slice and diode indices # non_zero_indices_slice = np.nonzero(count_each_slice)[0] # non_zero_indices_diode = np.nonzero(count_each_diode)[0] non_zero_indices_slice = np.flatnonzero(count_each_slice) non_zero_indices_diode = np.flatnonzero(count_each_diode) slice_start, slice_end = non_zero_indices_slice[0], non_zero_indices_slice[-1] diode_start, diode_end = non_zero_indices_diode[0], non_zero_indices_diode[-1] # slice_start, slice_end, diode_start, diode_end slice_length = slice_end - slice_start + 1 # D_t: Max distance in the time dimension diode_length = diode_end - diode_start + 1 # D_p: Max distance in the photodiode-array dimension #--- Using OpenCV package, but after test this method is less efficient. # # Find the coordinates of all pixels that are particle_mask (the irregular shape) # points = np.column_stack(np.where(image_buffer == particle_mask)) # # Convert points to the correct format for cv2.boundingRect # points = points.astype(np.float32) # # Compute the bounding Rectangle for the points # slice_start, diode_start, slice_length, diode_length = cv2.boundingRect(points) # Particle touching image edge # Using boolean operations directly to check for non-zero counts touch_bottom = int(count_each_diode[0] != 0) touch_top = int(count_each_diode[-1] != 0) touching_image_edge = np.array(touch_bottom+touch_top, dtype='int8') # 0 - no touch, 1 - touch one edge, 2 - touch both edges # define local function to calculate the length at first and last diodes def calculate_length_for_each_diode(column_data, particle_mask): """Calculate the length in a column matching the particle mask.""" non_zero_indices = np.where(column_data == particle_mask)[0] if non_zero_indices.size == 0: return 0 return non_zero_indices[-1] - non_zero_indices[0] + 1 length_first_diode = calculate_length_for_each_diode(image_buffer.values[:, 0], particle_mask) length_last_diode = calculate_length_for_each_diode(image_buffer.values[:, -1], particle_mask) # Determine 'all_in' and 'center_in' based on edge contact # If touching_image_edge is 0, it does not touch any edges all_in = 1 if touching_image_edge == 0 else 0 # Check if the slice length is greater than the maximum length of first or last diode center_in = 1 if all_in == 1 or slice_length > max(length_first_diode, length_last_diode) else 0 hollow_status, edge_at_max_hole, max_hole_diameter = is_it_hollow( image_buffer, particle_mask=particle_mask, method='contour_max_dy', _contour_data=contour_data, ) # Note on Aspect Ratio definition: Here aspect_ratio represents the ratio of the bounding box # dimensions along the slice (time/horizontal) direction vs diode (vertical) direction. aspect_ratio = 1.0 * slice_length / diode_length percent_shadow_area = 100.0 * shadowed_pixel / (slice_length * diode_length) #-- Reject conditions if shadowed_pixel > 0.8 * diode_num * n_slices: reject_status = 'A' elif hollow_status == 2: # split image reject_status = 's' elif touching_image_edge != 0 and (aspect_ratio > 5 or aspect_ratio < 1.0/5): reject_status = 't' elif aspect_ratio > 6 or aspect_ratio < 1.0/6: reject_status = 'a' elif percent_shadow_area < 25: reject_status = 'p' elif hollow_status == 1: # hollow image ratio_Dhole_Dedge = 0 if edge_at_max_hole <= 0 else 1.0 * max_hole_diameter / edge_at_max_hole if ratio_Dhole_Dedge == 0: diameter_correction_factor = 1.0 area_hole_ratio = 0 reject_status = 'h' elif max_hole_diameter <= 1: diameter_correction_factor = 1.0 area_hole_ratio = 0 reject_status = '0' else: diameter_correction_factor, _ = correct_spherical_poisson_spot(max_hole_diameter, edge_at_max_hole) # Note: area_hole_ratio has units of pixels (shadowed_pixel [px²] / max_hole_diameter [px]), # which makes the rejection thresholds (20, 35, 40) probe-resolution-dependent. A dimensionless # ratio (e.g., shadowed_pixel / max_hole_diameter**2) would be resolution-independent. area_hole_ratio = 1.0*shadowed_pixel/max_hole_diameter if max_hole_diameter != 0 else 0 reject_status = 'H' # default for hollow particles with valid hole # Conditional checks based on area_hole_ratio and habit if area_hole_ratio > 20 and holroyd_habit == 'i': diameter_correction_factor = 1.0 reject_status = 'u' elif area_hole_ratio > 35 and holroyd_habit == 'h': diameter_correction_factor = 1.0 reject_status = 'u' elif area_hole_ratio > 40 and holroyd_habit != 's': diameter_correction_factor = 1.0 reject_status = 'u' # Ensure diameter_correction_factor is reset to 1.0 for all non-spherical particles # so the stored DiameterCorrectionFactor matches the D_korolev calculation in process_ith_particle_image. if holroyd_habit != 's': diameter_correction_factor = 1.0 else: count_each_diode = np.sum(particle_pixels, axis=0) # count of each diode diameter_correction_factor = 1.0 reject_status = 'z' slice_length, diode_length = 0, 0 touching_image_edge = np.array(0, dtype='int8') area_hole_ratio = 0 edge_at_max_hole = 0 max_hole_diameter = 0 aspect_ratio = 0 percent_shadow_area = 0 center_in = 0 all_in = 0 hollow_status = -1 # redundant with top-level init, kept for clarity return_dict = { 'count_each_diode':count_each_diode, # count of each diode 'slice_length':slice_length, # slice (time) direction 'diode_length':diode_length, # diode direction 'shadowed_area':shadowed_pixel, 'touching_image_edge':touching_image_edge, # 0 - no touch, 1 - touch one edge, 2 - touch both edges 'center_in':center_in, 'all_in':all_in, 'hollow_status':hollow_status, 'holroyd_habit':holroyd_habit, 'diameter_correction_factor':diameter_correction_factor, 'area_hole_ratio':area_hole_ratio, 'edge_at_max_hole':edge_at_max_hole, 'max_hole_diameter':max_hole_diameter, 'aspect_ratio':aspect_ratio, 'percent_shadow_area':percent_shadow_area, 'reject_status':reject_status, } return_dict.update(holroyd_dict) # Add some variables from the least-squares fit # item_value = kwargs.get('item', 'default_value') return return_dict
# endregion # ============================================================================== # MARK: SECTION 3: LEVEL-1 IMAGE PIPELINE & SPIF APPEND # ============================================================================== # region SECTION 3: LEVEL-1 IMAGE PIPELINE & SPIF APPEND # NetCDF group discovery, active single-particle workers, parallel Level-1 dataset # construction, and the public SPIF Level-1 append entry point. The disabled # serial Level-1 implementation is retained at the end of this section for reference. # Functions: return_groups_with_specified_subgroup, process_ith_particle_image, # parallel_processing_images, calculate_particle_image_level1_variables_parallel, # process_spif_image_append_level1_data # ==============================================================================
[docs] def return_groups_with_specified_subgroup(nc_obj, target_subgroup: str, parent_path: str = '', groups_with_target: list | None = None, verbose: bool = True) -> list: """ Recursively searches all groups in a netCDF object for those that have a specified subgroup and returns their paths. Parameters: ----------- - nc_obj: The netCDF object to explore (can be the root of the file or a subgroup). - target_subgroup: The name of the subgroup to search for within each group. - parent_path: The path of the parent group leading to the current object, used for display purposes. - groups_with_target: A list to accumulate paths of groups that contain the specified subgroup. - verbose: If True, logs the path of each matching group found at INFO level. Returns: -------- - A list of paths to groups that contain the specified subgroup. History: -------- - 2024-03-05: Created by Yongjie Huang (huangynj@gmail.com) """ if groups_with_target is None: groups_with_target = [] # Iterate through all groups in the current netCDF object for group_name, group in nc_obj.groups.items(): # Check if this group contains the specified subgroup if target_subgroup in group.groups: # Construct the path for the current group current_path = f"{parent_path}/{group_name}" if parent_path else group_name if verbose: logger.info("Group with %r subgroup: %s", target_subgroup, current_path) groups_with_target.append(current_path) # Continue searching in subgroups return_groups_with_specified_subgroup(group, target_subgroup, f"{parent_path}/{group_name}" if parent_path else group_name, groups_with_target, verbose=verbose) return groups_with_target
[docs] def process_ith_particle_image( ip: int, time, time_sec, time_ns, InterArrivalTime, image_buffer: xr.DataArray, diode_size: float, diode_num: int, particle_mask: int = 0, iRectEllipse: int = 0, iCalcAllDiodeStats=0, total_images: int | None = None ) -> dict: """ Analyzes a single particle image to calculate various metrics, including dimensions, area, shape descriptors, and identifies if a particle is hollow. It optionally performs Korolev correction and calculates the minimum enclosing circle and ellipse metrics. Parameters ---------- ip : int The index of the particle image within the dataset. time : float The numeric representation of the image capture time since a fixed epoch. time_sec : int The time in seconds at which the image was captured since the start of the recording. time_ns : int Additional nanoseconds part of the capture time, providing higher precision. InterArrivalTime : float The time elapsed (in seconds) since the capture of the previous image. image_buffer : xarray.DataArray A 2D array representing the particle image to be processed. diode_size : float The physical size of a single diode/pixel in the imaging array, in millimeters. diode_num : int The total number of diodes/pixels in a single row or column of the imaging array. particle_mask : int, optional The value used to identify particles within the image, defaulting to 0. iRectEllipse : int, optional If set to 1, calculations for the minimum enclosing rectangle and ellipse metrics are performed, defaulting to 0. total_images : int, optional Total number of particle images in the dataset. When provided, debug progress messages use one-based ``current/total`` numbering. Returns ------- dict A dictionary containing the calculated metrics and properties of the particle, such as size, shape descriptors, and flags indicating whether the particle is hollow or touching the image edges. Notes ----- - This function is part of an image processing pipeline designed for analyzing particle images captured by imaging arrays. - The Korolev correction is applied to particles marked with 'H' in the auto_reject status, based on the size_factor derived from image analysis. History ------- - 2024-03-28: Yongjie Huang, first implemented. - 2024-04-16: Yongjie Huang, added 'ParticleDiodeStats'. - 2024-04-17: Yongjie Huang, added TAS ratio support for 'min_enclosing_circle'. """ # To do: update tasRatio in future tasRatio = 1. image_number = ip + 1 if total_images is None: log_progress = ip % 1000 == 0 else: log_progress = ( image_number == 1 or image_number % 1000 == 0 or image_number == total_images ) if log_progress: # Determine the current execution context (process or thread) and assign an appropriate identifier if isinstance(threading.current_thread(), threading._MainThread): # In a process (likely via ProcessPoolExecutor), use the process ID worker_id = f"PID {os.getpid()}" else: # In a thread (likely via ThreadPoolExecutor), use the thread's name worker_id = threading.current_thread().name timestamp = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f') if total_images is None: logger.debug( "%s - worker %s processing image %d", timestamp, worker_id, image_number, ) else: logger.debug( "%s - worker %s processing image %d/%d", timestamp, worker_id, image_number, total_images, ) #=== Start to calculate particle parameters data_dict = {} # dictionary for return # image_buffer = io.get_ith_particle_image(im_header, ds_images, ip) # ('slice','diode') # n_slices = image_buffer.sizes['slice'] # count_each_slice = np.sum(image_buffer.values==particle_mask, axis=1) # count of each slice # count_each_diode = np.sum(image_buffer.values==particle_mask, axis=0) # ParticleDiodeStats('diode') kwargs = dict( iRectEllipse=iRectEllipse, iCalcAllDiodeStats=iCalcAllDiodeStats, ) # item_value = kwargs.get('item', 'default_value') #-- Calculate particle parameters including particle Reject Status params_dict = get_particle_parameters(image_buffer, diode_size, particle_mask=particle_mask, **kwargs) # return_dict = { # 'count_each_diode':count_each_diode, # count of each diode # 'slice_length':slice_length, # slice (time) direction # 'diode_length':diode_length, # diode direction # 'shadowed_area':shadowed_pixel, # 'touching_image_edge':touching_image_edge, # 0 - no touch, 1 - touch one edge, 2 - touch both edges # 'center_in':center_in, # 'all_in':all_in, # 'hollow_status':hollow_status, # 'holroyd_habit':holroyd_habit, # 'F_fine_detail':F_fine_detail, # 'diameter_correction_factor':diameter_correction_factor, # 'area_hole_ratio':area_hole_ratio, # 'edge_at_max_hole':edge_at_max_hole, # 'max_hole_diameter':max_hole_diameter, # 'aspect_ratio':aspect_ratio, # 'percent_shadow_area':percent_shadow_area, # 'reject_status':reject_status, # 'fit_maj_axis':d_length, # 'fit_min_axis':w_width, # 'fit_angle':np.radians(angle_deg), # 'fit_r2':r2_correlation, # 'F_fine_detail':F_fine_detail, # 'S_ratio':S_ratio, # } # # Reject_status code: # - '0' = not rejected # - 'a' = reject max. aspect ratio # - 't' = reject max. aspect ratio touch edg # - 'p' = reject percent shadowed area # - 'h' = reject Hollow image # - 's' = reject split image # - 'z' = reject 0 area image # - 'f' = reject fake 0 area image #-- Calculate maximum dimension (diameter of minimum enclosing circle) # Added TAS ratio support, Yongjie Huang, 2024-04-17. min_circle_center_x, min_circle_center_y, min_circle_radius = min_enclosing_circle(image_buffer, particle_mask=particle_mask, tas_ratio=tasRatio) Dmax = 2 * min_circle_radius + 1 # diameter (pixel) of minimum enclosing circle, assume round doide, add 1 for the boundary ctx = min_circle_center_x cty = min_circle_center_y # Calculate arearatio_filled in image-space only (without TAS ratio) if hasattr(image_buffer, 'values'): image_data = image_buffer.values else: image_data = image_buffer image_filled = ndimage.binary_fill_holes(image_data == particle_mask) filled_area_pixels = np.sum(image_filled) circ_area_pixels = (np.pi / 4.0) * Dmax**2 arearatio_filled = float(np.clip(filled_area_pixels / circ_area_pixels, 0.0, 1.0)) if circ_area_pixels > 0 else 0.0 #-- Option to calculate parameters of rotated rectangle and ellipse if iRectEllipse == 1: (_, _), (RectangleL, RectangleW), RectangleAngle = min_enclosing_rotated_rectangle(image_buffer, particle_mask=particle_mask) (_, _), (EllipseL, EllipseW), EllipseAngle = min_enclosing_ellipse(image_buffer, particle_mask=particle_mask) data_dict['ParticleRectangleLength'] = RectangleL * diode_size data_dict['ParticleRectangleWidth'] = RectangleW * diode_size data_dict['ParticleRectangleAngle'] = RectangleAngle data_dict['ParticleEllipseLength'] = EllipseL * diode_size data_dict['ParticleEllipseWidth'] = EllipseW * diode_size data_dict['ParticleEllipseAngle'] = EllipseAngle #-- Calculate the Darea (area-equivalent diameter) # Darea, the equivalent diameter of the shaded area 'Sarea' of the image, that is, Darea = 2 * sqrt(Sarea/pi). Darea = 2 * np.sqrt(params_dict['shadowed_area'] / np.pi / tasRatio) # To do: update it considering tasRatio in future # Perimeter = particle_perimeter(image_buffer, particle_mask=particle_mask, boundary='all') / np.sqrt(tasRatio) # Perimeter = particle_perimeter(image_buffer, particle_mask=particle_mask, boundary='all') # in [pixel] Perimeter = particle_perimeter(image_buffer, particle_mask=particle_mask, boundary='outer') # in [pixel] if Perimeter == 0: sphericity = np.nan else: sphericity = np.sqrt(params_dict['shadowed_area']/tasRatio)/Perimeter # Perform Korolev correction for the Poisson Spot effect, only for all-in spherical particle D_korolev = Dmax if params_dict['touching_image_edge'] == 0 and \ params_dict['hollow_status'] == 1 and \ params_dict['holroyd_habit'] == 's': D_korolev = Dmax * params_dict['diameter_correction_factor'] #=== Save parameters to data_dict data_dict['time'] = time data_dict['time_sec'] = time_sec data_dict['time_ns'] = time_ns # data_dict['SliceCount'].append() # data_dict['Particle_number_all'].append() # data_dict['position'].append() # data_dict['ParticleTime'].append() # data_dict['ParticleMillisec'].append() # data_dict['ParticleMicrosec'].append() # data_dict['ParentRecordNumber'].append() # data_dict['ParticleNumber'].append(ip) data_dict['ParticleLength'] = params_dict['slice_length'] data_dict['ParticleWidth'] = params_dict['diode_length'] data_dict['ParticleArea'] = params_dict['shadowed_area'] * diode_size * diode_size / tasRatio # data_dict['ParticleLongestY'] = longest_y_within_a_slice # data_dict['ParticleMaxTopEdgeTouching'] = max_top_edge_touching # data_dict['ParticleMaxBottomEdgeTouching'] = max_bottom_edge_touching data_dict['ParticleTouchingEdge'] = params_dict['touching_image_edge'] data_dict['ParticleAutoReject'] = params_dict['reject_status'] data_dict['ParticleIsHollow'] = params_dict['hollow_status'] # data_dict['ParticleCenterIn'] = params_dict['center_in'] data_dict['ParticleAxisRatio'] = params_dict['aspect_ratio'] data_dict['ParticleDiameter_MinR'] = Dmax * diode_size data_dict['ParticleDiameter_AreaR'] = Darea * diode_size data_dict['ParticlePerimeter'] = Perimeter * diode_size data_dict['PercentShadowArea'] = params_dict['percent_shadow_area'] data_dict['EdgeAtMaxHole'] = params_dict['edge_at_max_hole'] data_dict['MaxHoleDiameter'] = params_dict['max_hole_diameter'] # data_dict['ParticleDepth'] = part_z data_dict['DiameterCorrectionFactor'] = params_dict['diameter_correction_factor'] data_dict['HolroydHabit'] = params_dict['holroyd_habit'] # data_dict['FineDetailRatio'] = params_dict['F_fine_detail'] data_dict['sphericity'] = sphericity data_dict['AreaHoleRatio'] = params_dict['area_hole_ratio'] data_dict['AreaRatioFilled'] = arearatio_filled # data_dict['InterArrivalTime'] = seconds_since_start[ip]-seconds_since_start[ip-1] if ip>0 else 0 data_dict['InterArrivalTime'] = InterArrivalTime # data_dict['DiodeStats'] = diode_stats # data_dict['ParticleDiodeStats'] = #-- Option to save all diode stats if iCalcAllDiodeStats: data_dict['ParticleDiodeStats'] = params_dict['count_each_diode'] # np.sum(image_buffer.values==particle_mask, axis=0) # ParticleDiodeStats('diode') #--- Level-1 data_dict['N_p'] = params_dict['diode_length'] data_dict['N_t'] = params_dict['slice_length'] data_dict['N_eq'] = Darea data_dict['N_s'] = Dmax data_dict['N_h'] = np.sqrt(data_dict['N_p']**2 + data_dict['N_t']**2) data_dict['N_m'] = (data_dict['N_p'] + data_dict['N_t']) * 0.5 # data_dict['N_slice_count'] = # data_dict['N_slice_diff'] = # data_dict['N_reconst'] = data_dict['N_hole'] = params_dict['max_hole_diameter'] # data_dict['N_korolev'] = data_dict['area_pixels'] = params_dict['shadowed_area'] data_dict['perimeter'] = Perimeter # data_dict['bbox'] = # data_dict['l_edge_count'] = # data_dict['r_edge_count'] = data_dict['center_in'] = params_dict['center_in'] data_dict['all_in'] = params_dict['all_in'] if iRectEllipse == 1: data_dict['ellipse_maj_axis'] = EllipseL data_dict['ellipse_min_axis'] = EllipseW data_dict['ellipse_angle'] = np.radians(EllipseAngle) data_dict['fit_maj_axis'] = params_dict['fit_maj_axis'] data_dict['fit_min_axis'] = params_dict['fit_min_axis'] data_dict['fit_angle'] = params_dict['fit_angle'] data_dict['fit_r2'] = params_dict['fit_r2'] data_dict['F'] = params_dict['F_fine_detail'] data_dict['S'] = params_dict['S_ratio'] #--- Level-1 data_dict['D_p'] = params_dict['diode_length'] * diode_size * 1e3 # [um] data_dict['D_t'] = params_dict['slice_length'] * diode_size * 1e3 # [um] data_dict['D_eq'] = Darea * diode_size * 1e3 # [um] data_dict['D_s'] = Dmax * diode_size * 1e3 # [um] data_dict['D_h'] = data_dict['N_h'] * diode_size * 1e3 # [um] data_dict['D_m'] = data_dict['N_m'] * diode_size * 1e3 # [um] # data_dict['D_slice_count'] = # data_dict['D_slice_diff'] = # data_dict['D_reconst'] = data_dict['D_hole'] = params_dict['max_hole_diameter'] * diode_size * 1e3 # [um] data_dict['D_korolev'] = D_korolev * diode_size * 1e3 # [um] if iRectEllipse == 1: data_dict['ellipse_maj_axis_um'] = EllipseL * diode_size * 1e3 # [um] data_dict['ellipse_min_axis_um'] = EllipseW * diode_size * 1e3 # [um] data_dict['fit_maj_axis_um'] = params_dict['fit_maj_axis'] * diode_size * 1e3 # [um] data_dict['fit_min_axis_um'] = params_dict['fit_min_axis'] * diode_size * 1e3 # [um] data_dict['area'] = params_dict['shadowed_area'] * (diode_size*1e3) * (diode_size*1e3) / tasRatio # [um^2] # data_dict['KorolevHabit'] = return data_dict
[docs] def process_particle_chunk( chunk_id: int, start_idx: int, end_idx: int, chunk_images_numpy: np.ndarray, local_slice_starts: np.ndarray, local_slice_ends: np.ndarray, times_local: np.ndarray, times_sec_local: np.ndarray, times_ns_local: np.ndarray, inter_arrival_times_local: np.ndarray, diode_size: float, diode_num: int, particle_mask: int, iRectEllipse: int, iCalcAllDiodeStats: int, total_images: int | None = None, ) -> list[dict]: """ Processes a chunk of particle images in a single parallel worker. Parameters ---------- chunk_id : int The identifier of the chunk being processed. start_idx : int The starting global index of the particles in this chunk. end_idx : int The ending global index (exclusive) of the particles in this chunk. chunk_images_numpy : np.ndarray A 2D NumPy array containing the raw image slice data for all particles in this chunk. local_slice_starts : np.ndarray A 1D array of local start slice indices within chunk_images_numpy for each particle. local_slice_ends : np.ndarray A 1D array of local end slice indices within chunk_images_numpy for each particle. times_local : np.ndarray A 1D array of capture times for the particles in this chunk. times_sec_local : np.ndarray A 1D array of capture times in seconds for the particles in this chunk. times_ns_local : np.ndarray A 1D array of capture times in nanoseconds for the particles in this chunk. inter_arrival_times_local : np.ndarray A 1D array of inter-arrival times for the particles in this chunk. diode_size : float The physical size of a single diode/pixel, in millimeters. diode_num : int The total number of diodes in the imaging array. particle_mask : int The value used to identify particles within the image. iRectEllipse : int Whether to calculate enclosing rectangle and ellipse properties. iCalcAllDiodeStats : int Whether to calculate detailed statistics for each diode. total_images : int, optional Total number of particle images in the dataset, forwarded to each particle worker for debug progress reporting. Returns ------- list of dict A list of dictionaries, where each dictionary contains the calculated level-1 metrics for a particle in this chunk. History: -------- - 2026-07-04: Created by Yongjie Huang to support coarse-grained parallel processing. """ results = [] for local_i, ip in enumerate(range(start_idx, end_idx)): # Slice chunk_images_numpy locally for this particle start_slice = local_slice_starts[local_i] end_slice = local_slice_ends[local_i] img_slice_numpy = chunk_images_numpy[start_slice:end_slice, :] # Convert to local xr.DataArray image_buffer = xr.DataArray( img_slice_numpy, dims=('slice', 'diode') ) # Process the particle image res = process_ith_particle_image( ip, times_local[local_i], times_sec_local[local_i], times_ns_local[local_i], inter_arrival_times_local[local_i], image_buffer, diode_size, diode_num, particle_mask, iRectEllipse, iCalcAllDiodeStats, total_images, ) results.append(res) return results
def _chunk_ranges_by_particle_count(image_num: int, n_chunks: int) -> list[tuple[int, int]]: """Split particles into contiguous chunks with similar particle counts. Parameters ---------- image_num : int The total number of particles (images) to be chunked. n_chunks : int The target number of chunks to create. Returns ------- list of tuple of (int, int) A list of (start_ip, end_ip) index ranges representing each particle chunk. """ if image_num <= 0 or n_chunks <= 0: return [] # Ensure we don't request more chunks than there are particles n_chunks = min(n_chunks, image_num) # Calculate partition size (rounding up to include all elements) chunk_size = (image_num + n_chunks - 1) // n_chunks chunks = [] for k in range(n_chunks): start_ip = k * chunk_size end_ip = min(start_ip + chunk_size, image_num) # Avoid creating empty chunks if start_ip < end_ip: chunks.append((start_ip, end_ip)) return chunks def _chunk_ranges_by_slice_count(cumsum: np.ndarray, n_chunks: int) -> list[tuple[int, int]]: """Split particles into contiguous chunks with similar image-slice counts. This function load-balances the workload across workers. Instead of giving each chunk an equal number of particles, it partitions particle indices such that the sum of image slices in each chunk is roughly equal. This prevents worker stragglers when some particles are very large (have many slices) and others are tiny. Parameters ---------- cumsum : np.ndarray 1D array containing the cumulative image slice counts up to each particle index. n_chunks : int The target number of chunks to create. Returns ------- list of tuple of (int, int) A list of (start_ip, end_ip) index ranges representing load-balanced chunks. """ image_num = len(cumsum) if image_num <= 0 or n_chunks <= 0: return [] n_chunks = min(n_chunks, image_num) total_slices = int(cumsum[-1]) # Fallback to simple particle-count partitioning if no slices exist if total_slices <= 0: return _chunk_ranges_by_particle_count(image_num, n_chunks) # 1. Define ideal slice counts at each chunk boundary edge slice_edges = np.linspace(0, total_slices, n_chunks + 1) # 2. Map these ideal slice edges back to particle indices (ip) using binary search. # side='right' ensures that we include the crossing particle in the current chunk. chunk_bounds = np.searchsorted(cumsum, slice_edges, side='right') # 3. Force exact boundaries at the ends to prevent off-by-one or floating precision issues chunk_bounds[0] = 0 chunk_bounds[-1] = image_num chunks = [] for k in range(n_chunks): start_ip = int(chunk_bounds[k]) end_ip = int(chunk_bounds[k + 1]) # Avoid creating empty chunks (e.g. if a single particle is larger than target slice count) if start_ip < end_ip: chunks.append((start_ip, end_ip)) return chunks
[docs] def parallel_processing_images( args_list: list, num_workers: int = 8, parallel_method: str = 'concurrent_futures', *, worker_fn: Callable = process_ith_particle_image ) -> list: """ Processes images in parallel using various parallel processing methods. This function is designed to work with different parallel processing libraries to apply a specified image processing function across multiple images concurrently. It maps the image processing function to each set of arguments provided in `args_list`. Parameters ---------- args_list : list of tuple A list where each tuple contains the arguments to be passed to the image processing function. Each tuple should match the signature of the processing function except for the first argument, which is implicitly provided by iterating over `args_list`. num_workers : int, optional The number of worker processes or threads to use for parallel processing. Defaults to 8. This parameter is applicable to methods that support parallel execution, such as 'concurrent_futures', 'loky', 'pathos', 'dask', and 'ray'. parallel_method : str, optional The parallel processing method to use. Defaults to 'concurrent_futures'. Supported methods include: - 'concurrent_futures': Uses the concurrent.futures.ProcessPoolExecutor. - 'loky': Uses the loky.get_reusable_executor. - 'p_tqdm': Combines pathos and tqdm for parallel processing with progress bars. - 'pathos': Uses the pathos.multiprocessing.ProcessingPool. - 'dask': Utilizes dask.distributed.Client for distributed task execution. - 'ray': Employs Ray for distributed applications. If None or an unsupported value is provided, the function will print a warning and proceed with serial processing. worker_fn : Callable, optional The worker function to process the task arguments. Defaults to process_ith_particle_image. Returns ------- list A list of processed datasets, one for each set of arguments in `args_list`. Notes ----- The 'p_tqdm' method is particularly useful for progress tracking when dealing with functions that require serialization of more complex objects. The choice of parallel processing method may significantly impact performance and resource utilization, depending on the nature of the processing function and the complexity of the tasks. History ------- - 2026-07-03: Updated by Yongjie Huang to support customizable worker_fn and try/finally cleanup blocks. - 2024-03-28: Created by Yongjie Huang. """ futures = [] if parallel_method == 'concurrent_futures': from concurrent.futures import ProcessPoolExecutor # Note: The Global Interpreter Lock (GIL) in CPython limits the # ThreadPoolExecutor parallel processing in CPU-bound tasks. # Use ProcessPoolExecutor for parallel processing. # with ThreadPoolExecutor(max_workers=num_workers) as executor: with process_pool_logging() as logging_context: logger.info( "Processing %d image task(s) with %d worker process(es)", len(args_list), num_workers, ) with ProcessPoolExecutor( max_workers=num_workers, mp_context=logging_context.mp_context, initializer=configure_worker_logging, initargs=(logging_context.queue, logging_context.level), ) as executor: futures = [executor.submit(worker_fn, *args) for args in args_list] # Collect processed results while the queue listener remains active. processed_datasets = [future.result() for future in futures] elif parallel_method == 'loky': # pip install loky from loky import get_reusable_executor with get_reusable_executor(max_workers=num_workers) as executor: futures = [executor.submit(worker_fn, *args) for args in args_list] # Collect processed results processed_datasets = [future.result() for future in futures] elif parallel_method == 'p_tqdm': # same as pathos but have a progress bar (aka Pathos + tqdm) # pip install p_tqdm from p_tqdm import p_map def worker_fn_wrapper(args_tuple): return worker_fn(*args_tuple) # Execute the function in parallel and collect processed results processed_datasets = p_map(worker_fn_wrapper, args_list, num_cpus=num_workers) elif parallel_method == 'pathos': # pip install pathos from pathos.multiprocessing import ProcessingPool as Pool def worker_fn_wrapper(args_tuple): return worker_fn(*args_tuple) # Initialize the pool with the desired number of workers pool = Pool(num_workers) try: # Map function over the dataset groups processed_datasets = pool.map(worker_fn_wrapper, args_list) finally: pool.close() pool.join() pool.clear() elif parallel_method == 'dask': # pip install dask distributed from dask.distributed import Client # Initialize the Dask Client client = Client(n_workers=num_workers, threads_per_worker=1) try: # Use Dask Distributed to submit tasks for parallel processing futures = [client.submit(worker_fn, *args) for args in args_list] # Collect processed results processed_datasets = client.gather(futures) finally: # Shutdown client client.close() elif parallel_method == 'ray': # pip install ray import ray # Wrap the processing function for Ray's remote execution @ray.remote def worker_fn_wrapper(args_tuple): return worker_fn(*args_tuple) # Initialize Ray ray_initialized_by_cops = False if not ray.is_initialized(): ray.init(num_cpus=num_workers) ray_initialized_by_cops = True try: # Submit the task to Ray futures = [worker_fn_wrapper.remote(args) for args in args_list] # Wait for all tasks to complete and retrieve the results processed_datasets = ray.get(futures) finally: # Shutdown Ray if ray_initialized_by_cops: ray.shutdown() elif parallel_method == 'serial': processed_datasets = [worker_fn(*args) for args in args_list] else: logger.warning( "Parallel method %r is not implemented; processing serially", parallel_method, ) processed_datasets = [worker_fn(*args) for args in args_list] return processed_datasets
[docs] def calculate_particle_image_level1_variables_parallel(spif_attr, im_header, ds_images: xr.Dataset, config: ProbeProcessingConfig | ConfigParser, num_workers: int | None = None, parallel_method:str | None = None, chunking_method: str = "slice_count") -> xr.Dataset: #particle_mask=0, iRectEllipse=0, iCalcAllDiodeStats=0 """ Calculates level-1 variables from particle images, incorporating time information and various particle properties, then organizes these data into an xarray.Dataset. Parameters: ----------- spif_attr : object SPIF file attributes containing essential metadata, such as the measurement start date (`start_date`) and institution information. im_header : object Image header containing probe-specific metadata including diode array details (`pixels`, `resolution`) and instrument name. ds_images : xarray.Dataset Dataset containing particle image data and associated variables (`image_sec`, `image_ns`, and `image_len`). config : ProbeProcessingConfig | configparser.ConfigParser Configuration object or parser containing user-defined settings. Relevant configuration parameters include: - `particle_mask` (int): Value identifying particle pixels within images (default=0). - `iRectEllipse` (int): Flag to calculate bounding rectangle and ellipse metrics (default=0). - `iCalcAllDiodeStats` (int): Flag to determine whether to compute statistics for all diodes. num_workers : int, optional Number of parallel workers (processes or threads) to use. If None, the maximum number of available CPU cores will be used (default: None). parallel_method : str, optional Method for parallel computation. Supported options: 'concurrent_futures', 'loky', 'pathos', 'dask', 'ray'. Defaults to 'concurrent_futures' if not specified. chunking_method : str, optional Chunking strategy for grouping particles into worker tasks. Supported options are 'slice_count' (default, balances chunks by total image slices), 'particle_count' (balances chunks by number of particles), and 'legacy_one_particle' (original one-task-per-particle method for comparison). Returns ------- ds_out : xarray.Dataset An xarray Dataset containing calculated Level-1 particle properties along with time-related variables, structured with dimensions including `particle`, `diode`, and other relevant coordinates. Examples -------- Compute Level-1 particle metrics from SPIF image data: >>> ds_out = calculate_particle_image_level1_variables_parallel(spif_attr, im_header, ds_images, config, num_workers=8, parallel_method='loky') Notes ----- - This function requires an external configuration `.ini` file defining critical parameters for particle analysis. - The computed dataset includes detailed time metrics derived from image timestamps. - Results retain the original core-group particle order after parallel processing so per-particle variables remain positionally aligned even when timestamps are non-monotonic. History ------- - 2024-03-28: Yongjie Huang (huangynj@gmail.com), initial implementation with parallel processing. - 2024-04-16: Yongjie Huang, added option `iCalcAllDiodeStats`. - 2025-03-14: Yongjie Huang, transitioned explicit parameters (`particle_mask`, `iRectEllipse`, `iCalcAllDiodeStats`) to an external configuration file-based approach. - 2026-07-04: Yongjie Huang, added load-balanced chunking partitioned by cumulative image slice count. """ # Extract configuration settings from ProbeProcessingConfig cfg = ensure_probe_config(config) particle_mask = cfg.image.particle_mask iRectEllipse = cfg.image.iRectEllipse iCalcAllDiodeStats = cfg.image.iCalcAllDiodeStats # Retrieve metadata from SPIF file attributes start_date_str = spif_attr.start_date.strip() diode_num = im_header.pixels.values diode_size = float(im_header.resolution.values) * 1e-3 # [um] -> [mm]; Python float keeps float64 on NumPy 1 and 2 # Initialize variables dictionary for storing level-1 calculations variables_dict = copy.deepcopy(LEVEL_1_VARIABLES) #--- Process time-related variables # Adjust the 'time_sec' attribute to include the start date in UTC variables_dict['time_sec']['attrs']['start_date'] = start_date_str.strip() + ' UTC' time_sec = ds_images['image_sec'].values # 'seconds (int) since start_date' time_ns = ds_images['image_ns'].values # 'ns since time_sec' # Convert time data to datetime objects based on SPIF metadata start_date = datetime.strptime(start_date_str.strip(), '%Y-%m-%d %H:%M:%S') additional_seconds = time_ns * 1e-9 # Convert nanoseconds to seconds seconds_since_start = time_sec + additional_seconds datetimes = [start_date + timedelta(seconds=sec) for sec in seconds_since_start] # Convert the seconds_since_start to datetime objects # Calculate InterArrivalTime (time between consecutive particle detections) if len(seconds_since_start) > 0: InterArrivalTime = np.diff(seconds_since_start, prepend=seconds_since_start[0]) # Make 0 for the 1st particle else: InterArrivalTime = np.array([], dtype=float) # Convert datetime objects to a numeric time format for compatibility with NetCDF time_units = variables_dict['time']['attrs']['units'] # "seconds since 1970-01-01 00:00:00" if len(datetimes) > 0: time = date2num(datetimes, units=time_units) # convert these datetime objects to a numeric time format for NetCDF else: time = np.array([], dtype=float) #--- Process particle images # Prepare particle image data for parallel processing images_all = xr.DataArray(ds_images.image.data.reshape(-1, diode_num), dims=('slice', 'diode')) image_len = ds_images.image_len # len in slice of each particle cumsum = image_len.cumsum().values slice_starts = np.insert(cumsum, 0, 0)[:-1] # Insert 0 at the beginning and exclude the last value slice_ends = cumsum image_num = ds_images.sizes['Images'] # Total number of images # If num_workers is not specified, all CPU cores will be used. if num_workers is None: num_cpu_cores = multiprocessing.cpu_count() logger.info("Using all available CPU cores: num_cpu_cores=%s", num_cpu_cores) num_workers = num_cpu_cores if num_workers < 1: raise ValueError(f"num_workers must be >= 1, got {num_workers}") if parallel_method is None: parallel_method = 'concurrent_futures' valid_chunking_methods = {"slice_count", "particle_count", "legacy_one_particle"} if chunking_method not in valid_chunking_methods: raise ValueError( "chunking_method must be 'slice_count', 'particle_count', or " f"'legacy_one_particle', got {chunking_method!r}" ) effective_workers = num_workers if parallel_method != 'serial' else 1 if image_num > 0: if chunking_method == "legacy_one_particle": images_list = [ images_all.isel(slice=slice(start, end)) for start, end in zip(slice_starts, slice_ends) ] # Prepare arguments for parallel processing function `process_ith_particle_image` # def process_ith_particle_image(ip, time, time_sec, time_ns, InterArrivalTime, image_buffer, # diode_size, diode_num, particle_mask=0, iRectEllipse=0, # iCalcAllDiodeStats=0, total_images=None): job_args = [ (ip, time[ip], time_sec[ip], time_ns[ip], InterArrivalTime[ip], images_list[ip], diode_size, diode_num, particle_mask, iRectEllipse, iCalcAllDiodeStats, image_num) for ip in range(image_num) ] results = parallel_processing_images( job_args, num_workers=num_workers, parallel_method=parallel_method, worker_fn=process_ith_particle_image, ) else: # Use 4x worker chunks to reduce process scheduling overhead while keeping enough tasks # for the executor to smooth uneven particle image lengths. n_chunks = effective_workers * 4 if chunking_method == "slice_count": chunks = _chunk_ranges_by_slice_count(cumsum, n_chunks) else: chunks = _chunk_ranges_by_particle_count(image_num, n_chunks) job_args = [] for chunk_id, (start_ip, end_ip) in enumerate(chunks): # Extract slices range for this chunk (as a numpy view) global_start_slice = slice_starts[start_ip] global_end_slice = slice_ends[end_ip - 1] chunk_images_numpy = images_all.values[global_start_slice:global_end_slice, :] # Local slice offsets local_slice_starts = slice_starts[start_ip:end_ip] - global_start_slice local_slice_ends = slice_ends[start_ip:end_ip] - global_start_slice job_args.append(( chunk_id, start_ip, end_ip, chunk_images_numpy, local_slice_starts, local_slice_ends, time[start_ip:end_ip], time_sec[start_ip:end_ip], time_ns[start_ip:end_ip], InterArrivalTime[start_ip:end_ip], diode_size, diode_num, particle_mask, iRectEllipse, iCalcAllDiodeStats, image_num, )) # Execute parallel chunk processing and retrieve results results_chunked = parallel_processing_images( job_args, num_workers=num_workers, parallel_method=parallel_method, worker_fn=process_particle_chunk ) # Flatten the list of lists of results results = [] for res_list in results_chunked: results.extend(res_list) else: results = [] # Keep the original SPIF core-group particle order. Every parallel backend above # returns results in submission order, while particle timestamps may be non-monotonic. # Sorting by time would misalign Level-1 records with position-aligned core variables # (for example tas, Pres, and Temp) and with file-order InterArrivalTime values. # results.sort(key=lambda x: x['time']) # Initialize a dictionary to store data for each variable # DATA = {} # for key in variables_dict.keys(): # DATA[key] = [] DATA = {key: [] for key in variables_dict.keys()} # Process results in original particle order for result in results: for key, value in result.items(): DATA[key].append(value) #--- Create output Dataset ds_out = xr.Dataset() # Define Dataset dimensions and coordinates ds_out = ds_out.assign_coords(particle=('particle', range(image_num))) # Empty list for unlimited dimension ds_out = ds_out.assign_coords(diode=('diode', range(diode_num))) ds_out = ds_out.assign_coords(slice_pos=('slice_pos', range(2))) ds_out = ds_out.assign_coords({'coords':range(4)}) ds_out['particle'].attrs['description'] = 'particle dimension' ds_out['diode'].attrs['description'] = 'diode dimension' # Add global attributes ds_out.attrs['Software'] = f'COPS V{__version__}' ds_out.attrs['Institution'] = spif_attr.institution ds_out.attrs['Creation_Time'] = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f') ds_out.attrs['Description'] = 'Contains size, morphological, and other particle properties from core group image data.' ds_out.attrs['Project'] = spif_attr.project.strip() ds_out.attrs['Probe_Type'] = im_header.instrument_name.strip() #ds_out.attrs['Image Source'] = input_spif_path ds_out.attrs['diode_size'] = float(diode_size) # Populate dataset with computed variables for key, values in variables_dict.items(): # # Check if dims is a single string or a list/tuple, and ensure it is a list # dims = [values['dims']] if isinstance(values['dims'], str) else values['dims'] # # Use a list comprehension to construct dim_tuple # dim_tuple = tuple(ds_out.sizes[dim] for dim in dims) # # Ensure 'coords' dimension exists if you intend to use it # if 'coords' not in ds_out.dims: # ds_out = ds_out.assign_coords({'coords': np.arange(4)}) # Create and assign the DataArray if len(DATA[key]) > 0: dims = [values['dims']] if isinstance(values['dims'], str) else values['dims'] dim_tuple = tuple(ds_out.sizes[dim] for dim in dims) logger.debug("Adding %r with dimensions %s", key, dim_tuple) ds_out[key] = xr.DataArray(data=np.array(DATA[key], dtype=values['dtype']), dims=dims, attrs=values['attrs']) # else: # ds_out[key] = xr.DataArray(data=np.zeros(dim_tuple, dtype=values['dtype']), dims=dims, attrs=values['attrs']) return ds_out
def _guard_existing_group(input_spif_path: str, output_spif_path: str, group: str, subgroup: str, allow_missing_config: bool, config_path: str | None, allow_cwd_fallback: bool) -> None: """Raise StaleOutputError if an existing ``group/subgroup`` would be reused incompatibly. COPS skips groups that already hold Level-1/Level-2 data. The skip is safe only when the existing group was made with the same diameter selection and ML outputs as the current request (see :mod:`cops.ml.sizing.selection`). An explicit ``config_path`` that does not exist always raises. When no configuration is found implicitly, the legacy skip is kept only for groups without ML provenance; an existing ML group whose request cannot be verified raises StaleOutputError. History: -------- - 2026-10-16: Added for optional ML size correction (stale-output protection). """ with Dataset(output_spif_path, 'r') as nc: node = nc[f'{group}/{subgroup}'] existing_attrs = {name: node.getncattr(name) for name in node.ncattrs()} spif_attr = im_header = None try: spif_attr = io.read_spif_header(input_spif_path).load() im_header = io.read_spif_header(input_spif_path, group=group).load() probe_name = resolve_probe_config_name(im_header.instrument_name, im_header.resolution.values) try: cfg = load_probe_config(input_spif_path, spif_attr.project, probe_name, allow_missing=allow_missing_config, config_path=config_path, allow_cwd_fallback=allow_cwd_fallback) except FileNotFoundError: if config_path is not None: raise if has_ml_provenance(existing_attrs) or has_ml_classification_provenance(existing_attrs): raise StaleOutputError( f"{output_spif_path}:{group}/{subgroup} holds ML-derived output, but no " "configuration was found to verify that reuse is compatible") return # legacy: no configuration, raw output -> skip as before selection, ml_outputs, selected = requested_ml_sizing_records( cfg, InstrumentIdentity.from_header(im_header, group), subgroup) class_outputs, phase_selection = requested_ml_classification_records( cfg, InstrumentIdentity.from_header(im_header, group), subgroup) finally: for ds in (spif_attr, im_header): if ds is not None: ds.close() where = f"{output_spif_path}:{group}/{subgroup}" check_existing_ml_classification(existing_attrs, class_outputs, phase_selection, where, selection) if subgroup == 'level-1': check_existing_level1(existing_attrs, selection, ml_outputs, selected, where) else: check_existing_level2(existing_attrs, selection, ml_outputs, where) def _preflight_ml_groups(input_spif_path: str, groups, level: str, allow_missing_config: bool, config_path: str | None, allow_cwd_fallback: bool) -> None: """Validate ML sizing/classification of every group before any output file is created. Level-1: for each group with data whose configuration enables ``[ml_sizing]`` or ``[ml_classification]``, bundle, population mode, routing, runtime and model checksums. Level-2: for each group with data, the requested selection against the Level-1 ML, bulk and persisted ``D_selected`` provenance (also for ML-disabled requests, so stale ML Level-1 data are refused). Groups without data or without a configuration are left to the processing loop, which handles them exactly as before. History: -------- - 2026-10-17: Added for split-population ML sizing (fail before output creation). - 2026-10-28: Also preflights ML classification bundles and Level-2 phase reuse. """ for group in groups: sub = 'core' if level == 'level-1' else 'level-1' with Dataset(input_spif_path, 'r') as nc: node = nc[f'{group}/{sub}'] dim = 'Images' if level == 'level-1' else 'particle' # NetCDF groups see dimensions defined in any ancestor group (SPIF core groups # usually inherit 'Images' from the probe group). size, scope = 0, node while scope is not None: if dim in scope.dimensions: size = scope.dimensions[dim].size break scope = scope.parent if size == 0: continue l1_attrs = {k: node.getncattr(k) for k in node.ncattrs()} if level == 'level-2' else None l1_has_phase = level == 'level-2' and any(v in node.variables for v in ( 'particle_phase', 'particle_mass_liquid', 'particle_vt_liquid', 'particle_pr_liquid')) l1_has_bulk = level == 'level-2' and 'particle_mass' in node.variables \ and 'area_ratio' in node.variables spif_attr = im_header = None try: spif_attr = io.read_spif_header(input_spif_path).load() im_header = io.read_spif_header(input_spif_path, group=group).load() probe_name = resolve_probe_config_name(im_header.instrument_name, im_header.resolution.values) try: cfg = load_probe_config(input_spif_path, spif_attr.project, probe_name, allow_missing=allow_missing_config, config_path=config_path, allow_cwd_fallback=allow_cwd_fallback) except FileNotFoundError: continue if level == 'level-1' and not (cfg.ml.enabled or cfg.classification.enabled): continue instrument = InstrumentIdentity.from_header(im_header, group) if level == 'level-1': preflight_ml_sizing(cfg, instrument) preflight_ml_classification(cfg, instrument) else: selection, _, _ = requested_ml_sizing_records(cfg, instrument, 'level-2') check_level2_inputs(l1_attrs, l1_has_bulk, selection, where=f"{input_spif_path}:{group}") # Unknown (unrecorded) settings warn later, in the Level-2 driver. check_level2_qc_settings(l1_attrs, l1_has_bulk, qc_settings_record(cfg.size), where=f"{input_spif_path}:{group}", warn_unknown=False) class_outputs, phase_selection = requested_ml_classification_records(cfg, instrument, 'level-2') check_ml_classification_level2_inputs(l1_attrs, l1_has_phase, class_outputs, phase_selection, f"{input_spif_path}:{group}") finally: for ds in (spif_attr, im_header): if ds is not None: ds.close()
[docs] def process_spif_image_append_level1_data(input_spif_path: str, output_spif_path: str | None = None, num_workers: int | None = None, parallel_method: str | None = None, chunking_method: str = "slice_count", allow_missing_config: bool = False, config_path: str | None = None, allow_cwd_fallback: bool = False, tas: float | np.ndarray | xr.DataArray | list[float] | tuple[float, ...] | None = None) -> None: """ Processes SPIF (Single Particle Image Format) image data and appends Level-1 data to a specified or the same output NetCDF file. This function reads SPIF formatted data from the input file, processes the images to calculate Level-1 variables for each particle, and appends these variables to an output NetCDF file. Level-1 data includes various metrics and descriptors for individual particles, prepared for further analysis. Parameters ---------- input_spif_path : str Path to the input SPIF (Single Particle Image Format) NetCDF file containing the 'core' image data. output_spif_path : str, optional Path to the output NetCDF file where the processed Level-1 data will be appended. If not specified, the input_spif_path will be used as the output, effectively updating the input file. num_workers : int, optional Number of worker processes or threads to use for parallel processing of images. If None, a default number of workers is chosen based on the system's available resources. parallel_method : str, optional The parallel processing method to use. Supports 'concurrent_futures', 'loky', 'pathos', 'dask', and 'ray'. If None, 'concurrent_futures' is used by default. Each method offers different performance characteristics and operational modes, which can be chosen based on the computational environment and specific needs. chunking_method : str, optional Chunking strategy for Level-1 particle image processing. Use 'slice_count' to balance chunks by total image slices (default), 'particle_count' to balance chunks by number of particles, or 'legacy_one_particle' to use the original one-task-per-particle method for comparison. allow_missing_config : bool, optional If True, the system will allow proceeding with default fallback parameters when the external `.ini` configuration file is missing instead of raising a FileNotFoundError. Defaults to False. config_path : str, optional Path to a specific configuration file. If provided, the configuration is loaded directly from this file. Defaults to None. allow_cwd_fallback : bool, optional If True, allows falling back to loading the configuration file from the current working directory if it is not found adjacent to the SPIF file. Defaults to False. tas : float, 1D array, or xarray.DataArray, optional True airspeed in [m s-1] to use when the SPIF core group does not contain ``tas``. A scalar is broadcast; an untimed array is assumed to match particle order and emits a warning; a time-aware DataArray is interpolated to particle timestamps with nearest-endpoint extrapolation. Core-group TAS takes precedence. Returns ------- None This function does not return a value. It writes the processed Level-1 data directly to the output NetCDF file. Examples -------- Processing a SPIF file and appending Level-1 data to the same file: >>> process_spif_image_append_level1_data('path/to/input_spif.nc') Processing a SPIF file with parallel processing and writing to a new file: >>> process_spif_image_append_level1_data('path/to/input_spif.nc', 'path/to/output_spif.nc', num_workers=4, parallel_method='loky') Processing a file without core TAS using a user-supplied constant: >>> process_spif_image_append_level1_data('path/to/input_spif.nc', tas=100.0) Notes ----- - The function operates in-place if no output_spif_path is provided. - Parallel processing can significantly speed up the processing of large datasets. - Ensure the input SPIF file follows the expected format with 'core' and 'level-1' (optionally) groups properly defined. - Configuration parameters previously provided explicitly (e.g., `particle_mask`, `iRectEllipse`, `iCalcAllDiodeStats`) are now set via the external configuration file. - The function reads probe-specific configuration settings from an `.ini` file named as `{project_name}.{probe_name}.ini`. This file should be placed in the current working directory. History ------- - 2026-07-17: Yongjie Huang, added aligned-array and time-aware TAS fallback inputs. - 2026-07-16: Yongjie Huang, added a user-supplied constant TAS fallback for files without core TAS. - 2026-07-06: Yongjie Huang, updated to write phase classification configuration parameters to Level-1 NetCDF attributes. - 2026-07-03: Updated by Yongjie Huang to expose config_path and allow_cwd_fallback. - 2024-03-05: Yongjie Huang (huangynj@gmail.com), first implementation. - 2024-03-28: Yongjie Huang (huangynj@gmail.com), added parallel processing function. - 2024-04-16: Yongjie Huang (huangynj@gmail.com), added option 'iCalcAllDiodeStats'. - 2025-03-14: Yongjie Huang (huangynj@gmail.com), replaced explicit function arguments (e.g., 'particle_mask', 'iRectEllipse', 'iCalcAllDiodeStats') with an external configuration file. """ # Open the NetCDF file to get all groups with specified subgroups ('core' and 'level-1') with Dataset(input_spif_path, 'r') as nc: groups_core = return_groups_with_specified_subgroup(nc, 'core') groups_lvl1 = return_groups_with_specified_subgroup(nc, 'level-1') # Check if there is any 'core' group in the file if len(groups_core) == 0: logger.warning("No image data to process") return # Optional ML sizing/classification: an invalid bundle, population mode, routing or # model fails here, before an output file is created. _preflight_ml_groups(input_spif_path, groups_core, 'level-1', allow_missing_config, config_path, allow_cwd_fallback) # Determine the output SPIF path, create parent directory if it doesn't exist, and copy file if necessary if output_spif_path is None: output_spif_path = input_spif_path else: if not os.path.exists(output_spif_path): # Ensure the output file's parent directory exists parent_dir = os.path.dirname(output_spif_path) if parent_dir and not os.path.exists(parent_dir): os.makedirs(parent_dir) # Copy the input file to the output path if they are not the same shutil.copy2(input_spif_path, output_spif_path) else: # Open the output NetCDF file to get all groups with specified subgroups ('level-1') with Dataset(output_spif_path, 'r') as nc: groups_lvl1 = return_groups_with_specified_subgroup(nc, 'level-1') # Process image data for each 'core' group for group in groups_core: logger.info("Processing image data in %r", group) # Check if the group already contains level-1 data if group in groups_lvl1: # Skipping keeps the existing group; refuse it when its diameter/ML provenance # differs from this request (raises StaleOutputError). _guard_existing_group(input_spif_path, output_spif_path, group, 'level-1', allow_missing_config, config_path, allow_cwd_fallback) logger.warning("%r already has Level-1 data; skipping", group) continue # Read SPIF headers and images for the current group spif_attr = im_header = ds_images = None try: spif_attr = io.read_spif_header(input_spif_path).load() im_header = io.read_spif_header(input_spif_path, group=group).load() ds_images = io.read_spif_images(input_spif_path, group=group).load() # Check if there are images to process image_num = ds_images.sizes['Images'] if image_num == 0: logger.warning("No image data to process") continue # Load probe-specific configuration from external .ini file project_name = spif_attr.project probe_name = resolve_probe_config_name( im_header.instrument_name, im_header.resolution.values ) loaded_config = load_probe_config(input_spif_path, project_name, probe_name, allow_missing=allow_missing_config, config_path=config_path, allow_cwd_fallback=allow_cwd_fallback) # Calculate level-1 variables for the particle images ds_out = calculate_particle_image_level1_variables_parallel(spif_attr, im_header, ds_images, loaded_config, num_workers=num_workers, parallel_method=parallel_method, chunking_method=chunking_method) #--- Optional ML models (cops.ml.combined): sizing writes D_s_<family>, # classification writes ml_p_<class>_<family>/ml_phase_<family>. When both # are enabled they share one bounded feature stream. Runs in the # coordinating process before bulk/QC (which may use the ML diameter or # phase), including geometry-only output; each model keeps its own preprocessing. ds_out = add_level1_ml_outputs( ds_out, ds_images, loaded_config, InstrumentIdentity.from_header(im_header, group)) #--- Apply Level-1 bulk properties & and inter-arrival time quality control (QC) ds_out = apply_level1_bulk_properties_and_qc(ds_out, ds_images, loaded_config, tas=tas) ds_out.attrs.update(loaded_config.provenance.attrs) ds_out.attrs.update(loaded_config.image.attrs_for_dataset()) finally: for ds in (spif_attr, im_header, ds_images): if ds is not None: ds.close() # Write the processed level-1 data to the output file logger.info("Writing Level-1 data to %r", output_spif_path) io.append_xarrayDataset_to_existing_NetCDF_file(nc_file_path=output_spif_path, ds_appended=ds_out, new_subgroup_name='level-1', parent_group=group, UNLIMITED_dims='particle') return
# Disabled serial Level-1 implementation retained for reference; the active # implementation is calculate_particle_image_level1_variables_parallel above. ''' def calculate_particle_image_level1_variables(spif_attr, im_header, ds_images, particle_mask=0, iRectEllipse=0): """ Calculates level-1 variables from particle images, incorporating time information and various particle properties, then organizes this data into an xarray.Dataset. Parameters: ----------- spif_attr: SPIF file attributes containing metadata such as start date. im_header: Image header information including diode number and resolution. ds_images: xarray Dataset containing images and associated data like image timestamps. particle_mask: Value used to identify particles within images (default=0). iRectEllipse: Flag indicating whether to calculate bounding rectangle and ellipse metrics (default=0). Returns: -------- ds_out: xarray.Dataset containing calculated particle properties and time information. History: -------- - 2024-03-05: Created by Yongjie Huang (huangynj@gmail.com) Note: ----- This function has been deprecated, use 'calculate_particle_image_level1_variables_parallel' instead. """ start_date_str = spif_attr.start_date.strip() diode_num = im_header.pixels.values diode_size = im_header.resolution.values * 1e-3 # [um] -> [mm] variables_dict = copy.deepcopy(LEVEL_1_VARIABLES) # Initialize a dictionary to store data for each variable DATA = {} for key in variables_dict.keys(): DATA[key] = [] #--- Process time variables # Adjust the 'time_sec' attribute to include the start date in UTC variables_dict['time_sec']['attrs']['start_date'] = start_date_str.strip() + ' UTC' time_sec = ds_images['image_sec'].values # 'seconds (int) since start_date' time_ns = ds_images['image_ns'].values # 'ns since time_sec' # Convert time data to datetime objects start_date = datetime.strptime(start_date_str.strip(), '%Y-%m-%d %H:%M:%S') additional_seconds = ds_images['image_ns'].values * 1e-9 # Convert nanoseconds to seconds seconds_since_start = ds_images['image_sec'].values + additional_seconds datetimes = [start_date + timedelta(seconds=sec) for sec in seconds_since_start] # Convert the seconds_since_start to datetime objects # Convert datetime objects to a numeric time format for NetCDF time_units = variables_dict['time']['attrs']['units'] # "seconds since 1970-01-01 00:00:00" time = date2num(datetimes, units=time_units) # convert these datetime objects to a numeric time format for NetCDF #--- Process particle images images_all = xr.DataArray(ds_images.image.data.reshape(-1, diode_num), dims=('slice', 'diode')) image_len = ds_images.image_len cumsum = image_len.cumsum().values slice_starts = np.insert(cumsum, 0, 0)[:-1] # Insert 0 at the beginning and exclude the last value slice_ends = cumsum images_list = [images_all.isel(slice=slice(start, end)) for start, end in zip(slice_starts, slice_ends)] image_num = ds_images.sizes['Images'] # Total number of images for ip in tqdm(range(image_num), mininterval=1.): # image_buffer = io.get_ith_particle_image(im_header, ds_images, ip) image_buffer = images_list[ip] n_slices = image_buffer.sizes['slice'] # Determine the Particle Habit using the Holroyd algorithm count_each_slice = np.sum(image_buffer.values == particle_mask, axis=1) # count of each slice # if iCalcAllDiodeStats: # images['diode_stats'][bin_edges] = np.sum(image_buffer.values == particle_mask, axis=1) # Option to save diode stats for every particle # diode_stats += np.sum(~c, axis=1) # csum = np.sum(~c, axis=1) min_circle_center_x, min_circle_center_y, min_circle_radius = min_enclosing_circle(image_buffer) Dmax = 2 * min_circle_radius + 1 # diameter of minimum enclosing circle, assume round doide, add 1 for the boundary ctx = min_circle_center_x cty = min_circle_center_y # Improved [EXPERIMENTAL] particle hollow identification if Dmax * diode_size < 0.3 and \ np.sum(image_buffer[max(0, int(np.floor(ctx))):min(n_slices-1, int(np.ceil(ctx))), max(0, int(np.floor(cty))):min(diode_num, int(np.ceil(cty)))]==1)>0: holroyd_dict = holroyd(image_buffer, diode_size, diode_num, particle_mask=particle_mask) F_fine_detail = holroyd_dict['F_fine_detail'] holroyd_habit = 's' is_hollow = 1 else: holroyd_dict = holroyd(image_buffer, diode_size, diode_num, particle_mask=particle_mask) holroyd_habit = holroyd_dict['holroyd_habit'] F_fine_detail = holroyd_dict['F_fine_detail'] is_hollow = 0 # Determine if the particle is rejected or not and calculate various metrics # Calculate the Particle Length, Width, Area, Auto Reject # Status And more... See calculate_reject_unified() # funtion for more information (particle_length, particle_width, particle_area, longest_y_within_a_slice, max_top_edge_touching, max_bottom_edge_touching, particle_touching_image_edge, auto_reject, is_hollow, percent_shadow, part_z, size_factor, area_hole_ratio, max_hole_diameter, edge_at_max_hole, center_in) = calculate_reject_unified(image_buffer, holroyd_habit, is_hollow) image_area = np.sum(image_buffer.values == particle_mask) dist_to_edge = np.min([np.abs(diode_num - 1 - cty), np.abs(cty)]) # if center_in == 1 and particle_touching_image_edge != '0': # image_area = image_area * 2 * (particle_width - dist_to_edge) / particle_width tasRatio = 1. # Calculate the Darea (area-equivalent diameter) Darea = 2 * np.sqrt(image_area / np.pi / tasRatio) # Perimeter = ParticlePerimeter(c) / np.sqrt(tasRatio) # sphericity = np.sqrt(image_area/tasRatio)/Perimeter # Perform Korolev correction if auto_reject == 'H': Dmax = Dmax / size_factor if holroyd_habit != 's': print(f"WARNING: Habit should be spherical but is {holroyd_habit}") if particle_width != 0: axis_ratio = particle_length / particle_width else: axis_ratio = 0 if iRectEllipse == 1: (_, _), (RectangleL, RectangleW), RectangleAngle = min_enclosing_rotated_rectangle(image_buffer) (_, _), (EllipseL, EllipseW), EllipseAngle = min_enclosing_ellipse(image_buffer) DATA['ParticleRectangleLength'].append(RectangleL*diode_size) DATA['ParticleRectangleWidth'].append(RectangleW*diode_size) DATA['ParticleRectangleAngle'].append(RectangleAngle) DATA['ParticleEllipseLength'].append(EllipseL*diode_size) DATA['ParticleEllipseWidth'].append(EllipseW*diode_size) DATA['ParticleEllipseAngle'].append(EllipseAngle) # Get the area ratio using the DL=max(DT,DP), only observed area are used if particle_length > particle_width: percent_shadow = image_area / (np.pi * particle_length**2 / 4) * 100 elif particle_width != 0: percent_shadow = image_area / (np.pi * particle_width**2 / 4) * 100 else: percent_shadow = 0 DATA['time'].append(time[ip]) DATA['time_sec'].append(time_sec[ip]) DATA['time_ns'].append(time_ns[ip]) # DATA['SliceCount'].append() # DATA['Particle_number_all'].append() # DATA['position'].append() # DATA['ParticleTime'].append() # DATA['ParticleMillisec'].append() # DATA['ParticleMicrosec'].append() # DATA['ParentRecordNumber'].append() # DATA['ParticleNumber'].append(ip) DATA['ParticleLength'].append(particle_length) DATA['ParticleWidth'].append(particle_width) DATA['ParticleArea'].append(particle_area*diode_size*diode_size/tasRatio) DATA['ParticleLongestY'].append(longest_y_within_a_slice) DATA['ParticleMaxTopEdgeTouching'].append(max_top_edge_touching) DATA['ParticleMaxBottomEdgeTouching'].append(max_bottom_edge_touching) DATA['ParticleTouchingEdge'].append(particle_touching_image_edge) DATA['ParticleAutoReject'].append(auto_reject) DATA['ParticleIsHollow'].append(is_hollow) DATA['ParticleCenterIn'].append(center_in) DATA['ParticleAxisRatio'].append(axis_ratio) DATA['ParticleDiameter_MinR'].append(Dmax*diode_size) DATA['ParticleDiameter_AreaR'].append(Darea*diode_size) # DATA['ParticlePerimeter'].append(Perimeter*diode_size) DATA['PercentShadowArea'].append(percent_shadow) DATA['EdgeAtMaxHole'].append(edge_at_max_hole) DATA['MaxHoleDiameter'].append(max_hole_diameter) DATA['ParticleDepth'].append(part_z) DATA['SizeFactor'].append(size_factor) DATA['HolroydHabit'].append(holroyd_habit) DATA['FineDetailRatio'].append(F_fine_detail) # DATA['sphericity'].append(sphericity) DATA['AreaHoleRatio'].append(area_hole_ratio) DATA['InterArrivalTime'].append(seconds_since_start[ip]-seconds_since_start[ip-1] if ip>0 else 0) # DATA['DiodeStats'].append(diode_stats) # DATA['ParticleDiodeStats'].append() # Create a new Dataset ds_out = xr.Dataset() # Define dimensions ds_out = ds_out.assign_coords(particle=('particle', range(image_num))) # Empty list for unlimited dimension ds_out = ds_out.assign_coords(diode=('diode', range(diode_num))) ds_out = ds_out.assign_coords(slice_pos=('slice_pos', range(2))) ds_out['particle'].attrs['description'] = 'particle dimension' ds_out['diode'].attrs['description'] = 'diode dimension' # Add global attributes ds_out.attrs['Software'] = f'COPS V{__version__}' ds_out.attrs['Institution'] = spif_attr.institution ds_out.attrs['Creation_Time'] = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f') ds_out.attrs['Description'] = 'Contains size, morphological, and other particle properties from core group image data.' ds_out.attrs['Project'] = spif_attr.project.strip() ds_out.attrs['Probe_Type'] = im_header.instrument_name.strip() #ds_out.attrs['Image Source'] = input_spif_path for key, values in variables_dict.items(): # Check if dims is a single string or a list/tuple, and ensure it is a list dims = [values['dims']] if isinstance(values['dims'], str) else values['dims'] # Use a list comprehension to construct dim_tuple dim_tuple = tuple(ds_out.sizes[dim] for dim in dims) # Create and assign the DataArray if len(DATA[key]) > 0: print(f' Add "{key}", dimension: {dim_tuple}') ds_out[key] = xr.DataArray(data=np.array(DATA[key], dtype=values['dtype']), dims=dims, attrs=values['attrs']) # else: # ds_out[key] = xr.DataArray(data=np.zeros(dim_tuple, dtype=values['dtype']), dims=dims, attrs=values['attrs']) return ds_out ''' # endregion # ============================================================================== # MARK: SECTION 4: MICROPHYSICAL PROPERTIES & LEVEL-1 QC # ============================================================================== # region SECTION 4: MICROPHYSICAL PROPERTIES & LEVEL-1 QC # Vectorized mass-diameter and area-diameter relationships, terminal velocity, # particle bulk property calculation, and Inter-Arrival Time QC for Level-1 output. # Disabled scalar formula references are retained before the active vectorized helpers. # Functions: vectorized_single_mass, vectorized_single_area, vectorized_single_vt, # calculate_particle_bulk_properties, apply_quality_control_InterArrivalTime, # apply_level1_bulk_properties_and_qc # ============================================================================== """ def single_mass(diameter: float, habit: str) -> float: ''' Calculate the ice water content (IWC) based on the diameter and habit of precipitation particles. This function is a Python adaptation of an original UIOOPS MATLAB code. Parameters: ----------- diameter : float The diameter of the precipitation particle in centimeters (cm). habit : str The habit of the precipitation particle. Supported habits include: - 's' for Sphere - 't' for Tiny - 'l' for Linear - 'o' for Oriented - 'h' for Plate - 'i' for Irregular - 'a' for Aggregate (alternative code, treated the same as 'i') - 'g' for Graupel - 'd' for Dendrite Returns: -------- iwc : float The calculated ice water content for the given diameter and habit, in grams per cubic centimeter (g/cm^3). Note: ----- This function uses coefficients (a and b) specific to each particle habit to compute the IWC. The calculations are performed in cgs units (centimeters, grams, seconds). History: -------- - 2024-03-13: Created by Yongjie Huang (huangynj@gmail.com) ''' # Initialize iwc to 0; it will be calculated based on the particle's habit iwc = 0 # Convert habit input to string to ensure consistent comparison habit = str(habit) if habit in ['s', 't']: # Sphere and Tiny piecewise, threshold 0.01 cm = 100 um # D < 100 um: solid ice sphere, m = rho_i*(pi/6)*D^3 with rho_i = 0.92 g/cm^3 -> 0.482*D^3 [CGS] # D >= 100 um: Brown & Francis (1995) m-D relation a = 0.482 if diameter < 0.01 else 0.00294 b = 3.0 if diameter < 0.01 else 1.9 iwc = a * diameter ** b elif habit in ['l', 'o']: # Linear and Oriented if diameter < 0.03: # Smaller diameters use one set of coefficients a = 0.001666 b = 1.91 else: # Larger diameters use a different set a = 0.000907 b = 1.74 iwc = a * diameter ** b elif habit == 'h': # Plate a = 0.00739 b = 2.45 iwc = a * diameter ** b elif habit in ['i', 'a']: # Irregular piecewise, threshold 0.01 cm = 100 um # Same piecewise relation as spheres: solid ice sphere below 100 um, # Brown & Francis (1995) above a = 0.482 if diameter < 0.01 else 0.00294 b = 3.0 if diameter < 0.01 else 1.9 iwc = a * diameter ** b elif habit == 'g': # Graupel a = 0.049 b = 2.8 iwc = a * diameter ** b elif habit == 'd': # Dendrite a = 0.000516 b = 1.8 iwc = a * diameter ** b # elif habit == 'a': # Aggregate # a=0.0033; # b=2.2; # iwc = a *diameter^b; # Return the calculated ice water content return iwc """ ''' def single_area(diameter: float, habit: str) -> float: """ Calculates the particle area using area-diameter (A-D) relationships, based on the particle's diameter and habit. This function is converted from UIOOPS MATLAB code to Python and uses coefficients specific to each particle habit to compute the area. The calculation is initially performed in CGS units (cm^2) but is converted to mm^2 at the end. Parameters: ----------- diameter : float The diameter of the precipitation particle in centimeters (cm). habit : str The habit of the precipitation particle. Supported habits include: - 'l' for Linear - 'o' for Oriented - 'h' for Plate - 'i', 'a' for Irregular - 's' for Sphere - 't' for Tiny - 'g' for Graupel - 'd' for Dendrite Returns: -------- area : float The calculated particle area in square millimeters (mm^2). Note: ----- The coefficients (a and b) used in the A-D relationships are specific to each particle habit. The final area is converted from CGS units (cm^2) to mm^2 by multiplying the CGS area by 100. History: -------- - 2024-03-13: Created by Yongjie Huang (huangynj@gmail.com) """ # Initialize area area = 0 habit = str(habit) # Ensure habit is a string for comparison # Determine coefficients based on habit and apply A-D relationship if habit in ['l', 'o']: # Linear and Oriented # Use different coefficients for particles smaller or larger than 0.03 cm if diameter < 0.03: a = 0.0696 b = 1.5 else: a = 0.0512 b = 1.414 elif habit == 'h': # Plate a = 0.65 b = 2.0 elif habit in ['i', 'a', 's', 't']: # Irregular, Sphere, and Tiny a = 0.2285 b = 1.88 elif habit == 'g': # Graupel a = 0.5 b = 2.0 elif habit == 'd': # Dendrite a = 0.21 b = 1.76 # Calculate area using the A-D relationship if coefficients are defined area = a * diameter ** b if 'a' in locals() else 0 # Convert area from CGS units (cm^2) to mm^2 area *= 100 return area '''
[docs] def vectorized_single_mass(diameter: np.ndarray, habit: np.ndarray) -> np.ndarray: ''' Calculates the ice water content (IWC) for an array of particle diameters and habits using a vectorized approach for efficiency. This function is designed to operate on NumPy arrays to leverage array operations for speed. The calculation is based on m-D relations and is performed in cgs units. Parameters: ----------- diameter : np.ndarray An array of particle diameters in [centimeters]. habit : np.ndarray An array of particle habits, represented as strings. Supported habits include: 's' (Sphere), 't' (Tiny), 'l' (Linear), 'o' (Oriented), 'h' (Plate), 'i' (Irregular), 'a' (Irregular, alternative), 'g' (Graupel), 'd' (Dendrite). Returns: -------- iwc : np.ndarray An array of calculated ice water content values for the given diameters and habits, in grams per cubic centimeter (g/cm^3). Reference: ---------- Holroyd , E. W., 1987: Some Techniques and Uses of 2D-C Habit Classification Software for Snow Particles. J. Atmos. Oceanic Technol., 4, 498-511, https://doi.org/10.1175/1520-0426(1987)004%3C0498:STAUOC%3E2.0.CO;2 Brown, P. R. A., and P. N. Francis, 1995: Improved Measurements of the Ice Water Content in Cirrus Using a Total-Water Probe. J. Atmos. Oceanic Technol., 12, 410-414, https://doi.org/10.1175/1520-0426(1995)012%3C0410:IMOTIW%3E2.0.CO;2 Mitchell, D. L., 1996: Use of Mass- and Area-Dimensional Power Laws for Determining Precipitation Particle Terminal Velocities. J. Atmos. Sci., 53, 1710-1723, https://doi.org/10.1175/1520-0469(1996)053%3C1710:UOMAAD%3E2.0.CO;2 Jackson, R. C., G. M. McFarquhar, J. Stith, M. Beals, R. A. Shaw, J. Jensen, J. Fugal, and A. Korolev, 2014: An Assessment of the Impact of Antishattering Tips and Artifact Removal Techniques on Cloud Ice Size Distributions Measured by the 2D Cloud Probe. J. Atmos. Oceanic Technol., 31, 2567-2590, https://doi.org/10.1175/JTECH-D-13-00239.1 History: -------- - 2024-03-13: Created by Yongjie Huang (huangynj@gmail.com) ''' diameter = np.maximum(diameter, 0.0) # Initialize the output array with the same shape as diameter, defaulting to 0 iwc = np.zeros(diameter.shape) # Define coefficient arrays, initialized to 0, with the same shape as habit array a = np.zeros(habit.shape) b = np.zeros(habit.shape) # Handle Sphere and Tiny habits (piecewise, D in cm, threshold 0.01 cm = 100 um): # solid ice sphere m = rho_i*(pi/6)*D^3 (rho_i = 0.92 g/cm^3) -> 0.482*D^3 [CGS] below, # Brown & Francis (1995) above mask_st = np.isin(habit, ['s', 't']) a[mask_st] = np.where(diameter[mask_st] < 0.01, 0.482, 0.00294) b[mask_st] = np.where(diameter[mask_st] < 0.01, 3.0, 1.9) # Handle Linear and Oriented habits with diameter-dependent coefficients mask_lo = np.isin(habit, ['l', 'o']) # Apply different coefficients based on diameter conditions a[mask_lo] = np.where(diameter[mask_lo] < 0.03, 0.001666, 0.000907) b[mask_lo] = np.where(diameter[mask_lo] < 0.03, 1.91, 1.74) # Handle Plate habit mask_h = (habit == 'h') a[mask_h] = 0.00739 b[mask_h] = 2.45 # Handle Irregular habits (same piecewise relation as spheres: solid ice sphere # below 0.01 cm = 100 um, Brown & Francis 1995 above) mask_ia = np.isin(habit, ['i', 'a']) a[mask_ia] = np.where(diameter[mask_ia] < 0.01, 0.482, 0.00294) b[mask_ia] = np.where(diameter[mask_ia] < 0.01, 3.0, 1.9) # Handle Graupel habit mask_g = (habit == 'g') a[mask_g] = 0.049 b[mask_g] = 2.8 # Handle Dendrite habit mask_d = (habit == 'd') a[mask_d] = 0.000516 b[mask_d] = 1.8 # Calculate iwc for each particle using vectorized operations and coefficients iwc = a * diameter ** b return iwc
[docs] def vectorized_single_area(diameter: np.ndarray, habit: np.ndarray) -> np.ndarray: """ Calculates the particle area for an array of particle diameters and habits using a vectorized approach for efficiency. The calculation is based on A-D (area-diameter) relations specific to each particle habit. The function performs calculations initially in cgs units (centimeter-gram-second) but converts the final area measurements to mm^2. Parameters: ----------- diameter : np.ndarray An array of particle diameters in [centimeters]. habit : np.ndarray An array of particle habits, represented as strings. Supported habits include: 'l' (Linear), 'o' (Oriented), 'h' (Plate), 'i' (Irregular), 'a' (Irregular, alternative), 's' (Sphere), 't' (Tiny), 'g' (Graupel), 'd' (Dendrite). Returns: -------- area : np.ndarray An array of calculated particle areas for the given diameters and habits, in [mm^2]. Reference: Mitchell, D. L., 1996: Use of Mass- and Area-Dimensional Power Laws for Determining Precipitation Particle Terminal Velocities. J. Atmos. Sci., 53, 1710-1723, https://doi.org/10.1175/1520-0469(1996)053%3C1710:UOMAAD%3E2.0.CO;2 History: -------- - 2024-03-13: Created by Yongjie Huang (huangynj@gmail.com) """ diameter = np.maximum(diameter, 0.0) # Initialize the output area array with zeros, matching the shape of the input diameter array area = np.zeros(diameter.shape) # Initialize coefficient arrays for A-D relations, with the same shape as the habit array a = np.zeros(habit.shape) b = np.zeros(habit.shape) # Linear and Oriented (l, o) particles have diameter-dependent coefficients mask_lo = np.isin(habit, ['l', 'o']) a[mask_lo] = np.where(diameter[mask_lo] < 0.03, 0.0696, 0.0512) b[mask_lo] = np.where(diameter[mask_lo] < 0.03, 1.5, 1.414) # Plate (h) mask_h = (habit == 'h') a[mask_h] = 0.65 b[mask_h] = 2.0 # Irregular (i, a), Sphere (s), and Tiny (t) mask_iast = np.isin(habit, ['i', 'a', 's', 't']) a[mask_iast] = 0.2285 b[mask_iast] = 1.88 # Graupel (g) mask_g = (habit == 'g') a[mask_g] = 0.5 b[mask_g] = 2.0 # Dendrite (d) mask_d = (habit == 'd') a[mask_d] = 0.21 b[mask_d] = 1.76 # Calculate the area for each particle using the A-D relation coefficients area = a * diameter ** b # Convert the calculated area from cgs units (cm^2) to mm^2 by multiplying by 100 area = area * 100 return area
[docs] def vectorized_single_vt(diameter: float | np.ndarray, area_ratio: float | np.ndarray, mass: float | np.ndarray, P: float | np.ndarray, T: float | np.ndarray, usingMitchell: bool = False) -> float | np.ndarray: """ Calculates the terminal velocity for a single particle or an array of particles. Both options to calculate the terminal velocity are available. Default is to use the Heymsfield and Westbrook (2010) method, but setting usingMitchell=True will use the Mitchell (1996) method. - Mass and Diameter use metric system - Pressure uses hPa - Temperature uses Celsius Parameters: ----------- - diameter: Diameter of the particle(s) (m) - area_ratio: Ratio of the particle's projected area A to the area of a circumscribing circle, Ar = A/[(π/4)D^2] - mass: Mass of the particle(s) (kg) - P: Pressure (hPa) - T: Temperature (Celsius) Returns: -------- - vt: Terminal velocity of the particle(s) (m/s) Reference: ---------- Heymsfield, A. J., and C. D. Westbrook, 2010: Advances in the Estimation of Ice Particle Fall Speeds Using Laboratory and Field Measurements. J. Atmos. Sci., 67, 2469–2482, https://doi.org/10.1175/2010JAS3379.1 History: -------- - 2026-07-06: Yongjie Huang, coerced inputs to NumPy arrays upfront to prevent xarray ufunc recursion bugs. - 2024-03-13: Yongjie Huang, Converted from UIOOPS MATLAB code """ is_xarray = hasattr(diameter, 'values') and hasattr(diameter, 'dims') orig_dims = getattr(diameter, 'dims', None) orig_coords = getattr(diameter, 'coords', None) diameter = np.asarray(diameter.values if hasattr(diameter, 'values') else diameter, dtype=float) area_ratio = np.asarray(area_ratio.values if hasattr(area_ratio, 'values') else area_ratio, dtype=float) mass = np.asarray(mass.values if hasattr(mass, 'values') else mass, dtype=float) P = np.asarray(P.values if hasattr(P, 'values') else P, dtype=float) T = np.asarray(T.values if hasattr(T, 'values') else T, dtype=float) diameter = np.maximum(diameter, 0.0) area_ratio = np.maximum(area_ratio, 0.0) mass = np.maximum(mass, 0.0) g = 9.8 # Acceleration due to gravity (m/s^2) pi = np.pi # Pi constant # Calculate environmental conditions T = T + 273.15 # Convert temperature from Celsius to Kelvin P = P * 100 # Convert pressure from hPa to Pa rho_a = P / (287.15 * T) # Calculate air density (kg/m^3) # Sutherland's formula to calculate the dynamic viscosity (Pa.s) eta = 18.27 * (291.15 + 120) / (T + 120) * (T / 291.15) ** (3 / 2) / 10**6 nu = eta / rho_a # Kinetic viscosity (m^2/s) if not usingMitchell: # Calculate modified Best Number using Heymsfield and Westbrook (2010) method # using drag C=0.35 and epsilon=8.0 ar_term = area_ratio ** 0.5 X = np.divide(rho_a / (eta ** 2) * 8 * mass * g, np.pi * ar_term, out=np.zeros_like(mass, dtype=float), where=(ar_term > 0)) ReynoldN = 16 * (np.sqrt(1 + 4 * np.sqrt(X) / 64 / np.sqrt(0.35)) - 1) ** 2 else: # Calculate modified Best Number using Mitchell (1996) method # This is actually a special case of Heymsfield and Westbrook (2010) Eqs. (3), (5) and (6), # with k=0, and here we use drag C=0.6 and epsilon=5.83 # We calculate from the original equations without using power law approximation X = np.divide(rho_a / (eta ** 2) * 8 * mass * g, np.pi * area_ratio, out=np.zeros_like(mass, dtype=float), where=(area_ratio > 0)) ReynoldN = 5.83 ** 2 / 4 * (np.sqrt(1 + 4 * np.sqrt(X) / (5.83 ** 2) / np.sqrt(0.6)) - 1) ** 2 vt = np.divide(nu * ReynoldN, diameter, out=np.zeros_like(diameter, dtype=float), where=(diameter > 0)) # Calculate terminal velocity (m/s) if is_xarray: return xr.DataArray(vt, dims=orig_dims, coords=orig_coords) return vt
[docs] def calculate_particle_bulk_properties(particle_diameter, ParticleArea, habit_str, Pres=None, Temp=None): """ Calculate derived particle bulk properties including mass, velocity, and area ratio. Parameters: ----------- particle_diameter : xarray.DataArray or array-like Particle diameter [mm]. If an xarray.DataArray is provided, it is coerced to a NumPy array internally for computation, and the returned dictionary values will be restored to xarray.DataArrays matching the input dimensions and coordinates. ParticleArea : xarray.DataArray or array-like Measured particle area [mm²] habit_str : xarray.DataArray or array-like Particle habit classification (string codes) Pres : xarray.DataArray or array-like, optional Atmospheric pressure [hPa]. Defaults to 500 hPa if not provided. Temp : xarray.DataArray or array-like, optional Atmospheric temperature [°C]. Defaults to -5°C if not provided. Returns: -------- dict : Dictionary containing: - particle_mass : Mass using habit-specific m-D relations [g] - calcd_area : Calculated area from habit [mm²] - particle_massbl : Mass using Baker-Lawson relation [g] - area_ratio : Particle area ratio (ParticleArea / circular area) [-] - particle_vt : Terminal velocity [m/s] - particle_pr : Precipitation rate [g·m/s] Notes: ------ - Baker-Lawson relation: m = 0.115e-3 * A^1.218 (Baker & Lawson, 2006) - Area ratio is capped at 1.0 (physical constraint) - Default atmospheric conditions: 500 hPa, -5°C History: -------- - 2026-06-27: Yongjie Huang, locked down input contract to coerce xarray to NumPy internally and added robust handling for zero/negative diameters and unknown habits. - 2025-12-30: Yongjie Huang, first created. """ # Establish clear input contract: check if input is xarray.DataArray and coerce to NumPy arrays internally is_xarray = hasattr(particle_diameter, 'values') and hasattr(particle_diameter, 'dims') d_arr = np.asarray(particle_diameter.values if hasattr(particle_diameter, 'values') else particle_diameter, dtype=float) area_arr = np.asarray(ParticleArea.values if hasattr(ParticleArea, 'values') else ParticleArea, dtype=float) habit_arr = np.asarray(habit_str.values if hasattr(habit_str, 'values') else habit_str, dtype=str) if Pres is None: pres_arr = np.full_like(d_arr, DEFAULT_PRESSURE, dtype=float) else: pres_arr = np.asarray(Pres.values if hasattr(Pres, 'values') else Pres, dtype=float) if Temp is None: temp_arr = np.full_like(d_arr, DEFAULT_TEMPERATURE, dtype=float) else: temp_arr = np.asarray(Temp.values if hasattr(Temp, 'values') else Temp, dtype=float) # Sanitize inputs: clamp zero/negative diameters and areas to prevent invalid power RuntimeWarnings valid_mask = d_arr > 0 d_clean = np.where(valid_mask, d_arr, 0.0) area_clean = np.where(valid_mask & (area_arr > 0), area_arr, 0.0) # Calculate mass using habit-specific mass-diameter relations particle_mass = vectorized_single_mass( d_clean / 10.0, # Convert [mm] to [cm] habit_arr ) # Result in [g] # Calculate area using habit-specific area-diameter relations calcd_area = vectorized_single_area( d_clean / 10.0, # Convert [mm] to [cm] habit_arr ) # Result in [mm²] # Calculate mass using Baker and Lawson (2006) empirical relation # m = a * A^b where a = 0.115e-3, b = 1.218 particle_massbl = BAKER_LAWSON_COEFF * area_clean ** BAKER_LAWSON_EXP # [g] # Calculate ratio of the particle’s projected area A to # the area of a circumscribing circle, Ar = A/[(π/4)D^2] # Heymsfield and Westbrook (2010) Eq. (6) circ_area = np.pi / 4. * d_clean ** 2 area_ratio = np.divide(area_clean, circ_area, out=np.zeros_like(area_clean, dtype=float), where=(circ_area > 0)) area_ratio[area_ratio > 1.] = 1.0 # Physical constraint # Calculate terminal velocity particle_vt = vectorized_single_vt( d_clean * 1e-3, # Convert [mm] to [m] area_ratio, particle_mass * 1e-3, # Convert [g] to [kg] pres_arr, # [hPa] temp_arr # [°C] ) # Result in [m/s] # Calculate precipitation rate particle_pr = particle_mass * particle_vt # [g·m/s] # Ensure any invalid particles (diameter <= 0) have exactly 0 for all properties particle_mass = np.where(valid_mask, particle_mass, 0.0) calcd_area = np.where(valid_mask, calcd_area, 0.0) particle_massbl = np.where(valid_mask, particle_massbl, 0.0) area_ratio = np.where(valid_mask, area_ratio, 0.0) particle_vt = np.where(valid_mask, particle_vt, 0.0) particle_pr = np.where(valid_mask, particle_pr, 0.0) results = { 'particle_mass': particle_mass, 'calcd_area': calcd_area, 'particle_massbl': particle_massbl, 'area_ratio': area_ratio, 'particle_vt': particle_vt, 'particle_pr': particle_pr } if is_xarray: for k, v in results.items(): results[k] = xr.DataArray(v, dims=particle_diameter.dims, coords=particle_diameter.coords) return results
# ============================================================================= # ICE SHATTERING DETECTION AND QUALITY CONTROL # ============================================================================= # The following functions implement various algorithms (fixed, adaptive, and # probabilistic/multifeature) to identify and filter out ice shattering artifacts.
[docs] def compute_adaptive_iat_threshold(iat_values: np.ndarray, tas_values: np.ndarray | float | None, diode_size_mm: float, intArrBins: int, intArrMinCount: int, intArrMaxSeconds: float, defaultIntArrThresh: float) -> dict: """ Computes the adaptive inter-arrival time (IAT) threshold (tau_star) for a given time window. This function implements interval-local, unnormalized log-binned IAT thresholding following the methodologies of Field (2006) and Korolev & Field (2015). It analyzes the unnormalized log-spaced count distribution of particle inter-arrival times to identify bimodality between short-IAT shattering modes and long-IAT natural particle modes. Counts are intentionally not normalized by bin width: Korolev & Field (2015) show that such normalization removes the inter-mode minimum needed to locate tau_star. Parameters: ----------- iat_values : np.ndarray Array of inter-arrival times [s] for particles within the current time slice. tas_values : np.ndarray | float | None True airspeed values [m/s] corresponding to the particles, or a single mean airspeed. diode_size_mm : float Effective optical resolution (diode size) of the probe [mm]. intArrBins : int Number of log-spaced bins to use for the IAT histogram. intArrMinCount : int Minimum number of valid (positive) IAT values required in the window to attempt peak finding. intArrMaxSeconds : float Maximum inter-arrival time [s] considered for the upper bound of the log-spaced histogram. defaultIntArrThresh : float Fallback fixed inter-arrival time threshold [s] used when bimodality is not detected or counts are insufficient. Returns: -------- dict A dictionary containing diagnostic results and the computed threshold: - 'tau_star' (float): The computed adaptive threshold [s], or the fallback defaultIntArrThresh. - 'source' (str): The method used ('adaptive', 'insufficient_count', or 'unimodal'). - 'bin_edges' (np.ndarray | None): The log-spaced bin edges used for the histogram. - 'hist_counts' (np.ndarray | None): The unnormalized particle counts per bin. References: ----------- Field, P. R., A. J. Heymsfield, and A. Bansemer, 2006: Shattering and Particle Interarrival Times Measured by Optical Array Probes in Ice Clouds. Journal of Atmospheric and Oceanic Technology, 23, 1357-1371, https://doi.org/10.1175/JTECH1922.1 Korolev, A., and P. R. Field, 2015: Assessment of the performance of the inter-arrival time algorithm to identify ice shattering artifacts in cloud particle probe measurements. Atmos. Meas. Tech., 8, 761-777, https://doi.org/10.5194/amt-8-761-2015 History: 2026-06-29: Yongjie Huang, first created. """ # 1. Filter for strictly positive inter-arrival times. # Negative or zero IATs are non-physical or represent co-arrival overloads. iat_valid = iat_values[iat_values > 0] if len(iat_valid) < intArrMinCount: return { 'tau_star': defaultIntArrThresh, 'source': 'insufficient_count', 'bin_edges': None, 'hist_counts': None, } # 2. Calculate mean true airspeed (TAS) across the time window. # Provides a robust average to compute the physical minimum transit time. if tas_values is not None: mean_tas = np.mean(tas_values) if mean_tas <= 0 or np.isnan(mean_tas): mean_tas = 100.0 # reasonable fallback if tas is invalid else: mean_tas = 100.0 # 3. Define the physical minimum inter-arrival time (dt_min) based on probe resolution. # dt_min = (diode_size [mm] * 1e-3 [m/mm]) / mean_tas [m/s] dt_min = diode_size_mm * 1e-3 / mean_tas if dt_min <= 0 or np.isnan(dt_min): dt_min = 1e-7 dt_max = float(intArrMaxSeconds) if dt_max <= dt_min: dt_max = 1.0 # 4. Construct log-spaced bins and compute the unnormalized histogram. # IMPORTANT: counts are deliberately NOT normalized by bin width. Korolev & Field (2015) # note that phi(dt) is a non-normalized count distribution, and that normalizing by the # bin width makes the minimum between the short- and long-time modes disappear, which # hinders the calculation of tau_star. Peak/valley detection therefore operates on the # raw counts; do not divide by np.diff(bin_edges) here. log_bins = np.logspace(np.log10(dt_min), np.log10(dt_max), intArrBins + 1) counts, bin_edges = np.histogram(iat_valid, bins=log_bins) # 5. Identify local maxima (peaks) in the unnormalized log-counts. # A valid local maximum must be strictly greater than its immediate neighbors and positive. local_max_idx = [] for i in range(1, len(counts) - 1): if counts[i] > counts[i-1] and counts[i] > counts[i+1] and counts[i] > 0: local_max_idx.append(i) # If fewer than 2 peaks are found, the distribution is unimodal; fall back to default threshold. if len(local_max_idx) < 2: return { 'tau_star': defaultIntArrThresh, 'source': 'unimodal', 'bin_edges': bin_edges, 'hist_counts': counts, } # 6. Select the two dominant peaks representing the shattering mode (short IAT) # and the natural particle mode (long IAT). # To prevent noise in the dominant natural mode from producing false twin peaks (which would # cause the algorithm to miss a smaller shattering mode), we explicitly separate candidate peaks # into a short-IAT regime (bin center < 1e-4 s) and a long-IAT regime (bin center >= 1e-4 s). bin_centers = np.sqrt(bin_edges[:-1] * bin_edges[1:]) short_peaks = [idx for idx in local_max_idx if bin_centers[idx] < 1e-4] long_peaks = [idx for idx in local_max_idx if bin_centers[idx] >= 1e-4] # If either regime lacks a distinct peak, the distribution is effectively unimodal. if not short_peaks or not long_peaks: return { 'tau_star': defaultIntArrThresh, 'source': 'unimodal', 'bin_edges': bin_edges, 'hist_counts': counts, } # Select the tallest peak from the short-IAT regime (shattering) and long-IAT regime (natural). left_peak = max(short_peaks, key=lambda idx: counts[idx]) right_peak = max(long_peaks, key=lambda idx: counts[idx]) # Ensure there is at least one intermediate bin between the two peaks to find a minimum. if right_peak <= left_peak + 1: return { 'tau_star': defaultIntArrThresh, 'source': 'unimodal', 'bin_edges': bin_edges, 'hist_counts': counts, } # 7. Locate the bin with the minimum count between the left and right dominant peaks. # tau_star is calculated as the geometric mean of the bin edges at the minimum. min_idx = left_peak + 1 + np.argmin(counts[left_peak + 1:right_peak]) tau_star = np.sqrt(bin_edges[min_idx] * bin_edges[min_idx + 1]) # 8. Physical safeguard: A true shattering separation valley for OAPs typically lies between # 1e-6 s and 5e-5 s. If the computed tau_star exceeds 5e-5 s (e.g., > 10^-4 s), it indicates # that no genuine shattering burst mode exists and the algorithm locked onto a noise dip in the # natural particle tail. Fall back to defaultIntArrThresh. if tau_star > 5e-5: return { 'tau_star': defaultIntArrThresh, 'source': 'unimodal', 'bin_edges': bin_edges, 'hist_counts': counts, } return { 'tau_star': float(tau_star), 'source': 'adaptive', 'bin_edges': bin_edges, 'hist_counts': counts, }
def _elapsed_seconds_from_time_values(time_values): """Return elapsed seconds from numeric, datetime64, or timedelta64 particle times.""" if time_values is None: return None arr = np.asarray(time_values) if arr.size == 0: return arr.astype(np.float64) if np.issubdtype(arr.dtype, np.datetime64): return ((arr - arr.flat[0]) / np.timedelta64(1, 's')).astype(np.float64) if np.issubdtype(arr.dtype, np.timedelta64): return (arr / np.timedelta64(1, 's')).astype(np.float64) try: arr = arr.astype(np.float64) except (TypeError, ValueError): return None first = arr.flat[0] if np.isfinite(first): arr = arr - first return arr def _resolve_particle_time_seconds(ds=None, time_sec=None): """Resolve particle time to elapsed seconds, preferring time_sec + time_ns.""" add_time_ns = False if time_sec is not None: time_values = time_sec add_time_ns = True elif ds is not None and 'time_sec' in ds: time_values = ds['time_sec'] add_time_ns = True elif ds is not None and 'time' in ds: return _elapsed_seconds_from_time_values(ds['time']) else: return None elapsed = _elapsed_seconds_from_time_values(time_values) if elapsed is None: return None if add_time_ns and ds is not None and 'time_ns' in ds: try: ns_arr = np.asarray(ds['time_ns'], dtype=np.float64) except (TypeError, ValueError): ns_arr = None if ns_arr is not None and ns_arr.shape == elapsed.shape and ns_arr.size > 0: first_ns = ns_arr.flat[0] if np.isfinite(first_ns): elapsed = elapsed + (ns_arr - first_ns) * 1e-9 return elapsed
[docs] def compute_rolling_poisson_metrics(full_time_sec, iat_arr, orig_negative_iat, window_sec, min_lambda): """ Computes rolling Poisson arrival rate (lambda_t) and arrival probability (p_i). """ n = len(iat_arr) if n == 0: return np.array([], dtype=np.float64), np.array([], dtype=np.float32) t_arr = _elapsed_seconds_from_time_values(full_time_sec) if full_time_sec is not None else None if t_arr is None: t_arr = np.cumsum(iat_arr) # Precise Lambda Estimation (MLE) # Exclude edge 0 and dt < 1e-6 s valid_edge_mask = (iat_arr >= 1e-6) & (~orig_negative_iat) valid_edge_mask[0] = False valid_counts = valid_edge_mask.astype(np.int64) valid_dts = np.where(valid_edge_mask, iat_arr, 0.0) cumsum_counts = np.concatenate(([0], np.cumsum(valid_counts))) cumsum_dts = np.concatenate(([0], np.cumsum(valid_dts))) half_win = window_sec / 2.0 win_start_t = t_arr - half_win win_end_t = t_arr + half_win left_idx = np.searchsorted(t_arr, win_start_t, side='left') right_idx = np.searchsorted(t_arr, win_end_t, side='right') N_valid_win = cumsum_counts[right_idx] - cumsum_counts[left_idx] sum_dt_win = cumsum_dts[right_idx] - cumsum_dts[left_idx] lambda_t = np.full(n, min_lambda, dtype=np.float64) valid_win_mask = (N_valid_win >= 10) & (sum_dt_win > 0) lambda_t[valid_win_mask] = N_valid_win[valid_win_mask] / sum_dt_win[valid_win_mask] # Poisson Arrival Probability (p_i) p_i = 1.0 - np.exp(-lambda_t * iat_arr) p_i[0] = np.nan p_i[orig_negative_iat] = np.nan return lambda_t, p_i.astype(np.float32)
def _compute_burst_density_score( t_arr, is_valid_edge, is_suspicious, density_half_win, density_max_seconds, ): """Compute local suspicious-edge fractions without a per-particle loop.""" t_arr = np.asarray(t_arr, dtype=np.float64) is_valid_edge = np.asarray(is_valid_edge, dtype=bool) is_suspicious = np.asarray(is_suspicious, dtype=bool) n = t_arr.size score = np.zeros(n, dtype=np.float32) if n <= 1: return score half_win = min(max(int(density_half_win), 0), n - 1) valid_edges = is_valid_edge.copy() valid_edges[0] = False suspicious_edges = is_suspicious & valid_edges valid_count = np.zeros(n, dtype=np.int64) suspicious_count = np.zeros(n, dtype=np.int64) # The configured index half-window is small, so iterate over offsets and # evaluate all particle centers at once. This retains the original exact # floating-point time comparison, including non-monotonic timestamps. for offset in range(-half_win, half_win + 1): if offset < 0: centers = slice(-offset, n) neighbors = slice(0, n + offset) elif offset > 0: centers = slice(0, n - offset) neighbors = slice(offset, n) else: centers = slice(0, n) neighbors = slice(0, n) time_mask = ( np.abs(t_arr[neighbors] - t_arr[centers]) <= density_max_seconds ) valid_count[centers] += valid_edges[neighbors] & time_mask suspicious_count[centers] += suspicious_edges[neighbors] & time_mask np.divide( suspicious_count, valid_count, out=score, where=valid_count > 0, ) score[0] = 0.0 return score
[docs] def compute_multifeature_edge_scores( iat_arr, iat_p_natural, orig_negative_iat, particle_diameter, area_ratio, full_time_sec, w_iat, w_density, w_size, w_fragment, w_morph, alpha_extend, density_half_win, density_max_seconds, small_diameter_mm, area_ratio_good ): """ Computes component feature scores and composite shatter score for all edges. All scores at edge 0 are forced to 0.0. """ n = len(iat_arr) iat_score = np.zeros(n, dtype=np.float32) burst_density_score = np.zeros(n, dtype=np.float32) size_contrast_score = np.zeros(n, dtype=np.float32) small_fragment_score = np.zeros(n, dtype=np.float32) morphology_score = np.zeros(n, dtype=np.float32) if n == 0: return iat_score, burst_density_score, size_contrast_score, small_fragment_score, morphology_score, np.zeros(n, dtype=np.float32) # 1. IAT Score valid_p = ~np.isnan(iat_p_natural) iat_score[valid_p] = 1.0 - iat_p_natural[valid_p] iat_score[0] = 0.0 # 2. Burst Density Score t_arr = _elapsed_seconds_from_time_values(full_time_sec) if full_time_sec is not None else None if t_arr is None: t_arr = np.cumsum(iat_arr) is_valid_edge = (~np.isnan(iat_p_natural)) & (~orig_negative_iat) is_valid_edge[0] = False is_suspicious = is_valid_edge & (iat_p_natural < alpha_extend) burst_density_score = _compute_burst_density_score( t_arr, is_valid_edge, is_suspicious, density_half_win, density_max_seconds, ) # 3. Size Contrast & Small Fragment Scores d_left = particle_diameter[:-1] d_right = particle_diameter[1:] valid_d = (~np.isnan(d_left)) & (~np.isnan(d_right)) & (d_left > 0) & (d_right > 0) min_d = np.minimum(d_left, d_right) max_d = np.maximum(d_left, d_right) safe_max_d = np.where(valid_d & (max_d > 0), max_d, 1.0) size_contrast_score[1:] = np.where(valid_d, 1.0 - min_d / safe_max_d, 0.0) size_contrast_score[0] = 0.0 small_fragment_score[1:] = np.where(valid_d & (min_d < small_diameter_mm), 1.0, 0.0) small_fragment_score[0] = 0.0 # 4. Morphology Score ar_left = area_ratio[:-1] ar_right = area_ratio[1:] valid_ar = (~np.isnan(ar_left)) & (~np.isnan(ar_right)) & (ar_left >= 0) & (ar_right >= 0) min_ar = np.minimum(ar_left, ar_right) denom = area_ratio_good - AREA_RATIO_MIN if abs(denom) < 1e-6: denom = 1e-6 morph_val = (area_ratio_good - min_ar) / denom morphology_score[1:] = np.where(valid_ar, np.clip(morph_val, 0.0, 1.0), 0.0) morphology_score[0] = 0.0 # 5. Composite Shatter Score shatter_score = ( w_iat * iat_score + w_density * burst_density_score + w_size * size_contrast_score + w_fragment * small_fragment_score + w_morph * morphology_score ) shatter_score[0] = 0.0 return iat_score, burst_density_score, size_contrast_score, small_fragment_score, morphology_score, shatter_score
[docs] def compute_multifeature_shattering_clusters( shatter_score, particle_diameter, is_accepted_arr, ParticleAutoReject_arr, reaccptShatrs, reaccptD, reaccptMaxIAT, parent_ratio, mf_score_start, mf_score_extend, iat_arr, orig_negative_iat ): """ Identifies shattering clusters using hysteresis on shatter_score, evaluates roles, and updates ParticleAutoReject. """ n = len(shatter_score) shatter_cluster_id = np.zeros(n, dtype=np.int32) shatter_confidence = np.zeros(n, dtype=np.float32) shatter_role = np.zeros(n, dtype=np.int32) if n == 0: return shatter_cluster_id, shatter_confidence, shatter_role, ParticleAutoReject_arr current_cluster_id = 0 clusters = [] i = 1 while i < n: if shatter_score[i] >= mf_score_start and not orig_negative_iat[i]: start_p = i - 1 j = i + 1 while j < n and shatter_score[j] >= mf_score_extend and not orig_negative_iat[j]: j += 1 end_p = j - 1 member_indices = list(range(start_p, end_p + 1)) if len(member_indices) >= 2: current_cluster_id += 1 for k in member_indices: shatter_cluster_id[k] = current_cluster_id inc_score = 0.0 if k > start_p and k <= end_p: inc_score = shatter_score[k] out_score = 0.0 if k >= start_p and k < end_p: out_score = shatter_score[k+1] shatter_confidence[k] = max(inc_score, out_score) clusters.append((current_cluster_id, member_indices, i, j - 1)) i = j else: i += 1 # Evaluate roles and apply QC flags within clusters for cid, mem_idx, edge_start, edge_end in clusters: # Candidate parent selection parents_reaccepted = set() for p_idx in mem_idx: if not is_accepted_arr[p_idx]: shatter_role[p_idx] = 3 continue shatter_role[p_idx] = 1 if reaccptShatrs != 1: continue d_p = particle_diameter[p_idx] if np.isnan(d_p) or d_p <= reaccptD: continue inc_valid = (p_idx >= edge_start and p_idx <= edge_end) and (p_idx > 0) and (iat_arr[p_idx] < reaccptMaxIAT) out_valid = (p_idx + 1 >= edge_start and p_idx + 1 <= edge_end) and (p_idx < n - 1) and (iat_arr[p_idx + 1] < reaccptMaxIAT) if not (inc_valid or out_valid): continue other_diams = [particle_diameter[k] for k in mem_idx if k != p_idx and not np.isnan(particle_diameter[k]) and particle_diameter[k] > 0] if not other_diams: continue median_diam = np.median(other_diams) if d_p >= parent_ratio * median_diam: parents_reaccepted.add(p_idx) # Update codes for p_idx in mem_idx: if shatter_role[p_idx] == 3: continue if p_idx in parents_reaccepted: shatter_role[p_idx] = 2 ParticleAutoReject_arr[p_idx] = REJECT_CODE_REACCEPTED else: shatter_role[p_idx] = 1 ParticleAutoReject_arr[p_idx] = REJECT_CODE_SHATTERING return shatter_cluster_id, shatter_confidence, shatter_role, ParticleAutoReject_arr
[docs] def compute_probabilistic_shattering_clusters( full_time_sec, iat_arr, orig_negative_iat, particle_diameter, is_accepted_arr, ParticleAutoReject_arr, alpha_start, alpha_extend, window_sec, min_lambda, reaccptShatrs, reaccptD, reaccptMaxIAT ): """ Computes probabilistic shattering clusters using an MLE Poisson arrival model and Schmitt trigger hysteresis, with edge-aware parent particle reacceptance preserving QC flag precedence. Parameters: ----------- full_time_sec : xarray.DataArray or np.ndarray or None Particle full high-precision timestamps [s]. iat_arr : np.ndarray Inter-arrival times [s]. orig_negative_iat : np.ndarray Boolean mask indicating particles originally possessing negative inter-arrival times. particle_diameter : np.ndarray Particle diameters [mm]. is_accepted_arr : np.ndarray Boolean mask indicating particles currently accepted by prior quality control steps. ParticleAutoReject_arr : np.ndarray Array of particle rejection codes (will be modified in-place for accepted shattering cluster members). alpha_start : float P-value threshold to initiate a new shattering cluster. alpha_extend : float P-value threshold to extend an active shattering cluster. window_sec : float or int Moving rolling window duration [s] for local Poisson rate estimation. min_lambda : float Fallback minimum natural arrival rate [s^-1]. reaccptShatrs : int Flag to enable edge-aware parent particle reacceptance (0 or 1). reaccptD : float Minimum diameter threshold for parent particle reacceptance [mm]. reaccptMaxIAT : float Maximum incident cluster inter-arrival time to qualify for reacceptance [s]. Returns: -------- tuple : (p_i, shatter_cluster_id, shatter_confidence, ParticleAutoReject_arr, lambda_t) - p_i (np.ndarray): Poisson arrival probability of natural occurrence. - shatter_cluster_id (np.ndarray): Integer cluster identifiers (0 = no cluster, positive int = cluster ID). - shatter_confidence (np.ndarray): Shattering confidence metric in [0, 1]. - ParticleAutoReject_arr (np.ndarray): Updated particle rejection codes array. - lambda_t (np.ndarray): Estimated local Poisson arrival rate [s^-1]. History: -------- - 2026-06-29: Yongjie Huang, first created. Implemented local Poisson MLE, Schmitt trigger hysteresis clustering, and edge-aware parent reacceptance. """ n = len(iat_arr) if n == 0: return np.array([], dtype=np.float32), np.array([], dtype=np.int32), np.array([], dtype=np.float32), ParticleAutoReject_arr, np.array([], dtype=np.float64) lambda_t, p_i = compute_rolling_poisson_metrics(full_time_sec, iat_arr, orig_negative_iat, window_sec, min_lambda) # 3. Schmitt Trigger Hysteresis & Graph Clustering shatter_cluster_id = np.zeros(n, dtype=np.int32) shatter_confidence = np.zeros(n, dtype=np.float32) edge_confidence = np.zeros(n, dtype=np.float32) valid_p_mask = ~np.isnan(p_i) edge_confidence[valid_p_mask] = 1.0 - p_i[valid_p_mask] current_cluster_id = 0 clusters = [] i = 1 while i < n: if valid_p_mask[i] and p_i[i] < alpha_start and not orig_negative_iat[i]: start_p = i - 1 j = i + 1 while j < n and valid_p_mask[j] and p_i[j] < alpha_extend and not orig_negative_iat[j]: j += 1 end_p = j - 1 member_indices = list(range(start_p, end_p + 1)) if len(member_indices) >= 2: current_cluster_id += 1 for k in member_indices: shatter_cluster_id[k] = current_cluster_id inc_conf = 0.0 if k > start_p and k <= end_p: inc_conf = edge_confidence[k] out_conf = 0.0 if k >= start_p and k < end_p: out_conf = edge_confidence[k+1] shatter_confidence[k] = max(inc_conf, out_conf) clusters.append((current_cluster_id, member_indices, i, j - 1)) i = j else: i += 1 # Mark cluster members as shattering if they are currently accepted shattering_mask = (shatter_cluster_id > 0) & is_accepted_arr ParticleAutoReject_arr[shattering_mask] = REJECT_CODE_SHATTERING # 4. Edge-Aware Parent Particle Reacceptance if reaccptShatrs == 1: for cid, mem_idx, edge_start, edge_end in clusters: if len(mem_idx) < 2: continue for p_idx in mem_idx: if ParticleAutoReject_arr[p_idx] != REJECT_CODE_SHATTERING: continue if particle_diameter[p_idx] <= reaccptD: continue inc_valid = (p_idx >= edge_start and p_idx <= edge_end) and (p_idx > 0) and (iat_arr[p_idx] < reaccptMaxIAT) out_valid = (p_idx + 1 >= edge_start and p_idx + 1 <= edge_end) and (p_idx < n - 1) and (iat_arr[p_idx + 1] < reaccptMaxIAT) if not (inc_valid or out_valid): continue other_diams = [particle_diameter[k] for k in mem_idx if k != p_idx] if not other_diams: continue ref_median = np.median(other_diams) if particle_diameter[p_idx] >= 2.0 * ref_median: ParticleAutoReject_arr[p_idx] = REJECT_CODE_REACCEPTED return p_i.astype(np.float32), shatter_cluster_id, shatter_confidence, ParticleAutoReject_arr, lambda_t
#--- QC-settings record: Level-1 stores the settings its ParticleAutoReject codes were # made with, so Level-2 can refuse reusing them under different settings. QC_SETTINGS_ATTR = 'qc_settings' # Every SizeDistributionConfig field read by apply_quality_control_InterArrivalTime # (probe_type selects the DMT depth-of-field rejection). _QC_SETTING_FIELDS = ( 'probe_type', 'applyIntArrThresh', 'defaultIntArrThresh', 'reaccptShatrs', 'reaccptD', 'reaccptMaxIAT', 'intArrThreshMode', 'intArrAdaptiveWindowSec', 'intArrBins', 'intArrMinCount', 'intArrMaxSeconds', 'intArrProbAlphaStart', 'intArrProbAlphaExtend', 'intArrProbRollingWindowSec', 'intArrProbMinLambda', 'intArrMFScoreStart', 'intArrMFScoreExtend', 'intArrMFIatWeight', 'intArrMFDensityWeight', 'intArrMFSizeWeight', 'intArrMFFragmentWeight', 'intArrMFMorphWeight', 'intArrMFSmallDiameterMm', 'intArrMFParentRatio', 'intArrMFDensityEdgeHalfWindow', 'intArrMFDensityMaxSeconds', 'intArrMFAreaRatioGood', 'accepted_codes', ) # Level-1 files written before QC_SETTINGS_ATTR existed store only this QC setting. _LEGACY_LEVEL1_QC_ATTRS = {'iat_qc_source': 'intArrThreshMode'} def _qc_setting_value(name, value): """Normalize one QC setting so NetCDF numpy types compare equal to config values.""" default = getattr(SizeDistributionConfig(), name) if isinstance(default, tuple): return sorted(str(c) for c in np.atleast_1d(np.asarray(value)).tolist()) return type(default)(value.item() if hasattr(value, 'item') else value)
[docs] def qc_settings_record(source) -> dict: """Requested QC settings from a ``SizeDistributionConfig`` or an attribute mapping. Missing attributes take the ``SizeDistributionConfig`` defaults, as the QC function does. """ defaults = SizeDistributionConfig() get = source.get if isinstance(source, dict) else lambda k, d: getattr(source, k, d) return {name: _qc_setting_value(name, get(name, getattr(defaults, name))) for name in _QC_SETTING_FIELDS}
[docs] def qc_settings_attrs(record: dict) -> dict: """NetCDF global attribute for a QC-settings record (JSON text).""" return {QC_SETTINGS_ATTR: json.dumps(record, sort_keys=True)}
def _level1_qc_settings(level1_attrs) -> dict: """QC settings a Level-1 group is known to have used; settings it does not store are absent.""" if QC_SETTINGS_ATTR in level1_attrs: return json.loads(level1_attrs[QC_SETTINGS_ATTR]) return {name: _qc_setting_value(name, level1_attrs[key]) for key, name in _LEGACY_LEVEL1_QC_ATTRS.items() if key in level1_attrs}
[docs] def check_level2_qc_settings(level1_attrs, level1_has_bulk: bool, requested: dict, where: str, warn_unknown: bool = True) -> None: """Refuse reusing Level-1 QC codes computed with QC settings other than ``requested``. Level-2 reuses Level-1 ``ParticleAutoReject`` whenever Level-1 bulk fields exist, so the requested QC is never applied. Geometry-only Level-1 is fine (Level-2 runs QC). Every setting the Level-1 group stores is compared; settings it does not store (older Level-1 files) are unknown, never assumed to be defaults, and only warn. """ if not level1_has_bulk: return known = _level1_qc_settings(level1_attrs) changed = [f" {name}: Level-1={known[name]}, requested={value}" for name, value in requested.items() if name in known and known[name] != value] if changed: raise StaleOutputError( f"{where}: Level-1 QC codes were computed with different QC settings:\n" + "\n".join(changed) + "\n" "Level-2 reuses Level-1 QC codes, so the requested QC would not be applied. " "Regenerate Level-1 before running Level-2 (same QC settings, or geometry-only, " "into a fresh file).") unknown = [name for name in requested if name not in known] if unknown and warn_unknown: warnings.warn( f"{where}: Level-1 does not record these QC settings, so Level-2 cannot verify " f"that the reused QC codes match the request: {', '.join(unknown)}. Regenerate " "Level-1 with the current configuration to be sure.", stacklevel=2)
[docs] def apply_quality_control_InterArrivalTime(ParticleAutoReject, InterArrivalTime, particle_diameter, area_ratio, ds, applyIntArrThresh, defaultIntArrThresh, reaccptShatrs, reaccptD, reaccptMaxIAT, probe_type, accepted_codes=ACCEPTED_CODES, *, tas=None, time_sec=None, diode_size=None, size_config=None, return_diagnostics=False): """ Apply quality control filters to particle data based on inter-arrival time. This function applies multiple QC criteria: 1. DMT depth-of-field rejection 2. Negative inter-arrival time rejection 3. Low area ratio rejection 4. Inter-arrival time threshold (shattering detection, fixed, adaptive, probabilistic, or probabilistic_multifeature) 5. Shattering event reacceptance (optional, pointwise or cluster-based) Parameters: ----------- ParticleAutoReject : xarray.DataArray Particle rejection codes (copied; the input is not modified) InterArrivalTime : xarray.DataArray Inter-arrival times [s] (copied; the input is not modified) particle_diameter : xarray.DataArray Particle diameters [mm] area_ratio : xarray.DataArray Particle area ratios [-] ds : xarray.Dataset Input dataset containing the active-high DMT ``dof_flag``, when available. applyIntArrThresh : int Flag to apply inter-arrival time threshold (0 or 1) defaultIntArrThresh : float Default inter-arrival time threshold [s] reaccptShatrs : int Flag to reaccept particles from shattering events (0 or 1) reaccptD : float Minimum diameter for reacceptance [mm] reaccptMaxIAT : float Maximum inter-arrival time for reacceptance [s] probe_type : int Probe category: 1=HVPS, 2=2DS, 3=HVPS4, 4=Fast2DS, 5=CIP, 6=PIP, 7=CIP25, 8=CIP_grey, and 9=2DC. accepted_codes : list or tuple List of accepted particle codes tas : xarray.DataArray or np.ndarray, optional True airspeed values [m/s] time_sec : xarray.DataArray or np.ndarray, optional Particle timestamps [s] diode_size : float, optional Diode size [mm] size_config : SizeDistributionConfig, optional Configuration object containing adaptive IAT settings return_diagnostics : bool, optional If True, returns (ParticleAutoReject, InterArrivalTime, diagnostics_dict) Returns: -------- tuple : (ParticleAutoReject, InterArrivalTime) or (ParticleAutoReject, InterArrivalTime, diagnostics_dict) History: -------- - 2025-12-30: Yongjie Huang, first created. - 2026-06-28: Added adaptive IAT mode with graph-edge cluster marking and burst reacceptance. - 2026-06-29: Added probabilistic edge-and-cluster shattering detector. - 2026-06-30: Added probabilistic_multifeature mode. """ # Make copies to avoid modifying original data ParticleAutoReject = ParticleAutoReject.copy() InterArrivalTime = InterArrivalTime.copy() get_cfg = lambda name, default: getattr(size_config, name, (size_config.attrs.get(name, default) if hasattr(size_config, 'attrs') else default)) if size_config is not None else default intArrThreshMode = get_cfg('intArrThreshMode', 'fixed') if accepted_codes in (['all'], ('all',)): if return_diagnostics: if intArrThreshMode == 'probabilistic': return ParticleAutoReject, InterArrivalTime, { 'iat_p_natural': np.full(len(InterArrivalTime), np.nan, dtype=np.float32), 'poisson_lambda': np.full(len(InterArrivalTime), np.nan, dtype=np.float64), 'shatter_cluster_id': np.zeros(len(InterArrivalTime), dtype=np.int32), 'shatter_confidence': np.zeros(len(InterArrivalTime), dtype=np.float32), 'iat_qc_source': 2 } elif intArrThreshMode == 'probabilistic_multifeature': return ParticleAutoReject, InterArrivalTime, { 'iat_p_natural': np.full(len(InterArrivalTime), np.nan, dtype=np.float32), 'poisson_lambda': np.full(len(InterArrivalTime), np.nan, dtype=np.float64), 'shatter_score': np.full(len(InterArrivalTime), np.nan, dtype=np.float32), 'shatter_cluster_id': np.zeros(len(InterArrivalTime), dtype=np.int32), 'shatter_confidence': np.zeros(len(InterArrivalTime), dtype=np.float32), 'shatter_role': np.zeros(len(InterArrivalTime), dtype=np.int32), 'iat_score': np.full(len(InterArrivalTime), np.nan, dtype=np.float32), 'burst_density_score': np.full(len(InterArrivalTime), np.nan, dtype=np.float32), 'size_contrast_score': np.full(len(InterArrivalTime), np.nan, dtype=np.float32), 'small_fragment_score': np.full(len(InterArrivalTime), np.nan, dtype=np.float32), 'morphology_score': np.full(len(InterArrivalTime), np.nan, dtype=np.float32), 'iat_qc_source': 3 } return ParticleAutoReject, InterArrivalTime, {'tau_star': np.full(len(InterArrivalTime), defaultIntArrThresh), 'tau_star_source': np.zeros(len(InterArrivalTime), dtype=np.int32), 'window_diagnostics': {}} return ParticleAutoReject, InterArrivalTime else: get_is_accepted = lambda: ParticleAutoReject.isin(accepted_codes) # 1. Reject DMT mono particles that do not meet the probe's depth-of-field # requirement. The DMT flag is active high: 1 = accepted, 0 = reject. # CIP_grey (8) is intentionally excluded because its decoder does not # emit this mono-probe flag; it requires a separate greyscale DoF test. if probe_type in (5, 6, 7) and 'dof_flag' in ds.variables: # CIP, PIP, CIP25 dof_flag = np.asarray(ds['dof_flag'].values) if dof_flag.ndim != 1 or dof_flag.size != ParticleAutoReject.size: raise ValueError( "The Level-1 'dof_flag' must be one-dimensional and particle-aligned: " f"expected {ParticleAutoReject.size} values, got shape {dof_flag.shape}." ) ParticleAutoReject[(dof_flag == 0) & np.asarray(get_is_accepted())] = REJECT_CODE_DOF_FAILURE # 2. Mark particles with negative inter-arrival time orig_negative_iat = np.asarray(InterArrivalTime < 0) ParticleAutoReject[(InterArrivalTime < 0) & get_is_accepted()] = REJECT_CODE_NEGATIVE_IAT InterArrivalTime[InterArrivalTime < 0] = 0 # 3. Reject particles with low area ratio ParticleAutoReject[(area_ratio < AREA_RATIO_MIN) & get_is_accepted()] = REJECT_CODE_LOW_AREA_RATIO if intArrThreshMode == 'probabilistic': diagnostics_dict = { 'iat_p_natural': np.full(len(InterArrivalTime), np.nan, dtype=np.float32), 'poisson_lambda': np.full(len(InterArrivalTime), np.nan, dtype=np.float64), 'shatter_cluster_id': np.zeros(len(InterArrivalTime), dtype=np.int32), 'shatter_confidence': np.zeros(len(InterArrivalTime), dtype=np.float32), 'iat_qc_source': 2 } else: diagnostics_dict = { 'tau_star': np.full(len(InterArrivalTime), defaultIntArrThresh), 'tau_star_source': np.zeros(len(InterArrivalTime), dtype=np.int32), 'window_diagnostics': {} } # 4. Apply inter-arrival time threshold for shattering detection if applyIntArrThresh == 1: # InterArrivalTime[i] is the edge linking particles i-1 and i. Index 0 # has no preceding particle, so its synthetic zero IAT is not a valid # shattering edge. valid_iat_edge = np.ones(len(InterArrivalTime), dtype=bool) if valid_iat_edge.size > 0: valid_iat_edge[0] = False if intArrThreshMode == 'fixed': fixed_reject = ( valid_iat_edge & np.asarray(InterArrivalTime <= defaultIntArrThresh) & np.asarray(get_is_accepted()) ) ParticleAutoReject[fixed_reject] = REJECT_CODE_SHATTERING # 5. Optionally reaccept large particles from shattering events. # A particle is reaccepted when it is currently flagged as a # shattering artifact yet is large enough (> reaccptD) and arrived # within reaccptMaxIAT -- i.e. a likely real particle embedded in a # burst rather than a fragment. if reaccptShatrs == 1: # Note on Shattering Reacceptance Logic Trade-offs: # The legacy rBegin/rEnd approach required particles to be embedded inside a contiguous # shattering burst window, but was vulnerable to segment boundary edge-cases. The vectorized pointwise approach # below resolves segment boundary failures but removes the surrounding burst-context requirement. Consequently, # an isolated large particle with an inter-arrival time just below defaultIntArrThresh in a non-burst context # will be reaccepted unconditionally. When reaccptMaxIAT == defaultIntArrThresh, the IAT check is nearly vacuous, # making reacceptance purely diameter-gated (diameter > reaccptD) for all shattering-flagged particles. reaccept = ( (ParticleAutoReject == REJECT_CODE_SHATTERING) & (particle_diameter > reaccptD) & (InterArrivalTime < reaccptMaxIAT) ) ParticleAutoReject[reaccept] = REJECT_CODE_REACCEPTED elif intArrThreshMode == 'adaptive': # Adaptive mode: compute tau_star per window and mark clusters formed by short edges iat_arr = np.asarray(InterArrivalTime) tas_arr = np.asarray(tas) if tas is not None else None diode_size_mm = diode_size if diode_size is not None else 0.025 w_sec = get_cfg('intArrAdaptiveWindowSec', 1) intArrBins = get_cfg('intArrBins', 35) intArrMinCount = get_cfg('intArrMinCount', 200) intArrMaxSeconds = get_cfg('intArrMaxSeconds', 1.0) if time_sec is not None: t_arr = np.asarray(time_sec) windows = (t_arr // w_sec) * w_sec unique_windows = np.unique(windows) else: windows = np.zeros(len(iat_arr)) unique_windows = np.array([0.0]) tau_star_arr = np.zeros(len(iat_arr)) tau_star_source_arr = np.zeros(len(iat_arr), dtype=np.int32) window_diagnostics = {} adaptive_source_mask = np.zeros(len(iat_arr), dtype=bool) is_accepted_arr = get_is_accepted() if isinstance(is_accepted_arr, xr.DataArray): is_accepted_arr = is_accepted_arr.values part_diam_arr = np.asarray(particle_diameter) par_arr = ParticleAutoReject.values if isinstance(ParticleAutoReject, xr.DataArray) else ParticleAutoReject for w in unique_windows: mask_w = (windows == w) iat_w = iat_arr[mask_w] tas_w = tas_arr[mask_w] if (tas_arr is not None and tas_arr.ndim > 0) else tas_arr res = compute_adaptive_iat_threshold( iat_w, tas_w, diode_size_mm, intArrBins, intArrMinCount, intArrMaxSeconds, defaultIntArrThresh ) tau_star_arr[mask_w] = res['tau_star'] window_diagnostics[w] = res source_str = res['source'] if source_str == 'adaptive': source_code = 1 elif source_str == 'insufficient_count': source_code = 2 elif source_str == 'unimodal': source_code = 3 else: source_code = 0 tau_star_source_arr[mask_w] = source_code if res['source'] == 'adaptive': adaptive_source_mask[mask_w] = True else: # Fallback windows behave exactly like fixed fallback (pointwise rejection/reacceptance) fallback_rej = mask_w & valid_iat_edge & (iat_arr <= defaultIntArrThresh) & is_accepted_arr par_arr[fallback_rej] = REJECT_CODE_SHATTERING if reaccptShatrs == 1: fallback_reac = mask_w & (par_arr == REJECT_CODE_SHATTERING) & (part_diam_arr > reaccptD) & (iat_arr < reaccptMaxIAT) par_arr[fallback_reac] = REJECT_CODE_REACCEPTED # Fallback windows mutate rejection codes, so cluster expansion # must use the resulting acceptance state rather than the snapshot # captured before those windows were processed. is_accepted_arr = get_is_accepted() if isinstance(is_accepted_arr, xr.DataArray): is_accepted_arr = is_accepted_arr.values diagnostics_dict['tau_star'] = tau_star_arr diagnostics_dict['tau_star_source'] = tau_star_source_arr diagnostics_dict['window_diagnostics'] = window_diagnostics # Graph/Edge View of IAT: InterArrivalTime[i] links particle i-1 and i. # Only apply cluster expansion to windows where source == 'adaptive' and exclude negative IAT edges. short_edge = ( valid_iat_edge & (iat_arr <= tau_star_arr) & adaptive_source_mask & ~orig_negative_iat ) # Find runs of short edges run_starts = np.where(short_edge & ~np.roll(short_edge, 1))[0] run_ends = np.where(short_edge & ~np.roll(short_edge, -1))[0] for s, e in zip(run_starts, run_ends): cluster_indices = np.arange(s - 1, e + 1) accepted_in_cluster = cluster_indices[is_accepted_arr[cluster_indices]] if len(accepted_in_cluster) > 0: par_arr[accepted_in_cluster] = REJECT_CODE_SHATTERING # Reacceptance within rejected adaptive clusters. # Edge-aware check: inspect only incoming/outgoing edges that formed this cluster. if reaccptShatrs == 1: for idx in accepted_in_cluster: if part_diam_arr[idx] > reaccptD: out_edge = idx + 1 inc_ok = (s <= idx <= e) and (iat_arr[idx] < reaccptMaxIAT) out_ok = (s <= out_edge <= e) and (iat_arr[out_edge] < reaccptMaxIAT) if inc_ok or out_ok: par_arr[idx] = REJECT_CODE_REACCEPTED if isinstance(ParticleAutoReject, xr.DataArray): ParticleAutoReject.values = par_arr elif intArrThreshMode == 'probabilistic': iat_arr = np.asarray(InterArrivalTime) diam_arr = np.asarray(particle_diameter) is_acc_arr = get_is_accepted() if isinstance(is_acc_arr, xr.DataArray): is_acc_arr = is_acc_arr.to_numpy() par_arr = np.asarray(ParticleAutoReject) alpha_start = get_cfg('intArrProbAlphaStart', 0.01) alpha_extend = get_cfg('intArrProbAlphaExtend', 0.05) window_sec = get_cfg('intArrProbRollingWindowSec', 5) min_lambda = get_cfg('intArrProbMinLambda', 10.0) full_time = _resolve_particle_time_seconds(ds, time_sec) p_i, s_cid, s_conf, par_arr_out, lam_t = compute_probabilistic_shattering_clusters( full_time, iat_arr, orig_negative_iat, diam_arr, is_acc_arr, par_arr, alpha_start, alpha_extend, window_sec, min_lambda, reaccptShatrs, reaccptD, reaccptMaxIAT ) if isinstance(ParticleAutoReject, xr.DataArray): ParticleAutoReject.values = par_arr_out else: ParticleAutoReject = par_arr_out diagnostics_dict['iat_p_natural'] = p_i diagnostics_dict['poisson_lambda'] = lam_t diagnostics_dict['shatter_cluster_id'] = s_cid diagnostics_dict['shatter_confidence'] = s_conf diagnostics_dict['iat_qc_source'] = 2 elif intArrThreshMode == 'probabilistic_multifeature': iat_arr = np.asarray(InterArrivalTime) diam_arr = np.asarray(particle_diameter) ar_arr = np.asarray(area_ratio) is_acc_arr = get_is_accepted() if isinstance(is_acc_arr, xr.DataArray): is_acc_arr = is_acc_arr.to_numpy() par_arr = np.asarray(ParticleAutoReject) alpha_start = get_cfg('intArrProbAlphaStart', 0.01) alpha_extend = get_cfg('intArrProbAlphaExtend', 0.05) window_sec = get_cfg('intArrProbRollingWindowSec', 5) min_lambda = get_cfg('intArrProbMinLambda', 10.0) # Multifeature parameters mf_score_start = get_cfg('intArrMFScoreStart', 0.75) mf_score_extend = get_cfg('intArrMFScoreExtend', 0.55) w_iat = get_cfg('intArrMFIatWeight', 0.50) w_density = get_cfg('intArrMFDensityWeight', 0.15) w_size = get_cfg('intArrMFSizeWeight', 0.20) w_fragment = get_cfg('intArrMFFragmentWeight', 0.10) w_morph = get_cfg('intArrMFMorphWeight', 0.05) small_diam = get_cfg('intArrMFSmallDiameterMm', 0.20) parent_ratio = get_cfg('intArrMFParentRatio', 2.0) density_half_win = get_cfg('intArrMFDensityEdgeHalfWindow', 5) density_max_sec = get_cfg('intArrMFDensityMaxSeconds', 1e-3) ar_good = get_cfg('intArrMFAreaRatioGood', 0.6) full_time = _resolve_particle_time_seconds(ds, time_sec) # 1. Compute Poisson metrics lambda_t, p_i = compute_rolling_poisson_metrics(full_time, iat_arr, orig_negative_iat, window_sec, min_lambda) # 2. Compute edge component scores and composite score iat_s, dens_s, size_s, frag_s, morph_s, s_score = compute_multifeature_edge_scores( iat_arr, p_i, orig_negative_iat, diam_arr, ar_arr, full_time, w_iat, w_density, w_size, w_fragment, w_morph, alpha_extend, density_half_win, density_max_sec, small_diam, ar_good ) # 3. Compute clusters and roles s_cid, s_conf, s_role, par_arr_out = compute_multifeature_shattering_clusters( s_score, diam_arr, is_acc_arr, par_arr, reaccptShatrs, reaccptD, reaccptMaxIAT, parent_ratio, mf_score_start, mf_score_extend, iat_arr, orig_negative_iat ) if isinstance(ParticleAutoReject, xr.DataArray): ParticleAutoReject.values = par_arr_out else: ParticleAutoReject = par_arr_out diagnostics_dict['iat_p_natural'] = p_i diagnostics_dict['poisson_lambda'] = lambda_t diagnostics_dict['shatter_score'] = s_score diagnostics_dict['shatter_cluster_id'] = s_cid diagnostics_dict['shatter_confidence'] = s_conf diagnostics_dict['shatter_role'] = s_role diagnostics_dict['iat_score'] = iat_s diagnostics_dict['burst_density_score'] = dens_s diagnostics_dict['size_contrast_score'] = size_s diagnostics_dict['small_fragment_score'] = frag_s diagnostics_dict['morphology_score'] = morph_s diagnostics_dict['iat_qc_source'] = 3 else: raise ValueError(f"Unknown intArrThreshMode: '{intArrThreshMode}'. Available modes are: 'fixed', 'adaptive', 'probabilistic', 'probabilistic_multifeature'.") if return_diagnostics: return ParticleAutoReject, InterArrivalTime, diagnostics_dict return ParticleAutoReject, InterArrivalTime
[docs] def classify_particle_phase( arearatio_filled: np.ndarray, holroyd_habit: np.ndarray, diameter_mm: np.ndarray, diode_size_mm: float, Temp: np.ndarray | None = None, phase_method: str = "soda2_roundness", phase_roundness_mode: str = "standard", phase_area_ratio_floor: float = 0.40, phase_max_liquid_diameter_mm: float = 6.0, phase_size_rule_diodes: int = 10, ) -> np.ndarray: """ Classifies the thermodynamic phase of each particle into one of three classes: - 0: Unknown (unclassified or ambiguous morphology) - 1: Liquid Candidate (spherical water droplets) - 2: Ice Candidate (ice habit morphology or physical overrides) This implements a modified SODA2-style roundness algorithm combined with environmental temperature regimes. Parameters: ----------- arearatio_filled : np.ndarray Area ratio computed from the binary-filled image in image space [-] holroyd_habit : np.ndarray Array of Holroyd classification habit string characters (e.g. 's', 'h') diameter_mm : np.ndarray Particle diameter in millimeters [mm] diode_size_mm : float Optical resolution of the probe diodes in millimeters [mm] Temp : np.ndarray, optional Atmospheric temperature at the particle time in degrees Celsius [°C] phase_method : str Method for phase identification; must be "soda2_roundness" or "none" phase_roundness_mode : str Threshold mode for large drops; must be "standard" or "strict" phase_area_ratio_floor : float Additional minimum area-ratio floor used to reject hollow or highly irregular particles. In mixed-phase and morphology-only regimes, this can tighten but does not lower SODA2's fixed 0.40 tiny-particle threshold. The warm liquid-habit override uses this configurable value directly. phase_max_liquid_diameter_mm : float Maximum diameter threshold for liquid droplets; any particle larger than this is forced to ice phase_size_rule_diodes : int Size threshold in diodes (pixels) to separate tiny vs large particle rules Returns: -------- phase : np.ndarray Phase classification codes (0=Unknown, 1=Liquid, 2=Ice) History: -------- - 2026-07-06: Yongjie Huang, first created. """ if phase_method not in ("none", "soda2_roundness"): raise ValueError("classify_particle_phase handles none/soda2_roundness; " "ML phase requires stored classifier outputs through the pipeline") n_particles = len(arearatio_filled) phase = np.zeros(n_particles, dtype=np.int8) # If phase processing is globally disabled, return all unknown (0) if phase_method == "none": return phase # Calculate particle diameter in diode pixel units d_diodes = diameter_mm / diode_size_mm # Define SODA2 roundness thresholds based on standard vs strict roundness modes. # Large particles (diameter > size rule diodes) require: # - Standard: 0.50 AreaRatioFilled # - Strict: 0.70 AreaRatioFilled large_thresh = 0.50 if phase_roundness_mode == "standard" else 0.70 is_round_large = (arearatio_filled >= large_thresh) & (d_diodes > phase_size_rule_diodes) # SODA2 fixes the tiny-particle threshold at 0.40. The configurable # phase_area_ratio_floor is applied separately below as an additional # classification floor and therefore does not replace this baseline. is_round_tiny = ( (arearatio_filled >= SODA2_TINY_AREA_RATIO_THRESHOLD) & (d_diodes <= phase_size_rule_diodes) ) # Combine standard SODA2 liquid criteria is_soda2_liquid = is_round_large | is_round_tiny # Holroyd classification groupings: # - Ice habits: 'h' (hexagonal), 'd' (dendrite), 'a' (aggregates), 'g' (graupel), # 'i' (irregular), 'l' (linear/columns), 'o' (other ice) # - Liquid habits: 's' (spherical), 't' (tiny) is_ice_habit = np.isin(holroyd_habit, ['h', 'd', 'a', 'g', 'i', 'l', 'o']) is_liquid_habit = np.isin(holroyd_habit, ['s', 't']) # Apply classification using temperature context when available if Temp is not None: temp_arr = np.asarray(Temp, dtype=float) # 1. Homogeneous freezing regime (Temp < -40°C): # All liquid drops are assumed frozen; classify as Ice Candidate (2) ice_temp_mask = temp_arr < -40.0 # 2. Warm regime (Temp > 0°C): # Particles are classified as liquid if they satisfy SODA2 roundness OR have a # spherical/tiny morphology habit and meet the area ratio floor requirement. warm_mask = temp_arr > 0.0 liquid_warm = warm_mask & (is_soda2_liquid | (is_liquid_habit & (arearatio_filled >= phase_area_ratio_floor))) # 3. Mixed phase regime (-40°C <= Temp <= 0°C): # Rely strictly on SODA2 roundness criteria to distinguish spherical candidates. liquid_mixed = (temp_arr >= -40.0) & (temp_arr <= 0.0) & is_soda2_liquid is_liquid = liquid_warm | liquid_mixed # Assign to Ice: homogeneous freezing, size limits, area ratio below the floor limit, # or Holroyd-identified ice habit that failed the liquid roundness check. is_ice = ( ice_temp_mask | (diameter_mm > phase_max_liquid_diameter_mm) | (arearatio_filled < phase_area_ratio_floor) | (~is_liquid & is_ice_habit) ) else: # Fallback to morphology-only classification if Temp is unavailable is_liquid = is_soda2_liquid is_ice = ( (diameter_mm > phase_max_liquid_diameter_mm) | (arearatio_filled < phase_area_ratio_floor) | (~is_liquid & is_ice_habit) ) # Assign phase codes (mutually exclusive) phase[is_ice] = 2 phase[is_liquid & ~is_ice] = 1 return phase
def _validate_user_tas_values(values, *, input_name: str = "tas") -> np.ndarray: """Return user-supplied TAS values as a finite, positive float array.""" raw_values = np.asarray(values) if raw_values.dtype.kind not in "iuf": raise TypeError(f"{input_name} must contain numeric values in m s-1") tas_values = raw_values.astype(np.float64, copy=False) if not np.all(np.isfinite(tas_values)) or np.any(tas_values <= 0): if tas_values.ndim == 0: raise ValueError(f"{input_name} must be a finite, positive number in m s-1") raise ValueError(f"{input_name} must contain only finite, positive values in m s-1") return tas_values def _find_tas_time_coordinate(tas: xr.DataArray) -> xr.DataArray | None: """Find an explicit one-dimensional time coordinate attached to TAS.""" if tas.ndim != 1: return None tas_dim = tas.dims[0] for coord_name, coord in tas.coords.items(): if coord.dims != (tas_dim,) or coord.size != tas.size: continue coord_values = np.asarray(coord.values) is_time_dtype = ( np.issubdtype(coord_values.dtype, np.datetime64) or np.issubdtype(coord_values.dtype, np.timedelta64) ) if "time" in coord_name.lower() or is_time_dtype: return coord return None def _particle_relative_time_seconds(ds_out: xr.Dataset) -> np.ndarray: """Return particle timestamps as seconds relative to the SPIF start date.""" if 'time_sec' not in ds_out: raise ValueError( "Time-aware tas input requires the Level-1 dataset to contain 'time_sec'." ) particle_time = np.asarray(ds_out['time_sec'].values, dtype=np.float64) if 'time_ns' in ds_out: particle_time = particle_time + np.asarray(ds_out['time_ns'].values, dtype=np.float64) * 1e-9 return particle_time def _particle_epoch_time_seconds(ds_out: xr.Dataset) -> np.ndarray: """Return particle timestamps as seconds since the Unix epoch.""" if 'time' not in ds_out: raise ValueError( "Datetime tas input requires the Level-1 dataset to contain the absolute 'time' variable." ) return np.asarray(ds_out['time'].values, dtype=np.float64) def _resolve_user_tas_for_particles( ds_out: xr.Dataset, tas: float | np.ndarray | xr.DataArray | list[float] | tuple[float, ...], ) -> xr.DataArray: """ Resolve scalar, particle-aligned, or time-aware user TAS to the particle dimension. Time-aware TAS is linearly interpolated within its time range. Values outside that range use the nearest endpoint TAS so that particles are not discarded. Numeric ``time`` coordinates are interpreted as Unix-epoch seconds; other numeric time coordinates are interpreted as seconds relative to SPIF start. """ particle_count = ds_out.sizes.get('particle', 0) particle_coords = {'particle': ds_out['particle']} if 'particle' in ds_out.coords else None if isinstance(tas, xr.DataArray): if tas.ndim != 1: raise ValueError(f"tas DataArray must be one-dimensional, got dimensions {tas.dims!r}") tas_values = _validate_user_tas_values(tas.values) time_coord = _find_tas_time_coordinate(tas) if time_coord is not None: if tas_values.size == 0: raise ValueError("Time-aware tas input must contain at least one value") source_time_values = np.asarray(time_coord.values) if np.issubdtype(source_time_values.dtype, np.datetime64): source_time = ( source_time_values.astype('datetime64[ns]') - np.datetime64('1970-01-01T00:00:00', 'ns') ) / np.timedelta64(1, 's') particle_time = _particle_epoch_time_seconds(ds_out) time_basis = 'datetime' elif np.issubdtype(source_time_values.dtype, np.timedelta64): source_time = source_time_values / np.timedelta64(1, 's') particle_time = _particle_relative_time_seconds(ds_out) time_basis = 'elapsed_seconds' else: try: source_time = source_time_values.astype(np.float64) except (TypeError, ValueError) as exc: raise TypeError("tas time coordinate must be numeric or datetime-like") from exc if time_coord.name == 'time': particle_time = _particle_epoch_time_seconds(ds_out) time_basis = 'epoch_seconds' else: particle_time = _particle_relative_time_seconds(ds_out) time_basis = 'seconds_since_spif_start' source_time = np.asarray(source_time, dtype=np.float64) particle_time = np.asarray(particle_time, dtype=np.float64) if not np.all(np.isfinite(source_time)) or not np.all(np.isfinite(particle_time)): raise ValueError("tas and particle time coordinates must contain only finite values") if source_time.size > 1 and np.any(np.diff(source_time) <= 0): raise ValueError("tas time coordinate must be strictly increasing with no duplicates") if source_time.size == 1: resolved_values = np.full(particle_count, tas_values[0], dtype=np.float64) else: # np.interp is linear inside the measured interval and holds the # nearest endpoint outside it, retaining all particle images. resolved_values = np.interp(particle_time, source_time, tas_values) extrapolated = (particle_time < source_time[0]) | (particle_time > source_time[-1]) extrapolated_count = int(np.count_nonzero(extrapolated)) if extrapolated_count: warnings.warn( f"{extrapolated_count} particle timestamps fall outside the supplied tas " "time range; COPS is retaining them with nearest-endpoint TAS values.", UserWarning, stacklevel=3, ) tas_data = xr.DataArray( resolved_values.astype(np.float32), dims=('particle',), coords=particle_coords, ) tas_data.attrs = { 'long_name': 'True airspeed', 'units': 'm s-1', 'source': 'user_input_time_series', 'alignment': 'interpolated_to_particle_time', 'time_basis': time_basis, 'interpolation_method': 'linear', 'extrapolation_method': 'nearest_endpoint', 'extrapolated_particle_count': extrapolated_count, } return tas_data else: tas_values = np.asarray(tas) if tas_values.ndim == 0: if isinstance(tas, (bool, np.bool_)): raise TypeError("tas must be a finite, positive number in m s-1") tas_value = _validate_user_tas_values(tas_values).item() tas_data = xr.DataArray( np.full(particle_count, tas_value, dtype=np.float32), dims=('particle',), coords=particle_coords, ) tas_data.attrs = { 'long_name': 'True airspeed', 'units': 'm s-1', 'source': 'user_input_constant', 'user_input_value': float(tas_value), } return tas_data if tas_values.ndim != 1: raise ValueError(f"tas array must be one-dimensional, got shape {tas_values.shape!r}") tas_values = _validate_user_tas_values(tas_values) if tas_values.size != particle_count: raise ValueError( "tas array without timestamps must have one value per Level-1 particle: " f"expected {particle_count}, got {tas_values.size}" ) warnings.warn( "tas input has no time coordinate; COPS is treating it as already aligned " "with the Level-1 particle order.", UserWarning, stacklevel=3, ) tas_data = xr.DataArray( tas_values.astype(np.float32), dims=('particle',), coords=particle_coords, ) tas_data.attrs = { 'long_name': 'True airspeed', 'units': 'm s-1', 'source': 'user_input_aligned_array', 'alignment': 'assumed_particle_order', } return tas_data _MISSING_OVERLOAD_POLICIES = frozenset( ('warn_nominal', 'invalidate', 'error') ) _OVERLOAD_STATUS_NATIVE = np.uint8(0) _OVERLOAD_STATUS_INFERRED = np.uint8(1) _OVERLOAD_STATUS_NOMINAL_ASSUMED = np.uint8(2) _OVERLOAD_STATUS_INVALID = np.uint8(3) def _validate_missing_overload_policy(policy: str) -> str: """Validate and return the configured missing-overload policy.""" if policy not in _MISSING_OVERLOAD_POLICIES: raise ValueError( "missing_overload_policy must be 'warn_nominal', 'invalidate', or " f"'error', got {policy!r}" ) return policy def _complete_overload_status(source: str) -> np.uint8: """Return the Level-2 status code for a complete overload source.""" if source.startswith('inferred_from_'): return _OVERLOAD_STATUS_INFERRED return _OVERLOAD_STATUS_NATIVE def _propagate_overload_flag(ds_out: xr.Dataset, ds_images: xr.Dataset, probe_type: int, missing_overload_policy: str = 'warn_nominal') -> xr.Dataset: """Preserve or infer the particle overload flag used for dead-time estimation.""" policy = _validate_missing_overload_policy(missing_overload_policy) probe_name = PROBE_CATEGORIES.get(probe_type, ('unknown',))[0] if 'overload_flag' in ds_out.variables: source = ds_out['overload_flag'].attrs.get( 'source', 'existing_level1_overload_flag' ) existing_flags = np.asarray( ds_out['overload_flag'].values, dtype=np.float64 ) missing_count = int(np.count_nonzero( ~np.isfinite(existing_flags) | (existing_flags == 255) )) ds_out.attrs['overload_correction_source'] = source ds_out.attrs['missing_overload_policy'] = policy if missing_count: if policy == 'error': raise ValueError( "Overload status is missing for " f"{missing_count} of {existing_flags.size} particles from source " f"{source} and missing_overload_policy='error'." ) outcome = ( "affected Level-2 output will be invalidated" if policy == 'invalidate' else "nominal sample time will be assumed for missing portions" ) logger.warning( "Overload status is missing for %d of %d particles from source %s; " "%s.", missing_count, existing_flags.size, source, outcome, ) else: logger.info( "Using overload dead-time source %s for %s (probe_type=%s)", source, probe_name, probe_type, ) return ds_out particle_count = ds_out.sizes.get('particle', 0) flag_values = None source = None expected_source = None if 'overload_flag' in ds_images.variables: raw_flag = np.asarray(ds_images['overload_flag'].values, dtype=np.float64) if raw_flag.ndim != 1 or raw_flag.size != particle_count: raise ValueError( "The core-group 'overload_flag' must be one-dimensional and particle-aligned: " f"expected {particle_count} values, got shape {raw_flag.shape}." ) missing = np.isnan(raw_flag) if not np.all(np.isin(raw_flag[~missing], (0, 1))): raise ValueError( "The core-group 'overload_flag' must contain active-high values 0 or 1, " "or be missing." ) flag_values = np.where(missing, 255, raw_flag).astype(np.uint8) source = 'probe_overload_flag' elif probe_type in _DMT_COUNTER_PROBE_TYPES: counter_name = next( (name for name in ('particle_count', 'image_count') if name in ds_images.variables), None, ) if counter_name is not None: counter = np.asarray(ds_images[counter_name].values, dtype=np.float64) if counter.ndim != 1 or counter.size != particle_count: raise ValueError( f"The core-group '{counter_name}' must be one-dimensional and particle-aligned: " f"expected {particle_count} values, got shape {counter.shape}." ) flag_values = np.zeros(particle_count, dtype=np.uint8) if particle_count > 1: valid_pair = np.isfinite(counter[:-1]) & np.isfinite(counter[1:]) counter_step = np.mod(counter[1:] - counter[:-1], 2**16) flag_values[1:][valid_pair] = (counter_step[valid_pair] != 1).astype(np.uint8) flag_values[1:][~valid_pair] = np.uint8(255) source = f'inferred_from_{counter_name}' elif probe_type in _PMS_BUFFER_GAP_PROBE_TYPES and 'buffer_index' in ds_images.variables: buffer_index = np.asarray(ds_images['buffer_index'].values, dtype=np.float64) if buffer_index.ndim != 1 or buffer_index.size != particle_count: raise ValueError( "The core-group 'buffer_index' must be one-dimensional and particle-aligned: " f"expected {particle_count} values, got shape {buffer_index.shape}." ) flag_values = np.zeros(particle_count, dtype=np.uint8) if particle_count > 1: valid_pair = np.isfinite(buffer_index[:-1]) & np.isfinite(buffer_index[1:]) flag_values[1:][valid_pair] = ( buffer_index[1:][valid_pair] != buffer_index[:-1][valid_pair] ).astype(np.uint8) flag_values[1:][~valid_pair] = np.uint8(255) source = 'inferred_from_buffer_index' if flag_values is None: if probe_type in PROBE_CATEGORIES: if probe_type in _DMT_COUNTER_PROBE_TYPES: expected_source = "'particle_count' or 'image_count'" elif probe_type in _PMS_BUFFER_GAP_PROBE_TYPES: expected_source = "'buffer_index'" else: expected_source = "'overload_flag'" flag_values = np.full(particle_count, 255, dtype=np.uint8) source = 'unavailable' else: return ds_out overload_meta = LEVEL_1_VARIABLES['overload_flag'] overload_attrs = copy.deepcopy(overload_meta['attrs']) overload_attrs['source'] = source ds_out['overload_flag'] = xr.DataArray( data=flag_values.astype(overload_meta['dtype']), dims=(overload_meta['dims'],), attrs=overload_attrs, ) ds_out.attrs['overload_correction_source'] = source ds_out.attrs['missing_overload_policy'] = policy missing_count = int(np.count_nonzero(flag_values == 255)) if missing_count: if policy == 'error': raise ValueError( "Overload status is missing for " f"{missing_count} of {particle_count} particles from source {source} " "and missing_overload_policy='error'." ) outcome = ( "Level-2 output will be invalidated" if policy == 'invalidate' else "nominal sample time will be assumed for missing portions" ) if source == 'unavailable': logger.warning( "No recognized overload source (%s) found for %s (probe_type=%s); %s.", expected_source, probe_name, probe_type, outcome, ) else: logger.warning( "Overload status is missing for %d of %d particles from source %s; %s.", missing_count, particle_count, source, outcome, ) elif not missing_count: logger.info( "Using overload dead-time source %s for %s (probe_type=%s)", source, probe_name, probe_type, ) return ds_out
[docs] def apply_level1_bulk_properties_and_qc(ds_out: xr.Dataset, ds_images: xr.Dataset, config: ProbeProcessingConfig | ConfigParser, tas: float | np.ndarray | xr.DataArray | list[float] | tuple[float, ...] | None = None) -> xr.Dataset: """ Applies bulk property calculations and inter-arrival time quality control (QC) to a Level-1 single-particle dataset. Parameters: ----------- ds_out : xarray.Dataset The Level-1 dataset containing single-particle geometric and morphological variables. ds_images : xarray.Dataset The core group dataset containing environmental variables (`tas`, `Pres`, `Temp`) and the active-high DMT ``dof_flag`` when provided by the probe decoder. config : ProbeProcessingConfig | configparser.ConfigParser The configuration object or parser containing processing parameters and QC thresholds. ``applyLevel1BulkAndQC=0`` skips the Level-1 bulk, phase, and QC calculations. tas : float, 1D array, or xarray.DataArray, optional True airspeed in m s-1 to use only when ``ds_images`` does not contain ``tas``. A scalar is broadcast to all particles. A timestamp-free 1D array must have one value per particle and emits a warning because particle-order alignment is assumed. A time-aware DataArray is linearly interpolated to particle time and uses its nearest endpoint outside the supplied time range. Returns: -------- xarray.Dataset The updated Level-1 dataset containing derived bulk properties and final QC flags. History: -------- - 2026-07-18: Yongjie Huang, propagated the active-high DMT ``dof_flag`` and overload information into Level-1. - 2026-07-17: Yongjie Huang, added a default-enabled configuration switch for Level-1 bulk and QC calculations. - 2026-07-17: Yongjie Huang, added aligned-array and time-aware TAS inputs with endpoint extrapolation. - 2026-07-16: Yongjie Huang, added a validated user TAS fallback for core datasets without TAS. - 2026-07-06: Yongjie Huang, integrated classify_particle_phase and computed liquid mass, terminal velocity, and precipitation rate contributions. - 2026-06-27: Yongjie Huang, extracted to a dedicated helper function for cleaner Level-1 pipeline structure. """ cfg = ensure_probe_config(config) apply_level1_bulk_and_qc = cfg.image.applyLevel1BulkAndQC == 1 ds_out = _propagate_overload_flag( ds_out, ds_images, cfg.size.probe_type, cfg.size.missing_overload_policy, ) # Preserve the probe-native active-high DMT depth-of-field flag in Level-1. # Level-1 processing retains SPIF core-group particle order, so this transfer # is positional after explicitly validating the one-to-one particle count. if 'dof_flag' in ds_images.variables: dof_values = np.asarray(ds_images['dof_flag'].values, dtype=np.float64) particle_count = ds_out.sizes.get('particle', 0) if dof_values.ndim != 1 or dof_values.size != particle_count: raise ValueError( "The core-group 'dof_flag' must be one-dimensional and particle-aligned: " f"expected {particle_count} values, got shape {dof_values.shape}." ) dof_meta = LEVEL_1_VARIABLES['dof_flag'] missing_dof = np.isnan(dof_values) if not np.all(np.isin(dof_values[~missing_dof], (0, 1))): raise ValueError( "The core-group 'dof_flag' must contain active-high values 0 or 1, " "or be missing." ) dof_fill_value = dof_meta['attrs']['_FillValue'] encoded_dof_values = np.where( missing_dof, dof_fill_value, dof_values ).astype(dof_meta['dtype']) missing_count = int(np.count_nonzero(missing_dof)) if missing_count: logger.warning( "The core-group 'dof_flag' contains %d missing value(s); preserving " "them as fill values and excluding them from depth-of-field rejection.", missing_count, ) ds_out['dof_flag'] = xr.DataArray( data=encoded_dof_values, dims=(dof_meta['dims'],), attrs=dof_meta['attrs'], ) #--- Resolve TAS before the optional bulk/QC stage so a supplied fallback is # retained for downstream Level-2 processing even when this stage is disabled. tas_data = None if 'tas' in ds_images.variables: tas_data = ds_images['tas'].rename({'Images': 'particle'}) elif tas is not None: tas_data = _resolve_user_tas_for_particles(ds_out, tas) # Persist the fallback in Level-1 so downstream Level-2 processing does not # require a TAS variable in the original core group. ds_out['tas'] = tas_data ds_out.attrs['tas_source'] = tas_data.attrs['source'] if 'alignment' in tas_data.attrs: ds_out.attrs['tas_alignment'] = tas_data.attrs['alignment'] if 'interpolation_method' in tas_data.attrs: ds_out.attrs['tas_interpolation_method'] = tas_data.attrs['interpolation_method'] ds_out.attrs['tas_extrapolation_method'] = tas_data.attrs['extrapolation_method'] ds_out.attrs['tas_extrapolated_particle_count'] = tas_data.attrs['extrapolated_particle_count'] if 'user_input_value' in tas_data.attrs: ds_out.attrs['tas_user_input'] = tas_data.attrs['user_input_value'] if not apply_level1_bulk_and_qc: ds_out.attrs['level1_bulk_qc_status'] = 'disabled' return ds_out if tas_data is None: raise ValueError( "The core image dataset does not contain 'tas'. Provide a finite, positive " "scalar, particle-aligned array, or time-aware DataArray with tas=<m s-1>, " "or set applyLevel1BulkAndQC=0 for geometry-only Level-1 processing." ) ds_out.attrs['level1_bulk_qc_status'] = 'enabled' Pres = ds_images['Pres'].rename({'Images': 'particle'}) if 'Pres' in ds_images.variables else None Temp = ds_images['Temp'].rename({'Images': 'particle'}) if 'Temp' in ds_images.variables else None probe_type = cfg.size.probe_type tasMax = cfg.image.tasMax diameter_choice = cfg.size.diameter_choice applyIntArrThresh = cfg.size.applyIntArrThresh defaultIntArrThresh = cfg.size.defaultIntArrThresh reaccptShatrs = cfg.size.reaccptShatrs reaccptD = cfg.size.reaccptD reaccptMaxIAT = cfg.size.reaccptMaxIAT accepted_codes = list(cfg.size.accepted_codes) #--- Correct particle areas for airspeeds exceeding tasMax # This operation will stretch the area of the particle for airspeeds exceeding tasMax. # It applies the stretching factor (tas_val / tasMax) only where tas > tasMax. # Otherwise, it keeps the original area. ParticleArea = ds_out['ParticleArea'] ParticleArea = ParticleArea.where(tas_data <= tasMax, ParticleArea * tas_data / tasMax) ds_out['ParticleArea'] = ParticleArea #--- Select diameter based on diameter_choice (8-11: selected ML diameter with the # configured per-particle fallback; the same resolver serves Level-2) particle_diameter = resolve_particle_diameter_um( ds_out, diameter_choice, cfg.ml.fallback, cfg.ml.min_n_s) * 1e-3 # [um] -> [mm] #--- Calculate all particle properties using helper function ParticleHabit = ds_out['HolroydHabit'] habit_str = ParticleHabit.astype(str) # Convert habit codes to strings if they are not already props = calculate_particle_bulk_properties( particle_diameter, ParticleArea, habit_str, Pres=Pres, Temp=Temp ) #-- Extract properties from returned dictionary and store in ds_out for var_name in ['particle_mass', 'calcd_area', 'particle_massbl', 'area_ratio', 'particle_vt', 'particle_pr']: meta = LEVEL_1_VARIABLES[var_name] dims = [meta['dims']] if isinstance(meta['dims'], str) else meta['dims'] ds_out[var_name] = xr.DataArray( data=np.array(props[var_name], dtype=meta['dtype']), dims=dims, attrs=meta['attrs'] ) #--- Phase classification and liquid properties calculation diode_size_mm = float(ds_out.attrs.get('diode_size', getattr(cfg.size, 'diode_size', getattr(cfg.image, 'diode_size', 0.025)))) if 'AreaRatioFilled' in ds_out.variables: arearatio_filled = ds_out['AreaRatioFilled'].values else: arearatio_filled = np.asarray(props['area_ratio'], dtype=float) d_clean = np.where(particle_diameter.values > 0, particle_diameter.values, 0.0) # in mm if cfg.image.phase_method in ML_PHASE_METHODS: particle_phase_vals = selected_ml_phase(ds_out, cfg.image.phase_method) else: particle_phase_vals = classify_particle_phase( arearatio_filled=arearatio_filled, holroyd_habit=habit_str.values, diameter_mm=d_clean, diode_size_mm=diode_size_mm, Temp=Temp, phase_method=cfg.image.phase_method, phase_roundness_mode=cfg.image.phase_roundness_mode, phase_area_ratio_floor=cfg.image.phase_area_ratio_floor, phase_max_liquid_diameter_mm=cfg.image.phase_max_liquid_diameter_mm, phase_size_rule_diodes=cfg.image.phase_size_rule_diodes, ) # Store particle_phase in ds_out meta_phase = LEVEL_1_VARIABLES['particle_phase'] ds_out['particle_phase'] = xr.DataArray( data=particle_phase_vals, dims=[meta_phase['dims']] if isinstance(meta_phase['dims'], str) else meta_phase['dims'], attrs=meta_phase['attrs'] ) if cfg.image.phase_method in ML_PHASE_METHODS: ds_out['particle_phase'].attrs.update({ 'phase_method': cfg.image.phase_method, 'source_variable': f"ml_phase_{ML_PHASE_METHODS[cfg.image.phase_method]}", 'description': "Liquid/ice candidate derived from uncalibrated synthetic " "drops/columns/ice classifier scores; 0 denotes unavailable prediction. " "Temperature is not used in ML phase selection.", }) # Compute particle_mass_liquid (in grams, using 1e-3 * pi/6 * D^3) particle_mass_liquid = np.where( particle_phase_vals == 1, 1e-3 * (np.pi / 6.0) * d_clean**3, 0.0 ) meta_mass_liq = LEVEL_1_VARIABLES['particle_mass_liquid'] ds_out['particle_mass_liquid'] = xr.DataArray( data=particle_mass_liquid.astype(meta_mass_liq['dtype']), dims=[meta_mass_liq['dims']] if isinstance(meta_mass_liq['dims'], str) else meta_mass_liq['dims'], attrs=meta_mass_liq['attrs'] ) # Compute particle_vt_liquid and particle_pr_liquid area_ratio_capped = np.clip(props['area_ratio'], 0.0, 1.0) if Pres is None: pres_arr = np.full_like(d_clean, DEFAULT_PRESSURE, dtype=float) else: pres_arr = np.asarray(Pres.values if hasattr(Pres, 'values') else Pres, dtype=float) if Temp is None: temp_arr = np.full_like(d_clean, DEFAULT_TEMPERATURE, dtype=float) else: temp_arr = np.asarray(Temp.values if hasattr(Temp, 'values') else Temp, dtype=float) particle_vt_liquid_vals = vectorized_single_vt( d_clean * 1e-3, # Convert mm to m area_ratio_capped, particle_mass_liquid * 1e-3, # Convert g to kg pres_arr, temp_arr ) # Set non-liquid to 0.0 particle_vt_liquid_vals = np.where(particle_phase_vals == 1, particle_vt_liquid_vals, 0.0) meta_vt_liq = LEVEL_1_VARIABLES['particle_vt_liquid'] ds_out['particle_vt_liquid'] = xr.DataArray( data=particle_vt_liquid_vals.astype(meta_vt_liq['dtype']), dims=[meta_vt_liq['dims']] if isinstance(meta_vt_liq['dims'], str) else meta_vt_liq['dims'], attrs=meta_vt_liq['attrs'] ) particle_pr_liquid_vals = particle_mass_liquid * particle_vt_liquid_vals meta_pr_liq = LEVEL_1_VARIABLES['particle_pr_liquid'] ds_out['particle_pr_liquid'] = xr.DataArray( data=particle_pr_liquid_vals.astype(meta_pr_liq['dtype']), dims=[meta_pr_liq['dims']] if isinstance(meta_pr_liq['dims'], str) else meta_pr_liq['dims'], attrs=meta_pr_liq['attrs'] ) #--- Apply all quality control filters using helper function ParticleAutoReject, InterArrivalTime, diagnostics = apply_quality_control_InterArrivalTime( ds_out['ParticleAutoReject'], ds_out['InterArrivalTime'], particle_diameter, props['area_ratio'], ds_out, applyIntArrThresh, defaultIntArrThresh, reaccptShatrs, reaccptD, reaccptMaxIAT, probe_type, accepted_codes=accepted_codes, tas=tas_data, time_sec=ds_out.get('time_sec', ds_images.get('time_sec', None)), diode_size=ds_out.attrs.get('diode_size', getattr(cfg.size, 'diode_size', getattr(cfg.image, 'diode_size', 0.025))), size_config=cfg.size, return_diagnostics=True ) ds_out['ParticleAutoReject'] = ParticleAutoReject ds_out['InterArrivalTime'] = InterArrivalTime get_cfg = lambda name, default: getattr(cfg.size, name, (cfg.size.attrs.get(name, default) if hasattr(cfg.size, 'attrs') else default)) if cfg.size is not None else default int_arr_thresh_mode = get_cfg('intArrThreshMode', 'fixed') ds_out.attrs['iat_qc_source'] = int_arr_thresh_mode if int_arr_thresh_mode == 'adaptive': iat_diagnostics = ['tau_star', 'tau_star_source'] elif applyIntArrThresh == 1 and int_arr_thresh_mode == 'probabilistic' and 'iat_p_natural' in diagnostics: iat_diagnostics = ['iat_p_natural', 'poisson_lambda', 'shatter_cluster_id', 'shatter_confidence'] elif applyIntArrThresh == 1 and int_arr_thresh_mode == 'probabilistic_multifeature' and 'shatter_score' in diagnostics: # Always write core multifeature diagnostics iat_diagnostics = ['iat_p_natural', 'poisson_lambda', 'shatter_score', 'shatter_cluster_id', 'shatter_confidence', 'shatter_role'] # Conditionally write component diagnostics if get_cfg('intArrMFWriteComponentDiagnostics', 0) == 1: iat_diagnostics += [k for k in IAT_MF_COMPONENT_SCORES if k in diagnostics] else: iat_diagnostics = [] for var_name in iat_diagnostics: meta = LEVEL_1_VARIABLES[var_name] dims = [meta['dims']] if isinstance(meta['dims'], str) else meta['dims'] ds_out[var_name] = xr.DataArray( data=np.array(diagnostics[var_name], dtype=meta['dtype']), dims=dims, attrs=dict(meta['attrs']) ) # Record the diameter selection these bulk/QC arrays were computed with. Only this # step writes the record, so it certifies an actual computation (Level-2 and # size_distribution_segment refuse to reuse the arrays under another selection). ds_out.attrs.update(provenance_attrs( bulk_selection_record(ds_out, diameter_choice, cfg.ml.fallback, cfg.ml.min_n_s), None)) # Likewise record the QC settings the ParticleAutoReject codes were made with. ds_out.attrs.update(qc_settings_attrs(qc_settings_record(cfg.size))) if cfg.classification.enabled or has_ml_classification_provenance(ds_out.attrs): produced = json.loads(ds_out.attrs[ML_CLASSIFICATION_OUTPUTS_ATTR]) if ML_CLASSIFICATION_OUTPUTS_ATTR in ds_out.attrs else None ds_out.attrs.update(phase_attrs(phase_record(cfg.image, produced))) return ds_out
# endregion # ============================================================================== # MARK: SECTION 5: LEVEL-2 DISTRIBUTIONS & SPIF APPEND # ============================================================================== # region SECTION 5: LEVEL-2 DISTRIBUTIONS & SPIF APPEND # Particle masking, sample-area and sample-volume calculation, size distributions, # concentration normalization, groupby parallelism, and the # public SPIF Level-2 append entry point. # Functions: get_particle_masks, compute_distributions, calculate_sample_area, # calculate_sample_volume, normalize_and_calculate_concentrations, # create_bulk_output_dataset, size_distribution_segment, # size_distribution_process_group, parallel_processing_DatasetGroupBy, # process_spif_level1_append_level2_data # ==============================================================================
[docs] def get_particle_masks(ParticleAutoReject: xr.DataArray, SAmethod: int, CenterIn: xr.DataArray, EntireIn: xr.DataArray, accepted_codes: list = ACCEPTED_CODES) -> tuple[xr.DataArray, xr.DataArray]: """ Generates boolean masks for good (accepted) and bad (rejected) particles. Parameters: ----------- ParticleAutoReject : xarray.DataArray Array containing rejection codes for each particle. SAmethod : int Sample Area method (0: Center-in, 1: Entire-in, 2: Correction). NOTE: Method 2 currently uses the same center-in acceptance as method 0; combined with the 0.72*D effective-array-width extension in calculate_sample_area(). CenterIn : xarray.DataArray Boolean array indicating if particle center is in DOF. EntireIn : xarray.DataArray Boolean array indicating if particle is entirely in DOF. Returns: -------- good_particles : boolean mask bad_particles : boolean mask History: -------- - 2025-12-29: Yongjie Huang, first created. """ # Define accepted particle rejection codes # ASCII reject code: # "0": accepted; # "H": accepted hollow particle; # "R": reaccepted after shattering check; # "a": aspect ratio > 6; # "t": aspect ratio > 5 + image touching edge; # "p": < 25% shadowed diodes in rectangle encompassing particle; # "h": rejected hollow particle (no valid edge); # "u": rejected hollow particle (unphysical area hole ratio); # "s": split image; # "z"/"f": zero area image; # "r": area ratio < 0.2; # "D": DMT DOF overload; # "I": negative inter-arrival time; # "S": shattering artifact if accepted_codes in (['all'], ('all',)): good_particles = xr.DataArray(np.ones_like(ParticleAutoReject, dtype=bool), coords=ParticleAutoReject.coords, dims=ParticleAutoReject.dims) else: good_particles = ParticleAutoReject.isin(accepted_codes) bad_particles = ~good_particles # print('ParticleAutoReject:', ParticleAutoReject.size, # 'good_particles.sum():', good_particles.sum().values, # 'good_particles.size:', good_particles.size) # Apply Sample Area method logic if SAmethod in (0, 2): good_particles = good_particles & (CenterIn == 1) bad_particles = bad_particles & (CenterIn == 1) elif SAmethod == 1: good_particles = good_particles & (EntireIn == 1) bad_particles = bad_particles & (EntireIn == 1) return good_particles, bad_particles
[docs] def compute_distributions(mask, diameter, diameter_AreaR, bin_edges, area_bins, iwc, partarea, iwcbl, vt, pr, ParticleArea, habit, habits, area_ratio, entirein_mask=None, AspectRatioRect=None, AspectRatioElli=None, iCreateAspectRatio=0): """ Computes size distributions and related metrics for a subset of particles defined by 'mask'. Returns a dictionary containing all computed distributions. History: -------- - 2025-12-29: Yongjie Huang, first created. """ num_bins = len(bin_edges) - 1 # Initialize results dictionary with zeros results = { 'count': np.zeros((num_bins,)), 'count_AreaR': np.zeros((num_bins,)), 'HabitSD': np.zeros((num_bins, len(habits))), 'HabitMSD': np.zeros((num_bins, len(habits))), 'area': np.zeros((num_bins,)), 'partarea': np.zeros((num_bins,)), 'iwc': np.zeros((num_bins,)), 'iwcbl': np.zeros((num_bins,)), 'vt': np.zeros((num_bins,)), 'pr': np.zeros((num_bins,)), 'area_dist2': np.zeros((num_bins, len(area_bins)-1)), 'mean_ar1': np.zeros((num_bins,)), 'mean_aspect_rect': np.zeros((num_bins,)), 'mean_aspect_elli': np.zeros((num_bins,)) } if mask.sum() == 0: return results # Helper for binned statistics def _binned_stat(data, values, statistic): stat, _, _ = binned_statistic(data, values, statistic=statistic, bins=bin_edges) return stat # Filter data by mask d = diameter[mask] d_AreaR = diameter_AreaR[mask] # 1. Basic counts results['count'] = _binned_stat(d, None, 'count') results['count_AreaR'] = _binned_stat(d_AreaR, None, 'count') # 2. Habit distributions h = habit[mask] w_iwc = iwc[mask] for k, hab in enumerate(habits): h_idx = (h == hab) if h_idx.any(): d_h = d[h_idx] results['HabitSD'][:, k] = _binned_stat(d_h, None, 'count') results['HabitMSD'][:, k] = _binned_stat(d_h, w_iwc[h_idx], 'sum') # 3. Summed distributions (Mass, Area, etc.) # Note: 'area' corresponds to ParticleArea (measured), 'partarea' corresponds to calcd_area results['area'] = _binned_stat(d, ParticleArea[mask], 'sum') results['partarea'] = _binned_stat(d, partarea[mask], 'sum') results['iwc'] = _binned_stat(d, iwc[mask], 'sum') results['iwcbl'] = _binned_stat(d, iwcbl[mask], 'sum') results['vt'] = _binned_stat(d, vt[mask], 'sum') results['pr'] = _binned_stat(d, pr[mask], 'sum') # 4. Aspect Ratio & specialized stats (require entire-in mask or sub-selection) if entirein_mask is not None and entirein_mask.sum() > 0: diameter1 = diameter[entirein_mask] ar1 = area_ratio[entirein_mask] results['mean_ar1'] = _binned_stat(diameter1, ar1, 'mean') if iCreateAspectRatio == 1 and AspectRatioRect is not None: results['mean_aspect_rect'] = _binned_stat(diameter1, AspectRatioRect[entirein_mask], 'mean') results['mean_aspect_elli'] = _binned_stat(diameter1, AspectRatioElli[entirein_mask], 'mean') # 5. 2D Area Ratio Distribution ar = area_ratio[mask] # binned_statistic_2d returns count in each 2D bin H, _, _, _ = binned_statistic_2d(d, ar, None, statistic='count', bins=[bin_edges, area_bins]) results['area_dist2'] = H return results
[docs] def calculate_sample_area(bin_centers: np.ndarray, res: float, arm_distance: float, num_diodes: int, sa_method: int, probe_type: int, laser_wavelength: float = 680.0, DoFConstant: float | None = None) -> np.ndarray: """ Calculate image sample area assuming Heymsfield and Parish (1978). Parameters: ----------- bin_centers : array_like Mid-point of each bin in [millimeters]. res : float Photodiode resolution, bin width in [microns]. arm_distance : float Distance between the probe arms in [millimeters], defining the maximum depth of field (DOF) that can be considered. num_diodes : int Number of photodiodes (does not need to equal number of bins). sa_method : int Method to calculate the sample area (SA). Possible values: - 0: "center in" method where particles are counted if their center is within the area. - 1: "entire in" method where particles are counted only if entirely within the area. - 2: Method with correction to account for edge effects. probe_type : int Type of probe used, influencing the depth of field (DOF) calculation. laser_wavelength : float, optional Laser wavelength in nanometers [nm]. Defaults to 680.0 nm. DoFConstant : float, optional Coefficient c in DoF = 2c*r^2/lambda. When omitted, the probe-specific default is selected by ``resolve_dof_constant``. Returns: -------- sa : np.ndarray Sample area in mm^2 for each bin, calculated based on the provided method and probe type. Reference: ---------- Heymsfield, A. J., and J. L. Parrish, 1978: A Computational Technique for Increasing the Effective Sampling Volume of the PMS Two-Dimensional Particle Size Spectrometer. J. Appl. Meteor. Climatol., 17, 1566-1572, https://doi.org/10.1175/1520-0450(1978)017%3C1566:ACTFIT%3E2.0.CO;2 History: -------- - 2024-03-13: Yongjie Huang, Converted from UIOOPS MatLab code """ # Convert resolution from microns to millimeters for further calculations res_mm = res * 1e-3 # Calculate diameter and radius of particles based on bin mid-points diameter = bin_centers radius = diameter / 2.0 # Determine the Effective Array Width (EAW) based on the specified sample area calculation method if sa_method == 0: # "center in" method: Sizes most particles, but some particles are sized inaccurately. This is a frequently used method effective_width = num_diodes * res_mm elif sa_method == 1: # "entire in" or "All in" method: Most accurate sizing method for sized particles, but many particles are rejected effective_width = (num_diodes - 1) * res_mm - diameter effective_width[effective_width < 0] = 0 # Ensure EAW is non-negative elif sa_method == 2: # "reconstructed" particle method: Useful in water clouds, not useful in ice clouds. Good for lots of big spherical particles. effective_width = num_diodes * res_mm + 0.72 * diameter # Calculate the Depth of Field (DoF) based on probe type # DoF: The maximum full distance from the focal plane where a particle is considered "in focus" (shadow a photodiode by at least 50%). # DoF = ± c * (D/2)^2 / λ = 2c * r^2 / λ, where D is diameter, r is radius, λ is laser wavelength lambda_mm = laser_wavelength * 1e-6 # Laser wavelength in mm dof_constant = resolve_dof_constant(probe_type, DoFConstant) dof = 2 * dof_constant * radius ** 2 / lambda_mm # Limit DoF to the arm distance to avoid unrealistic values (DoF <= arm_distance) dof[dof > arm_distance] = arm_distance # Calculate the sample area by multiplying DoF by the effective array width sa = dof * effective_width return sa
[docs] def estimate_active_sample_time(InterArrivalTime: xr.DataArray, overload_flag: xr.DataArray | None, time_interval_sec: float, overload_dead_time: float | None = None) -> float: """ Estimate active sample time as the nominal interval minus overload dead time. A preallocated ``overload_dead_time`` takes precedence over particle-level calculation so dead-time intervals crossing Level-2 boundaries can be apportioned before grouped processing. Otherwise, positive inter-arrival times associated with active-high overload flags are summed locally. Parameters ---------- InterArrivalTime : xarray.DataArray Particle-aligned inter-arrival times in seconds. Used only when ``overload_dead_time`` is not supplied and ``overload_flag`` is present. overload_flag : xarray.DataArray or None Particle-aligned active-high overload status: ``1`` marks the preceding inter-arrival time as dead time and ``0`` marks normal sampling. Missing values or the fill value ``255`` produce a NaN result. When ``None``, the complete nominal interval is treated as active. time_interval_sec : float Finite, positive duration of the output sampling interval in seconds. overload_dead_time : float or None, optional Dead time already allocated to the output interval in seconds. A NaN value propagates to the result; otherwise the value must be finite and non-negative. Defaults to ``None``. Returns ------- float Active sample time in seconds, clipped to the inclusive range from zero to ``time_interval_sec``. Returns NaN when overload correction for the interval is explicitly invalid. Raises ------ ValueError If the nominal interval or supplied dead time is invalid, the particle arrays are not one-dimensional and aligned, or an overload flag is not ``0``, ``1``, or missing. Notes ----- The calculation is ``active_time = nominal_time - dead_time``. Dead time greater than the nominal interval emits a warning and yields zero active time. History ------- - 2026-07-24: Clarified preallocated boundary allocations and missing-status behavior. - 2026-07-19: Yongjie Huang, first implemented overload-adjusted active sample time. """ nominal_time = float(time_interval_sec) if not np.isfinite(nominal_time) or nominal_time <= 0: raise ValueError( f"time_interval_sec must be a finite positive number, got {time_interval_sec!r}" ) if overload_dead_time is not None: dead_time = float(overload_dead_time) if np.isnan(dead_time): return np.nan if not np.isfinite(dead_time) or dead_time < 0: raise ValueError( "overload_dead_time must be a finite non-negative number, " f"got {overload_dead_time!r}" ) else: if overload_flag is None: return nominal_time iat = np.asarray(InterArrivalTime.values, dtype=np.float64) flags = np.asarray(overload_flag.values, dtype=np.float64) if iat.ndim != 1 or flags.ndim != 1 or flags.size != iat.size: raise ValueError( "InterArrivalTime and overload_flag must be one-dimensional and particle-aligned: " f"got shapes {iat.shape} and {flags.shape}." ) missing = ~np.isfinite(flags) | (flags == 255) invalid = ~missing & ~np.isin(flags, (0, 1)) if np.any(invalid): raise ValueError( "overload_flag must contain active-high values 0 or 1, or be missing." ) if np.any(missing): return np.nan dead_time = float(np.sum(iat[(flags == 1) & np.isfinite(iat) & (iat > 0)])) if dead_time > nominal_time: logger.warning( "Estimated overload dead time %.6g s exceeds the %.6g s sample interval; " "clipping active sample time to zero.", dead_time, nominal_time, ) return float(np.clip(nominal_time - dead_time, 0.0, nominal_time))
def _allocate_overload_dead_time( ds_grouped, time_interval_sec: float, missing_overload_policy: str = 'warn_nominal', ) -> list[tuple]: """ Attach overload dead time and correction status to already-grouped data. Each overload IAT initially belongs to the group containing its ending particle. With consecutive, chronological IATs, only the first particle in a group can cross the group's left edge. That interval is split between the current group and the preceding existing group before workers are launched. Parameters ---------- ds_grouped : iterable of tuple Chronologically ordered ``(group_label, dataset)`` pairs, typically produced by grouping a Level-1 dataset by its Level-2 time interval. time_interval_sec : float Finite, positive duration of each Level-2 output interval in seconds. missing_overload_policy : {'warn_nominal', 'invalidate', 'error'}, optional Behavior when overload status is unavailable or incomplete. ``warn_nominal`` assumes zero dead time for the missing portion, ``invalidate`` assigns NaN dead time to affected output intervals, and ``error`` raises ``ValueError``. Defaults to ``warn_nominal``. Returns ------- list of tuple The grouped ``(group_label, dataset)`` pairs with scalar ``_overload_dead_time`` and ``_overload_correction_status`` variables attached to each dataset. History ------- - 2026-07-24: Refactored allocation around pre-grouped data and the first particle's left-edge crossing; added missing-status policies and output correction status. - 2026-07-19: Yongjie Huang, first implemented temporal-overlap allocation of overload dead time across Level-2 output intervals. """ nominal_time = float(time_interval_sec) if not np.isfinite(nominal_time) or nominal_time <= 0: raise ValueError( f"time_interval_sec must be a finite positive number, got {time_interval_sec!r}" ) policy = _validate_missing_overload_policy(missing_overload_policy) groups = list(ds_grouped) if not groups: return groups group_starts = np.asarray([float(group_name) for group_name, _ in groups]) if ( not np.all(np.isfinite(group_starts)) or np.any(np.diff(group_starts) <= 0) ): raise ValueError( "Grouped Level-2 interval labels must be finite and strictly increasing." ) group_dead_time = np.zeros(len(groups), dtype=np.float64) group_incomplete = np.zeros(len(groups), dtype=bool) group_sources: list[str] = [] prepared_groups: list[tuple] = [] tolerance = ( np.finfo(np.float64).eps * max(1.0, nominal_time, float(np.max(np.abs(group_starts)))) * 32 ) previous_last_particle_time: float | None = None for group_index, (group_name, original_group) in enumerate(groups): group_ds = original_group.copy(deep=False) prepared_groups.append((group_name, group_ds)) particle_count = group_ds.sizes.get('particle', 0) source = group_ds.attrs.get('overload_correction_source') if source is None and 'overload_flag' in group_ds: source = group_ds['overload_flag'].attrs.get( 'source', 'existing_level1_overload_flag' ) if source is None: source = 'unavailable' source = str(source) group_sources.append(source) if particle_count == 0 or 'overload_flag' not in group_ds: group_incomplete[group_index] = True continue if 'InterArrivalTime' not in group_ds: raise ValueError( "InterArrivalTime is required when overload_flag is available." ) iat = np.asarray( group_ds['InterArrivalTime'].values, dtype=np.float64 ) flags = np.asarray( group_ds['overload_flag'].values, dtype=np.float64 ) particle_time = _particle_relative_time_seconds(group_ds) expected_shape = (particle_count,) if any( values.shape != expected_shape for values in (iat, flags, particle_time) ): raise ValueError( "InterArrivalTime, overload_flag, and particle time must be " "one-dimensional and particle-aligned with shape " f"{expected_shape}." ) if not np.all(np.isfinite(particle_time)): raise ValueError( "Particle timestamps must be finite before Level-2 grouping." ) if np.any(np.diff(particle_time) < -tolerance): raise ValueError( "Particles within each Level-2 group must be chronological for " "first-particle overload boundary allocation." ) if ( previous_last_particle_time is not None and particle_time[0] < previous_last_particle_time - tolerance ): raise ValueError( "Level-2 groups must preserve chronological particle order for " "first-particle overload boundary allocation." ) invalid_flags = ( np.isfinite(flags) & ~np.isin(flags, (0, 1, 255)) ) if np.any(invalid_flags): raise ValueError( "overload_flag must contain active-high values 0 or 1, or be missing." ) valid_overload = ( (flags == 1) & np.isfinite(iat) & (iat > 0) ) group_dead_time[group_index] = float(np.sum(iat[valid_overload])) missing_flag = ~np.isfinite(flags) | (flags == 255) invalid_overload_iat = ( (flags == 1) & (~np.isfinite(iat) | (iat < 0)) ) if source == 'unavailable': group_incomplete[group_index] = True if np.any(invalid_overload_iat): group_incomplete[group_index] = True if group_index > 0 and invalid_overload_iat[0]: group_incomplete[group_index - 1] = True group_start = group_starts[group_index] interval_start = particle_time - iat boundary_relevant = valid_overload | missing_flag if ( previous_last_particle_time is not None and boundary_relevant[0] and np.isfinite(iat[0]) and iat[0] > 0 and not np.isclose( interval_start[0], previous_last_particle_time, rtol=0.0, atol=tolerance, ) ): raise ValueError( "The first particle InterArrivalTime must begin at the preceding " "particle timestamp. Rebuild Level-1 InterArrivalTime from " "chronological particle timestamps." ) nonfirst_crossing = ( boundary_relevant[1:] & np.isfinite(iat[1:]) & (iat[1:] > 0) & (interval_start[1:] < group_start - tolerance) ) if np.any(nonfirst_crossing): raise ValueError( "Only the first particle in a Level-2 group may have an " "InterArrivalTime crossing the group boundary. Rebuild Level-1 " "InterArrivalTime from chronological particle timestamps." ) first_iat = iat[0] first_stop = particle_time[0] first_start = interval_start[0] first_crosses = ( np.isfinite(first_iat) and first_iat > 0 and first_start < group_start - tolerance ) current_overlap = 0.0 previous_overlap = 0.0 if first_crosses: current_overlap = max( 0.0, min(first_stop, group_start + nominal_time) - max(first_start, group_start), ) if group_index > 0: previous_start = group_starts[group_index - 1] previous_overlap = max( 0.0, min(first_stop, previous_start + nominal_time) - max(first_start, previous_start), ) if flags[0] == 1: group_dead_time[group_index] -= first_iat group_dead_time[group_index] += current_overlap if group_index > 0: group_dead_time[group_index - 1] += previous_overlap missing_indices = np.flatnonzero(missing_flag) for particle_index in missing_indices: if ( particle_index == 0 and first_crosses ): if current_overlap > tolerance: group_incomplete[group_index] = True if group_index > 0 and previous_overlap > tolerance: group_incomplete[group_index - 1] = True else: group_incomplete[group_index] = True if ( particle_index == 0 and group_index > 0 and (not np.isfinite(first_iat) or first_iat < 0) ): group_incomplete[group_index - 1] = True previous_last_particle_time = float(particle_time[-1]) if np.any(group_dead_time > nominal_time): logger.warning( "Estimated overload dead time exceeds the sample interval for %d " "output bin(s); clipping those bins to zero active time.", int(np.count_nonzero(group_dead_time > nominal_time)), ) group_dead_time = np.clip(group_dead_time, 0.0, nominal_time) incomplete_count = int(np.count_nonzero(group_incomplete)) if incomplete_count: if policy == 'error': raise ValueError( "Overload status is unavailable or incomplete for " f"{incomplete_count} Level-2 output bin(s) and " "missing_overload_policy='error'." ) if policy == 'invalidate': group_dead_time[group_incomplete] = np.nan logger.warning( "Overload status is unavailable or incomplete for %d Level-2 " "output bin(s); active sample time and sample volume will be invalid.", incomplete_count, ) else: logger.warning( "Overload status is unavailable or incomplete for %d Level-2 " "output bin(s); nominal sample time is assumed for missing portions.", incomplete_count, ) for group_index, (_, group_ds) in enumerate(prepared_groups): if group_incomplete[group_index]: status = ( _OVERLOAD_STATUS_INVALID if policy == 'invalidate' else _OVERLOAD_STATUS_NOMINAL_ASSUMED ) else: status = _complete_overload_status(group_sources[group_index]) group_ds['_overload_dead_time'] = xr.DataArray( np.float64(group_dead_time[group_index]), attrs={ 'units': 's', 'long_name': 'overload dead time allocated to output interval', }, ) group_ds['_overload_correction_status'] = xr.DataArray( np.uint8(status) ) group_ds.attrs['overload_correction_source'] = group_sources[group_index] group_ds.attrs['missing_overload_policy'] = policy return prepared_groups
[docs] def calculate_sample_volume(bin_edges: np.ndarray, InterArrivalTime: xr.DataArray, tas: xr.DataArray, tasMax: float, res: float, arm_distance: float, num_diodes: int, sa_method: int, probe_type: int, laser_wavelength: float = 680.0, DoFConstant: float | None = None, overload_flag: xr.DataArray | None = None, time_interval_sec: float = 1.0, overload_dead_time: float | None = None) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, float]: """ Calculate sample volume for each size bin. Parameters: ----------- bin_edges : array-like Bin edges [mm] InterArrivalTime : array-like Inter-arrival times [s] tas : array-like True airspeed [m/s] tasMax : float Maximum true airspeed [m/s] res : float Diode resolution [um] arm_distance : float Arm distance [mm] num_diodes : int Number of active diodes sa_method : int Sample area method probe_type : int Probe type laser_wavelength : float, optional Laser wavelength in nanometers [nm]. Defaults to 680.0 nm. DoFConstant : float, optional Coefficient used in the depth-of-field calculation. When omitted, the probe-specific default is selected by ``calculate_sample_area``. overload_flag : array-like, optional Active-high particle overload flag. The preceding inter-arrival time is treated as instrument dead time when the flag equals 1. time_interval_sec : float, optional Nominal duration of the output interval [s]. Defaults to 1 s. overload_dead_time : float, optional Dead time already allocated to this output interval [s]. When supplied, it takes precedence over summing particle overload inter-arrival times. Returns: -------- tuple : (bin_center, sa2, svol2, vol_scale_factor, active_sample_time) - bin_center: Bin centers [mm] - sa2: Sample area [mm²] - svol2: Sample volume [cm³] - vol_scale_factor: Clocking correction factor (unused) - active_sample_time: Nominal interval minus overload dead time [s] History: -------- - 2026-07-18: Yongjie Huang, calculated active sample time as the nominal interval minus overload dead time. - 2025-12-30: Yongjie Huang, first created. """ bin_center = (bin_edges[:-1] + bin_edges[1:]) * 0.5 # [mm] # sample area in each bin sa2 = calculate_sample_area( bin_center, res, arm_distance, num_diodes, sa_method, probe_type, laser_wavelength=laser_wavelength, DoFConstant=DoFConstant ) # [mm^2], shape (num_bins,) # Clocking problem correction # vol_scale_factor = np.maximum(tas.mean() / tasMax, 1) # shape (time, ) # Note: When tas > tasMax, probe electronics cannot clock fast enough, compressing recorded particle images # (which is corrected by stretching ParticleArea). However, the physical volume of air passing through the # probe arms depends strictly on the actual true airspeed, regardless of electronic clocking limits. # Therefore, no vol_scale_factor is applied to sample volume. vol_scale_factor = 1.0 # Maintained for return tuple compatibility # Active time is the nominal output interval minus the inter-arrival times # associated with instrument overload records (overload dead time). active_sample_time = estimate_active_sample_time( InterArrivalTime, overload_flag, time_interval_sec, overload_dead_time=overload_dead_time, ) mean_tas = tas.mean().values if np.isnan(mean_tas): logger.warning( "All TAS values are missing for this segment; sample volume and Level-2 TAS will be invalid." ) svol2 = sa2 * (1e-3) ** 2 * active_sample_time * mean_tas # * vol_scale_factor # [m^3], shape (num_bins,) svol2 = svol2 * 1e6 # Convert [m^3] to [cm^3] return bin_center, sa2, svol2, vol_scale_factor, active_sample_time
[docs] def normalize_and_calculate_concentrations(dist: dict, svol2: np.ndarray, binwidth_cm: np.ndarray, iCreateAspectRatio: int, density: float = 0.91, shape_factor: float = np.sqrt(3)/3.0) -> dict: """ Normalize distributions and calculate concentrations. Parameters: ----------- dist : dict Dictionary of un-normalized distributions (from compute_distributions) svol2 : array-like Sample volume [cm^3] binwidth_cm : float Bin width [cm] iCreateAspectRatio : int Flag to creating aspect ratio variables density : float, optional Density of the particle phase (e.g. 0.91 for ice, 1.0 for liquid water) in [g/cm^3]. Defaults to 0.91. shape_factor : float, optional Geometric shape factor of the particle phase used for effective radius calculations. Defaults to np.sqrt(3)/3.0. Returns: -------- dict : Dictionary containing finalized Concentration and normalized variables History: -------- - 2026-07-20: Preserve invalid sample-volume bins as NaN instead of reporting zero-valued science products. - 2026-07-06: Yongjie Huang, parameterized density and shape factor for phase-separated effective radius calculations, and coerced inputs to NumPy arrays to bypass recursion warnings. - 2025-12-30: Yongjie Huang, first created. """ # Ensure svol2 and binwidth_cm are numpy arrays svol2 = np.asarray(svol2, dtype=float) binwidth_cm = np.asarray(binwidth_cm, dtype=float) # Extract results as numpy arrays # Make a copy for raw counts particle_count = np.asarray(dist['count'], dtype=float).copy() particle_SizeDist = np.asarray(dist['count'], dtype=float) # Will be normalized in-place particle_SizeDist_AreaR = np.asarray(dist['count_AreaR'], dtype=float) HabitSD = np.asarray(dist['HabitSD'], dtype=float) HabitMSD = np.asarray(dist['HabitMSD'], dtype=float) particle_area = np.asarray(dist['area'], dtype=float) partarea = np.asarray(dist['partarea'], dtype=float) iwc = np.asarray(dist['iwc'], dtype=float) iwcbl = np.asarray(dist['iwcbl'], dtype=float) vt = np.asarray(dist['vt'], dtype=float) pr = np.asarray(dist['pr'], dtype=float) area_dist2 = np.asarray(dist['area_dist2'], dtype=float) particle_areaRatio1 = np.asarray(dist['mean_ar1'], dtype=float) if iCreateAspectRatio == 1: particle_AspectRatioRect = np.asarray(dist['mean_aspect_rect'], dtype=float) particle_AspectRatioElli = np.asarray(dist['mean_aspect_elli'], dtype=float) else: particle_AspectRatioRect = None particle_AspectRatioElli = None # A non-finite or non-positive sample volume means the concentration is not # measurable in that bin. Preserve that distinction as NaN rather than # turning an invalid measurement into a physically meaningful zero. valid_sample_volume = np.isfinite(svol2) & (svol2 > 0) inv_svol2 = np.full_like(svol2, np.nan, dtype=float) np.divide(1.0, svol2, out=inv_svol2, where=valid_sample_volume) # Calculate mass-weighted terminal velocity [m/s] before normalization vt_mass_weighted = np.divide(pr, iwc, out=np.zeros_like(pr, dtype=float), where=(iwc > 0)) # Calculate precipitation rate [mm/hr] before normalization # pr is sum(m * vt) in [g * m / s]. Convert to volume flux [cm/s] by multiplying by 100 [cm/m] / svol2 [cm^3], then multiply by 36000 [mm/hr per cm/s] prec_rate_mm_hr = pr * inv_svol2 * 3.6e6 # Normalization by binwidth # Note: These operations modify the arrays in-place if they are mutable # Since dist contains arrays created in compute_distributions, this is generally fine # but we extracted particle_count as a copy first to preserve raw counts. particle_SizeDist /= binwidth_cm particle_SizeDist_AreaR /= binwidth_cm iwc /= binwidth_cm # g/cm iwcbl /= binwidth_cm partarea /= binwidth_cm particle_area /= binwidth_cm HabitSD /= binwidth_cm[:, np.newaxis] HabitMSD /= binwidth_cm[:, np.newaxis] area_dist2 /= binwidth_cm[:, np.newaxis] # Effective radius calculation using sample-volume weighted concentrations # re = 3^0.5 / (3 * rhoi) * IWC / Ac * 1000 if np.any(valid_sample_volume): weighted_area_sum = np.sum( particle_area[valid_sample_volume] * inv_svol2[valid_sample_volume] * binwidth_cm[valid_sample_volume] ) weighted_mass_sum = np.sum( iwc[valid_sample_volume] * inv_svol2[valid_sample_volume] * binwidth_cm[valid_sample_volume] ) else: weighted_area_sum = np.nan weighted_mass_sum = np.nan if weighted_area_sum > 0: re = (shape_factor / density) * 1000 * (weighted_mass_sum / weighted_area_sum) * 1000 # [um] elif np.any(valid_sample_volume): re = 0. else: re = np.nan # Concentrations # n_D = N(D) [#/cm^4] n_D = particle_SizeDist * inv_svol2 n_Deq = particle_SizeDist_AreaR * inv_svol2 # Total number concentration [#/cm^3] if np.any(valid_sample_volume): conc = np.sum( n_D[valid_sample_volume] * binwidth_cm[valid_sample_volume], axis=0, ) else: conc = np.nan # Area distribution concentration conc_areaDist = area_dist2 * inv_svol2[:, np.newaxis] # Pack result dictionary result = { 'n_D': n_D, 'n_Deq': n_Deq, 'conc': conc, 'area': particle_area * inv_svol2, 'conc_areaDist': conc_areaDist, 'partarea': partarea * inv_svol2, 'iwc': iwc * inv_svol2, 'iwcbl': iwcbl * inv_svol2, 'vt': vt_mass_weighted, 'pr': prec_rate_mm_hr, 'HabitSD': HabitSD * inv_svol2[:, np.newaxis], 'HabitMSD': HabitMSD * inv_svol2[:, np.newaxis], 're': re, 'mean_area_ratio': particle_areaRatio1, 'particle_count': particle_count, # Raw counts } if iCreateAspectRatio == 1: result['mean_aspect_ratio_rectangle'] = particle_AspectRatioRect result['mean_aspect_ratio_ellipse'] = particle_AspectRatioElli return result
[docs] def create_bulk_output_dataset(results_good: dict, results_bad: dict | None, active_sample_time: float, svol2: np.ndarray, good_partpercent: float, bin_edges: np.ndarray, area_bins: np.ndarray, habits: list[str], iCreateAspectRatio: int, iCreateBad: int, results_liquid: dict | None = None, results_ice: dict | None = None, results_unknown: dict | None = None, LWC: float | np.ndarray = np.nan, IWC: float | np.ndarray = np.nan, UWC: float | np.ndarray = np.nan, TWC: float | np.ndarray = np.nan, phase_processing_status: str = "enabled") -> xr.Dataset: """ Constructs the final xarray Dataset for output using automated variable mapping. Parameters: ----------- results_good : dict Results dictionary for good particles results_bad : dict Results dictionary for bad particles (or None) active_sample_time : float Nominal output interval minus instrument overload dead time [s] svol2 : array-like Sample volume good_partpercent : float Percentage of good particles bin_edges : array-like Bin edges area_bins : array-like Area ratio bin edges habits : list List of habits iCreateAspectRatio : int Flag for aspect ratio iCreateBad : int Flag for bad particles results_liquid : dict, optional Results dictionary for liquid candidate particles. Defaults to None. results_ice : dict, optional Results dictionary for ice candidate particles. Defaults to None. results_unknown : dict, optional Results dictionary for unknown candidate particles. Defaults to None. LWC : float or np.ndarray, optional Liquid Water Content [g/m^3]. Defaults to np.nan. IWC : float or np.ndarray, optional Ice Water Content [g/m^3]. Defaults to np.nan. UWC : float or np.ndarray, optional Unknown Water Content [g/m^3]. Defaults to np.nan. TWC : float or np.ndarray, optional Total Water Content (LWC + IWC + UWC) [g/m^3]. Defaults to np.nan. phase_processing_status : str, optional Status of thermodynamic phase processing (e.g. "enabled", "disabled", "missing_input_skipping"). Defaults to "enabled". Returns: -------- xr.Dataset : Final output dataset History: -------- - 2026-07-06: Yongjie Huang, added phase-separated distributions, integrated water content scalars, and phase processing status metadata mapping. - 2025-12-30: Yongjie Huang, first created. """ # Prepare variables to output variables_dict = copy.deepcopy(LEVEL_2_VARIABLES) # Mapping from results keys to DATA keys # Key: target DATA key, Value: source results key var_mapping = { 'n_D': 'n_D', 'area': 'conc_areaDist', 'n_Deq': 'n_Deq', 'conc': 'conc', 'total_area': 'area', 'mass': 'iwc', 'habitsd': 'HabitSD', 're': 're', 'massBL': 'iwcbl', 'vt': 'vt', 'Prec_rate': 'pr', 'habitmsd': 'HabitMSD', 'Calcd_area': 'partarea', 'count': 'particle_count', 'mean_area_ratio': 'mean_area_ratio' } # Add aspect ratio variables if iCreateAspectRatio is 1 if iCreateAspectRatio == 1: var_mapping.update({ 'mean_aspect_ratio_rectangle': 'mean_aspect_ratio_rectangle', 'mean_aspect_ratio_ellipse': 'mean_aspect_ratio_ellipse' }) # Initialize DATA dictionary to store data for each variable DATA = {key: [] for key in variables_dict.keys()} # Helper to append data def append_data(target_dict, source_results): for target_key, source_key in var_mapping.items(): if target_key in target_dict and source_key in source_results: target_dict[target_key].append(source_results[source_key]) # Good particles append_data(DATA, results_good) DATA['Reject_ratio'].append(1 - good_partpercent) # Bad particles if iCreateBad == 1 and results_bad is not None: for target_key, source_key in var_mapping.items(): rej_target_key = 'REJ_' + target_key if rej_target_key in DATA and source_key in results_bad: DATA[rej_target_key].append(results_bad[source_key]) DATA['active_sample_time'].append(active_sample_time) DATA['sample_vol'].append(svol2) # Phase-separated size distributions and bulk scalar mapping if results_liquid is not None: DATA['n_D_liquid'].append(results_liquid['n_D']) DATA['conc_liquid'].append(results_liquid['conc']) DATA['total_area_liquid'].append(results_liquid['area']) DATA['mass_liquid'].append(results_liquid['iwc']) DATA['re_liquid'].append(results_liquid['re']) if results_ice is not None: DATA['n_D_ice'].append(results_ice['n_D']) DATA['conc_ice'].append(results_ice['conc']) DATA['total_area_ice'].append(results_ice['area']) DATA['mass_ice'].append(results_ice['iwc']) DATA['re_ice'].append(results_ice['re']) if results_unknown is not None: DATA['n_D_unknown'].append(results_unknown['n_D']) DATA['conc_unknown'].append(results_unknown['conc']) DATA['total_area_unknown'].append(results_unknown['area']) DATA['mass_unknown'].append(results_unknown['iwc']) if results_liquid is not None: DATA['LWC'].append(LWC) DATA['IWC'].append(IWC) DATA['UWC'].append(UWC) DATA['TWC'].append(TWC) #--- Create xarray Dataset for return ds_SD = xr.Dataset() ds_SD.attrs['phase_processing_status'] = phase_processing_status ds_SD = ds_SD.assign_coords(bin_center=('bins', (bin_edges[:-1]+bin_edges[1:])*0.5, dict(units='mm', long_name='bin center'))) ds_SD = ds_SD.assign_coords(bin_edges=('bin_edges', bin_edges, dict(units='mm', long_name='bin edges'))) ds_SD = ds_SD.assign_coords(ar_bin_center=('ar_bins', (area_bins[:-1]+area_bins[1:])*0.5, dict(units='-', long_name='area ratio bin center'))) ds_SD = ds_SD.assign_coords(ar_bin_edges=('ar_bin_edges', area_bins, dict(units='-', long_name='area ratio bin edges'))) ds_SD = ds_SD.assign_coords(habits=('habits', habits, dict(units='-', long_name='particle habits'))) #ds_SD['test'] = xr.DataArray(data=np.array([1]), attrs={'long_name':'test'}) #ds_SD['test'] = xr.DataArray(data=np.array(1), dims=(), attrs={'long_name':'test'}) # Convert DATA list to xarray Dataset for key, values in variables_dict.items(): # Check if dims is a single string or a list/tuple, and ensure it is a list dims = [values['dims']] if isinstance(values['dims'], str) else values['dims'] # Use a list comprehension to construct dim_tuple dim_tuple = tuple(ds_SD.sizes[dim] for dim in dims) # Create and assign the DataArray if len(DATA[key]) > 0: # print(f' Add "{key}", dimension: {dim_tuple}') ds_SD[key] = xr.DataArray(data=np.array(DATA[key] if len(DATA[key])>1 else DATA[key][0], dtype=values['dtype']), dims=dims, attrs=values['attrs'] ) # else: # ds_SD[key] = xr.DataArray(data=np.zeros(dim_tuple, dtype=values['dtype']), dims=dims, attrs=values['attrs']) return ds_SD
[docs] def size_distribution_segment(ds: xr.Dataset) -> xr.Dataset: """ Processes a segment of particle data from cloud probes, performs quality control, and computes various particle size distributions and related metrics. Parameters: ----------- - ds (xarray.Dataset): An Xarray Dataset containing particle data from cloud probes, including variables like tas (true airspeed), ParticleArea, ParticleHabit, ParticleAutoReject, and others relevant to the analysis. Returns: -------- - xarray.Dataset: A new Xarray Dataset containing the results of the analysis, including computed size distributions, habit number and mass size distributions, area distributions, and other derived metrics. The output Dataset includes variables such as bin centers, bin edges, habit types, concentration of particles in different size bins, and additional attributes providing context for each variable. The function performs several key steps: ---------------------------------------- 1. Parameter Extraction & Setup: Extracts particle and probe configuration variables, including true airspeed, inter-arrival times, and bounding box dimensions. 2. Bulk Properties & Quality Control: Checks if bulk properties (mass, area ratio, terminal velocity) and QC filtering were pre-calculated upstream during Level-1 processing. If present, it ingests them directly to avoid redundant computation; otherwise, it falls back to calculating bulk properties, stretching ParticleArea for airspeed exceeding tasMax, and applying inter-arrival time QC filters (overload, shattering rejection, and optional large particle re-acceptance). 3. Size Distribution Computation: Masks accepted (good) and rejected (bad) particles based on Sample Area method constraints (Center-in/Entire-in), calculates binned counts, habit distributions, and 2D area ratio distributions using modular helper functions. 4. Normalization & Concentration: Calculates binned sample volumes using the nominal interval minus instrument overload dead time, normalizes distributions by bin width, and computes integrated concentrations and effective radius. 5. Dataset Packaging: Automatically maps all computed metrics into a standardized Xarray Dataset, ensuring full dimensional alignment and rich metadata documentation. History: -------- - 2026-07-06: Yongjie Huang, implemented phase segmentation (liquid, ice, unknown), computed phase-separated distributions and integrated water contents (LWC, IWC, UWC, TWC), and copied global attributes from input ds. - 2026-06-27: Yongjie Huang, integrated Level-1 upstream QC/bulk properties and standardized sample volume parameter naming. - 2025-12-30: Yongjie Huang, extracted helper functions from size_distribution_segment. - 2024-03-23: Yongjie Huang, implemented based on MATLAB version and leveraged numpy and scipy packages """ #------------------------------------------------------ # Extract necessary variables #--- Extract particle variables tas = ds['tas'] ParticleArea = ds['ParticleArea'] # [mm^2] ParticleHabit = ds['HolroydHabit'] ParticleAutoReject = ds['ParticleAutoReject'] CenterIn = ds['center_in'] EntireIn = ds['all_in'] InterArrivalTime = ds['InterArrivalTime'].copy() # [s] #--- Extract probe parameters tasMax = ds.tasMax # [m/s] bin_edges = ds.bin_edges # [mm] binwidth = ds.bin_width # [mm] armdst = ds.armdst # [mm] diode_num = ds.diode_num diode_size = ds.diode_size # [mm] probe_type = ds.probe_type laser_wavelength = getattr(ds, 'laser_wavelength', getattr(ds, 'wavelength', 680.0)) DoFConstant = resolve_dof_constant(probe_type, getattr(ds, 'DoFConstant', None)) #--- Extract quality control parameters applyIntArrThresh = ds.applyIntArrThresh defaultIntArrThresh = ds.defaultIntArrThresh reaccptShatrs = ds.reaccptShatrs reaccptD = ds.reaccptD # min diameter size (50 um) to consider in reacceptance reaccptMaxIAT = ds.reaccptMaxIAT # max inter-arrival time to consider in reacceptance accepted_codes = getattr(ds, 'accepted_codes', ACCEPTED_CODES) #--- Extract other parameters diameter_choice = ds.diameter_choice SAmethod = ds.SAmethod iCreateAspectRatio = ds.iCreateAspectRatio iCreateBad = ds.iCreateBad if SAmethod == 2: warnings.warn( "SAmethod=2 (Heymsfield & Parrish 1978 reconstructed sample area) extends the " "effective array width by 0.72*D, but COPS does not reconstruct partially imaged " "edge particles and only counts center-in particles. Concentrations will be " "biased low by a factor of N*res / (N*res + 0.72*D), which grows with particle size.", stacklevel=2, ) if iCreateAspectRatio == 1: # Note on Aspect Ratio definitions: Unlike the bounding box slice/diode aspect ratio used in QC, # these aspect ratios represent the geometric minor-to-major (width/length) axis ratios of the # minimum enclosing rotated rectangle and minimum volume enclosing ellipse, respectively. AspectRatioRect = ds['ParticleRectangleWidth']/ds['ParticleRectangleLength'] AspectRatioElli = ds['ParticleEllipseWidth']/ds['ParticleEllipseLength'] # print('check:', tas, CenterIn, EntireIn, # tasMax, bin_edges, binwidth, armdst, diode_num, diode_size, probe_type, # diameter_choice, applyIntArrThresh, defaultIntArrThresh, reaccptShatrs, # reaccptD, reaccptMaxIAT, SAmethod, iCreateAspectRatio, iCreateBad) #------------------------------------------------------ # Quality control and setup #--- Select diameter based on diameter_choice (8-11: selected ML diameter; fallback # and support cutoff come from the [ml_sizing] attributes attached by the caller). # A persisted D_selected must have been made with this same selection. ml_fallback = read_ml_attribute(ds.attrs, 'ml_sizing_fallback', 'D_s') ml_min_n_s = float(read_ml_attribute(ds.attrs, 'ml_sizing_min_n_s', 0.0)) check_persisted_selected_diameter(ds, diameter_choice, ml_fallback, ml_min_n_s, where='size_distribution_segment') particle_diameter = resolve_particle_diameter_um( ds, diameter_choice, ml_fallback, ml_min_n_s) * 1e-3 # [um] -> [mm] habit_str = ParticleHabit.astype(str) # Convert habit codes to strings if they are not already #--- Check if bulk properties and QC were pre-calculated upstream in Level-1 processing has_phase = 'particle_phase' in ds.variables has_ar_filled = 'AreaRatioFilled' in ds.variables has_mass_liq = 'particle_mass_liquid' in ds.variables has_vt_liq = 'particle_vt_liquid' in ds.variables has_pr_liq = 'particle_pr_liquid' in ds.variables Pres = ds.get('Pres') if 'Pres' in ds.variables else None Temp = ds.get('Temp') if 'Temp' in ds.variables else None if 'particle_mass' in ds.variables and 'area_ratio' in ds.variables: # Cached arrays are valid only for the diameter selection they were computed with # (mass, area ratio, velocity, phase and QC all depend on it). check_cached_bulk(ds, diameter_choice, ml_fallback, ml_min_n_s, where='size_distribution_segment') # Cached QC codes are valid only for the QC settings they were computed with. # (Unrecorded settings of older Level-1 files warn once, in the Level-2 driver.) check_level2_qc_settings(ds.attrs, True, qc_settings_record(ds.attrs), where='size_distribution_segment', warn_unknown=False) # Simply read pre-calculated arrays from Level-1 dataset ParticleArea = ds['ParticleArea'] particle_mass = ds['particle_mass'] calcd_area = ds['calcd_area'] particle_massbl = ds['particle_massbl'] area_ratio = ds['area_ratio'] particle_vt = ds['particle_vt'] particle_pr = ds['particle_pr'] ParticleAutoReject = ds['ParticleAutoReject'] InterArrivalTime = ds['InterArrivalTime'] else: # Fallback for legacy Level-1 datasets or standalone tests #--- Correct particle areas for airspeeds exceeding tasMax # This operation will stretch the area of the particle for airspeeds exceeding tasMax. # It applies the stretching factor (tas_val / tasMax) only where tas > tasMax. # Otherwise, it keeps the original area. ParticleArea = ParticleArea.where(tas <= tasMax, ParticleArea * tas / tasMax) #--- Calculate all particle properties using helper function props = calculate_particle_bulk_properties( particle_diameter, ParticleArea, habit_str, Pres=Pres, Temp=Temp ) #-- Extract properties from returned dictionary particle_mass = props['particle_mass'] calcd_area = props['calcd_area'] particle_massbl = props['particle_massbl'] area_ratio = props['area_ratio'] particle_vt = props['particle_vt'] particle_pr = props['particle_pr'] #--- Apply all quality control filters using helper function ParticleAutoReject, InterArrivalTime = apply_quality_control_InterArrivalTime( ParticleAutoReject, InterArrivalTime, particle_diameter, area_ratio, ds, applyIntArrThresh, defaultIntArrThresh, reaccptShatrs, reaccptD, reaccptMaxIAT, probe_type, accepted_codes=accepted_codes, tas=tas, time_sec=ds.get('time_sec', None), diode_size=diode_size, size_config=ds, return_diagnostics=False ) #--- Now handle phase and liquid variables fallbacks skip_phase = False phase_processing_status = "enabled" # Get configuration attributes phase_method = getattr(ds, 'phase_method', ds.attrs.get('phase_method', 'soda2_roundness')) phase_roundness_mode = getattr(ds, 'phase_roundness_mode', ds.attrs.get('phase_roundness_mode', 'standard')) phase_area_ratio_floor = getattr(ds, 'phase_area_ratio_floor', ds.attrs.get('phase_area_ratio_floor', 0.40)) phase_max_liquid_diameter_mm = getattr(ds, 'phase_max_liquid_diameter_mm', ds.attrs.get('phase_max_liquid_diameter_mm', 6.0)) phase_size_rule_diodes = getattr(ds, 'phase_size_rule_diodes', ds.attrs.get('phase_size_rule_diodes', 10)) check_cached_phase(ds, where='size_distribution_segment') if phase_method == "none": skip_phase = True phase_processing_status = "disabled" elif phase_method not in ML_PHASE_METHODS and not has_phase and not has_ar_filled: # Case A: Legacy file missing both skip_phase = True phase_processing_status = "missing_input_skipping" else: if phase_method in ML_PHASE_METHODS: ml_phase = selected_ml_phase(ds, phase_method) if has_phase and not np.array_equal(ds['particle_phase'].values, ml_phase): raise StaleOutputError("stored particle_phase differs from selected ML phase") particle_phase = xr.DataArray(ml_phase, dims=particle_diameter.dims) # Case C: AreaRatioFilled present but phase flag is missing elif has_ar_filled and not has_phase: arearatio_filled = ds['AreaRatioFilled'].values d_clean = np.where(particle_diameter.values > 0, particle_diameter.values, 0.0) diode_size_mm = float(ds.attrs.get('diode_size', diode_size)) particle_phase_vals = classify_particle_phase( arearatio_filled=arearatio_filled, holroyd_habit=habit_str.values, diameter_mm=d_clean, diode_size_mm=diode_size_mm, Temp=Temp, phase_method=phase_method, phase_roundness_mode=phase_roundness_mode, phase_area_ratio_floor=phase_area_ratio_floor, phase_max_liquid_diameter_mm=phase_max_liquid_diameter_mm, phase_size_rule_diodes=phase_size_rule_diodes, ) particle_phase = xr.DataArray(particle_phase_vals, dims=particle_diameter.dims) else: particle_phase = ds['particle_phase'] # Case B: phase present but liquid bulk variables missing if not has_mass_liq or not has_vt_liq or not has_pr_liq: d_clean = np.where(particle_diameter.values > 0, particle_diameter.values, 0.0) phase_vals = particle_phase.values particle_mass_liquid_vals = np.where( phase_vals == 1, 1e-3 * (np.pi / 6.0) * d_clean**3, 0.0 ) particle_mass_liquid = xr.DataArray(particle_mass_liquid_vals, dims=particle_diameter.dims) ar_val = area_ratio.values if hasattr(area_ratio, 'values') else area_ratio area_ratio_capped = np.clip(ar_val, 0.0, 1.0) if Pres is None: pres_arr = np.full_like(d_clean, DEFAULT_PRESSURE, dtype=float) else: pres_arr = np.asarray(Pres.values if hasattr(Pres, 'values') else Pres, dtype=float) if Temp is None: temp_arr = np.full_like(d_clean, DEFAULT_TEMPERATURE, dtype=float) else: temp_arr = np.asarray(Temp.values if hasattr(Temp, 'values') else Temp, dtype=float) particle_vt_liquid_vals = vectorized_single_vt( d_clean * 1e-3, area_ratio_capped, particle_mass_liquid_vals * 1e-3, pres_arr, temp_arr ) particle_vt_liquid_vals = np.where(phase_vals == 1, particle_vt_liquid_vals, 0.0) particle_vt_liquid = xr.DataArray(particle_vt_liquid_vals, dims=particle_diameter.dims) particle_pr_liquid_vals = particle_mass_liquid_vals * particle_vt_liquid_vals particle_pr_liquid = xr.DataArray(particle_pr_liquid_vals, dims=particle_diameter.dims) else: particle_mass_liquid = ds['particle_mass_liquid'] particle_vt_liquid = ds['particle_vt_liquid'] particle_pr_liquid = ds['particle_pr_liquid'] if has_ml_classification_provenance(ds.attrs): ds.attrs.update(phase_attrs(phase_record_from_attrs(ds.attrs))) #------------------------------------------------------ # Compute size distributions, concentrations, and other metrics #--- Pre-define variables num_bins = len(bin_edges) - 1 habits = ['s', 'l', 'o', 't', 'h', 'i', 'g', 'd', 'a', 'I'] area_bins = np.arange(0, 1.01, 0.1) # area ratio bin edges [-] particle_diameter_AreaR = ds['D_eq'] * 1e-3 # [um] -> [mm] binwidth_cm = binwidth * 0.1 # [mm] -> [cm] #--- Mask good and bad particles to compute size distribution good_particles, bad_particles = get_particle_masks(ParticleAutoReject, SAmethod, CenterIn, EntireIn, accepted_codes=accepted_codes) # Note: good_particles has SAmethod center-in/entire-in constraint, while good_particles.size is all particles. # Therefore, Reject_ratio = 1 - good_partpercent counts out-of-DOF particles as "rejected". good_partpercent = good_particles.sum() / good_particles.size if good_particles.size > 0 else xr.DataArray(0.0) # print('ParticleAutoReject:', ParticleAutoReject.size, # 'good_particles.sum():', good_particles.sum().values, # 'good_particles.size:', good_particles.size) #--- Store reject percentages for each criterion in a dictionary # criteria = ['0', 'H', 'h', 'u', 'a', 't', 'p', 's', 'z', 'i', 'A', 'S', 'R'] # Add or remove criteria as necessary RejectPercentByCriterion = ParticleAutoReject.astype(str).to_pandas().value_counts(normalize=True).to_dict() # print('RejectPercentByCriterion:', RejectPercentByCriterion) #--- Store particle percentages for each habit in a dictionary ParticlePercentByHabit = habit_str.astype(str).to_pandas().value_counts(normalize=True).to_dict() # print('ParticlePercentByHabit:', ParticlePercentByHabit) #--- Compute distributions for GOOD particles good_dist = compute_distributions( good_particles, particle_diameter, particle_diameter_AreaR, bin_edges, area_bins, particle_mass, calcd_area, particle_massbl, particle_vt, particle_pr, ParticleArea, habit_str, habits, area_ratio, entirein_mask=(good_particles & (EntireIn==1)), AspectRatioRect=AspectRatioRect if iCreateAspectRatio==1 else None, AspectRatioElli=AspectRatioElli if iCreateAspectRatio==1 else None, iCreateAspectRatio=iCreateAspectRatio ) #--- Compute distributions for BAD particles (if any) if iCreateBad == 1: bad_dist = compute_distributions( bad_particles, particle_diameter, particle_diameter_AreaR, bin_edges, area_bins, particle_mass, calcd_area, particle_massbl, particle_vt, particle_pr, ParticleArea, habit_str, habits, area_ratio, entirein_mask=(bad_particles & (EntireIn==1)), AspectRatioRect=AspectRatioRect if iCreateAspectRatio==1 else None, AspectRatioElli=AspectRatioElli if iCreateAspectRatio==1 else None, iCreateAspectRatio=iCreateAspectRatio ) else: bad_dist = None #--- Particle concentrations and related calculations #-- Calculate sample volume (maps local armdst, diode_num, SAmethod to arm_distance, num_diodes, sa_method) res = diode_size * 1000. # [um] overload_dead_time = None if '_overload_dead_time' in ds: overload_dead_time_values = np.asarray( ds['_overload_dead_time'].values ) if overload_dead_time_values.size != 1: raise ValueError( "_overload_dead_time must be a scalar attached to each " "pre-grouped Level-2 dataset." ) overload_dead_time = float(overload_dead_time_values.item()) else: policy = _validate_missing_overload_policy( str(ds.attrs.get('missing_overload_policy', 'warn_nominal')) ) source = str(ds.attrs.get( 'overload_correction_source', ds['overload_flag'].attrs.get( 'source', 'existing_level1_overload_flag' ) if 'overload_flag' in ds else 'unavailable', )) if 'overload_flag' in ds: overload_flags = np.asarray( ds['overload_flag'].values, dtype=np.float64 ) incomplete_overload = bool(np.any( ~np.isfinite(overload_flags) | (overload_flags == 255) )) else: overload_flags = None incomplete_overload = True incomplete_overload = incomplete_overload or source == 'unavailable' if incomplete_overload: if policy == 'error': raise ValueError( "Overload status is unavailable or incomplete and " "missing_overload_policy='error'." ) if policy == 'invalidate': overload_dead_time = np.nan elif overload_flags is not None: iat_values = np.asarray( InterArrivalTime.values, dtype=np.float64 ) overload_dead_time = float(np.sum(iat_values[ (overload_flags == 1) & np.isfinite(iat_values) & (iat_values > 0) ])) bin_center, sa2, svol2, vol_scale_factor, active_sample_time = calculate_sample_volume( bin_edges, InterArrivalTime, tas, tasMax, res, armdst, diode_num, SAmethod, probe_type, laser_wavelength=laser_wavelength, DoFConstant=DoFConstant, overload_flag=ds.get('overload_flag'), time_interval_sec=getattr(ds, 'time_interval_sec', 1.0), overload_dead_time=overload_dead_time, ) #-- Process GOOD particles results_good = normalize_and_calculate_concentrations(good_dist, svol2, binwidth_cm, iCreateAspectRatio) #-- Process BAD particles (if any) results_bad = normalize_and_calculate_concentrations(bad_dist, svol2, binwidth_cm, iCreateAspectRatio) if iCreateBad == 1 else None #-- Process phase-separated paths if not skip_phase: liquid_mask = good_particles & (particle_phase == 1) ice_mask = good_particles & (particle_phase == 2) unknown_mask = good_particles & (particle_phase == 0) good_dist_liquid = compute_distributions( liquid_mask, particle_diameter, particle_diameter_AreaR, bin_edges, area_bins, particle_mass_liquid, calcd_area, particle_mass_liquid, particle_vt_liquid, particle_pr_liquid, ParticleArea, habit_str, habits, area_ratio, entirein_mask=(liquid_mask & (EntireIn==1)), AspectRatioRect=AspectRatioRect if iCreateAspectRatio==1 else None, AspectRatioElli=AspectRatioElli if iCreateAspectRatio==1 else None, iCreateAspectRatio=iCreateAspectRatio ) good_dist_ice = compute_distributions( ice_mask, particle_diameter, particle_diameter_AreaR, bin_edges, area_bins, particle_mass, calcd_area, particle_massbl, particle_vt, particle_pr, ParticleArea, habit_str, habits, area_ratio, entirein_mask=(ice_mask & (EntireIn==1)), AspectRatioRect=AspectRatioRect if iCreateAspectRatio==1 else None, AspectRatioElli=AspectRatioElli if iCreateAspectRatio==1 else None, iCreateAspectRatio=iCreateAspectRatio ) good_dist_unknown = compute_distributions( unknown_mask, particle_diameter, particle_diameter_AreaR, bin_edges, area_bins, particle_mass, calcd_area, particle_massbl, particle_vt, particle_pr, ParticleArea, habit_str, habits, area_ratio, entirein_mask=(unknown_mask & (EntireIn==1)), AspectRatioRect=AspectRatioRect if iCreateAspectRatio==1 else None, AspectRatioElli=AspectRatioElli if iCreateAspectRatio==1 else None, iCreateAspectRatio=iCreateAspectRatio ) results_liquid = normalize_and_calculate_concentrations( good_dist_liquid, svol2, binwidth_cm, iCreateAspectRatio, density=1.0, shape_factor=0.75 ) results_liquid['conc'] = results_liquid['conc'] * 1000.0 # [#/cm3] => [#/L] results_ice = normalize_and_calculate_concentrations( good_dist_ice, svol2, binwidth_cm, iCreateAspectRatio, density=0.91, shape_factor=np.sqrt(3)/3.0 ) results_ice['conc'] = results_ice['conc'] * 1000.0 # [#/cm3] => [#/L] results_unknown = normalize_and_calculate_concentrations( good_dist_unknown, svol2, binwidth_cm, iCreateAspectRatio, density=0.91, shape_factor=np.sqrt(3)/3.0 ) results_unknown['conc'] = results_unknown['conc'] * 1000.0 # [#/cm3] => [#/L] # Integrated bulk scalar water contents (g/m3). Bins with no valid # sample volume remain NaN in the spectra and are excluded from an # otherwise measurable integral. If no bin was sampled, the scalar is # invalid as well. valid_sample_volume = np.isfinite(svol2) & (svol2 > 0) if np.any(valid_sample_volume): LWC = float(np.sum( results_liquid['iwc'][valid_sample_volume] * binwidth_cm[valid_sample_volume] ) * 1e6) # [g/cm3] => [g/m3] IWC = float(np.sum( results_ice['iwc'][valid_sample_volume] * binwidth_cm[valid_sample_volume] ) * 1e6) # [g/cm3] => [g/m3] UWC = float(np.sum( results_unknown['iwc'][valid_sample_volume] * binwidth_cm[valid_sample_volume] ) * 1e6) # [g/cm3] => [g/m3] else: LWC = np.nan IWC = np.nan UWC = np.nan TWC = LWC + IWC + UWC else: results_liquid = None results_ice = None results_unknown = None LWC = np.nan IWC = np.nan UWC = np.nan TWC = np.nan #------------------------------------------------------ # Create Output Dataset ds_SD = create_bulk_output_dataset( results_good, results_bad, active_sample_time, svol2, good_partpercent, bin_edges, area_bins, habits, iCreateAspectRatio, iCreateBad, results_liquid=results_liquid, results_ice=results_ice, results_unknown=results_unknown, LWC=LWC, IWC=IWC, UWC=UWC, TWC=TWC, phase_processing_status=phase_processing_status ) overload_status_meta = LEVEL_2_VARIABLES['overload_correction_status'] if '_overload_correction_status' in ds: overload_status_values = np.asarray( ds['_overload_correction_status'].values ) if overload_status_values.size != 1: raise ValueError( "_overload_correction_status must be a scalar attached to each " "pre-grouped Level-2 dataset." ) overload_status = np.uint8(overload_status_values.item()) else: source = str(ds.attrs.get( 'overload_correction_source', ds['overload_flag'].attrs.get( 'source', 'existing_level1_overload_flag' ) if 'overload_flag' in ds else 'unavailable', )) if 'overload_flag' in ds: overload_flags = np.asarray( ds['overload_flag'].values, dtype=np.float64 ) incomplete = bool(np.any( ~np.isfinite(overload_flags) | (overload_flags == 255) )) else: incomplete = True incomplete = incomplete or source == 'unavailable' if incomplete: policy = _validate_missing_overload_policy( str(ds.attrs.get('missing_overload_policy', 'warn_nominal')) ) if policy == 'error': raise ValueError( "Overload status is unavailable or incomplete and " "missing_overload_policy='error'." ) overload_status = ( _OVERLOAD_STATUS_INVALID if policy == 'invalidate' else _OVERLOAD_STATUS_NOMINAL_ASSUMED ) else: overload_status = _complete_overload_status(source) ds_SD['overload_correction_status'] = xr.DataArray( data=np.asarray( overload_status, dtype=overload_status_meta['dtype'] ), dims=overload_status_meta['dims'], attrs=copy.deepcopy(overload_status_meta['attrs']), ) tas_meta = LEVEL_2_VARIABLES['tas'] mean_tas = tas.mean().values ds_SD['tas'] = xr.DataArray( data=np.asarray(mean_tas, dtype=tas_meta['dtype']), dims=tas_meta['dims'], attrs=tas_meta['attrs'], ) for key, val in canonical_ml_attributes(ds.attrs).items(): if key not in _TRANSIENT_LEVEL2_ATTRS and key not in ds_SD.attrs: ds_SD.attrs[key] = val # Record the resolved value actually used, including probe-specific fallbacks # for legacy inputs that did not already carry a DoFConstant attribute. ds_SD.attrs['DoFConstant'] = DoFConstant return ds_SD
[docs] def size_distribution_process_group(group: tuple) -> tuple: """ Processes a single group of data in the context of either a multiprocessing or multithreading environment. Identifies the current execution context (process or thread) and logs the worker's identity along with the group being processed. Then, it processes the data group using the `size_distribution_segment` function. Parameters: ----------- group : tuple A tuple where the first element is the name or identifier of the group, and the second element is the dataset (or data subset) associated with this group. Returns: -------- tuple A tuple where the first element is the processed dataset (or data subset) returned by the `size_distribution_segment` function, and the second element is the name or identifier of the group. History: -------- - 2024-03-20: Created by Yongjie Huang (huangynj@gmail.com) """ # Determine the current execution context (process or thread) and assign an appropriate identifier if isinstance(threading.current_thread(), threading._MainThread): # In a process (likely via ProcessPoolExecutor), use the process ID worker_id = f"PID {os.getpid()}" else: # In a thread (likely via ThreadPoolExecutor), use the thread's name worker_id = threading.current_thread().name logger.debug( "%s - Worker %s processing group %s", datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f'), worker_id, group[0], ) # Unpack the group tuple into its name/identifier and the dataset group_name, group_ds = group processed_group_ds = size_distribution_segment(group_ds) return processed_group_ds, group_name
[docs] def parallel_processing_DatasetGroupBy(ds_grouped, num_workers: int = 8, parallel_method: str = 'concurrent_futures') -> list: """ Processes groups in a Dataset using various parallel processing methods. This function supports multiple parallel processing libraries, allowing the user to choose the one that best fits their needs. It maps a given processing function over groups in an xarray Dataset groupby object and collects the results. The function is designed to work with different parallel processing libraries. Parameters ---------- ds_grouped : GroupBy object The grouped xarray Dataset to be processed in parallel. This object is typically obtained by calling `.groupby()` on an xarray Dataset. num_workers : int, optional The number of worker processes or threads to use for parallel processing. The default is 8. This parameter is applicable to methods that support parallel execution, such as 'concurrent_futures', 'loky', 'pathos', 'dask', and 'ray'. parallel_method : str, optional The parallel processing method to use. The default is 'concurrent_futures'. Supported methods include: - 'concurrent_futures': Uses the concurrent.futures.ProcessPoolExecutor. - 'loky': Uses the loky.get_reusable_executor. - 'p_tqdm': Combines pathos and tqdm for parallel processing with progress bars. - 'pathos': Uses the pathos.multiprocessing.ProcessingPool. - 'dask': Utilizes dask.distributed.Client for distributed task execution. - 'ray': Employs Ray for distributed applications. If None or an unsupported value is provided, the function will print a warning and proceed with serial processing. Returns ------- list A list of processed datasets, one for each group in the input ds_grouped object. Notes ----- The 'p_tqdm' and 'pathos' methods are particularly useful for progress tracking and when dealing with functions that require serialization of more complex objects, respectively. The choice of parallel processing method may significantly impact performance and resource utilization, depending on the nature of the processing function and the dataset size. History ------- - 2026-07-03: Updated by Yongjie Huang to add try/finally cleanup blocks. - 2024-03-24: Yongjie Huang, first created. """ futures = [] if parallel_method == 'concurrent_futures': from concurrent.futures import ProcessPoolExecutor # Note: The Global Interpreter Lock (GIL) in CPython limits the # ThreadPoolExecutor parallel processing in CPU-bound tasks. # Use ProcessPoolExecutor for parallel processing. # with ThreadPoolExecutor(max_workers=num_workers) as executor: with process_pool_logging() as logging_context: logger.info( "Processing Level-2 groups with %d worker process(es)", num_workers, ) with ProcessPoolExecutor( max_workers=num_workers, mp_context=logging_context.mp_context, initializer=configure_worker_logging, initargs=(logging_context.queue, logging_context.level), ) as executor: for ds_group in ds_grouped: futures.append(executor.submit(size_distribution_process_group, ds_group)) # Collect processed results while the queue listener remains active. processed_datasets = [future.result() for future in futures] elif parallel_method == 'loky': # pip install loky from loky import get_reusable_executor with get_reusable_executor(max_workers=num_workers) as executor: futures = [executor.submit(size_distribution_process_group, ds_group) for ds_group in ds_grouped] # Collect processed results processed_datasets = [future.result() for future in futures] elif parallel_method == 'p_tqdm': # same as pathos but have a progress bar (aka Pathos + tqdm) # pip install p_tqdm from p_tqdm import p_map # Execute the function in parallel and collect processed results processed_datasets = p_map(size_distribution_process_group, ds_grouped, num_cpus=num_workers) elif parallel_method == 'pathos': # pip install pathos from pathos.multiprocessing import ProcessingPool as Pool # Initialize the pool with the desired number of workers pool = Pool(num_workers) try: # Map function over the dataset groups processed_datasets = pool.map(size_distribution_process_group, ds_grouped) finally: pool.close() pool.join() pool.clear() elif parallel_method == 'dask': # pip install dask distributed from dask.distributed import Client # Initialize the Dask Client client = Client(n_workers=num_workers, threads_per_worker=1) try: # Use Dask Distributed to submit tasks for parallel processing futures = [client.submit(size_distribution_process_group, ds_group) for ds_group in ds_grouped] # Collect processed results processed_datasets = client.gather(futures) finally: # Shutdown client client.close() elif parallel_method == 'ray': # pip install ray import ray # Wrap the processing function for Ray's remote execution @ray.remote def size_distribution_process_group_wrap(group): return size_distribution_process_group(group) # Initialize Ray ray_initialized_by_cops = False if not ray.is_initialized(): ray.init(num_cpus=num_workers) ray_initialized_by_cops = True try: for ds_group in ds_grouped: # Submit the task to Ray futures.append(size_distribution_process_group_wrap.remote(ds_group)) # Wait for all tasks to complete and retrieve the results processed_datasets = ray.get(futures) finally: # Shutdown Ray if ray_initialized_by_cops: ray.shutdown() elif parallel_method == 'serial': processed_datasets = [size_distribution_process_group(ds_group) for ds_group in ds_grouped] else: logger.warning( "Parallel method %r is not implemented; processing serially", parallel_method, ) processed_datasets = [size_distribution_process_group(ds_group) for ds_group in ds_grouped] return processed_datasets
[docs] def process_spif_level1_append_level2_data(input_spif_path: str, output_spif_path: str | None = None, num_workers: int | None = None, parallel_method: str | None = None, allow_missing_config: bool = False, config_path: str | None = None, allow_cwd_fallback: bool = False) -> None: """ Processes SPIF (Single Particle Image Format) level-1 particle image data and appends computed level-2 data (particle size distributions, mass distributions, and bulk properties) to a specified or default output NetCDF file. This function reads Level-1 SPIF data, calculates higher-level variables (Level-2) including size distributions, applies configured shattering corrections, binning methods, and computes additional particle metrics based on provided configurations. Computed Level-2 data is then appended to the existing NetCDF file structure under the appropriate group hierarchy. Parameters: ----------- input_spif_path : str Path to the input SPIF (Single Particle Image Format) NetCDF file containing level-1 data. output_spif_path : str, optional Path to the output NetCDF file where processed level-2 data will be appended. If not provided, level-2 data is appended directly into the input file. num_workers : int, optional Number of parallel worker processes to use for data processing. If None (default), all available CPU cores are utilized. parallel_method : str, optional Parallel processing method to use ('concurrent_futures', etc.). Defaults to 'concurrent_futures' if not specified. allow_missing_config : bool, optional If True, the system will allow proceeding with default fallback parameters when the external `.ini` configuration file is missing instead of raising a FileNotFoundError. Defaults to False. config_path : str, optional Path to a specific configuration file. If provided, the configuration is loaded directly from this file. Defaults to None. allow_cwd_fallback : bool, optional If True, allows falling back to loading the configuration file from the current working directory if it is not found adjacent to the SPIF file. Defaults to False. Returns: -------- None Notes: ------ - Requires a corresponding '.ini' configuration file (`{project}.{probe_name}.ini`) containing parameters for particle size distribution calculations, shattering correction, particle diameter definitions, and binning strategies. - Level-2 processing includes applying inter-arrival time thresholding and shattering particle reacceptance algorithms if configured. History: -------- - 2026-07-24: Yongjie Huang, allocated overload dead time and correction status across grouped Level-2 intervals before parallel worker dispatch. - 2026-07-06: Yongjie Huang, updated to copy configuration and provenance attributes from Level-1 to Level-2 NetCDF output. - 2026-07-03: Yongjie Huang, updated to expose config_path and allow_cwd_fallback. - 2026-06-27: Yongjie Huang, refactored to use ProbeProcessingConfig dataclass models. - 2025-03-14: Yongjie Huang (huangynj@gmail.com), replaced parameter settings with an external configuration '.ini' file. - 2024-03-24: Yongjie Huang (huangynj@gmail.com), improved parallel processing handling to avoid serialization errors and segmentation faults on some platforms. - 2024-03-21: Yongjie Huang (huangynj@gmail.com), first created. """ # Open the NetCDF file to get all groups containing specified subgroups ('core', 'level-1', 'level-2') with Dataset(input_spif_path, 'r') as nc: groups_core = return_groups_with_specified_subgroup(nc, 'core') groups_lvl1 = return_groups_with_specified_subgroup(nc, 'level-1') groups_lvl2 = return_groups_with_specified_subgroup(nc, 'level-2') # Check if there is any 'core' or 'level-1' group in the file if len(groups_core) == 0: logger.warning("No core data available to process") return if len(groups_lvl1) == 0: logger.warning("No Level-1 data available to process") return # Optional ML sizing/classification: refuse an invalid bundle/mode/routing or # incompatible Level-1 ML or phase provenance before an output file is created (groups with Level-2 are guarded below). done = set(groups_lvl2) if output_spif_path is not None and os.path.exists(output_spif_path): with Dataset(output_spif_path, 'r') as nc: done |= set(return_groups_with_specified_subgroup(nc, 'level-2')) _preflight_ml_groups(input_spif_path, [g for g in groups_core if g in groups_lvl1 and g not in done], 'level-2', allow_missing_config, config_path, allow_cwd_fallback) # Determine the output SPIF path, create parent directory if it doesn't exist, and copy file if necessary if output_spif_path is None: output_spif_path = input_spif_path else: if not os.path.exists(output_spif_path): # Ensure the output file's parent directory exists parent_dir = os.path.dirname(output_spif_path) if parent_dir and not os.path.exists(parent_dir): os.makedirs(parent_dir) # Copy the input file to the output path if they are not the same shutil.copy2(input_spif_path, output_spif_path) else: # Re-check 'level-2' groups in the existing output file with Dataset(output_spif_path, 'r') as nc: groups_lvl2 = return_groups_with_specified_subgroup(nc, 'level-2') # Process image data for each 'core' group for group in groups_core: logger.info("Processing data in %r", group) # Check if the group already contains level-1 data if group not in groups_lvl1: logger.warning("%r does not have Level-1 data; skipping", group) logger.warning("Process image data in %r to create Level-1 data first", group) continue # Check if the group already contains level-2 data if group in groups_lvl2: _guard_existing_group(input_spif_path, output_spif_path, group, 'level-2', allow_missing_config, config_path, allow_cwd_fallback) logger.warning("%r already has Level-2 data; skipping", group) continue # Read SPIF headers and images for the current processing group spif_attr = ds_header = ds_core = ds_lvl1 = None try: spif_attr = io.read_spif_header(input_spif_path).load() ds_header = io.read_spif_header(input_spif_path, group=group).load() ds_core = io.read_spif_group(input_spif_path, group=f'{group}/core').load() ds_lvl1 = io.read_spif_group(input_spif_path, group=f'{group}/level-1').load() # Check if there are particles to process particle_num = ds_lvl1.sizes['particle'] if particle_num == 0: logger.warning("No particle data to process") continue # Load probe-specific configuration parameters from external .ini file project_name = spif_attr.project probe_name = resolve_probe_config_name( ds_header.instrument_name, ds_header.resolution.values ) loaded_config = load_probe_config(input_spif_path, project_name, probe_name, allow_missing=allow_missing_config, config_path=config_path, allow_cwd_fallback=allow_cwd_fallback) image_config = loaded_config.image size_config = loaded_config.size # Level-2 reuses Level-1 bulk/QC fields and, for diameter_choice 8-11, stored # ML predictions: both must match this request's diameter selection. diameter_selection, _, _ = requested_ml_sizing_records( loaded_config, InstrumentIdentity.from_header(ds_header, group), 'level-2') l1_has_bulk = 'particle_mass' in ds_lvl1.variables and 'area_ratio' in ds_lvl1.variables check_level2_inputs(ds_lvl1.attrs, l1_has_bulk, diameter_selection, where=f"{input_spif_path}:{group}") # Reused Level-1 QC codes must match the requested QC settings. check_level2_qc_settings(ds_lvl1.attrs, l1_has_bulk, qc_settings_record(size_config), where=f"{input_spif_path}:{group}") class_outputs, phase_selection = requested_ml_classification_records( loaded_config, InstrumentIdentity.from_header(ds_header, group), 'level-2') check_ml_classification_level2_inputs(ds_lvl1.attrs, any(v in ds_lvl1 for v in ( 'particle_phase', 'particle_mass_liquid', 'particle_vt_liquid', 'particle_pr_liquid')), class_outputs, phase_selection, f"{input_spif_path}:{group}") # Support existing Level-1 groups that predate overload propagation # by resolving the dead-time flag from the original core data. ds_lvl1 = _propagate_overload_flag( ds_lvl1, ds_core, size_config.probe_type, size_config.missing_overload_policy, ) # Append other necessary variables if 'tas' in ds_core.variables: ds_lvl1['tas'] = ds_core['tas'].rename({'Images': 'particle'}) elif 'tas' not in ds_lvl1.variables: raise ValueError( "Neither the core nor Level-1 dataset contains 'tas'. Re-run Level-1 " "processing with tas=<m s-1>." ) # Extract probe configuration details from header diode_num = ds_header.pixels.values diode_size = float(ds_header.resolution.values) * 1e-3 # [mm] armdst = ds_header.arm_separation.values # [mm] bin_edges = size_config.resolve_bin_edges(diode_size) ds_lvl1.attrs = canonical_ml_attributes(ds_lvl1.attrs) ds_lvl1.attrs.update(size_config.attrs_for_dataset()) ds_lvl1.attrs.update(image_config.attrs_for_dataset()) ds_lvl1.attrs.update(loaded_config.ml.attrs_for_dataset()) ds_lvl1.attrs.update(loaded_config.classification.attrs_for_dataset()) # These arrays are transient inputs to size_distribution_segment. # They are serialized only as Level-2 variables, not global attributes. ds_lvl1.attrs['bin_edges'] = bin_edges ds_lvl1.attrs['bin_width'] = np.diff(bin_edges) ds_lvl1.attrs['diode_size'] = diode_size ds_lvl1.attrs['armdst'] = armdst ds_lvl1.attrs['diode_num'] = diode_num ds_lvl1.attrs['Institution'] = spif_attr.institution ds_lvl1.attrs['Project'] = spif_attr.project ds_lvl1.attrs['Probe_Type'] = ds_header.instrument_name # Capture 'time_sec' attributes time_sec_attrs = ds_lvl1.time_sec.attrs.copy() # ds_lvl1.load() # Note: If don't load the dataset, on some platforms (no errors on Mac OS), # # it will cause serialization issue or 'Segmentation fault (core dumped)' issue with 'ds_lvl1.close()' # # when using ProcessPoolExecutor. # # Yongjie Huang, 2024-03-24. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # NOTE: Instead of lazily loading ds_lvl1 and calling .load() later, now call .load() immediately # upon reading the dataset at the start of the try block # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # Deep copy to memory-resident dataset to completely detach from open file ds_work = ds_lvl1.copy(deep=True) finally: for ds in (spif_attr, ds_header, ds_core, ds_lvl1): if ds is not None: ds.close() #--- Calculate level-2 variables using the detached ds_work copy # Group by 'time_sec' (or user-defined time_interval_sec) and prepare for parallel processing time_interval_sec = getattr(size_config, 'time_interval_sec', 1) if time_interval_sec > 1: time_group = (ds_work['time_sec'] // time_interval_sec) * time_interval_sec ds_grouped = ds_work.groupby(time_group) else: ds_grouped = ds_work.groupby('time_sec') # Prepare all groups together because the first particle's overload IAT # may contribute dead time to both the current and preceding interval. prepared_groups = _allocate_overload_dead_time( ds_grouped, time_interval_sec, size_config.missing_overload_policy, ) # Parallel processing the groupby dataset # If num_workers is not specified, all CPU cores will be used. if num_workers is None: num_cpu_cores = multiprocessing.cpu_count() logger.info("Using all available CPU cores: num_cpu_cores=%s", num_cpu_cores) num_workers = num_cpu_cores if parallel_method is None: parallel_method = 'concurrent_futures' processed_datasets = parallel_processing_DatasetGroupBy( prepared_groups, num_workers=num_workers, parallel_method=parallel_method, ) # Sort results by 'time_sec' to maintain correct order processed_datasets.sort(key=lambda x: x[1]) # Extract datasets and corresponding 'time_sec' values datasets, time_secs = zip(*processed_datasets) if time_interval_sec > 1: # Use the middle time point (midpoint) to represent each group interval time_secs = [t + time_interval_sec / 2.0 for t in time_secs] # Combine datasets along a new dimension, with 'time_sec' as coordinate ds_out = xr.concat(datasets, dim=pd.Index(time_secs, name='time_sec')) # Reassign 'time_sec' attributes to the combined dataset ds_out.time_sec.attrs = time_sec_attrs ds_out.time_sec.attrs['time_interval'] = f"{time_interval_sec} seconds" if time_interval_sec > 1: ds_out.time_sec.attrs['note'] = f"Values represent the midpoint of each {time_interval_sec}-second interval." #--- Add global attributes ds_out.attrs['Software'] = f'COPS V{__version__}' ds_out.attrs['Institution'] = ds_work.attrs.get('Institution', '') ds_out.attrs['Time_Interval'] = f"{time_interval_sec} seconds" ds_out.attrs['Creation_Time'] = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%f') ds_out.attrs['Description'] = 'Contains size distributions of particle count, mass, etc. & various bulk properties.' ds_out.attrs['Project'] = ds_work.attrs.get('Project', '').strip() ds_out.attrs['Probe_Type'] = ds_work.attrs.get('Probe_Type', '').strip() #ds_out.attrs['Data_Source'] = input_spif_path ds_out.attrs['DoFConstant'] = size_config.resolved_dof_constant ds_out.attrs['Sample_Area_Method'] = SA_METHODS[size_config.SAmethod] ds_out.attrs['Diameter_Definition'] = f'{DIAMETER_CATEGORIES[size_config.diameter_choice][0]}: {DIAMETER_CATEGORIES[size_config.diameter_choice][1]}' if (size_config.applyIntArrThresh==1) and (size_config.reaccptShatrs==1): ds_out.attrs['Shattering_Algorithm'] = 'Applied with reacceptance of particles' ds_out.attrs['Reacceptance_Criteria'] = f'D > {size_config.reaccptD*1000} um; inter-arrival < {size_config.reaccptMaxIAT} sec.' elif (size_config.applyIntArrThresh==1) and (size_config.reaccptShatrs!=1): ds_out.attrs['Shattering_Algorithm'] = 'Applied without reacceptance of particles' else: ds_out.attrs['Shattering_Algorithm'] = 'Not applied' # Copy any other configuration/provenance attributes from ds_work for key, val in ds_work.attrs.items(): if key not in _TRANSIENT_LEVEL2_ATTRS and key not in ds_out.attrs: ds_out.attrs[key] = val if size_config.iCreateBad == 1: ds_out.attrs['iCreateBad'] = f'iCreateBad = {size_config.iCreateBad}: SDs from rejected particles included.' if size_config.iCreateAspectRatio == 1: ds_out.attrs['iCreateAspectRatio'] = f'iCreateAspectRatio = {size_config.iCreateAspectRatio}: SDs with aspect ratio.' ds_out.attrs['Accepted_Codes'] = ', '.join(size_config.accepted_codes) ds_out.attrs.update(loaded_config.provenance.attrs) # The Level-2 diameter selection (overrides the copied Level-1 record) and, for # active ML sizing, how many particles used the ML diameter or the fallback. ds_out.attrs.update(provenance_attrs(diameter_selection, None)) if class_outputs is not None or has_ml_classification_provenance(ds_out.attrs): ds_out.attrs.update(phase_attrs(phase_selection)) ml_family = ml_selection_key(size_config.diameter_choice) if ml_family is not None: _, source = selected_ml_diameter(ds_work, ml_family, loaded_config.ml.fallback, loaded_config.ml.min_n_s) ds_out.attrs['level2_selected_diameter_source_counts'] = json.dumps( {name: int(np.count_nonzero(source == code)) for code, name in enumerate(SOURCE_MEANINGS.split())}) # print(ds_out.attrs.items()) #--- Write the processed level-2 data to the output file logger.info("Writing Level-2 data to %r", output_spif_path) io.append_xarrayDataset_to_existing_NetCDF_file(nc_file_path=output_spif_path, ds_appended=ds_out, new_subgroup_name='level-2', parent_group=group, UNLIMITED_dims='time_sec') return
# endregion