# utils.py
"""
Utility functions for Cloud OAP Processing Software (COPS).
Includes PSD reconstruction, combining, and moment calculations.
"""
import numpy as np
from scipy.interpolate import interp1d
[docs]
def reconstruct_psd(bin_edges_old, nD_old, bin_edges_new):
"""
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_old : array-like, shape (N+1,)
Original bin edges.
nD_old : array-like, shape (N,)
Original number concentration density n(D).
bin_edges_new : array-like, shape (M+1,)
New bin edges in the same units as bin_edges_old.
Returns:
--------
nD_new : ndarray, 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)
"""
bin_edges_old = np.asarray(bin_edges_old, dtype=float)
nD_old = np.asarray(nD_old, dtype=float)
bin_edges_new = np.asarray(bin_edges_new, dtype=float)
is_1d = nD_old.ndim == 1
if is_1d:
nD_old = nD_old[np.newaxis, :]
# --- Step 1: Build cumulative distribution at original bin edges ---
# N_cum[0] = 0, N_cum[i] = sum_{k=0}^{i-1} nD_old[k] * dD[k]
dD_old = np.diff(bin_edges_old)
N_per_bin = nD_old * dD_old
N_cum = np.zeros((nD_old.shape[0], len(bin_edges_old)))
N_cum[:, 1:] = np.cumsum(N_per_bin, axis=1)
# --- Step 2: Interpolate cumulative distribution at new bin edges ---
# Use linear interpolation; values outside the original range are
# clamped (no extrapolation).
# Old 1D support: N_cum_at_new = np.interp(bin_edges_new, bin_edges_old, N_cum)
f_interp = interp1d(
bin_edges_old,
N_cum,
axis=1,
kind='linear',
bounds_error=False,
fill_value=(0.0, N_cum[:, -1]), # (left_fill, right_fill)
assume_sorted=True
)
N_cum_at_new = f_interp(bin_edges_new)
# # Or only use numpy function
# # Find indices for interpolation using searchsorted
# # idx = np.searchsorted(bin_edges_old, bin_edges_new)
# # idx = np.clip(idx, 1, len(bin_edges_old) - 1)
#
# # x0 = bin_edges_old[idx - 1]
# # x1 = bin_edges_old[idx]
# # y0 = N_cum[:, idx - 1]
# # y1 = N_cum[:, idx]
#
# # weights = (bin_edges_new - x0) / (x1 - x0)
# # N_cum_at_new = y0 + weights * (y1 - y0)
#
# # # Handle values outside original domain (constant extrapolation)
# # left_mask = bin_edges_new < bin_edges_old[0]
# # right_mask = bin_edges_new > bin_edges_old[-1]
# # N_cum_at_new[:, left_mask] = N_cum[:, 0:1] # Which is exactly 0
# # N_cum_at_new[:, right_mask] = N_cum[:, -1:]
# --- Step 3: Difference to get N in each new bin, then divide by dD ---
dD_new = np.diff(bin_edges_new)
N_new = np.diff(N_cum_at_new, axis=1)
nD_new = np.where(dD_new > 0, N_new / dD_new, 0.0)
# Propagate NaNs if the original row contained any NaNs
nan_mask = np.isnan(nD_old).any(axis=1)
nD_new[nan_mask, :] = np.nan
if is_1d:
return nD_new[0]
return nD_new
[docs]
def combine_reconstructed_psd(sd_1, sd_2, bin_mid, overlap_min, overlap_max):
"""
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_1 : array-like, shape (N,) or (T, N)
PSD array for small particles.
sd_2 : array-like, shape (N,) or (T, N)
PSD array for large particles.
bin_mid : array-like, shape (N,)
Midpoint diameters of the bins.
overlap_min : float
Lower boundary of the overlap region.
overlap_max : float
Upper boundary of the overlap region.
Returns:
--------
sd_combined : ndarray, shape (N,) or (T, N)
Combined PSD array.
History:
--------
- 2026-07-06: Extracted to cops.utils module.
"""
sd_combined = np.full_like(sd_1, np.nan)
# Create boolean masks for the bin dimension
mask_1 = bin_mid < overlap_min
mask_2 = bin_mid > overlap_max
mask_overlap = (bin_mid >= overlap_min) & (bin_mid <= overlap_max)
if sd_1.ndim == 1:
sd_combined[mask_1] = sd_1[mask_1]
sd_combined[mask_2] = sd_2[mask_2]
with np.errstate(all='ignore'):
sd_combined[mask_overlap] = np.nanmean([sd_1[mask_overlap], sd_2[mask_overlap]], axis=0)
else:
sd_combined[:, mask_1] = sd_1[:, mask_1]
sd_combined[:, mask_2] = sd_2[:, mask_2]
with np.errstate(all='ignore'):
sd_combined[:, mask_overlap] = np.nanmean([sd_1[:, mask_overlap], sd_2[:, mask_overlap]], axis=0)
return sd_combined
[docs]
def calculate_effective_diameter(bin_edges, nD):
"""
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_edges : array-like, shape (N+1,)
1D array of bin edges.
nD : array-like, shape (N,) or (T, N)
1D or 2D array of spectral number density, n(D) = dN/dD.
Returns:
--------
Deff : float or ndarray, shape () or (T,)
The effective diameter (in the same units as bin_edges).
History:
--------
- 2026-07-06: Extracted to cops.utils module.
"""
bin_edges = np.asarray(bin_edges, dtype=float)
nD = np.asarray(nD, dtype=float)
# Calculate bin midpoints and bin widths
bin_mid = (bin_edges[:-1] + bin_edges[1:]) / 2.0
dD = np.diff(bin_edges)
# Calculate actual number of particles per bin: N = n(D) * dD
N_per_bin = nD * dD
# Calculate the 2nd and 3rd moments
# (bin_mid arrays will automatically broadcast to match 2D time series)
moment_2 = np.nansum(N_per_bin * (bin_mid ** 2), axis=-1)
moment_3 = np.nansum(N_per_bin * (bin_mid ** 3), axis=-1)
# Calculate effective diameter
# np.divide with 'where' ensures we avoid division-by-zero warnings for empty distributions
Deff = np.divide(moment_3, moment_2, out=np.full_like(moment_3, np.nan), where=(moment_2 > 0))
return Deff