From 15c1f28693e6099caf384912b938528d42cdc756 Mon Sep 17 00:00:00 2001 From: Mikael Lund Date: Thu, 4 Jul 2024 13:18:21 +0200 Subject: [PATCH] Partial migration from range-v3 to `std::ranges` (#452) --- .idea/inspectionProfiles/Project_Default.xml | 10 -- src/actions.cpp | 11 +- src/analysis.cpp | 101 ++++++++++--------- src/atomdata.h | 11 +- src/aux/arange.h | 17 ++-- src/auxiliary.h | 8 +- src/celllistimpl.h | 8 +- src/clustermove.cpp | 24 ++--- src/clustermove.h | 2 +- src/core.cpp | 7 +- src/core.h | 3 +- src/energy.cpp | 63 ++++++------ src/energy.h | 26 +++-- src/geometry.cpp | 2 +- src/geometry.h | 27 +++-- src/group.h | 32 +++--- src/io.h | 11 +- src/molecule.cpp | 14 ++- src/montecarlo.cpp | 6 +- src/move.cpp | 34 ++++--- src/move.h | 12 +-- src/mpicontroller.cpp | 15 ++- src/mpicontroller.h | 14 +-- src/particle.h | 4 +- src/random.h | 6 +- src/reactioncoordinate.cpp | 36 ++++--- src/regions.cpp | 5 +- src/regions.h | 5 +- src/sasa.cpp | 23 ++--- src/scatter.h | 3 +- src/smart_montecarlo.h | 20 ++-- src/space.cpp | 18 ++-- src/space.h | 21 ++-- src/speciation.cpp | 61 ++++++----- src/voronota.cpp | 2 +- 35 files changed, 318 insertions(+), 344 deletions(-) delete mode 100644 .idea/inspectionProfiles/Project_Default.xml diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml deleted file mode 100644 index 146ab09b7..000000000 --- a/.idea/inspectionProfiles/Project_Default.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - \ No newline at end of file diff --git a/src/actions.cpp b/src/actions.cpp index f2e1c9ebc..8e1939622 100644 --- a/src/actions.cpp +++ b/src/actions.cpp @@ -4,6 +4,7 @@ #include "io.h" #include "aux/arange.h" #include +#include #include namespace Faunus { @@ -49,7 +50,7 @@ AngularScan::AngularScan(const json& j, const Space& spc) */ void AngularScan::Molecule::initialize(const Space::GroupVector& groups, int molecule_index) { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; index = molecule_index; const auto& group = groups.at(index); if (group.isAtomic()) { @@ -66,7 +67,7 @@ void AngularScan::Molecule::initialize(const Space::GroupVector& groups, int mol ParticleVector AngularScan::Molecule::getRotatedReference(const Space::GroupVector& groups, const Eigen::Quaterniond& q) { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; const auto& group = groups.at(index); auto particles = ParticleVector(group.begin(), group.end()); // copy particles from Space auto positions = @@ -94,8 +95,8 @@ void AngularScan::report(const Group& group1, const Group& group2, const Eigen:: *stream << format(q1) << format(q2) << fmt::format("{:8.4f} {:>10.3E}\n", group2.mass_center.z(), energy / 1.0_kJmol); if (trajectory) { - auto positions = ranges::views::concat(group1, group2) | - ranges::cpp20::views::transform(&Particle::pos); + auto positions = + ranges::views::concat(group1, group2) | std::views::transform(&Particle::pos); trajectory->writeNext({500, 500, 500}, positions.begin(), positions.end()); } } @@ -127,7 +128,7 @@ void AngularScan::operator()(Space& spc, Energy::Hamiltonian& hamiltonian) const auto q2 = q_dihedral * q_body2; // simultaneous rotations (non-commutative) auto particles2 = molecules.second.getRotatedReference(spc.groups, q2); - ranges::cpp20::for_each(particles2, translate); + std::ranges::for_each(particles2, translate); auto group2 = Group(0, particles2.begin(), particles2.end()); group2.mass_center = {0.0, 0.0, z_pos}; report(group1, group2, q1, q2, *nonbonded); diff --git a/src/analysis.cpp b/src/analysis.cpp index bbe2b9044..f21647636 100644 --- a/src/analysis.cpp +++ b/src/analysis.cpp @@ -385,7 +385,7 @@ void SystemEnergy::createOutputStream() *output_stream << "#"; } *output_stream << fmt::format("{:>9}{}{:12}", "step", separator, "total"); - ranges::for_each(hamiltonian, [&](auto& energy) { + std::ranges::for_each(hamiltonian, [&](auto& energy) { *output_stream << fmt::format("{}{:12}", separator, energy->name); }); *output_stream << "\n"; @@ -405,7 +405,7 @@ std::vector SystemEnergy::calculateEnergies() const { Change change; change.everything = true; // trigger full energy calculation - return hamiltonian | ranges::views::transform([&](auto& i) { return i->energy(change); }) | + return hamiltonian | std::views::transform([&](auto& i) { return i->energy(change); }) | ranges::to_vector; } @@ -540,7 +540,7 @@ GroupMatrixAnalysis::GroupMatrixAnalysis(const json& j, const Space& spc, Energy::Hamiltonian& hamiltonian) : PairMatrixAnalysis(j, spc) { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; // finds the molecule ids and store their indices auto molids = Faunus::parseMolecules(j.at("molecules")); auto is_selected = [&](const auto& group) { @@ -562,8 +562,7 @@ GroupMatrixAnalysis::GroupMatrixAnalysis(const json& j, const Space& spc, void GroupMatrixAnalysis::setPairMatrix() { auto is_active = [&](auto index) { return !spc.groups.at(index).empty(); }; - const auto indices = - group_indices | ranges::cpp20::views::filter(is_active) | ranges::to_vector; + const auto indices = group_indices | std::views::filter(is_active) | ranges::to_vector; // zero matrix, then fill it pair_matrix.setZero(); @@ -1090,7 +1089,7 @@ AtomicDisplacement::AtomicDisplacement(const json& j, const Space& spc, std::str molid = molecule_data.id(); auto positions = getPositions(); - const auto num_positions = ranges::cpp20::distance(positions.begin(), positions.end()); + const auto num_positions = std::ranges::distance(positions.begin(), positions.end()); reference_positions = positions | ranges::to_vector; cell_indices.resize(num_positions, {0, 0, 0}); mean_squared_displacement.resize(num_positions); @@ -1191,7 +1190,7 @@ void AtomicDisplacement::_to_disk() PointVector AtomicDisplacement::getPositions() const { auto active_and_inactive = [&](const Group& group) { - return ranges::make_subrange(group.begin(), group.trueend()); + return std::ranges::subrange(group.begin(), group.trueend()); }; namespace rv = ranges::cpp20::views; return spc.findMolecules(molid, Space::Selection::ALL) | rv::transform(active_and_inactive) | @@ -1211,7 +1210,7 @@ MassCenterDisplacement::MassCenterDisplacement(const json& j, const Space& spc, PointVector MassCenterDisplacement::getPositions() const { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; return spc.findMolecules(molid, Space::Selection::ACTIVE) | rv::transform(&Group::mass_center) | ranges::to; } @@ -1227,7 +1226,7 @@ void WidomInsertion::selectGhostGroup() { change.clear(); auto inactive_groups = spc.findMolecules(molid, Space::Selection::INACTIVE); - if (!ranges::cpp20::empty(inactive_groups)) { + if (!std::ranges::empty(inactive_groups)) { const auto& group = *inactive_groups.begin(); // select first group if (group.empty() && group.capacity() > 0) { // must be inactive and have a non-zero capacity @@ -1384,7 +1383,7 @@ void AtomDensity::_sample() const auto& atomic_ids = reaction.participatingAtomsAndMolecules().first; unique_reactive_atoms.insert(atomic_ids.begin(), atomic_ids.end()); } - ranges::cpp20::for_each(unique_reactive_atoms, [&](auto id) { + std::ranges::for_each(unique_reactive_atoms, [&](auto id) { const auto count = spc.countAtoms(id); atomswap_probability_density[id](count)++; }); @@ -1395,21 +1394,23 @@ void AtomDensity::_sample() */ std::map AtomDensity::count() const { - namespace rv = ranges::cpp20::views; + using ranges::cpp20::views::filter; + using ranges::cpp20::views::join; + using ranges::cpp20::views::transform; // All ids incl. inactive are counted; std::vector ensures constant lookup (index = id) std::vector atom_count(names.size(), 0); // Count number of active atoms in atomic groups auto particle_ids_in_atomic_groups = - spc.groups | rv::filter(&Group::isAtomic) | rv::join | rv::transform(&Particle::id); - ranges::cpp20::for_each(particle_ids_in_atomic_groups, [&](auto id) { atom_count.at(id)++; }); + spc.groups | filter(&Group::isAtomic) | join | transform(&Particle::id); + std::ranges::for_each(particle_ids_in_atomic_groups, [&](auto id) { atom_count.at(id)++; }); // Copy vector --> map id_type id = 0U; std::map map; - ranges::cpp20::for_each(atom_count, - [&id, &map](auto count) { map.emplace_hint(map.end(), id++, count); }); + std::ranges::for_each(atom_count, + [&id, &map](auto count) { map.emplace_hint(map.end(), id++, count); }); return map; } @@ -1442,20 +1443,20 @@ void AtomDensity::_to_disk() */ std::map MoleculeDensity::count() const { - using namespace ranges::cpp20; + using std::views::transform; + using std::views::filter; std::map molecular_group_count; // ensure that also inactive groups are registered (as zero) - for_each(Faunus::molecules | views::filter(&MoleculeData::isMolecular), - [&](auto& moldata) { molecular_group_count[moldata.id()] = 0; }); + std::ranges::for_each(Faunus::molecules | filter(&MoleculeData::isMolecular), + [&](auto& moldata) { molecular_group_count[moldata.id()] = 0; }); auto non_empty_molecular = [](const Group& group) { return group.isMolecular() && !group.empty(); }; - auto molecular_group_ids = - spc.groups | views::filter(non_empty_molecular) | views::transform(&Group::id); + auto molecular_group_ids = spc.groups | filter(non_empty_molecular) | transform(&Group::id); - for_each(molecular_group_ids, [&](auto id) { molecular_group_count[id]++; }); + std::ranges::for_each(molecular_group_ids, [&](auto id) { molecular_group_count[id]++; }); return molecular_group_count; } @@ -1506,7 +1507,7 @@ void SanityCheck::checkGroupsCoverParticles() void SanityCheck::checkWithinContainer(const Space::GroupType& group) { bool outside_simulation_cell = false; - auto outside_particles = group | ranges::cpp20::views::filter([&](const Particle& particle) { + auto outside_particles = group | std::views::filter([&](const Particle& particle) { return spc.geometry.collision(particle.pos); }); @@ -1703,15 +1704,19 @@ XTCtraj::XTCtraj(const Space& spc, const std::string& filename, const std::vector& molecule_names) : Analysis(spc, "xtcfile") { - namespace rv = ranges::cpp20::views; + using ranges::cpp20::views::filter; + using ranges::cpp20::views::join; + using ranges::cpp20::views::transform; + using ranges::views::cache1; + writer = std::make_unique(filename); if (!molecule_names.empty()) { group_ids = Faunus::names2ids(Faunus::molecules, molecule_names); // molecule types to save group_indices = group_ids | - rv::transform([&](auto id) { return spc.findMolecules(id, Space::Selection::ALL); }) | - ranges::views::cache1 | rv::join | - rv::transform([&](const Group& group) { return spc.getGroupIndex(group); }) | + transform([&](auto id) { return spc.findMolecules(id, Space::Selection::ALL); }) | + cache1 | join | + transform([&](const Group& group) { return spc.getGroupIndex(group); }) | ranges::to_vector; if (group_indices.empty()) { throw ConfigurationError("xtc selection is empty - nothing to sample"); @@ -1732,7 +1737,7 @@ void XTCtraj::_to_json(json& j) const if (!group_ids.empty()) { j["molecules"] = group_ids | - ranges::cpp20::views::transform([](auto id) { return Faunus::molecules.at(id).name; }) | + std::views::transform([](auto id) { return Faunus::molecules.at(id).name; }) | ranges::to_vector; } } @@ -1744,7 +1749,7 @@ void XTCtraj::_sample() { namespace rv = ranges::cpp20::views; if (group_ids.empty()) { - auto positions = spc.particles | rv::transform(&Particle::pos); + auto positions = spc.particles | std::views::transform(&Particle::pos); writer->writeNext(spc.geometry.getLength(), positions.begin(), positions.end()); } else { @@ -1895,7 +1900,7 @@ void InertiaTensor::_to_json(json& j) const std::pair InertiaTensor::compute() const { const auto& group = spc.groups.at(group_index); - auto subgroup = ranges::make_subrange(group.begin() + particle_range.at(0), + auto subgroup = std::ranges::subrange(group.begin() + particle_range.at(0), group.begin() + particle_range.at(1) + 1); auto I = Geometry::inertia(subgroup.begin(), subgroup.end(), group.mass_center, @@ -2323,11 +2328,11 @@ void AtomsInMoleculePolicy::sample(const Space& spc, SASAAnalysis& analysis) { auto molecules = spc.findMolecules(molecule_id); - ranges::for_each(molecules, [&](const auto& molecule) { + std::ranges::for_each(molecules, [&](const auto& molecule) { auto is_selected = [&](const Particle& particle) { return selected_indices.count(molecule.getParticleIndex(particle)) > 0; }; - auto selected_atoms = molecule | ranges::cpp20::views::filter(is_selected); + auto selected_atoms = molecule | std::views::filter(is_selected); sampleTotalSASA(selected_atoms.begin(), selected_atoms.end(), analysis); }); } @@ -2396,7 +2401,7 @@ void AtomProfile::_sample() } auto selected_particles = - spc.activeParticles() | ranges::cpp20::views::filter([&](const Particle& particle) { + spc.activeParticles() | std::views::filter([&](const Particle& particle) { return atom_id_selection.count(particle.id) > 0; }); @@ -2485,7 +2490,7 @@ void SlicedDensity::_sample() } auto filtered_particles = - spc.activeParticles() | ranges::cpp20::views::filter([&](const auto& particle) { + spc.activeParticles() | std::views::filter([&](const auto& particle) { return std::find(atom_ids.begin(), atom_ids.end(), particle.id) != atom_ids.end(); }); @@ -2553,29 +2558,28 @@ std::vector ChargeFluctuations::getPredominantParticleNames() const return Faunus::atoms[atomid].name; }; // in a histogram, find the atom name with most counts - auto atom_names = atom_histograms | ranges::cpp20::views::transform(most_frequent_name); - return std::vector(ranges::cpp20::begin(atom_names), - ranges::cpp20::end(atom_names)); + auto atom_names = atom_histograms | std::views::transform(most_frequent_name); + return std::vector(std::ranges::begin(atom_names), std::ranges::end(atom_names)); } std::vector ChargeFluctuations::getChargeStandardDeviation() const { - auto stdev = - atom_mean_charges | ranges::cpp20::views::transform([](auto& i) { return i.stdev(); }); - return std::vector(ranges::cpp20::begin(stdev), ranges::cpp20::end(stdev)); + using namespace std::ranges; + auto stdev = atom_mean_charges | views::transform([](auto& i) { return i.stdev(); }); + return std::vector(begin(stdev), end(stdev)); } std::vector ChargeFluctuations::getMeanCharges() const { - return std::vector(ranges::cpp20::begin(atom_mean_charges), - ranges::cpp20::end(atom_mean_charges)); + return std::vector(std::ranges::begin(atom_mean_charges), + std::ranges::end(atom_mean_charges)); } void ChargeFluctuations::_to_disk() { if (not filename.empty()) { auto molecules = spc.findMolecules(mol_iter->id(), Space::Selection::ALL); - if (not ranges::cpp20::empty(molecules)) { + if (not std::ranges::empty(molecules)) { const auto particles_with_avg_charges = averageChargeParticles(*molecules.begin()); PQRWriter().save(MPI::prefix + filename, particles_with_avg_charges.begin(), particles_with_avg_charges.end(), spc.geometry.getLength()); @@ -2667,7 +2671,8 @@ void ScatteringFunction::_sample() scatter_positions.clear(); auto groups = molecule_ids | rv::transform([&](auto id) { return spc.findMolecules(id); }) | rv::join; - ranges::cpp20::for_each(groups, [&](auto& group) { + + std::ranges::for_each(groups, [&](auto& group) { if (mass_center_scattering && group.isMolecular()) { scatter_positions.push_back(group.mass_center); } @@ -2809,8 +2814,8 @@ void VirtualTranslate::_sample() return; } if (auto mollist = mutable_space.findMolecules(molid, Space::Selection::ACTIVE); - !ranges::cpp20::empty(mollist)) { - if (ranges::distance(mollist.begin(), mollist.end()) > 1) { + !std::ranges::empty(mollist)) { + if (std::ranges::distance(mollist.begin(), mollist.end()) > 1) { throw std::runtime_error("exactly ONE active molecule expected"); } if (auto group_it = random.sample(mollist.begin(), mollist.end()); not group_it->empty()) { @@ -3004,8 +3009,7 @@ void ElectricPotential::getTargets(const json& j) if (structure->is_string()) { // load positions from chemical structure file auto particles = loadStructure(structure->get(), false); - positions = - particles | ranges::cpp20::views::transform(&Particle::pos) | ranges::to_vector; + positions = particles | std::views::transform(&Particle::pos) | ranges::to_vector; } else if (structure->is_array()) { // list of positions @@ -3049,8 +3053,7 @@ double ElectricPotential::calcPotentialOnTarget(const ElectricPotential::Target& std::sqrt(spc.geometry.sqdist(particle.pos, target.position)); return coulomb->getCoulombGalore().ion_potential(particle.charge, distance_to_target); }; - auto potentials = - spc.activeParticles() | ranges::cpp20::views::transform(potential_from_particle); + auto potentials = spc.activeParticles() | std::views::transform(potential_from_particle); return std::accumulate(potentials.begin(), potentials.end(), 0.0); } diff --git a/src/atomdata.h b/src/atomdata.h index 63159143c..543833f7e 100644 --- a/src/atomdata.h +++ b/src/atomdata.h @@ -1,9 +1,8 @@ #pragma once #include "core.h" #include -#include -#include -#include +#include +#include #include namespace Faunus { @@ -121,7 +120,7 @@ template concept RequireNamedElements = requires(T db) { { db.begin() }; { db.begin()->name } -> std::convertible_to; - { std::is_integral_v::index_type> }; + { std::is_integral_v::index_type> }; }; /** @@ -178,10 +177,10 @@ AtomData& findAtomByName(std::string_view name); template auto names2ids(const T& database, const std::vector& names) { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; auto is_wildcard = [](auto& name) { return name == "*"; }; - if (ranges::cpp20::any_of(names, is_wildcard)) { // return all id's from database + if (std::ranges::any_of(names, is_wildcard)) { // return all id's from database return database | rv::transform([](auto& i) { return i.id(); }) | ranges::to_vector; } diff --git a/src/aux/arange.h b/src/aux/arange.h index 10ea398f3..8bfbbb7ac 100644 --- a/src/aux/arange.h +++ b/src/aux/arange.h @@ -21,8 +21,7 @@ OTHER DEALINGS IN THE SOFTWARE. #pragma once #include #include -#include -#include +#include #include namespace Faunus { @@ -54,8 +53,8 @@ template constexpr auto arange(const T start, const T stop, const T using int_type = typename std::conditional, T, int>::type; const auto length = static_cast(std::ceil((stop - start) / static_cast(step))); - return ranges::cpp20::views::iota(int_type(0), length) | - ranges::cpp20::views::transform( + return std::views::iota(int_type(0), length) | + std::views::transform( [start, step](auto i) -> T { return start + static_cast(i) * step; }); } @@ -65,7 +64,7 @@ TEST_CASE("[Faunus] arange") { auto r = arange(4.0, 10.0, 1.0); // --> 4 5 6 7 8 9 auto pos = r.begin(); - CHECK_EQ(ranges::size(r), 6); + CHECK_EQ(std::ranges::size(r), 6); CHECK_EQ(*(pos++), doctest::Approx(4.0)); CHECK_EQ(*(pos++), doctest::Approx(5.0)); CHECK_EQ(*(pos++), doctest::Approx(6.0)); @@ -77,7 +76,7 @@ TEST_CASE("[Faunus] arange") { auto r = arange(4, 10, 1); // --> 4 5 6 7 8 9 auto pos = r.begin(); - CHECK_EQ(ranges::size(r), 6); + CHECK_EQ(std::ranges::size(r), 6); CHECK_EQ(*(pos++), 4); CHECK_EQ(*(pos++), 5); CHECK_EQ(*(pos++), 6); @@ -89,7 +88,7 @@ TEST_CASE("[Faunus] arange") { auto r = arange(4.0, 20.0, 3.0); // --> 4 7 10 13 16 19 auto pos = r.begin(); - CHECK_EQ(ranges::size(r), 6); + CHECK_EQ(std::ranges::size(r), 6); CHECK_EQ(*(pos++), doctest::Approx(4.0)); CHECK_EQ(*(pos++), doctest::Approx(7.0)); CHECK_EQ(*(pos++), doctest::Approx(10.0)); @@ -101,7 +100,7 @@ TEST_CASE("[Faunus] arange") { auto r = arange(4, 20, 3); // --> 4 7 10 13 16 19 auto pos = r.begin(); - CHECK_EQ(ranges::size(r), 6); + CHECK_EQ(std::ranges::size(r), 6); CHECK_EQ(*(pos++), 4); CHECK_EQ(*(pos++), 7); CHECK_EQ(*(pos++), 10); @@ -114,7 +113,7 @@ TEST_CASE("[Faunus] arange") { auto r = arange(-1.0, 1.0, 0.5); // --> -1 -0.5 0 0.5 auto pos = r.begin(); - CHECK_EQ(ranges::size(r), 4); + CHECK_EQ(std::ranges::size(r), 4); CHECK_EQ(*(pos++), doctest::Approx(-1.0)); CHECK_EQ(*(pos++), doctest::Approx(-0.5)); CHECK_EQ(*(pos++), doctest::Approx(0.0)); diff --git a/src/auxiliary.h b/src/auxiliary.h index 1c3d3fe99..513e495ff 100644 --- a/src/auxiliary.h +++ b/src/auxiliary.h @@ -1,7 +1,7 @@ #pragma once #include "average.h" #include -#include +#include #include #include #include @@ -66,7 +66,7 @@ T for_each_unique_pair(Titer begin, Titer end, Tfunction f, } /** @brief Erase from `target` range all values found in `values` range */ -template T erase_range(T target, const T& values) +template T erase_range(T target, const T& values) { target.erase(std::remove_if(target.begin(), target.end(), [&](auto i) { @@ -222,9 +222,9 @@ template auto splitConvert(const std::string& words) * @param values Range (vector, set, ...) of values to convert * @return String with space sepatated values */ -template +template std::string joinToString(const Range& values) - requires StringStreamable> + requires StringStreamable> { std::ostringstream o; if (!values.empty()) { diff --git a/src/celllistimpl.h b/src/celllistimpl.h index 7182ba004..54e437d48 100644 --- a/src/celllistimpl.h +++ b/src/celllistimpl.h @@ -15,8 +15,7 @@ #include #include #include -#include -#include +#include #include "celllist.h" #include "core.h" #include @@ -682,9 +681,8 @@ class CellListBase std::vector getCells() const override { const auto indices = this->indices(); - return ranges::cpp20::views::all(indices) | - ranges::cpp20::views::transform( - [this](auto index) { return this->coordinates(index); }) | + return std::views::all(indices) | + std::views::transform([this](auto index) { return this->coordinates(index); }) | ranges::to_vector; } diff --git a/src/clustermove.cpp b/src/clustermove.cpp index eb21adafa..b338261e8 100644 --- a/src/clustermove.cpp +++ b/src/clustermove.cpp @@ -1,8 +1,8 @@ #include "clustermove.h" #include "aux/eigensupport.h" +#include #include #include -#include namespace Faunus { namespace move { @@ -96,7 +96,7 @@ double FindCluster::clusterProbability(const Group& group1, const Group& group2) */ void FindCluster::updateMoleculeIndex() { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; auto group_to_index = [&](auto& group) { return &group - &spc.groups.front(); }; auto matching_molid = [&](auto& group) { if (group.isAtomic() || group.end() != group.trueend()) { @@ -174,8 +174,8 @@ std::optional FindCluster::findSeed(Random& random) auto avoid_satellites = [&](auto index) { return (satellites.count(spc.groups.at(index).id) == 0); }; - auto not_satellites = molecule_index | ranges::cpp20::views::filter(avoid_satellites); - if (ranges::cpp20::empty(not_satellites)) { + auto not_satellites = molecule_index | std::views::filter(avoid_satellites); + if (std::ranges::empty(not_satellites)) { return std::nullopt; } return *random.sample(not_satellites.begin(), not_satellites.end()); @@ -190,7 +190,7 @@ std::optional FindCluster::findSeed(Random& random) */ std::pair, bool> FindCluster::findCluster(size_t seed_index) { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; assert(seed_index < spc.particles.size()); std::set pool(molecule_index.begin(), molecule_index.end()); // decreasing pool of candidate groups @@ -301,12 +301,12 @@ void Cluster::_from_json(const json& j) Point Cluster::clusterMassCenter(const std::vector& indices) const { assert(!indices.empty()); - namespace rv = ranges::cpp20::views; - auto groups = indices | rv::transform(index_to_group); - auto positions = groups | rv::transform(&Group::mass_center); - auto masses = groups | rv::transform(&Group::mass); + using std::views::transform; + auto groups = indices | transform(index_to_group); + auto positions = groups | transform(&Group::mass_center); + auto masses = groups | transform(&Group::mass); return Geometry::weightedCenter(positions, masses, spc.geometry.getBoundaryFunc(), - -groups.begin()->mass_center); + -((*groups.begin()).mass_center)); } void Cluster::_move(Change& change) @@ -318,14 +318,14 @@ void Cluster::_move(Change& change) } const auto [cluster, safe_to_rotate] = find_cluster->findCluster(seed_index.value()); const Point cluster_mass_center = clusterMassCenter(cluster); // cluster mass center - auto groups = cluster | ranges::cpp20::views::transform(index_to_group); + auto groups = cluster | std::views::transform(index_to_group); average_cluster_size += cluster.size(); // average cluster size if (number_of_attempted_moves % shape_analysis_interval == 0) { shape_analysis->sample(groups, cluster_mass_center, spc); } - using ranges::cpp20::for_each; + using std::ranges::for_each; auto boundary = spc.geometry.getBoundaryFunc(); if (safe_to_rotate) { for_each(groups, rotate->getLambda(boundary, cluster_mass_center, slump)); diff --git a/src/clustermove.h b/src/clustermove.h index 5d7f60e35..524fb061d 100644 --- a/src/clustermove.h +++ b/src/clustermove.h @@ -30,7 +30,7 @@ class ClusterShapeAnalysis const Range& groups, const Point& mass_center_of_groups, const Geometry::BoundaryFunction boundary = [](auto&) {}) { - using namespace ranges::cpp20::views; + using std::views::transform; auto positions = groups | transform(&Group::mass_center); auto masses = groups | transform(&Group::mass); return Geometry::gyration(positions.begin(), positions.end(), masses.begin(), diff --git a/src/core.cpp b/src/core.cpp index cb386302f..2140a1efa 100644 --- a/src/core.cpp +++ b/src/core.cpp @@ -10,8 +10,7 @@ #include #include #include -#include -#include +#include #include namespace Faunus { @@ -362,7 +361,7 @@ TEST_CASE("[Faunus] infinite/nan") TEST_CASE("[Faunus] distance") { std::vector v = {10, 20, 30, 40, 30}; - auto rng = v | ranges::cpp20::views::filter([](auto i) { return i == 30; }); + auto rng = v | std::views::filter([](auto i) { return i == 30; }); CHECK_EQ(Faunus::distance(v.begin(), rng.begin()), 2); auto it = rng.begin(); CHECK_EQ(Faunus::distance(v.begin(), ++it), 4); @@ -406,7 +405,7 @@ Electrolyte::Electrolyte(const double molarity, const std::vector& valencie : molarity(molarity) , valencies(valencies) { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; const auto sum_positive = ranges::accumulate(valencies | rv::filter([](auto v) { return v > 0; }), 0); const auto sum_negative = diff --git a/src/core.h b/src/core.h index cdb664c11..4ba14f4ab 100644 --- a/src/core.h +++ b/src/core.h @@ -6,6 +6,7 @@ #include #include #include +#include // forward declare logger namespace spdlog { @@ -25,7 +26,7 @@ class Random; /** Concept for a range of points */ template concept RequirePoints = - ranges::cpp20::range && std::is_same_v, Point>; + std::ranges::range && std::is_same_v, Point>; /** Concept for an iterator to a `Point` */ template diff --git a/src/energy.cpp b/src/energy.cpp index 8c5423311..1eb21c704 100644 --- a/src/energy.cpp +++ b/src/energy.cpp @@ -4,8 +4,6 @@ #include "externalpotential.h" #include #include -#include -#include #include #include #include @@ -229,7 +227,7 @@ void PolicyIonIon::updateComplex(EwaldData& d, const Change& change, auto& g_new = groups.at(changed_group.group_index); auto& g_old = oldgroups.at(changed_group.group_index); const auto max_group_size = std::max(g_new.size(), g_old.size()); - auto indices = (changed_group.all) ? ranges::cpp20::views::iota(0u, max_group_size) | + auto indices = (changed_group.all) ? std::views::iota(0u, max_group_size) | ranges::to> : changed_group.relative_atom_indices; for (auto i : indices) { @@ -466,7 +464,7 @@ void PolicyIonIonIPBC::updateComplex(EwaldData& d, const Change& change, double PolicyIonIon::surfaceEnergy(const EwaldData& data, [[maybe_unused]] const Change& change, const Space::GroupVector& groups) { - namespace rv = ranges::cpp20::views; + using ranges::cpp20::views::join; if (data.const_inf < 0.5 || change.empty()) { return 0.0; } @@ -474,7 +472,7 @@ double PolicyIonIon::surfaceEnergy(const EwaldData& data, [[maybe_unused]] const auto charge_x_position = [](const Particle& particle) -> Point { return particle.charge * particle.pos; }; - auto qr_range = groups | rv::join | rv::transform(charge_x_position); + auto qr_range = groups | join | std::views::transform(charge_x_position); const auto qr_squared = ranges::accumulate(qr_range, Point(0, 0, 0)).squaredNorm(); return data.const_inf * 2.0 * pc::pi / ((2.0 * data.surface_dielectric_constant + 1.0) * volume) * qr_squared * @@ -817,7 +815,7 @@ double ContainerOverlap::energy(const Change& change) double ContainerOverlap::energyOfAllGroups() const { auto positions = - spc.groups | ranges::cpp20::views::join | ranges::cpp20::views::transform(&Particle::pos); + spc.groups | ranges::cpp20::views::join | std::views::transform(&Particle::pos); bool outside = std::any_of(positions.begin(), positions.end(), [&](const auto& position) { return spc.geometry.collision(position); }); @@ -890,8 +888,8 @@ double Isobaric::energy(const Change& change) auto count_particles = [](const auto& group) { return group.isAtomic() ? group.size() : 1; }; - auto particles_per_group = spc.groups | ranges::cpp20::views::filter(group_is_active) | - ranges::cpp20::views::transform(count_particles); + auto particles_per_group = spc.groups | std::views::filter(group_is_active) | + std::views::transform(count_particles); auto number_of_particles = std::accumulate(particles_per_group.begin(), particles_per_group.end(), 0); const auto volume = spc.geometry.getVolume(); @@ -1067,7 +1065,6 @@ double Bonded::energy(const Change& change) double Bonded::internalGroupEnergy(const Change::GroupChange& changed) { - using namespace ranges::cpp20::views; // @todo cpp20 --> std::ranges double energy = 0.0; const auto& group = spc.groups.at(changed.group_index); if (changed.internal && !group.empty()) { @@ -1077,9 +1074,10 @@ double Bonded::internalGroupEnergy(const Change::GroupChange& changed) } else { // only partial update of affected atoms const auto first_particle_index = spc.getFirstParticleIndex(group); - auto particle_indices = - changed.relative_atom_indices | - transform([first_particle_index](auto i) { return i + first_particle_index; }); + auto particle_indices = changed.relative_atom_indices | + std::views::transform([first_particle_index](auto i) { + return i + first_particle_index; + }); energy += sumEnergy(bonds, particle_indices); } } @@ -1215,8 +1213,8 @@ void Hamiltonian::checkBondedMolecules() const if (find() .empty()) { // no bond potential added? issue warning if molecules w. bonds auto molecules_with_bonds = - Faunus::molecules | ranges::cpp20::views::filter( - [](const auto& molecule) { return !molecule.bonds.empty(); }); + Faunus::molecules | + std::views::filter([](const auto& molecule) { return !molecule.bonds.empty(); }); for (const auto& molecule : molecules_with_bonds) { faunus_logger->warn("{} bonds specified in topology but missing in energy", molecule.name); @@ -1463,7 +1461,7 @@ void FreeSASAEnergy::sync(EnergyTerm* energybase_ptr, const Change& change) const auto offset = spc.getFirstActiveParticleIndex(group); auto absolute_atom_index = group_change.relative_atom_indices | - ranges::cpp20::views::transform([offset](auto i) { return i + offset; }); + std::views::transform([offset](auto i) { return i + offset; }); for (auto i : absolute_atom_index) { radii.at(i) = other->radii.at(i); for (size_t k = 0; k < 3; ++k) { @@ -1635,14 +1633,13 @@ double SASAEnergyReference::energy(const Change& change) std::vector target_indices; auto to_index = [this](const auto& particle) { return indexOf(particle); }; - target_indices = - particles | ranges::cpp20::views::transform(to_index) | ranges::to; + target_indices = particles | std::views::transform(to_index) | ranges::to; const auto neighbours = sasa->calcNeighbourData(spc, target_indices); sasa->updateSASA(neighbours, target_indices); const auto& new_areas = sasa->getAreas(); - ranges::cpp20::for_each(target_indices, [this, &new_areas](const auto index) { + std::ranges::for_each(target_indices, [this, &new_areas](const auto index) { areas.at(index) = new_areas.at(index); }); @@ -1650,7 +1647,7 @@ double SASAEnergyReference::energy(const Change& change) energy += areas.at(indexOf(particle)) * (particle.traits().tension + cosolute_molarity * particle.traits().tfe); }; - ranges::cpp20::for_each(particles, accumulate_energy); + std::ranges::for_each(particles, accumulate_energy); return energy; } @@ -1700,14 +1697,13 @@ void SASAEnergy::updateChangedIndices(const Change& change) }; if (group_change.relative_atom_indices.empty()) { - const auto indices = ranges::cpp20::views::iota(offset, group.size() + offset); - ranges::cpp20::for_each(indices, insert_changed); + const auto indices = std::views::iota(offset, group.size() + offset); + std::ranges::for_each(indices, insert_changed); } else { - const auto indices = - group_change.relative_atom_indices | - ranges::cpp20::views::transform([offset](auto i) { return offset + i; }); - ranges::cpp20::for_each(indices, insert_changed); + const auto indices = group_change.relative_atom_indices | + std::views::transform([offset](auto i) { return offset + i; }); + std::ranges::for_each(indices, insert_changed); } } changed_indices.assign(target_indices.begin(), target_indices.end()); @@ -1742,8 +1738,7 @@ double SASAEnergy::energy(const Change& change) changed_indices.clear(); if (change.everything) { //! all the active particles will be used for SASA calculation auto to_index = [this](const auto& particle) { return indexOf(particle); }; - changed_indices = - particles | ranges::cpp20::views::transform(to_index) | ranges::to; + changed_indices = particles | std::views::transform(to_index) | ranges::to; } else { updateChangedIndices(change); @@ -1765,7 +1760,7 @@ double SASAEnergy::energy(const Change& change) energy += areas.at(indexOf(particle)) * (particle.traits().tension + cosolute_molarity * particle.traits().tfe); }; - ranges::cpp20::for_each(particles, accumulate_energy); + std::ranges::for_each(particles, accumulate_energy); return energy; } @@ -1780,10 +1775,10 @@ void SASAEnergy::sync(EnergyTerm* energybase_ptr, const Change& change) if (state == MonteCarloState::TRIAL) { //! changed_indices get updated only in TRIAL state //! for speedup - ranges::for_each(this->changed_indices, sync_data); + std::ranges::for_each(this->changed_indices, sync_data); } else { - ranges::for_each(other->changed_indices, sync_data); + std::ranges::for_each(other->changed_indices, sync_data); } if (sasa->needs_syncing) { @@ -2092,10 +2087,10 @@ double CustomGroupGroup::energy([[maybe_unused]] const Change& change) }; // all indices matching either molid1 or molid2 - auto indices = spc.groups | ranges::cpp20::views::filter(match_groups) | - ranges::cpp20::views::transform( - [&](const auto& group) { return spc.getGroupIndex(group); }) | - ranges::to_vector; + auto indices = + spc.groups | std::views::filter(match_groups) | + std::views::transform([&](const auto& group) { return spc.getGroupIndex(group); }) | + ranges::to_vector; return for_each_unique_pair(indices.begin(), indices.end(), group_group_energy, std::plus<>()); } diff --git a/src/energy.h b/src/energy.h index 8e0f983b7..e1e22b4d4 100644 --- a/src/energy.h +++ b/src/energy.h @@ -9,11 +9,9 @@ #include "aux/pairmatrix.h" #include "smart_montecarlo.h" #include -#include -#include -#include #include #include +#include #include #include #include @@ -174,7 +172,7 @@ class EwaldPolicyBase auto is_partially_inactive = [](const Group& group) { return group.size() != group.capacity(); }; - if (ranges::cpp20::any_of(groups, is_partially_inactive)) { + if (std::ranges::any_of(groups, is_partially_inactive)) { throw std::runtime_error("Eigen optimized Ewald not available with inactive groups"); } auto first_particle = groups.front().begin(); @@ -191,7 +189,7 @@ class EwaldPolicyBase auto is_partially_inactive = [](const Group& group) { return group.size() != group.capacity(); }; - if (ranges::cpp20::any_of(groups, is_partially_inactive)) { + if (std::ranges::any_of(groups, is_partially_inactive)) { throw std::runtime_error("Eigen optimized Ewald not available with inactive groups"); } auto first_particle = groups.front().begin(); @@ -342,7 +340,7 @@ class Bonded : public EnergyTerm double sumBondEnergy(const BondVector& bonds) const; //!< sum energy in vector of BondData double internalGroupEnergy(const Change::GroupChange& changed); //!< Energy from internal bonds double sumEnergy(const BondVector& bonds, - const ranges::cpp20::range auto& particle_indices) const; + const std::ranges::range auto& particle_indices) const; void updateInternalBonds(); //!< finds and adds all intra-molecular bonds of active molecules public: @@ -363,15 +361,15 @@ class Bonded : public EnergyTerm * to simplistic search which scales as number_of_bonds x number_of_moved_particles */ double Bonded::sumEnergy(const Bonded::BondVector& bonds, - const ranges::cpp20::range auto& particle_indices) const + const std::ranges::range auto& particle_indices) const { assert(std::is_sorted(particle_indices.begin(), particle_indices.end())); auto index_is_included = [&](auto index) { return std::binary_search(particle_indices.begin(), particle_indices.end(), index); }; - auto affected_bonds = bonds | ranges::cpp20::views::filter([&](const auto& bond) { - return ranges::cpp20::any_of(bond->indices, index_is_included); + auto affected_bonds = bonds | std::views::filter([&](const auto& bond) { + return std::ranges::any_of(bond->indices, index_is_included); }); auto bond_energy = [dist = spc.geometry.getDistanceFunc()](const auto& bond) { return bond->energyFunc(dist); @@ -388,11 +386,11 @@ double Bonded::sumEnergy(const Bonded::BondVector& bonds, * @param range an original set of integers (must be sorted) * @return a set of ints complementary to the original set */ -auto indexComplement(std::integral auto size, const ranges::cpp20::range auto& range) +auto indexComplement(std::integral auto size, const std::ranges::range auto& range) { - namespace rv = ranges::cpp20::views; - return rv::iota(0, static_cast(size)) | - rv::filter([&](auto i) { return !std::binary_search(range.begin(), range.end(), i); }); + using namespace std::views; + return iota(0, static_cast(size)) | + filter([&](auto i) { return !std::binary_search(range.begin(), range.end(), i); }); } /** @@ -1400,7 +1398,7 @@ template class GroupPairing const auto fixed = indexComplement(spc.groups.size(), moved) | ranges::to; // index of static groups auto filter_active = [](int size) { - return ranges::views::filter([size](const auto i) { return i < size; }); + return std::views::filter([size](const auto i) { return i < size; }); }; // loop over all changed groups diff --git a/src/geometry.cpp b/src/geometry.cpp index 6bba9aa24..21e4060d4 100644 --- a/src/geometry.cpp +++ b/src/geometry.cpp @@ -1583,7 +1583,7 @@ std::vector TwobodyAngles::fibonacciSphere(const size_t samples) TwobodyAngles::TwobodyAngles(const double angle_resolution) { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; const auto number_of_samples = size_t(std::round(4.0 * pc::pi / std::pow(angle_resolution, 2))); const auto points_on_sphere = fibonacciSphere(number_of_samples); diff --git a/src/geometry.h b/src/geometry.h index 187506717..dd1c01c16 100644 --- a/src/geometry.h +++ b/src/geometry.h @@ -9,10 +9,12 @@ #include #include #include +#include +#include #include +#ifndef __cpp_lib_ranges_join_with #include -#include -#include +#endif #include /** @brief Faunus main namespace */ @@ -548,7 +550,7 @@ enum class weight * @param boundary Used to remove periodic boundaries * @param shift Shift with this value before and after center calculation. To e.g. remove PBC */ -template +template Point weightedCenter( const Positions& positions, const Weights& weights, Geometry::BoundaryFunction boundary = [](auto&) {}, const Point& shift = Point::Zero()) @@ -589,8 +591,8 @@ Point weightedCenter(iterator begin, iterator end, BoundaryFunction boundary, std::function weight_function, const Point& shift = Point::Zero()) { - namespace rv = ranges::cpp20::views; - auto particles = ranges::make_subrange(begin, end); + namespace rv = std::views; + auto particles = std::ranges::subrange(begin, end); auto positions = particles | rv::transform(&Particle::pos); auto weights = particles | rv::transform(weight_function); return weightedCenter(positions, weights, boundary, shift); @@ -684,8 +686,13 @@ Point trigoCom(const Tspace& spc, const GroupIndex& indices, if (dir.empty() || dir.size() > 3) { throw std::out_of_range("invalid directions"); } - namespace rv = ranges::cpp20::views; - auto positions = indices | rv::transform([&](auto i) { return spc.groups.at(i); }) | rv::join | + namespace rv = std::views; +#ifdef __cpp_lib_ranges_join_with + using std::views::join; +#else + using ranges::cpp20::views::join; +#endif + auto positions = indices | rv::transform([&](auto i) { return spc.groups.at(i); }) | join | rv::transform(&Particle::pos); Point xhi(0, 0, 0); Point zeta(0, 0, 0); @@ -774,8 +781,8 @@ Tensor gyration( iterator begin, iterator end, const Point& mass_center, const BoundaryFunction boundary = [](auto&) {}) { - namespace rv = ranges::cpp20::views; - auto particles = ranges::make_subrange(begin, end); + namespace rv = std::views; + auto particles = std::ranges::subrange(begin, end); auto positions = particles | rv::transform(&Particle::pos); auto masses = particles | rv::transform(&Particle::traits) | rv::transform(&AtomData::mw); return gyration(positions.begin(), positions.end(), masses.begin(), mass_center, boundary); @@ -945,7 +952,7 @@ class TwobodyAngles return q_dihedral * q2; // noncommutative }; auto second_body_quaternions = - rv::cartesian_product(quaternions_2, dihedrals) | rv::transform(product); + rv::cartesian_product(quaternions_2, dihedrals) | std::views::transform(product); return rv::cartesian_product(quaternions_1, second_body_quaternions); } diff --git a/src/group.h b/src/group.h index 75cf1fa5e..69451c178 100644 --- a/src/group.h +++ b/src/group.h @@ -3,9 +3,7 @@ #include "particle.h" #include "molecule.h" #include "geometry.h" -#include -#include -#include +#include #include #include @@ -103,19 +101,14 @@ template class ElasticRange : public IterRange return (new_size >= 0 && new_size <= capacity()); } - /* - * @note On Apple Clang 12.0.5 (Nov. 2021) template deduction is unavailable, and we have to use - * `make_subrange()`. With GCC `cpp20::subrange()` can be used. More info here: - * https://stackoverflow.com/questions/58316189/in-ranges-v3-how-do-i-create-a-range-from-a-pair-of-iterators - */ inline auto all() { - return ranges::make_subrange(begin(), trueend()); + return std::ranges::subrange(begin(), trueend()); } //!< Active and inactive elements [[nodiscard]] inline auto all() const { - return ranges::make_subrange(begin(), trueend()); + return std::ranges::subrange(begin(), trueend()); } //!< Active and inactive elements }; @@ -299,15 +292,14 @@ class Group : public ElasticRange auto positions() { - return ranges::make_subrange(begin(), end()) | - ranges::cpp20::views::transform( - [&](Particle& particle) -> Point& { return particle.pos; }); + return std::ranges::subrange(begin(), end()) | + std::views::transform([&](Particle& particle) -> Point& { return particle.pos; }); } //!< Range of positions of active particles [[nodiscard]] auto positions() const { - return ranges::make_subrange(begin(), end()) | - ranges::cpp20::views::transform( + return std::ranges::subrange(begin(), end()) | + std::views::transform( [&](const Particle& particle) -> const Point& { return particle.pos; }); } //!< Range of positions of active particles @@ -317,8 +309,8 @@ class Group : public ElasticRange [[nodiscard]] auto findAtomID(AtomData::index_type atomid) const { - return *this | ranges::cpp20::views::filter( - [atomid](auto& particle) { return (particle.id == atomid); }); + return *this | + std::views::filter([atomid](auto& particle) { return (particle.id == atomid); }); } //!< Range of all (active) elements with matching particle id /** @@ -346,8 +338,8 @@ class Group : public ElasticRange assert(*std::max_element(indices.begin(), indices.end()) < size()); } #endif - return indices | ranges::cpp20::views::transform( - [this](auto i) -> Particle& { return *(begin() + i); }); + return indices | + std::views::transform([this](auto i) -> Particle& { return *(begin() + i); }); } /** @@ -436,6 +428,6 @@ template void load(Archive& archive, Group& group, std::uint32_t /** Concept for a range of groups */ template concept RequireGroups = - ranges::cpp20::range && std::is_convertible_v, Group>; + std::ranges::range && std::is_convertible_v, Group>; } // namespace Faunus diff --git a/src/io.h b/src/io.h index ba9e42074..1b3ce6d85 100644 --- a/src/io.h +++ b/src/io.h @@ -8,9 +8,8 @@ #include #include #include -#include -#include #include +#include namespace cereal { class BinaryOutputArchive; @@ -258,12 +257,12 @@ class StructureFileWriter particle_index = 0; box_dimensions = box_length; - auto group_sizes = groups | ranges::cpp20::views::transform(&Group::capacity); + auto group_sizes = groups | std::views::transform(&Group::capacity); const auto number_of_particles = std::accumulate(group_sizes.begin(), group_sizes.end(), 0u); saveHeader(stream, number_of_particles); - ranges::cpp20::for_each(groups, [&](const auto& group) { saveGroup(stream, group); }); + std::ranges::for_each(groups, [&](const auto& group) { saveGroup(stream, group); }); saveFooter(stream); } @@ -494,7 +493,7 @@ struct XTCTrajectoryFrame void importCoordinates(begin_iterator begin, end_iterator end, const Point& offset) const { int i = 0; - ranges::cpp20::for_each(begin, end, [&](const auto& position) { + std::ranges::for_each(begin, end, [&](const auto& position) { if (i >= number_of_atoms) { throw std::runtime_error("too many particles for XTC frame"); } @@ -704,7 +703,7 @@ class XTCWriter void writeNext(const Point& box, begin_iterator coordinates_begin, end_iterator coordinates_end) { if (!xtc_frame) { - auto number_of_atoms = ranges::cpp20::distance(coordinates_begin, coordinates_end); + auto number_of_atoms = std::ranges::distance(coordinates_begin, coordinates_end); faunus_logger->trace("preparing xtc output for {} particles", number_of_atoms); xtc_frame = std::make_unique(number_of_atoms); } diff --git a/src/molecule.cpp b/src/molecule.cpp index 8c7ee56de..760fa75bc 100644 --- a/src/molecule.cpp +++ b/src/molecule.cpp @@ -10,8 +10,6 @@ #include #include #include -#include -#include #include #include @@ -292,7 +290,7 @@ void NeighboursGenerator::generatePairs(AtomPairList& pairs, int bond_distance) paths | join | transform(make_ordered_pair) | filter(is_valid_pair) | ranges::to>; pairs.reserve(pairs.size() + excluded_pairs.size()); - std::copy(excluded_pairs.begin(), excluded_pairs.end(), std::back_inserter(pairs)); + std::ranges::copy(excluded_pairs, std::back_inserter(pairs)); } TEST_CASE("NeighboursGenerator") @@ -512,7 +510,7 @@ void MoleculeBuilder::readBonds(const json& j) bonds = j.value("bondlist", bonds); auto is_invalid_index = [size = particles.size()](auto& i) { return i >= size || i < 0; }; auto indices = bonds | views::transform(&pairpotential::BondData::indices) | views::join; - if (any_of(indices, is_invalid_index)) { + if (std::ranges::any_of(indices, is_invalid_index)) { throw ConfigurationError("bonded index out of range"); } } @@ -853,7 +851,7 @@ RandomInserter::operator()(const Geometry::GeometryBase& geo, MoleculeData& mole auto container_overlap = [&geo](const auto& particle) { return geo.collision(particle.pos); }; if (keep_positions) { // keep given positions - if (ranges::cpp20::none_of(particles, container_overlap)) { + if (std::ranges::none_of(particles, container_overlap)) { return particles; } throw std::runtime_error("inserted molecule does not fit in container"); @@ -866,7 +864,7 @@ RandomInserter::operator()(const Geometry::GeometryBase& geo, MoleculeData& mole else { translateRotateMolecularGroup(geo, rotator, particles); } - if (allow_overlap || ranges::cpp20::none_of(particles, container_overlap)) { + if (allow_overlap || std::ranges::none_of(particles, container_overlap)) { return particles; } } @@ -944,10 +942,10 @@ void Conformation::copyTo(ParticleVector& particles) const * Note how `std::ranges::transform` accepts data member pointers like `&Particle::pos` * which are internally accessed using `std::invoke`. */ - auto particle_positions = particles | ranges::cpp20::views::transform(&Particle::pos); + auto particle_positions = particles | std::views::transform(&Particle::pos); std::copy(positions.begin(), positions.end(), particle_positions.begin()); - auto particle_charges = particles | ranges::cpp20::views::transform(&Particle::charge); + auto particle_charges = particles | std::views::transform(&Particle::charge); std::copy(charges.begin(), charges.end(), particle_charges.begin()); } diff --git a/src/montecarlo.cpp b/src/montecarlo.cpp index aaaca8c71..a7b0feced 100644 --- a/src/montecarlo.cpp +++ b/src/montecarlo.cpp @@ -1,9 +1,7 @@ #include "montecarlo.h" -#include "speciation.h" #include "energy.h" #include "move.h" #include -#include namespace Faunus { @@ -221,8 +219,8 @@ void MetropolisMonteCarlo::sweep() assert(moves); number_of_sweeps++; auto perform_single_move = [&](auto& move) { performMove(*move); }; - ranges::cpp20::for_each(moves->repeatedStochasticMoves(), perform_single_move); - ranges::cpp20::for_each(moves->constantIntervalMoves(number_of_sweeps), perform_single_move); + std::ranges::for_each(moves->repeatedStochasticMoves(), perform_single_move); + std::ranges::for_each(moves->constantIntervalMoves(number_of_sweeps), perform_single_move); } Energy::Hamiltonian& MetropolisMonteCarlo::getHamiltonian() diff --git a/src/move.cpp b/src/move.cpp index 86a48bfea..c7e304935 100644 --- a/src/move.cpp +++ b/src/move.cpp @@ -9,11 +9,11 @@ #include "aux/eigensupport.h" #include #include -#include -#include -#include +#include +#include +#ifndef __cpp_lib_ranges_fold #include - +#endif namespace Faunus::move { Random Move::slump; // static instance of Random (shared for all moves) @@ -257,7 +257,7 @@ void AtomicTranslateRotate::groupToDisk(const Space::GroupType& group) const { if (auto stream = std::ofstream("mass-center-failure.pqr"); stream) { const auto group_iter = spc.groups.cbegin() + spc.getGroupIndex(group); - auto groups = ranges::cpp20::views::counted(group_iter, 1); // slice out single group + auto groups = std::views::counted(group_iter, 1); // slice out single group PQRWriter().save(stream, groups, spc.geometry.getLength()); } } @@ -572,11 +572,16 @@ double GibbsEnsembleHelper::exchange(const double value) const */ std::pair GibbsEnsembleHelper::currentNumParticles(const Space& spc) const { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; auto to_num_molecules = [&](auto molid) { return spc.numMolecules(molid); }; - const int n1 = ranges::fold_left(molids | rv::transform(to_num_molecules), 0, std::plus<>()); +#ifdef __cpp_lib_ranges_fold + using std::ranges::fold_left; +#else + using ranges::fold_left; +#endif + const int n1 = fold_left(molids | rv::transform(to_num_molecules), 0, std::plus<>()); const int n2 = total_num_particles - n1; return {n1, n2}; } @@ -842,12 +847,11 @@ void ParallelTempering::_to_json(json& j) const */ void ParallelTempering::exchangeGroupSizes(Space::GroupVector& groups, int partner_rank) { - std::vector sizes = - groups | ranges::cpp20::views::transform(&Group::size) | ranges::to_vector; + std::vector sizes = groups | std::views::transform(&Group::size) | ranges::to_vector; mpi.world.sendrecv_replace(sizes.begin(), sizes.end(), partner_rank, mpl::tag_t(0), partner_rank, mpl::tag_t(0)); auto it = sizes.begin(); - ranges::cpp20::for_each(groups, [&it](Group& group) { group.resize(*it++); }); + std::ranges::for_each(groups, [&it](Group& group) { group.resize(*it++); }); } /** @@ -1184,7 +1188,7 @@ void ChargeTransfer::_move(Change& change) { auto mollist1 = spc.findMolecules(mol1.id, Space::Selection::ACTIVE); auto mollist2 = spc.findMolecules(mol2.id, Space::Selection::ACTIVE); - if ((not ranges::cpp20::empty(mollist1)) and (not ranges::cpp20::empty(mollist2))) { + if ((not std::ranges::empty(mollist1)) and (not std::ranges::empty(mollist2))) { auto git1 = slump.sample(mollist1.begin(), mollist1.end()); // selecting a random molecule of type molecule1 auto git2 = slump.sample(mollist2.begin(), @@ -1392,7 +1396,7 @@ void QuadrantJump::_move(Change& change) // TODO: This can be slow -- implement look-up-table in Space auto mollist = spc.findMolecules(molid, Space::Selection::ACTIVE); // list of molecules w. 'molid' - if (not ranges::cpp20::empty(mollist)) { + if (not std::ranges::empty(mollist)) { auto it = slump.sample(mollist.begin(), mollist.end()); if (not it->empty()) { assert(it->id == molid); @@ -1466,7 +1470,7 @@ ParticleVector::iterator AtomicSwapCharge::randomAtom() { assert(molid >= 0); auto mollist = spc.findMolecules(molid); // all `molid` groups - if (not ranges::cpp20::empty(mollist)) { + if (not std::ranges::empty(mollist)) { auto git = slump.sample(mollist.begin(), mollist.end()); // random molecule iterator if (!git->empty()) { auto p = slump.sample(git->begin(), git->end()); // random particle iterator @@ -1584,7 +1588,7 @@ void TranslateRotate::_from_json(const json& j) TranslateRotate::OptionalGroup TranslateRotate::findRandomMolecule() { if (auto mollist = spc.findMolecules(molid, Space::Selection::ACTIVE); - not ranges::cpp20::empty(mollist)) { + not std::ranges::empty(mollist)) { if (auto group_it = random.sample(mollist.begin(), mollist.end()); not group_it->empty()) { return *group_it; } @@ -1921,7 +1925,7 @@ void ConformationSwap::checkConformationSize() const size_t conformation_id = 0; for (const auto& conformation : Faunus::molecules.at(molid).conformations.data) { - const auto positions = conformation | ranges::cpp20::views::transform(&Particle::pos); + const auto positions = conformation | std::views::transform(&Particle::pos); const auto max_separation = find_max_distance(positions); if (max_separation > max_allowed_separation) { faunus_logger->warn( diff --git a/src/move.h b/src/move.h index 280071cf0..f7eccbf91 100644 --- a/src/move.h +++ b/src/move.h @@ -11,8 +11,8 @@ #include "aux/sparsehistogram.h" #include #include +#include #include -#include #include namespace Faunus { @@ -639,10 +639,10 @@ class MoveCollection auto is_valid_and_stochastic = [&](auto move) { return move < moves.end() && (*move)->isStochastic(); }; - return ranges::cpp20::views::iota(0U, number_of_moves_per_sweep) | - ranges::cpp20::views::transform( - [&]([[maybe_unused]] auto count) { return sample(); }) | - ranges::cpp20::views::filter(is_valid_and_stochastic) | + using namespace ranges::cpp20; + return views::iota(0U, number_of_moves_per_sweep) | + views::transform([&]([[maybe_unused]] auto count) { return sample(); }) | + views::filter(is_valid_and_stochastic) | ranges::views::indirect; // dereference iterator } @@ -664,7 +664,7 @@ class MoveCollection auto is_static_and_time_to_sample = [&, sweep_number](const auto& move) { return (!move->isStochastic()) && (sweep_number % move->sweep_interval == 0); }; - return moves | ranges::cpp20::views::filter(is_static_and_time_to_sample); + return moves | std::views::filter(is_static_and_time_to_sample); } }; diff --git a/src/mpicontroller.cpp b/src/mpicontroller.cpp index a4af97c74..7332e0b3b 100644 --- a/src/mpicontroller.cpp +++ b/src/mpicontroller.cpp @@ -1,5 +1,4 @@ #include "mpicontroller.h" -#include #include #include @@ -99,7 +98,7 @@ void ParticleBuffer::setFormat(ParticleBuffer::Format data_format) case Format::XYZ: packet_size = 3; from_particle = [&](auto& particle, auto& destination) { - ranges::cpp20::copy(particle.pos, destination); + std::ranges::copy(particle.pos, destination); std::advance(destination, 3); }; to_particle = [&](auto& source, auto& particle) { @@ -110,7 +109,7 @@ void ParticleBuffer::setFormat(ParticleBuffer::Format data_format) case Format::XYZQ: packet_size = 4; from_particle = [&](auto& particle, auto& destination) { - ranges::cpp20::copy(particle.pos, destination); + std::ranges::copy(particle.pos, destination); std::advance(destination, 3); *(destination++) = particle.charge; }; @@ -123,7 +122,7 @@ void ParticleBuffer::setFormat(ParticleBuffer::Format data_format) case Format::XYZQI: packet_size = 5; from_particle = [&](auto& particle, auto& destination) { - ranges::cpp20::copy(particle.pos, destination); + std::ranges::copy(particle.pos, destination); std::advance(destination, 3); *(destination++) = particle.charge; *(destination++) = static_cast(particle.id); @@ -144,8 +143,8 @@ void ParticleBuffer::copyToBuffer(const ParticleVector& particles) { buffer.resize(packet_size * particles.size()); auto destination = buffer.begin(); // set *after* buffer resize - ranges::cpp20::for_each(particles, - std::bind(from_particle, std::placeholders::_1, std::ref(destination))); + std::ranges::for_each(particles, + std::bind(from_particle, std::placeholders::_1, std::ref(destination))); if (destination != buffer.end()) { throw std::runtime_error("buffer mismatch"); } @@ -157,8 +156,8 @@ void ParticleBuffer::copyFromBuffer(ParticleVector& particles) throw std::out_of_range("particles out of range"); } auto source = buffer.begin(); - ranges::cpp20::for_each(particles, - std::bind(to_particle, std::ref(source), std::placeholders::_1)); + std::ranges::for_each(particles, + std::bind(to_particle, std::ref(source), std::placeholders::_1)); assert(source == buffer.end()); } diff --git a/src/mpicontroller.h b/src/mpicontroller.h index 376c1e265..e9d5fb40b 100644 --- a/src/mpicontroller.h +++ b/src/mpicontroller.h @@ -7,13 +7,10 @@ #include "core.h" #include "particle.h" #include "geometry.h" - #include #include -#include -#include -#include #include +#include // Expose classes for MPI serialization MPL_REFLECTION(Faunus::Point, x(), y(), z()) @@ -232,18 +229,17 @@ void avgTables(const mpl::communicator& communicator, Ttable& table, int& size) else { send_buffer = table.hist2buf(size); recv_buffer.resize(size); - auto slaves = - ranges::cpp20::views::iota(0, communicator.size()) | - ranges::cpp20::views::filter([&](auto rank) { return rank != mpi.master_rank; }); + auto slaves = std::views::iota(0, communicator.size()) | + std::views::filter([&](auto rank) { return rank != mpi.master_rank; }); - ranges::cpp20::for_each(slaves, [&](auto rank) { + std::ranges::for_each(slaves, [&](auto rank) { communicator.recv(recv_buffer, rank); send_buffer.insert(send_buffer.end(), recv_buffer.begin(), recv_buffer.end()); }); table.buf2hist(send_buffer); send_buffer = table.hist2buf(size); - ranges::cpp20::for_each(slaves, [&](auto rank) { communicator.send(send_buffer, rank); }); + std::ranges::for_each(slaves, [&](auto rank) { communicator.send(send_buffer, rank); }); } } #endif diff --git a/src/particle.h b/src/particle.h index 200a55bfa..7db15de72 100644 --- a/src/particle.h +++ b/src/particle.h @@ -4,7 +4,7 @@ #include "tensor.h" #include #include -#include +#include namespace Eigen { using Matrix3d = Matrix; @@ -284,7 +284,7 @@ using ParticleVector = std::vector; /** Concept for a range of particles */ template concept RequireParticles = - ranges::cpp20::range && std::is_convertible_v, Particle>; + std::ranges::range && std::is_convertible_v, Particle>; template concept RequireParticleIterator = std::is_convertible_v, Particle>; diff --git a/src/random.h b/src/random.h index 94090e0da..ca847908e 100644 --- a/src/random.h +++ b/src/random.h @@ -1,5 +1,4 @@ #pragma once -#include #include #include #include @@ -113,7 +112,10 @@ template class WeightedDistribution */ template void setWeight(Iterator begin, Iterator end) { - static_assert(std::is_convertible_v, double>); + // Disable assert fow now + // see + // https://stackoverflow.com/questions/74496713/how-to-get-the-type-of-the-values-in-a-c20-stdranges-range + // static_assert(std::is_convertible_v, double>); if (auto size = std::distance(begin, end); size == data.size()) { weights.resize(size); std::copy(begin, end, weights.begin()); diff --git a/src/reactioncoordinate.cpp b/src/reactioncoordinate.cpp index 8b60d23e0..aa27ea7f6 100644 --- a/src/reactioncoordinate.cpp +++ b/src/reactioncoordinate.cpp @@ -5,10 +5,10 @@ #include "multipole.h" #include #include "aux/eigensupport.h" -#include -#include -#include +#include +#ifndef __cpp_lib_ranges_join_with #include +#endif #include "spdlog/spdlog.h" namespace Faunus::ReactionCoordinate { @@ -106,7 +106,12 @@ void SystemProperty::_to_json(json& j) const SystemProperty::SystemProperty(const json& j, const Space& spc) : ReactionCoordinateBase(j) { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; +#ifdef __cpp_lib_ranges_join_with + using std::views::join; +#else + using ranges::cpp20::views::join; +#endif name = "system"; property = j.at("property").get(); if (property == "V") { @@ -132,37 +137,37 @@ SystemProperty::SystemProperty(const json& j, const Space& spc) } else if (property == "Q") { // system net charge function = [&spc] { - auto charges = spc.groups | rv::join | rv::transform(&Particle::charge); + auto charges = spc.groups | join | rv::transform(&Particle::charge); return std::accumulate(charges.begin(), charges.end(), 0.0); }; } else if (property == "mu") { // system dipole moment function = [&spc]() { - auto particles = spc.groups | rv::join; + auto particles = spc.groups | join; return Faunus::dipoleMoment(particles.begin(), particles.end()).norm(); }; } else if (property == "mu_x") { // system dipole moment function = [&spc]() { - auto particles = spc.groups | rv::join; + auto particles = spc.groups | join; return Faunus::dipoleMoment(particles.begin(), particles.end()).x(); }; } else if (property == "mu_y") { // system dipole moment function = [&spc]() { - auto particles = spc.groups | rv::join; + auto particles = spc.groups | join; return Faunus::dipoleMoment(particles.begin(), particles.end()).y(); }; } else if (property == "mu_z") { // system dipole moment function = [&spc]() { - auto particles = spc.groups | rv::join; + auto particles = spc.groups | join; return Faunus::dipoleMoment(particles.begin(), particles.end()).z(); }; } else if (property == "N") { // number of particles function = [&spc]() { - auto sizes = spc.groups | rv::transform(&Space::GroupType::size); + auto sizes = spc.groups | std::views::transform(&Space::GroupType::size); return static_cast(std::accumulate(sizes.begin(), sizes.end(), size_t(0))); }; } @@ -213,9 +218,8 @@ AtomProperty::AtomProperty(const json& j, const Space& spc) else if (property == "N") { function = [&spc, id = index]() { return static_cast( - ranges::cpp20::count_if(spc.activeParticles(), [&](const Particle& particle) { - return particle.id == id; - })); + std::ranges::count_if(spc.activeParticles(), + [&](const Particle& particle) { return particle.id == id; })); }; } @@ -484,7 +488,7 @@ void MoleculeProperty::selectRinner(const json& j, const Space& spc) } function = [&spc, &dir = direction, i = indexes.at(0), j = indexes.at(1), k = indexes.at(2), l = indexes.at(3)]() { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; auto slicei = spc.findAtoms(i); const auto mass_center = Geometry::massCenter(slicei.begin(), slicei.end(), spc.geometry.getBoundaryFunc()); @@ -496,11 +500,11 @@ void MoleculeProperty::selectRinner(const json& j, const Space& spc) }; auto mean = [](auto& radii) { Average mean; - ranges::cpp20::for_each(radii, [&](auto radius) { mean += radius; }); + std::ranges::for_each(radii, [&](auto radius) { mean += radius; }); return mean.avg(); }; - auto radii_j = spc.findAtoms(j) | rv::transform(radius); + auto radii_j = spc.findAtoms(j) | std::views::transform(radius); auto mean_radii_j = mean(radii_j); auto radii = spc.activeParticles() | rv::filter(k_or_l) | rv::transform(radius) | diff --git a/src/regions.cpp b/src/regions.cpp index 008e38d26..4d2169b8f 100644 --- a/src/regions.cpp +++ b/src/regions.cpp @@ -1,6 +1,5 @@ #include "regions.h" #include "space.h" -#include #include #include @@ -29,7 +28,7 @@ bool RegionBase::inside(const Group& group) const return isInside(mass_center.value()); } } - return ranges::cpp20::any_of(group, [&](const Particle& particle) { return inside(particle); }); + return std::ranges::any_of(group, [&](const Particle& particle) { return inside(particle); }); } /** @@ -107,7 +106,7 @@ WithinMoleculeType::WithinMoleculeType(const Space& spc, const json& j) bool WithinMoleculeType::isInside(const Point& position) const { - using ranges::cpp20::any_of; + using std::ranges::any_of; auto has_position_inside = [&](const Group& group) { if (use_region_mass_center) { return within_threshold(position, *group.massCenter()); diff --git a/src/regions.h b/src/regions.h index f42134c02..f3045aa4a 100644 --- a/src/regions.h +++ b/src/regions.h @@ -3,8 +3,7 @@ #include "molecule.h" #include "group.h" #include "space.h" -#include -#include +#include namespace Faunus { class Space; @@ -55,7 +54,7 @@ class RegionBase /** Selects particles within the region */ template auto filterInside(const ParticleRange& particles) const { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; return particles | rv::transform(&Particle::pos) | rv::filter(&RegionBase::isInside); } }; diff --git a/src/sasa.cpp b/src/sasa.cpp index f5c13fa5f..1e13fad54 100644 --- a/src/sasa.cpp +++ b/src/sasa.cpp @@ -3,8 +3,6 @@ #include "space.h" #include #include -#include -#include #include namespace Faunus { @@ -172,8 +170,7 @@ void SASA::init(const Space& spc) auto sasa_radius_l = [this](const Particle& particle) { return 0.5 * particle.traits().sigma + probe_radius; }; - sasa_radii = - spc.particles | ranges::cpp20::views::transform(sasa_radius_l) | ranges::to; + sasa_radii = spc.particles | std::views::transform(sasa_radius_l) | ranges::to; areas.resize(spc.particles.size()); } @@ -219,7 +216,7 @@ std::vector SASA::calcNeighbourData(const Space& spc, const std::vector& target_indices) const { - return target_indices | ranges::views::transform([&](auto index) { + return target_indices | std::views::transform([&](auto index) { return calcNeighbourDataOfParticle(spc, index); }) | ranges::to; @@ -357,9 +354,8 @@ template void SASACellList::init(const Space& spc) } auto get_sasa_radius = [this](auto& i) { return 0.5 * i.traits().sigma + probe_radius; }; - sasa_radii = - spc.particles | ranges::cpp20::views::transform(get_sasa_radius) | ranges::to; - const auto max_sasa_radius = ranges::cpp20::max(sasa_radii); + sasa_radii = spc.particles | std::views::transform(get_sasa_radius) | ranges::to; + const double max_sasa_radius = std::ranges::max(sasa_radii); cell_length = 2.0 * (max_sasa_radius); const auto active_particles = spc.activeParticles(); @@ -422,7 +418,7 @@ std::vector SASACellList::calcNeighbourData(const Space& spc, const std::vector& target_indices) const { - return target_indices | ranges::views::transform([&](auto index) { + return target_indices | std::views::transform([&](auto index) { return calcNeighbourDataOfParticle(spc, index); }) | ranges::to; @@ -512,15 +508,14 @@ void SASACellList::updatePositionsChange(const Space& spc, const Chang }; if (group_change.relative_atom_indices.empty()) { - const auto changed_atom_indices = - ranges::cpp20::views::iota(offset, offset + group.size()); - ranges::cpp20::for_each(changed_atom_indices, update); + const auto changed_atom_indices = std::views::iota(offset, offset + group.size()); + std::ranges::for_each(changed_atom_indices, update); } else { const auto changed_atom_indices = group_change.relative_atom_indices | - ranges::cpp20::views::transform([offset](auto i) { return i + offset; }); - ranges::cpp20::for_each(changed_atom_indices, update); + std::views::transform([offset](auto i) { return i + offset; }); + std::ranges::for_each(changed_atom_indices, update); } } } diff --git a/src/scatter.h b/src/scatter.h index e611ed4da..add1b8b3f 100644 --- a/src/scatter.h +++ b/src/scatter.h @@ -338,8 +338,7 @@ class StructureFactorPBC : private TSamplingPolicy // Note January 2020: only GCC exploits this using libmvec library if --ffast-math is // enabled. auto dot_product = [q](const auto& pos) { return static_cast(q.dot(pos)); }; - auto qdotr = - positions | ranges::cpp20::views::transform(dot_product) | ranges::to; + auto qdotr = positions | std::views::transform(dot_product) | ranges::to; std::for_each(qdotr.begin(), qdotr.end(), [&](auto qr) { sum_cos += cos(qr); }); std::for_each(qdotr.begin(), qdotr.end(), [&](auto qr) { sum_sin += sin(qr); }); } diff --git a/src/smart_montecarlo.h b/src/smart_montecarlo.h index 25b758bdf..d01e196df 100644 --- a/src/smart_montecarlo.h +++ b/src/smart_montecarlo.h @@ -2,7 +2,7 @@ #include "regions.h" #include -#include +#include namespace Faunus::SmarterMonteCarlo { @@ -65,7 +65,7 @@ class RegionSampler const double outside_acceptance = 1.0; //!< Or "p" between ]0:1]; 1 --> uniform sampling (no regional preference) static BiasDirection getDirection(bool inside_before, bool inside_after); - template double getNumberInside(Range& range) const; + template double getNumberInside(Range& range) const; protected: const std::unique_ptr region; //!< This defines the smart MC region @@ -75,7 +75,7 @@ class RegionSampler virtual ~RegionSampler() = default; void to_json(json& j) const; //!< Serialise to json - template + template std::optional> select(Range& range, Random& random); template double bias(const Selection& selection); @@ -88,13 +88,13 @@ class RegionSampler * * @returns (mean) number of elements inside region */ -template double RegionSampler::getNumberInside(Range& range) const +template double RegionSampler::getNumberInside(Range& range) const { if (fixed_number_inside) { return fixed_number_inside.value(); } - return static_cast( - ranges::count_if(range, [&](const auto& i) { return region->inside(i); })); // expensive + return static_cast(std::ranges::count_if( + range, [&](const auto& i) { return region->inside(i); })); // expensive } /** @@ -109,10 +109,10 @@ template double RegionSampler::getNumberInside(Rang * without any selection, an empty object is returned and a warning issued. The maximum * number of attempts is currently set to 10x the size of the given range. */ -template +template std::optional> RegionSampler::select(Range& range, Random& random) { - const auto n_total = ranges::distance(range.begin(), range.end()); + const auto n_total = std::ranges::distance(range.begin(), range.end()); int max_selection_attempts = 10 * n_total; do { auto it = random.sample(range.begin(), range.end()); // random particle or group @@ -166,7 +166,7 @@ template class MoveSupport MoveSupport(const Space& spc, const json& j); double bias(); void to_json(json& j) const; - template OptionalElement select(Range& mollist, Random& random); + template OptionalElement select(Range& mollist, Random& random); }; template @@ -245,7 +245,7 @@ template void MoveSupport::to_json(json& j) const * @return Optional reference to selected element */ template -template +template typename MoveSupport::OptionalElement MoveSupport::select(Range& mollist, Random& random) { selection = region_sampler.select(mollist, random); diff --git a/src/space.cpp b/src/space.cpp index 4bb195234..010c2001d 100644 --- a/src/space.cpp +++ b/src/space.cpp @@ -2,9 +2,9 @@ #include "io.h" #include "aux/eigensupport.h" #include -#include -#include #include +#include +#include namespace Faunus { @@ -235,7 +235,7 @@ void Space::sync(const Space& other, const Change& change) } } // apply registered triggers - ranges::cpp20::for_each(onSyncTriggers, [&](auto& trigger) { trigger(*this, other, change); }); + std::ranges::for_each(onSyncTriggers, [&](auto& trigger) { trigger(*this, other, change); }); } /** @@ -330,7 +330,7 @@ Space::GroupVector::iterator Space::randomMolecule(MoleculeData::index_type moli Space::Selection selection) { auto found_molecules = findMolecules(molid, selection); - if (ranges::cpp20::empty(found_molecules)) { + if (std::ranges::empty(found_molecules)) { return groups.end(); } return groups.begin() + @@ -419,8 +419,8 @@ std::size_t Space::getFirstActiveParticleIndex(const GroupType& group) const size_t Space::countAtoms(AtomData::index_type atomid) const { - return ranges::cpp20::count_if(activeParticles(), - [&](auto& particle) { return particle.id == atomid; }); + return std::ranges::count_if(activeParticles(), + [&](auto& particle) { return particle.id == atomid; }); } void Space::updateInternalState(const Change& change) @@ -513,8 +513,8 @@ void from_json(const json& j, Space& spc) auto active_and_molecular = [](const auto& group) { return (!group.empty() && group.isMolecular()); }; - ranges::cpp20::for_each(spc.groups | ranges::cpp20::views::filter(active_and_molecular), - check_mass_center); + std::ranges::for_each(spc.groups | std::views::filter(active_and_molecular), + check_mass_center); } catch (const std::exception& e) { throw std::runtime_error("error building space -> "s + e.what()); @@ -613,7 +613,7 @@ TEST_CASE("[Faunus] Space::toIndices") Space spc; spc.particles.resize(3); - auto subrange = ranges::make_subrange(spc.particles.begin() + 1, spc.particles.end()); // p1, p2 + auto subrange = std::ranges::subrange(spc.particles.begin() + 1, spc.particles.end()); // p1, p2 auto indices = spc.toIndices(subrange); CHECK_EQ(indices.size(), 2); CHECK_EQ(indices.at(0), 1); diff --git a/src/space.h b/src/space.h index f7591dcae..f80b8a9fa 100644 --- a/src/space.h +++ b/src/space.h @@ -3,8 +3,9 @@ #include "geometry.h" #include "group.h" #include "molecule.h" +#include #include -#include +#include #include namespace Faunus { @@ -60,7 +61,7 @@ struct Change //! List of moved groups (index) [[nodiscard]] inline auto touchedGroupIndex() const { - return ranges::cpp20::views::transform(groups, &GroupChange::group_index); + return std::views::transform(groups, &GroupChange::group_index); } //! List of changed atom index relative to first particle in system @@ -203,7 +204,7 @@ class Space assert(size <= std::distance(destination, particles.end())); auto affected_groups = - groups | ranges::cpp20::views::filter([=](auto& group) { + groups | std::views::filter([=](auto& group) { return (group.begin() < destination + size) && (group.end() > destination); }); // filtered group with affected groups only. Note we copy in org. `destination` @@ -211,7 +212,7 @@ class Space std::for_each(begin, end, [&](const auto& source) { copy_function(source, *destination++); }); - std::for_each(affected_groups.begin(), affected_groups.end(), [&](Group& group) { + std::ranges::for_each(affected_groups, [&](Group& group) { group.updateMassCenter(geometry.getBoundaryFunc(), group.begin()->pos); }); } @@ -233,12 +234,12 @@ class Space //! Iterable range of all particle positions [[nodiscard]] auto positions() const { - return ranges::cpp20::views::transform( - particles, [](auto& particle) -> const Point& { return particle.pos; }); + return std::views::transform(particles, + [](auto& particle) -> const Point& { return particle.pos; }); } //! Mutable iterable range of all particle positions - auto positions() { return ranges::cpp20::views::transform(particles, &Particle::pos); } + auto positions() { return std::views::transform(particles, &Particle::pos); } static std::function getGroupFilter(MoleculeData::index_type molid, const Selection& selection) @@ -324,7 +325,7 @@ class Space } return static_cast(index); }; - return particle_range | ranges::cpp20::views::transform(to_index) | ranges::to_vector; + return particle_range | std::views::transform(to_index) | ranges::to_vector; } /** @@ -334,7 +335,7 @@ class Space */ auto findAtoms(AtomData::index_type atomid) { - return activeParticles() | ranges::cpp20::views::filter([atomid](const Particle& particle) { + return activeParticles() | std::views::filter([atomid](const Particle& particle) { return particle.id == atomid; }); } @@ -346,7 +347,7 @@ class Space */ [[nodiscard]] auto findAtoms(AtomData::index_type atomid) const { - return activeParticles() | ranges::cpp20::views::filter([atomid](const Particle& particle) { + return activeParticles() | std::views::filter([atomid](const Particle& particle) { return particle.id == atomid; }); } diff --git a/src/speciation.cpp b/src/speciation.cpp index a439b4f39..bae511bde 100644 --- a/src/speciation.cpp +++ b/src/speciation.cpp @@ -1,11 +1,10 @@ #include "bonds.h" #include "speciation.h" #include "aux/iteratorsupport.h" -#include #include -#include -#include +#include #include +#include #include namespace Faunus::Speciation { @@ -69,14 +68,14 @@ bool ReactionValidator::canReduceImplicitGroups(const ReactionData& reaction) co const auto& [molid, number_to_delete] = key_value; return spc.getImplicitReservoir().at(molid) >= number_to_delete; }; - auto implicit_reactants = reaction.getReactants().second | - ranges::cpp20::views::filter(ReactionData::is_implicit_group); - return ranges::cpp20::all_of(implicit_reactants, has_enough); + auto implicit_reactants = + reaction.getReactants().second | std::views::filter(ReactionData::is_implicit_group); + return std::ranges::all_of(implicit_reactants, has_enough); } bool ReactionValidator::canSwapAtoms(const ReactionData& reaction) const { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; if (reaction.containsAtomicSwap()) { auto reactive_atoms = reaction.getReactants().first | rv::filter(ReactionData::not_implicit_atom); @@ -92,7 +91,7 @@ bool ReactionValidator::canSwapAtoms(const ReactionData& reaction) const bool ReactionValidator::canReduceMolecularGroups(const ReactionData& reaction) const { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; auto selection = reaction.only_neutral_molecules ? Space::Selection::ACTIVE_NEUTRAL : Space::Selection::ACTIVE; @@ -116,12 +115,12 @@ bool ReactionValidator::canReduceMolecularGroups(const ReactionData& reaction) c rv::filter(ReactionData::not_implicit_group) | rv::filter(ReactionData::is_molecular_group); - return ranges::cpp20::all_of(molecular_groups, can_reduce); + return std::ranges::all_of(molecular_groups, can_reduce); } bool ReactionValidator::canReduceAtomicGroups(const ReactionData& reaction) const { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; auto can_reduce = [&](auto key_value) { const auto [molid, number_to_delete] = key_value; if (number_to_delete > 0) { @@ -143,12 +142,12 @@ bool ReactionValidator::canReduceAtomicGroups(const ReactionData& reaction) cons auto atomic_groups = reaction.getReactants().second | rv::filter(ReactionData::not_implicit_group) | rv::filter(ReactionData::is_atomic_group); - return ranges::cpp20::all_of(atomic_groups, can_reduce); + return std::ranges::all_of(atomic_groups, can_reduce); } bool ReactionValidator::canProduceMolecularGroups(const ReactionData& reaction) const { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; auto selection = reaction.only_neutral_molecules ? Space::Selection::INACTIVE_NEUTRAL : Space::Selection::INACTIVE; @@ -169,12 +168,12 @@ bool ReactionValidator::canProduceMolecularGroups(const ReactionData& reaction) rv::filter(ReactionData::not_implicit_group) | rv::filter(ReactionData::is_molecular_group); - return ranges::cpp20::all_of(molecular_groups, can_create); + return std::ranges::all_of(molecular_groups, can_create); } bool ReactionValidator::canProduceAtomicGroups(const ReactionData& reaction) const { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; auto can_expand = [&](auto key_value) { const auto [molid, number_to_insert] = key_value; auto groups = spc.findMolecules(molid, Space::Selection::ALL) | @@ -195,7 +194,7 @@ bool ReactionValidator::canProduceAtomicGroups(const ReactionData& reaction) con rv::filter(ReactionData::not_implicit_group) | rv::filter(ReactionData::is_atomic_group); - return ranges::cpp20::all_of(atomic_groups, can_expand); + return std::ranges::all_of(atomic_groups, can_expand); } // ---------------------------------------------- @@ -293,9 +292,8 @@ double MolecularGroupDeActivator::getBondEnergy(const Group& group) const { double energy = 0.0; if (apply_bond_bias) { - auto bonds = - group.traits().bonds | ranges::views::transform(&pairpotential::BondData::clone); - ranges::cpp20::for_each(bonds, [&](auto bond) { + auto bonds = group.traits().bonds | std::views::transform(&pairpotential::BondData::clone); + std::ranges::for_each(bonds, [&](auto bond) { bond->shiftIndices(spc.getFirstParticleIndex(group)); bond->setEnergyFunction(spc.particles); energy += bond->energyFunc(spc.geometry.getDistanceFunc()); @@ -373,7 +371,7 @@ AtomicGroupDeActivator::deactivate(Group& group, GroupDeActivator::OptionalInt n group.deactivate(last_particle, group.end()); // deactivate one particle at the time }; - ranges::for_each(ranges::cpp20::views::iota(0, number_to_delete), delete_particle); + std::ranges::for_each(std::views::iota(0, number_to_delete), delete_particle); change_data.sort(); return {change_data, 0.0}; } @@ -465,7 +463,7 @@ void SpeciationMove::activateProducts(Change& change) void SpeciationMove::activateMolecularGroups(Change& change) { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; auto selection = reaction->only_neutral_molecules ? Space::Selection::INACTIVE_NEUTRAL : Space::Selection::INACTIVE; @@ -478,7 +476,7 @@ void SpeciationMove::activateMolecularGroups(Change& change) ranges::views::sample(number_to_insert, random_internal.engine) | ranges::to>>; - ranges::for_each(inactive, [&](auto& group) { + std::ranges::for_each(inactive, [&](auto& group) { auto [change_data, bias] = molecular_group_bouncer->activate(group); change.groups.emplace_back(change_data); bias_energy += bias; @@ -488,7 +486,7 @@ void SpeciationMove::activateMolecularGroups(Change& change) void SpeciationMove::activateAtomicGroups(Change& change) { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; auto atomic_products = reaction->getProducts().second | rv::filter(ReactionData::not_implicit_group) | rv::filter(ReactionData::is_atomic_group); @@ -513,7 +511,7 @@ void SpeciationMove::deactivateReactants(Change& change) void SpeciationMove::deactivateMolecularGroups(Change& change) { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; auto nonzero_stoichiometric_coeff = [](auto key_value) { return key_value.second > 0; }; auto selection = (reaction->only_neutral_molecules) ? Space::Selection::ACTIVE_NEUTRAL : Space::Selection::ACTIVE; @@ -536,7 +534,7 @@ void SpeciationMove::deactivateMolecularGroups(Change& change) void SpeciationMove::deactivateAtomicGroups(Change& change) { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; auto nonzero_stoichiometric_coeff = [](auto key_value) { return key_value.second > 0; }; auto atomic_reactants = @@ -555,11 +553,12 @@ void SpeciationMove::deactivateAtomicGroups(Change& change) TEST_CASE("[Faunus] Speciation - Ranges::sample") { + using ranges::views::sample; std::vector vec = {1, 2, 3, 4}; - auto take_nothing = vec | ranges::views::sample(0); - auto take_less = vec | ranges::views::sample(2); - auto take_all = vec | ranges::views::sample(4); - auto take_too_much = vec | ranges::views::sample(10); + auto take_nothing = vec | sample(0); + auto take_less = vec | sample(2); + auto take_all = vec | sample(4); + auto take_too_much = vec | sample(10); CHECK_EQ(range_size(take_nothing), 0); CHECK_EQ(range_size(take_less), 2); @@ -616,7 +615,7 @@ void SpeciationMove::updateGroupMassCenters(const Change& change) const auto groups = change.groups | rv::filter(atomic_or_swap) | rv::transform(to_group) | rv::filter(has_mass_center); - ranges::cpp20::for_each(groups, [&](Group& group) { + std::ranges::for_each(groups, [&](Group& group) { group.updateMassCenter(spc.geometry.getBoundaryFunc(), group.massCenter().value()); }); } @@ -633,7 +632,7 @@ double SpeciationMove::bias([[maybe_unused]] Change& change, [[maybe_unused]] do void SpeciationMove::_accept([[maybe_unused]] Change& change) { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; direction_ratio[reaction].update(reaction->getDirection(), true); auto implicit_reactants = @@ -653,7 +652,7 @@ void SpeciationMove::_accept([[maybe_unused]] Change& change) void SpeciationMove::_reject([[maybe_unused]] Change& change) { - namespace rv = ranges::cpp20::views; + namespace rv = std::views; direction_ratio[reaction].update(reaction->getDirection(), false); auto implicit_reactants = diff --git a/src/voronota.cpp b/src/voronota.cpp index 814b7f787..f8e543e32 100644 --- a/src/voronota.cpp +++ b/src/voronota.cpp @@ -60,7 +60,7 @@ void Voronota::_to_disk() void Voronota::_sample() { using voronotalt::SimplePoint; - using namespace ranges::cpp20::views; + using namespace std::views; // Convert single `Particle` to Voronota's `SimpleSphere` auto to_sphere = [&](const Particle& p) -> voronotalt::SimpleSphere {