Skip to content

Commit 258dc22

Browse files
authored
Merge pull request #318 from lcpp-org/minor_code_fixes
Minor code fixes
2 parents 52dc705 + 5e2c426 commit 258dc22

11 files changed

Lines changed: 149 additions & 103 deletions

File tree

‎Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ hdf5 = {version = "0.7.1", optional = true}
2828
rcpr = { git = "https://github.com/drobnyjt/rcpr", optional = true}
2929
ndarray = {version = "0.14.0", features = ["serde"], optional = true}
3030
parry3d-f64 = {optional = true, version="0.2.0"}
31+
cached = {features=["proc_macro"], version="2.0.2"}
3132

3233
[dependencies.pyo3]
3334
version = "0.19.0"

‎src/bca.rs‎

Lines changed: 27 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -82,14 +82,6 @@ pub fn single_ion_bca<T: Geometry>(particle: particle::Particle, material: &mate
8282
//Choose impact parameters and azimuthal angles for all collisions, and determine mean free path
8383
let binary_collision_geometries = bca::determine_mfp_phi_impact_parameter(&mut particle_1, material, options, rng);
8484

85-
#[cfg(feature = "accelerated_ions")]
86-
let distance_to_target = if !material.inside(particle_1.pos.x, particle_1.pos.y, particle_1.pos.z) {
87-
let (x, y, z) = material.geometry.closest_point(particle_1.pos.x, particle_1.pos.y, particle_1.pos.z);
88-
((x - particle_1.pos.x).powi(2) + (y - particle_1.pos.y).powi(2) + (z - particle_1.pos.z).powi(2)).sqrt()
89-
} else {
90-
0.
91-
};
92-
9385
let mut total_energy_lost_to_recoils = 0.;
9486
let mut total_asymptotic_deflection = 0.;
9587
let mut normalized_distance_of_closest_approach = 0.;
@@ -159,7 +151,7 @@ pub fn single_ion_bca<T: Geometry>(particle: particle::Particle, material: &mate
159151

160152
let n = material.total_number_density(particle_2.pos.x, particle_2.pos.y, particle_2.pos.z);
161153
//We just need the lindhard screening length here, so the particular potential is not important
162-
let a: f64 = interactions::screening_length(Za, Zb, InteractionPotential::MOLIERE);
154+
let a: f64 = interactions::lindhard_screening_length_lookup(Za as u64, Zb as u64);
163155
let reduced_energy: f64 = LINDHARD_REDUCED_ENERGY_PREFACTOR*a*Mb/(Ma+Mb)/Za/Zb*E;
164156
let estimated_range_of_recoils = (reduced_energy.powf(0.3) + 0.1).powi(3)/n/a/a;
165157

@@ -181,14 +173,9 @@ pub fn single_ion_bca<T: Geometry>(particle: particle::Particle, material: &mate
181173
}
182174

183175
//Advance particle in space and track total distance traveled
184-
#[cfg(not(feature = "accelerated_ions"))]
185176
let distance_traveled = particle_1.advance(
186177
binary_collision_geometries[0].mfp, total_asymptotic_deflection);
187178

188-
#[cfg(feature = "accelerated_ions")]
189-
let distance_traveled = particle_1.advance(
190-
binary_collision_geometries[0].mfp + distance_to_target - material.geometry.get_energy_barrier_thickness(), total_asymptotic_deflection);
191-
192179
//Subtract total energy from all simultaneous collisions and electronic stopping
193180
let energy_lost_to_electronic_stopping = bca::subtract_electronic_stopping_energy(&mut particle_1, material, distance_traveled,
194181
normalized_distance_of_closest_approach, strong_collision_Z,
@@ -235,7 +222,8 @@ pub fn determine_mfp_phi_impact_parameter<T: Geometry>(particle_1: &mut particle
235222
let E: f64 = particle_1.E;
236223
let Ec: f64 = particle_1.Ec;
237224
//We just need the Lindhard screening length here, so the particular potential is not important
238-
let a: f64 = interactions::screening_length(Za, Zb, InteractionPotential::MOLIERE);
225+
let a: f64 = interactions::lindhard_screening_length_lookup(Za as u64, Zb as u64);
226+
239227
let reduced_energy: f64 = LINDHARD_REDUCED_ENERGY_PREFACTOR*a*Mb/(Ma+Mb)/Za/Zb*E;
240228

241229
//Minimum energy transfer for generating scattering event set to cutoff energy
@@ -510,8 +498,8 @@ pub fn calculate_binary_collision(particle_1: &particle::Particle, particle_2: &
510498
_ => x0*a*(theta/2.).sin()
511499
};
512500

513-
let psi = theta.sin().atan2(Ma/Mb + theta.cos());//.abs();
514-
let psi_recoil = theta.sin().atan2(1. - theta.cos());//.abs();
501+
let psi = theta.sin().atan2(Ma/Mb + theta.cos());
502+
let psi_recoil = theta.sin().atan2(1. - theta.cos());
515503
let recoil_energy = 4.*(Ma*Mb)/(Ma + Mb).powi(2)*E0*(theta/2.).sin().powi(2);
516504

517505
Ok(BinaryCollisionResult::new(theta, psi, psi_recoil, recoil_energy, asymptotic_deflection, x0))
@@ -525,7 +513,9 @@ fn scattering_integral_mw(x: f64, beta: f64, reduced_energy: f64, interaction_po
525513
}
526514

527515
/// Gauss-Legendre scattering integrand.
528-
fn scattering_function_gl(u: f64, impact_parameter: f64, r0: f64, relative_energy: f64, interaction_potential: &dyn Fn(f64) -> f64) -> Result<f64, anyhow::Error> {
516+
fn scattering_function_gl<F>(u: f64, impact_parameter: f64, r0: f64, relative_energy: f64, interaction_potential: F) -> Result<f64, anyhow::Error>
517+
where F: Fn(f64) -> f64
518+
{
529519
let result = 4.*impact_parameter*u/(r0*(1. - interaction_potential(r0/(1. - u*u))/relative_energy - impact_parameter*impact_parameter*(1. - u*u).powi(2)/r0/r0).sqrt());
530520

531521
if result.is_nan() {
@@ -537,7 +527,9 @@ fn scattering_function_gl(u: f64, impact_parameter: f64, r0: f64, relative_energ
537527
}
538528

539529
/// Gauss-Mehler scattering integrand.
540-
fn scattering_function_gm(u: f64, impact_parameter: f64, r0: f64, relative_energy: f64, interaction_potential: &dyn Fn(f64) -> f64) -> Result<f64, anyhow::Error> {
530+
fn scattering_function_gm<F>(u: f64, impact_parameter: f64, r0: f64, relative_energy: f64, interaction_potential: F) -> Result<f64, anyhow::Error>
531+
where F: Fn(f64) -> f64
532+
{
541533
let result = impact_parameter/r0/(1. - interaction_potential(r0/u)/relative_energy - (impact_parameter*u/r0).powi(2)).sqrt();
542534

543535
if result.is_nan() {
@@ -549,23 +541,27 @@ fn scattering_function_gm(u: f64, impact_parameter: f64, r0: f64, relative_energ
549541
}
550542

551543
/// Compute the scattering integral for a given relative energy, distance of closest approach `r0`, and interaction potential using a Gauss-Mehler, n-point quadrature.
552-
fn scattering_integral_gauss_mehler(impact_parameter: f64, relative_energy: f64, r0: f64, interaction_potential: &dyn Fn(f64) -> f64, n_points: usize) -> f64 {
544+
fn scattering_integral_gauss_mehler<F>(impact_parameter: f64, relative_energy: f64, r0: f64, interaction_potential: F, n_points: usize) -> f64
545+
where F: Fn(f64) -> f64 + Clone
546+
{
553547
let x: Vec<f64> = (1..=n_points).map(|i| ((2.*i as f64 - 1.)/4./n_points as f64*PI).cos()).collect();
554548
let w: Vec<f64> = (1..=n_points).map(|i| PI/n_points as f64*((2.*i as f64 - 1.)/4./n_points as f64*PI).sin()).collect();
555549

556550
PI - x.iter().zip(w)
557-
.map(|(&x, w)| w*scattering_function_gm(x, impact_parameter, r0, relative_energy, interaction_potential)
551+
.map(|(&x, w)| w*scattering_function_gm(x, impact_parameter, r0, relative_energy, interaction_potential.clone())
558552
.with_context(|| format!("Numerical error: NaN in Gauss-Mehler scattering integral at x = {} with Er = {} eV and p = {} A.", x, relative_energy/EV, impact_parameter/ANGSTROM))
559553
.unwrap()).sum::<f64>()
560554
}
561555

562556
/// Compute the scattering integral for a given relative energy, distance of closest approach `r0`, and interaction potential using a Gauss-Legendre, 5-point quadrature.
563-
fn scattering_integral_gauss_legendre(impact_parameter: f64, relative_energy: f64, r0: f64, interaction_potential: &dyn Fn(f64) -> f64) -> f64 {
557+
fn scattering_integral_gauss_legendre<F>(impact_parameter: f64, relative_energy: f64, r0: f64, interaction_potential: F) -> f64
558+
where F: Fn(f64) -> f64 + Clone
559+
{
564560
let x: Vec<f64> = [0., -0.538469, 0.538469, -0.90618, 0.90618].iter().map(|x| x/2. + 1./2.).collect();
565561
let w: Vec<f64> = [0.568889, 0.478629, 0.478629, 0.236927, 0.236927].iter().map(|w| w/2.).collect();
566562

567563
PI - x.iter().zip(w)
568-
.map(|(&x, w)| w*scattering_function_gl(x, impact_parameter, r0, relative_energy, interaction_potential)
564+
.map(|(&x, w)| w*scattering_function_gl(x, impact_parameter, r0, relative_energy, interaction_potential.clone())
569565
.with_context(|| format!("Numerical error: NaN in Gauss-Legendre scattering integral at x = {} with Er = {} eV and p = {} A.", x, relative_energy/EV, impact_parameter/ANGSTROM))
570566
.unwrap()).sum::<f64>()
571567
}
@@ -583,18 +579,6 @@ pub fn polynomial_rootfinder(Za: f64, Zb: f64, Ma: f64, Mb: f64, E0: f64, impact
583579
let coefficients = interactions::polynomial_coefficients(relative_energy, impact_parameter, interaction_potential);
584580
let roots = real_polynomial_roots(coefficients.clone(), polynom_complex_threshold).unwrap();
585581

586-
/*
587-
println!("p={}", impact_parameter/ANGSTROM);
588-
589-
for coefficient in &coefficients {
590-
println!("{}", {coefficient});
591-
}
592-
593-
for root in &roots {
594-
println!("{} A", {root});
595-
}
596-
*/
597-
598582
let max_root = roots.iter().cloned().fold(f64::NAN, f64::max);
599583

600584
let inverse_transformed_root = interactions::inverse_transform(max_root, interaction_potential);
@@ -642,8 +626,6 @@ pub fn cpr_rootfinder(Za: f64, Zb: f64, Ma: f64, Mb: f64, E0: f64, impact_parame
642626
let g = |r: f64| -> f64 {interactions::distance_of_closest_approach_function_singularity_free(r, a, Za, Zb, relative_energy, impact_parameter, interaction_potential)*
643627
interactions::scaling_function(r, impact_parameter, interaction_potential)};
644628

645-
//Using upper bound const, ~10, construct upper bound as a plateau near 0 and linear increase away from that
646-
//let upper_bound = f64::max(upper_bound_const*p, upper_bound_const*a);
647629
let upper_bound = impact_parameter + interactions::crossing_point_doca(interaction_potential);
648630

649631
let roots = match derivative_free {
@@ -683,14 +665,16 @@ pub fn newton_rootfinder(Za: f64, Zb: f64, Ma: f64, Mb: f64, E0: f64, impact_par
683665
let f = |r: f64| -> f64 {interactions::distance_of_closest_approach_function(r, a, Za, Zb, relative_energy, impact_parameter, interaction_potential)};
684666
let df = |r: f64| -> f64 {interactions::diff_distance_of_closest_approach_function(r, a, Za, Zb, relative_energy, impact_parameter, interaction_potential)};
685667

686-
//Guess for large reduced energy from Mendenhall and Weller 1991
687-
//For small energies, use pure Newton-Raphson with arbitrary guess of 1
688-
let mut x0 = beta;
689668
let mut xn: f64;
690-
if reduced_energy > 5. {
669+
670+
//Guess for large reduced energy from Mendenhall and Weller 1991
671+
//For small energies, use pure Newton-Raphson with arbitrary guess of beta
672+
let mut x0 = if reduced_energy > 5. {
691673
let inv_er_2 = 0.5/reduced_energy;
692-
x0 = inv_er_2 + (inv_er_2*inv_er_2 + beta*beta).sqrt();
693-
}
674+
inv_er_2 + (inv_er_2*inv_er_2 + beta*beta).sqrt()
675+
} else {
676+
beta
677+
};
694678

695679
//Newton-Raphson to determine distance of closest approach
696680
let mut err: f64 = tolerance + 1.;

‎src/geometry.rs‎

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ impl Geometry for Mesh0D {
5757
"NM" => NM,
5858
"M" => 1.,
5959
_ => input.length_unit.parse()
60-
.unwrap_or_else(|_| panic!("Input errror: could nor parse length unit {}. Use a valid float or one of ANGSTROM, NM, MICRON, CM, MM, M",
60+
.unwrap_or_else(|_| panic!("Input errror: could nor parse length unit {}. Use a valid float or one of ANGSTROM, NM, MICRON, CM, MM, M",
6161
&input.length_unit.as_str())),
6262
};
6363

@@ -295,7 +295,7 @@ impl Geometry for HomogeneousMesh2D {
295295
"NM" => NM,
296296
"M" => 1.,
297297
_ => input.length_unit.parse()
298-
.unwrap_or_else(|_| panic!("Input errror: could nor parse length unit {}. Use a valid float or one of ANGSTROM, NM, MICRON, CM, MM, M",
298+
.unwrap_or_else(|_| panic!("Input errror: could nor parse length unit {}. Use a valid float or one of ANGSTROM, NM, MICRON, CM, MM, M",
299299
&input.length_unit.as_str())),
300300
};
301301

@@ -353,16 +353,14 @@ impl Geometry for HomogeneousMesh2D {
353353
fn inside_energy_barrier(&self, x: f64, y: f64, z: f64) -> bool {
354354
if self.inside(x, y, z) {
355355
true
356-
} else {
357-
if let Closest::SinglePoint(p) = self.boundary.closest_point(&point!(x: x, y: y)) {
358-
let distance = ((x - p.x()).powi(2) + (y - p.y()).powi(2)).sqrt();
359-
distance < self.energy_barrier_thickness
360-
} else if let Closest::Intersection(p) = self.boundary.closest_point(&point!(x: x, y: y)) {
361-
true
362-
} else {
363-
panic!("Geometry error: closest point routine failed to find single closest point to ({}, {}, {}).", x, y, z);
364-
}
365-
}
356+
} else if let Closest::SinglePoint(p) = self.boundary.closest_point(&point!(x: x, y: y)) {
357+
let distance = ((x - p.x()).powi(2) + (y - p.y()).powi(2)).sqrt();
358+
distance < self.energy_barrier_thickness
359+
} else if let Closest::Intersection(p) = self.boundary.closest_point(&point!(x: x, y: y)) {
360+
true
361+
} else {
362+
panic!("Geometry error: closest point routine failed to find single closest point to ({}, {}, {}).", x, y, z);
363+
}
366364
}
367365
fn closest_point(&self, x: f64, y: f64, z: f64) -> (f64, f64, f64) {
368366
if let Closest::SinglePoint(p) = self.boundary.closest_point(&point!(x: x, y: y)) {
@@ -401,7 +399,7 @@ impl Mesh2D {
401399
/// Finds the cell that is nearest to (x, y).
402400
fn nearest_to(&self, x: f64, y: f64, z: f64) -> &Cell2D {
403401

404-
let mut min_distance: f64 = std::f64::MAX;
402+
let mut min_distance: f64 = f64::MAX;
405403
let mut index: usize = 0;
406404

407405
for (cell_index, cell) in self.mesh.iter().enumerate() {
@@ -760,7 +758,7 @@ impl Triangle2D {
760758

761759
/// Calculates the shortest distance from this triangle to the point (x, y).
762760
pub fn distance_to(&self, x: f64, y: f64) -> f64 {
763-
let mut distance_to = std::f64::MAX;
761+
let mut distance_to = f64::MAX;
764762

765763
for segment in &self.segments {
766764
let length_2 = (segment.2 - segment.0)*(segment.2 - segment.0) + (segment.3 - segment.1)*(segment.3 - segment.1);

‎src/interactions.rs‎

Lines changed: 56 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use super::*;
2+
use std::sync::LazyLock;
23

34
/// Analytic solutions to outermost root of the interaction potential.
45
pub fn crossing_point_doca(interaction_potential: InteractionPotential) -> f64 {
@@ -9,7 +10,6 @@ pub fn crossing_point_doca(interaction_potential: InteractionPotential) -> f64 {
910
InteractionPotential::WW => 50.*ANGSTROM,
1011
_ => 10.*ANGSTROM,
1112
}
12-
1313
}
1414

1515
fn smootherstep(x: f64, k: f64, x0: f64) -> f64 {
@@ -53,7 +53,6 @@ pub fn interaction_potential(r: f64, a: f64, Za: f64, Zb: f64, interaction_poten
5353
InteractionPotential::FOUR_EIGHT{alpha, beta} => {
5454
four_eight(r, alpha, beta)
5555
}
56-
5756
}
5857
}
5958

@@ -271,17 +270,61 @@ pub fn dphi(xi: f64, interaction_potential: InteractionPotential) -> f64 {
271270
pub fn screening_length(Za: f64, Zb: f64, interaction_potential: InteractionPotential) -> f64 {
272271
match interaction_potential {
273272
//ZBL screening length, Eckstein (4.1.8)
274-
InteractionPotential::ZBL => 0.88534*A0/(Za.powf(0.23) + Zb.powf(0.23)),
273+
InteractionPotential::ZBL => zbl_screening_length_lookup(Za as u64, Zb as u64),
275274
//Lindhard/Firsov screening length, Eckstein (4.1.5)
276-
InteractionPotential::MOLIERE | InteractionPotential::KR_C | InteractionPotential::LENZ_JENSEN | InteractionPotential::TRIDYN | InteractionPotential::WW => 0.8853*A0*(Za.sqrt() + Zb.sqrt()).powf(-2./3.),
277-
InteractionPotential::LENNARD_JONES_12_6{..} | InteractionPotential::LENNARD_JONES_65_6{..} => 0.8853*A0*(Za.sqrt() + Zb.sqrt()).powf(-2./3.),
275+
InteractionPotential::MOLIERE | InteractionPotential::KR_C | InteractionPotential::LENZ_JENSEN | InteractionPotential::TRIDYN | InteractionPotential::WW => lindhard_screening_length_lookup(Za as u64, Zb as u64),
276+
InteractionPotential::LENNARD_JONES_12_6{..} | InteractionPotential::LENNARD_JONES_65_6{..} => lindhard_screening_length_lookup(Za as u64, Zb as u64),
278277
InteractionPotential::MORSE{D, alpha, r0} => alpha,
279-
InteractionPotential::COULOMB{Za: Z1, Zb: Z2} => 0.88534*A0/(Z1.powf(0.23) + Z2.powf(0.23)),
280-
InteractionPotential::KRC_MORSE{..} => 0.8853*A0*(Za.sqrt() + Zb.sqrt()).powf(-2./3.),
281-
InteractionPotential::FOUR_EIGHT{..} =>0.8853*A0*(Za.sqrt() + Zb.sqrt()).powf(-2./3.),
278+
InteractionPotential::COULOMB{Za: Z1, Zb: Z2} => zbl_screening_length_lookup(Za as u64, Zb as u64),
279+
InteractionPotential::KRC_MORSE{..} => lindhard_screening_length_lookup(Za as u64, Zb as u64),
280+
InteractionPotential::FOUR_EIGHT{..} => lindhard_screening_length_lookup(Za as u64, Zb as u64),
282281
}
283282
}
284283

284+
// It turns out it's faster (~10% speedup) to just generate every possible screening length as a lookup table
285+
// LazyLock is a thread-safe value that is initialized whenever it is first accessed
286+
// It will block other threads while it runs, but it should run extremely quickly and only once
287+
const Z_MAX: usize = 120;
288+
static LINDHARD_SCREENING_LENGTH_TABLE: LazyLock<[f64; Z_MAX*Z_MAX]> = LazyLock::new(
289+
||
290+
std::array::from_fn(
291+
|i| {
292+
// standard 2D to 1D array indexing
293+
// I always have to look this up; copied from here
294+
// (e.g. https://stackoverflow.com/questions/5494974/convert-1d-array-index-to-2d-array-index)
295+
let Za = i / Z_MAX;
296+
let Zb = i % Z_MAX;
297+
lindhard_screening_length(Za as f64, Zb as f64)
298+
}
299+
)
300+
);
301+
static ZBL_SCREENING_LENGTH_TABLE: LazyLock<[f64; Z_MAX*Z_MAX]> = LazyLock::new(
302+
||
303+
std::array::from_fn(
304+
|i| {
305+
let Za = i / Z_MAX;
306+
let Zb = i % Z_MAX;
307+
zbl_screening_length(Za as f64, Zb as f64)
308+
}
309+
)
310+
);
311+
312+
pub fn zbl_screening_length(Za: f64, Zb: f64) -> f64{
313+
0.88534*A0/(Za.powf(0.23) + Zb.powf(0.23))
314+
}
315+
316+
pub fn lindhard_screening_length(Za: f64, Zb: f64) -> f64 {
317+
0.8853*A0*(Za.sqrt() + Zb.sqrt()).powf(-2./3.)
318+
}
319+
320+
pub fn lindhard_screening_length_lookup(Za: u64, Zb: u64) -> f64 {
321+
LINDHARD_SCREENING_LENGTH_TABLE[Za as usize * Z_MAX + Zb as usize]
322+
}
323+
324+
pub fn zbl_screening_length_lookup(Za: u64, Zb: u64) -> f64{
325+
ZBL_SCREENING_LENGTH_TABLE[Za as usize * Z_MAX + Zb as usize]
326+
}
327+
285328
/// Coefficients of inverse-polynomial interaction potentials.
286329
/// Note: these go in order of decreasing orders of r, e.g., [r^n, r^n-1, r^n-2, ... r, 1].
287330
pub fn polynomial_coefficients(relative_energy: f64, impact_parameter: f64, interaction_potential: InteractionPotential) -> Vec<f64> {
@@ -414,11 +457,11 @@ pub fn tungsten_tungsten_cubic_spline(r: f64) -> f64 {
414457

415458
} else if x <= x2 {
416459

417-
let a = [1.389653276380862E4,
418-
-3.596912431628216E4,
419-
3.739206756369099E4,
420-
-1.933748081656593E4,
421-
0.495516793802426E4,
460+
let a = [1.389653276380862E4,
461+
-3.596912431628216E4,
462+
3.739206756369099E4,
463+
-1.933748081656593E4,
464+
0.495516793802426E4,
422465
-0.050264585985867E4];
423466

424467
(a[0] + a[1]*x + a[2]*x.powi(2) + a[3]*x.powi(3) + a[4]*x.powi(4) + a[5]*x.powi(5))*EV

0 commit comments

Comments
 (0)