cops package
Submodules
cops.analysis module
- cops.analysis.apply_level1_bulk_properties_and_qc(ds_out: Dataset, ds_images: Dataset, config: ProbeProcessingConfig | ConfigParser, tas: float | ndarray | DataArray | list[float] | tuple[float, ...] | None = None) Dataset[source]
Applies bulk property calculations and inter-arrival time quality control (QC) to a Level-1 single-particle dataset.
Parameters:
- ds_outxarray.Dataset
The Level-1 dataset containing single-particle geometric and morphological variables.
- ds_imagesxarray.Dataset
The core group dataset containing environmental variables (tas, Pres, Temp) and the active-high DMT
dof_flagwhen provided by the probe decoder.- configProbeProcessingConfig | configparser.ConfigParser
The configuration object or parser containing processing parameters and QC thresholds.
applyLevel1BulkAndQC=0skips the Level-1 bulk, phase, and QC calculations.- tasfloat, 1D array, or xarray.DataArray, optional
True airspeed in m s-1 to use only when
ds_imagesdoes not containtas. 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_flagand 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.
- cops.analysis.apply_quality_control_InterArrivalTime(ParticleAutoReject, InterArrivalTime, particle_diameter, area_ratio, ds, applyIntArrThresh, defaultIntArrThresh, reaccptShatrs, reaccptD, reaccptMaxIAT, probe_type, accepted_codes=['0', 'H', 'R'], *, tas=None, time_sec=None, diode_size=None, size_config=None, return_diagnostics=False)[source]
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:
- ParticleAutoRejectxarray.DataArray
Particle rejection codes (copied; the input is not modified)
- InterArrivalTimexarray.DataArray
Inter-arrival times [s] (copied; the input is not modified)
- particle_diameterxarray.DataArray
Particle diameters [mm]
- area_ratioxarray.DataArray
Particle area ratios [-]
- dsxarray.Dataset
Input dataset containing the active-high DMT
dof_flag, when available.- applyIntArrThreshint
Flag to apply inter-arrival time threshold (0 or 1)
- defaultIntArrThreshfloat
Default inter-arrival time threshold [s]
- reaccptShatrsint
Flag to reaccept particles from shattering events (0 or 1)
- reaccptDfloat
Minimum diameter for reacceptance [mm]
- reaccptMaxIATfloat
Maximum inter-arrival time for reacceptance [s]
- probe_typeint
Probe category: 1=HVPS, 2=2DS, 3=HVPS4, 4=Fast2DS, 5=CIP, 6=PIP, 7=CIP25, 8=CIP_grey, and 9=2DC.
- accepted_codeslist or tuple
List of accepted particle codes
- tasxarray.DataArray or np.ndarray, optional
True airspeed values [m/s]
- time_secxarray.DataArray or np.ndarray, optional
Particle timestamps [s]
- diode_sizefloat, optional
Diode size [mm]
- size_configSizeDistributionConfig, optional
Configuration object containing adaptive IAT settings
- return_diagnosticsbool, 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.
- cops.analysis.calculate_particle_bulk_properties(particle_diameter, ParticleArea, habit_str, Pres=None, Temp=None)[source]
Calculate derived particle bulk properties including mass, velocity, and area ratio.
Parameters:
- particle_diameterxarray.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.
- ParticleAreaxarray.DataArray or array-like
Measured particle area [mm²]
- habit_strxarray.DataArray or array-like
Particle habit classification (string codes)
- Presxarray.DataArray or array-like, optional
Atmospheric pressure [hPa]. Defaults to 500 hPa if not provided.
- Tempxarray.DataArray or array-like, optional
Atmospheric temperature [°C]. Defaults to -5°C if not provided.
Returns:
- dictDictionary 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.
- cops.analysis.calculate_particle_image_level1_variables_parallel(spif_attr, im_header, ds_images: Dataset, config: ProbeProcessingConfig | ConfigParser, num_workers: int | None = None, parallel_method: str | None = None, chunking_method: str = 'slice_count') Dataset[source]
Calculates level-1 variables from particle images, incorporating time information and various particle properties, then organizes these data into an xarray.Dataset.
Parameters:
- spif_attrobject
SPIF file attributes containing essential metadata, such as the measurement start date (start_date) and institution information.
- im_headerobject
Image header containing probe-specific metadata including diode array details (pixels, resolution) and instrument name.
- ds_imagesxarray.Dataset
Dataset containing particle image data and associated variables (image_sec, image_ns, and image_len).
- configProbeProcessingConfig | 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_workersint, 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_methodstr, optional
Method for parallel computation. Supported options: ‘concurrent_futures’, ‘loky’, ‘pathos’, ‘dask’, ‘ray’. Defaults to ‘concurrent_futures’ if not specified.
- chunking_methodstr, 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 – An xarray Dataset containing calculated Level-1 particle properties along with time-related variables, structured with dimensions including particle, diode, and other relevant coordinates.
- rtype:
xarray.Dataset
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.
- cops.analysis.calculate_particle_morphology(image_buffer: 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][source]
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.
- cops.analysis.calculate_sample_area(bin_centers: ndarray, res: float, arm_distance: float, num_diodes: int, sa_method: int, probe_type: int, laser_wavelength: float = 680.0, DoFConstant: float | None = None) ndarray[source]
Calculate image sample area assuming Heymsfield and Parish (1978).
Parameters:
- bin_centersarray_like
Mid-point of each bin in [millimeters].
- resfloat
Photodiode resolution, bin width in [microns].
- arm_distancefloat
Distance between the probe arms in [millimeters], defining the maximum depth of field (DOF) that can be considered.
- num_diodesint
Number of photodiodes (does not need to equal number of bins).
- sa_methodint
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_typeint
Type of probe used, influencing the depth of field (DOF) calculation.
- laser_wavelengthfloat, optional
Laser wavelength in nanometers [nm]. Defaults to 680.0 nm.
- DoFConstantfloat, optional
Coefficient c in DoF = 2c*r^2/lambda. When omitted, the probe-specific default is selected by
resolve_dof_constant.
Returns:
- sanp.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
- cops.analysis.calculate_sample_volume(bin_edges: ndarray, InterArrivalTime: DataArray, tas: 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: DataArray | None = None, time_interval_sec: float = 1.0, overload_dead_time: float | None = None) tuple[ndarray, ndarray, ndarray, ndarray, float][source]
Calculate sample volume for each size bin.
Parameters:
- bin_edgesarray-like
Bin edges [mm]
- InterArrivalTimearray-like
Inter-arrival times [s]
- tasarray-like
True airspeed [m/s]
- tasMaxfloat
Maximum true airspeed [m/s]
- resfloat
Diode resolution [um]
- arm_distancefloat
Arm distance [mm]
- num_diodesint
Number of active diodes
- sa_methodint
Sample area method
- probe_typeint
Probe type
- laser_wavelengthfloat, optional
Laser wavelength in nanometers [nm]. Defaults to 680.0 nm.
- DoFConstantfloat, optional
Coefficient used in the depth-of-field calculation. When omitted, the probe-specific default is selected by
calculate_sample_area.- overload_flagarray-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_secfloat, optional
Nominal duration of the output interval [s]. Defaults to 1 s.
- overload_dead_timefloat, 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.
- cops.analysis.check_level2_qc_settings(level1_attrs, level1_has_bulk: bool, requested: dict, where: str, warn_unknown: bool = True) None[source]
Refuse reusing Level-1 QC codes computed with QC settings other than
requested.Level-2 reuses Level-1
ParticleAutoRejectwhenever 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.
- cops.analysis.classify_particle_phase(arearatio_filled: ndarray, holroyd_habit: ndarray, diameter_mm: ndarray, diode_size_mm: float, Temp: ndarray | None = None, phase_method: str = 'soda2_roundness', phase_roundness_mode: str = 'standard', phase_area_ratio_floor: float = 0.4, phase_max_liquid_diameter_mm: float = 6.0, phase_size_rule_diodes: int = 10) ndarray[source]
- 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_fillednp.ndarray
Area ratio computed from the binary-filled image in image space [-]
- holroyd_habitnp.ndarray
Array of Holroyd classification habit string characters (e.g. ‘s’, ‘h’)
- diameter_mmnp.ndarray
Particle diameter in millimeters [mm]
- diode_size_mmfloat
Optical resolution of the probe diodes in millimeters [mm]
- Tempnp.ndarray, optional
Atmospheric temperature at the particle time in degrees Celsius [°C]
- phase_methodstr
Method for phase identification; must be “soda2_roundness” or “none”
- phase_roundness_modestr
Threshold mode for large drops; must be “standard” or “strict”
- phase_area_ratio_floorfloat
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_mmfloat
Maximum diameter threshold for liquid droplets; any particle larger than this is forced to ice
- phase_size_rule_diodesint
Size threshold in diodes (pixels) to separate tiny vs large particle rules
Returns:
- phasenp.ndarray
Phase classification codes (0=Unknown, 1=Liquid, 2=Ice)
History:
2026-07-06: Yongjie Huang, first created.
- cops.analysis.compute_adaptive_iat_threshold(iat_values: ndarray, tas_values: ndarray | float | None, diode_size_mm: float, intArrBins: int, intArrMinCount: int, intArrMaxSeconds: float, defaultIntArrThresh: float) dict[source]
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_valuesnp.ndarray
Array of inter-arrival times [s] for particles within the current time slice.
- tas_valuesnp.ndarray | float | None
True airspeed values [m/s] corresponding to the particles, or a single mean airspeed.
- diode_size_mmfloat
Effective optical resolution (diode size) of the probe [mm].
- intArrBinsint
Number of log-spaced bins to use for the IAT histogram.
- intArrMinCountint
Minimum number of valid (positive) IAT values required in the window to attempt peak finding.
- intArrMaxSecondsfloat
Maximum inter-arrival time [s] considered for the upper bound of the log-spaced histogram.
- defaultIntArrThreshfloat
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.
- cops.analysis.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)[source]
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.
- cops.analysis.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)[source]
Computes component feature scores and composite shatter score for all edges. All scores at edge 0 are forced to 0.0.
- cops.analysis.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)[source]
Identifies shattering clusters using hysteresis on shatter_score, evaluates roles, and updates ParticleAutoReject.
- cops.analysis.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)[source]
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_secxarray.DataArray or np.ndarray or None
Particle full high-precision timestamps [s].
- iat_arrnp.ndarray
Inter-arrival times [s].
- orig_negative_iatnp.ndarray
Boolean mask indicating particles originally possessing negative inter-arrival times.
- particle_diameternp.ndarray
Particle diameters [mm].
- is_accepted_arrnp.ndarray
Boolean mask indicating particles currently accepted by prior quality control steps.
- ParticleAutoReject_arrnp.ndarray
Array of particle rejection codes (will be modified in-place for accepted shattering cluster members).
- alpha_startfloat
P-value threshold to initiate a new shattering cluster.
- alpha_extendfloat
P-value threshold to extend an active shattering cluster.
- window_secfloat or int
Moving rolling window duration [s] for local Poisson rate estimation.
- min_lambdafloat
Fallback minimum natural arrival rate [s^-1].
- reaccptShatrsint
Flag to enable edge-aware parent particle reacceptance (0 or 1).
- reaccptDfloat
Minimum diameter threshold for parent particle reacceptance [mm].
- reaccptMaxIATfloat
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.
- cops.analysis.compute_rolling_poisson_metrics(full_time_sec, iat_arr, orig_negative_iat, window_sec, min_lambda)[source]
Computes rolling Poisson arrival rate (lambda_t) and arrival probability (p_i).
- cops.analysis.correct_spherical_poisson_spot(Dspot: float, Dedge: float) tuple[float, float][source]
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:
Compute the ratio x = Dspot / Dedge.
Use numpy’s searchsorted function to locate where this ratio fits in the predefined lookup tables (Dspot_Dedge and Dedge_D0).
Depending on the position of x, either directly use the closest table value or perform linear interpolation between the two nearest values.
Compute the correction factor as the inverse of the interpolated value.
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).
- cops.analysis.create_bulk_output_dataset(results_good: dict, results_bad: dict | None, active_sample_time: float, svol2: ndarray, good_partpercent: float, bin_edges: ndarray, area_bins: 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 | ndarray = nan, IWC: float | ndarray = nan, UWC: float | ndarray = nan, TWC: float | ndarray = nan, phase_processing_status: str = 'enabled') Dataset[source]
Constructs the final xarray Dataset for output using automated variable mapping.
Parameters:
- results_gooddict
Results dictionary for good particles
- results_baddict
Results dictionary for bad particles (or None)
- active_sample_timefloat
Nominal output interval minus instrument overload dead time [s]
- svol2array-like
Sample volume
- good_partpercentfloat
Percentage of good particles
- bin_edgesarray-like
Bin edges
- area_binsarray-like
Area ratio bin edges
- habitslist
List of habits
- iCreateAspectRatioint
Flag for aspect ratio
- iCreateBadint
Flag for bad particles
- results_liquiddict, optional
Results dictionary for liquid candidate particles. Defaults to None.
- results_icedict, optional
Results dictionary for ice candidate particles. Defaults to None.
- results_unknowndict, optional
Results dictionary for unknown candidate particles. Defaults to None.
- LWCfloat or np.ndarray, optional
Liquid Water Content [g/m^3]. Defaults to np.nan.
- IWCfloat or np.ndarray, optional
Ice Water Content [g/m^3]. Defaults to np.nan.
- UWCfloat or np.ndarray, optional
Unknown Water Content [g/m^3]. Defaults to np.nan.
- TWCfloat or np.ndarray, optional
Total Water Content (LWC + IWC + UWC) [g/m^3]. Defaults to np.nan.
- phase_processing_statusstr, 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.
- cops.analysis.estimate_active_sample_time(InterArrivalTime: DataArray, overload_flag: DataArray | None, time_interval_sec: float, overload_dead_time: float | None = None) float[source]
Estimate active sample time as the nominal interval minus overload dead time.
A preallocated
overload_dead_timetakes 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_timeis not supplied andoverload_flagis present.overload_flag (xarray.DataArray or None) – Particle-aligned active-high overload status:
1marks the preceding inter-arrival time as dead time and0marks normal sampling. Missing values or the fill value255produce a NaN result. WhenNone, 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:
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.- Return type:
- 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.
- cops.analysis.fit_ellipse(image_buffer: DataArray | ndarray, particle_mask: int = 0, method: str = None) tuple[tuple[float, float], tuple[float, float], float][source]
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.
- cops.analysis.get_circle_diameters(image_buffer: DataArray | ndarray, particle_mask: int = 0, tas_ratio: float = 1.0) dict[source]
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.
- cops.analysis.get_particle_masks(ParticleAutoReject: DataArray, SAmethod: int, CenterIn: DataArray, EntireIn: DataArray, accepted_codes: list = ['0', 'H', 'R']) tuple[DataArray, DataArray][source]
Generates boolean masks for good (accepted) and bad (rejected) particles.
Parameters:
- ParticleAutoRejectxarray.DataArray
Array containing rejection codes for each particle.
- SAmethodint
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().
- CenterInxarray.DataArray
Boolean array indicating if particle center is in DOF.
- EntireInxarray.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.
- cops.analysis.get_particle_parameters(image_buffer: DataArray, diode_size: float, particle_mask: int = 0, **kwargs) dict[source]
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)
- cops.analysis.holroyd(image_buffer: DataArray, diode_size: float, diode_num: int, particle_mask: int = 0, print_result: bool = False, plot: bool = False, _contour_data=None) dict[source]
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_habitstr
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_detailfloat
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
- cops.analysis.is_it_hollow(image_buffer: DataArray, particle_mask: int = 0, method: str = 'bounding_box', _contour_data=None) tuple[int, int, int][source]
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.findContourswithcv2.RETR_TREEto 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 (-) – 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 (-) – 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 asmax(Y) - min(Y) - 1for 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
- cops.analysis.mask_start_end(end_mask: int, start_mask: int, to_mask: ndarray) ndarray[source]
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
- cops.analysis.max_interior_circle(image_buffer: DataArray | ndarray, particle_mask: int = 0, tas_ratio: float = 1.0) tuple[float, float, float][source]
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.
- cops.analysis.min_enclosing_circle(image_buffer: DataArray | ndarray, particle_mask: int = 0, tas_ratio: float = 1.0) tuple[float, float, float][source]
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.
- cops.analysis.min_enclosing_ellipse(image_buffer: DataArray | ndarray, particle_mask: int = 0, tolerance: float = 0.01) tuple[tuple[float, float], tuple[float, float], float][source]
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.
- cops.analysis.min_enclosing_rotated_rectangle(image_buffer: DataArray | ndarray, particle_mask: int = 0) tuple[tuple[float, float], tuple[float, float], float][source]
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.
- cops.analysis.min_volume_ellipse(P: ndarray, tolerance: float = 0.01, use_convex_hull: bool = True) tuple[ndarray, ndarray][source]
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:
- Pnumpy.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.
- tolerancefloat
Error in the solution with respect to the optimal value.
- use_convex_hullbool
If True, computes the convex hull of the points first to reduce the number of points. This significantly improves performance for large datasets.
Returns:
- Anumpy.ndarray
A (d x d) matrix of the ellipse equation in the ‘center form’: (x-c)’ * A * (x-c) = 1.
- cnumpy.ndarray
A ‘d’ dimensional vector representing the center of the ellipse.
Example Usage:
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)
- cops.analysis.normalize_and_calculate_concentrations(dist: dict, svol2: ndarray, binwidth_cm: ndarray, iCreateAspectRatio: int, density: float = 0.91, shape_factor: float = np.float64(0.5773502691896257)) dict[source]
Normalize distributions and calculate concentrations.
Parameters:
- distdict
Dictionary of un-normalized distributions (from compute_distributions)
- svol2array-like
Sample volume [cm^3]
- binwidth_cmfloat
Bin width [cm]
- iCreateAspectRatioint
Flag to creating aspect ratio variables
- densityfloat, 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_factorfloat, 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.
- cops.analysis.parallel_processing_DatasetGroupBy(ds_grouped, num_workers: int = 8, parallel_method: str = 'concurrent_futures') list[source]
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:
A list of processed datasets, one for each group in the input ds_grouped object.
- Return type:
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.
- cops.analysis.parallel_processing_images(args_list: list, num_workers: int = 8, parallel_method: str = 'concurrent_futures', *, worker_fn: Callable = <function process_ith_particle_image>) list[source]
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:
A list of processed datasets, one for each set of arguments in args_list.
- Return type:
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.
- cops.analysis.particle_perimeter(image_buffer: DataArray, particle_mask: int = 0, boundary: str = 'all', method: str = 'morphology') int[source]
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.
- cops.analysis.process_ith_particle_image(ip: int, time, time_sec, time_ns, InterArrivalTime, image_buffer: DataArray, diode_size: float, diode_num: int, particle_mask: int = 0, iRectEllipse: int = 0, iCalcAllDiodeStats=0, total_images: int | None = None) dict[source]
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/totalnumbering.
- Returns:
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.
- Return type:
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’.
- cops.analysis.process_particle_chunk(chunk_id: int, start_idx: int, end_idx: int, chunk_images_numpy: ndarray, local_slice_starts: ndarray, local_slice_ends: ndarray, times_local: ndarray, times_sec_local: ndarray, times_ns_local: ndarray, inter_arrival_times_local: ndarray, diode_size: float, diode_num: int, particle_mask: int, iRectEllipse: int, iCalcAllDiodeStats: int, total_images: int | None = None) list[dict][source]
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.)
- cops.analysis.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 | ndarray | DataArray | list[float] | tuple[float, ...] | None = None) None[source]
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:
This function does not return a value. It writes the processed Level-1 data directly to the output NetCDF file.
- Return type:
None
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.
- cops.analysis.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[source]
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_pathstr
Path to the input SPIF (Single Particle Image Format) NetCDF file containing level-1 data.
- output_spif_pathstr, 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_workersint, optional
Number of parallel worker processes to use for data processing. If None (default), all available CPU cores are utilized.
- parallel_methodstr, optional
Parallel processing method to use (‘concurrent_futures’, etc.). Defaults to ‘concurrent_futures’ if not specified.
- allow_missing_configbool, 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_pathstr, optional
Path to a specific configuration file. If provided, the configuration is loaded directly from this file. Defaults to None.
- allow_cwd_fallbackbool, 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.
- cops.analysis.qc_settings_attrs(record: dict) dict[source]
NetCDF global attribute for a QC-settings record (JSON text).
- cops.analysis.qc_settings_record(source) dict[source]
Requested QC settings from a
SizeDistributionConfigor an attribute mapping.Missing attributes take the
SizeDistributionConfigdefaults, as the QC function does.
- cops.analysis.return_groups_with_specified_subgroup(nc_obj, target_subgroup: str, parent_path: str = '', groups_with_target: list | None = None, verbose: bool = True) list[source]
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)
- cops.analysis.scan_slice(image_slice: ndarray) tuple[int, int, int][source]
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
- cops.analysis.size_distribution_process_group(group: tuple) tuple[source]
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:
- grouptuple
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)
- cops.analysis.size_distribution_segment(ds: Dataset) Dataset[source]
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:
Parameter Extraction & Setup: Extracts particle and probe configuration variables, including true airspeed, inter-arrival times, and bounding box dimensions.
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).
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.
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.
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
- cops.analysis.vectorized_single_area(diameter: ndarray, habit: ndarray) ndarray[source]
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:
- diameternp.ndarray
An array of particle diameters in [centimeters].
- habitnp.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:
- areanp.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)
- cops.analysis.vectorized_single_mass(diameter: ndarray, habit: ndarray) ndarray[source]
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:
- diameternp.ndarray
An array of particle diameters in [centimeters].
- habitnp.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:
- iwcnp.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)
- cops.analysis.vectorized_single_vt(diameter: float | ndarray, area_ratio: float | ndarray, mass: float | ndarray, P: float | ndarray, T: float | ndarray, usingMitchell: bool = False) float | ndarray[source]
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
cops.io module
- cops.io.append_xarrayDataset_to_existing_NetCDF_file(nc_file_path: str, ds_appended: Dataset, new_subgroup_name: str, parent_group: str | None = None, UNLIMITED_dims: str | List[str] | None = None) None[source]
Appends an xarray Dataset as a new subgroup to an existing NetCDF file.
Parameters:
nc_file_path: Path to the existing NetCDF file.
ds_appended: xarray Dataset to append.
new_subgroup_name: Name for the new subgroup.
parent_group: Name of the parent group within the NetCDF file to which the new subgroup will be added. If None, adds to the root group.
UNLIMITED_dims: Specifies which dimensions should be unlimited. Can be a string (single dimension) or a list of strings (multiple dimensions).
History:
2026-07-18: Validate metadata and stage writes before exposing the new subgroup.
2024-03-05: Created by Yongjie Huang (huangynj@gmail.com)
- cops.io.convert_instrument_raw_data_to_spif(raw_file_path: str, config_file_path: str, output_spif_path: str | None = None) None[source]
Converts raw data from instruments to Single Particle Image Format (SPIF) using specified configuration settings.
This function takes the path to a raw data file and a configuration file as inputs and converts the raw data into SPIF format, which is a standardized format for storing and analyzing particle imaging data. The output SPIF file can either be specified by the user or automatically generated based on the raw file name.
Parameters:
raw_file_path (str): The file path to the raw data file that needs to be converted.
- config_file_path (str): The file path to the configuration file that specifies settings and parameters for the
conversion process. This configuration dictates how raw data is interpreted and converted.
- output_spif_path (str, optional): The file path where the converted SPIF file will be saved. If not provided,
the function will automatically generate a file name by appending ‘.nc’ directly to the raw file name (e.g., ‘RF01.2DS’ becomes ‘RF01.2DS.nc’). The generated SPIF file will be saved in the same directory as the raw file.
Returns:
None. The function performs the conversion and prints a message indicating the success of the operation, including the path to the generated SPIF file.
Example Usage:
convert_instrument_raw_data_to_spif( raw_file_path='/path/to/raw/data.raw', config_file_path='/path/to/config/file.ini' )
This will convert the specified raw data file using the given configuration and automatically generate the output SPIF file name and location based on the raw file name.
convert_instrument_raw_data_to_spif( raw_file_path='/path/to/raw/data.raw', config_file_path='/path/to/config/file.ini', output_spif_path='/path/to/output/data_spif.nc' )
This will convert the specified raw data file using the given configuration and save the SPIF file to the specified output path.
History:
2026-06-24: Updated default output naming convention to append ‘.nc’ directly – Yongjie Huang
2024-02-24: Created by Yongjie Huang (huangynj@gmail.com)
- cops.io.copy_instrument_configuration(instrument: str, project_name: str | None = None, aux_config: bool = False, dst_instrument_config: str | Path | None = None, overwrite: bool = False) None[source]
Copies the specified instrument configuration file and an auxiliary configuration file from the package resources to the current working directory. If a project name is provided, it prefixes the copied configuration files with the project name for easy identification.
Current supported Optical Array Probes (OAP):
2DC (Two Dimension Cloud particle imaging probe)
2DP (Two Dimension Precipitation particle imaging probe)
2DS (2D-Stereo, SPEC Inc.)
CIP (Cloud Imaging Probe, DMT)
PIP (Precipitation Imaging Probe, DMT)
HVPS (High Volume Precipitation Spectrometer, SPEC Inc.)
HVPS4 (SPEC HVPS4)
Fast2DS (SPEC Fast2DS)
CIP25 (DMT CIP25)
CIP_grey (DMT CIP grey)
Parameters:
- instrument (str): Name of the instrument for which the configuration file is to be copied.
Must correspond to one of the supported OAPs listed above.
- project_name (str, optional): Project name to prefix the configuration file names.
If specified, files are named <project_name>.<filename>. If omitted, files retain their original names.
- aux_config (bool, optional): Flag indicating whether to also copy a general auxiliary
configuration file (aux_config.ini). Defaults to False.
- dst_instrument_config (str/Path, optional): Full path of output instrument configuration file.
If omitted, the full path is set to /path/of/current/working/directory/<project_name>.<filename>.
overwrite (bool, optional): If True, overwrites existing destination files. Defaults to False.
Operation Details:
The function looks for the instrument-specific configuration file (<instrument>.ini) and, optionally, a general auxiliary configuration file (aux_config.ini), within the probe_config subdirectory of the cops package.
If the specified instrument configuration file is not found, a FileNotFoundError is raised.
If aux_config is True and the auxiliary configuration file is not found, a FileNotFoundError is raised.
If destination files exist and overwrite is False, a FileExistsError is raised.
Returns:
None. The function logs success messages or raises errors if the specified files cannot be found or copied.
Example Usage:
Copy just the instrument configuration for ‘2DS’:
copy_instrument_configuration('2DS')
Copy both the instrument and auxiliary configuration files for ‘2DS’, prefixed with ‘ESCAPE’:
copy_instrument_configuration('2DS', 'ESCAPE', aux_config=True)
History:
2026-07-03: Refactored by Yongjie Huang to add overwrite controls, parent directory handling, and raise FileExistsError/FileNotFoundError.
2024-02-24: Created by Yongjie Huang (huangynj@gmail.com)
- cops.io.decode_OAP_raw_data(raw_file_list: List[str], probe_name: str, project_name: str | None = None, out_dir: str | None = None, config_path: str | None = None, create_config_template: bool = False, overwrite_config_template: bool = False, allow_cwd_fallback: bool = False) None[source]
Decodes raw data files from Optical Array Probes (OAP) into the Single Particle Image Format (SPIF), applying probe-specific configurations. The function processes each raw file to generate output in a specified directory.
Parameters:
- raw_file_listlist
A list of file paths pointing to the raw data files to be processed.
- probe_namestr
The name of the probe, which determines the specific configuration file to use for decoding the raw data. Current supported Optical Array Probes (OAP):
2DC (Two Dimension Cloud particle imaging probe)
2DP (Two Dimension Precipitation particle imaging probe)
2DS (2D-Stereo, SPEC Inc.)
CIP (Cloud Imaging Probe, DMT)
PIP (Precipitation Imaging Probe, DMT)
HVPS (High Volume Precipitation Spectrometer, SPEC Inc.)
HVPS4 (SPEC HVPS4)
Fast2DS (SPEC Fast2DS)
CIP25 (DMT CIP25)
CIP_grey (DMT CIP grey)
- project_namestr, optional
The name of the project, which if provided, will be used to update the ‘project’ parameter in the ‘root’ section of the probe’s configuration file. It also prefixes the configuration file name for easy identification.
- out_dirstr, optional
The directory where the processed files will be saved. If not provided, the current working directory is used.
- config_pathstr, optional
Path to a specific configuration file.
- create_config_templatebool, optional
If True, creates a default config file template.
- overwrite_config_templatebool, optional
If True, overwrites existing config file template.
- allow_cwd_fallbackbool, optional
If True, allows looking for config in current working directory.
Operation Details:
Checks for the existence of the probe’s configuration file in the current working directory. If it exists, reads the configuration; if not, attempts to copy a default configuration file.
If a project name is provided and the ‘root’ section exists in the configuration, updates the project name in the configuration file.
Logs the current configuration settings for verification.
Processes each raw data file specified in ‘raw_file_list’, converting it to a standardized format and saving the output in ‘out_dir’.
Skips processing for any raw data file if the output file already exists in the output directory.
Example Usage:
Basic usage (defaults to searching adjacent files and falls back to CWD if allowed):
decode_OAP_raw_data( raw_file_list=['/path/to/raw/file1', '/path/to/raw/file2'], probe_name='2DS', project_name='MyProject', out_dir='/path/to/output' )
This will process ‘file1’ and ‘file2’ using the ‘2DS’ probe configuration, updating the project name to ‘MyProject’ in the configuration file, and save the processed files in ‘/path/to/output’.
Production pipeline usage specifying a custom configuration path and disabling CWD fallbacks:
decode_OAP_raw_data( raw_file_list=['/path/to/raw/file1'], probe_name='2DS', config_path='/path/to/custom_config.ini', allow_cwd_fallback=False )
Generating a default configuration template file at a specific path without decoding:
decode_OAP_raw_data( raw_file_list=['/path/to/raw/file1'], probe_name='2DS', config_path='/path/to/generated_config.ini', create_config_template=True, overwrite_config_template=True )
Returns:
None. Logs messages indicating the status of configuration file existence, parameter updates, and the processing status of each raw data file.
History:
- 2026-07-03: Yongjie Huang, refactored to support resolve_probe_config_path, batch-safety raises,
template copying, and overwrite arguments.
- 2025-12-31: Yongjie Huang, added ‘update_ini_param’ function to update a parameter in
an INI file while preserving comments and structure.
2024-02-24: Created by Yongjie Huang (huangynj@gmail.com)
- cops.io.get_ith_particle_image(ds_header: Dataset, ds_images: Dataset, ith: int) DataArray[source]
Extracts the image of the i-th particle from a dataset of images stored in Single Particle Image Format (SPIF).
This function calculates the start and end indices for the ith particle’s image data within a larger array of images based on the cumulative sum of image lengths and the number of diodes (pixels per slice). It then reshapes and returns this specific image as an xarray DataArray with appropriate dimensions and metadata.
Parameters:
ds_header (xarray.Dataset): The dataset containing the header information of the SPIF file, which includes the number of diodes (pixels) per image slice.
ds_images (xarray.Dataset): The dataset containing the images and associated metadata, including the lengths of individual particle images.
ith (int): The zero-based index of the particle whose image is to be extracted. For example, ith=0 will extract the first particle’s image in the dataset.
Returns:
xarray.DataArray: A 2D array representing the image of the specified particle. The dimensions of the array are (‘slice’, ‘diode’), where ‘slice’ represents the image length (number of slices) and ‘diode’ represents the number of pixels in each slice.
Note:
The function assumes that the image data is stored linearly in ds_images.image and that each particle’s image can be uniquely identified by its position (ith) in the sequence. The image length for each particle, required for reshaping the image data, is obtained from ds_images.image_len.
Performance Warning: This function recomputes image_len[:ip].sum() per call. If called in a loop over N particles, it results in O(N²) time complexity. This is perfectly suitable as an interactive single-particle helper, but for bulk processing, use the bulk analysis pipeline where cumulative sums (cumsum) are precomputed.
History:
2024-02-24: Created by Yongjie Huang (huangynj@gmail.com)
- cops.io.get_multi_particle_image(ds_header: Dataset, ds_images: Dataset, start_particle: int, n_particle: int, plot: bool = False, show_separators: bool = True) DataArray[source]
Extracts images of multiple particles from a dataset of images stored in Single Particle Image Format (SPIF).
This function calculates the start and end indices for a range of particles’ images within a larger array of images based on the cumulative sum of image lengths and the number of diodes (pixels per slice). It then reshapes and returns these specific images as an xarray DataArray with appropriate dimensions and metadata.
Parameters:
- ds_headerxarray.Dataset
The dataset containing the header information of the SPIF file, which includes the number of diodes (pixels) per image slice.
- ds_imagesxarray.Dataset
The dataset containing the images and associated metadata, including the lengths of individual particle images.
- start_particleint
The zero-based index of the particle whose image is to be extracted. For example, start_particle=0 will extract the first particle’s image in the dataset.
- n_particleint
The number of particles to extract images for, starting from start_particle.
- plotbool, optional
If True, plots the extracted images using matplotlib’s pcolormesh.
- show_separatorsbool, optional
If True (default), adds vertical lines between particles for visual distinction when plotting. Only has effect when plot=True.
Returns:
- xarray.DataArray
A 2D xarray DataArray representing the images of the specified particles. The dimensions of the array are (‘slice’, ‘diode’), where ‘slice’ represents the image length (number of slices) and ‘diode’ represents the number of pixels in each slice.
Note:
The function assumes that the image data is stored linearly in ds_images.image and that each particle’s image can be uniquely identified by its position (ith) in the sequence. The image length for each particle, required for reshaping the image data, is obtained from ds_images.image_len.
History:
2026-01-12: Yongjie Huang, added show_separators option for vertical lines between particles.
2024-03-28: Created by Yongjie Huang (huangynj@gmail.com)
- cops.io.read_spif_group(spif_file: str, group: str | None = None, decode_times: bool = False) Dataset[source]
Reads data from a specified group within a SPIF (Single Particle Image Format) dataset, using xarray. If no group is specified, it defaults to reading from the root group.
Parameters:
spif_file (str): The file path to the SPIF dataset to be read.
group (str, optional): The name of the group within the SPIF file. It can include subgroup, e.g., ‘2DS-H/level-1’. If None, the function attempts to read from the root group. Defaults to None.
decode_times (bool, optional): Whether to decode time variables into datetime objects, simplifying time series analysis. Defaults to False.
Returns:
xarray.Dataset: An xarray dataset containing the data from the specified group of the SPIF file, along with associated metadata and variables.
History:
2024-03-21: Created by Yongjie Huang (huangynj@gmail.com)
- cops.io.read_spif_header(spif_file: str, group: str | None = None, decode_times: bool = False) Dataset[source]
Reads the header of specified group from a SPIF (Single Particle Image Format) dataset using xarray.
Parameters:
spif_file (str): The file path to the SPIF dataset to be read.
group (str, optional): The name of the group within the SPIF file to access. If None, the function reads the root group. Defaults to None.
decode_times (bool, optional): Whether to decode time variables into datetime objects. Defaults to False.
Returns:
xarray.Dataset: The header of the SPIF file as an xarray dataset, which includes metadata and data variables of the specified group.
History:
2024-02-24: Created by Yongjie Huang (huangynj@gmail.com)
- cops.io.read_spif_images(spif_file: str, group: str | None = None, decode_times: bool = False) Dataset[source]
Reads image data from a specified group within a SPIF (Single Particle Image Format) dataset, using xarray. This function is specifically designed to access image data stored in the ‘core’ subgroup of the specified group. If no group is specified, it defaults to reading from the root group.
Parameters:
spif_file (str): The file path to the SPIF dataset to be read.
group (str, optional): The name of the parent group within the SPIF file from which the ‘core’ subgroup containing image data will be accessed. If None, the function attempts to read from the root group’s ‘core’ subgroup, if it exists. Defaults to None.
decode_times (bool, optional): Whether to decode time variables into datetime objects, simplifying time series analysis. Defaults to False.
Returns:
xarray.Dataset: An xarray dataset containing the image data from the specified ‘core’ subgroup of the SPIF file, along with associated metadata and variables.
History:
2024-02-24: Created by Yongjie Huang (huangynj@gmail.com)
cops.plot module
- cops.plot.plot_single_particle_image_with_enclosing_shape(particle_image: DataArray, plot_circle: bool = True, plot_rectangle: bool = True, plot_MinEllipse: bool = True, plot_FitEllipse: bool = True, ax: Axes | None = None, show: bool = True) None[source]
Plots a single particle image along with various enclosing geometric shapes.
Parameters:
particle_image (xarray.DataArray): An xarray DataArray representing the image of a single particle.
plot_circle (bool, optional): Whether to plot the minimum enclosing circle. Defaults to True.
plot_rectangle (bool, optional): Whether to plot the minimum enclosing rotated rectangle. Defaults to True.
plot_MinEllipse (bool, optional): Whether to plot the minimum enclosing ellipse. Defaults to True.
plot_FitEllipse (bool, optional): Whether to plot the fitted ellipse. Defaults to True.
ax (matplotlib.axes.Axes, optional): The axes to plot on. If None, the current axes are used.
show (bool, optional): Whether to call plt.show() after plotting. Defaults to True.
Returns:
None. The function displays the plot or adds elements to the provided axes.
History:
2024-02-24: Created by Yongjie Huang (huangynj@gmail.com)
- cops.plot.quick_look_single_particle_image(particle_image: DataArray, ax: Axes | None = None, show: bool = True) None[source]
Displays a quick look visualization of a single particle image.
Parameters:
particle_image (xarray.DataArray): An xarray DataArray representing the image of a single particle. The DataArray should have two dimensions corresponding to the image’s pixel dimensions.
ax (matplotlib.axes.Axes, optional): The axes to plot on. If None, the current axes are used.
show (bool, optional): Whether to call plt.show() after plotting. Defaults to True.
Returns:
None. The function displays the image plot or adds it to the provided axes.
History:
2024-02-24: Created by Yongjie Huang (huangynj@gmail.com)
cops.variables module
- cops.variables.IAT_MF_COMPONENT_SCORES = ('iat_score', 'burst_density_score', 'size_contrast_score', 'small_fragment_score', 'morphology_score')
Per-particle multifeature shattering component scores (optional Level-1 diagnostics).
- cops.variables.level_1_variables() Dict[str, VariableMeta][source]
- cops.variables.level_2_variables() Dict[str, VariableMeta][source]
cops.config module
Configuration management models for COPS particle analysis.
This module centralizes configuration parsing, defaults, validation, and provenance tracking using immutable dataclass models, ensuring type safety and decoupling pipeline functions from raw ConfigParser instances.
History:
2026-07-03: Yongjie Huang, implemented resolve_probe_config_path and updated load_probe_config.
2026-06-27: Yongjie Huang, created to centralize ConfigParser logic into structured dataclass models.
- class cops.config.ConfigProvenance(path: str | None, status: str)[source]
Bases:
objectTracks the origin and operational status of processing configurations.
- class cops.config.ImageProcessingConfig(particle_mask: int = 0, iRectEllipse: int = 0, iCalcAllDiodeStats: int = 0, tasMax: float = 170.0, phase_method: str = 'soda2_roundness', phase_roundness_mode: str = 'standard', phase_area_ratio_floor: float = 0.4, phase_max_liquid_diameter_mm: float = 6.0, phase_size_rule_diodes: int = 10, applyLevel1BulkAndQC: int = 1)[source]
Bases:
objectConfiguration parameters for Level-1 particle image processing.
- attrs_for_dataset() dict[str, Any][source]
Returns dictionary of attributes to attach to NetCDF datasets.
- classmethod from_parser(config: ConfigParser) ImageProcessingConfig[source]
Instantiates configuration from a ConfigParser object.
- class cops.config.MLClassificationConfig(families: tuple[str, ...] = (), bundle_path: str | None = None, model_probe: str | None = None, n_threads: int = 1, batch_size: int = 20000)[source]
Bases:
objectOptional ML source-class classification (
[ml_classification]section).INI keys carry the same
ml_prefix as[ml_sizing]:ml_families,ml_bundle_path,ml_model_probe,ml_n_threadsandml_batch_size. The classifier is disabled whenfamiliesis empty. Enabling one or more families requires a model bundle, supplied bybundle_pathor theCOPS_ML_CLASSIFICATION_BUNDLEenvironment variable.n_threadsandbatch_sizeare runtime controls and therefore are not part of the scientific dataset identity returned byattrs_for_dataset().- attrs_for_dataset() dict[str, Any][source]
Return scientific identity attributes, or no attributes when disabled.
- classmethod from_parser(config: ConfigParser) MLClassificationConfig[source]
Instantiate configuration from the optional
[ml_classification]section.
- class cops.config.MLSizingConfig(families: tuple[str, ...] = (), bundle_path: str | None = None, model_probe: str | None = None, fallback: str = 'D_s', min_n_s: float = 0.0, n_threads: int = 1, batch_size: int = 20000, population_mode: str = 'split', entire_family: str | None = None, edge_family: str | None = None)[source]
Bases:
objectOptional ML size correction (
[ml_sizing]section); disabled whenfamiliesis empty.Enabling families stores diagnostic
D_s_<family>predictions in Level-1 without changing the selected diameter. Selecting one of them for sizing additionally needsdiameter_choice8/9/10 in[particle_size_distribution]and an explicitml_model_probe(validated inProbeProcessingConfig).population_mode(ml_population_mode) is"split"by default: entire-in and center-in edge particles are sized by separate models of the same family, which needs a version-2 bundle."entire_only"is the explicit legacy mode (entire-in models only; version-1 bundles).entire_family/edge_family(ml_entire_family,ml_edge_family) define the mixedD_s_mlselection ofdiameter_choice11; both or neither, split mode only, each enabled infamilies.bundle_pathfalls back to theCOPS_ML_SIZING_BUNDLEenvironment variable.fallbackis the per-particle policy for active sizing (only"D_s").min_n_sis an optional explicit support cutoff in pixels for active sizing: particles with storedN_sbelow it use the fallback (0 disables; raw predictions are always kept).n_threadsbounds BLAS/OpenMP/forest threads andbatch_sizethe particles per prediction batch; neither changes results.- attrs_for_dataset() dict[str, Any][source]
Attributes describing the ML configuration; empty when disabled (default outputs unchanged).
- classmethod from_parser(config: ConfigParser) MLSizingConfig[source]
Instantiates configuration from the optional
[ml_sizing]section.
- class cops.config.ProbeProcessingConfig(image: ImageProcessingConfig, size: SizeDistributionConfig, provenance: ConfigProvenance, ml: MLSizingConfig = MLSizingConfig(families=(), bundle_path=None, model_probe=None, fallback='D_s', min_n_s=0.0, n_threads=1, batch_size=20000, population_mode='split', entire_family=None, edge_family=None), classification: MLClassificationConfig = MLClassificationConfig(families=(), bundle_path=None, model_probe=None, n_threads=1, batch_size=20000))[source]
Bases:
objectAggregate configuration container combining image processing, size distributions, and provenance.
- classification: MLClassificationConfig = MLClassificationConfig(families=(), bundle_path=None, model_probe=None, n_threads=1, batch_size=20000)
- classmethod from_parser(config: ConfigParser, provenance: ConfigProvenance | None = None) ProbeProcessingConfig[source]
Instantiates aggregate configuration from a ConfigParser object.
- image: ImageProcessingConfig
- ml: MLSizingConfig = MLSizingConfig(families=(), bundle_path=None, model_probe=None, fallback='D_s', min_n_s=0.0, n_threads=1, batch_size=20000, population_mode='split', entire_family=None, edge_family=None)
- provenance: ConfigProvenance
- size: SizeDistributionConfig
- class cops.config.SizeDistributionConfig(probe_type: int = 0, laser_wavelength: float = 680.0, DoFConstant: float | None = None, diameter_choice: int = 6, applyIntArrThresh: int = 1, defaultIntArrThresh: float = 1e-06, reaccptShatrs: int = 1, reaccptD: float = 0.05, reaccptMaxIAT: float = 1e-06, SAmethod: int = 0, iCreateAspectRatio: int = 0, iCreateBad: int = 0, time_interval_sec: int = 1, missing_overload_policy: str = 'warn_nominal', intArrThreshMode: str = 'fixed', intArrAdaptiveWindowSec: int = 1, intArrBins: int = 35, intArrMinCount: int = 200, intArrMaxSeconds: float = 1.0, intArrFallback: str = 'fixed', intArrProbAlphaStart: float = 0.01, intArrProbAlphaExtend: float = 0.05, intArrProbRollingWindowSec: int = 5, intArrProbMinLambda: float = 10.0, intArrMFScoreStart: float = 0.75, intArrMFScoreExtend: float = 0.55, intArrMFIatWeight: float = 0.5, intArrMFDensityWeight: float = 0.15, intArrMFSizeWeight: float = 0.2, intArrMFFragmentWeight: float = 0.1, intArrMFMorphWeight: float = 0.05, intArrMFSmallDiameterMm: float = 0.2, intArrMFParentRatio: float = 2.0, intArrMFDensityEdgeHalfWindow: int = 5, intArrMFDensityMaxSeconds: float = 0.001, intArrMFAreaRatioGood: float = 0.6, intArrMFWriteComponentDiagnostics: int = 0, bin_edges_str: str | None = None, accepted_codes: tuple[str, ...] = ('0', 'H', 'R'))[source]
Bases:
objectConfiguration parameters for Level-2 particle size distribution calculations and QC.
- classmethod from_parser(config: ConfigParser) SizeDistributionConfig[source]
Instantiates configuration from a ConfigParser object.
- resolve_bin_edges(diode_size: float) ndarray[source]
Parses and resolves bin_edges array based on configuration string or diode size fallback.
- cops.config.ensure_probe_config(config: ProbeProcessingConfig | ConfigParser) ProbeProcessingConfig[source]
Transparently converts raw ConfigParser instances to ProbeProcessingConfig for backwards compatibility.
- cops.config.load_probe_config(input_spif_path: str, project_name: str | None, probe_name: str, allow_missing: bool = False, config_path: str | None = None, allow_cwd_fallback: bool = False) ProbeProcessingConfig[source]
Locates, loads, and parses probe configuration from an external .ini file. Searches current working directory and input file directory, establishing strict data provenance.
History:
2026-07-03: Refactored by Yongjie Huang to use resolve_probe_config_path.
- cops.config.resolve_dof_constant(probe_type: int, configured_value: float | None = None) float[source]
Resolve the configured DoF coefficient or the probe-specific default.
SPEC probes (HVPS, 2DS, HVPS4, and Fast2DS) use the SPEC/Lawson default; all other probe types use the general DMT/Knollenberg default.
References
- SPEC 2DS Post Processing Software Manual
Lawson, R. P., D. O’Connor, P. Zmarzly, K. Weaver, B. Baker, Q. Mo, and H. Jonsson, 2006: The 2D-S (Stereo) Probe: Design and Preliminary Tests of a New Airborne, High-Speed, High-Resolution Particle Imaging Probe. J. Atmos. Oceanic Technol., 23, 1462–1477, https://doi.org/10.1175/JTECH1927.1
- DMT Data Analysis User’s Guide – Chapter II: Single Particle Imaging
Knollenberg, R. G., 1970: The Optical Array: An Alternative to Scattering or Extinction for Airborne Particle Size Determination. J. Appl. Meteor. Climatol., 9, 86–103, https://doi.org/10.1175/1520-0450(1970)009%3C0086:TOAAAT%3E2.0.CO;2
History
2026-07-17: Yongjie Huang (huangynj@gmail.com), first created.
- cops.config.resolve_probe_config_name(instrument_name: str, resolution: float) str[source]
Return the COPS configuration name represented by a SPIF header.
- cops.config.resolve_probe_config_path(input_path: str, project_name: str | None, probe_name: str, config_path: str | None = None, allow_cwd_fallback: bool = False) str | None[source]
Resolves the configuration file path with priority checks and ambiguity/symlink guarding.
History:
2026-07-03: Created by Yongjie Huang to resolve configuration file paths.
cops.constants module
Physical constants and configuration defaults for COPS particle analysis.
This module centralizes constants used throughout the analysis pipeline, improving code readability and maintainability.
History:
2025-12-30: Yongjie Huang, created during refactoring of size_distribution_segment.
cops.utils module
Utility functions for Cloud OAP Processing Software (COPS). Includes PSD reconstruction, combining, and moment calculations.
- cops.utils.calculate_effective_diameter(bin_edges, nD)[source]
Calculate the effective diameter (Deff) of a particle size distribution. Deff is defined as the ratio of the 3rd moment to the 2nd moment of the PSD.
Parameters:
- bin_edgesarray-like, shape (N+1,)
1D array of bin edges.
- nDarray-like, shape (N,) or (T, N)
1D or 2D array of spectral number density, n(D) = dN/dD.
Returns:
- Defffloat or ndarray, shape () or (T,)
The effective diameter (in the same units as bin_edges).
History:
2026-07-06: Extracted to cops.utils module.
- cops.utils.combine_reconstructed_psd(sd_1, sd_2, bin_mid, overlap_min, overlap_max)[source]
Combine two PSD arrays on the same bins (sd_1 for small particles, sd_2 for large particles). Works for both 1D (single PSD) and 2D (time series of PSDs).
Below overlap_min: uses sd_1 Above overlap_max: uses sd_2 Between overlap_min and overlap_max: uses the mean of sd_1 and sd_2
Parameters:
- sd_1array-like, shape (N,) or (T, N)
PSD array for small particles.
- sd_2array-like, shape (N,) or (T, N)
PSD array for large particles.
- bin_midarray-like, shape (N,)
Midpoint diameters of the bins.
- overlap_minfloat
Lower boundary of the overlap region.
- overlap_maxfloat
Upper boundary of the overlap region.
Returns:
- sd_combinedndarray, shape (N,) or (T, N)
Combined PSD array.
History:
2026-07-06: Extracted to cops.utils module.
- cops.utils.reconstruct_psd(bin_edges_old, nD_old, bin_edges_new)[source]
Reconstruct a particle size distribution onto new bin edges.
The method builds a cumulative distribution from the original n(D) (assuming n(D) is constant within each bin), then differences the cumulative values at the new bin edges to obtain new n(D) values. Total number concentration is conserved over the overlapping size range.
Parameters:
- bin_edges_oldarray-like, shape (N+1,)
Original bin edges.
- nD_oldarray-like, shape (N,)
Original number concentration density n(D).
- bin_edges_newarray-like, shape (M+1,)
New bin edges in the same units as bin_edges_old.
Returns:
- nD_newndarray, shape (M,)
Reconstructed n(D) on the new bins in the same units as nD_old
History:
2026-07-06: Extracted to cops.utils module.
2026-06-11: Vectorized version using scipy.interpolate.interp1d, replacing np.interp.
2026-02-27: First created, Yongjie Huang (huangynj@gmail.com)