Skip to content

Commit 1dd8209

Browse files
authored
Minor speedup improvements (#323)
* Swapped out sin, cos with sin_cos where possible * Fixed bbe call - was calling average instead of actual, ignoring input option * Fixed incorrect bulk binding model in tests. * removed unnecessary invocations of screening_length * Put DEFAULTNEWTON back to 1e-6 * replace costly heap allocations in gauss-mehler with iterator solution * Don't need lazylock for GL points, can just make them consts * Removed further unnecessary heap allocations.
1 parent 6f609c3 commit 1dd8209

8 files changed

Lines changed: 78 additions & 122 deletions

File tree

‎examples/test_rustbca.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ def main():
273273
plt.plot([50.0, 50.0], [0.0, np.max(heights)*1.1])
274274
plt.gca().set_ylim([0.0, np.max(heights)*1.1])
275275

276-
np.testing.assert_approx_equal(np.mean(x), 12.957009857301925)
276+
np.testing.assert_approx_equal(np.mean(x), 10.424570485829282)
277277

278278
number_ions = 10000
279279

@@ -343,8 +343,8 @@ def main():
343343
print(f'RustBCA R: {len(reflected[:, 0])/number_ions} Thomas R: {thomas}')
344344
print(f'Time per ion: {delta_time/number_ions} s/{ion["symbol"]}')
345345

346-
np.testing.assert_approx_equal(len(sputtered[:, 0])/number_ions, 0.0267)
347-
np.testing.assert_approx_equal(len(reflected[:, 0])/number_ions, 0.5129)
346+
np.testing.assert_approx_equal(len(sputtered[:, 0])/number_ions, 0.027)
347+
np.testing.assert_approx_equal(len(reflected[:, 0])/number_ions, 0.5155)
348348

349349
plt.figure()
350350
plt.plot(incident_index)

‎src/bca.rs‎

Lines changed: 36 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,8 @@ pub fn single_ion_bca<T: Geometry>(particle: particle::Particle, material: &mate
112112
}
113113

114114
//Energy transfer to recoil
115-
particle_2.E = binary_collision_result.recoil_energy - material.average_bulk_binding_energy(particle_2.pos.x, particle_2.pos.y, particle_2.pos.z);
115+
particle_2.E = binary_collision_result.recoil_energy - material.actual_bulk_binding_energy(species_index, particle_2.pos.x, particle_2.pos.y, particle_2.pos.z);
116+
//particle_2.E = binary_collision_result.recoil_energy - material.average_bulk_binding_energy(particle_2.pos.x, particle_2.pos.y, particle_2.pos.z);
116117
particle_2.energy_origin = particle_2.E;
117118

118119
//Accumulate energy losses and asymptotic deflections for primary particle
@@ -207,7 +208,7 @@ pub fn determine_mfp_phi_impact_parameter<T: Geometry>(particle_1: &mut particle
207208
let mut binary_collision_geometries = Vec::with_capacity(options.weak_collision_order + 1);
208209

209210
//Each weak collision gets its own aziumuthal angle in annuli around collision point
210-
for k in 0..options.weak_collision_order + 1 {
211+
for _ in 0..options.weak_collision_order + 1 {
211212
phis_azimuthal.push(2.*PI*rng.random::<f64>());
212213
}
213214

@@ -217,7 +218,6 @@ pub fn determine_mfp_phi_impact_parameter<T: Geometry>(particle_1: &mut particle
217218
let Mb: f64 = material.average_mass(x, y, z);
218219
let Za: f64 = particle_1.Z;
219220
let Zb: f64 = material.average_Z(x, y, z);
220-
let n: &Vec<f64> = material.number_densities(x, y, z);
221221
let ck: f64 = material.electronic_stopping_correction_factor(x, y, z);
222222
let E: f64 = particle_1.E;
223223
let Ec: f64 = particle_1.Ec;
@@ -346,12 +346,10 @@ pub fn choose_collision_partner<T: Geometry>(particle_1: &particle::Particle, ma
346346
let phi_azimuthal = binary_collision_geometry.phi_azimuthal;
347347

348348
//Determine cosines and sines
349-
let sinphi: f64 = phi_azimuthal.sin();
350349
let cosx: f64 = particle_1.dir.x;
351350
let cosy: f64 = particle_1.dir.y;
352351
let cosz: f64 = particle_1.dir.z;
353-
let sinx: f64 = (1. - cosx*cosx).sqrt();
354-
let cosphi: f64 = phi_azimuthal.cos();
352+
let (sinphi, cosphi) = phi_azimuthal.sin_cos();
355353

356354
let (e1, e2) = math::duff_orthonormal_basis(particle_1.dir);
357355
let x_recoil = x + mfp*cosx - impact_parameter*(e1.x*cosphi + e2.x*sinphi);
@@ -392,9 +390,7 @@ fn distance_of_closest_approach(particle_1: &particle::Particle, particle_2: &pa
392390
return doca/interactions::screening_length(Z1, Z2, interaction_potential);
393391
}
394392

395-
let root_finder = if relative_energy < interactions::energy_threshold_single_root(interaction_potential) {
396-
options.root_finder[particle_1.interaction_index][particle_2.interaction_index]
397-
} else {Rootfinder::NEWTON{max_iterations: 100, tolerance: 1E-6}};
393+
let root_finder = options.root_finder[particle_1.interaction_index][particle_2.interaction_index];
398394

399395
#[cfg(feature = "cpr_rootfinder")]
400396
match root_finder {
@@ -408,7 +404,7 @@ fn distance_of_closest_approach(particle_1: &particle::Particle, particle_2: &pa
408404
Rootfinder::NEWTON{max_iterations, tolerance} => newton_rootfinder(Za, Zb, Ma, Mb, E0, p, interaction_potential, max_iterations, tolerance)
409405
.with_context(|| format!("Numerical error: Newton rootfinder failed for {} at {} eV with p = {} A.", interaction_potential, E0/EV, p/ANGSTROM))
410406
.unwrap(),
411-
Rootfinder::DEFAULTNEWTON => newton_rootfinder(Za, Zb, Ma, Mb, E0, p, interaction_potential, 100, 1E-3)
407+
Rootfinder::DEFAULTNEWTON => newton_rootfinder(Za, Zb, Ma, Mb, E0, p, interaction_potential, 100, 1E-6)
412408
.with_context(|| format!("Numerical error: Newton rootfinder failed for {} at {} eV with p = {} A.", interaction_potential, E0/EV, p/ANGSTROM))
413409
.unwrap(),
414410
}
@@ -418,7 +414,7 @@ fn distance_of_closest_approach(particle_1: &particle::Particle, particle_2: &pa
418414
Rootfinder::NEWTON{max_iterations, tolerance} => newton_rootfinder(Za, Zb, Ma, Mb, E0, p, interaction_potential, max_iterations, tolerance)
419415
.with_context(|| format!("Numerical error: Newton rootfinder failed for {} at {} eV with p = {} A.", interaction_potential, E0/EV, p/ANGSTROM))
420416
.unwrap(),
421-
Rootfinder::DEFAULTNEWTON => newton_rootfinder(Za, Zb, Ma, Mb, E0, p, interaction_potential, 100, 1E-3)
417+
Rootfinder::DEFAULTNEWTON => newton_rootfinder(Za, Zb, Ma, Mb, E0, p, interaction_potential, 100, 1E-6)
422418
.with_context(|| format!("Numerical error: Newton rootfinder failed for {} at {} eV with p = {} A.", interaction_potential, E0/EV, p/ANGSTROM))
423419
.unwrap(),
424420
_ => panic!("Input error: unimplemented root-finder. Choose NEWTON or build with cpr_rootfinder to enable CPR and POLYNOMIAL")
@@ -429,7 +425,7 @@ fn distance_of_closest_approach(particle_1: &particle::Particle, particle_2: &pa
429425
pub fn subtract_electronic_stopping_energy<T: Geometry>(particle_1: &mut particle::Particle, material: &material::Material<T>, distance_traveled: f64,
430426
x0: f64, strong_collision_Z: f64, strong_collision_index: usize, options: &Options) -> f64 {
431427

432-
assert!(!particle_1.E.is_nan(), "Numerical error: particle energy is NaN following collision.");
428+
//assert!(!particle_1.E.is_nan(), "Numerical error: particle energy is NaN following collision.");
433429

434430
let x = particle_1.pos.x;
435431
let y = particle_1.pos.y;
@@ -442,21 +438,23 @@ pub fn subtract_electronic_stopping_energy<T: Geometry>(particle_1: &mut particl
442438
let n = material.number_densities(x, y, z);
443439

444440
let delta_energy_electronic = match options.electronic_stopping_mode {
445-
ElectronicStoppingMode::INTERPOLATED | ElectronicStoppingMode::LOW_ENERGY_NONLOCAL | ElectronicStoppingMode::INTERPOLATEDPLUS{..} => electronic_stopping_powers.iter().zip(n).map(|(se, number_density)| se*number_density).collect::<Vec<f64>>().iter().sum::<f64>()*distance_traveled,
441+
ElectronicStoppingMode::INTERPOLATED | ElectronicStoppingMode::LOW_ENERGY_NONLOCAL | ElectronicStoppingMode::INTERPOLATEDPLUS{..} => electronic_stopping_powers.iter().zip(n).map(|(se, number_density)| se*number_density).sum::<f64>()*distance_traveled,
446442
//ElectronicStoppingMode::LOW_ENERGY_NONLOCAL => electronic_stopping_powers.iter().zip(n).map(|(se, number_density)| se*number_density).collect::<Vec<f64>>().iter().sum::<f64>()*distance_traveled,
447443
ElectronicStoppingMode::LOW_ENERGY_LOCAL => oen_robinson_loss(particle_1.Z, strong_collision_Z, electronic_stopping_powers[strong_collision_index], x0, interaction_potential),
448444
ElectronicStoppingMode::LOW_ENERGY_EQUIPARTITION => {
449445

450446
let delta_energy_local = oen_robinson_loss(particle_1.Z, strong_collision_Z, electronic_stopping_powers[strong_collision_index], x0, interaction_potential);
451-
let delta_energy_nonlocal = electronic_stopping_powers.iter().zip(n).map(|(se, number_density)| se*number_density).collect::<Vec<f64>>().iter().sum::<f64>()*distance_traveled;
447+
let delta_energy_nonlocal = electronic_stopping_powers.iter().zip(n).map(|(se, number_density)| se*number_density).sum::<f64>()*distance_traveled;
452448

453449
0.5*delta_energy_local + 0.5*delta_energy_nonlocal
454450
},
455451
};
456452

457453
particle_1.E += -delta_energy_electronic;
458454
//Make sure particle energy doesn't become negative again
455+
/*
459456
assert!(!particle_1.E.is_nan(), "Numerical error: particle energy is NaN following electronic stopping.");
457+
*/
460458
if particle_1.E < 0. {
461459
particle_1.E = 0.;
462460
}
@@ -473,7 +471,6 @@ pub fn calculate_binary_collision(particle_1: &particle::Particle, particle_2: &
473471
let Ma: f64 = particle_1.m;
474472
let Mb: f64 = particle_2.m;
475473
let E0: f64 = particle_1.E;
476-
let mu: f64 = Mb/(Ma + Mb);
477474

478475
let interaction_potential = options.interaction_potential[particle_1.interaction_index][particle_2.interaction_index];
479476
let scattering_integral = options.scattering_integral[particle_1.interaction_index][particle_2.interaction_index];
@@ -488,19 +485,23 @@ pub fn calculate_binary_collision(particle_1: &particle::Particle, particle_2: &
488485
ScatteringIntegral::MAGIC => magic(Za, Zb, Ma, Mb, E0, binary_collision_geometry.impact_parameter, x0, interaction_potential),
489486
};
490487

488+
/*
491489
if theta.is_nan() {
492490
return Err(anyhow!("Numerical error: CoM deflection angle is NaN for {}. Check input parameters.", binary_collision_geometry));
493491
}
492+
*/
493+
let (sin_theta, cos_theta) = theta.sin_cos();
494+
let sin_2_theta = (theta/2.).sin();
494495

495496
//See Eckstein 1991 for details on center of mass and lab frame angles
496497
let asymptotic_deflection = match interaction_potential {
497498
InteractionPotential::COULOMB{..} => 0.,
498-
_ => x0*a*(theta/2.).sin()
499+
_ => x0*a*sin_2_theta
499500
};
500-
501-
let psi = theta.sin().atan2(Ma/Mb + theta.cos());
502-
let psi_recoil = theta.sin().atan2(1. - theta.cos());
503-
let recoil_energy = 4.*(Ma*Mb)/(Ma + Mb).powi(2)*E0*(theta/2.).sin().powi(2);
501+
502+
let psi = sin_theta.atan2(Ma/Mb + cos_theta);
503+
let psi_recoil = sin_theta.atan2(1. - cos_theta);
504+
let recoil_energy = 4.*(Ma*Mb)/(Ma + Mb).powi(2)*E0*sin_2_theta.powi(2);
504505

505506
Ok(BinaryCollisionResult::new(theta, psi, psi_recoil, recoil_energy, asymptotic_deflection, x0))
506507
}
@@ -544,23 +545,26 @@ fn scattering_function_gm<F>(u: f64, impact_parameter: f64, r0: f64, relative_en
544545
fn scattering_integral_gauss_mehler<F>(impact_parameter: f64, relative_energy: f64, r0: f64, interaction_potential: F, n_points: usize) -> f64
545546
where F: Fn(f64) -> f64 + Clone
546547
{
547-
let x: Vec<f64> = (1..=n_points).map(|i| ((2.*i as f64 - 1.)/4./n_points as f64*PI).cos()).collect();
548-
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();
549-
550-
PI - x.iter().zip(w)
551-
.map(|(&x, w)| w*scattering_function_gm(x, impact_parameter, r0, relative_energy, interaction_potential.clone())
552-
.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))
553-
.unwrap()).sum::<f64>()
548+
PI - (1..=n_points).map(
549+
|i| {
550+
let x = ((2.*i as f64 - 1.)/4./n_points as f64*PI).cos();
551+
let w = PI/n_points as f64*((2.*i as f64 - 1.)/4./n_points as f64*PI).sin();
552+
(x, w)
553+
}
554+
).map(
555+
|(x, w)| {
556+
w*scattering_function_gm(x, impact_parameter, r0, relative_energy, interaction_potential.clone())
557+
.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))
558+
.unwrap()
559+
}
560+
).sum::<f64>()
554561
}
555562

556563
/// Compute the scattering integral for a given relative energy, distance of closest approach `r0`, and interaction potential using a Gauss-Legendre, 5-point quadrature.
557564
fn scattering_integral_gauss_legendre<F>(impact_parameter: f64, relative_energy: f64, r0: f64, interaction_potential: F) -> f64
558565
where F: Fn(f64) -> f64 + Clone
559566
{
560-
let x: Vec<f64> = [0., -0.538469, 0.538469, -0.90618, 0.90618].iter().map(|x| x/2. + 1./2.).collect();
561-
let w: Vec<f64> = [0.568889, 0.478629, 0.478629, 0.236927, 0.236927].iter().map(|w| w/2.).collect();
562-
563-
PI - x.iter().zip(w)
567+
PI - &GL_X.iter().zip(GL_W.iter())
564568
.map(|(&x, w)| w*scattering_function_gl(x, impact_parameter, r0, relative_energy, interaction_potential.clone())
565569
.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))
566570
.unwrap()).sum::<f64>()
@@ -678,7 +682,7 @@ pub fn newton_rootfinder(Za: f64, Zb: f64, Ma: f64, Mb: f64, E0: f64, impact_par
678682

679683
//Newton-Raphson to determine distance of closest approach
680684
let mut err: f64 = tolerance + 1.;
681-
for k in 0..max_iterations {
685+
for _ in 0..max_iterations {
682686
xn = x0 - f(x0*a)/df(x0*a);
683687
err = (xn - x0)*(xn - x0);
684688
x0 = xn;

‎src/consts.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,4 +43,8 @@ pub const Z_MAX: usize = 120;
4343
//https://math.stackexchange.com/questions/2388887/
4444
//num elements in a triangular NxN matrix (including diag)
4545
/// LUT size; triangular matrix of size Z_MAX * Z_MAX
46-
pub const TABLE_SIZE: usize = Z_MAX*(Z_MAX + 1)/2;
46+
pub const TABLE_SIZE: usize = Z_MAX*(Z_MAX + 1)/2;
47+
/// Gauss-Legendre Points
48+
pub const GL_X: [f64; 5] = [0./2. + 1./2., -0.538469/2. + 1./2., 0.538469/2. + 1./2., -0.90618/2. + 1./2., 0.90618/2. + 1./2.];
49+
/// Gauss-Legendre Weights
50+
pub const GL_W: [f64; 5] = [0.568889/2., 0.478629/2., 0.478629/2., 0.236927/2., 0.236927/2.];

‎src/geometry.rs‎

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -481,26 +481,6 @@ impl Geometry for Mesh2D {
481481
cells.push(Cell2D::new(coordinate_set_converted, densities, concentrations, ck));
482482
}
483483

484-
/*
485-
for ((coordinate_set, densities), ck) in triangles.iter().zip(densities).zip(electronic_stopping_correction_factors) {
486-
let coordinate_set_converted = (
487-
coordinate_set.0*length_unit,
488-
coordinate_set.1*length_unit,
489-
coordinate_set.2*length_unit,
490-
coordinate_set.3*length_unit,
491-
coordinate_set.4*length_unit,
492-
coordinate_set.5*length_unit,
493-
);
494-
495-
let total_density: f64 = densities.iter().sum();
496-
let concentrations: Vec<f64> = densities.iter().map(|&density| density/total_density).collect::<Vec<f64>>();
497-
498-
cells.push(Cell2D::new(coordinate_set_converted, densities, concentrations, ck));
499-
}
500-
*/
501-
502-
503-
504484
let mut boundary_points_converted = Vec::with_capacity(material_boundary_point_indices.len());
505485
for index in material_boundary_point_indices.iter() {
506486
boundary_points_converted.push((points[*index].0*length_unit, points[*index].1*length_unit));

0 commit comments

Comments
 (0)