diff --git a/lumol-core/src/energy/computations.rs b/lumol-core/src/energy/computations.rs index 3350adb4c..2d59b1a0d 100644 --- a/lumol-core/src/energy/computations.rs +++ b/lumol-core/src/energy/computations.rs @@ -99,7 +99,7 @@ impl TableComputation { /// assert_eq!(table.energy(1.0), 0.525); /// assert_eq!(table.energy(3.0), 0.0); /// ``` - pub fn new(potential: Box, size: usize, max: f64) -> TableComputation { + pub fn new(potential: Box, size: usize, max: f64) -> Self { let delta = max / (size as f64); let mut energy_table = Vec::with_capacity(size); let mut force_table = Vec::with_capacity(size); @@ -109,12 +109,12 @@ impl TableComputation { force_table.push(potential.force(r)); } - TableComputation { - delta: delta, + Self { + delta, cutoff: max, - energy_table: energy_table, - force_table: force_table, - potential: potential, + energy_table, + force_table, + potential, } } } diff --git a/lumol-core/src/energy/functions.rs b/lumol-core/src/energy/functions.rs index 7cf3b14b2..3e1582cc7 100644 --- a/lumol-core/src/energy/functions.rs +++ b/lumol-core/src/energy/functions.rs @@ -187,9 +187,9 @@ pub struct CosineHarmonic { impl CosineHarmonic { /// Create a new `CosineHarmonic` potentials, with elastic constant of `k` /// and equilibrium value of `x0` - pub fn new(k: f64, x0: f64) -> CosineHarmonic { - CosineHarmonic { - k: k, + pub fn new(k: f64, x0: f64) -> Self { + Self { + k, cos_x0: f64::cos(x0), } } @@ -465,9 +465,9 @@ pub struct Gaussian { impl Gaussian { /// Create a new `Gaussian` potential with a depth of `a` and a width of `b` - pub fn new(a: f64, b: f64) -> Gaussian { + pub fn new(a: f64, b: f64) -> Self { assert!(b > 0.0, "\"b\" has to be positive in Gaussian potential"); - Gaussian { a: a, b: b } + Self { a, b } } } @@ -537,14 +537,14 @@ pub struct Mie { impl Mie { /// Return Mie potential. - pub fn new(sigma: f64, epsilon: f64, n: f64, m: f64) -> Mie { + pub fn new(sigma: f64, epsilon: f64, n: f64, m: f64) -> Self { assert!(m < n, "The repulsive exponent n has to be larger than the attractive exponent m"); let prefac = n / (n - m) * (n / m).powf(m / (n - m)) * epsilon; - Mie { - sigma: sigma, - n: n, - m: m, - prefac: prefac, + Self { + sigma, + n, + m, + prefac, } } } diff --git a/lumol-core/src/energy/global/ewald.rs b/lumol-core/src/energy/global/ewald.rs index 267490d11..47d806980 100644 --- a/lumol-core/src/energy/global/ewald.rs +++ b/lumol-core/src/energy/global/ewald.rs @@ -47,7 +47,7 @@ impl Ewald3DArray { let i = (range.end + offset) as usize; Ewald3DArray { data: Array3::zeros((i, j, k)), - offset: offset + offset } } @@ -250,8 +250,8 @@ pub struct Ewald { } impl Clone for Ewald { - fn clone(&self) -> Ewald { - Ewald { + fn clone(&self) -> Self { + Self { parameters: self.parameters.clone(), factors: self.factors.clone(), restriction: self.restriction, @@ -275,7 +275,7 @@ impl Ewald { /// Create an Ewald summation using the given `cutoff` radius in real space, /// and `kmax` points in k-space (Fourier space). If `alpha` is None, then /// the default value of `π / cutoff` is used. - pub fn new>>(cutoff: f64, kmax: usize, alpha: I) -> Ewald { + pub fn new>>(cutoff: f64, kmax: usize, alpha: I) -> Self { let alpha = alpha.into().unwrap_or(PI / cutoff); if cutoff < 0.0 { panic!("the cutoff can not be negative in Ewald"); @@ -286,14 +286,14 @@ impl Ewald { } let parameters = EwaldParameters { - alpha: alpha, + alpha, rc: cutoff, kmax: kmax as isize, kmax2: 0.0, }; - Ewald { - parameters: parameters, + Self { + parameters, restriction: PairRestriction::None, factors: EwaldFactorVec::new(), eikr: Ewald3DArray::zeros((0..0, 0, 0)), @@ -855,8 +855,8 @@ impl SharedEwald { /// let ewald = SharedEwald::new(Ewald::new(12.5, 10, None)); /// let boxed: Box = Box::new(ewald); /// ``` - pub fn new(ewald: Ewald) -> SharedEwald { - SharedEwald(RwLock::new(ewald)) + pub fn new(ewald: Ewald) -> Self { + Self(RwLock::new(ewald)) } /// Get read access to the underlying Ewald solver diff --git a/lumol-core/src/energy/global/wolf.rs b/lumol-core/src/energy/global/wolf.rs index 693032213..bd5d2ef7f 100644 --- a/lumol-core/src/energy/global/wolf.rs +++ b/lumol-core/src/energy/global/wolf.rs @@ -65,7 +65,7 @@ pub struct Wolf { impl Wolf { /// Create a new Wolf summation, using a real-space cutoff of `cutoff`. - pub fn new(cutoff: f64) -> Wolf { + pub fn new(cutoff: f64) -> Self { assert!(cutoff > 0.0, "Got a negative cutoff in Wolf summation"); let alpha = PI / cutoff; @@ -74,11 +74,11 @@ impl Wolf { let energy_constant = erfc(alpha_cutoff) / cutoff; let force_constant = erfc(alpha_cutoff) / (cutoff * cutoff) + FRAC_2_SQRT_PI * alpha * f64::exp(-alpha_cutoff_2) / cutoff; - Wolf { - alpha: alpha, - cutoff: cutoff, - energy_constant: energy_constant, - force_constant: force_constant, + Self { + alpha, + cutoff, + energy_constant, + force_constant, restriction: PairRestriction::None, } } diff --git a/lumol-core/src/energy/pairs.rs b/lumol-core/src/energy/pairs.rs index ce0b8ade0..7f58567b9 100644 --- a/lumol-core/src/energy/pairs.rs +++ b/lumol-core/src/energy/pairs.rs @@ -54,10 +54,10 @@ impl PairInteraction { /// // energy at and after the cutoff is zero /// assert_eq!(interaction.energy(2.0), 0.0); /// ``` - pub fn new(potential: Box, cutoff: f64) -> PairInteraction { - PairInteraction { - potential: potential, - cutoff: cutoff, + pub fn new(potential: Box, cutoff: f64) -> Self { + Self { + potential, + cutoff, restriction: PairRestriction::None, computation: PairComputation::Cutoff, tail: false, @@ -83,11 +83,11 @@ impl PairInteraction { /// // energy after the cutoff is zero /// assert_eq!(interaction.energy(2.0), 0.0); /// ``` - pub fn shifted(potential: Box, cutoff: f64) -> PairInteraction { + pub fn shifted(potential: Box, cutoff: f64) -> Self { let shift = potential.energy(cutoff); - PairInteraction { - potential: potential, - cutoff: cutoff, + Self { + potential, + cutoff, restriction: PairRestriction::None, computation: PairComputation::Shifted(shift), tail: false, diff --git a/lumol-core/src/energy/restrictions.rs b/lumol-core/src/energy/restrictions.rs index 85202ac15..969b70a0e 100644 --- a/lumol-core/src/energy/restrictions.rs +++ b/lumol-core/src/energy/restrictions.rs @@ -85,19 +85,19 @@ impl PairRestriction { pub fn information(&self, path: BondPath) -> RestrictionInfo { let are_in_same_molecule = path != BondPath::None; let excluded = match *self { - PairRestriction::None => false, - PairRestriction::InterMolecular => are_in_same_molecule, - PairRestriction::IntraMolecular => !are_in_same_molecule, - PairRestriction::Exclude12 => path == BondPath::OneBond, - PairRestriction::Exclude13 | PairRestriction::Scale14(..) => { - path == BondPath::OneBond || path == BondPath::TwoBonds + Self::None => false, + Self::InterMolecular => are_in_same_molecule, + Self::IntraMolecular => !are_in_same_molecule, + Self::Exclude12 => path == BondPath::OneBond, + Self::Exclude13 | Self::Scale14(..) => { + matches!(path, BondPath::OneBond | BondPath::TwoBonds) } - PairRestriction::Exclude14 => { - path == BondPath::OneBond || path == BondPath::TwoBonds || path == BondPath::ThreeBonds + Self::Exclude14 => { + matches!(path, BondPath::OneBond | BondPath::TwoBonds | BondPath::ThreeBonds) }, }; - let scaling = if let PairRestriction::Scale14(scaling) = *self { + let scaling = if let Self::Scale14(scaling) = *self { if path == BondPath::ThreeBonds { scaling } else { @@ -108,8 +108,8 @@ impl PairRestriction { }; RestrictionInfo { - excluded: excluded, - scaling: scaling, + excluded, + scaling, } } } diff --git a/lumol-core/src/sys/cache.rs b/lumol-core/src/sys/cache.rs index 46a7707be..11cf1d548 100644 --- a/lumol-core/src/sys/cache.rs +++ b/lumol-core/src/sys/cache.rs @@ -43,8 +43,8 @@ pub struct EnergyCache { impl EnergyCache { /// Create a new empty energy cache. - pub fn new() -> EnergyCache { - EnergyCache { + pub fn new() -> Self { + Self { pairs_cache: Array2::zeros((0, 0)), pairs: 0.0, pairs_tail: 0.0, diff --git a/lumol-core/src/sys/chfl.rs b/lumol-core/src/sys/chfl.rs index 189d9b175..5adc7d805 100644 --- a/lumol-core/src/sys/chfl.rs +++ b/lumol-core/src/sys/chfl.rs @@ -206,8 +206,8 @@ impl<'a> TrajectoryBuilder<'a> { /// .open("file.xyz") /// .unwrap(); /// ``` - pub fn new() -> TrajectoryBuilder<'a> { - TrajectoryBuilder { + pub fn new() -> Self { + Self { mode: OpenMode::Read, format: "", } @@ -227,9 +227,9 @@ impl<'a> TrajectoryBuilder<'a> { /// .open("file.mol") /// .unwrap(); /// ``` - pub fn format(self, format: &'a str) -> TrajectoryBuilder<'a> { - TrajectoryBuilder { - format: format, + pub fn format(self, format: &'a str) -> Self { + Self { + format, mode: self.mode, } } @@ -245,9 +245,9 @@ impl<'a> TrajectoryBuilder<'a> { /// .open("file.nc") /// .unwrap(); /// ``` - pub fn mode(self, mode: OpenMode) -> TrajectoryBuilder<'a> { - TrajectoryBuilder { - mode: mode, + pub fn mode(self, mode: OpenMode) -> Self { + Self { + mode, format: self.format, } } @@ -270,7 +270,7 @@ impl<'a> TrajectoryBuilder<'a> { OpenMode::Append => 'a', }; let trajectory = chemfiles::Trajectory::open_with_format(path, mode, self.format)?; - return Ok(Trajectory(trajectory)); + Ok(Trajectory(trajectory)) } } diff --git a/lumol-core/src/sys/compute.rs b/lumol-core/src/sys/compute.rs index a836c9f9a..949f6c017 100644 --- a/lumol-core/src/sys/compute.rs +++ b/lumol-core/src/sys/compute.rs @@ -689,7 +689,7 @@ mod test { // Direct computation let expected = natoms * K_BOLTZMANN * temperature / volume + virial / (3.0 * volume); let pressure = PressureAtTemperature { - temperature: temperature, + temperature, }; let pressure = pressure.compute(system); assert_ulps_eq!(pressure, expected); @@ -703,7 +703,7 @@ mod test { // Computation with an external temperature for the system let pressure = PressureAtTemperature { - temperature: temperature, + temperature, }; let pressure = pressure.compute(system); system.simulated_temperature(Some(temperature)); @@ -730,11 +730,11 @@ mod test { let system = &mut test_pairs_system(); let temperature = 550.0; let stress = StressAtTemperature { - temperature: temperature, + temperature, }; let stress = stress.compute(system); let pressure = PressureAtTemperature { - temperature: temperature, + temperature, }; let pressure = pressure.compute(system); diff --git a/lumol-core/src/sys/config/bonding.rs b/lumol-core/src/sys/config/bonding.rs index 79677f20d..ce8ec7d01 100644 --- a/lumol-core/src/sys/config/bonding.rs +++ b/lumol-core/src/sys/config/bonding.rs @@ -31,8 +31,8 @@ pub struct Bonding { impl Bonding { /// Create a new `Bonding` containing only the atom i - pub fn new(i: usize) -> Bonding { - Bonding { + pub fn new(i: usize) -> Self { + Self { bonds: HashSet::new(), angles: HashSet::new(), dihedrals: HashSet::new(), diff --git a/lumol-core/src/sys/config/cells.rs b/lumol-core/src/sys/config/cells.rs index 20daa582c..47a7e5f82 100644 --- a/lumol-core/src/sys/config/cells.rs +++ b/lumol-core/src/sys/config/cells.rs @@ -40,36 +40,36 @@ pub struct UnitCell { impl UnitCell { /// Create an infinite unit cell - pub fn infinite() -> UnitCell { - UnitCell { + pub fn infinite() -> Self { + Self { cell: Matrix3::zero(), inv: Matrix3::zero(), shape: CellShape::Infinite, } } /// Create an orthorhombic unit cell, with side lengths `a, b, c`. - pub fn ortho(a: f64, b: f64, c: f64) -> UnitCell { + pub fn ortho(a: f64, b: f64, c: f64) -> Self { assert!(a > 0.0 && b > 0.0 && c > 0.0, "Cell lengths must be positive"); let cell = Matrix3::new([[a, 0.0, 0.0], [0.0, b, 0.0], [0.0, 0.0, c]]); - UnitCell { - cell: cell, + Self { + cell, inv: cell.inverse(), shape: CellShape::Orthorhombic, } } /// Create a cubic unit cell, with side lengths `length, length, length`. - pub fn cubic(length: f64) -> UnitCell { + pub fn cubic(length: f64) -> Self { assert!(length > 0.0, "Cell lengths must be positive"); let cell = Matrix3::new([[length, 0.0, 0.0], [0.0, length, 0.0], [0.0, 0.0, length]]); - UnitCell { - cell: cell, + Self { + cell, inv: cell.inverse(), shape: CellShape::Orthorhombic, } } /// Create a triclinic unit cell, with side lengths `a, b, c` and angles /// `alpha, beta, gamma`. - pub fn triclinic(a: f64, b: f64, c: f64, alpha: f64, beta: f64, gamma: f64) -> UnitCell { + pub fn triclinic(a: f64, b: f64, c: f64, alpha: f64, beta: f64, gamma: f64) -> Self { assert!(a > 0.0 && b > 0.0 && c > 0.0, "Cell lengths must be positive"); let cos_alpha = alpha.to_radians().cos(); let cos_beta = beta.to_radians().cos(); @@ -84,8 +84,8 @@ impl UnitCell { let cell = Matrix3::new([[a, b_x, c_x], [0.0, b_y, c_y], [0.0, 0.0, c_z]]); - UnitCell { - cell: cell, + Self { + cell, inv: cell.inverse(), shape: CellShape::Triclinic, } @@ -209,11 +209,11 @@ impl UnitCell { /// Scale this unit cell by multiplying the cell matrix by `s`, and return a /// new scaled unit cell #[inline] - pub fn scale(&self, s: Matrix3) -> UnitCell { + pub fn scale(&self, s: Matrix3) -> Self { assert!(self.shape() != CellShape::Infinite, "can not scale infinite cells"); let cell = s * self.cell; - UnitCell { - cell: cell, + Self { + cell, inv: cell.inverse(), shape: self.shape, } diff --git a/lumol-core/src/sys/config/composition.rs b/lumol-core/src/sys/config/composition.rs index 7d5ca3ee8..72fd516d6 100644 --- a/lumol-core/src/sys/config/composition.rs +++ b/lumol-core/src/sys/config/composition.rs @@ -31,8 +31,8 @@ impl Composition { /// // no molecules /// assert_eq!(composition.all_molecules().count(), 0); /// ``` - pub fn new() -> Composition { - Composition { + pub fn new() -> Self { + Self { particles: Vec::new(), molecules: BTreeMap::new(), } diff --git a/lumol-core/src/sys/config/configuration.rs b/lumol-core/src/sys/config/configuration.rs index f42da2285..94b3f4586 100644 --- a/lumol-core/src/sys/config/configuration.rs +++ b/lumol-core/src/sys/config/configuration.rs @@ -25,10 +25,10 @@ pub struct Permutation { } impl Permutation { - fn new(old: usize, new: usize) -> Permutation { - Permutation { - old: old, - new: new, + fn new(old: usize, new: usize) -> Self { + Self { + old, + new, } } } @@ -52,8 +52,8 @@ pub struct Configuration { impl Configuration { /// Create a new empty `Configuration` - pub fn new() -> Configuration { - Configuration { + pub fn new() -> Self { + Self { particles: ParticleVec::new(), bondings: Vec::new(), molecule_ids: Vec::new(), @@ -78,8 +78,8 @@ impl Configuration { }; MoleculeIter { bondings: self.bondings.iter(), - ptr: ptr, - end: end, + ptr, + end, _marker: PhantomData, } } @@ -92,8 +92,8 @@ impl Configuration { }; MoleculeIterMut { bondings: self.bondings.iter(), - ptr: ptr, - end: end, + ptr, + end, _marker: PhantomData, } } diff --git a/lumol-core/src/sys/config/connect.rs b/lumol-core/src/sys/config/connect.rs index fc1f7ad1c..3ba5158d7 100644 --- a/lumol-core/src/sys/config/connect.rs +++ b/lumol-core/src/sys/config/connect.rs @@ -18,11 +18,11 @@ pub struct Bond { impl Bond { /// Create a new Bond between the particles at indexes `first` and `second` - pub fn new(first: usize, second: usize) -> Bond { + pub fn new(first: usize, second: usize) -> Self { assert_ne!(first, second); let i = min(first, second); let j = max(first, second); - Bond { i: i, j: j } + Self { i, j } } /// Get the first particle in the bond @@ -51,16 +51,16 @@ pub struct Angle { impl Angle { /// Create a new Angle between the particles at indexes `first`, `second` and `third` - pub fn new(first: usize, second: usize, third: usize) -> Angle { + pub fn new(first: usize, second: usize, third: usize) -> Self { assert_ne!(first, second); assert_ne!(first, third); assert_ne!(second, third); let i = min(first, third); let k = max(first, third); - Angle { - i: i, + Self { + i, j: second, - k: k, + k, } } @@ -96,20 +96,20 @@ pub struct Dihedral { impl Dihedral { /// Create a new Dihedral between the particles at indexes `first`, `second`, /// `third` and `fourth` - pub fn new(first: usize, second: usize, third: usize, fourth: usize) -> Dihedral { + pub fn new(first: usize, second: usize, third: usize, fourth: usize) -> Self { assert_ne!(first, second); assert_ne!(second, third); assert_ne!(third, fourth); - let (i, j, k, m) = if max(first, second) < max(third, fourth) { + let (i, j, k, m) = if first.max(second) < third.max( fourth) { (first, second, third, fourth) } else { (fourth, third, second, first) }; - Dihedral { - i: i, - j: j, - k: k, - m: m, + Self { + i, + j, + k, + m, } } @@ -159,8 +159,8 @@ bitflags! { } impl Default for BondDistances { - fn default() -> BondDistances { - BondDistances::FAR + fn default() -> Self { + Self::FAR } } diff --git a/lumol-core/src/sys/config/molecules.rs b/lumol-core/src/sys/config/molecules.rs index a9a2f7376..8e31ea850 100644 --- a/lumol-core/src/sys/config/molecules.rs +++ b/lumol-core/src/sys/config/molecules.rs @@ -19,8 +19,8 @@ pub struct MoleculeHash(u64); #[cfg(test)] impl MoleculeHash { - pub(crate) fn new(value: u64) -> MoleculeHash { - MoleculeHash(value) + pub(crate) fn new(value: u64) -> Self { + Self(value) } } @@ -73,12 +73,12 @@ pub struct MoleculeRefMut<'a> { impl Molecule { /// Create a new `Molecule` containing a single `particle` - pub fn new(particle: Particle) -> Molecule { + pub fn new(particle: Particle) -> Self { let mut particles = ParticleVec::new(); particles.push(particle); - Molecule { + Self { bonding: Bonding::new(0), - particles: particles, + particles, } } @@ -144,11 +144,11 @@ impl<'a> MoleculeRef<'a> { /// /// If the `bonding` and the `particles` do not containe the same number /// of particles. - pub fn new(bonding: &'a Bonding, particles: ParticleSlice<'a>) -> MoleculeRef<'a> { + pub fn new(bonding: &'a Bonding, particles: ParticleSlice<'a>) -> Self { assert_eq!(bonding.size(), particles.len()); - MoleculeRef { - bonding: bonding, - particles: particles, + Self { + bonding, + particles, } } @@ -182,11 +182,11 @@ impl<'a> MoleculeRefMut<'a> { /// /// If the `bonding` and the `particles` do not containe the same number /// of particles. - pub fn new(bonding: &'a Bonding, particles: ParticleSliceMut<'a>) -> MoleculeRefMut<'a> { + pub fn new(bonding: &'a Bonding, particles: ParticleSliceMut<'a>) -> Self { assert_eq!(bonding.size(), particles.len()); - MoleculeRefMut { - bonding: bonding, - particles: particles, + Self { + bonding, + particles, } } diff --git a/lumol-core/src/sys/config/particles.rs b/lumol-core/src/sys/config/particles.rs index 784752fb5..49d74e0c6 100644 --- a/lumol-core/src/sys/config/particles.rs +++ b/lumol-core/src/sys/config/particles.rs @@ -49,22 +49,22 @@ impl Particle { /// Create a new `Particle` from a `name`, setting the mass to the atomic /// mass if the `name` can be found in the periodic table. The charge, /// position, and velocity are set to 0. - pub fn new>(name: S) -> Particle { - Particle::with_position(name, Vector3D::zero()) + pub fn new>(name: S) -> Self { + Self::with_position(name, Vector3D::zero()) } /// Create a new `Particle` from a `name` and a `position`, setting the /// mass to the atomic mass if the `name` can be found in the periodic /// table. The charge and velocity are set to 0. - pub fn with_position>(name: S, position: Vector3D) -> Particle { + pub fn with_position>(name: S, position: Vector3D) -> Self { let name = name.into(); let mass = get_atomic_mass(&name).unwrap_or(0.0); - Particle { - name: name, - mass: mass, + Self { + name, + mass, charge: 0.0, kind: ParticleKind::invalid(), - position: position, + position, velocity: Vector3D::zero(), } } diff --git a/lumol-core/src/sys/energy.rs b/lumol-core/src/sys/energy.rs index 862004c3e..c9e37f600 100644 --- a/lumol-core/src/sys/energy.rs +++ b/lumol-core/src/sys/energy.rs @@ -20,8 +20,8 @@ pub struct EnergyEvaluator<'a> { impl<'a> EnergyEvaluator<'a> { /// Create a new `EnergyEvaluator` acting on the given `system`. - pub fn new(system: &'a System) -> EnergyEvaluator<'a> { - EnergyEvaluator { system: system } + pub fn new(system: &'a System) -> Self { + Self { system } } } @@ -55,7 +55,7 @@ impl<'a> EnergyEvaluator<'a> { } local_energy }); - return energies.sum(); + energies.sum() } /// Compute the energy due to long range corrections for the pairs diff --git a/lumol-core/src/sys/interactions.rs b/lumol-core/src/sys/interactions.rs index 958c54c4d..4951608cb 100644 --- a/lumol-core/src/sys/interactions.rs +++ b/lumol-core/src/sys/interactions.rs @@ -78,8 +78,8 @@ pub struct Interactions { impl Interactions { /// Create a new empty `Interactions` - pub fn new() -> Interactions { - Interactions { + pub fn new() -> Self { + Self { coulomb: None, globals: Vec::new(), pairs: BTreeMap::new(), diff --git a/lumol-core/src/sys/system.rs b/lumol-core/src/sys/system.rs index 02fe979fb..54ca3949b 100644 --- a/lumol-core/src/sys/system.rs +++ b/lumol-core/src/sys/system.rs @@ -54,21 +54,21 @@ pub struct System { impl System { /// Create a new empty `System` - pub fn new() -> System { - System::with_configuration(Configuration::new()) + pub fn new() -> Self { + Self::with_configuration(Configuration::new()) } /// Create an empty system with a specific unit cell - pub fn with_cell(cell: UnitCell) -> System { + pub fn with_cell(cell: UnitCell) -> Self { let mut configuration = Configuration::new(); configuration.cell = cell; - System::with_configuration(configuration) + Self::with_configuration(configuration) } /// Create a system with the specified `configuration`, and no interactions. - fn with_configuration(configuration: Configuration) -> System { - System { - configuration: configuration, + fn with_configuration(configuration: Configuration) -> Self { + Self { + configuration, interactions: Interactions::new(), step: 0, external_temperature: None, @@ -293,7 +293,7 @@ impl System { match self.external_temperature { Some(temperature) => { PressureAtTemperature { - temperature: temperature, + temperature, }.compute(self) } None => Pressure.compute(self), @@ -305,7 +305,7 @@ impl System { match self.external_temperature { Some(temperature) => { StressAtTemperature { - temperature: temperature, + temperature, }.compute(self) } None => Stress.compute(self), diff --git a/lumol-core/src/types/matrix.rs b/lumol-core/src/types/matrix.rs index 54d1517ba..b1dafaf0b 100644 --- a/lumol-core/src/types/matrix.rs +++ b/lumol-core/src/types/matrix.rs @@ -84,8 +84,8 @@ impl Matrix3 { /// ]); /// assert_eq!(matrix[0][2], 3.0); /// ``` - pub fn new(data: [[f64; 3]; 3]) -> Matrix3 { - Matrix3(data) + pub fn new(data: [[f64; 3]; 3]) -> Self { + Self(data) } /// Create a new `Matrix3` with components set to `0` @@ -102,8 +102,8 @@ impl Matrix3 { /// } /// } /// ``` - pub fn zero() -> Matrix3 { - ::zero() + pub fn zero() -> Self { + ::zero() } /// Create a new `Vector3D` with components all components set to `0`, @@ -125,8 +125,8 @@ impl Matrix3 { /// } /// } /// ``` - pub fn one() -> Matrix3 { - ::one() + pub fn one() -> Self { + ::one() } /// Returns rotation matrix given a rotation angle and an axis. @@ -209,11 +209,11 @@ impl Matrix3 { /// /// If the matrix is not invertible, *i.e.* if the matrix determinant /// equals zero. - pub fn inverse(&self) -> Matrix3 { + pub fn inverse(&self) -> Self { let determinant = self.determinant(); assert!(determinant.abs() > 1e-30, "The matrix is not invertible!"); let inverse_determinant = 1.0 / determinant; - let mut res = Matrix3::zero(); + let mut res = Self::zero(); res[0][0] = (self[1][1] * self[2][2] - self[2][1] * self[1][2]) * inverse_determinant; res[0][1] = (self[0][2] * self[2][1] - self[0][1] * self[2][2]) * inverse_determinant; res[0][2] = (self[0][1] * self[1][2] - self[0][2] * self[1][1]) * inverse_determinant; @@ -223,7 +223,7 @@ impl Matrix3 { res[2][0] = (self[1][0] * self[2][1] - self[2][0] * self[1][1]) * inverse_determinant; res[2][1] = (self[2][0] * self[0][1] - self[0][0] * self[2][1]) * inverse_determinant; res[2][2] = (self[0][0] * self[1][1] - self[1][0] * self[0][1]) * inverse_determinant; - return res; + res } /// Computes the [determinant][Wiki] of a matrix @@ -268,8 +268,8 @@ impl Matrix3 { /// /// assert_eq!(matrix.transposed(), transposed); /// ``` - pub fn transposed(&self) -> Matrix3 { - Matrix3::new([ + pub fn transposed(&self) -> Self { + Self::new([ [self[0][0], self[1][0], self[2][0]], [self[0][1], self[1][1], self[2][1]], [self[0][2], self[1][2], self[2][2]], diff --git a/lumol-core/src/types/vectors.rs b/lumol-core/src/types/vectors.rs index 4f9819356..9eaf974ea 100644 --- a/lumol-core/src/types/vectors.rs +++ b/lumol-core/src/types/vectors.rs @@ -71,8 +71,8 @@ impl Vector3D { /// assert_eq!(vector[1], 0.0); /// assert_eq!(vector[2], -42.0); /// ``` - pub fn new(x: f64, y: f64, z: f64) -> Vector3D { - Vector3D([x, y, z]) + pub fn new(x: f64, y: f64, z: f64) -> Self { + Self([x, y, z]) } /// Create a new `Vector3D` with components `0`, `0`, `0` @@ -86,8 +86,8 @@ impl Vector3D { /// assert_eq!(vector[1], 0.0); /// assert_eq!(vector[2], 0.0); /// ``` - pub fn zero() -> Vector3D { - ::zero() + pub fn zero() -> Self { + ::zero() } /// Return the squared euclidean norm of a `Vector3D` diff --git a/lumol-core/src/units.rs b/lumol-core/src/units.rs index fc56b40d5..d16438ed5 100644 --- a/lumol-core/src/units.rs +++ b/lumol-core/src/units.rs @@ -117,11 +117,11 @@ impl From for ParseError { impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - ParseError::Power(ref err) => err.fmt(f), - ParseError::Value(ref err) => err.fmt(f), - ParseError::ParenthesesMismatch => write!(f, "Parentheses are not equilibrated."), - ParseError::NotFound { ref unit } => write!(f, "Unit '{unit}' not found."), - ParseError::MalformedExpr(ref err) => write!(f, "Malformed expression: {err}"), + Self::Power(ref err) => err.fmt(f), + Self::Value(ref err) => err.fmt(f), + Self::ParenthesesMismatch => write!(f, "Parentheses are not equilibrated."), + Self::NotFound { ref unit } => write!(f, "Unit '{unit}' not found."), + Self::MalformedExpr(ref err) => write!(f, "Malformed expression: {err}"), } } } @@ -129,11 +129,11 @@ impl fmt::Display for ParseError { impl Error for ParseError { fn source(&self) -> Option<&(dyn Error + 'static)> { match *self { - ParseError::Power(ref err) => Some(err), - ParseError::Value(ref err) => Some(err), - ParseError::ParenthesesMismatch | - ParseError::NotFound { .. } | - ParseError::MalformedExpr(..) => None, + Self::Power(ref err) => Some(err), + Self::Value(ref err) => Some(err), + Self::ParenthesesMismatch | + Self::NotFound { .. } | + Self::MalformedExpr(..) => None, } } } @@ -159,22 +159,22 @@ impl Token { /// What is the precedence of a specific token fn precedence(&self) -> usize { match *self { - Token::LParen | Token::RParen => 0, - Token::Div | Token::Mul => 10, - Token::Pow => 20, - Token::Value(..) => unreachable!("invalid call to units::Token::precedence for values"), + Self::LParen | Self::RParen => 0, + Self::Div | Self::Mul => 10, + Self::Pow => 20, + Self::Value(..) => unreachable!("invalid call to units::Token::precedence for values"), } } /// Get the string used to build this token in tokenize fn as_str(&self) -> &str { match *self { - Token::LParen => "(", - Token::RParen => ")", - Token::Div => "/", - Token::Mul => "*", - Token::Pow => "^", - Token::Value(ref value) => value, + Self::LParen => "(", + Self::RParen => ")", + Self::Div => "/", + Self::Mul => "*", + Self::Pow => "^", + Self::Value(ref value) => value, } } } @@ -278,15 +278,15 @@ impl UnitExpr { /// Recursively evaluate an unit expression fn eval(&self) -> f64 { match *self { - UnitExpr::Val(v) => v, - UnitExpr::Mul(ref lhs, ref rhs) => lhs.eval() * rhs.eval(), - UnitExpr::Div(ref lhs, ref rhs) => lhs.eval() / rhs.eval(), - UnitExpr::Pow(ref expr, pow) => expr.eval().powi(pow), + Self::Val(v) => v, + Self::Mul(ref lhs, ref rhs) => lhs.eval() * rhs.eval(), + Self::Div(ref lhs, ref rhs) => lhs.eval() / rhs.eval(), + Self::Pow(ref expr, pow) => expr.eval().powi(pow), } } /// Parse a string, and generate the corresponding unit expression - fn parse(unit: &str) -> Result { + fn parse(unit: &str) -> Result { let tokens = tokenize(unit); let mut stream = shunting_yard(tokens)?; let ast = read_expr(&mut stream)?; diff --git a/lumol-core/src/utils/thread_vec.rs b/lumol-core/src/utils/thread_vec.rs index d52545e15..a206ba513 100644 --- a/lumol-core/src/utils/thread_vec.rs +++ b/lumol-core/src/utils/thread_vec.rs @@ -21,9 +21,9 @@ impl ThreadLocalVec { let inner = ThreadLocal::new(); // Set the current thread as owner of the data let _ = inner.get_or(|| RefCell::new(vec![T::default(); size])); - ThreadLocalVec { - inner: inner, - size: size, + Self { + inner, + size, } } diff --git a/lumol-input/src/alternator.rs b/lumol-input/src/alternator.rs index c824d9054..be8dc5e62 100644 --- a/lumol-input/src/alternator.rs +++ b/lumol-input/src/alternator.rs @@ -15,10 +15,10 @@ pub struct Alternator { impl Alternator { /// Wrap the algorithm `base` to call it only every `every` time. - pub fn new(every: u64, inner: T) -> Alternator { - Alternator { - every: every, - inner: inner, + pub fn new(every: u64, inner: T) -> Self { + Self { + every, + inner, count: 0, } } diff --git a/lumol-input/src/error.rs b/lumol-input/src/error.rs index 9d8dbf54f..823886d00 100644 --- a/lumol-input/src/error.rs +++ b/lumol-input/src/error.rs @@ -73,7 +73,7 @@ impl From<(CustomOutputError, PathBuf)> for Error { impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { match *self { - Error::Io(ref err, ref path) => { + Self::Io(ref err, ref path) => { match err.kind() { io::ErrorKind::NotFound => { write!(fmt, "can not find '{}'", path.display()) @@ -86,11 +86,11 @@ impl fmt::Display for Error { } } } - Error::Trajectory(ref err) => write!(fmt, "{err}"), - Error::TOML(ref err) => write!(fmt, "{err}"), - Error::Config(ref err) => write!(fmt, "{err}"), - Error::Unit(ref err) => write!(fmt, "{err}"), - Error::CustomOutput(ref err) => write!(fmt, "{err}"), + Self::Trajectory(ref err) => write!(fmt, "{err}"), + Self::TOML(ref err) => write!(fmt, "{err}"), + Self::Config(ref err) => write!(fmt, "{err}"), + Self::Unit(ref err) => write!(fmt, "{err}"), + Self::CustomOutput(ref err) => write!(fmt, "{err}"), } } } @@ -98,11 +98,11 @@ impl fmt::Display for Error { impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match *self { - Error::TOML(..) | Error::Config(..) => None, - Error::Io(ref err, _) => Some(err), - Error::Trajectory(ref err) => Some(err), - Error::Unit(ref err) => Some(err), - Error::CustomOutput(ref err) => Some(err), + Self::TOML(..) | Error::Config(..) => None, + Self::Io(ref err, _) => Some(err), + Self::Trajectory(ref err) => Some(err), + Self::Unit(ref err) => Some(err), + Self::CustomOutput(ref err) => Some(err), } } } diff --git a/lumol-input/src/interactions/mod.rs b/lumol-input/src/interactions/mod.rs index dfa836964..3dd39dc02 100644 --- a/lumol-input/src/interactions/mod.rs +++ b/lumol-input/src/interactions/mod.rs @@ -26,27 +26,25 @@ pub struct InteractionsInput { impl InteractionsInput { /// Read interactions from the TOML formatted file at `path`. - pub fn new>(path: P) -> Result { + pub fn new>(path: P) -> Result { let path = path.into(); let mut file = try_io!(File::open(&path), path); let mut buffer = String::new(); let _ = try_io!(file.read_to_string(&mut buffer), path); - return InteractionsInput::from_str(&buffer); + Self::from_str(&buffer) } /// Read the interactions from a TOML formatted string. #[allow(clippy::should_implement_trait)] - pub fn from_str(string: &str) -> Result { + pub fn from_str(string: &str) -> Result { let config = parse(string).map_err(|err| Error::TOML(Box::new(err)))?; validate(&config)?; - return Ok(InteractionsInput::from_toml(config)); + Ok(Self::from_toml(config)) } /// Read the interactions from a TOML table. - pub(crate) fn from_toml(config: Table) -> InteractionsInput { - InteractionsInput { - config: config - } + pub(crate) fn from_toml(config: Table) -> Self { + Self { config } } /// Read the interactions from this input into the `system`. diff --git a/lumol-input/src/interactions/pairs.rs b/lumol-input/src/interactions/pairs.rs index d76ddfa9d..62d3e0d8a 100644 --- a/lumol-input/src/interactions/pairs.rs +++ b/lumol-input/src/interactions/pairs.rs @@ -15,14 +15,15 @@ use crate::{Error, InteractionsInput, FromToml, FromTomlWithData}; use crate::extract; /// Global settings for the pair interactions +#[derive(Default)] struct GlobalInformation<'a> { cutoff: Option<&'a Value>, tail: Option, } impl GlobalInformation<'_> { - fn read(config: &Table) -> Result, Error> { - match config.get("global") { + fn read(config: &Table) -> Result { + Ok(match config.get("global") { Some(global) => { let global = global.as_table().ok_or( Error::from("'global' section must be a table") @@ -37,18 +38,15 @@ impl GlobalInformation<'_> { }) .map_or(Ok(None), |tail| tail.map(Some))?; - Ok(GlobalInformation { - cutoff: cutoff, - tail: tail, - }) + Self { + cutoff, + tail, + } } None => { - Ok(GlobalInformation { - cutoff: None, - tail: None, - }) + Self::default() } - } + }) } } diff --git a/lumol-input/src/simulations/mod.rs b/lumol-input/src/simulations/mod.rs index 5436ba157..b31c14731 100644 --- a/lumol-input/src/simulations/mod.rs +++ b/lumol-input/src/simulations/mod.rs @@ -47,21 +47,21 @@ pub struct Input { impl Input { /// Read the file at `Path` and create a new `Input` from it. - pub fn new>(path: P) -> Result { + pub fn new>(path: P) -> Result { let path = path.into(); let mut file = try_io!(File::open(&path), path); let mut buffer = String::new(); let _ = try_io!(file.read_to_string(&mut buffer), path); - return Input::from_str(path, &buffer); + Self::from_str(path, &buffer) } /// Read the `Input` from a TOML formatted string. - pub fn from_str(path: PathBuf, string: &str) -> Result { + pub fn from_str(path: PathBuf, string: &str) -> Result { let config = parse_toml(string).map_err(|err| { Error::TOML(Box::new(err)) })?; validate(&config)?; - Ok(Input { - path: path, - config: config, + Ok(Self { + path, + config, }) } @@ -73,9 +73,9 @@ impl Input { let nsteps = self.read_nsteps()?; Ok(Config { - system: system, - simulation: simulation, - nsteps: nsteps, + system, + simulation, + nsteps, }) } } diff --git a/lumol-sim/src/mc/monte_carlo.rs b/lumol-sim/src/mc/monte_carlo.rs index 32470d62c..71c750686 100644 --- a/lumol-sim/src/mc/monte_carlo.rs +++ b/lumol-sim/src/mc/monte_carlo.rs @@ -37,9 +37,9 @@ struct Move { impl Move { /// Create a move, initializing all counts to zero and setting the /// `target_acceptance`. - pub fn new(mcmove: Box, target_acceptance: Option) -> Move { - let mut counter = Move { - mcmove: mcmove, + pub fn new(mcmove: Box, target_acceptance: Option) -> Self { + let mut counter = Self { + mcmove, total_attempted: 0, total_accepted: 0, accepted: 0, @@ -154,23 +154,23 @@ pub struct MonteCarloBuilder { impl MonteCarloBuilder { /// Create a new Monte Carlo propagator at temperature `T`. - pub fn new(temperature: f64) -> MonteCarloBuilder { + pub fn new(temperature: f64) -> Self { let rng = Box::new(rand_xorshift::XorShiftRng::from_seed([ 0xeb, 0xa8, 0xe4, 0x29, 0xca, 0x60, 0x44, 0xb0, 0xd3, 0x77, 0xc6, 0xa0, 0x21, 0x71, 0x37, 0xf7, ])); - return MonteCarloBuilder::from_rng(temperature, rng); + Self::from_rng(temperature, rng) } /// Create a Monte Carlo propagator at temperature `T`, using the `rng` /// random number generator. - pub fn from_rng(temperature: f64, rng: Box) -> MonteCarloBuilder { + pub fn from_rng(temperature: f64, rng: Box) -> Self { assert!(temperature > 0.0, "Monte Carlo temperature must be positive, got {}", temperature); - MonteCarloBuilder { + Self { beta: 1.0 / (K_BOLTZMANN * temperature), moves: Vec::new(), frequencies: Vec::new(), - rng: rng, + rng, } } diff --git a/lumol-sim/src/mc/moves/resize.rs b/lumol-sim/src/mc/moves/resize.rs index de633fdeb..981d86398 100644 --- a/lumol-sim/src/mc/moves/resize.rs +++ b/lumol-sim/src/mc/moves/resize.rs @@ -28,13 +28,13 @@ pub struct Resize { impl Resize { /// Create a new `Resize` move, with target pressure `pressure` and maximum /// displacement of `delta`. - pub fn new(pressure: f64, delta: f64) -> Resize { + pub fn new(pressure: f64, delta: f64) -> Self { assert!(delta > 0.0, "delta must be positive in Resize move"); - Resize { - delta: delta, + Self { + delta, range: Uniform::new(-delta, delta), previous: Configuration::new(), - pressure: pressure, + pressure, maximum_cutoff: None, } } diff --git a/lumol-sim/src/mc/moves/rotate.rs b/lumol-sim/src/mc/moves/rotate.rs index 3a61f81df..f2a7b08b4 100644 --- a/lumol-sim/src/mc/moves/rotate.rs +++ b/lumol-sim/src/mc/moves/rotate.rs @@ -35,13 +35,13 @@ impl Rotate { /// Create a new `Rotate` move, with maximum angular displacement of /// `theta`. This move will apply to the molecules with the given `hash`, /// or all molecules if `hash` is `None`. - pub fn new>>(theta: f64, hash: H) -> Rotate { + pub fn new>>(theta: f64, hash: H) -> Self { assert!(theta > 0.0, "theta must be positive in Rotate move"); - Rotate { + Self { hash: hash.into(), molid: usize::max_value(), newpos: Vec::new(), - theta: theta, + theta, range: Uniform::new(-theta, theta), } } diff --git a/lumol-sim/src/mc/moves/translate.rs b/lumol-sim/src/mc/moves/translate.rs index e340bc3bb..d2af8d5cc 100644 --- a/lumol-sim/src/mc/moves/translate.rs +++ b/lumol-sim/src/mc/moves/translate.rs @@ -38,14 +38,14 @@ impl Translate { /// Create a new `Translate` move, with maximum displacement of `delta`. /// This move will apply to the molecules with the given `hash`, or all /// molecules if `hash` is `None`. - pub fn new>>(delta: f64, hash: H) -> Translate { + pub fn new>>(delta: f64, hash: H) -> Self { assert!(delta > 0.0, "delta must be positive in Translate move"); let delta = delta / f64::sqrt(3.0); - Translate { + Self { hash: hash.into(), molid: usize::max_value(), newpos: Vec::new(), - delta: delta, + delta, maximum_cutoff: None, range: Uniform::new(-delta, delta), } diff --git a/lumol-sim/src/md/integrators.rs b/lumol-sim/src/md/integrators.rs index 057768dd3..6be1aeadc 100644 --- a/lumol-sim/src/md/integrators.rs +++ b/lumol-sim/src/md/integrators.rs @@ -28,9 +28,9 @@ pub struct VelocityVerlet { impl VelocityVerlet { /// Create a new integrator with a timestep of `timestep`. - pub fn new(timestep: f64) -> VelocityVerlet { - VelocityVerlet { - timestep: timestep, + pub fn new(timestep: f64) -> Self { + Self { + timestep, accelerations: Vec::new(), } } @@ -81,9 +81,9 @@ pub struct Verlet { impl Verlet { /// Create a new integrator with a timestep of `timestep`. - pub fn new(timestep: f64) -> Verlet { - Verlet { - timestep: timestep, + pub fn new(timestep: f64) -> Self { + Self { + timestep, prevpos: Vec::new(), } } @@ -134,9 +134,9 @@ pub struct LeapFrog { impl LeapFrog { /// Create a new integrator with a timestep of `timestep`. - pub fn new(timestep: f64) -> LeapFrog { - LeapFrog { - timestep: timestep, + pub fn new(timestep: f64) -> Self { + Self { + timestep, accelerations: Vec::new(), } } @@ -192,11 +192,11 @@ impl BerendsenBarostat { /// Create a new Berendsen barostat with an integration timestep of /// `timestep`, and a target pressure of `pressure` and the barostat time /// scale `tau`. - pub fn new(timestep: f64, pressure: f64, tau: f64) -> BerendsenBarostat { - BerendsenBarostat { - timestep: timestep, - pressure: pressure, - tau: tau, + pub fn new(timestep: f64, pressure: f64, tau: f64) -> Self { + Self { + timestep, + pressure, + tau, accelerations: Vec::new(), eta: 1.0, } @@ -269,11 +269,11 @@ impl AnisoBerendsenBarostat { /// Create a new anisotropic Berendsen barostat with an integration timestep /// of `timestep`, and a target stress matrix of `stress` and the barostat /// time scale `tau`. - pub fn new(timestep: f64, stress: Matrix3, tau: f64) -> AnisoBerendsenBarostat { - AnisoBerendsenBarostat { - timestep: timestep, - stress: stress, - tau: tau, + pub fn new(timestep: f64, stress: Matrix3, tau: f64) -> Self { + Self { + timestep, + stress, + tau, accelerations: Vec::new(), eta: Matrix3::one(), } @@ -282,8 +282,8 @@ impl AnisoBerendsenBarostat { /// Create a new anisotropic Berendsen barostat with an integration timestep /// of `timestep`, using an hydrostatic stress matrix corresponding to the /// pressure `pressure` and the barostat time scale `tau`. - pub fn hydrostatic(timestep: f64, pressure: f64, tau: f64) -> AnisoBerendsenBarostat { - AnisoBerendsenBarostat::new(timestep, pressure * Matrix3::one(), tau) + pub fn hydrostatic(timestep: f64, pressure: f64, tau: f64) -> Self { + Self::new(timestep, pressure * Matrix3::one(), tau) } } diff --git a/lumol-sim/src/md/molecular_dynamics.rs b/lumol-sim/src/md/molecular_dynamics.rs index 421dc4b12..728aac668 100644 --- a/lumol-sim/src/md/molecular_dynamics.rs +++ b/lumol-sim/src/md/molecular_dynamics.rs @@ -20,15 +20,15 @@ pub struct MolecularDynamics { impl MolecularDynamics { /// Create a new `MolecularDynamics` propagator using a `VelocityVerlet` /// integrator. - pub fn new(dt: f64) -> MolecularDynamics { - MolecularDynamics::from_integrator(Box::new(VelocityVerlet::new(dt))) + pub fn new(dt: f64) -> Self { + Self::from_integrator(Box::new(VelocityVerlet::new(dt))) } /// Create a new `MolecularDynamics` propagator using the specified /// `integrator`. - pub fn from_integrator(integrator: Box) -> MolecularDynamics { - MolecularDynamics { - integrator: integrator, + pub fn from_integrator(integrator: Box) -> Self { + Self { + integrator, thermostat: None, controls: Vec::new(), } diff --git a/lumol-sim/src/md/thermostats.rs b/lumol-sim/src/md/thermostats.rs index 35b026699..e9343e6d0 100644 --- a/lumol-sim/src/md/thermostats.rs +++ b/lumol-sim/src/md/thermostats.rs @@ -47,18 +47,18 @@ pub struct RescaleThermostat { impl RescaleThermostat { /// Create a new `RescaleThermostat` acting at temperature `temperature`, with a /// tolerance of `5% * temperature`. - pub fn new(temperature: f64) -> RescaleThermostat { + pub fn new(temperature: f64) -> Self { assert!(temperature >= 0.0, "The temperature must be positive in thermostats."); let tol = 0.05 * temperature; - RescaleThermostat::with_tolerance(temperature, tol) + Self::with_tolerance(temperature, tol) } /// Create a new `RescaleThermostat` acting at temperature `T`, with a /// tolerance of `tol`. For rescaling all the steps, use `tol = 0`. - pub fn with_tolerance(temperature: f64, tol: f64) -> RescaleThermostat { - RescaleThermostat { - temperature: temperature, - tol: tol, + pub fn with_tolerance(temperature: f64, tol: f64) -> Self { + Self { + temperature, + tol, } } } @@ -99,12 +99,12 @@ pub struct BerendsenThermostat { impl BerendsenThermostat { /// Create a new `BerendsenThermostat` acting at the given `temperature`, /// with a timestep of `tau` times the integrator timestep. - pub fn new(temperature: f64, tau: f64) -> BerendsenThermostat { + pub fn new(temperature: f64, tau: f64) -> Self { assert!(temperature >= 0.0, "The temperature must be positive in thermostats."); assert!(tau >= 1.0, "The timestep must be larger than 1 in berendsen thermostat."); - BerendsenThermostat { - temperature: temperature, - tau: tau, + Self { + temperature, + tau, } } } @@ -145,12 +145,12 @@ pub struct CSVRThermostat { impl CSVRThermostat { /// Create a new `CSVRThermostat` enforcing the given `temperature`, with a /// timestep of `tau` times the integrator timestep. - pub fn new(temperature: f64, tau: f64) -> CSVRThermostat { + pub fn new(temperature: f64, tau: f64) -> Self { let rng = Box::new(rand_xorshift::XorShiftRng::from_seed([ 0xeb, 0xa8, 0xe4, 0x29, 0xca, 0x60, 0x44, 0xb0, 0xd3, 0x77, 0xc6, 0xa0, 0x21, 0x71, 0x37, 0xf7, ])); - return CSVRThermostat::from_rng(temperature, tau, rng) + Self::from_rng(temperature, tau, rng) } /// Create a new `CSVRThermostat` enforcing the given `temperature`, with a @@ -161,8 +161,8 @@ impl CSVRThermostat { assert!(tau >= 1.0, "The timestep must be larger than 1 in CSVR thermostat."); CSVRThermostat { target_kinetic_per_dof: K_BOLTZMANN * temperature / 2.0, - tau: tau, - rng: rng, + tau, + rng, normal: Normal::new(0.0, 1.0).expect("bad normal distribution"), } } diff --git a/lumol-sim/src/min/minimization.rs b/lumol-sim/src/min/minimization.rs index 4f5e6c424..a14dcc9cc 100644 --- a/lumol-sim/src/min/minimization.rs +++ b/lumol-sim/src/min/minimization.rs @@ -52,12 +52,12 @@ pub struct Minimization { impl Minimization { /// Create a new `Minimization` using the given `minimizer` and specific /// energy and force `tolerance`. - pub fn new(minimizer: Box, tolerance: Tolerance) -> Minimization { - Minimization { - minimizer: minimizer, + pub fn new(minimizer: Box, tolerance: Tolerance) -> Self { + Self { + minimizer, is_converged: false, last_energy: 0.0, - tolerance: tolerance, + tolerance, } } diff --git a/lumol-sim/src/min/steepest_descent.rs b/lumol-sim/src/min/steepest_descent.rs index 50ebdafb2..944e76f3e 100644 --- a/lumol-sim/src/min/steepest_descent.rs +++ b/lumol-sim/src/min/steepest_descent.rs @@ -18,8 +18,8 @@ pub struct SteepestDescent { impl SteepestDescent { /// Create a new `SteepestDescent` minimizer - pub fn new() -> SteepestDescent { - SteepestDescent { + pub fn new() -> Self { + Self { gamma: units::from(0.1, "fs^2/u").expect("bad unit"), } } @@ -60,7 +60,7 @@ impl Minimizer for SteepestDescent { } return Tolerance { - energy: energy, + energy, force2: forces.iter().map(|&f| f.norm2()).fold(f64::NAN, f64::max), }; } diff --git a/lumol-sim/src/output/cell.rs b/lumol-sim/src/output/cell.rs index c8aa9c73b..281fb176b 100644 --- a/lumol-sim/src/output/cell.rs +++ b/lumol-sim/src/output/cell.rs @@ -21,8 +21,8 @@ pub struct CellOutput { impl CellOutput { /// Create a new `CellOutput` writing to `filename`. The file is replaced if /// it already exists. - pub fn new>(filename: P) -> Result { - Ok(CellOutput { + pub fn new>(filename: P) -> Result { + Ok(Self { file: BufWriter::new(File::create(filename.as_ref())?), path: filename.as_ref().to_owned(), }) diff --git a/lumol-sim/src/output/custom.rs b/lumol-sim/src/output/custom.rs index 4f72342b0..9f86e427f 100644 --- a/lumol-sim/src/output/custom.rs +++ b/lumol-sim/src/output/custom.rs @@ -49,9 +49,9 @@ impl From for CustomOutputError { impl fmt::Display for CustomOutputError { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { match *self { - CustomOutputError::Io(ref err) => write!(fmt, "{err}")?, - CustomOutputError::Expr(ref err) => write!(fmt, "{err}")?, - CustomOutputError::Custom(ref err) => write!(fmt, "{err}")?, + Self::Io(ref err) => write!(fmt, "{err}")?, + Self::Expr(ref err) => write!(fmt, "{err}")?, + Self::Custom(ref err) => write!(fmt, "{err}")?, } Ok(()) } @@ -60,9 +60,9 @@ impl fmt::Display for CustomOutputError { impl error::Error for CustomOutputError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match *self { - CustomOutputError::Io(ref err) => Some(err), - CustomOutputError::Expr(ref err) => Some(err), - CustomOutputError::Custom(_) => None, + Self::Io(ref err) | + Self::Expr(ref err) => Some(err), + Self::Custom(_) => None, } } } @@ -76,7 +76,7 @@ struct FormatArgs { } impl FormatArgs { - fn new(format: &str) -> Result { + fn new(format: &str) -> Result { let mut args = Vec::new(); let mut expr = String::new(); let mut tail = String::new(); @@ -115,9 +115,9 @@ impl FormatArgs { return Err(CustomOutputError::Custom("mismatched braces".into())); } - Ok(FormatArgs { - args: args, - tail: tail, + Ok(Self { + args, + tail, }) } diff --git a/lumol-sim/src/output/energy.rs b/lumol-sim/src/output/energy.rs index c3c686113..09d7869b4 100644 --- a/lumol-sim/src/output/energy.rs +++ b/lumol-sim/src/output/energy.rs @@ -22,8 +22,8 @@ pub struct EnergyOutput { impl EnergyOutput { /// Create a new `EnergyOutput` writing to `filename`. The file is replaced /// if it already exists. - pub fn new>(filename: P) -> Result { - Ok(EnergyOutput { + pub fn new>(filename: P) -> Result { + Ok(Self { file: BufWriter::new(File::create(filename.as_ref())?), path: filename.as_ref().to_owned(), }) diff --git a/lumol-sim/src/output/forces.rs b/lumol-sim/src/output/forces.rs index 0c2fcfa18..9e4dda7fe 100644 --- a/lumol-sim/src/output/forces.rs +++ b/lumol-sim/src/output/forces.rs @@ -21,8 +21,8 @@ pub struct ForcesOutput { impl ForcesOutput { /// Create a new `ForcesOutput` writing to `filename`. The file is replaced /// if it already exists. - pub fn new>(filename: P) -> Result { - Ok(ForcesOutput { + pub fn new>(filename: P) -> Result { + Ok(Self { file: BufWriter::new(File::create(filename.as_ref())?), path: filename.as_ref().to_owned(), }) diff --git a/lumol-sim/src/output/properties.rs b/lumol-sim/src/output/properties.rs index 1074146e8..11993c887 100644 --- a/lumol-sim/src/output/properties.rs +++ b/lumol-sim/src/output/properties.rs @@ -27,8 +27,8 @@ pub struct PropertiesOutput { impl PropertiesOutput { /// Create a new `PropertiesOutput` writing to `filename`. The file is replaced /// if it already exists. - pub fn new>(filename: P) -> Result { - Ok(PropertiesOutput { + pub fn new>(filename: P) -> Result { + Ok(Self { file: BufWriter::new(File::create(filename.as_ref())?), path: filename.as_ref().to_owned(), }) diff --git a/lumol-sim/src/output/stress.rs b/lumol-sim/src/output/stress.rs index ce8da8bb1..ff6d3237c 100644 --- a/lumol-sim/src/output/stress.rs +++ b/lumol-sim/src/output/stress.rs @@ -22,8 +22,8 @@ pub struct StressOutput { impl StressOutput { /// Create a new `StressOutput` writing to `filename`. The file is replaced /// if it already exists. - pub fn new>(filename: P) -> Result { - Ok(StressOutput { + pub fn new>(filename: P) -> Result { + Ok(Self { file: BufWriter::new(File::create(filename.as_ref())?), path: filename.as_ref().to_owned(), }) diff --git a/lumol-sim/src/output/trajectory.rs b/lumol-sim/src/output/trajectory.rs index ac14bc045..109409ae0 100644 --- a/lumol-sim/src/output/trajectory.rs +++ b/lumol-sim/src/output/trajectory.rs @@ -23,12 +23,12 @@ impl TrajectoryOutput { /// for more information. /// /// [formats]: http://chemfiles.org/chemfiles/latest/formats.html - pub fn new

(path: P) -> Result + pub fn new

(path: P) -> Result where P: AsRef, { let builder = TrajectoryBuilder::new().mode(OpenMode::Write); - Ok(TrajectoryOutput { + Ok(Self { file: builder.open(path)? }) } diff --git a/lumol-sim/src/simulations.rs b/lumol-sim/src/simulations.rs index 91e7cfe78..a4253e5af 100644 --- a/lumol-sim/src/simulations.rs +++ b/lumol-sim/src/simulations.rs @@ -17,17 +17,17 @@ struct OutputFrequency { } impl OutputFrequency { - pub fn new(output: Box) -> OutputFrequency { - OutputFrequency { + pub fn new(output: Box) -> Self { + Self { frequency: 1, - output: output, + output, } } - pub fn with_frequency(output: Box, frequency: u64) -> OutputFrequency { - OutputFrequency { - frequency: frequency, - output: output, + pub fn with_frequency(output: Box, frequency: u64) -> Self { + Self { + frequency, + output, } } } @@ -58,9 +58,9 @@ pub struct Simulation { impl Simulation { /// Create a new Simulation from a Propagator. - pub fn new(propagator: Box) -> Simulation { - Simulation { - propagator: propagator, + pub fn new(propagator: Box) -> Self { + Self { + propagator, outputs: Vec::new(), } } diff --git a/lumol-sim/src/velocities.rs b/lumol-sim/src/velocities.rs index cc38dccf9..327b24a92 100644 --- a/lumol-sim/src/velocities.rs +++ b/lumol-sim/src/velocities.rs @@ -38,12 +38,12 @@ pub struct BoltzmannVelocities { impl BoltzmannVelocities { /// Create a new `BoltzmannVelocities` at the given `temperature`. - pub fn new(temperature: f64) -> BoltzmannVelocities { + pub fn new(temperature: f64) -> Self { let dist = Normal::new(0.0, f64::sqrt(K_BOLTZMANN * temperature)) .expect("bad normal distribution"); - BoltzmannVelocities { - temperature: temperature, - dist: dist, + Self { + temperature, + dist, rng: XorShiftRng::from_seed([ 0xeb, 0xa8, 0xe4, 0x29, 0xca, 0x60, 0x44, 0xb0, 0xd3, 0x77, 0xc6, 0xa0, 0x21, 0x71, 0x37, 0xf7, @@ -91,10 +91,10 @@ pub struct UniformVelocities { impl UniformVelocities { /// Create a new `UniformVelocities` at the given `temperature`. - pub fn new(temperature: f64) -> UniformVelocities { + pub fn new(temperature: f64) -> Self { let factor = f64::sqrt(3.0 * K_BOLTZMANN * temperature); - UniformVelocities { - temperature: temperature, + Self { + temperature, dist: Uniform::new(-factor, factor), rng: XorShiftRng::from_seed([ 0xeb, 0xa8, 0xe4, 0x29, 0xca, 0x60, 0x44, 0xb0, diff --git a/src/main.rs b/src/main.rs index dae407f02..7be572b93 100644 --- a/src/main.rs +++ b/src/main.rs @@ -107,8 +107,8 @@ struct CleanedBacktrace { } impl CleanedBacktrace { - fn new() -> CleanedBacktrace { - CleanedBacktrace { + fn new() -> Self { + Self { inner: Backtrace::new() } } diff --git a/tests/docs.rs b/tests/docs.rs index f8ab3c828..5cd0bd389 100644 --- a/tests/docs.rs +++ b/tests/docs.rs @@ -13,8 +13,8 @@ struct Cleaner { } impl Cleaner { - fn new(files: Vec<&'static str>) -> Cleaner { - Cleaner { + fn new(files: Vec<&'static str>) -> Self { + Self { files } }