goad 1.1.9

Compute the single scattering properties of particles much larger than the wavelength of light with geometric optics and aperture diffraction theory.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use clap::{Args, Parser};
use log::{trace, warn};
use nalgebra::Complex;
use std::path::PathBuf;

use crate::bins::{self};
use crate::diff::Mapping;
use crate::orientation::{Euler, EulerConvention, Orientation, Scheme};
use crate::settings::{Settings, DEFAULT_EULER_ORDER};
use crate::zones::ZoneConfig;

#[derive(Parser, Debug)]
#[command(version, about = "GOAD - Geometric Optics with Aperture Diffraction")]
#[command(author = "Harry Ballington")]
pub struct CliArgs {
    #[command(flatten)]
    pub propagation: PropagationArgs,

    #[command(flatten)]
    pub material: MaterialArgs,

    #[command(flatten)]
    pub orientation: OrientationArgs,

    #[command(flatten)]
    pub binning: BinningArgs,

    /// Random seed for reproducibility.
    #[arg(short, long)]
    pub seed: Option<u64>,

    /// Output directory for simulation results.
    #[arg(long)]
    pub dir: Option<PathBuf>,

    /// Set the field of view truncation factor for diffraction of beams.
    #[arg(long)]
    pub fov_factor: Option<f32>,

    /// Set the near to far field mapping method.
    #[arg(long, value_enum)]
    pub mapping: Option<Mapping>,

    /// Set the coherence settings for near to far field mapping
    #[arg(long, value_enum)]
    pub coherence: Option<bool>,
}

/// Beam propagation parameters
#[derive(Args, Debug)]
pub struct PropagationArgs {
    /// Wavelength in units of the geometry.
    #[arg(short, long)]
    pub w: Option<f32>,

    /// Minimum beam power threshold for propagation.
    #[arg(long)]
    pub bp: Option<f32>,

    /// Minimum area factor threshold for beam propagation.
    #[arg(long)]
    pub baf: Option<f32>,

    /// Total power cutoff fraction (0.0-1.0).
    #[arg(long)]
    pub cop: Option<f32>,

    /// Maximum recursion depth for beam tracing.
    #[arg(long)]
    pub rec: Option<i32>,

    /// Maximum allowed total internal reflections.
    #[arg(long)]
    pub tir: Option<i32>,
}

/// Material and geometry parameters
#[derive(Args, Debug)]
pub struct MaterialArgs {
    /// Path to geometry file (.obj format).
    #[arg(short, long)]
    pub geo: Option<String>,

    /// Surrounding medium refractive index.
    #[arg(long)]
    pub ri0: Option<Complex<f32>>,

    /// Particle refractive indices, space-separated.
    #[arg(short, long, value_parser, num_args = 1.., value_delimiter = ' ')]
    pub ri: Option<Vec<Complex<f32>>>,

    /// Distortion factor for the geometry.
    #[arg(long)]
    pub distortion: Option<f32>,

    /// Geometry scale factors for each axis (x, y, z).
    #[arg(long, value_parser, num_args = 1..=3, value_delimiter = ' ')]
    pub geom_scale: Option<Vec<f32>>,
}

/// Orientation parameters
#[derive(Args, Debug)]
pub struct OrientationArgs {
    /// Use uniform random orientation scheme.
    #[arg(long, group = "orientation")]
    pub uniform: Option<usize>,

    /// Use discrete orientation scheme with specified Euler angles (degrees).
    #[arg(long, value_parser = parse_euler_angles, num_args = 1.., value_delimiter = ' ', group = "orientation")]
    pub discrete: Option<Vec<Euler>>,

    /// Use Sobol quasi-random orientation scheme (faster convergence).
    #[arg(long, group = "orientation")]
    pub sobol: Option<usize>,

    /// Use Halton quasi-random orientation scheme (faster convergence).
    #[arg(long, group = "orientation")]
    pub halton: Option<usize>,

    /// Specify Euler angle convention for orientation.
    #[arg(long, value_parser = parse_euler_convention)]
    pub euler: Option<EulerConvention>,
}

/// Output binning parameters
#[derive(Args, Debug)]
pub struct BinningArgs {
    /// Use simple equal-spacing binning scheme.
    #[arg(long, num_args = 2, value_delimiter = ' ', group = "binning")]
    pub simple: Option<Vec<usize>>,

    /// Enable interval binning scheme with variable spacing.
    #[arg(long, group = "binning")]
    pub interval: bool,

    /// Theta angle bins for interval binning (degrees).
    #[arg(long, requires = "interval", num_args = 3.., value_delimiter = ' ')]
    pub theta: Option<Vec<f32>>,

    /// Phi angle bins for interval binning (degrees).
    #[arg(long, requires = "interval", num_args = 3.., value_delimiter = ' ')]
    pub phi: Option<Vec<f32>>,

    /// Path to custom binning scheme file.
    #[arg(long)]
    pub custom: Option<String>,
}

fn parse_euler_angles(s: &str) -> Result<Euler, String> {
    log::debug!("Parsing Euler angles: '{}'", s);

    let angles: Vec<&str> = s.split(',').collect();
    if angles.len() != 3 {
        return Err(format!(
            "Invalid Euler angle format: '{}'. Expected 'alpha,beta,gamma'",
            s
        ));
    }

    let alpha = angles[0]
        .parse::<f32>()
        .map_err(|_| format!("Failed to parse alpha angle: {}", angles[0]))?;
    let beta = angles[1]
        .parse::<f32>()
        .map_err(|_| format!("Failed to parse beta angle: {}", angles[1]))?;
    let gamma = angles[2]
        .parse::<f32>()
        .map_err(|_| format!("Failed to parse gamma angle: {}", angles[2]))?;

    log::debug!("Parsed Euler angles: {}, {}, {}", alpha, beta, gamma);

    Ok(Euler::new(alpha, beta, gamma))
}

fn parse_interval_specification(values: &[f32]) -> Result<(Vec<f32>, Vec<f32>), String> {
    if values.len() < 3 {
        return Err(format!(
            "Insufficient values for interval specification: need at least 3, got {}",
            values.len()
        ));
    }

    let mut positions = Vec::new();
    let mut spacings = Vec::new();

    positions.push(values[0]);

    for i in (1..values.len() - 1).step_by(2) {
        let step = values[i];
        let pos = values[i + 1];

        if step <= 0.0 {
            return Err(format!("Step size must be positive. Got {}", step));
        }

        if pos < *positions.last().unwrap() {
            return Err(format!(
                "Positions must be monotonically increasing. Got {} after {}",
                pos,
                positions.last().unwrap()
            ));
        }

        spacings.push(step);
        positions.push(pos);
    }

    if values.len() % 2 == 0 {
        return Err("Interval specification must have an odd number of values".to_string());
    }

    Ok((positions, spacings))
}

fn parse_euler_convention(s: &str) -> Result<EulerConvention, String> {
    match s.to_uppercase().as_str() {
        "XYZ" => Ok(EulerConvention::XYZ),
        "XZY" => Ok(EulerConvention::XZY),
        "YXZ" => Ok(EulerConvention::YXZ),
        "YZX" => Ok(EulerConvention::YZX),
        "ZXY" => Ok(EulerConvention::ZXY),
        "ZYX" => Ok(EulerConvention::ZYX),
        "XYX" => Ok(EulerConvention::XYX),
        "XZX" => Ok(EulerConvention::XZX),
        "YXY" => Ok(EulerConvention::YXY),
        "YZY" => Ok(EulerConvention::YZY),
        "ZXZ" => Ok(EulerConvention::ZXZ),
        "ZYZ" => Ok(EulerConvention::ZYZ),
        _ => Err(format!("Invalid Euler convention: '{}'", s)),
    }
}

pub fn update_settings_from_cli(config: &mut Settings) {
    let args = CliArgs::parse();

    if let Some(wavelength) = args.propagation.w {
        trace!("config updated from cli arg: wavelength = {}", wavelength);
        config.wavelength = wavelength;
    }
    if let Some(medium) = args.material.ri0 {
        trace!(
            "config updated from cli arg: medium_refr_index = {}",
            medium
        );
        config.medium_refr_index = medium;
    }
    if let Some(particle) = args.material.ri.clone() {
        trace!(
            "config updated from cli arg: particle_refr_index = {:?}",
            particle
        );
        config.particle_refr_index = particle;
    }
    if let Some(geo) = args.material.geo.clone() {
        trace!("config updated from cli arg: geom_name = {}", geo);
        config.geom_name = geo;
    }
    if let Some(mp) = args.propagation.bp {
        trace!("config updated from cli arg: beam_power_threshold = {}", mp);
        config.beam_power_threshold = mp;
    }
    if let Some(maf) = args.propagation.baf {
        trace!(
            "config updated from cli arg: beam_area_threshold_fac = {}",
            maf
        );
        config.beam_area_threshold_fac = maf;
    }
    if let Some(cop) = args.propagation.cop {
        trace!("config updated from cli arg: cutoff = {}", cop);
        config.cutoff = cop;
    }
    if let Some(rec) = args.propagation.rec {
        trace!("config updated from cli arg: max_rec = {}", rec);
        config.max_rec = rec;
    }
    if let Some(tir) = args.propagation.tir {
        trace!("config updated from cli arg: max_tir = {}", tir);
        config.max_tir = tir;
    }

    let euler_convention = args.orientation.euler.unwrap_or(DEFAULT_EULER_ORDER);

    if let Some(num_orients) = args.orientation.uniform {
        trace!(
            "config updated from cli arg: orientation = Uniform {{ num_orients: {} }}",
            num_orients
        );
        config.orientation = Orientation {
            scheme: Scheme::Uniform { num_orients },
            euler_convention,
        };
    } else if let Some(eulers) = args.orientation.discrete.clone() {
        trace!(
            "config updated from cli arg: orientation = Discrete {{ eulers: {:?} }}",
            eulers
        );
        config.orientation = Orientation {
            scheme: Scheme::Discrete { eulers },
            euler_convention,
        };
    } else if let Some(num_orients) = args.orientation.sobol {
        trace!(
            "config updated from cli arg: orientation = Sobol {{ num_orients: {} }}",
            num_orients
        );
        config.orientation = Orientation {
            scheme: Scheme::Sobol { num_orients },
            euler_convention,
        };
    } else if let Some(num_orients) = args.orientation.halton {
        trace!(
            "config updated from cli arg: orientation = Halton {{ num_orients: {} }}",
            num_orients
        );
        config.orientation = Orientation {
            scheme: Scheme::Halton { num_orients },
            euler_convention,
        };
    } else if let Some(convention) = args.orientation.euler {
        trace!(
            "config updated from cli arg: euler_convention = {:?}",
            convention
        );
        config.orientation.euler_convention = convention;
    }

    // CLI binning args create a single zone (replaces existing zones)
    if let Some(custom_path) = &args.binning.custom {
        trace!(
            "config updated from cli arg: zone = Custom {{ file: {} }}",
            custom_path
        );
        config.zones = vec![ZoneConfig::new(bins::Scheme::Custom {
            bins: vec![],
            file: Some(custom_path.clone()),
        })];
    } else if let Some(simple_bins) = &args.binning.simple {
        if simple_bins.len() == 2 {
            let num_theta = simple_bins[0];
            let num_phi = simple_bins[1];
            trace!(
                "config updated from cli arg: zone = Simple {{ num_theta: {}, num_phi: {} }}",
                num_theta,
                num_phi
            );
            config.zones = vec![ZoneConfig::new(bins::Scheme::new_simple(
                num_theta, num_phi,
            ))];
        } else {
            warn!("Warning: Simple binning requires exactly two values. Using default zones.");
        }
    } else if args.binning.interval {
        let mut valid_binning = true;

        let (thetas, theta_spacings) = if let Some(theta_values) = &args.binning.theta {
            match parse_interval_specification(theta_values) {
                Ok(result) => result,
                Err(err) => {
                    warn!("Error in theta specification: {}", err);
                    valid_binning = false;
                    (vec![], vec![])
                }
            }
        } else {
            warn!("Warning: Interval binning requires --theta parameter.");
            valid_binning = false;
            (vec![], vec![])
        };

        let (phis, phi_spacings) = if let Some(phi_values) = &args.binning.phi {
            match parse_interval_specification(phi_values) {
                Ok(result) => result,
                Err(err) => {
                    warn!("Error in phi specification: {}", err);
                    valid_binning = false;
                    (vec![], vec![])
                }
            }
        } else {
            warn!("Warning: Interval binning requires --phi parameter.");
            valid_binning = false;
            (vec![], vec![])
        };

        if valid_binning {
            trace!(
                "config updated from cli arg: zone = Interval {{ thetas: {:?}, phis: {:?} }}",
                thetas,
                phis
            );
            config.zones = vec![ZoneConfig::new(bins::Scheme::Interval {
                thetas,
                theta_spacings,
                phis,
                phi_spacings,
            })];
        } else {
            warn!("Warning: Could not create interval binning. Using default zones.");
        }
    }

    if let Some(dir) = args.dir.clone() {
        trace!("config updated from cli arg: directory = {:?}", dir);
        config.directory = dir;
    }

    if let Some(distortion) = args.material.distortion {
        trace!("config updated from cli arg: distortion = {}", distortion);
        config.distortion = Some(distortion);
    }

    if let Some(fov_factor) = args.fov_factor {
        trace!("config updated from cli arg: fov_factor = {}", fov_factor);
        config.fov_factor = Some(fov_factor);
    }
    if let Some(mapping) = args.mapping {
        trace!("config updated from cli arg: mapping = {:?}", mapping);
        config.mapping = mapping;
    }

    if let Some(geom_scale) = args.material.geom_scale.clone() {
        if geom_scale.len() != 3 {
            panic!("Geometry scale must have exactly 3 values (x, y, z)");
        } else {
            trace!("config updated from cli arg: geom_scale = {:?}", geom_scale);
            config.geom_scale = Some(geom_scale);
        }
    }
}