Skip to main content

qualia_core_db/q42/material_coupling/
transduction.rs

1//! Cross-domain multipole & transduction coupling:
2//! 1. Photoacoustic thermoelastic transduction ($\Gamma = \frac{\beta c_s^2}{C_p}$, $p_0 = \Gamma \mu_a \Phi$, thermal & stress confinement).
3//! 2. Piezoelectric / electro-elastic coupling ($D_i = \varepsilon_{ij}^S E_j + e_{im} S_m$, $T_m = c_{mn}^E S_n - e_{km} E_k$, $k^2 < 1$ passivity).
4//! 3. Duhamel-Neumann thermo-elastic stress & coupled radar/sonar boundary scattering.
5//! 4. C02-C08 explicit EMF ($\exp(-i\omega t)$) $\leftrightarrow$ QAC ($\exp(+i\omega t)$) I/Q carrier conjugation.
6
7use std::f64::consts::PI;
8
9use super::acoustic_coupling::{
10    evaluate_planar_interface_scattering, AcousticCouplingError, CauchyStress6, ContinuumMedium,
11    InterfaceScatteringCoefficients, TensorStrain6,
12};
13use super::constitutive::{Complex64, ConstitutiveError, ConstitutiveModel};
14use super::dispersion::{evaluate_wave_propagation, DispersionError};
15
16/// Errors arising during cross-domain transduction or carrier conversion.
17#[derive(Clone, Copy, Debug, PartialEq)]
18pub enum TransductionError {
19    NonFiniteParameter,
20    InvalidPhotoacousticParameter,
21    StressConfinementViolated {
22        pulse_duration_s: f64,
23        stress_relaxation_s: f64,
24    },
25    ThermalConfinementViolated {
26        pulse_duration_s: f64,
27        thermal_diffusion_s: f64,
28    },
29    ThermodynamicEnergyBoundExceeded {
30        acoustic_energy_density_j_m3: f64,
31        absorbed_optical_energy_density_j_m3: f64,
32    },
33    InvalidPiezoelectricStiffnessOrPermittivity,
34    ElectromechanicalCouplingUnstable {
35        k_squared: f64,
36    },
37    InvalidThermoElasticParameter,
38    RawMemcpyBetweenOppositeCarrierConventionsForbidden,
39    Acoustic(AcousticCouplingError),
40    Constitutive(ConstitutiveError),
41    Dispersion(DispersionError),
42}
43
44impl From<AcousticCouplingError> for TransductionError {
45    fn from(e: AcousticCouplingError) -> Self {
46        Self::Acoustic(e)
47    }
48}
49
50impl From<ConstitutiveError> for TransductionError {
51    fn from(e: ConstitutiveError) -> Self {
52        Self::Constitutive(e)
53    }
54}
55
56impl From<DispersionError> for TransductionError {
57    fn from(e: DispersionError) -> Self {
58        Self::Dispersion(e)
59    }
60}
61
62/// Photoacoustic medium parameters in strict SI units.
63#[derive(Clone, Copy, Debug, PartialEq)]
64pub struct PhotoacousticParameters {
65    /// Optical absorption coefficient $\mu_a > 0$ in $\text{m}^{-1}$.
66    pub optical_absorption_per_m: f64,
67    /// Volumetric thermal expansion coefficient $\beta > 0$ in $\text{K}^{-1}$.
68    pub thermal_expansion_per_k: f64,
69    /// Isobaric specific heat capacity $C_p > 0$ in $\text{J}\cdot\text{kg}^{-1}\cdot\text{K}^{-1}$.
70    pub specific_heat_cp_j_per_kg_k: f64,
71    /// Mass density $\rho > 0$ in $\text{kg}\cdot\text{m}^{-3}$.
72    pub density_kg_per_m3: f64,
73    /// Acoustic speed of sound $c_s > 0$ in $\text{m}\cdot\text{s}^{-1}$.
74    pub sound_speed_m_per_s: f64,
75    /// Thermal diffusivity $D_T > 0$ in $\text{m}^2\cdot\text{s}^{-1}$.
76    pub thermal_diffusivity_m2_per_s: f64,
77    /// Characteristic heated spatial dimension $d_c > 0$ in $\text{m}$ (typically $\min(\text{beam diameter}, 1/\mu_a)$).
78    pub characteristic_length_m: f64,
79}
80
81/// Evaluated photoacoustic state and confinement diagnostics.
82#[derive(Clone, Copy, Debug, PartialEq)]
83pub struct PhotoacousticResponse {
84    /// Dimensionless Grüneisen parameter $\Gamma = \frac{\beta c_s^2}{C_p}$.
85    pub gruneisen_parameter: f64,
86    /// Initial thermoelastic pressure rise $p_0 = \Gamma \mu_a \Phi$ in $\text{Pa}$.
87    pub initial_pressure_pa: f64,
88    /// Absorbed volumetric optical energy density $q_{\text{abs}} = \mu_a \Phi$ in $\text{J}\cdot\text{m}^{-3}$.
89    pub absorbed_energy_density_j_per_m3: f64,
90    /// Initial local temperature rise $\Delta T = \frac{\mu_a \Phi}{\rho C_p}$ in $\text{K}$.
91    pub temperature_rise_k: f64,
92    /// Initial stored acoustic mechanical potential energy density $u_{\text{ac},0} = \frac{p_0^2}{2\rho c_s^2}$ in $\text{J}\cdot\text{m}^{-3}$.
93    pub acoustic_energy_density_j_per_m3: f64,
94    /// Stress confinement time $\tau_{\text{st}} = \frac{d_c}{c_s}$ in $\text{s}$.
95    pub stress_confinement_time_s: f64,
96    /// Thermal confinement time $\tau_{\text{th}} = \frac{d_c^2}{4 D_T}$ in $\text{s}$.
97    pub thermal_confinement_time_s: f64,
98}
99
100impl PhotoacousticParameters {
101    pub fn validate(&self) -> Result<(), TransductionError> {
102        let vals = [
103            self.optical_absorption_per_m,
104            self.thermal_expansion_per_k,
105            self.specific_heat_cp_j_per_kg_k,
106            self.density_kg_per_m3,
107            self.sound_speed_m_per_s,
108            self.thermal_diffusivity_m2_per_s,
109            self.characteristic_length_m,
110        ];
111        if vals.iter().any(|v| !v.is_finite()) {
112            return Err(TransductionError::NonFiniteParameter);
113        }
114        if vals.iter().any(|&v| v <= 0.0) {
115            return Err(TransductionError::InvalidPhotoacousticParameter);
116        }
117        Ok(())
118    }
119
120    /// Dimensionless Grüneisen parameter $\Gamma = \frac{\beta c_s^2}{C_p}$.
121    #[inline]
122    pub fn gruneisen_parameter(&self) -> f64 {
123        (self.thermal_expansion_per_k * self.sound_speed_m_per_s * self.sound_speed_m_per_s)
124            / self.specific_heat_cp_j_per_kg_k
125    }
126
127    /// Evaluate photoacoustic pressure generation $p_0 = \Gamma \mu_a \Phi$ from optical fluence $\Phi$ ($\text{J}\cdot\text{m}^{-2}$)
128    /// and verify both stress confinement ($\tau_p < \tau_{\text{st}}$) and thermal confinement ($\tau_p < \tau_{\text{th}}$)
129    /// as well as thermodynamic energy conservation ($u_{\text{ac},0} \le q_{\text{abs}}$).
130    pub fn evaluate_confined_excitation(
131        &self,
132        optical_fluence_j_per_m2: f64,
133        laser_pulse_duration_s: f64,
134    ) -> Result<PhotoacousticResponse, TransductionError> {
135        self.validate()?;
136        if !optical_fluence_j_per_m2.is_finite() || !laser_pulse_duration_s.is_finite() {
137            return Err(TransductionError::NonFiniteParameter);
138        }
139        if optical_fluence_j_per_m2 < 0.0 || laser_pulse_duration_s <= 0.0 {
140            return Err(TransductionError::InvalidPhotoacousticParameter);
141        }
142        let tau_st = self.characteristic_length_m / self.sound_speed_m_per_s;
143        let tau_th = (self.characteristic_length_m * self.characteristic_length_m)
144            / (4.0 * self.thermal_diffusivity_m2_per_s);
145
146        if laser_pulse_duration_s >= tau_st {
147            return Err(TransductionError::StressConfinementViolated {
148                pulse_duration_s: laser_pulse_duration_s,
149                stress_relaxation_s: tau_st,
150            });
151        }
152        if laser_pulse_duration_s >= tau_th {
153            return Err(TransductionError::ThermalConfinementViolated {
154                pulse_duration_s: laser_pulse_duration_s,
155                thermal_diffusion_s: tau_th,
156            });
157        }
158
159        let gamma = self.gruneisen_parameter();
160        let q_abs = self.optical_absorption_per_m * optical_fluence_j_per_m2;
161        let p0 = gamma * q_abs;
162        let delta_t = q_abs / (self.density_kg_per_m3 * self.specific_heat_cp_j_per_kg_k);
163        let k_bulk = self.density_kg_per_m3 * self.sound_speed_m_per_s * self.sound_speed_m_per_s;
164        let u_ac = (p0 * p0) / (2.0 * k_bulk);
165
166        if u_ac > q_abs + 1e-15 {
167            return Err(TransductionError::ThermodynamicEnergyBoundExceeded {
168                acoustic_energy_density_j_m3: u_ac,
169                absorbed_optical_energy_density_j_m3: q_abs,
170            });
171        }
172
173        Ok(PhotoacousticResponse {
174            gruneisen_parameter: gamma,
175            initial_pressure_pa: p0,
176            absorbed_energy_density_j_per_m3: q_abs,
177            temperature_rise_k: delta_t,
178            acoustic_energy_density_j_per_m3: u_ac,
179            stress_confinement_time_s: tau_st,
180            thermal_confinement_time_s: tau_th,
181        })
182    }
183}
184
185/// Piezoelectric / electro-elastic constitutive tensor model (stress-charge form in Voigt order
186/// `[xx, yy, zz, xy, yz, xz]` using engineering shear strain $S_4 = 2\varepsilon_{xy}, S_5 = 2\varepsilon_{yz}, S_6 = 2\varepsilon_{xz}$):
187/// $$D_i = \varepsilon_{ij}^S E_j + e_{im} S_m \quad (\text{C}\cdot\text{m}^{-2})$$
188/// $$T_m = c_{mn}^E S_n - e_{km} E_k \quad (\text{Pa})$$
189#[derive(Clone, Copy, Debug, PartialEq)]
190pub struct PiezoelectricConstitutiveModel {
191    /// Constant-electric-field elastic stiffness $c_{mn}^E$ ($6\times 6$ symmetric positive-definite, in $\text{Pa}$).
192    pub stiffness_c_e_pa: [[f64; 6]; 6],
193    /// Clamped (constant-strain) electric permittivity $\varepsilon_{ij}^S$ ($3\times 3$ symmetric positive-definite, in $\text{F}\cdot\text{m}^{-1}$).
194    pub permittivity_eps_s_f_per_m: [[f64; 3]; 3],
195    /// Piezoelectric stress coupling tensor $e_{im}$ ($3\times 6$, in $\text{C}\cdot\text{m}^{-2}$).
196    pub piezo_e_c_per_m2: [[f64; 6]; 3],
197}
198
199/// Coupled piezoelectric stress, electric displacement, and internal energy state.
200#[derive(Clone, Copy, Debug, PartialEq)]
201pub struct PiezoelectricState {
202    /// Cauchy stress $T_m$ (`[xx, yy, zz, xy, yz, xz]`) in $\text{Pa}$.
203    pub stress_pa: CauchyStress6,
204    /// Electric displacement vector $\mathbf{D}$ in $\text{C}\cdot\text{m}^{-2}$.
205    pub electric_displacement_c_per_m2: [f64; 3],
206    /// Mechanical elastic energy density $\frac{1}{2} S_m c_{mn}^E S_n$ in $\text{J}\cdot\text{m}^{-3}$.
207    pub mechanical_energy_j_per_m3: f64,
208    /// Clamped dielectric energy density $\frac{1}{2} E_i \varepsilon_{ij}^S E_j$ in $\text{J}\cdot\text{m}^{-3}$.
209    pub dielectric_energy_j_per_m3: f64,
210    /// Total internal electro-elastic energy density $U = \frac{1}{2}(T_m S_m + D_i E_i)$ in $\text{J}\cdot\text{m}^{-3}$.
211    pub total_internal_energy_j_per_m3: f64,
212}
213
214impl PiezoelectricConstitutiveModel {
215    /// Validate symmetry, positive diagonals, and axial electromechanical coupling factor $k_{im}^2 = \frac{e_{im}^2}{c_{mm}^E \varepsilon_{ii}^S} < 1$.
216    pub fn validate(&self) -> Result<f64, TransductionError> {
217        for r in &self.stiffness_c_e_pa {
218            if r.iter().any(|v| !v.is_finite()) {
219                return Err(TransductionError::NonFiniteParameter);
220            }
221        }
222        for r in &self.permittivity_eps_s_f_per_m {
223            if r.iter().any(|v| !v.is_finite()) {
224                return Err(TransductionError::NonFiniteParameter);
225            }
226        }
227        for r in &self.piezo_e_c_per_m2 {
228            if r.iter().any(|v| !v.is_finite()) {
229                return Err(TransductionError::NonFiniteParameter);
230            }
231        }
232
233        for m in 0..6 {
234            if self.stiffness_c_e_pa[m][m] <= 0.0 {
235                return Err(TransductionError::InvalidPiezoelectricStiffnessOrPermittivity);
236            }
237            for n in (m + 1)..6 {
238                if (self.stiffness_c_e_pa[m][n] - self.stiffness_c_e_pa[n][m]).abs() > 1e-6 {
239                    return Err(TransductionError::InvalidPiezoelectricStiffnessOrPermittivity);
240                }
241            }
242        }
243        for i in 0..3 {
244            if self.permittivity_eps_s_f_per_m[i][i] <= 0.0 {
245                return Err(TransductionError::InvalidPiezoelectricStiffnessOrPermittivity);
246            }
247            for j in (i + 1)..3 {
248                if (self.permittivity_eps_s_f_per_m[i][j] - self.permittivity_eps_s_f_per_m[j][i]).abs()
249                    > 1e-20
250                {
251                    return Err(TransductionError::InvalidPiezoelectricStiffnessOrPermittivity);
252                }
253            }
254        }
255
256        let mut max_k_sq = 0.0f64;
257        for i in 0..3 {
258            for m in 0..6 {
259                let e_im = self.piezo_e_c_per_m2[i][m];
260                let k_sq = (e_im * e_im)
261                    / (self.stiffness_c_e_pa[m][m] * self.permittivity_eps_s_f_per_m[i][i]);
262                if k_sq >= 1.0 {
263                    return Err(TransductionError::ElectromechanicalCouplingUnstable {
264                        k_squared: k_sq,
265                    });
266                }
267                max_k_sq = max_k_sq.max(k_sq);
268            }
269        }
270        Ok(max_k_sq)
271    }
272
273    /// Evaluate coupled stress $T_m$, electric displacement $D_i$, and internal energy density $U$
274    /// from tensor strain $\varepsilon_{ij}$ (converted to Voigt engineering shear $S_4 = 2\varepsilon_{xy}, S_5 = 2\varepsilon_{yz}, S_6 = 2\varepsilon_{xz}$)
275    /// and electric field $\mathbf{E}$ ($\text{V}\cdot\text{m}^{-1}$).
276    pub fn evaluate_coupled_state(
277        &self,
278        strain: &TensorStrain6,
279        electric_field_v_per_m: [f64; 3],
280    ) -> Result<PiezoelectricState, TransductionError> {
281        self.validate()?;
282        if strain.xx_yy_zz_xy_yz_xz.iter().any(|v| !v.is_finite())
283            || electric_field_v_per_m.iter().any(|v| !v.is_finite())
284        {
285            return Err(TransductionError::NonFiniteParameter);
286        }
287        // Convert tensor shear to Voigt engineering strain S_m
288        let [exx, eyy, ezz, exy, eyz, exz] = strain.xx_yy_zz_xy_yz_xz;
289        let s = [exx, eyy, ezz, 2.0 * exy, 2.0 * eyz, 2.0 * exz];
290
291        let mut t = [0.0; 6];
292        for m in 0..6 {
293            let mut sum_c = 0.0;
294            for n in 0..6 {
295                sum_c += self.stiffness_c_e_pa[m][n] * s[n];
296            }
297            let mut sum_e = 0.0;
298            for k in 0..3 {
299                sum_e += self.piezo_e_c_per_m2[k][m] * electric_field_v_per_m[k];
300            }
301            t[m] = sum_c - sum_e;
302        }
303
304        let mut d = [0.0; 3];
305        for i in 0..3 {
306            let mut sum_eps = 0.0;
307            for j in 0..3 {
308                sum_eps += self.permittivity_eps_s_f_per_m[i][j] * electric_field_v_per_m[j];
309            }
310            let mut sum_e = 0.0;
311            for m in 0..6 {
312                sum_e += self.piezo_e_c_per_m2[i][m] * s[m];
313            }
314            d[i] = sum_eps + sum_e;
315        }
316
317        let mut u_mech = 0.0;
318        for m in 0..6 {
319            for n in 0..6 {
320                u_mech += 0.5 * s[m] * self.stiffness_c_e_pa[m][n] * s[n];
321            }
322        }
323        let mut u_elec = 0.0;
324        for i in 0..3 {
325            for j in 0..3 {
326                u_elec +=
327                    0.5 * electric_field_v_per_m[i] * self.permittivity_eps_s_f_per_m[i][j] * electric_field_v_per_m[j];
328            }
329        }
330        // Verify thermodynamic identity: 0.5 * (T_m S_m + D_i E_i) == u_mech + u_elec
331        let mut u_total = 0.0;
332        for m in 0..6 {
333            u_total += 0.5 * t[m] * s[m];
334        }
335        for i in 0..3 {
336            u_total += 0.5 * d[i] * electric_field_v_per_m[i];
337        }
338
339        Ok(PiezoelectricState {
340            stress_pa: CauchyStress6 {
341                xx_yy_zz_xy_yz_xz_pa: t,
342            },
343            electric_displacement_c_per_m2: d,
344            mechanical_energy_j_per_m3: u_mech,
345            dielectric_energy_j_per_m3: u_elec,
346            total_internal_energy_j_per_m3: u_total,
347        })
348    }
349
350    /// Compute open-circuit ($D = 0$) piezoelectrically stiffened axial modulus
351    /// $c_{mm}^D = c_{mm}^E + \frac{e_{im}^2}{\varepsilon_{ii}^S}$ in $\text{Pa}$.
352    pub fn open_circuit_stiffened_modulus_pa(&self, e_axis: usize, voigt_m: usize) -> f64 {
353        let e_im = self.piezo_e_c_per_m2[e_axis][voigt_m];
354        self.stiffness_c_e_pa[voigt_m][voigt_m]
355            + (e_im * e_im) / self.permittivity_eps_s_f_per_m[e_axis][e_axis]
356    }
357}
358
359/// Evaluate Duhamel-Neumann isotropic thermo-elastic Cauchy stress:
360/// $\sigma_{ij} = \lambda \operatorname{tr}(\varepsilon)\delta_{ij} + 2\mu \varepsilon_{ij} - 3 K \alpha_L \Delta T \delta_{ij}$,
361/// where $\alpha_L$ is the linear thermal expansion coefficient ($\text{K}^{-1}$) and $\Delta T = T - T_0$ ($\text{K}$).
362pub fn evaluate_thermoelastic_stress(
363    medium: &ContinuumMedium,
364    strain: &TensorStrain6,
365    linear_thermal_expansion_per_k: f64,
366    delta_temperature_k: f64,
367) -> Result<CauchyStress6, TransductionError> {
368    medium.validate()?;
369    if !linear_thermal_expansion_per_k.is_finite()
370        || !delta_temperature_k.is_finite()
371        || strain.xx_yy_zz_xy_yz_xz.iter().any(|v| !v.is_finite())
372    {
373        return Err(TransductionError::NonFiniteParameter);
374    }
375    if linear_thermal_expansion_per_k < 0.0 {
376        return Err(TransductionError::InvalidThermoElasticParameter);
377    }
378    let mut stress = CauchyStress6::from_isotropic_strain(medium, strain);
379    let thermal_pressure_pa = 3.0 * medium.bulk_modulus_pa * linear_thermal_expansion_per_k * delta_temperature_k;
380    stress.xx_yy_zz_xy_yz_xz_pa[0] -= thermal_pressure_pa;
381    stress.xx_yy_zz_xy_yz_xz_pa[1] -= thermal_pressure_pa;
382    stress.xx_yy_zz_xy_yz_xz_pa[2] -= thermal_pressure_pa;
383    Ok(stress)
384}
385
386/// Co-located electromagnetic (radar/GPR) and acoustic (sonar/seismic) normal-incidence
387/// interface scattering summary across a shared material boundary.
388#[derive(Clone, Copy, Debug, PartialEq)]
389pub struct RadarSonarInterfaceSummary {
390    pub em_reflection_amplitude: Complex64,
391    pub em_transmission_amplitude: Complex64,
392    pub em_power_reflection: f64,
393    pub em_power_transmission: f64,
394    pub acoustic: InterfaceScatteringCoefficients,
395}
396
397/// Evaluate normal-incidence radar (EM Fresnel) and sonar (acoustic) scattering across the
398/// boundary from `(em_1, ac_1)` to `(em_2, ac_2)`.
399pub fn evaluate_radar_sonar_normal_interface(
400    em_1: &ConstitutiveModel,
401    ac_1: &ContinuumMedium,
402    em_2: &ConstitutiveModel,
403    ac_2: &ContinuumMedium,
404    em_omega_rad_s: f64,
405) -> Result<RadarSonarInterfaceSummary, TransductionError> {
406    let prop_1 = evaluate_wave_propagation(em_1, em_omega_rad_s)?;
407    let prop_2 = evaluate_wave_propagation(em_2, em_omega_rad_s)?;
408    let z1 = prop_1.complex_impedance_ohms;
409    let z2 = prop_2.complex_impedance_ohms;
410    let sum_z = z2.add(z1);
411    let r_em = z2
412        .sub(z1)
413        .div(sum_z)
414        .ok_or(TransductionError::NonFiniteParameter)?;
415    let t_em = z2
416        .scale(2.0)
417        .div(sum_z)
418        .ok_or(TransductionError::NonFiniteParameter)?;
419
420    let r_pow = r_em.norm_sq();
421    // Active power transmission for lossless/low-loss normal incidence: Re(1/Z2*) / Re(1/Z1*) |t|^2
422    let inv_z1_re = z1.re / z1.norm_sq();
423    let inv_z2_re = z2.re / z2.norm_sq();
424    let t_pow = if inv_z1_re > 0.0 {
425        (inv_z2_re / inv_z1_re) * t_em.norm_sq()
426    } else {
427        0.0
428    };
429
430    let acoustic = evaluate_planar_interface_scattering(ac_1, ac_2, 0.0)?;
431
432    Ok(RadarSonarInterfaceSummary {
433        em_reflection_amplitude: r_em,
434        em_transmission_amplitude: t_em,
435        em_power_reflection: r_pow,
436        em_power_transmission: t_pow,
437        acoustic,
438    })
439}
440
441/// Explicit I/Q complex baseband carrier convention per C02-C08:
442/// - `EmfNegativeCarrier`: $x_{\text{RF}}(t) = \operatorname{Re}\left((I + iQ)\exp(-i(2\pi f_c t + \phi_0))\right)$
443/// - `QacPositiveCarrier`: $p_{\text{RF}}(t) = \operatorname{Re}\left((I + iQ)\exp(+i(2\pi f_c t + \phi_0))\right)$
444#[derive(Clone, Copy, Debug, PartialEq, Eq)]
445pub enum IqCarrierConvention {
446    EmfNegativeCarrier,
447    QacPositiveCarrier,
448}
449
450/// Reconstruct the real physical passband waveform at elapsed time `dt_s` ($t - t_{\text{ref}}$)
451/// under the declared `IqCarrierConvention`.
452#[inline]
453pub fn reconstruct_real_passband_sample(
454    iq: Complex64,
455    carrier_hz: f64,
456    reference_phase_rad: f64,
457    dt_s: f64,
458    convention: IqCarrierConvention,
459) -> f64 {
460    let theta = 2.0 * PI * carrier_hz * dt_s + reference_phase_rad;
461    let (sin_t, cos_t) = theta.sin_cos();
462    match convention {
463        // Re((I + iQ)(cos(theta) - i sin(theta))) = I cos(theta) + Q sin(theta)
464        IqCarrierConvention::EmfNegativeCarrier => iq.re * cos_t + iq.im * sin_t,
465        // Re((I + iQ)(cos(theta) + i sin(theta))) = I cos(theta) - Q sin(theta)
466        IqCarrierConvention::QacPositiveCarrier => iq.re * cos_t - iq.im * sin_t,
467    }
468}
469
470/// Convert a complex I/Q sample from `source_convention` (with phase origin `source_phase_rad`)
471/// to `target_convention` (with phase origin `target_phase_rad`) per C02-C08 so that both
472/// reconstruct the exact same real physical passband waveform at every instant $t$.
473pub fn convert_iq_carrier_convention(
474    iq: Complex64,
475    source_convention: IqCarrierConvention,
476    source_phase_rad: f64,
477    target_convention: IqCarrierConvention,
478    target_phase_rad: f64,
479) -> Result<Complex64, TransductionError> {
480    if !iq.is_finite() || !source_phase_rad.is_finite() || !target_phase_rad.is_finite() {
481        return Err(TransductionError::NonFiniteParameter);
482    }
483    // First align to canonical zero-phase EMF representation z_0 = z_emf * exp(-i phi_src)
484    let (sin_s, cos_s) = source_phase_rad.sin_cos();
485    let z_emf_zero = match source_convention {
486        IqCarrierConvention::EmfNegativeCarrier => {
487            iq.mul(Complex64::new(cos_s, -sin_s))
488        }
489        IqCarrierConvention::QacPositiveCarrier => {
490            iq.conj().mul(Complex64::new(cos_s, -sin_s))
491        }
492    };
493    let (sin_t, cos_t) = target_phase_rad.sin_cos();
494    let out = match target_convention {
495        IqCarrierConvention::EmfNegativeCarrier => {
496            z_emf_zero.mul(Complex64::new(cos_t, sin_t))
497        }
498        IqCarrierConvention::QacPositiveCarrier => {
499            z_emf_zero.mul(Complex64::new(cos_t, sin_t)).conj()
500        }
501    };
502    Ok(out)
503}