COPS Example of Inter-Arrival Time Analysis

import xarray as xr
import numpy as np
import cops
**********************************************************
*            CCCCC    OOOOO   PPPPPPP    SSSSSSS __|__   *
*    _ .    CC   CC  OO   OO  PP    PP  SS    --*-(_)-*--*
*  (  _ )_  CC       OO   OO  PPPPPPP    SSSSSSS         *
*(_  _(_ ,) CC   CC  OO   OO  PP               SS        *
*            CCCCC    OOOOO   PP         SSSSSSS         *
**********************************************************
*          CLOUD OAP PROCESSING SOFTWARE (COPS)          *
*                    (Version 0.0.1)                     *
*                Copyright (C) 2024-2026                 *
**********************************************************
* This software is free: You may redistribute and/or     *
* modify it under the terms of the GNU General Public    *
* License version 3 or any later version                 *
* (GPL-3.0-or-later).                                    *
*                                                        *
* This software is distributed "AS IS", WITHOUT ANY      *
* WARRANTY; without even the implied warranty of         *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.   *
* See the GPL-3.0-or-later license for more details:     *
* https://www.gnu.org/licenses/gpl-3.0.html              *
**********************************************************
# output_spif_path = f'spif_2ds_lvl0/{file_2DS}'
# cops.analysis.process_spif_image_append_level0_data(input_spif_path=file_2DS, 
#                                                          output_spif_path=output_spif_path)
file_2DS_lvl0 = './output/spif_lvl1/base100101000000.2DS_ice_v01.nc'
file_2DS_lvl0
'./output/spif_lvl1/base100101000000.2DS_ice_v01.nc'
#!ncdump -h spif_2ds_lvl0/base100101000000_2DS_ice_v01.nc
ds_lvl0 = xr.open_dataset(file_2DS_lvl0, group='2DS-V/level-1', decode_times=False)
ds_lvl0
<xarray.Dataset> Size: 6MB
Dimensions:                   (particle: 7459, diode: 128, slice_pos: 2,
                               coords: 4)
Coordinates:
  * particle                  (particle) int64 60kB 0 1 2 3 ... 7456 7457 7458
  * diode                     (diode) int64 1kB 0 1 2 3 4 ... 124 125 126 127
  * slice_pos                 (slice_pos) int64 16B 0 1
  * coords                    (coords) int64 32B 0 1 2 3
Data variables: (12/62)
    time                      (particle) float64 60kB ...
    time_sec                  (particle) int32 30kB ...
    time_ns                   (particle) int32 30kB ...
    ParticleLength            (particle) int16 15kB ...
    ParticleWidth             (particle) int16 15kB ...
    ParticleArea              (particle) float64 60kB ...
    ...                        ...
    particle_vt               (particle) float32 30kB ...
    particle_pr               (particle) float32 30kB ...
    particle_phase            (particle) int8 7kB ...
    particle_mass_liquid      (particle) float32 30kB ...
    particle_vt_liquid        (particle) float32 30kB ...
    particle_pr_liquid        (particle) float32 30kB ...
Attributes: (12/22)
    processing_config_source:      ./ICCP2024_probe_raw_data/ICCP2024.2DS.ini
    Institution:                   University of Oklahoma
    diode_size:                    0.01
    Description:                   Contains size, morphological, and other pa...
    diameter_selection_signature:  a583fc8c24cb60f8a84eaa006a84dbc7e448b0b20f...
    overload_correction_source:    probe_overload_flag
    ...                            ...
    phase_area_ratio_floor:        0.4
    applyLevel1BulkAndQC:          1
    processing_provenance_status:  NOMINAL: Configured via external .ini file
    Probe_Type:                    2DS
    iat_qc_source:                 probabilistic
    level1_bulk_qc_status:         enabled
IntArr = ds_lvl0['InterArrivalTime']
IntArr
<xarray.DataArray 'InterArrivalTime' (particle: 7459)> Size: 60kB
[7459 values with dtype=float64]
Coordinates:
  * particle  (particle) int64 60kB 0 1 2 3 4 5 ... 7454 7455 7456 7457 7458
Attributes:
    units:        sec
    description:  Inter-arrival time between particles (use diff(time_in_seco...
time_sec, time_ns = ds_lvl0['time_sec'], ds_lvl0['time_ns']
time_sec
<xarray.DataArray 'time_sec' (particle: 7459)> Size: 30kB
[7459 values with dtype=int32]
Coordinates:
  * particle  (particle) int64 60kB 0 1 2 3 4 5 ... 7454 7455 7456 7457 7458
Attributes:
    units:        seconds since start_date
    start_date:   2010-01-01 00:00:00 UTC
    description:  image arrival time in seconds
Dmax = ds_lvl0['D_s']
Dmax
<xarray.DataArray 'D_s' (particle: 7459)> Size: 30kB
[7459 values with dtype=float32]
Coordinates:
  * particle  (particle) int64 60kB 0 1 2 3 4 5 ... 7454 7455 7456 7457 7458
Attributes:
    units:            um
    long_name:        Diameter of minimum enclosing circle
    equivalent_name:  D_max
IntArr[IntArr <= 0] = np.nan
from scipy.stats import mode

def determine_particles(timehhmmss, numparticles):
    mode_value, mode_count = mode(timehhmmss)[0], mode(timehhmmss)[1]
    print(mode_value, mode_count)
    if mode_count < numparticles:
        num_particles = numparticles
    else:
        num_particles = (numparticles / 4) * np.ceil(mode_count / (numparticles / 4))
    print(f'  {num_particles} particles will be factored into the bimodal distribution fit.')
    return num_particles
numparticles = 2000
num_particles = determine_particles(time_sec, numparticles)
53 146
  2000 particles will be factored into the bimodal distribution fit.
import numpy as np

IntArr[IntArr < 0] = 0
IntArr[IntArr > 0.1] = 0

# Generate bins for the histogram
bins = np.logspace(-7, 0, 35)  # Creates 35 logarithmically spaced bins between 10^-7 and 10^0

# Calculate the width of the bins for normalization
width = np.log(bins[1]) - np.log(bins[0])

bins, width
(array([1.00000000e-07, 1.60650600e-07, 2.58086154e-07, 4.14616956e-07,
        6.66084629e-07, 1.07006896e-06, 1.71907220e-06, 2.76169981e-06,
        4.43668733e-06, 7.12756483e-06, 1.14504757e-05, 1.83952580e-05,
        2.95520924e-05, 4.74756138e-05, 7.62698586e-05, 1.22527986e-04,
        1.96841945e-04, 3.16227766e-04, 5.08021805e-04, 8.16140079e-04,
        1.31113394e-03, 2.10634454e-03, 3.38385515e-03, 5.43618362e-03,
        8.73326162e-03, 1.40300372e-02, 2.25393390e-02, 3.62095835e-02,
        5.81709133e-02, 9.34519215e-02, 1.50131073e-01, 2.41186470e-01,
        3.87467512e-01, 6.22468884e-01, 1.00000000e+00]),
 0.4740616367928929)
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.stats import mode

def bimodal_fit_function(dt, tau1, tau2, A):
    return A * (dt/tau1) * np.exp(-dt/tau1) + (1-A) * (dt/tau2) * np.exp(-dt/tau2)

tau_std = [1e-2, 1e-6, 0.5]

# Assuming IntArr, num_particles, and bins are already defined
n_samples = len(IntArr) // num_particles + 1
hist2dc = np.nan * np.zeros((n_samples, len(bins) - 1))
NEWtime2dc = np.nan * np.zeros(n_samples)
NEWdate2dc = np.nan * np.zeros(n_samples)

threshhold = np.zeros_like(IntArr)  # Initialize threshold array
threshhold_ww = np.zeros_like(IntArr)
threshhold_ak = np.zeros_like(IntArr)
tau_all = np.zeros((len(IntArr), 3)) 

directory = './'

# Loop through sample populations and determine threshold
for n, i in enumerate(range(0, len(IntArr), num_particles)):
    print(f'  Current Progress: {i}/{len(IntArr)} Time: ', np.datetime64('now'))
    
    indices = slice(i, min(i + num_particles, len(IntArr)))
    arr = IntArr[indices]
    h, _ = np.histogram(arr, bins)
    bins_center = bins[:-1] + np.diff(bins) / 2
    
    hist2dc[n, :] = h
    NEWtime2dc[n] = time_ns.values[i] if i < len(time_ns.values) else np.nan
    #NEWdate2dc[n] = date[i] if i < len(date) else np.nan

    # Initial parameter guesses
    beta0 = [1e-2, 1e-6, 0.5]
    try:
        tau_opt, _ = curve_fit(bimodal_fit_function, bins_center, h/np.sum(h)/width, p0=beta0)
    except RuntimeError:
        # Handle fitting error by setting a default value
        tau_opt = [1e-2, 1e-6, 0.5]  # Example default values

    # Check if tau_opt contains any NaN values; this example uses default values to handle fit issues
    if np.isnan(tau_opt).any():
        threshhold[i:min(i+num_particles, len(IntArr))] = 1.3494e-6  # Set default threshold for this segment
    else:
        threshhold[i:min(i+num_particles, len(IntArr))] = min(tau_opt[0:2]) * 2  # Compute and set threshold for this segment
    
    # Update tau_all for each particle in the current segment
    for j in range(i, min(i+num_particles, len(IntArr))):
        tau_all[j, :] = tau_opt

    dt = bins_center
    tau = tau_opt 
    # Calculate the fitted histogram (hfit) based on the bimodal fit function
    # hfit = (1-tau[2]) * (dt/tau[0]) * np.exp(-dt/tau[0]) + tau[2] * (dt/tau[1]) * np.exp(-dt/tau[1])
    hfit = bimodal_fit_function(dt, *tau)

    # Determine thresholds
    tau1, tau2 = max(tau[0:2]), min(tau[0:2])
    mask = (dt < tau1) & (dt > tau2)
    newDT_indices = np.where(mask)[0]
    
    if len(newDT_indices) == 0:  # If newDT is empty, find closest points
        closest_below = np.max(np.where(dt < tau1)[0])
        closest_above = np.min(np.where(dt > tau2)[0])
        newDT_indices = [closest_below, closest_above]
    
    # Finding min values within newDT
    minFit = np.min(hfit[newDT_indices])
    indexFit = newDT_indices[np.argmin(hfit[newDT_indices])]
    minOriginal = np.min(h[newDT_indices])
    indexOriginal = newDT_indices[np.argmin(h[newDT_indices])]
    
    # Set thresholds based on newDT
    if len(newDT_indices) == 0:  # If no suitable newDT found, use default thresholds
        print(f'Trouble obtaining a bimodal fit for index {i}. Setting inter-arrival thresholds to a default value.')
        threshhold_ww[i:min(i+num_particles, len(IntArr))] = 1.3494e-6
        threshhold_ak[i:min(i+num_particles, len(IntArr))] = 1.3494e-6
    else:
        threshhold_ww[i:min(i+num_particles, len(IntArr))] = dt[indexFit]
        threshhold_ak[i:min(i+num_particles, len(IntArr))] = dt[indexOriginal]


    if not np.isnan(tau_std).any():
        plt.figure(figsize=(10, 6))
        plt.bar(bins[:-1], h / np.sum(h) / width, width=np.diff(bins), align='edge', color='grey', edgecolor='black', label='Frequency')
        plt.plot(dt, hfit, 'k', label='Fit')
        
        # Plotting tau lines and thresholds
        plt.axvline(x=tau2, color='k', linestyle='--', label=f'tau2={tau2}')
        plt.axvline(x=tau1, color='k', linestyle='-.', label=f'tau1={tau1}')
        plt.axvline(x=min(tau_std[:2])*2, color='g', label='2*(lower peak)')
        plt.axvline(x=dt[indexFit], color='b', label='threshold_ww')
        plt.axvline(x=dt[indexOriginal], color='r', label='threshold_ak')
        
        plt.ylim([0, 0.5])
        plt.xscale('log')
        plt.xlabel('Inter-arrival Time (s)')
        plt.ylabel('Frequency')
        plt.title(f'Inter-arrival Distribution ({NEWtime2dc[n]:.6f} UTC)')
        plt.legend(loc='upper left', fontsize=6)
        
        # Adjust the path and filename as necessary
        #plt.savefig(f"{directory}/{probeName}_IntArrHistogram_{NEWtime2dc[n]:06}.jpg", dpi=600)
        plt.show()
        plt.close()  # Close the figure to free memory, especially important in loops
  Current Progress: 0/7459 Time:  2026-11-08T01:16:58
../_images/964070fbb611e0e9734b208f9dba593e5aca4346ba9a0f7a0269043fd7db5ec4.png
  Current Progress: 2000/7459 Time:  2026-11-08T01:16:58
../_images/2c8e843b9d19132b2e4b7d9bfd8e27b1afd9573d61bd286d64c30c94ef3a7c8d.png
  Current Progress: 4000/7459 Time:  2026-11-08T01:16:58
../_images/42f116263bcc54628fba4a32349ef4b09b4bb4252077c3a33737bcdc592f3931.png
  Current Progress: 6000/7459 Time:  2026-11-08T01:16:59
../_images/aba04edecae0ec3352f90b5a738bb3da7bc0a1f10bb588e5109c6f609245d36d.png
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np

# Bins for histogram
bins = np.logspace(-7, 0, 70)
binsCenter = bins[:-1] + np.diff(bins) / 2

hist2dc_contour = []
NEWtime2dc = []

for n, i in enumerate(range(0, len(IntArr), num_particles)):
    indices = slice(i, min(i + num_particles, len(IntArr)))
    arr = IntArr[indices]
    h, _ = np.histogram(arr, bins)
    
    hist2dc_contour.append(h)
    
    # Time adjustment logic
    if n > 0 and time_sec.values[i] == NEWtime2dc[n-1]:
        NEWtime2dc.append(time_sec.values[i] + 1)
    else:
        NEWtime2dc.append(time_sec.values[i])

# Adjust the end time and date for the contour plot
NEWtime2dc[-1] = time_sec.values[-1]

hist2dc_contour = np.array(hist2dc_contour)
histsum = hist2dc_contour.sum(axis=1)
histsum = np.tile(histsum[:, np.newaxis], (1, 69))

# Reference datetime
reference_date = datetime.strptime(time_sec.start_date, '%Y-%m-%d %H:%M:%S UTC')
# Convert seconds to timedelta and calculate the new datetime 
time_contour = [reference_date + timedelta(seconds=int(sec)) for sec in NEWtime2dc]
hist2dc_contour.shape, histsum.shape
((4, 69), (4, 69))
threshhold_ww.shape
(7459,)
hist_normalized = hist2dc_contour / histsum

# Create the contour plot
plt.figure(figsize=(10, 6))
contour_levels = np.arange(0.005, 0.1, 0.005)
contour = plt.contourf(time_contour, binsCenter, hist_normalized.T, levels=contour_levels, linestyles='none')
plt.colorbar(contour)
plt.yscale('log')
plt.ylim([1e-7, 1])

# Plotting thresholds
#plt.plot(time_contour, threshhold, 'g', linewidth=2, label='2*lower peak')
#plt.plot(time_contour, threshhold_ww, 'b', linewidth=2, label='freq. min between peaks from fit')
#plt.plot(time_contour, threshhold_ak, 'r', linewidth=2, label='freq. min between peaks in hist')

# Formatting the x-axis as time
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))
#plt.gca().xaxis.set_major_locator(mdates.HourLocator())
plt.gcf().autofmt_xdate()  # Rotation

plt.title(f'Inter-arrival Time Frequency for {time_sec.start_date}')
plt.xlabel('Time')
plt.ylabel('Inter-arrival Time [sec]')
plt.legend(loc='upper left', fontsize=6)

# Save the plot
# plt.savefig(f"{directory}/{probeName}_IntArrAnalysis_{dateString}.jpg", dpi=300)
plt.show()
plt.close()  # Close the plot to free up memory
No artists with labels found to put in legend.  Note that artists whose label start with an underscore are ignored when legend() is called with no argument.
../_images/f4f35f594d0c9140efd885392a78a61363bdd31e5bc6597053287e7b70c0308c.png
# Prepare clean copies of ParticleAutoReject for Fixed, Adaptive, Probabilistic, and Multifeature modes
# In case ds_lvl0 already has shattering flags applied, we revert them to "0" (accepted) for a fair baseline comparison
base_par = ds_lvl0["ParticleAutoReject"].copy()
base_par.values[base_par.values == cops.analysis.REJECT_CODE_SHATTERING] = "0"
base_par.values[base_par.values == cops.analysis.REJECT_CODE_REACCEPTED] = "0"

par_fixed = base_par.copy()
par_adaptive = base_par.copy()
par_probabilistic = base_par.copy()
par_multifeature = base_par.copy()

iat_fixed = ds_lvl0["InterArrivalTime"].copy()
iat_adaptive = ds_lvl0["InterArrivalTime"].copy()
iat_probabilistic = ds_lvl0["InterArrivalTime"].copy()
iat_multifeature = ds_lvl0["InterArrivalTime"].copy()
diam = ds_lvl0["D_s"] * 1e-3 # [um] -> [mm]

if "area_ratio" in ds_lvl0.variables:
    area_ratio = ds_lvl0["area_ratio"]
else:
    props = cops.analysis.calculate_particle_bulk_properties(diam, ds_lvl0["ParticleArea"], ds_lvl0["HolroydHabit"].astype(str), Pres=ds_lvl0.get("Pres"), Temp=ds_lvl0.get("Temp"))
    area_ratio = props["area_ratio"]

# Set intArrMinCount=100 to ensure adaptive mode triggers and demonstrates interval-local bimodal thresholding
cfg_fixed = cops.config.SizeDistributionConfig(intArrThreshMode="fixed")
cfg_adaptive = cops.config.SizeDistributionConfig(intArrThreshMode="adaptive", intArrAdaptiveWindowSec=1, intArrBins=35, intArrMinCount=100, intArrMaxSeconds=1.0)
cfg_probabilistic = cops.config.SizeDistributionConfig(intArrThreshMode="probabilistic", intArrProbAlphaStart=0.01, intArrProbAlphaExtend=0.05, intArrProbRollingWindowSec=5, intArrProbMinLambda=10.0)
cfg_multifeature = cops.config.SizeDistributionConfig(
    intArrThreshMode="probabilistic_multifeature",
    intArrMFScoreStart=0.75,
    intArrMFScoreExtend=0.55,
    intArrMFIatWeight=0.50,
    intArrMFDensityWeight=0.15,
    intArrMFSizeWeight=0.20,
    intArrMFFragmentWeight=0.10,
    intArrMFMorphWeight=0.05,
    intArrMFSmallDiameterMm=0.20,
    intArrMFParentRatio=2.0,
    intArrMFDensityEdgeHalfWindow=5,
    intArrMFDensityMaxSeconds=1e-3,
    intArrMFAreaRatioGood=0.6
)

actual_tas = ds_lvl0["tas"].values if "tas" in ds_lvl0.variables else 100.0
actual_diode_size = ds_lvl0.attrs.get("diode_size", 0.010) # 2DS resolution is 10 um (0.010 mm)

# Run Fixed Mode QC
par_fixed, iat_fixed, diag_fixed = cops.analysis.apply_quality_control_InterArrivalTime(
    par_fixed, iat_fixed, diam, area_ratio, ds_lvl0,
    applyIntArrThresh=1, defaultIntArrThresh=1e-5,
    reaccptShatrs=1, reaccptD=0.05, reaccptMaxIAT=1e-5,
    probe_type="2DS", tas=actual_tas, time_sec=ds_lvl0["time_sec"], diode_size=actual_diode_size,
    size_config=cfg_fixed, return_diagnostics=True
)

# Run Adaptive Mode QC
par_adaptive, iat_adaptive, diag_adaptive = cops.analysis.apply_quality_control_InterArrivalTime(
    par_adaptive, iat_adaptive, diam, area_ratio, ds_lvl0,
    applyIntArrThresh=1, defaultIntArrThresh=1e-5,
    reaccptShatrs=1, reaccptD=0.05, reaccptMaxIAT=1e-5,
    probe_type="2DS", tas=actual_tas, time_sec=ds_lvl0["time_sec"], diode_size=actual_diode_size,
    size_config=cfg_adaptive, return_diagnostics=True
)

# Run Probabilistic Mode QC
par_probabilistic, iat_probabilistic, diag_probabilistic = cops.analysis.apply_quality_control_InterArrivalTime(
    par_probabilistic, iat_probabilistic, diam, area_ratio, ds_lvl0,
    applyIntArrThresh=1, defaultIntArrThresh=1e-5,
    reaccptShatrs=1, reaccptD=0.05, reaccptMaxIAT=1e-5,
    probe_type="2DS", tas=actual_tas, time_sec=ds_lvl0["time_sec"], diode_size=actual_diode_size,
    size_config=cfg_probabilistic, return_diagnostics=True
)

# Run Multifeature Mode QC
par_multifeature, iat_multifeature, diag_multifeature = cops.analysis.apply_quality_control_InterArrivalTime(
    par_multifeature, iat_multifeature, diam, area_ratio, ds_lvl0,
    applyIntArrThresh=1, defaultIntArrThresh=1e-5,
    reaccptShatrs=1, reaccptD=0.05, reaccptMaxIAT=1e-5,
    probe_type="2DS", tas=actual_tas, time_sec=ds_lvl0["time_sec"], diode_size=actual_diode_size,
    size_config=cfg_multifeature, return_diagnostics=True
)

total_particles = len(diam)
fixed_rejected = np.sum(par_fixed.values == cops.analysis.REJECT_CODE_SHATTERING)
fixed_reaccepted = np.sum(par_fixed.values == cops.analysis.REJECT_CODE_REACCEPTED)

adaptive_rejected = np.sum(par_adaptive.values == cops.analysis.REJECT_CODE_SHATTERING)
adaptive_reaccepted = np.sum(par_adaptive.values == cops.analysis.REJECT_CODE_REACCEPTED)

probabilistic_rejected = np.sum(par_probabilistic.values == cops.analysis.REJECT_CODE_SHATTERING)
probabilistic_reaccepted = np.sum(par_probabilistic.values == cops.analysis.REJECT_CODE_REACCEPTED)

multifeature_rejected = np.sum(par_multifeature.values == cops.analysis.REJECT_CODE_SHATTERING)
multifeature_reaccepted = np.sum(par_multifeature.values == cops.analysis.REJECT_CODE_REACCEPTED)

print(f"Total Particles: {total_particles}")
print(f"\n[Fixed Mode (defaultIntArrThresh=1e-5)]")
print(f"  Rejected Particles:   {fixed_rejected} ({fixed_rejected/total_particles*100:.2f}%)")
print(f"  Reaccepted Particles: {fixed_reaccepted} ({fixed_reaccepted/total_particles*100:.2f}%)")

print(f"\n[Adaptive Mode (intArrMinCount=100)]")
print(f"  Rejected Particles:   {adaptive_rejected} ({adaptive_rejected/total_particles*100:.2f}%)")
print(f"  Reaccepted Particles: {adaptive_reaccepted} ({adaptive_reaccepted/total_particles*100:.2f}%)")

print(f"\n[Probabilistic Mode (intArrProbRollingWindowSec=5)]")
print(f"  Rejected Particles:   {probabilistic_rejected} ({probabilistic_rejected/total_particles*100:.2f}%)")
print(f"  Reaccepted Particles: {probabilistic_reaccepted} ({probabilistic_reaccepted/total_particles*100:.2f}%)")

print(f"\n[Multifeature Mode]")
print(f"  Rejected Particles:   {multifeature_rejected} ({multifeature_rejected/total_particles*100:.2f}%)")
print(f"  Reaccepted Particles: {multifeature_reaccepted} ({multifeature_reaccepted/total_particles*100:.2f}%)")

if "tau_star" in diag_adaptive:
    print(f"\n  Adaptive tau_star range: {np.min(diag_adaptive['tau_star']):.2e} s to {np.max(diag_adaptive['tau_star']):.2e} s")

print("\n--- Size-Bin Breakdown (Rejection & Reacceptance Fractions) ---")
size_bins = [(0.0, 0.05), (0.05, 0.2), (0.2, 0.3), (0.3, 0.5), (0.5, np.inf)]
for low, high in size_bins:
    mask = (diam >= low) & (diam < high)
    n_bin = int(np.sum(mask))
    if n_bin == 0: continue
    f_rej_fixed = np.sum(par_fixed.values[mask] == cops.analysis.REJECT_CODE_SHATTERING) / n_bin * 100
    f_reac_fixed = np.sum(par_fixed.values[mask] == cops.analysis.REJECT_CODE_REACCEPTED) / n_bin * 100
    f_rej_adapt = np.sum(par_adaptive.values[mask] == cops.analysis.REJECT_CODE_SHATTERING) / n_bin * 100
    f_reac_adapt = np.sum(par_adaptive.values[mask] == cops.analysis.REJECT_CODE_REACCEPTED) / n_bin * 100
    f_rej_prob = np.sum(par_probabilistic.values[mask] == cops.analysis.REJECT_CODE_SHATTERING) / n_bin * 100
    f_reac_prob = np.sum(par_probabilistic.values[mask] == cops.analysis.REJECT_CODE_REACCEPTED) / n_bin * 100
    f_rej_mf = np.sum(par_multifeature.values[mask] == cops.analysis.REJECT_CODE_SHATTERING) / n_bin * 100
    f_reac_mf = np.sum(par_multifeature.values[mask] == cops.analysis.REJECT_CODE_REACCEPTED) / n_bin * 100
    label = f"{low:.2f}-{high:.2f} mm" if high < np.inf else f">= {low:.2f} mm"
    print(f"\nBin: {label} (N={n_bin})")
    print(f"  Fixed Mode         -> Rej: {f_rej_fixed:.1f}%, Reac: {f_reac_fixed:.1f}%")
    print(f"  Adaptive Mode      -> Rej: {f_rej_adapt:.1f}%, Reac: {f_reac_adapt:.1f}%")
    print(f"  Probabilistic Mode -> Rej: {f_rej_prob:.1f}%, Reac: {f_reac_prob:.1f}%")
    print(f"  Multifeature Mode  -> Rej: {f_rej_mf:.1f}%, Reac: {f_reac_mf:.1f}%")

print("\n--- Time-Resolved Fractions (Temporal Evolution of Rejection & Reacceptance) ---")
time_arr = ds_lvl0["time_sec"].values
t_min, t_max = np.min(time_arr), np.max(time_arr)
t_slices = np.linspace(t_min, t_max, 6)
for i in range(5):
    t_low, t_high = t_slices[i], t_slices[i+1]
    mask = (time_arr >= t_low) & (time_arr <= t_high)
    n_slice = int(np.sum(mask))
    if n_slice == 0: continue
    f_rej_fixed = np.sum(par_fixed.values[mask] == cops.analysis.REJECT_CODE_SHATTERING) / n_slice * 100
    f_reac_fixed = np.sum(par_fixed.values[mask] == cops.analysis.REJECT_CODE_REACCEPTED) / n_slice * 100
    f_rej_adapt = np.sum(par_adaptive.values[mask] == cops.analysis.REJECT_CODE_SHATTERING) / n_slice * 100
    f_reac_adapt = np.sum(par_adaptive.values[mask] == cops.analysis.REJECT_CODE_REACCEPTED) / n_slice * 100
    f_rej_prob = np.sum(par_probabilistic.values[mask] == cops.analysis.REJECT_CODE_SHATTERING) / n_slice * 100
    f_reac_prob = np.sum(par_probabilistic.values[mask] == cops.analysis.REJECT_CODE_REACCEPTED) / n_slice * 100
    f_rej_mf = np.sum(par_multifeature.values[mask] == cops.analysis.REJECT_CODE_SHATTERING) / n_slice * 100
    f_reac_mf = np.sum(par_multifeature.values[mask] == cops.analysis.REJECT_CODE_REACCEPTED) / n_slice * 100
    print(f"\nTime Slice {i+1}: {t_low:.1f}s - {t_high:.1f}s (N={n_slice})")
    print(f"  Fixed Mode         -> Rej: {f_rej_fixed:.1f}%, Reac: {f_reac_fixed:.1f}%")
    print(f"  Adaptive Mode      -> Rej: {f_rej_adapt:.1f}%, Reac: {f_reac_adapt:.1f}%")
    print(f"  Probabilistic Mode -> Rej: {f_rej_prob:.1f}%, Reac: {f_reac_prob:.1f}%")
    print(f"  Multifeature Mode  -> Rej: {f_rej_mf:.1f}%, Reac: {f_reac_mf:.1f}%")

if "poisson_lambda" in diag_probabilistic:
    print("\n--- Probabilistic Rolling MLE Diagnostics ---")
    l_arr = diag_probabilistic["poisson_lambda"]
    print(f"  Estimated lambda(t) range: {np.nanmin(l_arr):.2f} to {np.nanmax(l_arr):.2f} particles/s")
    if "iat_p_natural" in diag_probabilistic:
        p_arr = diag_probabilistic["iat_p_natural"]
        print(f"  P_shatter range: {np.nanmin(p_arr):.2e} to {np.nanmax(p_arr):.2e}")

# --- Plot Adaptive, Probabilistic and Multifeature Effective tau Thresholds vs Flight Time ---
import matplotlib.pyplot as plt
import numpy as np

if "tau_star" in diag_adaptive:
    tau_star_vals = diag_adaptive["tau_star"]
    time_vals = ds_lvl0["time_sec"].values
    
    plt.figure(figsize=(10, 5))
    plt.plot(time_vals, tau_star_vals, "b-", linewidth=1.5, label=r"Adaptive Threshold ($\tau^*$)")
    plt.axhline(1e-5, color="r", linestyle="--", label=r"Fixed Default Threshold ($10^{-5}$ s)")
    
    if "poisson_lambda" in diag_probabilistic:
        lam = diag_probabilistic["poisson_lambda"]
        valid = lam > 0
        tau_start = np.full_like(lam, np.nan, dtype=np.float64)
        tau_extend = np.full_like(lam, np.nan, dtype=np.float64)
        tau_start[valid] = -np.log1p(-cfg_probabilistic.intArrProbAlphaStart) / lam[valid]
        tau_extend[valid] = -np.log1p(-cfg_probabilistic.intArrProbAlphaExtend) / lam[valid]
        
        plt.plot(time_vals, tau_start, "g-", linewidth=1.2, label=r"Probabilistic Effective $\tau_{\rm start}$ ($\alpha_{\rm start}=0.01$)")
        plt.plot(time_vals, tau_extend, "m:", linewidth=1.2, label=r"Probabilistic Effective $\tau_{\rm extend}$ ($\alpha_{\rm extend}=0.05$)")
        plt.fill_between(time_vals, tau_start, tau_extend, color="g", alpha=0.15, label="Probabilistic Hysteresis Band")
    
    plt.yscale("log")
    plt.xlabel("Flight Time (seconds)", fontsize=12)
    plt.ylabel(r"Inter-Arrival Time Threshold (s)", fontsize=12)
    plt.title(r"Temporal Evolution of Shattering Thresholds (Fixed, Adaptive, and Probabilistic Effective $\tau$)", fontsize=14)
    plt.grid(True, which="both", ls="--", alpha=0.5)
    plt.legend(fontsize=10, loc="upper right")
    plt.tight_layout()
    plt.show()
Total Particles: 7459

[Fixed Mode (defaultIntArrThresh=1e-5)]
  Rejected Particles:   146 (1.96%)
  Reaccepted Particles: 280 (3.75%)

[Adaptive Mode (intArrMinCount=100)]
  Rejected Particles:   245 (3.28%)
  Reaccepted Particles: 428 (5.74%)

[Probabilistic Mode (intArrProbRollingWindowSec=5)]
  Rejected Particles:   755 (10.12%)
  Reaccepted Particles: 150 (2.01%)

[Multifeature Mode]
  Rejected Particles:   856 (11.48%)
  Reaccepted Particles: 106 (1.42%)

  Adaptive tau_star range: 3.16e-07 s to 3.16e-05 s

--- Size-Bin Breakdown (Rejection & Reacceptance Fractions) ---

Bin: 0.00-0.05 mm (N=424)
  Fixed Mode         -> Rej: 34.4%, Reac: 0.0%
  Adaptive Mode      -> Rej: 57.1%, Reac: 0.0%
  Probabilistic Mode -> Rej: 68.2%, Reac: 0.0%
  Multifeature Mode  -> Rej: 70.8%, Reac: 0.0%

Bin: 0.05-0.20 mm (N=1791)
  Fixed Mode         -> Rej: 0.0%, Reac: 12.1%
  Adaptive Mode      -> Rej: 0.0%, Reac: 19.3%
  Probabilistic Mode -> Rej: 20.8%, Reac: 3.3%
  Multifeature Mode  -> Rej: 20.8%, Reac: 1.6%

Bin: 0.20-0.30 mm (N=1858)
  Fixed Mode         -> Rej: 0.0%, Reac: 1.8%
  Adaptive Mode      -> Rej: 0.2%, Reac: 2.1%
  Probabilistic Mode -> Rej: 2.4%, Reac: 2.2%
  Multifeature Mode  -> Rej: 3.9%, Reac: 1.8%

Bin: 0.30-0.50 mm (N=2334)
  Fixed Mode         -> Rej: 0.0%, Reac: 1.2%
  Adaptive Mode      -> Rej: 0.0%, Reac: 1.7%
  Probabilistic Mode -> Rej: 1.5%, Reac: 2.0%
  Multifeature Mode  -> Rej: 3.4%, Reac: 1.8%

Bin: >= 0.50 mm (N=1052)
  Fixed Mode         -> Rej: 0.0%, Reac: 0.2%
  Adaptive Mode      -> Rej: 0.0%, Reac: 0.4%
  Probabilistic Mode -> Rej: 1.3%, Reac: 0.4%
  Multifeature Mode  -> Rej: 3.1%, Reac: 0.4%

--- Time-Resolved Fractions (Temporal Evolution of Rejection & Reacceptance) ---

Time Slice 1: 0.0s - 11.8s (N=1478)
  Fixed Mode         -> Rej: 2.2%, Reac: 3.3%
  Adaptive Mode      -> Rej: 3.5%, Reac: 5.1%
  Probabilistic Mode -> Rej: 9.8%, Reac: 1.8%
  Multifeature Mode  -> Rej: 12.0%, Reac: 1.2%

Time Slice 2: 11.8s - 23.6s (N=1493)
  Fixed Mode         -> Rej: 1.8%, Reac: 4.7%
  Adaptive Mode      -> Rej: 2.7%, Reac: 6.9%
  Probabilistic Mode -> Rej: 11.0%, Reac: 2.0%
  Multifeature Mode  -> Rej: 11.7%, Reac: 1.5%

Time Slice 3: 23.6s - 35.4s (N=1480)
  Fixed Mode         -> Rej: 2.6%, Reac: 3.1%
  Adaptive Mode      -> Rej: 4.2%, Reac: 5.8%
  Probabilistic Mode -> Rej: 10.3%, Reac: 2.1%
  Multifeature Mode  -> Rej: 11.7%, Reac: 1.2%

Time Slice 4: 35.4s - 47.2s (N=1437)
  Fixed Mode         -> Rej: 1.5%, Reac: 3.4%
  Adaptive Mode      -> Rej: 2.6%, Reac: 4.3%
  Probabilistic Mode -> Rej: 9.3%, Reac: 1.8%
  Multifeature Mode  -> Rej: 10.5%, Reac: 1.3%

Time Slice 5: 47.2s - 59.0s (N=1571)
  Fixed Mode         -> Rej: 1.6%, Reac: 4.2%
  Adaptive Mode      -> Rej: 3.4%, Reac: 6.5%
  Probabilistic Mode -> Rej: 10.2%, Reac: 2.3%
  Multifeature Mode  -> Rej: 11.4%, Reac: 1.8%

--- Probabilistic Rolling MLE Diagnostics ---
  Estimated lambda(t) range: 109.29 to 135.19 particles/s
  P_shatter range: 1.21e-05 to 1.00e+00
../_images/0cc46debd62db9eca33b5bcd85736679da5e0177697501c9787ce535461e4aa4.png
import matplotlib.pyplot as plt
import numpy as np
import cops.analysis

# Extract Inter-Arrival Times
iat_all = ds_lvl0["InterArrivalTime"].values

# Mask out shattering artifacts
mask_fixed = par_fixed.values != cops.analysis.REJECT_CODE_SHATTERING
mask_adaptive = par_adaptive.values != cops.analysis.REJECT_CODE_SHATTERING
mask_probabilistic = par_probabilistic.values != cops.analysis.REJECT_CODE_SHATTERING
mask_multifeature = par_multifeature.values != cops.analysis.REJECT_CODE_SHATTERING

iat_fixed = iat_all[mask_fixed]
iat_adaptive = iat_all[mask_adaptive]
iat_probabilistic = iat_all[mask_probabilistic]
iat_multifeature = iat_all[mask_multifeature]

# Define logarithmic bins for the distribution
# We filter out zeros or negative IATs for log scale
iat_valid = iat_all[iat_all > 0]
if len(iat_valid) > 0:
    bins = np.logspace(np.log10(max(1e-7, np.nanmin(iat_valid))), 
                       np.log10(np.nanmax(iat_valid)), 60)
else:
    bins = np.logspace(-7, 1, 60)

plt.figure(figsize=(12, 6))

# Plot Before
plt.hist(iat_valid, bins=bins, alpha=0.4, color='grey', label='Original (Before QC)', histtype='stepfilled')

# Plot After (Fixed)
plt.hist(iat_fixed[iat_fixed > 0], bins=bins, alpha=0.8, color='red', label='After Fixed Mode', histtype='step', linewidth=1.5)

# Plot After (Adaptive)
plt.hist(iat_adaptive[iat_adaptive > 0], bins=bins, alpha=0.8, color='blue', label='After Adaptive Mode', histtype='step', linewidth=1.5)

# Plot After (Probabilistic)
plt.hist(iat_probabilistic[iat_probabilistic > 0], bins=bins, alpha=0.8, color='green', label='After Probabilistic Mode', histtype='step', linewidth=1.5)

# Plot After (Multifeature)
plt.hist(iat_multifeature[iat_multifeature > 0], bins=bins, alpha=0.8, color='purple', label='After Multifeature Mode', histtype='step', linewidth=1.5)

plt.xscale('log')
plt.xlabel('Inter-Arrival Time (s)', fontsize=12)
plt.ylabel('Count', fontsize=12)
plt.title('Inter-Arrival Time Distribution: Before vs. After Artifact Removal', fontsize=14)
plt.legend(fontsize=10)
plt.grid(True, which='both', linestyle='--', alpha=0.5)
plt.tight_layout()
plt.show()
../_images/da1ae06ea507404cd6a4f12e6da43ecb31efb693ee1118b8872329923df9b2f2.png
import matplotlib.pyplot as plt
import numpy as np

# Multifeature Diagnostic Plotting
time_vals = ds_lvl0["time_sec"].values

# 1. Plot Shatter Score vs Time
plt.figure(figsize=(12, 5))
plt.plot(time_vals, diag_multifeature["shatter_score"], color="indigo", linewidth=1.0, label="Composite Shatter Score")
plt.axhline(cfg_multifeature.intArrMFScoreStart, color="red", linestyle="--", label="Start Threshold (0.75)")
plt.axhline(cfg_multifeature.intArrMFScoreExtend, color="orange", linestyle=":", label="Extend Threshold (0.55)")
plt.xlabel("Flight Time (seconds)", fontsize=12)
plt.ylabel("Shatter Score", fontsize=12)
plt.title("Temporal Evolution of Composite Shatter Score", fontsize=14)
plt.grid(True, which="both", ls="--", alpha=0.5)
plt.legend(fontsize=10)
plt.tight_layout()
plt.show()

# 2. Plot Component Score Contributions Snippet (first 100 particles)
n_snippet = min(100, len(time_vals))
idx = np.arange(n_snippet)

plt.figure(figsize=(12, 5))
plt.bar(idx, diag_multifeature["iat_score"][:n_snippet] * cfg_multifeature.intArrMFIatWeight, label="IAT Component", alpha=0.7)
plt.bar(idx, diag_multifeature["burst_density_score"][:n_snippet] * cfg_multifeature.intArrMFDensityWeight, 
        bottom=diag_multifeature["iat_score"][:n_snippet] * cfg_multifeature.intArrMFIatWeight, label="Density Component", alpha=0.7)
plt.bar(idx, diag_multifeature["size_contrast_score"][:n_snippet] * cfg_multifeature.intArrMFSizeWeight,
        bottom=(diag_multifeature["iat_score"][:n_snippet] * cfg_multifeature.intArrMFIatWeight + 
                diag_multifeature["burst_density_score"][:n_snippet] * cfg_multifeature.intArrMFDensityWeight), label="Size Contrast Component", alpha=0.7)
plt.bar(idx, diag_multifeature["small_fragment_score"][:n_snippet] * cfg_multifeature.intArrMFFragmentWeight,
        bottom=(diag_multifeature["iat_score"][:n_snippet] * cfg_multifeature.intArrMFIatWeight + 
                diag_multifeature["burst_density_score"][:n_snippet] * cfg_multifeature.intArrMFDensityWeight +
                diag_multifeature["size_contrast_score"][:n_snippet] * cfg_multifeature.intArrMFSizeWeight), label="Small Fragment Component", alpha=0.7)
plt.bar(idx, diag_multifeature["morphology_score"][:n_snippet] * cfg_multifeature.intArrMFMorphWeight,
        bottom=(diag_multifeature["iat_score"][:n_snippet] * cfg_multifeature.intArrMFIatWeight + 
                diag_multifeature["burst_density_score"][:n_snippet] * cfg_multifeature.intArrMFDensityWeight +
                diag_multifeature["size_contrast_score"][:n_snippet] * cfg_multifeature.intArrMFSizeWeight +
                diag_multifeature["small_fragment_score"][:n_snippet] * cfg_multifeature.intArrMFFragmentWeight), label="Morphology Component", alpha=0.7)

plt.xlabel("Particle Index (First 100)", fontsize=12)
plt.ylabel("Weighted Score Contribution", fontsize=12)
plt.title("Weighted Component Contributions to Composite Shatter Score", fontsize=14)
plt.legend(fontsize=10)
plt.grid(True, linestyle="--", alpha=0.5)
plt.tight_layout()
plt.show()

# 3. Print role breakdown counts
roles = diag_multifeature["shatter_role"]
print("--- Multifeature Cluster Member Roles Breakdown ---")
print(f"  Role 0 (Natural / Unclassified):      {np.sum(roles == 0)}")
print(f"  Role 1 (Fragment Rejected):            {np.sum(roles == 1)}")
print(f"  Role 2 (Parent Reaccepted):            {np.sum(roles == 2)}")
print(f"  Role 3 (Cluster Member Preserved):     {np.sum(roles == 3)}")
../_images/ac27305b5d0839402691f186fc9b6dd3b799fb9c65c98b93fcb453cc38105f88.png ../_images/105fdd0a23b3295c56f4aaaee45fa63d422407c562aca7385c657a347456ea65.png
--- Multifeature Cluster Member Roles Breakdown ---
  Role 0 (Natural / Unclassified):      6065
  Role 1 (Fragment Rejected):            856
  Role 2 (Parent Reaccepted):            106
  Role 3 (Cluster Member Preserved):     432