From: M. Eric Irrgang Date: Wed, 16 Dec 2020 17:45:40 +0000 (+0300) Subject: Apply re-formatting to C++ in src/ tree. X-Git-Url: http://biod.pnpi.spb.ru/gitweb/?a=commitdiff_plain;h=fdfc58342a6911b18a3d2916f3c07f45b9a204a2;p=alexxy%2Fgromacs.git Apply re-formatting to C++ in src/ tree. Apply formatting changes in bulk to reduce noise in subsequent functional changes. Will likely need to be repeated if clang-format version is updated per #3708. The formatting is sensitive to differences even between llvm tools versions 7.1.0.2 and 8.0.1.3. Here, I used 7.1. Refs #3833 --- diff --git a/api/gmxapi/cpp/context.cpp b/api/gmxapi/cpp/context.cpp index 6d11120eae..a46f78238a 100644 --- a/api/gmxapi/cpp/context.cpp +++ b/api/gmxapi/cpp/context.cpp @@ -347,13 +347,16 @@ std::shared_ptr ContextImpl::launch(const Workflow& work) SimulationContext simulationContext(communicator, multiSimDirectoryNames); - StartingBehavior startingBehavior = StartingBehavior::NewSimulation; - LogFilePtr logFileGuard = nullptr; - gmx_multisim_t* ms = simulationContext.multiSimulation_.get(); - std::tie(startingBehavior, logFileGuard) = handleRestart( - findIsSimulationMasterRank(ms, simulationContext.simulationCommunicator_), - simulationContext.simulationCommunicator_, ms, options.mdrunOptions.appendingBehavior, - ssize(options.filenames), options.filenames.data()); + StartingBehavior startingBehavior = StartingBehavior::NewSimulation; + LogFilePtr logFileGuard = nullptr; + gmx_multisim_t* ms = simulationContext.multiSimulation_.get(); + std::tie(startingBehavior, logFileGuard) = + handleRestart(findIsSimulationMasterRank(ms, simulationContext.simulationCommunicator_), + simulationContext.simulationCommunicator_, + ms, + options.mdrunOptions.appendingBehavior, + ssize(options.filenames), + options.filenames.data()); auto builder = MdrunnerBuilder(std::move(mdModules), compat::not_null(&simulationContext)); @@ -384,8 +387,8 @@ std::shared_ptr ContextImpl::launch(const Workflow& work) builder.addLogFile(logFileGuard.get()); // Note, creation is not mature enough to be exposed in the external API yet. - launchedSession = createSession(shared_from_this(), std::move(builder), - std::move(simulationContext), std::move(logFileGuard)); + launchedSession = createSession( + shared_from_this(), std::move(builder), std::move(simulationContext), std::move(logFileGuard)); // Clean up argv once builder is no longer in use // TODO: Remove long-lived references to argv so this is no longer necessary. diff --git a/api/gmxapi/cpp/mdsignals.cpp b/api/gmxapi/cpp/mdsignals.cpp index 6cf8f6158a..e54615a0c9 100644 --- a/api/gmxapi/cpp/mdsignals.cpp +++ b/api/gmxapi/cpp/mdsignals.cpp @@ -129,8 +129,9 @@ public: auto& callCounter = manager_->called_.at(name_); callCounter.store(true); using pairType = typename decltype(manager_->called_)::value_type; - if (std::all_of(manager_->called_.cbegin(), manager_->called_.cend(), - [](const pairType& p) { return p.second.load(); })) + if (std::all_of(manager_->called_.cbegin(), manager_->called_.cend(), [](const pairType& p) { + return p.second.load(); + })) { *manager_->state_ = gmx::StopSignal::stopAtNextNSStep; } diff --git a/api/gmxapi/cpp/session.cpp b/api/gmxapi/cpp/session.cpp index 2b909663b0..0bccfacf8d 100644 --- a/api/gmxapi/cpp/session.cpp +++ b/api/gmxapi/cpp/session.cpp @@ -122,8 +122,10 @@ std::unique_ptr SessionImpl::create(std::shared_ptr co { // We should be able to get a communicator (or subcommunicator) through the // Context. - return std::make_unique(std::move(context), std::move(runnerBuilder), - std::move(simulationContext), std::move(logFilehandle)); + return std::make_unique(std::move(context), + std::move(runnerBuilder), + std::move(simulationContext), + std::move(logFilehandle)); } SessionImpl::SessionImpl(std::shared_ptr context, @@ -156,8 +158,10 @@ std::shared_ptr createSession(std::shared_ptr context, gmx::SimulationContext&& simulationContext, gmx::LogFilePtr logFilehandle) { - auto newSession = SessionImpl::create(std::move(context), std::move(runnerBuilder), - std::move(simulationContext), std::move(logFilehandle)); + auto newSession = SessionImpl::create(std::move(context), + std::move(runnerBuilder), + std::move(simulationContext), + std::move(logFilehandle)); auto launchedSession = std::make_shared(std::move(newSession)); return launchedSession; } diff --git a/api/gmxapi/cpp/tpr.cpp b/api/gmxapi/cpp/tpr.cpp index 2d498079f8..2ea116e362 100644 --- a/api/gmxapi/cpp/tpr.cpp +++ b/api/gmxapi/cpp/tpr.cpp @@ -745,9 +745,11 @@ bool copy_tprfile(const gmxapicompat::TprReadHandle& input, const std::string& o { return false; } - gmxapicompat::writeTprFile( - outFile, *gmxapicompat::getMdParams(input), *gmxapicompat::getStructureSource(input), - *gmxapicompat::getSimulationState(input), *gmxapicompat::getTopologySource(input)); + gmxapicompat::writeTprFile(outFile, + *gmxapicompat::getMdParams(input), + *gmxapicompat::getStructureSource(input), + *gmxapicompat::getSimulationState(input), + *gmxapicompat::getTopologySource(input)); return true; } diff --git a/api/legacy/include/gromacs/utility/gmxassert.h b/api/legacy/include/gromacs/utility/gmxassert.h index 089b73c1df..14c0c8cdf3 100644 --- a/api/legacy/include/gromacs/utility/gmxassert.h +++ b/api/legacy/include/gromacs/utility/gmxassert.h @@ -66,10 +66,10 @@ # define GMX_RELEASE_ASSERT(condition, msg) #else # ifdef _MSC_VER -# define GMX_RELEASE_ASSERT(condition, msg) \ - ((void)((condition) ? (void)0 \ - : ::gmx::internal::assertHandler(#condition, msg, GMX_CURRENT_FUNCTION, \ - __FILE__, __LINE__))) +# define GMX_RELEASE_ASSERT(condition, msg) \ + ((void)((condition) ? (void)0 \ + : ::gmx::internal::assertHandler( \ + #condition, msg, GMX_CURRENT_FUNCTION, __FILE__, __LINE__))) # else // Use an "immediately invoked function expression" to allow being // used in constexpr context with older GCC versions diff --git a/api/legacy/include/gromacs/utility/listoflists.h b/api/legacy/include/gromacs/utility/listoflists.h index 8d707a0957..bcc94bd30d 100644 --- a/api/legacy/include/gromacs/utility/listoflists.h +++ b/api/legacy/include/gromacs/utility/listoflists.h @@ -188,8 +188,8 @@ public: //! Appends a ListOfLists at the end and increments the appended elements by \p offset void appendListOfLists(const ListOfLists& listOfLists, const T offset = 0) { - listRanges_.insert(listRanges_.end(), listOfLists.listRanges_.begin() + 1, - listOfLists.listRanges_.end()); + listRanges_.insert( + listRanges_.end(), listOfLists.listRanges_.begin() + 1, listOfLists.listRanges_.end()); const int oldNumElements = elements_.size(); for (std::size_t i = listRanges_.size() - listOfLists.size(); i < listRanges_.size(); i++) { diff --git a/api/nblib/gmxcalculator.cpp b/api/nblib/gmxcalculator.cpp index d49b1d1cb5..d4c8a1f417 100644 --- a/api/nblib/gmxcalculator.cpp +++ b/api/nblib/gmxcalculator.cpp @@ -73,8 +73,13 @@ void GmxForceCalculator::compute(gmx::ArrayRef coordinateInput, // update the coordinates in the backend nbv_->convertCoordinates(gmx::AtomLocality::Local, false, coordinateInput); - nbv_->dispatchNonbondedKernel(gmx::InteractionLocality::Local, *interactionConst_, *stepWork_, - enbvClearFYes, *forcerec_, enerd_.get(), nrnb_.get()); + nbv_->dispatchNonbondedKernel(gmx::InteractionLocality::Local, + *interactionConst_, + *stepWork_, + enbvClearFYes, + *forcerec_, + enerd_.get(), + nrnb_.get()); nbv_->atomdata_add_nbat_f_to_f(gmx::AtomLocality::All, forceOutput); } @@ -94,9 +99,18 @@ void GmxForceCalculator::setParticlesOnGrid(gmx::ArrayRef parti const real particleDensity = coordinates.size() / det(legacyBox); - nbnxn_put_on_grid(nbv_.get(), legacyBox, 0, lowerCorner, upperCorner, nullptr, - { 0, int(coordinates.size()) }, particleDensity, particleInfoAllVdw, - coordinates, 0, nullptr); + nbnxn_put_on_grid(nbv_.get(), + legacyBox, + 0, + lowerCorner, + upperCorner, + nullptr, + { 0, int(coordinates.size()) }, + particleDensity, + particleInfoAllVdw, + coordinates, + 0, + nullptr); } } // namespace nblib diff --git a/api/nblib/gmxsetup.cpp b/api/nblib/gmxsetup.cpp index 8501ff062a..52cbf0f0be 100644 --- a/api/nblib/gmxsetup.cpp +++ b/api/nblib/gmxsetup.cpp @@ -185,23 +185,27 @@ void NbvSetupUtil::setupNbnxmInstance(const size_t numParticleTypes, const NBKer Nbnxm::KernelSetup kernelSetup = getKernelSetup(options); PairlistParams pairlistParams(kernelSetup.kernelType, false, options.pairlistCutoff, false); - Nbnxm::GridSet gridSet(PbcType::Xyz, false, nullptr, nullptr, pairlistParams.pairlistType, - false, numThreads, pinPolicy); - auto pairlistSets = std::make_unique(pairlistParams, false, 0); - auto pairSearch = - std::make_unique(PbcType::Xyz, false, nullptr, nullptr, - pairlistParams.pairlistType, false, numThreads, pinPolicy); + Nbnxm::GridSet gridSet( + PbcType::Xyz, false, nullptr, nullptr, pairlistParams.pairlistType, false, numThreads, pinPolicy); + auto pairlistSets = std::make_unique(pairlistParams, false, 0); + auto pairSearch = std::make_unique( + PbcType::Xyz, false, nullptr, nullptr, pairlistParams.pairlistType, false, numThreads, pinPolicy); auto atomData = std::make_unique(pinPolicy); // Put everything together - auto nbv = std::make_unique(std::move(pairlistSets), std::move(pairSearch), - std::move(atomData), kernelSetup, nullptr, - nullWallcycle); + auto nbv = std::make_unique( + std::move(pairlistSets), std::move(pairSearch), std::move(atomData), kernelSetup, nullptr, nullWallcycle); // Needs to be called with the number of unique ParticleTypes - nbnxn_atomdata_init(gmx::MDLogger(), nbv->nbat.get(), kernelSetup.kernelType, combinationRule, - numParticleTypes, nonbondedParameters_, 1, numThreads); + nbnxn_atomdata_init(gmx::MDLogger(), + nbv->nbat.get(), + kernelSetup.kernelType, + combinationRule, + numParticleTypes, + nonbondedParameters_, + 1, + numThreads); gmxForceCalculator_->nbv_ = std::move(nbv); } @@ -264,7 +268,8 @@ void NbvSetupUtil::setupInteractionConst(const NBKernelOptions& options) gmxForceCalculator_->interactionConst_->epsfac = 0; } - calc_rffac(nullptr, gmxForceCalculator_->interactionConst_->epsilon_r, + calc_rffac(nullptr, + gmxForceCalculator_->interactionConst_->epsilon_r, gmxForceCalculator_->interactionConst_->epsilon_rf, gmxForceCalculator_->interactionConst_->rcoulomb, &gmxForceCalculator_->interactionConst_->k_rf, @@ -299,8 +304,8 @@ void NbvSetupUtil::setParticlesOnGrid(const std::vector& coordinates, cons void NbvSetupUtil::constructPairList(const gmx::ListOfLists& exclusions) { - gmxForceCalculator_->nbv_->constructPairlist(gmx::InteractionLocality::Local, exclusions, 0, - gmxForceCalculator_->nrnb_.get()); + gmxForceCalculator_->nbv_->constructPairlist( + gmx::InteractionLocality::Local, exclusions, 0, gmxForceCalculator_->nrnb_.get()); } diff --git a/api/nblib/interactions.cpp b/api/nblib/interactions.cpp index 47cb326f44..9297521875 100644 --- a/api/nblib/interactions.cpp +++ b/api/nblib/interactions.cpp @@ -138,7 +138,8 @@ ParticleTypesInteractions& ParticleTypesInteractions::add(const ParticleTypeName std::string message = formatString( "Attempting to add nonbonded interaction parameters between the particle types " "{} {} twice", - particleTypeName1.value(), particleTypeName2.value()); + particleTypeName1.value(), + particleTypeName2.value()); throw InputException(message); } } @@ -163,8 +164,8 @@ NonBondedInteractionMap ParticleTypesInteractions::generateTable() const C6 c6_combo{ combineNonbondedParameters(c6_1, c6_2, combinationRule_) }; C12 c12_combo{ combineNonbondedParameters(c12_1, c12_2, combinationRule_) }; - nonbondedParameters_.setInteractions(particleType1.first, particleType2.first, c6_combo, - c12_combo); + nonbondedParameters_.setInteractions( + particleType1.first, particleType2.first, c6_combo, c12_combo); } } @@ -195,7 +196,8 @@ NonBondedInteractionMap ParticleTypesInteractions::generateTable() const if (nonbondedParameters_.count(interactionKey) == 0) { std::string message = formatString("Missing interaction between {} {}", - particleTypeName1.value(), particleTypeName2.value()); + particleTypeName1.value(), + particleTypeName2.value()); throw InputException(message); } } @@ -217,7 +219,9 @@ void ParticleTypesInteractions::merge(const ParticleTypesInteractions& other) for (const auto& keyval : other.twoParticlesInteractionsMap_) { - add(std::get<0>(keyval.first), std::get<1>(keyval.first), std::get<0>(keyval.second), + add(std::get<0>(keyval.first), + std::get<1>(keyval.first), + std::get<0>(keyval.second), std::get<1>(keyval.second)); } } diff --git a/api/nblib/listed_forces/gmxcalculator.cpp b/api/nblib/listed_forces/gmxcalculator.cpp index 9aa215339d..7895b98267 100644 --- a/api/nblib/listed_forces/gmxcalculator.cpp +++ b/api/nblib/listed_forces/gmxcalculator.cpp @@ -100,8 +100,20 @@ void ListedGmxCalculator::compute(const std::vector& x, energies.fill(0); std::fill(enerd.term, enerd.term + F_NRE, 0.0); - calc_listed(wcycle, *idef, &bondedThreading, xdata, &forceOutputs, &fr, &pbc, &enerd, &nrnb, - lambdaBuffer.data(), nullptr, nullptr, nullptr, stepWork); + calc_listed(wcycle, + *idef, + &bondedThreading, + xdata, + &forceOutputs, + &fr, + &pbc, + &enerd, + &nrnb, + lambdaBuffer.data(), + nullptr, + nullptr, + nullptr, + stepWork); auto transferEnergy = [&energies, this](auto& interactionElement) { using InteractionType = typename std::decay_t::type; diff --git a/api/nblib/listed_forces/tests/bondtypes.cpp b/api/nblib/listed_forces/tests/bondtypes.cpp index 15863da8fa..31ddb4de4f 100644 --- a/api/nblib/listed_forces/tests/bondtypes.cpp +++ b/api/nblib/listed_forces/tests/bondtypes.cpp @@ -118,8 +118,8 @@ void testThreeParameterBondLessThan(const B& deduceType) TEST(NBlibTest, BondTypesOperatorEqualWorks) { - auto bondList3 = std::make_tuple(HarmonicBondType(), G96BondType(), FENEBondType(), - HalfAttractiveQuarticBondType()); + auto bondList3 = std::make_tuple( + HarmonicBondType(), G96BondType(), FENEBondType(), HalfAttractiveQuarticBondType()); for_each_tuple([](const auto& b) { test_detail::testTwoParameterBondEquality(b); }, bondList3); auto bondList4 = std::make_tuple(CubicBondType(), MorseBondType()); @@ -128,8 +128,8 @@ TEST(NBlibTest, BondTypesOperatorEqualWorks) TEST(NBlibTest, BondTypesLessThanWorks) { - auto bondList3 = std::make_tuple(HarmonicBondType(), G96BondType(), FENEBondType(), - HalfAttractiveQuarticBondType()); + auto bondList3 = std::make_tuple( + HarmonicBondType(), G96BondType(), FENEBondType(), HalfAttractiveQuarticBondType()); for_each_tuple([](const auto& b) { test_detail::testTwoParameterBondLessThan(b); }, bondList3); auto bondList4 = std::make_tuple(CubicBondType(), MorseBondType()); diff --git a/api/nblib/listed_forces/tests/calculator.cpp b/api/nblib/listed_forces/tests/calculator.cpp index e19f0d6608..b1876581b8 100644 --- a/api/nblib/listed_forces/tests/calculator.cpp +++ b/api/nblib/listed_forces/tests/calculator.cpp @@ -83,7 +83,9 @@ void compareVectors(const TestSeq& forces, for (int m = 0; m < dimSize; ++m) { EXPECT_FLOAT_DOUBLE_EQ_TOL( - forces[i][m], refForcesFloat[i][m], refForcesDouble[i][m], + forces[i][m], + refForcesFloat[i][m], + refForcesDouble[i][m], // Todo: why does the tolerance need to be so low? gmx::test::relativeToleranceAsFloatingPoint(refForcesDouble[i][m], 5e-5)); } @@ -168,7 +170,9 @@ TEST_F(ListedExampleData, DISABLED_ComputeHarmonicBondForces) auto bonds = pickType(interactions).parameters; real energy = computeForces(indices, bonds, x, &forces, *pbc); - EXPECT_FLOAT_DOUBLE_EQ_TOL(energy, refBondEnergyFloat, refBondEnergyDouble, + EXPECT_FLOAT_DOUBLE_EQ_TOL(energy, + refBondEnergyFloat, + refBondEnergyDouble, gmx::test::relativeToleranceAsFloatingPoint(refBondEnergyDouble, 1e-5)); compareVectors(forces, refBondForcesFloat, refBondForcesDouble); @@ -180,7 +184,9 @@ TEST_F(ListedExampleData, ComputeHarmonicAngleForces) auto angles = pickType(interactions).parameters; real energy = computeForces(indices, angles, x, &forces, *pbc); - EXPECT_FLOAT_DOUBLE_EQ_TOL(energy, refAngleEnergyFloat, refAngleEnergyDouble, + EXPECT_FLOAT_DOUBLE_EQ_TOL(energy, + refAngleEnergyFloat, + refAngleEnergyDouble, gmx::test::relativeToleranceAsFloatingPoint(refAngleEnergyDouble, 1e-5)); compareVectors(forces, refAngleForcesFloat, refAngleForcesDouble); @@ -191,12 +197,12 @@ TEST_F(ListedExampleData, DISABLED_CanReduceForces) auto energies = reduceListedForces(interactions, x, &forces, *pbc); real totalEnergy = std::accumulate(begin(energies), end(energies), 0.0); - EXPECT_FLOAT_DOUBLE_EQ_TOL(totalEnergy, refBondEnergyFloat + refAngleEnergyFloat, + EXPECT_FLOAT_DOUBLE_EQ_TOL(totalEnergy, + refBondEnergyFloat + refAngleEnergyFloat, refBondEnergyDouble + refAngleEnergyDouble, gmx::test::relativeToleranceAsFloatingPoint(refBondEnergyDouble, 1e-5)); - compareVectors(forces, refBondForcesFloat + refAngleForcesFloat, - refBondForcesDouble + refAngleForcesDouble); + compareVectors(forces, refBondForcesFloat + refAngleForcesFloat, refBondForcesDouble + refAngleForcesDouble); } @@ -205,7 +211,8 @@ void compareArray(const ListedForceCalculator::EnergyType& energies, { for (size_t i = 0; i < energies.size(); ++i) { - EXPECT_REAL_EQ_TOL(energies[i], refEnergies[i], + EXPECT_REAL_EQ_TOL(energies[i], + refEnergies[i], gmx::test::relativeToleranceAsFloatingPoint(refEnergies[i], 1e-5)); } } diff --git a/api/nblib/listed_forces/tests/helpers.cpp b/api/nblib/listed_forces/tests/helpers.cpp index e265bf7f33..47236951d8 100644 --- a/api/nblib/listed_forces/tests/helpers.cpp +++ b/api/nblib/listed_forces/tests/helpers.cpp @@ -131,8 +131,8 @@ TEST(NBlibTest, ListedForceBuffer) { for (size_t m = 0; m < dimSize; ++m) { - EXPECT_REAL_EQ_TOL(refMasterBuffer[i][m], masterBuffer[i][m], - gmx::test::defaultRealTolerance()); + EXPECT_REAL_EQ_TOL( + refMasterBuffer[i][m], masterBuffer[i][m], gmx::test::defaultRealTolerance()); } } diff --git a/api/nblib/molecules.cpp b/api/nblib/molecules.cpp index d9e672c0a9..679d888cd1 100644 --- a/api/nblib/molecules.cpp +++ b/api/nblib/molecules.cpp @@ -135,10 +135,12 @@ void Molecule::addInteraction(const ParticleName& particleNameI, } //! \cond DO_NOT_DOCUMENT -#define ADD_INTERACTION_INSTANTIATE_TEMPLATE(x) \ - template void Molecule::addInteraction( \ - const ParticleName& particleNameI, const ResidueName& residueNameI, \ - const ParticleName& particleNameJ, const ResidueName& residueNameJ, const x& interaction); +#define ADD_INTERACTION_INSTANTIATE_TEMPLATE(x) \ + template void Molecule::addInteraction(const ParticleName& particleNameI, \ + const ResidueName& residueNameI, \ + const ParticleName& particleNameJ, \ + const ResidueName& residueNameJ, \ + const x& interaction); MAP(ADD_INTERACTION_INSTANTIATE_TEMPLATE, SUPPORTED_TWO_CENTER_TYPES) #undef ADD_INTERACTION_INSTANTIATE_TEMPLATE //! \endcond @@ -153,9 +155,9 @@ void Molecule::addInteraction(const ParticleName& particleNameI, } //! \cond DO_NOT_DOCUMENT -#define ADD_INTERACTION_INSTANTIATE_TEMPLATE(x) \ - template void Molecule::addInteraction(const ParticleName& particleNameI, \ - const ParticleName& particleNameJ, const x& interaction); +#define ADD_INTERACTION_INSTANTIATE_TEMPLATE(x) \ + template void Molecule::addInteraction( \ + const ParticleName& particleNameI, const ParticleName& particleNameJ, const x& interaction); MAP(ADD_INTERACTION_INSTANTIATE_TEMPLATE, SUPPORTED_TWO_CENTER_TYPES) #undef ADD_INTERACTION_INSTANTIATE_TEMPLATE @@ -176,16 +178,19 @@ void Molecule::addInteraction(const ParticleName& particleNameI, } auto& interactionContainer = pickType(interactionData_); - interactionContainer.interactions_.emplace_back(particleNameI, residueNameI, particleNameJ, - residueNameJ, particleNameK, residueNameK); + interactionContainer.interactions_.emplace_back( + particleNameI, residueNameI, particleNameJ, residueNameJ, particleNameK, residueNameK); interactionContainer.interactionTypes_.push_back(interaction); } -#define ADD_INTERACTION_INSTANTIATE_TEMPLATE(x) \ - template void Molecule::addInteraction( \ - const ParticleName& particleNameI, const ResidueName& residueNameI, \ - const ParticleName& particleNameJ, const ResidueName& residueNameJ, \ - const ParticleName& particleNameK, const ResidueName& residueNameK, const x& interaction); +#define ADD_INTERACTION_INSTANTIATE_TEMPLATE(x) \ + template void Molecule::addInteraction(const ParticleName& particleNameI, \ + const ResidueName& residueNameI, \ + const ParticleName& particleNameJ, \ + const ResidueName& residueNameJ, \ + const ParticleName& particleNameK, \ + const ResidueName& residueNameK, \ + const x& interaction); MAP(ADD_INTERACTION_INSTANTIATE_TEMPLATE, SUPPORTED_THREE_CENTER_TYPES) #undef ADD_INTERACTION_INSTANTIATE_TEMPLATE @@ -195,14 +200,20 @@ void Molecule::addInteraction(const ParticleName& particleNameI, const ParticleName& particleNameK, const Interaction& interaction) { - addInteraction(particleNameI, ResidueName(name_), particleNameJ, ResidueName(name_), - particleNameK, ResidueName(name_), interaction); + addInteraction(particleNameI, + ResidueName(name_), + particleNameJ, + ResidueName(name_), + particleNameK, + ResidueName(name_), + interaction); } #define ADD_INTERACTION_INSTANTIATE_TEMPLATE(x) \ template void Molecule::addInteraction(const ParticleName& particleNameI, \ const ParticleName& particleNameJ, \ - const ParticleName& particleNameK, const x& interaction); + const ParticleName& particleNameK, \ + const x& interaction); MAP(ADD_INTERACTION_INSTANTIATE_TEMPLATE, SUPPORTED_THREE_CENTER_TYPES) #undef ADD_INTERACTION_INSTANTIATE_TEMPLATE //! \endcond @@ -227,7 +238,8 @@ void Molecule::addExclusion(std::tuple particle, std::tuple particleToExclude) { // duplication for the swapped pair happens in getExclusions() - exclusionsByName_.emplace_back(std::make_tuple(std::get<0>(particle), std::get<1>(particle), + exclusionsByName_.emplace_back(std::make_tuple(std::get<0>(particle), + std::get<1>(particle), std::get<0>(particleToExclude), std::get<1>(particleToExclude))); } @@ -295,8 +307,10 @@ std::vector> Molecule::getExclusions() const const std::string& residueName2 = std::get<3>(tup); // look up first index (binary search) - auto it1 = std::lower_bound(std::begin(indexKey), std::end(indexKey), - std::make_tuple(particleName1, residueName2, 0), sortKey); + auto it1 = std::lower_bound(std::begin(indexKey), + std::end(indexKey), + std::make_tuple(particleName1, residueName2, 0), + sortKey); // make sure we have the (particleName,residueName) combo if (it1 == std::end(indexKey) or std::get<0>(*it1) != particleName1 or std::get<1>(*it1) != residueName1) @@ -309,8 +323,10 @@ std::vector> Molecule::getExclusions() const int firstIndex = std::get<2>(*it1); // look up second index (binary search) - auto it2 = std::lower_bound(std::begin(indexKey), std::end(indexKey), - std::make_tuple(particleName2, residueName2, 0), sortKey); + auto it2 = std::lower_bound(std::begin(indexKey), + std::end(indexKey), + std::make_tuple(particleName2, residueName2, 0), + sortKey); // make sure we have the (particleName,residueName) combo if (it2 == std::end(indexKey) or std::get<0>(*it2) != particleName2 or std::get<1>(*it2) != residueName2) diff --git a/api/nblib/molecules.h b/api/nblib/molecules.h index 33b5dbe0bd..d9a4cdab9d 100644 --- a/api/nblib/molecules.h +++ b/api/nblib/molecules.h @@ -249,10 +249,12 @@ private: }; //! \cond DO_NOT_DOCUMENT -#define ADD_INTERACTION_EXTERN_TEMPLATE(x) \ - extern template void Molecule::addInteraction( \ - const ParticleName& particleNameI, const ResidueName& residueNameI, \ - const ParticleName& particleNameJ, const ResidueName& residueNameJ, const x& interaction); +#define ADD_INTERACTION_EXTERN_TEMPLATE(x) \ + extern template void Molecule::addInteraction(const ParticleName& particleNameI, \ + const ResidueName& residueNameI, \ + const ParticleName& particleNameJ, \ + const ResidueName& residueNameJ, \ + const x& interaction); MAP(ADD_INTERACTION_EXTERN_TEMPLATE, SUPPORTED_TWO_CENTER_TYPES) #undef ADD_INTERACTION_EXTERN_TEMPLATE @@ -262,18 +264,22 @@ MAP(ADD_INTERACTION_EXTERN_TEMPLATE, SUPPORTED_TWO_CENTER_TYPES) MAP(ADD_INTERACTION_EXTERN_TEMPLATE, SUPPORTED_TWO_CENTER_TYPES) #undef ADD_INTERACTION_EXTERN_TEMPLATE -#define ADD_INTERACTION_EXTERN_TEMPLATE(x) \ - extern template void Molecule::addInteraction( \ - const ParticleName& particleNameI, const ResidueName& residueNameI, \ - const ParticleName& particleNameJ, const ResidueName& residueNameJ, \ - const ParticleName& particleNameK, const ResidueName& residueNameK, const x& interaction); +#define ADD_INTERACTION_EXTERN_TEMPLATE(x) \ + extern template void Molecule::addInteraction(const ParticleName& particleNameI, \ + const ResidueName& residueNameI, \ + const ParticleName& particleNameJ, \ + const ResidueName& residueNameJ, \ + const ParticleName& particleNameK, \ + const ResidueName& residueNameK, \ + const x& interaction); MAP(ADD_INTERACTION_EXTERN_TEMPLATE, SUPPORTED_THREE_CENTER_TYPES) #undef ADD_INTERACTION_EXTERN_TEMPLATE -#define ADD_INTERACTION_EXTERN_TEMPLATE(x) \ - extern template void Molecule::addInteraction( \ - const ParticleName& particleNameI, const ParticleName& particleNameJ, \ - const ParticleName& particleNameK, const x& interaction); +#define ADD_INTERACTION_EXTERN_TEMPLATE(x) \ + extern template void Molecule::addInteraction(const ParticleName& particleNameI, \ + const ParticleName& particleNameJ, \ + const ParticleName& particleNameK, \ + const x& interaction); MAP(ADD_INTERACTION_EXTERN_TEMPLATE, SUPPORTED_THREE_CENTER_TYPES) #undef ADD_INTERACTION_EXTERN_TEMPLATE //! \endcond diff --git a/api/nblib/ppmap.h b/api/nblib/ppmap.h index 3f1b392fab..a138945479 100644 --- a/api/nblib/ppmap.h +++ b/api/nblib/ppmap.h @@ -130,10 +130,71 @@ */ #define PP_NARG(...) PP_NARG_(__VA_ARGS__, PP_RSEQ_N()) #define PP_NARG_(...) PP_ARG_N(__VA_ARGS__) -#define PP_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, \ - _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, \ - _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, \ - _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, N, ...) \ +#define PP_ARG_N(_1, \ + _2, \ + _3, \ + _4, \ + _5, \ + _6, \ + _7, \ + _8, \ + _9, \ + _10, \ + _11, \ + _12, \ + _13, \ + _14, \ + _15, \ + _16, \ + _17, \ + _18, \ + _19, \ + _20, \ + _21, \ + _22, \ + _23, \ + _24, \ + _25, \ + _26, \ + _27, \ + _28, \ + _29, \ + _30, \ + _31, \ + _32, \ + _33, \ + _34, \ + _35, \ + _36, \ + _37, \ + _38, \ + _39, \ + _40, \ + _41, \ + _42, \ + _43, \ + _44, \ + _45, \ + _46, \ + _47, \ + _48, \ + _49, \ + _50, \ + _51, \ + _52, \ + _53, \ + _54, \ + _55, \ + _56, \ + _57, \ + _58, \ + _59, \ + _60, \ + _61, \ + _62, \ + _63, \ + N, \ + ...) \ N #define PP_RSEQ_N() \ 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, \ diff --git a/api/nblib/samples/argon-forces-integration.cpp b/api/nblib/samples/argon-forces-integration.cpp index 9aacc2adb5..45e2d922f9 100644 --- a/api/nblib/samples/argon-forces-integration.cpp +++ b/api/nblib/samples/argon-forces-integration.cpp @@ -120,17 +120,23 @@ int main() gmx::ArrayRef userForces(simState.forces()); forceCalculator.compute(simState.coordinates(), userForces); // Print some diagnostic info - printf(" final forces on particle 0: x %4f y %4f z %4f\n", userForces[0][0], userForces[0][1], + printf(" final forces on particle 0: x %4f y %4f z %4f\n", + userForces[0][0], + userForces[0][1], userForces[0][2]); // User may modify forces stored in simState.forces() if needed // Print some diagnostic info - printf("initial position of particle 0: x %4f y %4f z %4f\n", simState.coordinates()[0][0], - simState.coordinates()[0][1], simState.coordinates()[0][2]); + printf("initial position of particle 0: x %4f y %4f z %4f\n", + simState.coordinates()[0][0], + simState.coordinates()[0][1], + simState.coordinates()[0][2]); // Integrate with a time step of 1 fs integrator.integrate(1.0, simState.coordinates(), simState.velocities(), simState.forces()); // Print some diagnostic info - printf(" final position of particle 0: x %4f y %4f z %4f\n", simState.coordinates()[0][0], - simState.coordinates()[0][1], simState.coordinates()[0][2]); + printf(" final position of particle 0: x %4f y %4f z %4f\n", + simState.coordinates()[0][0], + simState.coordinates()[0][1], + simState.coordinates()[0][2]); return 0; } diff --git a/api/nblib/tests/integrator.cpp b/api/nblib/tests/integrator.cpp index d4b9f3de97..6d26988a1b 100644 --- a/api/nblib/tests/integrator.cpp +++ b/api/nblib/tests/integrator.cpp @@ -116,17 +116,21 @@ TEST(NBlibTest, IntegratorWorks) << formatString( "Coordinate {} of atom {} is different from analytical solution " "at step {}.", - d, i, step); + d, + i, + step); EXPECT_REAL_EQ_TOL(vAnalytical[d], simulationState.velocities()[i][d], tolerance) << formatString( "Velocity component {} of atom {} is different from analytical " "solution at step {}.", - d, i, step); + d, + i, + step); } } - integrator.integrate(dt, simulationState.coordinates(), simulationState.velocities(), - simulationState.forces()); + integrator.integrate( + dt, simulationState.coordinates(), simulationState.velocities(), simulationState.forces()); } } diff --git a/api/nblib/tests/interactions.cpp b/api/nblib/tests/interactions.cpp index bb93f5dfd3..ca6a950d03 100644 --- a/api/nblib/tests/interactions.cpp +++ b/api/nblib/tests/interactions.cpp @@ -87,18 +87,22 @@ TEST(NBlibTest, NonBondedForceParamsCorrect) EXPECT_REAL_EQ_TOL(c12_1, nbfp.getC12(atom1.name(), atom1.name()), gmx::test::defaultRealTolerance()); //! geometric comb rule for c6 - EXPECT_REAL_EQ_TOL(std::sqrt(c6_1 * c6_2), nbfp.getC6(atom1.name(), atom2.name()), + EXPECT_REAL_EQ_TOL(std::sqrt(c6_1 * c6_2), + nbfp.getC6(atom1.name(), atom2.name()), gmx::test::defaultRealTolerance()); //! + symmetric pair - EXPECT_REAL_EQ_TOL(std::sqrt(c6_1 * c6_2), nbfp.getC6(atom2.name(), atom1.name()), + EXPECT_REAL_EQ_TOL(std::sqrt(c6_1 * c6_2), + nbfp.getC6(atom2.name(), atom1.name()), gmx::test::defaultRealTolerance()); //! geometric comb rule for c12 - EXPECT_REAL_EQ_TOL(std::sqrt(c12_1 * c12_2), nbfp.getC12(atom1.name(), atom2.name()), + EXPECT_REAL_EQ_TOL(std::sqrt(c12_1 * c12_2), + nbfp.getC12(atom1.name(), atom2.name()), gmx::test::defaultRealTolerance()); //! + symmetric par - EXPECT_REAL_EQ_TOL(std::sqrt(c12_1 * c12_2), nbfp.getC12(atom2.name(), atom1.name()), + EXPECT_REAL_EQ_TOL(std::sqrt(c12_1 * c12_2), + nbfp.getC12(atom2.name(), atom1.name()), gmx::test::defaultRealTolerance()); //! explicit pairwise interaction c6 @@ -106,10 +110,10 @@ TEST(NBlibTest, NonBondedForceParamsCorrect) EXPECT_REAL_EQ_TOL(c6comb, nbfp.getC6(atom3.name(), atom2.name()), gmx::test::defaultRealTolerance()); //! explicit pairwise interaction c12 - EXPECT_REAL_EQ_TOL(c12comb, nbfp.getC12(atom2.name(), atom3.name()), - gmx::test::defaultRealTolerance()); - EXPECT_REAL_EQ_TOL(c12comb, nbfp.getC12(atom3.name(), atom2.name()), - gmx::test::defaultRealTolerance()); + EXPECT_REAL_EQ_TOL( + c12comb, nbfp.getC12(atom2.name(), atom3.name()), gmx::test::defaultRealTolerance()); + EXPECT_REAL_EQ_TOL( + c12comb, nbfp.getC12(atom3.name(), atom2.name()), gmx::test::defaultRealTolerance()); ParticleType atom4(ParticleTypeName("a4"), Mass(1)); interactions.add(atom3.name(), atom4.name(), C6(1), C12(2)); @@ -160,14 +164,16 @@ TEST(NBlibTest, CanMergeInteractions) auto nbfp = interactions.generateTable(); - EXPECT_REAL_EQ_TOL(std::sqrt(c6_3 * c6_4), nbfp.getC6(atom3.name(), atom4.name()), - gmx::test::defaultRealTolerance()); - EXPECT_REAL_EQ_TOL(std::sqrt(c12_3 * c12_4), nbfp.getC12(atom3.name(), atom4.name()), - gmx::test::defaultRealTolerance()); - EXPECT_REAL_EQ_TOL(c6_override, nbfp.getC6(atom4.name(), atom5.name()), + EXPECT_REAL_EQ_TOL(std::sqrt(c6_3 * c6_4), + nbfp.getC6(atom3.name(), atom4.name()), gmx::test::defaultRealTolerance()); - EXPECT_REAL_EQ_TOL(c12_override, nbfp.getC12(atom4.name(), atom5.name()), + EXPECT_REAL_EQ_TOL(std::sqrt(c12_3 * c12_4), + nbfp.getC12(atom3.name(), atom4.name()), gmx::test::defaultRealTolerance()); + EXPECT_REAL_EQ_TOL( + c6_override, nbfp.getC6(atom4.name(), atom5.name()), gmx::test::defaultRealTolerance()); + EXPECT_REAL_EQ_TOL( + c12_override, nbfp.getC12(atom4.name(), atom5.name()), gmx::test::defaultRealTolerance()); } } // namespace diff --git a/api/nblib/tests/nbkernelsystem.cpp b/api/nblib/tests/nbkernelsystem.cpp index 816a545dfb..3e15e93878 100644 --- a/api/nblib/tests/nbkernelsystem.cpp +++ b/api/nblib/tests/nbkernelsystem.cpp @@ -121,8 +121,8 @@ TEST(NBlibTest, CanIntegrateSystem) { gmx::ArrayRef forces(simState.forces()); forceCalculator.compute(simState.coordinates(), simState.forces()); - EXPECT_NO_THROW(integrator.integrate(1.0, simState.coordinates(), simState.velocities(), - simState.forces())); + EXPECT_NO_THROW(integrator.integrate( + 1.0, simState.coordinates(), simState.velocities(), simState.forces())); } } diff --git a/api/nblib/tests/testsystems.cpp b/api/nblib/tests/testsystems.cpp index cb8f8bc236..43e6f45522 100644 --- a/api/nblib/tests/testsystems.cpp +++ b/api/nblib/tests/testsystems.cpp @@ -180,8 +180,8 @@ Topology WaterTopologyBuilder::buildTopology(int numMolecules) std::vector typeNames = { "Ow", "H" }; for (const auto& name : typeNames) { - interactions.add(ParticleTypeName(name), library.c6(ParticleName(name)), - library.c12(ParticleName(name))); + interactions.add( + ParticleTypeName(name), library.c6(ParticleName(name)), library.c12(ParticleName(name))); } // Add some molecules to the topology @@ -208,8 +208,8 @@ Topology SpcMethanolTopologyBuilder::buildTopology(int numWater, int numMethanol std::vector typeNames = { "Ow", "H", "OMet", "CMet" }; for (const auto& name : typeNames) { - interactions.add(ParticleTypeName(name), library.c6(ParticleName(name)), - library.c12(ParticleName(name))); + interactions.add( + ParticleTypeName(name), library.c6(ParticleName(name)), library.c12(ParticleName(name))); } // Add some molecules to the topology @@ -239,8 +239,8 @@ ArgonTopologyBuilder::ArgonTopologyBuilder(const int& numParticles) ParticleLibrary library; ParticleTypesInteractions nbinteractions; - nbinteractions.add(ParticleTypeName("Ar"), library.c6(ParticleName("Ar")), - library.c12(ParticleName("Ar"))); + nbinteractions.add( + ParticleTypeName("Ar"), library.c6(ParticleName("Ar")), library.c12(ParticleName("Ar"))); Molecule argonMolecule(MoleculeName("AR")); argonMolecule.addParticle(ParticleName("AR"), library.type("Ar")); diff --git a/api/nblib/tests/topology.cpp b/api/nblib/tests/topology.cpp index bf9bc58727..5d625d2fee 100644 --- a/api/nblib/tests/topology.cpp +++ b/api/nblib/tests/topology.cpp @@ -182,12 +182,10 @@ TEST(NBlibTest, TopologyHasSequencing) WaterTopologyBuilder waters; Topology watersTopology = waters.buildTopology(2); - EXPECT_EQ(0, watersTopology.sequenceID(MoleculeName("SOL"), 0, ResidueName("SOL"), - ParticleName("Oxygen"))); + EXPECT_EQ(0, watersTopology.sequenceID(MoleculeName("SOL"), 0, ResidueName("SOL"), ParticleName("Oxygen"))); EXPECT_EQ(1, watersTopology.sequenceID(MoleculeName("SOL"), 0, ResidueName("SOL"), ParticleName("H1"))); EXPECT_EQ(2, watersTopology.sequenceID(MoleculeName("SOL"), 0, ResidueName("SOL"), ParticleName("H2"))); - EXPECT_EQ(3, watersTopology.sequenceID(MoleculeName("SOL"), 1, ResidueName("SOL"), - ParticleName("Oxygen"))); + EXPECT_EQ(3, watersTopology.sequenceID(MoleculeName("SOL"), 1, ResidueName("SOL"), ParticleName("Oxygen"))); EXPECT_EQ(4, watersTopology.sequenceID(MoleculeName("SOL"), 1, ResidueName("SOL"), ParticleName("H1"))); EXPECT_EQ(5, watersTopology.sequenceID(MoleculeName("SOL"), 1, ResidueName("SOL"), ParticleName("H2"))); } @@ -205,7 +203,9 @@ TEST(NBlibTest, TopologyCanAggregateBonds) std::vector bondsTest; // use the expansionArray (bondsExpansion) to expand to the full list if bonds - std::transform(begin(bondsExpansion), end(bondsExpansion), std::back_inserter(bondsTest), + std::transform(begin(bondsExpansion), + end(bondsExpansion), + std::back_inserter(bondsTest), [&bonds](size_t i) { return bonds[i]; }); std::vector waterBonds = @@ -349,8 +349,8 @@ TEST(NBlibTest, TopologyListedInteractions) #undef SORT /// \endcond - EXPECT_TRUE(std::equal(begin(interactions_reference), end(interactions_reference), - begin(interactions_test))); + EXPECT_TRUE(std::equal( + begin(interactions_reference), end(interactions_reference), begin(interactions_test))); } TEST(NBlibTest, TopologyListedInteractionsMultipleTypes) @@ -401,8 +401,9 @@ TEST(NBlibTest, TopologyListedInteractionsMultipleTypes) int MeH1 = topology.sequenceID(MoleculeName("MeOH"), 0, ResidueName("MeOH"), ParticleName("H3")); std::vector cubicBondsReference{ testBond }; - std::vector> cubicIndicesReference{ { std::min(H1, H2), - std::max(H1, H2), 0 } }; + std::vector> cubicIndicesReference{ + { std::min(H1, H2), std::max(H1, H2), 0 } + }; EXPECT_EQ(cubicBondsReference, cubicBonds.parameters); EXPECT_EQ(cubicIndicesReference, cubicBonds.indices); diff --git a/api/nblib/topology.cpp b/api/nblib/topology.cpp index 71062a3a66..ca5b3df8c2 100644 --- a/api/nblib/topology.cpp +++ b/api/nblib/topology.cpp @@ -85,7 +85,8 @@ gmx::ListOfLists TopologyBuilder::createExclusionsListOfLists() const auto offsetExclusions = detail::offsetGmxBlock(exclusionBlockPerMolecule, particleNumberOffset); - std::copy(std::begin(offsetExclusions), std::end(offsetExclusions), + std::copy(std::begin(offsetExclusions), + std::end(offsetExclusions), std::back_inserter(exclusionBlockGlobal)); particleNumberOffset += molecule.numParticlesInMolecule(); @@ -125,7 +126,9 @@ ListedInteractionData TopologyBuilder::createInteractionData(const detail::Parti // combine stage 1 + 2 expansion arrays std::vector expansionArray(expansionArrayStage1.size()); - std::transform(begin(expansionArrayStage1), end(expansionArrayStage1), begin(expansionArray), + std::transform(begin(expansionArrayStage1), + end(expansionArrayStage1), + begin(expansionArray), [& S2 = expansionArrayStage2](size_t S1Element) { return S2[S1Element]; }); // add data about InteractionType instances @@ -135,7 +138,9 @@ ListedInteractionData TopologyBuilder::createInteractionData(const detail::Parti // coordinateIndices contains the particle sequence IDs of all interaction coordinates of type auto coordinateIndices = detail::sequenceIDs(this->molecules_, particleSequencer); // zip coordinateIndices(i,j,...) + expansionArray(k) -> interactionDataElement.indices(i,j,...,k) - std::transform(begin(coordinateIndices), end(coordinateIndices), begin(expansionArray), + std::transform(begin(coordinateIndices), + end(coordinateIndices), + begin(expansionArray), begin(interactionDataElement.indices), [](auto coordinateIndex, auto interactionIndex) { std::array ret{ 0 }; @@ -230,7 +235,8 @@ Topology TopologyBuilder::buildTopology() { std::string message = formatString("Missing nonbonded interaction parameters for pair {} {}", - particleType1.first, particleType2.first); + particleType1.first, + particleType2.first); throw InputException(message); } } diff --git a/api/nblib/topologyhelpers.cpp b/api/nblib/topologyhelpers.cpp index 47dee71d09..3a57ca375b 100644 --- a/api/nblib/topologyhelpers.cpp +++ b/api/nblib/topologyhelpers.cpp @@ -102,8 +102,10 @@ std::vector offsetGmxBlock(std::vector // shift particle numbers by offset for (auto& localBlock : inBlock) { - std::transform(std::begin(localBlock.atomNumber), std::end(localBlock.atomNumber), - std::begin(localBlock.atomNumber), [offset](auto i) { return i + offset; }); + std::transform(std::begin(localBlock.atomNumber), + std::end(localBlock.atomNumber), + std::begin(localBlock.atomNumber), + [offset](auto i) { return i + offset; }); } return inBlock; @@ -123,12 +125,15 @@ int ParticleSequencer::operator()(const MoleculeName& moleculeName, // TODO: use string format function once we have it if (moleculeName.value() == residueName.value()) { - printf("No particle %s in residue %s in molecule %s found\n", particleName.value().c_str(), - residueName.value().c_str(), moleculeName.value().c_str()); + printf("No particle %s in residue %s in molecule %s found\n", + particleName.value().c_str(), + residueName.value().c_str(), + moleculeName.value().c_str()); } else { - printf("No particle %s in molecule %s found\n", particleName.value().c_str(), + printf("No particle %s in molecule %s found\n", + particleName.value().c_str(), moleculeName.value().c_str()); } @@ -201,8 +206,8 @@ auto stringsToIndices_impl(const Tuple& tuple, std::index_sequence is, F& { // return std::make_tuple(f(args..., std::get<2 * Is + 1>(tuple), std::get<2 * Is>(tuple))...); ignore_unused(is); - return std::array{ f(args..., std::get<2 * Is + 1>(tuple), - std::get<2 * Is>(tuple))... }; + return std::array{ f( + args..., std::get<2 * Is + 1>(tuple), std::get<2 * Is>(tuple))... }; } /*! \brief @@ -266,7 +271,8 @@ std::vector> sequenceIDs(const std::vector> coordinateIndices; - auto callSequencer = [&particleSequencer](const MoleculeName& moleculeName, int i, + auto callSequencer = [&particleSequencer](const MoleculeName& moleculeName, + int i, const ResidueName& residueName, const ParticleName& particleName) { return particleSequencer(moleculeName, i, residueName, particleName); @@ -316,8 +322,11 @@ std::tuple, std::vector> eliminateDuplicateInteractions(c std::vector> enumeratedBonds(aggregatedInteractions.size()); // append each interaction with its index - std::transform(begin(aggregatedInteractions), end(aggregatedInteractions), begin(uniqueIndices), - begin(enumeratedBonds), [](I b, size_t i) { return std::make_tuple(b, i); }); + std::transform(begin(aggregatedInteractions), + end(aggregatedInteractions), + begin(uniqueIndices), + begin(enumeratedBonds), + [](I b, size_t i) { return std::make_tuple(b, i); }); auto sortKey = [](const auto& t1, const auto& t2) { return std::get<0>(t1) < std::get<0>(t2); }; // sort w.r.t bonds. the result will contain contiguous segments of identical bond instances diff --git a/api/nblib/util/user.cpp b/api/nblib/util/user.cpp index 0019143f78..3c087f8f97 100644 --- a/api/nblib/util/user.cpp +++ b/api/nblib/util/user.cpp @@ -118,7 +118,8 @@ static std::vector low_mspeed(real tempi, std::vector const& masses, fprintf(debug, "Velocities were taken from a Maxwell distribution\n" "Initial generated temperature: %12.5e (scaled to: %12.5e)\n", - temp, tempi); + temp, + tempi); } return velocities; diff --git a/python_packaging/src/gmxapi/export_context.cpp b/python_packaging/src/gmxapi/export_context.cpp index f618f052b7..4b8d15adb8 100644 --- a/python_packaging/src/gmxapi/export_context.cpp +++ b/python_packaging/src/gmxapi/export_context.cpp @@ -158,7 +158,8 @@ void export_context(py::module& m) // Add argument type before it is used for more sensible automatic bindings behavior. py::class_> mdargs(m, "MDArgs"); mdargs.def(py::init(), "Create an empty MDArgs object."); - mdargs.def("set", [](MDArgs* self, const py::dict& params) { setMDArgs(self, params); }, + mdargs.def("set", + [](MDArgs* self, const py::dict& params) { setMDArgs(self, params); }, "Assign parameters in MDArgs from Python dict."); // Export execution context class diff --git a/python_packaging/src/gmxapi/export_exceptions.cpp b/python_packaging/src/gmxapi/export_exceptions.cpp index fd864f5ada..a8012618a8 100644 --- a/python_packaging/src/gmxapi/export_exceptions.cpp +++ b/python_packaging/src/gmxapi/export_exceptions.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -87,8 +87,8 @@ void export_exceptions(pybind11::module& m) struct UnknownExceptionPlaceHolder { }; - static py::exception unknownException(m, "UnknownException", - baseException.ptr()); + static py::exception unknownException( + m, "UnknownException", baseException.ptr()); unknownException.doc() = "GROMACS library produced an exception that is " "not mapped in gmxapi or which should have been " diff --git a/python_packaging/src/gmxapi/export_system.cpp b/python_packaging/src/gmxapi/export_system.cpp index 91463edcff..bbb68ed0f8 100644 --- a/python_packaging/src/gmxapi/export_system.cpp +++ b/python_packaging/src/gmxapi/export_system.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -75,7 +75,8 @@ void export_system(py::module& m) // required to maintain and to pass to the API. py::class_<::gmxapi::Session, std::shared_ptr<::gmxapi::Session>> session(m, "MDSession"); session.def("run", &::gmxapi::Session::run, "Run the simulation workflow"); - session.def("close", &::gmxapi::Session::close, + session.def("close", + &::gmxapi::Session::close, "Shut down the execution environment and close the session."); // Export system container class @@ -88,7 +89,8 @@ void export_system(py::module& m) "Launch the configured workflow in the provided context."); // Module-level function - m.def("from_tpr", &gmxpy::from_tpr, + m.def("from_tpr", + &gmxpy::from_tpr, "Return a system container initialized from the given input record."); } diff --git a/python_packaging/src/gmxapi/export_tprfile.cpp b/python_packaging/src/gmxapi/export_tprfile.cpp index 9a80297e45..4f7301e2df 100644 --- a/python_packaging/src/gmxapi/export_tprfile.cpp +++ b/python_packaging/src/gmxapi/export_tprfile.cpp @@ -112,19 +112,22 @@ void detail::export_tprfile(pybind11::module& module) [](GmxMdParams* self, const std::string& key, int64_t value) { gmxapicompat::setParam(self, key, value); }, - py::arg("key").none(false), py::arg("value").none(false), + py::arg("key").none(false), + py::arg("value").none(false), "Use a dictionary to update simulation parameters."); mdparams.def("set", [](GmxMdParams* self, const std::string& key, double value) { gmxapicompat::setParam(self, key, value); }, - py::arg("key").none(false), py::arg("value").none(false), + py::arg("key").none(false), + py::arg("value").none(false), "Use a dictionary to update simulation parameters."); mdparams.def("set", [](GmxMdParams* self, const std::string& key, py::none) { // unsetParam(self, key); }, - py::arg("key").none(false), py::arg("value"), + py::arg("key").none(false), + py::arg("value"), "Use a dictionary to update simulation parameters."); @@ -134,7 +137,9 @@ void detail::export_tprfile(pybind11::module& module) return params; }); - module.def("read_tprfile", &readTprFile, py::arg("filename"), + module.def("read_tprfile", + &readTprFile, + py::arg("filename"), "Get a handle to a TPR file resource for a given file name."); module.def("write_tprfile", @@ -146,21 +151,25 @@ void detail::export_tprfile(pybind11::module& module) auto topology = gmxapicompat::getTopologySource(tprReadHandle); gmxapicompat::writeTprFile(filename, *params, *structure, *state, *topology); }, - py::arg("filename").none(false), py::arg("parameters"), + py::arg("filename").none(false), + py::arg("parameters"), "Write a new TPR file with the provided data."); module.def("copy_tprfile", [](const gmxapicompat::TprReadHandle& input, std::string outFile) { return gmxapicompat::copy_tprfile(input, outFile); }, - py::arg("source"), py::arg("destination"), + py::arg("source"), + py::arg("destination"), "Copy a TPR file from ``source`` to ``destination``."); module.def("rewrite_tprfile", [](std::string input, std::string output, double end_time) { return gmxapicompat::rewrite_tprfile(input, output, end_time); }, - py::arg("source"), py::arg("destination"), py::arg("end_time"), + py::arg("source"), + py::arg("destination"), + py::arg("end_time"), "Copy a TPR file from ``source`` to ``destination``, replacing `nsteps` with " "``end_time``."); } diff --git a/python_packaging/src/gmxapi/module.cpp b/python_packaging/src/gmxapi/module.cpp index 0496dc2b8a..1601cbae14 100644 --- a/python_packaging/src/gmxapi/module.cpp +++ b/python_packaging/src/gmxapi/module.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -88,7 +88,8 @@ PYBIND11_MODULE(_gmxapi, m) export_exceptions(m); // Export core bindings - m.def("has_feature", &gmxapi::Version::hasFeature, + m.def("has_feature", + &gmxapi::Version::hasFeature, "Check the gmxapi library for a named feature."); py::class_<::gmxapi::Status> gmx_status(m, "Status", "Holds status for API operations."); diff --git a/src/api/cpp/tests/testingconfiguration.h b/src/api/cpp/tests/testingconfiguration.h index e7180f8984..1becf04088 100644 --- a/src/api/cpp/tests/testingconfiguration.h +++ b/src/api/cpp/tests/testingconfiguration.h @@ -112,7 +112,8 @@ public: "tau-t = 1\n" "ref-t = 298\n" "compressed-x-grps = Sol\n", - steps, getTestStepSize())); + steps, + getTestStepSize())); EXPECT_EQ(0, runner_.callGromppOnThisRank()); } diff --git a/src/gromacs/analysisdata/arraydata.cpp b/src/gromacs/analysisdata/arraydata.cpp index 8dfa05a572..de6436e46c 100644 --- a/src/gromacs/analysisdata/arraydata.cpp +++ b/src/gromacs/analysisdata/arraydata.cpp @@ -171,8 +171,7 @@ void AbstractAnalysisArrayData::valuesReady() AnalysisDataFrameHeader header(i, xvalue(i), 0); modules.notifyFrameStart(header); modules.notifyPointsAdd(AnalysisDataPointSetRef( - header, pointSetInfo_, - makeConstArrayRef(value_).subArray(i * columnCount(), columnCount()))); + header, pointSetInfo_, makeConstArrayRef(value_).subArray(i * columnCount(), columnCount()))); modules.notifyFrameFinish(header); } modules.notifyDataFinish(); diff --git a/src/gromacs/analysisdata/datastorage.cpp b/src/gromacs/analysisdata/datastorage.cpp index 78f379e869..0601192788 100644 --- a/src/gromacs/analysisdata/datastorage.cpp +++ b/src/gromacs/analysisdata/datastorage.cpp @@ -674,8 +674,7 @@ void AnalysisDataStorageFrame::selectDataSet(int index) { GMX_RELEASE_ASSERT(data_ != nullptr, "Invalid frame accessed"); const AbstractAnalysisData& baseData = data_->baseData(); - GMX_RELEASE_ASSERT(index >= 0 && index < baseData.dataSetCount(), - "Out of range data set index"); + GMX_RELEASE_ASSERT(index >= 0 && index < baseData.dataSetCount(), "Out of range data set index"); GMX_RELEASE_ASSERT(!baseData.isMultipoint() || !bPointSetInProgress_, "Point sets in multipoint data cannot span data sets"); currentDataSet_ = index; @@ -712,8 +711,8 @@ void AnalysisDataStorageFrame::finishPointSet() { firstColumn = 0; } - data_->addPointSet(currentDataSet_, firstColumn, - makeConstArrayRef(values_).subArray(begin, end - begin)); + data_->addPointSet( + currentDataSet_, firstColumn, makeConstArrayRef(values_).subArray(begin, end - begin)); } clearValues(); } diff --git a/src/gromacs/analysisdata/modules/lifetime.cpp b/src/gromacs/analysisdata/modules/lifetime.cpp index f791cabd27..70ad587c59 100644 --- a/src/gromacs/analysisdata/modules/lifetime.cpp +++ b/src/gromacs/analysisdata/modules/lifetime.cpp @@ -195,7 +195,8 @@ void AnalysisDataLifetimeModule::dataFinished() // if explicitly requested. std::vector::iterator histogram; for (histogram = impl_->lifetimeHistograms_.begin(); - histogram != impl_->lifetimeHistograms_.end(); ++histogram) + histogram != impl_->lifetimeHistograms_.end(); + ++histogram) { Impl::LifetimeHistogram::iterator shorter, longer; for (shorter = histogram->begin(); shorter != histogram->end(); ++shorter) @@ -221,8 +222,8 @@ void AnalysisDataLifetimeModule::dataFinished() setColumnCount(impl_->lifetimeHistograms_.size()); std::vector::const_iterator histogram; size_t maxLifetime = 1; - for (histogram = impl_->lifetimeHistograms_.begin(); - histogram != impl_->lifetimeHistograms_.end(); ++histogram) + for (histogram = impl_->lifetimeHistograms_.begin(); histogram != impl_->lifetimeHistograms_.end(); + ++histogram) { maxLifetime = std::max(maxLifetime, histogram->size()); } @@ -231,8 +232,8 @@ void AnalysisDataLifetimeModule::dataFinished() // Fill up the output data from the histograms. allocateValues(); int column = 0; - for (histogram = impl_->lifetimeHistograms_.begin(); - histogram != impl_->lifetimeHistograms_.end(); ++histogram, ++column) + for (histogram = impl_->lifetimeHistograms_.begin(); histogram != impl_->lifetimeHistograms_.end(); + ++histogram, ++column) { int row = 0; Impl::LifetimeHistogram::const_iterator i; diff --git a/src/gromacs/analysisdata/modules/plot.cpp b/src/gromacs/analysisdata/modules/plot.cpp index 0ea52a0b8d..09fab9e125 100644 --- a/src/gromacs/analysisdata/modules/plot.cpp +++ b/src/gromacs/analysisdata/modules/plot.cpp @@ -89,8 +89,9 @@ void AnalysisDataPlotSettings::setSelectionCollection(const SelectionCollection* * Technically this duplicates a definition in pargs.cpp for legacy * support code, but as the latter will go away and the alternatives * are ugly, the duplication is acceptable. */ -const gmx::EnumerationArray c_xvgFormatNames = { { "xmgrace", "xmgr", - "none" } }; +const gmx::EnumerationArray c_xvgFormatNames = { + { "xmgrace", "xmgr", "none" } +}; void AnalysisDataPlotSettings::initOptions(IOptionsContainer* options) { @@ -312,8 +313,8 @@ void AbstractPlotModule::dataStarted(AbstractAnalysisData* /* data */) gmx_output_env_t* oenv; output_env_init(&oenv, getProgramContext(), timeUnit, FALSE, xvgFormat, 0); const unique_cptr oenvGuard(oenv); - impl_->fp_ = xvgropen(impl_->filename_.c_str(), impl_->title_.c_str(), impl_->xlabel_, - impl_->ylabel_, oenv); + impl_->fp_ = xvgropen( + impl_->filename_.c_str(), impl_->title_.c_str(), impl_->xlabel_, impl_->ylabel_, oenv); const SelectionCollection* selections = impl_->settings_.selectionCollection(); if (selections != nullptr && output_env_get_xvg_format(oenv) != XvgFormat::None) { diff --git a/src/gromacs/analysisdata/tests/datatest.cpp b/src/gromacs/analysisdata/tests/datatest.cpp index e8009f40a1..4bf7a4ef12 100644 --- a/src/gromacs/analysisdata/tests/datatest.cpp +++ b/src/gromacs/analysisdata/tests/datatest.cpp @@ -216,12 +216,15 @@ void AnalysisDataTestFixture::presentDataFrame(const AnalysisDataTestInput& inpu { if (points.hasError(j)) { - handle.setPoint(j + points.firstColumn(), points.y(j), points.error(j), + handle.setPoint(j + points.firstColumn(), + points.y(j), + points.error(j), AnalysisDataTestInputPointSet::present(j)); } else { - handle.setPoint(j + points.firstColumn(), points.y(j), + handle.setPoint(j + points.firstColumn(), + points.y(j), AnalysisDataTestInputPointSet::present(j)); } } diff --git a/src/gromacs/analysisdata/tests/mock_datamodule.cpp b/src/gromacs/analysisdata/tests/mock_datamodule.cpp index e0ccf94153..e99f5e8935 100644 --- a/src/gromacs/analysisdata/tests/mock_datamodule.cpp +++ b/src/gromacs/analysisdata/tests/mock_datamodule.cpp @@ -523,8 +523,8 @@ void MockAnalysisDataModule::setupStaticCheck(const AnalysisDataTestInput& data, for (int ps = 0; ps < frame.pointSetCount(); ++ps) { const AnalysisDataTestInputPointSet& points = frame.pointSet(ps); - StaticDataPointsChecker checker(&frame, &points, 0, - data.columnCount(points.dataSetIndex())); + StaticDataPointsChecker checker( + &frame, &points, 0, data.columnCount(points.dataSetIndex())); EXPECT_CALL(*this, pointsAdded(Property(&AnalysisDataPointSetRef::frameIndex, row))) .WillOnce(Invoke(checker)); } @@ -557,8 +557,8 @@ void MockAnalysisDataModule::setupStaticCheck(const AnalysisDataTestInput& data, for (int ps = 0; ps < frame.pointSetCount(); ++ps) { const AnalysisDataTestInputPointSet& points = frame.pointSet(ps); - StaticDataPointsChecker checker(&frame, &points, 0, - data.columnCount(points.dataSetIndex())); + StaticDataPointsChecker checker( + &frame, &points, 0, data.columnCount(points.dataSetIndex())); EXPECT_CALL(*this, pointsAdded(_)).WillOnce(Invoke(checker)); } EXPECT_CALL(*this, frameFinished(_)).WillOnce(Invoke(StaticDataFrameHeaderChecker(&frame))); diff --git a/src/gromacs/applied_forces/awh/awh.cpp b/src/gromacs/applied_forces/awh/awh.cpp index 0f3c8c28b4..4cf4249ca0 100644 --- a/src/gromacs/applied_forces/awh/awh.cpp +++ b/src/gromacs/applied_forces/awh/awh.cpp @@ -242,8 +242,8 @@ Awh::Awh(FILE* fplog, } double conversionFactor = pull_coordinate_is_angletype(&pullCoord) ? DEG2RAD : 1; pullCoordIndex.push_back(awhDimParams.coordIndex); - dimParams.push_back(DimParams::pullDimParams(conversionFactor, - awhDimParams.forceConstant, beta)); + dimParams.push_back(DimParams::pullDimParams( + conversionFactor, awhDimParams.forceConstant, beta)); } else { @@ -254,10 +254,16 @@ Awh::Awh(FILE* fplog, /* Construct the bias and couple it to the system. */ Bias::ThisRankWillDoIO thisRankWillDoIO = (MASTER(commRecord_) ? Bias::ThisRankWillDoIO::Yes : Bias::ThisRankWillDoIO::No); - biasCoupledToSystem_.emplace_back( - Bias(k, awhParams, awhParams.awhBiasParams[k], dimParams, beta, inputRecord.delta_t, - numSharingSimulations, biasInitFilename, thisRankWillDoIO), - pullCoordIndex); + biasCoupledToSystem_.emplace_back(Bias(k, + awhParams, + awhParams.awhBiasParams[k], + dimParams, + beta, + inputRecord.delta_t, + numSharingSimulations, + biasInitFilename, + thisRankWillDoIO), + pullCoordIndex); biasCoupledToSystem_.back().bias_.printInitializationToLog(fplog); } @@ -340,9 +346,18 @@ real Awh::applyBiasForcesAndUpdateBias(PbcType pbcType, /* Note: In the near future this call will be split in calls * to supports bias sharing within a single simulation. */ - gmx::ArrayRef biasForce = biasCts.bias_.calcForceAndUpdateBias( - coordValue, neighborLambdaEnergies, neighborLambdaDhdl, &biasPotential, - &biasPotentialJump, commRecord_, multiSimRecord_, t, step, seed_, fplog); + gmx::ArrayRef biasForce = + biasCts.bias_.calcForceAndUpdateBias(coordValue, + neighborLambdaEnergies, + neighborLambdaDhdl, + &biasPotential, + &biasPotentialJump, + commRecord_, + multiSimRecord_, + t, + step, + seed_, + fplog); awhPotential += biasPotential; @@ -358,8 +373,11 @@ real Awh::applyBiasForcesAndUpdateBias(PbcType pbcType, { if (biasCts.bias_.dimParams()[d].isPullDimension()) { - apply_external_pull_coord_force(pull_, biasCts.pullCoordIndex_[d - numLambdaDimsCounted], - biasForce[d], masses, forceWithVirial); + apply_external_pull_coord_force(pull_, + biasCts.pullCoordIndex_[d - numLambdaDimsCounted], + biasForce[d], + masses, + forceWithVirial); } else { @@ -471,8 +489,8 @@ void Awh::registerAwhWithPull(const AwhParams& awhParams, pull_t* pull_work) { if (biasParams.dimParams[d].eCoordProvider == eawhcoordproviderPULL) { - register_external_pull_potential(pull_work, biasParams.dimParams[d].coordIndex, - Awh::externalPotentialString()); + register_external_pull_potential( + pull_work, biasParams.dimParams[d].coordIndex, Awh::externalPotentialString()); } } } @@ -520,7 +538,8 @@ void Awh::writeToEnergyFrame(int64_t step, t_enxframe* frame) const bool Awh::hasFepLambdaDimension() const { return std::any_of( - std::begin(biasCoupledToSystem_), std::end(biasCoupledToSystem_), + std::begin(biasCoupledToSystem_), + std::end(biasCoupledToSystem_), [](const auto& coupledBias) { return coupledBias.bias_.hasFepLambdaDimension(); }); } @@ -568,9 +587,15 @@ std::unique_ptr prepareAwhModule(FILE* fplog, GMX_THROW(InvalidInputError("AWH biasing does not support shell particles.")); } - auto awh = std::make_unique( - fplog, inputRecord, commRecord, multiSimRecord, *inputRecord.awhParams, biasInitFilename, - pull_work, inputRecord.fepvals->n_lambda, inputRecord.fepvals->init_fep_state); + auto awh = std::make_unique(fplog, + inputRecord, + commRecord, + multiSimRecord, + *inputRecord.awhParams, + biasInitFilename, + pull_work, + inputRecord.fepvals->n_lambda, + inputRecord.fepvals->init_fep_state); if (startingFromCheckpoint) { diff --git a/src/gromacs/applied_forces/awh/bias.cpp b/src/gromacs/applied_forces/awh/bias.cpp index 5abd53402b..4021fc08d0 100644 --- a/src/gromacs/applied_forces/awh/bias.cpp +++ b/src/gromacs/applied_forces/awh/bias.cpp @@ -140,8 +140,7 @@ gmx::ArrayRef Bias::calcForceAndUpdateBias(const awh_dvec state_.doSkippedUpdatesInNeighborhood(params_, grid_); } convolvedBias = state_.updateProbabilityWeightsAndConvolvedBias( - dimParams_, grid_, moveUmbrella ? neighborLambdaEnergies : ArrayRef{}, - &probWeightNeighbor); + dimParams_, grid_, moveUmbrella ? neighborLambdaEnergies : ArrayRef{}, &probWeightNeighbor); if (isSampleCoordStep) { @@ -167,9 +166,12 @@ gmx::ArrayRef Bias::calcForceAndUpdateBias(const awh_dvec double potential; if (params_.convolveForce) { - state_.calcConvolvedForce(dimParams_, grid_, probWeightNeighbor, + state_.calcConvolvedForce(dimParams_, + grid_, + probWeightNeighbor, moveUmbrella ? neighborLambdaDhdl : ArrayRef{}, - tempForce_, biasForce_); + tempForce_, + biasForce_); potential = -convolvedBias * params_.invBeta; } @@ -180,8 +182,11 @@ gmx::ArrayRef Bias::calcForceAndUpdateBias(const awh_dvec "AWH bias grid point for the umbrella reference value is outside of the " "target region."); potential = state_.calcUmbrellaForceAndPotential( - dimParams_, grid_, coordState.umbrellaGridpoint(), - moveUmbrella ? neighborLambdaDhdl : ArrayRef{}, biasForce_); + dimParams_, + grid_, + coordState.umbrellaGridpoint(), + moveUmbrella ? neighborLambdaDhdl : ArrayRef{}, + biasForce_); /* Moving the umbrella results in a force correction and * a new potential. The umbrella center is sampled as often as @@ -191,18 +196,24 @@ gmx::ArrayRef Bias::calcForceAndUpdateBias(const awh_dvec if (moveUmbrella) { const bool onlySampleUmbrellaGridpoint = false; - double newPotential = state_.moveUmbrella(dimParams_, grid_, probWeightNeighbor, - neighborLambdaDhdl, biasForce_, step, seed, - params_.biasIndex, onlySampleUmbrellaGridpoint); - *potentialJump = newPotential - potential; + double newPotential = state_.moveUmbrella(dimParams_, + grid_, + probWeightNeighbor, + neighborLambdaDhdl, + biasForce_, + step, + seed, + params_.biasIndex, + onlySampleUmbrellaGridpoint); + *potentialJump = newPotential - potential; } } /* Update the free energy estimates and bias and other history dependent method parameters */ if (params_.isUpdateFreeEnergyStep(step)) { - state_.updateFreeEnergyAndAddSamplesToHistogram(dimParams_, grid_, params_, commRecord, ms, - t, step, fplog, &updateList_); + state_.updateFreeEnergyAndAddSamplesToHistogram( + dimParams_, grid_, params_, commRecord, ms, t, step, fplog, &updateList_); if (params_.convolveForce) { @@ -216,8 +227,15 @@ gmx::ArrayRef Bias::calcForceAndUpdateBias(const awh_dvec if (moveUmbrella && params_.convolveForce && grid_.hasLambdaAxis()) { const bool onlySampleUmbrellaGridpoint = true; - state_.moveUmbrella(dimParams_, grid_, probWeightNeighbor, neighborLambdaDhdl, biasForce_, - step, seed, params_.biasIndex, onlySampleUmbrellaGridpoint); + state_.moveUmbrella(dimParams_, + grid_, + probWeightNeighbor, + neighborLambdaDhdl, + biasForce_, + step, + seed, + params_.biasIndex, + onlySampleUmbrellaGridpoint); } /* Return the potential. */ @@ -266,8 +284,11 @@ static void ensureStateAndRunConsistency(const BiasParams& params, const BiasSta "The number of AWH updates in the checkpoint file (%" PRId64 ") does not match the total number of AWH samples divided by the number of samples " "per update for %d sharing AWH bias(es) (%" PRId64 "/%d=%" PRId64 ")", - numUpdatesExpected, params.numSharedUpdate, numSamples, - params.numSamplesUpdateFreeEnergy_ * params.numSharedUpdate, numUpdatesFromSamples); + numUpdatesExpected, + params.numSharedUpdate, + numSamples, + params.numSamplesUpdateFreeEnergy_ * params.numSharedUpdate, + numUpdatesFromSamples); mesg += " Maybe you changed AWH parameters."; /* Unfortunately we currently do not store the number of simulations * sharing the bias or the state to checkpoint. But we can hint at @@ -278,7 +299,8 @@ static void ensureStateAndRunConsistency(const BiasParams& params, const BiasSta mesg += gmx::formatString( " Or the run you continued from used %" PRId64 " sharing simulations, whereas you now specified %d sharing simulations.", - numUpdatesFromSamples / state.histogramSize().numUpdates(), params.numSharedUpdate); + numUpdatesFromSamples / state.histogramSize().numUpdates(), + params.numSharedUpdate); } GMX_THROW(InvalidInputError(mesg)); } @@ -379,9 +401,12 @@ Bias::Bias(int biasIndexInCollection, */ double blockLength = 0; /* Construct the force correlation object. */ - forceCorrelationGrid_ = std::make_unique( - state_.points().size(), ndim(), blockLength, - CorrelationGrid::BlockLengthMeasure::Time, awhParams.nstSampleCoord * mdTimeStep); + forceCorrelationGrid_ = + std::make_unique(state_.points().size(), + ndim(), + blockLength, + CorrelationGrid::BlockLengthMeasure::Time, + awhParams.nstSampleCoord * mdTimeStep); writer_ = std::make_unique(*this); } @@ -396,11 +421,13 @@ void Bias::printInitializationToLog(FILE* fplog) const fprintf(fplog, "%s initial force correlation block length = %g %s" "%s force correlation number of blocks = %d", - prefix.c_str(), forceCorrelationGrid().getBlockLength(), + prefix.c_str(), + forceCorrelationGrid().getBlockLength(), forceCorrelationGrid().blockLengthMeasure == CorrelationGrid::BlockLengthMeasure::Weight ? "" : "ps", - prefix.c_str(), forceCorrelationGrid().getNumBlocks()); + prefix.c_str(), + forceCorrelationGrid().getNumBlocks()); } } @@ -426,8 +453,8 @@ void Bias::updateForceCorrelationGrid(gmx::ArrayRef probWeightNeig We actually add the force normalized by beta which has the units of 1/length. This means that the resulting correlation time integral is directly in units of friction time/length^2 which is really what we're interested in. */ - state_.calcUmbrellaForceAndPotential(dimParams_, grid_, indexNeighbor, neighborLambdaDhdl, - forceFromNeighbor); + state_.calcUmbrellaForceAndPotential( + dimParams_, grid_, indexNeighbor, neighborLambdaDhdl, forceFromNeighbor); /* Note: we might want to give a whole list of data to add instead and have this loop in the data adding function */ forceCorrelationGrid_->addData(indexNeighbor, weightNeighbor, forceFromNeighbor, t); diff --git a/src/gromacs/applied_forces/awh/bias.h b/src/gromacs/applied_forces/awh/bias.h index 895bfe456a..5fd4ad5c82 100644 --- a/src/gromacs/applied_forces/awh/bias.h +++ b/src/gromacs/applied_forces/awh/bias.h @@ -355,8 +355,9 @@ public: */ bool hasFepLambdaDimension() const { - return std::any_of(std::begin(dimParams_), std::end(dimParams_), - [](const auto& dimParam) { return dimParam.isFepLambdaDimension(); }); + return std::any_of(std::begin(dimParams_), std::end(dimParams_), [](const auto& dimParam) { + return dimParam.isFepLambdaDimension(); + }); } /*! \brief diff --git a/src/gromacs/applied_forces/awh/biasgrid.cpp b/src/gromacs/applied_forces/awh/biasgrid.cpp index 0db229cd86..16d9d655b6 100644 --- a/src/gromacs/applied_forces/awh/biasgrid.cpp +++ b/src/gromacs/applied_forces/awh/biasgrid.cpp @@ -897,7 +897,8 @@ void mapGridToDataGrid(std::vector* gridpointToDatapoint, std::string mesg = gmx::formatString( "Could not extract data properly from %s. Wrong data format?" "\n\n%s", - dataFilename.c_str(), correctFormatMessage.c_str()); + dataFilename.c_str(), + correctFormatMessage.c_str()); GMX_THROW(InvalidInputError(mesg)); } @@ -912,8 +913,8 @@ void mapGridToDataGrid(std::vector* gridpointToDatapoint, } else { - axis_.emplace_back(data[d][0], data[d][numDataPoints - 1], grid.axis(d).period(), - numPoints[d], false); + axis_.emplace_back( + data[d][0], data[d][numDataPoints - 1], grid.axis(d).period(), numPoints[d], false); } } @@ -930,7 +931,8 @@ void mapGridToDataGrid(std::vector* gridpointToDatapoint, "%s does not contain data for all coordinate values. " "Make sure your input data covers the whole sampling domain " "and is correctly formatted. \n\n%s", - dataFilename.c_str(), correctFormatMessage.c_str()); + dataFilename.c_str(), + correctFormatMessage.c_str()); GMX_THROW(InvalidInputError(mesg)); } (*gridpointToDatapoint)[m] = getNearestIndexInGrid(grid.point(m).coordValue, axis_); diff --git a/src/gromacs/applied_forces/awh/biasgrid.h b/src/gromacs/applied_forces/awh/biasgrid.h index 9fd994daa7..8ca2c263a5 100644 --- a/src/gromacs/applied_forces/awh/biasgrid.h +++ b/src/gromacs/applied_forces/awh/biasgrid.h @@ -249,8 +249,9 @@ public: */ bool hasLambdaAxis() const { - return std::any_of(std::begin(axis_), std::end(axis_), - [](const auto& axis) { return axis.isFepLambdaAxis(); }); + return std::any_of(std::begin(axis_), std::end(axis_), [](const auto& axis) { + return axis.isFepLambdaAxis(); + }); } /*! \brief diff --git a/src/gromacs/applied_forces/awh/biasstate.cpp b/src/gromacs/applied_forces/awh/biasstate.cpp index 3713c0bbce..abcaaa8cb9 100644 --- a/src/gromacs/applied_forces/awh/biasstate.cpp +++ b/src/gromacs/applied_forces/awh/biasstate.cpp @@ -323,8 +323,8 @@ void BiasState::calcConvolvedPmf(const std::vector& dimParams, /* Add the convolved PMF weights for the neighbors of this point. Note that this function only adds point within the target > 0 region. Sum weights, take the logarithm last to get the free energy. */ - double logWeight = biasedLogWeightFromPoint(dimParams, points_, grid, neighbor, - biasNeighbor, point.coordValue, {}, m); + double logWeight = biasedLogWeightFromPoint( + dimParams, points_, grid, neighbor, biasNeighbor, point.coordValue, {}, m); freeEnergyWeights += std::exp(logWeight); } } @@ -455,7 +455,10 @@ int BiasState::warnForHistogramAnomalies(const BiasGrid& grid, int biasIndex, do "If you are not certain about your settings you might want to increase your " "pull force constant or " "modify your sampling region.\n", - biasIndex + 1, t, pointValueString.c_str(), maxHistogramRatio); + biasIndex + 1, + t, + pointValueString.c_str(), + maxHistogramRatio); gmx::TextLineWrapper wrapper; wrapper.settings().setLineLength(c_linewidth); fprintf(fplog, "%s", wrapper.wrapToString(warningMessage).c_str()); @@ -546,8 +549,8 @@ double BiasState::moveUmbrella(const std::vector& dimParams, bool onlySampleUmbrellaGridpoint) { /* Generate and set a new coordinate reference value */ - coordState_.sampleUmbrellaGridpoint(grid, coordState_.gridpointIndex(), probWeightNeighbor, - step, seed, indexSeed); + coordState_.sampleUmbrellaGridpoint( + grid, coordState_.gridpointIndex(), probWeightNeighbor, step, seed, indexSeed); if (onlySampleUmbrellaGridpoint) { @@ -632,8 +635,8 @@ void BiasState::getSkippedUpdateHistogramScaleFactors(const BiasParams& params, /* In between global updates the reference histogram size is kept constant so we trivially know what the histogram size was at the time of the skipped update. */ double histogramSize = histogramSize_.histogramSize(); - setHistogramUpdateScaleFactors(params, histogramSize, histogramSize, weightHistScaling, - logPmfSumScaling); + setHistogramUpdateScaleFactors( + params, histogramSize, histogramSize, weightHistScaling, logPmfSumScaling); } else { @@ -1040,8 +1043,12 @@ bool BiasState::isSamplingRegionCovered(const BiasParams& params, /* Label each point along each dimension as covered or not. */ for (int d = 0; d < grid.numDimensions(); d++) { - labelCoveredPoints(checkDim[d].visited, checkDim[d].checkCovering, grid.axis(d).numPoints(), - grid.axis(d).numPointsInPeriod(), params.coverRadius()[d], checkDim[d].covered); + labelCoveredPoints(checkDim[d].visited, + checkDim[d].checkCovering, + grid.axis(d).numPoints(), + grid.axis(d).numPointsInPeriod(), + params.coverRadius()[d], + checkDim[d].covered); } /* Now check for global covering. Each dimension needs to be covered separately. @@ -1065,7 +1072,8 @@ bool BiasState::isSamplingRegionCovered(const BiasParams& params, { sumOverSimulations( gmx::arrayRefFromArray(checkDim[d].covered.data(), grid.axis(d).numPoints()), - commRecord, multiSimComm); + commRecord, + multiSimComm); } } @@ -1161,8 +1169,8 @@ void BiasState::updateFreeEnergyAndAddSamplesToHistogram(const std::vectorperformPreviouslySkippedUpdates(params, histogramSize_.numUpdates(), - weightHistScalingSkipped, - logPmfsumScalingSkipped); + pointStateToUpdate->performPreviouslySkippedUpdates( + params, histogramSize_.numUpdates(), weightHistScalingSkipped, logPmfsumScalingSkipped); } /* Now do an update with new sampling data. */ - pointStateToUpdate->updateWithNewSampling(params, histogramSize_.numUpdates(), - weightHistScalingNew, logPmfsumScalingNew); + pointStateToUpdate->updateWithNewSampling( + params, histogramSize_.numUpdates(), weightHistScalingNew, logPmfsumScalingNew); } /* Only update the histogram size after we are done with the local point updates */ @@ -1272,9 +1279,14 @@ double BiasState::updateProbabilityWeightsAndConvolvedBias(const std::vector& dimParams, { continue; } - double logWeight = biasedLogWeightFromPoint(dimParams, points_, grid, neighbor, - points_[neighbor].bias(), coordValue, {}, point); + double logWeight = biasedLogWeightFromPoint( + dimParams, points_, grid, neighbor, points_[neighbor].bias(), coordValue, {}, point); weightSum += std::exp(logWeight); } @@ -1435,8 +1447,10 @@ void BiasState::sampleCoordAndPmf(const std::vector& dimParams, std::vector lambdaMarginalDistribution = calculateFELambdaMarginalDistribution(grid, neighbors, probWeightNeighbor); - awh_dvec coordValueAlongLambda = { coordState_.coordValue()[0], coordState_.coordValue()[1], - coordState_.coordValue()[2], coordState_.coordValue()[3] }; + awh_dvec coordValueAlongLambda = { coordState_.coordValue()[0], + coordState_.coordValue()[1], + coordState_.coordValue()[2], + coordState_.coordValue()[3] }; for (size_t i = 0; i < neighbors.size(); i++) { const int neighbor = neighbors[i]; @@ -1546,8 +1560,7 @@ void BiasState::broadcast(const t_commrec* commRecord) gmx_bcast(points_.size() * sizeof(PointState), points_.data(), commRecord->mpi_comm_mygroup); - gmx_bcast(weightSumCovering_.size() * sizeof(double), weightSumCovering_.data(), - commRecord->mpi_comm_mygroup); + gmx_bcast(weightSumCovering_.size() * sizeof(double), weightSumCovering_.data(), commRecord->mpi_comm_mygroup); gmx_bcast(sizeof(histogramSize_), &histogramSize_, commRecord->mpi_comm_mygroup); } @@ -1656,8 +1669,8 @@ static void readUserPmfAndTargetDistribution(const std::vector& dimPa if (numRows <= 0) { - std::string mesg = gmx::formatString("%s is empty!.\n\n%s", filename.c_str(), - correctFormatMessage.c_str()); + std::string mesg = gmx::formatString( + "%s is empty!.\n\n%s", filename.c_str(), correctFormatMessage.c_str()); GMX_THROW(InvalidInputError(mesg)); } @@ -1667,7 +1680,8 @@ static void readUserPmfAndTargetDistribution(const std::vector& dimPa std::string mesg = gmx::formatString( "%s contains too few data points (%d)." "The minimum number of points is 2.", - filename.c_str(), numRows); + filename.c_str(), + numRows); GMX_THROW(InvalidInputError(mesg)); } @@ -1695,7 +1709,9 @@ static void readUserPmfAndTargetDistribution(const std::vector& dimPa std::string mesg = gmx::formatString( "The number of columns in %s should be at least %d." "\n\n%s", - filename.c_str(), numColumnsMin, correctFormatMessage.c_str()); + filename.c_str(), + numColumnsMin, + correctFormatMessage.c_str()); GMX_THROW(InvalidInputError(mesg)); } @@ -1707,7 +1723,8 @@ static void readUserPmfAndTargetDistribution(const std::vector& dimPa std::string mesg = gmx::formatString( "Found %d trailing zero data rows in %s. Please remove trailing empty lines and " "try again.", - numZeroRows, filename.c_str()); + numZeroRows, + filename.c_str()); GMX_THROW(InvalidInputError(mesg)); } @@ -1742,7 +1759,9 @@ static void readUserPmfAndTargetDistribution(const std::vector& dimPa if (target < 0) { std::string mesg = gmx::formatString( - "Target distribution weight at point %zu (%g) in %s is negative.", m, target, + "Target distribution weight at point %zu (%g) in %s is negative.", + m, + target, filename.c_str()); GMX_THROW(InvalidInputError(mesg)); } @@ -1757,7 +1776,8 @@ static void readUserPmfAndTargetDistribution(const std::vector& dimPa { std::string mesg = gmx::formatString("The target weights given in column %d in %s are all 0", - columnIndexTarget, filename.c_str()); + columnIndexTarget, + filename.c_str()); GMX_THROW(InvalidInputError(mesg)); } diff --git a/src/gromacs/applied_forces/awh/coordstate.cpp b/src/gromacs/applied_forces/awh/coordstate.cpp index 6de8832213..bfa7022b10 100644 --- a/src/gromacs/applied_forces/awh/coordstate.cpp +++ b/src/gromacs/applied_forces/awh/coordstate.cpp @@ -173,7 +173,10 @@ void CoordState::setCoordValue(const BiasGrid& grid, const awh_dvec coordValue) "Coordinate %d of an AWH bias has a value %f which is more than %d sigma " "out of the AWH range of [%f, %f]. You seem to have an unstable reaction " "coordinate setup or an unequilibrated system.", - dim + 1, coordValue[dim], c_marginInSigma, axis.origin(), + dim + 1, + coordValue[dim], + c_marginInSigma, + axis.origin(), axis.origin() + axis.length()); GMX_THROW(SimulationInstabilityError(mesg)); } diff --git a/src/gromacs/applied_forces/awh/correlationhistory.cpp b/src/gromacs/applied_forces/awh/correlationhistory.cpp index f77ba39938..f24796ed37 100644 --- a/src/gromacs/applied_forces/awh/correlationhistory.cpp +++ b/src/gromacs/applied_forces/awh/correlationhistory.cpp @@ -77,8 +77,10 @@ CorrelationGridHistory initCorrelationGridHistoryFromState(const CorrelationGrid { CorrelationGridHistory correlationGridHistory; - initCorrelationGridHistory(&correlationGridHistory, correlationGrid.tensors().size(), - correlationGrid.tensorSize(), correlationGrid.blockDataListSize()); + initCorrelationGridHistory(&correlationGridHistory, + correlationGrid.tensors().size(), + correlationGrid.tensorSize(), + correlationGrid.blockDataListSize()); return correlationGridHistory; } diff --git a/src/gromacs/applied_forces/awh/histogramsize.cpp b/src/gromacs/applied_forces/awh/histogramsize.cpp index fcfd452d4a..a343b4dc82 100644 --- a/src/gromacs/applied_forces/awh/histogramsize.cpp +++ b/src/gromacs/applied_forces/awh/histogramsize.cpp @@ -232,8 +232,10 @@ double HistogramSize::newHistogramSize(const BiasParams& params, } else if (!havePrintedAboutCovering_) { - fprintf(fplog, "%s covered but histogram not equilibrated at t = %g ps.\n", - prefix.c_str(), t); + fprintf(fplog, + "%s covered but histogram not equilibrated at t = %g ps.\n", + prefix.c_str(), + t); havePrintedAboutCovering_ = true; /* Just print once. */ } } diff --git a/src/gromacs/applied_forces/awh/read_params.cpp b/src/gromacs/applied_forces/awh/read_params.cpp index 5654d57af4..013c3ced26 100644 --- a/src/gromacs/applied_forces/awh/read_params.cpp +++ b/src/gromacs/applied_forces/awh/read_params.cpp @@ -65,8 +65,11 @@ namespace gmx { -const char* eawhtarget_names[eawhtargetNR + 1] = { "constant", "cutoff", "boltzmann", - "local-boltzmann", nullptr }; +const char* eawhtarget_names[eawhtargetNR + 1] = { "constant", + "cutoff", + "boltzmann", + "local-boltzmann", + nullptr }; const char* eawhgrowth_names[eawhgrowthNR + 1] = { "exp-linear", "linear", nullptr }; @@ -153,13 +156,15 @@ void checkPullDimParams(const std::string& prefix, gmx_fatal(FARGS, "The given AWH coordinate index (%d) is larger than the number of pull " "coordinates (%d)", - dimParams->coordIndex + 1, pull_params.ncoord); + dimParams->coordIndex + 1, + pull_params.ncoord); } if (pull_params.coord[dimParams->coordIndex].rate != 0) { auto message = formatString( "Setting pull-coord%d-rate (%g) is incompatible with AWH biasing this coordinate", - dimParams->coordIndex + 1, pull_params.coord[dimParams->coordIndex].rate); + dimParams->coordIndex + 1, + pull_params.coord[dimParams->coordIndex].rate); warning_error(wi, message); } @@ -168,7 +173,10 @@ void checkPullDimParams(const std::string& prefix, auto message = formatString( "The given interval length given by %s-start (%g) and %s-end (%g) is zero. " "This will result in only one point along this axis in the coordinate value grid.", - prefix.c_str(), dimParams->origin, prefix.c_str(), dimParams->end); + prefix.c_str(), + dimParams->origin, + prefix.c_str(), + dimParams->end); warning(wi, message); } @@ -189,7 +197,10 @@ void checkPullDimParams(const std::string& prefix, "%s-start (%g) or %s-end (%g) set to a negative value. With pull " "geometry distance coordinate values are non-negative. " "Perhaps you want to use geometry %s instead?", - prefix.c_str(), dimParams->origin, prefix.c_str(), dimParams->end, + prefix.c_str(), + dimParams->origin, + prefix.c_str(), + dimParams->end, EPULLGEOM(epullgDIR)); } } @@ -200,8 +211,12 @@ void checkPullDimParams(const std::string& prefix, gmx_fatal(FARGS, "%s-start (%g) and %s-end (%g) are outside of the allowed range " "0 to 180 deg for pull geometries %s and %s ", - prefix.c_str(), dimParams->origin, prefix.c_str(), dimParams->end, - EPULLGEOM(epullgANGLE), EPULLGEOM(epullgANGLEAXIS)); + prefix.c_str(), + dimParams->origin, + prefix.c_str(), + dimParams->end, + EPULLGEOM(epullgANGLE), + EPULLGEOM(epullgANGLEAXIS)); } } else if (eGeom == epullgDIHEDRAL) @@ -211,7 +226,10 @@ void checkPullDimParams(const std::string& prefix, gmx_fatal(FARGS, "%s-start (%g) and %s-end (%g) are outside of the allowed range " "-180 to 180 deg for pull geometry %s. ", - prefix.c_str(), dimParams->origin, prefix.c_str(), dimParams->end, + prefix.c_str(), + dimParams->origin, + prefix.c_str(), + dimParams->end, EPULLGEOM(epullgDIHEDRAL)); } } @@ -247,7 +265,8 @@ void checkFepLambdaDimParams(const std::string& prefix, "When running AWH coupled to the free energy lambda state all lambda states " "should be used as neighbors in order to get correct probabilities, i.e. " "calc-lambda-neighbors (%d) must be %d.", - lambdaParams->lambda_neighbors, -1); + lambdaParams->lambda_neighbors, + -1); } if (efep == efepSLOWGROWTH || lambdaParams->delta_lambda != 0) @@ -269,7 +288,8 @@ void checkFepLambdaDimParams(const std::string& prefix, gmx_fatal(FARGS, "When running AWH coupled to the free energy lambda state the lower lambda state " "for AWH, %s (%.0f), must be >= 0.", - opt.c_str(), dimParams->origin); + opt.c_str(), + dimParams->origin); } if (dimParams->end >= lambdaParams->n_lambda) { @@ -277,7 +297,9 @@ void checkFepLambdaDimParams(const std::string& prefix, gmx_fatal(FARGS, "When running AWH coupled to the free energy lambda state the upper lambda state " "for AWH, %s (%.0f), must be < n_lambda (%d).", - opt.c_str(), dimParams->origin, lambdaParams->n_lambda); + opt.c_str(), + dimParams->origin, + lambdaParams->n_lambda); } if (gmx_within_tol(dimParams->end - dimParams->origin, 0, GMX_REAL_EPS)) { @@ -285,7 +307,10 @@ void checkFepLambdaDimParams(const std::string& prefix, "The given interval length given by %s-start (%g) and %s-end (%g) is zero. " "This will result in only one lambda point along this free energy lambda state " "axis in the coordinate value grid.", - prefix.c_str(), dimParams->origin, prefix.c_str(), dimParams->end); + prefix.c_str(), + dimParams->origin, + prefix.c_str(), + dimParams->end); warning(wi, message); } @@ -541,8 +566,7 @@ void readBiasParams(std::vector* inp, /* Check this before starting to read the AWH dimension parameters. */ if (awhBiasParams->ndim <= 0 || awhBiasParams->ndim > c_biasMaxNumDim) { - gmx_fatal(FARGS, "%s (%d) needs to be > 0 and at most %d\n", opt.c_str(), - awhBiasParams->ndim, c_biasMaxNumDim); + gmx_fatal(FARGS, "%s (%d) needs to be > 0 and at most %d\n", opt.c_str(), awhBiasParams->ndim, c_biasMaxNumDim); } snew(awhBiasParams->dimParams, awhBiasParams->ndim); for (int d = 0; d < awhBiasParams->ndim; d++) @@ -574,7 +598,8 @@ void checkBiasParams(const AwhBiasParams* awhBiasParams, const std::string& pref { auto message = formatString("Option %s will only have an effect for histogram growth type '%s'.", - opt.c_str(), EAWHGROWTH(eawhgrowthEXP_LINEAR)); + opt.c_str(), + EAWHGROWTH(eawhgrowthEXP_LINEAR)); warning(wi, message); } @@ -585,7 +610,8 @@ void checkBiasParams(const AwhBiasParams* awhBiasParams, const std::string& pref "Target type '%s' combined with histogram growth type '%s' is not " "expected to give stable bias updates. You probably want to use growth type " "'%s' instead.", - EAWHTARGET(eawhtargetLOCALBOLTZMANN), EAWHGROWTH(eawhgrowthEXP_LINEAR), + EAWHTARGET(eawhtargetLOCALBOLTZMANN), + EAWHGROWTH(eawhgrowthEXP_LINEAR), EAWHGROWTH(eawhgrowthLINEAR)); warning(wi, message); } @@ -597,8 +623,11 @@ void checkBiasParams(const AwhBiasParams* awhBiasParams, const std::string& pref case eawhtargetLOCALBOLTZMANN: if (awhBiasParams->targetBetaScaling < 0 || awhBiasParams->targetBetaScaling > 1) { - gmx_fatal(FARGS, "%s = %g is not useful for target type %s.", opt.c_str(), - awhBiasParams->targetBetaScaling, EAWHTARGET(awhBiasParams->eTarget)); + gmx_fatal(FARGS, + "%s = %g is not useful for target type %s.", + opt.c_str(), + awhBiasParams->targetBetaScaling, + EAWHTARGET(awhBiasParams->eTarget)); } break; default: @@ -607,7 +636,8 @@ void checkBiasParams(const AwhBiasParams* awhBiasParams, const std::string& pref gmx_fatal( FARGS, "Value for %s (%g) set explicitly but will not be used for target type %s.", - opt.c_str(), awhBiasParams->targetBetaScaling, + opt.c_str(), + awhBiasParams->targetBetaScaling, EAWHTARGET(awhBiasParams->eTarget)); } break; @@ -619,8 +649,11 @@ void checkBiasParams(const AwhBiasParams* awhBiasParams, const std::string& pref case eawhtargetCUTOFF: if (awhBiasParams->targetCutoff <= 0) { - gmx_fatal(FARGS, "%s = %g is not useful for target type %s.", opt.c_str(), - awhBiasParams->targetCutoff, EAWHTARGET(awhBiasParams->eTarget)); + gmx_fatal(FARGS, + "%s = %g is not useful for target type %s.", + opt.c_str(), + awhBiasParams->targetCutoff, + EAWHTARGET(awhBiasParams->eTarget)); } break; default: @@ -629,7 +662,9 @@ void checkBiasParams(const AwhBiasParams* awhBiasParams, const std::string& pref gmx_fatal( FARGS, "Value for %s (%g) set explicitly but will not be used for target type %s.", - opt.c_str(), awhBiasParams->targetCutoff, EAWHTARGET(awhBiasParams->eTarget)); + opt.c_str(), + awhBiasParams->targetCutoff, + EAWHTARGET(awhBiasParams->eTarget)); } break; } @@ -643,8 +678,7 @@ void checkBiasParams(const AwhBiasParams* awhBiasParams, const std::string& pref opt = prefix + "-ndim"; if (awhBiasParams->ndim <= 0 || awhBiasParams->ndim > c_biasMaxNumDim) { - gmx_fatal(FARGS, "%s (%d) needs to be > 0 and at most %d\n", opt.c_str(), - awhBiasParams->ndim, c_biasMaxNumDim); + gmx_fatal(FARGS, "%s (%d) needs to be > 0 and at most %d\n", opt.c_str(), awhBiasParams->ndim, c_biasMaxNumDim); } if (awhBiasParams->ndim > 2) { @@ -712,7 +746,10 @@ void checkInputConsistencyAwh(const AwhParams& awhParams, warninp_t wi) "dimensions (awh%d-dim%d and awh%d-dim%d). " "If this is really what you want to do you will have to duplicate " "this pull coordinate.", - awhBiasParams1.dimParams[d1].coordIndex + 1, k1 + 1, d1 + 1, k2 + 1, + awhBiasParams1.dimParams[d1].coordIndex + 1, + k1 + 1, + d1 + 1, + k2 + 1, d2 + 1); gmx_fatal(FARGS, "%s", errormsg); } @@ -810,14 +847,15 @@ void checkAwhParams(const AwhParams* awhParams, const t_inputrec* ir, warninp_t if (awhParams->nstOut <= 0) { auto message = formatString("Not writing AWH output with AWH (%s = %d) does not make sense", - opt.c_str(), awhParams->nstOut); + opt.c_str(), + awhParams->nstOut); warning_error(wi, message); } /* This restriction can be removed by changing a flag of print_ebin() */ if (ir->nstenergy == 0 || awhParams->nstOut % ir->nstenergy != 0) { - auto message = formatString("%s (%d) should be a multiple of nstenergy (%d)", opt.c_str(), - awhParams->nstOut, ir->nstenergy); + auto message = formatString( + "%s (%d) should be a multiple of nstenergy (%d)", opt.c_str(), awhParams->nstOut, ir->nstenergy); warning_error(wi, message); } @@ -872,7 +910,8 @@ static double get_pull_coord_period(const t_pull_coord& pullCoordParams, const t gmx_fatal(FARGS, "The AWH interval (%f nm) for a pull coordinate is larger than the " "box size (%f nm)", - intervalLength, boxLength); + intervalLength, + boxLength); } if (intervalLength > periodicFraction * boxLength) @@ -962,7 +1001,12 @@ static void checkInputConsistencyInterval(const AwhParams* awhParams, warninp_t gmx_fatal(FARGS, "For the non-periodic pull coordinates awh%d-dim%d-start (%f) cannot be " "larger than awh%d-dim%d-end (%f)", - k + 1, d + 1, origin, k + 1, d + 1, end); + k + 1, + d + 1, + origin, + k + 1, + d + 1, + end); } /* Currently we assume symmetric periodic intervals, meaning we use [-period/2, period/2] as the reference interval. @@ -982,7 +1026,15 @@ static void checkInputConsistencyInterval(const AwhParams* awhParams, warninp_t "values in between " "minus half a period and plus half a period, i.e. in the interval [%.8g, " "%.8g].", - k + 1, d + 1, origin, k + 1, d + 1, end, period, -0.5 * period, 0.5 * period); + k + 1, + d + 1, + origin, + k + 1, + d + 1, + end, + period, + -0.5 * period, + 0.5 * period); } /* Warn if the pull initial coordinate value is not in the grid */ @@ -995,7 +1047,14 @@ static void checkInputConsistencyInterval(const AwhParams* awhParams, warninp_t "(%.8g). " "This can lead to large initial forces pulling the coordinate towards the " "sampling interval.", - coordValueInit, coordIndex + 1, k + 1, d + 1, origin, k + 1, d + 1, end); + coordValueInit, + coordIndex + 1, + k + 1, + d + 1, + origin, + k + 1, + d + 1, + end); warning(wi, message); } } @@ -1034,7 +1093,8 @@ static void setStateDependentAwhPullDimParams(AwhDimParams* dimParams, "If the maximum distance between the groups is always " "less than half the box size, " "you can use geometry '%s' instead.", - EPULLGEOM(epullgDIRPBC), EPULLGEOM(epullgDIR)); + EPULLGEOM(epullgDIRPBC), + EPULLGEOM(epullgDIR)); } dimParams->period = get_pull_coord_period(pullCoordParams, pbc, dimParams->end - dimParams->origin); @@ -1056,7 +1116,9 @@ static void setStateDependentAwhPullDimParams(AwhDimParams* dimParams, "AWH dimension %d of bias %d is periodic with pull geometry '%s', " "while you should are applying pressure scaling to the " "corresponding box vector, this is not supported.", - dimIndex + 1, biasIndex + 1, EPULLGEOM(pullCoordParams.eGeom)); + dimIndex + 1, + biasIndex + 1, + EPULLGEOM(pullCoordParams.eGeom)); warning(wi, mesg.c_str()); } } @@ -1107,8 +1169,8 @@ void setStateDependentAwhParams(AwhParams* awhParams, AwhDimParams* dimParams = &awhBiasParams->dimParams[d]; if (dimParams->eCoordProvider == eawhcoordproviderPULL) { - setStateDependentAwhPullDimParams(dimParams, k, d, &pull_params, pull_work, pbc, - compressibility, wi); + setStateDependentAwhPullDimParams( + dimParams, k, d, &pull_params, pull_work, pbc, compressibility, wi); } else { diff --git a/src/gromacs/applied_forces/awh/tests/bias.cpp b/src/gromacs/applied_forces/awh/tests/bias.cpp index a0f8aae735..b64d01123e 100644 --- a/src/gromacs/applied_forces/awh/tests/bias.cpp +++ b/src/gromacs/applied_forces/awh/tests/bias.cpp @@ -196,8 +196,15 @@ public: "samples should be a multiple of the free-energy update interval (but " "the test should also runs fine without this condition)."); - bias_ = std::make_unique(-1, params.awhParams, params.awhBiasParams, params.dimParams, - params.beta, mdTimeStep, 1, "", Bias::ThisRankWillDoIO::No, + bias_ = std::make_unique(-1, + params.awhParams, + params.awhBiasParams, + params.dimParams, + params.beta, + mdTimeStep, + 1, + "", + Bias::ThisRankWillDoIO::No, disableUpdateSkips); } }; @@ -230,9 +237,8 @@ TEST_P(BiasTest, ForcesBiasPmf) awh_dvec coordValue = { coord, 0, 0, 0 }; double potential = 0; - gmx::ArrayRef biasForce = - bias.calcForceAndUpdateBias(coordValue, {}, {}, &potential, &potentialJump, nullptr, - nullptr, step, step, seed_, nullptr); + gmx::ArrayRef biasForce = bias.calcForceAndUpdateBias( + coordValue, {}, {}, &potential, &potentialJump, nullptr, nullptr, step, step, seed_, nullptr); force.push_back(biasForce[0]); pot.push_back(potential); @@ -294,8 +300,15 @@ TEST(BiasTest, DetectsCovering) const double mdTimeStep = 0.1; - Bias bias(-1, params.awhParams, params.awhBiasParams, params.dimParams, params.beta, mdTimeStep, - 1, "", Bias::ThisRankWillDoIO::No); + Bias bias(-1, + params.awhParams, + params.awhBiasParams, + params.dimParams, + params.beta, + mdTimeStep, + 1, + "", + Bias::ThisRankWillDoIO::No); /* We use a trajectory of the sum of two sines to cover the reaction * coordinate range in a semi-realistic way. The period is 4*pi=12.57. @@ -316,8 +329,17 @@ TEST(BiasTest, DetectsCovering) awh_dvec coordValue = { coord, 0, 0, 0 }; double potential = 0; double potentialJump = 0; - bias.calcForceAndUpdateBias(coordValue, {}, {}, &potential, &potentialJump, nullptr, - nullptr, step, step, params.awhParams.seed, nullptr); + bias.calcForceAndUpdateBias(coordValue, + {}, + {}, + &potential, + &potentialJump, + nullptr, + nullptr, + step, + step, + params.awhParams.seed, + nullptr); inInitialStage = bias.state().inInitialStage(); if (!inInitialStage) diff --git a/src/gromacs/applied_forces/awh/tests/bias_fep_lambda_state.cpp b/src/gromacs/applied_forces/awh/tests/bias_fep_lambda_state.cpp index a68095e010..de0d6de7c0 100644 --- a/src/gromacs/applied_forces/awh/tests/bias_fep_lambda_state.cpp +++ b/src/gromacs/applied_forces/awh/tests/bias_fep_lambda_state.cpp @@ -183,8 +183,15 @@ public: double mdTimeStep = 0.1; - bias_ = std::make_unique(-1, params.awhParams, params.awhBiasParams, params.dimParams, - params.beta, mdTimeStep, 1, "", Bias::ThisRankWillDoIO::No, + bias_ = std::make_unique(-1, + params.awhParams, + params.awhBiasParams, + params.dimParams, + params.beta, + mdTimeStep, + 1, + "", + Bias::ThisRankWillDoIO::No, disableUpdateSkips); } }; @@ -227,9 +234,17 @@ TEST_P(BiasFepLambdaStateTest, ForcesBiasPmf) int umbrellaGridpointIndex = bias.state().coordState().umbrellaGridpoint(); awh_dvec coordValue = { bias.getGridCoordValue(umbrellaGridpointIndex)[0], 0, 0, 0 }; double potential = 0; - gmx::ArrayRef biasForce = bias.calcForceAndUpdateBias( - coordValue, neighborLambdaEnergies, neighborLambdaDhdl, &potential, &potentialJump, - nullptr, nullptr, step * mdTimeStep, step, seed_, nullptr); + gmx::ArrayRef biasForce = bias.calcForceAndUpdateBias(coordValue, + neighborLambdaEnergies, + neighborLambdaDhdl, + &potential, + &potentialJump, + nullptr, + nullptr, + step * mdTimeStep, + step, + seed_, + nullptr); force.push_back(biasForce[0]); pot.push_back(potential); @@ -281,8 +296,15 @@ TEST(BiasFepLambdaStateTest, DetectsCovering) const double mdTimeStep = 0.1; - Bias bias(-1, params.awhParams, params.awhBiasParams, params.dimParams, params.beta, mdTimeStep, - 1, "", Bias::ThisRankWillDoIO::No); + Bias bias(-1, + params.awhParams, + params.awhBiasParams, + params.dimParams, + params.beta, + mdTimeStep, + 1, + "", + Bias::ThisRankWillDoIO::No); const int64_t exitStepRef = 320; @@ -307,9 +329,17 @@ TEST(BiasFepLambdaStateTest, DetectsCovering) double potential = 0; double potentialJump = 0; - bias.calcForceAndUpdateBias(coordValue, neighborLambdaEnergies, neighborLambdaDhdl, - &potential, &potentialJump, nullptr, nullptr, step, step, - params.awhParams.seed, nullptr); + bias.calcForceAndUpdateBias(coordValue, + neighborLambdaEnergies, + neighborLambdaDhdl, + &potential, + &potentialJump, + nullptr, + nullptr, + step, + step, + params.awhParams.seed, + nullptr); inInitialStage = bias.state().inInitialStage(); if (!inInitialStage) diff --git a/src/gromacs/applied_forces/awh/tests/biasstate.cpp b/src/gromacs/applied_forces/awh/tests/biasstate.cpp index a1e68b6460..4349d9b997 100644 --- a/src/gromacs/applied_forces/awh/tests/biasstate.cpp +++ b/src/gromacs/applied_forces/awh/tests/biasstate.cpp @@ -141,14 +141,14 @@ public: dimParams.push_back(DimParams::pullDimParams(1.0, 15.0, params.beta)); dimParams.push_back(DimParams::pullDimParams(1.0, 15.0, params.beta)); BiasGrid grid(dimParams, awhBiasParams.dimParams); - BiasParams biasParams(awhParams, awhBiasParams, dimParams, 1.0, 1.0, - BiasParams::DisableUpdateSkips::no, 1, grid.axis(), 0); + BiasParams biasParams( + awhParams, awhBiasParams, dimParams, 1.0, 1.0, BiasParams::DisableUpdateSkips::no, 1, grid.axis(), 0); biasState_ = std::make_unique(awhBiasParams, 1.0, dimParams, grid); // Here we initialize the grid point state using the input file std::string filename = gmx::test::TestFileManager::getInputFilePath(GetParam()); - biasState_->initGridPointState(awhBiasParams, dimParams, grid, biasParams, filename, - params.awhParams.numBias); + biasState_->initGridPointState( + awhBiasParams, dimParams, grid, biasParams, filename, params.awhParams.numBias); sfree(params.awhParams.awhBiasParams[0].dimParams); sfree(params.awhParams.awhBiasParams); diff --git a/src/gromacs/applied_forces/densityfitting/densityfitting.cpp b/src/gromacs/applied_forces/densityfitting/densityfitting.cpp index 819903868f..a891dfcf99 100644 --- a/src/gromacs/applied_forces/densityfitting/densityfitting.cpp +++ b/src/gromacs/applied_forces/densityfitting/densityfitting.cpp @@ -163,8 +163,8 @@ public: GMX_THROW(InternalError("Need to set reference density before normalizing it.")); } - const real sumOfDensityData = std::accumulate(begin(referenceDensity_->asView()), - end(referenceDensity_->asView()), 0.); + const real sumOfDensityData = std::accumulate( + begin(referenceDensity_->asView()), end(referenceDensity_->asView()), 0.); for (float& referenceDensityVoxel : referenceDensity_->asView()) { referenceDensityVoxel /= sumOfDensityData; @@ -359,11 +359,13 @@ public: densityFittingSimulationParameters_.normalizeReferenceDensity(); } forceProvider_ = std::make_unique( - parameters, densityFittingSimulationParameters_.referenceDensity(), + parameters, + densityFittingSimulationParameters_.referenceDensity(), densityFittingSimulationParameters_.transformationToDensityLattice(), densityFittingSimulationParameters_.localAtomSet(), densityFittingSimulationParameters_.periodicBoundaryConditionType(), - densityFittingSimulationParameters_.simulationTimeStep(), densityFittingState_); + densityFittingSimulationParameters_.simulationTimeStep(), + densityFittingState_); forceProviders->addForceProvider(forceProvider_.get()); } } diff --git a/src/gromacs/applied_forces/densityfitting/densityfittingamplitudelookup.cpp b/src/gromacs/applied_forces/densityfitting/densityfittingamplitudelookup.cpp index 27be15efb3..32dfd24aae 100644 --- a/src/gromacs/applied_forces/densityfitting/densityfittingamplitudelookup.cpp +++ b/src/gromacs/applied_forces/densityfitting/densityfittingamplitudelookup.cpp @@ -121,7 +121,9 @@ const std::vector& ChargesAsAmplitudes::operator()(const t_mdatoms& atoms, amplitude_.resize(localIndex.size()); } - std::transform(std::begin(localIndex), std::end(localIndex), std::begin(amplitude_), + std::transform(std::begin(localIndex), + std::end(localIndex), + std::begin(amplitude_), [&atoms](gmx::index index) { return atoms.chargeA[index]; }); return amplitude_; } @@ -151,7 +153,9 @@ const std::vector& MassesAsAmplitudes::operator()(const t_mdatoms& atoms, amplitude_.resize(localIndex.size()); } - std::transform(std::begin(localIndex), std::end(localIndex), std::begin(amplitude_), + std::transform(std::begin(localIndex), + std::end(localIndex), + std::begin(amplitude_), [&atoms](gmx::index index) { return atoms.massT[index]; }); return amplitude_; } diff --git a/src/gromacs/applied_forces/densityfitting/densityfittingforceprovider.cpp b/src/gromacs/applied_forces/densityfitting/densityfittingforceprovider.cpp index c2442bbd38..4bd0a47df4 100644 --- a/src/gromacs/applied_forces/densityfitting/densityfittingforceprovider.cpp +++ b/src/gromacs/applied_forces/densityfitting/densityfittingforceprovider.cpp @@ -79,8 +79,7 @@ GaussianSpreadKernelParameters::Shape makeSpreadKernel(real sigma, real nSigma, { RVec sigmaInLatticeCoordinates{ sigma, sigma, sigma }; scaleToLattice(&sigmaInLatticeCoordinates); - return { DVec{ sigmaInLatticeCoordinates[XX], sigmaInLatticeCoordinates[YY], - sigmaInLatticeCoordinates[ZZ] }, + return { DVec{ sigmaInLatticeCoordinates[XX], sigmaInLatticeCoordinates[YY], sigmaInLatticeCoordinates[ZZ] }, nSigma }; } @@ -102,10 +101,10 @@ const std::string DensityFittingForceProviderState::stepsSinceLastCalculationNam void DensityFittingForceProviderState::writeState(KeyValueTreeObjectBuilder kvtBuilder, const std::string& identifier) const { - writeKvtCheckpointValue(stepsSinceLastCalculation_, stepsSinceLastCalculationName_, identifier, - kvtBuilder); - writeKvtCheckpointValue(adaptiveForceConstantScale_, adaptiveForceConstantScaleName_, - identifier, kvtBuilder); + writeKvtCheckpointValue( + stepsSinceLastCalculation_, stepsSinceLastCalculationName_, identifier, kvtBuilder); + writeKvtCheckpointValue( + adaptiveForceConstantScale_, adaptiveForceConstantScaleName_, identifier, kvtBuilder); KeyValueTreeObjectBuilder exponentialMovingAverageKvtEntry = kvtBuilder.addObject(identifier + "-" + exponentialMovingAverageStateName_); @@ -117,9 +116,13 @@ void DensityFittingForceProviderState::readState(const KeyValueTreeObject& kvtDa const std::string& identifier) { readKvtCheckpointValue(compat::make_not_null(&stepsSinceLastCalculation_), - stepsSinceLastCalculationName_, identifier, kvtData); + stepsSinceLastCalculationName_, + identifier, + kvtData); readKvtCheckpointValue(compat::make_not_null(&adaptiveForceConstantScale_), - adaptiveForceConstantScaleName_, identifier, kvtData); + adaptiveForceConstantScaleName_, + identifier, + kvtData); if (kvtData.keyExists(identifier + "-" + exponentialMovingAverageStateName_)) { @@ -266,7 +269,8 @@ void DensityFittingForceProvider::Impl::calculateForces(const ForceProviderInput transformedCoordinates_.resize(localAtomSet_.numAtomsLocal()); // pick and copy atom coordinates - std::transform(std::cbegin(localAtomSet_.localIndex()), std::cend(localAtomSet_.localIndex()), + std::transform(std::cbegin(localAtomSet_.localIndex()), + std::cend(localAtomSet_.localIndex()), std::begin(transformedCoordinates_), [&forceProviderInput](int index) { return forceProviderInput.x_[index]; }); @@ -323,7 +327,8 @@ void DensityFittingForceProvider::Impl::calculateForces(const ForceProviderInput { // \todo update to real once GaussTransform class returns real gmx_sumf(gaussTransform_.view().mapping().required_span_size(), - gaussTransform_.view().data(), &forceProviderInput.cr_); + gaussTransform_.view().data(), + &forceProviderInput.cr_); } // calculate grid derivative @@ -332,8 +337,11 @@ void DensityFittingForceProvider::Impl::calculateForces(const ForceProviderInput // calculate forces forces_.resize(localAtomSet_.numAtomsLocal()); std::transform( - std::begin(transformedCoordinates_), std::end(transformedCoordinates_), std::begin(amplitudes), - std::begin(forces_), [&densityDerivative, this](const RVec r, real amplitude) { + std::begin(transformedCoordinates_), + std::end(transformedCoordinates_), + std::begin(amplitudes), + std::begin(forces_), + [&densityDerivative, this](const RVec r, real amplitude) { return densityFittingForce_.evaluateForce({ r, amplitude }, densityDerivative); }); diff --git a/src/gromacs/applied_forces/densityfitting/densityfittingoptions.cpp b/src/gromacs/applied_forces/densityfitting/densityfittingoptions.cpp index a3cb45794b..a008212c19 100644 --- a/src/gromacs/applied_forces/densityfitting/densityfittingoptions.cpp +++ b/src/gromacs/applied_forces/densityfitting/densityfittingoptions.cpp @@ -130,37 +130,39 @@ void DensityFittingOptions::initMdpTransform(IKeyValueTreeTransformRules* rules) const auto& stringIdentityTransform = [](std::string s) { return s; }; densityfittingMdpTransformFromString(rules, &fromStdString, c_activeTag_); densityfittingMdpTransformFromString(rules, stringIdentityTransform, c_groupTag_); - densityfittingMdpTransformFromString(rules, stringIdentityTransform, - c_similarityMeasureTag_); + densityfittingMdpTransformFromString( + rules, stringIdentityTransform, c_similarityMeasureTag_); densityfittingMdpTransformFromString(rules, stringIdentityTransform, c_amplitudeMethodTag_); densityfittingMdpTransformFromString(rules, &fromStdString, c_forceConstantTag_); - densityfittingMdpTransformFromString(rules, &fromStdString, - c_gaussianTransformSpreadingWidthTag_); + densityfittingMdpTransformFromString( + rules, &fromStdString, c_gaussianTransformSpreadingWidthTag_); densityfittingMdpTransformFromString( rules, &fromStdString, c_gaussianTransformSpreadingRangeInMultiplesOfWidthTag_); - densityfittingMdpTransformFromString(rules, stringIdentityTransform, - c_referenceDensityFileNameTag_); - densityfittingMdpTransformFromString(rules, &fromStdString, - c_everyNStepsTag_); + densityfittingMdpTransformFromString( + rules, stringIdentityTransform, c_referenceDensityFileNameTag_); + densityfittingMdpTransformFromString( + rules, &fromStdString, c_everyNStepsTag_); densityfittingMdpTransformFromString(rules, &fromStdString, c_normalizeDensitiesTag_); densityfittingMdpTransformFromString(rules, &fromStdString, c_adaptiveForceScalingTag_); - densityfittingMdpTransformFromString(rules, &fromStdString, - c_adaptiveForceScalingTimeConstantTag_); + densityfittingMdpTransformFromString( + rules, &fromStdString, c_adaptiveForceScalingTimeConstantTag_); const auto& stringRVecToStringRVecWithCheck = [](const std::string& str) { return stringIdentityTransformWithArrayCheck( - str, "Reading three real values as vector while parsing the .mdp input failed in " - + DensityFittingModuleInfo::name_ + "."); + str, + "Reading three real values as vector while parsing the .mdp input failed in " + + DensityFittingModuleInfo::name_ + "."); }; - densityfittingMdpTransformFromString(rules, stringRVecToStringRVecWithCheck, - c_translationTag_); + densityfittingMdpTransformFromString( + rules, stringRVecToStringRVecWithCheck, c_translationTag_); const auto& stringMatrixToStringMatrixWithCheck = [](const std::string& str) { return stringIdentityTransformWithArrayCheck( - str, "Reading nine real values as vector while parsing the .mdp input failed in " - + DensityFittingModuleInfo::name_ + "."); + str, + "Reading nine real values as vector while parsing the .mdp input failed in " + + DensityFittingModuleInfo::name_ + "."); }; - densityfittingMdpTransformFromString(rules, stringMatrixToStringMatrixWithCheck, - c_transformationMatrixTag_); + densityfittingMdpTransformFromString( + rules, stringMatrixToStringMatrixWithCheck, c_transformationMatrixTag_); } //! Name the methods that may be used to evaluate similarity between densities @@ -189,20 +191,23 @@ void DensityFittingOptions::buildMdpOutput(KeyValueTreeObjectBuilder* builder) c "cross-correlation", c_similarityMeasureTag_); addDensityFittingMdpOutputValue( - builder, c_densitySimilarityMeasureMethodNames[parameters_.similarityMeasureMethod_], + builder, + c_densitySimilarityMeasureMethodNames[parameters_.similarityMeasureMethod_], c_similarityMeasureTag_); addDensityFittingMdpOutputValueComment( - builder, "; Atom amplitude for spreading onto grid: unity, mass, or charge", - c_amplitudeMethodTag_); + builder, "; Atom amplitude for spreading onto grid: unity, mass, or charge", c_amplitudeMethodTag_); addDensityFittingMdpOutputValue( - builder, c_densityFittingAmplitudeMethodNames[parameters_.amplitudeLookupMethod_], + builder, + c_densityFittingAmplitudeMethodNames[parameters_.amplitudeLookupMethod_], c_amplitudeMethodTag_); addDensityFittingMdpOutputValue(builder, parameters_.forceConstant_, c_forceConstantTag_); - addDensityFittingMdpOutputValue(builder, parameters_.gaussianTransformSpreadingWidth_, + addDensityFittingMdpOutputValue(builder, + parameters_.gaussianTransformSpreadingWidth_, c_gaussianTransformSpreadingWidthTag_); - addDensityFittingMdpOutputValue(builder, parameters_.gaussianTransformSpreadingRangeInMultiplesOfWidth_, + addDensityFittingMdpOutputValue(builder, + parameters_.gaussianTransformSpreadingRangeInMultiplesOfWidth_, c_gaussianTransformSpreadingRangeInMultiplesOfWidthTag_); addDensityFittingMdpOutputValueComment(builder, "; Reference density file location as absolute path " @@ -213,14 +218,15 @@ void DensityFittingOptions::buildMdpOutput(KeyValueTreeObjectBuilder* builder) c addDensityFittingMdpOutputValueComment( builder, "; Normalize the sum of density voxel values to one", c_normalizeDensitiesTag_); addDensityFittingMdpOutputValue(builder, parameters_.normalizeDensities_, c_normalizeDensitiesTag_); - addDensityFittingMdpOutputValueComment(builder, "; Apply adaptive force scaling", - c_adaptiveForceScalingTag_); - addDensityFittingMdpOutputValue(builder, parameters_.adaptiveForceScaling_, - c_adaptiveForceScalingTag_); + addDensityFittingMdpOutputValueComment( + builder, "; Apply adaptive force scaling", c_adaptiveForceScalingTag_); + addDensityFittingMdpOutputValue( + builder, parameters_.adaptiveForceScaling_, c_adaptiveForceScalingTag_); addDensityFittingMdpOutputValueComment(builder, "; Time constant for adaptive force scaling in ps", c_adaptiveForceScalingTimeConstantTag_); - addDensityFittingMdpOutputValue(builder, parameters_.adaptiveForceScalingTimeConstant_, + addDensityFittingMdpOutputValue(builder, + parameters_.adaptiveForceScalingTimeConstant_, c_adaptiveForceScalingTimeConstantTag_); } } @@ -306,7 +312,9 @@ void DensityFittingOptions::readInternalParametersFromKvt(const KeyValueTreeObje } auto kvtIndexArray = tree[DensityFittingModuleInfo::name_ + "-" + c_groupTag_].asArray().values(); parameters_.indices_.resize(kvtIndexArray.size()); - std::transform(std::begin(kvtIndexArray), std::end(kvtIndexArray), std::begin(parameters_.indices_), + std::transform(std::begin(kvtIndexArray), + std::end(kvtIndexArray), + std::begin(parameters_.indices_), [](const KeyValueTreeValue& val) { return val.cast(); }); } diff --git a/src/gromacs/applied_forces/densityfitting/tests/densityfitting.cpp b/src/gromacs/applied_forces/densityfitting/tests/densityfitting.cpp index f9b09904e2..8ceca2f914 100644 --- a/src/gromacs/applied_forces/densityfitting/tests/densityfitting.cpp +++ b/src/gromacs/applied_forces/densityfitting/tests/densityfitting.cpp @@ -78,8 +78,7 @@ class DensityFittingTest : public ::testing::Test public: void addMdpOptionDensityFittingActive() { - mdpValueBuilder_.rootObject().addValue("density-guided-simulation-active", - std::string("yes")); + mdpValueBuilder_.rootObject().addValue("density-guided-simulation-active", std::string("yes")); } void addMdpOptionReferenceDensity() diff --git a/src/gromacs/applied_forces/densityfitting/tests/densityfittingoptions.cpp b/src/gromacs/applied_forces/densityfitting/tests/densityfittingoptions.cpp index 54600746e0..e6d04175ce 100644 --- a/src/gromacs/applied_forces/densityfitting/tests/densityfittingoptions.cpp +++ b/src/gromacs/applied_forces/densityfitting/tests/densityfittingoptions.cpp @@ -95,8 +95,7 @@ public: { // Prepare MDP inputs KeyValueTreeBuilder mdpValueBuilder; - mdpValueBuilder.rootObject().addValue("density-guided-simulation-active", - std::string("yes")); + mdpValueBuilder.rootObject().addValue("density-guided-simulation-active", std::string("yes")); return mdpValueBuilder.build(); } @@ -104,8 +103,9 @@ public: { done_blocka(&defaultGroups_); stupid_fill_blocka(&defaultGroups_, 3); - std::vector groupNames = { "A", "protein", "C" }; - const char* const namesAsConstChar[3] = { groupNames[0].c_str(), groupNames[1].c_str(), + std::vector groupNames = { "A", "protein", "C" }; + const char* const namesAsConstChar[3] = { groupNames[0].c_str(), + groupNames[1].c_str(), groupNames[2].c_str() }; return { defaultGroups_, namesAsConstChar }; } @@ -114,8 +114,9 @@ public: { done_blocka(&defaultGroups_); stupid_fill_blocka(&defaultGroups_, 3); - std::vector groupNames = { "protein", "C", "A" }; - const char* const namesAsConstChar[3] = { groupNames[0].c_str(), groupNames[1].c_str(), + std::vector groupNames = { "protein", "C", "A" }; + const char* const namesAsConstChar[3] = { groupNames[0].c_str(), + groupNames[1].c_str(), groupNames[2].c_str() }; return { defaultGroups_, namesAsConstChar }; } diff --git a/src/gromacs/applied_forces/electricfield.cpp b/src/gromacs/applied_forces/electricfield.cpp index 08c414f5d4..7c49428215 100644 --- a/src/gromacs/applied_forces/electricfield.cpp +++ b/src/gromacs/applied_forces/electricfield.cpp @@ -261,8 +261,11 @@ void ElectricField::initOutput(FILE* fplog, int nfile, const t_filenm fnm[], boo } else { - fpField_ = xvgropen(opt2fn("-field", nfile, fnm), "Applied electric field", - "Time (ps)", "E (V/nm)", oenv); + fpField_ = xvgropen(opt2fn("-field", nfile, fnm), + "Applied electric field", + "Time (ps)", + "E (V/nm)", + oenv); } } } diff --git a/src/gromacs/commandline/cmdlinehelpmodule.cpp b/src/gromacs/commandline/cmdlinehelpmodule.cpp index 95b4acfa61..029b90a680 100644 --- a/src/gromacs/commandline/cmdlinehelpmodule.cpp +++ b/src/gromacs/commandline/cmdlinehelpmodule.cpp @@ -528,7 +528,8 @@ HelpExportReStructuredText::HelpExportReStructuredText(const CommandLineHelpModu while (linksFile.readLine(&line)) { links_.addLink("[REF]." + line + "[ref]", - formatString(":ref:`.%s <%s>`", line.c_str(), line.c_str()), line); + formatString(":ref:`.%s <%s>`", line.c_str(), line.c_str()), + line); links_.addLink("[REF]" + line + "[ref]", formatString(":ref:`%s`", line.c_str()), line); } linksFile.close(); @@ -539,8 +540,8 @@ void HelpExportReStructuredText::startModuleExport() { indexFile_ = std::make_unique( outputRedirector_->openTextOutputFile("fragments/byname.rst")); - indexFile_->writeLine(formatString("* :doc:`%s ` - %s", binaryName_.c_str(), - binaryName_.c_str(), RootHelpText::title)); + indexFile_->writeLine(formatString( + "* :doc:`%s ` - %s", binaryName_.c_str(), binaryName_.c_str(), RootHelpText::title)); manPagesFile_ = std::make_unique(outputRedirector_->openTextOutputFile("conf-man.py")); manPagesFile_->writeLine("man_pages = ["); @@ -579,10 +580,12 @@ void HelpExportReStructuredText::exportModuleHelp(const ICommandLineModule& modu " More information about |Gromacs| is available at ."); file->close(); - indexFile_->writeLine(formatString("* :doc:`%s ` - %s", displayName.c_str(), - tag.c_str(), module.shortDescription())); + indexFile_->writeLine(formatString( + "* :doc:`%s ` - %s", displayName.c_str(), tag.c_str(), module.shortDescription())); manPagesFile_->writeLine(formatString(" ('onlinehelp/%s', '%s', \"%s\", '', 1),", - tag.c_str(), tag.c_str(), module.shortDescription())); + tag.c_str(), + tag.c_str(), + module.shortDescription())); } void HelpExportReStructuredText::finishModuleExport() @@ -591,7 +594,9 @@ void HelpExportReStructuredText::finishModuleExport() indexFile_.reset(); // TODO: Generalize. manPagesFile_->writeLine(formatString(" ('onlinehelp/%s', '%s', '%s', '', 1)", - binaryName_.c_str(), binaryName_.c_str(), RootHelpText::title)); + binaryName_.c_str(), + binaryName_.c_str(), + RootHelpText::title)); manPagesFile_->writeLine("]"); manPagesFile_->close(); manPagesFile_.reset(); @@ -625,8 +630,8 @@ void HelpExportReStructuredText::exportModuleGroup(const char* title, const Modu GMX_RELEASE_ASSERT(dashPos != std::string::npos, "There should always be at least one dash in the tag"); displayName[dashPos] = ' '; - indexFile_->writeLine(formatString(":doc:`%s `\n %s", displayName.c_str(), - tag.c_str(), module->second)); + indexFile_->writeLine(formatString( + ":doc:`%s `\n %s", displayName.c_str(), tag.c_str(), module->second)); manPagesFile_->writeLine(formatString(":manpage:`%s(1)`\n %s", tag.c_str(), module->second)); } } diff --git a/src/gromacs/commandline/cmdlinehelpwriter.cpp b/src/gromacs/commandline/cmdlinehelpwriter.cpp index df9bc173f4..bd03eebe65 100644 --- a/src/gromacs/commandline/cmdlinehelpwriter.cpp +++ b/src/gromacs/commandline/cmdlinehelpwriter.cpp @@ -2,7 +2,7 @@ * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2010-2018, The GROMACS development team. - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -548,8 +548,8 @@ void CommandLineHelpWriter::writeHelp(const CommandLineHelpContext& context) SynopsisFormatter synopsisFormatter(writerContext); synopsisFormatter.start(context.moduleDisplayName()); filter.formatSelected(OptionsFilter::eSelectInputFileOptions, &synopsisFormatter, impl_->options_); - filter.formatSelected(OptionsFilter::eSelectInputOutputFileOptions, &synopsisFormatter, - impl_->options_); + filter.formatSelected( + OptionsFilter::eSelectInputOutputFileOptions, &synopsisFormatter, impl_->options_); filter.formatSelected(OptionsFilter::eSelectOutputFileOptions, &synopsisFormatter, impl_->options_); filter.formatSelected(OptionsFilter::eSelectOtherOptions, &synopsisFormatter, impl_->options_); synopsisFormatter.finish(); diff --git a/src/gromacs/commandline/pargs.cpp b/src/gromacs/commandline/pargs.cpp index 1b4f6a8c52..079e9bb70f 100644 --- a/src/gromacs/commandline/pargs.cpp +++ b/src/gromacs/commandline/pargs.cpp @@ -189,8 +189,9 @@ namespace { //! Names for XvgFormat -const gmx::EnumerationArray c_xvgFormatNames = { { "xmgrace", "xmgr", - "none" } }; +const gmx::EnumerationArray c_xvgFormatNames = { + { "xmgrace", "xmgr", "none" } +}; /*! \brief Returns the default xvg format, as modified by GMX_VIEW_XVG * if that environment variable is set. diff --git a/src/gromacs/commandline/tests/cmdlinehelpwriter.cpp b/src/gromacs/commandline/tests/cmdlinehelpwriter.cpp index c8dd3e9f28..21e34b70ea 100644 --- a/src/gromacs/commandline/tests/cmdlinehelpwriter.cpp +++ b/src/gromacs/commandline/tests/cmdlinehelpwriter.cpp @@ -81,8 +81,8 @@ void CommandLineHelpWriterTest::checkHelp(gmx::CommandLineHelpWriter* writer) { gmx::StringOutputStream stream; gmx::TextWriter streamWriter(&stream); - gmx::CommandLineHelpContext context(&streamWriter, gmx::eHelpOutputFormat_Console, nullptr, - "test"); + gmx::CommandLineHelpContext context( + &streamWriter, gmx::eHelpOutputFormat_Console, nullptr, "test"); context.setShowHidden(bHidden_); writer->writeHelp(context); stream.close(); diff --git a/src/gromacs/commandline/tests/cmdlinemodulemanagertest.cpp b/src/gromacs/commandline/tests/cmdlinemodulemanagertest.cpp index fe4077ba18..cb31e7c6cd 100644 --- a/src/gromacs/commandline/tests/cmdlinemodulemanagertest.cpp +++ b/src/gromacs/commandline/tests/cmdlinemodulemanagertest.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2012,2013,2014,2015,2019, by the GROMACS development team, led by + * Copyright (c) 2012,2013,2014,2015,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -157,8 +157,8 @@ MockOptionsModule& CommandLineModuleManagerTestBase::addOptionsModule(const char { std::unique_ptr modulePtr(new MockOptionsModule()); MockOptionsModule* module = modulePtr.get(); - gmx::ICommandLineOptionsModule::registerModuleDirect(&manager(), name, description, - std::move(modulePtr)); + gmx::ICommandLineOptionsModule::registerModuleDirect( + &manager(), name, description, std::move(modulePtr)); return *module; } diff --git a/src/gromacs/commandline/tests/pargs.cpp b/src/gromacs/commandline/tests/pargs.cpp index c504953032..2377de53a8 100644 --- a/src/gromacs/commandline/tests/pargs.cpp +++ b/src/gromacs/commandline/tests/pargs.cpp @@ -83,8 +83,8 @@ public: void parseFromArgs(unsigned long flags, gmx::ArrayRef fnm, gmx::ArrayRef pa) { fileCount_ = fnm.size(); - bool bOk = parse_common_args(&args_.argc(), args_.argv(), flags, fnm.size(), fnm.data(), - pa.size(), pa.data(), 0, nullptr, 0, nullptr, &oenv_); + bool bOk = parse_common_args( + &args_.argc(), args_.argv(), flags, fnm.size(), fnm.data(), pa.size(), pa.data(), 0, nullptr, 0, nullptr, &oenv_); EXPECT_TRUE(bOk); } void parseFromArray(gmx::ArrayRef cmdline, diff --git a/src/gromacs/coordinateio/coordinatefile.cpp b/src/gromacs/coordinateio/coordinatefile.cpp index 09fc9733c1..2899ed0db8 100644 --- a/src/gromacs/coordinateio/coordinatefile.cpp +++ b/src/gromacs/coordinateio/coordinatefile.cpp @@ -346,16 +346,24 @@ static t_trxstatus* openTNG(const std::string& name, const Selection& sel, const if (sel.isValid()) { GMX_ASSERT(sel.hasOnlyAtoms(), "Can only work with selections consisting out of atoms"); - return trjtools_gmx_prepare_tng_writing(name.c_str(), filemode[0], + return trjtools_gmx_prepare_tng_writing(name.c_str(), + filemode[0], nullptr, // infile_, //how to get the input file here? - nullptr, sel.atomCount(), mtop, sel.atomIndices(), + nullptr, + sel.atomCount(), + mtop, + sel.atomIndices(), sel.name()); } else { - return trjtools_gmx_prepare_tng_writing(name.c_str(), filemode[0], + return trjtools_gmx_prepare_tng_writing(name.c_str(), + filemode[0], nullptr, // infile_, //how to get the input file here? - nullptr, mtop->natoms, mtop, get_atom_index(mtop), + nullptr, + mtop->natoms, + mtop, + get_atom_index(mtop), "System"); } } @@ -400,8 +408,8 @@ void TrajectoryFrameWriter::prepareAndWriteFrame(const int framenumber, const t_ { localF_.resize(input.natoms); } - deepCopy_t_trxframe(input, &local, localX_.data(), localV_.data(), localF_.data(), - localIndex_.data()); + deepCopy_t_trxframe( + input, &local, localX_.data(), localV_.data(), localF_.data(), localIndex_.data()); for (const auto& outputAdapter : outputAdapters_.getAdapters()) { if (outputAdapter) diff --git a/src/gromacs/coordinateio/outputadaptercontainer.cpp b/src/gromacs/coordinateio/outputadaptercontainer.cpp index d2febd7064..079c46d272 100644 --- a/src/gromacs/coordinateio/outputadaptercontainer.cpp +++ b/src/gromacs/coordinateio/outputadaptercontainer.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -64,7 +64,8 @@ void OutputAdapterContainer::addAdapter(OutputAdapterPointer adapter, Coordinate bool OutputAdapterContainer::isEmpty() const { - return std::none_of(outputAdapters_.begin(), outputAdapters_.end(), - [](const auto& adapter) { return adapter != nullptr; }); + return std::none_of(outputAdapters_.begin(), outputAdapters_.end(), [](const auto& adapter) { + return adapter != nullptr; + }); } } // namespace gmx diff --git a/src/gromacs/coordinateio/tests/coordinate_test.h b/src/gromacs/coordinateio/tests/coordinate_test.h index 98f278c38f..cf8e504388 100644 --- a/src/gromacs/coordinateio/tests/coordinate_test.h +++ b/src/gromacs/coordinateio/tests/coordinate_test.h @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -86,7 +86,9 @@ inline TrajectoryFrameWriterPointer createMinimalTrajectoryFrameWriter(const std const Selection& selection, OutputRequirements requirements) { - return createTrajectoryFrameWriter(topology.mtop(), selection, filename, + return createTrajectoryFrameWriter(topology.mtop(), + selection, + filename, topology.hasTopology() ? topology.copyAtoms() : nullptr, requirements); } diff --git a/src/gromacs/coordinateio/tests/outputadapters.h b/src/gromacs/coordinateio/tests/outputadapters.h index 37f24b6eb9..64569a0217 100644 --- a/src/gromacs/coordinateio/tests/outputadapters.h +++ b/src/gromacs/coordinateio/tests/outputadapters.h @@ -289,7 +289,8 @@ const char* const anySupported[] = { "spc2-traj.trr", #if GMX_USE_TNG "spc2-traj.tng", #endif - "spc2-traj.xtc", "spc2-traj.g96" }; + "spc2-traj.xtc", + "spc2-traj.g96" }; //! Names here work for setVelocity module const char* const setVelocitySupported[] = { @@ -312,7 +313,9 @@ const char* const setForceSupported[] = { }; //! Names here don't work for setForce module -const char* const setForceUnSupported[] = { "spc2-traj.xtc", "spc2-traj.pdb", "spc2-traj.gro", +const char* const setForceUnSupported[] = { "spc2-traj.xtc", + "spc2-traj.pdb", + "spc2-traj.gro", "spc2-traj.g96" }; //! Names here work for setPrecision module @@ -324,7 +327,9 @@ const char* const setPrecisionSupported[] = { }; //! Names here don't work for setPrecision module -const char* const setPrecisionUnSupported[] = { "spc2-traj.trr", "spc2-traj.pdb", "spc2-traj.gro", +const char* const setPrecisionUnSupported[] = { "spc2-traj.trr", + "spc2-traj.pdb", + "spc2-traj.gro", "spc2-traj.g96" }; diff --git a/src/gromacs/correlationfunctions/autocorr.cpp b/src/gromacs/correlationfunctions/autocorr.cpp index 3c6b4b7018..8d827a5f1e 100644 --- a/src/gromacs/correlationfunctions/autocorr.cpp +++ b/src/gromacs/correlationfunctions/autocorr.cpp @@ -141,8 +141,7 @@ static void do_ac_core(int nframes, int nout, real corr[], real c1[], int nresta } if (debug) { - fprintf(debug, "Starting do_ac_core: nframes=%d, nout=%d, nrestart=%d,mode=%lu\n", nframes, - nout, nrestart, mode); + fprintf(debug, "Starting do_ac_core: nframes=%d, nout=%d, nrestart=%d,mode=%lu\n", nframes, nout, nrestart, mode); } for (j = 0; (j < nout); j++) @@ -191,8 +190,15 @@ static void do_ac_core(int nframes, int nout, real corr[], real c1[], int nresta if (cth - 1.0 > 1.0e-15) { - printf("j: %d, k: %d, xj:(%g,%g,%g), xk:(%g,%g,%g)\n", j, k, xj[XX], xj[YY], - xj[ZZ], xk[XX], xk[YY], xk[ZZ]); + printf("j: %d, k: %d, xj:(%g,%g,%g), xk:(%g,%g,%g)\n", + j, + k, + xj[XX], + xj[YY], + xj[ZZ], + xk[XX], + xk[YY], + xk[ZZ]); } mmm = 1; if (MODE(eacP2)) @@ -582,10 +588,11 @@ void low_do_autocorr(const char* fn, /* Print flags and parameters */ if (bVerbose) { - printf("Will calculate %s of %d thingies for %d frames\n", - title ? title : "autocorrelation", nitem, nframes); - printf("bAver = %s, bFour = %s bNormalize= %s\n", gmx::boolToString(bAver), - gmx::boolToString(bFour), gmx::boolToString(bNormalize)); + printf("Will calculate %s of %d thingies for %d frames\n", title ? title : "autocorrelation", nitem, nframes); + printf("bAver = %s, bFour = %s bNormalize= %s\n", + gmx::boolToString(bAver), + gmx::boolToString(bFour), + gmx::boolToString(bNormalize)); printf("mode = %lu, dt = %g, nrestart = %d\n", mode, dt, nrestart); } /* Allocate temp arrays */ @@ -698,7 +705,8 @@ void low_do_autocorr(const char* fn, { Ctav /= nitem; Ct2av /= nitem; - printf("Average correlation time %.3f Std. Dev. %.3f Error %.3f (ps)\n", Ctav, + printf("Average correlation time %.3f Std. Dev. %.3f Error %.3f (ps)\n", + Ctav, std::sqrt((Ct2av - gmx::square(Ctav))), std::sqrt((Ct2av - gmx::square(Ctav)) / (nitem - 1))); } @@ -803,8 +811,22 @@ void do_autocorr(const char* fn, default: break; } - low_do_autocorr(fn, oenv, title, nframes, nitem, acf.nout, c1, dt, mode, acf.nrestart, bAver, - acf.bNormalize, bDebugMode(), acf.tbeginfit, acf.tendfit, acf.fitfn); + low_do_autocorr(fn, + oenv, + title, + nframes, + nitem, + acf.nout, + c1, + dt, + mode, + acf.nrestart, + bAver, + acf.bNormalize, + bDebugMode(), + acf.tbeginfit, + acf.tendfit, + acf.fitfn); } int get_acfnout() diff --git a/src/gromacs/correlationfunctions/expfit.cpp b/src/gromacs/correlationfunctions/expfit.cpp index d57ba055c9..752e0363a6 100644 --- a/src/gromacs/correlationfunctions/expfit.cpp +++ b/src/gromacs/correlationfunctions/expfit.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team. - * Copyright (c) 2013-2019, by the GROMACS development team, led by + * Copyright (c) 2013-2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -566,8 +566,12 @@ static void print_chi2_params(FILE* fp, double yfit = lmcurves[eFitFn](x[i], fitparms); chi2 += gmx::square(y[i] - yfit); } - fprintf(fp, "There are %d data points, %d parameters, %s chi2 = %g\nparams:", nfitpnts, - effnNparams(eFitFn), label, chi2); + fprintf(fp, + "There are %d data points, %d parameters, %s chi2 = %g\nparams:", + nfitpnts, + effnNparams(eFitFn), + label, + chi2); for (i = 0; (i < effnNparams(eFitFn)); i++) { fprintf(fp, " %10g", fitparms[i]); @@ -601,8 +605,7 @@ real do_lmfit(int ndata, if (debug) { fprintf(debug, "There are %d points to fit %d vars!\n", ndata, effnNparams(eFitFn)); - fprintf(debug, "Fit to function %d from %g through %g, dt=%g\n", eFitFn, begintimefit, - endtimefit, dt); + fprintf(debug, "Fit to function %d from %g through %g, dt=%g\n", eFitFn, begintimefit, endtimefit, dt); } snew(x, ndata); @@ -761,19 +764,24 @@ real fit_acf(int ncorr, if (bPrint) { - printf("COR: Correlation time (plain integral from %6.3f to %6.3f ps) = %8.5f ps\n", 0.0, - dt * nf_int, sum); + printf("COR: Correlation time (plain integral from %6.3f to %6.3f ps) = %8.5f ps\n", 0.0, dt * nf_int, sum); printf("COR: Relaxation times are computed as fit to an exponential:\n"); printf("COR: %s\n", effnDescription(fitfn)); printf("COR: Fit to correlation function from %6.3f ps to %6.3f ps, results in a\n", - tbeginfit, std::min(ncorr * dt, tendfit)); + tbeginfit, + std::min(ncorr * dt, tendfit)); } tStart = 0; if (bPrint) { - printf("COR:%11s%11s%11s%11s%11s%11s%11s\n", "Fit from", "Integral", "Tail Value", - "Sum (ps)", " a1 (ps)", (effnNparams(fitfn) >= 2) ? " a2 ()" : "", + printf("COR:%11s%11s%11s%11s%11s%11s%11s\n", + "Fit from", + "Integral", + "Tail Value", + "Sum (ps)", + " a1 (ps)", + (effnNparams(fitfn) >= 2) ? " a2 ()" : "", (effnNparams(fitfn) >= 3) ? " a3 (ps)" : ""); } @@ -843,9 +851,9 @@ real fit_acf(int ncorr, nf_int = std::min(ncorr, static_cast((tStart + 1e-4) / dt)); sum = print_and_integrate(debug, nf_int, dt, c1, nullptr, 1); - tail_corr = do_lmfit(ncorr, c1, sig, dt, nullptr, tStart, tendfit, oenv, bDebugMode(), - fitfn, fitparm, 0, nullptr); - sumtot = sum + tail_corr; + tail_corr = do_lmfit( + ncorr, c1, sig, dt, nullptr, tStart, tendfit, oenv, bDebugMode(), fitfn, fitparm, 0, nullptr); + sumtot = sum + tail_corr; if (fit && ((jmax == 1) || (j == 1))) { double mfp[3]; diff --git a/src/gromacs/correlationfunctions/gmx_lmcurve.cpp b/src/gromacs/correlationfunctions/gmx_lmcurve.cpp index f31daf4f8b..f70317db74 100644 --- a/src/gromacs/correlationfunctions/gmx_lmcurve.cpp +++ b/src/gromacs/correlationfunctions/gmx_lmcurve.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2016,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2016,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -169,8 +169,11 @@ bool lmfit_exp(int nfit, chisq = gmx::square(status->fnorm); if (bVerbose) { - printf("status: fnorm = %g, nfev = %d, userbreak = %d\noutcome = %s\n", status->fnorm, - status->nfev, status->userbreak, lm_infmsg[status->outcome]); + printf("status: fnorm = %g, nfev = %d, userbreak = %d\noutcome = %s\n", + status->fnorm, + status->nfev, + status->userbreak, + lm_infmsg[status->outcome]); } if (bVerbose) { diff --git a/src/gromacs/correlationfunctions/manyautocorrelation.cpp b/src/gromacs/correlationfunctions/manyautocorrelation.cpp index c23d4c694e..3a2866b6a3 100644 --- a/src/gromacs/correlationfunctions/manyautocorrelation.cpp +++ b/src/gromacs/correlationfunctions/manyautocorrelation.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2014,2015,2016,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2014,2015,2016,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -67,8 +67,11 @@ int many_auto_correl(std::vector>* c) if ((*c)[i].size() != ndata) { char buf[256]; - snprintf(buf, sizeof(buf), "Vectors of different lengths supplied (%d %d)", - static_cast((*c)[i].size()), static_cast(ndata)); + snprintf(buf, + sizeof(buf), + "Vectors of different lengths supplied (%d %d)", + static_cast((*c)[i].size()), + static_cast(ndata)); GMX_THROW(gmx::InconsistentInputError(buf)); } } diff --git a/src/gromacs/correlationfunctions/tests/autocorr.cpp b/src/gromacs/correlationfunctions/tests/autocorr.cpp index eb6e17e1c1..f4d8515d31 100644 --- a/src/gromacs/correlationfunctions/tests/autocorr.cpp +++ b/src/gromacs/correlationfunctions/tests/autocorr.cpp @@ -124,9 +124,22 @@ protected: } } real* ptr = result.data(); - low_do_autocorr(nullptr, nullptr, nullptr, nrFrames_, 1, get_acfnout(), &ptr, - data_->getDt(), mode, nrRestart, bAverage, bNormalize, bVerbose, - data_->getStartTime(), data_->getEndTime(), effnNONE); + low_do_autocorr(nullptr, + nullptr, + nullptr, + nrFrames_, + 1, + get_acfnout(), + &ptr, + data_->getDt(), + mode, + nrRestart, + bAverage, + bNormalize, + bVerbose, + data_->getStartTime(), + data_->getEndTime(), + effnNONE); double testResult = 0; for (int i = 0; i < get_acfnout(); i++) diff --git a/src/gromacs/correlationfunctions/tests/expfit.cpp b/src/gromacs/correlationfunctions/tests/expfit.cpp index c7427688f3..3189af7e22 100644 --- a/src/gromacs/correlationfunctions/tests/expfit.cpp +++ b/src/gromacs/correlationfunctions/tests/expfit.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2014,2015,2017,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2014,2015,2017,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -130,9 +130,19 @@ protected: GMX_THROW(InvalidInputError("testType out of range")); } output_env_init_default(&oenv); - do_lmfit(data_[testType].nrLines_, &(data_[testType].y_[0]), nullptr, data_[testType].dt_, - &(data_[testType].x_[0]), data_[testType].startTime_, data_[testType].endTime_, - oenv, false, type, result, 0, nullptr); + do_lmfit(data_[testType].nrLines_, + &(data_[testType].y_[0]), + nullptr, + data_[testType].dt_, + &(data_[testType].x_[0]), + data_[testType].startTime_, + data_[testType].endTime_, + oenv, + false, + type, + result, + 0, + nullptr); output_env_done(oenv); checker_.setDefaultTolerance(test::relativeToleranceAsFloatingPoint(1, tolerance)); checker_.checkSequenceArray(nfitparm, result, "result"); diff --git a/src/gromacs/domdec/box.cpp b/src/gromacs/domdec/box.cpp index 8c342f8438..86bffeec6b 100644 --- a/src/gromacs/domdec/box.cpp +++ b/src/gromacs/domdec/box.cpp @@ -144,8 +144,13 @@ static void set_tric_dir(const ivec* dd_nc, gmx_ddbox_t* ddbox, const matrix box "Domain decomposition has not been implemented for box vectors that " "have non-zero components in directions that do not use domain " "decomposition: ncells = %d %d %d, box vector[%d] = %f %f %f", - (*dd_nc)[XX], (*dd_nc)[YY], (*dd_nc)[ZZ], j + 1, box[j][XX], - box[j][YY], box[j][ZZ]); + (*dd_nc)[XX], + (*dd_nc)[YY], + (*dd_nc)[ZZ], + j + 1, + box[j][XX], + box[j][YY], + box[j][ZZ]); } } } @@ -210,8 +215,7 @@ static void set_tric_dir(const ivec* dd_nc, gmx_ddbox_t* ddbox, const matrix box if (debug) { fprintf(debug, "skew_fac[%d] = %f\n", d, ddbox->skew_fac[d]); - fprintf(debug, "normal[%d] %.3f %.3f %.3f\n", d, normal[d][XX], normal[d][YY], - normal[d][ZZ]); + fprintf(debug, "normal[%d] %.3f %.3f %.3f\n", d, normal[d][XX], normal[d][YY], normal[d][ZZ]); } } else @@ -289,9 +293,14 @@ void set_ddbox(const gmx_domdec_t& dd, gmx::ArrayRef xRef = constArrayRefFromArray( x.data(), masterRankHasTheSystemState ? x.size() : dd.comm->atomRanges.numHomeAtoms()); - low_set_ddbox(dd.unitCellInfo.npbcdim, dd.unitCellInfo.numBoundedDimensions, &dd.numCells, - box, calculateUnboundedSize, xRef, - needToReduceCoordinateData ? &dd.mpi_comm_all : nullptr, ddbox); + low_set_ddbox(dd.unitCellInfo.npbcdim, + dd.unitCellInfo.numBoundedDimensions, + &dd.numCells, + box, + calculateUnboundedSize, + xRef, + needToReduceCoordinateData ? &dd.mpi_comm_all : nullptr, + ddbox); } if (masterRankHasTheSystemState) @@ -310,8 +319,8 @@ void set_ddbox_cr(DDRole ddRole, { if (ddRole == DDRole::Master) { - low_set_ddbox(numPbcDimensions(ir.pbcType), inputrec2nboundeddim(&ir), dd_nc, box, true, x, - nullptr, ddbox); + low_set_ddbox( + numPbcDimensions(ir.pbcType), inputrec2nboundeddim(&ir), dd_nc, box, true, x, nullptr, ddbox); } gmx_bcast(sizeof(gmx_ddbox_t), ddbox, communicator); diff --git a/src/gromacs/domdec/cellsizes.cpp b/src/gromacs/domdec/cellsizes.cpp index 4867f64330..1faea8895a 100644 --- a/src/gromacs/domdec/cellsizes.cpp +++ b/src/gromacs/domdec/cellsizes.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2018,2019, by the GROMACS development team, led by + * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -143,7 +143,10 @@ static void check_box_size(const gmx_domdec_t* dd, const gmx_ddbox_t* ddbox) FARGS, "The %c-size of the box (%f) times the triclinic skew factor (%f) is smaller " "than the number of DD cells (%d) times the smallest allowed cell size (%f)\n", - dim2char(dim), ddbox->box_size[dim], ddbox->skew_fac[dim], dd->numCells[dim], + dim2char(dim), + ddbox->box_size[dim], + ddbox->skew_fac[dim], + dd->numCells[dim], dd->comm->cellsize_limit); } } @@ -294,8 +297,13 @@ set_dd_cell_sizes_slb(gmx_domdec_t* dd, const gmx_ddbox_t* ddbox, int setmode, i "The box size in direction %c (%f) times the triclinic skew factor (%f) is too " "small for a cut-off of %f with %d domain decomposition cells, use 1 or more " "than %d %s or increase the box size in this direction", - dim2char(d), ddbox->box_size[d], ddbox->skew_fac[d], comm->systemInfo.cutoff, - dd->numCells[d], dd->numCells[d], dd->nnodes > dd->numCells[d] ? "cells" : "ranks"); + dim2char(d), + ddbox->box_size[d], + ddbox->skew_fac[d], + comm->systemInfo.cutoff, + dd->numCells[d], + dd->numCells[d], + dd->nnodes > dd->numCells[d] ? "cells" : "ranks"); if (setmode == setcellsizeslbLOCAL) { @@ -316,7 +324,10 @@ set_dd_cell_sizes_slb(gmx_domdec_t* dd, const gmx_ddbox_t* ddbox, int setmode, i DDRankSetup& ddRankSetup = comm->ddRankSetup; for (int d = 0; d < ddRankSetup.npmedecompdim; d++) { - set_pme_maxshift(dd, &ddRankSetup.ddpme[d], comm->slb_frac[dd->dim[d]] == nullptr, ddbox, + set_pme_maxshift(dd, + &ddRankSetup.ddpme[d], + comm->slb_frac[dd->dim[d]] == nullptr, + ddbox, ddRankSetup.ddpme[d].slb_dim_f); } @@ -425,8 +436,12 @@ static void dd_cell_sizes_dlb_root_enforce_limits(gmx_domdec_t* dd, gmx_fatal(FARGS, "step %s: the dynamic load balancing could not balance dimension %c: box size " "%f, triclinic skew factor %f, #cells %d, minimum cell size %f\n", - gmx_step_str(step, buf), dim2char(dim), ddbox->box_size[dim], - ddbox->skew_fac[dim], ncd, comm->cellsize_min[dim]); + gmx_step_str(step, buf), + dim2char(dim), + ddbox->box_size[dim], + ddbox->skew_fac[dim], + ncd, + comm->cellsize_min[dim]); } rowMaster->dlbIsLimited = (nmin > 0) || (range[0] > 0) || (range[1] < ncd); @@ -502,13 +517,13 @@ static void dd_cell_sizes_dlb_root_enforce_limits(gmx_domdec_t* dd, rowMaster->cellFrac[i] = 0.5 * (bounds.boundMin + bounds.boundMax); nrange[0] = range[0]; nrange[1] = i; - dd_cell_sizes_dlb_root_enforce_limits(dd, d, dim, rowMaster, ddbox, bUniform, - step, cellsize_limit_f, nrange); + dd_cell_sizes_dlb_root_enforce_limits( + dd, d, dim, rowMaster, ddbox, bUniform, step, cellsize_limit_f, nrange); nrange[0] = i; nrange[1] = range[1]; - dd_cell_sizes_dlb_root_enforce_limits(dd, d, dim, rowMaster, ddbox, bUniform, - step, cellsize_limit_f, nrange); + dd_cell_sizes_dlb_root_enforce_limits( + dd, d, dim, rowMaster, ddbox, bUniform, step, cellsize_limit_f, nrange); return; } @@ -524,14 +539,14 @@ static void dd_cell_sizes_dlb_root_enforce_limits(gmx_domdec_t* dd, if (nrange[1] < range[1]) /* found a LimLo before */ { rowMaster->cellFrac[nrange[1]] = rowMaster->bounds[nrange[1]].boundMin; - dd_cell_sizes_dlb_root_enforce_limits(dd, d, dim, rowMaster, ddbox, bUniform, - step, cellsize_limit_f, nrange); + dd_cell_sizes_dlb_root_enforce_limits( + dd, d, dim, rowMaster, ddbox, bUniform, step, cellsize_limit_f, nrange); nrange[0] = nrange[1]; } rowMaster->cellFrac[i] = rowMaster->bounds[i].boundMax; nrange[1] = i; - dd_cell_sizes_dlb_root_enforce_limits(dd, d, dim, rowMaster, ddbox, bUniform, - step, cellsize_limit_f, nrange); + dd_cell_sizes_dlb_root_enforce_limits( + dd, d, dim, rowMaster, ddbox, bUniform, step, cellsize_limit_f, nrange); nrange[0] = i; nrange[1] = range[1]; } @@ -539,17 +554,17 @@ static void dd_cell_sizes_dlb_root_enforce_limits(gmx_domdec_t* dd, if (nrange[1] < range[1]) /* found last a LimLo */ { rowMaster->cellFrac[nrange[1]] = rowMaster->bounds[nrange[1]].boundMin; - dd_cell_sizes_dlb_root_enforce_limits(dd, d, dim, rowMaster, ddbox, bUniform, step, - cellsize_limit_f, nrange); + dd_cell_sizes_dlb_root_enforce_limits( + dd, d, dim, rowMaster, ddbox, bUniform, step, cellsize_limit_f, nrange); nrange[0] = nrange[1]; nrange[1] = range[1]; - dd_cell_sizes_dlb_root_enforce_limits(dd, d, dim, rowMaster, ddbox, bUniform, step, - cellsize_limit_f, nrange); + dd_cell_sizes_dlb_root_enforce_limits( + dd, d, dim, rowMaster, ddbox, bUniform, step, cellsize_limit_f, nrange); } else if (nrange[0] > range[0]) /* found at least one LimHi */ { - dd_cell_sizes_dlb_root_enforce_limits(dd, d, dim, rowMaster, ddbox, bUniform, step, - cellsize_limit_f, nrange); + dd_cell_sizes_dlb_root_enforce_limits( + dd, d, dim, rowMaster, ddbox, bUniform, step, cellsize_limit_f, nrange); } } } @@ -664,17 +679,23 @@ static void set_dd_cell_sizes_dlb_root(gmx_domdec_t* dd, } if (debug) { - fprintf(debug, "dim %d boundary %d %.3f < %.3f < %.3f < %.3f < %.3f\n", d, i, - boundsNeighbor.cellFracLowerMax + dist_min_f, bounds.boundMin, - rowMaster->cellFrac[i], bounds.boundMax, bounds.cellFracUpperMin - dist_min_f); + fprintf(debug, + "dim %d boundary %d %.3f < %.3f < %.3f < %.3f < %.3f\n", + d, + i, + boundsNeighbor.cellFracLowerMax + dist_min_f, + bounds.boundMin, + rowMaster->cellFrac[i], + bounds.boundMax, + bounds.cellFracUpperMin - dist_min_f); } } } range[1] = ncd; rowMaster->cellFrac[0] = 0; rowMaster->cellFrac[ncd] = 1; - dd_cell_sizes_dlb_root_enforce_limits(dd, d, dim, rowMaster, ddbox, bUniform, step, - cellsize_limit_f, range); + dd_cell_sizes_dlb_root_enforce_limits( + dd, d, dim, rowMaster, ddbox, bUniform, step, cellsize_limit_f, range); /* After the checks above, the cells should obey the cut-off @@ -684,16 +705,23 @@ static void set_dd_cell_sizes_dlb_root(gmx_domdec_t* dd, { if (debug) { - fprintf(debug, "Relative bounds dim %d cell %d: %f %f\n", dim, i, - rowMaster->cellFrac[i], rowMaster->cellFrac[i + 1]); + fprintf(debug, + "Relative bounds dim %d cell %d: %f %f\n", + dim, + i, + rowMaster->cellFrac[i], + rowMaster->cellFrac[i + 1]); } if ((bPBC || (i != 0 && i != dd->numCells[dim] - 1)) && rowMaster->cellFrac[i + 1] - rowMaster->cellFrac[i] < cellsize_limit_f / DD_CELL_MARGIN) { char buf[22]; - fprintf(stderr, "\nWARNING step %s: direction %c, cell %d too small: %f\n", - gmx_step_str(step, buf), dim2char(dim), i, + fprintf(stderr, + "\nWARNING step %s: direction %c, cell %d too small: %f\n", + gmx_step_str(step, buf), + dim2char(dim), + i, (rowMaster->cellFrac[i + 1] - rowMaster->cellFrac[i]) * ddbox->box_size[dim] * ddbox->skew_fac[dim]); } @@ -750,7 +778,10 @@ static void distribute_dd_cell_sizes_dlb(gmx_domdec_t* dd, /* Each node would only need to know two fractions, * but it is probably cheaper to broadcast the whole array. */ - MPI_Bcast(cellFracRow.data(), ddCellFractionBufferSize(dd, d) * sizeof(real), MPI_BYTE, 0, + MPI_Bcast(cellFracRow.data(), + ddCellFractionBufferSize(dd, d) * sizeof(real), + MPI_BYTE, + 0, comm.mpi_comm_load[d]); #endif /* Copy the fractions for this dimension from the buffer */ @@ -914,7 +945,9 @@ void set_dd_cell_sizes(gmx_domdec_t* dd, fprintf(debug, "Changing the number of halo communication pulses along dim %c from %d " "to %d\n", - dim2char(dd->dim[d]), cd.numPulses(), numPulsesDim); + dim2char(dd->dim[d]), + cd.numPulses(), + numPulsesDim); } cd.ind.resize(numPulsesDim); } @@ -925,8 +958,12 @@ void set_dd_cell_sizes(gmx_domdec_t* dd, { for (int d = 0; d < DIM; d++) { - fprintf(debug, "cell_x[%d] %f - %f skew_fac %f\n", d, comm->cell_x0[d], - comm->cell_x1[d], ddbox->skew_fac[d]); + fprintf(debug, + "cell_x[%d] %f - %f skew_fac %f\n", + d, + comm->cell_x0[d], + comm->cell_x1[d], + ddbox->skew_fac[d]); } } } diff --git a/src/gromacs/domdec/collect.cpp b/src/gromacs/domdec/collect.cpp index 0924461f78..59c23df45f 100644 --- a/src/gromacs/domdec/collect.cpp +++ b/src/gromacs/domdec/collect.cpp @@ -134,7 +134,9 @@ static void dd_collect_cg(gmx_domdec_t* dd, } /* Collect the charge group indices on the master */ - dd_gatherv(dd, atomGroups.size() * sizeof(int), atomGroups.data(), + dd_gatherv(dd, + atomGroups.size() * sizeof(int), + atomGroups.data(), DDMASTER(dd) ? ma->intBuffer.data() : nullptr, DDMASTER(dd) ? ma->intBuffer.data() + dd->nnodes : nullptr, DDMASTER(dd) ? ma->atomGroups.data() : nullptr); @@ -151,7 +153,11 @@ static void dd_collect_vec_sendrecv(gmx_domdec_t* dd, #if GMX_MPI const int numHomeAtoms = dd->comm->atomRanges.numHomeAtoms(); MPI_Send(const_cast(static_cast(lv.data())), - numHomeAtoms * sizeof(rvec), MPI_BYTE, dd->masterrank, dd->rank, dd->mpi_comm_all); + numHomeAtoms * sizeof(rvec), + MPI_BYTE, + dd->masterrank, + dd->rank, + dd->mpi_comm_all); #endif } else @@ -183,8 +189,13 @@ static void dd_collect_vec_sendrecv(gmx_domdec_t* dd, } #if GMX_MPI - MPI_Recv(ma.rvecBuffer.data(), domainGroups.numAtoms * sizeof(rvec), MPI_BYTE, rank, - rank, dd->mpi_comm_all, MPI_STATUS_IGNORE); + MPI_Recv(ma.rvecBuffer.data(), + domainGroups.numAtoms * sizeof(rvec), + MPI_BYTE, + rank, + rank, + dd->mpi_comm_all, + MPI_STATUS_IGNORE); #endif int localAtom = 0; for (const int& globalAtom : domainGroups.atomGroups) @@ -209,7 +220,11 @@ static void dd_collect_vec_gatherv(gmx_domdec_t* dd, } const int numHomeAtoms = dd->comm->atomRanges.numHomeAtoms(); - dd_gatherv(dd, numHomeAtoms * sizeof(rvec), lv.data(), recvCounts, displacements, + dd_gatherv(dd, + numHomeAtoms * sizeof(rvec), + lv.data(), + recvCounts, + displacements, DDMASTER(dd) ? dd->ma->rvecBuffer.data() : nullptr); if (DDMASTER(dd)) @@ -293,19 +308,31 @@ void dd_collect_state(gmx_domdec_t* dd, const t_state* state_local, t_state* sta if (state_local->flags & (1 << estX)) { auto globalXRef = state ? state->x : gmx::ArrayRef(); - dd_collect_vec(dd, state_local->ddp_count, state_local->ddp_count_cg_gl, state_local->cg_gl, - state_local->x, globalXRef); + dd_collect_vec(dd, + state_local->ddp_count, + state_local->ddp_count_cg_gl, + state_local->cg_gl, + state_local->x, + globalXRef); } if (state_local->flags & (1 << estV)) { auto globalVRef = state ? state->v : gmx::ArrayRef(); - dd_collect_vec(dd, state_local->ddp_count, state_local->ddp_count_cg_gl, state_local->cg_gl, - state_local->v, globalVRef); + dd_collect_vec(dd, + state_local->ddp_count, + state_local->ddp_count_cg_gl, + state_local->cg_gl, + state_local->v, + globalVRef); } if (state_local->flags & (1 << estCGP)) { auto globalCgpRef = state ? state->cg_p : gmx::ArrayRef(); - dd_collect_vec(dd, state_local->ddp_count, state_local->ddp_count_cg_gl, state_local->cg_gl, - state_local->cg_p, globalCgpRef); + dd_collect_vec(dd, + state_local->ddp_count, + state_local->ddp_count_cg_gl, + state_local->cg_gl, + state_local->cg_p, + globalCgpRef); } } diff --git a/src/gromacs/domdec/distribute.cpp b/src/gromacs/domdec/distribute.cpp index 062acc6b57..9485b08d13 100644 --- a/src/gromacs/domdec/distribute.cpp +++ b/src/gromacs/domdec/distribute.cpp @@ -87,8 +87,7 @@ static void distributeVecSendrecv(gmx_domdec_t* dd, "The index count and number of indices should match"); #if GMX_MPI - MPI_Send(buffer.data(), domainGroups.numAtoms * sizeof(gmx::RVec), MPI_BYTE, rank, - rank, dd->mpi_comm_all); + MPI_Send(buffer.data(), domainGroups.numAtoms * sizeof(gmx::RVec), MPI_BYTE, rank, rank, dd->mpi_comm_all); #endif } } @@ -104,8 +103,13 @@ static void distributeVecSendrecv(gmx_domdec_t* dd, { #if GMX_MPI int numHomeAtoms = dd->comm->atomRanges.numHomeAtoms(); - MPI_Recv(localVec.data(), numHomeAtoms * sizeof(gmx::RVec), MPI_BYTE, dd->masterrank, - MPI_ANY_TAG, dd->mpi_comm_all, MPI_STATUS_IGNORE); + MPI_Recv(localVec.data(), + numHomeAtoms * sizeof(gmx::RVec), + MPI_BYTE, + dd->masterrank, + MPI_ANY_TAG, + dd->mpi_comm_all, + MPI_STATUS_IGNORE); #endif } } @@ -136,8 +140,12 @@ static void distributeVecScatterv(gmx_domdec_t* dd, } int numHomeAtoms = dd->comm->atomRanges.numHomeAtoms(); - dd_scatterv(dd, sendCounts, displacements, DDMASTER(dd) ? dd->ma->rvecBuffer.data() : nullptr, - numHomeAtoms * sizeof(gmx::RVec), localVec.data()); + dd_scatterv(dd, + sendCounts, + displacements, + DDMASTER(dd) ? dd->ma->rvecBuffer.data() : nullptr, + numHomeAtoms * sizeof(gmx::RVec), + localVec.data()); } static void distributeVec(gmx_domdec_t* dd, @@ -401,12 +409,11 @@ static std::vector> getAtomGroupDistribution(const gmx::MDLogge { for (int g = 0; g < updateGrouping.numBlocks(); g++) { - const auto& block = updateGrouping.block(g); - const int atomBegin = atomOffset + block.begin(); - const int atomEnd = atomOffset + block.end(); - const int domainIndex = - computeAtomGroupDomainIndex(*dd, ddbox, triclinicCorrectionMatrix, - cellBoundaries, atomBegin, atomEnd, box, pos); + const auto& block = updateGrouping.block(g); + const int atomBegin = atomOffset + block.begin(); + const int atomEnd = atomOffset + block.end(); + const int domainIndex = computeAtomGroupDomainIndex( + *dd, ddbox, triclinicCorrectionMatrix, cellBoundaries, atomBegin, atomEnd, box, pos); for (int atomIndex : block) { @@ -426,8 +433,8 @@ static std::vector> getAtomGroupDistribution(const gmx::MDLogge /* Compute the center of geometry for all atoms */ for (int atom = 0; atom < mtop.natoms; atom++) { - int domainIndex = computeAtomGroupDomainIndex(*dd, ddbox, triclinicCorrectionMatrix, - cellBoundaries, atom, atom + 1, box, pos); + int domainIndex = computeAtomGroupDomainIndex( + *dd, ddbox, triclinicCorrectionMatrix, cellBoundaries, atom, atom + 1, box, pos); indices[domainIndex].push_back(atom); ma.domainGroups[domainIndex].numAtoms += 1; @@ -459,9 +466,11 @@ static std::vector> getAtomGroupDistribution(const gmx::MDLogge GMX_LOG(mdlog.info) .appendTextFormatted( "Atom distribution over %d domains: av %d stddev %d min %d max %d", - dd->nnodes, nat_sum, + dd->nnodes, + nat_sum, gmx::roundToInt(std::sqrt(nat2_sum - gmx::square(static_cast(nat_sum)))), - nat_min, nat_max); + nat_min, + nat_max); } return indices; @@ -519,8 +528,8 @@ static void distributeAtomGroups(const gmx::MDLogger& mdlog, ma->intBuffer[rank] = groupIndices[rank].size() * sizeof(int); ma->intBuffer[dd->nnodes + rank] = groupOffset * sizeof(int); - ma->atomGroups.insert(ma->atomGroups.end(), groupIndices[rank].begin(), - groupIndices[rank].end()); + ma->atomGroups.insert( + ma->atomGroups.end(), groupIndices[rank].begin(), groupIndices[rank].end()); ma->domainGroups[rank].atomGroups = gmx::constArrayRefFromArray( ma->atomGroups.data() + groupOffset, groupIndices[rank].size()); @@ -529,9 +538,11 @@ static void distributeAtomGroups(const gmx::MDLogger& mdlog, } } - dd_scatterv(dd, bMaster ? ma->intBuffer.data() : nullptr, + dd_scatterv(dd, + bMaster ? ma->intBuffer.data() : nullptr, bMaster ? ma->intBuffer.data() + dd->nnodes : nullptr, - bMaster ? ma->atomGroups.data() : nullptr, dd->ncg_home * sizeof(int), + bMaster ? ma->atomGroups.data() : nullptr, + dd->ncg_home * sizeof(int), dd->globalAtomGroupIndices.data()); if (debug) diff --git a/src/gromacs/domdec/domdec.cpp b/src/gromacs/domdec/domdec.cpp index d3ba5aba08..fe24a703b0 100644 --- a/src/gromacs/domdec/domdec.cpp +++ b/src/gromacs/domdec/domdec.cpp @@ -190,7 +190,8 @@ int ddglatnr(const gmx_domdec_t* dd, int i) { gmx_fatal(FARGS, "glatnr called with %d, which is larger than the local number of atoms (%d)", - i, dd->comm->atomRanges.numAtomsTotal()); + i, + dd->comm->atomRanges.numAtomsTotal()); } atnr = dd->globalAtomIndices[i] + 1; } @@ -1113,8 +1114,7 @@ void dd_setup_dlb_resource_sharing(const t_commrec* cr, int gpu_id) if (debug) { fprintf(debug, "dd_setup_dd_dlb_gpu_sharing:\n"); - fprintf(debug, "DD PP rank %d physical node hash %d gpu_id %d\n", dd->rank, - physicalnode_id_hash, gpu_id); + fprintf(debug, "DD PP rank %d physical node hash %d gpu_id %d\n", dd->rank, physicalnode_id_hash, gpu_id); } /* Split the PP communicator over the physical nodes */ /* TODO: See if we should store this (before), as it's also used for @@ -1215,8 +1215,12 @@ static void setup_neighbor_relations(gmx_domdec_t* dd) dd->neighbor[d][1] = ddcoord2ddnodeid(dd, tmp); if (debug) { - fprintf(debug, "DD rank %d neighbor ranks in dir %d are + %d - %d\n", dd->rank, dim, - dd->neighbor[d][0], dd->neighbor[d][1]); + fprintf(debug, + "DD rank %d neighbor ranks in dir %d are + %d - %d\n", + dd->rank, + dim, + dd->neighbor[d][0], + dd->neighbor[d][1]); } } @@ -1321,7 +1325,9 @@ static void make_pp_communicator(const gmx::MDLogger& mdlog, /* Set up cartesian communication for the particle-particle part */ GMX_LOG(mdlog.info) .appendTextFormatted("Will use a Cartesian communicator: %d x %d x %d", - dd->numCells[XX], dd->numCells[YY], dd->numCells[ZZ]); + dd->numCells[XX], + dd->numCells[YY], + dd->numCells[ZZ]); ivec periods; for (int i = 0; i < DIM; i++) @@ -1329,8 +1335,7 @@ static void make_pp_communicator(const gmx::MDLogger& mdlog, periods[i] = TRUE; } MPI_Comm comm_cart; - MPI_Cart_create(cr->mpi_comm_mygroup, DIM, dd->numCells, periods, static_cast(reorder), - &comm_cart); + MPI_Cart_create(cr->mpi_comm_mygroup, DIM, dd->numCells, periods, static_cast(reorder), &comm_cart); /* We overwrite the old communicator with the new cartesian one */ cr->mpi_comm_mygroup = comm_cart; } @@ -1383,8 +1388,7 @@ static void make_pp_communicator(const gmx::MDLogger& mdlog, buf[dd_index(dd->numCells, dd->ci)] = cr->sim_nodeid; } /* Communicate the ddindex to simulation nodeid index */ - MPI_Allreduce(buf.data(), cartSetup.ddindex2simnodeid.data(), dd->nnodes, MPI_INT, MPI_SUM, - cr->mpi_comm_mysim); + MPI_Allreduce(buf.data(), cartSetup.ddindex2simnodeid.data(), dd->nnodes, MPI_INT, MPI_SUM, cr->mpi_comm_mysim); /* Determine the master coordinates and rank. * The DD master should be the same node as the master of this sim. @@ -1414,12 +1418,19 @@ static void make_pp_communicator(const gmx::MDLogger& mdlog, #endif GMX_LOG(mdlog.info) - .appendTextFormatted("Domain decomposition rank %d, coordinates %d %d %d\n", dd->rank, - dd->ci[XX], dd->ci[YY], dd->ci[ZZ]); + .appendTextFormatted("Domain decomposition rank %d, coordinates %d %d %d\n", + dd->rank, + dd->ci[XX], + dd->ci[YY], + dd->ci[ZZ]); if (debug) { - fprintf(debug, "Domain decomposition rank %d, coordinates %d %d %d\n\n", dd->rank, - dd->ci[XX], dd->ci[YY], dd->ci[ZZ]); + fprintf(debug, + "Domain decomposition rank %d, coordinates %d %d %d\n\n", + dd->rank, + dd->ci[XX], + dd->ci[YY], + dd->ci[ZZ]); } } @@ -1437,8 +1448,7 @@ static void receive_ddindex2simnodeid(gmx_domdec_t* dd, t_commrec* cr) buf[dd_index(dd->numCells, dd->ci)] = cr->sim_nodeid; } /* Communicate the ddindex to simulation nodeid index */ - MPI_Allreduce(buf.data(), cartSetup.ddindex2simnodeid.data(), dd->nnodes, MPI_INT, MPI_SUM, - cr->mpi_comm_mysim); + MPI_Allreduce(buf.data(), cartSetup.ddindex2simnodeid.data(), dd->nnodes, MPI_INT, MPI_SUM, cr->mpi_comm_mysim); } #else GMX_UNUSED_VALUE(dd); @@ -1498,8 +1508,11 @@ static CartesianRankSetup split_communicator(const gmx::MDLogger& mdlog, .appendTextFormatted( "Number of PME-only ranks (%d) is not a multiple of nx*ny (%d*%d) or " "nx*nz (%d*%d)", - ddRankSetup.numRanksDoingPme, numDDCells[XX], numDDCells[YY], - numDDCells[XX], numDDCells[ZZ]); + ddRankSetup.numRanksDoingPme, + numDDCells[XX], + numDDCells[YY], + numDDCells[XX], + numDDCells[ZZ]); GMX_LOG(mdlog.info) .appendText("Will not use a Cartesian communicator for PP <-> PME\n"); } @@ -1514,15 +1527,16 @@ static CartesianRankSetup split_communicator(const gmx::MDLogger& mdlog, GMX_LOG(mdlog.info) .appendTextFormatted( "Will use a Cartesian communicator for PP <-> PME: %d x %d x %d", - cartSetup.ntot[XX], cartSetup.ntot[YY], cartSetup.ntot[ZZ]); + cartSetup.ntot[XX], + cartSetup.ntot[YY], + cartSetup.ntot[ZZ]); for (int i = 0; i < DIM; i++) { periods[i] = TRUE; } MPI_Comm comm_cart; - MPI_Cart_create(cr->mpi_comm_mysim, DIM, cartSetup.ntot, periods, static_cast(reorder), - &comm_cart); + MPI_Cart_create(cr->mpi_comm_mysim, DIM, cartSetup.ntot, periods, static_cast(reorder), &comm_cart); MPI_Comm_rank(comm_cart, &rank); if (MASTER(cr) && rank != 0) { @@ -1538,8 +1552,11 @@ static CartesianRankSetup split_communicator(const gmx::MDLogger& mdlog, MPI_Cart_coords(cr->mpi_comm_mysim, cr->sim_nodeid, DIM, ddCellIndex); GMX_LOG(mdlog.info) - .appendTextFormatted("Cartesian rank %d, coordinates %d %d %d\n", cr->sim_nodeid, - ddCellIndex[XX], ddCellIndex[YY], ddCellIndex[ZZ]); + .appendTextFormatted("Cartesian rank %d, coordinates %d %d %d\n", + cr->sim_nodeid, + ddCellIndex[XX], + ddCellIndex[YY], + ddCellIndex[ZZ]); if (ddCellIndex[cartSetup.cartpmedim] < numDDCells[cartSetup.cartpmedim]) { @@ -1552,8 +1569,10 @@ static CartesianRankSetup split_communicator(const gmx::MDLogger& mdlog, } /* Split the sim communicator into PP and PME only nodes */ - MPI_Comm_split(cr->mpi_comm_mysim, getThisRankDuties(cr), - dd_index(cartSetup.ntot, ddCellIndex), &cr->mpi_comm_mygroup); + MPI_Comm_split(cr->mpi_comm_mysim, + getThisRankDuties(cr), + dd_index(cartSetup.ntot, ddCellIndex), + &cr->mpi_comm_mygroup); #else GMX_UNUSED_VALUE(ddCellIndex); #endif @@ -1623,8 +1642,8 @@ static CartesianRankSetup makeGroupCommunicators(const gmx::MDLogger& mdlog, if (ddRankSetup.usePmeOnlyRanks) { /* Split the communicator into a PP and PME part */ - cartSetup = split_communicator(mdlog, cr, ddRankOrder, ddSettings.useCartesianReorder, - ddRankSetup, ddCellIndex, pmeRanks); + cartSetup = split_communicator( + mdlog, cr, ddRankOrder, ddSettings.useCartesianReorder, ddRankSetup, ddCellIndex, pmeRanks); } else { @@ -1675,7 +1694,9 @@ static void setupGroupCommunication(const gmx::MDLogger& mdlog, dd->pme_receive_vir_ener = receive_vir_ener(dd, pmeRanks, cr); if (debug) { - fprintf(debug, "My pme_nodeid %d receive ener %s\n", dd->pme_nodeid, + fprintf(debug, + "My pme_nodeid %d receive ener %s\n", + dd->pme_nodeid, gmx::boolToString(dd->pme_receive_vir_ener)); } } @@ -1711,7 +1732,8 @@ static real* get_slb_frac(const gmx::MDLogger& mdlog, const char* dir, int nc, c { gmx_fatal(FARGS, "Incorrect or not enough DD cell size entries for direction %s: '%s'", - dir, size_string); + dir, + size_string); } slb_frac[i] = dbl; size_string += n; @@ -1773,7 +1795,8 @@ static void check_dd_restrictions(const gmx_domdec_t* dd, const t_inputrec* ir, if (ir->pbcType == PbcType::Screw && (dd->numCells[XX] == 1 || dd->numCells[YY] > 1 || dd->numCells[ZZ] > 1)) { - gmx_fatal(FARGS, "With pbc=%s can only do domain decomposition in the x-direction", + gmx_fatal(FARGS, + "With pbc=%s can only do domain decomposition in the x-direction", c_pbcTypeNames[ir->pbcType].c_str()); } @@ -1900,7 +1923,8 @@ static DlbState determineInitialDlbState(const gmx::MDLogger& mdlog, "ensured.", mdlog); default: - gmx_fatal(FARGS, "Death horror: undefined case (%d) for load balancing choice", + gmx_fatal(FARGS, + "Death horror: undefined case (%d) for load balancing choice", static_cast(dlbState)); } } @@ -1994,7 +2018,8 @@ static void setupUpdateGroups(const gmx::MDLogger& mdlog, .appendTextFormatted( "Using update groups, nr %d, average size %.1f atoms, max. radius %.3f " "nm\n", - numUpdateGroups, mtop.natoms / static_cast(numUpdateGroups), + numUpdateGroups, + mtop.natoms / static_cast(numUpdateGroups), systemInfo->maxUpdateGroupRadius); } else @@ -2163,8 +2188,8 @@ static DDSystemInfo getSystemInfo(const gmx::MDLogger& mdlog, if (ddRole == DDRole::Master) { - dd_bonded_cg_distance(mdlog, &mtop, &ir, xGlobal, box, - options.checkBondedInteractions, &r_2b, &r_mb); + dd_bonded_cg_distance( + mdlog, &mtop, &ir, xGlobal, box, options.checkBondedInteractions, &r_2b, &r_mb); } gmx_bcast(sizeof(r_2b), &r_2b, communicator); gmx_bcast(sizeof(r_mb), &r_mb, communicator); @@ -2255,16 +2280,22 @@ static void checkDDGridSetup(const DDGridSetup& ddGridSetup, char buf[STRLEN]; gmx_bool bC = (systemInfo.haveSplitConstraints && systemInfo.constraintCommunicationRange > systemInfo.minCutoffForMultiBody); - sprintf(buf, "Change the number of ranks or mdrun option %s%s%s", !bC ? "-rdd" : "-rcon", + sprintf(buf, + "Change the number of ranks or mdrun option %s%s%s", + !bC ? "-rdd" : "-rcon", ddSettings.initialDlbState != DlbState::offUser ? " or -dds" : "", bC ? " or your LINCS settings" : ""); - gmx_fatal_collective(FARGS, communicator, ddRole == DDRole::Master, + gmx_fatal_collective(FARGS, + communicator, + ddRole == DDRole::Master, "There is no domain decomposition for %d ranks that is compatible " "with the given box and a minimum cell size of %g nm\n" "%s\n" "Look in the log file for details on the domain decomposition", - numNodes - ddGridSetup.numPmeOnlyRanks, cellsizeLimit, buf); + numNodes - ddGridSetup.numPmeOnlyRanks, + cellsizeLimit, + buf); } const real acs = average_cellsize_min(ddbox, ddGridSetup.numDomains); @@ -2279,10 +2310,13 @@ static void checkDDGridSetup(const DDGridSetup& ddGridSetup, else { gmx_fatal_collective( - FARGS, communicator, ddRole == DDRole::Master, + FARGS, + communicator, + ddRole == DDRole::Master, "The initial cell size (%f) is smaller than the cell size limit (%f), change " "options -dd, -rdd or -rcon, see the log file for details", - acs, cellsizeLimit); + acs, + cellsizeLimit); } } @@ -2290,17 +2324,24 @@ static void checkDDGridSetup(const DDGridSetup& ddGridSetup, ddGridSetup.numDomains[XX] * ddGridSetup.numDomains[YY] * ddGridSetup.numDomains[ZZ]; if (numNodes - numPPRanks != ddGridSetup.numPmeOnlyRanks) { - gmx_fatal_collective(FARGS, communicator, ddRole == DDRole::Master, + gmx_fatal_collective(FARGS, + communicator, + ddRole == DDRole::Master, "The size of the domain decomposition grid (%d) does not match the " "number of PP ranks (%d). The total number of ranks is %d", - numPPRanks, numNodes - ddGridSetup.numPmeOnlyRanks, numNodes); + numPPRanks, + numNodes - ddGridSetup.numPmeOnlyRanks, + numNodes); } if (ddGridSetup.numPmeOnlyRanks > numPPRanks) { - gmx_fatal_collective(FARGS, communicator, ddRole == DDRole::Master, + gmx_fatal_collective(FARGS, + communicator, + ddRole == DDRole::Master, "The number of separate PME ranks (%d) is larger than the number of " "PP ranks (%d), this is not supported.", - ddGridSetup.numPmeOnlyRanks, numPPRanks); + ddGridSetup.numPmeOnlyRanks, + numPPRanks); } } @@ -2312,8 +2353,10 @@ static DDRankSetup getDDRankSetup(const gmx::MDLogger& mdlog, { GMX_LOG(mdlog.info) .appendTextFormatted("Domain decomposition grid %d x %d x %d, separate PME ranks %d", - ddGridSetup.numDomains[XX], ddGridSetup.numDomains[YY], - ddGridSetup.numDomains[ZZ], ddGridSetup.numPmeOnlyRanks); + ddGridSetup.numDomains[XX], + ddGridSetup.numDomains[YY], + ddGridSetup.numDomains[ZZ], + ddGridSetup.numPmeOnlyRanks); DDRankSetup ddRankSetup; @@ -2370,7 +2413,9 @@ static DDRankSetup getDDRankSetup(const gmx::MDLogger& mdlog, } GMX_LOG(mdlog.info) .appendTextFormatted("PME domain decomposition: %d x %d x %d", - ddRankSetup.npmenodes_x, ddRankSetup.npmenodes_y, 1); + ddRankSetup.npmenodes_x, + ddRankSetup.npmenodes_y, + 1); } else { @@ -2423,8 +2468,7 @@ static void set_dd_limits(const gmx::MDLogger& mdlog, */ const int homeAtomCountEstimate = mtop->natoms / numPPRanks; comm->updateGroupsCog = std::make_unique( - *mtop, systemInfo.updateGroupingPerMoleculetype, maxReferenceTemperature(*ir), - homeAtomCountEstimate); + *mtop, systemInfo.updateGroupingPerMoleculetype, maxReferenceTemperature(*ir), homeAtomCountEstimate); } /* Set the DD setup given by ddGridSetup */ @@ -2490,7 +2534,8 @@ static void set_dd_limits(const gmx::MDLogger& mdlog, fprintf(debug, "Bonded atom communication beyond the cut-off: %s\n" "cellsize limit %f\n", - gmx::boolToString(systemInfo.filterBondedCommunication), comm->cellsize_limit); + gmx::boolToString(systemInfo.filterBondedCommunication), + comm->cellsize_limit); } if (ddRole == DDRole::Master) @@ -2609,8 +2654,8 @@ static void writeSettings(gmx::TextWriter* log, log->writeLineFormatted("The maximum allowed distance for %s involved in interactions is:", decompUnits.c_str()); - log->writeLineFormatted("%40s %-7s %6.3f nm", "non-bonded interactions", "", - comm->systemInfo.cutoff); + log->writeLineFormatted( + "%40s %-7s %6.3f nm", "non-bonded interactions", "", comm->systemInfo.cutoff); if (bDynLoadBal) { @@ -2633,9 +2678,12 @@ static void writeSettings(gmx::TextWriter* log, if (comm->systemInfo.haveInterDomainBondeds) { - log->writeLineFormatted("%40s %-7s %6.3f nm", "two-body bonded interactions", "(-rdd)", + log->writeLineFormatted("%40s %-7s %6.3f nm", + "two-body bonded interactions", + "(-rdd)", std::max(comm->systemInfo.cutoff, comm->cutoff_mbody)); - log->writeLineFormatted("%40s %-7s %6.3f nm", "multi-body bonded interactions", + log->writeLineFormatted("%40s %-7s %6.3f nm", + "multi-body bonded interactions", "(-rdd)", (comm->systemInfo.filterBondedCommunication || isDlbOn(dd->comm)) ? comm->cutoff_mbody @@ -2820,7 +2868,9 @@ static void set_ddgrid_parameters(const gmx::MDLogger& mdlog, ddRankSetup.numRanksDoingPme = 0; if (dd->pme_nodeid >= 0) { - gmx_fatal_collective(FARGS, dd->mpi_comm_all, DDMASTER(dd), + gmx_fatal_collective(FARGS, + dd->mpi_comm_all, + DDMASTER(dd), "Can not have separate PME ranks without PME electrostatics"); } } @@ -2892,8 +2942,8 @@ static DDSettings getDDSettings(const gmx::MDLogger& mdlog, ddSettings.recordLoad = (wallcycle_have_counter() && recload > 0); } - ddSettings.initialDlbState = determineInitialDlbState(mdlog, options.dlbOption, - ddSettings.recordLoad, mdrunOptions, &ir); + ddSettings.initialDlbState = determineInitialDlbState( + mdlog, options.dlbOption, ddSettings.recordLoad, mdrunOptions, &ir); GMX_LOG(mdlog.info) .appendTextFormatted("Dynamic load balancing: %s", edlbs_names[static_cast(ddSettings.initialDlbState)]); @@ -2984,35 +3034,59 @@ DomainDecompositionBuilder::Impl::Impl(const MDLogger& mdlog, srand(1 + cr_->rankInDefaultCommunicator); } - systemInfo_ = getSystemInfo(mdlog_, MASTER(cr_) ? DDRole::Master : DDRole::Agent, - cr->mpiDefaultCommunicator, options_, mtop_, ir_, box, xGlobal); + systemInfo_ = getSystemInfo(mdlog_, + MASTER(cr_) ? DDRole::Master : DDRole::Agent, + cr->mpiDefaultCommunicator, + options_, + mtop_, + ir_, + box, + xGlobal); const int numRanksRequested = cr_->sizeOfDefaultCommunicator; const bool checkForLargePrimeFactors = (options_.numCells[0] <= 0); - checkForValidRankCountRequests(numRanksRequested, EEL_PME(ir_.coulombtype), - options_.numPmeRanks, checkForLargePrimeFactors); + checkForValidRankCountRequests( + numRanksRequested, EEL_PME(ir_.coulombtype), options_.numPmeRanks, checkForLargePrimeFactors); // DD grid setup uses a more different cell size limit for // automated setup than the one in systemInfo_. The latter is used // in set_dd_limits() to configure DLB, for example. const real gridSetupCellsizeLimit = - getDDGridSetupCellSizeLimit(mdlog_, !isDlbDisabled(ddSettings_.initialDlbState), - options_.dlbScaling, ir_, systemInfo_.cellsizeLimit); - ddGridSetup_ = - getDDGridSetup(mdlog_, MASTER(cr_) ? DDRole::Master : DDRole::Agent, - cr->mpiDefaultCommunicator, numRanksRequested, options_, ddSettings_, - systemInfo_, gridSetupCellsizeLimit, mtop_, ir_, box, xGlobal, &ddbox_); - checkDDGridSetup(ddGridSetup_, MASTER(cr_) ? DDRole::Master : DDRole::Agent, - cr->mpiDefaultCommunicator, cr->sizeOfDefaultCommunicator, options_, - ddSettings_, systemInfo_, gridSetupCellsizeLimit, ddbox_); + getDDGridSetupCellSizeLimit(mdlog_, + !isDlbDisabled(ddSettings_.initialDlbState), + options_.dlbScaling, + ir_, + systemInfo_.cellsizeLimit); + ddGridSetup_ = getDDGridSetup(mdlog_, + MASTER(cr_) ? DDRole::Master : DDRole::Agent, + cr->mpiDefaultCommunicator, + numRanksRequested, + options_, + ddSettings_, + systemInfo_, + gridSetupCellsizeLimit, + mtop_, + ir_, + box, + xGlobal, + &ddbox_); + checkDDGridSetup(ddGridSetup_, + MASTER(cr_) ? DDRole::Master : DDRole::Agent, + cr->mpiDefaultCommunicator, + cr->sizeOfDefaultCommunicator, + options_, + ddSettings_, + systemInfo_, + gridSetupCellsizeLimit, + ddbox_); cr_->npmenodes = ddGridSetup_.numPmeOnlyRanks; ddRankSetup_ = getDDRankSetup(mdlog_, cr_->sizeOfDefaultCommunicator, ddGridSetup_, ir_); /* Generate the group communicator, also decides the duty of each rank */ - cartSetup_ = makeGroupCommunicators(mdlog_, ddSettings_, options_.rankOrder, ddRankSetup_, cr_, - ddCellIndex_, &pmeRanks_); + cartSetup_ = makeGroupCommunicators( + mdlog_, ddSettings_, options_.rankOrder, ddRankSetup_, cr_, ddCellIndex_, &pmeRanks_); } gmx_domdec_t* DomainDecompositionBuilder::Impl::build(LocalAtomSetManager* atomSets) @@ -3026,8 +3100,17 @@ gmx_domdec_t* DomainDecompositionBuilder::Impl::build(LocalAtomSetManager* atomS dd->comm->ddRankSetup = ddRankSetup_; dd->comm->cartesianRankSetup = cartSetup_; - set_dd_limits(mdlog_, MASTER(cr_) ? DDRole::Master : DDRole::Agent, dd, options_, ddSettings_, - systemInfo_, ddGridSetup_, ddRankSetup_.numPPRanks, &mtop_, &ir_, ddbox_); + set_dd_limits(mdlog_, + MASTER(cr_) ? DDRole::Master : DDRole::Agent, + dd, + options_, + ddSettings_, + systemInfo_, + ddGridSetup_, + ddRankSetup_.numPPRanks, + &mtop_, + &ir_, + ddbox_); setupGroupCommunication(mdlog_, ddSettings_, pmeRanks_, cr_, mtop_.natoms, dd); @@ -3174,9 +3257,14 @@ void constructGpuHaloExchange(const gmx::MDLogger& mdlog, for (int pulse = cr.dd->gpuHaloExchange[d].size(); pulse < cr.dd->comm->cd[d].numPulses(); pulse++) { cr.dd->gpuHaloExchange[d].push_back(std::make_unique( - cr.dd, d, cr.mpi_comm_mysim, deviceStreamManager.context(), + cr.dd, + d, + cr.mpi_comm_mysim, + deviceStreamManager.context(), deviceStreamManager.stream(gmx::DeviceStreamType::NonBondedLocal), - deviceStreamManager.stream(gmx::DeviceStreamType::NonBondedNonLocal), pulse, wcycle)); + deviceStreamManager.stream(gmx::DeviceStreamType::NonBondedNonLocal), + pulse, + wcycle)); } } } diff --git a/src/gromacs/domdec/domdec_constraints.cpp b/src/gromacs/domdec/domdec_constraints.cpp index b11ef6bdb3..306db7ea39 100644 --- a/src/gromacs/domdec/domdec_constraints.cpp +++ b/src/gromacs/domdec/domdec_constraints.cpp @@ -111,8 +111,8 @@ void dd_move_x_constraints(gmx_domdec_t* dd, { if (dd->constraint_comm) { - dd_move_x_specat(dd, dd->constraint_comm, box, as_rvec_array(x0.data()), - as_rvec_array(x1.data()), bX1IsCoord); + dd_move_x_specat( + dd, dd->constraint_comm, box, as_rvec_array(x0.data()), as_rvec_array(x1.data()), bX1IsCoord); ddReopenBalanceRegionCpu(dd); } @@ -221,8 +221,7 @@ static void walk_out(int con, } if (!ga2la.findHome(offset + b)) { - walk_out(coni, con_offset, b, offset, nrec - 1, ia1, ia2, at2con, ga2la, FALSE, - dc, dcc, il_local, ireq); + walk_out(coni, con_offset, b, offset, nrec - 1, ia1, ia2, at2con, ga2la, FALSE, dc, dcc, il_local, ireq); } } } @@ -383,8 +382,7 @@ static void atoms_to_constraints(gmx_domdec_t* dd, * Therefore we call walk_out with nrec recursions to go * after this first call. */ - walk_out(con, con_offset, b_mol, offset, nrec, ia1, ia2, at2con, ga2la, TRUE, - dc, dcc, ilc_local, ireq); + walk_out(con, con_offset, b_mol, offset, nrec, ia1, ia2, at2con, ga2la, TRUE, dc, dcc, ilc_local, ireq); } } } @@ -397,7 +395,10 @@ static void atoms_to_constraints(gmx_domdec_t* dd, if (debug) { - fprintf(debug, "Constraints: home %3d border %3d atoms: %3zu\n", nhome, dc->ncon - nhome, + fprintf(debug, + "Constraints: home %3d border %3d atoms: %3zu\n", + nhome, + dc->ncon - nhome, dd->constraint_comm ? ireq->size() : 0); } } @@ -536,8 +537,14 @@ int dd_make_local_constraints(gmx_domdec_t* dd, { int nral1; - at_end = setup_specat_communication(dd, ireq, dd->constraint_comm, dd->constraints->ga2la.get(), - at_start, 2, "constraint", " or lincs-order"); + at_end = setup_specat_communication(dd, + ireq, + dd->constraint_comm, + dd->constraints->ga2la.get(), + at_start, + 2, + "constraint", + " or lincs-order"); /* Fill in the missing indices */ ga2la_specat = dd->constraints->ga2la.get(); diff --git a/src/gromacs/domdec/domdec_network.cpp b/src/gromacs/domdec/domdec_network.cpp index 9bc3b99344..0a97f0a04b 100644 --- a/src/gromacs/domdec/domdec_network.cpp +++ b/src/gromacs/domdec/domdec_network.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2008-2019, by the GROMACS development team, led by + * Copyright (c) 2008-2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -83,9 +83,18 @@ void ddSendrecv(const struct gmx_domdec_t* dd, MPI_Status mpiStatus; if (numElementsToSend > 0 && numElementsToReceive > 0) { - MPI_Sendrecv(sendBuffer, numElementsToSend * sizeof(T), MPI_BYTE, sendRank, mpiTag, - receiveBuffer, numElementsToReceive * sizeof(T), MPI_BYTE, receiveRank, mpiTag, - dd->mpi_comm_all, &mpiStatus); + MPI_Sendrecv(sendBuffer, + numElementsToSend * sizeof(T), + MPI_BYTE, + sendRank, + mpiTag, + receiveBuffer, + numElementsToReceive * sizeof(T), + MPI_BYTE, + receiveRank, + mpiTag, + dd->mpi_comm_all, + &mpiStatus); } else if (numElementsToSend > 0) { @@ -93,8 +102,7 @@ void ddSendrecv(const struct gmx_domdec_t* dd, } else if (numElementsToReceive > 0) { - MPI_Recv(receiveBuffer, numElementsToReceive * sizeof(T), MPI_BYTE, receiveRank, mpiTag, - dd->mpi_comm_all, &mpiStatus); + MPI_Recv(receiveBuffer, numElementsToReceive * sizeof(T), MPI_BYTE, receiveRank, mpiTag, dd->mpi_comm_all, &mpiStatus); } #else // GMX_MPI GMX_UNUSED_VALUE(dd); @@ -121,8 +129,13 @@ void ddSendrecv(const gmx_domdec_t* dd, gmx::ArrayRef sendBuffer, gmx::ArrayRef receiveBuffer) { - ddSendrecv(dd, ddDimensionIndex, direction, sendBuffer.data(), sendBuffer.size(), - receiveBuffer.data(), receiveBuffer.size()); + ddSendrecv(dd, + ddDimensionIndex, + direction, + sendBuffer.data(), + sendBuffer.size(), + receiveBuffer.data(), + receiveBuffer.size()); } //! Specialization of extern template for int @@ -164,23 +177,19 @@ void dd_sendrecv2_rvec(const struct gmx_domdec_t gmx_unused* dd, nreq = 0; if (n_r_fw) { - MPI_Irecv(buf_r_fw[0], n_r_fw * sizeof(rvec), MPI_BYTE, rank_bw, 0, dd->mpi_comm_all, - &req[nreq++]); + MPI_Irecv(buf_r_fw[0], n_r_fw * sizeof(rvec), MPI_BYTE, rank_bw, 0, dd->mpi_comm_all, &req[nreq++]); } if (n_r_bw) { - MPI_Irecv(buf_r_bw[0], n_r_bw * sizeof(rvec), MPI_BYTE, rank_fw, 1, dd->mpi_comm_all, - &req[nreq++]); + MPI_Irecv(buf_r_bw[0], n_r_bw * sizeof(rvec), MPI_BYTE, rank_fw, 1, dd->mpi_comm_all, &req[nreq++]); } if (n_s_fw) { - MPI_Isend(buf_s_fw[0], n_s_fw * sizeof(rvec), MPI_BYTE, rank_fw, 0, dd->mpi_comm_all, - &req[nreq++]); + MPI_Isend(buf_s_fw[0], n_s_fw * sizeof(rvec), MPI_BYTE, rank_fw, 0, dd->mpi_comm_all, &req[nreq++]); } if (n_s_bw) { - MPI_Isend(buf_s_bw[0], n_s_bw * sizeof(rvec), MPI_BYTE, rank_bw, 1, dd->mpi_comm_all, - &req[nreq++]); + MPI_Isend(buf_s_bw[0], n_s_bw * sizeof(rvec), MPI_BYTE, rank_bw, 1, dd->mpi_comm_all, &req[nreq++]); } if (nreq) { @@ -194,11 +203,31 @@ void dd_sendrecv2_rvec(const struct gmx_domdec_t gmx_unused* dd, * with a single full-duplex network connection per machine. */ /* Forward */ - MPI_Sendrecv(buf_s_fw[0], n_s_fw * sizeof(rvec), MPI_BYTE, rank_fw, 0, buf_r_fw[0], - n_r_fw * sizeof(rvec), MPI_BYTE, rank_bw, 0, dd->mpi_comm_all, &stat[0]); + MPI_Sendrecv(buf_s_fw[0], + n_s_fw * sizeof(rvec), + MPI_BYTE, + rank_fw, + 0, + buf_r_fw[0], + n_r_fw * sizeof(rvec), + MPI_BYTE, + rank_bw, + 0, + dd->mpi_comm_all, + &stat[0]); /* Backward */ - MPI_Sendrecv(buf_s_bw[0], n_s_bw * sizeof(rvec), MPI_BYTE, rank_bw, 0, buf_r_bw[0], - n_r_bw * sizeof(rvec), MPI_BYTE, rank_fw, 0, dd->mpi_comm_all, &stat[0]); + MPI_Sendrecv(buf_s_bw[0], + n_s_bw * sizeof(rvec), + MPI_BYTE, + rank_bw, + 0, + buf_r_bw[0], + n_r_bw * sizeof(rvec), + MPI_BYTE, + rank_fw, + 0, + dd->mpi_comm_all, + &stat[0]); } #endif } @@ -233,8 +262,7 @@ void dd_scatter(const gmx_domdec_t gmx_unused* dd, int gmx_unused nbytes, const if (dd->nnodes > 1) { /* Some MPI implementions don't specify const */ - MPI_Scatter(const_cast(src), nbytes, MPI_BYTE, dest, nbytes, MPI_BYTE, - DDMASTERRANK(dd), dd->mpi_comm_all); + MPI_Scatter(const_cast(src), nbytes, MPI_BYTE, dest, nbytes, MPI_BYTE, DDMASTERRANK(dd), dd->mpi_comm_all); } else #endif @@ -254,8 +282,7 @@ void dd_gather(const gmx_domdec_t gmx_unused* dd, { #if GMX_MPI /* Some MPI implementions don't specify const */ - MPI_Gather(const_cast(src), nbytes, MPI_BYTE, dest, nbytes, MPI_BYTE, DDMASTERRANK(dd), - dd->mpi_comm_all); + MPI_Gather(const_cast(src), nbytes, MPI_BYTE, dest, nbytes, MPI_BYTE, DDMASTERRANK(dd), dd->mpi_comm_all); #endif } @@ -277,8 +304,8 @@ void dd_scatterv(const gmx_domdec_t gmx_unused* dd, rbuf = &dum; } /* Some MPI implementions don't specify const */ - MPI_Scatterv(const_cast(sbuf), scounts, disps, MPI_BYTE, rbuf, rcount, MPI_BYTE, - DDMASTERRANK(dd), dd->mpi_comm_all); + MPI_Scatterv( + const_cast(sbuf), scounts, disps, MPI_BYTE, rbuf, rcount, MPI_BYTE, DDMASTERRANK(dd), dd->mpi_comm_all); } else #endif @@ -307,7 +334,7 @@ void dd_gatherv(const gmx_domdec_t gmx_unused* dd, sbuf = &dum; } /* Some MPI implementions don't specify const */ - MPI_Gatherv(const_cast(sbuf), scount, MPI_BYTE, rbuf, rcounts, disps, MPI_BYTE, - DDMASTERRANK(dd), dd->mpi_comm_all); + MPI_Gatherv( + const_cast(sbuf), scount, MPI_BYTE, rbuf, rcounts, disps, MPI_BYTE, DDMASTERRANK(dd), dd->mpi_comm_all); #endif } diff --git a/src/gromacs/domdec/domdec_setup.cpp b/src/gromacs/domdec/domdec_setup.cpp index 1b058becc5..7b8d329b4a 100644 --- a/src/gromacs/domdec/domdec_setup.cpp +++ b/src/gromacs/domdec/domdec_setup.cpp @@ -253,7 +253,11 @@ static int guess_npme(const gmx::MDLogger& mdlog, "grid_y=%d).\n" "Use the -npme option of mdrun or change the number of ranks or the PME grid " "dimensions, see the manual for details.", - ratio, gmx::roundToInt(0.95 * ratio * nrank_tot), nrank_tot / 2, ir.nkx, ir.nky); + ratio, + gmx::roundToInt(0.95 * ratio * nrank_tot), + nrank_tot / 2, + ir.nkx, + ir.nky); } else { @@ -261,7 +265,8 @@ static int guess_npme(const gmx::MDLogger& mdlog, .appendTextFormatted( "Will use %d particle-particle and %d PME only ranks\n" "This is a guess, check the performance at the end of the log file", - nrank_tot - npme, npme); + nrank_tot - npme, + npme); } return npme; @@ -446,8 +451,8 @@ static float comm_cost_est(real limit, */ bool useThreads = true; bool errorsAreFatal = false; - if (!gmx_pme_check_restrictions(ir.pme_order, ir.nkx, ir.nky, ir.nkz, npme_x, useThreads, - errorsAreFatal)) + if (!gmx_pme_check_restrictions( + ir.pme_order, ir.nkx, ir.nky, ir.nkz, npme_x, useThreads, errorsAreFatal)) { return -1; } @@ -542,9 +547,17 @@ static float comm_cost_est(real limit, if (debug) { - fprintf(debug, "nc %2d %2d %2d %2d %2d vol pp %6.4f pbcdx %6.4f pme %9.3e tot %9.3e\n", - nc[XX], nc[YY], nc[ZZ], npme[XX], npme[YY], comm_vol, cost_pbcdx, - comm_pme / (3 * natoms), comm_vol + cost_pbcdx + comm_pme / (3 * natoms)); + fprintf(debug, + "nc %2d %2d %2d %2d %2d vol pp %6.4f pbcdx %6.4f pme %9.3e tot %9.3e\n", + nc[XX], + nc[YY], + nc[ZZ], + npme[XX], + npme[YY], + comm_vol, + cost_pbcdx, + comm_pme / (3 * natoms), + comm_vol + cost_pbcdx + comm_pme / (3 * natoms)); } return 3 * natoms * (comm_vol + cost_pbcdx) + comm_pme; @@ -602,8 +615,8 @@ static void assign_factors(const real limit, } /* recurse */ - assign_factors(limit, cutoff, box, ddbox, natoms, ir, pbcdxr, npme, ndiv - 1, div + 1, - mdiv + 1, irTryPtr, opt); + assign_factors( + limit, cutoff, box, ddbox, natoms, ir, pbcdxr, npme, ndiv - 1, div + 1, mdiv + 1, irTryPtr, opt); for (i = 0; i < mdiv[0] - x - y; i++) { @@ -643,7 +656,8 @@ static gmx::IVec optimizeDDCells(const gmx::MDLogger& mdlog, GMX_LOG(mdlog.info) .appendTextFormatted( "Optimizing the DD grid for %d cells with a minimum initial size of %.3f nm", - numPPRanks, cellSizeLimit); + numPPRanks, + cellSizeLimit); if (inhomogeneous_z(ir)) { GMX_LOG(mdlog.info) @@ -706,8 +720,19 @@ static gmx::IVec optimizeDDCells(const gmx::MDLogger& mdlog, gmx::IVec itry = { 1, 1, 1 }; gmx::IVec numDomains = { 0, 0, 0 }; - assign_factors(cellSizeLimit, systemInfo.cutoff, box, ddbox, mtop.natoms, ir, pbcdxr, - numRanksDoingPmeWork, div.size(), div.data(), mdiv.data(), &itry, &numDomains); + assign_factors(cellSizeLimit, + systemInfo.cutoff, + box, + ddbox, + mtop.natoms, + ir, + pbcdxr, + numRanksDoingPmeWork, + div.size(), + div.data(), + mdiv.data(), + &itry, + &numDomains); return numDomains; } @@ -729,8 +754,7 @@ real getDDGridSetupCellSizeLimit(const gmx::MDLogger& mdlog, } GMX_LOG(mdlog.info) .appendTextFormatted( - "Scaling the initial minimum size with 1/%g (option -dds) = %g", dlb_scale, - 1 / dlb_scale); + "Scaling the initial minimum size with 1/%g (option -dds) = %g", dlb_scale, 1 / dlb_scale); cellSizeLimit /= dlb_scale; } else if (ir.epc != epcNO) @@ -758,7 +782,8 @@ void checkForValidRankCountRequests(const int numRanksRequested, gmx_fatal(FARGS, "Cannot have %d separate PME ranks with only %d PP ranks, choose fewer or no " "separate PME ranks", - numPmeRanksRequested, numPPRanksRequested); + numPmeRanksRequested, + numPPRanksRequested); } } @@ -776,7 +801,8 @@ void checkForValidRankCountRequests(const int numRanksRequested, "contains a large prime factor %d. In most cases this will lead to " "bad performance. Choose a number with smaller prime factors or " "set the decomposition (option -dd) manually.", - numPPRanksRequested, largestDivisor); + numPPRanksRequested, + largestDivisor); } } } @@ -917,8 +943,8 @@ DDGridSetup getDDGridSetup(const gmx::MDLogger& mdlog, if (ddRole == DDRole::Master) { - numDomains = optimizeDDCells(mdlog, numRanksRequested, numPmeOnlyRanks, cellSizeLimit, - mtop, box, *ddbox, ir, systemInfo); + numDomains = optimizeDDCells( + mdlog, numRanksRequested, numPmeOnlyRanks, cellSizeLimit, mtop, box, *ddbox, ir, systemInfo); } } diff --git a/src/gromacs/domdec/domdec_specatomcomm.cpp b/src/gromacs/domdec/domdec_specatomcomm.cpp index 2c543a0343..89ac9df3f8 100644 --- a/src/gromacs/domdec/domdec_specatomcomm.cpp +++ b/src/gromacs/domdec/domdec_specatomcomm.cpp @@ -87,8 +87,16 @@ void dd_move_f_specat(const gmx_domdec_t* dd, gmx_domdec_specat_comm_t* spac, rv n -= n1 + n0; vbuf = as_rvec_array(spac->vbuf.data()); /* Send and receive the coordinates */ - dd_sendrecv2_rvec(dd, d, f + n + n1, n0, vbuf, spas[0].a.size(), f + n, n1, - vbuf + spas[0].a.size(), spas[1].a.size()); + dd_sendrecv2_rvec(dd, + d, + f + n + n1, + n0, + vbuf, + spas[0].a.size(), + f + n, + n1, + vbuf + spas[0].a.size(), + spas[1].a.size()); for (dir = 0; dir < 2; dir++) { bPBC = ((dir == 0 && dd->ci[dim] == 0) @@ -144,8 +152,7 @@ void dd_move_f_specat(const gmx_domdec_t* dd, gmx_domdec_specat_comm_t* spac, rv spas = &spac->spas[d][0]; n -= spas->nrecv; /* Send and receive the coordinates */ - ddSendrecv(dd, d, dddirForward, f + n, spas->nrecv, as_rvec_array(spac->vbuf.data()), - spas->a.size()); + ddSendrecv(dd, d, dddirForward, f + n, spas->nrecv, as_rvec_array(spac->vbuf.data()), spas->a.size()); /* Sum the buffer into the required forces */ if (dd->unitCellInfo.haveScrewPBC && dim == XX && (dd->ci[dim] == 0 || dd->ci[dim] == dd->numCells[dim] - 1)) @@ -273,8 +280,8 @@ void dd_move_x_specat(const gmx_domdec_t* dd, rvec* vbuf = as_rvec_array(spac->vbuf.data()); /* Communicate both vectors in one buffer */ rvec* rbuf = as_rvec_array(spac->vbuf2.data()); - dd_sendrecv2_rvec(dd, d, vbuf + 2 * ns0, 2 * ns1, rbuf, 2 * nr1, vbuf, 2 * ns0, - rbuf + 2 * nr1, 2 * nr0); + dd_sendrecv2_rvec( + dd, d, vbuf + 2 * ns0, 2 * ns1, rbuf, 2 * nr1, vbuf, 2 * ns0, rbuf + 2 * nr1, 2 * nr0); /* Split the buffer into the two vectors */ nn = n; for (dir = 1; dir >= 0; dir--) @@ -409,13 +416,17 @@ int setup_specat_communication(gmx_domdec_t* dd, nsend_ptr = nsend; } /* Communicate the number of indices */ - ddSendrecv(dd, d, dir == 0 ? dddirForward : dddirBackward, nsend_ptr, 2, - spac->nreq[d][dir], 2); + ddSendrecv(dd, d, dir == 0 ? dddirForward : dddirBackward, nsend_ptr, 2, spac->nreq[d][dir], 2); nr = spac->nreq[d][dir][1]; ireq->resize(nlast + nr); /* Communicate the indices */ - ddSendrecv(dd, d, dir == 0 ? dddirForward : dddirBackward, ireq->data(), nsend_ptr[1], - ireq->data() + nlast, nr); + ddSendrecv(dd, + d, + dir == 0 ? dddirForward : dddirBackward, + ireq->data(), + nsend_ptr[1], + ireq->data() + nlast, + nr); nlast += nr; } nsend[1] = nlast; @@ -512,7 +523,11 @@ int setup_specat_communication(gmx_domdec_t* dd, fprintf(debug, "Send to rank %d, %d (%d) indices, " "receive from rank %d, %d (%d) indices\n", - dd->neighbor[d][1 - dir], nsend[1], nsend[0], dd->neighbor[d][dir], buf[1], + dd->neighbor[d][1 - dir], + nsend[1], + nsend[0], + dd->neighbor[d][dir], + buf[1], buf[0]); if (gmx_debug_at) { @@ -527,8 +542,13 @@ int setup_specat_communication(gmx_domdec_t* dd, spas->nrecv = buf[1]; dd->globalAtomIndices.resize(nat_tot_specat + spas->nrecv); /* Send and receive the indices */ - ddSendrecv(dd, d, dir == 0 ? dddirBackward : dddirForward, spac->ibuf.data(), - spac->ibuf.size(), dd->globalAtomIndices.data() + nat_tot_specat, spas->nrecv); + ddSendrecv(dd, + d, + dir == 0 ? dddirBackward : dddirForward, + spac->ibuf.data(), + spac->ibuf.size(), + dd->globalAtomIndices.data() + nat_tot_specat, + spas->nrecv); nat_tot_specat += spas->nrecv; } @@ -561,7 +581,10 @@ int setup_specat_communication(gmx_domdec_t* dd, { if (debug) { - fprintf(debug, "Requested %d, received %d (tot recv %d)\n", numRequested, nrecv_local, + fprintf(debug, + "Requested %d, received %d (tot recv %d)\n", + numRequested, + nrecv_local, nat_tot_specat - at_start); if (gmx_debug_at) { @@ -573,8 +596,11 @@ int setup_specat_communication(gmx_domdec_t* dd, fprintf(debug, "\n"); } } - fprintf(stderr, "\nDD cell %d %d %d: Neighboring cells do not have atoms:", dd->ci[XX], - dd->ci[YY], dd->ci[ZZ]); + fprintf(stderr, + "\nDD cell %d %d %d: Neighboring cells do not have atoms:", + dd->ci[XX], + dd->ci[YY], + dd->ci[ZZ]); for (int i = 0; i < numRequested; i++) { if (!ga2la_specat->find((*ireq)[i])) @@ -588,8 +614,15 @@ int setup_specat_communication(gmx_domdec_t* dd, "%ss from the neighboring cells. This probably means your %s lengths are too " "long compared to the domain decomposition cell size. Decrease the number of " "domain decomposition grid cells%s%s.", - dd->ci[XX], dd->ci[YY], dd->ci[ZZ], nrecv_local, numRequested, specat_type, - specat_type, add_err, dd_dlb_is_on(dd) ? " or use the -rcon option of mdrun" : ""); + dd->ci[XX], + dd->ci[YY], + dd->ci[ZZ], + nrecv_local, + numRequested, + specat_type, + specat_type, + add_err, + dd_dlb_is_on(dd) ? " or use the -rcon option of mdrun" : ""); } spac->at_start = at_start; diff --git a/src/gromacs/domdec/domdec_topology.cpp b/src/gromacs/domdec/domdec_topology.cpp index 59815003f1..ad10295ed8 100644 --- a/src/gromacs/domdec/domdec_topology.cpp +++ b/src/gromacs/domdec/domdec_topology.cpp @@ -277,8 +277,8 @@ static std::string printMissingInteractionsMolblock(t_commrec* cr, { if (dd_check_ftype(ftype, rt.bBCheck, rt.bConstr, rt.bSettle)) { - flagInteractionsForType(ftype, idef.il[ftype], ril, atomRange, numAtomsPerMolecule, - cr->dd->globalAtomIndices, isAssigned); + flagInteractionsForType( + ftype, idef.il[ftype], ril, atomRange, numAtomsPerMolecule, cr->dd->globalAtomIndices, isAssigned); } } @@ -319,8 +319,9 @@ static std::string printMissingInteractionsMolblock(t_commrec* cr, log.writeString(" global"); for (a = 0; a < nral; a++) { - log.writeStringFormatted("%6d", atomRange.begin() + mol * numAtomsPerMolecule - + ril.il[j_mol + 2 + a] + 1); + log.writeStringFormatted("%6d", + atomRange.begin() + mol * numAtomsPerMolecule + + ril.il[j_mol + 2 + a] + 1); } log.ensureLineBreak(); } @@ -354,8 +355,8 @@ static void printMissingInteractionsAtoms(const gmx::MDLogger& mdlog, a_end = a_start + molb.nmol * moltype.atoms.nr; const gmx::Range atomRange(a_start, a_end); - auto warning = printMissingInteractionsMolblock(cr, rt, *(moltype.name), rt.ril_mt[molb.type], - atomRange, moltype.atoms.nr, molb.nmol, idef); + auto warning = printMissingInteractionsMolblock( + cr, rt, *(moltype.name), rt.ril_mt[molb.type], atomRange, moltype.atoms.nr, molb.nmol, idef); GMX_LOG(mdlog.warning).appendText(warning); } @@ -416,7 +417,9 @@ void dd_print_missing_interactions(const gmx::MDLogger& mdlog, { GMX_LOG(mdlog.warning) .appendTextFormatted("%20s of %6d missing %6d", - interaction_function[ftype].longname, n, -ndiff); + interaction_function[ftype].longname, + n, + -ndiff); } rest_global -= n; rest_local -= cl[ftype]; @@ -448,7 +451,10 @@ void dd_print_missing_interactions(const gmx::MDLogger& mdlog, "involved moved further apart than the multi-body cut-off distance (%g nm) or the " "two-body cut-off distance (%g nm), see option -rdd, for pairs and tabulated bonds " "also see option -ddcheck", - -ndiff_tot, cr->dd->nbonded_global, dd_cutoff_multibody(dd), dd_cutoff_twobody(dd)); + -ndiff_tot, + cr->dd->nbonded_global, + dd_cutoff_multibody(dd), + dd_cutoff_twobody(dd)); } gmx_fatal_collective(FARGS, cr->mpi_comm_mygroup, MASTER(cr), "%s", errorMessage.c_str()); } @@ -617,8 +623,8 @@ static int make_reverse_ilist(const InteractionLists& ilist, /* Count the interactions */ nat_mt = atoms->nr; snew(count, nat_mt); - low_make_reverse_ilist(ilist, atoms->atom, count, bConstr, bSettle, bBCheck, {}, {}, - bLinkToAllAtoms, FALSE); + low_make_reverse_ilist( + ilist, atoms->atom, count, bConstr, bSettle, bBCheck, {}, {}, bLinkToAllAtoms, FALSE); ril_mt->index.push_back(0); for (i = 0; i < nat_mt; i++) @@ -629,8 +635,8 @@ static int make_reverse_ilist(const InteractionLists& ilist, ril_mt->il.resize(ril_mt->index[nat_mt]); /* Store the interactions */ - nint_mt = low_make_reverse_ilist(ilist, atoms->atom, count, bConstr, bSettle, bBCheck, - ril_mt->index, ril_mt->il, bLinkToAllAtoms, TRUE); + nint_mt = low_make_reverse_ilist( + ilist, atoms->atom, count, bConstr, bSettle, bBCheck, ril_mt->index, ril_mt->il, bLinkToAllAtoms, TRUE); sfree(count); @@ -675,8 +681,7 @@ static gmx_reverse_top_t make_reverse_top(const gmx_mtop_t* mtop, } if (debug) { - fprintf(debug, "The total size of the atom to interaction index is %d integers\n", - rt.ril_mt_tot_size); + fprintf(debug, "The total size of the atom to interaction index is %d integers\n", rt.ril_mt_tot_size); } *nint = 0; @@ -697,8 +702,8 @@ static gmx_reverse_top_t make_reverse_top(const gmx_mtop_t* mtop, GMX_RELEASE_ASSERT(mtop->intermolecular_ilist, "We should have an ilist when intermolecular interactions are on"); - *nint += make_reverse_ilist(*mtop->intermolecular_ilist, &atoms_global, rt.bConstr, - rt.bSettle, rt.bBCheck, FALSE, &rt.ril_intermol); + *nint += make_reverse_ilist( + *mtop->intermolecular_ilist, &atoms_global, rt.bConstr, rt.bSettle, rt.bBCheck, FALSE, &rt.ril_intermol); } if (bFE && gmx_mtop_bondeds_free_energy(mtop)) @@ -751,10 +756,13 @@ void dd_make_reverse_top(FILE* fplog, * the parallel version constraint algorithm(s). */ - dd->reverse_top = new gmx_reverse_top_t; - *dd->reverse_top = - make_reverse_top(mtop, ir->efep != efepNO, !dd->comm->systemInfo.haveSplitConstraints, - !dd->comm->systemInfo.haveSplitSettles, bBCheck, &dd->nbonded_global); + dd->reverse_top = new gmx_reverse_top_t; + *dd->reverse_top = make_reverse_top(mtop, + ir->efep != efepNO, + !dd->comm->systemInfo.haveSplitConstraints, + !dd->comm->systemInfo.haveSplitSettles, + bBCheck, + &dd->nbonded_global); dd->haveExclusions = false; for (const gmx_molblock_t& molb : mtop->molblock) @@ -948,8 +956,10 @@ static void add_vsite(const gmx_ga2la_t& ga2la, /* This construction atoms is a vsite and not a home atom */ if (gmx_debug_at) { - fprintf(debug, "Constructing atom %d of vsite atom %d is a vsite and non-home\n", - iatoms[k] + 1, a_mol + 1); + fprintf(debug, + "Constructing atom %d of vsite atom %d is a vsite and non-home\n", + iatoms[k] + 1, + a_mol + 1); } /* Find the vsite construction */ @@ -962,8 +972,17 @@ static void add_vsite(const gmx_ga2la_t& ga2la, if (interaction_function[ftype_r].flags & IF_VSITE) { /* Add this vsite (recursion) */ - add_vsite(ga2la, index, rtil, ftype_r, nral_r, FALSE, -1, - a_gl + iatoms[k] - iatoms[1], iatoms[k], rtil.data() + j, idef); + add_vsite(ga2la, + index, + rtil, + ftype_r, + nral_r, + FALSE, + -1, + a_gl + iatoms[k] - iatoms[1], + iatoms[k], + rtil.data() + j, + idef); } j += 1 + nral_rt(ftype_r); } @@ -1291,10 +1310,30 @@ static int make_bondeds_zone(gmx_domdec_t* dd, gmx::ArrayRef index = rt->ril_mt[mt].index; gmx::ArrayRef rtil = rt->ril_mt[mt].il; - check_assign_interactions_atom(i, i_gl, mol, i_mol, rt->ril_mt[mt].numAtomsInMolecule, - index, rtil, FALSE, index[i_mol], index[i_mol + 1], dd, - zones, &molb[mb], bRCheckMB, rcheck, bRCheck2B, rc2, - pbc_null, cg_cm, ip_in, idef, izone, bBCheck, &nbonded_local); + check_assign_interactions_atom(i, + i_gl, + mol, + i_mol, + rt->ril_mt[mt].numAtomsInMolecule, + index, + rtil, + FALSE, + index[i_mol], + index[i_mol + 1], + dd, + zones, + &molb[mb], + bRCheckMB, + rcheck, + bRCheck2B, + rc2, + pbc_null, + cg_cm, + ip_in, + idef, + izone, + bBCheck, + &nbonded_local); if (rt->bIntermolecularInteractions) @@ -1303,10 +1342,30 @@ static int make_bondeds_zone(gmx_domdec_t* dd, index = rt->ril_intermol.index; rtil = rt->ril_intermol.il; - check_assign_interactions_atom(i, i_gl, mol, i_mol, rt->ril_mt[mt].numAtomsInMolecule, - index, rtil, TRUE, index[i_gl], index[i_gl + 1], dd, zones, - &molb[mb], bRCheckMB, rcheck, bRCheck2B, rc2, pbc_null, - cg_cm, ip_in, idef, izone, bBCheck, &nbonded_local); + check_assign_interactions_atom(i, + i_gl, + mol, + i_mol, + rt->ril_mt[mt].numAtomsInMolecule, + index, + rtil, + TRUE, + index[i_gl], + index[i_gl + 1], + dd, + zones, + &molb[mb], + bRCheckMB, + rcheck, + bRCheck2B, + rc2, + pbc_null, + cg_cm, + ip_in, + idef, + izone, + bBCheck, + &nbonded_local); } } @@ -1361,7 +1420,8 @@ static void make_exclusions_zone(gmx_domdec_t* dd, bool isExcludedAtom = !intermolecularExclusionGroup.empty() && std::find(intermolecularExclusionGroup.begin(), - intermolecularExclusionGroup.end(), dd->globalAtomIndices[at]) + intermolecularExclusionGroup.end(), + dd->globalAtomIndices[at]) != intermolecularExclusionGroup.end(); if (isExcludedAtom) @@ -1458,9 +1518,19 @@ static int make_local_bondeds_excls(gmx_domdec_t* dd, idef_t->clear(); } - rt->th_work[thread].nbonded = make_bondeds_zone( - dd, zones, mtop->molblock, bRCheckMB, rcheck, bRCheck2B, rc2, pbc_null, - cg_cm, idef->iparams.data(), idef_t, izone, gmx::Range(cg0t, cg1t)); + rt->th_work[thread].nbonded = make_bondeds_zone(dd, + zones, + mtop->molblock, + bRCheckMB, + rcheck, + bRCheck2B, + rc2, + pbc_null, + cg_cm, + idef->iparams.data(), + idef_t, + izone, + gmx::Range(cg0t, cg1t)); if (izone < numIZonesForExclusions) { @@ -1478,8 +1548,8 @@ static int make_local_bondeds_excls(gmx_domdec_t* dd, } /* No charge groups and no distance check required */ - make_exclusions_zone(dd, zones, mtop->moltype, cginfo, excl_t, izone, cg0t, - cg1t, mtop->intermolecularExclusionGroup); + make_exclusions_zone( + dd, zones, mtop->moltype, cginfo, excl_t, izone, cg0t, cg1t, mtop->intermolecularExclusionGroup); } } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR @@ -1573,8 +1643,13 @@ void dd_make_local_top(gmx_domdec_t* dd, } if (debug) { - fprintf(debug, "dim %d cellmin %f bonded rcheck[%d] = %d, bRCheck2B = %s\n", d, - cellsize_min[d], d, rcheck[d], gmx::boolToString(bRCheck2B)); + fprintf(debug, + "dim %d cellmin %f bonded rcheck[%d] = %d, bRCheck2B = %s\n", + d, + cellsize_min[d], + d, + rcheck[d], + gmx::boolToString(bRCheck2B)); } } if (bRCheckMB || bRCheck2B) @@ -1590,9 +1665,19 @@ void dd_make_local_top(gmx_domdec_t* dd, } } - dd->nbonded_local = make_local_bondeds_excls(dd, zones, &mtop, fr->cginfo.data(), bRCheckMB, - rcheck, bRCheck2B, rc, pbc_null, cgcm_or_x, - <op->idef, <op->excls, &nexcl); + dd->nbonded_local = make_local_bondeds_excls(dd, + zones, + &mtop, + fr->cginfo.data(), + bRCheckMB, + rcheck, + bRCheck2B, + rc, + pbc_null, + cgcm_or_x, + <op->idef, + <op->excls, + &nexcl); /* The ilist is not sorted yet, * we can only do this when we have the charge arrays. @@ -1768,8 +1853,11 @@ t_blocka* makeBondedLinks(const gmx_mtop_t& mtop, gmx::ArrayRef cgi if (debug) { - fprintf(debug, "molecule type '%s' %d atoms has %d atom links through bonded interac.\n", - *molt.name, molt.atoms.nr, nlink_mol); + fprintf(debug, + "molecule type '%s' %d atoms has %d atom links through bonded interac.\n", + *molt.name, + molt.atoms.nr, + nlink_mol); } if (molb.nmol > mol) @@ -1855,8 +1943,8 @@ static void bonded_cg_distance_mol(const gmx_moltype_t* molt, { real rij2 = distance2(x[atomI], x[atomJ]); - update_max_bonded_distance(rij2, ftype, atomI, atomJ, - (nral == 2) ? bd_2b : bd_mb); + update_max_bonded_distance( + rij2, ftype, atomI, atomJ, (nral == 2) ? bd_2b : bd_mb); } } } @@ -2025,8 +2113,13 @@ void dd_bonded_cg_distance(const gmx::MDLogger& mdlog, std::vector xs(molt.atoms.nr); for (int mol = 0; mol < molb.nmol; mol++) { - getWholeMoleculeCoordinates(&molt, &mtop->ffparams, ir->pbcType, &graph, box, - x.subArray(at_offset, molt.atoms.nr), xs); + getWholeMoleculeCoordinates(&molt, + &mtop->ffparams, + ir->pbcType, + &graph, + box, + x.subArray(at_offset, molt.atoms.nr), + xs); bonded_distance_t bd_mol_2b = { 0, -1, -1, -1 }; bonded_distance_t bd_mol_mb = { 0, -1, -1, -1 }; @@ -2034,10 +2127,16 @@ void dd_bonded_cg_distance(const gmx::MDLogger& mdlog, bonded_cg_distance_mol(&molt, bBCheck, bExclRequired, xs, &bd_mol_2b, &bd_mol_mb); /* Process the mol data adding the atom index offset */ - update_max_bonded_distance(bd_mol_2b.r2, bd_mol_2b.ftype, at_offset + bd_mol_2b.a1, - at_offset + bd_mol_2b.a2, &bd_2b); - update_max_bonded_distance(bd_mol_mb.r2, bd_mol_mb.ftype, at_offset + bd_mol_mb.a1, - at_offset + bd_mol_mb.a2, &bd_mb); + update_max_bonded_distance(bd_mol_2b.r2, + bd_mol_2b.ftype, + at_offset + bd_mol_2b.a1, + at_offset + bd_mol_2b.a2, + &bd_2b); + update_max_bonded_distance(bd_mol_mb.r2, + bd_mol_mb.ftype, + at_offset + bd_mol_mb.a1, + at_offset + bd_mol_mb.a2, + &bd_mb); at_offset += molt.atoms.nr; } @@ -2062,16 +2161,21 @@ void dd_bonded_cg_distance(const gmx::MDLogger& mdlog, { GMX_LOG(mdlog.info) .appendTextFormatted( - " two-body bonded interactions: %5.3f nm, %s, atoms %d %d", *r_2b, + " two-body bonded interactions: %5.3f nm, %s, atoms %d %d", + *r_2b, (bd_2b.ftype >= 0) ? interaction_function[bd_2b.ftype].longname : "Exclusion", - bd_2b.a1 + 1, bd_2b.a2 + 1); + bd_2b.a1 + 1, + bd_2b.a2 + 1); } if (*r_mb > 0) { GMX_LOG(mdlog.info) .appendTextFormatted( - " multi-body bonded interactions: %5.3f nm, %s, atoms %d %d", *r_mb, - interaction_function[bd_mb.ftype].longname, bd_mb.a1 + 1, bd_mb.a2 + 1); + " multi-body bonded interactions: %5.3f nm, %s, atoms %d %d", + *r_mb, + interaction_function[bd_mb.ftype].longname, + bd_mb.a1 + 1, + bd_mb.a2 + 1); } } } diff --git a/src/gromacs/domdec/domdec_vsite.cpp b/src/gromacs/domdec/domdec_vsite.cpp index 0fe374ee45..cc1880dde5 100644 --- a/src/gromacs/domdec/domdec_vsite.cpp +++ b/src/gromacs/domdec/domdec_vsite.cpp @@ -142,8 +142,8 @@ int dd_make_local_vsites(gmx_domdec_t* dd, int at_start, gmx::ArrayRefvsite_comm, ga2la_specat, at_start, 1, - "vsite", ""); + int at_end = setup_specat_communication( + dd, &ireq, dd->vsite_comm, ga2la_specat, at_start, 1, "vsite", ""); /* Fill in the missing indices */ for (int ftype = 0; ftype < F_NRE; ftype++) diff --git a/src/gromacs/domdec/dump.cpp b/src/gromacs/domdec/dump.cpp index c3f7eaad13..274a998789 100644 --- a/src/gromacs/domdec/dump.cpp +++ b/src/gromacs/domdec/dump.cpp @@ -119,8 +119,21 @@ void write_dd_grid_pdb(const char* fn, int64_t step, gmx_domdec_t* dd, matrix bo cx[YY] = grid_r[i * 2 + y][YY]; cx[ZZ] = grid_r[i * 2 + z][ZZ]; mvmul(tric, cx, r); - gmx_fprintf_pdb_atomline(out, epdbATOM, a++, "CA", ' ', "GLY", ' ', i + 1, ' ', - 10 * r[XX], 10 * r[YY], 10 * r[ZZ], 1.0, vol, ""); + gmx_fprintf_pdb_atomline(out, + epdbATOM, + a++, + "CA", + ' ', + "GLY", + ' ', + i + 1, + ' ', + 10 * r[XX], + 10 * r[YY], + 10 * r[ZZ], + 1.0, + vol, + ""); } } } @@ -194,8 +207,21 @@ void write_dd_pdb(const char* fn, { b = dd->comm->zones.n + 1; } - gmx_fprintf_pdb_atomline(out, epdbATOM, ii + 1, atomname, ' ', resname, ' ', resnr, ' ', - 10 * x[i][XX], 10 * x[i][YY], 10 * x[i][ZZ], 1.0, b, ""); + gmx_fprintf_pdb_atomline(out, + epdbATOM, + ii + 1, + atomname, + ' ', + resname, + ' ', + resnr, + ' ', + 10 * x[i][XX], + 10 * x[i][YY], + 10 * x[i][ZZ], + 1.0, + b, + ""); } fprintf(out, "TER\n"); diff --git a/src/gromacs/domdec/gpuhaloexchange_impl.cu b/src/gromacs/domdec/gpuhaloexchange_impl.cu index 8b84aa985b..2189f39fe4 100644 --- a/src/gromacs/domdec/gpuhaloexchange_impl.cu +++ b/src/gromacs/domdec/gpuhaloexchange_impl.cu @@ -180,8 +180,18 @@ void GpuHaloExchange::Impl::reinitHalo(float3* d_coordinatesBuffer, float3* d_fo xSendSize_ = newSize; #if GMX_MPI - MPI_Sendrecv(&xSendSize_, sizeof(int), MPI_BYTE, sendRankX_, 0, &xRecvSize_, sizeof(int), - MPI_BYTE, recvRankX_, 0, mpi_comm_mysim_, MPI_STATUS_IGNORE); + MPI_Sendrecv(&xSendSize_, + sizeof(int), + MPI_BYTE, + sendRankX_, + 0, + &xRecvSize_, + sizeof(int), + MPI_BYTE, + recvRankX_, + 0, + mpi_comm_mysim_, + MPI_STATUS_IGNORE); #endif fSendSize_ = xRecvSize_; fRecvSize_ = xSendSize_; @@ -193,8 +203,8 @@ void GpuHaloExchange::Impl::reinitHalo(float3* d_coordinatesBuffer, float3* d_fo "halo exchange index mapping array"); std::copy(ind.index.begin(), ind.index.end(), h_indexMap_.begin()); - copyToDeviceBuffer(&d_indexMap_, h_indexMap_.data(), 0, newSize, nonLocalStream_, - GpuApiCallBehavior::Async, nullptr); + copyToDeviceBuffer( + &d_indexMap_, h_indexMap_.data(), 0, newSize, nonLocalStream_, GpuApiCallBehavior::Async, nullptr); } // This rank will push data to its neighbor, so needs to know // the remote receive address and similarly send its receive @@ -204,13 +214,33 @@ void GpuHaloExchange::Impl::reinitHalo(float3* d_coordinatesBuffer, float3* d_fo // Coordinates buffer: void* recvPtr = static_cast(&d_x_[atomOffset_]); #if GMX_MPI - MPI_Sendrecv(&recvPtr, sizeof(void*), MPI_BYTE, recvRankX_, 0, &remoteXPtr_, sizeof(void*), - MPI_BYTE, sendRankX_, 0, mpi_comm_mysim_, MPI_STATUS_IGNORE); + MPI_Sendrecv(&recvPtr, + sizeof(void*), + MPI_BYTE, + recvRankX_, + 0, + &remoteXPtr_, + sizeof(void*), + MPI_BYTE, + sendRankX_, + 0, + mpi_comm_mysim_, + MPI_STATUS_IGNORE); // Force buffer: recvPtr = static_cast(d_recvBuf_); - MPI_Sendrecv(&recvPtr, sizeof(void*), MPI_BYTE, recvRankF_, 0, &remoteFPtr_, sizeof(void*), - MPI_BYTE, sendRankF_, 0, mpi_comm_mysim_, MPI_STATUS_IGNORE); + MPI_Sendrecv(&recvPtr, + sizeof(void*), + MPI_BYTE, + recvRankF_, + 0, + &remoteFPtr_, + sizeof(void*), + MPI_BYTE, + sendRankF_, + 0, + mpi_comm_mysim_, + MPI_STATUS_IGNORE); #endif wallcycle_sub_stop(wcycle_, ewcsDD_GPU); @@ -252,7 +282,8 @@ void GpuHaloExchange::Impl::communicateHaloCoordinates(const matrix box // is used every step to pass the shift vector as an argument of // the packing kernel. const int boxDimensionIndex = dd_->dim[dimIndex_]; - const float3 coordinateShift{ box[boxDimensionIndex][XX], box[boxDimensionIndex][YY], + const float3 coordinateShift{ box[boxDimensionIndex][XX], + box[boxDimensionIndex][YY], box[boxDimensionIndex][ZZ] }; // Avoid launching kernel when there is no work to do @@ -260,11 +291,11 @@ void GpuHaloExchange::Impl::communicateHaloCoordinates(const matrix box { auto kernelFn = usePBC_ ? packSendBufKernel : packSendBufKernel; - const auto kernelArgs = prepareGpuKernelArguments(kernelFn, config, &sendBuf, &d_x, - &indexMap, &size, &coordinateShift); + const auto kernelArgs = prepareGpuKernelArguments( + kernelFn, config, &sendBuf, &d_x, &indexMap, &size, &coordinateShift); - launchGpuKernel(kernelFn, config, nonLocalStream_, nullptr, - "Domdec GPU Apply X Halo Exchange", kernelArgs); + launchGpuKernel( + kernelFn, config, nonLocalStream_, nullptr, "Domdec GPU Apply X Halo Exchange", kernelArgs); } wallcycle_sub_stop(wcycle_, ewcsLAUNCH_GPU_MOVEX); @@ -349,8 +380,8 @@ void GpuHaloExchange::Impl::communicateHaloForces(bool accumulateForces) const auto kernelArgs = prepareGpuKernelArguments(kernelFn, config, &d_f, &recvBuf, &indexMap, &size); - launchGpuKernel(kernelFn, config, nonLocalStream_, nullptr, - "Domdec GPU Apply F Halo Exchange", kernelArgs); + launchGpuKernel( + kernelFn, config, nonLocalStream_, nullptr, "Domdec GPU Apply F Halo Exchange", kernelArgs); } if (pulse_ == 0) @@ -387,9 +418,18 @@ void GpuHaloExchange::Impl::communicateHaloData(float3* d_ptr, // for subsequent data push. This avoids a race condition with the remote data being written in the previous timestep. // Similarly send event to task that will push data to this task. GpuEventSynchronizer* remoteCoordinatesReadyOnDeviceEvent; - MPI_Sendrecv(&coordinatesReadyOnDeviceEvent, sizeof(GpuEventSynchronizer*), MPI_BYTE, - recvRank, 0, &remoteCoordinatesReadyOnDeviceEvent, sizeof(GpuEventSynchronizer*), - MPI_BYTE, sendRank, 0, mpi_comm_mysim_, MPI_STATUS_IGNORE); + MPI_Sendrecv(&coordinatesReadyOnDeviceEvent, + sizeof(GpuEventSynchronizer*), + MPI_BYTE, + recvRank, + 0, + &remoteCoordinatesReadyOnDeviceEvent, + sizeof(GpuEventSynchronizer*), + MPI_BYTE, + sendRank, + 0, + mpi_comm_mysim_, + MPI_STATUS_IGNORE); remoteCoordinatesReadyOnDeviceEvent->enqueueWaitEvent(nonLocalStream_); #else GMX_UNUSED_VALUE(coordinatesReadyOnDeviceEvent); @@ -425,8 +465,11 @@ void GpuHaloExchange::Impl::communicateHaloDataWithCudaDirect(void* sendPtr, // send data to neighbor, if any data exists to send if (sendSize > 0) { - stat = cudaMemcpyAsync(remotePtr, sendPtr, sendSize * DIM * sizeof(float), - cudaMemcpyDeviceToDevice, nonLocalStream_.stream()); + stat = cudaMemcpyAsync(remotePtr, + sendPtr, + sendSize * DIM * sizeof(float), + cudaMemcpyDeviceToDevice, + nonLocalStream_.stream()); CU_RET_ERR(stat, "cudaMemcpyAsync on GPU Domdec CUDA direct data transfer failed"); } @@ -440,9 +483,18 @@ void GpuHaloExchange::Impl::communicateHaloDataWithCudaDirect(void* sendPtr, haloDataTransferLaunched_->markEvent(nonLocalStream_); - MPI_Sendrecv(&haloDataTransferLaunched_, sizeof(GpuEventSynchronizer*), MPI_BYTE, sendRank, 0, - &haloDataTransferRemote, sizeof(GpuEventSynchronizer*), MPI_BYTE, recvRank, 0, - mpi_comm_mysim_, MPI_STATUS_IGNORE); + MPI_Sendrecv(&haloDataTransferLaunched_, + sizeof(GpuEventSynchronizer*), + MPI_BYTE, + sendRank, + 0, + &haloDataTransferRemote, + sizeof(GpuEventSynchronizer*), + MPI_BYTE, + recvRank, + 0, + mpi_comm_mysim_, + MPI_STATUS_IGNORE); haloDataTransferRemote->enqueueWaitEvent(nonLocalStream_); #else diff --git a/src/gromacs/domdec/mdsetup.cpp b/src/gromacs/domdec/mdsetup.cpp index 90f28d18a7..ce4458a49c 100644 --- a/src/gromacs/domdec/mdsetup.cpp +++ b/src/gromacs/domdec/mdsetup.cpp @@ -98,8 +98,12 @@ void mdAlgorithmsSetupAtomData(const t_commrec* cr, force->resize(numTotalAtoms); } - atoms2md(&top_global, ir, numAtomIndex, - usingDomDec ? cr->dd->globalAtomIndices : std::vector(), numHomeAtoms, mdAtoms); + atoms2md(&top_global, + ir, + numAtomIndex, + usingDomDec ? cr->dd->globalAtomIndices : std::vector(), + numHomeAtoms, + mdAtoms); auto mdatoms = mdAtoms->mdatoms(); if (usingDomDec) @@ -143,8 +147,14 @@ void mdAlgorithmsSetupAtomData(const t_commrec* cr, if (constr) { - constr->setConstraints(top, mdatoms->nr, mdatoms->homenr, mdatoms->massT, mdatoms->invmass, - mdatoms->nMassPerturbed != 0, mdatoms->lambda, mdatoms->cFREEZE); + constr->setConstraints(top, + mdatoms->nr, + mdatoms->homenr, + mdatoms->massT, + mdatoms->invmass, + mdatoms->nMassPerturbed != 0, + mdatoms->lambda, + mdatoms->cFREEZE); } } diff --git a/src/gromacs/domdec/partition.cpp b/src/gromacs/domdec/partition.cpp index b295040db7..9640d2756b 100644 --- a/src/gromacs/domdec/partition.cpp +++ b/src/gromacs/domdec/partition.cpp @@ -120,7 +120,15 @@ static void print_ddzone(FILE* fp, int d, int i, int j, gmx_ddzone_t* zone) fprintf(fp, "zone d0 %d d1 %d d2 %d min0 %6.3f max1 %6.3f mch0 %6.3f mch1 %6.3f p1_0 %6.3f p1_1 " "%6.3f\n", - d, i, j, zone->min0, zone->max1, zone->mch0, zone->mch0, zone->p1_0, zone->p1_1); + d, + i, + j, + zone->min0, + zone->max1, + zone->mch0, + zone->mch0, + zone->p1_0, + zone->p1_1); } /*! \brief Using the home grid size as input in cell_ns_x0 and cell_ns_x1 @@ -251,7 +259,10 @@ static void dd_move_cellx(gmx_domdec_t* dd, const gmx_ddbox_t* ddbox, rvec cell_ "Here we expect gmx_ddzone_t to consist of c_ddzoneNumReals reals (only)"); int numReals = numElementsInBuffer * c_ddzoneNumReals; - ddSendrecv(dd, d, dddirBackward, gmx::arrayRefFromArray(&buf_s[0].min0, numReals), + ddSendrecv(dd, + d, + dddirBackward, + gmx::arrayRefFromArray(&buf_s[0].min0, numReals), gmx::arrayRefFromArray(&buf_r[0].min0, numReals)); rvec dh = { 0 }; @@ -412,7 +423,10 @@ static void dd_move_cellx(gmx_domdec_t* dd, const gmx_ddbox_t* ddbox, rvec cell_ cellsizes[d].fracUpperMin = extr_s[d - 1][1]; if (debug) { - fprintf(debug, "Cell fraction d %d, max0 %f, min1 %f\n", d, cellsizes[d].fracLowerMax, + fprintf(debug, + "Cell fraction d %d, max0 %f, min1 %f\n", + d, + cellsizes[d].fracLowerMax, cellsizes[d].fracUpperMin); } } @@ -537,8 +551,12 @@ static void check_index_consistency(const gmx_domdec_t* dd, int natoms_sys, cons int globalAtomIndex = dd->globalAtomIndices[a]; if (have[globalAtomIndex] > 0) { - fprintf(stderr, "DD rank %d: global atom %d occurs twice: index %d and %d\n", - dd->rank, globalAtomIndex + 1, have[globalAtomIndex], a + 1); + fprintf(stderr, + "DD rank %d: global atom %d occurs twice: index %d and %d\n", + dd->rank, + globalAtomIndex + 1, + have[globalAtomIndex], + a + 1); } else { @@ -560,7 +578,10 @@ static void check_index_consistency(const gmx_domdec_t* dd, int natoms_sys, cons fprintf(stderr, "DD rank %d: global atom %d marked as local atom %d, which is larger than " "nat_tot (%d)\n", - dd->rank, i + 1, a + 1, numAtomsInZones); + dd->rank, + i + 1, + a + 1, + numAtomsInZones); nerr++; } else @@ -571,7 +592,10 @@ static void check_index_consistency(const gmx_domdec_t* dd, int natoms_sys, cons fprintf(stderr, "DD rank %d: global atom %d marked as local atom %d, which has global " "atom index %d\n", - dd->rank, i + 1, a + 1, dd->globalAtomIndices[a] + 1); + dd->rank, + i + 1, + a + 1, + dd->globalAtomIndices[a] + 1); nerr++; } } @@ -580,15 +604,18 @@ static void check_index_consistency(const gmx_domdec_t* dd, int natoms_sys, cons } if (ngl != numAtomsInZones) { - fprintf(stderr, "DD rank %d, %s: %d global atom indices, %d local atoms\n", dd->rank, where, - ngl, numAtomsInZones); + fprintf(stderr, "DD rank %d, %s: %d global atom indices, %d local atoms\n", dd->rank, where, ngl, numAtomsInZones); } for (int a = 0; a < numAtomsInZones; a++) { if (have[a] == 0) { - fprintf(stderr, "DD rank %d, %s: local atom %d, global %d has no global index\n", - dd->rank, where, a + 1, dd->globalAtomIndices[a] + 1); + fprintf(stderr, + "DD rank %d, %s: local atom %d, global %d has no global index\n", + dd->rank, + where, + a + 1, + dd->globalAtomIndices[a] + 1); } } @@ -656,7 +683,11 @@ bool check_grid_jump(int64_t step, const gmx_domdec_t* dd, real cutoff, const gm "step %s: The domain decomposition grid has shifted too much in the " "%c-direction around cell %d %d %d. This should not have happened. " "Running with fewer ranks might avoid this issue.", - gmx_step_str(step, buf), dim2char(dim), dd->ci[XX], dd->ci[YY], dd->ci[ZZ]); + gmx_step_str(step, buf), + dim2char(dim), + dd->ci[XX], + dd->ci[YY], + dd->ci[ZZ]); } } } @@ -742,9 +773,14 @@ static void comm_dd_ns_cell_sizes(gmx_domdec_t* dd, gmx_ddbox_t* ddbox, rvec cel "step %s: The %c-size (%f) times the triclinic skew factor (%f) is smaller " "than the smallest allowed cell size (%f) for domain decomposition grid cell " "%d %d %d", - gmx_step_str(step, buf), dim2char(dim), - comm->cell_x1[dim] - comm->cell_x0[dim], ddbox->skew_fac[dim], - dd->comm->cellsize_min[dim], dd->ci[XX], dd->ci[YY], dd->ci[ZZ]); + gmx_step_str(step, buf), + dim2char(dim), + comm->cell_x1[dim] - comm->cell_x0[dim], + ddbox->skew_fac[dim], + dd->comm->cellsize_min[dim], + dd->ci[XX], + dd->ci[YY], + dd->ci[ZZ]); } } @@ -844,8 +880,14 @@ static void get_load_distribution(gmx_domdec_t* dd, gmx_wallcycle_t wcycle) * The communicators are setup such that the root always has rank 0. */ #if GMX_MPI - MPI_Gather(sbuf, load->nload * sizeof(float), MPI_BYTE, load->load, - load->nload * sizeof(float), MPI_BYTE, 0, comm->mpi_comm_load[d]); + MPI_Gather(sbuf, + load->nload * sizeof(float), + MPI_BYTE, + load->load, + load->nload * sizeof(float), + MPI_BYTE, + 0, + comm->mpi_comm_load[d]); #endif if (dd->ci[dim] == dd->master_ci[dim]) { @@ -1074,7 +1116,8 @@ static void print_dd_load_av(FILE* fplog, gmx_domdec_t* dd) sprintf(buf, " Average PME mesh/force load: %5.3f\n", pmeForceRatio); fprintf(fplog, "%s", buf); fprintf(stderr, "%s", buf); - sprintf(buf, " Part of the total run time spent waiting due to PP/PME imbalance: %.1f %%\n", + sprintf(buf, + " Part of the total run time spent waiting due to PP/PME imbalance: %.1f %%\n", std::fabs(lossFractionPme) * 100); fprintf(fplog, "%s", buf); fprintf(stderr, "%s", buf); @@ -1119,7 +1162,8 @@ static void print_dd_load_av(FILE* fplog, gmx_domdec_t* dd) " had %s work to do than the PP ranks.\n" " You might want to %s the number of PME ranks\n" " or %s the cut-off and the grid spacing.\n", - std::fabs(lossFractionPme * 100), (lossFractionPme < 0) ? "less" : "more", + std::fabs(lossFractionPme * 100), + (lossFractionPme < 0) ? "less" : "more", (lossFractionPme < 0) ? "decrease" : "increase", (lossFractionPme < 0) ? "decrease" : "increase"); fprintf(fplog, "%s\n", buf); @@ -1225,7 +1269,8 @@ static void turn_on_dlb(const gmx::MDLogger& mdlog, gmx_domdec_t* dd, int64_t st "step %s Measured %.1f %% performance loss due to load imbalance, " "but the minimum cell size is smaller than 1.05 times the cell size limit. " "Will no longer try dynamic load balancing.", - gmx::toString(step).c_str(), dd_force_imb_perf_loss(dd) * 100); + gmx::toString(step).c_str(), + dd_force_imb_perf_loss(dd) * 100); comm->dlbState = DlbState::offForever; return; @@ -1235,7 +1280,8 @@ static void turn_on_dlb(const gmx::MDLogger& mdlog, gmx_domdec_t* dd, int64_t st .appendTextFormatted( "step %s Turning on dynamic load balancing, because the performance loss due " "to load imbalance is %.1f %%.", - gmx::toString(step).c_str(), dd_force_imb_perf_loss(dd) * 100); + gmx::toString(step).c_str(), + dd_force_imb_perf_loss(dd) * 100); comm->dlbState = DlbState::onCanTurnOff; /* Store the non-DLB performance, so we can check if DLB actually @@ -2006,12 +2052,37 @@ static void setup_dd_communication(gmx_domdec_t* dd, matrix box, gmx_ddbox_t* dd int cg1_th = cg0 + ((cg1 - cg0) * (th + 1)) / numThreads; /* Get the cg's for this pulse in this zone */ - get_zone_pulse_cgs(dd, zonei, zone, cg0_th, cg1_th, dd->globalAtomGroupIndices, - dim, dim_ind, dim0, dim1, dim2, r_comm2, r_bcomm2, box, - distanceIsTriclinic, normal, skew_fac2_d, skew_fac_01, - v_d, v_0, v_1, &corners, sf2_round, bDistBonded, bBondComm, - bDist2B, bDistMB, state->x.rvec_array(), fr->cginfo, - th == 0 ? &ind->index : &work.localAtomGroupBuffer, &work); + get_zone_pulse_cgs(dd, + zonei, + zone, + cg0_th, + cg1_th, + dd->globalAtomGroupIndices, + dim, + dim_ind, + dim0, + dim1, + dim2, + r_comm2, + r_bcomm2, + box, + distanceIsTriclinic, + normal, + skew_fac2_d, + skew_fac_01, + v_d, + v_0, + v_1, + &corners, + sf2_round, + bDistBonded, + bBondComm, + bDist2B, + bDistMB, + state->x.rvec_array(), + fr->cginfo, + th == 0 ? &ind->index : &work.localAtomGroupBuffer, + &work); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR } // END @@ -2024,12 +2095,13 @@ static void setup_dd_communication(gmx_domdec_t* dd, matrix box, gmx_ddbox_t* dd { const dd_comm_setup_work_t& dth = comm->dth[th]; - ind->index.insert(ind->index.end(), dth.localAtomGroupBuffer.begin(), + ind->index.insert(ind->index.end(), + dth.localAtomGroupBuffer.begin(), dth.localAtomGroupBuffer.end()); - atomGroups.insert(atomGroups.end(), dth.atomGroupBuffer.begin(), - dth.atomGroupBuffer.end()); - positions.insert(positions.end(), dth.positionBuffer.begin(), - dth.positionBuffer.end()); + atomGroups.insert( + atomGroups.end(), dth.atomGroupBuffer.begin(), dth.atomGroupBuffer.end()); + positions.insert( + positions.end(), dth.positionBuffer.begin(), dth.positionBuffer.end()); comm->dth[0].nat += dth.nat; ind->nsend[zone] += dth.nsend_zone; } @@ -2121,8 +2193,15 @@ static void setup_dd_communication(gmx_domdec_t* dd, matrix box, gmx_ddbox_t* dd else { /* This part of the code is never executed with bBondComm. */ - merge_cg_buffers(nzone, cd, p, zone_cg_range, dd->globalAtomGroupIndices, - integerBufferRef.data(), state->x, rvecBufferRef, fr->cginfo_mb, + merge_cg_buffers(nzone, + cd, + p, + zone_cg_range, + dd->globalAtomGroupIndices, + integerBufferRef.data(), + state->x, + rvecBufferRef, + fr->cginfo_mb, fr->cginfo); pos_cg += ind->nrecv[nzone]; } @@ -2427,12 +2506,24 @@ static void set_zones_size(gmx_domdec_t* dd, { for (z = zone_start; z < zone_end; z++) { - fprintf(debug, "zone %d %6.3f - %6.3f %6.3f - %6.3f %6.3f - %6.3f\n", z, - zones->size[z].x0[XX], zones->size[z].x1[XX], zones->size[z].x0[YY], - zones->size[z].x1[YY], zones->size[z].x0[ZZ], zones->size[z].x1[ZZ]); - fprintf(debug, "zone %d bb %6.3f - %6.3f %6.3f - %6.3f %6.3f - %6.3f\n", z, - zones->size[z].bb_x0[XX], zones->size[z].bb_x1[XX], zones->size[z].bb_x0[YY], - zones->size[z].bb_x1[YY], zones->size[z].bb_x0[ZZ], zones->size[z].bb_x1[ZZ]); + fprintf(debug, + "zone %d %6.3f - %6.3f %6.3f - %6.3f %6.3f - %6.3f\n", + z, + zones->size[z].x0[XX], + zones->size[z].x1[XX], + zones->size[z].x0[YY], + zones->size[z].x1[YY], + zones->size[z].x0[ZZ], + zones->size[z].x1[ZZ]); + fprintf(debug, + "zone %d bb %6.3f - %6.3f %6.3f - %6.3f %6.3f - %6.3f\n", + z, + zones->size[z].bb_x0[XX], + zones->size[z].bb_x1[XX], + zones->size[z].bb_x0[YY], + zones->size[z].bb_x1[YY], + zones->size[z].bb_x0[ZZ], + zones->size[z].bb_x1[ZZ]); } } } @@ -2601,15 +2692,19 @@ void print_dd_statistics(const t_commrec* cr, const t_inputrec* ir, FILE* fplog) case DDAtomRanges::Type::Vsites: if (cr->dd->vsite_comm) { - fprintf(fplog, " av. #atoms communicated per step for vsites: %d x %.1f\n", - (EEL_PME(ir->coulombtype) || ir->coulombtype == eelEWALD) ? 3 : 2, av); + fprintf(fplog, + " av. #atoms communicated per step for vsites: %d x %.1f\n", + (EEL_PME(ir->coulombtype) || ir->coulombtype == eelEWALD) ? 3 : 2, + av); } break; case DDAtomRanges::Type::Constraints: if (cr->dd->constraint_comm) { - fprintf(fplog, " av. #atoms communicated per step for LINCS: %d x %.1f\n", - 1 + ir->nLincsIter, av); + fprintf(fplog, + " av. #atoms communicated per step for LINCS: %d x %.1f\n", + 1 + ir->nLincsIter, + av); } break; default: gmx_incons(" Unknown type for DD statistics"); @@ -2876,7 +2971,8 @@ void dd_partition_system(FILE* fplog, gmx_fatal(FARGS, "Internal inconsistency state_local->ddp_count (%d) > dd->ddp_count (%" PRId64 ")", - state_local->ddp_count, dd->ddp_count); + state_local->ddp_count, + dd->ddp_count); } if (state_local->ddp_count_cg_gl != state_local->ddp_count) @@ -2884,7 +2980,8 @@ void dd_partition_system(FILE* fplog, gmx_fatal(FARGS, "Internal inconsistency state_local->ddp_count_cg_gl (%d) != " "state_local->ddp_count (%d)", - state_local->ddp_count_cg_gl, state_local->ddp_count); + state_local->ddp_count_cg_gl, + state_local->ddp_count); } /* Clear the old state */ @@ -2971,9 +3068,17 @@ void dd_partition_system(FILE* fplog, } // TODO: Integrate this code in the nbnxm module - get_nsgrid_boundaries(ddbox.nboundeddim, state_local->box, dd, &ddbox, &comm->cell_x0, - &comm->cell_x1, dd->ncg_home, as_rvec_array(state_local->x.data()), - cell_ns_x0, cell_ns_x1, &grid_density); + get_nsgrid_boundaries(ddbox.nboundeddim, + state_local->box, + dd, + &ddbox, + &comm->cell_x0, + &comm->cell_x1, + dd->ncg_home, + as_rvec_array(state_local->x.data()), + cell_ns_x0, + cell_ns_x1, + &grid_density); if (bBoxChanged) { @@ -2997,15 +3102,22 @@ void dd_partition_system(FILE* fplog, set_zones_size(dd, state_local->box, &ddbox, 0, 1, ncg_moved); - nbnxn_put_on_grid(fr->nbv.get(), state_local->box, 0, comm->zones.size[0].bb_x0, - comm->zones.size[0].bb_x1, comm->updateGroupsCog.get(), - { 0, dd->ncg_home }, comm->zones.dens_zone0, fr->cginfo, state_local->x, - ncg_moved, bRedist ? comm->movedBuffer.data() : nullptr); + nbnxn_put_on_grid(fr->nbv.get(), + state_local->box, + 0, + comm->zones.size[0].bb_x0, + comm->zones.size[0].bb_x1, + comm->updateGroupsCog.get(), + { 0, dd->ncg_home }, + comm->zones.dens_zone0, + fr->cginfo, + state_local->x, + ncg_moved, + bRedist ? comm->movedBuffer.data() : nullptr); if (debug) { - fprintf(debug, "Step %s, sorting the %d home charge groups\n", gmx_step_str(step, sbuf), - dd->ncg_home); + fprintf(debug, "Step %s, sorting the %d home charge groups\n", gmx_step_str(step, sbuf), dd->ncg_home); } dd_sort_state(dd, fr, state_local); @@ -3069,8 +3181,16 @@ void dd_partition_system(FILE* fplog, { np[dd->dim[i]] = comm->cd[i].numPulses(); } - dd_make_local_top(dd, &comm->zones, dd->unitCellInfo.npbcdim, state_local->box, - comm->cellsize_min, np, fr, state_local->x.rvec_array(), top_global, top_local); + dd_make_local_top(dd, + &comm->zones, + dd->unitCellInfo.npbcdim, + state_local->box, + comm->cellsize_min, + np, + fr, + state_local->x.rvec_array(), + top_global, + top_local); wallcycle_sub_stop(wcycle, ewcsDD_MAKETOP); @@ -3079,7 +3199,8 @@ void dd_partition_system(FILE* fplog, /* Set up the special atom communication */ int n = comm->atomRanges.end(DDAtomRanges::Type::Zones); for (int i = static_cast(DDAtomRanges::Type::Zones) + 1; - i < static_cast(DDAtomRanges::Type::Number); i++) + i < static_cast(DDAtomRanges::Type::Number); + i++) { auto range = static_cast(i); switch (range) @@ -3094,8 +3215,13 @@ void dd_partition_system(FILE* fplog, if (dd->comm->systemInfo.haveSplitConstraints || dd->comm->systemInfo.haveSplitSettles) { /* Only for inter-cg constraints we need special code */ - n = dd_make_local_constraints(dd, n, &top_global, fr->cginfo.data(), constr, - ir->nProjOrder, top_local->idef.il); + n = dd_make_local_constraints(dd, + n, + &top_global, + fr->cginfo.data(), + constr, + ir->nProjOrder, + top_local->idef.il); } break; default: gmx_incons("Unknown special atom type setup"); @@ -3136,8 +3262,10 @@ void dd_partition_system(FILE* fplog, * allocation, zeroing and copying, but this is probably not worth * the complications and checking. */ - forcerec_set_ranges(fr, comm->atomRanges.end(DDAtomRanges::Type::Zones), - comm->atomRanges.end(DDAtomRanges::Type::Constraints), nat_f_novirsum); + forcerec_set_ranges(fr, + comm->atomRanges.end(DDAtomRanges::Type::Zones), + comm->atomRanges.end(DDAtomRanges::Type::Constraints), + nat_f_novirsum); /* Update atom data for mdatoms and several algorithms */ mdAlgorithmsSetupAtomData(cr, ir, top_global, top_local, fr, f, mdAtoms, constr, vsite, nullptr); @@ -3146,10 +3274,18 @@ void dd_partition_system(FILE* fplog, if (!thisRankHasDuty(cr, DUTY_PME)) { /* Send the charges and/or c6/sigmas to our PME only node */ - gmx_pme_send_parameters(cr, fr->ic, mdatoms->nChargePerturbed != 0, - mdatoms->nTypePerturbed != 0, mdatoms->chargeA, mdatoms->chargeB, - mdatoms->sqrt_c6A, mdatoms->sqrt_c6B, mdatoms->sigmaA, - mdatoms->sigmaB, dd_pme_maxshift_x(dd), dd_pme_maxshift_y(dd)); + gmx_pme_send_parameters(cr, + fr->ic, + mdatoms->nChargePerturbed != 0, + mdatoms->nTypePerturbed != 0, + mdatoms->chargeA, + mdatoms->chargeB, + mdatoms->sqrt_c6A, + mdatoms->sqrt_c6B, + mdatoms->sigmaA, + mdatoms->sigmaB, + dd_pme_maxshift_x(dd), + dd_pme_maxshift_y(dd)); } if (dd->atomSets != nullptr) @@ -3184,7 +3320,13 @@ void dd_partition_system(FILE* fplog, if (comm->ddSettings.nstDDDump > 0 && step % comm->ddSettings.nstDDDump == 0) { dd_move_x(dd, state_local->box, state_local->x, nullWallcycle); - write_dd_pdb("dd_dump", step, "dump", &top_global, cr, -1, state_local->x.rvec_array(), + write_dd_pdb("dd_dump", + step, + "dump", + &top_global, + cr, + -1, + state_local->x.rvec_array(), state_local->box); } @@ -3226,8 +3368,8 @@ void checkNumberOfBondedInteractions(const gmx::MDLogger& mdlog, { if (totalNumberOfBondedInteractions != cr->dd->nbonded_global) { - dd_print_missing_interactions(mdlog, cr, totalNumberOfBondedInteractions, top_global, - top_local, x, box); // Does not return + dd_print_missing_interactions( + mdlog, cr, totalNumberOfBondedInteractions, top_global, top_local, x, box); // Does not return } *shouldCheckNumberOfBondedInteractions = false; } diff --git a/src/gromacs/domdec/redistribute.cpp b/src/gromacs/domdec/redistribute.cpp index 6b985c1345..7a6537ca8d 100644 --- a/src/gromacs/domdec/redistribute.cpp +++ b/src/gromacs/domdec/redistribute.cpp @@ -184,17 +184,24 @@ static void print_cg_move(FILE* fplog, mesg += gmx::formatString(" in direction %c\n", dim2char(dim)); fprintf(fplog, "%s", mesg.c_str()); - fprintf(fplog, "distance out of cell %f\n", + fprintf(fplog, + "distance out of cell %f\n", dir == 1 ? pos_d - comm->cell_x1[dim] : pos_d - comm->cell_x0[dim]); if (bHaveCgcmOld) { fprintf(fplog, "Old coordinates: %8.3f %8.3f %8.3f\n", cm_old[XX], cm_old[YY], cm_old[ZZ]); } fprintf(fplog, "New coordinates: %8.3f %8.3f %8.3f\n", cm_new[XX], cm_new[YY], cm_new[ZZ]); - fprintf(fplog, "Old cell boundaries in direction %c: %8.3f %8.3f\n", dim2char(dim), - comm->old_cell_x0[dim], comm->old_cell_x1[dim]); - fprintf(fplog, "New cell boundaries in direction %c: %8.3f %8.3f\n", dim2char(dim), - comm->cell_x0[dim], comm->cell_x1[dim]); + fprintf(fplog, + "Old cell boundaries in direction %c: %8.3f %8.3f\n", + dim2char(dim), + comm->old_cell_x0[dim], + comm->old_cell_x1[dim]); + fprintf(fplog, + "New cell boundaries in direction %c: %8.3f %8.3f\n", + dim2char(dim), + comm->cell_x0[dim], + comm->cell_x1[dim]); } [[noreturn]] static void cg_move_error(FILE* fplog, @@ -363,8 +370,8 @@ static void calc_cg_move(FILE* fplog, { if (pos_d >= moveLimits.upper[d]) { - cg_move_error(fplog, dd, step, a, d, 1, false, moveLimits.distance[d], - cm_new, cm_new, pos_d); + cg_move_error( + fplog, dd, step, a, d, 1, false, moveLimits.distance[d], cm_new, cm_new, pos_d); } dev[d] = 1; if (dd->ci[d] == dd->numCells[d] - 1) @@ -386,8 +393,8 @@ static void calc_cg_move(FILE* fplog, { if (pos_d < moveLimits.lower[d]) { - cg_move_error(fplog, dd, step, a, d, -1, false, moveLimits.distance[d], - cm_new, cm_new, pos_d); + cg_move_error( + fplog, dd, step, a, d, -1, false, moveLimits.distance[d], cm_new, cm_new, pos_d); } dev[d] = -1; if (dd->ci[d] == 0) @@ -486,8 +493,8 @@ static void calcGroupMove(FILE* fplog, { if (pos_d >= moveLimits.upper[d]) { - cg_move_error(fplog, dd, step, g, d, 1, true, moveLimits.distance[d], - cogOld, cog, pos_d); + cg_move_error( + fplog, dd, step, g, d, 1, true, moveLimits.distance[d], cogOld, cog, pos_d); } dev[d] = 1; if (dd->ci[d] == dd->numCells[d] - 1) @@ -499,8 +506,8 @@ static void calcGroupMove(FILE* fplog, { if (pos_d < moveLimits.lower[d]) { - cg_move_error(fplog, dd, step, g, d, -1, true, moveLimits.distance[d], - cogOld, cog, pos_d); + cg_move_error( + fplog, dd, step, g, d, -1, true, moveLimits.distance[d], cogOld, cog, pos_d); } dev[d] = -1; if (dd->ci[d] == 0) @@ -629,21 +636,43 @@ void dd_redistribute_cg(FILE* fplog, { const auto& updateGroupsCog = *comm->updateGroupsCog; const int numGroups = updateGroupsCog.numCogs(); - calcGroupMove(fplog, step, dd, state, tric_dir, tcm, cell_x0, cell_x1, moveLimits, - (thread * numGroups) / nthread, ((thread + 1) * numGroups) / nthread, + calcGroupMove(fplog, + step, + dd, + state, + tric_dir, + tcm, + cell_x0, + cell_x1, + moveLimits, + (thread * numGroups) / nthread, + ((thread + 1) * numGroups) / nthread, pbcAndFlags); /* We need a barrier as atoms below can be in a COG of a different thread */ #pragma omp barrier const int numHomeAtoms = comm->atomRanges.numHomeAtoms(); - applyPbcAndSetMoveFlags(updateGroupsCog, pbcAndFlags, (thread * numHomeAtoms) / nthread, - ((thread + 1) * numHomeAtoms) / nthread, state->x, move); + applyPbcAndSetMoveFlags(updateGroupsCog, + pbcAndFlags, + (thread * numHomeAtoms) / nthread, + ((thread + 1) * numHomeAtoms) / nthread, + state->x, + move); } else { /* Here we handle single atoms or charge groups */ - calc_cg_move(fplog, step, dd, state, tric_dir, tcm, cell_x0, cell_x1, moveLimits, + calc_cg_move(fplog, + step, + dd, + state, + tric_dir, + tcm, + cell_x0, + cell_x1, + moveLimits, (thread * dd->ncg_home) / nthread, - ((thread + 1) * dd->ncg_home) / nthread, move); + ((thread + 1) * dd->ncg_home) / nthread, + move); } } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR @@ -764,16 +793,26 @@ void dd_redistribute_cg(FILE* fplog, flagBuffer.resize((ncg_recv + rbuf[0]) * DD_CGIBS); /* Communicate the charge group indices, sizes and flags */ - ddSendrecv(dd, d, dir, comm->cggl_flag[cdd].data(), sbuf[0] * DD_CGIBS, - flagBuffer.buffer.data() + ncg_recv * DD_CGIBS, rbuf[0] * DD_CGIBS); + ddSendrecv(dd, + d, + dir, + comm->cggl_flag[cdd].data(), + sbuf[0] * DD_CGIBS, + flagBuffer.buffer.data() + ncg_recv * DD_CGIBS, + rbuf[0] * DD_CGIBS); const int nvs = ncg[cdd] + nat[cdd] * nvec; const int i = rbuf[0] + rbuf[1] * nvec; rvecBuffer.resize(nvr + i); /* Communicate cgcm and state */ - ddSendrecv(dd, d, dir, as_rvec_array(comm->cgcm_state[cdd].data()), nvs, - as_rvec_array(rvecBuffer.buffer.data()) + nvr, i); + ddSendrecv(dd, + d, + dir, + as_rvec_array(comm->cgcm_state[cdd].data()), + nvs, + as_rvec_array(rvecBuffer.buffer.data()) + nvr, + i); ncg_recv += rbuf[0]; nvr += i; } @@ -797,8 +836,8 @@ void dd_redistribute_cg(FILE* fplog, || ((flag & DD_FLAG_BW(d)) && cog[dim] < cell_x0[dim])) { rvec pos = { cog[0], cog[1], cog[2] }; - cg_move_error(fplog, dd, step, cg, dim, (flag & DD_FLAG_FW(d)) ? 1 : 0, false, - 0, pos, pos, pos[dim]); + cg_move_error( + fplog, dd, step, cg, dim, (flag & DD_FLAG_FW(d)) ? 1 : 0, false, 0, pos, pos, pos[dim]); } } @@ -927,8 +966,10 @@ void dd_redistribute_cg(FILE* fplog, } /* Copy from the receive to the send buffers */ memcpy(comm->cggl_flag[mc].data() + ncg[mc] * DD_CGIBS, - flagBuffer.buffer.data() + cg * DD_CGIBS, DD_CGIBS * sizeof(int)); - memcpy(comm->cgcm_state[mc][nvr], rvecBuffer.buffer.data() + buf_pos, + flagBuffer.buffer.data() + cg * DD_CGIBS, + DD_CGIBS * sizeof(int)); + memcpy(comm->cgcm_state[mc][nvr], + rvecBuffer.buffer.data() + buf_pos, (1 + nrcg * nvec) * sizeof(rvec)); buf_pos += 1 + nrcg * nvec; ncg[mc] += 1; @@ -957,7 +998,9 @@ void dd_redistribute_cg(FILE* fplog, if (debug) { - fprintf(debug, "Finished repartitioning: cgs moved out %d, new home %d\n", *ncg_moved, + fprintf(debug, + "Finished repartitioning: cgs moved out %d, new home %d\n", + *ncg_moved, dd->ncg_home - *ncg_moved); } } diff --git a/src/gromacs/domdec/tests/haloexchange_mpi.cpp b/src/gromacs/domdec/tests/haloexchange_mpi.cpp index 9b3eb6678d..c763db0a9e 100644 --- a/src/gromacs/domdec/tests/haloexchange_mpi.cpp +++ b/src/gromacs/domdec/tests/haloexchange_mpi.cpp @@ -150,8 +150,8 @@ void gpuHalo(gmx_domdec_t* dd, matrix box, HostVector* h_x, int numAtomsTo { for (int pulse = 0; pulse < dd->comm->cd[d].numPulses(); pulse++) { - gpuHaloExchange[d].push_back(GpuHaloExchange(dd, d, MPI_COMM_WORLD, deviceContext, - deviceStream, deviceStream, pulse, nullptr)); + gpuHaloExchange[d].push_back(GpuHaloExchange( + dd, d, MPI_COMM_WORLD, deviceContext, deviceStream, deviceStream, pulse, nullptr)); } } @@ -170,8 +170,8 @@ void gpuHalo(gmx_domdec_t* dd, matrix box, HostVector* h_x, int numAtomsTo haloCompletedEvent.waitForEvent(); // Copy results back to host - copyFromDeviceBuffer(h_x->data(), &d_x, 0, numAtomsTotal, deviceStream, - GpuApiCallBehavior::Sync, nullptr); + copyFromDeviceBuffer( + h_x->data(), &d_x, 0, numAtomsTotal, deviceStream, GpuApiCallBehavior::Sync, nullptr); freeDeviceBuffer(d_x); #else diff --git a/src/gromacs/essentialdynamics/edsam.cpp b/src/gromacs/essentialdynamics/edsam.cpp index aebd672980..a2071943c9 100644 --- a/src/gromacs/essentialdynamics/edsam.cpp +++ b/src/gromacs/essentialdynamics/edsam.cpp @@ -926,16 +926,34 @@ static void do_single_flood(FILE* edo, /* Broadcast the positions of the AVERAGE structure such that they are known on * every processor. Each node contributes its local positions x and stores them in * the collective ED array buf->xcoll */ - communicate_group_positions(cr, buf->xcoll, buf->shifts_xcoll, buf->extra_shifts_xcoll, bNS, x, - edi->sav.nr, edi->sav.nr_loc, edi->sav.anrs_loc, edi->sav.c_ind, - edi->sav.x_old, box); + communicate_group_positions(cr, + buf->xcoll, + buf->shifts_xcoll, + buf->extra_shifts_xcoll, + bNS, + x, + edi->sav.nr, + edi->sav.nr_loc, + edi->sav.anrs_loc, + edi->sav.c_ind, + edi->sav.x_old, + box); /* Only assembly REFERENCE positions if their indices differ from the average ones */ if (!edi->bRefEqAv) { - communicate_group_positions(cr, buf->xc_ref, buf->shifts_xc_ref, buf->extra_shifts_xc_ref, - bNS, x, edi->sref.nr, edi->sref.nr_loc, edi->sref.anrs_loc, - edi->sref.c_ind, edi->sref.x_old, box); + communicate_group_positions(cr, + buf->xc_ref, + buf->shifts_xc_ref, + buf->extra_shifts_xc_ref, + bNS, + x, + edi->sref.nr, + edi->sref.nr_loc, + edi->sref.anrs_loc, + edi->sref.c_ind, + edi->sref.x_old, + box); } /* If bUpdateShifts was TRUE, the shifts have just been updated in get_positions. @@ -1057,7 +1075,9 @@ static void init_flood(t_edpar* edi, gmx_edsam* ed, real dt) /* If in any of the ED groups we find a flooding vector, flooding is turned on */ ed->eEDtype = EssentialDynamicsType::Flooding; - fprintf(stderr, "ED: Flooding %d eigenvector%s.\n", edi->flood.vecs.neig, + fprintf(stderr, + "ED: Flooding %d eigenvector%s.\n", + edi->flood.vecs.neig, edi->flood.vecs.neig > 1 ? "s" : ""); if (edi->flood.bConstForce) @@ -1069,8 +1089,10 @@ static void init_flood(t_edpar* edi, gmx_edsam* ed, real dt) { edi->flood.vecs.fproj[i] = edi->flood.vecs.stpsz[i]; - fprintf(stderr, "ED: applying on eigenvector %d a constant force of %g\n", - edi->flood.vecs.ieig[i], edi->flood.vecs.fproj[i]); + fprintf(stderr, + "ED: applying on eigenvector %d a constant force of %g\n", + edi->flood.vecs.ieig[i], + edi->flood.vecs.fproj[i]); } } } @@ -1170,8 +1192,11 @@ static std::unique_ptr ed_open(int } else { - ed->edo = xvgropen(edoFileName, "Essential dynamics / flooding output", "Time (ps)", - "RMSDs (nm), projections on EVs (nm), ...", oenv); + ed->edo = xvgropen(edoFileName, + "Essential dynamics / flooding output", + "Time (ps)", + "RMSDs (nm), projections on EVs (nm), ...", + oenv); /* Make a descriptive legend */ write_edo_legend(ed, EDstate->nED, oenv); @@ -1199,8 +1224,7 @@ static void bc_ed_positions(const t_commrec* cr, struct gmx_edx* s, EssentialDyn * There, also memory is allocated */ s->nalloc_loc = 0; /* allocation size of s->anrs_loc */ snew_bc(MASTER(cr), s->x_old, s->nr); /* To be able to always make the ED molecule whole, ... */ - nblock_bc(cr->mpi_comm_mygroup, s->nr, - s->x_old); /* ... keep track of shift changes with the help of old coords */ + nblock_bc(cr->mpi_comm_mygroup, s->nr, s->x_old); /* ... keep track of shift changes with the help of old coords */ } /* broadcast masses for the reference structure (for mass-weighted fitting) */ @@ -1265,10 +1289,8 @@ static void broadcast_ed_data(const t_commrec* cr, gmx_edsam* ed) block_bc(cr->mpi_comm_mygroup, edi); /* Broadcast positions */ - bc_ed_positions(cr, &(edi.sref), - EssentialDynamicsStructure::Reference); /* reference positions (don't broadcast masses) */ - bc_ed_positions(cr, &(edi.sav), - EssentialDynamicsStructure::Average); /* average positions (do broadcast masses as well) */ + bc_ed_positions(cr, &(edi.sref), EssentialDynamicsStructure::Reference); /* reference positions (don't broadcast masses) */ + bc_ed_positions(cr, &(edi.sav), EssentialDynamicsStructure::Average); /* average positions (do broadcast masses as well) */ bc_ed_positions(cr, &(edi.star), EssentialDynamicsStructure::Target); /* target positions */ bc_ed_positions(cr, &(edi.sori), EssentialDynamicsStructure::Origin); /* origin positions */ @@ -1328,7 +1350,9 @@ static void init_edi(const gmx_mtop_t* mtop, t_edpar* edi) ">0.\n" "Either make the covariance analysis non-mass-weighted, or exclude massless\n" "atoms from the reference structure by creating a proper index group.\n", - i, edi->sref.anrs[i] + 1, edi->sref.m[i]); + i, + edi->sref.anrs[i] + 1, + edi->sref.m[i]); } totalmass += edi->sref.m[i]; @@ -1360,7 +1384,9 @@ static void init_edi(const gmx_mtop_t* mtop, t_edpar* edi) ">0.\n" "Either make the covariance analysis non-mass-weighted, or exclude massless\n" "atoms from the average structure by creating a proper index group.\n", - i, edi->sav.anrs[i] + 1, edi->sav.m[i]); + i, + edi->sav.anrs[i] + 1, + edi->sav.m[i]); } } @@ -1383,7 +1409,8 @@ static void check(const char* line, const char* label) gmx_fatal(FARGS, "Could not find input parameter %s at expected position in edsam input-file " "(.edi)\nline read instead is %s", - label, line); + label, + line); } } @@ -1558,8 +1585,8 @@ bool readEdVecWithReferenceProjection(FILE* in, double stepSize = 0.; double referenceProjection = 0.; double referenceSlope = 0.; - const int nscan = sscanf(line, max_ev_fmt_dlflflf, &numEigenVectors, &stepSize, - &referenceProjection, &referenceSlope); + const int nscan = sscanf( + line, max_ev_fmt_dlflflf, &numEigenVectors, &stepSize, &referenceProjection, &referenceSlope); /* Zero out values which were not scanned */ switch (nscan) { @@ -1732,8 +1759,7 @@ t_edpar read_edi(FILE* in, int nr_mdatoms, bool hasConstForceFlooding, const cha edi.nini = read_edint(in, &bEOF); if (edi.nini != nr_mdatoms) { - gmx_fatal(FARGS, "Nr of atoms in %s (%d) does not match nr of md atoms (%d)", fn, edi.nini, - nr_mdatoms); + gmx_fatal(FARGS, "Nr of atoms in %s (%d) does not match nr of md atoms (%d)", fn, edi.nini, nr_mdatoms); } /* Done checking. For the rest we blindly trust the input */ @@ -1788,7 +1814,9 @@ t_edpar read_edi(FILE* in, int nr_mdatoms, bool hasConstForceFlooding, const cha bool bHaveReference = false; if (edi.flood.bHarmonic) { - bHaveReference = readEdVecWithReferenceProjection(in, edi.sav.nr, &edi.flood.vecs, + bHaveReference = readEdVecWithReferenceProjection(in, + edi.sav.nr, + &edi.flood.vecs, &edi.flood.initialReferenceProjection, &edi.flood.referenceProjectionSlope); } @@ -1855,7 +1883,9 @@ std::vector read_edi_file(const char* fn, int nr_mdatoms) gmx_fatal(FARGS, "No complete ED data set found in edi file %s.", fn); } - fprintf(stderr, "ED: Found %zu ED group%s.\n", essentialDynamicsParameters.size(), + fprintf(stderr, + "ED: Found %zu ED group%s.\n", + essentialDynamicsParameters.size(), essentialDynamicsParameters.size() > 1 ? "s" : ""); /* Close the .edi file again */ @@ -1960,13 +1990,23 @@ void dd_make_local_ed_indices(gmx_domdec_t* dd, struct gmx_edsam* ed) * if their indices differ from the average ones */ if (!edi.bRefEqAv) { - dd_make_local_group_indices(dd->ga2la, edi.sref.nr, edi.sref.anrs, &edi.sref.nr_loc, - &edi.sref.anrs_loc, &edi.sref.nalloc_loc, edi.sref.c_ind); + dd_make_local_group_indices(dd->ga2la, + edi.sref.nr, + edi.sref.anrs, + &edi.sref.nr_loc, + &edi.sref.anrs_loc, + &edi.sref.nalloc_loc, + edi.sref.c_ind); } /* Local atoms of the average structure (on these ED will be performed) */ - dd_make_local_group_indices(dd->ga2la, edi.sav.nr, edi.sav.anrs, &edi.sav.nr_loc, - &edi.sav.anrs_loc, &edi.sav.nalloc_loc, edi.sav.c_ind); + dd_make_local_group_indices(dd->ga2la, + edi.sav.nr, + edi.sav.anrs, + &edi.sav.nr_loc, + &edi.sav.anrs_loc, + &edi.sav.nalloc_loc, + edi.sav.c_ind); /* Indicate that the ED shift vectors for this structure need to be updated * at the next call to communicate_group_positions, since obviously we are in a NS step */ @@ -2382,14 +2422,18 @@ static void crosscheck_edi_file_vs_checkpoint(const gmx_edsam& ed, edsamhistory_ gmx_fatal(FARGS, "The number of reference structure atoms in ED group %c is\n" "not the same in .cpt (NREF=%d) and .edi (NREF=%d) files!\n", - get_EDgroupChar(edinum + 1, 0), EDstate->nref[edinum], ed.edpar[edinum].sref.nr); + get_EDgroupChar(edinum + 1, 0), + EDstate->nref[edinum], + ed.edpar[edinum].sref.nr); } if (EDstate->nav[edinum] != ed.edpar[edinum].sav.nr) { gmx_fatal(FARGS, "The number of average structure atoms in ED group %c is\n" "not the same in .cpt (NREF=%d) and .edi (NREF=%d) files!\n", - get_EDgroupChar(edinum + 1, 0), EDstate->nav[edinum], ed.edpar[edinum].sav.nr); + get_EDgroupChar(edinum + 1, 0), + EDstate->nav[edinum], + ed.edpar[edinum].sav.nr); } } @@ -2399,7 +2443,8 @@ static void crosscheck_edi_file_vs_checkpoint(const gmx_edsam& ed, edsamhistory_ "The number of essential dynamics / flooding groups is not consistent.\n" "There are %d ED groups in the .cpt file, but %zu in the .edi file!\n" "Are you sure this is the correct .edi file?\n", - EDstate->nED, ed.edpar.size()); + EDstate->nED, + ed.edpar.size()); } } @@ -2522,29 +2567,37 @@ static void write_edo_legend(gmx_edsam* ed, int nED, const gmx_output_env_t* oen auto edi = ed->edpar.begin(); - fprintf(ed->edo, "# Output will be written every %d step%s\n", edi->outfrq, - edi->outfrq != 1 ? "s" : ""); + fprintf(ed->edo, "# Output will be written every %d step%s\n", edi->outfrq, edi->outfrq != 1 ? "s" : ""); for (nr_edi = 1; nr_edi <= nED; nr_edi++) { fprintf(ed->edo, "#\n"); - fprintf(ed->edo, "# Summary of applied con/restraints for the ED group %c\n", + fprintf(ed->edo, + "# Summary of applied con/restraints for the ED group %c\n", get_EDgroupChar(nr_edi, nED)); fprintf(ed->edo, "# Atoms in average structure: %d\n", edi->sav.nr); - fprintf(ed->edo, "# monitor : %d vec%s\n", edi->vecs.mon.neig, - edi->vecs.mon.neig != 1 ? "s" : ""); - fprintf(ed->edo, "# LINFIX : %d vec%s\n", edi->vecs.linfix.neig, + fprintf(ed->edo, "# monitor : %d vec%s\n", edi->vecs.mon.neig, edi->vecs.mon.neig != 1 ? "s" : ""); + fprintf(ed->edo, + "# LINFIX : %d vec%s\n", + edi->vecs.linfix.neig, edi->vecs.linfix.neig != 1 ? "s" : ""); - fprintf(ed->edo, "# LINACC : %d vec%s\n", edi->vecs.linacc.neig, + fprintf(ed->edo, + "# LINACC : %d vec%s\n", + edi->vecs.linacc.neig, edi->vecs.linacc.neig != 1 ? "s" : ""); - fprintf(ed->edo, "# RADFIX : %d vec%s\n", edi->vecs.radfix.neig, + fprintf(ed->edo, + "# RADFIX : %d vec%s\n", + edi->vecs.radfix.neig, edi->vecs.radfix.neig != 1 ? "s" : ""); - fprintf(ed->edo, "# RADACC : %d vec%s\n", edi->vecs.radacc.neig, + fprintf(ed->edo, + "# RADACC : %d vec%s\n", + edi->vecs.radacc.neig, edi->vecs.radacc.neig != 1 ? "s" : ""); - fprintf(ed->edo, "# RADCON : %d vec%s\n", edi->vecs.radcon.neig, + fprintf(ed->edo, + "# RADCON : %d vec%s\n", + edi->vecs.radcon.neig, edi->vecs.radcon.neig != 1 ? "s" : ""); - fprintf(ed->edo, "# FLOODING : %d vec%s ", edi->flood.vecs.neig, - edi->flood.vecs.neig != 1 ? "s" : ""); + fprintf(ed->edo, "# FLOODING : %d vec%s ", edi->flood.vecs.neig, edi->flood.vecs.neig != 1 ? "s" : ""); if (edi->flood.vecs.neig) { @@ -2653,32 +2706,53 @@ static void write_edo_legend(gmx_edsam* ed, int nED, const gmx_output_env_t* oen nice_legend(&setname, &nsets, &LegendStr, "RMSD to ref", "nm", get_EDgroupChar(nr_edi, nED)); /* Essential dynamics, projections on eigenvectors */ - nice_legend_evec(&setname, &nsets, &LegendStr, &edi->vecs.mon, - get_EDgroupChar(nr_edi, nED), "MON"); - nice_legend_evec(&setname, &nsets, &LegendStr, &edi->vecs.linfix, - get_EDgroupChar(nr_edi, nED), "LINFIX"); - nice_legend_evec(&setname, &nsets, &LegendStr, &edi->vecs.linacc, - get_EDgroupChar(nr_edi, nED), "LINACC"); - nice_legend_evec(&setname, &nsets, &LegendStr, &edi->vecs.radfix, - get_EDgroupChar(nr_edi, nED), "RADFIX"); + nice_legend_evec(&setname, + &nsets, + &LegendStr, + &edi->vecs.mon, + get_EDgroupChar(nr_edi, nED), + "MON"); + nice_legend_evec(&setname, + &nsets, + &LegendStr, + &edi->vecs.linfix, + get_EDgroupChar(nr_edi, nED), + "LINFIX"); + nice_legend_evec(&setname, + &nsets, + &LegendStr, + &edi->vecs.linacc, + get_EDgroupChar(nr_edi, nED), + "LINACC"); + nice_legend_evec(&setname, + &nsets, + &LegendStr, + &edi->vecs.radfix, + get_EDgroupChar(nr_edi, nED), + "RADFIX"); if (edi->vecs.radfix.neig) { - nice_legend(&setname, &nsets, &LegendStr, "RADFIX radius", "nm", - get_EDgroupChar(nr_edi, nED)); + nice_legend(&setname, &nsets, &LegendStr, "RADFIX radius", "nm", get_EDgroupChar(nr_edi, nED)); } - nice_legend_evec(&setname, &nsets, &LegendStr, &edi->vecs.radacc, - get_EDgroupChar(nr_edi, nED), "RADACC"); + nice_legend_evec(&setname, + &nsets, + &LegendStr, + &edi->vecs.radacc, + get_EDgroupChar(nr_edi, nED), + "RADACC"); if (edi->vecs.radacc.neig) { - nice_legend(&setname, &nsets, &LegendStr, "RADACC radius", "nm", - get_EDgroupChar(nr_edi, nED)); + nice_legend(&setname, &nsets, &LegendStr, "RADACC radius", "nm", get_EDgroupChar(nr_edi, nED)); } - nice_legend_evec(&setname, &nsets, &LegendStr, &edi->vecs.radcon, - get_EDgroupChar(nr_edi, nED), "RADCON"); + nice_legend_evec(&setname, + &nsets, + &LegendStr, + &edi->vecs.radcon, + get_EDgroupChar(nr_edi, nED), + "RADCON"); if (edi->vecs.radcon.neig) { - nice_legend(&setname, &nsets, &LegendStr, "RADCON radius", "nm", - get_EDgroupChar(nr_edi, nED)); + nice_legend(&setname, &nsets, &LegendStr, "RADCON radius", "nm", get_EDgroupChar(nr_edi, nED)); } } ++edi; @@ -2691,7 +2765,10 @@ static void write_edo_legend(gmx_edsam* ed, int nED, const gmx_output_env_t* oen fprintf(ed->edo, "#\n" "# Legend for %d column%s of flooding plus %d column%s of essential dynamics data:\n", - n_flood, 1 == n_flood ? "" : "s", n_edsam, 1 == n_edsam ? "" : "s"); + n_flood, + 1 == n_flood ? "" : "s", + n_edsam, + 1 == n_edsam ? "" : "s"); fprintf(ed->edo, "%s", LegendStr); sfree(LegendStr); @@ -2832,7 +2909,8 @@ std::unique_ptr init_edsam(const gmx::MDLogger& m /* Output how well we fit to the reference at the start */ translate_and_rotate(xfit, edi->sref.nr, fit_transvec, fit_rotmat); - fprintf(stderr, "ED: Initial RMSD from reference after fit = %f nm", + fprintf(stderr, + "ED: Initial RMSD from reference after fit = %f nm", rmsd_from_structure(xfit, &edi->sref)); if (EDstate->nED > 1) { @@ -2954,12 +3032,13 @@ std::unique_ptr init_edsam(const gmx::MDLogger& m { for (i = 0; i < edi->flood.vecs.neig; i++) { - fprintf(stdout, "ED: EV %d flooding potential center: %11.4e", - edi->flood.vecs.ieig[i], edi->flood.vecs.refproj[i]); + fprintf(stdout, + "ED: EV %d flooding potential center: %11.4e", + edi->flood.vecs.ieig[i], + edi->flood.vecs.refproj[i]); if (edi->flood.bHarmonic) { - fprintf(stdout, " (adding %11.4e/timestep)", - edi->flood.referenceProjectionSlope[i]); + fprintf(stdout, " (adding %11.4e/timestep)", edi->flood.referenceProjectionSlope[i]); } fprintf(stdout, "\n"); } @@ -3106,17 +3185,34 @@ void do_edsam(const t_inputrec* ir, int64_t step, const t_commrec* cr, rvec xs[] * the collective buf->xcoll array. Note that for edinr > 1 * xs could already have been modified by an earlier ED */ - communicate_group_positions(cr, buf->xcoll, buf->shifts_xcoll, buf->extra_shifts_xcoll, - PAR(cr) ? buf->bUpdateShifts : TRUE, xs, edi.sav.nr, edi.sav.nr_loc, - edi.sav.anrs_loc, edi.sav.c_ind, edi.sav.x_old, box); + communicate_group_positions(cr, + buf->xcoll, + buf->shifts_xcoll, + buf->extra_shifts_xcoll, + PAR(cr) ? buf->bUpdateShifts : TRUE, + xs, + edi.sav.nr, + edi.sav.nr_loc, + edi.sav.anrs_loc, + edi.sav.c_ind, + edi.sav.x_old, + box); /* Only assembly reference positions if their indices differ from the average ones */ if (!edi.bRefEqAv) { - communicate_group_positions( - cr, buf->xc_ref, buf->shifts_xc_ref, buf->extra_shifts_xc_ref, - PAR(cr) ? buf->bUpdateShifts : TRUE, xs, edi.sref.nr, edi.sref.nr_loc, - edi.sref.anrs_loc, edi.sref.c_ind, edi.sref.x_old, box); + communicate_group_positions(cr, + buf->xc_ref, + buf->shifts_xc_ref, + buf->extra_shifts_xc_ref, + PAR(cr) ? buf->bUpdateShifts : TRUE, + xs, + edi.sref.nr, + edi.sref.nr_loc, + edi.sref.anrs_loc, + edi.sref.c_ind, + edi.sref.x_old, + box); } /* If bUpdateShifts was TRUE then the shifts have just been updated in communicate_group_positions. @@ -3212,8 +3308,8 @@ void do_edsam(const t_inputrec* ir, int64_t step, const t_commrec* cr, rvec xs[] for (i = 0; i < edi.sav.nr_loc; i++) { /* Unshift local ED coordinate and store in x_unsh */ - ed_unshift_single_coord(box, buf->xcoll[edi.sav.c_ind[i]], - buf->shifts_xcoll[edi.sav.c_ind[i]], x_unsh); + ed_unshift_single_coord( + box, buf->xcoll[edi.sav.c_ind[i]], buf->shifts_xcoll[edi.sav.c_ind[i]], x_unsh); /* dx is the ED correction to the positions: */ rvec_sub(x_unsh, xs[edi.sav.anrs_loc[i]], dx); diff --git a/src/gromacs/ewald/long_range_correction.cpp b/src/gromacs/ewald/long_range_correction.cpp index b62a25e58c..b75afe50be 100644 --- a/src/gromacs/ewald/long_range_correction.cpp +++ b/src/gromacs/ewald/long_range_correction.cpp @@ -237,14 +237,17 @@ void ewald_LRcorrection(const int numAtomsLocal, if (debug) { fprintf(debug, "Long Range corrections for Ewald interactions:\n"); - fprintf(debug, "q2sum = %g, Vself_q=%g\n", L1_q * fr.q2sum[0] + lambda_q * fr.q2sum[1], + fprintf(debug, + "q2sum = %g, Vself_q=%g\n", + L1_q * fr.q2sum[0] + lambda_q * fr.q2sum[1], L1_q * Vself_q[0] + lambda_q * Vself_q[1]); fprintf(debug, "Electrostatic Long Range correction: Vexcl=%g\n", Vexcl_q); if (MASTER(cr) && thread == 0) { if (ir.epsilon_surface > 0 || ir.ewald_geometry == eewg3DC) { - fprintf(debug, "Total dipole correction: Vdipole=%g\n", + fprintf(debug, + "Total dipole correction: Vdipole=%g\n", L1_q * Vdipole[0] + lambda_q * Vdipole[1]); } } diff --git a/src/gromacs/ewald/pme.cpp b/src/gromacs/ewald/pme.cpp index 76051509ec..0daeb03685 100644 --- a/src/gromacs/ewald/pme.cpp +++ b/src/gromacs/ewald/pme.cpp @@ -475,8 +475,18 @@ static void init_overlap_comm(pme_overlap_t* ol, int norder, MPI_Comm comm, int MPI_Status stat; for (size_t b = 0; b < ol->comm_data.size(); b++) { - MPI_Sendrecv(&ol->send_size, 1, MPI_INT, ol->comm_data[b].send_id, b, &ol->comm_data[b].recv_size, - 1, MPI_INT, ol->comm_data[b].recv_id, b, ol->mpi_comm, &stat); + MPI_Sendrecv(&ol->send_size, + 1, + MPI_INT, + ol->comm_data[b].send_id, + b, + &ol->comm_data[b].recv_size, + 1, + MPI_INT, + ol->comm_data[b].recv_id, + b, + ol->mpi_comm, + &stat); } #endif @@ -514,7 +524,8 @@ bool gmx_pme_check_restrictions(int pme_order, int nkx, int nky, int nkz, int nu std::string message = gmx::formatString( "pme_order (%d) is larger than the maximum allowed value (%d). Modify and " "recompile the code if you really need such a high order.", - pme_order, PME_ORDER_MAX); + pme_order, + PME_ORDER_MAX); GMX_THROW(gmx::InconsistentInputError(message)); } @@ -545,7 +556,8 @@ bool gmx_pme_check_restrictions(int pme_order, int nkx, int nky, int nkz, int nu "threads, the number of grid lines per rank along x should be >= pme_order (%d) " "or = pmeorder-1. To resolve this issue, use fewer ranks along x (and possibly " "more along y and/or z) by specifying -dd manually.", - nkx / static_cast(numPmeDomainsAlongX), pme_order); + nkx / static_cast(numPmeDomainsAlongX), + pme_order); } return true; @@ -649,9 +661,13 @@ gmx_pme_t* gmx_pme_init(const t_commrec* cr, pme->ndecompdim = 2; #if GMX_MPI - MPI_Comm_split(pme->mpi_comm, pme->nodeid % numPmeDomains.y, pme->nodeid, + MPI_Comm_split(pme->mpi_comm, + pme->nodeid % numPmeDomains.y, + pme->nodeid, &pme->mpi_comm_d[0]); /* My communicator along major dimension */ - MPI_Comm_split(pme->mpi_comm, pme->nodeid / numPmeDomains.y, pme->nodeid, + MPI_Comm_split(pme->mpi_comm, + pme->nodeid / numPmeDomains.y, + pme->nodeid, &pme->mpi_comm_d[1]); /* My communicator along minor dimension */ MPI_Comm_rank(pme->mpi_comm_d[0], &pme->nodeid_major); @@ -719,8 +735,8 @@ gmx_pme_t* gmx_pme_init(const t_commrec* cr, pme->boxScaler = new EwaldBoxZScaler(*ir); /* If we violate restrictions, generate a fatal error here */ - gmx_pme_check_restrictions(pme->pme_order, pme->nkx, pme->nky, pme->nkz, pme->nnodes_major, - pme->bUseThreads, true); + gmx_pme_check_restrictions( + pme->pme_order, pme->nkx, pme->nky, pme->nkz, pme->nnodes_major, pme->bUseThreads, true); if (pme->nnodes > 1) { @@ -751,8 +767,13 @@ gmx_pme_t* gmx_pme_init(const t_commrec* cr, " and PME grid_y (%d) and grid_z (%d) should be divisible by " "#PME_ranks_y " "(%d)", - gmx::roundToInt((imbal - 1) * 100), pme->nkx, pme->nky, - pme->nnodes_major, pme->nky, pme->nkz, pme->nnodes_minor); + gmx::roundToInt((imbal - 1) * 100), + pme->nkx, + pme->nky, + pme->nnodes_major, + pme->nky, + pme->nkz, + pme->nnodes_minor); } } @@ -761,8 +782,12 @@ gmx_pme_t* gmx_pme_init(const t_commrec* cr, * y is always copied through a buffer: we don't need padding in z, * but we do need the overlap in x because of the communication order. */ - init_overlap_comm(&pme->overlap[0], pme->pme_order, pme->mpi_comm_d[0], pme->nnodes_major, - pme->nodeid_major, pme->nkx, + init_overlap_comm(&pme->overlap[0], + pme->pme_order, + pme->mpi_comm_d[0], + pme->nnodes_major, + pme->nodeid_major, + pme->nkx, (div_round_up(pme->nky, pme->nnodes_minor) + pme->pme_order) * (pme->nkz + pme->pme_order - 1)); @@ -770,8 +795,12 @@ gmx_pme_t* gmx_pme_init(const t_commrec* cr, * We do this with an offset buffer of equal size, so we need to allocate * extra for the offset. That's what the (+1)*pme->nkz is for. */ - init_overlap_comm(&pme->overlap[1], pme->pme_order, pme->mpi_comm_d[1], pme->nnodes_minor, - pme->nodeid_minor, pme->nky, + init_overlap_comm(&pme->overlap[1], + pme->pme_order, + pme->mpi_comm_d[1], + pme->nnodes_minor, + pme->nodeid_minor, + pme->nky, (div_round_up(pme->nkx, pme->nnodes_major) + pme->pme_order + 1) * pme->nkz); /* Double-check for a limitation of the (current) sum_fftgrid_dd code. @@ -803,12 +832,12 @@ gmx_pme_t* gmx_pme_init(const t_commrec* cr, pme->pmegrid_start_iy = pme->overlap[1].s2g0[pme->nodeid_minor]; pme->pmegrid_start_iz = 0; - make_gridindex_to_localindex(pme->nkx, pme->pmegrid_start_ix, - pme->pmegrid_nx - (pme->pme_order - 1), &pme->nnx, &pme->fshx); - make_gridindex_to_localindex(pme->nky, pme->pmegrid_start_iy, - pme->pmegrid_ny - (pme->pme_order - 1), &pme->nny, &pme->fshy); - make_gridindex_to_localindex(pme->nkz, pme->pmegrid_start_iz, pme->pmegrid_nz_base, &pme->nnz, - &pme->fshz); + make_gridindex_to_localindex( + pme->nkx, pme->pmegrid_start_ix, pme->pmegrid_nx - (pme->pme_order - 1), &pme->nnx, &pme->fshx); + make_gridindex_to_localindex( + pme->nky, pme->pmegrid_start_iy, pme->pmegrid_ny - (pme->pme_order - 1), &pme->nny, &pme->fshy); + make_gridindex_to_localindex( + pme->nkz, pme->pmegrid_start_iz, pme->pmegrid_nz_base, &pme->nnz, &pme->fshz); pme->spline_work = make_pme_spline_work(pme->pme_order); @@ -836,8 +865,14 @@ gmx_pme_t* gmx_pme_init(const t_commrec* cr, || (i >= DO_Q && pme->doLJ && (i == 2 || bFreeEnergy_lj || ir->ljpme_combination_rule == eljpmeLB))) { - pmegrids_init(&pme->pmegrid[i], pme->pmegrid_nx, pme->pmegrid_ny, pme->pmegrid_nz, - pme->pmegrid_nz_base, pme->pme_order, pme->bUseThreads, pme->nthread, + pmegrids_init(&pme->pmegrid[i], + pme->pmegrid_nx, + pme->pmegrid_ny, + pme->pmegrid_nz, + pme->pmegrid_nz_base, + pme->pme_order, + pme->bUseThreads, + pme->nthread, pme->overlap[0].s2g1[pme->nodeid_major] - pme->overlap[0].s2g0[pme->nodeid_major + 1], pme->overlap[1].s2g1[pme->nodeid_minor] @@ -846,8 +881,14 @@ gmx_pme_t* gmx_pme_init(const t_commrec* cr, const auto allocateRealGridForGpu = (pme->runMode == PmeRunMode::Mixed) ? gmx::PinningPolicy::PinnedIfSupported : gmx::PinningPolicy::CannotBePinned; - gmx_parallel_3dfft_init(&pme->pfft_setup[i], ndata, &pme->fftgrid[i], &pme->cfftgrid[i], - pme->mpi_comm_d, bReproducible, pme->nthread, allocateRealGridForGpu); + gmx_parallel_3dfft_init(&pme->pfft_setup[i], + ndata, + &pme->fftgrid[i], + &pme->cfftgrid[i], + pme->mpi_comm_d, + bReproducible, + pme->nthread, + allocateRealGridForGpu); } } @@ -928,9 +969,21 @@ void gmx_pme_reinit(struct gmx_pme_t** pmedata, const gmx::MDLogger dummyLogger; GMX_ASSERT(pmedata, "Invalid PME pointer"); NumPmeDomains numPmeDomains = { pme_src->nnodes_major, pme_src->nnodes_minor }; - *pmedata = gmx_pme_init(cr, numPmeDomains, &irc, pme_src->bFEP_q, pme_src->bFEP_lj, FALSE, - ewaldcoeff_q, ewaldcoeff_lj, pme_src->nthread, pme_src->runMode, - pme_src->gpu, nullptr, nullptr, nullptr, dummyLogger); + *pmedata = gmx_pme_init(cr, + numPmeDomains, + &irc, + pme_src->bFEP_q, + pme_src->bFEP_lj, + FALSE, + ewaldcoeff_q, + ewaldcoeff_lj, + pme_src->nthread, + pme_src->runMode, + pme_src->gpu, + nullptr, + nullptr, + nullptr, + dummyLogger); /* When running PME on the CPU not using domain decomposition, * the atom data is allocated once only in gmx_pme_(re)init(). */ @@ -1216,16 +1269,23 @@ int gmx_pme_do(struct gmx_pme_t* pme, } if (grid_index < DO_Q) { - loop_count = solve_pme_yzx( - pme, cfftgrid, scaledBox[XX][XX] * scaledBox[YY][YY] * scaledBox[ZZ][ZZ], - computeEnergyAndVirial, pme->nthread, thread); + loop_count = solve_pme_yzx(pme, + cfftgrid, + scaledBox[XX][XX] * scaledBox[YY][YY] * scaledBox[ZZ][ZZ], + computeEnergyAndVirial, + pme->nthread, + thread); } else { loop_count = - solve_pme_lj_yzx(pme, &cfftgrid, FALSE, + solve_pme_lj_yzx(pme, + &cfftgrid, + FALSE, scaledBox[XX][XX] * scaledBox[YY][YY] * scaledBox[ZZ][ZZ], - computeEnergyAndVirial, pme->nthread, thread); + computeEnergyAndVirial, + pme->nthread, + thread); } if (thread == 0) @@ -1290,15 +1350,18 @@ int gmx_pme_do(struct gmx_pme_t* pme, { try { - gather_f_bsplines(pme, grid, bClearF, &atc, &atc.spline[thread], + gather_f_bsplines(pme, + grid, + bClearF, + &atc, + &atc.spline[thread], pme->bFEP ? (grid_index % 2 == 0 ? 1.0 - lambda : lambda) : 1.0); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR } - inc_nrnb(nrnb, eNR_GATHERFBSP, - pme->pme_order * pme->pme_order * pme->pme_order * atc.numAtoms()); + inc_nrnb(nrnb, eNR_GATHERFBSP, pme->pme_order * pme->pme_order * pme->pme_order * atc.numAtoms()); /* Note: this wallcycle region is opened above inside an OpenMP region, so take care if refactoring code here. */ wallcycle_stop(wcycle, ewcPME_GATHER); @@ -1405,7 +1468,8 @@ int gmx_pme_do(struct gmx_pme_t* pme, inc_nrnb(nrnb, eNR_WEIGHTS, DIM * atc.numAtoms()); } - inc_nrnb(nrnb, eNR_SPREADBSP, + inc_nrnb(nrnb, + eNR_SPREADBSP, pme->pme_order * pme->pme_order * pme->pme_order * atc.numAtoms()); if (pme->nthread == 1) { @@ -1454,9 +1518,13 @@ int gmx_pme_do(struct gmx_pme_t* pme, } loop_count = - solve_pme_lj_yzx(pme, &pme->cfftgrid[2], TRUE, + solve_pme_lj_yzx(pme, + &pme->cfftgrid[2], + TRUE, scaledBox[XX][XX] * scaledBox[YY][YY] * scaledBox[ZZ][ZZ], - computeEnergyAndVirial, pme->nthread, thread); + computeEnergyAndVirial, + pme->nthread, + thread); if (thread == 0) { wallcycle_stop(wcycle, ewcLJPME); @@ -1535,14 +1603,15 @@ int gmx_pme_do(struct gmx_pme_t* pme, { try { - gather_f_bsplines(pme, grid, bClearF, &pme->atc[0], - &pme->atc[0].spline[thread], scale); + gather_f_bsplines( + pme, grid, bClearF, &pme->atc[0], &pme->atc[0].spline[thread], scale); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR } - inc_nrnb(nrnb, eNR_GATHERFBSP, + inc_nrnb(nrnb, + eNR_GATHERFBSP, pme->pme_order * pme->pme_order * pme->pme_order * pme->atc[0].numAtoms()); } wallcycle_stop(wcycle, ewcPME_GATHER); diff --git a/src/gromacs/ewald/pme_coordinate_receiver_gpu_impl.cu b/src/gromacs/ewald/pme_coordinate_receiver_gpu_impl.cu index db81fb7b0a..b37e3ec41d 100644 --- a/src/gromacs/ewald/pme_coordinate_receiver_gpu_impl.cu +++ b/src/gromacs/ewald/pme_coordinate_receiver_gpu_impl.cu @@ -99,8 +99,7 @@ void PmeCoordinateReceiverGpu::Impl::launchReceiveCoordinatesFromPpCudaDirect(in #if GMX_MPI // Receive event from PP task - MPI_Irecv(&ppSync_[recvCount_], sizeof(GpuEventSynchronizer*), MPI_BYTE, ppRank, 0, comm_, - &request_[recvCount_]); + MPI_Irecv(&ppSync_[recvCount_], sizeof(GpuEventSynchronizer*), MPI_BYTE, ppRank, 0, comm_, &request_[recvCount_]); recvCount_++; #else GMX_UNUSED_VALUE(ppRank); diff --git a/src/gromacs/ewald/pme_gather.clh b/src/gromacs/ewald/pme_gather.clh index 98cac0f282..361461b417 100644 --- a/src/gromacs/ewald/pme_gather.clh +++ b/src/gromacs/ewald/pme_gather.clh @@ -390,8 +390,8 @@ __kernel void CUSTOMIZED_KERNEL_NAME(pme_gather_kernel)(const struct PmeOpenCLKe if (chargeCheck) { - sumForceComponents(&fx, &fy, &fz, ixBase, nx, pny, pnz, constOffset, splineIndexBase, tdy, - tdz, sm_splineParams, gm_gridA); + sumForceComponents( + &fx, &fy, &fz, ixBase, nx, pny, pnz, constOffset, splineIndexBase, tdy, tdz, sm_splineParams, gm_gridA); } // Reduction of partial force contributions @@ -400,8 +400,16 @@ __kernel void CUSTOMIZED_KERNEL_NAME(pme_gather_kernel)(const struct PmeOpenCLKe __local float sm_forceReduction[totalSharedMemory]; __local float* sm_forceTemp[DIM]; - reduce_atom_forces(sm_forces, atomIndexLocal, splineIndex, lineIndex, - kernelParams.grid.realGridSizeFP, fx, fy, fz, sm_forceReduction, sm_forceTemp); + reduce_atom_forces(sm_forces, + atomIndexLocal, + splineIndex, + lineIndex, + kernelParams.grid.realGridSizeFP, + fx, + fy, + fz, + sm_forceReduction, + sm_forceTemp); barrier(CLK_LOCAL_MEM_FENCE); /* Calculating the final forces with no component branching, atomsPerBlock threads */ @@ -410,8 +418,8 @@ __kernel void CUSTOMIZED_KERNEL_NAME(pme_gather_kernel)(const struct PmeOpenCLKe const float scale = kernelParams.current.scale; if (forceIndexLocal < atomsPerBlock) { - calculateAndStoreGridForces(sm_forces, forceIndexLocal, forceIndexGlobal, - kernelParams.current.recipBox, scale, gm_coefficientsA); + calculateAndStoreGridForces( + sm_forces, forceIndexLocal, forceIndexGlobal, kernelParams.current.recipBox, scale, gm_coefficientsA); } #if !defined(_AMD_SOURCE_) && !defined(_NVIDIA_SOURCE_) @@ -448,16 +456,28 @@ __kernel void CUSTOMIZED_KERNEL_NAME(pme_gather_kernel)(const struct PmeOpenCLKe chargeCheck = pme_gpu_check_atom_charge(gm_coefficientsB[atomIndexGlobal]); if (chargeCheck) { - sumForceComponents(&fx, &fy, &fz, ixBase, nx, pny, pnz, constOffset, splineIndexBase, - tdy, tdz, sm_splineParams, gm_gridB); + sumForceComponents( + &fx, &fy, &fz, ixBase, nx, pny, pnz, constOffset, splineIndexBase, tdy, tdz, sm_splineParams, gm_gridB); } - reduce_atom_forces(sm_forces, atomIndexLocal, splineIndex, lineIndex, - kernelParams.grid.realGridSizeFP, fx, fy, fz, sm_forceReduction, sm_forceTemp); + reduce_atom_forces(sm_forces, + atomIndexLocal, + splineIndex, + lineIndex, + kernelParams.grid.realGridSizeFP, + fx, + fy, + fz, + sm_forceReduction, + sm_forceTemp); barrier(CLK_LOCAL_MEM_FENCE); if (forceIndexLocal < atomsPerBlock) { - calculateAndStoreGridForces(sm_forces, forceIndexLocal, forceIndexGlobal, - kernelParams.current.recipBox, 1.0F - scale, gm_coefficientsB); + calculateAndStoreGridForces(sm_forces, + forceIndexLocal, + forceIndexGlobal, + kernelParams.current.recipBox, + 1.0F - scale, + gm_coefficientsB); } #if !defined(_AMD_SOURCE_) && !defined(_NVIDIA_SOURCE_) diff --git a/src/gromacs/ewald/pme_gather.cu b/src/gromacs/ewald/pme_gather.cu index 160f544d3e..a81791765c 100644 --- a/src/gromacs/ewald/pme_gather.cu +++ b/src/gromacs/ewald/pme_gather.cu @@ -494,14 +494,29 @@ __launch_bounds__(c_gatherMaxThreadsPerBlock, c_gatherMinBlocksPerMP) __global__ const int ithyMax = (threadsPerAtom == ThreadsPerAtom::Order) ? order : threadIdx.y + 1; if (chargeCheck) { - sumForceComponents( - &fx, &fy, &fz, ithyMin, ithyMax, ixBase, iz, nx, ny, pny, pnz, atomIndexLocal, - splineIndexBase, tdz, sm_gridlineIndices, sm_theta, sm_dtheta, gm_gridA); + sumForceComponents(&fx, + &fy, + &fz, + ithyMin, + ithyMax, + ixBase, + iz, + nx, + ny, + pny, + pnz, + atomIndexLocal, + splineIndexBase, + tdz, + sm_gridlineIndices, + sm_theta, + sm_dtheta, + gm_gridA); } // Reduction of partial force contributions __shared__ float3 sm_forces[atomsPerBlock]; - reduce_atom_forces(sm_forces, atomIndexLocal, splineIndex, lineIndex, - kernelParams.grid.realGridSizeFP, fx, fy, fz); + reduce_atom_forces( + sm_forces, atomIndexLocal, splineIndex, lineIndex, kernelParams.grid.realGridSizeFP, fx, fy, fz); __syncthreads(); /* Calculating the final forces with no component branching, atomsPerBlock threads */ @@ -510,8 +525,8 @@ __launch_bounds__(c_gatherMaxThreadsPerBlock, c_gatherMinBlocksPerMP) __global__ const float scale = kernelParams.current.scale; if (forceIndexLocal < atomsPerBlock) { - calculateAndStoreGridForces(sm_forces, forceIndexLocal, forceIndexGlobal, - kernelParams.current.recipBox, scale, gm_coefficientsA); + calculateAndStoreGridForces( + sm_forces, forceIndexLocal, forceIndexGlobal, kernelParams.current.recipBox, scale, gm_coefficientsA); } __syncwarp(); @@ -543,21 +558,39 @@ __launch_bounds__(c_gatherMaxThreadsPerBlock, c_gatherMinBlocksPerMP) __global__ const int chargeCheck = pme_gpu_check_atom_charge(gm_coefficientsB[atomIndexGlobal]); if (chargeCheck) { - sumForceComponents( - &fx, &fy, &fz, ithyMin, ithyMax, ixBase, iz, nx, ny, pny, pnz, atomIndexLocal, - splineIndexBase, tdz, sm_gridlineIndices, sm_theta, sm_dtheta, gm_gridB); + sumForceComponents(&fx, + &fy, + &fz, + ithyMin, + ithyMax, + ixBase, + iz, + nx, + ny, + pny, + pnz, + atomIndexLocal, + splineIndexBase, + tdz, + sm_gridlineIndices, + sm_theta, + sm_dtheta, + gm_gridB); } // Reduction of partial force contributions - reduce_atom_forces(sm_forces, atomIndexLocal, splineIndex, - lineIndex, kernelParams.grid.realGridSizeFP, - fx, fy, fz); + reduce_atom_forces( + sm_forces, atomIndexLocal, splineIndex, lineIndex, kernelParams.grid.realGridSizeFP, fx, fy, fz); __syncthreads(); /* Calculating the final forces with no component branching, atomsPerBlock threads */ if (forceIndexLocal < atomsPerBlock) { - calculateAndStoreGridForces(sm_forces, forceIndexLocal, forceIndexGlobal, - kernelParams.current.recipBox, 1.0F - scale, gm_coefficientsB); + calculateAndStoreGridForces(sm_forces, + forceIndexLocal, + forceIndexGlobal, + kernelParams.current.recipBox, + 1.0F - scale, + gm_coefficientsB); } __syncwarp(); diff --git a/src/gromacs/ewald/pme_gpu.cpp b/src/gromacs/ewald/pme_gpu.cpp index fcae02ab69..b90170a045 100644 --- a/src/gromacs/ewald/pme_gpu.cpp +++ b/src/gromacs/ewald/pme_gpu.cpp @@ -260,8 +260,7 @@ void pme_gpu_launch_complex_transforms(gmx_pme_t* pme, gmx_wallcycle* wcycle, co #pragma omp parallel for num_threads(pme->nthread) schedule(static) for (int thread = 0; thread < pme->nthread; thread++) { - solve_pme_yzx(pme, cfftgrid, pme->boxVolume, computeEnergyAndVirial, - pme->nthread, thread); + solve_pme_yzx(pme, cfftgrid, pme->boxVolume, computeEnergyAndVirial, pme->nthread, thread); } wallcycle_stop(wcycle, ewcPME_SOLVE_MIXED_MODE); } @@ -373,8 +372,8 @@ bool pme_gpu_try_finish_task(gmx_pme_t* pme, pme_gpu_update_timings(pme->gpu); // There's no support for computing energy without virial, or vice versa const bool computeEnergyAndVirial = stepWork.computeEnergy || stepWork.computeVirial; - PmeOutput output = pme_gpu_getOutput(*pme, computeEnergyAndVirial, - pme->gpu->common->ngrids > 1 ? lambdaQ : 1.0); + PmeOutput output = pme_gpu_getOutput( + *pme, computeEnergyAndVirial, pme->gpu->common->ngrids > 1 ? lambdaQ : 1.0); wallcycle_stop(wcycle, ewcWAIT_GPU_PME_GATHER); GMX_ASSERT(pme->gpu->settings.useGpuForceReduction == !output.haveForceOutput_, @@ -402,8 +401,8 @@ PmeOutput pme_gpu_wait_finish_task(gmx_pme_t* pme, pme_gpu_synchronize(pme->gpu); } - PmeOutput output = pme_gpu_getOutput(*pme, computeEnergyAndVirial, - pme->gpu->common->ngrids > 1 ? lambdaQ : 1.0); + PmeOutput output = pme_gpu_getOutput( + *pme, computeEnergyAndVirial, pme->gpu->common->ngrids > 1 ? lambdaQ : 1.0); wallcycle_stop(wcycle, ewcWAIT_GPU_PME_GATHER); return output; } diff --git a/src/gromacs/ewald/pme_gpu_3dfft.cu b/src/gromacs/ewald/pme_gpu_3dfft.cu index ec928f745a..1a8e9c577b 100644 --- a/src/gromacs/ewald/pme_gpu_3dfft.cu +++ b/src/gromacs/ewald/pme_gpu_3dfft.cu @@ -95,13 +95,30 @@ GpuParallel3dFft::GpuParallel3dFft(const PmeGpu* pmeGpu, const int gridIndex) */ const int rank = 3, batch = 1; - result = cufftPlanMany(&planR2C_, rank, realGridSize, realGridSizePadded, 1, realGridSizePaddedTotal, - complexGridSizePadded, 1, complexGridSizePaddedTotal, CUFFT_R2C, batch); + result = cufftPlanMany(&planR2C_, + rank, + realGridSize, + realGridSizePadded, + 1, + realGridSizePaddedTotal, + complexGridSizePadded, + 1, + complexGridSizePaddedTotal, + CUFFT_R2C, + batch); handleCufftError(result, "cufftPlanMany R2C plan failure"); - result = cufftPlanMany(&planC2R_, rank, realGridSize, complexGridSizePadded, 1, - complexGridSizePaddedTotal, realGridSizePadded, 1, - realGridSizePaddedTotal, CUFFT_C2R, batch); + result = cufftPlanMany(&planC2R_, + rank, + realGridSize, + complexGridSizePadded, + 1, + complexGridSizePaddedTotal, + realGridSizePadded, + 1, + realGridSizePaddedTotal, + CUFFT_C2R, + batch); handleCufftError(result, "cufftPlanMany C2R plan failure"); cudaStream_t stream = pmeGpu->archSpecific->pmeStream_.stream(); diff --git a/src/gromacs/ewald/pme_gpu_3dfft_ocl.cpp b/src/gromacs/ewald/pme_gpu_3dfft_ocl.cpp index 4ba6649497..f9a5f11f06 100644 --- a/src/gromacs/ewald/pme_gpu_3dfft_ocl.cpp +++ b/src/gromacs/ewald/pme_gpu_3dfft_ocl.cpp @@ -89,10 +89,12 @@ GpuParallel3dFft::GpuParallel3dFft(const PmeGpu* pmeGpu, const int gridIndex) // clFFT expects row-major, so dimensions/strides are reversed (ZYX instead of XYZ) std::array realGridDimensions = { realGridSize[ZZ], realGridSize[YY], realGridSize[XX] }; - std::array realGridStrides = { 1, realGridSizePadded[ZZ], + std::array realGridStrides = { 1, + realGridSizePadded[ZZ], realGridSizePadded[YY] * realGridSizePadded[ZZ] }; - std::array complexGridStrides = { 1, complexGridSizePadded[ZZ], - complexGridSizePadded[YY] * complexGridSizePadded[ZZ] }; + std::array complexGridStrides = { + 1, complexGridSizePadded[ZZ], complexGridSizePadded[YY] * complexGridSizePadded[ZZ] + }; constexpr clfftDim dims = CLFFT_3D; handleClfftError(clfftCreateDefaultPlan(&planR2C_, context, dims, realGridDimensions.data()), @@ -166,8 +168,15 @@ void GpuParallel3dFft::perform3dFft(gmx_fft_direction dir, CommandEvent* timingE GMX_THROW( gmx::NotImplementedError("The chosen 3D-FFT case is not implemented on GPUs")); } - handleClfftError(clfftEnqueueTransform(plan, direction, deviceStreams_.size(), - deviceStreams_.data(), waitEvents.size(), waitEvents.data(), - timingEvent, inputGrids, outputGrids, tempBuffer), + handleClfftError(clfftEnqueueTransform(plan, + direction, + deviceStreams_.size(), + deviceStreams_.data(), + waitEvents.size(), + waitEvents.data(), + timingEvent, + inputGrids, + outputGrids, + tempBuffer), "clFFT execution failure"); } diff --git a/src/gromacs/ewald/pme_gpu_calculate_splines.cuh b/src/gromacs/ewald/pme_gpu_calculate_splines.cuh index fc319eb1c2..8e8496da8f 100644 --- a/src/gromacs/ewald/pme_gpu_calculate_splines.cuh +++ b/src/gromacs/ewald/pme_gpu_calculate_splines.cuh @@ -277,12 +277,12 @@ __device__ __forceinline__ void calculate_splines(const PmeGpuCudaKernelParams k // TODO have shared table for both parameters to share the fetch, as index is always same? // TODO compare texture/LDG performance - sm_fractCoords[sharedMemoryIndex] += - fetchFromParamLookupTable(kernelParams.grid.d_fractShiftsTable, - kernelParams.fractShiftsTableTexture, tableIndex); + sm_fractCoords[sharedMemoryIndex] += fetchFromParamLookupTable( + kernelParams.grid.d_fractShiftsTable, kernelParams.fractShiftsTableTexture, tableIndex); sm_gridlineIndices[sharedMemoryIndex] = fetchFromParamLookupTable(kernelParams.grid.d_gridlineIndicesTable, - kernelParams.gridlineIndicesTableTexture, tableIndex); + kernelParams.gridlineIndicesTableTexture, + tableIndex); if (writeGlobal) { gm_gridlineIndices[atomIndexOffset * DIM + sharedMemoryIndex] = diff --git a/src/gromacs/ewald/pme_gpu_internal.cpp b/src/gromacs/ewald/pme_gpu_internal.cpp index c67e471ca3..e78373ec8b 100644 --- a/src/gromacs/ewald/pme_gpu_internal.cpp +++ b/src/gromacs/ewald/pme_gpu_internal.cpp @@ -142,7 +142,8 @@ void pme_gpu_alloc_energy_virial(PmeGpu* pmeGpu) for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++) { allocateDeviceBuffer(&pmeGpu->kernelParams->constants.d_virialAndEnergy[gridIndex], - c_virialAndEnergyCount, pmeGpu->archSpecific->deviceContext_); + c_virialAndEnergyCount, + pmeGpu->archSpecific->deviceContext_); pmalloc(reinterpret_cast(&pmeGpu->staging.h_virialAndEnergy[gridIndex]), energyAndVirialSize); } } @@ -161,8 +162,10 @@ void pme_gpu_clear_energy_virial(const PmeGpu* pmeGpu) { for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++) { - clearDeviceBufferAsync(&pmeGpu->kernelParams->constants.d_virialAndEnergy[gridIndex], 0, - c_virialAndEnergyCount, pmeGpu->archSpecific->pmeStream_); + clearDeviceBufferAsync(&pmeGpu->kernelParams->constants.d_virialAndEnergy[gridIndex], + 0, + c_virialAndEnergyCount, + pmeGpu->archSpecific->pmeStream_); } } @@ -174,7 +177,8 @@ void pme_gpu_realloc_and_copy_bspline_values(PmeGpu* pmeGpu, const int gridIndex GMX_ASSERT(gridIndex < pmeGpu->common->ngrids, "Invalid combination of gridIndex and number of grids"); - const int splineValuesOffset[DIM] = { 0, pmeGpu->kernelParams->grid.realGridSize[XX], + const int splineValuesOffset[DIM] = { 0, + pmeGpu->kernelParams->grid.realGridSize[XX], pmeGpu->kernelParams->grid.realGridSize[XX] + pmeGpu->kernelParams->grid.realGridSize[YY] }; memcpy(&pmeGpu->kernelParams->grid.splineValuesOffset, &splineValuesOffset, sizeof(splineValuesOffset)); @@ -184,7 +188,8 @@ void pme_gpu_realloc_and_copy_bspline_values(PmeGpu* pmeGpu, const int gridIndex + pmeGpu->kernelParams->grid.realGridSize[ZZ]; const bool shouldRealloc = (newSplineValuesSize > pmeGpu->archSpecific->splineValuesSize[gridIndex]); reallocateDeviceBuffer(&pmeGpu->kernelParams->grid.d_splineModuli[gridIndex], - newSplineValuesSize, &pmeGpu->archSpecific->splineValuesSize[gridIndex], + newSplineValuesSize, + &pmeGpu->archSpecific->splineValuesSize[gridIndex], &pmeGpu->archSpecific->splineValuesCapacity[gridIndex], pmeGpu->archSpecific->deviceContext_); if (shouldRealloc) @@ -197,12 +202,17 @@ void pme_gpu_realloc_and_copy_bspline_values(PmeGpu* pmeGpu, const int gridIndex for (int i = 0; i < DIM; i++) { memcpy(pmeGpu->staging.h_splineModuli[gridIndex] + splineValuesOffset[i], - pmeGpu->common->bsp_mod[i].data(), pmeGpu->common->bsp_mod[i].size() * sizeof(float)); + pmeGpu->common->bsp_mod[i].data(), + pmeGpu->common->bsp_mod[i].size() * sizeof(float)); } /* TODO: pin original buffer instead! */ copyToDeviceBuffer(&pmeGpu->kernelParams->grid.d_splineModuli[gridIndex], - pmeGpu->staging.h_splineModuli[gridIndex], 0, newSplineValuesSize, - pmeGpu->archSpecific->pmeStream_, pmeGpu->settings.transferKind, nullptr); + pmeGpu->staging.h_splineModuli[gridIndex], + 0, + newSplineValuesSize, + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); } void pme_gpu_free_bspline_values(const PmeGpu* pmeGpu) @@ -218,8 +228,10 @@ void pme_gpu_realloc_forces(PmeGpu* pmeGpu) { const size_t newForcesSize = pmeGpu->nAtomsAlloc * DIM; GMX_ASSERT(newForcesSize > 0, "Bad number of atoms in PME GPU"); - reallocateDeviceBuffer(&pmeGpu->kernelParams->atoms.d_forces, newForcesSize, - &pmeGpu->archSpecific->forcesSize, &pmeGpu->archSpecific->forcesSizeAlloc, + reallocateDeviceBuffer(&pmeGpu->kernelParams->atoms.d_forces, + newForcesSize, + &pmeGpu->archSpecific->forcesSize, + &pmeGpu->archSpecific->forcesSizeAlloc, pmeGpu->archSpecific->deviceContext_); pmeGpu->staging.h_forces.reserveWithPadding(pmeGpu->nAtomsAlloc); pmeGpu->staging.h_forces.resizeWithPadding(pmeGpu->kernelParams->atoms.nAtoms); @@ -234,18 +246,26 @@ void pme_gpu_copy_input_forces(PmeGpu* pmeGpu) { GMX_ASSERT(pmeGpu->kernelParams->atoms.nAtoms > 0, "Bad number of atoms in PME GPU"); float* h_forcesFloat = reinterpret_cast(pmeGpu->staging.h_forces.data()); - copyToDeviceBuffer(&pmeGpu->kernelParams->atoms.d_forces, h_forcesFloat, 0, - DIM * pmeGpu->kernelParams->atoms.nAtoms, pmeGpu->archSpecific->pmeStream_, - pmeGpu->settings.transferKind, nullptr); + copyToDeviceBuffer(&pmeGpu->kernelParams->atoms.d_forces, + h_forcesFloat, + 0, + DIM * pmeGpu->kernelParams->atoms.nAtoms, + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); } void pme_gpu_copy_output_forces(PmeGpu* pmeGpu) { GMX_ASSERT(pmeGpu->kernelParams->atoms.nAtoms > 0, "Bad number of atoms in PME GPU"); float* h_forcesFloat = reinterpret_cast(pmeGpu->staging.h_forces.data()); - copyFromDeviceBuffer(h_forcesFloat, &pmeGpu->kernelParams->atoms.d_forces, 0, - DIM * pmeGpu->kernelParams->atoms.nAtoms, pmeGpu->archSpecific->pmeStream_, - pmeGpu->settings.transferKind, nullptr); + copyFromDeviceBuffer(h_forcesFloat, + &pmeGpu->kernelParams->atoms.d_forces, + 0, + DIM * pmeGpu->kernelParams->atoms.nAtoms, + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); } void pme_gpu_realloc_and_copy_input_coefficients(const PmeGpu* pmeGpu, @@ -256,19 +276,26 @@ void pme_gpu_realloc_and_copy_input_coefficients(const PmeGpu* pmeGpu, const size_t newCoefficientsSize = pmeGpu->nAtomsAlloc; GMX_ASSERT(newCoefficientsSize > 0, "Bad number of atoms in PME GPU"); reallocateDeviceBuffer(&pmeGpu->kernelParams->atoms.d_coefficients[gridIndex], - newCoefficientsSize, &pmeGpu->archSpecific->coefficientsSize[gridIndex], + newCoefficientsSize, + &pmeGpu->archSpecific->coefficientsSize[gridIndex], &pmeGpu->archSpecific->coefficientsCapacity[gridIndex], pmeGpu->archSpecific->deviceContext_); copyToDeviceBuffer(&pmeGpu->kernelParams->atoms.d_coefficients[gridIndex], - const_cast(h_coefficients), 0, pmeGpu->kernelParams->atoms.nAtoms, - pmeGpu->archSpecific->pmeStream_, pmeGpu->settings.transferKind, nullptr); + const_cast(h_coefficients), + 0, + pmeGpu->kernelParams->atoms.nAtoms, + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); const size_t paddingIndex = pmeGpu->kernelParams->atoms.nAtoms; const size_t paddingCount = pmeGpu->nAtomsAlloc - paddingIndex; if (paddingCount > 0) { - clearDeviceBufferAsync(&pmeGpu->kernelParams->atoms.d_coefficients[gridIndex], paddingIndex, - paddingCount, pmeGpu->archSpecific->pmeStream_); + clearDeviceBufferAsync(&pmeGpu->kernelParams->atoms.d_coefficients[gridIndex], + paddingIndex, + paddingCount, + pmeGpu->archSpecific->pmeStream_); } } @@ -289,10 +316,15 @@ void pme_gpu_realloc_spline_data(PmeGpu* pmeGpu) const bool shouldRealloc = (newSplineDataSize > pmeGpu->archSpecific->splineDataSize); int currentSizeTemp = pmeGpu->archSpecific->splineDataSize; int currentSizeTempAlloc = pmeGpu->archSpecific->splineDataSizeAlloc; - reallocateDeviceBuffer(&pmeGpu->kernelParams->atoms.d_theta, newSplineDataSize, ¤tSizeTemp, - ¤tSizeTempAlloc, pmeGpu->archSpecific->deviceContext_); - reallocateDeviceBuffer(&pmeGpu->kernelParams->atoms.d_dtheta, newSplineDataSize, - &pmeGpu->archSpecific->splineDataSize, &pmeGpu->archSpecific->splineDataSizeAlloc, + reallocateDeviceBuffer(&pmeGpu->kernelParams->atoms.d_theta, + newSplineDataSize, + ¤tSizeTemp, + ¤tSizeTempAlloc, + pmeGpu->archSpecific->deviceContext_); + reallocateDeviceBuffer(&pmeGpu->kernelParams->atoms.d_dtheta, + newSplineDataSize, + &pmeGpu->archSpecific->splineDataSize, + &pmeGpu->archSpecific->splineDataSizeAlloc, pmeGpu->archSpecific->deviceContext_); // the host side reallocation if (shouldRealloc) @@ -317,7 +349,8 @@ void pme_gpu_realloc_grid_indices(PmeGpu* pmeGpu) { const size_t newIndicesSize = DIM * pmeGpu->nAtomsAlloc; GMX_ASSERT(newIndicesSize > 0, "Bad number of atoms in PME GPU"); - reallocateDeviceBuffer(&pmeGpu->kernelParams->atoms.d_gridlineIndices, newIndicesSize, + reallocateDeviceBuffer(&pmeGpu->kernelParams->atoms.d_gridlineIndices, + newIndicesSize, &pmeGpu->archSpecific->gridlineIndicesSize, &pmeGpu->archSpecific->gridlineIndicesSizeAlloc, pmeGpu->archSpecific->deviceContext_); @@ -347,11 +380,13 @@ void pme_gpu_realloc_grids(PmeGpu* pmeGpu) if (pmeGpu->archSpecific->performOutOfPlaceFFT) { /* 2 separate grids */ - reallocateDeviceBuffer(&kernelParamsPtr->grid.d_fourierGrid[gridIndex], newComplexGridSize, + reallocateDeviceBuffer(&kernelParamsPtr->grid.d_fourierGrid[gridIndex], + newComplexGridSize, &pmeGpu->archSpecific->complexGridSize[gridIndex], &pmeGpu->archSpecific->complexGridCapacity[gridIndex], pmeGpu->archSpecific->deviceContext_); - reallocateDeviceBuffer(&kernelParamsPtr->grid.d_realGrid[gridIndex], newRealGridSize, + reallocateDeviceBuffer(&kernelParamsPtr->grid.d_realGrid[gridIndex], + newRealGridSize, &pmeGpu->archSpecific->realGridSize[gridIndex], &pmeGpu->archSpecific->realGridCapacity[gridIndex], pmeGpu->archSpecific->deviceContext_); @@ -360,7 +395,8 @@ void pme_gpu_realloc_grids(PmeGpu* pmeGpu) { /* A single buffer so that any grid will fit */ const int newGridsSize = std::max(newRealGridSize, newComplexGridSize); - reallocateDeviceBuffer(&kernelParamsPtr->grid.d_realGrid[gridIndex], newGridsSize, + reallocateDeviceBuffer(&kernelParamsPtr->grid.d_realGrid[gridIndex], + newGridsSize, &pmeGpu->archSpecific->realGridSize[gridIndex], &pmeGpu->archSpecific->realGridCapacity[gridIndex], pmeGpu->archSpecific->deviceContext_); @@ -388,7 +424,8 @@ void pme_gpu_clear_grids(const PmeGpu* pmeGpu) { for (int gridIndex = 0; gridIndex < pmeGpu->common->ngrids; gridIndex++) { - clearDeviceBufferAsync(&pmeGpu->kernelParams->grid.d_realGrid[gridIndex], 0, + clearDeviceBufferAsync(&pmeGpu->kernelParams->grid.d_realGrid[gridIndex], + 0, pmeGpu->archSpecific->realGridSize[gridIndex], pmeGpu->archSpecific->pmeStream_); } @@ -411,12 +448,16 @@ void pme_gpu_realloc_and_copy_fract_shifts(PmeGpu* pmeGpu) const int newFractShiftsSize = cellCount * (nx + ny + nz); initParamLookupTable(&kernelParamsPtr->grid.d_fractShiftsTable, - &kernelParamsPtr->fractShiftsTableTexture, pmeGpu->common->fsh.data(), - newFractShiftsSize, pmeGpu->archSpecific->deviceContext_); + &kernelParamsPtr->fractShiftsTableTexture, + pmeGpu->common->fsh.data(), + newFractShiftsSize, + pmeGpu->archSpecific->deviceContext_); initParamLookupTable(&kernelParamsPtr->grid.d_gridlineIndicesTable, - &kernelParamsPtr->gridlineIndicesTableTexture, pmeGpu->common->nn.data(), - newFractShiftsSize, pmeGpu->archSpecific->deviceContext_); + &kernelParamsPtr->gridlineIndicesTableTexture, + pmeGpu->common->nn.data(), + newFractShiftsSize, + pmeGpu->archSpecific->deviceContext_); } void pme_gpu_free_fract_shifts(const PmeGpu* pmeGpu) @@ -440,16 +481,24 @@ bool pme_gpu_stream_query(const PmeGpu* pmeGpu) void pme_gpu_copy_input_gather_grid(const PmeGpu* pmeGpu, const float* h_grid, const int gridIndex) { - copyToDeviceBuffer(&pmeGpu->kernelParams->grid.d_realGrid[gridIndex], h_grid, 0, + copyToDeviceBuffer(&pmeGpu->kernelParams->grid.d_realGrid[gridIndex], + h_grid, + 0, pmeGpu->archSpecific->realGridSize[gridIndex], - pmeGpu->archSpecific->pmeStream_, pmeGpu->settings.transferKind, nullptr); + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); } void pme_gpu_copy_output_spread_grid(const PmeGpu* pmeGpu, float* h_grid, const int gridIndex) { - copyFromDeviceBuffer(h_grid, &pmeGpu->kernelParams->grid.d_realGrid[gridIndex], 0, + copyFromDeviceBuffer(h_grid, + &pmeGpu->kernelParams->grid.d_realGrid[gridIndex], + 0, pmeGpu->archSpecific->realGridSize[gridIndex], - pmeGpu->archSpecific->pmeStream_, pmeGpu->settings.transferKind, nullptr); + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); pmeGpu->archSpecific->syncSpreadGridD2H.markEvent(pmeGpu->archSpecific->pmeStream_); } @@ -457,13 +506,27 @@ void pme_gpu_copy_output_spread_atom_data(const PmeGpu* pmeGpu) { const size_t splinesCount = DIM * pmeGpu->nAtomsAlloc * pmeGpu->common->pme_order; auto* kernelParamsPtr = pmeGpu->kernelParams.get(); - copyFromDeviceBuffer(pmeGpu->staging.h_dtheta, &kernelParamsPtr->atoms.d_dtheta, 0, splinesCount, - pmeGpu->archSpecific->pmeStream_, pmeGpu->settings.transferKind, nullptr); - copyFromDeviceBuffer(pmeGpu->staging.h_theta, &kernelParamsPtr->atoms.d_theta, 0, splinesCount, - pmeGpu->archSpecific->pmeStream_, pmeGpu->settings.transferKind, nullptr); - copyFromDeviceBuffer(pmeGpu->staging.h_gridlineIndices, &kernelParamsPtr->atoms.d_gridlineIndices, - 0, kernelParamsPtr->atoms.nAtoms * DIM, pmeGpu->archSpecific->pmeStream_, - pmeGpu->settings.transferKind, nullptr); + copyFromDeviceBuffer(pmeGpu->staging.h_dtheta, + &kernelParamsPtr->atoms.d_dtheta, + 0, + splinesCount, + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); + copyFromDeviceBuffer(pmeGpu->staging.h_theta, + &kernelParamsPtr->atoms.d_theta, + 0, + splinesCount, + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); + copyFromDeviceBuffer(pmeGpu->staging.h_gridlineIndices, + &kernelParamsPtr->atoms.d_gridlineIndices, + 0, + kernelParamsPtr->atoms.nAtoms * DIM, + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); } void pme_gpu_copy_input_gather_atom_data(const PmeGpu* pmeGpu) @@ -472,22 +535,40 @@ void pme_gpu_copy_input_gather_atom_data(const PmeGpu* pmeGpu) auto* kernelParamsPtr = pmeGpu->kernelParams.get(); // TODO: could clear only the padding and not the whole thing, but this is a test-exclusive code anyway - clearDeviceBufferAsync(&kernelParamsPtr->atoms.d_gridlineIndices, 0, pmeGpu->nAtomsAlloc * DIM, + clearDeviceBufferAsync(&kernelParamsPtr->atoms.d_gridlineIndices, + 0, + pmeGpu->nAtomsAlloc * DIM, pmeGpu->archSpecific->pmeStream_); - clearDeviceBufferAsync(&kernelParamsPtr->atoms.d_dtheta, 0, + clearDeviceBufferAsync(&kernelParamsPtr->atoms.d_dtheta, + 0, pmeGpu->nAtomsAlloc * pmeGpu->common->pme_order * DIM, pmeGpu->archSpecific->pmeStream_); - clearDeviceBufferAsync(&kernelParamsPtr->atoms.d_theta, 0, + clearDeviceBufferAsync(&kernelParamsPtr->atoms.d_theta, + 0, pmeGpu->nAtomsAlloc * pmeGpu->common->pme_order * DIM, pmeGpu->archSpecific->pmeStream_); - copyToDeviceBuffer(&kernelParamsPtr->atoms.d_dtheta, pmeGpu->staging.h_dtheta, 0, splinesCount, - pmeGpu->archSpecific->pmeStream_, pmeGpu->settings.transferKind, nullptr); - copyToDeviceBuffer(&kernelParamsPtr->atoms.d_theta, pmeGpu->staging.h_theta, 0, splinesCount, - pmeGpu->archSpecific->pmeStream_, pmeGpu->settings.transferKind, nullptr); - copyToDeviceBuffer(&kernelParamsPtr->atoms.d_gridlineIndices, pmeGpu->staging.h_gridlineIndices, - 0, kernelParamsPtr->atoms.nAtoms * DIM, pmeGpu->archSpecific->pmeStream_, - pmeGpu->settings.transferKind, nullptr); + copyToDeviceBuffer(&kernelParamsPtr->atoms.d_dtheta, + pmeGpu->staging.h_dtheta, + 0, + splinesCount, + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); + copyToDeviceBuffer(&kernelParamsPtr->atoms.d_theta, + pmeGpu->staging.h_theta, + 0, + splinesCount, + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); + copyToDeviceBuffer(&kernelParamsPtr->atoms.d_gridlineIndices, + pmeGpu->staging.h_gridlineIndices, + 0, + kernelParamsPtr->atoms.nAtoms * DIM, + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); } void pme_gpu_sync_spread_grid(const PmeGpu* pmeGpu) @@ -1238,14 +1319,16 @@ void pme_gpu_spread(const PmeGpu* pmeGpu, if (spreadCharges) { timingId = gtPME_SPLINEANDSPREAD; - kernelPtr = selectSplineAndSpreadKernelPtr(pmeGpu, pmeGpu->settings.threadsPerAtom, + kernelPtr = selectSplineAndSpreadKernelPtr(pmeGpu, + pmeGpu->settings.threadsPerAtom, writeGlobal || (!recalculateSplines), pmeGpu->common->ngrids); } else { timingId = gtPME_SPLINE; - kernelPtr = selectSplineKernelPtr(pmeGpu, pmeGpu->settings.threadsPerAtom, + kernelPtr = selectSplineKernelPtr(pmeGpu, + pmeGpu->settings.threadsPerAtom, writeGlobal || (!recalculateSplines), pmeGpu->common->ngrids); } @@ -1253,8 +1336,10 @@ void pme_gpu_spread(const PmeGpu* pmeGpu, else { timingId = gtPME_SPREAD; - kernelPtr = selectSpreadKernelPtr(pmeGpu, pmeGpu->settings.threadsPerAtom, - writeGlobal || (!recalculateSplines), pmeGpu->common->ngrids); + kernelPtr = selectSpreadKernelPtr(pmeGpu, + pmeGpu->settings.threadsPerAtom, + writeGlobal || (!recalculateSplines), + pmeGpu->common->ngrids); } @@ -1263,17 +1348,24 @@ void pme_gpu_spread(const PmeGpu* pmeGpu, #if c_canEmbedBuffers const auto kernelArgs = prepareGpuKernelArguments(kernelPtr, config, kernelParamsPtr); #else - const auto kernelArgs = prepareGpuKernelArguments( - kernelPtr, config, kernelParamsPtr, &kernelParamsPtr->atoms.d_theta, - &kernelParamsPtr->atoms.d_dtheta, &kernelParamsPtr->atoms.d_gridlineIndices, - &kernelParamsPtr->grid.d_realGrid[FEP_STATE_A], &kernelParamsPtr->grid.d_realGrid[FEP_STATE_B], - &kernelParamsPtr->grid.d_fractShiftsTable, &kernelParamsPtr->grid.d_gridlineIndicesTable, - &kernelParamsPtr->atoms.d_coefficients[FEP_STATE_A], - &kernelParamsPtr->atoms.d_coefficients[FEP_STATE_B], &kernelParamsPtr->atoms.d_coordinates); + const auto kernelArgs = + prepareGpuKernelArguments(kernelPtr, + config, + kernelParamsPtr, + &kernelParamsPtr->atoms.d_theta, + &kernelParamsPtr->atoms.d_dtheta, + &kernelParamsPtr->atoms.d_gridlineIndices, + &kernelParamsPtr->grid.d_realGrid[FEP_STATE_A], + &kernelParamsPtr->grid.d_realGrid[FEP_STATE_B], + &kernelParamsPtr->grid.d_fractShiftsTable, + &kernelParamsPtr->grid.d_gridlineIndicesTable, + &kernelParamsPtr->atoms.d_coefficients[FEP_STATE_A], + &kernelParamsPtr->atoms.d_coefficients[FEP_STATE_B], + &kernelParamsPtr->atoms.d_coordinates); #endif - launchGpuKernel(kernelPtr, config, pmeGpu->archSpecific->pmeStream_, timingEvent, - "PME spline/spread", kernelArgs); + launchGpuKernel( + kernelPtr, config, pmeGpu->archSpecific->pmeStream_, timingEvent, "PME spline/spread", kernelArgs); pme_gpu_stop_timing(pmeGpu, timingId); const auto& settings = pmeGpu->settings; @@ -1314,9 +1406,13 @@ void pme_gpu_solve(const PmeGpu* pmeGpu, float* h_gridFloat = reinterpret_cast(h_grid); if (copyInputAndOutputGrid) { - copyToDeviceBuffer(&kernelParamsPtr->grid.d_fourierGrid[gridIndex], h_gridFloat, 0, + copyToDeviceBuffer(&kernelParamsPtr->grid.d_fourierGrid[gridIndex], + h_gridFloat, + 0, pmeGpu->archSpecific->complexGridSize[gridIndex], - pmeGpu->archSpecific->pmeStream_, pmeGpu->settings.transferKind, nullptr); + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); } int majorDim = -1, middleDim = -1, minorDim = -1; @@ -1400,28 +1496,37 @@ void pme_gpu_solve(const PmeGpu* pmeGpu, #if c_canEmbedBuffers const auto kernelArgs = prepareGpuKernelArguments(kernelPtr, config, kernelParamsPtr); #else - const auto kernelArgs = prepareGpuKernelArguments( - kernelPtr, config, kernelParamsPtr, &kernelParamsPtr->grid.d_splineModuli[gridIndex], - &kernelParamsPtr->constants.d_virialAndEnergy[gridIndex], - &kernelParamsPtr->grid.d_fourierGrid[gridIndex]); + const auto kernelArgs = + prepareGpuKernelArguments(kernelPtr, + config, + kernelParamsPtr, + &kernelParamsPtr->grid.d_splineModuli[gridIndex], + &kernelParamsPtr->constants.d_virialAndEnergy[gridIndex], + &kernelParamsPtr->grid.d_fourierGrid[gridIndex]); #endif - launchGpuKernel(kernelPtr, config, pmeGpu->archSpecific->pmeStream_, timingEvent, "PME solve", - kernelArgs); + launchGpuKernel(kernelPtr, config, pmeGpu->archSpecific->pmeStream_, timingEvent, "PME solve", kernelArgs); pme_gpu_stop_timing(pmeGpu, timingId); if (computeEnergyAndVirial) { copyFromDeviceBuffer(pmeGpu->staging.h_virialAndEnergy[gridIndex], - &kernelParamsPtr->constants.d_virialAndEnergy[gridIndex], 0, - c_virialAndEnergyCount, pmeGpu->archSpecific->pmeStream_, - pmeGpu->settings.transferKind, nullptr); + &kernelParamsPtr->constants.d_virialAndEnergy[gridIndex], + 0, + c_virialAndEnergyCount, + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); } if (copyInputAndOutputGrid) { - copyFromDeviceBuffer(h_gridFloat, &kernelParamsPtr->grid.d_fourierGrid[gridIndex], 0, + copyFromDeviceBuffer(h_gridFloat, + &kernelParamsPtr->grid.d_fourierGrid[gridIndex], + 0, pmeGpu->archSpecific->complexGridSize[gridIndex], - pmeGpu->archSpecific->pmeStream_, pmeGpu->settings.transferKind, nullptr); + pmeGpu->archSpecific->pmeStream_, + pmeGpu->settings.transferKind, + nullptr); } } @@ -1551,8 +1656,10 @@ void pme_gpu_gather(PmeGpu* pmeGpu, real** h_grids, const float lambda) int timingId = gtPME_GATHER; PmeGpuProgramImpl::PmeKernelHandle kernelPtr = - selectGatherKernelPtr(pmeGpu, pmeGpu->settings.threadsPerAtom, - readGlobal || (!recalculateSplines), pmeGpu->common->ngrids); + selectGatherKernelPtr(pmeGpu, + pmeGpu->settings.threadsPerAtom, + readGlobal || (!recalculateSplines), + pmeGpu->common->ngrids); // TODO design kernel selection getters and make PmeGpu a friend of PmeGpuProgramImpl pme_gpu_start_timing(pmeGpu, timingId); @@ -1570,15 +1677,20 @@ void pme_gpu_gather(PmeGpu* pmeGpu, real** h_grids, const float lambda) #if c_canEmbedBuffers const auto kernelArgs = prepareGpuKernelArguments(kernelPtr, config, kernelParamsPtr); #else - const auto kernelArgs = prepareGpuKernelArguments( - kernelPtr, config, kernelParamsPtr, &kernelParamsPtr->atoms.d_coefficients[FEP_STATE_A], - &kernelParamsPtr->atoms.d_coefficients[FEP_STATE_B], - &kernelParamsPtr->grid.d_realGrid[FEP_STATE_A], &kernelParamsPtr->grid.d_realGrid[FEP_STATE_B], - &kernelParamsPtr->atoms.d_theta, &kernelParamsPtr->atoms.d_dtheta, - &kernelParamsPtr->atoms.d_gridlineIndices, &kernelParamsPtr->atoms.d_forces); + const auto kernelArgs = + prepareGpuKernelArguments(kernelPtr, + config, + kernelParamsPtr, + &kernelParamsPtr->atoms.d_coefficients[FEP_STATE_A], + &kernelParamsPtr->atoms.d_coefficients[FEP_STATE_B], + &kernelParamsPtr->grid.d_realGrid[FEP_STATE_A], + &kernelParamsPtr->grid.d_realGrid[FEP_STATE_B], + &kernelParamsPtr->atoms.d_theta, + &kernelParamsPtr->atoms.d_dtheta, + &kernelParamsPtr->atoms.d_gridlineIndices, + &kernelParamsPtr->atoms.d_forces); #endif - launchGpuKernel(kernelPtr, config, pmeGpu->archSpecific->pmeStream_, timingEvent, "PME gather", - kernelArgs); + launchGpuKernel(kernelPtr, config, pmeGpu->archSpecific->pmeStream_, timingEvent, "PME gather", kernelArgs); pme_gpu_stop_timing(pmeGpu, timingId); if (pmeGpu->settings.useGpuForceReduction) diff --git a/src/gromacs/ewald/pme_gpu_program_impl_ocl.cpp b/src/gromacs/ewald/pme_gpu_program_impl_ocl.cpp index c88baf40e5..85cee2f008 100644 --- a/src/gromacs/ewald/pme_gpu_program_impl_ocl.cpp +++ b/src/gromacs/ewald/pme_gpu_program_impl_ocl.cpp @@ -89,7 +89,8 @@ PmeGpuProgramImpl::~PmeGpuProgramImpl() stat |= clReleaseKernel(solveYZXKernelB); stat |= clReleaseKernel(solveYZXEnergyKernelB); GMX_ASSERT(stat == CL_SUCCESS, - gmx::formatString("Failed to release PME OpenCL resources %d: %s", stat, + gmx::formatString("Failed to release PME OpenCL resources %d: %s", + stat, ocl_get_error_string(stat).c_str()) .c_str()); } @@ -116,7 +117,10 @@ static void checkRequiredWarpSize(cl_kernel kernel, const char* kernelName, cons "PME OpenCL kernels require >=%d execution width, but the %s kernel " "has been compiled for the device %s to a %d width and therefore it can not " "execute correctly.", - minKernelWarpSize, kernelName, deviceInfo.device_name, kernelWarpSize); + minKernelWarpSize, + kernelName, + deviceInfo.device_name, + kernelWarpSize); GMX_THROW(gmx::InternalError(errorString)); } } @@ -150,17 +154,30 @@ void PmeGpuProgramImpl::compileKernels(const DeviceInformation& deviceInfo) "-DDIM=%d -DXX=%d -DYY=%d -DZZ=%d " // decomposition parameter placeholders "-DwrapX=true -DwrapY=true ", - warpSize_, c_pmeGpuOrder, c_pmeGpuOrder * c_pmeGpuOrder, - static_cast(c_pmeMaxUnitcellShift), static_cast(c_skipNeutralAtoms), - c_virialAndEnergyCount, spreadWorkGroupSize, solveMaxWorkGroupSize, - gatherWorkGroupSize, DIM, XX, YY, ZZ); + warpSize_, + c_pmeGpuOrder, + c_pmeGpuOrder * c_pmeGpuOrder, + static_cast(c_pmeMaxUnitcellShift), + static_cast(c_skipNeutralAtoms), + c_virialAndEnergyCount, + spreadWorkGroupSize, + solveMaxWorkGroupSize, + gatherWorkGroupSize, + DIM, + XX, + YY, + ZZ); try { /* TODO when we have a proper MPI-aware logging module, the log output here should be written there */ - program = gmx::ocl::compileProgram(stderr, "gromacs/ewald", "pme_program.cl", - commonDefines, deviceContext_.context(), - deviceInfo.oclDeviceId, deviceInfo.deviceVendor); + program = gmx::ocl::compileProgram(stderr, + "gromacs/ewald", + "pme_program.cl", + commonDefines, + deviceContext_.context(), + deviceInfo.oclDeviceId, + deviceInfo.deviceVendor); } catch (gmx::GromacsException& e) { @@ -181,7 +198,9 @@ void PmeGpuProgramImpl::compileKernels(const DeviceInformation& deviceInfo) { const std::string errorString = gmx::formatString( "Failed to create kernels for PME on GPU #%s:\n OpenCL error %d: %s", - deviceInfo.device_name, clError, ocl_get_error_string(clError).c_str()); + deviceInfo.device_name, + clError, + ocl_get_error_string(clError).c_str()); GMX_THROW(gmx::InternalError(errorString)); } kernels.resize(actualKernelCount); @@ -189,13 +208,15 @@ void PmeGpuProgramImpl::compileKernels(const DeviceInformation& deviceInfo) std::array kernelNamesBuffer; for (const auto& kernel : kernels) { - clError = clGetKernelInfo(kernel, CL_KERNEL_FUNCTION_NAME, kernelNamesBuffer.size(), - kernelNamesBuffer.data(), nullptr); + clError = clGetKernelInfo( + kernel, CL_KERNEL_FUNCTION_NAME, kernelNamesBuffer.size(), kernelNamesBuffer.data(), nullptr); if (clError != CL_SUCCESS) { const std::string errorString = gmx::formatString( "Failed to parse kernels for PME on GPU #%s:\n OpenCL error %d: %s", - deviceInfo.device_name, clError, ocl_get_error_string(clError).c_str()); + deviceInfo.device_name, + clError, + ocl_get_error_string(clError).c_str()); GMX_THROW(gmx::InternalError(errorString)); } diff --git a/src/gromacs/ewald/pme_grid.cpp b/src/gromacs/ewald/pme_grid.cpp index 3d277d3146..3f3eb48c23 100644 --- a/src/gromacs/ewald/pme_grid.cpp +++ b/src/gromacs/ewald/pme_grid.cpp @@ -108,8 +108,12 @@ void gmx_sum_qgrid_dd(gmx_pme_t* pme, real* grid, const int direction) /* Copy data to contiguous send buffer */ if (debug) { - fprintf(debug, "PME send rank %d %d -> %d grid start %d Communicating %d to %d\n", - pme->nodeid, overlap->nodeid, send_id, pme->pmegrid_start_iy, + fprintf(debug, + "PME send rank %d %d -> %d grid start %d Communicating %d to %d\n", + pme->nodeid, + overlap->nodeid, + send_id, + pme->pmegrid_start_iy, send_index0 - pme->pmegrid_start_iy, send_index0 - pme->pmegrid_start_iy + send_nindex); } @@ -131,15 +135,28 @@ void gmx_sum_qgrid_dd(gmx_pme_t* pme, real* grid, const int direction) datasize = pme->pmegrid_nx * pme->nkz; - MPI_Sendrecv(overlap->sendbuf.data(), send_nindex * datasize, GMX_MPI_REAL, send_id, ipulse, - overlap->recvbuf.data(), recv_nindex * datasize, GMX_MPI_REAL, recv_id, ipulse, - overlap->mpi_comm, &stat); + MPI_Sendrecv(overlap->sendbuf.data(), + send_nindex * datasize, + GMX_MPI_REAL, + send_id, + ipulse, + overlap->recvbuf.data(), + recv_nindex * datasize, + GMX_MPI_REAL, + recv_id, + ipulse, + overlap->mpi_comm, + &stat); /* Get data from contiguous recv buffer */ if (debug) { - fprintf(debug, "PME recv rank %d %d <- %d grid start %d Communicating %d to %d\n", - pme->nodeid, overlap->nodeid, recv_id, pme->pmegrid_start_iy, + fprintf(debug, + "PME recv rank %d %d <- %d grid start %d Communicating %d to %d\n", + pme->nodeid, + overlap->nodeid, + recv_id, + pme->pmegrid_start_iy, recv_index0 - pme->pmegrid_start_iy, recv_index0 - pme->pmegrid_start_iy + recv_nindex); } @@ -203,18 +220,36 @@ void gmx_sum_qgrid_dd(gmx_pme_t* pme, real* grid, const int direction) if (debug) { - fprintf(debug, "PME send rank %d %d -> %d grid start %d Communicating %d to %d\n", - pme->nodeid, overlap->nodeid, send_id, pme->pmegrid_start_ix, + fprintf(debug, + "PME send rank %d %d -> %d grid start %d Communicating %d to %d\n", + pme->nodeid, + overlap->nodeid, + send_id, + pme->pmegrid_start_ix, send_index0 - pme->pmegrid_start_ix, send_index0 - pme->pmegrid_start_ix + send_nindex); - fprintf(debug, "PME recv rank %d %d <- %d grid start %d Communicating %d to %d\n", - pme->nodeid, overlap->nodeid, recv_id, pme->pmegrid_start_ix, + fprintf(debug, + "PME recv rank %d %d <- %d grid start %d Communicating %d to %d\n", + pme->nodeid, + overlap->nodeid, + recv_id, + pme->pmegrid_start_ix, recv_index0 - pme->pmegrid_start_ix, recv_index0 - pme->pmegrid_start_ix + recv_nindex); } - MPI_Sendrecv(sendptr, send_nindex * datasize, GMX_MPI_REAL, send_id, ipulse, recvptr, - recv_nindex * datasize, GMX_MPI_REAL, recv_id, ipulse, overlap->mpi_comm, &stat); + MPI_Sendrecv(sendptr, + send_nindex * datasize, + GMX_MPI_REAL, + send_id, + ipulse, + recvptr, + recv_nindex * datasize, + GMX_MPI_REAL, + recv_id, + ipulse, + overlap->mpi_comm, + &stat); /* ADD data from contiguous recv buffer */ if (direction == GMX_SUM_GRID_FORWARD) @@ -244,8 +279,8 @@ int copy_pmegrid_to_fftgrid(const gmx_pme_t* pme, const real* pmegrid, real* fft int pmeidx, fftidx; /* Dimensions should be identical for A/B grid, so we just use A here */ - gmx_parallel_3dfft_real_limits(pme->pfft_setup[grid_index], local_fft_ndata, local_fft_offset, - local_fft_size); + gmx_parallel_3dfft_real_limits( + pme->pfft_setup[grid_index], local_fft_ndata, local_fft_offset, local_fft_size); local_pme_size[0] = pme->pmegrid_nx; local_pme_size[1] = pme->pmegrid_ny; @@ -280,14 +315,31 @@ int copy_pmegrid_to_fftgrid(const gmx_pme_t* pme, const real* pmegrid, real* fft val = 100 * pmegrid[pmeidx]; if (pmegrid[pmeidx] != 0) { - gmx_fprintf_pdb_atomline(fp, epdbATOM, pmeidx, "CA", ' ', "GLY", ' ', pmeidx, - ' ', 5.0 * ix, 5.0 * iy, 5.0 * iz, 1.0, val, ""); + gmx_fprintf_pdb_atomline(fp, + epdbATOM, + pmeidx, + "CA", + ' ', + "GLY", + ' ', + pmeidx, + ' ', + 5.0 * ix, + 5.0 * iy, + 5.0 * iz, + 1.0, + val, + ""); } if (pmegrid[pmeidx] != 0) { - fprintf(fp2, "%-12s %5d %5d %5d %12.5e\n", "qgrid", - pme->pmegrid_start_ix + ix, pme->pmegrid_start_iy + iy, - pme->pmegrid_start_iz + iz, pmegrid[pmeidx]); + fprintf(fp2, + "%-12s %5d %5d %5d %12.5e\n", + "qgrid", + pme->pmegrid_start_ix + ix, + pme->pmegrid_start_iy + iy, + pme->pmegrid_start_iz + iz, + pmegrid[pmeidx]); } #endif } @@ -331,8 +383,8 @@ int copy_fftgrid_to_pmegrid(struct gmx_pme_t* pme, const real* fftgrid, real* pm c1 = omp_cyc_start(); #endif /* Dimensions should be identical for A/B grid, so we just use A here */ - gmx_parallel_3dfft_real_limits(pme->pfft_setup[grid_index], local_fft_ndata, local_fft_offset, - local_fft_size); + gmx_parallel_3dfft_real_limits( + pme->pfft_setup[grid_index], local_fft_ndata, local_fft_offset, local_fft_size); local_pme_size[0] = pme->pmegrid_nx; local_pme_size[1] = pme->pmegrid_ny; @@ -630,7 +682,10 @@ static void make_subgrid_division(const ivec n, int ovl, int nthread, ivec nsub) gmx_fatal(FARGS, "PME grid thread division (%d x %d x %d) does not match the total number of " "threads (%d)", - nsub[XX], nsub[YY], nsub[ZZ], nthread); + nsub[XX], + nsub[YY], + nsub[ZZ], + nthread); } } @@ -675,17 +730,20 @@ void pmegrids_init(pmegrids_t* grids, if (debug) { - fprintf(debug, "pmegrid thread local division: %d x %d x %d\n", grids->nc[XX], - grids->nc[YY], grids->nc[ZZ]); - fprintf(debug, "pmegrid %d %d %d max thread pmegrid %d %d %d\n", nx, ny, nz, nst[XX], - nst[YY], nst[ZZ]); + fprintf(debug, + "pmegrid thread local division: %d x %d x %d\n", + grids->nc[XX], + grids->nc[YY], + grids->nc[ZZ]); + fprintf(debug, "pmegrid %d %d %d max thread pmegrid %d %d %d\n", nx, ny, nz, nst[XX], nst[YY], nst[ZZ]); } snew(grids->grid_th, grids->nthread); t = 0; gridsize = nst[XX] * nst[YY] * nst[ZZ]; set_gridsize_alignment(&gridsize, pme_order); - snew_aligned(grids->grid_all, grids->nthread * gridsize + (grids->nthread + 1) * GMX_CACHE_SEP, + snew_aligned(grids->grid_all, + grids->nthread * gridsize + (grids->nthread + 1) * GMX_CACHE_SEP, SIMD4_ALIGNMENT); for (x = 0; x < grids->nc[XX]; x++) @@ -694,10 +752,18 @@ void pmegrids_init(pmegrids_t* grids, { for (z = 0; z < grids->nc[ZZ]; z++) { - pmegrid_init(&grids->grid_th[t], x, y, z, (n[XX] * (x)) / grids->nc[XX], - (n[YY] * (y)) / grids->nc[YY], (n[ZZ] * (z)) / grids->nc[ZZ], - (n[XX] * (x + 1)) / grids->nc[XX], (n[YY] * (y + 1)) / grids->nc[YY], - (n[ZZ] * (z + 1)) / grids->nc[ZZ], TRUE, pme_order, + pmegrid_init(&grids->grid_th[t], + x, + y, + z, + (n[XX] * (x)) / grids->nc[XX], + (n[YY] * (y)) / grids->nc[YY], + (n[ZZ] * (z)) / grids->nc[ZZ], + (n[XX] * (x + 1)) / grids->nc[XX], + (n[YY] * (y + 1)) / grids->nc[YY], + (n[ZZ] * (z + 1)) / grids->nc[ZZ], + TRUE, + pme_order, grids->grid_all + GMX_CACHE_SEP + t * (gridsize + GMX_CACHE_SEP)); t++; } @@ -742,7 +808,9 @@ void pmegrids_init(pmegrids_t* grids, } if (debug != nullptr) { - fprintf(debug, "pmegrid thread grid communication range in %c: %d\n", 'x' + d, + fprintf(debug, + "pmegrid thread grid communication range in %c: %d\n", + 'x' + d, grids->nthread_comm[d]); } /* It should be possible to make grids->nthread_comm[d]==grids->nc[d] diff --git a/src/gromacs/ewald/pme_load_balancing.cpp b/src/gromacs/ewald/pme_load_balancing.cpp index 73b40cc43a..cae4afbc2d 100644 --- a/src/gromacs/ewald/pme_load_balancing.cpp +++ b/src/gromacs/ewald/pme_load_balancing.cpp @@ -153,7 +153,9 @@ enum epmelb }; /*! \brief Descriptive strings matching ::epmelb */ -static const char* pmelblim_str[epmelblimNR] = { "no", "box size", "domain decompostion", +static const char* pmelblim_str[epmelblimNR] = { "no", + "box size", + "domain decompostion", "PME grid restriction", "maximum allowed grid scaling" }; @@ -262,8 +264,7 @@ void pme_loadbal_init(pme_load_balancing_t** pme_lb_p, if (!pme_lb->bSepPMERanks) { - GMX_RELEASE_ASSERT(pmedata, - "On ranks doing both PP and PME we need a valid pmedata object"); + GMX_RELEASE_ASSERT(pmedata, "On ranks doing both PP and PME we need a valid pmedata object"); pme_lb->setup[0].pmedata = pmedata; } @@ -377,16 +378,21 @@ static gmx_bool pme_loadbal_increase_cutoff(pme_load_balancing_t* pme_lb, int pm fac *= 1.01; clear_ivec(set.grid); - sp = calcFftGrid(nullptr, pme_lb->box_start, fac * pme_lb->setup[pme_lb->cur].spacing, - minimalPmeGridSize(pme_order), &set.grid[XX], &set.grid[YY], &set.grid[ZZ]); + sp = calcFftGrid(nullptr, + pme_lb->box_start, + fac * pme_lb->setup[pme_lb->cur].spacing, + minimalPmeGridSize(pme_order), + &set.grid[XX], + &set.grid[YY], + &set.grid[ZZ]); /* As here we can't easily check if one of the PME ranks * uses threading, we do a conservative grid check. * This means we can't use pme_order or less grid lines * per PME rank along x, which is not a strong restriction. */ - grid_ok = gmx_pme_check_restrictions(pme_order, set.grid[XX], set.grid[YY], set.grid[ZZ], - numPmeDomains.x, true, false); + grid_ok = gmx_pme_check_restrictions( + pme_order, set.grid[XX], set.grid[YY], set.grid[ZZ], numPmeDomains.x, true, false); } while (sp <= 1.001 * pme_lb->setup[pme_lb->cur].spacing || !grid_ok); set.rcut_coulomb = pme_lb->cut_spacing * sp; @@ -438,8 +444,12 @@ static gmx_bool pme_loadbal_increase_cutoff(pme_load_balancing_t* pme_lb, int pm if (debug) { - fprintf(debug, "PME loadbal: grid %d %d %d, coulomb cutoff %f\n", set.grid[XX], - set.grid[YY], set.grid[ZZ], set.rcut_coulomb); + fprintf(debug, + "PME loadbal: grid %d %d %d, coulomb cutoff %f\n", + set.grid[XX], + set.grid[YY], + set.grid[ZZ], + set.rcut_coulomb); } pme_lb->setup.push_back(set); return TRUE; @@ -448,8 +458,13 @@ static gmx_bool pme_loadbal_increase_cutoff(pme_load_balancing_t* pme_lb, int pm /*! \brief Print the PME grid */ static void print_grid(FILE* fp_err, FILE* fp_log, const char* pre, const char* desc, const pme_setup_t* set, double cycles) { - auto buf = gmx::formatString("%-11s%10s pme grid %d %d %d, coulomb cutoff %.3f", pre, desc, - set->grid[XX], set->grid[YY], set->grid[ZZ], set->rcut_coulomb); + auto buf = gmx::formatString("%-11s%10s pme grid %d %d %d, coulomb cutoff %.3f", + pre, + desc, + set->grid[XX], + set->grid[YY], + set->grid[ZZ], + set->rcut_coulomb); if (cycles >= 0) { buf += gmx::formatString(": %.1f M-cycles", cycles * 1e-6); @@ -484,7 +499,8 @@ static void print_loadbal_limited(FILE* fp_err, FILE* fp_log, int64_t step, pme_ { auto buf = gmx::formatString( "step %4s: the %s limits the PME load balancing to a coulomb cut-off of %.3f", - gmx::int64ToString(step).c_str(), pmelblim_str[pme_lb->elimited], + gmx::int64ToString(step).c_str(), + pmelblim_str[pme_lb->elimited], pme_lb->setup[pme_loadbal_end(pme_lb) - 1].rcut_coulomb); if (fp_err != nullptr) { @@ -612,8 +628,13 @@ static void pme_load_balance(pme_load_balancing_t* pme_lb, "is more than %f\n" "Increased the number stages to %d" " and ignoring the previous performance\n", - set->grid[XX], set->grid[YY], set->grid[ZZ], set->cycles * 1e-6, - cycles * 1e-6, maxFluctuationAccepted, pme_lb->nstage); + set->grid[XX], + set->grid[YY], + set->grid[ZZ], + set->cycles * 1e-6, + cycles * 1e-6, + maxFluctuationAccepted, + pme_lb->nstage); } } set->cycles = std::min(set->cycles, cycles); @@ -852,8 +873,8 @@ static void pme_load_balance(pme_load_balancing_t* pme_lb, /* Generate a new PME data structure, * copying part of the old pointers. */ - gmx_pme_reinit(&set->pmedata, cr, pme_lb->setup[0].pmedata, &ir, set->grid, - set->ewaldcoeff_q, set->ewaldcoeff_lj); + gmx_pme_reinit( + &set->pmedata, cr, pme_lb->setup[0].pmedata, &ir, set->grid, set->ewaldcoeff_q, set->ewaldcoeff_lj); } *pmedata = set->pmedata; } @@ -1037,8 +1058,19 @@ void pme_loadbal_do(pme_load_balancing_t* pme_lb, * since init_step might not be a multiple of nstlist, * but the first data collected is skipped anyhow. */ - pme_load_balance(pme_lb, cr, fp_err, fp_log, mdlog, ir, box, x, - pme_lb->cycles_c - cycles_prev, fr->ic, fr->nbv.get(), &fr->pmedata, step); + pme_load_balance(pme_lb, + cr, + fp_err, + fp_log, + mdlog, + ir, + box, + x, + pme_lb->cycles_c - cycles_prev, + fr->ic, + fr->nbv.get(), + &fr->pmedata, + step); /* Update deprecated rlist in forcerec to stay in sync with fr->nbv */ fr->rlist = fr->nbv->pairlistOuterRadius(); @@ -1078,9 +1110,16 @@ static int pme_grid_points(const pme_setup_t* setup) /*! \brief Print one load-balancing setting */ static void print_pme_loadbal_setting(FILE* fplog, const char* name, const pme_setup_t* setup) { - fprintf(fplog, " %-7s %6.3f nm %6.3f nm %3d %3d %3d %5.3f nm %5.3f nm\n", name, - setup->rcut_coulomb, setup->rlistInner, setup->grid[XX], setup->grid[YY], - setup->grid[ZZ], setup->spacing, 1 / setup->ewaldcoeff_q); + fprintf(fplog, + " %-7s %6.3f nm %6.3f nm %3d %3d %3d %5.3f nm %5.3f nm\n", + name, + setup->rcut_coulomb, + setup->rlistInner, + setup->grid[XX], + setup->grid[YY], + setup->grid[ZZ], + setup->spacing, + 1 / setup->ewaldcoeff_q); } /*! \brief Print all load-balancing settings */ @@ -1103,7 +1142,8 @@ static void print_pme_loadbal_settings(pme_load_balancing_t* pme_lb, /* Here we only warn when the optimal setting is the last one */ if (pme_lb->elimited != epmelblimNO && pme_lb->cur == pme_loadbal_end(pme_lb) - 1) { - fprintf(fplog, " NOTE: The PP/PME load balancing was limited by the %s,\n", + fprintf(fplog, + " NOTE: The PP/PME load balancing was limited by the %s,\n", pmelblim_str[pme_lb->elimited]); fprintf(fplog, " you might not have reached a good load balance.\n"); if (pme_lb->elimited == epmelblimDD) diff --git a/src/gromacs/ewald/pme_only.cpp b/src/gromacs/ewald/pme_only.cpp index de9386f639..75f6c101bb 100644 --- a/src/gromacs/ewald/pme_only.cpp +++ b/src/gromacs/ewald/pme_only.cpp @@ -274,8 +274,7 @@ static int gmx_pme_recv_coeffs_coords(struct gmx_pme_t* pme, cnb.flags = 0; /* Receive the send count, box and time step from the peer PP node */ - MPI_Recv(&cnb, sizeof(cnb), MPI_BYTE, pme_pp->peerRankId, eCommType_CNB, - pme_pp->mpi_comm_mysim, MPI_STATUS_IGNORE); + MPI_Recv(&cnb, sizeof(cnb), MPI_BYTE, pme_pp->peerRankId, eCommType_CNB, pme_pp->mpi_comm_mysim, MPI_STATUS_IGNORE); /* We accumulate all received flags */ flags |= cnb.flags; @@ -284,7 +283,8 @@ static int gmx_pme_recv_coeffs_coords(struct gmx_pme_t* pme, if (debug) { - fprintf(debug, "PME only rank receiving:%s%s%s%s%s\n", + fprintf(debug, + "PME only rank receiving:%s%s%s%s%s\n", (cnb.flags & PP_PME_CHARGE) ? " charges" : "", (cnb.flags & PP_PME_COORD) ? " coordinates" : "", (cnb.flags & PP_PME_FINISH) ? " finish" : "", @@ -331,8 +331,13 @@ static int gmx_pme_recv_coeffs_coords(struct gmx_pme_t* pme, } else { - MPI_Irecv(&sender.numAtoms, sizeof(sender.numAtoms), MPI_BYTE, sender.rankId, - eCommType_CNB, pme_pp->mpi_comm_mysim, &pme_pp->req[messages++]); + MPI_Irecv(&sender.numAtoms, + sizeof(sender.numAtoms), + MPI_BYTE, + sender.rankId, + eCommType_CNB, + pme_pp->mpi_comm_mysim, + &pme_pp->req[messages++]); } } MPI_Waitall(messages, pme_pp->req.data(), pme_pp->stat.data()); @@ -399,12 +404,19 @@ static int gmx_pme_recv_coeffs_coords(struct gmx_pme_t* pme, { if (sender.numAtoms > 0) { - MPI_Irecv(bufferPtr + nat, sender.numAtoms * sizeof(real), MPI_BYTE, - sender.rankId, q, pme_pp->mpi_comm_mysim, &pme_pp->req[messages++]); + MPI_Irecv(bufferPtr + nat, + sender.numAtoms * sizeof(real), + MPI_BYTE, + sender.rankId, + q, + pme_pp->mpi_comm_mysim, + &pme_pp->req[messages++]); nat += sender.numAtoms; if (debug) { - fprintf(debug, "Received from PP rank %d: %d %s\n", sender.rankId, + fprintf(debug, + "Received from PP rank %d: %d %s\n", + sender.rankId, sender.numAtoms, (q == eCommType_ChargeA || q == eCommType_ChargeB) ? "charges" : "params"); @@ -460,8 +472,13 @@ static int gmx_pme_recv_coeffs_coords(struct gmx_pme_t* pme, } else { - MPI_Irecv(pme_pp->x[nat], sender.numAtoms * sizeof(rvec), MPI_BYTE, sender.rankId, - eCommType_COORD, pme_pp->mpi_comm_mysim, &pme_pp->req[messages++]); + MPI_Irecv(pme_pp->x[nat], + sender.numAtoms * sizeof(rvec), + MPI_BYTE, + sender.rankId, + eCommType_COORD, + pme_pp->mpi_comm_mysim, + &pme_pp->req[messages++]); } nat += sender.numAtoms; if (debug) @@ -469,7 +486,8 @@ static int gmx_pme_recv_coeffs_coords(struct gmx_pme_t* pme, fprintf(debug, "Received from PP rank %d: %d " "coordinates\n", - sender.rankId, sender.numAtoms); + sender.rankId, + sender.numAtoms); } } } @@ -529,8 +547,13 @@ static void sendFToPP(void* sendbuf, PpRanks receiver, gmx_pme_pp* pme_pp, int* else { // Send using MPI - MPI_Isend(sendbuf, receiver.numAtoms * sizeof(rvec), MPI_BYTE, receiver.rankId, 0, - pme_pp->mpi_comm_mysim, &pme_pp->req[*messages]); + MPI_Isend(sendbuf, + receiver.numAtoms * sizeof(rvec), + MPI_BYTE, + receiver.rankId, + 0, + pme_pp->mpi_comm_mysim, + &pme_pp->req[*messages]); *messages = *messages + 1; } } @@ -582,8 +605,7 @@ static void gmx_pme_send_force_vir_ener(const gmx_pme_t& pme, { fprintf(debug, "PME rank sending to PP rank %d: virial and energy\n", pme_pp->peerRankId); } - MPI_Isend(&cve, sizeof(cve), MPI_BYTE, pme_pp->peerRankId, 1, pme_pp->mpi_comm_mysim, - &pme_pp->req[messages++]); + MPI_Isend(&cve, sizeof(cve), MPI_BYTE, pme_pp->peerRankId, 1, pme_pp->mpi_comm_mysim, &pme_pp->req[messages++]); /* Wait for the forces to arrive */ MPI_Waitall(messages, pme_pp->req.data(), pme_pp->stat.data()); @@ -640,17 +662,22 @@ int gmx_pmeonly(struct gmx_pme_t* pme, if (c_enableGpuPmePpComms) { pme_pp->pmeCoordinateReceiverGpu = std::make_unique( - deviceStreamManager->stream(gmx::DeviceStreamType::Pme), pme_pp->mpi_comm_mysim, + deviceStreamManager->stream(gmx::DeviceStreamType::Pme), + pme_pp->mpi_comm_mysim, pme_pp->ppRanks); pme_pp->pmeForceSenderGpu = std::make_unique( - deviceStreamManager->stream(gmx::DeviceStreamType::Pme), pme_pp->mpi_comm_mysim, + deviceStreamManager->stream(gmx::DeviceStreamType::Pme), + pme_pp->mpi_comm_mysim, pme_pp->ppRanks); } // TODO: Special PME-only constructor is used here. There is no mechanism to prevent from using the other constructor here. // This should be made safer. stateGpu = std::make_unique( - &deviceStreamManager->stream(gmx::DeviceStreamType::Pme), deviceStreamManager->context(), - GpuApiCallBehavior::Async, pme_gpu_get_block_size(pme), wcycle); + &deviceStreamManager->stream(gmx::DeviceStreamType::Pme), + deviceStreamManager->context(), + GpuApiCallBehavior::Async, + pme_gpu_get_block_size(pme), + wcycle); } clear_nrnb(mynrnb); @@ -664,10 +691,22 @@ int gmx_pmeonly(struct gmx_pme_t* pme, /* Domain decomposition */ ivec newGridSize; real ewaldcoeff_q = 0, ewaldcoeff_lj = 0; - ret = gmx_pme_recv_coeffs_coords(pme, pme_pp.get(), &natoms, box, &maxshift_x, &maxshift_y, - &lambda_q, &lambda_lj, &computeEnergyAndVirial, &step, - &newGridSize, &ewaldcoeff_q, &ewaldcoeff_lj, - useGpuForPme, stateGpu.get(), runMode); + ret = gmx_pme_recv_coeffs_coords(pme, + pme_pp.get(), + &natoms, + box, + &maxshift_x, + &maxshift_y, + &lambda_q, + &lambda_lj, + &computeEnergyAndVirial, + &step, + &newGridSize, + &ewaldcoeff_q, + &ewaldcoeff_lj, + useGpuForPme, + stateGpu.get(), + runMode); if (ret == pmerecvqxSWITCHGRID) { @@ -734,12 +773,30 @@ int gmx_pmeonly(struct gmx_pme_t* pme, GMX_ASSERT(pme_pp->x.size() == static_cast(natoms), "The coordinate buffer should have size natoms"); - gmx_pme_do(pme, pme_pp->x, pme_pp->f, pme_pp->chargeA.data(), pme_pp->chargeB.data(), - pme_pp->sqrt_c6A.data(), pme_pp->sqrt_c6B.data(), pme_pp->sigmaA.data(), - pme_pp->sigmaB.data(), box, cr, maxshift_x, maxshift_y, mynrnb, wcycle, - output.coulombVirial_, output.lennardJonesVirial_, &output.coulombEnergy_, - &output.lennardJonesEnergy_, lambda_q, lambda_lj, &dvdlambda_q, - &dvdlambda_lj, stepWork); + gmx_pme_do(pme, + pme_pp->x, + pme_pp->f, + pme_pp->chargeA.data(), + pme_pp->chargeB.data(), + pme_pp->sqrt_c6A.data(), + pme_pp->sqrt_c6B.data(), + pme_pp->sigmaA.data(), + pme_pp->sigmaB.data(), + box, + cr, + maxshift_x, + maxshift_y, + mynrnb, + wcycle, + output.coulombVirial_, + output.lennardJonesVirial_, + &output.coulombEnergy_, + &output.lennardJonesEnergy_, + lambda_q, + lambda_lj, + &dvdlambda_q, + &dvdlambda_lj, + stepWork); output.forces_ = pme_pp->f; } diff --git a/src/gromacs/ewald/pme_pp.cpp b/src/gromacs/ewald/pme_pp.cpp index f788992e52..76dc21f721 100644 --- a/src/gromacs/ewald/pme_pp.cpp +++ b/src/gromacs/ewald/pme_pp.cpp @@ -124,9 +124,15 @@ static void gmx_pme_send_coeffs_coords(t_forcerec* fr, if (debug) { - fprintf(debug, "PP rank %d sending to PME rank %d: %d%s%s%s%s\n", cr->sim_nodeid, dd->pme_nodeid, - n, (flags & PP_PME_CHARGE) ? " charges" : "", (flags & PP_PME_SQRTC6) ? " sqrtC6" : "", - (flags & PP_PME_SIGMA) ? " sigma" : "", (flags & PP_PME_COORD) ? " coordinates" : ""); + fprintf(debug, + "PP rank %d sending to PME rank %d: %d%s%s%s%s\n", + cr->sim_nodeid, + dd->pme_nodeid, + n, + (flags & PP_PME_CHARGE) ? " charges" : "", + (flags & PP_PME_SQRTC6) ? " sqrtC6" : "", + (flags & PP_PME_SIGMA) ? " sigma" : "", + (flags & PP_PME_COORD) ? " coordinates" : ""); } if (useGpuPmePpComms) @@ -161,7 +167,12 @@ static void gmx_pme_send_coeffs_coords(t_forcerec* fr, copy_mat(box, cnb->box); } #if GMX_MPI - MPI_Isend(cnb, sizeof(*cnb), MPI_BYTE, dd->pme_nodeid, eCommType_CNB, cr->mpi_comm_mysim, + MPI_Isend(cnb, + sizeof(*cnb), + MPI_BYTE, + dd->pme_nodeid, + eCommType_CNB, + cr->mpi_comm_mysim, &dd->req_pme[dd->nreq_pme++]); #endif } @@ -169,7 +180,12 @@ static void gmx_pme_send_coeffs_coords(t_forcerec* fr, { #if GMX_MPI /* Communicate only the number of atoms */ - MPI_Isend(&n, sizeof(n), MPI_BYTE, dd->pme_nodeid, eCommType_CNB, cr->mpi_comm_mysim, + MPI_Isend(&n, + sizeof(n), + MPI_BYTE, + dd->pme_nodeid, + eCommType_CNB, + cr->mpi_comm_mysim, &dd->req_pme[dd->nreq_pme++]); #endif } @@ -179,33 +195,63 @@ static void gmx_pme_send_coeffs_coords(t_forcerec* fr, { if (flags & PP_PME_CHARGE) { - MPI_Isend(chargeA, n * sizeof(real), MPI_BYTE, dd->pme_nodeid, eCommType_ChargeA, - cr->mpi_comm_mysim, &dd->req_pme[dd->nreq_pme++]); + MPI_Isend(chargeA, + n * sizeof(real), + MPI_BYTE, + dd->pme_nodeid, + eCommType_ChargeA, + cr->mpi_comm_mysim, + &dd->req_pme[dd->nreq_pme++]); } if (flags & PP_PME_CHARGEB) { - MPI_Isend(chargeB, n * sizeof(real), MPI_BYTE, dd->pme_nodeid, eCommType_ChargeB, - cr->mpi_comm_mysim, &dd->req_pme[dd->nreq_pme++]); + MPI_Isend(chargeB, + n * sizeof(real), + MPI_BYTE, + dd->pme_nodeid, + eCommType_ChargeB, + cr->mpi_comm_mysim, + &dd->req_pme[dd->nreq_pme++]); } if (flags & PP_PME_SQRTC6) { - MPI_Isend(c6A, n * sizeof(real), MPI_BYTE, dd->pme_nodeid, eCommType_SQRTC6A, - cr->mpi_comm_mysim, &dd->req_pme[dd->nreq_pme++]); + MPI_Isend(c6A, + n * sizeof(real), + MPI_BYTE, + dd->pme_nodeid, + eCommType_SQRTC6A, + cr->mpi_comm_mysim, + &dd->req_pme[dd->nreq_pme++]); } if (flags & PP_PME_SQRTC6B) { - MPI_Isend(c6B, n * sizeof(real), MPI_BYTE, dd->pme_nodeid, eCommType_SQRTC6B, - cr->mpi_comm_mysim, &dd->req_pme[dd->nreq_pme++]); + MPI_Isend(c6B, + n * sizeof(real), + MPI_BYTE, + dd->pme_nodeid, + eCommType_SQRTC6B, + cr->mpi_comm_mysim, + &dd->req_pme[dd->nreq_pme++]); } if (flags & PP_PME_SIGMA) { - MPI_Isend(sigmaA, n * sizeof(real), MPI_BYTE, dd->pme_nodeid, eCommType_SigmaA, - cr->mpi_comm_mysim, &dd->req_pme[dd->nreq_pme++]); + MPI_Isend(sigmaA, + n * sizeof(real), + MPI_BYTE, + dd->pme_nodeid, + eCommType_SigmaA, + cr->mpi_comm_mysim, + &dd->req_pme[dd->nreq_pme++]); } if (flags & PP_PME_SIGMAB) { - MPI_Isend(sigmaB, n * sizeof(real), MPI_BYTE, dd->pme_nodeid, eCommType_SigmaB, - cr->mpi_comm_mysim, &dd->req_pme[dd->nreq_pme++]); + MPI_Isend(sigmaB, + n * sizeof(real), + MPI_BYTE, + dd->pme_nodeid, + eCommType_SigmaB, + cr->mpi_comm_mysim, + &dd->req_pme[dd->nreq_pme++]); } if (flags & PP_PME_COORD) { @@ -222,13 +268,18 @@ static void gmx_pme_send_coeffs_coords(t_forcerec* fr, void* sendPtr = sendCoordinatesFromGpu ? static_cast(fr->stateGpu->getCoordinates()) : static_cast(xRealPtr); - fr->pmePpCommGpu->sendCoordinatesToPmeCudaDirect(sendPtr, n, sendCoordinatesFromGpu, - coordinatesReadyOnDeviceEvent); + fr->pmePpCommGpu->sendCoordinatesToPmeCudaDirect( + sendPtr, n, sendCoordinatesFromGpu, coordinatesReadyOnDeviceEvent); } else { - MPI_Isend(xRealPtr, n * sizeof(rvec), MPI_BYTE, dd->pme_nodeid, eCommType_COORD, - cr->mpi_comm_mysim, &dd->req_pme[dd->nreq_pme++]); + MPI_Isend(xRealPtr, + n * sizeof(rvec), + MPI_BYTE, + dd->pme_nodeid, + eCommType_COORD, + cr->mpi_comm_mysim, + &dd->req_pme[dd->nreq_pme++]); } } } @@ -278,9 +329,26 @@ void gmx_pme_send_parameters(const t_commrec* cr, flags |= (flags << 1); } - gmx_pme_send_coeffs_coords(nullptr, cr, flags, chargeA, chargeB, sqrt_c6A, sqrt_c6B, sigmaA, - sigmaB, nullptr, nullptr, 0, 0, maxshift_x, maxshift_y, -1, false, - false, false, nullptr); + gmx_pme_send_coeffs_coords(nullptr, + cr, + flags, + chargeA, + chargeB, + sqrt_c6A, + sqrt_c6B, + sigmaA, + sigmaB, + nullptr, + nullptr, + 0, + 0, + maxshift_x, + maxshift_y, + -1, + false, + false, + false, + nullptr); } void gmx_pme_send_coordinates(t_forcerec* fr, @@ -304,9 +372,25 @@ void gmx_pme_send_coordinates(t_forcerec* fr, { flags |= PP_PME_ENER_VIR; } - gmx_pme_send_coeffs_coords(fr, cr, flags, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, - box, x, lambda_q, lambda_lj, 0, 0, step, useGpuPmePpComms, - receiveCoordinateAddressFromPme, sendCoordinatesFromGpu, + gmx_pme_send_coeffs_coords(fr, + cr, + flags, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + box, + x, + lambda_q, + lambda_lj, + 0, + 0, + step, + useGpuPmePpComms, + receiveCoordinateAddressFromPme, + sendCoordinatesFromGpu, coordinatesReadyOnDeviceEvent); wallcycle_stop(wcycle, ewcPP_PMESENDX); @@ -316,8 +400,26 @@ void gmx_pme_send_finish(const t_commrec* cr) { unsigned int flags = PP_PME_FINISH; - gmx_pme_send_coeffs_coords(nullptr, cr, flags, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, - nullptr, nullptr, 0, 0, 0, 0, -1, false, false, false, nullptr); + gmx_pme_send_coeffs_coords(nullptr, + cr, + flags, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + 0, + 0, + 0, + 0, + -1, + false, + false, + false, + nullptr); } void gmx_pme_send_switchgrid(const t_commrec* cr, ivec grid_size, real ewaldcoeff_q, real ewaldcoeff_lj) @@ -376,8 +478,10 @@ static void receive_virial_energy(const t_commrec* cr, { if (debug) { - fprintf(debug, "PP rank %d receiving from PME rank %d: virial and energy\n", - cr->sim_nodeid, cr->dd->pme_nodeid); + fprintf(debug, + "PP rank %d receiving from PME rank %d: virial and energy\n", + cr->sim_nodeid, + cr->dd->pme_nodeid); } #if GMX_MPI MPI_Recv(&cve, sizeof(cve), MPI_BYTE, cr->dd->pme_nodeid, 1, cr->mpi_comm_mysim, MPI_STATUS_IGNORE); @@ -424,8 +528,7 @@ static void recvFFromPme(gmx::PmePpCommGpu* pmePpCommGpu, { // Receive data using MPI #if GMX_MPI - MPI_Recv(recvptr, n * sizeof(rvec), MPI_BYTE, cr->dd->pme_nodeid, 0, cr->mpi_comm_mysim, - MPI_STATUS_IGNORE); + MPI_Recv(recvptr, n * sizeof(rvec), MPI_BYTE, cr->dd->pme_nodeid, 0, cr->mpi_comm_mysim, MPI_STATUS_IGNORE); #else GMX_UNUSED_VALUE(cr); #endif diff --git a/src/gromacs/ewald/pme_pp_comm_gpu_impl.cu b/src/gromacs/ewald/pme_pp_comm_gpu_impl.cu index acb5998b02..62bffa4e1b 100644 --- a/src/gromacs/ewald/pme_pp_comm_gpu_impl.cu +++ b/src/gromacs/ewald/pme_pp_comm_gpu_impl.cu @@ -101,8 +101,11 @@ void PmePpCommGpu::Impl::receiveForceFromPmeCudaDirect(void* recvPtr, int recvSi // Pull force data from remote GPU void* pmeForcePtr = receivePmeForceToGpu ? static_cast(d_pmeForces_) : recvPtr; - cudaError_t stat = cudaMemcpyAsync(pmeForcePtr, remotePmeFBuffer_, recvSize * DIM * sizeof(float), - cudaMemcpyDefault, pmePpCommStream_.stream()); + cudaError_t stat = cudaMemcpyAsync(pmeForcePtr, + remotePmeFBuffer_, + recvSize * DIM * sizeof(float), + cudaMemcpyDefault, + pmePpCommStream_.stream()); CU_RET_ERR(stat, "cudaMemcpyAsync on Recv from PME CUDA direct data transfer failed"); if (receivePmeForceToGpu) @@ -134,8 +137,11 @@ void PmePpCommGpu::Impl::sendCoordinatesToPmeCudaDirect(void* sendPtr, // ensure stream waits until coordinate data is available on device coordinatesReadyOnDeviceEvent->enqueueWaitEvent(pmePpCommStream_); - cudaError_t stat = cudaMemcpyAsync(remotePmeXBuffer_, sendPtr, sendSize * DIM * sizeof(float), - cudaMemcpyDefault, pmePpCommStream_.stream()); + cudaError_t stat = cudaMemcpyAsync(remotePmeXBuffer_, + sendPtr, + sendSize * DIM * sizeof(float), + cudaMemcpyDefault, + pmePpCommStream_.stream()); CU_RET_ERR(stat, "cudaMemcpyAsync on Send to PME CUDA direct data transfer failed"); // Record and send event to allow PME task to sync to above transfer before commencing force calculations @@ -184,8 +190,8 @@ void PmePpCommGpu::sendCoordinatesToPmeCudaDirect(void* sendPtr, bool sendPmeCoordinatesFromGpu, GpuEventSynchronizer* coordinatesReadyOnDeviceEvent) { - impl_->sendCoordinatesToPmeCudaDirect(sendPtr, sendSize, sendPmeCoordinatesFromGpu, - coordinatesReadyOnDeviceEvent); + impl_->sendCoordinatesToPmeCudaDirect( + sendPtr, sendSize, sendPmeCoordinatesFromGpu, coordinatesReadyOnDeviceEvent); } void* PmePpCommGpu::getGpuForceStagingPtr() diff --git a/src/gromacs/ewald/pme_redistribute.cpp b/src/gromacs/ewald/pme_redistribute.cpp index 063ceded37..0d366f98f2 100644 --- a/src/gromacs/ewald/pme_redistribute.cpp +++ b/src/gromacs/ewald/pme_redistribute.cpp @@ -135,8 +135,12 @@ static void pme_calc_pidx_wrapper(gmx::ArrayRef x, const matrix try { const int natoms = x.ssize(); - pme_calc_pidx(natoms * thread / nthread, natoms * (thread + 1) / nthread, recipbox, x, - atc, atc->count_thread[thread].data()); + pme_calc_pidx(natoms * thread / nthread, + natoms * (thread + 1) / nthread, + recipbox, + x, + atc, + atc->count_thread[thread].data()); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR } @@ -264,8 +268,8 @@ static void pme_dd_sendrecv(PmeAtomComm gmx_unused* atc, if (nbyte_s > 0 && nbyte_r > 0) { - MPI_Sendrecv(buf_s, nbyte_s, MPI_BYTE, dest, shift, buf_r, nbyte_r, MPI_BYTE, src, shift, - atc->mpi_comm, &stat); + MPI_Sendrecv( + buf_s, nbyte_s, MPI_BYTE, dest, shift, buf_r, nbyte_r, MPI_BYTE, src, shift, atc->mpi_comm, &stat); } else if (nbyte_s > 0) { @@ -306,7 +310,9 @@ static void dd_pmeredist_pos_coeffs(gmx_pme_t* pme, "%zd particles communicated to PME rank %d are more than 2/3 times the cut-off " "out of the domain decomposition cell of their charge group in dimension %c.\n" "This usually means that your system is not well equilibrated.", - x.ssize() - (sendCount[atc->nodeid] + nsend), pme->nodeid, 'x' + atc->dimind); + x.ssize() - (sendCount[atc->nodeid] + nsend), + pme->nodeid, + 'x' + atc->dimind); } if (nsend > pme->buf_nalloc) @@ -324,11 +330,10 @@ static void dd_pmeredist_pos_coeffs(gmx_pme_t* pme, /* Communicate the count */ if (debug) { - fprintf(debug, "dimind %d PME rank %d send to rank %d: %d\n", atc->dimind, - atc->nodeid, commnode, scount); + fprintf(debug, "dimind %d PME rank %d send to rank %d: %d\n", atc->dimind, atc->nodeid, commnode, scount); } - pme_dd_sendrecv(atc, FALSE, i, &scount, sizeof(int), &atc->slabCommSetup[i].rcount, - sizeof(int)); + pme_dd_sendrecv( + atc, FALSE, i, &scount, sizeof(int), &atc->slabCommSetup[i].rcount, sizeof(int)); numAtoms += atc->slabCommSetup[i].rcount; } @@ -372,12 +377,22 @@ static void dd_pmeredist_pos_coeffs(gmx_pme_t* pme, if (bX) { /* Communicate the coordinates */ - pme_dd_sendrecv(atc, FALSE, i, pme->bufv + buf_pos, scount * sizeof(rvec), - atc->xBuffer.data() + local_pos, rcount * sizeof(rvec)); + pme_dd_sendrecv(atc, + FALSE, + i, + pme->bufv + buf_pos, + scount * sizeof(rvec), + atc->xBuffer.data() + local_pos, + rcount * sizeof(rvec)); } /* Communicate the coefficients */ - pme_dd_sendrecv(atc, FALSE, i, pme->bufr + buf_pos, scount * sizeof(real), - atc->coefficientBuffer.data() + local_pos, rcount * sizeof(real)); + pme_dd_sendrecv(atc, + FALSE, + i, + pme->bufr + buf_pos, + scount * sizeof(real), + atc->coefficientBuffer.data() + local_pos, + rcount * sizeof(real)); buf_pos += scount; local_pos += atc->slabCommSetup[i].rcount; } @@ -401,8 +416,13 @@ void dd_pmeredist_f(struct gmx_pme_t* pme, PmeAtomComm* atc, gmx::ArrayRef 0 || rcount > 0) { /* Communicate the forces */ - pme_dd_sendrecv(atc, TRUE, i, atc->f.data() + local_pos, scount * sizeof(rvec), - pme->bufv + buf_pos, rcount * sizeof(rvec)); + pme_dd_sendrecv(atc, + TRUE, + i, + atc->f.data() + local_pos, + scount * sizeof(rvec), + pme->bufv + buf_pos, + rcount * sizeof(rvec)); local_pos += scount; } atc->slabCommSetup[commnode].buf_index = buf_pos; diff --git a/src/gromacs/ewald/pme_solve.cpp b/src/gromacs/ewald/pme_solve.cpp index 99ffa7f120..88e529b553 100644 --- a/src/gromacs/ewald/pme_solve.cpp +++ b/src/gromacs/ewald/pme_solve.cpp @@ -110,7 +110,8 @@ static size_t roundUpToMultipleOfFactor(size_t number) static void reallocSimdAlignedAndPadded(real** ptr, int unpaddedNumElements) { sfree_aligned(*ptr); - snew_aligned(*ptr, roundUpToMultipleOfFactor(unpaddedNumElements), + snew_aligned(*ptr, + roundUpToMultipleOfFactor(unpaddedNumElements), c_simdWidth * sizeof(real)); } @@ -359,8 +360,8 @@ int solve_pme_yzx(const gmx_pme_t* pme, t_complex* grid, real vol, bool computeE nz = pme->nkz; /* Dimensions should be identical for A/B grid, so we just use A here */ - gmx_parallel_3dfft_complex_limits(pme->pfft_setup[PME_GRID_QA], complex_order, local_ndata, - local_offset, local_size); + gmx_parallel_3dfft_complex_limits( + pme->pfft_setup[PME_GRID_QA], complex_order, local_ndata, local_offset, local_size); rxx = pme->recipbox[XX][XX]; ryx = pme->recipbox[YY][XX]; @@ -480,7 +481,9 @@ int solve_pme_yzx(const gmx_pme_t* pme, t_complex* grid, real vol, bool computeE } calc_exponentials_q( - kxstart, kxend, elfac, + kxstart, + kxend, + elfac, ArrayRef(denom, denom + roundUpToMultipleOfFactor(kxend)), ArrayRef(tmp1, tmp1 + roundUpToMultipleOfFactor(kxend)), ArrayRef(eterm, eterm + roundUpToMultipleOfFactor(kxend))); @@ -546,7 +549,9 @@ int solve_pme_yzx(const gmx_pme_t* pme, t_complex* grid, real vol, bool computeE } calc_exponentials_q( - kxstart, kxend, elfac, + kxstart, + kxend, + elfac, ArrayRef(denom, denom + roundUpToMultipleOfFactor(kxend)), ArrayRef(tmp1, tmp1 + roundUpToMultipleOfFactor(kxend)), ArrayRef(eterm, eterm + roundUpToMultipleOfFactor(kxend))); @@ -618,8 +623,8 @@ int solve_pme_lj_yzx(const gmx_pme_t* pme, nz = pme->nkz; /* Dimensions should be identical for A/B grid, so we just use A here */ - gmx_parallel_3dfft_complex_limits(pme->pfft_setup[PME_GRID_C6A], complex_order, local_ndata, - local_offset, local_size); + gmx_parallel_3dfft_complex_limits( + pme->pfft_setup[PME_GRID_C6A], complex_order, local_ndata, local_offset, local_size); rxx = pme->recipbox[XX][XX]; ryx = pme->recipbox[YY][XX]; ryy = pme->recipbox[YY][YY]; @@ -726,7 +731,8 @@ int solve_pme_lj_yzx(const gmx_pme_t* pme, } calc_exponentials_lj( - kxstart, kxend, + kxstart, + kxend, ArrayRef(tmp1, tmp1 + roundUpToMultipleOfFactor(kxend)), ArrayRef(tmp2, tmp2 + roundUpToMultipleOfFactor(kxend)), ArrayRef(denom, denom + roundUpToMultipleOfFactor(kxend))); @@ -868,7 +874,8 @@ int solve_pme_lj_yzx(const gmx_pme_t* pme, } calc_exponentials_lj( - kxstart, kxend, + kxstart, + kxend, ArrayRef(tmp1, tmp1 + roundUpToMultipleOfFactor(kxend)), ArrayRef(tmp2, tmp2 + roundUpToMultipleOfFactor(kxend)), ArrayRef(denom, denom + roundUpToMultipleOfFactor(kxend))); diff --git a/src/gromacs/ewald/pme_spread.clh b/src/gromacs/ewald/pme_spread.clh index 9e887a9e6e..d63c40ecbc 100644 --- a/src/gromacs/ewald/pme_spread.clh +++ b/src/gromacs/ewald/pme_spread.clh @@ -452,9 +452,18 @@ __attribute__((reqd_work_group_size(order, order, atomsPerBlock))) __kernel void pme_gpu_stage_atom_data(sm_coordinates, gm_coordinates, DIM); barrier(CLK_LOCAL_MEM_FENCE); - calculate_splines(kernelParams, atomIndexOffset, sm_coordinates, sm_coefficients, sm_theta, - sm_gridlineIndices, sm_fractCoords, gm_theta, gm_dtheta, - gm_gridlineIndices, gm_fractShiftsTable, gm_gridlineIndicesTable); + calculate_splines(kernelParams, + atomIndexOffset, + sm_coordinates, + sm_coefficients, + sm_theta, + sm_gridlineIndices, + sm_fractCoords, + gm_theta, + gm_dtheta, + gm_gridlineIndices, + gm_fractShiftsTable, + gm_gridlineIndicesTable); #if !defined(_AMD_SOURCE_) && !defined(_NVIDIA_SOURCE_) /* This is only here for execution of e.g. 32-sized warps on 16-wide hardware; this was * __syncwarp() in CUDA. #2519 @@ -471,8 +480,8 @@ __attribute__((reqd_work_group_size(order, order, atomsPerBlock))) __kernel void /* Spline data - only thetas (dthetas will only be needed in gather) */ pme_gpu_stage_atom_data(sm_theta, gm_theta, DIM * order); /* Gridline indices - they're actually int and not float, but C99 is angry about overloads */ - pme_gpu_stage_atom_data((__local float*)sm_gridlineIndices, - (__global const float*)gm_gridlineIndices, DIM); + pme_gpu_stage_atom_data( + (__local float*)sm_gridlineIndices, (__global const float*)gm_gridlineIndices, DIM); barrier(CLK_LOCAL_MEM_FENCE); } diff --git a/src/gromacs/ewald/pme_spread.cpp b/src/gromacs/ewald/pme_spread.cpp index c5711797a4..5fe1660c3f 100644 --- a/src/gromacs/ewald/pme_spread.cpp +++ b/src/gromacs/ewald/pme_spread.cpp @@ -417,8 +417,8 @@ static void copy_local_grid(const gmx_pme_t* pme, const pmegrids_t* pmegrids, in int d; real* grid_th; - gmx_parallel_3dfft_real_limits(pme->pfft_setup[grid_index], local_fft_ndata, local_fft_offset, - local_fft_size); + gmx_parallel_3dfft_real_limits( + pme->pfft_setup[grid_index], local_fft_ndata, local_fft_offset, local_fft_size); fft_my = local_fft_size[YY]; fft_mz = local_fft_size[ZZ]; @@ -478,8 +478,8 @@ static void reduce_threadgrid_overlap(const gmx_pme_t* pme, const real* grid_th; real* commbuf = nullptr; - gmx_parallel_3dfft_real_limits(pme->pfft_setup[grid_index], local_fft_ndata, local_fft_offset, - local_fft_size); + gmx_parallel_3dfft_real_limits( + pme->pfft_setup[grid_index], local_fft_ndata, local_fft_offset, local_fft_size); fft_nx = local_fft_ndata[XX]; fft_ny = local_fft_ndata[YY]; fft_nz = local_fft_ndata[ZZ]; @@ -608,9 +608,27 @@ static void reduce_threadgrid_overlap(const gmx_pme_t* pme, #ifdef DEBUG_PME_REDUCE printf("n%d t%d add %d %2d %2d %2d %2d %2d %2d %2d-%2d %2d-%2d, %2d-%2d " "%2d-%2d, %2d-%2d %2d-%2d\n", - pme->nodeid, thread, thread_f, pme->pmegrid_start_ix, pme->pmegrid_start_iy, - pme->pmegrid_start_iz, sx, sy, sz, offx - ox, tx1 - ox, offx, tx1, offy - oy, - ty1 - oy, offy, ty1, offz - oz, tz1 - oz, offz, tz1); + pme->nodeid, + thread, + thread_f, + pme->pmegrid_start_ix, + pme->pmegrid_start_iy, + pme->pmegrid_start_iz, + sx, + sy, + sz, + offx - ox, + tx1 - ox, + offx, + tx1, + offy - oy, + ty1 - oy, + offy, + ty1, + offz - oz, + tz1 - oz, + offz, + tz1); #endif if (!(bCommX || bCommY)) @@ -716,8 +734,8 @@ static void sum_fftgrid_dd(const gmx_pme_t* pme, real* fftgrid, int grid_index) * communication setup. */ - gmx_parallel_3dfft_real_limits(pme->pfft_setup[grid_index], local_fft_ndata, local_fft_offset, - local_fft_size); + gmx_parallel_3dfft_real_limits( + pme->pfft_setup[grid_index], local_fft_ndata, local_fft_offset, local_fft_size); if (pme->nnodes_minor > 1) { @@ -752,15 +770,28 @@ static void sum_fftgrid_dd(const gmx_pme_t* pme, real* fftgrid, int grid_index) if (debug != nullptr) { - fprintf(debug, "PME fftgrid comm y %2d x %2d x %2d\n", local_fft_ndata[XX], - send_nindex, local_fft_ndata[ZZ]); + fprintf(debug, + "PME fftgrid comm y %2d x %2d x %2d\n", + local_fft_ndata[XX], + send_nindex, + local_fft_ndata[ZZ]); } #if GMX_MPI int send_id = overlap->comm_data[ipulse].send_id; int recv_id = overlap->comm_data[ipulse].recv_id; - MPI_Sendrecv(sendptr, send_size_y * datasize, GMX_MPI_REAL, send_id, ipulse, recvptr, - recv_size_y * datasize, GMX_MPI_REAL, recv_id, ipulse, overlap->mpi_comm, &stat); + MPI_Sendrecv(sendptr, + send_size_y * datasize, + GMX_MPI_REAL, + send_id, + ipulse, + recvptr, + recv_size_y * datasize, + GMX_MPI_REAL, + recv_id, + ipulse, + overlap->mpi_comm, + &stat); #endif for (x = 0; x < local_fft_ndata[XX]; x++) @@ -813,7 +844,10 @@ static void sum_fftgrid_dd(const gmx_pme_t* pme, real* fftgrid, int grid_index) if (debug != nullptr) { - fprintf(debug, "PME fftgrid comm x %2d x %2d x %2d\n", send_nindex, local_fft_ndata[YY], + fprintf(debug, + "PME fftgrid comm x %2d x %2d x %2d\n", + send_nindex, + local_fft_ndata[YY], local_fft_ndata[ZZ]); } @@ -823,8 +857,18 @@ static void sum_fftgrid_dd(const gmx_pme_t* pme, real* fftgrid, int grid_index) int recv_id = overlap->comm_data[ipulse].recv_id; auto* sendptr = const_cast(overlap->sendbuf.data()); auto* recvptr = const_cast(overlap->recvbuf.data()); - MPI_Sendrecv(sendptr, send_nindex * datasize, GMX_MPI_REAL, send_id, ipulse, recvptr, - recv_nindex * datasize, GMX_MPI_REAL, recv_id, ipulse, overlap->mpi_comm, &stat); + MPI_Sendrecv(sendptr, + send_nindex * datasize, + GMX_MPI_REAL, + send_id, + ipulse, + recvptr, + recv_nindex * datasize, + GMX_MPI_REAL, + recv_id, + ipulse, + overlap->mpi_comm, + &stat); #endif for (x = 0; x < recv_nindex; x++) @@ -925,9 +969,14 @@ void spread_on_grid(const gmx_pme_t* pme, if (bCalcSplines) { - make_bsplines(spline->theta.coefficients, spline->dtheta.coefficients, - pme->pme_order, as_rvec_array(atc->fractx.data()), spline->n, - spline->ind.data(), atc->coefficient.data(), bDoSplines); + make_bsplines(spline->theta.coefficients, + spline->dtheta.coefficients, + pme->pme_order, + as_rvec_array(atc->fractx.data()), + spline->n, + spline->ind.data(), + atc->coefficient.data(), + bDoSplines); } if (bSpread) @@ -967,9 +1016,13 @@ void spread_on_grid(const gmx_pme_t* pme, { try { - reduce_threadgrid_overlap(pme, grids, thread, fftgrid, + reduce_threadgrid_overlap(pme, + grids, + thread, + fftgrid, const_cast(pme->overlap[0].sendbuf.data()), - const_cast(pme->overlap[1].sendbuf.data()), grid_index); + const_cast(pme->overlap[1].sendbuf.data()), + grid_index); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR } diff --git a/src/gromacs/ewald/pme_spread.cu b/src/gromacs/ewald/pme_spread.cu index 3cf3a1f7ca..62f3a61c8b 100644 --- a/src/gromacs/ewald/pme_spread.cu +++ b/src/gromacs/ewald/pme_spread.cu @@ -274,8 +274,8 @@ __launch_bounds__(c_spreadMaxThreadsPerBlock) CLANG_DISABLE_OPTIMIZATION_ATTRIBU /* Spreading */ if (spreadCharges) { - spread_charges(kernelParams, &atomCharge, - sm_gridlineIndices, sm_theta); + spread_charges( + kernelParams, &atomCharge, sm_gridlineIndices, sm_theta); } if (numGrids == 2) { @@ -293,8 +293,8 @@ __launch_bounds__(c_spreadMaxThreadsPerBlock) CLANG_DISABLE_OPTIMIZATION_ATTRIBU } if (spreadCharges) { - spread_charges(kernelParams, &atomCharge, - sm_gridlineIndices, sm_theta); + spread_charges( + kernelParams, &atomCharge, sm_gridlineIndices, sm_theta); } } } diff --git a/src/gromacs/ewald/tests/pmebsplinetest.cpp b/src/gromacs/ewald/tests/pmebsplinetest.cpp index b6a4e9e35f..aaf475f3c5 100644 --- a/src/gromacs/ewald/tests/pmebsplinetest.cpp +++ b/src/gromacs/ewald/tests/pmebsplinetest.cpp @@ -90,8 +90,11 @@ public: /* Describing the test in case it fails */ SCOPED_TRACE(formatString( "Testing B-spline moduli creation (%s) for PME order %d, grid size %d %d %d", - (moduliType == ModuliType::P3M) ? "P3M" : "plain", pmeOrder, gridSize[XX], - gridSize[YY], gridSize[ZZ])); + (moduliType == ModuliType::P3M) ? "P3M" : "plain", + pmeOrder, + gridSize[XX], + gridSize[YY], + gridSize[ZZ])); /* Storing the input where it's needed */ t_inputrec inputRec; @@ -147,7 +150,9 @@ std::vector const invalidInputs{ BSplineModuliInputParameters{ IVec{ 64, 2, 64 }, sanePmeOrder, ModuliType::PME }, /* Invalid interpolation orders */ BSplineModuliInputParameters{ - saneGridSize, 8 + 1, ModuliType::P3M // P3M only supports orders up to 8 + saneGridSize, + 8 + 1, + ModuliType::P3M // P3M only supports orders up to 8 }, BSplineModuliInputParameters{ saneGridSize, PME_ORDER_MAX + 1, ModuliType::PME }, }; diff --git a/src/gromacs/ewald/tests/pmegathertest.cpp b/src/gromacs/ewald/tests/pmegathertest.cpp index 1190caea1d..dde08758ee 100644 --- a/src/gromacs/ewald/tests/pmegathertest.cpp +++ b/src/gromacs/ewald/tests/pmegathertest.cpp @@ -298,13 +298,19 @@ public: SCOPED_TRACE( formatString("Testing force gathering on %s for PME grid size %d %d %d" ", order %d, %zu atoms", - pmeTestHardwareContext->description().c_str(), gridSize[XX], - gridSize[YY], gridSize[ZZ], pmeOrder, atomCount)); - - PmeSafePointer pmeSafe = - pmeInitWrapper(&inputRec, codePath, pmeTestHardwareContext->deviceContext(), - pmeTestHardwareContext->deviceStream(), - pmeTestHardwareContext->pmeGpuProgram(), box); + pmeTestHardwareContext->description().c_str(), + gridSize[XX], + gridSize[YY], + gridSize[ZZ], + pmeOrder, + atomCount)); + + PmeSafePointer pmeSafe = pmeInitWrapper(&inputRec, + codePath, + pmeTestHardwareContext->deviceContext(), + pmeTestHardwareContext->deviceStream(), + pmeTestHardwareContext->pmeGpuProgram(), + box); std::unique_ptr stateGpu = (codePath == CodePath::GPU) ? makeStatePropagatorDataGpu(*pmeSafe.get(), @@ -312,7 +318,10 @@ public: pmeTestHardwareContext->deviceStream()) : nullptr; - pmeInitAtoms(pmeSafe.get(), stateGpu.get(), codePath, inputAtomData.coordinates, + pmeInitAtoms(pmeSafe.get(), + stateGpu.get(), + codePath, + inputAtomData.coordinates, inputAtomData.charges); /* Setting some more inputs */ @@ -320,10 +329,16 @@ public: pmeSetGridLineIndices(pmeSafe.get(), codePath, inputAtomData.gridLineIndices); for (int dimIndex = 0; dimIndex < DIM; dimIndex++) { - pmeSetSplineData(pmeSafe.get(), codePath, inputAtomSplineData.splineValues[dimIndex], - PmeSplineDataType::Values, dimIndex); - pmeSetSplineData(pmeSafe.get(), codePath, inputAtomSplineData.splineDerivatives[dimIndex], - PmeSplineDataType::Derivatives, dimIndex); + pmeSetSplineData(pmeSafe.get(), + codePath, + inputAtomSplineData.splineValues[dimIndex], + PmeSplineDataType::Values, + dimIndex); + pmeSetSplineData(pmeSafe.get(), + codePath, + inputAtomSplineData.splineDerivatives[dimIndex], + PmeSplineDataType::Derivatives, + dimIndex); } /* Explicitly copying the sample forces to be able to modify them */ diff --git a/src/gromacs/ewald/tests/pmesolvetest.cpp b/src/gromacs/ewald/tests/pmesolvetest.cpp index 578fa8caa7..f32517da5d 100644 --- a/src/gromacs/ewald/tests/pmesolvetest.cpp +++ b/src/gromacs/ewald/tests/pmesolvetest.cpp @@ -119,9 +119,9 @@ public: if (!supportedInput) { /* Testing the failure for the unsupported input */ - EXPECT_THROW_GMX(pmeInitWrapper(&inputRec, codePath, nullptr, nullptr, nullptr, box, - ewaldCoeff_q, ewaldCoeff_lj), - NotImplementedError); + EXPECT_THROW_GMX( + pmeInitWrapper(&inputRec, codePath, nullptr, nullptr, nullptr, box, ewaldCoeff_q, ewaldCoeff_lj), + NotImplementedError); continue; } @@ -140,20 +140,28 @@ public: "Testing solving (%s, %s, %s energy/virial) on %s for PME grid " "size %d %d %d, Ewald coefficients %g %g", (method == PmeSolveAlgorithm::LennardJones) ? "Lennard-Jones" : "Coulomb", - gridOrdering.second.c_str(), computeEnergyAndVirial ? "with" : "without", - pmeTestHardwareContext->description().c_str(), gridSize[XX], - gridSize[YY], gridSize[ZZ], ewaldCoeff_q, ewaldCoeff_lj)); + gridOrdering.second.c_str(), + computeEnergyAndVirial ? "with" : "without", + pmeTestHardwareContext->description().c_str(), + gridSize[XX], + gridSize[YY], + gridSize[ZZ], + ewaldCoeff_q, + ewaldCoeff_lj)); /* Running the test */ - PmeSafePointer pmeSafe = pmeInitWrapper( - &inputRec, codePath, pmeTestHardwareContext->deviceContext(), - pmeTestHardwareContext->deviceStream(), - pmeTestHardwareContext->pmeGpuProgram(), box, ewaldCoeff_q, ewaldCoeff_lj); + PmeSafePointer pmeSafe = pmeInitWrapper(&inputRec, + codePath, + pmeTestHardwareContext->deviceContext(), + pmeTestHardwareContext->deviceStream(), + pmeTestHardwareContext->pmeGpuProgram(), + box, + ewaldCoeff_q, + ewaldCoeff_lj); pmeSetComplexGrid(pmeSafe.get(), codePath, gridOrdering.first, nonZeroGridValues); const real cellVolume = box[0] * box[4] * box[8]; // FIXME - this is box[XX][XX] * box[YY][YY] * box[ZZ][ZZ], should be stored in the PME structure - pmePerformSolve(pmeSafe.get(), codePath, method, cellVolume, gridOrdering.first, - computeEnergyAndVirial); + pmePerformSolve(pmeSafe.get(), codePath, method, cellVolume, gridOrdering.first, computeEnergyAndVirial); pmeFinalizeTest(pmeSafe.get(), codePath); /* Check the outputs */ @@ -181,7 +189,8 @@ public: const uint64_t splineModuliDoublePrecisionUlps = getSplineModuliDoublePrecisionUlps(inputRec.pme_order + 1); auto gridTolerance = relativeToleranceAsPrecisionDependentUlp( - gridValuesMagnitude, gridUlpToleranceFactor * c_splineModuliSinglePrecisionUlps, + gridValuesMagnitude, + gridUlpToleranceFactor * c_splineModuliSinglePrecisionUlps, gridUlpToleranceFactor * splineModuliDoublePrecisionUlps); gridValuesChecker.setDefaultTolerance(gridTolerance); @@ -220,7 +229,8 @@ public: // TODO This factor is arbitrary, do a proper error-propagation analysis uint64_t energyUlpToleranceFactor = gridUlpToleranceFactor * 2; auto energyTolerance = relativeToleranceAsPrecisionDependentUlp( - energyMagnitude, energyUlpToleranceFactor * c_splineModuliSinglePrecisionUlps, + energyMagnitude, + energyUlpToleranceFactor * c_splineModuliSinglePrecisionUlps, energyUlpToleranceFactor * splineModuliDoublePrecisionUlps); TestReferenceChecker energyChecker(checker); energyChecker.setDefaultTolerance(energyTolerance); @@ -231,7 +241,8 @@ public: // TODO This factor is arbitrary, do a proper error-propagation analysis uint64_t virialUlpToleranceFactor = energyUlpToleranceFactor * 2; auto virialTolerance = relativeToleranceAsPrecisionDependentUlp( - virialMagnitude, virialUlpToleranceFactor * c_splineModuliSinglePrecisionUlps, + virialMagnitude, + virialUlpToleranceFactor * c_splineModuliSinglePrecisionUlps, virialUlpToleranceFactor * splineModuliDoublePrecisionUlps); TestReferenceChecker virialChecker( checker.checkCompound("Matrix", "Virial")); diff --git a/src/gromacs/ewald/tests/pmesplinespreadtest.cpp b/src/gromacs/ewald/tests/pmesplinespreadtest.cpp index 4765acbddb..032188c247 100644 --- a/src/gromacs/ewald/tests/pmesplinespreadtest.cpp +++ b/src/gromacs/ewald/tests/pmesplinespreadtest.cpp @@ -145,18 +145,25 @@ public: { /* Describing the test uniquely in case it fails */ - SCOPED_TRACE(formatString( - "Testing %s on %s for PME grid size %d %d %d" - ", order %d, %zu atoms", - option.second.c_str(), pmeTestHardwareContext->description().c_str(), - gridSize[XX], gridSize[YY], gridSize[ZZ], pmeOrder, atomCount)); + SCOPED_TRACE( + formatString("Testing %s on %s for PME grid size %d %d %d" + ", order %d, %zu atoms", + option.second.c_str(), + pmeTestHardwareContext->description().c_str(), + gridSize[XX], + gridSize[YY], + gridSize[ZZ], + pmeOrder, + atomCount)); /* Running the test */ - PmeSafePointer pmeSafe = - pmeInitWrapper(&inputRec, codePath, pmeTestHardwareContext->deviceContext(), - pmeTestHardwareContext->deviceStream(), - pmeTestHardwareContext->pmeGpuProgram(), box); + PmeSafePointer pmeSafe = pmeInitWrapper(&inputRec, + codePath, + pmeTestHardwareContext->deviceContext(), + pmeTestHardwareContext->deviceStream(), + pmeTestHardwareContext->pmeGpuProgram(), + box); std::unique_ptr stateGpu = (codePath == CodePath::GPU) ? makeStatePropagatorDataGpu(*pmeSafe.get(), @@ -211,8 +218,8 @@ public: { auto splineValuesDim = pmeGetSplineData(pmeSafe.get(), codePath, PmeSplineDataType::Values, i); - splineValuesChecker.checkSequence(splineValuesDim.begin(), - splineValuesDim.end(), dimString[i]); + splineValuesChecker.checkSequence( + splineValuesDim.begin(), splineValuesDim.end(), dimString[i]); } /* Spline derivatives */ @@ -234,8 +241,8 @@ public: /* Particle gridline indices */ auto gridLineIndices = pmeGetGridlineIndices(pmeSafe.get(), codePath); - rootChecker.checkSequence(gridLineIndices.begin(), gridLineIndices.end(), - "Gridline indices"); + rootChecker.checkSequence( + gridLineIndices.begin(), gridLineIndices.end(), "Gridline indices"); } if (spreadCharges) @@ -308,28 +315,40 @@ auto const c_sampleCharges13 = ChargesVector(c_sampleChargesFull).subArray(3, 13 //! Random coordinate vectors CoordinatesVector const c_sampleCoordinatesFull{ { 5.59F, 1.37F, 0.95F }, { - 16.0F, 1.02F, 0.22F // 2 box lengths in x + 16.0F, + 1.02F, + 0.22F // 2 box lengths in x }, { 0.034F, 1.65F, 0.22F }, { 0.33F, 0.92F, 1.56F }, { 1.16F, 0.75F, 0.39F }, { 0.5F, 1.63F, 1.14F }, { - 16.0001F, 1.52F, 1.19F // > 2 box lengths in x + 16.0001F, + 1.52F, + 1.19F // > 2 box lengths in x }, { - 1.43F, 1.1F, 4.1F // > 2 box lengths in z + 1.43F, + 1.1F, + 4.1F // > 2 box lengths in z }, { - -1.08F, 1.19F, 0.08F // negative x + -1.08F, + 1.19F, + 0.08F // negative x }, { 1.6F, 0.93F, 0.53F }, { - 1.32F, -1.48F, 0.16F // negative y + 1.32F, + -1.48F, + 0.16F // negative y }, { 0.87F, 0.0F, 0.33F }, { - 0.95F, 7.7F, -0.48F // > 2 box lengths in y, negative z + 0.95F, + 7.7F, + -0.48F // > 2 box lengths in y, negative z }, { 1.23F, 0.91F, 0.68F }, { 0.19F, 1.45F, 0.94F }, diff --git a/src/gromacs/ewald/tests/pmetestcommon.cpp b/src/gromacs/ewald/tests/pmetestcommon.cpp index eb1e170411..63f0cadb11 100644 --- a/src/gromacs/ewald/tests/pmetestcommon.cpp +++ b/src/gromacs/ewald/tests/pmetestcommon.cpp @@ -120,9 +120,21 @@ PmeSafePointer pmeInitWrapper(const t_inputrec* inputRec, const auto runMode = (mode == CodePath::CPU) ? PmeRunMode::CPU : PmeRunMode::Mixed; t_commrec dummyCommrec = { 0 }; NumPmeDomains numPmeDomains = { 1, 1 }; - gmx_pme_t* pmeDataRaw = gmx_pme_init(&dummyCommrec, numPmeDomains, inputRec, false, false, true, - ewaldCoeff_q, ewaldCoeff_lj, 1, runMode, nullptr, - deviceContext, deviceStream, pmeGpuProgram, dummyLogger); + gmx_pme_t* pmeDataRaw = gmx_pme_init(&dummyCommrec, + numPmeDomains, + inputRec, + false, + false, + true, + ewaldCoeff_q, + ewaldCoeff_lj, + 1, + runMode, + nullptr, + deviceContext, + deviceStream, + pmeGpuProgram, + dummyLogger); PmeSafePointer pme(pmeDataRaw); // taking ownership // TODO get rid of this with proper matrix type @@ -166,8 +178,8 @@ std::unique_ptr makeStatePropagatorDataGpu(const gmx_pme // TODO: Pin the host buffer and use async memory copies // TODO: Special constructor for PME-only rank / PME-tests is used here. There should be a mechanism to // restrict one from using other constructor here. - return std::make_unique(deviceStream, *deviceContext, GpuApiCallBehavior::Sync, - pme_gpu_get_block_size(&pme), nullptr); + return std::make_unique( + deviceStream, *deviceContext, GpuApiCallBehavior::Sync, pme_gpu_get_block_size(&pme), nullptr); } //! PME initialization with atom data @@ -227,8 +239,8 @@ static void pmeGetRealGridSizesInternal(const gmx_pme_t* pme, switch (mode) { case CodePath::CPU: - gmx_parallel_3dfft_real_limits(pme->pfft_setup[gridIndex], gridSize, gridOffsetUnused, - paddedGridSize); + gmx_parallel_3dfft_real_limits( + pme->pfft_setup[gridIndex], gridSize, gridOffsetUnused, paddedGridSize); break; case CodePath::GPU: @@ -253,8 +265,8 @@ static void pmeGetComplexGridSizesInternal(const gmx_pme_t* pme, { const size_t gridIndex = 0; IVec gridOffsetUnused, complexOrderUnused; - gmx_parallel_3dfft_complex_limits(pme->pfft_setup[gridIndex], complexOrderUnused, gridSize, - gridOffsetUnused, paddedGridSize); // TODO: what about YZX ordering? + gmx_parallel_3dfft_complex_limits( + pme->pfft_setup[gridIndex], complexOrderUnused, gridSize, gridOffsetUnused, paddedGridSize); // TODO: what about YZX ordering? } //! Getting the PME grid memory buffer and its sizes - template definition @@ -305,9 +317,14 @@ void pmePerformSplineAndSpread(gmx_pme_t* pme, switch (mode) { case CodePath::CPU: - spread_on_grid(pme, atc, &pme->pmegrid[gridIndex], computeSplines, spreadCharges, + spread_on_grid(pme, + atc, + &pme->pmegrid[gridIndex], + computeSplines, + spreadCharges, fftgrid != nullptr ? fftgrid[gridIndex] : nullptr, - computeSplinesForZeroCharges, gridIndex); + computeSplinesForZeroCharges, + gridIndex); if (spreadCharges && !pme->bUseThreads) { wrap_periodic_pmegrid(pme, pmegrid); @@ -381,8 +398,13 @@ void pmePerformSolve(const gmx_pme_t* pme, break; case PmeSolveAlgorithm::LennardJones: - solve_pme_lj_yzx(pme, &h_grid, useLorentzBerthelot, cellVolume, - computeEnergyAndVirial, pme->nthread, threadIndex); + solve_pme_lj_yzx(pme, + &h_grid, + useLorentzBerthelot, + cellVolume, + computeEnergyAndVirial, + pme->nthread, + threadIndex); break; default: GMX_THROW(InternalError("Test not implemented for this mode")); @@ -659,7 +681,8 @@ void pmeSetGridLineIndices(gmx_pme_t* pme, CodePath mode, const GridLineIndicesV switch (mode) { case CodePath::GPU: - memcpy(pme_gpu_staging(pme->gpu).h_gridlineIndices, gridLineIndices.data(), + memcpy(pme_gpu_staging(pme->gpu).h_gridlineIndices, + gridLineIndices.data(), atomCount * sizeof(gridLineIndices[0])); break; @@ -705,8 +728,7 @@ static void pmeSetGridInternal(const gmx_pme_t* pme, { case CodePath::GPU: // intentional absence of break, the grid will be copied from the host buffer in testing mode case CodePath::CPU: - std::memset(grid, 0, - paddedGridSize[XX] * paddedGridSize[YY] * paddedGridSize[ZZ] * sizeof(ValueType)); + std::memset(grid, 0, paddedGridSize[XX] * paddedGridSize[YY] * paddedGridSize[ZZ] * sizeof(ValueType)); for (const auto& gridValue : gridValues) { for (int i = 0; i < DIM; i++) diff --git a/src/gromacs/fft/calcgrid.cpp b/src/gromacs/fft/calcgrid.cpp index de0bbb1b9a..22a842f35c 100644 --- a/src/gromacs/fft/calcgrid.cpp +++ b/src/gromacs/fft/calcgrid.cpp @@ -107,8 +107,11 @@ real calcFftGrid(FILE* fp, const matrix box, real gridSpacing, int minGridPoints { if (nullptr != fp) { - fprintf(fp, "Calculating fourier grid dimensions for%s%s%s\n", *nx > 0 ? "" : " X", - *ny > 0 ? "" : " Y", *nz > 0 ? "" : " Z"); + fprintf(fp, + "Calculating fourier grid dimensions for%s%s%s\n", + *nx > 0 ? "" : " X", + *ny > 0 ? "" : " Y", + *nz > 0 ? "" : " Z"); } } @@ -161,8 +164,14 @@ real calcFftGrid(FILE* fp, const matrix box, real gridSpacing, int minGridPoints *nz = n[ZZ]; if (nullptr != fp) { - fprintf(fp, "Using a fourier grid of %dx%dx%d, spacing %.3f %.3f %.3f\n", *nx, *ny, *nz, - spacing[XX], spacing[YY], spacing[ZZ]); + fprintf(fp, + "Using a fourier grid of %dx%dx%d, spacing %.3f %.3f %.3f\n", + *nx, + *ny, + *nz, + spacing[XX], + spacing[YY], + spacing[ZZ]); } return max_spacing; diff --git a/src/gromacs/fft/fft5d.cpp b/src/gromacs/fft/fft5d.cpp index e01d28027b..03fb8da297 100644 --- a/src/gromacs/fft/fft5d.cpp +++ b/src/gromacs/fft/fft5d.cpp @@ -223,8 +223,14 @@ fft5d_plan fft5d_plan_3d(int NG, fprintf(debug, "FFT5D: N: %d, M: %d, K: %d, P: %dx%d, real2complex: %d, backward: %d, order " "yz: %d, debug %d\n", - NG, MG, KG, P[0], P[1], int((flags & FFT5D_REALCOMPLEX) > 0), - int((flags & FFT5D_BACKWARD) > 0), int((flags & FFT5D_ORDER_YZ) > 0), + NG, + MG, + KG, + P[0], + P[1], + int((flags & FFT5D_REALCOMPLEX) > 0), + int((flags & FFT5D_BACKWARD) > 0), + int((flags & FFT5D_ORDER_YZ) > 0), int((flags & FFT5D_DEBUG) > 0)); } /* The check below is not correct, one prime factor 11 or 13 is ok. @@ -582,16 +588,20 @@ fft5d_plan fft5d_plan_3d(int NG, # endif if ((flags & FFT5D_REALCOMPLEX) && !(flags & FFT5D_BACKWARD)) { - plan->p3d = FFTW(plan_guru_dft_r2c)(/*rank*/ 3, dims, - /*howmany*/ 0, /*howmany_dims*/ nullptr, + plan->p3d = FFTW(plan_guru_dft_r2c)(/*rank*/ 3, + dims, + /*howmany*/ 0, + /*howmany_dims*/ nullptr, reinterpret_cast(lin), reinterpret_cast(lout), /*flags*/ fftwflags); } else if ((flags & FFT5D_REALCOMPLEX) && (flags & FFT5D_BACKWARD)) { - plan->p3d = FFTW(plan_guru_dft_c2r)(/*rank*/ 3, dims, - /*howmany*/ 0, /*howmany_dims*/ nullptr, + plan->p3d = FFTW(plan_guru_dft_c2r)(/*rank*/ 3, + dims, + /*howmany*/ 0, + /*howmany_dims*/ nullptr, reinterpret_cast(lin), reinterpret_cast(lout), /*flags*/ fftwflags); @@ -599,10 +609,14 @@ fft5d_plan fft5d_plan_3d(int NG, else { plan->p3d = FFTW(plan_guru_dft)( - /*rank*/ 3, dims, - /*howmany*/ 0, /*howmany_dims*/ nullptr, reinterpret_cast(lin), + /*rank*/ 3, + dims, + /*howmany*/ 0, + /*howmany_dims*/ nullptr, + reinterpret_cast(lin), reinterpret_cast(lout), - /*sign*/ (flags & FFT5D_BACKWARD) ? 1 : -1, /*flags*/ fftwflags); + /*sign*/ (flags & FFT5D_BACKWARD) ? 1 : -1, + /*flags*/ fftwflags); } # ifdef FFT5D_THREADS # ifdef FFT5D_FFTW_THREADS @@ -618,8 +632,7 @@ fft5d_plan fft5d_plan_3d(int NG, { if (debug) { - fprintf(debug, "FFT5D: Plan s %d rC %d M %d pK %d C %d lsize %d\n", s, rC[s], M[s], - pK[s], C[s], lsize); + fprintf(debug, "FFT5D: Plan s %d rC %d M %d pK %d C %d lsize %d\n", s, rC[s], M[s], pK[s], C[s], lsize); } plan->p1d[s] = static_cast(malloc(sizeof(gmx_fft_t) * nthreads)); @@ -640,12 +653,16 @@ fft5d_plan fft5d_plan_3d(int NG, || ((flags & FFT5D_BACKWARD) && s == 2))) { gmx_fft_init_many_1d_real( - &plan->p1d[s][t], rC[s], tsize, + &plan->p1d[s][t], + rC[s], + tsize, (flags & FFT5D_NOMEASURE) ? GMX_FFT_FLAG_CONSERVATIVE : 0); } else { - gmx_fft_init_many_1d(&plan->p1d[s][t], C[s], tsize, + gmx_fft_init_many_1d(&plan->p1d[s][t], + C[s], + tsize, (flags & FFT5D_NOMEASURE) ? GMX_FFT_FLAG_CONSERVATIVE : 0); } } @@ -673,15 +690,13 @@ fft5d_plan fft5d_plan_3d(int NG, { if ((s == 0 && !(flags & FFT5D_ORDER_YZ)) || (s == 1 && (flags & FFT5D_ORDER_YZ))) { - plan->mpip[s] = FFTW(mpi_plan_many_transpose)(nP[s], nP[s], N[s] * K[s] * pM[s] * 2, 1, - 1, (real*)lout2, (real*)lout3, - plan->cart[s], FFTW_PATIENT); + plan->mpip[s] = FFTW(mpi_plan_many_transpose)( + nP[s], nP[s], N[s] * K[s] * pM[s] * 2, 1, 1, (real*)lout2, (real*)lout3, plan->cart[s], FFTW_PATIENT); } else { - plan->mpip[s] = FFTW(mpi_plan_many_transpose)(nP[s], nP[s], N[s] * pK[s] * M[s] * 2, 1, - 1, (real*)lout2, (real*)lout3, - plan->cart[s], FFTW_PATIENT); + plan->mpip[s] = FFTW(mpi_plan_many_transpose)( + nP[s], nP[s], N[s] * pK[s] * M[s] * 2, 1, 1, (real*)lout2, (real*)lout3, plan->cart[s], FFTW_PATIENT); } } FFTW_UNLOCK; @@ -1085,7 +1100,8 @@ static void print_localdata(const t_complex* lin, const char* txt, int s, fft5d_ { for (l = 0; l < ll; l++) { - fprintf(debug, "%f ", + fprintf(debug, + "%f ", reinterpret_cast( lin)[(z * xs[2] + y * xs[1]) * 2 + (x * xs[0]) * ll + l]); } @@ -1195,13 +1211,15 @@ void fft5d_execute(fft5d_plan plan, int thread, fft5d_time times) gmx_fft_many_1d_real(p1d[s][thread], (plan->flags & FFT5D_BACKWARD) ? GMX_FFT_COMPLEX_TO_REAL : GMX_FFT_REAL_TO_COMPLEX, - lin + tstart, fftout + tstart); + lin + tstart, + fftout + tstart); } else { gmx_fft_many_1d(p1d[s][thread], (plan->flags & FFT5D_BACKWARD) ? GMX_FFT_BACKWARD : GMX_FFT_FORWARD, - lin + tstart, fftout + tstart); + lin + tstart, + fftout + tstart); } #ifdef NOGMX @@ -1233,8 +1251,20 @@ void fft5d_execute(fft5d_plan plan, int thread, fft5d_time times) { tend = ((thread + 1) * pM[s] * pK[s] / plan->nthreads); tstart /= C[s]; - splitaxes(lout2, lout, N[s], M[s], K[s], pM[s], P[s], C[s], iNout[s], oNout[s], - tstart % pM[s], tstart / pM[s], tend % pM[s], tend / pM[s]); + splitaxes(lout2, + lout, + N[s], + M[s], + K[s], + pM[s], + P[s], + C[s], + iNout[s], + oNout[s], + tstart % pM[s], + tstart / pM[s], + tend % pM[s], + tend / pM[s]); } #pragma omp barrier /*barrier required before AllToAll (all input has to be their) - before timing to make timing more acurate*/ #ifdef NOGMX @@ -1265,17 +1295,21 @@ void fft5d_execute(fft5d_plan plan, int thread, fft5d_time times) { MPI_Alltoall(reinterpret_cast(lout2), N[s] * pM[s] * K[s] * sizeof(t_complex) / sizeof(real), - GMX_MPI_REAL, reinterpret_cast(lout3), + GMX_MPI_REAL, + reinterpret_cast(lout3), N[s] * pM[s] * K[s] * sizeof(t_complex) / sizeof(real), - GMX_MPI_REAL, cart[s]); + GMX_MPI_REAL, + cart[s]); } else { MPI_Alltoall(reinterpret_cast(lout2), N[s] * M[s] * pK[s] * sizeof(t_complex) / sizeof(real), - GMX_MPI_REAL, reinterpret_cast(lout3), + GMX_MPI_REAL, + reinterpret_cast(lout3), N[s] * M[s] * pK[s] * sizeof(t_complex) / sizeof(real), - GMX_MPI_REAL, cart[s]); + GMX_MPI_REAL, + cart[s]); } # else GMX_RELEASE_ASSERT(false, "Invalid call to fft5d_execute"); @@ -1322,8 +1356,20 @@ void fft5d_execute(fft5d_plan plan, int thread, fft5d_time times) { tstart = (thread * pM[s] * pN[s] / plan->nthreads); tend = ((thread + 1) * pM[s] * pN[s] / plan->nthreads); - joinAxesTrans13(lin, joinin, N[s], pM[s], K[s], pM[s], P[s], C[s + 1], iNin[s + 1], - oNin[s + 1], tstart % pM[s], tstart / pM[s], tend % pM[s], tend / pM[s]); + joinAxesTrans13(lin, + joinin, + N[s], + pM[s], + K[s], + pM[s], + P[s], + C[s + 1], + iNin[s + 1], + oNin[s + 1], + tstart % pM[s], + tstart / pM[s], + tend % pM[s], + tend / pM[s]); } } else @@ -1332,8 +1378,20 @@ void fft5d_execute(fft5d_plan plan, int thread, fft5d_time times) { tstart = (thread * pK[s] * pN[s] / plan->nthreads); tend = ((thread + 1) * pK[s] * pN[s] / plan->nthreads); - joinAxesTrans12(lin, joinin, N[s], M[s], pK[s], pN[s], P[s], C[s + 1], iNin[s + 1], - oNin[s + 1], tstart % pN[s], tstart / pN[s], tend % pN[s], tend / pN[s]); + joinAxesTrans12(lin, + joinin, + N[s], + M[s], + pK[s], + pN[s], + P[s], + C[s + 1], + iNin[s + 1], + oNin[s + 1], + tstart % pN[s], + tstart / pN[s], + tend % pN[s], + tend / pN[s]); } } @@ -1368,12 +1426,15 @@ void fft5d_execute(fft5d_plan plan, int thread, fft5d_time times) { gmx_fft_many_1d_real(p1d[s][thread], (plan->flags & FFT5D_BACKWARD) ? GMX_FFT_COMPLEX_TO_REAL : GMX_FFT_REAL_TO_COMPLEX, - lin + tstart, lout + tstart); + lin + tstart, + lout + tstart); } else { - gmx_fft_many_1d(p1d[s][thread], (plan->flags & FFT5D_BACKWARD) ? GMX_FFT_BACKWARD : GMX_FFT_FORWARD, - lin + tstart, lout + tstart); + gmx_fft_many_1d(p1d[s][thread], + (plan->flags & FFT5D_BACKWARD) ? GMX_FFT_BACKWARD : GMX_FFT_FORWARD, + lin + tstart, + lout + tstart); } /* ------------ END FFT ---------*/ @@ -1594,7 +1655,13 @@ void fft5d_compare_data(const t_complex* lin, const t_complex* in, fft5d_plan pl if (std::fabs(a - b) > 2 * NG[0] * NG[1] * NG[2] * GMX_REAL_EPS) { printf("result incorrect on %d,%d at %d,%d,%d: FFT5D:%f reference:%f\n", - coor[0], coor[1], x, y, z, a, b); + coor[0], + coor[1], + x, + y, + z, + a, + b); } /* assert(fabs(a-b)<2*NG[0]*NG[1]*NG[2]*GMX_REAL_EPS);*/ } diff --git a/src/gromacs/fft/fft_fftw3.cpp b/src/gromacs/fft/fft_fftw3.cpp index 33c9b8c184..7e1f0e420c 100644 --- a/src/gromacs/fft/fft_fftw3.cpp +++ b/src/gromacs/fft/fft_fftw3.cpp @@ -176,22 +176,22 @@ int gmx_fft_init_many_1d(gmx_fft_t* pfft, int nx, int howmany, gmx_fft_flag flag fftw_complex *out, const int *onembed, int ostride, int odist, int sign, unsigned flags */ - fft->plan[0][0][0] = FFTWPREFIX(plan_many_dft)(1, &nx, howmany, up1, &nx, 1, nx, up2, &nx, 1, - nx, FFTW_BACKWARD, fftw_flags); - fft->plan[0][0][1] = FFTWPREFIX(plan_many_dft)(1, &nx, howmany, up1, &nx, 1, nx, up2, &nx, 1, - nx, FFTW_FORWARD, fftw_flags); - fft->plan[0][1][0] = FFTWPREFIX(plan_many_dft)(1, &nx, howmany, up1, &nx, 1, nx, up1, &nx, 1, - nx, FFTW_BACKWARD, fftw_flags); - fft->plan[0][1][1] = FFTWPREFIX(plan_many_dft)(1, &nx, howmany, up1, &nx, 1, nx, up1, &nx, 1, - nx, FFTW_FORWARD, fftw_flags); - fft->plan[1][0][0] = FFTWPREFIX(plan_many_dft)(1, &nx, howmany, p1, &nx, 1, nx, p2, &nx, 1, nx, - FFTW_BACKWARD, fftw_flags); - fft->plan[1][0][1] = FFTWPREFIX(plan_many_dft)(1, &nx, howmany, p1, &nx, 1, nx, p2, &nx, 1, nx, - FFTW_FORWARD, fftw_flags); - fft->plan[1][1][0] = FFTWPREFIX(plan_many_dft)(1, &nx, howmany, p1, &nx, 1, nx, p1, &nx, 1, nx, - FFTW_BACKWARD, fftw_flags); - fft->plan[1][1][1] = FFTWPREFIX(plan_many_dft)(1, &nx, howmany, p1, &nx, 1, nx, p1, &nx, 1, nx, - FFTW_FORWARD, fftw_flags); + fft->plan[0][0][0] = FFTWPREFIX(plan_many_dft)( + 1, &nx, howmany, up1, &nx, 1, nx, up2, &nx, 1, nx, FFTW_BACKWARD, fftw_flags); + fft->plan[0][0][1] = FFTWPREFIX(plan_many_dft)( + 1, &nx, howmany, up1, &nx, 1, nx, up2, &nx, 1, nx, FFTW_FORWARD, fftw_flags); + fft->plan[0][1][0] = FFTWPREFIX(plan_many_dft)( + 1, &nx, howmany, up1, &nx, 1, nx, up1, &nx, 1, nx, FFTW_BACKWARD, fftw_flags); + fft->plan[0][1][1] = FFTWPREFIX(plan_many_dft)( + 1, &nx, howmany, up1, &nx, 1, nx, up1, &nx, 1, nx, FFTW_FORWARD, fftw_flags); + fft->plan[1][0][0] = FFTWPREFIX(plan_many_dft)( + 1, &nx, howmany, p1, &nx, 1, nx, p2, &nx, 1, nx, FFTW_BACKWARD, fftw_flags); + fft->plan[1][0][1] = FFTWPREFIX(plan_many_dft)( + 1, &nx, howmany, p1, &nx, 1, nx, p2, &nx, 1, nx, FFTW_FORWARD, fftw_flags); + fft->plan[1][1][0] = FFTWPREFIX(plan_many_dft)( + 1, &nx, howmany, p1, &nx, 1, nx, p1, &nx, 1, nx, FFTW_BACKWARD, fftw_flags); + fft->plan[1][1][1] = FFTWPREFIX(plan_many_dft)( + 1, &nx, howmany, p1, &nx, 1, nx, p1, &nx, 1, nx, FFTW_FORWARD, fftw_flags); for (i = 0; i < 2; i++) { @@ -294,31 +294,103 @@ int gmx_fft_init_many_1d_real(gmx_fft_t* pfft, int nx, int howmany, gmx_fft_flag fftw_complex *out, const int *onembed, int ostride, int odist, unsigned flag */ - fft->plan[0][0][1] = FFTWPREFIX(plan_many_dft_r2c)( - 1, &nx, howmany, up1, nullptr, 1, (nx / 2 + 1) * 2, - reinterpret_cast(up2), nullptr, 1, (nx / 2 + 1), fftw_flags); - fft->plan[0][1][1] = FFTWPREFIX(plan_many_dft_r2c)( - 1, &nx, howmany, up1, nullptr, 1, (nx / 2 + 1) * 2, - reinterpret_cast(up1), nullptr, 1, (nx / 2 + 1), fftw_flags); - fft->plan[1][0][1] = FFTWPREFIX(plan_many_dft_r2c)( - 1, &nx, howmany, p1, nullptr, 1, (nx / 2 + 1) * 2, - reinterpret_cast(p2), nullptr, 1, (nx / 2 + 1), fftw_flags); - fft->plan[1][1][1] = FFTWPREFIX(plan_many_dft_r2c)( - 1, &nx, howmany, p1, nullptr, 1, (nx / 2 + 1) * 2, - reinterpret_cast(p1), nullptr, 1, (nx / 2 + 1), fftw_flags); - - fft->plan[0][0][0] = FFTWPREFIX(plan_many_dft_c2r)( - 1, &nx, howmany, reinterpret_cast(up1), nullptr, 1, (nx / 2 + 1), - up2, nullptr, 1, (nx / 2 + 1) * 2, fftw_flags); - fft->plan[0][1][0] = FFTWPREFIX(plan_many_dft_c2r)( - 1, &nx, howmany, reinterpret_cast(up1), nullptr, 1, (nx / 2 + 1), - up1, nullptr, 1, (nx / 2 + 1) * 2, fftw_flags); - fft->plan[1][0][0] = FFTWPREFIX(plan_many_dft_c2r)( - 1, &nx, howmany, reinterpret_cast(p1), nullptr, 1, (nx / 2 + 1), - p2, nullptr, 1, (nx / 2 + 1) * 2, fftw_flags); - fft->plan[1][1][0] = FFTWPREFIX(plan_many_dft_c2r)( - 1, &nx, howmany, reinterpret_cast(p1), nullptr, 1, (nx / 2 + 1), - p1, nullptr, 1, (nx / 2 + 1) * 2, fftw_flags); + fft->plan[0][0][1] = FFTWPREFIX(plan_many_dft_r2c)(1, + &nx, + howmany, + up1, + nullptr, + 1, + (nx / 2 + 1) * 2, + reinterpret_cast(up2), + nullptr, + 1, + (nx / 2 + 1), + fftw_flags); + fft->plan[0][1][1] = FFTWPREFIX(plan_many_dft_r2c)(1, + &nx, + howmany, + up1, + nullptr, + 1, + (nx / 2 + 1) * 2, + reinterpret_cast(up1), + nullptr, + 1, + (nx / 2 + 1), + fftw_flags); + fft->plan[1][0][1] = FFTWPREFIX(plan_many_dft_r2c)(1, + &nx, + howmany, + p1, + nullptr, + 1, + (nx / 2 + 1) * 2, + reinterpret_cast(p2), + nullptr, + 1, + (nx / 2 + 1), + fftw_flags); + fft->plan[1][1][1] = FFTWPREFIX(plan_many_dft_r2c)(1, + &nx, + howmany, + p1, + nullptr, + 1, + (nx / 2 + 1) * 2, + reinterpret_cast(p1), + nullptr, + 1, + (nx / 2 + 1), + fftw_flags); + + fft->plan[0][0][0] = FFTWPREFIX(plan_many_dft_c2r)(1, + &nx, + howmany, + reinterpret_cast(up1), + nullptr, + 1, + (nx / 2 + 1), + up2, + nullptr, + 1, + (nx / 2 + 1) * 2, + fftw_flags); + fft->plan[0][1][0] = FFTWPREFIX(plan_many_dft_c2r)(1, + &nx, + howmany, + reinterpret_cast(up1), + nullptr, + 1, + (nx / 2 + 1), + up1, + nullptr, + 1, + (nx / 2 + 1) * 2, + fftw_flags); + fft->plan[1][0][0] = FFTWPREFIX(plan_many_dft_c2r)(1, + &nx, + howmany, + reinterpret_cast(p1), + nullptr, + 1, + (nx / 2 + 1), + p2, + nullptr, + 1, + (nx / 2 + 1) * 2, + fftw_flags); + fft->plan[1][1][0] = FFTWPREFIX(plan_many_dft_c2r)(1, + &nx, + howmany, + reinterpret_cast(p1), + nullptr, + 1, + (nx / 2 + 1), + p1, + nullptr, + 1, + (nx / 2 + 1) * 2, + fftw_flags); for (i = 0; i < 2; i++) { @@ -478,7 +550,8 @@ int gmx_fft_1d(gmx_fft_t fft, enum gmx_fft_direction dir, void* in_data, void* o } FFTWPREFIX(execute_dft) - (fft->plan[aligned][inplace][isforward], static_cast(in_data), + (fft->plan[aligned][inplace][isforward], + static_cast(in_data), static_cast(out_data)); return 0; @@ -506,13 +579,15 @@ int gmx_fft_1d_real(gmx_fft_t fft, enum gmx_fft_direction dir, void* in_data, vo if (isforward) { FFTWPREFIX(execute_dft_r2c) - (fft->plan[aligned][inplace][isforward], static_cast(in_data), + (fft->plan[aligned][inplace][isforward], + static_cast(in_data), static_cast(out_data)); } else { FFTWPREFIX(execute_dft_c2r) - (fft->plan[aligned][inplace][isforward], static_cast(in_data), + (fft->plan[aligned][inplace][isforward], + static_cast(in_data), static_cast(out_data)); } @@ -541,13 +616,15 @@ int gmx_fft_2d_real(gmx_fft_t fft, enum gmx_fft_direction dir, void* in_data, vo if (isforward) { FFTWPREFIX(execute_dft_r2c) - (fft->plan[aligned][inplace][isforward], static_cast(in_data), + (fft->plan[aligned][inplace][isforward], + static_cast(in_data), static_cast(out_data)); } else { FFTWPREFIX(execute_dft_c2r) - (fft->plan[aligned][inplace][isforward], static_cast(in_data), + (fft->plan[aligned][inplace][isforward], + static_cast(in_data), static_cast(out_data)); } diff --git a/src/gromacs/fft/parallel_3dfft.cpp b/src/gromacs/fft/parallel_3dfft.cpp index 8b842fe5ac..24a679fc30 100644 --- a/src/gromacs/fft/parallel_3dfft.cpp +++ b/src/gromacs/fft/parallel_3dfft.cpp @@ -2,7 +2,7 @@ * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 1991-2005 David van der Spoel, Erik Lindahl, University of Groningen. - * Copyright (c) 2013,2014,2017,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2017,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -87,12 +87,19 @@ int gmx_parallel_3dfft_init(gmx_parallel_3dfft_t* pfft_setup, Kb = M; /* currently always true because ORDER_YZ always set */ } - (*pfft_setup)->p1 = fft5d_plan_3d(rN, M, K, rcomm, flags, reinterpret_cast(real_data), - complex_data, &buf1, &buf2, nthreads, realGridAllocation); + (*pfft_setup)->p1 = fft5d_plan_3d( + rN, M, K, rcomm, flags, reinterpret_cast(real_data), complex_data, &buf1, &buf2, nthreads, realGridAllocation); - (*pfft_setup)->p2 = fft5d_plan_3d( - Nb, Mb, Kb, rcomm, (flags | FFT5D_BACKWARD | FFT5D_NOMALLOC) ^ FFT5D_ORDER_YZ, - complex_data, reinterpret_cast(real_data), &buf1, &buf2, nthreads); + (*pfft_setup)->p2 = fft5d_plan_3d(Nb, + Mb, + Kb, + rcomm, + (flags | FFT5D_BACKWARD | FFT5D_NOMALLOC) ^ FFT5D_ORDER_YZ, + complex_data, + reinterpret_cast(real_data), + &buf1, + &buf2, + nthreads); return static_cast((*pfft_setup)->p1 != nullptr && (*pfft_setup)->p2 != nullptr); } @@ -168,8 +175,7 @@ int gmx_parallel_3dfft_execute(gmx_parallel_3dfft_t pfft_setup, if (((pfft_setup->p1->flags & FFT5D_REALCOMPLEX) == 0) ^ (dir == GMX_FFT_FORWARD || dir == GMX_FFT_BACKWARD)) { - gmx_fatal(FARGS, - "Invalid transform. Plan and execution don't match regarding reel/complex"); + gmx_fatal(FARGS, "Invalid transform. Plan and execution don't match regarding reel/complex"); } if (dir == GMX_FFT_FORWARD || dir == GMX_FFT_REAL_TO_COMPLEX) { diff --git a/src/gromacs/fft/tests/fft.cpp b/src/gromacs/fft/tests/fft.cpp index f422241309..10bb57b507 100644 --- a/src/gromacs/fft/tests/fft.cpp +++ b/src/gromacs/fft/tests/fft.cpp @@ -311,8 +311,8 @@ TEST_F(FFFTest3D, Real5_6_9) gmx_parallel_3dfft_execute(fft_, GMX_FFT_COMPLEX_TO_REAL, 0, nullptr); for (int i = 0; i < ndata[0] * ndata[1]; i++) // check sequence but skip unused data { - checker_.checkSequenceArray(ndata[2], rdata + i * rsize[2], - gmx::formatString("backward %d", i).c_str()); + checker_.checkSequenceArray( + ndata[2], rdata + i * rsize[2], gmx::formatString("backward %d", i).c_str()); } } diff --git a/src/gromacs/fileio/checkpoint.cpp b/src/gromacs/fileio/checkpoint.cpp index abd957f09a..8976350b59 100644 --- a/src/gromacs/fileio/checkpoint.cpp +++ b/src/gromacs/fileio/checkpoint.cpp @@ -284,7 +284,8 @@ static const char* eenh_names[eenhNR] = { "energy_n", "energy_delta_h_start_time", "energy_delta_h_start_lambda" }; -static const char* ePullhNames[epullhNR] = { "pullhistory_numcoordinates", "pullhistory_numgroups", +static const char* ePullhNames[epullhNR] = { "pullhistory_numcoordinates", + "pullhistory_numgroups", "pullhistory_numvaluesinxsum", "pullhistory_numvaluesinfsum" }; @@ -607,30 +608,26 @@ static bool_t listXdrVector(XDR* xd, StatePart part, int ecpt, int nf, int xdrTy #if !GMX_DOUBLE if (cptElementType == CptElementType::real3) { - pr_rvecs(list, 0, entryName(part, ecpt), - reinterpret_cast(data.data()), nf / 3); + pr_rvecs(list, 0, entryName(part, ecpt), reinterpret_cast(data.data()), nf / 3); } else #endif { /* Note: With double precision code dumping a single precision rvec will produce float iso rvec print, but that's a minor annoyance */ - pr_fvec(list, 0, entryName(part, ecpt), - reinterpret_cast(data.data()), nf, TRUE); + pr_fvec(list, 0, entryName(part, ecpt), reinterpret_cast(data.data()), nf, TRUE); } break; case xdr_datatype_double: #if GMX_DOUBLE if (cptElementType == CptElementType::real3) { - pr_rvecs(list, 0, entryName(part, ecpt), - reinterpret_cast(data.data()), nf / 3); + pr_rvecs(list, 0, entryName(part, ecpt), reinterpret_cast(data.data()), nf / 3); } else #endif { /* Note: With single precision code dumping a double precision rvec will produce float iso rvec print, but that's a minor annoyance */ - pr_dvec(list, 0, entryName(part, ecpt), - reinterpret_cast(data.data()), nf, TRUE); + pr_dvec(list, 0, entryName(part, ecpt), reinterpret_cast(data.data()), nf, TRUE); } break; default: GMX_RELEASE_ASSERT(false, "Data type not implemented for listing"); @@ -748,7 +745,9 @@ static int doVectorLow(XDR* xd, { gmx_fatal(FARGS, "Count mismatch for state entry %s, code count is %d, file count is %d\n", - entryName(part, ecpt), nval, numElemInTheFile); + entryName(part, ecpt), + nval, + numElemInTheFile); } } else if (nptr != nullptr) @@ -760,15 +759,18 @@ static int doVectorLow(XDR* xd, if (!typesMatch) { char buf[STRLEN]; - sprintf(buf, "mismatch for state entry %s, code precision is %s, file precision is %s", - entryName(part, ecpt), xdr_datatype_names[xdrTypeInTheCode], + sprintf(buf, + "mismatch for state entry %s, code precision is %s, file precision is %s", + entryName(part, ecpt), + xdr_datatype_names[xdrTypeInTheCode], xdr_datatype_names[xdrTypeInTheFile]); /* Matching int and real should never occur, but check anyhow */ if (xdrTypeInTheFile == xdr_datatype_int || xdrTypeInTheCode == xdr_datatype_int) { gmx_fatal(FARGS, - "Type %s: incompatible checkpoint formats or corrupted checkpoint file.", buf); + "Type %s: incompatible checkpoint formats or corrupted checkpoint file.", + buf); } } @@ -804,8 +806,8 @@ static int doVectorLow(XDR* xd, { snew(vChar, numElemInTheFile * sizeOfXdrType(xdrTypeInTheFile)); } - res = xdr_vector(xd, vChar, numElemInTheFile, sizeOfXdrType(xdrTypeInTheFile), - xdrProc(xdrTypeInTheFile)); + res = xdr_vector( + xd, vChar, numElemInTheFile, sizeOfXdrType(xdrTypeInTheFile), xdrProc(xdrTypeInTheFile)); if (res == 0) { return -1; @@ -835,16 +837,16 @@ template static int doVector(XDR* xd, StatePart part, int ecpt, int sflags, std::vector* vector, FILE* list, int numElements = -1) { - return doVectorLow(xd, part, ecpt, sflags, numElements, nullptr, nullptr, vector, list, - CptElementType::real); + return doVectorLow( + xd, part, ecpt, sflags, numElements, nullptr, nullptr, vector, list, CptElementType::real); } //! \brief Read/Write an ArrayRef. static int doRealArrayRef(XDR* xd, StatePart part, int ecpt, int sflags, gmx::ArrayRef vector, FILE* list) { real* v_real = vector.data(); - return doVectorLow>(xd, part, ecpt, sflags, vector.size(), nullptr, - &v_real, nullptr, list, CptElementType::real); + return doVectorLow>( + xd, part, ecpt, sflags, vector.size(), nullptr, &v_real, nullptr, list, CptElementType::real); } //! Convert from view of RVec to view of real. @@ -875,8 +877,8 @@ doRvecVector(XDR* xd, StatePart part, int ecpt, int sflags, PaddedVectorOfRVecTy // allocator from RVec to real. using realAllocator = typename std::allocator_traits::template rebind_alloc; - return doVectorLow(xd, part, ecpt, sflags, numReals, nullptr, nullptr, - nullptr, list, CptElementType::real); + return doVectorLow( + xd, part, ecpt, sflags, numReals, nullptr, nullptr, nullptr, list, CptElementType::real); } } @@ -886,8 +888,8 @@ doRvecVector(XDR* xd, StatePart part, int ecpt, int sflags, PaddedVectorOfRVecTy */ static int do_cpte_reals(XDR* xd, StatePart part, int ecpt, int sflags, int n, real** v, FILE* list) { - return doVectorLow>(xd, part, ecpt, sflags, n, nullptr, v, nullptr, - list, CptElementType::real); + return doVectorLow>( + xd, part, ecpt, sflags, n, nullptr, v, nullptr, list, CptElementType::real); } /* This function does the same as do_cpte_reals, @@ -896,20 +898,20 @@ static int do_cpte_reals(XDR* xd, StatePart part, int ecpt, int sflags, int n, r */ static int do_cpte_n_reals(XDR* xd, StatePart part, int ecpt, int sflags, int* n, real** v, FILE* list) { - return doVectorLow>(xd, part, ecpt, sflags, -1, n, v, nullptr, list, - CptElementType::real); + return doVectorLow>( + xd, part, ecpt, sflags, -1, n, v, nullptr, list, CptElementType::real); } static int do_cpte_real(XDR* xd, StatePart part, int ecpt, int sflags, real* r, FILE* list) { - return doVectorLow>(xd, part, ecpt, sflags, 1, nullptr, &r, nullptr, - list, CptElementType::real); + return doVectorLow>( + xd, part, ecpt, sflags, 1, nullptr, &r, nullptr, list, CptElementType::real); } static int do_cpte_ints(XDR* xd, StatePart part, int ecpt, int sflags, int n, int** v, FILE* list) { - return doVectorLow>(xd, part, ecpt, sflags, n, nullptr, v, nullptr, - list, CptElementType::integer); + return doVectorLow>( + xd, part, ecpt, sflags, n, nullptr, v, nullptr, list, CptElementType::integer); } static int do_cpte_int(XDR* xd, StatePart part, int ecpt, int sflags, int* i, FILE* list) @@ -927,8 +929,8 @@ static int do_cpte_bool(XDR* xd, StatePart part, int ecpt, int sflags, bool* b, static int do_cpte_doubles(XDR* xd, StatePart part, int ecpt, int sflags, int n, double** v, FILE* list) { - return doVectorLow>(xd, part, ecpt, sflags, n, nullptr, v, - nullptr, list, CptElementType::real); + return doVectorLow>( + xd, part, ecpt, sflags, n, nullptr, v, nullptr, list, CptElementType::real); } static int do_cpte_double(XDR* xd, StatePart part, int ecpt, int sflags, double* r, FILE* list) @@ -942,8 +944,8 @@ static int do_cpte_matrix(XDR* xd, StatePart part, int ecpt, int sflags, matrix int ret; vr = &(v[0][0]); - ret = doVectorLow>(xd, part, ecpt, sflags, DIM * DIM, nullptr, &vr, - nullptr, nullptr, CptElementType::matrix3x3); + ret = doVectorLow>( + xd, part, ecpt, sflags, DIM * DIM, nullptr, &vr, nullptr, nullptr, CptElementType::matrix3x3); if (list && ret == 0) { @@ -967,8 +969,8 @@ static int do_cpte_nmatrix(XDR* xd, StatePart part, int ecpt, int sflags, int n, } for (i = 0; i < n; i++) { - reti = doVectorLow>(xd, part, ecpt, sflags, n, nullptr, &(v[i]), - nullptr, nullptr, CptElementType::matrix3x3); + reti = doVectorLow>( + xd, part, ecpt, sflags, n, nullptr, &(v[i]), nullptr, nullptr, CptElementType::matrix3x3); if (list && reti == 0) { sprintf(name, "%s[%d]", entryName(part, ecpt), i); @@ -998,8 +1000,11 @@ static int do_cpte_matrices(XDR* xd, StatePart part, int ecpt, int sflags, int n } if (list == nullptr && nf != n) { - gmx_fatal(FARGS, "Count mismatch for state entry %s, code count is %d, file count is %d\n", - entryName(part, ecpt), n, nf); + gmx_fatal(FARGS, + "Count mismatch for state entry %s, code count is %d, file count is %d\n", + entryName(part, ecpt), + n, + nf); } if (list || !(sflags & (1 << ecpt))) { @@ -1025,8 +1030,8 @@ static int do_cpte_matrices(XDR* xd, StatePart part, int ecpt, int sflags, int n } } } - ret = doVectorLow>(xd, part, ecpt, sflags, nf * DIM * DIM, nullptr, - &vr, nullptr, nullptr, CptElementType::matrix3x3); + ret = doVectorLow>( + xd, part, ecpt, sflags, nf * DIM * DIM, nullptr, &vr, nullptr, nullptr, CptElementType::matrix3x3); for (i = 0; i < nf; i++) { for (j = 0; j < DIM; j++) @@ -1078,7 +1083,8 @@ static void do_cpt_header(XDR* xd, gmx_bool bRead, FILE* list, CheckpointHeaderC gmx_fatal(FARGS, "Start of file magic number mismatch, checkpoint file has %d, should be %d\n" "The checkpoint file is corrupted or not a checkpoint file", - magic, CPT_MAGIC1); + magic, + CPT_MAGIC1); } char fhost[255]; if (!bRead) @@ -1103,7 +1109,8 @@ static void do_cpt_header(XDR* xd, gmx_bool bRead, FILE* list, CheckpointHeaderC { gmx_fatal(FARGS, "Attempting to read a checkpoint file of version %d with code of version %d\n", - contents->file_version, cpt_version); + contents->file_version, + cpt_version); } if (contents->file_version >= 13) { @@ -1229,8 +1236,8 @@ static void do_cpt_header(XDR* xd, gmx_bool bRead, FILE* list, CheckpointHeaderC if (contents->file_version >= cptv_ModularSimulator) { - do_cpt_bool_err(xd, "Is modular simulator checkpoint", - &contents->isModularSimulatorCheckpoint, list); + do_cpt_bool_err( + xd, "Is modular simulator checkpoint", &contents->isModularSimulatorCheckpoint, list); } else { @@ -1277,7 +1284,10 @@ static int do_cpt_state(XDR* xd, int fflags, t_state* state, FILE* list) { case estLAMBDA: ret = doRealArrayRef( - xd, part, i, sflags, + xd, + part, + i, + sflags, gmx::arrayRefFromArray(state->lambda.data(), state->lambda.size()), list); break; @@ -1338,15 +1348,15 @@ static int do_cpt_state(XDR* xd, int fflags, t_state* state, FILE* list) ret = do_cpte_real(xd, part, i, sflags, &state->hist.disre_initf, list); break; case estDISRE_RM3TAV: - ret = do_cpte_n_reals(xd, part, i, sflags, &state->hist.ndisrepairs, - &state->hist.disre_rm3tav, list); + ret = do_cpte_n_reals( + xd, part, i, sflags, &state->hist.ndisrepairs, &state->hist.disre_rm3tav, list); break; case estORIRE_INITF: ret = do_cpte_real(xd, part, i, sflags, &state->hist.orire_initf, list); break; case estORIRE_DTAV: - ret = do_cpte_n_reals(xd, part, i, sflags, &state->hist.norire_Dtav, - &state->hist.orire_Dtav, list); + ret = do_cpte_n_reals( + xd, part, i, sflags, &state->hist.norire_Dtav, &state->hist.orire_Dtav, list); break; case estPULLCOMPREVSTEP: ret = doVector(xd, part, i, sflags, &state->pull_com_prev_step, list); @@ -1547,10 +1557,10 @@ static int do_cpt_swapstate(XDR* xd, gmx_bool bRead, int eSwapCoords, swaphistor } else { - do_cpt_n_rvecs_err(xd, "Ch0 whole x", swapstate->nat[eChan0], - *swapstate->xc_old_whole_p[eChan0], list); - do_cpt_n_rvecs_err(xd, "Ch1 whole x", swapstate->nat[eChan1], - *swapstate->xc_old_whole_p[eChan1], list); + do_cpt_n_rvecs_err( + xd, "Ch0 whole x", swapstate->nat[eChan0], *swapstate->xc_old_whole_p[eChan0], list); + do_cpt_n_rvecs_err( + xd, "Ch1 whole x", swapstate->nat[eChan1], *swapstate->xc_old_whole_p[eChan1], list); } return 0; @@ -1566,8 +1576,7 @@ static int do_cpt_enerhist(XDR* xd, gmx_bool bRead, int fflags, energyhistory_t* return ret; } - GMX_RELEASE_ASSERT(enerhist != nullptr, - "With energy history, we need a valid enerhist pointer"); + GMX_RELEASE_ASSERT(enerhist != nullptr, "With energy history, we need a valid enerhist pointer"); /* This is stored/read for backward compatibility */ int energyHistoryNumEnergies = 0; @@ -1977,8 +1986,8 @@ static int do_cpt_correlation_grid(XDR* xd, if (bRead) { - initCorrelationGridHistory(corrGrid, corrGrid->numCorrelationTensors, corrGrid->tensorSize, - corrGrid->blockDataListSize); + initCorrelationGridHistory( + corrGrid, corrGrid->numCorrelationTensors, corrGrid->tensorSize, corrGrid->blockDataListSize); } for (gmx::CorrelationBlockDataHistory& blockData : corrGrid->blockDataBuffer) @@ -2064,8 +2073,8 @@ static int do_cpt_awh_bias(XDR* xd, gmx_bool bRead, int fflags, gmx::AwhBiasHist do_cpt_step_err(xd, eawhh_names[i], &(state->numUpdates), list); break; case eawhhFORCECORRELATIONGRID: - ret = do_cpt_correlation_grid(xd, bRead, fflags, - &biasHistory->forceCorrelationGrid, list, i); + ret = do_cpt_correlation_grid( + xd, bRead, fflags, &biasHistory->forceCorrelationGrid, list, i); break; default: gmx_fatal(FARGS, "Unknown awh history entry %d\n", i); } @@ -2211,8 +2220,7 @@ static int do_cpt_files(XDR* xd, gmx_bool bRead, std::vectorflags, state, nullptr) < 0) || (do_cpt_ekinstate(gmx_fio_getxdr(fp), headerContents.flags_eks, &state->ekinstate, nullptr) < 0) || (do_cpt_enerhist(gmx_fio_getxdr(fp), FALSE, headerContents.flags_enh, enerhist, nullptr) < 0) - || (doCptPullHist(gmx_fio_getxdr(fp), FALSE, headerContents.flagsPullHistory, pullHist, - StatePart::pullHistory, nullptr) + || (doCptPullHist(gmx_fio_getxdr(fp), FALSE, headerContents.flagsPullHistory, pullHist, StatePart::pullHistory, nullptr) < 0) - || (do_cpt_df_hist(gmx_fio_getxdr(fp), headerContents.flags_dfh, headerContents.nlambda, - &state->dfhist, nullptr) + || (do_cpt_df_hist(gmx_fio_getxdr(fp), headerContents.flags_dfh, headerContents.nlambda, &state->dfhist, nullptr) < 0) - || (do_cpt_EDstate(gmx_fio_getxdr(fp), FALSE, headerContents.nED, - observablesHistory->edsamHistory.get(), nullptr) + || (do_cpt_EDstate( + gmx_fio_getxdr(fp), FALSE, headerContents.nED, observablesHistory->edsamHistory.get(), nullptr) < 0) || (do_cpt_awh(gmx_fio_getxdr(fp), FALSE, headerContents.flags_awhh, state->awhHistory.get(), nullptr) < 0) - || (do_cpt_swapstate(gmx_fio_getxdr(fp), FALSE, headerContents.eSwapCoords, - observablesHistory->swapHistory.get(), nullptr) + || (do_cpt_swapstate(gmx_fio_getxdr(fp), + FALSE, + headerContents.eSwapCoords, + observablesHistory->swapHistory.get(), + nullptr) < 0) || (do_cpt_files(gmx_fio_getxdr(fp), FALSE, outputfiles, nullptr, headerContents.file_version) < 0)) { @@ -2427,8 +2436,8 @@ static void check_match(FILE* fplog, if (reproducibilityRequested) { - check_string(fplog, "Program name", gmx::getProgramContext().fullBinaryPath(), - headerContents.fprog, &mm); + check_string( + fplog, "Program name", gmx::getProgramContext().fullBinaryPath(), headerContents.fprog, &mm); check_int(fplog, "#ranks", cr->nnodes, headerContents.nnodes, &mm); } @@ -2544,21 +2553,24 @@ static void read_checkpoint(const char* fn, gmx_fatal(FARGS, "Checkpoint file is for a system of %d atoms, while the current system consists " "of %d atoms", - headerContents->natoms, state->natoms); + headerContents->natoms, + state->natoms); } if (headerContents->ngtc != state->ngtc) { gmx_fatal(FARGS, "Checkpoint file is for a system of %d T-coupling groups, while the current " "system consists of %d T-coupling groups", - headerContents->ngtc, state->ngtc); + headerContents->ngtc, + state->ngtc); } if (headerContents->nnhpres != state->nnhpres) { gmx_fatal(FARGS, "Checkpoint file is for a system of %d NH-pressure-coupling variables, while the " "current system consists of %d NH-pressure-coupling variables", - headerContents->nnhpres, state->nnhpres); + headerContents->nnhpres, + state->nnhpres); } int nlambdaHistory = (state->dfhist ? state->dfhist->nlambda : 0); @@ -2567,10 +2579,13 @@ static void read_checkpoint(const char* fn, gmx_fatal(FARGS, "Checkpoint file is for a system with %d lambda states, while the current system " "consists of %d lambda states", - headerContents->nlambda, nlambdaHistory); + headerContents->nlambda, + nlambdaHistory); } - init_gtc_state(state, state->ngtc, state->nnhpres, + init_gtc_state(state, + state->ngtc, + state->nnhpres, headerContents->nhchainlength); /* need to keep this here to keep the tpr format working */ /* write over whatever was read; we use the number of Nose-Hoover chains from the checkpoint */ @@ -2627,8 +2642,8 @@ static void read_checkpoint(const char* fn, { observablesHistory->energyHistory = std::make_unique(); } - ret = do_cpt_enerhist(gmx_fio_getxdr(fp), TRUE, headerContents->flags_enh, - observablesHistory->energyHistory.get(), nullptr); + ret = do_cpt_enerhist( + gmx_fio_getxdr(fp), TRUE, headerContents->flags_enh, observablesHistory->energyHistory.get(), nullptr); if (ret) { cp_error(); @@ -2640,8 +2655,12 @@ static void read_checkpoint(const char* fn, { observablesHistory->pullHistory = std::make_unique(); } - ret = doCptPullHist(gmx_fio_getxdr(fp), TRUE, headerContents->flagsPullHistory, - observablesHistory->pullHistory.get(), StatePart::pullHistory, nullptr); + ret = doCptPullHist(gmx_fio_getxdr(fp), + TRUE, + headerContents->flagsPullHistory, + observablesHistory->pullHistory.get(), + StatePart::pullHistory, + nullptr); if (ret) { cp_error(); @@ -2654,8 +2673,8 @@ static void read_checkpoint(const char* fn, "Continuing from checkpoint files written before GROMACS 4.5 is not supported"); } - ret = do_cpt_df_hist(gmx_fio_getxdr(fp), headerContents->flags_dfh, headerContents->nlambda, - &state->dfhist, nullptr); + ret = do_cpt_df_hist( + gmx_fio_getxdr(fp), headerContents->flags_dfh, headerContents->nlambda, &state->dfhist, nullptr); if (ret) { cp_error(); @@ -2665,8 +2684,8 @@ static void read_checkpoint(const char* fn, { observablesHistory->edsamHistory = std::make_unique(edsamhistory_t{}); } - ret = do_cpt_EDstate(gmx_fio_getxdr(fp), TRUE, headerContents->nED, - observablesHistory->edsamHistory.get(), nullptr); + ret = do_cpt_EDstate( + gmx_fio_getxdr(fp), TRUE, headerContents->nED, observablesHistory->edsamHistory.get(), nullptr); if (ret) { cp_error(); @@ -2686,8 +2705,8 @@ static void read_checkpoint(const char* fn, { observablesHistory->swapHistory = std::make_unique(swaphistory_t{}); } - ret = do_cpt_swapstate(gmx_fio_getxdr(fp), TRUE, headerContents->eSwapCoords, - observablesHistory->swapHistory.get(), nullptr); + ret = do_cpt_swapstate( + gmx_fio_getxdr(fp), TRUE, headerContents->eSwapCoords, observablesHistory->swapHistory.get(), nullptr); if (ret) { cp_error(); @@ -2733,9 +2752,19 @@ void load_checkpoint(const char* fn, if (SIMMASTER(cr)) { /* Read the state from the checkpoint file */ - read_checkpoint(fn, logfio, cr, dd_nc, ir->eI, &(ir->fepvals->init_fep_state), - &headerContents, state, observablesHistory, reproducibilityRequested, - mdModulesNotifier, modularSimulatorCheckpointData, useModularSimulator); + read_checkpoint(fn, + logfio, + cr, + dd_nc, + ir->eI, + &(ir->fepvals->init_fep_state), + &headerContents, + state, + observablesHistory, + reproducibilityRequested, + mdModulesNotifier, + modularSimulatorCheckpointData, + useModularSimulator); } if (PAR(cr)) { @@ -2824,15 +2853,15 @@ static CheckpointHeaderContents read_checkpoint_data(t_fileio* cp_error(); } PullHistory pullHist = {}; - ret = doCptPullHist(gmx_fio_getxdr(fp), TRUE, headerContents.flagsPullHistory, &pullHist, - StatePart::pullHistory, nullptr); + ret = doCptPullHist( + gmx_fio_getxdr(fp), TRUE, headerContents.flagsPullHistory, &pullHist, StatePart::pullHistory, nullptr); if (ret) { cp_error(); } - ret = do_cpt_df_hist(gmx_fio_getxdr(fp), headerContents.flags_dfh, headerContents.nlambda, - &state->dfhist, nullptr); + ret = do_cpt_df_hist( + gmx_fio_getxdr(fp), headerContents.flags_dfh, headerContents.nlambda, &state->dfhist, nullptr); if (ret) { cp_error(); @@ -2947,14 +2976,14 @@ void list_checkpoint(const char* fn, FILE* out) if (ret == 0) { PullHistory pullHist = {}; - ret = doCptPullHist(gmx_fio_getxdr(fp), TRUE, headerContents.flagsPullHistory, &pullHist, - StatePart::pullHistory, out); + ret = doCptPullHist( + gmx_fio_getxdr(fp), TRUE, headerContents.flagsPullHistory, &pullHist, StatePart::pullHistory, out); } if (ret == 0) { - ret = do_cpt_df_hist(gmx_fio_getxdr(fp), headerContents.flags_dfh, headerContents.nlambda, - &state.dfhist, out); + ret = do_cpt_df_hist( + gmx_fio_getxdr(fp), headerContents.flags_dfh, headerContents.nlambda, &state.dfhist, out); } if (ret == 0) diff --git a/src/gromacs/fileio/confio.cpp b/src/gromacs/fileio/confio.cpp index 3b52aadf1c..fe71e265d9 100644 --- a/src/gromacs/fileio/confio.cpp +++ b/src/gromacs/fileio/confio.cpp @@ -107,8 +107,8 @@ void write_sto_conf_indexed(const char* outfile, case efENT: case efPQR: out = gmx_fio_fopen(outfile, "w"); - write_pdbfile_indexed(out, title, atoms, x, pbcType, box, ' ', -1, nindex, index, - nullptr, ftp == efPQR); + write_pdbfile_indexed( + out, title, atoms, x, pbcType, box, ' ', -1, nindex, index, nullptr, ftp == efPQR); gmx_fio_fclose(out); break; case efESP: @@ -473,8 +473,8 @@ void readConfAndTopology(const char* infile, snew(*v, header.natoms); } int natoms; - PbcType pbcType_tmp = read_tpx(infile, nullptr, box, &natoms, (x == nullptr) ? nullptr : *x, - (v == nullptr) ? nullptr : *v, mtop); + PbcType pbcType_tmp = read_tpx( + infile, nullptr, box, &natoms, (x == nullptr) ? nullptr : *x, (v == nullptr) ? nullptr : *v, mtop); if (pbcType != nullptr) { *pbcType = pbcType_tmp; diff --git a/src/gromacs/fileio/enxio.cpp b/src/gromacs/fileio/enxio.cpp index f36118b551..56d2279c7b 100644 --- a/src/gromacs/fileio/enxio.cpp +++ b/src/gromacs/fileio/enxio.cpp @@ -336,7 +336,9 @@ static void enx_warning(const char* msg) } else { - gmx_fatal(FARGS, "%s\n%s", msg, + gmx_fatal(FARGS, + "%s\n%s", + msg, "If you want to use the correct frames before the corrupted frame and avoid this " "fatal error set the env.var. GMX_ENX_NO_FATAL"); } @@ -424,8 +426,11 @@ void do_enxnms(ener_file_t ef, int* nre, gmx_enxnm_t** nms) xdr_int(xdr, &file_version); if (file_version > enx_version) { - gmx_fatal(FARGS, "reading tpx file (%s) version %d with version %d program", - gmx_fio_getname(ef->fio), file_version, enx_version); + gmx_fatal(FARGS, + "reading tpx file (%s) version %d with version %d program", + gmx_fio_getname(ef->fio), + file_version, + enx_version); } xdr_int(xdr, nre); } @@ -507,8 +512,11 @@ static gmx_bool do_eheader(ener_file_t ef, } if (*bOK && *file_version > enx_version) { - gmx_fatal(FARGS, "reading tpx file (%s) version %d with version %d program", - gmx_fio_getname(ef->fio), *file_version, enx_version); + gmx_fatal(FARGS, + "reading tpx file (%s) version %d with version %d program", + gmx_fio_getname(ef->fio), + *file_version, + enx_version); } if (!gmx_fio_do_double(ef->fio, fr->t)) { @@ -970,14 +978,12 @@ gmx_bool do_enx(ener_file_t ef, t_enxframe* fr) { if (bRead) { - fprintf(stderr, "\rLast energy frame read %d time %8.3f ", ef->framenr - 1, - ef->frametime); + fprintf(stderr, "\rLast energy frame read %d time %8.3f ", ef->framenr - 1, ef->frametime); fflush(stderr); if (!bOK) { - fprintf(stderr, "\nWARNING: Incomplete energy frame: nr %d time %8.3f\n", - ef->framenr, fr->t); + fprintf(stderr, "\nWARNING: Incomplete energy frame: nr %d time %8.3f\n", ef->framenr, fr->t); } } else @@ -1004,10 +1010,15 @@ gmx_bool do_enx(ener_file_t ef, t_enxframe* fr) } if (!((fr->step >= 0) && bSane) && bRead) { - fprintf(stderr, "\nWARNING: there may be something wrong with energy file %s\n", + fprintf(stderr, + "\nWARNING: there may be something wrong with energy file %s\n", gmx_fio_getname(ef->fio)); - fprintf(stderr, "Found: step=%" PRId64 ", nre=%d, nblock=%d, time=%g.\n", fr->step, fr->nre, - fr->nblock, fr->t); + fprintf(stderr, + "Found: step=%" PRId64 ", nre=%d, nblock=%d, time=%g.\n", + fr->step, + fr->nre, + fr->nblock, + fr->t); } if (bRead && fr->nre > fr->e_alloc) { @@ -1376,8 +1387,13 @@ static void cmp_energies(FILE* fp, } if (!equal_real(e1[ind1[i]].e, e2[ind2[i]].e, ftol_i, abstol_i)) { - fprintf(fp, "%-15s step %3d: %12g, step %3d: %12g\n", enm1[ind1[i]].name, step1, - e1[ind1[i]].e, step2, e2[ind2[i]].e); + fprintf(fp, + "%-15s step %3d: %12g, step %3d: %12g\n", + enm1[ind1[i]].name, + step1, + e1[ind1[i]].e, + step2, + e2[ind2[i]].e); } } @@ -1581,8 +1597,8 @@ void comp_enx(const char* fn1, const char* fn2, real ftol, real abstol, const ch /* cmp_int(stdout,"nre",-1,fr1->nre,fr2->nre); */ if ((fr1->nre >= nre) && (fr2->nre >= nre)) { - cmp_energies(stdout, fr1->step, fr1->step, fr1->ener, fr2->ener, enm1, ftol, abstol, - nre, ind1, ind2, maxener); + cmp_energies( + stdout, fr1->step, fr1->step, fr1->ener, fr2->ener, enm1, ftol, abstol, nre, ind1, ind2, maxener); } /*cmp_disres(fr1,fr2,ftol,abstol);*/ cmp_eblocks(fr1, fr2, ftol, abstol); diff --git a/src/gromacs/fileio/espio.cpp b/src/gromacs/fileio/espio.cpp index a380ffafc5..800628e32a 100644 --- a/src/gromacs/fileio/espio.cpp +++ b/src/gromacs/fileio/espio.cpp @@ -327,8 +327,7 @@ void gmx_espresso_read_conf(const char* infile, t_symtab* symtab, char** name, t } else { - sprintf(buf, "T%c%c", 'A' + atoms->atom[i].type / 26, - 'A' + atoms->atom[i].type % 26); + sprintf(buf, "T%c%c", 'A' + atoms->atom[i].type / 26, 'A' + atoms->atom[i].type % 26); } t_atoms_set_resinfo(atoms, i, symtab, buf, i, ' ', 0, ' '); } @@ -347,7 +346,8 @@ void gmx_espresso_read_conf(const char* infile, t_symtab* symtab, char** name, t gmx_fatal(FARGS, "Internal inconsistency in Espresso routines, read %d atoms, expected %d " "atoms", - i, atoms->nr); + i, + atoms->nr); } } else if (level == 1 && std::strcmp(word, "variable") == 0 && !bFoundVariable) @@ -469,7 +469,13 @@ void write_espresso_conf_indexed(FILE* out, { j = i; } - fprintf(out, "\t{%d %f %f %f %hu %g", j, x[j][XX], x[j][YY], x[j][ZZ], atoms->atom[j].type, + fprintf(out, + "\t{%d %f %f %f %hu %g", + j, + x[j][XX], + x[j][YY], + x[j][ZZ], + atoms->atom[j].type, atoms->atom[j].q); if (v) { diff --git a/src/gromacs/fileio/filetypes.cpp b/src/gromacs/fileio/filetypes.cpp index ac6c5820be..b3e9be6d20 100644 --- a/src/gromacs/fileio/filetypes.cpp +++ b/src/gromacs/fileio/filetypes.cpp @@ -95,8 +95,13 @@ static const t_deffile deffile[efNR] = { { eftGEN, ".???", "trajout", "-f", "Trajectory", NTROS, tros }, { eftGEN, ".???", "traj", nullptr, "Full precision trajectory", NTRNS, trns }, { eftXDR, ".trr", "traj", nullptr, "Trajectory in portable xdr format" }, - { eftGEN, ".???", "traj_comp", nullptr, - "Compressed trajectory (tng format or portable xdr format)", NTRCOMPRESSED, trcompressed }, + { eftGEN, + ".???", + "traj_comp", + nullptr, + "Compressed trajectory (tng format or portable xdr format)", + NTRCOMPRESSED, + trcompressed }, { eftXDR, ".xtc", "traj", nullptr, "Compressed trajectory (portable xdr format): xtc" }, { eftTNG, ".tng", "traj", nullptr, "Trajectory file (tng format)" }, { eftXDR, ".edr", "ener", nullptr, "Energy file" }, diff --git a/src/gromacs/fileio/g96io.cpp b/src/gromacs/fileio/g96io.cpp index e046b03d4d..cf0bd86cdb 100644 --- a/src/gromacs/fileio/g96io.cpp +++ b/src/gromacs/fileio/g96io.cpp @@ -107,8 +107,7 @@ static int read_g96_pos(char line[], t_symtab* symtab, FILE* fp, const char* inf } if ((nwanted != -1) && (natoms >= nwanted)) { - gmx_fatal(FARGS, "Found more coordinates (%d) in %s than expected %d\n", natoms, - infile, nwanted); + gmx_fatal(FARGS, "Found more coordinates (%d) in %s than expected %d\n", natoms, infile, nwanted); } if (atoms) { @@ -133,8 +132,7 @@ static int read_g96_pos(char line[], t_symtab* symtab, FILE* fp, const char* inf newres++; if (newres >= atoms->nr) { - gmx_fatal(FARGS, "More residues than atoms in %s (natoms = %d)", infile, - atoms->nr); + gmx_fatal(FARGS, "More residues than atoms in %s (natoms = %d)", infile, atoms->nr); } atoms->atom[natoms].resind = newres; if (newres + 1 > atoms->nres) @@ -159,8 +157,7 @@ static int read_g96_pos(char line[], t_symtab* symtab, FILE* fp, const char* inf } if ((nwanted != -1) && natoms != nwanted) { - fprintf(stderr, "Warning: found less coordinates (%d) in %s than expected %d\n", natoms, - infile, nwanted); + fprintf(stderr, "Warning: found less coordinates (%d) in %s than expected %d\n", natoms, infile, nwanted); } } @@ -200,8 +197,7 @@ static int read_g96_vel(char line[], FILE* fp, const char* infile, t_trxframe* f } if ((nwanted != -1) && (natoms >= nwanted)) { - gmx_fatal(FARGS, "Found more velocities (%d) in %s than expected %d\n", natoms, - infile, nwanted); + gmx_fatal(FARGS, "Found more velocities (%d) in %s than expected %d\n", natoms, infile, nwanted); } if (fr->v) { @@ -214,8 +210,7 @@ static int read_g96_vel(char line[], FILE* fp, const char* infile, t_trxframe* f } if ((nwanted != -1) && (natoms != nwanted)) { - fprintf(stderr, "Warning: found less velocities (%d) in %s than expected %d\n", natoms, - infile, nwanted); + fprintf(stderr, "Warning: found less velocities (%d) in %s than expected %d\n", natoms, infile, nwanted); } } @@ -312,8 +307,17 @@ int read_g96_conf(FILE* fp, const char* infile, char** name, t_trxframe* fr, t_s bEnd = (strncmp(line, "END", 3) == 0); if (!bEnd && (line[0] != '#')) { - nbp = sscanf(line, "%15lf%15lf%15lf%15lf%15lf%15lf%15lf%15lf%15lf", &db1, &db2, - &db3, &db4, &db5, &db6, &db7, &db8, &db9); + nbp = sscanf(line, + "%15lf%15lf%15lf%15lf%15lf%15lf%15lf%15lf%15lf", + &db1, + &db2, + &db3, + &db4, + &db5, + &db6, + &db7, + &db8, + &db9); if (nbp < 3) { gmx_fatal(FARGS, "Found a BOX line, but no box in %s", infile); @@ -378,10 +382,15 @@ void write_g96_conf(FILE* out, const char* title, const t_trxframe* fr, int nind { a = i; } - fprintf(out, "%5d %-5s %-5s%7d%15.9f%15.9f%15.9f\n", + fprintf(out, + "%5d %-5s %-5s%7d%15.9f%15.9f%15.9f\n", (atoms->resinfo[atoms->atom[a].resind].nr) % 100000, - *atoms->resinfo[atoms->atom[a].resind].name, *atoms->atomname[a], - (i + 1) % 10000000, fr->x[a][XX], fr->x[a][YY], fr->x[a][ZZ]); + *atoms->resinfo[atoms->atom[a].resind].name, + *atoms->atomname[a], + (i + 1) % 10000000, + fr->x[a][XX], + fr->x[a][YY], + fr->x[a][ZZ]); } } else @@ -417,10 +426,15 @@ void write_g96_conf(FILE* out, const char* title, const t_trxframe* fr, int nind { a = i; } - fprintf(out, "%5d %-5s %-5s%7d%15.9f%15.9f%15.9f\n", + fprintf(out, + "%5d %-5s %-5s%7d%15.9f%15.9f%15.9f\n", (atoms->resinfo[atoms->atom[a].resind].nr) % 100000, - *atoms->resinfo[atoms->atom[a].resind].name, *atoms->atomname[a], - (i + 1) % 10000000, fr->v[a][XX], fr->v[a][YY], fr->v[a][ZZ]); + *atoms->resinfo[atoms->atom[a].resind].name, + *atoms->atomname[a], + (i + 1) % 10000000, + fr->v[a][XX], + fr->v[a][YY], + fr->v[a][ZZ]); } } else @@ -448,8 +462,14 @@ void write_g96_conf(FILE* out, const char* title, const t_trxframe* fr, int nind if ((fr->box[XX][YY] != 0.0F) || (fr->box[XX][ZZ] != 0.0F) || (fr->box[YY][XX] != 0.0F) || (fr->box[YY][ZZ] != 0.0F) || (fr->box[ZZ][XX] != 0.0F) || (fr->box[ZZ][YY] != 0.0F)) { - fprintf(out, "%15.9f%15.9f%15.9f%15.9f%15.9f%15.9f", fr->box[XX][YY], fr->box[XX][ZZ], - fr->box[YY][XX], fr->box[YY][ZZ], fr->box[ZZ][XX], fr->box[ZZ][YY]); + fprintf(out, + "%15.9f%15.9f%15.9f%15.9f%15.9f%15.9f", + fr->box[XX][YY], + fr->box[XX][ZZ], + fr->box[YY][XX], + fr->box[YY][ZZ], + fr->box[ZZ][XX], + fr->box[ZZ][YY]); } fprintf(out, "\n"); fprintf(out, "END\n"); diff --git a/src/gromacs/fileio/gmxfio_xdr.cpp b/src/gromacs/fileio/gmxfio_xdr.cpp index 7df93fe4ef..45c9bbe4ef 100644 --- a/src/gromacs/fileio/gmxfio_xdr.cpp +++ b/src/gromacs/fileio/gmxfio_xdr.cpp @@ -114,16 +114,27 @@ static void gmx_fio_check_nitem(int eio, std::size_t nitem, const char* file, in gmx_fatal(FARGS, "nitem may differ from 1 only for %s, %s, %s or %s, not for %s" "(%s, %d)", - eioNames[eioNUCHAR], eioNames[eioNRVEC], eioNames[eioNCHAR], eioNames[eioOPAQUE], - eioNames[eio], file, line); + eioNames[eioNUCHAR], + eioNames[eioNRVEC], + eioNames[eioNCHAR], + eioNames[eioOPAQUE], + eioNames[eio], + file, + line); } } /* output a data type error. */ [[noreturn]] static void gmx_fio_fe(t_fileio* fio, int eio, const char* desc, const char* srcfile, int line) { - gmx_fatal(FARGS, "Trying to %s %s type %d (%s), src %s, line %d", fio->bRead ? "read" : "write", - desc, eio, ((eio >= 0) && (eio < eioNR)) ? eioNames[eio] : "unknown", srcfile, line); + gmx_fatal(FARGS, + "Trying to %s %s type %d (%s), src %s, line %d", + fio->bRead ? "read" : "write", + desc, + eio, + ((eio >= 0) && (eio < eioNR)) ? eioNames[eio] : "unknown", + srcfile, + line); } /* This is the part that reads xdr files. */ @@ -255,7 +266,9 @@ do_xdr(t_fileio* fio, void* item, std::size_t nitem, int eio, const char* desc, cptr = static_cast(item); GMX_RELEASE_ASSERT(nitem < static_cast(std::numeric_limits::max()), "The XDR interface cannot handle array lengths > 2^31"); - res = xdr_vector(fio->xdr, cptr, static_cast(nitem), + res = xdr_vector(fio->xdr, + cptr, + static_cast(nitem), static_cast(sizeof(char)), reinterpret_cast(xdr_char)); break; @@ -263,7 +276,9 @@ do_xdr(t_fileio* fio, void* item, std::size_t nitem, int eio, const char* desc, ucptr = static_cast(item); GMX_RELEASE_ASSERT(nitem < static_cast(std::numeric_limits::max()), "The XDR interface cannot handle array lengths > 2^31"); - res = xdr_vector(fio->xdr, reinterpret_cast(ucptr), static_cast(nitem), + res = xdr_vector(fio->xdr, + reinterpret_cast(ucptr), + static_cast(nitem), static_cast(sizeof(unsigned char)), reinterpret_cast(xdr_u_char)); break; @@ -288,7 +303,9 @@ do_xdr(t_fileio* fio, void* item, std::size_t nitem, int eio, const char* desc, dvec[m] = (static_cast(item))[m]; } } - res = xdr_vector(fio->xdr, reinterpret_cast(dvec), DIM, + res = xdr_vector(fio->xdr, + reinterpret_cast(dvec), + DIM, static_cast(sizeof(double)), reinterpret_cast(xdr_double)); if (item) @@ -308,7 +325,9 @@ do_xdr(t_fileio* fio, void* item, std::size_t nitem, int eio, const char* desc, fvec[m] = (static_cast(item))[m]; } } - res = xdr_vector(fio->xdr, reinterpret_cast(fvec), DIM, + res = xdr_vector(fio->xdr, + reinterpret_cast(fvec), + DIM, static_cast(sizeof(float)), reinterpret_cast(xdr_float)); if (item) @@ -374,7 +393,10 @@ do_xdr(t_fileio* fio, void* item, std::size_t nitem, int eio, const char* desc, gmx_fatal(FARGS, "wrong string length %d for string %s" " (source %s, line %d)", - slen, desc, srcfile, line); + slen, + desc, + srcfile, + line); } if (!item && fio->bRead) { diff --git a/src/gromacs/fileio/groio.cpp b/src/gromacs/fileio/groio.cpp index 45527bcee0..fdc1ebcb41 100644 --- a/src/gromacs/fileio/groio.cpp +++ b/src/gromacs/fileio/groio.cpp @@ -121,7 +121,8 @@ static gmx_bool get_w_conf(FILE* in, fprintf(stderr, "Warning: gro file contains less atoms (%d) than expected" " (%d)\n", - natoms, atoms->nr); + natoms, + atoms->nr); } atoms->haveMass = FALSE; @@ -294,8 +295,7 @@ static gmx_bool get_w_conf(FILE* in, { box[m][m] = (xmax[m] - xmin[m]); } - fprintf(stderr, "Generated a cubic box %8.3f x %8.3f x %8.3f\n", box[XX][XX], box[YY][YY], - box[ZZ][ZZ]); + fprintf(stderr, "Generated a cubic box %8.3f x %8.3f x %8.3f\n", box[XX][XX], box[YY][YY], box[ZZ][ZZ]); } else { @@ -406,7 +406,8 @@ gmx_bool gro_next_x_or_v(FILE* status, t_trxframe* fr) gmx_fatal(FARGS, "Number of atoms in gro frame (%d) doesn't match the number in the previous " "frame (%d)", - atoms.nr, fr->natoms); + atoms.nr, + fr->natoms); } return TRUE; @@ -450,9 +451,17 @@ static void write_hconf_box(FILE* out, const matrix box) if ((box[XX][YY] != 0.0F) || (box[XX][ZZ] != 0.0F) || (box[YY][XX] != 0.0F) || (box[YY][ZZ] != 0.0F) || (box[ZZ][XX] != 0.0F) || (box[ZZ][YY] != 0.0F)) { - fprintf(out, "%10.5f %9.5f %9.5f %9.5f %9.5f %9.5f %9.5f %9.5f %9.5f\n", box[XX][XX], - box[YY][YY], box[ZZ][ZZ], box[XX][YY], box[XX][ZZ], box[YY][XX], box[YY][ZZ], - box[ZZ][XX], box[ZZ][YY]); + fprintf(out, + "%10.5f %9.5f %9.5f %9.5f %9.5f %9.5f %9.5f %9.5f %9.5f\n", + box[XX][XX], + box[YY][YY], + box[ZZ][ZZ], + box[XX][YY], + box[XX][ZZ], + box[YY][XX], + box[YY][ZZ], + box[ZZ][XX], + box[ZZ][YY]); } else { diff --git a/src/gromacs/fileio/libxdrf.cpp b/src/gromacs/fileio/libxdrf.cpp index 2e64a58682..e9dcc679f9 100644 --- a/src/gromacs/fileio/libxdrf.cpp +++ b/src/gromacs/fileio/libxdrf.cpp @@ -244,7 +244,8 @@ static void sendints(int buf[], fprintf(stderr, "major breakdown in sendints num %u doesn't " "match size %u\n", - nums[i], sizes[i]); + nums[i], + sizes[i]); exit(1); } /* use one step multiply */ @@ -450,7 +451,9 @@ int xdr3dfcoord(XDR* xdrs, float* fp, int* size, float* precision) */ if (*size <= 9) { - return (xdr_vector(xdrs, reinterpret_cast(fp), static_cast(size3), + return (xdr_vector(xdrs, + reinterpret_cast(fp), + static_cast(size3), static_cast(sizeof(*fp)), reinterpret_cast(xdr_float))); } @@ -790,14 +793,17 @@ int xdr3dfcoord(XDR* xdrs, float* fp, int* size, float* precision) fprintf(stderr, "wrong number of coordinates in xdr3dfcoord; " "%d arg vs %d in file", - *size, lsize); + *size, + lsize); } *size = lsize; size3 = *size * 3; if (*size <= 9) { *precision = -1; - return (xdr_vector(xdrs, reinterpret_cast(fp), static_cast(size3), + return (xdr_vector(xdrs, + reinterpret_cast(fp), + static_cast(size3), static_cast(sizeof(*fp)), reinterpret_cast(xdr_float))); } diff --git a/src/gromacs/fileio/matio.cpp b/src/gromacs/fileio/matio.cpp index 8e1873867c..e0739c4462 100644 --- a/src/gromacs/fileio/matio.cpp +++ b/src/gromacs/fileio/matio.cpp @@ -143,7 +143,9 @@ static std::vector getcmap(FILE* in, const char* fn) gmx_fatal(FARGS, "Not enough lines in colormap file %s" "(should be %d, found only %d)", - fn, n + 1, i); + fn, + n + 1, + i); } sscanf(line, "%s%s%lf%lf%lf", code, desc, &r, &g, &b); m[i].code.c1 = code[0]; @@ -170,8 +172,13 @@ void printcmap(FILE* out, int n, t_mapping map[]) fprintf(out, "%d\n", n); for (i = 0; (i < n); i++) { - fprintf(out, "%c%c %20s %10g %10g %10g\n", map[i].code.c1 ? map[i].code.c1 : ' ', - map[i].code.c2 ? map[i].code.c2 : ' ', map[i].desc, map[i].rgb.r, map[i].rgb.g, + fprintf(out, + "%c%c %20s %10g %10g %10g\n", + map[i].code.c1 ? map[i].code.c1 : ' ', + map[i].code.c2 ? map[i].code.c2 : ' ', + map[i].desc, + map[i].rgb.r, + map[i].rgb.g, map[i].rgb.b); } } @@ -305,7 +312,11 @@ static t_matrix read_xpm_entry(FILE* in) if (debug) { - fprintf(debug, "%s %s %s %s\n", mm.title.c_str(), mm.legend.c_str(), mm.label_x.c_str(), + fprintf(debug, + "%s %s %s %s\n", + mm.title.c_str(), + mm.legend.c_str(), + mm.label_x.c_str(), mm.label_y.c_str()); } @@ -421,7 +432,8 @@ static t_matrix read_xpm_entry(FILE* in) gmx_fatal(FARGS, "Number of read colors map entries (%d) does not match the number in the header " "(%d)", - m, nmap); + m, + nmap); } /* Read axes, if there are any */ @@ -568,7 +580,8 @@ real** matrix2real(t_matrix* in, real** out) fprintf(stderr, "Could not convert matrix to reals,\n" "color map entry %zd has a non-real description: \"%s\"\n", - i, in->map[i].desc); + i, + in->map[i].desc); return nullptr; } rmap[i] = tmp; @@ -633,7 +646,9 @@ write_xpm_map3(FILE* out, int n_x, int n_y, int* nlevels, real lo, real mid, rea if (*nlevels > NMAP * NMAP) { - fprintf(stderr, "Warning, too many levels (%d) in matrix, using %d only\n", *nlevels, + fprintf(stderr, + "Warning, too many levels (%d) in matrix, using %d only\n", + *nlevels, static_cast(NMAP * NMAP)); *nlevels = NMAP * NMAP; } @@ -658,18 +673,23 @@ write_xpm_map3(FILE* out, int n_x, int n_y, int* nlevels, real lo, real mid, rea r = rlo.r + (i * (rmid.r - rlo.r) / clev_lo); g = rlo.g + (i * (rmid.g - rlo.g) / clev_lo); b = rlo.b + (i * (rmid.b - rlo.b) / clev_lo); - fprintf(out, "\"%c%c c #%02X%02X%02X \" /* \"%.3g\" */,\n", mapper[i % NMAP], + fprintf(out, + "\"%c%c c #%02X%02X%02X \" /* \"%.3g\" */,\n", + mapper[i % NMAP], (*nlevels <= NMAP) ? ' ' : mapper[i / NMAP], static_cast(std::round(255 * r)), static_cast(std::round(255 * g)), - static_cast(std::round(255 * b)), ((nmid - i) * lo + i * mid) / clev_lo); + static_cast(std::round(255 * b)), + ((nmid - i) * lo + i * mid) / clev_lo); } for (i = 0; (i < (*nlevels - nmid)); i++) { r = rmid.r + (i * (rhi.r - rmid.r) / clev_hi); g = rmid.g + (i * (rhi.g - rmid.g) / clev_hi); b = rmid.b + (i * (rhi.b - rmid.b) / clev_hi); - fprintf(out, "\"%c%c c #%02X%02X%02X \" /* \"%.3g\" */,\n", mapper[(i + nmid) % NMAP], + fprintf(out, + "\"%c%c c #%02X%02X%02X \" /* \"%.3g\" */,\n", + mapper[(i + nmid) % NMAP], (*nlevels <= NMAP) ? ' ' : mapper[(i + nmid) / NMAP], static_cast(std::round(255 * r)), static_cast(std::round(255 * g)), @@ -689,11 +709,14 @@ static void pr_simple_cmap(FILE* out, real lo, real hi, int nlevel, t_rgb rlo, t r = rlo.r + fac * (rhi.r - rlo.r); g = rlo.g + fac * (rhi.g - rlo.g); b = rlo.b + fac * (rhi.b - rlo.b); - fprintf(out, "\"%c%c c #%02X%02X%02X \" /* \"%.3g\" */,\n", mapper[(i + i0) % NMAP], + fprintf(out, + "\"%c%c c #%02X%02X%02X \" /* \"%.3g\" */,\n", + mapper[(i + i0) % NMAP], (nlevel <= NMAP) ? ' ' : mapper[(i + i0) / NMAP], static_cast(std::round(255 * r)), static_cast(std::round(255 * g)), - static_cast(std::round(255 * b)), lo + fac * (hi - lo)); + static_cast(std::round(255 * b)), + lo + fac * (hi - lo)); } } @@ -724,11 +747,14 @@ static void pr_discrete_cmap(FILE* out, int* nlevel, int i0) n = *nlevel; for (i = 0; (i < n); i++) { - fprintf(out, "\"%c%c c #%02X%02X%02X \" /* \"%3d\" */,\n", mapper[(i + i0) % NMAP], + fprintf(out, + "\"%c%c c #%02X%02X%02X \" /* \"%3d\" */,\n", + mapper[(i + i0) % NMAP], (n <= NMAP) ? ' ' : mapper[(i + i0) / NMAP], static_cast(round(255 * rgbd[i].r)), static_cast(round(255 * rgbd[i].g)), - static_cast(round(255 * rgbd[i].b)), i); + static_cast(round(255 * rgbd[i].b)), + i); } } @@ -779,7 +805,9 @@ static void write_xpm_map(FILE* out, int n_x, int n_y, int* nlevels, real lo, re if (*nlevels > NMAP * NMAP) { - fprintf(stderr, "Warning, too many levels (%d) in matrix, using %d only\n", *nlevels, + fprintf(stderr, + "Warning, too many levels (%d) in matrix, using %d only\n", + *nlevels, static_cast(NMAP * NMAP)); *nlevels = NMAP * NMAP; } @@ -799,11 +827,14 @@ static void write_xpm_map(FILE* out, int n_x, int n_y, int* nlevels, real lo, re r = (nlo * rlo.r + i * rhi.r) * invlevel; g = (nlo * rlo.g + i * rhi.g) * invlevel; b = (nlo * rlo.b + i * rhi.b) * invlevel; - fprintf(out, "\"%c%c c #%02X%02X%02X \" /* \"%.3g\" */,\n", mapper[i % NMAP], + fprintf(out, + "\"%c%c c #%02X%02X%02X \" /* \"%.3g\" */,\n", + mapper[i % NMAP], (*nlevels <= NMAP) ? ' ' : mapper[i / NMAP], static_cast(std::round(255 * r)), static_cast(std::round(255 * g)), - static_cast(std::round(255 * b)), (nlo * lo + i * hi) * invlevel); + static_cast(std::round(255 * b)), + (nlo * lo + i * hi) * invlevel); } } @@ -965,7 +996,12 @@ static void write_xpm_data_split(FILE* out, gmx_fatal(FARGS, "Range checking i = %d, j = %d, c = %d, bot = %d, top = %d " "matrix[i,j] = %f", - i, j, c, nlevel_bot, nlevel_top, mat[i][j]); + i, + j, + c, + nlevel_bot, + nlevel_top, + mat[i][j]); } } else if (i > j) @@ -976,7 +1012,12 @@ static void write_xpm_data_split(FILE* out, gmx_fatal(FARGS, "Range checking i = %d, j = %d, c = %d, bot = %d, top = %d " "matrix[i,j] = %f", - i, j, c, nlevel_bot, nlevel_top, mat[i][j]); + i, + j, + c, + nlevel_bot, + nlevel_top, + mat[i][j]); } } else @@ -1008,10 +1049,14 @@ void write_xpm_m(FILE* out, t_matrix m) fprintf(out, "\"%d %d %zu %d\",\n", m.nx, m.ny, m.map.size(), bOneChar ? 1 : 2); for (const auto& map : m.map) { - fprintf(out, "\"%c%c c #%02X%02X%02X \" /* \"%s\" */,\n", map.code.c1, - bOneChar ? ' ' : map.code.c2, static_cast(round(map.rgb.r * 255)), + fprintf(out, + "\"%c%c c #%02X%02X%02X \" /* \"%s\" */,\n", + map.code.c1, + bOneChar ? ' ' : map.code.c2, + static_cast(round(map.rgb.r * 255)), static_cast(round(map.rgb.g * 255)), - static_cast(round(map.rgb.b * 255)), map.desc); + static_cast(round(map.rgb.b * 255)), + map.desc); } writeXpmAxis(out, "x", m.axis_x); writeXpmAxis(out, "y", m.axis_y); @@ -1124,8 +1169,8 @@ void write_xpm_split(FILE* out, } write_xpm_header(out, title, legend, label_x, label_y, FALSE); - write_xpm_map_split(out, n_x, n_y, nlevel_top, lo_top, hi_top, rlo_top, rhi_top, bDiscreteColor, - nlevel_bot, lo_bot, hi_bot, rlo_bot, rhi_bot); + write_xpm_map_split( + out, n_x, n_y, nlevel_top, lo_top, hi_top, rlo_top, rhi_top, bDiscreteColor, nlevel_bot, lo_bot, hi_bot, rlo_bot, rhi_bot); writeXpmAxis(out, "x", ArrayRef(axis_x, axis_x + n_x + ((flags & MAT_SPATIAL_X) != 0U ? 1 : 0))); writeXpmAxis(out, "y", ArrayRef(axis_y, axis_y + n_y + ((flags & MAT_SPATIAL_Y) != 0U ? 1 : 0))); write_xpm_data_split(out, n_x, n_y, mat, lo_top, hi_top, *nlevel_top, lo_bot, hi_bot, *nlevel_bot); diff --git a/src/gromacs/fileio/mrcdensitymap.cpp b/src/gromacs/fileio/mrcdensitymap.cpp index de5dad2804..2fd3e5aa0f 100644 --- a/src/gromacs/fileio/mrcdensitymap.cpp +++ b/src/gromacs/fileio/mrcdensitymap.cpp @@ -84,8 +84,8 @@ std::vector readCharBufferFromFile(const std::string& filename) gmx_fseek(gmx_fio_getfp(mrcFile), 0, SEEK_SET); // Read whole file into buffer the size of the file std::vector fileContentBuffer(fileSize); - size_t readSize = fread(fileContentBuffer.data(), sizeof(char), fileContentBuffer.size(), - gmx_fio_getfp(mrcFile)); + size_t readSize = fread( + fileContentBuffer.data(), sizeof(char), fileContentBuffer.size(), gmx_fio_getfp(mrcFile)); gmx_fio_close(mrcFile); if (fileContentBuffer.size() != readSize) @@ -223,7 +223,8 @@ MultiDimArray, dynamicExtents3D> MrcDensityMapOfFloatFromFile { MultiDimArray, dynamicExtents3D> result( getDynamicExtents3D(impl_->reader().header())); - std::copy(std::begin(impl_->reader().constView()), std::end(impl_->reader().constView()), + std::copy(std::begin(impl_->reader().constView()), + std::end(impl_->reader().constView()), begin(result.asView())); return result; } diff --git a/src/gromacs/fileio/mrcdensitymapheader.cpp b/src/gromacs/fileio/mrcdensitymapheader.cpp index faaefc5773..d38a76caa7 100644 --- a/src/gromacs/fileio/mrcdensitymapheader.cpp +++ b/src/gromacs/fileio/mrcdensitymapheader.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -65,8 +65,9 @@ bool anySmallerZero(Container values) template bool anyLargerThanValue(Container values, typename Container::value_type boundaryValue) { - return std::any_of(std::begin(values), std::end(values), - [boundaryValue](auto v) { return v > boundaryValue; }); + return std::any_of(std::begin(values), std::end(values), [boundaryValue](auto v) { + return v > boundaryValue; + }); } } // namespace @@ -92,7 +93,8 @@ TranslateAndScale getCoordinateTransformationToLattice(const MrcDensityMapHeader RVec scale = { header.extent_[XX] / (header.cellLength_[XX] * c_AAtoNmConversion), header.extent_[YY] / (header.cellLength_[YY] * c_AAtoNmConversion), header.extent_[ZZ] / (header.cellLength_[ZZ] * c_AAtoNmConversion) }; - const RVec emdbOrigin{ header.userDefinedFloat_[12], header.userDefinedFloat_[13], + const RVec emdbOrigin{ header.userDefinedFloat_[12], + header.userDefinedFloat_[13], header.userDefinedFloat_[14] }; RVec translation; if (emdbOrigin[XX] == 0. && emdbOrigin[YY] == 0. && emdbOrigin[ZZ] == 0.) @@ -103,7 +105,8 @@ TranslateAndScale getCoordinateTransformationToLattice(const MrcDensityMapHeader } else { - translation = { -emdbOrigin[XX] * c_AAtoNmConversion, -emdbOrigin[YY] * c_AAtoNmConversion, + translation = { -emdbOrigin[XX] * c_AAtoNmConversion, + -emdbOrigin[YY] * c_AAtoNmConversion, -emdbOrigin[ZZ] * c_AAtoNmConversion }; } return { scale, translation }; @@ -111,7 +114,8 @@ TranslateAndScale getCoordinateTransformationToLattice(const MrcDensityMapHeader dynamicExtents3D getDynamicExtents3D(const MrcDensityMapHeader& header) { - return { header.numColumnRowSection_[ZZ], header.numColumnRowSection_[YY], + return { header.numColumnRowSection_[ZZ], + header.numColumnRowSection_[YY], header.numColumnRowSection_[XX] }; }; diff --git a/src/gromacs/fileio/mtxio.cpp b/src/gromacs/fileio/mtxio.cpp index b4b8cb1f30..4b567dcecb 100644 --- a/src/gromacs/fileio/mtxio.cpp +++ b/src/gromacs/fileio/mtxio.cpp @@ -181,8 +181,10 @@ void gmx_mtxio_read(const char* filename, int* nrow, int* ncol, real** full_matr } gmx_fio_do_int(fio, prec); - fprintf(stderr, "Reading %s precision matrix generated by GROMACS %s\n", - (prec == 1) ? "double" : "single", gmxver); + fprintf(stderr, + "Reading %s precision matrix generated by GROMACS %s\n", + (prec == 1) ? "double" : "single", + gmxver); gmx_fio_do_int(fio, i); *nrow = i; diff --git a/src/gromacs/fileio/pdbio.cpp b/src/gromacs/fileio/pdbio.cpp index c3f6810bcb..d2f373c63d 100644 --- a/src/gromacs/fileio/pdbio.cpp +++ b/src/gromacs/fileio/pdbio.cpp @@ -120,14 +120,30 @@ void gmx_write_pdb_box(FILE* out, PbcType pbcType, const matrix box) fprintf(out, "REMARK THIS IS A SIMULATION BOX\n"); if (pbcType != PbcType::Screw) { - fprintf(out, "CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %-11s%4d\n", 10 * norm(box[XX]), - 10 * norm(box[YY]), 10 * norm(box[ZZ]), alpha, beta, gamma, "P 1", 1); + fprintf(out, + "CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %-11s%4d\n", + 10 * norm(box[XX]), + 10 * norm(box[YY]), + 10 * norm(box[ZZ]), + alpha, + beta, + gamma, + "P 1", + 1); } else { /* Double the a-vector length and write the correct space group */ - fprintf(out, "CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %-11s%4d\n", 20 * norm(box[XX]), - 10 * norm(box[YY]), 10 * norm(box[ZZ]), alpha, beta, gamma, "P 21 1 1", 1); + fprintf(out, + "CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f %-11s%4d\n", + 20 * norm(box[XX]), + 10 * norm(box[YY]), + 10 * norm(box[ZZ]), + alpha, + beta, + gamma, + "P 21 1 1", + 1); } } @@ -245,9 +261,19 @@ static int gmx_fprintf_pqr_atomline(FILE* fp, atom_seq_number = atom_seq_number % 100000; res_seq_number = res_seq_number % 10000; - int n = fprintf(fp, "%-6s%5d %-4.4s%4.4s%c%4d %8.3f %8.3f %8.3f %6.2f %6.2f\n", pdbtp[record], - atom_seq_number, atom_name, res_name, chain_id, res_seq_number, x, y, z, - occupancy, b_factor); + int n = fprintf(fp, + "%-6s%5d %-4.4s%4.4s%c%4d %8.3f %8.3f %8.3f %6.2f %6.2f\n", + pdbtp[record], + atom_seq_number, + atom_name, + res_name, + chain_id, + res_seq_number, + x, + y, + z, + occupancy, + b_factor); return n; } @@ -343,22 +369,54 @@ void write_pdbfile_indexed(FILE* out, bfac = pdbinfo.bfac; if (!usePqrFormat) { - gmx_fprintf_pdb_atomline(out, type, i + 1, nm.c_str(), altloc, resnm.c_str(), ch, resnr, - resic, 10 * x[i][XX], 10 * x[i][YY], 10 * x[i][ZZ], occup, - bfac, atoms->atom[i].elem); + gmx_fprintf_pdb_atomline(out, + type, + i + 1, + nm.c_str(), + altloc, + resnm.c_str(), + ch, + resnr, + resic, + 10 * x[i][XX], + 10 * x[i][YY], + 10 * x[i][ZZ], + occup, + bfac, + atoms->atom[i].elem); if (atoms->pdbinfo && atoms->pdbinfo[i].bAnisotropic) { - fprintf(out, "ANISOU%5d %-4.4s%4.4s%c%4d%c %7d%7d%7d%7d%7d%7d\n", (i + 1) % 100000, - nm.c_str(), resnm.c_str(), ch, resnr, (resic == '\0') ? ' ' : resic, - atoms->pdbinfo[i].uij[0], atoms->pdbinfo[i].uij[1], atoms->pdbinfo[i].uij[2], - atoms->pdbinfo[i].uij[3], atoms->pdbinfo[i].uij[4], atoms->pdbinfo[i].uij[5]); + fprintf(out, + "ANISOU%5d %-4.4s%4.4s%c%4d%c %7d%7d%7d%7d%7d%7d\n", + (i + 1) % 100000, + nm.c_str(), + resnm.c_str(), + ch, + resnr, + (resic == '\0') ? ' ' : resic, + atoms->pdbinfo[i].uij[0], + atoms->pdbinfo[i].uij[1], + atoms->pdbinfo[i].uij[2], + atoms->pdbinfo[i].uij[3], + atoms->pdbinfo[i].uij[4], + atoms->pdbinfo[i].uij[5]); } } else { - gmx_fprintf_pqr_atomline(out, type, i + 1, nm.c_str(), resnm.c_str(), ch, resnr, - 10 * x[i][XX], 10 * x[i][YY], 10 * x[i][ZZ], occup, bfac); + gmx_fprintf_pqr_atomline(out, + type, + i + 1, + nm.c_str(), + resnm.c_str(), + ch, + resnr, + 10 * x[i][XX], + 10 * x[i][YY], + 10 * x[i][ZZ], + occup, + bfac); } } @@ -392,8 +450,8 @@ void write_pdbfile(FILE* out, { index[i] = i; } - write_pdbfile_indexed(out, title, atoms, x, pbcType, box, chainid, model_nr, atoms->nr, index, - conect, false); + write_pdbfile_indexed( + out, title, atoms, x, pbcType, box, chainid, model_nr, atoms->nr, index, conect, false); sfree(index); } @@ -458,9 +516,14 @@ static void read_anisou(char line[], int natom, t_atoms* atoms) } else { - if (sscanf(line + 29, "%d%d%d%d%d%d", &atoms->pdbinfo[i].uij[U11], &atoms->pdbinfo[i].uij[U22], - &atoms->pdbinfo[i].uij[U33], &atoms->pdbinfo[i].uij[U12], - &atoms->pdbinfo[i].uij[U13], &atoms->pdbinfo[i].uij[U23]) + if (sscanf(line + 29, + "%d%d%d%d%d%d", + &atoms->pdbinfo[i].uij[U11], + &atoms->pdbinfo[i].uij[U22], + &atoms->pdbinfo[i].uij[U33], + &atoms->pdbinfo[i].uij[U12], + &atoms->pdbinfo[i].uij[U13], + &atoms->pdbinfo[i].uij[U23]) == 6) { atoms->pdbinfo[i].bAnisotropic = TRUE; @@ -1055,9 +1118,21 @@ int gmx_fprintf_pdb_atomline(FILE* fp, atom_seq_number = atom_seq_number % 100000; res_seq_number = res_seq_number % 10000; - n = fprintf(fp, "%-6s%5d %-4.4s%c%4.4s%c%4d%c %8.3f%8.3f%8.3f%6.2f%6.2f %2s\n", - pdbtp[record], atom_seq_number, tmp_atomname, alternate_location, tmp_resname, - chain_id, res_seq_number, res_insertion_code, x, y, z, occupancy, b_factor, + n = fprintf(fp, + "%-6s%5d %-4.4s%c%4.4s%c%4d%c %8.3f%8.3f%8.3f%6.2f%6.2f %2s\n", + pdbtp[record], + atom_seq_number, + tmp_atomname, + alternate_location, + tmp_resname, + chain_id, + res_seq_number, + res_insertion_code, + x, + y, + z, + occupancy, + b_factor, (element != nullptr) ? element : ""); return n; diff --git a/src/gromacs/fileio/readinp.cpp b/src/gromacs/fileio/readinp.cpp index 5d497b8cd7..1da9fd268a 100644 --- a/src/gromacs/fileio/readinp.cpp +++ b/src/gromacs/fileio/readinp.cpp @@ -225,7 +225,8 @@ void write_inpfile(gmx::TextOutputStream* stream, } else { - writer.writeLine(formatString("%-24s = %s", local.name_.c_str(), + writer.writeLine(formatString("%-24s = %s", + local.name_.c_str(), !local.value_.empty() ? local.value_.c_str() : "")); } } @@ -263,7 +264,8 @@ void replace_inp_entry(gmx::ArrayRef inp, const char* old_entry, cons gmx_fatal(FARGS, "A parameter is present with both the old name '%s' and the new name " "'%s'.", - local.name_.c_str(), inp[foundIndex].name_.c_str()); + local.name_.c_str(), + inp[foundIndex].name_.c_str()); } local.name_.assign(new_entry); @@ -363,7 +365,8 @@ int get_eint(std::vector* inp, const char* name, int def, warninp_t w sprintf(warn_buf, "Right hand side '%s' for parameter '%s' in parameter file is not an integer " "value\n", - inpRef[ii].value_.c_str(), inpRef[ii].name_.c_str()); + inpRef[ii].value_.c_str(), + inpRef[ii].name_.c_str()); warning_error(wi, warn_buf); } @@ -399,7 +402,8 @@ int64_t get_eint64(std::vector* inp, const char* name, int64_t def, w sprintf(warn_buf, "Right hand side '%s' for parameter '%s' in parameter file is not an integer " "value\n", - inpRef[ii].value_.c_str(), inpRef[ii].name_.c_str()); + inpRef[ii].value_.c_str(), + inpRef[ii].name_.c_str()); warning_error(wi, warn_buf); } @@ -435,7 +439,8 @@ double get_ereal(std::vector* inp, const char* name, double def, warn sprintf(warn_buf, "Right hand side '%s' for parameter '%s' in parameter file is not a real " "value\n", - inpRef[ii].value_.c_str(), inpRef[ii].name_.c_str()); + inpRef[ii].value_.c_str(), + inpRef[ii].name_.c_str()); warning_error(wi, warn_buf); } @@ -505,8 +510,11 @@ int get_eeenum(std::vector* inp, const char* name, const char** defs, if (defs[i] == nullptr) { - n += sprintf(buf, "Invalid enum '%s' for variable %s, using '%s'\n", - inpRef[ii].value_.c_str(), name, defs[0]); + n += sprintf(buf, + "Invalid enum '%s' for variable %s, using '%s'\n", + inpRef[ii].value_.c_str(), + name, + defs[0]); n += sprintf(buf + n, "Next time use one of:"); int j = 0; while (defs[j]) diff --git a/src/gromacs/fileio/tests/confio.cpp b/src/gromacs/fileio/tests/confio.cpp index 53a1216ff3..70544f3d7a 100644 --- a/src/gromacs/fileio/tests/confio.cpp +++ b/src/gromacs/fileio/tests/confio.cpp @@ -103,8 +103,13 @@ public: void writeReferenceFile() { - write_sto_conf(referenceFilename_.c_str(), *refTop_->name, &refTop_->atoms, - as_rvec_array(refX_.data()), nullptr, PbcType::Unset, refBox_); + write_sto_conf(referenceFilename_.c_str(), + *refTop_->name, + &refTop_->atoms, + as_rvec_array(refX_.data()), + nullptr, + PbcType::Unset, + refBox_); } void readReferenceFileTps() @@ -121,8 +126,8 @@ public: void writeTestFileAndTest() { - write_sto_conf(testFilename_.c_str(), *testTop_->name, &testTop_->atoms, testX_, nullptr, - PbcType::Unset, testBox_); + write_sto_conf( + testFilename_.c_str(), *testTop_->name, &testTop_->atoms, testX_, nullptr, PbcType::Unset, testBox_); testFilesEqual(referenceFilename_, testFilename_); } diff --git a/src/gromacs/fileio/tests/mrcdensitymap.cpp b/src/gromacs/fileio/tests/mrcdensitymap.cpp index d142f0fb4b..57879d58fc 100644 --- a/src/gromacs/fileio/tests/mrcdensitymap.cpp +++ b/src/gromacs/fileio/tests/mrcdensitymap.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -135,7 +135,8 @@ TEST(MrcDensityMap, ReadsDensityDataFromFile) TestReferenceData refData; TestReferenceChecker checker(refData.rootChecker()); - checker.checkSequence(begin(densityData.asConstView()), end(densityData.asConstView()), + checker.checkSequence(begin(densityData.asConstView()), + end(densityData.asConstView()), "data ellipsoid density"); } diff --git a/src/gromacs/fileio/tngio.cpp b/src/gromacs/fileio/tngio.cpp index a872a8793b..90615238cc 100644 --- a/src/gromacs/fileio/tngio.cpp +++ b/src/gromacs/fileio/tngio.cpp @@ -158,8 +158,7 @@ void gmx_tng_open(const char* filename, char mode, gmx_tng_trajectory_t* gmx_tng # if GMX_DOUBLE precisionString = " (double precision)"; # endif - sprintf(programInfo, "%.100s %.128s%.24s", gmx::getProgramContext().displayName(), - gmx_version(), precisionString); + sprintf(programInfo, "%.100s %.128s%.24s", gmx::getProgramContext().displayName(), gmx_version(), precisionString); if (mode == 'w') { tng_first_program_name_set(*tng, programInfo); @@ -266,8 +265,8 @@ static void addTngMoleculeFromTopology(gmx_tng_trajectory_t gmx_tng, * number the latter should be used. Wait for TNG 2.0*/ tng_chain_residue_add(tng, tngChain, *resInfo->name, &tngRes); } - tng_residue_atom_add(tng, tngRes, *(atoms->atomname[atomIndex]), - *(atoms->atomtype[atomIndex]), &tngAtom); + tng_residue_atom_add( + tng, tngRes, *(atoms->atomname[atomIndex]), *(atoms->atomtype[atomIndex]), &tngAtom); } } tng_molecule_cnt_set(tng, *tngMol, numMolecules); @@ -342,18 +341,37 @@ void gmx_tng_add_mtop(gmx_tng_trajectory_t gmx_tng, const gmx_mtop_t* mtop) } for (int molCounter = 1; molCounter < molBlock.nmol; molCounter++) { - std::copy_n(atomCharges.end() - molType->atoms.nr, molType->atoms.nr, + std::copy_n(atomCharges.end() - molType->atoms.nr, + molType->atoms.nr, std::back_inserter(atomCharges)); - std::copy_n(atomMasses.end() - molType->atoms.nr, molType->atoms.nr, - std::back_inserter(atomMasses)); + std::copy_n(atomMasses.end() - molType->atoms.nr, molType->atoms.nr, std::back_inserter(atomMasses)); } } /* Write the TNG data blocks. */ - tng_particle_data_block_add(tng, TNG_TRAJ_PARTIAL_CHARGES, "PARTIAL CHARGES", datatype, - TNG_NON_TRAJECTORY_BLOCK, 1, 1, 1, 0, mtop->natoms, - TNG_GZIP_COMPRESSION, atomCharges.data()); - tng_particle_data_block_add(tng, TNG_TRAJ_MASSES, "ATOM MASSES", datatype, TNG_NON_TRAJECTORY_BLOCK, - 1, 1, 1, 0, mtop->natoms, TNG_GZIP_COMPRESSION, atomMasses.data()); + tng_particle_data_block_add(tng, + TNG_TRAJ_PARTIAL_CHARGES, + "PARTIAL CHARGES", + datatype, + TNG_NON_TRAJECTORY_BLOCK, + 1, + 1, + 1, + 0, + mtop->natoms, + TNG_GZIP_COMPRESSION, + atomCharges.data()); + tng_particle_data_block_add(tng, + TNG_TRAJ_MASSES, + "ATOM MASSES", + datatype, + TNG_NON_TRAJECTORY_BLOCK, + 1, + 1, + 1, + 0, + mtop->natoms, + TNG_GZIP_COMPRESSION, + atomMasses.data()); } /*! \libinternal \brief Compute greatest common divisor of n1 and n2 @@ -427,8 +445,7 @@ static void set_writing_intervals(gmx_tng_trajectory_t gmx_tng, /* Define pointers to specific writing functions depending on if we * write float or double data */ typedef tng_function_status (*set_writing_interval_func_pointer)( - tng_trajectory_t, const int64_t, const int64_t, const int64_t, const char*, const char, - const char); + tng_trajectory_t, const int64_t, const int64_t, const int64_t, const char*, const char, const char); # if GMX_DOUBLE set_writing_interval_func_pointer set_writing_interval = tng_util_generic_write_interval_double_set; # else @@ -467,8 +484,8 @@ static void set_writing_intervals(gmx_tng_trajectory_t gmx_tng, } if (xout) { - set_writing_interval(tng, xout, 3, TNG_TRAJ_POSITIONS, "POSITIONS", TNG_PARTICLE_BLOCK_DATA, - compression); + set_writing_interval( + tng, xout, 3, TNG_TRAJ_POSITIONS, "POSITIONS", TNG_PARTICLE_BLOCK_DATA, compression); /* TODO: if/when we write energies to TNG also, reconsider how * and when box information is written, because GROMACS * behaviour pre-5.0 was to write the box with every @@ -483,8 +500,8 @@ static void set_writing_intervals(gmx_tng_trajectory_t gmx_tng, } if (vout) { - set_writing_interval(tng, vout, 3, TNG_TRAJ_VELOCITIES, "VELOCITIES", - TNG_PARTICLE_BLOCK_DATA, compression); + set_writing_interval( + tng, vout, 3, TNG_TRAJ_VELOCITIES, "VELOCITIES", TNG_PARTICLE_BLOCK_DATA, compression); gcd = greatest_common_divisor_if_positive(gcd, vout); if (lowest < 0 || vout < lowest) @@ -494,8 +511,8 @@ static void set_writing_intervals(gmx_tng_trajectory_t gmx_tng, } if (fout) { - set_writing_interval(tng, fout, 3, TNG_TRAJ_FORCES, "FORCES", TNG_PARTICLE_BLOCK_DATA, - TNG_GZIP_COMPRESSION); + set_writing_interval( + tng, fout, 3, TNG_TRAJ_FORCES, "FORCES", TNG_PARTICLE_BLOCK_DATA, TNG_GZIP_COMPRESSION); gcd = greatest_common_divisor_if_positive(gcd, fout); if (lowest < 0 || fout < lowest) @@ -507,11 +524,11 @@ static void set_writing_intervals(gmx_tng_trajectory_t gmx_tng, { /* Lambdas and box shape written at an interval of the lowest common denominator of other output */ - set_writing_interval(tng, gcd, 1, TNG_GMX_LAMBDA, "LAMBDAS", TNG_NON_PARTICLE_BLOCK_DATA, - TNG_GZIP_COMPRESSION); + set_writing_interval( + tng, gcd, 1, TNG_GMX_LAMBDA, "LAMBDAS", TNG_NON_PARTICLE_BLOCK_DATA, TNG_GZIP_COMPRESSION); - set_writing_interval(tng, gcd, 9, TNG_TRAJ_BOX_SHAPE, "BOX SHAPE", - TNG_NON_PARTICLE_BLOCK_DATA, TNG_GZIP_COMPRESSION); + set_writing_interval( + tng, gcd, 9, TNG_TRAJ_BOX_SHAPE, "BOX SHAPE", TNG_NON_PARTICLE_BLOCK_DATA, TNG_GZIP_COMPRESSION); gmx_tng->lambdaOutputInterval = gcd; gmx_tng->boxOutputInterval = gcd; if (gcd < lowest / 10) @@ -520,7 +537,8 @@ static void set_writing_intervals(gmx_tng_trajectory_t gmx_tng, "The lowest common denominator of trajectory output is " "every %d step(s), whereas the shortest output interval " "is every %d steps.", - gcd, lowest); + gcd, + lowest); } } } @@ -657,8 +675,12 @@ static void add_selection_groups(gmx_tng_trajectory_t gmx_tng, const gmx_mtop_t* * original residue IDs - otherwise there might be conflicts. */ tng_chain_residue_add(tng, chain, res_name, &res); } - tng_residue_atom_w_id_add(tng, res, *(atoms->atomname[atomIndex]), - *(atoms->atomtype[atomIndex]), atom_offset + atomIndex, &atom); + tng_residue_atom_w_id_add(tng, + res, + *(atoms->atomname[atomIndex]), + *(atoms->atomtype[atomIndex]), + atom_offset + atomIndex, + &atom); bAtomsAdded = TRUE; } /* Add bonds. */ @@ -674,15 +696,13 @@ static void add_selection_groups(gmx_tng_trajectory_t gmx_tng, const gmx_mtop_t* int atom1, atom2; atom1 = ilist.iatoms[l] + atom_offset; atom2 = ilist.iatoms[l + 1] + atom_offset; - if (getGroupType(mtop->groups, - SimulationAtomGroupType::CompressedPositionOutput, atom1) + if (getGroupType(mtop->groups, SimulationAtomGroupType::CompressedPositionOutput, atom1) == 0 - && getGroupType(mtop->groups, - SimulationAtomGroupType::CompressedPositionOutput, atom2) + && getGroupType(mtop->groups, SimulationAtomGroupType::CompressedPositionOutput, atom2) == 0) { - tng_molecule_bond_add(tng, mol, ilist.iatoms[l], - ilist.iatoms[l + 1], &tngBond); + tng_molecule_bond_add( + tng, mol, ilist.iatoms[l], ilist.iatoms[l + 1], &tngBond); } } } @@ -767,9 +787,15 @@ void gmx_fwrite_tng(gmx_tng_trajectory_t gmx_tng, const rvec* f) { #if GMX_USE_TNG - typedef tng_function_status (*write_data_func_pointer)( - tng_trajectory_t, const int64_t, const double, const real*, const int64_t, - const int64_t, const char*, const char, const char); + typedef tng_function_status (*write_data_func_pointer)(tng_trajectory_t, + const int64_t, + const double, + const real*, + const int64_t, + const int64_t, + const char*, + const char, + const char); # if GMX_DOUBLE static write_data_func_pointer write_data = tng_util_generic_with_time_double_write; # else @@ -845,8 +871,15 @@ void gmx_fwrite_tng(gmx_tng_trajectory_t gmx_tng, { GMX_ASSERT(box, "Need a non-NULL box if positions are written"); - if (write_data(tng, step, elapsedSeconds, reinterpret_cast(x), 3, - TNG_TRAJ_POSITIONS, "POSITIONS", TNG_PARTICLE_BLOCK_DATA, compression) + if (write_data(tng, + step, + elapsedSeconds, + reinterpret_cast(x), + 3, + TNG_TRAJ_POSITIONS, + "POSITIONS", + TNG_PARTICLE_BLOCK_DATA, + compression) != TNG_SUCCESS) { gmx_file("Cannot write TNG trajectory frame; maybe you are out of disk space?"); @@ -855,8 +888,15 @@ void gmx_fwrite_tng(gmx_tng_trajectory_t gmx_tng, if (v) { - if (write_data(tng, step, elapsedSeconds, reinterpret_cast(v), 3, - TNG_TRAJ_VELOCITIES, "VELOCITIES", TNG_PARTICLE_BLOCK_DATA, compression) + if (write_data(tng, + step, + elapsedSeconds, + reinterpret_cast(v), + 3, + TNG_TRAJ_VELOCITIES, + "VELOCITIES", + TNG_PARTICLE_BLOCK_DATA, + compression) != TNG_SUCCESS) { gmx_file("Cannot write TNG trajectory frame; maybe you are out of disk space?"); @@ -867,8 +907,15 @@ void gmx_fwrite_tng(gmx_tng_trajectory_t gmx_tng, { /* TNG-MF1 compression only compresses positions and velocities. Use lossless * compression for forces regardless of output mode */ - if (write_data(tng, step, elapsedSeconds, reinterpret_cast(f), 3, - TNG_TRAJ_FORCES, "FORCES", TNG_PARTICLE_BLOCK_DATA, TNG_GZIP_COMPRESSION) + if (write_data(tng, + step, + elapsedSeconds, + reinterpret_cast(f), + 3, + TNG_TRAJ_FORCES, + "FORCES", + TNG_PARTICLE_BLOCK_DATA, + TNG_GZIP_COMPRESSION) != TNG_SUCCESS) { gmx_file("Cannot write TNG trajectory frame; maybe you are out of disk space?"); @@ -879,8 +926,15 @@ void gmx_fwrite_tng(gmx_tng_trajectory_t gmx_tng, { /* TNG-MF1 compression only compresses positions and velocities. Use lossless * compression for box shape regardless of output mode */ - if (write_data(tng, step, elapsedSeconds, reinterpret_cast(box), 9, - TNG_TRAJ_BOX_SHAPE, "BOX SHAPE", TNG_NON_PARTICLE_BLOCK_DATA, TNG_GZIP_COMPRESSION) + if (write_data(tng, + step, + elapsedSeconds, + reinterpret_cast(box), + 9, + TNG_TRAJ_BOX_SHAPE, + "BOX SHAPE", + TNG_NON_PARTICLE_BLOCK_DATA, + TNG_GZIP_COMPRESSION) != TNG_SUCCESS) { gmx_file("Cannot write TNG trajectory frame; maybe you are out of disk space?"); @@ -891,8 +945,15 @@ void gmx_fwrite_tng(gmx_tng_trajectory_t gmx_tng, { /* TNG-MF1 compression only compresses positions and velocities. Use lossless * compression for lambda regardless of output mode */ - if (write_data(tng, step, elapsedSeconds, reinterpret_cast(&lambda), 1, - TNG_GMX_LAMBDA, "LAMBDAS", TNG_NON_PARTICLE_BLOCK_DATA, TNG_GZIP_COMPRESSION) + if (write_data(tng, + step, + elapsedSeconds, + reinterpret_cast(&lambda), + 1, + TNG_GMX_LAMBDA, + "LAMBDAS", + TNG_NON_PARTICLE_BLOCK_DATA, + TNG_GZIP_COMPRESSION) != TNG_SUCCESS) { gmx_file("Cannot write TNG trajectory frame; maybe you are out of disk space?"); @@ -963,15 +1024,16 @@ void gmx_prepare_tng_writing(const char* filename, #if GMX_USE_TNG tng_trajectory_t* input = (gmx_tng_input && *gmx_tng_input) ? &(*gmx_tng_input)->tng : nullptr; /* FIXME after 5.0: Currently only standard block types are read */ - const int defaultNumIds = 5; - static int64_t fallbackIds[defaultNumIds] = { TNG_TRAJ_BOX_SHAPE, TNG_TRAJ_POSITIONS, - TNG_TRAJ_VELOCITIES, TNG_TRAJ_FORCES, TNG_GMX_LAMBDA }; - static char fallbackNames[defaultNumIds][32] = { "BOX SHAPE", "POSITIONS", "VELOCITIES", - "FORCES", "LAMBDAS" }; + const int defaultNumIds = 5; + static int64_t fallbackIds[defaultNumIds] = { + TNG_TRAJ_BOX_SHAPE, TNG_TRAJ_POSITIONS, TNG_TRAJ_VELOCITIES, TNG_TRAJ_FORCES, TNG_GMX_LAMBDA + }; + static char fallbackNames[defaultNumIds][32] = { + "BOX SHAPE", "POSITIONS", "VELOCITIES", "FORCES", "LAMBDAS" + }; typedef tng_function_status (*set_writing_interval_func_pointer)( - tng_trajectory_t, const int64_t, const int64_t, const int64_t, const char*, const char, - const char); + tng_trajectory_t, const int64_t, const int64_t, const int64_t, const char*, const char, const char); # if GMX_DOUBLE set_writing_interval_func_pointer set_writing_interval = tng_util_generic_write_interval_double_set; # else @@ -1016,21 +1078,41 @@ void gmx_prepare_tng_writing(const char* filename, { case TNG_TRAJ_POSITIONS: case TNG_TRAJ_VELOCITIES: - set_writing_interval(*output, interval, 3, fallbackIds[i], fallbackNames[i], - TNG_PARTICLE_BLOCK_DATA, compression_type); + set_writing_interval(*output, + interval, + 3, + fallbackIds[i], + fallbackNames[i], + TNG_PARTICLE_BLOCK_DATA, + compression_type); break; case TNG_TRAJ_FORCES: - set_writing_interval(*output, interval, 3, fallbackIds[i], fallbackNames[i], - TNG_PARTICLE_BLOCK_DATA, TNG_GZIP_COMPRESSION); + set_writing_interval(*output, + interval, + 3, + fallbackIds[i], + fallbackNames[i], + TNG_PARTICLE_BLOCK_DATA, + TNG_GZIP_COMPRESSION); break; case TNG_TRAJ_BOX_SHAPE: - set_writing_interval(*output, interval, 9, fallbackIds[i], fallbackNames[i], - TNG_NON_PARTICLE_BLOCK_DATA, TNG_GZIP_COMPRESSION); + set_writing_interval(*output, + interval, + 9, + fallbackIds[i], + fallbackNames[i], + TNG_NON_PARTICLE_BLOCK_DATA, + TNG_GZIP_COMPRESSION); (*gmx_tng_output)->boxOutputInterval = interval; break; case TNG_GMX_LAMBDA: - set_writing_interval(*output, interval, 1, fallbackIds[i], fallbackNames[i], - TNG_NON_PARTICLE_BLOCK_DATA, TNG_GZIP_COMPRESSION); + set_writing_interval(*output, + interval, + 1, + fallbackIds[i], + fallbackNames[i], + TNG_NON_PARTICLE_BLOCK_DATA, + TNG_GZIP_COMPRESSION); (*gmx_tng_output)->lambdaOutputInterval = interval; break; default: continue; @@ -1082,8 +1164,8 @@ void gmx_write_tng_from_trxframe(gmx_tng_trajectory_t gmx_tng_output, const t_tr { natoms = frame->natoms; } - gmx_fwrite_tng(gmx_tng_output, TRUE, frame->step, frame->time, 0, frame->box, natoms, frame->x, - frame->v, frame->f); + gmx_fwrite_tng( + gmx_tng_output, TRUE, frame->step, frame->time, 0, frame->box, natoms, frame->x, frame->v, frame->f); #else GMX_UNUSED_VALUE(gmx_tng_output); GMX_UNUSED_VALUE(frame); @@ -1309,10 +1391,10 @@ gmx_bool gmx_read_next_tng_frame(gmx_tng_trajectory_t gmx_tng_input, double frameTime = -1.0; int size, blockDependency; double prec; - const int defaultNumIds = 5; - static int64_t fallbackRequestedIds[defaultNumIds] = { TNG_TRAJ_BOX_SHAPE, TNG_TRAJ_POSITIONS, - TNG_TRAJ_VELOCITIES, TNG_TRAJ_FORCES, - TNG_GMX_LAMBDA }; + const int defaultNumIds = 5; + static int64_t fallbackRequestedIds[defaultNumIds] = { + TNG_TRAJ_BOX_SHAPE, TNG_TRAJ_POSITIONS, TNG_TRAJ_VELOCITIES, TNG_TRAJ_FORCES, TNG_GMX_LAMBDA + }; fr->bStep = FALSE; @@ -1359,13 +1441,13 @@ gmx_bool gmx_read_next_tng_frame(gmx_tng_trajectory_t gmx_tng_input, tng_data_block_dependency_get(input, blockId, &blockDependency); if (blockDependency & TNG_PARTICLE_DEPENDENT) { - stat = tng_util_particle_data_next_frame_read(input, blockId, &values, &datatype, - &frameNumber, &frameTime); + stat = tng_util_particle_data_next_frame_read( + input, blockId, &values, &datatype, &frameNumber, &frameTime); } else { - stat = tng_util_non_particle_data_next_frame_read(input, blockId, &values, &datatype, - &frameNumber, &frameTime); + stat = tng_util_non_particle_data_next_frame_read( + input, blockId, &values, &datatype, &frameNumber, &frameTime); } if (stat == TNG_CRITICAL) { @@ -1390,14 +1472,20 @@ gmx_bool gmx_read_next_tng_frame(gmx_tng_trajectory_t gmx_tng_input, { convert_array_to_real_array(reinterpret_cast(values) + size * i * DIM, reinterpret_cast(fr->box[i]), - getDistanceScaleFactor(gmx_tng_input), 1, DIM, datatype); + getDistanceScaleFactor(gmx_tng_input), + 1, + DIM, + datatype); } fr->bBox = TRUE; break; case TNG_TRAJ_POSITIONS: srenew(fr->x, fr->natoms); - convert_array_to_real_array(values, reinterpret_cast(fr->x), - getDistanceScaleFactor(gmx_tng_input), fr->natoms, DIM, + convert_array_to_real_array(values, + reinterpret_cast(fr->x), + getDistanceScaleFactor(gmx_tng_input), + fr->natoms, + DIM, datatype); fr->bX = TRUE; tng_util_frame_current_compression_get(input, blockId, &codecId, &prec); @@ -1410,8 +1498,11 @@ gmx_bool gmx_read_next_tng_frame(gmx_tng_trajectory_t gmx_tng_input, break; case TNG_TRAJ_VELOCITIES: srenew(fr->v, fr->natoms); - convert_array_to_real_array(values, reinterpret_cast(fr->v), - getDistanceScaleFactor(gmx_tng_input), fr->natoms, DIM, + convert_array_to_real_array(values, + reinterpret_cast(fr->v), + getDistanceScaleFactor(gmx_tng_input), + fr->natoms, + DIM, datatype); fr->bV = TRUE; tng_util_frame_current_compression_get(input, blockId, &codecId, &prec); @@ -1424,8 +1515,11 @@ gmx_bool gmx_read_next_tng_frame(gmx_tng_trajectory_t gmx_tng_input, break; case TNG_TRAJ_FORCES: srenew(fr->f, fr->natoms); - convert_array_to_real_array(values, reinterpret_cast(fr->f), - getDistanceScaleFactor(gmx_tng_input), fr->natoms, DIM, + convert_array_to_real_array(values, + reinterpret_cast(fr->f), + getDistanceScaleFactor(gmx_tng_input), + fr->natoms, + DIM, datatype); fr->bF = TRUE; break; @@ -1573,8 +1667,14 @@ void gmx_print_tng_molecule_system(gmx_tng_trajectory_t gmx_tng_input, FILE* str } tng_num_particles_get(input, &nAtoms); - stat = tng_particle_data_vector_get(input, TNG_TRAJ_PARTIAL_CHARGES, &data, &nFramesRead, - &strideLength, &nParticlesRead, &nValuesPerFrameRead, &datatype); + stat = tng_particle_data_vector_get(input, + TNG_TRAJ_PARTIAL_CHARGES, + &data, + &nFramesRead, + &strideLength, + &nParticlesRead, + &nValuesPerFrameRead, + &datatype); if (stat == TNG_SUCCESS) { atomCharges.resize(nAtoms); @@ -1592,8 +1692,8 @@ void gmx_print_tng_molecule_system(gmx_tng_trajectory_t gmx_tng_input, FILE* str } } - stat = tng_particle_data_vector_get(input, TNG_TRAJ_MASSES, &data, &nFramesRead, &strideLength, - &nParticlesRead, &nValuesPerFrameRead, &datatype); + stat = tng_particle_data_vector_get( + input, TNG_TRAJ_MASSES, &data, &nFramesRead, &strideLength, &nParticlesRead, &nValuesPerFrameRead, &datatype); if (stat == TNG_SUCCESS) { atomMasses.resize(nAtoms); @@ -1688,15 +1788,15 @@ gmx_bool gmx_get_tng_data_next_frame_of_block_type(gmx_tng_trajectory_t gmx_tng_ if (blockDependency & TNG_PARTICLE_DEPENDENT) { tng_num_particles_get(input, nAtoms); - stat = tng_util_particle_data_next_frame_read(input, blockId, &data, &datatype, frameNumber, - frameTime); + stat = tng_util_particle_data_next_frame_read( + input, blockId, &data, &datatype, frameNumber, frameTime); } else { *nAtoms = 1; /* There are not actually any atoms, but it is used for allocating memory */ - stat = tng_util_non_particle_data_next_frame_read(input, blockId, &data, &datatype, - frameNumber, frameTime); + stat = tng_util_non_particle_data_next_frame_read( + input, blockId, &data, &datatype, frameNumber, frameTime); } if (stat == TNG_CRITICAL) { @@ -1714,8 +1814,8 @@ gmx_bool gmx_get_tng_data_next_frame_of_block_type(gmx_tng_trajectory_t gmx_tng_ gmx_file("Cannot read next frame of TNG file"); } srenew(*values, sizeof(real) * *nValuesPerFrame * *nAtoms); - convert_array_to_real_array(data, *values, getDistanceScaleFactor(gmx_tng_input), *nAtoms, - *nValuesPerFrame, datatype); + convert_array_to_real_array( + data, *values, getDistanceScaleFactor(gmx_tng_input), *nAtoms, *nValuesPerFrame, datatype); tng_util_frame_current_compression_get(input, blockId, &codecId, &localPrec); diff --git a/src/gromacs/fileio/tpxio.cpp b/src/gromacs/fileio/tpxio.cpp index b72e66cf2a..568922aa44 100644 --- a/src/gromacs/fileio/tpxio.cpp +++ b/src/gromacs/fileio/tpxio.cpp @@ -2004,8 +2004,12 @@ static void do_iparams(gmx::ISerializer* serializer, t_functype ftype, t_iparams serializer->doInt(&iparams->cmap.cmapB); break; default: - gmx_fatal(FARGS, "unknown function type %d (%s) in %s line %d", ftype, - interaction_function[ftype].name, __FILE__, __LINE__); + gmx_fatal(FARGS, + "unknown function type %d (%s) in %s line %d", + ftype, + interaction_function[ftype].name, + __FILE__, + __LINE__); } } @@ -2667,10 +2671,16 @@ static void do_tpxheader(gmx::FileIOXdrSerializer* serializer, gmx_fatal(FARGS, "Unknown precision in file %s: real is %d bytes " "instead of %zu or %zu", - filename, precision, sizeof(float), sizeof(double)); + filename, + precision, + sizeof(float), + sizeof(double)); } gmx_fio_setprecision(fio, tpx->isDouble); - fprintf(stderr, "Reading file %s, %s (%s precision)\n", filename, buf.c_str(), + fprintf(stderr, + "Reading file %s, %s (%s precision)\n", + filename, + buf.c_str(), tpx->isDouble ? "double" : "single"); } else @@ -2721,7 +2731,11 @@ static void do_tpxheader(gmx::FileIOXdrSerializer* serializer, gmx_fatal(FARGS, "tpx tag/version mismatch: reading tpx file (%s) version %d, tag '%s' " "with program for tpx version %d, tag '%s'", - filename, tpx->fileVersion, fileTag.c_str(), tpx_version, tpx_tag); + filename, + tpx->fileVersion, + fileTag.c_str(), + tpx_version, + tpx_tag); } } } @@ -2730,8 +2744,11 @@ static void do_tpxheader(gmx::FileIOXdrSerializer* serializer, || ((tpx->fileVersion > tpx_version) && !TopOnlyOK) || (tpx->fileGeneration > tpx_generation) || tpx_version == 80) /*80 was used by both 5.0-dev and 4.6-dev*/ { - gmx_fatal(FARGS, "reading tpx file (%s) version %d with version %d program", filename, - tpx->fileVersion, tpx_version); + gmx_fatal(FARGS, + "reading tpx file (%s) version %d with version %d program", + filename, + tpx->fileVersion, + tpx_version); } serializer->doInt(&tpx->natoms); @@ -3267,8 +3284,13 @@ void write_tpx_state(const char* fn, const t_inputrec* ir, const t_state* state, // TPR file for now - and thus we ask the serializer to swap if this host is little endian. gmx::InMemorySerializer tprBodySerializer(gmx::EndianSwapBehavior::SwapIfHostIsLittleEndian); - do_tpx_body(&tprBodySerializer, &tpx, const_cast(ir), const_cast(state), - nullptr, nullptr, const_cast(mtop)); + do_tpx_body(&tprBodySerializer, + &tpx, + const_cast(ir), + const_cast(state), + nullptr, + nullptr, + const_cast(mtop)); std::vector tprBody = tprBodySerializer.finishAndGetBuffer(); tpx.sizeOfTprBody = tprBody.size(); diff --git a/src/gromacs/fileio/trrio.cpp b/src/gromacs/fileio/trrio.cpp index e9f227e4ca..e1cdadd30b 100644 --- a/src/gromacs/fileio/trrio.cpp +++ b/src/gromacs/fileio/trrio.cpp @@ -295,8 +295,16 @@ void gmx_trr_write_single_frame(const char* fn, const rvec* f) { t_fileio* fio = gmx_trr_open(fn, "w"); - do_trr_frame(fio, false, &step, &t, &lambda, const_cast(box), &natoms, - const_cast(x), const_cast(v), const_cast(f)); + do_trr_frame(fio, + false, + &step, + &t, + &lambda, + const_cast(box), + &natoms, + const_cast(x), + const_cast(v), + const_cast(f)); gmx_trr_close(fio); } @@ -325,8 +333,16 @@ void gmx_trr_write_frame(t_fileio* fio, const rvec* v, const rvec* f) { - if (!do_trr_frame(fio, false, &step, &t, &lambda, const_cast(box), &natoms, - const_cast(x), const_cast(v), const_cast(f))) + if (!do_trr_frame(fio, + false, + &step, + &t, + &lambda, + const_cast(box), + &natoms, + const_cast(x), + const_cast(v), + const_cast(f))) { gmx_file("Cannot write trajectory frame; maybe you are out of disk space?"); } diff --git a/src/gromacs/fileio/trxio.cpp b/src/gromacs/fileio/trxio.cpp index 2f20e18c5f..697fbb0727 100644 --- a/src/gromacs/fileio/trxio.cpp +++ b/src/gromacs/fileio/trxio.cpp @@ -141,8 +141,14 @@ int check_times2(real t, real t0, gmx_bool bDouble) } if (debug) { - fprintf(debug, "t=%g, t0=%g, b=%g, e=%g, dt=%g: r=%d\n", t, t0, rTimeValue(TBEGIN), - rTimeValue(TEND), rTimeValue(TDELTA), r); + fprintf(debug, + "t=%g, t0=%g, b=%g, e=%g, dt=%g: r=%d\n", + t, + t0, + rTimeValue(TBEGIN), + rTimeValue(TEND), + rTimeValue(TDELTA), + r); } return r; } @@ -242,8 +248,8 @@ float trx_get_time_of_final_frame(t_trxstatus* status) if (filetype == efXTC) { - lasttime = xdr_xtc_get_last_frame_time(gmx_fio_getfp(stfio), gmx_fio_getxdr(stfio), - status->natoms, &bOK); + lasttime = xdr_xtc_get_last_frame_time( + gmx_fio_getfp(stfio), gmx_fio_getxdr(stfio), status->natoms, &bOK); if (!bOK) { gmx_fatal(FARGS, "Error reading last frame. Maybe seek not supported."); @@ -391,8 +397,8 @@ int write_trxframe_indexed(t_trxstatus* status, const t_trxframe* fr, int nind, case efTNG: gmx_write_tng_from_trxframe(status->tng, fr, nind); break; case efXTC: write_xtc(status->fio, nind, fr->step, fr->time, fr->box, xout, prec); break; case efTRR: - gmx_trr_write_frame(status->fio, nframes_read(status), fr->time, fr->step, fr->box, - nind, xout, vout, fout); + gmx_trr_write_frame( + status->fio, nframes_read(status), fr->time, fr->step, fr->box, nind, xout, vout, fout); break; case efGRO: case efPDB: @@ -405,13 +411,29 @@ int write_trxframe_indexed(t_trxstatus* status, const t_trxframe* fr, int nind, sprintf(title, "frame t= %.3f", fr->time); if (ftp == efGRO) { - write_hconf_indexed_p(gmx_fio_getfp(status->fio), title, fr->atoms, nind, ind, - fr->x, fr->bV ? fr->v : nullptr, fr->box); + write_hconf_indexed_p(gmx_fio_getfp(status->fio), + title, + fr->atoms, + nind, + ind, + fr->x, + fr->bV ? fr->v : nullptr, + fr->box); } else { - write_pdbfile_indexed(gmx_fio_getfp(status->fio), title, fr->atoms, fr->x, - PbcType::Unset, fr->box, ' ', fr->step, nind, ind, gc, FALSE); + write_pdbfile_indexed(gmx_fio_getfp(status->fio), + title, + fr->atoms, + fr->x, + PbcType::Unset, + fr->box, + ' ', + fr->step, + nind, + ind, + gc, + FALSE); } break; case efG96: @@ -461,23 +483,23 @@ t_trxstatus* trjtools_gmx_prepare_tng_writing(const char* filename, if (in != nullptr) { - gmx_prepare_tng_writing(filename, filemode, &in->tng, &out->tng, natoms, mtop, index, - index_group_name); + gmx_prepare_tng_writing( + filename, filemode, &in->tng, &out->tng, natoms, mtop, index, index_group_name); } else if ((infile) && (efTNG == fn2ftp(infile))) { gmx_tng_trajectory_t tng_in; gmx_tng_open(infile, 'r', &tng_in); - gmx_prepare_tng_writing(filename, filemode, &tng_in, &out->tng, natoms, mtop, index, - index_group_name); + gmx_prepare_tng_writing( + filename, filemode, &tng_in, &out->tng, natoms, mtop, index, index_group_name); } else { // we start from a file that is not a tng file or have been unable to load the // input file, so we need to populate the fields independently of it - gmx_prepare_tng_writing(filename, filemode, nullptr, &out->tng, natoms, mtop, index, - index_group_name); + gmx_prepare_tng_writing( + filename, filemode, nullptr, &out->tng, natoms, mtop, index, index_group_name); } return out; } @@ -516,7 +538,8 @@ int write_trxframe(t_trxstatus* status, t_trxframe* fr, gmx_conect gc) default: if (!fr->bX) { - gmx_fatal(FARGS, "Need coordinates to write a %s trajectory", + gmx_fatal(FARGS, + "Need coordinates to write a %s trajectory", ftp2ext(gmx_fio_getftp(status->fio))); } break; @@ -528,8 +551,14 @@ int write_trxframe(t_trxstatus* status, t_trxframe* fr, gmx_conect gc) write_xtc(status->fio, fr->natoms, fr->step, fr->time, fr->box, fr->x, prec); break; case efTRR: - gmx_trr_write_frame(status->fio, fr->step, fr->time, fr->lambda, fr->box, fr->natoms, - fr->bX ? fr->x : nullptr, fr->bV ? fr->v : nullptr, + gmx_trr_write_frame(status->fio, + fr->step, + fr->time, + fr->lambda, + fr->box, + fr->natoms, + fr->bX ? fr->x : nullptr, + fr->bV ? fr->v : nullptr, fr->bF ? fr->f : nullptr); break; case efGRO: @@ -538,25 +567,32 @@ int write_trxframe(t_trxstatus* status, t_trxframe* fr, gmx_conect gc) case efENT: if (!fr->bAtoms) { - gmx_fatal(FARGS, "Can not write a %s file without atom names", + gmx_fatal(FARGS, + "Can not write a %s file without atom names", ftp2ext(gmx_fio_getftp(status->fio))); } sprintf(title, "frame t= %.3f", fr->time); if (gmx_fio_getftp(status->fio) == efGRO) { - write_hconf_p(gmx_fio_getfp(status->fio), title, fr->atoms, fr->x, - fr->bV ? fr->v : nullptr, fr->box); + write_hconf_p( + gmx_fio_getfp(status->fio), title, fr->atoms, fr->x, fr->bV ? fr->v : nullptr, fr->box); } else { - write_pdbfile(gmx_fio_getfp(status->fio), title, fr->atoms, fr->x, - fr->bPBC ? fr->pbcType : PbcType::Unset, fr->box, ' ', fr->step, gc); + write_pdbfile(gmx_fio_getfp(status->fio), + title, + fr->atoms, + fr->x, + fr->bPBC ? fr->pbcType : PbcType::Unset, + fr->box, + ' ', + fr->step, + gc); } break; case efG96: write_g96_conf(gmx_fio_getfp(status->fio), title, fr, -1, nullptr); break; default: - gmx_fatal(FARGS, "Sorry, write_trxframe can not write %s", - ftp2ext(gmx_fio_getftp(status->fio))); + gmx_fatal(FARGS, "Sorry, write_trxframe can not write %s", ftp2ext(gmx_fio_getftp(status->fio))); } return 0; @@ -742,8 +778,11 @@ static gmx_bool pdb_next_x(t_trxstatus* status, FILE* fp, t_trxframe* fr) { if (na != fr->natoms) { - gmx_fatal(FARGS, "Number of atoms in pdb frame %d is %d instead of %d", - nframes_read(status), na, fr->natoms); + gmx_fatal(FARGS, + "Number of atoms in pdb frame %d is %d instead of %d", + nframes_read(status), + na, + fr->natoms); } return TRUE; } @@ -799,8 +838,7 @@ bool read_next_frame(const gmx_output_env_t* oenv, t_trxstatus* status, t_trxfra case efG96: { t_symtab* symtab = nullptr; - read_g96_conf(gmx_fio_getfp(status->fio), nullptr, nullptr, fr, symtab, - status->persistent_line); + read_g96_conf(gmx_fio_getfp(status->fio), nullptr, nullptr, fr, symtab, status->persistent_line); bRet = (fr->natoms > 0); break; } @@ -816,8 +854,8 @@ bool read_next_frame(const gmx_output_env_t* oenv, t_trxstatus* status, t_trxfra } initcount(status); } - bRet = (read_next_xtc(status->fio, fr->natoms, &fr->step, &fr->time, fr->box, fr->x, - &fr->prec, &bOK) + bRet = (read_next_xtc( + status->fio, fr->natoms, &fr->step, &fr->time, fr->box, fr->x, &fr->prec, &bOK) != 0); fr->bPrec = (bRet && fr->prec > 0); fr->bStep = bRet; @@ -838,8 +876,10 @@ bool read_next_frame(const gmx_output_env_t* oenv, t_trxstatus* status, t_trxfra #if GMX_USE_PLUGINS bRet = read_next_vmd_frame(status->vmdplugin, fr); #else - gmx_fatal(FARGS, "DEATH HORROR in read_next_frame ftp=%s,status=%s", - ftp2ext(gmx_fio_getftp(status->fio)), gmx_fio_getname(status->fio)); + gmx_fatal(FARGS, + "DEATH HORROR in read_next_frame ftp=%s,status=%s", + ftp2ext(gmx_fio_getftp(status->fio)), + gmx_fio_getname(status->fio)); #endif } status->tf = fr->time; diff --git a/src/gromacs/fileio/vmdio.cpp b/src/gromacs/fileio/vmdio.cpp index 4e21ee5ace..b88ba615f5 100644 --- a/src/gromacs/fileio/vmdio.cpp +++ b/src/gromacs/fileio/vmdio.cpp @@ -2,7 +2,7 @@ * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2009-2018, The GROMACS development team. - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -146,8 +146,7 @@ static int load_sharedlibrary_plugins(const char* fullpath, gmx_vmdplugin_t* vmd { if (debug) { - fprintf(debug, "\nUnable to open dynamic library %s.\n%s\n", fullpath, - vmddlerror()); /*only to debug because of stdc++ erros */ + fprintf(debug, "\nUnable to open dynamic library %s.\n%s\n", fullpath, vmddlerror()); /*only to debug because of stdc++ erros */ } return 0; } diff --git a/src/gromacs/fileio/warninp.cpp b/src/gromacs/fileio/warninp.cpp index f186ff9562..cee3526950 100644 --- a/src/gromacs/fileio/warninp.cpp +++ b/src/gromacs/fileio/warninp.cpp @@ -119,8 +119,7 @@ static void low_warning(warninp_t wi, const char* wtype, int n, const char* s) { if (wi->lineno != -1) { - fprintf(stderr, "\n%s %d [file %s, line %d]:\n%s\n\n", wtype, n, wi->filenm.c_str(), - wi->lineno, temp2); + fprintf(stderr, "\n%s %d [file %s, line %d]:\n%s\n\n", wtype, n, wi->filenm.c_str(), wi->lineno, temp2); } else { @@ -189,8 +188,13 @@ static void print_warn_count(const char* type, int n) print_warn_count("note", wi->nwarn_note); print_warn_count("warning", wi->nwarn_warn); - gmx_fatal(f_errno, file, line, "There %s %d error%s in input file(s)", - (wi->nwarn_error == 1) ? "was" : "were", wi->nwarn_error, (wi->nwarn_error == 1) ? "" : "s"); + gmx_fatal(f_errno, + file, + line, + "There %s %d error%s in input file(s)", + (wi->nwarn_error == 1) ? "was" : "were", + wi->nwarn_error, + (wi->nwarn_error == 1) ? "" : "s"); } void check_warning_error(warninp_t wi, int f_errno, const char* file, int line) @@ -229,7 +233,9 @@ void done_warning(warninp_t wi, int f_errno, const char* file, int line) if (wi->maxwarn >= 0 && wi->nwarn_warn > wi->maxwarn) { - gmx_fatal(f_errno, file, line, + gmx_fatal(f_errno, + file, + line, "Too many warnings (%d).\n" "If you are sure all warnings are harmless, use the -maxwarn option.", wi->nwarn_warn); diff --git a/src/gromacs/fileio/writeps.cpp b/src/gromacs/fileio/writeps.cpp index 808bbaf9cc..2caf643e49 100644 --- a/src/gromacs/fileio/writeps.cpp +++ b/src/gromacs/fileio/writeps.cpp @@ -127,7 +127,12 @@ void ps_init_rgb_nbox(t_psdata* ps, real xbox, real ybox) fprintf(ps->fp, "/by {def currentpoint " "%g y r %g %g r %g y neg r %g %g r f y add moveto} bind def\n", - 0.0, xbox, 0.0, 0.0, -xbox, 0.0); + 0.0, + xbox, + 0.0, + 0.0, + -xbox, + 0.0); /* macro bn is used in ps_rgb_nbox to draw rectangular boxes */ } @@ -155,7 +160,15 @@ void ps_init_rgb_box(t_psdata* ps, real xbox, real ybox) fprintf(ps->fp, "/b {currentpoint " "%g %g r %g %g r %g %g r %g %g r f %g add moveto} bind def\n", - 0.0, ybox, xbox, 0.0, 0.0, -ybox, -xbox, 0.0, ybox); + 0.0, + ybox, + xbox, + 0.0, + 0.0, + -ybox, + -xbox, + 0.0, + ybox); /* macro b is used in search_col to define macro B */ } @@ -225,14 +238,12 @@ void ps_fillarc(t_psdata* ps, real x1, real y1, real rad, real a0, real a1) void ps_arcslice(t_psdata* ps, real xc, real yc, real rad1, real rad2, real a0, real a1) { - fprintf(ps->fp, "newpath %g %g %g %g %g arc %g %g %g %g %g arcn closepath s\n", xc, yc, rad1, - a0, a1, xc, yc, rad2, a1, a0); + fprintf(ps->fp, "newpath %g %g %g %g %g arc %g %g %g %g %g arcn closepath s\n", xc, yc, rad1, a0, a1, xc, yc, rad2, a1, a0); } void ps_fillarcslice(t_psdata* ps, real xc, real yc, real rad1, real rad2, real a0, real a1) { - fprintf(ps->fp, "newpath %g %g %g %g %g arc %g %g %g %g %g arcn closepath f\n", xc, yc, rad1, - a0, a1, xc, yc, rad2, a1, a0); + fprintf(ps->fp, "newpath %g %g %g %g %g arc %g %g %g %g %g arcn closepath f\n", xc, yc, rad1, a0, a1, xc, yc, rad2, a1, a0); } void ps_circle(t_psdata* ps, real x1, real y1, real rad) diff --git a/src/gromacs/fileio/xtcio.cpp b/src/gromacs/fileio/xtcio.cpp index c5ceb8338d..99763a73b5 100644 --- a/src/gromacs/fileio/xtcio.cpp +++ b/src/gromacs/fileio/xtcio.cpp @@ -102,7 +102,9 @@ static int xtc_check(const char* str, gmx_bool bResult, const char* file, int li fprintf(debug, "\nXTC error: read/write of %s failed, " "source file %s, line %d\n", - str, file, line); + str, + file, + line); } return 0; } @@ -221,8 +223,7 @@ int write_xtc(t_fileio* fio, int natoms, int64_t step, real time, const rvec* bo } /* write data */ - bOK = xtc_coord(xd, &natoms, const_cast(box), const_cast(x), &prec, - FALSE); /* bOK will be 1 if writing went well */ + bOK = xtc_coord(xd, &natoms, const_cast(box), const_cast(x), &prec, FALSE); /* bOK will be 1 if writing went well */ if (bOK) { diff --git a/src/gromacs/fileio/xvgr.cpp b/src/gromacs/fileio/xvgr.cpp index 4cc0794db2..b1504c4008 100644 --- a/src/gromacs/fileio/xvgr.cpp +++ b/src/gromacs/fileio/xvgr.cpp @@ -88,7 +88,8 @@ static char* xvgrstr(const std::string& gmx, const gmx_output_env_t* oenv, char* gmx_fatal(FARGS, "Output buffer length in xvgstr (%d) too small to process xvg input string " "'%s'", - buflen, gmx.c_str()); + buflen, + gmx.c_str()); } if (gmx[g] == '\\') { @@ -318,7 +319,10 @@ void xvgr_world(FILE* out, real xmin, real ymin, real xmax, real ymax, const gmx "@ world ymin %g\n" "@ world xmax %g\n" "@ world ymax %g\n", - xmin, ymin, xmax, ymax); + xmin, + ymin, + xmax, + ymax); } } @@ -386,13 +390,14 @@ void xvgr_new_dataset(FILE* out, int nr_first, int nsets, const char** setname, { if (output_env_get_xvg_format(oenv) == XvgFormat::Xmgr) { - fprintf(out, "@ legend string %d \"%s\"\n", i + nr_first, + fprintf(out, + "@ legend string %d \"%s\"\n", + i + nr_first, xvgrstr(setname[i], oenv, buf, STRLEN)); } else { - fprintf(out, "@ s%d legend \"%s\"\n", i + nr_first, - xvgrstr(setname[i], oenv, buf, STRLEN)); + fprintf(out, "@ s%d legend \"%s\"\n", i + nr_first, xvgrstr(setname[i], oenv, buf, STRLEN)); } } } @@ -1001,7 +1006,9 @@ real** read_xvg_time(const char* fn, fprintf(stderr, "Invalid line in %s:\n%s" "Using zeros for the last %d sets\n", - fn, line0, narg - a); + fn, + line0, + narg - a); } n++; } diff --git a/src/gromacs/gmxana/anadih.cpp b/src/gromacs/gmxana/anadih.cpp index 3a3a952f31..e08ccbc075 100644 --- a/src/gromacs/gmxana/anadih.cpp +++ b/src/gromacs/gmxana/anadih.cpp @@ -161,8 +161,8 @@ void ana_dih_trans(const char* fn_trans, multiplicity[k] = 3; } - low_ana_dih_trans(TRUE, fn_trans, TRUE, fn_histo, maxchi, dih, nlist, dlist, nframes, nangles, - grpname, multiplicity, time, bRb, 0.5, oenv); + low_ana_dih_trans( + TRUE, fn_trans, TRUE, fn_histo, maxchi, dih, nlist, dlist, nframes, nangles, grpname, multiplicity, time, bRb, 0.5, oenv); sfree(dlist); sfree(multiplicity); } @@ -575,8 +575,7 @@ void get_chi_product_traj(real** dih, if (bAll) { /* print cuml rotamer vs time */ - print_one(oenv, "chiproduct", dlist[i].name, "chi product for", - "cumulative rotamer", nframes, time, chi_prtrj); + print_one(oenv, "chiproduct", dlist[i].name, "chi product for", "cumulative rotamer", nframes, time, chi_prtrj); } /* make a histogram pf culm. rotamer occupancy too */ @@ -698,13 +697,12 @@ static void calc_angles(struct t_pbc* pbc, int n3, int index[], real ang[], rvec for (i = ix = 0; (ix < n3); i++, ix += 3) { - ang[i] = bond_angle(x_s[index[ix]], x_s[index[ix + 1]], x_s[index[ix + 2]], pbc, r_ij, r_kj, - &costh, &t1, &t2); + ang[i] = bond_angle( + x_s[index[ix]], x_s[index[ix + 1]], x_s[index[ix + 2]], pbc, r_ij, r_kj, &costh, &t1, &t2); } if (debug) { - fprintf(debug, "Angle[0]=%g, costh=%g, index0 = %d, %d, %d\n", ang[0], costh, index[0], - index[1], index[2]); + fprintf(debug, "Angle[0]=%g, costh=%g, index0 = %d, %d, %d\n", ang[0], costh, index[0], index[1], index[2]); pr_rvec(debug, 0, "rij", r_ij, DIM, TRUE); pr_rvec(debug, 0, "rkj", r_kj, DIM, TRUE); } @@ -747,8 +745,19 @@ static void calc_dihs(struct t_pbc* pbc, int n4, const int index[], real ang[], for (i = ix = 0; (ix < n4); i++, ix += 4) { - aaa = dih_angle(x_s[index[ix]], x_s[index[ix + 1]], x_s[index[ix + 2]], x_s[index[ix + 3]], - pbc, r_ij, r_kj, r_kl, m, n, &t1, &t2, &t3); + aaa = dih_angle(x_s[index[ix]], + x_s[index[ix + 1]], + x_s[index[ix + 2]], + x_s[index[ix + 3]], + pbc, + r_ij, + r_kj, + r_kl, + m, + n, + &t1, + &t2, + &t3); ang[i] = aaa; /* not taking into account ryckaert bellemans yet */ } @@ -772,8 +781,7 @@ void make_histo(FILE* log, int ndata, real data[], int npoints, int histo[], rea dx = npoints / (maxx - minx); if (debug) { - fprintf(debug, "Histogramming: ndata=%d, nhisto=%d, minx=%g,maxx=%g,dx=%g\n", ndata, - npoints, minx, maxx, dx); + fprintf(debug, "Histogramming: ndata=%d, nhisto=%d, minx=%g,maxx=%g,dx=%g\n", ndata, npoints, minx, maxx, dx); } for (i = 0; (i < ndata); i++) { diff --git a/src/gromacs/gmxana/dlist.cpp b/src/gromacs/gmxana/dlist.cpp index 908f0fa8ac..f71e69fd2b 100644 --- a/src/gromacs/gmxana/dlist.cpp +++ b/src/gromacs/gmxana/dlist.cpp @@ -246,7 +246,8 @@ t_dlist* mk_dlist(FILE* log, fprintf(debug, "Could not find N atom but could find other atoms" " in residue %s%d\n", - thisres, ires + r0); + thisres, + ires + r0); } } fprintf(stderr, "\n"); @@ -404,29 +405,45 @@ void pr_dlist(FILE* fp, } if (bPhi) { - fprintf(fp, " Phi [%5d,%5d,%5d,%5d]", - (dl[i].atm.H == -1) ? 1 + dl[i].atm.minC : 1 + dl[i].atm.H, 1 + dl[i].atm.N, - 1 + dl[i].atm.Cn[1], 1 + dl[i].atm.C); + fprintf(fp, + " Phi [%5d,%5d,%5d,%5d]", + (dl[i].atm.H == -1) ? 1 + dl[i].atm.minC : 1 + dl[i].atm.H, + 1 + dl[i].atm.N, + 1 + dl[i].atm.Cn[1], + 1 + dl[i].atm.C); pr_props(fp, &dl[i], edPhi, dt); } if (bPsi) { - fprintf(fp, " Psi [%5d,%5d,%5d,%5d]", 1 + dl[i].atm.N, 1 + dl[i].atm.Cn[1], - 1 + dl[i].atm.C, 1 + dl[i].atm.O); + fprintf(fp, + " Psi [%5d,%5d,%5d,%5d]", + 1 + dl[i].atm.N, + 1 + dl[i].atm.Cn[1], + 1 + dl[i].atm.C, + 1 + dl[i].atm.O); pr_props(fp, &dl[i], edPsi, dt); } if (bOmega && has_dihedral(edOmega, &(dl[i]))) { - fprintf(fp, " Omega [%5d,%5d,%5d,%5d]", 1 + dl[i].atm.minCalpha, 1 + dl[i].atm.minC, - 1 + dl[i].atm.N, 1 + dl[i].atm.Cn[1]); + fprintf(fp, + " Omega [%5d,%5d,%5d,%5d]", + 1 + dl[i].atm.minCalpha, + 1 + dl[i].atm.minC, + 1 + dl[i].atm.N, + 1 + dl[i].atm.Cn[1]); pr_props(fp, &dl[i], edOmega, dt); } for (Xi = 0; Xi < MAXCHI; Xi++) { if (bChi && (Xi < maxchi) && (dl[i].atm.Cn[Xi + 3] != -1)) { - fprintf(fp, " Chi%d[%5d,%5d,%5d,%5d]", Xi + 1, 1 + dl[i].atm.Cn[Xi], - 1 + dl[i].atm.Cn[Xi + 1], 1 + dl[i].atm.Cn[Xi + 2], 1 + dl[i].atm.Cn[Xi + 3]); + fprintf(fp, + " Chi%d[%5d,%5d,%5d,%5d]", + Xi + 1, + 1 + dl[i].atm.Cn[Xi], + 1 + dl[i].atm.Cn[Xi + 1], + 1 + dl[i].atm.Cn[Xi + 2], + 1 + dl[i].atm.Cn[Xi + 3]); pr_props(fp, &dl[i], Xi + edChi1, dt); /* Xi+2 was wrong here */ } } diff --git a/src/gromacs/gmxana/eigio.cpp b/src/gromacs/gmxana/eigio.cpp index 4433fb463c..45d1a9075c 100644 --- a/src/gromacs/gmxana/eigio.cpp +++ b/src/gromacs/gmxana/eigio.cpp @@ -84,8 +84,11 @@ void read_eigenvectors(const char* file, *bFit = (head.lambda > -0.5); if (*bFit) { - fprintf(stderr, "Read %smass weighted reference structure with %d atoms from %s\n", - *bDMR ? "" : "non ", *natoms, file); + fprintf(stderr, + "Read %smass weighted reference structure with %d atoms from %s\n", + *bDMR ? "" : "non ", + *natoms, + file); } else { @@ -112,8 +115,11 @@ void read_eigenvectors(const char* file, } else { - fprintf(stderr, "Read %smass weighted average/minimum structure with %d atoms from %s\n", - *bDMA ? "" : "non ", *natoms, file); + fprintf(stderr, + "Read %smass weighted average/minimum structure with %d atoms from %s\n", + *bDMA ? "" : "non ", + *natoms, + file); } snew(x, *natoms); @@ -171,8 +177,12 @@ void write_eigenvectors(const char* trrname, clear_mat(zerobox); snew(x, natoms); - fprintf(stderr, "\nWriting %saverage structure & eigenvectors %d--%d to %s\n", - (WriteXref == eWXR_YES) ? "reference, " : "", begin, end, trrname); + fprintf(stderr, + "\nWriting %saverage structure & eigenvectors %d--%d to %s\n", + (WriteXref == eWXR_YES) ? "reference, " : "", + begin, + end, + trrname); trrout = gmx_trr_open(trrname, "w"); if (WriteXref == eWXR_YES) diff --git a/src/gromacs/gmxana/fitahx.cpp b/src/gromacs/gmxana/fitahx.cpp index f38d2d77f4..82660f232c 100644 --- a/src/gromacs/gmxana/fitahx.cpp +++ b/src/gromacs/gmxana/fitahx.cpp @@ -106,8 +106,15 @@ real fit_ahx(int nres, t_bb bb[], int natoms, int nall, int allindex[], rvec x[] mass[ai] = 10.0; /*#define DEBUG*/ #ifdef DEBUG - fprintf(stderr, "%5d %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n", ai, x[ai][XX], x[ai][YY], - x[ai][ZZ], xref[ai][XX], xref[ai][YY], xref[ai][ZZ]); + fprintf(stderr, + "%5d %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n", + ai, + x[ai][XX], + x[ai][YY], + x[ai][ZZ], + xref[ai][XX], + xref[ai][YY], + xref[ai][ZZ]); #endif phi0 += tw; } diff --git a/src/gromacs/gmxana/gmx_anaeig.cpp b/src/gromacs/gmxana/gmx_anaeig.cpp index 08a5a74194..94c2b4b040 100644 --- a/src/gromacs/gmxana/gmx_anaeig.cpp +++ b/src/gromacs/gmxana/gmx_anaeig.cpp @@ -280,8 +280,10 @@ compare(int natoms, int n1, rvec** eigvec1, int n2, rvec** eigvec2, real* eigval fprintf(stdout, "Trace of the two matrices: %g and %g\n", sum1, sum2); if (neig1 != n || neig2 != n) { - fprintf(stdout, "this is %d%% and %d%% of the total trace\n", - gmx::roundToInt(100 * sum1 / trace1), gmx::roundToInt(100 * sum2 / trace2)); + fprintf(stdout, + "this is %d%% and %d%% of the total trace\n", + gmx::roundToInt(100 * sum1 / trace1), + gmx::roundToInt(100 * sum2 / trace2)); } fprintf(stdout, "Square root of the traces: %g and %g\n", std::sqrt(sum1), std::sqrt(sum2)); @@ -414,8 +416,7 @@ static void inprod_matrix(const char* matfile, rhi.b = 0; nlevels = 41; out = gmx_ffopen(matfile, "w"); - write_xpm(out, 0, "Eigenvector inner-products", "in.prod.", "run 1", "run 2", nx, ny, t_x, t_y, - mat, 0.0, maxval, rlo, rhi, &nlevels); + write_xpm(out, 0, "Eigenvector inner-products", "in.prod.", "run 1", "run 2", nx, ny, t_x, t_y, mat, 0.0, maxval, rlo, rhi, &nlevels); gmx_ffclose(out); } @@ -544,7 +545,8 @@ static void project(const char* trajfile, gmx_fatal(FARGS, "the number of atoms in your trajectory (%d) is larger than the number of " "atoms in your structure file (%d)", - nat, atoms->nr); + nat, + atoms->nr); } snew(all_at, nat); @@ -648,9 +650,21 @@ static void project(const char* trajfile, ylabel[v] = gmx_strdup(str); } sprintf(str, "projection on eigenvectors (%s)", proj_unit); - write_xvgr_graphs(projfile, noutvec, 1, str, nullptr, output_env_get_xvgr_tlabel(oenv), - ylabel, nframes, inprod[noutvec], inprod, nullptr, - output_env_get_time_factor(oenv), FALSE, bSplit, oenv); + write_xvgr_graphs(projfile, + noutvec, + 1, + str, + nullptr, + output_env_get_xvgr_tlabel(oenv), + ylabel, + nframes, + inprod[noutvec], + inprod, + nullptr, + output_env_get_time_factor(oenv), + FALSE, + bSplit, + oenv); } if (twodplotfile) @@ -696,13 +710,20 @@ static void project(const char* trajfile, "You have selected four or more eigenvectors:\n" "fourth eigenvector will be plotted " "in bfactor field of pdb file\n"); - sprintf(str, "4D proj. of traj. on eigenv. %d, %d, %d and %d", eignr[outvec[0]] + 1, - eignr[outvec[1]] + 1, eignr[outvec[2]] + 1, eignr[outvec[3]] + 1); + sprintf(str, + "4D proj. of traj. on eigenv. %d, %d, %d and %d", + eignr[outvec[0]] + 1, + eignr[outvec[1]] + 1, + eignr[outvec[2]] + 1, + eignr[outvec[3]] + 1); } else { - sprintf(str, "3D proj. of traj. on eigenv. %d, %d and %d", eignr[outvec[0]] + 1, - eignr[outvec[1]] + 1, eignr[outvec[2]] + 1); + sprintf(str, + "3D proj. of traj. on eigenv. %d, %d and %d", + eignr[outvec[0]] + 1, + eignr[outvec[1]] + 1, + eignr[outvec[2]] + 1); } init_t_atoms(&atoms, nframes, FALSE); snew(x, nframes); @@ -753,9 +774,21 @@ static void project(const char* trajfile, fprintf(out, "TER\n"); j = 0; } - gmx_fprintf_pdb_atomline(out, epdbATOM, i + 1, "C", ' ', "PRJ", ' ', j + 1, ' ', - 10 * x[i][XX], 10 * x[i][YY], 10 * x[i][ZZ], 1.0, - 10 * b[i], ""); + gmx_fprintf_pdb_atomline(out, + epdbATOM, + i + 1, + "C", + ' ', + "PRJ", + ' ', + j + 1, + ' ', + 10 * x[i][XX], + 10 * x[i][YY], + 10 * x[i][ZZ], + 1.0, + 10 * b[i], + ""); if (j > 0) { fprintf(out, "CONECT%5d%5d\n", i, i + 1); @@ -798,8 +831,7 @@ static void project(const char* trajfile, } pmin[v] = inprod[v][imin]; pmax[v] = inprod[v][imax]; - fprintf(stderr, "%7d %10.6f %10d %10.6f %10d\n", eignr[outvec[v]] + 1, pmin[v], - imin, pmax[v], imax); + fprintf(stderr, "%7d %10.6f %10d %10.6f %10d\n", eignr[outvec[v]] + 1, pmin[v], imin, pmax[v], imax); } } else @@ -895,9 +927,21 @@ static void components(const char* outfile, } } } - write_xvgr_graphs(outfile, noutvec, 4, "Eigenvector components", - "black: total, red: x, green: y, blue: z", "Atom number", ylabel, natoms, x, - nullptr, y, 1, FALSE, FALSE, oenv); + write_xvgr_graphs(outfile, + noutvec, + 4, + "Eigenvector components", + "black: total, red: x, green: y, blue: z", + "Atom number", + ylabel, + natoms, + x, + nullptr, + y, + 1, + FALSE, + FALSE, + oenv); fprintf(stderr, "\n"); } @@ -939,8 +983,10 @@ static void rmsf(const char* outfile, v = outvec[g]; if (eignr[v] >= neig) { - gmx_fatal(FARGS, "Selected vector %d is larger than the number of eigenvalues (%d)", - eignr[v] + 1, neig); + gmx_fatal(FARGS, + "Selected vector %d is larger than the number of eigenvalues (%d)", + eignr[v] + 1, + neig); } sprintf(str, "vec %d", eignr[v] + 1); ylabel[g] = gmx_strdup(str); @@ -950,8 +996,8 @@ static void rmsf(const char* outfile, y[g][i] = std::sqrt(eigval[eignr[v]] * norm2(eigvec[v][i])) / sqrtm[i]; } } - write_xvgr_graphs(outfile, noutvec, 1, "RMS fluctuation (nm) ", nullptr, "Atom number", ylabel, - natoms, x, y, nullptr, 1, TRUE, FALSE, oenv); + write_xvgr_graphs( + outfile, noutvec, 1, "RMS fluctuation (nm) ", nullptr, "Atom number", ylabel, natoms, x, y, nullptr, 1, TRUE, FALSE, oenv); fprintf(stderr, "\n"); } @@ -1109,8 +1155,8 @@ int gmx_anaeig(int argc, char* argv[]) }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT | PCA_CAN_VIEW, NFILE, fnm, - NPA, pa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT | PCA_CAN_VIEW, NFILE, fnm, NPA, pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -1149,15 +1195,18 @@ int gmx_anaeig(int argc, char* argv[]) bCompare = (Vec2File != nullptr) || (Eig2File != nullptr); bPDB3D = fn2ftp(ThreeDPlotFile) == efPDB; - read_eigenvectors(VecFile, &natoms, &bFit1, &xref1, &bDMR1, &xav1, &bDMA1, &nvec1, &eignr1, - &eigvec1, &eigval1); + read_eigenvectors( + VecFile, &natoms, &bFit1, &xref1, &bDMR1, &xav1, &bDMA1, &nvec1, &eignr1, &eigvec1, &eigval1); neig1 = std::min(nvec1, DIM * natoms); if (nvec1 != DIM * natoms) { fprintf(stderr, "Warning: number of eigenvectors %d does not match three times\n" "the number of atoms %d in %s. Using %d eigenvectors.\n\n", - nvec1, natoms, VecFile, neig1); + nvec1, + natoms, + VecFile, + neig1); } /* Overwrite eigenvalues from separate files if the user provides them */ @@ -1168,7 +1217,8 @@ int gmx_anaeig(int argc, char* argv[]) { fprintf(stderr, "Warning: number of eigenvalues in xvg file (%d) does not mtch trr file (%d)\n", - neig1, natoms); + neig1, + natoms); } neig1 = neig_tmp; srenew(eigval1, neig1); @@ -1178,8 +1228,7 @@ int gmx_anaeig(int argc, char* argv[]) eigval1[j] = xvgdata[1][j]; if (debug && (eigval1[j] != tmp)) { - fprintf(debug, "Replacing eigenvalue %d. From trr: %10g, from xvg: %10g\n", j, tmp, - eigval1[j]); + fprintf(debug, "Replacing eigenvalue %d. From trr: %10g, from xvg: %10g\n", j, tmp, eigval1[j]); } } for (j = 0; j < i; j++) @@ -1211,8 +1260,8 @@ int gmx_anaeig(int argc, char* argv[]) gmx_fatal(FARGS, "Need a second eigenvector file to do this analysis."); } int natoms2; - read_eigenvectors(Vec2File, &natoms2, &bFit2, &xref2, &bDMR2, &xav2, &bDMA2, &nvec2, - &eignr2, &eigvec2, &eigval2); + read_eigenvectors( + Vec2File, &natoms2, &bFit2, &xref2, &bDMR2, &xav2, &bDMA2, &nvec2, &eignr2, &eigvec2, &eigval2); neig2 = std::min(nvec2, DIM * natoms2); if (neig2 != neig1) @@ -1301,7 +1350,8 @@ int gmx_anaeig(int argc, char* argv[]) gmx_fatal(FARGS, "you selected a group with %d elements instead of %d, your selection " "does not fit the reference structure in the eigenvector file.", - nfit, natoms); + nfit, + natoms); } for (i = 0; (i < nfit); i++) { @@ -1465,10 +1515,35 @@ int gmx_anaeig(int argc, char* argv[]) if (bProj) { - project(bTraj ? opt2fn("-f", NFILE, fnm) : nullptr, bTop ? &top : nullptr, pbcType, topbox, - ProjOnVecFile, TwoDPlotFile, ThreeDPlotFile, FilterFile, skip, ExtremeFile, - bFirstLastSet, max, nextr, atoms, natoms, index, bFit1, xrefp, nfit, ifit, w_rls, - sqrtm, xav1, eignr1, eigvec1, noutvec, outvec, bSplit, oenv); + project(bTraj ? opt2fn("-f", NFILE, fnm) : nullptr, + bTop ? &top : nullptr, + pbcType, + topbox, + ProjOnVecFile, + TwoDPlotFile, + ThreeDPlotFile, + FilterFile, + skip, + ExtremeFile, + bFirstLastSet, + max, + nextr, + atoms, + natoms, + index, + bFit1, + xrefp, + nfit, + ifit, + w_rls, + sqrtm, + xav1, + eignr1, + eigvec1, + noutvec, + outvec, + bSplit, + oenv); } if (OverlapFile) @@ -1478,8 +1553,8 @@ int gmx_anaeig(int argc, char* argv[]) if (InpMatFile) { - inprod_matrix(InpMatFile, natoms, nvec1, eignr1, eigvec1, nvec2, eignr2, eigvec2, - bFirstLastSet, noutvec, outvec); + inprod_matrix( + InpMatFile, natoms, nvec1, eignr1, eigvec1, nvec2, eignr2, eigvec2, bFirstLastSet, noutvec, outvec); } if (bCompare) diff --git a/src/gromacs/gmxana/gmx_analyze.cpp b/src/gromacs/gmxana/gmx_analyze.cpp index 75888d57fc..4e29049cac 100644 --- a/src/gromacs/gmxana/gmx_analyze.cpp +++ b/src/gromacs/gmxana/gmx_analyze.cpp @@ -337,7 +337,8 @@ static void average(const char* avfile, int avbar_opt, int n, int nset, real** v fprintf(stdout, "Errorbars: discarding %d points on both sides: %d%%" " interval\n", - edge, gmx::roundToInt(100. * (nset - 2 * edge) / nset)); + edge, + gmx::roundToInt(100. * (nset - 2 * edge) / nset)); } else { @@ -575,8 +576,7 @@ static void estimate_error(const char* eefile, * to halfway between tau1_est and the total time (on log scale). */ fitparm[2] = std::sqrt(tau1_est * (n - 1) * dt); - do_lmfit(nbs, ybs, fitsig, 0, tbs, 0, dt * n, oenv, bDebugMode(), effnERREST, - fitparm, 0, nullptr); + do_lmfit(nbs, ybs, fitsig, 0, tbs, 0, dt * n, oenv, bDebugMode(), effnERREST, fitparm, 0, nullptr); } if (bSingleExpFit || fitparm[0] < 0 || fitparm[2] < 0 || fitparm[1] < 0 || (fitparm[1] > 1 && !bAllowNegLTCorr) || fitparm[2] > (n - 1) * dt) @@ -594,8 +594,11 @@ static void estimate_error(const char* eefile, { fprintf(stdout, "a fitted parameter is negative\n"); } - fprintf(stdout, "invalid fit: e.e. %g a %g tau1 %g tau2 %g\n", - optimal_error_estimate(sig[s], fitparm, n * dt), fitparm[1], fitparm[0], + fprintf(stdout, + "invalid fit: e.e. %g a %g tau1 %g tau2 %g\n", + optimal_error_estimate(sig[s], fitparm, n * dt), + fitparm[1], + fitparm[0], fitparm[2]); /* Do a fit with tau2 fixed at the total time. * One could also choose any other large value for tau2. @@ -604,25 +607,26 @@ static void estimate_error(const char* eefile, fitparm[1] = 0.95; fitparm[2] = (n - 1) * dt; fprintf(stdout, "Will fix tau2 at the total time: %g\n", fitparm[2]); - do_lmfit(nbs, ybs, fitsig, 0, tbs, 0, dt * n, oenv, bDebugMode(), effnERREST, - fitparm, 4, nullptr); + do_lmfit(nbs, ybs, fitsig, 0, tbs, 0, dt * n, oenv, bDebugMode(), effnERREST, fitparm, 4, nullptr); } if (bSingleExpFit || fitparm[0] < 0 || fitparm[1] < 0 || (fitparm[1] > 1 && !bAllowNegLTCorr)) { if (!bSingleExpFit) { fprintf(stdout, "a fitted parameter is negative\n"); - fprintf(stdout, "invalid fit: e.e. %g a %g tau1 %g tau2 %g\n", - optimal_error_estimate(sig[s], fitparm, n * dt), fitparm[1], - fitparm[0], fitparm[2]); + fprintf(stdout, + "invalid fit: e.e. %g a %g tau1 %g tau2 %g\n", + optimal_error_estimate(sig[s], fitparm, n * dt), + fitparm[1], + fitparm[0], + fitparm[2]); } /* Do a single exponential fit */ fprintf(stderr, "Will use a single exponential fit for set %d\n", s + 1); fitparm[0] = tau1_est; fitparm[1] = 1.0; fitparm[2] = 0.0; - do_lmfit(nbs, ybs, fitsig, 0, tbs, 0, dt * n, oenv, bDebugMode(), effnERREST, - fitparm, 6, nullptr); + do_lmfit(nbs, ybs, fitsig, 0, tbs, 0, dt * n, oenv, bDebugMode(), effnERREST, fitparm, 6, nullptr); } } ee = optimal_error_estimate(sig[s], fitparm, n * dt); @@ -634,18 +638,22 @@ static void estimate_error(const char* eefile, if (output_env_get_xvg_format(oenv) == XvgFormat::Xmgr) { fprintf(fp, "@ legend string %d \"av %f\"\n", 2 * s, av[s]); - fprintf(fp, "@ legend string %d \"ee %6g\"\n", 2 * s + 1, + fprintf(fp, + "@ legend string %d \"ee %6g\"\n", + 2 * s + 1, optimal_error_estimate(sig[s], fitparm, n * dt)); } else if (output_env_get_xvg_format(oenv) == XvgFormat::Xmgrace) { fprintf(fp, "@ s%d legend \"av %f\"\n", 2 * s, av[s]); - fprintf(fp, "@ s%d legend \"ee %6g\"\n", 2 * s + 1, - optimal_error_estimate(sig[s], fitparm, n * dt)); + fprintf(fp, "@ s%d legend \"ee %6g\"\n", 2 * s + 1, optimal_error_estimate(sig[s], fitparm, n * dt)); } for (i = 0; i < nbs; i++) { - fprintf(fp, "%g %g %g\n", tbs[i], sig[s] * std::sqrt(ybs[i] / (n * dt)), + fprintf(fp, + "%g %g %g\n", + tbs[i], + sig[s] * std::sqrt(ybs[i] / (n * dt)), sig[s] * std::sqrt(fit_function(effnERREST, fitparm, tbs[i]) / (n * dt))); } @@ -668,8 +676,8 @@ static void estimate_error(const char* eefile, fitsig[i] = 1; } } - low_do_autocorr(nullptr, oenv, nullptr, n, 1, -1, &ac, dt, eacNormal, 1, FALSE, TRUE, - FALSE, 0, 0, effnNONE); + low_do_autocorr( + nullptr, oenv, nullptr, n, 1, -1, &ac, dt, eacNormal, 1, FALSE, TRUE, FALSE, 0, 0, effnNONE); fitlen = n / nb_min; @@ -690,17 +698,23 @@ static void estimate_error(const char* eefile, ac_fit[0] = 0.5 * acint; ac_fit[1] = 0.95; ac_fit[2] = 10 * acint; - do_lmfit(n / nb_min, ac, fitsig, dt, nullptr, 0, fitlen * dt, oenv, bDebugMode(), - effnEXPEXP, ac_fit, 0, nullptr); + do_lmfit(n / nb_min, ac, fitsig, dt, nullptr, 0, fitlen * dt, oenv, bDebugMode(), effnEXPEXP, ac_fit, 0, nullptr); ac_fit[3] = 1 - ac_fit[1]; - fprintf(stdout, "Set %3d: ac erest %g a %g tau1 %g tau2 %g\n", s + 1, - optimal_error_estimate(sig[s], ac_fit, n * dt), ac_fit[1], ac_fit[0], ac_fit[2]); + fprintf(stdout, + "Set %3d: ac erest %g a %g tau1 %g tau2 %g\n", + s + 1, + optimal_error_estimate(sig[s], ac_fit, n * dt), + ac_fit[1], + ac_fit[0], + ac_fit[2]); fprintf(fp, "%s\n", output_env_get_print_xvgr_codes(oenv) ? "&" : ""); for (i = 0; i < nbs; i++) { - fprintf(fp, "%g %g\n", tbs[i], + fprintf(fp, + "%g %g\n", + tbs[i], sig[s] * std::sqrt(fit_function(effnERREST, ac_fit, tbs[i])) / (n * dt)); } @@ -1173,8 +1187,8 @@ int gmx_analyze(int argc, char* argv[]) npargs = asize(pa); ppa = add_acf_pargs(&npargs, pa); - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW, NFILE, fnm, npargs, ppa, asize(desc), desc, 0, - nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW, NFILE, fnm, npargs, ppa, asize(desc), desc, 0, nullptr, &oenv)) { sfree(ppa); return 0; @@ -1195,8 +1209,17 @@ int gmx_analyze(int argc, char* argv[]) fitfile = opt2fn_null("-g", NFILE, fnm); } - val = read_xvg_time(opt2fn("-f", NFILE, fnm), bHaveT, opt2parg_bSet("-b", npargs, ppa), tb, - opt2parg_bSet("-e", npargs, ppa), te, nsets_in, &nset, &n, &dt, &t); + val = read_xvg_time(opt2fn("-f", NFILE, fnm), + bHaveT, + opt2parg_bSet("-b", npargs, ppa), + tb, + opt2parg_bSet("-e", npargs, ppa), + te, + nsets_in, + &nset, + &n, + &dt, + &t); printf("Read %d sets of %d points, dt = %g\n\n", nset, n, dt); if (bDer) @@ -1235,8 +1258,8 @@ int gmx_analyze(int argc, char* argv[]) if (fitfile != nullptr) { - print_fitted_function(fitfile, opt2fn_null("-fitted", NFILE, fnm), bXYdy, nset, n, t, val, - npargs, ppa, oenv); + print_fitted_function( + fitfile, opt2fn_null("-fitted", NFILE, fnm), bXYdy, nset, n, t, val, npargs, ppa, oenv); } printf(" std. dev. relative deviation of\n"); @@ -1276,7 +1299,11 @@ int gmx_analyze(int argc, char* argv[]) { error = 0; } - printf("SS%d %13.6e %12.6e %12.6e %6.3f %6.3f\n", s + 1, av[s], sig[s], error, + printf("SS%d %13.6e %12.6e %12.6e %6.3f %6.3f\n", + s + 1, + av[s], + sig[s], + error, sig[s] != 0.0 ? cum3 / (sig[s] * sig[s] * sig[s] * std::sqrt(8 / M_PI)) : 0, sig[s] != 0.0 ? cum4 / (sig[s] * sig[s] * sig[s] * sig[s] * 3) - 1 : 0); } diff --git a/src/gromacs/gmxana/gmx_angle.cpp b/src/gromacs/gmxana/gmx_angle.cpp index 70f006512a..4fe720ba9d 100644 --- a/src/gromacs/gmxana/gmx_angle.cpp +++ b/src/gromacs/gmxana/gmx_angle.cpp @@ -192,8 +192,8 @@ int gmx_g_angle(int argc, char* argv[]) npargs = asize(pa); ppa = add_acf_pargs(&npargs, pa); - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, npargs, ppa, - asize(desc), desc, asize(bugs), bugs, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, npargs, ppa, asize(desc), desc, asize(bugs), bugs, &oenv)) { sfree(ppa); return 0; @@ -240,7 +240,8 @@ int gmx_g_angle(int argc, char* argv[]) gmx_fatal(FARGS, "number of index elements not multiple of %d, " "these can not be %s\n", - mult, (mult == 3) ? "angle triplets" : "dihedral quadruplets"); + mult, + (mult == 3) ? "angle triplets" : "dihedral quadruplets"); } @@ -287,9 +288,21 @@ int gmx_g_angle(int argc, char* argv[]) snew(angstat, maxangstat); - read_ang_dih(ftp2fn(efTRX, NFILE, fnm), (mult == 3), - bALL || bCorr || bTrans || opt2bSet("-or", NFILE, fnm), bRb, bPBC, maxangstat, - angstat, &nframes, &time, isize, index, &trans_frac, &aver_angle, dih, oenv); + read_ang_dih(ftp2fn(efTRX, NFILE, fnm), + (mult == 3), + bALL || bCorr || bTrans || opt2bSet("-or", NFILE, fnm), + bRb, + bPBC, + maxangstat, + angstat, + &nframes, + &time, + isize, + index, + &trans_frac, + &aver_angle, + dih, + oenv); dt = (time[nframes - 1] - time[0]) / (nframes - 1); @@ -343,8 +356,8 @@ int gmx_g_angle(int argc, char* argv[]) if (bTrans) { - ana_dih_trans(opt2fn("-ot", NFILE, fnm), opt2fn("-oh", NFILE, fnm), dih, nframes, nangles, - grpname, time, bRb, oenv); + ana_dih_trans( + opt2fn("-ot", NFILE, fnm), opt2fn("-oh", NFILE, fnm), dih, nframes, nangles, grpname, time, bRb, oenv); } if (bCorr) @@ -394,8 +407,15 @@ int gmx_g_angle(int argc, char* argv[]) { mode = eacCos; } - do_autocorr(opt2fn("-oc", NFILE, fnm), oenv, "Dihedral Autocorrelation Function", - nframes, nangles, dih, dt, mode, bAverCorr); + do_autocorr(opt2fn("-oc", NFILE, fnm), + oenv, + "Dihedral Autocorrelation Function", + nframes, + nangles, + dih, + dt, + mode, + bAverCorr); } } diff --git a/src/gromacs/gmxana/gmx_awh.cpp b/src/gromacs/gmxana/gmx_awh.cpp index f68beb07e9..00b0b9a542 100644 --- a/src/gromacs/gmxana/gmx_awh.cpp +++ b/src/gromacs/gmxana/gmx_awh.cpp @@ -250,10 +250,12 @@ std::vector makeLegend(const AwhBiasParams* awhBiasParams, OutputFileType outputFileType, size_t numLegend) { - const std::array legendBase = { - { "PMF", "Coord bias", "Coord distr", "Ref value distr", "Target ref value distr", - "Friction metric" } - }; + const std::array legendBase = { { "PMF", + "Coord bias", + "Coord distr", + "Ref value distr", + "Target ref value distr", + "Friction metric" } }; std::vector legend; /* Give legends to dimensions higher than the first */ @@ -344,8 +346,8 @@ void OutputFile::initializeAwhOutputFile(int subblockStart, yLabel_ = useKTForEnergy_ ? "(k\\sB\\NT)" : "(kJ/mol)"; if (graphSelection == AwhGraphSelection::All) { - yLabel_ += gmx::formatString(", (nm\\S-%d\\N or rad\\S-%d\\N), (-)", awhBiasParams->ndim, - awhBiasParams->ndim); + yLabel_ += gmx::formatString( + ", (nm\\S-%d\\N or rad\\S-%d\\N), (-)", awhBiasParams->ndim, awhBiasParams->ndim); } } @@ -420,8 +422,8 @@ AwhReader::AwhReader(const AwhParams* awhParams, std::unique_ptr awhOutputFile(new OutputFile( opt2fn("-o", numFileOptions, filenames), "AWH", awhParams->numBias, k)); - awhOutputFile->initializeAwhOutputFile(subblockStart, numSubBlocks, awhBiasParams, - awhGraphSelection, energyUnit, kT); + awhOutputFile->initializeAwhOutputFile( + subblockStart, numSubBlocks, awhBiasParams, awhGraphSelection, energyUnit, kT); std::unique_ptr frictionOutputFile; if (outputFriction) @@ -429,12 +431,12 @@ AwhReader::AwhReader(const AwhParams* awhParams, frictionOutputFile = std::make_unique( opt2fn("-fric", numFileOptions, filenames), "Friction tensor", awhParams->numBias, k); - frictionOutputFile->initializeFrictionOutputFile(subblockStart, numSubBlocks, - awhBiasParams, energyUnit, kT); + frictionOutputFile->initializeFrictionOutputFile( + subblockStart, numSubBlocks, awhBiasParams, energyUnit, kT); } - biasOutputSetups_.emplace_back(BiasOutputSetup(subblockStart, std::move(awhOutputFile), - std::move(frictionOutputFile))); + biasOutputSetups_.emplace_back(BiasOutputSetup( + subblockStart, std::move(awhOutputFile), std::move(frictionOutputFile))); subblockStart += numSubBlocks; } @@ -487,8 +489,10 @@ void AwhReader::processAwhFrame(const t_enxblock& block, double time, const gmx_ FILE* fpAwh = awhOutputFile.openBiasOutputFile(time, oenv); /* Now do the actual printing. Metadata in first subblock is treated separately. */ - fprintf(fpAwh, "# AWH metadata: target error = %.2f kT = %.2f kJ/mol\n", - block.sub[subStart].fval[1], block.sub[subStart].fval[1] * kT_); + fprintf(fpAwh, + "# AWH metadata: target error = %.2f kT = %.2f kJ/mol\n", + block.sub[subStart].fval[1], + block.sub[subStart].fval[1] * kT_); fprintf(fpAwh, "# AWH metadata: log sample weight = %4.2f\n", block.sub[subStart].fval[2]); @@ -548,8 +552,18 @@ int gmx_awh(int argc, char* argv[]) { efXVG, "-o", "awh", ffWRITE }, { efXVG, "-fric", "friction", ffOPTWR } }; const int nfile = asize(fnm); - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_BEGIN | PCA_CAN_END, nfile, fnm, - asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args(&argc, + argv, + PCA_CAN_VIEW | PCA_CAN_BEGIN | PCA_CAN_END, + nfile, + fnm, + asize(pa), + pa, + asize(desc), + desc, + 0, + nullptr, + &oenv)) { return 0; } @@ -616,8 +630,8 @@ int gmx_awh(int argc, char* argv[]) AwhGraphSelection awhGraphSelection = (moreGraphs ? AwhGraphSelection::All : AwhGraphSelection::Pmf); EnergyUnit energyUnit = (kTUnit ? EnergyUnit::KT : EnergyUnit::KJPerMol); - awhReader = std::make_unique(ir.awhParams, nfile, fnm, awhGraphSelection, - energyUnit, BOLTZ * ir.opts.ref_t[0], block); + awhReader = std::make_unique( + ir.awhParams, nfile, fnm, awhGraphSelection, energyUnit, BOLTZ * ir.opts.ref_t[0], block); } awhReader->processAwhFrame(*block, frame->t, oenv); diff --git a/src/gromacs/gmxana/gmx_bar.cpp b/src/gromacs/gmxana/gmx_bar.cpp index 04c9dda231..97b0e2c36d 100644 --- a/src/gromacs/gmxana/gmx_bar.cpp +++ b/src/gromacs/gmxana/gmx_bar.cpp @@ -745,18 +745,24 @@ static void sample_coll_insert_sample(sample_coll_t* sc, samples_t* s, sample_ra GMX_ASSERT(sc->next->s, "Next not properly initialized!"); if (sc->temp != s->temp) { - gmx_fatal(FARGS, "Temperatures in files %s and %s are not the same!", s->filename, + gmx_fatal(FARGS, + "Temperatures in files %s and %s are not the same!", + s->filename, sc->next->s[0]->filename); } if (!lambda_vec_same(sc->native_lambda, s->native_lambda)) { - gmx_fatal(FARGS, "Native lambda in files %s and %s are not the same (and they should be)!", - s->filename, sc->next->s[0]->filename); + gmx_fatal(FARGS, + "Native lambda in files %s and %s are not the same (and they should be)!", + s->filename, + sc->next->s[0]->filename); } if (!lambda_vec_same(sc->foreign_lambda, s->foreign_lambda)) { - gmx_fatal(FARGS, "Foreign lambda in files %s and %s are not the same (and they should be)!", - s->filename, sc->next->s[0]->filename); + gmx_fatal(FARGS, + "Foreign lambda in files %s and %s are not the same (and they should be)!", + s->filename, + sc->next->s[0]->filename); } /* check if there's room */ @@ -1153,7 +1159,8 @@ static barres_t* barres_list_create(sim_data_t* sd, int* nres, gmx_bool use_dhdl "them.\nAlternatively, use the -extp option if (and only if) the " "Hamiltonian\ndepends linearly on lambda, which is NOT normally the " "case.\n\n%s\n%s\n", - descX, descY); + descX, + descY); } /* normal delta H */ @@ -1165,7 +1172,8 @@ static barres_t* barres_list_create(sim_data_t* sd, int* nres, gmx_bool use_dhdl gmx_fatal(FARGS, "Could not find a set for foreign lambda (state X below)\nin the files for " "main lambda (state Y below)\n\n%s\n%s\n", - descX, descY); + descX, + descY); } if (!sc) { @@ -1175,7 +1183,8 @@ static barres_t* barres_list_create(sim_data_t* sd, int* nres, gmx_bool use_dhdl gmx_fatal(FARGS, "Could not find a set for foreign lambda (state X below)\nin the files for " "main lambda (state Y below)\n\n%s\n%s\n", - descX, descY); + descX, + descY); } br->a = scprev; br->b = sc; @@ -2592,7 +2601,8 @@ static gmx_bool subtitle2lambda(const char* subtitle, xvg_t* ba, const char* fn, if (!lambda_components_check(lc, 0, "", 0)) { gmx_fatal(FARGS, - "lambda vector components in %s don't match those previously read", fn); + "lambda vector components in %s don't match those previously read", + fn); } } else @@ -2758,8 +2768,12 @@ static void read_bar_xvg(const char* fn, real* temp, sim_data_t* sd) snew(s, barsim->nset); for (i = 0; i < barsim->nset; i++) { - samples_init(s + i, &(barsim->native_lambda), &(barsim->lambda[i]), barsim->temp, - lambda_vec_same(&(barsim->native_lambda), &(barsim->lambda[i])), fn); + samples_init(s + i, + &(barsim->native_lambda), + &(barsim->lambda[i]), + barsim->temp, + lambda_vec_same(&(barsim->native_lambda), &(barsim->lambda[i])), + fn); s[i].du = barsim->y[i]; s[i].ndu = barsim->np[i]; s[i].t = barsim->t; @@ -2770,8 +2784,11 @@ static void read_bar_xvg(const char* fn, real* temp, sim_data_t* sd) char buf[STRLEN]; lambda_vec_print(s[0].native_lambda, buf, FALSE); - printf("%s: %.1f - %.1f; lambda = %s\n dH/dl & foreign lambdas:\n", fn, s[0].t[0], - s[0].t[s[0].ndu - 1], buf); + printf("%s: %.1f - %.1f; lambda = %s\n dH/dl & foreign lambdas:\n", + fn, + s[0].t[0], + s[0].t[s[0].ndu - 1], + buf); for (i = 0; i < barsim->nset; i++) { lambda_vec_print(s[i].foreign_lambda, buf, TRUE); @@ -3086,7 +3103,8 @@ static void read_barsim_edr(const char* fn, real* temp, sim_data_t* sd) if ((*temp != rtemp) && (*temp > 0)) { gmx_fatal(FARGS, - "Temperature in file %s different from earlier files or setting\n", fn); + "Temperature in file %s different from earlier files or setting\n", + fn); } *temp = rtemp; @@ -3189,12 +3207,18 @@ static void read_barsim_edr(const char* fn, real* temp, sim_data_t* sd) gmx_fatal(FARGS, "Native lambda not constant in file %s: started at %f, and becomes %f at " "time %f", - fn, native_lambda->val[0], start_lambda.val[0], start_time); + fn, + native_lambda->val[0], + start_lambda.val[0], + start_time); } /* check the number of samples against the previous number */ if (((nblocks_raw + nblocks_hist) != nsamples) || (nlam != 1)) { - gmx_fatal(FARGS, "Unexpected block count in %s: was %d, now %d\n", fn, nsamples + 1, + gmx_fatal(FARGS, + "Unexpected block count in %s: was %d, now %d\n", + fn, + nsamples + 1, nblocks_raw + nblocks_hist + nlam); } /* check whether last iterations's end time matches with @@ -3226,8 +3250,15 @@ static void read_barsim_edr(const char* fn, real* temp, sim_data_t* sd) if (type == dhbtDH || type == dhbtDHDL) { int ndu; - read_edr_rawdh_block(&(samples_rawdh[k]), &ndu, &(fr->block[i]), start_time, - delta_time, native_lambda, rtemp, &last_t, fn); + read_edr_rawdh_block(&(samples_rawdh[k]), + &ndu, + &(fr->block[i]), + start_time, + delta_time, + native_lambda, + rtemp, + &last_t, + fn); npts[k] += ndu; if (samples_rawdh[k]) { @@ -3244,8 +3275,8 @@ static void read_barsim_edr(const char* fn, real* temp, sim_data_t* sd) int j; int nb = 0; samples_t* s; /* this is where the data will go */ - s = read_edr_hist_block(&nb, &(fr->block[i]), start_time, delta_time, - native_lambda, rtemp, &last_t, fn); + s = read_edr_hist_block( + &nb, &(fr->block[i]), start_time, delta_time, native_lambda, rtemp, &last_t, fn); nhists[k] += nb; if (nb > 0) { @@ -3457,8 +3488,8 @@ int gmx_bar(int argc, char* argv[]) double sum_histrange_err = 0.; /* histogram range error */ double stat_err = 0.; /* statistical error */ - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, - 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -3551,8 +3582,8 @@ int gmx_bar(int argc, char* argv[]) if (opt2bSet("-o", NFILE, fnm)) { sprintf(buf, "%s (%s)", "\\DeltaG", "kT"); - fpb = xvgropen_type(opt2fn("-o", NFILE, fnm), "Free energy differences", "\\lambda", buf, - exvggtXYDY, oenv); + fpb = xvgropen_type( + opt2fn("-o", NFILE, fnm), "Free energy differences", "\\lambda", buf, exvggtXYDY, oenv); } fpi = nullptr; diff --git a/src/gromacs/gmxana/gmx_bundle.cpp b/src/gromacs/gmxana/gmx_bundle.cpp index a55cde5f95..07564ee2d5 100644 --- a/src/gromacs/gmxana/gmx_bundle.cpp +++ b/src/gromacs/gmxana/gmx_bundle.cpp @@ -257,8 +257,8 @@ int gmx_bundle(int argc, char* argv[]) }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -298,31 +298,52 @@ int gmx_bundle(int argc, char* argv[]) snew(bun.dir, n); snew(bun.len, n); - flen = xvgropen(opt2fn("-ol", NFILE, fnm), "Axis lengths", output_env_get_xvgr_tlabel(oenv), - "(nm)", oenv); - fdist = xvgropen(opt2fn("-od", NFILE, fnm), "Distance of axis centers", - output_env_get_xvgr_tlabel(oenv), "(nm)", oenv); - fz = xvgropen(opt2fn("-oz", NFILE, fnm), "Z-shift of axis centers", - output_env_get_xvgr_tlabel(oenv), "(nm)", oenv); - ftilt = xvgropen(opt2fn("-ot", NFILE, fnm), "Axis tilts", output_env_get_xvgr_tlabel(oenv), - "(degrees)", oenv); - ftiltr = xvgropen(opt2fn("-otr", NFILE, fnm), "Radial axis tilts", - output_env_get_xvgr_tlabel(oenv), "(degrees)", oenv); - ftiltl = xvgropen(opt2fn("-otl", NFILE, fnm), "Lateral axis tilts", - output_env_get_xvgr_tlabel(oenv), "(degrees)", oenv); + flen = xvgropen( + opt2fn("-ol", NFILE, fnm), "Axis lengths", output_env_get_xvgr_tlabel(oenv), "(nm)", oenv); + fdist = xvgropen(opt2fn("-od", NFILE, fnm), + "Distance of axis centers", + output_env_get_xvgr_tlabel(oenv), + "(nm)", + oenv); + fz = xvgropen(opt2fn("-oz", NFILE, fnm), + "Z-shift of axis centers", + output_env_get_xvgr_tlabel(oenv), + "(nm)", + oenv); + ftilt = xvgropen( + opt2fn("-ot", NFILE, fnm), "Axis tilts", output_env_get_xvgr_tlabel(oenv), "(degrees)", oenv); + ftiltr = xvgropen(opt2fn("-otr", NFILE, fnm), + "Radial axis tilts", + output_env_get_xvgr_tlabel(oenv), + "(degrees)", + oenv); + ftiltl = xvgropen(opt2fn("-otl", NFILE, fnm), + "Lateral axis tilts", + output_env_get_xvgr_tlabel(oenv), + "(degrees)", + oenv); if (bKink) { - fkink = xvgropen(opt2fn("-ok", NFILE, fnm), "Kink angles", output_env_get_xvgr_tlabel(oenv), - "(degrees)", oenv); - fkinkr = xvgropen(opt2fn("-okr", NFILE, fnm), "Radial kink angles", - output_env_get_xvgr_tlabel(oenv), "(degrees)", oenv); + fkink = xvgropen(opt2fn("-ok", NFILE, fnm), + "Kink angles", + output_env_get_xvgr_tlabel(oenv), + "(degrees)", + oenv); + fkinkr = xvgropen(opt2fn("-okr", NFILE, fnm), + "Radial kink angles", + output_env_get_xvgr_tlabel(oenv), + "(degrees)", + oenv); if (output_env_get_print_xvgr_codes(oenv)) { fprintf(fkinkr, "@ subtitle \"+ = ) ( - = ( )\"\n"); } - fkinkl = xvgropen(opt2fn("-okl", NFILE, fnm), "Lateral kink angles", - output_env_get_xvgr_tlabel(oenv), "(degrees)", oenv); + fkinkl = xvgropen(opt2fn("-okl", NFILE, fnm), + "Lateral kink angles", + output_env_get_xvgr_tlabel(oenv), + "(degrees)", + oenv); } if (opt2bSet("-oa", NFILE, fnm)) diff --git a/src/gromacs/gmxana/gmx_chi.cpp b/src/gromacs/gmxana/gmx_chi.cpp index c30d7e641d..429f21a710 100644 --- a/src/gromacs/gmxana/gmx_chi.cpp +++ b/src/gromacs/gmxana/gmx_chi.cpp @@ -596,8 +596,7 @@ static void histogramming(FILE* log, } else if (debug) { - fprintf(debug, "Res. %d has imcomplete occupancy or bfacs > %g\n", - dlist[i].resnr, bfac_max); + fprintf(debug, "Res. %d has imcomplete occupancy or bfacs > %g\n", dlist[i].resnr, bfac_max); } } else @@ -767,8 +766,7 @@ static void histogramming(FILE* log, break; default: sprintf(hisfile, "histo-chi%d%s", Dih - NONCHI + 1, residue_name); - sprintf(title, "\\xc\\f{}\\s%d\\N Distribution for %s", Dih - NONCHI + 1, - residue_name); + sprintf(title, "\\xc\\f{}\\s%d\\N Distribution for %s", Dih - NONCHI + 1, residue_name); } std::strcpy(hhisfile, hisfile); std::strcat(hhisfile, ".xvg"); @@ -987,8 +985,24 @@ static void do_rama(int nf, lo += 180; hi += 180; nlevels = 20; - write_xpm3(fp, 0, "Omega/Ramachandran Plot", "Deg", "Phi", "Psi", NMAT, NMAT, axis, - axis, mat, lo, 180.0, hi, rlo, rmid, rhi, &nlevels); + write_xpm3(fp, + 0, + "Omega/Ramachandran Plot", + "Deg", + "Phi", + "Psi", + NMAT, + NMAT, + axis, + axis, + mat, + lo, + 180.0, + hi, + rlo, + rmid, + rhi, + &nlevels); gmx_ffclose(fp); for (j = 0; (j < NMAT); j++) { @@ -1000,8 +1014,11 @@ static void do_rama(int nf, if ((has_dihedral(edChi1, &(dlist[i]))) && (has_dihedral(edChi2, &(dlist[i])))) { sprintf(fn, "ramaX1X2%s.xvg", dlist[i].name); - fp = rama_file(fn, "\\8c\\4\\s1\\N-\\8c\\4\\s2\\N Ramachandran Plot", - "\\8c\\4\\s1\\N (deg)", "\\8c\\4\\s2\\N (deg)", oenv); + fp = rama_file(fn, + "\\8c\\4\\s1\\N-\\8c\\4\\s2\\N Ramachandran Plot", + "\\8c\\4\\s1\\N (deg)", + "\\8c\\4\\s2\\N (deg)", + oenv); Xi1 = dlist[i].j0[edChi1]; Xi2 = dlist[i].j0[edChi2]; for (j = 0; (j < nf); j++) @@ -1195,8 +1212,20 @@ static void order_params(FILE* log, z0 *= 10.0; /* nm -> angstrom */ for (i = 0; (i < 10); i++) { - gmx_fprintf_pdb_atomline(fp, epdbATOM, atoms->nr + 1 + i, "CA", ' ', "LEG", ' ', - atoms->nres + 1, ' ', x0, y0, z0 + (1.2 * i), 0.0, -0.1 * i, + gmx_fprintf_pdb_atomline(fp, + epdbATOM, + atoms->nr + 1 + i, + "CA", + ' ', + "LEG", + ' ', + atoms->nres + 1, + ' ', + x0, + y0, + z0 + (1.2 * i), + 0.0, + -0.1 * i, ""); } gmx_ffclose(fp); @@ -1435,8 +1464,8 @@ int gmx_chi(int argc, char* argv[]) npargs = asize(pa); ppa = add_acf_pargs(&npargs, pa); - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, npargs, ppa, - asize(desc), desc, asize(bugs), bugs, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, npargs, ppa, asize(desc), desc, asize(bugs), bugs, &oenv)) { sfree(ppa); return 0; @@ -1513,8 +1542,8 @@ int gmx_chi(int argc, char* argv[]) snew(dih, ndih); /* COMPUTE ALL DIHEDRALS! */ - read_ang_dih(ftp2fn(efTRX, NFILE, fnm), FALSE, TRUE, FALSE, bPBC, 1, &idum, &nf, &time, isize, - index, &trans_frac, &aver_angle, dih, oenv); + read_ang_dih( + ftp2fn(efTRX, NFILE, fnm), FALSE, TRUE, FALSE, bPBC, 1, &idum, &nf, &time, isize, index, &trans_frac, &aver_angle, dih, oenv); dt = (time[nf - 1] - time[0]) / (nf - 1); /* might want this for corr or n. transit*/ if (bCorr) @@ -1536,9 +1565,27 @@ int gmx_chi(int argc, char* argv[]) } /* Histogramming & J coupling constants & calc of S2 order params */ - histogramming(log, nbin, &rt, nf, maxchi, dih, nlist, dlist, index, bPhi, bPsi, bOmega, bChi, - bNormHisto, bSSHisto, ftp2fn(efDAT, NFILE, fnm), bfac_max, &atoms, bDo_jc, - opt2fn("-jc", NFILE, fnm), oenv); + histogramming(log, + nbin, + &rt, + nf, + maxchi, + dih, + nlist, + dlist, + index, + bPhi, + bPsi, + bOmega, + bChi, + bNormHisto, + bSSHisto, + ftp2fn(efDAT, NFILE, fnm), + bfac_max, + &atoms, + bDo_jc, + opt2fn("-jc", NFILE, fnm), + oenv); /* transitions * @@ -1567,12 +1614,39 @@ int gmx_chi(int argc, char* argv[]) } - low_ana_dih_trans(bDo_ot, opt2fn("-ot", NFILE, fnm), bDo_oh, opt2fn("-oh", NFILE, fnm), maxchi, dih, - nlist, dlist, nf, nactdih, grpname, multiplicity, time, FALSE, core_frac, oenv); + low_ana_dih_trans(bDo_ot, + opt2fn("-ot", NFILE, fnm), + bDo_oh, + opt2fn("-oh", NFILE, fnm), + maxchi, + dih, + nlist, + dlist, + nf, + nactdih, + grpname, + multiplicity, + time, + FALSE, + core_frac, + oenv); /* Order parameters */ - order_params(log, opt2fn("-o", NFILE, fnm), maxchi, nlist, dlist, ftp2fn_null(efPDB, NFILE, fnm), - bfac_init, &atoms, x, pbcType, box, bPhi, bPsi, bChi, oenv); + order_params(log, + opt2fn("-o", NFILE, fnm), + maxchi, + nlist, + dlist, + ftp2fn_null(efPDB, NFILE, fnm), + bfac_init, + &atoms, + x, + pbcType, + box, + bPhi, + bPsi, + bChi, + oenv); /* Print ramachandran maps! */ if (bRama) @@ -1606,8 +1680,20 @@ int gmx_chi(int argc, char* argv[]) } mk_chi_lookup(chi_lookup, maxchi, nlist, dlist); - get_chi_product_traj(dih, nf, nactdih, maxchi, dlist, time, chi_lookup, multiplicity, FALSE, - bNormHisto, core_frac, bAll, opt2fn("-cp", NFILE, fnm), oenv); + get_chi_product_traj(dih, + nf, + nactdih, + maxchi, + dlist, + time, + chi_lookup, + multiplicity, + FALSE, + bNormHisto, + core_frac, + bAll, + opt2fn("-cp", NFILE, fnm), + oenv); for (i = 0; i < nlist; i++) { @@ -1618,8 +1704,7 @@ int gmx_chi(int argc, char* argv[]) /* Correlation comes last because it messes up the angles */ if (bCorr) { - do_dihcorr(opt2fn("-corr", NFILE, fnm), nf, ndih, dih, dt, nlist, dlist, time, maxchi, bPhi, - bPsi, bChi, bOmega, oenv); + do_dihcorr(opt2fn("-corr", NFILE, fnm), nf, ndih, dih, dt, nlist, dlist, time, maxchi, bPhi, bPsi, bChi, bOmega, oenv); } diff --git a/src/gromacs/gmxana/gmx_cluster.cpp b/src/gromacs/gmxana/gmx_cluster.cpp index 751c62f6d0..c855499dd3 100644 --- a/src/gromacs/gmxana/gmx_cluster.cpp +++ b/src/gromacs/gmxana/gmx_cluster.cpp @@ -243,8 +243,7 @@ static void mc_optimize(FILE* log, nuphill++; } - fprintf(log, "Iter: %d Swapped %4d and %4d (energy: %g prob: %g)\n", i, iswap, jswap, - enext, prob); + fprintf(log, "Iter: %d Swapped %4d and %4d (energy: %g prob: %g)\n", i, iswap, jswap, enext, prob); if (nullptr != fp) { fprintf(fp, "%6d %10g\n", i, enext); @@ -266,7 +265,10 @@ static void mc_optimize(FILE* log, fprintf(log, "Swapped time and frame indices and RMSD to next neighbor:\n"); for (i = 0; (i < m->nn); i++) { - fprintf(log, "%10g %5d %10g\n", time[m->m_ind[i]], m->m_ind[i], + fprintf(log, + "%10g %5d %10g\n", + time[m->m_ind[i]], + m->m_ind[i], (i < m->nn - 1) ? m->mat[m->m_ind[i]][m->m_ind[i + 1]] : 0); } @@ -942,16 +944,33 @@ static void ana_trans(t_clusters* clust, trans[clust->cl[i] - 1][clust->cl[i - 1] - 1])); } } - ffprintf_dd(stderr, log, buf, + ffprintf_dd(stderr, + log, + buf, "Counted %d transitions in total, " "max %d between two specific clusters\n", - ntranst, maxtrans); + ntranst, + maxtrans); if (transfn) { fp = gmx_ffopen(transfn, "w"); i = std::min(maxtrans + 1, 80); - write_xpm(fp, 0, "Cluster Transitions", "# transitions", "from cluster", "to cluster", - clust->ncl, clust->ncl, axis, axis, trans, 0, maxtrans, rlo, rhi, &i); + write_xpm(fp, + 0, + "Cluster Transitions", + "# transitions", + "from cluster", + "to cluster", + clust->ncl, + clust->ncl, + axis, + axis, + trans, + 0, + maxtrans, + rlo, + rhi, + &i); gmx_ffclose(fp); } if (ntransfn) @@ -1026,8 +1045,12 @@ static void analyze_clusters(int nf, trxsfn = parse_filename(trxfn, std::max(write_ncl, clust->ncl)); snew(bWrite, nf); } - ffprintf_ss(stderr, log, buf, "Writing %s structure for each cluster to %s\n", - bAverage ? "average" : "middle", trxfn); + ffprintf_ss(stderr, + log, + buf, + "Writing %s structure for each cluster to %s\n", + bAverage ? "average" : "middle", + trxfn); if (write_ncl) { /* find out what we want to tell the user: @@ -1107,7 +1130,12 @@ static void analyze_clusters(int nf, } snew(structure, nf); - fprintf(log, "\n%3s | %3s %4s | %6s %4s | cluster members\n", "cl.", "#st", "rmsd", "middle", + fprintf(log, + "\n%3s | %3s %4s | %6s %4s | cluster members\n", + "cl.", + "#st", + "rmsd", + "middle", "rmsd"); for (cl = 1; cl <= clust->ncl; cl++) { @@ -1266,8 +1294,16 @@ static void analyze_clusters(int nf, } if (bWrite[i]) { - write_trx(trxsout, iosize, outidx, atoms, i, time[structure[i]], - boxes[structure[i]], xx[structure[i]], nullptr, nullptr); + write_trx(trxsout, + iosize, + outidx, + atoms, + i, + time[structure[i]], + boxes[structure[i]], + xx[structure[i]], + nullptr, + nullptr); } } close_trx(trxsout); @@ -1565,8 +1601,18 @@ int gmx_cluster(int argc, char* argv[]) }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME | PCA_TIME_UNIT, NFILE, fnm, - asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args(&argc, + argv, + PCA_CAN_VIEW | PCA_CAN_TIME | PCA_TIME_UNIT, + NFILE, + fnm, + asize(pa), + pa, + asize(desc), + desc, + 0, + nullptr, + &oenv)) { return 0; } @@ -1586,8 +1632,10 @@ int gmx_cluster(int argc, char* argv[]) } if (bReadMat && output_env_get_time_factor(oenv) != 1) { - fprintf(stderr, "\nWarning: assuming the time unit in %s is %s\n", - opt2fn("-dm", NFILE, fnm), output_env_get_time_unit(oenv).c_str()); + fprintf(stderr, + "\nWarning: assuming the time unit in %s is %s\n", + opt2fn("-dm", NFILE, fnm), + output_env_get_time_unit(oenv).c_str()); } if (trx_out_fn && !bReadTraj) { @@ -1766,7 +1814,9 @@ int gmx_cluster(int argc, char* argv[]) gmx_fatal(FARGS, "Matrix size (%dx%d) does not match the number of " "frames (%d)", - readmat[0].nx, readmat[0].ny, nf); + readmat[0].nx, + readmat[0].ny, + nf); } nf = readmat[0].nx; @@ -1863,7 +1913,9 @@ int gmx_cluster(int argc, char* argv[]) fprintf(stderr, "WARNING: rmsd cutoff %g is outside range of rmsd values " "%g to %g\n", - rmsdcut, rms->minrms, rms->maxrms); + rmsdcut, + rms->minrms, + rms->maxrms); } if (bAnalyze && (rmsmin < rms->minrms)) { @@ -1910,8 +1962,11 @@ int gmx_cluster(int argc, char* argv[]) eigensolver(eigenvectors, nf, 0, nf, eigenvalues, rms->mat[0]); sfree(eigenvectors); - fp = xvgropen(opt2fn("-ev", NFILE, fnm), "RMSD matrix Eigenvalues", "Eigenvector index", - "Eigenvalues (nm\\S2\\N)", oenv); + fp = xvgropen(opt2fn("-ev", NFILE, fnm), + "RMSD matrix Eigenvalues", + "Eigenvector index", + "Eigenvalues (nm\\S2\\N)", + oenv); for (i = 0; (i < nf); i++) { fprintf(fp, "%10d %10g\n", i, eigenvalues[i]); @@ -1957,12 +2012,36 @@ int gmx_cluster(int argc, char* argv[]) copy_rvec(xtps[index[i]], usextps[i]); } useatoms.nr = isize; - analyze_clusters(nf, &clust, rms->mat, isize, &useatoms, usextps, mass, xx, time, boxes, - frameindices, ifsize, fitidx, iosize, outidx, - bReadTraj ? trx_out_fn : nullptr, opt2fn_null("-sz", NFILE, fnm), - opt2fn_null("-tr", NFILE, fnm), opt2fn_null("-ntr", NFILE, fnm), - opt2fn_null("-clid", NFILE, fnm), opt2fn_null("-clndx", NFILE, fnm), - bAverage, write_ncl, write_nst, rmsmin, bFit, log, rlo_bot, rhi_bot, oenv); + analyze_clusters(nf, + &clust, + rms->mat, + isize, + &useatoms, + usextps, + mass, + xx, + time, + boxes, + frameindices, + ifsize, + fitidx, + iosize, + outidx, + bReadTraj ? trx_out_fn : nullptr, + opt2fn_null("-sz", NFILE, fnm), + opt2fn_null("-tr", NFILE, fnm), + opt2fn_null("-ntr", NFILE, fnm), + opt2fn_null("-clid", NFILE, fnm), + opt2fn_null("-clndx", NFILE, fnm), + bAverage, + write_ncl, + write_nst, + rmsmin, + bFit, + log, + rlo_bot, + rhi_bot, + oenv); sfree(boxes); sfree(frameindices); } @@ -1987,9 +2066,22 @@ int gmx_cluster(int argc, char* argv[]) fprintf(stderr, "Writing rms distance/clustering matrix "); if (bReadMat) { - write_xpm(fp, 0, readmat[0].title, readmat[0].legend, readmat[0].label_x, - readmat[0].label_y, nf, nf, readmat[0].axis_x.data(), readmat[0].axis_y.data(), - rms->mat, 0.0, rms->maxrms, rlo_top, rhi_top, &nlevels); + write_xpm(fp, + 0, + readmat[0].title, + readmat[0].legend, + readmat[0].label_x, + readmat[0].label_y, + nf, + nf, + readmat[0].axis_x.data(), + readmat[0].axis_y.data(), + rms->mat, + 0.0, + rms->maxrms, + rlo_top, + rhi_top, + &nlevels); } else { @@ -1997,14 +2089,47 @@ int gmx_cluster(int argc, char* argv[]) auto title = gmx::formatString("RMS%sDeviation / Cluster Index", bRMSdist ? " Distance " : " "); if (minstruct > 1) { - write_xpm_split(fp, 0, title, "RMSD (nm)", timeLabel, timeLabel, nf, nf, time, time, - rms->mat, 0.0, rms->maxrms, &nlevels, rlo_top, rhi_top, 0.0, ncluster, - &ncluster, TRUE, rlo_bot, rhi_bot); + write_xpm_split(fp, + 0, + title, + "RMSD (nm)", + timeLabel, + timeLabel, + nf, + nf, + time, + time, + rms->mat, + 0.0, + rms->maxrms, + &nlevels, + rlo_top, + rhi_top, + 0.0, + ncluster, + &ncluster, + TRUE, + rlo_bot, + rhi_bot); } else { - write_xpm(fp, 0, title, "RMSD (nm)", timeLabel, timeLabel, nf, nf, time, time, rms->mat, - 0.0, rms->maxrms, rlo_top, rhi_top, &nlevels); + write_xpm(fp, + 0, + title, + "RMSD (nm)", + timeLabel, + timeLabel, + nf, + nf, + time, + time, + rms->mat, + 0.0, + rms->maxrms, + rlo_top, + rhi_top, + &nlevels); } } fprintf(stderr, "\n"); @@ -2014,8 +2139,22 @@ int gmx_cluster(int argc, char* argv[]) fp = opt2FILE("-om", NFILE, fnm, "w"); auto timeLabel = output_env_get_time_label(oenv); auto title = gmx::formatString("RMS%sDeviation", bRMSdist ? " Distance " : " "); - write_xpm(fp, 0, title, "RMSD (nm)", timeLabel, timeLabel, nf, nf, time, time, orig->mat, - 0.0, orig->maxrms, rlo_top, rhi_top, &nlevels); + write_xpm(fp, + 0, + title, + "RMSD (nm)", + timeLabel, + timeLabel, + nf, + nf, + time, + time, + orig->mat, + 0.0, + orig->maxrms, + rlo_top, + rhi_top, + &nlevels); gmx_ffclose(fp); done_mat(&orig); sfree(orig); diff --git a/src/gromacs/gmxana/gmx_clustsize.cpp b/src/gromacs/gmxana/gmx_clustsize.cpp index fd64ddf7f9..b98b5b1db9 100644 --- a/src/gromacs/gmxana/gmx_clustsize.cpp +++ b/src/gromacs/gmxana/gmx_clustsize.cpp @@ -266,8 +266,10 @@ static void clust_size(const char* ndx, { if (clust_size[cj] <= 0) { - gmx_fatal(FARGS, "negative cluster size %d for element %d", - clust_size[cj], cj); + gmx_fatal(FARGS, + "negative cluster size %d for element %d", + clust_size[cj], + cj); } clust_size[cj]--; clust_index[k] = ci; @@ -430,8 +432,24 @@ static void clust_size(const char* ndx, fprintf(stderr, "cmid: %g, cmax: %g, max_size: %d\n", cmid, cmax, max_size); cmid = 1; fp = gmx_ffopen(xpm, "w"); - write_xpm3(fp, 0, "Cluster size distribution", "# clusters", timeLabel, "Size", n_x, max_size, - t_x, t_y, cs_dist, 0, cmid, cmax, rlo, rmid, rhi, &nlevels); + write_xpm3(fp, + 0, + "Cluster size distribution", + "# clusters", + timeLabel, + "Size", + n_x, + max_size, + t_x, + t_y, + cs_dist, + 0, + cmid, + cmax, + rlo, + rmid, + rhi, + &nlevels); gmx_ffclose(fp); cmid = 100.0; cmax = 0.0; @@ -449,8 +467,24 @@ static void clust_size(const char* ndx, } fprintf(stderr, "cmid: %g, cmax: %g, max_size: %d\n", cmid, cmax, max_size); fp = gmx_ffopen(xpmw, "w"); - write_xpm3(fp, 0, "Weighted cluster size distribution", "Fraction", timeLabel, "Size", n_x, - max_size, t_x, t_y, cs_dist, 0, cmid, cmax, rlo, rmid, rhi, &nlevels); + write_xpm3(fp, + 0, + "Weighted cluster size distribution", + "Fraction", + timeLabel, + "Size", + n_x, + max_size, + t_x, + t_y, + cs_dist, + 0, + cmid, + cmax, + rlo, + rmid, + rhi, + &nlevels); gmx_ffclose(fp); delete mtop; sfree(t_x); @@ -546,8 +580,8 @@ int gmx_clustsize(int argc, char* argv[]) }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME | PCA_TIME_UNIT, NFILE, fnm, - NPA, pa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME | PCA_TIME_UNIT, NFILE, fnm, NPA, pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -566,10 +600,26 @@ int gmx_clustsize(int argc, char* argv[]) gmx_fatal(FARGS, "You need a tpr file for the -mol option"); } - clust_size(fnNDX, ftp2fn(efTRX, NFILE, fnm), opt2fn("-o", NFILE, fnm), opt2fn("-ow", NFILE, fnm), - opt2fn("-nc", NFILE, fnm), opt2fn("-ac", NFILE, fnm), opt2fn("-mc", NFILE, fnm), - opt2fn("-hc", NFILE, fnm), opt2fn("-temp", NFILE, fnm), opt2fn("-mcn", NFILE, fnm), - bMol, bPBC, fnTPR, cutoff, nskip, nlevels, rgblo, rgbhi, ndf, oenv); + clust_size(fnNDX, + ftp2fn(efTRX, NFILE, fnm), + opt2fn("-o", NFILE, fnm), + opt2fn("-ow", NFILE, fnm), + opt2fn("-nc", NFILE, fnm), + opt2fn("-ac", NFILE, fnm), + opt2fn("-mc", NFILE, fnm), + opt2fn("-hc", NFILE, fnm), + opt2fn("-temp", NFILE, fnm), + opt2fn("-mcn", NFILE, fnm), + bMol, + bPBC, + fnTPR, + cutoff, + nskip, + nlevels, + rgblo, + rgbhi, + ndf, + oenv); output_env_done(oenv); diff --git a/src/gromacs/gmxana/gmx_confrms.cpp b/src/gromacs/gmxana/gmx_confrms.cpp index 213aaf1130..dcd6adba8a 100644 --- a/src/gromacs/gmxana/gmx_confrms.cpp +++ b/src/gromacs/gmxana/gmx_confrms.cpp @@ -280,7 +280,12 @@ static int find_next_match_res(int* rnr1, { if (debug) { - fprintf(debug, "%d.%d.%dX%sX%s", dx, rr1, rr2, *resinfo1[index1[rr1 + 1]].name, + fprintf(debug, + "%d.%d.%dX%sX%s", + dx, + rr1, + rr2, + *resinfo1[index1[rr1 + 1]].name, *resinfo2[index2[rr2 + 1]].name); } dx = 1; @@ -417,8 +422,16 @@ static void find_matching_names(int* isize1, } if (debug) { - fprintf(debug, " -> %s%d-%s%d %s%d-%s%d", *resinfo1[rnr1].name, rnr1, *atnms1[index1[i1]], - index1[i1], *resinfo2[rnr2].name, rnr2, *atnms2[index2[i2]], index2[i2]); + fprintf(debug, + " -> %s%d-%s%d %s%d-%s%d", + *resinfo1[rnr1].name, + rnr1, + *atnms1[index1[i1]], + index1[i1], + *resinfo2[rnr2].name, + rnr2, + *atnms2[index2[i2]], + index2[i2]); } m1 = find_res_end(i1, *isize1, index1, atoms1); m2 = find_res_end(i2, *isize2, index2, atoms2); @@ -550,8 +563,8 @@ int gmx_confrms(int argc, char* argv[]) real* msds; - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, - 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -601,8 +614,12 @@ int gmx_confrms(int argc, char* argv[]) if (matchndxfile) { fp = gmx_ffopen(matchndxfile, "w"); - fprintf(fp, "; Matching atoms between %s from %s and %s from %s\n", groupnames1, - conf1file, groupnames2, conf2file); + fprintf(fp, + "; Matching atoms between %s from %s and %s from %s\n", + groupnames1, + conf1file, + groupnames2, + conf2file); fprintf(fp, "[ Match_%s_%s ]\n", conf1file, groupnames1); for (i = 0; i < isize1; i++) { @@ -630,8 +647,13 @@ int gmx_confrms(int argc, char* argv[]) { if (warn < 20) { - fprintf(stderr, "Warning: atomnames at index %d don't match: %d %s, %d %s\n", i + 1, - index1[i] + 1, name1, index2[i] + 1, name2); + fprintf(stderr, + "Warning: atomnames at index %d don't match: %d %s, %d %s\n", + i + 1, + index1[i] + 1, + name1, + index2[i] + 1, + name2); } warn++; } @@ -814,12 +836,14 @@ int gmx_confrms(int argc, char* argv[]) default: if (bBfac) { - fprintf(stderr, "WARNING: cannot write B-factor values to %s file\n", + fprintf(stderr, + "WARNING: cannot write B-factor values to %s file\n", ftp2ext(fn2ftp(outfile))); } if (!bOne) { - fprintf(stderr, "WARNING: cannot write the reference structure to %s file\n", + fprintf(stderr, + "WARNING: cannot write the reference structure to %s file\n", ftp2ext(fn2ftp(outfile))); } write_sto_conf(outfile, *top2->name, atoms2, x2, v2, pbcType2, box2); diff --git a/src/gromacs/gmxana/gmx_covar.cpp b/src/gromacs/gmxana/gmx_covar.cpp index 559c1f9637..a6a07535ca 100644 --- a/src/gromacs/gmxana/gmx_covar.cpp +++ b/src/gromacs/gmxana/gmx_covar.cpp @@ -188,8 +188,8 @@ int gmx_covar(int argc, char* argv[]) }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -309,7 +309,8 @@ int gmx_covar(int argc, char* argv[]) fprintf(stderr, "\nWARNING: number of atoms in structure file (%d) and trajectory (%d) do not " "match\n", - natoms, nat); + natoms, + nat); } gmx::throwErrorIfIndexOutOfBounds({ ifit, ifit + nfit }, nat, "fitting"); gmx::throwErrorIfIndexOutOfBounds({ index, index + natoms }, nat, "analysis"); @@ -343,11 +344,13 @@ int gmx_covar(int argc, char* argv[]) xread[index[i]][d] = xav[i][d]; } } - write_sto_conf_indexed(opt2fn("-av", NFILE, fnm), "Average structure", atoms, xread, nullptr, - PbcType::No, zerobox, natoms, index); + write_sto_conf_indexed( + opt2fn("-av", NFILE, fnm), "Average structure", atoms, xread, nullptr, PbcType::No, zerobox, natoms, index); sfree(xread); - fprintf(stderr, "Constructing covariance matrix (%dx%d) ...\n", static_cast(ndim), + fprintf(stderr, + "Constructing covariance matrix (%dx%d) ...\n", + static_cast(ndim), static_cast(ndim)); nframes = 0; nat = read_first_x(oenv, &status, trxfile, &t, &xread, box); @@ -457,8 +460,7 @@ int gmx_covar(int argc, char* argv[]) { for (i = 0; i < ndim; i += 3) { - fprintf(out, "%g %g %g\n", mat[ndim * j + i], mat[ndim * j + i + 1], - mat[ndim * j + i + 2]); + fprintf(out, "%g %g %g\n", mat[ndim * j + i], mat[ndim * j + i + 1], mat[ndim * j + i + 2]); } } gmx_ffclose(out); @@ -500,8 +502,24 @@ int gmx_covar(int argc, char* argv[]) rhi.b = 0; out = gmx_ffopen(xpmfile, "w"); nlevels = 80; - write_xpm3(out, 0, "Covariance", bM ? "u nm^2" : "nm^2", "dim", "dim", ndim, ndim, axis, - axis, mat2, min, 0.0, max, rlo, rmi, rhi, &nlevels); + write_xpm3(out, + 0, + "Covariance", + bM ? "u nm^2" : "nm^2", + "dim", + "dim", + ndim, + ndim, + axis, + axis, + mat2, + min, + 0.0, + max, + rlo, + rmi, + rhi, + &nlevels); gmx_ffclose(out); sfree(axis); sfree(mat2); @@ -552,8 +570,24 @@ int gmx_covar(int argc, char* argv[]) rhi.b = 0; out = gmx_ffopen(xpmafile, "w"); nlevels = 80; - write_xpm3(out, 0, "Covariance", bM ? "u nm^2" : "nm^2", "atom", "atom", ndim / DIM, - ndim / DIM, axis, axis, mat2, min, 0.0, max, rlo, rmi, rhi, &nlevels); + write_xpm3(out, + 0, + "Covariance", + bM ? "u nm^2" : "nm^2", + "atom", + "atom", + ndim / DIM, + ndim / DIM, + axis, + axis, + mat2, + min, + 0.0, + max, + rlo, + rmi, + rhi, + &nlevels); gmx_ffclose(out); sfree(axis); for (i = 0; i < ndim / DIM; i++) @@ -595,8 +629,7 @@ int gmx_covar(int argc, char* argv[]) if (nframes - 1 < ndim) { end = nframes - 1; - fprintf(stderr, - "\nWARNING: there are fewer frames in your trajectory than there are\n"); + fprintf(stderr, "\nWARNING: there are fewer frames in your trajectory than there are\n"); fprintf(stderr, "degrees of freedom in your system. Only generating the first\n"); fprintf(stderr, "%d out of %d eigenvectors and eigenvalues.\n", end, static_cast(ndim)); } @@ -638,8 +671,8 @@ int gmx_covar(int argc, char* argv[]) WriteXref = eWXR_NOFIT; } - write_eigenvectors(eigvecfile, natoms, mat, TRUE, 1, end, WriteXref, x, bDiffMass1, xproj, bM, - eigenvalues); + write_eigenvectors( + eigvecfile, natoms, mat, TRUE, 1, end, WriteXref, x, bDiffMass1, xproj, bM, eigenvalues); out = gmx_ffopen(logfile, "w"); @@ -650,8 +683,12 @@ int gmx_covar(int argc, char* argv[]) fprintf(out, "Working directory: %s\n\n", str); - fprintf(out, "Read %d frames from %s (time %g to %g %s)\n", nframes, trxfile, - output_env_conv_time(oenv, tstart), output_env_conv_time(oenv, tend), + fprintf(out, + "Read %d frames from %s (time %g to %g %s)\n", + nframes, + trxfile, + output_env_conv_time(oenv, tstart), + output_env_conv_time(oenv, tend), output_env_get_time_unit(oenv).c_str()); if (bFit) { @@ -677,8 +714,7 @@ int gmx_covar(int argc, char* argv[]) { fprintf(out, "Fit is %smass weighted\n", bDiffMass1 ? "" : "non-"); } - fprintf(out, "Diagonalized the %dx%d covariance matrix\n", static_cast(ndim), - static_cast(ndim)); + fprintf(out, "Diagonalized the %dx%d covariance matrix\n", static_cast(ndim), static_cast(ndim)); fprintf(out, "Trace of the covariance matrix before diagonalizing: %g\n", trace); fprintf(out, "Trace of the covariance matrix after diagonalizing: %g\n\n", sum); diff --git a/src/gromacs/gmxana/gmx_current.cpp b/src/gromacs/gmxana/gmx_current.cpp index 067f46c797..228ddaba0c 100644 --- a/src/gromacs/gmxana/gmx_current.cpp +++ b/src/gromacs/gmxana/gmx_current.cpp @@ -614,10 +614,22 @@ static void dielectric(FILE* fmj, mj2 += iprod(mtrans[nfr], mtrans[nfr]); md2 += iprod(mu[nfr], mu[nfr]); - fprintf(fmj, "%.3f\t%8.5f\t%8.5f\t%8.5f\t%8.5f\t%8.5f\n", time[nfr], mtrans[nfr][XX], - mtrans[nfr][YY], mtrans[nfr][ZZ], mj2 / refr, norm(mja_tmp) / refr); - fprintf(fmd, "%.3f\t%8.5f\t%8.5f\t%8.5f\t%8.5f\t%8.5f\n", time[nfr], mu[nfr][XX], - mu[nfr][YY], mu[nfr][ZZ], md2 / refr, norm(mdvec) / refr); + fprintf(fmj, + "%.3f\t%8.5f\t%8.5f\t%8.5f\t%8.5f\t%8.5f\n", + time[nfr], + mtrans[nfr][XX], + mtrans[nfr][YY], + mtrans[nfr][ZZ], + mj2 / refr, + norm(mja_tmp) / refr); + fprintf(fmd, + "%.3f\t%8.5f\t%8.5f\t%8.5f\t%8.5f\t%8.5f\n", + time[nfr], + mu[nfr][XX], + mu[nfr][YY], + mu[nfr][ZZ], + md2 / refr, + norm(mdvec) / refr); nfr++; @@ -657,9 +669,17 @@ static void dielectric(FILE* fmj, printf("\n\nAverage translational dipole moment M_J [enm] after %d frames (|M|^2): %f %f %f " "(%f)\n", - nfr, mja_tmp[XX], mja_tmp[YY], mja_tmp[ZZ], mj2); + nfr, + mja_tmp[XX], + mja_tmp[YY], + mja_tmp[ZZ], + mj2); printf("\n\nAverage molecular dipole moment M_D [enm] after %d frames (|M|^2): %f %f %f (%f)\n", - nfr, mdvec[XX], mdvec[YY], mdvec[ZZ], md2); + nfr, + mdvec[XX], + mdvec[YY], + mdvec[ZZ], + md2); if (v0 != nullptr) { @@ -716,8 +736,7 @@ static void dielectric(FILE* fmj, dk_f = calceps(prefactor, md2 - mdav2, mj2 - mj, mjd - mjdav, eps_rf, FALSE); fprintf(stderr, "\n\nFluctuations:\n epsilon=%f\n\n", dk_f); - fprintf(stderr, "\n deltaM_D , deltaM_J, deltaM_JD: (%f, %f, %f)\n", md2 - mdav2, mj2 - mj, - mjd - mjdav); + fprintf(stderr, "\n deltaM_D , deltaM_J, deltaM_JD: (%f, %f, %f)\n", md2 - mdav2, mj2 - mj, mjd - mjdav); fprintf(stderr, "\n********************************************\n"); if (bINT) { @@ -734,8 +753,7 @@ static void dielectric(FILE* fmj, if (bACF && (ii < nvfr)) { fprintf(stderr, "Integral and integrated fit to the current acf yields at t=%f:\n", time[vfr[ii]]); - fprintf(stderr, "sigma=%8.3f (pure integral: %.3f)\n", - sgk - malt * std::pow(time[vfr[ii]], sigma), sgk); + fprintf(stderr, "sigma=%8.3f (pure integral: %.3f)\n", sgk - malt * std::pow(time[vfr[ii]], sigma), sgk); } if (ei > bi) @@ -934,8 +952,8 @@ int gmx_current(int argc, char* argv[]) /* At first the arguments will be parsed and the system information processed */ - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -976,41 +994,81 @@ int gmx_current(int argc, char* argv[]) { if (bACF) { - outf = xvgropen(opt2fn("-caf", NFILE, fnm), "Current autocorrelation function", - output_env_get_xvgr_tlabel(oenv), "ACF (e nm/ps)\\S2", oenv); + outf = xvgropen(opt2fn("-caf", NFILE, fnm), + "Current autocorrelation function", + output_env_get_xvgr_tlabel(oenv), + "ACF (e nm/ps)\\S2", + oenv); fprintf(outf, "# time\t acf\t average \t std.dev\n"); } - fcur = xvgropen(opt2fn("-o", NFILE, fnm), "Current", output_env_get_xvgr_tlabel(oenv), - "J(t) (e nm/ps)", oenv); + fcur = xvgropen(opt2fn("-o", NFILE, fnm), + "Current", + output_env_get_xvgr_tlabel(oenv), + "J(t) (e nm/ps)", + oenv); fprintf(fcur, "# time\t Jx\t Jy \t J_z \n"); if (bINT) { mcor = xvgropen(opt2fn("-mc", NFILE, fnm), "M\\sD\\N - current autocorrelation function", output_env_get_xvgr_tlabel(oenv), - "< M\\sD\\N (0)\\c7\\CJ(t) > (e nm/ps)\\S2", oenv); + "< M\\sD\\N (0)\\c7\\CJ(t) > (e nm/ps)\\S2", + oenv); fprintf(mcor, "# time\t M_D(0) J(t) acf \t Integral acf\n"); } } - fmj = xvgropen(opt2fn("-mj", NFILE, fnm), "Averaged translational part of M", - output_env_get_xvgr_tlabel(oenv), "< M\\sJ\\N > (enm)", oenv); + fmj = xvgropen(opt2fn("-mj", NFILE, fnm), + "Averaged translational part of M", + output_env_get_xvgr_tlabel(oenv), + "< M\\sJ\\N > (enm)", + oenv); fprintf(fmj, "# time\t x\t y \t z \t average of M_J^2 \t std.dev\n"); - fmd = xvgropen(opt2fn("-md", NFILE, fnm), "Averaged rotational part of M", - output_env_get_xvgr_tlabel(oenv), "< M\\sD\\N > (enm)", oenv); + fmd = xvgropen(opt2fn("-md", NFILE, fnm), + "Averaged rotational part of M", + output_env_get_xvgr_tlabel(oenv), + "< M\\sD\\N > (enm)", + oenv); fprintf(fmd, "# time\t x\t y \t z \t average of M_D^2 \t std.dev\n"); fmjdsp = xvgropen( - opt2fn("-dsp", NFILE, fnm), "MSD of the squared translational dipole moment M", + opt2fn("-dsp", NFILE, fnm), + "MSD of the squared translational dipole moment M", output_env_get_xvgr_tlabel(oenv), - "<|M\\sJ\\N(t)-M\\sJ\\N(0)|\\S2\\N > / 6.0*V*k\\sB\\N*T / Sm\\S-1\\Nps\\S-1\\N", oenv); + "<|M\\sJ\\N(t)-M\\sJ\\N(0)|\\S2\\N > / 6.0*V*k\\sB\\N*T / Sm\\S-1\\Nps\\S-1\\N", + oenv); /* System information is read and prepared, dielectric() processes the frames * and calculates the requested quantities */ - dielectric(fmj, fmd, outf, fcur, mcor, fmjdsp, bNoJump, bACF, bINT, pbcType, top, fr, temp, bfit, efit, - bvit, evit, status, isize, nmols, nshift, index0, indexm, mass2, qmol, eps_rf, oenv); + dielectric(fmj, + fmd, + outf, + fcur, + mcor, + fmjdsp, + bNoJump, + bACF, + bINT, + pbcType, + top, + fr, + temp, + bfit, + efit, + bvit, + evit, + status, + isize, + nmols, + nshift, + index0, + indexm, + mass2, + qmol, + eps_rf, + oenv); xvgrclose(fmj); xvgrclose(fmd); diff --git a/src/gromacs/gmxana/gmx_density.cpp b/src/gromacs/gmxana/gmx_density.cpp index 1a15db384e..950e69b231 100644 --- a/src/gromacs/gmxana/gmx_density.cpp +++ b/src/gromacs/gmxana/gmx_density.cpp @@ -144,8 +144,11 @@ static void center_coords(t_atoms* atoms, const int* index_center, int ncenter, i = index_center[k]; if (i >= atoms->nr) { - gmx_fatal(FARGS, "Index %d refers to atom %d, which is larger than natoms (%d).", k + 1, - i + 1, atoms->nr); + gmx_fatal(FARGS, + "Index %d refers to atom %d, which is larger than natoms (%d).", + k + 1, + i + 1, + atoms->nr); } mm = atoms->atom[i].m; tmass += mm; @@ -287,12 +290,16 @@ static void calc_electron_density(const char* fn, /* now find the number of electrons. This is not efficient. */ found = static_cast( - bsearch(&sought, eltab, nr, sizeof(t_electron), + bsearch(&sought, + eltab, + nr, + sizeof(t_electron), reinterpret_cast(compare))); if (found == nullptr) { - fprintf(stderr, "Couldn't find %s. Add it to the .dat file\n", + fprintf(stderr, + "Couldn't find %s. Add it to the .dat file\n", *(top->atoms.atomname[index[n][i]])); } else @@ -729,8 +736,8 @@ int gmx_density(int argc, char* argv[]) #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, - asize(desc), desc, asize(bugs), bugs, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, asize(bugs), bugs, &oenv)) { return 0; } @@ -774,18 +781,46 @@ int gmx_density(int argc, char* argv[]) nr_electrons = get_electrons(&el_tab, ftp2fn(efDAT, NFILE, fnm)); fprintf(stderr, "Read %d atomtypes from datafile\n", nr_electrons); - calc_electron_density(ftp2fn(efTRX, NFILE, fnm), index, ngx, &density, &nslices, top, - pbcType, axis, ngrps, &slWidth, el_tab, nr_electrons, bCenter, - index_center, ncenter, bRelative, oenv); + calc_electron_density(ftp2fn(efTRX, NFILE, fnm), + index, + ngx, + &density, + &nslices, + top, + pbcType, + axis, + ngrps, + &slWidth, + el_tab, + nr_electrons, + bCenter, + index_center, + ncenter, + bRelative, + oenv); } else { - calc_density(ftp2fn(efTRX, NFILE, fnm), index, ngx, &density, &nslices, top, pbcType, axis, - ngrps, &slWidth, bCenter, index_center, ncenter, bRelative, oenv, dens_opt); - } - - plot_density(density, opt2fn("-o", NFILE, fnm), nslices, ngrps, grpname, slWidth, dens_opt, - bCenter, bRelative, bSymmetrize, oenv); + calc_density(ftp2fn(efTRX, NFILE, fnm), + index, + ngx, + &density, + &nslices, + top, + pbcType, + axis, + ngrps, + &slWidth, + bCenter, + index_center, + ncenter, + bRelative, + oenv, + dens_opt); + } + + plot_density( + density, opt2fn("-o", NFILE, fnm), nslices, ngrps, grpname, slWidth, dens_opt, bCenter, bRelative, bSymmetrize, oenv); do_view(oenv, opt2fn("-o", NFILE, fnm), "-nxy"); /* view xvgr file */ return 0; diff --git a/src/gromacs/gmxana/gmx_densmap.cpp b/src/gromacs/gmxana/gmx_densmap.cpp index f9c838b2a7..f4d013df6b 100644 --- a/src/gromacs/gmxana/gmx_densmap.cpp +++ b/src/gromacs/gmxana/gmx_densmap.cpp @@ -147,8 +147,8 @@ int gmx_densmap(int argc, char* argv[]) npargs = asize(pa); - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, npargs, pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, npargs, pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -518,9 +518,22 @@ int gmx_densmap(int argc, char* argv[]) else { fp = gmx_ffopen(ftp2fn(efXPM, NFILE, fnm), "w"); - write_xpm(fp, MAT_SPATIAL_X | MAT_SPATIAL_Y, buf, unit, bRadial ? "axial (nm)" : label[c1], - bRadial ? "r (nm)" : label[c2], n1, n2, tickx, tickz, grid, dmin, maxgrid, rlo, - rhi, &nlev); + write_xpm(fp, + MAT_SPATIAL_X | MAT_SPATIAL_Y, + buf, + unit, + bRadial ? "axial (nm)" : label[c1], + bRadial ? "r (nm)" : label[c2], + n1, + n2, + tickx, + tickz, + grid, + dmin, + maxgrid, + rlo, + rhi, + &nlev); gmx_ffclose(fp); } diff --git a/src/gromacs/gmxana/gmx_densorder.cpp b/src/gromacs/gmxana/gmx_densorder.cpp index 0942cda75c..f512024c4d 100644 --- a/src/gromacs/gmxana/gmx_densorder.cpp +++ b/src/gromacs/gmxana/gmx_densorder.cpp @@ -184,8 +184,13 @@ static void density_in_time(const char* fn, *yslices = 1; } } - fprintf(stderr, "\nDividing the box in %5d x %5d x %5d slices with binw %f along axis %d\n", - *xslices, *yslices, *zslices, bw, axis); + fprintf(stderr, + "\nDividing the box in %5d x %5d x %5d slices with binw %f along axis %d\n", + *xslices, + *yslices, + *zslices, + bw, + axis); /****Start trajectory processing***/ @@ -501,8 +506,8 @@ static void interfaces_txy(real**** Densmap, if (debug) { - xvg = xvgropen("DensprofileonZ.xvg", "Averaged Densityprofile on Z", "z[nm]", - "Density[kg/m^3]", oenv); + xvg = xvgropen( + "DensprofileonZ.xvg", "Averaged Densityprofile on Z", "z[nm]", "Density[kg/m^3]", oenv); for (k = 0; k < zslices; k++) { fprintf(xvg, "%4f.3 %8f.4\n", k * binwidth, zDensavg[k]); @@ -513,11 +518,9 @@ static void interfaces_txy(real**** Densmap, /*Fit average density in z over whole trajectory to obtain tentative fit-parameters in fit1 and fit2*/ /*Fit 1st half of box*/ - do_lmfit(zslices, zDensavg, sigma1, binwidth, nullptr, startpoint, splitpoint, oenv, FALSE, - effnERF, beginfit1, 8, nullptr); + do_lmfit(zslices, zDensavg, sigma1, binwidth, nullptr, startpoint, splitpoint, oenv, FALSE, effnERF, beginfit1, 8, nullptr); /*Fit 2nd half of box*/ - do_lmfit(zslices, zDensavg, sigma2, binwidth, nullptr, splitpoint, endpoint, oenv, FALSE, - effnERF, beginfit2, 8, nullptr); + do_lmfit(zslices, zDensavg, sigma2, binwidth, nullptr, splitpoint, endpoint, oenv, FALSE, effnERF, beginfit2, 8, nullptr); /*Initialise the const arrays for storing the average fit parameters*/ avgfit1 = beginfit1; @@ -540,12 +543,34 @@ static void interfaces_txy(real**** Densmap, fit2[k] = avgfit2[k]; } /*Now fit and store in structures in row-major order int[n][i][j]*/ - do_lmfit(zslices, Densmap[n][i][j], sigma1, binwidth, nullptr, startpoint, - splitpoint, oenv, FALSE, effnERF, fit1, 0, nullptr); + do_lmfit(zslices, + Densmap[n][i][j], + sigma1, + binwidth, + nullptr, + startpoint, + splitpoint, + oenv, + FALSE, + effnERF, + fit1, + 0, + nullptr); int1[n][j + (yslices * i)]->Z = fit1[2]; int1[n][j + (yslices * i)]->t = fit1[3]; - do_lmfit(zslices, Densmap[n][i][j], sigma2, binwidth, nullptr, splitpoint, - endpoint, oenv, FALSE, effnERF, fit2, 0, nullptr); + do_lmfit(zslices, + Densmap[n][i][j], + sigma2, + binwidth, + nullptr, + splitpoint, + endpoint, + oenv, + FALSE, + effnERF, + fit2, + 0, + nullptr); int2[n][j + (yslices * i)]->Z = fit2[2]; int2[n][j + (yslices * i)]->t = fit2[3]; } @@ -631,10 +656,8 @@ static void writesurftoxpms(t_interf*** surf1, } } - write_xpm(xpmfile1, 3, numbuf, "Height", "x[nm]", "y[nm]", xbins, ybins, xticks, yticks, - profile1, min1, max1, lo, hi, &maplevels); - write_xpm(xpmfile2, 3, numbuf, "Height", "x[nm]", "y[nm]", xbins, ybins, xticks, yticks, - profile2, min2, max2, lo, hi, &maplevels); + write_xpm(xpmfile1, 3, numbuf, "Height", "x[nm]", "y[nm]", xbins, ybins, xticks, yticks, profile1, min1, max1, lo, hi, &maplevels); + write_xpm(xpmfile2, 3, numbuf, "Height", "x[nm]", "y[nm]", xbins, ybins, xticks, yticks, profile2, min2, max2, lo, hi, &maplevels); } gmx_ffclose(xpmfile1); @@ -679,9 +702,17 @@ static void writeraw(t_interf*** int1, { for (j = 0; j < ybins; j++) { - fprintf(raw1, "%i %i %8.5f %6.4f\n", i, j, (int1[n][j + ybins * i])->Z, + fprintf(raw1, + "%i %i %8.5f %6.4f\n", + i, + j, + (int1[n][j + ybins * i])->Z, (int1[n][j + ybins * i])->t); - fprintf(raw2, "%i %i %8.5f %6.4f\n", i, j, (int2[n][j + ybins * i])->Z, + fprintf(raw2, + "%i %i %8.5f %6.4f\n", + i, + j, + (int2[n][j + ybins * i])->Z, (int2[n][j + ybins * i])->t); } } @@ -765,12 +796,9 @@ int gmx_densorder(int argc, char* argv[]) { efTPR, "-s", nullptr, ffREAD }, /* this is for the topology */ { efTRX, "-f", nullptr, ffREAD }, /* and this for the trajectory */ { efNDX, "-n", nullptr, ffREAD }, /* this is to select groups */ - { efDAT, "-o", "Density4D", - ffOPTWR }, /* This is for outputting the entire 4D densityfield in binary format */ - { efOUT, "-or", nullptr, - ffOPTWRMULT }, /* This is for writing out the entire information in the t_interf arrays */ - { efXPM, "-og", "interface", - ffOPTWRMULT }, /* This is for writing out the interface meshes - one xpm-file per tblock*/ + { efDAT, "-o", "Density4D", ffOPTWR }, /* This is for outputting the entire 4D densityfield in binary format */ + { efOUT, "-or", nullptr, ffOPTWRMULT }, /* This is for writing out the entire information in the t_interf arrays */ + { efXPM, "-og", "interface", ffOPTWRMULT }, /* This is for writing out the interface meshes - one xpm-file per tblock*/ { efOUT, "-Spect", "intfspect", ffOPTWRMULT }, /* This is for the trajectory averaged Fourier-spectra*/ }; @@ -778,8 +806,8 @@ int gmx_densorder(int argc, char* argv[]) /* This is the routine responsible for adding default options, * calling the X/motif interface, etc. */ - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -800,8 +828,23 @@ int gmx_densorder(int argc, char* argv[]) get_index(&top->atoms, ftp2fn_null(efNDX, NFILE, fnm), 1, ngx, index, grpname); - density_in_time(ftp2fn(efTRX, NFILE, fnm), index, ngx, binw, binwz, nsttblock, &Densmap, - &xslices, &yslices, &zslices, &tblock, top, pbcType, axis, bCenter, b1d, oenv); + density_in_time(ftp2fn(efTRX, NFILE, fnm), + index, + ngx, + binw, + binwz, + nsttblock, + &Densmap, + &xslices, + &yslices, + &zslices, + &tblock, + top, + pbcType, + axis, + bCenter, + b1d, + oenv); if (ftorder > 0) { @@ -813,8 +856,8 @@ int gmx_densorder(int argc, char* argv[]) outputfield(opt2fn("-o", NFILE, fnm), Densmap, xslices, yslices, zslices, tblock); } - interfaces_txy(Densmap, xslices, yslices, zslices, tblock, binwz, eMeth, dens1, dens2, &surf1, - &surf2, oenv); + interfaces_txy( + Densmap, xslices, yslices, zslices, tblock, binwz, eMeth, dens1, dens2, &surf1, &surf2, oenv); if (bGraph) { diff --git a/src/gromacs/gmxana/gmx_dielectric.cpp b/src/gromacs/gmxana/gmx_dielectric.cpp index 3ab32fd482..7fff4051b4 100644 --- a/src/gromacs/gmxana/gmx_dielectric.cpp +++ b/src/gromacs/gmxana/gmx_dielectric.cpp @@ -236,7 +236,9 @@ static void do_four(const char* fn, fprintf(fp, "%10.5e %10.5e %10.5e\n", nu, kw.re, kw.im); fprintf(cp, "%10.5e %10.5e\n", kw.re, kw.im); } - printf("MAXEPS = %10.5e at frequency %10.5e GHz (tauD = %8.1f ps)\n", maxeps, numax, + printf("MAXEPS = %10.5e at frequency %10.5e GHz (tauD = %8.1f ps)\n", + maxeps, + numax, 1000 / (2 * M_PI * numax)); xvgrclose(fp); xvgrclose(cp); @@ -319,8 +321,8 @@ int gmx_dielectric(int argc, char* argv[]) { "-nsmooth", FALSE, etINT, { &nsmooth }, "Number of points for smoothing" } }; - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -414,9 +416,13 @@ int gmx_dielectric(int argc, char* argv[]) } printf("DATA INTEGRAL: %5.1f, tauD(old) = %5.1f ps, " "tau_slope = %5.1f, tau_slope,D = %5.1f ps\n", - integral, integral * rffac, fitparms[0], fitparms[0] * rffac); + integral, + integral * rffac, + fitparms[0], + fitparms[0] * rffac); - printf("tau_D from tau1 = %8.3g , eps(Infty) = %8.3f\n", fitparms[0] * (1 + fitparms[1] * lambda), + printf("tau_D from tau1 = %8.3g , eps(Infty) = %8.3f\n", + fitparms[0] * (1 + fitparms[1] * lambda), 1 + ((1 - fitparms[1]) * (eps0 - 1)) / (1 + fitparms[1] * lambda)); fitintegral = numerical_deriv(nx, y[0], y[1], y[3], y[4], y[5], tendInt, nsmooth); diff --git a/src/gromacs/gmxana/gmx_dipoles.cpp b/src/gromacs/gmxana/gmx_dipoles.cpp index 4f5e8f2d00..7e335775a4 100644 --- a/src/gromacs/gmxana/gmx_dipoles.cpp +++ b/src/gromacs/gmxana/gmx_dipoles.cpp @@ -257,8 +257,19 @@ static void do_gkr(t_gkrbin* gb, copy_rvec(xcm[grp1][j], xk); rvec_add(xj, mu[gi], xi); rvec_add(xk, mu[gj], xl); - phi = dih_angle(xi, xj, xk, xl, &pbc, r_ij, r_kj, r_kl, mm, nn, /* out */ - &t1, &t2, &t3); + phi = dih_angle(xi, + xj, + xk, + xl, + &pbc, + r_ij, + r_kj, + r_kl, + mm, + nn, /* out */ + &t1, + &t2, + &t3); cosa = std::cos(phi); } else @@ -271,8 +282,18 @@ static void do_gkr(t_gkrbin* gb, fprintf(debug ? debug : stderr, "mu[%d] = %5.2f %5.2f %5.2f |mi| = %5.2f, mu[%d] = %5.2f %5.2f %5.2f " "|mj| = %5.2f rr = %5.2f cosa = %5.2f\n", - gi, mu[gi][XX], mu[gi][YY], mu[gi][ZZ], norm(mu[gi]), gj, mu[gj][XX], - mu[gj][YY], mu[gj][ZZ], norm(mu[gj]), rr, cosa); + gi, + mu[gi][XX], + mu[gi][YY], + mu[gi][ZZ], + norm(mu[gi]), + gj, + mu[gj][XX], + mu[gj][YY], + mu[gj][ZZ], + norm(mu[gj]), + rr, + cosa); } add2gkr(gb, rr, cosa, phi); @@ -334,8 +355,22 @@ static void print_cmap(const char* cmap, t_gkrbin* gb, int* nlevels) /*2.0*j/(gb->ny-1.0)-1.0;*/ } out = gmx_ffopen(cmap, "w"); - write_xpm(out, 0, "Dipole Orientation Distribution", "Fraction", "r (nm)", gb->bPhi ? "Phi" : "Alpha", - gb->nx, gb->ny, xaxis, yaxis, gb->cmap, 0, hi, rlo, rhi, nlevels); + write_xpm(out, + 0, + "Dipole Orientation Distribution", + "Fraction", + "r (nm)", + gb->bPhi ? "Phi" : "Alpha", + gb->nx, + gb->ny, + xaxis, + yaxis, + gb->cmap, + 0, + hi, + rlo, + rhi, + nlevels); gmx_ffclose(out); sfree(xaxis); sfree(yaxis); @@ -428,7 +463,10 @@ read_mu_from_enx(ener_file_t fmu, int Vol, const ivec iMu, rvec mu, real* vol, r fprintf(stderr, "Something strange: expected %d entries in energy file at step %s\n(time %g) but " "found %d entries\n", - nre, gmx_step_str(fr->step, buf), fr->t, fr->nre); + nre, + gmx_step_str(fr->step, buf), + fr->t, + fr->nre); } if (bCont) @@ -678,8 +716,10 @@ static void dump_slab_dipoles(const char* fn, char buf[STRLEN]; int i; real mutot; - const char* leg_dim[4] = { "\\f{12}m\\f{4}\\sX\\N", "\\f{12}m\\f{4}\\sY\\N", - "\\f{12}m\\f{4}\\sZ\\N", "\\f{12}m\\f{4}\\stot\\N" }; + const char* leg_dim[4] = { "\\f{12}m\\f{4}\\sX\\N", + "\\f{12}m\\f{4}\\sY\\N", + "\\f{12}m\\f{4}\\sZ\\N", + "\\f{12}m\\f{4}\\stot\\N" }; sprintf(buf, "Box-%c (nm)", 'X' + idim); fp = xvgropen(fn, "Average dipole moment per slab", buf, "\\f{12}m\\f{4} (D)", oenv); @@ -687,9 +727,13 @@ static void dump_slab_dipoles(const char* fn, for (i = 0; (i < nslice); i++) { mutot = norm(slab_dipole[i]) / nframes; - fprintf(fp, "%10.3f %10.3f %10.3f %10.3f %10.3f\n", - ((i + 0.5) * box[idim][idim]) / nslice, slab_dipole[i][XX] / nframes, - slab_dipole[i][YY] / nframes, slab_dipole[i][ZZ] / nframes, mutot); + fprintf(fp, + "%10.3f %10.3f %10.3f %10.3f %10.3f\n", + ((i + 0.5) * box[idim][idim]) / nslice, + slab_dipole[i][XX] / nframes, + slab_dipole[i][YY] / nframes, + slab_dipole[i][ZZ] / nframes, + mutot); } xvgrclose(fp); do_view(oenv, fn, "-autoscale xy -nxy"); @@ -768,10 +812,13 @@ static void do_dip(const t_topology* top, #define NLEGMTOT asize(leg_mtot) const char* leg_eps[] = { "epsilon", "G\\sk", "g\\sk" }; #define NLEGEPS asize(leg_eps) - const char* leg_aver[] = { "< |M|\\S2\\N >", "< |M| >\\S2\\N", "< |M|\\S2\\N > - < |M| >\\S2\\N", + const char* leg_aver[] = { "< |M|\\S2\\N >", + "< |M| >\\S2\\N", + "< |M|\\S2\\N > - < |M| >\\S2\\N", "< |M| >\\S2\\N / < |M|\\S2\\N >" }; #define NLEGAVER asize(leg_aver) - const char* leg_cosaver[] = { "\\f{4}<|cos\\f{12}q\\f{4}\\sij\\N|>", "RMSD cos", + const char* leg_cosaver[] = { "\\f{4}<|cos\\f{12}q\\f{4}\\sij\\N|>", + "RMSD cos", "\\f{4}<|cos\\f{12}q\\f{4}\\siX\\N|>", "\\f{4}<|cos\\f{12}q\\f{4}\\siY\\N|>", "\\f{4}<|cos\\f{12}q\\f{4}\\siZ\\N|>" }; @@ -896,8 +943,11 @@ static void do_dip(const t_topology* top, mulsq = gmx_stats_init(); /* Open all the files */ - outmtot = xvgropen(out_mtot, "Total dipole moment of the simulation box vs. time", "Time (ps)", - "Total Dipole Moment (Debye)", oenv); + outmtot = xvgropen(out_mtot, + "Total dipole moment of the simulation box vs. time", + "Time (ps)", + "Total Dipole Moment (Debye)", + oenv); outeps = xvgropen(out_eps, "Epsilon and Kirkwood factors", "Time (ps)", "", oenv); outaver = xvgropen(out_aver, "Total dipole moment", "Time (ps)", "D", oenv); if (bSlab) @@ -930,8 +980,11 @@ static void do_dip(const t_topology* top, } if (cosaver) { - caver = xvgropen(cosaver, bPairs ? "Average pair orientation" : "Average absolute dipole orientation", - "Time (ps)", "", oenv); + caver = xvgropen(cosaver, + bPairs ? "Average pair orientation" : "Average absolute dipole orientation", + "Time (ps)", + "", + oenv); xvgr_legend(caver, NLEGCOSAVER, bPairs ? leg_cosaver : &(leg_cosaver[1]), oenv); } @@ -1171,9 +1224,16 @@ static void do_dip(const t_topology* top, { fprintf(dip3d, "set arrow %d from %f, %f, %f to %f, %f, %f lt %d # %d %d\n", - i + 1, x[ind0][XX], x[ind0][YY], x[ind0][ZZ], - x[ind0][XX] + dipole[i][XX] / 25, x[ind0][YY] + dipole[i][YY] / 25, - x[ind0][ZZ] + dipole[i][ZZ] / 25, ncolour, ind0, i); + i + 1, + x[ind0][XX], + x[ind0][YY], + x[ind0][ZZ], + x[ind0][XX] + dipole[i][XX] / 25, + x[ind0][YY] + dipole[i][YY] / 25, + x[ind0][ZZ] + dipole[i][ZZ] / 25, + ncolour, + ind0, + i); } } } /* End loop of all molecules in frame */ @@ -1202,13 +1262,24 @@ static void do_dip(const t_topology* top, + gmx::square(dipaxis[ZZ] - 0.5)); if (bPairs) { - fprintf(caver, "%10.3e %10.3e %10.3e %10.3e %10.3e %10.3e\n", t, dd, rms_cos, - dipaxis[XX], dipaxis[YY], dipaxis[ZZ]); + fprintf(caver, + "%10.3e %10.3e %10.3e %10.3e %10.3e %10.3e\n", + t, + dd, + rms_cos, + dipaxis[XX], + dipaxis[YY], + dipaxis[ZZ]); } else { - fprintf(caver, "%10.3e %10.3e %10.3e %10.3e %10.3e\n", t, rms_cos, dipaxis[XX], - dipaxis[YY], dipaxis[ZZ]); + fprintf(caver, + "%10.3e %10.3e %10.3e %10.3e %10.3e\n", + t, + rms_cos, + dipaxis[XX], + dipaxis[YY], + dipaxis[ZZ]); } } @@ -1230,7 +1301,12 @@ static void do_dip(const t_topology* top, */ if ((skip == 0) || ((teller % skip) == 0)) { - fprintf(outmtot, "%10g %12.8e %12.8e %12.8e %12.8e\n", t, M_av[XX], M_av[YY], M_av[ZZ], + fprintf(outmtot, + "%10g %12.8e %12.8e %12.8e %12.8e\n", + t, + M_av[XX], + M_av[YY], + M_av[ZZ], std::sqrt(M_av2[XX] + M_av2[YY] + M_av2[ZZ])); } @@ -1270,8 +1346,7 @@ static void do_dip(const t_topology* top, * the two. Here M is sum mu_i. Further write the finite system * Kirkwood G factor and epsilon. */ - fprintf(outaver, "%10g %10.3e %10.3e %10.3e %10.3e\n", t, M2_ave, M_ave2, M_diff, - M_ave2 / M2_ave); + fprintf(outaver, "%10g %10.3e %10.3e %10.3e %10.3e\n", t, M2_ave, M_ave2, M_diff, M_ave2 / M2_ave); if (fnadip) { @@ -1377,13 +1452,20 @@ static void do_dip(const t_topology* top, if (bTotal) { - do_autocorr(corf, oenv, "Autocorrelation Function of Total Dipole", teller, 1, - muall, dt, mode, TRUE); + do_autocorr( + corf, oenv, "Autocorrelation Function of Total Dipole", teller, 1, muall, dt, mode, TRUE); } else { - do_autocorr(corf, oenv, "Dipole Autocorrelation Function", teller, gnx_tot, muall, - dt, mode, std::strcmp(corrtype, "molsep") != 0); + do_autocorr(corf, + oenv, + "Dipole Autocorrelation Function", + teller, + gnx_tot, + muall, + dt, + mode, + std::strcmp(corrtype, "molsep") != 0); } } } @@ -1465,8 +1547,10 @@ static void dipole_atom2molindex(int* n, int* index, const t_block* mols) } if (m == mols->nr) { - gmx_fatal(FARGS, "index[%d]=%d does not correspond to the first atom of a molecule", - i + 1, index[i] + 1); + gmx_fatal(FARGS, + "index[%d]=%d does not correspond to the first atom of a molecule", + i + 1, + index[i] + 1); } for (j = mols->index[m]; j < mols->index[m + 1]; j++) { @@ -1629,8 +1713,8 @@ int gmx_dipoles(int argc, char* argv[]) npargs = asize(pa); ppa = add_acf_pargs(&npargs, pa); - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, npargs, ppa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, npargs, ppa, asize(desc), desc, 0, nullptr, &oenv)) { sfree(ppa); return 0; @@ -1695,13 +1779,44 @@ int gmx_dipoles(int argc, char* argv[]) } nFF[0] = nFA; nFF[1] = nFB; - do_dip(top, pbcType, det(box), ftp2fn(efTRX, NFILE, fnm), opt2fn("-o", NFILE, fnm), - opt2fn("-eps", NFILE, fnm), opt2fn("-a", NFILE, fnm), opt2fn("-d", NFILE, fnm), - opt2fn_null("-cos", NFILE, fnm), opt2fn_null("-dip3d", NFILE, fnm), - opt2fn_null("-adip", NFILE, fnm), bPairs, corrtype[0], opt2fn("-c", NFILE, fnm), bGkr, - opt2fn("-g", NFILE, fnm), bPhi, &nlevels, ndegrees, ncos, opt2fn("-cmap", NFILE, fnm), - rcmax, bQuad, bMU, opt2fn("-en", NFILE, fnm), gnx, grpindex, mu_max, mu_aver, epsilonRF, - temp, nFF, skip, bSlab, nslices, axtitle, opt2fn("-slab", NFILE, fnm), oenv); + do_dip(top, + pbcType, + det(box), + ftp2fn(efTRX, NFILE, fnm), + opt2fn("-o", NFILE, fnm), + opt2fn("-eps", NFILE, fnm), + opt2fn("-a", NFILE, fnm), + opt2fn("-d", NFILE, fnm), + opt2fn_null("-cos", NFILE, fnm), + opt2fn_null("-dip3d", NFILE, fnm), + opt2fn_null("-adip", NFILE, fnm), + bPairs, + corrtype[0], + opt2fn("-c", NFILE, fnm), + bGkr, + opt2fn("-g", NFILE, fnm), + bPhi, + &nlevels, + ndegrees, + ncos, + opt2fn("-cmap", NFILE, fnm), + rcmax, + bQuad, + bMU, + opt2fn("-en", NFILE, fnm), + gnx, + grpindex, + mu_max, + mu_aver, + epsilonRF, + temp, + nFF, + skip, + bSlab, + nslices, + axtitle, + opt2fn("-slab", NFILE, fnm), + oenv); do_view(oenv, opt2fn("-o", NFILE, fnm), "-autoscale xy -nxy"); do_view(oenv, opt2fn("-eps", NFILE, fnm), "-autoscale xy -nxy"); diff --git a/src/gromacs/gmxana/gmx_disre.cpp b/src/gromacs/gmxana/gmx_disre.cpp index 045481ac3e..8b8eade002 100644 --- a/src/gromacs/gmxana/gmx_disre.cpp +++ b/src/gromacs/gmxana/gmx_disre.cpp @@ -198,7 +198,10 @@ static void check_viol(FILE* log, gmx_fatal(FARGS, "Label mismatch in distance restrains. Label for restraint %d is %d, " "expected it to be either %d or %d", - i / nat, label, label_old, label_old + 1); + i / nat, + label, + label_old, + label_old + 1); } } @@ -238,8 +241,7 @@ static void check_viol(FILE* log, dr[clust_id].aver_6[ndr] += disresdata->Rt_6[label]; snew(fshift, SHIFTS); - ta_disres(n, &forceatoms[i], forceparams.data(), x, f, fshift, pbc, lam, &dvdl, nullptr, - &fcd, nullptr); + ta_disres(n, &forceatoms[i], forceparams.data(), x, f, fshift, pbc, lam, &dvdl, nullptr, &fcd, nullptr); sfree(fshift); viol = disresdata->sumviol; @@ -356,9 +358,17 @@ static void dump_viol(FILE* log, int ndr, t_dr_stats* drs, gmx_bool bLinear) { break; } - fprintf(log, "%6d%5s%8.3f%8.3f%8.3f%8.3f%8.3f%8.3f%8.3f\n", drs[i].label, - yesno_names[drs[i].bCore], drs[i].up1, drs[i].r, drs[i].rT3, drs[i].rT6, - drs[i].viol, drs[i].violT3, drs[i].violT6); + fprintf(log, + "%6d%5s%8.3f%8.3f%8.3f%8.3f%8.3f%8.3f%8.3f\n", + drs[i].label, + yesno_names[drs[i].bCore], + drs[i].up1, + drs[i].r, + drs[i].rT3, + drs[i].rT6, + drs[i].viol, + drs[i].violT3, + drs[i].violT6); } } @@ -417,8 +427,9 @@ static void dump_stats(FILE* log, dump_viol(log, dd.nres, drs, FALSE); fprintf(log, "+++ Sorted by linear averaged violations: +++\n"); - std::sort(drs, drs + dd.nres, - [](const t_dr_stats& a, const t_dr_stats& b) { return a.viol > b.viol; }); // Reverse sort + std::sort(drs, drs + dd.nres, [](const t_dr_stats& a, const t_dr_stats& b) { + return a.viol > b.viol; + }); // Reverse sort dump_viol(log, dd.nres, drs, TRUE); dump_dump(log, dd.nres, drs); @@ -457,7 +468,9 @@ static void dump_clust_stats(FILE* fp, gmx_fatal(FARGS, "Inconsistency in cluster %s.\n" "Found %d frames in trajectory rather than the expected %d\n", - clust_name[k], dr[k].nframes, clust->index[k + 1] - clust->index[k]); + clust_name[k], + dr[k].nframes, + clust->index[k + 1] - clust->index[k]); } if (!clust_name[k]) { @@ -505,8 +518,16 @@ static void dump_clust_stats(FILE* fp, { mmm++; } - fprintf(fp, "%-10s%6d%8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n", clust_name[k], - dr[k].nframes, sumV, maxV, sumVT3, maxVT3, sumVT6, maxVT6); + fprintf(fp, + "%-10s%6d%8.3f %8.3f %8.3f %8.3f %8.3f %8.3f\n", + clust_name[k], + dr[k].nframes, + sumV, + maxV, + sumVT3, + maxVT3, + sumVT6, + maxVT6); } fflush(fp); sfree(drs); @@ -649,14 +670,29 @@ static void dump_disre_matrix(const char* fn, { printf("Warning: the maxdr that you have specified (%g) is smaller than\nthe largest " "value in your simulation (%g)\n", - max_dr, hi); + max_dr, + hi); } hi = max_dr; } printf("Highest level in the matrix will be %g\n", hi); fp = gmx_ffopen(fn, "w"); - write_xpm(fp, 0, "Distance Violations", " (nm)", "Residue", "Residue", n_res, n_res, t_res, - t_res, matrix, 0, hi, rlo, rhi, &nlevels); + write_xpm(fp, + 0, + "Distance Violations", + " (nm)", + "Residue", + "Residue", + n_res, + n_res, + t_res, + t_res, + matrix, + 0, + hi, + rlo, + rhi, + &nlevels); gmx_ffclose(fp); } @@ -732,8 +768,8 @@ int gmx_disre(int argc, char* argv[]) { efNDX, "-c", "clust", ffOPTRD }, { efXPM, "-x", "matrix", ffOPTWR } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -806,8 +842,17 @@ int gmx_disre(int argc, char* argv[]) ir->dr_tau = 0.0; t_disresdata disresdata; - init_disres(fplog, topInfo.mtop(), ir, DisResRunMode::AnalysisTool, DDRole::Master, - NumRanks::Single, MPI_COMM_NULL, nullptr, &disresdata, nullptr, FALSE); + init_disres(fplog, + topInfo.mtop(), + ir, + DisResRunMode::AnalysisTool, + DDRole::Master, + NumRanks::Single, + MPI_COMM_NULL, + nullptr, + &disresdata, + nullptr, + FALSE); int natoms = read_first_x(oenv, &status, ftp2fn(efTRX, NFILE, fnm), &t, &x, box); snew(f, 5 * natoms); @@ -864,13 +909,12 @@ int gmx_disre(int argc, char* argv[]) } my_clust = clust->inv_clust[j]; range_check(my_clust, 0, clust->clust->nr); - check_viol(fplog, idef.il[F_DISRES], idef.iparams, x, f, pbc_null, dr_clust, my_clust, - isize, index, vvindex, &disresdata); + check_viol( + fplog, idef.il[F_DISRES], idef.iparams, x, f, pbc_null, dr_clust, my_clust, isize, index, vvindex, &disresdata); } else { - check_viol(fplog, idef.il[F_DISRES], idef.iparams, x, f, pbc_null, &dr, 0, isize, index, - vvindex, &disresdata); + check_viol(fplog, idef.il[F_DISRES], idef.iparams, x, f, pbc_null, &dr, 0, isize, index, vvindex, &disresdata); } if (bPDB) { @@ -913,20 +957,24 @@ int gmx_disre(int argc, char* argv[]) if (clust) { - dump_clust_stats(fplog, disresdata, idef.il[F_DISRES], idef.iparams, clust->clust, dr_clust, - clust->grpname, isize, index); + dump_clust_stats( + fplog, disresdata, idef.il[F_DISRES], idef.iparams, clust->clust, dr_clust, clust->grpname, isize, index); } else { - dump_stats(fplog, j, disresdata, idef.il[F_DISRES], idef.iparams, &dr, isize, index, - bPDB ? atoms.get() : nullptr); + dump_stats(fplog, j, disresdata, idef.il[F_DISRES], idef.iparams, &dr, isize, index, bPDB ? atoms.get() : nullptr); if (bPDB) { - write_sto_conf(opt2fn("-q", NFILE, fnm), "Coloured by average violation in Angstrom", - atoms.get(), xav, nullptr, ir->pbcType, box); + write_sto_conf(opt2fn("-q", NFILE, fnm), + "Coloured by average violation in Angstrom", + atoms.get(), + xav, + nullptr, + ir->pbcType, + box); } - dump_disre_matrix(opt2fn_null("-x", NFILE, fnm), &dr, disresdata.nres, j, idef, - topInfo.mtop(), max_dr, nlevels, bThird); + dump_disre_matrix( + opt2fn_null("-x", NFILE, fnm), &dr, disresdata.nres, j, idef, topInfo.mtop(), max_dr, nlevels, bThird); xvgrclose(out); xvgrclose(aver); xvgrclose(numv); diff --git a/src/gromacs/gmxana/gmx_do_dssp.cpp b/src/gromacs/gmxana/gmx_do_dssp.cpp index 1cfcde6f38..71c8c5ddc0 100644 --- a/src/gromacs/gmxana/gmx_do_dssp.cpp +++ b/src/gromacs/gmxana/gmx_do_dssp.cpp @@ -90,8 +90,13 @@ static void printDsspResult(char* dssp, const DsspInputStrings& strings, const s #if HAVE_PIPES || GMX_NATIVE_WINDOWS sprintf(dssp, "%s -i %s %s", strings.dptr.c_str(), strings.pdbfile.c_str(), redirectionString.c_str()); #else - sprintf(dssp, "%s -i %s -o %s > %s %s", strings.dptr.c_str(), strings.pdbfile.c_str(), - strings.tmpfile.c_str(), NULL_DEVICE, redirectionString.c_str()); + sprintf(dssp, + "%s -i %s -o %s > %s %s", + strings.dptr.c_str(), + strings.pdbfile.c_str(), + strings.tmpfile.c_str(), + NULL_DEVICE, + redirectionString.c_str()); #endif } @@ -176,8 +181,7 @@ static int strip_dssp(FILE* tapeout, { if (nullptr != acc) { - fprintf(stderr, "%d residues were classified as hydrophobic and %d as hydrophilic.\n", - naccb, naccf); + fprintf(stderr, "%d residues were classified as hydrophobic and %d as hydrophilic.\n", naccb, naccf); } mat->title = "Secondary structure"; @@ -245,7 +249,9 @@ static gmx_bool* bPhobics(t_atoms* atoms) if (i != j) { fprintf(stderr, - "Not all residues were recognized (%d from %d), the result may be inaccurate!\n", j, i); + "Not all residues were recognized (%d from %d), the result may be inaccurate!\n", + j, + i); } for (i = 0; (i < n_surf); i++) @@ -299,8 +305,7 @@ static void norm_acc(t_atoms* atoms, int nres, const real av_area[], real norm_a } else { - fprintf(stderr, "Residue %s not found in surface database (%s)\n", - *atoms->resinfo[i].name, surffn); + fprintf(stderr, "Residue %s not found in surface database (%s)\n", *atoms->resinfo[i].name, surffn); } } } @@ -361,8 +366,22 @@ static void write_sas_mat(const char* fn, real** accr, int nframe, int nres, t_m } fp = gmx_ffopen(fn, "w"); nlev = static_cast(hi - lo + 1); - write_xpm(fp, 0, "Solvent Accessible Surface", "Surface (A^2)", "Time", "Residue Index", - nframe, nres, mat->axis_x.data(), mat->axis_y.data(), accr, lo, hi, rlo, rhi, &nlev); + write_xpm(fp, + 0, + "Solvent Accessible Surface", + "Surface (A^2)", + "Time", + "Residue Index", + nframe, + nres, + mat->axis_x.data(), + mat->axis_y.data(), + accr, + lo, + hi, + rlo, + rhi, + &nlev); gmx_ffclose(fp); } } @@ -385,8 +404,8 @@ static void analyse_ss(const char* outfile, t_matrix* mat, const char* ss_string leg.emplace_back(m.desc); } - fp = xvgropen(outfile, "Secondary Structure", output_env_get_xvgr_tlabel(oenv), - "Number of Residues", oenv); + fp = xvgropen( + outfile, "Secondary Structure", output_env_get_xvgr_tlabel(oenv), "Number of Residues", oenv); if (output_env_get_print_xvgr_codes(oenv)) { fprintf(fp, "@ subtitle \"Structure = "); @@ -458,13 +477,16 @@ static void analyse_ss(const char* outfile, t_matrix* mat, const char* ss_string int gmx_do_dssp(int argc, char* argv[]) { const char* desc[] = { - "[THISMODULE] ", "reads a trajectory file and computes the secondary structure for", - "each time frame ", "calling the dssp program. If you do not have the dssp program,", + "[THISMODULE] ", + "reads a trajectory file and computes the secondary structure for", + "each time frame ", + "calling the dssp program. If you do not have the dssp program,", "get it from http://swift.cmbi.ru.nl/gv/dssp. [THISMODULE] assumes ", "that the dssp executable is located in ", // NOLINTNEXTLINE(bugprone-suspicious-missing-comma) "[TT]" GMX_DSSP_PROGRAM_PATH "[tt]. If this is not the case, then you should", - "set an environment variable [TT]DSSP[tt] pointing to the dssp", "executable, e.g.: [PAR]", + "set an environment variable [TT]DSSP[tt] pointing to the dssp", + "executable, e.g.: [PAR]", "[TT]setenv DSSP /opt/dssp/bin/dssp[tt][PAR]", "Since version 2.0.0, dssp is invoked with a syntax that differs", "from earlier versions. If you have an older version of dssp,", @@ -476,7 +498,8 @@ int gmx_do_dssp(int argc, char* argv[]) "[REF].xpm[ref] matrix file. This file can be visualized with for instance", "[TT]xv[tt] and can be converted to postscript with [TT]xpm2ps[tt].", "Individual chains are separated by light grey lines in the [REF].xpm[ref] and", - "postscript files.", "The number of residues with each secondary structure type and the", + "postscript files.", + "The number of residues with each secondary structure type and the", "total secondary structure ([TT]-sss[tt]) count as a function of", "time are also written to file ([TT]-sc[tt]).[PAR]", "Solvent accessible surface (SAS) per residue can be calculated, both in", @@ -538,8 +561,18 @@ int gmx_do_dssp(int argc, char* argv[]) }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW | PCA_TIME_UNIT, NFILE, fnm, - asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args(&argc, + argv, + PCA_CAN_TIME | PCA_CAN_VIEW | PCA_TIME_UNIT, + NFILE, + fnm, + asize(pa), + pa, + asize(desc), + desc, + 0, + nullptr, + &oenv)) { return 0; } @@ -635,8 +668,11 @@ int gmx_do_dssp(int argc, char* argv[]) if (fnTArea) { - fTArea = xvgropen(fnTArea, "Solvent Accessible Surface Area", - output_env_get_xvgr_tlabel(oenv), "Area (nm\\S2\\N)", oenv); + fTArea = xvgropen(fnTArea, + "Solvent Accessible Surface Area", + output_env_get_xvgr_tlabel(oenv), + "Area (nm\\S2\\N)", + oenv); xvgr_legend(fTArea, 2, leg, oenv); } else diff --git a/src/gromacs/gmxana/gmx_dos.cpp b/src/gromacs/gmxana/gmx_dos.cpp index 2c1a9717c4..1c4483c069 100644 --- a/src/gromacs/gmxana/gmx_dos.cpp +++ b/src/gromacs/gmxana/gmx_dos.cpp @@ -334,8 +334,8 @@ int gmx_dos(int argc, char* argv[]) npargs = asize(pa); ppa = add_acf_pargs(&npargs, pa); - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, npargs, ppa, - asize(desc), desc, asize(bugs), bugs, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, npargs, ppa, asize(desc), desc, asize(bugs), bugs, &oenv)) { sfree(ppa); return 0; @@ -410,8 +410,7 @@ int gmx_dos(int argc, char* argv[]) if (nframes < min_frames) { - gmx_fatal(FARGS, "You need at least %d frames in the trajectory and you only have %d.", - min_frames, nframes); + gmx_fatal(FARGS, "You need at least %d frames in the trajectory and you only have %d.", min_frames, nframes); } dt = (t1 - t0) / (nframes - 1); if (nV > 0) @@ -437,8 +436,8 @@ int gmx_dos(int argc, char* argv[]) normalizeAutocorrelation = opt2parg_bool("-normalize", npargs, ppa); /* Note that we always disable normalization here, regardless of user settings */ - low_do_autocorr(nullptr, oenv, nullptr, nframes, gnx, nframes, c1, dt, eacNormal, 0, FALSE, - FALSE, FALSE, -1, -1, 0); + low_do_autocorr( + nullptr, oenv, nullptr, nframes, gnx, nframes, c1, dt, eacNormal, 0, FALSE, FALSE, FALSE, -1, -1, 0); snew(dos, DOS_NR); for (j = 0; (j < DOS_NR); j++) { @@ -460,8 +459,8 @@ int gmx_dos(int argc, char* argv[]) } } - fp = xvgropen(opt2fn("-vacf", NFILE, fnm), "Velocity autocorrelation function", "Time (ps)", - "C(t)", oenv); + fp = xvgropen( + opt2fn("-vacf", NFILE, fnm), "Velocity autocorrelation function", "Time (ps)", "C(t)", oenv); snew(tt, nframes / 2); invNormalize = normalizeAutocorrelation ? 1.0 / dos[VACF][0] : 1.0; @@ -473,8 +472,11 @@ int gmx_dos(int argc, char* argv[]) } xvgrclose(fp); - fp = xvgropen(opt2fn("-mvacf", NFILE, fnm), "Mass-weighted velocity autocorrelation function", - "Time (ps)", "C(t)", oenv); + fp = xvgropen(opt2fn("-mvacf", NFILE, fnm), + "Mass-weighted velocity autocorrelation function", + "Time (ps)", + "C(t)", + oenv); invNormalize = normalizeAutocorrelation ? 1.0 / dos[VACF][0] : 1.0; @@ -559,16 +561,23 @@ int gmx_dos(int argc, char* argv[]) fprintf(fplog, "DoSTot = %g\n", dostot); /* Now compute solid (2) and diffusive (3) components */ - fp = xvgropen(opt2fn("-dos", NFILE, fnm), "Density of states", - bRecip ? "E (cm\\S-1\\N)" : "\\f{12}n\\f{4} (1/ps)", "\\f{4}S(\\f{12}n\\f{4})", oenv); + fp = xvgropen(opt2fn("-dos", NFILE, fnm), + "Density of states", + bRecip ? "E (cm\\S-1\\N)" : "\\f{12}n\\f{4} (1/ps)", + "\\f{4}S(\\f{12}n\\f{4})", + oenv); xvgr_legend(fp, asize(DoSlegend), DoSlegend, oenv); recip_fac = bRecip ? (1e7 / SPEED_OF_LIGHT) : 1.0; for (j = 0; (j < nframes / 4); j++) { dos[DOS_DIFF][j] = DoS0 / (1 + gmx::square(DoS0 * M_PI * nu[j] / (6 * f * Natom))); dos[DOS_SOLID][j] = dos[DOS][j] - dos[DOS_DIFF][j]; - fprintf(fp, "%10g %10g %10g %10g\n", recip_fac * nu[j], dos[DOS][j] / recip_fac, - dos[DOS_SOLID][j] / recip_fac, dos[DOS_DIFF][j] / recip_fac); + fprintf(fp, + "%10g %10g %10g %10g\n", + recip_fac * nu[j], + dos[DOS][j] / recip_fac, + dos[DOS_SOLID][j] / recip_fac, + dos[DOS_DIFF][j] / recip_fac); } xvgrclose(fp); diff --git a/src/gromacs/gmxana/gmx_dyecoupl.cpp b/src/gromacs/gmxana/gmx_dyecoupl.cpp index 301ca77e8e..c32ddfc29a 100644 --- a/src/gromacs/gmxana/gmx_dyecoupl.cpp +++ b/src/gromacs/gmxana/gmx_dyecoupl.cpp @@ -125,8 +125,18 @@ int gmx_dyecoupl(int argc, char* argv[]) rrange, krange, rincr, kincr, Rfrac; int rkcount = 0, rblocksallocated = 0, kblocksallocated = 0; - if (!parse_common_args(&argc, argv, PCA_CAN_BEGIN | PCA_CAN_END | PCA_CAN_VIEW | PCA_TIME_UNIT, - NFILE, fnm, NPA, pa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args(&argc, + argv, + PCA_CAN_BEGIN | PCA_CAN_END | PCA_CAN_VIEW | PCA_TIME_UNIT, + NFILE, + fnm, + NPA, + pa, + asize(desc), + desc, + 0, + nullptr, + &oenv)) { return 0; } @@ -228,15 +238,21 @@ int gmx_dyecoupl(int argc, char* argv[]) if (bRKout) { - rkfp = xvgropen(out_xvgrkfile, "Distance and \\f{Symbol}k\\f{}\\S2\\N trajectory", - "Time (ps)", "Distance (nm) / \\f{Symbol}k\\f{}\\S2\\N", oenv); + rkfp = xvgropen(out_xvgrkfile, + "Distance and \\f{Symbol}k\\f{}\\S2\\N trajectory", + "Time (ps)", + "Distance (nm) / \\f{Symbol}k\\f{}\\S2\\N", + oenv); xvgr_legend(rkfp, 2, rkleg, oenv); } if (bInstEffout) { - iefp = xvgropen(out_xvginstefffile, "Instantaneous RET Efficiency", "Time (ps)", - "RET Efficiency", oenv); + iefp = xvgropen(out_xvginstefffile, + "Instantaneous RET Efficiency", + "Time (ps)", + "RET Efficiency", + oenv); xvgr_legend(iefp, 1, ieleg, oenv); } @@ -396,13 +412,16 @@ int gmx_dyecoupl(int argc, char* argv[]) { rhist[i] /= rkcount * rrange / histbins; } - rhfp = xvgropen(out_xvgrhistfile, "Distance Distribution", "R (nm)", - "Normalized Probability", oenv); + rhfp = xvgropen(out_xvgrhistfile, + "Distance Distribution", + "R (nm)", + "Normalized Probability", + oenv); } else { - rhfp = xvgropen(out_xvgrhistfile, "Distance Distribution", "R (nm)", - "Probability", oenv); + rhfp = xvgropen( + out_xvgrhistfile, "Distance Distribution", "R (nm)", "Probability", oenv); } xvgr_legend(rhfp, 1, rhleg, oenv); for (i = 0; i < histbins; i++) @@ -429,13 +448,19 @@ int gmx_dyecoupl(int argc, char* argv[]) { khist[i] /= rkcount * krange / histbins; } - khfp = xvgropen(out_xvgkhistfile, "\\f{Symbol}k\\f{}\\S2\\N Distribution", - "\\f{Symbol}k\\f{}\\S2\\N", "Normalized Probability", oenv); + khfp = xvgropen(out_xvgkhistfile, + "\\f{Symbol}k\\f{}\\S2\\N Distribution", + "\\f{Symbol}k\\f{}\\S2\\N", + "Normalized Probability", + oenv); } else { - khfp = xvgropen(out_xvgkhistfile, "\\f{Symbol}k\\f{}\\S2\\N Distribution", - "\\f{Symbol}k\\f{}\\S2\\N", "Probability", oenv); + khfp = xvgropen(out_xvgkhistfile, + "\\f{Symbol}k\\f{}\\S2\\N Distribution", + "\\f{Symbol}k\\f{}\\S2\\N", + "Probability", + oenv); } xvgr_legend(khfp, 1, khleg, oenv); for (i = 0; i < histbins; i++) diff --git a/src/gromacs/gmxana/gmx_enemat.cpp b/src/gromacs/gmxana/gmx_enemat.cpp index 25b5db7513..c03904be6d 100644 --- a/src/gromacs/gmxana/gmx_enemat.cpp +++ b/src/gromacs/gmxana/gmx_enemat.cpp @@ -190,8 +190,8 @@ int gmx_enemat(int argc, char* argv[]) { efXVG, "-etot", "energy", ffWRITE } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -254,7 +254,9 @@ int gmx_enemat(int argc, char* argv[]) fprintf(stderr, "WARNING! could not find group %s (%d,%d) " "in energy file\n", - groupname, i, j); + groupname, + i, + j); } else { @@ -330,7 +332,9 @@ int gmx_enemat(int argc, char* argv[]) fprintf(stderr, "Will build energy half-matrix of %d groups, %d elements, " "over %d frames\n", - ngroups, nset, nenergy); + ngroups, + nset, + nenergy); snew(emat, egNR + egSP); for (j = 0; (j < egNR + egSP); j++) @@ -476,7 +480,8 @@ int gmx_enemat(int argc, char* argv[]) fprintf(stderr, "Matrix of %s energy is uniform at %f " "(will not produce output).\n", - egrp_nm[m], emax); + egrp_nm[m], + emax); } else { @@ -499,21 +504,62 @@ int gmx_enemat(int argc, char* argv[]) out = gmx_ffopen(fn, "w"); if (emin >= emid) { - write_xpm(out, 0, label, "Energy (kJ/mol)", "Residue Index", - "Residue Index", ngroups, ngroups, groupnr, groupnr, emat[m], - emid, emax, rmid, rhi, &nlevels); + write_xpm(out, + 0, + label, + "Energy (kJ/mol)", + "Residue Index", + "Residue Index", + ngroups, + ngroups, + groupnr, + groupnr, + emat[m], + emid, + emax, + rmid, + rhi, + &nlevels); } else if (emax <= emid) { - write_xpm(out, 0, label, "Energy (kJ/mol)", "Residue Index", - "Residue Index", ngroups, ngroups, groupnr, groupnr, emat[m], - emin, emid, rlo, rmid, &nlevels); + write_xpm(out, + 0, + label, + "Energy (kJ/mol)", + "Residue Index", + "Residue Index", + ngroups, + ngroups, + groupnr, + groupnr, + emat[m], + emin, + emid, + rlo, + rmid, + &nlevels); } else { - write_xpm3(out, 0, label, "Energy (kJ/mol)", "Residue Index", - "Residue Index", ngroups, ngroups, groupnr, groupnr, emat[m], - emin, emid, emax, rlo, rmid, rhi, &nlevels); + write_xpm3(out, + 0, + label, + "Energy (kJ/mol)", + "Residue Index", + "Residue Index", + ngroups, + ngroups, + groupnr, + groupnr, + emat[m], + emin, + emid, + emax, + rlo, + rmid, + rhi, + &nlevels); } gmx_ffclose(out); } diff --git a/src/gromacs/gmxana/gmx_energy.cpp b/src/gromacs/gmxana/gmx_energy.cpp index 25e6a2e9c7..e3778d7747 100644 --- a/src/gromacs/gmxana/gmx_energy.cpp +++ b/src/gromacs/gmxana/gmx_energy.cpp @@ -340,8 +340,8 @@ static void einstein_visco(const char* fn, avold[i] = 0; } fp0 = xvgropen(fni, "Shear viscosity integral", "Time (ps)", "(kg m\\S-1\\N s\\S-1\\N ps)", oenv); - fp1 = xvgropen(fn, "Shear viscosity using Einstein relation", "Time (ps)", - "(kg m\\S-1\\N s\\S-1\\N)", oenv); + fp1 = xvgropen( + fn, "Shear viscosity using Einstein relation", "Time (ps)", "(kg m\\S-1\\N s\\S-1\\N)", oenv); for (i = 0; i < nf4; i++) { for (m = 0; m <= nsets; m++) @@ -596,8 +596,12 @@ static void calc_averages(int nset, enerdata_t* edat, int nbmin, int nbmax) if (debug) { char buf1[STEPSTRSIZE], buf2[STEPSTRSIZE]; - fprintf(debug, "Requested %d blocks, we have %d blocks, min %s nsteps %s\n", nb, - eee[nb].b, gmx_step_str(eee[nb].nst_min, buf1), gmx_step_str(edat->nsteps, buf2)); + fprintf(debug, + "Requested %d blocks, we have %d blocks, min %s nsteps %s\n", + nb, + eee[nb].b, + gmx_step_str(eee[nb].nst_min, buf1), + gmx_step_str(edat->nsteps, buf2)); } if (eee[nb].b == nb && 5 * nb * eee[nb].nst_min >= 4 * edat->nsteps) { @@ -832,8 +836,7 @@ if (tt != NOTSET) } if (varh != NOTSET) { - fprintf(fp, "Enthalpy = %10g kJ/mol\n", - hh * AVOGADRO / (KILO * nmol)); + fprintf(fp, "Enthalpy = %10g kJ/mol\n", hh * AVOGADRO / (KILO * nmol)); } if (alpha != NOTSET) { @@ -913,8 +916,12 @@ static void analyse_ener(gmx_bool bCorr, /* Calculate the time difference */ delta_t = t - start_t; - fprintf(stdout, "\nStatistics over %s steps [ %.4f through %.4f ps ], %d data sets\n", - gmx_step_str(nsteps, buf), start_t, t, nset); + fprintf(stdout, + "\nStatistics over %s steps [ %.4f through %.4f ps ], %d data sets\n", + gmx_step_str(nsteps, buf), + start_t, + t, + nset); calc_averages(nset, edat, nbmin, nbmax); @@ -963,13 +970,20 @@ static void analyse_ener(gmx_bool bCorr, fprintf(stdout, " '%s'", leg[i]); } } - fprintf(stdout, " %s has statistics over %d points (frames)\n", - nnotexact == 1 ? "is" : "are", edat->nframes); + fprintf(stdout, + " %s has statistics over %d points (frames)\n", + nnotexact == 1 ? "is" : "are", + edat->nframes); fprintf(stdout, "All other statistics are over %s points\n", gmx_step_str(edat->npoints, buf)); } fprintf(stdout, "\n"); - fprintf(stdout, "%-24s %10s %10s %10s %10s", "Energy", "Average", "Err.Est.", "RMSD", + fprintf(stdout, + "%-24s %10s %10s %10s %10s", + "Energy", + "Average", + "Err.Est.", + "RMSD", "Tot-Drift"); if (bFee) { @@ -1063,12 +1077,20 @@ static void analyse_ener(gmx_bool bCorr, { totaldrift = (edat->nsteps - 1) * esum->s[0].slope; ee_pr(esum->s[0].ee / nmol, sizeof(eebuf), eebuf); - fprintf(stdout, "%-24s %10g %10s %10s %10g (%s)", "Total", esum->s[0].av / nmol, eebuf, - "--", totaldrift / nmol, enm[set[0]].unit); + fprintf(stdout, + "%-24s %10g %10s %10s %10g (%s)", + "Total", + esum->s[0].av / nmol, + eebuf, + "--", + totaldrift / nmol, + enm[set[0]].unit); /* pr_aver,pr_stddev,a,totaldrift */ if (bFee) { - fprintf(stdout, " %10g %10g\n", std::log(expEtot) / beta + esum->s[0].av / nmol, + fprintf(stdout, + " %10g %10g\n", + std::log(expEtot) / beta + esum->s[0].av / nmol, std::log(expEtot) / beta); } else @@ -1148,13 +1170,41 @@ static void analyse_ener(gmx_bool bCorr, /*do_autocorr(corrfn,buf,nenergy,3,eneset,Dt,eacNormal,TRUE);*/ /* Do it for shear viscosity */ std::strcpy(buf, "Shear Viscosity"); - low_do_autocorr(corrfn, oenv, buf, edat->nframes, 3, (edat->nframes + 1) / 2, eneset, - Dt, eacNormal, 1, TRUE, FALSE, FALSE, 0.0, 0.0, 0); + low_do_autocorr(corrfn, + oenv, + buf, + edat->nframes, + 3, + (edat->nframes + 1) / 2, + eneset, + Dt, + eacNormal, + 1, + TRUE, + FALSE, + FALSE, + 0.0, + 0.0, + 0); /* Now for bulk viscosity */ std::strcpy(buf, "Bulk Viscosity"); - low_do_autocorr(corrfn, oenv, buf, edat->nframes, 1, (edat->nframes + 1) / 2, - &(eneset[11]), Dt, eacNormal, 1, TRUE, FALSE, FALSE, 0.0, 0.0, 0); + low_do_autocorr(corrfn, + oenv, + buf, + edat->nframes, + 1, + (edat->nframes + 1) / 2, + &(eneset[11]), + Dt, + eacNormal, + 1, + TRUE, + FALSE, + FALSE, + 0.0, + 0.0, + 0); factor = (Vaver * 1e-26 / (BOLTZMANN * Temp)) * Dt; fp = xvgropen(visfn, buf, "Time (ps)", "\\8h\\4 (cp)", oenv); @@ -1285,8 +1335,11 @@ static void fec(const char* ene2fn, if (fr->t != time[nenergy2]) { - fprintf(stderr, "\nWARNING time mismatch %g!=%g at frame %s\n", fr->t, - time[nenergy2], gmx_step_str(fr->step, buf)); + fprintf(stderr, + "\nWARNING time mismatch %g!=%g at frame %s\n", + fr->t, + time[nenergy2], + gmx_step_str(fr->step, buf)); } for (i = 0; i < nset; i++) { @@ -1308,8 +1361,11 @@ static void fec(const char* ene2fn, fp = nullptr; if (runavgfn) { - fp = xvgropen(runavgfn, "Running average free energy difference", "Time (" unit_time ")", - "\\8D\\4E (" unit_energy ")", oenv); + fp = xvgropen(runavgfn, + "Running average free energy difference", + "Time (" unit_time ")", + "\\8D\\4E (" unit_energy ")", + oenv); xvgr_legend(fp, asize(ravgleg), ravgleg, oenv); } fprintf(stdout, "\n%-24s %10s\n", "Energy", "dF = -kT ln < exp(-(EB-EA)/kT) >A"); @@ -1487,8 +1543,7 @@ static void do_dhdl(t_enxframe* fr, if (!derivative) { - sprintf(legend, "N(%s(%s=%g) | %s=%g)", deltag, lambda, foreign_lambda, - lambda, start_lambda); + sprintf(legend, "N(%s(%s=%g) | %s=%g)", deltag, lambda, foreign_lambda, lambda, start_lambda); } else { @@ -1568,8 +1623,7 @@ static void do_dhdl(t_enxframe* fr, if (j == 1 && ir->bExpanded) { - fprintf(*fp_dhdl, "%4d", - static_cast(value)); /* if expanded ensembles and zero, this is a state value, it's an integer. We need a cleaner conditional than if j==1! */ + fprintf(*fp_dhdl, "%4d", static_cast(value)); /* if expanded ensembles and zero, this is a state value, it's an integer. We need a cleaner conditional than if j==1! */ } else { @@ -1768,8 +1822,8 @@ int gmx_energy(int argc, char* argv[]) npargs = asize(pa); ppa = add_acf_pargs(&npargs, pa); - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_BEGIN | PCA_CAN_END, NFILE, fnm, - npargs, ppa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_BEGIN | PCA_CAN_END, NFILE, fnm, npargs, ppa, asize(desc), desc, 0, nullptr, &oenv)) { sfree(ppa); return 0; @@ -2021,8 +2075,7 @@ int gmx_energy(int argc, char* argv[]) } if (bDHDL) { - do_dhdl(fr, ir, &fp_dhdl, opt2fn("-odh", NFILE, fnm), bDp, &dh_blocks, &dh_hists, - &dh_samples, &dh_lambdas, oenv); + do_dhdl(fr, ir, &fp_dhdl, opt2fn("-odh", NFILE, fnm), bDp, &dh_blocks, &dh_hists, &dh_samples, &dh_lambdas, oenv); } /******************************************* @@ -2110,11 +2163,32 @@ int gmx_energy(int argc, char* argv[]) else { double dt = (frame[cur].t - start_t) / (edat.nframes - 1); - analyse_ener(opt2bSet("-corr", NFILE, fnm), opt2fn("-corr", NFILE, fnm), - opt2fn("-evisco", NFILE, fnm), opt2fn("-eviscoi", NFILE, fnm), bFee, bSum, - bFluct, bVisco, opt2fn("-vis", NFILE, fnm), nmol, start_step, start_t, - frame[cur].step, frame[cur].t, reftemp, &edat, nset, set, bIsEner, leg, enm, - Vaver, ezero, nbmin, nbmax, oenv); + analyse_ener(opt2bSet("-corr", NFILE, fnm), + opt2fn("-corr", NFILE, fnm), + opt2fn("-evisco", NFILE, fnm), + opt2fn("-eviscoi", NFILE, fnm), + bFee, + bSum, + bFluct, + bVisco, + opt2fn("-vis", NFILE, fnm), + nmol, + start_step, + start_t, + frame[cur].step, + frame[cur].t, + reftemp, + &edat, + nset, + set, + bIsEner, + leg, + enm, + Vaver, + ezero, + nbmin, + nbmax, + oenv); if (bFluctProps) { calc_fluctuation_props(stdout, bDriftCorr, dt, nset, nmol, leg, &edat, nbmin, nbmax); @@ -2122,8 +2196,7 @@ int gmx_energy(int argc, char* argv[]) } if (opt2bSet("-f2", NFILE, fnm)) { - fec(opt2fn("-f2", NFILE, fnm), opt2fn("-ravg", NFILE, fnm), reftemp, nset, set, leg, &edat, - time, oenv); + fec(opt2fn("-f2", NFILE, fnm), opt2fn("-ravg", NFILE, fnm), reftemp, nset, set, leg, &edat, time, oenv); } // Clean up! done_enerdata_t(nset, &edat); diff --git a/src/gromacs/gmxana/gmx_filter.cpp b/src/gromacs/gmxana/gmx_filter.cpp index c9567a806b..5500736cc9 100644 --- a/src/gromacs/gmxana/gmx_filter.cpp +++ b/src/gromacs/gmxana/gmx_filter.cpp @@ -119,8 +119,8 @@ int gmx_filter(int argc, char* argv[]) { efTRO, "-oh", "highpass", ffOPTWR } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -298,8 +298,16 @@ int gmx_filter(int argc, char* argv[]) } if (outl && (bLowAll || fr % nf == nf - 1)) { - write_trx(outl, nat, ind, topfile ? &(top.atoms) : nullptr, 0, t[nf - 1], - bFit ? topbox : boxf, xf, nullptr, nullptr); + write_trx(outl, + nat, + ind, + topfile ? &(top.atoms) : nullptr, + 0, + t[nf - 1], + bFit ? topbox : boxf, + xf, + nullptr, + nullptr); } if (outh) { @@ -325,8 +333,16 @@ int gmx_filter(int argc, char* argv[]) boxf[j][d] = topbox[j][d] + box[nf - 1][j][d] - boxf[j][d]; } } - write_trx(outh, nat, ind, topfile ? &(top.atoms) : nullptr, 0, t[nf - 1], - bFit ? topbox : boxf, xf, nullptr, nullptr); + write_trx(outh, + nat, + ind, + topfile ? &(top.atoms) : nullptr, + 0, + t[nf - 1], + bFit ? topbox : boxf, + xf, + nullptr, + nullptr); } } /* Cycle all the pointer and the box by one */ diff --git a/src/gromacs/gmxana/gmx_gyrate.cpp b/src/gromacs/gmxana/gmx_gyrate.cpp index 6df19ae6fe..9c0b241395 100644 --- a/src/gromacs/gmxana/gmx_gyrate.cpp +++ b/src/gromacs/gmxana/gmx_gyrate.cpp @@ -252,8 +252,8 @@ int gmx_gyrate(int argc, char* argv[]) npargs = asize(pa); ppa = add_acf_pargs(&npargs, pa); - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, npargs, ppa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, npargs, ppa, asize(desc), desc, 0, nullptr, &oenv)) { sfree(ppa); return 0; @@ -299,18 +299,27 @@ int gmx_gyrate(int argc, char* argv[]) t0 = t; if (bQ) { - out = xvgropen(ftp2fn(efXVG, NFILE, fnm), "Radius of Charge (total and around axes)", - "Time (ps)", "Rg (nm)", oenv); + out = xvgropen(ftp2fn(efXVG, NFILE, fnm), + "Radius of Charge (total and around axes)", + "Time (ps)", + "Rg (nm)", + oenv); } else if (bMOI) { - out = xvgropen(ftp2fn(efXVG, NFILE, fnm), "Moments of inertia (total and around axes)", - "Time (ps)", "I (a.m.u. nm\\S2\\N)", oenv); + out = xvgropen(ftp2fn(efXVG, NFILE, fnm), + "Moments of inertia (total and around axes)", + "Time (ps)", + "I (a.m.u. nm\\S2\\N)", + oenv); } else { - out = xvgropen(ftp2fn(efXVG, NFILE, fnm), "Radius of gyration (total and around axes)", - "Time (ps)", "Rg (nm)", oenv); + out = xvgropen(ftp2fn(efXVG, NFILE, fnm), + "Radius of gyration (total and around axes)", + "Time (ps)", + "Rg (nm)", + oenv); } if (bMOI) { @@ -347,8 +356,8 @@ int gmx_gyrate(int argc, char* argv[]) tm = sub_xcm(nz == 0 ? x_s : x, nam, index + mol * nam, top.atoms.atom, xcm, bQ); if (nz == 0) { - gyro += calc_gyro(x_s, nam, index + mol * nam, top.atoms.atom, tm, gvec1, d1, bQ, - bRot, bMOI, trans); + gyro += calc_gyro( + x_s, nam, index + mol * nam, top.atoms.atom, tm, gvec1, d1, bQ, bRot, bMOI, trans); } else { @@ -401,8 +410,15 @@ int gmx_gyrate(int argc, char* argv[]) { int mode = eacVector; - do_autocorr(opt2fn("-acf", NFILE, fnm), oenv, "Moment of inertia vector ACF", j, 3, - moi_trans, (t - t0) / j, mode, FALSE); + do_autocorr(opt2fn("-acf", NFILE, fnm), + oenv, + "Moment of inertia vector ACF", + j, + 3, + moi_trans, + (t - t0) / j, + mode, + FALSE); do_view(oenv, opt2fn("-acf", NFILE, fnm), "-nxy"); } diff --git a/src/gromacs/gmxana/gmx_h2order.cpp b/src/gromacs/gmxana/gmx_h2order.cpp index 509801a572..b3f4b46a7b 100644 --- a/src/gromacs/gmxana/gmx_h2order.cpp +++ b/src/gromacs/gmxana/gmx_h2order.cpp @@ -252,8 +252,13 @@ static void h2order_plot(rvec dipole[], real order[], const char* afile, int nsl for (slice = 0; slice < nslices; slice++) { - fprintf(ord, "%8.3f %8.3f %8.3f %8.3f %e\n", slWidth * slice, factor * dipole[slice][XX], - factor * dipole[slice][YY], factor * dipole[slice][ZZ], order[slice]); + fprintf(ord, + "%8.3f %8.3f %8.3f %8.3f %e\n", + slWidth * slice, + factor * dipole[slice][XX], + factor * dipole[slice][YY], + factor * dipole[slice][ZZ], + order[slice]); } xvgrclose(ord); @@ -326,8 +331,8 @@ int gmx_h2order(int argc, char* argv[]) #define NFILE asize(fnm) // Parse the user input in argv into pa - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, - asize(desc), desc, asize(bugs), bugs, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, asize(bugs), bugs, &oenv)) { return 0; } @@ -355,8 +360,20 @@ int gmx_h2order(int argc, char* argv[]) rd_index(opt2fn("-nm", NFILE, fnm), 1, &nmic, &micelle, &micname); } - calc_h2order(ftp2fn(efTRX, NFILE, fnm), index, ngx, &slDipole, &slOrder, &slWidth, &nslices, - top, pbcType, axis, bMicel, micelle, nmic, oenv); + calc_h2order(ftp2fn(efTRX, NFILE, fnm), + index, + ngx, + &slDipole, + &slOrder, + &slWidth, + &nslices, + top, + pbcType, + axis, + bMicel, + micelle, + nmic, + oenv); h2order_plot(slDipole, slOrder, opt2fn("-o", NFILE, fnm), nslices, slWidth, oenv); diff --git a/src/gromacs/gmxana/gmx_hbond.cpp b/src/gromacs/gmxana/gmx_hbond.cpp index b9bb443893..b4795b68f5 100644 --- a/src/gromacs/gmxana/gmx_hbond.cpp +++ b/src/gromacs/gmxana/gmx_hbond.cpp @@ -376,8 +376,7 @@ static int _acceptor_index(t_acceptors* a, int grp, int i, const char* file, int { if (debug && bDebug) { - fprintf(debug, "Acc. group inconsist.. grp[%d] = %d, grp = %d (%s, %d)\n", ai, - a->grp[ai], grp, file, line); + fprintf(debug, "Acc. group inconsist.. grp[%d] = %d, grp = %d (%s, %d)\n", ai, a->grp[ai], grp, file, line); } return NOTSET; } @@ -401,8 +400,7 @@ static int _donor_index(t_donors* d, int grp, int i, const char* file, int line) { if (debug && bDebug) { - fprintf(debug, "Don. group inconsist.. grp[%d] = %d, grp = %d (%s, %d)\n", di, - d->grp[di], grp, file, line); + fprintf(debug, "Don. group inconsist.. grp[%d] = %d, grp = %d (%s, %d)\n", di, d->grp[di], grp, file, line); } return NOTSET; } @@ -436,8 +434,7 @@ add_hbond(t_hbdata* hb, int d, int a, int h, int grpd, int grpa, int frame, gmx_ } else if (grpd != hb->d.grp[id]) { - gmx_fatal(FARGS, "Inconsistent donor groups, %d instead of %d, atom %d", grpd, - hb->d.grp[id], d + 1); + gmx_fatal(FARGS, "Inconsistent donor groups, %d instead of %d, atom %d", grpd, hb->d.grp[id], d + 1); } if ((ia = hb->a.aptr[a]) == NOTSET) { @@ -445,8 +442,7 @@ add_hbond(t_hbdata* hb, int d, int a, int h, int grpd, int grpa, int frame, gmx_ } else if (grpa != hb->a.grp[ia]) { - gmx_fatal(FARGS, "Inconsistent acceptor groups, %d instead of %d, atom %d", grpa, - hb->a.grp[ia], a + 1); + gmx_fatal(FARGS, "Inconsistent acceptor groups, %d instead of %d, atom %d", grpa, hb->a.grp[ia], a + 1); } if (bMerge) @@ -470,8 +466,11 @@ add_hbond(t_hbdata* hb, int d, int a, int h, int grpd, int grpa, int frame, gmx_ } else if (grpd != hb->d.grp[id]) { - gmx_fatal(FARGS, "Inconsistent donor groups, %d instead of %d, atom %d", grpd, - hb->d.grp[id], d + 1); + gmx_fatal(FARGS, + "Inconsistent donor groups, %d instead of %d, atom %d", + grpd, + hb->d.grp[id], + d + 1); } if ((ia = hb->a.aptr[a]) == NOTSET) { @@ -479,8 +478,11 @@ add_hbond(t_hbdata* hb, int d, int a, int h, int grpd, int grpa, int frame, gmx_ } else if (grpa != hb->a.grp[ia]) { - gmx_fatal(FARGS, "Inconsistent acceptor groups, %d instead of %d, atom %d", grpa, - hb->a.grp[ia], a + 1); + gmx_fatal(FARGS, + "Inconsistent acceptor groups, %d instead of %d, atom %d", + grpa, + hb->a.grp[ia], + a + 1); } } } @@ -900,8 +902,7 @@ static t_gridcell*** init_grid(gmx_bool bBox, rvec box[], real rcut, ivec ngrid) } else { - printf("\nWill do grid-search on %dx%dx%d grid, rcut=%3.8f\n", ngrid[XX], ngrid[YY], - ngrid[ZZ], rcut); + printf("\nWill do grid-search on %dx%dx%d grid, rcut=%3.8f\n", ngrid[XX], ngrid[YY], ngrid[ZZ], rcut); } if (((ngrid[XX] * ngrid[YY] * ngrid[ZZ]) * sizeof(grid)) > INT_MAX) { @@ -910,8 +911,14 @@ static t_gridcell*** init_grid(gmx_bool bBox, rvec box[], real rcut, ivec ngrid) "the maximum of %zu. " "You are likely either using a box that is too large (box dimensions are %3.8f " "nm x%3.8f nm x%3.8f nm) or a cutoff (%3.8f nm) that is too small.", - ngrid[XX], ngrid[YY], ngrid[ZZ], INT_MAX / sizeof(grid), box[XX][XX], box[YY][YY], - box[ZZ][ZZ], rcut); + ngrid[XX], + ngrid[YY], + ngrid[ZZ], + INT_MAX / sizeof(grid), + box[XX][XX], + box[YY][YY], + box[ZZ][ZZ], + rcut); } snew(grid, ngrid[ZZ]); for (z = 0; z < ngrid[ZZ]; z++) @@ -1638,8 +1645,8 @@ static void do_hblife(const char* fn, t_hbdata* hb, gmx_bool bMerge, gmx_bool bC } else { - fp = xvgropen(fn, "Uninterrupted hydrogen bond lifetime", output_env_get_xvgr_tlabel(oenv), - "()", oenv); + fp = xvgropen( + fn, "Uninterrupted hydrogen bond lifetime", output_env_get_xvgr_tlabel(oenv), "()", oenv); } xvgr_legend(fp, asize(leg), leg, oenv); @@ -1855,19 +1862,27 @@ void analyse_corr(int n, { chi2 += gmx::square(k * ct[i] - kp * nt[i] - kt[i]); } - compute_weighted_rates(n, t, ct, nt, kt, sigma_ct, sigma_nt, sigma_kt, &k, &kp, - &sigma_k, &sigma_kp, fit_start); + compute_weighted_rates( + n, t, ct, nt, kt, sigma_ct, sigma_nt, sigma_kt, &k, &kp, &sigma_k, &sigma_kp, fit_start); Q = 0; /* quality_of_fit(chi2, 2);*/ ddg = BOLTZ * temp * sigma_k / k; printf("Fitting paramaters chi^2 = %10g, Quality of fit = %10g\n", chi2, Q); printf("The Rate and Delta G are followed by an error estimate\n"); printf("----------------------------------------------------------\n" "Type Rate (1/ps) Sigma Time (ps) DG (kJ/mol) Sigma\n"); - printf("Forward %10.3f %6.2f %8.3f %10.3f %6.2f\n", k, sigma_k, 1 / k, - calc_dg(1 / k, temp), ddg); + printf("Forward %10.3f %6.2f %8.3f %10.3f %6.2f\n", + k, + sigma_k, + 1 / k, + calc_dg(1 / k, temp), + ddg); ddg = BOLTZ * temp * sigma_kp / kp; - printf("Backward %10.3f %6.2f %8.3f %10.3f %6.2f\n", kp, sigma_kp, 1 / kp, - calc_dg(1 / kp, temp), ddg); + printf("Backward %10.3f %6.2f %8.3f %10.3f %6.2f\n", + kp, + sigma_kp, + 1 / kp, + calc_dg(1 / kp, temp), + ddg); } else { @@ -1886,18 +1901,29 @@ void analyse_corr(int n, if (sc2 > 0) { kow = 2 * sck / sc2; - printf("One-way %10.3f %s%8.3f %10.3f\n", kow, bError ? " " : "", 1 / kow, + printf("One-way %10.3f %s%8.3f %10.3f\n", + kow, + bError ? " " : "", + 1 / kow, calc_dg(1 / kow, temp)); } else { printf(" - Numerical problems computing HB thermodynamics:\n" "sc2 = %g sn2 = %g sk2 = %g sck = %g snk = %g scn = %g\n", - sc2, sn2, sk2, sck, snk, scn); + sc2, + sn2, + sk2, + sck, + snk, + scn); } /* Determine integral of the correlation function */ tau_hb = evaluate_integral(n, t, ct, nullptr, (t[n - 1] - t[0]) / 2, &dtau); - printf("Integral %10.3f %s%8.3f %10.3f\n", 1 / tau_hb, bError ? " " : "", tau_hb, + printf("Integral %10.3f %s%8.3f %10.3f\n", + 1 / tau_hb, + bError ? " " : "", + tau_hb, calc_dg(tau_hb, temp)); e_1 = std::exp(-1.0); for (i = 0; (i < n - 2); i++) @@ -1911,8 +1937,11 @@ void analyse_corr(int n, { /* Determine tau_relax from linear interpolation */ tau_rlx = t[i] - t[0] + (e_1 - ct[i]) * (t[i + 1] - t[i]) / (ct[i + 1] - ct[i]); - printf("Relaxation %10.3f %8.3f %s%10.3f\n", 1 / tau_rlx, tau_rlx, - bError ? " " : "", calc_dg(tau_rlx, temp)); + printf("Relaxation %10.3f %8.3f %s%10.3f\n", + 1 / tau_rlx, + tau_rlx, + bError ? " " : "", + calc_dg(tau_rlx, temp)); } } else @@ -1973,14 +2002,16 @@ static void do_hbac(const char* fn, FILE* fp; int i, j, k, m, ihb, idist, n2, nn; - const char* legLuzar[] = { "Ac\\sfin sys\\v{}\\z{}(t)", "Ac(t)", "Cc\\scontact,hb\\v{}\\z{}(t)", + const char* legLuzar[] = { "Ac\\sfin sys\\v{}\\z{}(t)", + "Ac(t)", + "Cc\\scontact,hb\\v{}\\z{}(t)", "-dAc\\sfs\\v{}\\z{}/dt" }; - gmx_bool bNorm = FALSE; - double nhb = 0; - real * rhbex = nullptr, *ht, *gt, *ght, *dght, *kt; - real * ct, tail, tail2, dtail, *cct; - const real tol = 1e-3; - int nframes = hb->nframes; + gmx_bool bNorm = FALSE; + double nhb = 0; + real * rhbex = nullptr, *ht, *gt, *ght, *dght, *kt; + real * ct, tail, tail2, dtail, *cct; + const real tol = 1e-3; + int nframes = hb->nframes; unsigned int **h = nullptr, **g = nullptr; int nh, nhbonds, nhydro; t_hbond* hbh; @@ -2131,9 +2162,22 @@ static void do_hbac(const char* fn, } /* The autocorrelation function is normalized after summation only */ - low_do_autocorr(nullptr, oenv, nullptr, nframes, 1, -1, &rhbex, - hb->time[1] - hb->time[0], eacNormal, 1, FALSE, bNorm, FALSE, 0, - -1, 0); + low_do_autocorr(nullptr, + oenv, + nullptr, + nframes, + 1, + -1, + &rhbex, + hb->time[1] - hb->time[0], + eacNormal, + 1, + FALSE, + bNorm, + FALSE, + 0, + -1, + 0); /* Cross correlation analysis for thermodynamics */ for (j = nframes; (j < n2); j++) @@ -2176,7 +2220,9 @@ static void do_hbac(const char* fn, printf("\nWARNING: Correlation function is probably not long enough\n" "because the standard deviation in the tail of C(t) > %g\n" "Tail value (average C(t) over second half of acf): %g +/- %g\n", - tol, tail, dtail); + tol, + tail, + dtail); } for (j = 0; (j < nn); j++) { @@ -2204,8 +2250,7 @@ static void do_hbac(const char* fn, for (j = 0; (j < nn); j++) { - fprintf(fp, "%10g %10g %10g %10g %10g\n", hb->time[j] - hb->time[0], ct[j], cct[j], - ght[j], kt[j]); + fprintf(fp, "%10g %10g %10g %10g %10g\n", hb->time[j] - hb->time[0], ct[j], cct[j], ght[j], kt[j]); } xvgrclose(fp); @@ -2436,7 +2481,8 @@ int gmx_hbond(int argc, char* argv[]) "If you set [TT]-shell[tt], you will be asked for an additional index group", "which should contain exactly one atom. In this case, only hydrogen", - "bonds between atoms within the shell distance from the one atom are", "considered.[PAR]", + "bonds between atoms within the shell distance from the one atom are", + "considered.[PAR]", "With option -ac, rate constants for hydrogen bonding can be derived with the", "model of Luzar and Chandler (Nature 379:55, 1996; J. Chem. Phys. 113:23, 2000).", @@ -2444,7 +2490,8 @@ int gmx_hbond(int argc, char* argv[]) "n(t) can be defined as either all pairs that are not within contact distance r at time t", "(corresponding to leaving the -r2 option at the default value 0) or all pairs that", "are within distance r2 (corresponding to setting a second cut-off value with option -r2).", - "See mentioned literature for more details and definitions.", "[PAR]", + "See mentioned literature for more details and definitions.", + "[PAR]", /* "It is also possible to analyse specific hydrogen bonds with", "[TT]-sel[tt]. This index file must contain a group of atom triplets", @@ -2460,7 +2507,9 @@ int gmx_hbond(int argc, char* argv[]) "note also that no check is made for the types of atoms.[PAR]", */ - "[BB]Output:[bb]", "", " * [TT]-num[tt]: number of hydrogen bonds as a function of time.", + "[BB]Output:[bb]", + "", + " * [TT]-num[tt]: number of hydrogen bonds as a function of time.", " * [TT]-ac[tt]: average over all autocorrelations of the existence", " functions (either 0 or 1) of all hydrogen bonds.", " * [TT]-dist[tt]: distance distribution of all hydrogen bonds.", @@ -2474,11 +2523,13 @@ int gmx_hbond(int argc, char* argv[]) " all solvent atoms involved in insertion.", " * [TT]-hbm[tt]: existence matrix for all hydrogen bonds over all", " frames, this also contains information on solvent insertion", - " into hydrogen bonds. Ordering is identical to that in [TT]-hbn[tt]", " index file.", + " into hydrogen bonds. Ordering is identical to that in [TT]-hbn[tt]", + " index file.", " * [TT]-dan[tt]: write out the number of donors and acceptors analyzed for", " each timeframe. This is especially useful when using [TT]-shell[tt].", " * [TT]-nhbdist[tt]: compute the number of HBonds per hydrogen in order to", - " compare results to Raman Spectroscopy.", "", + " compare results to Raman Spectroscopy.", + "", "Note: options [TT]-ac[tt], [TT]-life[tt], [TT]-hbn[tt] and [TT]-hbm[tt]", "require an amount of memory proportional to the total numbers of donors", "times the total number of acceptors in the selected group(s)." @@ -2635,8 +2686,8 @@ int gmx_hbond(int argc, char* argv[]) npargs = asize(pa); ppa = add_acf_pargs(&npargs, pa); - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT, NFILE, fnm, npargs, ppa, - asize(desc), desc, asize(bugs), bugs, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT, NFILE, fnm, npargs, ppa, asize(desc), desc, asize(bugs), bugs, &oenv)) { sfree(ppa); return 0; @@ -2665,8 +2716,11 @@ int gmx_hbond(int argc, char* argv[]) if (opt2bSet("-nhbdist", NFILE, fnm)) { const char* leg[MAXHH + 1] = { "0 HBs", "1 HB", "2 HBs", "3 HBs", "Total" }; - fpnhb = xvgropen(opt2fn("-nhbdist", NFILE, fnm), "Number of donor-H with N HBs", - output_env_get_xvgr_tlabel(oenv), "N", oenv); + fpnhb = xvgropen(opt2fn("-nhbdist", NFILE, fnm), + "Number of donor-H with N HBs", + output_env_get_xvgr_tlabel(oenv), + "N", + oenv); xvgr_legend(fpnhb, asize(leg), leg, oenv); } @@ -2734,8 +2788,7 @@ int gmx_hbond(int argc, char* argv[]) { if (ISINGRP(datable[index[1][i]])) { - gmx_fatal(FARGS, "Partial overlap between groups '%s' and '%s'", grpnames[0], - grpnames[1]); + gmx_fatal(FARGS, "Partial overlap between groups '%s' and '%s'", grpnames[0], grpnames[1]); } } } @@ -2743,13 +2796,19 @@ int gmx_hbond(int argc, char* argv[]) { printf("Calculating %s " "between %s (%d atoms) and %s (%d atoms)\n", - bContact ? "contacts" : "hydrogen bonds", grpnames[0], isize[0], grpnames[1], + bContact ? "contacts" : "hydrogen bonds", + grpnames[0], + isize[0], + grpnames[1], isize[1]); } else { - fprintf(stderr, "Calculating %s in %s (%d atoms)\n", - bContact ? "contacts" : "hydrogen bonds", grpnames[0], isize[0]); + fprintf(stderr, + "Calculating %s in %s (%d atoms)\n", + bContact ? "contacts" : "hydrogen bonds", + grpnames[0], + isize[0]); } } sfree(datable); @@ -2763,10 +2822,9 @@ int gmx_hbond(int argc, char* argv[]) gen_datable(index[i], isize[i], datable, top.atoms.nr); if (bContact) { - search_acceptors(&top, isize[i], index[i], &hb->a, i, bNitAcc, TRUE, - (bTwo && (i == gr0)) || !bTwo, datable); - search_donors(&top, isize[i], index[i], &hb->d, i, TRUE, - (bTwo && (i == gr1)) || !bTwo, datable); + search_acceptors( + &top, isize[i], index[i], &hb->a, i, bNitAcc, TRUE, (bTwo && (i == gr0)) || !bTwo, datable); + search_donors(&top, isize[i], index[i], &hb->d, i, TRUE, (bTwo && (i == gr1)) || !bTwo, datable); } else { @@ -2838,7 +2896,8 @@ int gmx_hbond(int argc, char* argv[]) shatom = shidx[0]; printf("Will calculate hydrogen bonds within a shell " "of %g nm around atom %i\n", - rshell, shatom + 1); + rshell, + shatom + 1); } /* Analyze trajectory */ @@ -2920,9 +2979,34 @@ int gmx_hbond(int argc, char* argv[]) /* Make a thread pool here, * instead of forking anew at every frame. */ -#pragma omp parallel firstprivate(i) private( \ - j, h, ii, hh, xi, yi, zi, xj, yj, zj, threadNr, dist, ang, icell, jcell, grp, ogrp, ai, \ - aj, xjj, yjj, zjj, ihb, resdist, k, bTric, bEdge_xjj, bEdge_yjj) default(shared) +#pragma omp parallel firstprivate(i) private(j, \ + h, \ + ii, \ + hh, \ + xi, \ + yi, \ + zi, \ + xj, \ + yj, \ + zj, \ + threadNr, \ + dist, \ + ang, \ + icell, \ + jcell, \ + grp, \ + ogrp, \ + ai, \ + aj, \ + xjj, \ + yjj, \ + zjj, \ + ihb, \ + resdist, \ + k, \ + bTric, \ + bEdge_xjj, \ + bEdge_yjj) default(shared) { /* Start of parallel region */ if (bOMP) { @@ -2945,8 +3029,7 @@ int gmx_hbond(int argc, char* argv[]) { try { - build_grid(hb, x, x[shatom], bBox, box, hbox, (rcut > r2cut) ? rcut : r2cut, - rshell, ngrid, grid); + build_grid(hb, x, x[shatom], bBox, box, hbox, (rcut > r2cut) ? rcut : r2cut, rshell, ngrid, grid); reset_nhbonds(&(hb->d)); if (debug && bDebug) @@ -2984,8 +3067,8 @@ int gmx_hbond(int argc, char* argv[]) int dd = index[0][i]; int aa = index[0][i + 2]; /* int */ hh = index[0][i + 1]; - ihb = is_hbond(hb, ii, ii, dd, aa, rcut, r2cut, ccut, x, bBox, box, - hbox, &dist, &ang, bDA, &h, bContact, bMerge); + ihb = is_hbond( + hb, ii, ii, dd, aa, rcut, r2cut, ccut, x, bBox, box, hbox, &dist, &ang, bDA, &h, bContact, bMerge); if (ihb) { @@ -3034,7 +3117,8 @@ int gmx_hbond(int argc, char* argv[]) /* loop over all adjacent gridcells (xj,yj,zj) */ for (zjj = grid_loop_begin(ngrid[ZZ], zi, bTric, FALSE); - zjj <= grid_loop_end(ngrid[ZZ], zi, bTric, FALSE); zjj++) + zjj <= grid_loop_end(ngrid[ZZ], zi, bTric, FALSE); + zjj++) { zj = grid_mod(zjj, ngrid[ZZ]); bEdge_yjj = (zj == 0) || (zj == ngrid[ZZ] - 1); @@ -3059,17 +3143,30 @@ int gmx_hbond(int argc, char* argv[]) j = jcell->atoms[aj]; /* check if this once was a h-bond */ - ihb = is_hbond(__HBDATA, grp, ogrp, i, j, - rcut, r2cut, ccut, x, bBox, - box, hbox, &dist, &ang, bDA, - &h, bContact, bMerge); + ihb = is_hbond(__HBDATA, + grp, + ogrp, + i, + j, + rcut, + r2cut, + ccut, + x, + bBox, + box, + hbox, + &dist, + &ang, + bDA, + &h, + bContact, + bMerge); if (ihb) { /* add to index if not already there */ /* Add a hbond */ - add_hbond(__HBDATA, i, j, h, grp, ogrp, - nframes, bMerge, ihb, bContact); + add_hbond(__HBDATA, i, j, h, grp, ogrp, nframes, bMerge, ihb, bContact); /* make angle and distance distributions */ if (ihb == hbHB && !bContact) @@ -3092,7 +3189,8 @@ int gmx_hbond(int argc, char* argv[]) { gmx_fatal( FARGS, - "Invalid donor %d", i); + "Invalid donor %d", + i); } if (acceptor_index(&hb->a, ogrp, j) == NOTSET) @@ -3239,8 +3337,7 @@ int gmx_hbond(int argc, char* argv[]) if (nframes < 2 && (opt2bSet("-ac", NFILE, fnm) || opt2bSet("-life", NFILE, fnm))) { - gmx_fatal(FARGS, - "Cannot calculate autocorrelation of life times with less than two frames"); + gmx_fatal(FARGS, "Cannot calculate autocorrelation of life times with less than two frames"); } free_grid(ngrid, &grid); @@ -3277,7 +3374,9 @@ int gmx_hbond(int argc, char* argv[]) { printf("Found %d different %s in trajectory\n" "Found %d different atom-pairs within %s distance\n", - hb->nrhb, bContact ? "contacts" : "hydrogen bonds", hb->nrdist, + hb->nrhb, + bContact ? "contacts" : "hydrogen bonds", + hb->nrdist, (r2cut > 0) ? "second cut-off" : "hydrogen bonding"); if (bMerge) @@ -3298,8 +3397,11 @@ int gmx_hbond(int argc, char* argv[]) /* Print out number of hbonds and distances */ aver_nhb = 0; aver_dist = 0; - fp = xvgropen(opt2fn("-num", NFILE, fnm), bContact ? "Contacts" : "Hydrogen Bonds", - output_env_get_xvgr_tlabel(oenv), "Number", oenv); + fp = xvgropen(opt2fn("-num", NFILE, fnm), + bContact ? "Contacts" : "Hydrogen Bonds", + output_env_get_xvgr_tlabel(oenv), + "Number", + oenv); snew(leg, 2); snew(leg[0], STRLEN); snew(leg[1], STRLEN); @@ -3329,9 +3431,11 @@ int gmx_hbond(int argc, char* argv[]) sum += rdist[i]; } - fp = xvgropen(opt2fn("-dist", NFILE, fnm), "Hydrogen Bond Distribution", + fp = xvgropen(opt2fn("-dist", NFILE, fnm), + "Hydrogen Bond Distribution", bDA ? "Donor - Acceptor Distance (nm)" : "Hydrogen - Acceptor Distance (nm)", - "", oenv); + "", + oenv); for (i = 0; i < nrbin; i++) { fprintf(fp, "%10g %10g\n", (i + 0.5) * rbin, rdist[i] / (rbin * sum)); @@ -3350,8 +3454,11 @@ int gmx_hbond(int argc, char* argv[]) sum += adist[i]; } - fp = xvgropen(opt2fn("-ang", NFILE, fnm), "Hydrogen Bond Distribution", - "Hydrogen - Donor - Acceptor Angle (\\SO\\N)", "", oenv); + fp = xvgropen(opt2fn("-ang", NFILE, fnm), + "Hydrogen Bond Distribution", + "Hydrogen - Donor - Acceptor Angle (\\SO\\N)", + "", + oenv); for (i = 0; i < nabin; i++) { fprintf(fp, "%10g %10g\n", (i + 0.5) * abin, adist[i] / (abin * sum)); @@ -3362,8 +3469,11 @@ int gmx_hbond(int argc, char* argv[]) /* Print HB in alpha-helix */ if (opt2bSet("-hx", NFILE, fnm)) { - fp = xvgropen(opt2fn("-hx", NFILE, fnm), "Hydrogen Bonds", output_env_get_xvgr_tlabel(oenv), - "Count", oenv); + fp = xvgropen(opt2fn("-hx", NFILE, fnm), + "Hydrogen Bonds", + output_env_get_xvgr_tlabel(oenv), + "Count", + oenv); xvgr_legend(fp, NRHXTYPES, hxtypenames, oenv); for (i = 0; i < nframes; i++) { @@ -3378,7 +3488,9 @@ int gmx_hbond(int argc, char* argv[]) } printf("Average number of %s per timeframe %.3f out of %g possible\n", - bContact ? "contacts" : "hbonds", bContact ? aver_dist : aver_nhb, max_nhb); + bContact ? "contacts" : "hbonds", + bContact ? aver_dist : aver_nhb, + max_nhb); /* Do Autocorrelation etc. */ if (hb->bHBmap) @@ -3393,8 +3505,7 @@ int gmx_hbond(int argc, char* argv[]) } if (opt2bSet("-ac", NFILE, fnm)) { - do_hbac(opt2fn("-ac", NFILE, fnm), hb, nDump, bMerge, bContact, fit_start, temp, - r2cut > 0, oenv, nThreads); + do_hbac(opt2fn("-ac", NFILE, fnm), hb, nDump, bMerge, bContact, fit_start, temp, r2cut > 0, oenv, nThreads); } if (opt2bSet("-life", NFILE, fnm)) { @@ -3481,8 +3592,11 @@ int gmx_hbond(int argc, char* argv[]) #define USE_THIS_GROUP(j) (((j) == gr0) || (bTwo && ((j) == gr1))) - fp = xvgropen(opt2fn("-dan", NFILE, fnm), "Donors and Acceptors", - output_env_get_xvgr_tlabel(oenv), "Count", oenv); + fp = xvgropen(opt2fn("-dan", NFILE, fnm), + "Donors and Acceptors", + output_env_get_xvgr_tlabel(oenv), + "Count", + oenv); nleg = (bTwo ? 2 : 1) * 2; snew(legnames, nleg); i = 0; diff --git a/src/gromacs/gmxana/gmx_helix.cpp b/src/gromacs/gmxana/gmx_helix.cpp index 0b9399ae09..a5362468d4 100644 --- a/src/gromacs/gmxana/gmx_helix.cpp +++ b/src/gromacs/gmxana/gmx_helix.cpp @@ -159,8 +159,8 @@ int gmx_helix(int argc, char* argv[]) }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -176,11 +176,19 @@ int gmx_helix(int argc, char* argv[]) gmx_fatal(FARGS, "Sorry can only run when the number of atoms in the run input file (%d) is equal " "to the number in the trajectory (%d)", - top->atoms.nr, natoms); + top->atoms.nr, + natoms); } - bb = mkbbind(ftp2fn(efNDX, NFILE, fnm), &nres, &nbb, r0, &nall, &allindex, top->atoms.atomname, - top->atoms.atom, top->atoms.resinfo); + bb = mkbbind(ftp2fn(efNDX, NFILE, fnm), + &nres, + &nbb, + r0, + &nall, + &allindex, + top->atoms.atomname, + top->atoms.atom, + top->atoms.resinfo); snew(bbindex, natoms); snew(caindex, nres); @@ -237,8 +245,8 @@ int gmx_helix(int argc, char* argv[]) if (teller == 1) { - write_sto_conf(opt2fn("-cz", NFILE, fnm), "Helix fitted to Z-Axis", &(top->atoms), - x, nullptr, pbcType, box); + write_sto_conf( + opt2fn("-cz", NFILE, fnm), "Helix fitted to Z-Axis", &(top->atoms), x, nullptr, pbcType, box); } xf[efhRAD].val = radius(xf[efhRAD].fp2, nca, caindex, x); @@ -257,8 +265,15 @@ int gmx_helix(int argc, char* argv[]) } av_phipsi(xf[efhPHI].fp, xf[efhPSI].fp, xf[efhPHI].fp2, xf[efhPSI].fp2, t, nres, bb); - av_hblen(xf[efhHB3].fp, xf[efhHB3].fp2, xf[efhHB4].fp, xf[efhHB4].fp2, xf[efhHB5].fp, - xf[efhHB5].fp2, t, nres, bb); + av_hblen(xf[efhHB3].fp, + xf[efhHB3].fp2, + xf[efhHB4].fp, + xf[efhHB4].fp2, + xf[efhHB5].fp, + xf[efhHB5].fp2, + t, + nres, + bb); } } while (read_next_x(oenv, status, &t, x, box)); fprintf(stderr, "\n"); @@ -274,8 +289,7 @@ int gmx_helix(int argc, char* argv[]) fprintf(xf[efhRMSA].fp, "%10d %10g\n", r0 + i, bb[i].rmsa / bb[i].nrms); } fprintf(xf[efhAHX].fp, "%10d %10g\n", r0 + i, (bb[i].nhx * 100.0) / static_cast(teller)); - fprintf(xf[efhJCA].fp, "%10d %10g\n", r0 + i, - 140.3 + (bb[i].jcaha / static_cast(teller))); + fprintf(xf[efhJCA].fp, "%10d %10g\n", r0 + i, 140.3 + (bb[i].jcaha / static_cast(teller))); } for (i = 0; (i < efhNR); i++) diff --git a/src/gromacs/gmxana/gmx_helixorient.cpp b/src/gromacs/gmxana/gmx_helixorient.cpp index c5651ce84a..f225eb1bad 100644 --- a/src/gromacs/gmxana/gmx_helixorient.cpp +++ b/src/gromacs/gmxana/gmx_helixorient.cpp @@ -162,8 +162,8 @@ int gmx_helixorient(int argc, char* argv[]) }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME, NFILE, fnm, NPA, pa, asize(desc), desc, 0, - nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME, NFILE, fnm, NPA, pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -231,17 +231,29 @@ int gmx_helixorient(int argc, char* argv[]) if (bIncremental) { - fptilt = xvgropen(opt2fn("-otilt", NFILE, fnm), "Incremental local helix tilt", "Time(ps)", - "Tilt (degrees)", oenv); - fprotation = xvgropen(opt2fn("-orot", NFILE, fnm), "Incremental local helix rotation", - "Time(ps)", "Rotation (degrees)", oenv); + fptilt = xvgropen(opt2fn("-otilt", NFILE, fnm), + "Incremental local helix tilt", + "Time(ps)", + "Tilt (degrees)", + oenv); + fprotation = xvgropen(opt2fn("-orot", NFILE, fnm), + "Incremental local helix rotation", + "Time(ps)", + "Rotation (degrees)", + oenv); } else { - fptilt = xvgropen(opt2fn("-otilt", NFILE, fnm), "Cumulative local helix tilt", "Time(ps)", - "Tilt (degrees)", oenv); - fprotation = xvgropen(opt2fn("-orot", NFILE, fnm), "Cumulative local helix rotation", - "Time(ps)", "Rotation (degrees)", oenv); + fptilt = xvgropen(opt2fn("-otilt", NFILE, fnm), + "Cumulative local helix tilt", + "Time(ps)", + "Tilt (degrees)", + oenv); + fprotation = xvgropen(opt2fn("-orot", NFILE, fnm), + "Cumulative local helix rotation", + "Time(ps)", + "Rotation (degrees)", + oenv); } clear_rvecs(3, unitaxes); @@ -357,10 +369,16 @@ int gmx_helixorient(int argc, char* argv[]) rvec_sub(bSC ? x_SC[i] : x_CA[i], residueorigin[i], residuevector[i]); svmul(1.0 / norm(residuevector[i]), residuevector[i], residuevector[i]); cprod(residuehelixaxis[i], residuevector[i], axis3[i]); - fprintf(fpaxis, "%15.12g %15.12g %15.12g ", residuehelixaxis[i][0], - residuehelixaxis[i][1], residuehelixaxis[i][2]); - fprintf(fpcenter, "%15.12g %15.12g %15.12g ", residueorigin[i][0], - residueorigin[i][1], residueorigin[i][2]); + fprintf(fpaxis, + "%15.12g %15.12g %15.12g ", + residuehelixaxis[i][0], + residuehelixaxis[i][1], + residuehelixaxis[i][2]); + fprintf(fpcenter, + "%15.12g %15.12g %15.12g ", + residueorigin[i][0], + residueorigin[i][1], + residueorigin[i][2]); fprintf(fprise, "%15.12g ", residuerise[i]); fprintf(fpradius, "%15.12g ", residueradius[i]); diff --git a/src/gromacs/gmxana/gmx_hydorder.cpp b/src/gromacs/gmxana/gmx_hydorder.cpp index 9e45a5ba7d..6cf1c4e6c3 100644 --- a/src/gromacs/gmxana/gmx_hydorder.cpp +++ b/src/gromacs/gmxana/gmx_hydorder.cpp @@ -366,8 +366,8 @@ static void calc_tetra_order_interface(const char* fnNDX, } } - find_tetra_order_grid(top, pbcType, natoms, box, x, isize[0], index[0], &sg, &sk, *nslicex, - *nslicey, nslicez, sg_grid, sk_grid); + find_tetra_order_grid( + top, pbcType, natoms, box, x, isize[0], index[0], &sg, &sk, *nslicex, *nslicey, nslicez, sg_grid, sk_grid); GMX_RELEASE_ASSERT(sk_fravg != nullptr, "Trying to dereference NULL sk_fravg pointer"); for (i = 0; i < *nslicex; i++) { @@ -401,10 +401,10 @@ static void calc_tetra_order_interface(const char* fnNDX, /*Debugging for printing out the entire order parameter meshes.*/ if (debug) { - fpsg = xvgropen("sg_ang_mesh", "S\\sg\\N Angle Order Parameter / Meshpoint", "(nm)", - "S\\sg\\N", oenv); - fpsk = xvgropen("sk_dist_mesh", "S\\sk\\N Distance Order Parameter / Meshpoint", "(nm)", - "S\\sk\\N", oenv); + fpsg = xvgropen( + "sg_ang_mesh", "S\\sg\\N Angle Order Parameter / Meshpoint", "(nm)", "S\\sg\\N", oenv); + fpsk = xvgropen( + "sk_dist_mesh", "S\\sk\\N Distance Order Parameter / Meshpoint", "(nm)", "S\\sk\\N", oenv); for (n = 0; n < (*nframes); n++) { fprintf(fpsg, "%i\n", n); @@ -415,12 +415,18 @@ static void calc_tetra_order_interface(const char* fnNDX, { for (k = 0; k < nslicez; k++) { - fprintf(fpsg, "%4f %4f %4f %8f\n", (i + 0.5) * box[XX][XX] / (*nslicex), + fprintf(fpsg, + "%4f %4f %4f %8f\n", + (i + 0.5) * box[XX][XX] / (*nslicex), (j + 0.5) * box[YY][YY] / (*nslicey), - (k + 0.5) * box[ZZ][ZZ] / nslicez, sg_4d[n][i][j][k]); - fprintf(fpsk, "%4f %4f %4f %8f\n", (i + 0.5) * box[XX][XX] / (*nslicex), + (k + 0.5) * box[ZZ][ZZ] / nslicez, + sg_4d[n][i][j][k]); + fprintf(fpsk, + "%4f %4f %4f %8f\n", + (i + 0.5) * box[XX][XX] / (*nslicex), (j + 0.5) * box[YY][YY] / (*nslicey), - (k + 0.5) * box[ZZ][ZZ] / nslicez, sk_4d[n][i][j][k]); + (k + 0.5) * box[ZZ][ZZ] / nslicez, + sk_4d[n][i][j][k]); } } } @@ -549,10 +555,8 @@ static void writesurftoxpms(real*** surf, } } - write_xpm(xpmfile1, 3, numbuf, "Height", "x[nm]", "y[nm]", xbins, ybins, xticks, yticks, - profile1, min1, max1, lo, hi, &maplevels); - write_xpm(xpmfile2, 3, numbuf, "Height", "x[nm]", "y[nm]", xbins, ybins, xticks, yticks, - profile2, min2, max2, lo, hi, &maplevels); + write_xpm(xpmfile1, 3, numbuf, "Height", "x[nm]", "y[nm]", xbins, ybins, xticks, yticks, profile1, min1, max1, lo, hi, &maplevels); + write_xpm(xpmfile2, 3, numbuf, "Height", "x[nm]", "y[nm]", xbins, ybins, xticks, yticks, profile2, min2, max2, lo, hi, &maplevels); } gmx_ffclose(xpmfile1); @@ -643,8 +647,8 @@ int gmx_hydorder(int argc, char* argv[]) const char * ndxfnm, *tpsfnm, *trxfnm; gmx_output_env_t* oenv; - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -694,8 +698,8 @@ int gmx_hydorder(int argc, char* argv[]) { gmx_fatal(FARGS, "No or not correct number (2) of output-files: %td", intfn.ssize()); } - calc_tetra_order_interface(ndxfnm, tpsfnm, trxfnm, binwidth, nsttblock, &frames, &xslices, - &yslices, sg1, sg2, &intfpos, oenv); + calc_tetra_order_interface( + ndxfnm, tpsfnm, trxfnm, binwidth, nsttblock, &frames, &xslices, &yslices, sg1, sg2, &intfpos, oenv); writesurftoxpms(intfpos, frames, xslices, yslices, binwidth, intfn, nlevels); if (bFourier) diff --git a/src/gromacs/gmxana/gmx_lie.cpp b/src/gromacs/gmxana/gmx_lie.cpp index 7ad065cbf8..580de7876c 100644 --- a/src/gromacs/gmxana/gmx_lie.cpp +++ b/src/gromacs/gmxana/gmx_lie.cpp @@ -184,8 +184,8 @@ int gmx_lie(int argc, char* argv[]) t_filenm fnm[] = { { efEDR, "-f", "ener", ffREAD }, { efXVG, "-o", "lie", ffWRITE } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, NPA, pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, NPA, pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -196,8 +196,8 @@ int gmx_lie(int argc, char* argv[]) ld = analyze_names(nre, enm, ligand); snew(fr, 1); - out = xvgropen(ftp2fn(efXVG, NFILE, fnm), "LIE free energy estimate", "Time (ps)", - "DGbind (kJ/mol)", oenv); + out = xvgropen( + ftp2fn(efXVG, NFILE, fnm), "LIE free energy estimate", "Time (ps)", "DGbind (kJ/mol)", oenv); while (do_enx(fp, fr)) { ct = check_times(fr->t); @@ -216,7 +216,8 @@ int gmx_lie(int argc, char* argv[]) if (nframes > 0) { - printf("DGbind = %.3f (%.3f)\n", lieaver / nframes, + printf("DGbind = %.3f (%.3f)\n", + lieaver / nframes, std::sqrt(lieav2 / nframes - gmx::square(lieaver / nframes))); } diff --git a/src/gromacs/gmxana/gmx_make_edi.cpp b/src/gromacs/gmxana/gmx_make_edi.cpp index 288cff7fed..7f154cd85e 100644 --- a/src/gromacs/gmxana/gmx_make_edi.cpp +++ b/src/gromacs/gmxana/gmx_make_edi.cpp @@ -304,19 +304,26 @@ static int sscan_list(int* list[], const char* str, const char* listname) /* format error occured */ case sError: - gmx_fatal(FARGS, "Error in the list of eigenvectors for %s at pos %td with char %c", - listname, pos - startpos, *(pos - 1)); + gmx_fatal(FARGS, + "Error in the list of eigenvectors for %s at pos %td with char %c", + listname, + pos - startpos, + *(pos - 1)); /* logical error occured */ case sZero: gmx_fatal(FARGS, "Error in the list of eigenvectors for %s at pos %td: eigenvector 0 is " "not valid", - listname, pos - startpos); + listname, + pos - startpos); case sSmaller: gmx_fatal(FARGS, "Error in the list of eigenvectors for %s at pos %td: second index %d is " "not bigger than %d", - listname, pos - startpos, end_number, number); + listname, + pos - startpos, + end_number, + number); } ++pos; /* read next character */ } /*scanner has finished */ @@ -369,7 +376,8 @@ write_eigvec(FILE* fp, int natoms, int eig_list[], rvec** eigvecs, int nvec, con gmx_fatal(FARGS, "Selected eigenvector %d is higher than maximum number %d of available " "eigenvectors", - eig_list[n], nvec); + eig_list[n], + nvec); } copy_rvec(eigvecs[eig_list[n] - 1][i], x); fprintf(fp, "%8.5f %8.5f %8.5f\n", x[XX], x[YY], x[ZZ]); @@ -405,16 +413,25 @@ static void write_the_whole_thing(FILE* fp, /* write edi-file */ /*Header*/ - fprintf(fp, "#MAGIC\n %d \n#NINI\n %d\n#FITMAS\n %d\n#ANALYSIS_MAS\n %d\n", MAGIC, edpars->nini, - int(edpars->fitmas), int(edpars->pcamas)); - fprintf(fp, "#OUTFRQ\n %d\n#MAXLEN\n %d\n#SLOPECRIT\n %f\n", edpars->outfrq, edpars->maxedsteps, - edpars->slope); + fprintf(fp, + "#MAGIC\n %d \n#NINI\n %d\n#FITMAS\n %d\n#ANALYSIS_MAS\n %d\n", + MAGIC, + edpars->nini, + int(edpars->fitmas), + int(edpars->pcamas)); + fprintf(fp, "#OUTFRQ\n %d\n#MAXLEN\n %d\n#SLOPECRIT\n %f\n", edpars->outfrq, edpars->maxedsteps, edpars->slope); fprintf(fp, "#PRESTEPS\n %d\n#DELTA_F0\n %f\n#INIT_DELTA_F\n %f\n#TAU\n %f\n#EFL_NULL\n " "%f\n#ALPHA2\n %f\n#KT\n %f\n#HARMONIC\n %d\n#CONST_FORCE_FLOODING\n %d\n", - edpars->presteps, edpars->flood.deltaF0, edpars->flood.deltaF, edpars->flood.tau, - edpars->flood.constEfl, edpars->flood.alpha2, edpars->flood.kT, - int(edpars->flood.bHarmonic), int(edpars->flood.bConstForce)); + edpars->presteps, + edpars->flood.deltaF0, + edpars->flood.deltaF, + edpars->flood.tau, + edpars->flood.constEfl, + edpars->flood.alpha2, + edpars->flood.kT, + int(edpars->flood.bHarmonic), + int(edpars->flood.bConstForce)); /* Average and reference positions */ write_t_edx(fp, edpars->sref, "NREF, XREF"); @@ -423,16 +440,12 @@ static void write_the_whole_thing(FILE* fp, /*Eigenvectors */ write_eigvec(fp, edpars->ned, eig_listen[evMON], eigvecs, nvec, "COMPONENTS GROUP 1", nullptr); - write_eigvec(fp, edpars->ned, eig_listen[evLINFIX], eigvecs, nvec, "COMPONENTS GROUP 2", - evStepList[evLINFIX]); - write_eigvec(fp, edpars->ned, eig_listen[evLINACC], eigvecs, nvec, "COMPONENTS GROUP 3", - evStepList[evLINACC]); - write_eigvec(fp, edpars->ned, eig_listen[evRADFIX], eigvecs, nvec, "COMPONENTS GROUP 4", - evStepList[evRADFIX]); + write_eigvec(fp, edpars->ned, eig_listen[evLINFIX], eigvecs, nvec, "COMPONENTS GROUP 2", evStepList[evLINFIX]); + write_eigvec(fp, edpars->ned, eig_listen[evLINACC], eigvecs, nvec, "COMPONENTS GROUP 3", evStepList[evLINACC]); + write_eigvec(fp, edpars->ned, eig_listen[evRADFIX], eigvecs, nvec, "COMPONENTS GROUP 4", evStepList[evRADFIX]); write_eigvec(fp, edpars->ned, eig_listen[evRADACC], eigvecs, nvec, "COMPONENTS GROUP 5", nullptr); write_eigvec(fp, edpars->ned, eig_listen[evRADCON], eigvecs, nvec, "COMPONENTS GROUP 6", nullptr); - write_eigvec(fp, edpars->ned, eig_listen[evFLOOD], eigvecs, nvec, "COMPONENTS GROUP 7", - evStepList[evFLOOD]); + write_eigvec(fp, edpars->ned, eig_listen[evFLOOD], eigvecs, nvec, "COMPONENTS GROUP 7", evStepList[evFLOOD]); /*Target and Origin positions */ @@ -600,7 +613,8 @@ static void get_structure(const t_atoms* atoms, ntar = read_conffile(StructureFile, &xtar); printf("Select an index group of %d elements that corresponds to the atoms in the structure " "file %s\n", - ntar, StructureFile); + ntar, + StructureFile); get_index(atoms, IndexFile, 1, &ngro, &igro, &grpname); if (ngro != ntar) { @@ -930,15 +944,15 @@ int gmx_make_edi(int argc, char* argv[]) if (opt2parg_bSet(evOptions[ev_class], NPA, pa)) { /*get list of eigenvectors*/ - nvecs = sscan_list(&(listen[ev_class]), opt2parg_str(evOptions[ev_class], NPA, pa), - evOptions[ev_class]); + nvecs = sscan_list( + &(listen[ev_class]), opt2parg_str(evOptions[ev_class], NPA, pa), evOptions[ev_class]); if (ev_class < evStepNr - 2) { /*if apropriate get list of stepsizes for these eigenvectors*/ if (opt2parg_bSet(evStepOptions[ev_class], NPA, pa)) { - evStepList[ev_class] = scan_vecparams(opt2parg_str(evStepOptions[ev_class], NPA, pa), - evStepOptions[ev_class], nvecs); + evStepList[ev_class] = scan_vecparams( + opt2parg_str(evStepOptions[ev_class], NPA, pa), evStepOptions[ev_class], nvecs); } else /*if list is not given fill with zeros */ { @@ -996,8 +1010,8 @@ int gmx_make_edi(int argc, char* argv[]) EigvecFile = opt2fn("-f", NFILE, fnm); /*read eigenvectors from eigvec.trr*/ - read_eigenvectors(EigvecFile, &nav, &bFit1, &xref1, &edi_params.fitmas, &xav1, - &edi_params.pcamas, &nvec1, &eignr1, &eigvec1, &eigval1); + read_eigenvectors( + EigvecFile, &nav, &bFit1, &xref1, &edi_params.fitmas, &xav1, &edi_params.pcamas, &nvec1, &eignr1, &eigvec1, &eigval1); read_tps_conf(ftp2fn(efTPS, NFILE, fnm), &top, &pbcType, &xtop, nullptr, topbox, false); atoms = &top.atoms; @@ -1052,8 +1066,8 @@ int gmx_make_edi(int argc, char* argv[]) if (listen[evFLOOD][0] != 0) { - read_eigenvalues(listen[evFLOOD], opt2fn("-eig", NFILE, fnm), evStepList[evFLOOD], - bHesse, kB * T, nav); + read_eigenvalues( + listen[evFLOOD], opt2fn("-eig", NFILE, fnm), evStepList[evFLOOD], bHesse, kB * T, nav); } edi_params.flood.tau = tau; diff --git a/src/gromacs/gmxana/gmx_mdmat.cpp b/src/gromacs/gmxana/gmx_mdmat.cpp index a6a9058d7a..dd567d225e 100644 --- a/src/gromacs/gmxana/gmx_mdmat.cpp +++ b/src/gromacs/gmxana/gmx_mdmat.cpp @@ -229,8 +229,8 @@ int gmx_mdmat(int argc, char* argv[]) gmx_output_env_t* oenv; gmx_rmpbc_t gpbc = nullptr; - if (!parse_common_args(&argc, argv, PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, - 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -268,9 +268,13 @@ int gmx_mdmat(int argc, char* argv[]) useatoms.resinfo[i] = top.atoms.resinfo[prevres]; if (debug) { - fprintf(debug, "New residue: atom %5s %5s %6d, index entry %5d, newres %5d\n", + fprintf(debug, + "New residue: atom %5s %5s %6d, index entry %5d, newres %5d\n", *(top.atoms.resinfo[top.atoms.atom[ii].resind].name), - *(top.atoms.atomname[ii]), ii, i, newres); + *(top.atoms.atomname[ii]), + ii, + i, + newres); } } useatoms.atom[i].resind = newres; @@ -344,8 +348,22 @@ int gmx_mdmat(int argc, char* argv[]) if (bFrames) { sprintf(label, "t=%.0f ps", t); - write_xpm(out, 0, label, "Distance (nm)", "Residue Index", "Residue Index", nres, nres, - resnr, resnr, mdmat, 0, truncate, rlo, rhi, &nlevels); + write_xpm(out, + 0, + label, + "Distance (nm)", + "Residue Index", + "Residue Index", + nres, + nres, + resnr, + resnr, + mdmat, + 0, + truncate, + rlo, + rhi, + &nlevels); } } while (read_next_x(oenv, status, &t, x, box)); fprintf(stderr, "\n"); @@ -365,9 +383,22 @@ int gmx_mdmat(int argc, char* argv[]) totmdmat[i][j] /= nframes; } } - write_xpm(opt2FILE("-mean", NFILE, fnm, "w"), 0, "Mean smallest distance", "Distance (nm)", - "Residue Index", "Residue Index", nres, nres, resnr, resnr, totmdmat, 0, truncate, - rlo, rhi, &nlevels); + write_xpm(opt2FILE("-mean", NFILE, fnm, "w"), + 0, + "Mean smallest distance", + "Distance (nm)", + "Residue Index", + "Residue Index", + nres, + nres, + resnr, + resnr, + totmdmat, + 0, + truncate, + rlo, + rhi, + &nlevels); if (bCalcN) { @@ -379,8 +410,8 @@ int gmx_mdmat(int argc, char* argv[]) snew(legend[i], STRLEN); } tot_nmat(nres, natoms, nframes, totnmat, tot_n, mean_n); - fp = xvgropen(ftp2fn(efXVG, NFILE, fnm), "Increase in number of contacts", "Residue", - "Ratio", oenv); + fp = xvgropen( + ftp2fn(efXVG, NFILE, fnm), "Increase in number of contacts", "Residue", "Ratio", oenv); sprintf(legend[0], "Total/mean"); sprintf(legend[1], "Total"); sprintf(legend[2], "Mean"); @@ -397,8 +428,14 @@ int gmx_mdmat(int argc, char* argv[]) { ratio = tot_n[i] / mean_n[i]; } - fprintf(fp, "%3d %8.3f %3d %8.3f %3d %8.3f\n", i + 1, ratio, tot_n[i], mean_n[i], - natm[i], mean_n[i] / natm[i]); + fprintf(fp, + "%3d %8.3f %3d %8.3f %3d %8.3f\n", + i + 1, + ratio, + tot_n[i], + mean_n[i], + natm[i], + mean_n[i] / natm[i]); } xvgrclose(fp); } diff --git a/src/gromacs/gmxana/gmx_mindist.cpp b/src/gromacs/gmxana/gmx_mindist.cpp index ed51f851d9..4fae525630 100644 --- a/src/gromacs/gmxana/gmx_mindist.cpp +++ b/src/gromacs/gmxana/gmx_mindist.cpp @@ -161,8 +161,11 @@ static void periodic_mindist_plot(const char* trxfn, check_index(nullptr, n, index, nullptr, natoms); - out = xvgropen(outfn, "Minimum distance to periodic image", output_env_get_time_label(oenv), - "Distance (nm)", oenv); + out = xvgropen(outfn, + "Minimum distance to periodic image", + output_env_get_time_label(oenv), + "Distance (nm)", + oenv); if (output_env_get_print_xvgr_codes(oenv)) { fprintf(out, "@ subtitle \"and maximum internal distance\"\n"); @@ -197,8 +200,14 @@ static void periodic_mindist_plot(const char* trxfn, { fprintf(out, "%s\n", output_env_get_print_xvgr_codes(oenv) ? "&" : ""); } - fprintf(out, "\t%g\t%6.3f %6.3f %6.3f %6.3f %6.3f\n", output_env_conv_time(oenv, t), rmin, - rmax, norm(box[0]), norm(box[1]), norm(box[2])); + fprintf(out, + "\t%g\t%6.3f %6.3f %6.3f %6.3f %6.3f\n", + output_env_conv_time(oenv, t), + rmin, + rmax, + norm(box[0]), + norm(box[1]), + norm(box[2])); bFirst = FALSE; } while (read_next_x(oenv, status, &t, x, box)); @@ -212,8 +221,11 @@ static void periodic_mindist_plot(const char* trxfn, fprintf(stdout, "\nThe shortest periodic distance is %g (nm) at time %g (%s),\n" "between atoms %d and %d\n", - rmint, output_env_conv_time(oenv, tmint), output_env_get_time_unit(oenv).c_str(), - index[ind_mini] + 1, index[ind_minj] + 1); + rmint, + output_env_conv_time(oenv, tmint), + output_env_get_time_unit(oenv).c_str(), + index[ind_mini] + 1, + index[ind_minj] + 1); } static void calc_dist(real rcut, @@ -450,7 +462,8 @@ static void dist_plot(const char* fn, for (j = 0; j < nres; j++) { - fprintf(respertime, "%s%d ", + fprintf(respertime, + "%s%d ", *(atoms->resinfo[atoms->atom[index[0][residue[j]]].resind].name), atoms->atom[index[0][residue[j]]].resind); } @@ -498,8 +511,24 @@ static void dist_plot(const char* fn, { if (ng == 1) { - calc_dist(rcut, bPBC, pbcType, box, x0, gnx[0], gnx[0], index[0], index[0], bGroup, - &dmin, &dmax, &nmin, &nmax, &min1, &min2, &max1, &max2); + calc_dist(rcut, + bPBC, + pbcType, + box, + x0, + gnx[0], + gnx[0], + index[0], + index[0], + bGroup, + &dmin, + &dmax, + &nmin, + &nmax, + &min1, + &min2, + &max1, + &max2); fprintf(dist, " %12e", bMin ? dmin : dmax); if (num) { @@ -512,8 +541,24 @@ static void dist_plot(const char* fn, { for (k = i + 1; (k < ng); k++) { - calc_dist(rcut, bPBC, pbcType, box, x0, gnx[i], gnx[k], index[i], index[k], - bGroup, &dmin, &dmax, &nmin, &nmax, &min1, &min2, &max1, &max2); + calc_dist(rcut, + bPBC, + pbcType, + box, + x0, + gnx[i], + gnx[k], + index[i], + index[k], + bGroup, + &dmin, + &dmax, + &nmin, + &nmax, + &min1, + &min2, + &max1, + &max2); fprintf(dist, " %12e", bMin ? dmin : dmax); if (num) { @@ -528,8 +573,24 @@ static void dist_plot(const char* fn, GMX_RELEASE_ASSERT(ng > 1, "Must have more than one group when not using -matrix"); for (i = 1; (i < ng); i++) { - calc_dist(rcut, bPBC, pbcType, box, x0, gnx[0], gnx[i], index[0], index[i], bGroup, - &dmin, &dmax, &nmin, &nmax, &min1, &min2, &max1, &max2); + calc_dist(rcut, + bPBC, + pbcType, + box, + x0, + gnx[0], + gnx[i], + index[0], + index[i], + bGroup, + &dmin, + &dmax, + &nmin, + &nmax, + &min1, + &min2, + &max1, + &max2); fprintf(dist, " %12e", bMin ? dmin : dmax); if (num) { @@ -539,9 +600,24 @@ static void dist_plot(const char* fn, { for (j = 0; j < nres; j++) { - calc_dist(rcut, bPBC, pbcType, box, x0, residue[j + 1] - residue[j], gnx[i], - &(index[0][residue[j]]), index[i], bGroup, &dmin, &dmax, &nmin, - &nmax, &min1r, &min2r, &max1r, &max2r); + calc_dist(rcut, + bPBC, + pbcType, + box, + x0, + residue[j + 1] - residue[j], + gnx[i], + &(index[0][residue[j]]), + index[i], + bGroup, + &dmin, + &dmax, + &nmin, + &nmax, + &min1r, + &min2r, + &max1r, + &max2r); mindres[i - 1][j] = std::min(mindres[i - 1][j], dmin); maxdres[i - 1][j] = std::max(maxdres[i - 1][j], dmax); } @@ -557,8 +633,11 @@ static void dist_plot(const char* fn, { if (atm) { - fprintf(atm, "%12e %12d %12d\n", output_env_conv_time(oenv, t), - 1 + (bMin ? min1 : max1), 1 + (bMin ? min2 : max2)); + fprintf(atm, + "%12e %12d %12d\n", + output_env_conv_time(oenv, t), + 1 + (bMin ? min1 : max1), + 1 + (bMin ? min2 : max2)); } } @@ -755,8 +834,18 @@ int gmx_mindist(int argc, char* argv[]) { efTRO, "-ox", "mindist", ffOPTWR }, { efXVG, "-or", "mindistres", ffOPTWR } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME | PCA_TIME_UNIT, NFILE, fnm, - asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args(&argc, + argv, + PCA_CAN_VIEW | PCA_CAN_TIME | PCA_TIME_UNIT, + NFILE, + fnm, + asize(pa), + pa, + asize(desc), + desc, + 0, + nullptr, + &oenv)) { return 0; } @@ -848,9 +937,29 @@ int gmx_mindist(int argc, char* argv[]) } else { - dist_plot(trxfnm, atmfnm, distfnm, numfnm, resfnm, oxfnm, rcutoff, bMat, - top ? &(top->atoms) : nullptr, ng, index, gnx, grpname, bSplit, !bMax, nres, - residues, bPBC, pbcType, bGroup, bEachResEachTime, bPrintResName, oenv); + dist_plot(trxfnm, + atmfnm, + distfnm, + numfnm, + resfnm, + oxfnm, + rcutoff, + bMat, + top ? &(top->atoms) : nullptr, + ng, + index, + gnx, + grpname, + bSplit, + !bMax, + nres, + residues, + bPBC, + pbcType, + bGroup, + bEachResEachTime, + bPrintResName, + oenv); } do_view(oenv, distfnm, "-nxy"); diff --git a/src/gromacs/gmxana/gmx_msd.cpp b/src/gromacs/gmxana/gmx_msd.cpp index 964888ada0..b5d7061933 100644 --- a/src/gromacs/gmxana/gmx_msd.cpp +++ b/src/gromacs/gmxana/gmx_msd.cpp @@ -207,9 +207,15 @@ static void corr_print(t_corr* curr, out = xvgropen(fn, title, output_env_get_xvgr_tlabel(oenv), yaxis, oenv); if (DD) { - fprintf(out, "# MSD gathered over %g %s with %d restarts\n", msdtime, - output_env_get_time_unit(oenv).c_str(), curr->nrestart); - fprintf(out, "# Diffusion constants fitted from time %g to %g %s\n", beginfit, endfit, + fprintf(out, + "# MSD gathered over %g %s with %d restarts\n", + msdtime, + output_env_get_time_unit(oenv).c_str(), + curr->nrestart); + fprintf(out, + "# Diffusion constants fitted from time %g to %g %s\n", + beginfit, + endfit, output_env_get_time_unit(oenv).c_str()); for (i = 0; i < curr->ngrp; i++) { @@ -224,9 +230,14 @@ static void corr_print(t_corr* curr, fprintf(out, " %10g", curr->data[j][i]); if (bTen) { - fprintf(out, " %10g %10g %10g %10g %10g %10g", curr->datam[j][i][XX][XX], - curr->datam[j][i][YY][YY], curr->datam[j][i][ZZ][ZZ], curr->datam[j][i][YY][XX], - curr->datam[j][i][ZZ][XX], curr->datam[j][i][ZZ][YY]); + fprintf(out, + " %10g %10g %10g %10g %10g %10g", + curr->datam[j][i][XX][XX], + curr->datam[j][i][YY][YY], + curr->datam[j][i][ZZ][ZZ], + curr->datam[j][i][YY][XX], + curr->datam[j][i][ZZ][XX], + curr->datam[j][i][ZZ][YY]); } } fprintf(out, "\n"); @@ -628,8 +639,7 @@ static void printmol(t_corr* curr, Dav /= curr->nmol; D2av /= curr->nmol; VarD = D2av - gmx::square(Dav); - printf(" = %.4f Std. Dev. = %.4f Error = %.4f\n", Dav, std::sqrt(VarD), - std::sqrt(VarD / curr->nmol)); + printf(" = %.4f Std. Dev. = %.4f Error = %.4f\n", Dav, std::sqrt(VarD), std::sqrt(VarD / curr->nmol)); if (fn_pdb && x) { @@ -692,7 +702,8 @@ static int corr_loop(t_corr* curr, fprintf(stderr, "WARNING: The trajectory only contains part of the system (%d of %d atoms) and " "therefore the COM motion of only this part of the system will be removed\n", - natoms, top->atoms.nr); + natoms, + top->atoms.nr); } snew(x[prev], natoms); @@ -849,8 +860,11 @@ static int corr_loop(t_corr* curr, curr->nframes++; } while (read_next_x(oenv, status, &t, x[cur], box)); - fprintf(stderr, "\nUsed %d restart points spaced %g %s over %g %s\n\n", curr->nrestart, - output_env_conv_time(oenv, dt), output_env_get_time_unit(oenv).c_str(), + fprintf(stderr, + "\nUsed %d restart points spaced %g %s over %g %s\n\n", + curr->nrestart, + output_env_conv_time(oenv, dt), + output_env_get_time_unit(oenv).c_str(), output_env_conv_time(oenv, curr->time[curr->nframes - 1]), output_env_get_time_unit(oenv).c_str()); @@ -952,12 +966,25 @@ static void do_corr(const char* trx_file, index_atom2mol(&gnx[0], index[0], &top->mols); } - msd = std::make_unique(nrgrp, type, axis, dim_factor, mol_file == nullptr ? 0 : gnx[0], - bTen, bMW, dt, top, beginfit, endfit); - - nat_trx = corr_loop(msd.get(), trx_file, top, pbcType, mol_file ? gnx[0] != 0 : false, gnx.data(), - index, (mol_file != nullptr) ? calc1_mol : (bMW ? calc1_mw : calc1_norm), - bTen, gnx_com, index_com, dt, t_pdb, pdb_file ? &x : nullptr, box, oenv); + msd = std::make_unique( + nrgrp, type, axis, dim_factor, mol_file == nullptr ? 0 : gnx[0], bTen, bMW, dt, top, beginfit, endfit); + + nat_trx = corr_loop(msd.get(), + trx_file, + top, + pbcType, + mol_file ? gnx[0] != 0 : false, + gnx.data(), + index, + (mol_file != nullptr) ? calc1_mol : (bMW ? calc1_mw : calc1_norm), + bTen, + gnx_com, + index_com, + dt, + t_pdb, + pdb_file ? &x : nullptr, + box, + oenv); /* Correct for the number of points */ for (j = 0; (j < msd->ngrp); j++) @@ -979,7 +1006,8 @@ static void do_corr(const char* trx_file, fprintf(stderr, "\nNo frame found need time tpdb = %g ps\n" "Can not write %s\n\n", - t_pdb, pdb_file); + t_pdb, + pdb_file); } i = top->atoms.nr; top->atoms.nr = nat_trx; @@ -1010,8 +1038,7 @@ static void do_corr(const char* trx_file, { for (i1 = i0; i1 < msd->nframes && msd->time[i1] <= endfit; i1++) {} } - fprintf(stdout, "Fitting from %g to %g %s\n\n", beginfit, endfit, - output_env_get_time_unit(oenv).c_str()); + fprintf(stdout, "Fitting from %g to %g %s\n\n", beginfit, endfit, output_env_get_time_unit(oenv).c_str()); N = i1 - i0; if (N <= 2) @@ -1051,8 +1078,18 @@ static void do_corr(const char* trx_file, } } /* Print mean square displacement */ - corr_print(msd.get(), bTen, msd_file, "Mean Square Displacement", "MSD (nm\\S2\\N)", - msd->time[msd->nframes - 1], beginfit, endfit, DD.data(), SigmaD.data(), grpname, oenv); + corr_print(msd.get(), + bTen, + msd_file, + "Mean Square Displacement", + "MSD (nm\\S2\\N)", + msd->time[msd->nframes - 1], + beginfit, + endfit, + DD.data(), + SigmaD.data(), + grpname, + oenv); } int gmx_msd(int argc, char* argv[]) @@ -1147,8 +1184,18 @@ int gmx_msd(int argc, char* argv[]) real dim_factor; gmx_output_env_t* oenv; - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_BEGIN | PCA_CAN_END | PCA_TIME_UNIT, - NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args(&argc, + argv, + PCA_CAN_VIEW | PCA_CAN_BEGIN | PCA_CAN_END | PCA_TIME_UNIT, + NFILE, + fnm, + asize(pa), + pa, + asize(desc), + desc, + 0, + nullptr, + &oenv)) { return 0; } @@ -1217,8 +1264,25 @@ int gmx_msd(int argc, char* argv[]) gmx_fatal(FARGS, "Could not read a topology from %s. Try a tpr file instead.", tps_file); } - do_corr(trx_file, ndx_file, msd_file, mol_file, pdb_file, t_pdb, ngroup, &top, pbcType, bTen, - bMW, bRmCOMM, type, dim_factor, axis, dt, beginfit, endfit, oenv); + do_corr(trx_file, + ndx_file, + msd_file, + mol_file, + pdb_file, + t_pdb, + ngroup, + &top, + pbcType, + bTen, + bMW, + bRmCOMM, + type, + dim_factor, + axis, + dt, + beginfit, + endfit, + oenv); done_top(&top); view_all(oenv, NFILE, fnm); diff --git a/src/gromacs/gmxana/gmx_nmeig.cpp b/src/gromacs/gmxana/gmx_nmeig.cpp index 2df043607d..560425e38e 100644 --- a/src/gromacs/gmxana/gmx_nmeig.cpp +++ b/src/gromacs/gmxana/gmx_nmeig.cpp @@ -271,7 +271,10 @@ static real* allocateEigenvectors(int nrow, int first, int last, bool ignoreBegi gmx_fatal(FARGS, "You asked to store %d eigenvectors of size %d, which requires more than the " "supported %d elements; %sdecrease -last", - numVector, nrow, INT_MAX, ignoreBegin ? "" : "increase -first and/or "); + numVector, + nrow, + INT_MAX, + ignoreBegin ? "" : "increase -first and/or "); } real* eigenvectors; @@ -589,7 +592,9 @@ int gmx_nmeig(int argc, char* argv[]) gmx_fatal(FARGS, "Hessian size is %d x %d, which is larger than the maximum allowed %d " "elements.", - nrow, ncol, INT_MAX); + nrow, + ncol, + INT_MAX); } snew(full_hessian, hessianSize); for (i = 0; i < nrow * ncol; i++) @@ -648,8 +653,11 @@ int gmx_nmeig(int argc, char* argv[]) /* now write the output */ fprintf(stderr, "Writing eigenvalues...\n"); - out = xvgropen(opt2fn("-ol", NFILE, fnm), "Eigenvalues", "Eigenvalue index", - "Eigenvalue [Gromacs units]", oenv); + out = xvgropen(opt2fn("-ol", NFILE, fnm), + "Eigenvalues", + "Eigenvalue index", + "Eigenvalue [Gromacs units]", + oenv); if (output_env_get_print_xvgr_codes(oenv)) { if (bM) @@ -681,8 +689,11 @@ int gmx_nmeig(int argc, char* argv[]) } printf("Writing eigenfrequencies - negative eigenvalues will be set to zero.\n"); - out = xvgropen(opt2fn("-of", NFILE, fnm), "Eigenfrequencies", "Eigenvector index", - "Wavenumber [cm\\S-1\\N]", oenv); + out = xvgropen(opt2fn("-of", NFILE, fnm), + "Eigenfrequencies", + "Eigenvector index", + "Wavenumber [cm\\S-1\\N]", + oenv); if (output_env_get_print_xvgr_codes(oenv)) { if (bM) @@ -701,7 +712,9 @@ int gmx_nmeig(int argc, char* argv[]) snew(spectrum, maxspec); spec = xvgropen(opt2fn("-os", NFILE, fnm), "Vibrational spectrum based on harmonic approximation", - "\\f{12}w\\f{4} (cm\\S-1\\N)", "Intensity [Gromacs units]", oenv); + "\\f{12}w\\f{4} (cm\\S-1\\N)", + "Intensity [Gromacs units]", + oenv); for (i = 0; (i < maxspec); i++) { spectrum[i] = 0; @@ -793,13 +806,23 @@ int gmx_nmeig(int argc, char* argv[]) /* The sparse matrix diagonalization store all eigenvectors up to end */ eigenvectorPtr = eigenvectors + (begin - 1) * atom_index.size(); } - write_eigenvectors(opt2fn("-v", NFILE, fnm), atom_index.size(), eigenvectorPtr, FALSE, begin, - end, eWXR_NO, nullptr, FALSE, top_x, bM, eigenvalues); + write_eigenvectors(opt2fn("-v", NFILE, fnm), + atom_index.size(), + eigenvectorPtr, + FALSE, + begin, + end, + eWXR_NO, + nullptr, + FALSE, + top_x, + bM, + eigenvalues); if (begin == 1) { - analyzeThermochemistry(stdout, top, top_x, atom_index, eigenvalues, T, P, sigma_r, - scale_factor, linear_toler); + analyzeThermochemistry( + stdout, top, top_x, atom_index, eigenvalues, T, P, sigma_r, scale_factor, linear_toler); please_cite(stdout, "Spoel2018a"); } else diff --git a/src/gromacs/gmxana/gmx_nmens.cpp b/src/gromacs/gmxana/gmx_nmens.cpp index 78859917b4..2ddcc6a234 100644 --- a/src/gromacs/gmxana/gmx_nmens.cpp +++ b/src/gromacs/gmxana/gmx_nmens.cpp @@ -120,8 +120,8 @@ int gmx_nmens(int argc, char* argv[]) indexfile = ftp2fn_null(efNDX, NFILE, fnm); - read_eigenvectors(opt2fn("-v", NFILE, fnm), &natoms, &bFit, &xref, &bDMR, &xav, &bDMA, &nvec, - &eignr, &eigvec, &eigval); + read_eigenvectors( + opt2fn("-v", NFILE, fnm), &natoms, &bFit, &xref, &bDMR, &xav, &bDMA, &nvec, &eignr, &eigvec, &eigval); read_tps_conf(ftp2fn(efTPS, NFILE, fnm), &top, &pbcType, &xtop, nullptr, box, bDMA); atoms = &top.atoms; diff --git a/src/gromacs/gmxana/gmx_nmr.cpp b/src/gromacs/gmxana/gmx_nmr.cpp index 8d597542cd..119c5e0a05 100644 --- a/src/gromacs/gmxana/gmx_nmr.cpp +++ b/src/gromacs/gmxana/gmx_nmr.cpp @@ -446,8 +446,8 @@ int gmx_nmr(int argc, char* argv[]) int npargs; npargs = asize(pa); - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_BEGIN | PCA_CAN_END, NFILE, fnm, - npargs, pa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_BEGIN | PCA_CAN_END, NFILE, fnm, npargs, pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -557,8 +557,8 @@ int gmx_nmr(int argc, char* argv[]) } if (bORT) { - fort = xvgropen(opt2fn("-ort", NFILE, fnm), "Calculated orientations", - "Time (ps)", "", oenv); + fort = xvgropen( + opt2fn("-ort", NFILE, fnm), "Calculated orientations", "Time (ps)", "", oenv); if (bOrinst && output_env_get_print_xvgr_codes(oenv)) { fprintf(fort, "%s", orinst_sub); @@ -567,8 +567,11 @@ int gmx_nmr(int argc, char* argv[]) } if (bODT) { - fodt = xvgropen(opt2fn("-odt", NFILE, fnm), "Orientation restraint deviation", - "Time (ps)", "", oenv); + fodt = xvgropen(opt2fn("-odt", NFILE, fnm), + "Orientation restraint deviation", + "Time (ps)", + "", + oenv); if (bOrinst && output_env_get_print_xvgr_codes(oenv)) { fprintf(fodt, "%s", orinst_sub); @@ -623,8 +626,8 @@ int gmx_nmr(int argc, char* argv[]) xvgr_legend(out_disre, 2, drleg, oenv); if (bDRAll) { - fp_pairs = xvgropen(opt2fn("-pairs", NFILE, fnm), "Pair Distances", "Time (ps)", - "Distance (nm)", oenv); + fp_pairs = xvgropen( + opt2fn("-pairs", NFILE, fnm), "Pair Distances", "Time (ps)", "Distance (nm)", oenv); if (output_env_get_print_xvgr_codes(oenv)) { fprintf(fp_pairs, "@ subtitle \"averaged (tau=%g) and instantaneous\"\n", ir->dr_tau); @@ -672,7 +675,8 @@ int gmx_nmr(int argc, char* argv[]) gmx_fatal(FARGS, "Number of disre pairs in the energy file (%d) does not match the " "number in the run input file (%d)\n", - ndisre, ilist.size() / 3); + ndisre, + ilist.size() / 3); } snew(pairleg, ndisre); int molb = 0; @@ -683,7 +687,12 @@ int gmx_nmr(int argc, char* argv[]) k = fa[3 * i + 2]; mtopGetAtomAndResidueName(topInfo.mtop(), j, &molb, &anm_j, &resnr_j, &resnm_j, nullptr); mtopGetAtomAndResidueName(topInfo.mtop(), k, &molb, &anm_k, &resnr_k, &resnm_k, nullptr); - sprintf(pairleg[i], "%d %s %d %s (%d)", resnr_j, anm_j, resnr_k, anm_k, + sprintf(pairleg[i], + "%d %s %d %s (%d)", + resnr_j, + anm_j, + resnr_k, + anm_k, ip[fa[3 * i]].disres.label); } set = select_it(ndisre, pairleg, &nset); @@ -727,8 +736,8 @@ int gmx_nmr(int argc, char* argv[]) } /* Subtract bounds from distances, to calculate violations */ - calc_violations(disre_rt, disre_rm3tav, nbounds, pair, bounds, violaver, - &sumt, &sumaver); + calc_violations( + disre_rt, disre_rm3tav, nbounds, pair, bounds, violaver, &sumt, &sumaver); fprintf(out_disre, " %8.4f %8.4f\n", sumaver, sumt); if (bDRAll) @@ -764,7 +773,8 @@ int gmx_nmr(int argc, char* argv[]) gmx_fatal(FARGS, "Number of orientation restraints in energy file (%d) does " "not match with the topology (%d)", - blk->sub[0].nr, nor); + blk->sub[0].nr, + nor); } if (bORA || bODA) { @@ -814,7 +824,8 @@ int gmx_nmr(int argc, char* argv[]) gmx_fatal(FARGS, "Number of orientation experiments in energy file (%d) does " "not match with the topology (%d)", - blk->sub[0].nr / 12, nex); + blk->sub[0].nr / 12, + nex); } fprintf(foten, " %10f", fr.t); for (i = 0; i < nex; i++) @@ -855,8 +866,8 @@ int gmx_nmr(int argc, char* argv[]) } if (bORA) { - FILE* out = xvgropen(opt2fn("-ora", NFILE, fnm), "Average calculated orientations", - "Restraint label", "", oenv); + FILE* out = xvgropen( + opt2fn("-ora", NFILE, fnm), "Average calculated orientations", "Restraint label", "", oenv); if (bOrinst && output_env_get_print_xvgr_codes(oenv)) { fprintf(out, "%s", orinst_sub); @@ -869,8 +880,8 @@ int gmx_nmr(int argc, char* argv[]) } if (bODA) { - FILE* out = xvgropen(opt2fn("-oda", NFILE, fnm), "Average restraint deviation", - "Restraint label", "", oenv); + FILE* out = xvgropen( + opt2fn("-oda", NFILE, fnm), "Average restraint deviation", "Restraint label", "", oenv); if (bOrinst && output_env_get_print_xvgr_codes(oenv)) { fprintf(out, "%s", orinst_sub); @@ -883,8 +894,11 @@ int gmx_nmr(int argc, char* argv[]) } if (bODR) { - FILE* out = xvgropen(opt2fn("-odr", NFILE, fnm), "RMS orientation restraint deviations", - "Restraint label", "", oenv); + FILE* out = xvgropen(opt2fn("-odr", NFILE, fnm), + "RMS orientation restraint deviations", + "Restraint label", + "", + oenv); if (bOrinst && output_env_get_print_xvgr_codes(oenv)) { fprintf(out, "%s", orinst_sub); @@ -908,8 +922,7 @@ int gmx_nmr(int argc, char* argv[]) if (bDisRe) { - analyse_disre(opt2fn("-viol", NFILE, fnm), teller_disre, violaver, bounds, index, pair, - nbounds, oenv); + analyse_disre(opt2fn("-viol", NFILE, fnm), teller_disre, violaver, bounds, index, pair, nbounds, oenv); } { const char* nxy = "-nxy"; diff --git a/src/gromacs/gmxana/gmx_nmtraj.cpp b/src/gromacs/gmxana/gmx_nmtraj.cpp index c752308e92..006f66b2f9 100644 --- a/src/gromacs/gmxana/gmx_nmtraj.cpp +++ b/src/gromacs/gmxana/gmx_nmtraj.cpp @@ -127,8 +127,8 @@ int gmx_nmtraj(int argc, char* argv[]) return 0; } - read_eigenvectors(opt2fn("-v", NFILE, fnm), &natoms, &bFit, &xref, &bDMR, &xav, &bDMA, &nvec, - &eignr, &eigvec, &eigval); + read_eigenvectors( + opt2fn("-v", NFILE, fnm), &natoms, &bFit, &xref, &bDMR, &xav, &bDMA, &nvec, &eignr, &eigvec, &eigval); read_tps_conf(ftp2fn(efTPS, NFILE, fnm), &top, &pbcType, &xtop, nullptr, box, bDMA); diff --git a/src/gromacs/gmxana/gmx_order.cpp b/src/gromacs/gmxana/gmx_order.cpp index aa97af5f97..bbf61e90b3 100644 --- a/src/gromacs/gmxana/gmx_order.cpp +++ b/src/gromacs/gmxana/gmx_order.cpp @@ -328,8 +328,8 @@ static void calc_tetra_order_parm(const char* fnNDX, nframes = 0; do { - find_nearest_neighbours(pbcType, natoms, box, x, isize[0], index[0], &sg, &sk, nslice, - slice_dim, sg_slice, sk_slice, gpbc); + find_nearest_neighbours( + pbcType, natoms, box, x, isize[0], index[0], &sg, &sk, nslice, slice_dim, sg_slice, sk_slice, gpbc); for (i = 0; (i < nslice); i++) { sg_slice_tot[i] += sg_slice[i]; @@ -353,9 +353,13 @@ static void calc_tetra_order_parm(const char* fnNDX, fpsk = xvgropen(skslfn, "S\\sk\\N Distance Order Parameter / Slab", "(nm)", "S\\sk\\N", oenv); for (i = 0; (i < nslice); i++) { - fprintf(fpsg, "%10g %10g\n", (i + 0.5) * box[slice_dim][slice_dim] / nslice, + fprintf(fpsg, + "%10g %10g\n", + (i + 0.5) * box[slice_dim][slice_dim] / nslice, sg_slice_tot[i] / static_cast(nframes)); - fprintf(fpsk, "%10g %10g\n", (i + 0.5) * box[slice_dim][slice_dim] / nslice, + fprintf(fpsk, + "%10g %10g\n", + (i + 0.5) * box[slice_dim][slice_dim] / nslice, sk_slice_tot[i] / static_cast(nframes)); } xvgrclose(fpsg); @@ -371,8 +375,11 @@ static void print_types(const int index[], int a[], int ngrps, char* groups[], c fprintf(stderr, "Using following groups: \n"); for (i = 0; i < ngrps; i++) { - fprintf(stderr, "Groupname: %s First atomname: %s First atomnr %d\n", groups[i], - *(top->atoms.atomname[a[index[i]]]), a[index[i]]); + fprintf(stderr, + "Groupname: %s First atomname: %s First atomnr %d\n", + groups[i], + *(top->atoms.atomname[a[index[i]]]), + a[index[i]]); } fprintf(stderr, "\n"); } @@ -384,7 +391,9 @@ static void check_length(real length, int a, int b) fprintf(stderr, "WARNING: distance between atoms %d and " "%d > 0.3 nm (%f). Index file might be corrupt.\n", - a, b, length); + a, + b, + length); } } @@ -746,7 +755,11 @@ static void calc_order(const char* fn, for (i = 1; i < ngrps - 1; i++) { svmul(1.0 / nr_frames, (*order)[i], (*order)[i]); - fprintf(stderr, "Atom %d Tensor: x=%g , y=%g, z=%g\n", i, (*order)[i][XX], (*order)[i][YY], + fprintf(stderr, + "Atom %d Tensor: x=%g , y=%g, z=%g\n", + i, + (*order)[i][XX], + (*order)[i][YY], (*order)[i][ZZ]); if (bSliced || permolecule) { @@ -766,7 +779,8 @@ static void calc_order(const char* fn, if (bUnsat) { - fprintf(stderr, "Average angle between double bond and normal: %f\n", + fprintf(stderr, + "Average angle between double bond and normal: %f\n", 180 * sdbangle / (nr_frames * static_cast(size) * M_PI)); } @@ -813,7 +827,9 @@ static void order_plot(rvec order[], slOrd = xvgropen(bfile, buf, "Molecule", "S", oenv); for (atom = 1; atom < ngrps - 1; atom++) { - fprintf(ord, "%12d %12g\n", atom, + fprintf(ord, + "%12d %12g\n", + atom, -1.0 * (2.0 / 3.0 * order[atom][XX] + 1.0 / 3.0 * order[atom][YY])); } @@ -852,8 +868,7 @@ static void order_plot(rvec order[], { S += slOrder[slice][atom]; } - fprintf(slOrd, "%12g %12g\n", static_cast(slice) * slWidth, - S / static_cast(atom)); + fprintf(slOrd, "%12g %12g\n", static_cast(slice) * slWidth, S / static_cast(atom)); } } else @@ -865,9 +880,10 @@ static void order_plot(rvec order[], for (atom = 1; atom < ngrps - 1; atom++) { - fprintf(ord, "%12d %12g %12g %12g\n", atom, order[atom][XX], order[atom][YY], - order[atom][ZZ]); - fprintf(slOrd, "%12d %12g\n", atom, + fprintf(ord, "%12d %12g %12g %12g\n", atom, order[atom][XX], order[atom][YY], order[atom][ZZ]); + fprintf(slOrd, + "%12d %12g\n", + atom, -1.0 * (2.0 / 3.0 * order[atom][XX] + 1.0 / 3.0 * order[atom][YY])); } } @@ -937,8 +953,8 @@ static void write_bfactors(t_filenm* fnm, } } - write_sto_conf(opt2fn("-ob", nfile, fnm), "Order parameters", &useatoms, frout.x, nullptr, - frout.pbcType, frout.box); + write_sto_conf( + opt2fn("-ob", nfile, fnm), "Order parameters", &useatoms, frout.x, nullptr, frout.pbcType, frout.box); sfree(frout.x); done_atom(&useatoms); @@ -1034,8 +1050,8 @@ int gmx_order(int argc, char* argv[]) const char * sgfnm, *skfnm, *ndxfnm, *tpsfnm, *trxfnm; gmx_output_env_t* oenv; - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -1081,8 +1097,16 @@ int gmx_order(int argc, char* argv[]) /* If either of theoptions is set we compute both */ sgfnm = opt2fn("-Sg", NFILE, fnm); skfnm = opt2fn("-Sk", NFILE, fnm); - calc_tetra_order_parm(ndxfnm, tpsfnm, trxfnm, sgfnm, skfnm, nslices, axis, - opt2fn("-Sgsl", NFILE, fnm), opt2fn("-Sksl", NFILE, fnm), oenv); + calc_tetra_order_parm(ndxfnm, + tpsfnm, + trxfnm, + sgfnm, + skfnm, + nslices, + axis, + opt2fn("-Sgsl", NFILE, fnm), + opt2fn("-Sksl", NFILE, fnm), + oenv); /* view xvgr files */ do_view(oenv, opt2fn("-Sg", NFILE, fnm), nullptr); do_view(oenv, opt2fn("-Sk", NFILE, fnm), nullptr); @@ -1136,18 +1160,43 @@ int gmx_order(int argc, char* argv[]) /* show atomtypes, to check if index file is correct */ print_types(index, a, ngrps, grpname, top); - calc_order(ftp2fn(efTRX, NFILE, fnm), index, a, &order, &slOrder, &slWidth, nslices, - bSliced, bUnsat, top, pbcType, ngrps, axis, permolecule, radial, distcalc, - opt2fn_null("-nr", NFILE, fnm), &distvals, oenv); + calc_order(ftp2fn(efTRX, NFILE, fnm), + index, + a, + &order, + &slOrder, + &slWidth, + nslices, + bSliced, + bUnsat, + top, + pbcType, + ngrps, + axis, + permolecule, + radial, + distcalc, + opt2fn_null("-nr", NFILE, fnm), + &distvals, + oenv); if (radial) { ngrps--; /*don't print the last group--was used for center-of-mass determination*/ } - order_plot(order, slOrder, opt2fn("-o", NFILE, fnm), opt2fn("-os", NFILE, fnm), - opt2fn("-od", NFILE, fnm), ngrps, nslices, slWidth, bSzonly, permolecule, - distvals, oenv); + order_plot(order, + slOrder, + opt2fn("-o", NFILE, fnm), + opt2fn("-os", NFILE, fnm), + opt2fn("-od", NFILE, fnm), + ngrps, + nslices, + slWidth, + bSzonly, + permolecule, + distvals, + oenv); if (opt2bSet("-ob", NFILE, fnm)) { diff --git a/src/gromacs/gmxana/gmx_polystat.cpp b/src/gromacs/gmxana/gmx_polystat.cpp index ee1cfe1af4..c60fd3af61 100644 --- a/src/gromacs/gmxana/gmx_polystat.cpp +++ b/src/gromacs/gmxana/gmx_polystat.cpp @@ -170,8 +170,18 @@ int gmx_polystat(int argc, char* argv[]) char ** legp, buf[STRLEN]; gmx_rmpbc_t gpbc = nullptr; - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME | PCA_TIME_UNIT, NFILE, fnm, - asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args(&argc, + argv, + PCA_CAN_VIEW | PCA_CAN_TIME | PCA_TIME_UNIT, + NFILE, + fnm, + asize(pa), + pa, + asize(desc), + desc, + 0, + nullptr, + &oenv)) { return 0; } @@ -213,8 +223,11 @@ int gmx_polystat(int argc, char* argv[]) if (opt2bSet("-v", NFILE, fnm)) { - outv = xvgropen(opt2fn("-v", NFILE, fnm), "Principal components", - output_env_get_xvgr_tlabel(oenv), "(nm)", oenv); + outv = xvgropen(opt2fn("-v", NFILE, fnm), + "Principal components", + output_env_get_xvgr_tlabel(oenv), + "(nm)", + oenv); snew(legp, DIM * DIM); for (d = 0; d < DIM; d++) { @@ -233,8 +246,11 @@ int gmx_polystat(int argc, char* argv[]) if (opt2bSet("-p", NFILE, fnm)) { - outp = xvgropen(opt2fn("-p", NFILE, fnm), "Persistence length", - output_env_get_xvgr_tlabel(oenv), "bonds", oenv); + outp = xvgropen(opt2fn("-p", NFILE, fnm), + "Persistence length", + output_env_get_xvgr_tlabel(oenv), + "bonds", + oenv); snew(bond, nat_max - 1); snew(sum_inp, nat_min / 2); snew(ninp, nat_min / 2); @@ -246,9 +262,9 @@ int gmx_polystat(int argc, char* argv[]) if (opt2bSet("-i", NFILE, fnm)) { - outi = xvgropen(opt2fn("-i", NFILE, fnm), "Internal distances", "n", - "/n (nm\\S2\\N)", oenv); - i = index[molind[1] - 1] - index[molind[0]]; /* Length of polymer -1 */ + outi = xvgropen( + opt2fn("-i", NFILE, fnm), "Internal distances", "n", "/n (nm\\S2\\N)", oenv); + i = index[molind[1] - 1] - index[molind[0]]; /* Length of polymer -1 */ snew(intd, i); } else @@ -391,8 +407,13 @@ int gmx_polystat(int argc, char* argv[]) gyro_eigen(gyr_all, eig, eigv, ord); - fprintf(out, "%10.3f %8.4f %8.4f %8.4f %8.4f %8.4f", t * output_env_get_time_factor(oenv), - std::sqrt(sum_eed2), sqrt(sum_gyro), std::sqrt(eig[ord[0]]), std::sqrt(eig[ord[1]]), + fprintf(out, + "%10.3f %8.4f %8.4f %8.4f %8.4f %8.4f", + t * output_env_get_time_factor(oenv), + std::sqrt(sum_eed2), + sqrt(sum_gyro), + std::sqrt(eig[ord[0]]), + std::sqrt(eig[ord[1]]), std::sqrt(eig[ord[2]])); if (bPC) { diff --git a/src/gromacs/gmxana/gmx_potential.cpp b/src/gromacs/gmxana/gmx_potential.cpp index fb417b0f8f..d6502e69e5 100644 --- a/src/gromacs/gmxana/gmx_potential.cpp +++ b/src/gromacs/gmxana/gmx_potential.cpp @@ -194,7 +194,8 @@ static void calc_potential(const char* fn, gmx_fatal(FARGS, "You selected a group with %d atoms, but only %d atoms\n" "were found in the trajectory.\n", - gnx[n], natoms); + gnx[n], + natoms); } for (i = 0; i < gnx[n]; i++) /* loop over all atoms in index file */ { @@ -499,8 +500,8 @@ int gmx_potential(int argc, char* argv[]) #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, - asize(desc), desc, asize(bugs), bugs, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, asize(bugs), bugs, &oenv)) { return 0; } @@ -517,11 +518,34 @@ int gmx_potential(int argc, char* argv[]) rd_index(ftp2fn(efNDX, NFILE, fnm), ngrps, ngx, index, grpname); - calc_potential(ftp2fn(efTRX, NFILE, fnm), index, ngx, &potential, &charge, &field, &nslices, - top, pbcType, axis, ngrps, &slWidth, fudge_z, bSpherical, bCorrect, oenv); - - plot_potential(potential, charge, field, opt2fn("-o", NFILE, fnm), opt2fn("-oc", NFILE, fnm), - opt2fn("-of", NFILE, fnm), nslices, ngrps, grpname, slWidth, oenv); + calc_potential(ftp2fn(efTRX, NFILE, fnm), + index, + ngx, + &potential, + &charge, + &field, + &nslices, + top, + pbcType, + axis, + ngrps, + &slWidth, + fudge_z, + bSpherical, + bCorrect, + oenv); + + plot_potential(potential, + charge, + field, + opt2fn("-o", NFILE, fnm), + opt2fn("-oc", NFILE, fnm), + opt2fn("-of", NFILE, fnm), + nslices, + ngrps, + grpname, + slWidth, + oenv); do_view(oenv, opt2fn("-o", NFILE, fnm), nullptr); /* view xvgr file */ do_view(oenv, opt2fn("-oc", NFILE, fnm), nullptr); /* view xvgr file */ diff --git a/src/gromacs/gmxana/gmx_principal.cpp b/src/gromacs/gmxana/gmx_principal.cpp index 40092a218f..94376e129f 100644 --- a/src/gromacs/gmxana/gmx_principal.cpp +++ b/src/gromacs/gmxana/gmx_principal.cpp @@ -104,8 +104,18 @@ int gmx_principal(int argc, char* argv[]) { efXVG, "-om", "moi", ffWRITE } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT | PCA_CAN_VIEW, NFILE, fnm, - asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args(&argc, + argv, + PCA_CAN_TIME | PCA_TIME_UNIT | PCA_CAN_VIEW, + NFILE, + fnm, + asize(pa), + pa, + asize(desc), + desc, + 0, + nullptr, + &oenv)) { return 0; } @@ -117,24 +127,36 @@ int gmx_principal(int argc, char* argv[]) sprintf(legend[i], "%c component", 'X' + i); } - axis1 = xvgropen(opt2fn("-a1", NFILE, fnm), "Principal axis 1 (major axis)", - output_env_get_xvgr_tlabel(oenv), "Component (nm)", oenv); + axis1 = xvgropen(opt2fn("-a1", NFILE, fnm), + "Principal axis 1 (major axis)", + output_env_get_xvgr_tlabel(oenv), + "Component (nm)", + oenv); xvgr_legend(axis1, DIM, legend, oenv); - axis2 = xvgropen(opt2fn("-a2", NFILE, fnm), "Principal axis 2 (middle axis)", - output_env_get_xvgr_tlabel(oenv), "Component (nm)", oenv); + axis2 = xvgropen(opt2fn("-a2", NFILE, fnm), + "Principal axis 2 (middle axis)", + output_env_get_xvgr_tlabel(oenv), + "Component (nm)", + oenv); xvgr_legend(axis2, DIM, legend, oenv); - axis3 = xvgropen(opt2fn("-a3", NFILE, fnm), "Principal axis 3 (minor axis)", - output_env_get_xvgr_tlabel(oenv), "Component (nm)", oenv); + axis3 = xvgropen(opt2fn("-a3", NFILE, fnm), + "Principal axis 3 (minor axis)", + output_env_get_xvgr_tlabel(oenv), + "Component (nm)", + oenv); xvgr_legend(axis3, DIM, legend, oenv); sprintf(legend[XX], "Axis 1 (major)"); sprintf(legend[YY], "Axis 2 (middle)"); sprintf(legend[ZZ], "Axis 3 (minor)"); - fmoi = xvgropen(opt2fn("-om", NFILE, fnm), "Moments of inertia around inertial axes", - output_env_get_xvgr_tlabel(oenv), "I (au nm\\S2\\N)", oenv); + fmoi = xvgropen(opt2fn("-om", NFILE, fnm), + "Moments of inertia around inertial axes", + output_env_get_xvgr_tlabel(oenv), + "I (au nm\\S2\\N)", + oenv); xvgr_legend(fmoi, DIM, legend, oenv); for (i = 0; i < DIM; i++) @@ -157,12 +179,9 @@ int gmx_principal(int argc, char* argv[]) calc_principal_axes(&top, x, index, gnx, axes, moi); - fprintf(axis1, "%15.10f %15.10f %15.10f %15.10f\n", t, axes[XX][XX], axes[XX][YY], - axes[XX][ZZ]); - fprintf(axis2, "%15.10f %15.10f %15.10f %15.10f\n", t, axes[YY][XX], axes[YY][YY], - axes[YY][ZZ]); - fprintf(axis3, "%15.10f %15.10f %15.10f %15.10f\n", t, axes[ZZ][XX], axes[ZZ][YY], - axes[ZZ][ZZ]); + fprintf(axis1, "%15.10f %15.10f %15.10f %15.10f\n", t, axes[XX][XX], axes[XX][YY], axes[XX][ZZ]); + fprintf(axis2, "%15.10f %15.10f %15.10f %15.10f\n", t, axes[YY][XX], axes[YY][YY], axes[YY][ZZ]); + fprintf(axis3, "%15.10f %15.10f %15.10f %15.10f\n", t, axes[ZZ][XX], axes[ZZ][YY], axes[ZZ][ZZ]); fprintf(fmoi, "%15.10f %15.10f %15.10f %15.10f\n", t, moi[XX], moi[YY], moi[ZZ]); } while (read_next_x(oenv, status, &t, x, box)); diff --git a/src/gromacs/gmxana/gmx_rama.cpp b/src/gromacs/gmxana/gmx_rama.cpp index f0646dabd0..c10b877468 100644 --- a/src/gromacs/gmxana/gmx_rama.cpp +++ b/src/gromacs/gmxana/gmx_rama.cpp @@ -81,8 +81,8 @@ int gmx_rama(int argc, char* argv[]) { efXVG, nullptr, "rama", ffWRITE } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, 0, nullptr, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, 0, nullptr, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } diff --git a/src/gromacs/gmxana/gmx_rms.cpp b/src/gromacs/gmxana/gmx_rms.cpp index 43c3419d25..52a82a0cf1 100644 --- a/src/gromacs/gmxana/gmx_rms.cpp +++ b/src/gromacs/gmxana/gmx_rms.cpp @@ -241,8 +241,18 @@ int gmx_rms(int argc, char* argv[]) }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT | PCA_CAN_VIEW, NFILE, fnm, - asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args(&argc, + argv, + PCA_CAN_TIME | PCA_TIME_UNIT | PCA_CAN_VIEW, + NFILE, + fnm, + asize(pa), + pa, + asize(desc), + desc, + 0, + nullptr, + &oenv)) { return 0; } @@ -462,8 +472,7 @@ int gmx_rms(int argc, char* argv[]) natoms_trx = read_first_x(oenv, &status, opt2fn("-f", NFILE, fnm), &t, &x, box); if (natoms_trx != top.atoms.nr) { - fprintf(stderr, "\nWARNING: topology has %d atoms, whereas trajectory has %d\n", - top.atoms.nr, natoms_trx); + fprintf(stderr, "\nWARNING: topology has %d atoms, whereas trajectory has %d\n", top.atoms.nr, natoms_trx); } natoms = std::min(top.atoms.nr, natoms_trx); if (bMat || bBond || bPrev) @@ -701,7 +710,8 @@ int gmx_rms(int argc, char* argv[]) gmx_fatal(FARGS, "Second trajectory (%d atoms) does not match the first one" " (%d atoms)", - natoms_trx2, natoms_trx); + natoms_trx2, + natoms_trx); } frame2 = 0; do @@ -859,8 +869,8 @@ int gmx_rms(int argc, char* argv[]) { if (bFile2 || (i < j)) { - rmsd_mat[i][j] = calc_similar_ind(ewhat != ewRMSD, irms[0], ind_rms_m, - w_rms_m, mat_x[i], mat_x2_j); + rmsd_mat[i][j] = calc_similar_ind( + ewhat != ewRMSD, irms[0], ind_rms_m, w_rms_m, mat_x[i], mat_x2_j); if (rmsd_mat[i][j] > rmsd_max) { rmsd_max = rmsd_mat[i][j]; @@ -972,9 +982,22 @@ int gmx_rms(int argc, char* argv[]) fprintf(stderr, "Min and Max value set to resp. %f and %f\n", rmsd_min, rmsd_max); } sprintf(buf, "%s %s matrix", gn_rms[0], whatname[ewhat]); - write_xpm(opt2FILE("-m", NFILE, fnm, "w"), 0, buf, whatlabel[ewhat], - output_env_get_time_label(oenv), output_env_get_time_label(oenv), tel_mat, - tel_mat2, axis, axis2, rmsd_mat, rmsd_min, rmsd_max, rlo, rhi, &nlevels); + write_xpm(opt2FILE("-m", NFILE, fnm, "w"), + 0, + buf, + whatlabel[ewhat], + output_env_get_time_label(oenv), + output_env_get_time_label(oenv), + tel_mat, + tel_mat2, + axis, + axis2, + rmsd_mat, + rmsd_min, + rmsd_max, + rlo, + rhi, + &nlevels); /* Print the distribution of RMSD values */ if (opt2bSet("-dist", NFILE, fnm)) { @@ -1033,9 +1056,22 @@ int gmx_rms(int argc, char* argv[]) } sprintf(buf, "%s %s vs. delta t", gn_rms[0], whatname[ewhat]); fp = gmx_ffopen("delta.xpm", "w"); - write_xpm(fp, 0, buf, "density", output_env_get_time_label(oenv), whatlabel[ewhat], - delta_xsize, del_lev + 1, del_xaxis, del_yaxis, delta, 0.0, delta_max, - rlo, rhi, &nlevels); + write_xpm(fp, + 0, + buf, + "density", + output_env_get_time_label(oenv), + whatlabel[ewhat], + delta_xsize, + del_lev + 1, + del_xaxis, + del_yaxis, + delta, + 0.0, + delta_max, + rlo, + rhi, + &nlevels); gmx_ffclose(fp); } if (opt2bSet("-bin", NFILE, fnm)) @@ -1068,7 +1104,8 @@ int gmx_rms(int argc, char* argv[]) fprintf(stderr, "Bond angle Min and Max set to:\n" "Min. angle: %f, Max. angle: %f\n", - bond_min, bond_max); + bond_min, + bond_max); } rlo.r = 1; rlo.g = 1; @@ -1077,9 +1114,22 @@ int gmx_rms(int argc, char* argv[]) rhi.g = 0; rhi.b = 0; sprintf(buf, "%s av. bond angle deviation", gn_rms[0]); - write_xpm(opt2FILE("-bm", NFILE, fnm, "w"), 0, buf, "degrees", - output_env_get_time_label(oenv), output_env_get_time_label(oenv), tel_mat, - tel_mat2, axis, axis2, bond_mat, bond_min, bond_max, rlo, rhi, &nlevels); + write_xpm(opt2FILE("-bm", NFILE, fnm, "w"), + 0, + buf, + "degrees", + output_env_get_time_label(oenv), + output_env_get_time_label(oenv), + tel_mat, + tel_mat2, + axis, + axis2, + bond_mat, + bond_min, + bond_max, + rlo, + rhi, + &nlevels); } } @@ -1092,15 +1142,22 @@ int gmx_rms(int argc, char* argv[]) } else { - sprintf(buf, "%s with frame %g %s ago", whatxvgname[ewhat], time[prev * freq] - time[0], + sprintf(buf, + "%s with frame %g %s ago", + whatxvgname[ewhat], + time[prev * freq] - time[0], output_env_get_time_label(oenv).c_str()); } - fp = xvgropen(opt2fn("-o", NFILE, fnm), buf, output_env_get_xvgr_tlabel(oenv), - whatxvglabel[ewhat], oenv); + fp = xvgropen(opt2fn("-o", NFILE, fnm), buf, output_env_get_xvgr_tlabel(oenv), whatxvglabel[ewhat], oenv); if (output_env_get_print_xvgr_codes(oenv)) { - fprintf(fp, "@ subtitle \"%s%s after %s%s%s\"\n", (nrms == 1) ? "" : "of ", gn_rms[0], - fitgraphlabel[efit], bFit ? " to " : "", bFit ? gn_fit : ""); + fprintf(fp, + "@ subtitle \"%s%s after %s%s%s\"\n", + (nrms == 1) ? "" : "of ", + gn_rms[0], + fitgraphlabel[efit], + bFit ? " to " : "", + bFit ? gn_fit : ""); } if (nrms != 1) { @@ -1135,8 +1192,7 @@ int gmx_rms(int argc, char* argv[]) { if (output_env_get_print_xvgr_codes(oenv)) { - fprintf(fp, "@ subtitle \"of %s after lsq fit to mirror of %s\"\n", gn_rms[0], - bFit ? gn_fit : ""); + fprintf(fp, "@ subtitle \"of %s after lsq fit to mirror of %s\"\n", gn_rms[0], bFit ? gn_fit : ""); } } else diff --git a/src/gromacs/gmxana/gmx_rmsdist.cpp b/src/gromacs/gmxana/gmx_rmsdist.cpp index af62354919..950565b796 100644 --- a/src/gromacs/gmxana/gmx_rmsdist.cpp +++ b/src/gromacs/gmxana/gmx_rmsdist.cpp @@ -326,8 +326,14 @@ static int analyze_noe_equivalent(const char* eq_fn, j = i + 1; rnri = atoms->atom[index[i]].resind; rnrj = atoms->atom[index[j]].resind; - bEquiv = is_equiv(neq, equiv, &nnm[i], rnri, *atoms->resinfo[rnri].name, - *atoms->atomname[index[i]], rnrj, *atoms->resinfo[rnrj].name, + bEquiv = is_equiv(neq, + equiv, + &nnm[i], + rnri, + *atoms->resinfo[rnri].name, + *atoms->atomname[index[i]], + rnrj, + *atoms->resinfo[rnrj].name, *atoms->atomname[index[j]]); if (nnm[i] && bEquiv) { @@ -398,8 +404,12 @@ static int analyze_noe_equivalent(const char* eq_fn, for (i = 0; i < isize; i++) { rnri = atoms->atom[index[i]].resind; - fprintf(debug, "%s %s %d -> %s\n", *atoms->atomname[index[i]], - *atoms->resinfo[rnri].name, rnri, nnm[i] ? nnm[i] : ""); + fprintf(debug, + "%s %s %d -> %s\n", + *atoms->atomname[index[i]], + *atoms->resinfo[rnri].name, + rnri, + nnm[i] ? nnm[i] : ""); } } @@ -427,8 +437,15 @@ static int analyze_noe_equivalent(const char* eq_fn, /* dump group definitions */ if (debug) { - fprintf(debug, "%d %d %d %d %s %s %d\n", i, gi, noe_gr[gi].ianr, noe_gr[gi].anr, - noe_gr[gi].aname, noe_gr[gi].rname, noe_gr[gi].rnr); + fprintf(debug, + "%d %d %d %d %s %s %d\n", + i, + gi, + noe_gr[gi].ianr, + noe_gr[gi].anr, + noe_gr[gi].aname, + noe_gr[gi].rname, + noe_gr[gi].rnr); } } } @@ -508,9 +525,24 @@ static void write_noe(FILE* fp, int gnr, t_noe** noe, t_noe_gr* noe_gr, real rma t_noe_gr gri, grj; min3 = min6 = 1e6; - fprintf(fp, ";%4s %3s %4s %4s%3s %4s %4s %4s %4s%3s %5s %5s %8s %2s %2s %s\n", "ianr", "anr", - "anm", "rnm", "rnr", "ianr", "anr", "anm", "rnm", "rnr", "1/r^3", "1/r^6", "intnsty", - "Dr", "Da", "scale"); + fprintf(fp, + ";%4s %3s %4s %4s%3s %4s %4s %4s %4s%3s %5s %5s %8s %2s %2s %s\n", + "ianr", + "anr", + "anm", + "rnm", + "rnr", + "ianr", + "anr", + "anm", + "rnm", + "rnr", + "1/r^3", + "1/r^6", + "intnsty", + "Dr", + "Da", + "scale"); for (i = 0; i < gnr; i++) { gri = noe_gr[i]; @@ -547,10 +579,24 @@ static void write_noe(FILE* fp, int gnr, t_noe** noe, t_noe_gr* noe_gr, real rma { std::strcpy(b6, "-"); } - fprintf(fp, "%4d %4d %4s %4s%3d %4d %4d %4s %4s%3d %5s %5s %8d %2d %2s %s\n", - gri.ianr + 1, gri.anr + 1, gri.aname, gri.rname, gri.rnr + 1, grj.ianr + 1, - grj.anr + 1, grj.aname, grj.rname, grj.rnr + 1, b3, b6, - gmx::roundToInt(noe[i][j].i_6), grj.rnr - gri.rnr, buf, noe2scale(r3, r6, rmax)); + fprintf(fp, + "%4d %4d %4s %4s%3d %4d %4d %4s %4s%3d %5s %5s %8d %2d %2s %s\n", + gri.ianr + 1, + gri.anr + 1, + gri.aname, + gri.rname, + gri.rnr + 1, + grj.ianr + 1, + grj.anr + 1, + grj.aname, + grj.rname, + grj.rnr + 1, + b3, + b6, + gmx::roundToInt(noe[i][j].i_6), + grj.rnr - gri.rnr, + buf, + noe2scale(r3, r6, rmax)); } } } @@ -562,7 +608,9 @@ static void write_noe(FILE* fp, int gnr, t_noe** noe, t_noe_gr* noe_gr, real rma fprintf(stdout, "NOTE: no 1/r^%d averaged distances found below %g, " "smallest was %g\n", - i, rmax, MINI); + i, + rmax, + MINI); } else { @@ -714,8 +762,8 @@ int gmx_rmsdist(int argc, char* argv[]) }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -834,8 +882,8 @@ int gmx_rmsdist(int argc, char* argv[]) /* make list of noe atom groups */ snew(noe_index, isize + 1); snew(noe_gr, isize); - gnr = analyze_noe_equivalent(opt2fn_null("-equiv", NFILE, fnm), atoms, isize, index, bSumH, - noe_index, noe_gr); + gnr = analyze_noe_equivalent( + opt2fn_null("-equiv", NFILE, fnm), atoms, isize, index, bSumH, noe_index, noe_gr); fprintf(stdout, "Found %d non-equivalent atom-groups in %d atoms\n", gnr, isize); /* make half matrix of of noe-group distances from atom distances */ snew(noe, gnr); @@ -855,34 +903,101 @@ int gmx_rmsdist(int argc, char* argv[]) if (bRMS) { - write_xpm(opt2FILE("-rms", NFILE, fnm, "w"), 0, "RMS of distance", "RMS (nm)", "Atom Index", - "Atom Index", isize, isize, resnr, resnr, rms, 0.0, rmsmax, rlo, rhi, &nlevels); + write_xpm(opt2FILE("-rms", NFILE, fnm, "w"), + 0, + "RMS of distance", + "RMS (nm)", + "Atom Index", + "Atom Index", + isize, + isize, + resnr, + resnr, + rms, + 0.0, + rmsmax, + rlo, + rhi, + &nlevels); } if (bScale) { - write_xpm(opt2FILE("-scl", NFILE, fnm, "w"), 0, "Relative RMS", "RMS", "Atom Index", - "Atom Index", isize, isize, resnr, resnr, rmsc, 0.0, rmscmax, rlo, rhi, &nlevels); + write_xpm(opt2FILE("-scl", NFILE, fnm, "w"), + 0, + "Relative RMS", + "RMS", + "Atom Index", + "Atom Index", + isize, + isize, + resnr, + resnr, + rmsc, + 0.0, + rmscmax, + rlo, + rhi, + &nlevels); } if (bMean) { - write_xpm(opt2FILE("-mean", NFILE, fnm, "w"), 0, "Mean Distance", "Distance (nm)", - "Atom Index", "Atom Index", isize, isize, resnr, resnr, mean, 0.0, meanmax, rlo, - rhi, &nlevels); + write_xpm(opt2FILE("-mean", NFILE, fnm, "w"), + 0, + "Mean Distance", + "Distance (nm)", + "Atom Index", + "Atom Index", + isize, + isize, + resnr, + resnr, + mean, + 0.0, + meanmax, + rlo, + rhi, + &nlevels); } if (bNMR3) { - write_xpm(opt2FILE("-nmr3", NFILE, fnm, "w"), 0, "1/r^3 averaged distances", - "Distance (nm)", "Atom Index", "Atom Index", isize, isize, resnr, resnr, dtot1_3, - 0.0, max1_3, rlo, rhi, &nlevels); + write_xpm(opt2FILE("-nmr3", NFILE, fnm, "w"), + 0, + "1/r^3 averaged distances", + "Distance (nm)", + "Atom Index", + "Atom Index", + isize, + isize, + resnr, + resnr, + dtot1_3, + 0.0, + max1_3, + rlo, + rhi, + &nlevels); } if (bNMR6) { - write_xpm(opt2FILE("-nmr6", NFILE, fnm, "w"), 0, "1/r^6 averaged distances", - "Distance (nm)", "Atom Index", "Atom Index", isize, isize, resnr, resnr, dtot1_6, - 0.0, max1_6, rlo, rhi, &nlevels); + write_xpm(opt2FILE("-nmr6", NFILE, fnm, "w"), + 0, + "1/r^6 averaged distances", + "Distance (nm)", + "Atom Index", + "Atom Index", + isize, + isize, + resnr, + resnr, + dtot1_6, + 0.0, + max1_6, + rlo, + rhi, + &nlevels); } if (bNOE) diff --git a/src/gromacs/gmxana/gmx_rmsf.cpp b/src/gromacs/gmxana/gmx_rmsf.cpp index c0c439afd6..1cd80dd499 100644 --- a/src/gromacs/gmxana/gmx_rmsf.cpp +++ b/src/gromacs/gmxana/gmx_rmsf.cpp @@ -278,8 +278,8 @@ int gmx_rmsf(int argc, char* argv[]) { efXVG, "-oc", "correl", ffOPTWR }, { efLOG, "-dir", "rmsf", ffOPTWR } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pargs), - pargs, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pargs), pargs, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -492,12 +492,14 @@ int gmx_rmsf(int argc, char* argv[]) || top.atoms.atom[index[i]].resind != top.atoms.atom[index[i + 1]].resind) { resind = top.atoms.atom[index[i]].resind; - pdb_bfac = find_pdb_bfac(pdbatoms, &top.atoms.resinfo[resind], - *(top.atoms.atomname[index[i]])); + pdb_bfac = find_pdb_bfac( + pdbatoms, &top.atoms.resinfo[resind], *(top.atoms.atomname[index[i]])); - fprintf(fp, "%5d %10.5f %10.5f\n", + fprintf(fp, + "%5d %10.5f %10.5f\n", bRes ? top.atoms.resinfo[top.atoms.atom[index[i]].resind].nr : index[i] + 1, - rmsf[i] * bfac, pdb_bfac); + rmsf[i] * bfac, + pdb_bfac); } } xvgrclose(fp); @@ -510,7 +512,8 @@ int gmx_rmsf(int argc, char* argv[]) if (!bRes || i + 1 == isize || top.atoms.atom[index[i]].resind != top.atoms.atom[index[i + 1]].resind) { - fprintf(fp, "%5d %8.4f\n", + fprintf(fp, + "%5d %8.4f\n", bRes ? top.atoms.resinfo[top.atoms.atom[index[i]].resind].nr : index[i] + 1, std::sqrt(rmsf[i])); } @@ -540,7 +543,8 @@ int gmx_rmsf(int argc, char* argv[]) if (!bRes || i + 1 == isize || top.atoms.atom[index[i]].resind != top.atoms.atom[index[i + 1]].resind) { - fprintf(fp, "%5d %8.4f\n", + fprintf(fp, + "%5d %8.4f\n", bRes ? top.atoms.resinfo[top.atoms.atom[index[i]].resind].nr : index[i] + 1, std::sqrt(rmsf[i])); } @@ -555,8 +559,8 @@ int gmx_rmsf(int argc, char* argv[]) { rvec_inc(pdbx[index[i]], xcm); } - write_sto_conf_indexed(opt2fn("-oq", NFILE, fnm), title, pdbatoms, pdbx, nullptr, pbcType, - pdbbox, isize, index); + write_sto_conf_indexed( + opt2fn("-oq", NFILE, fnm), title, pdbatoms, pdbx, nullptr, pbcType, pdbbox, isize, index); } if (opt2bSet("-ox", NFILE, fnm)) { @@ -570,8 +574,8 @@ int gmx_rmsf(int argc, char* argv[]) } } /* Write a .pdb file with B-factors and optionally anisou records */ - write_sto_conf_indexed(opt2fn("-ox", NFILE, fnm), title, pdbatoms, bFactorX, nullptr, - pbcType, pdbbox, isize, index); + write_sto_conf_indexed( + opt2fn("-ox", NFILE, fnm), title, pdbatoms, bFactorX, nullptr, pbcType, pdbbox, isize, index); sfree(bFactorX); } if (bAniso) diff --git a/src/gromacs/gmxana/gmx_rotacf.cpp b/src/gromacs/gmxana/gmx_rotacf.cpp index 048c663158..7b5f2ffe3b 100644 --- a/src/gromacs/gmxana/gmx_rotacf.cpp +++ b/src/gromacs/gmxana/gmx_rotacf.cpp @@ -113,8 +113,8 @@ int gmx_rotacf(int argc, char* argv[]) npargs = asize(pa); ppa = add_acf_pargs(&npargs, pa); - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, npargs, ppa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, npargs, ppa, asize(desc), desc, 0, nullptr, &oenv)) { sfree(ppa); return 0; @@ -228,8 +228,8 @@ int gmx_rotacf(int argc, char* argv[]) mode = eacVector; - do_autocorr(ftp2fn(efXVG, NFILE, fnm), oenv, "Rotational Correlation Function", teller, - nvec, c1, dt, mode, bAver); + do_autocorr( + ftp2fn(efXVG, NFILE, fnm), oenv, "Rotational Correlation Function", teller, nvec, c1, dt, mode, bAver); } do_view(oenv, ftp2fn(efXVG, NFILE, fnm), nullptr); diff --git a/src/gromacs/gmxana/gmx_rotmat.cpp b/src/gromacs/gmxana/gmx_rotmat.cpp index 6bc93086af..2a0959aee1 100644 --- a/src/gromacs/gmxana/gmx_rotmat.cpp +++ b/src/gromacs/gmxana/gmx_rotmat.cpp @@ -92,7 +92,8 @@ static void get_refx(gmx_output_env_t* oenv, { gmx_fatal(FARGS, "Atom index (%d) is larger than the number of atoms in the trajecory (%d)", - index[a] + 1, natoms); + index[a] + 1, + natoms); } w_rls[a] = (bMW ? top->atoms.atom[index[a]].m : 1.0); tot_mass += w_rls[a]; @@ -246,8 +247,8 @@ int gmx_rotmat(int argc, char* argv[]) { efXVG, nullptr, "rotmat", ffWRITE } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -263,8 +264,7 @@ int gmx_rotmat(int argc, char* argv[]) GMX_RELEASE_ASSERT(reffit[0] != nullptr, "Options inconsistency; reffit[0] is NULL"); if (reffit[0][0] != 'n') { - get_refx(oenv, ftp2fn(efTRX, NFILE, fnm), reffit[0][2] == 'z' ? 3 : 2, skip, gnx, index, - bMW, &top, pbcType, x_ref); + get_refx(oenv, ftp2fn(efTRX, NFILE, fnm), reffit[0][2] == 'z' ? 3 : 2, skip, gnx, index, bMW, &top, pbcType, x_ref); } natoms = read_first_x(oenv, &status, ftp2fn(efTRX, NFILE, fnm), &t, &x, box); @@ -276,7 +276,8 @@ int gmx_rotmat(int argc, char* argv[]) { gmx_fatal(FARGS, "Atom index (%d) is larger than the number of atoms in the trajecory (%d)", - index[i] + 1, natoms); + index[i] + 1, + natoms); } w_rls[index[i]] = (bMW ? top.atoms.atom[index[i]].m : 1.0); } @@ -302,8 +303,18 @@ int gmx_rotmat(int argc, char* argv[]) calc_fit_R(DIM, natoms, w_rls, x_ref, x, R); - fprintf(out, "%7g %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f\n", t, R[XX][XX], - R[XX][YY], R[XX][ZZ], R[YY][XX], R[YY][YY], R[YY][ZZ], R[ZZ][XX], R[ZZ][YY], R[ZZ][ZZ]); + fprintf(out, + "%7g %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f %7.4f\n", + t, + R[XX][XX], + R[XX][YY], + R[XX][ZZ], + R[YY][XX], + R[YY][YY], + R[YY][ZZ], + R[ZZ][XX], + R[ZZ][YY], + R[ZZ][ZZ]); } while (read_next_x(oenv, status, &t, x, box)); gmx_rmpbc_done(gpbc); diff --git a/src/gromacs/gmxana/gmx_saltbr.cpp b/src/gromacs/gmxana/gmx_saltbr.cpp index 46faac3668..bf21debe3c 100644 --- a/src/gromacs/gmxana/gmx_saltbr.cpp +++ b/src/gromacs/gmxana/gmx_saltbr.cpp @@ -150,8 +150,8 @@ int gmx_saltbr(int argc, char* argv[]) matrix box; gmx_output_env_t* oenv; - if (!parse_common_args(&argc, argv, PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, - 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } diff --git a/src/gromacs/gmxana/gmx_sans.cpp b/src/gromacs/gmxana/gmx_sans.cpp index ab77d08a1c..b6ac442c47 100644 --- a/src/gromacs/gmxana/gmx_sans.cpp +++ b/src/gromacs/gmxana/gmx_sans.cpp @@ -157,8 +157,8 @@ int gmx_sans(int argc, char* argv[]) nthreads = gmx_omp_get_max_threads(); - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -213,8 +213,7 @@ int gmx_sans(int argc, char* argv[]) fnTRX = ftp2fn(efTRX, NFILE, fnm); gnsf = gmx_neutronstructurefactors_init(fnDAT); - fprintf(stderr, "Read %d atom names from %s with neutron scattering parameters\n\n", - gnsf->nratoms, fnDAT); + fprintf(stderr, "Read %d atom names from %s with neutron scattering parameters\n\n", gnsf->nratoms, fnDAT); snew(top, 1); snew(grpname, 1); @@ -237,8 +236,10 @@ int gmx_sans(int argc, char* argv[]) natoms = read_first_x(oenv, &status, fnTRX, &t, &x, box); if (natoms != top->atoms.nr) { - fprintf(stderr, "\nWARNING: number of atoms in tpx (%d) and trajectory (%d) do not match\n", - natoms, top->atoms.nr); + fprintf(stderr, + "\nWARNING: number of atoms in tpx (%d) and trajectory (%d) do not match\n", + natoms, + top->atoms.nr); } do @@ -254,8 +255,8 @@ int gmx_sans(int argc, char* argv[]) snew(pr, 1); } /* realy calc p(r) */ - prframecurrent = calc_radial_distribution_histogram(gsans, x, box, index, isize, binwidth, - bMC, bNORM, mcover, seed); + prframecurrent = calc_radial_distribution_histogram( + gsans, x, box, index, isize, binwidth, bMC, bNORM, mcover, seed); /* copy prframecurrent -> pr and summ up pr->gr[i] */ /* allocate and/or resize memory for pr->gr[i] and pr->r[i] */ if (pr->gr == nullptr) @@ -296,8 +297,11 @@ int gmx_sans(int argc, char* argv[]) auto fnmdup = filenames; sprintf(suffix, "-t%.2f", t); add_suffix_to_output_names(fnmdup.data(), NFILE, suffix); - fp = xvgropen(opt2fn_null("-prframe", NFILE, fnmdup.data()), hdr, "Distance (nm)", - "Probability", oenv); + fp = xvgropen(opt2fn_null("-prframe", NFILE, fnmdup.data()), + hdr, + "Distance (nm)", + "Probability", + oenv); for (i = 0; i < prframecurrent->grn; i++) { fprintf(fp, "%10.6f%10.6f\n", prframecurrent->r[i], prframecurrent->gr[i]); @@ -316,8 +320,8 @@ int gmx_sans(int argc, char* argv[]) auto fnmdup = filenames; sprintf(suffix, "-t%.2f", t); add_suffix_to_output_names(fnmdup.data(), NFILE, suffix); - fp = xvgropen(opt2fn_null("-sqframe", NFILE, fnmdup.data()), hdr, "q (nm^-1)", - "s(q)/s(0)", oenv); + fp = xvgropen( + opt2fn_null("-sqframe", NFILE, fnmdup.data()), hdr, "q (nm^-1)", "s(q)/s(0)", oenv); for (i = 0; i < sqframecurrent->qn; i++) { fprintf(fp, "%10.6f%10.6f\n", sqframecurrent->q[i], sqframecurrent->s[i]); diff --git a/src/gromacs/gmxana/gmx_saxs.cpp b/src/gromacs/gmxana/gmx_saxs.cpp index 6827fa1c8d..9db2db1fda 100644 --- a/src/gromacs/gmxana/gmx_saxs.cpp +++ b/src/gromacs/gmxana/gmx_saxs.cpp @@ -72,8 +72,8 @@ int gmx_saxs(int argc, char* argv[]) { efXVG, "-sq", "sq", ffWRITE }, }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME, NFILE, fnm, NPA, pa, asize(desc), desc, 0, - nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME, NFILE, fnm, NPA, pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -83,8 +83,8 @@ int gmx_saxs(int argc, char* argv[]) fnDAT = ftp2fn(efDAT, NFILE, fnm); fnNDX = ftp2fn_null(efNDX, NFILE, fnm); - do_scattering_intensity(fnTPS, fnNDX, opt2fn("-sq", NFILE, fnm), fnTRX, fnDAT, start_q, end_q, - energy, ngroups, oenv); + do_scattering_intensity( + fnTPS, fnNDX, opt2fn("-sq", NFILE, fnm), fnTRX, fnDAT, start_q, end_q, energy, ngroups, oenv); please_cite(stdout, "Cromer1968a"); diff --git a/src/gromacs/gmxana/gmx_sham.cpp b/src/gromacs/gmxana/gmx_sham.cpp index cc7d8f9e88..2fe286abe1 100644 --- a/src/gromacs/gmxana/gmx_sham.cpp +++ b/src/gromacs/gmxana/gmx_sham.cpp @@ -112,10 +112,25 @@ static void lo_write_xplor(XplorMap* map, const char* file) fprintf(fp, "\n 2 !NTITLE\n"); fprintf(fp, " REMARKS Energy Landscape from GROMACS\n"); fprintf(fp, " REMARKS DATE: 2004-12-21 \n"); - fprintf(fp, " %7d %7d %7d %7d %7d %7d %7d %7d %7d\n", map->Nx, map->dmin[0], map->dmax[0], - map->Ny, map->dmin[1], map->dmax[1], map->Nz, map->dmin[2], map->dmax[2]); - fprintf(fp, "%12.5E%12.5E%12.5E%12.5E%12.5E%12.5E\n", map->cell[0], map->cell[1], map->cell[2], - map->cell[3], map->cell[4], map->cell[5]); + fprintf(fp, + " %7d %7d %7d %7d %7d %7d %7d %7d %7d\n", + map->Nx, + map->dmin[0], + map->dmax[0], + map->Ny, + map->dmin[1], + map->dmax[1], + map->Nz, + map->dmin[2], + map->dmax[2]); + fprintf(fp, + "%12.5E%12.5E%12.5E%12.5E%12.5E%12.5E\n", + map->cell[0], + map->cell[1], + map->cell[2], + map->cell[3], + map->cell[4], + map->cell[5]); fprintf(fp, "ZYX\n"); z = map->dmin[2]; @@ -233,7 +248,9 @@ static inline void print_minimum(FILE* fp, int num, const t_minimum* min) fprintf(fp, "Minimum %d at index " "%" PRId64 " energy %10.3f\n", - num, min->index, min->ener); + num, + min->index, + min->ener); } static inline void add_minimum(FILE* fp, int num, const t_minimum* min, t_minimum* mm) @@ -314,14 +331,14 @@ static void pick_minima(const char* logfile, int* ibox, int ndim, int len, real this_min.index = index3(ibox, i, j, k); this_min.ener = W[this_min.index]; if (is_local_minimum_from_below(&this_min, i, 0, index3(ibox, i - 1, j, k), W) - && is_local_minimum_from_above(&this_min, i, ibox[0] - 1, - index3(ibox, i + 1, j, k), W) + && is_local_minimum_from_above( + &this_min, i, ibox[0] - 1, index3(ibox, i + 1, j, k), W) && is_local_minimum_from_below(&this_min, j, 0, index3(ibox, i, j - 1, k), W) - && is_local_minimum_from_above(&this_min, j, ibox[1] - 1, - index3(ibox, i, j + 1, k), W) + && is_local_minimum_from_above( + &this_min, j, ibox[1] - 1, index3(ibox, i, j + 1, k), W) && is_local_minimum_from_below(&this_min, k, 0, index3(ibox, i, j, k - 1), W) - && is_local_minimum_from_above(&this_min, k, ibox[2] - 1, - index3(ibox, i, j, k + 1), W)) + && is_local_minimum_from_above( + &this_min, k, ibox[2] - 1, index3(ibox, i, j, k + 1), W)) { add_minimum(fp, nmin, &this_min, mm); nmin++; @@ -365,12 +382,12 @@ static void pick_minima(const char* logfile, int* ibox, int ndim, int len, real int index = this_point[i]; this_point[i]--; bMin = bMin - && is_local_minimum_from_below(&this_min, index, 0, - indexn(ndim, ibox, this_point), W); + && is_local_minimum_from_below( + &this_min, index, 0, indexn(ndim, ibox, this_point), W); this_point[i] += 2; bMin = bMin - && is_local_minimum_from_above(&this_min, index, ibox[i] - 1, - indexn(ndim, ibox, this_point), W); + && is_local_minimum_from_above( + &this_min, index, ibox[i] - 1, indexn(ndim, ibox, this_point), W); this_point[i]--; } if (bMin) @@ -481,8 +498,10 @@ static void do_sham(const char* fn, { if (max_eig[i] > xmax[i]) { - gmx_warning("Your xmax[%d] value %f is smaller than the largest data point %f", i, - xmax[i], max_eig[i]); + gmx_warning("Your xmax[%d] value %f is smaller than the largest data point %f", + i, + xmax[i], + max_eig[i]); } max_eig[i] = xmax[i]; } @@ -495,8 +514,10 @@ static void do_sham(const char* fn, { if (min_eig[i] < xmin[i]) { - gmx_warning("Your xmin[%d] value %f is larger than the smallest data point %f", i, - xmin[i], min_eig[i]); + gmx_warning("Your xmin[%d] value %f is larger than the smallest data point %f", + i, + xmin[i], + min_eig[i]); } min_eig[i] = xmin[i]; } @@ -744,20 +765,76 @@ static void do_sham(const char* fn, SS[i] = &(S[i * ibox[1]]); } fp = gmx_ffopen(xpmP, "w"); - write_xpm(fp, flags, "Probability Distribution", "", "PC1", "PC2", ibox[0], ibox[1], axis_x, - axis_y, PP, 0, Pmax, rlo, rhi, &nlevels); + write_xpm(fp, + flags, + "Probability Distribution", + "", + "PC1", + "PC2", + ibox[0], + ibox[1], + axis_x, + axis_y, + PP, + 0, + Pmax, + rlo, + rhi, + &nlevels); gmx_ffclose(fp); fp = gmx_ffopen(xpm, "w"); - write_xpm(fp, flags, "Gibbs Energy Landscape", "G (kJ/mol)", "PC1", "PC2", ibox[0], ibox[1], - axis_x, axis_y, WW, 0, gmax, rlo, rhi, &nlevels); + write_xpm(fp, + flags, + "Gibbs Energy Landscape", + "G (kJ/mol)", + "PC1", + "PC2", + ibox[0], + ibox[1], + axis_x, + axis_y, + WW, + 0, + gmax, + rlo, + rhi, + &nlevels); gmx_ffclose(fp); fp = gmx_ffopen(xpm2, "w"); - write_xpm(fp, flags, "Enthalpy Landscape", "H (kJ/mol)", "PC1", "PC2", ibox[0], ibox[1], - axis_x, axis_y, EE, emin ? *emin : Emin, emax ? *emax : Einf, rlo, rhi, &nlevels); + write_xpm(fp, + flags, + "Enthalpy Landscape", + "H (kJ/mol)", + "PC1", + "PC2", + ibox[0], + ibox[1], + axis_x, + axis_y, + EE, + emin ? *emin : Emin, + emax ? *emax : Einf, + rlo, + rhi, + &nlevels); gmx_ffclose(fp); fp = gmx_ffopen(xpm3, "w"); - write_xpm(fp, flags, "Entropy Landscape", "TDS (kJ/mol)", "PC1", "PC2", ibox[0], ibox[1], - axis_x, axis_y, SS, 0, Sinf, rlo, rhi, &nlevels); + write_xpm(fp, + flags, + "Entropy Landscape", + "TDS (kJ/mol)", + "PC1", + "PC2", + ibox[0], + ibox[1], + axis_x, + axis_y, + SS, + 0, + Sinf, + rlo, + rhi, + &nlevels); gmx_ffclose(fp); } else if (neig == 3) @@ -776,9 +853,18 @@ static void do_sham(const char* fn, index = index3(ibox, i, j, k); if (P[index] > 0) { - fprintf(fp, "%-6s%5d %-4.4s%3.3s %4d %8.3f%8.3f%8.3f%6.2f%6.2f\n", - "ATOM", (index + 1) % 10000, "H", "H", (index + 1) % 10000, xxx[XX], - xxx[YY], xxx[ZZ], 1.0, W[index]); + fprintf(fp, + "%-6s%5d %-4.4s%3.3s %4d %8.3f%8.3f%8.3f%6.2f%6.2f\n", + "ATOM", + (index + 1) % 10000, + "H", + "H", + (index + 1) % 10000, + xxx[XX], + xxx[YY], + xxx[ZZ], + 1.0, + W[index]); } } } @@ -800,8 +886,22 @@ static void do_sham(const char* fn, sprintf(buf, "%s", xpm); sprintf(&buf[std::strlen(xpm) - 4], "12.xpm"); fp = gmx_ffopen(buf, "w"); - write_xpm(fp, flags, "Gibbs Energy Landscape", "W (kJ/mol)", "PC1", "PC2", ibox[0], ibox[1], - axis_x, axis_y, WW, 0, gmax, rlo, rhi, &nlevels); + write_xpm(fp, + flags, + "Gibbs Energy Landscape", + "W (kJ/mol)", + "PC1", + "PC2", + ibox[0], + ibox[1], + axis_x, + axis_y, + WW, + 0, + gmax, + rlo, + rhi, + &nlevels); gmx_ffclose(fp); for (i = 0; (i < ibox[0]); i++) { @@ -812,8 +912,22 @@ static void do_sham(const char* fn, } sprintf(&buf[std::strlen(xpm) - 4], "13.xpm"); fp = gmx_ffopen(buf, "w"); - write_xpm(fp, flags, "SHAM Energy Landscape", "kJ/mol", "PC1", "PC3", ibox[0], ibox[2], - axis_x, axis_z, WW, 0, gmax, rlo, rhi, &nlevels); + write_xpm(fp, + flags, + "SHAM Energy Landscape", + "kJ/mol", + "PC1", + "PC3", + ibox[0], + ibox[2], + axis_x, + axis_z, + WW, + 0, + gmax, + rlo, + rhi, + &nlevels); gmx_ffclose(fp); for (i = 0; (i < ibox[1]); i++) { @@ -824,8 +938,22 @@ static void do_sham(const char* fn, } sprintf(&buf[std::strlen(xpm) - 4], "23.xpm"); fp = gmx_ffopen(buf, "w"); - write_xpm(fp, flags, "SHAM Energy Landscape", "kJ/mol", "PC2", "PC3", ibox[1], ibox[2], - axis_y, axis_z, WW, 0, gmax, rlo, rhi, &nlevels); + write_xpm(fp, + flags, + "SHAM Energy Landscape", + "kJ/mol", + "PC2", + "PC3", + ibox[1], + ibox[2], + axis_y, + axis_z, + WW, + 0, + gmax, + rlo, + rhi, + &nlevels); gmx_ffclose(fp); sfree(buf); } @@ -1011,14 +1139,23 @@ int gmx_sham(int argc, char* argv[]) int npargs; npargs = asize(pa); - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW, NFILE, fnm, npargs, pa, asize(desc), desc, 0, - nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW, NFILE, fnm, npargs, pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } - val = read_xvg_time(opt2fn("-f", NFILE, fnm), bHaveT, opt2parg_bSet("-b", npargs, pa), tb - ttol, - opt2parg_bSet("-e", npargs, pa), te + ttol, nsets_in, &nset, &n, &dt, &t); + val = read_xvg_time(opt2fn("-f", NFILE, fnm), + bHaveT, + opt2parg_bSet("-b", npargs, pa), + tb - ttol, + opt2parg_bSet("-e", npargs, pa), + te + ttol, + nsets_in, + &nset, + &n, + &dt, + &t); printf("Read %d sets of %d points, dt = %g\n\n", nset, n, dt); fn_ge = opt2fn_null("-ge", NFILE, fnm); @@ -1031,9 +1168,17 @@ int gmx_sham(int argc, char* argv[]) if (fn_ge || fn_ene) { - et_val = read_xvg_time(fn_ge ? fn_ge : fn_ene, bHaveT, opt2parg_bSet("-b", npargs, pa), - tb - ttol, opt2parg_bSet("-e", npargs, pa), te + ttol, 1, &e_nset, - &e_n, &e_dt, &e_t); + et_val = read_xvg_time(fn_ge ? fn_ge : fn_ene, + bHaveT, + opt2parg_bSet("-b", npargs, pa), + tb - ttol, + opt2parg_bSet("-e", npargs, pa), + te + ttol, + 1, + &e_nset, + &e_n, + &e_dt, + &e_t); if (fn_ge) { if (e_nset != 1) @@ -1046,13 +1191,17 @@ int gmx_sham(int argc, char* argv[]) if (e_nset != 1 && e_nset != 2) { gmx_fatal(FARGS, - "Can only handle one energy component or one energy and one T in %s", fn_ene); + "Can only handle one energy component or one energy and one T in %s", + fn_ene); } } if (e_n != n) { - gmx_fatal(FARGS, "Number of energies (%d) does not match number of entries (%d) in %s", - e_n, n, opt2fn("-f", NFILE, fnm)); + gmx_fatal(FARGS, + "Number of energies (%d) does not match number of entries (%d) in %s", + e_n, + n, + opt2fn("-f", NFILE, fnm)); } } else @@ -1098,12 +1247,33 @@ int gmx_sham(int argc, char* argv[]) } /* The number of grid points fits in a int64_t. */ - do_sham(opt2fn("-dist", NFILE, fnm), opt2fn("-bin", NFILE, fnm), opt2fn("-lp", NFILE, fnm), - opt2fn("-ls", NFILE, fnm), opt2fn("-lsh", NFILE, fnm), opt2fn("-lss", NFILE, fnm), - opt2fn("-ls3", NFILE, fnm), opt2fn("-g", NFILE, fnm), n, nset, val, fn_ge != nullptr, - e_nset, et_val, Tref, pmax, gmax, opt2parg_bSet("-emin", NPA, pa) ? &emin : nullptr, - opt2parg_bSet("-emax", NPA, pa) ? &emax : nullptr, nlevels, pmin, idim, ibox, - opt2parg_bSet("-xmin", NPA, pa), rmin, opt2parg_bSet("-xmax", NPA, pa), rmax); + do_sham(opt2fn("-dist", NFILE, fnm), + opt2fn("-bin", NFILE, fnm), + opt2fn("-lp", NFILE, fnm), + opt2fn("-ls", NFILE, fnm), + opt2fn("-lsh", NFILE, fnm), + opt2fn("-lss", NFILE, fnm), + opt2fn("-ls3", NFILE, fnm), + opt2fn("-g", NFILE, fnm), + n, + nset, + val, + fn_ge != nullptr, + e_nset, + et_val, + Tref, + pmax, + gmax, + opt2parg_bSet("-emin", NPA, pa) ? &emin : nullptr, + opt2parg_bSet("-emax", NPA, pa) ? &emax : nullptr, + nlevels, + pmin, + idim, + ibox, + opt2parg_bSet("-xmin", NPA, pa), + rmin, + opt2parg_bSet("-xmax", NPA, pa), + rmax); return 0; } diff --git a/src/gromacs/gmxana/gmx_sigeps.cpp b/src/gromacs/gmxana/gmx_sigeps.cpp index 498416abcf..e50ca4ee42 100644 --- a/src/gromacs/gmxana/gmx_sigeps.cpp +++ b/src/gromacs/gmxana/gmx_sigeps.cpp @@ -104,8 +104,8 @@ int gmx_sigeps(int argc, char* argv[]) int cur = 0; #define next (1 - cur) - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, - 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -169,8 +169,7 @@ int gmx_sigeps(int argc, char* argv[]) { minimum = oldx + dp[cur] * (x - oldx) / (dp[cur] - dp[next]); mval = pot(minimum, qq, c6, cn, npow); - printf("Van der Waals + Coulomb minimum at r = %g (nm). Value = %g (kJ/mol)\n", - minimum, mval); + printf("Van der Waals + Coulomb minimum at r = %g (nm). Value = %g (kJ/mol)\n", minimum, mval); } } cur = next; diff --git a/src/gromacs/gmxana/gmx_sorient.cpp b/src/gromacs/gmxana/gmx_sorient.cpp index 4561a28a80..905769d4ce 100644 --- a/src/gromacs/gmxana/gmx_sorient.cpp +++ b/src/gromacs/gmxana/gmx_sorient.cpp @@ -195,8 +195,8 @@ int gmx_sorient(int argc, char* argv[]) { efXVG, "-co", "scum", ffWRITE }, { efXVG, "-rc", "scount", ffWRITE } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -415,7 +415,10 @@ int gmx_sorient(int argc, char* argv[]) xvgr_legend(fp, 2, legr, oenv); for (i = 0; i < nrbin; i++) { - fprintf(fp, "%g %g %g\n", (i + 0.5) * rbinw, histn[i] ? histi1[i] / histn[i] : 0, + fprintf(fp, + "%g %g %g\n", + (i + 0.5) * rbinw, + histn[i] ? histi1[i] / histn[i] : 0, histn[i] ? histi2[i] / histn[i] : 0); } xvgrclose(fp); diff --git a/src/gromacs/gmxana/gmx_spatial.cpp b/src/gromacs/gmxana/gmx_spatial.cpp index 0ec43ffafd..81ea6d0c77 100644 --- a/src/gromacs/gmxana/gmx_spatial.cpp +++ b/src/gromacs/gmxana/gmx_spatial.cpp @@ -190,8 +190,8 @@ int gmx_spatial(int argc, char* argv[]) /* This is the routine responsible for adding default options, * calling the X/motif interface, etc. */ - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, - asize(desc), desc, asize(bugs), bugs, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, asize(bugs), bugs, &oenv)) { return 0; } @@ -284,10 +284,17 @@ int gmx_spatial(int argc, char* argv[]) { printf("There was an item outside of the allocated memory. Increase the value " "given with the -nab option.\n"); - printf("Memory was allocated for [%f,%f,%f]\tto\t[%f,%f,%f]\n", MINBIN[XX], - MINBIN[YY], MINBIN[ZZ], MAXBIN[XX], MAXBIN[YY], MAXBIN[ZZ]); - printf("Memory was required for [%f,%f,%f]\n", fr.x[index[i]][XX], - fr.x[index[i]][YY], fr.x[index[i]][ZZ]); + printf("Memory was allocated for [%f,%f,%f]\tto\t[%f,%f,%f]\n", + MINBIN[XX], + MINBIN[YY], + MINBIN[ZZ], + MAXBIN[XX], + MAXBIN[YY], + MAXBIN[ZZ]); + printf("Memory was required for [%f,%f,%f]\n", + fr.x[index[i]][XX], + fr.x[index[i]][YY], + fr.x[index[i]][ZZ]); exit(1); } x = static_cast(std::ceil((fr.x[index[i]][XX] - MINBIN[XX]) / rBINWIDTH)); @@ -341,16 +348,15 @@ int gmx_spatial(int argc, char* argv[]) flp = gmx_ffopen("grid.cube", "w"); fprintf(flp, "Spatial Distribution Function\n"); fprintf(flp, "test\n"); - fprintf(flp, "%5d%12.6f%12.6f%12.6f\n", nidxp, + fprintf(flp, + "%5d%12.6f%12.6f%12.6f\n", + nidxp, (MINBIN[XX] + (minx + iIGNOREOUTER) * rBINWIDTH) * 10. / bohr, (MINBIN[YY] + (miny + iIGNOREOUTER) * rBINWIDTH) * 10. / bohr, (MINBIN[ZZ] + (minz + iIGNOREOUTER) * rBINWIDTH) * 10. / bohr); - fprintf(flp, "%5d%12.6f%12.6f%12.6f\n", maxx - minx + 1 - (2 * iIGNOREOUTER), - rBINWIDTH * 10. / bohr, 0., 0.); - fprintf(flp, "%5d%12.6f%12.6f%12.6f\n", maxy - miny + 1 - (2 * iIGNOREOUTER), 0., - rBINWIDTH * 10. / bohr, 0.); - fprintf(flp, "%5d%12.6f%12.6f%12.6f\n", maxz - minz + 1 - (2 * iIGNOREOUTER), 0., 0., - rBINWIDTH * 10. / bohr); + fprintf(flp, "%5d%12.6f%12.6f%12.6f\n", maxx - minx + 1 - (2 * iIGNOREOUTER), rBINWIDTH * 10. / bohr, 0., 0.); + fprintf(flp, "%5d%12.6f%12.6f%12.6f\n", maxy - miny + 1 - (2 * iIGNOREOUTER), 0., rBINWIDTH * 10. / bohr, 0.); + fprintf(flp, "%5d%12.6f%12.6f%12.6f\n", maxz - minz + 1 - (2 * iIGNOREOUTER), 0., 0., rBINWIDTH * 10. / bohr); for (i = 0; i < nidxp; i++) { v = 2; @@ -374,8 +380,13 @@ int gmx_spatial(int argc, char* argv[]) { v = 16; } - fprintf(flp, "%5d%12.6f%12.6f%12.6f%12.6f\n", v, 0., fr.x[indexp[i]][XX] * 10.0 / bohr, - fr.x[indexp[i]][YY] * 10.0 / bohr, fr.x[indexp[i]][ZZ] * 10.0 / bohr); + fprintf(flp, + "%5d%12.6f%12.6f%12.6f%12.6f\n", + v, + 0., + fr.x[indexp[i]][XX] * 10.0 / bohr, + fr.x[indexp[i]][YY] * 10.0 / bohr, + fr.x[indexp[i]][ZZ] * 10.0 / bohr); } tot = 0; @@ -481,14 +492,18 @@ int gmx_spatial(int argc, char* argv[]) if (bCALCDIV) { printf("Counts per frame in all %d cubes divided by %le\n", numcu, 1.0 / norm); - printf("Normalized data: average %le, min %le, max %le\n", 1.0, minval * norm / numfr, + printf("Normalized data: average %le, min %le, max %le\n", + 1.0, + minval * norm / numfr, maxval * norm / numfr); } else { printf("grid.cube contains counts per frame in all %d cubes\n", numcu); - printf("Raw data: average %le, min %le, max %le\n", 1.0 / norm, - static_cast(minval) / numfr, static_cast(maxval) / numfr); + printf("Raw data: average %le, min %le, max %le\n", + 1.0 / norm, + static_cast(minval) / numfr, + static_cast(maxval) / numfr); } return 0; diff --git a/src/gromacs/gmxana/gmx_spol.cpp b/src/gromacs/gmxana/gmx_spol.cpp index d67045be90..a787a78aeb 100644 --- a/src/gromacs/gmxana/gmx_spol.cpp +++ b/src/gromacs/gmxana/gmx_spol.cpp @@ -129,8 +129,10 @@ static void spol_atom2molindex(int* n, int* index, const t_block* mols) } if (m == mols->nr) { - gmx_fatal(FARGS, "index[%d]=%d does not correspond to the first atom of a molecule", - i + 1, index[i] + 1); + gmx_fatal(FARGS, + "index[%d]=%d does not correspond to the first atom of a molecule", + i + 1, + index[i] + 1); } for (j = mols->index[m]; j < mols->index[m + 1]; j++) { @@ -210,8 +212,8 @@ int gmx_spol(int argc, char* argv[]) { efXVG, nullptr, "scdist", ffWRITE } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME | PCA_CAN_VIEW, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -356,15 +358,16 @@ int gmx_spol(int argc, char* argv[]) sfree(x); close_trx(status); - fprintf(stderr, "Average number of molecules within %g nm is %.1f\n", rmax, - static_cast(ntot) / nf); + fprintf(stderr, "Average number of molecules within %g nm is %.1f\n", rmax, static_cast(ntot) / nf); if (ntot > 0) { sdip /= ntot; sdip2 /= ntot; sinp /= ntot; sdinp /= ntot; - fprintf(stderr, "Average dipole: %f (D), std.dev. %f\n", sdip, + fprintf(stderr, + "Average dipole: %f (D), std.dev. %f\n", + sdip, std::sqrt(sdip2 - gmx::square(sdip))); fprintf(stderr, "Average radial component of the dipole: %f (D)\n", sinp); fprintf(stderr, "Average radial component of the polarization: %f (D)\n", sdinp); diff --git a/src/gromacs/gmxana/gmx_tcaf.cpp b/src/gromacs/gmxana/gmx_tcaf.cpp index 03e9f2c6ad..a0d0ce2ae6 100644 --- a/src/gromacs/gmxana/gmx_tcaf.cpp +++ b/src/gromacs/gmxana/gmx_tcaf.cpp @@ -151,8 +151,22 @@ static void process_tcaf(int nframes, sig[i] = std::exp(0.5 * i * dt / wt); } - low_do_autocorr(fn_tca, oenv, "Transverse Current Autocorrelation Functions", nframes, ntc, - ncorr, tc, dt, eacNormal, 1, FALSE, FALSE, FALSE, 0, 0, 0); + low_do_autocorr(fn_tca, + oenv, + "Transverse Current Autocorrelation Functions", + nframes, + ntc, + ncorr, + tc, + dt, + eacNormal, + 1, + FALSE, + FALSE, + FALSE, + 0, + 0, + 0); do_view(oenv, fn_tca, "-nxy"); fp = xvgropen(fn_tc, "Transverse Current Autocorrelation Functions", "Time (ps)", "TCAF", oenv); @@ -226,8 +240,7 @@ static void process_tcaf(int nframes, tcaf[k][0] = 1.0; fitparms[0] = 1; fitparms[1] = 1; - do_lmfit(ncorr, tcaf[k], sig, dt, nullptr, 0, ncorr * dt, oenv, bDebugMode(), effnVAC, - fitparms, 0, nullptr); + do_lmfit(ncorr, tcaf[k], sig, dt, nullptr, 0, ncorr * dt, oenv, bDebugMode(), effnVAC, fitparms, 0, nullptr); eta = 1000 * fitparms[1] * rho / (4 * fitparms[0] * PICO * norm2(kfac[k]) / (NANO * NANO)); fprintf(stdout, "k %6.3f tau %6.3f eta %8.5f 10^-3 kg/(m s)\n", norm(kfac[k]), fitparms[0], eta); fprintf(fp_vk, "%6.3f %g\n", norm(kfac[k]), eta); @@ -249,12 +262,15 @@ static void process_tcaf(int nframes, tcafc[k][0] = 1.0; fitparms[0] = 1; fitparms[1] = 1; - do_lmfit(ncorr, tcafc[k], sig, dt, nullptr, 0, ncorr * dt, oenv, bDebugMode(), effnVAC, - fitparms, 0, nullptr); + do_lmfit(ncorr, tcafc[k], sig, dt, nullptr, 0, ncorr * dt, oenv, bDebugMode(), effnVAC, fitparms, 0, nullptr); eta = 1000 * fitparms[1] * rho / (4 * fitparms[0] * PICO * norm2(kfac[kset_c[k]]) / (NANO * NANO)); - fprintf(stdout, "k %6.3f tau %6.3f Omega %6.3f eta %8.5f 10^-3 kg/(m s)\n", - norm(kfac[kset_c[k]]), fitparms[0], fitparms[1], eta); + fprintf(stdout, + "k %6.3f tau %6.3f Omega %6.3f eta %8.5f 10^-3 kg/(m s)\n", + norm(kfac[kset_c[k]]), + fitparms[0], + fitparms[1], + eta); fprintf(fp_vk, "%6.3f %g\n", norm(kfac[kset_c[k]]), eta); for (i = 0; i < ncorr; i++) { @@ -350,8 +366,8 @@ int gmx_tcaf(int argc, char* argv[]) npargs = asize(pa); ppa = add_acf_pargs(&npargs, pa); - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, npargs, ppa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, npargs, ppa, asize(desc), desc, 0, nullptr, &oenv)) { sfree(ppa); return 0; @@ -494,9 +510,20 @@ int gmx_tcaf(int argc, char* argv[]) rho *= sysmass / nframes * AMU / (NANO * NANO * NANO); fprintf(stdout, "Density = %g (kg/m^3)\n", rho); - process_tcaf(nframes, dt, nkc, tc, kfac, rho, wt, opt2fn_null("-ot", NFILE, fnm), - opt2fn("-oa", NFILE, fnm), opt2fn("-o", NFILE, fnm), opt2fn("-of", NFILE, fnm), - opt2fn_null("-oc", NFILE, fnm), opt2fn("-ov", NFILE, fnm), oenv); + process_tcaf(nframes, + dt, + nkc, + tc, + kfac, + rho, + wt, + opt2fn_null("-ot", NFILE, fnm), + opt2fn("-oa", NFILE, fnm), + opt2fn("-o", NFILE, fnm), + opt2fn("-of", NFILE, fnm), + opt2fn_null("-oc", NFILE, fnm), + opt2fn("-ov", NFILE, fnm), + oenv); return 0; } diff --git a/src/gromacs/gmxana/gmx_traj.cpp b/src/gromacs/gmxana/gmx_traj.cpp index 93c811bb5a..53c71154a0 100644 --- a/src/gromacs/gmxana/gmx_traj.cpp +++ b/src/gromacs/gmxana/gmx_traj.cpp @@ -478,8 +478,12 @@ static void write_pdb_bfac(const char* fname, fp = xvgropen(xname, title, "Atom", "Spatial component", oenv); for (i = 0; i < isize; i++) { - fprintf(fp, "%-5d %10.3f %10.3f %10.3f\n", 1 + i, sum[index[i]][XX], - sum[index[i]][YY], sum[index[i]][ZZ]); + fprintf(fp, + "%-5d %10.3f %10.3f %10.3f\n", + 1 + i, + sum[index[i]][XX], + sum[index[i]][YY], + sum[index[i]][ZZ]); } xvgrclose(fp); max = 0; @@ -516,8 +520,12 @@ static void write_pdb_bfac(const char* fname, } } - printf("Maximum %s is %g on atom %d %s, res. %s %d\n", title, std::sqrt(max), maxi + 1, - *(atoms->atomname[maxi]), *(atoms->resinfo[atoms->atom[maxi].resind].name), + printf("Maximum %s is %g on atom %d %s, res. %s %d\n", + title, + std::sqrt(max), + maxi + 1, + *(atoms->atomname[maxi]), + *(atoms->resinfo[atoms->atom[maxi].resind].name), atoms->resinfo[atoms->atom[maxi].resind].nr); if (atoms->pdbinfo == nullptr) @@ -707,8 +715,18 @@ int gmx_traj(int argc, char* argv[]) }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME | PCA_TIME_UNIT | PCA_CAN_VIEW, NFILE, fnm, - asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args(&argc, + argv, + PCA_CAN_TIME | PCA_TIME_UNIT | PCA_CAN_VIEW, + NFILE, + fnm, + asize(pa), + pa, + asize(desc), + desc, + 0, + nullptr, + &oenv)) { return 0; } @@ -751,7 +769,12 @@ int gmx_traj(int argc, char* argv[]) } std::string sffmt6 = gmx::formatString("%s%s%s%s%s%s", sffmt, sffmt, sffmt, sffmt, sffmt, sffmt); - bTop = read_tps_conf(ftp2fn(efTPS, NFILE, fnm), &top, &pbcType, &xtop, nullptr, topbox, + bTop = read_tps_conf(ftp2fn(efTPS, NFILE, fnm), + &top, + &pbcType, + &xtop, + nullptr, + topbox, bCom && (bOX || bOXT || bOV || bOT || bEKT || bEKR)); sfree(xtop); if ((bMol || bCV || bCF) && !bTop) @@ -788,8 +811,7 @@ int gmx_traj(int argc, char* argv[]) { if (index0[0][i] < 0 || index0[0][i] >= mols->nr) { - gmx_fatal(FARGS, "Molecule index (%d) is out of range (%d-%d)", index0[0][i] + 1, 1, - mols->nr); + gmx_fatal(FARGS, "Molecule index (%d) is out of range (%d-%d)", index0[0][i] + 1, 1, mols->nr); } isize[i] = atndx[index0[0][i] + 1] - atndx[index0[0][i]]; snew(index[i], isize[i]); @@ -822,8 +844,11 @@ int gmx_traj(int argc, char* argv[]) if (bOX) { flags = flags | TRX_READ_X; - outx = xvgropen(opt2fn("-ox", NFILE, fnm), bCom ? "Center of mass" : "Coordinate", label, - "Coordinate (nm)", oenv); + outx = xvgropen(opt2fn("-ox", NFILE, fnm), + bCom ? "Center of mass" : "Coordinate", + label, + "Coordinate (nm)", + oenv); make_legend(outx, ngroups, isize0[0], index0[0], grpname, bCom, bMol, bDim, oenv); } if (bOXT) @@ -834,15 +859,18 @@ int gmx_traj(int argc, char* argv[]) if (bOV) { flags = flags | TRX_READ_V; - outv = xvgropen(opt2fn("-ov", NFILE, fnm), bCom ? "Center of mass velocity" : "Velocity", - label, "Velocity (nm/ps)", oenv); + outv = xvgropen(opt2fn("-ov", NFILE, fnm), + bCom ? "Center of mass velocity" : "Velocity", + label, + "Velocity (nm/ps)", + oenv); make_legend(outv, ngroups, isize0[0], index0[0], grpname, bCom, bMol, bDim, oenv); } if (bOF) { flags = flags | TRX_READ_F; - outf = xvgropen(opt2fn("-of", NFILE, fnm), "Force", label, - "Force (kJ mol\\S-1\\N nm\\S-1\\N)", oenv); + outf = xvgropen( + opt2fn("-of", NFILE, fnm), "Force", label, "Force (kJ mol\\S-1\\N nm\\S-1\\N)", oenv); make_legend(outf, ngroups, isize0[0], index0[0], grpname, bCom, bMol, bDim, oenv); } if (bOB) @@ -868,8 +896,11 @@ int gmx_traj(int argc, char* argv[]) bDum[ZZ] = FALSE; bDum[DIM] = TRUE; flags = flags | TRX_READ_V; - outekt = xvgropen(opt2fn("-ekt", NFILE, fnm), "Center of mass translation", label, - "Energy (kJ mol\\S-1\\N)", oenv); + outekt = xvgropen(opt2fn("-ekt", NFILE, fnm), + "Center of mass translation", + label, + "Energy (kJ mol\\S-1\\N)", + oenv); make_legend(outekt, ngroups, isize[0], index[0], grpname, bCom, bMol, bDum, oenv); } if (bEKR) @@ -879,8 +910,11 @@ int gmx_traj(int argc, char* argv[]) bDum[ZZ] = FALSE; bDum[DIM] = TRUE; flags = flags | TRX_READ_X | TRX_READ_V; - outekr = xvgropen(opt2fn("-ekr", NFILE, fnm), "Center of mass rotation", label, - "Energy (kJ mol\\S-1\\N)", oenv); + outekr = xvgropen(opt2fn("-ekr", NFILE, fnm), + "Center of mass rotation", + label, + "Energy (kJ mol\\S-1\\N)", + oenv); make_legend(outekr, ngroups, isize[0], index[0], grpname, bCom, bMol, bDum, oenv); } if (bVD) @@ -989,8 +1023,14 @@ int gmx_traj(int argc, char* argv[]) if (bOB && fr.bBox) { fprintf(outb, "\t%g", fr.time); - fprintf(outb, sffmt6.c_str(), fr.box[XX][XX], fr.box[YY][YY], fr.box[ZZ][ZZ], - fr.box[YY][XX], fr.box[ZZ][XX], fr.box[ZZ][YY]); + fprintf(outb, + sffmt6.c_str(), + fr.box[XX][XX], + fr.box[YY][YY], + fr.box[ZZ][ZZ], + fr.box[YY][XX], + fr.box[ZZ][XX], + fr.box[ZZ][YY]); fprintf(outb, "\n"); } if (bOT && fr.bV) @@ -1117,15 +1157,39 @@ int gmx_traj(int argc, char* argv[]) } if (bCV) { - write_pdb_bfac(opt2fn("-cv", NFILE, fnm), opt2fn("-av", NFILE, fnm), "average velocity", - &(top.atoms), pbcType, topbox, isize[0], index[0], nr_xfr, sumx, nr_vfr, - sumv, bDim, scale, oenv); + write_pdb_bfac(opt2fn("-cv", NFILE, fnm), + opt2fn("-av", NFILE, fnm), + "average velocity", + &(top.atoms), + pbcType, + topbox, + isize[0], + index[0], + nr_xfr, + sumx, + nr_vfr, + sumv, + bDim, + scale, + oenv); } if (bCF) { - write_pdb_bfac(opt2fn("-cf", NFILE, fnm), opt2fn("-af", NFILE, fnm), "average force", - &(top.atoms), pbcType, topbox, isize[0], index[0], nr_xfr, sumx, nr_ffr, - sumf, bDim, scale, oenv); + write_pdb_bfac(opt2fn("-cf", NFILE, fnm), + opt2fn("-af", NFILE, fnm), + "average force", + &(top.atoms), + pbcType, + topbox, + isize[0], + index[0], + nr_xfr, + sumx, + nr_ffr, + sumf, + bDim, + scale, + oenv); } /* view it */ diff --git a/src/gromacs/gmxana/gmx_trjorder.cpp b/src/gromacs/gmxana/gmx_trjorder.cpp index 96966c9a00..4c4a9470bf 100644 --- a/src/gromacs/gmxana/gmx_trjorder.cpp +++ b/src/gromacs/gmxana/gmx_trjorder.cpp @@ -151,8 +151,8 @@ int gmx_trjorder(int argc, char* argv[]) { efXVG, "-nshell", "nshell", ffOPTWR } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, - 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -201,8 +201,10 @@ int gmx_trjorder(int argc, char* argv[]) if ((isize_sol % na) != 0) { - gmx_fatal(FARGS, "Number of atoms in the molecule group (%d) is not a multiple of na (%d)", - isize[1], na); + gmx_fatal(FARGS, + "Number of atoms in the molecule group (%d) is not a multiple of na (%d)", + isize[1], + na); } nwat = isize_sol / na; diff --git a/src/gromacs/gmxana/gmx_vanhove.cpp b/src/gromacs/gmxana/gmx_vanhove.cpp index 44edc6539d..011063a4b2 100644 --- a/src/gromacs/gmxana/gmx_vanhove.cpp +++ b/src/gromacs/gmxana/gmx_vanhove.cpp @@ -150,8 +150,8 @@ int gmx_vanhove(int argc, char* argv[]) FILE* fp; t_rgb rlo = { 1, 1, 1 }, rhi = { 0, 0, 0 }; - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -430,9 +430,22 @@ int gmx_vanhove(int argc, char* argv[]) ticky[i] = i * rbin; } fp = gmx_ffopen(matfile, "w"); - write_xpm(fp, MAT_SPATIAL_Y, "Van Hove function", "G (1/nm)", - sbin == 0 ? "time (ps)" : "sqrt(time) (ps^1/2)", "r (nm)", mat_nx, nbin, tickx, - ticky, mat, 0, matmax, rlo, rhi, &nlev); + write_xpm(fp, + MAT_SPATIAL_Y, + "Van Hove function", + "G (1/nm)", + sbin == 0 ? "time (ps)" : "sqrt(time) (ps^1/2)", + "r (nm)", + mat_nx, + nbin, + tickx, + ticky, + mat, + 0, + matmax, + rlo, + rhi, + &nlev); gmx_ffclose(fp); } @@ -455,7 +468,8 @@ int gmx_vanhove(int argc, char* argv[]) fprintf(fp, "%g", i * rbin); for (fbin = 0; fbin < nr; fbin++) { - fprintf(fp, " %g", + fprintf(fp, + " %g", static_cast(pr[fbin][i] / (rcount[fbin] * isize * rbin * (i == 0 ? 0.5 : 1.0)))); } diff --git a/src/gromacs/gmxana/gmx_velacc.cpp b/src/gromacs/gmxana/gmx_velacc.cpp index 48a0ee567f..20c21c5b7a 100644 --- a/src/gromacs/gmxana/gmx_velacc.cpp +++ b/src/gromacs/gmxana/gmx_velacc.cpp @@ -143,8 +143,11 @@ static void calc_spectrum(int n, const real c[], real dt, const char* fn, gmx_ou { gmx_fatal(FARGS, "Invalid fft return status %d", status); } - fp = xvgropen(fn, "Vibrational Power Spectrum", - bRecip ? "\\f{12}w\\f{4} (cm\\S-1\\N)" : "\\f{12}n\\f{4} (ps\\S-1\\N)", "a.u.", oenv); + fp = xvgropen(fn, + "Vibrational Power Spectrum", + bRecip ? "\\f{12}w\\f{4} (cm\\S-1\\N)" : "\\f{12}n\\f{4} (ps\\S-1\\N)", + "a.u.", + oenv); /* This is difficult. * The length of the ACF is dt (as passed to this routine). * We pass the vacf with N time steps from 0 to dt. @@ -229,8 +232,8 @@ int gmx_velacc(int argc, char* argv[]) npargs = asize(pa); ppa = add_acf_pargs(&npargs, pa); - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, npargs, ppa, - asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW | PCA_CAN_TIME, NFILE, fnm, npargs, ppa, asize(desc), desc, 0, nullptr, &oenv)) { sfree(ppa); return 0; @@ -340,9 +343,15 @@ int gmx_velacc(int argc, char* argv[]) { /* Compute time step between frames */ dt = (t1 - t0) / (counter - 1); - do_autocorr(opt2fn("-o", NFILE, fnm), oenv, + do_autocorr(opt2fn("-o", NFILE, fnm), + oenv, bMass ? "Momentum Autocorrelation Function" : "Velocity Autocorrelation Function", - counter, gnx, c1, dt, eacVector, TRUE); + counter, + gnx, + c1, + dt, + eacVector, + TRUE); do_view(oenv, opt2fn("-o", NFILE, fnm), "-nxy"); diff --git a/src/gromacs/gmxana/gmx_wham.cpp b/src/gromacs/gmxana/gmx_wham.cpp index 9162bbcd4e..1cf91e42d7 100644 --- a/src/gromacs/gmxana/gmx_wham.cpp +++ b/src/gromacs/gmxana/gmx_wham.cpp @@ -444,8 +444,10 @@ static void setup_tab(const char* fn, t_UmbrellaOptions* opt) opt->tabX[i] = y[0][i]; opt->tabY[i] = y[1][i]; } - printf("Found equally spaced tabulated potential from %g to %g, spacing %g\n", opt->tabMin, - opt->tabMax, opt->tabDz); + printf("Found equally spaced tabulated potential from %g to %g, spacing %g\n", + opt->tabMin, + opt->tabMax, + opt->tabDz); } //! Read the header of an PDO file (position, force const, nr of groups) @@ -468,7 +470,9 @@ static void read_pdo_header(FILE* file, t_UmbrellaHeader* header, t_UmbrellaOpti gmx_fatal(FARGS, "This does not appear to be a valid pdo file. Found %s, expected %s\n" "(Found in first line: `%s')\n", - Buffer1, "UMBRELLA", line); + Buffer1, + "UMBRELLA", + line); } if (std::strcmp(Buffer2, "3.0") != 0) { @@ -532,8 +536,11 @@ static void read_pdo_header(FILE* file, t_UmbrellaHeader* header, t_UmbrellaOpti if (opt->verbose) { - printf("\tpullgroup %d, pullname = %s, UmbPos = %g, UmbConst = %g\n", i, - header->PullName[i], header->UmbPos[i][0], header->UmbCons[i][0]); + printf("\tpullgroup %d, pullname = %s, UmbPos = %g, UmbConst = %g\n", + i, + header->PullName[i], + header->UmbPos[i][0], + header->UmbCons[i][0]); } } @@ -840,7 +847,9 @@ static double tabulated_pot(double dist, t_UmbrellaOptions* opt) gmx_fatal(FARGS, "Distance %f out of bounds of tabulated potential (jl=%d, ju=%d).\n" "Provide an extended table.", - dist, jl, ju); + dist, + jl, + ju); } pl = opt->tabY[jl]; pu = opt->tabY[ju]; @@ -946,7 +955,9 @@ static void setup_acc_wham(const double* profile, t_UmbrellaWindow* window, int { printf("Initialized rapid wham stuff (contrib tolerance %g)\n" "Evaluating only %d of %d expressions.\n\n", - wham_contrib_lim, nContrib, nTot); + wham_contrib_lim, + nContrib, + nTot); } if (opt->verbose) @@ -1125,8 +1136,7 @@ static void symmetrizeProfile(double* profile, t_UmbrellaOptions* opt) if (min > 0. || max < 0.) { - gmx_fatal(FARGS, "Cannot symmetrize profile around z=0 with min=%f and max=%f\n", opt->min, - opt->max); + gmx_fatal(FARGS, "Cannot symmetrize profile around z=0 with min=%f and max=%f\n", opt->min, opt->max); } snew(prof2, bins); @@ -1249,7 +1259,11 @@ static void getRandomIntArray(int nPull, int blockLength, int* randomArray, gmx: gmx_fatal(FARGS, "Ups, random iWin = %d, nPull = %d, nr = %d, " "blockLength = %d, blockBase = %d\n", - ipullRandom, nPull, nr, blockLength, blockBase); + ipullRandom, + nPull, + nr, + blockLength, + blockBase); } randomArray[ipull] = ipullRandom; } @@ -2106,7 +2120,9 @@ static void read_tpr_header(const char* fn, t_UmbrellaHeader* header, t_Umbrella gmx_fatal(FARGS, "Found %d pull coordinates in %s, but %d columns in the respective line\n" "coordinate selection file (option -is)\n", - ir->pull->ncoord, fn, coordsel->n); + ir->pull->ncoord, + fn, + coordsel->n); } } @@ -2125,7 +2141,9 @@ static void read_tpr_header(const char* fn, t_UmbrellaHeader* header, t_Umbrella "umbrella coodinates can enter WHAM.\n" "If you have umrella and non-umbrella coordinates, you can select the " "umbrella coordinates with gmx wham -is\n", - fn, i + 1, epull_names[header->pcrd[i].pull_type]); + fn, + i + 1, + epull_names[header->pcrd[i].pull_type]); } if (!geometryIsSet) { @@ -2140,7 +2158,10 @@ static void read_tpr_header(const char* fn, t_UmbrellaHeader* header, t_Umbrella "%s, coordinate %d: %s)\n" "If you want to use only some pull coordinates in WHAM, please select " "them with option gmx wham -is\n", - fn, epullg_names[geom], i + 1, epullg_names[header->pcrd[i].geometry]); + fn, + epullg_names[geom], + i + 1, + epullg_names[header->pcrd[i].geometry]); } if (thedim[XX] != header->pcrd[i].dim[XX] || thedim[YY] != header->pcrd[i].dim[YY] || thedim[ZZ] != header->pcrd[i].dim[ZZ]) @@ -2150,8 +2171,13 @@ static void read_tpr_header(const char* fn, t_UmbrellaHeader* header, t_Umbrella "%s %s %s, coordinate %d: %s %s %s)\n" "If you want to use only some pull coordinates in WHAM, please select " "them with option gmx wham -is\n", - fn, int2YN(thedim[XX]), int2YN(thedim[YY]), int2YN(thedim[ZZ]), i + 1, - int2YN(header->pcrd[i].dim[XX]), int2YN(header->pcrd[i].dim[YY]), + fn, + int2YN(thedim[XX]), + int2YN(thedim[YY]), + int2YN(thedim[ZZ]), + i + 1, + int2YN(header->pcrd[i].dim[XX]), + int2YN(header->pcrd[i].dim[YY]), int2YN(header->pcrd[i].dim[ZZ])); } if (header->pcrd[i].geometry == epullgCYL) @@ -2162,7 +2188,8 @@ static void read_tpr_header(const char* fn, t_UmbrellaHeader* header, t_Umbrella FARGS, "With pull geometry 'cylinder', expected pulling in Z direction only.\n" "However, found dimensions [%s %s %s]\n", - int2YN(header->pcrd[i].dim[XX]), int2YN(header->pcrd[i].dim[YY]), + int2YN(header->pcrd[i].dim[XX]), + int2YN(header->pcrd[i].dim[YY]), int2YN(header->pcrd[i].dim[ZZ])); } } @@ -2171,7 +2198,9 @@ static void read_tpr_header(const char* fn, t_UmbrellaHeader* header, t_Umbrella gmx_fatal(FARGS, "%s: Pull coordinate %d has force constant of of %g.\n" "That doesn't seem to be an Umbrella tpr.\n", - fn, i + 1, header->pcrd[i].k); + fn, + i + 1, + header->pcrd[i].k); } } } @@ -2193,9 +2222,15 @@ static void read_tpr_header(const char* fn, t_UmbrellaHeader* header, t_Umbrella for (int i = 0; i < ir->pull->ncoord; i++) { bool use = (coordsel == nullptr || coordsel->bUse[i]); - printf(fmt, epullg_names[header->pcrd[i].geometry], header->pcrd[i].k, header->pcrd[i].init_dist, - int2YN(header->pcrd[i].dim[XX]), int2YN(header->pcrd[i].dim[YY]), - int2YN(header->pcrd[i].dim[ZZ]), header->pcrd[i].ndim, use ? "Yes" : "No"); + printf(fmt, + epullg_names[header->pcrd[i].geometry], + header->pcrd[i].k, + header->pcrd[i].init_dist, + int2YN(header->pcrd[i].dim[XX]), + int2YN(header->pcrd[i].dim[YY]), + int2YN(header->pcrd[i].dim[ZZ]), + header->pcrd[i].ndim, + use ? "Yes" : "No"); printf("\tPull group coordinates of %d groups expected in pullx files.\n", ir->pull->bPrintCOM ? header->pcrd[i].ngroup : 0); } @@ -2301,7 +2336,9 @@ static void read_pull_xf(const char* fn, printf("\t\treaction coordinate: %d\n" "\t\tcenter-of-mass of groups: %d\n" "\t\treference position column: %s\n", - 1, nColCOMCrd[i], (header->bPrintRefValue ? "Yes" : "No")); + 1, + nColCOMCrd[i], + (header->bPrintRefValue ? "Yes" : "No")); } printf("\tFound %d times in %s\n", nt, fn); bFirst = FALSE; @@ -2311,7 +2348,9 @@ static void read_pull_xf(const char* fn, gmx_fatal(FARGS, "Expected %d columns (including time column) in %s, but found %d." " Maybe you confused options -if and -ix ?", - nColExpect, fn, ny); + nColExpect, + fn, + ny); } if (!bGetMinMax) @@ -2338,7 +2377,8 @@ static void read_pull_xf(const char* fn, gmx_fatal(FARGS, "tpr file contains %d pull groups, but expected %d from group selection " "file\n", - header->npullcrds, coordsel->n); + header->npullcrds, + coordsel->n); } window->nPull = coordsel->nUse; } @@ -2491,7 +2531,8 @@ static void read_pull_xf(const char* fn, gmx_fatal(FARGS, "gUsed too large (%d, nPull=%d). This error should have been " "caught before.\n", - gUsed, window->nPull); + gUsed, + window->nPull); } if (opt->bCalcTauInt && !bGetMinMax) @@ -2579,9 +2620,16 @@ static void read_tpr_pullxf_files(char** fnTprs, if (whaminFileType(fnPull[i]) != whamin_pullxf) { gmx_fatal(FARGS, - "Expected the %d'th file in input file to be a xvg (pullx/pullf) file\n", i); - } - read_pull_xf(fnPull[i], header, nullptr, opt, TRUE, &mintmp, &maxtmp, + "Expected the %d'th file in input file to be a xvg (pullx/pullf) file\n", + i); + } + read_pull_xf(fnPull[i], + header, + nullptr, + opt, + TRUE, + &mintmp, + &maxtmp, (opt->nCoordsel > 0) ? &opt->coordsel[i] : nullptr); if (maxtmp > opt->max) { @@ -2612,10 +2660,16 @@ static void read_tpr_pullxf_files(char** fnTprs, read_tpr_header(fnTprs[i], header, opt, (opt->nCoordsel > 0) ? &opt->coordsel[i] : nullptr); if (whaminFileType(fnPull[i]) != whamin_pullxf) { - gmx_fatal(FARGS, - "Expected the %d'th file in input file to be a xvg (pullx/pullf) file\n", i); + gmx_fatal( + FARGS, "Expected the %d'th file in input file to be a xvg (pullx/pullf) file\n", i); } - read_pull_xf(fnPull[i], header, window + i, opt, FALSE, nullptr, nullptr, + read_pull_xf(fnPull[i], + header, + window + i, + opt, + FALSE, + nullptr, + nullptr, (opt->nCoordsel > 0) ? &opt->coordsel[i] : nullptr); if (window[i].Ntot[0] == 0) { @@ -2656,8 +2710,11 @@ static void readIntegratedAutocorrelationTimes(t_UmbrellaWindow* window, int nwi nlines = read_xvg(fn, &iact, &ny); if (nlines != nwins) { - gmx_fatal(FARGS, "Found %d lines with integrated autocorrelation times in %s.\nExpected %d", - nlines, fn, nwins); + gmx_fatal(FARGS, + "Found %d lines with integrated autocorrelation times in %s.\nExpected %d", + nlines, + fn, + nwins); } for (i = 0; i < nlines; i++) { @@ -2758,14 +2815,18 @@ static void calcIntegratedAutocorrelationTimes(t_UmbrellaWindow* window, if (opt->verbose) { - fpcorr = xvgropen("hist_autocorr.xvg", "Autocorrelation functions of umbrella windows", - "time [ps]", "autocorrelation function", opt->oenv); + fpcorr = xvgropen("hist_autocorr.xvg", + "Autocorrelation functions of umbrella windows", + "time [ps]", + "autocorrelation function", + opt->oenv); } printf("\n"); for (i = 0; i < nwins; i++) { - fprintf(stdout, "\rEstimating integrated autocorrelation times ... [%2.0f%%] ...", + fprintf(stdout, + "\rEstimating integrated autocorrelation times ... [%2.0f%%] ...", 100. * (i + 1) / nwins); fflush(stdout); ntot = window[i].Ntot[0]; @@ -2797,7 +2858,8 @@ static void calcIntegratedAutocorrelationTimes(t_UmbrellaWindow* window, gmx_fatal(FARGS, "Encountered different nr of frames in different pull groups.\n" "That should not happen. (%d and %d)\n", - ntot, window[i].Ntot[ig]); + ntot, + window[i].Ntot[ig]); } ztime = window[i].ztime[ig]; @@ -3064,7 +3126,8 @@ static void checkReactionCoordinateCovered(t_UmbrellaWindow* window, int nwins, fprintf(stderr, "\nWARNING, no data point in bin %d (z=%g) !\n" "You may not get a reasonable profile. Check your histograms!\n", - j, z); + j, + z); } /* and check for poor sampling */ else if (relcount < 0.005 && !bBoundary) @@ -3256,7 +3319,9 @@ static void readPullCoordSelection(t_UmbrellaOptions* opt, char** fnTpr, int nTp printf("\nUse only these pull coordinates:\n"); for (iline = 0; iline < nTpr; iline++) { - printf("%s (%d of %d coordinates):", fnTpr[iline], opt->coordsel[iline].nUse, + printf("%s (%d of %d coordinates):", + fnTpr[iline], + opt->coordsel[iline].nUse, opt->coordsel[iline].n); for (i = 0; i < opt->coordsel[iline].n; i++) { @@ -3610,8 +3675,8 @@ int gmx_wham(int argc, char* argv[]) opt.stepchange = 100; opt.stepUpdateContrib = 100; - if (!parse_common_args(&argc, argv, 0, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, - &opt.oenv)) + if (!parse_common_args( + &argc, argv, 0, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &opt.oenv)) { return 0; } @@ -3697,8 +3762,12 @@ int gmx_wham(int argc, char* argv[]) fnPull = opt.bPullf ? opt.fnPullf : opt.fnPullx; read_wham_in(fnPull, &fninPull, &nfiles2, &opt); - printf("Found %d tpr and %d pull %s files in %s and %s, respectively\n", nfiles, nfiles2, - opt.bPullf ? "force" : "position", opt.fnTpr, fnPull); + printf("Found %d tpr and %d pull %s files in %s and %s, respectively\n", + nfiles, + nfiles2, + opt.bPullf ? "force" : "position", + opt.fnTpr, + fnPull); if (nfiles != nfiles2) { gmx_fatal(FARGS, "Found %d file names in %s, but %d in %s\n", nfiles, opt.fnTpr, nfiles2, fnPull); @@ -3860,8 +3929,15 @@ int gmx_wham(int argc, char* argv[]) /* Bootstrap Method */ if (opt.nBootStrap) { - do_bootstrapping(opt2fn("-bsres", NFILE, fnm), opt2fn("-bsprof", NFILE, fnm), - opt2fn("-hist", NFILE, fnm), xlabel, ylabel, profile, window, nwins, &opt); + do_bootstrapping(opt2fn("-bsres", NFILE, fnm), + opt2fn("-bsprof", NFILE, fnm), + opt2fn("-hist", NFILE, fnm), + xlabel, + ylabel, + profile, + window, + nwins, + &opt); } sfree(profile); diff --git a/src/gromacs/gmxana/gmx_xpm2ps.cpp b/src/gromacs/gmxana/gmx_xpm2ps.cpp index e0e24fea33..22422c2586 100644 --- a/src/gromacs/gmxana/gmx_xpm2ps.cpp +++ b/src/gromacs/gmxana/gmx_xpm2ps.cpp @@ -422,8 +422,7 @@ static void draw_boxes(t_psdata* ps, real x0, real y0, real w, gmx::ArrayRefX.majorticklen - psr->X.tickfontsize * 0.8, - xtick[x], eXCenter); + ps_ctext(ps, xx, yy00 - DDD - psr->X.majorticklen - psr->X.tickfontsize * 0.8, xtick[x], eXCenter); } } else if (bRmod(m->axis_x[x], psr->X.offset, psr->X.minor) @@ -454,8 +453,7 @@ static void draw_boxes(t_psdata* ps, real x0, real y0, real w, gmx::ArrayRefY.majorticklen, yy); - ps_ctext(ps, xx00 - psr->Y.majorticklen - DDD, yy - psr->Y.tickfontsize / 3.0, - ytick[y], eXRight); + ps_ctext(ps, xx00 - psr->Y.majorticklen - DDD, yy - psr->Y.tickfontsize / 3.0, ytick[y], eXRight); } else if (bRmod(m->axis_y[y], psr->Y.offset, psr->Y.minor)) { @@ -503,9 +501,11 @@ static void draw_boxes(t_psdata* ps, real x0, real y0, real w, gmx::ArrayRefX.font, psr->X.fontsize); - ps_ctext(ps, x0 + w / 2, + ps_ctext(ps, + x0 + w / 2, y0 - DDD - psr->X.majorticklen - psr->X.tickfontsize * FUDGE - psr->X.fontsize, - mylab, eXCenter); + mylab, + eXCenter); } } @@ -641,8 +641,10 @@ static std::vector add_maps(gmx::ArrayRef map1, gmx::Array { gmx_fatal(FARGS, "Not enough symbols to merge the two colormaps\n"); } - printf("Combining colormaps of %zu and %zu elements into one of %zu elements\n", map1.size(), - map2.size(), map.size()); + printf("Combining colormaps of %zu and %zu elements into one of %zu elements\n", + map1.size(), + map2.size(), + map.size()); gmx::index k = 0; for (gmx::index j = 0; j < gmx::ssize(map1) && k < gmx::ssize(map); ++j, ++k) { @@ -814,7 +816,11 @@ static void ps_mat(const char* outf, if (psr->X.major <= 0) { tick_spacing((mat[0].flags & MAT_SPATIAL_X) ? mat[0].nx + 1 : mat[0].nx, - mat[0].axis_x.data(), psr->X.offset, 'X', &(psr->X.major), &(psr->X.minor)); + mat[0].axis_x.data(), + psr->X.offset, + 'X', + &(psr->X.major), + &(psr->X.minor)); } if (psr->X.minor <= 0) { @@ -823,7 +829,11 @@ static void ps_mat(const char* outf, if (psr->Y.major <= 0) { tick_spacing((mat[0].flags & MAT_SPATIAL_Y) ? mat[0].ny + 1 : mat[0].ny, - mat[0].axis_y.data(), psr->Y.offset, 'Y', &(psr->Y.major), &(psr->Y.minor)); + mat[0].axis_y.data(), + psr->Y.offset, + 'Y', + &(psr->Y.major), + &(psr->Y.minor)); } if (psr->Y.minor <= 0) { @@ -1031,14 +1041,14 @@ static void ps_mat(const char* outf, { if (elegend != elBoth) { - leg_continuous(&out, x0 + w / 2, w / 2, DDD, legend, psr->legfontsize, psr->legfont, - leg_map, mapoffset); + leg_continuous( + &out, x0 + w / 2, w / 2, DDD, legend, psr->legfontsize, psr->legfont, leg_map, mapoffset); } else { assert(!mat2.empty()); - leg_bicontinuous(&out, x0 + w / 2, w, DDD, mat[0].legend, mat2[0].legend, - psr->legfontsize, psr->legfont, map1, map2); + leg_bicontinuous( + &out, x0 + w / 2, w, DDD, mat[0].legend, mat2[0].legend, psr->legfontsize, psr->legfont, map1, map2); } } ps_comment(&out, "Done processing"); @@ -1072,8 +1082,12 @@ static void prune_mat(gmx::ArrayRef mat, gmx::ArrayRef mat2, "Matrix pruning requires matrices of the same size"); for (gmx::index i = 0; i != gmx::ssize(mat); ++i) { - fprintf(stderr, "converting %dx%d matrix to %dx%d\n", mat[i].nx, mat[i].ny, - (mat[i].nx + skip - 1) / skip, (mat[i].ny + skip - 1) / skip); + fprintf(stderr, + "converting %dx%d matrix to %dx%d\n", + mat[i].nx, + mat[i].ny, + (mat[i].nx + skip - 1) / skip, + (mat[i].ny + skip - 1) / skip); /* walk through matrix */ int xs = 0; for (int x = 0; (x < mat[i].nx); x++) @@ -1181,7 +1195,11 @@ static void write_combined_matrix(int ecombine, gmx_fatal(FARGS, "Size of frame %zd in 1st (%dx%d) and 2nd matrix (%dx%d) do" " not match.\n", - k, mat1[k].nx, mat1[k].ny, mat2[k].nx, mat2[k].ny); + k, + mat1[k].nx, + mat1[k].ny, + mat2[k].nx, + mat2[k].ny); } printf("Combining two %dx%d matrices\n", mat1[k].nx, mat1[k].ny); rmat1 = matrix2real(&mat1[k], nullptr); @@ -1226,9 +1244,22 @@ static void write_combined_matrix(int ecombine, } else { - write_xpm(out, mat1[k].flags, mat1[k].title, mat1[k].legend, mat1[k].label_x, - mat1[k].label_y, mat1[k].nx, mat1[k].ny, mat1[k].axis_x.data(), - mat1[k].axis_y.data(), rmat1, rlo, rhi, white, black, &nlevels); + write_xpm(out, + mat1[k].flags, + mat1[k].title, + mat1[k].legend, + mat1[k].label_x, + mat1[k].label_y, + mat1[k].nx, + mat1[k].ny, + mat1[k].axis_x.data(), + mat1[k].axis_y.data(), + rmat1, + rlo, + rhi, + white, + black, + &nlevels); } } gmx_ffclose(out); @@ -1265,7 +1296,11 @@ static void do_mat(gmx::ArrayRef mat, gmx_fatal(FARGS, "WAKE UP!! Size of frame %zd in 2nd matrix file (%dx%d) does not match " "size of 1st matrix (%dx%d) or the other way around.\n", - k, mat2[k].nx, mat2[k].ny, mat[k].nx, mat[k].ny); + k, + mat2[k].nx, + mat2[k].ny, + mat[k].nx, + mat[k].ny); } for (int j = 0; (j < mat[k].ny); j++) { @@ -1295,8 +1330,7 @@ static void do_mat(gmx::ArrayRef mat, if (epsfile != nullptr) { - ps_mat(epsfile, mat, mat2, bFrame, bDiag, bFirstDiag, bTitle, bTitleOnce, bYonce, elegend, - size, boxx, boxy, m2p, m2pout, mapoffset); + ps_mat(epsfile, mat, mat2, bFrame, bDiag, bFirstDiag, bTitle, bTitleOnce, bYonce, elegend, size, boxx, boxy, m2p, m2pout, mapoffset); } if (xpmfile != nullptr) { @@ -1503,8 +1537,8 @@ int gmx_xpm2ps(int argc, char* argv[]) { efEPS, "-o", nullptr, ffOPTWR }, { efXPM, "-xpm", nullptr, ffOPTWR } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW, NFILE, fnm, NPA, pa, asize(desc), desc, 0, - nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW, NFILE, fnm, NPA, pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -1557,14 +1591,22 @@ int gmx_xpm2ps(int argc, char* argv[]) fn = opt2fn("-f", NFILE, fnm); std::vector mat, mat2; mat = read_xpm_matrix(fn); - fprintf(stderr, "There %s %zu matri%s in %s\n", (mat.size() > 1) ? "are" : "is", mat.size(), - (mat.size() > 1) ? "ces" : "x", fn); + fprintf(stderr, + "There %s %zu matri%s in %s\n", + (mat.size() > 1) ? "are" : "is", + mat.size(), + (mat.size() > 1) ? "ces" : "x", + fn); fn = opt2fn_null("-f2", NFILE, fnm); if (fn) { mat2 = read_xpm_matrix(fn); - fprintf(stderr, "There %s %zu matri%s in %s\n", (mat2.size() > 1) ? "are" : "is", - mat2.size(), (mat2.size() > 1) ? "ces" : "x", fn); + fprintf(stderr, + "There %s %zu matri%s in %s\n", + (mat2.size() > 1) ? "are" : "is", + mat2.size(), + (mat2.size() > 1) ? "ces" : "x", + fn); if (mat.size() != mat2.size()) { fprintf(stderr, "Different number of matrices, using the smallest number.\n"); @@ -1626,14 +1668,34 @@ int gmx_xpm2ps(int argc, char* argv[]) if (ecombine && ecombine != ecHalves) { - write_combined_matrix(ecombine, xpmfile, mat, mat2, opt2parg_bSet("-cmin", NPA, pa) ? &cmin : nullptr, + write_combined_matrix(ecombine, + xpmfile, + mat, + mat2, + opt2parg_bSet("-cmin", NPA, pa) ? &cmin : nullptr, opt2parg_bSet("-cmax", NPA, pa) ? &cmax : nullptr); } else { - do_mat(mat, mat2, bFrame, bZeroLine, bDiag, bFirstDiag, bTitle, bTitleOnce, bYonce, elegend, - size, boxx, boxy, epsfile, xpmfile, opt2fn_null("-di", NFILE, fnm), - opt2fn_null("-do", NFILE, fnm), skip, mapoffset); + do_mat(mat, + mat2, + bFrame, + bZeroLine, + bDiag, + bFirstDiag, + bTitle, + bTitleOnce, + bYonce, + elegend, + size, + boxx, + boxy, + epsfile, + xpmfile, + opt2fn_null("-di", NFILE, fnm), + opt2fn_null("-do", NFILE, fnm), + skip, + mapoffset); } view_all(oenv, NFILE, fnm); diff --git a/src/gromacs/gmxana/hxprops.cpp b/src/gromacs/gmxana/hxprops.cpp index 59206dd2ea..4698ee3bf1 100644 --- a/src/gromacs/gmxana/hxprops.cpp +++ b/src/gromacs/gmxana/hxprops.cpp @@ -420,8 +420,7 @@ t_bb* mkbbind(const char* fn, bb[i].Nnext = bb[i + 1].N; } rnr = std::max(0, i1 - i0 + 1); - fprintf(stderr, "There are %d complete backbone residues (from %d to %d)\n", rnr, bb[i0].resno, - bb[i1].resno); + fprintf(stderr, "There are %d complete backbone residues (from %d to %d)\n", rnr, bb[i0].resno, bb[i1].resno); if (rnr == 0) { gmx_fatal(FARGS, "Zero complete backbone residues were found, cannot proceed"); @@ -496,11 +495,33 @@ void calc_hxprops(int nres, t_bb bb[], const rvec x[]) } bb[i].phi = RAD2DEG - * dih_angle(x[bb[i].Cprev], x[bb[i].N], x[bb[i].CA], x[bb[i].C], nullptr, r_ij, - r_kj, r_kl, m, n, &t1, &t2, &t3); + * dih_angle(x[bb[i].Cprev], + x[bb[i].N], + x[bb[i].CA], + x[bb[i].C], + nullptr, + r_ij, + r_kj, + r_kl, + m, + n, + &t1, + &t2, + &t3); bb[i].psi = RAD2DEG - * dih_angle(x[bb[i].N], x[bb[i].CA], x[bb[i].C], x[bb[i].Nnext], nullptr, r_ij, - r_kj, r_kl, m, n, &t1, &t2, &t3); + * dih_angle(x[bb[i].N], + x[bb[i].CA], + x[bb[i].C], + x[bb[i].Nnext], + nullptr, + r_ij, + r_kj, + r_kl, + m, + n, + &t1, + &t2, + &t3); bb[i].pprms2 = gmx::square(bb[i].phi - PHI_AHX) + gmx::square(bb[i].psi - PSI_AHX); bb[i].jcaha += 1.4 * std::sin((bb[i].psi + 138.0) * DEG2RAD) @@ -581,12 +602,33 @@ void pr_bb(FILE* fp, int nres, t_bb bb[]) int i; fprintf(fp, "\n"); - fprintf(fp, "%3s %3s %3s %3s %3s %7s %7s %7s %7s %7s %3s\n", "AA", "N", "Ca", "C", "O", "Phi", - "Psi", "D3", "D4", "D5", "Hx?"); + fprintf(fp, + "%3s %3s %3s %3s %3s %7s %7s %7s %7s %7s %3s\n", + "AA", + "N", + "Ca", + "C", + "O", + "Phi", + "Psi", + "D3", + "D4", + "D5", + "Hx?"); for (i = 0; (i < nres); i++) { - fprintf(fp, "%3d %3d %3d %3d %3d %7.2f %7.2f %7.3f %7.3f %7.3f %3s\n", bb[i].resno, bb[i].N, - bb[i].CA, bb[i].C, bb[i].O, bb[i].phi, bb[i].psi, bb[i].d3, bb[i].d4, bb[i].d5, + fprintf(fp, + "%3d %3d %3d %3d %3d %7.2f %7.2f %7.3f %7.3f %7.3f %3s\n", + bb[i].resno, + bb[i].N, + bb[i].CA, + bb[i].C, + bb[i].O, + bb[i].phi, + bb[i].psi, + bb[i].d3, + bb[i].d4, + bb[i].d5, bb[i].bHelix ? "Yes" : "No"); } fprintf(fp, "\n"); diff --git a/src/gromacs/gmxana/nrama.cpp b/src/gromacs/gmxana/nrama.cpp index f1bf5bb89e..3e8c5fdcf0 100644 --- a/src/gromacs/gmxana/nrama.cpp +++ b/src/gromacs/gmxana/nrama.cpp @@ -85,8 +85,19 @@ static void calc_dihs(t_xrama* xr) for (i = 0; (i < xr->ndih); i++) { dd = &(xr->dih[i]); - dd->ang = dih_angle(xr->x[dd->ai[0]], xr->x[dd->ai[1]], xr->x[dd->ai[2]], xr->x[dd->ai[3]], - nullptr, r_ij, r_kj, r_kl, m, n, &t1, &t2, &t3); + dd->ang = dih_angle(xr->x[dd->ai[0]], + xr->x[dd->ai[1]], + xr->x[dd->ai[2]], + xr->x[dd->ai[3]], + nullptr, + r_ij, + r_kj, + r_kl, + m, + n, + &t1, + &t2, + &t3); } } @@ -136,7 +147,9 @@ static void add_xr(t_xrama* xr, const int ff[5], const t_atoms* atoms) xr->pp[xr->npp].iphi = xr->ndih - 2; xr->pp[xr->npp].ipsi = xr->ndih - 1; xr->pp[xr->npp].bShow = FALSE; - sprintf(buf, "%s-%d", *atoms->resinfo[atoms->atom[ff[1]].resind].name, + sprintf(buf, + "%s-%d", + *atoms->resinfo[atoms->atom[ff[1]].resind].name, atoms->resinfo[atoms->atom[ff[1]].resind].nr); xr->pp[xr->npp].label = gmx_strdup(buf); xr->npp++; @@ -229,8 +242,11 @@ static void get_dih_props(t_xrama* xr, const t_idef* idef, int mult) { if (xr->dih[i].mult == 0) { - fprintf(stderr, "Dihedral around %d,%d not found in topology. Using mult=%d\n", - xr->dih[i].ai[1], xr->dih[i].ai[2], mult); + fprintf(stderr, + "Dihedral around %d,%d not found in topology. Using mult=%d\n", + xr->dih[i].ai[1], + xr->dih[i].ai[2], + mult); xr->dih[i].mult = mult; xr->dih[i].phi0 = 180; } diff --git a/src/gromacs/gmxana/pp2shift.cpp b/src/gromacs/gmxana/pp2shift.cpp index cbb4a0d58a..707673c662 100644 --- a/src/gromacs/gmxana/pp2shift.cpp +++ b/src/gromacs/gmxana/pp2shift.cpp @@ -222,7 +222,12 @@ void do_pp2shifts(FILE* fp, int nf, int nlist, t_dlist dlist[], real** dih) fprintf(fp, "\n *** Chemical shifts from the chemical shift index ***\n"); please_cite(fp, "Wishart98a"); - fprintf(fp, "%12s %10s %10s %10s %10s\n", "Residue", "delta Ca", "delta Ha", "delta CO", + fprintf(fp, + "%12s %10s %10s %10s %10s\n", + "Residue", + "delta Ca", + "delta Ha", + "delta CO", "delta Cb"); for (i = 0; (i < nlist); i++) { @@ -241,8 +246,7 @@ void do_pp2shifts(FILE* fp, int nf, int nlist, t_dlist dlist[], real** dih) co += interpolate(phi, psi, co_sd); ha += interpolate(phi, psi, ha_sd); } - fprintf(fp, "%12s %10g %10g %10g %10g\n", dlist[i].name, ca / nf, ha / nf, co / nf, - cb / nf); + fprintf(fp, "%12s %10g %10g %10g %10g\n", dlist[i].name, ca / nf, ha / nf, co / nf, cb / nf); } } fprintf(fp, "\n"); diff --git a/src/gromacs/gmxana/princ.cpp b/src/gromacs/gmxana/princ.cpp index 8f32afa7b3..ded0e6fc9e 100644 --- a/src/gromacs/gmxana/princ.cpp +++ b/src/gromacs/gmxana/princ.cpp @@ -75,8 +75,7 @@ static void ptrans(char* s, real** inten, real d[], real e[]) y = inten[m][2]; z = inten[m][3]; n = x * x + y * y + z * z; - fprintf(stderr, "%8s %8.3f %8.3f %8.3f, norm:%8.3f, d:%8.3f, e:%8.3f\n", s, x, y, z, - std::sqrt(n), d[m], e[m]); + fprintf(stderr, "%8s %8.3f %8.3f %8.3f, norm:%8.3f, d:%8.3f, e:%8.3f\n", s, x, y, z, std::sqrt(n), d[m], e[m]); } fprintf(stderr, "\n"); } diff --git a/src/gromacs/gmxana/sfactor.cpp b/src/gromacs/gmxana/sfactor.cpp index 87b08d6e84..bc4010f694 100644 --- a/src/gromacs/gmxana/sfactor.cpp +++ b/src/gromacs/gmxana/sfactor.cpp @@ -295,8 +295,7 @@ extern gmx_structurefactors_t* gmx_structurefactors_init(const char* datfn) while (get_a_line(fp.get(), line, STRLEN)) { i = line_no; - if (sscanf(line, "%s %d %lf %lf %lf %lf %lf %lf %lf %lf %lf", atomn, &p, &a1, &a2, &a3, &a4, - &b1, &b2, &b3, &b4, &c) + if (sscanf(line, "%s %d %lf %lf %lf %lf %lf %lf %lf %lf %lf", atomn, &p, &a1, &a2, &a3, &a4, &b1, &b2, &b3, &b4, &c) == 11) { gsf->atomnm[i] = gmx_strdup(atomn); @@ -541,8 +540,8 @@ extern int do_scattering_intensity(const char* fnTPS, { rearrange_atoms(red[i], &fr, index[i], isize[i], &top, FALSE, gmx_sf); - compute_structure_factor(static_cast(sf), box, red[i], isize[i], - start_q, end_q, i, sf_table); + compute_structure_factor( + static_cast(sf), box, red[i], isize[i], start_q, end_q, i, sf_table); } } diff --git a/src/gromacs/gmxana/thermochemistry.cpp b/src/gromacs/gmxana/thermochemistry.cpp index b9124abe5d..20bae48db8 100644 --- a/src/gromacs/gmxana/thermochemistry.cpp +++ b/src/gromacs/gmxana/thermochemistry.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2017,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2017,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -80,8 +80,13 @@ double calcVibrationalInternalEnergy(gmx::ArrayRef eigval, real temp double dEvib = hwkT * (0.5 + 1.0 / (std::expm1(hwkT))); if (debug) { - fprintf(debug, "i %d eigval %g omega %g hwkT %g dEvib %g\n", - static_cast(i + 1), static_cast(eigval[i]), omega, hwkT, dEvib); + fprintf(debug, + "i %d eigval %g omega %g hwkT %g dEvib %g\n", + static_cast(i + 1), + static_cast(eigval[i]), + omega, + hwkT, + dEvib); } Evib += dEvib; } @@ -107,8 +112,13 @@ double calcVibrationalHeatCapacity(gmx::ArrayRef eigval, real temper double dcv = std::exp(hwkT) * gmx::square(hwkT / std::expm1(hwkT)); if (debug) { - fprintf(debug, "i %d eigval %g omega %g hwkT %g dcv %g\n", - static_cast(i + 1), static_cast(eigval[i]), omega, hwkT, dcv); + fprintf(debug, + "i %d eigval %g omega %g hwkT %g dcv %g\n", + static_cast(i + 1), + static_cast(eigval[i]), + omega, + hwkT, + dcv); } cv += dcv; } @@ -170,8 +180,13 @@ double calcQuasiHarmonicEntropy(gmx::ArrayRef eigval, real temperatu S += dS; if (debug) { - fprintf(debug, "i = %5d eigval = %10g w = %10g hwkT = %10g dS = %10g\n", - static_cast(i + 1), static_cast(eigval[i]), omega, hwkT, dS); + fprintf(debug, + "i = %5d eigval = %10g w = %10g hwkT = %10g dS = %10g\n", + static_cast(i + 1), + static_cast(eigval[i]), + omega, + hwkT, + dS); } } else if (debug) diff --git a/src/gromacs/gmxlib/network.cpp b/src/gromacs/gmxlib/network.cpp index 66023edac8..a9be4ebbe8 100644 --- a/src/gromacs/gmxlib/network.cpp +++ b/src/gromacs/gmxlib/network.cpp @@ -190,7 +190,9 @@ void gmx_setup_nodecomm(FILE gmx_unused* fplog, t_commrec* cr) nc->bUse = TRUE; if (fplog) { - fprintf(fplog, "Using two step summing over %d groups of on average %.1f ranks\n\n", ng, + fprintf(fplog, + "Using two step summing over %d groups of on average %.1f ranks\n\n", + ng, (real)n / (real)ng); } if (nc->rank_intra > 0) diff --git a/src/gromacs/gmxlib/nrnb.cpp b/src/gromacs/gmxlib/nrnb.cpp index 1366d351e5..59ff411b15 100644 --- a/src/gromacs/gmxlib/nrnb.cpp +++ b/src/gromacs/gmxlib/nrnb.cpp @@ -295,8 +295,7 @@ void _inc_nrnb(t_nrnb* nrnb, int enr, int inc, char gmx_unused* file, int gmx_un { nrnb->n[enr] += inc; #ifdef DEBUG_NRNB - printf("nrnb %15s(%2d) incremented with %8d from file %s line %d\n", nbdata[enr].name, enr, inc, - file, line); + printf("nrnb %15s(%2d) incremented with %8d from file %s line %d\n", nbdata[enr].name, enr, inc, file, line); #endif } @@ -439,8 +438,7 @@ void print_perf(FILE* out, if (time_per_node > 0) { fprintf(out, "%12s %12s %12s %10s\n", "", "Core t (s)", "Wall t (s)", "(%)"); - fprintf(out, "%12s %12.3f %12.3f %10.1f\n", "Time:", time_per_thread, time_per_node, - 100.0 * time_per_thread / time_per_node); + fprintf(out, "%12s %12.3f %12.3f %10.1f\n", "Time:", time_per_thread, time_per_node, 100.0 * time_per_thread / time_per_node); /* only print day-hour-sec format if time_per_node is more than 30 min */ if (time_per_node > 30 * 60) { @@ -455,15 +453,27 @@ void print_perf(FILE* out, if (getenv("GMX_DETAILED_PERF_STATS") == nullptr) { fprintf(out, "%12s %12s %12s\n", "", "(ns/day)", "(hour/ns)"); - fprintf(out, "%12s %12.3f %12.3f\n", "Performance:", wallclocktime * 24 * 3.6 / time_per_node, + fprintf(out, + "%12s %12.3f %12.3f\n", + "Performance:", + wallclocktime * 24 * 3.6 / time_per_node, 1000 * time_per_node / (3600 * wallclocktime)); } else { - fprintf(out, "%12s %12s %12s %12s %12s\n", "", "(Mnbf/s)", - (mflop > 1000) ? "(GFlops)" : "(MFlops)", "(ns/day)", "(hour/ns)"); - fprintf(out, "%12s %12.3f %12.3f %12.3f %12.3f\n", "Performance:", nbfs / time_per_node, - (mflop > 1000) ? (mflop / 1000) : mflop, wallclocktime * 24 * 3.6 / time_per_node, + fprintf(out, + "%12s %12s %12s %12s %12s\n", + "", + "(Mnbf/s)", + (mflop > 1000) ? "(GFlops)" : "(MFlops)", + "(ns/day)", + "(hour/ns)"); + fprintf(out, + "%12s %12.3f %12.3f %12.3f %12.3f\n", + "Performance:", + nbfs / time_per_node, + (mflop > 1000) ? (mflop / 1000) : mflop, + wallclocktime * 24 * 3.6 / time_per_node, 1000 * time_per_node / (3600 * wallclocktime)); } } @@ -476,10 +486,18 @@ void print_perf(FILE* out, } else { - fprintf(out, "%12s %12s %12s %14s\n", "", "(Mnbf/s)", - (mflop > 1000) ? "(GFlops)" : "(MFlops)", "(steps/hour)"); - fprintf(out, "%12s %12.3f %12.3f %14.1f\n", "Performance:", nbfs / time_per_node, - (mflop > 1000) ? (mflop / 1000) : mflop, nsteps * 3600.0 / time_per_node); + fprintf(out, + "%12s %12s %12s %14s\n", + "", + "(Mnbf/s)", + (mflop > 1000) ? "(GFlops)" : "(MFlops)", + "(steps/hour)"); + fprintf(out, + "%12s %12.3f %12.3f %14.1f\n", + "Performance:", + nbfs / time_per_node, + (mflop > 1000) ? (mflop / 1000) : mflop, + nsteps * 3600.0 / time_per_node); } } } diff --git a/src/gromacs/gmxpreprocess/add_par.cpp b/src/gromacs/gmxpreprocess/add_par.cpp index aac7f94e74..a071525678 100644 --- a/src/gromacs/gmxpreprocess/add_par.cpp +++ b/src/gromacs/gmxpreprocess/add_par.cpp @@ -159,7 +159,9 @@ int search_jtype(const PreprocessResidue& localPpResidue, const char* name, bool } if (jmax == -1) { - gmx_fatal(FARGS, "Atom %s not found in rtp database in residue %s", searchname, + gmx_fatal(FARGS, + "Atom %s not found in rtp database in residue %s", + searchname, localPpResidue.resname.c_str()); } if (kmax != strlen(searchname)) @@ -167,7 +169,9 @@ int search_jtype(const PreprocessResidue& localPpResidue, const char* name, bool gmx_fatal(FARGS, "Atom %s not found in rtp database in residue %s, " "it looks a bit like %s", - searchname, localPpResidue.resname.c_str(), *(localPpResidue.atomname[jmax])); + searchname, + localPpResidue.resname.c_str(), + *(localPpResidue.atomname[jmax])); } return jmax; } diff --git a/src/gromacs/gmxpreprocess/convparm.cpp b/src/gromacs/gmxpreprocess/convparm.cpp index 225086c52f..bafd389bee 100644 --- a/src/gromacs/gmxpreprocess/convparm.cpp +++ b/src/gromacs/gmxpreprocess/convparm.cpp @@ -66,14 +66,21 @@ static int round_check(real r, int limit, int ftype, const char* name) if (r - i > 0.01 || r - i < -0.01) { - gmx_fatal(FARGS, "A non-integer value (%f) was supplied for '%s' in %s", r, name, + gmx_fatal(FARGS, + "A non-integer value (%f) was supplied for '%s' in %s", + r, + name, interaction_function[ftype].longname); } if (i < limit) { - gmx_fatal(FARGS, "Value of '%s' in %s is %d, which is smaller than the minimum of %d", name, - interaction_function[ftype].longname, i, limit); + gmx_fatal(FARGS, + "Value of '%s' in %s is %d, which is smaller than the minimum of %d", + name, + interaction_function[ftype].longname, + i, + limit); } return i; @@ -327,7 +334,8 @@ static int assign_param(t_functype ftype, t_iparams* newparam, gmx::ArrayReffbposres.geom); + efbposresNR - 1, + newparam->fbposres.geom); } newparam->fbposres.r = old[1]; newparam->fbposres.k = old[2]; @@ -552,8 +560,8 @@ void convertInteractionsOfType(int atnr, ffp->reppow = reppow; enter_function(&(nbtypes[F_LJ]), static_cast(F_LJ), comb, reppow, ffp, nullptr, TRUE, TRUE); - enter_function(&(nbtypes[F_BHAM]), static_cast(F_BHAM), comb, reppow, ffp, nullptr, - TRUE, TRUE); + enter_function( + &(nbtypes[F_BHAM]), static_cast(F_BHAM), comb, reppow, ffp, nullptr, TRUE, TRUE); for (size_t mt = 0; mt < mtop->moltype.size(); mt++) { @@ -568,8 +576,14 @@ void convertInteractionsOfType(int atnr, if ((i != F_LJ) && (i != F_BHAM) && ((flags & IF_BOND) || (flags & IF_VSITE) || (flags & IF_CONSTRAINT))) { - enter_function(&(interactions[i]), static_cast(i), comb, reppow, ffp, - &molt->ilist[i], FALSE, (i == F_POSRES || i == F_FBPOSRES)); + enter_function(&(interactions[i]), + static_cast(i), + comb, + reppow, + ffp, + &molt->ilist[i], + FALSE, + (i == F_POSRES || i == F_FBPOSRES)); } } } @@ -615,8 +629,14 @@ void convertInteractionsOfType(int atnr, } else { - enter_function(&(interactions[i]), static_cast(i), comb, reppow, - ffp, &(*mtop->intermolecular_ilist)[i], FALSE, FALSE); + enter_function(&(interactions[i]), + static_cast(i), + comb, + reppow, + ffp, + &(*mtop->intermolecular_ilist)[i], + FALSE, + FALSE); mtop->bIntermolecularInteractions = TRUE; } diff --git a/src/gromacs/gmxpreprocess/editconf.cpp b/src/gromacs/gmxpreprocess/editconf.cpp index 45f02a99cc..257f1bbb39 100644 --- a/src/gromacs/gmxpreprocess/editconf.cpp +++ b/src/gromacs/gmxpreprocess/editconf.cpp @@ -79,8 +79,10 @@ static real calc_mass(t_atoms* atoms, gmx_bool bGetMass, AtomProperties* aps) { if (bGetMass) { - aps->setAtomProperty(epropMass, std::string(*atoms->resinfo[atoms->atom[i].resind].name), - std::string(*atoms->atomname[i]), &(atoms->atom[i].m)); + aps->setAtomProperty(epropMass, + std::string(*atoms->resinfo[atoms->atom[i].resind].name), + std::string(*atoms->atomname[i]), + &(atoms->atom[i].m)); } tmass += atoms->atom[i].m; } @@ -244,7 +246,8 @@ static void set_pdb_conf_bfac(int natoms, int nres, t_atoms* atoms, int n_bfac, fprintf(stderr, "Range of values for B-factors too large (min %g, max %g) " "will scale down a factor 10\n", - bfac_min, bfac_max); + bfac_min, + bfac_max); for (i = 0; (i < n_bfac); i++) { bfac[i] /= 10; @@ -257,7 +260,8 @@ static void set_pdb_conf_bfac(int natoms, int nres, t_atoms* atoms, int n_bfac, fprintf(stderr, "Range of values for B-factors too small (min %g, max %g) " "will scale up a factor 10\n", - bfac_min, bfac_max); + bfac_min, + bfac_max); for (i = 0; (i < n_bfac); i++) { bfac[i] *= 10; @@ -323,9 +327,20 @@ static void pdb_legend(FILE* out, int natoms, int nres, t_atoms* atoms, rvec x[] fprintf(stderr, "B-factors range from %g to %g\n", bfac_min, bfac_max); for (i = 1; (i < 12); i++) { - fprintf(out, "%-6s%5d %-4.4s%3.3s %c%4d%c %8.3f%8.3f%8.3f%6.2f%6.2f\n", "ATOM ", - natoms + 1 + i, "CA", "LEG", space, nres + 1, space, (xmin + (i * 0.12)) * 10, - ymin * 10, zmin * 10, 1.0, bfac_min + ((i - 1.0) * (bfac_max - bfac_min) / 10)); + fprintf(out, + "%-6s%5d %-4.4s%3.3s %c%4d%c %8.3f%8.3f%8.3f%6.2f%6.2f\n", + "ATOM ", + natoms + 1 + i, + "CA", + "LEG", + space, + nres + 1, + space, + (xmin + (i * 0.12)) * 10, + ymin * 10, + zmin * 10, + 1.0, + bfac_min + ((i - 1.0) * (bfac_max - bfac_min) / 10)); } } @@ -401,9 +416,21 @@ static void visualize_box(FILE* out, int a0, int r0, matrix box, const rvec grid for (i = 0; i < nat; i++) { - gmx_fprintf_pdb_atomline(out, epdbATOM, a0 + i, "C", ' ', "BOX", 'K' + i / NCUCVERT, - r0 + i, ' ', 10 * vert[i][XX], 10 * vert[i][YY], - 10 * vert[i][ZZ], 1.0, 0.0, ""); + gmx_fprintf_pdb_atomline(out, + epdbATOM, + a0 + i, + "C", + ' ', + "BOX", + 'K' + i / NCUCVERT, + r0 + i, + ' ', + 10 * vert[i][XX], + 10 * vert[i][YY], + 10 * vert[i][ZZ], + 1.0, + 0.0, + ""); } edge = compact_unitcell_edges(); @@ -411,7 +438,9 @@ static void visualize_box(FILE* out, int a0, int r0, matrix box, const rvec grid { for (i = 0; i < NCUCEDGE; i++) { - fprintf(out, "CONECT%5d%5d\n", a0 + j * NCUCVERT + edge[2 * i], + fprintf(out, + "CONECT%5d%5d\n", + a0 + j * NCUCVERT + edge[2 * i], a0 + j * NCUCVERT + edge[2 * i + 1]); } } @@ -427,9 +456,21 @@ static void visualize_box(FILE* out, int a0, int r0, matrix box, const rvec grid { for (x = 0; x <= 1; x++) { - gmx_fprintf_pdb_atomline(out, epdbATOM, a0 + i, "C", ' ', "BOX", 'K' + i / 8, - r0 + i, ' ', x * 10 * box[XX][XX], y * 10 * box[YY][YY], - z * 10 * box[ZZ][ZZ], 1.0, 0.0, ""); + gmx_fprintf_pdb_atomline(out, + epdbATOM, + a0 + i, + "C", + ' ', + "BOX", + 'K' + i / 8, + r0 + i, + ' ', + x * 10 * box[XX][XX], + y * 10 * box[YY][YY], + z * 10 * box[ZZ][ZZ], + 1.0, + 0.0, + ""); i++; } } @@ -452,9 +493,16 @@ static void calc_rotmatrix(rvec principal_axis, rvec targetvec, matrix rotmatrix /* Determine rotation from cross product with target vector */ cprod(principal_axis, targetvec, rotvec); unitv(rotvec, rotvec); - printf("Aligning %g %g %g to %g %g %g : xprod %g %g %g\n", principal_axis[XX], - principal_axis[YY], principal_axis[ZZ], targetvec[XX], targetvec[YY], targetvec[ZZ], - rotvec[XX], rotvec[YY], rotvec[ZZ]); + printf("Aligning %g %g %g to %g %g %g : xprod %g %g %g\n", + principal_axis[XX], + principal_axis[YY], + principal_axis[ZZ], + targetvec[XX], + targetvec[YY], + targetvec[ZZ], + rotvec[XX], + rotvec[YY], + rotvec[ZZ]); ux = rotvec[XX]; uy = rotvec[YY]; @@ -469,9 +517,16 @@ static void calc_rotmatrix(rvec principal_axis, rvec targetvec, matrix rotmatrix rotmatrix[2][1] = uy * uz * (1 - costheta) + ux * sintheta; rotmatrix[2][2] = uz * uz + (1.0 - uz * uz) * costheta; - printf("Rotation matrix: \n%g %g %g\n%g %g %g\n%g %g %g\n", rotmatrix[0][0], rotmatrix[0][1], - rotmatrix[0][2], rotmatrix[1][0], rotmatrix[1][1], rotmatrix[1][2], rotmatrix[2][0], - rotmatrix[2][1], rotmatrix[2][2]); + printf("Rotation matrix: \n%g %g %g\n%g %g %g\n%g %g %g\n", + rotmatrix[0][0], + rotmatrix[0][1], + rotmatrix[0][2], + rotmatrix[1][0], + rotmatrix[1][1], + rotmatrix[1][2], + rotmatrix[2][0], + rotmatrix[2][1], + rotmatrix[2][2]); } static void renum_resnr(t_atoms* atoms, int isize, const int* index, int resnr_start) @@ -697,8 +752,8 @@ int gmx_editconf(int argc, char* argv[]) { efDAT, "-bf", "bfact", ffOPTRD } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_VIEW, NFILE, fnm, NPA, pa, asize(desc), desc, - asize(bugs), bugs, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_CAN_VIEW, NFILE, fnm, NPA, pa, asize(desc), desc, asize(bugs), bugs, &oenv)) { return 0; } @@ -792,7 +847,8 @@ int gmx_editconf(int argc, char* argv[]) if (pbcType != PbcType::No) { real vol = det(box); - printf("Volume: %g nm^3, corresponds to roughly %d electrons\n", vol, + printf("Volume: %g nm^3, corresponds to roughly %d electrons\n", + vol, 100 * (static_cast(vol * 4.5))); } @@ -814,8 +870,10 @@ int gmx_editconf(int argc, char* argv[]) /* Determine the Van der Waals radius from the force field */ if (bReadVDW) { - if (!aps.setAtomProperty(epropVDW, *top->atoms.resinfo[top->atoms.atom[i].resind].name, - *top->atoms.atomname[i], &vdw)) + if (!aps.setAtomProperty(epropVDW, + *top->atoms.resinfo[top->atoms.atom[i].resind].name, + *top->atoms.atomname[i], + &vdw)) { vdw = rvdw; } @@ -956,7 +1014,8 @@ int gmx_editconf(int argc, char* argv[]) gmx_fatal(FARGS, "Cannot scale density with " "zero mass (%g) or volume (%g)\n", - mass, vol); + mass, + vol); } scale[XX] = scale[YY] = scale[ZZ] = std::cbrt(dens / rho); @@ -982,8 +1041,14 @@ int gmx_editconf(int argc, char* argv[]) } } printf("Aligning %d atoms (out of %d) to %g %g %g, center of rotation %g %g %g\n", - numAlignmentAtoms, natom, targetvec[XX], targetvec[YY], targetvec[ZZ], - aligncenter[XX], aligncenter[YY], aligncenter[ZZ]); + numAlignmentAtoms, + natom, + targetvec[XX], + targetvec[YY], + targetvec[ZZ], + aligncenter[XX], + aligncenter[YY], + aligncenter[ZZ]); /*subtract out pivot point*/ for (i = 0; i < numAlignmentAtoms; i++) { @@ -1030,8 +1095,12 @@ int gmx_editconf(int argc, char* argv[]) ssize = atoms.nr; sindex = nullptr; } - printf("Translating %d atoms (out of %d) by %g %g %g nm\n", ssize, natom, translation[XX], - translation[YY], translation[ZZ]); + printf("Translating %d atoms (out of %d) by %g %g %g nm\n", + ssize, + natom, + translation[XX], + translation[YY], + translation[ZZ]); if (sindex) { for (i = 0; i < ssize; i++) @@ -1051,7 +1120,9 @@ int gmx_editconf(int argc, char* argv[]) { /* Rotate */ printf("Rotating %g, %g, %g degrees around the X, Y and Z axis respectively\n", - rotangles[XX], rotangles[YY], rotangles[ZZ]); + rotangles[XX], + rotangles[YY], + rotangles[ZZ]); for (i = 0; i < DIM; i++) { rotangles[i] *= DEG2RAD; @@ -1236,8 +1307,8 @@ int gmx_editconf(int argc, char* argv[]) } else { - write_sto_conf_indexed(outfile, name, &atoms, x, bHaveV ? v : nullptr, pbcType, box, - isize, index); + write_sto_conf_indexed( + outfile, name, &atoms, x, bHaveV ? v : nullptr, pbcType, box, isize, index); } sfree(grpname); sfree(index); @@ -1292,8 +1363,8 @@ int gmx_editconf(int argc, char* argv[]) { index[i] = i; } - write_pdbfile_indexed(out, name, &atoms, x, pbcType, box, ' ', -1, atoms.nr, index, - conect, outftp == efPQR); + write_pdbfile_indexed( + out, name, &atoms, x, pbcType, box, ' ', -1, atoms.nr, index, conect, outftp == efPQR); sfree(index); if (bLegend) { @@ -1301,8 +1372,11 @@ int gmx_editconf(int argc, char* argv[]) } if (visbox[0] > 0) { - visualize_box(out, bLegend ? atoms.nr + 12 : atoms.nr, - bLegend ? atoms.nres = 12 : atoms.nres, box, visbox); + visualize_box(out, + bLegend ? atoms.nr + 12 : atoms.nr, + bLegend ? atoms.nres = 12 : atoms.nres, + box, + visbox); } gmx_ffclose(out); } diff --git a/src/gromacs/gmxpreprocess/fflibutil.cpp b/src/gromacs/gmxpreprocess/fflibutil.cpp index 9942775507..3fd538825c 100644 --- a/src/gromacs/gmxpreprocess/fflibutil.cpp +++ b/src/gromacs/gmxpreprocess/fflibutil.cpp @@ -108,7 +108,8 @@ std::vector fflib_search_file_end(const char* ffdir, const char* fi std::string message = gmx::formatString( "Could not find any files ending on '%s' " "in the force field directory '%s'", - file_end, ffdir); + file_end, + ffdir); GMX_THROW(gmx::InvalidInputError(message)); } for (std::string& filename : result) @@ -145,7 +146,8 @@ std::vector fflib_enumerate_forcefields() std::string message = gmx::formatString( "No force fields found (files with name '%s' " "in subdirectories ending on '%s')", - filename, dirend); + filename, + dirend); GMX_THROW(gmx::InvalidInputError(message)); } diff --git a/src/gromacs/gmxpreprocess/gen_ad.cpp b/src/gromacs/gmxpreprocess/gen_ad.cpp index 8c3a4a3998..36d11e2296 100644 --- a/src/gromacs/gmxpreprocess/gen_ad.cpp +++ b/src/gromacs/gmxpreprocess/gen_ad.cpp @@ -129,9 +129,10 @@ static bool dcomp(const InteractionOfType& d1, const InteractionOfType& d2) { // AMBER force fields with type 9 dihedrals can reach here, where we sort on // the contents of the string that names the macro for the parameters. - return std::lexicographical_compare( - d1.interactionTypeName().begin(), d1.interactionTypeName().end(), - d2.interactionTypeName().begin(), d2.interactionTypeName().end()); + return std::lexicographical_compare(d1.interactionTypeName().begin(), + d1.interactionTypeName().end(), + d2.interactionTypeName().begin(), + d2.interactionTypeName().end()); } } @@ -299,7 +300,8 @@ static std::vector clean_dih(gmx::ArrayRefsecond + 1; for (int l = dihedral->second; - (l < next && is_dihedral_on_same_bond(dihedral->first, dih[l])); l++) + (l < next && is_dihedral_on_same_bond(dihedral->first, dih[l])); + l++) { int nh = n_hydro(dih[l].atoms(), atoms->atomname); if (nh < minh) @@ -354,8 +356,8 @@ static std::vector get_impropers(t_atoms* std::vector ai; for (int k = 0; (k < 4) && !bStop; k++) { - const int entry = search_atom(bondeds.a[k].c_str(), start, atoms, "improper", - bAllowMissing, cyclicBondsIndex); + const int entry = search_atom( + bondeds.a[k].c_str(), start, atoms, "improper", bAllowMissing, cyclicBondsIndex); if (entry != -1) { @@ -913,8 +915,7 @@ void gen_pad(t_atoms* atoms, if (!dih.empty()) { fprintf(stderr, "Before cleaning: %zu dihedrals\n", dih.size()); - dih = clean_dih(dih, improper, atoms, rtpFFDB[0].bKeepAllGeneratedDihedrals, - rtpFFDB[0].bRemoveDihedralIfWithImproper); + dih = clean_dih(dih, improper, atoms, rtpFFDB[0].bKeepAllGeneratedDihedrals, rtpFFDB[0].bRemoveDihedralIfWithImproper); } /* Now we have unique lists of angles and dihedrals diff --git a/src/gromacs/gmxpreprocess/gen_maxwell_velocities.cpp b/src/gromacs/gmxpreprocess/gen_maxwell_velocities.cpp index 41d53a1d3c..2893816f38 100644 --- a/src/gromacs/gmxpreprocess/gen_maxwell_velocities.cpp +++ b/src/gromacs/gmxpreprocess/gen_maxwell_velocities.cpp @@ -99,7 +99,8 @@ static void low_mspeed(real tempi, gmx_mtop_t* mtop, rvec v[], gmx::ThreeFry2x64 fprintf(debug, "Velocities were taken from a Maxwell distribution\n" "Initial generated temperature: %12.5e (scaled to: %12.5e)\n", - temp, tempi); + temp, + tempi); } } diff --git a/src/gromacs/gmxpreprocess/gen_vsite.cpp b/src/gromacs/gmxpreprocess/gen_vsite.cpp index cb0735fce7..fea34d8027 100644 --- a/src/gromacs/gmxpreprocess/gen_vsite.cpp +++ b/src/gromacs/gmxpreprocess/gen_vsite.cpp @@ -365,21 +365,23 @@ static void read_vsite_database(const char* ddbname, else if (numberOfSites == 4) { /* angle */ - vsitetoplist->back().angle.emplace_back(s1String, s2String, s3String, - strtod(s4, nullptr)); + vsitetoplist->back().angle.emplace_back( + s1String, s2String, s3String, strtod(s4, nullptr)); /* angle */ } else { gmx_fatal(FARGS, "Need 3 or 4 values to specify bond/angle values in %s: %s\n", - ddbname, pline); + ddbname, + pline); } } break; default: gmx_fatal(FARGS, - "Didnt find a case for directive %s in read_vsite_database\n", dirstr); + "Didnt find a case for directive %s in read_vsite_database\n", + dirstr); } } } @@ -450,8 +452,11 @@ static real get_ddb_bond(gmx::ArrayRef vsitetop, }); if (foundBond == found->bond.end()) { - gmx_fatal(FARGS, "Couldnt find bond %s-%s for residue %s in vsite database.\n", - atom1.c_str(), atom2.c_str(), res.c_str()); + gmx_fatal(FARGS, + "Couldnt find bond %s-%s for residue %s in vsite database.\n", + atom1.c_str(), + atom2.c_str(), + res.c_str()); } return foundBond->value; @@ -482,8 +487,12 @@ static real get_ddb_angle(gmx::ArrayRef vsitetop, if (foundAngle == found->angle.end()) { - gmx_fatal(FARGS, "Couldnt find angle %s-%s-%s for residue %s in vsite database.\n", - atom1.c_str(), atom2.c_str(), atom3.c_str(), res.c_str()); + gmx_fatal(FARGS, + "Couldnt find angle %s-%s-%s for residue %s in vsite database.\n", + atom1.c_str(), + atom2.c_str(), + atom3.c_str(), + res.c_str()); } return foundAngle->value; @@ -505,7 +514,8 @@ static void count_bonds(int atom, /* find heavy atom bound to this hydrogen */ heavy = NOTSET; for (auto parm = psb->interactionTypes.begin(); - (parm != psb->interactionTypes.end()) && (heavy == NOTSET); parm++) + (parm != psb->interactionTypes.end()) && (heavy == NOTSET); + parm++) { if (parm->ai() == atom) { @@ -668,7 +678,8 @@ static void add_vsites(gmx::ArrayRef plist, gmx_fatal(FARGS, "cannot make constraint in add_vsites for %d heavy " "atoms and %d hydrogen atoms", - nrheavies, nrHatoms); + nrheavies, + nrHatoms); } my_add_param(&(plist[F_CONSTRNC]), Hatoms[i], heavies[0], NOTSET); } @@ -681,8 +692,10 @@ static void add_vsites(gmx::ArrayRef plist, case F_VSITE3OUT: if (nrheavies < 2) { - gmx_fatal(FARGS, "Not enough heavy atoms (%d) for %s (min 3)", - nrheavies + 1, interaction_function[vsite_type[Hatoms[i]]].name); + gmx_fatal(FARGS, + "Not enough heavy atoms (%d) for %s (min 3)", + nrheavies + 1, + interaction_function[vsite_type[Hatoms[i]]].name); } add_vsite3_atoms(&plist[ftype], Hatoms[i], Heavy, heavies[0], heavies[1], bSwapParity); break; @@ -725,14 +738,17 @@ static void add_vsites(gmx::ArrayRef plist, case F_VSITE4FDN: if (nrheavies < 3) { - gmx_fatal(FARGS, "Not enough heavy atoms (%d) for %s (min 4)", - nrheavies + 1, interaction_function[vsite_type[Hatoms[i]]].name); + gmx_fatal(FARGS, + "Not enough heavy atoms (%d) for %s (min 4)", + nrheavies + 1, + interaction_function[vsite_type[Hatoms[i]]].name); } add_vsite4_atoms(&plist[ftype], Hatoms[0], Heavy, heavies[0], heavies[1], heavies[2]); break; default: - gmx_fatal(FARGS, "can't use add_vsites for interaction function %s", + gmx_fatal(FARGS, + "can't use add_vsites for interaction function %s", interaction_function[vsite_type[Hatoms[i]]].name); } /* switch ftype */ } /* else */ @@ -1143,15 +1159,15 @@ static int gen_vsites_trp(PreprocessingAtomTypes* atype, */ rvec_sub(x[ats[atCB]], x[ats[atCG]], r_ij); rvec_sub(x[ats[atCD2]], x[ats[atCG]], r_ik); - calc_vsite3_param(xcom[0], ycom[0], xi[atCG], yi[atCG], xi[atCB], yi[atCB], xi[atCD2], - yi[atCD2], &a, &b); + calc_vsite3_param( + xcom[0], ycom[0], xi[atCG], yi[atCG], xi[atCB], yi[atCB], xi[atCD2], yi[atCD2], &a, &b); svmul(a, r_ij, t1); svmul(b, r_ik, t2); rvec_add(t1, t2, t1); rvec_add(t1, x[ats[atCG]], (*newx)[atM[0]]); - calc_vsite3_param(xcom[1], ycom[1], xi[atCG], yi[atCG], xi[atCB], yi[atCB], xi[atCD2], - yi[atCD2], &a, &b); + calc_vsite3_param( + xcom[1], ycom[1], xi[atCG], yi[atCG], xi[atCB], yi[atCB], xi[atCD2], yi[atCD2], &a, &b); svmul(a, r_ij, t1); svmul(b, r_ik, t2); rvec_add(t1, t2, t1); @@ -1205,10 +1221,10 @@ static int gen_vsites_trp(PreprocessingAtomTypes* atype, { if ((*vsite_type)[ats[i]] == F_VSITE3) { - calc_vsite3_param(xi[i], yi[i], xcom[0], ycom[0], xcom[1], ycom[1], xi[atCB], yi[atCB], - &a, &b); - add_vsite3_param(&plist[F_VSITE3], ats[i], add_shift + atM[0], add_shift + atM[1], - ats[atCB], a, b); + calc_vsite3_param( + xi[i], yi[i], xcom[0], ycom[0], xcom[1], ycom[1], xi[atCB], yi[atCB], &a, &b); + add_vsite3_param( + &plist[F_VSITE3], ats[i], add_shift + atM[0], add_shift + atM[1], ats[atCB], a, b); } } return nvsite; @@ -1584,40 +1600,40 @@ static int gen_vsites_his(t_atoms* at, /* HE1 */ if (ats[atHE1] != NOTSET) { - calc_vsite3_param(x[atHE1], y[atHE1], x[atCE1], y[atCE1], x[atNE2], y[atNE2], x[atCG], - y[atCG], &a, &b); + calc_vsite3_param( + x[atHE1], y[atHE1], x[atCE1], y[atCE1], x[atNE2], y[atNE2], x[atCG], y[atCG], &a, &b); add_vsite3_param(&plist[F_VSITE3], ats[atHE1], ats[atCE1], ats[atNE2], ats[atCG], a, b); } /* HE2 */ if (ats[atHE2] != NOTSET) { - calc_vsite3_param(x[atHE2], y[atHE2], x[atNE2], y[atNE2], x[atCE1], y[atCE1], x[atCG], - y[atCG], &a, &b); + calc_vsite3_param( + x[atHE2], y[atHE2], x[atNE2], y[atNE2], x[atCE1], y[atCE1], x[atCG], y[atCG], &a, &b); add_vsite3_param(&plist[F_VSITE3], ats[atHE2], ats[atNE2], ats[atCE1], ats[atCG], a, b); } /* ND1 */ - calc_vsite3_param(x[atND1], y[atND1], x[atNE2], y[atNE2], x[atCE1], y[atCE1], x[atCG], y[atCG], - &a, &b); + calc_vsite3_param( + x[atND1], y[atND1], x[atNE2], y[atNE2], x[atCE1], y[atCE1], x[atCG], y[atCG], &a, &b); add_vsite3_param(&plist[F_VSITE3], ats[atND1], ats[atNE2], ats[atCE1], ats[atCG], a, b); /* CD2 */ - calc_vsite3_param(x[atCD2], y[atCD2], x[atCE1], y[atCE1], x[atNE2], y[atNE2], x[atCG], y[atCG], - &a, &b); + calc_vsite3_param( + x[atCD2], y[atCD2], x[atCE1], y[atCE1], x[atNE2], y[atNE2], x[atCG], y[atCG], &a, &b); add_vsite3_param(&plist[F_VSITE3], ats[atCD2], ats[atCE1], ats[atNE2], ats[atCG], a, b); /* HD1 */ if (ats[atHD1] != NOTSET) { - calc_vsite3_param(x[atHD1], y[atHD1], x[atNE2], y[atNE2], x[atCE1], y[atCE1], x[atCG], - y[atCG], &a, &b); + calc_vsite3_param( + x[atHD1], y[atHD1], x[atNE2], y[atNE2], x[atCE1], y[atCE1], x[atCG], y[atCG], &a, &b); add_vsite3_param(&plist[F_VSITE3], ats[atHD1], ats[atNE2], ats[atCE1], ats[atCG], a, b); } /* HD2 */ if (ats[atHD2] != NOTSET) { - calc_vsite3_param(x[atHD2], y[atHD2], x[atCE1], y[atCE1], x[atNE2], y[atNE2], x[atCG], - y[atCG], &a, &b); + calc_vsite3_param( + x[atHD2], y[atHD2], x[atCE1], y[atCE1], x[atNE2], y[atNE2], x[atCG], y[atCG], &a, &b); add_vsite3_param(&plist[F_VSITE3], ats[atHD2], ats[atCE1], ats[atNE2], ats[atCG], a, b); } return nvsite; @@ -1690,17 +1706,58 @@ void do_vsites(gmx::ArrayRef rtpFFDB, /* the atnms for every residue MUST correspond to the enums in the gen_vsites_* (one for each residue) routines! */ /* also the atom names in atnms MUST be in the same order as in the .rtp! */ - const char* atnms[resNR][MAXATOMSPERRESIDUE + 1] = { - { "CG", /* PHE */ - "CD1", "HD1", "CD2", "HD2", "CE1", "HE1", "CE2", "HE2", "CZ", "HZ", nullptr }, - { "CB", /* TRP */ - "CG", "CD1", "HD1", "CD2", "NE1", "HE1", "CE2", "CE3", "HE3", "CZ2", "HZ2", "CZ3", "HZ3", - "CH2", "HH2", nullptr }, - { "CG", /* TYR */ - "CD1", "HD1", "CD2", "HD2", "CE1", "HE1", "CE2", "HE2", "CZ", "OH", "HH", nullptr }, - { "CG", /* HIS */ - "ND1", "HD1", "CD2", "HD2", "CE1", "HE1", "NE2", "HE2", nullptr } - }; + const char* atnms[resNR][MAXATOMSPERRESIDUE + 1] = { { "CG", /* PHE */ + "CD1", + "HD1", + "CD2", + "HD2", + "CE1", + "HE1", + "CE2", + "HE2", + "CZ", + "HZ", + nullptr }, + { "CB", /* TRP */ + "CG", + "CD1", + "HD1", + "CD2", + "NE1", + "HE1", + "CE2", + "CE3", + "HE3", + "CZ2", + "HZ2", + "CZ3", + "HZ3", + "CH2", + "HH2", + nullptr }, + { "CG", /* TYR */ + "CD1", + "HD1", + "CD2", + "HD2", + "CE1", + "HE1", + "CE2", + "HE2", + "CZ", + "OH", + "HH", + nullptr }, + { "CG", /* HIS */ + "ND1", + "HD1", + "CD2", + "HD2", + "CE1", + "HE1", + "NE2", + "HE2", + nullptr } }; if (debug) { @@ -1818,7 +1875,10 @@ void do_vsites(gmx::ArrayRef rtpFFDB, "not enough atoms found (%d, need %d) in " "residue %s %d while\n " "generating aromatics virtual site construction", - nrfound, needed, resnm, at->resinfo[resind].nr); + nrfound, + needed, + resnm, + at->resinfo[resind].nr); } /* Advance overall atom counter */ i++; @@ -1839,18 +1899,48 @@ void do_vsites(gmx::ArrayRef rtpFFDB, { fprintf(stderr, "TRP at %d\n", o2n[ats[0]] + 1); } - nvsite += gen_vsites_trp(atype, &newx, &newatom, &newatomname, &o2n, - &newvsite_type, &newcgnr, symtab, &nadd, *x, cgnr, at, - vsite_type, plist, nrfound, ats, add_shift, vsitetop); + nvsite += gen_vsites_trp(atype, + &newx, + &newatom, + &newatomname, + &o2n, + &newvsite_type, + &newcgnr, + symtab, + &nadd, + *x, + cgnr, + at, + vsite_type, + plist, + nrfound, + ats, + add_shift, + vsitetop); break; case resTYR: if (debug) { fprintf(stderr, "TYR at %d\n", o2n[ats[0]] + 1); } - nvsite += gen_vsites_tyr(atype, &newx, &newatom, &newatomname, &o2n, - &newvsite_type, &newcgnr, symtab, &nadd, *x, cgnr, at, - vsite_type, plist, nrfound, ats, add_shift, vsitetop); + nvsite += gen_vsites_tyr(atype, + &newx, + &newatom, + &newatomname, + &o2n, + &newvsite_type, + &newcgnr, + symtab, + &nadd, + *x, + cgnr, + at, + vsite_type, + plist, + nrfound, + ats, + add_shift, + vsitetop); break; case resHIS: if (debug) @@ -1877,8 +1967,7 @@ void do_vsites(gmx::ArrayRef rtpFFDB, { /* find heavy atom, count #bonds from it and #H atoms bound to it and return H atom numbers (Hatoms) and heavy atom numbers (heavies) */ - count_bonds(i, &plist[F_BONDS], at->atomname, &nrbonds, &nrHatoms, Hatoms, &Heavy, - &nrheavies, heavies); + count_bonds(i, &plist[F_BONDS], at->atomname, &nrbonds, &nrHatoms, Hatoms, &Heavy, &nrheavies, heavies); /* get Heavy atom type */ tpHeavy = get_atype(Heavy, at, rtpFFDB, &rt); strcpy(tpname, atype->atomNameFromAtomType(tpHeavy)); @@ -1990,14 +2079,16 @@ void do_vsites(gmx::ArrayRef rtpFFDB, FARGS, "Can't find dummy mass for type %s bonded to type %s in the " "virtual site database (.vsd files). Add it to the database!\n", - tpname, nexttpname); + tpname, + nexttpname); } else { gmx_fatal(FARGS, "A dummy mass for type %s bonded to type %s is required, but " "no virtual site database (.vsd) files where found.\n", - tpname, nexttpname); + tpname, + nexttpname); } } else @@ -2099,12 +2190,20 @@ void do_vsites(gmx::ArrayRef rtpFFDB, /* generate Heavy, H1, H2 and H3 from M1, M2 and heavies[0] */ /* note that vsite_type cannot be NOTSET, because we just set it */ - add_vsite3_atoms(&plist[(*vsite_type)[Heavy]], Heavy, heavies[0], - add_shift + ni0, add_shift + ni0 + 1, FALSE); + add_vsite3_atoms(&plist[(*vsite_type)[Heavy]], + Heavy, + heavies[0], + add_shift + ni0, + add_shift + ni0 + 1, + FALSE); for (int j = 0; j < nrHatoms; j++) { - add_vsite3_atoms(&plist[(*vsite_type)[Hatoms[j]]], Hatoms[j], heavies[0], - add_shift + ni0, add_shift + ni0 + 1, Hat_SwapParity[j]); + add_vsite3_atoms(&plist[(*vsite_type)[Hatoms[j]]], + Hatoms[j], + heavies[0], + add_shift + ni0, + add_shift + ni0 + 1, + Hat_SwapParity[j]); } #undef NMASS } @@ -2119,7 +2218,11 @@ void do_vsites(gmx::ArrayRef rtpFFDB, "Cannot convert atom %d %s (bound to a heavy atom " "%s with \n" " %d bonds and %d bound hydrogens atoms) to virtual site\n", - i + 1, *(at->atomname[i]), tpname, nrbonds, nrHatoms); + i + 1, + *(at->atomname[i]), + tpname, + nrbonds, + nrHatoms); } if (bAddVsiteParam) { @@ -2152,8 +2255,12 @@ void do_vsites(gmx::ArrayRef rtpFFDB, fprintf(debug, "Before inserting new atoms:\n"); for (int i = 0; i < at->nr; i++) { - fprintf(debug, "%4d %4d %4s %4d %4s %6d %-10s\n", i + 1, o2n[i] + 1, - at->atomname[i] ? *(at->atomname[i]) : "(NULL)", at->resinfo[at->atom[i].resind].nr, + fprintf(debug, + "%4d %4d %4s %4d %4s %6d %-10s\n", + i + 1, + o2n[i] + 1, + at->atomname[i] ? *(at->atomname[i]) : "(NULL)", + at->resinfo[at->atom[i].resind].nr, at->resinfo[at->atom[i].resind].name ? *(at->resinfo[at->atom[i].resind].name) : "(NULL)", (*cgnr)[i], ((*vsite_type)[i] == NOTSET) ? "NOTSET" : interaction_function[(*vsite_type)[i]].name); @@ -2163,8 +2270,12 @@ void do_vsites(gmx::ArrayRef rtpFFDB, { if (newatomname[i]) { - fprintf(debug, "%4d %4s %4d %6d %-10s\n", i + 1, - newatomname[i] ? *(newatomname[i]) : "(NULL)", newatom[i].resind, newcgnr[i], + fprintf(debug, + "%4d %4s %4d %6d %-10s\n", + i + 1, + newatomname[i] ? *(newatomname[i]) : "(NULL)", + newatom[i].resind, + newcgnr[i], (newvsite_type[i] == NOTSET) ? "NOTSET" : interaction_function[newvsite_type[i]].name); } @@ -2197,7 +2308,8 @@ void do_vsites(gmx::ArrayRef rtpFFDB, gmx_fatal(FARGS, "Added impossible amount of dummy masses " "(%d on a total of %d atoms)\n", - nadd, at->nr - nadd); + nadd, + at->nr - nadd); } if (debug) @@ -2205,8 +2317,11 @@ void do_vsites(gmx::ArrayRef rtpFFDB, fprintf(debug, "After inserting new atoms:\n"); for (int i = 0; i < at->nr; i++) { - fprintf(debug, "%4d %4s %4d %4s %6d %-10s\n", i + 1, - at->atomname[i] ? *(at->atomname[i]) : "(NULL)", at->resinfo[at->atom[i].resind].nr, + fprintf(debug, + "%4d %4s %4d %4s %6d %-10s\n", + i + 1, + at->atomname[i] ? *(at->atomname[i]) : "(NULL)", + at->resinfo[at->atom[i].resind].nr, at->resinfo[at->atom[i].resind].name ? *(at->resinfo[at->atom[i].resind].name) : "(NULL)", (*cgnr)[i], ((*vsite_type)[i] == NOTSET) ? "NOTSET" : interaction_function[(*vsite_type)[i]].name); @@ -2279,7 +2394,8 @@ void do_h_mass(InteractionsOfType* psb, int vsite_type[], t_atoms* at, real mHmu /* find bonded heavy atom */ int a = NOTSET; for (auto parm = psb->interactionTypes.begin(); - (parm != psb->interactionTypes.end()) && (a == NOTSET); parm++) + (parm != psb->interactionTypes.end()) && (a == NOTSET); + parm++) { /* if other atom is not a virtual site, it is the one we want */ if ((parm->ai() == i) && !is_vsite(vsite_type[parm->aj()])) diff --git a/src/gromacs/gmxpreprocess/genconf.cpp b/src/gromacs/gmxpreprocess/genconf.cpp index 37d6384f6e..55bc942955 100644 --- a/src/gromacs/gmxpreprocess/genconf.cpp +++ b/src/gromacs/gmxpreprocess/genconf.cpp @@ -152,8 +152,8 @@ int gmx_genconf(int argc, char* argv[]) { "-renumber", FALSE, etBOOL, { &bRenum }, "Renumber residues" } }; - if (!parse_common_args(&argc, argv, 0, NFILE, fnm, asize(pa), pa, asize(desc), desc, - asize(bugs), bugs, &oenv)) + if (!parse_common_args( + &argc, argv, 0, NFILE, fnm, asize(pa), pa, asize(desc), desc, asize(bugs), bugs, &oenv)) { return 0; } diff --git a/src/gromacs/gmxpreprocess/genhydro.cpp b/src/gromacs/gmxpreprocess/genhydro.cpp index d745204dc1..af370d5e71 100644 --- a/src/gromacs/gmxpreprocess/genhydro.cpp +++ b/src/gromacs/gmxpreprocess/genhydro.cpp @@ -208,7 +208,9 @@ static void expand_hackblocks_one(const MoleculePatchDatabase& newPatch, { fprintf(debug, "Hack '%s' %d, replacing nname '%s' with '%s' (old name '%s')\n", - localAtomName.c_str(), pos, patch->nname.c_str(), + localAtomName.c_str(), + pos, + patch->nname.c_str(), singlePatch.nname.c_str(), patch->oname.empty() ? "" : patch->oname.c_str()); } @@ -240,8 +242,11 @@ static void expand_hackblocks_one(const MoleculePatchDatabase& newPatch, for (int k = 0; k < singlePatch.nr; k++) { expand_hackblocks_one( - newPatch, globalPatches->at(globalPatches->size() - singlePatch.nr + k).nname, - globalPatches, bN, bC); + newPatch, + globalPatches->at(globalPatches->size() - singlePatch.nr + k).nname, + globalPatches, + bN, + bC); } } } @@ -347,8 +352,12 @@ static void calc_all_pos(const t_atoms* pdba, bool bFoundAll = true; for (int m = 0; (m < patch->nctl && bFoundAll); m++) { - int ia = pdbasearch_atom(patch->a[m].c_str(), rnr, pdba, bCheckMissing ? "atom" : "check", - !bCheckMissing, cyclicBondsIndex); + int ia = pdbasearch_atom(patch->a[m].c_str(), + rnr, + pdba, + bCheckMissing ? "atom" : "check", + !bCheckMissing, + cyclicBondsIndex); if (ia < 0) { /* not found in original atoms, might still be in @@ -367,8 +376,10 @@ static void calc_all_pos(const t_atoms* pdba, "Atom %s not found in residue %s %d" ", rtp entry %s" " while adding hydrogens", - patch->a[m].c_str(), *pdba->resinfo[rnr].name, - pdba->resinfo[rnr].nr, *pdba->resinfo[rnr].rtp); + patch->a[m].c_str(), + *pdba->resinfo[rnr].name, + pdba->resinfo[rnr].nr, + *pdba->resinfo[rnr].rtp); } } } @@ -510,7 +521,9 @@ static int add_h_low(t_atoms** initialAtoms, { if (gmx_debug_at) { - fprintf(debug, "Replacing %d '%s' with (old name '%s') %s\n", newi, + fprintf(debug, + "Replacing %d '%s' with (old name '%s') %s\n", + newi, ((*modifiedAtoms)->atomname[newi] && *(*modifiedAtoms)->atomname[newi]) ? *(*modifiedAtoms)->atomname[newi] : "", @@ -525,8 +538,11 @@ static int add_h_low(t_atoms** initialAtoms, } if (debug) { - fprintf(debug, " %s %g %g", *(*modifiedAtoms)->atomname[newi], - (*modifiedAtoms)->atom[newi].m, (*modifiedAtoms)->atom[newi].q); + fprintf(debug, + " %s %g %g", + *(*modifiedAtoms)->atomname[newi], + (*modifiedAtoms)->atom[newi].m, + (*modifiedAtoms)->atom[newi].q); } } } @@ -567,8 +583,8 @@ int add_h(t_atoms** initialAtoms, do { nold = nnew; - nnew = add_h_low(initialAtoms, localAtoms, xptr, globalPatches, symtab, nterpairs, ntdb, - ctdb, rN, rC, FALSE, cyclicBondsIndex); + nnew = add_h_low( + initialAtoms, localAtoms, xptr, globalPatches, symtab, nterpairs, ntdb, ctdb, rN, rC, FALSE, cyclicBondsIndex); niter++; if (niter > 100) { @@ -581,8 +597,7 @@ int add_h(t_atoms** initialAtoms, if (!bAllowMissing) { /* Call add_h_low once more, now only for the missing atoms check */ - add_h_low(initialAtoms, localAtoms, xptr, globalPatches, symtab, nterpairs, ntdb, ctdb, rN, - rC, TRUE, cyclicBondsIndex); + add_h_low(initialAtoms, localAtoms, xptr, globalPatches, symtab, nterpairs, ntdb, ctdb, rN, rC, TRUE, cyclicBondsIndex); } return nnew; diff --git a/src/gromacs/gmxpreprocess/genion.cpp b/src/gromacs/gmxpreprocess/genion.cpp index 487ffa0c8f..4d98124057 100644 --- a/src/gromacs/gmxpreprocess/genion.cpp +++ b/src/gromacs/gmxpreprocess/genion.cpp @@ -155,8 +155,11 @@ static void insert_ion(int nsa, gmx_fatal(FARGS, "No more replaceable solvent!"); } - fprintf(stderr, "Replacing solvent molecule %d (atom %d) with %s\n", - solventMoleculesForReplacement->back(), solventMoleculeAtomsToBeReplaced[0], ionname); + fprintf(stderr, + "Replacing solvent molecule %d (atom %d) with %s\n", + solventMoleculesForReplacement->back(), + solventMoleculeAtomsToBeReplaced[0], + ionname); /* Replace solvent molecule charges with ion charge */ notSolventGroup->push_back(solventMoleculeAtomsToBeReplaced[0]); @@ -166,7 +169,8 @@ static void insert_ion(int nsa, // charge while the rest of the solvent molecule atoms is set to 0 charge. atoms->atom[solventMoleculeAtomsToBeReplaced.front()].q = q; for (auto replacedMoleculeAtom = solventMoleculeAtomsToBeReplaced.begin() + 1; - replacedMoleculeAtom != solventMoleculeAtomsToBeReplaced.end(); ++replacedMoleculeAtom) + replacedMoleculeAtom != solventMoleculeAtomsToBeReplaced.end(); + ++replacedMoleculeAtom) { atoms->atom[*replacedMoleculeAtom].q = 0; } @@ -350,7 +354,8 @@ static void update_topol(const char* topinout, int p_num, int n_num, const char* gmx_ffclose(fpout); gmx_fatal(FARGS, "No line with moleculetype '%s' found the [ molecules ] section of file '%s'", - grpname, topinout); + grpname, + topinout); } if (nsol_last < p_num + n_num) { @@ -358,7 +363,10 @@ static void update_topol(const char* topinout, int p_num, int n_num, const char* gmx_fatal(FARGS, "The last entry for moleculetype '%s' in the [ molecules ] section of file '%s' " "has less solvent molecules (%d) than were replaced (%d)", - grpname, topinout, nsol_last, p_num + n_num); + grpname, + topinout, + nsol_last, + p_num + n_num); } /* Print all the molecule entries */ @@ -372,7 +380,12 @@ static void update_topol(const char* topinout, int p_num, int n_num, const char* { printf("Replacing %d solute molecules in topology file (%s) " " by %d %s and %d %s ions.\n", - p_num + n_num, topinout, p_num, p_name, n_num, n_name); + p_num + n_num, + topinout, + p_num, + p_name, + n_num, + n_name); nsol_last -= p_num + n_num; if (nsol_last > 0) { @@ -417,8 +430,7 @@ static std::vector invertIndexGroup(int nrAtoms, std::vector indexGrou if (numIndicesToAdd > 0) { invertedGroup.resize(invertedGroup.size() + numIndicesToAdd); - std::iota(std::end(invertedGroup) - numIndicesToAdd, std::end(invertedGroup), - firstToAddToInvertedGroup); + std::iota(std::end(invertedGroup) - numIndicesToAdd, std::end(invertedGroup), firstToAddToInvertedGroup); } } @@ -490,8 +502,8 @@ int gmx_genion(int argc, char* argv[]) { efTOP, "-p", "topol", ffOPTRW } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, 0, NFILE, fnm, asize(pa), pa, asize(desc), desc, - asize(bugs), bugs, &oenv)) + if (!parse_common_args( + &argc, argv, 0, NFILE, fnm, asize(pa), pa, asize(desc), desc, asize(bugs), bugs, &oenv)) { if (oenv != nullptr) { @@ -544,7 +556,8 @@ int gmx_genion(int argc, char* argv[]) gmx_fatal(FARGS, "Can't neutralize this system using -nq %d and" " -pq %d.\n", - n_q, p_q); + n_q, + p_q); } while (qdelta != 0) @@ -594,7 +607,11 @@ int gmx_genion(int argc, char* argv[]) gmx_fatal(FARGS, "The solvent group %s is not continuous: " "index[%d]=%d, index[%d]=%d", - grpname, int(i), solventGroup[i - 1] + 1, int(i + 1), solventGroup[i] + 1); + grpname, + int(i), + solventGroup[i - 1] + 1, + int(i + 1), + solventGroup[i] + 1); } } nsa = 1; @@ -605,8 +622,10 @@ int gmx_genion(int argc, char* argv[]) } if (solventGroup.size() % nsa != 0) { - gmx_fatal(FARGS, "Your solvent group size (%td) is not a multiple of %d", - gmx::ssize(solventGroup), nsa); + gmx_fatal(FARGS, + "Your solvent group size (%td) is not a multiple of %d", + gmx::ssize(solventGroup), + nsa); } nw = solventGroup.size() / nsa; fprintf(stderr, "Number of (%d-atomic) solvent molecules: %d\n", nsa, nw); @@ -640,19 +659,19 @@ int gmx_genion(int argc, char* argv[]) // Randomly shuffle the solvent molecules that shall be replaced by ions // then pick molecules from the back of the list as replacement candidates gmx::DefaultRandomEngine rng(seed); - std::shuffle(std::begin(solventMoleculesForReplacement), - std::end(solventMoleculesForReplacement), rng); + std::shuffle( + std::begin(solventMoleculesForReplacement), std::end(solventMoleculesForReplacement), rng); /* Now loop over the ions that have to be placed */ while (p_num-- > 0) { - insert_ion(nsa, &solventMoleculesForReplacement, repl, solventGroup, x, &pbc, 1, p_q, - p_name, &atoms, rmin, ¬SolventGroup); + insert_ion( + nsa, &solventMoleculesForReplacement, repl, solventGroup, x, &pbc, 1, p_q, p_name, &atoms, rmin, ¬SolventGroup); } while (n_num-- > 0) { - insert_ion(nsa, &solventMoleculesForReplacement, repl, solventGroup, x, &pbc, -1, n_q, - n_name, &atoms, rmin, ¬SolventGroup); + insert_ion( + nsa, &solventMoleculesForReplacement, repl, solventGroup, x, &pbc, -1, n_q, n_name, &atoms, rmin, ¬SolventGroup); } fprintf(stderr, "\n"); diff --git a/src/gromacs/gmxpreprocess/genrestr.cpp b/src/gromacs/gmxpreprocess/genrestr.cpp index 7c488ab20e..2670ae994b 100644 --- a/src/gromacs/gmxpreprocess/genrestr.cpp +++ b/src/gromacs/gmxpreprocess/genrestr.cpp @@ -232,8 +232,17 @@ int gmx_genrestr(int argc, char* argv[]) { fprintf(out, "; distance restraints for %s of %s\n\n", indexGroupNames, title); fprintf(out, "[ distance_restraints ]\n"); - fprintf(out, ";%4s %5s %1s %5s %10s %10s %10s %10s %10s\n", "i", "j", "?", "label", - "funct", "lo", "up1", "up2", "weight"); + fprintf(out, + ";%4s %5s %1s %5s %10s %10s %10s %10s %10s\n", + "i", + "j", + "?", + "label", + "funct", + "lo", + "up1", + "up2", + "weight"); } for (i = k = 0; i < igrp; i++) { @@ -259,8 +268,17 @@ int gmx_genrestr(int argc, char* argv[]) } lo = std::max(0.0_real, d - dd); hi = d + dd; - fprintf(out, "%5d %5d %1d %5d %10d %10g %10g %10g %10g\n", indexGroups[i] + 1, - indexGroups[j] + 1, 1, k, 1, lo, hi, hi + disre_up2, 1.0); + fprintf(out, + "%5d %5d %1d %5d %10d %10g %10g %10g %10g\n", + indexGroups[i] + 1, + indexGroups[j] + 1, + 1, + k, + 1, + lo, + hi, + hi + disre_up2, + 1.0); } } } diff --git a/src/gromacs/gmxpreprocess/gmxcpp.cpp b/src/gromacs/gmxpreprocess/gmxcpp.cpp index c359c7a450..1a597a4101 100644 --- a/src/gromacs/gmxpreprocess/gmxcpp.cpp +++ b/src/gromacs/gmxpreprocess/gmxcpp.cpp @@ -477,8 +477,8 @@ static int process_directive(gmx_cpp_t* handlep, const std::string& dname, const std::string inc_fn = dval.substr(i0, len); /* Open include file and store it as a child in the handle structure */ - int status = cpp_open_file(inc_fn.c_str(), &(handle->child), nullptr, &handle->defines, - &handle->includes); + int status = cpp_open_file( + inc_fn.c_str(), &(handle->child), nullptr, &handle->defines, &handle->includes); if (status != eCPP_OK) { handle->child = nullptr; @@ -751,9 +751,12 @@ char* cpp_error(gmx_cpp_t* handlep, int status) status = eCPP_NR; } - sprintf(buf, "%s - File %s, line %d\nLast line read:\n'%s'", ecpp[status], + sprintf(buf, + "%s - File %s, line %d\nLast line read:\n'%s'", + ecpp[status], (handle && !handle->fn.empty()) ? handle->fn.c_str() : "unknown", - (handle) ? handle->line_nr : -1, !handle->line.empty() ? handle->line.c_str() : ""); + (handle) ? handle->line_nr : -1, + !handle->line.empty() ? handle->line.c_str() : ""); return gmx_strdup(buf); } diff --git a/src/gromacs/gmxpreprocess/gpp_atomtype.cpp b/src/gromacs/gmxpreprocess/gpp_atomtype.cpp index 46376534a0..404e4d77b4 100644 --- a/src/gromacs/gmxpreprocess/gpp_atomtype.cpp +++ b/src/gromacs/gmxpreprocess/gpp_atomtype.cpp @@ -96,8 +96,9 @@ bool PreprocessingAtomTypes::isSet(int nt) const int PreprocessingAtomTypes::atomTypeFromName(const std::string& str) const { /* Atom types are always case sensitive */ - auto found = std::find_if(impl_->types.begin(), impl_->types.end(), - [&str](const auto& type) { return str == *type.name_; }); + auto found = std::find_if(impl_->types.begin(), impl_->types.end(), [&str](const auto& type) { + return str == *type.name_; + }); if (found == impl_->types.end()) { return NOTSET; @@ -216,12 +217,24 @@ int PreprocessingAtomTypes::setType(int nt, void PreprocessingAtomTypes::printTypes(FILE* out) { fprintf(out, "[ %s ]\n", dir2str(Directive::d_atomtypes)); - fprintf(out, "; %6s %8s %8s %8s %12s %12s\n", "type", "mass", "charge", "particle", "c6", + fprintf(out, + "; %6s %8s %8s %8s %12s %12s\n", + "type", + "mass", + "charge", + "particle", + "c6", "c12"); for (auto& entry : impl_->types) { - fprintf(out, "%8s %8.3f %8.3f %8s %12e %12e\n", *(entry.name_), entry.atom_.m, - entry.atom_.q, "A", entry.nb_.c0(), entry.nb_.c1()); + fprintf(out, + "%8s %8.3f %8.3f %8s %12e %12e\n", + *(entry.name_), + entry.atom_.m, + entry.atom_.q, + "A", + entry.nb_.c0(), + entry.nb_.c1()); } fprintf(out, "\n"); @@ -328,10 +341,10 @@ void PreprocessingAtomTypes::renumberTypes(gmx::ArrayRef pli const t_atoms* atoms = &moltype.atoms; for (int i = 0; (i < atoms->nr); i++) { - atoms->atom[i].type = search_atomtypes(this, &nat, typelist, atoms->atom[i].type, - plist[ftype].interactionTypes, ftype); - atoms->atom[i].typeB = search_atomtypes(this, &nat, typelist, atoms->atom[i].typeB, - plist[ftype].interactionTypes, ftype); + atoms->atom[i].type = search_atomtypes( + this, &nat, typelist, atoms->atom[i].type, plist[ftype].interactionTypes, ftype); + atoms->atom[i].typeB = search_atomtypes( + this, &nat, typelist, atoms->atom[i].typeB, plist[ftype].interactionTypes, ftype); } } @@ -339,8 +352,8 @@ void PreprocessingAtomTypes::renumberTypes(gmx::ArrayRef pli { if (wall_atomtype[i] >= 0) { - wall_atomtype[i] = search_atomtypes(this, &nat, typelist, wall_atomtype[i], - plist[ftype].interactionTypes, ftype); + wall_atomtype[i] = search_atomtypes( + this, &nat, typelist, wall_atomtype[i], plist[ftype].interactionTypes, ftype); } } @@ -357,7 +370,8 @@ void PreprocessingAtomTypes::renumberTypes(gmx::ArrayRef pli { int mj = typelist[j]; const InteractionOfType& interactionType = plist[ftype].interactionTypes[ntype * mi + mj]; - nbsnew.emplace_back(interactionType.atoms(), interactionType.forceParam(), + nbsnew.emplace_back(interactionType.atoms(), + interactionType.forceParam(), interactionType.interactionTypeName()); } new_types.push_back(impl_->types[mi]); diff --git a/src/gromacs/gmxpreprocess/gpp_bond_atomtype.cpp b/src/gromacs/gmxpreprocess/gpp_bond_atomtype.cpp index 395bf76067..887d54743a 100644 --- a/src/gromacs/gmxpreprocess/gpp_bond_atomtype.cpp +++ b/src/gromacs/gmxpreprocess/gpp_bond_atomtype.cpp @@ -59,9 +59,9 @@ public: int PreprocessingBondAtomType::bondAtomTypeFromName(const std::string& str) const { /* Atom types are always case sensitive */ - auto found = - std::find_if(impl_->typeNames.begin(), impl_->typeNames.end(), - [&str](const auto& type) { return str == const_cast(*type); }); + auto found = std::find_if(impl_->typeNames.begin(), impl_->typeNames.end(), [&str](const auto& type) { + return str == const_cast(*type); + }); if (found == impl_->typeNames.end()) { return NOTSET; diff --git a/src/gromacs/gmxpreprocess/grompp.cpp b/src/gromacs/gmxpreprocess/grompp.cpp index 46a48b93e4..cb052c723a 100644 --- a/src/gromacs/gmxpreprocess/grompp.cpp +++ b/src/gromacs/gmxpreprocess/grompp.cpp @@ -297,8 +297,12 @@ static int check_atom_names(const char* fn1, GMX_LOG(logger.warning) .asParagraph() .appendTextFormatted( - "atom name %d in %s and %s does not match (%s - %s)", i + 1, - fn1, fn2, *(tat->atomname[j]), *(at->atomname[i])); + "atom name %d in %s and %s does not match (%s - %s)", + i + 1, + fn1, + fn2, + *(tat->atomname[j]), + *(at->atomname[i])); } else if (nmismatch == c_maxNumberOfMismatches) { @@ -436,9 +440,14 @@ static void check_bonds_timestep(const gmx_mtop_t* mtop, double dt, warninp* wi) "oscillational period of %.1e ps, which is less than %d times the time step of " "%.1e ps.\n" "%s", - *w_moltype->name, w_a1 + 1, *w_moltype->atoms.atomname[w_a1], w_a2 + 1, - *w_moltype->atoms.atomname[w_a2], std::sqrt(w_period2), - bWarn ? min_steps_warn : min_steps_note, dt, + *w_moltype->name, + w_a1 + 1, + *w_moltype->atoms.atomname[w_a1], + w_a2 + 1, + *w_moltype->atoms.atomname[w_a2], + std::sqrt(w_period2), + bWarn ? min_steps_warn : min_steps_note, + dt, bWater ? "Maybe you asked for fexible water." : "Maybe you forgot to change the constraints mdp option."); if (bWarn) @@ -588,9 +597,24 @@ static void new_status(const char* topfile, bool ffParametrizedWithHBondConstraints; /* TOPOLOGY processing */ - sys->name = do_top(bVerbose, topfile, topppfile, opts, bZero, &(sys->symtab), interactions, - comb, reppow, fudgeQQ, atypes, mi, intermolecular_interactions, ir, - &molblock, &ffParametrizedWithHBondConstraints, wi, logger); + sys->name = do_top(bVerbose, + topfile, + topppfile, + opts, + bZero, + &(sys->symtab), + interactions, + comb, + reppow, + fudgeQQ, + atypes, + mi, + intermolecular_interactions, + ir, + &molblock, + &ffParametrizedWithHBondConstraints, + wi, + logger); sys->molblock.clear(); @@ -681,7 +705,10 @@ static void new_status(const char* topfile, gmx_fatal(FARGS, "number of coordinates in coordinate file (%s, %d)\n" " does not match topology (%s, %d)", - confin, state->natoms, topfile, sys->natoms); + confin, + state->natoms, + topfile, + sys->natoms); } /* It would be nice to get rid of the copies below, but we don't know * a priori if the number of atoms in confin matches what we expect. @@ -712,7 +739,10 @@ static void new_status(const char* topfile, "%d non-matching atom name%s\n" "atom names from %s will be used\n" "atom names from %s will be ignored\n", - nmismatch, (nmismatch == 1) ? "" : "s", topfile, confin); + nmismatch, + (nmismatch == 1) ? "" : "s", + topfile, + confin); warning(wi, warningMessage.c_str()); } @@ -913,7 +943,11 @@ static void read_posres(gmx_mtop_t* mtop, std::string warningMessage = gmx::formatString( "The number of atoms in %s (%d) does not match the number of atoms in the topology " "(%d). Will assume that the first %d atoms in the topology and %s match.", - fn, natoms, mtop->natoms, std::min(mtop->natoms, natoms), fn); + fn, + natoms, + mtop->natoms, + std::min(mtop->natoms, natoms), + fn); warning(wi, warningMessage.c_str()); } @@ -952,7 +986,10 @@ static void read_posres(gmx_mtop_t* mtop, gmx_fatal(FARGS, "Position restraint atom index (%d) in moltype '%s' is larger than " "number of atoms in %s (%d).\n", - ai + 1, *molinfo[molb.type].name, fn, natoms); + ai + 1, + *molinfo[molb.type].name, + fn, + natoms); } hadAtom[ai] = TRUE; if (rc_scaling == erscCOM) @@ -974,7 +1011,10 @@ static void read_posres(gmx_mtop_t* mtop, gmx_fatal(FARGS, "Position restraint atom index (%d) in moltype '%s' is larger than " "number of atoms in %s (%d).\n", - ai + 1, *molinfo[molb.type].name, fn, natoms); + ai + 1, + *molinfo[molb.type].name, + fn, + natoms); } if (rc_scaling == erscCOM && !hadAtom[ai]) { @@ -1019,7 +1059,9 @@ static void read_posres(gmx_mtop_t* mtop, .asParagraph() .appendTextFormatted( "The center of mass of the position restraint coord's is %6.3f %6.3f %6.3f", - com[XX], com[YY], com[ZZ]); + com[XX], + com[YY], + com[ZZ]); } if (rc_scaling != erscNO) @@ -1221,7 +1263,10 @@ static void setup_cmap(int grid_spacing, int nc, gmx::ArrayRef grid, for (i = 0; i < 2 * grid_spacing; i++) { - spline1d(dx, &(tmp_grid[2 * grid_spacing * i]), 2 * grid_spacing, tmp_u.data(), + spline1d(dx, + &(tmp_grid[2 * grid_spacing * i]), + 2 * grid_spacing, + tmp_u.data(), &(tmp_t2[2 * grid_spacing * i])); } @@ -1237,8 +1282,13 @@ static void setup_cmap(int grid_spacing, int nc, gmx::ArrayRef grid, for (k = 0; k < 2 * grid_spacing; k++) { - interpolate1d(xmin, dx, &(tmp_grid[2 * grid_spacing * k]), - &(tmp_t2[2 * grid_spacing * k]), psi, &tmp_yy[k], &tmp_y1[k]); + interpolate1d(xmin, + dx, + &(tmp_grid[2 * grid_spacing * k]), + &(tmp_t2[2 * grid_spacing * k]), + psi, + &tmp_yy[k], + &tmp_y1[k]); } spline1d(dx, tmp_yy.data(), 2 * grid_spacing, tmp_u.data(), tmp_u2.data()); @@ -1300,7 +1350,9 @@ static int count_constraints(const gmx_mtop_t* mtop, gmx::ArrayRefatomname[a], *molt->name); + a + 1, + *atoms->atomname[a], + *molt->name); } numDanglingAtoms++; } @@ -1420,7 +1474,8 @@ static void checkForUnboundAtoms(const gmx_moltype_t* molt, gmx_bool bVerbose, w "issues in a simulation, this often means that the user forgot to add a " "bond/potential/constraint or put multiple molecules in the same moleculetype " "definition by mistake. Run with -v to get information for each atom.", - *molt->name, numDanglingAtoms); + *molt->name, + numDanglingAtoms); warning_note(wi, warningMessage.c_str()); } } @@ -1583,8 +1638,11 @@ static void checkDecoupledModeAccuracy(const gmx_mtop_t* mtop, const t_inputrec* "hydrogens) or use integrator = %s or decrease one or more tolerances: " "verlet-buffer-tolerance <= %g, LINCS iterations >= %d, LINCS order " ">= %d or SHAKE tolerance <= %g", - ei_names[eiSD1], bufferToleranceThreshold, lincsIterationThreshold, - lincsOrderThreshold, shakeToleranceThreshold); + ei_names[eiSD1], + bufferToleranceThreshold, + lincsIterationThreshold, + lincsOrderThreshold, + shakeToleranceThreshold); } else { @@ -1609,19 +1667,20 @@ static void set_verlet_buffer(const gmx_mtop_t* mtop, .asParagraph() .appendTextFormatted( "Determining Verlet buffer for a tolerance of %g kJ/mol/ps at %g K", - ir->verletbuf_tol, buffer_temp); + ir->verletbuf_tol, + buffer_temp); /* Calculate the buffer size for simple atom vs atoms list */ VerletbufListSetup listSetup1x1; listSetup1x1.cluster_size_i = 1; listSetup1x1.cluster_size_j = 1; - const real rlist_1x1 = calcVerletBufferSize(*mtop, det(box), *ir, ir->nstlist, ir->nstlist - 1, - buffer_temp, listSetup1x1); + const real rlist_1x1 = calcVerletBufferSize( + *mtop, det(box), *ir, ir->nstlist, ir->nstlist - 1, buffer_temp, listSetup1x1); /* Set the pair-list buffer size in ir */ VerletbufListSetup listSetup4x4 = verletbufGetSafeListSetup(ListSetupType::CpuNoSimd); - ir->rlist = calcVerletBufferSize(*mtop, det(box), *ir, ir->nstlist, ir->nstlist - 1, - buffer_temp, listSetup4x4); + ir->rlist = calcVerletBufferSize( + *mtop, det(box), *ir, ir->nstlist, ir->nstlist - 1, buffer_temp, listSetup4x4); const int n_nonlin_vsite = gmx::countNonlinearVsites(*mtop); if (n_nonlin_vsite > 0) @@ -1637,14 +1696,19 @@ static void set_verlet_buffer(const gmx_mtop_t* mtop, GMX_LOG(logger.info) .asParagraph() .appendTextFormatted( - "Calculated rlist for %dx%d atom pair-list as %.3f nm, buffer size %.3f nm", 1, - 1, rlist_1x1, rlist_1x1 - std::max(ir->rvdw, ir->rcoulomb)); + "Calculated rlist for %dx%d atom pair-list as %.3f nm, buffer size %.3f nm", + 1, + 1, + rlist_1x1, + rlist_1x1 - std::max(ir->rvdw, ir->rcoulomb)); GMX_LOG(logger.info) .asParagraph() .appendTextFormatted( "Set rlist, assuming %dx%d atom pair-list, to %.3f nm, buffer size %.3f nm", - listSetup4x4.cluster_size_i, listSetup4x4.cluster_size_j, ir->rlist, + listSetup4x4.cluster_size_i, + listSetup4x4.cluster_size_j, + ir->rlist, ir->rlist - std::max(ir->rvdw, ir->rcoulomb)); GMX_LOG(logger.info) @@ -1658,7 +1722,8 @@ static void set_verlet_buffer(const gmx_mtop_t* mtop, "The pair-list cut-off (%g nm) is longer than half the shortest box vector or " "longer than the smallest box diagonal element (%g nm). Increase the box size or " "decrease nstlist or increase verlet-buffer-tolerance.", - ir->rlist, std::sqrt(max_cutoff2(ir->pbcType, box))); + ir->rlist, + std::sqrt(max_cutoff2(ir->pbcType, box))); } } @@ -1909,9 +1974,26 @@ int gmx_grompp(int argc, char* argv[]) } t_state state; - new_status(fn, opt2fn_null("-pp", NFILE, fnm), opt2fn("-c", NFILE, fnm), opts, ir, bZero, - bGenVel, bVerbose, &state, &atypes, &sys, &mi, &intermolecular_interactions, - interactions, &comb, &reppow, &fudgeQQ, opts->bMorse, wi, logger); + new_status(fn, + opt2fn_null("-pp", NFILE, fnm), + opt2fn("-c", NFILE, fnm), + opts, + ir, + bZero, + bGenVel, + bVerbose, + &state, + &atypes, + &sys, + &mi, + &intermolecular_interactions, + interactions, + &comb, + &reppow, + &fudgeQQ, + opts->bMorse, + wi, + logger); if (debug) { @@ -1938,16 +2020,18 @@ int gmx_grompp(int argc, char* argv[]) { if (ir->eI == eiCG || ir->eI == eiLBFGS) { - std::string warningMessage = - gmx::formatString("Can not do %s with %s, use %s", EI(ir->eI), - econstr_names[econtSHAKE], econstr_names[econtLINCS]); + std::string warningMessage = gmx::formatString("Can not do %s with %s, use %s", + EI(ir->eI), + econstr_names[econtSHAKE], + econstr_names[econtLINCS]); warning_error(wi, warningMessage); } if (ir->bPeriodicMols) { std::string warningMessage = gmx::formatString("Can not do periodic molecules with %s, use %s", - econstr_names[econtSHAKE], econstr_names[econtLINCS]); + econstr_names[econtSHAKE], + econstr_names[econtLINCS]); warning_error(wi, warningMessage); } } @@ -1970,7 +2054,8 @@ int gmx_grompp(int argc, char* argv[]) "You are combining position restraints with %s pressure coupling, which can " "lead to instabilities. If you really want to combine position restraints with " "pressure coupling, we suggest to use %s pressure coupling instead.", - EPCOUPLTYPE(ir->epc), EPCOUPLTYPE(epcBERENDSEN)); + EPCOUPLTYPE(ir->epc), + EPCOUPLTYPE(epcBERENDSEN)); warning_note(wi, warningMessage); } @@ -2014,17 +2099,19 @@ int gmx_grompp(int argc, char* argv[]) } GMX_LOG(logger.info).asParagraph().appendText(message); } - gen_posres(&sys, mi, fn, fnB, ir->refcoord_scaling, ir->pbcType, ir->posres_com, - ir->posres_comB, wi, logger); + gen_posres(&sys, mi, fn, fnB, ir->refcoord_scaling, ir->pbcType, ir->posres_com, ir->posres_comB, wi, logger); } /* If we are using CMAP, setup the pre-interpolation grid */ if (interactions[F_CMAP].ncmap() > 0) { - init_cmap_grid(&sys.ffparams.cmap_grid, interactions[F_CMAP].cmapAngles, + init_cmap_grid(&sys.ffparams.cmap_grid, + interactions[F_CMAP].cmapAngles, interactions[F_CMAP].cmakeGridSpacing); - setup_cmap(interactions[F_CMAP].cmakeGridSpacing, interactions[F_CMAP].cmapAngles, - interactions[F_CMAP].cmap, &sys.ffparams.cmap_grid); + setup_cmap(interactions[F_CMAP].cmakeGridSpacing, + interactions[F_CMAP].cmapAngles, + interactions[F_CMAP].cmap, + &sys.ffparams.cmap_grid); } set_wall_atomtype(&atypes, opts, ir, wi, logger); @@ -2052,8 +2139,8 @@ int gmx_grompp(int argc, char* argv[]) } const int ntype = atypes.size(); - convertInteractionsOfType(ntype, interactions, mi, intermolecular_interactions.get(), comb, - reppow, fudgeQQ, &sys); + convertInteractionsOfType( + ntype, interactions, mi, intermolecular_interactions.get(), comb, reppow, fudgeQQ, &sys); if (debug) { @@ -2178,7 +2265,8 @@ int gmx_grompp(int argc, char* argv[]) "NVE simulation of length %g ps, which can give a final drift of " "%d%%. For conserving energy to %d%% when using constraints, you " "might need to set verlet-buffer-tolerance to %.1e.", - ir->verletbuf_tol, ir->nsteps * ir->delta_t, + ir->verletbuf_tol, + ir->nsteps * ir->delta_t, gmx::roundToInt(ir->verletbuf_tol / totalEnergyDriftPerAtomPerPicosecond * 100), gmx::roundToInt(100 * driftTolerance), driftTolerance * totalEnergyDriftPerAtomPerPicosecond); @@ -2219,8 +2307,16 @@ int gmx_grompp(int argc, char* argv[]) .asParagraph() .appendTextFormatted("getting data from old trajectory ..."); } - cont_status(ftp2fn(efTRN, NFILE, fnm), ftp2fn_null(efEDR, NFILE, fnm), bNeedVel, bGenVel, - fr_time, ir, &state, &sys, oenv, logger); + cont_status(ftp2fn(efTRN, NFILE, fnm), + ftp2fn_null(efEDR, NFILE, fnm), + bNeedVel, + bGenVel, + fr_time, + ir, + &state, + &sys, + oenv, + logger); } if (ir->pbcType == PbcType::XY && ir->nwall != 2) @@ -2247,8 +2343,7 @@ int gmx_grompp(int argc, char* argv[]) wi, "Some of the Fourier grid sizes are set, but all of them need to be set."); } const int minGridSize = minimalPmeGridSize(ir->pme_order); - calcFftGrid(stdout, scaledBox, ir->fourier_spacing, minGridSize, &(ir->nkx), &(ir->nky), - &(ir->nkz)); + calcFftGrid(stdout, scaledBox, ir->fourier_spacing, minGridSize, &(ir->nkx), &(ir->nky), &(ir->nkz)); if (ir->nkx < minGridSize || ir->nky < minGridSize || ir->nkz < minGridSize) { warning_error(wi, @@ -2304,9 +2399,16 @@ int gmx_grompp(int argc, char* argv[]) copy_mat(ir->compress, compressibility); } setStateDependentAwhParams( - ir->awhParams, *ir->pull, pull, state.box, ir->pbcType, compressibility, &ir->opts, + ir->awhParams, + *ir->pull, + pull, + state.box, + ir->pbcType, + compressibility, + &ir->opts, ir->efep != efepNO ? ir->fepvals->all_lambda[efptFEP][ir->fepvals->init_fep_state] : 0, - sys, wi); + sys, + wi); } if (ir->bPull) @@ -2316,8 +2418,12 @@ int gmx_grompp(int argc, char* argv[]) if (ir->bRot) { - set_reference_positions(ir->rot, state.x.rvec_array(), state.box, - opt2fn("-ref", NFILE, fnm), opt2bSet("-ref", NFILE, fnm), wi); + set_reference_positions(ir->rot, + state.x.rvec_array(), + state.box, + opt2fn("-ref", NFILE, fnm), + opt2bSet("-ref", NFILE, fnm), + wi); } /* reset_multinr(sys); */ diff --git a/src/gromacs/gmxpreprocess/h_db.cpp b/src/gromacs/gmxpreprocess/h_db.cpp index 9092fc8310..14b4528320 100644 --- a/src/gromacs/gmxpreprocess/h_db.cpp +++ b/src/gromacs/gmxpreprocess/h_db.cpp @@ -98,8 +98,11 @@ void read_ab(char* line, const char* fn, MoleculePatch* hack) hack->tp = tp; if ((tp < 1) || (tp >= maxcontrol)) { - gmx_fatal(FARGS, "Error in hdb file %s:\nH-type should be in 1-%d. Offending line:\n%s", fn, - maxcontrol - 1, line); + gmx_fatal(FARGS, + "Error in hdb file %s:\nH-type should be in 1-%d. Offending line:\n%s", + fn, + maxcontrol - 1, + line); } hack->nctl = ns - 3; @@ -108,7 +111,10 @@ void read_ab(char* line, const char* fn, MoleculePatch* hack) gmx_fatal(FARGS, "Error in hdb file %s:\nWrong number of control atoms (%d instead of %d) on " "line:\n%s\n", - fn, hack->nctl, ncontrol[hack->tp], line); + fn, + hack->nctl, + ncontrol[hack->tp], + line); } for (int i = 0; (i < hack->nctl); i++) { @@ -167,7 +173,10 @@ static void read_h_db_file(const char* hfn, std::vector* gmx_fatal(FARGS, "Expected %d lines of hydrogens, found only %d " "while reading Hydrogen Database %s residue %s", - nab, i - 1, block->name.c_str(), hfn); + nab, + i - 1, + block->name.c_str(), + hfn); } if (nullptr == fgets(buf, STRLEN, in)) { @@ -183,13 +192,16 @@ static void read_h_db_file(const char* hfn, std::vector* if (!globalPatches->empty()) { /* Sort the list for searching later */ - std::sort(globalPatches->begin(), globalPatches->end(), + std::sort(globalPatches->begin(), + globalPatches->end(), [](const MoleculePatchDatabase& a1, const MoleculePatchDatabase& a2) { - return std::lexicographical_compare( - a1.name.begin(), a1.name.end(), a2.name.begin(), a2.name.end(), - [](const char& c1, const char& c2) { - return std::toupper(c1) < std::toupper(c2); - }); + return std::lexicographical_compare(a1.name.begin(), + a1.name.end(), + a2.name.begin(), + a2.name.end(), + [](const char& c1, const char& c2) { + return std::toupper(c1) < std::toupper(c2); + }); }); } } @@ -212,7 +224,7 @@ int read_h_db(const char* ffdir, std::vector* globalPatch gmx::ArrayRef::iterator search_h_db(gmx::ArrayRef globalPatches, const char* key) { - return std::find_if( - globalPatches.begin(), globalPatches.end(), - [&key](const MoleculePatchDatabase& a) { return gmx::equalCaseInsensitive(key, a.name); }); + return std::find_if(globalPatches.begin(), globalPatches.end(), [&key](const MoleculePatchDatabase& a) { + return gmx::equalCaseInsensitive(key, a.name); + }); } diff --git a/src/gromacs/gmxpreprocess/insert_molecules.cpp b/src/gromacs/gmxpreprocess/insert_molecules.cpp index 94cde0b968..ef9f9f32b7 100644 --- a/src/gromacs/gmxpreprocess/insert_molecules.cpp +++ b/src/gromacs/gmxpreprocess/insert_molecules.cpp @@ -88,8 +88,9 @@ enum class RotationType : int None, Count }; -static const gmx::EnumerationArray c_rotationTypeNames = { { "xyz", "z", - "none" } }; +static const gmx::EnumerationArray c_rotationTypeNames = { + { "xyz", "z", "none" } +}; static void center_molecule(gmx::ArrayRef x) { @@ -264,8 +265,11 @@ static void insert_mols(int nmol_insrt, // Skip a position if ntry trials were not successful. if (trial >= firstTrial + ntry) { - fprintf(stderr, " skipped position (%.3f, %.3f, %.3f)\n", rpos[XX][mol], - rpos[YY][mol], rpos[ZZ][mol]); + fprintf(stderr, + " skipped position (%.3f, %.3f, %.3f)\n", + rpos[XX][mol], + rpos[YY][mol], + rpos[ZZ][mol]); ++mol; ++failed; firstTrial = trial; @@ -282,11 +286,12 @@ static void insert_mols(int nmol_insrt, generate_trial_conf(x_insrt, offset_x, enum_rot, &rng, &x_n); gmx::AnalysisNeighborhoodPositions pos(*x); gmx::AnalysisNeighborhoodSearch search = nb.initSearch(&pbc, pos); - if (isInsertionAllowed(&search, exclusionDistances, x_n, exclusionDistances_insrt, *atoms, - removableAtoms, &remover)) + if (isInsertionAllowed( + &search, exclusionDistances, x_n, exclusionDistances_insrt, *atoms, removableAtoms, &remover)) { x->insert(x->end(), x_n.begin(), x_n.end()); - exclusionDistances.insert(exclusionDistances.end(), exclusionDistances_insrt.begin(), + exclusionDistances.insert(exclusionDistances.end(), + exclusionDistances_insrt.begin(), exclusionDistances_insrt.end()); builder.mergeAtoms(atoms_insrt); ++mol; @@ -306,7 +311,9 @@ static void insert_mols(int nmol_insrt, remover.removeMarkedAtoms(atoms); if (atoms->nr < originalAtomCount) { - fprintf(stderr, "Replaced %d residues (%d atoms)\n", originalResidueCount - atoms->nres, + fprintf(stderr, + "Replaced %d residues (%d atoms)\n", + originalResidueCount - atoms->nres, originalAtomCount - atoms->nr); } @@ -508,8 +515,8 @@ void InsertMolecules::optionsFinished() bool bTprFileWasRead; rvec* temporaryX = nullptr; fprintf(stderr, "Reading solute configuration\n"); - readConfAndTopology(inputConfFile_.c_str(), &bTprFileWasRead, &top_, &pbcType_, &temporaryX, - nullptr, box_); + readConfAndTopology( + inputConfFile_.c_str(), &bTprFileWasRead, &top_, &pbcType_, &temporaryX, nullptr, box_); x_.assign(temporaryX, temporaryX + top_.natoms); sfree(temporaryX); if (top_.natoms == 0) @@ -563,8 +570,8 @@ int InsertMolecules::run() PbcType pbcType_dummy; matrix box_dummy; rvec* temporaryX; - readConfAndTopology(insertConfFile_.c_str(), &bTprFileWasRead, &topInserted, &pbcType_dummy, - &temporaryX, nullptr, box_dummy); + readConfAndTopology( + insertConfFile_.c_str(), &bTprFileWasRead, &topInserted, &pbcType_dummy, &temporaryX, nullptr, box_dummy); xInserted.assign(temporaryX, temporaryX + topInserted.natoms); sfree(temporaryX); atomsInserted = gmx_mtop_global_atoms(&topInserted); @@ -586,14 +593,27 @@ int InsertMolecules::run() /* add nmol_ins molecules of atoms_ins in random orientation at random place */ - insert_mols(nmolIns_, nmolTry_, seed_, defaultDistance_, scaleFactor_, &atoms, &top_.symtab, - &x_, removableAtoms, atomsInserted, xInserted, pbcTypeForOutput, box_, - positionFile_, deltaR_, enumRot_); + insert_mols(nmolIns_, + nmolTry_, + seed_, + defaultDistance_, + scaleFactor_, + &atoms, + &top_.symtab, + &x_, + removableAtoms, + atomsInserted, + xInserted, + pbcTypeForOutput, + box_, + positionFile_, + deltaR_, + enumRot_); /* write new configuration to file confout */ fprintf(stderr, "Writing generated configuration to %s\n", outputConfFile_.c_str()); - write_sto_conf(outputConfFile_.c_str(), *top_.name, &atoms, as_rvec_array(x_.data()), nullptr, - pbcTypeForOutput, box_); + write_sto_conf( + outputConfFile_.c_str(), *top_.name, &atoms, as_rvec_array(x_.data()), nullptr, pbcTypeForOutput, box_); /* print size of generated configuration */ fprintf(stderr, "\nOutput configuration contains %d atoms in %d residues\n", atoms.nr, atoms.nres); diff --git a/src/gromacs/gmxpreprocess/makeexclusiondistances.cpp b/src/gromacs/gmxpreprocess/makeexclusiondistances.cpp index 3258fc0591..f603524183 100644 --- a/src/gromacs/gmxpreprocess/makeexclusiondistances.cpp +++ b/src/gromacs/gmxpreprocess/makeexclusiondistances.cpp @@ -53,8 +53,10 @@ std::vector makeExclusionDistances(const t_atoms* a, AtomProperties* aps, for (int i = 0; i < a->nr; ++i) { real value; - if (!aps->setAtomProperty(epropVDW, std::string(*(a->resinfo[a->atom[i].resind].name)), - std::string(*(a->atomname[i])), &value)) + if (!aps->setAtomProperty(epropVDW, + std::string(*(a->resinfo[a->atom[i].resind].name)), + std::string(*(a->atomname[i])), + &value)) { value = defaultDistance; } diff --git a/src/gromacs/gmxpreprocess/nm2type.cpp b/src/gromacs/gmxpreprocess/nm2type.cpp index 035daabf2a..e76a357e0a 100644 --- a/src/gromacs/gmxpreprocess/nm2type.cpp +++ b/src/gromacs/gmxpreprocess/nm2type.cpp @@ -151,8 +151,7 @@ void dump_nm2type(FILE* fp, int nnm, t_nm2type nm2t[]) fprintf(fp, "; nm2type database\n"); for (i = 0; (i < nnm); i++) { - fprintf(fp, "%-8s %-8s %8.4f %8.4f %-4d", nm2t[i].elem, nm2t[i].type, nm2t[i].q, nm2t[i].m, - nm2t[i].nbonds); + fprintf(fp, "%-8s %-8s %8.4f %8.4f %-4d", nm2t[i].elem, nm2t[i].type, nm2t[i].q, nm2t[i].m, nm2t[i].nbonds); for (j = 0; (j < nm2t[i].nbonds); j++) { fprintf(fp, " %-5s %6.4f", nm2t[i].bond[j], nm2t[i].blen[j]); @@ -340,8 +339,8 @@ int nm2type(int nnm, { atoms->atom[i].qB = alpha; atoms->atom[i].m = atoms->atom[i].mB = mm; - k = atype->addType(tab, atoms->atom[i], type, InteractionOfType({}, {}), - atoms->atom[i].type, atomnr); + k = atype->addType( + tab, atoms->atom[i], type, InteractionOfType({}, {}), atoms->atom[i].type, atomnr); } atoms->atom[i].type = k; atoms->atom[i].typeB = k; @@ -353,8 +352,11 @@ int nm2type(int nnm, } else { - fprintf(stderr, "Can not find forcefield for atom %s-%d with %d bonds\n", - *atoms->atomname[i], i + 1, nb); + fprintf(stderr, + "Can not find forcefield for atom %s-%d with %d bonds\n", + *atoms->atomname[i], + i + 1, + nb); } } sfree(bbb); diff --git a/src/gromacs/gmxpreprocess/pdb2gmx.cpp b/src/gromacs/gmxpreprocess/pdb2gmx.cpp index 2ee2fa5365..0f23058fa7 100644 --- a/src/gromacs/gmxpreprocess/pdb2gmx.cpp +++ b/src/gromacs/gmxpreprocess/pdb2gmx.cpp @@ -217,8 +217,9 @@ const char* get_argtp(int resnr, gmx::ArrayRef rr) const char* get_histp(int resnr, gmx::ArrayRef rr) { - const char* expl[ehisNR] = { "H on ND1 only", "H on NE2 only", "H on ND1 and NE2", - "Coupled to Heme" }; + const char* expl[ehisNR] = { + "H on ND1 only", "H on NE2 only", "H on ND1 and NE2", "Coupled to Heme" + }; return select_res(ehisNR, resnr, hh, expl, "HISTIDINE", rr); } @@ -251,8 +252,12 @@ void read_rtprename(const char* fname, FILE* fp, std::vector* rtprena { if (nc != 2 && nc != 5) { - gmx_fatal(FARGS, "Residue renaming database '%s' has %d columns instead of %d or %d", - fname, ncol, 2, 5); + gmx_fatal(FARGS, + "Residue renaming database '%s' has %d columns instead of %d or %d", + fname, + ncol, + 2, + 5); } ncol = nc; } @@ -261,7 +266,9 @@ void read_rtprename(const char* fname, FILE* fp, std::vector* rtprena gmx_fatal(FARGS, "A line in residue renaming database '%s' has %d columns, while previous " "lines have %d columns", - fname, nc, ncol); + fname, + nc, + ncol); } if (nc == 2) @@ -307,7 +314,9 @@ std::string search_resrename(gmx::ArrayRef rr, const char* name if (newName[0] == '-') { - gmx_fatal(FARGS, "In the chosen force field there is no residue type for '%s'%s", name, + gmx_fatal(FARGS, + "In the chosen force field there is no residue type for '%s'%s", + name, bStart ? (bEnd ? " as a standalone (starting & ending) residue" : " as a starting terminus") : (bEnd ? " as an ending terminus" : "")); } @@ -365,7 +374,8 @@ void rename_resrtp(t_atoms* pdba, GMX_LOG(logger.info) .asParagraph() .appendTextFormatted("Changing rtp entry of residue %d %s to '%s'", - pdba->resinfo[r].nr, *pdba->resinfo[r].name, + pdba->resinfo[r].nr, + *pdba->resinfo[r].name, newName.c_str()); } pdba->resinfo[r].rtp = put_symtab(symtab, newName.c_str()); @@ -468,7 +478,8 @@ void check_occupancy(t_atoms* atoms, const char* filename, bool bVerbose, const .appendTextFormatted("Occupancy for atom %s%d-%s is %f rather than 1", *atoms->resinfo[atoms->atom[i].resind].name, atoms->resinfo[atoms->atom[i].resind].nr, - *atoms->atomname[i], atoms->pdbinfo[i].occup); + *atoms->atomname[i], + atoms->pdbinfo[i].occup); } if (atoms->pdbinfo[i].occup == 0) { @@ -495,7 +506,9 @@ void check_occupancy(t_atoms* atoms, const char* filename, bool bVerbose, const "there were %d atoms with zero occupancy and %d atoms with " " occupancy unequal to one (out of %d atoms). Check your pdb " "file.", - nzero, nnotone, atoms->nr); + nzero, + nnotone, + atoms->nr); } else { @@ -518,7 +531,11 @@ void write_posres(const char* fn, t_atoms* pdba, real fc) "\n" "[ position_restraints ]\n" "; %4s%6s%8s%8s%8s\n", - "atom", "type", "fx", "fy", "fz"); + "atom", + "type", + "fx", + "fy", + "fz"); for (i = 0; (i < pdba->nr); i++) { if (!is_hydrogen(*pdba->atomname[i]) && !is_dummymass(*pdba->atomname[i])) @@ -731,15 +748,18 @@ void sort_pdbatoms(gmx::ArrayRef restp_chain, atomnm = *pdba->atomname[i]; const PreprocessResidue* localPpResidue = &restp_chain[pdba->atom[i].resind]; auto found = - std::find_if(localPpResidue->atomname.begin(), localPpResidue->atomname.end(), + std::find_if(localPpResidue->atomname.begin(), + localPpResidue->atomname.end(), [&atomnm](char** it) { return gmx::equalCaseInsensitive(atomnm, *it); }); if (found == localPpResidue->atomname.end()) { std::string buf = gmx::formatString( "Atom %s in residue %s %d was not found in rtp entry %s with %d atoms\n" "while sorting atoms.\n%s", - atomnm, *pdba->resinfo[pdba->atom[i].resind].name, - pdba->resinfo[pdba->atom[i].resind].nr, localPpResidue->resname.c_str(), + atomnm, + *pdba->resinfo[pdba->atom[i].resind].name, + pdba->resinfo[pdba->atom[i].resind].nr, + localPpResidue->resname.c_str(), localPpResidue->natom(), is_hydrogen(atomnm) ? "\nFor a hydrogen, this can be a different protonation state, or it\n" @@ -813,7 +833,10 @@ int remove_duplicate_atoms(t_atoms* pdba, gmx::ArrayRef x, bool bVerb GMX_LOG(logger.info) .asParagraph() .appendTextFormatted("deleting duplicate atom %4s %s%4d%c", - *pdba->atomname[i], *ri->name, ri->nr, ri->ic); + *pdba->atomname[i], + *ri->name, + ri->nr, + ri->ic); if (ri->chainid && (ri->chainid != ' ')) { printf(" ch %c", ri->chainid); @@ -888,8 +911,11 @@ void checkResidueTypeSanity(t_atoms* pdba, int r0, int r1, ResidueType* rt) gmx_fatal(FARGS, "The chain covering the range %s--%s does not have a consistent chain ID. " "The first residue has ID '%c', while residue %s has ID '%c'.", - startResidueString.c_str(), endResidueString.c_str(), chainID0, - residueString.c_str(), chainID); + startResidueString.c_str(), + endResidueString.c_str(), + chainID0, + residueString.c_str(), + chainID); } // At this point all residues have the same ID. If they are also non-blank @@ -921,8 +947,11 @@ void checkResidueTypeSanity(t_atoms* pdba, int r0, int r1, ResidueType* rt) "file in the GROMACS library directory. If there are other molecules " "such as ligands, they should not have the same chain ID as the " "adjacent protein chain since it's a separate molecule.", - startResidueString.c_str(), endResidueString.c_str(), restype0.c_str(), - residueString.c_str(), restype.c_str()); + startResidueString.c_str(), + endResidueString.c_str(), + restype0.c_str(), + residueString.c_str(), + restype.c_str()); } } } @@ -968,7 +997,8 @@ void find_nc_ter(t_atoms* pdba, int r0, int r1, int* r_start, int* r_end, Residu GMX_LOG(logger.info) .asParagraph() .appendTextFormatted("Identified residue %s%d as a starting terminus.", - *pdba->resinfo[i].name, pdba->resinfo[i].nr); + *pdba->resinfo[i].name, + pdba->resinfo[i].nr); *r_start = i; } else if (gmx::equalCaseInsensitive(*startrestype, "Ion")) @@ -980,7 +1010,8 @@ void find_nc_ter(t_atoms* pdba, int r0, int r1, int* r_start, int* r_end, Residu .appendTextFormatted( "Residue %s%d has type 'Ion', assuming it is not linked into a " "chain.", - *pdba->resinfo[i].name, pdba->resinfo[i].nr); + *pdba->resinfo[i].name, + pdba->resinfo[i].nr); } if (ionNotes == 4) { @@ -1011,7 +1042,9 @@ void find_nc_ter(t_atoms* pdba, int r0, int r1, int* r_start, int* r_end, Residu "be catastrophic if they should in fact be linked. Please " "check your structure, " "and add %s to residuetypes.dat if this was not correct.", - *pdba->resinfo[i].name, pdba->resinfo[i].nr, *pdba->resinfo[i].name); + *pdba->resinfo[i].name, + pdba->resinfo[i].nr, + *pdba->resinfo[i].name); } else { @@ -1026,7 +1059,8 @@ void find_nc_ter(t_atoms* pdba, int r0, int r1, int* r_start, int* r_end, Residu "and add all " "necessary residue names to residuetypes.dat if this was not " "correct.", - *pdba->resinfo[i].name, pdba->resinfo[i].nr); + *pdba->resinfo[i].name, + pdba->resinfo[i].nr); } } if (startWarnings == 4) @@ -1065,7 +1099,8 @@ void find_nc_ter(t_atoms* pdba, int r0, int r1, int* r_start, int* r_end, Residu .appendTextFormatted( "Residue %s%d has type 'Ion', assuming it is not linked into a " "chain.", - *pdba->resinfo[i].name, pdba->resinfo[i].nr); + *pdba->resinfo[i].name, + pdba->resinfo[i].nr); } if (ionNotes == 4) { @@ -1098,9 +1133,13 @@ void find_nc_ter(t_atoms* pdba, int r0, int r1, int* r_start, int* r_end, Residu "linked. Please check your structure, and add %s to " "residuetypes.dat " "if this was not correct.", - *pdba->resinfo[i].name, pdba->resinfo[i].nr, restype->c_str(), - *pdba->resinfo[*r_start].name, pdba->resinfo[*r_start].nr, - startrestype->c_str(), *pdba->resinfo[i].name); + *pdba->resinfo[i].name, + pdba->resinfo[i].nr, + restype->c_str(), + *pdba->resinfo[*r_start].name, + pdba->resinfo[*r_start].nr, + startrestype->c_str(), + *pdba->resinfo[i].name); } if (endWarnings == 4) { @@ -1120,7 +1159,8 @@ void find_nc_ter(t_atoms* pdba, int r0, int r1, int* r_start, int* r_end, Residu GMX_LOG(logger.info) .asParagraph() .appendTextFormatted("Identified residue %s%d as a ending terminus.", - *pdba->resinfo[*r_end].name, pdba->resinfo[*r_end].nr); + *pdba->resinfo[*r_end].name, + pdba->resinfo[*r_end].nr); } } @@ -1236,9 +1276,16 @@ void modify_chain_numbers(t_atoms* pdba, ChainSeparationType chainSeparation, co "Split the chain (and introduce termini) between residue %s%d (chain id '%c', atom %d %s)\ " "and residue %s%d (chain id '%c', atom %d %s) ? [n/y]", - prev_resname, prev_resnum, prev_chainid, prev_atomnum, - prev_atomname, this_resname, this_resnum, this_chainid, - this_atomnum, this_atomname); + prev_resname, + prev_resnum, + prev_chainid, + prev_atomnum, + prev_atomname, + this_resname, + this_resnum, + this_chainid, + this_atomnum, + this_atomname); if (nullptr == fgets(select, STRLEN - 1, stdin)) { @@ -1378,8 +1425,9 @@ enum class VSitesType : int Aromatics, Count }; -const gmx::EnumerationArray c_vsitesTypeNames = { { "none", "hydrogens", - "aromatics" } }; +const gmx::EnumerationArray c_vsitesTypeNames = { + { "none", "hydrogens", "aromatics" } +}; enum class WaterType : int { @@ -1404,8 +1452,9 @@ enum class MergeType : int Interactive, Count }; -const gmx::EnumerationArray c_mergeTypeNames = { { "no", "all", - "interactive" } }; +const gmx::EnumerationArray c_mergeTypeNames = { + { "no", "all", "interactive" } +}; } // namespace @@ -1789,8 +1838,12 @@ void pdb2gmx::optionsFinished() } /* Force field selection, interactive or direct */ - choose_ff(strcmp(ff_.c_str(), "select") == 0 ? nullptr : ff_.c_str(), forcefield_, - sizeof(forcefield_), ffdir_, sizeof(ffdir_), loggerOwner_->logger()); + choose_ff(strcmp(ff_.c_str(), "select") == 0 ? nullptr : ff_.c_str(), + forcefield_, + sizeof(forcefield_), + ffdir_, + sizeof(ffdir_), + loggerOwner_->logger()); if (strlen(forcefield_) > 0) { @@ -1903,8 +1956,20 @@ int pdb2gmx::run() PbcType pbcType; t_atoms pdba_all; rvec* pdbx; - int natom = read_pdball(inputConfFile_.c_str(), bOutputSet_, outFile_.c_str(), &title, &pdba_all, - &pdbx, &pbcType, box, bRemoveH_, &symtab, &rt, watres, &aps, bVerbose_); + int natom = read_pdball(inputConfFile_.c_str(), + bOutputSet_, + outFile_.c_str(), + &title, + &pdba_all, + &pdbx, + &pbcType, + box, + bRemoveH_, + &symtab, + &rt, + watres, + &aps, + bVerbose_); if (natom == 0) { @@ -1978,9 +2043,16 @@ int pdb2gmx::run() "%s) and chain starting with " "residue %s%d (chain id '%c', atom %d %s) into a single " "moleculetype (keeping termini)? [n/y]", - prev_resname, prev_resnum, prev_chainid, prev_atomnum, - prev_atomname, this_resname, this_resnum, this_chainid, - this_atomnum, this_atomname); + prev_resname, + prev_resnum, + prev_chainid, + prev_atomnum, + prev_atomname, + this_resname, + this_resnum, + this_chainid, + this_atomnum, + this_atomname); if (nullptr == fgets(select, STRLEN - 1, stdin)) { @@ -2135,7 +2207,10 @@ int pdb2gmx::run() .appendTextFormatted( "There are %d chains and %d blocks of water and " "%d residues with %d atoms", - numChains - nwaterchain, nwaterchain, pdba_all.nres, natom); + numChains - nwaterchain, + nwaterchain, + pdba_all.nres, + natom); GMX_LOG(logger.info) .asParagraph() @@ -2144,9 +2219,12 @@ int pdb2gmx::run() { GMX_LOG(logger.info) .asParagraph() - .appendTextFormatted(" %d '%c' %5d %6d %s\n", i + 1, - chains[i].chainid ? chains[i].chainid : '-', chains[i].pdba->nres, - chains[i].pdba->nr, chains[i].bAllWat ? "(only water)" : ""); + .appendTextFormatted(" %d '%c' %5d %6d %s\n", + i + 1, + chains[i].chainid ? chains[i].chainid : '-', + chains[i].pdba->nres, + chains[i].pdba->nr, + chains[i].bAllWat ? "(only water)" : ""); } check_occupancy(&pdba_all, inputConfFile_.c_str(), bVerbose_, logger); @@ -2207,29 +2285,45 @@ int pdb2gmx::run() GMX_LOG(logger.info) .asParagraph() .appendTextFormatted("Processing chain %d '%c' (%d atoms, %d residues)", - chain + 1, cc->chainid, natom, nres); + chain + 1, + cc->chainid, + natom, + nres); } else { GMX_LOG(logger.info) .asParagraph() - .appendTextFormatted("Processing chain %d (%d atoms, %d residues)", chain + 1, - natom, nres); - } - - process_chain(pdba, x, bUnA_, bUnA_, bUnA_, bLysMan_, bAspMan_, bGluMan_, bHisMan_, - bArgMan_, bGlnMan_, angle_, distance_, &symtab, rtprename); + .appendTextFormatted( + "Processing chain %d (%d atoms, %d residues)", chain + 1, natom, nres); + } + + process_chain(pdba, + x, + bUnA_, + bUnA_, + bUnA_, + bLysMan_, + bAspMan_, + bGluMan_, + bHisMan_, + bArgMan_, + bGlnMan_, + angle_, + distance_, + &symtab, + rtprename); cc->chainstart[cc->nterpairs] = pdba->nres; j = 0; for (int i = 0; i < cc->nterpairs; i++) { - find_nc_ter(pdba, cc->chainstart[i], cc->chainstart[i + 1], &(cc->r_start[j]), - &(cc->r_end[j]), &rt, logger); + find_nc_ter( + pdba, cc->chainstart[i], cc->chainstart[i + 1], &(cc->r_start[j]), &(cc->r_end[j]), &rt, logger); if (cc->r_start[j] >= 0 && cc->r_end[j] >= 0) { - if (checkChainCyclicity(pdba, pdbx, cc->r_start[j], cc->r_end[j], rtpFFDB, - rtprename, long_bond_dist_, short_bond_dist_)) + if (checkChainCyclicity( + pdba, pdbx, cc->r_start[j], cc->r_end[j], rtpFFDB, rtprename, long_bond_dist_, short_bond_dist_)) { cc->cyclicBondsIndex.push_back(cc->r_start[j]); cc->cyclicBondsIndex.push_back(cc->r_end[j]); @@ -2288,8 +2382,10 @@ int pdb2gmx::run() { if (bTerMan_ && !tdblist.empty()) { - sprintf(select, "Select start terminus type for %s-%d", - *pdba->resinfo[cc->r_start[i]].name, pdba->resinfo[cc->r_start[i]].nr); + sprintf(select, + "Select start terminus type for %s-%d", + *pdba->resinfo[cc->r_start[i]].name, + pdba->resinfo[cc->r_start[i]].nr); cc->ntdb.push_back(choose_ter(tdblist, select)); } else @@ -2297,8 +2393,10 @@ int pdb2gmx::run() cc->ntdb.push_back(tdblist[0]); } - printf("Start terminus %s-%d: %s\n", *pdba->resinfo[cc->r_start[i]].name, - pdba->resinfo[cc->r_start[i]].nr, (cc->ntdb[i])->name.c_str()); + printf("Start terminus %s-%d: %s\n", + *pdba->resinfo[cc->r_start[i]].name, + pdba->resinfo[cc->r_start[i]].nr, + (cc->ntdb[i])->name.c_str()); tdblist.clear(); } } @@ -2326,16 +2424,20 @@ int pdb2gmx::run() { if (bTerMan_ && !tdblist.empty()) { - sprintf(select, "Select end terminus type for %s-%d", - *pdba->resinfo[cc->r_end[i]].name, pdba->resinfo[cc->r_end[i]].nr); + sprintf(select, + "Select end terminus type for %s-%d", + *pdba->resinfo[cc->r_end[i]].name, + pdba->resinfo[cc->r_end[i]].nr); cc->ctdb.push_back(choose_ter(tdblist, select)); } else { cc->ctdb.push_back(tdblist[0]); } - printf("End terminus %s-%d: %s\n", *pdba->resinfo[cc->r_end[i]].name, - pdba->resinfo[cc->r_end[i]].nr, (cc->ctdb[i])->name.c_str()); + printf("End terminus %s-%d: %s\n", + *pdba->resinfo[cc->r_end[i]].name, + pdba->resinfo[cc->r_end[i]].nr, + (cc->ctdb[i])->name.c_str()); tdblist.clear(); } } @@ -2347,8 +2449,19 @@ int pdb2gmx::run() std::vector hb_chain; /* lookup hackblocks and rtp for all residues */ std::vector restp_chain; - get_hackblocks_rtp(&hb_chain, &restp_chain, rtpFFDB, pdba->nres, pdba->resinfo, cc->nterpairs, - &symtab, cc->ntdb, cc->ctdb, cc->r_start, cc->r_end, bAllowMissing_, logger); + get_hackblocks_rtp(&hb_chain, + &restp_chain, + rtpFFDB, + pdba->nres, + pdba->resinfo, + cc->nterpairs, + &symtab, + cc->ntdb, + cc->ctdb, + cc->r_start, + cc->r_end, + bAllowMissing_, + logger); /* ideally, now we would not need the rtp itself anymore, but do everything using the hb and restp arrays. Unfortunately, that requires some re-thinking of code in gen_vsite.c, which I won't @@ -2400,8 +2513,18 @@ int pdb2gmx::run() .asParagraph() .appendTextFormatted( "Generating any missing hydrogen atoms and/or adding termini."); - add_h(&pdba, &localAtoms[chain], &x, ah, &symtab, cc->nterpairs, cc->ntdb, cc->ctdb, - cc->r_start, cc->r_end, bAllowMissing_, cc->cyclicBondsIndex); + add_h(&pdba, + &localAtoms[chain], + &x, + ah, + &symtab, + cc->nterpairs, + cc->ntdb, + cc->ctdb, + cc->r_start, + cc->r_end, + bAllowMissing_, + cc->cyclicBondsIndex); GMX_LOG(logger.info) .asParagraph() .appendTextFormatted("Now there are %d residues with %d atoms", pdba->nres, pdba->nr); @@ -2514,10 +2637,31 @@ int pdb2gmx::run() top_file2 = top_file; } - pdb2top(top_file2, posre_fn.c_str(), molname.c_str(), pdba, &x, &atype, &symtab, rtpFFDB, - restp_chain, hb_chain, bAllowMissing_, bVsites_, bVsiteAromatics_, ffdir_, mHmult_, - ssbonds, long_bond_dist_, short_bond_dist_, bDeuterate_, bChargeGroups_, bCmap_, - bRenumRes_, bRTPresname_, cc->cyclicBondsIndex, logger); + pdb2top(top_file2, + posre_fn.c_str(), + molname.c_str(), + pdba, + &x, + &atype, + &symtab, + rtpFFDB, + restp_chain, + hb_chain, + bAllowMissing_, + bVsites_, + bVsiteAromatics_, + ffdir_, + mHmult_, + ssbonds, + long_bond_dist_, + short_bond_dist_, + bDeuterate_, + bChargeGroups_, + bCmap_, + bRenumRes_, + bRTPresname_, + cc->cyclicBondsIndex, + logger); if (!cc->bAllWat) { @@ -2557,7 +2701,8 @@ int pdb2gmx::run() "The topology file '%s' for the selected water " "model '%s' can not be found in the force field " "directory. Select a different water model.", - waterFile.c_str(), watermodel_); + waterFile.c_str(), + watermodel_); GMX_THROW(InconsistentInputError(message)); } } @@ -2592,7 +2737,9 @@ int pdb2gmx::run() GMX_LOG(logger.info) .asParagraph() .appendTextFormatted("Including chain %d in system: %d atoms %d residues", - i + 1, chains[i].pdba->nr, chains[i].pdba->nres); + i + 1, + chains[i].pdba->nr, + chains[i].pdba->nres); } for (int j = 0; (j < chains[i].pdba->nr); j++) { @@ -2630,8 +2777,8 @@ int pdb2gmx::run() { make_new_box(atoms->nr, gmx::as_rvec_array(x.data()), box, box_space, false); } - write_sto_conf(outputConfFile_.c_str(), title, atoms, gmx::as_rvec_array(x.data()), nullptr, - pbcType, box); + write_sto_conf( + outputConfFile_.c_str(), title, atoms, gmx::as_rvec_array(x.data()), nullptr, pbcType, box); done_symtab(&symtab); done_atom(&pdba_all); @@ -2658,8 +2805,8 @@ int pdb2gmx::run() { GMX_LOG(logger.info) .asParagraph() - .appendTextFormatted("The %s force field and the %s water model are used.", ffname_, - watermodel_); + .appendTextFormatted( + "The %s force field and the %s water model are used.", ffname_, watermodel_); sfree(watermodel_); } else diff --git a/src/gromacs/gmxpreprocess/pdb2top.cpp b/src/gromacs/gmxpreprocess/pdb2top.cpp index 351168fdc1..1199f4f15c 100644 --- a/src/gromacs/gmxpreprocess/pdb2top.cpp +++ b/src/gromacs/gmxpreprocess/pdb2top.cpp @@ -104,7 +104,9 @@ static int missing_atoms(const PreprocessResidue* rp, int resind, t_atoms* at, i GMX_LOG(logger.warning) .asParagraph() .appendTextFormatted("atom %s is missing in residue %s %d in the pdb file", - name, *(at->resinfo[resind].name), at->resinfo[resind].nr); + name, + *(at->resinfo[resind].name), + at->resinfo[resind].nr); if (name[0] == 'H' || name[0] == 'h') { GMX_LOG(logger.warning) @@ -113,7 +115,9 @@ static int missing_atoms(const PreprocessResidue* rp, int resind, t_atoms* at, i "You might need to add atom %s to the hydrogen database of " "building block %s " "in the file %s.hdb (see the manual)", - name, *(at->resinfo[resind].rtp), rp->filebase.c_str()); + name, + *(at->resinfo[resind].rtp), + rp->filebase.c_str()); } } } @@ -197,7 +201,8 @@ static void choose_ff_impl(const char* ffsel, "Force field '%s' occurs in %d places. pdb2gmx is using the one in " "the current directory. Use interactive selection " "(not the -ff option) if you would prefer a different one.", - ffsel, nfound); + ffsel, + nfound); } else { @@ -206,7 +211,8 @@ static void choose_ff_impl(const char* ffsel, "the current directory.\n" "Run without the -ff switch and select the force " "field interactively.", - ffsel, nfound); + ffsel, + nfound); GMX_THROW(gmx::InconsistentInputError(message)); } } @@ -315,7 +321,8 @@ static void choose_ff_impl(const char* ffsel, "to point to the desired force field first, and/or " "rename or move the force field directory present " "in the current working directory.", - ffs[sel].c_str(), fflib_forcefield_dir_ext()); + ffs[sel].c_str(), + fflib_forcefield_dir_ext()); GMX_THROW(gmx::NotImplementedError(message)); } } @@ -328,7 +335,8 @@ static void choose_ff_impl(const char* ffsel, if (ffs[sel].length() >= static_cast(ff_maxlen)) { std::string message = gmx::formatString("Length of force field name (%d) >= maxlen (%d)", - static_cast(ffs[sel].length()), ff_maxlen); + static_cast(ffs[sel].length()), + ff_maxlen); GMX_THROW(gmx::InvalidInputError(message)); } strcpy(forcefield, ffs[sel].c_str()); @@ -345,7 +353,8 @@ static void choose_ff_impl(const char* ffsel, if (ffpath.length() >= static_cast(ffdir_maxlen)) { std::string message = gmx::formatString("Length of force field dir (%d) >= maxlen (%d)", - static_cast(ffpath.length()), ffdir_maxlen); + static_cast(ffpath.length()), + ffdir_maxlen); GMX_THROW(gmx::InvalidInputError(message)); } strcpy(ffdir, ffpath.c_str()); @@ -743,8 +752,10 @@ static void do_ssbonds(InteractionsOfType* ps, int aj = search_res_atom(bond.secondAtom.c_str(), rj, atoms, "special bond", bAllowMissing); if ((ai == -1) || (aj == -1)) { - gmx_fatal(FARGS, "Trying to make impossible special bond (%s-%s)!", - bond.firstAtom.c_str(), bond.secondAtom.c_str()); + gmx_fatal(FARGS, + "Trying to make impossible special bond (%s-%s)!", + bond.firstAtom.c_str(), + bond.secondAtom.c_str()); } add_param(ps, ai, aj, {}, nullptr); } @@ -795,15 +806,15 @@ static void at2bonds(InteractionsOfType* psb, { GMX_LOG(logger.warning) .asParagraph() - .appendTextFormatted("Long Bond (%d-%d = %g nm)", ai + 1, aj + 1, - std::sqrt(dist2)); + .appendTextFormatted( + "Long Bond (%d-%d = %g nm)", ai + 1, aj + 1, std::sqrt(dist2)); } else if (dist2 < short_bond_dist2) { GMX_LOG(logger.warning) .asParagraph() - .appendTextFormatted("Short Bond (%d-%d = %g nm)", ai + 1, aj + 1, - std::sqrt(dist2)); + .appendTextFormatted( + "Short Bond (%d-%d = %g nm)", ai + 1, aj + 1, std::sqrt(dist2)); } add_param(psb, ai, aj, {}, patch.s.c_str()); } @@ -923,12 +934,15 @@ static void check_restp_type(const char* name, int t1, int t2) static void check_restp_types(const PreprocessResidue& r0, const PreprocessResidue& r1) { - check_restp_type("all dihedrals", static_cast(r0.bKeepAllGeneratedDihedrals), + check_restp_type("all dihedrals", + static_cast(r0.bKeepAllGeneratedDihedrals), static_cast(r1.bKeepAllGeneratedDihedrals)); check_restp_type("nrexcl", r0.nrexcl, r1.nrexcl); - check_restp_type("HH14", static_cast(r0.bGenerateHH14Interactions), + check_restp_type("HH14", + static_cast(r0.bGenerateHH14Interactions), static_cast(r1.bGenerateHH14Interactions)); - check_restp_type("remove dihedrals", static_cast(r0.bRemoveDihedralIfWithImproper), + check_restp_type("remove dihedrals", + static_cast(r0.bRemoveDihedralIfWithImproper), static_cast(r1.bRemoveDihedralIfWithImproper)); for (int i = 0; i < ebtsNR; i++) @@ -1084,11 +1098,11 @@ void get_hackblocks_rtp(std::vector* globalPatches, if (patch->nr != 0) { /* find atom in restp */ - auto found = std::find_if(posres->atomname.begin(), posres->atomname.end(), - [&patch](char** name) { - return (patch->oname.empty() && patch->a[0] == *name) - || (patch->oname == *name); - }); + auto found = std::find_if( + posres->atomname.begin(), posres->atomname.end(), [&patch](char** name) { + return (patch->oname.empty() && patch->a[0] == *name) + || (patch->oname == *name); + }); if (found == posres->atomname.end()) { @@ -1105,7 +1119,8 @@ void get_hackblocks_rtp(std::vector* globalPatches, "atom %s not found in buiding block %d%s " "while combining tdb and rtp", patch->oname.empty() ? patch->a[0].c_str() : patch->oname.c_str(), - pos + 1, *resinfo[pos].rtp); + pos + 1, + *resinfo[pos].rtp); } } else @@ -1221,7 +1236,8 @@ static bool match_atomnames_with_rtp_atom(t_atoms* pdba, /* This atom still has the old name, rename it */ std::string newnm = patch->nname; auto found = std::find_if( - localPpResidue->atomname.begin(), localPpResidue->atomname.end(), + localPpResidue->atomname.begin(), + localPpResidue->atomname.end(), [&newnm](char** name) { return gmx::equalCaseInsensitive(newnm, *name); }); if (found == localPpResidue->atomname.end()) { @@ -1234,7 +1250,8 @@ static bool match_atomnames_with_rtp_atom(t_atoms* pdba, */ bool bFoundInAdd = false; for (auto rtpModification = singlePatch.hack.begin(); - rtpModification != singlePatch.hack.end(); rtpModification++) + rtpModification != singlePatch.hack.end(); + rtpModification++) { int k = std::distance(localPpResidue->atomname.begin(), found); std::string start_at; @@ -1247,23 +1264,26 @@ static bool match_atomnames_with_rtp_atom(t_atoms* pdba, } else { - start_at = gmx::formatString("%s%d", singlePatch.hack[k].nname.c_str(), - anmnr - 1); + start_at = gmx::formatString( + "%s%d", singlePatch.hack[k].nname.c_str(), anmnr - 1); } - auto found2 = - std::find_if(localPpResidue->atomname.begin(), - localPpResidue->atomname.end(), [&start_at](char** name) { - return gmx::equalCaseInsensitive(start_at, *name); - }); + auto found2 = std::find_if(localPpResidue->atomname.begin(), + localPpResidue->atomname.end(), + [&start_at](char** name) { + return gmx::equalCaseInsensitive(start_at, *name); + }); if (found2 == localPpResidue->atomname.end()) { gmx_fatal(FARGS, "Could not find atom '%s' in residue building block '%s' to " "add atom '%s' to", - start_at.c_str(), localPpResidue->resname.c_str(), newnm.c_str()); + start_at.c_str(), + localPpResidue->resname.c_str(), + newnm.c_str()); } /* We can add the atom after atom start_nr */ - add_atom_to_restp(localPpResidue, symtab, + add_atom_to_restp(localPpResidue, + symtab, std::distance(localPpResidue->atomname.begin(), found2), &(*patch)); @@ -1277,7 +1297,9 @@ static bool match_atomnames_with_rtp_atom(t_atoms* pdba, "Could not find an 'add' entry for atom named '%s' corresponding to " "the 'replace' entry from atom name '%s' to '%s' for tdb or hdb " "database of residue type '%s'", - newnm.c_str(), patch->oname.c_str(), patch->nname.c_str(), + newnm.c_str(), + patch->oname.c_str(), + patch->nname.c_str(), localPpResidue->resname.c_str()); } } @@ -1286,8 +1308,11 @@ static bool match_atomnames_with_rtp_atom(t_atoms* pdba, { GMX_LOG(logger.info) .asParagraph() - .appendTextFormatted("Renaming atom '%s' in residue '%s' %d to '%s'", oldnm, - localPpResidue->resname.c_str(), resnr, newnm.c_str()); + .appendTextFormatted("Renaming atom '%s' in residue '%s' %d to '%s'", + oldnm, + localPpResidue->resname.c_str(), + resnr, + newnm.c_str()); } /* Rename the atom in pdba */ pdba->atomname[atind] = put_symtab(symtab, newnm.c_str()); @@ -1299,7 +1324,8 @@ static bool match_atomnames_with_rtp_atom(t_atoms* pdba, * in the rtp entry of this residue. */ auto found3 = std::find_if( - localPpResidue->atomname.begin(), localPpResidue->atomname.end(), + localPpResidue->atomname.begin(), + localPpResidue->atomname.end(), [&oldnm](char** name) { return gmx::equalCaseInsensitive(oldnm, *name); }); if (found3 == localPpResidue->atomname.end()) { @@ -1310,8 +1336,10 @@ static bool match_atomnames_with_rtp_atom(t_atoms* pdba, { GMX_LOG(logger.info) .asParagraph() - .appendTextFormatted("Deleting atom '%s' in residue '%s' %d", oldnm, - localPpResidue->resname.c_str(), resnr); + .appendTextFormatted("Deleting atom '%s' in residue '%s' %d", + oldnm, + localPpResidue->resname.c_str(), + resnr); } /* We should free the atom name, * but it might be used multiple times in the symtab. @@ -1345,13 +1373,14 @@ void match_atomnames_with_rtp(gmx::ArrayRef usedPpResidue const char* oldnm = *pdba->atomname[i]; PreprocessResidue* localPpResidue = &usedPpResidues[pdba->atom[i].resind]; auto found = std::find_if( - localPpResidue->atomname.begin(), localPpResidue->atomname.end(), - [&oldnm](char** name) { return gmx::equalCaseInsensitive(oldnm, *name); }); + localPpResidue->atomname.begin(), localPpResidue->atomname.end(), [&oldnm](char** name) { + return gmx::equalCaseInsensitive(oldnm, *name); + }); if (found == localPpResidue->atomname.end()) { /* Not found yet, check if we have to rename this atom */ - if (match_atomnames_with_rtp_atom(pdba, x, symtab, i, localPpResidue, - globalPatches[pdba->atom[i].resind], bVerbose, logger)) + if (match_atomnames_with_rtp_atom( + pdba, x, symtab, i, localPpResidue, globalPatches[pdba->atom[i].resind], bVerbose, logger)) { /* We deleted this atom, decrease the atom counter by 1. */ i--; @@ -1451,8 +1480,13 @@ static void gen_cmap(InteractionsOfType* psb, if (bAddCMAP) { - add_cmap_param(psb, cmap_atomid[0], cmap_atomid[1], cmap_atomid[2], cmap_atomid[3], - cmap_atomid[4], b.s.c_str()); + add_cmap_param(psb, + cmap_atomid[0], + cmap_atomid[1], + cmap_atomid[2], + cmap_atomid[3], + cmap_atomid[4], + b.s.c_str()); } } @@ -1514,8 +1548,7 @@ void pdb2top(FILE* top_file, ResidueType rt; /* Make bonds */ - at2bonds(&(plist[F_BONDS]), globalPatches, atoms, *x, long_bond_dist, short_bond_dist, - cyclicBondsIndex, logger); + at2bonds(&(plist[F_BONDS]), globalPatches, atoms, *x, long_bond_dist, short_bond_dist, cyclicBondsIndex, logger); /* specbonds: disulphide bonds & heme-his */ do_ssbonds(&(plist[F_BONDS]), atoms, ssbonds, bAllowMissing); @@ -1534,7 +1567,8 @@ void pdb2top(FILE* top_file, gmx_fatal(FARGS, "There were %d missing atoms in molecule %s, if you want to use this " "incomplete topology anyhow, use the option -missing", - nmissat, molname); + nmissat, + molname); } } @@ -1595,8 +1629,11 @@ void pdb2top(FILE* top_file, .appendTextFormatted( "There are %4zu dihedrals, %4zu impropers, %4zu angles\n" " %4zu pairs, %4zu bonds and %4zu virtual sites", - plist[F_PDIHS].size(), plist[F_IDIHS].size(), plist[F_ANGLES].size(), - plist[F_LJ14].size(), plist[F_BONDS].size(), + plist[F_PDIHS].size(), + plist[F_IDIHS].size(), + plist[F_ANGLES].size(), + plist[F_LJ14].size(), + plist[F_BONDS].size(), plist[F_VSITE2].size() + plist[F_VSITE3].size() + plist[F_VSITE3FD].size() + plist[F_VSITE3FAD].size() + plist[F_VSITE3OUT].size() + plist[F_VSITE4FD].size() + plist[F_VSITE4FDN].size()); @@ -1627,7 +1664,16 @@ void pdb2top(FILE* top_file, { bts[i] = usedPpResidues[0].rb[i].type; } - write_top(top_file, posre_fn, molname, atoms, bRTPresname, bts, plist, excls, atype, cgnr, + write_top(top_file, + posre_fn, + molname, + atoms, + bRTPresname, + bts, + plist, + excls, + atype, + cgnr, usedPpResidues[0].nrexcl); } diff --git a/src/gromacs/gmxpreprocess/pgutil.cpp b/src/gromacs/gmxpreprocess/pgutil.cpp index c9387601d5..1c0afb4d8e 100644 --- a/src/gromacs/gmxpreprocess/pgutil.cpp +++ b/src/gromacs/gmxpreprocess/pgutil.cpp @@ -65,22 +65,29 @@ static void atom_not_found(int fatal_errno, { if (0 != strcmp(bondtype, "atom")) { - snprintf(message_buffer, 1024, + snprintf(message_buffer, + 1024, "Residue %d named %s of a molecule in the input file was mapped\n" "to an entry in the topology database, but the atom %s used in\n" "an interaction of type %s in that entry is not found in the\n" "input file. Perhaps your atom and/or residue naming needs to be\n" "fixed.\n", - resind + 1, resname, atomname, bondtype); + resind + 1, + resname, + atomname, + bondtype); } else { - snprintf(message_buffer, 1024, + snprintf(message_buffer, + 1024, "Residue %d named %s of a molecule in the input file was mapped\n" "to an entry in the topology database, but the atom %s used in\n" "that entry is not found in the input file. Perhaps your atom\n" "and/or residue naming needs to be fixed.\n", - resind + 1, resname, atomname); + resind + 1, + resname, + atomname); } if (bAllowMissing) { @@ -148,8 +155,7 @@ int search_atom(const char* type, } if (!(bNext && at[start].resind == at[natoms - 1].resind)) { - atom_not_found(FARGS, type, at[start].resind, *atoms->resinfo[resind].name, bondtype, - bAllowMissing); + atom_not_found(FARGS, type, at[start].resind, *atoms->resinfo[resind].name, bondtype, bAllowMissing); } } else @@ -188,8 +194,7 @@ int search_atom(const char* type, } if (start > 0) { - atom_not_found(FARGS, type, at[start].resind, *atoms->resinfo[resind].name, bondtype, - bAllowMissing); + atom_not_found(FARGS, type, at[start].resind, *atoms->resinfo[resind].name, bondtype, bAllowMissing); } } return -1; diff --git a/src/gromacs/gmxpreprocess/readir.cpp b/src/gromacs/gmxpreprocess/readir.cpp index cdb0ef93cd..5456e16f63 100644 --- a/src/gromacs/gmxpreprocess/readir.cpp +++ b/src/gromacs/gmxpreprocess/readir.cpp @@ -336,15 +336,19 @@ void check_ir(const char* mdparin, sprintf(warn_buf, "Replacing vdwtype=%s by the equivalent combination of vdwtype=%s and " "vdw_modifier=%s", - evdw_names[ir->vdwtype], evdw_names[evdwCUT], eintmod_names[ir->vdw_modifier]); + evdw_names[ir->vdwtype], + evdw_names[evdwCUT], + eintmod_names[ir->vdw_modifier]); warning_note(wi, warn_buf); ir->vdwtype = evdwCUT; } else { - sprintf(warn_buf, "Unsupported combination of vdwtype=%s and vdw_modifier=%s", - evdw_names[ir->vdwtype], eintmod_names[ir->vdw_modifier]); + sprintf(warn_buf, + "Unsupported combination of vdwtype=%s and vdw_modifier=%s", + evdw_names[ir->vdwtype], + eintmod_names[ir->vdw_modifier]); warning_error(wi, warn_buf); } } @@ -369,7 +373,8 @@ void check_ir(const char* mdparin, if (EEL_USER(ir->coulombtype)) { - sprintf(warn_buf, "Coulomb type %s is not supported with the verlet scheme", + sprintf(warn_buf, + "Coulomb type %s is not supported with the verlet scheme", eel_names[ir->coulombtype]); warning_error(wi, warn_buf); } @@ -468,14 +473,17 @@ void check_ir(const char* mdparin, "Setting tcoupl from '%s' to 'no'. %s handles temperature coupling " "implicitly. See the documentation for more information on which " "parameters affect temperature for %s.", - etcoupl_names[ir->etc], ei_names[ir->eI], ei_names[ir->eI]); + etcoupl_names[ir->etc], + ei_names[ir->eI], + ei_names[ir->eI]); } else { sprintf(warn_buf, "Setting tcoupl from '%s' to 'no'. Temperature coupling does not apply to " "%s.", - etcoupl_names[ir->etc], ei_names[ir->eI]); + etcoupl_names[ir->etc], + ei_names[ir->eI]); } warning_note(wi, warn_buf); } @@ -486,7 +494,9 @@ void check_ir(const char* mdparin, sprintf(warn_buf, "Integrator method %s is implemented primarily for validation purposes; for " "molecular dynamics, you should probably be using %s or %s", - ei_names[eiVVAK], ei_names[eiMD], ei_names[eiVV]); + ei_names[eiVVAK], + ei_names[eiMD], + ei_names[eiVV]); warning_note(wi, warn_buf); } if (!EI_DYNAMICS(ir->eI)) @@ -495,7 +505,8 @@ void check_ir(const char* mdparin, { sprintf(warn_buf, "Setting pcoupl from '%s' to 'no'. Pressure coupling does not apply to %s.", - epcoupl_names[ir->epc], ei_names[ir->eI]); + epcoupl_names[ir->epc], + ei_names[ir->eI]); warning_note(wi, warn_buf); } ir->epc = epcNO; @@ -538,8 +549,7 @@ void check_ir(const char* mdparin, min_name = nstdh; } /* If the user sets nstenergy small, we should respect that */ - sprintf(warn_buf, "Setting nstcalcenergy (%d) equal to %s (%d)", ir->nstcalcenergy, - min_name, min_nst); + sprintf(warn_buf, "Setting nstcalcenergy (%d) equal to %s (%d)", ir->nstcalcenergy, min_name, min_nst); warning_note(wi, warn_buf); ir->nstcalcenergy = min_nst; } @@ -568,8 +578,7 @@ void check_ir(const char* mdparin, if (ir->bExpanded) { /* nstexpanded should be a multiple of nstcalcenergy */ - check_nst("nstcalcenergy", ir->nstcalcenergy, "nstexpanded", - &ir->expandedvals->nstexpanded, wi); + check_nst("nstcalcenergy", ir->nstcalcenergy, "nstexpanded", &ir->expandedvals->nstexpanded, wi); } /* for storing exact averages nstenergy should be * a multiple of nstcalcenergy @@ -636,8 +645,11 @@ void check_ir(const char* mdparin, bool bAllTempZero = TRUE; for (i = 0; i < fep->n_lambda; i++) { - sprintf(err_buf, "Entry %d for %s must be between 0 and 1, instead is %g", i, - efpt_names[efptTEMPERATURE], fep->all_lambda[efptTEMPERATURE][i]); + sprintf(err_buf, + "Entry %d for %s must be between 0 and 1, instead is %g", + i, + efpt_names[efptTEMPERATURE], + fep->all_lambda[efptTEMPERATURE][i]); CHECK((fep->all_lambda[efptTEMPERATURE][i] < 0) || (fep->all_lambda[efptTEMPERATURE][i] > 1)); if (fep->all_lambda[efptTEMPERATURE][i] > 0) { @@ -666,14 +678,17 @@ void check_ir(const char* mdparin, sprintf(err_buf, "Higher simulated tempering temperature (%g) must be >= than the simulated " "tempering lower temperature (%g)", - ir->simtempvals->simtemp_high, ir->simtempvals->simtemp_low); + ir->simtempvals->simtemp_high, + ir->simtempvals->simtemp_low); CHECK(ir->simtempvals->simtemp_high <= ir->simtempvals->simtemp_low); - sprintf(err_buf, "Higher simulated tempering temperature (%g) must be >= zero", + sprintf(err_buf, + "Higher simulated tempering temperature (%g) must be >= zero", ir->simtempvals->simtemp_high); CHECK(ir->simtempvals->simtemp_high <= 0); - sprintf(err_buf, "Lower simulated tempering temperature (%g) must be >= zero", + sprintf(err_buf, + "Lower simulated tempering temperature (%g) must be >= zero", ir->simtempvals->simtemp_low); CHECK(ir->simtempvals->simtemp_low <= 0); } @@ -698,7 +713,8 @@ void check_ir(const char* mdparin, fep->delta_lambda); CHECK(fep->delta_lambda > 0 && ((fep->init_fep_state > 0) || (fep->init_lambda > 0))); - sprintf(err_buf, "Can't use positive delta-lambda (%g) with expanded ensemble simulations", + sprintf(err_buf, + "Can't use positive delta-lambda (%g) with expanded ensemble simulations", fep->delta_lambda); CHECK(fep->delta_lambda > 0 && (ir->efep == efepEXPANDED)); @@ -712,14 +728,15 @@ void check_ir(const char* mdparin, if (fep->n_lambda == 0) { /* Clear output in case of no states:*/ - sprintf(err_buf, "init-lambda-state set to %d: no lambda states are defined.", - fep->init_fep_state); + sprintf(err_buf, "init-lambda-state set to %d: no lambda states are defined.", fep->init_fep_state); CHECK((fep->init_fep_state >= 0) && (fep->n_lambda == 0)); } else { - sprintf(err_buf, "initial thermodynamic state %d does not exist, only goes to %d", - fep->init_fep_state, fep->n_lambda - 1); + sprintf(err_buf, + "initial thermodynamic state %d does not exist, only goes to %d", + fep->init_fep_state, + fep->n_lambda - 1); CHECK((fep->init_fep_state >= fep->n_lambda)); } @@ -730,7 +747,8 @@ void check_ir(const char* mdparin, sprintf(err_buf, "init-lambda=%g while init-lambda-state=%d. Lambda state must be set either with " "init-lambda-state or with init-lambda, but not both", - fep->init_lambda, fep->init_fep_state); + fep->init_lambda, + fep->init_fep_state); CHECK((fep->init_fep_state >= 0) && (fep->init_lambda >= 0)); @@ -766,8 +784,11 @@ void check_ir(const char* mdparin, { for (i = 0; i < fep->n_lambda; i++) { - sprintf(err_buf, "Entry %d for %s must be between 0 and 1, instead is %g", i, - efpt_names[j], fep->all_lambda[j][i]); + sprintf(err_buf, + "Entry %d for %s must be between 0 and 1, instead is %g", + i, + efpt_names[j], + fep->all_lambda[j][i]); CHECK((fep->all_lambda[j][i] < 0) || (fep->all_lambda[j][i] > 1)); } } @@ -780,7 +801,9 @@ void check_ir(const char* mdparin, "For state %d, vdw-lambdas (%f) is changing with vdw softcore, while " "coul-lambdas (%f) is nonzero without coulomb softcore: this will lead to " "crashes, and is not supported.", - i, fep->all_lambda[efptVDW][i], fep->all_lambda[efptCOUL][i]); + i, + fep->all_lambda[efptVDW][i], + fep->all_lambda[efptCOUL][i]); CHECK((fep->sc_alpha > 0) && (((fep->all_lambda[efptCOUL][i] > 0.0) && (fep->all_lambda[efptCOUL][i] < 1.0)) && ((fep->all_lambda[efptVDW][i] > 0.0) && (fep->all_lambda[efptVDW][i] < 1.0)))); @@ -802,7 +825,11 @@ void check_ir(const char* mdparin, "energy conservation, but usually other effects dominate. With a common sigma " "value of %g nm the fraction of the particle-particle potential at the cut-off " "at lambda=%g is around %.1e, while ewald-rtol is %.1e.", - fep->sc_r_power, sigma, lambda, r_sc - 1.0, ir->ewald_rtol); + fep->sc_r_power, + sigma, + lambda, + r_sc - 1.0, + ir->ewald_rtol); warning_note(wi, warn_buf); } @@ -828,57 +855,72 @@ void check_ir(const char* mdparin, sprintf(err_buf, "weight-equil-number-all-lambda (%d) is ignored if lmc-weights-equil is not equal " "to %s", - expand->equil_n_at_lam, elmceq_names[elmceqNUMATLAM]); + expand->equil_n_at_lam, + elmceq_names[elmceqNUMATLAM]); CHECK((expand->equil_n_at_lam > 0) && (expand->elmceq != elmceqNUMATLAM)); sprintf(err_buf, "weight-equil-number-samples (%d) is ignored if lmc-weights-equil is not equal to " "%s", - expand->equil_samples, elmceq_names[elmceqSAMPLES]); + expand->equil_samples, + elmceq_names[elmceqSAMPLES]); CHECK((expand->equil_samples > 0) && (expand->elmceq != elmceqSAMPLES)); sprintf(err_buf, "weight-equil-number-steps (%d) is ignored if lmc-weights-equil is not equal to %s", - expand->equil_steps, elmceq_names[elmceqSTEPS]); + expand->equil_steps, + elmceq_names[elmceqSTEPS]); CHECK((expand->equil_steps > 0) && (expand->elmceq != elmceqSTEPS)); sprintf(err_buf, "weight-equil-wl-delta (%d) is ignored if lmc-weights-equil is not equal to %s", - expand->equil_samples, elmceq_names[elmceqWLDELTA]); + expand->equil_samples, + elmceq_names[elmceqWLDELTA]); CHECK((expand->equil_wl_delta > 0) && (expand->elmceq != elmceqWLDELTA)); sprintf(err_buf, "weight-equil-count-ratio (%f) is ignored if lmc-weights-equil is not equal to %s", - expand->equil_ratio, elmceq_names[elmceqRATIO]); + expand->equil_ratio, + elmceq_names[elmceqRATIO]); CHECK((expand->equil_ratio > 0) && (expand->elmceq != elmceqRATIO)); sprintf(err_buf, "weight-equil-number-all-lambda (%d) must be a positive integer if " "lmc-weights-equil=%s", - expand->equil_n_at_lam, elmceq_names[elmceqNUMATLAM]); + expand->equil_n_at_lam, + elmceq_names[elmceqNUMATLAM]); CHECK((expand->equil_n_at_lam <= 0) && (expand->elmceq == elmceqNUMATLAM)); sprintf(err_buf, "weight-equil-number-samples (%d) must be a positive integer if " "lmc-weights-equil=%s", - expand->equil_samples, elmceq_names[elmceqSAMPLES]); + expand->equil_samples, + elmceq_names[elmceqSAMPLES]); CHECK((expand->equil_samples <= 0) && (expand->elmceq == elmceqSAMPLES)); sprintf(err_buf, "weight-equil-number-steps (%d) must be a positive integer if lmc-weights-equil=%s", - expand->equil_steps, elmceq_names[elmceqSTEPS]); + expand->equil_steps, + elmceq_names[elmceqSTEPS]); CHECK((expand->equil_steps <= 0) && (expand->elmceq == elmceqSTEPS)); - sprintf(err_buf, "weight-equil-wl-delta (%f) must be > 0 if lmc-weights-equil=%s", - expand->equil_wl_delta, elmceq_names[elmceqWLDELTA]); + sprintf(err_buf, + "weight-equil-wl-delta (%f) must be > 0 if lmc-weights-equil=%s", + expand->equil_wl_delta, + elmceq_names[elmceqWLDELTA]); CHECK((expand->equil_wl_delta <= 0) && (expand->elmceq == elmceqWLDELTA)); - sprintf(err_buf, "weight-equil-count-ratio (%f) must be > 0 if lmc-weights-equil=%s", - expand->equil_ratio, elmceq_names[elmceqRATIO]); + sprintf(err_buf, + "weight-equil-count-ratio (%f) must be > 0 if lmc-weights-equil=%s", + expand->equil_ratio, + elmceq_names[elmceqRATIO]); CHECK((expand->equil_ratio <= 0) && (expand->elmceq == elmceqRATIO)); - sprintf(err_buf, "lmc-weights-equil=%s only possible when lmc-stats = %s or lmc-stats %s", - elmceq_names[elmceqWLDELTA], elamstats_names[elamstatsWL], elamstats_names[elamstatsWWL]); + sprintf(err_buf, + "lmc-weights-equil=%s only possible when lmc-stats = %s or lmc-stats %s", + elmceq_names[elmceqWLDELTA], + elamstats_names[elamstatsWL], + elamstats_names[elamstatsWWL]); CHECK((expand->elmceq == elmceqWLDELTA) && (!EWL(expand->elamstats))); sprintf(err_buf, "lmc-repeats (%d) must be greater than 0", expand->lmc_repeats); @@ -890,12 +932,14 @@ void check_ir(const char* mdparin, sprintf(err_buf, "init-lambda-state (%d) must be zero if lmc-forced-nstart (%d)> 0 and lmc-move != " "'no'", - fep->init_fep_state, expand->lmc_forced_nstart); + fep->init_fep_state, + expand->lmc_forced_nstart); CHECK((fep->init_fep_state != 0) && (expand->lmc_forced_nstart > 0) && (expand->elmcmove != elmcmoveNO)); sprintf(err_buf, "lmc-forced-nstart (%d) must not be negative", expand->lmc_forced_nstart); CHECK((expand->lmc_forced_nstart < 0)); - sprintf(err_buf, "init-lambda-state (%d) must be in the interval [0,number of lambdas)", + sprintf(err_buf, + "init-lambda-state (%d) must be in the interval [0,number of lambdas)", fep->init_fep_state); CHECK((fep->init_fep_state < 0) || (fep->init_fep_state >= fep->n_lambda)); @@ -924,7 +968,8 @@ void check_ir(const char* mdparin, { sprintf(err_buf, "nst-transition-matrix (%d) must be an integer multiple of nstlog (%d)", - expand->nstTij, ir->nstlog); + expand->nstTij, + ir->nstlog); CHECK((expand->nstTij % ir->nstlog) != 0); } } @@ -947,14 +992,16 @@ void check_ir(const char* mdparin, } else { - sprintf(err_buf, "Can not have pressure coupling with pbc=%s", + sprintf(err_buf, + "Can not have pressure coupling with pbc=%s", c_pbcTypeNames[ir->pbcType].c_str()); CHECK(ir->epc != epcNO); } sprintf(err_buf, "Can not have Ewald with pbc=%s", c_pbcTypeNames[ir->pbcType].c_str()); CHECK(EEL_FULL(ir->coulombtype)); - sprintf(err_buf, "Can not have dispersion correction with pbc=%s", + sprintf(err_buf, + "Can not have dispersion correction with pbc=%s", c_pbcTypeNames[ir->pbcType].c_str()); CHECK(ir->eDispCorr != edispcNO); } @@ -966,7 +1013,9 @@ void check_ir(const char* mdparin, "with coulombtype = %s or coulombtype = %s\n" "without periodic boundary conditions (pbc = %s) and\n" "rcoulomb and rvdw set to zero", - eel_names[eelCUT], eel_names[eelUSER], c_pbcTypeNames[PbcType::No].c_str()); + eel_names[eelCUT], + eel_names[eelUSER], + c_pbcTypeNames[PbcType::No].c_str()); CHECK(((ir->coulombtype != eelCUT) && (ir->coulombtype != eelUSER)) || (ir->pbcType != PbcType::No) || (ir->rcoulomb != 0.0) || (ir->rvdw != 0.0)); @@ -1079,8 +1128,10 @@ void check_ir(const char* mdparin, if (ETC_ANDERSEN(ir->etc)) { - sprintf(err_buf, "%s temperature control not supported for integrator %s.", - etcoupl_names[ir->etc], ei_names[ir->eI]); + sprintf(err_buf, + "%s temperature control not supported for integrator %s.", + etcoupl_names[ir->etc], + ei_names[ir->eI]); CHECK(!(EI_VV(ir->eI))); if (ir->nstcomm > 0 && (ir->etc == etcANDERSEN)) @@ -1096,7 +1147,8 @@ void check_ir(const char* mdparin, sprintf(err_buf, "nstcomm must be 1, not %d for %s, as velocities of atoms in coupled groups are " "randomized every time step", - ir->nstcomm, etcoupl_names[ir->etc]); + ir->nstcomm, + etcoupl_names[ir->etc]); CHECK(ir->nstcomm > 1 && (ir->etc == etcANDERSEN)); } @@ -1105,7 +1157,8 @@ void check_ir(const char* mdparin, sprintf(warn_buf, "The %s thermostat does not generate the correct kinetic energy distribution. You " "might want to consider using the %s thermostat.", - ETCOUPLTYPE(ir->etc), ETCOUPLTYPE(etcVRESCALE)); + ETCOUPLTYPE(ir->etc), + ETCOUPLTYPE(etcVRESCALE)); warning_note(wi, warn_buf); } @@ -1138,7 +1191,10 @@ void check_ir(const char* mdparin, sprintf(warn_buf, "For proper integration of the %s barostat, tau-p (%g) should be at least %d " "times larger than nstpcouple*dt (%g)", - EPCOUPLTYPE(ir->epc), ir->tau_p, pcouple_min_integration_steps(ir->epc), dt_pcoupl); + EPCOUPLTYPE(ir->epc), + ir->tau_p, + pcouple_min_integration_steps(ir->epc), + dt_pcoupl); warning(wi, warn_buf); } @@ -1181,7 +1237,8 @@ void check_ir(const char* mdparin, sprintf(warn_buf, "coulombtype = %s is only for testing purposes and can lead to serious " "artifacts, advice: use coulombtype = %s", - eel_names[ir->coulombtype], eel_names[eelRF_ZERO]); + eel_names[ir->coulombtype], + eel_names[eelRF_ZERO]); warning(wi, warn_buf); } @@ -1229,7 +1286,8 @@ void check_ir(const char* mdparin, CHECK((ir->epsilon_rf < ir->epsilon_r && ir->epsilon_rf != 0) || (ir->epsilon_r == 0)); if (ir->epsilon_rf == ir->epsilon_r) { - sprintf(warn_buf, "Using epsilon-rf = epsilon-r with %s does not make sense", + sprintf(warn_buf, + "Using epsilon-rf = epsilon-r with %s does not make sense", eel_names[ir->coulombtype]); warning(wi, warn_buf); } @@ -1284,7 +1342,10 @@ void check_ir(const char* mdparin, "The switching range should be 5%% or less (currently %.2f%% using a switching " "range of %4f-%4f) for accurate electrostatic energies, energy conservation " "will be good regardless, since ewald_rtol = %g.", - percentage, ir->rcoulomb_switch, ir->rcoulomb, ir->ewald_rtol); + percentage, + ir->rcoulomb_switch, + ir->rcoulomb, + ir->ewald_rtol); warning(wi, warn_buf); } } @@ -1307,8 +1368,7 @@ void check_ir(const char* mdparin, if (ir->coulombtype == eelPMESWITCH || ir->coulombtype == eelPMEUSER || ir->coulombtype == eelPMEUSERSWITCH) { - sprintf(err_buf, "With coulombtype = %s, rcoulomb must be <= rlist", - eel_names[ir->coulombtype]); + sprintf(err_buf, "With coulombtype = %s, rcoulomb must be <= rlist", eel_names[ir->coulombtype]); CHECK(ir->rcoulomb > ir->rlist); } } @@ -1321,8 +1381,11 @@ void check_ir(const char* mdparin, if (ir->pme_order < orderMin || ir->pme_order > orderMax) { - sprintf(warn_buf, "With coulombtype = %s, you should have %d <= pme-order <= %d", - eel_names[ir->coulombtype], orderMin, orderMax); + sprintf(warn_buf, + "With coulombtype = %s, you should have %d <= pme-order <= %d", + eel_names[ir->coulombtype], + orderMin, + orderMax); warning_error(wi, warn_buf); } } @@ -1331,8 +1394,10 @@ void check_ir(const char* mdparin, { if (ir->ewald_geometry == eewg3D) { - sprintf(warn_buf, "With pbc=%s you should use ewald-geometry=%s", - c_pbcTypeNames[ir->pbcType].c_str(), eewg_names[eewg3DC]); + sprintf(warn_buf, + "With pbc=%s you should use ewald-geometry=%s", + c_pbcTypeNames[ir->pbcType].c_str(), + eewg_names[eewg3DC]); warning(wi, warn_buf); } /* This check avoids extra pbc coding for exclusion corrections */ @@ -1341,8 +1406,11 @@ void check_ir(const char* mdparin, } if ((ir->ewald_geometry == eewg3DC) && (ir->pbcType != PbcType::XY) && EEL_FULL(ir->coulombtype)) { - sprintf(warn_buf, "With %s and ewald_geometry = %s you should use pbc = %s", - eel_names[ir->coulombtype], eewg_names[eewg3DC], c_pbcTypeNames[PbcType::XY].c_str()); + sprintf(warn_buf, + "With %s and ewald_geometry = %s you should use pbc = %s", + eel_names[ir->coulombtype], + eewg_names[eewg3DC], + c_pbcTypeNames[PbcType::XY].c_str()); warning(wi, warn_buf); } if ((ir->epsilon_surface != 0) && EEL_FULL(ir->coulombtype)) @@ -1369,7 +1437,8 @@ void check_ir(const char* mdparin, "You are applying a switch function to vdw forces or potentials from %g to %g " "nm, which is more than half the interaction range, whereas switch functions " "are intended to act only close to the cut-off.", - ir->rvdw_switch, ir->rvdw); + ir->rvdw_switch, + ir->rvdw); warning_note(wi, warn_buf); } } @@ -1378,8 +1447,11 @@ void check_ir(const char* mdparin, { if (!(ir->vdw_modifier == eintmodNONE || ir->vdw_modifier == eintmodPOTSHIFT)) { - sprintf(err_buf, "With vdwtype = %s, the only supported modifiers are %s and %s", - evdw_names[ir->vdwtype], eintmod_names[eintmodPOTSHIFT], eintmod_names[eintmodNONE]); + sprintf(err_buf, + "With vdwtype = %s, the only supported modifiers are %s and %s", + evdw_names[ir->vdwtype], + eintmod_names[eintmodPOTSHIFT], + eintmod_names[eintmodNONE]); warning_error(wi, err_buf); } } @@ -1440,8 +1512,9 @@ static void parse_n_real(char* str, int* n, real** r, warninp_t wi) } catch (gmx::GromacsException&) { - warning_error(wi, "Invalid value " + values[i] - + " in string in mdp file. Expected a real number."); + warning_error(wi, + "Invalid value " + values[i] + + " in string in mdp file. Expected a real number."); } } } @@ -1499,7 +1572,9 @@ static void do_fep_params(t_inputrec* ir, char fep_lambda[][STRLEN], char weight gmx_fatal(FARGS, "Number of lambdas (%d) for FEP type %s not equal to number of other types " "(%d)", - nfep[i], efpt_names[i], max_n_lambda); + nfep[i], + efpt_names[i], + max_n_lambda); } } /* we don't print out dhdl if the temperature is changing, since we can't correctly define dhdl in this case */ @@ -1589,8 +1664,10 @@ static void do_fep_params(t_inputrec* ir, char fep_lambda[][STRLEN], char weight } else if (nweights != fep->n_lambda) { - gmx_fatal(FARGS, "Number of weights (%d) is not equal to number of lambda values (%d)", - nweights, fep->n_lambda); + gmx_fatal(FARGS, + "Number of weights (%d) is not equal to number of lambda values (%d)", + nweights, + fep->n_lambda); } if ((expand->nstexpanded < 0) && (ir->efep != efepNO)) { @@ -1622,7 +1699,8 @@ void convertInts(warninp_t wi, gmx::ArrayRef inputs, const ch auto message = gmx::formatString( "Invalid value for mdp option %s. %s should only consist of integers separated " "by spaces.", - name, name); + name, + name); warning_error(wi, message); } ++i; @@ -1643,7 +1721,8 @@ static void convertReals(warninp_t wi, gmx::ArrayRef inputs, auto message = gmx::formatString( "Invalid value for mdp option %s. %s should only consist of real numbers " "separated by spaces.", - name, name); + name, + name); warning_error(wi, message); } ++i; @@ -1664,7 +1743,8 @@ static void convertRvecs(warninp_t wi, gmx::ArrayRef inputs, auto message = gmx::formatString( "Invalid value for mdp option %s. %s should only consist of real numbers " "separated by spaces.", - name, name); + name, + name); warning_error(wi, message); } ++d; @@ -1691,7 +1771,9 @@ static void do_wall_params(t_inputrec* ir, char* wall_atomtype, char* wall_densi auto wallAtomTypes = gmx::splitString(wall_atomtype); if (wallAtomTypes.size() != size_t(ir->nwall)) { - gmx_fatal(FARGS, "Expected %d elements for wall_atomtype, found %zu", ir->nwall, + gmx_fatal(FARGS, + "Expected %d elements for wall_atomtype, found %zu", + ir->nwall, wallAtomTypes.size()); } GMX_RELEASE_ASSERT(ir->nwall < 3, "Invalid number of walls"); @@ -1705,7 +1787,9 @@ static void do_wall_params(t_inputrec* ir, char* wall_atomtype, char* wall_densi auto wallDensity = gmx::splitString(wall_density); if (wallDensity.size() != size_t(ir->nwall)) { - gmx_fatal(FARGS, "Expected %d elements for wall-density, found %zu", ir->nwall, + gmx_fatal(FARGS, + "Expected %d elements for wall-density, found %zu", + ir->nwall, wallDensity.size()); } convertReals(wi, wallDensity, "wall-density", ir->wall_density); @@ -1909,8 +1993,8 @@ void get_ir(const char* mdparin, gmx::GromppMtsOpts& mtsOpts = opts->mtsOpts; mtsOpts.numLevels = get_eint(&inp, "mts-levels", 2, wi); ir->mtsLevels.resize(2); - mtsOpts.level2Forces = setStringEntry(&inp, "mts-level2-forces", - "longrange-nonbonded nonbonded pair dihedral"); + mtsOpts.level2Forces = setStringEntry( + &inp, "mts-level2-forces", "longrange-nonbonded nonbonded pair dihedral"); mtsOpts.level2Factor = get_eint(&inp, "mts-level2-factor", 2, wi); // We clear after reading without dynamics to not force the user to remove MTS mdp options @@ -1998,8 +2082,7 @@ void get_ir(const char* mdparin, printStringNoNewline(&inp, "cut-off lengths"); ir->rcoulomb_switch = get_ereal(&inp, "rcoulomb-switch", 0.0, wi); ir->rcoulomb = get_ereal(&inp, "rcoulomb", 1.0, wi); - printStringNoNewline(&inp, - "Relative dielectric constant for the medium and the reaction field"); + printStringNoNewline(&inp, "Relative dielectric constant for the medium and the reaction field"); ir->epsilon_r = get_ereal(&inp, "epsilon-r", 1.0, wi); ir->epsilon_rf = get_ereal(&inp, "epsilon-rf", 0.0, wi); printStringNoNewline(&inp, "Method for doing Van der Waals"); @@ -2437,8 +2520,14 @@ void get_ir(const char* mdparin, dumdub[m][YY] = dumdub[m][XX]; break; case epctANISOTROPIC: - if (sscanf(dumstr[m], "%lf%lf%lf%lf%lf%lf", &(dumdub[m][XX]), &(dumdub[m][YY]), - &(dumdub[m][ZZ]), &(dumdub[m][3]), &(dumdub[m][4]), &(dumdub[m][5])) + if (sscanf(dumstr[m], + "%lf%lf%lf%lf%lf%lf", + &(dumdub[m][XX]), + &(dumdub[m][YY]), + &(dumdub[m][ZZ]), + &(dumdub[m][3]), + &(dumdub[m][4]), + &(dumdub[m][5])) != 6) { warning_error( @@ -2447,7 +2536,8 @@ void get_ir(const char* mdparin, } break; default: - gmx_fatal(FARGS, "Pressure coupling type %s not implemented yet", + gmx_fatal(FARGS, + "Pressure coupling type %s not implemented yet", epcoupltype_names[ir->epct]); } } @@ -2598,9 +2688,15 @@ void get_ir(const char* mdparin, } double gmx_unused canary; - int ndeform = sscanf(inputrecStrings->deform, "%lf %lf %lf %lf %lf %lf %lf", &(dumdub[0][0]), - &(dumdub[0][1]), &(dumdub[0][2]), &(dumdub[0][3]), &(dumdub[0][4]), - &(dumdub[0][5]), &canary); + int ndeform = sscanf(inputrecStrings->deform, + "%lf %lf %lf %lf %lf %lf %lf", + &(dumdub[0][0]), + &(dumdub[0][1]), + &(dumdub[0][2]), + &(dumdub[0][3]), + &(dumdub[0][4]), + &(dumdub[0][5]), + &canary); if (strlen(inputrecStrings->deform) > 0 && ndeform != 6) { @@ -2763,8 +2859,7 @@ static void do_numbering(int natoms, ognr = cbuf[aj]; if (ognr != NOGID) { - gmx_fatal(FARGS, "Atom %d in multiple %s groups (%d and %d)", aj + 1, title, - ognr + 1, i + 1); + gmx_fatal(FARGS, "Atom %d in multiple %s groups (%d and %d)", aj + 1, title, ognr + 1, i + 1); } else { @@ -2806,8 +2901,7 @@ static void do_numbering(int natoms, { if (bVerbose) { - fprintf(stderr, "Making dummy/rest group for %s containing %d elements\n", title, - natoms - ntot); + fprintf(stderr, "Making dummy/rest group for %s containing %d elements\n", title, natoms - ntot); } /* Add group name "rest" */ grps->emplace_back(restnm); @@ -2877,7 +2971,8 @@ static void calc_nrdf(const gmx_mtop_t* mtop, t_inputrec* ir, char** gnames) nrdf_tc[i] = 0; } for (gmx::index i = 0; - i < gmx::ssize(groups.groups[SimulationAtomGroupType::MassCenterVelocityRemoval]) + 1; i++) + i < gmx::ssize(groups.groups[SimulationAtomGroupType::MassCenterVelocityRemoval]) + 1; + i++) { nrdf_vcm[i] = 0; clear_ivec(dof_vcm[i]); @@ -3052,7 +3147,8 @@ static void calc_nrdf(const gmx_mtop_t* mtop, t_inputrec* ir, char** gnames) * Note that we do not and should not include the rest group here. */ for (gmx::index j = 0; - j < gmx::ssize(groups.groups[SimulationAtomGroupType::MassCenterVelocityRemoval]); j++) + j < gmx::ssize(groups.groups[SimulationAtomGroupType::MassCenterVelocityRemoval]); + j++) { switch (ir->comm_mode) { @@ -3073,11 +3169,13 @@ static void calc_nrdf(const gmx_mtop_t* mtop, t_inputrec* ir, char** gnames) } for (gmx::index i = 0; - i < gmx::ssize(groups.groups[SimulationAtomGroupType::TemperatureCoupling]); i++) + i < gmx::ssize(groups.groups[SimulationAtomGroupType::TemperatureCoupling]); + i++) { /* Count the number of atoms of TC group i for every VCM group */ for (gmx::index j = 0; - j < gmx::ssize(groups.groups[SimulationAtomGroupType::MassCenterVelocityRemoval]) + 1; j++) + j < gmx::ssize(groups.groups[SimulationAtomGroupType::MassCenterVelocityRemoval]) + 1; + j++) { na_vcm[j] = 0; } @@ -3096,7 +3194,8 @@ static void calc_nrdf(const gmx_mtop_t* mtop, t_inputrec* ir, char** gnames) nrdf_uc = nrdf_tc[i]; nrdf_tc[i] = 0; for (gmx::index j = 0; - j < gmx::ssize(groups.groups[SimulationAtomGroupType::MassCenterVelocityRemoval]) + 1; j++) + j < gmx::ssize(groups.groups[SimulationAtomGroupType::MassCenterVelocityRemoval]) + 1; + j++) { if (nrdf_vcm[j] > nrdf_vcm_sub[j]) { @@ -3113,8 +3212,10 @@ static void calc_nrdf(const gmx_mtop_t* mtop, t_inputrec* ir, char** gnames) { opts->nrdf[i] = 0; } - fprintf(stderr, "Number of degrees of freedom in T-Coupling group %s is %.2f\n", - gnames[groups.groups[SimulationAtomGroupType::TemperatureCoupling][i]], opts->nrdf[i]); + fprintf(stderr, + "Number of degrees of freedom in T-Coupling group %s is %.2f\n", + gnames[groups.groups[SimulationAtomGroupType::TemperatureCoupling][i]], + opts->nrdf[i]); } sfree(nrdf2); @@ -3202,8 +3303,11 @@ static void make_swap_groups(t_swapcoords* swap, t_blocka* grps, char** gnames) if (swapg->nat > 0) { - fprintf(stderr, "%s group '%s' contains %d atoms.\n", - ig < 3 ? eSwapFixedGrp_names[ig] : "Swap", swap->grp[ig].molname, swapg->nat); + fprintf(stderr, + "%s group '%s' contains %d atoms.\n", + ig < 3 ? eSwapFixedGrp_names[ig] : "Swap", + swap->grp[ig].molname, + swapg->nat); snew(swapg->ind, swapg->nat); for (i = 0; i < swapg->nat; i++) { @@ -3231,7 +3335,8 @@ static void make_IMD_group(t_IMD* IMDgroup, char* IMDgname, t_blocka* grps, char fprintf(stderr, "Group '%s' with %d atoms can be activated for interactive molecular dynamics " "(IMD).\n", - IMDgname, IMDgroup->nat); + IMDgname, + IMDgroup->nat); snew(IMDgroup->ind, IMDgroup->nat); for (i = 0; i < IMDgroup->nat; i++) { @@ -3309,7 +3414,8 @@ static void checkAndUpdateVcmFreezeGroupConsistency(SimulationGroups* groups, "removal group(s), due to limitations in the code these still contribute to the " "mass of the COM along frozen dimensions and therefore the COMM correction will be " "too small.", - numPartiallyFrozenVcmAtoms, DIM); + numPartiallyFrozenVcmAtoms, + DIM); warning(wi, warningText.c_str()); } if (numNonVcmAtoms > 0) @@ -3386,14 +3492,22 @@ void do_index(const char* mdparin, gmx_fatal(FARGS, "Invalid T coupling input: %zu groups, %zu ref-t values and " "%zu tau-t values", - temperatureCouplingGroupNames.size(), temperatureCouplingReferenceValues.size(), + temperatureCouplingGroupNames.size(), + temperatureCouplingReferenceValues.size(), temperatureCouplingTauValues.size()); } const bool useReferenceTemperature = integratorHasReferenceTemperature(ir); - do_numbering(natoms, groups, temperatureCouplingGroupNames, defaultIndexGroups, gnames, - SimulationAtomGroupType::TemperatureCoupling, restnm, - useReferenceTemperature ? egrptpALL : egrptpALL_GENREST, bVerbose, wi); + do_numbering(natoms, + groups, + temperatureCouplingGroupNames, + defaultIndexGroups, + gnames, + SimulationAtomGroupType::TemperatureCoupling, + restnm, + useReferenceTemperature ? egrptpALL : egrptpALL_GENREST, + bVerbose, + wi); nr = groups->groups[SimulationAtomGroupType::TemperatureCoupling].size(); ir->opts.ngtc = nr; snew(ir->opts.nrdf, nr); @@ -3495,7 +3609,10 @@ void do_index(const char* mdparin, sprintf(warn_buf, "For proper integration of the %s thermostat, tau-t (%g) should be at " "least %d times larger than nsttcouple*dt (%g)", - ETCOUPLTYPE(ir->etc), tau_min, nstcmin, ir->nsttcouple * ir->delta_t); + ETCOUPLTYPE(ir->etc), + tau_min, + nstcmin, + ir->nsttcouple * ir->delta_t); warning(wi, warn_buf); } } @@ -3524,8 +3641,10 @@ void do_index(const char* mdparin, } if (!simulatedAnnealingGroupNames.empty() && gmx::ssize(simulatedAnnealingGroupNames) != nr) { - gmx_fatal(FARGS, "Wrong number of annealing values: %zu (for %d groups)\n", - simulatedAnnealingGroupNames.size(), nr); + gmx_fatal(FARGS, + "Wrong number of annealing values: %zu (for %d groups)\n", + simulatedAnnealingGroupNames.size(), + nr); } else { @@ -3566,8 +3685,10 @@ void do_index(const char* mdparin, auto simulatedAnnealingPoints = gmx::splitString(inputrecStrings->anneal_npoints); if (simulatedAnnealingPoints.size() != simulatedAnnealingGroupNames.size()) { - gmx_fatal(FARGS, "Found %zu annealing-npoints values for %zu groups\n", - simulatedAnnealingPoints.size(), simulatedAnnealingGroupNames.size()); + gmx_fatal(FARGS, + "Found %zu annealing-npoints values for %zu groups\n", + simulatedAnnealingPoints.size(), + simulatedAnnealingGroupNames.size()); } convertInts(wi, simulatedAnnealingPoints, "annealing points", ir->opts.anneal_npoints); size_t numSimulatedAnnealingFields = 0; @@ -3588,21 +3709,26 @@ void do_index(const char* mdparin, if (simulatedAnnealingTimes.size() != numSimulatedAnnealingFields) { - gmx_fatal(FARGS, "Found %zu annealing-time values, wanted %zu\n", - simulatedAnnealingTimes.size(), numSimulatedAnnealingFields); + gmx_fatal(FARGS, + "Found %zu annealing-time values, wanted %zu\n", + simulatedAnnealingTimes.size(), + numSimulatedAnnealingFields); } auto simulatedAnnealingTemperatures = gmx::splitString(inputrecStrings->anneal_temp); if (simulatedAnnealingTemperatures.size() != numSimulatedAnnealingFields) { - gmx_fatal(FARGS, "Found %zu annealing-temp values, wanted %zu\n", - simulatedAnnealingTemperatures.size(), numSimulatedAnnealingFields); + gmx_fatal(FARGS, + "Found %zu annealing-temp values, wanted %zu\n", + simulatedAnnealingTemperatures.size(), + numSimulatedAnnealingFields); } std::vector allSimulatedAnnealingTimes(numSimulatedAnnealingFields); std::vector allSimulatedAnnealingTemperatures(numSimulatedAnnealingFields); - convertReals(wi, simulatedAnnealingTimes, "anneal-time", - allSimulatedAnnealingTimes.data()); - convertReals(wi, simulatedAnnealingTemperatures, "anneal-temp", + convertReals(wi, simulatedAnnealingTimes, "anneal-time", allSimulatedAnnealingTimes.data()); + convertReals(wi, + simulatedAnnealingTemperatures, + "anneal-temp", allSimulatedAnnealingTemperatures.data()); for (i = 0, k = 0; i < nr; i++) { @@ -3625,12 +3751,14 @@ void do_index(const char* mdparin, gmx_fatal(FARGS, "Annealing timepoints out of order: t=%f comes after " "t=%f\n", - ir->opts.anneal_time[i][j], ir->opts.anneal_time[i][j - 1]); + ir->opts.anneal_time[i][j], + ir->opts.anneal_time[i][j - 1]); } } if (ir->opts.anneal_temp[i][j] < 0) { - gmx_fatal(FARGS, "Found negative temperature in annealing: %f\n", + gmx_fatal(FARGS, + "Found negative temperature in annealing: %f\n", ir->opts.anneal_temp[i][j]); } k++; @@ -3642,14 +3770,18 @@ void do_index(const char* mdparin, if (ir->opts.annealing[i] != eannNO) { j = groups->groups[SimulationAtomGroupType::TemperatureCoupling][i]; - fprintf(stderr, "Simulated annealing for group %s: %s, %d timepoints\n", - *(groups->groupNames[j]), eann_names[ir->opts.annealing[i]], + fprintf(stderr, + "Simulated annealing for group %s: %s, %d timepoints\n", + *(groups->groupNames[j]), + eann_names[ir->opts.annealing[i]], ir->opts.anneal_npoints[i]); fprintf(stderr, "Time (ps) Temperature (K)\n"); /* All terms except the last one */ for (j = 0; j < (ir->opts.anneal_npoints[i] - 1); j++) { - fprintf(stderr, "%9.1f %5.1f\n", ir->opts.anneal_time[i][j], + fprintf(stderr, + "%9.1f %5.1f\n", + ir->opts.anneal_time[i][j], ir->opts.anneal_temp[i][j]); } @@ -3657,12 +3789,16 @@ void do_index(const char* mdparin, j = ir->opts.anneal_npoints[i] - 1; if (ir->opts.annealing[i] == eannSINGLE) { - fprintf(stderr, "%9.1f- %5.1f\n", ir->opts.anneal_time[i][j], + fprintf(stderr, + "%9.1f- %5.1f\n", + ir->opts.anneal_time[i][j], ir->opts.anneal_temp[i][j]); } else { - fprintf(stderr, "%9.1f %5.1f\n", ir->opts.anneal_time[i][j], + fprintf(stderr, + "%9.1f %5.1f\n", + ir->opts.anneal_time[i][j], ir->opts.anneal_temp[i][j]); if (std::fabs(ir->opts.anneal_temp[i][j] - ir->opts.anneal_temp[i][0]) > GMX_REAL_EPS) { @@ -3708,11 +3844,21 @@ void do_index(const char* mdparin, auto accelerationGroupNames = gmx::splitString(inputrecStrings->accgrps); if (accelerationGroupNames.size() * DIM != accelerations.size()) { - gmx_fatal(FARGS, "Invalid Acceleration input: %zu groups and %zu acc. values", - accelerationGroupNames.size(), accelerations.size()); - } - do_numbering(natoms, groups, accelerationGroupNames, defaultIndexGroups, gnames, - SimulationAtomGroupType::Acceleration, restnm, egrptpALL_GENREST, bVerbose, wi); + gmx_fatal(FARGS, + "Invalid Acceleration input: %zu groups and %zu acc. values", + accelerationGroupNames.size(), + accelerations.size()); + } + do_numbering(natoms, + groups, + accelerationGroupNames, + defaultIndexGroups, + gnames, + SimulationAtomGroupType::Acceleration, + restnm, + egrptpALL_GENREST, + bVerbose, + wi); nr = groups->groups[SimulationAtomGroupType::Acceleration].size(); snew(ir->opts.acc, nr); ir->opts.ngacc = nr; @@ -3723,11 +3869,21 @@ void do_index(const char* mdparin, auto freezeGroupNames = gmx::splitString(inputrecStrings->freeze); if (freezeDims.size() != DIM * freezeGroupNames.size()) { - gmx_fatal(FARGS, "Invalid Freezing input: %zu groups and %zu freeze values", - freezeGroupNames.size(), freezeDims.size()); - } - do_numbering(natoms, groups, freezeGroupNames, defaultIndexGroups, gnames, - SimulationAtomGroupType::Freeze, restnm, egrptpALL_GENREST, bVerbose, wi); + gmx_fatal(FARGS, + "Invalid Freezing input: %zu groups and %zu freeze values", + freezeGroupNames.size(), + freezeDims.size()); + } + do_numbering(natoms, + groups, + freezeGroupNames, + defaultIndexGroups, + gnames, + SimulationAtomGroupType::Freeze, + restnm, + egrptpALL_GENREST, + bVerbose, + wi); nr = groups->groups[SimulationAtomGroupType::Freeze].size(); ir->opts.ngfrz = nr; snew(ir->opts.nFreeze, nr); @@ -3758,14 +3914,29 @@ void do_index(const char* mdparin, } auto energyGroupNames = gmx::splitString(inputrecStrings->energy); - do_numbering(natoms, groups, energyGroupNames, defaultIndexGroups, gnames, - SimulationAtomGroupType::EnergyOutput, restnm, egrptpALL_GENREST, bVerbose, wi); + do_numbering(natoms, + groups, + energyGroupNames, + defaultIndexGroups, + gnames, + SimulationAtomGroupType::EnergyOutput, + restnm, + egrptpALL_GENREST, + bVerbose, + wi); add_wall_energrps(groups, ir->nwall, symtab); ir->opts.ngener = groups->groups[SimulationAtomGroupType::EnergyOutput].size(); auto vcmGroupNames = gmx::splitString(inputrecStrings->vcm); - do_numbering(natoms, groups, vcmGroupNames, defaultIndexGroups, gnames, - SimulationAtomGroupType::MassCenterVelocityRemoval, restnm, - vcmGroupNames.empty() ? egrptpALL_GENREST : egrptpPART, bVerbose, wi); + do_numbering(natoms, + groups, + vcmGroupNames, + defaultIndexGroups, + gnames, + SimulationAtomGroupType::MassCenterVelocityRemoval, + restnm, + vcmGroupNames.empty() ? egrptpALL_GENREST : egrptpPART, + bVerbose, + wi); if (ir->comm_mode != ecmNO) { @@ -3776,18 +3947,49 @@ void do_index(const char* mdparin, calc_nrdf(mtop, ir, gnames); auto user1GroupNames = gmx::splitString(inputrecStrings->user1); - do_numbering(natoms, groups, user1GroupNames, defaultIndexGroups, gnames, - SimulationAtomGroupType::User1, restnm, egrptpALL_GENREST, bVerbose, wi); + do_numbering(natoms, + groups, + user1GroupNames, + defaultIndexGroups, + gnames, + SimulationAtomGroupType::User1, + restnm, + egrptpALL_GENREST, + bVerbose, + wi); auto user2GroupNames = gmx::splitString(inputrecStrings->user2); - do_numbering(natoms, groups, user2GroupNames, defaultIndexGroups, gnames, - SimulationAtomGroupType::User2, restnm, egrptpALL_GENREST, bVerbose, wi); + do_numbering(natoms, + groups, + user2GroupNames, + defaultIndexGroups, + gnames, + SimulationAtomGroupType::User2, + restnm, + egrptpALL_GENREST, + bVerbose, + wi); auto compressedXGroupNames = gmx::splitString(inputrecStrings->x_compressed_groups); - do_numbering(natoms, groups, compressedXGroupNames, defaultIndexGroups, gnames, - SimulationAtomGroupType::CompressedPositionOutput, restnm, egrptpONE, bVerbose, wi); + do_numbering(natoms, + groups, + compressedXGroupNames, + defaultIndexGroups, + gnames, + SimulationAtomGroupType::CompressedPositionOutput, + restnm, + egrptpONE, + bVerbose, + wi); auto orirefFitGroupNames = gmx::splitString(inputrecStrings->orirefitgrp); - do_numbering(natoms, groups, orirefFitGroupNames, defaultIndexGroups, gnames, - SimulationAtomGroupType::OrientationRestraintsFit, restnm, egrptpALL_GENREST, - bVerbose, wi); + do_numbering(natoms, + groups, + orirefFitGroupNames, + defaultIndexGroups, + gnames, + SimulationAtomGroupType::OrientationRestraintsFit, + restnm, + egrptpALL_GENREST, + bVerbose, + wi); /* MiMiC QMMM input processing */ auto qmGroupNames = gmx::splitString(inputrecStrings->QMMM); @@ -3796,8 +3998,16 @@ void do_index(const char* mdparin, gmx_fatal(FARGS, "Currently, having more than one QM group in MiMiC is not supported"); } /* group rest, if any, is always MM! */ - do_numbering(natoms, groups, qmGroupNames, defaultIndexGroups, gnames, - SimulationAtomGroupType::QuantumMechanics, restnm, egrptpALL_GENREST, bVerbose, wi); + do_numbering(natoms, + groups, + qmGroupNames, + defaultIndexGroups, + gnames, + SimulationAtomGroupType::QuantumMechanics, + restnm, + egrptpALL_GENREST, + bVerbose, + wi); ir->opts.ngQM = qmGroupNames.size(); /* end of MiMiC QMMM input */ @@ -3843,11 +4053,12 @@ void do_index(const char* mdparin, if ((ir->expandedvals->nstexpanded < 0) && ir->bSimTemp) { ir->expandedvals->nstexpanded = 2 * static_cast(ir->opts.tau_t[0] / ir->delta_t); - warning(wi, gmx::formatString( - "the value for nstexpanded was not specified for " - " expanded ensemble simulated tempering. It is set to 2*tau_t (%d) " - "by default, but it is recommended to set it to an explicit value!", - ir->expandedvals->nstexpanded)); + warning(wi, + gmx::formatString( + "the value for nstexpanded was not specified for " + " expanded ensemble simulated tempering. It is set to 2*tau_t (%d) " + "by default, but it is recommended to set it to an explicit value!", + ir->expandedvals->nstexpanded)); } for (i = 0; (i < defaultIndexGroups->nr); i++) { @@ -3961,7 +4172,8 @@ static bool absolute_reference(const t_inputrec* ir, const gmx_mtop_t* sys, cons gmx_fatal(FARGS, " Invalid geometry for flat-bottom position restraint.\n" "Expected nr between 1 and %d. Found %d\n", - efbposresNR - 1, pr->fbposres.geom); + efbposresNR - 1, + pr->fbposres.geom); } } } @@ -3998,8 +4210,8 @@ static void check_combination_rule_differences(const gmx_mtop_t* mtop, if (sscanf(ptr, "%lf%lf", &dbl, &canary) != 1) { - gmx_fatal(FARGS, - "Could not parse a single floating-point number from GMX_LJCOMB_TOL (%s)", ptr); + gmx_fatal( + FARGS, "Could not parse a single floating-point number from GMX_LJCOMB_TOL (%s)", ptr); } tol = dbl; } @@ -4059,8 +4271,8 @@ static void check_combination_rules(const t_inputrec* ir, const gmx_mtop_t* mtop { bool bLBRulesPossible, bC6ParametersWorkWithGeometricRules, bC6ParametersWorkWithLBRules; - check_combination_rule_differences(mtop, 0, &bC6ParametersWorkWithGeometricRules, - &bC6ParametersWorkWithLBRules, &bLBRulesPossible); + check_combination_rule_differences( + mtop, 0, &bC6ParametersWorkWithGeometricRules, &bC6ParametersWorkWithLBRules, &bLBRulesPossible); if (ir->ljpme_combination_rule == eljpmeLB) { if (!bC6ParametersWorkWithLBRules || !bLBRulesPossible) @@ -4161,7 +4373,11 @@ void triple_check(const char* mdparin, t_inputrec* ir, gmx_mtop_t* sys, warninp_ "of %g and a tau_t of %g, your temperature might be off by up to %.1f%%. " "To ensure the error is below %.1f%%, decrease verlet-buffer-tolerance to " "%.0e or decrease tau_t.", - ir->verletbuf_tol, T, tau, 100 * max_T_error, 100 * T_error_suggest, + ir->verletbuf_tol, + T, + tau, + 100 * max_T_error, + 100 * T_error_suggest, ir->verletbuf_tol * T_error_suggest / max_T_error); warning(wi, warn_buf); } @@ -4182,7 +4398,8 @@ void triple_check(const char* mdparin, t_inputrec* ir, gmx_mtop_t* sys, warninp_ sprintf(err_buf, "all tau_t must be positive using Andersen temperature control, " "tau_t[%d]=%10.6f", - i, ir->opts.tau_t[i]); + i, + ir->opts.tau_t[i]); CHECK(ir->opts.tau_t[i] < 0); } @@ -4196,7 +4413,11 @@ void triple_check(const char* mdparin, t_inputrec* ir, gmx_mtop_t* sys, warninp_ "multiple of nstcomm (%d), as velocities of atoms in coupled groups are " "randomized every time step. The input tau_t (%8.3f) leads to %d steps per " "randomization", - i, etcoupl_names[ir->etc], ir->nstcomm, ir->opts.tau_t[i], nsteps); + i, + etcoupl_names[ir->etc], + ir->nstcomm, + ir->opts.tau_t[i], + nsteps); CHECK(nsteps % ir->nstcomm != 0); } } @@ -4222,7 +4443,11 @@ void triple_check(const char* mdparin, t_inputrec* ir, gmx_mtop_t* sys, warninp_ std::string message = gmx::formatString( "With %s T-coupling and %s p-coupling, " "%s (%g) should be at least twice as large as %s (%g) to avoid resonances", - etcoupl_names[ir->etc], epcoupl_names[ir->epc], "tau-p", ir->tau_p, "tau-t", + etcoupl_names[ir->etc], + epcoupl_names[ir->epc], + "tau-p", + ir->tau_p, + "tau-t", tau_t_max); warning(wi, message.c_str()); } @@ -4265,7 +4490,8 @@ void triple_check(const char* mdparin, t_inputrec* ir, gmx_mtop_t* sys, warninp_ "You are using full electrostatics treatment %s for a system without charges.\n" "This costs a lot of performance for just processing zeros, consider using %s " "instead.\n", - EELTYPE(ir->coulombtype), EELTYPE(eelCUT)); + EELTYPE(ir->coulombtype), + EELTYPE(eelCUT)); warning(wi, err_buf); } } @@ -4331,13 +4557,16 @@ void triple_check(const char* mdparin, t_inputrec* ir, gmx_mtop_t* sys, warninp_ if (fabs(acc[m]) > 1e-6) { const char* dim[DIM] = { "X", "Y", "Z" }; - fprintf(stderr, "Net Acceleration in %s direction, will %s be corrected\n", dim[m], + fprintf(stderr, + "Net Acceleration in %s direction, will %s be corrected\n", + dim[m], ir->nstcomm != 0 ? "" : "not"); if (ir->nstcomm != 0 && m < ndof_com(ir)) { acc[m] /= mt; for (i = 0; - (i < gmx::ssize(sys->groups.groups[SimulationAtomGroupType::Acceleration])); i++) + (i < gmx::ssize(sys->groups.groups[SimulationAtomGroupType::Acceleration])); + i++) { ir->opts.acc[i][m] -= acc[m]; } @@ -4391,7 +4620,8 @@ void triple_check(const char* mdparin, t_inputrec* ir, gmx_mtop_t* sys, warninp_ gmx_fatal(FARGS, "Can not have dynamic box while using pull geometry '%s' " "(dim %c)", - EPULLGEOM(ir->pull->coord[c].eGeom), 'x' + m); + EPULLGEOM(ir->pull->coord[c].eGeom), + 'x' + m); } } } diff --git a/src/gromacs/gmxpreprocess/readpull.cpp b/src/gromacs/gmxpreprocess/readpull.cpp index 0a5b1afea5..103f9a279f 100644 --- a/src/gromacs/gmxpreprocess/readpull.cpp +++ b/src/gromacs/gmxpreprocess/readpull.cpp @@ -149,7 +149,9 @@ static void init_pull_coord(t_pull_coord* pcrd, gmx_fatal(FARGS, "Pulling of type %s can not be combined with geometry %s. Consider using pull " "type %s.", - epull_names[pcrd->eType], epullg_names[pcrd->eGeom], epull_names[epullUMBRELLA]); + epull_names[pcrd->eType], + epullg_names[pcrd->eGeom], + epull_names[epullUMBRELLA]); } if (pcrd->eType == epullEXTERNAL) @@ -159,8 +161,11 @@ static void init_pull_coord(t_pull_coord* pcrd, sprintf(buf, "The use of pull type '%s' for pull coordinate %d requires that the name of " "the module providing the potential external is set with the option %s%d%s", - epull_names[pcrd->eType], coord_index_for_output, "pull-coord", - coord_index_for_output, "-potential-provider"); + epull_names[pcrd->eType], + coord_index_for_output, + "pull-coord", + coord_index_for_output, + "-potential-provider"); warning_error(wi, buf); } @@ -169,7 +174,8 @@ static void init_pull_coord(t_pull_coord* pcrd, sprintf(buf, "The use of pull type '%s' for pull coordinate %d requires that the pull rate " "is zero", - epull_names[pcrd->eType], coord_index_for_output); + epull_names[pcrd->eType], + coord_index_for_output); warning_error(wi, buf); } @@ -182,7 +188,8 @@ static void init_pull_coord(t_pull_coord* pcrd, "With pull type '%s' and geometry '%s', the distance component along the " "cylinder axis between atoms in the cylinder group and the COM of the pull " "group should be smaller than half the box length", - epull_names[pcrd->eType], epullg_names[pcrd->eGeom]); + epull_names[pcrd->eType], + epullg_names[pcrd->eGeom]); warning_note(wi, buf); } } @@ -206,7 +213,9 @@ static void init_pull_coord(t_pull_coord* pcrd, "This may work, since you have set pull-coord-start to 'yes' which modifies " "this value, but only for certain starting distances. " "If this is a mistake you may want to use geometry %s instead.", - pcrd->init, EPULLGEOM(pcrd->eGeom), EPULLGEOM(epullgDIR)); + pcrd->init, + EPULLGEOM(pcrd->eGeom), + EPULLGEOM(epullgDIR)); warning(wi, buf); } } @@ -220,7 +229,8 @@ static void init_pull_coord(t_pull_coord* pcrd, "allowed range [0, 180] degrees for geometry (%s). " "This may work, since you have set pull-coord-start to 'yes' which modifies " "this value, but only for certain starting angles.", - pcrd->init, EPULLGEOM(pcrd->eGeom)); + pcrd->init, + EPULLGEOM(pcrd->eGeom)); warning(wi, buf); } } @@ -233,7 +243,8 @@ static void init_pull_coord(t_pull_coord* pcrd, "allowed range [-180, 180] degrees for geometry (%s). " "This may work, since you have set pull-coord-start to 'yes' which modifies " "this value, but only for certain starting angles.", - pcrd->init, EPULLGEOM(pcrd->eGeom)); + pcrd->init, + EPULLGEOM(pcrd->eGeom)); warning(wi, buf); } } @@ -247,7 +258,8 @@ static void init_pull_coord(t_pull_coord* pcrd, { if (dnorm2(vec) == 0) { - gmx_fatal(FARGS, "With pull geometry %s the pull vector can not be 0,0,0", + gmx_fatal(FARGS, + "With pull geometry %s the pull vector can not be 0,0,0", epullg_names[pcrd->eGeom]); } for (int d = 0; d < DIM; d++) @@ -257,7 +269,8 @@ static void init_pull_coord(t_pull_coord* pcrd, gmx_fatal(FARGS, "pull-coord-vec has non-zero %c-component while pull_dim for the " "%c-dimension is set to N", - 'x' + d, 'x' + d); + 'x' + d, + 'x' + d); } } @@ -272,7 +285,10 @@ static void init_pull_coord(t_pull_coord* pcrd, "A pull vector is given (%g %g %g) but will not be used with geometry %s. If " "you really want to use this " "vector, consider using geometry %s instead.", - vec[0], vec[1], vec[2], EPULLGEOM(pcrd->eGeom), + vec[0], + vec[1], + vec[2], + EPULLGEOM(pcrd->eGeom), pcrd->eGeom == epullgANGLE ? EPULLGEOM(epullgANGLEAXIS) : EPULLGEOM(epullgDIR)); warning(wi, buf); } @@ -366,14 +382,22 @@ std::vector read_pullparams(std::vector* inp, pull_param default: pullCoord.ngroup = 2; break; } - nscan = sscanf(groups, "%d %d %d %d %d %d %d", &pullCoord.group[0], &pullCoord.group[1], - &pullCoord.group[2], &pullCoord.group[3], &pullCoord.group[4], - &pullCoord.group[5], &idum); + nscan = sscanf(groups, + "%d %d %d %d %d %d %d", + &pullCoord.group[0], + &pullCoord.group[1], + &pullCoord.group[2], + &pullCoord.group[3], + &pullCoord.group[4], + &pullCoord.group[5], + &idum); if (nscan != pullCoord.ngroup) { auto message = gmx::formatString("%s should contain %d pull group indices with geometry %s", - buf, pullCoord.ngroup, epullg_names[pullCoord.eGeom]); + buf, + pullCoord.ngroup, + epullg_names[pullCoord.eGeom]); set_warning_line(wi, nullptr, -1); warning_error(wi, message); } @@ -384,7 +408,10 @@ std::vector read_pullparams(std::vector* inp, pull_param /* Quit with a fatal error to avoid invalid memory access */ gmx_fatal(FARGS, "%s contains an invalid pull group %d, you should have %d <= group <= %d", - buf, pullCoord.group[g], 0, pull->ngroup - 1); + buf, + pullCoord.group[g], + 0, + pull->ngroup - 1); } } @@ -452,7 +479,9 @@ void process_pull_groups(gmx::ArrayRef pullGroups, gmx_fatal(FARGS, "Number of weights (%ld) for pull group %d '%s' does not match the number of " "atoms (%ld)", - gmx::ssize(pullGroup.weight), g, pullGroupNames[g].c_str(), + gmx::ssize(pullGroup.weight), + g, + pullGroupNames[g].c_str(), gmx::ssize(pullGroup.ind)); } @@ -493,7 +522,9 @@ void checkPullCoords(gmx::ArrayRef pullGroups, gmx::ArrayRef gmx_fatal(FARGS, "Pull group index in pull-coord%d-groups out of range, should be between %d " "and %d", - c + 1, 0, int(pullGroups.size()) + 1); + c + 1, + 0, + int(pullGroups.size()) + 1); } if (pcrd.group[0] == pcrd.group[1]) @@ -544,8 +575,11 @@ pull_t* set_pull_init(t_inputrec* ir, const gmx_mtop_t* mtop, rvec* x, matrix bo for (int g = 0; g < pull->ngroup; g++) { bool groupObeysPbc = pullCheckPbcWithinGroup( - *pull_work, gmx::arrayRefFromArray(reinterpret_cast(x), mtop->natoms), - pbc, g, c_pullGroupSmallGroupThreshold); + *pull_work, + gmx::arrayRefFromArray(reinterpret_cast(x), mtop->natoms), + pbc, + g, + c_pullGroupSmallGroupThreshold); if (!groupObeysPbc) { char buf[STRLEN]; @@ -558,7 +592,8 @@ pull_t* set_pull_init(t_inputrec* ir, const gmx_mtop_t* mtop, rvec* x, matrix bo "atom should be chosen as pbcatom. Pull group %d is larger than that and " "does not have " "a specific atom selected as reference atom.", - c_pullGroupSmallGroupThreshold, g); + c_pullGroupSmallGroupThreshold, + g); warning_error(wi, buf); } else if (!pull->bSetPbcRefToPrevStepCOM) @@ -568,15 +603,20 @@ pull_t* set_pull_init(t_inputrec* ir, const gmx_mtop_t* mtop, rvec* x, matrix bo "other " "atoms in the group is larger than %g times half the box size. " "Set the pull-pbc-ref-prev-step-com option to yes.", - pull->group[g].pbcatom + 1, g, c_pullGroupSmallGroupThreshold); + pull->group[g].pbcatom + 1, + g, + c_pullGroupSmallGroupThreshold); warning_error(wi, buf); } } if (groupObeysPbc) { groupObeysPbc = pullCheckPbcWithinGroup( - *pull_work, gmx::arrayRefFromArray(reinterpret_cast(x), mtop->natoms), - pbc, g, c_pullGroupPbcMargin); + *pull_work, + gmx::arrayRefFromArray(reinterpret_cast(x), mtop->natoms), + pbc, + g, + c_pullGroupPbcMargin); if (!groupObeysPbc) { char buf[STRLEN]; @@ -585,7 +625,9 @@ pull_t* set_pull_init(t_inputrec* ir, const gmx_mtop_t* mtop, rvec* x, matrix bo "size from the PBC atom (%d). " "If atoms are or will more beyond half the box size from the PBC atom, the " "COM will be ill defined.", - g, c_pullGroupPbcMargin, pull->group[g].pbcatom + 1); + g, + c_pullGroupPbcMargin, + pull->group[g].pbcatom + 1); set_warning_line(wi, nullptr, -1); warning(wi, buf); } @@ -630,7 +672,9 @@ pull_t* set_pull_init(t_inputrec* ir, const gmx_mtop_t* mtop, rvec* x, matrix bo gmx_fatal(FARGS, "The initial pull distance (%g) needs to be non-negative with geometry " "%s. If you want a signed distance, use geometry %s instead.", - pcrd->init, EPULLGEOM(pcrd->eGeom), EPULLGEOM(epullgDIR)); + pcrd->init, + EPULLGEOM(pcrd->eGeom), + EPULLGEOM(epullgDIR)); } /* TODO: With a positive init but a negative rate things could still diff --git a/src/gromacs/gmxpreprocess/readrot.cpp b/src/gromacs/gmxpreprocess/readrot.cpp index 6ef252e7f5..7643c5888d 100644 --- a/src/gromacs/gmxpreprocess/readrot.cpp +++ b/src/gromacs/gmxpreprocess/readrot.cpp @@ -131,8 +131,14 @@ extern std::vector read_rotparams(std::vector* inp, t_ro sprintf(warn_buf, "rot-vec%d = 0", g); warning_error(wi, warn_buf); } - fprintf(stderr, "%s Group %d (%s) normalized rot. vector: %f %f %f\n", RotStr, g, - erotg_names[rotg->eType], vec[0], vec[1], vec[2]); + fprintf(stderr, + "%s Group %d (%s) normalized rot. vector: %f %f %f\n", + RotStr, + g, + erotg_names[rotg->eType], + vec[0], + vec[1], + vec[2]); for (m = 0; m < DIM; m++) { rotg->inputVec[m] = vec[m]; @@ -210,8 +216,7 @@ extern std::vector read_rotparams(std::vector* inp, t_ro warning_error(wi, warn_buf); } printStringNoNewline( - inp, - "For fit type 'potential', distance in degrees between two consecutive angles"); + inp, "For fit type 'potential', distance in degrees between two consecutive angles"); sprintf(buf, "rot-potfit-step%d", g); rotg->PotAngle_step = get_ereal(inp, buf, 0.25, wi); } @@ -274,7 +279,9 @@ extern void set_reference_positions(t_rot* rot, rvec* x, matrix box, const char* gmx_fatal(FARGS, "%s The file containing the reference positions was not found.\n" "Expected the file '%s' for group %d.\n", - RotStr, reffile, g); + RotStr, + reffile, + g); } if (gmx_fexist(reffile)) @@ -286,10 +293,12 @@ extern void set_reference_positions(t_rot* rot, rvec* x, matrix box, const char* gmx_fatal(FARGS, "Number of atoms in file %s (%d) does not match the number of atoms in " "rotation group (%d)!\n", - reffile, header.natoms, rotg->nat); + reffile, + header.natoms, + rotg->nat); } - gmx_trr_read_single_frame(reffile, &header.step, &header.t, &header.lambda, f_box, - &header.natoms, rotg->x_ref, nullptr, nullptr); + gmx_trr_read_single_frame( + reffile, &header.step, &header.t, &header.lambda, f_box, &header.natoms, rotg->x_ref, nullptr, nullptr); /* Check whether the box is unchanged and output a warning if not: */ check_box_unchanged(f_box, box, reffile, wi); @@ -325,8 +334,7 @@ extern void make_rotation_groups(t_rot* rot, if (rotg->nat > 0) { - fprintf(stderr, "Rotation group %d '%s' has %d atoms\n", g, rotateGroupNames[g].c_str(), - rotg->nat); + fprintf(stderr, "Rotation group %d '%s' has %d atoms\n", g, rotateGroupNames[g].c_str(), rotg->nat); snew(rotg->ind, rotg->nat); for (i = 0; i < rotg->nat; i++) { diff --git a/src/gromacs/gmxpreprocess/resall.cpp b/src/gromacs/gmxpreprocess/resall.cpp index 30a8b5cbb7..53c16f51c3 100644 --- a/src/gromacs/gmxpreprocess/resall.cpp +++ b/src/gromacs/gmxpreprocess/resall.cpp @@ -118,8 +118,12 @@ static void print_resatoms(FILE* out, const PreprocessingAtomTypes& atype, const { gmx_fatal(FARGS, "Incorrect atomtype (%d)", tp); } - fprintf(out, "%6s %6s %8.3f %6d\n", *(rtpDBEntry.atomname[j]), tpnm, - rtpDBEntry.atom[j].q, rtpDBEntry.cgnr[j]); + fprintf(out, + "%6s %6s %8.3f %6d\n", + *(rtpDBEntry.atomname[j]), + tpnm, + rtpDBEntry.atom[j].q, + rtpDBEntry.cgnr[j]); } } @@ -149,7 +153,8 @@ static bool read_atoms(FILE* in, char* line, PreprocessResidue* r0, t_symtab* ta gmx_fatal(FARGS, "Atom type %s (residue %s) not found in atomtype " "database", - buf1, r0->resname.c_str()); + buf1, + r0->resname.c_str()); } r0->atom.back().type = j; r0->atom.back().m = atype->atomMassFromAtomType(j); @@ -250,9 +255,14 @@ static void print_resall_header(FILE* out, gmx::ArrayRef(rtpDBEntry[0].bKeepAllGeneratedDihedrals), rtpDBEntry[0].nrexcl, + fprintf(out, + " %5d %6d %9d %9d %14d %14d %14d %14d\n\n", + rtpDBEntry[0].rb[0].type, + rtpDBEntry[0].rb[1].type, + rtpDBEntry[0].rb[2].type, + rtpDBEntry[0].rb[3].type, + static_cast(rtpDBEntry[0].bKeepAllGeneratedDihedrals), + rtpDBEntry[0].nrexcl, static_cast(rtpDBEntry[0].bGenerateHH14Interactions), static_cast(rtpDBEntry[0].bRemoveDihedralIfWithImproper)); } @@ -268,12 +278,15 @@ static void print_resall_log(const gmx::MDLogger& logger, gmx::ArrayRef(rtpDBEntry[0].bKeepAllGeneratedDihedrals), - rtpDBEntry[0].nrexcl, static_cast(rtpDBEntry[0].bGenerateHH14Interactions), - static_cast(rtpDBEntry[0].bRemoveDihedralIfWithImproper)); + .appendTextFormatted(" %5d %6d %9d %9d %14d %14d %14d %14d", + rtpDBEntry[0].rb[0].type, + rtpDBEntry[0].rb[1].type, + rtpDBEntry[0].rb[2].type, + rtpDBEntry[0].rb[3].type, + static_cast(rtpDBEntry[0].bKeepAllGeneratedDihedrals), + rtpDBEntry[0].nrexcl, + static_cast(rtpDBEntry[0].bGenerateHH14Interactions), + static_cast(rtpDBEntry[0].bRemoveDihedralIfWithImproper)); } @@ -357,14 +370,22 @@ void readResidueDatabase(const std::string& rrdb, if (gmx::equalCaseInsensitive("bondedtypes", header, 5)) { get_a_line(in, line, STRLEN); - if ((nparam = sscanf(line, "%d %d %d %d %d %d %d %d", &header_settings.rb[ebtsBONDS].type, + if ((nparam = sscanf(line, + "%d %d %d %d %d %d %d %d", + &header_settings.rb[ebtsBONDS].type, &header_settings.rb[ebtsANGLES].type, - &header_settings.rb[ebtsPDIHS].type, &header_settings.rb[ebtsIDIHS].type, - &dum1, &header_settings.nrexcl, &dum2, &dum3)) + &header_settings.rb[ebtsPDIHS].type, + &header_settings.rb[ebtsIDIHS].type, + &dum1, + &header_settings.nrexcl, + &dum2, + &dum3)) < 4) { - gmx_fatal(FARGS, "need 4 to 8 parameters in the header of .rtp file %s at line:\n%s\n", - rrdb.c_str(), line); + gmx_fatal(FARGS, + "need 4 to 8 parameters in the header of .rtp file %s at line:\n%s\n", + rrdb.c_str(), + line); } header_settings.bKeepAllGeneratedDihedrals = (dum1 != 0); header_settings.bGenerateHH14Interactions = (dum2 != 0); @@ -463,17 +484,16 @@ void readResidueDatabase(const std::string& rrdb, gmx_fatal(FARGS, "No atoms found in .rtp file in residue %s\n", res->resname.c_str()); } - auto found = std::find_if(rtpDBEntry->begin(), rtpDBEntry->end() - 1, - [&res](const PreprocessResidue& entry) { - return gmx::equalCaseInsensitive(entry.resname, res->resname); - }); + auto found = std::find_if( + rtpDBEntry->begin(), rtpDBEntry->end() - 1, [&res](const PreprocessResidue& entry) { + return gmx::equalCaseInsensitive(entry.resname, res->resname); + }); if (found != rtpDBEntry->end() - 1) { if (found >= oldArrayEnd) { - gmx_fatal(FARGS, "Found a second entry for '%s' in '%s'", res->resname.c_str(), - rrdb.c_str()); + gmx_fatal(FARGS, "Found a second entry for '%s' in '%s'", res->resname.c_str(), rrdb.c_str()); } if (bAllowOverrideRTP) { @@ -482,7 +502,9 @@ void readResidueDatabase(const std::string& rrdb, .appendTextFormatted( "Found another rtp entry for '%s' in '%s'," " ignoring this entry and keeping the one from '%s.rtp'", - res->resname.c_str(), rrdb.c_str(), found->filebase.c_str()); + res->resname.c_str(), + rrdb.c_str(), + found->filebase.c_str()); /* We should free all the data for this entry. * The current code gives a lot of dangling pointers. */ @@ -493,7 +515,9 @@ void readResidueDatabase(const std::string& rrdb, gmx_fatal(FARGS, "Found rtp entries for '%s' in both '%s' and '%s'. If you want the first " "definition to override the second one, set the -rtpo option of pdb2gmx.", - res->resname.c_str(), found->filebase.c_str(), rrdb.c_str()); + res->resname.c_str(), + found->filebase.c_str(), + rrdb.c_str()); } } } @@ -501,7 +525,10 @@ void readResidueDatabase(const std::string& rrdb, std::sort(rtpDBEntry->begin(), rtpDBEntry->end(), [](const PreprocessResidue& a, const PreprocessResidue& b) { return std::lexicographical_compare( - a.resname.begin(), a.resname.end(), b.resname.begin(), b.resname.end(), + a.resname.begin(), + a.resname.end(), + b.resname.begin(), + b.resname.end(), [](const char& c1, const char& c2) { return std::toupper(c1) < std::toupper(c2); }); }); @@ -589,8 +616,10 @@ std::string searchResidueDatabase(const std::string& key, } if (nbest > 1) { - gmx_fatal(FARGS, "Residue '%s' not found in residue topology database, looks a bit like %s", - key.c_str(), bestbuf.c_str()); + gmx_fatal(FARGS, + "Residue '%s' not found in residue topology database, looks a bit like %s", + key.c_str(), + bestbuf.c_str()); } else if (besti == -1) { @@ -603,7 +632,8 @@ std::string searchResidueDatabase(const std::string& key, .appendTextFormatted( "'%s' not found in residue topology database, " "trying to use '%s'", - key.c_str(), rtpDBEntry[besti].resname.c_str()); + key.c_str(), + rtpDBEntry[besti].resname.c_str()); } return rtpDBEntry[besti].resname; @@ -612,10 +642,10 @@ std::string searchResidueDatabase(const std::string& key, gmx::ArrayRef::const_iterator getDatabaseEntry(const std::string& rtpname, gmx::ArrayRef rtpDBEntry) { - auto found = std::find_if(rtpDBEntry.begin(), rtpDBEntry.end(), - [&rtpname](const PreprocessResidue& entry) { - return gmx::equalCaseInsensitive(rtpname, entry.resname); - }); + auto found = std::find_if( + rtpDBEntry.begin(), rtpDBEntry.end(), [&rtpname](const PreprocessResidue& entry) { + return gmx::equalCaseInsensitive(rtpname, entry.resname); + }); if (found == rtpDBEntry.end()) { /* This should never happen, since searchResidueDatabase should have been called diff --git a/src/gromacs/gmxpreprocess/solvate.cpp b/src/gromacs/gmxpreprocess/solvate.cpp index 054d5b223a..4d747607a4 100644 --- a/src/gromacs/gmxpreprocess/solvate.cpp +++ b/src/gromacs/gmxpreprocess/solvate.cpp @@ -109,8 +109,8 @@ static void sort_molecule(t_atoms** atoms_solvt, t_atoms** newatoms, std::vector { numAtomsInMolType++; } - molTypes.emplace_back(MoleculeType{ *atoms->resinfo[atoms->atom[i].resind].name, - numAtomsInMolType, 1 }); + molTypes.emplace_back(MoleculeType{ + *atoms->resinfo[atoms->atom[i].resind].name, numAtomsInMolType, 1 }); } else { @@ -119,12 +119,14 @@ static void sort_molecule(t_atoms** atoms_solvt, t_atoms** newatoms, std::vector } } - fprintf(stderr, "Found %zu%s molecule type%s:\n", molTypes.size(), - molTypes.size() == 1 ? "" : " different", molTypes.size() == 1 ? "" : "s"); + fprintf(stderr, + "Found %zu%s molecule type%s:\n", + molTypes.size(), + molTypes.size() == 1 ? "" : " different", + molTypes.size() == 1 ? "" : "s"); for (const auto& molType : molTypes) { - fprintf(stderr, "%7s (%4d atoms): %5d residues\n", molType.name.c_str(), molType.numAtoms, - molType.numMolecules); + fprintf(stderr, "%7s (%4d atoms): %5d residues\n", molType.name.c_str(), molType.numAtoms, molType.numMolecules); } /* if we have only 1 moleculetype, we don't have to sort */ @@ -277,8 +279,7 @@ static void replicateSolventBox(t_atoms* atoms, } nmol *= n_box[i]; } - fprintf(stderr, "Will generate new solvent configuration of %dx%dx%d boxes\n", n_box[XX], - n_box[YY], n_box[ZZ]); + fprintf(stderr, "Will generate new solvent configuration of %dx%dx%d boxes\n", n_box[XX], n_box[YY], n_box[ZZ]); // Create arrays for storing the generated system (cannot be done in-place // in case the target box is smaller than the original in one dimension, @@ -460,8 +461,7 @@ static void removeSolventBoxOverlap(t_atoms* atoms, remover.removeMarkedElements(r); const int originalAtomCount = atoms->nr; remover.removeMarkedAtoms(atoms); - fprintf(stderr, "Removed %d solvent atoms due to solvent-solvent overlap\n", - originalAtomCount - atoms->nr); + fprintf(stderr, "Removed %d solvent atoms due to solvent-solvent overlap\n", originalAtomCount - atoms->nr); } /*! \brief @@ -508,8 +508,10 @@ static void removeSolventOutsideShell(t_atoms* atoms, remover.removeMarkedElements(r); const int originalAtomCount = atoms->nr; remover.removeMarkedAtoms(atoms); - fprintf(stderr, "Removed %d solvent atoms more than %f nm from solute.\n", - originalAtomCount - atoms->nr, rshell); + fprintf(stderr, + "Removed %d solvent atoms more than %f nm from solute.\n", + originalAtomCount - atoms->nr, + rshell); } /*! \brief @@ -564,8 +566,7 @@ static void removeSolventOverlappingWithSolute(t_atoms* atoms, remover.removeMarkedElements(r); const int originalAtomCount = atoms->nr; remover.removeMarkedAtoms(atoms); - fprintf(stderr, "Removed %d solvent atoms due to solute-solvent overlap\n", - originalAtomCount - atoms->nr); + fprintf(stderr, "Removed %d solvent atoms due to solute-solvent overlap\n", originalAtomCount - atoms->nr); } /*! \brief @@ -624,8 +625,13 @@ static void add_solv(const char* filename, fprintf(stderr, "Reading solvent configuration\n"); bool bTprFileWasRead; rvec *temporaryX = nullptr, *temporaryV = nullptr; - readConfAndTopology(gmx::findLibraryFile(filename).c_str(), &bTprFileWasRead, &topSolvent, - &pbcTypeSolvent, &temporaryX, &temporaryV, boxSolvent); + readConfAndTopology(gmx::findLibraryFile(filename).c_str(), + &bTprFileWasRead, + &topSolvent, + &pbcTypeSolvent, + &temporaryX, + &temporaryV, + boxSolvent); t_atoms* atomsSolvent; snew(atomsSolvent, 1); *atomsSolvent = gmx_mtop_global_atoms(&topSolvent); @@ -676,11 +682,11 @@ static void add_solv(const char* filename, { if (rshell > 0.0) { - removeSolventOutsideShell(atomsSolvent, &xSolvent, &vSolvent, &exclusionDistances_solvt, - pbc, *x, rshell); + removeSolventOutsideShell( + atomsSolvent, &xSolvent, &vSolvent, &exclusionDistances_solvt, pbc, *x, rshell); } - removeSolventOverlappingWithSolute(atomsSolvent, &xSolvent, &vSolvent, - &exclusionDistances_solvt, pbc, *x, exclusionDistances); + removeSolventOverlappingWithSolute( + atomsSolvent, &xSolvent, &vSolvent, &exclusionDistances_solvt, pbc, *x, exclusionDistances); } if (max_sol > 0 && atomsSolvent->nres > max_sol) @@ -708,7 +714,9 @@ static void add_solv(const char* filename, gmx::AtomsBuilder builder(atoms, symtab); builder.mergeAtoms(*sortedAtomsSolvent); } - fprintf(stderr, "Generated solvent containing %d atoms in %d residues\n", atomsSolvent->nr, + fprintf(stderr, + "Generated solvent containing %d atoms in %d residues\n", + atomsSolvent->nr, atomsSolvent->nres); if (newatoms) @@ -744,8 +752,10 @@ static void update_top(t_atoms* atoms, mtot = 0; for (i = 0; (i < atoms->nr); i++) { - aps->setAtomProperty(epropMass, std::string(*atoms->resinfo[atoms->atom[i].resind].name), - std::string(*atoms->atomname[i]), &mm); + aps->setAtomProperty(epropMass, + std::string(*atoms->resinfo[atoms->atom[i].resind].name), + std::string(*atoms->atomname[i]), + &mm); mtot += mm; } @@ -825,7 +835,9 @@ static void update_top(t_atoms* atoms, fprintf(stdout, "Adding line for %d solvent molecules with resname (%s) to " "topology file (%s)\n", - resCount, currRes.c_str(), topinout); + resCount, + currRes.c_str(), + topinout); fprintf(fpout, "%-15s %5d\n", currRes.c_str(), resCount); currRes = *atoms->resinfo[i].name; resCount = 1; @@ -835,7 +847,9 @@ static void update_top(t_atoms* atoms, fprintf(stdout, "Adding line for %d solvent molecules with resname (%s) to " "topology file (%s)\n", - resCount, currRes.c_str(), topinout); + resCount, + currRes.c_str(), + topinout); fprintf(fpout, "%-15s %5d\n", currRes.c_str(), resCount); } gmx_ffclose(fpout); @@ -941,8 +955,8 @@ int gmx_solvate(int argc, char* argv[]) { "-vel", FALSE, etBOOL, { &bReadV }, "Keep velocities from input solute and solvent" }, }; - if (!parse_common_args(&argc, argv, 0, NFILE, fnm, asize(pa), pa, asize(desc), desc, - asize(bugs), bugs, &oenv)) + if (!parse_common_args( + &argc, argv, 0, NFILE, fnm, asize(pa), pa, asize(desc), desc, asize(bugs), bugs, &oenv)) { return 0; } @@ -975,8 +989,8 @@ int gmx_solvate(int argc, char* argv[]) fprintf(stderr, "Reading solute configuration%s\n", bReadV ? " and velocities" : ""); bool bTprFileWasRead; rvec *temporaryX = nullptr, *temporaryV = nullptr; - readConfAndTopology(conf_prot, &bTprFileWasRead, &top, &pbcType, &temporaryX, - bReadV ? &temporaryV : nullptr, box); + readConfAndTopology( + conf_prot, &bTprFileWasRead, &top, &pbcType, &temporaryX, bReadV ? &temporaryV : nullptr, box); *atoms = gmx_mtop_global_atoms(&top); x.assign(temporaryX, temporaryX + top.natoms); sfree(temporaryX); @@ -1015,15 +1029,19 @@ int gmx_solvate(int argc, char* argv[]) "or give explicit -box command line option"); } - add_solv(solventFileName, atoms, &top.symtab, &x, &v, pbcTypeForOutput, box, &aps, - defaultDistance, scaleFactor, r_shell, max_sol); + add_solv(solventFileName, atoms, &top.symtab, &x, &v, pbcTypeForOutput, box, &aps, defaultDistance, scaleFactor, r_shell, max_sol); /* write new configuration 1 to file confout */ confout = ftp2fn(efSTO, NFILE, fnm); fprintf(stderr, "Writing generated configuration to %s\n", confout); const char* outputTitle = (bProt ? *top.name : "Generated by gmx solvate"); - write_sto_conf(confout, outputTitle, atoms, as_rvec_array(x.data()), - !v.empty() ? as_rvec_array(v.data()) : nullptr, pbcTypeForOutput, box); + write_sto_conf(confout, + outputTitle, + atoms, + as_rvec_array(x.data()), + !v.empty() ? as_rvec_array(v.data()) : nullptr, + pbcTypeForOutput, + box); /* print size of generated configuration */ fprintf(stderr, "\nOutput configuration contains %d atoms in %d residues\n", atoms->nr, atoms->nres); diff --git a/src/gromacs/gmxpreprocess/specbond.cpp b/src/gromacs/gmxpreprocess/specbond.cpp index 5e30f10c28..81385114a8 100644 --- a/src/gromacs/gmxpreprocess/specbond.cpp +++ b/src/gromacs/gmxpreprocess/specbond.cpp @@ -88,8 +88,7 @@ std::vector generateSpecialBonds() int nlines = get_lines(sbfile, &lines); for (int i = 0; (i < nlines); i++) { - if (sscanf(lines[i], "%s%s%d%s%s%d%lf%s%s", r1buf, a1buf, &nb1, r2buf, a2buf, &nb2, &length, - nr1buf, nr2buf) + if (sscanf(lines[i], "%s%s%d%s%s%d%lf%s%s", r1buf, a1buf, &nb1, r2buf, a2buf, &nb2, &length, nr1buf, nr2buf) != 9) { fprintf(stderr, "Invalid line '%s' in %s\n", lines[i], sbfile); @@ -115,8 +114,7 @@ std::vector generateSpecialBonds() { sfree(lines); } - fprintf(stderr, "%zu out of %d lines of %s converted successfully\n", specialBonds.size(), - nlines, sbfile); + fprintf(stderr, "%zu out of %d lines of %s converted successfully\n", specialBonds.size(), nlines, sbfile); return specialBonds; } @@ -178,7 +176,9 @@ static void rename_1res(t_atoms* pdba, int resind, const char* newres, bool bVer { if (bVerbose) { - printf("Using rtp entry %s for %s %d\n", newres, *pdba->resinfo[resind].name, + printf("Using rtp entry %s for %s %d\n", + newres, + *pdba->resinfo[resind].name, pdba->resinfo[resind].nr); } /* this used to free *resname, which messes up the symtab! */ @@ -242,7 +242,9 @@ std::vector makeDisulfideBonds(t_atoms* pdba, rvec x[], bool bInt int e = std::min(b + MAXCOL, nspec - 1); for (int i = b; (i < e); i++) { - sprintf(buf, "%s%d", *pdba->resinfo[pdba->atom[specialBondAtomIdxs[i]].resind].name, + sprintf(buf, + "%s%d", + *pdba->resinfo[pdba->atom[specialBondAtomIdxs[i]].resind].name, pdba->resinfo[specialBondResIdxs[i]].nr); fprintf(stderr, "%8s", buf); } @@ -252,8 +254,8 @@ std::vector makeDisulfideBonds(t_atoms* pdba, rvec x[], bool bInt e = std::min(b + MAXCOL, nspec - 1); for (int i = b; (i < e); i++) { - std::string buf = gmx::formatString("%s%d", *pdba->atomname[specialBondAtomIdxs[i]], - specialBondAtomIdxs[i] + 1); + std::string buf = gmx::formatString( + "%s%d", *pdba->atomname[specialBondAtomIdxs[i]], specialBondAtomIdxs[i] + 1); fprintf(stderr, "%8s", buf.c_str()); } fprintf(stderr, "\n"); @@ -262,11 +264,12 @@ std::vector makeDisulfideBonds(t_atoms* pdba, rvec x[], bool bInt for (int i = b + 1; (i < nspec); i++) { std::string buf = gmx::formatString( - "%s%d", *pdba->resinfo[pdba->atom[specialBondAtomIdxs[i]].resind].name, + "%s%d", + *pdba->resinfo[pdba->atom[specialBondAtomIdxs[i]].resind].name, pdba->resinfo[specialBondResIdxs[i]].nr); fprintf(stderr, "%8s", buf.c_str()); - buf = gmx::formatString("%s%d", *pdba->atomname[specialBondAtomIdxs[i]], - specialBondAtomIdxs[i] + 1); + buf = gmx::formatString( + "%s%d", *pdba->atomname[specialBondAtomIdxs[i]], specialBondAtomIdxs[i] + 1); fprintf(stderr, "%8s", buf.c_str()); int e2 = std::min(i, e); for (int j = b; (j < e2); j++) @@ -288,11 +291,17 @@ std::vector makeDisulfideBonds(t_atoms* pdba, rvec x[], bool bInt if (bonds.size() < specialBondAtomIdxs.size() && is_bond(specialBonds, pdba, ai, aj, d[i][j], &index_sb, &bSwap)) { - fprintf(stderr, "%s %s-%d %s-%d and %s-%d %s-%d%s", bInteractive ? "Link" : "Linking", + fprintf(stderr, + "%s %s-%d %s-%d and %s-%d %s-%d%s", + bInteractive ? "Link" : "Linking", *pdba->resinfo[pdba->atom[ai].resind].name, - pdba->resinfo[specialBondResIdxs[i]].nr, *pdba->atomname[ai], ai + 1, + pdba->resinfo[specialBondResIdxs[i]].nr, + *pdba->atomname[ai], + ai + 1, *pdba->resinfo[pdba->atom[aj].resind].name, - pdba->resinfo[specialBondResIdxs[j]].nr, *pdba->atomname[aj], aj + 1, + pdba->resinfo[specialBondResIdxs[j]].nr, + *pdba->atomname[aj], + aj + 1, bInteractive ? " (y/n) ?" : "...\n"); bool bDoit = bInteractive ? yesno() : true; @@ -308,17 +317,25 @@ std::vector makeDisulfideBonds(t_atoms* pdba, rvec x[], bool bInt /* rename residues */ if (bSwap) { - rename_1res(pdba, specialBondResIdxs[i], - specialBonds[index_sb].newSecondResidue.c_str(), bVerbose); - rename_1res(pdba, specialBondResIdxs[j], - specialBonds[index_sb].newFirstResidue.c_str(), bVerbose); + rename_1res(pdba, + specialBondResIdxs[i], + specialBonds[index_sb].newSecondResidue.c_str(), + bVerbose); + rename_1res(pdba, + specialBondResIdxs[j], + specialBonds[index_sb].newFirstResidue.c_str(), + bVerbose); } else { - rename_1res(pdba, specialBondResIdxs[i], - specialBonds[index_sb].newFirstResidue.c_str(), bVerbose); - rename_1res(pdba, specialBondResIdxs[j], - specialBonds[index_sb].newSecondResidue.c_str(), bVerbose); + rename_1res(pdba, + specialBondResIdxs[i], + specialBonds[index_sb].newFirstResidue.c_str(), + bVerbose); + rename_1res(pdba, + specialBondResIdxs[j], + specialBonds[index_sb].newSecondResidue.c_str(), + bVerbose); } } } diff --git a/src/gromacs/gmxpreprocess/ter_db.cpp b/src/gromacs/gmxpreprocess/ter_db.cpp index bdf1f3db8e..ee59938c25 100644 --- a/src/gromacs/gmxpreprocess/ter_db.cpp +++ b/src/gromacs/gmxpreprocess/ter_db.cpp @@ -120,7 +120,10 @@ static void read_atom(char* line, bool bAdd, std::string* nname, t_atom* a, Prep gmx_fatal(FARGS, "Reading Termini Database: expected %d or %d items of atom data in stead of %d " "on line\n%s", - 3, 4, nr, line); + 3, + 4, + nr, + line); } i = 0; if (!bAdd) @@ -166,8 +169,9 @@ static void print_ter_db(const char* ff, { fprintf(out, "[ %s ]\n", modification.name.c_str()); - if (std::any_of(modification.hack.begin(), modification.hack.end(), - [](const auto& mod) { return mod.type() == MoleculePatchType::Replace; })) + if (std::any_of(modification.hack.begin(), modification.hack.end(), [](const auto& mod) { + return mod.type() == MoleculePatchType::Replace; + })) { fprintf(out, "[ %s ]\n", kw_names[ekwRepl - ebtsNR - 1]); for (const auto& hack : modification.hack) @@ -179,8 +183,9 @@ static void print_ter_db(const char* ff, } } } - if (std::any_of(modification.hack.begin(), modification.hack.end(), - [](const auto& mod) { return mod.type() == MoleculePatchType::Add; })) + if (std::any_of(modification.hack.begin(), modification.hack.end(), [](const auto& mod) { + return mod.type() == MoleculePatchType::Add; + })) { fprintf(out, "[ %s ]\n", kw_names[ekwAdd - ebtsNR - 1]); for (const auto& hack : modification.hack) @@ -192,8 +197,9 @@ static void print_ter_db(const char* ff, } } } - if (std::any_of(modification.hack.begin(), modification.hack.end(), - [](const auto& mod) { return mod.type() == MoleculePatchType::Delete; })) + if (std::any_of(modification.hack.begin(), modification.hack.end(), [](const auto& mod) { + return mod.type() == MoleculePatchType::Delete; + })) { fprintf(out, "[ %s ]\n", kw_names[ekwDel - ebtsNR - 1]); for (const auto& hack : modification.hack) @@ -291,7 +297,8 @@ static void read_ter_db_file(const char* fn, gmx_fatal(FARGS, "Reading Termini Database '%s': " "expected atom name on line\n%s", - fn, line); + fn, + line); } hack->oname = buf; /* we only replace or delete one atom at a time */ @@ -309,8 +316,7 @@ static void read_ter_db_file(const char* fn, if (kwnr == ekwRepl || kwnr == ekwAdd) { hack->atom.emplace_back(); - read_atom(line + n, kwnr == ekwAdd, &hack->nname, &hack->atom.back(), atype, - &hack->cgnr); + read_atom(line + n, kwnr == ekwAdd, &hack->nname, &hack->atom.back(), atype, &hack->cgnr); if (hack->nname.empty()) { if (!hack->oname.empty()) @@ -322,7 +328,8 @@ static void read_ter_db_file(const char* fn, gmx_fatal(FARGS, "Reading Termini Database '%s': don't know which name the " "new atom should have on line\n%s", - fn, line); + fn, + line); } } } @@ -345,7 +352,10 @@ static void read_ter_db_file(const char* fn, gmx_fatal(FARGS, "Reading Termini Database '%s': expected %d atom names (found " "%d) on line\n%s", - fn, btsNiatoms[kwnr], j - 1, line); + fn, + btsNiatoms[kwnr], + j - 1, + line); } n += ni; } @@ -501,7 +511,9 @@ MoleculePatchDatabase* choose_ter(gmx::ArrayRef tb, cons for (const auto& modification : tb) { bool bIsZwitterion = (0 == gmx_wcmatch("*ZWITTERION*", modification->name.c_str())); - printf("%2d: %s%s\n", i, modification->name.c_str(), + printf("%2d: %s%s\n", + i, + modification->name.c_str(), bIsZwitterion ? " (only use with zwitterions containing exactly one residue)" : ""); i++; } diff --git a/src/gromacs/gmxpreprocess/tests/insert_molecules.cpp b/src/gromacs/gmxpreprocess/tests/insert_molecules.cpp index 53cf3080ea..97909b736f 100644 --- a/src/gromacs/gmxpreprocess/tests/insert_molecules.cpp +++ b/src/gromacs/gmxpreprocess/tests/insert_molecules.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2013,2014,2015,2016,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2015,2016,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -66,8 +66,9 @@ public: gmx::test::TestReferenceChecker rootChecker(this->rootChecker()); rootChecker.checkString(args.toString(), "CommandLine"); - ASSERT_EQ(0, gmx::test::CommandLineTestHelper::runModuleFactory( - &gmx::InsertMoleculesInfo::create, &cmdline)); + ASSERT_EQ(0, + gmx::test::CommandLineTestHelper::runModuleFactory( + &gmx::InsertMoleculesInfo::create, &cmdline)); checkOutputFiles(); } @@ -109,8 +110,9 @@ TEST_F(InsertMoleculesTest, InsertsMoleculesWithReplacement) TEST_F(InsertMoleculesTest, InsertsMoleculesIntoFixedPositions) { const char* const cmdline[] = { "insert-molecules", "-box", "4", "-seed", "1997" }; - const char* const positions[] = { "0.0 0.0 0.0", "1.0 2.0 3.0", "0.99 2.01 3.0", - "2.0 1.0 2.0" }; + const char* const positions[] = { + "0.0 0.0 0.0", "1.0 2.0 3.0", "0.99 2.01 3.0", "2.0 1.0 2.0" + }; setInputFile("-ci", "x0.gro"); setInputFileContents("-ip", "dat", positions); runTest(CommandLine(cmdline)); diff --git a/src/gromacs/gmxpreprocess/tests/readir.cpp b/src/gromacs/gmxpreprocess/tests/readir.cpp index e2591c7392..0ad5a321f3 100644 --- a/src/gromacs/gmxpreprocess/tests/readir.cpp +++ b/src/gromacs/gmxpreprocess/tests/readir.cpp @@ -94,8 +94,7 @@ public: TextWriter::writeFileFromString(inputMdpFilename, inputMdpFileContents); - get_ir(inputMdpFilename.c_str(), outputMdpFilename.c_str(), &mdModules_, &ir_, &opts_, - WriteMdpHeader::no, wi_); + get_ir(inputMdpFilename.c_str(), outputMdpFilename.c_str(), &mdModules_, &ir_, &opts_, WriteMdpHeader::no, wi_); check_ir(inputMdpFilename.c_str(), mdModules_.notifier(), &ir_, &opts_, wi_); // Now check diff --git a/src/gromacs/gmxpreprocess/tomorse.cpp b/src/gromacs/gmxpreprocess/tomorse.cpp index f49f44ec20..320911ea61 100644 --- a/src/gromacs/gmxpreprocess/tomorse.cpp +++ b/src/gromacs/gmxpreprocess/tomorse.cpp @@ -218,7 +218,8 @@ void convert_harmonics(gmx::ArrayRef mols, PreprocessingAto { int ni = harmonic->ai(); int nj = harmonic->aj(); - real edis = search_e_diss(n2m, t2m, + real edis = search_e_diss(n2m, + t2m, atype->atomNameFromAtomType(mol.atoms.atom[ni].type), atype->atomNameFromAtomType(mol.atoms.atom[nj].type)); if (edis != 0) @@ -239,8 +240,12 @@ void convert_harmonics(gmx::ArrayRef mols, PreprocessingAto } int newHarmonics = mol.interactions[bb].size(); - fprintf(stderr, "Converted %d out of %d %s to morse bonds for mol %d\n", - nrharm - newHarmonics, nrharm, interaction_function[bb].name, i); + fprintf(stderr, + "Converted %d out of %d %s to morse bonds for mol %d\n", + nrharm - newHarmonics, + nrharm, + interaction_function[bb].name, + i); } } i++; diff --git a/src/gromacs/gmxpreprocess/topdirs.cpp b/src/gromacs/gmxpreprocess/topdirs.cpp index a6139cf3c9..d72b4fa205 100644 --- a/src/gromacs/gmxpreprocess/topdirs.cpp +++ b/src/gromacs/gmxpreprocess/topdirs.cpp @@ -52,16 +52,48 @@ /* Must correspond to the Directive enum in grompp_impl.h */ static gmx::EnumerationArray directive_names = { - { "defaults", "atomtypes", "bondtypes", "constrainttypes", "pairtypes", "angletypes", - "dihedraltypes", "nonbond_params", "implicit_genborn_params", "implicit_surface_params", + { "defaults", + "atomtypes", + "bondtypes", + "constrainttypes", + "pairtypes", + "angletypes", + "dihedraltypes", + "nonbond_params", + "implicit_genborn_params", + "implicit_surface_params", "cmaptypes", /* All the directives above can not appear after moleculetype */ - "moleculetype", "atoms", "virtual_sites2", "virtual_sites3", "virtual_sites4", - "virtual_sitesn", "bonds", "exclusions", "pairs", "pairs_nb", "angles", "dihedrals", - "constraints", "settles", "polarization", "water_polarization", "thole_polarization", - "system", "molecules", "position_restraints", "angle_restraints", "angle_restraints_z", - "distance_restraints", "orientation_restraints", "dihedral_restraints", "cmap", - "intermolecular_interactions", "maxdirs", "invalid", "none" } + "moleculetype", + "atoms", + "virtual_sites2", + "virtual_sites3", + "virtual_sites4", + "virtual_sitesn", + "bonds", + "exclusions", + "pairs", + "pairs_nb", + "angles", + "dihedrals", + "constraints", + "settles", + "polarization", + "water_polarization", + "thole_polarization", + "system", + "molecules", + "position_restraints", + "angle_restraints", + "angle_restraints_z", + "distance_restraints", + "orientation_restraints", + "dihedral_restraints", + "cmap", + "intermolecular_interactions", + "maxdirs", + "invalid", + "none" } }; int ifunc_index(Directive d, int type) @@ -271,10 +303,8 @@ void DS_Init(DirStack** DS) // be in the same place that was valid in old versions (ie. child // directive of [atomtypes]) but any relevant case will // satisfy that. - set_nec(&(necessary[Directive::d_implicit_genborn_params]), Directive::d_atomtypes, - Directive::d_none); - set_nec(&(necessary[Directive::d_implicit_surface_params]), Directive::d_atomtypes, - Directive::d_none); + set_nec(&(necessary[Directive::d_implicit_genborn_params]), Directive::d_atomtypes, Directive::d_none); + set_nec(&(necessary[Directive::d_implicit_surface_params]), Directive::d_atomtypes, Directive::d_none); set_nec(&(necessary[Directive::d_cmaptypes]), Directive::d_atomtypes, Directive::d_none); set_nec(&(necessary[Directive::d_moleculetype]), Directive::d_atomtypes, Directive::d_none); set_nec(&(necessary[Directive::d_atoms]), Directive::d_moleculetype, Directive::d_none); @@ -283,8 +313,11 @@ void DS_Init(DirStack** DS) set_nec(&(necessary[Directive::d_vsites4]), Directive::d_atoms, Directive::d_none); set_nec(&(necessary[Directive::d_vsitesn]), Directive::d_atoms, Directive::d_none); set_nec(&(necessary[Directive::d_bonds]), Directive::d_atoms, Directive::d_none); - set_nec(&(necessary[Directive::d_exclusions]), Directive::d_bonds, Directive::d_constraints, - Directive::d_settles, Directive::d_none); + set_nec(&(necessary[Directive::d_exclusions]), + Directive::d_bonds, + Directive::d_constraints, + Directive::d_settles, + Directive::d_none); set_nec(&(necessary[Directive::d_pairs]), Directive::d_atoms, Directive::d_none); set_nec(&(necessary[Directive::d_pairs_nb]), Directive::d_atoms, Directive::d_none); set_nec(&(necessary[Directive::d_angles]), Directive::d_atoms, Directive::d_none); @@ -303,7 +336,8 @@ void DS_Init(DirStack** DS) set_nec(&(necessary[Directive::d_orientation_restraints]), Directive::d_atoms, Directive::d_none); set_nec(&(necessary[Directive::d_dihedral_restraints]), Directive::d_atoms, Directive::d_none); set_nec(&(necessary[Directive::d_cmap]), Directive::d_atoms, Directive::d_none); - set_nec(&(necessary[Directive::d_intermolecular_interactions]), Directive::d_molecules, + set_nec(&(necessary[Directive::d_intermolecular_interactions]), + Directive::d_molecules, Directive::d_none); } *DS = nullptr; diff --git a/src/gromacs/gmxpreprocess/topio.cpp b/src/gromacs/gmxpreprocess/topio.cpp index 316656d7a6..998fc40edd 100644 --- a/src/gromacs/gmxpreprocess/topio.cpp +++ b/src/gromacs/gmxpreprocess/topio.cpp @@ -164,8 +164,13 @@ double check_mol(const gmx_mtop_t* mtop, warninp* wi) if (((m <= 0.0) || (mB <= 0.0)) && ((pt == eptAtom) || (pt == eptNucleus))) { ri = atoms->atom[i].resind; - sprintf(buf, "atom %s (Res %s-%d) has mass %g (state A) / %g (state B)\n", - *(atoms->atomname[i]), *(atoms->resinfo[ri].name), atoms->resinfo[ri].nr, m, mB); + sprintf(buf, + "atom %s (Res %s-%d) has mass %g (state A) / %g (state B)\n", + *(atoms->atomname[i]), + *(atoms->resinfo[ri].name), + atoms->resinfo[ri].nr, + m, + mB); warning_error(wi, buf); } else if (((m != 0) || (mB != 0)) && (pt == eptVSite)) @@ -175,7 +180,11 @@ double check_mol(const gmx_mtop_t* mtop, warninp* wi) "virtual site %s (Res %s-%d) has non-zero mass %g (state A) / %g (state " "B)\n" " Check your topology.\n", - *(atoms->atomname[i]), *(atoms->resinfo[ri].name), atoms->resinfo[ri].nr, m, mB); + *(atoms->atomname[i]), + *(atoms->resinfo[ri].name), + atoms->resinfo[ri].nr, + m, + mB); warning_error(wi, buf); /* The following statements make LINCS break! */ /* atoms->atom[i].m=0; */ @@ -553,8 +562,10 @@ static char** read_topol(const char* infile, { /* we should print here which directives should have been present, and which actually are */ - gmx_fatal(FARGS, "%s\nInvalid order for directive %s", - cpp_error(&handle, eCPP_SYNTAX), dir2str(newd)); + gmx_fatal(FARGS, + "%s\nInvalid order for directive %s", + cpp_error(&handle, eCPP_SYNTAX), + dir2str(newd)); /* d = Directive::d_invalid; */ } @@ -586,12 +597,13 @@ static char** read_topol(const char* infile, case Directive::d_defaults: if (bReadDefaults) { - gmx_fatal(FARGS, "%s\nFound a second defaults directive.\n", + gmx_fatal(FARGS, + "%s\nFound a second defaults directive.\n", cpp_error(&handle, eCPP_SYNTAX)); } bReadDefaults = TRUE; - nscan = sscanf(pline, "%s%s%s%lf%lf%lf", nb_str, comb_str, genpairs, - &fLJ, &fQQ, &fPOW); + nscan = sscanf( + pline, "%s%s%s%lf%lf%lf", nb_str, comb_str, genpairs, &fLJ, &fQQ, &fPOW); if (nscan < 2) { too_few(wi); @@ -630,8 +642,14 @@ static char** read_topol(const char* infile, break; case Directive::d_atomtypes: - push_at(symtab, atypes, &bondAtomType, pline, nb_funct, &nbparam, - bGenPairs ? &pair : nullptr, wi); + push_at(symtab, + atypes, + &bondAtomType, + pline, + nb_funct, + &nbparam, + bGenPairs ? &pair : nullptr, + wi); break; case Directive::d_bondtypes: // Intended to fall through @@ -686,32 +704,36 @@ static char** read_topol(const char* infile, || opts->couple_lam1 == ecouplamNONE || opts->couple_lam1 == ecouplamQ)) { - dcatt = add_atomtype_decoupled(symtab, atypes, &nbparam, - bGenPairs ? &pair : nullptr); + dcatt = add_atomtype_decoupled( + symtab, atypes, &nbparam, bGenPairs ? &pair : nullptr); } ntype = atypes->size(); ncombs = (ntype * (ntype + 1)) / 2; - generate_nbparams(*combination_rule, nb_funct, - &(interactions[nb_funct]), atypes, wi); + generate_nbparams( + *combination_rule, nb_funct, &(interactions[nb_funct]), atypes, wi); ncopy = copy_nbparams(nbparam, nb_funct, &(interactions[nb_funct]), ntype); GMX_LOG(logger.info) .asParagraph() .appendTextFormatted( "Generated %d of the %d non-bonded parameter " "combinations", - ncombs - ncopy, ncombs); + ncombs - ncopy, + ncombs); free_nbparam(nbparam, ntype); if (bGenPairs) { - gen_pairs((interactions[nb_funct]), &(interactions[F_LJ14]), - fudgeLJ, *combination_rule); + gen_pairs((interactions[nb_funct]), + &(interactions[F_LJ14]), + fudgeLJ, + *combination_rule); ncopy = copy_nbparams(pair, nb_funct, &(interactions[F_LJ14]), ntype); GMX_LOG(logger.info) .asParagraph() .appendTextFormatted( "Generated %d of the %d 1-4 parameter " "combinations", - ncombs - ncopy, ncombs); + ncombs - ncopy, + ncombs); free_nbparam(pair, ntype); } /* Copy GBSA parameters to atomtype array? */ @@ -737,15 +759,35 @@ static char** read_topol(const char* infile, GMX_RELEASE_ASSERT( mi0, "Need to have a valid MoleculeInformation object to work on"); - push_bond(d, interactions, mi0->interactions, &(mi0->atoms), atypes, - pline, FALSE, bGenPairs, *fudgeQQ, bZero, &bWarn_copy_A_B, wi); + push_bond(d, + interactions, + mi0->interactions, + &(mi0->atoms), + atypes, + pline, + FALSE, + bGenPairs, + *fudgeQQ, + bZero, + &bWarn_copy_A_B, + wi); break; case Directive::d_pairs_nb: GMX_RELEASE_ASSERT( mi0, "Need to have a valid MoleculeInformation object to work on"); - push_bond(d, interactions, mi0->interactions, &(mi0->atoms), atypes, - pline, FALSE, FALSE, 1.0, bZero, &bWarn_copy_A_B, wi); + push_bond(d, + interactions, + mi0->interactions, + &(mi0->atoms), + atypes, + pline, + FALSE, + FALSE, + 1.0, + bZero, + &bWarn_copy_A_B, + wi); break; case Directive::d_vsites2: @@ -768,8 +810,18 @@ static char** read_topol(const char* infile, GMX_RELEASE_ASSERT( mi0, "Need to have a valid MoleculeInformation object to work on"); - push_bond(d, interactions, mi0->interactions, &(mi0->atoms), atypes, - pline, TRUE, bGenPairs, *fudgeQQ, bZero, &bWarn_copy_A_B, wi); + push_bond(d, + interactions, + mi0->interactions, + &(mi0->atoms), + atypes, + pline, + TRUE, + bGenPairs, + *fudgeQQ, + bZero, + &bWarn_copy_A_B, + wi); break; case Directive::d_cmap: GMX_RELEASE_ASSERT( @@ -828,7 +880,8 @@ static char** read_topol(const char* infile, .asParagraph() .appendTextFormatted( "Excluding %d bonded neighbours molecule type '%s'", - mi0->nrexcl, *mi0->name); + mi0->nrexcl, + *mi0->name); sum_q(&mi0->atoms, nrcopies, &qt, &qBt); if (!mi0->bProcessed) { @@ -838,9 +891,15 @@ static char** read_topol(const char* infile, if (bCouple) { - convert_moltype_couple(mi0, dcatt, *fudgeQQ, opts->couple_lam0, - opts->couple_lam1, opts->bCoupleIntra, - nb_funct, &(interactions[nb_funct]), wi); + convert_moltype_couple(mi0, + dcatt, + *fudgeQQ, + opts->couple_lam0, + opts->couple_lam1, + opts->bCoupleIntra, + nb_funct, + &(interactions[nb_funct]), + wi); } stupid_fill_block(&mi0->mols, mi0->atoms.nr, TRUE); mi0->bProcessed = TRUE; @@ -918,8 +977,8 @@ static char** read_topol(const char* infile, } GMX_LOG(logger.info) .asParagraph() - .appendTextFormatted("Coupling %d copies of molecule type '%s'", nmol_couple, - opts->couple_moltype); + .appendTextFormatted( + "Coupling %d copies of molecule type '%s'", nmol_couple, opts->couple_moltype); } /* this is not very clean, but fixes core dump on empty system name */ @@ -935,8 +994,7 @@ static char** read_topol(const char* infile, } if (fabs(qBt) > 1e-4 && !gmx_within_tol(qBt, qt, 1e-6)) { - sprintf(warn_buf, "State B has non-zero total charge: %.6f\n%s\n", qBt, - floating_point_arithmetic_tip); + sprintf(warn_buf, "State B has non-zero total charge: %.6f\n%s\n", qBt, floating_point_arithmetic_tip); warning_note(wi, warn_buf); } if (usingFullRangeElectrostatics && (fabs(qt) > 1e-4 || fabs(qBt) > 1e-4)) @@ -995,10 +1053,26 @@ char** do_top(bool bVerbose, { GMX_LOG(logger.info).asParagraph().appendTextFormatted("processing topology..."); } - title = read_topol(topfile, tmpfile, opts->define, opts->include, symtab, atypes, molinfo, - intermolecular_interactions, interactions, combination_rule, repulsion_power, - opts, fudgeQQ, molblock, ffParametrizedWithHBondConstraints, - ir->efep != efepNO, bZero, EEL_FULL(ir->coulombtype), wi, logger); + title = read_topol(topfile, + tmpfile, + opts->define, + opts->include, + symtab, + atypes, + molinfo, + intermolecular_interactions, + interactions, + combination_rule, + repulsion_power, + opts, + fudgeQQ, + molblock, + ffParametrizedWithHBondConstraints, + ir->efep != efepNO, + bZero, + EEL_FULL(ir->coulombtype), + wi, + logger); if ((*combination_rule != eCOMB_GEOMETRIC) && (ir->vdwtype == evdwUSER)) { diff --git a/src/gromacs/gmxpreprocess/toppush.cpp b/src/gromacs/gmxpreprocess/toppush.cpp index 1c61976460..0abf710622 100644 --- a/src/gromacs/gmxpreprocess/toppush.cpp +++ b/src/gromacs/gmxpreprocess/toppush.cpp @@ -304,9 +304,20 @@ void push_at(t_symtab* symtab, snew(atom, 1); /* First assign input line to temporary array */ - nfields = sscanf(line, "%s%s%s%s%s%s%s%s%s%s%s%s", tmpfield[0], tmpfield[1], tmpfield[2], - tmpfield[3], tmpfield[4], tmpfield[5], tmpfield[6], tmpfield[7], tmpfield[8], - tmpfield[9], tmpfield[10], tmpfield[11]); + nfields = sscanf(line, + "%s%s%s%s%s%s%s%s%s%s%s%s", + tmpfield[0], + tmpfield[1], + tmpfield[2], + tmpfield[3], + tmpfield[4], + tmpfield[5], + tmpfield[6], + tmpfield[7], + tmpfield[8], + tmpfield[9], + tmpfield[10], + tmpfield[11]); /* Comments on optional fields in the atomtypes section: * @@ -373,8 +384,8 @@ void push_at(t_symtab* symtab, { if (have_bonded_type) { - nread = sscanf(line, "%s%s%d%lf%lf%s%lf%lf", type, btype, &atomnr, &m, &q, - ptype, &c[0], &c[1]); + nread = sscanf( + line, "%s%s%d%lf%lf%s%lf%lf", type, btype, &atomnr, &m, &q, ptype, &c[0], &c[1]); if (nread < 8) { too_few(wi); @@ -435,8 +446,8 @@ void push_at(t_symtab* symtab, { if (have_bonded_type) { - nread = sscanf(line, "%s%s%d%lf%lf%s%lf%lf%lf", type, btype, &atomnr, &m, &q, - ptype, &c[0], &c[1], &c[2]); + nread = sscanf( + line, "%s%s%d%lf%lf%s%lf%lf%lf", type, btype, &atomnr, &m, &q, ptype, &c[0], &c[1], &c[2]); if (nread < 9) { too_few(wi); @@ -446,8 +457,8 @@ void push_at(t_symtab* symtab, else { /* have_atomic_number && !have_bonded_type */ - nread = sscanf(line, "%s%d%lf%lf%s%lf%lf%lf", type, &atomnr, &m, &q, ptype, - &c[0], &c[1], &c[2]); + nread = sscanf( + line, "%s%d%lf%lf%s%lf%lf%lf", type, &atomnr, &m, &q, ptype, &c[0], &c[1], &c[2]); if (nread < 8) { too_few(wi); @@ -460,8 +471,8 @@ void push_at(t_symtab* symtab, if (have_bonded_type) { /* !have_atomic_number && have_bonded_type */ - nread = sscanf(line, "%s%s%lf%lf%s%lf%lf%lf", type, btype, &m, &q, ptype, &c[0], - &c[1], &c[2]); + nread = sscanf( + line, "%s%s%lf%lf%s%lf%lf%lf", type, btype, &m, &q, ptype, &c[0], &c[1], &c[2]); if (nread < 8) { too_few(wi); @@ -634,9 +645,9 @@ static void push_bondtype(InteractionsOfType* bt, GMX_ASSERT(nrfp <= MAXFORCEPARAM, "This is ensured in other places, but we need this assert to keep the clang " "analyzer happy"); - const bool identicalParameters = std::equal( - bt->interactionTypes[i].forceParam().begin(), - bt->interactionTypes[i].forceParam().begin() + nrfp, b.forceParam().begin()); + const bool identicalParameters = std::equal(bt->interactionTypes[i].forceParam().begin(), + bt->interactionTypes[i].forceParam().begin() + nrfp, + b.forceParam().begin()); if (!bAllowRepeat || identicalParameters) { @@ -813,8 +824,8 @@ void push_bt(Directive d, nrfpA = interaction_function[ftype].nrfpA; strcpy(f1, formnl[nral]); strcat(f1, formlf); - if ((nn = sscanf(line, f1, &c[0], &c[1], &c[2], &c[3], &c[4], &c[5], &c[6], &c[7], &c[8], &c[9], - &c[10], &c[11], &c[12])) + if ((nn = sscanf( + line, f1, &c[0], &c[1], &c[2], &c[3], &c[4], &c[5], &c[6], &c[7], &c[8], &c[9], &c[10], &c[11], &c[12])) != nrfp) { if (nn == nrfpA) @@ -961,8 +972,8 @@ void push_dihedraltype(Directive d, strcat(f1, formlf[nrfp - 1]); /* Check number of parameters given */ - if ((nn = sscanf(line, f1, &c[0], &c[1], &c[2], &c[3], &c[4], &c[5], &c[6], &c[7], &c[8], &c[9], - &c[10], &c[11])) + if ((nn = sscanf( + line, f1, &c[0], &c[1], &c[2], &c[3], &c[4], &c[5], &c[6], &c[7], &c[8], &c[9], &c[10], &c[11])) != nrfp) { if (nn == nrfpA) @@ -1223,7 +1234,11 @@ void push_cmaptype(Directive d, { auto message = gmx::formatString("Error in reading cmap parameter for angle %s %s %s %s %s", - alc[0], alc[1], alc[2], alc[3], alc[4]); + alc[0], + alc[1], + alc[2], + alc[3], + alc[4]); warning_error(wi, message); } } @@ -1275,8 +1290,8 @@ void push_cmaptype(Directive d, /* Check for the correct number of atoms (again) */ if (bt[F_CMAP].nct() != nct) { - auto message = gmx::formatString("Incorrect number of atom types (%d) in cmap type %d\n", - nct, bt[F_CMAP].cmapAngles); + auto message = gmx::formatString( + "Incorrect number of atom types (%d) in cmap type %d\n", nct, bt[F_CMAP].cmapAngles); warning_error(wi, message); } std::vector atomTypes = @@ -1315,7 +1330,8 @@ static void push_atom_now(t_symtab* symtab, auto message = gmx::formatString( "Atoms in the .top are not numbered consecutively from 1 (rather, " "atomnr = %d, while at->nr = %d)", - atomnr, at->nr); + atomnr, + at->nr); warning_error_and_exit(wi, message, FARGS); } @@ -1452,8 +1468,23 @@ void push_atom(t_symtab* symtab, t_atoms* at, PreprocessingAtomTypes* atypes, ch } } - push_atom_now(symtab, at, atomnr, atypes->atomNumberFromAtomType(type), type, ctype, ptype, - resnumberic, resname, name, m0, q0, typeB, typeB == type ? ctype : ctypeB, mB, qB, wi); + push_atom_now(symtab, + at, + atomnr, + atypes->atomNumberFromAtomType(type), + type, + ctype, + ptype, + resnumberic, + resname, + name, + m0, + q0, + typeB, + typeB == type ? ctype : ctypeB, + mB, + qB, + wi); } void push_molt(t_symtab* symtab, std::vector* mol, char* line, warninp* wi) @@ -1467,8 +1498,8 @@ void push_molt(t_symtab* symtab, std::vector* mol, char* li } /* Test if this moleculetype overwrites another */ - const auto found = std::find_if(mol->begin(), mol->end(), - [&type](const auto& m) { return strcmp(*(m.name), type) == 0; }); + const auto found = std::find_if( + mol->begin(), mol->end(), [&type](const auto& m) { return strcmp(*(m.name), type) == 0; }); if (found != mol->end()) { auto message = gmx::formatString("moleculetype %s is redefined", type); @@ -1574,7 +1605,8 @@ static bool default_nb_params(int ftype, if (!bFound) { auto foundParameter = - std::find_if(bt[ftype].interactionTypes.begin(), bt[ftype].interactionTypes.end(), + std::find_if(bt[ftype].interactionTypes.begin(), + bt[ftype].interactionTypes.end(), [¶mAtoms, &at, &bB](const auto& param) { return findIfAllNBAtomsMatch(param.atoms(), paramAtoms, at, bB); }); @@ -1661,8 +1693,12 @@ static bool default_cmap_params(gmx::ArrayRef bondtype, /* If we did not find a matching type for this cmap torsion */ if (!bFound) { - auto message = gmx::formatString("Unknown cmap torsion between atoms %d %d %d %d %d", p->ai() + 1, - p->aj() + 1, p->ak() + 1, p->al() + 1, p->am() + 1); + auto message = gmx::formatString("Unknown cmap torsion between atoms %d %d %d %d %d", + p->ai() + 1, + p->aj() + 1, + p->ak() + 1, + p->al() + 1, + p->am() + 1); warning_error_and_exit(wi, message, FARGS); } @@ -1704,15 +1740,21 @@ static int findNumberOfDihedralAtomMatches(const InteractionOfType& currentParam { if (bB) { - return natom_match(currentParamFromParameterArray, at->atom[parameterToAdd.ai()].typeB, - at->atom[parameterToAdd.aj()].typeB, at->atom[parameterToAdd.ak()].typeB, - at->atom[parameterToAdd.al()].typeB, atypes); + return natom_match(currentParamFromParameterArray, + at->atom[parameterToAdd.ai()].typeB, + at->atom[parameterToAdd.aj()].typeB, + at->atom[parameterToAdd.ak()].typeB, + at->atom[parameterToAdd.al()].typeB, + atypes); } else { - return natom_match(currentParamFromParameterArray, at->atom[parameterToAdd.ai()].type, - at->atom[parameterToAdd.aj()].type, at->atom[parameterToAdd.ak()].type, - at->atom[parameterToAdd.al()].type, atypes); + return natom_match(currentParamFromParameterArray, + at->atom[parameterToAdd.ai()].type, + at->atom[parameterToAdd.aj()].type, + at->atom[parameterToAdd.ak()].type, + at->atom[parameterToAdd.al()].type, + atypes); } } @@ -1782,7 +1824,8 @@ static std::vector::iterator defaultInteractionsOfType(int ft auto pos = bt[ftype].interactionTypes.begin(); while (pos != bt[ftype].interactionTypes.end() && nmatch_max < 4) { - pos = std::find_if(bt[ftype].interactionTypes.begin(), bt[ftype].interactionTypes.end(), + pos = std::find_if(bt[ftype].interactionTypes.begin(), + bt[ftype].interactionTypes.end(), [&p, &at, &atypes, &bB, &nmatch_max](const auto& param) { return (findNumberOfDihedralAtomMatches(param, p, at, atypes, bB) > nmatch_max); @@ -1829,11 +1872,12 @@ static std::vector::iterator defaultInteractionsOfType(int ft else /* Not a dihedral */ { gmx::ArrayRef atomParam = p.atoms(); - auto found = std::find_if( - bt[ftype].interactionTypes.begin(), bt[ftype].interactionTypes.end(), - [&atomParam, &at, &atypes, &bB](const auto& param) { - return findIfAllParameterAtomsMatch(param.atoms(), atomParam, at, atypes, bB); - }); + auto found = std::find_if(bt[ftype].interactionTypes.begin(), + bt[ftype].interactionTypes.end(), + [&atomParam, &at, &atypes, &bB](const auto& param) { + return findIfAllParameterAtomsMatch( + param.atoms(), atomParam, at, atypes, bB); + }); if (found != bt[ftype].interactionTypes.end()) { nparam_found = 1; @@ -1944,7 +1988,11 @@ void push_bond(Directive d, "This probably means that you have inserted topology section \"%s\"\n" "in a part belonging to a different molecule than you intended to.\n" "In that case move the \"%s\" section to the right molecule.", - aa[i], dir2str(d), at->nr, dir2str(d), dir2str(d)); + aa[i], + dir2str(d), + at->nr, + dir2str(d), + dir2str(d)); warning_error_and_exit(wi, message, FARGS); } for (int j = i + 1; (j < nral); j++) @@ -2056,8 +2104,21 @@ void push_bond(Directive d, strcpy(format, asformat[nral_fmt - 1]); strcat(format, ccformat); - nread = sscanf(line, format, &cc[0], &cc[1], &cc[2], &cc[3], &cc[4], &cc[5], &cc[6], &cc[7], - &cc[8], &cc[9], &cc[10], &cc[11], &cc[12]); + nread = sscanf(line, + format, + &cc[0], + &cc[1], + &cc[2], + &cc[3], + &cc[4], + &cc[5], + &cc[6], + &cc[7], + &cc[8], + &cc[9], + &cc[10], + &cc[11], + &cc[12]); if ((nread == NRFPA(ftype)) && (NRFPB(ftype) != 0)) { @@ -2100,7 +2161,10 @@ void push_bond(Directive d, auto message = gmx::formatString( "Incorrect number of parameters - found %d, expected %d " "or %d for %s (after the function type).", - nread, NRFPA(ftype), NRFP(ftype), interaction_function[ftype].longname); + nread, + NRFPA(ftype), + NRFP(ftype), + interaction_function[ftype].longname); warning_error_and_exit(wi, message, FARGS); } @@ -2166,7 +2230,8 @@ void push_bond(Directive d, { if (bZero) { - fprintf(stderr, "NOTE: No default %s types, using zeroes\n", + fprintf(stderr, + "NOTE: No default %s types, using zeroes\n", interaction_function[ftype].longname); } else @@ -2214,7 +2279,8 @@ void push_bond(Directive d, if ((ftype == F_PDIHS || ftype == F_ANGRES || ftype == F_ANGRESZ) && paramValue[5] != paramValue[2]) { auto message = gmx::formatString("%s multiplicity can not be perturbed %f!=%f", - interaction_function[ftype].longname, paramValue[2], + interaction_function[ftype].longname, + paramValue[2], paramValue[5]); warning_error_and_exit(wi, message, FARGS); } @@ -2223,7 +2289,8 @@ void push_bond(Directive d, { auto message = gmx::formatString("%s table number can not be perturbed %d!=%d", interaction_function[ftype].longname, - gmx::roundToInt(param.c0()), gmx::roundToInt(param.c0())); + gmx::roundToInt(param.c0()), + gmx::roundToInt(param.c0())); warning_error_and_exit(wi, message, FARGS); } @@ -2313,7 +2380,11 @@ void push_cmap(Directive d, "This probably means that you have inserted topology section \"%s\"\n" "in a part belonging to a different molecule than you intended to.\n" "In that case move the \"%s\" section to the right molecule.", - aa[i], dir2str(d), at->nr, dir2str(d), dir2str(d)); + aa[i], + dir2str(d), + at->nr, + dir2str(d), + dir2str(d)); warning_error_and_exit(wi, message, FARGS); } @@ -2348,9 +2419,13 @@ void push_cmap(Directive d, else { /* This is essentially the same check as in default_cmap_params() done one more time */ - auto message = gmx::formatString( - "Unable to assign a cmap type to torsion %d %d %d %d and %d\n", param.ai() + 1, - param.aj() + 1, param.ak() + 1, param.al() + 1, param.am() + 1); + auto message = + gmx::formatString("Unable to assign a cmap type to torsion %d %d %d %d and %d\n", + param.ai() + 1, + param.aj() + 1, + param.ak() + 1, + param.al() + 1, + param.am() + 1); warning_error_and_exit(wi, message, FARGS); } } @@ -2410,7 +2485,8 @@ void push_vsitesn(Directive d, gmx::ArrayRef bond, t_atoms* auto message = gmx::formatString( "No weight or negative weight found for vsiten " "constructing atom %d (atom index %d)", - nj + 1, atc[nj] + 1); + nj + 1, + atc[nj] + 1); warning_error_and_exit(wi, message, FARGS); } break; @@ -2498,7 +2574,9 @@ void push_mol(gmx::ArrayRef mols, char* pline, int* whichmo "For moleculetype '%s' in [ system ] %d case insensitive " "matches, but %d case sensitive matches were found. Check " "the case of the characters in the moleculetypes.", - type, nrci, nrcs); + type, + nrci, + nrcs); warning_error_and_exit(wi, message, FARGS); } if (nrci == 1) @@ -2602,8 +2680,9 @@ static void convert_pairs_to_pairsQ(gmx::ArrayRef interactio for (const auto& param : paramp1) { - std::vector forceParam = { fudgeQQ, atoms->atom[param.ai()].q, - atoms->atom[param.aj()].q, param.c0(), param.c1() }; + std::vector forceParam = { + fudgeQQ, atoms->atom[param.ai()].q, atoms->atom[param.aj()].q, param.c0(), param.c1() + }; paramnew.emplace_back(InteractionOfType(param.atoms(), forceParam, "")); } @@ -2651,7 +2730,9 @@ static void generate_LJCpairsNB(MoleculeInformation* mol, int nb_funct, Interact } std::vector atoms = { i, j }; std::vector forceParam = { - atom[i].q, atom[j].q, nbp->interactionTypes[ntype * atom[i].type + atom[j].type].c0(), + atom[i].q, + atom[j].q, + nbp->interactionTypes[ntype * atom[i].type + atom[j].type].c0(), nbp->interactionTypes[ntype * atom[i].type + atom[j].type].c1() }; add_param_to_list(&mol->interactions[F_LJC_PAIRS_NB], InteractionOfType(atoms, forceParam)); @@ -2698,7 +2779,9 @@ static void decouple_atoms(t_atoms* atoms, "charges and/or atom types set in the topology file as well " "as through the mdp option '%s'. You can not use both " "these methods simultaneously.", - i + 1, mol_name, "couple-moltype"); + i + 1, + mol_name, + "couple-moltype"); warning_error_and_exit(wi, message, FARGS); } diff --git a/src/gromacs/gmxpreprocess/topshake.cpp b/src/gromacs/gmxpreprocess/topshake.cpp index d1c8abba67..acea8377c5 100644 --- a/src/gromacs/gmxpreprocess/topshake.cpp +++ b/src/gromacs/gmxpreprocess/topshake.cpp @@ -130,8 +130,8 @@ void make_shake(gmx::ArrayRef plist, t_atoms* atoms, int nsh #ifdef DEBUG GMX_LOG(logger.info) .asParagraph() - .appendTextFormatted("Angle: %d-%d-%d", ang->ai(), - ang->aj(), ang->ak()); + .appendTextFormatted( + "Angle: %d-%d-%d", ang->ai(), ang->aj(), ang->ak()); #endif int numhydrogens = count_hydrogens(info, 3, ang->atoms()); if ((nshake == eshALLANGLES) || (numhydrogens > 1) @@ -178,7 +178,8 @@ void make_shake(gmx::ArrayRef plist, t_atoms* atoms, int nsh GMX_LOG(logger.info) .asParagraph() .appendTextFormatted("p: %d, q: %d, dist: %12.5e", - atomNumbers[0], atomNumbers[1], + atomNumbers[0], + atomNumbers[1], forceParm[0]); #endif add_param_to_list(&(plist[F_CONSTR]), diff --git a/src/gromacs/gmxpreprocess/toputil.cpp b/src/gromacs/gmxpreprocess/toputil.cpp index 10ebbfce3e..af5558b48e 100644 --- a/src/gromacs/gmxpreprocess/toputil.cpp +++ b/src/gromacs/gmxpreprocess/toputil.cpp @@ -252,8 +252,19 @@ void print_atoms(FILE* out, PreprocessingAtomTypes* atype, t_atoms* at, int* cgn as = dir2str(Directive::d_atoms); fprintf(out, "[ %s ]\n", as); - fprintf(out, "; %4s %10s %6s %7s%6s %6s %10s %10s %6s %10s %10s\n", "nr", "type", "resnr", - "residue", "atom", "cgnr", "charge", "mass", "typeB", "chargeB", "massB"); + fprintf(out, + "; %4s %10s %6s %7s%6s %6s %10s %10s %6s %10s %10s\n", + "nr", + "type", + "resnr", + "residue", + "atom", + "cgnr", + "charge", + "mass", + "typeB", + "chargeB", + "massB"); qtot = 0; @@ -266,8 +277,11 @@ void print_atoms(FILE* out, PreprocessingAtomTypes* atype, t_atoms* at, int* cgn if ((i == 0 || ri != at->atom[i - 1].resind) && at->resinfo[ri].rtp != nullptr) { qres = get_residue_charge(at, i); - fprintf(out, "; residue %3d %-3s rtp %-4s q ", at->resinfo[ri].nr, - *at->resinfo[ri].name, *at->resinfo[ri].rtp); + fprintf(out, + "; residue %3d %-3s rtp %-4s q ", + at->resinfo[ri].nr, + *at->resinfo[ri].name, + *at->resinfo[ri].rtp); if (fabs(qres) < 0.001) { fprintf(out, " %s", "0.0"); @@ -287,11 +301,18 @@ void print_atoms(FILE* out, PreprocessingAtomTypes* atype, t_atoms* at, int* cgn /* This is true by construction, but static analysers don't know */ GMX_ASSERT(!bRTPresname || at->resinfo[at->atom[i].resind].rtp, "-rtpres did not have residue name available"); - fprintf(out, "%6d %10s %6d%c %5s %6s %6d %10g %10g", i + 1, tpnmA, at->resinfo[ri].nr, + fprintf(out, + "%6d %10s %6d%c %5s %6s %6d %10g %10g", + i + 1, + tpnmA, + at->resinfo[ri].nr, at->resinfo[ri].ic, bRTPresname ? *(at->resinfo[at->atom[i].resind].rtp) : *(at->resinfo[at->atom[i].resind].name), - *(at->atomname[i]), cgnr[i], at->atom[i].q, at->atom[i].m); + *(at->atomname[i]), + cgnr[i], + at->atom[i].q, + at->atom[i].m); if (PERTURBED(at->atom[i])) { tpB = at->atom[i].typeB; diff --git a/src/gromacs/gmxpreprocess/vsite_parm.cpp b/src/gromacs/gmxpreprocess/vsite_parm.cpp index 8d4669f734..3ddd90b761 100644 --- a/src/gromacs/gmxpreprocess/vsite_parm.cpp +++ b/src/gromacs/gmxpreprocess/vsite_parm.cpp @@ -305,8 +305,7 @@ static void print_bad(FILE* fp, fprintf(fp, "angles:"); for (const auto& angle : angles) { - fprintf(fp, " %d-%d-%d (%g)", angle.ai() + 1, angle.aj() + 1, angle.ak() + 1, - angle.parameterValue()); + fprintf(fp, " %d-%d-%d (%g)", angle.ai() + 1, angle.aj() + 1, angle.ak() + 1, angle.parameterValue()); } fprintf(fp, "\n"); } @@ -315,8 +314,13 @@ static void print_bad(FILE* fp, fprintf(fp, "idihs:"); for (const auto& idih : idihs) { - fprintf(fp, " %d-%d-%d-%d (%g)", idih.ai() + 1, idih.aj() + 1, idih.ak() + 1, - idih.al() + 1, idih.parameterValue()); + fprintf(fp, + " %d-%d-%d-%d (%g)", + idih.ai() + 1, + idih.aj() + 1, + idih.ak() + 1, + idih.al() + 1, + idih.parameterValue()); } fprintf(fp, "\n"); } @@ -417,12 +421,12 @@ static bool calc_vsite3_param(PreprocessingAtomTypes* atypes /* check if this is part of a NH3 , NH2-umbrella or CH3 group, * i.e. if atom k and l are dummy masses (MNH* or MCH3*) */ bXH3 = ((gmx::equalCaseInsensitive(get_atomtype_name_AB(&at->atom[vsite->ak()], atypes), "MNH", 3)) - && (gmx::equalCaseInsensitive(get_atomtype_name_AB(&at->atom[vsite->al()], atypes), - "MNH", 3))) - || ((gmx::equalCaseInsensitive(get_atomtype_name_AB(&at->atom[vsite->ak()], atypes), - "MCH3", 4)) - && (gmx::equalCaseInsensitive(get_atomtype_name_AB(&at->atom[vsite->al()], atypes), - "MCH3", 4))); + && (gmx::equalCaseInsensitive( + get_atomtype_name_AB(&at->atom[vsite->al()], atypes), "MNH", 3))) + || ((gmx::equalCaseInsensitive( + get_atomtype_name_AB(&at->atom[vsite->ak()], atypes), "MCH3", 4)) + && (gmx::equalCaseInsensitive( + get_atomtype_name_AB(&at->atom[vsite->al()], atypes), "MCH3", 4))); bjk = get_bond_length(bonds, vsite->aj(), vsite->ak()); bjl = get_bond_length(bonds, vsite->aj(), vsite->al()); @@ -559,12 +563,12 @@ static bool calc_vsite3out_param(PreprocessingAtomTypes* aty /* check if this is part of a NH2-umbrella, NH3 or CH3 group, * i.e. if atom k and l are dummy masses (MNH* or MCH3*) */ bXH3 = ((gmx::equalCaseInsensitive(get_atomtype_name_AB(&at->atom[vsite->ak()], atypes), "MNH", 3)) - && (gmx::equalCaseInsensitive(get_atomtype_name_AB(&at->atom[vsite->al()], atypes), - "MNH", 3))) - || ((gmx::equalCaseInsensitive(get_atomtype_name_AB(&at->atom[vsite->ak()], atypes), - "MCH3", 4)) - && (gmx::equalCaseInsensitive(get_atomtype_name_AB(&at->atom[vsite->al()], atypes), - "MCH3", 4))); + && (gmx::equalCaseInsensitive( + get_atomtype_name_AB(&at->atom[vsite->al()], atypes), "MNH", 3))) + || ((gmx::equalCaseInsensitive( + get_atomtype_name_AB(&at->atom[vsite->ak()], atypes), "MCH3", 4)) + && (gmx::equalCaseInsensitive( + get_atomtype_name_AB(&at->atom[vsite->al()], atypes), "MCH3", 4))); /* check if construction parity must be swapped */ bSwapParity = (vsite->c1() == -1); @@ -677,11 +681,16 @@ static bool calc_vsite4fd_param(InteractionOfType* vsit .asParagraph() .appendTextFormatted( "virtual site %d: angle ijk = %f, angle ijl = %f, angle ijm = %f", - vsite->ai() + 1, RAD2DEG * aijk, RAD2DEG * aijl, RAD2DEG * aijm); + vsite->ai() + 1, + RAD2DEG * aijk, + RAD2DEG * aijl, + RAD2DEG * aijm); gmx_fatal(FARGS, "invalid construction in calc_vsite4fd for atom %d: " "cosakl=%f, cosakm=%f\n", - vsite->ai() + 1, cosakl, cosakm); + vsite->ai() + 1, + cosakl, + cosakm); } sinakl = std::sqrt(1 - gmx::square(cosakl)); sinakm = std::sqrt(1 - gmx::square(cosakm)); @@ -742,11 +751,16 @@ static bool calc_vsite4fdn_param(InteractionOfType* vsi .asParagraph() .appendTextFormatted( "virtual site %d: angle ijk = %f, angle ijl = %f, angle ijm = %f", - vsite->ai() + 1, RAD2DEG * aijk, RAD2DEG * aijl, RAD2DEG * aijm); + vsite->ai() + 1, + RAD2DEG * aijk, + RAD2DEG * aijl, + RAD2DEG * aijm); gmx_fatal(FARGS, "invalid construction in calc_vsite4fdn for atom %d: " "pl=%f, pm=%f\n", - vsite->ai() + 1, pl, pm); + vsite->ai() + 1, + pl, + pm); } a = pk / pl; @@ -825,43 +839,48 @@ int set_vsites(bool bVerbose, fprintf(debug, "Found %zu bonds, %zu angles and %zu idihs " "for virtual site %d (%s)\n", - allVsiteBondeds.bonds.size(), allVsiteBondeds.angles.size(), - allVsiteBondeds.dihedrals.size(), param.ai() + 1, + allVsiteBondeds.bonds.size(), + allVsiteBondeds.angles.size(), + allVsiteBondeds.dihedrals.size(), + param.ai() + 1, interaction_function[ftype].longname); - print_bad(debug, allVsiteBondeds.bonds, allVsiteBondeds.angles, + print_bad(debug, + allVsiteBondeds.bonds, + allVsiteBondeds.angles, allVsiteBondeds.dihedrals); } /* debug */ switch (ftype) { case F_VSITE3: - bERROR = calc_vsite3_param(atypes, ¶m, atoms, allVsiteBondeds.bonds, - allVsiteBondeds.angles); + bERROR = calc_vsite3_param( + atypes, ¶m, atoms, allVsiteBondeds.bonds, allVsiteBondeds.angles); break; case F_VSITE3FD: - bERROR = calc_vsite3fd_param(¶m, allVsiteBondeds.bonds, - allVsiteBondeds.angles); + bERROR = calc_vsite3fd_param( + ¶m, allVsiteBondeds.bonds, allVsiteBondeds.angles); break; case F_VSITE3FAD: - bERROR = calc_vsite3fad_param(¶m, allVsiteBondeds.bonds, - allVsiteBondeds.angles); + bERROR = calc_vsite3fad_param( + ¶m, allVsiteBondeds.bonds, allVsiteBondeds.angles); break; case F_VSITE3OUT: - bERROR = calc_vsite3out_param(atypes, ¶m, atoms, allVsiteBondeds.bonds, - allVsiteBondeds.angles); + bERROR = calc_vsite3out_param( + atypes, ¶m, atoms, allVsiteBondeds.bonds, allVsiteBondeds.angles); break; case F_VSITE4FD: - bERROR = calc_vsite4fd_param(¶m, allVsiteBondeds.bonds, - allVsiteBondeds.angles, logger); + bERROR = calc_vsite4fd_param( + ¶m, allVsiteBondeds.bonds, allVsiteBondeds.angles, logger); break; case F_VSITE4FDN: - bERROR = calc_vsite4fdn_param(¶m, allVsiteBondeds.bonds, - allVsiteBondeds.angles, logger); + bERROR = calc_vsite4fdn_param( + ¶m, allVsiteBondeds.bonds, allVsiteBondeds.angles, logger); break; default: gmx_fatal(FARGS, "Automatic parameter generation not supported " "for %s atom %d", - interaction_function[ftype].longname, param.ai() + 1); + interaction_function[ftype].longname, + param.ai() + 1); bERROR = TRUE; } /* switch */ if (bERROR) @@ -869,7 +888,8 @@ int set_vsites(bool bVerbose, gmx_fatal(FARGS, "Automatic parameter generation not supported " "for %s atom %d for this bonding configuration", - interaction_function[ftype].longname, param.ai() + 1); + interaction_function[ftype].longname, + param.ai() + 1); } } /* if bSet */ i++; @@ -902,7 +922,8 @@ void set_vsites_ptype(bool bVerbose, gmx_moltype_t* molt, const gmx::MDLogger& l { GMX_LOG(logger.info) .asParagraph() - .appendTextFormatted("doing %d %s virtual sites", (nrd / (nra + 1)), + .appendTextFormatted("doing %d %s virtual sites", + (nrd / (nra + 1)), interaction_function[ftype].longname); } @@ -965,7 +986,9 @@ static void check_vsite_constraints(gmx::ArrayRef plist, .asParagraph() .appendTextFormatted( "ERROR: Cannot have constraint (%d-%d) with virtual site (%d)", - param.ai() + 1, param.aj() + 1, atom + 1); + param.ai() + 1, + param.aj() + 1, + atom + 1); n++; } } @@ -1158,7 +1181,8 @@ static void clean_vsite_bonds(gmx::ArrayRef plist, if (interaction_function[ftype].flags & IF_CONSTRAINT) { for (auto entry = plist[ftype].interactionTypes.begin(); - (entry != plist[ftype].interactionTypes.end()) && !bPresent; entry++) + (entry != plist[ftype].interactionTypes.end()) && !bPresent; + entry++) { /* all constraints until one matches */ bPresent = (((entry->ai() == at1) && (entry->aj() == at2)) @@ -1195,8 +1219,10 @@ static void clean_vsite_bonds(gmx::ArrayRef plist, { GMX_LOG(logger.info) .asParagraph() - .appendTextFormatted("Removed %4d %15ss with virtual sites, %zu left", nremoved, - interaction_function[cftype].longname, ps->size()); + .appendTextFormatted("Removed %4d %15ss with virtual sites, %zu left", + nremoved, + interaction_function[cftype].longname, + ps->size()); } if (nconverted) { @@ -1204,7 +1230,9 @@ static void clean_vsite_bonds(gmx::ArrayRef plist, .asParagraph() .appendTextFormatted( "Converted %4d %15ss with virtual sites to connections, %zu left", - nconverted, interaction_function[cftype].longname, ps->size()); + nconverted, + interaction_function[cftype].longname, + ps->size()); } if (nOut) { @@ -1216,7 +1244,8 @@ static void clean_vsite_bonds(gmx::ArrayRef plist, "bond-length\n" " If the constructions were generated by pdb2gmx ignore " "this warning", - nOut, interaction_function[cftype].longname, + nOut, + interaction_function[cftype].longname, interaction_function[F_VSITE3OUT].longname); } } @@ -1371,7 +1400,8 @@ static void clean_vsite_angles(gmx::ArrayRef plist, GMX_LOG(logger.info) .asParagraph() .appendTextFormatted("Removed %4zu %15ss with virtual sites, %zu left", - oldSize - ps->size(), interaction_function[cftype].longname, + oldSize - ps->size(), + interaction_function[cftype].longname, ps->size()); } } @@ -1502,7 +1532,8 @@ static void clean_vsite_dihs(gmx::ArrayRef plist, GMX_LOG(logger.info) .asParagraph() .appendTextFormatted("Removed %4zu %15ss with virtual sites, %zu left", - oldSize - ps->size(), interaction_function[cftype].longname, + oldSize - ps->size(), + interaction_function[cftype].longname, ps->size()); } } diff --git a/src/gromacs/gmxpreprocess/x2top.cpp b/src/gromacs/gmxpreprocess/x2top.cpp index 17410a6408..63c6007fe8 100644 --- a/src/gromacs/gmxpreprocess/x2top.cpp +++ b/src/gromacs/gmxpreprocess/x2top.cpp @@ -280,9 +280,9 @@ static void calc_angles_dihs(InteractionsOfType* ang, InteractionsOfType* dih, c int aj = dihedral.aj(); int ak = dihedral.ak(); int al = dihedral.al(); - real ph = RAD2DEG - * dih_angle(x[ai], x[aj], x[ak], x[al], bPBC ? &pbc : nullptr, r_ij, r_kj, r_kl, - m, n, &t1, &t2, &t3); + real ph = + RAD2DEG + * dih_angle(x[ai], x[aj], x[ak], x[al], bPBC ? &pbc : nullptr, r_ij, r_kj, r_kl, m, n, &t1, &t2, &t3); dihedral.setForceParameter(0, ph); } } @@ -382,7 +382,8 @@ int gmx_x2top(int argc, char* argv[]) }; const char* bugs[] = { "The atom type selection is primitive. Virtually no chemical knowledge is used", - "Periodic boundary conditions screw up the bonding", "No improper dihedrals are generated", + "Periodic boundary conditions screw up the bonding", + "No improper dihedrals are generated", "The atoms to atomtype translation table is incomplete ([TT]atomname2type.n2t[tt] file in", "the data directory). Please extend it and send the results back to the GROMACS crew." }; @@ -458,8 +459,8 @@ int gmx_x2top(int argc, char* argv[]) { "-kp", FALSE, etREAL, { &kp }, "Dihedral angle force constant (kJ/mol/rad^2)" } }; - if (!parse_common_args(&argc, argv, 0, NFILE, fnm, asize(pa), pa, asize(desc), desc, - asize(bugs), bugs, &oenv)) + if (!parse_common_args( + &argc, argv, 0, NFILE, fnm, asize(pa), pa, asize(desc), desc, asize(bugs), bugs, &oenv)) { return 0; } @@ -485,8 +486,7 @@ int gmx_x2top(int argc, char* argv[]) /* Force field selection, interactive or direct */ - choose_ff(strcmp(ff, "select") == 0 ? nullptr : ff, forcefield, sizeof(forcefield), ffdir, - sizeof(ffdir), logger); + choose_ff(strcmp(ff, "select") == 0 ? nullptr : ff, forcefield, sizeof(forcefield), ffdir, sizeof(ffdir), logger); bOPLS = (strcmp(forcefield, "oplsaa") == 0); @@ -545,8 +545,13 @@ int gmx_x2top(int argc, char* argv[]) .appendTextFormatted( "There are %4zu %s dihedrals, %4zu impropers, %4zu angles\n" " %4zu pairs, %4zu bonds and %4d atoms\n", - plist[F_PDIHS].size(), bOPLS ? "Ryckaert-Bellemans" : "proper", plist[F_IDIHS].size(), - plist[F_ANGLES].size(), plist[F_LJ14].size(), plist[F_BONDS].size(), atoms->nr); + plist[F_PDIHS].size(), + bOPLS ? "Ryckaert-Bellemans" : "proper", + plist[F_IDIHS].size(), + plist[F_ANGLES].size(), + plist[F_LJ14].size(), + plist[F_BONDS].size(), + atoms->nr); calc_angles_dihs(&plist[F_ANGLES], &plist[F_PDIHS], x, bPBC, box); @@ -565,7 +570,16 @@ int gmx_x2top(int argc, char* argv[]) fp = ftp2FILE(efTOP, NFILE, fnm, "w"); print_top_header(fp, ftp2fn(efTOP, NFILE, fnm), TRUE, ffdir, 1.0); - write_top(fp, nullptr, mymol.name.c_str(), atoms, FALSE, bts, plist, excls, &atypes, cgnr, + write_top(fp, + nullptr, + mymol.name.c_str(), + atoms, + FALSE, + bts, + plist, + excls, + &atypes, + cgnr, rtp_header_settings.nrexcl); print_top_mols(fp, mymol.name.c_str(), ffdir, nullptr, {}, gmx::arrayRefFromArray(&mymol, 1)); diff --git a/src/gromacs/gmxpreprocess/xlate.cpp b/src/gromacs/gmxpreprocess/xlate.cpp index 4166698511..0cb0529620 100644 --- a/src/gromacs/gmxpreprocess/xlate.cpp +++ b/src/gromacs/gmxpreprocess/xlate.cpp @@ -91,8 +91,10 @@ static void get_xlatoms(const std::string& filename, FILE* fp, int* nptr, t_xlat } if (na != 3) { - gmx_fatal(FARGS, "Expected a residue name and two atom names in file '%s', not '%s'", - filename.c_str(), line); + gmx_fatal(FARGS, + "Expected a residue name and two atom names in file '%s', not '%s'", + filename.c_str(), + line); } srenew(xl, n + 1); @@ -245,8 +247,11 @@ void rename_atoms(const char* xlfile, const char* ptr0 = xlatom[i].replace; if (bVerbose) { - printf("Renaming atom '%s' in residue %d %s to '%s'\n", *atoms->atomname[a], - atoms->resinfo[resind].nr, *atoms->resinfo[resind].name, ptr0); + printf("Renaming atom '%s' in residue %d %s to '%s'\n", + *atoms->atomname[a], + atoms->resinfo[resind].nr, + *atoms->resinfo[resind].name, + ptr0); } atoms->atomname[a] = put_symtab(symtab, ptr0); bRenamed = TRUE; diff --git a/src/gromacs/gpu_utils/cudautils.cuh b/src/gromacs/gpu_utils/cudautils.cuh index 9a69fe9ef0..e5d3c3aad6 100644 --- a/src/gromacs/gpu_utils/cudautils.cuh +++ b/src/gromacs/gpu_utils/cudautils.cuh @@ -63,7 +63,9 @@ namespace */ static inline std::string getDeviceErrorString(const cudaError_t deviceError) { - return formatString("CUDA error #%d (%s): %s.", deviceError, cudaGetErrorName(deviceError), + return formatString("CUDA error #%d (%s): %s.", + deviceError, + cudaGetErrorName(deviceError), cudaGetErrorString(deviceError)); } @@ -281,8 +283,12 @@ void launchGpuKernel(void (*kernel)(Args...), { dim3 blockSize(config.blockSize[0], config.blockSize[1], config.blockSize[2]); dim3 gridSize(config.gridSize[0], config.gridSize[1], config.gridSize[2]); - cudaLaunchKernel((void*)kernel, gridSize, blockSize, const_cast(kernelArgs.data()), - config.sharedMemorySize, deviceStream.stream()); + cudaLaunchKernel((void*)kernel, + gridSize, + blockSize, + const_cast(kernelArgs.data()), + config.sharedMemorySize, + deviceStream.stream()); gmx::ensureNoPendingDeviceError("GPU kernel (" + std::string(kernelName) + ") failed to launch."); diff --git a/src/gromacs/gpu_utils/device_context_ocl.cpp b/src/gromacs/gpu_utils/device_context_ocl.cpp index c7fa8af860..0ecf83daf5 100644 --- a/src/gromacs/gpu_utils/device_context_ocl.cpp +++ b/src/gromacs/gpu_utils/device_context_ocl.cpp @@ -84,7 +84,8 @@ DeviceContext::DeviceContext(const DeviceInformation& deviceInfo) : deviceInfo_( { GMX_THROW(gmx::InternalError(gmx::formatString( "Failed to create OpenCL context on device %s (OpenCL error ID %d).", - deviceInfo.device_name, clError))); + deviceInfo.device_name, + clError))); } } diff --git a/src/gromacs/gpu_utils/device_stream_ocl.cpp b/src/gromacs/gpu_utils/device_stream_ocl.cpp index 9140616271..1aeb807d13 100644 --- a/src/gromacs/gpu_utils/device_stream_ocl.cpp +++ b/src/gromacs/gpu_utils/device_stream_ocl.cpp @@ -63,7 +63,8 @@ DeviceStream::DeviceStream(const DeviceContext& deviceContext, { GMX_THROW(gmx::InternalError(gmx::formatString( "Failed to create OpenCL command queue on GPU %s (OpenCL error ID %d).", - deviceInfo.device_name, clError))); + deviceInfo.device_name, + clError))); } } diff --git a/src/gromacs/gpu_utils/devicebuffer.cuh b/src/gromacs/gpu_utils/devicebuffer.cuh index ec544aa3c2..a28585bdf5 100644 --- a/src/gromacs/gpu_utils/devicebuffer.cuh +++ b/src/gromacs/gpu_utils/devicebuffer.cuh @@ -129,18 +129,20 @@ void copyToDeviceBuffer(DeviceBuffer* buffer, switch (transferKind) { case GpuApiCallBehavior::Async: - GMX_ASSERT(isHostMemoryPinned(hostBuffer), - "Source host buffer was not pinned for CUDA"); - stat = cudaMemcpyAsync(*((ValueType**)buffer) + startingOffset, hostBuffer, bytes, - cudaMemcpyHostToDevice, deviceStream.stream()); + GMX_ASSERT(isHostMemoryPinned(hostBuffer), "Source host buffer was not pinned for CUDA"); + stat = cudaMemcpyAsync(*((ValueType**)buffer) + startingOffset, + hostBuffer, + bytes, + cudaMemcpyHostToDevice, + deviceStream.stream()); GMX_RELEASE_ASSERT( stat == cudaSuccess, ("Asynchronous H2D copy failed. " + gmx::getDeviceErrorString(stat)).c_str()); break; case GpuApiCallBehavior::Sync: - stat = cudaMemcpy(*((ValueType**)buffer) + startingOffset, hostBuffer, bytes, - cudaMemcpyHostToDevice); + stat = cudaMemcpy( + *((ValueType**)buffer) + startingOffset, hostBuffer, bytes, cudaMemcpyHostToDevice); GMX_RELEASE_ASSERT( stat == cudaSuccess, ("Synchronous H2D copy failed. " + gmx::getDeviceErrorString(stat)).c_str()); @@ -186,16 +188,19 @@ void copyFromDeviceBuffer(ValueType* hostBuffer, case GpuApiCallBehavior::Async: GMX_ASSERT(isHostMemoryPinned(hostBuffer), "Destination host buffer was not pinned for CUDA"); - stat = cudaMemcpyAsync(hostBuffer, *((ValueType**)buffer) + startingOffset, bytes, - cudaMemcpyDeviceToHost, deviceStream.stream()); + stat = cudaMemcpyAsync(hostBuffer, + *((ValueType**)buffer) + startingOffset, + bytes, + cudaMemcpyDeviceToHost, + deviceStream.stream()); GMX_RELEASE_ASSERT( stat == cudaSuccess, ("Asynchronous D2H copy failed. " + gmx::getDeviceErrorString(stat)).c_str()); break; case GpuApiCallBehavior::Sync: - stat = cudaMemcpy(hostBuffer, *((ValueType**)buffer) + startingOffset, bytes, - cudaMemcpyDeviceToHost); + stat = cudaMemcpy( + hostBuffer, *((ValueType**)buffer) + startingOffset, bytes, cudaMemcpyDeviceToHost); GMX_RELEASE_ASSERT( stat == cudaSuccess, ("Synchronous D2H copy failed. " + gmx::getDeviceErrorString(stat)).c_str()); @@ -224,8 +229,8 @@ void clearDeviceBufferAsync(DeviceBuffer* buffer, const size_t bytes = numValues * sizeof(ValueType); const char pattern = 0; - cudaError_t stat = cudaMemsetAsync(*((ValueType**)buffer) + startingOffset, pattern, bytes, - deviceStream.stream()); + cudaError_t stat = cudaMemsetAsync( + *((ValueType**)buffer) + startingOffset, pattern, bytes, deviceStream.stream()); GMX_RELEASE_ASSERT(stat == cudaSuccess, ("Couldn't clear the device buffer. " + gmx::getDeviceErrorString(stat)).c_str()); } diff --git a/src/gromacs/gpu_utils/devicebuffer_ocl.h b/src/gromacs/gpu_utils/devicebuffer_ocl.h index 81501a2b08..ce6600afe3 100644 --- a/src/gromacs/gpu_utils/devicebuffer_ocl.h +++ b/src/gromacs/gpu_utils/devicebuffer_ocl.h @@ -69,10 +69,11 @@ void allocateDeviceBuffer(DeviceBuffer* buffer, size_t numValues, con GMX_ASSERT(buffer, "needs a buffer pointer"); void* hostPtr = nullptr; cl_int clError; - *buffer = clCreateBuffer(deviceContext.context(), CL_MEM_READ_WRITE, - numValues * sizeof(ValueType), hostPtr, &clError); + *buffer = clCreateBuffer( + deviceContext.context(), CL_MEM_READ_WRITE, numValues * sizeof(ValueType), hostPtr, &clError); GMX_RELEASE_ASSERT(clError == CL_SUCCESS, - gmx::formatString("clCreateBuffer failure (OpenCL error %d: %s)", clError, + gmx::formatString("clCreateBuffer failure (OpenCL error %d: %s)", + clError, ocl_get_error_string(clError).c_str()) .c_str()); } @@ -94,7 +95,8 @@ void freeDeviceBuffer(DeviceBuffer* buffer) cl_int clError = clReleaseMemObject(*buffer); GMX_RELEASE_ASSERT(clError == CL_SUCCESS, gmx::formatString("clReleaseMemObject failed (OpenCL error %d: %s)", - clError, ocl_get_error_string(clError).c_str()) + clError, + ocl_get_error_string(clError).c_str()) .c_str()); } } @@ -137,21 +139,23 @@ void copyToDeviceBuffer(DeviceBuffer* buffer, switch (transferKind) { case GpuApiCallBehavior::Async: - clError = clEnqueueWriteBuffer(deviceStream.stream(), *buffer, CL_FALSE, offset, bytes, - hostBuffer, 0, nullptr, timingEvent); + clError = clEnqueueWriteBuffer( + deviceStream.stream(), *buffer, CL_FALSE, offset, bytes, hostBuffer, 0, nullptr, timingEvent); GMX_RELEASE_ASSERT( clError == CL_SUCCESS, - gmx::formatString("Asynchronous H2D copy failed (OpenCL error %d: %s)", clError, + gmx::formatString("Asynchronous H2D copy failed (OpenCL error %d: %s)", + clError, ocl_get_error_string(clError).c_str()) .c_str()); break; case GpuApiCallBehavior::Sync: - clError = clEnqueueWriteBuffer(deviceStream.stream(), *buffer, CL_TRUE, offset, bytes, - hostBuffer, 0, nullptr, timingEvent); + clError = clEnqueueWriteBuffer( + deviceStream.stream(), *buffer, CL_TRUE, offset, bytes, hostBuffer, 0, nullptr, timingEvent); GMX_RELEASE_ASSERT( clError == CL_SUCCESS, - gmx::formatString("Synchronous H2D copy failed (OpenCL error %d: %s)", clError, + gmx::formatString("Synchronous H2D copy failed (OpenCL error %d: %s)", + clError, ocl_get_error_string(clError).c_str()) .c_str()); break; @@ -198,21 +202,23 @@ void copyFromDeviceBuffer(ValueType* hostBuffer, switch (transferKind) { case GpuApiCallBehavior::Async: - clError = clEnqueueReadBuffer(deviceStream.stream(), *buffer, CL_FALSE, offset, bytes, - hostBuffer, 0, nullptr, timingEvent); + clError = clEnqueueReadBuffer( + deviceStream.stream(), *buffer, CL_FALSE, offset, bytes, hostBuffer, 0, nullptr, timingEvent); GMX_RELEASE_ASSERT( clError == CL_SUCCESS, - gmx::formatString("Asynchronous D2H copy failed (OpenCL error %d: %s)", clError, + gmx::formatString("Asynchronous D2H copy failed (OpenCL error %d: %s)", + clError, ocl_get_error_string(clError).c_str()) .c_str()); break; case GpuApiCallBehavior::Sync: - clError = clEnqueueReadBuffer(deviceStream.stream(), *buffer, CL_TRUE, offset, bytes, - hostBuffer, 0, nullptr, timingEvent); + clError = clEnqueueReadBuffer( + deviceStream.stream(), *buffer, CL_TRUE, offset, bytes, hostBuffer, 0, nullptr, timingEvent); GMX_RELEASE_ASSERT( clError == CL_SUCCESS, - gmx::formatString("Synchronous D2H copy failed (OpenCL error %d: %s)", clError, + gmx::formatString("Synchronous D2H copy failed (OpenCL error %d: %s)", + clError, ocl_get_error_string(clError).c_str()) .c_str()); break; @@ -243,11 +249,12 @@ void clearDeviceBufferAsync(DeviceBuffer* buffer, const cl_uint numWaitEvents = 0; const cl_event* waitEvents = nullptr; cl_event commandEvent; - cl_int clError = clEnqueueFillBuffer(deviceStream.stream(), *buffer, &pattern, sizeof(pattern), - offset, bytes, numWaitEvents, waitEvents, &commandEvent); + cl_int clError = clEnqueueFillBuffer( + deviceStream.stream(), *buffer, &pattern, sizeof(pattern), offset, bytes, numWaitEvents, waitEvents, &commandEvent); GMX_RELEASE_ASSERT(clError == CL_SUCCESS, gmx::formatString("Couldn't clear the device buffer (OpenCL error %d: %s)", - clError, ocl_get_error_string(clError).c_str()) + clError, + ocl_get_error_string(clError).c_str()) .c_str()); } @@ -306,11 +313,14 @@ void initParamLookupTable(DeviceBuffer* deviceBuffer, cl_int clError; *deviceBuffer = clCreateBuffer(deviceContext.context(), CL_MEM_READ_ONLY | CL_MEM_HOST_WRITE_ONLY | CL_MEM_COPY_HOST_PTR, - bytes, const_cast(hostBuffer), &clError); + bytes, + const_cast(hostBuffer), + &clError); GMX_RELEASE_ASSERT(clError == CL_SUCCESS, gmx::formatString("Constant memory allocation failed (OpenCL error %d: %s)", - clError, ocl_get_error_string(clError).c_str()) + clError, + ocl_get_error_string(clError).c_str()) .c_str()); } diff --git a/src/gromacs/gpu_utils/gpu_utils.cu b/src/gromacs/gpu_utils/gpu_utils.cu index 8df9282b6b..4736d26664 100644 --- a/src/gromacs/gpu_utils/gpu_utils.cu +++ b/src/gromacs/gpu_utils/gpu_utils.cu @@ -172,7 +172,10 @@ static void peerAccessCheckStat(const cudaError_t stat, .appendTextFormatted( "GPU peer access not enabled between GPUs %d and %d due to unexpected " "return value from %s. %s", - gpuA, gpuB, cudaCallName, gmx::getDeviceErrorString(stat).c_str()); + gpuA, + gpuB, + cudaCallName, + gmx::getDeviceErrorString(stat).c_str()); } } @@ -200,7 +203,8 @@ void setupGpuDevicePeerAccess(const std::vector& gpuIdsToUse, const gmx::MD .appendTextFormatted( "GPU peer access not enabled due to unexpected return value from " "cudaSetDevice(%d). %s", - gpuA, gmx::getDeviceErrorString(stat).c_str()); + gpuA, + gmx::getDeviceErrorString(stat).c_str()); return; } for (unsigned int j = 0; j < gpuIdsToUse.size(); j++) diff --git a/src/gromacs/gpu_utils/gpuregiontimer_ocl.h b/src/gromacs/gpu_utils/gpuregiontimer_ocl.h index 3434a451e4..8adaf08eef 100644 --- a/src/gromacs/gpu_utils/gpuregiontimer_ocl.h +++ b/src/gromacs/gpu_utils/gpuregiontimer_ocl.h @@ -97,17 +97,19 @@ public: cl_ulong start_ns, end_ns; cl_int gmx_unused cl_error; - cl_error = clGetEventProfilingInfo(events_[i], CL_PROFILING_COMMAND_START, - sizeof(cl_ulong), &start_ns, nullptr); + cl_error = clGetEventProfilingInfo( + events_[i], CL_PROFILING_COMMAND_START, sizeof(cl_ulong), &start_ns, nullptr); GMX_ASSERT(CL_SUCCESS == cl_error, gmx::formatString("GPU timing update failure (OpenCL error %d: %s).", - cl_error, ocl_get_error_string(cl_error).c_str()) + cl_error, + ocl_get_error_string(cl_error).c_str()) .c_str()); - cl_error = clGetEventProfilingInfo(events_[i], CL_PROFILING_COMMAND_END, - sizeof(cl_ulong), &end_ns, nullptr); + cl_error = clGetEventProfilingInfo( + events_[i], CL_PROFILING_COMMAND_END, sizeof(cl_ulong), &end_ns, nullptr); GMX_ASSERT(CL_SUCCESS == cl_error, gmx::formatString("GPU timing update failure (OpenCL error %d: %s).", - cl_error, ocl_get_error_string(cl_error).c_str()) + cl_error, + ocl_get_error_string(cl_error).c_str()) .c_str()); milliseconds += (end_ns - start_ns) / 1000000.0; } diff --git a/src/gromacs/gpu_utils/ocl_caching.cpp b/src/gromacs/gpu_utils/ocl_caching.cpp index e8894aaad0..bdc71c69bc 100644 --- a/src/gromacs/gpu_utils/ocl_caching.cpp +++ b/src/gromacs/gpu_utils/ocl_caching.cpp @@ -75,8 +75,8 @@ std::string makeBinaryCacheFilename(const std::string& kernelFilename, cl_device // assume that sizeof(char) is one byte. std::array deviceName; size_t deviceNameLength; - cl_int cl_error = clGetDeviceInfo(deviceId, CL_DEVICE_NAME, deviceName.size(), - deviceName.data(), &deviceNameLength); + cl_int cl_error = clGetDeviceInfo( + deviceId, CL_DEVICE_NAME, deviceName.size(), deviceName.data(), &deviceNameLength); if (cl_error != CL_SUCCESS) { GMX_THROW(InternalError(formatString("Could not get OpenCL device name, error was %s", @@ -94,8 +94,10 @@ std::string makeBinaryCacheFilename(const std::string& kernelFilename, cl_device (symbols), by permitting only alphanumeric characters from the current locale. We assume these work well enough in a filename. */ - std::copy_if(deviceName.begin(), deviceName.begin() + deviceNameLength, - std::back_inserter(cacheFilename), isalnum); + std::copy_if(deviceName.begin(), + deviceName.begin() + deviceNameLength, + std::back_inserter(cacheFilename), + isalnum); cacheFilename += ".bin"; return cacheFilename; @@ -134,9 +136,8 @@ cl_program makeProgramFromCache(const std::string& filename, cl_context context, /* Create program from pre-built binary */ cl_int cl_error; - cl_program program = clCreateProgramWithBinary(context, 1, &deviceId, &fileSize, - const_cast(&binary), - nullptr, &cl_error); + cl_program program = clCreateProgramWithBinary( + context, 1, &deviceId, &fileSize, const_cast(&binary), nullptr, &cl_error); if (cl_error != CL_SUCCESS) { GMX_THROW(InternalError("Could not create OpenCL program from the cache file " + filename diff --git a/src/gromacs/gpu_utils/ocl_compiler.cpp b/src/gromacs/gpu_utils/ocl_compiler.cpp index 1f670e8b91..c8ed6f19c5 100644 --- a/src/gromacs/gpu_utils/ocl_compiler.cpp +++ b/src/gromacs/gpu_utils/ocl_compiler.cpp @@ -126,8 +126,8 @@ static void writeOclBuildLog(FILE* fplog, buildLogGuard.reset(buildLog); /* Get the actual compilation log */ - cl_error = clGetProgramBuildInfo(program, deviceId, CL_PROGRAM_BUILD_LOG, buildLogSize, - buildLog, nullptr); + cl_error = clGetProgramBuildInfo( + program, deviceId, CL_PROGRAM_BUILD_LOG, buildLogSize, buildLog, nullptr); if (cl_error != CL_SUCCESS) { GMX_THROW(InternalError("Could not get OpenCL program build log, error was " @@ -248,9 +248,8 @@ static std::string getSourceRootPath(const std::string& sourceRelativePath) size_t getKernelWarpSize(cl_kernel kernel, cl_device_id deviceId) { size_t warpSize = 0; - cl_int cl_error = - clGetKernelWorkGroupInfo(kernel, deviceId, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, - sizeof(warpSize), &warpSize, nullptr); + cl_int cl_error = clGetKernelWorkGroupInfo( + kernel, deviceId, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, sizeof(warpSize), &warpSize, nullptr); if (cl_error != CL_SUCCESS) { GMX_THROW(InternalError("Could not query OpenCL preferred workgroup size, error was " @@ -450,7 +449,8 @@ cl_program compileProgram(FILE* fplog, // Failing to read from the cache is not a critical error formatExceptionMessageToFile(fplog, e); } - fprintf(fplog, "OpenCL binary cache file %s is present, will load kernels.\n", + fprintf(fplog, + "OpenCL binary cache file %s is present, will load kernels.\n", cacheFilename.c_str()); } else @@ -487,8 +487,7 @@ cl_program compileProgram(FILE* fplog, /* Write log first, and then throw exception that the user know what is the issue even if the build fails. */ - writeOclBuildLog(fplog, program, deviceId, kernelFilename, preprocessorOptions, - buildStatus != CL_SUCCESS); + writeOclBuildLog(fplog, program, deviceId, kernelFilename, preprocessorOptions, buildStatus != CL_SUCCESS); if (buildStatus != CL_SUCCESS) { diff --git a/src/gromacs/gpu_utils/oclutils.h b/src/gromacs/gpu_utils/oclutils.h index e5d4f6da33..c408167161 100644 --- a/src/gromacs/gpu_utils/oclutils.h +++ b/src/gromacs/gpu_utils/oclutils.h @@ -189,9 +189,15 @@ inline void launchGpuKernel(cl_kernel kernel, { globalWorkSize[i] = config.gridSize[i] * config.blockSize[i]; } - cl_int clError = clEnqueueNDRangeKernel(deviceStream.stream(), kernel, workDimensions, - globalWorkOffset, globalWorkSize, config.blockSize, - waitListSize, waitList, timingEvent); + cl_int clError = clEnqueueNDRangeKernel(deviceStream.stream(), + kernel, + workDimensions, + globalWorkOffset, + globalWorkSize, + config.blockSize, + waitListSize, + waitList, + timingEvent); if (CL_SUCCESS != clError) { const std::string errorMessage = "GPU kernel (" + std::string(kernelName) diff --git a/src/gromacs/gpu_utils/tests/device_buffer.cpp b/src/gromacs/gpu_utils/tests/device_buffer.cpp index 3acfee0204..86cfa6bdd5 100644 --- a/src/gromacs/gpu_utils/tests/device_buffer.cpp +++ b/src/gromacs/gpu_utils/tests/device_buffer.cpp @@ -156,10 +156,10 @@ TYPED_TEST(DeviceBufferTest, CanCopyToAndFromDevice) std::iota(valuesIn.begin(), valuesIn.end(), c_initialValue); - copyToDeviceBuffer(&buffer, valuesIn.data(), 0, numValues, deviceStream, - GpuApiCallBehavior::Sync, nullptr); - copyFromDeviceBuffer(valuesOut.data(), &buffer, 0, numValues, deviceStream, - GpuApiCallBehavior::Sync, nullptr); + copyToDeviceBuffer( + &buffer, valuesIn.data(), 0, numValues, deviceStream, GpuApiCallBehavior::Sync, nullptr); + copyFromDeviceBuffer( + valuesOut.data(), &buffer, 0, numValues, deviceStream, GpuApiCallBehavior::Sync, nullptr); EXPECT_THAT(valuesOut, Pointwise(Eq(), valuesIn)) << "Changed after H2D and D2H copy."; freeDeviceBuffer(&buffer); } @@ -182,16 +182,16 @@ TYPED_TEST(DeviceBufferTest, CanCopyToAndFromDeviceWithOffset) std::iota(valuesIn.begin(), valuesIn.end(), c_initialValue); // Fill the buffer with two copies of valuesIn, one after the other. - copyToDeviceBuffer(&buffer, valuesIn.data(), 0, numValues, deviceStream, - GpuApiCallBehavior::Sync, nullptr); - copyToDeviceBuffer(&buffer, valuesIn.data(), numValues, numValues, deviceStream, - GpuApiCallBehavior::Sync, nullptr); + copyToDeviceBuffer( + &buffer, valuesIn.data(), 0, numValues, deviceStream, GpuApiCallBehavior::Sync, nullptr); + copyToDeviceBuffer( + &buffer, valuesIn.data(), numValues, numValues, deviceStream, GpuApiCallBehavior::Sync, nullptr); // Do the same copying on the CPU, so we can test it works // correctly. valuesIn.insert(valuesIn.end(), valuesIn.begin(), valuesIn.end()); - copyFromDeviceBuffer(valuesOut.data(), &buffer, 0, 2 * numValues, deviceStream, - GpuApiCallBehavior::Sync, nullptr); + copyFromDeviceBuffer( + valuesOut.data(), &buffer, 0, 2 * numValues, deviceStream, GpuApiCallBehavior::Sync, nullptr); EXPECT_THAT(valuesOut, Pointwise(Eq(), valuesIn)) << "Changed after H2D and D2H copy."; SCOPED_TRACE("Checking the copy respects the output range"); @@ -202,8 +202,8 @@ TYPED_TEST(DeviceBufferTest, CanCopyToAndFromDeviceWithOffset) // all but one of the old values. valuesIn.erase(valuesIn.begin()); valuesIn.push_back(valuesIn.back()); - copyFromDeviceBuffer(valuesOut.data(), &buffer, 1, 2 * numValues - 1, deviceStream, - GpuApiCallBehavior::Sync, nullptr); + copyFromDeviceBuffer( + valuesOut.data(), &buffer, 1, 2 * numValues - 1, deviceStream, GpuApiCallBehavior::Sync, nullptr); EXPECT_THAT(valuesOut, Pointwise(Eq(), valuesIn)) << "Changed after H2D and D2H copy."; } } diff --git a/src/gromacs/gpu_utils/tests/device_stream_manager.cpp b/src/gromacs/gpu_utils/tests/device_stream_manager.cpp index d01aff20ea..8166eaa771 100644 --- a/src/gromacs/gpu_utils/tests/device_stream_manager.cpp +++ b/src/gromacs/gpu_utils/tests/device_stream_manager.cpp @@ -126,9 +126,11 @@ TEST_F(DeviceStreamManagerTest, CorrectStreamsAreReturnedOnNonbondedDevice) DeviceStreamManager manager(deviceInfo, havePpDomainDecomposition, simulationWork, useTiming); expectValidStreams(&manager, { DeviceStreamType::NonBondedLocal }); - expectInvalidStreams(&manager, { DeviceStreamType::NonBondedNonLocal, - DeviceStreamType::Pme, DeviceStreamType::PmePpTransfer, - DeviceStreamType::UpdateAndConstraints }); + expectInvalidStreams(&manager, + { DeviceStreamType::NonBondedNonLocal, + DeviceStreamType::Pme, + DeviceStreamType::PmePpTransfer, + DeviceStreamType::UpdateAndConstraints }); } { @@ -140,10 +142,12 @@ TEST_F(DeviceStreamManagerTest, CorrectStreamsAreReturnedOnNonbondedDevice) bool havePpDomainDecomposition = true; DeviceStreamManager manager(deviceInfo, havePpDomainDecomposition, simulationWork, useTiming); - expectValidStreams(&manager, { DeviceStreamType::NonBondedLocal, - DeviceStreamType::NonBondedNonLocal }); - expectInvalidStreams(&manager, { DeviceStreamType::Pme, DeviceStreamType::PmePpTransfer, - DeviceStreamType::UpdateAndConstraints }); + expectValidStreams( + &manager, { DeviceStreamType::NonBondedLocal, DeviceStreamType::NonBondedNonLocal }); + expectInvalidStreams(&manager, + { DeviceStreamType::Pme, + DeviceStreamType::PmePpTransfer, + DeviceStreamType::UpdateAndConstraints }); } { @@ -155,9 +159,11 @@ TEST_F(DeviceStreamManagerTest, CorrectStreamsAreReturnedOnNonbondedDevice) bool havePpDomainDecomposition = false; DeviceStreamManager manager(deviceInfo, havePpDomainDecomposition, simulationWork, useTiming); - expectValidStreams(&manager, { DeviceStreamType::Pme, DeviceStreamType::NonBondedLocal, - DeviceStreamType::PmePpTransfer, - DeviceStreamType::UpdateAndConstraints }); + expectValidStreams(&manager, + { DeviceStreamType::Pme, + DeviceStreamType::NonBondedLocal, + DeviceStreamType::PmePpTransfer, + DeviceStreamType::UpdateAndConstraints }); expectInvalidStreams(&manager, { DeviceStreamType::NonBondedNonLocal }); } @@ -170,9 +176,12 @@ TEST_F(DeviceStreamManagerTest, CorrectStreamsAreReturnedOnNonbondedDevice) bool havePpDomainDecomposition = true; DeviceStreamManager manager(deviceInfo, havePpDomainDecomposition, simulationWork, useTiming); - expectValidStreams(&manager, { DeviceStreamType::Pme, DeviceStreamType::NonBondedLocal, - DeviceStreamType::NonBondedNonLocal, DeviceStreamType::PmePpTransfer, - DeviceStreamType::UpdateAndConstraints }); + expectValidStreams(&manager, + { DeviceStreamType::Pme, + DeviceStreamType::NonBondedLocal, + DeviceStreamType::NonBondedNonLocal, + DeviceStreamType::PmePpTransfer, + DeviceStreamType::UpdateAndConstraints }); } { @@ -184,10 +193,12 @@ TEST_F(DeviceStreamManagerTest, CorrectStreamsAreReturnedOnNonbondedDevice) bool havePpDomainDecomposition = false; DeviceStreamManager manager(deviceInfo, havePpDomainDecomposition, simulationWork, useTiming); - expectValidStreams(&manager, { DeviceStreamType::NonBondedLocal, - DeviceStreamType::UpdateAndConstraints }); - expectInvalidStreams(&manager, { DeviceStreamType::NonBondedNonLocal, - DeviceStreamType::Pme, DeviceStreamType::PmePpTransfer }); + expectValidStreams( + &manager, { DeviceStreamType::NonBondedLocal, DeviceStreamType::UpdateAndConstraints }); + expectInvalidStreams(&manager, + { DeviceStreamType::NonBondedNonLocal, + DeviceStreamType::Pme, + DeviceStreamType::PmePpTransfer }); } { @@ -199,8 +210,10 @@ TEST_F(DeviceStreamManagerTest, CorrectStreamsAreReturnedOnNonbondedDevice) bool havePpDomainDecomposition = true; DeviceStreamManager manager(deviceInfo, havePpDomainDecomposition, simulationWork, useTiming); - expectValidStreams(&manager, { DeviceStreamType::NonBondedLocal, DeviceStreamType::NonBondedNonLocal, - DeviceStreamType::UpdateAndConstraints }); + expectValidStreams(&manager, + { DeviceStreamType::NonBondedLocal, + DeviceStreamType::NonBondedNonLocal, + DeviceStreamType::UpdateAndConstraints }); expectInvalidStreams(&manager, { DeviceStreamType::Pme, DeviceStreamType::PmePpTransfer }); } @@ -213,9 +226,11 @@ TEST_F(DeviceStreamManagerTest, CorrectStreamsAreReturnedOnNonbondedDevice) bool havePpDomainDecomposition = false; DeviceStreamManager manager(deviceInfo, havePpDomainDecomposition, simulationWork, useTiming); - expectValidStreams(&manager, { DeviceStreamType::Pme, DeviceStreamType::NonBondedLocal, - DeviceStreamType::PmePpTransfer, - DeviceStreamType::UpdateAndConstraints }); + expectValidStreams(&manager, + { DeviceStreamType::Pme, + DeviceStreamType::NonBondedLocal, + DeviceStreamType::PmePpTransfer, + DeviceStreamType::UpdateAndConstraints }); expectInvalidStreams(&manager, { DeviceStreamType::NonBondedNonLocal }); } @@ -228,9 +243,12 @@ TEST_F(DeviceStreamManagerTest, CorrectStreamsAreReturnedOnNonbondedDevice) bool havePpDomainDecomposition = true; DeviceStreamManager manager(deviceInfo, havePpDomainDecomposition, simulationWork, useTiming); - expectValidStreams(&manager, { DeviceStreamType::Pme, DeviceStreamType::NonBondedLocal, - DeviceStreamType::NonBondedNonLocal, DeviceStreamType::PmePpTransfer, - DeviceStreamType::UpdateAndConstraints }); + expectValidStreams(&manager, + { DeviceStreamType::Pme, + DeviceStreamType::NonBondedLocal, + DeviceStreamType::NonBondedNonLocal, + DeviceStreamType::PmePpTransfer, + DeviceStreamType::UpdateAndConstraints }); } } } diff --git a/src/gromacs/gpu_utils/tests/devicetransfers_ocl.cpp b/src/gromacs/gpu_utils/tests/devicetransfers_ocl.cpp index 1888a35729..c01232fc13 100644 --- a/src/gromacs/gpu_utils/tests/devicetransfers_ocl.cpp +++ b/src/gromacs/gpu_utils/tests/devicetransfers_ocl.cpp @@ -64,8 +64,8 @@ void throwUponFailure(cl_int status, const char* message) { if (status != CL_SUCCESS) { - GMX_THROW(InternalError(formatString("Failure while %s, error was %s", message, - ocl_get_error_string(status).c_str()))); + GMX_THROW(InternalError(formatString( + "Failure while %s, error was %s", message, ocl_get_error_string(status).c_str()))); } } @@ -90,11 +90,11 @@ void doDeviceTransfers(const DeviceInformation& deviceInfo, ArrayRef auto devicePointer = clCreateBuffer(context, CL_MEM_READ_WRITE, input.size(), nullptr, &status); throwUponFailure(status, "creating buffer"); - status = clEnqueueWriteBuffer(commandQueue, devicePointer, CL_TRUE, 0, input.size(), - input.data(), 0, nullptr, nullptr); + status = clEnqueueWriteBuffer( + commandQueue, devicePointer, CL_TRUE, 0, input.size(), input.data(), 0, nullptr, nullptr); throwUponFailure(status, "transferring host to device"); - status = clEnqueueReadBuffer(commandQueue, devicePointer, CL_TRUE, 0, output.size(), - output.data(), 0, nullptr, nullptr); + status = clEnqueueReadBuffer( + commandQueue, devicePointer, CL_TRUE, 0, output.size(), output.data(), 0, nullptr, nullptr); throwUponFailure(status, "transferring device to host"); status = clReleaseMemObject(devicePointer); diff --git a/src/gromacs/gpu_utils/tests/typecasts_runner.cu b/src/gromacs/gpu_utils/tests/typecasts_runner.cu index 7d88601d9f..dde856d93f 100644 --- a/src/gromacs/gpu_utils/tests/typecasts_runner.cu +++ b/src/gromacs/gpu_utils/tests/typecasts_runner.cu @@ -118,8 +118,8 @@ void convertRVecToFloat3OnDevice(std::vector& h_rVecOutput, DeviceBuffer d_rVecInput; allocateDeviceBuffer(&d_rVecInput, numElements, deviceContext); - copyToDeviceBuffer(&d_rVecInput, h_rVecInput.data(), 0, numElements, deviceStream, - GpuApiCallBehavior::Sync, nullptr); + copyToDeviceBuffer( + &d_rVecInput, h_rVecInput.data(), 0, numElements, deviceStream, GpuApiCallBehavior::Sync, nullptr); DeviceBuffer d_float3Output; allocateDeviceBuffer(&d_float3Output, numElements * DIM, deviceContext); @@ -134,13 +134,17 @@ void convertRVecToFloat3OnDevice(std::vector& h_rVecOutput, kernelLaunchConfig.sharedMemorySize = 0; auto kernelPtr = convertRVecToFloat3OnDevice_kernel; - const auto kernelArgs = prepareGpuKernelArguments(kernelPtr, kernelLaunchConfig, - &d_float3Output, &d_rVecInput, &numElements); - launchGpuKernel(kernelPtr, kernelLaunchConfig, deviceStream, nullptr, - "convertRVecToFloat3OnDevice_kernel", kernelArgs); - - copyFromDeviceBuffer(h_float3Output.data(), &d_float3Output, 0, numElements, deviceStream, - GpuApiCallBehavior::Sync, nullptr); + const auto kernelArgs = prepareGpuKernelArguments( + kernelPtr, kernelLaunchConfig, &d_float3Output, &d_rVecInput, &numElements); + launchGpuKernel(kernelPtr, + kernelLaunchConfig, + deviceStream, + nullptr, + "convertRVecToFloat3OnDevice_kernel", + kernelArgs); + + copyFromDeviceBuffer( + h_float3Output.data(), &d_float3Output, 0, numElements, deviceStream, GpuApiCallBehavior::Sync, nullptr); saveFloat3InRVecFormat(h_rVecOutput, h_float3Output.data(), numElements); diff --git a/src/gromacs/hardware/cpuinfo.cpp b/src/gromacs/hardware/cpuinfo.cpp index 0c49696d92..15fa3cdbda 100644 --- a/src/gromacs/hardware/cpuinfo.cpp +++ b/src/gromacs/hardware/cpuinfo.cpp @@ -548,7 +548,9 @@ void renumberIndex(std::vector* v) for (std::size_t i = 0; i < uniqueSortedV.size(); i++) { unsigned int val = uniqueSortedV[i]; - std::replace_if(v->begin(), v->end(), [val](unsigned int& c) -> bool { return c == val; }, + std::replace_if(v->begin(), + v->end(), + [val](unsigned int& c) -> bool { return c == val; }, static_cast(i)); } } @@ -1027,8 +1029,8 @@ CpuInfo CpuInfo::detect() { result.features_.insert(CpuInfo::Feature::X86_Hygon); } - detectX86Features(&result.brandString_, &result.family_, &result.model_, &result.stepping_, - &result.features_); + detectX86Features( + &result.brandString_, &result.family_, &result.model_, &result.stepping_, &result.features_); result.logicalProcessors_ = detectX86LogicalProcessors(); } else @@ -1057,8 +1059,12 @@ CpuInfo CpuInfo::detect() // On Linux we might be able to find information in /proc/cpuinfo. If vendor or brand // is set to a known value this routine will not overwrite it. - detectProcCpuInfo(&result.vendor_, &result.brandString_, &result.family_, &result.model_, - &result.stepping_, &result.features_); + detectProcCpuInfo(&result.vendor_, + &result.brandString_, + &result.family_, + &result.model_, + &result.stepping_, + &result.features_); } if (!result.logicalProcessors_.empty()) diff --git a/src/gromacs/hardware/detecthardware.cpp b/src/gromacs/hardware/detecthardware.cpp index 690457fc52..2325c71bd1 100644 --- a/src/gromacs/hardware/detecthardware.cpp +++ b/src/gromacs/hardware/detecthardware.cpp @@ -248,8 +248,7 @@ static void gmx_collect_hardware_mpi(const gmx::CpuInfo& cpuInfo, countsLocal[3] = numCompatibleDevices; } - MPI_Allreduce(countsLocal.data(), countsReduced.data(), countsLocal.size(), MPI_INT, - MPI_SUM, MPI_COMM_WORLD); + MPI_Allreduce(countsLocal.data(), countsReduced.data(), countsLocal.size(), MPI_INT, MPI_SUM, MPI_COMM_WORLD); } constexpr int numElementsMax = 11; @@ -271,8 +270,7 @@ static void gmx_collect_hardware_mpi(const gmx::CpuInfo& cpuInfo, maxMinLocal[9] = -maxMinLocal[4]; maxMinLocal[10] = (cpuIsAmdZen1 ? 1 : 0); - MPI_Allreduce(maxMinLocal.data(), maxMinReduced.data(), maxMinLocal.size(), MPI_INT, - MPI_MAX, MPI_COMM_WORLD); + MPI_Allreduce(maxMinLocal.data(), maxMinReduced.data(), maxMinLocal.size(), MPI_INT, MPI_MAX, MPI_COMM_WORLD); } hardwareInfo->nphysicalnode = countsReduced[0]; @@ -330,7 +328,8 @@ void hardwareTopologyDoubleCheckDetection(const gmx::MDLogger gmx_unused& mdlog, GMX_LOG(mdlog.info) .appendTextFormatted( "Note: %d CPUs configured, but only %d were detected to be online.\n", - countConfigured, countFromDetection); + countConfigured, + countFromDetection); if (c_architecture == Architecture::X86 && countConfigured == 2 * countFromDetection) { diff --git a/src/gromacs/hardware/device_information.h b/src/gromacs/hardware/device_information.h index 54915dc52e..3b02e9ae6f 100644 --- a/src/gromacs/hardware/device_information.h +++ b/src/gromacs/hardware/device_information.h @@ -102,12 +102,15 @@ enum class DeviceStatus : int * missing, so that is suppressed. */ static const gmx::EnumerationArray c_deviceStateString = { - "compatible", "nonexistent", "incompatible", + "compatible", + "nonexistent", + "incompatible", // clang-format off // NOLINTNEXTLINE(bugprone-suspicious-missing-comma) "incompatible (please recompile with correct GMX" "_OPENCL_NB_CLUSTER_SIZE of 4)", // clang-format on - "incompatible (please use CUDA build for NVIDIA Volta GPUs or newer)", "non-functional", + "incompatible (please use CUDA build for NVIDIA Volta GPUs or newer)", + "non-functional", "unavailable" }; diff --git a/src/gromacs/hardware/device_management.cu b/src/gromacs/hardware/device_management.cu index 0e77621a5b..3df63f8131 100644 --- a/src/gromacs/hardware/device_management.cu +++ b/src/gromacs/hardware/device_management.cu @@ -86,7 +86,10 @@ static cudaError_t checkCompiledTargetCompatibility(int deviceId, const cudaDevi "might be rare, or some architectures were disabled in the build. \n" "Consult the install guide for how to use the GMX_CUDA_TARGET_SM and " "GMX_CUDA_TARGET_COMPUTE CMake variables to add this architecture. \n", - gmx::getProgramContext().displayName(), deviceId, deviceProp.major, deviceProp.minor); + gmx::getProgramContext().displayName(), + deviceId, + deviceProp.major, + deviceProp.minor); } return stat; @@ -127,7 +130,9 @@ static DeviceStatus isDeviceFunctional(const DeviceInformation& deviceInfo) cu_err = cudaSetDevice(deviceInfo.id); if (cu_err != cudaSuccess) { - fprintf(stderr, "Error while switching to device #%d. %s\n", deviceInfo.id, + fprintf(stderr, + "Error while switching to device #%d. %s\n", + deviceInfo.id, gmx::getDeviceErrorString(cu_err).c_str()); return DeviceStatus::NonFunctional; } @@ -160,7 +165,8 @@ static DeviceStatus isDeviceFunctional(const DeviceInformation& deviceInfo) // launchGpuKernel error is not fatal and should continue with marking the device bad fprintf(stderr, "Error occurred while running dummy kernel sanity check on device #%d:\n %s\n", - deviceInfo.id, formatExceptionMessageToString(ex).c_str()); + deviceInfo.id, + formatExceptionMessageToString(ex).c_str()); return DeviceStatus::NonFunctional; } @@ -373,14 +379,17 @@ std::string getDeviceInformationString(const DeviceInformation& deviceInfo) if (!gpuExists) { - return gmx::formatString("#%d: %s, stat: %s", deviceInfo.id, "N/A", - c_deviceStateString[deviceInfo.status]); + return gmx::formatString( + "#%d: %s, stat: %s", deviceInfo.id, "N/A", c_deviceStateString[deviceInfo.status]); } else { return gmx::formatString("#%d: NVIDIA %s, compute cap.: %d.%d, ECC: %3s, stat: %s", - deviceInfo.id, deviceInfo.prop.name, deviceInfo.prop.major, - deviceInfo.prop.minor, deviceInfo.prop.ECCEnabled ? "yes" : " no", + deviceInfo.id, + deviceInfo.prop.name, + deviceInfo.prop.major, + deviceInfo.prop.minor, + deviceInfo.prop.ECCEnabled ? "yes" : " no", c_deviceStateString[deviceInfo.status]); } } diff --git a/src/gromacs/hardware/device_management_common.cpp b/src/gromacs/hardware/device_management_common.cpp index 1392020ce0..608d9498b1 100644 --- a/src/gromacs/hardware/device_management_common.cpp +++ b/src/gromacs/hardware/device_management_common.cpp @@ -128,12 +128,14 @@ std::vector getCompatibleDeviceIds(const std::vector>& deviceInfoList, const int deviceId) { - auto foundIt = std::find_if(deviceInfoList.begin(), deviceInfoList.end(), + auto foundIt = std::find_if(deviceInfoList.begin(), + deviceInfoList.end(), [deviceId](auto& deviceInfo) { return deviceInfo->id == deviceId; }); if (foundIt == deviceInfoList.end()) { GMX_THROW(gmx::RangeError(gmx::formatString( - "Device ID %d did not correspond to any of the %zu detected device(s)", deviceId, + "Device ID %d did not correspond to any of the %zu detected device(s)", + deviceId, deviceInfoList.size()))); } return (*foundIt)->status == DeviceStatus::Compatible; diff --git a/src/gromacs/hardware/device_management_ocl.cpp b/src/gromacs/hardware/device_management_ocl.cpp index 3c25f64199..9f84049072 100644 --- a/src/gromacs/hardware/device_management_ocl.cpp +++ b/src/gromacs/hardware/device_management_ocl.cpp @@ -107,8 +107,8 @@ static bool runningOnCompatibleHWForNvidia(const DeviceInformation& deviceInfo) static const unsigned int ccMajorBad = 7; // Volta and Turing unsigned int ccMajor; cl_device_id devId = deviceInfo.oclDeviceId; - const cl_int err = clGetDeviceInfo(devId, CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV, - sizeof(ccMajor), &ccMajor, nullptr); + const cl_int err = clGetDeviceInfo( + devId, CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV, sizeof(ccMajor), &ccMajor, nullptr); if (err != CL_SUCCESS) { return true; // Err on a side of trusting the user to know what they are doing. @@ -150,9 +150,9 @@ static DeviceStatus isDeviceFunctional(const DeviceInformation& deviceInfo) // the device which has the following format: // OpenCL unsigned int deviceVersionMinor, deviceVersionMajor; - const int valuesScanned = std::sscanf(deviceInfo.device_version, "OpenCL %u.%u", - &deviceVersionMajor, &deviceVersionMinor); - const bool versionLargeEnough = + const int valuesScanned = std::sscanf( + deviceInfo.device_version, "OpenCL %u.%u", &deviceVersionMajor, &deviceVersionMinor); + const bool versionLargeEnough = ((valuesScanned == 2) && ((deviceVersionMajor > minVersionMajor) || (deviceVersionMajor == minVersionMajor && deviceVersionMinor >= minVersionMinor))); @@ -191,14 +191,17 @@ inline std::string makeOpenClInternalErrorString(const char* message, cl_int sta { if (message != nullptr) { - return gmx::formatString("%s did %ssucceed %d: %s", message, - ((status != CL_SUCCESS) ? "not " : ""), status, + return gmx::formatString("%s did %ssucceed %d: %s", + message, + ((status != CL_SUCCESS) ? "not " : ""), + status, ocl_get_error_string(status).c_str()); } else { return gmx::formatString("%sOpenCL error encountered %d: %s", - ((status != CL_SUCCESS) ? "" : "No "), status, + ((status != CL_SUCCESS) ? "" : "No "), + status, ocl_get_error_string(status).c_str()); } } @@ -262,8 +265,8 @@ static bool isDeviceFunctional(const DeviceInformation& deviceInfo, std::string* clSetKernelArg(kernel, 0, sizeof(void*), nullptr); const size_t localWorkSize = 1, globalWorkSize = 1; - if ((status = clEnqueueNDRangeKernel(commandQueue, kernel, 1, nullptr, &globalWorkSize, - &localWorkSize, 0, nullptr, nullptr)) + if ((status = clEnqueueNDRangeKernel( + commandQueue, kernel, 1, nullptr, &globalWorkSize, &localWorkSize, 0, nullptr, nullptr)) != CL_SUCCESS) { errorMessage->assign(makeOpenClInternalErrorString("clEnqueueNDRangeKernel", status)); @@ -324,7 +327,8 @@ bool isDeviceDetectionFunctional(std::string* errorMessage) GMX_RELEASE_ASSERT( status == CL_SUCCESS, gmx::formatString("An unexpected value was returned from clGetPlatformIDs %d: %s", - status, ocl_get_error_string(status).c_str()) + status, + ocl_get_error_string(status).c_str()) .c_str()); bool foundPlatform = (numPlatforms > 0); if (!foundPlatform && errorMessage != nullptr) @@ -412,8 +416,7 @@ std::vector> findDevices() /* If requesting req_dev_type devices fails, just go to the next platform */ if (CL_SUCCESS - != clGetDeviceIDs(ocl_platform_ids[i], req_dev_type, numDevices, ocl_device_ids, - &ocl_device_count)) + != clGetDeviceIDs(ocl_platform_ids[i], req_dev_type, numDevices, ocl_device_ids, &ocl_device_count)) { continue; } @@ -433,38 +436,54 @@ std::vector> findDevices() deviceInfoList[device_index]->oclDeviceId = ocl_device_ids[j]; deviceInfoList[device_index]->device_name[0] = 0; - clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_NAME, + clGetDeviceInfo(ocl_device_ids[j], + CL_DEVICE_NAME, sizeof(deviceInfoList[device_index]->device_name), - deviceInfoList[device_index]->device_name, nullptr); + deviceInfoList[device_index]->device_name, + nullptr); deviceInfoList[device_index]->device_version[0] = 0; - clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_VERSION, + clGetDeviceInfo(ocl_device_ids[j], + CL_DEVICE_VERSION, sizeof(deviceInfoList[device_index]->device_version), - deviceInfoList[device_index]->device_version, nullptr); + deviceInfoList[device_index]->device_version, + nullptr); deviceInfoList[device_index]->vendorName[0] = 0; - clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_VENDOR, + clGetDeviceInfo(ocl_device_ids[j], + CL_DEVICE_VENDOR, sizeof(deviceInfoList[device_index]->vendorName), - deviceInfoList[device_index]->vendorName, nullptr); + deviceInfoList[device_index]->vendorName, + nullptr); deviceInfoList[device_index]->compute_units = 0; - clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_MAX_COMPUTE_UNITS, + clGetDeviceInfo(ocl_device_ids[j], + CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(deviceInfoList[device_index]->compute_units), - &(deviceInfoList[device_index]->compute_units), nullptr); + &(deviceInfoList[device_index]->compute_units), + nullptr); deviceInfoList[device_index]->adress_bits = 0; - clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_ADDRESS_BITS, + clGetDeviceInfo(ocl_device_ids[j], + CL_DEVICE_ADDRESS_BITS, sizeof(deviceInfoList[device_index]->adress_bits), - &(deviceInfoList[device_index]->adress_bits), nullptr); + &(deviceInfoList[device_index]->adress_bits), + nullptr); deviceInfoList[device_index]->deviceVendor = getDeviceVendor(deviceInfoList[device_index]->vendorName); - clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_MAX_WORK_ITEM_SIZES, 3 * sizeof(size_t), - &deviceInfoList[device_index]->maxWorkItemSizes, nullptr); + clGetDeviceInfo(ocl_device_ids[j], + CL_DEVICE_MAX_WORK_ITEM_SIZES, + 3 * sizeof(size_t), + &deviceInfoList[device_index]->maxWorkItemSizes, + nullptr); - clGetDeviceInfo(ocl_device_ids[j], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), - &deviceInfoList[device_index]->maxWorkGroupSize, nullptr); + clGetDeviceInfo(ocl_device_ids[j], + CL_DEVICE_MAX_WORK_GROUP_SIZE, + sizeof(size_t), + &deviceInfoList[device_index]->maxWorkGroupSize, + nullptr); deviceInfoList[device_index]->status = gmx::checkGpu(device_index, *deviceInfoList[device_index]); @@ -550,13 +569,16 @@ std::string getDeviceInformationString(const DeviceInformation& deviceInfo) if (!gpuExists) { - return gmx::formatString("#%d: %s, status: %s", deviceInfo.id, "N/A", - c_deviceStateString[deviceInfo.status]); + return gmx::formatString( + "#%d: %s, status: %s", deviceInfo.id, "N/A", c_deviceStateString[deviceInfo.status]); } else { return gmx::formatString("#%d: name: %s, vendor: %s, device version: %s, status: %s", - deviceInfo.id, deviceInfo.device_name, deviceInfo.vendorName, - deviceInfo.device_version, c_deviceStateString[deviceInfo.status]); + deviceInfo.id, + deviceInfo.device_name, + deviceInfo.vendorName, + deviceInfo.device_version, + c_deviceStateString[deviceInfo.status]); } } diff --git a/src/gromacs/hardware/device_management_sycl.cpp b/src/gromacs/hardware/device_management_sycl.cpp index 0c142e0001..063fac54b5 100644 --- a/src/gromacs/hardware/device_management_sycl.cpp +++ b/src/gromacs/hardware/device_management_sycl.cpp @@ -146,9 +146,10 @@ static bool isDeviceFunctional(const cl::sycl::device& syclDevice, std::string* { if (errorMessage != nullptr) { - errorMessage->assign(gmx::formatString( - "Unable to run dummy kernel on device %s: %s", - syclDevice.get_info().c_str(), e.what())); + errorMessage->assign( + gmx::formatString("Unable to run dummy kernel on device %s: %s", + syclDevice.get_info().c_str(), + e.what())); } return false; } @@ -217,13 +218,14 @@ std::string getDeviceInformationString(const DeviceInformation& deviceInfo) if (!deviceExists) { - return gmx::formatString("#%d: %s, status: %s", deviceInfo.id, "N/A", - c_deviceStateString[deviceInfo.status]); + return gmx::formatString( + "#%d: %s, status: %s", deviceInfo.id, "N/A", c_deviceStateString[deviceInfo.status]); } else { return gmx::formatString( - "#%d: name: %s, vendor: %s, device version: %s, status: %s", deviceInfo.id, + "#%d: name: %s, vendor: %s, device version: %s, status: %s", + deviceInfo.id, deviceInfo.syclDevice.get_info().c_str(), deviceInfo.syclDevice.get_info().c_str(), deviceInfo.syclDevice.get_info().c_str(), diff --git a/src/gromacs/hardware/hardwaretopology.cpp b/src/gromacs/hardware/hardwaretopology.cpp index 1e9d785ce4..3659bc4e52 100644 --- a/src/gromacs/hardware/hardwaretopology.cpp +++ b/src/gromacs/hardware/hardwaretopology.cpp @@ -218,8 +218,8 @@ std::vector getHwLocDescendantsByType(const hwloc_topology* t // Go through children; if this object has no children obj->arity is 0, // and we'll return an empty vector. hwloc_obj_t tempNode = nullptr; - while ((tempNode = hwloc_get_next_child(const_cast(topo), - const_cast(obj), tempNode)) + while ((tempNode = hwloc_get_next_child( + const_cast(topo), const_cast(obj), tempNode)) != nullptr) { std::vector v2 = getHwLocDescendantsByType(topo, tempNode, type); @@ -463,7 +463,9 @@ bool parseHwLocNuma(hwloc_topology_t topo, HardwareTopology::Machine* machine) // assign stuff for (auto& v : machine->numa.relativeLatency) { - std::transform(v.begin(), v.end(), v.begin(), + std::transform(v.begin(), + v.end(), + v.begin(), std::bind(std::multiplies(), std::placeholders::_1, 1.0 / minLatency)); } machine->numa.baseLatency = 1.0; // latencies still do not have any units in hwloc-2.x @@ -589,9 +591,13 @@ bool parseHwLocDevices(hwloc_topology_t topo, HardwareTopology::Machine* machine GMX_RELEASE_ASSERT(p->attr, "Attributes should not be NULL for hwloc PCI object"); - machine->devices.push_back({ p->attr->pcidev.vendor_id, p->attr->pcidev.device_id, - p->attr->pcidev.class_id, p->attr->pcidev.domain, - p->attr->pcidev.bus, p->attr->pcidev.dev, p->attr->pcidev.func, + machine->devices.push_back({ p->attr->pcidev.vendor_id, + p->attr->pcidev.device_id, + p->attr->pcidev.class_id, + p->attr->pcidev.domain, + p->attr->pcidev.bus, + p->attr->pcidev.dev, + p->attr->pcidev.func, numaId }); } return !pcidevs.empty(); diff --git a/src/gromacs/hardware/identifyavx512fmaunits.cpp b/src/gromacs/hardware/identifyavx512fmaunits.cpp index 3ee4686533..4138130eef 100644 --- a/src/gromacs/hardware/identifyavx512fmaunits.cpp +++ b/src/gromacs/hardware/identifyavx512fmaunits.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2017,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2017,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -152,9 +152,35 @@ uint64_t timeFmaAndShuffleLoop(uint64_t loopCount) "\tmovq %%rdx, %0\n" : "=r"(cycles) : "r"(loopCount) - : "rax", "rbx", "rcx", "rdx", "zmm0", "zmm1", "zmm2", "zmm3", "zmm4", "zmm5", "zmm6", - "zmm7", "zmm8", "zmm9", "zmm10", "zmm11", "zmm12", "zmm13", "zmm14", "zmm15", "zmm16", - "zmm17", "zmm18", "zmm19", "zmm20", "zmm21", "zmm22", "zmm23", "zmm30"); + : "rax", + "rbx", + "rcx", + "rdx", + "zmm0", + "zmm1", + "zmm2", + "zmm3", + "zmm4", + "zmm5", + "zmm6", + "zmm7", + "zmm8", + "zmm9", + "zmm10", + "zmm11", + "zmm12", + "zmm13", + "zmm14", + "zmm15", + "zmm16", + "zmm17", + "zmm18", + "zmm19", + "zmm20", + "zmm21", + "zmm22", + "zmm23", + "zmm30"); return cycles; } @@ -219,8 +245,22 @@ uint64_t timeFmaOnlyLoop(uint64_t loopCount) "\tmovq %%rdx, %0\n" : "=r"(cycles) : "r"(loopCount) - : "rax", "rbx", "rcx", "rdx", "zmm0", "zmm1", "zmm2", "zmm3", "zmm4", "zmm5", "zmm6", - "zmm7", "zmm8", "zmm9", "zmm10", "zmm11"); + : "rax", + "rbx", + "rcx", + "rdx", + "zmm0", + "zmm1", + "zmm2", + "zmm3", + "zmm4", + "zmm5", + "zmm6", + "zmm7", + "zmm8", + "zmm9", + "zmm10", + "zmm11"); return cycles; } diff --git a/src/gromacs/hardware/printhardware.cpp b/src/gromacs/hardware/printhardware.cpp index 0720a12bbe..767b4f12b8 100644 --- a/src/gromacs/hardware/printhardware.cpp +++ b/src/gromacs/hardware/printhardware.cpp @@ -125,7 +125,8 @@ static void check_use_of_rdtscp_on_this_cpu(const gmx::MDLogger& mdlog, const gm "speed as accurate timings are needed for load-balancing.\n" "Please consider rebuilding %s with the GMX_USE_RDTSCP=ON CMake " "option.", - programName, programName); + programName, + programName); } } } @@ -138,7 +139,8 @@ static std::string detected_hardware_string(const gmx_hw_info_t* hwinfo, bool bF const gmx::HardwareTopology& hwTop = *hwinfo->hardwareTopology; s = gmx::formatString("\n"); - s += gmx::formatString("Running on %d node%s with total", hwinfo->nphysicalnode, + s += gmx::formatString("Running on %d node%s with total", + hwinfo->nphysicalnode, hwinfo->nphysicalnode == 1 ? "" : "s"); if (hwinfo->ncore_tot > 0) { @@ -147,7 +149,8 @@ static std::string detected_hardware_string(const gmx_hw_info_t* hwinfo, bool bF s += gmx::formatString(" %d logical cores", hwinfo->nhwthread_tot); if (canPerformDeviceDetection(nullptr)) { - s += gmx::formatString(", %d compatible GPU%s", hwinfo->ngpu_compatible_tot, + s += gmx::formatString(", %d compatible GPU%s", + hwinfo->ngpu_compatible_tot, hwinfo->ngpu_compatible_tot == 1 ? "" : "s"); } else if (bGPUBinary) @@ -228,8 +231,10 @@ static std::string detected_hardware_string(const gmx_hw_info_t* hwinfo, bool bF if (bFullCpuInfo) { - s += gmx::formatString(" Family: %d Model: %d Stepping: %d\n", cpuInfo.family(), - cpuInfo.model(), cpuInfo.stepping()); + s += gmx::formatString(" Family: %d Model: %d Stepping: %d\n", + cpuInfo.family(), + cpuInfo.model(), + cpuInfo.stepping()); s += gmx::formatString(" Features:"); for (auto& f : cpuInfo.featureSet()) @@ -336,7 +341,11 @@ static std::string detected_hardware_string(const gmx_hw_info_t* hwinfo, bool bF { s += gmx::formatString( " L%d: %zu bytes, linesize %d bytes, assoc. %d, shared %d ways\n", - c.level, c.size, c.linesize, c.associativity, c.shared); + c.level, + c.size, + c.linesize, + c.associativity, + c.shared); } } if (hwTop.supportLevel() >= gmx::HardwareTopology::SupportLevel::FullWithDevices) @@ -345,8 +354,15 @@ static std::string detected_hardware_string(const gmx_hw_info_t* hwinfo, bool bF for (auto& d : hwTop.machine().devices) { s += gmx::formatString( - " %04x:%02x:%02x.%1x Id: %04x:%04x Class: 0x%04x Numa: %d\n", d.domain, - d.bus, d.dev, d.func, d.vendorId, d.deviceId, d.classId, d.numaNodeId); + " %04x:%02x:%02x.%1x Id: %04x:%04x Class: 0x%04x Numa: %d\n", + d.domain, + d.bus, + d.dev, + d.func, + d.vendorId, + d.deviceId, + d.classId, + d.numaNodeId); } } } diff --git a/src/gromacs/hardware/tests/hardwaretopology.cpp b/src/gromacs/hardware/tests/hardwaretopology.cpp index 537807bd65..7f7fb076b7 100644 --- a/src/gromacs/hardware/tests/hardwaretopology.cpp +++ b/src/gromacs/hardware/tests/hardwaretopology.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2015,2016,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2015,2016,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -108,7 +108,8 @@ TEST(HardwareTopologyTest, ProcessorSelfconsistency) auto logicalProcessors = hwTop.machine().logicalProcessors; for (auto logicalProcessorIt = logicalProcessors.begin(); - logicalProcessorIt != logicalProcessors.end(); ++logicalProcessorIt) + logicalProcessorIt != logicalProcessors.end(); + ++logicalProcessorIt) { // Check that logical processor information contains // reasonable values. @@ -128,7 +129,8 @@ TEST(HardwareTopologyTest, ProcessorSelfconsistency) // for each logical processor. for (auto remainingLogicalProcessorIt = logicalProcessorIt + 1; - remainingLogicalProcessorIt != logicalProcessors.end(); ++remainingLogicalProcessorIt) + remainingLogicalProcessorIt != logicalProcessors.end(); + ++remainingLogicalProcessorIt) { SCOPED_TRACE(gmx::formatString("Other socket rank in machine: %d", remainingLogicalProcessorIt->socketRankInMachine)); diff --git a/src/gromacs/imd/imd.cpp b/src/gromacs/imd/imd.cpp index 6b5d3d28f4..995c4da8df 100644 --- a/src/gromacs/imd/imd.cpp +++ b/src/gromacs/imd/imd.cpp @@ -526,9 +526,15 @@ void write_IMDgroup_to_file(bool bIMD, if (bIMD) { IMDatoms = gmx_mtop_global_atoms(sys); - write_sto_conf_indexed(opt2fn("-imd", nfile, fnm), "IMDgroup", &IMDatoms, - state->x.rvec_array(), state->v.rvec_array(), ir->pbcType, - state->box, ir->imd->nat, ir->imd->ind); + write_sto_conf_indexed(opt2fn("-imd", nfile, fnm), + "IMDgroup", + &IMDatoms, + state->x.rvec_array(), + state->v.rvec_array(), + ir->pbcType, + state->box, + ir->imd->nat, + ir->imd->ind); } } @@ -540,8 +546,8 @@ void ImdSession::dd_make_local_IMD_atoms(const gmx_domdec_t* dd) return; } - dd_make_local_group_indices(dd->ga2la, impl_->nat, impl_->ind, &impl_->nat_loc, &impl_->ind_loc, - &impl_->nalloc_loc, impl_->xa_ind); + dd_make_local_group_indices( + dd->ga2la, impl_->nat, impl_->ind, &impl_->nat_loc, &impl_->ind_loc, &impl_->nalloc_loc, impl_->xa_ind); } @@ -991,7 +997,8 @@ void ImdSession::Impl::readCommand() /* Catch all rule for the remaining IMD types which we don't expect */ default: GMX_LOG(mdlog.warning) - .appendTextFormatted(" %s Received unexpected %s.", IMDstr, + .appendTextFormatted(" %s Received unexpected %s.", + IMDstr, enum_name(static_cast(itype), IMD_NR, eIMDType_names)); issueFatalError("Terminating connection"); break; @@ -1012,7 +1019,8 @@ void ImdSession::Impl::openOutputFile(const char* fn, "%s For a log of the IMD pull forces explicitly specify '-if' on the command " "line.\n" "%s (Not possible with energy minimization.)\n", - IMDstr, IMDstr); + IMDstr, + IMDstr); return; } @@ -1031,8 +1039,7 @@ void ImdSession::Impl::openOutputFile(const char* fn, "the atoms suffices.\n"); } - xvgr_header(outf, "IMD Pull Forces", "Time (ps)", - "# of Forces / Atom IDs / Forces (kJ/mol)", exvggtNONE, oenv); + xvgr_header(outf, "IMD Pull Forces", "Time (ps)", "# of Forces / Atom IDs / Forces (kJ/mol)", exvggtNONE, oenv); fprintf(outf, "# Can display and manipulate %d (of a total of %d) atoms via IMD.\n", nat, nat_total); fprintf(outf, "# column 1 : time (ps)\n"); @@ -1335,7 +1342,8 @@ std::unique_ptr makeImdSession(const t_inputrec* ir, .appendTextFormatted( "%s Integrator '%s' is not supported for Interactive Molecular Dynamics, " "running normally instead", - IMDstr, ei_names[ir->eI]); + IMDstr, + ei_names[ir->eI]); return session; } if (isMultiSim(ms)) @@ -1367,7 +1375,8 @@ std::unique_ptr makeImdSession(const t_inputrec* ir, .appendTextFormatted( "%s None of the -imd switches was used.\n" "%s This run will not accept incoming IMD connections", - IMDstr, IMDstr); + IMDstr, + IMDstr); } } /* end master only */ @@ -1556,8 +1565,8 @@ bool ImdSession::Impl::run(int64_t step, bool bNS, const matrix box, const rvec { /* Transfer the IMD positions to the master node. Every node contributes * its local positions x and stores them in the assembled xa array. */ - communicate_group_positions(cr, xa, xa_shifts, xa_eshifts, true, x, nat, nat_loc, ind_loc, - xa_ind, xa_old, box); + communicate_group_positions( + cr, xa, xa_shifts, xa_eshifts, true, x, nat, nat_loc, ind_loc, xa_ind, xa_old, box); /* If connected and master -> remove shifts */ if ((imdstep && bConnected) && MASTER(cr)) diff --git a/src/gromacs/linearalgebra/eigensolver.cpp b/src/gromacs/linearalgebra/eigensolver.cpp index f0643b413b..e365d9b1d0 100644 --- a/src/gromacs/linearalgebra/eigensolver.cpp +++ b/src/gromacs/linearalgebra/eigensolver.cpp @@ -91,12 +91,50 @@ void eigensolver(real* a, int n, int index_lower, int index_upper, real* eigenva */ #if GMX_DOUBLE F77_FUNC(dsyevr, DSYEVR) - (jobz, "I", "L", &n, a, &n, &vl, &vu, &index_lower, &index_upper, &abstol, &m, eigenvalues, - eigenvectors, &n, isuppz, &w0, &lwork, &iw0, &liwork, &info); + (jobz, + "I", + "L", + &n, + a, + &n, + &vl, + &vu, + &index_lower, + &index_upper, + &abstol, + &m, + eigenvalues, + eigenvectors, + &n, + isuppz, + &w0, + &lwork, + &iw0, + &liwork, + &info); #else F77_FUNC(ssyevr, SSYEVR) - (jobz, "I", "L", &n, a, &n, &vl, &vu, &index_lower, &index_upper, &abstol, &m, eigenvalues, - eigenvectors, &n, isuppz, &w0, &lwork, &iw0, &liwork, &info); + (jobz, + "I", + "L", + &n, + a, + &n, + &vl, + &vu, + &index_lower, + &index_upper, + &abstol, + &m, + eigenvalues, + eigenvectors, + &n, + isuppz, + &w0, + &lwork, + &iw0, + &liwork, + &info); #endif if (info != 0) @@ -115,12 +153,50 @@ void eigensolver(real* a, int n, int index_lower, int index_upper, real* eigenva #if GMX_DOUBLE F77_FUNC(dsyevr, DSYEVR) - (jobz, "I", "L", &n, a, &n, &vl, &vu, &index_lower, &index_upper, &abstol, &m, eigenvalues, - eigenvectors, &n, isuppz, work, &lwork, iwork, &liwork, &info); + (jobz, + "I", + "L", + &n, + a, + &n, + &vl, + &vu, + &index_lower, + &index_upper, + &abstol, + &m, + eigenvalues, + eigenvectors, + &n, + isuppz, + work, + &lwork, + iwork, + &liwork, + &info); #else F77_FUNC(ssyevr, SSYEVR) - (jobz, "I", "L", &n, a, &n, &vl, &vu, &index_lower, &index_upper, &abstol, &m, eigenvalues, - eigenvectors, &n, isuppz, work, &lwork, iwork, &liwork, &info); + (jobz, + "I", + "L", + &n, + a, + &n, + &vl, + &vu, + &index_lower, + &index_upper, + &abstol, + &m, + eigenvalues, + eigenvectors, + &n, + isuppz, + work, + &lwork, + iwork, + &liwork, + &info); #endif sfree(isuppz); @@ -198,12 +274,10 @@ void sparse_parallel_eigensolver(gmx_sparsematrix_t* A, int neig, real* eigenval { # if GMX_DOUBLE F77_FUNC(pdsaupd, PDSAUPD) - (&ido, "I", &n, "SA", &neig, &abstol, resid, &ncv, v, &n, iparam, ipntr, workd, iwork, - workl, &lworkl, &info); + (&ido, "I", &n, "SA", &neig, &abstol, resid, &ncv, v, &n, iparam, ipntr, workd, iwork, workl, &lworkl, &info); # else F77_FUNC(pssaupd, PSSAUPD) - (&ido, "I", &n, "SA", &neig, &abstol, resid, &ncv, v, &n, iparam, ipntr, workd, iwork, - workl, &lworkl, &info); + (&ido, "I", &n, "SA", &neig, &abstol, resid, &ncv, v, &n, iparam, ipntr, workd, iwork, workl, &lworkl, &info); # endif if (ido == -1 || ido == 1) { @@ -220,7 +294,9 @@ void sparse_parallel_eigensolver(gmx_sparsematrix_t* A, int neig, real* eigenval gmx_fatal(FARGS, "Maximum number of iterations (%d) reached in Arnoldi\n" "diagonalization, but only %d of %d eigenvectors converged.\n", - maxiter, iparam[4], neig); + maxiter, + iparam[4], + neig); } else if (info != 0) { @@ -233,12 +309,52 @@ void sparse_parallel_eigensolver(gmx_sparsematrix_t* A, int neig, real* eigenval # if GMX_DOUBLE F77_FUNC(pdseupd, PDSEUPD) - (&dovec, "A", select, eigenvalues, eigenvectors, &n, NULL, "I", &n, "SA", &neig, &abstol, resid, - &ncv, v, &n, iparam, ipntr, workd, workl, &lworkl, &info); + (&dovec, + "A", + select, + eigenvalues, + eigenvectors, + &n, + NULL, + "I", + &n, + "SA", + &neig, + &abstol, + resid, + &ncv, + v, + &n, + iparam, + ipntr, + workd, + workl, + &lworkl, + &info); # else F77_FUNC(psseupd, PSSEUPD) - (&dovec, "A", select, eigenvalues, eigenvectors, &n, NULL, "I", &n, "SA", &neig, &abstol, resid, - &ncv, v, &n, iparam, ipntr, workd, workl, &lworkl, &info); + (&dovec, + "A", + select, + eigenvalues, + eigenvectors, + &n, + NULL, + "I", + &n, + "SA", + &neig, + &abstol, + resid, + &ncv, + v, + &n, + iparam, + ipntr, + workd, + workl, + &lworkl, + &info); # endif sfree(v); @@ -318,12 +434,10 @@ void sparse_eigensolver(gmx_sparsematrix_t* A, int neig, real* eigenvalues, real { #if GMX_DOUBLE F77_FUNC(dsaupd, DSAUPD) - (&ido, "I", &n, "SA", &neig, &abstol, resid, &ncv, v, &n, iparam, ipntr, workd, iwork, - workl, &lworkl, &info); + (&ido, "I", &n, "SA", &neig, &abstol, resid, &ncv, v, &n, iparam, ipntr, workd, iwork, workl, &lworkl, &info); #else F77_FUNC(ssaupd, SSAUPD) - (&ido, "I", &n, "SA", &neig, &abstol, resid, &ncv, v, &n, iparam, ipntr, workd, iwork, - workl, &lworkl, &info); + (&ido, "I", &n, "SA", &neig, &abstol, resid, &ncv, v, &n, iparam, ipntr, workd, iwork, workl, &lworkl, &info); #endif if (ido == -1 || ido == 1) { @@ -340,7 +454,9 @@ void sparse_eigensolver(gmx_sparsematrix_t* A, int neig, real* eigenvalues, real gmx_fatal(FARGS, "Maximum number of iterations (%d) reached in Arnoldi\n" "diagonalization, but only %d of %d eigenvectors converged.\n", - maxiter, iparam[4], neig); + maxiter, + iparam[4], + neig); } else if (info != 0) { @@ -353,12 +469,52 @@ void sparse_eigensolver(gmx_sparsematrix_t* A, int neig, real* eigenvalues, real #if GMX_DOUBLE F77_FUNC(dseupd, DSEUPD) - (&dovec, "A", select, eigenvalues, eigenvectors, &n, nullptr, "I", &n, "SA", &neig, &abstol, - resid, &ncv, v, &n, iparam, ipntr, workd, workl, &lworkl, &info); + (&dovec, + "A", + select, + eigenvalues, + eigenvectors, + &n, + nullptr, + "I", + &n, + "SA", + &neig, + &abstol, + resid, + &ncv, + v, + &n, + iparam, + ipntr, + workd, + workl, + &lworkl, + &info); #else F77_FUNC(sseupd, SSEUPD) - (&dovec, "A", select, eigenvalues, eigenvectors, &n, nullptr, "I", &n, "SA", &neig, &abstol, - resid, &ncv, v, &n, iparam, ipntr, workd, workl, &lworkl, &info); + (&dovec, + "A", + select, + eigenvalues, + eigenvectors, + &n, + nullptr, + "I", + &n, + "SA", + &neig, + &abstol, + resid, + &ncv, + v, + &n, + iparam, + ipntr, + workd, + workl, + &lworkl, + &info); #endif sfree(v); diff --git a/src/gromacs/linearalgebra/gmx_arpack.cpp b/src/gromacs/linearalgebra/gmx_arpack.cpp index 4ee3114cb0..8009a46988 100644 --- a/src/gromacs/linearalgebra/gmx_arpack.cpp +++ b/src/gromacs/linearalgebra/gmx_arpack.cpp @@ -841,8 +841,7 @@ static void F77_FUNC(dsapps, DSAPPS)(int* n, if (h__[*kev + 1 + h_dim1] > 0.) { F77_FUNC(dgemv, DGEMV) - ("N", n, &kplusp, &c_b5, &v[v_offset], ldv, &q[(*kev + 1) * q_dim1 + 1], &c__1, &c_b4, - &workd[*n + 1], &c__1); + ("N", n, &kplusp, &c_b5, &v[v_offset], ldv, &q[(*kev + 1) * q_dim1 + 1], &c__1, &c_b4, &workd[*n + 1], &c__1); } i__1 = *kev; @@ -850,8 +849,7 @@ static void F77_FUNC(dsapps, DSAPPS)(int* n, { i__2 = kplusp - i__ + 1; F77_FUNC(dgemv, DGEMV) - ("N", n, &i__2, &c_b5, &v[v_offset], ldv, &q[(*kev - i__ + 1) * q_dim1 + 1], &c__1, &c_b4, - &workd[1], &c__1); + ("N", n, &i__2, &c_b5, &v[v_offset], ldv, &q[(*kev - i__ + 1) * q_dim1 + 1], &c__1, &c_b4, &workd[1], &c__1); F77_FUNC(dcopy, DCOPY)(n, &workd[1], &c__1, &v[(kplusp - i__ + 1) * v_dim1 + 1], &c__1); } @@ -1461,8 +1459,20 @@ L20: L30: F77_FUNC(dgetv0, DGETV0) - (ido, bmat, &iwork[11], &c__0, n, &iwork[12], &v[v_offset], ldv, &resid[1], rnorm, &ipntr[1], - &workd[1], &iwork[21], &iwork[7]); + (ido, + bmat, + &iwork[11], + &c__0, + n, + &iwork[12], + &v[v_offset], + ldv, + &resid[1], + rnorm, + &ipntr[1], + &workd[1], + &iwork[21], + &iwork[7]); if (*ido != 99) { goto L9000; @@ -1554,14 +1564,12 @@ L65: if (*mode != 2) { F77_FUNC(dgemv, DGEMV) - ("T", n, &iwork[12], &c_b18, &v[v_offset], ldv, &workd[iwork[8]], &c__1, &c_b42, - &workd[iwork[9]], &c__1); + ("T", n, &iwork[12], &c_b18, &v[v_offset], ldv, &workd[iwork[8]], &c__1, &c_b42, &workd[iwork[9]], &c__1); } else { F77_FUNC(dgemv, DGEMV) - ("T", n, &iwork[12], &c_b18, &v[v_offset], ldv, &workd[iwork[10]], &c__1, &c_b42, - &workd[iwork[9]], &c__1); + ("T", n, &iwork[12], &c_b18, &v[v_offset], ldv, &workd[iwork[10]], &c__1, &c_b42, &workd[iwork[9]], &c__1); } F77_FUNC(dgemv, DGEMV) @@ -1615,8 +1623,7 @@ L70: L80: F77_FUNC(dgemv, DGEMV) - ("T", n, &iwork[12], &c_b18, &v[v_offset], ldv, &workd[iwork[8]], &c__1, &c_b42, - &workd[iwork[9]], &c__1); + ("T", n, &iwork[12], &c_b18, &v[v_offset], ldv, &workd[iwork[8]], &c__1, &c_b42, &workd[iwork[9]], &c__1); F77_FUNC(dgemv, DGEMV) ("N", n, &iwork[12], &c_b50, &v[v_offset], ldv, &workd[iwork[9]], &c__1, &c_b18, &resid[1], &c__1); @@ -1808,8 +1815,20 @@ static void F77_FUNC(dsaup2, DSAUP2)(int* ido, if (iwork[2] == 1) { F77_FUNC(dgetv0, DGETV0) - (ido, bmat, &c__1, &iwork[3], n, &c__1, &v[v_offset], ldv, &resid[1], &workd[*n * 3 + 1], - &ipntr[1], &workd[1], &iwork[41], info); + (ido, + bmat, + &c__1, + &iwork[3], + n, + &c__1, + &v[v_offset], + ldv, + &resid[1], + &workd[*n * 3 + 1], + &ipntr[1], + &workd[1], + &iwork[41], + info); if (*ido != 99) { @@ -1842,8 +1861,22 @@ static void F77_FUNC(dsaup2, DSAUP2)(int* ido, } F77_FUNC(dsaitr, DSAITR) - (ido, bmat, n, &c__0, &iwork[9], mode, &resid[1], &workd[*n * 3 + 1], &v[v_offset], ldv, - &h__[h_offset], ldh, &ipntr[1], &workd[1], &iwork[21], info); + (ido, + bmat, + n, + &c__0, + &iwork[9], + mode, + &resid[1], + &workd[*n * 3 + 1], + &v[v_offset], + ldv, + &h__[h_offset], + ldh, + &ipntr[1], + &workd[1], + &iwork[21], + info); if (*ido != 99) { @@ -1869,8 +1902,22 @@ L20: iwork[4] = 1; F77_FUNC(dsaitr, DSAITR) - (ido, bmat, n, nev, np, mode, &resid[1], &workd[*n * 3 + 1], &v[v_offset], ldv, &h__[h_offset], - ldh, &ipntr[1], &workd[1], &iwork[21], info); + (ido, + bmat, + n, + nev, + np, + mode, + &resid[1], + &workd[*n * 3 + 1], + &v[v_offset], + ldv, + &h__[h_offset], + ldh, + &ipntr[1], + &workd[1], + &iwork[21], + info); if (*ido != 99) { @@ -2050,8 +2097,7 @@ L50: } F77_FUNC(dsapps, DSAPPS) - (n, nev, np, &ritz[1], &v[v_offset], ldv, &h__[h_offset], ldh, &resid[1], &q[q_offset], ldq, - &workd[1]); + (n, nev, np, &ritz[1], &v[v_offset], ldv, &h__[h_offset], ldh, &resid[1], &q[q_offset], ldq, &workd[1]); iwork[1] = 1; if (*bmat == 'G') @@ -2235,9 +2281,31 @@ void F77_FUNC(dsaupd, DSAUPD)(int* ido, } F77_FUNC(dsaup2, DSAUP2) - (ido, bmat, n, which, &iwork[13], &iwork[15], tol, &resid[1], &iwork[11], &iwork[6], &iwork[5], - &iwork[10], &v[v_offset], ldv, &workl[iwork[3]], &iwork[8], &workl[iwork[16]], &workl[iwork[1]], - &workl[iwork[4]], &iwork[9], &workl[iwork[7]], &ipntr[1], &workd[1], &iwork[21], info); + (ido, + bmat, + n, + which, + &iwork[13], + &iwork[15], + tol, + &resid[1], + &iwork[11], + &iwork[6], + &iwork[5], + &iwork[10], + &v[v_offset], + ldv, + &workl[iwork[3]], + &iwork[8], + &workl[iwork[16]], + &workl[iwork[1]], + &workl[iwork[4]], + &iwork[9], + &workl[iwork[7]], + &ipntr[1], + &workd[1], + &iwork[21], + info); if (*ido == 3) { @@ -2673,8 +2741,18 @@ void F77_FUNC(dseupd, DSEUPD)(int* rvec, (ncv, &nconv, &workl[iq], &ldq, &workl[iw + *ncv], &workl[ihb], &ierr); F77_FUNC(dorm2r, DORM2R) - ("Right", "Notranspose", n, ncv, &nconv, &workl[iq], &ldq, &workl[iw + *ncv], &v[v_offset], - ldv, &workd[*n + 1], &ierr); + ("Right", + "Notranspose", + n, + ncv, + &nconv, + &workl[iq], + &ldq, + &workl[iw + *ncv], + &v[v_offset], + ldv, + &workd[*n + 1], + &ierr); F77_FUNC(dlacpy, DLACPY)("All", n, &nconv, &v[v_offset], ldv, &z__[z_offset], ldz); i__1 = *ncv - 1; @@ -2684,8 +2762,7 @@ void F77_FUNC(dseupd, DSEUPD)(int* rvec, } workl[ihb + *ncv - 1] = 1.; F77_FUNC(dorm2r, DORM2R) - ("Left", "Transpose", ncv, &c__1, &nconv, &workl[iq], &ldq, &workl[iw + *ncv], &workl[ihb], - ncv, &temp, &ierr); + ("Left", "Transpose", ncv, &c__1, &nconv, &workl[iq], &ldq, &workl[iw + *ncv], &workl[ihb], ncv, &temp, &ierr); } else if (*rvec && *howmny == 'S') { @@ -3562,8 +3639,7 @@ static void F77_FUNC(ssapps, SSAPPS)(int* n, if (h__[*kev + 1 + h_dim1] > 0.) { F77_FUNC(sgemv, SGEMV) - ("N", n, &kplusp, &c_b5, &v[v_offset], ldv, &q[(*kev + 1) * q_dim1 + 1], &c__1, &c_b4, - &workd[*n + 1], &c__1); + ("N", n, &kplusp, &c_b5, &v[v_offset], ldv, &q[(*kev + 1) * q_dim1 + 1], &c__1, &c_b4, &workd[*n + 1], &c__1); } i__1 = *kev; @@ -3571,8 +3647,7 @@ static void F77_FUNC(ssapps, SSAPPS)(int* n, { i__2 = kplusp - i__ + 1; F77_FUNC(sgemv, SGEMV) - ("N", n, &i__2, &c_b5, &v[v_offset], ldv, &q[(*kev - i__ + 1) * q_dim1 + 1], &c__1, &c_b4, - &workd[1], &c__1); + ("N", n, &i__2, &c_b5, &v[v_offset], ldv, &q[(*kev - i__ + 1) * q_dim1 + 1], &c__1, &c_b4, &workd[1], &c__1); F77_FUNC(scopy, SCOPY)(n, &workd[1], &c__1, &v[(kplusp - i__ + 1) * v_dim1 + 1], &c__1); } @@ -4177,8 +4252,20 @@ L20: L30: F77_FUNC(sgetv0, sgetv0) - (ido, bmat, &iwork[11], &c__0, n, &iwork[12], &v[v_offset], ldv, &resid[1], rnorm, &ipntr[1], - &workd[1], &iwork[21], &iwork[7]); + (ido, + bmat, + &iwork[11], + &c__0, + n, + &iwork[12], + &v[v_offset], + ldv, + &resid[1], + rnorm, + &ipntr[1], + &workd[1], + &iwork[21], + &iwork[7]); if (*ido != 99) { goto L9000; @@ -4270,14 +4357,12 @@ L65: if (*mode != 2) { F77_FUNC(sgemv, SGEMV) - ("T", n, &iwork[12], &c_b18, &v[v_offset], ldv, &workd[iwork[8]], &c__1, &c_b42, - &workd[iwork[9]], &c__1); + ("T", n, &iwork[12], &c_b18, &v[v_offset], ldv, &workd[iwork[8]], &c__1, &c_b42, &workd[iwork[9]], &c__1); } else { F77_FUNC(sgemv, SGEMV) - ("T", n, &iwork[12], &c_b18, &v[v_offset], ldv, &workd[iwork[10]], &c__1, &c_b42, - &workd[iwork[9]], &c__1); + ("T", n, &iwork[12], &c_b18, &v[v_offset], ldv, &workd[iwork[10]], &c__1, &c_b42, &workd[iwork[9]], &c__1); } F77_FUNC(sgemv, SGEMV) @@ -4331,8 +4416,7 @@ L70: L80: F77_FUNC(sgemv, SGEMV) - ("T", n, &iwork[12], &c_b18, &v[v_offset], ldv, &workd[iwork[8]], &c__1, &c_b42, - &workd[iwork[9]], &c__1); + ("T", n, &iwork[12], &c_b18, &v[v_offset], ldv, &workd[iwork[8]], &c__1, &c_b42, &workd[iwork[9]], &c__1); F77_FUNC(sgemv, SGEMV) ("N", n, &iwork[12], &c_b50, &v[v_offset], ldv, &workd[iwork[9]], &c__1, &c_b18, &resid[1], &c__1); @@ -4524,8 +4608,20 @@ static void F77_FUNC(ssaup2, SSAUP2)(int* ido, if (iwork[2] == 1) { F77_FUNC(sgetv0, SGETV0) - (ido, bmat, &c__1, &iwork[3], n, &c__1, &v[v_offset], ldv, &resid[1], &workd[*n * 3 + 1], - &ipntr[1], &workd[1], &iwork[41], info); + (ido, + bmat, + &c__1, + &iwork[3], + n, + &c__1, + &v[v_offset], + ldv, + &resid[1], + &workd[*n * 3 + 1], + &ipntr[1], + &workd[1], + &iwork[41], + info); if (*ido != 99) { @@ -4558,8 +4654,22 @@ static void F77_FUNC(ssaup2, SSAUP2)(int* ido, } F77_FUNC(ssaitr, SSAITR) - (ido, bmat, n, &c__0, &iwork[9], mode, &resid[1], &workd[*n * 3 + 1], &v[v_offset], ldv, - &h__[h_offset], ldh, &ipntr[1], &workd[1], &iwork[21], info); + (ido, + bmat, + n, + &c__0, + &iwork[9], + mode, + &resid[1], + &workd[*n * 3 + 1], + &v[v_offset], + ldv, + &h__[h_offset], + ldh, + &ipntr[1], + &workd[1], + &iwork[21], + info); if (*ido != 99) { @@ -4585,8 +4695,22 @@ L20: iwork[4] = 1; F77_FUNC(ssaitr, SSAITR) - (ido, bmat, n, nev, np, mode, &resid[1], &workd[*n * 3 + 1], &v[v_offset], ldv, &h__[h_offset], - ldh, &ipntr[1], &workd[1], &iwork[21], info); + (ido, + bmat, + n, + nev, + np, + mode, + &resid[1], + &workd[*n * 3 + 1], + &v[v_offset], + ldv, + &h__[h_offset], + ldh, + &ipntr[1], + &workd[1], + &iwork[21], + info); if (*ido != 99) { @@ -4767,8 +4891,7 @@ L50: } F77_FUNC(ssapps, SSAPPS) - (n, nev, np, &ritz[1], &v[v_offset], ldv, &h__[h_offset], ldh, &resid[1], &q[q_offset], ldq, - &workd[1]); + (n, nev, np, &ritz[1], &v[v_offset], ldv, &h__[h_offset], ldh, &resid[1], &q[q_offset], ldq, &workd[1]); iwork[1] = 1; if (*bmat == 'G') @@ -4952,9 +5075,31 @@ void F77_FUNC(ssaupd, SSAUPD)(int* ido, } F77_FUNC(ssaup2, SSAUP2) - (ido, bmat, n, which, &iwork[13], &iwork[15], tol, &resid[1], &iwork[11], &iwork[6], &iwork[5], - &iwork[10], &v[v_offset], ldv, &workl[iwork[3]], &iwork[8], &workl[iwork[16]], &workl[iwork[1]], - &workl[iwork[4]], &iwork[9], &workl[iwork[7]], &ipntr[1], &workd[1], &iwork[21], info); + (ido, + bmat, + n, + which, + &iwork[13], + &iwork[15], + tol, + &resid[1], + &iwork[11], + &iwork[6], + &iwork[5], + &iwork[10], + &v[v_offset], + ldv, + &workl[iwork[3]], + &iwork[8], + &workl[iwork[16]], + &workl[iwork[1]], + &workl[iwork[4]], + &iwork[9], + &workl[iwork[7]], + &ipntr[1], + &workd[1], + &iwork[21], + info); if (*ido == 3) { @@ -5390,8 +5535,18 @@ void F77_FUNC(sseupd, SSEUPD)(int* rvec, (ncv, &nconv, &workl[iq], &ldq, &workl[iw + *ncv], &workl[ihb], &ierr); F77_FUNC(sorm2r, SORM2R) - ("Right", "Notranspose", n, ncv, &nconv, &workl[iq], &ldq, &workl[iw + *ncv], &v[v_offset], - ldv, &workd[*n + 1], &ierr); + ("Right", + "Notranspose", + n, + ncv, + &nconv, + &workl[iq], + &ldq, + &workl[iw + *ncv], + &v[v_offset], + ldv, + &workd[*n + 1], + &ierr); F77_FUNC(slacpy, SLACPY)("All", n, &nconv, &v[v_offset], ldv, &z__[z_offset], ldz); i__1 = *ncv - 1; @@ -5401,8 +5556,7 @@ void F77_FUNC(sseupd, SSEUPD)(int* rvec, } workl[ihb + *ncv - 1] = 1.; F77_FUNC(sorm2r, SORM2R) - ("Left", "Transpose", ncv, &c__1, &nconv, &workl[iq], &ldq, &workl[iw + *ncv], &workl[ihb], - ncv, &temp, &ierr); + ("Left", "Transpose", ncv, &c__1, &nconv, &workl[iq], &ldq, &workl[iw + *ncv], &workl[ihb], ncv, &temp, &ierr); } else if (*rvec && *howmny == 'S') { diff --git a/src/gromacs/listed_forces/bonded.cpp b/src/gromacs/listed_forces/bonded.cpp index 4daf423874..d5b939696b 100644 --- a/src/gromacs/listed_forces/bonded.cpp +++ b/src/gromacs/listed_forces/bonded.cpp @@ -82,8 +82,10 @@ using namespace gmx; // TODO: Remove when this file is moved into gmx namespace const EnumerationArray c_bondedKernelFlavorStrings = { - "forces, using SIMD when available", "forces, not using SIMD", - "forces, virial, and energy (ie. not using SIMD)", "forces and energy (ie. not using SIMD)" + "forces, using SIMD when available", + "forces, not using SIMD", + "forces, virial, and energy (ie. not using SIMD)", + "forces and energy (ie. not using SIMD)" }; namespace { @@ -408,8 +410,12 @@ real FENE_bonds(int nbonds, if (dr2 >= bm2) { - gmx_fatal(FARGS, "r^2 (%f) >= bm^2 (%f) in FENE bond between atoms %d and %d", dr2, bm2, - glatnr(global_atom_index, ai), glatnr(global_atom_index, aj)); + gmx_fatal(FARGS, + "r^2 (%f) >= bm^2 (%f) in FENE bond between atoms %d and %d", + dr2, + bm2, + glatnr(global_atom_index, ai), + glatnr(global_atom_index, aj)); } omdr2obm2 = one - dr2 / bm2; @@ -479,9 +485,14 @@ bonds(int nbonds, dr2 = iprod(dx, dx); /* 5 */ dr = std::sqrt(dr2); /* 10 */ - *dvdlambda += harmonic(forceparams[type].harmonic.krA, forceparams[type].harmonic.krB, - forceparams[type].harmonic.rA, forceparams[type].harmonic.rB, dr, - lambda, &vbond, &fbond); /* 19 */ + *dvdlambda += harmonic(forceparams[type].harmonic.krA, + forceparams[type].harmonic.krB, + forceparams[type].harmonic.rA, + forceparams[type].harmonic.rB, + dr, + lambda, + &vbond, + &fbond); /* 19 */ if (dr2 == 0.0) { @@ -819,8 +830,7 @@ real water_pol(int nbonds, type = forceatoms[i]; if (type != type0) { - gmx_fatal(FARGS, "Sorry, type = %d, type0 = %d, file = %s, line = %d", type, type0, - __FILE__, __LINE__); + gmx_fatal(FARGS, "Sorry, type = %d, type0 = %d, file = %s, line = %d", type, type0, __FILE__, __LINE__); } aO = forceatoms[i + 1]; aH1 = forceatoms[i + 2]; @@ -1005,9 +1015,14 @@ angles(int nbonds, theta = bond_angle(x[ai], x[aj], x[ak], pbc, r_ij, r_kj, &cos_theta, &t1, &t2); /* 41 */ - *dvdlambda += harmonic(forceparams[type].harmonic.krA, forceparams[type].harmonic.krB, + *dvdlambda += harmonic(forceparams[type].harmonic.krA, + forceparams[type].harmonic.krB, forceparams[type].harmonic.rA * DEG2RAD, - forceparams[type].harmonic.rB * DEG2RAD, theta, lambda, &va, &dVdt); /* 21 */ + forceparams[type].harmonic.rB * DEG2RAD, + theta, + lambda, + &va, + &dVdt); /* 21 */ vtot += va; cos_theta2 = gmx::square(cos_theta); @@ -1212,8 +1227,8 @@ angles(int nbonds, f_kz_S = fnma(cik_S, rijz_S, f_kz_S); transposeScatterIncrU<4>(reinterpret_cast(f), ai, f_ix_S, f_iy_S, f_iz_S); - transposeScatterDecrU<4>(reinterpret_cast(f), aj, f_ix_S + f_kx_S, f_iy_S + f_ky_S, - f_iz_S + f_kz_S); + transposeScatterDecrU<4>( + reinterpret_cast(f), aj, f_ix_S + f_kx_S, f_iy_S + f_ky_S, f_iz_S + f_kz_S); transposeScatterIncrU<4>(reinterpret_cast(f), ak, f_kx_S, f_ky_S, f_kz_S); } @@ -1534,8 +1549,8 @@ urey_bradley(int nbonds, const SimdReal f_kz_S = fnma(cik_S, rijz_S, ckk_S * rkjz_S) - f_ikz_S; transposeScatterIncrU<4>(reinterpret_cast(f), ai, f_ix_S, f_iy_S, f_iz_S); - transposeScatterDecrU<4>(reinterpret_cast(f), aj, f_ix_S + f_kx_S, f_iy_S + f_ky_S, - f_iz_S + f_kz_S); + transposeScatterDecrU<4>( + reinterpret_cast(f), aj, f_ix_S + f_kx_S, f_iy_S + f_ky_S, f_iz_S + f_kz_S); transposeScatterIncrU<4>(reinterpret_cast(f), ak, f_kx_S, f_ky_S, f_kz_S); } @@ -1935,8 +1950,8 @@ pdihs(int nbonds, const int ak = forceatoms[i + 3]; const int al = forceatoms[i + 4]; - const real phi = dih_angle(x[ai], x[aj], x[ak], x[al], pbc, r_ij, r_kj, r_kl, m, n, &t1, - &t2, &t3); /* 84 */ + const real phi = + dih_angle(x[ai], x[aj], x[ak], x[al], pbc, r_ij, r_kj, r_kl, m, n, &t1, &t2, &t3); /* 84 */ /* Loop over dihedrals working on the same atoms, * so we avoid recalculating angles and distributing forces. @@ -1945,17 +1960,23 @@ pdihs(int nbonds, do { const int type = forceatoms[i]; - ddphi_tot += dopdihs(forceparams[type].pdihs.cpA, forceparams[type].pdihs.cpB, - forceparams[type].pdihs.phiA, forceparams[type].pdihs.phiB, - forceparams[type].pdihs.mult, phi, lambda, &vtot, dvdlambda); + ddphi_tot += dopdihs(forceparams[type].pdihs.cpA, + forceparams[type].pdihs.cpB, + forceparams[type].pdihs.phiA, + forceparams[type].pdihs.phiB, + forceparams[type].pdihs.mult, + phi, + lambda, + &vtot, + dvdlambda); i += 5; } while (i < nbonds && forceatoms[i + 1] == ai && forceatoms[i + 2] == aj && forceatoms[i + 3] == ak && forceatoms[i + 4] == al); - do_dih_fup(ai, aj, ak, al, ddphi_tot, r_ij, r_kj, r_kl, m, n, f, fshift, pbc, x, t1, - t2, t3); /* 112 */ - } /* 223 TOTAL */ + do_dih_fup( + ai, aj, ak, al, ddphi_tot, r_ij, r_kj, r_kl, m, n, f, fshift, pbc, x, t1, t2, t3); /* 112 */ + } /* 223 TOTAL */ return vtot; } @@ -2042,8 +2063,8 @@ pdihs(int nbonds, } /* Calculate GMX_SIMD_REAL_WIDTH dihedral angles at once */ - dih_angle_simd(x, ai, aj, ak, al, pbc_simd, &phi_S, &mx_S, &my_S, &mz_S, &nx_S, &ny_S, - &nz_S, &nrkj_m2_S, &nrkj_n2_S, &p_S, &q_S); + dih_angle_simd( + x, ai, aj, ak, al, pbc_simd, &phi_S, &mx_S, &my_S, &mz_S, &nx_S, &ny_S, &nz_S, &nrkj_m2_S, &nrkj_n2_S, &p_S, &q_S); cp_S = load(cp); phi0_S = load(phi0) * deg2rad_S; @@ -2158,8 +2179,8 @@ rbdihs(int nbonds, } /* Calculate GMX_SIMD_REAL_WIDTH dihedral angles at once */ - dih_angle_simd(x, ai, aj, ak, al, pbc_simd, &phi_S, &mx_S, &my_S, &mz_S, &nx_S, &ny_S, - &nz_S, &nrkj_m2_S, &nrkj_n2_S, &p_S, &q_S); + dih_angle_simd( + x, ai, aj, ak, al, pbc_simd, &phi_S, &mx_S, &my_S, &mz_S, &nx_S, &ny_S, &nz_S, &nrkj_m2_S, &nrkj_n2_S, &p_S, &q_S); /* Change to polymer convention */ phi_S = phi_S - pi_S; @@ -2264,8 +2285,7 @@ real idihs(int nbonds, dvdl_term += 0.5 * (kB - kA) * dp2 - kk * dphi0 * dp; - do_dih_fup(ai, aj, ak, al, -ddphi, r_ij, r_kj, r_kl, m, n, f, fshift, pbc, x, t1, - t2, t3); /* 112 */ + do_dih_fup(ai, aj, ak, al, -ddphi, r_ij, r_kj, r_kl, m, n, f, fshift, pbc, x, t1, t2, t3); /* 112 */ /* 218 TOTAL */ } @@ -2318,9 +2338,15 @@ real low_angres(int nbonds, cos_phi = cos_angle(r_ij, r_kl); /* 25 */ phi = std::acos(cos_phi); /* 10 */ - *dvdlambda += dopdihs_min(forceparams[type].pdihs.cpA, forceparams[type].pdihs.cpB, - forceparams[type].pdihs.phiA, forceparams[type].pdihs.phiB, - forceparams[type].pdihs.mult, phi, lambda, &vid, &dVdphi); /* 40 */ + *dvdlambda += dopdihs_min(forceparams[type].pdihs.cpA, + forceparams[type].pdihs.cpB, + forceparams[type].pdihs.phiA, + forceparams[type].pdihs.phiB, + forceparams[type].pdihs.mult, + phi, + lambda, + &vid, + &dVdphi); /* 40 */ vtot += vid; @@ -2485,8 +2511,8 @@ real dihres(int nbonds, { *dvdlambda += kfac * ddp * ((dphiB - dphiA) - (phi0B - phi0A)); } - do_dih_fup(ai, aj, ak, al, ddphi, r_ij, r_kj, r_kl, m, n, f, fshift, pbc, x, t1, - t2, t3); /* 112 */ + do_dih_fup( + ai, aj, ak, al, ddphi, r_ij, r_kj, r_kl, m, n, f, fshift, pbc, x, t1, t2, t3); /* 112 */ } } return vtot; @@ -2575,8 +2601,8 @@ real restrangles(int nbonds, * {\sin^2\theta_i}\f] ({eq:ReB} and ref \cite{MonicaGoga2013} from the manual). * For more explanations see comments file "restcbt.h". */ - compute_factors_restangles(type, forceparams, delta_ante, delta_post, &prefactor, - &ratio_ante, &ratio_post, &v); + compute_factors_restangles( + type, forceparams, delta_ante, delta_post, &prefactor, &ratio_ante, &ratio_post, &v); /* Forces are computed per component */ for (d = 0; d < DIM; d++) @@ -2662,11 +2688,25 @@ real restrdihs(int nbonds, * ({eq:ReB} and ref \cite{MonicaGoga2013} from the manual). * For more explanations see comments file "restcbt.h" */ - compute_factors_restrdihs( - type, forceparams, delta_ante, delta_crnt, delta_post, &factor_phi_ai_ante, - &factor_phi_ai_crnt, &factor_phi_ai_post, &factor_phi_aj_ante, &factor_phi_aj_crnt, - &factor_phi_aj_post, &factor_phi_ak_ante, &factor_phi_ak_crnt, &factor_phi_ak_post, - &factor_phi_al_ante, &factor_phi_al_crnt, &factor_phi_al_post, &prefactor_phi, &v); + compute_factors_restrdihs(type, + forceparams, + delta_ante, + delta_crnt, + delta_post, + &factor_phi_ai_ante, + &factor_phi_ai_crnt, + &factor_phi_ai_post, + &factor_phi_aj_ante, + &factor_phi_aj_crnt, + &factor_phi_aj_post, + &factor_phi_ak_ante, + &factor_phi_ak_crnt, + &factor_phi_ak_post, + &factor_phi_al_ante, + &factor_phi_al_crnt, + &factor_phi_al_post, + &prefactor_phi, + &v); /* Computation of forces per component */ @@ -2773,9 +2813,22 @@ real cbtdihs(int nbonds, * --- the adjacent bending angles. * For more explanations see comments file "restcbt.h". */ - compute_factors_cbtdihs(type, forceparams, delta_ante, delta_crnt, delta_post, f_phi_ai, - f_phi_aj, f_phi_ak, f_phi_al, f_theta_ante_ai, f_theta_ante_aj, - f_theta_ante_ak, f_theta_post_aj, f_theta_post_ak, f_theta_post_al, &v); + compute_factors_cbtdihs(type, + forceparams, + delta_ante, + delta_crnt, + delta_post, + f_phi_ai, + f_phi_aj, + f_phi_ak, + f_phi_al, + f_theta_ante_ai, + f_theta_ante_aj, + f_theta_ante_ak, + f_theta_post_aj, + f_theta_post_ak, + f_theta_post_al, + &v); /* Acumulate the resuts per beads */ @@ -2920,8 +2973,7 @@ rbdihs(int nbonds, ddphi = -ddphi * sin_phi; /* 11 */ - do_dih_fup(ai, aj, ak, al, ddphi, r_ij, r_kj, r_kl, m, n, f, fshift, pbc, x, t1, t2, - t3); /* 112 */ + do_dih_fup(ai, aj, ak, al, ddphi, r_ij, r_kj, r_kl, m, n, f, fshift, pbc, x, t1, t2, t3); /* 112 */ vtot += v; } *dvdlambda += dvdl_term; @@ -3039,8 +3091,8 @@ real cmap_dihs(int nbonds, a1k = ak; a1l = al; - phi1 = dih_angle(x[a1i], x[a1j], x[a1k], x[a1l], pbc, r1_ij, r1_kj, r1_kl, m1, n1, &t11, - &t21, &t31); /* 84 */ + phi1 = dih_angle( + x[a1i], x[a1j], x[a1k], x[a1l], pbc, r1_ij, r1_kj, r1_kl, m1, n1, &t11, &t21, &t31); /* 84 */ cos_phi1 = std::cos(phi1); @@ -3100,8 +3152,8 @@ real cmap_dihs(int nbonds, a2k = al; a2l = am; - phi2 = dih_angle(x[a2i], x[a2j], x[a2k], x[a2l], pbc, r2_ij, r2_kj, r2_kl, m2, n2, &t12, - &t22, &t32); /* 84 */ + phi2 = dih_angle( + x[a2i], x[a2j], x[a2k], x[a2l], pbc, r2_ij, r2_kj, r2_kl, m2, n2, &t12, &t22, &t32); /* 84 */ cos_phi2 = std::cos(phi2); @@ -3404,9 +3456,14 @@ real g96bonds(int nbonds, ki = pbc_rvec_sub(pbc, x[ai], x[aj], dx); /* 3 */ dr2 = iprod(dx, dx); /* 5 */ - *dvdlambda += g96harmonic(forceparams[type].harmonic.krA, forceparams[type].harmonic.krB, - forceparams[type].harmonic.rA, forceparams[type].harmonic.rB, dr2, - lambda, &vbond, &fbond); + *dvdlambda += g96harmonic(forceparams[type].harmonic.krA, + forceparams[type].harmonic.krB, + forceparams[type].harmonic.rA, + forceparams[type].harmonic.rB, + dr2, + lambda, + &vbond, + &fbond); vtot += 0.5 * vbond; /* 1*/ @@ -3458,9 +3515,14 @@ real g96angles(int nbonds, cos_theta = g96bond_angle(x[ai], x[aj], x[ak], pbc, r_ij, r_kj, &t1, &t2); - *dvdlambda += g96harmonic(forceparams[type].harmonic.krA, forceparams[type].harmonic.krB, - forceparams[type].harmonic.rA, forceparams[type].harmonic.rB, - cos_theta, lambda, &va, &dVdt); + *dvdlambda += g96harmonic(forceparams[type].harmonic.krA, + forceparams[type].harmonic.krB, + forceparams[type].harmonic.rA, + forceparams[type].harmonic.rB, + cos_theta, + lambda, + &va, + &dVdt); vtot += va; rij_1 = gmx::invsqrt(iprod(r_ij, r_ij)); @@ -3671,7 +3733,12 @@ real bonded_tab(const char* type, gmx_fatal(FARGS, "A tabulated %s interaction table number %d is out of the table range: r %f, " "between table indices %d and %d, table length %d", - type, table_nr, r, n0, n0 + 1, table->n); + type, + table_nr, + r, + n0, + n0 + 1, + table->n); } eps = rt - n0; eps2 = eps * eps; @@ -3724,8 +3791,15 @@ real tab_bonds(int nbonds, table = forceparams[type].tab.table; - *dvdlambda += bonded_tab("bond", table, &fcd->bondtab[table], forceparams[type].tab.kA, - forceparams[type].tab.kB, dr, lambda, &vbond, &fbond); /* 22 */ + *dvdlambda += bonded_tab("bond", + table, + &fcd->bondtab[table], + forceparams[type].tab.kA, + forceparams[type].tab.kB, + dr, + lambda, + &vbond, + &fbond); /* 22 */ if (dr2 == 0.0) { @@ -3771,8 +3845,15 @@ real tab_angles(int nbonds, table = forceparams[type].tab.table; - *dvdlambda += bonded_tab("angle", table, &fcd->angletab[table], forceparams[type].tab.kA, - forceparams[type].tab.kB, theta, lambda, &va, &dVdt); /* 22 */ + *dvdlambda += bonded_tab("angle", + table, + &fcd->angletab[table], + forceparams[type].tab.kA, + forceparams[type].tab.kB, + theta, + lambda, + &va, + &dVdt); /* 22 */ vtot += va; cos_theta2 = gmx::square(cos_theta); /* 1 */ @@ -3847,12 +3928,18 @@ real tab_dihs(int nbonds, table = forceparams[type].tab.table; /* Hopefully phi+M_PI never results in values < 0 */ - *dvdlambda += bonded_tab("dihedral", table, &fcd->dihtab[table], forceparams[type].tab.kA, - forceparams[type].tab.kB, phi + M_PI, lambda, &vpd, &ddphi); + *dvdlambda += bonded_tab("dihedral", + table, + &fcd->dihtab[table], + forceparams[type].tab.kA, + forceparams[type].tab.kB, + phi + M_PI, + lambda, + &vpd, + &ddphi); vtot += vpd; - do_dih_fup(ai, aj, ak, al, -ddphi, r_ij, r_kj, r_kl, m, n, f, fshift, pbc, x, t1, - t2, t3); /* 112 */ + do_dih_fup(ai, aj, ak, al, -ddphi, r_ij, r_kj, r_kl, m, n, f, fshift, pbc, x, t1, t2, t3); /* 112 */ } /* 227 TOTAL */ @@ -4001,8 +4088,8 @@ real calculateSimpleBond(const int ftype, { const BondedInteractions& bonded = c_bondedInteractionFunctionsPerFlavor[bondedKernelFlavor][ftype]; - real v = bonded.function(numForceatoms, forceatoms, forceparams, x, f, fshift, pbc, lambda, - dvdlambda, md, fcd, global_atom_index); + real v = bonded.function( + numForceatoms, forceatoms, forceparams, x, f, fshift, pbc, lambda, dvdlambda, md, fcd, global_atom_index); return v; } diff --git a/src/gromacs/listed_forces/disre.cpp b/src/gromacs/listed_forces/disre.cpp index d95867cf7d..73d23f5f52 100644 --- a/src/gromacs/listed_forces/disre.cpp +++ b/src/gromacs/listed_forces/disre.cpp @@ -245,7 +245,8 @@ void init_disres(FILE* fplog, gmx_fatal(FARGS, "GMX_DISRE_ENSEMBLE_SIZE (%d) is not equal to 1 or the number of systems " "(option -multidir) %d", - dd->nsystems, ms->numSimulations_); + dd->nsystems, + ms->numSimulations_); } if (fplog) { @@ -278,8 +279,7 @@ void init_disres(FILE* fplog, { if (fplog) { - fprintf(fplog, "There are %d distance restraints involving %d atom pairs\n", dd->nres, - dd->npair); + fprintf(fplog, "There are %d distance restraints involving %d atom pairs\n", dd->nres, dd->npair); } /* Have to avoid g_disre de-referencing cr blindly, mdrun not * doing consistency checks for ensemble-averaged distance diff --git a/src/gromacs/listed_forces/gpubonded_impl.cu b/src/gromacs/listed_forces/gpubonded_impl.cu index 741244caaf..ff34ad967c 100644 --- a/src/gromacs/listed_forces/gpubonded_impl.cu +++ b/src/gromacs/listed_forces/gpubonded_impl.cu @@ -88,8 +88,13 @@ GpuBonded::Impl::Impl(const gmx_ffparams_t& ffparams, // This could be an async transfer (if the source is pinned), so // long as it uses the same stream as the kernels and we are happy // to consume additional pinned pages. - copyToDeviceBuffer(&d_forceParams_, ffparams.iparams.data(), 0, ffparams.numTypes(), - deviceStream_, GpuApiCallBehavior::Sync, nullptr); + copyToDeviceBuffer(&d_forceParams_, + ffparams.iparams.data(), + 0, + ffparams.numTypes(), + deviceStream_, + GpuApiCallBehavior::Sync, + nullptr); vTot_.resize(F_NRE); allocateDeviceBuffer(&d_vTot_, F_NRE, deviceContext_); clearDeviceBufferAsync(&d_vTot_, 0, F_NRE, deviceStream_); @@ -230,11 +235,16 @@ void GpuBonded::Impl::updateInteractionListsAndDeviceBuffers(ArrayRef { t_ilist& d_iList = d_iLists_[fType]; - reallocateDeviceBuffer(&d_iList.iatoms, iList.size(), &d_iList.nr, &d_iList.nalloc, - deviceContext_); + reallocateDeviceBuffer( + &d_iList.iatoms, iList.size(), &d_iList.nr, &d_iList.nalloc, deviceContext_); - copyToDeviceBuffer(&d_iList.iatoms, iList.iatoms.data(), 0, iList.size(), deviceStream_, - GpuApiCallBehavior::Async, nullptr); + copyToDeviceBuffer(&d_iList.iatoms, + iList.iatoms.data(), + 0, + iList.size(), + deviceStream_, + GpuApiCallBehavior::Async, + nullptr); } kernelParams_.fTypesOnGpu[fTypesCounter] = fType; kernelParams_.numFTypeIAtoms[fTypesCounter] = iList.size(); diff --git a/src/gromacs/listed_forces/gpubondedkernels.cu b/src/gromacs/listed_forces/gpubondedkernels.cu index d8ad851446..d3f9d4f3ac 100644 --- a/src/gromacs/listed_forces/gpubondedkernels.cu +++ b/src/gromacs/listed_forces/gpubondedkernels.cu @@ -186,13 +186,16 @@ __device__ void angles_gpu(const int i, float cos_theta; int t1; int t2; - float theta = bond_angle_gpu(gm_xq[ai], gm_xq[aj], gm_xq[ak], pbcAiuc, &r_ij, - &r_kj, &cos_theta, &t1, &t2); + float theta = bond_angle_gpu( + gm_xq[ai], gm_xq[aj], gm_xq[ak], pbcAiuc, &r_ij, &r_kj, &cos_theta, &t1, &t2); float va; float dVdt; harmonic_gpu(d_forceparams[type].harmonic.krA, - d_forceparams[type].harmonic.rA * CUDA_DEG2RAD_F, theta, &va, &dVdt); + d_forceparams[type].harmonic.rA * CUDA_DEG2RAD_F, + theta, + &va, + &dVdt); if (calcEner) { @@ -261,8 +264,8 @@ __device__ void urey_bradley_gpu(const int i, float cos_theta; int t1; int t2; - float theta = bond_angle_gpu(gm_xq[ai], gm_xq[aj], gm_xq[ak], pbcAiuc, &r_ij, - &r_kj, &cos_theta, &t1, &t2); + float theta = bond_angle_gpu( + gm_xq[ai], gm_xq[aj], gm_xq[ak], pbcAiuc, &r_ij, &r_kj, &cos_theta, &t1, &t2); float va; float dVdt; @@ -463,21 +466,25 @@ __device__ void pdihs_gpu(const int i, int t1; int t2; int t3; - float phi = dih_angle_gpu(gm_xq[ai], gm_xq[aj], gm_xq[ak], gm_xq[al], pbcAiuc, - &r_ij, &r_kj, &r_kl, &m, &n, &t1, &t2, &t3); + float phi = dih_angle_gpu( + gm_xq[ai], gm_xq[aj], gm_xq[ak], gm_xq[al], pbcAiuc, &r_ij, &r_kj, &r_kl, &m, &n, &t1, &t2, &t3); float vpd; float ddphi; - dopdihs_gpu(d_forceparams[type].pdihs.cpA, d_forceparams[type].pdihs.phiA, - d_forceparams[type].pdihs.mult, phi, &vpd, &ddphi); + dopdihs_gpu(d_forceparams[type].pdihs.cpA, + d_forceparams[type].pdihs.phiA, + d_forceparams[type].pdihs.mult, + phi, + &vpd, + &ddphi); if (calcEner) { *vtot_loc += vpd; } - do_dih_fup_gpu(ai, aj, ak, al, ddphi, r_ij, r_kj, r_kl, m, n, gm_f, sm_fShiftLoc, - pbcAiuc, gm_xq, t1, t2, t3); + do_dih_fup_gpu( + ai, aj, ak, al, ddphi, r_ij, r_kj, r_kl, m, n, gm_f, sm_fShiftLoc, pbcAiuc, gm_xq, t1, t2, t3); } } @@ -510,8 +517,8 @@ __device__ void rbdihs_gpu(const int i, int t1; int t2; int t3; - float phi = dih_angle_gpu(gm_xq[ai], gm_xq[aj], gm_xq[ak], gm_xq[al], pbcAiuc, - &r_ij, &r_kj, &r_kl, &m, &n, &t1, &t2, &t3); + float phi = dih_angle_gpu( + gm_xq[ai], gm_xq[aj], gm_xq[ak], gm_xq[al], pbcAiuc, &r_ij, &r_kj, &r_kl, &m, &n, &t1, &t2, &t3); /* Change to polymer convention */ if (phi < c0) @@ -576,8 +583,8 @@ __device__ void rbdihs_gpu(const int i, ddphi = -ddphi * sin_phi; - do_dih_fup_gpu(ai, aj, ak, al, ddphi, r_ij, r_kj, r_kl, m, n, gm_f, sm_fShiftLoc, - pbcAiuc, gm_xq, t1, t2, t3); + do_dih_fup_gpu( + ai, aj, ak, al, ddphi, r_ij, r_kj, r_kl, m, n, gm_f, sm_fShiftLoc, pbcAiuc, gm_xq, t1, t2, t3); if (calcEner) { *vtot_loc += v; @@ -625,8 +632,8 @@ __device__ void idihs_gpu(const int i, int t1; int t2; int t3; - float phi = dih_angle_gpu(gm_xq[ai], gm_xq[aj], gm_xq[ak], gm_xq[al], pbcAiuc, - &r_ij, &r_kj, &r_kl, &m, &n, &t1, &t2, &t3); + float phi = dih_angle_gpu( + gm_xq[ai], gm_xq[aj], gm_xq[ak], gm_xq[al], pbcAiuc, &r_ij, &r_kj, &r_kl, &m, &n, &t1, &t2, &t3); /* phi can jump if phi0 is close to Pi/-Pi, which will cause huge * force changes if we just apply a normal harmonic. @@ -646,8 +653,8 @@ __device__ void idihs_gpu(const int i, float ddphi = -kA * dp; - do_dih_fup_gpu(ai, aj, ak, al, -ddphi, r_ij, r_kj, r_kl, m, n, gm_f, sm_fShiftLoc, - pbcAiuc, gm_xq, t1, t2, t3); + do_dih_fup_gpu( + ai, aj, ak, al, -ddphi, r_ij, r_kj, r_kl, m, n, gm_f, sm_fShiftLoc, pbcAiuc, gm_xq, t1, t2, t3); if (calcEner) { @@ -757,41 +764,84 @@ __global__ void exec_kernel_gpu(BondedCudaKernelParameters kernelParams) switch (fType) { case F_BONDS: - bonds_gpu(fTypeTid, &vtot_loc, numBonds, iatoms, - kernelParams.d_forceParams, kernelParams.d_xq, - kernelParams.d_f, sm_fShiftLoc, kernelParams.pbcAiuc); + bonds_gpu(fTypeTid, + &vtot_loc, + numBonds, + iatoms, + kernelParams.d_forceParams, + kernelParams.d_xq, + kernelParams.d_f, + sm_fShiftLoc, + kernelParams.pbcAiuc); break; case F_ANGLES: - angles_gpu( - fTypeTid, &vtot_loc, numBonds, iatoms, kernelParams.d_forceParams, - kernelParams.d_xq, kernelParams.d_f, sm_fShiftLoc, kernelParams.pbcAiuc); + angles_gpu(fTypeTid, + &vtot_loc, + numBonds, + iatoms, + kernelParams.d_forceParams, + kernelParams.d_xq, + kernelParams.d_f, + sm_fShiftLoc, + kernelParams.pbcAiuc); break; case F_UREY_BRADLEY: - urey_bradley_gpu( - fTypeTid, &vtot_loc, numBonds, iatoms, kernelParams.d_forceParams, - kernelParams.d_xq, kernelParams.d_f, sm_fShiftLoc, kernelParams.pbcAiuc); + urey_bradley_gpu(fTypeTid, + &vtot_loc, + numBonds, + iatoms, + kernelParams.d_forceParams, + kernelParams.d_xq, + kernelParams.d_f, + sm_fShiftLoc, + kernelParams.pbcAiuc); break; case F_PDIHS: case F_PIDIHS: - pdihs_gpu(fTypeTid, &vtot_loc, numBonds, iatoms, - kernelParams.d_forceParams, kernelParams.d_xq, - kernelParams.d_f, sm_fShiftLoc, kernelParams.pbcAiuc); + pdihs_gpu(fTypeTid, + &vtot_loc, + numBonds, + iatoms, + kernelParams.d_forceParams, + kernelParams.d_xq, + kernelParams.d_f, + sm_fShiftLoc, + kernelParams.pbcAiuc); break; case F_RBDIHS: - rbdihs_gpu( - fTypeTid, &vtot_loc, numBonds, iatoms, kernelParams.d_forceParams, - kernelParams.d_xq, kernelParams.d_f, sm_fShiftLoc, kernelParams.pbcAiuc); + rbdihs_gpu(fTypeTid, + &vtot_loc, + numBonds, + iatoms, + kernelParams.d_forceParams, + kernelParams.d_xq, + kernelParams.d_f, + sm_fShiftLoc, + kernelParams.pbcAiuc); break; case F_IDIHS: - idihs_gpu(fTypeTid, &vtot_loc, numBonds, iatoms, - kernelParams.d_forceParams, kernelParams.d_xq, - kernelParams.d_f, sm_fShiftLoc, kernelParams.pbcAiuc); + idihs_gpu(fTypeTid, + &vtot_loc, + numBonds, + iatoms, + kernelParams.d_forceParams, + kernelParams.d_xq, + kernelParams.d_f, + sm_fShiftLoc, + kernelParams.pbcAiuc); break; case F_LJ14: - pairs_gpu( - fTypeTid, numBonds, iatoms, kernelParams.d_forceParams, - kernelParams.d_xq, kernelParams.d_f, sm_fShiftLoc, kernelParams.pbcAiuc, - kernelParams.electrostaticsScaleFactor, &vtotVdw_loc, &vtotElec_loc); + pairs_gpu(fTypeTid, + numBonds, + iatoms, + kernelParams.d_forceParams, + kernelParams.d_xq, + kernelParams.d_f, + sm_fShiftLoc, + kernelParams.pbcAiuc, + kernelParams.electrostaticsScaleFactor, + &vtotVdw_loc, + &vtotElec_loc); break; } break; @@ -841,8 +891,12 @@ void GpuBonded::Impl::launchKernel() const auto kernelArgs = prepareGpuKernelArguments(kernelPtr, kernelLaunchConfig_, &kernelParams_); - launchGpuKernel(kernelPtr, kernelLaunchConfig_, deviceStream_, nullptr, - "exec_kernel_gpu", kernelArgs); + launchGpuKernel(kernelPtr, + kernelLaunchConfig_, + deviceStream_, + nullptr, + "exec_kernel_gpu", + kernelArgs); wallcycle_sub_stop(wcycle_, ewcsLAUNCH_GPU_BONDED); wallcycle_stop(wcycle_, ewcLAUNCH_GPU); diff --git a/src/gromacs/listed_forces/listed_forces.cpp b/src/gromacs/listed_forces/listed_forces.cpp index e64de500d0..5c27087d4c 100644 --- a/src/gromacs/listed_forces/listed_forces.cpp +++ b/src/gromacs/listed_forces/listed_forces.cpp @@ -458,14 +458,36 @@ real calc_one_bond(int thread, nice to account to its own subtimer, but first wallcycle needs to be extended to support calling from multiple threads. */ - v = cmap_dihs(nbn, iatoms.data() + nb0, iparams.data(), &idef.cmap_grid, x, f, fshift, - pbc, lambda[efptFTYPE], &(dvdl[efptFTYPE]), md, fcd, global_atom_index); + v = cmap_dihs(nbn, + iatoms.data() + nb0, + iparams.data(), + &idef.cmap_grid, + x, + f, + fshift, + pbc, + lambda[efptFTYPE], + &(dvdl[efptFTYPE]), + md, + fcd, + global_atom_index); } else { - v = calculateSimpleBond(ftype, nbn, iatoms.data() + nb0, iparams.data(), x, f, fshift, - pbc, lambda[efptFTYPE], &(dvdl[efptFTYPE]), md, fcd, - global_atom_index, flavor); + v = calculateSimpleBond(ftype, + nbn, + iatoms.data() + nb0, + iparams.data(), + x, + f, + fshift, + pbc, + lambda[efptFTYPE], + &(dvdl[efptFTYPE]), + md, + fcd, + global_atom_index, + flavor); } } else @@ -473,8 +495,22 @@ real calc_one_bond(int thread, /* TODO The execution time for pairs might be nice to account to its own subtimer, but first wallcycle needs to be extended to support calling from multiple threads. */ - do_pairs(ftype, nbn, iatoms.data() + nb0, iparams.data(), x, f, fshift, pbc, lambda, dvdl, - md, fr, havePerturbedInteractions, stepWork, grpp, global_atom_index); + do_pairs(ftype, + nbn, + iatoms.data() + nb0, + iparams.data(), + x, + f, + fshift, + pbc, + lambda, + dvdl, + md, + fr, + havePerturbedInteractions, + stepWork, + grpp, + global_atom_index); } if (thread == 0) @@ -545,9 +581,25 @@ static void calcBondedForces(const InteractionDefinitions& idef, if (!ilist.empty() && ftype_is_bonded_potential(ftype)) { ArrayRef iatoms = gmx::makeConstArrayRef(ilist.iatoms); - v = calc_one_bond(thread, ftype, idef, iatoms, idef.numNonperturbedInteractions[ftype], - bt->workDivision, x, ft, fshift, fr, pbc_null, grpp, nrnb, - lambda, dvdlt, md, fcd, stepWork, global_atom_index); + v = calc_one_bond(thread, + ftype, + idef, + iatoms, + idef.numNonperturbedInteractions[ftype], + bt->workDivision, + x, + ft, + fshift, + fr, + pbc_null, + grpp, + nrnb, + lambda, + dvdlt, + md, + fcd, + stepWork, + global_atom_index); epot[ftype] += v; } } @@ -601,9 +653,20 @@ void calc_listed(struct gmx_wallcycle* wcycle, /* The dummy array is to have a place to store the dhdl at other values of lambda, which will be thrown away in the end */ real dvdl[efptNR] = { 0 }; - calcBondedForces(idef, bt, x, fr, fr->bMolPBC ? pbc : nullptr, - as_rvec_array(forceWithShiftForces.shiftForces().data()), enerd, nrnb, - lambda, dvdl, md, fcd, stepWork, global_atom_index); + calcBondedForces(idef, + bt, + x, + fr, + fr->bMolPBC ? pbc : nullptr, + as_rvec_array(forceWithShiftForces.shiftForces().data()), + enerd, + nrnb, + lambda, + dvdl, + md, + fcd, + stepWork, + global_atom_index); wallcycle_sub_stop(wcycle, ewcsLISTED); wallcycle_sub_start(wcycle, ewcsLISTED_BUF_OPS); @@ -661,7 +724,8 @@ void calc_listed_lambda(const InteractionDefinitions& idef, /* We already have the forces, so we use temp buffers here */ std::fill(forceBufferLambda.begin(), forceBufferLambda.end(), 0.0_real); - std::fill(shiftForceBufferLambda.begin(), shiftForceBufferLambda.end(), + std::fill(shiftForceBufferLambda.begin(), + shiftForceBufferLambda.end(), gmx::RVec{ 0.0_real, 0.0_real, 0.0_real }); rvec4* f = reinterpret_cast(forceBufferLambda.data()); rvec* fshift = as_rvec_array(shiftForceBufferLambda.data()); @@ -684,9 +748,25 @@ void calc_listed_lambda(const InteractionDefinitions& idef, gmx::StepWorkload tempFlags; tempFlags.computeEnergy = true; - real v = calc_one_bond(0, ftype, idef, iatomsPerturbed, iatomsPerturbed.ssize(), - workDivision, x, f, fshift, fr, pbc_null, grpp, nrnb, lambda, - dvdl.data(), md, fcd, tempFlags, global_atom_index); + real v = calc_one_bond(0, + ftype, + idef, + iatomsPerturbed, + iatomsPerturbed.ssize(), + workDivision, + x, + f, + fshift, + fr, + pbc_null, + grpp, + nrnb, + lambda, + dvdl.data(), + md, + fcd, + tempFlags, + global_atom_index); epot[ftype] += v; } } @@ -754,21 +834,33 @@ void ListedForces::calculate(struct gmx_wallcycle* wcycle, if (fcdata->orires->nr > 0) { GMX_ASSERT(!xWholeMolecules.empty(), "Need whole molecules for orienation restraints"); - enerd->term[F_ORIRESDEV] = calc_orires_dev( - ms, idef.il[F_ORIRES].size(), idef.il[F_ORIRES].iatoms.data(), idef.iparams.data(), - md, xWholeMolecules, x, fr->bMolPBC ? pbc : nullptr, fcdata->orires, hist); + enerd->term[F_ORIRESDEV] = calc_orires_dev(ms, + idef.il[F_ORIRES].size(), + idef.il[F_ORIRES].iatoms.data(), + idef.iparams.data(), + md, + xWholeMolecules, + x, + fr->bMolPBC ? pbc : nullptr, + fcdata->orires, + hist); } if (fcdata->disres->nres > 0) { - calc_disres_R_6(cr, ms, idef.il[F_DISRES].size(), idef.il[F_DISRES].iatoms.data(), x, - fr->bMolPBC ? pbc : nullptr, fcdata->disres, hist); + calc_disres_R_6(cr, + ms, + idef.il[F_DISRES].size(), + idef.il[F_DISRES].iatoms.data(), + x, + fr->bMolPBC ? pbc : nullptr, + fcdata->disres, + hist); } wallcycle_sub_stop(wcycle, ewcsRESTRAINTS); } - calc_listed(wcycle, idef, threading_.get(), x, forceOutputs, fr, pbc, enerd, nrnb, lambda, md, - fcdata, global_atom_index, stepWork); + calc_listed(wcycle, idef, threading_.get(), x, forceOutputs, fr, pbc, enerd, nrnb, lambda, md, fcdata, global_atom_index, stepWork); /* Check if we have to determine energy differences * at foreign lambda's. @@ -796,9 +888,21 @@ void ListedForces::calculate(struct gmx_wallcycle* wcycle, { lam_i[j] = (i == 0 ? lambda[j] : fepvals->all_lambda[j][i - 1]); } - calc_listed_lambda(idef, threading_.get(), x, fr, pbc, forceBufferLambda_, - shiftForceBufferLambda_, &(enerd->foreign_grpp), enerd->foreign_term, - dvdl, nrnb, lam_i, md, fcdata, global_atom_index); + calc_listed_lambda(idef, + threading_.get(), + x, + fr, + pbc, + forceBufferLambda_, + shiftForceBufferLambda_, + &(enerd->foreign_grpp), + enerd->foreign_term, + dvdl, + nrnb, + lam_i, + md, + fcdata, + global_atom_index); sum_epot(enerd->foreign_grpp, enerd->foreign_term); const double dvdlSum = std::accumulate(std::begin(dvdl), std::end(dvdl), 0.); std::fill(std::begin(dvdl), std::end(dvdl), 0.0); diff --git a/src/gromacs/listed_forces/manage_threading.cpp b/src/gromacs/listed_forces/manage_threading.cpp index f666b5a012..db95e75c03 100644 --- a/src/gromacs/listed_forces/manage_threading.cpp +++ b/src/gromacs/listed_forces/manage_threading.cpp @@ -316,7 +316,8 @@ static void divide_bondeds_over_threads(bonded_threading_t* bt, fprintf(debug, "%16s", interaction_function[f].name); for (t = 0; t < numThreads; t++) { - fprintf(debug, " %4d", + fprintf(debug, + " %4d", (bt->workDivision.bound(f, t + 1) - bt->workDivision.bound(f, t)) / (1 + NRAL(f))); } @@ -342,7 +343,8 @@ static void calc_bonded_reduction_mask(int natoms, "You are using %d OpenMP threads, which is larger than GMX_OPENMP_MAX_THREADS " "(%d). Decrease the number of OpenMP threads or rebuild GROMACS with a larger " "value for GMX_OPENMP_MAX_THREADS passed to CMake.", - bondedThreading.nthreads, GMX_OPENMP_MAX_THREADS); + bondedThreading.nthreads, + GMX_OPENMP_MAX_THREADS); } GMX_ASSERT(bondedThreading.nthreads <= BITMASK_SIZE, "We need at least nthreads bits in the mask"); @@ -481,7 +483,8 @@ void setup_bonded_threading(bonded_threading_t* bt, if (debug) { fprintf(debug, "Number of %d atom blocks to reduce: %d\n", reduction_block_size, bt->nblock_used); - fprintf(debug, "Reduction density %.2f for touched blocks only %.2f\n", + fprintf(debug, + "Reduction density %.2f for touched blocks only %.2f\n", ctot * reduction_block_size / static_cast(numAtomsForce), ctot / static_cast(bt->nblock_used)); } @@ -531,7 +534,8 @@ bonded_threading_t::bonded_threading_t(const int numThreads, const int numEnergy sscanf(ptr, "%d", &max_nthread_uniform); if (fplog != nullptr) { - fprintf(fplog, "\nMax threads for uniform bonded distribution set to %d by env.var.\n", + fprintf(fplog, + "\nMax threads for uniform bonded distribution set to %d by env.var.\n", max_nthread_uniform); } } diff --git a/src/gromacs/listed_forces/orires.cpp b/src/gromacs/listed_forces/orires.cpp index aab79ed972..70e5af4275 100644 --- a/src/gromacs/listed_forces/orires.cpp +++ b/src/gromacs/listed_forces/orires.cpp @@ -90,7 +90,9 @@ void init_orires(FILE* fplog, gmx_fatal(FARGS, "The system has %d orientation restraints, but at least %d are required, since " "there are %d fitting parameters.", - od->nr, numFitParams + 1, numFitParams); + od->nr, + numFitParams + 1, + numFitParams); } if (ir->bPeriodicMols) @@ -282,8 +284,7 @@ void init_orires(FILE* fplog, if (ms) { - fprintf(fplog, " the orientation restraints are ensemble averaged over %d systems\n", - ms->numSimulations_); + fprintf(fplog, " the orientation restraints are ensemble averaged over %d systems\n", ms->numSimulations_); check_multi_int(fplog, ms, od->nr, "the number of orientation restraints", FALSE); check_multi_int(fplog, ms, od->nref, "the number of fit atoms for orientation restraining", FALSE); @@ -374,8 +375,12 @@ void print_orires_log(FILE* log, t_oriresdata* od) fprintf(log, " order parameter: %g\n", eig[0]); for (int i = 0; i < DIM; i++) { - fprintf(log, " eig: %6.3f %6.3f %6.3f %6.3f\n", (eig[0] != 0) ? eig[i] / eig[0] : eig[i], - eig[DIM + i * DIM + XX], eig[DIM + i * DIM + YY], eig[DIM + i * DIM + ZZ]); + fprintf(log, + " eig: %6.3f %6.3f %6.3f %6.3f\n", + (eig[0] != 0) ? eig[i] / eig[0] : eig[i], + eig[DIM + i * DIM + XX], + eig[DIM + i * DIM + YY], + eig[DIM + i * DIM + ZZ]); } fprintf(log, "\n"); } diff --git a/src/gromacs/listed_forces/pairs.cpp b/src/gromacs/listed_forces/pairs.cpp index 1d0393fb71..b742311a43 100644 --- a/src/gromacs/listed_forces/pairs.cpp +++ b/src/gromacs/listed_forces/pairs.cpp @@ -87,15 +87,25 @@ static void warning_rlimit(const rvec* x, int ai, int aj, int* global_atom_index "IMPORTANT: This should not happen in a stable simulation, so there is\n" "probably something wrong with your system. Only change the table-extension\n" "distance in the mdp file if you are really sure that is the reason.\n", - glatnr(global_atom_index, ai), glatnr(global_atom_index, aj), r, rlimit); + glatnr(global_atom_index, ai), + glatnr(global_atom_index, aj), + r, + rlimit); if (debug) { fprintf(debug, "%8f %8f %8f\n%8f %8f %8f\n1-4 (%d,%d) interaction not within cut-off! r=%g. " "Ignored\n", - x[ai][XX], x[ai][YY], x[ai][ZZ], x[aj][XX], x[aj][YY], x[aj][ZZ], - glatnr(global_atom_index, ai), glatnr(global_atom_index, aj), r); + x[ai][XX], + x[ai][YY], + x[ai][ZZ], + x[aj][XX], + x[aj][YY], + x[aj][ZZ], + glatnr(global_atom_index, ai), + glatnr(global_atom_index, aj), + r); } } @@ -493,16 +503,40 @@ static real do_pairs_general(int ftype, c6B = iparams[itype].lj14.c6B * 6.0; c12B = iparams[itype].lj14.c12B * 12.0; - fscal = free_energy_evaluate_single( - r2, *fr->ic->softCoreParameters, fr->pairsTable->scale, - fr->pairsTable->data.data(), fr->pairsTable->stride, qq, c6, c12, qqB, c6B, c12B, - LFC, LFV, DLF, lfac_coul, lfac_vdw, dlfac_coul, dlfac_vdw, &velec, &vvdw, dvdl); + fscal = free_energy_evaluate_single(r2, + *fr->ic->softCoreParameters, + fr->pairsTable->scale, + fr->pairsTable->data.data(), + fr->pairsTable->stride, + qq, + c6, + c12, + qqB, + c6B, + c12B, + LFC, + LFV, + DLF, + lfac_coul, + lfac_vdw, + dlfac_coul, + dlfac_vdw, + &velec, + &vvdw, + dvdl); } else { /* Evaluate tabulated interaction without free energy */ - fscal = evaluate_single(r2, fr->pairsTable->scale, fr->pairsTable->data.data(), - fr->pairsTable->stride, qq, c6, c12, &velec, &vvdw); + fscal = evaluate_single(r2, + fr->pairsTable->scale, + fr->pairsTable->data.data(), + fr->pairsTable->stride, + qq, + c6, + c12, + &velec, + &vvdw); } energygrp_elec[gid] += velec; @@ -687,20 +721,18 @@ void do_pairs(int ftype, pbc_nonnull = &pbc_no; } - do_pairs_simple(nbonds, iatoms, iparams, x, f, pbc_nonnull, md, - fr->ic->epsfac * fr->fudgeQQ); + do_pairs_simple( + nbonds, iatoms, iparams, x, f, pbc_nonnull, md, fr->ic->epsfac * fr->fudgeQQ); } } else if (stepWork.computeVirial) { do_pairs_general( - ftype, nbonds, iatoms, iparams, x, f, fshift, pbc, lambda, dvdl, md, fr, grppener, - global_atom_index); + ftype, nbonds, iatoms, iparams, x, f, fshift, pbc, lambda, dvdl, md, fr, grppener, global_atom_index); } else { - do_pairs_general(ftype, nbonds, iatoms, iparams, x, f, - fshift, pbc, lambda, dvdl, md, fr, - grppener, global_atom_index); + do_pairs_general( + ftype, nbonds, iatoms, iparams, x, f, fshift, pbc, lambda, dvdl, md, fr, grppener, global_atom_index); } } diff --git a/src/gromacs/listed_forces/position_restraints.cpp b/src/gromacs/listed_forces/position_restraints.cpp index 5b12681b79..ebd3d99ccc 100644 --- a/src/gromacs/listed_forces/position_restraints.cpp +++ b/src/gromacs/listed_forces/position_restraints.cpp @@ -231,8 +231,18 @@ real fbposres(int nbonds, pr = &forceparams[type]; /* same calculation as for normal posres, but with identical A and B states, and lambda==0 */ - posres_dx(x[ai], forceparams[type].fbposres.pos0, forceparams[type].fbposres.pos0, com_sc, - com_sc, 0.0, pbc, refcoord_scaling, npbcdim, dx, rdist, dpdl); + posres_dx(x[ai], + forceparams[type].fbposres.pos0, + forceparams[type].fbposres.pos0, + com_sc, + com_sc, + 0.0, + pbc, + refcoord_scaling, + npbcdim, + dx, + rdist, + dpdl); clear_rvec(fm); v = 0.0; @@ -372,8 +382,18 @@ real posres(int nbonds, pr = &forceparams[type]; /* return dx, rdist, and dpdl */ - posres_dx(x[ai], forceparams[type].posres.pos0A, forceparams[type].posres.pos0B, comA_sc, - comB_sc, lambda, pbc, refcoord_scaling, npbcdim, dx, rdist, dpdl); + posres_dx(x[ai], + forceparams[type].posres.pos0A, + forceparams[type].posres.pos0B, + comA_sc, + comB_sc, + lambda, + pbc, + refcoord_scaling, + npbcdim, + dx, + rdist, + dpdl); for (m = 0; (m < DIM); m++) { @@ -413,10 +433,18 @@ void posres_wrapper(t_nrnb* nrnb, real v, dvdl; dvdl = 0; - v = posres(idef.il[F_POSRES].size(), idef.il[F_POSRES].iatoms.data(), - idef.iparams_posres.data(), x, forceWithVirial, - fr->pbcType == PbcType::No ? nullptr : pbc, lambda[efptRESTRAINT], &dvdl, - fr->rc_scaling, fr->pbcType, fr->posres_com, fr->posres_comB); + v = posres(idef.il[F_POSRES].size(), + idef.il[F_POSRES].iatoms.data(), + idef.iparams_posres.data(), + x, + forceWithVirial, + fr->pbcType == PbcType::No ? nullptr : pbc, + lambda[efptRESTRAINT], + &dvdl, + fr->rc_scaling, + fr->pbcType, + fr->posres_com, + fr->posres_comB); enerd->term[F_POSRES] += v; /* If just the force constant changes, the FEP term is linear, * but if k changes, it is not. @@ -443,10 +471,18 @@ void posres_wrapper_lambda(struct gmx_wallcycle* wcycle, const real lambda_dum = (i == 0 ? lambda[efptRESTRAINT] : fepvals->all_lambda[efptRESTRAINT][i - 1]); - const real v = posres(idef.il[F_POSRES].size(), idef.il[F_POSRES].iatoms.data(), - idef.iparams_posres.data(), x, nullptr, - fr->pbcType == PbcType::No ? nullptr : pbc, lambda_dum, &dvdl, - fr->rc_scaling, fr->pbcType, fr->posres_com, fr->posres_comB); + const real v = posres(idef.il[F_POSRES].size(), + idef.il[F_POSRES].iatoms.data(), + idef.iparams_posres.data(), + x, + nullptr, + fr->pbcType == PbcType::No ? nullptr : pbc, + lambda_dum, + &dvdl, + fr->rc_scaling, + fr->pbcType, + fr->posres_com, + fr->posres_comB); foreignTerms.accumulate(i, v, dvdl); } wallcycle_sub_stop(wcycle, ewcsRESTRAINTS); @@ -464,9 +500,15 @@ void fbposres_wrapper(t_nrnb* nrnb, { real v; - v = fbposres(idef.il[F_FBPOSRES].size(), idef.il[F_FBPOSRES].iatoms.data(), - idef.iparams_fbposres.data(), x, forceWithVirial, - fr->pbcType == PbcType::No ? nullptr : pbc, fr->rc_scaling, fr->pbcType, fr->posres_com); + v = fbposres(idef.il[F_FBPOSRES].size(), + idef.il[F_FBPOSRES].iatoms.data(), + idef.iparams_fbposres.data(), + x, + forceWithVirial, + fr->pbcType == PbcType::No ? nullptr : pbc, + fr->rc_scaling, + fr->pbcType, + fr->posres_com); enerd->term[F_FBPOSRES] += v; inc_nrnb(nrnb, eNR_FBPOSRES, gmx::exactDiv(idef.il[F_FBPOSRES].size(), 2)); } diff --git a/src/gromacs/listed_forces/tests/bonded.cpp b/src/gromacs/listed_forces/tests/bonded.cpp index 9cd1273cb9..d358542f90 100644 --- a/src/gromacs/listed_forces/tests/bonded.cpp +++ b/src/gromacs/listed_forces/tests/bonded.cpp @@ -565,9 +565,13 @@ protected: // have an implementation for uint64_t(!) but this is likely to // work because that type is likely to be a typedef for one of // the other numerical types that happens to be 64-bits wide. - shiftForcesTolerance_ = FloatingPointTolerance(singleShiftForcesAbsoluteTolerance, 1e-8, 1e-6, - 1e-12, std::numeric_limits::max(), - std::numeric_limits::max(), false); + shiftForcesTolerance_ = FloatingPointTolerance(singleShiftForcesAbsoluteTolerance, + 1e-8, + 1e-6, + 1e-12, + std::numeric_limits::max(), + std::numeric_limits::max(), + false); } void testOneIfunc(TestReferenceChecker* checker, const std::vector& iatoms, const real lambda) { @@ -590,11 +594,20 @@ protected: { SCOPED_TRACE("Testing bonded kernel flavor: " + c_bondedKernelFlavorStrings[flavor]); OutputQuantities output; - output.energy = - calculateSimpleBond(input_.ftype, iatoms.size(), iatoms.data(), &input_.iparams, - as_rvec_array(x_.data()), output.f, output.fshift, &pbc_, - lambda, &output.dvdlambda, &mdatoms, - /* struct t_fcdata * */ nullptr, ddgatindex.data(), flavor); + output.energy = calculateSimpleBond(input_.ftype, + iatoms.size(), + iatoms.data(), + &input_.iparams, + as_rvec_array(x_.data()), + output.f, + output.fshift, + &pbc_, + lambda, + &output.dvdlambda, + &mdatoms, + /* struct t_fcdata * */ nullptr, + ddgatindex.data(), + flavor); // Internal consistency test of both test input // and bonded functions. EXPECT_TRUE((input_.fep || (output.dvdlambda == 0.0))) << "dvdlambda was " << output.dvdlambda; diff --git a/src/gromacs/math/densityfit.cpp b/src/gromacs/math/densityfit.cpp index 3301fc73df..5304ac5fe2 100644 --- a/src/gromacs/math/densityfit.cpp +++ b/src/gromacs/math/densityfit.cpp @@ -104,8 +104,9 @@ DensitySimilarityInnerProduct::DensitySimilarityInnerProduct(density referenceDe const auto numVoxels = gradient_.asConstView().mapping().required_span_size(); /* the gradient for the inner product measure of fit is constant and does not * depend on the compared density, so it is pre-computed here */ - std::transform(begin(referenceDensity_), end(referenceDensity), begin(gradient_), - [numVoxels](float x) { return x / numVoxels; }); + std::transform(begin(referenceDensity_), end(referenceDensity), begin(gradient_), [numVoxels](float x) { + return x / numVoxels; + }); } real DensitySimilarityInnerProduct::similarity(density comparedDensity) @@ -194,8 +195,12 @@ real DensitySimilarityRelativeEntropy::similarity(density comparedDensity) { GMX_THROW(RangeError("Reference density and compared density need to have same extents.")); } - return std::inner_product(begin(referenceDensity_), end(referenceDensity_), - begin(comparedDensity), 0., std::plus<>(), relativeEntropyAtVoxel); + return std::inner_product(begin(referenceDensity_), + end(referenceDensity_), + begin(comparedDensity), + 0., + std::plus<>(), + relativeEntropyAtVoxel); } DensitySimilarityMeasure::density DensitySimilarityRelativeEntropy::gradient(density comparedDensity) @@ -204,8 +209,11 @@ DensitySimilarityMeasure::density DensitySimilarityRelativeEntropy::gradient(den { GMX_THROW(RangeError("Reference density and compared density need to have same extents.")); } - std::transform(begin(referenceDensity_), end(referenceDensity_), begin(comparedDensity), - begin(gradient_), relativeEntropyGradientAtVoxel); + std::transform(begin(referenceDensity_), + end(referenceDensity_), + begin(comparedDensity), + begin(gradient_), + relativeEntropyGradientAtVoxel); return gradient_.asConstView(); } @@ -361,8 +369,11 @@ DensitySimilarityMeasure::density DensitySimilarityCrossCorrelation::gradient(de CrossCorrelationEvaluationHelperValues helperValues = evaluateHelperValues(referenceDensity_, comparedDensity); - std::transform(begin(referenceDensity_), end(referenceDensity_), begin(comparedDensity), - begin(gradient_), CrossCorrelationGradientAtVoxel(helperValues)); + std::transform(begin(referenceDensity_), + end(referenceDensity_), + begin(comparedDensity), + begin(gradient_), + CrossCorrelationGradientAtVoxel(helperValues)); return gradient_.asConstView(); } diff --git a/src/gromacs/math/densityfittingforce.cpp b/src/gromacs/math/densityfittingforce.cpp index b3c8694639..a389054fba 100644 --- a/src/gromacs/math/densityfittingforce.cpp +++ b/src/gromacs/math/densityfittingforce.cpp @@ -107,8 +107,8 @@ RVec DensityFittingForce::Impl::evaluateForce(const GaussianSpreadKernelParamete { // multiply with amplitude so that Gauss3D = (amplitude * Gauss_x) * Gauss_y * Gauss_z const float gauss1DAmplitude = dimension > XX ? 1.0 : localParameters.amplitude_; - gauss1d_[dimension].spread(gauss1DAmplitude, localParameters.coordinate_[dimension] - - closestLatticePoint[dimension]); + gauss1d_[dimension].spread( + gauss1DAmplitude, localParameters.coordinate_[dimension] - closestLatticePoint[dimension]); } const auto spreadZY = outerProductZY_(gauss1d_[ZZ].view(), gauss1d_[YY].view()); @@ -117,7 +117,8 @@ RVec DensityFittingForce::Impl::evaluateForce(const GaussianSpreadKernelParamete latticeSpreadRange_[YY] - closestLatticePoint[YY], latticeSpreadRange_[ZZ] - closestLatticePoint[ZZ]); - const DVec differenceVectorScale = { 1. / (square(sigma_[XX])), 1. / (square(sigma_[YY])), + const DVec differenceVectorScale = { 1. / (square(sigma_[XX])), + 1. / (square(sigma_[YY])), 1. / (square(sigma_[ZZ])) }; const DVec differenceVectorOffset = scaleByVector( spreadRange.begin().toDVec() - localParameters.coordinate_.toDVec(), differenceVectorScale); diff --git a/src/gromacs/math/gausstransform.cpp b/src/gromacs/math/gausstransform.cpp index 111e2c7ccd..66ae8d6f97 100644 --- a/src/gromacs/math/gausstransform.cpp +++ b/src/gromacs/math/gausstransform.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -115,10 +115,10 @@ GaussianOn1DLattice::Impl::Impl(int numGridPointsForSpreadingHalfWidth, real sig std::min(maxEvaluatedSpreadDistance_, static_cast(std::floor(sigma * sqrt(-2.0 * c_logMinFloat))) - 1); - std::generate_n(std::back_inserter(e3_), maxEvaluatedSpreadDistance_ + 1, - [sigma, latticeIndex = 0]() mutable { - return std::exp(-0.5 * square(latticeIndex++ / sigma)); - }); + std::generate_n( + std::back_inserter(e3_), maxEvaluatedSpreadDistance_ + 1, [sigma, latticeIndex = 0]() mutable { + return std::exp(-0.5 * square(latticeIndex++ / sigma)); + }); std::fill(std::begin(spreadingResult_), std::end(spreadingResult_), 0.); }; @@ -235,7 +235,8 @@ IVec rangeBeginWithinLattice(const IVec& index, const IVec& range) */ IVec rangeEndWithinLattice(const IVec& index, const dynamicExtents3D& extents, const IVec& range) { - IVec extentAsIvec(static_cast(extents.extent(ZZ)), static_cast(extents.extent(YY)), + IVec extentAsIvec(static_cast(extents.extent(ZZ)), + static_cast(extents.extent(YY)), static_cast(extents.extent(XX))); return elementWiseMin(extentAsIvec, index + range); } @@ -254,8 +255,9 @@ mdspan OuterProductEvaluator:: for (gmx::index xIndex = 0; xIndex < ssize(x); ++xIndex) { const auto xValue = x[xIndex]; - std::transform(std::begin(y), std::end(y), begin(data_.asView()[xIndex]), - [xValue](float yValue) { return xValue * yValue; }); + std::transform(std::begin(y), std::end(y), begin(data_.asView()[xIndex]), [xValue](float yValue) { + return xValue * yValue; + }); } return data_.asConstView(); } @@ -356,8 +358,8 @@ void GaussTransform3D::Impl::add(const GaussianSpreadKernelParameters::PositionA { // multiply with amplitude so that Gauss3D = (amplitude * Gauss_x) * Gauss_y * Gauss_z const float gauss1DAmplitude = dimension > XX ? 1.0 : localParameters.amplitude_; - gauss1d_[dimension].spread(gauss1DAmplitude, localParameters.coordinate_[dimension] - - closestLatticePoint[dimension]); + gauss1d_[dimension].spread( + gauss1DAmplitude, localParameters.coordinate_[dimension] - closestLatticePoint[dimension]); } const auto spreadZY = outerProductZY_(gauss1d_[ZZ].view(), gauss1d_[YY].view()); diff --git a/src/gromacs/math/matrix.cpp b/src/gromacs/math/matrix.cpp index 662d6cf791..fffbce5fc5 100644 --- a/src/gromacs/math/matrix.cpp +++ b/src/gromacs/math/matrix.cpp @@ -50,8 +50,14 @@ namespace gmx Matrix3x3 transpose(Matrix3x3ConstSpan matrixView) { - return Matrix3x3({ matrixView(0, 0), matrixView(1, 0), matrixView(2, 0), matrixView(0, 1), - matrixView(1, 1), matrixView(2, 1), matrixView(0, 2), matrixView(1, 2), + return Matrix3x3({ matrixView(0, 0), + matrixView(1, 0), + matrixView(2, 0), + matrixView(0, 1), + matrixView(1, 1), + matrixView(2, 1), + matrixView(0, 2), + matrixView(1, 2), matrixView(2, 2) }); } diff --git a/src/gromacs/math/neldermead.cpp b/src/gromacs/math/neldermead.cpp index 9bb1df25af..d0d348a1ab 100644 --- a/src/gromacs/math/neldermead.cpp +++ b/src/gromacs/math/neldermead.cpp @@ -72,8 +72,10 @@ std::vector linearCombination(real alpha, ArrayRef a, real bet GMX_ASSERT(a.size() == b.size(), "Input vectors have to have the same size to evaluate their linear combination."); std::vector result(a.size()); - std::transform(std::begin(a), std::end(a), std::begin(b), std::begin(result), - [alpha, beta](auto a, auto b) { return alpha * a + beta * b; }); + std::transform( + std::begin(a), std::end(a), std::begin(b), std::begin(result), [alpha, beta](auto a, auto b) { + return alpha * a + beta * b; + }); return result; }; @@ -151,17 +153,20 @@ RealFunctionvalueAtCoordinate NelderMeadSimplex::evaluateExpansionPoint(const std::function)>& f) const { const std::vector expansionPointCoordinate = - linearCombination(1 - defaultNelderMeadParameters.gamma_, centroidWithoutWorstPoint_, - defaultNelderMeadParameters.gamma_, reflectionPointCoordinates_); + linearCombination(1 - defaultNelderMeadParameters.gamma_, + centroidWithoutWorstPoint_, + defaultNelderMeadParameters.gamma_, + reflectionPointCoordinates_); return { expansionPointCoordinate, f(expansionPointCoordinate) }; } RealFunctionvalueAtCoordinate NelderMeadSimplex::evaluateContractionPoint(const std::function)>& f) const { - std::vector contractionPoint = - linearCombination(1 - defaultNelderMeadParameters.rho_, centroidWithoutWorstPoint_, - defaultNelderMeadParameters.rho_, worstVertex().coordinate_); + std::vector contractionPoint = linearCombination(1 - defaultNelderMeadParameters.rho_, + centroidWithoutWorstPoint_, + defaultNelderMeadParameters.rho_, + worstVertex().coordinate_); return { contractionPoint, f(contractionPoint) }; } @@ -173,7 +178,9 @@ void NelderMeadSimplex::swapOutWorst(const RealFunctionvalueAtCoordinate& newVer // find the point to insert the new vertex, so that the simplex vertices // keep being sorted according to function value const auto insertionPoint = std::lower_bound( - std::begin(simplex_), std::end(simplex_), newVertex.value_, + std::begin(simplex_), + std::end(simplex_), + newVertex.value_, [](const RealFunctionvalueAtCoordinate& lhs, real value) { return lhs.value_ < value; }); simplex_.insert(insertionPoint, newVertex); // now that the simplex has changed, it has a new centroid and reflection point @@ -185,11 +192,15 @@ void NelderMeadSimplex::shrinkSimplexPointsExceptBest(const std::function bestPointCoordinate = simplex_.front().coordinate_; // skipping over the first simplex vertex, pull points closer to the best // vertex - std::transform(std::next(std::begin(simplex_)), std::end(simplex_), std::next(std::begin(simplex_)), + std::transform(std::next(std::begin(simplex_)), + std::end(simplex_), + std::next(std::begin(simplex_)), [bestPointCoordinate, f](const RealFunctionvalueAtCoordinate& d) -> RealFunctionvalueAtCoordinate { - const std::vector shrinkPoint = linearCombination( - defaultNelderMeadParameters.sigma_, d.coordinate_, - 1 - defaultNelderMeadParameters.sigma_, bestPointCoordinate); + const std::vector shrinkPoint = + linearCombination(defaultNelderMeadParameters.sigma_, + d.coordinate_, + 1 - defaultNelderMeadParameters.sigma_, + bestPointCoordinate); return { shrinkPoint, f(shrinkPoint) }; }); @@ -209,9 +220,10 @@ real NelderMeadSimplex::orientedLength() const { const std::vector differenceVector = linearCombination(1, firstSimplexVertexCoordinate, -1, simplexVertex.coordinate_); - const real thisLength = - std::accumulate(std::begin(differenceVector), std::end(differenceVector), 0., - [](real sum, real value) { return sum + value * value; }); + const real thisLength = std::accumulate( + std::begin(differenceVector), std::end(differenceVector), 0., [](real sum, real value) { + return sum + value * value; + }); result = std::max(result, thisLength); } return sqrt(result); @@ -221,23 +233,28 @@ void NelderMeadSimplex::updateCentroidAndReflectionPoint() { // intialize with first vertex, then add up all other vertex coordinates // expect last one - centroidWithoutWorstPoint_ = std::accumulate( - std::next(std::begin(simplex_)), std::prev(std::end(simplex_)), simplex_.front().coordinate_, - [](std::vector sum, const RealFunctionvalueAtCoordinate& x) { - std::transform(std::begin(sum), std::end(sum), std::begin(x.coordinate_), - std::begin(sum), std::plus<>()); - return sum; - }); + centroidWithoutWorstPoint_ = + std::accumulate(std::next(std::begin(simplex_)), + std::prev(std::end(simplex_)), + simplex_.front().coordinate_, + [](std::vector sum, const RealFunctionvalueAtCoordinate& x) { + std::transform(std::begin(sum), + std::end(sum), + std::begin(x.coordinate_), + std::begin(sum), + std::plus<>()); + return sum; + }); // divide the summed up coordinates by N (the simplex has N+1 vertices) - std::transform(std::begin(centroidWithoutWorstPoint_), std::end(centroidWithoutWorstPoint_), + std::transform(std::begin(centroidWithoutWorstPoint_), + std::end(centroidWithoutWorstPoint_), std::begin(centroidWithoutWorstPoint_), [n = simplex_.size() - 1](const auto& x) { return x / n; }); // now, that we have evaluated the centroid, update the reflection points - reflectionPointCoordinates_ = - linearCombination(defaultNelderMeadParameters.alpha_ + 1, centroidWithoutWorstPoint_, - -1, worstVertex().coordinate_); + reflectionPointCoordinates_ = linearCombination( + defaultNelderMeadParameters.alpha_ + 1, centroidWithoutWorstPoint_, -1, worstVertex().coordinate_); } } // namespace gmx diff --git a/src/gromacs/math/optimization.cpp b/src/gromacs/math/optimization.cpp index 4535fd86b4..7cf3b0c0ba 100644 --- a/src/gromacs/math/optimization.cpp +++ b/src/gromacs/math/optimization.cpp @@ -60,7 +60,8 @@ OptimisationResult nelderMead(const std::function)>& f // the oriented simplex length is smaller or equal a given number. const real minimumSimplexLength = minimumRelativeSimplexLength * nelderMeadSimplex.orientedLength(); for (int currentStep = 0; - nelderMeadSimplex.orientedLength() > minimumSimplexLength && currentStep < maxSteps; ++currentStep) + nelderMeadSimplex.orientedLength() > minimumSimplexLength && currentStep < maxSteps; + ++currentStep) { // see if simplex can by improved by reflecing the worst vertex at the centroid diff --git a/src/gromacs/math/tests/arrayrefwithpadding.cpp b/src/gromacs/math/tests/arrayrefwithpadding.cpp index a06f144236..3990584c16 100644 --- a/src/gromacs/math/tests/arrayrefwithpadding.cpp +++ b/src/gromacs/math/tests/arrayrefwithpadding.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2018,2019, by the GROMACS development team, led by + * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -170,8 +170,8 @@ TYPED_TEST(ArrayRefWithPaddingTest, AssignFromPaddedVectorWorks) TYPED_TEST(ArrayRefWithPaddingTest, ConstructFromPointersWorks) { - typename TestFixture::ArrayRefType arrayRef(this->v.data(), this->v.data() + this->v.size(), - this->v.data() + this->v.paddedSize()); + typename TestFixture::ArrayRefType arrayRef( + this->v.data(), this->v.data() + this->v.size(), this->v.data() + this->v.paddedSize()); this->runTests(arrayRef); } diff --git a/src/gromacs/math/tests/coordinatetransformation.cpp b/src/gromacs/math/tests/coordinatetransformation.cpp index 19472d019a..7fdf5561db 100644 --- a/src/gromacs/math/tests/coordinatetransformation.cpp +++ b/src/gromacs/math/tests/coordinatetransformation.cpp @@ -226,11 +226,14 @@ TEST_F(AffineTransformationTest, applyTransformationToVectors) RVec vectorTransformed = vector; affineTransformation(&vectorTransformed); // need relaxed tolerance here, due to the number of operations involved - EXPECT_REAL_EQ_TOL((*expected)[XX], vectorTransformed[XX], + EXPECT_REAL_EQ_TOL((*expected)[XX], + vectorTransformed[XX], relativeToleranceAsFloatingPoint((*expected)[XX], 1e-5)); - EXPECT_REAL_EQ_TOL((*expected)[YY], vectorTransformed[YY], + EXPECT_REAL_EQ_TOL((*expected)[YY], + vectorTransformed[YY], relativeToleranceAsFloatingPoint((*expected)[YY], 1e-5)); - EXPECT_REAL_EQ_TOL((*expected)[ZZ], vectorTransformed[ZZ], + EXPECT_REAL_EQ_TOL((*expected)[ZZ], + vectorTransformed[ZZ], relativeToleranceAsFloatingPoint((*expected)[ZZ], 1e-5)); ++expected; } diff --git a/src/gromacs/math/tests/densityfit.cpp b/src/gromacs/math/tests/densityfit.cpp index 1ebda302a7..fc6ad029e5 100644 --- a/src/gromacs/math/tests/densityfit.cpp +++ b/src/gromacs/math/tests/densityfit.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -88,8 +88,7 @@ TEST(DensitySimilarityTest, InnerProductGradientIsCorrect) std::iota(begin(comparedDensity), end(comparedDensity), -18); std::vector expectedSimilarityGradient; - std::copy(begin(referenceDensity), end(referenceDensity), - std::back_inserter(expectedSimilarityGradient)); + std::copy(begin(referenceDensity), end(referenceDensity), std::back_inserter(expectedSimilarityGradient)); for (auto& x : expectedSimilarityGradient) { x /= comparedDensity.asConstView().mapping().required_span_size(); diff --git a/src/gromacs/math/tests/dofit.cpp b/src/gromacs/math/tests/dofit.cpp index 2976200e98..a797f2a399 100644 --- a/src/gromacs/math/tests/dofit.cpp +++ b/src/gromacs/math/tests/dofit.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2018,2019, by the GROMACS development team, led by + * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -90,8 +90,8 @@ TEST_F(StructureSimilarityTest, YieldsCorrectRho) TEST_F(StructureSimilarityTest, YieldsCorrectRMSDWithIndex) { - EXPECT_REAL_EQ_TOL(sqrt(2.0), rmsdev_ind(index_.size(), index_.data(), m_, x1_, x2_), - defaultRealTolerance()); + EXPECT_REAL_EQ_TOL( + sqrt(2.0), rmsdev_ind(index_.size(), index_.data(), m_, x1_, x2_), defaultRealTolerance()); } TEST_F(StructureSimilarityTest, YieldsCorrectRhoWidthIndex) diff --git a/src/gromacs/math/tests/gausstransform.cpp b/src/gromacs/math/tests/gausstransform.cpp index a0f35646ac..06faafb4df 100644 --- a/src/gromacs/math/tests/gausstransform.cpp +++ b/src/gromacs/math/tests/gausstransform.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -90,10 +90,11 @@ TEST(GaussianOn1DLattice, isCorrect) FloatingPointTolerance tolerance(defaultFloatTolerance()); const real amplitude = 1.0; gauss1d.spread(amplitude, shift); - std::array expected = { - 0.0047816522419452667236328125, 0.2613909542560577392578125, 0.65811407566070556640625, - 0.07631497085094451904296875, 0.000407583254855126142501831054688 - }; + std::array expected = { 0.0047816522419452667236328125, + 0.2613909542560577392578125, + 0.65811407566070556640625, + 0.07631497085094451904296875, + 0.000407583254855126142501831054688 }; EXPECT_THAT(expected, Pointwise(FloatEq(tolerance), viewOnResult)); } @@ -109,13 +110,14 @@ TEST(GaussianOn1DLattice, complementaryAmplitudesSumToZero) gauss1d.spread(amplitude, shift); std::vector sumOfComplementaryGaussians; // keep a copy of the first Gaussian - std::copy(std::begin(viewOnResult), std::end(viewOnResult), - std::back_inserter(sumOfComplementaryGaussians)); + std::copy(std::begin(viewOnResult), std::end(viewOnResult), std::back_inserter(sumOfComplementaryGaussians)); gauss1d.spread(-amplitude, shift); // add the two spread Gaussians - std::transform(std::begin(viewOnResult), std::end(viewOnResult), - std::begin(sumOfComplementaryGaussians), std::begin(sumOfComplementaryGaussians), + std::transform(std::begin(viewOnResult), + std::end(viewOnResult), + std::begin(sumOfComplementaryGaussians), + std::begin(sumOfComplementaryGaussians), std::plus<>()); // Expect all zeros std::array expected = {}; diff --git a/src/gromacs/math/veccompare.cpp b/src/gromacs/math/veccompare.cpp index 22c75d49f7..1914b9d18e 100644 --- a/src/gromacs/math/veccompare.cpp +++ b/src/gromacs/math/veccompare.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team. - * Copyright (c) 2013,2014,2015,2016,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2015,2016,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -50,13 +50,28 @@ void cmp_rvec(FILE* fp, const char* s, int index, const rvec i1, const rvec i2, { if (index != -1) { - fprintf(fp, "%s[%5d] (%12.5e %12.5e %12.5e) - (%12.5e %12.5e %12.5e)\n", s, index, - i1[XX], i1[YY], i1[ZZ], i2[XX], i2[YY], i2[ZZ]); + fprintf(fp, + "%s[%5d] (%12.5e %12.5e %12.5e) - (%12.5e %12.5e %12.5e)\n", + s, + index, + i1[XX], + i1[YY], + i1[ZZ], + i2[XX], + i2[YY], + i2[ZZ]); } else { - fprintf(fp, "%s (%12.5e %12.5e %12.5e) - (%12.5e %12.5e %12.5e)\n", s, i1[XX], i1[YY], - i1[ZZ], i2[XX], i2[YY], i2[ZZ]); + fprintf(fp, + "%s (%12.5e %12.5e %12.5e) - (%12.5e %12.5e %12.5e)\n", + s, + i1[XX], + i1[YY], + i1[ZZ], + i2[XX], + i2[YY], + i2[ZZ]); } } } @@ -67,13 +82,20 @@ void cmp_ivec(FILE* fp, const char* s, int index, const ivec i1, const ivec i2) { if (index != -1) { - fprintf(fp, "%s[%5d] (%8d,%8d,%8d - %8d,%8d,%8d)\n", s, index, i1[XX], i1[YY], i1[ZZ], - i2[XX], i2[YY], i2[ZZ]); + fprintf(fp, + "%s[%5d] (%8d,%8d,%8d - %8d,%8d,%8d)\n", + s, + index, + i1[XX], + i1[YY], + i1[ZZ], + i2[XX], + i2[YY], + i2[ZZ]); } else { - fprintf(fp, "%s (%8d,%8d,%8d - %8d,%8d,%8d)\n", s, i1[XX], i1[YY], i1[ZZ], i2[XX], - i2[YY], i2[ZZ]); + fprintf(fp, "%s (%8d,%8d,%8d - %8d,%8d,%8d)\n", s, i1[XX], i1[YY], i1[ZZ], i2[XX], i2[YY], i2[ZZ]); } } } diff --git a/src/gromacs/math/vecdump.cpp b/src/gromacs/math/vecdump.cpp index 6e640d69ce..4fde70e8bd 100644 --- a/src/gromacs/math/vecdump.cpp +++ b/src/gromacs/math/vecdump.cpp @@ -89,8 +89,13 @@ void pr_ivec_block(FILE* fp, int indent, const char* title, const int vec[], int else { pr_indent(fp, indent); - fprintf(fp, "%s[%d,...,%d] = {%d,...,%d}\n", title, bShowNumbers ? i : -1, - bShowNumbers ? j - 1 : -1, vec[i], vec[j - 1]); + fprintf(fp, + "%s[%d,...,%d] = {%d,...,%d}\n", + title, + bShowNumbers ? i : -1, + bShowNumbers ? j - 1 : -1, + vec[i], + vec[j - 1]); i = j; } } diff --git a/src/gromacs/mdlib/calc_verletbuf.cpp b/src/gromacs/mdlib/calc_verletbuf.cpp index 90e9acf927..b904b9c409 100644 --- a/src/gromacs/mdlib/calc_verletbuf.cpp +++ b/src/gromacs/mdlib/calc_verletbuf.cpp @@ -311,8 +311,11 @@ static void get_vsite_masses(const gmx_moltype_t& moltype, } if (gmx_debug_at) { - fprintf(debug, "atom %4d %-20s mass %6.3f\n", a1, - interaction_function[ilist.functionType].longname, vsite_m[a1]); + fprintf(debug, + "atom %4d %-20s mass %6.3f\n", + a1, + interaction_function[ilist.functionType].longname, + vsite_m[a1]); } } } @@ -421,10 +424,16 @@ static std::vector getVerletBufferAtomtypes(const gmx_mtop_t& { for (size_t a = 0; a < att.size(); a++) { - fprintf(debug, "type %zu: m %5.2f t %d q %6.3f con %s con_m %5.3f con_l %5.3f n %d\n", - a, att[a].prop.mass, att[a].prop.type, att[a].prop.q, - gmx::boolToString(att[a].prop.bConstr), att[a].prop.con_mass, - att[a].prop.con_len, att[a].n); + fprintf(debug, + "type %zu: m %5.2f t %d q %6.3f con %s con_m %5.3f con_l %5.3f n %d\n", + a, + att[a].prop.mass, + att[a].prop.type, + att[a].prop.q, + gmx::boolToString(att[a].prop.bConstr), + att[a].prop.con_mass, + att[a].prop.con_len, + att[a].n); } } @@ -657,8 +666,8 @@ static real energyDrift(gmx::ArrayRef att, lj.d2 = c6 * ljDisp->d2 + c12 * ljRep->d2; lj.md3 = c6 * ljDisp->md3 + c12 * ljRep->md3; - real pot_lj = energyDriftAtomPair(prop_i->bConstr, prop_j->bConstr, s2, s2i_2d, s2j_2d, - rlist - rlj, &lj); + real pot_lj = energyDriftAtomPair( + prop_i->bConstr, prop_j->bConstr, s2, s2i_2d, s2j_2d, rlist - rlj, &lj); // Set -V' and V'' at the cut-off for Coulomb pot_derivatives_t elec_qq; @@ -666,8 +675,8 @@ static real energyDrift(gmx::ArrayRef att, elec_qq.d2 = elec->d2 * prop_i->q * prop_j->q; elec_qq.md3 = 0; - real pot_q = energyDriftAtomPair(prop_i->bConstr, prop_j->bConstr, s2, s2i_2d, s2j_2d, - rlist - rcoulomb, &elec_qq); + real pot_q = energyDriftAtomPair( + prop_i->bConstr, prop_j->bConstr, s2, s2i_2d, s2j_2d, rlist - rcoulomb, &elec_qq); // Note that attractive and repulsive potentials for individual // pairs can partially cancel. @@ -1053,8 +1062,8 @@ real calcVerletBufferSize(const gmx_mtop_t& mtop, /* Calculate the average energy drift at the last step * of the nstlist steps at which the pair-list is used. */ - drift = energyDrift(att, &mtop.ffparams, kT_fac, &ljDisp, &ljRep, &elec, ir.rvdw, - ir.rcoulomb, rl, boxVolume); + drift = energyDrift( + att, &mtop.ffparams, kT_fac, &ljDisp, &ljRep, &elec, ir.rvdw, ir.rcoulomb, rl, boxVolume); /* Correct for the fact that we are using a Ni x Nj particle pair list * and not a 1 x 1 particle pair list. This reduces the drift. @@ -1070,9 +1079,16 @@ real calcVerletBufferSize(const gmx_mtop_t& mtop, if (debug) { - fprintf(debug, "ib %3d %3d %3d rb %.3f %dx%d fac %.3f drift %.1e\n", ib0, ib, ib1, rb, - listSetup.cluster_size_i, listSetup.cluster_size_j, - nb_clust_frac_pairs_not_in_list_at_cutoff, drift); + fprintf(debug, + "ib %3d %3d %3d rb %.3f %dx%d fac %.3f drift %.1e\n", + ib0, + ib, + ib1, + rb, + listSetup.cluster_size_i, + listSetup.cluster_size_j, + nb_clust_frac_pairs_not_in_list_at_cutoff, + drift); } if (std::abs(drift) > ir.verletbuf_tol) @@ -1120,8 +1136,8 @@ static real chanceOfAtomCrossingCell(gmx::ArrayRef atom real s2_3d; get_atom_sigma2(kT_fac, &propAtom, &s2_2d, &s2_3d); - real chancePerAtom = energyDriftAtomPair(propAtom.bConstr, false, s2_2d + s2_3d, s2_2d, 0, - cellSize, &boundaryInteraction); + real chancePerAtom = energyDriftAtomPair( + propAtom.bConstr, false, s2_2d + s2_3d, s2_2d, 0, cellSize, &boundaryInteraction); if (propAtom.bConstr) { @@ -1273,8 +1289,8 @@ static real chanceOfUpdateGroupCrossingCell(const gmx_moltype_t& moltyp } } real s2_3d = kT_fac / massSum; - chance += energyDriftAtomPair(false, false, s2_3d, 0, 0, cellSize - 2 * maxComCogDistance, - &boundaryInteraction); + chance += energyDriftAtomPair( + false, false, s2_3d, 0, 0, cellSize - 2 * maxComCogDistance, &boundaryInteraction); } return chance; @@ -1294,8 +1310,8 @@ static real chanceOfUpdateGroupCrossingCell(const gmx_mtop_t& mtop, { const gmx_moltype_t& moltype = mtop.moltype[molblock.type]; chance += molblock.nmol - * chanceOfUpdateGroupCrossingCell(moltype, mtop.ffparams, - updateGrouping[molblock.type], kT_fac, cellSize); + * chanceOfUpdateGroupCrossingCell( + moltype, mtop.ffparams, updateGrouping[molblock.type], kT_fac, cellSize); } return chance; diff --git a/src/gromacs/mdlib/calcvir.cpp b/src/gromacs/mdlib/calcvir.cpp index 99398cff84..0cf7c41952 100644 --- a/src/gromacs/mdlib/calcvir.cpp +++ b/src/gromacs/mdlib/calcvir.cpp @@ -126,7 +126,11 @@ void calc_vir(int nxf, const rvec x[], const rvec f[], tensor vir, bool bScrewPB int start = (nxf * thread) / nthreads; int end = std::min(nxf * (thread + 1) / nthreads, nxf); - calc_x_times_f(end - start, x + start, f + start, bScrewPBC, box, + calc_x_times_f(end - start, + x + start, + f + start, + bScrewPBC, + box, thread == 0 ? x_times_f : xf_buf[thread * 3]); } diff --git a/src/gromacs/mdlib/constr.cpp b/src/gromacs/mdlib/constr.cpp index 21397f342b..3c78f53cd3 100644 --- a/src/gromacs/mdlib/constr.cpp +++ b/src/gromacs/mdlib/constr.cpp @@ -243,7 +243,8 @@ void too_many_constraint_warnings(int eConstrAlg, int warncount) "If you know what you are doing you can %s" "set the environment variable GMX_MAXCONSTRWARN to -1,\n" "but normally it is better to fix the problem", - (eConstrAlg == econtLINCS) ? "LINCS" : "SETTLE", warncount, + (eConstrAlg == econtLINCS) ? "LINCS" : "SETTLE", + warncount, (eConstrAlg == econtLINCS) ? "adjust the lincs warning threshold in your mdp file\nor " : "\n"); } @@ -301,8 +302,21 @@ static void write_constr_pdb(const char* fn, ii = i; } mtopGetAtomAndResidueName(mtop, ii, &molb, &anm, &resnr, &resnm, nullptr); - gmx_fprintf_pdb_atomline(out, epdbATOM, ii + 1, anm, ' ', resnm, ' ', resnr, ' ', - 10 * x[i][XX], 10 * x[i][YY], 10 * x[i][ZZ], 1.0, 0.0, ""); + gmx_fprintf_pdb_atomline(out, + epdbATOM, + ii + 1, + anm, + ' ', + resnm, + ' ', + resnr, + ' ', + 10 * x[i][XX], + 10 * x[i][YY], + 10 * x[i][ZZ], + 1.0, + 0.0, + ""); } fprintf(out, "TER\n"); @@ -355,9 +369,21 @@ bool Constraints::apply(bool bLog, tensor constraintsVirial, ConstraintVariable econq) { - return impl_->apply(bLog, bEner, step, delta_step, step_scaling, std::move(x), - std::move(xprime), min_proj, box, lambda, dvdlambda, std::move(v), - computeVirial, constraintsVirial, econq); + return impl_->apply(bLog, + bEner, + step, + delta_step, + step_scaling, + std::move(x), + std::move(xprime), + min_proj, + box, + lambda, + dvdlambda, + std::move(v), + computeVirial, + constraintsVirial, + econq); } bool Constraints::Impl::apply(bool bLog, @@ -461,7 +487,10 @@ bool Constraints::Impl::apply(bool bLog, */ if (cr->dd) { - dd_move_x_constraints(cr->dd, box, x.unpaddedArrayRef(), xprime.unpaddedArrayRef(), + dd_move_x_constraints(cr->dd, + box, + x.unpaddedArrayRef(), + xprime.unpaddedArrayRef(), econq == ConstraintVariable::Positions); if (!v.empty()) @@ -476,16 +505,37 @@ bool Constraints::Impl::apply(bool bLog, if (lincsd != nullptr) { - bOK = constrain_lincs(bLog || bEner, ir, step, lincsd, inverseMasses_, cr, ms, x, xprime, - min_proj, box, pbc_null, hasMassPerturbedAtoms_, lambda, dvdlambda, - invdt, v.unpaddedArrayRef(), computeVirial, constraintsVirial, econq, - nrnb, maxwarn, &warncount_lincs); + bOK = constrain_lincs(bLog || bEner, + ir, + step, + lincsd, + inverseMasses_, + cr, + ms, + x, + xprime, + min_proj, + box, + pbc_null, + hasMassPerturbedAtoms_, + lambda, + dvdlambda, + invdt, + v.unpaddedArrayRef(), + computeVirial, + constraintsVirial, + econq, + nrnb, + maxwarn, + &warncount_lincs); if (!bOK && maxwarn < INT_MAX) { if (log != nullptr) { - fprintf(log, "Constraint error in algorithm %s at step %s\n", - econstr_names[econtLINCS], gmx_step_str(step, buf)); + fprintf(log, + "Constraint error in algorithm %s at step %s\n", + econstr_names[econtLINCS], + gmx_step_str(step, buf)); } bDump = TRUE; } @@ -493,17 +543,33 @@ bool Constraints::Impl::apply(bool bLog, if (shaked != nullptr) { - bOK = constrain_shake(log, shaked.get(), inverseMasses_, *idef, ir, x.unpaddedArrayRef(), - xprime.unpaddedArrayRef(), min_proj, pbc_null, nrnb, lambda, - dvdlambda, invdt, v.unpaddedArrayRef(), computeVirial, - constraintsVirial, maxwarn < INT_MAX, econq); + bOK = constrain_shake(log, + shaked.get(), + inverseMasses_, + *idef, + ir, + x.unpaddedArrayRef(), + xprime.unpaddedArrayRef(), + min_proj, + pbc_null, + nrnb, + lambda, + dvdlambda, + invdt, + v.unpaddedArrayRef(), + computeVirial, + constraintsVirial, + maxwarn < INT_MAX, + econq); if (!bOK && maxwarn < INT_MAX) { if (log != nullptr) { - fprintf(log, "Constraint error in algorithm %s at step %s\n", - econstr_names[econtSHAKE], gmx_step_str(step, buf)); + fprintf(log, + "Constraint error in algorithm %s at step %s\n", + econstr_names[econtSHAKE], + gmx_step_str(step, buf)); } bDump = TRUE; } @@ -526,7 +592,15 @@ bool Constraints::Impl::apply(bool bLog, clear_mat(threadConstraintsVirial[th]); } - csettle(*settled, nth, th, pbc_null, x, xprime, invdt, v, computeVirial, + csettle(*settled, + nth, + th, + pbc_null, + x, + xprime, + invdt, + v, + computeVirial, th == 0 ? constraintsVirial : threadConstraintsVirial[th], th == 0 ? &bSettleErrorHasOccurred0 : &bSettleErrorHasOccurred[th]); } @@ -572,10 +646,15 @@ bool Constraints::Impl::apply(bool bLog, if (start_th >= 0 && end_th - start_th > 0) { - settle_proj(*settled, econq, end_th - start_th, + settle_proj(*settled, + econq, + end_th - start_th, settle.iatoms.data() + start_th * (1 + NRAL(F_SETTLE)), - pbc_null, x.unpaddedArrayRef(), xprime.unpaddedArrayRef(), - min_proj, calcvir_atom_end, + pbc_null, + x.unpaddedArrayRef(), + xprime.unpaddedArrayRef(), + min_proj, + calcvir_atom_end, th == 0 ? constraintsVirial : threadConstraintsVirial[th]); } } @@ -666,8 +745,7 @@ bool Constraints::Impl::apply(bool bLog, if (bDump) { - dump_confs(log, step, mtop, start, numHomeAtoms_, cr, x.unpaddedArrayRef(), - xprime.unpaddedArrayRef(), box); + dump_confs(log, step, mtop, start, numHomeAtoms_, cr, x.unpaddedArrayRef(), xprime.unpaddedArrayRef(), box); } if (econq == ConstraintVariable::Positions) @@ -683,16 +761,27 @@ bool Constraints::Impl::apply(bool bLog, t = ir.init_t; } set_pbc(&pbc, ir.pbcType, box); - pull_constraint(pull_work, masses_, &pbc, cr, ir.delta_t, t, + pull_constraint(pull_work, + masses_, + &pbc, + cr, + ir.delta_t, + t, as_rvec_array(x.unpaddedArrayRef().data()), as_rvec_array(xprime.unpaddedArrayRef().data()), - as_rvec_array(v.unpaddedArrayRef().data()), constraintsVirial); + as_rvec_array(v.unpaddedArrayRef().data()), + constraintsVirial); } if (ed && delta_step > 0) { /* apply the essential dynamics constraints here */ - do_edsam(&ir, step, cr, as_rvec_array(xprime.unpaddedArrayRef().data()), - as_rvec_array(v.unpaddedArrayRef().data()), box, ed); + do_edsam(&ir, + step, + cr, + as_rvec_array(xprime.unpaddedArrayRef().data()), + as_rvec_array(v.unpaddedArrayRef().data()), + box, + ed); } } wallcycle_stop(wcycle, ewcCONSTR); @@ -852,8 +941,8 @@ ListOfLists make_at2con(const gmx_moltype_t& moltype, gmx::ArrayRef iparams, FlexibleConstraintTreatment flexibleConstraintTreatment) { - return makeAtomsToConstraintsList(moltype.atoms.nr, makeConstArrayRef(moltype.ilist), iparams, - flexibleConstraintTreatment); + return makeAtomsToConstraintsList( + moltype.atoms.nr, makeConstArrayRef(moltype.ilist), iparams, flexibleConstraintTreatment); } //! Return the number of flexible constraints in the \c ilist and \c iparams. @@ -960,8 +1049,8 @@ void Constraints::setConstraints(gmx_localtop_t* top, const real lambda, unsigned short* cFREEZE) { - impl_->setConstraints(top, numAtoms, numHomeAtoms, masses, inverseMasses, hasMassPerturbedAtoms, - lambda, cFREEZE); + impl_->setConstraints( + top, numAtoms, numHomeAtoms, masses, inverseMasses, hasMassPerturbedAtoms, lambda, cFREEZE); } /*! \brief Makes a per-moleculetype container of mappings from atom @@ -1058,8 +1147,12 @@ Constraints::Impl::Impl(const gmx_mtop_t& mtop_p, if (ir.eConstrAlg == econtLINCS) { - lincsd = init_lincs(log, mtop, nflexcon, at2con_mt, - DOMAINDECOMP(cr) && ddHaveSplitConstraints(*cr->dd), ir.nLincsIter, + lincsd = init_lincs(log, + mtop, + nflexcon, + at2con_mt, + DOMAINDECOMP(cr) && ddHaveSplitConstraints(*cr->dd), + ir.nLincsIter, ir.nProjOrder); } @@ -1197,14 +1290,40 @@ void do_constrain_first(FILE* fplog, bool computeEnergy = false; bool computeVirial = false; /* constrain the current position */ - constr->apply(needsLogging, computeEnergy, step, 0, 1.0, x, x, {}, box, lambda, &dvdl_dum, {}, - computeVirial, nullptr, gmx::ConstraintVariable::Positions); + constr->apply(needsLogging, + computeEnergy, + step, + 0, + 1.0, + x, + x, + {}, + box, + lambda, + &dvdl_dum, + {}, + computeVirial, + nullptr, + gmx::ConstraintVariable::Positions); if (EI_VV(ir->eI)) { /* constrain the inital velocity, and save it */ /* also may be useful if we need the ekin from the halfstep for velocity verlet */ - constr->apply(needsLogging, computeEnergy, step, 0, 1.0, x, v, v.unpaddedArrayRef(), box, lambda, - &dvdl_dum, {}, computeVirial, nullptr, gmx::ConstraintVariable::Velocities); + constr->apply(needsLogging, + computeEnergy, + step, + 0, + 1.0, + x, + v, + v.unpaddedArrayRef(), + box, + lambda, + &dvdl_dum, + {}, + computeVirial, + nullptr, + gmx::ConstraintVariable::Velocities); } /* constrain the inital velocities at t-dt/2 */ if (EI_STATE_VELOCITY(ir->eI) && ir->eI != eiVV) @@ -1230,8 +1349,20 @@ void do_constrain_first(FILE* fplog, fprintf(fplog, "\nConstraining the coordinates at t0-dt (step %s)\n", gmx_step_str(step, buf)); } dvdl_dum = 0; - constr->apply(needsLogging, computeEnergy, step, -1, 1.0, x, savex.arrayRefWithPadding(), - {}, box, lambda, &dvdl_dum, v, computeVirial, nullptr, + constr->apply(needsLogging, + computeEnergy, + step, + -1, + 1.0, + x, + savex.arrayRefWithPadding(), + {}, + box, + lambda, + &dvdl_dum, + v, + computeVirial, + nullptr, gmx::ConstraintVariable::Positions); for (i = start; i < end; i++) @@ -1256,10 +1387,21 @@ void constrain_velocities(gmx::Constraints* constr, { if (constr != nullptr) { - constr->apply(do_log, do_ene, step, 1, 1.0, state->x.arrayRefWithPadding(), - state->v.arrayRefWithPadding(), state->v.arrayRefWithPadding().unpaddedArrayRef(), - state->box, state->lambda[efptBONDED], dvdlambda, ArrayRefWithPadding(), - computeVirial, constraintsVirial, ConstraintVariable::Velocities); + constr->apply(do_log, + do_ene, + step, + 1, + 1.0, + state->x.arrayRefWithPadding(), + state->v.arrayRefWithPadding(), + state->v.arrayRefWithPadding().unpaddedArrayRef(), + state->box, + state->lambda[efptBONDED], + dvdlambda, + ArrayRefWithPadding(), + computeVirial, + constraintsVirial, + ConstraintVariable::Velocities); } } @@ -1275,9 +1417,20 @@ void constrain_coordinates(gmx::Constraints* constr, { if (constr != nullptr) { - constr->apply(do_log, do_ene, step, 1, 1.0, state->x.arrayRefWithPadding(), std::move(xp), - ArrayRef(), state->box, state->lambda[efptBONDED], dvdlambda, - state->v.arrayRefWithPadding(), computeVirial, constraintsVirial, + constr->apply(do_log, + do_ene, + step, + 1, + 1.0, + state->x.arrayRefWithPadding(), + std::move(xp), + ArrayRef(), + state->box, + state->lambda[efptBONDED], + dvdlambda, + state->v.arrayRefWithPadding(), + computeVirial, + constraintsVirial, ConstraintVariable::Positions); } } diff --git a/src/gromacs/mdlib/constraintrange.cpp b/src/gromacs/mdlib/constraintrange.cpp index 90d16294d0..a3eacef6f1 100644 --- a/src/gromacs/mdlib/constraintrange.cpp +++ b/src/gromacs/mdlib/constraintrange.cpp @@ -120,11 +120,15 @@ static void constr_recur(const ListOfLists& at2con, if (debug) { fprintf(debug, - "Found longer constraint distance: r0 %5.3f r1 %5.3f rmax %5.3f\n", rn0, - rn1, sqrt(*r2max)); + "Found longer constraint distance: r0 %5.3f r1 %5.3f rmax %5.3f\n", + rn0, + rn1, + sqrt(*r2max)); for (int a1 = 0; a1 < depth; a1++) { - fprintf(debug, " %d %5.3f", path[a1], + fprintf(debug, + " %d %5.3f", + path[a1], iparams[constr_iatomptr(ia1, ia2, con)[0]].constr.dA); } fprintf(debug, " %d %5.3f\n", con, len); @@ -185,8 +189,8 @@ static real constr_r_max_moltype(const gmx_moltype_t* molt, r1 = 0; count = 0; - constr_recur(at2con, molt->ilist, iparams, FALSE, at, 0, 1 + ir->nProjOrder, path, r0, r1, - &r2maxA, &count); + constr_recur( + at2con, molt->ilist, iparams, FALSE, at, 0, 1 + ir->nProjOrder, path, r0, r1, &r2maxA, &count); } if (ir->efep == efepNO) { @@ -200,8 +204,8 @@ static real constr_r_max_moltype(const gmx_moltype_t* molt, r0 = 0; r1 = 0; count = 0; - constr_recur(at2con, molt->ilist, iparams, TRUE, at, 0, 1 + ir->nProjOrder, path, r0, - r1, &r2maxB, &count); + constr_recur( + at2con, molt->ilist, iparams, TRUE, at, 0, 1 + ir->nProjOrder, path, r0, r1, &r2maxB, &count); } lam0 = ir->fepvals->init_lambda; if (EI_DYNAMICS(ir->eI)) @@ -230,7 +234,8 @@ real constr_r_max(const MDLogger& mdlog, const gmx_mtop_t* mtop, const t_inputre GMX_LOG(mdlog.info) .appendTextFormatted( "Maximum distance for %d constraints, at 120 deg. angles, all-trans: %.3f nm", - 1 + ir->nProjOrder, rmax); + 1 + ir->nProjOrder, + rmax); return rmax; } diff --git a/src/gromacs/mdlib/coupling.cpp b/src/gromacs/mdlib/coupling.cpp index e56bcada93..8bc70fbe4b 100644 --- a/src/gromacs/mdlib/coupling.cpp +++ b/src/gromacs/mdlib/coupling.cpp @@ -87,8 +87,11 @@ static const double sy_const_1[] = { 1. }; static const double sy_const_3[] = { 0.828981543588751, -0.657963087177502, 0.828981543588751 }; -static const double sy_const_5[] = { 0.2967324292201065, 0.2967324292201065, -0.186929716880426, - 0.2967324292201065, 0.2967324292201065 }; +static const double sy_const_5[] = { 0.2967324292201065, + 0.2967324292201065, + -0.186929716880426, + 0.2967324292201065, + 0.2967324292201065 }; static const double* sy_const[] = { nullptr, sy_const_1, nullptr, sy_const_3, nullptr, sy_const_5 }; @@ -138,8 +141,12 @@ void update_tcouple(int64_t step, berendsen_tcoupl(inputrec, ekind, dttc, state->therm_integral); break; case etcNOSEHOOVER: - nosehoover_tcoupl(&(inputrec->opts), ekind, dttc, state->nosehoover_xi.data(), - state->nosehoover_vxi.data(), MassQ); + nosehoover_tcoupl(&(inputrec->opts), + ekind, + dttc, + state->nosehoover_xi.data(), + state->nosehoover_vxi.data(), + MassQ); break; case etcVRESCALE: vrescale_tcoupl(inputrec, step, ekind, dttc, state->therm_integral.data()); @@ -178,8 +185,8 @@ void update_pcouple_before_coordinates(FILE* fplog, { real dtpc = inputrec->nstpcouple * inputrec->delta_t; - parrinellorahman_pcoupl(fplog, step, inputrec, dtpc, state->pres_prev, state->box, - state->box_rel, state->boxv, M, parrinellorahmanMu, bInitStep); + parrinellorahman_pcoupl( + fplog, step, inputrec, dtpc, state->pres_prev, state->box, state->box_rel, state->boxv, M, parrinellorahmanMu, bInitStep); } } @@ -211,21 +218,53 @@ void update_pcouple_after_coordinates(FILE* fplog, if (do_per_step(step, inputrec->nstpcouple)) { real dtpc = inputrec->nstpcouple * dt; - berendsen_pcoupl(fplog, step, inputrec, dtpc, pressure, state->box, forceVirial, - constraintVirial, pressureCouplingMu, &state->baros_integral); - berendsen_pscale(inputrec, pressureCouplingMu, state->box, state->box_rel, start, - homenr, state->x.rvec_array(), md->cFREEZE, nrnb, scaleCoordinates); + berendsen_pcoupl(fplog, + step, + inputrec, + dtpc, + pressure, + state->box, + forceVirial, + constraintVirial, + pressureCouplingMu, + &state->baros_integral); + berendsen_pscale(inputrec, + pressureCouplingMu, + state->box, + state->box_rel, + start, + homenr, + state->x.rvec_array(), + md->cFREEZE, + nrnb, + scaleCoordinates); } break; case (epcCRESCALE): if (do_per_step(step, inputrec->nstpcouple)) { real dtpc = inputrec->nstpcouple * dt; - crescale_pcoupl(fplog, step, inputrec, dtpc, pressure, state->box, forceVirial, - constraintVirial, pressureCouplingMu, &state->baros_integral); - crescale_pscale(inputrec, pressureCouplingMu, state->box, state->box_rel, start, - homenr, state->x.rvec_array(), state->v.rvec_array(), md->cFREEZE, - nrnb, scaleCoordinates); + crescale_pcoupl(fplog, + step, + inputrec, + dtpc, + pressure, + state->box, + forceVirial, + constraintVirial, + pressureCouplingMu, + &state->baros_integral); + crescale_pscale(inputrec, + pressureCouplingMu, + state->box, + state->box_rel, + start, + homenr, + state->x.rvec_array(), + state->v.rvec_array(), + md->cFREEZE, + nrnb, + scaleCoordinates); } break; case (epcPARRINELLORAHMAN): @@ -318,8 +357,8 @@ extern gmx_bool update_randomize_velocities(const t_inputrec* ir, particle andersen or 2) it's massive andersen and it's tau_t/dt */ if ((ir->etc == etcANDERSEN) || do_per_step(step, gmx::roundToInt(1.0 / rate))) { - andersen_tcoupl(ir, step, cr, md, v, rate, upd->getAndersenRandomizeGroup(), - upd->getBoltzmanFactor()); + andersen_tcoupl( + ir, step, cr, md, v, rate, upd->getAndersenRandomizeGroup(), upd->getBoltzmanFactor()); return TRUE; } return FALSE; @@ -882,7 +921,8 @@ void berendsen_pcoupl(FILE* fplog, } break; default: - gmx_fatal(FARGS, "Berendsen pressure coupling type %s not supported yet\n", + gmx_fatal(FARGS, + "Berendsen pressure coupling type %s not supported yet\n", EPCOUPLTYPETYPE(ir->epct)); } /* To fullfill the orientation restrictions on triclinic boxes @@ -927,7 +967,10 @@ void berendsen_pcoupl(FILE* fplog, sprintf(buf, "\nStep %s Warning: pressure scaling more than 1%%, " "mu: %g %g %g\n", - gmx_step_str(step, buf2), mu[XX][XX], mu[YY][YY], mu[ZZ][ZZ]); + gmx_step_str(step, buf2), + mu[XX][XX], + mu[YY][YY], + mu[ZZ][ZZ]); if (fplog) { fprintf(fplog, "%s", buf); @@ -1029,7 +1072,8 @@ void crescale_pcoupl(FILE* fplog, } break; default: - gmx_fatal(FARGS, "C-rescale pressure coupling type %s not supported yet\n", + gmx_fatal(FARGS, + "C-rescale pressure coupling type %s not supported yet\n", EPCOUPLTYPETYPE(ir->epct)); } /* To fullfill the orientation restrictions on triclinic boxes @@ -1075,7 +1119,10 @@ void crescale_pcoupl(FILE* fplog, sprintf(buf, "\nStep %s Warning: pressure scaling more than 1%%, " "mu: %g %g %g\n", - gmx_step_str(step, buf2), mu[XX][XX], mu[YY][YY], mu[ZZ][ZZ]); + gmx_step_str(step, buf2), + mu[XX][XX], + mu[YY][YY], + mu[ZZ][ZZ]); if (fplog) { fprintf(fplog, "%s", buf); @@ -1416,18 +1463,33 @@ void trotter_update(const t_inputrec* ir, { case etrtBAROV: case etrtBAROV2: - boxv_trotter(ir, &(state->veta), dt, state->box, ekind, vir, - enerd->term[F_PDISPCORR], MassQ); + boxv_trotter(ir, &(state->veta), dt, state->box, ekind, vir, enerd->term[F_PDISPCORR], MassQ); break; case etrtBARONHC: case etrtBARONHC2: - NHC_trotter(opts, state->nnhpres, ekind, dt, state->nhpres_xi.data(), - state->nhpres_vxi.data(), nullptr, &(state->veta), MassQ, FALSE); + NHC_trotter(opts, + state->nnhpres, + ekind, + dt, + state->nhpres_xi.data(), + state->nhpres_vxi.data(), + nullptr, + &(state->veta), + MassQ, + FALSE); break; case etrtNHC: case etrtNHC2: - NHC_trotter(opts, opts->ngtc, ekind, dt, state->nosehoover_xi.data(), - state->nosehoover_vxi.data(), scalefac, nullptr, MassQ, (ir->eI == eiVV)); + NHC_trotter(opts, + opts->ngtc, + ekind, + dt, + state->nosehoover_xi.data(), + state->nosehoover_vxi.data(), + scalefac, + nullptr, + MassQ, + (ir->eI == eiVV)); /* need to rescale the kinetic energies and velocities here. Could scale the velocities later, but we need them scaled in order to produce the correct outputs, so we'll scale them here. */ @@ -1581,8 +1643,7 @@ init_npt_vars(const t_inputrec* ir, t_state* state, t_extmass* MassQ, gmx_bool b if (EI_VV(ir->eI) && (ir->epc == epcMTTK) && (ir->etc != etcNOSEHOOVER)) { - gmx_fatal(FARGS, - "Cannot do MTTK pressure coupling without Nose-Hoover temperature control"); + gmx_fatal(FARGS, "Cannot do MTTK pressure coupling without Nose-Hoover temperature control"); } init_npt_masses(ir, state, MassQ, TRUE); @@ -1827,8 +1888,12 @@ static real energyPressureMTTK(const t_inputrec* ir, const t_state* state, const } if (debug) { - fprintf(debug, "P-T-group: %10d Chain %4d ThermV: %15.8f ThermX: %15.8f", i, j, - state->nhpres_vxi[i * nh + j], state->nhpres_xi[i * nh + j]); + fprintf(debug, + "P-T-group: %10d Chain %4d ThermV: %15.8f ThermX: %15.8f", + i, + j, + state->nhpres_vxi[i * nh + j], + state->nhpres_xi[i * nh + j]); } } } @@ -2049,8 +2114,13 @@ void vrescale_tcoupl(const t_inputrec* ir, int64_t step, gmx_ekindata_t* ekind, if (debug) { - fprintf(debug, "TC: group %d: Ekr %g, Ek %g, Ek_new %g, Lambda: %g\n", i, Ek_ref, - Ek, Ek_new, ekind->tcstat[i].lambda); + fprintf(debug, + "TC: group %d: Ekr %g, Ek %g, Ek_new %g, Lambda: %g\n", + i, + Ek_ref, + Ek, + Ek_new, + ekind->tcstat[i].lambda); } } else @@ -2166,8 +2236,11 @@ void update_annealing_target_temp(t_inputrec* ir, real t, gmx::Update* upd) break; case eannSINGLE: thist = t; break; default: - gmx_fatal(FARGS, "Death horror in update_annealing_target_temp (i=%d/%d npoints=%d)", - i, ir->opts.ngtc, npoints); + gmx_fatal(FARGS, + "Death horror in update_annealing_target_temp (i=%d/%d npoints=%d)", + i, + ir->opts.ngtc, + npoints); } /* We are doing annealing for this group if we got here, * and we have the (relative) time as thist. diff --git a/src/gromacs/mdlib/dispersioncorrection.cpp b/src/gromacs/mdlib/dispersioncorrection.cpp index b4871765ce..3557950ddb 100644 --- a/src/gromacs/mdlib/dispersioncorrection.cpp +++ b/src/gromacs/mdlib/dispersioncorrection.cpp @@ -504,8 +504,7 @@ void DispersionCorrection::setInteractionParameters(InteractionParams* i } else { - gmx_fatal(FARGS, "Dispersion correction is not implemented for vdw-type = %s", - evdw_names[ic.vdwtype]); + gmx_fatal(FARGS, "Dispersion correction is not implemented for vdw-type = %s", evdw_names[ic.vdwtype]); } iParams->enerdiffsix_ = energy.dispersion; diff --git a/src/gromacs/mdlib/ebin.cpp b/src/gromacs/mdlib/ebin.cpp index 6c830526be..a9f80a1c57 100644 --- a/src/gromacs/mdlib/ebin.cpp +++ b/src/gromacs/mdlib/ebin.cpp @@ -147,8 +147,13 @@ void add_ebin(t_ebin* eb, int entryIndex, int nener, const real ener[], gmx_bool if ((entryIndex + nener > eb->nener) || (entryIndex < 0)) { - gmx_fatal(FARGS, "%s-%d: Energies out of range: entryIndex=%d nener=%d maxener=%d", - __FILE__, __LINE__, entryIndex, nener, eb->nener); + gmx_fatal(FARGS, + "%s-%d: Energies out of range: entryIndex=%d nener=%d maxener=%d", + __FILE__, + __LINE__, + entryIndex, + nener, + eb->nener); } eg = &(eb->e[entryIndex]); @@ -205,8 +210,10 @@ void add_ebin_indexed(t_ebin* eb, GMX_ASSERT(shouldUse.size() == ener.size(), "View sizes must match"); GMX_ASSERT(entryIndex + std::count(shouldUse.begin(), shouldUse.end(), true) <= eb->nener, - gmx::formatString("Energies out of range: entryIndex=%d nener=%td maxener=%d", entryIndex, - std::count(shouldUse.begin(), shouldUse.end(), true), eb->nener) + gmx::formatString("Energies out of range: entryIndex=%d nener=%td maxener=%d", + entryIndex, + std::count(shouldUse.begin(), shouldUse.end(), true), + eb->nener) .c_str()); GMX_ASSERT(entryIndex >= 0, "Must have non-negative entry"); diff --git a/src/gromacs/mdlib/enerdata_utils.cpp b/src/gromacs/mdlib/enerdata_utils.cpp index 8f7cf633a9..a546dc4125 100644 --- a/src/gromacs/mdlib/enerdata_utils.cpp +++ b/src/gromacs/mdlib/enerdata_utils.cpp @@ -150,8 +150,13 @@ static void set_dvdl_output(gmx_enerdata_t* enerd, const t_lambda& fepvals) enerd->term[index] = enerd->dvdl_lin[i] + enerd->dvdl_nonlin[i]; if (debug) { - fprintf(debug, "dvdl-%s[%2d]: %f: non-linear %f + linear %f\n", efpt_names[i], i, - enerd->term[index], enerd->dvdl_nonlin[i], enerd->dvdl_lin[i]); + fprintf(debug, + "dvdl-%s[%2d]: %f: non-linear %f + linear %f\n", + efpt_names[i], + i, + enerd->term[index], + enerd->dvdl_nonlin[i], + enerd->dvdl_lin[i]); } } else @@ -159,8 +164,13 @@ static void set_dvdl_output(gmx_enerdata_t* enerd, const t_lambda& fepvals) enerd->term[F_DVDL] += enerd->dvdl_lin[i] + enerd->dvdl_nonlin[i]; if (debug) { - fprintf(debug, "dvd-%sl[%2d]: %f: non-linear %f + linear %f\n", efpt_names[0], i, - enerd->term[F_DVDL], enerd->dvdl_nonlin[i], enerd->dvdl_lin[i]); + fprintf(debug, + "dvd-%sl[%2d]: %f: non-linear %f + linear %f\n", + efpt_names[0], + i, + enerd->term[F_DVDL], + enerd->dvdl_nonlin[i], + enerd->dvdl_lin[i]); } } } @@ -286,8 +296,8 @@ void accumulateKineticLambdaComponents(gmx_enerdata_t* enerd, enerd->term[F_DVDL] += enerd->term[F_DVDL_CONSTR]; } - enerd->foreignLambdaTerms.finalizeKineticContributions(enerd->term, enerd->dvdl_lin[efptMASS], - lambda, fepvals); + enerd->foreignLambdaTerms.finalizeKineticContributions( + enerd->term, enerd->dvdl_lin[efptMASS], lambda, fepvals); /* The constrain contribution is now included in other terms, so clear it */ enerd->term[F_DVDL_CONSTR] = 0; diff --git a/src/gromacs/mdlib/energydrifttracker.cpp b/src/gromacs/mdlib/energydrifttracker.cpp index 1d5f2b13dd..ddbd078fe2 100644 --- a/src/gromacs/mdlib/energydrifttracker.cpp +++ b/src/gromacs/mdlib/energydrifttracker.cpp @@ -87,14 +87,18 @@ std::string EnergyDriftTracker::energyDriftString(const std::string& partName) c if (timeInterval() > 0) { mesg = formatString("Energy conservation over %s of length %g ns, time %g to %g ns\n", - partName.c_str(), timeInterval(), firstTime_, lastTime_); + partName.c_str(), + timeInterval(), + firstTime_, + lastTime_); mesg += formatString(" Conserved energy drift: %.2e kJ/mol/ps per atom\n", energyDrift()); } else { mesg = formatString( "Time interval for measuring conserved energy has length 0, time %g to %g\n", - firstTime_, lastTime_); + firstTime_, + lastTime_); } return mesg; diff --git a/src/gromacs/mdlib/energyoutput.cpp b/src/gromacs/mdlib/energyoutput.cpp index 0b72fc4e0c..daa1da99f8 100644 --- a/src/gromacs/mdlib/energyoutput.cpp +++ b/src/gromacs/mdlib/energyoutput.cpp @@ -287,8 +287,10 @@ EnergyOutput::EnergyOutput(ener_file* fp_ene, } if (bDynBox_) { - ib_ = get_ebin_space(ebin_, bTricl_ ? tricl_boxs_nm.size() : boxs_nm.size(), - bTricl_ ? tricl_boxs_nm.data() : boxs_nm.data(), unit_length); + ib_ = get_ebin_space(ebin_, + bTricl_ ? tricl_boxs_nm.size() : boxs_nm.size(), + bTricl_ ? tricl_boxs_nm.data() : boxs_nm.data(), + unit_length); ivol_ = get_ebin_space(ebin_, 1, vol_nm, unit_volume); idens_ = get_ebin_space(ebin_, 1, dens_nm, unit_density_SI); if (bDiagPres_) @@ -371,7 +373,10 @@ EnergyOutput::EnergyOutput(ener_file* fp_ene, { if (bEInd_[k]) { - sprintf(gnm[kk], "%s:%s-%s", egrp_nm[k], *(groups->groupNames[ni]), + sprintf(gnm[kk], + "%s:%s-%s", + egrp_nm[k], + *(groups->groupNames[ni]), *(groups->groupNames[nj])); kk++; } @@ -693,8 +698,8 @@ FILE* open_dhdl(const char* filename, const t_inputrec* ir, const gmx_output_env { title = gmx::formatString("%s and %s", dhdl, deltag); label_x = gmx::formatString("Time (ps)"); - label_y = gmx::formatString("%s and %s (%s %s)", dhdl, deltag, unit_energy, - "[\\8l\\4]\\S-1\\N"); + label_y = gmx::formatString( + "%s and %s (%s %s)", dhdl, deltag, unit_energy, "[\\8l\\4]\\S-1\\N"); } fp = gmx_fio_fopen(filename, "w+"); xvgr_header(fp, title.c_str(), label_x, label_y, exvggtXNY, oenv); @@ -715,8 +720,8 @@ FILE* open_dhdl(const char* filename, const t_inputrec* ir, const gmx_output_env { print_lambda_vector(fep, fep->init_fep_state, true, false, lambda_vec_str); print_lambda_vector(fep, fep->init_fep_state, true, true, lambda_name_str); - buf += gmx::formatString("%s %d: %s = %s", lambdastate, fep->init_fep_state, - lambda_name_str, lambda_vec_str); + buf += gmx::formatString( + "%s %d: %s = %s", lambdastate, fep->init_fep_state, lambda_name_str, lambda_vec_str); } } xvgr_subtitle(fp, buf.c_str(), oenv); @@ -1146,8 +1151,8 @@ void EnergyOutput::addDataAtEnergyStep(bool bDoDHDL, } store_energy = enerd->term[F_ETOT]; /* store_dh is dE */ - mde_delta_h_coll_add_dh(dhc_, static_cast(fep_state), store_energy, pv, - store_dhdl, dE_ + fep->lambda_start_n, time); + mde_delta_h_coll_add_dh( + dhc_, static_cast(fep_state), store_energy, pv, store_dhdl, dE_ + fep->lambda_start_n, time); } } @@ -1170,7 +1175,10 @@ void EnergyOutput::printHeader(FILE* log, int64_t steps, double time) fprintf(log, " %12s %12s\n" " %12s %12.5f\n\n", - "Step", "Time", gmx_step_str(steps, buf), time); + "Step", + "Time", + gmx_step_str(steps, buf), + time); } void EnergyOutput::printStepToEnergyFile(ener_file* fp_ene, @@ -1322,7 +1330,8 @@ void EnergyOutput::printAnnealingTemperatures(FILE* log, const SimulationGroups* { if (opts->annealing[i] != eannNO) { - fprintf(log, "Current ref_t for group %s: %8.1f\n", + fprintf(log, + "Current ref_t for group %s: %8.1f\n", *(groups->groupNames[groups->groups[SimulationAtomGroupType::TemperatureCoupling][i]]), opts->ref_t[i]); } @@ -1351,8 +1360,10 @@ void EnergyOutput::printAverages(FILE* log, const SimulationGroups* groups) fprintf(log, "\t<==== A V E R A G E S ====>\n"); fprintf(log, "\t<== ############### ======>\n\n"); - fprintf(log, "\tStatistics over %s steps using %s frames\n", - gmx_step_str(ebin_->nsteps_sim, buf1), gmx_step_str(ebin_->nsum_sim, buf2)); + fprintf(log, + "\tStatistics over %s steps using %s frames\n", + gmx_step_str(ebin_->nsteps_sim, buf1), + gmx_step_str(ebin_->nsum_sim, buf2)); fprintf(log, "\n"); fprintf(log, " Energies (%s)\n", unit_energy); @@ -1411,8 +1422,7 @@ void EnergyOutput::printAverages(FILE* log, const SimulationGroups* groups) int nj = groups->groups[SimulationAtomGroupType::EnergyOutput][j]; int padding = 14 - (strlen(*(groups->groupNames[ni])) + strlen(*(groups->groupNames[nj]))); - fprintf(log, "%*s%s-%s", padding, "", *(groups->groupNames[ni]), - *(groups->groupNames[nj])); + fprintf(log, "%*s%s-%s", padding, "", *(groups->groupNames[ni]), *(groups->groupNames[nj])); pr_ebin(log, ebin_, igrp_[n], nEc_, nEc_, eprAVER, false); n++; } @@ -1486,7 +1496,9 @@ void EnergyOutput::restoreFromEnergyHistory(const energyhistory_t& enerhist) gmx_fatal(FARGS, "Mismatch between number of energies in run input (%u) and checkpoint file (%zu " "or %zu).", - nener, enerhist.ener_sum.size(), enerhist.ener_sum_sim.size()); + nener, + enerhist.ener_sum.size(), + enerhist.ener_sum_sim.size()); } ebin_->nsteps = enerhist.nsteps; diff --git a/src/gromacs/mdlib/expanded.cpp b/src/gromacs/mdlib/expanded.cpp index 9e55df33da..15b8863745 100644 --- a/src/gromacs/mdlib/expanded.cpp +++ b/src/gromacs/mdlib/expanded.cpp @@ -398,8 +398,8 @@ static gmx_bool UpdateWeights(int nlim, /* then increment weights (uses count) */ pks = 0.0; - GenerateWeightedGibbsProbabilities(weighted_lamee, p_k, &pks, nlim, dfhist->wl_histo, - dfhist->wl_delta); + GenerateWeightedGibbsProbabilities( + weighted_lamee, p_k, &pks, nlim, dfhist->wl_histo, dfhist->wl_delta); for (i = 0; i < nlim; i++) { @@ -922,11 +922,16 @@ static int ChooseNewLambda(int nlim, "Something wrong in choosing new lambda state with a Gibbs move -- " "probably underflow in weight determination.\nDenominator is: " "%3d%17.10e\n i dE numerator weights\n", - 0, pks); + 0, + pks); for (ifep = minfep; ifep <= maxfep; ifep++) { - loc += sprintf(&errorstr[loc], "%3d %17.10e%17.10e%17.10e\n", ifep, - weighted_lamee[ifep], p_k[ifep], dfhist->sum_weights[ifep]); + loc += sprintf(&errorstr[loc], + "%3d %17.10e%17.10e%17.10e\n", + ifep, + weighted_lamee[ifep], + p_k[ifep], + dfhist->sum_weights[ifep]); } gmx_fatal(FARGS, "%s", errorstr); } @@ -1108,8 +1113,12 @@ void PrintFreeEnergyInfoToFile(FILE* outfile, } if (expand->elamstats == elamstatsMINVAR) { - fprintf(outfile, " %10.5f %10.5f %10.5f %10.5f", dfhist->sum_weights[ifep], - dfhist->sum_dg[ifep], dg, dv); + fprintf(outfile, + " %10.5f %10.5f %10.5f %10.5f", + dfhist->sum_weights[ifep], + dfhist->sum_dg[ifep], + dg, + dv); } else { @@ -1315,13 +1324,15 @@ int ExpandedEnsembleDynamics(FILE* log, { if (log) { - fprintf(log, "\nStep %" PRId64 ": Weights have equilibrated, using criteria: %s\n", - step, elmceq_names[expand->elmceq]); + fprintf(log, + "\nStep %" PRId64 ": Weights have equilibrated, using criteria: %s\n", + step, + elmceq_names[expand->elmceq]); } } - lamnew = ChooseNewLambda(nlim, expand, dfhist, fep_state, weighted_lamee, p_k, - ir->expandedvals->lmc_seed, step); + lamnew = ChooseNewLambda( + nlim, expand, dfhist, fep_state, weighted_lamee, p_k, ir->expandedvals->lmc_seed, step); /* if using simulated tempering, we need to adjust the temperatures */ if (ir->bSimTemp && (lamnew != fep_state)) /* only need to change the temperatures if we change the state */ { diff --git a/src/gromacs/mdlib/force.cpp b/src/gromacs/mdlib/force.cpp index 2bd8088a6a..6b9996def9 100644 --- a/src/gromacs/mdlib/force.cpp +++ b/src/gromacs/mdlib/force.cpp @@ -159,10 +159,22 @@ void calculateLongRangeNonbondeds(t_forcerec* fr, * the forces in the normal, single forceWithVirial->force_ array. */ const rvec* x = as_rvec_array(coordinates.data()); - ewald_LRcorrection(md->homenr, cr, nthreads, t, *fr, *ir, md->chargeA, - md->chargeB, (md->nChargePerturbed != 0), x, box, mu_tot, + ewald_LRcorrection(md->homenr, + cr, + nthreads, + t, + *fr, + *ir, + md->chargeA, + md->chargeB, + (md->nChargePerturbed != 0), + x, + box, + mu_tot, as_rvec_array(forceWithVirial->force_.data()), - &ewc_t.Vcorr_q, lambda[efptCOUL], &ewc_t.dvdl[efptCOUL]); + &ewc_t.Vcorr_q, + lambda[efptCOUL], + &ewc_t.dvdl[efptCOUL]); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR } @@ -197,13 +209,28 @@ void calculateLongRangeNonbondeds(t_forcerec* fr, status = gmx_pme_do( fr->pmedata, gmx::constArrayRefFromArray(coordinates.data(), md->homenr - fr->n_tpi), - forceWithVirial->force_, md->chargeA, md->chargeB, md->sqrt_c6A, - md->sqrt_c6B, md->sigmaA, md->sigmaB, box, cr, + forceWithVirial->force_, + md->chargeA, + md->chargeB, + md->sqrt_c6A, + md->sqrt_c6B, + md->sigmaA, + md->sigmaB, + box, + cr, DOMAINDECOMP(cr) ? dd_pme_maxshift_x(cr->dd) : 0, - DOMAINDECOMP(cr) ? dd_pme_maxshift_y(cr->dd) : 0, nrnb, wcycle, - ewaldOutput.vir_q, ewaldOutput.vir_lj, &Vlr_q, &Vlr_lj, - lambda[efptCOUL], lambda[efptVDW], &ewaldOutput.dvdl[efptCOUL], - &ewaldOutput.dvdl[efptVDW], stepWork); + DOMAINDECOMP(cr) ? dd_pme_maxshift_y(cr->dd) : 0, + nrnb, + wcycle, + ewaldOutput.vir_q, + ewaldOutput.vir_lj, + &Vlr_q, + &Vlr_lj, + lambda[efptCOUL], + lambda[efptVDW], + &ewaldOutput.dvdl[efptCOUL], + &ewaldOutput.dvdl[efptVDW], + stepWork); wallcycle_stop(wcycle, ewcPMEMESH); if (status != 0) { @@ -224,7 +251,8 @@ void calculateLongRangeNonbondeds(t_forcerec* fr, * with the PME grid potential of the other charges. */ gmx_pme_calc_energy( - fr->pmedata, coordinates.subArray(md->homenr - fr->n_tpi, fr->n_tpi), + fr->pmedata, + coordinates.subArray(md->homenr - fr->n_tpi, fr->n_tpi), gmx::arrayRefFromArray(md->chargeA + md->homenr - fr->n_tpi, fr->n_tpi), &Vlr_q); } @@ -234,9 +262,19 @@ void calculateLongRangeNonbondeds(t_forcerec* fr, if (fr->ic->eeltype == eelEWALD) { const rvec* x = as_rvec_array(coordinates.data()); - Vlr_q = do_ewald(ir, x, as_rvec_array(forceWithVirial->force_.data()), md->chargeA, - md->chargeB, box, cr, md->homenr, ewaldOutput.vir_q, fr->ic->ewaldcoeff_q, - lambda[efptCOUL], &ewaldOutput.dvdl[efptCOUL], fr->ewald_table); + Vlr_q = do_ewald(ir, + x, + as_rvec_array(forceWithVirial->force_.data()), + md->chargeA, + md->chargeB, + box, + cr, + md->homenr, + ewaldOutput.vir_q, + fr->ic->ewaldcoeff_q, + lambda[efptCOUL], + &ewaldOutput.dvdl[efptCOUL], + fr->ewald_table); } /* Note that with separate PME nodes we get the real energies later */ @@ -251,11 +289,17 @@ void calculateLongRangeNonbondeds(t_forcerec* fr, if (debug) { - fprintf(debug, "Vlr_q = %g, Vcorr_q = %g, Vlr_corr_q = %g\n", Vlr_q, - ewaldOutput.Vcorr_q, enerd->term[F_COUL_RECIP]); + fprintf(debug, + "Vlr_q = %g, Vcorr_q = %g, Vlr_corr_q = %g\n", + Vlr_q, + ewaldOutput.Vcorr_q, + enerd->term[F_COUL_RECIP]); pr_rvecs(debug, 0, "vir_el_recip after corr", ewaldOutput.vir_q, DIM); - fprintf(debug, "Vlr_lj: %g, Vcorr_lj = %g, Vlr_corr_lj = %g\n", Vlr_lj, - ewaldOutput.Vcorr_lj, enerd->term[F_LJ_RECIP]); + fprintf(debug, + "Vlr_lj: %g, Vcorr_lj = %g, Vlr_corr_lj = %g\n", + Vlr_lj, + ewaldOutput.Vcorr_lj, + enerd->term[F_LJ_RECIP]); pr_rvecs(debug, 0, "vir_lj_recip after corr", ewaldOutput.vir_lj, DIM); } } diff --git a/src/gromacs/mdlib/forcerec.cpp b/src/gromacs/mdlib/forcerec.cpp index ad0e645c4e..c743b77c91 100644 --- a/src/gromacs/mdlib/forcerec.cpp +++ b/src/gromacs/mdlib/forcerec.cpp @@ -287,7 +287,8 @@ static std::vector init_cginfo_mb(const gmx_mtop_t* mtop, const t_f int& atomInfo = cginfo[molculeOffsetInBlock + a]; /* Store the energy group in cginfo */ - int gid = getGroupType(mtop->groups, SimulationAtomGroupType::EnergyOutput, + int gid = getGroupType(mtop->groups, + SimulationAtomGroupType::EnergyOutput, a_offset + molculeOffsetInBlock + a); SET_CGINFO_GID(atomInfo, gid); @@ -597,8 +598,10 @@ static std::vector make_bonded_tables(FILE* "Tabulated interaction of type '%s%s%s' with index %d cannot be used " "because no table file whose name matched '%s' was passed via the " "gmx mdrun -tableb command-line option.", - interaction_function[ftype1].longname, isPlural ? "' or '" : "", - isPlural ? interaction_function[ftype2].longname : "", i, + interaction_function[ftype1].longname, + isPlural ? "' or '" : "", + isPlural ? interaction_function[ftype2].longname : "", + i, patternToFind.c_str()); } } @@ -659,7 +662,8 @@ static void initCoulombEwaldParameters(FILE* fp, { if (fp) { - fprintf(fp, "Using the Ewald3DC correction for systems with a slab geometry%s.\n", + fprintf(fp, + "Using the Ewald3DC correction for systems with a slab geometry%s.\n", systemHasNetCharge ? " and net charge" : ""); } please_cite(fp, "In-Chul99a"); @@ -767,12 +771,14 @@ void init_interaction_const_tables(FILE* fp, interaction_const_t* ic, const real { if (EEL_PME_EWALD(ic->eeltype) || EVDW_PME(ic->vdwtype)) { - init_ewald_f_table(*ic, tableExtensionLength, ic->coulombEwaldTables.get(), - ic->vdwEwaldTables.get()); + init_ewald_f_table( + *ic, tableExtensionLength, ic->coulombEwaldTables.get(), ic->vdwEwaldTables.get()); if (fp != nullptr) { - fprintf(fp, "Initialized non-bonded Ewald tables, spacing: %.2e size: %zu\n\n", - 1 / ic->coulombEwaldTables->scale, ic->coulombEwaldTables->tableF.size()); + fprintf(fp, + "Initialized non-bonded Ewald tables, spacing: %.2e size: %zu\n\n", + 1 / ic->coulombEwaldTables->scale, + ic->coulombEwaldTables->tableF.size()); } } } @@ -1207,8 +1213,11 @@ void init_forcerec(FILE* fp, } if (fp) { - fprintf(fp, "Using %s Lennard-Jones, switch between %g and %g nm\n", - (ic->eeltype == eelSWITCH) ? "switched" : "shifted", ic->rvdw_switch, ic->rvdw); + fprintf(fp, + "Using %s Lennard-Jones, switch between %g and %g nm\n", + (ic->eeltype == eelSWITCH) ? "switched" : "shifted", + ic->rvdw_switch, + ic->rvdw); } } @@ -1307,17 +1316,21 @@ void init_forcerec(FILE* fp, interactionSelection.set(static_cast(ListedForces::InteractionGroup::Rest)); isFirstLevel = false; } - fr->listedForces.emplace_back( - mtop->ffparams, mtop->groups.groups[SimulationAtomGroupType::EnergyOutput].size(), - gmx_omp_nthreads_get(emntBonded), interactionSelection, fp); + fr->listedForces.emplace_back(mtop->ffparams, + mtop->groups.groups[SimulationAtomGroupType::EnergyOutput].size(), + gmx_omp_nthreads_get(emntBonded), + interactionSelection, + fp); } } else { // Add one ListedForces object with all listed interactions - fr->listedForces.emplace_back( - mtop->ffparams, mtop->groups.groups[SimulationAtomGroupType::EnergyOutput].size(), - gmx_omp_nthreads_get(emntBonded), ListedForces::interactionSelectionAll(), fp); + fr->listedForces.emplace_back(mtop->ffparams, + mtop->groups.groups[SimulationAtomGroupType::EnergyOutput].size(), + gmx_omp_nthreads_get(emntBonded), + ListedForces::interactionSelectionAll(), + fp); } // QM/MM initialization if requested diff --git a/src/gromacs/mdlib/freeenergyparameters.cpp b/src/gromacs/mdlib/freeenergyparameters.cpp index ff47b98b1d..2ec8bd8acf 100644 --- a/src/gromacs/mdlib/freeenergyparameters.cpp +++ b/src/gromacs/mdlib/freeenergyparameters.cpp @@ -175,8 +175,8 @@ std::array currentLambdas(const int64_t step, const t_lambda& fepv std::fill(std::begin(lambdas), std::end(lambdas), fepvals.init_lambda); return lambdas; } - const double globalLambda = currentGlobalLambda(step, fepvals.delta_lambda, fepvals.init_fep_state, - fepvals.init_lambda, fepvals.n_lambda); + const double globalLambda = currentGlobalLambda( + step, fepvals.delta_lambda, fepvals.init_fep_state, fepvals.init_lambda, fepvals.n_lambda); return interpolatedLambdas(globalLambda, fepvals.all_lambda, fepvals.n_lambda); } diff --git a/src/gromacs/mdlib/gmx_omp_nthreads.cpp b/src/gromacs/mdlib/gmx_omp_nthreads.cpp index aa3327c822..d1979af8a3 100644 --- a/src/gromacs/mdlib/gmx_omp_nthreads.cpp +++ b/src/gromacs/mdlib/gmx_omp_nthreads.cpp @@ -127,7 +127,9 @@ static void pick_module_nthreads(const gmx::MDLogger& mdlog, int m, gmx_bool bSe if (!bOMP) { - gmx_warning("%s=%d is set, but %s is compiled without OpenMP!", modth_env_var[m], nth, + gmx_warning("%s=%d is set, but %s is compiled without OpenMP!", + modth_env_var[m], + nth, gmx::getProgramContext().displayName()); } @@ -138,7 +140,8 @@ static void pick_module_nthreads(const gmx::MDLogger& mdlog, int m, gmx_bool bSe gmx_warning( "%s=%d is set, the default number of threads also " "needs to be set with OMP_NUM_THREADS!", - modth_env_var[m], nth); + modth_env_var[m], + nth); } /* only babble if we are really overriding with a different value */ @@ -147,7 +150,9 @@ static void pick_module_nthreads(const gmx::MDLogger& mdlog, int m, gmx_bool bSe GMX_LOG(mdlog.warning) .asParagraph() .appendTextFormatted("%s=%d set, overriding the default number of %s threads", - modth_env_var[m], nth, mod_name[m]); + modth_env_var[m], + nth, + mod_name[m]); } } else @@ -184,7 +189,8 @@ void gmx_omp_nthreads_read_env(const gmx::MDLogger& mdlog, int* nthreads_omp) "Environment variable OMP_NUM_THREADS (%d) and the number of threads " "requested on the command line (%d) have different values. Either omit one, " "or set them both to the same value.", - nt_omp, *nthreads_omp); + nt_omp, + *nthreads_omp); } /* Setting the number of OpenMP threads. */ @@ -405,7 +411,9 @@ static void reportOpenmpSettings(const gmx::MDLogger& mdlog, const t_commrec* cr if (nth_max == nth_min) { GMX_LOG(mdlog.warning) - .appendTextFormatted("Using %d OpenMP thread%s %s", nth_min, nth_min > 1 ? "s" : "", + .appendTextFormatted("Using %d OpenMP thread%s %s", + nth_min, + nth_min > 1 ? "s" : "", cr->nnodes > 1 ? mpi_str : ""); } else @@ -418,14 +426,16 @@ static void reportOpenmpSettings(const gmx::MDLogger& mdlog, const t_commrec* cr if (nth_pme_max == nth_pme_min) { GMX_LOG(mdlog.warning) - .appendTextFormatted("Using %d OpenMP thread%s %s for PME", nth_pme_min, - nth_pme_min > 1 ? "s" : "", cr->nnodes > 1 ? mpi_str : ""); + .appendTextFormatted("Using %d OpenMP thread%s %s for PME", + nth_pme_min, + nth_pme_min > 1 ? "s" : "", + cr->nnodes > 1 ? mpi_str : ""); } else { GMX_LOG(mdlog.warning) - .appendTextFormatted("Using %d - %d OpenMP threads %s for PME", nth_pme_min, - nth_pme_max, mpi_str); + .appendTextFormatted( + "Using %d - %d OpenMP threads %s for PME", nth_pme_min, nth_pme_max, mpi_str); } } GMX_LOG(mdlog.warning); @@ -445,8 +455,15 @@ void gmx_omp_nthreads_init(const gmx::MDLogger& mdlog, bSepPME = (thisRankHasDuty(cr, DUTY_PP) != thisRankHasDuty(cr, DUTY_PME)); - manage_number_of_openmp_threads(mdlog, cr, bOMP, nthreads_hw_avail, omp_nthreads_req, - omp_nthreads_pme_req, bThisNodePMEOnly, numRanksOnThisNode, bSepPME); + manage_number_of_openmp_threads(mdlog, + cr, + bOMP, + nthreads_hw_avail, + omp_nthreads_req, + omp_nthreads_pme_req, + bThisNodePMEOnly, + numRanksOnThisNode, + bSepPME); #if GMX_THREAD_MPI /* Non-master threads have to wait for the OpenMP management to be * done, so that code elsewhere that uses OpenMP can be certain diff --git a/src/gromacs/mdlib/gpuforcereduction_impl.cu b/src/gromacs/mdlib/gpuforcereduction_impl.cu index afe7b03058..f95f6f1439 100644 --- a/src/gromacs/mdlib/gpuforcereduction_impl.cu +++ b/src/gromacs/mdlib/gpuforcereduction_impl.cu @@ -128,10 +128,15 @@ void GpuForceReduction::Impl::reinit(float3* baseForcePtr, cellInfo_.cell = cell.data(); wallcycle_start_nocount(wcycle_, ewcLAUNCH_GPU); - reallocateDeviceBuffer(&cellInfo_.d_cell, numAtoms_, &cellInfo_.cellSize, - &cellInfo_.cellSizeAlloc, deviceContext_); - copyToDeviceBuffer(&cellInfo_.d_cell, &(cellInfo_.cell[atomStart]), 0, numAtoms_, deviceStream_, - GpuApiCallBehavior::Async, nullptr); + reallocateDeviceBuffer( + &cellInfo_.d_cell, numAtoms_, &cellInfo_.cellSize, &cellInfo_.cellSizeAlloc, deviceContext_); + copyToDeviceBuffer(&cellInfo_.d_cell, + &(cellInfo_.cell[atomStart]), + 0, + numAtoms_, + deviceStream_, + GpuApiCallBehavior::Async, + nullptr); wallcycle_stop(wcycle_, ewcLAUNCH_GPU); dependencyList_.clear(); @@ -189,8 +194,8 @@ void GpuForceReduction::Impl::execute() ? (accumulate_ ? reduceKernel : reduceKernel) : (accumulate_ ? reduceKernel : reduceKernel); - const auto kernelArgs = prepareGpuKernelArguments(kernelFn, config, &d_nbnxmForce, &d_rvecForceToAdd, - &baseForce_, &cellInfo_.d_cell, &numAtoms_); + const auto kernelArgs = prepareGpuKernelArguments( + kernelFn, config, &d_nbnxmForce, &d_rvecForceToAdd, &baseForce_, &cellInfo_.d_cell, &numAtoms_); launchGpuKernel(kernelFn, config, deviceStream_, nullptr, "Force Reduction", kernelArgs); diff --git a/src/gromacs/mdlib/leapfrog_gpu.cu b/src/gromacs/mdlib/leapfrog_gpu.cu index a5ac290f6f..d47619109e 100644 --- a/src/gromacs/mdlib/leapfrog_gpu.cu +++ b/src/gromacs/mdlib/leapfrog_gpu.cu @@ -263,8 +263,13 @@ void LeapFrogGpu::integrate(const DeviceBuffer d_x, { h_lambdas_[i] = tcstat[i].lambda; } - copyToDeviceBuffer(&d_lambdas_, h_lambdas_.data(), 0, numTempScaleValues_, - deviceStream_, GpuApiCallBehavior::Async, nullptr); + copyToDeviceBuffer(&d_lambdas_, + h_lambdas_.data(), + 0, + numTempScaleValues_, + deviceStream_, + GpuApiCallBehavior::Async, + nullptr); } VelocityScalingType prVelocityScalingType = VelocityScalingType::None; if (doParrinelloRahman) @@ -285,9 +290,18 @@ void LeapFrogGpu::integrate(const DeviceBuffer d_x, kernelPtr = selectLeapFrogKernelPtr(doTemperatureScaling, numTempScaleValues_, prVelocityScalingType); } - const auto kernelArgs = prepareGpuKernelArguments( - kernelPtr, kernelLaunchConfig_, &numAtoms_, &d_x, &d_xp, &d_v, &d_f, &d_inverseMasses_, - &dt, &d_lambdas_, &d_tempScaleGroups_, &prVelocityScalingMatrixDiagonal_); + const auto kernelArgs = prepareGpuKernelArguments(kernelPtr, + kernelLaunchConfig_, + &numAtoms_, + &d_x, + &d_xp, + &d_v, + &d_f, + &d_inverseMasses_, + &dt, + &d_lambdas_, + &d_tempScaleGroups_, + &prVelocityScalingMatrixDiagonal_); launchGpuKernel(kernelPtr, kernelLaunchConfig_, deviceStream_, nullptr, "leapfrog_kernel", kernelArgs); return; @@ -322,26 +336,26 @@ void LeapFrogGpu::set(const int numAtoms, numTempScaleValues_ = numTempScaleValues; - reallocateDeviceBuffer(&d_inverseMasses_, numAtoms_, &numInverseMasses_, - &numInverseMassesAlloc_, deviceContext_); - copyToDeviceBuffer(&d_inverseMasses_, (float*)inverseMasses, 0, numAtoms_, deviceStream_, - GpuApiCallBehavior::Sync, nullptr); + reallocateDeviceBuffer( + &d_inverseMasses_, numAtoms_, &numInverseMasses_, &numInverseMassesAlloc_, deviceContext_); + copyToDeviceBuffer( + &d_inverseMasses_, (float*)inverseMasses, 0, numAtoms_, deviceStream_, GpuApiCallBehavior::Sync, nullptr); // Temperature scale group map only used if there are more then one group if (numTempScaleValues > 1) { - reallocateDeviceBuffer(&d_tempScaleGroups_, numAtoms_, &numTempScaleGroups_, - &numTempScaleGroupsAlloc_, deviceContext_); - copyToDeviceBuffer(&d_tempScaleGroups_, tempScaleGroups, 0, numAtoms_, deviceStream_, - GpuApiCallBehavior::Sync, nullptr); + reallocateDeviceBuffer( + &d_tempScaleGroups_, numAtoms_, &numTempScaleGroups_, &numTempScaleGroupsAlloc_, deviceContext_); + copyToDeviceBuffer( + &d_tempScaleGroups_, tempScaleGroups, 0, numAtoms_, deviceStream_, GpuApiCallBehavior::Sync, nullptr); } // If the temperature coupling is enabled, we need to make space for scaling factors if (numTempScaleValues_ > 0) { h_lambdas_.resize(numTempScaleValues); - reallocateDeviceBuffer(&d_lambdas_, numTempScaleValues_, &numLambdas_, &numLambdasAlloc_, - deviceContext_); + reallocateDeviceBuffer( + &d_lambdas_, numTempScaleValues_, &numLambdas_, &numLambdasAlloc_, deviceContext_); } } diff --git a/src/gromacs/mdlib/leapfrog_gpu_sycl.cpp b/src/gromacs/mdlib/leapfrog_gpu_sycl.cpp index 61484f8968..d82c9c12eb 100644 --- a/src/gromacs/mdlib/leapfrog_gpu_sycl.cpp +++ b/src/gromacs/mdlib/leapfrog_gpu_sycl.cpp @@ -212,7 +212,8 @@ static inline cl::sycl::event launchLeapFrogKernel(NumTempScaleValues tempScali [&](auto tempScalingType_, auto prScalingType_) { return launchLeapFrogKernel(std::forward(args)...); }, - tempScalingType, prVelocityScalingType); + tempScalingType, + prVelocityScalingType); } void LeapFrogGpu::integrate(DeviceBuffer d_x, @@ -251,14 +252,24 @@ void LeapFrogGpu::integrate(DeviceBuffer d_x, && prVelocityScalingMatrix[XX][ZZ] == 0 && prVelocityScalingMatrix[YY][ZZ] == 0, "Fully anisotropic Parrinello-Rahman pressure coupling is not yet supported " "in GPU version of Leap-Frog integrator."); - prVelocityScalingMatrixDiagonal_ = - dtPressureCouple - * float3{ prVelocityScalingMatrix[XX][XX], prVelocityScalingMatrix[YY][YY], - prVelocityScalingMatrix[ZZ][ZZ] }; + prVelocityScalingMatrixDiagonal_ = dtPressureCouple + * float3{ prVelocityScalingMatrix[XX][XX], + prVelocityScalingMatrix[YY][YY], + prVelocityScalingMatrix[ZZ][ZZ] }; } - launchLeapFrogKernel(tempVelocityScalingType, prVelocityScalingType, deviceStream_, numAtoms_, - d_x, d_xp, d_v, d_f, d_inverseMasses_, dt, d_lambdas_, d_tempScaleGroups_, + launchLeapFrogKernel(tempVelocityScalingType, + prVelocityScalingType, + deviceStream_, + numAtoms_, + d_x, + d_xp, + d_v, + d_f, + d_inverseMasses_, + dt, + d_lambdas_, + d_tempScaleGroups_, prVelocityScalingMatrixDiagonal_); } @@ -282,25 +293,25 @@ void LeapFrogGpu::set(const int numAtoms, numAtoms_ = numAtoms; numTempScaleValues_ = numTempScaleValues; - reallocateDeviceBuffer(&d_inverseMasses_, numAtoms_, &numInverseMasses_, - &numInverseMassesAlloc_, deviceContext_); - copyToDeviceBuffer(&d_inverseMasses_, inverseMasses, 0, numAtoms_, deviceStream_, - GpuApiCallBehavior::Sync, nullptr); + reallocateDeviceBuffer( + &d_inverseMasses_, numAtoms_, &numInverseMasses_, &numInverseMassesAlloc_, deviceContext_); + copyToDeviceBuffer( + &d_inverseMasses_, inverseMasses, 0, numAtoms_, deviceStream_, GpuApiCallBehavior::Sync, nullptr); // Temperature scale group map only used if there are more then one group if (numTempScaleValues_ > 1) { - reallocateDeviceBuffer(&d_tempScaleGroups_, numAtoms_, &numTempScaleGroups_, - &numTempScaleGroupsAlloc_, deviceContext_); - copyToDeviceBuffer(&d_tempScaleGroups_, tempScaleGroups, 0, numAtoms_, deviceStream_, - GpuApiCallBehavior::Sync, nullptr); + reallocateDeviceBuffer( + &d_tempScaleGroups_, numAtoms_, &numTempScaleGroups_, &numTempScaleGroupsAlloc_, deviceContext_); + copyToDeviceBuffer( + &d_tempScaleGroups_, tempScaleGroups, 0, numAtoms_, deviceStream_, GpuApiCallBehavior::Sync, nullptr); } // If the temperature coupling is enabled, we need to make space for scaling factors if (numTempScaleValues_ > 0) { - reallocateDeviceBuffer(&d_lambdas_, numTempScaleValues_, &numLambdas_, &numLambdasAlloc_, - deviceContext_); + reallocateDeviceBuffer( + &d_lambdas_, numTempScaleValues_, &numLambdas_, &numLambdasAlloc_, deviceContext_); } } diff --git a/src/gromacs/mdlib/lincs.cpp b/src/gromacs/mdlib/lincs.cpp index 2f8119da4a..582676445a 100644 --- a/src/gromacs/mdlib/lincs.cpp +++ b/src/gromacs/mdlib/lincs.cpp @@ -623,8 +623,8 @@ static void do_lincsp(ArrayRefWithPadding xPadded, /* Compute normalized x i-j vectors, store in r. * Compute the inner product of r and xp i-j and store in rhs1. */ - calc_dr_x_f_simd(b0, b1, atoms, x, f, blc.data(), pbc_simd, as_rvec_array(r.data()), - rhs1.data(), sol.data()); + calc_dr_x_f_simd( + b0, b1, atoms, x, f, blc.data(), pbc_simd, as_rvec_array(r.data()), rhs1.data(), sol.data()); #else // GMX_SIMD_HAVE_REAL @@ -708,7 +708,12 @@ static void do_lincsp(ArrayRefWithPadding xPadded, /* When constraining forces, we should not use mass weighting, * so we pass invmass=NULL, which results in the use of 1 for all atoms. */ - lincs_update_atoms(lincsd, th, 1.0, sol, r, (econq != ConstraintVariable::Force) ? invmass : nullptr, + lincs_update_atoms(lincsd, + th, + 1.0, + sol, + r, + (econq != ConstraintVariable::Force) ? invmass : nullptr, as_rvec_array(fp.data())); if (bCalcDHDL) @@ -999,8 +1004,8 @@ static void do_lincs(ArrayRefWithPadding xPadded, /* Compute normalized x i-j vectors, store in r. * Compute the inner product of r and xp i-j and store in rhs1. */ - calc_dr_x_xp_simd(b0, b1, atoms, x, xp, bllen.data(), blc.data(), pbc_simd, - as_rvec_array(r.data()), rhs1.data(), sol.data()); + calc_dr_x_xp_simd( + b0, b1, atoms, x, xp, bllen.data(), blc.data(), pbc_simd, as_rvec_array(r.data()), rhs1.data(), sol.data()); #else // GMX_SIMD_HAVE_REAL @@ -1115,11 +1120,10 @@ static void do_lincs(ArrayRefWithPadding xPadded, } #if GMX_SIMD_HAVE_REAL - calc_dist_iter_simd(b0, b1, atoms, xp, bllen.data(), blc.data(), pbc_simd, wfac, - rhs1.data(), sol.data(), bWarn); + calc_dist_iter_simd( + b0, b1, atoms, xp, bllen.data(), blc.data(), pbc_simd, wfac, rhs1.data(), sol.data(), bWarn); #else - calc_dist_iter(b0, b1, atoms, xp, bllen.data(), blc.data(), pbc, wfac, rhs1.data(), - sol.data(), bWarn); + calc_dist_iter(b0, b1, atoms, xp, bllen.data(), blc.data(), pbc, wfac, rhs1.data(), sol.data(), bWarn); /* 20*ncons flops */ #endif // GMX_SIMD_HAVE_REAL @@ -1332,8 +1336,7 @@ static void set_lincs_matrix(Lincs* li, const real* invmass, real lambda) if (debug) { fprintf(debug, "The %d constraints participate in %d triangles\n", li->nc, li->ntriangle); - fprintf(debug, "There are %d constraint couplings, of which %d in triangles\n", li->ncc, - li->ncc_triangle); + fprintf(debug, "There are %d constraint couplings, of which %d in triangles\n", li->ncc, li->ncc_triangle); if (li->ntriangle > 0 && li->ntask > 1) { fprintf(debug, @@ -1502,8 +1505,7 @@ Lincs* init_lincs(FILE* fplog, li->bTaskDep = (li->ntask > 1 && bMoreThanTwoSeq); if (debug) { - fprintf(debug, "LINCS: using %d threads, tasks are %sdependent\n", li->ntask, - li->bTaskDep ? "" : "in"); + fprintf(debug, "LINCS: using %d threads, tasks are %sdependent\n", li->ntask, li->bTaskDep ? "" : "in"); } if (li->ntask == 1) { @@ -1539,7 +1541,8 @@ Lincs* init_lincs(FILE* fplog, "%d constraints are involved in constraint triangles,\n" "will apply an additional matrix expansion of order %d for couplings\n" "between constraints inside triangles\n", - li->ncg_triangle, li->nOrder); + li->ncg_triangle, + li->nOrder); } } @@ -2122,8 +2125,7 @@ void set_lincs(const InteractionDefinitions& idef, if (debug) { - fprintf(debug, "Number of constraints is %d, padded %d, couplings %d\n", li->nc_real, - li->nc, li->ncc); + fprintf(debug, "Number of constraints is %d, padded %d, couplings %d\n", li->nc_real, li->nc, li->ncc); } if (li->ntask > 1) @@ -2177,8 +2179,14 @@ static void lincs_warning(gmx_domdec_t* dd, real cosine = ::iprod(v0, v1) / (d0 * d1); if (cosine < wfac) { - fprintf(stderr, " %6d %6d %5.1f %8.4f %8.4f %8.4f\n", ddglatnr(dd, i), - ddglatnr(dd, j), RAD2DEG * std::acos(cosine), d0, d1, bllen[b]); + fprintf(stderr, + " %6d %6d %5.1f %8.4f %8.4f %8.4f\n", + ddglatnr(dd, i), + ddglatnr(dd, j), + RAD2DEG * std::acos(cosine), + d0, + d1, + bllen[b]); if (!std::isfinite(d1)) { gmx_fatal(FARGS, "Bond length not finite."); @@ -2352,7 +2360,8 @@ bool constrain_lincs(bool computeRmsd, { LincsDeviations deviations = makeLincsDeviations(*lincsd, xprime, pbc); fprintf(debug, " Rel. Constraint Deviation: RMS MAX between atoms\n"); - fprintf(debug, " Before LINCS %.6f %.6f %6d %6d\n", + fprintf(debug, + " Before LINCS %.6f %.6f %6d %6d\n", std::sqrt(deviations.sumSquaredDeviation / deviations.numConstraints), deviations.maxDeviation, ddglatnr(cr->dd, lincsd->atoms[deviations.indexOfMaxDeviation].index1), @@ -2374,8 +2383,20 @@ bool constrain_lincs(bool computeRmsd, clear_mat(lincsd->task[th].vir_r_m_dr); - do_lincs(xPadded, xprimePadded, box, pbc, lincsd, th, invmass, cr, bCalcDHDL, - ir.LincsWarnAngle, &bWarn, invdt, v, bCalcVir, + do_lincs(xPadded, + xprimePadded, + box, + pbc, + lincsd, + th, + invmass, + cr, + bCalcDHDL, + ir.LincsWarnAngle, + &bWarn, + invdt, + v, + bCalcVir, th == 0 ? vir_r_m_dr : lincsd->task[th].vir_r_m_dr); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR @@ -2399,7 +2420,8 @@ bool constrain_lincs(bool computeRmsd, } if (printDebugOutput) { - fprintf(debug, " After LINCS %.6f %.6f %6d %6d\n\n", + fprintf(debug, + " After LINCS %.6f %.6f %6d %6d\n\n", std::sqrt(deviations.sumSquaredDeviation / deviations.numConstraints), deviations.maxDeviation, ddglatnr(cr->dd, lincsd->atoms[deviations.indexOfMaxDeviation].index1), @@ -2420,14 +2442,16 @@ bool constrain_lincs(bool computeRmsd, ", time %g (ps) LINCS WARNING%s\n" "relative constraint deviation after LINCS:\n" "rms %.6f, max %.6f (between atoms %d and %d)\n", - step, ir.init_t + step * ir.delta_t, simMesg.c_str(), + step, + ir.init_t + step * ir.delta_t, + simMesg.c_str(), std::sqrt(deviations.sumSquaredDeviation / deviations.numConstraints), deviations.maxDeviation, ddglatnr(cr->dd, lincsd->atoms[deviations.indexOfMaxDeviation].index1), ddglatnr(cr->dd, lincsd->atoms[deviations.indexOfMaxDeviation].index2)); - lincs_warning(cr->dd, x, xprime, pbc, lincsd->nc, lincsd->atoms, lincsd->bllen, - ir.LincsWarnAngle, maxwarn, warncount); + lincs_warning( + cr->dd, x, xprime, pbc, lincsd->nc, lincsd->atoms, lincsd->bllen, ir.LincsWarnAngle, maxwarn, warncount); } bOK = (deviations.maxDeviation < 0.5); } @@ -2453,8 +2477,17 @@ bool constrain_lincs(bool computeRmsd, { int th = gmx_omp_get_thread_num(); - do_lincsp(xPadded, xprimePadded, min_proj, pbc, lincsd, th, invmass, econq, - bCalcDHDL, bCalcVir, th == 0 ? vir_r_m_dr : lincsd->task[th].vir_r_m_dr); + do_lincsp(xPadded, + xprimePadded, + min_proj, + pbc, + lincsd, + th, + invmass, + econq, + bCalcDHDL, + bCalcVir, + th == 0 ? vir_r_m_dr : lincsd->task[th].vir_r_m_dr); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR } diff --git a/src/gromacs/mdlib/lincs_gpu.cu b/src/gromacs/mdlib/lincs_gpu.cu index edffc43821..ac879bcfae 100644 --- a/src/gromacs/mdlib/lincs_gpu.cu +++ b/src/gromacs/mdlib/lincs_gpu.cu @@ -481,14 +481,23 @@ void LincsGpu::apply(const float3* d_x, const auto kernelArgs = prepareGpuKernelArguments(kernelPtr, config, &kernelParams_, &d_x, &d_xp, &d_v, &invdt); - launchGpuKernel(kernelPtr, config, deviceStream_, nullptr, - "lincs_kernel", kernelArgs); + launchGpuKernel(kernelPtr, + config, + deviceStream_, + nullptr, + "lincs_kernel", + kernelArgs); if (computeVirial) { // Copy LINCS virial data and add it to the common virial - copyFromDeviceBuffer(h_virialScaled_.data(), &kernelParams_.d_virialScaled, 0, 6, - deviceStream_, GpuApiCallBehavior::Sync, nullptr); + copyFromDeviceBuffer(h_virialScaled_.data(), + &kernelParams_.d_virialScaled, + 0, + 6, + deviceStream_, + GpuApiCallBehavior::Sync, + nullptr); // Mapping [XX, XY, XZ, YY, YZ, ZZ] internal format to a tensor object virialScaled[XX][XX] += h_virialScaled_[0]; @@ -627,7 +636,8 @@ inline int countCoupled(int a, numCoupledConstraints[c2] = 0; // To indicate we've been here counted += 1 + countCoupled(adjacentAtom.indexOfSecondConstrainedAtom_, - numCoupledConstraints, atomsAdjacencyList); + numCoupledConstraints, + atomsAdjacencyList); } } return counted; @@ -771,7 +781,8 @@ void LincsGpu::set(const InteractionDefinitions& idef, const int numAtoms, const "LINCS with constraints on all-bonds, which is not supported for large " "molecules. When compatible with the force field and integration settings, " "using constraints on H-bonds only.", - numCoupledConstraints.at(c), c_threadsPerBlock); + numCoupledConstraints.at(c), + c_threadsPerBlock); } if (currentMapIndex / c_threadsPerBlock != (currentMapIndex + numCoupledConstraints.at(c)) / c_threadsPerBlock) @@ -916,19 +927,24 @@ void LincsGpu::set(const InteractionDefinitions& idef, const int numAtoms, const numConstraintsThreadsAlloc_ = kernelParams_.numConstraintsThreads; - allocateDeviceBuffer(&kernelParams_.d_constraints, kernelParams_.numConstraintsThreads, - deviceContext_); + allocateDeviceBuffer( + &kernelParams_.d_constraints, kernelParams_.numConstraintsThreads, deviceContext_); allocateDeviceBuffer(&kernelParams_.d_constraintsTargetLengths, - kernelParams_.numConstraintsThreads, deviceContext_); + kernelParams_.numConstraintsThreads, + deviceContext_); allocateDeviceBuffer(&kernelParams_.d_coupledConstraintsCounts, - kernelParams_.numConstraintsThreads, deviceContext_); + kernelParams_.numConstraintsThreads, + deviceContext_); allocateDeviceBuffer(&kernelParams_.d_coupledConstraintsIndices, - maxCoupledConstraints * kernelParams_.numConstraintsThreads, deviceContext_); + maxCoupledConstraints * kernelParams_.numConstraintsThreads, + deviceContext_); allocateDeviceBuffer(&kernelParams_.d_massFactors, - maxCoupledConstraints * kernelParams_.numConstraintsThreads, deviceContext_); + maxCoupledConstraints * kernelParams_.numConstraintsThreads, + deviceContext_); allocateDeviceBuffer(&kernelParams_.d_matrixA, - maxCoupledConstraints * kernelParams_.numConstraintsThreads, deviceContext_); + maxCoupledConstraints * kernelParams_.numConstraintsThreads, + deviceContext_); } // (Re)allocate the memory, if the number of atoms has increased. @@ -943,25 +959,45 @@ void LincsGpu::set(const InteractionDefinitions& idef, const int numAtoms, const } // Copy data to GPU. - copyToDeviceBuffer(&kernelParams_.d_constraints, constraintsHost.data(), 0, - kernelParams_.numConstraintsThreads, deviceStream_, GpuApiCallBehavior::Sync, + copyToDeviceBuffer(&kernelParams_.d_constraints, + constraintsHost.data(), + 0, + kernelParams_.numConstraintsThreads, + deviceStream_, + GpuApiCallBehavior::Sync, nullptr); copyToDeviceBuffer(&kernelParams_.d_constraintsTargetLengths, - constraintsTargetLengthsHost.data(), 0, kernelParams_.numConstraintsThreads, - deviceStream_, GpuApiCallBehavior::Sync, nullptr); + constraintsTargetLengthsHost.data(), + 0, + kernelParams_.numConstraintsThreads, + deviceStream_, + GpuApiCallBehavior::Sync, + nullptr); copyToDeviceBuffer(&kernelParams_.d_coupledConstraintsCounts, - coupledConstraintsCountsHost.data(), 0, kernelParams_.numConstraintsThreads, - deviceStream_, GpuApiCallBehavior::Sync, nullptr); - copyToDeviceBuffer(&kernelParams_.d_coupledConstraintsIndices, coupledConstraintsIndicesHost.data(), - 0, maxCoupledConstraints * kernelParams_.numConstraintsThreads, - deviceStream_, GpuApiCallBehavior::Sync, nullptr); - copyToDeviceBuffer(&kernelParams_.d_massFactors, massFactorsHost.data(), 0, - maxCoupledConstraints * kernelParams_.numConstraintsThreads, deviceStream_, - GpuApiCallBehavior::Sync, nullptr); + coupledConstraintsCountsHost.data(), + 0, + kernelParams_.numConstraintsThreads, + deviceStream_, + GpuApiCallBehavior::Sync, + nullptr); + copyToDeviceBuffer(&kernelParams_.d_coupledConstraintsIndices, + coupledConstraintsIndicesHost.data(), + 0, + maxCoupledConstraints * kernelParams_.numConstraintsThreads, + deviceStream_, + GpuApiCallBehavior::Sync, + nullptr); + copyToDeviceBuffer(&kernelParams_.d_massFactors, + massFactorsHost.data(), + 0, + maxCoupledConstraints * kernelParams_.numConstraintsThreads, + deviceStream_, + GpuApiCallBehavior::Sync, + nullptr); GMX_RELEASE_ASSERT(invmass != nullptr, "Masses of atoms should be specified.\n"); - copyToDeviceBuffer(&kernelParams_.d_inverseMasses, invmass, 0, numAtoms, deviceStream_, - GpuApiCallBehavior::Sync, nullptr); + copyToDeviceBuffer( + &kernelParams_.d_inverseMasses, invmass, 0, numAtoms, deviceStream_, GpuApiCallBehavior::Sync, nullptr); } } // namespace gmx diff --git a/src/gromacs/mdlib/md_support.cpp b/src/gromacs/mdlib/md_support.cpp index cecbc3ca0c..cea710ba18 100644 --- a/src/gromacs/mdlib/md_support.cpp +++ b/src/gromacs/mdlib/md_support.cpp @@ -381,9 +381,20 @@ void compute_globals(gmx_global_stat* gstat, if (PAR(cr)) { wallcycle_start(wcycle, ewcMoveE); - global_stat(gstat, cr, enerd, force_vir, shake_vir, ir, ekind, constr, - bStopCM ? vcm : nullptr, signalBuffer.size(), signalBuffer.data(), - totalNumberOfBondedInteractions, *bSumEkinhOld, flags); + global_stat(gstat, + cr, + enerd, + force_vir, + shake_vir, + ir, + ekind, + constr, + bStopCM ? vcm : nullptr, + signalBuffer.size(), + signalBuffer.data(), + totalNumberOfBondedInteractions, + *bSumEkinhOld, + flags); wallcycle_stop(wcycle, ewcMoveE); } signalCoordinator->finalizeSignals(); @@ -485,7 +496,9 @@ int computeGlobalCommunicationPeriod(const gmx::MDLogger& mdlog, t_inputrec* ir, * here a leftover of the twin-range scheme? Can we remove * nstlist when we remove the group scheme? */ - nstglobalcomm = lcd4(ir->nstcalcenergy, ir->nstlist, ir->etc != etcNO ? ir->nsttcouple : 0, + nstglobalcomm = lcd4(ir->nstcalcenergy, + ir->nstlist, + ir->etc != etcNO ? ir->nsttcouple : 0, ir->epc != epcNO ? ir->nstpcouple : 0); } } @@ -589,8 +602,7 @@ void set_state_entries(t_state* state, const t_inputrec* ir, bool useModularSimu state->flags |= (1 << estTHERM_INT); } - init_gtc_state(state, state->ngtc, state->nnhpres, - ir->opts.nhchainlength); /* allocate the space for nose-hoover chains */ + init_gtc_state(state, state->ngtc, state->nnhpres, ir->opts.nhchainlength); /* allocate the space for nose-hoover chains */ init_ekinstate(&state->ekinstate, ir); if (ir->bExpanded) diff --git a/src/gromacs/mdlib/mdatoms.cpp b/src/gromacs/mdlib/mdatoms.cpp index 0d1abd8565..787a711f73 100644 --- a/src/gromacs/mdlib/mdatoms.cpp +++ b/src/gromacs/mdlib/mdatoms.cpp @@ -184,8 +184,10 @@ std::unique_ptr makeMDAtoms(FILE* fp, const gmx_mtop_t& mtop, const t_i if (ir.efep != efepNO && fp) { - fprintf(fp, "There are %d atoms and %d charges for free energy perturbation\n", - md->nPerturbed, md->nChargePerturbed); + fprintf(fp, + "There are %d atoms and %d charges for free energy perturbation\n", + md->nPerturbed, + md->nChargePerturbed); } md->havePartiallyFrozenAtoms = FALSE; @@ -404,8 +406,7 @@ void atoms2md(const gmx_mtop_t* mtop, else if (md->cFREEZE) { g = md->cFREEZE[i]; - GMX_ASSERT(opts->nFreeze != nullptr, - "Must have freeze groups to initialize masses"); + GMX_ASSERT(opts->nFreeze != nullptr, "Must have freeze groups to initialize masses"); if (opts->nFreeze[g][XX] && opts->nFreeze[g][YY] && opts->nFreeze[g][ZZ]) { /* Set the mass of completely frozen particles to ALMOST_ZERO diff --git a/src/gromacs/mdlib/mdebin_bar.cpp b/src/gromacs/mdlib/mdebin_bar.cpp index bed78d90c1..994ed39ccc 100644 --- a/src/gromacs/mdlib/mdebin_bar.cpp +++ b/src/gromacs/mdlib/mdebin_bar.cpp @@ -506,15 +506,21 @@ void mde_delta_h_coll_init(t_mde_delta_h_coll* dhc, const t_inputrec* ir) if (bExpanded) { dhc->dh_expanded = dhc->dh + n; - mde_delta_h_init(dhc->dh + n, ir->fepvals->dh_hist_size, ir->fepvals->dh_hist_spacing, - ndhmax, dhbtEXPANDED, 0, 0, nullptr); + mde_delta_h_init(dhc->dh + n, + ir->fepvals->dh_hist_size, + ir->fepvals->dh_hist_spacing, + ndhmax, + dhbtEXPANDED, + 0, + 0, + nullptr); n++; } if (bEnergy) { dhc->dh_energy = dhc->dh + n; - mde_delta_h_init(dhc->dh + n, ir->fepvals->dh_hist_size, ir->fepvals->dh_hist_spacing, - ndhmax, dhbtEN, 0, 0, nullptr); + mde_delta_h_init( + dhc->dh + n, ir->fepvals->dh_hist_size, ir->fepvals->dh_hist_spacing, ndhmax, dhbtEN, 0, 0, nullptr); n++; } /* add the dhdl's */ @@ -527,8 +533,14 @@ void mde_delta_h_coll_init(t_mde_delta_h_coll* dhc, const t_inputrec* ir) if (ir->fepvals->separate_dvdl[i]) { /* we give it init_lambda for compatibility */ - mde_delta_h_init(dhc->dh + n, ir->fepvals->dh_hist_size, ir->fepvals->dh_hist_spacing, - ndhmax, dhbtDHDL, n_lambda_components, 1, &(fep->init_lambda)); + mde_delta_h_init(dhc->dh + n, + ir->fepvals->dh_hist_size, + ir->fepvals->dh_hist_spacing, + ndhmax, + dhbtDHDL, + n_lambda_components, + 1, + &(fep->init_lambda)); n++; n_lambda_components++; } @@ -559,16 +571,22 @@ void mde_delta_h_coll_init(t_mde_delta_h_coll* dhc, const t_inputrec* ir) } } - mde_delta_h_init(dhc->dh + n, ir->fepvals->dh_hist_size, ir->fepvals->dh_hist_spacing, - ndhmax, dhbtDH, 0, n_lambda_components, lambda_vec); + mde_delta_h_init(dhc->dh + n, + ir->fepvals->dh_hist_size, + ir->fepvals->dh_hist_spacing, + ndhmax, + dhbtDH, + 0, + n_lambda_components, + lambda_vec); n++; } sfree(lambda_vec); if (bPV) { dhc->dh_pv = dhc->dh + n; - mde_delta_h_init(dhc->dh + n, ir->fepvals->dh_hist_size, ir->fepvals->dh_hist_spacing, - ndhmax, dhbtPV, 0, 0, nullptr); + mde_delta_h_init( + dhc->dh + n, ir->fepvals->dh_hist_size, ir->fepvals->dh_hist_spacing, ndhmax, dhbtPV, 0, 0, nullptr); n++; } } diff --git a/src/gromacs/mdlib/mdoutf.cpp b/src/gromacs/mdlib/mdoutf.cpp index 6ba96c8950..4325e3a9c0 100644 --- a/src/gromacs/mdlib/mdoutf.cpp +++ b/src/gromacs/mdlib/mdoutf.cpp @@ -394,8 +394,15 @@ static void write_checkpoint(const char* fn, copy_ivec(domdecCells, headerContents.dd_nc); } - write_checkpoint_data(fp, headerContents, bExpanded, elamstats, state, observablesHistory, - mdModulesNotifier, &outputfiles, modularSimulatorCheckpointData); + write_checkpoint_data(fp, + headerContents, + bExpanded, + elamstats, + state, + observablesHistory, + mdModulesNotifier, + &outputfiles, + modularSimulatorCheckpointData); /* we really, REALLY, want to make sure to physically write the checkpoint, and all the files it depends on, out to disk. Because we've @@ -495,12 +502,24 @@ void mdoutf_write_checkpoint(gmx_mdoutf_t of, * checkpoint files getting out of sync. */ ivec one_ivec = { 1, 1, 1 }; - write_checkpoint(of->fn_cpt, of->bKeepAndNumCPT, fplog, cr, + write_checkpoint(of->fn_cpt, + of->bKeepAndNumCPT, + fplog, + cr, DOMAINDECOMP(cr) ? cr->dd->numCells : one_ivec, - DOMAINDECOMP(cr) ? cr->dd->nnodes : cr->nnodes, of->eIntegrator, - of->simulation_part, of->bExpanded, of->elamstats, step, t, state_global, - observablesHistory, *(of->mdModulesNotifier), modularSimulatorCheckpointData, - of->simulationsShareState, of->mastersComm); + DOMAINDECOMP(cr) ? cr->dd->nnodes : cr->nnodes, + of->eIntegrator, + of->simulation_part, + of->bExpanded, + of->elamstats, + step, + t, + state_global, + observablesHistory, + *(of->mdModulesNotifier), + modularSimulatorCheckpointData, + of->simulationsShareState, + of->mastersComm); } void mdoutf_write_to_trajectory_files(FILE* fplog, @@ -529,21 +548,33 @@ void mdoutf_write_to_trajectory_files(FILE* fplog, if (mdof_flags & (MDOF_X | MDOF_X_COMPRESSED)) { auto globalXRef = MASTER(cr) ? state_global->x : gmx::ArrayRef(); - dd_collect_vec(cr->dd, state_local->ddp_count, state_local->ddp_count_cg_gl, - state_local->cg_gl, state_local->x, globalXRef); + dd_collect_vec(cr->dd, + state_local->ddp_count, + state_local->ddp_count_cg_gl, + state_local->cg_gl, + state_local->x, + globalXRef); } if (mdof_flags & MDOF_V) { auto globalVRef = MASTER(cr) ? state_global->v : gmx::ArrayRef(); - dd_collect_vec(cr->dd, state_local->ddp_count, state_local->ddp_count_cg_gl, - state_local->cg_gl, state_local->v, globalVRef); + dd_collect_vec(cr->dd, + state_local->ddp_count, + state_local->ddp_count_cg_gl, + state_local->cg_gl, + state_local->v, + globalVRef); } } f_global = of->f_global; if (mdof_flags & MDOF_F) { dd_collect_vec( - cr->dd, state_local->ddp_count, state_local->ddp_count_cg_gl, state_local->cg_gl, f_local, + cr->dd, + state_local->ddp_count, + state_local->ddp_count_cg_gl, + state_local->cg_gl, + f_local, gmx::arrayRefFromArray(reinterpret_cast(of->f_global), f_local.size())); } } @@ -559,8 +590,8 @@ void mdoutf_write_to_trajectory_files(FILE* fplog, { if (mdof_flags & MDOF_CPT) { - mdoutf_write_checkpoint(of, fplog, cr, step, t, state_global, observablesHistory, - modularSimulatorCheckpointData); + mdoutf_write_checkpoint( + of, fplog, cr, step, t, state_global, observablesHistory, modularSimulatorCheckpointData); } if (mdof_flags & (MDOF_X | MDOF_V | MDOF_F)) @@ -571,8 +602,8 @@ void mdoutf_write_to_trajectory_files(FILE* fplog, if (of->fp_trn) { - gmx_trr_write_frame(of->fp_trn, step, t, state_local->lambda[efptFEP], - state_local->box, natoms, x, v, f); + gmx_trr_write_frame( + of->fp_trn, step, t, state_local->lambda[efptFEP], state_local->box, natoms, x, v, f); if (gmx_fio_flush(of->fp_trn) != 0) { gmx_file("Cannot write trajectory; maybe you are out of disk space?"); @@ -583,15 +614,23 @@ void mdoutf_write_to_trajectory_files(FILE* fplog, velocities and forces to it. */ else if (of->tng) { - gmx_fwrite_tng(of->tng, FALSE, step, t, state_local->lambda[efptFEP], - state_local->box, natoms, x, v, f); + gmx_fwrite_tng( + of->tng, FALSE, step, t, state_local->lambda[efptFEP], state_local->box, natoms, x, v, f); } /* If only a TNG file is open for compressed coordinate output (no uncompressed coordinate output) also write forces and velocities to it. */ else if (of->tng_low_prec) { - gmx_fwrite_tng(of->tng_low_prec, FALSE, step, t, state_local->lambda[efptFEP], - state_local->box, natoms, x, v, f); + gmx_fwrite_tng(of->tng_low_prec, + FALSE, + step, + t, + state_local->lambda[efptFEP], + state_local->box, + natoms, + x, + v, + f); } } if (mdof_flags & MDOF_X_COMPRESSED) @@ -621,8 +660,7 @@ void mdoutf_write_to_trajectory_files(FILE* fplog, } } } - if (write_xtc(of->fp_xtc, of->natoms_x_compressed, step, t, state_local->box, xxtc, - of->x_compression_precision) + if (write_xtc(of->fp_xtc, of->natoms_x_compressed, step, t, state_local->box, xxtc, of->x_compression_precision) == 0) { gmx_fatal(FARGS, @@ -630,8 +668,16 @@ void mdoutf_write_to_trajectory_files(FILE* fplog, "simulation with major instabilities resulting in coordinates " "that are NaN or too large to be represented in the XTC format.\n"); } - gmx_fwrite_tng(of->tng_low_prec, TRUE, step, t, state_local->lambda[efptFEP], - state_local->box, of->natoms_x_compressed, xxtc, nullptr, nullptr); + gmx_fwrite_tng(of->tng_low_prec, + TRUE, + step, + t, + state_local->lambda[efptFEP], + state_local->box, + of->natoms_x_compressed, + xxtc, + nullptr, + nullptr); if (of->natoms_x_compressed != of->natoms_global) { sfree(xxtc); @@ -669,8 +715,7 @@ void mdoutf_write_to_trajectory_files(FILE* fplog, { lambda = state_local->lambda[efptFEP]; } - gmx_fwrite_tng(of->tng_low_prec, FALSE, step, t, lambda, box, natoms, nullptr, - nullptr, nullptr); + gmx_fwrite_tng(of->tng_low_prec, FALSE, step, t, lambda, box, natoms, nullptr, nullptr, nullptr); } } diff --git a/src/gromacs/mdlib/membed.cpp b/src/gromacs/mdlib/membed.cpp index a32c758b39..61e676c338 100644 --- a/src/gromacs/mdlib/membed.cpp +++ b/src/gromacs/mdlib/membed.cpp @@ -446,7 +446,8 @@ static int init_mem_at(mem_t* mem_p, gmx_mtop_t* mtop, rvec* r, matrix box, pos_ "so that one membrane is distributed over two periodic box images. Another " "possibility is that\n" "your water layer is not thick enough.\n", - zmax, zmin); + zmax, + zmin); } mem_p->zmin = zmin; mem_p->zmax = zmax; @@ -515,8 +516,12 @@ static void init_resize(t_block* ins_at, rvec* r_ins, pos_ins_t* pos_ins, mem_t* pos_ins->geom_cent[i][ZZ] = mem_p->zmed; } - fprintf(stderr, "Embedding piece %d with center of geometry: %f %f %f\n", i, - pos_ins->geom_cent[i][XX], pos_ins->geom_cent[i][YY], pos_ins->geom_cent[i][ZZ]); + fprintf(stderr, + "Embedding piece %d with center of geometry: %f %f %f\n", + i, + pos_ins->geom_cent[i][XX], + pos_ins->geom_cent[i][YY], + pos_ins->geom_cent[i][ZZ]); } fprintf(stderr, "\n"); } @@ -1066,8 +1071,18 @@ gmx_membed_t* init_membed(FILE* fplog, /* get input data out membed file */ try { - get_input(opt2fn("-membed", nfile, fnm), &xy_fac, &xy_max, &z_fac, &z_max, &it_xy, - &it_z, &probe_rad, &low_up_rm, &maxwarn, &pieces, &bALLOW_ASYMMETRY); + get_input(opt2fn("-membed", nfile, fnm), + &xy_fac, + &xy_max, + &z_fac, + &z_max, + &it_xy, + &it_z, + &probe_rad, + &low_up_rm, + &maxwarn, + &pieces, + &bALLOW_ASYMMETRY); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR @@ -1118,8 +1133,12 @@ gmx_membed_t* init_membed(FILE* fplog, ins_grp_id = std::distance(gnames.begin(), found); } fprintf(stderr, "\nSelect a group to embed %s into (e.g. the membrane):\n", ins); - get_index(&atoms, opt2fn_null("-mn", nfile, fnm), 1, &(mem_p->mem_at.nr), - &(mem_p->mem_at.index), &(mem_p->name)); + get_index(&atoms, + opt2fn_null("-mn", nfile, fnm), + 1, + &(mem_p->mem_at.nr), + &(mem_p->mem_at.index), + &(mem_p->name)); pos_ins->pieces = pieces; snew(pos_ins->nidx, pieces); @@ -1128,8 +1147,7 @@ gmx_membed_t* init_membed(FILE* fplog, if (pieces > 1) { fprintf(stderr, "\nSelect pieces to embed:\n"); - get_index(&atoms, opt2fn_null("-mn", nfile, fnm), pieces, pos_ins->nidx, - pos_ins->subindex, piecename); + get_index(&atoms, opt2fn_null("-mn", nfile, fnm), pieces, pos_ins->nidx, pos_ins->subindex, piecename); } else { @@ -1162,7 +1180,9 @@ gmx_membed_t* init_membed(FILE* fplog, fprintf(stderr, "\nWarning %d;\nThe number of steps used to grow the xy-coordinates of %s (%d)" " is probably too small.\nIncrease -nxy or.\n\n", - warn, ins, it_xy); + warn, + ins, + it_xy); } if ((it_z < min_it_z) && (z_fac < 0.99999999 || z_fac > 1.0000001)) @@ -1172,7 +1192,9 @@ gmx_membed_t* init_membed(FILE* fplog, "\nWarning %d;\nThe number of steps used to grow the z-coordinate of %s (%d)" " is probably too small.\nIncrease -nz or the maxwarn setting in the membed " "input file.\n\n", - warn, ins, it_z); + warn, + ins, + it_z); } if (it_xy + it_z > inputrec->nsteps) @@ -1284,7 +1306,8 @@ gmx_membed_t* init_membed(FILE* fplog, printf("The estimated area of the protein in the membrane is %.3f nm^2\n", prot_area); printf("\nThere are %d lipids in the membrane part that overlaps the protein.\n" "The area per lipid is %.4f nm^2.\n", - mem_p->nmol, mem_p->lip_area); + mem_p->nmol, + mem_p->lip_area); /* Maximum number of lipids to be removed*/ max_lip_rm = static_cast(2 * prot_area / mem_p->lip_area); @@ -1295,7 +1318,10 @@ gmx_membed_t* init_membed(FILE* fplog, "This resizing will be done with respect to the geometrical center of all protein " "atoms\n" "that span the membrane region, i.e. z between %.3f and %.3f\n\n", - xy_fac, z_fac, mem_p->zmin, mem_p->zmax); + xy_fac, + z_fac, + mem_p->zmin, + mem_p->zmax); /* resize the protein by xy and by z if necessary*/ snew(r_ins, ins_at->nr); @@ -1314,8 +1340,8 @@ gmx_membed_t* init_membed(FILE* fplog, set_pbc(pbc, inputrec->pbcType, state->box); snew(rm_p, 1); - lip_rm = gen_rm_list(rm_p, ins_at, rest_at, pbc, mtop, state->x.rvec_array(), mem_p, - pos_ins, probe_rad, low_up_rm, bALLOW_ASYMMETRY); + lip_rm = gen_rm_list( + rm_p, ins_at, rest_at, pbc, mtop, state->x.rvec_array(), mem_p, pos_ins, probe_rad, low_up_rm, bALLOW_ASYMMETRY); lip_rm -= low_up_rm; if (fplog) @@ -1361,7 +1387,8 @@ gmx_membed_t* init_membed(FILE* fplog, "while %d atoms are embedded. Make sure that the atoms to be embedded are not " "in the same" "molecule type as atoms that are not to be embedded.\n", - rm_bonded_at, ins_at->nr); + rm_bonded_at, + ins_at->nr); } if (warn > maxwarn) diff --git a/src/gromacs/mdlib/nsgrid.cpp b/src/gromacs/mdlib/nsgrid.cpp index e9f7f0c973..47736d18d1 100644 --- a/src/gromacs/mdlib/nsgrid.cpp +++ b/src/gromacs/mdlib/nsgrid.cpp @@ -215,8 +215,11 @@ static void set_grid_sizes(matrix box, { if (debug) { - fprintf(debug, "set_grid_sizes, i-zone bounds for dim %d: %6.3f %6.3f\n", i, - izones_x0[i], izones_x1[i]); + fprintf(debug, + "set_grid_sizes, i-zone bounds for dim %d: %6.3f %6.3f\n", + i, + izones_x0[i], + izones_x1[i]); } izones_size[i] = izones_x1[i] - izones_x0[i]; } @@ -345,14 +348,21 @@ static void set_grid_sizes(matrix box, } if (debug) { - fprintf(debug, "grid dim %d size %d x %f: %f - %f\n", i, grid->n[i], grid->cell_size[i], - grid->cell_offset[i], grid->cell_offset[i] + grid->n[i] * grid->cell_size[i]); + fprintf(debug, + "grid dim %d size %d x %f: %f - %f\n", + i, + grid->n[i], + grid->cell_size[i], + grid->cell_offset[i], + grid->cell_offset[i] + grid->n[i] * grid->cell_size[i]); } } if (debug) { - fprintf(debug, "CG ncg ideal %d, actual density %.1f\n", grid->ncg_ideal, + fprintf(debug, + "CG ncg ideal %d, actual density %.1f\n", + grid->ncg_ideal, grid_density * grid->cell_size[XX] * grid->cell_size[YY] * grid->cell_size[ZZ]); } } @@ -797,8 +807,7 @@ void fill_grid(gmx_domdec_zones_t* dd_zones, t_grid* grid, int ncg_tot, int cg0, } if (cg > grid->nr_alloc) { - fprintf(stderr, "WARNING: nra_alloc %d cg0 %d cg1 %d cg %d\n", grid->nr_alloc, - cg0, cg1, cg); + fprintf(stderr, "WARNING: nra_alloc %d cg0 %d cg1 %d cg %d\n", grid->nr_alloc, cg0, cg1, cg); } if (bUse) { diff --git a/src/gromacs/mdlib/perf_est.cpp b/src/gromacs/mdlib/perf_est.cpp index a0a288dbee..402d10a38f 100644 --- a/src/gromacs/mdlib/perf_est.cpp +++ b/src/gromacs/mdlib/perf_est.cpp @@ -336,8 +336,14 @@ static void pp_verlet_load(const gmx_mtop_t& mtop, if (debug) { - fprintf(debug, "nqlj %d nq %d nlj %d rlist %.3f r_eff %.3f pairs per atom %.1f\n", nqlj, nq, - nlj, ir.rlist, r_eff, nppa); + fprintf(debug, + "nqlj %d nq %d nlj %d rlist %.3f r_eff %.3f pairs per atom %.1f\n", + nqlj, + nq, + nlj, + ir.rlist, + r_eff, + nppa); } /* Determine the cost per pair interaction */ @@ -436,7 +442,12 @@ float pme_load_estimate(const gmx_mtop_t& mtop, const t_inputrec& ir, const matr "cost_spread %f\n" "cost_fft %f\n" "cost_solve %f\n", - cost_bond, cost_pp, cost_redist, cost_spread, cost_fft, cost_solve); + cost_bond, + cost_pp, + cost_redist, + cost_spread, + cost_fft, + cost_solve); fprintf(debug, "Estimate for relative PME load: %.3f\n", ratio); } diff --git a/src/gromacs/mdlib/resethandler.h b/src/gromacs/mdlib/resethandler.h index 2185c2b70a..d8a4a4ffe6 100644 --- a/src/gromacs/mdlib/resethandler.h +++ b/src/gromacs/mdlib/resethandler.h @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2018,2019, by the GROMACS development team, led by + * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -161,8 +161,7 @@ public: { if (simulationNeedsReset_) { - if (resetCountersImpl(step, step_rel, mdlog, fplog, cr, nbv, nrnb, pme, pme_loadbal, - wcycle, walltime_accounting)) + if (resetCountersImpl(step, step_rel, mdlog, fplog, cr, nbv, nrnb, pme, pme_loadbal, wcycle, walltime_accounting)) { // need to reset the counters only once simulationNeedsReset_ = false; diff --git a/src/gromacs/mdlib/rf_util.cpp b/src/gromacs/mdlib/rf_util.cpp index a113269537..fd02d2d752 100644 --- a/src/gromacs/mdlib/rf_util.cpp +++ b/src/gromacs/mdlib/rf_util.cpp @@ -69,7 +69,12 @@ void calc_rffac(FILE* fplog, real eps_r, real eps_rf, real Rc, real* krf, real* fprintf(fplog, "%s:\n" "epsRF = %g, rc = %g, krf = %g, crf = %g, epsfac = %g\n", - eel_names[eelRF], eps_rf, Rc, *krf, *crf, ONE_4PI_EPS0 / eps_r); + eel_names[eelRF], + eps_rf, + Rc, + *krf, + *crf, + ONE_4PI_EPS0 / eps_r); // Make sure we don't lose resolution in pow() by casting real arg to double real rmin = gmx::invcbrt(static_cast(*krf * 2.0)); fprintf(fplog, "The electrostatics potential has its minimum at r = %g\n", rmin); diff --git a/src/gromacs/mdlib/settle.cpp b/src/gromacs/mdlib/settle.cpp index 508bafc750..43e21eb486 100644 --- a/src/gromacs/mdlib/settle.cpp +++ b/src/gromacs/mdlib/settle.cpp @@ -146,8 +146,7 @@ settleParameters(const real mO, const real mH, const real invmO, const real invm if (debug) { fprintf(debug, "wh =%g, rc = %g, ra = %g\n", params.wh, params.rc, params.ra); - fprintf(debug, "rb = %g, irc2 = %g, dHH = %g, dOH = %g\n", params.rb, params.irc2, - params.dHH, params.dOH); + fprintf(debug, "rb = %g, irc2 = %g, dHH = %g, dOH = %g\n", params.rb, params.irc2, params.dHH, params.dOH); } return params; @@ -221,9 +220,12 @@ void SettleData::setConstraints(const InteractionList& il_settle, { int firstO = iatoms[1]; int firstH = iatoms[2]; - parametersMassWeighted_ = settleParameters( - masses[firstO], masses[firstH], inverseMasses[firstO], inverseMasses[firstH], - parametersAllMasses1_.dOH, parametersAllMasses1_.dHH); + parametersMassWeighted_ = settleParameters(masses[firstO], + masses[firstH], + inverseMasses[firstO], + inverseMasses[firstH], + parametersAllMasses1_.dOH, + parametersAllMasses1_.dHH); } const int paddedSize = ((nsettle + pack_size - 1) / pack_size) * pack_size; @@ -770,8 +772,7 @@ void csettle(const SettleData& settled, set_pbc_simd(pbc, pbcSimd); settleTemplateWrapper( - settled, nthread, thread, pbcSimd, xPtr, xprimePtr, invdt, vPtr, bCalcVirial, - vir_r_m_dr, bErrorHasOccurred); + settled, nthread, thread, pbcSimd, xPtr, xprimePtr, invdt, vPtr, bCalcVirial, vir_r_m_dr, bErrorHasOccurred); } else #endif @@ -790,9 +791,8 @@ void csettle(const SettleData& settled, pbcNonNull = &pbcNo; } - settleTemplateWrapper(settled, nthread, thread, pbcNonNull, - &xPtr[0], &xprimePtr[0], invdt, &vPtr[0], - bCalcVirial, vir_r_m_dr, bErrorHasOccurred); + settleTemplateWrapper( + settled, nthread, thread, pbcNonNull, &xPtr[0], &xprimePtr[0], invdt, &vPtr[0], bCalcVirial, vir_r_m_dr, bErrorHasOccurred); } } diff --git a/src/gromacs/mdlib/settle_gpu.cu b/src/gromacs/mdlib/settle_gpu.cu index c02f0d5884..eb4f7b066b 100644 --- a/src/gromacs/mdlib/settle_gpu.cu +++ b/src/gromacs/mdlib/settle_gpu.cu @@ -439,17 +439,20 @@ void SettleGpu::apply(const float3* d_x, config.sharedMemorySize = 0; } - const auto kernelArgs = prepareGpuKernelArguments(kernelPtr, config, &numSettles_, &d_atomIds_, - &settleParameters_, &d_x, &d_xp, &invdt, &d_v, - &d_virialScaled_, &pbcAiuc); + const auto kernelArgs = prepareGpuKernelArguments( + kernelPtr, config, &numSettles_, &d_atomIds_, &settleParameters_, &d_x, &d_xp, &invdt, &d_v, &d_virialScaled_, &pbcAiuc); - launchGpuKernel(kernelPtr, config, deviceStream_, nullptr, - "settle_kernel", kernelArgs); + launchGpuKernel(kernelPtr, + config, + deviceStream_, + nullptr, + "settle_kernel", + kernelArgs); if (computeVirial) { - copyFromDeviceBuffer(h_virialScaled_.data(), &d_virialScaled_, 0, 6, deviceStream_, - GpuApiCallBehavior::Sync, nullptr); + copyFromDeviceBuffer( + h_virialScaled_.data(), &d_virialScaled_, 0, 6, deviceStream_, GpuApiCallBehavior::Sync, nullptr); // Mapping [XX, XY, XZ, YY, YZ, ZZ] internal format to a tensor object virialScaled[XX][XX] += h_virialScaled_[0]; @@ -605,8 +608,8 @@ void SettleGpu::set(const InteractionDefinitions& idef) settler.z = iatoms[i * nral1 + 3]; // Second hydrogen index h_atomIds_.at(i) = settler; } - copyToDeviceBuffer(&d_atomIds_, h_atomIds_.data(), 0, numSettles_, deviceStream_, - GpuApiCallBehavior::Sync, nullptr); + copyToDeviceBuffer( + &d_atomIds_, h_atomIds_.data(), 0, numSettles_, deviceStream_, GpuApiCallBehavior::Sync, nullptr); } } // namespace gmx diff --git a/src/gromacs/mdlib/shake.cpp b/src/gromacs/mdlib/shake.cpp index ee5dee5f4f..e638fc993a 100644 --- a/src/gromacs/mdlib/shake.cpp +++ b/src/gromacs/mdlib/shake.cpp @@ -111,8 +111,13 @@ static void pr_sortblock(FILE* fp, const char* title, int nsb, t_sortblock sb[]) fprintf(fp, "%s\n", title); for (i = 0; (i < nsb); i++) { - fprintf(fp, "i: %5d, iatom: (%5d %5d %5d), blocknr: %5d\n", i, sb[i].iatom[0], - sb[i].iatom[1], sb[i].iatom[2], sb[i].blocknr); + fprintf(fp, + "i: %5d, iatom: (%5d %5d %5d), blocknr: %5d\n", + i, + sb[i].iatom[0], + sb[i].iatom[1], + sb[i].iatom[2], + sb[i].blocknr); } } @@ -502,14 +507,36 @@ static int vec_shakef(FILE* fplog, switch (econq) { case ConstraintVariable::Positions: - cshake(iatom, ncon, &nit, maxnit, constraint_distance_squared, prime, pbc, rij, - half_of_reduced_mass, omega, invmass, distance_squared_tolerance, - scaled_lagrange_multiplier, &error); + cshake(iatom, + ncon, + &nit, + maxnit, + constraint_distance_squared, + prime, + pbc, + rij, + half_of_reduced_mass, + omega, + invmass, + distance_squared_tolerance, + scaled_lagrange_multiplier, + &error); break; case ConstraintVariable::Velocities: - crattle(iatom, ncon, &nit, maxnit, constraint_distance_squared, prime, rij, - half_of_reduced_mass, omega, invmass, distance_squared_tolerance, - scaled_lagrange_multiplier, &error, invdt); + crattle(iatom, + ncon, + &nit, + maxnit, + constraint_distance_squared, + prime, + rij, + half_of_reduced_mass, + omega, + invmass, + distance_squared_tolerance, + scaled_lagrange_multiplier, + &error, + invdt); break; default: gmx_incons("Unknown constraint quantity for SHAKE"); } @@ -530,12 +557,16 @@ static int vec_shakef(FILE* fplog, fprintf(fplog, "Inner product between old and new vector <= 0.0!\n" "constraint #%d atoms %d and %d\n", - error - 1, iatom[3 * (error - 1) + 1] + 1, iatom[3 * (error - 1) + 2] + 1); + error - 1, + iatom[3 * (error - 1) + 1] + 1, + iatom[3 * (error - 1) + 2] + 1); } fprintf(stderr, "Inner product between old and new vector <= 0.0!\n" "constraint #%d atoms %d and %d\n", - error - 1, iatom[3 * (error - 1) + 1] + 1, iatom[3 * (error - 1) + 2] + 1); + error - 1, + iatom[3 * (error - 1) + 1] + 1, + iatom[3 * (error - 1) + 2] + 1); nit = 0; } @@ -635,16 +666,30 @@ static void check_cons(FILE* log, rvec_sub(prime[ai], prime[aj], dx); } dp = norm(dx); - fprintf(log, "%5d %5.2f %5d %5.2f %10.5f %10.5f %10.5f\n", ai + 1, - 1.0 / invmass[ai], aj + 1, 1.0 / invmass[aj], d, dp, ip[ia[0]].constr.dA); + fprintf(log, + "%5d %5.2f %5d %5.2f %10.5f %10.5f %10.5f\n", + ai + 1, + 1.0 / invmass[ai], + aj + 1, + 1.0 / invmass[aj], + d, + dp, + ip[ia[0]].constr.dA); break; case ConstraintVariable::Velocities: rvec_sub(v[ai], v[aj], dv); d = iprod(dx, dv); rvec_sub(prime[ai], prime[aj], dv); dp = iprod(dx, dv); - fprintf(log, "%5d %5.2f %5d %5.2f %10.5f %10.5f %10.5f\n", ai + 1, - 1.0 / invmass[ai], aj + 1, 1.0 / invmass[aj], d, dp, 0.); + fprintf(log, + "%5d %5.2f %5d %5.2f %10.5f %10.5f %10.5f\n", + ai + 1, + 1.0 / invmass[ai], + aj + 1, + 1.0 / invmass[aj], + d, + dp, + 0.); break; default: gmx_incons("Unknown constraint quantity for SHAKE"); } @@ -690,9 +735,25 @@ static bool bshakef(FILE* log, { blen = (shaked->sblock[i + 1] - shaked->sblock[i]); blen /= 3; - n0 = vec_shakef(log, shaked, invmass, blen, idef.iparams, iatoms, ir.shake_tol, x_s, prime, - pbc, shaked->omega, ir.efep != efepNO, lambda, lam, invdt, v, bCalcVir, - vir_r_m_dr, econq); + n0 = vec_shakef(log, + shaked, + invmass, + blen, + idef.iparams, + iatoms, + ir.shake_tol, + x_s, + prime, + pbc, + shaked->omega, + ir.efep != efepNO, + lambda, + lam, + invdt, + v, + bCalcVir, + vir_r_m_dr, + econq); if (n0 == 0) { @@ -785,12 +846,27 @@ bool constrain_shake(FILE* log, switch (econq) { case (ConstraintVariable::Positions): - bOK = bshakef(log, shaked, invmass, idef, ir, x_s, xprime, pbc, nrnb, lambda, dvdlambda, - invdt, v, bCalcVir, vir_r_m_dr, bDumpOnError, econq); + bOK = bshakef( + log, shaked, invmass, idef, ir, x_s, xprime, pbc, nrnb, lambda, dvdlambda, invdt, v, bCalcVir, vir_r_m_dr, bDumpOnError, econq); break; case (ConstraintVariable::Velocities): - bOK = bshakef(log, shaked, invmass, idef, ir, x_s, vprime, pbc, nrnb, lambda, dvdlambda, - invdt, {}, bCalcVir, vir_r_m_dr, bDumpOnError, econq); + bOK = bshakef(log, + shaked, + invmass, + idef, + ir, + x_s, + vprime, + pbc, + nrnb, + lambda, + dvdlambda, + invdt, + {}, + bCalcVir, + vir_r_m_dr, + bDumpOnError, + econq); break; default: gmx_fatal(FARGS, diff --git a/src/gromacs/mdlib/sighandler.cpp b/src/gromacs/mdlib/sighandler.cpp index 392afa9fad..05c255e328 100644 --- a/src/gromacs/mdlib/sighandler.cpp +++ b/src/gromacs/mdlib/sighandler.cpp @@ -46,8 +46,10 @@ #include "gromacs/utility/fatalerror.h" -const char* gmx_stop_cond_name[] = { "None", "Stop at the next neighbor search step", - "Stop at the next step", "Abort" }; +const char* gmx_stop_cond_name[] = { "None", + "Stop at the next neighbor search step", + "Stop at the next step", + "Abort" }; /* these do not neccesarily match the stop condition, but are referred to in the signal handler. */ diff --git a/src/gromacs/mdlib/sim_util.cpp b/src/gromacs/mdlib/sim_util.cpp index 9ef783b67a..c4c3f5e7ca 100644 --- a/src/gromacs/mdlib/sim_util.cpp +++ b/src/gromacs/mdlib/sim_util.cpp @@ -203,9 +203,8 @@ static void pull_potential_wrapper(const t_commrec* cr, wallcycle_start(wcycle, ewcPULLPOT); set_pbc(&pbc, ir->pbcType, box); dvdl = 0; - enerd->term[F_COM_PULL] += - pull_potential(pull_work, mdatoms->massT, &pbc, cr, t, lambda[efptRESTRAINT], - as_rvec_array(x.data()), force, &dvdl); + enerd->term[F_COM_PULL] += pull_potential( + pull_work, mdatoms->massT, &pbc, cr, t, lambda[efptRESTRAINT], as_rvec_array(x.data()), force, &dvdl); enerd->dvdl_lin[efptRESTRAINT] += dvdl; wallcycle_stop(wcycle, ewcPULLPOT); } @@ -230,8 +229,16 @@ static void pme_receive_force_ener(t_forcerec* fr, wallcycle_start(wcycle, ewcPP_PMEWAITRECVF); dvdl_q = 0; dvdl_lj = 0; - gmx_pme_receive_f(fr->pmePpCommGpu.get(), cr, forceWithVirial, &e_q, &e_lj, &dvdl_q, &dvdl_lj, - useGpuPmePpComms, receivePmeForceToGpu, &cycles_seppme); + gmx_pme_receive_f(fr->pmePpCommGpu.get(), + cr, + forceWithVirial, + &e_q, + &e_lj, + &dvdl_q, + &dvdl_lj, + useGpuPmePpComms, + receivePmeForceToGpu, + &cycles_seppme); enerd->term[F_COUL_RECIP] += e_q; enerd->term[F_LJ_RECIP] += e_lj; enerd->dvdl_lin[efptCOUL] += dvdl_q; @@ -260,8 +267,14 @@ static void print_large_forces(FILE* fp, bool nonFinite = !std::isfinite(force2); if (force2 >= force2Tolerance || nonFinite) { - fprintf(fp, "step %" PRId64 " atom %6d x %8.3f %8.3f %8.3f force %12.5e\n", step, - ddglatnr(cr->dd, i), x[i][XX], x[i][YY], x[i][ZZ], std::sqrt(force2)); + fprintf(fp, + "step %" PRId64 " atom %6d x %8.3f %8.3f %8.3f force %12.5e\n", + step, + ddglatnr(cr->dd, i), + x[i][XX], + x[i][YY], + x[i][ZZ], + std::sqrt(force2)); } if (nonFinite) { @@ -311,8 +324,8 @@ static void postProcessForceWithShiftForces(t_nrnb* nrnb, if (stepWork.computeVirial) { /* Calculation of the virial must be done after vsites! */ - calc_virial(0, mdatoms.homenr, as_rvec_array(x.data()), forceWithShiftForces, vir_force, - box, nrnb, &fr, fr.pbcType); + calc_virial( + 0, mdatoms.homenr, as_rvec_array(x.data()), forceWithShiftForces, vir_force, box, nrnb, &fr, fr.pbcType); } } @@ -530,9 +543,13 @@ static void checkPotentialEnergyValidity(int64_t step, const gmx_enerdata_t& ene "can be caused by overlapping interactions in bonded interactions or very large%s " "coordinate values. Usually this is caused by a badly- or non-equilibrated initial " "configuration, incorrect interactions or parameters in the topology.", - step, enerd.term[F_EPOT], energyIsNotFinite ? "not finite" : "extremely high", - enerd.term[F_LJ], enerd.term[F_COUL_SR], - energyIsNotFinite ? "non-finite" : "very high", energyIsNotFinite ? " or Nan" : ""); + step, + enerd.term[F_EPOT], + energyIsNotFinite ? "not finite" : "extremely high", + enerd.term[F_LJ], + enerd.term[F_COUL_SR], + energyIsNotFinite ? "non-finite" : "very high", + energyIsNotFinite ? " or Nan" : ""); } } @@ -629,8 +646,8 @@ static void computeSpecialForces(FILE* fplog, if (mtsLevel == 0 || stepWork.computeSlowForces) { auto& forceWithVirial = (mtsLevel == 0) ? forceWithVirialMtsLevel0 : forceWithVirialMtsLevel1; - pull_potential_wrapper(cr, inputrec, box, x, forceWithVirial, mdatoms, enerd, pull_work, - lambda.data(), t, wcycle); + pull_potential_wrapper( + cr, inputrec, box, x, forceWithVirial, mdatoms, enerd, pull_work, lambda.data(), t, wcycle); } } if (awh) @@ -642,15 +659,22 @@ static void computeSpecialForces(FILE* fplog, std::vector foreignLambdaDeltaH, foreignLambdaDhDl; if (needForeignEnergyDifferences) { - enerd->foreignLambdaTerms.finalizePotentialContributions(enerd->dvdl_lin, lambda, - *inputrec->fepvals); + enerd->foreignLambdaTerms.finalizePotentialContributions( + enerd->dvdl_lin, lambda, *inputrec->fepvals); std::tie(foreignLambdaDeltaH, foreignLambdaDhDl) = enerd->foreignLambdaTerms.getTerms(cr); } auto& forceWithVirial = (mtsLevel == 0) ? forceWithVirialMtsLevel0 : forceWithVirialMtsLevel1; - enerd->term[F_COM_PULL] += awh->applyBiasForcesAndUpdateBias( - inputrec->pbcType, mdatoms->massT, foreignLambdaDeltaH, foreignLambdaDhDl, box, - forceWithVirial, t, step, wcycle, fplog); + enerd->term[F_COM_PULL] += awh->applyBiasForcesAndUpdateBias(inputrec->pbcType, + mdatoms->massT, + foreignLambdaDeltaH, + foreignLambdaDhDl, + box, + forceWithVirial, + t, + step, + wcycle, + fplog); } } @@ -757,9 +781,8 @@ static void alternatePmeNbGpuWaitReduce(nonbonded_verlet_t* nbv, { GpuTaskCompletion completionType = (isNbGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check; - isPmeGpuDone = pme_gpu_try_finish_task(pmedata, stepWork, wcycle, - &forceOutputsPme->forceWithVirial(), enerd, - lambdaQ, completionType); + isPmeGpuDone = pme_gpu_try_finish_task( + pmedata, stepWork, wcycle, &forceOutputsPme->forceWithVirial(), enerd, lambdaQ, completionType); } if (!isNbGpuDone) @@ -767,10 +790,14 @@ static void alternatePmeNbGpuWaitReduce(nonbonded_verlet_t* nbv, auto& forceBuffersNonbonded = forceOutputsNonbonded->forceWithShiftForces(); GpuTaskCompletion completionType = (isPmeGpuDone) ? GpuTaskCompletion::Wait : GpuTaskCompletion::Check; - isNbGpuDone = Nbnxm::gpu_try_finish_task( - nbv->gpu_nbv, stepWork, AtomLocality::Local, enerd->grpp.ener[egLJSR].data(), - enerd->grpp.ener[egCOULSR].data(), forceBuffersNonbonded.shiftForces(), - completionType, wcycle); + isNbGpuDone = Nbnxm::gpu_try_finish_task(nbv->gpu_nbv, + stepWork, + AtomLocality::Local, + enerd->grpp.ener[egLJSR].data(), + enerd->grpp.ener[egCOULSR].data(), + forceBuffersNonbonded.shiftForces(), + completionType, + wcycle); if (isNbGpuDone) { @@ -797,8 +824,8 @@ static ForceOutputs setupForceOutputs(ForceHelperBuffers* forceH wallcycle_sub_start(wcycle, ewcsCLEAR_FORCE_BUFFER); /* NOTE: We assume fr->shiftForces is all zeros here */ - gmx::ForceWithShiftForces forceWithShiftForces(force, stepWork.computeVirial, - forceHelperBuffers->shiftForces()); + gmx::ForceWithShiftForces forceWithShiftForces( + force, stepWork.computeVirial, forceHelperBuffers->shiftForces()); if (stepWork.computeForces) { @@ -835,8 +862,8 @@ static ForceOutputs setupForceOutputs(ForceHelperBuffers* forceH wallcycle_sub_stop(wcycle, ewcsCLEAR_FORCE_BUFFER); - return ForceOutputs(forceWithShiftForces, forceHelperBuffers->haveDirectVirialContributions(), - forceWithVirial); + return ForceOutputs( + forceWithShiftForces, forceHelperBuffers->haveDirectVirialContributions(), forceWithVirial); } @@ -1064,9 +1091,12 @@ static void setupGpuForceReductions(gmx::MdrunScheduleWorkload* runScheduleWork, const bool accumulate = runScheduleWork->domainWork.haveCpuLocalForceWork || havePPDomainDecomposition(cr); const int atomStart = 0; - fr->gpuForceReduction[gmx::AtomLocality::Local]->reinit( - stateGpu->getForces(), nbv->getNumAtoms(AtomLocality::Local), nbv->getGridIndices(), - atomStart, accumulate, stateGpu->fReducedOnDevice()); + fr->gpuForceReduction[gmx::AtomLocality::Local]->reinit(stateGpu->getForces(), + nbv->getNumAtoms(AtomLocality::Local), + nbv->getGridIndices(), + atomStart, + accumulate, + stateGpu->fReducedOnDevice()); // register forces and add dependencies fr->gpuForceReduction[gmx::AtomLocality::Local]->registerNbnxmForce(nbv->getGpuForces()); @@ -1107,9 +1137,11 @@ static void setupGpuForceReductions(gmx::MdrunScheduleWorkload* runScheduleWork, const bool accumulate = runScheduleWork->domainWork.haveCpuBondedWork || runScheduleWork->domainWork.haveFreeEnergyWork; const int atomStart = dd_numHomeAtoms(*cr->dd); - fr->gpuForceReduction[gmx::AtomLocality::NonLocal]->reinit( - stateGpu->getForces(), nbv->getNumAtoms(AtomLocality::NonLocal), - nbv->getGridIndices(), atomStart, accumulate); + fr->gpuForceReduction[gmx::AtomLocality::NonLocal]->reinit(stateGpu->getForces(), + nbv->getNumAtoms(AtomLocality::NonLocal), + nbv->getGridIndices(), + atomStart, + accumulate); // register forces and add dependencies fr->gpuForceReduction[gmx::AtomLocality::NonLocal]->registerNbnxmForce(nbv->getGpuForces()); @@ -1163,8 +1195,8 @@ void do_force(FILE* fplog, const SimulationWorkload& simulationWork = runScheduleWork->simulationWork; - runScheduleWork->stepWork = setupStepWorkload(legacyFlags, inputrec->mtsLevels, step, - simulationWork, thisRankHasDuty(cr, DUTY_PME)); + runScheduleWork->stepWork = setupStepWorkload( + legacyFlags, inputrec->mtsLevels, step, simulationWork, thisRankHasDuty(cr, DUTY_PME)); const StepWorkload& stepWork = runScheduleWork->stepWork; const bool useGpuPmeOnThisRank = @@ -1195,7 +1227,9 @@ void do_force(FILE* fplog, const bool calcCGCM = (fillGrid && !DOMAINDECOMP(cr)); if (calcCGCM) { - put_atoms_in_box_omp(fr->pbcType, box, x.unpaddedArrayRef().subArray(0, mdatoms->homenr), + put_atoms_in_box_omp(fr->pbcType, + box, + x.unpaddedArrayRef().subArray(0, mdatoms->homenr), gmx_omp_nthreads_get(emntDefault)); inc_nrnb(nrnb, eNR_SHIFTX, mdatoms->homenr); } @@ -1247,10 +1281,19 @@ void do_force(FILE* fplog, stateGpu->waitCoordinatesReadyOnHost(AtomLocality::Local); } - gmx_pme_send_coordinates(fr, cr, box, as_rvec_array(x.unpaddedArrayRef().data()), lambda[efptCOUL], - lambda[efptVDW], (stepWork.computeVirial || stepWork.computeEnergy), - step, simulationWork.useGpuPmePpCommunication, reinitGpuPmePpComms, - pmeSendCoordinatesFromGpu, localXReadyOnDevice, wcycle); + gmx_pme_send_coordinates(fr, + cr, + box, + as_rvec_array(x.unpaddedArrayRef().data()), + lambda[efptCOUL], + lambda[efptVDW], + (stepWork.computeVirial || stepWork.computeEnergy), + step, + simulationWork.useGpuPmePpCommunication, + reinitGpuPmePpComms, + pmeSendCoordinatesFromGpu, + localXReadyOnDevice, + wcycle); } // Coordinates on the device are needed if PME or BufferOps are offloaded. @@ -1285,10 +1328,19 @@ void do_force(FILE* fplog, if (!thisRankHasDuty(cr, DUTY_PME) && pmeSendCoordinatesFromGpu) { /* Send particle coordinates to the pme nodes */ - gmx_pme_send_coordinates(fr, cr, box, as_rvec_array(x.unpaddedArrayRef().data()), lambda[efptCOUL], - lambda[efptVDW], (stepWork.computeVirial || stepWork.computeEnergy), - step, simulationWork.useGpuPmePpCommunication, reinitGpuPmePpComms, - pmeSendCoordinatesFromGpu, localXReadyOnDevice, wcycle); + gmx_pme_send_coordinates(fr, + cr, + box, + as_rvec_array(x.unpaddedArrayRef().data()), + lambda[efptCOUL], + lambda[efptVDW], + (stepWork.computeVirial || stepWork.computeEnergy), + step, + simulationWork.useGpuPmePpCommunication, + reinitGpuPmePpComms, + pmeSendCoordinatesFromGpu, + localXReadyOnDevice, + wcycle); } if (useGpuPmeOnThisRank) @@ -1322,8 +1374,18 @@ void do_force(FILE* fplog, if (!DOMAINDECOMP(cr)) { wallcycle_sub_start(wcycle, ewcsNBS_GRID_LOCAL); - nbnxn_put_on_grid(nbv, box, 0, vzero, box_diag, nullptr, { 0, mdatoms->homenr }, -1, - fr->cginfo, x.unpaddedArrayRef(), 0, nullptr); + nbnxn_put_on_grid(nbv, + box, + 0, + vzero, + box_diag, + nullptr, + { 0, mdatoms->homenr }, + -1, + fr->cginfo, + x.unpaddedArrayRef(), + 0, + nullptr); wallcycle_sub_stop(wcycle, ewcsNBS_GRID_LOCAL); } else @@ -1334,7 +1396,8 @@ void do_force(FILE* fplog, } nbv->setAtomProperties(gmx::constArrayRefFromArray(mdatoms->typeA, mdatoms->nr), - gmx::constArrayRefFromArray(mdatoms->chargeA, mdatoms->nr), fr->cginfo); + gmx::constArrayRefFromArray(mdatoms->chargeA, mdatoms->nr), + fr->cginfo); wallcycle_stop(wcycle, ewcNS); @@ -1358,9 +1421,11 @@ void do_force(FILE* fplog, // TODO the xq, f, and fshift buffers are now shared // resources, so they should be maintained by a // higher-level object than the nb module. - fr->gpuBonded->updateInteractionListsAndDeviceBuffers( - nbv->getGridIndices(), top->idef, Nbnxm::gpu_get_xq(nbv->gpu_nbv), - Nbnxm::gpu_get_f(nbv->gpu_nbv), Nbnxm::gpu_get_fshift(nbv->gpu_nbv)); + fr->gpuBonded->updateInteractionListsAndDeviceBuffers(nbv->getGridIndices(), + top->idef, + Nbnxm::gpu_get_xq(nbv->gpu_nbv), + Nbnxm::gpu_get_f(nbv->gpu_nbv), + Nbnxm::gpu_get_fshift(nbv->gpu_nbv)); } } @@ -1394,8 +1459,8 @@ void do_force(FILE* fplog, if (stepWork.useGpuXBufferOps) { GMX_ASSERT(stateGpu, "stateGpu should be valid when buffer ops are offloaded"); - nbv->convertCoordinatesGpu(AtomLocality::Local, false, stateGpu->getCoordinates(), - localXReadyOnDevice); + nbv->convertCoordinatesGpu( + AtomLocality::Local, false, stateGpu->getCoordinates(), localXReadyOnDevice); } else { @@ -1504,7 +1569,9 @@ void do_force(FILE* fplog, { stateGpu->copyCoordinatesToGpu(x.unpaddedArrayRef(), AtomLocality::NonLocal); } - nbv->convertCoordinatesGpu(AtomLocality::NonLocal, false, stateGpu->getCoordinates(), + nbv->convertCoordinatesGpu(AtomLocality::NonLocal, + false, + stateGpu->getCoordinates(), stateGpu->getCoordinatesReadyOnDeviceEvent( AtomLocality::NonLocal, simulationWork, stepWork)); } @@ -1534,8 +1601,7 @@ void do_force(FILE* fplog, /* launch non-local nonbonded tasks on GPU */ wallcycle_start_nocount(wcycle, ewcLAUNCH_GPU); wallcycle_sub_start(wcycle, ewcsLAUNCH_GPU_NONBONDED); - do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::NonLocal, enbvClearFNo, step, - nrnb, wcycle); + do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::NonLocal, enbvClearFNo, step, nrnb, wcycle); wallcycle_sub_stop(wcycle, ewcsLAUNCH_GPU_NONBONDED); wallcycle_stop(wcycle, ewcLAUNCH_GPU); } @@ -1578,8 +1644,14 @@ void do_force(FILE* fplog, */ gmx::ArrayRef xRef = (xWholeMolecules.empty() ? x.unpaddedArrayRef() : xWholeMolecules); - calc_mu(start, mdatoms->homenr, xRef, mdatoms->chargeA, mdatoms->chargeB, - mdatoms->nChargePerturbed, dipoleData.muStaging[0], dipoleData.muStaging[1]); + calc_mu(start, + mdatoms->homenr, + xRef, + mdatoms->chargeA, + mdatoms->chargeB, + mdatoms->nChargePerturbed, + dipoleData.muStaging[0], + dipoleData.muStaging[1]); reduceAndUpdateMuTot(&dipoleData, cr, (fr->efep != efepNO), lambda, muTotal, ddBalanceRegionHandler); } @@ -1604,8 +1676,7 @@ void do_force(FILE* fplog, if (inputrec->bRot) { wallcycle_start(wcycle, ewcROT); - do_rotation(cr, enforcedRotation, box, as_rvec_array(x.unpaddedArrayRef().data()), t, step, - stepWork.doNeighborSearch); + do_rotation(cr, enforcedRotation, box, as_rvec_array(x.unpaddedArrayRef().data()), t, step, stepWork.doNeighborSearch); wallcycle_stop(wcycle, ewcROT); } @@ -1629,7 +1700,8 @@ void do_force(FILE* fplog, (fr->useMts && stepWork.computeSlowForces) ? std::optional(setupForceOutputs(&fr->forceHelperBuffers[1], forceView->forceMtsCombinedWithPadding(), - stepWork, wcycle)) + stepWork, + wcycle)) : std::nullopt; ForceOutputs* forceOutMtsLevel1 = @@ -1664,17 +1736,29 @@ void do_force(FILE* fplog, /* Calculate the local and non-local free energy interactions here. * Happens here on the CPU both with and without GPU. */ - nbv->dispatchFreeEnergyKernel(InteractionLocality::Local, fr, + nbv->dispatchFreeEnergyKernel(InteractionLocality::Local, + fr, as_rvec_array(x.unpaddedArrayRef().data()), - &forceOutNonbonded->forceWithShiftForces(), *mdatoms, - inputrec->fepvals, lambda, enerd, stepWork, nrnb); + &forceOutNonbonded->forceWithShiftForces(), + *mdatoms, + inputrec->fepvals, + lambda, + enerd, + stepWork, + nrnb); if (havePPDomainDecomposition(cr)) { - nbv->dispatchFreeEnergyKernel(InteractionLocality::NonLocal, fr, + nbv->dispatchFreeEnergyKernel(InteractionLocality::NonLocal, + fr, as_rvec_array(x.unpaddedArrayRef().data()), - &forceOutNonbonded->forceWithShiftForces(), *mdatoms, - inputrec->fepvals, lambda, enerd, stepWork, nrnb); + &forceOutNonbonded->forceWithShiftForces(), + *mdatoms, + inputrec->fepvals, + lambda, + enerd, + stepWork, + nrnb); } } @@ -1682,8 +1766,7 @@ void do_force(FILE* fplog, { if (havePPDomainDecomposition(cr)) { - do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::NonLocal, enbvClearFNo, step, - nrnb, wcycle); + do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::NonLocal, enbvClearFNo, step, nrnb, wcycle); } if (stepWork.computeForces) @@ -1722,9 +1805,15 @@ void do_force(FILE* fplog, if (inputrec->nwall && stepWork.computeNonbondedForces) { /* foreign lambda component for walls */ - real dvdl_walls = do_walls(*inputrec, *fr, box, *mdatoms, x.unpaddedConstArrayRef(), - &forceOutMtsLevel0.forceWithVirial(), lambda[efptVDW], - enerd->grpp.ener[egLJSR].data(), nrnb); + real dvdl_walls = do_walls(*inputrec, + *fr, + box, + *mdatoms, + x.unpaddedConstArrayRef(), + &forceOutMtsLevel0.forceWithVirial(), + lambda[efptVDW], + enerd->grpp.ener[egLJSR].data(), + nrnb); enerd->dvdl_lin[efptVDW] += dvdl_walls; } @@ -1754,19 +1843,43 @@ void do_force(FILE* fplog, { ListedForces& listedForces = fr->listedForces[mtsIndex]; ForceOutputs& forceOut = (mtsIndex == 0 ? forceOutMtsLevel0 : *forceOutMtsLevel1); - listedForces.calculate( - wcycle, box, inputrec->fepvals, cr, ms, x, xWholeMolecules, fr->fcdata.get(), - hist, &forceOut, fr, &pbc, enerd, nrnb, lambda.data(), mdatoms, - DOMAINDECOMP(cr) ? cr->dd->globalAtomIndices.data() : nullptr, stepWork); + listedForces.calculate(wcycle, + box, + inputrec->fepvals, + cr, + ms, + x, + xWholeMolecules, + fr->fcdata.get(), + hist, + &forceOut, + fr, + &pbc, + enerd, + nrnb, + lambda.data(), + mdatoms, + DOMAINDECOMP(cr) ? cr->dd->globalAtomIndices.data() : nullptr, + stepWork); } } if (stepWork.computeSlowForces) { - calculateLongRangeNonbondeds(fr, inputrec, cr, nrnb, wcycle, mdatoms, - x.unpaddedConstArrayRef(), &forceOutMtsLevel1->forceWithVirial(), - enerd, box, lambda.data(), as_rvec_array(dipoleData.muStateAB), - stepWork, ddBalanceRegionHandler); + calculateLongRangeNonbondeds(fr, + inputrec, + cr, + nrnb, + wcycle, + mdatoms, + x.unpaddedConstArrayRef(), + &forceOutMtsLevel1->forceWithVirial(), + enerd, + box, + lambda.data(), + as_rvec_array(dipoleData.muStateAB), + stepWork, + ddBalanceRegionHandler); } wallcycle_stop(wcycle, ewcFORCE); @@ -1791,11 +1904,27 @@ void do_force(FILE* fplog, } } - computeSpecialForces(fplog, cr, inputrec, awh, enforcedRotation, imdSession, pull_work, step, t, - wcycle, fr->forceProviders, box, x.unpaddedArrayRef(), mdatoms, lambda, - stepWork, &forceOutMtsLevel0.forceWithVirial(), - forceOutMtsLevel1 ? &forceOutMtsLevel1->forceWithVirial() : nullptr, enerd, - ed, stepWork.doNeighborSearch); + computeSpecialForces(fplog, + cr, + inputrec, + awh, + enforcedRotation, + imdSession, + pull_work, + step, + t, + wcycle, + fr->forceProviders, + box, + x.unpaddedArrayRef(), + mdatoms, + lambda, + stepWork, + &forceOutMtsLevel0.forceWithVirial(), + forceOutMtsLevel1 ? &forceOutMtsLevel1->forceWithVirial() : nullptr, + enerd, + ed, + stepWork.doNeighborSearch); GMX_ASSERT(!(nonbondedAtMtsLevel1 && stepWork.useGpuFBufferOps), "The schedule below does not allow for nonbonded MTS with GPU buffer ops"); @@ -1813,15 +1942,19 @@ void do_force(FILE* fplog, { if (simulationWork.useGpuNonbonded) { - cycles_wait_gpu += Nbnxm::gpu_wait_finish_task( - nbv->gpu_nbv, stepWork, AtomLocality::NonLocal, enerd->grpp.ener[egLJSR].data(), - enerd->grpp.ener[egCOULSR].data(), forceWithShiftForces.shiftForces(), wcycle); + cycles_wait_gpu += Nbnxm::gpu_wait_finish_task(nbv->gpu_nbv, + stepWork, + AtomLocality::NonLocal, + enerd->grpp.ener[egLJSR].data(), + enerd->grpp.ener[egCOULSR].data(), + forceWithShiftForces.shiftForces(), + wcycle); } else { wallcycle_start_nocount(wcycle, ewcFORCE); - do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::NonLocal, enbvClearFYes, - step, nrnb, wcycle); + do_nb_verlet( + fr, ic, enerd, stepWork, InteractionLocality::NonLocal, enbvClearFYes, step, nrnb, wcycle); wallcycle_stop(wcycle, ewcFORCE); } @@ -1871,7 +2004,9 @@ void do_force(FILE* fplog, if (combineMtsForcesBeforeHaloExchange) { const int numAtoms = havePPDomainDecomposition(cr) ? dd_numAtomsZones(*cr->dd) : mdatoms->homenr; - combineMtsForces(numAtoms, force.unpaddedArrayRef(), forceView->forceMtsCombined(), + combineMtsForces(numAtoms, + force.unpaddedArrayRef(), + forceView->forceMtsCombined(), inputrec->mtsLevels[1].stepFactor); } @@ -1924,14 +2059,14 @@ void do_force(FILE* fplog, && !DOMAINDECOMP(cr) && !stepWork.useGpuFBufferOps); if (alternateGpuWait) { - alternatePmeNbGpuWaitReduce(fr->nbv.get(), fr->pmedata, forceOutNonbonded, - forceOutMtsLevel1, enerd, lambda[efptCOUL], stepWork, wcycle); + alternatePmeNbGpuWaitReduce( + fr->nbv.get(), fr->pmedata, forceOutNonbonded, forceOutMtsLevel1, enerd, lambda[efptCOUL], stepWork, wcycle); } if (!alternateGpuWait && useGpuPmeOnThisRank) { - pme_gpu_wait_and_reduce(fr->pmedata, stepWork, wcycle, - &forceOutMtsLevel1->forceWithVirial(), enerd, lambda[efptCOUL]); + pme_gpu_wait_and_reduce( + fr->pmedata, stepWork, wcycle, &forceOutMtsLevel1->forceWithVirial(), enerd, lambda[efptCOUL]); } /* Wait for local GPU NB outputs on the non-alternating wait path */ @@ -1943,10 +2078,14 @@ void do_force(FILE* fplog, * of the step time. */ const float gpuWaitApiOverheadMargin = 2e6F; /* cycles */ - const float waitCycles = Nbnxm::gpu_wait_finish_task( - nbv->gpu_nbv, stepWork, AtomLocality::Local, enerd->grpp.ener[egLJSR].data(), - enerd->grpp.ener[egCOULSR].data(), - forceOutNonbonded->forceWithShiftForces().shiftForces(), wcycle); + const float waitCycles = + Nbnxm::gpu_wait_finish_task(nbv->gpu_nbv, + stepWork, + AtomLocality::Local, + enerd->grpp.ener[egLJSR].data(), + enerd->grpp.ener[egCOULSR].data(), + forceOutNonbonded->forceWithShiftForces().shiftForces(), + wcycle); if (ddBalanceRegionHandler.useBalancingRegion()) { @@ -1970,8 +2109,15 @@ void do_force(FILE* fplog, // NOTE: emulation kernel is not included in the balancing region, // but emulation mode does not target performance anyway wallcycle_start_nocount(wcycle, ewcFORCE); - do_nb_verlet(fr, ic, enerd, stepWork, InteractionLocality::Local, - DOMAINDECOMP(cr) ? enbvClearFNo : enbvClearFYes, step, nrnb, wcycle); + do_nb_verlet(fr, + ic, + enerd, + stepWork, + InteractionLocality::Local, + DOMAINDECOMP(cr) ? enbvClearFNo : enbvClearFYes, + step, + nrnb, + wcycle); wallcycle_stop(wcycle, ewcFORCE); } @@ -1983,9 +2129,13 @@ void do_force(FILE* fplog, /* In case of node-splitting, the PP nodes receive the long-range * forces, virial and energy from the PME nodes here. */ - pme_receive_force_ener(fr, cr, &forceOutMtsLevel1->forceWithVirial(), enerd, + pme_receive_force_ener(fr, + cr, + &forceOutMtsLevel1->forceWithVirial(), + enerd, simulationWork.useGpuPmePpCommunication, - stepWork.useGpuPmeFReduction, wcycle); + stepWork.useGpuPmeFReduction, + wcycle); } @@ -2050,8 +2200,8 @@ void do_force(FILE* fplog, } } - launchGpuEndOfStepTasks(nbv, fr->gpuBonded, fr->pmedata, enerd, *runScheduleWork, - useGpuPmeOnThisRank, step, wcycle); + launchGpuEndOfStepTasks( + nbv, fr->gpuBonded, fr->pmedata, enerd, *runScheduleWork, useGpuPmeOnThisRank, step, wcycle); if (DOMAINDECOMP(cr)) { @@ -2062,13 +2212,13 @@ void do_force(FILE* fplog, && combineMtsForcesBeforeHaloExchange); if (stepWork.computeForces) { - postProcessForceWithShiftForces(nrnb, wcycle, box, x.unpaddedArrayRef(), &forceOutMtsLevel0, - vir_force, *mdatoms, *fr, vsite, stepWork); + postProcessForceWithShiftForces( + nrnb, wcycle, box, x.unpaddedArrayRef(), &forceOutMtsLevel0, vir_force, *mdatoms, *fr, vsite, stepWork); if (fr->useMts && stepWork.computeSlowForces && !haveCombinedMtsForces) { - postProcessForceWithShiftForces(nrnb, wcycle, box, x.unpaddedArrayRef(), forceOutMtsLevel1, - vir_force, *mdatoms, *fr, vsite, stepWork); + postProcessForceWithShiftForces( + nrnb, wcycle, box, x.unpaddedArrayRef(), forceOutMtsLevel1, vir_force, *mdatoms, *fr, vsite, stepWork); } } @@ -2079,8 +2229,13 @@ void do_force(FILE* fplog, /* In case of node-splitting, the PP nodes receive the long-range * forces, virial and energy from the PME nodes here. */ - pme_receive_force_ener(fr, cr, &forceOutMtsLevel1->forceWithVirial(), enerd, - simulationWork.useGpuPmePpCommunication, false, wcycle); + pme_receive_force_ener(fr, + cr, + &forceOutMtsLevel1->forceWithVirial(), + enerd, + simulationWork.useGpuPmePpCommunication, + false, + wcycle); } if (stepWork.computeForces) @@ -2090,16 +2245,18 @@ void do_force(FILE* fplog, * otherwise we have to post-process two outputs and then combine them. */ ForceOutputs& forceOutCombined = (haveCombinedMtsForces ? forceOutMts.value() : forceOutMtsLevel0); - postProcessForces(cr, step, nrnb, wcycle, box, x.unpaddedArrayRef(), &forceOutCombined, - vir_force, mdatoms, fr, vsite, stepWork); + postProcessForces( + cr, step, nrnb, wcycle, box, x.unpaddedArrayRef(), &forceOutCombined, vir_force, mdatoms, fr, vsite, stepWork); if (fr->useMts && stepWork.computeSlowForces && !haveCombinedMtsForces) { - postProcessForces(cr, step, nrnb, wcycle, box, x.unpaddedArrayRef(), forceOutMtsLevel1, - vir_force, mdatoms, fr, vsite, stepWork); + postProcessForces( + cr, step, nrnb, wcycle, box, x.unpaddedArrayRef(), forceOutMtsLevel1, vir_force, mdatoms, fr, vsite, stepWork); - combineMtsForces(mdatoms->homenr, force.unpaddedArrayRef(), - forceView->forceMtsCombined(), inputrec->mtsLevels[1].stepFactor); + combineMtsForces(mdatoms->homenr, + force.unpaddedArrayRef(), + forceView->forceMtsCombined(), + inputrec->mtsLevels[1].stepFactor); } } diff --git a/src/gromacs/mdlib/simulationsignal.cpp b/src/gromacs/mdlib/simulationsignal.cpp index 15f44ccbf4..8199dcb450 100644 --- a/src/gromacs/mdlib/simulationsignal.cpp +++ b/src/gromacs/mdlib/simulationsignal.cpp @@ -85,7 +85,9 @@ gmx::ArrayRef SimulationSignaller::getCommunicationBuffer() { if (doIntraSim_) { - std::transform(std::begin(*signals_), std::end(*signals_), std::begin(mpiBuffer_), + std::transform(std::begin(*signals_), + std::end(*signals_), + std::begin(mpiBuffer_), [](const SimulationSignals::value_type& s) { return s.sig; }); return mpiBuffer_; diff --git a/src/gromacs/mdlib/splitter.cpp b/src/gromacs/mdlib/splitter.cpp index a970c3fc0a..a90ebe958d 100644 --- a/src/gromacs/mdlib/splitter.cpp +++ b/src/gromacs/mdlib/splitter.cpp @@ -94,8 +94,14 @@ static int mk_grey(gmx::ArrayRef edgeColor, const t_graph* g, int* AtomI, range_check(ai + g0, 0, maxsid); if (sid[aj + g0].sid != -1) { - gmx_fatal(FARGS, "sid[%d]=%d, sid[%d]=%d, file %s, line %d", ai, sid[ai + g0].sid, - aj, sid[aj + g0].sid, __FILE__, __LINE__); + gmx_fatal(FARGS, + "sid[%d]=%d, sid[%d]=%d, file %s, line %d", + ai, + sid[ai + g0].sid, + aj, + sid[aj + g0].sid, + __FILE__, + __LINE__); } else { diff --git a/src/gromacs/mdlib/stat.cpp b/src/gromacs/mdlib/stat.cpp index 2c8c6b44d0..26d2fe5b02 100644 --- a/src/gromacs/mdlib/stat.cpp +++ b/src/gromacs/mdlib/stat.cpp @@ -258,7 +258,8 @@ void global_stat(const gmx_global_stat* gs, idvdlnl = add_bind(rb, efptNR, enerd->dvdl_nonlin); if (enerd->foreignLambdaTerms.numLambdas() > 0) { - iepl = add_bind(rb, enerd->foreignLambdaTerms.energies().size(), + iepl = add_bind(rb, + enerd->foreignLambdaTerms.energies().size(), enerd->foreignLambdaTerms.energies().data()); } } @@ -354,7 +355,9 @@ void global_stat(const gmx_global_stat* gs, extract_bind(rb, idvdlnl, efptNR, enerd->dvdl_nonlin); if (enerd->foreignLambdaTerms.numLambdas() > 0) { - extract_bind(rb, iepl, enerd->foreignLambdaTerms.energies().size(), + extract_bind(rb, + iepl, + enerd->foreignLambdaTerms.energies().size(), enerd->foreignLambdaTerms.energies().data()); } } diff --git a/src/gromacs/mdlib/stophandler.cpp b/src/gromacs/mdlib/stophandler.cpp index 040fd5fb18..46894c0ecb 100644 --- a/src/gromacs/mdlib/stophandler.cpp +++ b/src/gromacs/mdlib/stophandler.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2018,2019, by the GROMACS development team, led by + * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -106,12 +106,16 @@ StopSignal StopConditionSignal::getSignal(FILE* fplog) } if (fplog) { - fprintf(fplog, "\n\nReceived the %s signal, stopping within %d steps\n\n", - gmx_get_signal_name(), nsteps_stop); + fprintf(fplog, + "\n\nReceived the %s signal, stopping within %d steps\n\n", + gmx_get_signal_name(), + nsteps_stop); fflush(fplog); } - fprintf(stderr, "\n\nReceived the %s signal, stopping within %d steps\n\n", - gmx_get_signal_name(), nsteps_stop); + fprintf(stderr, + "\n\nReceived the %s signal, stopping within %d steps\n\n", + gmx_get_signal_name(), + nsteps_stop); fflush(stderr); handledStopCondition_ = static_cast(gmx_get_stop_condition()); } @@ -147,12 +151,16 @@ StopSignal StopConditionTime::getSignal(bool bNS, int64_t step, FILE* fplog, gmx fprintf(fplog, "\nStep %s: Run time exceeded %.3f hours, " "will terminate the run within %d steps\n", - gmx_step_str(step, sbuf), maximumHoursToRun_ * 0.99, nsteps_stop); + gmx_step_str(step, sbuf), + maximumHoursToRun_ * 0.99, + nsteps_stop); } fprintf(stderr, "\nStep %s: Run time exceeded %.3f hours, " "will terminate the run within %d steps\n", - gmx_step_str(step, sbuf), maximumHoursToRun_ * 0.99, nsteps_stop); + gmx_step_str(step, sbuf), + maximumHoursToRun_ * 0.99, + nsteps_stop); signalSent_ = true; return StopSignal::stopAtNextNSStep; } @@ -196,8 +204,8 @@ std::unique_ptr StopHandlerBuilder::getStopHandlerMD(compat::not_nu }); } - return std::make_unique(signal, simulationShareState, stopConditions_, - neverUpdateNeighborList); + return std::make_unique( + signal, simulationShareState, stopConditions_, neverUpdateNeighborList); } } // namespace gmx diff --git a/src/gromacs/mdlib/tests/constr.cpp b/src/gromacs/mdlib/tests/constr.cpp index 6c74a5a989..631da1df81 100644 --- a/src/gromacs/mdlib/tests/constr.cpp +++ b/src/gromacs/mdlib/tests/constr.cpp @@ -151,7 +151,12 @@ public: "rij = %f, which is not equal to r0 = %f for constraint #%zd, between atoms %d " "and %d" " (before constraining rij was %f).", - d1, r0, c, i, j, d0); + d1, + r0, + c, + i, + j, + d0); } } @@ -274,7 +279,8 @@ public: << gmx::formatString( "Values in virial tensor at [%d][%d] are not within the " "tolerance from reference value.", - i, j); + i, + j); } } } @@ -323,18 +329,36 @@ TEST_P(ConstraintsTest, SingleConstraint) int lincslincsExpansionOrder = 4; real lincsWarnAngle = 30.0; - std::unique_ptr testData = std::make_unique( - title, numAtoms, masses, constraints, constraintsR0, true, virialScaledRef, false, 0, - real(0.0), real(0.001), x, xPrime, v, shakeTolerance, shakeUseSOR, lincsNIter, - lincslincsExpansionOrder, lincsWarnAngle); + std::unique_ptr testData = + std::make_unique(title, + numAtoms, + masses, + constraints, + constraintsR0, + true, + virialScaledRef, + false, + 0, + real(0.0), + real(0.001), + x, + xPrime, + v, + shakeTolerance, + shakeUseSOR, + lincsNIter, + lincslincsExpansionOrder, + lincsWarnAngle); t_pbc pbc = GetParam(); // Cycle through all available runners for (const auto& runner : getRunners()) { - SCOPED_TRACE(formatString("Testing %s with %s PBC using %s.", testData->title_.c_str(), - c_pbcTypeNames[pbc.pbcType].c_str(), runner->name().c_str())); + SCOPED_TRACE(formatString("Testing %s with %s PBC using %s.", + testData->title_.c_str(), + c_pbcTypeNames[pbc.pbcType].c_str(), + runner->name().c_str())); testData->reset(); @@ -381,18 +405,36 @@ TEST_P(ConstraintsTest, TwoDisjointConstraints) int lincslincsExpansionOrder = 4; real lincsWarnAngle = 30.0; - std::unique_ptr testData = std::make_unique( - title, numAtoms, masses, constraints, constraintsR0, true, virialScaledRef, false, 0, - real(0.0), real(0.001), x, xPrime, v, shakeTolerance, shakeUseSOR, lincsNIter, - lincslincsExpansionOrder, lincsWarnAngle); + std::unique_ptr testData = + std::make_unique(title, + numAtoms, + masses, + constraints, + constraintsR0, + true, + virialScaledRef, + false, + 0, + real(0.0), + real(0.001), + x, + xPrime, + v, + shakeTolerance, + shakeUseSOR, + lincsNIter, + lincslincsExpansionOrder, + lincsWarnAngle); t_pbc pbc = GetParam(); // Cycle through all available runners for (const auto& runner : getRunners()) { - SCOPED_TRACE(formatString("Testing %s with %s PBC using %s.", testData->title_.c_str(), - c_pbcTypeNames[pbc.pbcType].c_str(), runner->name().c_str())); + SCOPED_TRACE(formatString("Testing %s with %s PBC using %s.", + testData->title_.c_str(), + c_pbcTypeNames[pbc.pbcType].c_str(), + runner->name().c_str())); testData->reset(); @@ -439,18 +481,36 @@ TEST_P(ConstraintsTest, ThreeSequentialConstraints) int lincslincsExpansionOrder = 4; real lincsWarnAngle = 30.0; - std::unique_ptr testData = std::make_unique( - title, numAtoms, masses, constraints, constraintsR0, true, virialScaledRef, false, 0, - real(0.0), real(0.001), x, xPrime, v, shakeTolerance, shakeUseSOR, lincsNIter, - lincslincsExpansionOrder, lincsWarnAngle); + std::unique_ptr testData = + std::make_unique(title, + numAtoms, + masses, + constraints, + constraintsR0, + true, + virialScaledRef, + false, + 0, + real(0.0), + real(0.001), + x, + xPrime, + v, + shakeTolerance, + shakeUseSOR, + lincsNIter, + lincslincsExpansionOrder, + lincsWarnAngle); t_pbc pbc = GetParam(); // Cycle through all available runners for (const auto& runner : getRunners()) { - SCOPED_TRACE(formatString("Testing %s with %s PBC using %s.", testData->title_.c_str(), - c_pbcTypeNames[pbc.pbcType].c_str(), runner->name().c_str())); + SCOPED_TRACE(formatString("Testing %s with %s PBC using %s.", + testData->title_.c_str(), + c_pbcTypeNames[pbc.pbcType].c_str(), + runner->name().c_str())); testData->reset(); @@ -498,18 +558,36 @@ TEST_P(ConstraintsTest, ThreeConstraintsWithCentralAtom) int lincslincsExpansionOrder = 4; real lincsWarnAngle = 30.0; - std::unique_ptr testData = std::make_unique( - title, numAtoms, masses, constraints, constraintsR0, true, virialScaledRef, false, 0, - real(0.0), real(0.001), x, xPrime, v, shakeTolerance, shakeUseSOR, lincsNIter, - lincslincsExpansionOrder, lincsWarnAngle); + std::unique_ptr testData = + std::make_unique(title, + numAtoms, + masses, + constraints, + constraintsR0, + true, + virialScaledRef, + false, + 0, + real(0.0), + real(0.001), + x, + xPrime, + v, + shakeTolerance, + shakeUseSOR, + lincsNIter, + lincslincsExpansionOrder, + lincsWarnAngle); t_pbc pbc = GetParam(); // Cycle through all available runners for (const auto& runner : getRunners()) { - SCOPED_TRACE(formatString("Testing %s with %s PBC using %s.", testData->title_.c_str(), - c_pbcTypeNames[pbc.pbcType].c_str(), runner->name().c_str())); + SCOPED_TRACE(formatString("Testing %s with %s PBC using %s.", + testData->title_.c_str(), + c_pbcTypeNames[pbc.pbcType].c_str(), + runner->name().c_str())); testData->reset(); @@ -556,18 +634,36 @@ TEST_P(ConstraintsTest, FourSequentialConstraints) int lincslincsExpansionOrder = 8; real lincsWarnAngle = 30.0; - std::unique_ptr testData = std::make_unique( - title, numAtoms, masses, constraints, constraintsR0, true, virialScaledRef, false, 0, - real(0.0), real(0.001), x, xPrime, v, shakeTolerance, shakeUseSOR, lincsNIter, - lincslincsExpansionOrder, lincsWarnAngle); + std::unique_ptr testData = + std::make_unique(title, + numAtoms, + masses, + constraints, + constraintsR0, + true, + virialScaledRef, + false, + 0, + real(0.0), + real(0.001), + x, + xPrime, + v, + shakeTolerance, + shakeUseSOR, + lincsNIter, + lincslincsExpansionOrder, + lincsWarnAngle); t_pbc pbc = GetParam(); // Cycle through all available runners for (const auto& runner : getRunners()) { - SCOPED_TRACE(formatString("Testing %s with %s PBC using %s.", testData->title_.c_str(), - c_pbcTypeNames[pbc.pbcType].c_str(), runner->name().c_str())); + SCOPED_TRACE(formatString("Testing %s with %s PBC using %s.", + testData->title_.c_str(), + c_pbcTypeNames[pbc.pbcType].c_str(), + runner->name().c_str())); testData->reset(); @@ -613,18 +709,36 @@ TEST_P(ConstraintsTest, TriangleOfConstraints) int lincslincsExpansionOrder = 4; real lincsWarnAngle = 30.0; - std::unique_ptr testData = std::make_unique( - title, numAtoms, masses, constraints, constraintsR0, true, virialScaledRef, false, 0, - real(0.0), real(0.001), x, xPrime, v, shakeTolerance, shakeUseSOR, lincsNIter, - lincslincsExpansionOrder, lincsWarnAngle); + std::unique_ptr testData = + std::make_unique(title, + numAtoms, + masses, + constraints, + constraintsR0, + true, + virialScaledRef, + false, + 0, + real(0.0), + real(0.001), + x, + xPrime, + v, + shakeTolerance, + shakeUseSOR, + lincsNIter, + lincslincsExpansionOrder, + lincsWarnAngle); t_pbc pbc = GetParam(); // Cycle through all available runners for (const auto& runner : getRunners()) { - SCOPED_TRACE(formatString("Testing %s with %s PBC using %s.", testData->title_.c_str(), - c_pbcTypeNames[pbc.pbcType].c_str(), runner->name().c_str())); + SCOPED_TRACE(formatString("Testing %s with %s PBC using %s.", + testData->title_.c_str(), + c_pbcTypeNames[pbc.pbcType].c_str(), + runner->name().c_str())); testData->reset(); diff --git a/src/gromacs/mdlib/tests/constrtestrunners.cpp b/src/gromacs/mdlib/tests/constrtestrunners.cpp index f57a9de20d..d8b0bfc53c 100644 --- a/src/gromacs/mdlib/tests/constrtestrunners.cpp +++ b/src/gromacs/mdlib/tests/constrtestrunners.cpp @@ -84,11 +84,24 @@ void ShakeConstraintsRunner::applyConstraints(ConstraintsTestData* testData, t_p { shakedata shaked; make_shake_sblock_serial(&shaked, testData->idef_.get(), testData->numAtoms_); - bool success = constrain_shake( - nullptr, &shaked, testData->invmass_.data(), *testData->idef_, testData->ir_, testData->x_, - testData->xPrime_, testData->xPrime2_, nullptr, &testData->nrnb_, testData->lambda_, - &testData->dHdLambda_, testData->invdt_, testData->v_, testData->computeVirial_, - testData->virialScaled_, false, gmx::ConstraintVariable::Positions); + bool success = constrain_shake(nullptr, + &shaked, + testData->invmass_.data(), + *testData->idef_, + testData->ir_, + testData->x_, + testData->xPrime_, + testData->xPrime2_, + nullptr, + &testData->nrnb_, + testData->lambda_, + &testData->dHdLambda_, + testData->invdt_, + testData->v_, + testData->computeVirial_, + testData->virialScaled_, + false, + gmx::ConstraintVariable::Positions); EXPECT_TRUE(success) << "Test failed with a false return value in SHAKE."; } @@ -114,24 +127,50 @@ void LincsConstraintsRunner::applyConstraints(ConstraintsTestData* testData, t_p for (const gmx_moltype_t& moltype : testData->mtop_.moltype) { // This function is in constr.cpp - at2con_mt.push_back(make_at2con(moltype, testData->mtop_.ffparams.iparams, + at2con_mt.push_back(make_at2con(moltype, + testData->mtop_.ffparams.iparams, flexibleConstraintTreatment(EI_DYNAMICS(testData->ir_.eI)))); } // Initialize LINCS - lincsd = init_lincs(nullptr, testData->mtop_, testData->nflexcon_, at2con_mt, false, - testData->ir_.nLincsIter, testData->ir_.nProjOrder); - set_lincs(*testData->idef_, testData->numAtoms_, testData->invmass_.data(), testData->lambda_, - EI_DYNAMICS(testData->ir_.eI), &cr, lincsd); + lincsd = init_lincs(nullptr, + testData->mtop_, + testData->nflexcon_, + at2con_mt, + false, + testData->ir_.nLincsIter, + testData->ir_.nProjOrder); + set_lincs(*testData->idef_, + testData->numAtoms_, + testData->invmass_.data(), + testData->lambda_, + EI_DYNAMICS(testData->ir_.eI), + &cr, + lincsd); // Evaluate constraints - bool success = constrain_lincs( - false, testData->ir_, 0, lincsd, testData->invmass_.data(), &cr, &ms, - testData->x_.arrayRefWithPadding(), testData->xPrime_.arrayRefWithPadding(), - testData->xPrime2_.arrayRefWithPadding().unpaddedArrayRef(), pbc.box, &pbc, - testData->hasMassPerturbed_, testData->lambda_, &testData->dHdLambda_, testData->invdt_, - testData->v_.arrayRefWithPadding().unpaddedArrayRef(), testData->computeVirial_, - testData->virialScaled_, gmx::ConstraintVariable::Positions, &testData->nrnb_, maxwarn, - &warncount_lincs); + bool success = constrain_lincs(false, + testData->ir_, + 0, + lincsd, + testData->invmass_.data(), + &cr, + &ms, + testData->x_.arrayRefWithPadding(), + testData->xPrime_.arrayRefWithPadding(), + testData->xPrime2_.arrayRefWithPadding().unpaddedArrayRef(), + pbc.box, + &pbc, + testData->hasMassPerturbed_, + testData->lambda_, + &testData->dHdLambda_, + testData->invdt_, + testData->v_.arrayRefWithPadding().unpaddedArrayRef(), + testData->computeVirial_, + testData->virialScaled_, + gmx::ConstraintVariable::Positions, + &testData->nrnb_, + maxwarn, + &warncount_lincs); EXPECT_TRUE(success) << "Test failed with a false return value in LINCS."; EXPECT_EQ(warncount_lincs, 0) << "There were warnings in LINCS."; done_lincs(lincsd); diff --git a/src/gromacs/mdlib/tests/constrtestrunners.cu b/src/gromacs/mdlib/tests/constrtestrunners.cu index 88cc8e866d..94be8b35f9 100644 --- a/src/gromacs/mdlib/tests/constrtestrunners.cu +++ b/src/gromacs/mdlib/tests/constrtestrunners.cu @@ -68,8 +68,8 @@ void LincsDeviceConstraintsRunner::applyConstraints(ConstraintsTestData* testDat const DeviceStream& deviceStream = testDevice_.deviceStream(); setActiveDevice(testDevice_.deviceInfo()); - auto lincsGpu = std::make_unique(testData->ir_.nLincsIter, testData->ir_.nProjOrder, - deviceContext, deviceStream); + auto lincsGpu = std::make_unique( + testData->ir_.nLincsIter, testData->ir_.nProjOrder, deviceContext, deviceStream); bool updateVelocities = true; int numAtoms = testData->numAtoms_; @@ -83,24 +83,24 @@ void LincsDeviceConstraintsRunner::applyConstraints(ConstraintsTestData* testDat allocateDeviceBuffer(&d_xp, numAtoms, deviceContext); allocateDeviceBuffer(&d_v, numAtoms, deviceContext); - copyToDeviceBuffer(&d_x, (float3*)(testData->x_.data()), 0, numAtoms, deviceStream, - GpuApiCallBehavior::Sync, nullptr); - copyToDeviceBuffer(&d_xp, (float3*)(testData->xPrime_.data()), 0, numAtoms, deviceStream, - GpuApiCallBehavior::Sync, nullptr); + copyToDeviceBuffer( + &d_x, (float3*)(testData->x_.data()), 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr); + copyToDeviceBuffer( + &d_xp, (float3*)(testData->xPrime_.data()), 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr); if (updateVelocities) { - copyToDeviceBuffer(&d_v, (float3*)(testData->v_.data()), 0, numAtoms, deviceStream, - GpuApiCallBehavior::Sync, nullptr); + copyToDeviceBuffer( + &d_v, (float3*)(testData->v_.data()), 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr); } - lincsGpu->apply(d_x, d_xp, updateVelocities, d_v, testData->invdt_, testData->computeVirial_, - testData->virialScaled_, pbcAiuc); + lincsGpu->apply( + d_x, d_xp, updateVelocities, d_v, testData->invdt_, testData->computeVirial_, testData->virialScaled_, pbcAiuc); - copyFromDeviceBuffer((float3*)(testData->xPrime_.data()), &d_xp, 0, numAtoms, deviceStream, - GpuApiCallBehavior::Sync, nullptr); + copyFromDeviceBuffer( + (float3*)(testData->xPrime_.data()), &d_xp, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr); if (updateVelocities) { - copyFromDeviceBuffer((float3*)(testData->v_.data()), &d_v, 0, numAtoms, deviceStream, - GpuApiCallBehavior::Sync, nullptr); + copyFromDeviceBuffer( + (float3*)(testData->v_.data()), &d_v, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr); } freeDeviceBuffer(&d_x); diff --git a/src/gromacs/mdlib/tests/energyoutput.cpp b/src/gromacs/mdlib/tests/energyoutput.cpp index 4ebb7eb445..0d70031606 100644 --- a/src/gromacs/mdlib/tests/energyoutput.cpp +++ b/src/gromacs/mdlib/tests/energyoutput.cpp @@ -374,8 +374,8 @@ public: // TODO EnergyOutput should not take Constraints object // TODO This object will always return zero as RMSD value. // It is more relevant to have non-zero value for testing. - constraints_ = makeConstraints(mtop_, inputrec_, nullptr, false, nullptr, &cr_, nullptr, - nullptr, nullptr, false); + constraints_ = makeConstraints( + mtop_, inputrec_, nullptr, false, nullptr, &cr_, nullptr, nullptr, nullptr, false); } /*! \brief Helper function to generate synthetic data to output @@ -625,25 +625,47 @@ TEST_P(EnergyOutputTest, CheckOutput) } MdModulesNotifier mdModulesNotifier; - std::unique_ptr energyOutput = std::make_unique( - energyFile_, &mtop_, &inputrec_, nullptr, nullptr, parameters.isRerun, - StartingBehavior::NewSimulation, false, mdModulesNotifier); + std::unique_ptr energyOutput = + std::make_unique(energyFile_, + &mtop_, + &inputrec_, + nullptr, + nullptr, + parameters.isRerun, + StartingBehavior::NewSimulation, + false, + mdModulesNotifier); // Add synthetic data for a single step double testValue = 10.0; for (int frame = 0; frame < parameters.numFrames; frame++) { setStepData(&testValue); - energyOutput->addDataAtEnergyStep( - false, true, time_, tmass_, enerdata_.get(), nullptr, nullptr, box_, - PTCouplingArrays({ state_.boxv, state_.nosehoover_xi, state_.nosehoover_vxi, - state_.nhpres_xi, state_.nhpres_vxi }), - state_.fep_state, constraintsVirial_, forceVirial_, totalVirial_, pressure_, - &ekindata_, muTotal_, constraints_.get()); + energyOutput->addDataAtEnergyStep(false, + true, + time_, + tmass_, + enerdata_.get(), + nullptr, + nullptr, + box_, + PTCouplingArrays({ state_.boxv, + state_.nosehoover_xi, + state_.nosehoover_vxi, + state_.nhpres_xi, + state_.nhpres_vxi }), + state_.fep_state, + constraintsVirial_, + forceVirial_, + totalVirial_, + pressure_, + &ekindata_, + muTotal_, + constraints_.get()); energyOutput->printAnnealingTemperatures(log_, &mtop_.groups, &inputrec_.opts); - energyOutput->printStepToEnergyFile(energyFile_, true, false, false, log_, 100 * frame, - time_, nullptr, nullptr); + energyOutput->printStepToEnergyFile( + energyFile_, true, false, false, log_, 100 * frame, time_, nullptr, nullptr); time_ += 1.0; } diff --git a/src/gromacs/mdlib/tests/leapfrog.cpp b/src/gromacs/mdlib/tests/leapfrog.cpp index 85822ebe81..504b9600c2 100644 --- a/src/gromacs/mdlib/tests/leapfrog.cpp +++ b/src/gromacs/mdlib/tests/leapfrog.cpp @@ -228,15 +228,28 @@ TEST_P(LeapFrogTest, SimpleIntegration) "groups and " "%s pressure coupling (dt = %f, v0=(%f, %f, %f), f0=(%f, %f, %f), nstpcouple = " "%d)", - runner->hardwareDescription().c_str(), parameters.numAtoms, parameters.numSteps, - parameters.numTCoupleGroups, parameters.nstpcouple == 0 ? "without" : "with", - parameters.timestep, parameters.v[XX], parameters.v[YY], parameters.v[ZZ], - parameters.f[XX], parameters.f[YY], parameters.f[ZZ], parameters.nstpcouple); + runner->hardwareDescription().c_str(), + parameters.numAtoms, + parameters.numSteps, + parameters.numTCoupleGroups, + parameters.nstpcouple == 0 ? "without" : "with", + parameters.timestep, + parameters.v[XX], + parameters.v[YY], + parameters.v[ZZ], + parameters.f[XX], + parameters.f[YY], + parameters.f[ZZ], + parameters.nstpcouple); SCOPED_TRACE(testDescription); - std::unique_ptr testData = std::make_unique( - parameters.numAtoms, parameters.timestep, parameters.v, parameters.f, - parameters.numTCoupleGroups, parameters.nstpcouple); + std::unique_ptr testData = + std::make_unique(parameters.numAtoms, + parameters.timestep, + parameters.v, + parameters.f, + parameters.numTCoupleGroups, + parameters.nstpcouple); runner->integrate(testData.get(), parameters.numSteps); diff --git a/src/gromacs/mdlib/tests/leapfrogtestrunners.cpp b/src/gromacs/mdlib/tests/leapfrogtestrunners.cpp index a9739e6028..8bc5f7f807 100644 --- a/src/gromacs/mdlib/tests/leapfrogtestrunners.cpp +++ b/src/gromacs/mdlib/tests/leapfrogtestrunners.cpp @@ -71,12 +71,19 @@ void LeapFrogHostTestRunner::integrate(LeapFrogTestData* testData, int numSteps) for (int step = 0; step < numSteps; step++) { - testData->update_->update_coords( - testData->inputRecord_, step, &testData->mdAtoms_, &testData->state_, testData->f_, - testData->forceCalculationData_, &testData->kineticEnergyData_, - testData->velocityScalingMatrix_, etrtNONE, nullptr, false); - testData->update_->finish_update(testData->inputRecord_, &testData->mdAtoms_, - &testData->state_, nullptr, false); + testData->update_->update_coords(testData->inputRecord_, + step, + &testData->mdAtoms_, + &testData->state_, + testData->f_, + testData->forceCalculationData_, + &testData->kineticEnergyData_, + testData->velocityScalingMatrix_, + etrtNONE, + nullptr, + false); + testData->update_->finish_update( + testData->inputRecord_, &testData->mdAtoms_, &testData->state_, nullptr, false); } const auto xp = makeArrayRef(*testData->update_->xp()).subArray(0, testData->numAtoms_); for (int i = 0; i < testData->numAtoms_; i++) diff --git a/src/gromacs/mdlib/tests/leapfrogtestrunners_gpu.cpp b/src/gromacs/mdlib/tests/leapfrogtestrunners_gpu.cpp index 1e102035d6..f88ae219ce 100644 --- a/src/gromacs/mdlib/tests/leapfrogtestrunners_gpu.cpp +++ b/src/gromacs/mdlib/tests/leapfrogtestrunners_gpu.cpp @@ -97,8 +97,10 @@ void LeapFrogDeviceTestRunner::integrate(LeapFrogTestData* testData, int numStep auto integrator = std::make_unique(deviceContext, deviceStream); - integrator->set(testData->numAtoms_, testData->inverseMasses_.data(), - testData->numTCoupleGroups_, testData->mdAtoms_.cTC); + integrator->set(testData->numAtoms_, + testData->inverseMasses_.data(), + testData->numTCoupleGroups_, + testData->mdAtoms_.cTC); bool doTempCouple = testData->numTCoupleGroups_ > 0; for (int step = 0; step < numSteps; step++) @@ -107,9 +109,16 @@ void LeapFrogDeviceTestRunner::integrate(LeapFrogTestData* testData, int numStep bool doPressureCouple = testData->doPressureCouple_ && do_per_step(step + testData->inputRecord_.nstpcouple - 1, testData->inputRecord_.nstpcouple); - integrator->integrate(d_x, d_xp, d_v, d_f, testData->timestep_, doTempCouple, - testData->kineticEnergyData_.tcstat, doPressureCouple, - testData->dtPressureCouple_, testData->velocityScalingMatrix_); + integrator->integrate(d_x, + d_xp, + d_v, + d_f, + testData->timestep_, + doTempCouple, + testData->kineticEnergyData_.tcstat, + doPressureCouple, + testData->dtPressureCouple_, + testData->velocityScalingMatrix_); } copyFromDeviceBuffer(h_xp, &d_x, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr); diff --git a/src/gromacs/mdlib/tests/settle.cpp b/src/gromacs/mdlib/tests/settle.cpp index e565b52848..1d71b0f420 100644 --- a/src/gromacs/mdlib/tests/settle.cpp +++ b/src/gromacs/mdlib/tests/settle.cpp @@ -335,8 +335,11 @@ TEST_P(SettleTest, SatisfiesConstraints) // being tested, to help make failing tests comprehensible. std::string testDescription = formatString( "Testing %s with %d SETTLEs, %s, %svelocities and %scalculating the virial.", - runner->hardwareDescription().c_str(), numSettles, pbcName.c_str(), - updateVelocities ? "with " : "without ", calcVirial ? "" : "not "); + runner->hardwareDescription().c_str(), + numSettles, + pbcName.c_str(), + updateVelocities ? "with " : "without ", + calcVirial ? "" : "not "); SCOPED_TRACE(testDescription); diff --git a/src/gromacs/mdlib/tests/settletestrunners.cpp b/src/gromacs/mdlib/tests/settletestrunners.cpp index cfc2b0ca20..6dc80bf66e 100644 --- a/src/gromacs/mdlib/tests/settletestrunners.cpp +++ b/src/gromacs/mdlib/tests/settletestrunners.cpp @@ -65,16 +65,25 @@ void SettleHostTestRunner::applySettle(SettleTestData* testData, { SettleData settled(testData->mtop_); - settled.setConstraints(testData->idef_->il[F_SETTLE], testData->numAtoms_, - testData->masses_.data(), testData->inverseMasses_.data()); + settled.setConstraints(testData->idef_->il[F_SETTLE], + testData->numAtoms_, + testData->masses_.data(), + testData->inverseMasses_.data()); bool errorOccured; int numThreads = 1; int threadIndex = 0; - csettle(settled, numThreads, threadIndex, &pbc, testData->x_.arrayRefWithPadding(), - testData->xPrime_.arrayRefWithPadding(), testData->reciprocalTimeStep_, + csettle(settled, + numThreads, + threadIndex, + &pbc, + testData->x_.arrayRefWithPadding(), + testData->xPrime_.arrayRefWithPadding(), + testData->reciprocalTimeStep_, updateVelocities ? testData->v_.arrayRefWithPadding() : ArrayRefWithPadding(), - calcVirial, testData->virial_, &errorOccured); + calcVirial, + testData->virial_, + &errorOccured); EXPECT_FALSE(errorOccured) << testDescription; } diff --git a/src/gromacs/mdlib/tests/settletestrunners.cu b/src/gromacs/mdlib/tests/settletestrunners.cu index 1200626ad0..0d2a3e116b 100644 --- a/src/gromacs/mdlib/tests/settletestrunners.cu +++ b/src/gromacs/mdlib/tests/settletestrunners.cu @@ -101,14 +101,14 @@ void SettleDeviceTestRunner::applySettle(SettleTestData* testData, { copyToDeviceBuffer(&d_v, (float3*)h_v, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr); } - settleGpu->apply(d_x, d_xp, updateVelocities, d_v, testData->reciprocalTimeStep_, calcVirial, - testData->virial_, pbcAiuc); + settleGpu->apply( + d_x, d_xp, updateVelocities, d_v, testData->reciprocalTimeStep_, calcVirial, testData->virial_, pbcAiuc); copyFromDeviceBuffer((float3*)h_xp, &d_xp, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr); if (updateVelocities) { - copyFromDeviceBuffer((float3*)h_v, &d_v, 0, numAtoms, deviceStream, - GpuApiCallBehavior::Sync, nullptr); + copyFromDeviceBuffer( + (float3*)h_v, &d_v, 0, numAtoms, deviceStream, GpuApiCallBehavior::Sync, nullptr); } freeDeviceBuffer(&d_x); diff --git a/src/gromacs/mdlib/tests/shake.cpp b/src/gromacs/mdlib/tests/shake.cpp index 4d29a38f91..50ef3e0fb2 100644 --- a/src/gromacs/mdlib/tests/shake.cpp +++ b/src/gromacs/mdlib/tests/shake.cpp @@ -195,10 +195,20 @@ public: int numIterations = 0; int numErrors = 0; - cshake(iatom.data(), numConstraints, &numIterations, ShakeTest::maxNumIterations_, - constrainedDistancesSquared, finalPositions, nullptr, initialDisplacements, - halfOfReducedMasses, omega_, inverseMasses.data(), distanceSquaredTolerances, - lagrangianValues, &numErrors); + cshake(iatom.data(), + numConstraints, + &numIterations, + ShakeTest::maxNumIterations_, + constrainedDistancesSquared, + finalPositions, + nullptr, + initialDisplacements, + halfOfReducedMasses, + omega_, + inverseMasses.data(), + distanceSquaredTolerances, + lagrangianValues, + &numErrors); std::vector finalDisplacements = computeDisplacements(iatom, finalPositions); std::vector finalDistancesSquared = computeDistancesSquared(finalDisplacements); @@ -218,7 +228,8 @@ public: + coordMax * GMX_REAL_EPS); // Assert that the constrained distances are within the required tolerance EXPECT_FLOAT_EQ_TOL(std::sqrt(constrainedDistancesSquared[i]), - std::sqrt(finalDistancesSquared[i]), constraintTolerance); + std::sqrt(finalDistancesSquared[i]), + constraintTolerance); } } diff --git a/src/gromacs/mdlib/trajectory_writing.cpp b/src/gromacs/mdlib/trajectory_writing.cpp index f0f9f25fda..3883006ca1 100644 --- a/src/gromacs/mdlib/trajectory_writing.cpp +++ b/src/gromacs/mdlib/trajectory_writing.cpp @@ -146,8 +146,8 @@ void do_md_trajectory_writing(FILE* fplog, // Note that part of the following code is duplicated in StatePropagatorData::trajectoryWriterTeardown. // This duplication is needed while both legacy and modular code paths are in use. // TODO: Remove duplication asap, make sure to keep in sync in the meantime. - mdoutf_write_to_trajectory_files(fplog, cr, outf, mdof_flags, top_global->natoms, step, t, state, - state_global, observablesHistory, f, &checkpointDataHolder); + mdoutf_write_to_trajectory_files( + fplog, cr, outf, mdof_flags, top_global->natoms, step, t, state, state_global, observablesHistory, f, &checkpointDataHolder); if (bLastStep && step_rel == ir->nsteps && bDoConfOut && MASTER(cr) && !bRerunMD) { if (fr->bMolPBC && state == state_global) @@ -179,8 +179,13 @@ void do_md_trajectory_writing(FILE* fplog, /* Make molecules whole only for confout writing */ do_pbc_mtop(ir->pbcType, state->box, top_global, x_for_confout); } - write_sto_conf_mtop(ftp2fn(efSTO, nfile, fnm), *top_global->name, top_global, - x_for_confout, state_global->v.rvec_array(), ir->pbcType, state->box); + write_sto_conf_mtop(ftp2fn(efSTO, nfile, fnm), + *top_global->name, + top_global, + x_for_confout, + state_global->v.rvec_array(), + ir->pbcType, + state->box); if (fr->bMolPBC && state == state_global) { sfree(x_for_confout); diff --git a/src/gromacs/mdlib/update.cpp b/src/gromacs/mdlib/update.cpp index 46f848d4e7..9617f6e1a4 100644 --- a/src/gromacs/mdlib/update.cpp +++ b/src/gromacs/mdlib/update.cpp @@ -212,8 +212,8 @@ void Update::update_coords(const t_inputrec& inpu const t_commrec* cr, const bool haveConstraints) { - return impl_->update_coords(inputRecord, step, md, state, f, fcdata, ekind, M, updatePart, cr, - haveConstraints); + return impl_->update_coords( + inputRecord, step, md, state, f, fcdata, ekind, M, updatePart, cr, haveConstraints); } void Update::finish_update(const t_inputrec& inputRecord, @@ -237,8 +237,8 @@ void Update::update_sd_second_half(const t_inputrec& inputRecord, bool do_log, bool do_ene) { - return impl_->update_sd_second_half(inputRecord, step, dvdlambda, md, state, cr, nrnb, wcycle, - constr, do_log, do_ene); + return impl_->update_sd_second_half( + inputRecord, step, dvdlambda, md, state, cr, nrnb, wcycle, constr, do_log, do_ene); } void Update::update_for_constraint_virial(const t_inputrec& inputRecord, @@ -673,21 +673,18 @@ static void do_update_md(int start, if (!doAcceleration) { - updateMDLeapfrogGeneral(start, nrend, doNoseHoover, dt, - dtPressureCouple, accel, md, ekind, box, x, - xprime, v, f, nh_vxi, nsttcouple, stepM); + updateMDLeapfrogGeneral( + start, nrend, doNoseHoover, dt, dtPressureCouple, accel, md, ekind, box, x, xprime, v, f, nh_vxi, nsttcouple, stepM); } else if (ekind->bNEMD) { updateMDLeapfrogGeneral( - start, nrend, doNoseHoover, dt, dtPressureCouple, accel, md, ekind, box, x, - xprime, v, f, nh_vxi, nsttcouple, stepM); + start, nrend, doNoseHoover, dt, dtPressureCouple, accel, md, ekind, box, x, xprime, v, f, nh_vxi, nsttcouple, stepM); } else { updateMDLeapfrogGeneral( - start, nrend, doNoseHoover, dt, dtPressureCouple, accel, md, ekind, box, x, - xprime, v, f, nh_vxi, nsttcouple, stepM); + start, nrend, doNoseHoover, dt, dtPressureCouple, accel, md, ekind, box, x, xprime, v, f, nh_vxi, nsttcouple, stepM); } } else @@ -731,17 +728,13 @@ static void do_update_md(int start, if (haveSingleTempScaleValue) { - updateMDLeapfrogSimple( - start, nrend, dt, dtPressureCouple, invMassPerDim, tcstat, cTC, diagM, x, - xprime, v, f); + updateMDLeapfrogSimple( + start, nrend, dt, dtPressureCouple, invMassPerDim, tcstat, cTC, diagM, x, xprime, v, f); } else { - updateMDLeapfrogSimple( - start, nrend, dt, dtPressureCouple, invMassPerDim, tcstat, cTC, diagM, x, - xprime, v, f); + updateMDLeapfrogSimple( + start, nrend, dt, dtPressureCouple, invMassPerDim, tcstat, cTC, diagM, x, xprime, v, f); } } else @@ -763,18 +756,14 @@ static void do_update_md(int start, else #endif { - updateMDLeapfrogSimple( - start, nrend, dt, dtPressureCouple, invMassPerDim, tcstat, cTC, nullptr, - x, xprime, v, f); + updateMDLeapfrogSimple( + start, nrend, dt, dtPressureCouple, invMassPerDim, tcstat, cTC, nullptr, x, xprime, v, f); } } else { - updateMDLeapfrogSimple( - start, nrend, dt, dtPressureCouple, invMassPerDim, tcstat, cTC, nullptr, x, - xprime, v, f); + updateMDLeapfrogSimple( + start, nrend, dt, dtPressureCouple, invMassPerDim, tcstat, cTC, nullptr, x, xprime, v, f); } } } @@ -799,8 +788,8 @@ static void doUpdateMDDoNotUpdateVelocities(int start, #if GMX_HAVE_SIMD_UPDATE if (!md.havePartiallyFrozenAtoms) { - updateMDLeapfrogSimpleSimd(start, nrend, dt, md.invmass, tcstat, - x, xprime, v, f); + updateMDLeapfrogSimpleSimd( + start, nrend, dt, md.invmass, tcstat, x, xprime, v, f); } else #endif @@ -1160,15 +1149,29 @@ static void do_update_sd(int start, if (haveConstraints) { // With constraints, the SD update is done in 2 parts - doSDUpdateGeneral(sd, start, nrend, dt, accel, nFreeze, invmass, - ptype, cFREEZE, cACC, nullptr, x, xprime, v, f, - step, seed, nullptr); + doSDUpdateGeneral( + sd, start, nrend, dt, accel, nFreeze, invmass, ptype, cFREEZE, cACC, nullptr, x, xprime, v, f, step, seed, nullptr); } else { - doSDUpdateGeneral( - sd, start, nrend, dt, accel, nFreeze, invmass, ptype, cFREEZE, cACC, cTC, x, xprime, - v, f, step, seed, DOMAINDECOMP(cr) ? cr->dd->globalAtomIndices.data() : nullptr); + doSDUpdateGeneral(sd, + start, + nrend, + dt, + accel, + nFreeze, + invmass, + ptype, + cFREEZE, + cACC, + cTC, + x, + xprime, + v, + f, + step, + seed, + DOMAINDECOMP(cr) ? cr->dd->globalAtomIndices.data() : nullptr); } } @@ -1308,19 +1311,23 @@ void restore_ekinstate_from_state(const t_commrec* cr, gmx_ekindata_t* ekind, co gmx_bcast(sizeof(n), &n, cr->mpi_comm_mygroup); for (i = 0; i < n; i++) { - gmx_bcast(DIM * DIM * sizeof(ekind->tcstat[i].ekinh[0][0]), ekind->tcstat[i].ekinh[0], + gmx_bcast(DIM * DIM * sizeof(ekind->tcstat[i].ekinh[0][0]), + ekind->tcstat[i].ekinh[0], cr->mpi_comm_mygroup); - gmx_bcast(DIM * DIM * sizeof(ekind->tcstat[i].ekinf[0][0]), ekind->tcstat[i].ekinf[0], + gmx_bcast(DIM * DIM * sizeof(ekind->tcstat[i].ekinf[0][0]), + ekind->tcstat[i].ekinf[0], cr->mpi_comm_mygroup); gmx_bcast(DIM * DIM * sizeof(ekind->tcstat[i].ekinh_old[0][0]), - ekind->tcstat[i].ekinh_old[0], cr->mpi_comm_mygroup); - - gmx_bcast(sizeof(ekind->tcstat[i].ekinscalef_nhc), &(ekind->tcstat[i].ekinscalef_nhc), + ekind->tcstat[i].ekinh_old[0], cr->mpi_comm_mygroup); - gmx_bcast(sizeof(ekind->tcstat[i].ekinscaleh_nhc), &(ekind->tcstat[i].ekinscaleh_nhc), + + gmx_bcast(sizeof(ekind->tcstat[i].ekinscalef_nhc), + &(ekind->tcstat[i].ekinscalef_nhc), cr->mpi_comm_mygroup); - gmx_bcast(sizeof(ekind->tcstat[i].vscale_nhc), &(ekind->tcstat[i].vscale_nhc), + gmx_bcast(sizeof(ekind->tcstat[i].ekinscaleh_nhc), + &(ekind->tcstat[i].ekinscaleh_nhc), cr->mpi_comm_mygroup); + gmx_bcast(sizeof(ekind->tcstat[i].vscale_nhc), &(ekind->tcstat[i].vscale_nhc), cr->mpi_comm_mygroup); } gmx_bcast(DIM * DIM * sizeof(ekind->ekin[0][0]), ekind->ekin[0], cr->mpi_comm_mygroup); @@ -1388,9 +1395,23 @@ void Update::Impl::update_sd_second_half(const t_inputrec& inputRecord, getThreadAtomRange(nth, th, homenr, &start_th, &end_th); doSDUpdateGeneral( - sd_, start_th, end_th, dt, inputRecord.opts.acc, inputRecord.opts.nFreeze, - md->invmass, md->ptype, md->cFREEZE, nullptr, md->cTC, state->x.rvec_array(), - xp_.rvec_array(), state->v.rvec_array(), nullptr, step, inputRecord.ld_seed, + sd_, + start_th, + end_th, + dt, + inputRecord.opts.acc, + inputRecord.opts.nFreeze, + md->invmass, + md->ptype, + md->cFREEZE, + nullptr, + md->cTC, + state->x.rvec_array(), + xp_.rvec_array(), + state->v.rvec_array(), + nullptr, + step, + inputRecord.ld_seed, DOMAINDECOMP(cr) ? cr->dd->globalAtomIndices.data() : nullptr); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR @@ -1400,10 +1421,21 @@ void Update::Impl::update_sd_second_half(const t_inputrec& inputRecord, /* Constrain the coordinates upd->xp for half a time step */ bool computeVirial = false; - constr->apply(do_log, do_ene, step, 1, 0.5, state->x.arrayRefWithPadding(), - xp_.arrayRefWithPadding(), ArrayRef(), state->box, - state->lambda[efptBONDED], dvdlambda, state->v.arrayRefWithPadding(), - computeVirial, nullptr, ConstraintVariable::Positions); + constr->apply(do_log, + do_ene, + step, + 1, + 0.5, + state->x.arrayRefWithPadding(), + xp_.arrayRefWithPadding(), + ArrayRef(), + state->box, + state->lambda[efptBONDED], + dvdlambda, + state->v.arrayRefWithPadding(), + computeVirial, + nullptr, + ConstraintVariable::Positions); } } @@ -1513,21 +1545,63 @@ void Update::Impl::update_coords(const t_inputrec& switch (inputRecord.eI) { case (eiMD): - do_update_md(start_th, end_th, dt, step, x_rvec, xp_rvec, v_rvec, f_rvec, - inputRecord.opts.acc, inputRecord.etc, inputRecord.epc, - inputRecord.nsttcouple, inputRecord.nstpcouple, md, ekind, - state->box, state->nosehoover_vxi.data(), M); + do_update_md(start_th, + end_th, + dt, + step, + x_rvec, + xp_rvec, + v_rvec, + f_rvec, + inputRecord.opts.acc, + inputRecord.etc, + inputRecord.epc, + inputRecord.nsttcouple, + inputRecord.nstpcouple, + md, + ekind, + state->box, + state->nosehoover_vxi.data(), + M); break; case (eiSD1): - do_update_sd(start_th, end_th, dt, step, x_rvec, xp_rvec, v_rvec, f_rvec, - inputRecord.opts.acc, inputRecord.opts.nFreeze, md->invmass, - md->ptype, md->cFREEZE, md->cACC, md->cTC, inputRecord.ld_seed, cr, - sd_, haveConstraints); + do_update_sd(start_th, + end_th, + dt, + step, + x_rvec, + xp_rvec, + v_rvec, + f_rvec, + inputRecord.opts.acc, + inputRecord.opts.nFreeze, + md->invmass, + md->ptype, + md->cFREEZE, + md->cACC, + md->cTC, + inputRecord.ld_seed, + cr, + sd_, + haveConstraints); break; case (eiBD): - do_update_bd(start_th, end_th, dt, step, x_rvec, xp_rvec, v_rvec, f_rvec, - inputRecord.opts.nFreeze, md->invmass, md->ptype, md->cFREEZE, - md->cTC, inputRecord.bd_fric, sd_.bd_rf.data(), inputRecord.ld_seed, + do_update_bd(start_th, + end_th, + dt, + step, + x_rvec, + xp_rvec, + v_rvec, + f_rvec, + inputRecord.opts.nFreeze, + md->invmass, + md->ptype, + md->cFREEZE, + md->cTC, + inputRecord.bd_fric, + sd_.bd_rf.data(), + inputRecord.ld_seed, DOMAINDECOMP(cr) ? cr->dd->globalAtomIndices.data() : nullptr); break; case (eiVV): @@ -1542,14 +1616,33 @@ void Update::Impl::update_coords(const t_inputrec& { case etrtVELOCITY1: case etrtVELOCITY2: - do_update_vv_vel(start_th, end_th, dt, inputRecord.opts.acc, - inputRecord.opts.nFreeze, md->invmass, md->ptype, md->cFREEZE, - md->cACC, v_rvec, f_rvec, bExtended, state->veta, alpha); + do_update_vv_vel(start_th, + end_th, + dt, + inputRecord.opts.acc, + inputRecord.opts.nFreeze, + md->invmass, + md->ptype, + md->cFREEZE, + md->cACC, + v_rvec, + f_rvec, + bExtended, + state->veta, + alpha); break; case etrtPOSITION: - do_update_vv_pos(start_th, end_th, dt, inputRecord.opts.nFreeze, - md->ptype, md->cFREEZE, x_rvec, xp_rvec, v_rvec, - bExtended, state->veta); + do_update_vv_pos(start_th, + end_th, + dt, + inputRecord.opts.nFreeze, + md->ptype, + md->cFREEZE, + x_rvec, + xp_rvec, + v_rvec, + bExtended, + state->veta); break; } break; @@ -1588,8 +1681,8 @@ void Update::Impl::update_for_constraint_virial(const t_inputrec& inputRecord, rvec* v_rvec = const_cast(state.v.rvec_array()); const rvec* f_rvec = as_rvec_array(f.unpaddedConstArrayRef().data()); - doUpdateMDDoNotUpdateVelocities(start_th, end_th, dt, x_rvec, xp_rvec, v_rvec, f_rvec, - md, ekind); + doUpdateMDDoNotUpdateVelocities( + start_th, end_th, dt, x_rvec, xp_rvec, v_rvec, f_rvec, md, ekind); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR } diff --git a/src/gromacs/mdlib/update_constrain_gpu_impl.cu b/src/gromacs/mdlib/update_constrain_gpu_impl.cu index 825890ce82..ba27a8a58c 100644 --- a/src/gromacs/mdlib/update_constrain_gpu_impl.cu +++ b/src/gromacs/mdlib/update_constrain_gpu_impl.cu @@ -129,8 +129,8 @@ void UpdateConstrainGpu::Impl::integrate(GpuEventSynchronizer* fRead // The integrate should save a copy of the current coordinates in d_xp_ and write updated // once into d_x_. The d_xp_ is only needed by constraints. - integrator_->integrate(d_x_, d_xp_, d_v_, d_f_, dt, doTemperatureScaling, tcstat, - doParrinelloRahman, dtPressureCouple, prVelocityScalingMatrix); + integrator_->integrate( + d_x_, d_xp_, d_v_, d_f_, dt, doTemperatureScaling, tcstat, doParrinelloRahman, dtPressureCouple, prVelocityScalingMatrix); // Constraints need both coordinates before (d_x_) and after (d_xp_) update. However, after constraints // are applied, the d_x_ can be discarded. So we intentionally swap the d_x_ and d_xp_ here to avoid the // d_xp_ -> d_x_ copy after constraints. Note that the integrate saves them in the wrong order as well. @@ -170,8 +170,12 @@ void UpdateConstrainGpu::Impl::scaleCoordinates(const matrix scalingMatrix) const auto kernelArgs = prepareGpuKernelArguments( scaleCoordinates_kernel, coordinateScalingKernelLaunchConfig_, &numAtoms_, &d_x_, &mu); - launchGpuKernel(scaleCoordinates_kernel, coordinateScalingKernelLaunchConfig_, deviceStream_, - nullptr, "scaleCoordinates_kernel", kernelArgs); + launchGpuKernel(scaleCoordinates_kernel, + coordinateScalingKernelLaunchConfig_, + deviceStream_, + nullptr, + "scaleCoordinates_kernel", + kernelArgs); // TODO: Although this only happens on the pressure coupling steps, this synchronization // can affect the performance if nstpcouple is small. deviceStream_.synchronize(); @@ -195,8 +199,12 @@ void UpdateConstrainGpu::Impl::scaleVelocities(const matrix scalingMatrix) const auto kernelArgs = prepareGpuKernelArguments( scaleCoordinates_kernel, coordinateScalingKernelLaunchConfig_, &numAtoms_, &d_v_, &mu); - launchGpuKernel(scaleCoordinates_kernel, coordinateScalingKernelLaunchConfig_, deviceStream_, - nullptr, "scaleCoordinates_kernel", kernelArgs); + launchGpuKernel(scaleCoordinates_kernel, + coordinateScalingKernelLaunchConfig_, + deviceStream_, + nullptr, + "scaleCoordinates_kernel", + kernelArgs); // TODO: Although this only happens on the pressure coupling steps, this synchronization // can affect the performance if nstpcouple is small. deviceStream_.synchronize(); @@ -254,8 +262,8 @@ void UpdateConstrainGpu::Impl::set(DeviceBuffer d_x, reallocateDeviceBuffer(&d_xp_, numAtoms_, &numXp_, &numXpAlloc_, deviceContext_); - reallocateDeviceBuffer(&d_inverseMasses_, numAtoms_, &numInverseMasses_, - &numInverseMassesAlloc_, deviceContext_); + reallocateDeviceBuffer( + &d_inverseMasses_, numAtoms_, &numInverseMasses_, &numInverseMassesAlloc_, deviceContext_); // Integrator should also update something, but it does not even have a method yet integrator_->set(numAtoms_, md.invmass, numTempScaleValues, md.cTC); @@ -303,8 +311,16 @@ void UpdateConstrainGpu::integrate(GpuEventSynchronizer* fReadyOnDev const float dtPressureCouple, const matrix prVelocityScalingMatrix) { - impl_->integrate(fReadyOnDevice, dt, updateVelocities, computeVirial, virialScaled, doTemperatureScaling, - tcstat, doParrinelloRahman, dtPressureCouple, prVelocityScalingMatrix); + impl_->integrate(fReadyOnDevice, + dt, + updateVelocities, + computeVirial, + virialScaled, + doTemperatureScaling, + tcstat, + doParrinelloRahman, + dtPressureCouple, + prVelocityScalingMatrix); } void UpdateConstrainGpu::scaleCoordinates(const matrix scalingMatrix) diff --git a/src/gromacs/mdlib/update_vv.cpp b/src/gromacs/mdlib/update_vv.cpp index afc6b4d069..40b99699a8 100644 --- a/src/gromacs/mdlib/update_vv.cpp +++ b/src/gromacs/mdlib/update_vv.cpp @@ -130,8 +130,7 @@ void integrateVVFirstStep(int64_t step, * so that the input is actually the initial step. */ snew(vbuf, state->natoms); - copy_rvecn(state->v.rvec_array(), vbuf, 0, - state->natoms); /* should make this better for parallelizing? */ + copy_rvecn(state->v.rvec_array(), vbuf, 0, state->natoms); /* should make this better for parallelizing? */ } else { @@ -139,8 +138,8 @@ void integrateVVFirstStep(int64_t step, trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, MassQ, trotter_seq, ettTSEQ1); } - upd->update_coords(*ir, step, mdatoms, state, f->view().forceWithPadding(), fcdata, ekind, - M, etrtVELOCITY1, cr, constr != nullptr); + upd->update_coords( + *ir, step, mdatoms, state, f->view().forceWithPadding(), fcdata, ekind, M, etrtVELOCITY1, cr, constr != nullptr); wallcycle_stop(wcycle, ewcUPDATE); constrain_velocities(constr, do_log, do_ene, step, state, nullptr, bCalcVir, shake_vir); @@ -166,10 +165,28 @@ void integrateVVFirstStep(int64_t step, { wallcycle_stop(wcycle, ewcUPDATE); int totalNumberOfBondedInteractions = -1; - compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), - makeConstArrayRef(state->v), state->box, mdatoms, nrnb, vcm, wcycle, - enerd, force_vir, shake_vir, total_vir, pres, constr, nullSignaller, - state->box, &totalNumberOfBondedInteractions, bSumEkinhOld, + compute_globals(gstat, + cr, + ir, + fr, + ekind, + makeConstArrayRef(state->x), + makeConstArrayRef(state->v), + state->box, + mdatoms, + nrnb, + vcm, + wcycle, + enerd, + force_vir, + shake_vir, + total_vir, + pres, + constr, + nullSignaller, + state->box, + &totalNumberOfBondedInteractions, + bSumEkinhOld, (bGStat ? CGLO_GSTAT : 0) | (bCalcEner ? CGLO_ENERGY : 0) | (bTemp ? CGLO_TEMPERATURE : 0) | (bPres ? CGLO_PRESSURE : 0) | (bPres ? CGLO_CONSTRAINT : 0) | (bStopCM ? CGLO_STOPCM : 0) @@ -183,13 +200,18 @@ void integrateVVFirstStep(int64_t step, time step kinetic energy for the pressure (always true now, since we want accurate statistics). b) If we are using EkinAveEkin for the kinetic energy for the temperature control, we still feed in EkinAveVel because it's needed for the pressure */ - checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions, top_global, - &top, makeConstArrayRef(state->x), state->box, + checkNumberOfBondedInteractions(mdlog, + cr, + totalNumberOfBondedInteractions, + top_global, + &top, + makeConstArrayRef(state->x), + state->box, shouldCheckNumberOfBondedInteractions); if (bStopCM) { - process_and_stopcm_grp(fplog, vcm, *mdatoms, makeArrayRef(state->x), - makeArrayRef(state->v)); + process_and_stopcm_grp( + fplog, vcm, *mdatoms, makeArrayRef(state->x), makeArrayRef(state->v)); inc_nrnb(nrnb, eNR_STOPCM, mdatoms->homenr); } wallcycle_start(wcycle, ewcUPDATE); @@ -200,8 +222,7 @@ void integrateVVFirstStep(int64_t step, if (bTrotter) { m_add(force_vir, shake_vir, total_vir); /* we need the un-dispersion corrected total vir here */ - trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, MassQ, - trotter_seq, ettTSEQ2); + trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, MassQ, trotter_seq, ettTSEQ2); /* TODO This is only needed when we're about to write * a checkpoint, because we use it after the restart @@ -225,10 +246,29 @@ void integrateVVFirstStep(int64_t step, /* We need the kinetic energy at minus the half step for determining * the full step kinetic energy and possibly for T-coupling.*/ /* This may not be quite working correctly yet . . . . */ - compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), - makeConstArrayRef(state->v), state->box, mdatoms, nrnb, vcm, wcycle, - enerd, nullptr, nullptr, nullptr, nullptr, constr, nullSignaller, - state->box, nullptr, bSumEkinhOld, CGLO_GSTAT | CGLO_TEMPERATURE); + compute_globals(gstat, + cr, + ir, + fr, + ekind, + makeConstArrayRef(state->x), + makeConstArrayRef(state->v), + state->box, + mdatoms, + nrnb, + vcm, + wcycle, + enerd, + nullptr, + nullptr, + nullptr, + nullptr, + constr, + nullSignaller, + state->box, + nullptr, + bSumEkinhOld, + CGLO_GSTAT | CGLO_TEMPERATURE); wallcycle_start(wcycle, ewcUPDATE); } } @@ -293,8 +333,8 @@ void integrateVVSecondStep(int64_t step, gmx_wallcycle* wcycle) { /* velocity half-step update */ - upd->update_coords(*ir, step, mdatoms, state, f->view().forceWithPadding(), fcdata, ekind, M, - etrtVELOCITY2, cr, constr != nullptr); + upd->update_coords( + *ir, step, mdatoms, state, f->view().forceWithPadding(), fcdata, ekind, M, etrtVELOCITY2, cr, constr != nullptr); /* Above, initialize just copies ekinh into ekin, @@ -313,33 +353,52 @@ void integrateVVSecondStep(int64_t step, updatePrevStepPullCom(pull_work, state); } - upd->update_coords(*ir, step, mdatoms, state, f->view().forceWithPadding(), fcdata, ekind, M, - etrtPOSITION, cr, constr != nullptr); + upd->update_coords( + *ir, step, mdatoms, state, f->view().forceWithPadding(), fcdata, ekind, M, etrtPOSITION, cr, constr != nullptr); wallcycle_stop(wcycle, ewcUPDATE); - constrain_coordinates(constr, do_log, do_ene, step, state, upd->xp()->arrayRefWithPadding(), - dvdl_constr, bCalcVir, shake_vir); + constrain_coordinates( + constr, do_log, do_ene, step, state, upd->xp()->arrayRefWithPadding(), dvdl_constr, bCalcVir, shake_vir); - upd->update_sd_second_half(*ir, step, dvdl_constr, mdatoms, state, cr, nrnb, wcycle, constr, - do_log, do_ene); + upd->update_sd_second_half( + *ir, step, dvdl_constr, mdatoms, state, cr, nrnb, wcycle, constr, do_log, do_ene); upd->finish_update(*ir, mdatoms, state, wcycle, constr != nullptr); if (ir->eI == eiVVAK) { /* erase F_EKIN and F_TEMP here? */ /* just compute the kinetic energy at the half step to perform a trotter step */ - compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), - makeConstArrayRef(state->v), state->box, mdatoms, nrnb, vcm, wcycle, enerd, - force_vir, shake_vir, total_vir, pres, constr, nullSignaller, lastbox, - nullptr, bSumEkinhOld, (bGStat ? CGLO_GSTAT : 0) | CGLO_TEMPERATURE); + compute_globals(gstat, + cr, + ir, + fr, + ekind, + makeConstArrayRef(state->x), + makeConstArrayRef(state->v), + state->box, + mdatoms, + nrnb, + vcm, + wcycle, + enerd, + force_vir, + shake_vir, + total_vir, + pres, + constr, + nullSignaller, + lastbox, + nullptr, + bSumEkinhOld, + (bGStat ? CGLO_GSTAT : 0) | CGLO_TEMPERATURE); wallcycle_start(wcycle, ewcUPDATE); trotter_update(ir, step, ekind, enerd, state, total_vir, mdatoms, MassQ, trotter_seq, ettTSEQ4); /* now we know the scaling, we can compute the positions again */ std::copy(cbuf->begin(), cbuf->end(), state->x.begin()); - upd->update_coords(*ir, step, mdatoms, state, f->view().forceWithPadding(), fcdata, ekind, - M, etrtPOSITION, cr, constr != nullptr); + upd->update_coords( + *ir, step, mdatoms, state, f->view().forceWithPadding(), fcdata, ekind, M, etrtPOSITION, cr, constr != nullptr); wallcycle_stop(wcycle, ewcUPDATE); /* do we need an extra constraint here? just need to copy out of as_rvec_array(state->v.data()) to upd->xp? */ diff --git a/src/gromacs/mdlib/updategroups.cpp b/src/gromacs/mdlib/updategroups.cpp index cf4856825c..b8ed8dcadb 100644 --- a/src/gromacs/mdlib/updategroups.cpp +++ b/src/gromacs/mdlib/updategroups.cpp @@ -355,8 +355,8 @@ static RangePartitioning makeUpdateGroups(const gmx_moltype_t& moltype, gmx::Arr std::array ilistsCombined; ilistsCombined[F_CONSTR] = jointConstraintList(moltype); /* We "include" flexible constraints, but none are present (checked above) */ - const ListOfLists at2con = make_at2con(moltype.atoms.nr, ilistsCombined, iparams, - FlexibleConstraintTreatment::Include); + const ListOfLists at2con = make_at2con( + moltype.atoms.nr, ilistsCombined, iparams, FlexibleConstraintTreatment::Include); bool satisfiesCriteria = true; @@ -679,8 +679,8 @@ static real computeMaxUpdateGroupRadius(const gmx_moltype_t& moltype, */ if (numConstraints == 2 && allTypesAreEqual && temperature > 0) { - radius = constraintGroupRadius<2>(moltype, iparams, maxAtom, at2con, angleIndices, - maxConstraintLength, temperature); + radius = constraintGroupRadius<2>( + moltype, iparams, maxAtom, at2con, angleIndices, maxConstraintLength, temperature); } /* With 3 constraints the maximum possible radius is 1.4 times * the constraint length, so it is worth computing a smaller @@ -688,8 +688,8 @@ static real computeMaxUpdateGroupRadius(const gmx_moltype_t& moltype, */ if (numConstraints == 3 && allTypesAreEqual && temperature >= 0) { - radius = constraintGroupRadius<3>(moltype, iparams, maxAtom, at2con, angleIndices, - maxConstraintLength, temperature); + radius = constraintGroupRadius<3>( + moltype, iparams, maxAtom, at2con, angleIndices, maxConstraintLength, temperature); if (temperature == 0 && radius >= 0) { /* Add a 10% margin for deviation at 0 K */ @@ -740,8 +740,9 @@ real computeMaxUpdateGroupRadius(const gmx_mtop_t& mtop, for (size_t moltype = 0; moltype < mtop.moltype.size(); moltype++) { maxRadius = std::max( - maxRadius, computeMaxUpdateGroupRadius(mtop.moltype[moltype], mtop.ffparams.iparams, - updateGroups[moltype], temperature)); + maxRadius, + computeMaxUpdateGroupRadius( + mtop.moltype[moltype], mtop.ffparams.iparams, updateGroups[moltype], temperature)); } return maxRadius; diff --git a/src/gromacs/mdlib/vcm.cpp b/src/gromacs/mdlib/vcm.cpp index 63a3df664a..1f1691f1b8 100644 --- a/src/gromacs/mdlib/vcm.cpp +++ b/src/gromacs/mdlib/vcm.cpp @@ -64,8 +64,7 @@ t_vcm::t_vcm(const SimulationGroups& groups, const t_inputrec& ir) : if (mode == ecmANGULAR && ndim < 3) { - gmx_fatal(FARGS, "Can not have angular comm removal with pbc=%s", - c_pbcTypeNames[ir.pbcType].c_str()); + gmx_fatal(FARGS, "Can not have angular comm removal with pbc=%s", c_pbcTypeNames[ir.pbcType].c_str()); } if (mode != ecmNO) @@ -544,9 +543,13 @@ static void process_and_check_cm_grp(FILE* fp, t_vcm* vcm, real Temp_Max) if ((Temp_cm > Temp_Max) && fp) { - fprintf(fp, "Large VCM(group %s): %12.5f, %12.5f, %12.5f, Temp-cm: %12.5e\n", - vcm->group_name[g], vcm->group_v[g][XX], vcm->group_v[g][YY], - vcm->group_v[g][ZZ], Temp_cm); + fprintf(fp, + "Large VCM(group %s): %12.5f, %12.5f, %12.5f, Temp-cm: %12.5e\n", + vcm->group_name[g], + vcm->group_v[g][XX], + vcm->group_v[g][YY], + vcm->group_v[g][ZZ], + Temp_cm); } if (vcm->mode == ecmANGULAR) @@ -557,18 +560,37 @@ static void process_and_check_cm_grp(FILE* fp, t_vcm* vcm, real Temp_Max) { /* if we have an integrator that may not conserve momenta, skip */ tm = vcm->group_mass[g]; - fprintf(fp, "Group %s with mass %12.5e, Ekrot %12.5e Det(I) = %12.5e\n", - vcm->group_name[g], tm, ekrot, det(vcm->group_i[g])); - fprintf(fp, " COM: %12.5f %12.5f %12.5f\n", vcm->group_x[g][XX], - vcm->group_x[g][YY], vcm->group_x[g][ZZ]); - fprintf(fp, " P: %12.5f %12.5f %12.5f\n", vcm->group_p[g][XX], - vcm->group_p[g][YY], vcm->group_p[g][ZZ]); - fprintf(fp, " V: %12.5f %12.5f %12.5f\n", vcm->group_v[g][XX], - vcm->group_v[g][YY], vcm->group_v[g][ZZ]); - fprintf(fp, " J: %12.5f %12.5f %12.5f\n", vcm->group_j[g][XX], - vcm->group_j[g][YY], vcm->group_j[g][ZZ]); - fprintf(fp, " w: %12.5f %12.5f %12.5f\n", vcm->group_w[g][XX], - vcm->group_w[g][YY], vcm->group_w[g][ZZ]); + fprintf(fp, + "Group %s with mass %12.5e, Ekrot %12.5e Det(I) = %12.5e\n", + vcm->group_name[g], + tm, + ekrot, + det(vcm->group_i[g])); + fprintf(fp, + " COM: %12.5f %12.5f %12.5f\n", + vcm->group_x[g][XX], + vcm->group_x[g][YY], + vcm->group_x[g][ZZ]); + fprintf(fp, + " P: %12.5f %12.5f %12.5f\n", + vcm->group_p[g][XX], + vcm->group_p[g][YY], + vcm->group_p[g][ZZ]); + fprintf(fp, + " V: %12.5f %12.5f %12.5f\n", + vcm->group_v[g][XX], + vcm->group_v[g][YY], + vcm->group_v[g][ZZ]); + fprintf(fp, + " J: %12.5f %12.5f %12.5f\n", + vcm->group_j[g][XX], + vcm->group_j[g][YY], + vcm->group_j[g][ZZ]); + fprintf(fp, + " w: %12.5f %12.5f %12.5f\n", + vcm->group_w[g][XX], + vcm->group_w[g][YY], + vcm->group_w[g][ZZ]); pr_rvecs(fp, 0, "Inertia tensor", vcm->group_i[g], DIM); } } diff --git a/src/gromacs/mdlib/vsite.cpp b/src/gromacs/mdlib/vsite.cpp index 35628004ec..4a421847e6 100644 --- a/src/gromacs/mdlib/vsite.cpp +++ b/src/gromacs/mdlib/vsite.cpp @@ -791,8 +791,8 @@ static void construct_vsites(const ThreadingInfo* threadingInfo, */ ivec null_ivec; clear_ivec(null_ivec); - pbc_null = set_pbc_dd(&pbc, domainInfo.pbcType_, - useDomdec ? domainInfo.domdec_->numCells : null_ivec, FALSE, box); + pbc_null = set_pbc_dd( + &pbc, domainInfo.pbcType_, useDomdec ? domainInfo.domdec_->numCells : null_ivec, FALSE, box); } else { @@ -929,8 +929,8 @@ void constructVirtualSitesGlobal(const gmx_mtop_t& mtop, gmx::ArrayRef x, /* This is wasting some CPU time as we now do this multiple times * per MD step. */ - pbc_null = set_pbc_dd(&pbc, domainInfo_.pbcType_, - useDomdec ? domainInfo_.domdec_->numCells : nullptr, FALSE, box); + pbc_null = set_pbc_dd( + &pbc, domainInfo_.pbcType_, useDomdec ? domainInfo_.domdec_->numCells : nullptr, FALSE, box); } else { @@ -1920,8 +1920,15 @@ void VirtualSitesHandler::Impl::spreadForces(ArrayRef x, { /* First spread the vsites that might depend on non-local vsites */ auto& nlDependentVSites = threadingInfo_.threadDataNonLocalDependent(); - spreadForceWrapper(x, f, virialHandling, fshift, nlDependentVSites.dxdf, true, iparams_, - nlDependentVSites.ilist, pbc_null); + spreadForceWrapper(x, + f, + virialHandling, + fshift, + nlDependentVSites.dxdf, + true, + iparams_, + nlDependentVSites.ilist, + pbc_null); #pragma omp parallel num_threads(numThreads) { @@ -1966,8 +1973,15 @@ void VirtualSitesHandler::Impl::spreadForces(ArrayRef x, { copy_rvec(f[idTask->vsite[i]], idTask->force[idTask->vsite[i]]); } - spreadForceWrapper(x, idTask->force, virialHandling, fshift_t, tData.dxdf, true, - iparams_, tData.idTask.ilist, pbc_null); + spreadForceWrapper(x, + idTask->force, + virialHandling, + fshift_t, + tData.dxdf, + true, + iparams_, + tData.idTask.ilist, + pbc_null); /* We need a barrier before reducing forces below * that have been produced by a different thread above. @@ -2003,8 +2017,8 @@ void VirtualSitesHandler::Impl::spreadForces(ArrayRef x, } /* Spread the vsites that spread locally only */ - spreadForceWrapper(x, f, virialHandling, fshift_t, tData.dxdf, false, iparams_, - tData.ilist, pbc_null); + spreadForceWrapper( + x, f, virialHandling, fshift_t, tData.dxdf, false, iparams_, tData.ilist, pbc_null); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR } @@ -2503,8 +2517,11 @@ void ThreadingInfo::setVirtualSites(ArrayRef ilists, if (debug) { - fprintf(debug, "virtual site thread dist: natoms %d, range %d, natperthread %d\n", - mdatoms.nr, vsite_atom_range, natperthread); + fprintf(debug, + "virtual site thread dist: natoms %d, range %d, natperthread %d\n", + mdatoms.nr, + vsite_atom_range, + natperthread); } /* To simplify the vsite assignment, we make an index which tells us @@ -2601,8 +2618,8 @@ void ThreadingInfo::setVirtualSites(ArrayRef ilists, /* The last thread should cover up to the end of the range */ tData.rangeEnd = mdatoms.nr; } - assignVsitesToThread(&tData, thread, numThreads_, natperthread, taskIndex_, ilists, - iparams, mdatoms.ptype); + assignVsitesToThread( + &tData, thread, numThreads_, natperthread, taskIndex_, ilists, iparams, mdatoms.ptype); if (tData.useInterdependentTask) { @@ -2644,7 +2661,8 @@ void ThreadingInfo::setVirtualSites(ArrayRef ilists, if (debug && numThreads_ > 1) { - fprintf(debug, "virtual site useInterdependentTask %d, nuse:\n", + fprintf(debug, + "virtual site useInterdependentTask %d, nuse:\n", static_cast(tData_[0]->useInterdependentTask)); for (int th = 0; th < numThreads_ + 1; th++) { @@ -2659,7 +2677,9 @@ void ThreadingInfo::setVirtualSites(ArrayRef ilists, fprintf(debug, "%-20s thread dist:", interaction_function[ftype].longname); for (int th = 0; th < numThreads_ + 1; th++) { - fprintf(debug, " %4d %4d ", tData_[th]->ilist[ftype].size(), + fprintf(debug, + " %4d %4d ", + tData_[th]->ilist[ftype].size(), tData_[th]->idTask.ilist[ftype].size()); } fprintf(debug, "\n"); diff --git a/src/gromacs/mdlib/wall.cpp b/src/gromacs/mdlib/wall.cpp index b8d5d77fd9..e4d49cc83d 100644 --- a/src/gromacs/mdlib/wall.cpp +++ b/src/gromacs/mdlib/wall.cpp @@ -88,8 +88,10 @@ void make_wall_tables(FILE* fplog, if (!(fr->egp_flags[egp * ir->opts.ngener + negp_pp + w] & EGP_EXCL)) { sprintf(buf, "%s", tabfn); - sprintf(buf + strlen(tabfn) - strlen(ftp2ext(efXVG)) - 1, "_%s_%s.%s", - *groups->groupNames[nm_ind[egp]], *groups->groupNames[nm_ind[negp_pp + w]], + sprintf(buf + strlen(tabfn) - strlen(ftp2ext(efXVG)) - 1, + "_%s_%s.%s", + *groups->groupNames[nm_ind[egp]], + *groups->groupNames[nm_ind[negp_pp + w]], ftp2ext(efXVG)); fr->wall_tab[w][egp] = make_tables(fplog, fr->ic, buf, 0, GMX_MAKETABLES_FORCEUSER); @@ -112,7 +114,10 @@ void make_wall_tables(FILE* fplog, gmx_fatal(FARGS, "An atom is beyond the wall: coordinates %f %f %f, distance %f\n" "You might want to use the mdp option wall_r_linpot", - x[a][XX], x[a][YY], x[a][ZZ], r); + x[a][XX], + x[a][YY], + x[a][ZZ], + r); } static void tableForce(real r, const t_forcetable& tab, real Cd, real Cr, real* V, real* F) diff --git a/src/gromacs/mdrun/legacymdrunoptions.cpp b/src/gromacs/mdrun/legacymdrunoptions.cpp index 42d0a7df38..3ef319dadd 100644 --- a/src/gromacs/mdrun/legacymdrunoptions.cpp +++ b/src/gromacs/mdrun/legacymdrunoptions.cpp @@ -85,8 +85,18 @@ int LegacyMdrunOptions::updateFromCommandLine(int argc, char** argv, ArrayRef(DdRankOrder::Count) + 1] = { - nullptr, "interleave", "pp_pme", "cartesian", nullptr - }; - const char* dddlb_opt_choices[static_cast(DlbOption::Count) + 1] = { nullptr, "auto", "no", - "yes", nullptr }; - const char* thread_aff_opt_choices[static_cast(ThreadAffinity::Count) + 1] = { - nullptr, "auto", "on", "off", nullptr - }; + rvec realddxyz = { 0, 0, 0 }; + const char* ddrank_opt_choices[static_cast(DdRankOrder::Count) + 1] = { nullptr, + "interleave", + "pp_pme", + "cartesian", + nullptr }; + const char* dddlb_opt_choices[static_cast(DlbOption::Count) + 1] = { nullptr, + "auto", + "no", + "yes", + nullptr }; + const char* thread_aff_opt_choices[static_cast(ThreadAffinity::Count) + 1] = { nullptr, + "auto", + "on", + "off", + nullptr }; const char* nbpu_opt_choices[5] = { nullptr, "auto", "cpu", "gpu", nullptr }; const char* pme_opt_choices[5] = { nullptr, "auto", "cpu", "gpu", nullptr }; const char* pme_fft_opt_choices[5] = { nullptr, "auto", "cpu", "gpu", nullptr }; diff --git a/src/gromacs/mdrun/md.cpp b/src/gromacs/mdrun/md.cpp index 9d866de380..1d786bc946 100644 --- a/src/gromacs/mdrun/md.cpp +++ b/src/gromacs/mdrun/md.cpp @@ -242,8 +242,17 @@ void gmx::LegacySimulator::do_md() if (opt2bSet("-ei", nfile, fnm)) { /* Initialize essential dynamics sampling */ - ed = init_edsam(mdlog, opt2fn_null("-ei", nfile, fnm), opt2fn("-eo", nfile, fnm), top_global, - ir, cr, constr, state_global, observablesHistory, oenv, startingBehavior); + ed = init_edsam(mdlog, + opt2fn_null("-ei", nfile, fnm), + opt2fn("-eo", nfile, fnm), + top_global, + ir, + cr, + constr, + state_global, + observablesHistory, + oenv, + startingBehavior); } else if (observablesHistory->edsamHistory) { @@ -293,12 +302,29 @@ void gmx::LegacySimulator::do_md() { pleaseCiteCouplingAlgorithms(fplog, *ir); } - gmx_mdoutf* outf = - init_mdoutf(fplog, nfile, fnm, mdrunOptions, cr, outputProvider, mdModulesNotifier, ir, - top_global, oenv, wcycle, startingBehavior, simulationsShareState, ms); - gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), top_global, ir, pull_work, - mdoutf_get_fp_dhdl(outf), false, startingBehavior, - simulationsShareState, mdModulesNotifier); + gmx_mdoutf* outf = init_mdoutf(fplog, + nfile, + fnm, + mdrunOptions, + cr, + outputProvider, + mdModulesNotifier, + ir, + top_global, + oenv, + wcycle, + startingBehavior, + simulationsShareState, + ms); + gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), + top_global, + ir, + pull_work, + mdoutf_get_fp_dhdl(outf), + false, + startingBehavior, + simulationsShareState, + mdModulesNotifier); gstat = global_stat_init(ir); @@ -309,8 +335,12 @@ void gmx::LegacySimulator::do_md() const bool useGpuForUpdate = simulationWork.useGpuUpdate; /* Check for polarizable models and flexible constraints */ - shellfc = init_shell_flexcon(fplog, top_global, constr ? constr->numFlexibleConstraints() : 0, - ir->nstcalcenergy, DOMAINDECOMP(cr), useGpuForPme); + shellfc = init_shell_flexcon(fplog, + top_global, + constr ? constr->numFlexibleConstraints() : 0, + ir->nstcalcenergy, + DOMAINDECOMP(cr), + useGpuForPme); { double io = compute_io(ir, top_global->natoms, *groups, energyOutput.numEnergyTerms(), 1); @@ -328,9 +358,10 @@ void gmx::LegacySimulator::do_md() auto mdatoms = mdAtoms->mdatoms(); - ForceBuffers f(fr->useMts, ((useGpuForNonbonded && useGpuForBufferOps) || useGpuForUpdate) - ? PinningPolicy::PinnedIfSupported - : PinningPolicy::CannotBePinned); + ForceBuffers f(fr->useMts, + ((useGpuForNonbonded && useGpuForBufferOps) || useGpuForUpdate) + ? PinningPolicy::PinnedIfSupported + : PinningPolicy::CannotBePinned); if (DOMAINDECOMP(cr)) { stateInstance = std::make_unique(); @@ -338,9 +369,27 @@ void gmx::LegacySimulator::do_md() dd_init_local_state(cr->dd, state_global, state); /* Distribute the charge groups over the nodes from the master node */ - dd_partition_system(fplog, mdlog, ir->init_step, cr, TRUE, 1, state_global, *top_global, ir, - imdSession, pull_work, state, &f, mdAtoms, &top, fr, vsite, constr, - nrnb, nullptr, FALSE); + dd_partition_system(fplog, + mdlog, + ir->init_step, + cr, + TRUE, + 1, + state_global, + *top_global, + ir, + imdSession, + pull_work, + state, + &f, + mdAtoms, + &top, + fr, + vsite, + constr, + nrnb, + nullptr, + FALSE); shouldCheckNumberOfBondedInteractions = true; upd.setNumAtoms(state->natoms); } @@ -415,9 +464,12 @@ void gmx::LegacySimulator::do_md() "Update stream should be initialized in order to use GPU " "update-constraints."); integrator = std::make_unique( - *ir, *top_global, fr->deviceStreamManager->context(), + *ir, + *top_global, + fr->deviceStreamManager->context(), fr->deviceStreamManager->stream(gmx::DeviceStreamType::UpdateAndConstraints), - stateGpu->xUpdatedOnDevice(), wcycle); + stateGpu->xUpdatedOnDevice(), + wcycle); integrator->setPbc(PbcType::Xyz, state->box); } @@ -454,13 +506,19 @@ void gmx::LegacySimulator::do_md() EnergyData::initializeEnergyHistory(startingBehavior, observablesHistory, &energyOutput); } - preparePrevStepPullCom(ir, pull_work, mdatoms->massT, state, state_global, cr, - startingBehavior != StartingBehavior::NewSimulation); + preparePrevStepPullCom( + ir, pull_work, mdatoms->massT, state, state_global, cr, startingBehavior != StartingBehavior::NewSimulation); // TODO: Remove this by converting AWH into a ForceProvider - auto awh = prepareAwhModule(fplog, *ir, state_global, cr, ms, + auto awh = prepareAwhModule(fplog, + *ir, + state_global, + cr, + ms, startingBehavior != StartingBehavior::NewSimulation, - shellfc != nullptr, opt2fn("-awh", nfile, fnm), pull_work); + shellfc != nullptr, + opt2fn("-awh", nfile, fnm), + pull_work); if (useReplicaExchange && MASTER(cr)) { @@ -474,8 +532,8 @@ void gmx::LegacySimulator::do_md() pme_load_balancing_t* pme_loadbal = nullptr; if (bPMETune) { - pme_loadbal_init(&pme_loadbal, cr, mdlog, *ir, state->box, *fr->ic, *fr->nbv, fr->pmedata, - fr->nbv->useGpu()); + pme_loadbal_init( + &pme_loadbal, cr, mdlog, *ir, state->box, *fr->ic, *fr->nbv, fr->pmedata, fr->nbv->useGpu()); } if (!ir->bContinuation) @@ -506,9 +564,15 @@ void gmx::LegacySimulator::do_md() if (constr) { /* Constrain the initial coordinates and velocities */ - do_constrain_first(fplog, constr, ir, mdatoms->nr, mdatoms->homenr, - state->x.arrayRefWithPadding(), state->v.arrayRefWithPadding(), - state->box, state->lambda[efptBONDED]); + do_constrain_first(fplog, + constr, + ir, + mdatoms->nr, + mdatoms->homenr, + state->x.arrayRefWithPadding(), + state->v.arrayRefWithPadding(), + state->box, + state->lambda[efptBONDED]); } if (vsite) { @@ -584,10 +648,28 @@ void gmx::LegacySimulator::do_md() cglo_flags_iteration |= CGLO_STOPCM; cglo_flags_iteration &= ~CGLO_TEMPERATURE; } - compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), - makeConstArrayRef(state->v), state->box, mdatoms, nrnb, &vcm, nullptr, - enerd, force_vir, shake_vir, total_vir, pres, constr, &nullSignaller, - state->box, &totalNumberOfBondedInteractions, &bSumEkinhOld, + compute_globals(gstat, + cr, + ir, + fr, + ekind, + makeConstArrayRef(state->x), + makeConstArrayRef(state->v), + state->box, + mdatoms, + nrnb, + &vcm, + nullptr, + enerd, + force_vir, + shake_vir, + total_vir, + pres, + constr, + &nullSignaller, + state->box, + &totalNumberOfBondedInteractions, + &bSumEkinhOld, cglo_flags_iteration | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0)); @@ -602,8 +684,13 @@ void gmx::LegacySimulator::do_md() inc_nrnb(nrnb, eNR_STOPCM, mdatoms->homenr); } } - checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions, top_global, &top, - makeConstArrayRef(state->x), state->box, + checkNumberOfBondedInteractions(mdlog, + cr, + totalNumberOfBondedInteractions, + top_global, + &top, + makeConstArrayRef(state->x), + state->box, &shouldCheckNumberOfBondedInteractions); if (ir->eI == eiVVAK) { @@ -613,10 +700,29 @@ void gmx::LegacySimulator::do_md() kinetic energy calculation. This minimized excess variables, but perhaps loses some logic?*/ - compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), - makeConstArrayRef(state->v), state->box, mdatoms, nrnb, &vcm, nullptr, - enerd, force_vir, shake_vir, total_vir, pres, constr, &nullSignaller, - state->box, nullptr, &bSumEkinhOld, cglo_flags & ~CGLO_PRESSURE); + compute_globals(gstat, + cr, + ir, + fr, + ekind, + makeConstArrayRef(state->x), + makeConstArrayRef(state->v), + state->box, + mdatoms, + nrnb, + &vcm, + nullptr, + enerd, + force_vir, + shake_vir, + total_vir, + pres, + constr, + &nullSignaller, + state->box, + nullptr, + &bSumEkinhOld, + cglo_flags & ~CGLO_PRESSURE); } /* Calculate the initial half step temperature, and save the ekinh_old */ @@ -638,7 +744,8 @@ void gmx::LegacySimulator::do_md() { if (constr && ir->eConstrAlg == econtLINCS) { - fprintf(fplog, "RMS relative constraint deviation after constraining: %.2e\n", + fprintf(fplog, + "RMS relative constraint deviation after constraining: %.2e\n", constr->rmsd()); } if (EI_STATE_VELOCITY(ir->eI)) @@ -667,9 +774,12 @@ void gmx::LegacySimulator::do_md() } if (ir->init_step > 0) { - fprintf(stderr, "%s steps, %s ps (continuing from step %s, %8.1f ps).\n", - gmx_step_str(ir->init_step + ir->nsteps, sbuf), tbuf, - gmx_step_str(ir->init_step, sbuf2), ir->init_step * ir->delta_t); + fprintf(stderr, + "%s steps, %s ps (continuing from step %s, %8.1f ps).\n", + gmx_step_str(ir->init_step + ir->nsteps, sbuf), + tbuf, + gmx_step_str(ir->init_step, sbuf2), + ir->init_step * ir->delta_t); } else { @@ -699,20 +809,38 @@ void gmx::LegacySimulator::do_md() step_rel = 0; auto stopHandler = stopHandlerBuilder->getStopHandlerMD( - compat::not_null(&signals[eglsSTOPCOND]), simulationsShareState, - MASTER(cr), ir->nstlist, mdrunOptions.reproducible, nstSignalComm, - mdrunOptions.maximumHoursToRun, ir->nstlist == 0, fplog, step, bNS, walltime_accounting); + compat::not_null(&signals[eglsSTOPCOND]), + simulationsShareState, + MASTER(cr), + ir->nstlist, + mdrunOptions.reproducible, + nstSignalComm, + mdrunOptions.maximumHoursToRun, + ir->nstlist == 0, + fplog, + step, + bNS, + walltime_accounting); auto checkpointHandler = std::make_unique( - compat::make_not_null(&signals[eglsCHKPT]), simulationsShareState, - ir->nstlist == 0, MASTER(cr), mdrunOptions.writeConfout, + compat::make_not_null(&signals[eglsCHKPT]), + simulationsShareState, + ir->nstlist == 0, + MASTER(cr), + mdrunOptions.writeConfout, mdrunOptions.checkpointOptions.period); const bool resetCountersIsLocal = true; auto resetHandler = std::make_unique( compat::make_not_null(&signals[eglsRESETCOUNTERS]), - !resetCountersIsLocal, ir->nsteps, MASTER(cr), mdrunOptions.timingOptions.resetHalfway, - mdrunOptions.maximumHoursToRun, mdlog, wcycle, walltime_accounting); + !resetCountersIsLocal, + ir->nsteps, + MASTER(cr), + mdrunOptions.timingOptions.resetHalfway, + mdrunOptions.maximumHoursToRun, + mdlog, + wcycle, + walltime_accounting); const DDBalanceRegionHandler ddBalanceRegionHandler(cr); @@ -739,9 +867,20 @@ void gmx::LegacySimulator::do_md() stateGpu->waitCoordinatesReadyOnHost(AtomLocality::Local); } /* PME grid + cut-off optimization with GPUs or PME nodes */ - pme_loadbal_do(pme_loadbal, cr, (mdrunOptions.verbose && MASTER(cr)) ? stderr : nullptr, - fplog, mdlog, *ir, fr, state->box, state->x, wcycle, step, step_rel, - &bPMETunePrinting, simulationWork.useGpuPmePpCommunication); + pme_loadbal_do(pme_loadbal, + cr, + (mdrunOptions.verbose && MASTER(cr)) ? stderr : nullptr, + fplog, + mdlog, + *ir, + fr, + state->box, + state->x, + wcycle, + step, + step_rel, + &bPMETunePrinting, + simulationWork.useGpuPmePpCommunication); } wallcycle_start(wcycle, ewcSTEP); @@ -829,9 +968,27 @@ void gmx::LegacySimulator::do_md() if (DOMAINDECOMP(cr)) { /* Repartition the domain decomposition */ - dd_partition_system(fplog, mdlog, step, cr, bMasterState, nstglobalcomm, state_global, - *top_global, ir, imdSession, pull_work, state, &f, mdAtoms, &top, - fr, vsite, constr, nrnb, wcycle, do_verbose && !bPMETunePrinting); + dd_partition_system(fplog, + mdlog, + step, + cr, + bMasterState, + nstglobalcomm, + state_global, + *top_global, + ir, + imdSession, + pull_work, + state, + &f, + mdAtoms, + &top, + fr, + vsite, + constr, + nrnb, + wcycle, + do_verbose && !bPMETunePrinting); shouldCheckNumberOfBondedInteractions = true; upd.setNumAtoms(state->natoms); } @@ -848,8 +1005,8 @@ void gmx::LegacySimulator::do_md() if (MASTER(cr) && do_log) { - gmx::EnergyOutput::printHeader(fplog, step, - t); /* can we improve the information printed here? */ + gmx::EnergyOutput::printHeader( + fplog, step, t); /* can we improve the information printed here? */ } if (ir->efep != efepNO) @@ -862,13 +1019,36 @@ void gmx::LegacySimulator::do_md() /* We need the kinetic energy at minus the half step for determining * the full step kinetic energy and possibly for T-coupling.*/ /* This may not be quite working correctly yet . . . . */ - compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), - makeConstArrayRef(state->v), state->box, mdatoms, nrnb, &vcm, wcycle, - enerd, nullptr, nullptr, nullptr, nullptr, constr, &nullSignaller, - state->box, &totalNumberOfBondedInteractions, &bSumEkinhOld, + compute_globals(gstat, + cr, + ir, + fr, + ekind, + makeConstArrayRef(state->x), + makeConstArrayRef(state->v), + state->box, + mdatoms, + nrnb, + &vcm, + wcycle, + enerd, + nullptr, + nullptr, + nullptr, + nullptr, + constr, + &nullSignaller, + state->box, + &totalNumberOfBondedInteractions, + &bSumEkinhOld, CGLO_GSTAT | CGLO_TEMPERATURE | CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS); - checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions, top_global, - &top, makeConstArrayRef(state->x), state->box, + checkNumberOfBondedInteractions(mdlog, + cr, + totalNumberOfBondedInteractions, + top_global, + &top, + makeConstArrayRef(state->x), + state->box, &shouldCheckNumberOfBondedInteractions); } clear_mat(force_vir); @@ -915,12 +1095,38 @@ void gmx::LegacySimulator::do_md() if (shellfc) { /* Now is the time to relax the shells */ - relax_shell_flexcon(fplog, cr, ms, mdrunOptions.verbose, enforcedRotation, step, ir, - imdSession, pull_work, bNS, force_flags, &top, constr, enerd, - state->natoms, state->x.arrayRefWithPadding(), - state->v.arrayRefWithPadding(), state->box, state->lambda, - &state->hist, &f.view(), force_vir, mdatoms, nrnb, wcycle, shellfc, - fr, runScheduleWork, t, mu_tot, vsite, ddBalanceRegionHandler); + relax_shell_flexcon(fplog, + cr, + ms, + mdrunOptions.verbose, + enforcedRotation, + step, + ir, + imdSession, + pull_work, + bNS, + force_flags, + &top, + constr, + enerd, + state->natoms, + state->x.arrayRefWithPadding(), + state->v.arrayRefWithPadding(), + state->box, + state->lambda, + &state->hist, + &f.view(), + force_vir, + mdatoms, + nrnb, + wcycle, + shellfc, + fr, + runScheduleWork, + t, + mu_tot, + vsite, + ddBalanceRegionHandler); } else { @@ -942,11 +1148,34 @@ void gmx::LegacySimulator::do_md() * This is parallellized as well, and does communication too. * Check comments in sim_util.c */ - do_force(fplog, cr, ms, ir, awh.get(), enforcedRotation, imdSession, pull_work, step, - nrnb, wcycle, &top, state->box, state->x.arrayRefWithPadding(), &state->hist, - &f.view(), force_vir, mdatoms, enerd, state->lambda, fr, runScheduleWork, - vsite, mu_tot, t, ed ? ed->getLegacyED() : nullptr, - (bNS ? GMX_FORCE_NS : 0) | force_flags, ddBalanceRegionHandler); + do_force(fplog, + cr, + ms, + ir, + awh.get(), + enforcedRotation, + imdSession, + pull_work, + step, + nrnb, + wcycle, + &top, + state->box, + state->x.arrayRefWithPadding(), + &state->hist, + &f.view(), + force_vir, + mdatoms, + enerd, + state->lambda, + fr, + runScheduleWork, + vsite, + mu_tot, + t, + ed ? ed->getLegacyED() : nullptr, + (bNS ? GMX_FORCE_NS : 0) | force_flags, + ddBalanceRegionHandler); } // VV integrators do not need the following velocity half step @@ -955,13 +1184,50 @@ void gmx::LegacySimulator::do_md() // also the first step when starting from a .tpr file. if (EI_VV(ir->eI)) { - integrateVVFirstStep(step, bFirstStep, bInitStep, startingBehavior, nstglobalcomm, ir, - fr, cr, state, mdatoms, fcdata, &MassQ, &vcm, top_global, top, enerd, - ekind, gstat, &last_ekin, bCalcVir, total_vir, shake_vir, force_vir, - pres, M, do_log, do_ene, bCalcEner, bGStat, bStopCM, bTrotter, - bExchanged, &bSumEkinhOld, &shouldCheckNumberOfBondedInteractions, - &saved_conserved_quantity, &f, &upd, constr, &nullSignaller, - trotter_seq, nrnb, mdlog, fplog, wcycle); + integrateVVFirstStep(step, + bFirstStep, + bInitStep, + startingBehavior, + nstglobalcomm, + ir, + fr, + cr, + state, + mdatoms, + fcdata, + &MassQ, + &vcm, + top_global, + top, + enerd, + ekind, + gstat, + &last_ekin, + bCalcVir, + total_vir, + shake_vir, + force_vir, + pres, + M, + do_log, + do_ene, + bCalcEner, + bGStat, + bStopCM, + bTrotter, + bExchanged, + &bSumEkinhOld, + &shouldCheckNumberOfBondedInteractions, + &saved_conserved_quantity, + &f, + &upd, + constr, + &nullSignaller, + trotter_seq, + nrnb, + mdlog, + fplog, + wcycle); } /* ######## END FIRST UPDATE STEP ############## */ @@ -973,8 +1239,8 @@ void gmx::LegacySimulator::do_md() statistics, but if performing simulated tempering, we do update the velocities and the tau_t. */ - lamnew = ExpandedEnsembleDynamics(fplog, ir, enerd, state, &MassQ, state->fep_state, - state->dfhist, step, state->v.rvec_array(), mdatoms); + lamnew = ExpandedEnsembleDynamics( + fplog, ir, enerd, state, &MassQ, state->fep_state, state->dfhist, step, state->v.rvec_array(), mdatoms); /* history is maintained in state->dfhist, but state_global is what is sent to trajectory and log output */ if (MASTER(cr)) { @@ -1019,10 +1285,28 @@ void gmx::LegacySimulator::do_md() * coordinates at time t. We must output all of this before * the update. */ - do_md_trajectory_writing(fplog, cr, nfile, fnm, step, step_rel, t, ir, state, state_global, - observablesHistory, top_global, fr, outf, energyOutput, ekind, - f.view().force(), checkpointHandler->isCheckpointingStep(), - bRerunMD, bLastStep, mdrunOptions.writeConfout, bSumEkinhOld); + do_md_trajectory_writing(fplog, + cr, + nfile, + fnm, + step, + step_rel, + t, + ir, + state, + state_global, + observablesHistory, + top_global, + fr, + outf, + energyOutput, + ekind, + f.view().force(), + checkpointHandler->isCheckpointingStep(), + bRerunMD, + bLastStep, + mdrunOptions.writeConfout, + bSumEkinhOld); /* Check if IMD step and do IMD communication, if bIMD is TRUE. */ bInteractiveMDstep = imdSession->run(step, bNS, state->box, state->x.rvec_array(), t); @@ -1107,10 +1391,39 @@ void gmx::LegacySimulator::do_md() { GMX_ASSERT(!useGpuForUpdate, "GPU update is not supported with VVAK integrator."); - integrateVVSecondStep(step, ir, fr, cr, state, mdatoms, fcdata, &MassQ, &vcm, pull_work, - enerd, ekind, gstat, &dvdl_constr, bCalcVir, total_vir, shake_vir, - force_vir, pres, M, lastbox, do_log, do_ene, bGStat, &bSumEkinhOld, - &f, &cbuf, &upd, constr, &nullSignaller, trotter_seq, nrnb, wcycle); + integrateVVSecondStep(step, + ir, + fr, + cr, + state, + mdatoms, + fcdata, + &MassQ, + &vcm, + pull_work, + enerd, + ekind, + gstat, + &dvdl_constr, + bCalcVir, + total_vir, + shake_vir, + force_vir, + pres, + M, + lastbox, + do_log, + do_ene, + bGStat, + &bSumEkinhOld, + &f, + &cbuf, + &upd, + constr, + &nullSignaller, + trotter_seq, + nrnb, + wcycle); } else { @@ -1121,8 +1434,12 @@ void gmx::LegacySimulator::do_md() if (bNS && (bFirstStep || DOMAINDECOMP(cr))) { - integrator->set(stateGpu->getCoordinates(), stateGpu->getVelocities(), - stateGpu->getForces(), top.idef, *mdatoms, ekind->ngtc); + integrator->set(stateGpu->getCoordinates(), + stateGpu->getVelocities(), + stateGpu->getForces(), + top.idef, + *mdatoms, + ekind->ngtc); // Copy data to the GPU after buffers might have being reinitialized stateGpu->copyVelocitiesToGpu(state->v, AtomLocality::Local); @@ -1149,8 +1466,15 @@ void gmx::LegacySimulator::do_md() integrator->integrate( stateGpu->getForcesReadyOnDeviceEvent( AtomLocality::Local, runScheduleWork->stepWork.useGpuFBufferOps), - ir->delta_t, true, bCalcVir, shake_vir, doTemperatureScaling, ekind->tcstat, - doParrinelloRahman, ir->nstpcouple * ir->delta_t, M); + ir->delta_t, + true, + bCalcVir, + shake_vir, + doTemperatureScaling, + ekind->tcstat, + doParrinelloRahman, + ir->nstpcouple * ir->delta_t, + M); // Copy velocities D2H after update if: // - Globals are computed this step (includes the energy output steps). @@ -1171,11 +1495,17 @@ void gmx::LegacySimulator::do_md() */ if (fr->useMts && bCalcVir && constr != nullptr) { - upd.update_for_constraint_virial(*ir, *mdatoms, *state, - f.view().forceWithPadding(), *ekind); - - constrain_coordinates(constr, do_log, do_ene, step, state, - upd.xp()->arrayRefWithPadding(), &dvdl_constr, bCalcVir, + upd.update_for_constraint_virial( + *ir, *mdatoms, *state, f.view().forceWithPadding(), *ekind); + + constrain_coordinates(constr, + do_log, + do_ene, + step, + state, + upd.xp()->arrayRefWithPadding(), + &dvdl_constr, + bCalcVir, shake_vir); } @@ -1183,17 +1513,23 @@ void gmx::LegacySimulator::do_md() (fr->useMts && step % ir->mtsLevels[1].stepFactor == 0) ? f.view().forceMtsCombinedWithPadding() : f.view().forceWithPadding(); - upd.update_coords(*ir, step, mdatoms, state, forceCombined, fcdata, ekind, M, - etrtPOSITION, cr, constr != nullptr); + upd.update_coords( + *ir, step, mdatoms, state, forceCombined, fcdata, ekind, M, etrtPOSITION, cr, constr != nullptr); wallcycle_stop(wcycle, ewcUPDATE); - constrain_coordinates(constr, do_log, do_ene, step, state, - upd.xp()->arrayRefWithPadding(), &dvdl_constr, - bCalcVir && !fr->useMts, shake_vir); - - upd.update_sd_second_half(*ir, step, &dvdl_constr, mdatoms, state, cr, nrnb, wcycle, - constr, do_log, do_ene); + constrain_coordinates(constr, + do_log, + do_ene, + step, + state, + upd.xp()->arrayRefWithPadding(), + &dvdl_constr, + bCalcVir && !fr->useMts, + shake_vir); + + upd.update_sd_second_half( + *ir, step, &dvdl_constr, mdatoms, state, cr, nrnb, wcycle, constr, do_log, do_ene); upd.finish_update(*ir, mdatoms, state, wcycle, constr != nullptr); } @@ -1240,23 +1576,46 @@ void gmx::LegacySimulator::do_md() bool doIntraSimSignal = true; SimulationSignaller signaller(&signals, cr, ms, doInterSimSignal, doIntraSimSignal); - compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), - makeConstArrayRef(state->v), state->box, mdatoms, nrnb, &vcm, - wcycle, enerd, force_vir, shake_vir, total_vir, pres, constr, - &signaller, lastbox, &totalNumberOfBondedInteractions, &bSumEkinhOld, + compute_globals(gstat, + cr, + ir, + fr, + ekind, + makeConstArrayRef(state->x), + makeConstArrayRef(state->v), + state->box, + mdatoms, + nrnb, + &vcm, + wcycle, + enerd, + force_vir, + shake_vir, + total_vir, + pres, + constr, + &signaller, + lastbox, + &totalNumberOfBondedInteractions, + &bSumEkinhOld, (bGStat ? CGLO_GSTAT : 0) | (!EI_VV(ir->eI) && bCalcEner ? CGLO_ENERGY : 0) | (!EI_VV(ir->eI) && bStopCM ? CGLO_STOPCM : 0) | (!EI_VV(ir->eI) ? CGLO_TEMPERATURE : 0) | (!EI_VV(ir->eI) ? CGLO_PRESSURE : 0) | CGLO_CONSTRAINT | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0)); - checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions, - top_global, &top, makeConstArrayRef(state->x), - state->box, &shouldCheckNumberOfBondedInteractions); + checkNumberOfBondedInteractions(mdlog, + cr, + totalNumberOfBondedInteractions, + top_global, + &top, + makeConstArrayRef(state->x), + state->box, + &shouldCheckNumberOfBondedInteractions); if (!EI_VV(ir->eI) && bStopCM) { - process_and_stopcm_grp(fplog, &vcm, *mdatoms, makeArrayRef(state->x), - makeArrayRef(state->v)); + process_and_stopcm_grp( + fplog, &vcm, *mdatoms, makeArrayRef(state->x), makeArrayRef(state->v)); inc_nrnb(nrnb, eNR_STOPCM, mdatoms->homenr); // TODO: The special case of removing CM motion should be dealt more gracefully @@ -1291,8 +1650,8 @@ void gmx::LegacySimulator::do_md() accumulateKineticLambdaComponents(enerd, state->lambda, *ir->fepvals); } - update_pcouple_after_coordinates(fplog, step, ir, mdatoms, pres, force_vir, shake_vir, - pressureCouplingMu, state, nrnb, upd.deform(), !useGpuForUpdate); + update_pcouple_after_coordinates( + fplog, step, ir, mdatoms, pres, force_vir, shake_vir, pressureCouplingMu, state, nrnb, upd.deform(), !useGpuForUpdate); const bool doBerendsenPressureCoupling = (inputrec->epc == epcBERENDSEN && do_per_step(step, inputrec->nstpcouple)); @@ -1354,18 +1713,38 @@ void gmx::LegacySimulator::do_md() if (fplog && do_log && bDoExpanded) { /* only needed if doing expanded ensemble */ - PrintFreeEnergyInfoToFile(fplog, ir->fepvals, ir->expandedvals, + PrintFreeEnergyInfoToFile(fplog, + ir->fepvals, + ir->expandedvals, ir->bSimTemp ? ir->simtempvals : nullptr, - state_global->dfhist, state->fep_state, ir->nstlog, step); + state_global->dfhist, + state->fep_state, + ir->nstlog, + step); } if (bCalcEner) { - energyOutput.addDataAtEnergyStep( - bDoDHDL, bCalcEnerStep, t, mdatoms->tmass, enerd, ir->fepvals, - ir->expandedvals, lastbox, - PTCouplingArrays{ state->boxv, state->nosehoover_xi, state->nosehoover_vxi, - state->nhpres_xi, state->nhpres_vxi }, - state->fep_state, shake_vir, force_vir, total_vir, pres, ekind, mu_tot, constr); + energyOutput.addDataAtEnergyStep(bDoDHDL, + bCalcEnerStep, + t, + mdatoms->tmass, + enerd, + ir->fepvals, + ir->expandedvals, + lastbox, + PTCouplingArrays{ state->boxv, + state->nosehoover_xi, + state->nosehoover_vxi, + state->nhpres_xi, + state->nhpres_vxi }, + state->fep_state, + shake_vir, + force_vir, + total_vir, + pres, + ekind, + mu_tot, + constr); } else { @@ -1377,14 +1756,20 @@ void gmx::LegacySimulator::do_md() if (doSimulatedAnnealing) { - gmx::EnergyOutput::printAnnealingTemperatures(do_log ? fplog : nullptr, groups, - &(ir->opts)); + gmx::EnergyOutput::printAnnealingTemperatures( + do_log ? fplog : nullptr, groups, &(ir->opts)); } if (do_log || do_ene || do_dr || do_or) { - energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), do_ene, do_dr, do_or, - do_log ? fplog : nullptr, step, t, - fr->fcdata.get(), awh.get()); + energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), + do_ene, + do_dr, + do_or, + do_log ? fplog : nullptr, + step, + t, + fr->fcdata.get(), + awh.get()); } if (do_log && ir->bDoAwh && awh->hasFepLambdaDimension()) { @@ -1431,9 +1816,16 @@ void gmx::LegacySimulator::do_md() bNeedRepartition = FALSE; if ((ir->eSwapCoords != eswapNO) && (step > 0) && !bLastStep && do_per_step(step, ir->swap->nstswap)) { - bNeedRepartition = - do_swapcoords(cr, step, t, ir, swap, wcycle, as_rvec_array(state->x.data()), - state->box, MASTER(cr) && mdrunOptions.verbose, bRerunMD); + bNeedRepartition = do_swapcoords(cr, + step, + t, + ir, + swap, + wcycle, + as_rvec_array(state->x.data()), + state->box, + MASTER(cr) && mdrunOptions.verbose, + bRerunMD); if (bNeedRepartition && DOMAINDECOMP(cr)) { @@ -1450,9 +1842,27 @@ void gmx::LegacySimulator::do_md() if ((bExchanged || bNeedRepartition) && DOMAINDECOMP(cr)) { - dd_partition_system(fplog, mdlog, step, cr, TRUE, 1, state_global, *top_global, ir, - imdSession, pull_work, state, &f, mdAtoms, &top, fr, vsite, constr, - nrnb, wcycle, FALSE); + dd_partition_system(fplog, + mdlog, + step, + cr, + TRUE, + 1, + state_global, + *top_global, + ir, + imdSession, + pull_work, + state, + &f, + mdAtoms, + &top, + fr, + vsite, + constr, + nrnb, + wcycle, + FALSE); shouldCheckNumberOfBondedInteractions = true; upd.setNumAtoms(state->natoms); } @@ -1497,8 +1907,8 @@ void gmx::LegacySimulator::do_md() } #endif - resetHandler->resetCounters(step, step_rel, mdlog, fplog, cr, fr->nbv.get(), nrnb, - fr->pmedata, pme_loadbal, wcycle, walltime_accounting); + resetHandler->resetCounters( + step, step_rel, mdlog, fplog, cr, fr->nbv.get(), nrnb, fr->pmedata, pme_loadbal, wcycle, walltime_accounting); /* If bIMD is TRUE, the master updates the IMD energy record and sends positions to VMD client */ imdSession->updateEnergyRecordAndSendPositionsAndEnergies(bInteractiveMDstep, step, bCalcEner); diff --git a/src/gromacs/mdrun/mimic.cpp b/src/gromacs/mdrun/mimic.cpp index 22a8458f02..adc120d1b2 100644 --- a/src/gromacs/mdrun/mimic.cpp +++ b/src/gromacs/mdrun/mimic.cpp @@ -197,8 +197,9 @@ void gmx::LegacySimulator::do_mimic() { gmx_fatal(FARGS, "Multiple simulations not supported by MiMiC."); } - if (std::any_of(ir->opts.annealing, ir->opts.annealing + ir->opts.ngtc, - [](int i) { return i != eannNO; })) + if (std::any_of(ir->opts.annealing, ir->opts.annealing + ir->opts.ngtc, [](int i) { + return i != eannNO; + })) { gmx_fatal(FARGS, "Simulated annealing not supported by MiMiC."); } @@ -227,18 +228,38 @@ void gmx::LegacySimulator::do_mimic() initialize_lambdas(fplog, *ir, MASTER(cr), &state_global->fep_state, state_global->lambda); const bool simulationsShareState = false; - gmx_mdoutf* outf = init_mdoutf(fplog, nfile, fnm, mdrunOptions, cr, outputProvider, - mdModulesNotifier, ir, top_global, oenv, wcycle, - StartingBehavior::NewSimulation, simulationsShareState, ms); - gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), top_global, ir, pull_work, - mdoutf_get_fp_dhdl(outf), true, StartingBehavior::NewSimulation, - simulationsShareState, mdModulesNotifier); + gmx_mdoutf* outf = init_mdoutf(fplog, + nfile, + fnm, + mdrunOptions, + cr, + outputProvider, + mdModulesNotifier, + ir, + top_global, + oenv, + wcycle, + StartingBehavior::NewSimulation, + simulationsShareState, + ms); + gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), + top_global, + ir, + pull_work, + mdoutf_get_fp_dhdl(outf), + true, + StartingBehavior::NewSimulation, + simulationsShareState, + mdModulesNotifier); gstat = global_stat_init(ir); /* Check for polarizable models and flexible constraints */ - shellfc = init_shell_flexcon(fplog, top_global, constr ? constr->numFlexibleConstraints() : 0, - ir->nstcalcenergy, DOMAINDECOMP(cr), + shellfc = init_shell_flexcon(fplog, + top_global, + constr ? constr->numFlexibleConstraints() : 0, + ir->nstcalcenergy, + DOMAINDECOMP(cr), runScheduleWork->simulationWork.useGpuPme); { @@ -262,9 +283,27 @@ void gmx::LegacySimulator::do_mimic() dd_init_local_state(cr->dd, state_global, state); /* Distribute the charge groups over the nodes from the master node */ - dd_partition_system(fplog, mdlog, ir->init_step, cr, TRUE, 1, state_global, *top_global, ir, - imdSession, pull_work, state, &f, mdAtoms, &top, fr, vsite, constr, - nrnb, nullptr, FALSE); + dd_partition_system(fplog, + mdlog, + ir->init_step, + cr, + TRUE, + 1, + state_global, + *top_global, + ir, + imdSession, + pull_work, + state, + &f, + mdAtoms, + &top, + fr, + vsite, + constr, + nrnb, + nullptr, + FALSE); shouldCheckNumberOfBondedInteractions = true; gmx_bcast(sizeof(ir->nsteps), &ir->nsteps, cr->mpi_comm_mygroup); } @@ -297,13 +336,37 @@ void gmx::LegacySimulator::do_mimic() | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0)); bool bSumEkinhOld = false; t_vcm* vcm = nullptr; - compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), - makeConstArrayRef(state->v), state->box, mdatoms, nrnb, vcm, nullptr, enerd, - force_vir, shake_vir, total_vir, pres, constr, &nullSignaller, state->box, - &totalNumberOfBondedInteractions, &bSumEkinhOld, cglo_flags); + compute_globals(gstat, + cr, + ir, + fr, + ekind, + makeConstArrayRef(state->x), + makeConstArrayRef(state->v), + state->box, + mdatoms, + nrnb, + vcm, + nullptr, + enerd, + force_vir, + shake_vir, + total_vir, + pres, + constr, + &nullSignaller, + state->box, + &totalNumberOfBondedInteractions, + &bSumEkinhOld, + cglo_flags); } - checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions, top_global, &top, - makeConstArrayRef(state->x), state->box, + checkNumberOfBondedInteractions(mdlog, + cr, + totalNumberOfBondedInteractions, + top_global, + &top, + makeConstArrayRef(state->x), + state->box, &shouldCheckNumberOfBondedInteractions); if (MASTER(cr)) @@ -348,9 +411,18 @@ void gmx::LegacySimulator::do_mimic() step_rel = 0; auto stopHandler = stopHandlerBuilder->getStopHandlerMD( - compat::not_null(&signals[eglsSTOPCOND]), false, MASTER(cr), - ir->nstlist, mdrunOptions.reproducible, nstglobalcomm, mdrunOptions.maximumHoursToRun, - ir->nstlist == 0, fplog, step, bNS, walltime_accounting); + compat::not_null(&signals[eglsSTOPCOND]), + false, + MASTER(cr), + ir->nstlist, + mdrunOptions.reproducible, + nstglobalcomm, + mdrunOptions.maximumHoursToRun, + ir->nstlist == 0, + fplog, + step, + bNS, + walltime_accounting); // we don't do counter resetting in rerun - finish will always be valid walltime_accounting_set_valid_finish(walltime_accounting); @@ -392,9 +464,27 @@ void gmx::LegacySimulator::do_mimic() { /* Repartition the domain decomposition */ const bool bMasterState = true; - dd_partition_system(fplog, mdlog, step, cr, bMasterState, nstglobalcomm, state_global, - *top_global, ir, imdSession, pull_work, state, &f, mdAtoms, &top, - fr, vsite, constr, nrnb, wcycle, mdrunOptions.verbose); + dd_partition_system(fplog, + mdlog, + step, + cr, + bMasterState, + nstglobalcomm, + state_global, + *top_global, + ir, + imdSession, + pull_work, + state, + &f, + mdAtoms, + &top, + fr, + vsite, + constr, + nrnb, + wcycle, + mdrunOptions.verbose); shouldCheckNumberOfBondedInteractions = true; } @@ -415,12 +505,38 @@ void gmx::LegacySimulator::do_mimic() if (shellfc) { /* Now is the time to relax the shells */ - relax_shell_flexcon(fplog, cr, ms, mdrunOptions.verbose, enforcedRotation, step, ir, - imdSession, pull_work, bNS, force_flags, &top, constr, enerd, - state->natoms, state->x.arrayRefWithPadding(), - state->v.arrayRefWithPadding(), state->box, state->lambda, - &state->hist, &f.view(), force_vir, mdatoms, nrnb, wcycle, shellfc, - fr, runScheduleWork, t, mu_tot, vsite, ddBalanceRegionHandler); + relax_shell_flexcon(fplog, + cr, + ms, + mdrunOptions.verbose, + enforcedRotation, + step, + ir, + imdSession, + pull_work, + bNS, + force_flags, + &top, + constr, + enerd, + state->natoms, + state->x.arrayRefWithPadding(), + state->v.arrayRefWithPadding(), + state->box, + state->lambda, + &state->hist, + &f.view(), + force_vir, + mdatoms, + nrnb, + wcycle, + shellfc, + fr, + runScheduleWork, + t, + mu_tot, + vsite, + ddBalanceRegionHandler); } else { @@ -431,10 +547,34 @@ void gmx::LegacySimulator::do_mimic() */ Awh* awh = nullptr; gmx_edsam* ed = nullptr; - do_force(fplog, cr, ms, ir, awh, enforcedRotation, imdSession, pull_work, step, nrnb, - wcycle, &top, state->box, state->x.arrayRefWithPadding(), &state->hist, - &f.view(), force_vir, mdatoms, enerd, state->lambda, fr, runScheduleWork, - vsite, mu_tot, t, ed, GMX_FORCE_NS | force_flags, ddBalanceRegionHandler); + do_force(fplog, + cr, + ms, + ir, + awh, + enforcedRotation, + imdSession, + pull_work, + step, + nrnb, + wcycle, + &top, + state->box, + state->x.arrayRefWithPadding(), + &state->hist, + &f.view(), + force_vir, + mdatoms, + enerd, + state->lambda, + fr, + runScheduleWork, + vsite, + mu_tot, + t, + ed, + GMX_FORCE_NS | force_flags, + ddBalanceRegionHandler); } /* Now we have the energies and forces corresponding to the @@ -444,10 +584,28 @@ void gmx::LegacySimulator::do_mimic() const bool isCheckpointingStep = false; const bool doRerun = false; const bool bSumEkinhOld = false; - do_md_trajectory_writing(fplog, cr, nfile, fnm, step, step_rel, t, ir, state, - state_global, observablesHistory, top_global, fr, outf, - energyOutput, ekind, f.view().force(), isCheckpointingStep, - doRerun, isLastStep, mdrunOptions.writeConfout, bSumEkinhOld); + do_md_trajectory_writing(fplog, + cr, + nfile, + fnm, + step, + step_rel, + t, + ir, + state, + state_global, + observablesHistory, + top_global, + fr, + outf, + energyOutput, + ekind, + f.view().force(), + isCheckpointingStep, + doRerun, + isLastStep, + mdrunOptions.writeConfout, + bSumEkinhOld); } stopHandler->setSignal(); @@ -466,15 +624,38 @@ void gmx::LegacySimulator::do_mimic() t_vcm* vcm = nullptr; SimulationSignaller signaller(&signals, cr, ms, doInterSimSignal, doIntraSimSignal); - compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), - makeConstArrayRef(state->v), state->box, mdatoms, nrnb, vcm, wcycle, - enerd, nullptr, nullptr, nullptr, nullptr, constr, &signaller, - state->box, &totalNumberOfBondedInteractions, &bSumEkinhOld, + compute_globals(gstat, + cr, + ir, + fr, + ekind, + makeConstArrayRef(state->x), + makeConstArrayRef(state->v), + state->box, + mdatoms, + nrnb, + vcm, + wcycle, + enerd, + nullptr, + nullptr, + nullptr, + nullptr, + constr, + &signaller, + state->box, + &totalNumberOfBondedInteractions, + &bSumEkinhOld, CGLO_GSTAT | CGLO_ENERGY | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0)); - checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions, top_global, - &top, makeConstArrayRef(state->x), state->box, + checkNumberOfBondedInteractions(mdlog, + cr, + totalNumberOfBondedInteractions, + top_global, + &top, + makeConstArrayRef(state->x), + state->box, &shouldCheckNumberOfBondedInteractions); } @@ -485,8 +666,7 @@ void gmx::LegacySimulator::do_mimic() if (DOMAINDECOMP(cr)) { ftemp = gmx::makeArrayRef(fglobal); - dd_collect_vec(cr->dd, state->ddp_count, state->ddp_count_cg_gl, state->cg_gl, - flocal, ftemp); + dd_collect_vec(cr->dd, state->ddp_count, state->ddp_count_cg_gl, state->cg_gl, flocal, ftemp); } else { @@ -517,12 +697,27 @@ void gmx::LegacySimulator::do_mimic() if (MASTER(cr)) { const bool bCalcEnerStep = true; - energyOutput.addDataAtEnergyStep( - doFreeEnergyPerturbation, bCalcEnerStep, t, mdatoms->tmass, enerd, ir->fepvals, - ir->expandedvals, state->box, - PTCouplingArrays({ state->boxv, state->nosehoover_xi, state->nosehoover_vxi, - state->nhpres_xi, state->nhpres_vxi }), - state->fep_state, shake_vir, force_vir, total_vir, pres, ekind, mu_tot, constr); + energyOutput.addDataAtEnergyStep(doFreeEnergyPerturbation, + bCalcEnerStep, + t, + mdatoms->tmass, + enerd, + ir->fepvals, + ir->expandedvals, + state->box, + PTCouplingArrays({ state->boxv, + state->nosehoover_xi, + state->nosehoover_vxi, + state->nhpres_xi, + state->nhpres_vxi }), + state->fep_state, + shake_vir, + force_vir, + total_vir, + pres, + ekind, + mu_tot, + constr); const bool do_ene = true; const bool do_log = true; @@ -531,8 +726,15 @@ void gmx::LegacySimulator::do_mimic() const bool do_or = ir->nstorireout != 0; EnergyOutput::printAnnealingTemperatures(do_log ? fplog : nullptr, groups, &(ir->opts)); - energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), do_ene, do_dr, do_or, - do_log ? fplog : nullptr, step, t, fr->fcdata.get(), awh); + energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), + do_ene, + do_dr, + do_or, + do_log ? fplog : nullptr, + step, + t, + fr->fcdata.get(), + awh); if (do_per_step(step, ir->nstlog)) { diff --git a/src/gromacs/mdrun/minimize.cpp b/src/gromacs/mdrun/minimize.cpp index f93b04245c..7415046e1a 100644 --- a/src/gromacs/mdrun/minimize.cpp +++ b/src/gromacs/mdrun/minimize.cpp @@ -237,12 +237,13 @@ static void print_converged(FILE* fp, fprintf(fp, "\n%s converged to machine precision in %s steps,\n" "but did not reach the requested Fmax < %g.\n", - alg, gmx_step_str(count, buf), ftol); + alg, + gmx_step_str(count, buf), + ftol); } else { - fprintf(fp, "\n%s did not converge to Fmax < %g in %s steps.\n", alg, ftol, - gmx_step_str(count, buf)); + fprintf(fp, "\n%s did not converge to Fmax < %g in %s steps.\n", alg, ftol, gmx_step_str(count, buf)); } #if GMX_DOUBLE @@ -399,9 +400,12 @@ static void init_em(FILE* fplog, { GMX_ASSERT(shellfc != nullptr, "With NM we always support shells"); - *shellfc = - init_shell_flexcon(stdout, top_global, constr ? constr->numFlexibleConstraints() : 0, - ir->nstcalcenergy, DOMAINDECOMP(cr), thisRankHasDuty(cr, DUTY_PME)); + *shellfc = init_shell_flexcon(stdout, + top_global, + constr ? constr->numFlexibleConstraints() : 0, + ir->nstcalcenergy, + DOMAINDECOMP(cr), + thisRankHasDuty(cr, DUTY_PME)); } else { @@ -423,9 +427,27 @@ static void init_em(FILE* fplog, dd_init_local_state(cr->dd, state_global, &ems->s); /* Distribute the charge groups over the nodes from the master node */ - dd_partition_system(fplog, mdlog, ir->init_step, cr, TRUE, 1, state_global, *top_global, ir, - imdSession, pull_work, &ems->s, &ems->f, mdAtoms, top, fr, vsite, - constr, nrnb, nullptr, FALSE); + dd_partition_system(fplog, + mdlog, + ir->init_step, + cr, + TRUE, + 1, + state_global, + *top_global, + ir, + imdSession, + pull_work, + &ems->s, + &ems->f, + mdAtoms, + top, + fr, + vsite, + constr, + nrnb, + nullptr, + FALSE); dd_store_state(cr->dd, &ems->s); } else @@ -435,8 +457,8 @@ static void init_em(FILE* fplog, ems->s = *state_global; state_change_natoms(&ems->s, ems->s.natoms); - mdAlgorithmsSetupAtomData(cr, ir, *top_global, top, fr, &ems->f, mdAtoms, constr, vsite, - shellfc ? *shellfc : nullptr); + mdAlgorithmsSetupAtomData( + cr, ir, *top_global, top, fr, &ems->f, mdAtoms, constr, vsite, shellfc ? *shellfc : nullptr); } update_mdatoms(mdAtoms->mdatoms(), ems->s.lambda[efptMASS]); @@ -446,8 +468,10 @@ static void init_em(FILE* fplog, // TODO how should this cross-module support dependency be managed? if (ir->eConstrAlg == econtSHAKE && gmx_mtop_ftype_count(top_global, F_CONSTR) > 0) { - gmx_fatal(FARGS, "Can not do energy minimization with %s, use %s\n", - econstr_names[econtSHAKE], econstr_names[econtLINCS]); + gmx_fatal(FARGS, + "Can not do energy minimization with %s, use %s\n", + econstr_names[econtSHAKE], + econstr_names[econtLINCS]); } if (!ir->bContinuation) @@ -457,10 +481,21 @@ static void init_em(FILE* fplog, bool computeEnergy = true; bool computeVirial = false; dvdl_constr = 0; - constr->apply(needsLogging, computeEnergy, -1, 0, 1.0, ems->s.x.arrayRefWithPadding(), - ems->s.x.arrayRefWithPadding(), ArrayRef(), ems->s.box, - ems->s.lambda[efptFEP], &dvdl_constr, gmx::ArrayRefWithPadding(), - computeVirial, nullptr, gmx::ConstraintVariable::Positions); + constr->apply(needsLogging, + computeEnergy, + -1, + 0, + 1.0, + ems->s.x.arrayRefWithPadding(), + ems->s.x.arrayRefWithPadding(), + ArrayRef(), + ems->s.box, + ems->s.lambda[efptFEP], + &dvdl_constr, + gmx::ArrayRefWithPadding(), + computeVirial, + nullptr, + gmx::ConstraintVariable::Positions); } } @@ -535,9 +570,18 @@ static void write_em_traj(FILE* fplog, } gmx::WriteCheckpointDataHolder checkpointDataHolder; - mdoutf_write_to_trajectory_files(fplog, cr, outf, mdof_flags, top_global->natoms, step, - static_cast(step), &state->s, state_global, - observablesHistory, state->f.view().force(), &checkpointDataHolder); + mdoutf_write_to_trajectory_files(fplog, + cr, + outf, + mdof_flags, + top_global->natoms, + step, + static_cast(step), + &state->s, + state_global, + observablesHistory, + state->f.view().force(), + &checkpointDataHolder); if (confout != nullptr) { @@ -547,8 +591,8 @@ static void write_em_traj(FILE* fplog, if (!bX) { auto globalXRef = MASTER(cr) ? state_global->x : gmx::ArrayRef(); - dd_collect_vec(cr->dd, state->s.ddp_count, state->s.ddp_count_cg_gl, state->s.cg_gl, - state->s.x, globalXRef); + dd_collect_vec( + cr->dd, state->s.ddp_count, state->s.ddp_count_cg_gl, state->s.cg_gl, state->s.x, globalXRef); } } else @@ -565,8 +609,13 @@ static void write_em_traj(FILE* fplog, do_pbc_mtop(ir->pbcType, state->s.box, top_global, state_global->x.rvec_array()); } - write_sto_conf_mtop(confout, *top_global->name, top_global, - state_global->x.rvec_array(), nullptr, ir->pbcType, state->s.box); + write_sto_conf_mtop(confout, + *top_global->name, + top_global, + state_global->x.rvec_array(), + nullptr, + ir->pbcType, + state->s.box); } } } @@ -685,10 +734,21 @@ static bool do_em_step(const t_commrec* cr, if (constr) { dvdl_constr = 0; - validStep = constr->apply( - TRUE, TRUE, count, 0, 1.0, s1->x.arrayRefWithPadding(), s2->x.arrayRefWithPadding(), - ArrayRef(), s2->box, s2->lambda[efptBONDED], &dvdl_constr, - gmx::ArrayRefWithPadding(), false, nullptr, gmx::ConstraintVariable::Positions); + validStep = constr->apply(TRUE, + TRUE, + count, + 0, + 1.0, + s1->x.arrayRefWithPadding(), + s2->x.arrayRefWithPadding(), + ArrayRef(), + s2->box, + s2->lambda[efptBONDED], + &dvdl_constr, + gmx::ArrayRefWithPadding(), + false, + nullptr, + gmx::ConstraintVariable::Positions); if (cr->nnodes > 1) { @@ -707,7 +767,9 @@ static bool do_em_step(const t_commrec* cr, gmx_fatal(FARGS, "The coordinates could not be constrained. Minimizer '%s' can not handle " "constraint failures, use minimizer '%s' before using '%s'.", - EI(ir->eI), EI(eiSteep), EI(ir->eI)); + EI(ir->eI), + EI(eiSteep), + EI(ir->eI)); } } @@ -733,8 +795,27 @@ static void em_dd_partition_system(FILE* fplog, gmx_wallcycle_t wcycle) { /* Repartition the domain decomposition */ - dd_partition_system(fplog, mdlog, step, cr, FALSE, 1, nullptr, *top_global, ir, imdSession, pull_work, - &ems->s, &ems->f, mdAtoms, top, fr, vsite, constr, nrnb, wcycle, FALSE); + dd_partition_system(fplog, + mdlog, + step, + cr, + FALSE, + 1, + nullptr, + *top_global, + ir, + imdSession, + pull_work, + &ems->s, + &ems->f, + mdAtoms, + top, + fr, + vsite, + constr, + nrnb, + wcycle, + FALSE); dd_store_state(cr->dd, &ems->s); } @@ -836,17 +917,40 @@ void EnergyEvaluator::run(em_state_t* ems, rvec mu_tot, tensor vir, tensor pres, if (DOMAINDECOMP(cr) && bNS) { /* Repartition the domain decomposition */ - em_dd_partition_system(fplog, mdlog, count, cr, top_global, inputrec, imdSession, pull_work, - ems, top, mdAtoms, fr, vsite, constr, nrnb, wcycle); + em_dd_partition_system( + fplog, mdlog, count, cr, top_global, inputrec, imdSession, pull_work, ems, top, mdAtoms, fr, vsite, constr, nrnb, wcycle); } /* Calc force & energy on new trial position */ /* do_force always puts the charge groups in the box and shifts again * We do not unshift, so molecules are always whole in congrad.c */ - do_force(fplog, cr, ms, inputrec, nullptr, nullptr, imdSession, pull_work, count, nrnb, wcycle, - top, ems->s.box, ems->s.x.arrayRefWithPadding(), &ems->s.hist, &ems->f.view(), force_vir, - mdAtoms->mdatoms(), enerd, ems->s.lambda, fr, runScheduleWork, vsite, mu_tot, t, nullptr, + do_force(fplog, + cr, + ms, + inputrec, + nullptr, + nullptr, + imdSession, + pull_work, + count, + nrnb, + wcycle, + top, + ems->s.box, + ems->s.x.arrayRefWithPadding(), + &ems->s.hist, + &ems->f.view(), + force_vir, + mdAtoms->mdatoms(), + enerd, + ems->s.lambda, + fr, + runScheduleWork, + vsite, + mu_tot, + t, + nullptr, GMX_FORCE_STATECHANGED | GMX_FORCE_ALLFORCES | GMX_FORCE_VIRIAL | GMX_FORCE_ENERGY | (bNS ? GMX_FORCE_NS : 0), DDBalanceRegionHandler(cr)); @@ -860,8 +964,20 @@ void EnergyEvaluator::run(em_state_t* ems, rvec mu_tot, tensor vir, tensor pres, { wallcycle_start(wcycle, ewcMoveE); - global_stat(gstat, cr, enerd, force_vir, shake_vir, inputrec, nullptr, nullptr, nullptr, 1, - &terminate, nullptr, FALSE, CGLO_ENERGY | CGLO_PRESSURE | CGLO_CONSTRAINT); + global_stat(gstat, + cr, + enerd, + force_vir, + shake_vir, + inputrec, + nullptr, + nullptr, + nullptr, + 1, + &terminate, + nullptr, + FALSE, + CGLO_ENERGY | CGLO_PRESSURE | CGLO_CONSTRAINT); wallcycle_stop(wcycle, ewcMoveE); } @@ -892,9 +1008,20 @@ void EnergyEvaluator::run(em_state_t* ems, rvec mu_tot, tensor vir, tensor pres, bool computeVirial = true; dvdl_constr = 0; auto f = ems->f.view().forceWithPadding(); - constr->apply(needsLogging, computeEnergy, count, 0, 1.0, ems->s.x.arrayRefWithPadding(), f, - f.unpaddedArrayRef(), ems->s.box, ems->s.lambda[efptBONDED], &dvdl_constr, - gmx::ArrayRefWithPadding(), computeVirial, shake_vir, + constr->apply(needsLogging, + computeEnergy, + count, + 0, + 1.0, + ems->s.x.arrayRefWithPadding(), + f, + f.unpaddedArrayRef(), + ems->s.box, + ems->s.lambda[efptBONDED], + &dvdl_constr, + gmx::ArrayRefWithPadding(), + computeVirial, + shake_vir, gmx::ConstraintVariable::ForceDispl); enerd->term[F_DVDL_CONSTR] += dvdl_constr; m_add(force_vir, shake_vir, vir); @@ -1089,15 +1216,48 @@ void LegacySimulator::do_cg() em_state_t* s_c = &s3; /* Init em and store the local state in s_min */ - init_em(fplog, mdlog, CG, cr, inputrec, imdSession, pull_work, state_global, top_global, s_min, - &top, nrnb, fr, mdAtoms, &gstat, vsite, constr, nullptr); + init_em(fplog, + mdlog, + CG, + cr, + inputrec, + imdSession, + pull_work, + state_global, + top_global, + s_min, + &top, + nrnb, + fr, + mdAtoms, + &gstat, + vsite, + constr, + nullptr); const bool simulationsShareState = false; - gmx_mdoutf* outf = init_mdoutf(fplog, nfile, fnm, mdrunOptions, cr, outputProvider, - mdModulesNotifier, inputrec, top_global, nullptr, wcycle, - StartingBehavior::NewSimulation, simulationsShareState, ms); - gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), top_global, inputrec, pull_work, - nullptr, false, StartingBehavior::NewSimulation, - simulationsShareState, mdModulesNotifier); + gmx_mdoutf* outf = init_mdoutf(fplog, + nfile, + fnm, + mdrunOptions, + cr, + outputProvider, + mdModulesNotifier, + inputrec, + top_global, + nullptr, + wcycle, + StartingBehavior::NewSimulation, + simulationsShareState, + ms); + gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), + top_global, + inputrec, + pull_work, + nullptr, + false, + StartingBehavior::NewSimulation, + simulationsShareState, + mdModulesNotifier); /* Print to log file */ print_em_start(fplog, cr, walltime_accounting, wcycle, CG); @@ -1127,13 +1287,27 @@ void LegacySimulator::do_cg() { /* Copy stuff to the energy bin for easy printing etc. */ matrix nullBox = {}; - energyOutput.addDataAtEnergyStep(false, false, static_cast(step), mdatoms->tmass, - enerd, nullptr, nullptr, nullBox, PTCouplingArrays(), 0, - nullptr, nullptr, vir, pres, nullptr, mu_tot, constr); + energyOutput.addDataAtEnergyStep(false, + false, + static_cast(step), + mdatoms->tmass, + enerd, + nullptr, + nullptr, + nullBox, + PTCouplingArrays(), + 0, + nullptr, + nullptr, + vir, + pres, + nullptr, + mu_tot, + constr); EnergyOutput::printHeader(fplog, step, step); - energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), TRUE, FALSE, FALSE, fplog, step, - step, fr->fcdata.get(), nullptr); + energyOutput.printStepToEnergyFile( + mdoutf_get_fp_ene(outf), TRUE, FALSE, FALSE, fplog, step, step, fr->fcdata.get(), nullptr); } /* Estimate/guess the initial stepsize */ @@ -1253,8 +1427,8 @@ void LegacySimulator::do_cg() do_x = do_per_step(step, inputrec->nstxout); do_f = do_per_step(step, inputrec->nstfout); - write_em_traj(fplog, cr, outf, do_x, do_f, nullptr, top_global, inputrec, step, s_min, - state_global, observablesHistory); + write_em_traj( + fplog, cr, outf, do_x, do_f, nullptr, top_global, inputrec, step, s_min, state_global, observablesHistory); /* Take a step downhill. * In theory, we should minimize the function along this direction. @@ -1279,13 +1453,26 @@ void LegacySimulator::do_cg() if (DOMAINDECOMP(cr) && s_min->s.ddp_count < cr->dd->ddp_count) { - em_dd_partition_system(fplog, mdlog, step, cr, top_global, inputrec, imdSession, - pull_work, s_min, &top, mdAtoms, fr, vsite, constr, nrnb, wcycle); + em_dd_partition_system(fplog, + mdlog, + step, + cr, + top_global, + inputrec, + imdSession, + pull_work, + s_min, + &top, + mdAtoms, + fr, + vsite, + constr, + nrnb, + wcycle); } /* Take a trial step (new coords in s_c) */ - do_em_step(cr, inputrec, mdatoms, s_min, c, s_min->s.cg_p.constArrayRefWithPadding(), s_c, - constr, -1); + do_em_step(cr, inputrec, mdatoms, s_min, c, s_min->s.cg_p.constArrayRefWithPadding(), s_c, constr, -1); neval++; /* Calculate energy for the trial step */ @@ -1381,13 +1568,26 @@ void LegacySimulator::do_cg() if (DOMAINDECOMP(cr) && s_min->s.ddp_count != cr->dd->ddp_count) { /* Reload the old state */ - em_dd_partition_system(fplog, mdlog, -1, cr, top_global, inputrec, imdSession, pull_work, - s_min, &top, mdAtoms, fr, vsite, constr, nrnb, wcycle); + em_dd_partition_system(fplog, + mdlog, + -1, + cr, + top_global, + inputrec, + imdSession, + pull_work, + s_min, + &top, + mdAtoms, + fr, + vsite, + constr, + nrnb, + wcycle); } /* Take a trial step to this new point - new coords in s_b */ - do_em_step(cr, inputrec, mdatoms, s_min, b, - s_min->s.cg_p.constArrayRefWithPadding(), s_b, constr, -1); + do_em_step(cr, inputrec, mdatoms, s_min, b, s_min->s.cg_p.constArrayRefWithPadding(), s_b, constr, -1); neval++; /* Calculate energy for the trial step */ @@ -1414,8 +1614,7 @@ void LegacySimulator::do_cg() if (debug) { - fprintf(debug, "CGE: EpotA %f EpotB %f EpotC %f gpb %f\n", s_a->epot, s_b->epot, - s_c->epot, gpb); + fprintf(debug, "CGE: EpotA %f EpotB %f EpotC %f gpb %f\n", s_a->epot, s_b->epot, s_c->epot, gpb); } epot_repl = s_b->epot; @@ -1469,8 +1668,7 @@ void LegacySimulator::do_cg() { if (debug) { - fprintf(debug, "CGE: C (%f) is lower than A (%f), moving C to B\n", s_c->epot, - s_a->epot); + fprintf(debug, "CGE: C (%f) is lower than A (%f), moving C to B\n", s_c->epot, s_a->epot); } swap_em_state(&s_b, &s_c); gpb = gpc; @@ -1479,8 +1677,7 @@ void LegacySimulator::do_cg() { if (debug) { - fprintf(debug, "CGE: A (%f) is lower than C (%f), moving A to B\n", s_a->epot, - s_c->epot); + fprintf(debug, "CGE: A (%f) is lower than C (%f), moving A to B\n", s_a->epot, s_c->epot); } swap_em_state(&s_b, &s_a); gpb = gpa; @@ -1530,15 +1727,34 @@ void LegacySimulator::do_cg() if (mdrunOptions.verbose) { double sqrtNumAtoms = sqrt(static_cast(state_global->natoms)); - fprintf(stderr, "\rStep %d, Epot=%12.6e, Fnorm=%9.3e, Fmax=%9.3e (atom %d)\n", step, - s_min->epot, s_min->fnorm / sqrtNumAtoms, s_min->fmax, s_min->a_fmax + 1); + fprintf(stderr, + "\rStep %d, Epot=%12.6e, Fnorm=%9.3e, Fmax=%9.3e (atom %d)\n", + step, + s_min->epot, + s_min->fnorm / sqrtNumAtoms, + s_min->fmax, + s_min->a_fmax + 1); fflush(stderr); } /* Store the new (lower) energies */ matrix nullBox = {}; - energyOutput.addDataAtEnergyStep(false, false, static_cast(step), mdatoms->tmass, - enerd, nullptr, nullptr, nullBox, PTCouplingArrays(), 0, - nullptr, nullptr, vir, pres, nullptr, mu_tot, constr); + energyOutput.addDataAtEnergyStep(false, + false, + static_cast(step), + mdatoms->tmass, + enerd, + nullptr, + nullptr, + nullBox, + PTCouplingArrays(), + 0, + nullptr, + nullptr, + vir, + pres, + nullptr, + mu_tot, + constr); do_log = do_per_step(step, inputrec->nstlog); do_ene = do_per_step(step, inputrec->nstenergy); @@ -1549,9 +1765,15 @@ void LegacySimulator::do_cg() { EnergyOutput::printHeader(fplog, step, step); } - energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), do_ene, FALSE, FALSE, - do_log ? fplog : nullptr, step, step, - fr->fcdata.get(), nullptr); + energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), + do_ene, + FALSE, + FALSE, + do_log ? fplog : nullptr, + step, + step, + fr->fcdata.get(), + nullptr); } /* Send energies and positions to the IMD client if bIMD is TRUE. */ @@ -1593,9 +1815,15 @@ void LegacySimulator::do_cg() if (!do_ene || !do_log) { /* Write final energy file entries */ - energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), !do_ene, FALSE, FALSE, - !do_log ? fplog : nullptr, step, step, - fr->fcdata.get(), nullptr); + energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), + !do_ene, + FALSE, + FALSE, + !do_log ? fplog : nullptr, + step, + step, + fr->fcdata.get(), + nullptr); } } @@ -1618,8 +1846,8 @@ void LegacySimulator::do_cg() do_x = !do_per_step(step, inputrec->nstxout); do_f = (inputrec->nstfout > 0 && !do_per_step(step, inputrec->nstfout)); - write_em_traj(fplog, cr, outf, do_x, do_f, ftp2fn(efSTO, nfile, fnm), top_global, inputrec, - step, s_min, state_global, observablesHistory); + write_em_traj( + fplog, cr, outf, do_x, do_f, ftp2fn(efSTO, nfile, fnm), top_global, inputrec, step, s_min, state_global, observablesHistory); if (MASTER(cr)) @@ -1705,15 +1933,48 @@ void LegacySimulator::do_lbfgs() neval = 0; /* Init em */ - init_em(fplog, mdlog, LBFGS, cr, inputrec, imdSession, pull_work, state_global, top_global, - &ems, &top, nrnb, fr, mdAtoms, &gstat, vsite, constr, nullptr); + init_em(fplog, + mdlog, + LBFGS, + cr, + inputrec, + imdSession, + pull_work, + state_global, + top_global, + &ems, + &top, + nrnb, + fr, + mdAtoms, + &gstat, + vsite, + constr, + nullptr); const bool simulationsShareState = false; - gmx_mdoutf* outf = init_mdoutf(fplog, nfile, fnm, mdrunOptions, cr, outputProvider, - mdModulesNotifier, inputrec, top_global, nullptr, wcycle, - StartingBehavior::NewSimulation, simulationsShareState, ms); - gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), top_global, inputrec, pull_work, - nullptr, false, StartingBehavior::NewSimulation, - simulationsShareState, mdModulesNotifier); + gmx_mdoutf* outf = init_mdoutf(fplog, + nfile, + fnm, + mdrunOptions, + cr, + outputProvider, + mdModulesNotifier, + inputrec, + top_global, + nullptr, + wcycle, + StartingBehavior::NewSimulation, + simulationsShareState, + ms); + gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), + top_global, + inputrec, + pull_work, + nullptr, + false, + StartingBehavior::NewSimulation, + simulationsShareState, + mdModulesNotifier); start = 0; end = mdatoms->homenr; @@ -1778,13 +2039,27 @@ void LegacySimulator::do_lbfgs() { /* Copy stuff to the energy bin for easy printing etc. */ matrix nullBox = {}; - energyOutput.addDataAtEnergyStep(false, false, static_cast(step), mdatoms->tmass, - enerd, nullptr, nullptr, nullBox, PTCouplingArrays(), 0, - nullptr, nullptr, vir, pres, nullptr, mu_tot, constr); + energyOutput.addDataAtEnergyStep(false, + false, + static_cast(step), + mdatoms->tmass, + enerd, + nullptr, + nullptr, + nullBox, + PTCouplingArrays(), + 0, + nullptr, + nullptr, + vir, + pres, + nullptr, + mu_tot, + constr); EnergyOutput::printHeader(fplog, step, step); - energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), TRUE, FALSE, FALSE, fplog, step, - step, fr->fcdata.get(), nullptr); + energyOutput.printStepToEnergyFile( + mdoutf_get_fp_ene(outf), TRUE, FALSE, FALSE, fplog, step, step, fr->fcdata.get(), nullptr); } /* Set the initial step. @@ -1863,9 +2138,18 @@ void LegacySimulator::do_lbfgs() } gmx::WriteCheckpointDataHolder checkpointDataHolder; - mdoutf_write_to_trajectory_files(fplog, cr, outf, mdof_flags, top_global->natoms, step, - static_cast(step), &ems.s, state_global, observablesHistory, - ems.f.view().force(), &checkpointDataHolder); + mdoutf_write_to_trajectory_files(fplog, + cr, + outf, + mdof_flags, + top_global->natoms, + step, + static_cast(step), + &ems.s, + state_global, + observablesHistory, + ems.f.view().force(), + &checkpointDataHolder); /* Do the linesearching in the direction dx[point][0..(n-1)] */ @@ -2257,15 +2541,34 @@ void LegacySimulator::do_lbfgs() if (mdrunOptions.verbose) { double sqrtNumAtoms = sqrt(static_cast(state_global->natoms)); - fprintf(stderr, "\rStep %d, Epot=%12.6e, Fnorm=%9.3e, Fmax=%9.3e (atom %d)\n", step, - ems.epot, ems.fnorm / sqrtNumAtoms, ems.fmax, ems.a_fmax + 1); + fprintf(stderr, + "\rStep %d, Epot=%12.6e, Fnorm=%9.3e, Fmax=%9.3e (atom %d)\n", + step, + ems.epot, + ems.fnorm / sqrtNumAtoms, + ems.fmax, + ems.a_fmax + 1); fflush(stderr); } /* Store the new (lower) energies */ matrix nullBox = {}; - energyOutput.addDataAtEnergyStep(false, false, static_cast(step), mdatoms->tmass, - enerd, nullptr, nullptr, nullBox, PTCouplingArrays(), 0, - nullptr, nullptr, vir, pres, nullptr, mu_tot, constr); + energyOutput.addDataAtEnergyStep(false, + false, + static_cast(step), + mdatoms->tmass, + enerd, + nullptr, + nullptr, + nullBox, + PTCouplingArrays(), + 0, + nullptr, + nullptr, + vir, + pres, + nullptr, + mu_tot, + constr); do_log = do_per_step(step, inputrec->nstlog); do_ene = do_per_step(step, inputrec->nstenergy); @@ -2276,9 +2579,15 @@ void LegacySimulator::do_lbfgs() { EnergyOutput::printHeader(fplog, step, step); } - energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), do_ene, FALSE, FALSE, - do_log ? fplog : nullptr, step, step, - fr->fcdata.get(), nullptr); + energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), + do_ene, + FALSE, + FALSE, + do_log ? fplog : nullptr, + step, + step, + fr->fcdata.get(), + nullptr); } /* Send x and E to IMD client, if bIMD is TRUE. */ @@ -2319,8 +2628,14 @@ void LegacySimulator::do_lbfgs() } if (!do_ene || !do_log) /* Write final energy file entries */ { - energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), !do_ene, FALSE, FALSE, - !do_log ? fplog : nullptr, step, step, fr->fcdata.get(), + energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), + !do_ene, + FALSE, + FALSE, + !do_log ? fplog : nullptr, + step, + step, + fr->fcdata.get(), nullptr); } @@ -2339,8 +2654,8 @@ void LegacySimulator::do_lbfgs() */ do_x = !do_per_step(step, inputrec->nstxout); do_f = !do_per_step(step, inputrec->nstfout); - write_em_traj(fplog, cr, outf, do_x, do_f, ftp2fn(efSTO, nfile, fnm), top_global, inputrec, - step, &ems, state_global, observablesHistory); + write_em_traj( + fplog, cr, outf, do_x, do_f, ftp2fn(efSTO, nfile, fnm), top_global, inputrec, step, &ems, state_global, observablesHistory); if (MASTER(cr)) { @@ -2386,15 +2701,48 @@ void LegacySimulator::do_steep() em_state_t* s_try = &s1; /* Init em and store the local state in s_try */ - init_em(fplog, mdlog, SD, cr, inputrec, imdSession, pull_work, state_global, top_global, s_try, - &top, nrnb, fr, mdAtoms, &gstat, vsite, constr, nullptr); + init_em(fplog, + mdlog, + SD, + cr, + inputrec, + imdSession, + pull_work, + state_global, + top_global, + s_try, + &top, + nrnb, + fr, + mdAtoms, + &gstat, + vsite, + constr, + nullptr); const bool simulationsShareState = false; - gmx_mdoutf* outf = init_mdoutf(fplog, nfile, fnm, mdrunOptions, cr, outputProvider, - mdModulesNotifier, inputrec, top_global, nullptr, wcycle, - StartingBehavior::NewSimulation, simulationsShareState, ms); - gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), top_global, inputrec, pull_work, - nullptr, false, StartingBehavior::NewSimulation, - simulationsShareState, mdModulesNotifier); + gmx_mdoutf* outf = init_mdoutf(fplog, + nfile, + fnm, + mdrunOptions, + cr, + outputProvider, + mdModulesNotifier, + inputrec, + top_global, + nullptr, + wcycle, + StartingBehavior::NewSimulation, + simulationsShareState, + ms); + gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), + top_global, + inputrec, + pull_work, + nullptr, + false, + StartingBehavior::NewSimulation, + simulationsShareState, + mdModulesNotifier); /* Print to log file */ print_em_start(fplog, cr, walltime_accounting, wcycle, SD); @@ -2438,8 +2786,8 @@ void LegacySimulator::do_steep() bool validStep = true; if (count > 0) { - validStep = do_em_step(cr, inputrec, mdatoms, s_min, stepsize, - s_min->f.view().forceWithPadding(), s_try, constr, count); + validStep = do_em_step( + cr, inputrec, mdatoms, s_min, stepsize, s_min->f.view().forceWithPadding(), s_try, constr, count); } if (validStep) @@ -2467,8 +2815,13 @@ void LegacySimulator::do_steep() { if (mdrunOptions.verbose) { - fprintf(stderr, "Step=%5d, Dmax= %6.1e nm, Epot= %12.5e Fmax= %11.5e, atom= %d%c", - count, ustep, s_try->epot, s_try->fmax, s_try->a_fmax + 1, + fprintf(stderr, + "Step=%5d, Dmax= %6.1e nm, Epot= %12.5e Fmax= %11.5e, atom= %d%c", + count, + ustep, + s_try->epot, + s_try->fmax, + s_try->a_fmax + 1, ((count == 0) || (s_try->epot < s_min->epot)) ? '\n' : '\r'); fflush(stderr); } @@ -2477,17 +2830,30 @@ void LegacySimulator::do_steep() { /* Store the new (lower) energies */ matrix nullBox = {}; - energyOutput.addDataAtEnergyStep(false, false, static_cast(count), - mdatoms->tmass, enerd, nullptr, nullptr, nullBox, - PTCouplingArrays(), 0, nullptr, nullptr, vir, pres, - nullptr, mu_tot, constr); + energyOutput.addDataAtEnergyStep(false, + false, + static_cast(count), + mdatoms->tmass, + enerd, + nullptr, + nullptr, + nullBox, + PTCouplingArrays(), + 0, + nullptr, + nullptr, + vir, + pres, + nullptr, + mu_tot, + constr); imdSession->fillEnergyRecord(count, TRUE); const bool do_dr = do_per_step(steps_accepted, inputrec->nstdisreout); const bool do_or = do_per_step(steps_accepted, inputrec->nstorireout); - energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), TRUE, do_dr, do_or, - fplog, count, count, fr->fcdata.get(), nullptr); + energyOutput.printStepToEnergyFile( + mdoutf_get_fp_ene(outf), TRUE, do_dr, do_or, fplog, count, count, fr->fcdata.get(), nullptr); fflush(fplog); } } @@ -2516,8 +2882,8 @@ void LegacySimulator::do_steep() /* Write to trn, if necessary */ do_x = do_per_step(steps_accepted, inputrec->nstxout); do_f = do_per_step(steps_accepted, inputrec->nstfout); - write_em_traj(fplog, cr, outf, do_x, do_f, nullptr, top_global, inputrec, count, s_min, - state_global, observablesHistory); + write_em_traj( + fplog, cr, outf, do_x, do_f, nullptr, top_global, inputrec, count, s_min, state_global, observablesHistory); } else { @@ -2527,8 +2893,22 @@ void LegacySimulator::do_steep() if (DOMAINDECOMP(cr) && s_min->s.ddp_count != cr->dd->ddp_count) { /* Reload the old state */ - em_dd_partition_system(fplog, mdlog, count, cr, top_global, inputrec, imdSession, - pull_work, s_min, &top, mdAtoms, fr, vsite, constr, nrnb, wcycle); + em_dd_partition_system(fplog, + mdlog, + count, + cr, + top_global, + inputrec, + imdSession, + pull_work, + s_min, + &top, + mdAtoms, + fr, + vsite, + constr, + nrnb, + wcycle); } } @@ -2557,8 +2937,11 @@ void LegacySimulator::do_steep() } /* Send IMD energies and positions, if bIMD is TRUE. */ - if (imdSession->run(count, TRUE, MASTER(cr) ? state_global->box : nullptr, - MASTER(cr) ? state_global->x.rvec_array() : nullptr, 0) + if (imdSession->run(count, + TRUE, + MASTER(cr) ? state_global->box : nullptr, + MASTER(cr) ? state_global->x.rvec_array() : nullptr, + 0) && MASTER(cr)) { imdSession->sendPositionsAndEnergies(); @@ -2572,8 +2955,18 @@ void LegacySimulator::do_steep() { fprintf(stderr, "\nwriting lowest energy coordinates.\n"); } - write_em_traj(fplog, cr, outf, TRUE, inputrec->nstfout != 0, ftp2fn(efSTO, nfile, fnm), - top_global, inputrec, count, s_min, state_global, observablesHistory); + write_em_traj(fplog, + cr, + outf, + TRUE, + inputrec->nstfout != 0, + ftp2fn(efSTO, nfile, fnm), + top_global, + inputrec, + count, + s_min, + state_global, + observablesHistory); if (MASTER(cr)) { @@ -2632,12 +3025,39 @@ void LegacySimulator::do_nm() em_state_t state_work{}; /* Init em and store the local state in state_minimum */ - init_em(fplog, mdlog, NM, cr, inputrec, imdSession, pull_work, state_global, top_global, - &state_work, &top, nrnb, fr, mdAtoms, &gstat, vsite, constr, &shellfc); + init_em(fplog, + mdlog, + NM, + cr, + inputrec, + imdSession, + pull_work, + state_global, + top_global, + &state_work, + &top, + nrnb, + fr, + mdAtoms, + &gstat, + vsite, + constr, + &shellfc); const bool simulationsShareState = false; - gmx_mdoutf* outf = init_mdoutf(fplog, nfile, fnm, mdrunOptions, cr, outputProvider, - mdModulesNotifier, inputrec, top_global, nullptr, wcycle, - StartingBehavior::NewSimulation, simulationsShareState, ms); + gmx_mdoutf* outf = init_mdoutf(fplog, + nfile, + fnm, + mdrunOptions, + cr, + outputProvider, + mdModulesNotifier, + inputrec, + top_global, + nullptr, + wcycle, + StartingBehavior::NewSimulation, + simulationsShareState, + ms); std::vector atom_index = get_atom_index(top_global); std::vector fneg(atom_index.size(), { 0, 0, 0 }); @@ -2702,8 +3122,10 @@ void LegacySimulator::do_nm() if (bIsMaster) { - fprintf(stderr, "starting normal mode calculation '%s'\n%" PRId64 " steps.\n\n", - *(top_global->name), inputrec->nsteps); + fprintf(stderr, + "starting normal mode calculation '%s'\n%" PRId64 " steps.\n\n", + *(top_global->name), + inputrec->nsteps); } nnodes = cr->nnodes; @@ -2770,13 +3192,38 @@ void LegacySimulator::do_nm() if (shellfc) { /* Now is the time to relax the shells */ - relax_shell_flexcon(fplog, cr, ms, mdrunOptions.verbose, nullptr, step, inputrec, - imdSession, pull_work, bNS, force_flags, &top, constr, enerd, - state_work.s.natoms, state_work.s.x.arrayRefWithPadding(), - state_work.s.v.arrayRefWithPadding(), state_work.s.box, - state_work.s.lambda, &state_work.s.hist, &state_work.f.view(), - vir, mdatoms, nrnb, wcycle, shellfc, fr, runScheduleWork, t, - mu_tot, vsite, DDBalanceRegionHandler(nullptr)); + relax_shell_flexcon(fplog, + cr, + ms, + mdrunOptions.verbose, + nullptr, + step, + inputrec, + imdSession, + pull_work, + bNS, + force_flags, + &top, + constr, + enerd, + state_work.s.natoms, + state_work.s.x.arrayRefWithPadding(), + state_work.s.v.arrayRefWithPadding(), + state_work.s.box, + state_work.s.lambda, + &state_work.s.hist, + &state_work.f.view(), + vir, + mdatoms, + nrnb, + wcycle, + shellfc, + fr, + runScheduleWork, + t, + mu_tot, + vsite, + DDBalanceRegionHandler(nullptr)); bNS = false; step++; } @@ -2789,8 +3236,7 @@ void LegacySimulator::do_nm() if (dx == 0) { - std::copy(state_work_f.begin(), state_work_f.begin() + atom_index.size(), - fneg.begin()); + std::copy(state_work_f.begin(), state_work_f.begin() + atom_index.size(), fneg.begin()); } } @@ -2809,8 +3255,7 @@ void LegacySimulator::do_nm() { #if GMX_MPI # define mpi_type GMX_MPI_REAL - MPI_Send(dfdx[0], atom_index.size() * DIM, mpi_type, MASTER(cr), cr->nodeid, - cr->mpi_comm_mygroup); + MPI_Send(dfdx[0], atom_index.size() * DIM, mpi_type, MASTER(cr), cr->nodeid, cr->mpi_comm_mygroup); #endif } else @@ -2821,8 +3266,7 @@ void LegacySimulator::do_nm() { #if GMX_MPI MPI_Status stat; - MPI_Recv(dfdx[0], atom_index.size() * DIM, mpi_type, node, node, - cr->mpi_comm_mygroup, &stat); + MPI_Recv(dfdx[0], atom_index.size() * DIM, mpi_type, node, node, cr->mpi_comm_mygroup, &stat); # undef mpi_type #endif } @@ -2859,8 +3303,10 @@ void LegacySimulator::do_nm() /* write progress */ if (bIsMaster && mdrunOptions.verbose) { - fprintf(stderr, "\rFinished step %d out of %td", - std::min(atom + nnodes, atom_index.size()), ssize(atom_index)); + fprintf(stderr, + "\rFinished step %d out of %td", + std::min(atom + nnodes, atom_index.size()), + ssize(atom_index)); fflush(stderr); } } diff --git a/src/gromacs/mdrun/replicaexchange.cpp b/src/gromacs/mdrun/replicaexchange.cpp index c40161d9ef..19172eb0de 100644 --- a/src/gromacs/mdrun/replicaexchange.cpp +++ b/src/gromacs/mdrun/replicaexchange.cpp @@ -97,7 +97,9 @@ enum * 'lambda_and_pressure', 'temperature_lambda_pressure'?; Let's wait * until we feel better about the pressure control methods giving * exact ensembles. Right now, we assume constant pressure */ -static const char* erename[ereNR] = { "temperature", "lambda", "end_single_marker", +static const char* erename[ereNR] = { "temperature", + "lambda", + "end_single_marker", "temperature and lambda" }; //! Working data for replica exchange. @@ -249,8 +251,8 @@ gmx_repl_ex_t init_replica_exchange(FILE* fplog, check_multi_int(fplog, ms, ir->eI, "the integrator", FALSE); check_multi_int64(fplog, ms, ir->init_step + ir->nsteps, "init_step+nsteps", FALSE); const int nst = replExParams.exchangeInterval; - check_multi_int64(fplog, ms, (ir->init_step + nst - 1) / nst, - "first exchange step: init_step/-replex", FALSE); + check_multi_int64( + fplog, ms, (ir->init_step + nst - 1) / nst, "first exchange step: init_step/-replex", FALSE); check_multi_int(fplog, ms, ir->etc, "the temperature coupling", FALSE); check_multi_int(fplog, ms, ir->opts.ngtc, "the number of temperature coupling groups", FALSE); check_multi_int(fplog, ms, ir->epc, "the pressure coupling", FALSE); @@ -302,7 +304,8 @@ gmx_repl_ex_t init_replica_exchange(FILE* fplog, gmx_fatal(FARGS, "REMD with the %s thermostat does not produce correct potential energy " "distributions, consider using the %s thermostat instead", - ETCOUPLTYPE(ir->etc), ETCOUPLTYPE(etcVRESCALE)); + ETCOUPLTYPE(ir->etc), + ETCOUPLTYPE(etcVRESCALE)); } } if (bLambda) @@ -362,7 +365,11 @@ gmx_repl_ex_t init_replica_exchange(FILE* fplog, gmx_fatal(FARGS, "Replicas with indices %d < %d have %ss %g > %g, please order your " "replicas on increasing %s", - i, j, erename[re->type], re->q[re->type][i], re->q[re->type][j], + i, + j, + erename[re->type], + re->q[re->type][i], + re->q[re->type][j], erename[re->type]); } else if (re->q[re->type][re->ind[j]] == re->q[re->type][re->ind[i]]) @@ -544,8 +551,7 @@ static void exchange_doubles(const gmx_multisim_t gmx_unused* ms, int gmx_unused MPI_Request mpi_req; MPI_Isend(v, n * sizeof(double), MPI_BYTE, MSRANK(ms, b), 0, ms->mastersComm_, &mpi_req); - MPI_Recv(buf, n * sizeof(double), MPI_BYTE, MSRANK(ms, b), 0, ms->mastersComm_, - MPI_STATUS_IGNORE); + MPI_Recv(buf, n * sizeof(double), MPI_BYTE, MSRANK(ms, b), 0, ms->mastersComm_, MPI_STATUS_IGNORE); MPI_Wait(&mpi_req, MPI_STATUS_IGNORE); } #endif @@ -575,8 +581,7 @@ static void exchange_rvecs(const gmx_multisim_t gmx_unused* ms, int gmx_unused b MPI_Request mpi_req; MPI_Isend(v[0], n * sizeof(rvec), MPI_BYTE, MSRANK(ms, b), 0, ms->mastersComm_, &mpi_req); - MPI_Recv(buf[0], n * sizeof(rvec), MPI_BYTE, MSRANK(ms, b), 0, ms->mastersComm_, - MPI_STATUS_IGNORE); + MPI_Recv(buf[0], n * sizeof(rvec), MPI_BYTE, MSRANK(ms, b), 0, ms->mastersComm_, MPI_STATUS_IGNORE); MPI_Wait(&mpi_req, MPI_STATUS_IGNORE); } #endif @@ -1319,8 +1324,9 @@ gmx_bool replica_exchange(FILE* fplog, * the velocities. */ if (re->type == ereTEMP || re->type == ereTL) { - scale_velocities(state->v, std::sqrt(re->q[ereTEMP][replica_id] - / re->q[ereTEMP][re->destinations[replica_id]])); + scale_velocities(state->v, + std::sqrt(re->q[ereTEMP][replica_id] + / re->q[ereTEMP][re->destinations[replica_id]])); } } @@ -1343,8 +1349,11 @@ void print_replica_exchange_statistics(FILE* fplog, struct gmx_repl_ex* re) if (re->nex == 0) { - fprintf(fplog, "Repl %d attempts, %d odd, %d even\n", re->nattempt[0] + re->nattempt[1], - re->nattempt[1], re->nattempt[0]); + fprintf(fplog, + "Repl %d attempts, %d odd, %d even\n", + re->nattempt[0] + re->nattempt[1], + re->nattempt[1], + re->nattempt[0]); fprintf(fplog, "Repl average probabilities:\n"); for (i = 1; i < re->nrepl; i++) diff --git a/src/gromacs/mdrun/rerun.cpp b/src/gromacs/mdrun/rerun.cpp index 137e2d75c8..ab974dd8d7 100644 --- a/src/gromacs/mdrun/rerun.cpp +++ b/src/gromacs/mdrun/rerun.cpp @@ -247,8 +247,9 @@ void gmx::LegacySimulator::do_rerun() { gmx_fatal(FARGS, "Multiple simulations not supported by rerun."); } - if (std::any_of(ir->opts.annealing, ir->opts.annealing + ir->opts.ngtc, - [](int i) { return i != eannNO; })) + if (std::any_of(ir->opts.annealing, ir->opts.annealing + ir->opts.ngtc, [](int i) { + return i != eannNO; + })) { gmx_fatal(FARGS, "Simulated annealing not supported by rerun."); } @@ -283,18 +284,38 @@ void gmx::LegacySimulator::do_rerun() gmx::ArrayRef lambda = MASTER(cr) ? state_global->lambda : gmx::ArrayRef(); initialize_lambdas(fplog, *ir, MASTER(cr), fep_state, lambda); const bool simulationsShareState = false; - gmx_mdoutf* outf = init_mdoutf(fplog, nfile, fnm, mdrunOptions, cr, outputProvider, - mdModulesNotifier, ir, top_global, oenv, wcycle, - StartingBehavior::NewSimulation, simulationsShareState, ms); - gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), top_global, ir, pull_work, - mdoutf_get_fp_dhdl(outf), true, StartingBehavior::NewSimulation, - simulationsShareState, mdModulesNotifier); + gmx_mdoutf* outf = init_mdoutf(fplog, + nfile, + fnm, + mdrunOptions, + cr, + outputProvider, + mdModulesNotifier, + ir, + top_global, + oenv, + wcycle, + StartingBehavior::NewSimulation, + simulationsShareState, + ms); + gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), + top_global, + ir, + pull_work, + mdoutf_get_fp_dhdl(outf), + true, + StartingBehavior::NewSimulation, + simulationsShareState, + mdModulesNotifier); gstat = global_stat_init(ir); /* Check for polarizable models and flexible constraints */ - shellfc = init_shell_flexcon(fplog, top_global, constr ? constr->numFlexibleConstraints() : 0, - ir->nstcalcenergy, DOMAINDECOMP(cr), + shellfc = init_shell_flexcon(fplog, + top_global, + constr ? constr->numFlexibleConstraints() : 0, + ir->nstcalcenergy, + DOMAINDECOMP(cr), runScheduleWork->simulationWork.useGpuPme); { @@ -316,9 +337,27 @@ void gmx::LegacySimulator::do_rerun() dd_init_local_state(cr->dd, state_global, state); /* Distribute the charge groups over the nodes from the master node */ - dd_partition_system(fplog, mdlog, ir->init_step, cr, TRUE, 1, state_global, *top_global, ir, - imdSession, pull_work, state, &f, mdAtoms, &top, fr, vsite, constr, - nrnb, nullptr, FALSE); + dd_partition_system(fplog, + mdlog, + ir->init_step, + cr, + TRUE, + 1, + state_global, + *top_global, + ir, + imdSession, + pull_work, + state, + &f, + mdAtoms, + &top, + fr, + vsite, + constr, + nrnb, + nullptr, + FALSE); shouldCheckNumberOfBondedInteractions = true; } else @@ -350,13 +389,37 @@ void gmx::LegacySimulator::do_rerun() | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0)); bool bSumEkinhOld = false; t_vcm* vcm = nullptr; - compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), - makeConstArrayRef(state->v), state->box, mdatoms, nrnb, vcm, nullptr, enerd, - force_vir, shake_vir, total_vir, pres, constr, &nullSignaller, state->box, - &totalNumberOfBondedInteractions, &bSumEkinhOld, cglo_flags); + compute_globals(gstat, + cr, + ir, + fr, + ekind, + makeConstArrayRef(state->x), + makeConstArrayRef(state->v), + state->box, + mdatoms, + nrnb, + vcm, + nullptr, + enerd, + force_vir, + shake_vir, + total_vir, + pres, + constr, + &nullSignaller, + state->box, + &totalNumberOfBondedInteractions, + &bSumEkinhOld, + cglo_flags); } - checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions, top_global, &top, - makeConstArrayRef(state->x), state->box, + checkNumberOfBondedInteractions(mdlog, + cr, + totalNumberOfBondedInteractions, + top_global, + &top, + makeConstArrayRef(state->x), + state->box, &shouldCheckNumberOfBondedInteractions); if (MASTER(cr)) @@ -364,7 +427,8 @@ void gmx::LegacySimulator::do_rerun() fprintf(stderr, "starting md rerun '%s', reading coordinates from" " input trajectory '%s'\n\n", - *(top_global->name), opt2fn("-rerun", nfile, fnm)); + *(top_global->name), + opt2fn("-rerun", nfile, fnm)); if (mdrunOptions.verbose) { fprintf(stderr, @@ -401,7 +465,8 @@ void gmx::LegacySimulator::do_rerun() gmx_fatal(FARGS, "Number of atoms in trajectory (%d) does not match the " "run input file (%d)\n", - rerun_fr.natoms, top_global->natoms); + rerun_fr.natoms, + top_global->natoms); } if (ir->pbcType != PbcType::No) @@ -412,7 +477,8 @@ void gmx::LegacySimulator::do_rerun() "Rerun trajectory frame step %" PRId64 " time %f " "does not contain a box, while pbc is used", - rerun_fr.step, rerun_fr.time); + rerun_fr.step, + rerun_fr.time); } if (max_cutoff2(ir->pbcType, rerun_fr.box) < gmx::square(fr->rlist)) { @@ -420,7 +486,8 @@ void gmx::LegacySimulator::do_rerun() "Rerun trajectory frame step %" PRId64 " time %f " "has too small box dimensions", - rerun_fr.step, rerun_fr.time); + rerun_fr.step, + rerun_fr.time); } } } @@ -448,9 +515,18 @@ void gmx::LegacySimulator::do_rerun() step_rel = 0; auto stopHandler = stopHandlerBuilder->getStopHandlerMD( - compat::not_null(&signals[eglsSTOPCOND]), false, MASTER(cr), - ir->nstlist, mdrunOptions.reproducible, nstglobalcomm, mdrunOptions.maximumHoursToRun, - ir->nstlist == 0, fplog, step, bNS, walltime_accounting); + compat::not_null(&signals[eglsSTOPCOND]), + false, + MASTER(cr), + ir->nstlist, + mdrunOptions.reproducible, + nstglobalcomm, + mdrunOptions.maximumHoursToRun, + ir->nstlist == 0, + fplog, + step, + bNS, + walltime_accounting); // we don't do counter resetting in rerun - finish will always be valid walltime_accounting_set_valid_finish(walltime_accounting); @@ -513,9 +589,27 @@ void gmx::LegacySimulator::do_rerun() { /* Repartition the domain decomposition */ const bool bMasterState = true; - dd_partition_system(fplog, mdlog, step, cr, bMasterState, nstglobalcomm, state_global, - *top_global, ir, imdSession, pull_work, state, &f, mdAtoms, &top, - fr, vsite, constr, nrnb, wcycle, mdrunOptions.verbose); + dd_partition_system(fplog, + mdlog, + step, + cr, + bMasterState, + nstglobalcomm, + state_global, + *top_global, + ir, + imdSession, + pull_work, + state, + &f, + mdAtoms, + &top, + fr, + vsite, + constr, + nrnb, + wcycle, + mdrunOptions.verbose); shouldCheckNumberOfBondedInteractions = true; } @@ -536,12 +630,38 @@ void gmx::LegacySimulator::do_rerun() if (shellfc) { /* Now is the time to relax the shells */ - relax_shell_flexcon(fplog, cr, ms, mdrunOptions.verbose, enforcedRotation, step, ir, - imdSession, pull_work, bNS, force_flags, &top, constr, enerd, - state->natoms, state->x.arrayRefWithPadding(), - state->v.arrayRefWithPadding(), state->box, state->lambda, - &state->hist, &f.view(), force_vir, mdatoms, nrnb, wcycle, shellfc, - fr, runScheduleWork, t, mu_tot, vsite, ddBalanceRegionHandler); + relax_shell_flexcon(fplog, + cr, + ms, + mdrunOptions.verbose, + enforcedRotation, + step, + ir, + imdSession, + pull_work, + bNS, + force_flags, + &top, + constr, + enerd, + state->natoms, + state->x.arrayRefWithPadding(), + state->v.arrayRefWithPadding(), + state->box, + state->lambda, + &state->hist, + &f.view(), + force_vir, + mdatoms, + nrnb, + wcycle, + shellfc, + fr, + runScheduleWork, + t, + mu_tot, + vsite, + ddBalanceRegionHandler); } else { @@ -552,10 +672,34 @@ void gmx::LegacySimulator::do_rerun() */ Awh* awh = nullptr; gmx_edsam* ed = nullptr; - do_force(fplog, cr, ms, ir, awh, enforcedRotation, imdSession, pull_work, step, nrnb, - wcycle, &top, state->box, state->x.arrayRefWithPadding(), &state->hist, - &f.view(), force_vir, mdatoms, enerd, state->lambda, fr, runScheduleWork, - vsite, mu_tot, t, ed, GMX_FORCE_NS | force_flags, ddBalanceRegionHandler); + do_force(fplog, + cr, + ms, + ir, + awh, + enforcedRotation, + imdSession, + pull_work, + step, + nrnb, + wcycle, + &top, + state->box, + state->x.arrayRefWithPadding(), + &state->hist, + &f.view(), + force_vir, + mdatoms, + enerd, + state->lambda, + fr, + runScheduleWork, + vsite, + mu_tot, + t, + ed, + GMX_FORCE_NS | force_flags, + ddBalanceRegionHandler); } /* Now we have the energies and forces corresponding to the @@ -565,10 +709,28 @@ void gmx::LegacySimulator::do_rerun() const bool isCheckpointingStep = false; const bool doRerun = true; const bool bSumEkinhOld = false; - do_md_trajectory_writing(fplog, cr, nfile, fnm, step, step_rel, t, ir, state, - state_global, observablesHistory, top_global, fr, outf, - energyOutput, ekind, f.view().force(), isCheckpointingStep, - doRerun, isLastStep, mdrunOptions.writeConfout, bSumEkinhOld); + do_md_trajectory_writing(fplog, + cr, + nfile, + fnm, + step, + step_rel, + t, + ir, + state, + state_global, + observablesHistory, + top_global, + fr, + outf, + energyOutput, + ekind, + f.view().force(), + isCheckpointingStep, + doRerun, + isLastStep, + mdrunOptions.writeConfout, + bSumEkinhOld); } stopHandler->setSignal(); @@ -587,15 +749,38 @@ void gmx::LegacySimulator::do_rerun() t_vcm* vcm = nullptr; SimulationSignaller signaller(&signals, cr, ms, doInterSimSignal, doIntraSimSignal); - compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), - makeConstArrayRef(state->v), state->box, mdatoms, nrnb, vcm, wcycle, - enerd, force_vir, shake_vir, total_vir, pres, constr, &signaller, - state->box, &totalNumberOfBondedInteractions, &bSumEkinhOld, + compute_globals(gstat, + cr, + ir, + fr, + ekind, + makeConstArrayRef(state->x), + makeConstArrayRef(state->v), + state->box, + mdatoms, + nrnb, + vcm, + wcycle, + enerd, + force_vir, + shake_vir, + total_vir, + pres, + constr, + &signaller, + state->box, + &totalNumberOfBondedInteractions, + &bSumEkinhOld, CGLO_GSTAT | CGLO_ENERGY | (shouldCheckNumberOfBondedInteractions ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0)); - checkNumberOfBondedInteractions(mdlog, cr, totalNumberOfBondedInteractions, top_global, - &top, makeConstArrayRef(state->x), state->box, + checkNumberOfBondedInteractions(mdlog, + cr, + totalNumberOfBondedInteractions, + top_global, + &top, + makeConstArrayRef(state->x), + state->box, &shouldCheckNumberOfBondedInteractions); } @@ -608,12 +793,27 @@ void gmx::LegacySimulator::do_rerun() if (MASTER(cr)) { const bool bCalcEnerStep = true; - energyOutput.addDataAtEnergyStep( - doFreeEnergyPerturbation, bCalcEnerStep, t, mdatoms->tmass, enerd, ir->fepvals, - ir->expandedvals, state->box, - PTCouplingArrays({ state->boxv, state->nosehoover_xi, state->nosehoover_vxi, - state->nhpres_xi, state->nhpres_vxi }), - state->fep_state, shake_vir, force_vir, total_vir, pres, ekind, mu_tot, constr); + energyOutput.addDataAtEnergyStep(doFreeEnergyPerturbation, + bCalcEnerStep, + t, + mdatoms->tmass, + enerd, + ir->fepvals, + ir->expandedvals, + state->box, + PTCouplingArrays({ state->boxv, + state->nosehoover_xi, + state->nosehoover_vxi, + state->nhpres_xi, + state->nhpres_vxi }), + state->fep_state, + shake_vir, + force_vir, + total_vir, + pres, + ekind, + mu_tot, + constr); const bool do_ene = true; const bool do_log = true; @@ -622,8 +822,15 @@ void gmx::LegacySimulator::do_rerun() const bool do_or = ir->nstorireout != 0; EnergyOutput::printAnnealingTemperatures(do_log ? fplog : nullptr, groups, &(ir->opts)); - energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), do_ene, do_dr, do_or, - do_log ? fplog : nullptr, step, t, fr->fcdata.get(), awh); + energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), + do_ene, + do_dr, + do_or, + do_log ? fplog : nullptr, + step, + t, + fr->fcdata.get(), + awh); if (do_per_step(step, ir->nstlog)) { @@ -650,8 +857,16 @@ void gmx::LegacySimulator::do_rerun() if ((ir->eSwapCoords != eswapNO) && (step > 0) && !isLastStep && do_per_step(step, ir->swap->nstswap)) { const bool doRerun = true; - do_swapcoords(cr, step, t, ir, swap, wcycle, rerun_fr.x, rerun_fr.box, - MASTER(cr) && mdrunOptions.verbose, doRerun); + do_swapcoords(cr, + step, + t, + ir, + swap, + wcycle, + rerun_fr.x, + rerun_fr.box, + MASTER(cr) && mdrunOptions.verbose, + doRerun); } if (MASTER(cr)) diff --git a/src/gromacs/mdrun/runner.cpp b/src/gromacs/mdrun/runner.cpp index e78faae8d5..2b1445ef55 100644 --- a/src/gromacs/mdrun/runner.cpp +++ b/src/gromacs/mdrun/runner.cpp @@ -388,8 +388,7 @@ void Mdrunner::spawnThreads(int numThreadsToLaunch) #if GMX_THREAD_MPI /* now spawn new threads that start mdrunner_start_fn(), while the main thread returns. Thread affinity is handled later. */ - if (tMPI_Init_fn(TRUE, numThreadsToLaunch, TMPI_AFFINITY_NONE, mdrunner_start_fn, - static_cast(this)) + if (tMPI_Init_fn(TRUE, numThreadsToLaunch, TMPI_AFFINITY_NONE, mdrunner_start_fn, static_cast(this)) != TMPI_SUCCESS) { GMX_THROW(gmx::InternalError("Failed to spawn thread-MPI threads")); @@ -452,7 +451,10 @@ static void prepare_verlet_scheme(FILE* fplog, { fprintf(fplog, "\nChanging rlist from %g to %g for non-bonded %dx%d atom kernels\n\n", - ir->rlist, rlist_new, listSetup.cluster_size_i, listSetup.cluster_size_j); + ir->rlist, + rlist_new, + listSetup.cluster_size_i, + listSetup.cluster_size_j); } ir->rlist = rlist_new; } @@ -460,7 +462,8 @@ static void prepare_verlet_scheme(FILE* fplog, if (nstlist_cmdline > 0 && (!EI_DYNAMICS(ir->eI) || ir->verletbuf_tol <= 0)) { - gmx_fatal(FARGS, "Can not set nstlist without %s", + gmx_fatal(FARGS, + "Can not set nstlist without %s", !EI_DYNAMICS(ir->eI) ? "dynamics" : "verlet-buffer-tolerance"); } @@ -490,11 +493,13 @@ static void override_nsteps_cmdline(const gmx::MDLogger& mdlog, int64_t nsteps_c { sprintf(sbuf_msg, "Overriding nsteps with value passed on the command line: %s steps, %.3g ps", - gmx_step_str(nsteps_cmdline, sbuf_steps), fabs(nsteps_cmdline * ir->delta_t)); + gmx_step_str(nsteps_cmdline, sbuf_steps), + fabs(nsteps_cmdline * ir->delta_t)); } else { - sprintf(sbuf_msg, "Overriding nsteps with value passed on the command line: %s steps", + sprintf(sbuf_msg, + "Overriding nsteps with value passed on the command line: %s steps", gmx_step_str(nsteps_cmdline, sbuf_steps)); } @@ -647,13 +652,16 @@ static void finish_run(FILE* fplog, { #if GMX_MPI /* reduce elapsed_time over all MPI ranks in the current simulation */ - MPI_Allreduce(&elapsed_time, &elapsed_time_over_all_ranks, 1, MPI_DOUBLE, MPI_SUM, - cr->mpi_comm_mysim); + MPI_Allreduce(&elapsed_time, &elapsed_time_over_all_ranks, 1, MPI_DOUBLE, MPI_SUM, cr->mpi_comm_mysim); elapsed_time_over_all_ranks /= cr->nnodes; /* Reduce elapsed_time_over_all_threads over all MPI ranks in the * current simulation. */ - MPI_Allreduce(&elapsed_time_over_all_threads, &elapsed_time_over_all_threads_over_all_ranks, - 1, MPI_DOUBLE, MPI_SUM, cr->mpi_comm_mysim); + MPI_Allreduce(&elapsed_time_over_all_threads, + &elapsed_time_over_all_threads_over_all_ranks, + 1, + MPI_DOUBLE, + MPI_SUM, + cr->mpi_comm_mysim); #endif } else @@ -678,8 +686,8 @@ static void finish_run(FILE* fplog, * to task parallelism. */ int nthreads_pp = gmx_omp_nthreads_get(emntNonbonded); int nthreads_pme = gmx_omp_nthreads_get(emntPME); - wallcycle_scale_by_num_threads(wcycle, thisRankHasDuty(cr, DUTY_PME) && !thisRankHasDuty(cr, DUTY_PP), - nthreads_pp, nthreads_pme); + wallcycle_scale_by_num_threads( + wcycle, thisRankHasDuty(cr, DUTY_PME) && !thisRankHasDuty(cr, DUTY_PP), nthreads_pp, nthreads_pme); auto cycle_sum(wallcycle_sum(cr, wcycle)); if (printReport) @@ -692,8 +700,16 @@ static void finish_run(FILE* fplog, { pme_gpu_get_timings(pme, &pme_gpu_timings); } - wallcycle_print(fplog, mdlog, cr->nnodes, cr->npmenodes, nthreads_pp, nthreads_pme, - elapsed_time_over_all_ranks, wcycle, cycle_sum, nbnxn_gpu_timings, + wallcycle_print(fplog, + mdlog, + cr->nnodes, + cr->npmenodes, + nthreads_pp, + nthreads_pme, + elapsed_time_over_all_ranks, + wcycle, + cycle_sum, + nbnxn_gpu_timings, &pme_gpu_timings); if (EI_DYNAMICS(inputrec->eI)) @@ -703,15 +719,23 @@ static void finish_run(FILE* fplog, if (fplog) { - print_perf(fplog, elapsed_time_over_all_threads_over_all_ranks, elapsed_time_over_all_ranks, + print_perf(fplog, + elapsed_time_over_all_threads_over_all_ranks, + elapsed_time_over_all_ranks, walltime_accounting_get_nsteps_done_since_reset(walltime_accounting), - delta_t, nbfs, mflop); + delta_t, + nbfs, + mflop); } if (bWriteStat) { - print_perf(stderr, elapsed_time_over_all_threads_over_all_ranks, elapsed_time_over_all_ranks, + print_perf(stderr, + elapsed_time_over_all_threads_over_all_ranks, + elapsed_time_over_all_ranks, walltime_accounting_get_nsteps_done_since_reset(walltime_accounting), - delta_t, nbfs, mflop); + delta_t, + nbfs, + mflop); } } } @@ -789,13 +813,13 @@ int Mdrunner::mdrunner() /* Read (nearly) all data required for the simulation * and keep the partly serialized tpr contents to send to other ranks later */ - applyGlobalSimulationState(*inputHolder_.get(), partialDeserializedTpr.get(), - globalState.get(), inputrec.get(), &mtop); + applyGlobalSimulationState( + *inputHolder_.get(), partialDeserializedTpr.get(), globalState.get(), inputrec.get(), &mtop); } /* Check and update the hardware options for internal consistency */ - checkAndUpdateHardwareOptions(mdlog, &hw_opt, isSimulationMasterRank, domdecOptions.numPmeRanks, - inputrec.get()); + checkAndUpdateHardwareOptions( + mdlog, &hw_opt, isSimulationMasterRank, domdecOptions.numPmeRanks, inputrec.get()); if (GMX_THREAD_MPI && isSimulationMasterRank) { @@ -810,13 +834,21 @@ int Mdrunner::mdrunner() // the number of GPUs to choose the number of ranks. auto canUseGpuForNonbonded = buildSupportsNonbondedOnGpu(nullptr); useGpuForNonbonded = decideWhetherToUseGpusForNonbondedWithThreadMpi( - nonbondedTarget, numDevicesToUse, userGpuTaskAssignment, emulateGpuNonbonded, + nonbondedTarget, + numDevicesToUse, + userGpuTaskAssignment, + emulateGpuNonbonded, canUseGpuForNonbonded, gpuAccelerationOfNonbondedIsUseful(mdlog, *inputrec, GMX_THREAD_MPI), hw_opt.nthreads_tmpi); - useGpuForPme = decideWhetherToUseGpusForPmeWithThreadMpi( - useGpuForNonbonded, pmeTarget, numDevicesToUse, userGpuTaskAssignment, *hwinfo_, - *inputrec, hw_opt.nthreads_tmpi, domdecOptions.numPmeRanks); + useGpuForPme = decideWhetherToUseGpusForPmeWithThreadMpi(useGpuForNonbonded, + pmeTarget, + numDevicesToUse, + userGpuTaskAssignment, + *hwinfo_, + *inputrec, + hw_opt.nthreads_tmpi, + domdecOptions.numPmeRanks); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR @@ -825,9 +857,15 @@ int Mdrunner::mdrunner() * TODO Over-writing the user-supplied value here does * prevent any possible subsequent checks from working * correctly. */ - hw_opt.nthreads_tmpi = - get_nthreads_mpi(hwinfo_, &hw_opt, numDevicesToUse, useGpuForNonbonded, useGpuForPme, - inputrec.get(), &mtop, mdlog, membedHolder.doMembed()); + hw_opt.nthreads_tmpi = get_nthreads_mpi(hwinfo_, + &hw_opt, + numDevicesToUse, + useGpuForNonbonded, + useGpuForPme, + inputrec.get(), + &mtop, + mdlog, + membedHolder.doMembed()); // Now start the threads for thread MPI. spawnThreads(hw_opt.nthreads_tmpi); @@ -858,7 +896,10 @@ int Mdrunner::mdrunner() // On non-master ranks, allocate the object that will receive data in the following call. inputrec = std::make_unique(); } - init_parallel(cr->mpiDefaultCommunicator, MASTER(cr), inputrec.get(), &mtop, + init_parallel(cr->mpiDefaultCommunicator, + MASTER(cr), + inputrec.get(), + &mtop, partialDeserializedTpr.get()); } GMX_RELEASE_ASSERT(inputrec != nullptr, "All ranks should have a valid inputrec now"); @@ -888,14 +929,22 @@ int Mdrunner::mdrunner() // assignment. auto canUseGpuForNonbonded = buildSupportsNonbondedOnGpu(nullptr); useGpuForNonbonded = decideWhetherToUseGpusForNonbonded( - nonbondedTarget, userGpuTaskAssignment, emulateGpuNonbonded, canUseGpuForNonbonded, - gpuAccelerationOfNonbondedIsUseful(mdlog, *inputrec, !GMX_THREAD_MPI), gpusWereDetected); - useGpuForPme = decideWhetherToUseGpusForPme( - useGpuForNonbonded, pmeTarget, userGpuTaskAssignment, *hwinfo_, *inputrec, - cr->sizeOfDefaultCommunicator, domdecOptions.numPmeRanks, gpusWereDetected); - useGpuForBonded = decideWhetherToUseGpusForBonded(useGpuForNonbonded, useGpuForPme, - bondedTarget, *inputrec, mtop, - domdecOptions.numPmeRanks, gpusWereDetected); + nonbondedTarget, + userGpuTaskAssignment, + emulateGpuNonbonded, + canUseGpuForNonbonded, + gpuAccelerationOfNonbondedIsUseful(mdlog, *inputrec, !GMX_THREAD_MPI), + gpusWereDetected); + useGpuForPme = decideWhetherToUseGpusForPme(useGpuForNonbonded, + pmeTarget, + userGpuTaskAssignment, + *hwinfo_, + *inputrec, + cr->sizeOfDefaultCommunicator, + domdecOptions.numPmeRanks, + gpusWereDetected); + useGpuForBonded = decideWhetherToUseGpusForBonded( + useGpuForNonbonded, useGpuForPme, bondedTarget, *inputrec, mtop, domdecOptions.numPmeRanks, gpusWereDetected); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR @@ -906,9 +955,15 @@ int Mdrunner::mdrunner() const DevelopmentFeatureFlags devFlags = manageDevelopmentFeatures(mdlog, useGpuForNonbonded, pmeRunMode); - const bool useModularSimulator = - checkUseModularSimulator(false, inputrec.get(), doRerun, mtop, ms, replExParams, - nullptr, doEssentialDynamics, membedHolder.doMembed()); + const bool useModularSimulator = checkUseModularSimulator(false, + inputrec.get(), + doRerun, + mtop, + ms, + replExParams, + nullptr, + doEssentialDynamics, + membedHolder.doMembed()); // Build restraints. // TODO: hide restraint implementation details from Mdrunner. @@ -970,8 +1025,8 @@ int Mdrunner::mdrunner() { globalState = std::make_unique(); } - broadcastStateWithoutDynamics(cr->mpiDefaultCommunicator, DOMAINDECOMP(cr), PAR(cr), - globalState.get()); + broadcastStateWithoutDynamics( + cr->mpiDefaultCommunicator, DOMAINDECOMP(cr), PAR(cr), globalState.get()); } /* A parallel command line option consistency check that we can @@ -1005,7 +1060,9 @@ int Mdrunner::mdrunner() { if (domdecOptions.numPmeRanks > 0) { - gmx_fatal_collective(FARGS, cr->mpiDefaultCommunicator, MASTER(cr), + gmx_fatal_collective(FARGS, + cr->mpiDefaultCommunicator, + MASTER(cr), "PME-only ranks are requested, but the system does not use PME " "for electrostatics or LJ"); } @@ -1046,18 +1103,27 @@ int Mdrunner::mdrunner() /* This needs to be called before read_checkpoint to extend the state */ t_disresdata* disresdata; snew(disresdata, 1); - init_disres(fplog, &mtop, inputrec.get(), DisResRunMode::MDRun, + init_disres(fplog, + &mtop, + inputrec.get(), + DisResRunMode::MDRun, MASTER(cr) ? DDRole::Master : DDRole::Agent, - PAR(cr) ? NumRanks::Multiple : NumRanks::Single, cr->mpi_comm_mysim, ms, disresdata, - globalState.get(), replExParams.exchangeInterval > 0); + PAR(cr) ? NumRanks::Multiple : NumRanks::Single, + cr->mpi_comm_mysim, + ms, + disresdata, + globalState.get(), + replExParams.exchangeInterval > 0); t_oriresdata* oriresdata; snew(oriresdata, 1); init_orires(fplog, &mtop, inputrec.get(), cr, ms, globalState.get(), oriresdata); - auto deform = prepareBoxDeformation( - globalState != nullptr ? globalState->box : box, MASTER(cr) ? DDRole::Master : DDRole::Agent, - PAR(cr) ? NumRanks::Multiple : NumRanks::Single, cr->mpi_comm_mygroup, *inputrec); + auto deform = prepareBoxDeformation(globalState != nullptr ? globalState->box : box, + MASTER(cr) ? DDRole::Master : DDRole::Agent, + PAR(cr) ? NumRanks::Multiple : NumRanks::Single, + cr->mpi_comm_mygroup, + *inputrec); #if GMX_FAHCORE /* We have to remember the generation's first step before reading checkpoint. @@ -1093,10 +1159,17 @@ int Mdrunner::mdrunner() // Finish applying initial simulation state information from external sources on all ranks. // Reconcile checkpoint file data with Mdrunner state established up to this point. - applyLocalState(*inputHolder_.get(), logFileHandle, cr, domdecOptions.numCells, - inputrec.get(), globalState.get(), &observablesHistory, - mdrunOptions.reproducible, mdModules_->notifier(), - modularSimulatorCheckpointData.get(), useModularSimulator); + applyLocalState(*inputHolder_.get(), + logFileHandle, + cr, + domdecOptions.numCells, + inputrec.get(), + globalState.get(), + &observablesHistory, + mdrunOptions.reproducible, + mdModules_->notifier(), + modularSimulatorCheckpointData.get(), + useModularSimulator); // TODO: (#3652) Synchronize filesystem state, SimulationInput contents, and program // invariants // on all code paths. @@ -1158,7 +1231,12 @@ int Mdrunner::mdrunner() * increase rlist) tries to check if the newly chosen value fits with the DD scheme. As this is * run before any DD scheme is set up, this check is never executed. See #3334 for more details. */ - prepare_verlet_scheme(fplog, cr, inputrec.get(), nstlist_cmdline, &mtop, box, + prepare_verlet_scheme(fplog, + cr, + inputrec.get(), + nstlist_cmdline, + &mtop, + box, useGpuForNonbonded || (emulateGpuNonbonded == EmulateGpuNonbonded::Yes), *hwinfo_->cpuInfo); @@ -1170,7 +1248,13 @@ int Mdrunner::mdrunner() if (useDomainDecomposition) { ddBuilder = std::make_unique( - mdlog, cr, domdecOptions, mdrunOptions, mtop, *inputrec, box, + mdlog, + cr, + domdecOptions, + mdrunOptions, + mtop, + *inputrec, + box, positionsFromStatePointer(globalState.get())); } else @@ -1190,9 +1274,18 @@ int Mdrunner::mdrunner() // Produce the task assignment for this rank - done after DD is constructed GpuTaskAssignments gpuTaskAssignments = GpuTaskAssignmentsBuilder::build( - gpuIdsToUse, userGpuTaskAssignment, *hwinfo_, simulationCommunicator, physicalNodeComm, - nonbondedTarget, pmeTarget, bondedTarget, updateTarget, useGpuForNonbonded, - useGpuForPme, thisRankHasDuty(cr, DUTY_PP), + gpuIdsToUse, + userGpuTaskAssignment, + *hwinfo_, + simulationCommunicator, + physicalNodeComm, + nonbondedTarget, + pmeTarget, + bondedTarget, + updateTarget, + useGpuForNonbonded, + useGpuForPme, + thisRankHasDuty(cr, DUTY_PP), // TODO cr->duty & DUTY_PME should imply that a PME // algorithm is active, but currently does not. EEL_PME(inputrec->coulombtype) && thisRankHasDuty(cr, DUTY_PME)); @@ -1241,11 +1334,21 @@ int Mdrunner::mdrunner() { const bool useUpdateGroups = cr->dd ? ddUsesUpdateGroups(*cr->dd) : false; - useGpuForUpdate = decideWhetherToUseGpuForUpdate( - useDomainDecomposition, useUpdateGroups, pmeRunMode, domdecOptions.numPmeRanks > 0, - useGpuForNonbonded, updateTarget, gpusWereDetected, *inputrec, mtop, - doEssentialDynamics, gmx_mtop_ftype_count(mtop, F_ORIRES) > 0, - replExParams.exchangeInterval > 0, doRerun, devFlags, mdlog); + useGpuForUpdate = decideWhetherToUseGpuForUpdate(useDomainDecomposition, + useUpdateGroups, + pmeRunMode, + domdecOptions.numPmeRanks > 0, + useGpuForNonbonded, + updateTarget, + gpusWereDetected, + *inputrec, + mtop, + doEssentialDynamics, + gmx_mtop_ftype_count(mtop, F_ORIRES) > 0, + replExParams.exchangeInterval > 0, + doRerun, + devFlags, + mdlog); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR @@ -1265,14 +1368,22 @@ int Mdrunner::mdrunner() MdrunScheduleWorkload runScheduleWork; - bool useGpuDirectHalo = decideWhetherToUseGpuForHalo( - devFlags, havePPDomainDecomposition(cr), useGpuForNonbonded, useModularSimulator, - doRerun, EI_ENERGY_MINIMIZATION(inputrec->eI)); + bool useGpuDirectHalo = decideWhetherToUseGpuForHalo(devFlags, + havePPDomainDecomposition(cr), + useGpuForNonbonded, + useModularSimulator, + doRerun, + EI_ENERGY_MINIMIZATION(inputrec->eI)); // Also populates the simulation constant workload description. - runScheduleWork.simulationWork = createSimulationWorkload( - *inputrec, disableNonbondedCalculation, devFlags, useGpuForNonbonded, pmeRunMode, - useGpuForBonded, useGpuForUpdate, useGpuDirectHalo); + runScheduleWork.simulationWork = createSimulationWorkload(*inputrec, + disableNonbondedCalculation, + devFlags, + useGpuForNonbonded, + pmeRunMode, + useGpuForBonded, + useGpuForUpdate, + useGpuDirectHalo); std::unique_ptr deviceStreamManager = nullptr; @@ -1309,10 +1420,12 @@ int Mdrunner::mdrunner() .appendTextFormatted( "This is simulation %d out of %d running as a composite GROMACS\n" "multi-simulation job. Setup for this simulation:\n", - ms->simulationIndex_, ms->numSimulations_); + ms->simulationIndex_, + ms->numSimulations_); } GMX_LOG(mdlog.warning) - .appendTextFormatted("Using %d MPI %s\n", cr->nnodes, + .appendTextFormatted("Using %d MPI %s\n", + cr->nnodes, # if GMX_THREAD_MPI cr->nnodes == 1 ? "thread" : "threads" # else @@ -1329,11 +1442,16 @@ int Mdrunner::mdrunner() // the OpenMP support. gmx_check_thread_affinity_set(mdlog, &hw_opt, hwinfo_->nthreads_hw_avail, FALSE); /* Check and update the number of OpenMP threads requested */ - checkAndUpdateRequestedNumOpenmpThreads(&hw_opt, *hwinfo_, cr, ms, physicalNodeComm.size_, - pmeRunMode, mtop, *inputrec); + checkAndUpdateRequestedNumOpenmpThreads( + &hw_opt, *hwinfo_, cr, ms, physicalNodeComm.size_, pmeRunMode, mtop, *inputrec); - gmx_omp_nthreads_init(mdlog, cr, hwinfo_->nthreads_hw_avail, physicalNodeComm.size_, - hw_opt.nthreads_omp, hw_opt.nthreads_omp_pme, !thisRankHasDuty(cr, DUTY_PP)); + gmx_omp_nthreads_init(mdlog, + cr, + hwinfo_->nthreads_hw_avail, + physicalNodeComm.size_, + hw_opt.nthreads_omp, + hw_opt.nthreads_omp_pme, + !thisRankHasDuty(cr, DUTY_PP)); // Enable FP exception detection, but not in // Release mode and not for compilers with known buggy FP @@ -1353,8 +1471,8 @@ int Mdrunner::mdrunner() } /* Now that we know the setup is consistent, check for efficiency */ - check_resource_division_efficiency(hwinfo_, gpuTaskAssignments.thisRankHasAnyGpuTask(), - mdrunOptions.ntompOptionIsSet, cr, mdlog); + check_resource_division_efficiency( + hwinfo_, gpuTaskAssignments.thisRankHasAnyGpuTask(), mdrunOptions.ntompOptionIsSet, cr, mdlog); /* getting number of PP/PME threads on this MPI / tMPI rank. PME: env variable should be read only on one node to make sure it is @@ -1362,8 +1480,8 @@ int Mdrunner::mdrunner() */ const int numThreadsOnThisRank = thisRankHasDuty(cr, DUTY_PP) ? gmx_omp_nthreads_get(emntNonbonded) : gmx_omp_nthreads_get(emntPME); - checkHardwareOversubscription(numThreadsOnThisRank, cr->nodeid, *hwinfo_->hardwareTopology, - physicalNodeComm, mdlog); + checkHardwareOversubscription( + numThreadsOnThisRank, cr->nodeid, *hwinfo_->hardwareTopology, physicalNodeComm, mdlog); // Enable Peer access between GPUs where available // Only for DD, only master PP rank needs to perform setup, and only if thread MPI plus @@ -1384,12 +1502,18 @@ int Mdrunner::mdrunner() gmx_check_thread_affinity_set(mdlog, &hw_opt, hwinfo_->nthreads_hw_avail, TRUE); int numThreadsOnThisNode, intraNodeThreadOffset; - analyzeThreadsOnThisNode(physicalNodeComm, numThreadsOnThisRank, &numThreadsOnThisNode, - &intraNodeThreadOffset); + analyzeThreadsOnThisNode( + physicalNodeComm, numThreadsOnThisRank, &numThreadsOnThisNode, &intraNodeThreadOffset); /* Set the CPU affinity */ - gmx_set_thread_affinity(mdlog, cr, &hw_opt, *hwinfo_->hardwareTopology, numThreadsOnThisRank, - numThreadsOnThisNode, intraNodeThreadOffset, nullptr); + gmx_set_thread_affinity(mdlog, + cr, + &hw_opt, + *hwinfo_->hardwareTopology, + numThreadsOnThisRank, + numThreadsOnThisNode, + intraNodeThreadOffset, + nullptr); } if (mdrunOptions.timingOptions.resetStep > -1) @@ -1412,8 +1536,14 @@ int Mdrunner::mdrunner() } // Membrane embedding must be initialized before we call init_forcerec() - membedHolder.initializeMembed(fplog, filenames.size(), filenames.data(), &mtop, inputrec.get(), - globalState.get(), cr, &mdrunOptions.checkpointOptions.period); + membedHolder.initializeMembed(fplog, + filenames.size(), + filenames.data(), + &mtop, + inputrec.get(), + globalState.get(), + cr, + &mdrunOptions.checkpointOptions.period); const bool thisRankHasPmeGpuTask = gpuTaskAssignments.thisRankHasPmeGpuTask(); std::unique_ptr mdAtoms; @@ -1430,10 +1560,17 @@ int Mdrunner::mdrunner() /* Initiate forcerecord */ fr = new t_forcerec; fr->forceProviders = mdModules_->initForceProviders(); - init_forcerec(fplog, mdlog, fr, inputrec.get(), &mtop, cr, box, + init_forcerec(fplog, + mdlog, + fr, + inputrec.get(), + &mtop, + cr, + box, opt2fn("-table", filenames.size(), filenames.data()), opt2fn("-tablep", filenames.size(), filenames.data()), - opt2fns("-tableb", filenames.size(), filenames.data()), pforce); + opt2fns("-tableb", filenames.size(), filenames.data()), + pforce); // Dirty hack, for fixing disres and orires should be made mdmodules fr->fcdata->disres = disresdata; fr->fcdata->orires = oriresdata; @@ -1453,13 +1590,22 @@ int Mdrunner::mdrunner() "GPU PP-PME stream should be valid in order to use GPU PME-PP direct " "communications."); fr->pmePpCommGpu = std::make_unique( - cr->mpi_comm_mysim, cr->dd->pme_nodeid, deviceStreamManager->context(), + cr->mpi_comm_mysim, + cr->dd->pme_nodeid, + deviceStreamManager->context(), deviceStreamManager->stream(DeviceStreamType::PmePpTransfer)); } - fr->nbv = Nbnxm::init_nb_verlet(mdlog, inputrec.get(), fr, cr, *hwinfo_, + fr->nbv = Nbnxm::init_nb_verlet(mdlog, + inputrec.get(), + fr, + cr, + *hwinfo_, runScheduleWork.simulationWork.useGpuNonbonded, - deviceStreamManager.get(), &mtop, box, wcycle); + deviceStreamManager.get(), + &mtop, + box, + wcycle); // TODO: Move the logic below to a GPU bonded builder if (runScheduleWork.simulationWork.useGpuBonded) { @@ -1467,8 +1613,11 @@ int Mdrunner::mdrunner() "GPU device stream manager should be valid in order to use GPU " "version of bonded forces."); gpuBonded = std::make_unique( - mtop.ffparams, fr->ic->epsfac * fr->fudgeQQ, deviceStreamManager->context(), - deviceStreamManager->bondedStream(havePPDomainDecomposition(cr)), wcycle); + mtop.ffparams, + fr->ic->epsfac * fr->fudgeQQ, + deviceStreamManager->context(), + deviceStreamManager->bondedStream(havePPDomainDecomposition(cr)), + wcycle); fr->gpuBonded = gpuBonded.get(); } @@ -1593,11 +1742,21 @@ int Mdrunner::mdrunner() ? &deviceStreamManager->stream(DeviceStreamType::Pme) : nullptr; - pmedata = gmx_pme_init(cr, getNumPmeDomains(cr->dd), inputrec.get(), - nChargePerturbed != 0, nTypePerturbed != 0, - mdrunOptions.reproducible, ewaldcoeff_q, ewaldcoeff_lj, - gmx_omp_nthreads_get(emntPME), pmeRunMode, nullptr, - deviceContext, pmeStream, pmeGpuProgram.get(), mdlog); + pmedata = gmx_pme_init(cr, + getNumPmeDomains(cr->dd), + inputrec.get(), + nChargePerturbed != 0, + nTypePerturbed != 0, + mdrunOptions.reproducible, + ewaldcoeff_q, + ewaldcoeff_lj, + gmx_omp_nthreads_get(emntPME), + pmeRunMode, + nullptr, + deviceContext, + pmeStream, + pmeGpuProgram.get(), + mdlog); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR } @@ -1623,7 +1782,12 @@ int Mdrunner::mdrunner() if (inputrec->bPull) { /* Initialize pull code */ - pull_work = init_pull(fplog, inputrec->pull.get(), inputrec.get(), &mtop, cr, &atomSets, + pull_work = init_pull(fplog, + inputrec->pull.get(), + inputrec.get(), + &mtop, + cr, + &atomSets, inputrec->fepvals->init_lambda); if (inputrec->pull->bXOutAverage || inputrec->pull->bFOutAverage) { @@ -1639,8 +1803,16 @@ int Mdrunner::mdrunner() if (inputrec->bRot) { /* Initialize enforced rotation code */ - enforcedRotation = init_rot(fplog, inputrec.get(), filenames.size(), filenames.data(), - cr, &atomSets, globalState.get(), &mtop, oenv, mdrunOptions, + enforcedRotation = init_rot(fplog, + inputrec.get(), + filenames.size(), + filenames.data(), + cr, + &atomSets, + globalState.get(), + &mtop, + oenv, + mdrunOptions, startingBehavior); } @@ -1648,15 +1820,22 @@ int Mdrunner::mdrunner() if (inputrec->eSwapCoords != eswapNO) { /* Initialize ion swapping code */ - swap = init_swapcoords(fplog, inputrec.get(), + swap = init_swapcoords(fplog, + inputrec.get(), opt2fn_master("-swap", filenames.size(), filenames.data(), cr), - &mtop, globalState.get(), &observablesHistory, cr, &atomSets, - oenv, mdrunOptions, startingBehavior); + &mtop, + globalState.get(), + &observablesHistory, + cr, + &atomSets, + oenv, + mdrunOptions, + startingBehavior); } /* Let makeConstraints know whether we have essential dynamics constraints. */ - auto constr = makeConstraints(mtop, *inputrec, pull_work, doEssentialDynamics, fplog, cr, - ms, &nrnb, wcycle, fr->bMolPBC); + auto constr = makeConstraints( + mtop, *inputrec, pull_work, doEssentialDynamics, fplog, cr, ms, &nrnb, wcycle, fr->bMolPBC); /* Energy terms and groups */ gmx_enerdata_t enerd(mtop.groups.groups[SimulationAtomGroupType::EnergyOutput].size(), @@ -1667,10 +1846,19 @@ int Mdrunner::mdrunner() init_ekindata(fplog, &mtop, &(inputrec->opts), &ekind, inputrec->cos_accel); /* Set up interactive MD (IMD) */ - auto imdSession = - makeImdSession(inputrec.get(), cr, wcycle, &enerd, ms, &mtop, mdlog, - MASTER(cr) ? globalState->x.rvec_array() : nullptr, filenames.size(), - filenames.data(), oenv, mdrunOptions.imdOptions, startingBehavior); + auto imdSession = makeImdSession(inputrec.get(), + cr, + wcycle, + &enerd, + ms, + &mtop, + mdlog, + MASTER(cr) ? globalState->x.rvec_array() : nullptr, + filenames.size(), + filenames.data(), + oenv, + mdrunOptions.imdOptions, + startingBehavior); if (DOMAINDECOMP(cr)) { @@ -1678,18 +1866,25 @@ int Mdrunner::mdrunner() /* This call is not included in init_domain_decomposition mainly * because fr->cginfo_mb is set later. */ - dd_init_bondeds(fplog, cr->dd, mtop, vsite.get(), inputrec.get(), - domdecOptions.checkBondedInteractions, fr->cginfo_mb); + dd_init_bondeds(fplog, + cr->dd, + mtop, + vsite.get(), + inputrec.get(), + domdecOptions.checkBondedInteractions, + fr->cginfo_mb); } if (runScheduleWork.simulationWork.useGpuBufferOps) { fr->gpuForceReduction[gmx::AtomLocality::Local] = std::make_unique( deviceStreamManager->context(), - deviceStreamManager->stream(gmx::DeviceStreamType::NonBondedLocal), wcycle); + deviceStreamManager->stream(gmx::DeviceStreamType::NonBondedLocal), + wcycle); fr->gpuForceReduction[gmx::AtomLocality::NonLocal] = std::make_unique( deviceStreamManager->context(), - deviceStreamManager->stream(gmx::DeviceStreamType::NonBondedNonLocal), wcycle); + deviceStreamManager->stream(gmx::DeviceStreamType::NonBondedNonLocal), + wcycle); } std::unique_ptr stateGpu; @@ -1719,11 +1914,10 @@ int Mdrunner::mdrunner() simulatorBuilder.add(SimulatorEnv(fplog, cr, ms, mdlog, oenv)); simulatorBuilder.add(Profiling(&nrnb, walltime_accounting, wcycle)); simulatorBuilder.add(ConstraintsParam( - constr.get(), enforcedRotation ? enforcedRotation->getLegacyEnfrot() : nullptr, - vsite.get())); + constr.get(), enforcedRotation ? enforcedRotation->getLegacyEnfrot() : nullptr, vsite.get())); // TODO: Separate `fr` to a separate add, and make the `build` handle the coupling sensibly. - simulatorBuilder.add(LegacyInput(static_cast(filenames.size()), filenames.data(), - inputrec.get(), fr)); + simulatorBuilder.add(LegacyInput( + static_cast(filenames.size()), filenames.data(), inputrec.get(), fr)); simulatorBuilder.add(ReplicaExchangeParameters(replExParams)); simulatorBuilder.add(InteractiveMD(imdSession.get())); simulatorBuilder.add(SimulatorModules(mdModules_->outputProvider(), mdModules_->notifier())); @@ -1755,7 +1949,13 @@ int Mdrunner::mdrunner() GMX_RELEASE_ASSERT(pmedata, "pmedata was NULL while cr->duty was not DUTY_PP"); /* do PME only */ walltime_accounting = walltime_accounting_init(gmx_omp_nthreads_get(emntPME)); - gmx_pmeonly(pmedata, cr, &nrnb, wcycle, walltime_accounting, inputrec.get(), pmeRunMode, + gmx_pmeonly(pmedata, + cr, + &nrnb, + wcycle, + walltime_accounting, + inputrec.get(), + pmeRunMode, deviceStreamManager.get()); } @@ -1764,8 +1964,16 @@ int Mdrunner::mdrunner() /* Finish up, write some stuff * if rerunMD, don't write last frame again */ - finish_run(fplog, mdlog, cr, inputrec.get(), &nrnb, wcycle, walltime_accounting, - fr ? fr->nbv.get() : nullptr, pmedata, EI_DYNAMICS(inputrec->eI) && !isMultiSim(ms)); + finish_run(fplog, + mdlog, + cr, + inputrec.get(), + &nrnb, + wcycle, + walltime_accounting, + fr ? fr->nbv.get() : nullptr, + pmedata, + EI_DYNAMICS(inputrec->eI) && !isMultiSim(ms)); // clean up cycle counter wallcycle_destroy(wcycle); diff --git a/src/gromacs/mdrun/shellfc.cpp b/src/gromacs/mdrun/shellfc.cpp index ccc3c3e3ca..35853df4f3 100644 --- a/src/gromacs/mdrun/shellfc.cpp +++ b/src/gromacs/mdrun/shellfc.cpp @@ -450,7 +450,10 @@ gmx_shellfc_t* init_shell_flexcon(FILE* fplog, gmx_fatal(FARGS, "polarize can not be used with qA(%e) != qB(%e) for " "atom %d of molecule block %zu", - qS, atom[aS].qB, aS + 1, mb + 1); + qS, + atom[aS].qB, + aS + 1, + mb + 1); } shell[nsi].k += gmx::square(qS) * ONE_4PI_EPS0 / ffparams->iparams[type].polarize.alpha; @@ -461,7 +464,10 @@ gmx_shellfc_t* init_shell_flexcon(FILE* fplog, gmx_fatal(FARGS, "water_pol can not be used with qA(%e) != qB(%e) for " "atom %d of molecule block %zu", - qS, atom[aS].qB, aS + 1, mb + 1); + qS, + atom[aS].qB, + aS + 1, + mb + 1); } alpha = (ffparams->iparams[type].wpol.al_x + ffparams->iparams[type].wpol.al_y @@ -819,8 +825,13 @@ static void dump_shells(FILE* fp, ArrayRef f, real ftol, ArrayRef ft2) { - fprintf(fp, "SHELL %5d, force %10.5f %10.5f %10.5f, |f| %10.5f\n", ind, f[ind][XX], - f[ind][YY], f[ind][ZZ], std::sqrt(ff2)); + fprintf(fp, + "SHELL %5d, force %10.5f %10.5f %10.5f, |f| %10.5f\n", + ind, + f[ind][XX], + f[ind][YY], + f[ind][ZZ], + std::sqrt(ff2)); } } } @@ -887,13 +898,35 @@ static void init_adir(gmx_shellfc_t* shfc, bool needsLogging = false; bool computeEnergy = false; bool computeVirial = false; - constr->apply(needsLogging, computeEnergy, step, 0, 1.0, xCurrent, - shfc->adir_xnold.arrayRefWithPadding(), {}, box, lambda[efptBONDED], - &(dvdlambda[efptBONDED]), {}, computeVirial, nullptr, + constr->apply(needsLogging, + computeEnergy, + step, + 0, + 1.0, + xCurrent, + shfc->adir_xnold.arrayRefWithPadding(), + {}, + box, + lambda[efptBONDED], + &(dvdlambda[efptBONDED]), + {}, + computeVirial, + nullptr, gmx::ConstraintVariable::Positions); - constr->apply(needsLogging, computeEnergy, step, 0, 1.0, xCurrent, - shfc->adir_xnew.arrayRefWithPadding(), {}, box, lambda[efptBONDED], - &(dvdlambda[efptBONDED]), {}, computeVirial, nullptr, + constr->apply(needsLogging, + computeEnergy, + step, + 0, + 1.0, + xCurrent, + shfc->adir_xnew.arrayRefWithPadding(), + {}, + box, + lambda[efptBONDED], + &(dvdlambda[efptBONDED]), + {}, + computeVirial, + nullptr, gmx::ConstraintVariable::Positions); for (n = 0; n < end; n++) @@ -907,9 +940,21 @@ static void init_adir(gmx_shellfc_t* shfc, } /* Project the acceleration on the old bond directions */ - constr->apply(needsLogging, computeEnergy, step, 0, 1.0, xOld, shfc->adir_xnew.arrayRefWithPadding(), - acc_dir, box, lambda[efptBONDED], &(dvdlambda[efptBONDED]), {}, computeVirial, - nullptr, gmx::ConstraintVariable::Deriv_FlexCon); + constr->apply(needsLogging, + computeEnergy, + step, + 0, + 1.0, + xOld, + shfc->adir_xnew.arrayRefWithPadding(), + acc_dir, + box, + lambda[efptBONDED], + &(dvdlambda[efptBONDED]), + {}, + computeVirial, + nullptr, + gmx::ConstraintVariable::Deriv_FlexCon); } void relax_shell_flexcon(FILE* fplog, @@ -1003,8 +1048,8 @@ void relax_shell_flexcon(FILE* fplog, * before do_force is called, which normally puts all * charge groups in the box. */ - put_atoms_in_box_omp(fr->pbcType, box, x.subArray(0, md->homenr), - gmx_omp_nthreads_get(emntDefault)); + put_atoms_in_box_omp( + fr->pbcType, box, x.subArray(0, md->homenr), gmx_omp_nthreads_get(emntDefault)); } if (nflexcon) @@ -1036,16 +1081,54 @@ void relax_shell_flexcon(FILE* fplog, } int shellfc_flags = force_flags | (bVerbose ? GMX_FORCE_ENERGY : 0); gmx::ForceBuffersView forceViewInit = gmx::ForceBuffersView(forceWithPadding[Min], {}, false); - do_force(fplog, cr, ms, inputrec, nullptr, enforcedRotation, imdSession, pull_work, mdstep, - nrnb, wcycle, top, box, xPadded, hist, &forceViewInit, force_vir, md, enerd, lambda, - fr, runScheduleWork, vsite, mu_tot, t, nullptr, - (bDoNS ? GMX_FORCE_NS : 0) | shellfc_flags, ddBalanceRegionHandler); + do_force(fplog, + cr, + ms, + inputrec, + nullptr, + enforcedRotation, + imdSession, + pull_work, + mdstep, + nrnb, + wcycle, + top, + box, + xPadded, + hist, + &forceViewInit, + force_vir, + md, + enerd, + lambda, + fr, + runScheduleWork, + vsite, + mu_tot, + t, + nullptr, + (bDoNS ? GMX_FORCE_NS : 0) | shellfc_flags, + ddBalanceRegionHandler); sf_dir = 0; if (nflexcon) { - init_adir(shfc, constr, inputrec, cr, dd_ac1, mdstep, md, end, shfc->x_old.arrayRefWithPadding(), - x, xPadded, force[Min], shfc->acc_dir, box, lambda, &dum); + init_adir(shfc, + constr, + inputrec, + cr, + dd_ac1, + mdstep, + md, + end, + shfc->x_old.arrayRefWithPadding(), + x, + xPadded, + force[Min], + shfc->acc_dir, + box, + lambda, + &dum); for (i = 0; i < end; i++) { @@ -1073,9 +1156,11 @@ void relax_shell_flexcon(FILE* fplog, * shell positions are updated, therefore the other particles must * be set here, in advance. */ - std::copy(xPadded.paddedArrayRef().begin(), xPadded.paddedArrayRef().end(), + std::copy(xPadded.paddedArrayRef().begin(), + xPadded.paddedArrayRef().end(), posWithPadding[Min].paddedArrayRef().begin()); - std::copy(xPadded.paddedArrayRef().begin(), xPadded.paddedArrayRef().end(), + std::copy(xPadded.paddedArrayRef().begin(), + xPadded.paddedArrayRef().end(), posWithPadding[Try].paddedArrayRef().begin()); } @@ -1106,9 +1191,22 @@ void relax_shell_flexcon(FILE* fplog, if (nflexcon) { - init_adir(shfc, constr, inputrec, cr, dd_ac1, mdstep, md, end, - shfc->x_old.arrayRefWithPadding(), x, posWithPadding[Min], force[Min], - shfc->acc_dir, box, lambda, &dum); + init_adir(shfc, + constr, + inputrec, + cr, + dd_ac1, + mdstep, + md, + end, + shfc->x_old.arrayRefWithPadding(), + x, + posWithPadding[Min], + force[Min], + shfc->acc_dir, + box, + lambda, + &dum); directional_sd(pos[Min], pos[Try], shfc->acc_dir, end, fr->fc_stepsize); } @@ -1123,9 +1221,34 @@ void relax_shell_flexcon(FILE* fplog, } /* Try the new positions */ gmx::ForceBuffersView forceViewTry = gmx::ForceBuffersView(forceWithPadding[Try], {}, false); - do_force(fplog, cr, ms, inputrec, nullptr, enforcedRotation, imdSession, pull_work, 1, nrnb, wcycle, - top, box, posWithPadding[Try], hist, &forceViewTry, force_vir, md, enerd, lambda, fr, - runScheduleWork, vsite, mu_tot, t, nullptr, shellfc_flags, ddBalanceRegionHandler); + do_force(fplog, + cr, + ms, + inputrec, + nullptr, + enforcedRotation, + imdSession, + pull_work, + 1, + nrnb, + wcycle, + top, + box, + posWithPadding[Try], + hist, + &forceViewTry, + force_vir, + md, + enerd, + lambda, + fr, + runScheduleWork, + vsite, + mu_tot, + t, + nullptr, + shellfc_flags, + ddBalanceRegionHandler); accumulatePotentialEnergies(enerd, lambda, inputrec->fepvals); if (gmx_debug_at) { @@ -1135,9 +1258,22 @@ void relax_shell_flexcon(FILE* fplog, sf_dir = 0; if (nflexcon) { - init_adir(shfc, constr, inputrec, cr, dd_ac1, mdstep, md, end, - shfc->x_old.arrayRefWithPadding(), x, posWithPadding[Try], force[Try], - shfc->acc_dir, box, lambda, &dum); + init_adir(shfc, + constr, + inputrec, + cr, + dd_ac1, + mdstep, + md, + end, + shfc->x_old.arrayRefWithPadding(), + x, + posWithPadding[Try], + force[Try], + shfc->acc_dir, + box, + lambda, + &dum); ArrayRef acc_dir = shfc->acc_dir; for (i = 0; i < end; i++) @@ -1210,11 +1346,17 @@ void relax_shell_flexcon(FILE* fplog, /* Note that the energies and virial are incorrect when not converged */ if (fplog) { - fprintf(fplog, "step %s: EM did not converge in %d iterations, RMS force %6.2e\n", - gmx_step_str(mdstep, sbuf), number_steps, df[Min]); + fprintf(fplog, + "step %s: EM did not converge in %d iterations, RMS force %6.2e\n", + gmx_step_str(mdstep, sbuf), + number_steps, + df[Min]); } - fprintf(stderr, "step %s: EM did not converge in %d iterations, RMS force %6.2e\n", - gmx_step_str(mdstep, sbuf), number_steps, df[Min]); + fprintf(stderr, + "step %s: EM did not converge in %d iterations, RMS force %6.2e\n", + gmx_step_str(mdstep, sbuf), + number_steps, + df[Min]); } /* Copy back the coordinates and the forces */ @@ -1227,9 +1369,11 @@ void done_shellfc(FILE* fplog, gmx_shellfc_t* shfc, int64_t numSteps) if (shfc && fplog && numSteps > 0) { double numStepsAsDouble = static_cast(numSteps); - fprintf(fplog, "Fraction of iterations that converged: %.2f %%\n", + fprintf(fplog, + "Fraction of iterations that converged: %.2f %%\n", (shfc->numConvergedIterations * 100.0) / numStepsAsDouble); - fprintf(fplog, "Average number of force evaluations per MD step: %.2f\n\n", + fprintf(fplog, + "Average number of force evaluations per MD step: %.2f\n\n", shfc->numForceEvaluations / numStepsAsDouble); } diff --git a/src/gromacs/mdrun/simulationinput.cpp b/src/gromacs/mdrun/simulationinput.cpp index a29c252103..b22c7ee3ac 100644 --- a/src/gromacs/mdrun/simulationinput.cpp +++ b/src/gromacs/mdrun/simulationinput.cpp @@ -52,8 +52,8 @@ void applyGlobalSimulationState(const SimulationInput& simulationInput, t_inputrec* inputRecord, gmx_mtop_t* molecularTopology) { - *partialDeserializedTpr = read_tpx_state(simulationInput.tprFilename_.c_str(), inputRecord, - globalState, molecularTopology); + *partialDeserializedTpr = read_tpx_state( + simulationInput.tprFilename_.c_str(), inputRecord, globalState, molecularTopology); } void applyLocalState(const SimulationInput& simulationInput, @@ -68,9 +68,17 @@ void applyLocalState(const SimulationInput& simulationInput, gmx::ReadCheckpointDataHolder* modularSimulatorCheckpointData, const bool useModularSimulator) { - load_checkpoint(simulationInput.cpiFilename_.c_str(), logfio, cr, dd_nc, inputRecord, state, - observablesHistory, reproducibilityRequested, mdModulesNotifier, - modularSimulatorCheckpointData, useModularSimulator); + load_checkpoint(simulationInput.cpiFilename_.c_str(), + logfio, + cr, + dd_nc, + inputRecord, + state, + observablesHistory, + reproducibilityRequested, + mdModulesNotifier, + modularSimulatorCheckpointData, + useModularSimulator); } } // end namespace gmx diff --git a/src/gromacs/mdrun/tpi.cpp b/src/gromacs/mdrun/tpi.cpp index 7536de08eb..481a361962 100644 --- a/src/gromacs/mdrun/tpi.cpp +++ b/src/gromacs/mdrun/tpi.cpp @@ -386,10 +386,11 @@ void LegacySimulator::do_tpi() if (fplog) { - fprintf(fplog, "\nWill insert %d atoms %s partial charges\n", a_tp1 - a_tp0, - bCharge ? "with" : "without"); + fprintf(fplog, "\nWill insert %d atoms %s partial charges\n", a_tp1 - a_tp0, bCharge ? "with" : "without"); - fprintf(fplog, "\nWill insert %" PRId64 " times in each frame of %s\n", nsteps, + fprintf(fplog, + "\nWill insert %" PRId64 " times in each frame of %s\n", + nsteps, opt2fn("-rerun", nfile, fnm)); } @@ -404,14 +405,16 @@ void LegacySimulator::do_tpi() gmx_fatal(FARGS, "Re-using the neighborlist %d times for insertions of a single atom in a " "sphere of radius %f does not make sense", - inputrec->nstlist, drmax); + inputrec->nstlist, + drmax); } if (fplog) { fprintf(fplog, "Will use the same neighborlist for %d insertions in a sphere of radius " "%f\n", - inputrec->nstlist, drmax); + inputrec->nstlist, + drmax); } } } @@ -475,8 +478,11 @@ void LegacySimulator::do_tpi() if (MASTER(cr)) { - fp_tpi = xvgropen(opt2fn("-tpi", nfile, fnm), "TPI energies", "Time (ps)", - "(kJ mol\\S-1\\N) / (nm\\S3\\N)", oenv); + fp_tpi = xvgropen(opt2fn("-tpi", nfile, fnm), + "TPI energies", + "Time (ps)", + "(kJ mol\\S-1\\N) / (nm\\S3\\N)", + oenv); xvgr_subtitle(fp_tpi, "f. are averages over one frame", oenv); snew(leg, 4 + nener); e = 0; @@ -492,7 +498,8 @@ void LegacySimulator::do_tpi() leg[e++] = gmx_strdup(str); for (i = 0; i < ngid; i++) { - sprintf(str, "f. ", + sprintf(str, + "f. ", *(groups->groupNames[groups->groups[SimulationAtomGroupType::EnergyOutput][i]])); leg[e++] = gmx_strdup(str); } @@ -505,7 +512,8 @@ void LegacySimulator::do_tpi() { for (i = 0; i < ngid; i++) { - sprintf(str, "f. ", + sprintf(str, + "f. ", *(groups->groupNames[groups->groups[SimulationAtomGroupType::EnergyOutput][i]])); leg[e++] = gmx_strdup(str); } @@ -547,7 +555,10 @@ void LegacySimulator::do_tpi() "Number of atoms in trajectory (%d)%s " "is not equal the number in the run input file (%d) " "minus the number of atoms to insert (%d)\n", - rerun_fr.natoms, bCavity ? " minus one" : "", mdatoms->nr, a_tp1 - a_tp0); + rerun_fr.natoms, + bCavity ? " minus one" : "", + mdatoms->nr, + a_tp1 - a_tp0); } refvolshift = log(det(rerun_fr.box)); @@ -602,8 +613,8 @@ void LegacySimulator::do_tpi() /* Put all atoms except for the inserted ones on the grid */ rvec vzero = { 0, 0, 0 }; rvec boxDiagonal = { box[XX][XX], box[YY][YY], box[ZZ][ZZ] }; - nbnxn_put_on_grid(fr->nbv.get(), box, 0, vzero, boxDiagonal, nullptr, { 0, a_tp0 }, -1, - fr->cginfo, x, 0, nullptr); + nbnxn_put_on_grid( + fr->nbv.get(), box, 0, vzero, boxDiagonal, nullptr, { 0, a_tp0 }, -1, fr->cginfo, x, 0, nullptr); step = cr->nodeid * stepblocksize; while (step < nsteps) @@ -674,8 +685,8 @@ void LegacySimulator::do_tpi() } /* Put the inserted molecule on it's own search grid */ - nbnxn_put_on_grid(fr->nbv.get(), box, 1, x_init, x_init, nullptr, { a_tp0, a_tp1 }, - -1, fr->cginfo, x, 0, nullptr); + nbnxn_put_on_grid( + fr->nbv.get(), box, 1, x_init, x_init, nullptr, { a_tp0, a_tp1 }, -1, fr->cginfo, x, 0, nullptr); /* TODO: Avoid updating all atoms at every bNS step */ fr->nbv->setAtomProperties(gmx::constArrayRefFromArray(mdatoms->typeA, mdatoms->nr), @@ -725,8 +736,7 @@ void LegacySimulator::do_tpi() real angleX = 2 * M_PI * dist(rng); real angleY = 2 * M_PI * dist(rng); real angleZ = 2 * M_PI * dist(rng); - rotate_conf(a_tp1 - a_tp0, state_global->x.rvec_array() + a_tp0, nullptr, angleX, - angleY, angleZ); + rotate_conf(a_tp1 - a_tp0, state_global->x.rvec_array() + a_tp0, nullptr, angleX, angleY, angleZ); /* Shift to the insertion location */ for (i = a_tp0; i < a_tp1; i++) { @@ -753,10 +763,32 @@ void LegacySimulator::do_tpi() // might raise, then restore the old behaviour. std::fenv_t floatingPointEnvironment; std::feholdexcept(&floatingPointEnvironment); - do_force(fplog, cr, ms, inputrec, nullptr, nullptr, imdSession, pull_work, step, nrnb, - wcycle, &top, state_global->box, state_global->x.arrayRefWithPadding(), - &state_global->hist, &f.view(), force_vir, mdatoms, enerd, - state_global->lambda, fr, runScheduleWork, nullptr, mu_tot, t, nullptr, + do_force(fplog, + cr, + ms, + inputrec, + nullptr, + nullptr, + imdSession, + pull_work, + step, + nrnb, + wcycle, + &top, + state_global->box, + state_global->x.arrayRefWithPadding(), + &state_global->hist, + &f.view(), + force_vir, + mdatoms, + enerd, + state_global->lambda, + fr, + runScheduleWork, + nullptr, + mu_tot, + t, + nullptr, GMX_FORCE_NONBONDED | GMX_FORCE_ENERGY | (bStateChanged ? GMX_FORCE_STATECHANGED : 0), DDBalanceRegionHandler(nullptr)); std::feclearexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW); @@ -811,8 +843,10 @@ void LegacySimulator::do_tpi() if (debug) { fprintf(debug, - "\n time %.3f, step %d: non-finite energy %f, using exp(-bU)=0\n", t, - static_cast(step), epot); + "\n time %.3f, step %d: non-finite energy %f, using exp(-bU)=0\n", + t, + static_cast(step), + epot); } embU = 0; } @@ -879,16 +913,26 @@ void LegacySimulator::do_tpi() if (debug) { - fprintf(debug, "TPI %7d %12.5e %12.5f %12.5f %12.5f\n", static_cast(step), - epot, x_tp[XX], x_tp[YY], x_tp[ZZ]); + fprintf(debug, + "TPI %7d %12.5e %12.5f %12.5f %12.5f\n", + static_cast(step), + epot, + x_tp[XX], + x_tp[YY], + x_tp[ZZ]); } if (dump_pdb && epot <= dump_ener) { sprintf(str, "t%g_step%d.pdb", t, static_cast(step)); sprintf(str2, "t: %f step %d ener: %f", t, static_cast(step), epot); - write_sto_conf_mtop(str, str2, top_global, state_global->x.rvec_array(), - state_global->v.rvec_array(), inputrec->pbcType, state_global->box); + write_sto_conf_mtop(str, + str2, + top_global, + state_global->x.rvec_array(), + state_global->v.rvec_array(), + inputrec->pbcType, + state_global->box); } step++; @@ -914,13 +958,19 @@ void LegacySimulator::do_tpi() { if (mdrunOptions.verbose || frame % 10 == 0 || frame < 10) { - fprintf(stderr, "mu %10.3e %10.3e\n", -log(sum_embU / nsteps) / beta, + fprintf(stderr, + "mu %10.3e %10.3e\n", + -log(sum_embU / nsteps) / beta, -log(VembU_all / V_all) / beta); } - fprintf(fp_tpi, "%10.3f %12.5e %12.5e %12.5e %12.5e", t, + fprintf(fp_tpi, + "%10.3f %12.5e %12.5e %12.5e %12.5e", + t, VembU_all == 0 ? 20 / beta : -log(VembU_all / V_all) / beta, - sum_embU == 0 ? 20 / beta : -log(sum_embU / nsteps) / beta, sum_embU / nsteps, V); + sum_embU == 0 ? 20 / beta : -log(sum_embU / nsteps) / beta, + sum_embU / nsteps, + V); for (e = 0; e < nener; e++) { fprintf(fp_tpi, " %12.5e", sum_UgembU[e] / nsteps); @@ -966,16 +1016,18 @@ void LegacySimulator::do_tpi() } if (MASTER(cr)) { - fp_tpi = xvgropen(opt2fn("-tpid", nfile, fnm), "TPI energy distribution", - "\\betaU - log(V/)", "count", oenv); + fp_tpi = xvgropen(opt2fn("-tpid", nfile, fnm), + "TPI energy distribution", + "\\betaU - log(V/)", + "count", + oenv); sprintf(str, "number \\betaU > %g: %9.3e", bU_bin_limit, bin[0]); xvgr_subtitle(fp_tpi, str, oenv); xvgr_legend(fp_tpi, 2, tpid_leg, oenv); for (i = nbin - 1; i > 0; i--) { bUlogV = -i / invbinw + bU_logV_bin_limit - refvolshift + log(V_all / frame); - fprintf(fp_tpi, "%6.2f %10d %12.5e\n", bUlogV, roundToInt(bin[i]), - bin[i] * exp(-bUlogV) * V_all / VembU_all); + fprintf(fp_tpi, "%6.2f %10d %12.5e\n", bUlogV, roundToInt(bin[i]), bin[i] * exp(-bUlogV) * V_all / VembU_all); } xvgrclose(fp_tpi); } diff --git a/src/gromacs/mdrunutility/handlerestart.cpp b/src/gromacs/mdrunutility/handlerestart.cpp index b21f113029..05b6a4f3be 100644 --- a/src/gromacs/mdrunutility/handlerestart.cpp +++ b/src/gromacs/mdrunutility/handlerestart.cpp @@ -156,7 +156,8 @@ output files exactly the same as the previous simulation part (e.g. with -deffnm make sure all the output files are present (e.g. run from the same directory as the previous simulation part), or instruct mdrun to write new output files with mdrun -noappend. In the last case, you will not be able to use appending in future for this simulation.)", - numFilesMissing, outputfiles.size()); + numFilesMissing, + outputfiles.size()); GMX_THROW(InconsistentInputError(stream.toString())); } @@ -263,7 +264,8 @@ StartingBehaviorHandler chooseStartingBehavior(const AppendingBehavior appending GMX_RELEASE_ASSERT(Path::extensionMatches(logFilename, ftp2ext(efLOG)), formatString("The checkpoint file or its reading is broken, the first " "output file '%s' must be a log file with extension '%s'", - logFilename, ftp2ext(efLOG)) + logFilename, + ftp2ext(efLOG)) .c_str()); if (appendingBehavior != AppendingBehavior::NoAppending) @@ -321,7 +323,8 @@ StartingBehaviorHandler chooseStartingBehavior(const AppendingBehavior appending "Cannot restart with appending because the previous simulation part used " "%s precision which does not match the %s precision used by this build " "of GROMACS. Either use matching precision or use mdrun -noappend.", - precisionToString(headerContents.double_prec), precisionToString(GMX_DOUBLE)))); + precisionToString(headerContents.double_prec), + precisionToString(GMX_DOUBLE)))); } } // If the previous log filename had a part number, then we @@ -369,7 +372,8 @@ void checkOutputFile(t_fileio* fileToCheck, const gmx_file_position_t& outputfil "Can't read %d bytes of '%s' to compute checksum. The file " "has been replaced or its contents have been modified. Cannot " "do appending because of this condition.", - outputfile.checksumSize, outputfile.filename); + outputfile.checksumSize, + outputfile.filename); GMX_THROW(InconsistentInputError(message)); } } @@ -511,8 +515,8 @@ void StartingBehaviorHandler::ensureMultiSimBehaviorsMatch(const gmx_multisim_t* auto startingBehaviors = gatherIntFromMultiSimulation(ms, static_cast(startingBehavior)); bool identicalStartingBehaviors = - (std::adjacent_find(std::begin(startingBehaviors), std::end(startingBehaviors), - std::not_equal_to<>()) + (std::adjacent_find( + std::begin(startingBehaviors), std::end(startingBehaviors), std::not_equal_to<>()) == std::end(startingBehaviors)); const EnumerationArray behaviorStrings = { @@ -537,8 +541,8 @@ simulations wanted the following respective behaviors: for (index simIndex = 0; simIndex != ssize(startingBehaviors); ++simIndex) { auto behavior = static_cast(startingBehaviors[simIndex]); - message += formatString(" Simulation %6zd: %s\n", simIndex, - behaviorStrings[behavior].c_str()); + message += formatString( + " Simulation %6zd: %s\n", simIndex, behaviorStrings[behavior].c_str()); } GMX_THROW(InconsistentInputError(message)); } @@ -553,9 +557,10 @@ simulations wanted the following respective behaviors: // describes the same simulation part. If those don't match, then // the simulation cannot proceed. auto simulationParts = gatherIntFromMultiSimulation(ms, headerContents->simulation_part); - bool identicalSimulationParts = (std::adjacent_find(std::begin(simulationParts), - std::end(simulationParts), std::not_equal_to<>()) - == std::end(simulationParts)); + bool identicalSimulationParts = + (std::adjacent_find( + std::begin(simulationParts), std::end(simulationParts), std::not_equal_to<>()) + == std::end(simulationParts)); if (!identicalSimulationParts) { diff --git a/src/gromacs/mdrunutility/multisim.cpp b/src/gromacs/mdrunutility/multisim.cpp index 70aba55b94..459078394a 100644 --- a/src/gromacs/mdrunutility/multisim.cpp +++ b/src/gromacs/mdrunutility/multisim.cpp @@ -84,7 +84,8 @@ std::unique_ptr buildMultiSimulation(MPI_Comm { auto message = gmx::formatString( "The number of ranks (%d) is not a multiple of the number of simulations (%td)", - numRanks, multidirs.ssize()); + numRanks, + multidirs.ssize()); GMX_THROW(gmx::InconsistentInputError(message)); } @@ -94,8 +95,11 @@ std::unique_ptr buildMultiSimulation(MPI_Comm if (debug) { - fprintf(debug, "We have %td simulations, %d ranks per simulation, local simulation is %d\n", - multidirs.ssize(), numRanksPerSimulation, rankWithinWorldComm / numRanksPerSimulation); + fprintf(debug, + "We have %td simulations, %d ranks per simulation, local simulation is %d\n", + multidirs.ssize(), + numRanksPerSimulation, + rankWithinWorldComm / numRanksPerSimulation); } int numSimulations = multidirs.size(); diff --git a/src/gromacs/mdrunutility/printtime.cpp b/src/gromacs/mdrunutility/printtime.cpp index 5a4a3caea9..5c42923711 100644 --- a/src/gromacs/mdrunutility/printtime.cpp +++ b/src/gromacs/mdrunutility/printtime.cpp @@ -126,6 +126,6 @@ void print_start(FILE* fplog, const t_commrec* cr, gmx_walltime_accounting_t wal char buf[STRLEN]; sprintf(buf, "Started %s", name); - print_date_and_time(fplog, cr->nodeid, buf, - walltime_accounting_get_start_time_stamp(walltime_accounting)); + print_date_and_time( + fplog, cr->nodeid, buf, walltime_accounting_get_start_time_stamp(walltime_accounting)); } diff --git a/src/gromacs/mdrunutility/tests/threadaffinitytest.h b/src/gromacs/mdrunutility/tests/threadaffinitytest.h index ade195c5d4..cda3de427d 100644 --- a/src/gromacs/mdrunutility/tests/threadaffinitytest.h +++ b/src/gromacs/mdrunutility/tests/threadaffinitytest.h @@ -132,8 +132,8 @@ public: } void expectPinningMessage(bool userSpecifiedStride, int stride) { - std::string pattern = formatString("Pinning threads .* %s.* stride of %d", - userSpecifiedStride ? "user" : "auto", stride); + std::string pattern = formatString( + "Pinning threads .* %s.* stride of %d", userSpecifiedStride ? "user" : "auto", stride); expectInfoMatchingRegex(pattern.c_str()); } void expectLogMessageMatchingRegexIf(MDLogger::LogLevel level, const char* re, bool condition) @@ -152,10 +152,15 @@ public: } gmx::PhysicalNodeCommunicator comm(MPI_COMM_WORLD, physicalNodeId_); int numThreadsOnThisNode, indexWithinNodeOfFirstThreadOnThisRank; - analyzeThreadsOnThisNode(comm, numThreadsOnThisRank, &numThreadsOnThisNode, - &indexWithinNodeOfFirstThreadOnThisRank); - gmx_set_thread_affinity(logHelper_.logger(), cr_, &hwOpt_, *hwTop_, numThreadsOnThisRank, - numThreadsOnThisNode, indexWithinNodeOfFirstThreadOnThisRank, + analyzeThreadsOnThisNode( + comm, numThreadsOnThisRank, &numThreadsOnThisNode, &indexWithinNodeOfFirstThreadOnThisRank); + gmx_set_thread_affinity(logHelper_.logger(), + cr_, + &hwOpt_, + *hwTop_, + numThreadsOnThisRank, + numThreadsOnThisNode, + indexWithinNodeOfFirstThreadOnThisRank, &affinityAccess_); } diff --git a/src/gromacs/mdrunutility/threadaffinity.cpp b/src/gromacs/mdrunutility/threadaffinity.cpp index 8cf377acbf..1324cf7c79 100644 --- a/src/gromacs/mdrunutility/threadaffinity.cpp +++ b/src/gromacs/mdrunutility/threadaffinity.cpp @@ -262,7 +262,8 @@ static bool get_thread_affinity_layout(const gmx::MDLogger& mdlog, { GMX_LOG(mdlog.info) .appendTextFormatted("Pinning threads with a%s logical core stride of %d", - bPickPinStride ? "n auto-selected" : " user-specified", *pin_stride); + bPickPinStride ? "n auto-selected" : " user-specified", + *pin_stride); } *issuedWarning = alreadyWarned; @@ -317,7 +318,11 @@ static bool set_affinity(const t_commrec* cr, fprintf(debug, "On rank %2d, thread %2d, index %2d, core %2d the affinity setting " "returned %d\n", - cr->nodeid, gmx_omp_get_thread_num(), index, core, ret ? 1 : 0); + cr->nodeid, + gmx_omp_get_thread_num(), + index, + core, + ret ? 1 : 0); } } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR @@ -330,7 +335,8 @@ static bool set_affinity(const t_commrec* cr, sprintf(msg, "Looks like we have set affinity for more threads than " "we have (%d > %d)!\n", - nth_affinity_set, nthread_local); + nth_affinity_set, + nthread_local); gmx_incons(msg); } @@ -356,7 +362,10 @@ static bool set_affinity(const t_commrec* cr, if (nthread_local > 1) { - sprintf(sbuf2, "for %d/%d thread%s ", nthread_local - nth_affinity_set, nthread_local, + sprintf(sbuf2, + "for %d/%d thread%s ", + nthread_local - nth_affinity_set, + nthread_local, nthread_local > 1 ? "s" : ""); } @@ -382,8 +391,8 @@ void analyzeThreadsOnThisNode(const gmx::PhysicalNodeCommunicator& physicalNodeC /* MPI_Scan is inclusive, but here we need exclusive */ *intraNodeThreadOffset -= numThreadsOnThisRank; /* Get the total number of threads on this physical node */ - MPI_Allreduce(&numThreadsOnThisRank, numThreadsOnThisNode, 1, MPI_INT, MPI_SUM, - physicalNodeComm.comm_); + MPI_Allreduce( + &numThreadsOnThisRank, numThreadsOnThisNode, 1, MPI_INT, MPI_SUM, physicalNodeComm.comm_); } #else GMX_UNUSED_VALUE(physicalNodeComm); @@ -446,17 +455,23 @@ void gmx_set_thread_affinity(const gmx::MDLogger& mdlog, bool affinityIsAutoAndNumThreadsIsNotAuto = (hw_opt->threadAffinity == ThreadAffinity::Auto && !hw_opt->totNumThreadsIsAuto); - bool issuedWarning; - bool validLayout = get_thread_affinity_layout( - mdlog, cr, hwTop, numThreadsOnThisNode, affinityIsAutoAndNumThreadsIsNotAuto, offset, - &core_pinning_stride, &localityOrder, &issuedWarning); + bool issuedWarning; + bool validLayout = get_thread_affinity_layout(mdlog, + cr, + hwTop, + numThreadsOnThisNode, + affinityIsAutoAndNumThreadsIsNotAuto, + offset, + &core_pinning_stride, + &localityOrder, + &issuedWarning); const gmx::sfree_guard localityOrderGuard(localityOrder); bool allAffinitiesSet; if (validLayout) { - allAffinitiesSet = set_affinity(cr, numThreadsOnThisRank, intraNodeThreadOffset, offset, - core_pinning_stride, localityOrder, affinityAccess); + allAffinitiesSet = set_affinity( + cr, numThreadsOnThisRank, intraNodeThreadOffset, offset, core_pinning_stride, localityOrder, affinityAccess); } else { @@ -502,8 +517,10 @@ static bool detectDefaultAffinityMask(const int nthreads_hw_avail) { if (debug) { - fprintf(debug, "%d hardware threads detected, but %d was returned by CPU_COUNT", - nthreads_hw_avail, CPU_COUNT(&mask_current)); + fprintf(debug, + "%d hardware threads detected, but %d was returned by CPU_COUNT", + nthreads_hw_avail, + CPU_COUNT(&mask_current)); } detectedDefaultAffinityMask = false; } diff --git a/src/gromacs/mdspan/extensions.h b/src/gromacs/mdspan/extensions.h index 7a62dd61c8..cff8eeea47 100644 --- a/src/gromacs/mdspan/extensions.h +++ b/src/gromacs/mdspan/extensions.h @@ -89,7 +89,10 @@ template constexpr BasicMdspan addElementwise(const BasicMdspan& span1, const BasicMdspan& span2) { BasicMdspan result(span1); - std::transform(begin(span1), end(span1), begin(span2), begin(result), + std::transform(begin(span1), + end(span1), + begin(span2), + begin(result), std::plus()); return result; } @@ -99,7 +102,10 @@ template constexpr BasicMdspan subtractElementwise(const BasicMdspan& span1, const BasicMdspan& span2) { BasicMdspan result(span1); - std::transform(begin(span1), end(span1), begin(span2), begin(result), + std::transform(begin(span1), + end(span1), + begin(span2), + begin(result), std::minus()); return result; } @@ -109,7 +115,10 @@ template constexpr BasicMdspan multiplyElementwise(const BasicMdspan& span1, const BasicMdspan& span2) { BasicMdspan result(span1); - std::transform(begin(span1), end(span1), begin(span2), begin(result), + std::transform(begin(span1), + end(span1), + begin(span2), + begin(result), std::multiplies()); return result; } @@ -119,7 +128,10 @@ template constexpr BasicMdspan divideElementwise(const BasicMdspan& span1, const BasicMdspan& span2) { BasicMdspan result(span1); - std::transform(begin(span1), end(span1), begin(span2), begin(result), + std::transform(begin(span1), + end(span1), + begin(span2), + begin(result), std::divides()); return result; } diff --git a/src/gromacs/mdspan/tests/mdspan.cpp b/src/gromacs/mdspan/tests/mdspan.cpp index c61c5598f2..cb24993566 100644 --- a/src/gromacs/mdspan/tests/mdspan.cpp +++ b/src/gromacs/mdspan/tests/mdspan.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2018,2019, by the GROMACS development team, led by + * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -240,14 +240,14 @@ struct MdSpanTest : public ::testing::Test bool contiguous, bool strided) { - check_properties_internal(my_mdspan_mapping, always_unique, always_contiguous, - always_strided, unique, contiguous, strided); - check_properties_internal(my_mdspan_map_acc, always_unique, always_contiguous, - always_strided, unique, contiguous, strided); - check_properties_internal(my_mdspan_extents, always_unique, always_contiguous, - always_strided, unique, contiguous, strided); - check_properties_internal(my_mdspan_copy, always_unique, always_contiguous, always_strided, - unique, contiguous, strided); + check_properties_internal( + my_mdspan_mapping, always_unique, always_contiguous, always_strided, unique, contiguous, strided); + check_properties_internal( + my_mdspan_map_acc, always_unique, always_contiguous, always_strided, unique, contiguous, strided); + check_properties_internal( + my_mdspan_extents, always_unique, always_contiguous, always_strided, unique, contiguous, strided); + check_properties_internal( + my_mdspan_copy, always_unique, always_contiguous, always_strided, unique, contiguous, strided); } void check_operator() diff --git a/src/gromacs/mdtypes/checkpointdata.h b/src/gromacs/mdtypes/checkpointdata.h index a01f7de822..d8ae5e02fc 100644 --- a/src/gromacs/mdtypes/checkpointdata.h +++ b/src/gromacs/mdtypes/checkpointdata.h @@ -466,8 +466,7 @@ inline void ReadCheckpointData::arrayRef(const std::string& key, ArrayRef for (; outputIt != outputEnd && inputIt != inputEnd; outputIt++, inputIt++) { auto storedRVec = inputIt->asObject()["RVec"].asArray().values(); - *outputIt = { storedRVec[XX].cast(), storedRVec[YY].cast(), - storedRVec[ZZ].cast() }; + *outputIt = { storedRVec[XX].cast(), storedRVec[YY].cast(), storedRVec[ZZ].cast() }; } } diff --git a/src/gromacs/mdtypes/forcebuffers.cpp b/src/gromacs/mdtypes/forcebuffers.cpp index ee0c0d0d91..03d3e66f29 100644 --- a/src/gromacs/mdtypes/forcebuffers.cpp +++ b/src/gromacs/mdtypes/forcebuffers.cpp @@ -88,8 +88,8 @@ void ForceBuffers::resize(int numAtoms) { forceMtsCombined_.resizeWithPadding(numAtoms); } - view_ = ForceBuffersView(force_.arrayRefWithPadding(), forceMtsCombined_.arrayRefWithPadding(), - useForceMtsCombined_); + view_ = ForceBuffersView( + force_.arrayRefWithPadding(), forceMtsCombined_.arrayRefWithPadding(), useForceMtsCombined_); } } // namespace gmx diff --git a/src/gromacs/mdtypes/inputrec.cpp b/src/gromacs/mdtypes/inputrec.cpp index b872095f52..7e9639a23f 100644 --- a/src/gromacs/mdtypes/inputrec.cpp +++ b/src/gromacs/mdtypes/inputrec.cpp @@ -439,8 +439,15 @@ static void pr_matrix(FILE* fp, int indent, const char* title, const rvec* m, gm { if (bMDPformat) { - fprintf(fp, "%-10s = %g %g %g %g %g %g\n", title, m[XX][XX], m[YY][YY], m[ZZ][ZZ], - m[XX][YY], m[XX][ZZ], m[YY][ZZ]); + fprintf(fp, + "%-10s = %g %g %g %g %g %g\n", + title, + m[XX][XX], + m[YY][YY], + m[ZZ][ZZ], + m[XX][YY], + m[XX][ZZ], + m[YY][ZZ]); } else { @@ -926,10 +933,8 @@ void pr_inputrec(FILE* fp, int indent, const char* title, const t_inputrec* ir, if (bMDPformat) { - fprintf(fp, "posres-com = %g %g %g\n", ir->posres_com[XX], ir->posres_com[YY], - ir->posres_com[ZZ]); - fprintf(fp, "posres-comB = %g %g %g\n", ir->posres_comB[XX], ir->posres_comB[YY], - ir->posres_comB[ZZ]); + fprintf(fp, "posres-com = %g %g %g\n", ir->posres_com[XX], ir->posres_com[YY], ir->posres_com[ZZ]); + fprintf(fp, "posres-comB = %g %g %g\n", ir->posres_comB[XX], ir->posres_comB[YY], ir->posres_comB[ZZ]); } else { @@ -1072,8 +1077,7 @@ static void cmp_grpopts(FILE* fp, const t_grpopts* opt1, const t_grpopts* opt2, cmp_real(fp, "inputrec->grpopts.ref_t", i, opt1->ref_t[i], opt2->ref_t[i], ftol, abstol); cmp_real(fp, "inputrec->grpopts.tau_t", i, opt1->tau_t[i], opt2->tau_t[i], ftol, abstol); cmp_int(fp, "inputrec->grpopts.annealing", i, opt1->annealing[i], opt2->annealing[i]); - cmp_int(fp, "inputrec->grpopts.anneal_npoints", i, opt1->anneal_npoints[i], - opt2->anneal_npoints[i]); + cmp_int(fp, "inputrec->grpopts.anneal_npoints", i, opt1->anneal_npoints[i], opt2->anneal_npoints[i]); if (opt1->anneal_npoints[i] == opt2->anneal_npoints[i]) { sprintf(buf1, "inputrec->grpopts.anneal_time[%d]", i); @@ -1092,8 +1096,7 @@ static void cmp_grpopts(FILE* fp, const t_grpopts* opt1, const t_grpopts* opt2, for (j = i; j < opt1->ngener; j++) { sprintf(buf1, "inputrec->grpopts.egp_flags[%d]", i); - cmp_int(fp, buf1, j, opt1->egp_flags[opt1->ngener * i + j], - opt2->egp_flags[opt1->ngener * i + j]); + cmp_int(fp, buf1, j, opt1->egp_flags[opt1->ngener * i + j], opt2->egp_flags[opt1->ngener * i + j]); } } } @@ -1124,19 +1127,25 @@ static void cmp_awhDimParams(FILE* fp, /* Note that we have double index here, but the compare functions only * support one index, so here we only print the dim index and not the bias. */ - cmp_int(fp, "inputrec.awhParams->bias?->dim->coord_index", dimIndex, dimp1->coordIndex, - dimp2->coordIndex); - cmp_double(fp, "inputrec->awhParams->bias?->dim->period", dimIndex, dimp1->period, - dimp2->period, ftol, abstol); - cmp_double(fp, "inputrec->awhParams->bias?->dim->diffusion", dimIndex, dimp1->diffusion, - dimp2->diffusion, ftol, abstol); - cmp_double(fp, "inputrec->awhParams->bias?->dim->origin", dimIndex, dimp1->origin, - dimp2->origin, ftol, abstol); + cmp_int(fp, "inputrec.awhParams->bias?->dim->coord_index", dimIndex, dimp1->coordIndex, dimp2->coordIndex); + cmp_double(fp, "inputrec->awhParams->bias?->dim->period", dimIndex, dimp1->period, dimp2->period, ftol, abstol); + cmp_double(fp, "inputrec->awhParams->bias?->dim->diffusion", dimIndex, dimp1->diffusion, dimp2->diffusion, ftol, abstol); + cmp_double(fp, "inputrec->awhParams->bias?->dim->origin", dimIndex, dimp1->origin, dimp2->origin, ftol, abstol); cmp_double(fp, "inputrec->awhParams->bias?->dim->end", dimIndex, dimp1->end, dimp2->end, ftol, abstol); - cmp_double(fp, "inputrec->awhParams->bias?->dim->coord_value_init", dimIndex, - dimp1->coordValueInit, dimp2->coordValueInit, ftol, abstol); - cmp_double(fp, "inputrec->awhParams->bias?->dim->coverDiameter", dimIndex, dimp1->coverDiameter, - dimp2->coverDiameter, ftol, abstol); + cmp_double(fp, + "inputrec->awhParams->bias?->dim->coord_value_init", + dimIndex, + dimp1->coordValueInit, + dimp2->coordValueInit, + ftol, + abstol); + cmp_double(fp, + "inputrec->awhParams->bias?->dim->coverDiameter", + dimIndex, + dimp1->coverDiameter, + dimp2->coverDiameter, + ftol, + abstol); } static void cmp_awhBiasParams(FILE* fp, @@ -1148,15 +1157,29 @@ static void cmp_awhBiasParams(FILE* fp, { cmp_int(fp, "inputrec->awhParams->ndim", biasIndex, bias1->ndim, bias2->ndim); cmp_int(fp, "inputrec->awhParams->biaseTarget", biasIndex, bias1->eTarget, bias2->eTarget); - cmp_double(fp, "inputrec->awhParams->biastargetBetaScaling", biasIndex, - bias1->targetBetaScaling, bias2->targetBetaScaling, ftol, abstol); - cmp_double(fp, "inputrec->awhParams->biastargetCutoff", biasIndex, bias1->targetCutoff, - bias2->targetCutoff, ftol, abstol); + cmp_double(fp, + "inputrec->awhParams->biastargetBetaScaling", + biasIndex, + bias1->targetBetaScaling, + bias2->targetBetaScaling, + ftol, + abstol); + cmp_double(fp, + "inputrec->awhParams->biastargetCutoff", + biasIndex, + bias1->targetCutoff, + bias2->targetCutoff, + ftol, + abstol); cmp_int(fp, "inputrec->awhParams->biaseGrowth", biasIndex, bias1->eGrowth, bias2->eGrowth); - cmp_bool(fp, "inputrec->awhParams->biasbUserData", biasIndex, bias1->bUserData != 0, - bias2->bUserData != 0); - cmp_double(fp, "inputrec->awhParams->biaserror_initial", biasIndex, bias1->errorInitial, - bias2->errorInitial, ftol, abstol); + cmp_bool(fp, "inputrec->awhParams->biasbUserData", biasIndex, bias1->bUserData != 0, bias2->bUserData != 0); + cmp_double(fp, + "inputrec->awhParams->biaserror_initial", + biasIndex, + bias1->errorInitial, + bias2->errorInitial, + ftol, + abstol); cmp_int(fp, "inputrec->awhParams->biasShareGroup", biasIndex, bias1->shareGroup, bias2->shareGroup); for (int dim = 0; dim < std::min(bias1->ndim, bias2->ndim); dim++) @@ -1171,11 +1194,13 @@ static void cmp_awhParams(FILE* fp, const gmx::AwhParams* awh1, const gmx::AwhPa cmp_int64(fp, "inputrec->awhParams->seed", awh1->seed, awh2->seed); cmp_int(fp, "inputrec->awhParams->nstout", -1, awh1->nstOut, awh2->nstOut); cmp_int(fp, "inputrec->awhParams->nstsample_coord", -1, awh1->nstSampleCoord, awh2->nstSampleCoord); - cmp_int(fp, "inputrec->awhParams->nsamples_update_free_energy", -1, - awh1->numSamplesUpdateFreeEnergy, awh2->numSamplesUpdateFreeEnergy); + cmp_int(fp, + "inputrec->awhParams->nsamples_update_free_energy", + -1, + awh1->numSamplesUpdateFreeEnergy, + awh2->numSamplesUpdateFreeEnergy); cmp_int(fp, "inputrec->awhParams->ePotential", -1, awh1->ePotential, awh2->ePotential); - cmp_bool(fp, "inputrec->awhParams->shareBiasMultisim", -1, awh1->shareBiasMultisim, - awh2->shareBiasMultisim); + cmp_bool(fp, "inputrec->awhParams->shareBiasMultisim", -1, awh1->shareBiasMultisim, awh2->shareBiasMultisim); if (awh1->numBias == awh2->numBias) { @@ -1195,14 +1220,17 @@ static void cmp_simtempvals(FILE* fp, { int i; cmp_int(fp, "inputrec->simtempvals->eSimTempScale", -1, simtemp1->eSimTempScale, simtemp2->eSimTempScale); - cmp_real(fp, "inputrec->simtempvals->simtemp_high", -1, simtemp1->simtemp_high, - simtemp2->simtemp_high, ftol, abstol); - cmp_real(fp, "inputrec->simtempvals->simtemp_low", -1, simtemp1->simtemp_low, - simtemp2->simtemp_low, ftol, abstol); + cmp_real(fp, "inputrec->simtempvals->simtemp_high", -1, simtemp1->simtemp_high, simtemp2->simtemp_high, ftol, abstol); + cmp_real(fp, "inputrec->simtempvals->simtemp_low", -1, simtemp1->simtemp_low, simtemp2->simtemp_low, ftol, abstol); for (i = 0; i < n_lambda; i++) { - cmp_real(fp, "inputrec->simtempvals->temperatures", -1, simtemp1->temperatures[i], - simtemp2->temperatures[i], ftol, abstol); + cmp_real(fp, + "inputrec->simtempvals->temperatures", + -1, + simtemp1->temperatures[i], + simtemp2->temperatures[i], + ftol, + abstol); } } @@ -1220,58 +1248,76 @@ static void cmp_expandedvals(FILE* fp, for (i = 0; i < n_lambda; i++) { - cmp_real(fp, "inputrec->expandedvals->init_lambda_weights", -1, - expand1->init_lambda_weights[i], expand2->init_lambda_weights[i], ftol, abstol); + cmp_real(fp, + "inputrec->expandedvals->init_lambda_weights", + -1, + expand1->init_lambda_weights[i], + expand2->init_lambda_weights[i], + ftol, + abstol); } cmp_int(fp, "inputrec->expandedvals->lambda-stats", -1, expand1->elamstats, expand2->elamstats); cmp_int(fp, "inputrec->expandedvals->lambda-mc-move", -1, expand1->elmcmove, expand2->elmcmove); cmp_int(fp, "inputrec->expandedvals->lmc-repeats", -1, expand1->lmc_repeats, expand2->lmc_repeats); cmp_int(fp, "inputrec->expandedvals->lmc-gibbsdelta", -1, expand1->gibbsdeltalam, expand2->gibbsdeltalam); - cmp_int(fp, "inputrec->expandedvals->lmc-forced-nstart", -1, expand1->lmc_forced_nstart, - expand2->lmc_forced_nstart); + cmp_int(fp, "inputrec->expandedvals->lmc-forced-nstart", -1, expand1->lmc_forced_nstart, expand2->lmc_forced_nstart); cmp_int(fp, "inputrec->expandedvals->lambda-weights-equil", -1, expand1->elmceq, expand2->elmceq); - cmp_int(fp, "inputrec->expandedvals->,weight-equil-number-all-lambda", -1, - expand1->equil_n_at_lam, expand2->equil_n_at_lam); - cmp_int(fp, "inputrec->expandedvals->weight-equil-number-samples", -1, expand1->equil_samples, - expand2->equil_samples); - cmp_int(fp, "inputrec->expandedvals->weight-equil-number-steps", -1, expand1->equil_steps, - expand2->equil_steps); - cmp_real(fp, "inputrec->expandedvals->weight-equil-wl-delta", -1, expand1->equil_wl_delta, - expand2->equil_wl_delta, ftol, abstol); - cmp_real(fp, "inputrec->expandedvals->weight-equil-count-ratio", -1, expand1->equil_ratio, - expand2->equil_ratio, ftol, abstol); - cmp_bool(fp, "inputrec->expandedvals->symmetrized-transition-matrix", -1, - expand1->bSymmetrizedTMatrix, expand2->bSymmetrizedTMatrix); + cmp_int(fp, + "inputrec->expandedvals->,weight-equil-number-all-lambda", + -1, + expand1->equil_n_at_lam, + expand2->equil_n_at_lam); + cmp_int(fp, "inputrec->expandedvals->weight-equil-number-samples", -1, expand1->equil_samples, expand2->equil_samples); + cmp_int(fp, "inputrec->expandedvals->weight-equil-number-steps", -1, expand1->equil_steps, expand2->equil_steps); + cmp_real(fp, + "inputrec->expandedvals->weight-equil-wl-delta", + -1, + expand1->equil_wl_delta, + expand2->equil_wl_delta, + ftol, + abstol); + cmp_real(fp, + "inputrec->expandedvals->weight-equil-count-ratio", + -1, + expand1->equil_ratio, + expand2->equil_ratio, + ftol, + abstol); + cmp_bool(fp, + "inputrec->expandedvals->symmetrized-transition-matrix", + -1, + expand1->bSymmetrizedTMatrix, + expand2->bSymmetrizedTMatrix); cmp_int(fp, "inputrec->expandedvals->nstTij", -1, expand1->nstTij, expand2->nstTij); - cmp_int(fp, "inputrec->expandedvals->mininum-var-min", -1, expand1->minvarmin, - expand2->minvarmin); /*default is reasonable */ + cmp_int(fp, "inputrec->expandedvals->mininum-var-min", -1, expand1->minvarmin, expand2->minvarmin); /*default is reasonable */ cmp_int(fp, "inputrec->expandedvals->weight-c-range", -1, expand1->c_range, expand2->c_range); /* default is just C=0 */ cmp_real(fp, "inputrec->expandedvals->wl-scale", -1, expand1->wl_scale, expand2->wl_scale, ftol, abstol); - cmp_real(fp, "inputrec->expandedvals->init-wl-delta", -1, expand1->init_wl_delta, - expand2->init_wl_delta, ftol, abstol); + cmp_real(fp, "inputrec->expandedvals->init-wl-delta", -1, expand1->init_wl_delta, expand2->init_wl_delta, ftol, abstol); cmp_real(fp, "inputrec->expandedvals->wl-ratio", -1, expand1->wl_ratio, expand2->wl_ratio, ftol, abstol); cmp_int(fp, "inputrec->expandedvals->nstexpanded", -1, expand1->nstexpanded, expand2->nstexpanded); cmp_int(fp, "inputrec->expandedvals->lmc-seed", -1, expand1->lmc_seed, expand2->lmc_seed); - cmp_real(fp, "inputrec->expandedvals->mc-temperature", -1, expand1->mc_temp, expand2->mc_temp, - ftol, abstol); + cmp_real(fp, "inputrec->expandedvals->mc-temperature", -1, expand1->mc_temp, expand2->mc_temp, ftol, abstol); } static void cmp_fepvals(FILE* fp, const t_lambda* fep1, const t_lambda* fep2, real ftol, real abstol) { int i, j; cmp_int(fp, "inputrec->nstdhdl", -1, fep1->nstdhdl, fep2->nstdhdl); - cmp_double(fp, "inputrec->fepvals->init_fep_state", -1, fep1->init_fep_state, - fep2->init_fep_state, ftol, abstol); - cmp_double(fp, "inputrec->fepvals->delta_lambda", -1, fep1->delta_lambda, fep2->delta_lambda, - ftol, abstol); + cmp_double(fp, "inputrec->fepvals->init_fep_state", -1, fep1->init_fep_state, fep2->init_fep_state, ftol, abstol); + cmp_double(fp, "inputrec->fepvals->delta_lambda", -1, fep1->delta_lambda, fep2->delta_lambda, ftol, abstol); cmp_int(fp, "inputrec->fepvals->n_lambda", -1, fep1->n_lambda, fep2->n_lambda); for (i = 0; i < efptNR; i++) { for (j = 0; j < std::min(fep1->n_lambda, fep2->n_lambda); j++) { - cmp_double(fp, "inputrec->fepvals->all_lambda", -1, fep1->all_lambda[i][j], - fep2->all_lambda[i][j], ftol, abstol); + cmp_double(fp, + "inputrec->fepvals->all_lambda", + -1, + fep1->all_lambda[i][j], + fep2->all_lambda[i][j], + ftol, + abstol); } } cmp_int(fp, "inputrec->fepvals->lambda_neighbors", 1, fep1->lambda_neighbors, fep2->lambda_neighbors); @@ -1284,8 +1330,7 @@ static void cmp_fepvals(FILE* fp, const t_lambda* fep1, const t_lambda* fep2, re cmp_int(fp, "inputrec->separate_dhdl_file", -1, fep1->separate_dhdl_file, fep2->separate_dhdl_file); cmp_int(fp, "inputrec->dhdl_derivatives", -1, fep1->dhdl_derivatives, fep2->dhdl_derivatives); cmp_int(fp, "inputrec->dh_hist_size", -1, fep1->dh_hist_size, fep2->dh_hist_size); - cmp_double(fp, "inputrec->dh_hist_spacing", -1, fep1->dh_hist_spacing, fep2->dh_hist_spacing, - ftol, abstol); + cmp_double(fp, "inputrec->dh_hist_spacing", -1, fep1->dh_hist_spacing, fep2->dh_hist_spacing, ftol, abstol); } void cmp_inputrec(FILE* fp, const t_inputrec* ir1, const t_inputrec* ir2, real ftol, real abstol) @@ -1307,9 +1352,15 @@ void cmp_inputrec(FILE* fp, const t_inputrec* ir1, const t_inputrec* ir2, real f if (ir1->useMts && ir2->useMts) { cmp_int(fp, "inputrec->mts-levels", -1, ir1->mtsLevels.size(), ir2->mtsLevels.size()); - cmp_int(fp, "inputrec->mts-level2-forces", -1, ir1->mtsLevels[1].forceGroups.to_ulong(), + cmp_int(fp, + "inputrec->mts-level2-forces", + -1, + ir1->mtsLevels[1].forceGroups.to_ulong(), ir2->mtsLevels[1].forceGroups.to_ulong()); - cmp_int(fp, "inputrec->mts-level2-factor", -1, ir1->mtsLevels[1].stepFactor, + cmp_int(fp, + "inputrec->mts-level2-factor", + -1, + ir1->mtsLevels[1].stepFactor, ir2->mtsLevels[1].stepFactor); } cmp_int(fp, "inputrec->pbcType", -1, static_cast(ir1->pbcType), static_cast(ir2->pbcType)); @@ -1327,8 +1378,13 @@ void cmp_inputrec(FILE* fp, const t_inputrec* ir1, const t_inputrec* ir2, real f cmp_int(fp, "inputrec->nstxout_compressed", -1, ir1->nstxout_compressed, ir2->nstxout_compressed); cmp_double(fp, "inputrec->init_t", -1, ir1->init_t, ir2->init_t, ftol, abstol); cmp_double(fp, "inputrec->delta_t", -1, ir1->delta_t, ir2->delta_t, ftol, abstol); - cmp_real(fp, "inputrec->x_compression_precision", -1, ir1->x_compression_precision, - ir2->x_compression_precision, ftol, abstol); + cmp_real(fp, + "inputrec->x_compression_precision", + -1, + ir1->x_compression_precision, + ir2->x_compression_precision, + ftol, + abstol); cmp_real(fp, "inputrec->fourierspacing", -1, ir1->fourier_spacing, ir2->fourier_spacing, ftol, abstol); cmp_int(fp, "inputrec->nkx", -1, ir1->nkx, ir2->nkx); cmp_int(fp, "inputrec->nky", -1, ir1->nky, ir2->nky); @@ -1337,12 +1393,17 @@ void cmp_inputrec(FILE* fp, const t_inputrec* ir1, const t_inputrec* ir2, real f cmp_real(fp, "inputrec->ewald_rtol", -1, ir1->ewald_rtol, ir2->ewald_rtol, ftol, abstol); cmp_int(fp, "inputrec->ewald_geometry", -1, ir1->ewald_geometry, ir2->ewald_geometry); cmp_real(fp, "inputrec->epsilon_surface", -1, ir1->epsilon_surface, ir2->epsilon_surface, ftol, abstol); - cmp_int(fp, "inputrec->bContinuation", -1, static_cast(ir1->bContinuation), + cmp_int(fp, + "inputrec->bContinuation", + -1, + static_cast(ir1->bContinuation), static_cast(ir2->bContinuation)); - cmp_int(fp, "inputrec->bShakeSOR", -1, static_cast(ir1->bShakeSOR), - static_cast(ir2->bShakeSOR)); + cmp_int(fp, "inputrec->bShakeSOR", -1, static_cast(ir1->bShakeSOR), static_cast(ir2->bShakeSOR)); cmp_int(fp, "inputrec->etc", -1, ir1->etc, ir2->etc); - cmp_int(fp, "inputrec->bPrintNHChains", -1, static_cast(ir1->bPrintNHChains), + cmp_int(fp, + "inputrec->bPrintNHChains", + -1, + static_cast(ir1->bPrintNHChains), static_cast(ir2->bPrintNHChains)); cmp_int(fp, "inputrec->epc", -1, ir1->epc, ir2->epc); cmp_int(fp, "inputrec->epct", -1, ir1->epct, ir2->epct); @@ -1378,15 +1439,22 @@ void cmp_inputrec(FILE* fp, const t_inputrec* ir1, const t_inputrec* ir2, real f cmp_int(fp, "inputrec->bSimTemp", -1, static_cast(ir1->bSimTemp), static_cast(ir2->bSimTemp)); if ((ir1->bSimTemp == ir2->bSimTemp) && (ir1->bSimTemp)) { - cmp_simtempvals(fp, ir1->simtempvals, ir2->simtempvals, - std::min(ir1->fepvals->n_lambda, ir2->fepvals->n_lambda), ftol, abstol); + cmp_simtempvals(fp, + ir1->simtempvals, + ir2->simtempvals, + std::min(ir1->fepvals->n_lambda, ir2->fepvals->n_lambda), + ftol, + abstol); } - cmp_int(fp, "inputrec->bExpanded", -1, static_cast(ir1->bExpanded), - static_cast(ir2->bExpanded)); + cmp_int(fp, "inputrec->bExpanded", -1, static_cast(ir1->bExpanded), static_cast(ir2->bExpanded)); if ((ir1->bExpanded == ir2->bExpanded) && (ir1->bExpanded)) { - cmp_expandedvals(fp, ir1->expandedvals, ir2->expandedvals, - std::min(ir1->fepvals->n_lambda, ir2->fepvals->n_lambda), ftol, abstol); + cmp_expandedvals(fp, + ir1->expandedvals, + ir2->expandedvals, + std::min(ir1->fepvals->n_lambda, ir2->fepvals->n_lambda), + ftol, + abstol); } cmp_int(fp, "inputrec->nwall", -1, ir1->nwall, ir2->nwall); cmp_int(fp, "inputrec->wall_type", -1, ir1->wall_type, ir2->wall_type); @@ -1411,8 +1479,7 @@ void cmp_inputrec(FILE* fp, const t_inputrec* ir1, const t_inputrec* ir2, real f cmp_int(fp, "inputrec->eDisre", -1, ir1->eDisre, ir2->eDisre); cmp_real(fp, "inputrec->dr_fc", -1, ir1->dr_fc, ir2->dr_fc, ftol, abstol); cmp_int(fp, "inputrec->eDisreWeighting", -1, ir1->eDisreWeighting, ir2->eDisreWeighting); - cmp_int(fp, "inputrec->bDisreMixed", -1, static_cast(ir1->bDisreMixed), - static_cast(ir2->bDisreMixed)); + cmp_int(fp, "inputrec->bDisreMixed", -1, static_cast(ir1->bDisreMixed), static_cast(ir2->bDisreMixed)); cmp_int(fp, "inputrec->nstdisreout", -1, ir1->nstdisreout, ir2->nstdisreout); cmp_real(fp, "inputrec->dr_tau", -1, ir1->dr_tau, ir2->dr_tau, ftol, abstol); cmp_real(fp, "inputrec->orires_fc", -1, ir1->orires_fc, ir2->orires_fc, ftol, abstol); diff --git a/src/gromacs/mdtypes/md_enums.cpp b/src/gromacs/mdtypes/md_enums.cpp index 0fdb10091b..bd498df332 100644 --- a/src/gromacs/mdtypes/md_enums.cpp +++ b/src/gromacs/mdtypes/md_enums.cpp @@ -103,8 +103,11 @@ const char* epcoupl_names[epcNR + 1] = { "No", "Berendsen", "Parrinello-R "Isotropic", "MTTK", "C-rescale", nullptr }; /* isotropic is alias for berendsen */ -const char* epcoupltype_names[epctNR + 1] = { "Isotropic", "Semiisotropic", "Anisotropic", - "Surface-Tension", nullptr }; +const char* epcoupltype_names[epctNR + 1] = { "Isotropic", + "Semiisotropic", + "Anisotropic", + "Surface-Tension", + nullptr }; const char* edisre_names[edrNR + 1] = { "No", "Simple", "Ensemble", nullptr }; @@ -182,7 +185,8 @@ const char* gmx_nblist_geometry_names[GMX_NBLIST_GEOMETRY_NR + 1] = { }; const char* gmx_nblist_interaction_names[GMX_NBLIST_INTERACTION_NR + 1] = { "Standard", - "Free_Energy", nullptr }; + "Free_Energy", + nullptr }; const char* gmx_nbkernel_elec_names[GMX_NBKERNEL_ELEC_NR + 1] = { "None", "Coulomb", "Reaction-Field", "Cubic-Spline-Table", "Ewald", nullptr diff --git a/src/gromacs/mdtypes/multipletimestepping.cpp b/src/gromacs/mdtypes/multipletimestepping.cpp index ef25f9cd0e..177dba0e6f 100644 --- a/src/gromacs/mdtypes/multipletimestepping.cpp +++ b/src/gromacs/mdtypes/multipletimestepping.cpp @@ -133,8 +133,8 @@ std::optional checkMtsInterval(ArrayRef mtsLevels, } else { - return gmx::formatString("With MTS, %s = %d should be a multiple of mts-factor = %d", param, - nstValue, mtsFactor); + return gmx::formatString( + "With MTS, %s = %d should be a multiple of mts-factor = %d", param, nstValue, mtsFactor); } } @@ -157,7 +157,8 @@ std::vector checkMtsRequirements(const t_inputrec& ir) { errorMessages.push_back(gmx::formatString( "Multiple time stepping is only supported with integrators %s and %s", - ei_names[eiMD], ei_names[eiSD1])); + ei_names[eiMD], + ei_names[eiSD1])); } if ((EEL_FULL(ir.coulombtype) || EVDW_PME(ir.vdwtype)) diff --git a/src/gromacs/mdtypes/state.cpp b/src/gromacs/mdtypes/state.cpp index 0f36009513..73cfe78998 100644 --- a/src/gromacs/mdtypes/state.cpp +++ b/src/gromacs/mdtypes/state.cpp @@ -230,8 +230,7 @@ void comp_state(const t_state* st1, const t_state* st2, gmx_bool bRMSD, real fto nc = i * st1->nhchainlength; for (j = 0; j < nc; j++) { - cmp_real(stdout, "nosehoover_xi", i, st1->nosehoover_xi[nc + j], - st2->nosehoover_xi[nc + j], ftol, abstol); + cmp_real(stdout, "nosehoover_xi", i, st1->nosehoover_xi[nc + j], st2->nosehoover_xi[nc + j], ftol, abstol); } } } @@ -243,8 +242,7 @@ void comp_state(const t_state* st1, const t_state* st2, gmx_bool bRMSD, real fto nc = i * st1->nhchainlength; for (j = 0; j < nc; j++) { - cmp_real(stdout, "nosehoover_xi", i, st1->nhpres_xi[nc + j], st2->nhpres_xi[nc + j], - ftol, abstol); + cmp_real(stdout, "nosehoover_xi", i, st1->nhpres_xi[nc + j], st2->nhpres_xi[nc + j], ftol, abstol); } } } @@ -255,14 +253,12 @@ void comp_state(const t_state* st1, const t_state* st2, gmx_bool bRMSD, real fto if ((st1->flags & (1 << estX)) && (st2->flags & (1 << estX))) { fprintf(stdout, "comparing x\n"); - cmp_rvecs(stdout, "x", st1->natoms, st1->x.rvec_array(), st2->x.rvec_array(), bRMSD, - ftol, abstol); + cmp_rvecs(stdout, "x", st1->natoms, st1->x.rvec_array(), st2->x.rvec_array(), bRMSD, ftol, abstol); } if ((st1->flags & (1 << estV)) && (st2->flags & (1 << estV))) { fprintf(stdout, "comparing v\n"); - cmp_rvecs(stdout, "v", st1->natoms, st1->v.rvec_array(), st2->v.rvec_array(), bRMSD, - ftol, abstol); + cmp_rvecs(stdout, "v", st1->natoms, st1->v.rvec_array(), st2->v.rvec_array(), bRMSD, ftol, abstol); } } } diff --git a/src/gromacs/mdtypes/state_propagator_data_gpu_impl_gpu.cpp b/src/gromacs/mdtypes/state_propagator_data_gpu_impl_gpu.cpp index 8737f63ba9..37d00888d5 100644 --- a/src/gromacs/mdtypes/state_propagator_data_gpu_impl_gpu.cpp +++ b/src/gromacs/mdtypes/state_propagator_data_gpu_impl_gpu.cpp @@ -234,8 +234,13 @@ void StatePropagatorDataGpu::Impl::copyToDevice(DeviceBuffer GMX_ASSERT(atomsStartAt + numAtomsToCopy <= h_data.ssize(), "The host buffer is smaller than the requested copy range."); - copyToDeviceBuffer(&d_data, reinterpret_cast(&h_data.data()[atomsStartAt]), - atomsStartAt, numAtomsToCopy, deviceStream, transferKind_, nullptr); + copyToDeviceBuffer(&d_data, + reinterpret_cast(&h_data.data()[atomsStartAt]), + atomsStartAt, + numAtomsToCopy, + deviceStream, + transferKind_, + nullptr); } } @@ -263,8 +268,13 @@ void StatePropagatorDataGpu::Impl::copyFromDevice(gmx::ArrayRef h_dat GMX_ASSERT(atomsStartAt + numAtomsToCopy <= h_data.ssize(), "The host buffer is smaller than the requested copy range."); - copyFromDeviceBuffer(reinterpret_cast(&h_data.data()[atomsStartAt]), &d_data, - atomsStartAt, numAtomsToCopy, deviceStream, transferKind_, nullptr); + copyFromDeviceBuffer(reinterpret_cast(&h_data.data()[atomsStartAt]), + &d_data, + atomsStartAt, + numAtomsToCopy, + deviceStream, + transferKind_, + nullptr); } } diff --git a/src/gromacs/modularsimulator/checkpointhelper.cpp b/src/gromacs/modularsimulator/checkpointhelper.cpp index 64487905f4..cebedc7847 100644 --- a/src/gromacs/modularsimulator/checkpointhelper.cpp +++ b/src/gromacs/modularsimulator/checkpointhelper.cpp @@ -124,8 +124,8 @@ void CheckpointHelper::writeCheckpoint(Step step, Time time) if (MASTER(cr_)) { - mdoutf_write_checkpoint(trajectoryElement_->outf_, fplog_, cr_, step, time, state_global_, - observablesHistory_, &checkpointDataHolder); + mdoutf_write_checkpoint( + trajectoryElement_->outf_, fplog_, cr_, step, time, state_global_, observablesHistory_, &checkpointDataHolder); } } @@ -170,7 +170,8 @@ void CheckpointHelperBuilder::registerClient(ICheckpointHelperClient* client) formatString( "CheckpointHelper client with key %s registered for checkpointing, " "but %s does not exist in the input checkpoint file.", - key.c_str(), key.c_str()) + key.c_str(), + key.c_str()) .c_str()); } client->restoreCheckpointState( diff --git a/src/gromacs/modularsimulator/checkpointhelper.h b/src/gromacs/modularsimulator/checkpointhelper.h index dcebdc5ba9..f73e4b5cb1 100644 --- a/src/gromacs/modularsimulator/checkpointhelper.h +++ b/src/gromacs/modularsimulator/checkpointhelper.h @@ -227,8 +227,8 @@ std::unique_ptr CheckpointHelperBuilder::build(Args&&... args) std::vector>&& clients = { clientsMap_.begin(), clientsMap_.end() }; - return std::make_unique(std::move(clients), std::move(checkpointHandler_), - std::forward(args)...); + return std::make_unique( + std::move(clients), std::move(checkpointHandler_), std::forward(args)...); } } // namespace gmx diff --git a/src/gromacs/modularsimulator/computeglobalselement.cpp b/src/gromacs/modularsimulator/computeglobalselement.cpp index 28062291c6..0507afad2e 100644 --- a/src/gromacs/modularsimulator/computeglobalselement.cpp +++ b/src/gromacs/modularsimulator/computeglobalselement.cpp @@ -137,8 +137,8 @@ void ComputeGlobalsElement::elementSetup() // to avoid (incorrect) correction of the initial coordinates. auto x = vcm_.mode == ecmLINEAR_ACCELERATION_CORRECTION ? ArrayRefWithPadding() : statePropagatorData_->positionsView(); - process_and_stopcm_grp(fplog_, &vcm_, *mdAtoms_->mdatoms(), x.unpaddedArrayRef(), - v.unpaddedArrayRef()); + process_and_stopcm_grp( + fplog_, &vcm_, *mdAtoms_->mdatoms(), x.unpaddedArrayRef(), v.unpaddedArrayRef()); inc_nrnb(nrnb_, eNR_STOPCM, mdAtoms_->mdatoms()->homenr); } @@ -202,8 +202,8 @@ void ComputeGlobalsElement::scheduleTask(Step step, const bool doInterSimSignal = false; // Make signaller to signal stop / reset / checkpointing signals - auto signaller = std::make_shared(signals_, cr_, nullptr, - doInterSimSignal, doIntraSimSignal); + auto signaller = std::make_shared( + signals_, cr_, nullptr, doInterSimSignal, doIntraSimSignal); registerRunFunction([this, step, flags, signaller = std::move(signaller)]() { compute(step, flags, signaller.get(), true); @@ -282,14 +282,31 @@ void ComputeGlobalsElement::compute(gmx::Step step, : statePropagatorData_->constBox(); compute_globals( - gstat_, cr_, inputrec_, fr_, energyData_->ekindata(), x, v, box, mdAtoms_->mdatoms(), - nrnb_, &vcm_, step != -1 ? wcycle_ : nullptr, energyData_->enerdata(), - energyData_->forceVirial(step), energyData_->constraintVirial(step), - energyData_->totalVirial(step), energyData_->pressure(step), constr_, signaller, - lastbox, &totalNumberOfBondedInteractions_, energyData_->needToSumEkinhOld(), + gstat_, + cr_, + inputrec_, + fr_, + energyData_->ekindata(), + x, + v, + box, + mdAtoms_->mdatoms(), + nrnb_, + &vcm_, + step != -1 ? wcycle_ : nullptr, + energyData_->enerdata(), + energyData_->forceVirial(step), + energyData_->constraintVirial(step), + energyData_->totalVirial(step), + energyData_->pressure(step), + constr_, + signaller, + lastbox, + &totalNumberOfBondedInteractions_, + energyData_->needToSumEkinhOld(), flags | (shouldCheckNumberOfBondedInteractions_ ? CGLO_CHECK_NUMBER_OF_BONDED_INTERACTIONS : 0)); - checkNumberOfBondedInteractions(mdlog_, cr_, totalNumberOfBondedInteractions_, top_global_, - localTopology_, x, box, &shouldCheckNumberOfBondedInteractions_); + checkNumberOfBondedInteractions( + mdlog_, cr_, totalNumberOfBondedInteractions_, top_global_, localTopology_, x, box, &shouldCheckNumberOfBondedInteractions_); if (flags & CGLO_STOPCM && !isInit) { process_and_stopcm_grp(fplog_, &vcm_, *mdAtoms_->mdatoms(), x, v); @@ -357,13 +374,21 @@ ISimulatorElement* ComputeGlobalsElement::get { auto* element = builderHelper->storeElement( std::make_unique>( - statePropagatorData, energyData, freeEnergyPerturbationData, + statePropagatorData, + energyData, + freeEnergyPerturbationData, globalCommunicationHelper->simulationSignals(), - globalCommunicationHelper->nstglobalcomm(), legacySimulatorData->fplog, - legacySimulatorData->mdlog, legacySimulatorData->cr, - legacySimulatorData->inputrec, legacySimulatorData->mdAtoms, - legacySimulatorData->nrnb, legacySimulatorData->wcycle, legacySimulatorData->fr, - legacySimulatorData->top_global, legacySimulatorData->constr)); + globalCommunicationHelper->nstglobalcomm(), + legacySimulatorData->fplog, + legacySimulatorData->mdlog, + legacySimulatorData->cr, + legacySimulatorData->inputrec, + legacySimulatorData->mdAtoms, + legacySimulatorData->nrnb, + legacySimulatorData->wcycle, + legacySimulatorData->fr, + legacySimulatorData->top_global, + legacySimulatorData->constr)); // TODO: Remove this when DD can reduce bonded interactions independently (#3421) auto* castedElement = static_cast*>(element); @@ -396,11 +421,21 @@ ISimulatorElement* ComputeGlobalsElementstoreElement( std::make_unique>( - statePropagatorData, energyData, freeEnergyPerturbationData, + statePropagatorData, + energyData, + freeEnergyPerturbationData, globalCommunicationHelper->simulationSignals(), - globalCommunicationHelper->nstglobalcomm(), simulator->fplog, simulator->mdlog, - simulator->cr, simulator->inputrec, simulator->mdAtoms, simulator->nrnb, - simulator->wcycle, simulator->fr, simulator->top_global, simulator->constr)); + globalCommunicationHelper->nstglobalcomm(), + simulator->fplog, + simulator->mdlog, + simulator->cr, + simulator->inputrec, + simulator->mdAtoms, + simulator->nrnb, + simulator->wcycle, + simulator->fr, + simulator->top_global, + simulator->constr)); // TODO: Remove this when DD can reduce bonded interactions independently (#3421) auto* castedElement = diff --git a/src/gromacs/modularsimulator/constraintelement.cpp b/src/gromacs/modularsimulator/constraintelement.cpp index 8519279a8e..bba9ffa92e 100644 --- a/src/gromacs/modularsimulator/constraintelement.cpp +++ b/src/gromacs/modularsimulator/constraintelement.cpp @@ -95,16 +95,22 @@ void ConstraintsElement::elementSetup() ? freeEnergyPerturbationData_->constLambdaView()[efptBONDED] : 0; // Constrain the initial coordinates and velocities - do_constrain_first( - fplog_, constr_, inputrec_, statePropagatorData_->totalNumAtoms(), - statePropagatorData_->localNumAtoms(), statePropagatorData_->positionsView(), - statePropagatorData_->velocitiesView(), statePropagatorData_->box(), lambdaBonded); + do_constrain_first(fplog_, + constr_, + inputrec_, + statePropagatorData_->totalNumAtoms(), + statePropagatorData_->localNumAtoms(), + statePropagatorData_->positionsView(), + statePropagatorData_->velocitiesView(), + statePropagatorData_->box(), + lambdaBonded); if (isMasterRank_) { if (inputrec_->eConstrAlg == econtLINCS) { - fprintf(fplog_, "RMS relative constraint deviation after constraining: %.2e\n", + fprintf(fplog_, + "RMS relative constraint deviation after constraining: %.2e\n", constr_->rmsd()); } } @@ -155,8 +161,21 @@ void ConstraintsElement::apply(Step step, bool calculateVirial, bool w default: gmx_fatal(FARGS, "Constraint algorithm not implemented for modular simulator."); } - constr_->apply(writeLog, writeEnergy, step, 1, 1.0, x, xprime, min_proj, statePropagatorData_->box(), - lambdaBonded, &dvdlambda, v, calculateVirial, vir_con, variable); + constr_->apply(writeLog, + writeEnergy, + step, + 1, + 1.0, + x, + xprime, + min_proj, + statePropagatorData_->box(), + lambdaBonded, + &dvdlambda, + v, + calculateVirial, + vir_con, + variable); if (calculateVirial) { @@ -216,10 +235,15 @@ ISimulatorElement* ConstraintsElement::getElementPointerImpl( FreeEnergyPerturbationData* freeEnergyPerturbationData, GlobalCommunicationHelper gmx_unused* globalCommunicationHelper) { - return builderHelper->storeElement(std::make_unique>( - legacySimulatorData->constr, statePropagatorData, energyData, - freeEnergyPerturbationData, MASTER(legacySimulatorData->cr), legacySimulatorData->fplog, - legacySimulatorData->inputrec, legacySimulatorData->mdAtoms->mdatoms())); + return builderHelper->storeElement( + std::make_unique>(legacySimulatorData->constr, + statePropagatorData, + energyData, + freeEnergyPerturbationData, + MASTER(legacySimulatorData->cr), + legacySimulatorData->fplog, + legacySimulatorData->inputrec, + legacySimulatorData->mdAtoms->mdatoms())); } // Explicit template initializations diff --git a/src/gromacs/modularsimulator/domdechelper.cpp b/src/gromacs/modularsimulator/domdechelper.cpp index 9128119bfe..f635d30ce9 100644 --- a/src/gromacs/modularsimulator/domdechelper.cpp +++ b/src/gromacs/modularsimulator/domdechelper.cpp @@ -108,8 +108,12 @@ void DomDecHelper::setup() gmx_wallcycle* wcycle = nullptr; // Distribute the charge groups over the nodes from the master node - partitionSystem(verbose, isMasterState, nstglobalcomm, wcycle, - statePropagatorData_->localState(), statePropagatorData_->globalState()); + partitionSystem(verbose, + isMasterState, + nstglobalcomm, + wcycle, + statePropagatorData_->localState(), + statePropagatorData_->globalState()); } void DomDecHelper::run(Step step, Time gmx_unused time) @@ -154,10 +158,26 @@ void DomDecHelper::partitionSystem(bool verbose, ForceBuffers* forcePointer = statePropagatorData_->forcePointer(); // Distribute the charge groups over the nodes from the master node - dd_partition_system(fplog_, mdlog_, inputrec_->init_step, cr_, isMasterState, nstglobalcomm, - globalState, topologyHolder_->globalTopology(), inputrec_, imdSession_, - pull_work_, localState.get(), forcePointer, mdAtoms_, - topologyHolder_->localTopology_.get(), fr_, vsite_, constr_, nrnb_, wcycle, + dd_partition_system(fplog_, + mdlog_, + inputrec_->init_step, + cr_, + isMasterState, + nstglobalcomm, + globalState, + topologyHolder_->globalTopology(), + inputrec_, + imdSession_, + pull_work_, + localState.get(), + forcePointer, + mdAtoms_, + topologyHolder_->localTopology_.get(), + fr_, + vsite_, + constr_, + nrnb_, + wcycle, verbose); topologyHolder_->updateLocalTopology(); checkBondedInteractionsCallback_(); diff --git a/src/gromacs/modularsimulator/energydata.cpp b/src/gromacs/modularsimulator/energydata.cpp index 18174c4917..53f72f6090 100644 --- a/src/gromacs/modularsimulator/energydata.cpp +++ b/src/gromacs/modularsimulator/energydata.cpp @@ -166,9 +166,15 @@ void EnergyData::Element::trajectoryWriterSetup(gmx_mdoutf* outf) void EnergyData::setup(gmx_mdoutf* outf) { pull_t* pull_work = nullptr; - energyOutput_ = std::make_unique( - mdoutf_get_fp_ene(outf), top_global_, inputrec_, pull_work, mdoutf_get_fp_dhdl(outf), - false, startingBehavior_, simulationsShareState_, mdModulesNotifier_); + energyOutput_ = std::make_unique(mdoutf_get_fp_ene(outf), + top_global_, + inputrec_, + pull_work, + mdoutf_get_fp_dhdl(outf), + false, + startingBehavior_, + simulationsShareState_, + mdModulesNotifier_); if (!isMasterRank_) { @@ -237,8 +243,8 @@ void EnergyData::doStep(Time time, bool isEnergyCalculationStep, bool isFreeEner enerd_->term[F_ETOT] = enerd_->term[F_EPOT] + enerd_->term[F_EKIN]; if (freeEnergyPerturbationData_) { - accumulateKineticLambdaComponents(enerd_, freeEnergyPerturbationData_->constLambdaView(), - *inputrec_->fepvals); + accumulateKineticLambdaComponents( + enerd_, freeEnergyPerturbationData_->constLambdaView(), *inputrec_->fepvals); } if (integratorHasConservedEnergyQuantity(inputrec_)) { @@ -251,15 +257,27 @@ void EnergyData::doStep(Time time, bool isEnergyCalculationStep, bool isFreeEner } matrix nullMatrix = {}; energyOutput_->addDataAtEnergyStep( - isFreeEnergyCalculationStep, isEnergyCalculationStep, time, mdAtoms_->mdatoms()->tmass, enerd_, - inputrec_->fepvals, inputrec_->expandedvals, statePropagatorData_->constPreviousBox(), + isFreeEnergyCalculationStep, + isEnergyCalculationStep, + time, + mdAtoms_->mdatoms()->tmass, + enerd_, + inputrec_->fepvals, + inputrec_->expandedvals, + statePropagatorData_->constPreviousBox(), PTCouplingArrays({ parrinelloRahmanBarostat_ ? parrinelloRahmanBarostat_->boxVelocities() : nullMatrix, {}, {}, {}, {} }), freeEnergyPerturbationData_ ? freeEnergyPerturbationData_->currentFEPState() : 0, - shakeVirial_, forceVirial_, totalVirial_, pressure_, ekind_, muTot_, constr_); + shakeVirial_, + forceVirial_, + totalVirial_, + pressure_, + ekind_, + muTot_, + constr_); } void EnergyData::write(gmx_mdoutf* outf, Step step, Time time, bool writeTrajectory, bool writeLog) @@ -274,8 +292,8 @@ void EnergyData::write(gmx_mdoutf* outf, Step step, Time time, bool writeTraject // energyOutput_->printAnnealingTemperatures(writeLog ? fplog_ : nullptr, groups_, &(inputrec_->opts)); Awh* awh = nullptr; - energyOutput_->printStepToEnergyFile(mdoutf_get_fp_ene(outf), writeTrajectory, do_dr, do_or, - writeLog ? fplog_ : nullptr, step, time, fcd_, awh); + energyOutput_->printStepToEnergyFile( + mdoutf_get_fp_ene(outf), writeTrajectory, do_dr, do_or, writeLog ? fplog_ : nullptr, step, time, fcd_, awh); } void EnergyData::addToForceVirial(const tensor virial, Step step) @@ -341,8 +359,7 @@ rvec* EnergyData::pressure(Step gmx_unused step) pressureStep_ = step; clear_mat(pressure_); } - GMX_ASSERT(step >= pressureStep_ || pressureStep_ == -1, - "Asked for pressure of previous step."); + GMX_ASSERT(step >= pressureStep_ || pressureStep_ == -1, "Asked for pressure of previous step."); return pressure_; } @@ -427,7 +444,8 @@ void EnergyData::Element::restoreCheckpointState(std::optionalhasReadEkinFromCheckpoint_ = MASTER(cr) ? energyData_->ekinstate_.bUpToDate : false; if (PAR(cr)) { - gmx_bcast(sizeof(hasReadEkinFromCheckpoint_), &energyData_->hasReadEkinFromCheckpoint_, + gmx_bcast(sizeof(hasReadEkinFromCheckpoint_), + &energyData_->hasReadEkinFromCheckpoint_, cr->mpi_comm_mygroup); } if (energyData_->hasReadEkinFromCheckpoint_) diff --git a/src/gromacs/modularsimulator/forceelement.cpp b/src/gromacs/modularsimulator/forceelement.cpp index 3aae7e3756..fb1978578c 100644 --- a/src/gromacs/modularsimulator/forceelement.cpp +++ b/src/gromacs/modularsimulator/forceelement.cpp @@ -194,12 +194,38 @@ void ForceElement::run(Step step, Time time, unsigned int flags) { auto v = statePropagatorData_->velocitiesView(); - relax_shell_flexcon( - fplog_, cr_, ms, isVerbose_, enforcedRotation_, step, inputrec_, imdSession_, - pull_work_, step == nextNSStep_, static_cast(flags), localTopology_, constr_, - energyData_->enerdata(), statePropagatorData_->localNumAtoms(), x, v, box, lambda, - hist, &forces, force_vir, mdAtoms_->mdatoms(), nrnb_, wcycle_, shellfc_, fr_, - runScheduleWork_, time, energyData_->muTot(), vsite_, ddBalanceRegionHandler_); + relax_shell_flexcon(fplog_, + cr_, + ms, + isVerbose_, + enforcedRotation_, + step, + inputrec_, + imdSession_, + pull_work_, + step == nextNSStep_, + static_cast(flags), + localTopology_, + constr_, + energyData_->enerdata(), + statePropagatorData_->localNumAtoms(), + x, + v, + box, + lambda, + hist, + &forces, + force_vir, + mdAtoms_->mdatoms(), + nrnb_, + wcycle_, + shellfc_, + fr_, + runScheduleWork_, + time, + energyData_->muTot(), + vsite_, + ddBalanceRegionHandler_); nShellRelaxationSteps_++; } else @@ -208,10 +234,34 @@ void ForceElement::run(Step step, Time time, unsigned int flags) Awh* awh = nullptr; gmx_edsam* ed = nullptr; - do_force(fplog_, cr_, ms, inputrec_, awh, enforcedRotation_, imdSession_, pull_work_, step, - nrnb_, wcycle_, localTopology_, box, x, hist, &forces, force_vir, - mdAtoms_->mdatoms(), energyData_->enerdata(), lambda, fr_, runScheduleWork_, vsite_, - energyData_->muTot(), time, ed, static_cast(flags), ddBalanceRegionHandler_); + do_force(fplog_, + cr_, + ms, + inputrec_, + awh, + enforcedRotation_, + imdSession_, + pull_work_, + step, + nrnb_, + wcycle_, + localTopology_, + box, + x, + hist, + &forces, + force_vir, + mdAtoms_->mdatoms(), + energyData_->enerdata(), + lambda, + fr_, + runScheduleWork_, + vsite_, + energyData_->muTot(), + time, + ed, + static_cast(flags), + ddBalanceRegionHandler_); } energyData_->addToForceVirial(force_vir, step); } @@ -261,12 +311,25 @@ ForceElement::getElementPointerImpl(LegacySimulatorData* lega { const bool isVerbose = legacySimulatorData->mdrunOptions.verbose; const bool isDynamicBox = inputrecDynamicBox(legacySimulatorData->inputrec); - return builderHelper->storeElement(std::make_unique( - statePropagatorData, energyData, freeEnergyPerturbationData, isVerbose, isDynamicBox, - legacySimulatorData->fplog, legacySimulatorData->cr, legacySimulatorData->inputrec, - legacySimulatorData->mdAtoms, legacySimulatorData->nrnb, legacySimulatorData->fr, - legacySimulatorData->wcycle, legacySimulatorData->runScheduleWork, legacySimulatorData->vsite, - legacySimulatorData->imdSession, legacySimulatorData->pull_work, legacySimulatorData->constr, - legacySimulatorData->top_global, legacySimulatorData->enforcedRotation)); + return builderHelper->storeElement( + std::make_unique(statePropagatorData, + energyData, + freeEnergyPerturbationData, + isVerbose, + isDynamicBox, + legacySimulatorData->fplog, + legacySimulatorData->cr, + legacySimulatorData->inputrec, + legacySimulatorData->mdAtoms, + legacySimulatorData->nrnb, + legacySimulatorData->fr, + legacySimulatorData->wcycle, + legacySimulatorData->runScheduleWork, + legacySimulatorData->vsite, + legacySimulatorData->imdSession, + legacySimulatorData->pull_work, + legacySimulatorData->constr, + legacySimulatorData->top_global, + legacySimulatorData->enforcedRotation)); } } // namespace gmx diff --git a/src/gromacs/modularsimulator/freeenergyperturbationdata.cpp b/src/gromacs/modularsimulator/freeenergyperturbationdata.cpp index 28d5e9d169..352ab3e39f 100644 --- a/src/gromacs/modularsimulator/freeenergyperturbationdata.cpp +++ b/src/gromacs/modularsimulator/freeenergyperturbationdata.cpp @@ -156,7 +156,8 @@ void FreeEnergyPerturbationData::Element::restoreCheckpointState(std::optionaldd, sizeof(int), &freeEnergyPerturbationData_->currentFEPState_); - dd_bcast(cr->dd, ssize(freeEnergyPerturbationData_->lambda_) * int(sizeof(real)), + dd_bcast(cr->dd, + ssize(freeEnergyPerturbationData_->lambda_) * int(sizeof(real)), freeEnergyPerturbationData_->lambda_.data()); } } diff --git a/src/gromacs/modularsimulator/modularsimulator.cpp b/src/gromacs/modularsimulator/modularsimulator.cpp index 2b31b9f11e..f660dfd7af 100644 --- a/src/gromacs/modularsimulator/modularsimulator.cpp +++ b/src/gromacs/modularsimulator/modularsimulator.cpp @@ -111,8 +111,8 @@ void ModularSimulator::addIntegrationElements(ModularSimulatorAlgorithmBuilder* if (legacySimulatorData_->inputrec->etc == etcVRESCALE || legacySimulatorData_->inputrec->etc == etcBERENDSEN) { - builder->add(-1, UseFullStepKE::No, - ReportPreviousStepConservedEnergy::No); + builder->add( + -1, UseFullStepKE::No, ReportPreviousStepConservedEnergy::No); } builder->add>(legacySimulatorData_->inputrec->delta_t, RegisterWithThermostat::True, @@ -133,7 +133,8 @@ void ModularSimulator::addIntegrationElements(ModularSimulatorAlgorithmBuilder* // The velocity verlet integration algorithm builder->add(); builder->add>( - 0.5 * legacySimulatorData_->inputrec->delta_t, RegisterWithThermostat::False, + 0.5 * legacySimulatorData_->inputrec->delta_t, + RegisterWithThermostat::False, RegisterWithBarostat::True); if (legacySimulatorData_->constr) { @@ -148,7 +149,8 @@ void ModularSimulator::addIntegrationElements(ModularSimulatorAlgorithmBuilder* 0, UseFullStepKE::Yes, ReportPreviousStepConservedEnergy::Yes); } builder->add>( - legacySimulatorData_->inputrec->delta_t, RegisterWithThermostat::True, + legacySimulatorData_->inputrec->delta_t, + RegisterWithThermostat::True, RegisterWithBarostat::False); if (legacySimulatorData_->constr) { @@ -361,9 +363,13 @@ ModularSimulator::ModularSimulator(std::unique_ptr leg void ModularSimulator::checkInputForDisabledFunctionality() { - isInputCompatible(true, legacySimulatorData_->inputrec, legacySimulatorData_->mdrunOptions.rerun, - *legacySimulatorData_->top_global, legacySimulatorData_->ms, - legacySimulatorData_->replExParams, legacySimulatorData_->fr->fcdata.get(), + isInputCompatible(true, + legacySimulatorData_->inputrec, + legacySimulatorData_->mdrunOptions.rerun, + *legacySimulatorData_->top_global, + legacySimulatorData_->ms, + legacySimulatorData_->replExParams, + legacySimulatorData_->fr->fcdata.get(), opt2bSet("-ei", legacySimulatorData_->nfile, legacySimulatorData_->fnm), legacySimulatorData_->membed != nullptr); if (legacySimulatorData_->observablesHistory->edsamHistory) diff --git a/src/gromacs/modularsimulator/parrinellorahmanbarostat.cpp b/src/gromacs/modularsimulator/parrinellorahmanbarostat.cpp index 7bf5c7fe99..95f0bab2d3 100644 --- a/src/gromacs/modularsimulator/parrinellorahmanbarostat.cpp +++ b/src/gromacs/modularsimulator/parrinellorahmanbarostat.cpp @@ -116,8 +116,17 @@ void ParrinelloRahmanBarostat::scheduleTask(Step step, void ParrinelloRahmanBarostat::integrateBoxVelocityEquations(Step step) { auto box = statePropagatorData_->constBox(); - parrinellorahman_pcoupl(fplog_, step, inputrec_, couplingTimeStep_, energyData_->pressure(step), - box, boxRel_, boxVelocity_, scalingTensor_.data(), mu_, false); + parrinellorahman_pcoupl(fplog_, + step, + inputrec_, + couplingTimeStep_, + energyData_->pressure(step), + box, + boxRel_, + boxVelocity_, + scalingTensor_.data(), + mu_, + false); // multiply matrix by the coupling time step to avoid having the propagator needing to know about that msmul(scalingTensor_.data(), couplingTimeStep_, scalingTensor_.data()); } @@ -175,8 +184,17 @@ void ParrinelloRahmanBarostat::elementSetup() // The call to parrinellorahman_pcoupl is using nullptr for fplog (since we don't expect any // output here) and for the pressure (since it might not be calculated yet, and we don't need it). auto box = statePropagatorData_->constBox(); - parrinellorahman_pcoupl(nullptr, initStep_, inputrec_, couplingTimeStep_, nullptr, box, - boxRel_, boxVelocity_, scalingTensor_.data(), mu_, true); + parrinellorahman_pcoupl(nullptr, + initStep_, + inputrec_, + couplingTimeStep_, + nullptr, + box, + boxRel_, + boxVelocity_, + scalingTensor_.data(), + mu_, + true); // multiply matrix by the coupling time step to avoid having the propagator needing to know about that msmul(scalingTensor_.data(), couplingTimeStep_, scalingTensor_.data()); @@ -285,10 +303,15 @@ ISimulatorElement* ParrinelloRahmanBarostat::getElementPointerImpl( int offset) { auto* element = builderHelper->storeElement(std::make_unique( - legacySimulatorData->inputrec->nstpcouple, offset, + legacySimulatorData->inputrec->nstpcouple, + offset, legacySimulatorData->inputrec->delta_t * legacySimulatorData->inputrec->nstpcouple, - legacySimulatorData->inputrec->init_step, statePropagatorData, energyData, - legacySimulatorData->fplog, legacySimulatorData->inputrec, legacySimulatorData->mdAtoms)); + legacySimulatorData->inputrec->init_step, + statePropagatorData, + energyData, + legacySimulatorData->fplog, + legacySimulatorData->inputrec, + legacySimulatorData->mdAtoms)); auto* barostat = static_cast(element); builderHelper->registerBarostat([barostat](const PropagatorBarostatConnection& connection) { barostat->connectWithPropagator(connection); diff --git a/src/gromacs/modularsimulator/pmeloadbalancehelper.cpp b/src/gromacs/modularsimulator/pmeloadbalancehelper.cpp index a75ea901a6..7c31518acc 100644 --- a/src/gromacs/modularsimulator/pmeloadbalancehelper.cpp +++ b/src/gromacs/modularsimulator/pmeloadbalancehelper.cpp @@ -91,8 +91,8 @@ void PmeLoadBalanceHelper::setup() auto box = statePropagatorData_->constBox(); GMX_RELEASE_ASSERT(box[0][0] != 0 && box[1][1] != 0 && box[2][2] != 0, "PmeLoadBalanceHelper cannot be initialized with zero box."); - pme_loadbal_init(&pme_loadbal_, cr_, mdlog_, *inputrec_, box, *fr_->ic, *fr_->nbv, fr_->pmedata, - fr_->nbv->useGpu()); + pme_loadbal_init( + &pme_loadbal_, cr_, mdlog_, *inputrec_, box, *fr_->ic, *fr_->nbv, fr_->pmedata, fr_->nbv->useGpu()); } void PmeLoadBalanceHelper::run(gmx::Step step, gmx::Time gmx_unused time) @@ -105,10 +105,20 @@ void PmeLoadBalanceHelper::run(gmx::Step step, gmx::Time gmx_unused time) // PME grid + cut-off optimization with GPUs or PME nodes // TODO pass SimulationWork object into this function, such that last argument can be set as // simulationWork.useGpuPmePpCommunication as is done in main MD loop. - pme_loadbal_do(pme_loadbal_, cr_, (isVerbose_ && MASTER(cr_)) ? stderr : nullptr, fplog_, - mdlog_, *inputrec_, fr_, statePropagatorData_->constBox(), - statePropagatorData_->constPositionsView().paddedArrayRef(), wcycle_, step, - step - inputrec_->init_step, &bPMETunePrinting_, false); + pme_loadbal_do(pme_loadbal_, + cr_, + (isVerbose_ && MASTER(cr_)) ? stderr : nullptr, + fplog_, + mdlog_, + *inputrec_, + fr_, + statePropagatorData_->constBox(), + statePropagatorData_->constPositionsView().paddedArrayRef(), + wcycle_, + step, + step - inputrec_->init_step, + &bPMETunePrinting_, + false); } void PmeLoadBalanceHelper::teardown() diff --git a/src/gromacs/modularsimulator/propagator.cpp b/src/gromacs/modularsimulator/propagator.cpp index b40abb9b1e..de13bbf1a0 100644 --- a/src/gromacs/modularsimulator/propagator.cpp +++ b/src/gromacs/modularsimulator/propagator.cpp @@ -208,20 +208,30 @@ void Propagator::run() if (isFullScalingMatrixDiagonal) { updateVelocities( - a, timestep_, + a, + timestep_, numVelocityScalingValues == NumVelocityScalingValues::Multiple ? velocityScaling_[mdAtoms_->mdatoms()->cTC[a]] : lambda, - invMassPerDim, v, f, diagPR_, matrixPR_); + invMassPerDim, + v, + f, + diagPR_, + matrixPR_); } else { updateVelocities( - a, timestep_, + a, + timestep_, numVelocityScalingValues == NumVelocityScalingValues::Multiple ? velocityScaling_[mdAtoms_->mdatoms()->cTC[a]] : lambda, - invMassPerDim, v, f, diagPR_, matrixPR_); + invMassPerDim, + v, + f, + diagPR_, + matrixPR_); } } } @@ -268,20 +278,30 @@ void Propagator::run() if (isFullScalingMatrixDiagonal) { updateVelocities( - a, timestep_, + a, + timestep_, numVelocityScalingValues == NumVelocityScalingValues::Multiple ? velocityScaling_[mdAtoms_->mdatoms()->cTC[a]] : lambda, - invMassPerDim, v, f, diagPR_, matrixPR_); + invMassPerDim, + v, + f, + diagPR_, + matrixPR_); } else { updateVelocities( - a, timestep_, + a, + timestep_, numVelocityScalingValues == NumVelocityScalingValues::Multiple ? velocityScaling_[mdAtoms_->mdatoms()->cTC[a]] : lambda, - invMassPerDim, v, f, diagPR_, matrixPR_); + invMassPerDim, + v, + f, + diagPR_, + matrixPR_); } updatePositions(a, timestep_, x, xp, v); } @@ -329,20 +349,30 @@ void Propagator::run() if (isFullScalingMatrixDiagonal) { updateVelocities( - a, 0.5 * timestep_, + a, + 0.5 * timestep_, numVelocityScalingValues == NumVelocityScalingValues::Multiple ? velocityScaling_[mdAtoms_->mdatoms()->cTC[a]] : lambda, - invMassPerDim, v, f, diagPR_, matrixPR_); + invMassPerDim, + v, + f, + diagPR_, + matrixPR_); } else { updateVelocities( - a, 0.5 * timestep_, + a, + 0.5 * timestep_, numVelocityScalingValues == NumVelocityScalingValues::Multiple ? velocityScaling_[mdAtoms_->mdatoms()->cTC[a]] : lambda, - invMassPerDim, v, f, diagPR_, matrixPR_); + invMassPerDim, + v, + f, + diagPR_, + matrixPR_); } updatePositions(a, timestep_, x, xp, v); } diff --git a/src/gromacs/modularsimulator/signallers.h b/src/gromacs/modularsimulator/signallers.h index 2c74ab9454..8c8769e4a4 100644 --- a/src/gromacs/modularsimulator/signallers.h +++ b/src/gromacs/modularsimulator/signallers.h @@ -464,9 +464,10 @@ std::unique_ptr SignallerBuilder::build(Args&& auto calculateFreeEnergyCallbacks = buildCallbackVector(EnergySignallerEvent::FreeEnergyCalculationStep); // NOLINTNEXTLINE(modernize-make-unique): make_unique does not work with private constructor - return std::unique_ptr(new EnergySignaller( - std::move(calculateEnergyCallbacks), std::move(calculateVirialCallbacks), - std::move(calculateFreeEnergyCallbacks), std::forward(args)...)); + return std::unique_ptr(new EnergySignaller(std::move(calculateEnergyCallbacks), + std::move(calculateVirialCallbacks), + std::move(calculateFreeEnergyCallbacks), + std::forward(args)...)); } //! Helper function to get the callbacks from the clients diff --git a/src/gromacs/modularsimulator/simulatoralgorithm.cpp b/src/gromacs/modularsimulator/simulatoralgorithm.cpp index 4e0b71a918..81a0c1741c 100644 --- a/src/gromacs/modularsimulator/simulatoralgorithm.cpp +++ b/src/gromacs/modularsimulator/simulatoralgorithm.cpp @@ -204,8 +204,8 @@ void ModularSimulatorAlgorithm::simulatorSetup() fprintf(stderr, "starting mdrun '%s'\n", topologyName_.c_str()); if (inputrec->nsteps >= 0) { - timeString = formatString("%8.1f", static_cast(inputrec->init_step + inputrec->nsteps) - * inputrec->delta_t); + timeString = formatString( + "%8.1f", static_cast(inputrec->init_step + inputrec->nsteps) * inputrec->delta_t); } else { @@ -213,14 +213,16 @@ void ModularSimulatorAlgorithm::simulatorSetup() } if (inputrec->init_step > 0) { - fprintf(stderr, "%s steps, %s ps (continuing from step %s, %8.1f ps).\n", - gmx_step_str(inputrec->init_step + inputrec->nsteps, sbuf), timeString.c_str(), - gmx_step_str(inputrec->init_step, sbuf2), inputrec->init_step * inputrec->delta_t); + fprintf(stderr, + "%s steps, %s ps (continuing from step %s, %8.1f ps).\n", + gmx_step_str(inputrec->init_step + inputrec->nsteps, sbuf), + timeString.c_str(), + gmx_step_str(inputrec->init_step, sbuf2), + inputrec->init_step * inputrec->delta_t); } else { - fprintf(stderr, "%s steps, %s ps.\n", gmx_step_str(inputrec->nsteps, sbuf), - timeString.c_str()); + fprintf(stderr, "%s steps, %s ps.\n", gmx_step_str(inputrec->nsteps, sbuf), timeString.c_str()); } fprintf(fplog, "\n"); } @@ -305,10 +307,17 @@ void ModularSimulatorAlgorithm::postStep(Step step, Time gmx_unused time) dd_cycles_add(cr->dd, static_cast(cycles), ddCyclStep); } - resetHandler_->resetCounters( - step, step - inputrec->init_step, mdlog, fplog, cr, fr->nbv.get(), nrnb, fr->pmedata, - pmeLoadBalanceHelper_ ? pmeLoadBalanceHelper_->loadBalancingObject() : nullptr, wcycle, - walltime_accounting); + resetHandler_->resetCounters(step, + step - inputrec->init_step, + mdlog, + fplog, + cr, + fr->nbv.get(), + nrnb, + fr->pmedata, + pmeLoadBalanceHelper_ ? pmeLoadBalanceHelper_->loadBalancingObject() : nullptr, + wcycle, + walltime_accounting); } void ModularSimulatorAlgorithm::populateTaskQueue() @@ -402,22 +411,36 @@ ModularSimulatorAlgorithmBuilder::ModularSimulatorAlgorithmBuilder( } statePropagatorData_ = std::make_unique( - legacySimulatorData->top_global->natoms, legacySimulatorData->fplog, legacySimulatorData->cr, - legacySimulatorData->state_global, legacySimulatorData->fr->nbv->useGpu(), - legacySimulatorData->fr->bMolPBC, legacySimulatorData->mdrunOptions.writeConfout, - opt2fn("-c", legacySimulatorData->nfile, legacySimulatorData->fnm), legacySimulatorData->inputrec, - legacySimulatorData->mdAtoms->mdatoms(), legacySimulatorData->top_global); + legacySimulatorData->top_global->natoms, + legacySimulatorData->fplog, + legacySimulatorData->cr, + legacySimulatorData->state_global, + legacySimulatorData->fr->nbv->useGpu(), + legacySimulatorData->fr->bMolPBC, + legacySimulatorData->mdrunOptions.writeConfout, + opt2fn("-c", legacySimulatorData->nfile, legacySimulatorData->fnm), + legacySimulatorData->inputrec, + legacySimulatorData->mdAtoms->mdatoms(), + legacySimulatorData->top_global); // Multi sim is turned off const bool simulationsShareState = false; - energyData_ = std::make_unique( - statePropagatorData_.get(), freeEnergyPerturbationData_.get(), legacySimulatorData->top_global, - legacySimulatorData->inputrec, legacySimulatorData->mdAtoms, legacySimulatorData->enerd, - legacySimulatorData->ekind, legacySimulatorData->constr, legacySimulatorData->fplog, - legacySimulatorData->fr->fcdata.get(), legacySimulatorData->mdModulesNotifier, - MASTER(legacySimulatorData->cr), legacySimulatorData->observablesHistory, - legacySimulatorData->startingBehavior, simulationsShareState); + energyData_ = std::make_unique(statePropagatorData_.get(), + freeEnergyPerturbationData_.get(), + legacySimulatorData->top_global, + legacySimulatorData->inputrec, + legacySimulatorData->mdAtoms, + legacySimulatorData->enerd, + legacySimulatorData->ekind, + legacySimulatorData->constr, + legacySimulatorData->fplog, + legacySimulatorData->fr->fcdata.get(), + legacySimulatorData->mdModulesNotifier, + MASTER(legacySimulatorData->cr), + legacySimulatorData->observablesHistory, + legacySimulatorData->startingBehavior, + simulationsShareState); } ModularSimulatorAlgorithm ModularSimulatorAlgorithmBuilder::build() @@ -445,11 +468,16 @@ ModularSimulatorAlgorithm ModularSimulatorAlgorithmBuilder::build() } } - ModularSimulatorAlgorithm algorithm( - *(legacySimulatorData_->top_global->name), legacySimulatorData_->fplog, - legacySimulatorData_->cr, legacySimulatorData_->mdlog, legacySimulatorData_->mdrunOptions, - legacySimulatorData_->inputrec, legacySimulatorData_->nrnb, legacySimulatorData_->wcycle, - legacySimulatorData_->fr, legacySimulatorData_->walltime_accounting); + ModularSimulatorAlgorithm algorithm(*(legacySimulatorData_->top_global->name), + legacySimulatorData_->fplog, + legacySimulatorData_->cr, + legacySimulatorData_->mdlog, + legacySimulatorData_->mdrunOptions, + legacySimulatorData_->inputrec, + legacySimulatorData_->nrnb, + legacySimulatorData_->wcycle, + legacySimulatorData_->fr, + legacySimulatorData_->walltime_accounting); registerWithInfrastructureAndSignallers(algorithm.signalHelper_.get()); algorithm.statePropagatorData_ = std::move(statePropagatorData_); algorithm.energyData_ = std::move(energyData_); @@ -463,11 +491,16 @@ ModularSimulatorAlgorithm ModularSimulatorAlgorithmBuilder::build() algorithm.stopHandler_ = legacySimulatorData_->stopHandlerBuilder->getStopHandlerMD( compat::not_null( &(*globalCommunicationHelper_.simulationSignals())[eglsSTOPCOND]), - simulationsShareState, MASTER(legacySimulatorData_->cr), - legacySimulatorData_->inputrec->nstlist, legacySimulatorData_->mdrunOptions.reproducible, - globalCommunicationHelper_.nstglobalcomm(), legacySimulatorData_->mdrunOptions.maximumHoursToRun, - legacySimulatorData_->inputrec->nstlist == 0, legacySimulatorData_->fplog, - algorithm.stophandlerCurrentStep_, algorithm.stophandlerIsNSStep_, + simulationsShareState, + MASTER(legacySimulatorData_->cr), + legacySimulatorData_->inputrec->nstlist, + legacySimulatorData_->mdrunOptions.reproducible, + globalCommunicationHelper_.nstglobalcomm(), + legacySimulatorData_->mdrunOptions.maximumHoursToRun, + legacySimulatorData_->inputrec->nstlist == 0, + legacySimulatorData_->fplog, + algorithm.stophandlerCurrentStep_, + algorithm.stophandlerIsNSStep_, legacySimulatorData_->walltime_accounting); // Build reset handler @@ -475,26 +508,38 @@ ModularSimulatorAlgorithm ModularSimulatorAlgorithmBuilder::build() algorithm.resetHandler_ = std::make_unique( compat::make_not_null( &(*globalCommunicationHelper_.simulationSignals())[eglsRESETCOUNTERS]), - simulationsShareResetCounters, legacySimulatorData_->inputrec->nsteps, - MASTER(legacySimulatorData_->cr), legacySimulatorData_->mdrunOptions.timingOptions.resetHalfway, - legacySimulatorData_->mdrunOptions.maximumHoursToRun, legacySimulatorData_->mdlog, - legacySimulatorData_->wcycle, legacySimulatorData_->walltime_accounting); + simulationsShareResetCounters, + legacySimulatorData_->inputrec->nsteps, + MASTER(legacySimulatorData_->cr), + legacySimulatorData_->mdrunOptions.timingOptions.resetHalfway, + legacySimulatorData_->mdrunOptions.maximumHoursToRun, + legacySimulatorData_->mdlog, + legacySimulatorData_->wcycle, + legacySimulatorData_->walltime_accounting); // Build topology holder - algorithm.topologyHolder_ = topologyHolderBuilder_.build( - *legacySimulatorData_->top_global, legacySimulatorData_->cr, - legacySimulatorData_->inputrec, legacySimulatorData_->fr, legacySimulatorData_->mdAtoms, - legacySimulatorData_->constr, legacySimulatorData_->vsite); + algorithm.topologyHolder_ = topologyHolderBuilder_.build(*legacySimulatorData_->top_global, + legacySimulatorData_->cr, + legacySimulatorData_->inputrec, + legacySimulatorData_->fr, + legacySimulatorData_->mdAtoms, + legacySimulatorData_->constr, + legacySimulatorData_->vsite); // Build PME load balance helper if (PmeLoadBalanceHelper::doPmeLoadBalancing(legacySimulatorData_->mdrunOptions, legacySimulatorData_->inputrec, legacySimulatorData_->fr)) { - algorithm.pmeLoadBalanceHelper_ = std::make_unique( - legacySimulatorData_->mdrunOptions.verbose, algorithm.statePropagatorData_.get(), - legacySimulatorData_->fplog, legacySimulatorData_->cr, legacySimulatorData_->mdlog, - legacySimulatorData_->inputrec, legacySimulatorData_->wcycle, legacySimulatorData_->fr); + algorithm.pmeLoadBalanceHelper_ = + std::make_unique(legacySimulatorData_->mdrunOptions.verbose, + algorithm.statePropagatorData_.get(), + legacySimulatorData_->fplog, + legacySimulatorData_->cr, + legacySimulatorData_->mdlog, + legacySimulatorData_->inputrec, + legacySimulatorData_->wcycle, + legacySimulatorData_->fr); registerWithInfrastructureAndSignallers(algorithm.pmeLoadBalanceHelper_.get()); } // Build domdec helper @@ -503,25 +548,40 @@ ModularSimulatorAlgorithm ModularSimulatorAlgorithmBuilder::build() algorithm.domDecHelper_ = std::make_unique( legacySimulatorData_->mdrunOptions.verbose, legacySimulatorData_->mdrunOptions.verboseStepPrintInterval, - algorithm.statePropagatorData_.get(), algorithm.freeEnergyPerturbationData_.get(), + algorithm.statePropagatorData_.get(), + algorithm.freeEnergyPerturbationData_.get(), algorithm.topologyHolder_.get(), globalCommunicationHelper_.moveCheckBondedInteractionsCallback(), - globalCommunicationHelper_.nstglobalcomm(), legacySimulatorData_->fplog, - legacySimulatorData_->cr, legacySimulatorData_->mdlog, legacySimulatorData_->constr, - legacySimulatorData_->inputrec, legacySimulatorData_->mdAtoms, legacySimulatorData_->nrnb, - legacySimulatorData_->wcycle, legacySimulatorData_->fr, legacySimulatorData_->vsite, - legacySimulatorData_->imdSession, legacySimulatorData_->pull_work); + globalCommunicationHelper_.nstglobalcomm(), + legacySimulatorData_->fplog, + legacySimulatorData_->cr, + legacySimulatorData_->mdlog, + legacySimulatorData_->constr, + legacySimulatorData_->inputrec, + legacySimulatorData_->mdAtoms, + legacySimulatorData_->nrnb, + legacySimulatorData_->wcycle, + legacySimulatorData_->fr, + legacySimulatorData_->vsite, + legacySimulatorData_->imdSession, + legacySimulatorData_->pull_work); registerWithInfrastructureAndSignallers(algorithm.domDecHelper_.get()); } // Build trajectory element - auto trajectoryElement = trajectoryElementBuilder_.build( - legacySimulatorData_->fplog, legacySimulatorData_->nfile, legacySimulatorData_->fnm, - legacySimulatorData_->mdrunOptions, legacySimulatorData_->cr, - legacySimulatorData_->outputProvider, legacySimulatorData_->mdModulesNotifier, - legacySimulatorData_->inputrec, legacySimulatorData_->top_global, - legacySimulatorData_->oenv, legacySimulatorData_->wcycle, - legacySimulatorData_->startingBehavior, simulationsShareState); + auto trajectoryElement = trajectoryElementBuilder_.build(legacySimulatorData_->fplog, + legacySimulatorData_->nfile, + legacySimulatorData_->fnm, + legacySimulatorData_->mdrunOptions, + legacySimulatorData_->cr, + legacySimulatorData_->outputProvider, + legacySimulatorData_->mdModulesNotifier, + legacySimulatorData_->inputrec, + legacySimulatorData_->top_global, + legacySimulatorData_->oenv, + legacySimulatorData_->wcycle, + legacySimulatorData_->startingBehavior, + simulationsShareState); registerWithInfrastructureAndSignallers(trajectoryElement.get()); // Build free energy element @@ -538,14 +598,20 @@ ModularSimulatorAlgorithm ModularSimulatorAlgorithmBuilder::build() { checkpointHelperBuilder_.setCheckpointHandler(std::make_unique( compat::make_not_null(&(*algorithm.signals_)[eglsCHKPT]), - simulationsShareState, legacySimulatorData_->inputrec->nstlist == 0, - MASTER(legacySimulatorData_->cr), legacySimulatorData_->mdrunOptions.writeConfout, + simulationsShareState, + legacySimulatorData_->inputrec->nstlist == 0, + MASTER(legacySimulatorData_->cr), + legacySimulatorData_->mdrunOptions.writeConfout, legacySimulatorData_->mdrunOptions.checkpointOptions.period)); - algorithm.checkpointHelper_ = checkpointHelperBuilder_.build( - legacySimulatorData_->inputrec->init_step, trajectoryElement.get(), - legacySimulatorData_->fplog, legacySimulatorData_->cr, - legacySimulatorData_->observablesHistory, legacySimulatorData_->walltime_accounting, - legacySimulatorData_->state_global, legacySimulatorData_->mdrunOptions.writeConfout); + algorithm.checkpointHelper_ = + checkpointHelperBuilder_.build(legacySimulatorData_->inputrec->init_step, + trajectoryElement.get(), + legacySimulatorData_->fplog, + legacySimulatorData_->cr, + legacySimulatorData_->observablesHistory, + legacySimulatorData_->walltime_accounting, + legacySimulatorData_->state_global, + legacySimulatorData_->mdrunOptions.writeConfout); registerWithInfrastructureAndSignallers(algorithm.checkpointHelper_.get()); } @@ -573,16 +639,20 @@ ModularSimulatorAlgorithm ModularSimulatorAlgorithmBuilder::build() const auto* inputrec = legacySimulatorData_->inputrec; addSignaller(energySignallerBuilder_.build( inputrec->nstcalcenergy, inputrec->fepvals->nstdhdl, inputrec->nstpcouple)); - addSignaller(trajectorySignallerBuilder_.build( - inputrec->nstxout, inputrec->nstvout, inputrec->nstfout, - inputrec->nstxout_compressed, trajectoryElement->tngBoxOut(), - trajectoryElement->tngLambdaOut(), trajectoryElement->tngBoxOutCompressed(), - trajectoryElement->tngLambdaOutCompressed(), inputrec->nstenergy)); + addSignaller(trajectorySignallerBuilder_.build(inputrec->nstxout, + inputrec->nstvout, + inputrec->nstfout, + inputrec->nstxout_compressed, + trajectoryElement->tngBoxOut(), + trajectoryElement->tngLambdaOut(), + trajectoryElement->tngBoxOutCompressed(), + trajectoryElement->tngLambdaOutCompressed(), + inputrec->nstenergy)); addSignaller(loggingSignallerBuilder_.build(inputrec->nstlog, inputrec->init_step, inputrec->init_t)); - addSignaller(lastStepSignallerBuilder_.build(inputrec->nsteps, inputrec->init_step, - algorithm.stopHandler_.get())); - addSignaller(neighborSearchSignallerBuilder_.build(inputrec->nstlist, inputrec->init_step, - inputrec->init_t)); + addSignaller(lastStepSignallerBuilder_.build( + inputrec->nsteps, inputrec->init_step, algorithm.stopHandler_.get())); + addSignaller(neighborSearchSignallerBuilder_.build( + inputrec->nstlist, inputrec->init_step, inputrec->init_t)); } // Create element list @@ -620,8 +690,9 @@ ISimulatorElement* ModularSimulatorAlgorithmBuilder::addElementToSimulatorAlgori bool ModularSimulatorAlgorithmBuilder::elementExists(const ISimulatorElement* element) const { // Check whether element exists in element list - if (std::any_of(elements_.begin(), elements_.end(), - [element](auto& existingElement) { return element == existingElement.get(); })) + if (std::any_of(elements_.begin(), elements_.end(), [element](auto& existingElement) { + return element == existingElement.get(); + })) { return true; } diff --git a/src/gromacs/modularsimulator/simulatoralgorithm.h b/src/gromacs/modularsimulator/simulatoralgorithm.h index e1e94f9150..97923abbbb 100644 --- a/src/gromacs/modularsimulator/simulatoralgorithm.h +++ b/src/gromacs/modularsimulator/simulatoralgorithm.h @@ -549,9 +549,13 @@ ISimulatorElement* getElementPointer(LegacySimulatorData* leg GlobalCommunicationHelper* globalCommunicationHelper, Args&&... args) { - return Element::getElementPointerImpl(legacySimulatorData, builderHelper, statePropagatorData, - energyData, freeEnergyPerturbationData, - globalCommunicationHelper, std::forward(args)...); + return Element::getElementPointerImpl(legacySimulatorData, + builderHelper, + statePropagatorData, + energyData, + freeEnergyPerturbationData, + globalCommunicationHelper, + std::forward(args)...); } template @@ -564,10 +568,13 @@ void ModularSimulatorAlgorithmBuilder::add(Args&&... args) } // Get element from factory method - auto* element = static_cast(getElementPointer( - legacySimulatorData_, &elementAdditionHelper_, statePropagatorData_.get(), - energyData_.get(), freeEnergyPerturbationData_.get(), &globalCommunicationHelper_, - std::forward(args)...)); + auto* element = static_cast(getElementPointer(legacySimulatorData_, + &elementAdditionHelper_, + statePropagatorData_.get(), + energyData_.get(), + freeEnergyPerturbationData_.get(), + &globalCommunicationHelper_, + std::forward(args)...)); // Make sure returned element pointer is owned by *this // Ensuring this makes sure we can control the life time diff --git a/src/gromacs/modularsimulator/statepropagatordata.cpp b/src/gromacs/modularsimulator/statepropagatordata.cpp index bf5bf8e10f..28e4ef9a25 100644 --- a/src/gromacs/modularsimulator/statepropagatordata.cpp +++ b/src/gromacs/modularsimulator/statepropagatordata.cpp @@ -436,10 +436,18 @@ void StatePropagatorData::Element::write(gmx_mdoutf_t outf, Step currentStep, Ti // TODO: This is only used for CPT - needs to be filled when we turn CPT back on ObservablesHistory* observablesHistory = nullptr; - mdoutf_write_to_trajectory_files( - fplog_, cr_, outf, static_cast(mdof_flags), statePropagatorData_->totalNumAtoms_, - currentStep, currentTime, localStateBackup_.get(), statePropagatorData_->globalState_, - observablesHistory, statePropagatorData_->f_.view().force(), &dummyCheckpointDataHolder_); + mdoutf_write_to_trajectory_files(fplog_, + cr_, + outf, + static_cast(mdof_flags), + statePropagatorData_->totalNumAtoms_, + currentStep, + currentTime, + localStateBackup_.get(), + statePropagatorData_->globalState_, + observablesHistory, + statePropagatorData_->f_.view().force(), + &dummyCheckpointDataHolder_); if (currentStep != lastStep_ || !isRegularSimulationEnd_) { @@ -495,10 +503,18 @@ void StatePropagatorData::Element::doCheckpointData(CheckpointData* c } if (operation == CheckpointDataOperation::Write) { - dd_collect_vec(cr->dd, statePropagatorData_->ddpCount_, statePropagatorData_->ddpCountCgGl_, - statePropagatorData_->cgGl_, statePropagatorData_->x_, xGlobalRef); - dd_collect_vec(cr->dd, statePropagatorData_->ddpCount_, statePropagatorData_->ddpCountCgGl_, - statePropagatorData_->cgGl_, statePropagatorData_->v_, vGlobalRef); + dd_collect_vec(cr->dd, + statePropagatorData_->ddpCount_, + statePropagatorData_->ddpCountCgGl_, + statePropagatorData_->cgGl_, + statePropagatorData_->x_, + xGlobalRef); + dd_collect_vec(cr->dd, + statePropagatorData_->ddpCount_, + statePropagatorData_->ddpCountCgGl_, + statePropagatorData_->cgGl_, + statePropagatorData_->v_, + vGlobalRef); } } else @@ -557,9 +573,12 @@ void StatePropagatorData::Element::restoreCheckpointState(std::optionalglobalState_, statePropagatorData_->xGlobal_, - statePropagatorData_->vGlobal_, statePropagatorData_->box_, - statePropagatorData_->ddpCount_, statePropagatorData_->ddpCountCgGl_, + updateGlobalState(statePropagatorData_->globalState_, + statePropagatorData_->xGlobal_, + statePropagatorData_->vGlobal_, + statePropagatorData_->box_, + statePropagatorData_->ddpCount_, + statePropagatorData_->ddpCountCgGl_, statePropagatorData_->cgGl_); } } @@ -586,12 +605,20 @@ void StatePropagatorData::Element::trajectoryWriterTeardown(gmx_mdoutf* gmx_unus { auto globalXRef = MASTER(cr_) ? statePropagatorData_->globalState_->x : gmx::ArrayRef(); - dd_collect_vec(cr_->dd, localStateBackup_->ddp_count, localStateBackup_->ddp_count_cg_gl, - localStateBackup_->cg_gl, localStateBackup_->x, globalXRef); + dd_collect_vec(cr_->dd, + localStateBackup_->ddp_count, + localStateBackup_->ddp_count_cg_gl, + localStateBackup_->cg_gl, + localStateBackup_->x, + globalXRef); auto globalVRef = MASTER(cr_) ? statePropagatorData_->globalState_->v : gmx::ArrayRef(); - dd_collect_vec(cr_->dd, localStateBackup_->ddp_count, localStateBackup_->ddp_count_cg_gl, - localStateBackup_->cg_gl, localStateBackup_->v, globalVRef); + dd_collect_vec(cr_->dd, + localStateBackup_->ddp_count, + localStateBackup_->ddp_count_cg_gl, + localStateBackup_->cg_gl, + localStateBackup_->v, + globalVRef); } else { @@ -605,12 +632,17 @@ void StatePropagatorData::Element::trajectoryWriterTeardown(gmx_mdoutf* gmx_unus if (canMoleculesBeDistributedOverPBC_ && !systemHasPeriodicMolecules_) { // Make molecules whole only for confout writing - do_pbc_mtop(pbcType_, localStateBackup_->box, top_global_, + do_pbc_mtop(pbcType_, + localStateBackup_->box, + top_global_, statePropagatorData_->globalState_->x.rvec_array()); } - write_sto_conf_mtop(finalConfigurationFilename_.c_str(), *top_global_->name, top_global_, + write_sto_conf_mtop(finalConfigurationFilename_.c_str(), + *top_global_->name, + top_global_, statePropagatorData_->globalState_->x.rvec_array(), - statePropagatorData_->globalState_->v.rvec_array(), pbcType_, + statePropagatorData_->globalState_->v.rvec_array(), + pbcType_, localStateBackup_->box); } wallcycle_stop(mdoutf_get_wcycle(outf), ewcTRAJ); diff --git a/src/gromacs/modularsimulator/topologyholder.cpp b/src/gromacs/modularsimulator/topologyholder.cpp index 8fb91190b0..87e647bd54 100644 --- a/src/gromacs/modularsimulator/topologyholder.cpp +++ b/src/gromacs/modularsimulator/topologyholder.cpp @@ -70,8 +70,8 @@ TopologyHolder::TopologyHolder(std::vector clients, // Note: Legacy mdrun resizes the force buffer in mdAlgorithmsSetupAtomData() // TopologyHolder has no access to the forces, so we are passing a nullptr // TODO: Find a unique approach to resizing the forces in modular simulator (#3461) - mdAlgorithmsSetupAtomData(cr, inputrec, globalTopology, localTopology_.get(), fr, nullptr, - mdAtoms, constr, vsite, nullptr); + mdAlgorithmsSetupAtomData( + cr, inputrec, globalTopology, localTopology_.get(), fr, nullptr, mdAtoms, constr, vsite, nullptr); } // Send copy of initial topology to clients updateLocalTopology(); diff --git a/src/gromacs/modularsimulator/velocityscalingtemperaturecoupling.cpp b/src/gromacs/modularsimulator/velocityscalingtemperaturecoupling.cpp index 3a2e482b54..89e8b69e05 100644 --- a/src/gromacs/modularsimulator/velocityscalingtemperaturecoupling.cpp +++ b/src/gromacs/modularsimulator/velocityscalingtemperaturecoupling.cpp @@ -142,11 +142,13 @@ public: * temperatureCouplingData.numDegreesOfFreedom[temperatureGroup]; const real newKineticEnergy = - vrescale_resamplekin(currentKineticEnergy, referenceKineticEnergy, + vrescale_resamplekin(currentKineticEnergy, + referenceKineticEnergy, temperatureCouplingData.numDegreesOfFreedom[temperatureGroup], temperatureCouplingData.couplingTime[temperatureGroup] / temperatureCouplingData.couplingTimeStep, - step, seed_); + step, + seed_); // Analytically newKineticEnergy >= 0, but we check for rounding errors if (newKineticEnergy <= 0) @@ -160,8 +162,12 @@ public: if (debug) { - fprintf(debug, "TC: group %d: Ekr %g, Ek %g, Ek_new %g, Lambda: %g\n", temperatureGroup, - referenceKineticEnergy, currentKineticEnergy, newKineticEnergy, + fprintf(debug, + "TC: group %d: Ekr %g, Ek %g, Ek_new %g, Lambda: %g\n", + temperatureGroup, + referenceKineticEnergy, + currentKineticEnergy, + newKineticEnergy, lambdaStartVelocities_[temperatureGroup]); } @@ -230,8 +236,11 @@ public: std::max(std::min(lambda, 1.25_real), 0.8_real); if (debug) { - fprintf(debug, "TC: group %d: T: %g, Lambda: %g\n", temperatureGroup, - currentTemperature, lambdaStartVelocities_[temperatureGroup]); + fprintf(debug, + "TC: group %d: T: %g, Lambda: %g\n", + temperatureGroup, + currentTemperature, + lambdaStartVelocities_[temperatureGroup]); } return temperatureCouplingData.temperatureCouplingIntegral[temperatureGroup] - (lambdaStartVelocities_[temperatureGroup] * lambdaStartVelocities_[temperatureGroup] @@ -356,8 +365,9 @@ void VelocityScalingTemperatureCoupling::setLambda(Step step) } const auto* ekind = energyData_->ekindata(); - TemperatureCouplingData thermostatData = { couplingTimeStep_, referenceTemperature_, couplingTime_, - numDegreesOfFreedom_, temperatureCouplingIntegral_ }; + TemperatureCouplingData thermostatData = { + couplingTimeStep_, referenceTemperature_, couplingTime_, numDegreesOfFreedom_, temperatureCouplingIntegral_ + }; for (int temperatureGroup = 0; (temperatureGroup < numTemperatureGroups_); temperatureGroup++) { @@ -421,7 +431,8 @@ void VelocityScalingTemperatureCoupling::restoreCheckpointState(std::optionaldd, ssize(temperatureCouplingIntegral_) * int(sizeof(double)), + dd_bcast(cr->dd, + ssize(temperatureCouplingIntegral_) * int(sizeof(double)), temperatureCouplingIntegral_.data()); } temperatureCouplingImpl_->readCheckpoint( @@ -441,12 +452,13 @@ real VelocityScalingTemperatureCoupling::conservedEnergyContribution() const if (reportPreviousConservedEnergy_ == ReportPreviousStepConservedEnergy::Yes) { return std::accumulate(temperatureCouplingIntegralPreviousStep_.begin(), - temperatureCouplingIntegralPreviousStep_.end(), 0.0); + temperatureCouplingIntegralPreviousStep_.end(), + 0.0); } else { - return std::accumulate(temperatureCouplingIntegral_.begin(), - temperatureCouplingIntegral_.end(), 0.0); + return std::accumulate( + temperatureCouplingIntegral_.begin(), temperatureCouplingIntegral_.end(), 0.0); } } @@ -463,11 +475,18 @@ ISimulatorElement* VelocityScalingTemperatureCoupling::getElementPointerImpl( { // Element is now owned by the caller of this method, who will handle lifetime (see ModularSimulatorAlgorithm) auto* element = builderHelper->storeElement(std::make_unique( - legacySimulatorData->inputrec->nsttcouple, offset, useFullStepKE, reportPreviousStepConservedEnergy, - legacySimulatorData->inputrec->ld_seed, legacySimulatorData->inputrec->opts.ngtc, + legacySimulatorData->inputrec->nsttcouple, + offset, + useFullStepKE, + reportPreviousStepConservedEnergy, + legacySimulatorData->inputrec->ld_seed, + legacySimulatorData->inputrec->opts.ngtc, legacySimulatorData->inputrec->delta_t * legacySimulatorData->inputrec->nsttcouple, - legacySimulatorData->inputrec->opts.ref_t, legacySimulatorData->inputrec->opts.tau_t, - legacySimulatorData->inputrec->opts.nrdf, energyData, legacySimulatorData->inputrec->etc)); + legacySimulatorData->inputrec->opts.ref_t, + legacySimulatorData->inputrec->opts.tau_t, + legacySimulatorData->inputrec->opts.nrdf, + energyData, + legacySimulatorData->inputrec->etc)); auto* thermostat = static_cast(element); // Capturing pointer is safe because lifetime is handled by caller builderHelper->registerThermostat([thermostat](const PropagatorThermostatConnection& connection) { diff --git a/src/gromacs/nbnxm/atomdata.cpp b/src/gromacs/nbnxm/atomdata.cpp index 76b394c98b..1582c50155 100644 --- a/src/gromacs/nbnxm/atomdata.cpp +++ b/src/gromacs/nbnxm/atomdata.cpp @@ -516,8 +516,7 @@ static void nbnxn_atomdata_params_init(const gmx::MDLogger& mdlog, /* Compare 6*C6 and 12*C12 for geometric cobination rule */ bCombGeom = bCombGeom - && gmx_within_tol(c6 * c6, - nbfp[(i * ntype + i) * 2] * nbfp[(j * ntype + j) * 2], tol) + && gmx_within_tol(c6 * c6, nbfp[(i * ntype + i) * 2] * nbfp[(j * ntype + j) * 2], tol) && gmx_within_tol(c12 * c12, nbfp[(i * ntype + i) * 2 + 1] * nbfp[(j * ntype + j) * 2 + 1], tol); @@ -530,9 +529,9 @@ static void nbnxn_atomdata_params_init(const gmx::MDLogger& mdlog, && ((c6 == 0 && c12 == 0 && (params->nbfp_comb[i * 2 + 1] == 0 || params->nbfp_comb[j * 2 + 1] == 0)) || (c6 > 0 && c12 > 0 - && gmx_within_tol( - gmx::sixthroot(c12 / c6), - 0.5 * (params->nbfp_comb[i * 2] + params->nbfp_comb[j * 2]), tol) + && gmx_within_tol(gmx::sixthroot(c12 / c6), + 0.5 * (params->nbfp_comb[i * 2] + params->nbfp_comb[j * 2]), + tol) && gmx_within_tol(0.25 * c6 * c6 / c12, std::sqrt(params->nbfp_comb[i * 2 + 1] * params->nbfp_comb[j * 2 + 1]), @@ -548,8 +547,10 @@ static void nbnxn_atomdata_params_init(const gmx::MDLogger& mdlog, } if (debug) { - fprintf(debug, "Combination rules: geometric %s Lorentz-Berthelot %s\n", - gmx::boolToString(bCombGeom), gmx::boolToString(bCombLB)); + fprintf(debug, + "Combination rules: geometric %s Lorentz-Berthelot %s\n", + gmx::boolToString(bCombGeom), + gmx::boolToString(bCombLB)); } simple = Nbnxm::kernelTypeUsesSimplePairlist(kernelType); @@ -631,8 +632,8 @@ void nbnxn_atomdata_init(const gmx::MDLogger& mdlog, int n_energygroups, int nout) { - nbnxn_atomdata_params_init(mdlog, &nbat->paramsDeprecated(), kernelType, enbnxninitcombrule, - ntype, nbfp, n_energygroups); + nbnxn_atomdata_params_init( + mdlog, &nbat->paramsDeprecated(), kernelType, enbnxninitcombrule, ntype, nbfp, n_energygroups); const bool simple = Nbnxm::kernelTypeUsesSimplePairlist(kernelType); const bool bSIMD = Nbnxm::kernelTypeIsSimd(kernelType); @@ -673,8 +674,8 @@ void nbnxn_atomdata_init(const gmx::MDLogger& mdlog, for (int i = 0; i < nout; i++) { const auto& pinningPolicy = nbat->params().type.get_allocator().pinningPolicy(); - nbat->out.emplace_back(kernelType, nbat->params().nenergrp, 1 << nbat->params().neg_2log, - pinningPolicy); + nbat->out.emplace_back( + kernelType, nbat->params().nenergrp, 1 << nbat->params().neg_2log, pinningPolicy); } nbat->buffer_flags.clear(); @@ -737,8 +738,11 @@ static void nbnxn_atomdata_set_atomtypes(nbnxn_atomdata_t::Params* params, const int atomOffset = grid.firstAtomInColumn(i); copy_int_to_nbat_int(gridSet.atomIndices().data() + atomOffset, - grid.numAtomsInColumn(i), numAtoms, atomTypes.data(), - params->numTypes - 1, params->type.data() + atomOffset); + grid.numAtomsInColumn(i), + numAtoms, + atomTypes.data(), + params->numTypes - 1, + params->type.data() + atomOffset); } } } @@ -763,19 +767,23 @@ static void nbnxn_atomdata_set_ljcombparams(nbnxn_atomdata_t::Params* params, if (XFormat == nbatX4) { copy_lj_to_nbat_lj_comb(params->nbfp_comb, - params->type.data() + atomOffset, numAtoms, + params->type.data() + atomOffset, + numAtoms, params->lj_comb.data() + atomOffset * 2); } else if (XFormat == nbatX8) { copy_lj_to_nbat_lj_comb(params->nbfp_comb, - params->type.data() + atomOffset, numAtoms, + params->type.data() + atomOffset, + numAtoms, params->lj_comb.data() + atomOffset * 2); } else if (XFormat == nbatXYZQ) { - copy_lj_to_nbat_lj_comb<1>(params->nbfp_comb, params->type.data() + atomOffset, - numAtoms, params->lj_comb.data() + atomOffset * 2); + copy_lj_to_nbat_lj_comb<1>(params->nbfp_comb, + params->type.data() + atomOffset, + numAtoms, + params->lj_comb.data() + atomOffset * 2); } } } @@ -946,8 +954,12 @@ static void nbnxn_atomdata_set_energygroups(nbnxn_atomdata_t::Params* params, const int numAtoms = grid.paddedNumAtomsInColumn(i); const int atomOffset = grid.firstAtomInColumn(i); - copy_egp_to_nbat_egps(gridSet.atomIndices().data() + atomOffset, grid.numAtomsInColumn(i), - numAtoms, c_nbnxnCpuIClusterSize, params->neg_2log, atomInfo.data(), + copy_egp_to_nbat_egps(gridSet.atomIndices().data() + atomOffset, + grid.numAtomsInColumn(i), + numAtoms, + c_nbnxnCpuIClusterSize, + params->neg_2log, + atomInfo.data(), params->energrp.data() + grid.atomToCluster(atomOffset)); } } @@ -1065,8 +1077,13 @@ void nbnxn_atomdata_copy_x_to_nbat_x(const Nbnxm::GridSet& gridSet, */ na_fill = na; } - copy_rvec_to_nbat_real(gridSet.atomIndices().data() + ash, na, na_fill, - coordinates, nbat->XFormat, nbat->x().data(), ash); + copy_rvec_to_nbat_real(gridSet.atomIndices().data() + ash, + na, + na_fill, + coordinates, + nbat->XFormat, + nbat->x().data(), + ash); } } } @@ -1089,8 +1106,14 @@ void nbnxn_atomdata_x_to_nbat_x_gpu(const Nbnxm::GridSet& gridSet, for (int g = gridBegin; g < gridEnd; g++) { - nbnxn_gpu_x_to_nbat_x(gridSet.grids()[g], fillLocal && g == 0, gpu_nbv, d_x, xReadyOnDevice, - locality, g, gridSet.numColumnsMax()); + nbnxn_gpu_x_to_nbat_x(gridSet.grids()[g], + fillLocal && g == 0, + gpu_nbv, + d_x, + xReadyOnDevice, + locality, + g, + gridSet.numColumnsMax()); } } @@ -1280,7 +1303,8 @@ static void nbnxn_atomdata_add_nbat_f_to_f_treereduce(nbnxn_atomdata_t* nbat, in /* find thread to sync with. Equal to partner_th unless nth is not a power of two. */ for (sync_th = partner_th, sync_group_size = group_size; - sync_th >= nth && sync_group_size > 2; sync_group_size /= 2) + sync_th >= nth && sync_group_size > 2; + sync_group_size /= 2) { sync_th &= ~(sync_group_size / 4); } @@ -1358,8 +1382,11 @@ static void nbnxn_atomdata_add_nbat_f_to_f_treereduce(nbnxn_atomdata_t* nbat, in nbnxn_atomdata_reduce_reals #endif (nbat->out[index[0]].f.data(), - bitmask_is_set(flags[b], index[0]) || group_size > 2, &fIndex1, - 1, i0, i1); + bitmask_is_set(flags[b], index[0]) || group_size > 2, + &fIndex1, + 1, + i0, + i1); } else if (!bitmask_is_set(flags[b], index[0])) { @@ -1463,8 +1490,8 @@ void reduceForces(nbnxn_atomdata_t* nbat, const gmx::AtomLocality locality, cons { try { - nbnxn_atomdata_add_nbat_f_to_f_part(gridSet, *nbat, nbat->out[0], a0 + ((th + 0) * na) / nth, - a0 + ((th + 1) * na) / nth, f); + nbnxn_atomdata_add_nbat_f_to_f_part( + gridSet, *nbat, nbat->out[0], a0 + ((th + 0) * na) / nth, a0 + ((th + 1) * na) / nth, f); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR } diff --git a/src/gromacs/nbnxm/benchmark/bench_setup.cpp b/src/gromacs/nbnxm/benchmark/bench_setup.cpp index 9fffb257ea..6f0be163ca 100644 --- a/src/gromacs/nbnxm/benchmark/bench_setup.cpp +++ b/src/gromacs/nbnxm/benchmark/bench_setup.cpp @@ -190,23 +190,28 @@ static std::unique_ptr setupNbnxmForBenchInstance(const Kern PairlistParams pairlistParams(kernelSetup.kernelType, false, options.pairlistCutoff, false); - GridSet gridSet(PbcType::Xyz, false, nullptr, nullptr, pairlistParams.pairlistType, false, - numThreads, pinPolicy); + GridSet gridSet( + PbcType::Xyz, false, nullptr, nullptr, pairlistParams.pairlistType, false, numThreads, pinPolicy); auto pairlistSets = std::make_unique(pairlistParams, false, 0); - auto pairSearch = - std::make_unique(PbcType::Xyz, false, nullptr, nullptr, - pairlistParams.pairlistType, false, numThreads, pinPolicy); + auto pairSearch = std::make_unique( + PbcType::Xyz, false, nullptr, nullptr, pairlistParams.pairlistType, false, numThreads, pinPolicy); auto atomData = std::make_unique(pinPolicy); // Put everything together - auto nbv = std::make_unique(std::move(pairlistSets), std::move(pairSearch), - std::move(atomData), kernelSetup, nullptr, nullptr); - - nbnxn_atomdata_init(gmx::MDLogger(), nbv->nbat.get(), kernelSetup.kernelType, combinationRule, - system.numAtomTypes, system.nonbondedParameters, 1, numThreads); + auto nbv = std::make_unique( + std::move(pairlistSets), std::move(pairSearch), std::move(atomData), kernelSetup, nullptr, nullptr); + + nbnxn_atomdata_init(gmx::MDLogger(), + nbv->nbat.get(), + kernelSetup.kernelType, + combinationRule, + system.numAtomTypes, + system.nonbondedParameters, + 1, + numThreads); t_nrnb nrnb; @@ -226,9 +231,18 @@ static std::unique_ptr setupNbnxmForBenchInstance(const Kern const real atomDensity = system.coordinates.size() / det(system.box); - nbnxn_put_on_grid(nbv.get(), system.box, 0, lowerCorner, upperCorner, nullptr, - { 0, int(system.coordinates.size()) }, atomDensity, atomInfo, - system.coordinates, 0, nullptr); + nbnxn_put_on_grid(nbv.get(), + system.box, + 0, + lowerCorner, + upperCorner, + nullptr, + { 0, int(system.coordinates.size()) }, + atomDensity, + atomInfo, + system.coordinates, + 0, + nullptr); nbv->constructPairlist(gmx::InteractionLocality::Local, system.excls, 0, &nrnb); @@ -297,18 +311,22 @@ static void setupAndRunInstance(const gmx::BenchmarkSystem& system, stepWork.computeEnergy = true; } - const gmx::EnumerationArray kernelNames = { "auto", "no", "4xM", - "2xMM" }; + const gmx::EnumerationArray kernelNames = { + "auto", "no", "4xM", "2xMM" + }; - const gmx::EnumerationArray combruleNames = { "geom.", "LB", + const gmx::EnumerationArray combruleNames = { "geom.", + "LB", "none" }; if (!doWarmup) { - fprintf(stdout, "%-7s %-4s %-5s %-4s ", + fprintf(stdout, + "%-7s %-4s %-5s %-4s ", options.coulombType == BenchMarkCoulomb::Pme ? "Ewald" : "RF", options.useHalfLJOptimization ? "half" : "all", - combruleNames[options.ljCombinationRule].c_str(), kernelNames[options.nbnxmSimd].c_str()); + combruleNames[options.ljCombinationRule].c_str(), + kernelNames[options.nbnxmSimd].c_str()); if (!options.outputFile.empty()) { fprintf(system.csv, @@ -319,8 +337,11 @@ static void setupAndRunInstance(const gmx::BenchmarkSystem& system, #else 0, #endif - system.coordinates.size(), options.pairlistCutoff, options.numThreads, - options.numIterations, options.computeVirialAndEnergy ? "yes" : "no", + system.coordinates.size(), + options.pairlistCutoff, + options.numThreads, + options.numIterations, + options.computeVirialAndEnergy ? "yes" : "no", (options.coulombType != BenchMarkCoulomb::ReactionField) ? ((options.nbnxmSimd == BenchMarkKernels::SimdNo || options.useTabulatedEwaldCorr) ? "table" @@ -336,8 +357,8 @@ static void setupAndRunInstance(const gmx::BenchmarkSystem& system, // Run pre-iteration to avoid cache misses for (int iter = 0; iter < options.numPreIterations; iter++) { - nbv->dispatchNonbondedKernel(gmx::InteractionLocality::Local, ic, stepWork, enbvClearFYes, - system.forceRec, &enerd, &nrnb); + nbv->dispatchNonbondedKernel( + gmx::InteractionLocality::Local, ic, stepWork, enbvClearFYes, system.forceRec, &enerd, &nrnb); } const int numIterations = (doWarmup ? options.numWarmupIterations : options.numIterations); @@ -347,8 +368,8 @@ static void setupAndRunInstance(const gmx::BenchmarkSystem& system, for (int iter = 0; iter < numIterations; iter++) { // Run the kernel without force clearing - nbv->dispatchNonbondedKernel(gmx::InteractionLocality::Local, ic, stepWork, enbvClearFNo, - system.forceRec, &enerd, &nrnb); + nbv->dispatchNonbondedKernel( + gmx::InteractionLocality::Local, ic, stepWork, enbvClearFNo, system.forceRec, &enerd, &nrnb); } cycles = gmx_cycles_read() - cycles; if (!doWarmup) @@ -358,25 +379,37 @@ static void setupAndRunInstance(const gmx::BenchmarkSystem& system, const double uSec = static_cast(cycles) * gmx_cycles_calibrate(1.0) * 1.e6; if (options.cyclesPerPair) { - fprintf(stdout, "%13.2f %13.3f %10.3f %10.3f\n", uSec, uSec / options.numIterations, + fprintf(stdout, + "%13.2f %13.3f %10.3f %10.3f\n", + uSec, + uSec / options.numIterations, uSec / (options.numIterations * numPairs), uSec / (options.numIterations * numUsefulPairs)); if (!options.outputFile.empty()) { - fprintf(system.csv, "\"%.3f\",\"%.4f\",\"%.4f\",\"%.4f\"\n", uSec, - uSec / options.numIterations, uSec / (options.numIterations * numPairs), + fprintf(system.csv, + "\"%.3f\",\"%.4f\",\"%.4f\",\"%.4f\"\n", + uSec, + uSec / options.numIterations, + uSec / (options.numIterations * numPairs), uSec / (options.numIterations * numUsefulPairs)); } } else { - fprintf(stdout, "%13.2f %13.3f %10.3f %10.3f\n", uSec, uSec / options.numIterations, + fprintf(stdout, + "%13.2f %13.3f %10.3f %10.3f\n", + uSec, + uSec / options.numIterations, options.numIterations * numPairs / uSec, options.numIterations * numUsefulPairs / uSec); if (!options.outputFile.empty()) { - fprintf(system.csv, "\"%.3f\",\"%.4f\",\"%.4f\",\"%.4f\"\n", uSec, - uSec / options.numIterations, options.numIterations * numPairs / uSec, + fprintf(system.csv, + "\"%.3f\",\"%.4f\",\"%.4f\",\"%.4f\"\n", + uSec, + uSec / options.numIterations, + options.numIterations * numPairs / uSec, options.numIterations * numUsefulPairs / uSec); } } @@ -386,15 +419,20 @@ static void setupAndRunInstance(const gmx::BenchmarkSystem& system, const double dCycles = static_cast(cycles); if (options.cyclesPerPair) { - fprintf(stdout, "%10.3f %10.4f %8.4f %8.4f\n", cycles * 1e-6, + fprintf(stdout, + "%10.3f %10.4f %8.4f %8.4f\n", + cycles * 1e-6, dCycles / options.numIterations * 1e-6, dCycles / (options.numIterations * numPairs), dCycles / (options.numIterations * numUsefulPairs)); } else { - fprintf(stdout, "%10.3f %10.4f %8.4f %8.4f\n", dCycles * 1e-6, - dCycles / options.numIterations * 1e-6, options.numIterations * numPairs / dCycles, + fprintf(stdout, + "%10.3f %10.4f %8.4f %8.4f\n", + dCycles * 1e-6, + dCycles / options.numIterations * 1e-6, + options.numIterations * numPairs / dCycles, options.numIterations * numUsefulPairs / dCycles); } } @@ -460,7 +498,8 @@ void bench(const int sizeFactor, const KernelBenchOptions& options) fprintf(stdout, "Compute energies: %s\n", options.computeVirialAndEnergy ? "yes" : "no"); if (options.coulombType != BenchMarkCoulomb::ReactionField) { - fprintf(stdout, "Ewald excl. corr.: %s\n", + fprintf(stdout, + "Ewald excl. corr.: %s\n", options.nbnxmSimd == BenchMarkKernels::SimdNo || options.useTabulatedEwaldCorr ? "table" : "analytical"); @@ -474,7 +513,8 @@ void bench(const int sizeFactor, const KernelBenchOptions& options) if (options.reportTime) { - fprintf(stdout, "Coulomb LJ comb. SIMD usec usec/it. %s\n", + fprintf(stdout, + "Coulomb LJ comb. SIMD usec usec/it. %s\n", options.cyclesPerPair ? "usec/pair" : "pairs/usec"); if (!options.outputFile.empty()) { @@ -489,7 +529,8 @@ void bench(const int sizeFactor, const KernelBenchOptions& options) } else { - fprintf(stdout, "Coulomb LJ comb. SIMD Mcycles Mcycles/it. %s\n", + fprintf(stdout, + "Coulomb LJ comb. SIMD Mcycles Mcycles/it. %s\n", options.cyclesPerPair ? "cycles/pair" : "pairs/cycle"); if (!options.outputFile.empty()) { diff --git a/src/gromacs/nbnxm/benchmark/bench_system.cpp b/src/gromacs/nbnxm/benchmark/bench_system.cpp index de4d738969..9ed356933a 100644 --- a/src/gromacs/nbnxm/benchmark/bench_system.cpp +++ b/src/gromacs/nbnxm/benchmark/bench_system.cpp @@ -115,8 +115,11 @@ static void generateCoordinates(int multiplicationFactor, std::vector dim = 0; } } - printf("Stacking a box of %zu atoms %d x %d x %d times\n", coordinates1000.size(), factors[XX], - factors[YY], factors[ZZ]); + printf("Stacking a box of %zu atoms %d x %d x %d times\n", + coordinates1000.size(), + factors[XX], + factors[YY], + factors[ZZ]); coordinates->resize(factors[XX] * factors[YY] * factors[ZZ] * coordinates1000.size()); diff --git a/src/gromacs/nbnxm/clusterdistancekerneltype.h b/src/gromacs/nbnxm/clusterdistancekerneltype.h index c7f680ab0c..80da0881e2 100644 --- a/src/gromacs/nbnxm/clusterdistancekerneltype.h +++ b/src/gromacs/nbnxm/clusterdistancekerneltype.h @@ -87,8 +87,7 @@ static inline ClusterDistanceKernelType getClusterDistanceKernelType(const Pairl #elif GMX_SIMD && GMX_SIMD_REAL_WIDTH == 8 return ClusterDistanceKernelType::CpuSimd_2xMM; #else - GMX_RELEASE_ASSERT(false, - "Expect 4-wide or 8-wide SIMD with 4x4 list and nbat SIMD layout"); + GMX_RELEASE_ASSERT(false, "Expect 4-wide or 8-wide SIMD with 4x4 list and nbat SIMD layout"); #endif } else diff --git a/src/gromacs/nbnxm/cuda/nbnxm_cuda.cu b/src/gromacs/nbnxm/cuda/nbnxm_cuda.cu index 29ec2288a9..d269ac27bb 100644 --- a/src/gromacs/nbnxm/cuda/nbnxm_cuda.cu +++ b/src/gromacs/nbnxm/cuda/nbnxm_cuda.cu @@ -145,7 +145,8 @@ static inline int calc_nb_kernel_nblock(int nwork_units, const DeviceInformation "Watch out, the input system is too large to simulate!\n" "The number of nonbonded work units (=number of super-clusters) exceeds the" "maximum grid size in x dimension (%d > %d)!", - nwork_units, max_grid_x_size); + nwork_units, + max_grid_x_size); } return nwork_units; @@ -165,103 +166,164 @@ static inline int calc_nb_kernel_nblock(int nwork_units, const DeviceInformation /*! Force-only kernel function pointers. */ static const nbnxn_cu_kfunc_ptr_t nb_kfunc_noener_noprune_ptr[c_numElecTypes][c_numVdwTypes] = { - { nbnxn_kernel_ElecCut_VdwLJ_F_cuda, nbnxn_kernel_ElecCut_VdwLJCombGeom_F_cuda, - nbnxn_kernel_ElecCut_VdwLJCombLB_F_cuda, nbnxn_kernel_ElecCut_VdwLJFsw_F_cuda, - nbnxn_kernel_ElecCut_VdwLJPsw_F_cuda, nbnxn_kernel_ElecCut_VdwLJEwCombGeom_F_cuda, + { nbnxn_kernel_ElecCut_VdwLJ_F_cuda, + nbnxn_kernel_ElecCut_VdwLJCombGeom_F_cuda, + nbnxn_kernel_ElecCut_VdwLJCombLB_F_cuda, + nbnxn_kernel_ElecCut_VdwLJFsw_F_cuda, + nbnxn_kernel_ElecCut_VdwLJPsw_F_cuda, + nbnxn_kernel_ElecCut_VdwLJEwCombGeom_F_cuda, nbnxn_kernel_ElecCut_VdwLJEwCombLB_F_cuda }, - { nbnxn_kernel_ElecRF_VdwLJ_F_cuda, nbnxn_kernel_ElecRF_VdwLJCombGeom_F_cuda, - nbnxn_kernel_ElecRF_VdwLJCombLB_F_cuda, nbnxn_kernel_ElecRF_VdwLJFsw_F_cuda, - nbnxn_kernel_ElecRF_VdwLJPsw_F_cuda, nbnxn_kernel_ElecRF_VdwLJEwCombGeom_F_cuda, + { nbnxn_kernel_ElecRF_VdwLJ_F_cuda, + nbnxn_kernel_ElecRF_VdwLJCombGeom_F_cuda, + nbnxn_kernel_ElecRF_VdwLJCombLB_F_cuda, + nbnxn_kernel_ElecRF_VdwLJFsw_F_cuda, + nbnxn_kernel_ElecRF_VdwLJPsw_F_cuda, + nbnxn_kernel_ElecRF_VdwLJEwCombGeom_F_cuda, nbnxn_kernel_ElecRF_VdwLJEwCombLB_F_cuda }, - { nbnxn_kernel_ElecEwQSTab_VdwLJ_F_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJCombGeom_F_cuda, - nbnxn_kernel_ElecEwQSTab_VdwLJCombLB_F_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJFsw_F_cuda, - nbnxn_kernel_ElecEwQSTab_VdwLJPsw_F_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJEwCombGeom_F_cuda, + { nbnxn_kernel_ElecEwQSTab_VdwLJ_F_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJCombGeom_F_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJCombLB_F_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJFsw_F_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJPsw_F_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJEwCombGeom_F_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJEwCombLB_F_cuda }, - { nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJ_F_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJCombGeom_F_cuda, - nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJCombLB_F_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJFsw_F_cuda, - nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJPsw_F_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombGeom_F_cuda, + { nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJ_F_cuda, + nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJCombGeom_F_cuda, + nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJCombLB_F_cuda, + nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJFsw_F_cuda, + nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJPsw_F_cuda, + nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombGeom_F_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombLB_F_cuda }, - { nbnxn_kernel_ElecEw_VdwLJ_F_cuda, nbnxn_kernel_ElecEw_VdwLJCombGeom_F_cuda, - nbnxn_kernel_ElecEw_VdwLJCombLB_F_cuda, nbnxn_kernel_ElecEw_VdwLJFsw_F_cuda, - nbnxn_kernel_ElecEw_VdwLJPsw_F_cuda, nbnxn_kernel_ElecEw_VdwLJEwCombGeom_F_cuda, + { nbnxn_kernel_ElecEw_VdwLJ_F_cuda, + nbnxn_kernel_ElecEw_VdwLJCombGeom_F_cuda, + nbnxn_kernel_ElecEw_VdwLJCombLB_F_cuda, + nbnxn_kernel_ElecEw_VdwLJFsw_F_cuda, + nbnxn_kernel_ElecEw_VdwLJPsw_F_cuda, + nbnxn_kernel_ElecEw_VdwLJEwCombGeom_F_cuda, nbnxn_kernel_ElecEw_VdwLJEwCombLB_F_cuda }, - { nbnxn_kernel_ElecEwTwinCut_VdwLJ_F_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJCombGeom_F_cuda, - nbnxn_kernel_ElecEwTwinCut_VdwLJCombLB_F_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJFsw_F_cuda, - nbnxn_kernel_ElecEwTwinCut_VdwLJPsw_F_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJEwCombGeom_F_cuda, + { nbnxn_kernel_ElecEwTwinCut_VdwLJ_F_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJCombGeom_F_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJCombLB_F_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJFsw_F_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJPsw_F_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJEwCombGeom_F_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJEwCombLB_F_cuda } }; /*! Force + energy kernel function pointers. */ static const nbnxn_cu_kfunc_ptr_t nb_kfunc_ener_noprune_ptr[c_numElecTypes][c_numVdwTypes] = { - { nbnxn_kernel_ElecCut_VdwLJ_VF_cuda, nbnxn_kernel_ElecCut_VdwLJCombGeom_VF_cuda, - nbnxn_kernel_ElecCut_VdwLJCombLB_VF_cuda, nbnxn_kernel_ElecCut_VdwLJFsw_VF_cuda, - nbnxn_kernel_ElecCut_VdwLJPsw_VF_cuda, nbnxn_kernel_ElecCut_VdwLJEwCombGeom_VF_cuda, + { nbnxn_kernel_ElecCut_VdwLJ_VF_cuda, + nbnxn_kernel_ElecCut_VdwLJCombGeom_VF_cuda, + nbnxn_kernel_ElecCut_VdwLJCombLB_VF_cuda, + nbnxn_kernel_ElecCut_VdwLJFsw_VF_cuda, + nbnxn_kernel_ElecCut_VdwLJPsw_VF_cuda, + nbnxn_kernel_ElecCut_VdwLJEwCombGeom_VF_cuda, nbnxn_kernel_ElecCut_VdwLJEwCombLB_VF_cuda }, - { nbnxn_kernel_ElecRF_VdwLJ_VF_cuda, nbnxn_kernel_ElecRF_VdwLJCombGeom_VF_cuda, - nbnxn_kernel_ElecRF_VdwLJCombLB_VF_cuda, nbnxn_kernel_ElecRF_VdwLJFsw_VF_cuda, - nbnxn_kernel_ElecRF_VdwLJPsw_VF_cuda, nbnxn_kernel_ElecRF_VdwLJEwCombGeom_VF_cuda, + { nbnxn_kernel_ElecRF_VdwLJ_VF_cuda, + nbnxn_kernel_ElecRF_VdwLJCombGeom_VF_cuda, + nbnxn_kernel_ElecRF_VdwLJCombLB_VF_cuda, + nbnxn_kernel_ElecRF_VdwLJFsw_VF_cuda, + nbnxn_kernel_ElecRF_VdwLJPsw_VF_cuda, + nbnxn_kernel_ElecRF_VdwLJEwCombGeom_VF_cuda, nbnxn_kernel_ElecRF_VdwLJEwCombLB_VF_cuda }, - { nbnxn_kernel_ElecEwQSTab_VdwLJ_VF_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJCombGeom_VF_cuda, - nbnxn_kernel_ElecEwQSTab_VdwLJCombLB_VF_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJFsw_VF_cuda, - nbnxn_kernel_ElecEwQSTab_VdwLJPsw_VF_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJEwCombGeom_VF_cuda, + { nbnxn_kernel_ElecEwQSTab_VdwLJ_VF_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJCombGeom_VF_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJCombLB_VF_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJFsw_VF_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJPsw_VF_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJEwCombGeom_VF_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJEwCombLB_VF_cuda }, - { nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJ_VF_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJCombGeom_VF_cuda, - nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJCombLB_VF_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJFsw_VF_cuda, - nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJPsw_VF_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombGeom_VF_cuda, + { nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJ_VF_cuda, + nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJCombGeom_VF_cuda, + nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJCombLB_VF_cuda, + nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJFsw_VF_cuda, + nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJPsw_VF_cuda, + nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombGeom_VF_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombLB_VF_cuda }, - { nbnxn_kernel_ElecEw_VdwLJ_VF_cuda, nbnxn_kernel_ElecEw_VdwLJCombGeom_VF_cuda, - nbnxn_kernel_ElecEw_VdwLJCombLB_VF_cuda, nbnxn_kernel_ElecEw_VdwLJFsw_VF_cuda, - nbnxn_kernel_ElecEw_VdwLJPsw_VF_cuda, nbnxn_kernel_ElecEw_VdwLJEwCombGeom_VF_cuda, + { nbnxn_kernel_ElecEw_VdwLJ_VF_cuda, + nbnxn_kernel_ElecEw_VdwLJCombGeom_VF_cuda, + nbnxn_kernel_ElecEw_VdwLJCombLB_VF_cuda, + nbnxn_kernel_ElecEw_VdwLJFsw_VF_cuda, + nbnxn_kernel_ElecEw_VdwLJPsw_VF_cuda, + nbnxn_kernel_ElecEw_VdwLJEwCombGeom_VF_cuda, nbnxn_kernel_ElecEw_VdwLJEwCombLB_VF_cuda }, - { nbnxn_kernel_ElecEwTwinCut_VdwLJ_VF_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJCombGeom_VF_cuda, - nbnxn_kernel_ElecEwTwinCut_VdwLJCombLB_VF_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJFsw_VF_cuda, - nbnxn_kernel_ElecEwTwinCut_VdwLJPsw_VF_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJEwCombGeom_VF_cuda, + { nbnxn_kernel_ElecEwTwinCut_VdwLJ_VF_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJCombGeom_VF_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJCombLB_VF_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJFsw_VF_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJPsw_VF_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJEwCombGeom_VF_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJEwCombLB_VF_cuda } }; /*! Force + pruning kernel function pointers. */ static const nbnxn_cu_kfunc_ptr_t nb_kfunc_noener_prune_ptr[c_numElecTypes][c_numVdwTypes] = { - { nbnxn_kernel_ElecCut_VdwLJ_F_prune_cuda, nbnxn_kernel_ElecCut_VdwLJCombGeom_F_prune_cuda, - nbnxn_kernel_ElecCut_VdwLJCombLB_F_prune_cuda, nbnxn_kernel_ElecCut_VdwLJFsw_F_prune_cuda, - nbnxn_kernel_ElecCut_VdwLJPsw_F_prune_cuda, nbnxn_kernel_ElecCut_VdwLJEwCombGeom_F_prune_cuda, + { nbnxn_kernel_ElecCut_VdwLJ_F_prune_cuda, + nbnxn_kernel_ElecCut_VdwLJCombGeom_F_prune_cuda, + nbnxn_kernel_ElecCut_VdwLJCombLB_F_prune_cuda, + nbnxn_kernel_ElecCut_VdwLJFsw_F_prune_cuda, + nbnxn_kernel_ElecCut_VdwLJPsw_F_prune_cuda, + nbnxn_kernel_ElecCut_VdwLJEwCombGeom_F_prune_cuda, nbnxn_kernel_ElecCut_VdwLJEwCombLB_F_prune_cuda }, - { nbnxn_kernel_ElecRF_VdwLJ_F_prune_cuda, nbnxn_kernel_ElecRF_VdwLJCombGeom_F_prune_cuda, - nbnxn_kernel_ElecRF_VdwLJCombLB_F_prune_cuda, nbnxn_kernel_ElecRF_VdwLJFsw_F_prune_cuda, - nbnxn_kernel_ElecRF_VdwLJPsw_F_prune_cuda, nbnxn_kernel_ElecRF_VdwLJEwCombGeom_F_prune_cuda, + { nbnxn_kernel_ElecRF_VdwLJ_F_prune_cuda, + nbnxn_kernel_ElecRF_VdwLJCombGeom_F_prune_cuda, + nbnxn_kernel_ElecRF_VdwLJCombLB_F_prune_cuda, + nbnxn_kernel_ElecRF_VdwLJFsw_F_prune_cuda, + nbnxn_kernel_ElecRF_VdwLJPsw_F_prune_cuda, + nbnxn_kernel_ElecRF_VdwLJEwCombGeom_F_prune_cuda, nbnxn_kernel_ElecRF_VdwLJEwCombLB_F_prune_cuda }, - { nbnxn_kernel_ElecEwQSTab_VdwLJ_F_prune_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJCombGeom_F_prune_cuda, - nbnxn_kernel_ElecEwQSTab_VdwLJCombLB_F_prune_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJFsw_F_prune_cuda, - nbnxn_kernel_ElecEwQSTab_VdwLJPsw_F_prune_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJEwCombGeom_F_prune_cuda, + { nbnxn_kernel_ElecEwQSTab_VdwLJ_F_prune_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJCombGeom_F_prune_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJCombLB_F_prune_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJFsw_F_prune_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJPsw_F_prune_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJEwCombGeom_F_prune_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJEwCombLB_F_prune_cuda }, { nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJ_F_prune_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJCombGeom_F_prune_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJCombLB_F_prune_cuda, - nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJFsw_F_prune_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJPsw_F_prune_cuda, + nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJFsw_F_prune_cuda, + nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJPsw_F_prune_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombGeom_F_prune_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombLB_F_prune_cuda }, - { nbnxn_kernel_ElecEw_VdwLJ_F_prune_cuda, nbnxn_kernel_ElecEw_VdwLJCombGeom_F_prune_cuda, - nbnxn_kernel_ElecEw_VdwLJCombLB_F_prune_cuda, nbnxn_kernel_ElecEw_VdwLJFsw_F_prune_cuda, - nbnxn_kernel_ElecEw_VdwLJPsw_F_prune_cuda, nbnxn_kernel_ElecEw_VdwLJEwCombGeom_F_prune_cuda, + { nbnxn_kernel_ElecEw_VdwLJ_F_prune_cuda, + nbnxn_kernel_ElecEw_VdwLJCombGeom_F_prune_cuda, + nbnxn_kernel_ElecEw_VdwLJCombLB_F_prune_cuda, + nbnxn_kernel_ElecEw_VdwLJFsw_F_prune_cuda, + nbnxn_kernel_ElecEw_VdwLJPsw_F_prune_cuda, + nbnxn_kernel_ElecEw_VdwLJEwCombGeom_F_prune_cuda, nbnxn_kernel_ElecEw_VdwLJEwCombLB_F_prune_cuda }, - { nbnxn_kernel_ElecEwTwinCut_VdwLJ_F_prune_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJCombGeom_F_prune_cuda, - nbnxn_kernel_ElecEwTwinCut_VdwLJCombLB_F_prune_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJFsw_F_prune_cuda, - nbnxn_kernel_ElecEwTwinCut_VdwLJPsw_F_prune_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJEwCombGeom_F_prune_cuda, + { nbnxn_kernel_ElecEwTwinCut_VdwLJ_F_prune_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJCombGeom_F_prune_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJCombLB_F_prune_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJFsw_F_prune_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJPsw_F_prune_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJEwCombGeom_F_prune_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJEwCombLB_F_prune_cuda } }; /*! Force + energy + pruning kernel function pointers. */ static const nbnxn_cu_kfunc_ptr_t nb_kfunc_ener_prune_ptr[c_numElecTypes][c_numVdwTypes] = { - { nbnxn_kernel_ElecCut_VdwLJ_VF_prune_cuda, nbnxn_kernel_ElecCut_VdwLJCombGeom_VF_prune_cuda, - nbnxn_kernel_ElecCut_VdwLJCombLB_VF_prune_cuda, nbnxn_kernel_ElecCut_VdwLJFsw_VF_prune_cuda, - nbnxn_kernel_ElecCut_VdwLJPsw_VF_prune_cuda, nbnxn_kernel_ElecCut_VdwLJEwCombGeom_VF_prune_cuda, + { nbnxn_kernel_ElecCut_VdwLJ_VF_prune_cuda, + nbnxn_kernel_ElecCut_VdwLJCombGeom_VF_prune_cuda, + nbnxn_kernel_ElecCut_VdwLJCombLB_VF_prune_cuda, + nbnxn_kernel_ElecCut_VdwLJFsw_VF_prune_cuda, + nbnxn_kernel_ElecCut_VdwLJPsw_VF_prune_cuda, + nbnxn_kernel_ElecCut_VdwLJEwCombGeom_VF_prune_cuda, nbnxn_kernel_ElecCut_VdwLJEwCombLB_VF_prune_cuda }, - { nbnxn_kernel_ElecRF_VdwLJ_VF_prune_cuda, nbnxn_kernel_ElecRF_VdwLJCombGeom_VF_prune_cuda, - nbnxn_kernel_ElecRF_VdwLJCombLB_VF_prune_cuda, nbnxn_kernel_ElecRF_VdwLJFsw_VF_prune_cuda, - nbnxn_kernel_ElecRF_VdwLJPsw_VF_prune_cuda, nbnxn_kernel_ElecRF_VdwLJEwCombGeom_VF_prune_cuda, + { nbnxn_kernel_ElecRF_VdwLJ_VF_prune_cuda, + nbnxn_kernel_ElecRF_VdwLJCombGeom_VF_prune_cuda, + nbnxn_kernel_ElecRF_VdwLJCombLB_VF_prune_cuda, + nbnxn_kernel_ElecRF_VdwLJFsw_VF_prune_cuda, + nbnxn_kernel_ElecRF_VdwLJPsw_VF_prune_cuda, + nbnxn_kernel_ElecRF_VdwLJEwCombGeom_VF_prune_cuda, nbnxn_kernel_ElecRF_VdwLJEwCombLB_VF_prune_cuda }, - { nbnxn_kernel_ElecEwQSTab_VdwLJ_VF_prune_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJCombGeom_VF_prune_cuda, - nbnxn_kernel_ElecEwQSTab_VdwLJCombLB_VF_prune_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJFsw_VF_prune_cuda, - nbnxn_kernel_ElecEwQSTab_VdwLJPsw_VF_prune_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJEwCombGeom_VF_prune_cuda, + { nbnxn_kernel_ElecEwQSTab_VdwLJ_VF_prune_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJCombGeom_VF_prune_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJCombLB_VF_prune_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJFsw_VF_prune_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJPsw_VF_prune_cuda, + nbnxn_kernel_ElecEwQSTab_VdwLJEwCombGeom_VF_prune_cuda, nbnxn_kernel_ElecEwQSTab_VdwLJEwCombLB_VF_prune_cuda }, { nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJ_VF_prune_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJCombGeom_VF_prune_cuda, @@ -270,13 +332,18 @@ static const nbnxn_cu_kfunc_ptr_t nb_kfunc_ener_prune_ptr[c_numElecTypes][c_numV nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJPsw_VF_prune_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombGeom_VF_prune_cuda, nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombLB_VF_prune_cuda }, - { nbnxn_kernel_ElecEw_VdwLJ_VF_prune_cuda, nbnxn_kernel_ElecEw_VdwLJCombGeom_VF_prune_cuda, - nbnxn_kernel_ElecEw_VdwLJCombLB_VF_prune_cuda, nbnxn_kernel_ElecEw_VdwLJFsw_VF_prune_cuda, - nbnxn_kernel_ElecEw_VdwLJPsw_VF_prune_cuda, nbnxn_kernel_ElecEw_VdwLJEwCombGeom_VF_prune_cuda, + { nbnxn_kernel_ElecEw_VdwLJ_VF_prune_cuda, + nbnxn_kernel_ElecEw_VdwLJCombGeom_VF_prune_cuda, + nbnxn_kernel_ElecEw_VdwLJCombLB_VF_prune_cuda, + nbnxn_kernel_ElecEw_VdwLJFsw_VF_prune_cuda, + nbnxn_kernel_ElecEw_VdwLJPsw_VF_prune_cuda, + nbnxn_kernel_ElecEw_VdwLJEwCombGeom_VF_prune_cuda, nbnxn_kernel_ElecEw_VdwLJEwCombLB_VF_prune_cuda }, - { nbnxn_kernel_ElecEwTwinCut_VdwLJ_VF_prune_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJCombGeom_VF_prune_cuda, + { nbnxn_kernel_ElecEwTwinCut_VdwLJ_VF_prune_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJCombGeom_VF_prune_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJCombLB_VF_prune_cuda, - nbnxn_kernel_ElecEwTwinCut_VdwLJFsw_VF_prune_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJPsw_VF_prune_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJFsw_VF_prune_cuda, + nbnxn_kernel_ElecEwTwinCut_VdwLJPsw_VF_prune_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJEwCombGeom_VF_prune_cuda, nbnxn_kernel_ElecEwTwinCut_VdwLJEwCombLB_VF_prune_cuda } }; @@ -446,8 +513,13 @@ void gpu_copy_xq_to_gpu(NbnxmGpu* nb, const nbnxn_atomdata_t* nbatom, const Atom static_assert(sizeof(adat->xq[0]) == sizeof(float4), "The size of the xyzq buffer element should be equal to the size of float4."); - copyToDeviceBuffer(&adat->xq, reinterpret_cast(nbatom->x().data()) + adat_begin, - adat_begin, adat_len, deviceStream, GpuApiCallBehavior::Async, nullptr); + copyToDeviceBuffer(&adat->xq, + reinterpret_cast(nbatom->x().data()) + adat_begin, + adat_begin, + adat_len, + deviceStream, + GpuApiCallBehavior::Async, + nullptr); if (bDoTime) { @@ -554,14 +626,22 @@ void gpu_launch_kernel(NbnxmGpu* nb, const gmx::StepWorkload& stepWork, const In "Non-bonded GPU launch configuration:\n\tThread block: %zux%zux%zu\n\t" "\tGrid: %zux%zu\n\t#Super-clusters/clusters: %d/%d (%d)\n" "\tShMem: %zu\n", - config.blockSize[0], config.blockSize[1], config.blockSize[2], config.gridSize[0], - config.gridSize[1], plist->nsci * c_nbnxnGpuNumClusterPerSupercluster, - c_nbnxnGpuNumClusterPerSupercluster, plist->na_c, config.sharedMemorySize); + config.blockSize[0], + config.blockSize[1], + config.blockSize[2], + config.gridSize[0], + config.gridSize[1], + plist->nsci * c_nbnxnGpuNumClusterPerSupercluster, + c_nbnxnGpuNumClusterPerSupercluster, + plist->na_c, + config.sharedMemorySize); } auto* timingEvent = bDoTime ? t->interaction[iloc].nb_k.fetchNextEvent() : nullptr; const auto kernel = - select_nbnxn_kernel(nbp->elecType, nbp->vdwType, stepWork.computeEnergy, + select_nbnxn_kernel(nbp->elecType, + nbp->vdwType, + stepWork.computeEnergy, (plist->haveFreshList && !nb->timers->interaction[iloc].didPrune), &nb->deviceContext_->deviceInfo()); const auto kernelArgs = @@ -678,9 +758,15 @@ void gpu_launch_kernel_pruneonly(NbnxmGpu* nb, const InteractionLocality iloc, c "Pruning GPU kernel launch configuration:\n\tThread block: %zux%zux%zu\n\t" "\tGrid: %zux%zu\n\t#Super-clusters/clusters: %d/%d (%d)\n" "\tShMem: %zu\n", - config.blockSize[0], config.blockSize[1], config.blockSize[2], config.gridSize[0], - config.gridSize[1], numSciInPart * c_nbnxnGpuNumClusterPerSupercluster, - c_nbnxnGpuNumClusterPerSupercluster, plist->na_c, config.sharedMemorySize); + config.blockSize[0], + config.blockSize[1], + config.blockSize[2], + config.gridSize[0], + config.gridSize[1], + numSciInPart * c_nbnxnGpuNumClusterPerSupercluster, + c_nbnxnGpuNumClusterPerSupercluster, + plist->na_c, + config.sharedMemorySize); } auto* timingEvent = bDoTime ? timer->fetchNextEvent() : nullptr; @@ -765,8 +851,13 @@ void gpu_launch_cpyback(NbnxmGpu* nb, static_assert( sizeof(adat->f[0]) == sizeof(float3), "The size of the force buffer element should be equal to the size of float3."); - copyFromDeviceBuffer(reinterpret_cast(nbatom->out[0].f.data()) + adat_begin, &adat->f, - adat_begin, adat_len, deviceStream, GpuApiCallBehavior::Async, nullptr); + copyFromDeviceBuffer(reinterpret_cast(nbatom->out[0].f.data()) + adat_begin, + &adat->f, + adat_begin, + adat_len, + deviceStream, + GpuApiCallBehavior::Async, + nullptr); } /* After the non-local D2H is launched the nonlocal_done event can be @@ -787,8 +878,8 @@ void gpu_launch_cpyback(NbnxmGpu* nb, { static_assert(sizeof(nb->nbst.fshift[0]) == sizeof(adat->fshift[0]), "Sizes of host- and device-side shift vectors should be the same."); - copyFromDeviceBuffer(nb->nbst.fshift, &adat->fshift, 0, SHIFTS, deviceStream, - GpuApiCallBehavior::Async, nullptr); + copyFromDeviceBuffer( + nb->nbst.fshift, &adat->fshift, 0, SHIFTS, deviceStream, GpuApiCallBehavior::Async, nullptr); } /* DtoH energies */ @@ -796,13 +887,13 @@ void gpu_launch_cpyback(NbnxmGpu* nb, { static_assert(sizeof(nb->nbst.e_lj[0]) == sizeof(adat->e_lj[0]), "Sizes of host- and device-side LJ energy terms should be the same."); - copyFromDeviceBuffer(nb->nbst.e_lj, &adat->e_lj, 0, 1, deviceStream, - GpuApiCallBehavior::Async, nullptr); + copyFromDeviceBuffer( + nb->nbst.e_lj, &adat->e_lj, 0, 1, deviceStream, GpuApiCallBehavior::Async, nullptr); static_assert(sizeof(nb->nbst.e_el[0]) == sizeof(adat->e_el[0]), "Sizes of host- and device-side electrostatic energy terms should be the " "same."); - copyFromDeviceBuffer(nb->nbst.e_el, &adat->e_el, 0, 1, deviceStream, - GpuApiCallBehavior::Async, nullptr); + copyFromDeviceBuffer( + nb->nbst.e_el, &adat->e_el, 0, 1, deviceStream, GpuApiCallBehavior::Async, nullptr); } } @@ -881,9 +972,16 @@ void nbnxn_gpu_x_to_nbat_x(const Nbnxm::Grid& grid, const int* d_atomIndices = nb->atomIndices; const int* d_cxy_na = &nb->cxy_na[numColumnsMax * gridId]; const int* d_cxy_ind = &nb->cxy_ind[numColumnsMax * gridId]; - const auto kernelArgs = prepareGpuKernelArguments(kernelFn, config, &numColumns, &d_xq, - &d_xFloat3, &d_atomIndices, &d_cxy_na, - &d_cxy_ind, &cellOffset, &numAtomsPerCell); + const auto kernelArgs = prepareGpuKernelArguments(kernelFn, + config, + &numColumns, + &d_xq, + &d_xFloat3, + &d_atomIndices, + &d_cxy_na, + &d_cxy_ind, + &cellOffset, + &numAtomsPerCell); launchGpuKernel(kernelFn, config, deviceStream, nullptr, "XbufferOps", kernelArgs); } diff --git a/src/gromacs/nbnxm/cuda/nbnxm_cuda_data_mgmt.cu b/src/gromacs/nbnxm/cuda/nbnxm_cuda_data_mgmt.cu index 65ec216351..584c84dc83 100644 --- a/src/gromacs/nbnxm/cuda/nbnxm_cuda_data_mgmt.cu +++ b/src/gromacs/nbnxm/cuda/nbnxm_cuda_data_mgmt.cu @@ -151,15 +151,15 @@ static void init_nbparam(NBParamGpu* nbp, /* set up LJ parameter lookup table */ if (!useLjCombRule(nbp->vdwType)) { - initParamLookupTable(&nbp->nbfp, &nbp->nbfp_texobj, nbatParams.nbfp.data(), - 2 * ntypes * ntypes, deviceContext); + initParamLookupTable( + &nbp->nbfp, &nbp->nbfp_texobj, nbatParams.nbfp.data(), 2 * ntypes * ntypes, deviceContext); } /* set up LJ-PME parameter lookup table */ if (ic->vdwtype == evdwPME) { - initParamLookupTable(&nbp->nbfp_comb, &nbp->nbfp_comb_texobj, nbatParams.nbfp_comb.data(), - 2 * ntypes, deviceContext); + initParamLookupTable( + &nbp->nbfp_comb, &nbp->nbfp_comb_texobj, nbatParams.nbfp_comb.data(), 2 * ntypes, deviceContext); } } @@ -277,8 +277,13 @@ void gpu_upload_shiftvec(NbnxmGpu* nb, const nbnxn_atomdata_t* nbatom) { static_assert(sizeof(adat->shift_vec[0]) == sizeof(nbatom->shift_vec[0]), "Sizes of host- and device-side shift vectors should be the same."); - copyToDeviceBuffer(&adat->shift_vec, reinterpret_cast(nbatom->shift_vec.data()), - 0, SHIFTS, localStream, GpuApiCallBehavior::Async, nullptr); + copyToDeviceBuffer(&adat->shift_vec, + reinterpret_cast(nbatom->shift_vec.data()), + 0, + SHIFTS, + localStream, + GpuApiCallBehavior::Async, + nullptr); adat->bShiftVecUploaded = true; } } @@ -376,15 +381,24 @@ void gpu_init_atomdata(NbnxmGpu* nb, const nbnxn_atomdata_t* nbat) static_assert(sizeof(d_atdat->lj_comb[0]) == sizeof(float2), "Size of the LJ parameters element should be equal to the size of float2."); copyToDeviceBuffer(&d_atdat->lj_comb, - reinterpret_cast(nbat->params().lj_comb.data()), 0, - natoms, localStream, GpuApiCallBehavior::Async, nullptr); + reinterpret_cast(nbat->params().lj_comb.data()), + 0, + natoms, + localStream, + GpuApiCallBehavior::Async, + nullptr); } else { static_assert(sizeof(d_atdat->atom_types[0]) == sizeof(nbat->params().type[0]), "Sizes of host- and device-side atom types should be the same."); - copyToDeviceBuffer(&d_atdat->atom_types, nbat->params().type.data(), 0, natoms, localStream, - GpuApiCallBehavior::Async, nullptr); + copyToDeviceBuffer(&d_atdat->atom_types, + nbat->params().type.data(), + 0, + natoms, + localStream, + GpuApiCallBehavior::Async, + nullptr); } if (bDoTime) @@ -514,10 +528,16 @@ void nbnxn_gpu_init_x_to_nbat_x(const Nbnxm::GridSet& gridSet, NbnxmGpu* gpu_nbv bool bDoTime = gpu_nbv->bDoTime; const int maxNumColumns = gridSet.numColumnsMax(); - reallocateDeviceBuffer(&gpu_nbv->cxy_na, maxNumColumns * gridSet.grids().size(), - &gpu_nbv->ncxy_na, &gpu_nbv->ncxy_na_alloc, *gpu_nbv->deviceContext_); - reallocateDeviceBuffer(&gpu_nbv->cxy_ind, maxNumColumns * gridSet.grids().size(), - &gpu_nbv->ncxy_ind, &gpu_nbv->ncxy_ind_alloc, *gpu_nbv->deviceContext_); + reallocateDeviceBuffer(&gpu_nbv->cxy_na, + maxNumColumns * gridSet.grids().size(), + &gpu_nbv->ncxy_na, + &gpu_nbv->ncxy_na_alloc, + *gpu_nbv->deviceContext_); + reallocateDeviceBuffer(&gpu_nbv->cxy_ind, + maxNumColumns * gridSet.grids().size(), + &gpu_nbv->ncxy_ind, + &gpu_nbv->ncxy_ind_alloc, + *gpu_nbv->deviceContext_); for (unsigned int g = 0; g < gridSet.grids().size(); g++) { @@ -530,8 +550,11 @@ void nbnxn_gpu_init_x_to_nbat_x(const Nbnxm::GridSet& gridSet, NbnxmGpu* gpu_nbv const int* cxy_na = grid.cxy_na().data(); const int* cxy_ind = grid.cxy_ind().data(); - reallocateDeviceBuffer(&gpu_nbv->atomIndices, atomIndicesSize, &gpu_nbv->atomIndicesSize, - &gpu_nbv->atomIndicesSize_alloc, *gpu_nbv->deviceContext_); + reallocateDeviceBuffer(&gpu_nbv->atomIndices, + atomIndicesSize, + &gpu_nbv->atomIndicesSize, + &gpu_nbv->atomIndicesSize_alloc, + *gpu_nbv->deviceContext_); if (atomIndicesSize > 0) { @@ -541,8 +564,13 @@ void nbnxn_gpu_init_x_to_nbat_x(const Nbnxm::GridSet& gridSet, NbnxmGpu* gpu_nbv gpu_nbv->timers->xf[AtomLocality::Local].nb_h2d.openTimingRegion(deviceStream); } - copyToDeviceBuffer(&gpu_nbv->atomIndices, atomIndices, 0, atomIndicesSize, deviceStream, - GpuApiCallBehavior::Async, nullptr); + copyToDeviceBuffer(&gpu_nbv->atomIndices, + atomIndices, + 0, + atomIndicesSize, + deviceStream, + GpuApiCallBehavior::Async, + nullptr); if (bDoTime) { @@ -558,8 +586,8 @@ void nbnxn_gpu_init_x_to_nbat_x(const Nbnxm::GridSet& gridSet, NbnxmGpu* gpu_nbv } int* destPtr = &gpu_nbv->cxy_na[maxNumColumns * g]; - copyToDeviceBuffer(&destPtr, cxy_na, 0, numColumns, deviceStream, - GpuApiCallBehavior::Async, nullptr); + copyToDeviceBuffer( + &destPtr, cxy_na, 0, numColumns, deviceStream, GpuApiCallBehavior::Async, nullptr); if (bDoTime) { @@ -572,8 +600,8 @@ void nbnxn_gpu_init_x_to_nbat_x(const Nbnxm::GridSet& gridSet, NbnxmGpu* gpu_nbv } destPtr = &gpu_nbv->cxy_ind[maxNumColumns * g]; - copyToDeviceBuffer(&destPtr, cxy_ind, 0, numColumns, deviceStream, - GpuApiCallBehavior::Async, nullptr); + copyToDeviceBuffer( + &destPtr, cxy_ind, 0, numColumns, deviceStream, GpuApiCallBehavior::Async, nullptr); if (bDoTime) { diff --git a/src/gromacs/nbnxm/cuda/nbnxm_cuda_kernel.cuh b/src/gromacs/nbnxm/cuda/nbnxm_cuda_kernel.cuh index 9cddbc1999..9819cfaca9 100644 --- a/src/gromacs/nbnxm/cuda/nbnxm_cuda_kernel.cuh +++ b/src/gromacs/nbnxm/cuda/nbnxm_cuda_kernel.cuh @@ -517,20 +517,28 @@ __launch_bounds__(THREADS_PER_BLOCK) # ifdef LJ_EWALD # ifdef LJ_EWALD_COMB_GEOM # ifdef CALC_ENERGIES - calculate_lj_ewald_comb_geom_F_E(nbparam, typei, typej, r2, inv_r2, - lje_coeff2, lje_coeff6_6, int_bit, - &F_invr, &E_lj_p); + calculate_lj_ewald_comb_geom_F_E( + nbparam, typei, typej, r2, inv_r2, lje_coeff2, lje_coeff6_6, int_bit, &F_invr, &E_lj_p); # else - calculate_lj_ewald_comb_geom_F(nbparam, typei, typej, r2, inv_r2, - lje_coeff2, lje_coeff6_6, &F_invr); + calculate_lj_ewald_comb_geom_F( + nbparam, typei, typej, r2, inv_r2, lje_coeff2, lje_coeff6_6, &F_invr); # endif /* CALC_ENERGIES */ # elif defined LJ_EWALD_COMB_LB - calculate_lj_ewald_comb_LB_F_E(nbparam, typei, typej, r2, inv_r2, - lje_coeff2, lje_coeff6_6, + calculate_lj_ewald_comb_LB_F_E(nbparam, + typei, + typej, + r2, + inv_r2, + lje_coeff2, + lje_coeff6_6, # ifdef CALC_ENERGIES - int_bit, &F_invr, &E_lj_p + int_bit, + &F_invr, + &E_lj_p # else - 0, &F_invr, nullptr + 0, + &F_invr, + nullptr # endif /* CALC_ENERGIES */ ); # endif /* LJ_EWALD_COMB_GEOM */ diff --git a/src/gromacs/nbnxm/gpu_common.h b/src/gromacs/nbnxm/gpu_common.h index 7d41ee6180..9b383d2ec6 100644 --- a/src/gromacs/nbnxm/gpu_common.h +++ b/src/gromacs/nbnxm/gpu_common.h @@ -89,7 +89,8 @@ static inline void validateGpuAtomLocality(const AtomLocality atomLocality) std::string str = gmx::formatString( "Invalid atom locality passed (%d); valid here is only " "local (%d) or nonlocal (%d)", - static_cast(atomLocality), static_cast(AtomLocality::Local), + static_cast(atomLocality), + static_cast(AtomLocality::Local), static_cast(AtomLocality::NonLocal)); GMX_ASSERT(atomLocality == AtomLocality::Local || atomLocality == AtomLocality::NonLocal, str.c_str()); @@ -424,8 +425,13 @@ bool gpu_try_finish_task(NbnxmGpu* nb, if (stepWork.computeEnergy || stepWork.computeVirial) { - gpu_reduce_staged_outputs(nb->nbst, iLocality, stepWork.computeEnergy, stepWork.computeVirial, - e_lj, e_el, as_rvec_array(shiftForces.data())); + gpu_reduce_staged_outputs(nb->nbst, + iLocality, + stepWork.computeEnergy, + stepWork.computeVirial, + e_lj, + e_el, + as_rvec_array(shiftForces.data())); } } diff --git a/src/gromacs/nbnxm/grid.cpp b/src/gromacs/nbnxm/grid.cpp index d852ec4f08..b259daacdb 100644 --- a/src/gromacs/nbnxm/grid.cpp +++ b/src/gromacs/nbnxm/grid.cpp @@ -334,8 +334,16 @@ static void sort_atoms(int dim, /* As we can have rounding effect, we use > iso >= here */ if (relevantAtomsAreWithinGridBounds && (zi < 0 || (dd_zone == 0 && zi > n_per_h * c_sortGridRatio))) { - gmx_fatal(FARGS, "(int)((x[%d][%c]=%f - %f)*%f) = %d, not in 0 - %d*%d\n", a[i], - 'x' + dim, x[a[i]][dim], h0, invh, zi, n_per_h, c_sortGridRatio); + gmx_fatal(FARGS, + "(int)((x[%d][%c]=%f - %f)*%f) = %d, not in 0 - %d*%d\n", + a[i], + 'x' + dim, + x[a[i]][dim], + h0, + invh, + zi, + n_per_h, + c_sortGridRatio); } #endif if (zi < 0) @@ -717,9 +725,16 @@ static void print_bbsizes_simple(FILE* fp, const Grid& grid) / (dims.atomDensity * dims.cellSize[XX] * dims.cellSize[YY]) : 0.0); - fprintf(fp, "ns bb: grid %4.2f %4.2f %4.2f abs %4.2f %4.2f %4.2f rel %4.2f %4.2f %4.2f\n", - dims.cellSize[XX], dims.cellSize[YY], avgCellSizeZ, ba[XX], ba[YY], ba[ZZ], - ba[XX] * dims.invCellSize[XX], ba[YY] * dims.invCellSize[YY], + fprintf(fp, + "ns bb: grid %4.2f %4.2f %4.2f abs %4.2f %4.2f %4.2f rel %4.2f %4.2f %4.2f\n", + dims.cellSize[XX], + dims.cellSize[YY], + avgCellSizeZ, + ba[XX], + ba[YY], + ba[ZZ], + ba[XX] * dims.invCellSize[XX], + ba[YY] * dims.invCellSize[YY], dims.atomDensity > 0 ? ba[ZZ] / avgCellSizeZ : 0.0); } @@ -768,9 +783,14 @@ static void print_bbsizes_supersub(FILE* fp, const Grid& grid) * dims.cellSize[YY] * c_gpuNumClusterPerCellZ) : 0.0); - fprintf(fp, "ns bb: grid %4.2f %4.2f %4.2f abs %4.2f %4.2f %4.2f rel %4.2f %4.2f %4.2f\n", + fprintf(fp, + "ns bb: grid %4.2f %4.2f %4.2f abs %4.2f %4.2f %4.2f rel %4.2f %4.2f %4.2f\n", dims.cellSize[XX] / c_gpuNumClusterPerCellX, - dims.cellSize[YY] / c_gpuNumClusterPerCellY, avgClusterSizeZ, ba[XX], ba[YY], ba[ZZ], + dims.cellSize[YY] / c_gpuNumClusterPerCellY, + avgClusterSizeZ, + ba[XX], + ba[YY], + ba[ZZ], ba[XX] * c_gpuNumClusterPerCellX * dims.invCellSize[XX], ba[YY] * c_gpuNumClusterPerCellY * dims.invCellSize[YY], dims.atomDensity > 0 ? ba[ZZ] / avgClusterSizeZ : 0.0); @@ -876,7 +896,11 @@ void Grid::fillCell(GridSetData* gridSetData, * Then sort_cluster_on_flag will only set the flags and the sorting * will not affect the atom order. */ - sort_cluster_on_flag(geometry_.numAtomsICluster, atomStart, atomEnd, atinfo, atomIndices, + sort_cluster_on_flag(geometry_.numAtomsICluster, + atomStart, + atomEnd, + atinfo, + atomIndices, flags_.data() + atomToCluster(atomStart) - cellOffset_); } @@ -903,8 +927,13 @@ void Grid::fillCell(GridSetData* gridSetData, cells[atomIndices[at]] = at; } - copy_rvec_to_nbat_real(atomIndices.data() + atomStart, numAtoms, geometry_.numAtomsICluster, - as_rvec_array(x.data()), nbat->XFormat, nbat->x().data(), atomStart); + copy_rvec_to_nbat_real(atomIndices.data() + atomStart, + numAtoms, + geometry_.numAtomsICluster, + as_rvec_array(x.data()), + nbat->XFormat, + nbat->x().data(), + atomStart); if (nbat->XFormat == nbatX4) { @@ -917,7 +946,8 @@ void Grid::fillCell(GridSetData* gridSetData, { calc_bounding_box_x_x4_halves(numAtoms, nbat->x().data() + atom_to_x_index(atomStart), - bb_ptr, bbj_.data() + offset * 2); + bb_ptr, + bbj_.data() + offset * 2); } else #endif @@ -948,21 +978,25 @@ void Grid::fillCell(GridSetData* gridSetData, if (nbat->XFormat == nbatXYZQ) { GMX_ASSERT(bb_work_aligned != nullptr, "Must have valid aligned work structure"); - calc_bounding_box_xxxx_simd4(numAtoms, nbat->x().data() + atomStart * nbat->xstride, - bb_work_aligned, pbb_ptr); + calc_bounding_box_xxxx_simd4( + numAtoms, nbat->x().data() + atomStart * nbat->xstride, bb_work_aligned, pbb_ptr); } else # endif { - calc_bounding_box_xxxx(numAtoms, nbat->xstride, - nbat->x().data() + atomStart * nbat->xstride, pbb_ptr); + calc_bounding_box_xxxx( + numAtoms, nbat->xstride, nbat->x().data() + atomStart * nbat->xstride, pbb_ptr); } if (gmx_debug_at) { - fprintf(debug, "cell %4d bb %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\n", - atomToCluster(atomStart), pbb_ptr[0 * c_packedBoundingBoxesDimSize], - pbb_ptr[3 * c_packedBoundingBoxesDimSize], pbb_ptr[1 * c_packedBoundingBoxesDimSize], - pbb_ptr[4 * c_packedBoundingBoxesDimSize], pbb_ptr[2 * c_packedBoundingBoxesDimSize], + fprintf(debug, + "cell %4d bb %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\n", + atomToCluster(atomStart), + pbb_ptr[0 * c_packedBoundingBoxesDimSize], + pbb_ptr[3 * c_packedBoundingBoxesDimSize], + pbb_ptr[1 * c_packedBoundingBoxesDimSize], + pbb_ptr[4 * c_packedBoundingBoxesDimSize], + pbb_ptr[2 * c_packedBoundingBoxesDimSize], pbb_ptr[5 * c_packedBoundingBoxesDimSize]); } } @@ -978,9 +1012,15 @@ void Grid::fillCell(GridSetData* gridSetData, if (gmx_debug_at) { int bbo = atomToCluster(atomStart - cellOffset_ * geometry_.numAtomsPerCell); - fprintf(debug, "cell %4d bb %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\n", - atomToCluster(atomStart), bb_[bbo].lower.x, bb_[bbo].lower.y, bb_[bbo].lower.z, - bb_[bbo].upper.x, bb_[bbo].upper.y, bb_[bbo].upper.z); + fprintf(debug, + "cell %4d bb %5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\n", + atomToCluster(atomStart), + bb_[bbo].lower.x, + bb_[bbo].lower.y, + bb_[bbo].lower.z, + bb_[bbo].upper.x, + bb_[bbo].upper.y, + bb_[bbo].upper.z); } } } @@ -995,8 +1035,11 @@ void Grid::sortColumnsCpuGeometry(GridSetData* gridSetData, { if (debug) { - fprintf(debug, "cell_offset %d sorting columns %d - %d\n", cellOffset_, - *columnRange.begin(), *columnRange.end()); + fprintf(debug, + "cell_offset %d sorting columns %d - %d\n", + cellOffset_, + *columnRange.begin(), + *columnRange.end()); } const bool relevantAtomsAreWithinGridBounds = (dimensions_.maxAtomGroupRadius == 0); @@ -1011,9 +1054,17 @@ void Grid::sortColumnsCpuGeometry(GridSetData* gridSetData, const int atomOffset = firstAtomInColumn(cxy); /* Sort the atoms within each x,y column on z coordinate */ - sort_atoms(ZZ, FALSE, dd_zone, relevantAtomsAreWithinGridBounds, - gridSetData->atomIndices.data() + atomOffset, numAtoms, x, dimensions_.lowerCorner[ZZ], - 1.0 / dimensions_.gridSize[ZZ], numCellsZ * numAtomsPerCell, sort_work); + sort_atoms(ZZ, + FALSE, + dd_zone, + relevantAtomsAreWithinGridBounds, + gridSetData->atomIndices.data() + atomOffset, + numAtoms, + x, + dimensions_.lowerCorner[ZZ], + 1.0 / dimensions_.gridSize[ZZ], + numCellsZ * numAtomsPerCell, + sort_work); /* Fill the ncz cells in this column */ const int firstCell = firstCellInColumn(cxy); @@ -1062,8 +1113,11 @@ void Grid::sortColumnsGpuGeometry(GridSetData* gridSetData, if (debug) { - fprintf(debug, "cell_offset %d sorting columns %d - %d\n", cellOffset_, - *columnRange.begin(), *columnRange.end()); + fprintf(debug, + "cell_offset %d sorting columns %d - %d\n", + cellOffset_, + *columnRange.begin(), + *columnRange.end()); } const bool relevantAtomsAreWithinGridBounds = (dimensions_.maxAtomGroupRadius == 0); @@ -1090,9 +1144,17 @@ void Grid::sortColumnsGpuGeometry(GridSetData* gridSetData, const int atomOffset = firstAtomInColumn(cxy); /* Sort the atoms within each x,y column on z coordinate */ - sort_atoms(ZZ, FALSE, dd_zone, relevantAtomsAreWithinGridBounds, - atomIndices.data() + atomOffset, numAtomsInColumn, x, dimensions_.lowerCorner[ZZ], - 1.0 / dimensions_.gridSize[ZZ], numCellsInColumn * numAtomsPerCell, sort_work); + sort_atoms(ZZ, + FALSE, + dd_zone, + relevantAtomsAreWithinGridBounds, + atomIndices.data() + atomOffset, + numAtomsInColumn, + x, + dimensions_.lowerCorner[ZZ], + 1.0 / dimensions_.gridSize[ZZ], + numCellsInColumn * numAtomsPerCell, + sort_work); /* This loop goes over the cells and clusters along z at once */ for (int sub_z = 0; sub_z < numCellsInColumn * c_gpuNumClusterPerCellZ; sub_z++) @@ -1111,9 +1173,9 @@ void Grid::sortColumnsGpuGeometry(GridSetData* gridSetData, const int numAtoms = std::min(numAtomsPerCell, numAtomsInColumn - (atomOffsetZ - atomOffset)); - numClusters_[cell] = - std::min(c_gpuNumClusterPerCell, (numAtoms + geometry_.numAtomsICluster - 1) - / geometry_.numAtomsICluster); + numClusters_[cell] = std::min( + c_gpuNumClusterPerCell, + (numAtoms + geometry_.numAtomsICluster - 1) / geometry_.numAtomsICluster); /* Store the z-boundaries of the bounding box of the cell */ bbcz_[cell].lower = x[atomIndices[atomOffsetZ]][ZZ]; @@ -1123,10 +1185,17 @@ void Grid::sortColumnsGpuGeometry(GridSetData* gridSetData, if (c_gpuNumClusterPerCellY > 1) { /* Sort the atoms along y */ - sort_atoms(YY, (sub_z & 1) != 0, dd_zone, relevantAtomsAreWithinGridBounds, - atomIndices.data() + atomOffsetZ, numAtomsZ, x, + sort_atoms(YY, + (sub_z & 1) != 0, + dd_zone, + relevantAtomsAreWithinGridBounds, + atomIndices.data() + atomOffsetZ, + numAtomsZ, + x, dimensions_.lowerCorner[YY] + gridY * dimensions_.cellSize[YY], - dimensions_.invCellSize[YY], subdiv_z, sort_work); + dimensions_.invCellSize[YY], + subdiv_z, + sort_work); } for (int sub_y = 0; sub_y < c_gpuNumClusterPerCellY; sub_y++) @@ -1137,10 +1206,17 @@ void Grid::sortColumnsGpuGeometry(GridSetData* gridSetData, if (c_gpuNumClusterPerCellX > 1) { /* Sort the atoms along x */ - sort_atoms(XX, ((cz * c_gpuNumClusterPerCellY + sub_y) & 1) != 0, dd_zone, - relevantAtomsAreWithinGridBounds, atomIndices.data() + atomOffsetY, numAtomsY, - x, dimensions_.lowerCorner[XX] + gridX * dimensions_.cellSize[XX], - dimensions_.invCellSize[XX], subdiv_y, sort_work); + sort_atoms(XX, + ((cz * c_gpuNumClusterPerCellY + sub_y) & 1) != 0, + dd_zone, + relevantAtomsAreWithinGridBounds, + atomIndices.data() + atomOffsetY, + numAtomsY, + x, + dimensions_.lowerCorner[XX] + gridX * dimensions_.cellSize[XX], + dimensions_.invCellSize[XX], + subdiv_y, + sort_work); } for (int sub_x = 0; sub_x < c_gpuNumClusterPerCellX; sub_x++) @@ -1149,8 +1225,7 @@ void Grid::sortColumnsGpuGeometry(GridSetData* gridSetData, const int numAtomsX = std::min(subdiv_x, numAtomsInColumn - (atomOffsetX - atomOffset)); - fillCell(gridSetData, nbat, atomOffsetX, atomOffsetX + numAtomsX, atinfo, x, - bb_work_aligned); + fillCell(gridSetData, nbat, atomOffsetX, atomOffsetX + numAtomsX, atinfo, x, bb_work_aligned); } } } @@ -1218,8 +1293,15 @@ void Grid::calcColumnIndices(const Grid::Dimensions& gridDims, gmx_fatal(FARGS, "grid cell cx %d cy %d out of range (max %d %d)\n" "atom %f %f %f, grid->c0 %f %f", - cx, cy, gridDims.numCells[XX], gridDims.numCells[YY], x[i][XX], - x[i][YY], x[i][ZZ], gridDims.lowerCorner[XX], gridDims.lowerCorner[YY]); + cx, + cy, + gridDims.numCells[XX], + gridDims.numCells[YY], + x[i][XX], + x[i][YY], + x[i][ZZ], + gridDims.lowerCorner[XX], + gridDims.lowerCorner[YY]); } #endif /* Take care of potential rouding issues */ @@ -1340,9 +1422,15 @@ void Grid::setCellIndices(int ddZone, if (debug) { - fprintf(debug, "ns na_sc %d na_c %d super-cells: %d x %d y %d z %.1f maxz %d\n", - numAtomsPerCell, geometry_.numAtomsICluster, numCellsTotal_, dimensions_.numCells[XX], - dimensions_.numCells[YY], numCellsTotal_ / (static_cast(numColumns())), ncz_max); + fprintf(debug, + "ns na_sc %d na_c %d super-cells: %d x %d y %d z %.1f maxz %d\n", + numAtomsPerCell, + geometry_.numAtomsICluster, + numCellsTotal_, + dimensions_.numCells[XX], + dimensions_.numCells[YY], + numCellsTotal_ / (static_cast(numColumns())), + ncz_max); if (gmx_debug_at) { int i = 0; @@ -1402,13 +1490,13 @@ void Grid::setCellIndices(int ddZone, ((thread + 1) * numColumns()) / nthread); if (geometry_.isSimple) { - sortColumnsCpuGeometry(gridSetData, ddZone, atinfo, x, nbat, columnRange, - gridWork[thread].sortBuffer); + sortColumnsCpuGeometry( + gridSetData, ddZone, atinfo, x, nbat, columnRange, gridWork[thread].sortBuffer); } else { - sortColumnsGpuGeometry(gridSetData, ddZone, atinfo, x, nbat, columnRange, - gridWork[thread].sortBuffer); + sortColumnsGpuGeometry( + gridSetData, ddZone, atinfo, x, nbat, columnRange, gridWork[thread].sortBuffer); } } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR @@ -1436,7 +1524,9 @@ void Grid::setCellIndices(int ddZone, } else { - fprintf(debug, "ns non-zero sub-cells: %d average atoms %.2f\n", numClustersTotal_, + fprintf(debug, + "ns non-zero sub-cells: %d average atoms %.2f\n", + numClustersTotal_, atomRange.size() / static_cast(numClustersTotal_)); print_bbsizes_supersub(debug, *this); diff --git a/src/gromacs/nbnxm/gridset.cpp b/src/gromacs/nbnxm/gridset.cpp index a2e83ddc6a..95078bcc62 100644 --- a/src/gromacs/nbnxm/gridset.cpp +++ b/src/gromacs/nbnxm/gridset.cpp @@ -193,8 +193,8 @@ void GridSet::putOnGrid(const matrix box, const int ddZone = (domainSetup_.doTestParticleInsertion ? 0 : gridIndex); // grid data used in GPU transfers inherits the gridset pinning policy auto pinPolicy = gridSetData_.cells.get_allocator().pinningPolicy(); - grid.setDimensions(ddZone, n - numAtomsMoved, lowerCorner, upperCorner, atomDensity, - maxAtomGroupRadius, haveFep_, pinPolicy); + grid.setDimensions( + ddZone, n - numAtomsMoved, lowerCorner, upperCorner, atomDensity, maxAtomGroupRadius, haveFep_, pinPolicy); for (GridWork& work : gridWork_) { @@ -212,15 +212,23 @@ void GridSet::putOnGrid(const matrix box, { try { - Grid::calcColumnIndices(grid.dimensions(), updateGroupsCog, atomRange, x, ddZone, move, thread, - nthread, gridSetData_.cells, gridWork_[thread].numAtomsPerColumn); + Grid::calcColumnIndices(grid.dimensions(), + updateGroupsCog, + atomRange, + x, + ddZone, + move, + thread, + nthread, + gridSetData_.cells, + gridWork_[thread].numAtomsPerColumn); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR } /* Copy the already computed cell indices to the grid and sort, when needed */ - grid.setCellIndices(ddZone, cellOffset, &gridSetData_, gridWork_, atomRange, atomInfo.data(), x, - numAtomsMoved, nbat); + grid.setCellIndices( + ddZone, cellOffset, &gridSetData_, gridWork_, atomRange, atomInfo.data(), x, numAtomsMoved, nbat); if (gridIndex == 0) { diff --git a/src/gromacs/nbnxm/kerneldispatch.cpp b/src/gromacs/nbnxm/kerneldispatch.cpp index aaf9bd863e..5b4c5d7906 100644 --- a/src/gromacs/nbnxm/kerneldispatch.cpp +++ b/src/gromacs/nbnxm/kerneldispatch.cpp @@ -400,19 +400,22 @@ static void accountFlops(t_nrnb* nrnb, if (ic.vdw_modifier == eintmodFORCESWITCH) { /* We add up the switch cost separately */ - inc_nrnb(nrnb, eNR_NBNXN_ADD_LJ_FSW + (stepWork.computeEnergy ? 1 : 0), + inc_nrnb(nrnb, + eNR_NBNXN_ADD_LJ_FSW + (stepWork.computeEnergy ? 1 : 0), pairlistSet.natpair_ljq_ + pairlistSet.natpair_lj_); } if (ic.vdw_modifier == eintmodPOTSWITCH) { /* We add up the switch cost separately */ - inc_nrnb(nrnb, eNR_NBNXN_ADD_LJ_PSW + (stepWork.computeEnergy ? 1 : 0), + inc_nrnb(nrnb, + eNR_NBNXN_ADD_LJ_PSW + (stepWork.computeEnergy ? 1 : 0), pairlistSet.natpair_ljq_ + pairlistSet.natpair_lj_); } if (ic.vdwtype == evdwPME) { /* We add up the LJ Ewald cost separately */ - inc_nrnb(nrnb, eNR_NBNXN_ADD_LJ_EWALD + (stepWork.computeEnergy ? 1 : 0), + inc_nrnb(nrnb, + eNR_NBNXN_ADD_LJ_EWALD + (stepWork.computeEnergy ? 1 : 0), pairlistSet.natpair_ljq_ + pairlistSet.natpair_lj_); } } @@ -432,8 +435,14 @@ void nonbonded_verlet_t::dispatchNonbondedKernel(gmx::InteractionLocality iLoc case Nbnxm::KernelType::Cpu4x4_PlainC: case Nbnxm::KernelType::Cpu4xN_Simd_4xN: case Nbnxm::KernelType::Cpu4xN_Simd_2xNN: - nbnxn_kernel_cpu(pairlistSet, kernelSetup(), nbat.get(), ic, fr.shift_vec, stepWork, - clearF, enerd->grpp.ener[egCOULSR].data(), + nbnxn_kernel_cpu(pairlistSet, + kernelSetup(), + nbat.get(), + ic, + fr.shift_vec, + stepWork, + clearF, + enerd->grpp.ener[egCOULSR].data(), fr.bBHAM ? enerd->grpp.ener[egBHAMSR].data() : enerd->grpp.ener[egLJSR].data(), wcycle_); break; @@ -444,8 +453,15 @@ void nonbonded_verlet_t::dispatchNonbondedKernel(gmx::InteractionLocality iLoc case Nbnxm::KernelType::Cpu8x8x8_PlainC: nbnxn_kernel_gpu_ref( - pairlistSet.gpuList(), nbat.get(), &ic, fr.shift_vec, stepWork, clearF, - nbat->out[0].f, nbat->out[0].fshift.data(), enerd->grpp.ener[egCOULSR].data(), + pairlistSet.gpuList(), + nbat.get(), + &ic, + fr.shift_vec, + stepWork, + clearF, + nbat->out[0].f, + nbat->out[0].fshift.data(), + enerd->grpp.ener[egCOULSR].data(), fr.bBHAM ? enerd->grpp.ener[egBHAMSR].data() : enerd->grpp.ener[egLJSR].data()); break; @@ -509,8 +525,8 @@ void nonbonded_verlet_t::dispatchFreeEnergyKernel(gmx::InteractionLocality iLo { try { - gmx_nb_free_energy_kernel(nbl_fep[th].get(), x, forceWithShiftForces, fr, &mdatoms, - &kernel_data, nrnb); + gmx_nb_free_energy_kernel( + nbl_fep[th].get(), x, forceWithShiftForces, fr, &mdatoms, &kernel_data, nrnb); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR } @@ -552,15 +568,15 @@ void nonbonded_verlet_t::dispatchFreeEnergyKernel(gmx::InteractionLocality iLo { try { - gmx_nb_free_energy_kernel(nbl_fep[th].get(), x, forceWithShiftForces, fr, - &mdatoms, &kernel_data, nrnb); + gmx_nb_free_energy_kernel( + nbl_fep[th].get(), x, forceWithShiftForces, fr, &mdatoms, &kernel_data, nrnb); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR } sum_epot(enerd->foreign_grpp, enerd->foreign_term); - enerd->foreignLambdaTerms.accumulate(i, enerd->foreign_term[F_EPOT], - dvdl_nb[efptVDW] + dvdl_nb[efptCOUL]); + enerd->foreignLambdaTerms.accumulate( + i, enerd->foreign_term[F_EPOT], dvdl_nb[efptVDW] + dvdl_nb[efptCOUL]); } } wallcycle_sub_stop(wcycle_, ewcsNONBONDED_FEP); diff --git a/src/gromacs/nbnxm/kernels_reference/kernel_gpu_ref.cpp b/src/gromacs/nbnxm/kernels_reference/kernel_gpu_ref.cpp index 0b25a95da8..bee2cf12ac 100644 --- a/src/gromacs/nbnxm/kernels_reference/kernel_gpu_ref.cpp +++ b/src/gromacs/nbnxm/kernels_reference/kernel_gpu_ref.cpp @@ -105,7 +105,8 @@ void nbnxn_kernel_gpu_ref(const NbnxnPairlistGpu* nbl, gmx_fatal(FARGS, "The neighborlist cluster size in the GPU reference kernel is %d, expected it to " "be %d", - nbl->na_ci, c_clSize); + nbl->na_ci, + c_clSize); } if (clearF == enbvClearFYes) @@ -366,14 +367,20 @@ void nbnxn_kernel_gpu_ref(const NbnxnPairlistGpu* nbl, if (debug) { - fprintf(debug, "number of half %dx%d atom pairs: %d after pruning: %d fraction %4.2f\n", - nbl->na_ci, nbl->na_ci, nhwu, nhwu_pruned, nhwu_pruned / static_cast(nhwu)); - fprintf(debug, "generic kernel pair interactions: %d\n", - nhwu * nbl->na_ci / 2 * nbl->na_ci); - fprintf(debug, "generic kernel post-prune pair interactions: %d\n", + fprintf(debug, + "number of half %dx%d atom pairs: %d after pruning: %d fraction %4.2f\n", + nbl->na_ci, + nbl->na_ci, + nhwu, + nhwu_pruned, + nhwu_pruned / static_cast(nhwu)); + fprintf(debug, "generic kernel pair interactions: %d\n", nhwu * nbl->na_ci / 2 * nbl->na_ci); + fprintf(debug, + "generic kernel post-prune pair interactions: %d\n", nhwu_pruned * nbl->na_ci / 2 * nbl->na_ci); fprintf(debug, "generic kernel non-zero pair interactions: %d\n", npair_tot); - fprintf(debug, "ratio non-zero/post-prune pair interactions: %4.2f\n", + fprintf(debug, + "ratio non-zero/post-prune pair interactions: %4.2f\n", npair_tot / static_cast(nhwu_pruned * gmx::exactDiv(nbl->na_ci, 2) * nbl->na_ci)); } } diff --git a/src/gromacs/nbnxm/kernels_reference/kernel_ref.h b/src/gromacs/nbnxm/kernels_reference/kernel_ref.h index 242536c99f..021cb917e0 100644 --- a/src/gromacs/nbnxm/kernels_reference/kernel_ref.h +++ b/src/gromacs/nbnxm/kernels_reference/kernel_ref.h @@ -108,68 +108,116 @@ nbk_func_ener nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombLB_VgrpF_ref; */ //! \{ static p_nbk_func_noener nbnxn_kernel_noener_ref[coulktNR][vdwktNR_ref] = { - { nbnxn_kernel_ElecRF_VdwLJ_F_ref, nbnxn_kernel_ElecRF_VdwLJ_F_ref, nbnxn_kernel_ElecRF_VdwLJ_F_ref, - nbnxn_kernel_ElecRF_VdwLJFsw_F_ref, nbnxn_kernel_ElecRF_VdwLJPsw_F_ref, - nbnxn_kernel_ElecRF_VdwLJEwCombGeom_F_ref, nbnxn_kernel_ElecRF_VdwLJEwCombLB_F_ref }, - { nbnxn_kernel_ElecQSTab_VdwLJ_F_ref, nbnxn_kernel_ElecQSTab_VdwLJ_F_ref, nbnxn_kernel_ElecQSTab_VdwLJ_F_ref, - nbnxn_kernel_ElecQSTab_VdwLJFsw_F_ref, nbnxn_kernel_ElecQSTab_VdwLJPsw_F_ref, - nbnxn_kernel_ElecQSTab_VdwLJEwCombGeom_F_ref, nbnxn_kernel_ElecQSTab_VdwLJEwCombLB_F_ref }, - { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_F_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_F_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_F_ref, + { nbnxn_kernel_ElecRF_VdwLJ_F_ref, + nbnxn_kernel_ElecRF_VdwLJ_F_ref, + nbnxn_kernel_ElecRF_VdwLJ_F_ref, + nbnxn_kernel_ElecRF_VdwLJFsw_F_ref, + nbnxn_kernel_ElecRF_VdwLJPsw_F_ref, + nbnxn_kernel_ElecRF_VdwLJEwCombGeom_F_ref, + nbnxn_kernel_ElecRF_VdwLJEwCombLB_F_ref }, + { nbnxn_kernel_ElecQSTab_VdwLJ_F_ref, + nbnxn_kernel_ElecQSTab_VdwLJ_F_ref, + nbnxn_kernel_ElecQSTab_VdwLJ_F_ref, + nbnxn_kernel_ElecQSTab_VdwLJFsw_F_ref, + nbnxn_kernel_ElecQSTab_VdwLJPsw_F_ref, + nbnxn_kernel_ElecQSTab_VdwLJEwCombGeom_F_ref, + nbnxn_kernel_ElecQSTab_VdwLJEwCombLB_F_ref }, + { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_F_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombLB_F_ref }, - { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_F_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_F_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_F_ref, + { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_F_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombLB_F_ref }, - { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_F_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_F_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_F_ref, + { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_F_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_F_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombLB_F_ref } }; static p_nbk_func_ener nbnxn_kernel_ener_ref[coulktNR][vdwktNR_ref] = { - { nbnxn_kernel_ElecRF_VdwLJ_VF_ref, nbnxn_kernel_ElecRF_VdwLJ_VF_ref, nbnxn_kernel_ElecRF_VdwLJ_VF_ref, - nbnxn_kernel_ElecRF_VdwLJFsw_VF_ref, nbnxn_kernel_ElecRF_VdwLJPsw_VF_ref, - nbnxn_kernel_ElecRF_VdwLJEwCombGeom_VF_ref, nbnxn_kernel_ElecRF_VdwLJEwCombLB_VF_ref }, - { nbnxn_kernel_ElecQSTab_VdwLJ_VF_ref, nbnxn_kernel_ElecQSTab_VdwLJ_VF_ref, - nbnxn_kernel_ElecQSTab_VdwLJ_VF_ref, nbnxn_kernel_ElecQSTab_VdwLJFsw_VF_ref, - nbnxn_kernel_ElecQSTab_VdwLJPsw_VF_ref, nbnxn_kernel_ElecQSTab_VdwLJEwCombGeom_VF_ref, + { nbnxn_kernel_ElecRF_VdwLJ_VF_ref, + nbnxn_kernel_ElecRF_VdwLJ_VF_ref, + nbnxn_kernel_ElecRF_VdwLJ_VF_ref, + nbnxn_kernel_ElecRF_VdwLJFsw_VF_ref, + nbnxn_kernel_ElecRF_VdwLJPsw_VF_ref, + nbnxn_kernel_ElecRF_VdwLJEwCombGeom_VF_ref, + nbnxn_kernel_ElecRF_VdwLJEwCombLB_VF_ref }, + { nbnxn_kernel_ElecQSTab_VdwLJ_VF_ref, + nbnxn_kernel_ElecQSTab_VdwLJ_VF_ref, + nbnxn_kernel_ElecQSTab_VdwLJ_VF_ref, + nbnxn_kernel_ElecQSTab_VdwLJFsw_VF_ref, + nbnxn_kernel_ElecQSTab_VdwLJPsw_VF_ref, + nbnxn_kernel_ElecQSTab_VdwLJEwCombGeom_VF_ref, nbnxn_kernel_ElecQSTab_VdwLJEwCombLB_VF_ref }, - { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_VF_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_VF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_VF_ref, + { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_VF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombLB_VF_ref }, - { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_VF_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_VF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_VF_ref, + { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_VF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombLB_VF_ref }, - { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_VF_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_VF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_VF_ref, + { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_VF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_VF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombLB_VF_ref } }; static p_nbk_func_ener nbnxn_kernel_energrp_ref[coulktNR][vdwktNR_ref] = { - { nbnxn_kernel_ElecRF_VdwLJ_VgrpF_ref, nbnxn_kernel_ElecRF_VdwLJ_VgrpF_ref, - nbnxn_kernel_ElecRF_VdwLJ_VgrpF_ref, nbnxn_kernel_ElecRF_VdwLJFsw_VgrpF_ref, - nbnxn_kernel_ElecRF_VdwLJPsw_VgrpF_ref, nbnxn_kernel_ElecRF_VdwLJEwCombGeom_VgrpF_ref, + { nbnxn_kernel_ElecRF_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecRF_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecRF_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecRF_VdwLJFsw_VgrpF_ref, + nbnxn_kernel_ElecRF_VdwLJPsw_VgrpF_ref, + nbnxn_kernel_ElecRF_VdwLJEwCombGeom_VgrpF_ref, nbnxn_kernel_ElecRF_VdwLJEwCombLB_VgrpF_ref }, - { nbnxn_kernel_ElecQSTab_VdwLJ_VgrpF_ref, nbnxn_kernel_ElecQSTab_VdwLJ_VgrpF_ref, - nbnxn_kernel_ElecQSTab_VdwLJ_VgrpF_ref, nbnxn_kernel_ElecQSTab_VdwLJFsw_VgrpF_ref, - nbnxn_kernel_ElecQSTab_VdwLJPsw_VgrpF_ref, nbnxn_kernel_ElecQSTab_VdwLJEwCombGeom_VgrpF_ref, + { nbnxn_kernel_ElecQSTab_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecQSTab_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecQSTab_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecQSTab_VdwLJFsw_VgrpF_ref, + nbnxn_kernel_ElecQSTab_VdwLJPsw_VgrpF_ref, + nbnxn_kernel_ElecQSTab_VdwLJEwCombGeom_VgrpF_ref, nbnxn_kernel_ElecQSTab_VdwLJEwCombLB_VgrpF_ref }, - { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_VgrpF_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_VgrpF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_VgrpF_ref, + { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_VgrpF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombLB_VgrpF_ref }, - { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_VgrpF_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_VgrpF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_VgrpF_ref, + { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_VgrpF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombLB_VgrpF_ref }, - { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_VgrpF_ref, - nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_VgrpF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_VgrpF_ref, + { nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJ_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJFsw_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJPsw_VgrpF_ref, + nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombGeom_VgrpF_ref, nbnxn_kernel_ElecQSTabTwinCut_VdwLJEwCombLB_VgrpF_ref } }; //! \} diff --git a/src/gromacs/nbnxm/kernels_simd_2xmm/kernel_common.h b/src/gromacs/nbnxm/kernels_simd_2xmm/kernel_common.h index 6f6a2400b5..34160ab8c9 100644 --- a/src/gromacs/nbnxm/kernels_simd_2xmm/kernel_common.h +++ b/src/gromacs/nbnxm/kernels_simd_2xmm/kernel_common.h @@ -79,7 +79,8 @@ static inline void add_ener_grp_halves(gmx::SimdReal e_S, real* v0, real* v1, co for (int jj = 0; jj < (UNROLLJ / 2); jj++) { incrDualHsimd(v0 + offset_jj[jj] + jj * GMX_SIMD_REAL_WIDTH / 2, - v1 + offset_jj[jj] + jj * GMX_SIMD_REAL_WIDTH / 2, e_S); + v1 + offset_jj[jj] + jj * GMX_SIMD_REAL_WIDTH / 2, + e_S); } } #endif diff --git a/src/gromacs/nbnxm/kernels_simd_2xmm/kernel_inner.h b/src/gromacs/nbnxm/kernels_simd_2xmm/kernel_inner.h index 458c23b1b8..813e4f64ed 100644 --- a/src/gromacs/nbnxm/kernels_simd_2xmm/kernel_inner.h +++ b/src/gromacs/nbnxm/kernels_simd_2xmm/kernel_inner.h @@ -219,8 +219,8 @@ ajz = ajy + STRIDE; #ifdef CHECK_EXCLS - gmx_load_simd_2xnn_interactions(static_cast(l_cj[cjind].excl), filter_S0, filter_S2, - &interact_S0, &interact_S2); + gmx_load_simd_2xnn_interactions( + static_cast(l_cj[cjind].excl), filter_S0, filter_S2, &interact_S0, &interact_S2); #endif /* CHECK_EXCLS */ /* load j atom coordinates */ @@ -634,11 +634,13 @@ c6_S2 * fma(sixth_S, rinvsix_S2, v_fswitch_pr(rsw_S2, rsw2_S2, p6_6cpot_S, p6_vc3_S, p6_vc4_S)); # endif SimdReal VLJ12_S0 = c12_S0 - * fma(twelveth_S, rinvsix_S0 * rinvsix_S0, + * fma(twelveth_S, + rinvsix_S0 * rinvsix_S0, v_fswitch_pr(rsw_S0, rsw2_S0, p12_12cpot_S, p12_vc3_S, p12_vc4_S)); # ifndef HALF_LJ SimdReal VLJ12_S2 = c12_S2 - * fma(twelveth_S, rinvsix_S2 * rinvsix_S2, + * fma(twelveth_S, + rinvsix_S2 * rinvsix_S2, v_fswitch_pr(rsw_S2, rsw2_S2, p12_12cpot_S, p12_vc3_S, p12_vc4_S)); # endif # undef v_fswitch_pr @@ -756,10 +758,12 @@ * r^-6*cexp*(1 + cr2 + cr2^2/2 + cr2^3/6) = cexp*(r^-6*poly + c^6/6) */ frLJ_S0 = fma(c6grid_S0, - fnma(expmcr2_S0, fma(rinvsix_nm_S0, poly_S0, lje_c6_6_S), rinvsix_nm_S0), frLJ_S0); + fnma(expmcr2_S0, fma(rinvsix_nm_S0, poly_S0, lje_c6_6_S), rinvsix_nm_S0), + frLJ_S0); # ifndef HALF_LJ frLJ_S2 = fma(c6grid_S2, - fnma(expmcr2_S2, fma(rinvsix_nm_S2, poly_S2, lje_c6_6_S), rinvsix_nm_S2), frLJ_S2); + fnma(expmcr2_S2, fma(rinvsix_nm_S2, poly_S2, lje_c6_6_S), rinvsix_nm_S2), + frLJ_S2); # endif # ifdef CALC_ENERGIES @@ -776,10 +780,12 @@ # endif VLJ_S0 = fma(sixth_S * c6grid_S0, - fma(rinvsix_nm_S0, fnma(expmcr2_S0, poly_S0, one_S), sh_mask_S0), VLJ_S0); + fma(rinvsix_nm_S0, fnma(expmcr2_S0, poly_S0, one_S), sh_mask_S0), + VLJ_S0); # ifndef HALF_LJ VLJ_S2 = fma(sixth_S * c6grid_S2, - fma(rinvsix_nm_S2, fnma(expmcr2_S2, poly_S2, one_S), sh_mask_S2), VLJ_S2); + fma(rinvsix_nm_S2, fnma(expmcr2_S2, poly_S2, one_S), sh_mask_S2), + VLJ_S2); # endif # endif /* CALC_ENERGIES */ } diff --git a/src/gromacs/nbnxm/kernels_simd_4xm/kernel_inner.h b/src/gromacs/nbnxm/kernels_simd_4xm/kernel_inner.h index 01646f3b04..fed076db50 100644 --- a/src/gromacs/nbnxm/kernels_simd_4xm/kernel_inner.h +++ b/src/gromacs/nbnxm/kernels_simd_4xm/kernel_inner.h @@ -269,9 +269,16 @@ ajz = ajy + STRIDE; # ifdef CHECK_EXCLS - gmx_load_simd_4xn_interactions(static_cast(l_cj[cjind].excl), filter_S0, filter_S1, - filter_S2, filter_S3, nbat->simdMasks.interaction_array.data(), - &interact_S0, &interact_S1, &interact_S2, &interact_S3); + gmx_load_simd_4xn_interactions(static_cast(l_cj[cjind].excl), + filter_S0, + filter_S1, + filter_S2, + filter_S3, + nbat->simdMasks.interaction_array.data(), + &interact_S0, + &interact_S1, + &interact_S2, + &interact_S3); # endif /* CHECK_EXCLS */ /* load j atom coordinates */ @@ -853,17 +860,21 @@ c6_S3 * fma(sixth_S, rinvsix_S3, v_fswitch_r(rsw_S3, rsw2_S3, p6_6cpot_S, p6_vc3_S, p6_vc4_S)); # endif SimdReal VLJ12_S0 = c12_S0 - * fma(twelveth_S, rinvsix_S0 * rinvsix_S0, + * fma(twelveth_S, + rinvsix_S0 * rinvsix_S0, v_fswitch_r(rsw_S0, rsw2_S0, p12_12cpot_S, p12_vc3_S, p12_vc4_S)); SimdReal VLJ12_S1 = c12_S1 - * fma(twelveth_S, rinvsix_S1 * rinvsix_S1, + * fma(twelveth_S, + rinvsix_S1 * rinvsix_S1, v_fswitch_r(rsw_S1, rsw2_S1, p12_12cpot_S, p12_vc3_S, p12_vc4_S)); # ifndef HALF_LJ SimdReal VLJ12_S2 = c12_S2 - * fma(twelveth_S, rinvsix_S2 * rinvsix_S2, + * fma(twelveth_S, + rinvsix_S2 * rinvsix_S2, v_fswitch_r(rsw_S2, rsw2_S2, p12_12cpot_S, p12_vc3_S, p12_vc4_S)); SimdReal VLJ12_S3 = c12_S3 - * fma(twelveth_S, rinvsix_S3 * rinvsix_S3, + * fma(twelveth_S, + rinvsix_S3 * rinvsix_S3, v_fswitch_r(rsw_S3, rsw2_S3, p12_12cpot_S, p12_vc3_S, p12_vc4_S)); # endif # undef v_fswitch_r @@ -1013,14 +1024,18 @@ * r^-6*cexp*(1 + cr2 + cr2^2/2 + cr2^3/6) = cexp*(r^-6*poly + c^6/6) */ frLJ_S0 = fma(c6grid_S0, - fnma(expmcr2_S0, fma(rinvsix_nm_S0, poly_S0, lje_c6_6_S), rinvsix_nm_S0), frLJ_S0); + fnma(expmcr2_S0, fma(rinvsix_nm_S0, poly_S0, lje_c6_6_S), rinvsix_nm_S0), + frLJ_S0); frLJ_S1 = fma(c6grid_S1, - fnma(expmcr2_S1, fma(rinvsix_nm_S1, poly_S1, lje_c6_6_S), rinvsix_nm_S1), frLJ_S1); + fnma(expmcr2_S1, fma(rinvsix_nm_S1, poly_S1, lje_c6_6_S), rinvsix_nm_S1), + frLJ_S1); # ifndef HALF_LJ frLJ_S2 = fma(c6grid_S2, - fnma(expmcr2_S2, fma(rinvsix_nm_S2, poly_S2, lje_c6_6_S), rinvsix_nm_S2), frLJ_S2); + fnma(expmcr2_S2, fma(rinvsix_nm_S2, poly_S2, lje_c6_6_S), rinvsix_nm_S2), + frLJ_S2); frLJ_S3 = fma(c6grid_S3, - fnma(expmcr2_S3, fma(rinvsix_nm_S3, poly_S3, lje_c6_6_S), rinvsix_nm_S3), frLJ_S3); + fnma(expmcr2_S3, fma(rinvsix_nm_S3, poly_S3, lje_c6_6_S), rinvsix_nm_S3), + frLJ_S3); # endif # ifdef CALC_ENERGIES @@ -1041,14 +1056,18 @@ # endif VLJ_S0 = fma(sixth_S * c6grid_S0, - fma(rinvsix_nm_S0, fnma(expmcr2_S0, poly_S0, one_S), sh_mask_S0), VLJ_S0); + fma(rinvsix_nm_S0, fnma(expmcr2_S0, poly_S0, one_S), sh_mask_S0), + VLJ_S0); VLJ_S1 = fma(sixth_S * c6grid_S1, - fma(rinvsix_nm_S1, fnma(expmcr2_S1, poly_S1, one_S), sh_mask_S1), VLJ_S1); + fma(rinvsix_nm_S1, fnma(expmcr2_S1, poly_S1, one_S), sh_mask_S1), + VLJ_S1); # ifndef HALF_LJ VLJ_S2 = fma(sixth_S * c6grid_S2, - fma(rinvsix_nm_S2, fnma(expmcr2_S2, poly_S2, one_S), sh_mask_S2), VLJ_S2); + fma(rinvsix_nm_S2, fnma(expmcr2_S2, poly_S2, one_S), sh_mask_S2), + VLJ_S2); VLJ_S3 = fma(sixth_S * c6grid_S3, - fma(rinvsix_nm_S3, fnma(expmcr2_S3, poly_S3, one_S), sh_mask_S3), VLJ_S3); + fma(rinvsix_nm_S3, fnma(expmcr2_S3, poly_S3, one_S), sh_mask_S3), + VLJ_S3); # endif # endif /* CALC_ENERGIES */ } diff --git a/src/gromacs/nbnxm/nbnxm.cpp b/src/gromacs/nbnxm/nbnxm.cpp index 76e2eead9f..33d50502c7 100644 --- a/src/gromacs/nbnxm/nbnxm.cpp +++ b/src/gromacs/nbnxm/nbnxm.cpp @@ -68,8 +68,17 @@ void nbnxn_put_on_grid(nonbonded_verlet_t* nb_verlet, int numAtomsMoved, const int* move) { - nb_verlet->pairSearch_->putOnGrid(box, gridIndex, lowerCorner, upperCorner, updateGroupsCog, - atomRange, atomDensity, atomInfo, x, numAtomsMoved, move, + nb_verlet->pairSearch_->putOnGrid(box, + gridIndex, + lowerCorner, + upperCorner, + updateGroupsCog, + atomRange, + atomDensity, + atomInfo, + x, + numAtomsMoved, + move, nb_verlet->nbat.get()); } @@ -88,8 +97,17 @@ void nbnxn_put_on_grid_nonlocal(nonbonded_verlet_t* nbv, c1[d] = zones->size[zone].bb_x1[d]; } - nbnxn_put_on_grid(nbv, nullptr, zone, c0, c1, nullptr, - { zones->cg_range[zone], zones->cg_range[zone + 1] }, -1, atomInfo, x, 0, + nbnxn_put_on_grid(nbv, + nullptr, + zone, + c0, + c1, + nullptr, + { zones->cg_range[zone], zones->cg_range[zone + 1] }, + -1, + atomInfo, + x, + 0, nullptr); } } @@ -133,8 +151,8 @@ void nonbonded_verlet_t::convertCoordinates(const gmx::AtomLocality local wallcycle_start(wcycle_, ewcNB_XF_BUF_OPS); wallcycle_sub_start(wcycle_, ewcsNB_X_BUF_OPS); - nbnxn_atomdata_copy_x_to_nbat_x(pairSearch_->gridSet(), locality, fillLocal, - as_rvec_array(coordinates.data()), nbat.get()); + nbnxn_atomdata_copy_x_to_nbat_x( + pairSearch_->gridSet(), locality, fillLocal, as_rvec_array(coordinates.data()), nbat.get()); wallcycle_sub_stop(wcycle_, ewcsNB_X_BUF_OPS); wallcycle_stop(wcycle_, ewcNB_XF_BUF_OPS); diff --git a/src/gromacs/nbnxm/nbnxm_geometry.h b/src/gromacs/nbnxm/nbnxm_geometry.h index 0df65f2bc5..0335909996 100644 --- a/src/gromacs/nbnxm/nbnxm_geometry.h +++ b/src/gromacs/nbnxm/nbnxm_geometry.h @@ -78,19 +78,22 @@ namespace Nbnxm /*! \brief The nbnxn i-cluster size in atoms for each nbnxn kernel type */ static constexpr gmx::EnumerationArray IClusterSizePerKernelType = { - { 0, c_nbnxnCpuIClusterSize, c_nbnxnCpuIClusterSize, c_nbnxnCpuIClusterSize, - c_nbnxnGpuClusterSize, c_nbnxnGpuClusterSize } + { 0, c_nbnxnCpuIClusterSize, c_nbnxnCpuIClusterSize, c_nbnxnCpuIClusterSize, c_nbnxnGpuClusterSize, c_nbnxnGpuClusterSize } }; /*! \brief The nbnxn j-cluster size in atoms for each nbnxn kernel type */ static constexpr gmx::EnumerationArray JClusterSizePerKernelType = { - { 0, c_nbnxnCpuIClusterSize, + { 0, + c_nbnxnCpuIClusterSize, #if GMX_SIMD - GMX_SIMD_REAL_WIDTH, GMX_SIMD_REAL_WIDTH / 2, + GMX_SIMD_REAL_WIDTH, + GMX_SIMD_REAL_WIDTH / 2, #else - 0, 0, + 0, + 0, #endif - c_nbnxnGpuClusterSize, c_nbnxnGpuClusterSize / 2 } + c_nbnxnGpuClusterSize, + c_nbnxnGpuClusterSize / 2 } }; /*! \brief Returns whether the pair-list corresponding to nb_kernel_type is simple */ diff --git a/src/gromacs/nbnxm/nbnxm_gpu_data_mgmt.cpp b/src/gromacs/nbnxm/nbnxm_gpu_data_mgmt.cpp index e98651f1ad..ad7c2c8017 100644 --- a/src/gromacs/nbnxm/nbnxm_gpu_data_mgmt.cpp +++ b/src/gromacs/nbnxm/nbnxm_gpu_data_mgmt.cpp @@ -79,8 +79,8 @@ void init_ewald_coulomb_force_table(const EwaldCorrectionTables& tables, } nbp->coulomb_tab_scale = tables.scale; - initParamLookupTable(&nbp->coulomb_tab, &nbp->coulomb_tab_texobj, tables.tableF.data(), - tables.tableF.size(), deviceContext); + initParamLookupTable( + &nbp->coulomb_tab, &nbp->coulomb_tab_texobj, tables.tableF.data(), tables.tableF.size(), deviceContext); } void inline printEnvironmentVariableDeprecationMessage(bool isEnvironmentVariableSet, @@ -91,7 +91,8 @@ void inline printEnvironmentVariableDeprecationMessage(bool isEnvi fprintf(stderr, "Environment variables GMX_CUDA_%s and GMX_OCL_%s are deprecated and will be\n" "removed in release 2022, please use GMX_GPU_%s instead.", - environmentVariableSuffix.c_str(), environmentVariableSuffix.c_str(), + environmentVariableSuffix.c_str(), + environmentVariableSuffix.c_str(), environmentVariableSuffix.c_str()); } } @@ -266,8 +267,10 @@ void gpu_init_pairlist(NbnxmGpu* nb, const NbnxnPairlistGpu* h_plist, const Inte { if (d_plist->na_c != h_plist->na_ci) { - sprintf(sbuf, "In init_plist: the #atoms per cell has changed (from %d to %d)", - d_plist->na_c, h_plist->na_ci); + sprintf(sbuf, + "In init_plist: the #atoms per cell has changed (from %d to %d)", + d_plist->na_c, + h_plist->na_ci); gmx_incons(sbuf); } } @@ -283,23 +286,41 @@ void gpu_init_pairlist(NbnxmGpu* nb, const NbnxnPairlistGpu* h_plist, const Inte // TODO most of this function is same in CUDA and OpenCL, move into the header const DeviceContext& deviceContext = *nb->deviceContext_; - reallocateDeviceBuffer(&d_plist->sci, h_plist->sci.size(), &d_plist->nsci, &d_plist->sci_nalloc, + reallocateDeviceBuffer( + &d_plist->sci, h_plist->sci.size(), &d_plist->nsci, &d_plist->sci_nalloc, deviceContext); + copyToDeviceBuffer(&d_plist->sci, + h_plist->sci.data(), + 0, + h_plist->sci.size(), + deviceStream, + GpuApiCallBehavior::Async, + bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr); + + reallocateDeviceBuffer( + &d_plist->cj4, h_plist->cj4.size(), &d_plist->ncj4, &d_plist->cj4_nalloc, deviceContext); + copyToDeviceBuffer(&d_plist->cj4, + h_plist->cj4.data(), + 0, + h_plist->cj4.size(), + deviceStream, + GpuApiCallBehavior::Async, + bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr); + + reallocateDeviceBuffer(&d_plist->imask, + h_plist->cj4.size() * c_nbnxnGpuClusterpairSplit, + &d_plist->nimask, + &d_plist->imask_nalloc, deviceContext); - copyToDeviceBuffer(&d_plist->sci, h_plist->sci.data(), 0, h_plist->sci.size(), deviceStream, - GpuApiCallBehavior::Async, bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr); - reallocateDeviceBuffer(&d_plist->cj4, h_plist->cj4.size(), &d_plist->ncj4, &d_plist->cj4_nalloc, - deviceContext); - copyToDeviceBuffer(&d_plist->cj4, h_plist->cj4.data(), 0, h_plist->cj4.size(), deviceStream, - GpuApiCallBehavior::Async, bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr); - - reallocateDeviceBuffer(&d_plist->imask, h_plist->cj4.size() * c_nbnxnGpuClusterpairSplit, - &d_plist->nimask, &d_plist->imask_nalloc, deviceContext); - - reallocateDeviceBuffer(&d_plist->excl, h_plist->excl.size(), &d_plist->nexcl, - &d_plist->excl_nalloc, deviceContext); - copyToDeviceBuffer(&d_plist->excl, h_plist->excl.data(), 0, h_plist->excl.size(), deviceStream, - GpuApiCallBehavior::Async, bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr); + reallocateDeviceBuffer( + &d_plist->excl, h_plist->excl.size(), &d_plist->nexcl, &d_plist->excl_nalloc, deviceContext); + copyToDeviceBuffer(&d_plist->excl, + h_plist->excl.data(), + 0, + h_plist->excl.size(), + deviceStream, + GpuApiCallBehavior::Async, + bDoTime ? iTimers.pl_h2d.fetchNextEvent() : nullptr); if (bDoTime) { @@ -351,7 +372,8 @@ enum ElecType nbnxmGpuPickElectrostaticsKernelType(const interaction_const_t* ic GMX_THROW(gmx::InconsistentInputError( gmx::formatString("The requested electrostatics type %s (%d) is not implemented in " "the GPU accelerated kernels!", - EELTYPE(ic->eeltype), ic->eeltype))); + EELTYPE(ic->eeltype), + ic->eeltype))); } } @@ -373,7 +395,8 @@ enum VdwType nbnxmGpuPickVdwKernelType(const interaction_const_t* ic, int combRu GMX_THROW(gmx::InconsistentInputError(gmx::formatString( "The requested LJ combination rule %s (%d) is not implemented in " "the GPU accelerated kernels!", - enum_name(combRule, ljcrNR, c_ljcrNames), combRule))); + enum_name(combRule, ljcrNR, c_ljcrNames), + combRule))); } case eintmodFORCESWITCH: return VdwType::FSwitch; case eintmodPOTSWITCH: return VdwType::PSwitch; @@ -381,7 +404,8 @@ enum VdwType nbnxmGpuPickVdwKernelType(const interaction_const_t* ic, int combRu GMX_THROW(gmx::InconsistentInputError( gmx::formatString("The requested VdW interaction modifier %s (%d) is not " "implemented in the GPU accelerated kernels!", - INTMODIFIER(ic->vdw_modifier), ic->vdw_modifier))); + INTMODIFIER(ic->vdw_modifier), + ic->vdw_modifier))); } } else if (ic->vdwtype == evdwPME) @@ -401,7 +425,8 @@ enum VdwType nbnxmGpuPickVdwKernelType(const interaction_const_t* ic, int combRu { GMX_THROW(gmx::InconsistentInputError(gmx::formatString( "The requested VdW type %s (%d) is not implemented in the GPU accelerated kernels!", - EVDWTYPE(ic->vdwtype), ic->vdwtype))); + EVDWTYPE(ic->vdwtype), + ic->vdwtype))); } } diff --git a/src/gromacs/nbnxm/nbnxm_setup.cpp b/src/gromacs/nbnxm/nbnxm_setup.cpp index 74086df3de..03eab394b6 100644 --- a/src/gromacs/nbnxm/nbnxm_setup.cpp +++ b/src/gromacs/nbnxm/nbnxm_setup.cpp @@ -323,14 +323,13 @@ static int getMinimumIlistCountForGpuBalancing(NbnxmGpu* nbnxmGpu) minimumIlistCount = strtol(env, &end, 10); if (!end || (*end != 0) || minimumIlistCount < 0) { - gmx_fatal(FARGS, - "Invalid value passed in GMX_NB_MIN_CI=%s, non-negative integer required", env); + gmx_fatal( + FARGS, "Invalid value passed in GMX_NB_MIN_CI=%s, non-negative integer required", env); } if (debug) { - fprintf(debug, "Neighbor-list balancing parameter: %d (passed as env. var.)\n", - minimumIlistCount); + fprintf(debug, "Neighbor-list balancing parameter: %d (passed as env. var.)\n", minimumIlistCount); } } else @@ -428,8 +427,13 @@ std::unique_ptr init_nb_verlet(const gmx::MDLogger& mdlog, */ mimimumNumEnergyGroupNonbonded = 1; } - nbnxn_atomdata_init(mdlog, nbat.get(), kernelSetup.kernelType, enbnxninitcombrule, fr->ntype, - fr->nbfp, mimimumNumEnergyGroupNonbonded, + nbnxn_atomdata_init(mdlog, + nbat.get(), + kernelSetup.kernelType, + enbnxninitcombrule, + fr->ntype, + fr->nbfp, + mimimumNumEnergyGroupNonbonded, (useGpuForNonbonded || emulateGpu) ? 1 : gmx_omp_nthreads_get(emntNonbonded)); NbnxmGpu* gpu_nbv = nullptr; @@ -446,16 +450,20 @@ std::unique_ptr init_nb_verlet(const gmx::MDLogger& mdlog, minimumIlistCountForGpuBalancing = getMinimumIlistCountForGpuBalancing(gpu_nbv); } - auto pairlistSets = std::make_unique(pairlistParams, haveMultipleDomains, - minimumIlistCountForGpuBalancing); + auto pairlistSets = std::make_unique( + pairlistParams, haveMultipleDomains, minimumIlistCountForGpuBalancing); - auto pairSearch = std::make_unique( - ir->pbcType, EI_TPI(ir->eI), DOMAINDECOMP(cr) ? &cr->dd->numCells : nullptr, - DOMAINDECOMP(cr) ? domdec_zones(cr->dd) : nullptr, pairlistParams.pairlistType, - bFEP_NonBonded, gmx_omp_nthreads_get(emntPairsearch), pinPolicy); + auto pairSearch = std::make_unique(ir->pbcType, + EI_TPI(ir->eI), + DOMAINDECOMP(cr) ? &cr->dd->numCells : nullptr, + DOMAINDECOMP(cr) ? domdec_zones(cr->dd) : nullptr, + pairlistParams.pairlistType, + bFEP_NonBonded, + gmx_omp_nthreads_get(emntPairsearch), + pinPolicy); - return std::make_unique(std::move(pairlistSets), std::move(pairSearch), - std::move(nbat), kernelSetup, gpu_nbv, wcycle); + return std::make_unique( + std::move(pairlistSets), std::move(pairSearch), std::move(nbat), kernelSetup, gpu_nbv, wcycle); } } // namespace Nbnxm diff --git a/src/gromacs/nbnxm/opencl/nbnxm_ocl.cpp b/src/gromacs/nbnxm/opencl/nbnxm_ocl.cpp index affbad0811..2f6cb2db7b 100644 --- a/src/gromacs/nbnxm/opencl/nbnxm_ocl.cpp +++ b/src/gromacs/nbnxm/opencl/nbnxm_ocl.cpp @@ -147,7 +147,8 @@ static inline void validate_global_work_size(const KernelLaunchConfig& config, "Watch out, the input system is too large to simulate!\n" "The number of nonbonded work units (=number of super-clusters) exceeds the" "device capabilities. Global work size limit exceeded (%zu > %zu)!", - global_work_size[i], device_limit); + global_work_size[i], + device_limit); } } } @@ -163,16 +164,24 @@ static inline void validate_global_work_size(const KernelLaunchConfig& config, /*! \brief Force-only kernel function names. */ static const char* nb_kfunc_noener_noprune_ptr[c_numElecTypes][c_numVdwTypes] = { - { "nbnxn_kernel_ElecCut_VdwLJ_F_opencl", "nbnxn_kernel_ElecCut_VdwLJCombGeom_F_opencl", - "nbnxn_kernel_ElecCut_VdwLJCombLB_F_opencl", "nbnxn_kernel_ElecCut_VdwLJFsw_F_opencl", - "nbnxn_kernel_ElecCut_VdwLJPsw_F_opencl", "nbnxn_kernel_ElecCut_VdwLJEwCombGeom_F_opencl", + { "nbnxn_kernel_ElecCut_VdwLJ_F_opencl", + "nbnxn_kernel_ElecCut_VdwLJCombGeom_F_opencl", + "nbnxn_kernel_ElecCut_VdwLJCombLB_F_opencl", + "nbnxn_kernel_ElecCut_VdwLJFsw_F_opencl", + "nbnxn_kernel_ElecCut_VdwLJPsw_F_opencl", + "nbnxn_kernel_ElecCut_VdwLJEwCombGeom_F_opencl", "nbnxn_kernel_ElecCut_VdwLJEwCombLB_F_opencl" }, - { "nbnxn_kernel_ElecRF_VdwLJ_F_opencl", "nbnxn_kernel_ElecRF_VdwLJCombGeom_F_opencl", - "nbnxn_kernel_ElecRF_VdwLJCombLB_F_opencl", "nbnxn_kernel_ElecRF_VdwLJFsw_F_opencl", - "nbnxn_kernel_ElecRF_VdwLJPsw_F_opencl", "nbnxn_kernel_ElecRF_VdwLJEwCombGeom_F_opencl", + { "nbnxn_kernel_ElecRF_VdwLJ_F_opencl", + "nbnxn_kernel_ElecRF_VdwLJCombGeom_F_opencl", + "nbnxn_kernel_ElecRF_VdwLJCombLB_F_opencl", + "nbnxn_kernel_ElecRF_VdwLJFsw_F_opencl", + "nbnxn_kernel_ElecRF_VdwLJPsw_F_opencl", + "nbnxn_kernel_ElecRF_VdwLJEwCombGeom_F_opencl", "nbnxn_kernel_ElecRF_VdwLJEwCombLB_F_opencl" }, - { "nbnxn_kernel_ElecEwQSTab_VdwLJ_F_opencl", "nbnxn_kernel_ElecEwQSTab_VdwLJCombGeom_F_opencl", - "nbnxn_kernel_ElecEwQSTab_VdwLJCombLB_F_opencl", "nbnxn_kernel_ElecEwQSTab_VdwLJFsw_F_opencl", + { "nbnxn_kernel_ElecEwQSTab_VdwLJ_F_opencl", + "nbnxn_kernel_ElecEwQSTab_VdwLJCombGeom_F_opencl", + "nbnxn_kernel_ElecEwQSTab_VdwLJCombLB_F_opencl", + "nbnxn_kernel_ElecEwQSTab_VdwLJFsw_F_opencl", "nbnxn_kernel_ElecEwQSTab_VdwLJPsw_F_opencl", "nbnxn_kernel_ElecEwQSTab_VdwLJEwCombGeom_F_opencl", "nbnxn_kernel_ElecEwQSTab_VdwLJEwCombLB_F_opencl" }, @@ -183,31 +192,43 @@ static const char* nb_kfunc_noener_noprune_ptr[c_numElecTypes][c_numVdwTypes] = "nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJPsw_F_opencl", "nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombGeom_F_opencl", "nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombLB_F_opencl" }, - { "nbnxn_kernel_ElecEw_VdwLJ_F_opencl", "nbnxn_kernel_ElecEw_VdwLJCombGeom_F_opencl", - "nbnxn_kernel_ElecEw_VdwLJCombLB_F_opencl", "nbnxn_kernel_ElecEw_VdwLJFsw_F_opencl", - "nbnxn_kernel_ElecEw_VdwLJPsw_F_opencl", "nbnxn_kernel_ElecEw_VdwLJEwCombGeom_F_opencl", + { "nbnxn_kernel_ElecEw_VdwLJ_F_opencl", + "nbnxn_kernel_ElecEw_VdwLJCombGeom_F_opencl", + "nbnxn_kernel_ElecEw_VdwLJCombLB_F_opencl", + "nbnxn_kernel_ElecEw_VdwLJFsw_F_opencl", + "nbnxn_kernel_ElecEw_VdwLJPsw_F_opencl", + "nbnxn_kernel_ElecEw_VdwLJEwCombGeom_F_opencl", "nbnxn_kernel_ElecEw_VdwLJEwCombLB_F_opencl" }, { "nbnxn_kernel_ElecEwTwinCut_VdwLJ_F_opencl", "nbnxn_kernel_ElecEwTwinCut_VdwLJCombGeom_F_opencl", "nbnxn_kernel_ElecEwTwinCut_VdwLJCombLB_F_opencl", - "nbnxn_kernel_ElecEwTwinCut_VdwLJFsw_F_opencl", "nbnxn_kernel_ElecEwTwinCut_VdwLJPsw_F_opencl", + "nbnxn_kernel_ElecEwTwinCut_VdwLJFsw_F_opencl", + "nbnxn_kernel_ElecEwTwinCut_VdwLJPsw_F_opencl", "nbnxn_kernel_ElecEwTwinCut_VdwLJEwCombGeom_F_opencl", "nbnxn_kernel_ElecEwTwinCut_VdwLJEwCombLB_F_opencl" } }; /*! \brief Force + energy kernel function pointers. */ static const char* nb_kfunc_ener_noprune_ptr[c_numElecTypes][c_numVdwTypes] = { - { "nbnxn_kernel_ElecCut_VdwLJ_VF_opencl", "nbnxn_kernel_ElecCut_VdwLJCombGeom_VF_opencl", - "nbnxn_kernel_ElecCut_VdwLJCombLB_VF_opencl", "nbnxn_kernel_ElecCut_VdwLJFsw_VF_opencl", - "nbnxn_kernel_ElecCut_VdwLJPsw_VF_opencl", "nbnxn_kernel_ElecCut_VdwLJEwCombGeom_VF_opencl", + { "nbnxn_kernel_ElecCut_VdwLJ_VF_opencl", + "nbnxn_kernel_ElecCut_VdwLJCombGeom_VF_opencl", + "nbnxn_kernel_ElecCut_VdwLJCombLB_VF_opencl", + "nbnxn_kernel_ElecCut_VdwLJFsw_VF_opencl", + "nbnxn_kernel_ElecCut_VdwLJPsw_VF_opencl", + "nbnxn_kernel_ElecCut_VdwLJEwCombGeom_VF_opencl", "nbnxn_kernel_ElecCut_VdwLJEwCombLB_VF_opencl" }, - { "nbnxn_kernel_ElecRF_VdwLJ_VF_opencl", "nbnxn_kernel_ElecRF_VdwLJCombGeom_VF_opencl", - "nbnxn_kernel_ElecRF_VdwLJCombLB_VF_opencl", "nbnxn_kernel_ElecRF_VdwLJFsw_VF_opencl", - "nbnxn_kernel_ElecRF_VdwLJPsw_VF_opencl", "nbnxn_kernel_ElecRF_VdwLJEwCombGeom_VF_opencl", + { "nbnxn_kernel_ElecRF_VdwLJ_VF_opencl", + "nbnxn_kernel_ElecRF_VdwLJCombGeom_VF_opencl", + "nbnxn_kernel_ElecRF_VdwLJCombLB_VF_opencl", + "nbnxn_kernel_ElecRF_VdwLJFsw_VF_opencl", + "nbnxn_kernel_ElecRF_VdwLJPsw_VF_opencl", + "nbnxn_kernel_ElecRF_VdwLJEwCombGeom_VF_opencl", "nbnxn_kernel_ElecRF_VdwLJEwCombLB_VF_opencl" }, - { "nbnxn_kernel_ElecEwQSTab_VdwLJ_VF_opencl", "nbnxn_kernel_ElecEwQSTab_VdwLJCombGeom_VF_opencl", + { "nbnxn_kernel_ElecEwQSTab_VdwLJ_VF_opencl", + "nbnxn_kernel_ElecEwQSTab_VdwLJCombGeom_VF_opencl", "nbnxn_kernel_ElecEwQSTab_VdwLJCombLB_VF_opencl", - "nbnxn_kernel_ElecEwQSTab_VdwLJFsw_VF_opencl", "nbnxn_kernel_ElecEwQSTab_VdwLJPsw_VF_opencl", + "nbnxn_kernel_ElecEwQSTab_VdwLJFsw_VF_opencl", + "nbnxn_kernel_ElecEwQSTab_VdwLJPsw_VF_opencl", "nbnxn_kernel_ElecEwQSTab_VdwLJEwCombGeom_VF_opencl", "nbnxn_kernel_ElecEwQSTab_VdwLJEwCombLB_VF_opencl" }, { "nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJ_VF_opencl", @@ -217,9 +238,12 @@ static const char* nb_kfunc_ener_noprune_ptr[c_numElecTypes][c_numVdwTypes] = { "nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJPsw_VF_opencl", "nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombGeom_VF_opencl", "nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombLB_VF_opencl" }, - { "nbnxn_kernel_ElecEw_VdwLJ_VF_opencl", "nbnxn_kernel_ElecEw_VdwLJCombGeom_VF_opencl", - "nbnxn_kernel_ElecEw_VdwLJCombLB_VF_opencl", "nbnxn_kernel_ElecEw_VdwLJFsw_VF_opencl", - "nbnxn_kernel_ElecEw_VdwLJPsw_VF_opencl", "nbnxn_kernel_ElecEw_VdwLJEwCombGeom_VF_opencl", + { "nbnxn_kernel_ElecEw_VdwLJ_VF_opencl", + "nbnxn_kernel_ElecEw_VdwLJCombGeom_VF_opencl", + "nbnxn_kernel_ElecEw_VdwLJCombLB_VF_opencl", + "nbnxn_kernel_ElecEw_VdwLJFsw_VF_opencl", + "nbnxn_kernel_ElecEw_VdwLJPsw_VF_opencl", + "nbnxn_kernel_ElecEw_VdwLJEwCombGeom_VF_opencl", "nbnxn_kernel_ElecEw_VdwLJEwCombLB_VF_opencl" }, { "nbnxn_kernel_ElecEwTwinCut_VdwLJ_VF_opencl", "nbnxn_kernel_ElecEwTwinCut_VdwLJCombGeom_VF_opencl", @@ -235,12 +259,15 @@ static const char* nb_kfunc_noener_prune_ptr[c_numElecTypes][c_numVdwTypes] = { { "nbnxn_kernel_ElecCut_VdwLJ_F_prune_opencl", "nbnxn_kernel_ElecCut_VdwLJCombGeom_F_prune_opencl", "nbnxn_kernel_ElecCut_VdwLJCombLB_F_prune_opencl", - "nbnxn_kernel_ElecCut_VdwLJFsw_F_prune_opencl", "nbnxn_kernel_ElecCut_VdwLJPsw_F_prune_opencl", + "nbnxn_kernel_ElecCut_VdwLJFsw_F_prune_opencl", + "nbnxn_kernel_ElecCut_VdwLJPsw_F_prune_opencl", "nbnxn_kernel_ElecCut_VdwLJEwCombGeom_F_prune_opencl", "nbnxn_kernel_ElecCut_VdwLJEwCombLB_F_prune_opencl" }, - { "nbnxn_kernel_ElecRF_VdwLJ_F_prune_opencl", "nbnxn_kernel_ElecRF_VdwLJCombGeom_F_prune_opencl", + { "nbnxn_kernel_ElecRF_VdwLJ_F_prune_opencl", + "nbnxn_kernel_ElecRF_VdwLJCombGeom_F_prune_opencl", "nbnxn_kernel_ElecRF_VdwLJCombLB_F_prune_opencl", - "nbnxn_kernel_ElecRF_VdwLJFsw_F_prune_opencl", "nbnxn_kernel_ElecRF_VdwLJPsw_F_prune_opencl", + "nbnxn_kernel_ElecRF_VdwLJFsw_F_prune_opencl", + "nbnxn_kernel_ElecRF_VdwLJPsw_F_prune_opencl", "nbnxn_kernel_ElecRF_VdwLJEwCombGeom_F_prune_opencl", "nbnxn_kernel_ElecRF_VdwLJEwCombLB_F_prune_opencl" }, { "nbnxn_kernel_ElecEwQSTab_VdwLJ_F_prune_opencl", @@ -257,9 +284,11 @@ static const char* nb_kfunc_noener_prune_ptr[c_numElecTypes][c_numVdwTypes] = { "nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJPsw_F_prune_opencl", "nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombGeom_F_prune_opencl", "nbnxn_kernel_ElecEwQSTabTwinCut_VdwLJEwCombLB_F_prune_opencl" }, - { "nbnxn_kernel_ElecEw_VdwLJ_F_prune_opencl", "nbnxn_kernel_ElecEw_VdwLJCombGeom_F_prune_opencl", + { "nbnxn_kernel_ElecEw_VdwLJ_F_prune_opencl", + "nbnxn_kernel_ElecEw_VdwLJCombGeom_F_prune_opencl", "nbnxn_kernel_ElecEw_VdwLJCombLB_F_prune_opencl", - "nbnxn_kernel_ElecEw_VdwLJFsw_F_prune_opencl", "nbnxn_kernel_ElecEw_VdwLJPsw_F_prune_opencl", + "nbnxn_kernel_ElecEw_VdwLJFsw_F_prune_opencl", + "nbnxn_kernel_ElecEw_VdwLJPsw_F_prune_opencl", "nbnxn_kernel_ElecEw_VdwLJEwCombGeom_F_prune_opencl", "nbnxn_kernel_ElecEw_VdwLJEwCombLB_F_prune_opencl" }, { "nbnxn_kernel_ElecEwTwinCut_VdwLJ_F_prune_opencl", @@ -283,7 +312,8 @@ static const char* nb_kfunc_ener_prune_ptr[c_numElecTypes][c_numVdwTypes] = { { "nbnxn_kernel_ElecRF_VdwLJ_VF_prune_opencl", "nbnxn_kernel_ElecRF_VdwLJCombGeom_VF_prune_opencl", "nbnxn_kernel_ElecRF_VdwLJCombLB_VF_prune_opencl", - "nbnxn_kernel_ElecRF_VdwLJFsw_VF_prune_opencl", "nbnxn_kernel_ElecRF_VdwLJPsw_VF_prune_opencl", + "nbnxn_kernel_ElecRF_VdwLJFsw_VF_prune_opencl", + "nbnxn_kernel_ElecRF_VdwLJPsw_VF_prune_opencl", "nbnxn_kernel_ElecRF_VdwLJEwCombGeom_VF_prune_opencl", "nbnxn_kernel_ElecRF_VdwLJEwCombLB_VF_prune_opencl" }, { "nbnxn_kernel_ElecEwQSTab_VdwLJ_VF_prune_opencl", @@ -303,7 +333,8 @@ static const char* nb_kfunc_ener_prune_ptr[c_numElecTypes][c_numVdwTypes] = { { "nbnxn_kernel_ElecEw_VdwLJ_VF_prune_opencl", "nbnxn_kernel_ElecEw_VdwLJCombGeom_VF_prune_opencl", "nbnxn_kernel_ElecEw_VdwLJCombLB_VF_prune_opencl", - "nbnxn_kernel_ElecEw_VdwLJFsw_VF_prune_opencl", "nbnxn_kernel_ElecEw_VdwLJPsw_VF_prune_opencl", + "nbnxn_kernel_ElecEw_VdwLJFsw_VF_prune_opencl", + "nbnxn_kernel_ElecEw_VdwLJPsw_VF_prune_opencl", "nbnxn_kernel_ElecEw_VdwLJEwCombGeom_VF_prune_opencl", "nbnxn_kernel_ElecEw_VdwLJEwCombLB_VF_prune_opencl" }, { "nbnxn_kernel_ElecEwTwinCut_VdwLJ_VF_prune_opencl", @@ -386,9 +417,10 @@ select_nbnxn_kernel(NbnxmGpu* nb, enum ElecType elecType, enum VdwType vdwType, if (nullptr == kernel_ptr[0]) { *kernel_ptr = clCreateKernel(nb->dev_rundata->program, kernel_name_to_run, &cl_error); - GMX_ASSERT(cl_error == CL_SUCCESS, ("clCreateKernel failed: " + ocl_get_error_string(cl_error) - + " for kernel named " + kernel_name_to_run) - .c_str()); + GMX_ASSERT(cl_error == CL_SUCCESS, + ("clCreateKernel failed: " + ocl_get_error_string(cl_error) + + " for kernel named " + kernel_name_to_run) + .c_str()); } return *kernel_ptr; @@ -533,8 +565,12 @@ void gpu_copy_xq_to_gpu(NbnxmGpu* nb, const nbnxn_atomdata_t* nbatom, const Atom /* HtoD x, q */ GMX_ASSERT(sizeof(float) == sizeof(*nbatom->x().data()), "The size of the xyzq buffer element should be equal to the size of float4."); - copyToDeviceBuffer(&adat->xq, nbatom->x().data() + adat_begin * 4, adat_begin * 4, adat_len * 4, - deviceStream, GpuApiCallBehavior::Async, + copyToDeviceBuffer(&adat->xq, + nbatom->x().data() + adat_begin * 4, + adat_begin * 4, + adat_len * 4, + deviceStream, + GpuApiCallBehavior::Async, bDoTime ? t->xf[atomLocality].nb_h2d.fetchNextEvent() : nullptr); if (bDoTime) @@ -653,10 +689,14 @@ void gpu_launch_kernel(NbnxmGpu* nb, const gmx::StepWorkload& stepWork, const Nb fprintf(debug, "Non-bonded GPU launch configuration:\n\tLocal work size: %zux%zux%zu\n\t" "Global work size : %zux%zu\n\t#Super-clusters/clusters: %d/%d (%d)\n", - config.blockSize[0], config.blockSize[1], config.blockSize[2], - config.blockSize[0] * config.gridSize[0], config.blockSize[1] * config.gridSize[1], + config.blockSize[0], + config.blockSize[1], + config.blockSize[2], + config.blockSize[0] * config.gridSize[0], + config.blockSize[1] * config.gridSize[1], plist->nsci * c_nbnxnGpuNumClusterPerSupercluster, - c_nbnxnGpuNumClusterPerSupercluster, plist->na_c); + c_nbnxnGpuNumClusterPerSupercluster, + plist->na_c); } fillin_ocl_structures(nbp, &nbparams_params); @@ -664,7 +704,10 @@ void gpu_launch_kernel(NbnxmGpu* nb, const gmx::StepWorkload& stepWork, const Nb auto* timingEvent = bDoTime ? t->interaction[iloc].nb_k.fetchNextEvent() : nullptr; constexpr char kernelName[] = "k_calc_nb"; const auto kernel = - select_nbnxn_kernel(nb, nbp->elecType, nbp->vdwType, stepWork.computeEnergy, + select_nbnxn_kernel(nb, + nbp->elecType, + nbp->vdwType, + stepWork.computeEnergy, (plist->haveFreshList && !nb->timers->interaction[iloc].didPrune)); @@ -673,19 +716,46 @@ void gpu_launch_kernel(NbnxmGpu* nb, const gmx::StepWorkload& stepWork, const Nb const int computeFshift = static_cast(stepWork.computeVirial); if (useLjCombRule(nb->nbparam->vdwType)) { - const auto kernelArgs = prepareGpuKernelArguments( - kernel, config, &nbparams_params, &adat->xq, &adat->f, &adat->e_lj, &adat->e_el, - &adat->fshift, &adat->lj_comb, &adat->shift_vec, &nbp->nbfp, &nbp->nbfp_comb, - &nbp->coulomb_tab, &plist->sci, &plist->cj4, &plist->excl, &computeFshift); + const auto kernelArgs = prepareGpuKernelArguments(kernel, + config, + &nbparams_params, + &adat->xq, + &adat->f, + &adat->e_lj, + &adat->e_el, + &adat->fshift, + &adat->lj_comb, + &adat->shift_vec, + &nbp->nbfp, + &nbp->nbfp_comb, + &nbp->coulomb_tab, + &plist->sci, + &plist->cj4, + &plist->excl, + &computeFshift); launchGpuKernel(kernel, config, deviceStream, timingEvent, kernelName, kernelArgs); } else { - const auto kernelArgs = prepareGpuKernelArguments( - kernel, config, &adat->ntypes, &nbparams_params, &adat->xq, &adat->f, &adat->e_lj, - &adat->e_el, &adat->fshift, &adat->atom_types, &adat->shift_vec, &nbp->nbfp, &nbp->nbfp_comb, - &nbp->coulomb_tab, &plist->sci, &plist->cj4, &plist->excl, &computeFshift); + const auto kernelArgs = prepareGpuKernelArguments(kernel, + config, + &adat->ntypes, + &nbparams_params, + &adat->xq, + &adat->f, + &adat->e_lj, + &adat->e_el, + &adat->fshift, + &adat->atom_types, + &adat->shift_vec, + &nbp->nbfp, + &nbp->nbfp_comb, + &nbp->coulomb_tab, + &plist->sci, + &plist->cj4, + &plist->excl, + &computeFshift); launchGpuKernel(kernel, config, deviceStream, timingEvent, kernelName, kernelArgs); } @@ -813,10 +883,15 @@ void gpu_launch_kernel_pruneonly(NbnxmGpu* nb, const InteractionLocality iloc, c "Pruning GPU kernel launch configuration:\n\tLocal work size: %zux%zux%zu\n\t" "\tGlobal work size: %zux%zu\n\t#Super-clusters/clusters: %d/%d (%d)\n" "\tShMem: %zu\n", - config.blockSize[0], config.blockSize[1], config.blockSize[2], - config.blockSize[0] * config.gridSize[0], config.blockSize[1] * config.gridSize[1], + config.blockSize[0], + config.blockSize[1], + config.blockSize[2], + config.blockSize[0] * config.gridSize[0], + config.blockSize[1] * config.gridSize[1], plist->nsci * c_nbnxnGpuNumClusterPerSupercluster, - c_nbnxnGpuNumClusterPerSupercluster, plist->na_c, config.sharedMemorySize); + c_nbnxnGpuNumClusterPerSupercluster, + plist->na_c, + config.sharedMemorySize); } cl_nbparam_params_t nbparams_params; @@ -825,9 +900,16 @@ void gpu_launch_kernel_pruneonly(NbnxmGpu* nb, const InteractionLocality iloc, c auto* timingEvent = bDoTime ? timer->fetchNextEvent() : nullptr; constexpr char kernelName[] = "k_pruneonly"; const auto pruneKernel = selectPruneKernel(nb->kernel_pruneonly, plist->haveFreshList); - const auto kernelArgs = prepareGpuKernelArguments(pruneKernel, config, &nbparams_params, - &adat->xq, &adat->shift_vec, &plist->sci, - &plist->cj4, &plist->imask, &numParts, &part); + const auto kernelArgs = prepareGpuKernelArguments(pruneKernel, + config, + &nbparams_params, + &adat->xq, + &adat->shift_vec, + &plist->sci, + &plist->cj4, + &plist->imask, + &numParts, + &part); launchGpuKernel(pruneKernel, config, deviceStream, timingEvent, kernelName, kernelArgs); if (plist->haveFreshList) @@ -903,8 +985,12 @@ void gpu_launch_cpyback(NbnxmGpu* nb, /* DtoH f */ GMX_ASSERT(sizeof(*nbatom->out[0].f.data()) == sizeof(float), "The host force buffer should be in single precision to match device data size."); - copyFromDeviceBuffer(&nbatom->out[0].f[adat_begin * DIM], &adat->f, adat_begin * DIM, - adat_len * DIM, deviceStream, GpuApiCallBehavior::Async, + copyFromDeviceBuffer(&nbatom->out[0].f[adat_begin * DIM], + &adat->f, + adat_begin * DIM, + adat_len * DIM, + deviceStream, + GpuApiCallBehavior::Async, bDoTime ? t->xf[aloc].nb_d2h.fetchNextEvent() : nullptr); /* kick off work */ @@ -931,8 +1017,12 @@ void gpu_launch_cpyback(NbnxmGpu* nb, { GMX_ASSERT(sizeof(*nb->nbst.fshift) == DIM * sizeof(float), "Sizes of host- and device-side shift vector elements should be the same."); - copyFromDeviceBuffer(reinterpret_cast(nb->nbst.fshift), &adat->fshift, 0, - SHIFTS * DIM, deviceStream, GpuApiCallBehavior::Async, + copyFromDeviceBuffer(reinterpret_cast(nb->nbst.fshift), + &adat->fshift, + 0, + SHIFTS * DIM, + deviceStream, + GpuApiCallBehavior::Async, bDoTime ? t->xf[aloc].nb_d2h.fetchNextEvent() : nullptr); } @@ -941,12 +1031,22 @@ void gpu_launch_cpyback(NbnxmGpu* nb, { GMX_ASSERT(sizeof(*nb->nbst.e_lj) == sizeof(float), "Sizes of host- and device-side LJ energy terms should be the same."); - copyFromDeviceBuffer(nb->nbst.e_lj, &adat->e_lj, 0, 1, deviceStream, GpuApiCallBehavior::Async, + copyFromDeviceBuffer(nb->nbst.e_lj, + &adat->e_lj, + 0, + 1, + deviceStream, + GpuApiCallBehavior::Async, bDoTime ? t->xf[aloc].nb_d2h.fetchNextEvent() : nullptr); GMX_ASSERT(sizeof(*nb->nbst.e_el) == sizeof(float), "Sizes of host- and device-side electrostatic energy terms should be the " "same."); - copyFromDeviceBuffer(nb->nbst.e_el, &adat->e_el, 0, 1, deviceStream, GpuApiCallBehavior::Async, + copyFromDeviceBuffer(nb->nbst.e_el, + &adat->e_el, + 0, + 1, + deviceStream, + GpuApiCallBehavior::Async, bDoTime ? t->xf[aloc].nb_d2h.fetchNextEvent() : nullptr); } } diff --git a/src/gromacs/nbnxm/opencl/nbnxm_ocl_data_mgmt.cpp b/src/gromacs/nbnxm/opencl/nbnxm_ocl_data_mgmt.cpp index 8197c72cf9..f37dfbe582 100644 --- a/src/gromacs/nbnxm/opencl/nbnxm_ocl_data_mgmt.cpp +++ b/src/gromacs/nbnxm/opencl/nbnxm_ocl_data_mgmt.cpp @@ -188,8 +188,11 @@ static cl_kernel nbnxn_gpu_create_kernel(NbnxmGpu* nb, const char* kernel_name) kernel = clCreateKernel(nb->dev_rundata->program, kernel_name, &cl_error); if (CL_SUCCESS != cl_error) { - gmx_fatal(FARGS, "Failed to create kernel '%s' for GPU #%s: OpenCL error %d", kernel_name, - nb->deviceContext_->deviceInfo().device_name, cl_error); + gmx_fatal(FARGS, + "Failed to create kernel '%s' for GPU #%s: OpenCL error %d", + kernel_name, + nb->deviceContext_->deviceInfo().device_name, + cl_error); } return kernel; @@ -224,8 +227,8 @@ static void nbnxn_ocl_clear_e_fshift(NbnxmGpu* nb) cl_error |= clSetKernelArg(zero_e_fshift, arg_no++, sizeof(cl_uint), &shifts); GMX_ASSERT(cl_error == CL_SUCCESS, ocl_get_error_string(cl_error).c_str()); - cl_error = clEnqueueNDRangeKernel(ls, zero_e_fshift, 3, nullptr, global_work_size, - local_work_size, 0, nullptr, nullptr); + cl_error = clEnqueueNDRangeKernel( + ls, zero_e_fshift, 3, nullptr, global_work_size, local_work_size, 0, nullptr, nullptr); GMX_ASSERT(cl_error == CL_SUCCESS, ocl_get_error_string(cl_error).c_str()); } @@ -401,8 +404,13 @@ void gpu_upload_shiftvec(NbnxmGpu* nb, const nbnxn_atomdata_t* nbatom) { GMX_ASSERT(sizeof(float) * DIM == sizeof(*nbatom->shift_vec.data()), "Sizes of host- and device-side shift vectors should be the same."); - copyToDeviceBuffer(&adat->shift_vec, reinterpret_cast(nbatom->shift_vec.data()), - 0, SHIFTS * DIM, deviceStream, GpuApiCallBehavior::Async, nullptr); + copyToDeviceBuffer(&adat->shift_vec, + reinterpret_cast(nbatom->shift_vec.data()), + 0, + SHIFTS * DIM, + deviceStream, + GpuApiCallBehavior::Async, + nullptr); adat->bShiftVecUploaded = CL_TRUE; } } @@ -474,16 +482,25 @@ void gpu_init_atomdata(NbnxmGpu* nb, const nbnxn_atomdata_t* nbat) { GMX_ASSERT(sizeof(float) == sizeof(*nbat->params().lj_comb.data()), "Size of the LJ parameters element should be equal to the size of float2."); - copyToDeviceBuffer(&d_atdat->lj_comb, nbat->params().lj_comb.data(), 0, 2 * natoms, - deviceStream, GpuApiCallBehavior::Async, + copyToDeviceBuffer(&d_atdat->lj_comb, + nbat->params().lj_comb.data(), + 0, + 2 * natoms, + deviceStream, + GpuApiCallBehavior::Async, bDoTime ? timers->atdat.fetchNextEvent() : nullptr); } else { GMX_ASSERT(sizeof(int) == sizeof(*nbat->params().type.data()), "Sizes of host- and device-side atom types should be the same."); - copyToDeviceBuffer(&d_atdat->atom_types, nbat->params().type.data(), 0, natoms, deviceStream, - GpuApiCallBehavior::Async, bDoTime ? timers->atdat.fetchNextEvent() : nullptr); + copyToDeviceBuffer(&d_atdat->atom_types, + nbat->params().type.data(), + 0, + natoms, + deviceStream, + GpuApiCallBehavior::Async, + bDoTime ? timers->atdat.fetchNextEvent() : nullptr); } if (bDoTime) diff --git a/src/gromacs/nbnxm/opencl/nbnxm_ocl_jit_support.cpp b/src/gromacs/nbnxm/opencl/nbnxm_ocl_jit_support.cpp index 4717e1601c..6a494e0821 100644 --- a/src/gromacs/nbnxm/opencl/nbnxm_ocl_jit_support.cpp +++ b/src/gromacs/nbnxm/opencl/nbnxm_ocl_jit_support.cpp @@ -200,22 +200,29 @@ void nbnxn_gpu_compile_kernels(NbnxmGpu* nb) " -Dc_nbnxnGpuNumClusterPerSupercluster=%d" " -Dc_nbnxnGpuJgroupSize=%d" "%s", - c_nbnxnGpuClusterSize, c_nbnxnMinDistanceSquared, c_nbnxnGpuNumClusterPerSupercluster, - c_nbnxnGpuJgroupSize, (nb->bPrefetchLjParam) ? " -DIATYPE_SHMEM" : ""); + c_nbnxnGpuClusterSize, + c_nbnxnMinDistanceSquared, + c_nbnxnGpuNumClusterPerSupercluster, + c_nbnxnGpuJgroupSize, + (nb->bPrefetchLjParam) ? " -DIATYPE_SHMEM" : ""); try { /* TODO when we have a proper MPI-aware logging module, the log output here should be written there */ - program = gmx::ocl::compileProgram( - stderr, "gromacs/nbnxm/opencl", "nbnxm_ocl_kernels.cl", extraDefines, - nb->deviceContext_->context(), nb->deviceContext_->deviceInfo().oclDeviceId, - nb->deviceContext_->deviceInfo().deviceVendor); + program = gmx::ocl::compileProgram(stderr, + "gromacs/nbnxm/opencl", + "nbnxm_ocl_kernels.cl", + extraDefines, + nb->deviceContext_->context(), + nb->deviceContext_->deviceInfo().oclDeviceId, + nb->deviceContext_->deviceInfo().deviceVendor); } catch (gmx::GromacsException& e) { - e.prependContext(gmx::formatString( - "Failed to compile/load nbnxm kernels for GPU #%d %s\n", - nb->deviceContext_->deviceInfo().id, nb->deviceContext_->deviceInfo().device_name)); + e.prependContext( + gmx::formatString("Failed to compile/load nbnxm kernels for GPU #%d %s\n", + nb->deviceContext_->deviceInfo().id, + nb->deviceContext_->deviceInfo().device_name)); throw; } } diff --git a/src/gromacs/nbnxm/opencl/nbnxm_ocl_kernel.clh b/src/gromacs/nbnxm/opencl/nbnxm_ocl_kernel.clh index 11516fd4f1..68e5b854cb 100644 --- a/src/gromacs/nbnxm/opencl/nbnxm_ocl_kernel.clh +++ b/src/gromacs/nbnxm/opencl/nbnxm_ocl_kernel.clh @@ -232,8 +232,10 @@ __kernel void NB_KERNEL_FUNC_NAME(nbnxn_kernel, _F_opencl) const int ai = ci * CL_SIZE + tidxi; float4 xqbuf = xq[ai] - + (float4)(shift_vec[3 * nb_sci.shift], shift_vec[3 * nb_sci.shift + 1], - shift_vec[3 * nb_sci.shift + 2], 0.0F); + + (float4)(shift_vec[3 * nb_sci.shift], + shift_vec[3 * nb_sci.shift + 1], + shift_vec[3 * nb_sci.shift + 2], + 0.0F); xqbuf.w *= nbparam->epsfac; xqib[(tidxj + i) * CL_SIZE + tidxi] = xqbuf; #ifdef IATYPE_SHMEM @@ -472,20 +474,40 @@ __kernel void NB_KERNEL_FUNC_NAME(nbnxn_kernel, _F_opencl) #ifdef LJ_EWALD # ifdef LJ_EWALD_COMB_GEOM # ifdef CALC_ENERGIES - calculate_lj_ewald_comb_geom_F_E( - nbfp_comb_climg2d, nbparam, typei, typej, r2, inv_r2, - lje_coeff2, lje_coeff6_6, int_bit, &F_invr, &E_lj_p); + calculate_lj_ewald_comb_geom_F_E(nbfp_comb_climg2d, + nbparam, + typei, + typej, + r2, + inv_r2, + lje_coeff2, + lje_coeff6_6, + int_bit, + &F_invr, + &E_lj_p); # else - calculate_lj_ewald_comb_geom_F(nbfp_comb_climg2d, typei, typej, r2, inv_r2, - lje_coeff2, lje_coeff6_6, &F_invr); + calculate_lj_ewald_comb_geom_F( + nbfp_comb_climg2d, typei, typej, r2, inv_r2, lje_coeff2, lje_coeff6_6, &F_invr); # endif /* CALC_ENERGIES */ # elif defined LJ_EWALD_COMB_LB - calculate_lj_ewald_comb_LB_F_E(nbfp_comb_climg2d, nbparam, typei, typej, - r2, inv_r2, lje_coeff2, lje_coeff6_6, + calculate_lj_ewald_comb_LB_F_E(nbfp_comb_climg2d, + nbparam, + typei, + typej, + r2, + inv_r2, + lje_coeff2, + lje_coeff6_6, # ifdef CALC_ENERGIES - int_bit, true, &F_invr, &E_lj_p + int_bit, + true, + &F_invr, + &E_lj_p # else - 0, false, &F_invr, 0 + 0, + false, + &F_invr, + 0 # endif /* CALC_ENERGIES */ ); # endif /* LJ_EWALD_COMB_GEOM */ @@ -532,8 +554,8 @@ __kernel void NB_KERNEL_FUNC_NAME(nbnxn_kernel, _F_opencl) #elif defined EL_EWALD_TAB F_invr += qi * qj_f * (int_bit * inv_r2 - - interpolate_coulomb_force_r(coulomb_tab_climg2d, r2 * inv_r, - coulomb_tab_scale)) + - interpolate_coulomb_force_r( + coulomb_tab_climg2d, r2 * inv_r, coulomb_tab_scale)) * inv_r; #endif /* EL_EWALD_ANA/TAB */ diff --git a/src/gromacs/nbnxm/opencl/nbnxm_ocl_kernel_pruneonly.clh b/src/gromacs/nbnxm/opencl/nbnxm_ocl_kernel_pruneonly.clh index dfafdcbf28..49d19645a9 100644 --- a/src/gromacs/nbnxm/opencl/nbnxm_ocl_kernel_pruneonly.clh +++ b/src/gromacs/nbnxm/opencl/nbnxm_ocl_kernel_pruneonly.clh @@ -155,8 +155,10 @@ nbnxn_kernel_prune_rolling_opencl /* We don't need q, but using float4 in shmem avoids bank conflicts */ const float4 tmp = xq[ai]; const float4 xi = tmp - + (float4)(shift_vec[3 * nb_sci.shift], shift_vec[3 * nb_sci.shift + 1], - shift_vec[3 * nb_sci.shift + 2], 0.0F); + + (float4)(shift_vec[3 * nb_sci.shift], + shift_vec[3 * nb_sci.shift + 1], + shift_vec[3 * nb_sci.shift + 2], + 0.0F); xib[(tidxj + i) * c_clSize + tidxi] = xi; } } diff --git a/src/gromacs/nbnxm/pairlist.cpp b/src/gromacs/nbnxm/pairlist.cpp index 3f9a9f21c5..4c6a529ded 100644 --- a/src/gromacs/nbnxm/pairlist.cpp +++ b/src/gromacs/nbnxm/pairlist.cpp @@ -695,7 +695,9 @@ PairlistSet::PairlistSet(const InteractionLocality locality, const PairlistParam "%d OpenMP threads were requested. Since the non-bonded force buffer reduction " "is prohibitively slow with more than %d threads, we do not allow this. Use %d " "or less OpenMP threads.", - numLists, NBNXN_BUFFERFLAG_MAX_THREADS, NBNXN_BUFFERFLAG_MAX_THREADS); + numLists, + NBNXN_BUFFERFLAG_MAX_THREADS, + NBNXN_BUFFERFLAG_MAX_THREADS); } if (isCpuType_) @@ -753,13 +755,19 @@ static void print_nblist_statistics(FILE* fp, fprintf(fp, "nbl nci %zu ncj %d\n", nbl.ci.size(), nbl.ncjInUse); const int numAtomsJCluster = grid.geometry().numAtomsJCluster; const double numAtomsPerCell = nbl.ncjInUse / static_cast(grid.numCells()) * numAtomsJCluster; - fprintf(fp, "nbl na_cj %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n", nbl.na_cj, rl, - nbl.ncjInUse, nbl.ncjInUse / static_cast(grid.numCells()), numAtomsPerCell, + fprintf(fp, + "nbl na_cj %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n", + nbl.na_cj, + rl, + nbl.ncjInUse, + nbl.ncjInUse / static_cast(grid.numCells()), + numAtomsPerCell, numAtomsPerCell / (0.5 * 4.0 / 3.0 * M_PI * rl * rl * rl * grid.numCells() * numAtomsJCluster / (dims.gridSize[XX] * dims.gridSize[YY] * dims.gridSize[ZZ]))); - fprintf(fp, "nbl average j cell list length %.1f\n", + fprintf(fp, + "nbl average j cell list length %.1f\n", 0.25 * nbl.ncjInUse / std::max(static_cast(nbl.ci.size()), 1.0)); int cs[SHIFTS] = { 0 }; @@ -775,7 +783,10 @@ static void print_nblist_statistics(FILE* fp, j++; } } - fprintf(fp, "nbl cell pairs, total: %zu excl: %d %.1f%%\n", nbl.cj.size(), npexcl, + fprintf(fp, + "nbl cell pairs, total: %zu excl: %d %.1f%%\n", + nbl.cj.size(), + npexcl, 100 * npexcl / std::max(static_cast(nbl.cj.size()), 1.0)); for (int s = 0; s < SHIFTS; s++) { @@ -795,12 +806,21 @@ static void print_nblist_statistics(FILE* fp, const Grid& grid = gridSet.grids()[0]; const Grid::Dimensions& dims = grid.dimensions(); - fprintf(fp, "nbl nsci %zu ncj4 %zu nsi %d excl4 %zu\n", nbl.sci.size(), nbl.cj4.size(), - nbl.nci_tot, nbl.excl.size()); + fprintf(fp, + "nbl nsci %zu ncj4 %zu nsi %d excl4 %zu\n", + nbl.sci.size(), + nbl.cj4.size(), + nbl.nci_tot, + nbl.excl.size()); const int numAtomsCluster = grid.geometry().numAtomsICluster; const double numAtomsPerCell = nbl.nci_tot / static_cast(grid.numClusters()) * numAtomsCluster; - fprintf(fp, "nbl na_c %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n", nbl.na_ci, rl, - nbl.nci_tot, nbl.nci_tot / static_cast(grid.numClusters()), numAtomsPerCell, + fprintf(fp, + "nbl na_c %d rl %g ncp %d per cell %.1f atoms %.1f ratio %.2f\n", + nbl.na_ci, + rl, + nbl.nci_tot, + nbl.nci_tot / static_cast(grid.numClusters()), + numAtomsPerCell, numAtomsPerCell / (0.5 * 4.0 / 3.0 * M_PI * rl * rl * rl * grid.numClusters() * numAtomsCluster / (dims.gridSize[XX] * dims.gridSize[YY] * dims.gridSize[ZZ]))); @@ -837,14 +857,20 @@ static void print_nblist_statistics(FILE* fp, sum_nsp /= nbl.sci.size(); sum_nsp2 /= nbl.sci.size(); } - fprintf(fp, "nbl #cluster-pairs: av %.1f stddev %.1f max %d\n", sum_nsp, - std::sqrt(sum_nsp2 - sum_nsp * sum_nsp), nsp_max); + fprintf(fp, + "nbl #cluster-pairs: av %.1f stddev %.1f max %d\n", + sum_nsp, + std::sqrt(sum_nsp2 - sum_nsp * sum_nsp), + nsp_max); if (!nbl.cj4.empty()) { for (int b = 0; b <= c_gpuNumClusterPerCell; b++) { - fprintf(fp, "nbl j-list #i-subcell %d %7d %4.1f\n", b, c[b], + fprintf(fp, + "nbl j-list #i-subcell %d %7d %4.1f\n", + b, + c[b], 100.0 * c[b] / size_t{ nbl.cj4.size() * c_nbnxnGpuJgroupSize }); } } @@ -1145,8 +1171,8 @@ static void make_cluster_list_supersub(const Grid& iGrid, #if NBNXN_BBXXXX /* Determine all ci1 bb distances in one call with SIMD4 */ const int offset = packedBoundingBoxesIndex(cj) + (cj & (c_packedBoundingBoxesDimSize - 1)); - clusterBoundingBoxDistance2_xxxx_simd4(jGrid.packedBoundingBoxes().data() + offset, ci1, - pbb_ci, d2l); + clusterBoundingBoxDistance2_xxxx_simd4( + jGrid.packedBoundingBoxes().data() + offset, ci1, pbb_ci, d2l); *numDistanceChecks += c_nbnxnGpuClusterSize * 2; #endif @@ -1456,7 +1482,11 @@ static void reallocate_nblist(t_nblist* nl) { fprintf(debug, "reallocating neigborlist (ielec=%d, ivdw=%d, igeometry=%d, type=%d), maxnri=%d\n", - nl->ielec, nl->ivdw, nl->igeometry, nl->type, nl->maxnri); + nl->ielec, + nl->ivdw, + nl->igeometry, + nl->type, + nl->maxnri); } srenew(nl->iinr, nl->maxnri); srenew(nl->gid, nl->maxnri); @@ -1535,7 +1565,8 @@ static void make_fep_list(gmx::ArrayRef atomIndices, gmx_fatal(FARGS, "The Verlet scheme with %dx%d kernels and free-energy only supports up to %zu " "energy groups", - iGrid.geometry().numAtomsICluster, numAtomsJCluster, + iGrid.geometry().numAtomsICluster, + numAtomsJCluster, (sizeof(gid_cj) * 8) / numAtomsJCluster); } @@ -1888,7 +1919,8 @@ static void setExclusionsForIEntry(const Nbnxm::GridSet& gridSet, * Note that here we can not use cj4_ind_end, since the last cj4 * can be only partially filled, so we use cj_ind. */ - const JListRanges ranges(iEntry.cj4_ind_start * c_nbnxnGpuJgroupSize, nbl->work->cj_ind, + const JListRanges ranges(iEntry.cj4_ind_start * c_nbnxnGpuJgroupSize, + nbl->work->cj_ind, gmx::makeConstArrayRef(nbl->cj4)); GMX_ASSERT(nbl->na_ci == c_nbnxnGpuClusterSize, "na_ci should match the GPU cluster size"); @@ -2295,8 +2327,8 @@ gmx_unused static void set_icell_bb_supersub(gmx::ArrayRef bb gmx_unused static void set_icell_bb(const Grid& iGrid, int ci, real shx, real shy, real shz, NbnxnPairlistGpuWork* work) { #if NBNXN_BBXXXX - set_icell_bbxxxx_supersub(iGrid.packedBoundingBoxes(), ci, shx, shy, shz, - work->iSuperClusterData.bbPacked.data()); + set_icell_bbxxxx_supersub( + iGrid.packedBoundingBoxes(), ci, shx, shy, shz, work->iSuperClusterData.bbPacked.data()); #else set_icell_bb_supersub(iGrid.iBoundingBoxes(), ci, shx, shy, shz, work->iSuperClusterData.bb.data()); #endif @@ -2591,8 +2623,7 @@ static void print_nblist_ci_cj(FILE* fp, const NbnxnPairlistCpu& nbl) { for (const nbnxn_ci_t& ciEntry : nbl.ci) { - fprintf(fp, "ci %4d shift %2d ncj %3d\n", ciEntry.ci, ciEntry.shift, - ciEntry.cj_ind_end - ciEntry.cj_ind_start); + fprintf(fp, "ci %4d shift %2d ncj %3d\n", ciEntry.ci, ciEntry.shift, ciEntry.cj_ind_end - ciEntry.cj_ind_start); for (int j = ciEntry.cj_ind_start; j < ciEntry.cj_ind_end; j++) { @@ -2623,8 +2654,7 @@ static void print_nblist_sci_cj(FILE* fp, const NbnxnPairlistGpu& nbl) } } } - fprintf(fp, "ci %4d shift %2d ncj4 %2d ncp %3d\n", sci.sci, sci.shift, - sci.numJClusterGroups(), ncp); + fprintf(fp, "ci %4d shift %2d ncj4 %2d ncp %3d\n", sci.sci, sci.shift, sci.numJClusterGroups(), ncp); } } @@ -2972,19 +3002,19 @@ static void makeClusterListWrapper(NbnxnPairlistCpu* nbl, switch (kernelType) { case ClusterDistanceKernelType::CpuPlainC: - makeClusterListSimple(jGrid, nbl, ci, firstCell, lastCell, excludeSubDiagonal, - nbat->x().data(), rlist2, rbb2, numDistanceChecks); + makeClusterListSimple( + jGrid, nbl, ci, firstCell, lastCell, excludeSubDiagonal, nbat->x().data(), rlist2, rbb2, numDistanceChecks); break; #ifdef GMX_NBNXN_SIMD_4XN case ClusterDistanceKernelType::CpuSimd_4xM: - makeClusterListSimd4xn(jGrid, nbl, ci, firstCell, lastCell, excludeSubDiagonal, - nbat->x().data(), rlist2, rbb2, numDistanceChecks); + makeClusterListSimd4xn( + jGrid, nbl, ci, firstCell, lastCell, excludeSubDiagonal, nbat->x().data(), rlist2, rbb2, numDistanceChecks); break; #endif #ifdef GMX_NBNXN_SIMD_2XNN case ClusterDistanceKernelType::CpuSimd_2xMM: - makeClusterListSimd2xnn(jGrid, nbl, ci, firstCell, lastCell, excludeSubDiagonal, - nbat->x().data(), rlist2, rbb2, numDistanceChecks); + makeClusterListSimd2xnn( + jGrid, nbl, ci, firstCell, lastCell, excludeSubDiagonal, nbat->x().data(), rlist2, rbb2, numDistanceChecks); break; #endif default: GMX_ASSERT(false, "Unhandled kernel type"); @@ -3006,8 +3036,8 @@ static void makeClusterListWrapper(NbnxnPairlistGpu* nbl, { for (int cj = firstCell; cj <= lastCell; cj++) { - make_cluster_list_supersub(iGrid, jGrid, nbl, ci, cj, excludeSubDiagonal, nbat->xstride, - nbat->x().data(), rlist2, rbb2, numDistanceChecks); + make_cluster_list_supersub( + iGrid, jGrid, nbl, ci, cj, excludeSubDiagonal, nbat->xstride, nbat->x().data(), rlist2, rbb2, numDistanceChecks); } } @@ -3215,8 +3245,11 @@ static void nbnxn_make_pairlist_part(const Nbnxm::GridSet& gridSet, if (debug) { - fprintf(debug, "nbl nc_i %d col.av. %.1f ci_block %d\n", iGrid.numCells(), - iGrid.numCells() / static_cast(iGrid.numColumns()), ci_block); + fprintf(debug, + "nbl nc_i %d col.av. %.1f ci_block %d\n", + iGrid.numCells(), + iGrid.numCells() / static_cast(iGrid.numColumns()), + ci_block); } numDistanceChecks = 0; @@ -3374,8 +3407,14 @@ static void nbnxn_make_pairlist_part(const Nbnxm::GridSet& gridSet, set_icell_bb(iGrid, ci, shx, shy, shz, nbl->work.get()); - icell_set_x(cell0_i + ci, shx, shy, shz, nbat->xstride, nbat->x().data(), - kernelType, nbl->work.get()); + icell_set_x(cell0_i + ci, + shx, + shy, + shz, + nbat->xstride, + nbat->x().data(), + kernelType, + nbl->work.get()); for (int cx = cxf; cx <= cxl; cx++) { @@ -3524,9 +3563,18 @@ static void nbnxn_make_pairlist_part(const Nbnxm::GridSet& gridSet, /* For f buffer flags with simple lists */ ncj_old_j = getNumSimpleJClustersInList(*nbl); - makeClusterListWrapper(nbl, iGrid, ci, jGrid, firstCell, lastCell, - excludeSubDiagonal, nbat, rlist2, rbb2, - kernelType, &numDistanceChecks); + makeClusterListWrapper(nbl, + iGrid, + ci, + jGrid, + firstCell, + lastCell, + excludeSubDiagonal, + nbat, + rlist2, + rbb2, + kernelType, + &numDistanceChecks); if (bFBufferFlag) { @@ -3542,14 +3590,24 @@ static void nbnxn_make_pairlist_part(const Nbnxm::GridSet& gridSet, if (!exclusions.empty()) { /* Set the exclusions for this ci list */ - setExclusionsForIEntry(gridSet, nbl, excludeSubDiagonal, na_cj_2log, - *getOpenIEntry(nbl), exclusions); + setExclusionsForIEntry( + gridSet, nbl, excludeSubDiagonal, na_cj_2log, *getOpenIEntry(nbl), exclusions); } if (haveFep) { - make_fep_list(gridSet.atomIndices(), nbat, nbl, excludeSubDiagonal, - getOpenIEntry(nbl), shx, shy, shz, rl_fep2, iGrid, jGrid, nbl_fep); + make_fep_list(gridSet.atomIndices(), + nbat, + nbl, + excludeSubDiagonal, + getOpenIEntry(nbl), + shx, + shy, + shz, + rl_fep2, + iGrid, + jGrid, + nbl_fep); } /* Close this ci list */ @@ -3639,7 +3697,12 @@ static void print_reduction_cost(gmx::ArrayRef flags, int n const auto numFlags = static_cast(flags.size()); fprintf(debug, "nbnxn reduction: #flag %zu #list %d elem %4.2f, keep %4.2f copy %4.2f red %4.2f\n", - flags.size(), nout, nelem / numFlags, nkeep / numFlags, ncopy / numFlags, nred / numFlags); + flags.size(), + nout, + nelem / numFlags, + nkeep / numFlags, + ncopy / numFlags, + nred / numFlags); } /* Copies the list entries from src to dest when cjStart <= *cjGlobal < cjEnd. @@ -3766,8 +3829,8 @@ static void rebalanceSimpleLists(gmx::ArrayRef srcSet, } else { - copySelectedListRange(srcCi, src, &dest, flag, iFlagShift, - jFlagShift, t); + copySelectedListRange( + srcCi, src, &dest, flag, iFlagShift, jFlagShift, t); } } cjGlobal += ncj; @@ -3950,8 +4013,8 @@ void PairlistSet::constructPairlists(const Nbnxm::GridSet& gridSet, if (!isCpuType_ && minimumIlistCountForGpuBalancing > 0) { - get_nsubpair_target(gridSet, locality_, rlist, minimumIlistCountForGpuBalancing, - &nsubpair_target, &nsubpair_tot_est); + get_nsubpair_target( + gridSet, locality_, rlist, minimumIlistCountForGpuBalancing, &nsubpair_target, &nsubpair_tot_est); } else { @@ -4036,17 +4099,43 @@ void PairlistSet::constructPairlists(const Nbnxm::GridSet& gridSet, /* Divide the i cells equally over the pairlists */ if (isCpuType_) { - nbnxn_make_pairlist_part(gridSet, iGrid, jGrid, &work, nbat, exclusions, rlist, - params_.pairlistType, ci_block, nbat->bUseBufferFlags, - nsubpair_target, progBal, nsubpair_tot_est, th, - numLists, &cpuLists_[th], fepListPtr); + nbnxn_make_pairlist_part(gridSet, + iGrid, + jGrid, + &work, + nbat, + exclusions, + rlist, + params_.pairlistType, + ci_block, + nbat->bUseBufferFlags, + nsubpair_target, + progBal, + nsubpair_tot_est, + th, + numLists, + &cpuLists_[th], + fepListPtr); } else { - nbnxn_make_pairlist_part(gridSet, iGrid, jGrid, &work, nbat, exclusions, rlist, - params_.pairlistType, ci_block, nbat->bUseBufferFlags, - nsubpair_target, progBal, nsubpair_tot_est, th, - numLists, &gpuLists_[th], fepListPtr); + nbnxn_make_pairlist_part(gridSet, + iGrid, + jGrid, + &work, + nbat, + exclusions, + rlist, + params_.pairlistType, + ci_block, + nbat->bUseBufferFlags, + nsubpair_target, + progBal, + nsubpair_tot_est, + th, + numLists, + &gpuLists_[th], + fepListPtr); } work.cycleCounter.stop(); @@ -4217,8 +4306,12 @@ void PairlistSets::construct(const InteractionLocality iLocality, "exclusions should either be empty or the number of lists should match the number of " "local i-atoms"); - pairlistSet(iLocality).constructPairlists(gridSet, pairSearch->work(), nbat, exclusions, - minimumIlistCountForGpuBalancing_, nrnb, + pairlistSet(iLocality).constructPairlists(gridSet, + pairSearch->work(), + nbat, + exclusions, + minimumIlistCountForGpuBalancing_, + nrnb, &pairSearch->cycleCounting_); if (iLocality == InteractionLocality::Local) diff --git a/src/gromacs/nbnxm/pairlist_tuning.cpp b/src/gromacs/nbnxm/pairlist_tuning.cpp index 6d0afa41ce..c9c3f3df8d 100644 --- a/src/gromacs/nbnxm/pairlist_tuning.cpp +++ b/src/gromacs/nbnxm/pairlist_tuning.cpp @@ -272,8 +272,7 @@ void increaseNstlist(FILE* fp, rlist_max = (rlistWithReferenceNstlist + rlist_inc) * std::cbrt(listfac_max) - rlist_inc; if (debug) { - fprintf(debug, "nstlist tuning: rlist_inc %.3f rlist_ok %.3f rlist_max %.3f\n", rlist_inc, - rlist_ok, rlist_max); + fprintf(debug, "nstlist tuning: rlist_inc %.3f rlist_ok %.3f rlist_max %.3f\n", rlist_inc, rlist_ok, rlist_max); } nstlist_prev = nstlist_orig; @@ -286,8 +285,8 @@ void increaseNstlist(FILE* fp, } /* Set the pair-list buffer size in ir */ - rlist_new = calcVerletBufferSize(*mtop, det(box), *ir, ir->nstlist, ir->nstlist - mtsFactor, - -1, listSetup); + rlist_new = calcVerletBufferSize( + *mtop, det(box), *ir, ir->nstlist, ir->nstlist - mtsFactor, -1, listSetup); /* Does rlist fit in the box? */ bBox = (gmx::square(rlist_new) < max_cutoff2(ir->pbcType, box)); @@ -311,8 +310,12 @@ void increaseNstlist(FILE* fp, if (debug) { - fprintf(debug, "nstlist %d rlist %.3f bBox %s bDD %s\n", ir->nstlist, rlist_new, - gmx::boolToString(bBox), gmx::boolToString(bDD)); + fprintf(debug, + "nstlist %d rlist %.3f bBox %s bDD %s\n", + ir->nstlist, + rlist_new, + gmx::boolToString(bBox), + gmx::boolToString(bDD)); } bCont = FALSE; @@ -350,8 +353,12 @@ void increaseNstlist(FILE* fp, } else if (ir->nstlist != nstlist_orig || rlist_new != ir->rlist) { - sprintf(buf, "Changing nstlist from %d to %d, rlist from %g to %g", nstlist_orig, - ir->nstlist, ir->rlist, rlist_new); + sprintf(buf, + "Changing nstlist from %d to %d, rlist from %g to %g", + nstlist_orig, + ir->nstlist, + ir->rlist, + rlist_new); if (MASTER(cr)) { fprintf(stderr, "%s\n\n", buf); @@ -431,8 +438,8 @@ static void setDynamicPairlistPruningParameters(const t_inputrec* ir, */ int listLifetime = tunedNstlistPrune - (useGpuList ? 0 : mtsFactor); listParams->nstlistPrune = tunedNstlistPrune; - listParams->rlistInner = calcVerletBufferSize(*mtop, det(box), *ir, tunedNstlistPrune, - listLifetime, -1, listSetup); + listParams->rlistInner = calcVerletBufferSize( + *mtop, det(box), *ir, tunedNstlistPrune, listLifetime, -1, listSetup); /* On the GPU we apply the dynamic pruning in a rolling fashion * every c_nbnxnGpuRollingListPruningInterval steps, @@ -497,8 +504,8 @@ static std::string formatListSetup(const std::string& listName, std::string nstListFormat = "%" + gmx::formatString("%zu", gmx::formatString("%d", nstListForSpacing).size()) + "d"; listSetup += gmx::formatString(nstListFormat.c_str(), nstList); - listSetup += gmx::formatString(" steps, buffer %.3f nm, rlist %.3f nm\n", - rList - interactionCutoff, rList); + listSetup += gmx::formatString( + " steps, buffer %.3f nm, rlist %.3f nm\n", rList - interactionCutoff, rList); return listSetup; } @@ -554,8 +561,8 @@ void setupDynamicPairlistPruning(const gmx::MDLogger& mdlog, listParams->nstlistPrune = c_nbnxnDynamicListPruningMinLifetime; } - setDynamicPairlistPruningParameters(ir, mtop, box, useGpuList, ls, userSetNstlistPrune, ic, - listParams); + setDynamicPairlistPruningParameters( + ir, mtop, box, useGpuList, ls, userSetNstlistPrune, ic, listParams); if (listParams->useDynamicPruning && useGpuList) { @@ -563,10 +570,11 @@ void setupDynamicPairlistPruning(const gmx::MDLogger& mdlog, * rolling pruning interval slightly shorter than nstlistTune, * thus giving correct results, but a slightly lower efficiency. */ - GMX_RELEASE_ASSERT(listParams->nstlistPrune >= c_nbnxnGpuRollingListPruningInterval, ("With dynamic list pruning on GPUs pruning frequency must be at least as large as the rolling pruning interval (" - + std::to_string(c_nbnxnGpuRollingListPruningInterval) - + ").") - .c_str()); + GMX_RELEASE_ASSERT(listParams->nstlistPrune >= c_nbnxnGpuRollingListPruningInterval, + ("With dynamic list pruning on GPUs pruning frequency must be at " + "least as large as the rolling pruning interval (" + + std::to_string(c_nbnxnGpuRollingListPruningInterval) + ").") + .c_str()); listParams->numRollingPruningParts = listParams->nstlistPrune / c_nbnxnGpuRollingListPruningInterval; } @@ -582,11 +590,13 @@ void setupDynamicPairlistPruning(const gmx::MDLogger& mdlog, if (listParams->useDynamicPruning) { mesg += gmx::formatString( - "Using a dual %dx%d pair-list setup updated with dynamic%s pruning:\n", ls.cluster_size_i, - ls.cluster_size_j, listParams->numRollingPruningParts > 1 ? ", rolling" : ""); + "Using a dual %dx%d pair-list setup updated with dynamic%s pruning:\n", + ls.cluster_size_i, + ls.cluster_size_j, + listParams->numRollingPruningParts > 1 ? ", rolling" : ""); mesg += formatListSetup("outer", ir->nstlist, ir->nstlist, listParams->rlistOuter, interactionCutoff); - mesg += formatListSetup("inner", listParams->nstlistPrune, ir->nstlist, - listParams->rlistInner, interactionCutoff); + mesg += formatListSetup( + "inner", listParams->nstlistPrune, ir->nstlist, listParams->rlistInner, interactionCutoff); } else { @@ -596,14 +606,14 @@ void setupDynamicPairlistPruning(const gmx::MDLogger& mdlog, if (supportsDynamicPairlistGenerationInterval(*ir)) { const VerletbufListSetup listSetup1x1 = { 1, 1 }; - const real rlistOuter = calcVerletBufferSize(*mtop, det(box), *ir, ir->nstlist, - ir->nstlist - 1, -1, listSetup1x1); - real rlistInner = rlistOuter; + const real rlistOuter = calcVerletBufferSize( + *mtop, det(box), *ir, ir->nstlist, ir->nstlist - 1, -1, listSetup1x1); + real rlistInner = rlistOuter; if (listParams->useDynamicPruning) { int listLifeTime = listParams->nstlistPrune - (useGpuList ? 0 : 1); - rlistInner = calcVerletBufferSize(*mtop, det(box), *ir, listParams->nstlistPrune, - listLifeTime, -1, listSetup1x1); + rlistInner = calcVerletBufferSize( + *mtop, det(box), *ir, listParams->nstlistPrune, listLifeTime, -1, listSetup1x1); } mesg += gmx::formatString( @@ -612,8 +622,8 @@ void setupDynamicPairlistPruning(const gmx::MDLogger& mdlog, if (listParams->useDynamicPruning) { mesg += formatListSetup("outer", ir->nstlist, ir->nstlist, rlistOuter, interactionCutoff); - mesg += formatListSetup("inner", listParams->nstlistPrune, ir->nstlist, rlistInner, - interactionCutoff); + mesg += formatListSetup( + "inner", listParams->nstlistPrune, ir->nstlist, rlistInner, interactionCutoff); } else { diff --git a/src/gromacs/nbnxm/pairsearch.cpp b/src/gromacs/nbnxm/pairsearch.cpp index be981232e2..d606779b8c 100644 --- a/src/gromacs/nbnxm/pairsearch.cpp +++ b/src/gromacs/nbnxm/pairsearch.cpp @@ -54,8 +54,11 @@ void SearchCycleCounting::printCycles(FILE* fp, gmx::ArrayRef work) const { fprintf(fp, "\n"); - fprintf(fp, "ns %4d grid %4.1f search %4.1f", cc_[enbsCCgrid].count(), - cc_[enbsCCgrid].averageMCycles(), cc_[enbsCCsearch].averageMCycles()); + fprintf(fp, + "ns %4d grid %4.1f search %4.1f", + cc_[enbsCCgrid].count(), + cc_[enbsCCgrid].averageMCycles(), + cc_[enbsCCsearch].averageMCycles()); if (work.size() > 1) { diff --git a/src/gromacs/nbnxm/pairsearch.h b/src/gromacs/nbnxm/pairsearch.h index bd5529dbd5..c4c92969a1 100644 --- a/src/gromacs/nbnxm/pairsearch.h +++ b/src/gromacs/nbnxm/pairsearch.h @@ -194,8 +194,18 @@ public: { cycleCounting_.start(enbsCCgrid); - gridSet_.putOnGrid(box, ddZone, lowerCorner, upperCorner, updateGroupsCog, atomRange, - atomDensity, atomInfo, x, numAtomsMoved, move, nbat); + gridSet_.putOnGrid(box, + ddZone, + lowerCorner, + upperCorner, + updateGroupsCog, + atomRange, + atomDensity, + atomInfo, + x, + numAtomsMoved, + move, + nbat); cycleCounting_.stop(enbsCCgrid); } diff --git a/src/gromacs/nbnxm/prunekerneldispatch.cpp b/src/gromacs/nbnxm/prunekerneldispatch.cpp index 1ad8ef347a..9b98e5f92f 100644 --- a/src/gromacs/nbnxm/prunekerneldispatch.cpp +++ b/src/gromacs/nbnxm/prunekerneldispatch.cpp @@ -105,7 +105,8 @@ void nonbonded_verlet_t::dispatchPruneKernelGpu(int64_t step) (pairlistSets().numStepsWithPairlist(step) % (2 * pairlistSets().params().mtsFactor) == 0); Nbnxm::gpu_launch_kernel_pruneonly( - gpu_nbv, stepIsEven ? gmx::InteractionLocality::Local : gmx::InteractionLocality::NonLocal, + gpu_nbv, + stepIsEven ? gmx::InteractionLocality::Local : gmx::InteractionLocality::NonLocal, pairlistSets().params().numRollingPruningParts); wallcycle_sub_stop(wcycle_, ewcsLAUNCH_GPU_NONBONDED); diff --git a/src/gromacs/onlinehelp/helpmanager.cpp b/src/gromacs/onlinehelp/helpmanager.cpp index de9dfcedd8..c61927b459 100644 --- a/src/gromacs/onlinehelp/helpmanager.cpp +++ b/src/gromacs/onlinehelp/helpmanager.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2012,2014,2015,2017,2019, by the GROMACS development team, led by + * Copyright (c) 2012,2014,2015,2017,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -134,8 +134,8 @@ void HelpManager::enterTopic(const char* name) } else { - GMX_THROW(InvalidInputError(formatString("Help topic '%s' has no subtopic '%s'", - impl_->currentTopicAsString().c_str(), name))); + GMX_THROW(InvalidInputError(formatString( + "Help topic '%s' has no subtopic '%s'", impl_->currentTopicAsString().c_str(), name))); } } impl_->topicStack_.push_back(newTopic); diff --git a/src/gromacs/onlinehelp/helpwritercontext.cpp b/src/gromacs/onlinehelp/helpwritercontext.cpp index f89611ab9c..68f5ab8edd 100644 --- a/src/gromacs/onlinehelp/helpwritercontext.cpp +++ b/src/gromacs/onlinehelp/helpwritercontext.cpp @@ -445,8 +445,7 @@ std::string HelpWriterContext::Impl::replaceLinks(const std::string& input) cons if (state_->links_ != nullptr) { HelpLinks::Impl::LinkList::const_iterator link; - for (link = state_->links_->impl_->links_.begin(); - link != state_->links_->impl_->links_.end(); ++link) + for (link = state_->links_->impl_->links_.begin(); link != state_->links_->impl_->links_.end(); ++link) { result = replaceAllWords(result, link->linkName, link->replacement); } diff --git a/src/gromacs/options/basicoptions.h b/src/gromacs/options/basicoptions.h index 65e4895680..d432055b26 100644 --- a/src/gromacs/options/basicoptions.h +++ b/src/gromacs/options/basicoptions.h @@ -563,7 +563,9 @@ private: AbstractOptionStorage* createStorage(const OptionManagerContainer& /*managers*/) const override { // TODO: Implement storeCount() if necessary. - return internal::createEnumOptionStorage(*this, enumValues_, enumValuesCount_, + return internal::createEnumOptionStorage(*this, + enumValues_, + enumValuesCount_, convertToInt(MyBase::defaultValue()), convertToInt(MyBase::defaultValueIfSet()), std::make_unique>( @@ -675,7 +677,9 @@ private: AbstractOptionStorage* createStorage(const OptionManagerContainer& /*managers*/) const override { // TODO: Implement storeCount() if necessary. - return internal::createEnumOptionStorage(*this, enumValues_, enumValuesCount_, + return internal::createEnumOptionStorage(*this, + enumValues_, + enumValuesCount_, convertToInt(MyBase::defaultValue()), convertToInt(MyBase::defaultValueIfSet()), std::make_unique>( diff --git a/src/gromacs/options/filenameoption.cpp b/src/gromacs/options/filenameoption.cpp index 9df3722459..f93e082e91 100644 --- a/src/gromacs/options/filenameoption.cpp +++ b/src/gromacs/options/filenameoption.cpp @@ -360,7 +360,8 @@ std::string FileNameOptionStorage::processValue(const std::string& value) const "File '%s' cannot be used by GROMACS because it " "does not have a recognizable extension.\n" "The following extensions are possible for this option:\n %s", - value.c_str(), joinStrings(extensions(), ", ").c_str()); + value.c_str(), + joinStrings(extensions(), ", ").c_str()); GMX_THROW(InvalidInputError(message)); } else if (!isValidType(fileType)) @@ -368,7 +369,8 @@ std::string FileNameOptionStorage::processValue(const std::string& value) const std::string message = formatString( "File name '%s' cannot be used for this option.\n" "Only the following extensions are possible:\n %s", - value.c_str(), joinStrings(extensions(), ", ").c_str()); + value.c_str(), + joinStrings(extensions(), ", ").c_str()); GMX_THROW(InvalidInputError(message)); } return value; diff --git a/src/gromacs/options/filenameoptionmanager.cpp b/src/gromacs/options/filenameoptionmanager.cpp index 54a4d407ff..697ae3bfb8 100644 --- a/src/gromacs/options/filenameoptionmanager.cpp +++ b/src/gromacs/options/filenameoptionmanager.cpp @@ -211,7 +211,8 @@ std::string FileNameOptionManager::completeFileName(const std::string& value, co std::string message = formatString( "File '%s' does not exist or is not accessible.\n" "The following extensions were tried to complete the file name:\n %s", - value.c_str(), joinStrings(option.extensions(), ", ").c_str()); + value.c_str(), + joinStrings(option.extensions(), ", ").c_str()); GMX_THROW(InvalidInputError(message)); } } @@ -276,7 +277,8 @@ std::string FileNameOptionManager::completeDefaultFileName(const std::string& "No file name was provided, and the default file " "'%s' does not exist or is not accessible.\n" "The following extensions were tried to complete the file name:\n %s", - prefix.c_str(), joinStrings(option.extensions(), ", ").c_str()); + prefix.c_str(), + joinStrings(option.extensions(), ", ").c_str()); GMX_THROW(InvalidInputError(message)); } else if (option.isRequired()) @@ -285,7 +287,8 @@ std::string FileNameOptionManager::completeDefaultFileName(const std::string& "Required option was not provided, and the default file " "'%s' does not exist or is not accessible.\n" "The following extensions were tried to complete the file name:\n %s", - prefix.c_str(), joinStrings(option.extensions(), ", ").c_str()); + prefix.c_str(), + joinStrings(option.extensions(), ", ").c_str()); GMX_THROW(InvalidInputError(message)); } // We get here with the legacy optional behavior. diff --git a/src/gromacs/options/timeunitmanager.cpp b/src/gromacs/options/timeunitmanager.cpp index 0dc7a4f2d4..2b09594759 100644 --- a/src/gromacs/options/timeunitmanager.cpp +++ b/src/gromacs/options/timeunitmanager.cpp @@ -69,8 +69,9 @@ namespace * * These must correspond to the TimeUnit enum in the header! */ -const EnumerationArray c_timeUnitNames = { { "fs", "ps", "ns", "us", "ms", - "s" } }; +const EnumerationArray c_timeUnitNames = { + { "fs", "ps", "ns", "us", "ms", "s" } +}; /*! \brief * Scaling factors from each time unit to internal units (=picoseconds). * @@ -145,7 +146,8 @@ void TimeUnitBehavior::setTimeUnitFromEnvironment() "Time unit provided with environment variable GMXTIMEUNIT=%s " "is not recognized as a valid time unit.\n" "Possible values are: %s", - value, joinStrings(c_timeUnitNames, ", ").c_str()); + value, + joinStrings(c_timeUnitNames, ", ").c_str()); GMX_THROW(InvalidInputError(message)); } setTimeUnit(result); diff --git a/src/gromacs/options/treesupport.cpp b/src/gromacs/options/treesupport.cpp index d8d14b58ff..d4b5d37192 100644 --- a/src/gromacs/options/treesupport.cpp +++ b/src/gromacs/options/treesupport.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2016,2017,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2016,2017,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -316,8 +316,9 @@ void checkForUnknownOptionsInKeyValueTree(const KeyValueTreeObject& tree, const helper.processOptionSection(options.rootSection()); if (helper.hasUnknownPaths()) { - std::string paths(formatAndJoin(helper.unknownPaths(), "\n ", - [](const KeyValueTreePath& path) { return path.toString(); })); + std::string paths(formatAndJoin(helper.unknownPaths(), "\n ", [](const KeyValueTreePath& path) { + return path.toString(); + })); std::string message("Unknown input values:\n " + paths); GMX_THROW(InvalidInputError(message)); } diff --git a/src/gromacs/pbcutil/mshift.cpp b/src/gromacs/pbcutil/mshift.cpp index 99824fc172..b71484d1ea 100644 --- a/src/gromacs/pbcutil/mshift.cpp +++ b/src/gromacs/pbcutil/mshift.cpp @@ -124,7 +124,8 @@ static bool mk_igraph(EdgesGenerator* edgesG, int ftype, const T& il, int at_end "You are probably trying to use a trajectory which does " "not match the first %d atoms of the run input file.\n" "You can make a matching run input file with gmx convert-tpr.", - at_end, at_end); + at_end, + at_end); } if (ftype == F_SETTLE) { @@ -186,10 +187,14 @@ void p_graph(FILE* log, const char* title, const t_graph* g) { if (!g->edges[i].empty()) { - fprintf(log, "%5d%7d%7d%7d %1s%5zu", g->edgeAtomBegin + i + 1, - g->ishift[g->edgeAtomBegin + i][XX], g->ishift[g->edgeAtomBegin + i][YY], + fprintf(log, + "%5d%7d%7d%7d %1s%5zu", + g->edgeAtomBegin + i + 1, + g->ishift[g->edgeAtomBegin + i][XX], + g->ishift[g->edgeAtomBegin + i][YY], g->ishift[g->edgeAtomBegin + i][ZZ], - (!g->edgeColor.empty()) ? cc[g->edgeColor[i]] : " ", g->edges[i].size()); + (!g->edgeColor.empty()) ? cc[g->edgeColor[i]] : " ", + g->edges[i].size()); for (const int edge : g->edges[i]) { fprintf(log, " %5d", edge + 1); @@ -293,7 +298,9 @@ static gmx_bool determine_graph_parts(const EdgesGenerator& edgesG, ArrayRef 0); @@ -625,8 +632,17 @@ static int mk_grey(ArrayRef edgeColor, "mk_grey: shifts for atom %d due to atom %d\n" "are (%d,%d,%d), should be (%d,%d,%d)\n" "dx = (%g,%g,%g)\n", - aj + 1, ai + 1, is_aj[XX], is_aj[YY], is_aj[ZZ], g->ishift[aj][XX], - g->ishift[aj][YY], g->ishift[aj][ZZ], dx[XX], dx[YY], dx[ZZ]); + aj + 1, + ai + 1, + is_aj[XX], + is_aj[YY], + is_aj[ZZ], + g->ishift[aj][XX], + g->ishift[aj][YY], + g->ishift[aj][ZZ], + dx[XX], + dx[YY], + dx[ZZ]); } (*nerror)++; } @@ -788,7 +804,9 @@ void mk_mshift(FILE* log, t_graph* g, PbcType pbcType, const matrix box, const r "There are inconsistent shifts over periodic boundaries in a molecule type " "consisting of %d atoms. The longest distance involved in such interactions is " "%.3f nm which is %s half the box length.", - g->shiftAtomEnd, maxDistance, maxDistance >= 0.5 * minBoxSize ? "above" : "close to"); + g->shiftAtomEnd, + maxDistance, + maxDistance >= 0.5 * minBoxSize ? "above" : "close to"); switch (g->parts) { diff --git a/src/gromacs/pbcutil/pbc.cpp b/src/gromacs/pbcutil/pbc.cpp index a97372f88f..dc66f20558 100644 --- a/src/gromacs/pbcutil/pbc.cpp +++ b/src/gromacs/pbcutil/pbc.cpp @@ -63,8 +63,9 @@ #include "gromacs/utility/gmxassert.h" #include "gromacs/utility/smalloc.h" -const gmx::EnumerationArray c_pbcTypeNames = { { "xyz", "no", "xy", "screw", - "unset" } }; +const gmx::EnumerationArray c_pbcTypeNames = { + { "xyz", "no", "xy", "screw", "unset" } +}; /* Skip 0 so we have more chance of detecting if we forgot to call set_pbc. */ enum @@ -233,7 +234,9 @@ PbcType guessPbcType(const matrix box) fprintf(stderr, "WARNING: Unsupported box diagonal %f %f %f, " "will not use periodic boundary conditions\n\n", - box[XX][XX], box[YY][YY], box[ZZ][ZZ]); + box[XX][XX], + box[YY][YY], + box[ZZ][ZZ]); bWarnedGuess = TRUE; } pbcType = PbcType::No; @@ -550,9 +553,18 @@ static void low_set_pbc(t_pbc* pbc, PbcType pbcType, const ivec dd_pbc, const ma fprintf(debug, " tricvec %2d = %2d %2d %2d %5.2f %5.2f " "%5.2f %5.2f %5.2f %5.2f %5.2f %5.2f\n", - pbc->ntric_vec, i, j, k, sqrt(d2old), - sqrt(d2new), trial[XX], trial[YY], trial[ZZ], - pos[XX], pos[YY], pos[ZZ]); + pbc->ntric_vec, + i, + j, + k, + sqrt(d2old), + sqrt(d2new), + trial[XX], + trial[YY], + trial[ZZ], + pos[XX], + pos[YY], + pos[ZZ]); } } } diff --git a/src/gromacs/pbcutil/pbcmethods.cpp b/src/gromacs/pbcutil/pbcmethods.cpp index 3b8f887fee..400c1c8459 100644 --- a/src/gromacs/pbcutil/pbcmethods.cpp +++ b/src/gromacs/pbcutil/pbcmethods.cpp @@ -124,14 +124,16 @@ void calc_pbc_cluster(int ecenter, int nrefat, t_topology* top, PbcType pbcType, gmx_fatal(FARGS, "Molecule %d marked for clustering but not atom %d in it - check your " "index!", - i + 1, j + 1); + i + 1, + j + 1); } else if (!bMol[i] && bTmp[j]) { gmx_fatal(FARGS, "Atom %d marked for clustering but not molecule %d - this is an internal " "error...", - j + 1, i + 1); + j + 1, + i + 1); } else if (bMol[i]) { @@ -297,7 +299,10 @@ void put_molecule_com_in_box(int unitcell_enum, fprintf(debug, "\nShifting position of molecule %d " "by %8.3f %8.3f %8.3f\n", - i + 1, shift[XX], shift[YY], shift[ZZ]); + i + 1, + shift[XX], + shift[YY], + shift[ZZ]); } for (j = mols->index[i]; (j < mols->index[i + 1] && j < natoms); j++) { @@ -355,8 +360,12 @@ void put_residue_com_in_box(int unitcell_enum, fprintf(debug, "\nShifting position of residue %d (atoms %d-%d) " "by %g,%g,%g\n", - atom[res_start].resind + 1, res_start + 1, res_end + 1, shift[XX], - shift[YY], shift[ZZ]); + atom[res_start].resind + 1, + res_start + 1, + res_end + 1, + shift[XX], + shift[YY], + shift[ZZ]); } for (j = res_start; j < res_end; j++) { diff --git a/src/gromacs/pbcutil/rmpbc.cpp b/src/gromacs/pbcutil/rmpbc.cpp index a355d6df66..ee79717113 100644 --- a/src/gromacs/pbcutil/rmpbc.cpp +++ b/src/gromacs/pbcutil/rmpbc.cpp @@ -100,7 +100,8 @@ static t_graph* gmx_rmpbc_get_graph(gmx_rmpbc_t gpbc, PbcType pbcType, int natom { gmx_fatal(FARGS, "Structure or trajectory file has more atoms (%d) than the topology (%d)", - natoms, gpbc->natoms_init); + natoms, + gpbc->natoms_init); } gpbc->ngraph++; srenew(gpbc->graph, gpbc->ngraph); diff --git a/src/gromacs/pbcutil/tests/com.cpp b/src/gromacs/pbcutil/tests/com.cpp index 84249c46b1..7442b01326 100644 --- a/src/gromacs/pbcutil/tests/com.cpp +++ b/src/gromacs/pbcutil/tests/com.cpp @@ -165,8 +165,8 @@ void COMInPlaceTest::runTestMolecule(const matrix box) auto unitcell = std::get<0>(params); auto center = std::get<1>(params); auto pbcType = std::get<2>(params); - placeCoordinatesWithCOMInBox(pbcType, unitcell, center, box, testCoordinates_, testTopology_, - COMShiftType::Molecule); + placeCoordinatesWithCOMInBox( + pbcType, unitcell, center, box, testCoordinates_, testTopology_, COMShiftType::Molecule); std::string testString = "Molecule " + std::string(unitCellTypeNames(unitcell)) + std::string(centerTypeNames(center)) + c_pbcTypeNames[pbcType] + c_pbcTypeNames[guessPbcType(box)]; @@ -179,8 +179,8 @@ void COMInPlaceTest::runTestResidue(const matrix box) auto unitcell = std::get<0>(params); auto center = std::get<1>(params); auto pbcType = std::get<2>(params); - placeCoordinatesWithCOMInBox(pbcType, unitcell, center, box, testCoordinates_, testTopology_, - COMShiftType::Residue); + placeCoordinatesWithCOMInBox( + pbcType, unitcell, center, box, testCoordinates_, testTopology_, COMShiftType::Residue); std::string testString = "Residue " + std::string(unitCellTypeNames(unitcell)) + std::string(centerTypeNames(center)) + c_pbcTypeNames[pbcType] + c_pbcTypeNames[guessPbcType(box)]; diff --git a/src/gromacs/pulling/output.cpp b/src/gromacs/pulling/output.cpp index e534415e70..627700a3b2 100644 --- a/src/gromacs/pulling/output.cpp +++ b/src/gromacs/pulling/output.cpp @@ -212,13 +212,13 @@ static void pull_print_x(FILE* out, pull_t* pull, double t) pcrdHistory = &pull->coordForceHistory->pullCoordinateSums[c]; numValuesInSum = pull->coordForceHistory->numValuesInXSum; - pull_print_coord_dr(out, pull->params, pcrd.params, *pcrdHistory, pcrdHistory->valueRef, - numValuesInSum); + pull_print_coord_dr( + out, pull->params, pcrd.params, *pcrdHistory, pcrdHistory->valueRef, numValuesInSum); } else { - pull_print_coord_dr(out, pull->params, pcrd.params, pcrd.spatialData, pcrd.value_ref, - numValuesInSum); + pull_print_coord_dr( + out, pull->params, pcrd.params, pcrd.spatialData, pcrd.value_ref, numValuesInSum); } if (pull->params.bPrintCOM) @@ -249,7 +249,8 @@ static void pull_print_x(FILE* out, pull_t* pull, double t) { if (pull->bXOutAverage) { - fprintf(out, "\t%g", + fprintf(out, + "\t%g", pull->coordForceHistory->pullGroupSums[pcrd.params.group[0]].x[m] / numValuesInSum); } @@ -268,7 +269,8 @@ static void pull_print_x(FILE* out, pull_t* pull, double t) { if (pull->bXOutAverage) { - fprintf(out, "\t%g", + fprintf(out, + "\t%g", pull->coordForceHistory->pullGroupSums[pcrd.params.group[g]].x[m] / numValuesInSum); } @@ -297,7 +299,8 @@ static void pull_print_f(FILE* out, const pull_t* pull, double t) { for (size_t c = 0; c < pull->coord.size(); c++) { - fprintf(out, "\t%g", + fprintf(out, + "\t%g", pull->coordForceHistory->pullCoordinateSums[c].scalarForce / pull->coordForceHistory->numValuesInFSum); } @@ -438,8 +441,8 @@ static FILE* open_pull_out(const char* fn, * the group COMs for all the groups (+ ngroups_max*DIM) * and the components of the distance vectors can be printed (+ (ngroups_max/2)*DIM). */ - snew(setname, pull->coord.size() - * (1 + 1 + c_pullCoordNgroupMax * DIM + c_pullCoordNgroupMax / 2 * DIM)); + snew(setname, + pull->coord.size() * (1 + 1 + c_pullCoordNgroupMax * DIM + c_pullCoordNgroupMax / 2 * DIM)); nsets = 0; for (size_t c = 0; c < pull->coord.size(); c++) diff --git a/src/gromacs/pulling/pull.cpp b/src/gromacs/pulling/pull.cpp index 3d37732337..15eaee5503 100644 --- a/src/gromacs/pulling/pull.cpp +++ b/src/gromacs/pulling/pull.cpp @@ -335,8 +335,14 @@ static void apply_forces_coord(struct pull_t* pull, if (pcrd.params.eGeom == epullgCYL) { - apply_forces_cyl_grp(&pull->dyna[coord], pcrd.spatialData.cyl_dev, masses, forces.force01, - pcrd.scalarForce, -1, f, pull->nthreads); + apply_forces_cyl_grp(&pull->dyna[coord], + pcrd.spatialData.cyl_dev, + masses, + forces.force01, + pcrd.scalarForce, + -1, + f, + pull->nthreads); /* Sum the force along the vector and the radial force */ dvec f_tot; @@ -358,24 +364,22 @@ static void apply_forces_coord(struct pull_t* pull, if (!pull->group[pcrd.params.group[0]].params.ind.empty()) { - apply_forces_grp(&pull->group[pcrd.params.group[0]], masses, forces.force01, -1, f, - pull->nthreads); + apply_forces_grp( + &pull->group[pcrd.params.group[0]], masses, forces.force01, -1, f, pull->nthreads); } apply_forces_grp(&pull->group[pcrd.params.group[1]], masses, forces.force01, 1, f, pull->nthreads); if (pcrd.params.ngroup >= 4) { - apply_forces_grp(&pull->group[pcrd.params.group[2]], masses, forces.force23, -1, f, - pull->nthreads); - apply_forces_grp(&pull->group[pcrd.params.group[3]], masses, forces.force23, 1, f, - pull->nthreads); + apply_forces_grp( + &pull->group[pcrd.params.group[2]], masses, forces.force23, -1, f, pull->nthreads); + apply_forces_grp(&pull->group[pcrd.params.group[3]], masses, forces.force23, 1, f, pull->nthreads); } if (pcrd.params.ngroup >= 6) { - apply_forces_grp(&pull->group[pcrd.params.group[4]], masses, forces.force45, -1, f, - pull->nthreads); - apply_forces_grp(&pull->group[pcrd.params.group[5]], masses, forces.force45, 1, f, - pull->nthreads); + apply_forces_grp( + &pull->group[pcrd.params.group[4]], masses, forces.force45, -1, f, pull->nthreads); + apply_forces_grp(&pull->group[pcrd.params.group[5]], masses, forces.force45, 1, f, pull->nthreads); } } } @@ -502,8 +506,14 @@ static void low_get_pull_coord_dr(const struct pull_t* pull, gmx_fatal(FARGS, "Distance between pull groups %d and %d (%f nm) is larger than 0.49 times the " "box size (%f).\n%s", - pcrd->params.group[0], pcrd->params.group[1], sqrt(dr2), - sqrt(0.98 * 0.98 * max_dist2), pcrd->params.eGeom == epullgDIR ? "You might want to consider using \"pull-geometry = direction-periodic\" instead.\n" : ""); + pcrd->params.group[0], + pcrd->params.group[1], + sqrt(dr2), + sqrt(0.98 * 0.98 * max_dist2), + pcrd->params.eGeom == epullgDIR + ? "You might want to consider using \"pull-geometry = " + "direction-periodic\" instead.\n" + : ""); } if (pcrd->params.eGeom == epullgDIRPBC) @@ -556,8 +566,14 @@ static void get_pull_coord_dr(struct pull_t* pull, int coord_ind, const t_pbc* p } if (debug) { - fprintf(debug, "pull coord %d vector: %6.3f %6.3f %6.3f normalized: %6.3f %6.3f %6.3f\n", - coord_ind, vec[XX], vec[YY], vec[ZZ], spatialData.vec[XX], spatialData.vec[YY], + fprintf(debug, + "pull coord %d vector: %6.3f %6.3f %6.3f normalized: %6.3f %6.3f %6.3f\n", + coord_ind, + vec[XX], + vec[YY], + vec[ZZ], + spatialData.vec[XX], + spatialData.vec[YY], spatialData.vec[ZZ]); } } @@ -565,8 +581,12 @@ static void get_pull_coord_dr(struct pull_t* pull, int coord_ind, const t_pbc* p pull_group_work_t* pgrp0 = &pull->group[pcrd->params.group[0]]; pull_group_work_t* pgrp1 = &pull->group[pcrd->params.group[1]]; - low_get_pull_coord_dr(pull, pcrd, pbc, pgrp1->x, - pcrd->params.eGeom == epullgCYL ? pull->dyna[coord_ind].x : pgrp0->x, md2, + low_get_pull_coord_dr(pull, + pcrd, + pbc, + pgrp1->x, + pcrd->params.eGeom == epullgCYL ? pull->dyna[coord_ind].x : pgrp0->x, + md2, spatialData.dr01); if (pcrd->params.ngroup >= 4) @@ -615,7 +635,8 @@ static void low_set_pull_coord_reference_value(pull_coord_work_t* pcrd, int coor { gmx_fatal(FARGS, "Pull reference distance for coordinate %d (%f) needs to be non-negative", - coord_ind + 1, value_ref); + coord_ind + 1, + value_ref); } } else if (pcrd->params.eGeom == epullgANGLE || pcrd->params.eGeom == epullgANGLEAXIS) @@ -823,8 +844,12 @@ do_constraint(struct pull_t* pull, t_pbc* pbc, rvec* x, rvec* v, gmx_bool bMaste const PullCoordSpatialData& spatialData = pcrd->spatialData; if (debug) { - fprintf(debug, "Pull coord %zu dr %f %f %f\n", c, spatialData.dr01[XX], - spatialData.dr01[YY], spatialData.dr01[ZZ]); + fprintf(debug, + "Pull coord %zu dr %f %f %f\n", + c, + spatialData.dr01[XX], + spatialData.dr01[YY], + spatialData.dr01[ZZ]); } if (pcrd->params.eGeom == epullgDIR || pcrd->params.eGeom == epullgDIRPBC) @@ -879,8 +904,8 @@ do_constraint(struct pull_t* pull, t_pbc* pbc, rvec* x, rvec* v, gmx_bool bMaste pgrp1 = &pull->group[pcrd->params.group[1]]; /* Get the current difference vector */ - low_get_pull_coord_dr(pull, pcrd, pbc, rnew[pcrd->params.group[1]], - rnew[pcrd->params.group[0]], -1, unc_ij); + low_get_pull_coord_dr( + pull, pcrd, pbc, rnew[pcrd->params.group[1]], rnew[pcrd->params.group[0]], -1, unc_ij); if (debug) { @@ -897,7 +922,8 @@ do_constraint(struct pull_t* pull, t_pbc* pbc, rvec* x, rvec* v, gmx_bool bMaste gmx_fatal( FARGS, "The pull constraint reference distance for group %zu is <= 0 (%f)", - c, pcrd->value_ref); + c, + pcrd->value_ref); } { @@ -920,8 +946,7 @@ do_constraint(struct pull_t* pull, t_pbc* pbc, rvec* x, rvec* v, gmx_bool bMaste if (debug) { - fprintf(debug, "Pull ax^2+bx+c=0: a=%e b=%e c=%e lambda=%e\n", c_a, c_b, - c_c, lambda); + fprintf(debug, "Pull ax^2+bx+c=0: a=%e b=%e c=%e lambda=%e\n", c_a, c_b, c_c, lambda); } } @@ -965,12 +990,33 @@ do_constraint(struct pull_t* pull, t_pbc* pbc, rvec* x, rvec* v, gmx_bool bMaste g1 = pcrd->params.group[1]; low_get_pull_coord_dr(pull, pcrd, pbc, rnew[g1], rnew[g0], -1, tmp); low_get_pull_coord_dr(pull, pcrd, pbc, dr1, dr0, -1, tmp3); - fprintf(debug, "Pull cur %8.5f %8.5f %8.5f j:%8.5f %8.5f %8.5f d: %8.5f\n", rnew[g0][0], - rnew[g0][1], rnew[g0][2], rnew[g1][0], rnew[g1][1], rnew[g1][2], dnorm(tmp)); - fprintf(debug, "Pull ref %8s %8s %8s %8s %8s %8s d: %8.5f\n", "", "", "", "", "", - "", pcrd->value_ref); - fprintf(debug, "Pull cor %8.5f %8.5f %8.5f j:%8.5f %8.5f %8.5f d: %8.5f\n", dr0[0], - dr0[1], dr0[2], dr1[0], dr1[1], dr1[2], dnorm(tmp3)); + fprintf(debug, + "Pull cur %8.5f %8.5f %8.5f j:%8.5f %8.5f %8.5f d: %8.5f\n", + rnew[g0][0], + rnew[g0][1], + rnew[g0][2], + rnew[g1][0], + rnew[g1][1], + rnew[g1][2], + dnorm(tmp)); + fprintf(debug, + "Pull ref %8s %8s %8s %8s %8s %8s d: %8.5f\n", + "", + "", + "", + "", + "", + "", + pcrd->value_ref); + fprintf(debug, + "Pull cor %8.5f %8.5f %8.5f j:%8.5f %8.5f %8.5f d: %8.5f\n", + dr0[0], + dr0[1], + dr0[2], + dr1[0], + dr1[1], + dr1[2], + dnorm(tmp3)); } /* END DEBUG */ /* Update the COMs with dr */ @@ -986,8 +1032,8 @@ do_constraint(struct pull_t* pull, t_pbc* pbc, rvec* x, rvec* v, gmx_bool bMaste continue; } - low_get_pull_coord_dr(pull, &coord, pbc, rnew[coord.params.group[1]], - rnew[coord.params.group[0]], -1, unc_ij); + low_get_pull_coord_dr( + pull, &coord, pbc, rnew[coord.params.group[1]], rnew[coord.params.group[0]], -1, unc_ij); switch (coord.params.eGeom) { @@ -1015,7 +1061,10 @@ do_constraint(struct pull_t* pull, t_pbc* pbc, rvec* x, rvec* v, gmx_bool bMaste "Pull constraint not converged: " "groups %d %d," "d_ref = %f, current d = %f\n", - coord.params.group[0], coord.params.group[1], coord.value_ref, dnorm(unc_ij)); + coord.params.group[0], + coord.params.group[1], + coord.value_ref, + dnorm(unc_ij)); } bConverged_all = FALSE; @@ -1311,9 +1360,8 @@ static PullCoordVectorForces calculateVectorForces(const pull_coord_work_t& pcrd dist_32 = sqrdist_32 * inv_dist_32; /* Forces on groups 0, 1 */ - a_01 = pcrd.scalarForce * dist_32 / m2; /* scalarForce is -dV/dphi */ - dsvmul(-a_01, spatialData.planevec_m, - forces.force01); /* added sign to get force on group 1, not 0 */ + a_01 = pcrd.scalarForce * dist_32 / m2; /* scalarForce is -dV/dphi */ + dsvmul(-a_01, spatialData.planevec_m, forces.force01); /* added sign to get force on group 1, not 0 */ /* Forces on groups 4, 5 */ a_45 = -pcrd.scalarForce * dist_32 / n2; @@ -1366,7 +1414,10 @@ void register_external_pull_potential(struct pull_t* pull, int coord_index, cons gmx_fatal(FARGS, "Module '%s' attempted to register an external potential for pull coordinate %d " "which is out of the pull coordinate range %d - %zu\n", - provider, coord_index + 1, 1, pull->coord.size()); + provider, + coord_index + 1, + 1, + pull->coord.size()); } pull_coord_work_t* pcrd = &pull->coord[coord_index]; @@ -1377,7 +1428,10 @@ void register_external_pull_potential(struct pull_t* pull, int coord_index, cons FARGS, "Module '%s' attempted to register an external potential for pull coordinate %d " "which of type '%s', whereas external potentials are only supported with type '%s'", - provider, coord_index + 1, epull_names[pcrd->params.eType], epull_names[epullEXTERNAL]); + provider, + coord_index + 1, + epull_names[pcrd->params.eType], + epull_names[epullEXTERNAL]); } GMX_RELEASE_ASSERT(!pcrd->params.externalPotentialProvider.empty(), @@ -1388,7 +1442,9 @@ void register_external_pull_potential(struct pull_t* pull, int coord_index, cons gmx_fatal(FARGS, "Module '%s' attempted to register an external potential for pull coordinate %d " "which expects the external potential to be provided by a module named '%s'", - provider, coord_index + 1, pcrd->params.externalPotentialProvider.c_str()); + provider, + coord_index + 1, + pcrd->params.externalPotentialProvider.c_str()); } /* Lock to avoid (extremely unlikely) simultaneous reading and writing of @@ -1402,7 +1458,8 @@ void register_external_pull_potential(struct pull_t* pull, int coord_index, cons gmx_fatal(FARGS, "Module '%s' attempted to register an external potential for pull coordinate %d " "more than once", - provider, coord_index + 1); + provider, + coord_index + 1); } pcrd->bExternalPotentialProviderHasBeenRegistered = true; @@ -1434,7 +1491,8 @@ static void check_external_potential_registration(const struct pull_t* pull) "No external provider for external pull potentials have been provided for %d " "pull coordinates. The first coordinate without provider is number %zu, which " "expects a module named '%s' to provide the external potential.", - pull->numUnregisteredExternalPotentials, c + 1, + pull->numUnregisteredExternalPotentials, + c + 1, pull->coord[c].params.externalPotentialProvider.c_str()); } } @@ -1481,8 +1539,8 @@ void apply_external_pull_coord_force(struct pull_t* pull, forceWithVirial->addVirialContribution(virial); } - apply_forces_coord(pull, coord_index, pullCoordForces, masses, - as_rvec_array(forceWithVirial->force_.data())); + apply_forces_coord( + pull, coord_index, pullCoordForces, masses, as_rvec_array(forceWithVirial->force_.data())); } pull->numExternalPotentialsStillToBeAppliedThisStep--; @@ -1662,8 +1720,11 @@ void dd_make_local_pull_groups(const t_commrec* cr, struct pull_t* pull) if (debug && dd != nullptr) { - fprintf(debug, "Our DD rank (%3d) pull #atoms>0 or master: %s, will be part %s\n", dd->rank, - gmx::boolToString(bMustParticipate), gmx::boolToString(bWillParticipate)); + fprintf(debug, + "Our DD rank (%3d) pull #atoms>0 or master: %s, will be part %s\n", + dd->rank, + gmx::boolToString(bMustParticipate), + gmx::boolToString(bWillParticipate)); } if (bWillParticipate) @@ -1842,8 +1903,10 @@ static void init_pull_group_index(FILE* fplog, } else { - gmx_fatal(FARGS, "The total%s mass of pull group %d is zero", - !pg->params.weight.empty() ? " weighted" : "", g); + gmx_fatal(FARGS, + "The total%s mass of pull group %d is zero", + !pg->params.weight.empty() ? " weighted" : "", + g); } } if (fplog) @@ -1903,7 +1966,8 @@ struct pull_t* init_pull(FILE* fplog, for (int i = 0; i < pull_params->ngroup; ++i) { - pull->group.emplace_back(pull_params->group[i], atomSets->add(pull_params->group[i].ind), + pull->group.emplace_back(pull_params->group[i], + atomSets->add(pull_params->group[i].ind), pull_params->bSetPbcRefToPrevStepCOM); } @@ -1967,7 +2031,9 @@ struct pull_t* init_pull(FILE* fplog, "%d in the input is larger than that supported by the code (up to %d). " "You are probably reading a tpr file generated with a newer version of " "Gromacs with an binary from an older version of Gromacs.", - c + 1, pcrd->params.eGeom, epullgNR - 1); + c + 1, + pcrd->params.eGeom, + epullgNR - 1); } if (pcrd->params.eType == epullCONSTRAINT) @@ -1980,7 +2046,8 @@ struct pull_t* init_pull(FILE* fplog, gmx_fatal(FARGS, "Pulling of type %s can not be combined with geometry %s. Consider using " "pull type %s.", - epull_names[pcrd->params.eType], epullg_names[pcrd->params.eGeom], + epull_names[pcrd->params.eType], + epullg_names[pcrd->params.eGeom], epull_names[epullUMBRELLA]); } @@ -2025,8 +2092,7 @@ struct pull_t* init_pull(FILE* fplog, if (pcrd->params.eType != epullEXTERNAL) { low_set_pull_coord_reference_value( - pcrd, c, - pcrd->params.init * pull_conversion_factor_userinput2internal(&pcrd->params)); + pcrd, c, pcrd->params.init * pull_conversion_factor_userinput2internal(&pcrd->params)); } else { @@ -2092,8 +2158,12 @@ struct pull_t* init_pull(FILE* fplog, int numRealGroups = pull->group.size() - 1; GMX_RELEASE_ASSERT(numRealGroups > 0, "The reference absolute position pull group should always be present"); - fprintf(fplog, "with %zu pull coordinate%s and %d group%s\n", pull->coord.size(), - pull->coord.size() == 1 ? "" : "s", numRealGroups, numRealGroups == 1 ? "" : "s"); + fprintf(fplog, + "with %zu pull coordinate%s and %d group%s\n", + pull->coord.size(), + pull->coord.size() == 1 ? "" : "s", + numRealGroups, + numRealGroups == 1 ? "" : "s"); if (bAbs) { fprintf(fplog, "with an absolute reference\n"); @@ -2229,8 +2299,8 @@ struct pull_t* init_pull(FILE* fplog, } } const auto& referenceGroup = pull->group[coord.params.group[0]]; - pull->dyna.emplace_back(referenceGroup.params, referenceGroup.atomSet, - pull->params.bSetPbcRefToPrevStepCOM); + pull->dyna.emplace_back( + referenceGroup.params, referenceGroup.atomSet, pull->params.bSetPbcRefToPrevStepCOM); } } @@ -2319,7 +2389,8 @@ void preparePrevStepPullCom(const t_inputrec* ir, { /* Only the master rank has the checkpointed COM from the previous step */ gmx_bcast(sizeof(double) * state->pull_com_prev_step.size(), - &state->pull_com_prev_step[0], cr->mpi_comm_mygroup); + &state->pull_com_prev_step[0], + cr->mpi_comm_mygroup); } setPrevStepPullComFromState(pull_work, state); } diff --git a/src/gromacs/pulling/pull_rotation.cpp b/src/gromacs/pulling/pull_rotation.cpp index 17cb7bdd8c..40e4910c9b 100644 --- a/src/gromacs/pulling/pull_rotation.cpp +++ b/src/gromacs/pulling/pull_rotation.cpp @@ -323,16 +323,21 @@ gmx_enfrot* EnforcedRotation::getLegacyEnfrot() /* Activate output of forces for correctness checks */ /* #define PRINT_FORCES */ #ifdef PRINT_FORCES -# define PRINT_FORCE_J \ - fprintf(stderr, "f%d = %15.8f %15.8f %15.8f\n", erg->xc_ref_ind[j], erg->f_rot_loc[j][XX], \ - erg->f_rot_loc[j][YY], erg->f_rot_loc[j][ZZ]); +# define PRINT_FORCE_J \ + fprintf(stderr, \ + "f%d = %15.8f %15.8f %15.8f\n", \ + erg->xc_ref_ind[j], \ + erg->f_rot_loc[j][XX], \ + erg->f_rot_loc[j][YY], \ + erg->f_rot_loc[j][ZZ]); # define PRINT_POT_TAU \ if (MASTER(cr)) \ { \ fprintf(stderr, \ "potential = %15.8f\n" \ "torque = %15.8f\n", \ - erg->V, erg->torque_v); \ + erg->V, \ + erg->torque_v); \ } #else # define PRINT_FORCE_J @@ -490,8 +495,7 @@ static void reduce_output(const t_commrec* cr, gmx_enfrot* er, real t, int64_t s } #if GMX_MPI - MPI_Reduce(er->mpi_inbuf, er->mpi_outbuf, count, GMX_MPI_REAL, MPI_SUM, MASTERRANK(cr), - cr->mpi_comm_mygroup); + MPI_Reduce(er->mpi_inbuf, er->mpi_outbuf, count, GMX_MPI_REAL, MPI_SUM, MASTERRANK(cr), cr->mpi_comm_mygroup); #endif /* Copy back the reduced data from the buffer on the master */ @@ -742,8 +746,7 @@ static void get_slab_centers(gmx_enfrotgrp* erg, /* Enforced rotation group wor /* We can do the calculations ONLY if there is weight in the slab! */ if (erg->slab_weights[slabIndex] > WEIGHT_MIN) { - svmul(1.0 / erg->slab_weights[slabIndex], erg->slab_center[slabIndex], - erg->slab_center[slabIndex]); + svmul(1.0 / erg->slab_weights[slabIndex], erg->slab_center[slabIndex], erg->slab_center[slabIndex]); } else { @@ -766,8 +769,12 @@ static void get_slab_centers(gmx_enfrotgrp* erg, /* Enforced rotation group wor for (int j = erg->slab_first; j <= erg->slab_last; j++) { int slabIndex = j - erg->slab_first; - fprintf(out_slabs, "%6d%12.3e%12.3e%12.3e", j, erg->slab_center[slabIndex][XX], - erg->slab_center[slabIndex][YY], erg->slab_center[slabIndex][ZZ]); + fprintf(out_slabs, + "%6d%12.3e%12.3e%12.3e", + j, + erg->slab_center[slabIndex][XX], + erg->slab_center[slabIndex][YY], + erg->slab_center[slabIndex][ZZ]); } fprintf(out_slabs, "\n"); } @@ -867,8 +874,7 @@ static FILE* open_output_file(const char* fn, int steps, const char what[]) fp = gmx_ffopen(fn, "w"); - fprintf(fp, "# Output of %s is written in intervals of %d time step%s.\n#\n", what, steps, - steps > 1 ? "s" : ""); + fprintf(fp, "# Output of %s is written in intervals of %d time step%s.\n#\n", what, steps, steps > 1 ? "s" : ""); return fp; } @@ -892,8 +898,11 @@ static FILE* open_slab_out(const char* fn, gmx_enfrot* er) gmx_enfrotgrp* erg = &ergRef; if (ISFLEX(erg->rotg)) { - fprintf(fp, "# Rotation group %d (%s), slab distance %f nm, %s.\n", erg->groupIndex, - erotg_names[erg->rotg->eType], erg->rotg->slab_dist, + fprintf(fp, + "# Rotation group %d (%s), slab distance %f nm, %s.\n", + erg->groupIndex, + erotg_names[erg->rotg->eType], + erg->rotg->slab_dist, erg->rotg->bMassW ? "centers of mass" : "geometrical centers"); } } @@ -958,12 +967,16 @@ static FILE* open_rot_out(const char* fn, const gmx_output_env_t* oenv, gmx_enfr } else { - fp = xvgropen(fn, "Rotation angles and energy", "Time (ps)", - "angles (degrees) and energies (kJ/mol)", oenv); + fp = xvgropen(fn, + "Rotation angles and energy", + "Time (ps)", + "angles (degrees) and energies (kJ/mol)", + oenv); fprintf(fp, "# Output of enforced rotation data is written in intervals of %d time " "step%s.\n#\n", - er->nstrout, er->nstrout > 1 ? "s" : ""); + er->nstrout, + er->nstrout > 1 ? "s" : ""); fprintf(fp, "# The scalar tau is the torque (kJ/mol) in the direction of the rotation vector " "v.\n"); @@ -982,15 +995,23 @@ static FILE* open_rot_out(const char* fn, const gmx_output_env_t* oenv, gmx_enfr fprintf(fp, "#\n"); fprintf(fp, "# ROTATION GROUP %d, potential type '%s':\n", g, erotg_names[rotg->eType]); fprintf(fp, "# rot-massw%d %s\n", g, yesno_names[rotg->bMassW]); - fprintf(fp, "# rot-vec%d %12.5e %12.5e %12.5e\n", g, erg->vec[XX], - erg->vec[YY], erg->vec[ZZ]); + fprintf(fp, + "# rot-vec%d %12.5e %12.5e %12.5e\n", + g, + erg->vec[XX], + erg->vec[YY], + erg->vec[ZZ]); fprintf(fp, "# rot-rate%d %12.5e degrees/ps\n", g, rotg->rate); fprintf(fp, "# rot-k%d %12.5e kJ/(mol*nm^2)\n", g, rotg->k); if (rotg->eType == erotgISO || rotg->eType == erotgPM || rotg->eType == erotgRM || rotg->eType == erotgRM2) { - fprintf(fp, "# rot-pivot%d %12.5e %12.5e %12.5e nm\n", g, rotg->pivot[XX], - rotg->pivot[YY], rotg->pivot[ZZ]); + fprintf(fp, + "# rot-pivot%d %12.5e %12.5e %12.5e nm\n", + g, + rotg->pivot[XX], + rotg->pivot[YY], + rotg->pivot[ZZ]); } if (bFlex) @@ -1003,11 +1024,19 @@ static FILE* open_rot_out(const char* fn, const gmx_output_env_t* oenv, gmx_enfr if ((rotg->eType == erotgISOPF) || (rotg->eType == erotgPMPF) || (rotg->eType == erotgRMPF) || (rotg->eType == erotgRM2PF || (rotg->eType == erotgFLEXT) || (rotg->eType == erotgFLEX2T))) { - fprintf(fp, "# ref. grp. %d center %12.5e %12.5e %12.5e\n", g, - erg->xc_ref_center[XX], erg->xc_ref_center[YY], erg->xc_ref_center[ZZ]); + fprintf(fp, + "# ref. grp. %d center %12.5e %12.5e %12.5e\n", + g, + erg->xc_ref_center[XX], + erg->xc_ref_center[YY], + erg->xc_ref_center[ZZ]); - fprintf(fp, "# grp. %d init.center %12.5e %12.5e %12.5e\n", g, erg->xc_center[XX], - erg->xc_center[YY], erg->xc_center[ZZ]); + fprintf(fp, + "# grp. %d init.center %12.5e %12.5e %12.5e\n", + g, + erg->xc_center[XX], + erg->xc_center[YY], + erg->xc_center[ZZ]); } if ((rotg->eType == erotgRM2) || (rotg->eType == erotgFLEX2) || (rotg->eType == erotgFLEX2T)) @@ -1020,7 +1049,9 @@ static FILE* open_rot_out(const char* fn, const gmx_output_env_t* oenv, gmx_enfr fprintf(fp, "# theta_fit%d is determined by first evaluating the potential for %d " "angles around theta_ref%d.\n", - g, rotg->PotAngle_nstep, g); + g, + rotg->PotAngle_nstep, + g); fprintf(fp, "# The fit angle is the one with the smallest potential. It is given as " "the deviation\n"); @@ -1137,8 +1168,12 @@ static FILE* open_angles_out(const char* fn, gmx_enfrot* er) buf[0] = '\0'; } - fprintf(fp, "#\n# ROTATION GROUP %d '%s',%s fit type '%s'.\n", g, - erotg_names[rotg->eType], buf, erotg_fitnames[rotg->eFittype]); + fprintf(fp, + "#\n# ROTATION GROUP %d '%s',%s fit type '%s'.\n", + g, + erotg_names[rotg->eType], + buf, + erotg_fitnames[rotg->eFittype]); /* Special type of fitting using the potential minimum. This is * done for the whole group only, not for the individual slabs. */ @@ -1147,7 +1182,9 @@ static FILE* open_angles_out(const char* fn, gmx_enfrot* er) fprintf(fp, "# To obtain theta_fit%d, the potential is evaluated for %d angles " "around theta_ref%d\n", - g, rotg->PotAngle_nstep, g); + g, + rotg->PotAngle_nstep, + g); fprintf(fp, "# The fit angle in the rotation standard outfile is the one with " "minimal energy E(theta_fit) [kJ/mol].\n"); @@ -1211,14 +1248,21 @@ static FILE* open_torque_out(const char* fn, gmx_enfrot* er) const gmx_enfrotgrp* erg = &er->enfrotgrp[g]; if (ISFLEX(rotg)) { - fprintf(fp, "# Rotation group %d (%s), slab distance %f nm.\n", g, - erotg_names[rotg->eType], rotg->slab_dist); + fprintf(fp, + "# Rotation group %d (%s), slab distance %f nm.\n", + g, + erotg_names[rotg->eType], + rotg->slab_dist); fprintf(fp, "# The scalar tau is the torque (kJ/mol) in the direction of the rotation " "vector.\n"); fprintf(fp, "# To obtain the vectorial torque, multiply tau with\n"); - fprintf(fp, "# rot-vec%d %10.3e %10.3e %10.3e\n", g, erg->vec[XX], - erg->vec[YY], erg->vec[ZZ]); + fprintf(fp, + "# rot-vec%d %10.3e %10.3e %10.3e\n", + g, + erg->vec[XX], + erg->vec[YY], + erg->vec[ZZ]); fprintf(fp, "#\n"); } } @@ -1593,8 +1637,8 @@ static real flex_fit_angle(gmx_enfrotgrp* erg) /* From the point of view of the current positions, the reference has rotated * backwards. Since we output the angle relative to the fixed reference, * we need the minus sign. */ - fitangle = -opt_angle_analytic(erg->xc_ref_sorted, fitcoords, erg->mc_sorted, erg->rotg->nat, - erg->xc_ref_center, center, erg->vec); + fitangle = -opt_angle_analytic( + erg->xc_ref_sorted, fitcoords, erg->mc_sorted, erg->rotg->nat, erg->xc_ref_center, center, erg->vec); return fitangle; } @@ -1692,8 +1736,8 @@ static void flex_fit_angle_perslab(gmx_enfrotgrp* erg, double t, real degangle, clear_rvec(ref_center); clear_rvec(act_center); } - fitangle = -opt_angle_analytic(sd->ref, sd->x, sd->weight, sd->nat, ref_center, - act_center, erg->vec); + fitangle = -opt_angle_analytic( + sd->ref, sd->x, sd->weight, sd->nat, ref_center, act_center, erg->vec); fprintf(fp, "%6d%6d%12.3f", n, sd->nat, fitangle); } } @@ -2191,14 +2235,26 @@ static real do_flex2_lowlevel(gmx_enfrotgrp* erg, } #ifdef SUM_PARTS - fprintf(stderr, "sum1: %15.8f %15.8f %15.8f\n", -erg->rotg->k * sum1vec[XX], - -erg->rotg->k * sum1vec[YY], -erg->rotg->k * sum1vec[ZZ]); - fprintf(stderr, "sum2: %15.8f %15.8f %15.8f\n", erg->rotg->k * sum2vec[XX], - erg->rotg->k * sum2vec[YY], erg->rotg->k * sum2vec[ZZ]); - fprintf(stderr, "sum3: %15.8f %15.8f %15.8f\n", -erg->rotg->k * sum3vec[XX], - -erg->rotg->k * sum3vec[YY], -erg->rotg->k * sum3vec[ZZ]); - fprintf(stderr, "sum4: %15.8f %15.8f %15.8f\n", 0.5 * erg->rotg->k * sum4vec[XX], - 0.5 * erg->rotg->k * sum4vec[YY], 0.5 * erg->rotg->k * sum4vec[ZZ]); + fprintf(stderr, + "sum1: %15.8f %15.8f %15.8f\n", + -erg->rotg->k * sum1vec[XX], + -erg->rotg->k * sum1vec[YY], + -erg->rotg->k * sum1vec[ZZ]); + fprintf(stderr, + "sum2: %15.8f %15.8f %15.8f\n", + erg->rotg->k * sum2vec[XX], + erg->rotg->k * sum2vec[YY], + erg->rotg->k * sum2vec[ZZ]); + fprintf(stderr, + "sum3: %15.8f %15.8f %15.8f\n", + -erg->rotg->k * sum3vec[XX], + -erg->rotg->k * sum3vec[YY], + -erg->rotg->k * sum3vec[ZZ]); + fprintf(stderr, + "sum4: %15.8f %15.8f %15.8f\n", + 0.5 * erg->rotg->k * sum4vec[XX], + 0.5 * erg->rotg->k * sum4vec[YY], + 0.5 * erg->rotg->k * sum4vec[ZZ]); #endif PRINT_FORCE_J @@ -2525,15 +2581,13 @@ static void get_firstlast_slab_check(gmx_enfrotgrp* erg, /* The rotation group ( /* Check whether we have reference data to compare against */ if (erg->slab_first < erg->slab_first_ref) { - gmx_fatal(FARGS, "%s No reference data for first slab (n=%d), unable to proceed.", RotStr, - erg->slab_first); + gmx_fatal(FARGS, "%s No reference data for first slab (n=%d), unable to proceed.", RotStr, erg->slab_first); } /* Check whether we have reference data to compare against */ if (erg->slab_last > erg->slab_last_ref) { - gmx_fatal(FARGS, "%s No reference data for last slab (n=%d), unable to proceed.", RotStr, - erg->slab_last); + gmx_fatal(FARGS, "%s No reference data for last slab (n=%d), unable to proceed.", RotStr, erg->slab_last); } } @@ -2732,8 +2786,7 @@ static void do_fixed(gmx_enfrotgrp* erg, /* Rotate with the alternative angle. Like rotate_local_reference(), * just for a single local atom */ - mvmul(erg->PotAngleFit->rotmat[ifit], erg->rotg->x_ref[jj], - fit_xr_loc); /* fit_xr_loc = Omega*(y_i-y_c) */ + mvmul(erg->PotAngleFit->rotmat[ifit], erg->rotg->x_ref[jj], fit_xr_loc); /* fit_xr_loc = Omega*(y_i-y_c) */ /* Calculate Omega*(y_i-y_c)-(x_i-x_c) */ rvec_sub(fit_xr_loc, xi_xc, dr); @@ -2833,8 +2886,7 @@ static void do_radial_motion(gmx_enfrotgrp* erg, /* Rotate with the alternative angle. Like rotate_local_reference(), * just for a single local atom */ - mvmul(erg->PotAngleFit->rotmat[ifit], erg->rotg->x_ref[jj], - fit_tmpvec); /* fit_tmpvec = Omega*(yj0-u) */ + mvmul(erg->PotAngleFit->rotmat[ifit], erg->rotg->x_ref[jj], fit_tmpvec); /* fit_tmpvec = Omega*(yj0-u) */ /* Calculate Omega.(yj0-u) */ cprod(erg->vec, fit_tmpvec, tmpvec); /* tmpvec = v x Omega.(yj0-u) */ @@ -3199,8 +3251,7 @@ static void do_radial_motion2(gmx_enfrotgrp* erg, int iigrp = collectiveRotationGroupIndex[j]; /* Rotate with the alternative angle. Like rotate_local_reference(), * just for a single local atom */ - mvmul(erg->PotAngleFit->rotmat[ifit], erg->rotg->x_ref[iigrp], - fit_rj); /* fit_rj = Omega*(yj0-u) */ + mvmul(erg->PotAngleFit->rotmat[ifit], erg->rotg->x_ref[iigrp], fit_rj); /* fit_rj = Omega*(yj0-u) */ } fit_fac = iprod(v_xj_u, fit_rj); /* fac = (v x (xj-u)).fit_rj */ /* Add to the rotation potential for this angle: */ @@ -3275,8 +3326,11 @@ static void allocate_slabs(gmx_enfrotgrp* erg, FILE* fplog, gmx_bool bVerbose) if ((nullptr != fplog) && bVerbose) { - fprintf(fplog, "%s allocating memory to store data for %d slabs (rotation group %d).\n", - RotStr, nslabs, erg->groupIndex); + fprintf(fplog, + "%s allocating memory to store data for %d slabs (rotation group %d).\n", + RotStr, + nslabs, + erg->groupIndex); } snew(erg->slab_center, nslabs); snew(erg->slab_center_ref, nslabs); @@ -3698,8 +3752,15 @@ std::unique_ptr init_rot(FILE* fplo { nat_max = std::max(nat_max, erg->rotg->nat); - init_rot_group(fplog, cr, erg, x_pbc, mtop, mdrunOptions.verbose, er->out_slabs, - MASTER(cr) ? globalState->box : nullptr, ir, + init_rot_group(fplog, + cr, + erg, + x_pbc, + mtop, + mdrunOptions.verbose, + er->out_slabs, + MASTER(cr) ? globalState->box : nullptr, + ir, !er->restartWithAppending); /* Do not output the reference centers * again if we are appending */ } @@ -3837,10 +3898,18 @@ void do_rotation(const t_commrec* cr, gmx_enfrot* er, const matrix box, rvec x[] /* Transfer the rotation group's positions such that every node has * all of them. Every node contributes its local positions x and stores * it in the collective erg->xc array. */ - communicate_group_positions(cr, erg->xc, erg->xc_shifts, erg->xc_eshifts, bNS, x, - rotg->nat, erg->atomSet->numAtomsLocal(), + communicate_group_positions(cr, + erg->xc, + erg->xc_shifts, + erg->xc_eshifts, + bNS, + x, + rotg->nat, + erg->atomSet->numAtomsLocal(), erg->atomSet->localIndex().data(), - erg->atomSet->collectiveIndex().data(), erg->xc_old, box); + erg->atomSet->collectiveIndex().data(), + erg->xc_old, + box); } else { @@ -3867,8 +3936,8 @@ void do_rotation(const t_commrec* cr, gmx_enfrot* er, const matrix box, rvec x[] /* Get the center of the rotation group */ if ((rotg->eType == erotgISOPF) || (rotg->eType == erotgPMPF)) { - get_center_comm(cr, erg->x_loc_pbc, erg->m_loc, erg->atomSet->numAtomsLocal(), - rotg->nat, erg->xc_center); + get_center_comm( + cr, erg->x_loc_pbc, erg->m_loc, erg->atomSet->numAtomsLocal(), rotg->nat, erg->xc_center); } } diff --git a/src/gromacs/pulling/pullutil.cpp b/src/gromacs/pulling/pullutil.cpp index 875b535560..8b04f2aa0c 100644 --- a/src/gromacs/pulling/pullutil.cpp +++ b/src/gromacs/pulling/pullutil.cpp @@ -362,10 +362,18 @@ make_cyl_refgrps(const t_commrec* cr, pull_t* pull, const real* masses, t_pbc* p if (debug) { - fprintf(debug, "Pull cylinder group %zu:%8.3f%8.3f%8.3f m:%8.3f\n", c, pdyna->x[0], - pdyna->x[1], pdyna->x[2], 1.0 / pdyna->invtm); - fprintf(debug, "ffrad %8.3f %8.3f %8.3f\n", spatialData.ffrad[XX], - spatialData.ffrad[YY], spatialData.ffrad[ZZ]); + fprintf(debug, + "Pull cylinder group %zu:%8.3f%8.3f%8.3f m:%8.3f\n", + c, + pdyna->x[0], + pdyna->x[1], + pdyna->x[2], + 1.0 / pdyna->invtm); + fprintf(debug, + "ffrad %8.3f %8.3f %8.3f\n", + spatialData.ffrad[XX], + spatialData.ffrad[YY], + spatialData.ffrad[ZZ]); } } } @@ -629,8 +637,7 @@ void pull_calc_coms(const t_commrec* cr, pull_t* pull, const real* masses, t_pbc } else if (pgrp->atomSet.numAtomsLocal() <= c_pullMaxNumLocalAtomsSingleThreaded) { - sum_com_part(pgrp, 0, pgrp->atomSet.numAtomsLocal(), x, xp, masses, pbc, x_pbc, - &comSumsTotal); + sum_com_part(pgrp, 0, pgrp->atomSet.numAtomsLocal(), x, xp, masses, pbc, x_pbc, &comSumsTotal); } else { @@ -639,8 +646,8 @@ void pull_calc_coms(const t_commrec* cr, pull_t* pull, const real* masses, t_pbc { int ind_start = (pgrp->atomSet.numAtomsLocal() * (t + 0)) / pull->nthreads; int ind_end = (pgrp->atomSet.numAtomsLocal() * (t + 1)) / pull->nthreads; - sum_com_part(pgrp, ind_start, ind_end, x, xp, masses, pbc, x_pbc, - &pull->comSums[t]); + sum_com_part( + pgrp, ind_start, ind_end, x, xp, masses, pbc, x_pbc, &pull->comSums[t]); } /* Reduce the thread contributions to sum_com[0] */ @@ -678,8 +685,8 @@ void pull_calc_coms(const t_commrec* cr, pull_t* pull, const real* masses, t_pbc { int ind_start = (pgrp->atomSet.numAtomsLocal() * (t + 0)) / pull->nthreads; int ind_end = (pgrp->atomSet.numAtomsLocal() * (t + 1)) / pull->nthreads; - sum_com_part_cosweight(pgrp, ind_start, ind_end, pull->cosdim, twopi_box, x, xp, - masses, &pull->comSums[t]); + sum_com_part_cosweight( + pgrp, ind_start, ind_end, pull->cosdim, twopi_box, x, xp, masses, &pull->comSums[t]); } /* Reduce the thread contributions to comSums[0] */ @@ -715,7 +722,9 @@ void pull_calc_coms(const t_commrec* cr, pull_t* pull, const real* masses, t_pbc } } - pullAllReduce(cr, comm, pull->group.size() * c_comBufferStride * DIM, + pullAllReduce(cr, + comm, + pull->group.size() * c_comBufferStride * DIM, static_cast(comm->comBuffer[0])); for (size_t g = 0; g < pull->group.size(); g++) @@ -981,8 +990,8 @@ bool pullCheckPbcWithinGroup(const pull_t& pull, } } - return (pullGroupObeysPbcRestrictions(group, dimUsed, as_rvec_array(x.data()), pbc, - pull.comm.pbcAtomBuffer[groupNr], pbcMargin)); + return (pullGroupObeysPbcRestrictions( + group, dimUsed, as_rvec_array(x.data()), pbc, pull.comm.pbcAtomBuffer[groupNr], pbcMargin)); } void setPrevStepPullComFromState(struct pull_t* pull, const t_state* state) @@ -1074,8 +1083,7 @@ void initPullComFromPrevStep(const t_commrec* cr, pull_t* pull, const real* mass if (pgrp->atomSet.numAtomsLocal() <= c_pullMaxNumLocalAtomsSingleThreaded) { - sum_com_part(pgrp, 0, pgrp->atomSet.numAtomsLocal(), x, nullptr, masses, pbc, x_pbc, - &comSumsTotal); + sum_com_part(pgrp, 0, pgrp->atomSet.numAtomsLocal(), x, nullptr, masses, pbc, x_pbc, &comSumsTotal); } else { @@ -1084,8 +1092,8 @@ void initPullComFromPrevStep(const t_commrec* cr, pull_t* pull, const real* mass { int ind_start = (pgrp->atomSet.numAtomsLocal() * (t + 0)) / pull->nthreads; int ind_end = (pgrp->atomSet.numAtomsLocal() * (t + 1)) / pull->nthreads; - sum_com_part(pgrp, ind_start, ind_end, x, nullptr, masses, pbc, x_pbc, - &pull->comSums[t]); + sum_com_part( + pgrp, ind_start, ind_end, x, nullptr, masses, pbc, x_pbc, &pull->comSums[t]); } /* Reduce the thread contributions to sum_com[0] */ @@ -1148,8 +1156,7 @@ void initPullComFromPrevStep(const t_commrec* cr, pull_t* pull, const real* mass } if (debug) { - fprintf(debug, "Pull group %zu wmass %f invtm %f\n", g, 1.0 / pgrp->mwscale, - pgrp->invtm); + fprintf(debug, "Pull group %zu wmass %f invtm %f\n", g, 1.0 / pgrp->mwscale, pgrp->invtm); fprintf(debug, "Initialising prev step COM of pull group %zu to", g); for (int m = 0; m < DIM; m++) { diff --git a/src/gromacs/pulling/tests/pull.cpp b/src/gromacs/pulling/tests/pull.cpp index fe8e604d6c..d42ddc6580 100644 --- a/src/gromacs/pulling/tests/pull.cpp +++ b/src/gromacs/pulling/tests/pull.cpp @@ -105,8 +105,8 @@ protected: { minBoxSize2 = std::min(minBoxSize2, norm2(box[d])); } - EXPECT_REAL_EQ_TOL(0.25 * minBoxSize2, max_pull_distance2(&pcrd, &pbc), - defaultRealTolerance()); + EXPECT_REAL_EQ_TOL( + 0.25 * minBoxSize2, max_pull_distance2(&pcrd, &pbc), defaultRealTolerance()); } { @@ -118,8 +118,8 @@ protected: params.dim[ZZ] = 1; pull_coord_work_t pcrd(params); clear_dvec(pcrd.spatialData.vec); - EXPECT_REAL_EQ_TOL(0.25 * boxSizeZSquared, max_pull_distance2(&pcrd, &pbc), - defaultRealTolerance()); + EXPECT_REAL_EQ_TOL( + 0.25 * boxSizeZSquared, max_pull_distance2(&pcrd, &pbc), defaultRealTolerance()); } { @@ -132,8 +132,8 @@ protected: pull_coord_work_t pcrd(params); clear_dvec(pcrd.spatialData.vec); pcrd.spatialData.vec[ZZ] = 1; - EXPECT_REAL_EQ_TOL(0.25 * boxSizeZSquared, max_pull_distance2(&pcrd, &pbc), - defaultRealTolerance()); + EXPECT_REAL_EQ_TOL( + 0.25 * boxSizeZSquared, max_pull_distance2(&pcrd, &pbc), defaultRealTolerance()); } { diff --git a/src/gromacs/random/tests/threefry.cpp b/src/gromacs/random/tests/threefry.cpp index a31e6ead19..acf09b7ceb 100644 --- a/src/gromacs/random/tests/threefry.cpp +++ b/src/gromacs/random/tests/threefry.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2015,2016,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2015,2016,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -123,8 +123,9 @@ const std::vector bitsZero{ { 0, 0, 0, 0 } }; * The 2x64 flavors of ThreeFry64 will use the first four values, while * the 4x64 version uses all eight. */ -const std::vector bitsOne{ { 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, - 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL } }; +const std::vector bitsOne{ + { 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFFULL } +}; /*! \brief Constant array of integers with bitpattern from Pi. * @@ -132,8 +133,9 @@ const std::vector bitsOne{ { 0xFFFFFFFFFFFFFFFFULL, 0xFFFFFFFFFFFFFFFF * The 2x64 flavors of ThreeFry64 will use the first four values, while * the 4x64 version uses all eight. */ -const std::vector bitsPi{ { 0x243f6a8885a308d3ULL, 0x13198a2e03707344ULL, - 0xa4093822299f31d0ULL, 0x082efa98ec4e6c89ULL } }; +const std::vector bitsPi{ + { 0x243f6a8885a308d3ULL, 0x13198a2e03707344ULL, 0xa4093822299f31d0ULL, 0x082efa98ec4e6c89ULL } +}; // Test the known ansers for the ThreeFry random function when the argument // is (1) all zero, (2) all ones, (3) the bits of pi, for a bunch of different flavors of ThreeFry. diff --git a/src/gromacs/selection/compiler.cpp b/src/gromacs/selection/compiler.cpp index 52a26628d9..154a1a12d0 100644 --- a/src/gromacs/selection/compiler.cpp +++ b/src/gromacs/selection/compiler.cpp @@ -1782,8 +1782,8 @@ static void init_method(const SelectionTreeElementPointer& sel, const gmx_mtop_t if (sel->u.expr.method->init && (bAtomVal || !(sel->flags & SEL_METHODINIT))) { sel->flags |= SEL_METHODINIT; - sel->u.expr.method->init(top, sel->u.expr.method->nparams, sel->u.expr.method->param, - sel->u.expr.mdata); + sel->u.expr.method->init( + top, sel->u.expr.method->nparams, sel->u.expr.method->param, sel->u.expr.mdata); } if (bAtomVal || !(sel->flags & SEL_OUTINIT)) { @@ -2614,8 +2614,8 @@ void compileSelection(SelectionCollection* coll) for (i = 0; i < sc->sel.size(); ++i) { gmx::internal::SelectionData& sel = *sc->sel[i]; - init_pos_keyword_defaults(&sel.rootElement(), coll->impl_->spost_.c_str(), - coll->impl_->rpost_.c_str(), &sel); + init_pos_keyword_defaults( + &sel.rootElement(), coll->impl_->spost_.c_str(), coll->impl_->rpost_.c_str(), &sel); } /* Remove any unused variables. */ diff --git a/src/gromacs/selection/evaluate.cpp b/src/gromacs/selection/evaluate.cpp index fd2be14434..23781cee8c 100644 --- a/src/gromacs/selection/evaluate.cpp +++ b/src/gromacs/selection/evaluate.cpp @@ -953,8 +953,7 @@ void _gmx_sel_evaluate_method(gmx_sel_evaluate_t* data, expandValueForPositions(sel->v.u.r, &sel->v.nr, sel->u.expr.pos); break; default: - GMX_RELEASE_ASSERT(false, - "Unimplemented value type for position update method"); + GMX_RELEASE_ASSERT(false, "Unimplemented value type for position update method"); } } } diff --git a/src/gromacs/selection/indexutil.cpp b/src/gromacs/selection/indexutil.cpp index 5a6a4507bc..160676281c 100644 --- a/src/gromacs/selection/indexutil.cpp +++ b/src/gromacs/selection/indexutil.cpp @@ -77,9 +77,9 @@ IndexGroupsAndNames::IndexGroupsAndNames(const t_blocka& indexGroup, ArrayRef IndexGroupsAndNames::indices(const std::string& groupName) const @@ -96,14 +96,17 @@ std::vector IndexGroupsAndNames::indices(const std::string& groupName) co "of grompp.")); } const auto groupNamePosition = std::find_if( - std::begin(groupNames_), std::end(groupNames_), - [&groupName](const std::string& name) { return equalCaseInsensitive(groupName, name); }); + std::begin(groupNames_), std::end(groupNames_), [&groupName](const std::string& name) { + return equalCaseInsensitive(groupName, name); + }); const auto groupIndex = std::distance(std::begin(groupNames_), groupNamePosition); const auto groupSize = indexGroup_.index[groupIndex + 1] - indexGroup_.index[groupIndex]; std::vector groupIndices(groupSize); const auto startingIndex = indexGroup_.index[groupIndex]; std::iota(std::begin(groupIndices), std::end(groupIndices), startingIndex); - std::transform(std::begin(groupIndices), std::end(groupIndices), std::begin(groupIndices), + std::transform(std::begin(groupIndices), + std::end(groupIndices), + std::begin(groupIndices), [blockLookup = indexGroup_.a](auto i) { return blockLookup[i]; }); return groupIndices; } diff --git a/src/gromacs/selection/nbsearch.cpp b/src/gromacs/selection/nbsearch.cpp index 96443c208d..c1d26ed296 100644 --- a/src/gromacs/selection/nbsearch.cpp +++ b/src/gromacs/selection/nbsearch.cpp @@ -906,8 +906,8 @@ void AnalysisNeighborhoodSearchImpl::init(AnalysisNeighborhood::SearchMode m } else if (bTryGrid_) { - bGrid_ = initGrid(pbc_, positions.count_, positions.x_, - mode == AnalysisNeighborhood::eSearchMode_Grid); + bGrid_ = initGrid( + pbc_, positions.count_, positions.x_, mode == AnalysisNeighborhood::eSearchMode_Grid); } refIndices_ = positions.indices_; if (bGrid_) diff --git a/src/gromacs/selection/params.cpp b/src/gromacs/selection/params.cpp index 9c44d422da..7bf73880fb 100644 --- a/src/gromacs/selection/params.cpp +++ b/src/gromacs/selection/params.cpp @@ -149,8 +149,8 @@ static void convert_value(SelectionParserValue* value, e_selvalue_t type, Except /* Integers to floating point are easy */ if (value->type == INT_VALUE && type == REAL_VALUE) { - *value = SelectionParserValue::createRealRange(value->u.i.i1, value->u.i.i2, - value->location()); + *value = SelectionParserValue::createRealRange( + value->u.i.i1, value->u.i.i2, value->location()); return; } /* Reals that are integer-valued can also be converted */ @@ -532,8 +532,7 @@ static void parse_values_varnum(const SelectionParserValueList& values, GMX_RELEASE_ASSERT(false, "Variable-count value type not implemented"); } } - GMX_RELEASE_ASSERT(i == valueCount, - "Inconsistent value count wrt. the actual value population"); + GMX_RELEASE_ASSERT(i == valueCount, "Inconsistent value count wrt. the actual value population"); if (param->nvalptr) { *param->nvalptr = param->val.nr; diff --git a/src/gromacs/selection/parsetree.cpp b/src/gromacs/selection/parsetree.cpp index d7e536358e..9f78139847 100644 --- a/src/gromacs/selection/parsetree.cpp +++ b/src/gromacs/selection/parsetree.cpp @@ -706,8 +706,8 @@ static SelectionTreeElementPointer init_keyword_internal(gmx_ana_selmethod_t* SelectionParserParameterList params; params.push_back(SelectionParserParameter::createFromExpression(nullptr, child)); params.push_back(SelectionParserParameter::create(nullptr, std::move(args), location)); - _gmx_sel_parse_params(params, root->u.expr.method->nparams, root->u.expr.method->param, - root, scanner); + _gmx_sel_parse_params( + params, root->u.expr.method->nparams, root->u.expr.method->param, root, scanner); } set_refpos_type(&sc->pcc, child, rpost); @@ -847,8 +847,8 @@ SelectionTreeElementPointer _gmx_sel_init_modifier(gmx_ana_selmethod_t* root = modifier; } /* Process the parameters */ - _gmx_sel_parse_params(*params, modifier->u.expr.method->nparams, modifier->u.expr.method->param, - modifier, scanner); + _gmx_sel_parse_params( + *params, modifier->u.expr.method->nparams, modifier->u.expr.method->param, modifier, scanner); return root; } diff --git a/src/gromacs/selection/poscalc.cpp b/src/gromacs/selection/poscalc.cpp index 38b8bb67ea..4e59956084 100644 --- a/src/gromacs/selection/poscalc.cpp +++ b/src/gromacs/selection/poscalc.cpp @@ -1341,17 +1341,17 @@ void gmx_ana_poscalc_update(gmx_ana_poscalc_t* pc, break; default: // TODO: It would probably be better to do this without the type casts. - gmx_calc_comg_block(top, fr->x, reinterpret_cast(&pc->b), index.data(), - bMass, p->x); + gmx_calc_comg_block( + top, fr->x, reinterpret_cast(&pc->b), index.data(), bMass, p->x); if (p->v && fr->bV) { - gmx_calc_comg_block(top, fr->v, reinterpret_cast(&pc->b), - index.data(), bMass, p->v); + gmx_calc_comg_block( + top, fr->v, reinterpret_cast(&pc->b), index.data(), bMass, p->v); } if (p->f && fr->bF) { - gmx_calc_comg_f_block(top, fr->f, reinterpret_cast(&pc->b), - index.data(), bMass, p->f); + gmx_calc_comg_f_block( + top, fr->f, reinterpret_cast(&pc->b), index.data(), bMass, p->f); } break; } diff --git a/src/gromacs/selection/selection.cpp b/src/gromacs/selection/selection.cpp index 20926675fd..b3cadb741d 100644 --- a/src/gromacs/selection/selection.cpp +++ b/src/gromacs/selection/selection.cpp @@ -296,7 +296,8 @@ int Selection::initOriginalIdsToGroup(const gmx_mtop_t* top, e_index_t type) std::string message = formatString( "Cannot group selection '%s' into %s, because some " "positions have atoms from more than one such group.", - name(), type == INDEX_MOL ? "molecules" : "residues"); + name(), + type == INDEX_MOL ? "molecules" : "residues"); GMX_THROW(InconsistentInputError(message)); } } @@ -304,8 +305,14 @@ int Selection::initOriginalIdsToGroup(const gmx_mtop_t* top, e_index_t type) void Selection::printInfo(FILE* fp) const { - fprintf(fp, "\"%s\" (%d position%s, %d atom%s%s)", name(), posCount(), posCount() == 1 ? "" : "s", - atomCount(), atomCount() == 1 ? "" : "s", isDynamic() ? ", dynamic" : ""); + fprintf(fp, + "\"%s\" (%d position%s, %d atom%s%s)", + name(), + posCount(), + posCount() == 1 ? "" : "s", + atomCount(), + atomCount() == 1 ? "" : "s", + isDynamic() ? ", dynamic" : ""); fprintf(fp, "\n"); } diff --git a/src/gromacs/selection/selectioncollection.cpp b/src/gromacs/selection/selectioncollection.cpp index a9c6e6825a..0ed46f7892 100644 --- a/src/gromacs/selection/selectioncollection.cpp +++ b/src/gromacs/selection/selectioncollection.cpp @@ -257,14 +257,14 @@ void printCurrentStatus(TextWriter* writer, } for (size_t i = firstSelection; i < sc->sel.size(); ++i) { - writer->writeString(formatString(" %2d. %s\n", static_cast(i - firstSelection + 1), - sc->sel[i]->selectionText())); + writer->writeString(formatString( + " %2d. %s\n", static_cast(i - firstSelection + 1), sc->sel[i]->selectionText())); } if (maxCount > 0) { const int remaining = maxCount - static_cast(sc->sel.size() - firstSelection); - writer->writeString(formatString("(%d more selection%s required)\n", remaining, - remaining > 1 ? "s" : "")); + writer->writeString(formatString( + "(%d more selection%s required)\n", remaining, remaining > 1 ? "s" : "")); } } } @@ -688,8 +688,8 @@ bool SelectionCollection::requiresIndexGroups() const SelectionList SelectionCollection::parseFromStdin(int count, bool bInteractive, const std::string& context) { StandardInputStream inputStream; - return parseInteractive(count, &inputStream, - bInteractive ? &TextOutputFile::standardError() : nullptr, context); + return parseInteractive( + count, &inputStream, bInteractive ? &TextOutputFile::standardError() : nullptr, context); } namespace @@ -717,8 +717,8 @@ SelectionList SelectionCollection::parseInteractive(int count, yyscan_t scanner; const std::unique_ptr statusWriter(initStatusWriter(statusStream)); - _gmx_sel_init_lexer(&scanner, &impl_->sc_, statusWriter.get(), count, - impl_->bExternalGroupsSet_, impl_->grps_); + _gmx_sel_init_lexer( + &scanner, &impl_->sc_, statusWriter.get(), count, impl_->bExternalGroupsSet_, impl_->grps_); return runParser(scanner, inputStream, true, count, context); } @@ -853,7 +853,8 @@ void SelectionCollection::evaluate(t_trxframe* fr, t_pbc* pbc) "Trajectory has less atoms (%d) than what is required for " "evaluating the provided selections (atoms up to index %d " "are required).", - fr->natoms, maxAtomIndex + 1); + fr->natoms, + maxAtomIndex + 1); GMX_THROW(InconsistentInputError(message)); } } diff --git a/src/gromacs/selection/selectionoptionmanager.cpp b/src/gromacs/selection/selectionoptionmanager.cpp index bc755086c4..3d6a601e74 100644 --- a/src/gromacs/selection/selectionoptionmanager.cpp +++ b/src/gromacs/selection/selectionoptionmanager.cpp @@ -176,7 +176,10 @@ void SelectionOptionManager::Impl::placeSelectionsInRequests(const SelectionList formatString("Too few selections provided for '%s': " "Expected %d selections, but only %d left " "after assigning the first %d to other selections.", - request.name().c_str(), request.count(), remaining, assigned))); + request.name().c_str(), + request.count(), + remaining, + assigned))); } last = first + request.count(); } @@ -195,7 +198,10 @@ void SelectionOptionManager::Impl::placeSelectionsInRequests(const SelectionList "selections to be assigned to '%s'. " "Resolution for such cases is not implemented, " "and may be impossible.", - name, conflictName, name, conflictName))); + name, + conflictName, + name, + conflictName))); } last = selections.end(); } @@ -212,7 +218,9 @@ void SelectionOptionManager::Impl::placeSelectionsInRequests(const SelectionList formatString("Too many selections provided: " "Expected %d selections, but %d provided. " "Last %d selections could not be assigned to any option.", - assigned, count, remaining))); + assigned, + count, + remaining))); } } @@ -291,8 +299,8 @@ void SelectionOptionManager::parseRequestedFromStdin(bool bInteractive) for (i = impl_->requests_.begin(); i != impl_->requests_.end(); ++i) { const Impl::SelectionRequest& request = *i; - std::string context = formatString("for option '%s'\n(%s)", request.name().c_str(), - request.description().c_str()); + std::string context = formatString( + "for option '%s'\n(%s)", request.name().c_str(), request.description().c_str()); SelectionList selections = impl_->collection_.parseFromStdin(request.count(), bInteractive, context); request.storage_->addSelections(selections, true); diff --git a/src/gromacs/selection/selelem.cpp b/src/gromacs/selection/selelem.cpp index d81d5ff4a8..05f89fc48e 100644 --- a/src/gromacs/selection/selelem.cpp +++ b/src/gromacs/selection/selelem.cpp @@ -469,7 +469,8 @@ void SelectionTreeElement::checkIndexGroup(int natoms) "Group '%s' cannot be used in selections, because it " "contains negative atom indices and/or references atoms " "not present (largest allowed atom index is %d).", - name().c_str(), natoms); + name().c_str(), + natoms); GMX_THROW(InconsistentInputError(message)); } } @@ -564,8 +565,7 @@ void _gmx_selelem_print_tree(FILE* fp, const gmx::SelectionTreeElement& sel, boo { int i; - fprintf(fp, "%*c %s %s", level * 2 + 1, '*', _gmx_selelem_type_str(sel), - _gmx_sel_value_type_str(&sel.v)); + fprintf(fp, "%*c %s %s", level * 2 + 1, '*', _gmx_selelem_type_str(sel), _gmx_sel_value_type_str(&sel.v)); if (!sel.name().empty()) { fprintf(fp, " \"%s\"", sel.name().c_str()); @@ -716,8 +716,7 @@ void _gmx_selelem_print_tree(FILE* fp, const gmx::SelectionTreeElement& sel, boo * segfaults when printing the selection tree. */ if (sel.v.u.p->x) { - fprintf(fp, "(%f, %f, %f)", sel.v.u.p->x[0][XX], sel.v.u.p->x[0][YY], - sel.v.u.p->x[0][ZZ]); + fprintf(fp, "(%f, %f, %f)", sel.v.u.p->x[0][XX], sel.v.u.p->x[0][YY], sel.v.u.p->x[0][ZZ]); } else { diff --git a/src/gromacs/selection/selmethod.cpp b/src/gromacs/selection/selmethod.cpp index a648c3ca4f..489fb97560 100644 --- a/src/gromacs/selection/selmethod.cpp +++ b/src/gromacs/selection/selmethod.cpp @@ -2,7 +2,7 @@ * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2009-2018, The GROMACS development team. - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -181,53 +181,65 @@ static bool check_params(FILE* fp, { if (param[i].val.type != INT_VALUE && param[i].val.type != REAL_VALUE) { - report_param_error(fp, name, param[i].name, + report_param_error(fp, + name, + param[i].name, "error: SPAR_RANGES cannot be set for a non-numeric parameter"); bOk = false; } if (param[i].flags & SPAR_DYNAMIC) { - report_param_error(fp, name, param[i].name, + report_param_error(fp, + name, + param[i].name, "warning: SPAR_DYNAMIC does not have effect with SPAR_RANGES"); param[i].flags &= ~SPAR_DYNAMIC; } if (!(param[i].flags & SPAR_VARNUM) && param[i].val.nr != 1) { report_param_error( - fp, name, param[i].name, + fp, + name, + param[i].name, "error: range should take either one or an arbitrary number of values"); bOk = false; } if (param[i].flags & SPAR_ATOMVAL) { - report_param_error(fp, name, param[i].name, - "error: SPAR_RANGES and SPAR_ATOMVAL both set"); + report_param_error( + fp, name, param[i].name, "error: SPAR_RANGES and SPAR_ATOMVAL both set"); bOk = false; } } if ((param[i].flags & SPAR_VARNUM) && (param[i].flags & SPAR_ATOMVAL)) { - report_param_error(fp, name, param[i].name, - "error: SPAR_VARNUM and SPAR_ATOMVAL both set"); + report_param_error( + fp, name, param[i].name, "error: SPAR_VARNUM and SPAR_ATOMVAL both set"); bOk = false; } if (param[i].flags & SPAR_ENUMVAL) { if (param[i].val.type != STR_VALUE) { - report_param_error(fp, name, param[i].name, + report_param_error(fp, + name, + param[i].name, "error: SPAR_ENUMVAL can only be set for string parameters"); bOk = false; } if (param[i].val.nr != 1) { - report_param_error(fp, name, param[i].name, + report_param_error(fp, + name, + param[i].name, "error: SPAR_ENUMVAL parameters should take exactly one value"); bOk = false; } if (param[i].flags & (SPAR_DYNAMIC | SPAR_VARNUM | SPAR_ATOMVAL)) { - report_param_error(fp, name, param[i].name, + report_param_error(fp, + name, + param[i].name, "error: only SPAR_OPTIONAL supported with SPAR_ENUMVAL"); bOk = false; } @@ -237,7 +249,9 @@ static bool check_params(FILE* fp, { if (param[i].val.nr != 0) { - report_param_error(fp, name, param[i].name, + report_param_error(fp, + name, + param[i].name, "error: number of values should be zero for boolean parameters"); bOk = false; } @@ -247,7 +261,9 @@ static bool check_params(FILE* fp, /* Any other flags should not be specified */ if (param[i].flags & ~SPAR_OPTIONAL) { - report_param_error(fp, name, param[i].name, + report_param_error(fp, + name, + param[i].name, "error: boolean parameter should not have any flags set"); bOk = false; } @@ -258,7 +274,9 @@ static bool check_params(FILE* fp, if (param[i].val.nr != -1) { report_param_error( - fp, name, param[i].name, + fp, + name, + param[i].name, "warning: val.nr is not -1 although SPAR_VARNUM/SPAR_ATOMVAL is set"); } param[i].val.nr = -1; @@ -295,8 +313,8 @@ static bool check_params(FILE* fp, { if (param[i].name[j] != '_' && !isalnum(param[i].name[j])) { - report_param_error(fp, name, param[i].name, - "error: name contains non-alphanumeric characters"); + report_param_error( + fp, name, param[i].name, "error: name contains non-alphanumeric characters"); bOk = false; break; } @@ -308,7 +326,9 @@ static bool check_params(FILE* fp, /* Check that the name does not conflict with a method */ if (symtab.findSymbol(param[i].name) != nullptr) { - report_param_error(fp, name, param[i].name, + report_param_error(fp, + name, + param[i].name, "error: name conflicts with another method or a keyword"); bOk = false; } @@ -322,7 +342,9 @@ static bool check_params(FILE* fp, gmx_ana_selparam_t* param = gmx_ana_selmethod_find_param(name, method); if (param) { - report_param_error(fp, method->name, param->name, + report_param_error(fp, + method->name, + param->name, "error: name conflicts with another method or a keyword"); bOk = false; } @@ -353,7 +375,8 @@ static bool check_callbacks(FILE* fp, gmx_ana_selmethod_t* method) /* Make some checks on init_data and free */ if (method->nparams > 0 && !method->init_data) { - report_error(fp, method->name, + report_error(fp, + method->name, "error: init_data should be provided because the method has parameters"); bOk = false; } @@ -364,14 +387,16 @@ static bool check_callbacks(FILE* fp, gmx_ana_selmethod_t* method) /* Check presence of outinit for position-valued methods */ if (method->type == POS_VALUE && !method->outinit) { - report_error(fp, method->name, + report_error(fp, + method->name, "error: outinit should be provided because the method has POS_VALUE"); bOk = false; } /* Check presence of outinit for variable output count methods */ if ((method->flags & SMETH_VARNUMVAL) && !method->outinit) { - report_error(fp, method->name, + report_error(fp, + method->name, "error: outinit should be provided because the method has SMETH_VARNUMVAL"); bOk = false; } @@ -447,7 +472,8 @@ static bool check_method(FILE* fp, gmx_ana_selmethod_t* method, const gmx::Selec /* Check that conflicting flags are not present. */ if (method->flags & SMETH_VARNUMVAL) { - report_error(fp, method->name, + report_error(fp, + method->name, "error: SMETH_VARNUMVAL cannot be set for group-valued methods"); bOk = false; } @@ -462,7 +488,8 @@ static bool check_method(FILE* fp, gmx_ana_selmethod_t* method, const gmx::Selec } if ((method->flags & SMETH_CHARVAL) && method->type != STR_VALUE) { - report_error(fp, method->name, + report_error(fp, + method->name, "error: SMETH_CHARVAL can only be specified for STR_VALUE methods"); bOk = false; } @@ -506,7 +533,8 @@ static bool check_modifier(FILE* fp, gmx_ana_selmethod_t* method, const gmx::Sel /* Check flags */ if (method->flags & (SMETH_SINGLEVAL | SMETH_VARNUMVAL)) { - report_error(fp, method->name, + report_error(fp, + method->name, "error: modifier should not have SMETH_SINGLEVAL or SMETH_VARNUMVAL set"); bOk = false; } diff --git a/src/gromacs/selection/sm_insolidangle.cpp b/src/gromacs/selection/sm_insolidangle.cpp index d649a874a4..bbcffa350e 100644 --- a/src/gromacs/selection/sm_insolidangle.cpp +++ b/src/gromacs/selection/sm_insolidangle.cpp @@ -356,8 +356,10 @@ gmx_ana_selmethod_t sm_insolidangle = { &init_frame_insolidangle, nullptr, &evaluate_insolidangle, - { "insolidangle center POS span POS_EXPR [cutoff REAL]", "Selecting atoms in a solid angle", - asize(help_insolidangle), help_insolidangle }, + { "insolidangle center POS span POS_EXPR [cutoff REAL]", + "Selecting atoms in a solid angle", + asize(help_insolidangle), + help_insolidangle }, }; static void* init_data_insolidangle(int /* npar */, gmx_ana_selparam_t* param) diff --git a/src/gromacs/selection/sm_merge.cpp b/src/gromacs/selection/sm_merge.cpp index 1bf833e32a..d7936966c3 100644 --- a/src/gromacs/selection/sm_merge.cpp +++ b/src/gromacs/selection/sm_merge.cpp @@ -242,8 +242,11 @@ static void init_output_common(const gmx_mtop_t* top, gmx_ana_selvalue_t* out, v { out->u.p->m.type = d->p1.m.type; } - gmx_ana_pos_reserve_for_append(out->u.p, d->p1.count() + d->p2.count(), - d->p1.m.b.nra + d->p2.m.b.nra, d->p1.v != nullptr, d->p1.f != nullptr); + gmx_ana_pos_reserve_for_append(out->u.p, + d->p1.count() + d->p2.count(), + d->p1.m.b.nra + d->p2.m.b.nra, + d->p1.v != nullptr, + d->p1.f != nullptr); gmx_ana_pos_empty_init(out->u.p); } diff --git a/src/gromacs/selection/sm_permute.cpp b/src/gromacs/selection/sm_permute.cpp index f8a4e8c175..c8c24cd6be 100644 --- a/src/gromacs/selection/sm_permute.cpp +++ b/src/gromacs/selection/sm_permute.cpp @@ -206,8 +206,8 @@ static void init_output_permute(const gmx_mtop_t* /* top */, gmx_ana_selvalue_t* int i, j, b; out->u.p->m.type = d->p.m.type; - gmx_ana_pos_reserve_for_append(out->u.p, d->p.count(), d->p.m.b.nra, d->p.v != nullptr, - d->p.f != nullptr); + gmx_ana_pos_reserve_for_append( + out->u.p, d->p.count(), d->p.m.b.nra, d->p.v != nullptr, d->p.f != nullptr); gmx_ana_pos_empty_init(out->u.p); for (i = 0; i < d->p.count(); i += d->n) { diff --git a/src/gromacs/selection/tests/indexutil.cpp b/src/gromacs/selection/tests/indexutil.cpp index a58289be0d..afc4fcce3b 100644 --- a/src/gromacs/selection/tests/indexutil.cpp +++ b/src/gromacs/selection/tests/indexutil.cpp @@ -143,8 +143,8 @@ void IndexBlockTest::checkBlocka(const char* id) for (int i = 0; i < blocka_.nr; ++i) { gmx::test::TestReferenceChecker blockCompound(compound.checkCompound("Block", nullptr)); - blockCompound.checkSequence(&blocka_.a[blocka_.index[i]], &blocka_.a[blocka_.index[i + 1]], - "Atoms"); + blockCompound.checkSequence( + &blocka_.a[blocka_.index[i]], &blocka_.a[blocka_.index[i + 1]], "Atoms"); } } @@ -545,8 +545,8 @@ void IndexMapTest::checkMapping(int atomCount, const int atoms[], const char* na for (int i = 0; i < map_.mapb.nr; ++i) { gmx::test::TestReferenceChecker blockCompound(compound.checkCompound("Block", nullptr)); - blockCompound.checkSequence(&atoms[map_.mapb.index[i]], &atoms[map_.mapb.index[i + 1]], - "Atoms"); + blockCompound.checkSequence( + &atoms[map_.mapb.index[i]], &atoms[map_.mapb.index[i + 1]], "Atoms"); blockCompound.checkInteger(map_.refid[i], "RefId"); blockCompound.checkInteger(map_.mapid[i], "MapId"); int originalIdIndex = (map_.refid[i] != -1 ? map_.refid[i] : i); @@ -673,8 +673,9 @@ public: addGroupToBlocka_(indicesGroupSecondA_); addGroupToBlocka_(indicesGroupC_); - const char* const namesAsConstCharArray[4] = { groupNames[0].c_str(), groupNames[1].c_str(), - groupNames[2].c_str(), groupNames[3].c_str() }; + const char* const namesAsConstCharArray[4] = { + groupNames[0].c_str(), groupNames[1].c_str(), groupNames[2].c_str(), groupNames[3].c_str() + }; indexGroupAndNames_ = std::make_unique(blockA_, namesAsConstCharArray); } ~IndexGroupsAndNamesTest() override { done_blocka(&blockA_); } diff --git a/src/gromacs/selection/tests/nbsearch.cpp b/src/gromacs/selection/tests/nbsearch.cpp index d0f61f30f7..4601e45fd5 100644 --- a/src/gromacs/selection/tests/nbsearch.cpp +++ b/src/gromacs/selection/tests/nbsearch.cpp @@ -626,8 +626,8 @@ void NeighborhoodSearchTest::testPairSearchFull(gmx::AnalysisNeighborhoodSearch* if (selfPairs) { searchPair = NeighborhoodSearchTestData::RefPair(testIndex, 0.0); - const auto otherRefPair = std::lower_bound(refPairs[refIndex].begin(), - refPairs[refIndex].end(), searchPair); + const auto otherRefPair = std::lower_bound( + refPairs[refIndex].begin(), refPairs[refIndex].end(), searchPair); GMX_RELEASE_ASSERT(otherRefPair != refPairs[refIndex].end(), "Precomputed reference data is not symmetric"); otherRefPair->bFound = true; @@ -1111,8 +1111,13 @@ TEST_F(NeighborhoodSearchTest, SimpleSearchExclusions) nb_.initSearch(&data.pbc_, data.refPositions().exclusionIds(helper.refPosIds())); ASSERT_EQ(gmx::AnalysisNeighborhood::eSearchMode_Simple, search.mode()); - testPairSearchFull(&search, data, data.testPositions().exclusionIds(helper.testPosIds()), - helper.exclusions(), {}, {}, false); + testPairSearchFull(&search, + data, + data.testPositions().exclusionIds(helper.testPosIds()), + helper.exclusions(), + {}, + {}, + false); } TEST_F(NeighborhoodSearchTest, GridSearchExclusions) @@ -1129,8 +1134,13 @@ TEST_F(NeighborhoodSearchTest, GridSearchExclusions) nb_.initSearch(&data.pbc_, data.refPositions().exclusionIds(helper.refPosIds())); ASSERT_EQ(gmx::AnalysisNeighborhood::eSearchMode_Grid, search.mode()); - testPairSearchFull(&search, data, data.testPositions().exclusionIds(helper.testPosIds()), - helper.exclusions(), {}, {}, false); + testPairSearchFull(&search, + data, + data.testPositions().exclusionIds(helper.testPosIds()), + helper.exclusions(), + {}, + {}, + false); } } // namespace diff --git a/src/gromacs/selection/tests/poscalc.cpp b/src/gromacs/selection/tests/poscalc.cpp index 9748909eb1..f4f2fcafe3 100644 --- a/src/gromacs/selection/tests/poscalc.cpp +++ b/src/gromacs/selection/tests/poscalc.cpp @@ -324,8 +324,8 @@ void PositionCalculationTest::checkPositions(gmx::test::TestReferenceChecker* ch for (int i = 0; i < p->count(); ++i) { gmx::test::TestReferenceChecker posCompound(compound.checkCompound("Position", nullptr)); - posCompound.checkSequence(&p->m.mapb.a[p->m.mapb.index[i]], - &p->m.mapb.a[p->m.mapb.index[i + 1]], "Atoms"); + posCompound.checkSequence( + &p->m.mapb.a[p->m.mapb.index[i]], &p->m.mapb.a[p->m.mapb.index[i + 1]], "Atoms"); posCompound.checkInteger(p->m.refid[i], "RefId"); if (bCoordinates) { diff --git a/src/gromacs/selection/tests/selectioncollection.cpp b/src/gromacs/selection/tests/selectioncollection.cpp index b8c02bb836..a7a54235b0 100644 --- a/src/gromacs/selection/tests/selectioncollection.cpp +++ b/src/gromacs/selection/tests/selectioncollection.cpp @@ -160,7 +160,8 @@ void SelectionCollectionInteractiveTest::runTest(int count, { helper_.setInputLines(inputLines); // TODO: Check something about the returned selections as well. - ASSERT_NO_THROW_GMX(sc_.parseInteractive(count, &helper_.inputStream(), + ASSERT_NO_THROW_GMX(sc_.parseInteractive(count, + &helper_.inputStream(), bInteractive ? &helper_.outputStream() : nullptr, "for test context")); helper_.checkSession(); @@ -742,7 +743,8 @@ TEST_F(SelectionCollectionDataTest, HandlesAllNone) TEST_F(SelectionCollectionDataTest, HandlesAtomnr) { - static const char* const selections[] = { "atomnr 1 to 3 6 to 8", "atomnr 4 2 5 to 7", + static const char* const selections[] = { "atomnr 1 to 3 6 to 8", + "atomnr 4 2 5 to 7", "atomnr <= 5" }; runTest(10, selections); } @@ -777,8 +779,9 @@ TEST_F(SelectionCollectionDataTest, HandlesAtomname) TEST_F(SelectionCollectionDataTest, HandlesPdbAtomname) { - static const char* const selections[] = { "name HG21", "name 1HG2", "pdbname HG21 CB", - "pdbatomname 1HG2" }; + static const char* const selections[] = { + "name HG21", "name 1HG2", "pdbname HG21 CB", "pdbatomname 1HG2" + }; runTest("simple.pdb", selections); } @@ -888,9 +891,11 @@ TEST_F(SelectionCollectionDataTest, HandlesSameResidueName) TEST_F(SelectionCollectionDataTest, HandlesPositionKeywords) { - static const char* const selections[] = { "cog of resnr 1 3", "res_cog of name CB and resnr 1 3", + static const char* const selections[] = { "cog of resnr 1 3", + "res_cog of name CB and resnr 1 3", "whole_res_cog of name CB and resnr 1 3", - "part_res_cog of x < 3", "dyn_res_cog of x < 3" }; + "part_res_cog of x < 3", + "dyn_res_cog of x < 3" }; setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates | efTestPositionAtoms); runTest("simple.gro", selections); } @@ -946,7 +951,8 @@ TEST_F(SelectionCollectionDataTest, HandlesPermuteModifier) TEST_F(SelectionCollectionDataTest, HandlesPlusModifier) { static const char* const selections[] = { - "name S2 plus name S1", "res_cog of resnr 2 plus res_cog of resnr 1 plus res_cog of resnr 3", + "name S2 plus name S1", + "res_cog of resnr 2 plus res_cog of resnr 1 plus res_cog of resnr 3", "name S1 and y < 3 plus res_cog of x < 2.5" }; setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates | efTestPositionAtoms @@ -1003,7 +1009,8 @@ TEST_F(SelectionCollectionDataTest, ComputesMassesAndChargesWithoutTopology) TEST_F(SelectionCollectionDataTest, HandlesFramesWithAtomSubsets) { const int index[] = { 0, 1, 2, 3, 4, 5, 9, 10, 11 }; - const char* const selections[] = { "resnr 1 4", "atomnr 1 2 5 11 and y > 2", + const char* const selections[] = { "resnr 1 4", + "atomnr 1 2 5 11 and y > 2", "res_cog of atomnr 2 5 11" }; setFlags(TestFlags() | efTestEvaluation | efTestPositionAtoms); ASSERT_NO_FATAL_FAILURE(runParser(selections)); @@ -1022,7 +1029,8 @@ TEST_F(SelectionCollectionDataTest, HandlesFramesWithAtomSubsets) TEST_F(SelectionCollectionDataTest, HandlesSelectionNames) { static const char* const selections[] = { "\"GroupSelection\" group \"GrpA\"", - "\"DynamicSelection\" x < 5", "y < 3" }; + "\"DynamicSelection\" x < 5", + "y < 3" }; setFlags(TestFlags() | efTestSelectionNames); ASSERT_NO_THROW_GMX(loadIndexGroups("simple.ndx")); runTest(10, selections); @@ -1030,7 +1038,9 @@ TEST_F(SelectionCollectionDataTest, HandlesSelectionNames) TEST_F(SelectionCollectionDataTest, HandlesIndexGroupsInSelections) { - static const char* const selections[] = { "group \"GrpA\"", "GrpB", "1", + static const char* const selections[] = { "group \"GrpA\"", + "GrpB", + "1", // These test that the name of the group is not too // eagerly promoted to the name of the selection. "group \"GrpB\" and resname RB", @@ -1044,8 +1054,9 @@ TEST_F(SelectionCollectionDataTest, HandlesIndexGroupsInSelections) TEST_F(SelectionCollectionDataTest, HandlesIndexGroupsInSelectionsDelayed) { - static const char* const selections[] = { "group \"GrpA\"", "GrpB", "1", - "group \"GrpB\" and resname RB" }; + static const char* const selections[] = { + "group \"GrpA\"", "GrpB", "1", "group \"GrpB\" and resname RB" + }; setFlags(TestFlags() | efTestSelectionNames); ASSERT_NO_FATAL_FAILURE(runParser(selections)); ASSERT_NO_FATAL_FAILURE(loadTopology("simple.gro")); @@ -1155,7 +1166,8 @@ TEST_F(SelectionCollectionDataTest, HandlesRegexMatching) TEST_F(SelectionCollectionDataTest, HandlesBasicBoolean) { static const char* const selections[] = { - "atomnr 1 to 5 and atomnr 2 to 7", "atomnr 1 to 5 or not atomnr 3 to 8", + "atomnr 1 to 5 and atomnr 2 to 7", + "atomnr 1 to 5 or not atomnr 3 to 8", "not not atomnr 1 to 5 and atomnr 2 to 6 and not not atomnr 3 to 7", "atomnr 1 to 5 and (atomnr 2 to 7 and atomnr 3 to 6)", "x < 5 and atomnr 1 to 5 and y < 3 and atomnr 2 to 4" @@ -1177,8 +1189,7 @@ TEST_F(SelectionCollectionDataTest, HandlesDynamicAtomValuedParameters) TEST_F(SelectionCollectionDataTest, HandlesEmptySelectionWithUnevaluatedExpressions) { - static const char* const selections[] = { "none and x > 2", - "none and same resname as resnr 2" }; + static const char* const selections[] = { "none and x > 2", "none and same resname as resnr 2" }; runTest("simple.gro", selections); } @@ -1224,8 +1235,9 @@ TEST_F(SelectionCollectionDataTest, HandlesKeywordOfPositionsInArithmetic) TEST_F(SelectionCollectionDataTest, HandlesNumericComparisons) { - static const char* const selections[] = { "x > 2", "2 < x", "y > resnr", "resnr < 2.5", - "2.5 > resnr" }; + static const char* const selections[] = { + "x > 2", "2 < x", "y > resnr", "resnr < 2.5", "2.5 > resnr" + }; setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates); runTest("simple.gro", selections); } @@ -1241,8 +1253,9 @@ TEST_F(SelectionCollectionDataTest, HandlesArithmeticExpressions) TEST_F(SelectionCollectionDataTest, HandlesNumericVariables) { - static const char* const selections[] = { "value = x + y", "value <= 4", "index = resnr", - "index < 3" }; + static const char* const selections[] = { + "value = x + y", "value <= 4", "index = resnr", "index < 3" + }; setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates); runTest("simple.gro", selections); } @@ -1272,7 +1285,8 @@ TEST_F(SelectionCollectionDataTest, HandlesPositionVariables) TEST_F(SelectionCollectionDataTest, HandlesPositionVariableInModifier) { - static const char* const selections[] = { "foo = cog of resnr 1", "cog of resnr 2 plus foo", + static const char* const selections[] = { "foo = cog of resnr 1", + "cog of resnr 2 plus foo", "cog of resnr 3 plus foo" }; setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates); runTest("simple.gro", selections); @@ -1281,7 +1295,8 @@ TEST_F(SelectionCollectionDataTest, HandlesPositionVariableInModifier) TEST_F(SelectionCollectionDataTest, HandlesConstantPositionInVariable) { - static const char* const selections[] = { "constpos = [1.0, 2.5, 0.5]", "constpos", + static const char* const selections[] = { "constpos = [1.0, 2.5, 0.5]", + "constpos", "within 2 of constpos" }; setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates | efTestPositionAtoms); runTest("simple.gro", selections); @@ -1290,8 +1305,11 @@ TEST_F(SelectionCollectionDataTest, HandlesConstantPositionInVariable) TEST_F(SelectionCollectionDataTest, HandlesNumericConstantsInVariables) { - static const char* const selections[] = { "constint = 4", "constreal1 = 0.5", "constreal2 = 2.7", - "resnr < constint", "x + constreal1 < constreal2" }; + static const char* const selections[] = { "constint = 4", + "constreal1 = 0.5", + "constreal2 = 2.7", + "resnr < constint", + "x + constreal1 < constreal2" }; setFlags(TestFlags() | efTestEvaluation | efTestPositionCoordinates); runTest("simple.gro", selections); } @@ -1304,7 +1322,8 @@ TEST_F(SelectionCollectionDataTest, HandlesNumericConstantsInVariables) TEST_F(SelectionCollectionDataTest, HandlesBooleanStaticAnalysis) { static const char* const selections[] = { - "atomnr 1 to 5 and atomnr 2 to 7 and x < 2", "atomnr 1 to 5 and (atomnr 4 to 7 or x < 2)", + "atomnr 1 to 5 and atomnr 2 to 7 and x < 2", + "atomnr 1 to 5 and (atomnr 4 to 7 or x < 2)", "atomnr 1 to 5 and y < 3 and (atomnr 4 to 7 or x < 2)", "atomnr 1 to 5 and not (atomnr 4 to 7 or x < 2)", "atomnr 1 to 5 or (atomnr 4 to 6 and (atomnr 5 to 7 or x < 2))" @@ -1344,8 +1363,10 @@ TEST_F(SelectionCollectionDataTest, HandlesBooleanStaticAnalysisWithMoreVariable TEST_F(SelectionCollectionDataTest, HandlesUnusedVariables) { - static const char* const selections[] = { "unused1 = atomnr 1 to 3", "foo = atomnr 4 to 7", - "atomnr 1 to 6 and foo", "unused2 = atomnr 3 to 5" }; + static const char* const selections[] = { "unused1 = atomnr 1 to 3", + "foo = atomnr 4 to 7", + "atomnr 1 to 6 and foo", + "unused2 = atomnr 3 to 5" }; runTest(10, selections); } @@ -1353,15 +1374,17 @@ TEST_F(SelectionCollectionDataTest, HandlesUnusedVariables) TEST_F(SelectionCollectionDataTest, HandlesVariablesWithStaticEvaluationGroups) { static const char* const selections[] = { "foo = atomnr 4 to 7 and x < 2", - "atomnr 1 to 5 and foo", "atomnr 3 to 7 and foo" }; + "atomnr 1 to 5 and foo", + "atomnr 3 to 7 and foo" }; runTest(10, selections); } TEST_F(SelectionCollectionDataTest, HandlesVariablesWithMixedEvaluationGroups) { - static const char* const selections[] = { "foo = atomnr 4 to 7 and x < 2", - "atomnr 1 to 6 and foo", "within 1 of foo", "foo" }; + static const char* const selections[] = { + "foo = atomnr 4 to 7 and x < 2", "atomnr 1 to 6 and foo", "within 1 of foo", "foo" + }; runTest(10, selections); } @@ -1369,7 +1392,8 @@ TEST_F(SelectionCollectionDataTest, HandlesVariablesWithMixedEvaluationGroups) TEST_F(SelectionCollectionDataTest, HandlesVariablesWithMixedEvaluationGroups2) { static const char* const selections[] = { "foo = atomnr 1 to 8 and x < 10", - "atomnr 1 to 5 and y < 10 and foo", "foo" }; + "atomnr 1 to 5 and y < 10 and foo", + "foo" }; setFlags(TestFlags() | efTestEvaluation); runTest("simple.gro", selections); } diff --git a/src/gromacs/selection/tests/toputils.cpp b/src/gromacs/selection/tests/toputils.cpp index 8b6388db44..dcb450937d 100644 --- a/src/gromacs/selection/tests/toputils.cpp +++ b/src/gromacs/selection/tests/toputils.cpp @@ -126,8 +126,13 @@ void TopologyManager::loadTopology(const char* filename) GMX_RELEASE_ASSERT(mtop_ == nullptr, "Topology initialized more than once"); mtop_ = std::make_unique(); - readConfAndTopology(gmx::test::TestFileManager::getInputFilePath(filename).c_str(), &fullTopology, - mtop_.get(), &pbcType, frame_ != nullptr ? &xtop : nullptr, nullptr, box); + readConfAndTopology(gmx::test::TestFileManager::getInputFilePath(filename).c_str(), + &fullTopology, + mtop_.get(), + &pbcType, + frame_ != nullptr ? &xtop : nullptr, + nullptr, + box); if (frame_ != nullptr) { diff --git a/src/gromacs/simd/impl_arm_sve/impl_arm_sve_simd4_double.h b/src/gromacs/simd/impl_arm_sve/impl_arm_sve_simd4_double.h index 037f3e6c05..7834553a13 100644 --- a/src/gromacs/simd/impl_arm_sve/impl_arm_sve_simd4_double.h +++ b/src/gromacs/simd/impl_arm_sve/impl_arm_sve_simd4_double.h @@ -116,29 +116,29 @@ static inline Simd4Double gmx_simdcall simd4SetZeroD() static inline Simd4Double gmx_simdcall operator&(Simd4Double a, Simd4Double b) { svbool_t pg = svptrue_b64(); - return { svreinterpret_f64_s64(svand_s64_z(pg, svreinterpret_s64_f64(a.simdInternal_), - svreinterpret_s64_f64(b.simdInternal_))) }; + return { svreinterpret_f64_s64(svand_s64_z( + pg, svreinterpret_s64_f64(a.simdInternal_), svreinterpret_s64_f64(b.simdInternal_))) }; } static inline Simd4Double gmx_simdcall andNot(Simd4Double a, Simd4Double b) { svbool_t pg = svptrue_b64(); - return { svreinterpret_f64_s64(svbic_s64_z(pg, svreinterpret_s64_f64(b.simdInternal_), - svreinterpret_s64_f64(a.simdInternal_))) }; + return { svreinterpret_f64_s64(svbic_s64_z( + pg, svreinterpret_s64_f64(b.simdInternal_), svreinterpret_s64_f64(a.simdInternal_))) }; } static inline Simd4Double gmx_simdcall operator|(Simd4Double a, Simd4Double b) { svbool_t pg = svptrue_b64(); - return { svreinterpret_f64_s64(svorr_s64_z(pg, svreinterpret_s64_f64(a.simdInternal_), - svreinterpret_s64_f64(b.simdInternal_))) }; + return { svreinterpret_f64_s64(svorr_s64_z( + pg, svreinterpret_s64_f64(a.simdInternal_), svreinterpret_s64_f64(b.simdInternal_))) }; } static inline Simd4Double gmx_simdcall operator^(Simd4Double a, Simd4Double b) { svbool_t pg = svptrue_b64(); - return { svreinterpret_f64_s64(sveor_s64_z(pg, svreinterpret_s64_f64(a.simdInternal_), - svreinterpret_s64_f64(b.simdInternal_))) }; + return { svreinterpret_f64_s64(sveor_s64_z( + pg, svreinterpret_s64_f64(a.simdInternal_), svreinterpret_s64_f64(b.simdInternal_))) }; } static inline Simd4Double gmx_simdcall operator+(Simd4Double a, Simd4Double b) diff --git a/src/gromacs/simd/impl_arm_sve/impl_arm_sve_simd_double.h b/src/gromacs/simd/impl_arm_sve/impl_arm_sve_simd_double.h index 04cf849e46..542d642f49 100644 --- a/src/gromacs/simd/impl_arm_sve/impl_arm_sve_simd_double.h +++ b/src/gromacs/simd/impl_arm_sve/impl_arm_sve_simd_double.h @@ -174,8 +174,7 @@ static inline void gmx_simdcall store(std::int32_t* m, SimdDInt32 a) { assert(0 == (std::size_t(m) % GMX_SIMD_ALIGNMENT)); svbool_t pg = svwhilelt_b32(0, (int32_t)GMX_SIMD_DINT32_WIDTH); - svst1_s32(pg, m, - svuzp1(svreinterpret_s32_s64(a.simdInternal_), svreinterpret_s32_s64(a.simdInternal_))); + svst1_s32(pg, m, svuzp1(svreinterpret_s32_s64(a.simdInternal_), svreinterpret_s32_s64(a.simdInternal_))); } static inline SimdDInt32 gmx_simdcall simdLoadU(const std::int32_t* m, SimdDInt32Tag) @@ -187,8 +186,7 @@ static inline SimdDInt32 gmx_simdcall simdLoadU(const std::int32_t* m, SimdDInt3 static inline void gmx_simdcall storeU(std::int32_t* m, SimdDInt32 a) { svbool_t pg = svwhilelt_b32(0, (int32_t)GMX_SIMD_DINT32_WIDTH); - svst1_s32(pg, m, - svuzp1(svreinterpret_s32_s64(a.simdInternal_), svreinterpret_s32_s64(a.simdInternal_))); + svst1_s32(pg, m, svuzp1(svreinterpret_s32_s64(a.simdInternal_), svreinterpret_s32_s64(a.simdInternal_))); } static inline SimdDInt32 gmx_simdcall setZeroDI() @@ -213,29 +211,29 @@ gmx_simdcall static inline double extract(SimdDouble a) static inline SimdDouble gmx_simdcall operator&(SimdDouble a, SimdDouble b) { svbool_t pg = svptrue_b64(); - return { svreinterpret_f64_s64(svand_s64_x(pg, svreinterpret_s64_f64(a.simdInternal_), - svreinterpret_s64_f64(b.simdInternal_))) }; + return { svreinterpret_f64_s64(svand_s64_x( + pg, svreinterpret_s64_f64(a.simdInternal_), svreinterpret_s64_f64(b.simdInternal_))) }; } static inline SimdDouble gmx_simdcall andNot(SimdDouble a, SimdDouble b) { svbool_t pg = svptrue_b64(); - return { svreinterpret_f64_s64(svbic_s64_x(pg, svreinterpret_s64_f64(b.simdInternal_), - svreinterpret_s64_f64(a.simdInternal_))) }; + return { svreinterpret_f64_s64(svbic_s64_x( + pg, svreinterpret_s64_f64(b.simdInternal_), svreinterpret_s64_f64(a.simdInternal_))) }; } static inline SimdDouble gmx_simdcall operator|(SimdDouble a, SimdDouble b) { svbool_t pg = svptrue_b64(); - return { svreinterpret_f64_s64(svorr_s64_x(pg, svreinterpret_s64_f64(a.simdInternal_), - svreinterpret_s64_f64(b.simdInternal_))) }; + return { svreinterpret_f64_s64(svorr_s64_x( + pg, svreinterpret_s64_f64(a.simdInternal_), svreinterpret_s64_f64(b.simdInternal_))) }; } static inline SimdDouble gmx_simdcall operator^(SimdDouble a, SimdDouble b) { svbool_t pg = svptrue_b64(); - return { svreinterpret_f64_s64(sveor_s64_x(pg, svreinterpret_s64_f64(a.simdInternal_), - svreinterpret_s64_f64(b.simdInternal_))) }; + return { svreinterpret_f64_s64(sveor_s64_x( + pg, svreinterpret_s64_f64(a.simdInternal_), svreinterpret_s64_f64(b.simdInternal_))) }; } static inline SimdDouble gmx_simdcall operator+(SimdDouble a, SimdDouble b) @@ -393,9 +391,10 @@ static inline SimdDouble gmx_simdcall frexp(SimdDouble value, SimdDInt32* expone exponent->simdInternal_ = iExponent; - return { svreinterpret_f64_s64(svorr_s64_x( - pg, svand_s64_x(pg, svreinterpret_s64_f64(value.simdInternal_), mantissaMask), - svreinterpret_s64_f64(half))) }; + return { svreinterpret_f64_s64( + svorr_s64_x(pg, + svand_s64_x(pg, svreinterpret_s64_f64(value.simdInternal_), mantissaMask), + svreinterpret_s64_f64(half))) }; } template diff --git a/src/gromacs/simd/impl_arm_sve/impl_arm_sve_simd_float.h b/src/gromacs/simd/impl_arm_sve/impl_arm_sve_simd_float.h index ffa53071d2..a7f2737c27 100644 --- a/src/gromacs/simd/impl_arm_sve/impl_arm_sve_simd_float.h +++ b/src/gromacs/simd/impl_arm_sve/impl_arm_sve_simd_float.h @@ -211,29 +211,29 @@ gmx_simdcall static inline float extract(SimdFloat a) static inline SimdFloat gmx_simdcall operator&(SimdFloat a, SimdFloat b) { svbool_t pg = svptrue_b32(); - return { svreinterpret_f32_s32(svand_s32_x(pg, svreinterpret_s32_f32(a.simdInternal_), - svreinterpret_s32_f32(b.simdInternal_))) }; + return { svreinterpret_f32_s32(svand_s32_x( + pg, svreinterpret_s32_f32(a.simdInternal_), svreinterpret_s32_f32(b.simdInternal_))) }; } static inline SimdFloat gmx_simdcall andNot(SimdFloat a, SimdFloat b) { svbool_t pg = svptrue_b32(); - return { svreinterpret_f32_s32(svbic_s32_x(pg, svreinterpret_s32_f32(b.simdInternal_), - svreinterpret_s32_f32(a.simdInternal_))) }; + return { svreinterpret_f32_s32(svbic_s32_x( + pg, svreinterpret_s32_f32(b.simdInternal_), svreinterpret_s32_f32(a.simdInternal_))) }; } static inline SimdFloat gmx_simdcall operator|(SimdFloat a, SimdFloat b) { svbool_t pg = svptrue_b32(); - return { svreinterpret_f32_s32(svorr_s32_x(pg, svreinterpret_s32_f32(a.simdInternal_), - svreinterpret_s32_f32(b.simdInternal_))) }; + return { svreinterpret_f32_s32(svorr_s32_x( + pg, svreinterpret_s32_f32(a.simdInternal_), svreinterpret_s32_f32(b.simdInternal_))) }; } static inline SimdFloat gmx_simdcall operator^(SimdFloat a, SimdFloat b) { svbool_t pg = svptrue_b32(); - return { svreinterpret_f32_s32(sveor_s32_x(pg, svreinterpret_s32_f32(a.simdInternal_), - svreinterpret_s32_f32(b.simdInternal_))) }; + return { svreinterpret_f32_s32(sveor_s32_x( + pg, svreinterpret_s32_f32(a.simdInternal_), svreinterpret_s32_f32(b.simdInternal_))) }; } static inline SimdFloat gmx_simdcall operator+(SimdFloat a, SimdFloat b) @@ -394,9 +394,10 @@ static inline SimdFloat gmx_simdcall frexp(SimdFloat value, SimdFInt32* exponent pg, svreinterpret_s32_u32(svlsr_n_u32_x(pg, svreinterpret_u32_s32(iExponent), 23)), exponentBias); exponent->simdInternal_ = iExponent; - return { svreinterpret_f32_s32(svorr_s32_x( - pg, svand_s32_x(pg, svreinterpret_s32_f32(value.simdInternal_), mantissaMask), - svreinterpret_s32_f32(half))) }; + return { svreinterpret_f32_s32( + svorr_s32_x(pg, + svand_s32_x(pg, svreinterpret_s32_f32(value.simdInternal_), mantissaMask), + svreinterpret_s32_f32(half))) }; } template diff --git a/src/gromacs/simd/impl_arm_sve/impl_arm_sve_util_double.h b/src/gromacs/simd/impl_arm_sve/impl_arm_sve_util_double.h index f4bfe49e03..572266a983 100644 --- a/src/gromacs/simd/impl_arm_sve/impl_arm_sve_util_double.h +++ b/src/gromacs/simd/impl_arm_sve/impl_arm_sve_util_double.h @@ -90,7 +90,8 @@ static inline void gmx_simdcall gatherLoadTranspose(const double* base, svint64_t offsets; svbool_t pg = svptrue_b64(); offsets = svmul_n_s64_x( - pg, svunpklo_s64(svld1_s32(svwhilelt_b32(0, (int32_t)GMX_SIMD_DINT32_WIDTH), offset)), + pg, + svunpklo_s64(svld1_s32(svwhilelt_b32(0, (int32_t)GMX_SIMD_DINT32_WIDTH), offset)), align * sizeof(double)); v0->simdInternal_ = svld1_gather_s64offset_f64(pg, base, offsets); offsets = svadd_n_s64_x(pg, offsets, sizeof(double)); @@ -146,7 +147,8 @@ static inline void gmx_simdcall gatherLoadUTranspose(const double* base, svint64_t offsets; svbool_t pg = svptrue_b64(); offsets = svmul_n_s64_x( - pg, svunpklo_s64(svld1_s32(svwhilelt_b32(0, (int32_t)GMX_SIMD_DINT32_WIDTH), offset)), + pg, + svunpklo_s64(svld1_s32(svwhilelt_b32(0, (int32_t)GMX_SIMD_DINT32_WIDTH), offset)), align * sizeof(double)); v0->simdInternal_ = svld1_gather_s64offset_f64(pg, base, offsets); offsets = svadd_n_s64_x(pg, offsets, sizeof(double)); @@ -168,7 +170,8 @@ static inline void gmx_simdcall transposeScatterStoreU(double* base, svint64_t offsets; svbool_t pg = svptrue_b64(); offsets = svmul_n_s64_x( - pg, svunpklo_s64(svld1_s32(svwhilelt_b32(0, (int32_t)GMX_SIMD_DINT32_WIDTH), offset)), + pg, + svunpklo_s64(svld1_s32(svwhilelt_b32(0, (int32_t)GMX_SIMD_DINT32_WIDTH), offset)), align * sizeof(double)); svst1_scatter_s64offset_f64(pg, base, offsets, v0.simdInternal_); offsets = svadd_n_s64_x(pg, offsets, sizeof(double)); @@ -375,7 +378,8 @@ static inline void gmx_simdcall gatherLoadTransposeHsimd(const double* base svbool_t pg = svwhilelt_b64(0, (int32_t)GMX_SIMD_DOUBLE_WIDTH / 2); svfloat64_t _v0, _v1; offsets = svmul_n_s64_x( - pg, svunpklo(svld1_s32(svwhilelt_b32(0, (int32_t)GMX_SIMD_DINT32_WIDTH / 2), offset)), + pg, + svunpklo(svld1_s32(svwhilelt_b32(0, (int32_t)GMX_SIMD_DINT32_WIDTH / 2), offset)), align * sizeof(double)); _v0 = svld1_gather_s64offset_f64(pg, base0, offsets); _v1 = svld1_gather_s64offset_f64(pg, base1, offsets); diff --git a/src/gromacs/simd/impl_ibm_vmx/impl_ibm_vmx_simd4_float.h b/src/gromacs/simd/impl_ibm_vmx/impl_ibm_vmx_simd4_float.h index c489f92061..5b403de272 100644 --- a/src/gromacs/simd/impl_ibm_vmx/impl_ibm_vmx_simd4_float.h +++ b/src/gromacs/simd/impl_ibm_vmx/impl_ibm_vmx_simd4_float.h @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2014,2015,2019, by the GROMACS development team, led by + * Copyright (c) 2014,2015,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -135,8 +135,8 @@ static inline Simd4Float gmx_simdcall operator-(Simd4Float x) static inline Simd4Float gmx_simdcall operator*(Simd4Float a, Simd4Float b) { - return { vec_madd(a.simdInternal_, b.simdInternal_, - reinterpret_cast<__vector float>(vec_splat_u32(0))) }; + return { vec_madd( + a.simdInternal_, b.simdInternal_, reinterpret_cast<__vector float>(vec_splat_u32(0))) }; } static inline Simd4Float gmx_simdcall fma(Simd4Float a, Simd4Float b, Simd4Float c) @@ -193,8 +193,8 @@ static inline float gmx_simdcall dotProduct(Simd4Float a, Simd4Float b) { float res; - __vector float c = vec_madd(a.simdInternal_, b.simdInternal_, - reinterpret_cast<__vector float>(vec_splat_u32(0))); + __vector float c = vec_madd( + a.simdInternal_, b.simdInternal_, reinterpret_cast<__vector float>(vec_splat_u32(0))); // Keep only elements 0,1,2 by shifting in zero from right (xor of a vector with itself is 0) c = vec_sld(c, vec_xor(a.simdInternal_, a.simdInternal_), 4); // calculate sum diff --git a/src/gromacs/simd/impl_ibm_vmx/impl_ibm_vmx_simd_float.h b/src/gromacs/simd/impl_ibm_vmx/impl_ibm_vmx_simd_float.h index 4284e004bd..f397d401ff 100644 --- a/src/gromacs/simd/impl_ibm_vmx/impl_ibm_vmx_simd_float.h +++ b/src/gromacs/simd/impl_ibm_vmx/impl_ibm_vmx_simd_float.h @@ -191,8 +191,8 @@ static inline SimdFloat gmx_simdcall operator-(SimdFloat x) static inline SimdFloat gmx_simdcall operator*(SimdFloat a, SimdFloat b) { - return { vec_madd(a.simdInternal_, b.simdInternal_, - reinterpret_cast<__vector float>(vec_splat_u32(0))) }; + return { vec_madd( + a.simdInternal_, b.simdInternal_, reinterpret_cast<__vector float>(vec_splat_u32(0))) }; } static inline SimdFloat gmx_simdcall fma(SimdFloat a, SimdFloat b, SimdFloat c) @@ -335,7 +335,8 @@ static inline SimdFloat gmx_simdcall ldexp(SimdFloat value, SimdFInt32 exponent) iExponent = vec_sl(iExponent, vec_add(vec_splat_u32(15), vec_splat_u32(8))); - return { vec_madd(value.simdInternal_, reinterpret_cast<__vector float>(iExponent), + return { vec_madd(value.simdInternal_, + reinterpret_cast<__vector float>(iExponent), reinterpret_cast<__vector float>(vec_splat_u32(0))) }; } diff --git a/src/gromacs/simd/impl_ibm_vsx/impl_ibm_vsx_simd_double.h b/src/gromacs/simd/impl_ibm_vsx/impl_ibm_vsx_simd_double.h index 3c6f3009b1..53981ed8a7 100644 --- a/src/gromacs/simd/impl_ibm_vsx/impl_ibm_vsx_simd_double.h +++ b/src/gromacs/simd/impl_ibm_vsx/impl_ibm_vsx_simd_double.h @@ -415,10 +415,11 @@ static inline double gmx_simdcall reduce(SimdDouble x) const __vector unsigned char perm = { 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7 }; #ifdef __xlC__ /* old xlc version 12 does not understand vec_perm() with double arguments */ - x.simdInternal_ = vec_add( - x.simdInternal_, reinterpret_cast<__vector double>(vec_perm( - reinterpret_cast<__vector signed int>(x.simdInternal_), - reinterpret_cast<__vector signed int>(x.simdInternal_), perm))); + x.simdInternal_ = vec_add(x.simdInternal_, + reinterpret_cast<__vector double>(vec_perm( + reinterpret_cast<__vector signed int>(x.simdInternal_), + reinterpret_cast<__vector signed int>(x.simdInternal_), + perm))); #else x.simdInternal_ = vec_add(x.simdInternal_, vec_perm(x.simdInternal_, x.simdInternal_, perm)); #endif diff --git a/src/gromacs/simd/impl_x86_avx_256/impl_x86_avx_256_simd_double.h b/src/gromacs/simd/impl_x86_avx_256/impl_x86_avx_256_simd_double.h index db17ac26bd..d60a11c52c 100644 --- a/src/gromacs/simd/impl_x86_avx_256/impl_x86_avx_256_simd_double.h +++ b/src/gromacs/simd/impl_x86_avx_256/impl_x86_avx_256_simd_double.h @@ -331,9 +331,10 @@ static inline SimdDouble frexp(SimdDouble value, SimdDInt32* exponent) // precision fields, but a bit below we'll need a corresponding integer variable with 4x // 32-bit fields. Since AVX1 does not support shuffling across the upper/lower 128-bit // lanes, we need to extract those first, and then shuffle between two 128-bit variables. - __m128i iValueIsZero = _mm_castps_si128(_mm_shuffle_ps( - _mm256_extractf128_ps(_mm256_castpd_ps(valueIsZero), 0x0), - _mm256_extractf128_ps(_mm256_castpd_ps(valueIsZero), 0x1), _MM_SHUFFLE(2, 0, 2, 0))); + __m128i iValueIsZero = _mm_castps_si128( + _mm_shuffle_ps(_mm256_extractf128_ps(_mm256_castpd_ps(valueIsZero), 0x0), + _mm256_extractf128_ps(_mm256_castpd_ps(valueIsZero), 0x1), + _MM_SHUFFLE(2, 0, 2, 0))); // Set exponent to 0 when input value was zero iExponentLow = _mm_andnot_si128(iValueIsZero, iExponentLow); diff --git a/src/gromacs/simd/impl_x86_avx_256/impl_x86_avx_256_util_float.h b/src/gromacs/simd/impl_x86_avx_256/impl_x86_avx_256_util_float.h index 0e0957a813..532dd2eb1e 100644 --- a/src/gromacs/simd/impl_x86_avx_256/impl_x86_avx_256_util_float.h +++ b/src/gromacs/simd/impl_x86_avx_256/impl_x86_avx_256_util_float.h @@ -179,25 +179,33 @@ static inline void gmx_simdcall gatherLoadUTranspose(const float* base, // we can use aligned loads since base should also be aligned in this case assert(std::size_t(base) % 16 == 0); t1 = _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_load_ps(base + align * offset[0])), - _mm_load_ps(base + align * offset[4]), 0x1); + _mm_load_ps(base + align * offset[4]), + 0x1); t2 = _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_load_ps(base + align * offset[1])), - _mm_load_ps(base + align * offset[5]), 0x1); + _mm_load_ps(base + align * offset[5]), + 0x1); t3 = _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_load_ps(base + align * offset[2])), - _mm_load_ps(base + align * offset[6]), 0x1); + _mm_load_ps(base + align * offset[6]), + 0x1); t4 = _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_load_ps(base + align * offset[3])), - _mm_load_ps(base + align * offset[7]), 0x1); + _mm_load_ps(base + align * offset[7]), + 0x1); } else { // Use unaligned loads t1 = _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_loadu_ps(base + align * offset[0])), - _mm_loadu_ps(base + align * offset[4]), 0x1); + _mm_loadu_ps(base + align * offset[4]), + 0x1); t2 = _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_loadu_ps(base + align * offset[1])), - _mm_loadu_ps(base + align * offset[5]), 0x1); + _mm_loadu_ps(base + align * offset[5]), + 0x1); t3 = _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_loadu_ps(base + align * offset[2])), - _mm_loadu_ps(base + align * offset[6]), 0x1); + _mm_loadu_ps(base + align * offset[6]), + 0x1); t4 = _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_loadu_ps(base + align * offset[3])), - _mm_loadu_ps(base + align * offset[7]), 0x1); + _mm_loadu_ps(base + align * offset[7]), + 0x1); } t5 = _mm256_unpacklo_ps(t1, t2); @@ -325,34 +333,38 @@ static inline void gmx_simdcall _mm_add_ps(_mm_load_ps(base + align * offset[2]), _mm256_castps256_ps128(t7))); _mm_store_ps(base + align * offset[3], _mm_add_ps(_mm_load_ps(base + align * offset[3]), _mm256_castps256_ps128(t8))); - _mm_store_ps(base + align * offset[4], _mm_add_ps(_mm_load_ps(base + align * offset[4]), - _mm256_extractf128_ps(t5, 0x1))); - _mm_store_ps(base + align * offset[5], _mm_add_ps(_mm_load_ps(base + align * offset[5]), - _mm256_extractf128_ps(t6, 0x1))); - _mm_store_ps(base + align * offset[6], _mm_add_ps(_mm_load_ps(base + align * offset[6]), - _mm256_extractf128_ps(t7, 0x1))); - _mm_store_ps(base + align * offset[7], _mm_add_ps(_mm_load_ps(base + align * offset[7]), - _mm256_extractf128_ps(t8, 0x1))); + _mm_store_ps(base + align * offset[4], + _mm_add_ps(_mm_load_ps(base + align * offset[4]), _mm256_extractf128_ps(t5, 0x1))); + _mm_store_ps(base + align * offset[5], + _mm_add_ps(_mm_load_ps(base + align * offset[5]), _mm256_extractf128_ps(t6, 0x1))); + _mm_store_ps(base + align * offset[6], + _mm_add_ps(_mm_load_ps(base + align * offset[6]), _mm256_extractf128_ps(t7, 0x1))); + _mm_store_ps(base + align * offset[7], + _mm_add_ps(_mm_load_ps(base + align * offset[7]), _mm256_extractf128_ps(t8, 0x1))); } else { // alignment >=5, but not a multiple of 4 - _mm_storeu_ps(base + align * offset[0], _mm_add_ps(_mm_loadu_ps(base + align * offset[0]), - _mm256_castps256_ps128(t5))); - _mm_storeu_ps(base + align * offset[1], _mm_add_ps(_mm_loadu_ps(base + align * offset[1]), - _mm256_castps256_ps128(t6))); - _mm_storeu_ps(base + align * offset[2], _mm_add_ps(_mm_loadu_ps(base + align * offset[2]), - _mm256_castps256_ps128(t7))); - _mm_storeu_ps(base + align * offset[3], _mm_add_ps(_mm_loadu_ps(base + align * offset[3]), - _mm256_castps256_ps128(t8))); - _mm_storeu_ps(base + align * offset[4], _mm_add_ps(_mm_loadu_ps(base + align * offset[4]), - _mm256_extractf128_ps(t5, 0x1))); - _mm_storeu_ps(base + align * offset[5], _mm_add_ps(_mm_loadu_ps(base + align * offset[5]), - _mm256_extractf128_ps(t6, 0x1))); - _mm_storeu_ps(base + align * offset[6], _mm_add_ps(_mm_loadu_ps(base + align * offset[6]), - _mm256_extractf128_ps(t7, 0x1))); - _mm_storeu_ps(base + align * offset[7], _mm_add_ps(_mm_loadu_ps(base + align * offset[7]), - _mm256_extractf128_ps(t8, 0x1))); + _mm_storeu_ps(base + align * offset[0], + _mm_add_ps(_mm_loadu_ps(base + align * offset[0]), _mm256_castps256_ps128(t5))); + _mm_storeu_ps(base + align * offset[1], + _mm_add_ps(_mm_loadu_ps(base + align * offset[1]), _mm256_castps256_ps128(t6))); + _mm_storeu_ps(base + align * offset[2], + _mm_add_ps(_mm_loadu_ps(base + align * offset[2]), _mm256_castps256_ps128(t7))); + _mm_storeu_ps(base + align * offset[3], + _mm_add_ps(_mm_loadu_ps(base + align * offset[3]), _mm256_castps256_ps128(t8))); + _mm_storeu_ps( + base + align * offset[4], + _mm_add_ps(_mm_loadu_ps(base + align * offset[4]), _mm256_extractf128_ps(t5, 0x1))); + _mm_storeu_ps( + base + align * offset[5], + _mm_add_ps(_mm_loadu_ps(base + align * offset[5]), _mm256_extractf128_ps(t6, 0x1))); + _mm_storeu_ps( + base + align * offset[6], + _mm_add_ps(_mm_loadu_ps(base + align * offset[6]), _mm256_extractf128_ps(t7, 0x1))); + _mm_storeu_ps( + base + align * offset[7], + _mm_add_ps(_mm_loadu_ps(base + align * offset[7]), _mm256_extractf128_ps(t8, 0x1))); } } } @@ -453,34 +465,38 @@ static inline void gmx_simdcall _mm_sub_ps(_mm_load_ps(base + align * offset[2]), _mm256_castps256_ps128(t7))); _mm_store_ps(base + align * offset[3], _mm_sub_ps(_mm_load_ps(base + align * offset[3]), _mm256_castps256_ps128(t8))); - _mm_store_ps(base + align * offset[4], _mm_sub_ps(_mm_load_ps(base + align * offset[4]), - _mm256_extractf128_ps(t5, 0x1))); - _mm_store_ps(base + align * offset[5], _mm_sub_ps(_mm_load_ps(base + align * offset[5]), - _mm256_extractf128_ps(t6, 0x1))); - _mm_store_ps(base + align * offset[6], _mm_sub_ps(_mm_load_ps(base + align * offset[6]), - _mm256_extractf128_ps(t7, 0x1))); - _mm_store_ps(base + align * offset[7], _mm_sub_ps(_mm_load_ps(base + align * offset[7]), - _mm256_extractf128_ps(t8, 0x1))); + _mm_store_ps(base + align * offset[4], + _mm_sub_ps(_mm_load_ps(base + align * offset[4]), _mm256_extractf128_ps(t5, 0x1))); + _mm_store_ps(base + align * offset[5], + _mm_sub_ps(_mm_load_ps(base + align * offset[5]), _mm256_extractf128_ps(t6, 0x1))); + _mm_store_ps(base + align * offset[6], + _mm_sub_ps(_mm_load_ps(base + align * offset[6]), _mm256_extractf128_ps(t7, 0x1))); + _mm_store_ps(base + align * offset[7], + _mm_sub_ps(_mm_load_ps(base + align * offset[7]), _mm256_extractf128_ps(t8, 0x1))); } else { // alignment >=5, but not a multiple of 4 - _mm_storeu_ps(base + align * offset[0], _mm_sub_ps(_mm_loadu_ps(base + align * offset[0]), - _mm256_castps256_ps128(t5))); - _mm_storeu_ps(base + align * offset[1], _mm_sub_ps(_mm_loadu_ps(base + align * offset[1]), - _mm256_castps256_ps128(t6))); - _mm_storeu_ps(base + align * offset[2], _mm_sub_ps(_mm_loadu_ps(base + align * offset[2]), - _mm256_castps256_ps128(t7))); - _mm_storeu_ps(base + align * offset[3], _mm_sub_ps(_mm_loadu_ps(base + align * offset[3]), - _mm256_castps256_ps128(t8))); - _mm_storeu_ps(base + align * offset[4], _mm_sub_ps(_mm_loadu_ps(base + align * offset[4]), - _mm256_extractf128_ps(t5, 0x1))); - _mm_storeu_ps(base + align * offset[5], _mm_sub_ps(_mm_loadu_ps(base + align * offset[5]), - _mm256_extractf128_ps(t6, 0x1))); - _mm_storeu_ps(base + align * offset[6], _mm_sub_ps(_mm_loadu_ps(base + align * offset[6]), - _mm256_extractf128_ps(t7, 0x1))); - _mm_storeu_ps(base + align * offset[7], _mm_sub_ps(_mm_loadu_ps(base + align * offset[7]), - _mm256_extractf128_ps(t8, 0x1))); + _mm_storeu_ps(base + align * offset[0], + _mm_sub_ps(_mm_loadu_ps(base + align * offset[0]), _mm256_castps256_ps128(t5))); + _mm_storeu_ps(base + align * offset[1], + _mm_sub_ps(_mm_loadu_ps(base + align * offset[1]), _mm256_castps256_ps128(t6))); + _mm_storeu_ps(base + align * offset[2], + _mm_sub_ps(_mm_loadu_ps(base + align * offset[2]), _mm256_castps256_ps128(t7))); + _mm_storeu_ps(base + align * offset[3], + _mm_sub_ps(_mm_loadu_ps(base + align * offset[3]), _mm256_castps256_ps128(t8))); + _mm_storeu_ps( + base + align * offset[4], + _mm_sub_ps(_mm_loadu_ps(base + align * offset[4]), _mm256_extractf128_ps(t5, 0x1))); + _mm_storeu_ps( + base + align * offset[5], + _mm_sub_ps(_mm_loadu_ps(base + align * offset[5]), _mm256_extractf128_ps(t6, 0x1))); + _mm_storeu_ps( + base + align * offset[6], + _mm_sub_ps(_mm_loadu_ps(base + align * offset[6]), _mm256_extractf128_ps(t7, 0x1))); + _mm_storeu_ps( + base + align * offset[7], + _mm_sub_ps(_mm_loadu_ps(base + align * offset[7]), _mm256_extractf128_ps(t8, 0x1))); } } } diff --git a/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd4_double.h b/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd4_double.h index 75b7c2d663..165717e7d1 100644 --- a/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd4_double.h +++ b/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd4_double.h @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2014,2015,2016,2017,2019, by the GROMACS development team, led by + * Copyright (c) 2014,2015,2016,2017,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -220,26 +220,34 @@ static inline void gmx_simdcall transpose(Simd4Double* v0, Simd4Double* v1, Simd static inline Simd4DBool gmx_simdcall operator==(Simd4Double a, Simd4Double b) { - return { _mm512_mask_cmp_pd_mask(avx512Int2Mask(0xF), _mm512_castpd256_pd512(a.simdInternal_), - _mm512_castpd256_pd512(b.simdInternal_), _CMP_EQ_OQ) }; + return { _mm512_mask_cmp_pd_mask(avx512Int2Mask(0xF), + _mm512_castpd256_pd512(a.simdInternal_), + _mm512_castpd256_pd512(b.simdInternal_), + _CMP_EQ_OQ) }; } static inline Simd4DBool gmx_simdcall operator!=(Simd4Double a, Simd4Double b) { - return { _mm512_mask_cmp_pd_mask(avx512Int2Mask(0xF), _mm512_castpd256_pd512(a.simdInternal_), - _mm512_castpd256_pd512(b.simdInternal_), _CMP_NEQ_OQ) }; + return { _mm512_mask_cmp_pd_mask(avx512Int2Mask(0xF), + _mm512_castpd256_pd512(a.simdInternal_), + _mm512_castpd256_pd512(b.simdInternal_), + _CMP_NEQ_OQ) }; } static inline Simd4DBool gmx_simdcall operator<(Simd4Double a, Simd4Double b) { - return { _mm512_mask_cmp_pd_mask(avx512Int2Mask(0xF), _mm512_castpd256_pd512(a.simdInternal_), - _mm512_castpd256_pd512(b.simdInternal_), _CMP_LT_OQ) }; + return { _mm512_mask_cmp_pd_mask(avx512Int2Mask(0xF), + _mm512_castpd256_pd512(a.simdInternal_), + _mm512_castpd256_pd512(b.simdInternal_), + _CMP_LT_OQ) }; } static inline Simd4DBool gmx_simdcall operator<=(Simd4Double a, Simd4Double b) { - return { _mm512_mask_cmp_pd_mask(avx512Int2Mask(0xF), _mm512_castpd256_pd512(a.simdInternal_), - _mm512_castpd256_pd512(b.simdInternal_), _CMP_LE_OQ) }; + return { _mm512_mask_cmp_pd_mask(avx512Int2Mask(0xF), + _mm512_castpd256_pd512(a.simdInternal_), + _mm512_castpd256_pd512(b.simdInternal_), + _CMP_LE_OQ) }; } static inline Simd4DBool gmx_simdcall operator&&(Simd4DBool a, Simd4DBool b) @@ -259,14 +267,14 @@ static inline bool gmx_simdcall anyTrue(Simd4DBool x) static inline Simd4Double gmx_simdcall selectByMask(Simd4Double a, Simd4DBool m) { - return { _mm512_castpd512_pd256(_mm512_mask_mov_pd(_mm512_setzero_pd(), m.simdInternal_, - _mm512_castpd256_pd512(a.simdInternal_))) }; + return { _mm512_castpd512_pd256(_mm512_mask_mov_pd( + _mm512_setzero_pd(), m.simdInternal_, _mm512_castpd256_pd512(a.simdInternal_))) }; } static inline Simd4Double gmx_simdcall selectByNotMask(Simd4Double a, Simd4DBool m) { - return { _mm512_castpd512_pd256(_mm512_mask_mov_pd(_mm512_castpd256_pd512(a.simdInternal_), - m.simdInternal_, _mm512_setzero_pd())) }; + return { _mm512_castpd512_pd256(_mm512_mask_mov_pd( + _mm512_castpd256_pd512(a.simdInternal_), m.simdInternal_, _mm512_setzero_pd())) }; } static inline Simd4Double gmx_simdcall blend(Simd4Double a, Simd4Double b, Simd4DBool sel) diff --git a/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd4_float.h b/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd4_float.h index 48debf7f2f..46928859ec 100644 --- a/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd4_float.h +++ b/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd4_float.h @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2014,2015,2016,2019, by the GROMACS development team, led by + * Copyright (c) 2014,2015,2016,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -218,26 +218,34 @@ static inline void gmx_simdcall transpose(Simd4Float* v0, Simd4Float* v1, Simd4F static inline Simd4FBool gmx_simdcall operator==(Simd4Float a, Simd4Float b) { - return { _mm512_mask_cmp_ps_mask(avx512Int2Mask(0xF), _mm512_castps128_ps512(a.simdInternal_), - _mm512_castps128_ps512(b.simdInternal_), _CMP_EQ_OQ) }; + return { _mm512_mask_cmp_ps_mask(avx512Int2Mask(0xF), + _mm512_castps128_ps512(a.simdInternal_), + _mm512_castps128_ps512(b.simdInternal_), + _CMP_EQ_OQ) }; } static inline Simd4FBool gmx_simdcall operator!=(Simd4Float a, Simd4Float b) { - return { _mm512_mask_cmp_ps_mask(avx512Int2Mask(0xF), _mm512_castps128_ps512(a.simdInternal_), - _mm512_castps128_ps512(b.simdInternal_), _CMP_NEQ_OQ) }; + return { _mm512_mask_cmp_ps_mask(avx512Int2Mask(0xF), + _mm512_castps128_ps512(a.simdInternal_), + _mm512_castps128_ps512(b.simdInternal_), + _CMP_NEQ_OQ) }; } static inline Simd4FBool gmx_simdcall operator<(Simd4Float a, Simd4Float b) { - return { _mm512_mask_cmp_ps_mask(avx512Int2Mask(0xF), _mm512_castps128_ps512(a.simdInternal_), - _mm512_castps128_ps512(b.simdInternal_), _CMP_LT_OQ) }; + return { _mm512_mask_cmp_ps_mask(avx512Int2Mask(0xF), + _mm512_castps128_ps512(a.simdInternal_), + _mm512_castps128_ps512(b.simdInternal_), + _CMP_LT_OQ) }; } static inline Simd4FBool gmx_simdcall operator<=(Simd4Float a, Simd4Float b) { - return { _mm512_mask_cmp_ps_mask(avx512Int2Mask(0xF), _mm512_castps128_ps512(a.simdInternal_), - _mm512_castps128_ps512(b.simdInternal_), _CMP_LE_OQ) }; + return { _mm512_mask_cmp_ps_mask(avx512Int2Mask(0xF), + _mm512_castps128_ps512(a.simdInternal_), + _mm512_castps128_ps512(b.simdInternal_), + _CMP_LE_OQ) }; } static inline Simd4FBool gmx_simdcall operator&&(Simd4FBool a, Simd4FBool b) @@ -257,14 +265,14 @@ static inline bool gmx_simdcall anyTrue(Simd4FBool a) static inline Simd4Float gmx_simdcall selectByMask(Simd4Float a, Simd4FBool m) { - return { _mm512_castps512_ps128(_mm512_mask_mov_ps(_mm512_setzero_ps(), m.simdInternal_, - _mm512_castps128_ps512(a.simdInternal_))) }; + return { _mm512_castps512_ps128(_mm512_mask_mov_ps( + _mm512_setzero_ps(), m.simdInternal_, _mm512_castps128_ps512(a.simdInternal_))) }; } static inline Simd4Float gmx_simdcall selectByNotMask(Simd4Float a, Simd4FBool m) { - return { _mm512_castps512_ps128(_mm512_mask_mov_ps(_mm512_castps128_ps512(a.simdInternal_), - m.simdInternal_, _mm512_setzero_ps())) }; + return { _mm512_castps512_ps128(_mm512_mask_mov_ps( + _mm512_castps128_ps512(a.simdInternal_), m.simdInternal_, _mm512_setzero_ps())) }; } static inline Simd4Float gmx_simdcall blend(Simd4Float a, Simd4Float b, Simd4FBool sel) diff --git a/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd_double.h b/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd_double.h index 8dd20c2e6c..669c2aaeff 100644 --- a/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd_double.h +++ b/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd_double.h @@ -315,8 +315,8 @@ static inline SimdDouble frexp(SimdDouble value, SimdDInt32* exponent) iExponent = _mm256_add_epi32(iExponent, _mm256_set1_epi32(1)); // Set result to value (+-0) when it is zero. - result = _mm512_mask_getmant_pd(value.simdInternal_, valueIsNonZero, value.simdInternal_, - _MM_MANT_NORM_p5_1, _MM_MANT_SIGN_src); + result = _mm512_mask_getmant_pd( + value.simdInternal_, valueIsNonZero, value.simdInternal_, _MM_MANT_NORM_p5_1, _MM_MANT_SIGN_src); } else { @@ -423,7 +423,8 @@ static inline SimdDouble gmx_simdcall copysign(SimdDouble a, SimdDouble b) { return { _mm512_castsi512_pd(_mm512_ternarylogic_epi64(_mm512_castpd_si512(a.simdInternal_), _mm512_castpd_si512(b.simdInternal_), - _mm512_set1_epi64(INT64_MIN), 0xD8)) }; + _mm512_set1_epi64(INT64_MIN), + 0xD8)) }; } static inline SimdDInt32 gmx_simdcall operator&(SimdDInt32 a, SimdDInt32 b) @@ -463,20 +464,25 @@ static inline SimdDInt32 gmx_simdcall operator*(SimdDInt32 a, SimdDInt32 b) static inline SimdDIBool gmx_simdcall operator==(SimdDInt32 a, SimdDInt32 b) { - return { _mm512_mask_cmp_epi32_mask(avx512Int2Mask(0xFF), _mm512_castsi256_si512(a.simdInternal_), - _mm512_castsi256_si512(b.simdInternal_), _MM_CMPINT_EQ) }; + return { _mm512_mask_cmp_epi32_mask(avx512Int2Mask(0xFF), + _mm512_castsi256_si512(a.simdInternal_), + _mm512_castsi256_si512(b.simdInternal_), + _MM_CMPINT_EQ) }; } static inline SimdDIBool gmx_simdcall testBits(SimdDInt32 a) { - return { _mm512_mask_test_epi32_mask(avx512Int2Mask(0xFF), _mm512_castsi256_si512(a.simdInternal_), + return { _mm512_mask_test_epi32_mask(avx512Int2Mask(0xFF), + _mm512_castsi256_si512(a.simdInternal_), _mm512_castsi256_si512(a.simdInternal_)) }; } static inline SimdDIBool gmx_simdcall operator<(SimdDInt32 a, SimdDInt32 b) { - return { _mm512_mask_cmp_epi32_mask(avx512Int2Mask(0xFF), _mm512_castsi256_si512(a.simdInternal_), - _mm512_castsi256_si512(b.simdInternal_), _MM_CMPINT_LT) }; + return { _mm512_mask_cmp_epi32_mask(avx512Int2Mask(0xFF), + _mm512_castsi256_si512(a.simdInternal_), + _mm512_castsi256_si512(b.simdInternal_), + _MM_CMPINT_LT) }; } static inline SimdDIBool gmx_simdcall operator&&(SimdDIBool a, SimdDIBool b) @@ -508,9 +514,9 @@ static inline SimdDInt32 gmx_simdcall selectByNotMask(SimdDInt32 a, SimdDIBool m static inline SimdDInt32 gmx_simdcall blend(SimdDInt32 a, SimdDInt32 b, SimdDIBool sel) { - return { _mm512_castsi512_si256( - _mm512_mask_blend_epi32(sel.simdInternal_, _mm512_castsi256_si512(a.simdInternal_), - _mm512_castsi256_si512(b.simdInternal_))) }; + return { _mm512_castsi512_si256(_mm512_mask_blend_epi32(sel.simdInternal_, + _mm512_castsi256_si512(a.simdInternal_), + _mm512_castsi256_si512(b.simdInternal_))) }; } static inline SimdDInt32 gmx_simdcall cvtR2I(SimdDouble a) diff --git a/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd_float.h b/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd_float.h index 6ef6b774d3..86594486f1 100644 --- a/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd_float.h +++ b/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_simd_float.h @@ -309,8 +309,8 @@ static inline SimdFloat gmx_simdcall frexp(SimdFloat value, SimdFInt32* exponent iExponent = _mm512_mask_add_epi32(iExponent, valueIsNonZero, iExponent, _mm512_set1_epi32(1)); // Set result to input value when the latter is +-0 - result = _mm512_mask_getmant_ps(value.simdInternal_, valueIsNonZero, value.simdInternal_, - _MM_MANT_NORM_p5_1, _MM_MANT_SIGN_src); + result = _mm512_mask_getmant_ps( + value.simdInternal_, valueIsNonZero, value.simdInternal_, _MM_MANT_NORM_p5_1, _MM_MANT_SIGN_src); } else { @@ -415,7 +415,8 @@ static inline SimdFloat gmx_simdcall copysign(SimdFloat a, SimdFloat b) { return { _mm512_castsi512_ps(_mm512_ternarylogic_epi32(_mm512_castps_si512(a.simdInternal_), _mm512_castps_si512(b.simdInternal_), - _mm512_set1_epi32(INT32_MIN), 0xD8)) }; + _mm512_set1_epi32(INT32_MIN), + 0xD8)) }; } static inline SimdFInt32 gmx_simdcall operator&(SimdFInt32 a, SimdFInt32 b) diff --git a/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_util_double.h b/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_util_double.h index dac65b0978..acde31b609 100644 --- a/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_util_double.h +++ b/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_util_double.h @@ -164,8 +164,9 @@ static inline void gmx_simdcall __m512d t[4], t5, t6, t7, t8; alignas(GMX_SIMD_ALIGNMENT) std::int64_t o[8]; // TODO: should use fastMultiply - _mm512_store_epi64(o, _mm512_cvtepi32_epi64(_mm256_mullo_epi32( - _mm256_load_si256((const __m256i*)(offset)), _mm256_set1_epi32(align)))); + _mm512_store_epi64(o, + _mm512_cvtepi32_epi64(_mm256_mullo_epi32( + _mm256_load_si256((const __m256i*)(offset)), _mm256_set1_epi32(align)))); t5 = _mm512_unpacklo_pd(v0.simdInternal_, v1.simdInternal_); t6 = _mm512_unpackhi_pd(v0.simdInternal_, v1.simdInternal_); t7 = _mm512_unpacklo_pd(v2.simdInternal_, _mm512_setzero_pd()); @@ -178,11 +179,13 @@ static inline void gmx_simdcall { for (int i = 0; i < 4; i++) { - _mm512_mask_storeu_pd(base + o[0 + i], avx512Int2Mask(7), + _mm512_mask_storeu_pd(base + o[0 + i], + avx512Int2Mask(7), _mm512_castpd256_pd512(_mm256_add_pd(_mm256_loadu_pd(base + o[0 + i]), _mm512_castpd512_pd256(t[i])))); _mm512_mask_storeu_pd( - base + o[4 + i], avx512Int2Mask(7), + base + o[4 + i], + avx512Int2Mask(7), _mm512_castpd256_pd512(_mm256_add_pd(_mm256_loadu_pd(base + o[4 + i]), _mm512_extractf64x4_pd(t[i], 1)))); } @@ -193,20 +196,24 @@ static inline void gmx_simdcall { for (int i = 0; i < 4; i++) { - _mm256_store_pd(base + o[0 + i], _mm256_add_pd(_mm256_load_pd(base + o[0 + i]), - _mm512_castpd512_pd256(t[i]))); - _mm256_store_pd(base + o[4 + i], _mm256_add_pd(_mm256_load_pd(base + o[4 + i]), - _mm512_extractf64x4_pd(t[i], 1))); + _mm256_store_pd( + base + o[0 + i], + _mm256_add_pd(_mm256_load_pd(base + o[0 + i]), _mm512_castpd512_pd256(t[i]))); + _mm256_store_pd(base + o[4 + i], + _mm256_add_pd(_mm256_load_pd(base + o[4 + i]), + _mm512_extractf64x4_pd(t[i], 1))); } } else { for (int i = 0; i < 4; i++) { - _mm256_storeu_pd(base + o[0 + i], _mm256_add_pd(_mm256_loadu_pd(base + o[0 + i]), - _mm512_castpd512_pd256(t[i]))); - _mm256_storeu_pd(base + o[4 + i], _mm256_add_pd(_mm256_loadu_pd(base + o[4 + i]), - _mm512_extractf64x4_pd(t[i], 1))); + _mm256_storeu_pd( + base + o[0 + i], + _mm256_add_pd(_mm256_loadu_pd(base + o[0 + i]), _mm512_castpd512_pd256(t[i]))); + _mm256_storeu_pd(base + o[4 + i], + _mm256_add_pd(_mm256_loadu_pd(base + o[4 + i]), + _mm512_extractf64x4_pd(t[i], 1))); } } } @@ -219,8 +226,9 @@ static inline void gmx_simdcall __m512d t[4], t5, t6, t7, t8; alignas(GMX_SIMD_ALIGNMENT) std::int64_t o[8]; // TODO: should use fastMultiply - _mm512_store_epi64(o, _mm512_cvtepi32_epi64(_mm256_mullo_epi32( - _mm256_load_si256((const __m256i*)(offset)), _mm256_set1_epi32(align)))); + _mm512_store_epi64(o, + _mm512_cvtepi32_epi64(_mm256_mullo_epi32( + _mm256_load_si256((const __m256i*)(offset)), _mm256_set1_epi32(align)))); t5 = _mm512_unpacklo_pd(v0.simdInternal_, v1.simdInternal_); t6 = _mm512_unpackhi_pd(v0.simdInternal_, v1.simdInternal_); t7 = _mm512_unpacklo_pd(v2.simdInternal_, _mm512_setzero_pd()); @@ -233,11 +241,13 @@ static inline void gmx_simdcall { for (int i = 0; i < 4; i++) { - _mm512_mask_storeu_pd(base + o[0 + i], avx512Int2Mask(7), + _mm512_mask_storeu_pd(base + o[0 + i], + avx512Int2Mask(7), _mm512_castpd256_pd512(_mm256_sub_pd(_mm256_loadu_pd(base + o[0 + i]), _mm512_castpd512_pd256(t[i])))); _mm512_mask_storeu_pd( - base + o[4 + i], avx512Int2Mask(7), + base + o[4 + i], + avx512Int2Mask(7), _mm512_castpd256_pd512(_mm256_sub_pd(_mm256_loadu_pd(base + o[4 + i]), _mm512_extractf64x4_pd(t[i], 1)))); } @@ -248,20 +258,24 @@ static inline void gmx_simdcall { for (int i = 0; i < 4; i++) { - _mm256_store_pd(base + o[0 + i], _mm256_sub_pd(_mm256_load_pd(base + o[0 + i]), - _mm512_castpd512_pd256(t[i]))); - _mm256_store_pd(base + o[4 + i], _mm256_sub_pd(_mm256_load_pd(base + o[4 + i]), - _mm512_extractf64x4_pd(t[i], 1))); + _mm256_store_pd( + base + o[0 + i], + _mm256_sub_pd(_mm256_load_pd(base + o[0 + i]), _mm512_castpd512_pd256(t[i]))); + _mm256_store_pd(base + o[4 + i], + _mm256_sub_pd(_mm256_load_pd(base + o[4 + i]), + _mm512_extractf64x4_pd(t[i], 1))); } } else { for (int i = 0; i < 4; i++) { - _mm256_storeu_pd(base + o[0 + i], _mm256_sub_pd(_mm256_loadu_pd(base + o[0 + i]), - _mm512_castpd512_pd256(t[i]))); - _mm256_storeu_pd(base + o[4 + i], _mm256_sub_pd(_mm256_loadu_pd(base + o[4 + i]), - _mm512_extractf64x4_pd(t[i], 1))); + _mm256_storeu_pd( + base + o[0 + i], + _mm256_sub_pd(_mm256_loadu_pd(base + o[0 + i]), _mm512_castpd512_pd256(t[i]))); + _mm256_storeu_pd(base + o[4 + i], + _mm256_sub_pd(_mm256_loadu_pd(base + o[4 + i]), + _mm512_extractf64x4_pd(t[i], 1))); } } } @@ -294,10 +308,10 @@ static inline double gmx_simdcall t0 = _mm512_add_pd(v0.simdInternal_, _mm512_permute_pd(v0.simdInternal_, 0x55)); t2 = _mm512_add_pd(v2.simdInternal_, _mm512_permute_pd(v2.simdInternal_, 0x55)); - t0 = _mm512_mask_add_pd(t0, avx512Int2Mask(0xAA), v1.simdInternal_, - _mm512_permute_pd(v1.simdInternal_, 0x55)); - t2 = _mm512_mask_add_pd(t2, avx512Int2Mask(0xAA), v3.simdInternal_, - _mm512_permute_pd(v3.simdInternal_, 0x55)); + t0 = _mm512_mask_add_pd( + t0, avx512Int2Mask(0xAA), v1.simdInternal_, _mm512_permute_pd(v1.simdInternal_, 0x55)); + t2 = _mm512_mask_add_pd( + t2, avx512Int2Mask(0xAA), v3.simdInternal_, _mm512_permute_pd(v3.simdInternal_, 0x55)); t0 = _mm512_add_pd(t0, _mm512_shuffle_f64x2(t0, t0, 0x4E)); t0 = _mm512_mask_add_pd(t0, avx512Int2Mask(0xF0), t2, _mm512_shuffle_f64x2(t2, t2, 0x4E)); t0 = _mm512_add_pd(t0, _mm512_shuffle_f64x2(t0, t0, 0xB1)); @@ -331,8 +345,8 @@ static inline SimdDouble gmx_simdcall loadDuplicateHsimd(const double* m) static inline SimdDouble gmx_simdcall loadU1DualHsimd(const double* m) { - return { _mm512_insertf64x4(_mm512_broadcastsd_pd(_mm_load_sd(m)), - _mm256_broadcastsd_pd(_mm_load_sd(m + 1)), 1) }; + return { _mm512_insertf64x4( + _mm512_broadcastsd_pd(_mm_load_sd(m)), _mm256_broadcastsd_pd(_mm_load_sd(m + 1)), 1) }; } @@ -410,8 +424,8 @@ static inline double gmx_simdcall reduceIncr4ReturnSumHsimd(double* m, SimdDoubl assert(std::size_t(m) % 32 == 0); t0 = _mm512_add_pd(v0.simdInternal_, _mm512_permutex_pd(v0.simdInternal_, 0x4E)); - t0 = _mm512_mask_add_pd(t0, avx512Int2Mask(0xCC), v1.simdInternal_, - _mm512_permutex_pd(v1.simdInternal_, 0x4E)); + t0 = _mm512_mask_add_pd( + t0, avx512Int2Mask(0xCC), v1.simdInternal_, _mm512_permutex_pd(v1.simdInternal_, 0x4E)); t0 = _mm512_add_pd(t0, _mm512_permutex_pd(t0, 0xB1)); t0 = _mm512_mask_shuffle_f64x2(t0, avx512Int2Mask(0xAA), t0, t0, 0xEE); @@ -428,8 +442,8 @@ static inline double gmx_simdcall reduceIncr4ReturnSumHsimd(double* m, SimdDoubl static inline SimdDouble gmx_simdcall loadU4NOffset(const double* m, int offset) { - return { _mm512_insertf64x4(_mm512_castpd256_pd512(_mm256_loadu_pd(m)), - _mm256_loadu_pd(m + offset), 1) }; + return { _mm512_insertf64x4( + _mm512_castpd256_pd512(_mm256_loadu_pd(m)), _mm256_loadu_pd(m + offset), 1) }; } } // namespace gmx diff --git a/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_util_float.h b/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_util_float.h index 8c3f9621a1..65d1320d67 100644 --- a/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_util_float.h +++ b/src/gromacs/simd/impl_x86_avx_512/impl_x86_avx_512_util_float.h @@ -173,16 +173,20 @@ static inline void gmx_simdcall t[3] = _mm512_shuffle_ps(t6, v2.simdInternal_, _MM_SHUFFLE(3, 3, 3, 2)); for (i = 0; i < 4; i++) { - _mm512_mask_storeu_ps(base + o[i], avx512Int2Mask(7), + _mm512_mask_storeu_ps(base + o[i], + avx512Int2Mask(7), _mm512_castps128_ps512(_mm_add_ps(_mm_loadu_ps(base + o[i]), _mm512_castps512_ps128(t[i])))); - _mm512_mask_storeu_ps(base + o[4 + i], avx512Int2Mask(7), + _mm512_mask_storeu_ps(base + o[4 + i], + avx512Int2Mask(7), _mm512_castps128_ps512(_mm_add_ps(_mm_loadu_ps(base + o[4 + i]), _mm512_extractf32x4_ps(t[i], 1)))); - _mm512_mask_storeu_ps(base + o[8 + i], avx512Int2Mask(7), + _mm512_mask_storeu_ps(base + o[8 + i], + avx512Int2Mask(7), _mm512_castps128_ps512(_mm_add_ps(_mm_loadu_ps(base + o[8 + i]), _mm512_extractf32x4_ps(t[i], 2)))); - _mm512_mask_storeu_ps(base + o[12 + i], avx512Int2Mask(7), + _mm512_mask_storeu_ps(base + o[12 + i], + avx512Int2Mask(7), _mm512_castps128_ps512(_mm_add_ps(_mm_loadu_ps(base + o[12 + i]), _mm512_extractf32x4_ps(t[i], 3)))); } @@ -208,8 +212,8 @@ static inline void gmx_simdcall _mm_add_ps(_mm_load_ps(base + o[4 + i]), _mm512_extractf32x4_ps(t[i], 1))); _mm_store_ps(base + o[8 + i], _mm_add_ps(_mm_load_ps(base + o[8 + i]), _mm512_extractf32x4_ps(t[i], 2))); - _mm_store_ps(base + o[12 + i], _mm_add_ps(_mm_load_ps(base + o[12 + i]), - _mm512_extractf32x4_ps(t[i], 3))); + _mm_store_ps(base + o[12 + i], + _mm_add_ps(_mm_load_ps(base + o[12 + i]), _mm512_extractf32x4_ps(t[i], 3))); } } else @@ -218,12 +222,12 @@ static inline void gmx_simdcall { _mm_storeu_ps(base + o[i], _mm_add_ps(_mm_loadu_ps(base + o[i]), _mm512_castps512_ps128(t[i]))); - _mm_storeu_ps(base + o[4 + i], _mm_add_ps(_mm_loadu_ps(base + o[4 + i]), - _mm512_extractf32x4_ps(t[i], 1))); - _mm_storeu_ps(base + o[8 + i], _mm_add_ps(_mm_loadu_ps(base + o[8 + i]), - _mm512_extractf32x4_ps(t[i], 2))); - _mm_storeu_ps(base + o[12 + i], _mm_add_ps(_mm_loadu_ps(base + o[12 + i]), - _mm512_extractf32x4_ps(t[i], 3))); + _mm_storeu_ps(base + o[4 + i], + _mm_add_ps(_mm_loadu_ps(base + o[4 + i]), _mm512_extractf32x4_ps(t[i], 1))); + _mm_storeu_ps(base + o[8 + i], + _mm_add_ps(_mm_loadu_ps(base + o[8 + i]), _mm512_extractf32x4_ps(t[i], 2))); + _mm_storeu_ps(base + o[12 + i], + _mm_add_ps(_mm_loadu_ps(base + o[12 + i]), _mm512_extractf32x4_ps(t[i], 3))); } } } @@ -247,16 +251,20 @@ static inline void gmx_simdcall t[3] = _mm512_shuffle_ps(t6, v2.simdInternal_, _MM_SHUFFLE(3, 3, 3, 2)); for (i = 0; i < 4; i++) { - _mm512_mask_storeu_ps(base + o[i], avx512Int2Mask(7), + _mm512_mask_storeu_ps(base + o[i], + avx512Int2Mask(7), _mm512_castps128_ps512(_mm_sub_ps(_mm_loadu_ps(base + o[i]), _mm512_castps512_ps128(t[i])))); - _mm512_mask_storeu_ps(base + o[4 + i], avx512Int2Mask(7), + _mm512_mask_storeu_ps(base + o[4 + i], + avx512Int2Mask(7), _mm512_castps128_ps512(_mm_sub_ps(_mm_loadu_ps(base + o[4 + i]), _mm512_extractf32x4_ps(t[i], 1)))); - _mm512_mask_storeu_ps(base + o[8 + i], avx512Int2Mask(7), + _mm512_mask_storeu_ps(base + o[8 + i], + avx512Int2Mask(7), _mm512_castps128_ps512(_mm_sub_ps(_mm_loadu_ps(base + o[8 + i]), _mm512_extractf32x4_ps(t[i], 2)))); - _mm512_mask_storeu_ps(base + o[12 + i], avx512Int2Mask(7), + _mm512_mask_storeu_ps(base + o[12 + i], + avx512Int2Mask(7), _mm512_castps128_ps512(_mm_sub_ps(_mm_loadu_ps(base + o[12 + i]), _mm512_extractf32x4_ps(t[i], 3)))); } @@ -282,8 +290,8 @@ static inline void gmx_simdcall _mm_sub_ps(_mm_load_ps(base + o[4 + i]), _mm512_extractf32x4_ps(t[i], 1))); _mm_store_ps(base + o[8 + i], _mm_sub_ps(_mm_load_ps(base + o[8 + i]), _mm512_extractf32x4_ps(t[i], 2))); - _mm_store_ps(base + o[12 + i], _mm_sub_ps(_mm_load_ps(base + o[12 + i]), - _mm512_extractf32x4_ps(t[i], 3))); + _mm_store_ps(base + o[12 + i], + _mm_sub_ps(_mm_load_ps(base + o[12 + i]), _mm512_extractf32x4_ps(t[i], 3))); } } else @@ -292,12 +300,12 @@ static inline void gmx_simdcall { _mm_storeu_ps(base + o[i], _mm_sub_ps(_mm_loadu_ps(base + o[i]), _mm512_castps512_ps128(t[i]))); - _mm_storeu_ps(base + o[4 + i], _mm_sub_ps(_mm_loadu_ps(base + o[4 + i]), - _mm512_extractf32x4_ps(t[i], 1))); - _mm_storeu_ps(base + o[8 + i], _mm_sub_ps(_mm_loadu_ps(base + o[8 + i]), - _mm512_extractf32x4_ps(t[i], 2))); - _mm_storeu_ps(base + o[12 + i], _mm_sub_ps(_mm_loadu_ps(base + o[12 + i]), - _mm512_extractf32x4_ps(t[i], 3))); + _mm_storeu_ps(base + o[4 + i], + _mm_sub_ps(_mm_loadu_ps(base + o[4 + i]), _mm512_extractf32x4_ps(t[i], 1))); + _mm_storeu_ps(base + o[8 + i], + _mm_sub_ps(_mm_loadu_ps(base + o[8 + i]), _mm512_extractf32x4_ps(t[i], 2))); + _mm_storeu_ps(base + o[12 + i], + _mm_sub_ps(_mm_loadu_ps(base + o[12 + i]), _mm512_extractf32x4_ps(t[i], 3))); } } } @@ -326,11 +334,11 @@ static inline float gmx_simdcall reduceIncr4ReturnSum(float* m, SimdFloat v0, Si assert(std::size_t(m) % 16 == 0); t0 = _mm512_add_ps(v0.simdInternal_, _mm512_permute_ps(v0.simdInternal_, 0x4E)); - t0 = _mm512_mask_add_ps(t0, avx512Int2Mask(0xCCCC), v2.simdInternal_, - _mm512_permute_ps(v2.simdInternal_, 0x4E)); + t0 = _mm512_mask_add_ps( + t0, avx512Int2Mask(0xCCCC), v2.simdInternal_, _mm512_permute_ps(v2.simdInternal_, 0x4E)); t1 = _mm512_add_ps(v1.simdInternal_, _mm512_permute_ps(v1.simdInternal_, 0x4E)); - t1 = _mm512_mask_add_ps(t1, avx512Int2Mask(0xCCCC), v3.simdInternal_, - _mm512_permute_ps(v3.simdInternal_, 0x4E)); + t1 = _mm512_mask_add_ps( + t1, avx512Int2Mask(0xCCCC), v3.simdInternal_, _mm512_permute_ps(v3.simdInternal_, 0x4E)); t2 = _mm512_add_ps(t0, _mm512_permute_ps(t0, 0xB1)); t2 = _mm512_mask_add_ps(t2, avx512Int2Mask(0xAAAA), t1, _mm512_permute_ps(t1, 0xB1)); @@ -355,7 +363,8 @@ static inline SimdFloat gmx_simdcall loadDualHsimd(const float* m0, const float* return { _mm512_castpd_ps(_mm512_insertf64x4( _mm512_castpd256_pd512(_mm256_load_pd(reinterpret_cast(m0))), - _mm256_load_pd(reinterpret_cast(m1)), 1)) }; + _mm256_load_pd(reinterpret_cast(m1)), + 1)) }; } static inline SimdFloat gmx_simdcall loadDuplicateHsimd(const float* m) @@ -366,8 +375,8 @@ static inline SimdFloat gmx_simdcall loadDuplicateHsimd(const float* m) static inline SimdFloat gmx_simdcall loadU1DualHsimd(const float* m) { - return { _mm512_shuffle_f32x4(_mm512_broadcastss_ps(_mm_load_ss(m)), - _mm512_broadcastss_ps(_mm_load_ss(m + 1)), 0x44) }; + return { _mm512_shuffle_f32x4( + _mm512_broadcastss_ps(_mm_load_ss(m)), _mm512_broadcastss_ps(_mm_load_ss(m + 1)), 0x44) }; } diff --git a/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd4_double.h b/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd4_double.h index b4965c9677..8179a1c4e0 100644 --- a/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd4_double.h +++ b/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd4_double.h @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2014,2015,2017,2019, by the GROMACS development team, led by + * Copyright (c) 2014,2015,2017,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -76,8 +76,8 @@ public: static inline Simd4Double gmx_simdcall load4(const double* m) { assert(size_t(m) % 32 == 0); - return { _mm512_mask_extload_pd(_mm512_undefined_pd(), _mm512_int2mask(0xF), m, - _MM_UPCONV_PD_NONE, _MM_BROADCAST_4X8, _MM_HINT_NONE) }; + return { _mm512_mask_extload_pd( + _mm512_undefined_pd(), _mm512_int2mask(0xF), m, _MM_UPCONV_PD_NONE, _MM_BROADCAST_4X8, _MM_HINT_NONE) }; } static inline void gmx_simdcall store4(double* m, Simd4Double a) @@ -90,7 +90,8 @@ static inline Simd4Double gmx_simdcall load4U(const double* m) { return { _mm512_mask_loadunpackhi_pd( _mm512_mask_loadunpacklo_pd(_mm512_undefined_pd(), _mm512_int2mask(0xF), m), - _mm512_int2mask(0xF), m + 8) }; + _mm512_int2mask(0xF), + m + 8) }; } static inline void gmx_simdcall store4U(double* m, Simd4Double a) @@ -106,54 +107,58 @@ static inline Simd4Double gmx_simdcall simd4SetZeroD() static inline Simd4Double gmx_simdcall operator&(Simd4Double a, Simd4Double b) { - return { _mm512_castsi512_pd(_mm512_mask_and_epi32( - _mm512_undefined_epi32(), _mm512_int2mask(0x00FF), _mm512_castpd_si512(a.simdInternal_), - _mm512_castpd_si512(b.simdInternal_))) }; + return { _mm512_castsi512_pd(_mm512_mask_and_epi32(_mm512_undefined_epi32(), + _mm512_int2mask(0x00FF), + _mm512_castpd_si512(a.simdInternal_), + _mm512_castpd_si512(b.simdInternal_))) }; } static inline Simd4Double gmx_simdcall andNot(Simd4Double a, Simd4Double b) { - return { _mm512_castsi512_pd(_mm512_mask_andnot_epi32( - _mm512_undefined_epi32(), _mm512_int2mask(0x00FF), _mm512_castpd_si512(a.simdInternal_), - _mm512_castpd_si512(b.simdInternal_))) }; + return { _mm512_castsi512_pd(_mm512_mask_andnot_epi32(_mm512_undefined_epi32(), + _mm512_int2mask(0x00FF), + _mm512_castpd_si512(a.simdInternal_), + _mm512_castpd_si512(b.simdInternal_))) }; } static inline Simd4Double gmx_simdcall operator|(Simd4Double a, Simd4Double b) { - return { _mm512_castsi512_pd(_mm512_mask_or_epi32( - _mm512_undefined_epi32(), _mm512_int2mask(0x00FF), _mm512_castpd_si512(a.simdInternal_), - _mm512_castpd_si512(b.simdInternal_))) }; + return { _mm512_castsi512_pd(_mm512_mask_or_epi32(_mm512_undefined_epi32(), + _mm512_int2mask(0x00FF), + _mm512_castpd_si512(a.simdInternal_), + _mm512_castpd_si512(b.simdInternal_))) }; } static inline Simd4Double gmx_simdcall operator^(Simd4Double a, Simd4Double b) { - return { _mm512_castsi512_pd(_mm512_mask_xor_epi32( - _mm512_undefined_epi32(), _mm512_int2mask(0x00FF), _mm512_castpd_si512(a.simdInternal_), - _mm512_castpd_si512(b.simdInternal_))) }; + return { _mm512_castsi512_pd(_mm512_mask_xor_epi32(_mm512_undefined_epi32(), + _mm512_int2mask(0x00FF), + _mm512_castpd_si512(a.simdInternal_), + _mm512_castpd_si512(b.simdInternal_))) }; } static inline Simd4Double gmx_simdcall operator+(Simd4Double a, Simd4Double b) { - return { _mm512_mask_add_pd(_mm512_undefined_pd(), _mm512_int2mask(0xF), a.simdInternal_, - b.simdInternal_) }; + return { _mm512_mask_add_pd( + _mm512_undefined_pd(), _mm512_int2mask(0xF), a.simdInternal_, b.simdInternal_) }; } static inline Simd4Double gmx_simdcall operator-(Simd4Double a, Simd4Double b) { - return { _mm512_mask_sub_pd(_mm512_undefined_pd(), _mm512_int2mask(0xF), a.simdInternal_, - b.simdInternal_) }; + return { _mm512_mask_sub_pd( + _mm512_undefined_pd(), _mm512_int2mask(0xF), a.simdInternal_, b.simdInternal_) }; } static inline Simd4Double gmx_simdcall operator-(Simd4Double x) { - return { _mm512_mask_addn_pd(_mm512_undefined_pd(), _mm512_int2mask(0xF), x.simdInternal_, - _mm512_setzero_pd()) }; + return { _mm512_mask_addn_pd( + _mm512_undefined_pd(), _mm512_int2mask(0xF), x.simdInternal_, _mm512_setzero_pd()) }; } static inline Simd4Double gmx_simdcall operator*(Simd4Double a, Simd4Double b) { - return { _mm512_mask_mul_pd(_mm512_undefined_pd(), _mm512_int2mask(0xF), a.simdInternal_, - b.simdInternal_) }; + return { _mm512_mask_mul_pd( + _mm512_undefined_pd(), _mm512_int2mask(0xF), a.simdInternal_, b.simdInternal_) }; } static inline Simd4Double gmx_simdcall fma(Simd4Double a, Simd4Double b, Simd4Double c) @@ -179,68 +184,76 @@ static inline Simd4Double gmx_simdcall fnms(Simd4Double a, Simd4Double b, Simd4D static inline Simd4Double gmx_simdcall rsqrt(Simd4Double x) { return { _mm512_mask_cvtpslo_pd( - _mm512_undefined_pd(), _mm512_int2mask(0xF), - _mm512_mask_rsqrt23_ps(_mm512_undefined_ps(), _mm512_int2mask(0xF), - _mm512_mask_cvtpd_pslo(_mm512_undefined_ps(), - _mm512_int2mask(0xF), x.simdInternal_))) }; + _mm512_undefined_pd(), + _mm512_int2mask(0xF), + _mm512_mask_rsqrt23_ps( + _mm512_undefined_ps(), + _mm512_int2mask(0xF), + _mm512_mask_cvtpd_pslo(_mm512_undefined_ps(), _mm512_int2mask(0xF), x.simdInternal_))) }; } static inline Simd4Double gmx_simdcall abs(Simd4Double x) { - return { _mm512_castsi512_pd(_mm512_mask_andnot_epi32( - _mm512_undefined_epi32(), _mm512_int2mask(0x00FF), - _mm512_castpd_si512(_mm512_set1_pd(GMX_DOUBLE_NEGZERO)), _mm512_castpd_si512(x.simdInternal_))) + return { _mm512_castsi512_pd( + _mm512_mask_andnot_epi32(_mm512_undefined_epi32(), + _mm512_int2mask(0x00FF), + _mm512_castpd_si512(_mm512_set1_pd(GMX_DOUBLE_NEGZERO)), + _mm512_castpd_si512(x.simdInternal_))) }; } static inline Simd4Double gmx_simdcall max(Simd4Double a, Simd4Double b) { - return { _mm512_mask_gmax_pd(_mm512_undefined_pd(), _mm512_int2mask(0xF), a.simdInternal_, - b.simdInternal_) }; + return { _mm512_mask_gmax_pd( + _mm512_undefined_pd(), _mm512_int2mask(0xF), a.simdInternal_, b.simdInternal_) }; } static inline Simd4Double gmx_simdcall min(Simd4Double a, Simd4Double b) { - return { _mm512_mask_gmin_pd(_mm512_undefined_pd(), _mm512_int2mask(0xF), a.simdInternal_, - b.simdInternal_) }; + return { _mm512_mask_gmin_pd( + _mm512_undefined_pd(), _mm512_int2mask(0xF), a.simdInternal_, b.simdInternal_) }; } static inline Simd4Double gmx_simdcall round(Simd4Double x) { - return { _mm512_mask_roundfxpnt_adjust_pd(_mm512_undefined_pd(), _mm512_int2mask(0xF), x.simdInternal_, - _MM_FROUND_TO_NEAREST_INT, _MM_EXPADJ_NONE) }; + return { _mm512_mask_roundfxpnt_adjust_pd( + _mm512_undefined_pd(), _mm512_int2mask(0xF), x.simdInternal_, _MM_FROUND_TO_NEAREST_INT, _MM_EXPADJ_NONE) }; } static inline Simd4Double gmx_simdcall trunc(Simd4Double x) { - return { _mm512_mask_roundfxpnt_adjust_pd(_mm512_undefined_pd(), _mm512_int2mask(0xF), - x.simdInternal_, _MM_FROUND_TO_ZERO, _MM_EXPADJ_NONE) }; + return { _mm512_mask_roundfxpnt_adjust_pd( + _mm512_undefined_pd(), _mm512_int2mask(0xF), x.simdInternal_, _MM_FROUND_TO_ZERO, _MM_EXPADJ_NONE) }; } static inline double gmx_simdcall dotProduct(Simd4Double a, Simd4Double b) { - return _mm512_mask_reduce_add_pd(_mm512_int2mask(7), - _mm512_mask_mul_pd(_mm512_undefined_pd(), _mm512_int2mask(7), - a.simdInternal_, b.simdInternal_)); + return _mm512_mask_reduce_add_pd( + _mm512_int2mask(7), + _mm512_mask_mul_pd(_mm512_undefined_pd(), _mm512_int2mask(7), a.simdInternal_, b.simdInternal_)); } static inline void gmx_simdcall transpose(Simd4Double* v0, Simd4Double* v1, Simd4Double* v2, Simd4Double* v3) { - __m512i t0 = _mm512_mask_permute4f128_epi32(_mm512_castpd_si512(v0->simdInternal_), 0xFF00, - _mm512_castpd_si512(v1->simdInternal_), _MM_PERM_BABA); - __m512i t1 = _mm512_mask_permute4f128_epi32(_mm512_castpd_si512(v2->simdInternal_), 0xFF00, - _mm512_castpd_si512(v3->simdInternal_), _MM_PERM_BABA); + __m512i t0 = _mm512_mask_permute4f128_epi32(_mm512_castpd_si512(v0->simdInternal_), + 0xFF00, + _mm512_castpd_si512(v1->simdInternal_), + _MM_PERM_BABA); + __m512i t1 = _mm512_mask_permute4f128_epi32(_mm512_castpd_si512(v2->simdInternal_), + 0xFF00, + _mm512_castpd_si512(v3->simdInternal_), + _MM_PERM_BABA); t0 = _mm512_permutevar_epi32( _mm512_set_epi32(15, 14, 7, 6, 13, 12, 5, 4, 11, 10, 3, 2, 9, 8, 1, 0), t0); t1 = _mm512_permutevar_epi32( _mm512_set_epi32(15, 14, 7, 6, 13, 12, 5, 4, 11, 10, 3, 2, 9, 8, 1, 0), t1); - v0->simdInternal_ = _mm512_mask_swizzle_pd(_mm512_castsi512_pd(t0), _mm512_int2mask(0xCC), - _mm512_castsi512_pd(t1), _MM_SWIZ_REG_BADC); - v1->simdInternal_ = _mm512_mask_swizzle_pd(_mm512_castsi512_pd(t1), _mm512_int2mask(0x33), - _mm512_castsi512_pd(t0), _MM_SWIZ_REG_BADC); + v0->simdInternal_ = _mm512_mask_swizzle_pd( + _mm512_castsi512_pd(t0), _mm512_int2mask(0xCC), _mm512_castsi512_pd(t1), _MM_SWIZ_REG_BADC); + v1->simdInternal_ = _mm512_mask_swizzle_pd( + _mm512_castsi512_pd(t1), _mm512_int2mask(0x33), _mm512_castsi512_pd(t0), _MM_SWIZ_REG_BADC); v2->simdInternal_ = _mm512_castps_pd(_mm512_permute4f128_ps(_mm512_castpd_ps(v0->simdInternal_), _MM_PERM_DCDC)); diff --git a/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd4_float.h b/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd4_float.h index a9bb3a860a..644ee6de0e 100644 --- a/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd4_float.h +++ b/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd4_float.h @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2014,2015,2019, by the GROMACS development team, led by + * Copyright (c) 2014,2015,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -76,8 +76,8 @@ public: static inline Simd4Float gmx_simdcall load4(const float* m) { assert(size_t(m) % 16 == 0); - return { _mm512_mask_extload_ps(_mm512_undefined_ps(), _mm512_int2mask(0xF), m, - _MM_UPCONV_PS_NONE, _MM_BROADCAST_4X16, _MM_HINT_NONE) }; + return { _mm512_mask_extload_ps( + _mm512_undefined_ps(), _mm512_int2mask(0xF), m, _MM_UPCONV_PS_NONE, _MM_BROADCAST_4X16, _MM_HINT_NONE) }; } static inline void gmx_simdcall store4(float* m, Simd4Float a) @@ -90,7 +90,8 @@ static inline Simd4Float gmx_simdcall load4U(const float* m) { return { _mm512_mask_loadunpackhi_ps( _mm512_mask_loadunpacklo_ps(_mm512_undefined_ps(), _mm512_int2mask(0xF), m), - _mm512_int2mask(0xF), m + 16) }; + _mm512_int2mask(0xF), + m + 16) }; } static inline void gmx_simdcall store4U(float* m, Simd4Float a) @@ -106,54 +107,58 @@ static inline Simd4Float gmx_simdcall simd4SetZeroF() static inline Simd4Float gmx_simdcall operator&(Simd4Float a, Simd4Float b) { - return { _mm512_castsi512_ps(_mm512_mask_and_epi32(_mm512_undefined_epi32(), _mm512_int2mask(0xF), + return { _mm512_castsi512_ps(_mm512_mask_and_epi32(_mm512_undefined_epi32(), + _mm512_int2mask(0xF), _mm512_castps_si512(a.simdInternal_), _mm512_castps_si512(b.simdInternal_))) }; } static inline Simd4Float gmx_simdcall andNot(Simd4Float a, Simd4Float b) { - return { _mm512_castsi512_ps(_mm512_mask_andnot_epi32( - _mm512_undefined_epi32(), _mm512_int2mask(0xF), _mm512_castps_si512(a.simdInternal_), - _mm512_castps_si512(b.simdInternal_))) }; + return { _mm512_castsi512_ps(_mm512_mask_andnot_epi32(_mm512_undefined_epi32(), + _mm512_int2mask(0xF), + _mm512_castps_si512(a.simdInternal_), + _mm512_castps_si512(b.simdInternal_))) }; } static inline Simd4Float gmx_simdcall operator|(Simd4Float a, Simd4Float b) { - return { _mm512_castsi512_ps(_mm512_mask_or_epi32(_mm512_undefined_epi32(), _mm512_int2mask(0xF), + return { _mm512_castsi512_ps(_mm512_mask_or_epi32(_mm512_undefined_epi32(), + _mm512_int2mask(0xF), _mm512_castps_si512(a.simdInternal_), _mm512_castps_si512(b.simdInternal_))) }; } static inline Simd4Float gmx_simdcall operator^(Simd4Float a, Simd4Float b) { - return { _mm512_castsi512_ps(_mm512_mask_xor_epi32(_mm512_undefined_epi32(), _mm512_int2mask(0xF), + return { _mm512_castsi512_ps(_mm512_mask_xor_epi32(_mm512_undefined_epi32(), + _mm512_int2mask(0xF), _mm512_castps_si512(a.simdInternal_), _mm512_castps_si512(b.simdInternal_))) }; } static inline Simd4Float gmx_simdcall operator+(Simd4Float a, Simd4Float b) { - return { _mm512_mask_add_ps(_mm512_undefined_ps(), _mm512_int2mask(0xF), a.simdInternal_, - b.simdInternal_) }; + return { _mm512_mask_add_ps( + _mm512_undefined_ps(), _mm512_int2mask(0xF), a.simdInternal_, b.simdInternal_) }; } static inline Simd4Float gmx_simdcall operator-(Simd4Float a, Simd4Float b) { - return { _mm512_mask_sub_ps(_mm512_undefined_ps(), _mm512_int2mask(0xF), a.simdInternal_, - b.simdInternal_) }; + return { _mm512_mask_sub_ps( + _mm512_undefined_ps(), _mm512_int2mask(0xF), a.simdInternal_, b.simdInternal_) }; } static inline Simd4Float gmx_simdcall operator-(Simd4Float x) { - return { _mm512_mask_addn_ps(_mm512_undefined_ps(), _mm512_int2mask(0xF), x.simdInternal_, - _mm512_setzero_ps()) }; + return { _mm512_mask_addn_ps( + _mm512_undefined_ps(), _mm512_int2mask(0xF), x.simdInternal_, _mm512_setzero_ps()) }; } static inline Simd4Float gmx_simdcall operator*(Simd4Float a, Simd4Float b) { - return { _mm512_mask_mul_ps(_mm512_undefined_ps(), _mm512_int2mask(0xF), a.simdInternal_, - b.simdInternal_) }; + return { _mm512_mask_mul_ps( + _mm512_undefined_ps(), _mm512_int2mask(0xF), a.simdInternal_, b.simdInternal_) }; } static inline Simd4Float gmx_simdcall fma(Simd4Float a, Simd4Float b, Simd4Float c) @@ -183,41 +188,42 @@ static inline Simd4Float gmx_simdcall rsqrt(Simd4Float x) static inline Simd4Float gmx_simdcall abs(Simd4Float x) { - return { _mm512_castsi512_ps(_mm512_mask_andnot_epi32( - _mm512_undefined_epi32(), _mm512_int2mask(0xF), - _mm512_castps_si512(_mm512_set1_ps(GMX_FLOAT_NEGZERO)), _mm512_castps_si512(x.simdInternal_))) }; + return { _mm512_castsi512_ps(_mm512_mask_andnot_epi32(_mm512_undefined_epi32(), + _mm512_int2mask(0xF), + _mm512_castps_si512(_mm512_set1_ps(GMX_FLOAT_NEGZERO)), + _mm512_castps_si512(x.simdInternal_))) }; } static inline Simd4Float gmx_simdcall max(Simd4Float a, Simd4Float b) { - return { _mm512_mask_gmax_ps(_mm512_undefined_ps(), _mm512_int2mask(0xF), a.simdInternal_, - b.simdInternal_) }; + return { _mm512_mask_gmax_ps( + _mm512_undefined_ps(), _mm512_int2mask(0xF), a.simdInternal_, b.simdInternal_) }; } static inline Simd4Float gmx_simdcall min(Simd4Float a, Simd4Float b) { - return { _mm512_mask_gmin_ps(_mm512_undefined_ps(), _mm512_int2mask(0xF), a.simdInternal_, - b.simdInternal_) }; + return { _mm512_mask_gmin_ps( + _mm512_undefined_ps(), _mm512_int2mask(0xF), a.simdInternal_, b.simdInternal_) }; } static inline Simd4Float gmx_simdcall round(Simd4Float x) { - return { _mm512_mask_round_ps(_mm512_undefined_ps(), _mm512_int2mask(0xF), x.simdInternal_, - _MM_FROUND_TO_NEAREST_INT, _MM_EXPADJ_NONE) }; + return { _mm512_mask_round_ps( + _mm512_undefined_ps(), _mm512_int2mask(0xF), x.simdInternal_, _MM_FROUND_TO_NEAREST_INT, _MM_EXPADJ_NONE) }; } static inline Simd4Float gmx_simdcall trunc(Simd4Float x) { - return { _mm512_mask_round_ps(_mm512_undefined_ps(), _mm512_int2mask(0xF), x.simdInternal_, - _MM_FROUND_TO_ZERO, _MM_EXPADJ_NONE) }; + return { _mm512_mask_round_ps( + _mm512_undefined_ps(), _mm512_int2mask(0xF), x.simdInternal_, _MM_FROUND_TO_ZERO, _MM_EXPADJ_NONE) }; } static inline float gmx_simdcall dotProduct(Simd4Float a, Simd4Float b) { - __m512 x = _mm512_mask_mul_ps(_mm512_setzero_ps(), _mm512_int2mask(0x7), a.simdInternal_, - b.simdInternal_); - x = _mm512_add_ps(x, _mm512_swizzle_ps(x, _MM_SWIZ_REG_BADC)); - x = _mm512_add_ps(x, _mm512_swizzle_ps(x, _MM_SWIZ_REG_CDAB)); + __m512 x = _mm512_mask_mul_ps( + _mm512_setzero_ps(), _mm512_int2mask(0x7), a.simdInternal_, b.simdInternal_); + x = _mm512_add_ps(x, _mm512_swizzle_ps(x, _MM_SWIZ_REG_BADC)); + x = _mm512_add_ps(x, _mm512_swizzle_ps(x, _MM_SWIZ_REG_CDAB)); float f; _mm512_mask_packstorelo_ps(&f, _mm512_mask2int(0x1), x); return f; @@ -225,21 +231,21 @@ static inline float gmx_simdcall dotProduct(Simd4Float a, Simd4Float b) static inline void gmx_simdcall transpose(Simd4Float* v0, Simd4Float* v1, Simd4Float* v2, Simd4Float* v3) { - v0->simdInternal_ = _mm512_mask_permute4f128_ps(v0->simdInternal_, _mm512_int2mask(0x00F0), - v1->simdInternal_, _MM_PERM_AAAA); - v2->simdInternal_ = _mm512_mask_permute4f128_ps(v2->simdInternal_, _mm512_int2mask(0x00F0), - v3->simdInternal_, _MM_PERM_AAAA); - v0->simdInternal_ = _mm512_mask_permute4f128_ps(v0->simdInternal_, _mm512_int2mask(0xFF00), - v2->simdInternal_, _MM_PERM_BABA); + v0->simdInternal_ = _mm512_mask_permute4f128_ps( + v0->simdInternal_, _mm512_int2mask(0x00F0), v1->simdInternal_, _MM_PERM_AAAA); + v2->simdInternal_ = _mm512_mask_permute4f128_ps( + v2->simdInternal_, _mm512_int2mask(0x00F0), v3->simdInternal_, _MM_PERM_AAAA); + v0->simdInternal_ = _mm512_mask_permute4f128_ps( + v0->simdInternal_, _mm512_int2mask(0xFF00), v2->simdInternal_, _MM_PERM_BABA); v0->simdInternal_ = _mm512_castsi512_ps(_mm512_permutevar_epi32( _mm512_set_epi32(15, 11, 7, 3, 14, 10, 6, 2, 13, 9, 5, 1, 12, 8, 4, 0), _mm512_castps_si512(v0->simdInternal_))); - v1->simdInternal_ = _mm512_mask_permute4f128_ps(_mm512_setzero_ps(), _mm512_int2mask(0x000F), - v0->simdInternal_, _MM_PERM_BBBB); - v2->simdInternal_ = _mm512_mask_permute4f128_ps(_mm512_setzero_ps(), _mm512_int2mask(0x000F), - v0->simdInternal_, _MM_PERM_CCCC); - v3->simdInternal_ = _mm512_mask_permute4f128_ps(_mm512_setzero_ps(), _mm512_int2mask(0x000F), - v0->simdInternal_, _MM_PERM_DDDD); + v1->simdInternal_ = _mm512_mask_permute4f128_ps( + _mm512_setzero_ps(), _mm512_int2mask(0x000F), v0->simdInternal_, _MM_PERM_BBBB); + v2->simdInternal_ = _mm512_mask_permute4f128_ps( + _mm512_setzero_ps(), _mm512_int2mask(0x000F), v0->simdInternal_, _MM_PERM_CCCC); + v3->simdInternal_ = _mm512_mask_permute4f128_ps( + _mm512_setzero_ps(), _mm512_int2mask(0x000F), v0->simdInternal_, _MM_PERM_DDDD); } // Picky, picky, picky: diff --git a/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd_double.h b/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd_double.h index 7fe86f9726..09631b2e00 100644 --- a/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd_double.h +++ b/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd_double.h @@ -143,7 +143,8 @@ static inline SimdDInt32 gmx_simdcall simdLoadU(const std::int32_t* m, SimdDInt3 { return { _mm512_mask_loadunpackhi_epi32( _mm512_mask_loadunpacklo_epi32(_mm512_undefined_epi32(), _mm512_int2mask(0x00FF), m), - _mm512_int2mask(0x00FF), m + 16) }; + _mm512_int2mask(0x00FF), + m + 16) }; } static inline void gmx_simdcall storeU(std::int32_t* m, SimdDInt32 a) @@ -251,20 +252,21 @@ static inline SimdDouble gmx_simdcall maskzMul(SimdDouble a, SimdDouble b, SimdD static inline SimdDouble gmx_simdcall maskzFma(SimdDouble a, SimdDouble b, SimdDouble c, SimdDBool m) { - return { _mm512_mask_mov_pd(_mm512_setzero_pd(), m.simdInternal_, + return { _mm512_mask_mov_pd(_mm512_setzero_pd(), + m.simdInternal_, _mm512_fmadd_pd(a.simdInternal_, b.simdInternal_, c.simdInternal_)) }; } static inline SimdDouble gmx_simdcall maskzRsqrt(SimdDouble x, SimdDBool m) { - return { _mm512_cvtpslo_pd(_mm512_mask_rsqrt23_ps(_mm512_setzero_ps(), m.simdInternal_, - _mm512_cvtpd_pslo(x.simdInternal_))) }; + return { _mm512_cvtpslo_pd(_mm512_mask_rsqrt23_ps( + _mm512_setzero_ps(), m.simdInternal_, _mm512_cvtpd_pslo(x.simdInternal_))) }; } static inline SimdDouble gmx_simdcall maskzRcp(SimdDouble x, SimdDBool m) { - return { _mm512_cvtpslo_pd(_mm512_mask_rcp23_ps(_mm512_setzero_ps(), m.simdInternal_, - _mm512_cvtpd_pslo(x.simdInternal_))) }; + return { _mm512_cvtpslo_pd(_mm512_mask_rcp23_ps( + _mm512_setzero_ps(), m.simdInternal_, _mm512_cvtpd_pslo(x.simdInternal_))) }; } static inline SimdDouble gmx_simdcall abs(SimdDouble x) @@ -311,13 +313,13 @@ static inline SimdDouble frexp(SimdDouble value, SimdDInt32* exponent) // Create an integer -1 value, and use masking in the conversion as the result for // zero-value input. When we later add 1 to all fields, the fields that were formerly -1 // (corresponding to zero exponent) will be assigned -1 + 1 = 0. - iExponent = _mm512_mask_cvtfxpnt_roundpd_epi32lo(_mm512_set_epi32(-1), valueIsNonZero, - rExponent, _MM_FROUND_TO_NEAREST_INT); + iExponent = _mm512_mask_cvtfxpnt_roundpd_epi32lo( + _mm512_set_epi32(-1), valueIsNonZero, rExponent, _MM_FROUND_TO_NEAREST_INT); iExponent = _mm512__add_epi32(iExponent, _mm512_set1_epi32(1)); // Set result to value (+-0) when it is zero. - result = _mm512_mask_getmant_pd(value.simdInternal_, valueIsNonZero, value.simdInternal_, - _MM_MANT_NORM_p5_1, _MM_MANT_SIGN_src); + result = _mm512_mask_getmant_pd( + value.simdInternal_, valueIsNonZero, value.simdInternal_, _MM_MANT_NORM_p5_1, _MM_MANT_SIGN_src); } else { diff --git a/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd_float.h b/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd_float.h index f1ab6da335..b0603e07df 100644 --- a/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd_float.h +++ b/src/gromacs/simd/impl_x86_mic/impl_x86_mic_simd_float.h @@ -251,7 +251,8 @@ static inline SimdFloat gmx_simdcall maskzMul(SimdFloat a, SimdFloat b, SimdFBoo static inline SimdFloat gmx_simdcall maskzFma(SimdFloat a, SimdFloat b, SimdFloat c, SimdFBool m) { - return { _mm512_mask_mov_ps(_mm512_setzero_ps(), m.simdInternal_, + return { _mm512_mask_mov_ps(_mm512_setzero_ps(), + m.simdInternal_, _mm512_fmadd_ps(a.simdInternal_, b.simdInternal_, c.simdInternal_)) }; } @@ -305,19 +306,19 @@ static inline SimdFloat gmx_simdcall frexp(SimdFloat value, SimdFInt32* exponent __mmask16 valueIsNonZero = _mm512_cmp_ps_mask(_mm512_setzero_ps(), value.simdInternal_, _CMP_NEQ_OQ); rExponent = _mm512_mask_getexp_ps(_mm512_setzero_ps(), valueIsNonZero, value.simdInternal_); - iExponent = _mm512_cvtfxpnt_round_adjustps_epi32(rExponent, _MM_FROUND_TO_NEAREST_INT, - _MM_EXPADJ_NONE); + iExponent = _mm512_cvtfxpnt_round_adjustps_epi32( + rExponent, _MM_FROUND_TO_NEAREST_INT, _MM_EXPADJ_NONE); iExponent = _mm512_mask_add_epi32(iExponent, valueIsNonZero, iExponent, _mm512_set1_epi32(1)); // Set result to input value when the latter is +-0 - result = _mm512_mask_getmant_ps(value.simdInternal_, valueIsNonZero, value.simdInternal_, - _MM_MANT_NORM_p5_1, _MM_MANT_SIGN_src); + result = _mm512_mask_getmant_ps( + value.simdInternal_, valueIsNonZero, value.simdInternal_, _MM_MANT_NORM_p5_1, _MM_MANT_SIGN_src); } else { rExponent = _mm512_getexp_ps(value.simdInternal_); - iExponent = _mm512_cvtfxpnt_round_adjustps_epi32(rExponent, _MM_FROUND_TO_NEAREST_INT, - _MM_EXPADJ_NONE); + iExponent = _mm512_cvtfxpnt_round_adjustps_epi32( + rExponent, _MM_FROUND_TO_NEAREST_INT, _MM_EXPADJ_NONE); iExponent = _mm512_add_epi32(iExponent, _mm512_set1_epi32(1)); result = _mm512_getmant_ps(value.simdInternal_, _MM_MANT_NORM_p5_1, _MM_MANT_SIGN_src); } @@ -494,8 +495,8 @@ static inline SimdFInt32 gmx_simdcall blend(SimdFInt32 a, SimdFInt32 b, SimdFIBo static inline SimdFInt32 gmx_simdcall cvtR2I(SimdFloat a) { - return { _mm512_cvtfxpnt_round_adjustps_epi32(a.simdInternal_, _MM_FROUND_TO_NEAREST_INT, - _MM_EXPADJ_NONE) }; + return { _mm512_cvtfxpnt_round_adjustps_epi32( + a.simdInternal_, _MM_FROUND_TO_NEAREST_INT, _MM_EXPADJ_NONE) }; } static inline SimdFInt32 gmx_simdcall cvttR2I(SimdFloat a) @@ -505,8 +506,8 @@ static inline SimdFInt32 gmx_simdcall cvttR2I(SimdFloat a) static inline SimdFloat gmx_simdcall cvtI2R(SimdFInt32 a) { - return { _mm512_cvtfxpnt_round_adjustepi32_ps(a.simdInternal_, _MM_FROUND_TO_NEAREST_INT, - _MM_EXPADJ_NONE) }; + return { _mm512_cvtfxpnt_round_adjustepi32_ps( + a.simdInternal_, _MM_FROUND_TO_NEAREST_INT, _MM_EXPADJ_NONE) }; } static inline SimdFIBool gmx_simdcall cvtB2IB(SimdFBool a) diff --git a/src/gromacs/simd/impl_x86_mic/impl_x86_mic_util_double.h b/src/gromacs/simd/impl_x86_mic/impl_x86_mic_util_double.h index 18769d61e4..d08086c6c6 100644 --- a/src/gromacs/simd/impl_x86_mic/impl_x86_mic_util_double.h +++ b/src/gromacs/simd/impl_x86_mic/impl_x86_mic_util_double.h @@ -316,8 +316,8 @@ static inline double gmx_simdcall t2 = _mm512_add_pd(t2, _mm512_castps_pd(_mm512_permute4f128_ps(_mm512_castpd_ps(t2), _MM_PERM_BADC))); - t0 = _mm512_mask_extload_pd(_mm512_undefined_pd(), _mm512_int2mask(0xF), m, _MM_UPCONV_PD_NONE, - _MM_BROADCAST_4X8, _MM_HINT_NONE); + t0 = _mm512_mask_extload_pd( + _mm512_undefined_pd(), _mm512_int2mask(0xF), m, _MM_UPCONV_PD_NONE, _MM_BROADCAST_4X8, _MM_HINT_NONE); t0 = _mm512_add_pd(t0, t2); _mm512_mask_packstorelo_pd(m, _mm512_int2mask(0xF), t0); @@ -333,9 +333,12 @@ static inline SimdDouble gmx_simdcall loadDualHsimd(const double* m0, const doub assert(std::size_t(m0) % 32 == 0); assert(std::size_t(m1) % 32 == 0); - return _mm512_mask_extload_pd( - _mm512_extload_pd(m0, _MM_UPCONV_PD_NONE, _MM_BROADCAST_4X8, _MM_HINT_NONE), - _mm512_int2mask(0xF0), m1, _MM_UPCONV_PD_NONE, _MM_BROADCAST_4X8, _MM_HINT_NONE); + return _mm512_mask_extload_pd(_mm512_extload_pd(m0, _MM_UPCONV_PD_NONE, _MM_BROADCAST_4X8, _MM_HINT_NONE), + _mm512_int2mask(0xF0), + m1, + _MM_UPCONV_PD_NONE, + _MM_BROADCAST_4X8, + _MM_HINT_NONE); } static inline SimdDouble gmx_simdcall loadDuplicateHsimd(const double* m) @@ -347,9 +350,12 @@ static inline SimdDouble gmx_simdcall loadDuplicateHsimd(const double* m) static inline SimdDouble gmx_simdcall loadU1DualHsimd(const double* m) { - return _mm512_mask_extload_pd( - _mm512_extload_pd(m, _MM_UPCONV_PD_NONE, _MM_BROADCAST_1X8, _MM_HINT_NONE), - _mm512_int2mask(0xF0), m + 1, _MM_UPCONV_PD_NONE, _MM_BROADCAST_1X8, _MM_HINT_NONE); + return _mm512_mask_extload_pd(_mm512_extload_pd(m, _MM_UPCONV_PD_NONE, _MM_BROADCAST_1X8, _MM_HINT_NONE), + _mm512_int2mask(0xF0), + m + 1, + _MM_UPCONV_PD_NONE, + _MM_BROADCAST_1X8, + _MM_HINT_NONE); } @@ -428,14 +434,16 @@ static inline double gmx_simdcall reduceIncr4ReturnSumHsimd(double* m, SimdDoubl assert(std::size_t(m) % 32 == 0); t0 = _mm512_add_pd(v0.simdInternal_, _mm512_swizzle_pd(v0.simdInternal_, _MM_SWIZ_REG_BADC)); - t0 = _mm512_mask_add_pd(t0, _mm512_int2mask(0xCC), v1.simdInternal_, + t0 = _mm512_mask_add_pd(t0, + _mm512_int2mask(0xCC), + v1.simdInternal_, _mm512_swizzle_pd(v1.simdInternal_, _MM_SWIZ_REG_BADC)); t0 = _mm512_add_pd(t0, _mm512_swizzle_pd(t0, _MM_SWIZ_REG_CDAB)); - t0 = _mm512_castps_pd(_mm512_mask_permute4f128_ps(_mm512_castpd_ps(t0), _mm512_int2mask(0xCCCC), - _mm512_castpd_ps(t0), _MM_PERM_DCDC)); + t0 = _mm512_castps_pd(_mm512_mask_permute4f128_ps( + _mm512_castpd_ps(t0), _mm512_int2mask(0xCCCC), _mm512_castpd_ps(t0), _MM_PERM_DCDC)); - t1 = _mm512_mask_extload_pd(_mm512_undefined_pd(), _mm512_int2mask(0xF), m, _MM_UPCONV_PD_NONE, - _MM_BROADCAST_4X8, _MM_HINT_NONE); + t1 = _mm512_mask_extload_pd( + _mm512_undefined_pd(), _mm512_int2mask(0xF), m, _MM_UPCONV_PD_NONE, _MM_BROADCAST_4X8, _MM_HINT_NONE); t1 = _mm512_add_pd(t1, t0); _mm512_mask_packstorelo_pd(m, _mm512_int2mask(0xF), t1); diff --git a/src/gromacs/simd/impl_x86_mic/impl_x86_mic_util_float.h b/src/gromacs/simd/impl_x86_mic/impl_x86_mic_util_float.h index 13a6147f87..bf5db5b77a 100644 --- a/src/gromacs/simd/impl_x86_mic/impl_x86_mic_util_float.h +++ b/src/gromacs/simd/impl_x86_mic/impl_x86_mic_util_float.h @@ -61,8 +61,8 @@ inline void gmx_simdcall decrHsimd(float* m, SimdFloat a) assert(std::size_t(m) % 32 == 0); - t = _mm512_castpd_ps(_mm512_extload_pd(reinterpret_cast(m), _MM_UPCONV_PD_NONE, - _MM_BROADCAST_4X8, _MM_HINT_NONE)); + t = _mm512_castpd_ps(_mm512_extload_pd( + reinterpret_cast(m), _MM_UPCONV_PD_NONE, _MM_BROADCAST_4X8, _MM_HINT_NONE)); a = _mm512_add_ps(a.simdInternal_, _mm512_permute4f128_ps(a.simdInternal_, _MM_PERM_BADC)); t = _mm512_sub_ps(t, a.simdInternal_); _mm512_mask_packstorelo_ps(m, _mm512_int2mask(0x00FF), t); @@ -300,10 +300,14 @@ static inline float gmx_simdcall reduceIncr4ReturnSum(float* m, SimdFloat v0, Si assert(std::size_t(m) % 16 == 0); t0 = _mm512_add_ps(v0.simdInternal_, _mm512_swizzle_ps(v0.simdInternal_, _MM_SWIZ_REG_BADC)); - t0 = _mm512_mask_add_ps(t0, _mm512_int2mask(0xCCCC), v2.simdInternal_, + t0 = _mm512_mask_add_ps(t0, + _mm512_int2mask(0xCCCC), + v2.simdInternal_, _mm512_swizzle_ps(v2.simdInternal_, _MM_SWIZ_REG_BADC)); t1 = _mm512_add_ps(v1.simdInternal_, _mm512_swizzle_ps(v1.simdInternal_, _MM_SWIZ_REG_BADC)); - t1 = _mm512_mask_add_ps(t1, _mm512_int2mask(0xCCCC), v3.simdInternal_, + t1 = _mm512_mask_add_ps(t1, + _mm512_int2mask(0xCCCC), + v3.simdInternal_, _mm512_swizzle_ps(v3.simdInternal_, _MM_SWIZ_REG_BADC)); t2 = _mm512_add_ps(t0, _mm512_swizzle_ps(t0, _MM_SWIZ_REG_CDAB)); t2 = _mm512_mask_add_ps(t2, _mm512_int2mask(0xAAAA), t1, _mm512_swizzle_ps(t1, _MM_SWIZ_REG_CDAB)); @@ -311,8 +315,8 @@ static inline float gmx_simdcall reduceIncr4ReturnSum(float* m, SimdFloat v0, Si t2 = _mm512_add_ps(t2, _mm512_permute4f128_ps(t2, _MM_PERM_BADC)); t2 = _mm512_add_ps(t2, _mm512_permute4f128_ps(t2, _MM_PERM_CDAB)); - t0 = _mm512_mask_extload_ps(_mm512_undefined_ps(), _mm512_int2mask(0xF), m, _MM_UPCONV_PS_NONE, - _MM_BROADCAST_4X16, _MM_HINT_NONE); + t0 = _mm512_mask_extload_ps( + _mm512_undefined_ps(), _mm512_int2mask(0xF), m, _MM_UPCONV_PS_NONE, _MM_BROADCAST_4X16, _MM_HINT_NONE); t0 = _mm512_add_ps(t0, t2); _mm512_mask_packstorelo_ps(m, _mm512_int2mask(0xF), t0); @@ -329,25 +333,30 @@ static inline SimdFloat gmx_simdcall loadDualHsimd(const float* m0, const float* assert(std::size_t(m1) % 32 == 0); return _mm512_castpd_ps(_mm512_mask_extload_pd( - _mm512_extload_pd(reinterpret_cast(m0), _MM_UPCONV_PD_NONE, - _MM_BROADCAST_4X8, _MM_HINT_NONE), - _mm512_int2mask(0xF0), reinterpret_cast(m1), _MM_UPCONV_PD_NONE, - _MM_BROADCAST_4X8, _MM_HINT_NONE)); + _mm512_extload_pd(reinterpret_cast(m0), _MM_UPCONV_PD_NONE, _MM_BROADCAST_4X8, _MM_HINT_NONE), + _mm512_int2mask(0xF0), + reinterpret_cast(m1), + _MM_UPCONV_PD_NONE, + _MM_BROADCAST_4X8, + _MM_HINT_NONE)); } static inline SimdFloat gmx_simdcall loadDuplicateHsimd(const float* m) { assert(std::size_t(m) % 32 == 0); - return _mm512_castpd_ps(_mm512_extload_pd(reinterpret_cast(m), - _MM_UPCONV_PD_NONE, _MM_BROADCAST_4X8, _MM_HINT_NONE)); + return _mm512_castpd_ps(_mm512_extload_pd( + reinterpret_cast(m), _MM_UPCONV_PD_NONE, _MM_BROADCAST_4X8, _MM_HINT_NONE)); } static inline SimdFloat gmx_simdcall loadU1DualHsimd(const float* m) { - return _mm512_mask_extload_ps( - _mm512_extload_ps(m, _MM_UPCONV_PS_NONE, _MM_BROADCAST_1X16, _MM_HINT_NONE), - _mm512_int2mask(0xFF00), m + 1, _MM_UPCONV_PS_NONE, _MM_BROADCAST_1X16, _MM_HINT_NONE); + return _mm512_mask_extload_ps(_mm512_extload_ps(m, _MM_UPCONV_PS_NONE, _MM_BROADCAST_1X16, _MM_HINT_NONE), + _mm512_int2mask(0xFF00), + m + 1, + _MM_UPCONV_PS_NONE, + _MM_BROADCAST_1X16, + _MM_HINT_NONE); } @@ -370,14 +379,14 @@ static inline void gmx_simdcall incrDualHsimd(float* m0, float* m1, SimdFloat a) __m512 x; // Update lower half - x = _mm512_castpd_ps(_mm512_extload_pd(reinterpret_cast(m0), _MM_UPCONV_PD_NONE, - _MM_BROADCAST_4X8, _MM_HINT_NONE)); + x = _mm512_castpd_ps(_mm512_extload_pd( + reinterpret_cast(m0), _MM_UPCONV_PD_NONE, _MM_BROADCAST_4X8, _MM_HINT_NONE)); x = _mm512_add_ps(x, a.simdInternal_); _mm512_mask_packstorelo_ps(m0, _mm512_int2mask(0x00FF), x); // Update upper half - x = _mm512_castpd_ps(_mm512_extload_pd(reinterpret_cast(m1), _MM_UPCONV_PD_NONE, - _MM_BROADCAST_4X8, _MM_HINT_NONE)); + x = _mm512_castpd_ps(_mm512_extload_pd( + reinterpret_cast(m1), _MM_UPCONV_PD_NONE, _MM_BROADCAST_4X8, _MM_HINT_NONE)); x = _mm512_add_ps(x, a.simdInternal_); _mm512_mask_packstorelo_ps(m1, _mm512_int2mask(0xFF00), x); } @@ -428,13 +437,15 @@ static inline float gmx_simdcall reduceIncr4ReturnSumHsimd(float* m, SimdFloat v assert(std::size_t(m) % 32 == 0); t0 = _mm512_add_ps(v0.simdInternal_, _mm512_swizzle_ps(v0.simdInternal_, _MM_SWIZ_REG_BADC)); - t0 = _mm512_mask_add_ps(t0, _mm512_int2mask(0xCCCC), v1.simdInternal_, + t0 = _mm512_mask_add_ps(t0, + _mm512_int2mask(0xCCCC), + v1.simdInternal_, _mm512_swizzle_ps(v1.simdInternal_, _MM_SWIZ_REG_BADC)); t0 = _mm512_add_ps(t0, _mm512_swizzle_ps(t0, _MM_SWIZ_REG_CDAB)); t0 = _mm512_add_ps(t0, _mm512_castpd_ps(_mm512_swizzle_pd(_mm512_castps_pd(t0), _MM_SWIZ_REG_BADC))); t0 = _mm512_mask_permute4f128_ps(t0, _mm512_int2mask(0xAAAA), t0, _MM_PERM_BADC); - t1 = _mm512_mask_extload_ps(_mm512_undefined_ps(), _mm512_int2mask(0xF), m, _MM_UPCONV_PS_NONE, - _MM_BROADCAST_4X16, _MM_HINT_NONE); + t1 = _mm512_mask_extload_ps( + _mm512_undefined_ps(), _mm512_int2mask(0xF), m, _MM_UPCONV_PS_NONE, _MM_BROADCAST_4X16, _MM_HINT_NONE); t1 = _mm512_add_ps(t1, t0); _mm512_mask_packstorelo_ps(m, _mm512_int2mask(0xF), t1); diff --git a/src/gromacs/simd/support.cpp b/src/gromacs/simd/support.cpp index 47fe1b582f..ba14076f06 100644 --- a/src/gromacs/simd/support.cpp +++ b/src/gromacs/simd/support.cpp @@ -256,10 +256,12 @@ bool simdCheck(gmx::SimdType wanted, FILE* log, bool warnToStdErr) "which could influence performance. This build might have been configured on " "a login node with only a single AVX-512 FMA unit (in which case AVX2 is faster), " "while the node you are running on has dual AVX-512 FMA units.", - simdString(wanted).c_str(), simdString(compiled).c_str())); + simdString(wanted).c_str(), + simdString(compiled).c_str())); warnMsg = wrapper.wrapToString(formatString( "Compiled SIMD: %s, but for this host/run %s might be better (see log).", - simdString(compiled).c_str(), simdString(wanted).c_str())); + simdString(compiled).c_str(), + simdString(wanted).c_str())); } else if (compiled == SimdType::X86_Avx512 && wanted == SimdType::X86_Avx2 && identifyAvx512FmaUnits() == 1) @@ -273,10 +275,12 @@ bool simdCheck(gmx::SimdType wanted, FILE* log, bool warnToStdErr) "which could influence performance." "This host supports AVX-512, but since it only has 1 AVX-512" "FMA unit, it would be faster to use AVX2 instead.", - simdString(wanted).c_str(), simdString(compiled).c_str())); + simdString(wanted).c_str(), + simdString(compiled).c_str())); warnMsg = wrapper.wrapToString(formatString( "Compiled SIMD: %s, but for this host/run %s might be better (see log).", - simdString(compiled).c_str(), simdString(wanted).c_str())); + simdString(compiled).c_str(), + simdString(wanted).c_str())); } else if (compiled == SimdType::X86_Avx2 && wanted == SimdType::X86_Avx2_128) { @@ -294,7 +298,8 @@ bool simdCheck(gmx::SimdType wanted, FILE* log, bool warnToStdErr) formatString("Highest SIMD level requested by all nodes in run: %s\n" "SIMD instructions selected at compile time: %s\n" "Compiled SIMD newer than requested; program might crash.", - simdString(wanted).c_str(), simdString(compiled).c_str())); + simdString(wanted).c_str(), + simdString(compiled).c_str())); warnMsg = logMsg; } else if (wanted != compiled) @@ -305,10 +310,12 @@ bool simdCheck(gmx::SimdType wanted, FILE* log, bool warnToStdErr) "SIMD instructions selected at compile time: %s\n" "This program was compiled for different hardware than you are running on, " "which could influence performance.", - simdString(wanted).c_str(), simdString(compiled).c_str())); + simdString(wanted).c_str(), + simdString(compiled).c_str())); warnMsg = wrapper.wrapToString(formatString( "Compiled SIMD: %s, but for this host/run %s might be better (see log).", - simdString(compiled).c_str(), simdString(wanted).c_str())); + simdString(compiled).c_str(), + simdString(wanted).c_str())); #if GMX_SIMD_ARM_SVE } else if ((compiled == SimdType::Arm_Sve) && (svcntb() != GMX_SIMD_ARM_SVE_LENGTH_VALUE / 8)) @@ -319,10 +326,12 @@ bool simdCheck(gmx::SimdType wanted, FILE* log, bool warnToStdErr) "This program was compiled for different hardware than you are running on, " "which will lead to incorrect behavior.\n" "Aborting", - GMX_SIMD_ARM_SVE_LENGTH_VALUE, svcntb() * 8)); + GMX_SIMD_ARM_SVE_LENGTH_VALUE, + svcntb() * 8)); warnMsg = wrapper.wrapToString(formatString( "Compiled SVE Length: %d, but for this process requires %ld (see log).", - GMX_SIMD_ARM_SVE_LENGTH_VALUE, svcntb() * 8)); + GMX_SIMD_ARM_SVE_LENGTH_VALUE, + svcntb() * 8)); #endif } diff --git a/src/gromacs/simd/tests/simd4_vector_operations.cpp b/src/gromacs/simd/tests/simd4_vector_operations.cpp index 4853a5a662..0cf3958d67 100644 --- a/src/gromacs/simd/tests/simd4_vector_operations.cpp +++ b/src/gromacs/simd/tests/simd4_vector_operations.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2014,2015,2017,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2014,2015,2017,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -65,8 +65,8 @@ TEST_F(Simd4VectorOperationsTest, norm2) Simd4Real simdX = rSimd4_c0c1c2; Simd4Real simdY = rSimd4_c3c4c5; Simd4Real simdZ = rSimd4_c6c7c8; - Simd4Real simdR2 = setSimd4RealFrom3R(c0 * c0 + c3 * c3 + c6 * c6, c1 * c1 + c4 * c4 + c7 * c7, - c2 * c2 + c5 * c5 + c8 * c8); + Simd4Real simdR2 = setSimd4RealFrom3R( + c0 * c0 + c3 * c3 + c6 * c6, c1 * c1 + c4 * c4 + c7 * c7, c2 * c2 + c5 * c5 + c8 * c8); setUlpTol(2); GMX_EXPECT_SIMD4_REAL_NEAR(simdR2, norm2(simdX, simdY, simdZ)); diff --git a/src/gromacs/simd/tests/simd_floatingpoint.cpp b/src/gromacs/simd/tests/simd_floatingpoint.cpp index 28d07cb771..57d2c9c710 100644 --- a/src/gromacs/simd/tests/simd_floatingpoint.cpp +++ b/src/gromacs/simd/tests/simd_floatingpoint.cpp @@ -243,14 +243,16 @@ TEST_F(SimdFloatingpointTest, frexp) fraction = frexp(rSimd_Exp, &exponent); - GMX_EXPECT_SIMD_REAL_EQ(setSimdRealFrom3R(0.609548660288905419513128, 0.5833690139241746175358116, + GMX_EXPECT_SIMD_REAL_EQ(setSimdRealFrom3R(0.609548660288905419513128, + 0.5833690139241746175358116, -0.584452007502232362412542), fraction); GMX_EXPECT_SIMD_INT_EQ(setSimdIntFrom3I(61, -40, 55), exponent); // Test the unsafe flavor too, in case they use different branches fraction = frexp(rSimd_Exp, &exponent); - GMX_EXPECT_SIMD_REAL_EQ(setSimdRealFrom3R(0.609548660288905419513128, 0.5833690139241746175358116, + GMX_EXPECT_SIMD_REAL_EQ(setSimdRealFrom3R(0.609548660288905419513128, + 0.5833690139241746175358116, -0.584452007502232362412542), fraction); GMX_EXPECT_SIMD_INT_EQ(setSimdIntFrom3I(61, -40, 55), exponent); diff --git a/src/gromacs/simd/tests/simd_math.cpp b/src/gromacs/simd/tests/simd_math.cpp index 07b25cde5f..2b6c07f4cc 100644 --- a/src/gromacs/simd/tests/simd_math.cpp +++ b/src/gromacs/simd/tests/simd_math.cpp @@ -712,13 +712,17 @@ TEST_F(SimdMathTest, exp2) GMX_EXPECT_SIMD_FUNC_NEAR(std::exp2, exp2, settings); // Subnormal range, require matching, but DTZ is fine - settings = { Range(lowestRealThatProducesDenormal, lowestRealThatProducesNormal), ulpTol_, - absTol_, MatchRule::Dtz }; + settings = { Range(lowestRealThatProducesDenormal, lowestRealThatProducesNormal), + ulpTol_, + absTol_, + MatchRule::Dtz }; GMX_EXPECT_SIMD_FUNC_NEAR(std::exp2, exp2, settings); // Normal range, standard result expected - settings = { Range(lowestRealThatProducesNormal, highestRealThatProducesNormal), ulpTol_, - absTol_, MatchRule::Normal }; + settings = { Range(lowestRealThatProducesNormal, highestRealThatProducesNormal), + ulpTol_, + absTol_, + MatchRule::Normal }; GMX_EXPECT_SIMD_FUNC_NEAR(std::exp2, exp2, settings); } @@ -733,7 +737,9 @@ TEST_F(SimdMathTest, exp2Unsafe) - 1; // adding the significant corresponds to one more unit in exponent CompareSettings settings{ Range(lowestRealThatProducesNormal, highestRealThatProducesNormal), - ulpTol_, absTol_, MatchRule::Normal }; + ulpTol_, + absTol_, + MatchRule::Normal }; GMX_EXPECT_SIMD_FUNC_NEAR(std::exp2, exp2, settings); } @@ -759,13 +765,17 @@ TEST_F(SimdMathTest, exp) GMX_EXPECT_SIMD_FUNC_NEAR(std::exp, exp, settings); // Subnormal range, require matching, but DTZ is fine - settings = { Range(lowestRealThatProducesDenormal, lowestRealThatProducesNormal), ulpTol_, - absTol_, MatchRule::Dtz }; + settings = { Range(lowestRealThatProducesDenormal, lowestRealThatProducesNormal), + ulpTol_, + absTol_, + MatchRule::Dtz }; GMX_EXPECT_SIMD_FUNC_NEAR(std::exp, exp, settings); // Normal range, standard result expected - settings = { Range(lowestRealThatProducesNormal, highestRealThatProducesNormal), ulpTol_, - absTol_, MatchRule::Normal }; + settings = { Range(lowestRealThatProducesNormal, highestRealThatProducesNormal), + ulpTol_, + absTol_, + MatchRule::Normal }; GMX_EXPECT_SIMD_FUNC_NEAR(std::exp, exp, settings); } @@ -779,7 +789,9 @@ TEST_F(SimdMathTest, expUnsafe) (std::numeric_limits::max_exponent - 1) * std::log(2.0); CompareSettings settings{ Range(lowestRealThatProducesNormal, highestRealThatProducesNormal), - ulpTol_, absTol_, MatchRule::Normal }; + ulpTol_, + absTol_, + MatchRule::Normal }; GMX_EXPECT_SIMD_FUNC_NEAR(std::exp, exp, settings); } @@ -842,8 +854,7 @@ real refErfc(real x) TEST_F(SimdMathTest, erfc) { // Our erfc algorithm has 4 ulp accuracy, so relax tolerance a bit to 4*ulpTol - CompareSettings settings{ Range(-9, 9), 4 * ulpTol_, std::numeric_limits::min(), - MatchRule::Normal }; + CompareSettings settings{ Range(-9, 9), 4 * ulpTol_, std::numeric_limits::min(), MatchRule::Normal }; GMX_EXPECT_SIMD_FUNC_NEAR(refErfc, erfc, settings); } @@ -1183,13 +1194,17 @@ TEST_F(SimdMathTest, exp2SingleAccuracy) GMX_EXPECT_SIMD_FUNC_NEAR(std::exp2, exp2SingleAccuracy, settings); // Subnormal range, require matching, but DTZ is fine - settings = { Range(lowestRealThatProducesDenormal, lowestRealThatProducesNormal), ulpTol_, - absTol_, MatchRule::Dtz }; + settings = { Range(lowestRealThatProducesDenormal, lowestRealThatProducesNormal), + ulpTol_, + absTol_, + MatchRule::Dtz }; GMX_EXPECT_SIMD_FUNC_NEAR(std::exp2, exp2SingleAccuracy, settings); // Normal range, standard result expected - settings = { Range(lowestRealThatProducesNormal, highestRealThatProducesNormal), ulpTol_, - absTol_, MatchRule::Normal }; + settings = { Range(lowestRealThatProducesNormal, highestRealThatProducesNormal), + ulpTol_, + absTol_, + MatchRule::Normal }; GMX_EXPECT_SIMD_FUNC_NEAR(std::exp2, exp2SingleAccuracy, settings); } @@ -1207,7 +1222,9 @@ TEST_F(SimdMathTest, exp2SingleAccuracyUnsafe) setUlpTolSingleAccuracy(ulpTol_); CompareSettings settings{ Range(lowestRealThatProducesNormal, highestRealThatProducesNormal), - ulpTol_, absTol_, MatchRule::Normal }; + ulpTol_, + absTol_, + MatchRule::Normal }; GMX_EXPECT_SIMD_FUNC_NEAR(std::exp2, exp2SingleAccuracy, settings); } @@ -1235,13 +1252,17 @@ TEST_F(SimdMathTest, expSingleAccuracy) GMX_EXPECT_SIMD_FUNC_NEAR(std::exp, expSingleAccuracy, settings); // Subnormal range, require matching, but DTZ is fine - settings = { Range(lowestRealThatProducesDenormal, lowestRealThatProducesNormal), ulpTol_, - absTol_, MatchRule::Dtz }; + settings = { Range(lowestRealThatProducesDenormal, lowestRealThatProducesNormal), + ulpTol_, + absTol_, + MatchRule::Dtz }; GMX_EXPECT_SIMD_FUNC_NEAR(std::exp, expSingleAccuracy, settings); // Normal range, standard result expected - settings = { Range(lowestRealThatProducesNormal, highestRealThatProducesNormal), ulpTol_, - absTol_, MatchRule::Normal }; + settings = { Range(lowestRealThatProducesNormal, highestRealThatProducesNormal), + ulpTol_, + absTol_, + MatchRule::Normal }; GMX_EXPECT_SIMD_FUNC_NEAR(std::exp, expSingleAccuracy, settings); } @@ -1258,7 +1279,9 @@ TEST_F(SimdMathTest, expSingleAccuracyUnsafe) setUlpTolSingleAccuracy(ulpTol_); CompareSettings settings{ Range(lowestRealThatProducesNormal, highestRealThatProducesNormal), - ulpTol_, absTol_, MatchRule::Normal }; + ulpTol_, + absTol_, + MatchRule::Normal }; GMX_EXPECT_SIMD_FUNC_NEAR(std::exp, expSingleAccuracy, settings); } diff --git a/src/gromacs/simd/tests/simd_vector_operations.cpp b/src/gromacs/simd/tests/simd_vector_operations.cpp index a662f14a84..8e3e4ff29c 100644 --- a/src/gromacs/simd/tests/simd_vector_operations.cpp +++ b/src/gromacs/simd/tests/simd_vector_operations.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2014,2015,2017,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2014,2015,2017,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -68,8 +68,8 @@ TEST_F(SimdVectorOperationsTest, iprod) SimdReal bX = rSimd_c3c0c4; SimdReal bY = rSimd_c4c6c8; SimdReal bZ = rSimd_c7c2c3; - SimdReal iprodRef = setSimdRealFrom3R(c0 * c3 + c3 * c4 + c6 * c7, c1 * c0 + c4 * c6 + c7 * c2, - c2 * c4 + c5 * c8 + c8 * c3); + SimdReal iprodRef = setSimdRealFrom3R( + c0 * c3 + c3 * c4 + c6 * c7, c1 * c0 + c4 * c6 + c7 * c2, c2 * c4 + c5 * c8 + c8 * c3); setUlpTol(2); GMX_EXPECT_SIMD_REAL_NEAR(iprodRef, iprod(aX, aY, aZ, bX, bY, bZ)); @@ -80,8 +80,8 @@ TEST_F(SimdVectorOperationsTest, norm2) SimdReal simdX = rSimd_c0c1c2; SimdReal simdY = rSimd_c3c4c5; SimdReal simdZ = rSimd_c6c7c8; - SimdReal norm2Ref = setSimdRealFrom3R(c0 * c0 + c3 * c3 + c6 * c6, c1 * c1 + c4 * c4 + c7 * c7, - c2 * c2 + c5 * c5 + c8 * c8); + SimdReal norm2Ref = setSimdRealFrom3R( + c0 * c0 + c3 * c3 + c6 * c6, c1 * c1 + c4 * c4 + c7 * c7, c2 * c2 + c5 * c5 + c8 * c8); setUlpTol(2); GMX_EXPECT_SIMD_REAL_NEAR(norm2Ref, norm2(simdX, simdY, simdZ)); @@ -98,12 +98,12 @@ TEST_F(SimdVectorOperationsTest, cprod) // The SIMD version might use FMA. If we don't force FMA for the reference value, the compiler is free to use FMA // for either product. If the compiler uses FMA for one product and the SIMD version uses FMA for the other, the // rounding error of each product adds up and the total possible ulp-error is 12. - SimdReal refcX = setSimdRealFrom3R(std::fma(-c6, c4, c3 * c7), std::fma(-c7, c6, c4 * c2), - std::fma(-c8, c8, c5 * c3)); - SimdReal refcY = setSimdRealFrom3R(std::fma(-c0, c7, c6 * c3), std::fma(-c1, c2, c7 * c0), - std::fma(-c2, c3, c8 * c4)); - SimdReal refcZ = setSimdRealFrom3R(std::fma(-c3, c3, c0 * c4), std::fma(-c4, c0, c1 * c6), - std::fma(-c5, c4, c2 * c8)); + SimdReal refcX = setSimdRealFrom3R( + std::fma(-c6, c4, c3 * c7), std::fma(-c7, c6, c4 * c2), std::fma(-c8, c8, c5 * c3)); + SimdReal refcY = setSimdRealFrom3R( + std::fma(-c0, c7, c6 * c3), std::fma(-c1, c2, c7 * c0), std::fma(-c2, c3, c8 * c4)); + SimdReal refcZ = setSimdRealFrom3R( + std::fma(-c3, c3, c0 * c4), std::fma(-c4, c0, c1 * c6), std::fma(-c5, c4, c2 * c8)); SimdReal cX, cY, cZ; // The test assumes that cprod uses FMA on architectures which have FMA so that the compiler diff --git a/src/gromacs/statistics/statistics.cpp b/src/gromacs/statistics/statistics.cpp index 5e1315cfeb..2e30ce8d69 100644 --- a/src/gromacs/statistics/statistics.cpp +++ b/src/gromacs/statistics/statistics.cpp @@ -178,8 +178,8 @@ int gmx_stats_add_points(gmx_stats_t gstats, int n, real* x, real* y, real* dx, for (int i = 0; (i < n); i++) { int ok; - if ((ok = gmx_stats_add_point(gstats, x[i], y[i], (nullptr != dx) ? dx[i] : 0, - (nullptr != dy) ? dy[i] : 0)) + if ((ok = gmx_stats_add_point( + gstats, x[i], y[i], (nullptr != dx) ? dx[i] : 0, (nullptr != dy) ? dy[i] : 0)) != estatsOK) { return ok; @@ -514,8 +514,12 @@ int gmx_stats_remove_outliers(gmx_stats_t gstats, double level) r = std::abs(stats->x[i] - stats->y[i]); if (r > level * rmsd) { - fprintf(stderr, "Removing outlier, iter = %d, rmsd = %g, x = %g, y = %g\n", iter, - rmsd, stats->x[i], stats->y[i]); + fprintf(stderr, + "Removing outlier, iter = %d, rmsd = %g, x = %g, y = %g\n", + iter, + rmsd, + stats->x[i], + stats->y[i]); if (i < stats->np - 1) { stats->x[i] = stats->x[stats->np - 1]; diff --git a/src/gromacs/swap/swapcoords.cpp b/src/gromacs/swap/swapcoords.cpp index e6debca14e..9dbac86f6d 100644 --- a/src/gromacs/swap/swapcoords.cpp +++ b/src/gromacs/swap/swapcoords.cpp @@ -82,9 +82,8 @@ static const char* SwS = { "SWAP:" }; /**< For output that comes from the swap module */ static const char* SwSEmpty = { " " }; /**< Placeholder for multi-line output */ -static const char* CompStr[eCompNR] = { "A", "B" }; /**< Compartment name */ -static const char* SwapStr[eSwapTypesNR + 1] = { "", "X-", "Y-", "Z-", - nullptr }; /**< Name for the swap types. */ +static const char* CompStr[eCompNR] = { "A", "B" }; /**< Compartment name */ +static const char* SwapStr[eSwapTypesNR + 1] = { "", "X-", "Y-", "Z-", nullptr }; /**< Name for the swap types. */ static const char* DimStr[DIM + 1] = { "X", "Y", "Z", nullptr }; /**< Name for the swap dimension. */ /** Keep track of through which channel the ions have passed */ @@ -109,8 +108,7 @@ enum eDomain eDomainB, eDomainNr }; -static const char* DomainString[eDomainNr] = { "not_assigned", "Domain_A", - "Domain_B" }; /**< Name for the domains */ +static const char* DomainString[eDomainNr] = { "not_assigned", "Domain_A", "Domain_B" }; /**< Name for the domains */ namespace gmx { @@ -305,7 +303,9 @@ static void print_ionlist(t_swap* s, double time, const char comment[]) } // Output center of split groups - fprintf(s->fpout, "%10g%10g", s->group[eGrpSplit0].center[s->swapdim], + fprintf(s->fpout, + "%10g%10g", + s->group[eGrpSplit0].center[s->swapdim], s->group[eGrpSplit1].center[s->swapdim]); // Output ion flux for each channel and ion type @@ -569,10 +569,10 @@ static void detect_flux_per_channel(t_swapgrp* g, sd = s->swapdim; /* Check whether ion is inside any of the channels */ - in_cyl0 = is_in_channel(atomPosition, s->group[eGrpSplit0].center, sc->cyl0u, sc->cyl0l, - cyl0_r2, s->pbc, sd); - in_cyl1 = is_in_channel(atomPosition, s->group[eGrpSplit1].center, sc->cyl1u, sc->cyl1l, - cyl1_r2, s->pbc, sd); + in_cyl0 = is_in_channel( + atomPosition, s->group[eGrpSplit0].center, sc->cyl0u, sc->cyl0l, cyl0_r2, s->pbc, sd); + in_cyl1 = is_in_channel( + atomPosition, s->group[eGrpSplit1].center, sc->cyl1u, sc->cyl1l, cyl1_r2, s->pbc, sd); if (in_cyl0 && in_cyl1) { @@ -627,8 +627,12 @@ static void detect_flux_per_channel(t_swapgrp* g, case eChHistPassedNone: ++s->fluxleak; - fprintf(stderr, " %s Warning! Step %s, ion %d moved from %s to %s\n", SwS, - gmx_step_str(step, buf), iAtom, DomainString[*comp_from], + fprintf(stderr, + " %s Warning! Step %s, ion %d moved from %s to %s\n", + SwS, + gmx_step_str(step, buf), + iAtom, + DomainString[*comp_from], DomainString[*comp_now]); if (bRerun) { @@ -643,7 +647,9 @@ static void detect_flux_per_channel(t_swapgrp* g, fprintf(s->fpout, " # Warning: step %s, ion %d moved from %s to %s (probably through the " "membrane)\n", - gmx_step_str(step, buf), iAtom, DomainString[*comp_from], + gmx_step_str(step, buf), + iAtom, + DomainString[*comp_from], DomainString[*comp_now]); } break; @@ -666,8 +672,7 @@ static void detect_flux_per_channel(t_swapgrp* g, { g->fluxfromAtoB[chan_nr]--; } - fprintf(fpout, "# Atom nr. %d finished passing %s.\n", iAtom, - ChannelString[*channel_label]); + fprintf(fpout, "# Atom nr. %d finished passing %s.\n", iAtom, ChannelString[*channel_label]); break; default: gmx_fatal(FARGS, "%s Unknown channel history entry for ion type '%s'\n", SwS, g->molname); @@ -718,8 +723,8 @@ static void sortMoleculesIntoCompartments(t_swapgrp* g, int sd = s->swapdim; /* Is this first atom of the molecule in the compartment that we look at? */ - if (compartment_contains_atom(left, right, g->xc[iAtom][sd], box[sd][sd], - sc->bulkOffset[comp], &dist)) + if (compartment_contains_atom( + left, right, g->xc[iAtom][sd], box[sd][sd], sc->bulkOffset[comp], &dist)) { /* Add the first atom of this molecule to the list of molecules in this compartment */ add_to_list(iAtom, &g->comp[comp], dist); @@ -728,9 +733,20 @@ static void sortMoleculesIntoCompartments(t_swapgrp* g, if (MASTER(cr) && (g->comp_now != nullptr) && !bIsSolvent) { int globalAtomNr = g->atomset.globalIndex()[iAtom] + 1; /* PDB index starts at 1 ... */ - detect_flux_per_channel(g, globalAtomNr, comp, g->xc[iAtom], &g->comp_now[iMol], - &g->comp_from[iMol], &g->channel_label[iMol], sc, s, - cyl0_r2, cyl1_r2, step, bRerun, fpout); + detect_flux_per_channel(g, + globalAtomNr, + comp, + g->xc[iAtom], + &g->comp_now[iMol], + &g->comp_from[iMol], + &g->channel_label[iMol], + sc, + s, + cyl0_r2, + cyl1_r2, + step, + bRerun, + fpout); } } else @@ -756,7 +772,10 @@ static void sortMoleculesIntoCompartments(t_swapgrp* g, "split\n" "%s cylinder is way too large, or one compartment has collapsed (step " "%" PRId64 ")\n", - SwS, g->nCylBoth, SwS, step); + SwS, + g->nCylBoth, + SwS, + step); fprintf(s->fpout, "Warning: %d atoms were assigned to both channels!\n", g->nCylBoth); @@ -766,8 +785,12 @@ static void sortMoleculesIntoCompartments(t_swapgrp* g, if (bIsSolvent && nullptr != fpout) { - fprintf(fpout, "# Solv. molecules in comp.%s: %d comp.%s: %d\n", CompStr[eCompA], - g->comp[eCompA].nMol, CompStr[eCompB], g->comp[eCompB].nMol); + fprintf(fpout, + "# Solv. molecules in comp.%s: %d comp.%s: %d\n", + CompStr[eCompA], + g->comp[eCompA].nMol, + CompStr[eCompB], + g->comp[eCompB].nMol); } /* Consistency checks */ @@ -777,7 +800,11 @@ static void sortMoleculesIntoCompartments(t_swapgrp* g, fprintf(stderr, "%s Warning: Inconsistency while assigning '%s' molecules to compartments. !inA: " "%d, !inB: %d, total molecules %d\n", - SwS, g->molname, nMolNotInComp[eCompA], nMolNotInComp[eCompB], numMolecules); + SwS, + g->molname, + nMolNotInComp[eCompA], + nMolNotInComp[eCompB], + numMolecules); } int sum = g->comp[eCompA].nMol + g->comp[eCompB].nMol; @@ -786,7 +813,10 @@ static void sortMoleculesIntoCompartments(t_swapgrp* g, fprintf(stderr, "%s Warning: %d molecules are in group '%s', but altogether %d have been assigned " "to the compartments.\n", - SwS, numMolecules, g->molname, sum); + SwS, + numMolecules, + g->molname, + sum); } } @@ -844,7 +874,11 @@ static void get_initial_ioncounts(const t_inputrec* ir, "Mismatch of the number of %s ions summed over both compartments.\n" "You requested a total of %d ions (%d in A and %d in B),\n" "but there are a total of %d ions of this type in the system.\n", - g->molname, req, g->comp[eCompA].nMolReq, g->comp[eCompB].nMolReq, tot); + g->molname, + req, + g->comp[eCompA].nMolReq, + g->comp[eCompB].nMolReq, + tot); } /* Initialize time-averaging: @@ -898,8 +932,11 @@ static void get_initial_ioncounts_from_cpt(const t_inputrec* ir, if (bVerbose) { - fprintf(stderr, "%s ... Influx netto: %d Requested: %d Past values: ", SwS, - g->comp[ic].inflow_net, g->comp[ic].nMolReq); + fprintf(stderr, + "%s ... Influx netto: %d Requested: %d Past values: ", + SwS, + g->comp[ic].inflow_net, + g->comp[ic].nMolReq); } for (int j = 0; j < sc->nAverage; j++) @@ -935,8 +972,7 @@ static void bc_initial_concentrations(t_commrec* cr, t_swapcoords* swap, t_swap* { gmx_bcast(sizeof(g->comp[ic].nMolReq), &(g->comp[ic].nMolReq), cr->mpi_comm_mygroup); gmx_bcast(sizeof(g->comp[ic].nMol), &(g->comp[ic].nMol), cr->mpi_comm_mygroup); - gmx_bcast(swap->nAverage * sizeof(g->comp[ic].nMolPast[0]), g->comp[ic].nMolPast, - cr->mpi_comm_mygroup); + gmx_bcast(swap->nAverage * sizeof(g->comp[ic].nMolPast[0]), g->comp[ic].nMolPast, cr->mpi_comm_mygroup); } } } @@ -987,7 +1023,11 @@ static void check_swap_groups(t_swap* s, int nat, gmx_bool bVerbose) "groups, or the solvent.\n" "%s Check the .mdp file settings regarding the swap index groups or the index " "groups themselves.\n", - SwS, nMultiple, (1 == nMultiple) ? " is" : "s are", SwSEmpty, SwSEmpty); + SwS, + nMultiple, + (1 == nMultiple) ? " is" : "s are", + SwSEmpty, + SwSEmpty); } } @@ -1010,8 +1050,12 @@ static int get_group_apm_check(int igroup, t_swap* s, gmx_bool bVerbose, gmx_mto if (bVerbose) { - fprintf(stderr, "%s Checking whether all %s molecules consist of %d atom%s\n", SwS, - g->molname, apm, apm > 1 ? "s" : ""); + fprintf(stderr, + "%s Checking whether all %s molecules consist of %d atom%s\n", + SwS, + g->molname, + apm, + apm > 1 ? "s" : ""); } /* Check whether this is also true for all other solvent atoms */ @@ -1054,8 +1098,12 @@ static void print_ionlist_legend(const t_inputrec* ir, t_swap* s, const gmx_outp snprintf(buf, STRLEN, "%s %s ions (charge %s%g)", CompStr[ic], g->molname, q > 0 ? "+" : "", q); legend[count++] = gmx_strdup(buf); - snprintf(buf, STRLEN, "%s av. mismatch to %d %s ions", CompStr[ic], - s->group[ig].comp[ic].nMolReq, g->molname); + snprintf(buf, + STRLEN, + "%s av. mismatch to %d %s ions", + CompStr[ic], + s->group[ig].comp[ic].nMolReq, + g->molname); legend[count++] = gmx_strdup(buf); snprintf(buf, STRLEN, "%s net %s ion influx", CompStr[ic], g->molname); @@ -1064,10 +1112,16 @@ static void print_ionlist_legend(const t_inputrec* ir, t_swap* s, const gmx_outp } // Center of split groups - snprintf(buf, STRLEN, "%scenter of %s of split group 0", SwapStr[ir->eSwapCoords], + snprintf(buf, + STRLEN, + "%scenter of %s of split group 0", + SwapStr[ir->eSwapCoords], (nullptr != s->group[eGrpSplit0].m) ? "mass" : "geometry"); legend[count++] = gmx_strdup(buf); - snprintf(buf, STRLEN, "%scenter of %s of split group 1", SwapStr[ir->eSwapCoords], + snprintf(buf, + STRLEN, + "%scenter of %s of split group 1", + SwapStr[ir->eSwapCoords], (nullptr != s->group[eGrpSplit1].m) ? "mass" : "geometry"); legend[count++] = gmx_strdup(buf); @@ -1174,8 +1228,7 @@ static void detect_flux_per_channel_init(t_swap* s, swaphistory_t* swapstate, co for (int ic = 0; ic < eChanNR; ic++) { - fprintf(stderr, "%s Channel %d flux history for ion type %s (charge %g): ", SwS, ic, - g->molname, g->q); + fprintf(stderr, "%s Channel %d flux history for ion type %s (charge %g): ", SwS, ic, g->molname, g->q); if (isRestart) { g->fluxfromAtoB[ic] = gs->fluxfromAtoB[ic]; @@ -1223,10 +1276,11 @@ static void outputStartStructureIfWanted(gmx_mtop_t* mtop, rvec* x, PbcType pbcT "whole.\n" "%s In case of multimeric channels, please check whether they have the correct PBC " "representation.\n", - SwS, SwSEmpty); + SwS, + SwSEmpty); - write_sto_conf_mtop("CompELAssumedWholeConfiguration.pdb", *mtop->name, mtop, x, nullptr, - pbcType, box); + write_sto_conf_mtop( + "CompELAssumedWholeConfiguration.pdb", *mtop->name, mtop, x, nullptr, pbcType, box); } } @@ -1363,14 +1417,21 @@ static void copyIndicesToGroup(const int* indIons, int nIons, t_swapGroup* g, t_ { if (g->nat != (g->nmolReq[eCompA] + g->nmolReq[eCompB])) { - gmx_fatal_collective(FARGS, cr->mpi_comm_mysim, MASTER(cr), + gmx_fatal_collective(FARGS, + cr->mpi_comm_mysim, + MASTER(cr), "%s Inconsistency while importing swap-related data from an old " "input file version.\n" "%s The requested ion counts in compartments A (%d) and B (%d)\n" "%s do not add up to the number of ions (%d) of this type for the " "group '%s'.\n", - SwS, SwSEmpty, g->nmolReq[eCompA], g->nmolReq[eCompB], SwSEmpty, - g->nat, g->molname); + SwS, + SwSEmpty, + g->nmolReq[eCompA], + g->nmolReq[eCompB], + SwSEmpty, + g->nat, + g->molname); } } @@ -1427,8 +1488,12 @@ static void convertOldToNewGroupFormat(t_swapcoords* sc, gmx_mtop_t* mtop, gmx_b if (bVerbose) { - fprintf(stdout, "%s Sorted %d ions into separate groups of %d anions and %d cations.\n", - SwS, g->nat, nAnions, nCations); + fprintf(stdout, + "%s Sorted %d ions into separate groups of %d anions and %d cations.\n", + SwS, + g->nat, + nAnions, + nCations); } @@ -1563,8 +1628,7 @@ t_swap* init_swapcoords(FILE* fplog, for (int ig = eGrpSplit0; ig <= eGrpSplit1; ig++) { g = &(s->group[ig]); - gmx_bcast((g->atomset.numAtomsGlobal()) * sizeof((g->xc_old)[0]), g->xc_old, - cr->mpi_comm_mygroup); + gmx_bcast((g->atomset.numAtomsGlobal()) * sizeof((g->xc_old)[0]), g->xc_old, cr->mpi_comm_mygroup); } } @@ -1618,8 +1682,7 @@ t_swap* init_swapcoords(FILE* fplog, { if (bVerbose) { - fprintf(stderr, "%s Opening output file %s%s\n", SwS, fn, - restartWithAppending ? " for appending" : ""); + fprintf(stderr, "%s Opening output file %s%s\n", SwS, fn, restartWithAppending ? " for appending" : ""); } s->fpout = gmx_fio_fopen(fn, restartWithAppending ? "a" : "w"); @@ -1631,14 +1694,19 @@ t_swap* init_swapcoords(FILE* fplog, for (int ig = 0; ig < s->ngrp; ig++) { g = &(s->group[ig]); - fprintf(s->fpout, "# %s group '%s' contains %d atom%s", - ig < eSwapFixedGrpNR ? eSwapFixedGrp_names[ig] : "Ion", g->molname, + fprintf(s->fpout, + "# %s group '%s' contains %d atom%s", + ig < eSwapFixedGrpNR ? eSwapFixedGrp_names[ig] : "Ion", + g->molname, static_cast(g->atomset.numAtomsGlobal()), (g->atomset.numAtomsGlobal() > 1) ? "s" : ""); if (!(eGrpSplit0 == ig || eGrpSplit1 == ig)) { - fprintf(s->fpout, " with %d atom%s in each molecule of charge %g", g->apm, - (g->apm > 1) ? "s" : "", g->q); + fprintf(s->fpout, + " with %d atom%s in each molecule of charge %g", + g->apm, + (g->apm > 1) ? "s" : "", + g->q); } fprintf(s->fpout, ".\n"); } @@ -1658,8 +1726,11 @@ t_swap* init_swapcoords(FILE* fplog, get_center(g->xc, g->m, g->atomset.numAtomsGlobal(), g->center); if (!restartWithAppending) { - fprintf(s->fpout, "# %s group %s-center %5f nm\n", eSwapFixedGrp_names[j], - DimStr[s->swapdim], g->center[s->swapdim]); + fprintf(s->fpout, + "# %s group %s-center %5f nm\n", + eSwapFixedGrp_names[j], + DimStr[s->swapdim], + g->center[s->swapdim]); } } @@ -1681,10 +1752,16 @@ t_swap* init_swapcoords(FILE* fplog, } fprintf(s->fpout, "#\n"); - fprintf(s->fpout, "# Split0 cylinder radius %f nm, up %f nm, down %f nm\n", sc->cyl0r, - sc->cyl0u, sc->cyl0l); - fprintf(s->fpout, "# Split1 cylinder radius %f nm, up %f nm, down %f nm\n", sc->cyl1r, - sc->cyl1u, sc->cyl1l); + fprintf(s->fpout, + "# Split0 cylinder radius %f nm, up %f nm, down %f nm\n", + sc->cyl0r, + sc->cyl0u, + sc->cyl0l); + fprintf(s->fpout, + "# Split1 cylinder radius %f nm, up %f nm, down %f nm\n", + sc->cyl1r, + sc->cyl1u, + sc->cyl1l); fprintf(s->fpout, "#\n"); if (!mdrunOptions.rerun) @@ -1692,7 +1769,8 @@ t_swap* init_swapcoords(FILE* fplog, fprintf(s->fpout, "# Coupling constant (number of swap attempt steps to average over): %d " "(translates to %f ps).\n", - sc->nAverage, sc->nAverage * sc->nstswap * ir->delta_t); + sc->nAverage, + sc->nAverage * sc->nstswap * ir->delta_t); fprintf(s->fpout, "# Threshold is %f\n", sc->threshold); fprintf(s->fpout, "#\n"); fprintf(s->fpout, @@ -1726,8 +1804,8 @@ t_swap* init_swapcoords(FILE* fplog, else { fprintf(stderr, "%s Determining initial numbers of ions per compartment.\n", SwS); - get_initial_ioncounts(ir, s, globalState->x.rvec_array(), globalState->box, cr, - mdrunOptions.rerun); + get_initial_ioncounts( + ir, s, globalState->x.rvec_array(), globalState->box, cr, mdrunOptions.rerun); } /* Prepare (further) checkpoint writes ... */ @@ -1736,8 +1814,11 @@ t_swap* init_swapcoords(FILE* fplog, /* Consistency check */ if (swapstate->nAverage != sc->nAverage) { - gmx_fatal(FARGS, "%s Ion count averaging steps mismatch! checkpoint: %d, tpr: %d", - SwS, swapstate->nAverage, sc->nAverage); + gmx_fatal(FARGS, + "%s Ion count averaging steps mismatch! checkpoint: %d, tpr: %d", + SwS, + swapstate->nAverage, + sc->nAverage); } } else @@ -1872,7 +1953,9 @@ static int get_index_of_distant_atom(t_compartment* comp, const char molname[]) gmx_fatal(FARGS, "Could not get index of %s atom. Compartment contains %d %s molecules before " "swaps.", - molname, comp->nMolBefore, molname); + molname, + comp->nMolBefore, + molname); } /* Set the distance of this index to infinity such that it won't get selected again in @@ -1957,10 +2040,18 @@ gmx_bool do_swapcoords(t_commrec* cr, for (ig = eGrpSplit0; ig <= eGrpSplit1; ig++) { g = &(s->group[ig]); - communicate_group_positions(cr, g->xc, g->xc_shifts, g->xc_eshifts, TRUE, x, - g->atomset.numAtomsGlobal(), g->atomset.numAtomsLocal(), + communicate_group_positions(cr, + g->xc, + g->xc_shifts, + g->xc_eshifts, + TRUE, + x, + g->atomset.numAtomsGlobal(), + g->atomset.numAtomsLocal(), g->atomset.localIndex().data(), - g->atomset.collectiveIndex().data(), g->xc_old, box); + g->atomset.collectiveIndex().data(), + g->xc_old, + box); get_center(g->xc, g->m, g->atomset.numAtomsGlobal(), g->center); /* center of split groups == channels */ } @@ -1971,9 +2062,18 @@ gmx_bool do_swapcoords(t_commrec* cr, for (ig = eSwapFixedGrpNR; ig < s->ngrp; ig++) { g = &(s->group[ig]); - communicate_group_positions(cr, g->xc, nullptr, nullptr, FALSE, x, g->atomset.numAtomsGlobal(), - g->atomset.numAtomsLocal(), g->atomset.localIndex().data(), - g->atomset.collectiveIndex().data(), nullptr, nullptr); + communicate_group_positions(cr, + g->xc, + nullptr, + nullptr, + FALSE, + x, + g->atomset.numAtomsGlobal(), + g->atomset.numAtomsLocal(), + g->atomset.localIndex().data(), + g->atomset.collectiveIndex().data(), + nullptr, + nullptr); /* Determine how many ions of this type each compartment contains */ sortMoleculesIntoCompartments(g, cr, sc, s, box, step, s->fpout, bRerun, FALSE); @@ -1999,9 +2099,18 @@ gmx_bool do_swapcoords(t_commrec* cr, /* Since we here know that we have to perform ion/water position exchanges, * we now assemble the solvent positions */ g = &(s->group[eGrpSolvent]); - communicate_group_positions(cr, g->xc, nullptr, nullptr, FALSE, x, g->atomset.numAtomsGlobal(), - g->atomset.numAtomsLocal(), g->atomset.localIndex().data(), - g->atomset.collectiveIndex().data(), nullptr, nullptr); + communicate_group_positions(cr, + g->xc, + nullptr, + nullptr, + FALSE, + x, + g->atomset.numAtomsGlobal(), + g->atomset.numAtomsLocal(), + g->atomset.localIndex().data(), + g->atomset.collectiveIndex().data(), + nullptr, + nullptr); /* Determine how many molecules of solvent each compartment contains */ sortMoleculesIntoCompartments(g, cr, sc, s, box, step, s->fpout, bRerun, TRUE); @@ -2082,8 +2191,13 @@ gmx_bool do_swapcoords(t_commrec* cr, if (nswaps && bVerbose) { - fprintf(stderr, "%s Performed %d swap%s in step %" PRId64 " for iontype %s.\n", SwS, - nswaps, nswaps > 1 ? "s" : "", step, g->molname); + fprintf(stderr, + "%s Performed %d swap%s in step %" PRId64 " for iontype %s.\n", + SwS, + nswaps, + nswaps > 1 ? "s" : "", + step, + g->molname); } } diff --git a/src/gromacs/tables/cubicsplinetable.cpp b/src/gromacs/tables/cubicsplinetable.cpp index 9f0bf2b451..dcbdbfe7a2 100644 --- a/src/gromacs/tables/cubicsplinetable.cpp +++ b/src/gromacs/tables/cubicsplinetable.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2016,2017,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2016,2017,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -116,8 +116,8 @@ void cubicSplineInterpolationFromFunctionAndDerivative(double functionValue0, { double Y, F, G, H; - calculateCubicSplineCoefficients(functionValue0, functionValue1, derivativeValue0, - derivativeValue1, spacing, &Y, &F, &G, &H); + calculateCubicSplineCoefficients( + functionValue0, functionValue1, derivativeValue0, derivativeValue1, spacing, &Y, &F, &G, &H); double Fp = fma(fma(H, eps, G), eps, F); @@ -179,8 +179,15 @@ void fillSingleCubicSplineTableData(const std::function& functio if (functionIsInRange) { - calculateCubicSplineCoefficients(tmpFunctionValue, nextHigherFunction, tmpDerivativeValue, - nextHigherDerivative, spacing, &Y, &F, &G, &H); + calculateCubicSplineCoefficients(tmpFunctionValue, + nextHigherFunction, + tmpDerivativeValue, + nextHigherDerivative, + spacing, + &Y, + &F, + &G, + &H); lastIndexInRange--; } else @@ -250,9 +257,14 @@ void fillSingleCubicSplineTableData(ArrayRef function, if (functionIsInRange) { - cubicSplineInterpolationFromFunctionAndDerivative( - function[index], function[index + 1], derivative[index], derivative[index + 1], - inputSpacing, eps, &(tmpFunction[i]), &(tmpDerivative[i])); + cubicSplineInterpolationFromFunctionAndDerivative(function[index], + function[index + 1], + derivative[index], + derivative[index + 1], + inputSpacing, + eps, + &(tmpFunction[i]), + &(tmpDerivative[i])); lastIndexInRange--; } else @@ -273,8 +285,8 @@ void fillSingleCubicSplineTableData(ArrayRef function, double nextFunction = ((i + 1) < endIndex) ? tmpFunction[i + 1] : 0.0; double nextDerivative = ((i + 1) < endIndex) ? tmpDerivative[i + 1] : 0.0; - calculateCubicSplineCoefficients(tmpFunction[i], nextFunction, tmpDerivative[i], - nextDerivative, spacing, &Y, &F, &G, &H); + calculateCubicSplineCoefficients( + tmpFunction[i], nextFunction, tmpDerivative[i], nextDerivative, spacing, &Y, &F, &G, &H); (*yfghTableData)[4 * i] = Y; (*yfghTableData)[4 * i + 1] = F; (*yfghTableData)[4 * i + 2] = G; @@ -362,11 +374,11 @@ CubicSplineTable::CubicSplineTable(std::initializer_list tmpYfghTableData; - fillSingleCubicSplineTableData(thisFuncInput.function, thisFuncInput.derivative, range_, - spacing, &tmpYfghTableData); + fillSingleCubicSplineTableData( + thisFuncInput.function, thisFuncInput.derivative, range_, spacing, &tmpYfghTableData); - internal::fillMultiplexedTableData(tmpYfghTableData, &yfghMultiTableData_, 4, - numFuncInTable_, funcIndex); + internal::fillMultiplexedTableData( + tmpYfghTableData, &yfghMultiTableData_, 4, numFuncInTable_, funcIndex); funcIndex++; } @@ -467,11 +479,15 @@ CubicSplineTable::CubicSplineTable(std::initializer_list tmpYfghTableData; - fillSingleCubicSplineTableData(thisFuncInput.function, thisFuncInput.derivative, - thisFuncInput.spacing, range, spacing, &tmpYfghTableData); + fillSingleCubicSplineTableData(thisFuncInput.function, + thisFuncInput.derivative, + thisFuncInput.spacing, + range, + spacing, + &tmpYfghTableData); - internal::fillMultiplexedTableData(tmpYfghTableData, &yfghMultiTableData_, 4, - numFuncInTable_, funcIndex); + internal::fillMultiplexedTableData( + tmpYfghTableData, &yfghMultiTableData_, 4, numFuncInTable_, funcIndex); funcIndex++; } diff --git a/src/gromacs/tables/cubicsplinetable.h b/src/gromacs/tables/cubicsplinetable.h index 268a19faf1..4cbc4d330c 100644 --- a/src/gromacs/tables/cubicsplinetable.h +++ b/src/gromacs/tables/cubicsplinetable.h @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2016,2017,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2016,2017,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -291,8 +291,8 @@ public: // Load Derivative, Delta, Function, and Zero values for each table point. // The 4 refers to these four values - not any SIMD width. - gatherLoadBySimdIntTranspose<4 * numFuncInTable>(yfghMultiTableData_.data() + 4 * funcIndex, - tabIndex, &Y, &F, &G, &H); + gatherLoadBySimdIntTranspose<4 * numFuncInTable>( + yfghMultiTableData_.data() + 4 * funcIndex, tabIndex, &Y, &F, &G, &H); *functionValue = fma(fma(fma(H, eps, G), eps, F), eps, Y); *derivativeValue = tableScale_ * fma(fma(T(3.0) * H, eps, T(2.0) * G), eps, F); } @@ -347,8 +347,8 @@ public: // Load Derivative, Delta, Function, and Zero values for each table point. // The 4 refers to these four values - not any SIMD width. - gatherLoadBySimdIntTranspose<4 * numFuncInTable>(yfghMultiTableData_.data() + 4 * funcIndex, - tabIndex, &Y, &F, &G, &H); + gatherLoadBySimdIntTranspose<4 * numFuncInTable>( + yfghMultiTableData_.data() + 4 * funcIndex, tabIndex, &Y, &F, &G, &H); *derivativeValue = tableScale_ * fma(fma(T(3.0) * H, eps, T(2.0) * G), eps, F); } diff --git a/src/gromacs/tables/forcetable.cpp b/src/gromacs/tables/forcetable.cpp index 2e61e90b08..b803652555 100644 --- a/src/gromacs/tables/forcetable.cpp +++ b/src/gromacs/tables/forcetable.cpp @@ -335,8 +335,7 @@ real ewald_spline3_table_scale(const interaction_const_t& ic, { GMX_RELEASE_ASSERT(!generateCoulombTables || EEL_PME_EWALD(ic.eeltype), "Can only use tables with Ewald"); - GMX_RELEASE_ASSERT(!generateVdwTables || EVDW_PME(ic.vdwtype), - "Can only use tables with Ewald"); + GMX_RELEASE_ASSERT(!generateVdwTables || EVDW_PME(ic.vdwtype), "Can only use tables with Ewald"); real sc = 0; @@ -574,8 +573,12 @@ static void set_forces(FILE* fp, int angle, int nx, double h, double v[], double if (fp) { - fprintf(fp, "Generating forces for table %d, boundary conditions: V''' at %g, %s at %g\n", - table + 1, start * h, end == nx ? "V'''" : "V'=0", (end - 1) * h); + fprintf(fp, + "Generating forces for table %d, boundary conditions: V''' at %g, %s at %g\n", + table + 1, + start * h, + end == nx ? "V'''" : "V'=0", + (end - 1) * h); } spline_forces(end - start, h, v + start, TRUE, end == nx, f + start); } @@ -594,8 +597,7 @@ static void read_tables(FILE* fp, const char* filename, int ntab, int angle, t_t int numColumns = xvgData.extent(0); if (numColumns != nny) { - gmx_fatal(FARGS, "Trying to read file %s, but nr columns = %d, should be %d", libfn.c_str(), - numColumns, nny); + gmx_fatal(FARGS, "Trying to read file %s, but nr columns = %d, should be %d", libfn.c_str(), numColumns, nny); } int numRows = xvgData.extent(1); @@ -604,8 +606,11 @@ static void read_tables(FILE* fp, const char* filename, int ntab, int angle, t_t { if (yy[0][0] != 0.0) { - gmx_fatal(FARGS, "The first distance in file %s is %f nm instead of %f nm", - libfn.c_str(), yy[0][0], 0.0); + gmx_fatal(FARGS, + "The first distance in file %s is %f nm instead of %f nm", + libfn.c_str(), + yy[0][0], + 0.0); } } else @@ -621,8 +626,13 @@ static void read_tables(FILE* fp, const char* filename, int ntab, int angle, t_t end = 180.0; if (yy[0][0] != start || yy[0][numRows - 1] != end) { - gmx_fatal(FARGS, "The angles in file %s should go from %f to %f instead of %f to %f\n", - libfn.c_str(), start, end, yy[0][0], yy[0][numRows - 1]); + gmx_fatal(FARGS, + "The angles in file %s should go from %f to %f instead of %f to %f\n", + libfn.c_str(), + start, + end, + yy[0][0], + yy[0][numRows - 1]); } } @@ -653,7 +663,10 @@ static void read_tables(FILE* fp, const char* filename, int ntab, int angle, t_t { gmx_fatal(FARGS, "In table file '%s' the x values are not equally spaced: %f %f %f", - filename, yy[0][i - 2], yy[0][i - 1], yy[0][i]); + filename, + yy[0][i - 2], + yy[0][i - 1], + yy[0][i]); } } if (yy[1 + k * 2][i] != 0) @@ -666,8 +679,7 @@ static void read_tables(FILE* fp, const char* filename, int ntab, int angle, t_t } if (yy[1 + k * 2][i] > 0.01 * GMX_REAL_MAX || yy[1 + k * 2][i] < -0.01 * GMX_REAL_MAX) { - gmx_fatal(FARGS, "Out of range potential value %g in file '%s'", - yy[1 + k * 2][i], filename); + gmx_fatal(FARGS, "Out of range potential value %g in file '%s'", yy[1 + k * 2][i], filename); } } if (yy[1 + k * 2 + 1][i] != 0) @@ -680,16 +692,14 @@ static void read_tables(FILE* fp, const char* filename, int ntab, int angle, t_t } if (yy[1 + k * 2 + 1][i] > 0.01 * GMX_REAL_MAX || yy[1 + k * 2 + 1][i] < -0.01 * GMX_REAL_MAX) { - gmx_fatal(FARGS, "Out of range force value %g in file '%s'", - yy[1 + k * 2 + 1][i], filename); + gmx_fatal(FARGS, "Out of range force value %g in file '%s'", yy[1 + k * 2 + 1][i], filename); } } } if (!bZeroV && bZeroF) { - set_forces(fp, angle, numRows, 1 / tabscale, yy[1 + k * 2].data(), - yy[1 + k * 2 + 1].data(), k); + set_forces(fp, angle, numRows, 1 / tabscale, yy[1 + k * 2].data(), yy[1 + k * 2 + 1].data(), k); } else { @@ -721,7 +731,10 @@ static void read_tables(FILE* fp, const char* filename, int ntab, int angle, t_t "For the %d non-zero entries for table %d in %s the forces deviate on " "average %" PRId64 "%% from minus the numerical derivative of the potential\n", - ns, k, libfn.c_str(), gmx::roundToInt64(100 * ssd)); + ns, + k, + libfn.c_str(), + gmx::roundToInt64(100 * ssd)); if (debug) { fprintf(debug, "%s", buf); @@ -910,7 +923,9 @@ static void fill_table(t_tabledata* td, int tp, const interaction_const_t* ic, g gmx_fatal(FARGS, "Cannot apply new potential-shift modifier to interaction type '%s' yet. " "(%s,%d)", - tprops[tp].name, __FILE__, __LINE__); + tprops[tp].name, + __FILE__, + __LINE__); } } @@ -1298,7 +1313,8 @@ t_forcetable* make_tables(FILE* out, const interaction_const_t* ic, const char* gmx_fatal(FARGS, "Tables in file %s not long enough for cut-off:\n" "\tshould be at least %f nm\n", - fn, rtab); + fn, + rtab); } table->n = gmx::roundToInt(rtab * td[0].tabscale); } @@ -1343,7 +1359,10 @@ t_forcetable* make_tables(FILE* out, const interaction_const_t* ic, const char* fprintf(out, "Generated table with %d data points for %s%s.\n" "Tabscale = %g points/nm\n", - td[k].nx, b14only ? "1-4 " : "", tprops[tabsel[k]].name, td[k].tabscale); + td[k].nx, + b14only ? "1-4 " : "", + tprops[tabsel[k]].name, + td[k].tabscale); } } @@ -1366,8 +1385,14 @@ t_forcetable* make_tables(FILE* out, const interaction_const_t* ic, const char* scalefactor = 1.0; } - copy2table(table->n, k * table->formatsize, table->stride, td[k].x, td[k].v, td[k].f, - scalefactor, table->data.data()); + copy2table(table->n, + k * table->formatsize, + table->stride, + td[k].x, + td[k].v, + td[k].f, + scalefactor, + table->data.data()); done_tabledata(&(td[k])); } diff --git a/src/gromacs/tables/quadraticsplinetable.cpp b/src/gromacs/tables/quadraticsplinetable.cpp index 695e06dc88..af5129f2a3 100644 --- a/src/gromacs/tables/quadraticsplinetable.cpp +++ b/src/gromacs/tables/quadraticsplinetable.cpp @@ -247,8 +247,7 @@ void fillDdfzTableData(const std::vector& functionTableData, const std::vector& derivativeTableData, std::vector* ddfzTableData) { - GMX_ASSERT(functionTableData.size() == derivativeTableData.size(), - "Mismatching vector lengths"); + GMX_ASSERT(functionTableData.size() == derivativeTableData.size(), "Mismatching vector lengths"); std::size_t points = functionTableData.size(); @@ -342,16 +341,20 @@ QuadraticSplineTable::QuadraticSplineTable(std::initializer_list tmpDerTableData; std::vector tmpDdfzTableData; - fillSingleQuadraticSplineTableData(thisFuncInput.function, thisFuncInput.derivative, - range_, spacing, &tmpFuncTableData, &tmpDerTableData); + fillSingleQuadraticSplineTableData(thisFuncInput.function, + thisFuncInput.derivative, + range_, + spacing, + &tmpFuncTableData, + &tmpDerTableData); fillDdfzTableData(tmpFuncTableData, tmpDerTableData, &tmpDdfzTableData); - internal::fillMultiplexedTableData(tmpDerTableData, &derivativeMultiTableData_, 1, - numFuncInTable_, funcIndex); + internal::fillMultiplexedTableData( + tmpDerTableData, &derivativeMultiTableData_, 1, numFuncInTable_, funcIndex); - internal::fillMultiplexedTableData(tmpDdfzTableData, &ddfzMultiTableData_, 4, - numFuncInTable_, funcIndex); + internal::fillMultiplexedTableData( + tmpDdfzTableData, &ddfzMultiTableData_, 4, numFuncInTable_, funcIndex); funcIndex++; } @@ -458,17 +461,21 @@ QuadraticSplineTable::QuadraticSplineTable(std::initializer_list tmpDerTableData; std::vector tmpDdfzTableData; - fillSingleQuadraticSplineTableData(thisFuncInput.function, thisFuncInput.derivative, - thisFuncInput.spacing, range, spacing, - &tmpFuncTableData, &tmpDerTableData); + fillSingleQuadraticSplineTableData(thisFuncInput.function, + thisFuncInput.derivative, + thisFuncInput.spacing, + range, + spacing, + &tmpFuncTableData, + &tmpDerTableData); fillDdfzTableData(tmpFuncTableData, tmpDerTableData, &tmpDdfzTableData); - internal::fillMultiplexedTableData(tmpDerTableData, &derivativeMultiTableData_, 1, - numFuncInTable_, funcIndex); + internal::fillMultiplexedTableData( + tmpDerTableData, &derivativeMultiTableData_, 1, numFuncInTable_, funcIndex); - internal::fillMultiplexedTableData(tmpDdfzTableData, &ddfzMultiTableData_, 4, - numFuncInTable_, funcIndex); + internal::fillMultiplexedTableData( + tmpDdfzTableData, &ddfzMultiTableData_, 4, numFuncInTable_, funcIndex); funcIndex++; } diff --git a/src/gromacs/tables/quadraticsplinetable.h b/src/gromacs/tables/quadraticsplinetable.h index 5c74216190..4a494dd5ca 100644 --- a/src/gromacs/tables/quadraticsplinetable.h +++ b/src/gromacs/tables/quadraticsplinetable.h @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2016,2019, by the GROMACS development team, led by + * Copyright (c) 2016,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -330,8 +330,8 @@ public: // Load Derivative, Delta, Function, and Zero values for each table point. // The 4 refers to these four values - not any SIMD width. - gatherLoadBySimdIntTranspose<4 * numFuncInTable>(ddfzMultiTableData_.data() + 4 * funcIndex, - tabIndex, &t0, &t1, &t2, &t3); + gatherLoadBySimdIntTranspose<4 * numFuncInTable>( + ddfzMultiTableData_.data() + 4 * funcIndex, tabIndex, &t0, &t1, &t2, &t3); t1 = t0 + eps * t1; *functionValue = fma(eps * T(halfSpacing_), t0 + t1, t2); @@ -390,17 +390,18 @@ public: if (numFuncInTable == 1) { - gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + funcIndex, - tabIndex, &t0, &t1); // works for scalar T too + gatherLoadUBySimdIntTranspose( + derivativeMultiTableData_.data() + funcIndex, tabIndex, &t0, &t1); // works for scalar T too } else { // This is not ideal, but we need a version of gatherLoadUBySimdIntTranspose that // only loads a single value from memory to implement it better (will be written) + gatherLoadUBySimdIntTranspose( + derivativeMultiTableData_.data() + funcIndex, tabIndex, &t0, &t2); // works for scalar T too gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + funcIndex, - tabIndex, &t0, &t2); // works for scalar T too - gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + funcIndex, - tabIndex + T(1), &t1, + tabIndex + T(1), + &t1, &t2); // works for scalar T too } @@ -517,10 +518,10 @@ public: if (numFuncInTable == 2 && funcIndex0 == 0 && funcIndex1 == 1) { T t0A, t0B, t1A, t1B; - gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data(), tabIndex, - &t0A, &t0B); // works for scalar T too - gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + 2, tabIndex, - &t1A, &t1B); // works for scalar T too + gatherLoadUBySimdIntTranspose( + derivativeMultiTableData_.data(), tabIndex, &t0A, &t0B); // works for scalar T too + gatherLoadUBySimdIntTranspose( + derivativeMultiTableData_.data() + 2, tabIndex, &t1A, &t1B); // works for scalar T too *derivativeValue1 = fma(t1A - t0A, eps, t0A); *derivativeValue2 = fma(t1B - t0B, eps, t0B); } @@ -529,17 +530,19 @@ public: T t0, t1, t2; // This is not ideal, but we need a version of gatherLoadUBySimdIntTranspose that // only loads a single value from memory to implement it better (will be written) + gatherLoadUBySimdIntTranspose( + derivativeMultiTableData_.data() + funcIndex0, tabIndex, &t0, &t2); // works for scalar T too gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + funcIndex0, - tabIndex, &t0, &t2); // works for scalar T too - gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + funcIndex0, - tabIndex + T(1), &t1, + tabIndex + T(1), + &t1, &t2); // works for scalar T too *derivativeValue1 = fma(t1 - t0, eps, t0); + gatherLoadUBySimdIntTranspose( + derivativeMultiTableData_.data() + funcIndex1, tabIndex, &t0, &t2); // works for scalar T too gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + funcIndex1, - tabIndex, &t0, &t2); // works for scalar T too - gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + funcIndex1, - tabIndex + T(1), &t1, + tabIndex + T(1), + &t1, &t2); // works for scalar T too *derivativeValue2 = fma(t1 - t0, eps, t0); } @@ -673,12 +676,12 @@ public: if (numFuncInTable == 3 && funcIndex0 == 0 && funcIndex1 == 1 && funcIndex2 == 2) { T t0A, t0B, t0C, t1A, t1B, t1C; - gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data(), - tabIndex, &t0A, &t0B); - gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + 2, - tabIndex, &t0C, &t1A); - gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + 4, - tabIndex, &t1B, &t1C); + gatherLoadUBySimdIntTranspose( + derivativeMultiTableData_.data(), tabIndex, &t0A, &t0B); + gatherLoadUBySimdIntTranspose( + derivativeMultiTableData_.data() + 2, tabIndex, &t0C, &t1A); + gatherLoadUBySimdIntTranspose( + derivativeMultiTableData_.data() + 4, tabIndex, &t1B, &t1C); *derivativeValue1 = fma(t1A - t0A, eps, t0A); *derivativeValue2 = fma(t1B - t0B, eps, t0B); *derivativeValue3 = fma(t1C - t0C, eps, t0C); @@ -688,24 +691,27 @@ public: T t0, t1, t2; // This is not ideal, but we need a version of gatherLoadUBySimdIntTranspose that // only loads a single value from memory to implement it better (will be written) + gatherLoadUBySimdIntTranspose( + derivativeMultiTableData_.data() + funcIndex0, tabIndex, &t0, &t2); // works for scalar T too gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + funcIndex0, - tabIndex, &t0, &t2); // works for scalar T too - gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + funcIndex0, - tabIndex + T(1), &t1, + tabIndex + T(1), + &t1, &t2); // works for scalar T too *derivativeValue1 = fma(t1 - t0, eps, t0); + gatherLoadUBySimdIntTranspose( + derivativeMultiTableData_.data() + funcIndex1, tabIndex, &t0, &t2); // works for scalar T too gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + funcIndex1, - tabIndex, &t0, &t2); // works for scalar T too - gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + funcIndex1, - tabIndex + T(1), &t1, + tabIndex + T(1), + &t1, &t2); // works for scalar T too *derivativeValue2 = fma(t1 - t0, eps, t0); + gatherLoadUBySimdIntTranspose( + derivativeMultiTableData_.data() + funcIndex2, tabIndex, &t0, &t2); // works for scalar T too gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + funcIndex2, - tabIndex, &t0, &t2); // works for scalar T too - gatherLoadUBySimdIntTranspose(derivativeMultiTableData_.data() + funcIndex2, - tabIndex + T(1), &t1, + tabIndex + T(1), + &t1, &t2); // works for scalar T too *derivativeValue3 = fma(t1 - t0, eps, t0); } diff --git a/src/gromacs/tables/splineutil.cpp b/src/gromacs/tables/splineutil.cpp index 2f1c704843..71c859b4e3 100644 --- a/src/gromacs/tables/splineutil.cpp +++ b/src/gromacs/tables/splineutil.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2016,2017,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2016,2017,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -145,9 +145,8 @@ void throwUnlessDerivativeIsConsistentWithFunction(ArrayRef } if (!isConsistent) { - GMX_THROW(InconsistentInputError( - formatString("Derivative inconsistent with numerical vector for elements %zu-%zu", - minFail + 1, maxFail + 1))); + GMX_THROW(InconsistentInputError(formatString( + "Derivative inconsistent with numerical vector for elements %zu-%zu", minFail + 1, maxFail + 1))); } } @@ -219,9 +218,9 @@ real findSmallestQuotientOfFunctionAndSecondDerivative(ArrayRef for (std::size_t i = firstIndex + 1; (i + 1) < lastIndex; i++) { - minQuotient = std::min( - minQuotient, quotientOfFunctionAndSecondDerivative(function[i - 1], function[i], - function[i + 1], inputSpacing)); + minQuotient = std::min(minQuotient, + quotientOfFunctionAndSecondDerivative( + function[i - 1], function[i], function[i + 1], inputSpacing)); } return static_cast(minQuotient); } @@ -281,8 +280,8 @@ real findSmallestQuotientOfFunctionAndThirdDerivative(const std::function(minQuotient); } @@ -299,9 +298,10 @@ real findSmallestQuotientOfFunctionAndThirdDerivative(ArrayRef for (std::size_t i = firstIndex + 2; (i + 2) < lastIndex; i++) { - minQuotient = std::min(minQuotient, quotientOfFunctionAndThirdDerivative( - function[i - 2], function[i - 1], function[i], - function[i + 1], function[i + 2], inputSpacing)); + minQuotient = std::min( + minQuotient, + quotientOfFunctionAndThirdDerivative( + function[i - 2], function[i - 1], function[i], function[i + 1], function[i + 2], inputSpacing)); } return static_cast(minQuotient); } diff --git a/src/gromacs/tables/tests/splinetable.cpp b/src/gromacs/tables/tests/splinetable.cpp index 7af4e80c2c..8c8af207e0 100644 --- a/src/gromacs/tables/tests/splinetable.cpp +++ b/src/gromacs/tables/tests/splinetable.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2015,2016,2017,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2015,2016,2017,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -137,8 +137,8 @@ void SplineTableTest::testSplineTableAgainstFunctions(const std::string& real testFuncValue; real testDerValue; - table.template evaluateFunctionAndDerivative(x, &testFuncValue, - &testDerValue); + table.template evaluateFunctionAndDerivative( + x, &testFuncValue, &testDerValue); // Check that we get the same values from function/derivative-only methods real tmpFunc, tmpDer; @@ -443,8 +443,8 @@ TYPED_TEST(SplineTableTest, PmeCorrection) TypeParam pmeCorrTable({ { "PMECorr", pmeCorrFunction, pmeCorrDerivative } }, range, tolerance); TestFixture::setTolerance(tolerance); - TestFixture::testSplineTableAgainstFunctions("PMECorr", pmeCorrFunction, pmeCorrDerivative, - pmeCorrTable, range); + TestFixture::testSplineTableAgainstFunctions( + "PMECorr", pmeCorrFunction, pmeCorrDerivative, pmeCorrTable, range); } @@ -512,12 +512,12 @@ TYPED_TEST(SplineTableTest, NumericalInputPmeCorr) derivativeValues.push_back(pmeCorrDerivative(x)); } - TypeParam pmeCorrTable({ { "NumericalPMECorr", functionValues, derivativeValues, inputSpacing } }, - range, tolerance); + TypeParam pmeCorrTable( + { { "NumericalPMECorr", functionValues, derivativeValues, inputSpacing } }, range, tolerance); TestFixture::setTolerance(tolerance); - TestFixture::testSplineTableAgainstFunctions("NumericalPMECorr", pmeCorrFunction, - pmeCorrDerivative, pmeCorrTable, range); + TestFixture::testSplineTableAgainstFunctions( + "NumericalPMECorr", pmeCorrFunction, pmeCorrDerivative, pmeCorrTable, range); } TYPED_TEST(SplineTableTest, TwoFunctions) @@ -528,10 +528,10 @@ TYPED_TEST(SplineTableTest, TwoFunctions) range); // Test entire range for each function. This will use the method that interpolates a single function - TestFixture::template testSplineTableAgainstFunctions<2, 0>("LJ6", lj6Function, lj6Derivative, - table, range); - TestFixture::template testSplineTableAgainstFunctions<2, 1>("LJ12", lj12Function, - lj12Derivative, table, range); + TestFixture::template testSplineTableAgainstFunctions<2, 0>( + "LJ6", lj6Function, lj6Derivative, table, range); + TestFixture::template testSplineTableAgainstFunctions<2, 1>( + "LJ12", lj12Function, lj12Derivative, table, range); // Test the methods that evaluated both functions for one value real x = 0.5 * (range.first + range.second); @@ -590,12 +590,12 @@ TYPED_TEST(SplineTableTest, ThreeFunctions) range); // Test entire range for each function - TestFixture::template testSplineTableAgainstFunctions<3, 0>("Coulomb", coulombFunction, - coulombDerivative, table, range); - TestFixture::template testSplineTableAgainstFunctions<3, 1>("LJ6", lj6Function, lj6Derivative, - table, range); - TestFixture::template testSplineTableAgainstFunctions<3, 2>("LJ12", lj12Function, - lj12Derivative, table, range); + TestFixture::template testSplineTableAgainstFunctions<3, 0>( + "Coulomb", coulombFunction, coulombDerivative, table, range); + TestFixture::template testSplineTableAgainstFunctions<3, 1>( + "LJ6", lj6Function, lj6Derivative, table, range); + TestFixture::template testSplineTableAgainstFunctions<3, 2>( + "LJ12", lj12Function, lj12Derivative, table, range); // Test the methods that evaluated both functions for one value real x = 0.5 * (range.first + range.second); @@ -653,8 +653,8 @@ TYPED_TEST(SplineTableTest, ThreeFunctions) EXPECT_EQ(tstDer1, tmpDer1); // Test that scrambled order interpolation methods work - table.template evaluateFunctionAndDerivative<3, 2, 1, 0>(x, &tstFunc2, &tstDer2, &tstFunc1, - &tstDer1, &tstFunc0, &tstDer0); + table.template evaluateFunctionAndDerivative<3, 2, 1, 0>( + x, &tstFunc2, &tstDer2, &tstFunc1, &tstDer1, &tstFunc0, &tstDer0); EXPECT_EQ(tstFunc0, tmpFunc0); EXPECT_EQ(tstFunc1, tmpFunc1); EXPECT_EQ(tstFunc2, tmpFunc2); diff --git a/src/gromacs/taskassignment/findallgputasks.cpp b/src/gromacs/taskassignment/findallgputasks.cpp index d1b403362d..24612e648c 100644 --- a/src/gromacs/taskassignment/findallgputasks.cpp +++ b/src/gromacs/taskassignment/findallgputasks.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2017,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2017,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -138,8 +138,7 @@ std::vector allgather(const int& input, int numRanks, MPI_Comm communicator // to compile warning-free with all versions of MPI headers. // // TODO Make an allgather template to deal with this nonsense. - MPI_Gather(const_cast(&input), 1, MPI_INT, const_cast(result.data()), 1, - MPI_INT, root, communicator); + MPI_Gather(const_cast(&input), 1, MPI_INT, const_cast(result.data()), 1, MPI_INT, root, communicator); MPI_Bcast(const_cast(result.data()), result.size(), MPI_INT, root, communicator); #else GMX_UNUSED_VALUE(communicator); @@ -158,8 +157,8 @@ std::vector computeDisplacements(ArrayRef extentOnEachRank, int { std::vector displacements(numRanks + 1); displacements[0] = 0; - std::partial_sum(std::begin(extentOnEachRank), std::end(extentOnEachRank), - std::begin(displacements) + 1); + std::partial_sum( + std::begin(extentOnEachRank), std::end(extentOnEachRank), std::begin(displacements) + 1); return displacements; } @@ -185,9 +184,15 @@ std::vector allgatherv(ArrayRef input, int root = 0; // Calling a C API with the const T * from data() doesn't seem to compile reliably. // TODO Make an allgatherv template to deal with this nonsense. - MPI_Gatherv(const_cast(input.data()), input.size(), MPI_INT, - const_cast(result.data()), const_cast(extentOnEachRank.data()), - const_cast(displacementForEachRank.data()), MPI_INT, root, communicator); + MPI_Gatherv(const_cast(input.data()), + input.size(), + MPI_INT, + const_cast(result.data()), + const_cast(extentOnEachRank.data()), + const_cast(displacementForEachRank.data()), + MPI_INT, + root, + communicator); MPI_Bcast(const_cast(result.data()), result.size(), MPI_INT, root, communicator); #else GMX_UNUSED_VALUE(communicator); @@ -227,8 +232,8 @@ GpuTasksOnRanks findAllGpuTasksOnThisNode(ArrayRef gpuTas * the vector. */ auto displacementsForEachRank = computeDisplacements(numGpuTasksOnEachRankOfThisNode, numRanksOnThisNode); - auto gpuTasksOnThisNode = allgatherv(gpuTasksOnThisRank, numGpuTasksOnEachRankOfThisNode, - displacementsForEachRank, communicator); + auto gpuTasksOnThisNode = allgatherv( + gpuTasksOnThisRank, numGpuTasksOnEachRankOfThisNode, displacementsForEachRank, communicator); /* Next, we re-use the displacements to break up the vector * of GPU tasks into something that can be indexed like @@ -245,8 +250,8 @@ GpuTasksOnRanks findAllGpuTasksOnThisNode(ArrayRef gpuTas do { gpuTasksOnRanksOfThisNode.emplace_back(std::vector()); - for (auto taskOnThisRankIndex = *currentDisplacementIt; - taskOnThisRankIndex != *nextDisplacementIt; ++taskOnThisRankIndex) + for (auto taskOnThisRankIndex = *currentDisplacementIt; taskOnThisRankIndex != *nextDisplacementIt; + ++taskOnThisRankIndex) { gpuTasksOnRanksOfThisNode.back().push_back(gpuTasksOnThisNode[taskOnThisRankIndex]); } diff --git a/src/gromacs/taskassignment/reportgpuusage.cpp b/src/gromacs/taskassignment/reportgpuusage.cpp index bdcde8beb1..a320ae08bd 100644 --- a/src/gromacs/taskassignment/reportgpuusage.cpp +++ b/src/gromacs/taskassignment/reportgpuusage.cpp @@ -131,8 +131,12 @@ void reportGpuUsage(const MDLogger& mdlog, output += gmx::formatString( "%zu GPU%s selected for this run.\n" "Mapping of GPU IDs to the %zu GPU task%s in the %zu rank%s on this node:\n %s\n", - numGpusInUse, bPluralGpus ? "s" : "", numGpuTasksOnThisNode, - (numGpuTasksOnThisNode > 1) ? "s" : "", numRanks, (numRanks > 1) ? "s" : "", + numGpusInUse, + bPluralGpus ? "s" : "", + numGpuTasksOnThisNode, + (numGpuTasksOnThisNode > 1) ? "s" : "", + numRanks, + (numRanks > 1) ? "s" : "", gpuIdsString.c_str()); // Because there is a GPU in use, there must be a PP task on a GPU. output += gmx::formatString( diff --git a/src/gromacs/taskassignment/resourcedivision.cpp b/src/gromacs/taskassignment/resourcedivision.cpp index a967ed1c1b..9312fdc0bb 100644 --- a/src/gromacs/taskassignment/resourcedivision.cpp +++ b/src/gromacs/taskassignment/resourcedivision.cpp @@ -609,7 +609,9 @@ void check_resource_division_efficiency(const gmx_hw_info_t* hwinfo, "threads per rank, which is most likely inefficient. The optimum is usually " "between %d and" " %d threads per rank.", - nth_omp_max, nthreads_omp_mpi_ok_min, nthreads_omp_mpi_target_max); + nth_omp_max, + nthreads_omp_mpi_ok_min, + nthreads_omp_mpi_target_max); if (bNtOmpOptionSet) { @@ -625,7 +627,8 @@ void check_resource_division_efficiency(const gmx_hw_info_t* hwinfo, "%s If you want to run with this setup, specify the -ntomp option. But " "we suggest to " "change the number of MPI ranks%s.", - buf, mpi_option); + buf, + mpi_option); } } } @@ -653,9 +656,14 @@ void check_resource_division_efficiency(const gmx_hw_info_t* hwinfo, //! Dump a \c hw_opt to \c fp. static void print_hw_opt(FILE* fp, const gmx_hw_opt_t* hw_opt) { - fprintf(fp, "hw_opt: nt %d ntmpi %d ntomp %d ntomp_pme %d gpu_id '%s' gputasks '%s'\n", - hw_opt->nthreads_tot, hw_opt->nthreads_tmpi, hw_opt->nthreads_omp, hw_opt->nthreads_omp_pme, - hw_opt->gpuIdsAvailable.c_str(), hw_opt->userGpuTaskAssignment.c_str()); + fprintf(fp, + "hw_opt: nt %d ntmpi %d ntomp %d ntomp_pme %d gpu_id '%s' gputasks '%s'\n", + hw_opt->nthreads_tot, + hw_opt->nthreads_tmpi, + hw_opt->nthreads_omp, + hw_opt->nthreads_omp_pme, + hw_opt->gpuIdsAvailable.c_str(), + hw_opt->userGpuTaskAssignment.c_str()); } void checkAndUpdateHardwareOptions(const gmx::MDLogger& mdlog, @@ -772,7 +780,9 @@ void checkAndUpdateHardwareOptions(const gmx::MDLogger& mdlog, "The total number of threads requested (%d) does not match the thread-MPI " "ranks (%d) " "times the OpenMP threads (%d) requested", - hw_opt->nthreads_tot, hw_opt->nthreads_tmpi, hw_opt->nthreads_omp); + hw_opt->nthreads_tot, + hw_opt->nthreads_tmpi, + hw_opt->nthreads_omp); } if (hw_opt->nthreads_tmpi > 0 && hw_opt->nthreads_tot % hw_opt->nthreads_tmpi != 0) @@ -781,7 +791,8 @@ void checkAndUpdateHardwareOptions(const gmx::MDLogger& mdlog, "The total number of threads requested (%d) is not divisible by the number " "of thread-MPI " "ranks requested (%d)", - hw_opt->nthreads_tot, hw_opt->nthreads_tmpi); + hw_opt->nthreads_tot, + hw_opt->nthreads_tmpi); } if (hw_opt->nthreads_omp > 0 && hw_opt->nthreads_tot % hw_opt->nthreads_omp != 0) @@ -790,7 +801,8 @@ void checkAndUpdateHardwareOptions(const gmx::MDLogger& mdlog, "The total number of threads requested (%d) is not divisible by the number " "of OpenMP " "threads requested (%d)", - hw_opt->nthreads_tot, hw_opt->nthreads_omp); + hw_opt->nthreads_tot, + hw_opt->nthreads_omp); } } @@ -802,7 +814,8 @@ void checkAndUpdateHardwareOptions(const gmx::MDLogger& mdlog, "You requested %d OpenMP threads with %d total threads. Choose a total " "number of threads " "that is a multiple of the number of OpenMP threads.", - hw_opt->nthreads_omp, hw_opt->nthreads_tot); + hw_opt->nthreads_omp, + hw_opt->nthreads_tot); } if (hw_opt->nthreads_tmpi > hw_opt->nthreads_tot) @@ -811,7 +824,8 @@ void checkAndUpdateHardwareOptions(const gmx::MDLogger& mdlog, "You requested %d thread-MPI ranks with %d total threads. Choose a total " "number of " "threads that is a multiple of the number of thread-MPI ranks.", - hw_opt->nthreads_tmpi, hw_opt->nthreads_tot); + hw_opt->nthreads_tmpi, + hw_opt->nthreads_tot); } } diff --git a/src/gromacs/taskassignment/taskassignment.cpp b/src/gromacs/taskassignment/taskassignment.cpp index 2a823e5728..bcfce0e0ec 100644 --- a/src/gromacs/taskassignment/taskassignment.cpp +++ b/src/gromacs/taskassignment/taskassignment.cpp @@ -249,9 +249,15 @@ GpuTaskAssignments GpuTaskAssignmentsBuilder::build(const std::vector& gpuI bool rankHasPmeTask) { size_t numRanksOnThisNode = physicalNodeComm.size_; - std::vector gpuTasksOnThisRank = findGpuTasksOnThisRank( - !gpuIdsToUse.empty(), nonbondedTarget, pmeTarget, bondedTarget, updateTarget, - useGpuForNonbonded, useGpuForPme, rankHasPpTask, rankHasPmeTask); + std::vector gpuTasksOnThisRank = findGpuTasksOnThisRank(!gpuIdsToUse.empty(), + nonbondedTarget, + pmeTarget, + bondedTarget, + updateTarget, + useGpuForNonbonded, + useGpuForPme, + rankHasPpTask, + rankHasPmeTask); /* Communicate among ranks on this node to find each task that can * be executed on a GPU, on each rank. */ auto gpuTasksOnRanksOfThisNode = findAllGpuTasksOnThisNode(gpuTasksOnThisRank, physicalNodeComm); @@ -310,7 +316,9 @@ GpuTaskAssignments GpuTaskAssignmentsBuilder::build(const std::vector& gpuI "You should reconsider your GPU task assignment, " "number of ranks, or your use of the -nb, -pme, and -npme options, " "perhaps after measuring the performance you can get.", - numGpuTasksOnThisNode, host, gpuIdsToUse.size()))); + numGpuTasksOnThisNode, + host, + gpuIdsToUse.size()))); } gpuIdsForTaskAssignment = generatedGpuIds; } @@ -327,7 +335,9 @@ GpuTaskAssignments GpuTaskAssignmentsBuilder::build(const std::vector& gpuI "There were %zu GPU tasks assigned on node %s, but %zu GPU tasks were " "identified, and these must match. Reconsider your GPU task assignment, " "number of ranks, or your use of the -nb, -pme, and -npme options.", - userGpuTaskAssignment.size(), host, numGpuTasksOnThisNode))); + userGpuTaskAssignment.size(), + host, + numGpuTasksOnThisNode))); } // Did the user choose compatible GPUs? checkUserGpuIds(hardwareInfo.deviceInfoList, gpuIdsToUse, userGpuTaskAssignment); @@ -396,8 +406,14 @@ void GpuTaskAssignments::reportGpuUsage(const MDLogger& mdlog, PmeRunMode pmeRunMode, bool useGpuForUpdate) { - gmx::reportGpuUsage(mdlog, assignmentForAllRanksOnThisNode_, numGpuTasksOnThisNode_, - numRanksOnThisNode_, printHostName, useGpuForBonded, pmeRunMode, useGpuForUpdate); + gmx::reportGpuUsage(mdlog, + assignmentForAllRanksOnThisNode_, + numGpuTasksOnThisNode_, + numRanksOnThisNode_, + printHostName, + useGpuForBonded, + pmeRunMode, + useGpuForUpdate); } /*! \brief Function for whether the task of \c mapping has value \c TaskType. @@ -443,8 +459,8 @@ bool GpuTaskAssignments::thisRankHasPmeGpuTask() const { const GpuTaskAssignment& gpuTaskAssignment = assignmentForAllRanksOnThisNode_[indexOfThisRank_]; - auto pmeGpuTaskMapping = std::find_if(gpuTaskAssignment.begin(), gpuTaskAssignment.end(), - hasTaskType); + auto pmeGpuTaskMapping = std::find_if( + gpuTaskAssignment.begin(), gpuTaskAssignment.end(), hasTaskType); const bool thisRankHasPmeGpuTask = (pmeGpuTaskMapping != gpuTaskAssignment.end()); return thisRankHasPmeGpuTask; diff --git a/src/gromacs/taskassignment/usergpuids.cpp b/src/gromacs/taskassignment/usergpuids.cpp index 8271d00913..881d3eea86 100644 --- a/src/gromacs/taskassignment/usergpuids.cpp +++ b/src/gromacs/taskassignment/usergpuids.cpp @@ -222,7 +222,8 @@ void checkUserGpuIds(const std::vector>& devi if (std::find(compatibleGpus.begin(), compatibleGpus.end(), gpuId) == compatibleGpus.end()) { foundIncompatibleGpuIds = true; - message += gmx::formatString(" GPU #%d: %s\n", gpuId, + message += gmx::formatString(" GPU #%d: %s\n", + gpuId, getDeviceCompatibilityDescription(deviceInfoList, gpuId).c_str()); } } diff --git a/src/gromacs/timing/wallcycle.cpp b/src/gromacs/timing/wallcycle.cpp index a80254755c..0692ee8b41 100644 --- a/src/gromacs/timing/wallcycle.cpp +++ b/src/gromacs/timing/wallcycle.cpp @@ -324,13 +324,14 @@ static void debug_stop_check(gmx_wallcycle_t wc, int ewc) if (wc->count_depth < 0) { - gmx_fatal(FARGS, "wallcycle counter depth out of range when stopping %s: %d", wcn[ewc], - wc->count_depth); + gmx_fatal(FARGS, "wallcycle counter depth out of range when stopping %s: %d", wcn[ewc], wc->count_depth); } if (wc->counterlist[wc->count_depth] != ewc) { - gmx_fatal(FARGS, "wallcycle mismatch at stop, start %s, stop %s", - wcn[wc->counterlist[wc->count_depth]], wcn[ewc]); + gmx_fatal(FARGS, + "wallcycle mismatch at stop, start %s, stop %s", + wcn[wc->counterlist[wc->count_depth]], + wcn[ewc]); } } #endif @@ -733,8 +734,15 @@ print_cycles(FILE* fplog, double c2t, const char* name, int nnodes, int nthreads /* Convert the cycle count to wallclock time for this task */ wallt = c_sum * c2t; - fprintf(fplog, " %-19.19s %4s %4s %10s %10.3f %14.3f %5.1f\n", name, nnodes_str, - nthreads_str, ncalls_str, wallt, c_sum * 1e-9, percentage); + fprintf(fplog, + " %-19.19s %4s %4s %10s %10.3f %14.3f %5.1f\n", + name, + nnodes_str, + nthreads_str, + ncalls_str, + wallt, + c_sum * 1e-9, + percentage); } } @@ -914,8 +922,14 @@ void wallcycle_print(FILE* fplog, for (j = 0; j < ewcNR; j++) { snprintf(buf, 20, "%-9.9s %-9.9s", wcn[i], wcn[j]); - print_cycles(fplog, c2t_pp, buf, npp, nth_pp, wc->wcc_all[i * ewcNR + j].n, - wc->wcc_all[i * ewcNR + j].c, tot); + print_cycles(fplog, + c2t_pp, + buf, + npp, + nth_pp, + wc->wcc_all[i * ewcNR + j].n, + wc->wcc_all[i * ewcNR + j].c, + tot); } } } @@ -953,8 +967,14 @@ void wallcycle_print(FILE* fplog, fprintf(fplog, "%s\n", hline); for (auto i : validPmeSubcounterIndices) { - print_cycles(fplog, npme > 0 ? c2t_pme : c2t_pp, wcn[i], npme > 0 ? npme : npp, - nth_pme, wc->wcc[i].n, cyc_sum[i], tot); + print_cycles(fplog, + npme > 0 ? c2t_pme : c2t_pp, + wcn[i], + npme > 0 ? npme : npp, + nth_pme, + wc->wcc[i].n, + cyc_sum[i], + tot); } fprintf(fplog, "%s\n", hline); } @@ -1005,7 +1025,8 @@ void wallcycle_print(FILE* fplog, fprintf(fplog, "\n GPU timings\n%s\n", hline); fprintf(fplog, - " Computing: Count Wall t (s) ms/step %c\n", '%'); + " Computing: Count Wall t (s) ms/step %c\n", + '%'); fprintf(fplog, "%s\n", hline); print_gputimes(fplog, "Pair list H2D", gpu_nbnxn_t->pl_h2d_c, gpu_nbnxn_t->pl_h2d_t, tot_gpu); print_gputimes(fplog, "X / q H2D", gpu_nbnxn_t->nb_c, gpu_nbnxn_t->nb_h2d_t, tot_gpu); @@ -1016,8 +1037,11 @@ void wallcycle_print(FILE* fplog, { if (gpu_nbnxn_t->ktime[i][j].c) { - print_gputimes(fplog, k_log_str[i][j], gpu_nbnxn_t->ktime[i][j].c, - gpu_nbnxn_t->ktime[i][j].t, tot_gpu); + print_gputimes(fplog, + k_log_str[i][j], + gpu_nbnxn_t->ktime[i][j].c, + gpu_nbnxn_t->ktime[i][j].t, + tot_gpu); } } } @@ -1027,15 +1051,14 @@ void wallcycle_print(FILE* fplog, { if (gpu_pme_t->timing[k].c) { - print_gputimes(fplog, PMEStageNames[k], gpu_pme_t->timing[k].c, - gpu_pme_t->timing[k].t, tot_gpu); + print_gputimes( + fplog, PMEStageNames[k], gpu_pme_t->timing[k].c, gpu_pme_t->timing[k].t, tot_gpu); } } } if (gpu_nbnxn_t->pruneTime.c) { - print_gputimes(fplog, "Pruning kernel", gpu_nbnxn_t->pruneTime.c, - gpu_nbnxn_t->pruneTime.t, tot_gpu); + print_gputimes(fplog, "Pruning kernel", gpu_nbnxn_t->pruneTime.c, gpu_nbnxn_t->pruneTime.t, tot_gpu); } print_gputimes(fplog, "F D2H", gpu_nbnxn_t->nb_c, gpu_nbnxn_t->nb_d2h_t, tot_gpu); fprintf(fplog, "%s\n", hline); @@ -1047,8 +1070,11 @@ void wallcycle_print(FILE* fplog, * and avoid adding it to tot_gpu as this is not in the force * overlap. We print the fraction as relative to the rest. */ - print_gputimes(fplog, "*Dynamic pruning", gpu_nbnxn_t->dynamicPruneTime.c, - gpu_nbnxn_t->dynamicPruneTime.t, tot_gpu); + print_gputimes(fplog, + "*Dynamic pruning", + gpu_nbnxn_t->dynamicPruneTime.c, + gpu_nbnxn_t->dynamicPruneTime.t, + tot_gpu); fprintf(fplog, "%s\n", hline); } gpu_cpu_ratio = tot_gpu / tot_cpu_overlap; @@ -1057,7 +1083,9 @@ void wallcycle_print(FILE* fplog, fprintf(fplog, "\nAverage per-step force GPU/CPU evaluation time ratio: %.3f ms/%.3f ms = " "%.3f\n", - tot_gpu / gpu_nbnxn_t->nb_c, tot_cpu_overlap / wc->wcc[ewcFORCE].n, gpu_cpu_ratio); + tot_gpu / gpu_nbnxn_t->nb_c, + tot_cpu_overlap / wc->wcc[ewcFORCE].n, + gpu_cpu_ratio); } /* only print notes related to CPU-GPU load balance with PME */ diff --git a/src/gromacs/tools/check.cpp b/src/gromacs/tools/check.cpp index dc7d16b573..740a7ffff4 100644 --- a/src/gromacs/tools/check.cpp +++ b/src/gromacs/tools/check.cpp @@ -271,8 +271,12 @@ static void chk_bonds(const InteractionDefinitions* idef, PbcType pbcType, rvec* deviation = gmx::square(blen - b0); if (std::sqrt(deviation / gmx::square(b0)) > tol) { - fprintf(stderr, "Distance between atoms %d and %d is %.3f, should be %.3f\n", - ai + 1, aj + 1, blen, b0); + fprintf(stderr, + "Distance between atoms %d and %d is %.3f, should be %.3f\n", + ai + 1, + aj + 1, + blen, + b0); } } } @@ -357,8 +361,12 @@ static void chk_trj(const gmx_output_env_t* oenv, const char* fn, const char* tp > 0.1 * (std::fabs(fr.time - old_t1) + std::fabs(old_t1 - old_t2))) { bShowTimestep = FALSE; - fprintf(stderr, "%sTimesteps at t=%g don't match (%g, %g)\n", newline ? "\n" : "", - old_t1, old_t1 - old_t2, fr.time - old_t1); + fprintf(stderr, + "%sTimesteps at t=%g don't match (%g, %g)\n", + newline ? "\n" : "", + old_t1, + old_t1 - old_t2, + fr.time - old_t1); } } natoms = new_natoms; @@ -494,7 +502,10 @@ static void chk_tps(const char* fn, real vdw_fac, real bon_lo, real bon_hi) "Natoms * %d or Natoms * %d,\n" "the velocities correspond to a temperature of the system\n" "of %g K or %g K respectively.\n\n", - DIM, DIM - 1, temp1, temp2); + DIM, + DIM - 1, + temp1, + temp2); } /* check coordinates */ @@ -507,17 +518,25 @@ static void chk_tps(const char* fn, real vdw_fac, real bon_lo, real bon_hi) fprintf(stderr, "Checking for atoms closer than %g and not between %g and %g,\n" "relative to sum of Van der Waals distance:\n", - vdw_fac, bon_lo, bon_hi); + vdw_fac, + bon_lo, + bon_hi); snew(atom_vdw, natom); AtomProperties aps; for (i = 0; (i < natom); i++) { - aps.setAtomProperty(epropVDW, *(atoms->resinfo[atoms->atom[i].resind].name), - *(atoms->atomname[i]), &(atom_vdw[i])); + aps.setAtomProperty(epropVDW, + *(atoms->resinfo[atoms->atom[i].resind].name), + *(atoms->atomname[i]), + &(atom_vdw[i])); if (debug) { - fprintf(debug, "%5d %4s %4s %7g\n", i + 1, *(atoms->resinfo[atoms->atom[i].resind].name), - *(atoms->atomname[i]), atom_vdw[i]); + fprintf(debug, + "%5d %4s %4s %7g\n", + i + 1, + *(atoms->resinfo[atoms->atom[i].resind].name), + *(atoms->atomname[i]), + atom_vdw[i]); } } if (bB) @@ -549,15 +568,32 @@ static void chk_tps(const char* fn, real vdw_fac, real bon_lo, real bon_hi) { if (bFirst) { - fprintf(stderr, "\r%5s %4s %8s %5s %5s %4s %8s %5s %6s\n", "atom#", "name", - "residue", "r_vdw", "atom#", "name", "residue", "r_vdw", "distance"); + fprintf(stderr, + "\r%5s %4s %8s %5s %5s %4s %8s %5s %6s\n", + "atom#", + "name", + "residue", + "r_vdw", + "atom#", + "name", + "residue", + "r_vdw", + "distance"); bFirst = FALSE; } - fprintf(stderr, "\r%5d %4s %4s%4d %-5.3g %5d %4s %4s%4d %-5.3g %-6.4g\n", i + 1, - *(atoms->atomname[i]), *(atoms->resinfo[atoms->atom[i].resind].name), - atoms->resinfo[atoms->atom[i].resind].nr, atom_vdw[i], j + 1, - *(atoms->atomname[j]), *(atoms->resinfo[atoms->atom[j].resind].name), - atoms->resinfo[atoms->atom[j].resind].nr, atom_vdw[j], std::sqrt(r2)); + fprintf(stderr, + "\r%5d %4s %4s%4d %-5.3g %5d %4s %4s%4d %-5.3g %-6.4g\n", + i + 1, + *(atoms->atomname[i]), + *(atoms->resinfo[atoms->atom[i].resind].name), + atoms->resinfo[atoms->atom[i].resind].nr, + atom_vdw[i], + j + 1, + *(atoms->atomname[j]), + *(atoms->resinfo[atoms->atom[j].resind].name), + atoms->resinfo[atoms->atom[j].resind].nr, + atom_vdw[j], + std::sqrt(r2)); } } } @@ -593,12 +629,20 @@ static void chk_tps(const char* fn, real vdw_fac, real bon_lo, real bon_hi) "):\n" "(These may occur often and are normally not a problem)\n" "%5s %4s %8s %5s %s\n", - "atom#", "name", "residue", "r_vdw", "coordinate"); + "atom#", + "name", + "residue", + "r_vdw", + "coordinate"); bFirst = FALSE; } - fprintf(stderr, "%5d %4s %4s%4d %-5.3g", i, *(atoms->atomname[i]), + fprintf(stderr, + "%5d %4s %4s%4d %-5.3g", + i, + *(atoms->atomname[i]), *(atoms->resinfo[atoms->atom[i].resind].name), - atoms->resinfo[atoms->atom[i].resind].nr, atom_vdw[i]); + atoms->resinfo[atoms->atom[i].resind].nr, + atom_vdw[i]); for (j = 0; (j < DIM); j++) { fprintf(stderr, " %6.3g", x[i][j]); @@ -637,8 +681,12 @@ static void chk_ndx(const char* fn) printf("Nr. Group #Entries First Last\n"); for (i = 0; (i < grps->nr); i++) { - printf("%4d %-20s%8d%8d%8d\n", i, grpname[i], grps->index[i + 1] - grps->index[i], - grps->a[grps->index[i]] + 1, grps->a[grps->index[i + 1] - 1] + 1); + printf("%4d %-20s%8d%8d%8d\n", + i, + grpname[i], + grps->index[i + 1] - grps->index[i], + grps->a[grps->index[i]] + 1, + grps->a[grps->index[i + 1] - 1] + 1); } } for (i = 0; (i < grps->nr); i++) @@ -681,8 +729,7 @@ static void chk_enx(const char* fn) > 0.1 * (fabs(fr->t - old_t1) + std::fabs(old_t1 - old_t2))) { bShowTStep = FALSE; - fprintf(stderr, "\nTimesteps at t=%g don't match (%g, %g)\n", old_t1, - old_t1 - old_t2, fr->t - old_t1); + fprintf(stderr, "\nTimesteps at t=%g don't match (%g, %g)\n", old_t1, old_t1 - old_t2, fr->t - old_t1); } } old_t2 = old_t1; @@ -694,8 +741,7 @@ static void chk_enx(const char* fn) } if (fnr == 0) { - fprintf(stderr, "\rframe: %6s (index %6d), t: %10.3f\n", gmx_step_str(fr->step, buf), - fnr, fr->t); + fprintf(stderr, "\rframe: %6s (index %6d), t: %10.3f\n", gmx_step_str(fr->step, buf), fnr, fr->t); } fnr++; } diff --git a/src/gromacs/tools/convert_tpr.cpp b/src/gromacs/tools/convert_tpr.cpp index fe66b9f588..66922ac5c6 100644 --- a/src/gromacs/tools/convert_tpr.cpp +++ b/src/gromacs/tools/convert_tpr.cpp @@ -73,7 +73,8 @@ static void rangeCheck(int numberInIndexFile, int maxAtomNumber) gmx_fatal(FARGS, "Your index file contains atomnumbers (e.g. %d)\nthat are larger than the number " "of atoms in the tpr file (%d)", - (numberInIndexFile), (maxAtomNumber)); + (numberInIndexFile), + (maxAtomNumber)); } } @@ -127,8 +128,13 @@ static gmx::ListOfLists reduce_listoflists(gmx::ArrayRef inv } } - fprintf(stderr, "Reduced block %8s from %6zu to %6zu index-, %6d to %6d a-entries\n", name, - src.size(), lists.size(), src.numElements(), lists.numElements()); + fprintf(stderr, + "Reduced block %8s from %6zu to %6zu index-, %6d to %6d a-entries\n", + name, + src.size(), + lists.size(), + src.numElements(), + lists.numElements()); return lists; } @@ -215,8 +221,11 @@ static void reduce_ilist(gmx::ArrayRef invindex, ilReduced.push_back(il->iatoms[i], nratoms, newAtoms.data()); } } - fprintf(stderr, "Reduced ilist %8s from %6d to %6d entries\n", name, - il->size() / (nratoms + 1), ilReduced.size() / (nratoms + 1)); + fprintf(stderr, + "Reduced ilist %8s from %6d to %6d entries\n", + name, + il->size() / (nratoms + 1), + ilReduced.size() / (nratoms + 1)); *il = std::move(ilReduced); } @@ -237,7 +246,10 @@ static void reduce_topology_x(int gnx, int index[], gmx_mtop_t* mtop, rvec x[], for (int i = 0; (i < F_NRE); i++) { - reduce_ilist(invindex, bKeep, &(top.idef.il[i]), interaction_function[i].nratoms, + reduce_ilist(invindex, + bKeep, + &(top.idef.il[i]), + interaction_function[i].nratoms, interaction_function[i].name); } @@ -400,23 +412,28 @@ int ConvertTpr::run() { ir->nsteps = ir->nsteps - (currentMaxStep - ir->init_step) + gmx::roundToInt64(extendTime_ / ir->delta_t); - printf("Extending remaining runtime of by %g ps (now %s steps)\n", extendTime_, + printf("Extending remaining runtime of by %g ps (now %s steps)\n", + extendTime_, gmx_step_str(ir->nsteps, buf)); } else if (runToMaxTimeIsSet_) { printf("nsteps = %s, run_step = %s, current_t = %g, until = %g\n", - gmx_step_str(ir->nsteps, buf), gmx_step_str(currentMaxStep, buf2), - currentRunTime, runToMaxTime_); + gmx_step_str(ir->nsteps, buf), + gmx_step_str(currentMaxStep, buf2), + currentRunTime, + runToMaxTime_); ir->nsteps = gmx::roundToInt64((currentMaxRunTime - currentRunTime) / ir->delta_t); - printf("Extending remaining runtime until %g ps (now %s steps)\n", currentMaxRunTime, + printf("Extending remaining runtime until %g ps (now %s steps)\n", + currentMaxRunTime, gmx_step_str(ir->nsteps, buf)); } else { ir->nsteps -= currentMaxStep - ir->init_step; /* Print message */ - printf("%s steps (%g ps) remaining from first run.\n", gmx_step_str(ir->nsteps, buf), + printf("%s steps (%g ps) remaining from first run.\n", + gmx_step_str(ir->nsteps, buf), ir->nsteps * ir->delta_t); } } @@ -450,7 +467,8 @@ int ConvertTpr::run() fprintf(stderr, "Will write subset %s of original tpx containing %d " "atoms\n", - grpname, gnx); + grpname, + gnx); reduce_topology_x(gnx, index, &mtop, state.x.rvec_array(), state.v.rvec_array()); state.natoms = gnx; } @@ -466,11 +484,17 @@ int ConvertTpr::run() } double stateTime = ir->init_t + ir->init_step * ir->delta_t; - sprintf(buf, "Writing statusfile with starting step %s%s and length %s%s steps...\n", "%10", - PRId64, "%10", PRId64); + sprintf(buf, + "Writing statusfile with starting step %s%s and length %s%s steps...\n", + "%10", + PRId64, + "%10", + PRId64); fprintf(stderr, buf, ir->init_step, ir->nsteps); - fprintf(stderr, " time %10.3f and length %10.3f ps\n", - stateTime, ir->nsteps * ir->delta_t); + fprintf(stderr, + " time %10.3f and length %10.3f ps\n", + stateTime, + ir->nsteps * ir->delta_t); write_tpx_state(outputTprFileName_.c_str(), ir, &state, &mtop); } else diff --git a/src/gromacs/tools/dump.cpp b/src/gromacs/tools/dump.cpp index 9f004bc9fa..a945fec149 100644 --- a/src/gromacs/tools/dump.cpp +++ b/src/gromacs/tools/dump.cpp @@ -242,16 +242,23 @@ void list_trr(const char* fn) snew(x, trrheader.natoms); snew(v, trrheader.natoms); snew(f, trrheader.natoms); - if (gmx_trr_read_frame_data(fpread, &trrheader, trrheader.box_size ? box : nullptr, - trrheader.x_size ? x : nullptr, trrheader.v_size ? v : nullptr, + if (gmx_trr_read_frame_data(fpread, + &trrheader, + trrheader.box_size ? box : nullptr, + trrheader.x_size ? x : nullptr, + trrheader.v_size ? v : nullptr, trrheader.f_size ? f : nullptr)) { sprintf(buf, "%s frame %d", fn, nframe); indent = 0; indent = pr_title(stdout, indent, buf); pr_indent(stdout, indent); - fprintf(stdout, "natoms=%10d step=%10" PRId64 " time=%12.7e lambda=%10g\n", - trrheader.natoms, trrheader.step, trrheader.t, trrheader.lambda); + fprintf(stdout, + "natoms=%10d step=%10" PRId64 " time=%12.7e lambda=%10g\n", + trrheader.natoms, + trrheader.step, + trrheader.t, + trrheader.lambda); if (trrheader.box_size) { pr_rvecs(stdout, indent, "box", box, DIM); @@ -309,8 +316,7 @@ void list_xtc(const char* fn) indent = 0; indent = pr_title(stdout, indent, buf); pr_indent(stdout, indent); - fprintf(stdout, "natoms=%10d step=%10" PRId64 " time=%12.7e prec=%10g\n", natoms, step, - time, prec); + fprintf(stdout, "natoms=%10d step=%10" PRId64 " time=%12.7e prec=%10g\n", natoms, step, time, prec); pr_rvecs(stdout, indent, "box", box, DIM); pr_rvecs(stdout, indent, "x", x, natoms); nframe++; @@ -381,25 +387,32 @@ void list_tng(const char* fn) int64_t n_values_per_frame, n_atoms; char block_name[STRLEN]; - gmx_get_tng_data_next_frame_of_block_type(tng, block_ids[i], &values, &step, - &frame_time, &n_values_per_frame, &n_atoms, - &prec, block_name, STRLEN, &bOK); + gmx_get_tng_data_next_frame_of_block_type(tng, + block_ids[i], + &values, + &step, + &frame_time, + &n_values_per_frame, + &n_atoms, + &prec, + block_name, + STRLEN, + &bOK); if (!bOK) { /* Can't write any output because we don't know what arrays are valid. */ - fprintf(stderr, "\nWARNING: Incomplete frame at time %g, will not write output\n", - frame_time); + fprintf(stderr, "\nWARNING: Incomplete frame at time %g, will not write output\n", frame_time); } else { - list_tng_inner(fn, (0 == i), values, step, frame_time, n_values_per_frame, n_atoms, - prec, nframe, block_name); + list_tng_inner( + fn, (0 == i), values, step, frame_time, n_values_per_frame, n_atoms, prec, nframe, block_name); } } nframe++; - } while (gmx_get_tng_data_block_types_of_next_frame(tng, step, 0, nullptr, &step, &ndatablocks, - &block_ids)); + } while (gmx_get_tng_data_block_types_of_next_frame( + tng, step, 0, nullptr, &step, &ndatablocks, &block_ids)); if (block_ids) { @@ -421,8 +434,7 @@ void list_trx(const char* fn) case efTRR: list_trr(fn); break; case efTNG: list_tng(fn); break; default: - fprintf(stderr, "File %s is of an unsupported type. Try using the command\n 'less %s'\n", - fn, fn); + fprintf(stderr, "File %s is of an unsupported type. Try using the command\n 'less %s'\n", fn, fn); } } @@ -456,18 +468,23 @@ void list_ene(const char* fn) { printf("\n%24s %12.5e %12s %12s\n", "time:", fr->t, "step:", gmx_step_str(fr->step, buf)); printf("%24s %12s %12s %12s\n", "", "", "nsteps:", gmx_step_str(fr->nsteps, buf)); - printf("%24s %12.5e %12s %12s\n", "delta_t:", fr->dt, - "sum steps:", gmx_step_str(fr->nsum, buf)); + printf("%24s %12.5e %12s %12s\n", "delta_t:", fr->dt, "sum steps:", gmx_step_str(fr->nsum, buf)); if (fr->nre == nre) { - printf("%24s %12s %12s %12s\n", "Component", "Energy", "Av. Energy", + printf("%24s %12s %12s %12s\n", + "Component", + "Energy", + "Av. Energy", "Sum Energy"); if (fr->nsum > 0) { for (i = 0; (i < nre); i++) { - printf("%24s %12.5e %12.5e %12.5e\n", enm[i].name, fr->ener[i].e, - fr->ener[i].eav, fr->ener[i].esum); + printf("%24s %12.5e %12.5e %12.5e\n", + enm[i].name, + fr->ener[i].e, + fr->ener[i].eav, + fr->ener[i].esum); } } else @@ -493,7 +510,9 @@ void list_ene(const char* fn) for (i = 0; i < eb->nsub; i++) { t_enxsubblock* sb = &(eb->sub[i]); - printf(" Sub block %3d (%5d elems, type=%s) values:\n", i, sb->nr, + printf(" Sub block %3d (%5d elems, type=%s) values:\n", + i, + sb->nr, xdr_datatype_names[sb->type]); switch (sb->type) @@ -686,8 +705,11 @@ int Dump::run() { if (!inputTprFilename_.empty()) { - list_tpr(inputTprFilename_.c_str(), bShowNumbers_, bShowParams_, - outputMdpFilename_.empty() ? nullptr : outputMdpFilename_.c_str(), bSysTop_, + list_tpr(inputTprFilename_.c_str(), + bShowNumbers_, + bShowParams_, + outputMdpFilename_.empty() ? nullptr : outputMdpFilename_.c_str(), + bSysTop_, bOriginalInputrec_); } else if (!inputTrajectoryFilename_.empty()) diff --git a/src/gromacs/tools/eneconv.cpp b/src/gromacs/tools/eneconv.cpp index f918abed80..eabfffaabe 100644 --- a/src/gromacs/tools/eneconv.cpp +++ b/src/gromacs/tools/eneconv.cpp @@ -187,7 +187,10 @@ static int scan_ene_files(const std::vector& files, real* readtime, fprintf(stderr, "Energy files don't match, different number of energies:\n" " %s: %d\n %s: %d\n", - files[f - 1].c_str(), nresav, files[f].c_str(), fr->nre); + files[f - 1].c_str(), + nresav, + files[f].c_str(), + fr->nre); fprintf(stderr, "\nContinue conversion using only the first %d terms (n/y)?\n" "(you should be sure that the energy terms match)\n", @@ -500,8 +503,8 @@ int gmx_eneconv(int argc, char* argv[]) { "-error", FALSE, etBOOL, { &bError }, "Stop on errors in the file" } }; - if (!parse_common_args(&argc, argv, 0, NFILE, fnm, asize(pa), pa, asize(desc), desc, - asize(bugs), bugs, &oenv)) + if (!parse_common_args( + &argc, argv, 0, NFILE, fnm, asize(pa), pa, asize(desc), desc, asize(bugs), bugs, &oenv)) { return 0; } @@ -598,8 +601,12 @@ int gmx_eneconv(int argc, char* argv[]) if (debug) { - fprintf(debug, "fr->step %s, fr->t %.4f, fro->step %s fro->t %.4f, w %s\n", - gmx_step_str(fr->step, buf), fr->t, gmx_step_str(fro->step, buf2), fro->t, + fprintf(debug, + "fr->step %s, fr->t %.4f, fro->step %s fro->t %.4f, w %s\n", + gmx_step_str(fr->step, buf), + fr->t, + gmx_step_str(fro->step, buf2), + fro->t, gmx::boolToString(bWrite)); } @@ -632,7 +639,9 @@ int gmx_eneconv(int argc, char* argv[]) if (bNewOutput) { bNewOutput = FALSE; - fprintf(stderr, "\nContinue writing frames from t=%g, step=%s\n", fro->t, + fprintf(stderr, + "\nContinue writing frames from t=%g, step=%s\n", + fro->t, gmx_step_str(fro->step, buf)); } @@ -742,7 +751,8 @@ int gmx_eneconv(int argc, char* argv[]) "samples away.\n" " Use g_energy -odh option to extract these " "samples.\n", - files[f].c_str(), size); + files[f].c_str(), + size); warned_about_dh = TRUE; break; } @@ -764,7 +774,9 @@ int gmx_eneconv(int argc, char* argv[]) { f--; } - printf("\nLast step written from %s: t %g, step %s\n", files[f].c_str(), last_t, + printf("\nLast step written from %s: t %g, step %s\n", + files[f].c_str(), + last_t, gmx_step_str(laststep, buf)); lastfilestep = laststep; @@ -797,8 +809,7 @@ int gmx_eneconv(int argc, char* argv[]) } else { - fprintf(stderr, "Last frame written was at step %s, time %f\n", - gmx_step_str(fro->step, buf), fro->t); + fprintf(stderr, "Last frame written was at step %s, time %f\n", gmx_step_str(fro->step, buf), fro->t); fprintf(stderr, "Wrote %d frames\n", noutfr); } diff --git a/src/gromacs/tools/mk_angndx.cpp b/src/gromacs/tools/mk_angndx.cpp index ad7a15459c..a2198abef7 100644 --- a/src/gromacs/tools/mk_angndx.cpp +++ b/src/gromacs/tools/mk_angndx.cpp @@ -89,31 +89,47 @@ static void fill_ft_ind(int nft, const int* ft, const t_idef* idef, int ft_ind[] switch (ftype) { case F_ANGLES: - sprintf(buf, "Theta=%.1f_%.2f", idef->iparams[i].harmonic.rA, + sprintf(buf, + "Theta=%.1f_%.2f", + idef->iparams[i].harmonic.rA, idef->iparams[i].harmonic.krA); break; case F_G96ANGLES: - sprintf(buf, "Cos_th=%.1f_%.2f", idef->iparams[i].harmonic.rA, + sprintf(buf, + "Cos_th=%.1f_%.2f", + idef->iparams[i].harmonic.rA, idef->iparams[i].harmonic.krA); break; case F_UREY_BRADLEY: - sprintf(buf, "UB_th=%.1f_%.2f2f", idef->iparams[i].u_b.thetaA, + sprintf(buf, + "UB_th=%.1f_%.2f2f", + idef->iparams[i].u_b.thetaA, idef->iparams[i].u_b.kthetaA); break; case F_QUARTIC_ANGLES: - sprintf(buf, "Q_th=%.1f_%.2f_%.2f", idef->iparams[i].qangle.theta, - idef->iparams[i].qangle.c[0], idef->iparams[i].qangle.c[1]); + sprintf(buf, + "Q_th=%.1f_%.2f_%.2f", + idef->iparams[i].qangle.theta, + idef->iparams[i].qangle.c[0], + idef->iparams[i].qangle.c[1]); break; case F_TABANGLES: - sprintf(buf, "Table=%d_%.2f", idef->iparams[i].tab.table, + sprintf(buf, + "Table=%d_%.2f", + idef->iparams[i].tab.table, idef->iparams[i].tab.kA); break; case F_PDIHS: - sprintf(buf, "Phi=%.1f_%d_%.2f", idef->iparams[i].pdihs.phiA, - idef->iparams[i].pdihs.mult, idef->iparams[i].pdihs.cpA); + sprintf(buf, + "Phi=%.1f_%d_%.2f", + idef->iparams[i].pdihs.phiA, + idef->iparams[i].pdihs.mult, + idef->iparams[i].pdihs.cpA); break; case F_IDIHS: - sprintf(buf, "Xi=%.1f_%.2f", idef->iparams[i].harmonic.rA, + sprintf(buf, + "Xi=%.1f_%.2f", + idef->iparams[i].harmonic.rA, idef->iparams[i].harmonic.krA); break; case F_RBDIHS: @@ -122,7 +138,9 @@ static void fill_ft_ind(int nft, const int* ft, const t_idef* idef, int ft_ind[] case F_RESTRANGLES: // Fall through intended case F_RESTRDIHS: - sprintf(buf, "Theta=%.1f_%.2f", idef->iparams[i].harmonic.rA, + sprintf(buf, + "Theta=%.1f_%.2f", + idef->iparams[i].harmonic.rA, idef->iparams[i].harmonic.krA); break; case F_CBTDIHS: @@ -130,7 +148,8 @@ static void fill_ft_ind(int nft, const int* ft, const t_idef* idef, int ft_ind[] break; default: - gmx_fatal(FARGS, "Unsupported function type '%s' selected", + gmx_fatal(FARGS, + "Unsupported function type '%s' selected", interaction_function[ftype].longname); } grpnames[ind] = gmx_strdup(buf); diff --git a/src/gromacs/tools/pme_error.cpp b/src/gromacs/tools/pme_error.cpp index ba1fb3b142..51bebada58 100644 --- a/src/gromacs/tools/pme_error.cpp +++ b/src/gromacs/tools/pme_error.cpp @@ -153,7 +153,13 @@ static void calc_q2all(const gmx_mtop_t* mtop, /* molecular topology */ fprintf(stderr, "Molecule %2d (%5d atoms) q2_mol=%10.3e nr.mol.charges=%5d (%6dx) q2_all=%10.3e " "tot.charges=%d\n", - imol, molecule.atoms.nr, q2_mol, nrq_mol, molblock.nmol, q2_all, nrq_all); + imol, + molecule.atoms.nr, + q2_mol, + nrq_mol, + molblock.nmol, + q2_all, + nrq_all); #endif } @@ -599,7 +605,8 @@ static real estimate_reciprocal(t_inputinfo* info, } if (MASTER(cr)) { - fprintf(stderr, "\rCalculating reciprocal error part 1 ... %3.0f%%", + fprintf(stderr, + "\rCalculating reciprocal error part 1 ... %3.0f%%", 100.0 * (nx - startlocal + 1) / (x_per_core)); fflush(stderr); } @@ -652,8 +659,10 @@ static real estimate_reciprocal(t_inputinfo* info, if (bVerbose && MASTER(cr)) { - fprintf(stdout, "Using %d sample%s to approximate the self interaction error term", - xtot, xtot == 1 ? "" : "s"); + fprintf(stdout, + "Using %d sample%s to approximate the self interaction error term", + xtot, + xtot == 1 ? "" : "s"); if (PAR(cr)) { fprintf(stdout, " (%d sample%s per rank)", x_per_core, x_per_core == 1 ? "" : "s"); @@ -944,8 +953,7 @@ static void estimate_PME_error(t_inputinfo* info, fprintf(fp_out, "Ewald_rtol : %g\n", info->ewald_rtol[0]); fprintf(fp_out, "Ewald parameter beta : %g\n", info->ewald_beta[0]); fprintf(fp_out, "Interpolation order : %d\n", info->pme_order[0]); - fprintf(fp_out, "Fourier grid (nx,ny,nz) : %d x %d x %d\n", info->nkx[0], info->nky[0], - info->nkz[0]); + fprintf(fp_out, "Fourier grid (nx,ny,nz) : %d x %d x %d\n", info->nkx[0], info->nky[0], info->nkz[0]); fflush(fp_out); } @@ -1033,7 +1041,9 @@ static void estimate_PME_error(t_inputinfo* info, if (MASTER(cr)) { i++; - fprintf(stderr, "difference between real and rec. space error (step %d): %g\n", i, + fprintf(stderr, + "difference between real and rec. space error (step %d): %g\n", + i, std::abs(derr)); fprintf(stderr, "old beta: %f\n", beta0); fprintf(stderr, "new beta: %f\n", beta); @@ -1125,8 +1135,8 @@ int gmx_pme_error(int argc, char* argv[]) t_commrec* cr = commrecHandle.get(); PCA_Flags = PCA_NOEXIT_ON_ARGS; - if (!parse_common_args(&argc, argv, PCA_Flags, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, - nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_Flags, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -1163,14 +1173,25 @@ int gmx_pme_error(int argc, char* argv[]) info.nkx[0] = 0; info.nky[0] = 0; info.nkz[0] = 0; - calcFftGrid(stdout, state.box, info.fourier_sp[0], minimalPmeGridSize(info.pme_order[0]), - &(info.nkx[0]), &(info.nky[0]), &(info.nkz[0])); + calcFftGrid(stdout, + state.box, + info.fourier_sp[0], + minimalPmeGridSize(info.pme_order[0]), + &(info.nkx[0]), + &(info.nky[0]), + &(info.nkz[0])); if ((ir.nkx != info.nkx[0]) || (ir.nky != info.nky[0]) || (ir.nkz != info.nkz[0])) { gmx_fatal(FARGS, "Wrong fourierspacing %f nm, input file grid = %d x %d x %d, computed grid = " "%d x %d x %d", - fs, ir.nkx, ir.nky, ir.nkz, info.nkx[0], info.nky[0], info.nkz[0]); + fs, + ir.nkx, + ir.nky, + ir.nkz, + info.nkx[0], + info.nky[0], + info.nkz[0]); } } diff --git a/src/gromacs/tools/report_methods.cpp b/src/gromacs/tools/report_methods.cpp index 4074465931..f7889056b1 100644 --- a/src/gromacs/tools/report_methods.cpp +++ b/src/gromacs/tools/report_methods.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2018,2019, by the GROMACS development team, led by + * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -86,7 +86,8 @@ void writeSystemInformation(TextWriter* writer, const gmx_mtop_t& top, bool writ } { writer->writeLine(formatString("A system of %d molecules (%d atoms) was simulated.", - gmx_mtop_num_molecules(top), top.natoms - nvsite)); + gmx_mtop_num_molecules(top), + top.natoms - nvsite)); } if (nvsite) { @@ -99,7 +100,8 @@ void writeParameterInformation(TextWriter* writer, const t_inputrec& ir, bool wr { writeHeader(writer, "Simulation settings", "subsection", writeFormattedText); writer->writeLine(formatString("A total of %g ns were simulated with a time step of %g fs.", - ir.nsteps * ir.delta_t * 0.001, 1000 * ir.delta_t)); + ir.nsteps * ir.delta_t * 0.001, + 1000 * ir.delta_t)); writer->writeLine(formatString("Neighbor searching was performed every %d steps.", ir.nstlist)); writer->writeLine(formatString("The %s algorithm was used for electrostatic interactions.", EELTYPE(ir.coulombtype))); @@ -109,7 +111,10 @@ void writeParameterInformation(TextWriter* writer, const t_inputrec& ir, bool wr writer->writeLine( formatString("A reciprocal grid of %d x %d x %d cells was used with %dth order " "B-spline interpolation.", - ir.nkx, ir.nky, ir.nkz, ir.pme_order)); + ir.nkx, + ir.nky, + ir.nkz, + ir.pme_order)); } writer->writeLine(formatString( "A single cut-off of %g nm was used for Van der Waals interactions.", ir.rlist)); diff --git a/src/gromacs/tools/tests/dump.cpp b/src/gromacs/tools/tests/dump.cpp index 8e61b543c6..f179796764 100644 --- a/src/gromacs/tools/tests/dump.cpp +++ b/src/gromacs/tools/tests/dump.cpp @@ -91,11 +91,10 @@ TEST_F(DumpTest, WorksWithTpr) TEST_F(DumpTest, WorksWithTprAndMdpWriting) { - TestFileManager fileManager; - std::string mdpName = fileManager.getTemporaryFilePath("output.mdp"); - const char* const command[] = { "dump", "-s", s_tprFileHandle->tprName().c_str(), "-om", - mdpName.c_str() }; - CommandLine cmdline(command); + TestFileManager fileManager; + std::string mdpName = fileManager.getTemporaryFilePath("output.mdp"); + const char* const command[] = { "dump", "-s", s_tprFileHandle->tprName().c_str(), "-om", mdpName.c_str() }; + CommandLine cmdline(command); runTest(&cmdline); } diff --git a/src/gromacs/tools/tests/report_methods.cpp b/src/gromacs/tools/tests/report_methods.cpp index 1283cb1865..5de42bdc72 100644 --- a/src/gromacs/tools/tests/report_methods.cpp +++ b/src/gromacs/tools/tests/report_methods.cpp @@ -176,8 +176,7 @@ TEST_F(ReportMethodsTest, ToolEndToEndTest) { const char* const command[] = { "report-methods", "-s", s_tprFileHandle->tprName().c_str() }; CommandLine cmdline(command); - EXPECT_EQ(0, gmx::test::CommandLineTestHelper::runModuleFactory(&gmx::ReportMethodsInfo::create, - &cmdline)); + EXPECT_EQ(0, gmx::test::CommandLineTestHelper::runModuleFactory(&gmx::ReportMethodsInfo::create, &cmdline)); } } // namespace test diff --git a/src/gromacs/tools/trjcat.cpp b/src/gromacs/tools/trjcat.cpp index b2377eafd6..a44057b880 100644 --- a/src/gromacs/tools/trjcat.cpp +++ b/src/gromacs/tools/trjcat.cpp @@ -203,12 +203,16 @@ static void edit_files(gmx::ArrayRef files, fprintf(stderr, " File Current start (%s) New start (%s)\n" "---------------------------------------------------------\n", - timeUnit.c_str(), timeUnit.c_str()); + timeUnit.c_str(), + timeUnit.c_str()); for (gmx::index i = 0; i < files.ssize(); i++) { - fprintf(stderr, "%25s %10.3f %s ", files[i].c_str(), - output_env_conv_time(oenv, readtime[i]), timeUnit.c_str()); + fprintf(stderr, + "%25s %10.3f %s ", + files[i].c_str(), + output_env_conv_time(oenv, readtime[i]), + timeUnit.c_str()); ok = FALSE; do { @@ -282,9 +286,13 @@ static void edit_files(gmx::ArrayRef files, switch (cont_type[i]) { case TIME_EXPLICIT: - fprintf(stderr, "%25s %10.3f %s %10.3f %s", files[i].c_str(), - output_env_conv_time(oenv, settime[i]), timeUnit.c_str(), - output_env_conv_time(oenv, timestep[i]), timeUnit.c_str()); + fprintf(stderr, + "%25s %10.3f %s %10.3f %s", + files[i].c_str(), + output_env_conv_time(oenv, settime[i]), + timeUnit.c_str(), + output_env_conv_time(oenv, timestep[i]), + timeUnit.c_str()); if (i > 0 && cont_type[i - 1] == TIME_EXPLICIT && settime[i] == settime[i - 1]) { fprintf(stderr, " WARNING: same Start time as previous"); @@ -338,8 +346,11 @@ static void do_demux(gmx::ArrayRef inFiles, } else if (natoms != trx[i].natoms) { - gmx_fatal(FARGS, "Trajectory file %s has %d atoms while previous trajs had %d atoms", - inFiles[i].c_str(), trx[i].natoms, natoms); + gmx_fatal(FARGS, + "Trajectory file %s has %d atoms while previous trajs had %d atoms", + inFiles[i].c_str(), + trx[i].natoms, + natoms); } if (t == -1) { @@ -347,8 +358,11 @@ static void do_demux(gmx::ArrayRef inFiles, } else if (t != trx[i].time) { - gmx_fatal(FARGS, "Trajectory file %s has time %f while previous trajs had time %f", - inFiles[i].c_str(), trx[i].time, t); + gmx_fatal(FARGS, + "Trajectory file %s has time %f while previous trajs had time %f", + inFiles[i].c_str(), + trx[i].time, + t); } } @@ -497,8 +511,8 @@ int gmx_trjcat(int argc, char* argv[]) #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_TIME_UNIT, NFILE, fnm, asize(pa), pa, asize(desc), desc, - 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_TIME_UNIT, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -528,8 +542,17 @@ int gmx_trjcat(int argc, char* argv[]) { nset = 0; dt_remd = 0; - val = read_xvg_time(opt2fn("-demux", NFILE, fnm), TRUE, opt2parg_bSet("-b", npargs, pa), - begin, opt2parg_bSet("-e", npargs, pa), end, 1, &nset, &n, &dt_remd, &t); + val = read_xvg_time(opt2fn("-demux", NFILE, fnm), + TRUE, + opt2parg_bSet("-b", npargs, pa), + begin, + opt2parg_bSet("-e", npargs, pa), + end, + 1, + &nset, + &n, + &dt_remd, + &t); printf("Read %d sets of %d points, dt = %g\n\n", nset, n, dt_remd); if (debug) { @@ -554,8 +577,7 @@ int gmx_trjcat(int argc, char* argv[]) if (bDeMux && ssize(inFiles) != nset) { - gmx_fatal(FARGS, "You have specified %td files and %d entries in the demux table", - inFiles.ssize(), nset); + gmx_fatal(FARGS, "You have specified %td files and %d entries in the demux table", inFiles.ssize(), nset); } ftpin = fn2ftp(inFiles[0].c_str()); @@ -585,7 +607,9 @@ int gmx_trjcat(int argc, char* argv[]) } else if (bDeMux && ssize(outFiles) != nset && outFiles.size() != 1) { - gmx_fatal(FARGS, "Number of output files should be 1 or %d (#input files), not %td", nset, + gmx_fatal(FARGS, + "Number of output files should be 1 or %d (#input files), not %td", + nset, outFiles.ssize()); } if (bDeMux) @@ -632,8 +656,10 @@ int gmx_trjcat(int argc, char* argv[]) } else if (n_append != -1) { - gmx_fatal(FARGS, "Can only append to the first file which is %s (not %s)", - inFilesEdited[0].c_str(), out_file); + gmx_fatal(FARGS, + "Can only append to the first file which is %s (not %s)", + inFilesEdited[0].c_str(), + out_file); } /* Not checking input format, could be dangerous :-) */ @@ -656,9 +682,14 @@ int gmx_trjcat(int argc, char* argv[]) } if (bIndex) { - trxout = trjtools_gmx_prepare_tng_writing( - out_file, 'w', nullptr, inFilesEdited[0].c_str(), isize, nullptr, - gmx::arrayRefFromArray(index, isize), grpname); + trxout = trjtools_gmx_prepare_tng_writing(out_file, + 'w', + nullptr, + inFilesEdited[0].c_str(), + isize, + nullptr, + gmx::arrayRefFromArray(index, isize), + grpname); } else { @@ -736,8 +767,7 @@ int gmx_trjcat(int argc, char* argv[]) read_next_frame(oenv, status, &fr); if (std::abs(searchtime - fr.time) > timest[0] * 0.5) { - gmx_fatal(FARGS, "Error seeking: attempted to seek to %f but got %f.", - searchtime, fr.time); + gmx_fatal(FARGS, "Error seeking: attempted to seek to %f but got %f.", searchtime, fr.time); } lasttime = fr.time; lastTimeSet = TRUE; @@ -803,7 +833,8 @@ int gmx_trjcat(int argc, char* argv[]) "spacing than the rest,\n" "might be a gap or overlap that couldn't be corrected " "automatically.\n", - output_env_conv_time(oenv, frout.time), timeUnit.c_str()); + output_env_conv_time(oenv, frout.time), + timeUnit.c_str()); } } } @@ -895,7 +926,9 @@ int gmx_trjcat(int argc, char* argv[]) "\nContinue writing frames from %s t=%g %s, " "frame=%d \n", inFilesEdited[i].c_str(), - output_env_conv_time(oenv, frout.time), timeUnit.c_str(), frame); + output_env_conv_time(oenv, frout.time), + timeUnit.c_str(), + frame); bNewFile = FALSE; } @@ -909,8 +942,11 @@ int gmx_trjcat(int argc, char* argv[]) } if (((frame % 10) == 0) || (frame < 10)) { - fprintf(stderr, " -> frame %6d time %8.3f %s \r", frame_out, - output_env_conv_time(oenv, frout.time), timeUnit.c_str()); + fprintf(stderr, + " -> frame %6d time %8.3f %s \r", + frame_out, + output_env_conv_time(oenv, frout.time), + timeUnit.c_str()); fflush(stderr); } } @@ -923,8 +959,11 @@ int gmx_trjcat(int argc, char* argv[]) { close_trx(trxout); } - fprintf(stderr, "\nLast frame written was %d, time %f %s\n", frame, - output_env_conv_time(oenv, last_ok_t), timeUnit.c_str()); + fprintf(stderr, + "\nLast frame written was %d, time %f %s\n", + frame, + output_env_conv_time(oenv, last_ok_t), + timeUnit.c_str()); } return 0; diff --git a/src/gromacs/tools/trjconv.cpp b/src/gromacs/tools/trjconv.cpp index 43274a7522..67eb02938a 100644 --- a/src/gromacs/tools/trjconv.cpp +++ b/src/gromacs/tools/trjconv.cpp @@ -152,7 +152,10 @@ static void do_trunc(const char* fn, real t0) fprintf(stderr, "Do you REALLY want to truncate this trajectory (%s) at:\n" "frame %d, time %g, bytes %ld ??? (type YES if so)\n", - fn, j, t, static_cast(fpos)); + fn, + j, + t, + static_cast(fpos)); if (1 != scanf("%s", yesno)) { gmx_fatal(FARGS, "Error reading user input"); @@ -521,8 +524,18 @@ int gmx_trjconv(int argc, char* argv[]) { efXVG, "-drop", "drop", ffOPTRD } }; #define NFILE asize(fnm) - if (!parse_common_args(&argc, argv, PCA_CAN_BEGIN | PCA_CAN_END | PCA_CAN_VIEW | PCA_TIME_UNIT, - NFILE, fnm, NPA, pa, asize(desc), desc, 0, nullptr, &oenv)) + if (!parse_common_args(&argc, + argv, + PCA_CAN_BEGIN | PCA_CAN_END | PCA_CAN_VIEW | PCA_TIME_UNIT, + NFILE, + fnm, + NPA, + pa, + asize(desc), + desc, + 0, + nullptr, + &oenv)) { return 0; } @@ -594,7 +607,10 @@ int gmx_trjconv(int argc, char* argv[]) "WARNING: Option for unitcell representation (-ur %s)\n" " only has effect in combination with -pbc %s, %s or %s.\n" " Ingoring unitcell representation.\n\n", - unitcell_opt[0], pbc_opt[2], pbc_opt[3], pbc_opt[4]); + unitcell_opt[0], + pbc_opt[2], + pbc_opt[3], + pbc_opt[4]); } } if (bFit && bPBC) @@ -676,8 +692,7 @@ int gmx_trjconv(int argc, char* argv[]) if (0 == top->mols.nr && (bCluster || bPBCcomMol)) { - gmx_fatal(FARGS, "Option -pbc %s requires a .tpr file for the -s option", - pbc_opt[pbc_enum]); + gmx_fatal(FARGS, "Option -pbc %s requires a .tpr file for the -s option", pbc_opt[pbc_enum]); } /* top_title is only used for gro and pdb, @@ -922,7 +937,9 @@ int gmx_trjconv(int argc, char* argv[]) "Index[%d] %d is larger than the number of atoms in the\n" "trajectory file (%d). There is a mismatch in the contents\n" "of your -f, -s and/or -n files.", - i, index[i] + 1, natoms); + i, + index[i] + 1, + natoms); } bCopy = bCopy || (i != index[i]); } @@ -933,9 +950,14 @@ int gmx_trjconv(int argc, char* argv[]) switch (ftp) { case efTNG: - trxout = trjtools_gmx_prepare_tng_writing( - out_file, filemode[0], trxin, nullptr, nout, mtop.get(), - gmx::arrayRefFromArray(index, nout), grpnm); + trxout = trjtools_gmx_prepare_tng_writing(out_file, + filemode[0], + trxin, + nullptr, + nout, + mtop.get(), + gmx::arrayRefFromArray(index, nout), + grpnm); break; case efXTC: case efTRR: @@ -1167,7 +1189,8 @@ int gmx_trjconv(int argc, char* argv[]) if (bTDump) { - fprintf(stderr, "\nDumping frame at t= %g %s\n", + fprintf(stderr, + "\nDumping frame at t= %g %s\n", output_env_conv_time(oenv, frout_time), output_env_get_time_unit(oenv).c_str()); } @@ -1183,7 +1206,8 @@ int gmx_trjconv(int argc, char* argv[]) else { /* round() is not C89 compatible, so we do this: */ - bDoIt = bRmod(std::floor(frout_time + 0.5), std::floor(tzero + 0.5), + bDoIt = bRmod(std::floor(frout_time + 0.5), + std::floor(tzero + 0.5), std::floor(delta_t + 0.5)); } } @@ -1193,7 +1217,9 @@ int gmx_trjconv(int argc, char* argv[]) /* print sometimes */ if (((outframe % SKIP) == 0) || (outframe < SKIP)) { - fprintf(stderr, " -> frame %6d time %8.3f \r", outframe, + fprintf(stderr, + " -> frame %6d time %8.3f \r", + outframe, output_env_conv_time(oenv, frout_time)); fflush(stderr); } @@ -1243,20 +1269,20 @@ int gmx_trjconv(int argc, char* argv[]) put_atoms_in_triclinic_unitcell(ecenter, fr.box, positionsArrayRef); break; case euCompact: - put_atoms_in_compact_unitcell(pbcType, ecenter, fr.box, - positionsArrayRef); + put_atoms_in_compact_unitcell( + pbcType, ecenter, fr.box, positionsArrayRef); break; } } if (bPBCcomRes) { - put_residue_com_in_box(unitcell_enum, ecenter, natoms, atoms->atom, - pbcType, fr.box, fr.x); + put_residue_com_in_box( + unitcell_enum, ecenter, natoms, atoms->atom, pbcType, fr.box, fr.x); } if (bPBCcomMol) { - put_molecule_com_in_box(unitcell_enum, ecenter, &top->mols, natoms, - atoms->atom, pbcType, fr.box, fr.x); + put_molecule_com_in_box( + unitcell_enum, ecenter, &top->mols, natoms, atoms->atom, pbcType, fr.box, fr.x); } /* Copy the input trxframe struct to the output trxframe struct */ frout = fr; @@ -1314,7 +1340,8 @@ int gmx_trjconv(int argc, char* argv[]) /* round() is not C89 compatible, so we do this: */ bSplitHere = bSplit && bRmod(std::floor(frout.time + 0.5), - std::floor(tzero + 0.5), std::floor(split_t + 0.5)); + std::floor(tzero + 0.5), + std::floor(split_t + 0.5)); } if (bSeparate || bSplitHere) { @@ -1373,8 +1400,12 @@ int gmx_trjconv(int argc, char* argv[]) switch (ftp) { case efGRO: - write_hconf_p(out, title.c_str(), &useatoms, frout.x, - frout.bV ? frout.v : nullptr, frout.box); + write_hconf_p(out, + title.c_str(), + &useatoms, + frout.x, + frout.bV ? frout.v : nullptr, + frout.box); break; case efPDB: fprintf(out, "REMARK GENERATED BY TRJCONV\n"); @@ -1389,8 +1420,15 @@ int gmx_trjconv(int argc, char* argv[]) { model_nr++; } - write_pdbfile(out, title.c_str(), &useatoms, frout.x, - frout.pbcType, frout.box, ' ', model_nr, gc); + write_pdbfile(out, + title.c_str(), + &useatoms, + frout.x, + frout.pbcType, + frout.box, + ' ', + model_nr, + gc); break; case efG96: const char* outputTitle = ""; diff --git a/src/gromacs/tools/tune_pme.cpp b/src/gromacs/tools/tune_pme.cpp index da954ea332..a9ffd5cb2f 100644 --- a/src/gromacs/tools/tune_pme.cpp +++ b/src/gromacs/tools/tune_pme.cpp @@ -265,7 +265,8 @@ static int parse_logfile(const char* logfile, fprintf(stderr, "WARNING: Time step counters were reset at step %s,\n" " though they were supposed to be reset at step %s!\n", - dumstring, dumstring2); + dumstring, + dumstring2); } } } @@ -277,8 +278,12 @@ static int parse_logfile(const char* logfile, /* Look for domain decomp grid and separate PME nodes: */ if (str_starts(line, matchstrdd)) { - sscanf(line, "Domain decomposition grid %d x %d x %d, separate PME ranks %d", - &(perfdata->nx), &(perfdata->ny), &(perfdata->nz), &npme); + sscanf(line, + "Domain decomposition grid %d x %d x %d, separate PME ranks %d", + &(perfdata->nx), + &(perfdata->ny), + &(perfdata->nz), + &npme); if (perfdata->nPMEnodes == -1) { perfdata->guessPME = npme; @@ -511,8 +516,16 @@ static gmx_bool analyze_data(FILE* fp, s /= (nrepeats - 1); s = std::sqrt(s); - fprintf(fp, "%4d %3d %4d%s %12.3f %12.3f %12.3f %s", line, k, pd->nPMEnodes, - strbuf, pd->Gcycles_Av, s, pd->ns_per_day_Av, str_PME_f_load); + fprintf(fp, + "%4d %3d %4d%s %12.3f %12.3f %12.3f %s", + line, + k, + pd->nPMEnodes, + strbuf, + pd->Gcycles_Av, + s, + pd->ns_per_day_Av, + str_PME_f_load); if (nnodes > 1) { fprintf(fp, " %3d %3d %3d", pd->nx, pd->ny, pd->nz); @@ -582,8 +595,7 @@ static gmx_bool analyze_data(FILE* fp, if (bRefinedCoul) { - fprintf(fp, " New Coulomb radius: %f nm (was %f nm)\n", info->rcoulomb[k_win], - info->rcoulomb[0]); + fprintf(fp, " New Coulomb radius: %f nm (was %f nm)\n", info->rcoulomb[k_win], info->rcoulomb[0]); } if (bRefinedVdW) @@ -593,8 +605,14 @@ static gmx_bool analyze_data(FILE* fp, if (bRefinedGrid) { - fprintf(fp, " New Fourier grid xyz: %d %d %d (was %d %d %d)\n", info->nkx[k_win], - info->nky[k_win], info->nkz[k_win], info->nkx[0], info->nky[0], info->nkz[0]); + fprintf(fp, + " New Fourier grid xyz: %d %d %d (was %d %d %d)\n", + info->nkx[k_win], + info->nky[k_win], + info->nkz[k_win], + info->nkx[0], + info->nky[0], + info->nkz[0]); } if (bCanUseOrigTPR && ntprs > 1) @@ -690,8 +708,9 @@ static void check_mdrun_works(gmx_bool bThreads, } else { - snew(command, std::strlen(cmd_mpirun) + std::strlen(cmd_np) + std::strlen(cmd_mdrun) - + std::strlen(filename) + 50); + snew(command, + std::strlen(cmd_mpirun) + std::strlen(cmd_np) + std::strlen(cmd_mdrun) + + std::strlen(filename) + 50); sprintf(command, "%s%s%s -version -maxh 0.001 1> %s 2>&1", cmd_mpirun, cmd_np, cmd_mdrun, filename); } fprintf(stdout, "Trying '%s' ... ", command); @@ -800,8 +819,9 @@ static void launch_simulation(gmx_bool bLaunch, /* Should the simula /* Make enough space for the system call command, * (200 extra chars for -npme ... etc. options should suffice): */ - snew(command, std::strlen(cmd_mpirun) + std::strlen(cmd_mdrun) + std::strlen(cmd_np) - + std::strlen(args_for_mdrun) + std::strlen(simulation_tpr) + 200); + snew(command, + std::strlen(cmd_mpirun) + std::strlen(cmd_mdrun) + std::strlen(cmd_np) + + std::strlen(args_for_mdrun) + std::strlen(simulation_tpr) + 200); auto cmd_gpu_ids = make_gpu_id_command_line(eligible_gpu_ids); @@ -809,17 +829,29 @@ static void launch_simulation(gmx_bool bLaunch, /* Should the simula * of the command line string */ if (bThreads) { - sprintf(command, "%s%s-npme %d -s %s %s %s", cmd_mdrun, cmd_np, nPMEnodes, simulation_tpr, - args_for_mdrun, cmd_gpu_ids.c_str()); + sprintf(command, + "%s%s-npme %d -s %s %s %s", + cmd_mdrun, + cmd_np, + nPMEnodes, + simulation_tpr, + args_for_mdrun, + cmd_gpu_ids.c_str()); } else { - sprintf(command, "%s%s%s -npme %d -s %s %s %s", cmd_mpirun, cmd_np, cmd_mdrun, nPMEnodes, - simulation_tpr, args_for_mdrun, cmd_gpu_ids.c_str()); + sprintf(command, + "%s%s%s -npme %d -s %s %s %s", + cmd_mpirun, + cmd_np, + cmd_mdrun, + nPMEnodes, + simulation_tpr, + args_for_mdrun, + cmd_gpu_ids.c_str()); } - fprintf(fp, "%s this command line to launch the simulation:\n\n%s", - bLaunch ? "Using" : "Please use", command); + fprintf(fp, "%s this command line to launch the simulation:\n\n%s", bLaunch ? "Using" : "Please use", command); sep_line(fp); fflush(fp); @@ -891,8 +923,11 @@ static void make_benchmark_tprs(const char* fn_sim_tpr, /* READ : User-provided real fourierspacing; /* Basic fourierspacing from tpr */ - sprintf(buf, "Making benchmark tpr file%s with %s time step%s", *ntprs > 1 ? "s" : "", - "%" PRId64, benchsteps > 1 ? "s" : ""); + sprintf(buf, + "Making benchmark tpr file%s with %s time step%s", + *ntprs > 1 ? "s" : "", + "%" PRId64, + benchsteps > 1 ? "s" : ""); fprintf(stdout, buf, benchsteps); if (statesteps > 0) { @@ -909,21 +944,26 @@ static void make_benchmark_tprs(const char* fn_sim_tpr, /* READ : User-provided /* Check if some kind of PME was chosen */ if (EEL_PME(ir->coulombtype) == FALSE) { - gmx_fatal(FARGS, "Can only do optimizations for simulations with %s electrostatics.", - EELTYPE(eelPME)); + gmx_fatal(FARGS, "Can only do optimizations for simulations with %s electrostatics.", EELTYPE(eelPME)); } /* Check if rcoulomb == rlist, which is necessary for plain PME. */ if ((ir->cutoff_scheme != ecutsVERLET) && (eelPME == ir->coulombtype) && !(ir->rcoulomb == ir->rlist)) { - gmx_fatal(FARGS, "%s requires rcoulomb (%f) to be equal to rlist (%f).", EELTYPE(eelPME), - ir->rcoulomb, ir->rlist); + gmx_fatal(FARGS, + "%s requires rcoulomb (%f) to be equal to rlist (%f).", + EELTYPE(eelPME), + ir->rcoulomb, + ir->rlist); } /* For other PME types, rcoulomb is allowed to be smaller than rlist */ else if (ir->rcoulomb > ir->rlist) { - gmx_fatal(FARGS, "%s requires rcoulomb (%f) to be equal to or smaller than rlist (%f)", - EELTYPE(ir->coulombtype), ir->rcoulomb, ir->rlist); + gmx_fatal(FARGS, + "%s requires rcoulomb (%f) to be equal to or smaller than rlist (%f)", + EELTYPE(ir->coulombtype), + ir->rcoulomb, + ir->rlist); } if (bScaleRvdw && ir->rvdw != ir->rcoulomb) @@ -980,16 +1020,18 @@ static void make_benchmark_tprs(const char* fn_sim_tpr, /* READ : User-provided fourierspacing = std::max(std::max(info->fsx[0], info->fsy[0]), info->fsz[0]); } - fprintf(stdout, "Calculating PME grid points on the basis of a fourierspacing of %f nm\n", - fourierspacing); + fprintf(stdout, "Calculating PME grid points on the basis of a fourierspacing of %f nm\n", fourierspacing); /* For performance comparisons the number of particles is useful to have */ fprintf(fp, " Number of particles : %d\n", mtop.natoms); /* Print information about settings of which some are potentially modified: */ fprintf(fp, " Coulomb type : %s\n", EELTYPE(ir->coulombtype)); - fprintf(fp, " Grid spacing x y z : %f %f %f\n", box_size[XX] / ir->nkx, - box_size[YY] / ir->nky, box_size[ZZ] / ir->nkz); + fprintf(fp, + " Grid spacing x y z : %f %f %f\n", + box_size[XX] / ir->nkx, + box_size[YY] / ir->nky, + box_size[ZZ] / ir->nkz); fprintf(fp, " Van der Waals type : %s\n", EVDWTYPE(ir->vdwtype)); if (ir_vdw_switched(ir)) { @@ -1044,8 +1086,13 @@ static void make_benchmark_tprs(const char* fn_sim_tpr, /* READ : User-provided /* Scale the Fourier grid spacing */ ir->nkx = ir->nky = ir->nkz = 0; - calcFftGrid(nullptr, state.box, fourierspacing * fac, minimalPmeGridSize(ir->pme_order), - &ir->nkx, &ir->nky, &ir->nkz); + calcFftGrid(nullptr, + state.box, + fourierspacing * fac, + minimalPmeGridSize(ir->pme_order), + &ir->nkx, + &ir->nky, + &ir->nkz); /* Adjust other radii since various conditions need to be fulfilled */ if (eelPME == ir->coulombtype) @@ -1501,8 +1548,13 @@ static void do_the_tests(FILE* fp, /* General tune_pme outpu * the -passall (if set) options requires cmd_args_bench to be * at the end of the command line string */ snew(pd->mdrun_cmd_line, cmdline_length); - sprintf(pd->mdrun_cmd_line, "%s-npme %d -s %s %s %s", cmd_stub, pd->nPMEnodes, - tpr_names[k], cmd_args_bench, cmd_gpu_ids.c_str()); + sprintf(pd->mdrun_cmd_line, + "%s-npme %d -s %s %s %s", + cmd_stub, + pd->nPMEnodes, + tpr_names[k], + cmd_args_bench, + cmd_gpu_ids.c_str()); /* To prevent that all benchmarks fail due to a show-stopper argument * on the mdrun command line, we make a quick check first. @@ -1527,8 +1579,7 @@ static void do_the_tests(FILE* fp, /* General tune_pme outpu do for this check, but it'll be easier to implement that after some refactoring of how the number of MPI ranks is managed. */ - sprintf(temporary_cmd_line, "%s-npme 0 -nb cpu -s %s %s", cmd_stub, - tpr_names[k], cmd_args_bench); + sprintf(temporary_cmd_line, "%s-npme 0 -nb cpu -s %s %s", cmd_stub, tpr_names[k], cmd_args_bench); make_sure_it_runs(temporary_cmd_line, cmdline_length, fp, fnm, nfile); } bFirst = FALSE; @@ -1542,8 +1593,14 @@ static void do_the_tests(FILE* fp, /* General tune_pme outpu { buf[0] = '\0'; } - fprintf(stdout, "\n=== Progress %2.0f%%, tpr %d/%d, run %d/%d%s:\n", - (100.0 * count) / totaltests, k + 1, nr_tprs, i + 1, *pmeentries, buf); + fprintf(stdout, + "\n=== Progress %2.0f%%, tpr %d/%d, run %d/%d%s:\n", + (100.0 * count) / totaltests, + k + 1, + nr_tprs, + i + 1, + *pmeentries, + buf); make_backup(opt2fn("-err", nfile, fnm)); sprintf(command, "%s 1> /dev/null 2>%s", pd->mdrun_cmd_line, opt2fn("-err", nfile, fnm)); fprintf(stdout, "%s\n", pd->mdrun_cmd_line); @@ -1551,8 +1608,8 @@ static void do_the_tests(FILE* fp, /* General tune_pme outpu /* Collect the performance data from the log file; also check stderr * for fatal errors */ - ret = parse_logfile(opt2fn("-bg", nfile, fnm), opt2fn("-err", nfile, fnm), pd, nr, - presteps, cpt_steps, nnodes); + ret = parse_logfile( + opt2fn("-bg", nfile, fnm), opt2fn("-err", nfile, fnm), pd, nr, presteps, cpt_steps, nnodes); if ((presteps > 0) && (ret == eParselogResetProblem)) { bResetProblem = TRUE; @@ -1578,8 +1635,14 @@ static void do_the_tests(FILE* fp, /* General tune_pme outpu } /* Write the data we got to disk */ - fprintf(fp, "%4d%s %12.3f %12.3f %s %s", pd->nPMEnodes, buf, pd->Gcycles[nr], - pd->ns_per_day[nr], str_PME_f_load, ParseLog[ret]); + fprintf(fp, + "%4d%s %12.3f %12.3f %s %s", + pd->nPMEnodes, + buf, + pd->Gcycles[nr], + pd->ns_per_day[nr], + str_PME_f_load, + ParseLog[ret]); if (!(ret == eParselogOK || ret == eParselogNoDDGrid || ret == eParselogNotFound)) { fprintf(fp, " Check %s file for problems.", ret == eParselogFatal ? "err" : "log"); @@ -1703,7 +1766,9 @@ static void check_input(int nnodes, gmx_fatal(FARGS, "Please choose the Coulomb radii such that rmin <= rmax.\n" "rmin = %g, rmax = %g, actual rcoul from .tpr file = %g\n", - *rmin, *rmax, rcoulomb); + *rmin, + *rmax, + rcoulomb); } /* Add test scenarios if rmin or rmax were set */ if (*ntprs <= 2) @@ -1774,7 +1839,8 @@ static void check_input(int nnodes, { fprintf(stderr, "WARNING: steps="); fprintf(stderr, "%" PRId64, bench_nsteps); - fprintf(stderr, ". Are you sure you want to perform so %s steps for each benchmark?\n", + fprintf(stderr, + ". Are you sure you want to perform so %s steps for each benchmark?\n", (bench_nsteps < 100) ? "few" : "many"); } @@ -1805,7 +1871,9 @@ static void check_input(int nnodes, gmx_fatal(FARGS, "Cannot have more than %d PME-only ranks for a total of %d ranks (you chose " "%d).\n", - nnodes / 2, nnodes, npme_fixed); + nnodes / 2, + nnodes, + npme_fixed); } if ((npme_fixed > 0) && (5 * npme_fixed < nnodes)) { @@ -2376,8 +2444,8 @@ int gmx_tune_pme(int argc, char* argv[]) seconds = gmx_gettime(); - if (!parse_common_args(&argc, argv, PCA_NOEXIT_ON_ARGS, NFILE, fnm, asize(pa), pa, asize(desc), - desc, 0, nullptr, &oenv)) + if (!parse_common_args( + &argc, argv, PCA_NOEXIT_ON_ARGS, NFILE, fnm, asize(pa), pa, asize(desc), desc, 0, nullptr, &oenv)) { return 0; } @@ -2438,8 +2506,16 @@ int gmx_tune_pme(int argc, char* argv[]) cmd_np = bbuf; - create_command_line_snippets(bAppendFiles, bKeepAndNumCPT, bResetCountersHalfWay, presteps, - NFILE, fnm, &cmd_args_bench, &cmd_args_launch, ExtraArgs, deffnm); + create_command_line_snippets(bAppendFiles, + bKeepAndNumCPT, + bResetCountersHalfWay, + presteps, + NFILE, + fnm, + &cmd_args_bench, + &cmd_args_launch, + ExtraArgs, + deffnm); /* Prepare to use checkpoint file if requested */ sim_part = 1; @@ -2460,8 +2536,22 @@ int gmx_tune_pme(int argc, char* argv[]) fp = gmx_ffopen(opt2fn("-p", NFILE, fnm), "w"); /* Make a quick consistency check of command line parameters */ - check_input(nnodes, repeats, &ntprs, &rmin, rcoulomb, &rmax, maxPMEfraction, minPMEfraction, - npme_fixed, bench_nsteps, fnm, NFILE, sim_part, presteps, asize(pa), pa); + check_input(nnodes, + repeats, + &ntprs, + &rmin, + rcoulomb, + &rmax, + maxPMEfraction, + minPMEfraction, + npme_fixed, + bench_nsteps, + fnm, + NFILE, + sim_part, + presteps, + asize(pa), + pa); /* Determine the maximum and minimum number of PME nodes to test, * the actual list of settings is build in do_the_tests(). */ @@ -2597,8 +2687,16 @@ int gmx_tune_pme(int argc, char* argv[]) /* It can be that ntprs is reduced by make_benchmark_tprs if not enough * different grids could be found. */ - make_benchmark_tprs(opt2fn("-s", NFILE, fnm), tpr_names, bench_nsteps + presteps, cpt_steps, - rmin, rmax, bScaleRvdw, &ntprs, info, fp); + make_benchmark_tprs(opt2fn("-s", NFILE, fnm), + tpr_names, + bench_nsteps + presteps, + cpt_steps, + rmin, + rmax, + bScaleRvdw, + &ntprs, + info, + fp); /********************************************************************************/ /* Main loop over all scenarios we need to test: tpr files, PME nodes, repeats */ @@ -2608,15 +2706,34 @@ int gmx_tune_pme(int argc, char* argv[]) { GMX_RELEASE_ASSERT(npmevalues_opt[0] != nullptr, "Options inconsistency; npmevalues_opt[0] is NULL"); - do_the_tests(fp, tpr_names, maxPMEnodes, minPMEnodes, npme_fixed, npmevalues_opt[0], perfdata, - &pmeentries, repeats, nnodes, ntprs, bThreads, cmd_mpirun, cmd_np, cmd_mdrun, - cmd_args_bench, fnm, NFILE, presteps, cpt_steps, bCheck, eligible_gpu_ids); + do_the_tests(fp, + tpr_names, + maxPMEnodes, + minPMEnodes, + npme_fixed, + npmevalues_opt[0], + perfdata, + &pmeentries, + repeats, + nnodes, + ntprs, + bThreads, + cmd_mpirun, + cmd_np, + cmd_mdrun, + cmd_args_bench, + fnm, + NFILE, + presteps, + cpt_steps, + bCheck, + eligible_gpu_ids); fprintf(fp, "\nTuning took%8.1f minutes.\n", (gmx_gettime() - seconds) / 60.0); /* Analyse the results and give a suggestion for optimal settings: */ - bKeepTPR = analyze_data(fp, opt2fn("-p", NFILE, fnm), perfdata, nnodes, ntprs, pmeentries, - repeats, info, &best_tpr, &best_npme); + bKeepTPR = analyze_data( + fp, opt2fn("-p", NFILE, fnm), perfdata, nnodes, ntprs, pmeentries, repeats, info, &best_tpr, &best_npme); /* Take the best-performing tpr file and enlarge nsteps to original value */ if (bKeepTPR && !bOverwrite) @@ -2627,7 +2744,9 @@ int gmx_tune_pme(int argc, char* argv[]) { simulation_tpr = opt2fn("-so", NFILE, fnm); modify_PMEsettings(bOverwrite ? (new_sim_nsteps + cpt_steps) : info->orig_sim_steps, - info->orig_init_step, tpr_names[best_tpr], simulation_tpr); + info->orig_init_step, + tpr_names[best_tpr], + simulation_tpr); } /* Let's get rid of the temporary benchmark input files */ @@ -2638,8 +2757,8 @@ int gmx_tune_pme(int argc, char* argv[]) } /* Now start the real simulation if the user requested it ... */ - launch_simulation(bLaunch, fp, bThreads, cmd_mpirun, cmd_np, cmd_mdrun, cmd_args_launch, - simulation_tpr, best_npme, eligible_gpu_ids); + launch_simulation( + bLaunch, fp, bThreads, cmd_mpirun, cmd_np, cmd_mdrun, cmd_args_launch, simulation_tpr, best_npme, eligible_gpu_ids); } gmx_ffclose(fp); diff --git a/src/gromacs/topology/atomprop.cpp b/src/gromacs/topology/atomprop.cpp index c415086bfb..4874044330 100644 --- a/src/gromacs/topology/atomprop.cpp +++ b/src/gromacs/topology/atomprop.cpp @@ -211,7 +211,9 @@ static int findPropertyIndex(AtomProperty* ap, } else { - fprintf(debug, " match: %4s %4s\n", ap->entry[j].residueName.c_str(), + fprintf(debug, + " match: %4s %4s\n", + ap->entry[j].residueName.c_str(), ap->entry[j].atomName.c_str()); } } @@ -248,16 +250,26 @@ static void addProperty(AtomProperty* ap, { if (ap->entry[j].value == propValue) { - fprintf(stderr, "Warning double identical entries for %s %s %g on line %d in file %s\n", - residueName.c_str(), atomName.c_str(), propValue, line, ap->db.c_str()); + fprintf(stderr, + "Warning double identical entries for %s %s %g on line %d in file %s\n", + residueName.c_str(), + atomName.c_str(), + propValue, + line, + ap->db.c_str()); } else { fprintf(stderr, "Warning double different entries %s %s %g and %g on line %d in file %s\n" "Using last entry (%g)\n", - residueName.c_str(), atomName.c_str(), propValue, ap->entry[j].value, line, - ap->db.c_str(), propValue); + residueName.c_str(), + atomName.c_str(), + propValue, + ap->entry[j].value, + line, + ap->db.c_str(), + propValue); ap->entry[j].value = propValue; } } @@ -309,10 +321,11 @@ static void readProperty(AtomProperty* ap, ResidueType* restype, double factor) */ static bool setProperties(AtomProperty* ap, ResidueType* restype, int eprop, bool haveBeenWarned) { - const char* fns[epropNR] = { "atommass.dat", "vdwradii.dat", "dgsolv.dat", "electroneg.dat", - "elements.dat" }; - double fac[epropNR] = { 1.0, 1.0, 418.4, 1.0, 1.0 }; - double def[epropNR] = { 12.011, 0.14, 0.0, 2.2, -1 }; + const char* fns[epropNR] = { + "atommass.dat", "vdwradii.dat", "dgsolv.dat", "electroneg.dat", "elements.dat" + }; + double fac[epropNR] = { 1.0, 1.0, 418.4, 1.0, 1.0 }; + double def[epropNR] = { 12.011, 0.14, 0.0, 2.2, -1 }; bool printWarning = false; if (!ap->isSet) @@ -364,7 +377,8 @@ static void printvdwWarning(FILE* fp) { if (nullptr != fp) { - fprintf(fp, "NOTE: From version 5.0 %s uses the Van der Waals radii\n", + fprintf(fp, + "NOTE: From version 5.0 %s uses the Van der Waals radii\n", gmx::getProgramContext().displayName()); fprintf(fp, "from the source below. This means the results may be different\n"); fprintf(fp, "compared to previous GROMACS versions.\n"); diff --git a/src/gromacs/topology/atoms.cpp b/src/gromacs/topology/atoms.cpp index 20ce6be8bb..4da6464a03 100644 --- a/src/gromacs/topology/atoms.cpp +++ b/src/gromacs/topology/atoms.cpp @@ -271,8 +271,17 @@ static void pr_atom(FILE* fp, int indent, const char* title, const t_atom* atom, fprintf(fp, "%s[%6d]={type=%3hu, typeB=%3hu, ptype=%8s, m=%12.5e, " "q=%12.5e, mB=%12.5e, qB=%12.5e, resind=%5d, atomnumber=%3d}\n", - title, i, atom[i].type, atom[i].typeB, ptype_str[atom[i].ptype], atom[i].m, - atom[i].q, atom[i].mB, atom[i].qB, atom[i].resind, atom[i].atomnumber); + title, + i, + atom[i].type, + atom[i].typeB, + ptype_str[atom[i].ptype], + atom[i].m, + atom[i].q, + atom[i].mB, + atom[i].qB, + atom[i].resind, + atom[i].atomnumber); } } } @@ -287,8 +296,7 @@ static void pr_strings2(FILE* fp, int indent, const char* title, char*** nm, cha for (i = 0; i < n; i++) { pr_indent(fp, indent); - fprintf(fp, "%s[%d]={name=\"%s\",nameB=\"%s\"}\n", title, bShowNumbers ? i : -1, - *(nm[i]), *(nmB[i])); + fprintf(fp, "%s[%d]={name=\"%s\",nameB=\"%s\"}\n", title, bShowNumbers ? i : -1, *(nm[i]), *(nmB[i])); } } } @@ -303,8 +311,13 @@ static void pr_resinfo(FILE* fp, int indent, const char* title, const t_resinfo* for (i = 0; i < n; i++) { pr_indent(fp, indent); - fprintf(fp, "%s[%d]={name=\"%s\", nr=%d, ic='%c'}\n", title, bShowNumbers ? i : -1, - *(resinfo[i].name), resinfo[i].nr, (resinfo[i].ic == '\0') ? ' ' : resinfo[i].ic); + fprintf(fp, + "%s[%d]={name=\"%s\", nr=%d, ic='%c'}\n", + title, + bShowNumbers ? i : -1, + *(resinfo[i].name), + resinfo[i].nr, + (resinfo[i].ic == '\0') ? ' ' : resinfo[i].ic); } } } @@ -331,8 +344,7 @@ void pr_atomtypes(FILE* fp, int indent, const char* title, const t_atomtypes* at for (i = 0; i < atomtypes->nr; i++) { pr_indent(fp, indent); - fprintf(fp, "atomtype[%3d]={atomnumber=%4d}\n", bShowNumbers ? i : -1, - atomtypes->atomnumber[i]); + fprintf(fp, "atomtype[%3d]={atomnumber=%4d}\n", bShowNumbers ? i : -1, atomtypes->atomnumber[i]); } } } @@ -466,15 +478,19 @@ void atomsSetMassesBasedOnNames(t_atoms* atoms, gmx_bool printMissingMasses) bool haveMass = true; for (int i = 0; i < atoms->nr; i++) { - if (!aps.setAtomProperty(epropMass, *atoms->resinfo[atoms->atom[i].resind].name, - *atoms->atomname[i], &atoms->atom[i].m)) + if (!aps.setAtomProperty(epropMass, + *atoms->resinfo[atoms->atom[i].resind].name, + *atoms->atomname[i], + &atoms->atom[i].m)) { haveMass = false; if (numWarn < maxWarn) { - fprintf(stderr, "Can not find mass in database for atom %s in residue %d %s\n", - *atoms->atomname[i], atoms->resinfo[atoms->atom[i].resind].nr, + fprintf(stderr, + "Can not find mass in database for atom %s in residue %d %s\n", + *atoms->atomname[i], + atoms->resinfo[atoms->atom[i].resind].nr, *atoms->resinfo[atoms->atom[i].resind].name); numWarn++; } diff --git a/src/gromacs/topology/block.cpp b/src/gromacs/topology/block.cpp index cc6ad6b191..b31d5e2c06 100644 --- a/src/gromacs/topology/block.cpp +++ b/src/gromacs/topology/block.cpp @@ -277,8 +277,12 @@ void pr_block(FILE* fp, int indent, const char* title, const t_block* block, gmx } else { - fprintf(fp, "%s[%d]={%d..%d}\n", title, bShowNumbers ? i : -1, - bShowNumbers ? start : -1, bShowNumbers ? end - 1 : -1); + fprintf(fp, + "%s[%d]={%d..%d}\n", + title, + bShowNumbers ? i : -1, + bShowNumbers ? start : -1, + bShowNumbers ? end - 1 : -1); } start = end; } @@ -311,8 +315,12 @@ void pr_blocka(FILE* fp, int indent, const char* title, const t_blocka* block, g } else { - size += fprintf(fp, "%s[%d][%d..%d]={", title, bShowNumbers ? i : -1, - bShowNumbers ? start : -1, bShowNumbers ? end - 1 : -1); + size += fprintf(fp, + "%s[%d][%d..%d]={", + title, + bShowNumbers ? i : -1, + bShowNumbers ? start : -1, + bShowNumbers ? end - 1 : -1); } for (j = start; j < end; j++) { diff --git a/src/gromacs/topology/forcefieldparameters.cpp b/src/gromacs/topology/forcefieldparameters.cpp index 036960895d..24c72ca9ad 100644 --- a/src/gromacs/topology/forcefieldparameters.cpp +++ b/src/gromacs/topology/forcefieldparameters.cpp @@ -98,7 +98,9 @@ void pr_ffparams(FILE* fp, int indent, const char* title, const gmx_ffparams_t* for (i = 0; i < ffparams->numTypes(); i++) { pr_indent(fp, indent + INDENT); - fprintf(fp, "functype[%d]=%s, ", bShowNumbers ? i : -1, + fprintf(fp, + "functype[%d]=%s, ", + bShowNumbers ? i : -1, interaction_function[ffparams->functype[i]].name); pr_iparams(fp, ffparams->functype[i], ffparams->iparams[i]); } diff --git a/src/gromacs/topology/idef.cpp b/src/gromacs/topology/idef.cpp index a82e6e5754..cbc9b16a60 100644 --- a/src/gromacs/topology/idef.cpp +++ b/src/gromacs/topology/idef.cpp @@ -54,9 +54,15 @@ static void printHarmonicInteraction(gmx::TextWriter* writer, const char* r, const char* kr) { - writer->writeLineFormatted("%sA=%12.5e, %sA=%12.5e, %sB=%12.5e, %sB=%12.5e", r, - iparams.harmonic.rA, kr, iparams.harmonic.krA, r, - iparams.harmonic.rB, kr, iparams.harmonic.krB); + writer->writeLineFormatted("%sA=%12.5e, %sA=%12.5e, %sB=%12.5e, %sB=%12.5e", + r, + iparams.harmonic.rA, + kr, + iparams.harmonic.krA, + r, + iparams.harmonic.rB, + kr, + iparams.harmonic.krB); } void pr_iparams(FILE* fp, t_functype ftype, const t_iparams& iparams) @@ -76,25 +82,37 @@ void printInteractionParameters(gmx::TextWriter* writer, t_functype ftype, const case F_ANGLES: case F_G96ANGLES: printHarmonicInteraction(writer, iparams, "th", "ct"); break; case F_CROSS_BOND_BONDS: - writer->writeLineFormatted("r1e=%15.8e, r2e=%15.8e, krr=%15.8e", iparams.cross_bb.r1e, - iparams.cross_bb.r2e, iparams.cross_bb.krr); + writer->writeLineFormatted("r1e=%15.8e, r2e=%15.8e, krr=%15.8e", + iparams.cross_bb.r1e, + iparams.cross_bb.r2e, + iparams.cross_bb.krr); break; case F_CROSS_BOND_ANGLES: writer->writeLineFormatted("r1e=%15.8e, r1e=%15.8e, r3e=%15.8e, krt=%15.8e", - iparams.cross_ba.r1e, iparams.cross_ba.r2e, - iparams.cross_ba.r3e, iparams.cross_ba.krt); + iparams.cross_ba.r1e, + iparams.cross_ba.r2e, + iparams.cross_ba.r3e, + iparams.cross_ba.krt); break; case F_LINEAR_ANGLES: writer->writeLineFormatted("klinA=%15.8e, aA=%15.8e, klinB=%15.8e, aB=%15.8e", - iparams.linangle.klinA, iparams.linangle.aA, - iparams.linangle.klinB, iparams.linangle.aB); + iparams.linangle.klinA, + iparams.linangle.aA, + iparams.linangle.klinB, + iparams.linangle.aB); break; case F_UREY_BRADLEY: writer->writeLineFormatted( "thetaA=%15.8e, kthetaA=%15.8e, r13A=%15.8e, kUBA=%15.8e, thetaB=%15.8e, " "kthetaB=%15.8e, r13B=%15.8e, kUBB=%15.8e", - iparams.u_b.thetaA, iparams.u_b.kthetaA, iparams.u_b.r13A, iparams.u_b.kUBA, - iparams.u_b.thetaB, iparams.u_b.kthetaB, iparams.u_b.r13B, iparams.u_b.kUBB); + iparams.u_b.thetaA, + iparams.u_b.kthetaA, + iparams.u_b.r13A, + iparams.u_b.kUBA, + iparams.u_b.thetaB, + iparams.u_b.kthetaB, + iparams.u_b.r13B, + iparams.u_b.kUBB); break; case F_QUARTIC_ANGLES: writer->writeStringFormatted("theta=%15.8e", iparams.qangle.theta); @@ -105,8 +123,8 @@ void printInteractionParameters(gmx::TextWriter* writer, t_functype ftype, const writer->ensureLineBreak(); break; case F_BHAM: - writer->writeLineFormatted("a=%15.8e, b=%15.8e, c=%15.8e", iparams.bham.a, - iparams.bham.b, iparams.bham.c); + writer->writeLineFormatted( + "a=%15.8e, b=%15.8e, c=%15.8e", iparams.bham.a, iparams.bham.b, iparams.bham.c); break; case F_BONDS: case F_G96BONDS: @@ -115,12 +133,18 @@ void printInteractionParameters(gmx::TextWriter* writer, t_functype ftype, const case F_MORSE: writer->writeLineFormatted( "b0A=%15.8e, cbA=%15.8e, betaA=%15.8e, b0B=%15.8e, cbB=%15.8e, betaB=%15.8e", - iparams.morse.b0A, iparams.morse.cbA, iparams.morse.betaA, iparams.morse.b0B, - iparams.morse.cbB, iparams.morse.betaB); + iparams.morse.b0A, + iparams.morse.cbA, + iparams.morse.betaA, + iparams.morse.b0B, + iparams.morse.cbB, + iparams.morse.betaB); break; case F_CUBICBONDS: - writer->writeLineFormatted("b0=%15.8e, kb=%15.8e, kcub=%15.8e", iparams.cubic.b0, - iparams.cubic.kb, iparams.cubic.kcub); + writer->writeLineFormatted("b0=%15.8e, kb=%15.8e, kcub=%15.8e", + iparams.cubic.b0, + iparams.cubic.kb, + iparams.cubic.kcub); break; case F_CONNBONDS: writer->ensureEmptyLine(); break; case F_FENEBONDS: @@ -130,106 +154,153 @@ void printInteractionParameters(gmx::TextWriter* writer, t_functype ftype, const writer->writeLineFormatted( "lowA=%15.8e, up1A=%15.8e, up2A=%15.8e, kA=%15.8e, lowB=%15.8e, up1B=%15.8e, " "up2B=%15.8e, kB=%15.8e,", - iparams.restraint.lowA, iparams.restraint.up1A, iparams.restraint.up2A, - iparams.restraint.kA, iparams.restraint.lowB, iparams.restraint.up1B, - iparams.restraint.up2B, iparams.restraint.kB); + iparams.restraint.lowA, + iparams.restraint.up1A, + iparams.restraint.up2A, + iparams.restraint.kA, + iparams.restraint.lowB, + iparams.restraint.up1B, + iparams.restraint.up2B, + iparams.restraint.kB); break; case F_TABBONDS: case F_TABBONDSNC: case F_TABANGLES: case F_TABDIHS: - writer->writeLineFormatted("tab=%d, kA=%15.8e, kB=%15.8e", iparams.tab.table, - iparams.tab.kA, iparams.tab.kB); + writer->writeLineFormatted( + "tab=%d, kA=%15.8e, kB=%15.8e", iparams.tab.table, iparams.tab.kA, iparams.tab.kB); break; case F_POLARIZATION: writer->writeLineFormatted("alpha=%15.8e", iparams.polarize.alpha); break; case F_ANHARM_POL: writer->writeLineFormatted("alpha=%15.8e drcut=%15.8e khyp=%15.8e", - iparams.anharm_polarize.alpha, iparams.anharm_polarize.drcut, + iparams.anharm_polarize.alpha, + iparams.anharm_polarize.drcut, iparams.anharm_polarize.khyp); break; case F_THOLE_POL: writer->writeLineFormatted("a=%15.8e, alpha1=%15.8e, alpha2=%15.8e, rfac=%15.8e", - iparams.thole.a, iparams.thole.alpha1, iparams.thole.alpha2, + iparams.thole.a, + iparams.thole.alpha1, + iparams.thole.alpha2, iparams.thole.rfac); break; case F_WATER_POL: writer->writeLineFormatted( "al_x=%15.8e, al_y=%15.8e, al_z=%15.8e, rOH=%9.6f, rHH=%9.6f, rOD=%9.6f", - iparams.wpol.al_x, iparams.wpol.al_y, iparams.wpol.al_z, iparams.wpol.rOH, - iparams.wpol.rHH, iparams.wpol.rOD); + iparams.wpol.al_x, + iparams.wpol.al_y, + iparams.wpol.al_z, + iparams.wpol.rOH, + iparams.wpol.rHH, + iparams.wpol.rOD); break; case F_LJ: writer->writeLineFormatted("c6=%15.8e, c12=%15.8e", iparams.lj.c6, iparams.lj.c12); break; case F_LJ14: writer->writeLineFormatted("c6A=%15.8e, c12A=%15.8e, c6B=%15.8e, c12B=%15.8e", - iparams.lj14.c6A, iparams.lj14.c12A, iparams.lj14.c6B, + iparams.lj14.c6A, + iparams.lj14.c12A, + iparams.lj14.c6B, iparams.lj14.c12B); break; case F_LJC14_Q: writer->writeLineFormatted("fqq=%15.8e, qi=%15.8e, qj=%15.8e, c6=%15.8e, c12=%15.8e", - iparams.ljc14.fqq, iparams.ljc14.qi, iparams.ljc14.qj, - iparams.ljc14.c6, iparams.ljc14.c12); + iparams.ljc14.fqq, + iparams.ljc14.qi, + iparams.ljc14.qj, + iparams.ljc14.c6, + iparams.ljc14.c12); break; case F_LJC_PAIRS_NB: - writer->writeLineFormatted("qi=%15.8e, qj=%15.8e, c6=%15.8e, c12=%15.8e", iparams.ljcnb.qi, - iparams.ljcnb.qj, iparams.ljcnb.c6, iparams.ljcnb.c12); + writer->writeLineFormatted("qi=%15.8e, qj=%15.8e, c6=%15.8e, c12=%15.8e", + iparams.ljcnb.qi, + iparams.ljcnb.qj, + iparams.ljcnb.c6, + iparams.ljcnb.c12); break; case F_PDIHS: case F_PIDIHS: case F_ANGRES: case F_ANGRESZ: writer->writeLineFormatted("phiA=%15.8e, cpA=%15.8e, phiB=%15.8e, cpB=%15.8e, mult=%d", - iparams.pdihs.phiA, iparams.pdihs.cpA, iparams.pdihs.phiB, - iparams.pdihs.cpB, iparams.pdihs.mult); + iparams.pdihs.phiA, + iparams.pdihs.cpA, + iparams.pdihs.phiB, + iparams.pdihs.cpB, + iparams.pdihs.mult); break; case F_DISRES: writer->writeLineFormatted( "label=%4d, type=%1d, low=%15.8e, up1=%15.8e, up2=%15.8e, fac=%15.8e)", - iparams.disres.label, iparams.disres.type, iparams.disres.low, - iparams.disres.up1, iparams.disres.up2, iparams.disres.kfac); + iparams.disres.label, + iparams.disres.type, + iparams.disres.low, + iparams.disres.up1, + iparams.disres.up2, + iparams.disres.kfac); break; case F_ORIRES: writer->writeLineFormatted( "ex=%4d, label=%d, power=%4d, c=%15.8e, obs=%15.8e, kfac=%15.8e)", - iparams.orires.ex, iparams.orires.label, iparams.orires.power, iparams.orires.c, - iparams.orires.obs, iparams.orires.kfac); + iparams.orires.ex, + iparams.orires.label, + iparams.orires.power, + iparams.orires.c, + iparams.orires.obs, + iparams.orires.kfac); break; case F_DIHRES: writer->writeLineFormatted( "phiA=%15.8e, dphiA=%15.8e, kfacA=%15.8e, phiB=%15.8e, dphiB=%15.8e, " "kfacB=%15.8e", - iparams.dihres.phiA, iparams.dihres.dphiA, iparams.dihres.kfacA, - iparams.dihres.phiB, iparams.dihres.dphiB, iparams.dihres.kfacB); + iparams.dihres.phiA, + iparams.dihres.dphiA, + iparams.dihres.kfacA, + iparams.dihres.phiB, + iparams.dihres.dphiB, + iparams.dihres.kfacB); break; case F_POSRES: writer->writeLineFormatted( "pos0A=(%15.8e,%15.8e,%15.8e), fcA=(%15.8e,%15.8e,%15.8e), " "pos0B=(%15.8e,%15.8e,%15.8e), fcB=(%15.8e,%15.8e,%15.8e)", - iparams.posres.pos0A[XX], iparams.posres.pos0A[YY], iparams.posres.pos0A[ZZ], - iparams.posres.fcA[XX], iparams.posres.fcA[YY], iparams.posres.fcA[ZZ], - iparams.posres.pos0B[XX], iparams.posres.pos0B[YY], iparams.posres.pos0B[ZZ], - iparams.posres.fcB[XX], iparams.posres.fcB[YY], iparams.posres.fcB[ZZ]); + iparams.posres.pos0A[XX], + iparams.posres.pos0A[YY], + iparams.posres.pos0A[ZZ], + iparams.posres.fcA[XX], + iparams.posres.fcA[YY], + iparams.posres.fcA[ZZ], + iparams.posres.pos0B[XX], + iparams.posres.pos0B[YY], + iparams.posres.pos0B[ZZ], + iparams.posres.fcB[XX], + iparams.posres.fcB[YY], + iparams.posres.fcB[ZZ]); break; case F_FBPOSRES: writer->writeLineFormatted( "pos0=(%15.8e,%15.8e,%15.8e), geometry=%d, r=%15.8e, k=%15.8e", - iparams.fbposres.pos0[XX], iparams.fbposres.pos0[YY], iparams.fbposres.pos0[ZZ], - iparams.fbposres.geom, iparams.fbposres.r, iparams.fbposres.k); + iparams.fbposres.pos0[XX], + iparams.fbposres.pos0[YY], + iparams.fbposres.pos0[ZZ], + iparams.fbposres.geom, + iparams.fbposres.r, + iparams.fbposres.k); break; case F_RBDIHS: for (int i = 0; i < NR_RBDIHS; i++) { - writer->writeStringFormatted("%srbcA[%d]=%15.8e", i == 0 ? "" : ", ", i, - iparams.rbdihs.rbcA[i]); + writer->writeStringFormatted( + "%srbcA[%d]=%15.8e", i == 0 ? "" : ", ", i, iparams.rbdihs.rbcA[i]); } writer->ensureLineBreak(); for (int i = 0; i < NR_RBDIHS; i++) { - writer->writeStringFormatted("%srbcB[%d]=%15.8e", i == 0 ? "" : ", ", i, - iparams.rbdihs.rbcB[i]); + writer->writeStringFormatted( + "%srbcB[%d]=%15.8e", i == 0 ? "" : ", ", i, iparams.rbdihs.rbcB[i]); } writer->ensureLineBreak(); break; @@ -281,8 +352,8 @@ void printInteractionParameters(gmx::TextWriter* writer, t_functype ftype, const case F_VSITE3OUT: case F_VSITE4FD: case F_VSITE4FDN: - writer->writeLineFormatted("a=%15.8e, b=%15.8e, c=%15.8e", iparams.vsite.a, - iparams.vsite.b, iparams.vsite.c); + writer->writeLineFormatted( + "a=%15.8e, b=%15.8e, c=%15.8e", iparams.vsite.a, iparams.vsite.b, iparams.vsite.c); break; case F_VSITEN: writer->writeLineFormatted("n=%2d, a=%15.8e", iparams.vsiten.n, iparams.vsiten.a); @@ -312,8 +383,12 @@ void printInteractionParameters(gmx::TextWriter* writer, t_functype ftype, const writer->ensureLineBreak(); break; default: - gmx_fatal(FARGS, "unknown function type %d (%s) in %s line %d", ftype, - interaction_function[ftype].name, __FILE__, __LINE__); + gmx_fatal(FARGS, + "unknown function type %d (%s) in %s line %d", + ftype, + interaction_function[ftype].name, + __FILE__, + __LINE__); } } @@ -388,7 +463,9 @@ void pr_idef(FILE* fp, int indent, const char* title, const t_idef* idef, gmx_bo for (i = 0; i < idef->ntypes; i++) { pr_indent(fp, indent + INDENT); - fprintf(fp, "functype[%d]=%s, ", bShowNumbers ? i : -1, + fprintf(fp, + "functype[%d]=%s, ", + bShowNumbers ? i : -1, interaction_function[idef->functype[i]].name); pr_iparams(fp, idef->functype[i], idef->iparams[i]); } @@ -396,8 +473,14 @@ void pr_idef(FILE* fp, int indent, const char* title, const t_idef* idef, gmx_bo for (j = 0; (j < F_NRE); j++) { - printIlist(fp, indent, interaction_function[j].longname, idef->functype, idef->il[j], - bShowNumbers, bShowParameters, idef->iparams); + printIlist(fp, + indent, + interaction_function[j].longname, + idef->functype, + idef->il[j], + bShowNumbers, + bShowParameters, + idef->iparams); } } } diff --git a/src/gromacs/topology/ifunc.cpp b/src/gromacs/topology/ifunc.cpp index 0be9b8bb1e..f52fdce4aa 100644 --- a/src/gromacs/topology/ifunc.cpp +++ b/src/gromacs/topology/ifunc.cpp @@ -117,57 +117,101 @@ /* this MUST correspond to the enum in src/gromacs/topology/ifunc.h */ const t_interaction_function interaction_function[F_NRE] = { - def_bond("BONDS", "Bond", 2, 2, 2), def_bond("G96BONDS", "G96Bond", 2, 2, 2), - def_bond("MORSE", "Morse", 2, 3, 3), def_bond("CUBICBONDS", "Cubic Bonds", 2, 3, 0), + def_bond("BONDS", "Bond", 2, 2, 2), + def_bond("G96BONDS", "G96Bond", 2, 2, 2), + def_bond("MORSE", "Morse", 2, 3, 3), + def_bond("CUBICBONDS", "Cubic Bonds", 2, 3, 0), def_bondnb("CONNBONDS", "Connect Bonds", 2, 0, 0), - def_bonded("HARMONIC", "Harmonic Pot.", 2, 2, 2), def_bondnb("FENEBONDS", "FENE Bonds", 2, 2, 0), - def_bondt("TABBONDS", "Tab. Bonds", 2, 2, 2), def_bondedtz("TABBONDSNC", "Tab. Bonds NC", 2, 2, 2), - def_bonded("RESTRAINTPOT", "Restraint Pot.", 2, 4, 4), def_angle("ANGLES", "Angle", 3, 2, 2), - def_angle("G96ANGLES", "G96Angle", 3, 2, 2), def_angle("RESTRANGLES", "Restricted Angles", 3, 2, 2), + def_bonded("HARMONIC", "Harmonic Pot.", 2, 2, 2), + def_bondnb("FENEBONDS", "FENE Bonds", 2, 2, 0), + def_bondt("TABBONDS", "Tab. Bonds", 2, 2, 2), + def_bondedtz("TABBONDSNC", "Tab. Bonds NC", 2, 2, 2), + def_bonded("RESTRAINTPOT", "Restraint Pot.", 2, 4, 4), + def_angle("ANGLES", "Angle", 3, 2, 2), + def_angle("G96ANGLES", "G96Angle", 3, 2, 2), + def_angle("RESTRANGLES", "Restricted Angles", 3, 2, 2), def_angle("LINEAR_ANGLES", "Lin. Angle", 3, 2, 2), def_bonded("CROSS_BOND_BOND", "Bond-Cross", 3, 3, 0), - def_bonded("CROSS_BOND_ANGLE", "BA-Cross", 3, 4, 0), def_angle("UREY_BRADLEY", "U-B", 3, 4, 4), - def_angle("QANGLES", "Quartic Angles", 3, 6, 0), def_bondedt("TABANGLES", "Tab. Angles", 3, 2, 2), - def_dihedral("PDIHS", "Proper Dih.", 4, 3, 3), def_dihedral("RBDIHS", "Ryckaert-Bell.", 4, 6, 6), + def_bonded("CROSS_BOND_ANGLE", "BA-Cross", 3, 4, 0), + def_angle("UREY_BRADLEY", "U-B", 3, 4, 4), + def_angle("QANGLES", "Quartic Angles", 3, 6, 0), + def_bondedt("TABANGLES", "Tab. Angles", 3, 2, 2), + def_dihedral("PDIHS", "Proper Dih.", 4, 3, 3), + def_dihedral("RBDIHS", "Ryckaert-Bell.", 4, 6, 6), def_dihedral("RESTRDIHS", "Restricted Dih.", 4, 2, 2), - def_dihedral("CBTDIHS", "CBT Dih.", 4, 6, 6), def_dihedral("FOURDIHS", "Fourier Dih.", 4, 4, 4), - def_dihedral("IDIHS", "Improper Dih.", 4, 2, 2), def_dihedral("PIDIHS", "Improper Dih.", 4, 3, 3), + def_dihedral("CBTDIHS", "CBT Dih.", 4, 6, 6), + def_dihedral("FOURDIHS", "Fourier Dih.", 4, 4, 4), + def_dihedral("IDIHS", "Improper Dih.", 4, 2, 2), + def_dihedral("PIDIHS", "Improper Dih.", 4, 3, 3), def_dihedral_tabulated("TABDIHS", "Tab. Dih.", 4, 2, 2), - def_dihedral("CMAP", "CMAP Dih.", 5, -1, -1), def_nofc("GB12", "GB 1-2 Pol. (unused)"), - def_nofc("GB13", "GB 1-3 Pol. (unused)"), def_nofc("GB14", "GB 1-4 Pol. (unused)"), - def_nofc("GBPOL", "GB Polarization (unused)"), def_nofc("NPSOLVATION", "Nonpolar Sol. (unused)"), - def_pair("LJ14", "LJ-14", 2, 2, 2), def_nofc("COUL14", "Coulomb-14"), - def_pair("LJC14_Q", "LJC-14 q", 2, 5, 0), def_pair("LJC_NB", "LJC Pairs NB", 2, 4, 0), - def_nb("LJ_SR", "LJ (SR)", 2, 2), def_nb("BHAM", "Buck.ham (SR)", 2, 3), - def_nofc("LJ_LR", "LJ (unused)"), def_nofc("BHAM_LR", "B.ham (unused)"), - def_nofc("DISPCORR", "Disper. corr."), def_nofc("COUL_SR", "Coulomb (SR)"), - def_nofc("COUL_LR", "Coul (unused)"), def_nofc("RF_EXCL", "RF excl."), - def_nofc("COUL_RECIP", "Coul. recip."), def_nofc("LJ_RECIP", "LJ recip."), - def_nofc("DPD", "DPD"), def_bondnb("POLARIZATION", "Polarization", 2, 1, 0), - def_bonded("WATERPOL", "Water Pol.", 5, 6, 0), def_bonded("THOLE", "Thole Pol.", 4, 3, 0), - def_bondnb("ANHARM_POL", "Anharm. Pol.", 2, 3, 0), def_bonded("POSRES", "Position Rest.", 1, 3, 3), - def_bonded("FBPOSRES", "Flat-bottom posres", 1, 3, 0), def_bonded("DISRES", "Dis. Rest.", 2, 6, 0), - def_nofc("DISRESVIOL", "D.R.Viol. (nm)"), def_bonded("ORIRES", "Orient. Rest.", 2, 6, 0), - def_nofc("ORDEV", "Ori. R. RMSD"), def_bonded("ANGRES", "Angle Rest.", 4, 3, 3), - def_bonded("ANGRESZ", "Angle Rest. Z", 2, 3, 3), def_bonded("DIHRES", "Dih. Rest.", 4, 3, 3), + def_dihedral("CMAP", "CMAP Dih.", 5, -1, -1), + def_nofc("GB12", "GB 1-2 Pol. (unused)"), + def_nofc("GB13", "GB 1-3 Pol. (unused)"), + def_nofc("GB14", "GB 1-4 Pol. (unused)"), + def_nofc("GBPOL", "GB Polarization (unused)"), + def_nofc("NPSOLVATION", "Nonpolar Sol. (unused)"), + def_pair("LJ14", "LJ-14", 2, 2, 2), + def_nofc("COUL14", "Coulomb-14"), + def_pair("LJC14_Q", "LJC-14 q", 2, 5, 0), + def_pair("LJC_NB", "LJC Pairs NB", 2, 4, 0), + def_nb("LJ_SR", "LJ (SR)", 2, 2), + def_nb("BHAM", "Buck.ham (SR)", 2, 3), + def_nofc("LJ_LR", "LJ (unused)"), + def_nofc("BHAM_LR", "B.ham (unused)"), + def_nofc("DISPCORR", "Disper. corr."), + def_nofc("COUL_SR", "Coulomb (SR)"), + def_nofc("COUL_LR", "Coul (unused)"), + def_nofc("RF_EXCL", "RF excl."), + def_nofc("COUL_RECIP", "Coul. recip."), + def_nofc("LJ_RECIP", "LJ recip."), + def_nofc("DPD", "DPD"), + def_bondnb("POLARIZATION", "Polarization", 2, 1, 0), + def_bonded("WATERPOL", "Water Pol.", 5, 6, 0), + def_bonded("THOLE", "Thole Pol.", 4, 3, 0), + def_bondnb("ANHARM_POL", "Anharm. Pol.", 2, 3, 0), + def_bonded("POSRES", "Position Rest.", 1, 3, 3), + def_bonded("FBPOSRES", "Flat-bottom posres", 1, 3, 0), + def_bonded("DISRES", "Dis. Rest.", 2, 6, 0), + def_nofc("DISRESVIOL", "D.R.Viol. (nm)"), + def_bonded("ORIRES", "Orient. Rest.", 2, 6, 0), + def_nofc("ORDEV", "Ori. R. RMSD"), + def_bonded("ANGRES", "Angle Rest.", 4, 3, 3), + def_bonded("ANGRESZ", "Angle Rest. Z", 2, 3, 3), + def_bonded("DIHRES", "Dih. Rest.", 4, 3, 3), def_nofc("DIHRESVIOL", "Dih. Rest. Viol."), /* obsolete */ - def_shkcb("CONSTR", "Constraint", 2, 1, 1), def_shk("CONSTRNC", "Constr. No Conn.", 2, 1, 1), - def_shkcb("SETTLE", "Settle", 3, 2, 0), def_vsite("VSITE1", "Virtual site 1", 2, 0), - def_vsite("VSITE2", "Virtual site 2", 3, 1), def_vsite("VSITE2FD", "Virtual site 2fd", 3, 1), - def_vsite("VSITE3", "Virtual site 3", 4, 2), def_vsite("VSITE3FD", "Virtual site 3fd", 4, 2), + def_shkcb("CONSTR", "Constraint", 2, 1, 1), + def_shk("CONSTRNC", "Constr. No Conn.", 2, 1, 1), + def_shkcb("SETTLE", "Settle", 3, 2, 0), + def_vsite("VSITE1", "Virtual site 1", 2, 0), + def_vsite("VSITE2", "Virtual site 2", 3, 1), + def_vsite("VSITE2FD", "Virtual site 2fd", 3, 1), + def_vsite("VSITE3", "Virtual site 3", 4, 2), + def_vsite("VSITE3FD", "Virtual site 3fd", 4, 2), def_vsite("VSITE3FAD", "Virtual site 3fad", 4, 2), - def_vsite("VSITE3OUT", "Virtual site 3out", 4, 3), def_vsite("VSITE4FD", "Virtual site 4fd", 5, 3), - def_vsite("VSITE4FDN", "Virtual site 4fdn", 5, 3), def_vsite("VSITEN", "Virtual site N", 2, 2), - def_nofc("COM_PULL", "COM Pull En."), def_nofc("DENSITYFIT", "Density fitting"), - def_nofc("EQM", "Quantum En."), def_nofc("EPOT", "Potential"), def_nofc("EKIN", "Kinetic En."), - def_nofc("ETOT", "Total Energy"), def_nofc("ECONS", "Conserved En."), - def_nofc("TEMP", "Temperature"), def_nofc("VTEMP", "Vir. Temp. (not used)"), + def_vsite("VSITE3OUT", "Virtual site 3out", 4, 3), + def_vsite("VSITE4FD", "Virtual site 4fd", 5, 3), + def_vsite("VSITE4FDN", "Virtual site 4fdn", 5, 3), + def_vsite("VSITEN", "Virtual site N", 2, 2), + def_nofc("COM_PULL", "COM Pull En."), + def_nofc("DENSITYFIT", "Density fitting"), + def_nofc("EQM", "Quantum En."), + def_nofc("EPOT", "Potential"), + def_nofc("EKIN", "Kinetic En."), + def_nofc("ETOT", "Total Energy"), + def_nofc("ECONS", "Conserved En."), + def_nofc("TEMP", "Temperature"), + def_nofc("VTEMP", "Vir. Temp. (not used)"), /* Note that pressure names can not be more than 8 char's, * because " (bar)" is appended to them. */ - def_nofc("PDISPCORR", "Pres. DC"), def_nofc("PRES", "Pressure"), + def_nofc("PDISPCORR", "Pres. DC"), + def_nofc("PRES", "Pressure"), def_nofc("DH/DL_CON", "dH/dl constr."), /* obsolete */ - def_nofc("DV/DL", "dVremain/dl"), def_nofc("DK/DL", "dEkin/dl"), def_nofc("DVC/DL", "dVcoul/dl"), - def_nofc("DVV/DL", "dVvdw/dl"), def_nofc("DVB/DL", "dVbonded/dl"), - def_nofc("DVR/DL", "dVrestraint/dl"), def_nofc("DVT/DL", "dVtemperature/dl") + def_nofc("DV/DL", "dVremain/dl"), + def_nofc("DK/DL", "dEkin/dl"), + def_nofc("DVC/DL", "dVcoul/dl"), + def_nofc("DVV/DL", "dVvdw/dl"), + def_nofc("DVB/DL", "dVbonded/dl"), + def_nofc("DVR/DL", "dVrestraint/dl"), + def_nofc("DVT/DL", "dVtemperature/dl") }; diff --git a/src/gromacs/topology/index.cpp b/src/gromacs/topology/index.cpp index 46dd0653dc..bb2d495e49 100644 --- a/src/gromacs/topology/index.cpp +++ b/src/gromacs/topology/index.cpp @@ -448,7 +448,8 @@ static void analyse_prot(gmx::ArrayRef restype, else { if (0 - == gmx_strncasecmp(constructing_data[i].defining_atomnames[j], atnm, + == gmx_strncasecmp(constructing_data[i].defining_atomnames[j], + atnm, strlen(constructing_data[i].defining_atomnames[j]))) { match = TRUE; @@ -504,8 +505,12 @@ static void analyse_prot(gmx::ArrayRef restype, { t_resinfo* ri; ri = &atoms->resinfo[resind]; - sprintf(ndx_name, "%s_%s%d%c", constructing_data[i].group_name, *ri->name, - ri->nr, ri->ic == ' ' ? '\0' : ri->ic); + sprintf(ndx_name, + "%s_%s%d%c", + constructing_data[i].group_name, + *ri->name, + ri->nr, + ri->ic == ' ' ? '\0' : ri->ic); add_grp(gb, gn, aid, ndx_name); aid.clear(); } @@ -723,13 +728,19 @@ void check_index(const char* gname, int n, int index[], const char* traj, int na { gmx_fatal(FARGS, "%s atom number (index[%d]=%d) is larger than the number of atoms in %s (%d)", - gname ? gname : "Index", i + 1, index[i] + 1, traj ? traj : "the trajectory", + gname ? gname : "Index", + i + 1, + index[i] + 1, + traj ? traj : "the trajectory", natoms); } else if (index[i] < 0) { - gmx_fatal(FARGS, "%s atom number (index[%d]=%d) is less than zero", - gname ? gname : "Index", i + 1, index[i] + 1); + gmx_fatal(FARGS, + "%s atom number (index[%d]=%d) is less than zero", + gname ? gname : "Index", + i + 1, + index[i] + 1); } } } @@ -930,8 +941,7 @@ rd_groups(t_blocka* grps, char** grpname, char* gnames[], int ngrps, int isize[] } for (i = 0; (i < grps->nr); i++) { - fprintf(stderr, "Group %5d (%15s) has %5d elements\n", i, grpname[i], - grps->index[i + 1] - grps->index[i]); + fprintf(stderr, "Group %5d (%15s) has %5d elements\n", i, grpname[i], grps->index[i + 1] - grps->index[i]); } for (i = 0; (i < ngrps); i++) { @@ -1032,8 +1042,10 @@ t_cluster_ndx* cluster_index(FILE* fplog, const char* ndx) c->maxframe = std::max(c->maxframe, c->clust->a[i]); } fprintf(fplog ? fplog : stdout, - "There are %d clusters containing %d structures, highest framenr is %d\n", c->clust->nr, - c->clust->nra, c->maxframe); + "There are %d clusters containing %d structures, highest framenr is %d\n", + c->clust->nr, + c->clust->nra, + c->maxframe); if (debug) { pr_blocka(debug, 0, "clust", c->clust, TRUE); @@ -1044,7 +1056,9 @@ t_cluster_ndx* cluster_index(FILE* fplog, const char* ndx) gmx_fatal(FARGS, "Range check error for c->clust->a[%d] = %d\n" "should be within 0 and %d", - i, c->clust->a[i], c->maxframe + 1); + i, + c->clust->a[i], + c->maxframe + 1); } } } diff --git a/src/gromacs/topology/invblock.cpp b/src/gromacs/topology/invblock.cpp index 9f4d6878f3..d50e75abea 100644 --- a/src/gromacs/topology/invblock.cpp +++ b/src/gromacs/topology/invblock.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team. - * Copyright (c) 2010,2014,2015,2019, by the GROMACS development team, led by + * Copyright (c) 2010,2014,2015,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -67,7 +67,9 @@ int* make_invblock(const t_block* block, int nr) gmx_fatal(FARGS, "Double entries in block structure. Item %d is in blocks %d and %d\n" " Cannot make an unambiguous inverse block.", - j, i, invblock[j]); + j, + i, + invblock[j]); } } } @@ -98,7 +100,9 @@ int* make_invblocka(const t_blocka* block, int nr) gmx_fatal(FARGS, "Double entries in block structure. Item %d is in blocks %d and %d\n" " Cannot make an unambiguous inverse block.", - j, i, invblock[block->a[j]]); + j, + i, + invblock[block->a[j]]); } } } diff --git a/src/gromacs/topology/mtop_lookup.h b/src/gromacs/topology/mtop_lookup.h index 0c61cc0265..8416952059 100644 --- a/src/gromacs/topology/mtop_lookup.h +++ b/src/gromacs/topology/mtop_lookup.h @@ -250,8 +250,8 @@ static inline void mtopGetAtomAndResidueName(const gmx_mtop_t& mtop, const char** residueName, int* globalResidueIndex) { - mtopGetAtomAndResidueName(&mtop, globalAtomIndex, moleculeBlock, atomName, residueNumber, - residueName, globalResidueIndex); + mtopGetAtomAndResidueName( + &mtop, globalAtomIndex, moleculeBlock, atomName, residueNumber, residueName, globalResidueIndex); } /*! \brief Returns residue information for an atom based on global atom index diff --git a/src/gromacs/topology/mtop_util.cpp b/src/gromacs/topology/mtop_util.cpp index 789a35eced..0433952b68 100644 --- a/src/gromacs/topology/mtop_util.cpp +++ b/src/gromacs/topology/mtop_util.cpp @@ -429,13 +429,15 @@ static void atomcat(t_atoms* dest, const t_atoms* src, int copies, int maxres_re /* residue information */ for (l = dest->nres, j = 0; (j < copies); j++, l += src->nres) { - memcpy(reinterpret_cast(&(dest->resinfo[l])), reinterpret_cast(&(src->resinfo[0])), + memcpy(reinterpret_cast(&(dest->resinfo[l])), + reinterpret_cast(&(src->resinfo[0])), static_cast(src->nres * sizeof(src->resinfo[0]))); } for (l = destnr, j = 0; (j < copies); j++, l += srcnr) { - memcpy(reinterpret_cast(&(dest->atom[l])), reinterpret_cast(&(src->atom[0])), + memcpy(reinterpret_cast(&(dest->atom[l])), + reinterpret_cast(&(src->atom[0])), static_cast(srcnr * sizeof(src->atom[0]))); memcpy(reinterpret_cast(&(dest->atomname[l])), reinterpret_cast(&(src->atomname[0])), @@ -495,8 +497,11 @@ t_atoms gmx_mtop_global_atoms(const gmx_mtop_t* mtop) int maxresnr = mtop->maxResNumberNotRenumbered(); for (const gmx_molblock_t& molb : mtop->molblock) { - atomcat(&atoms, &mtop->moltype[molb.type].atoms, molb.nmol, - mtop->maxResiduesPerMoleculeToTriggerRenumber(), &maxresnr); + atomcat(&atoms, + &mtop->moltype[molb.type].atoms, + molb.nmol, + mtop->maxResiduesPerMoleculeToTriggerRenumber(), + &maxresnr); } return atoms; @@ -715,10 +720,8 @@ static void copyIListsFromMtop(const gmx_mtop_t& mtop, IdefType* idef, bool merg */ for (int mol = 0; mol < molb.nmol; mol++) { - ilistcat(ftype, &idef->il[F_CONSTR], molt.ilist[F_CONSTR], 1, - destnr + mol * srcnr, srcnr); - ilistcat(ftype, &idef->il[F_CONSTR], molt.ilist[F_CONSTRNC], 1, - destnr + mol * srcnr, srcnr); + ilistcat(ftype, &idef->il[F_CONSTR], molt.ilist[F_CONSTR], 1, destnr + mol * srcnr, srcnr); + ilistcat(ftype, &idef->il[F_CONSTR], molt.ilist[F_CONSTRNC], 1, destnr + mol * srcnr, srcnr); } } else if (!(mergeConstr && ftype == F_CONSTRNC)) @@ -766,7 +769,8 @@ static void copyAtomtypesFromMtop(const gmx_mtop_t& mtop, t_atomtypes* atomtypes if (mtop.atomtypes.atomnumber) { snew(atomtypes->atomnumber, mtop.atomtypes.nr); - std::copy(mtop.atomtypes.atomnumber, mtop.atomtypes.atomnumber + mtop.atomtypes.nr, + std::copy(mtop.atomtypes.atomnumber, + mtop.atomtypes.atomnumber + mtop.atomtypes.nr, atomtypes->atomnumber); } else diff --git a/src/gromacs/topology/residuetypes.cpp b/src/gromacs/topology/residuetypes.cpp index 73aad6d57f..b60dd11802 100644 --- a/src/gromacs/topology/residuetypes.cpp +++ b/src/gromacs/topology/residuetypes.cpp @@ -135,7 +135,9 @@ void ResidueType::addResidue(const std::string& residueName, const std::string& fprintf(stderr, "Warning: Residue '%s' already present with type '%s' in database, ignoring " "new type '%s'.\n", - residueName.c_str(), (*foundIt)->residueType.c_str(), residueType.c_str()); + residueName.c_str(), + (*foundIt)->residueType.c_str(), + residueType.c_str()); } } else diff --git a/src/gromacs/topology/symtab.cpp b/src/gromacs/topology/symtab.cpp index d7432ebfaf..c6e56a5ec1 100644 --- a/src/gromacs/topology/symtab.cpp +++ b/src/gromacs/topology/symtab.cpp @@ -108,8 +108,7 @@ void StringTable::printStringTableStorageToFile(FILE* fp, int indent, const char StringTable::StringTable(gmx::ISerializer* serializer) { - GMX_RELEASE_ASSERT(serializer->reading(), - "Can not use writing serializer to read string table"); + GMX_RELEASE_ASSERT(serializer->reading(), "Can not use writing serializer to read string table"); int nr = 0; serializer->doInt(&nr); table_.resize(nr); @@ -156,8 +155,7 @@ void StringTableEntry::serialize(gmx::ISerializer* serializer) const StringTableEntry readStringTableEntry(gmx::ISerializer* serializer, const StringTable& table) { - GMX_RELEASE_ASSERT(serializer->reading(), - "Can not use writing serializer to read string index"); + GMX_RELEASE_ASSERT(serializer->reading(), "Can not use writing serializer to read string index"); int entry = 0; serializer->doInt(&entry); return table.at(entry); diff --git a/src/gromacs/topology/topology.cpp b/src/gromacs/topology/topology.cpp index 6c9bfc1d60..fc20e30d0d 100644 --- a/src/gromacs/topology/topology.cpp +++ b/src/gromacs/topology/topology.cpp @@ -56,8 +56,16 @@ #include "gromacs/utility/txtdump.h" static gmx::EnumerationArray c_simulationAtomGroupTypeShortNames = { - { "T-Coupling", "Energy Mon.", "Acceleration", "Freeze", "User1", "User2", "VCM", - "Compressed X", "Or. Res. Fit", "QMMM" } + { "T-Coupling", + "Energy Mon.", + "Acceleration", + "Freeze", + "User1", + "User2", + "VCM", + "Compressed X", + "Or. Res. Fit", + "QMMM" } }; const char* shortName(SimulationAtomGroupType type) @@ -279,8 +287,7 @@ static void pr_grps(FILE* fp, const char* title, gmx::ArrayRef(groups.groupNames.data())); - pr_strings(fp, indent, "grpname", const_cast(groups.groupNames.data()), - groups.groupNames.size(), bShowNumbers); + pr_strings(fp, + indent, + "grpname", + const_cast(groups.groupNames.data()), + groups.groupNames.size(), + bShowNumbers); pr_indent(fp, indent); fprintf(fp, "groups "); @@ -332,7 +343,8 @@ static void pr_groups(FILE* fp, int indent, const SimulationGroups& groups, gmx_ fprintf(fp, "groupnr[%5d] =", i); for (auto group : keysOf(groups.groups)) { - fprintf(fp, " %3d ", + fprintf(fp, + " %3d ", !groups.groupNumbers[group].empty() ? groups.groupNumbers[group][i] : 0); } fprintf(fp, "\n"); @@ -358,8 +370,14 @@ static void pr_moltype(FILE* fp, pr_listoflists(fp, indent, "excls", &molt->excls, bShowNumbers); for (j = 0; (j < F_NRE); j++) { - pr_ilist(fp, indent, interaction_function[j].longname, ffparams->functype.data(), - molt->ilist[j], bShowNumbers, bShowParameters, ffparams->iparams.data()); + pr_ilist(fp, + indent, + interaction_function[j].longname, + ffparams->functype.data(), + molt->ilist[j], + bShowNumbers, + bShowParameters, + ffparams->iparams.data()); } } @@ -399,23 +417,26 @@ void pr_mtop(FILE* fp, int indent, const char* title, const gmx_mtop_t* mtop, gm { pr_molblock(fp, indent, "molblock", &mtop->molblock[mb], mb, mtop->moltype); } - pr_str(fp, indent, "bIntermolecularInteractions", - gmx::boolToString(mtop->bIntermolecularInteractions)); + pr_str(fp, indent, "bIntermolecularInteractions", gmx::boolToString(mtop->bIntermolecularInteractions)); if (mtop->bIntermolecularInteractions) { for (int j = 0; j < F_NRE; j++) { - pr_ilist(fp, indent, interaction_function[j].longname, - mtop->ffparams.functype.data(), (*mtop->intermolecular_ilist)[j], - bShowNumbers, bShowParameters, mtop->ffparams.iparams.data()); + pr_ilist(fp, + indent, + interaction_function[j].longname, + mtop->ffparams.functype.data(), + (*mtop->intermolecular_ilist)[j], + bShowNumbers, + bShowParameters, + mtop->ffparams.iparams.data()); } } pr_ffparams(fp, indent, "ffparams", &(mtop->ffparams), bShowNumbers); pr_atomtypes(fp, indent, "atomtypes", &(mtop->atomtypes), bShowNumbers); for (size_t mt = 0; mt < mtop->moltype.size(); mt++) { - pr_moltype(fp, indent, "moltype", &mtop->moltype[mt], mt, &mtop->ffparams, bShowNumbers, - bShowParameters); + pr_moltype(fp, indent, "moltype", &mtop->moltype[mt], mt, &mtop->ffparams, bShowNumbers, bShowParameters); } pr_groups(fp, indent, mtop->groups, bShowNumbers); } @@ -431,8 +452,7 @@ void pr_top(FILE* fp, int indent, const char* title, const t_topology* top, gmx_ pr_atoms(fp, indent, "atoms", &(top->atoms), bShowNumbers); pr_atomtypes(fp, indent, "atomtypes", &(top->atomtypes), bShowNumbers); pr_block(fp, indent, "mols", &top->mols, bShowNumbers); - pr_str(fp, indent, "bIntermolecularInteractions", - gmx::boolToString(top->bIntermolecularInteractions)); + pr_str(fp, indent, "bIntermolecularInteractions", gmx::boolToString(top->bIntermolecularInteractions)); pr_idef(fp, indent, "idef", &top->idef, bShowNumbers, bShowParameters); } } @@ -484,8 +504,8 @@ static void cmp_iparm_AB(FILE* fp, const char* s, t_functype ft, const t_iparams bDiff = FALSE; for (i = 0; i < nrfpB && !bDiff; i++) { - bDiff = !equal_real(ip1.generic.buf[p0 + i], ip1.generic.buf[nrfpA + i], relativeTolerance, - absoluteTolerance); + bDiff = !equal_real( + ip1.generic.buf[p0 + i], ip1.generic.buf[nrfpA + i], relativeTolerance, absoluteTolerance); } if (bDiff) { @@ -517,8 +537,7 @@ static void cmp_cmap(FILE* fp, const gmx_cmap_t* cmap1, const gmx_cmap_t* cmap2, for (i = 0; i < 4 * cmap1->grid_spacing * cmap1->grid_spacing; i++) { - cmp_real(fp, "", i, cmap1->cmapdata[g].cmap[i], cmap2->cmapdata[g].cmap[i], - relativeTolerance, absoluteTolerance); + cmp_real(fp, "", i, cmap1->cmapdata[g].cmap[i], cmap2->cmapdata[g].cmap[i], relativeTolerance, absoluteTolerance); } } } @@ -555,8 +574,7 @@ static void compareFfparams(FILE* fp, std::string buf = gmx::formatString("ffparams->functype[%d]", i); cmp_int(fp, buf.c_str(), i, ff1.functype[i], ff2.functype[i]); buf = gmx::formatString("ffparams->iparams[%d]", i); - cmp_iparm(fp, buf.c_str(), ff1.functype[i], ff1.iparams[i], ff2.iparams[i], - relativeTolerance, absoluteTolerance); + cmp_iparm(fp, buf.c_str(), ff1.functype[i], ff1.iparams[i], ff2.iparams[i], relativeTolerance, absoluteTolerance); } } @@ -679,11 +697,13 @@ void compareMtop(FILE* fp, const gmx_mtop_t& mtop1, const gmx_mtop_t& mtop2, rea fprintf(fp, "comparing mtop topology\n"); cmp_str(fp, "Name", -1, *mtop1.name, *mtop2.name); cmp_int(fp, "natoms", -1, mtop1.natoms, mtop2.natoms); - cmp_int(fp, "maxres_renum", -1, mtop1.maxResiduesPerMoleculeToTriggerRenumber(), + cmp_int(fp, + "maxres_renum", + -1, + mtop1.maxResiduesPerMoleculeToTriggerRenumber(), mtop2.maxResiduesPerMoleculeToTriggerRenumber()); cmp_int(fp, "maxresnr", -1, mtop1.maxResNumberNotRenumbered(), mtop2.maxResNumberNotRenumbered()); - cmp_bool(fp, "bIntermolecularInteractions", -1, mtop1.bIntermolecularInteractions, - mtop2.bIntermolecularInteractions); + cmp_bool(fp, "bIntermolecularInteractions", -1, mtop1.bIntermolecularInteractions, mtop2.bIntermolecularInteractions); cmp_bool(fp, "haveMoleculeIndices", -1, mtop1.haveMoleculeIndices, mtop2.haveMoleculeIndices); compareFfparams(fp, mtop1.ffparams, mtop2.ffparams, relativeTolerance, absoluteTolerance); @@ -692,8 +712,8 @@ void compareMtop(FILE* fp, const gmx_mtop_t& mtop1, const gmx_mtop_t& mtop2, rea compareInteractionLists(fp, mtop1.intermolecular_ilist.get(), mtop2.intermolecular_ilist.get()); compareAtomtypes(fp, mtop1.atomtypes, mtop2.atomtypes); compareAtomGroups(fp, mtop1.groups, mtop2.groups, mtop1.natoms, mtop2.natoms); - compareIntermolecularExclusions(fp, mtop1.intermolecularExclusionGroup, - mtop2.intermolecularExclusionGroup); + compareIntermolecularExclusions( + fp, mtop1.intermolecularExclusionGroup, mtop2.intermolecularExclusionGroup); compareBlockIndices(fp, mtop1.moleculeBlockIndices, mtop2.moleculeBlockIndices); } @@ -717,19 +737,28 @@ void compareAtomGroups(FILE* fp, const SimulationGroups& g0, const SimulationGro for (gmx::index j = 0; j < gmx::ssize(g0.groups[group]); j++) { buf = gmx::formatString("grps[%d].name[%zd]", static_cast(group), j); - cmp_str(fp, buf.c_str(), -1, *g0.groupNames[g0.groups[group][j]], + cmp_str(fp, + buf.c_str(), + -1, + *g0.groupNames[g0.groups[group][j]], *g1.groupNames[g1.groups[group][j]]); } } - cmp_int(fp, "ngrpnr", static_cast(group), g0.numberOfGroupNumbers(group), + cmp_int(fp, + "ngrpnr", + static_cast(group), + g0.numberOfGroupNumbers(group), g1.numberOfGroupNumbers(group)); if (g0.numberOfGroupNumbers(group) == g1.numberOfGroupNumbers(group) && natoms0 == natoms1 && (!g0.groupNumbers[group].empty() || !g1.groupNumbers[group].empty())) { for (int j = 0; j < natoms0; j++) { - cmp_int(fp, c_simulationAtomGroupTypeShortNames[group], j, - getGroupType(g0, group, j), getGroupType(g1, group, j)); + cmp_int(fp, + c_simulationAtomGroupTypeShortNames[group], + j, + getGroupType(g0, group, j), + getGroupType(g1, group, j)); } } } diff --git a/src/gromacs/topology/topsort.cpp b/src/gromacs/topology/topsort.cpp index 5971a45094..81900500c8 100644 --- a/src/gromacs/topology/topsort.cpp +++ b/src/gromacs/topology/topsort.cpp @@ -121,10 +121,12 @@ static gmx_bool ip_pert(int ftype, const t_iparams* ip) case F_RESTRANGLES: case F_RESTRDIHS: case F_CBTDIHS: - gmx_fatal(FARGS, "Function type %s does not support currentely free energy calculations", + gmx_fatal(FARGS, + "Function type %s does not support currentely free energy calculations", interaction_function[ftype].longname); default: - gmx_fatal(FARGS, "Function type %s not implemented in ip_pert", + gmx_fatal(FARGS, + "Function type %s not implemented in ip_pert", interaction_function[ftype].longname); } @@ -241,8 +243,11 @@ void gmx_sort_ilist_fe(InteractionDefinitions* idef, const real* qA, const real* if (debug) { const int numNonperturbed = idef->numNonperturbedInteractions[ftype]; - fprintf(debug, "%s non-pert %d pert %d\n", interaction_function[ftype].longname, - numNonperturbed, ilist->size() - numNonperturbed); + fprintf(debug, + "%s non-pert %d pert %d\n", + interaction_function[ftype].longname, + numNonperturbed, + ilist->size() - numNonperturbed); } } } diff --git a/src/gromacs/trajectory/energyframe.cpp b/src/gromacs/trajectory/energyframe.cpp index 41be658f4f..5fa2cdfd55 100644 --- a/src/gromacs/trajectory/energyframe.cpp +++ b/src/gromacs/trajectory/energyframe.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2018,2019, by the GROMACS development team, led by + * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -63,7 +63,9 @@ EnergyFrame::EnergyFrame(const t_enxframe& enxframe, const std::map c_group1TypeEnumNames = { { "angle", "dihedral", - "vector", "plane" } }; +const EnumerationArray c_group1TypeEnumNames = { + { "angle", "dihedral", "vector", "plane" } +}; //! String values corresponding to Group2Type. const EnumerationArray c_group2TypeEnumNames = { { "none", "vector", "plane", "t0", "z", "sphnorm" } @@ -489,7 +490,8 @@ void Angle::initFromSelections(const SelectionList& sel1, const SelectionList& s { GMX_THROW(InconsistentInputError(formatString( "Number of positions in selection %d in the first group not divisible by %d", - static_cast(g + 1), natoms1_))); + static_cast(g + 1), + natoms1_))); } const int angleCount1 = posCount1 / natoms1_; int angleCount = angleCount1; @@ -502,7 +504,8 @@ void Angle::initFromSelections(const SelectionList& sel1, const SelectionList& s GMX_THROW(InconsistentInputError( formatString("Number of positions in selection %d in the second group not " "divisible by %d", - static_cast(g + 1), natoms2_))); + static_cast(g + 1), + natoms2_))); } if (g2type_ == Group2Type::SphereNormal && posCount2 != 1) { diff --git a/src/gromacs/trajectoryanalysis/modules/convert_trj.cpp b/src/gromacs/trajectoryanalysis/modules/convert_trj.cpp index 9673a8aaec..c5de9bd05f 100644 --- a/src/gromacs/trajectoryanalysis/modules/convert_trj.cpp +++ b/src/gromacs/trajectoryanalysis/modules/convert_trj.cpp @@ -136,7 +136,9 @@ void ConvertTrj::optionsFinished(TrajectoryAnalysisSettings* settings) void ConvertTrj::initAnalysis(const TrajectoryAnalysisSettings& /*settings*/, const TopologyInformation& top) { - output_ = createTrajectoryFrameWriter(top.mtop(), sel_, name_, + output_ = createTrajectoryFrameWriter(top.mtop(), + sel_, + name_, top.hasTopology() ? top.copyAtoms() : nullptr, requirementsBuilder_.process()); } diff --git a/src/gromacs/trajectoryanalysis/modules/distance.cpp b/src/gromacs/trajectoryanalysis/modules/distance.cpp index 6acf73ab1d..bb21423a3c 100644 --- a/src/gromacs/trajectoryanalysis/modules/distance.cpp +++ b/src/gromacs/trajectoryanalysis/modules/distance.cpp @@ -214,7 +214,8 @@ void checkSelections(const SelectionList& sel) std::string message = formatString( "Selection '%s' does not evaluate into an even number of positions " "(there are %d positions)", - sel[g].name(), sel[g].posCount()); + sel[g].name(), + sel[g].posCount()); GMX_THROW(InconsistentInputError(message)); } if (sel[g].isDynamic()) diff --git a/src/gromacs/trajectoryanalysis/modules/extract_cluster.cpp b/src/gromacs/trajectoryanalysis/modules/extract_cluster.cpp index 7e92eb0e81..9d337c01ef 100644 --- a/src/gromacs/trajectoryanalysis/modules/extract_cluster.cpp +++ b/src/gromacs/trajectoryanalysis/modules/extract_cluster.cpp @@ -185,7 +185,9 @@ void ExtractCluster::initAnalysis(const TrajectoryAnalysisSettings& /*settings*/ { std::string outputName = Path::concatenateBeforeExtension( outputNamePrefix_, formatString("_%s", clusterIndex_->grpname[i])); - writers_.emplace_back(createTrajectoryFrameWriter(top.mtop(), sel_, outputName, + writers_.emplace_back(createTrajectoryFrameWriter(top.mtop(), + sel_, + outputName, top.hasTopology() ? top.copyAtoms() : nullptr, requirementsBuilder_.process())); } diff --git a/src/gromacs/trajectoryanalysis/modules/freevolume.cpp b/src/gromacs/trajectoryanalysis/modules/freevolume.cpp index 2597e359ea..83eacf7f3f 100644 --- a/src/gromacs/trajectoryanalysis/modules/freevolume.cpp +++ b/src/gromacs/trajectoryanalysis/modules/freevolume.cpp @@ -265,8 +265,10 @@ void FreeVolume::initAnalysis(const TrajectoryAnalysisSettings& settings, const nnovdw++; if (nnovdw < maxnovdw) { - fprintf(stderr, "Could not determine VDW radius for %s-%s. Set to zero.\n", - *(atoms->resinfo[resnr].name), *(atoms->atomname[i])); + fprintf(stderr, + "Could not determine VDW radius for %s-%s. Set to zero.\n", + *(atoms->resinfo[resnr].name), + *(atoms->atomname[i])); } vdw_radius_.push_back(0.0); } diff --git a/src/gromacs/trajectoryanalysis/modules/pairdist.cpp b/src/gromacs/trajectoryanalysis/modules/pairdist.cpp index e5e27165d3..2193089b99 100644 --- a/src/gromacs/trajectoryanalysis/modules/pairdist.cpp +++ b/src/gromacs/trajectoryanalysis/modules/pairdist.cpp @@ -98,8 +98,9 @@ enum class GroupType : int //! Strings corresponding to DistanceType. const EnumerationArray c_distanceTypeNames = { { "min", "max" } }; //! Strings corresponding to GroupType. -const EnumerationArray c_groupTypeNames = { { "all", "res", "mol", - "none" } }; +const EnumerationArray c_groupTypeNames = { + { "all", "res", "mol", "none" } +}; /*! \brief * Implements `gmx pairdist` trajectory analysis module. diff --git a/src/gromacs/trajectoryanalysis/modules/sasa.cpp b/src/gromacs/trajectoryanalysis/modules/sasa.cpp index 502f51d073..d48f4df9de 100644 --- a/src/gromacs/trajectoryanalysis/modules/sasa.cpp +++ b/src/gromacs/trajectoryanalysis/modules/sasa.cpp @@ -439,7 +439,8 @@ void Sasa::initOptions(IOptionsContainer* options, TrajectoryAnalysisSettings* s "from the full surface.[PAR]", "The average and standard deviation of the area over the trajectory", - "can be calculated per residue and atom (options [TT]-or[tt] and", "[TT]-oa[tt]).[PAR]", + "can be calculated per residue and atom (options [TT]-or[tt] and", + "[TT]-oa[tt]).[PAR]", //"In combination with the latter option an [REF].itp[ref] file can be", //"generated (option [TT]-i[tt])", //"which can be used to restrain surface atoms.[PAR]", @@ -610,8 +611,8 @@ void Sasa::initAnalysis(const TrajectoryAnalysisSettings& settings, const Topolo if (bDGsol) { real dgsFactor; - if (!aps.setAtomProperty(epropDGsol, *(atoms_->resinfo[resind].name), - *(atoms_->atomtype[ii]), &dgsFactor)) + if (!aps.setAtomProperty( + epropDGsol, *(atoms_->resinfo[resind].name), *(atoms_->atomtype[ii]), &dgsFactor)) { dgsFactor = dgsDefault_; } @@ -640,7 +641,8 @@ void Sasa::initAnalysis(const TrajectoryAnalysisSettings& settings, const Topolo "Output selection '%s' is not a subset of " "the surface selection (atom %d is the first " "atom not in the surface selection)", - outputSel_[g].name(), outputIndices[i] + 1); + outputSel_[g].name(), + outputIndices[i] + 1); GMX_THROW(InconsistentInputError(message)); } outputSel_[g].setOriginalId(i, j); @@ -950,8 +952,15 @@ void Sasa::analyzeFrame(int frnr, const t_trxframe& fr, t_pbc* pbc, TrajectoryAn real totarea, totvolume; real *area = nullptr, *surfacedots = nullptr; int nsurfacedots; - calculator_.calculate(surfaceSel.coordinates().data(), pbc, frameData.index_.size(), - frameData.index_.data(), flag, &totarea, &totvolume, &area, &surfacedots, + calculator_.calculate(surfaceSel.coordinates().data(), + pbc, + frameData.index_.size(), + frameData.index_.data(), + flag, + &totarea, + &totvolume, + &area, + &surfacedots, &nsurfacedots); // Unpack the atomwise areas into the frameData.atomAreas_ array for easier // indexing in the case of dynamic surfaceSel. @@ -985,8 +994,15 @@ void Sasa::analyzeFrame(int frnr, const t_trxframe& fr, t_pbc* pbc, TrajectoryAn // structures. But since it is only used in the first frame, and no // one else uses the topology after initialization, it may just work // even with future parallelization. - connolly_plot(fnConnolly_.c_str(), nsurfacedots, surfacedots, fr.x, atoms_.get(), - &mtop_->symtab, fr.pbcType, fr.box, bIncludeSolute_); + connolly_plot(fnConnolly_.c_str(), + nsurfacedots, + surfacedots, + fr.x, + atoms_.get(), + &mtop_->symtab, + fr.pbcType, + fr.box, + bIncludeSolute_); } ah.startFrame(frnr, fr.time); @@ -1005,8 +1021,15 @@ void Sasa::analyzeFrame(int frnr, const t_trxframe& fr, t_pbc* pbc, TrajectoryAn real totalArea, dgsolv; if (bResAt || bDGsol) { - computeAreas(surfaceSel, surfaceSel, frameData.atomAreas_, dgsFactor_, &totalArea, &dgsolv, - aah, rah, &frameData.res_a_); + computeAreas(surfaceSel, + surfaceSel, + frameData.atomAreas_, + dgsFactor_, + &totalArea, + &dgsolv, + aah, + rah, + &frameData.res_a_); if (bDGsol) { dgh.setPoint(0, dgsolv); @@ -1019,8 +1042,15 @@ void Sasa::analyzeFrame(int frnr, const t_trxframe& fr, t_pbc* pbc, TrajectoryAn aah.selectDataSet(g + 1); rah.selectDataSet(g + 1); } - computeAreas(surfaceSel, outputSel[g], frameData.atomAreas_, dgsFactor_, &totalArea, - &dgsolv, aah, rah, &frameData.res_a_); + computeAreas(surfaceSel, + outputSel[g], + frameData.atomAreas_, + dgsFactor_, + &totalArea, + &dgsolv, + aah, + rah, + &frameData.res_a_); ah.setPoint(g + 1, totalArea); if (bDGsol) { diff --git a/src/gromacs/trajectoryanalysis/modules/select.cpp b/src/gromacs/trajectoryanalysis/modules/select.cpp index 77fec1d469..6ccc686d75 100644 --- a/src/gromacs/trajectoryanalysis/modules/select.cpp +++ b/src/gromacs/trajectoryanalysis/modules/select.cpp @@ -275,8 +275,9 @@ enum class PdbAtomsSelection : int const EnumerationArray c_residueNumberingTypeNames = { { "number", "index" } }; //! String values corresponding to PdbAtomsSelection. -const EnumerationArray c_pdbAtomsTypeNames = { { "all", "maxsel", - "selected" } }; +const EnumerationArray c_pdbAtomsTypeNames = { + { "all", "maxsel", "selected" } +}; class Select : public TrajectoryAnalysisModule { diff --git a/src/gromacs/trajectoryanalysis/modules/surfacearea.cpp b/src/gromacs/trajectoryanalysis/modules/surfacearea.cpp index 1e28faf599..d1a4c6d2a7 100644 --- a/src/gromacs/trajectoryanalysis/modules/surfacearea.cpp +++ b/src/gromacs/trajectoryanalysis/modules/surfacearea.cpp @@ -193,8 +193,17 @@ static std::vector ico_dot_arc(int densit) for (tl = 1; tl < tess; tl++) { GMX_ASSERT(tn < ndot, "Inconsistent precomputed surface dot count"); - divarc(xus[3 * i], xus[1 + 3 * i], xus[2 + 3 * i], xus[3 * j], xus[1 + 3 * j], - xus[2 + 3 * j], tl, tess, &xus[3 * tn], &xus[1 + 3 * tn], &xus[2 + 3 * tn]); + divarc(xus[3 * i], + xus[1 + 3 * i], + xus[2 + 3 * i], + xus[3 * j], + xus[1 + 3 * j], + xus[2 + 3 * j], + tl, + tess, + &xus[3 * tn], + &xus[1 + 3 * tn], + &xus[2 + 3 * tn]); tn++; } } @@ -233,21 +242,75 @@ static std::vector ico_dot_arc(int densit) } for (tl = 1; tl < tess - 1; tl++) { - divarc(xus[3 * j], xus[1 + 3 * j], xus[2 + 3 * j], xus[3 * i], - xus[1 + 3 * i], xus[2 + 3 * i], tl, tess, &xji, &yji, &zji); - divarc(xus[3 * k], xus[1 + 3 * k], xus[2 + 3 * k], xus[3 * i], - xus[1 + 3 * i], xus[2 + 3 * i], tl, tess, &xki, &yki, &zki); + divarc(xus[3 * j], + xus[1 + 3 * j], + xus[2 + 3 * j], + xus[3 * i], + xus[1 + 3 * i], + xus[2 + 3 * i], + tl, + tess, + &xji, + &yji, + &zji); + divarc(xus[3 * k], + xus[1 + 3 * k], + xus[2 + 3 * k], + xus[3 * i], + xus[1 + 3 * i], + xus[2 + 3 * i], + tl, + tess, + &xki, + &yki, + &zki); for (tl2 = 1; tl2 < tess - tl; tl2++) { - divarc(xus[3 * i], xus[1 + 3 * i], xus[2 + 3 * i], xus[3 * j], - xus[1 + 3 * j], xus[2 + 3 * j], tl2, tess, &xij, &yij, &zij); - divarc(xus[3 * k], xus[1 + 3 * k], xus[2 + 3 * k], xus[3 * j], - xus[1 + 3 * j], xus[2 + 3 * j], tl2, tess, &xkj, &ykj, &zkj); - divarc(xus[3 * i], xus[1 + 3 * i], xus[2 + 3 * i], xus[3 * k], xus[1 + 3 * k], - xus[2 + 3 * k], tess - tl - tl2, tess, &xik, &yik, &zik); - divarc(xus[3 * j], xus[1 + 3 * j], xus[2 + 3 * j], xus[3 * k], xus[1 + 3 * k], - xus[2 + 3 * k], tess - tl - tl2, tess, &xjk, &yjk, &zjk); + divarc(xus[3 * i], + xus[1 + 3 * i], + xus[2 + 3 * i], + xus[3 * j], + xus[1 + 3 * j], + xus[2 + 3 * j], + tl2, + tess, + &xij, + &yij, + &zij); + divarc(xus[3 * k], + xus[1 + 3 * k], + xus[2 + 3 * k], + xus[3 * j], + xus[1 + 3 * j], + xus[2 + 3 * j], + tl2, + tess, + &xkj, + &ykj, + &zkj); + divarc(xus[3 * i], + xus[1 + 3 * i], + xus[2 + 3 * i], + xus[3 * k], + xus[1 + 3 * k], + xus[2 + 3 * k], + tess - tl - tl2, + tess, + &xik, + &yik, + &zik); + divarc(xus[3 * j], + xus[1 + 3 * j], + xus[2 + 3 * j], + xus[3 * k], + xus[1 + 3 * k], + xus[2 + 3 * k], + tess - tl - tl2, + tess, + &xjk, + &yjk, + &zjk); divarc(xki, yki, zki, xji, yji, zji, tl2, tess - tl, &x, &y, &z); divarc(xkj, ykj, zkj, xij, yij, zij, tl, tess - tl2, &x2, &y2, &z2); divarc(xjk, yjk, zjk, xik, yik, zik, tl, tl + tl2, &x3, &y3, &z3); @@ -368,8 +431,17 @@ static std::vector ico_dot_dod(int densit) for (tl = 1; tl < tess; tl++) { GMX_ASSERT(tn < ndot, "Inconsistent precomputed surface dot count"); - divarc(xus[3 * i], xus[1 + 3 * i], xus[2 + 3 * i], xus[3 * j], xus[1 + 3 * j], - xus[2 + 3 * j], tl, tess, &xus[3 * tn], &xus[1 + 3 * tn], &xus[2 + 3 * tn]); + divarc(xus[3 * i], + xus[1 + 3 * i], + xus[2 + 3 * i], + xus[3 * j], + xus[1 + 3 * j], + xus[2 + 3 * j], + tl, + tess, + &xus[3 * tn], + &xus[1 + 3 * tn], + &xus[2 + 3 * tn]); tn++; } } @@ -408,21 +480,75 @@ static std::vector ico_dot_dod(int densit) } for (tl = 1; tl < tess - 1; tl++) { - divarc(xus[3 * j], xus[1 + 3 * j], xus[2 + 3 * j], xus[3 * i], - xus[1 + 3 * i], xus[2 + 3 * i], tl, tess, &xji, &yji, &zji); - divarc(xus[3 * k], xus[1 + 3 * k], xus[2 + 3 * k], xus[3 * i], - xus[1 + 3 * i], xus[2 + 3 * i], tl, tess, &xki, &yki, &zki); + divarc(xus[3 * j], + xus[1 + 3 * j], + xus[2 + 3 * j], + xus[3 * i], + xus[1 + 3 * i], + xus[2 + 3 * i], + tl, + tess, + &xji, + &yji, + &zji); + divarc(xus[3 * k], + xus[1 + 3 * k], + xus[2 + 3 * k], + xus[3 * i], + xus[1 + 3 * i], + xus[2 + 3 * i], + tl, + tess, + &xki, + &yki, + &zki); for (tl2 = 1; tl2 < tess - tl; tl2++) { - divarc(xus[3 * i], xus[1 + 3 * i], xus[2 + 3 * i], xus[3 * j], - xus[1 + 3 * j], xus[2 + 3 * j], tl2, tess, &xij, &yij, &zij); - divarc(xus[3 * k], xus[1 + 3 * k], xus[2 + 3 * k], xus[3 * j], - xus[1 + 3 * j], xus[2 + 3 * j], tl2, tess, &xkj, &ykj, &zkj); - divarc(xus[3 * i], xus[1 + 3 * i], xus[2 + 3 * i], xus[3 * k], xus[1 + 3 * k], - xus[2 + 3 * k], tess - tl - tl2, tess, &xik, &yik, &zik); - divarc(xus[3 * j], xus[1 + 3 * j], xus[2 + 3 * j], xus[3 * k], xus[1 + 3 * k], - xus[2 + 3 * k], tess - tl - tl2, tess, &xjk, &yjk, &zjk); + divarc(xus[3 * i], + xus[1 + 3 * i], + xus[2 + 3 * i], + xus[3 * j], + xus[1 + 3 * j], + xus[2 + 3 * j], + tl2, + tess, + &xij, + &yij, + &zij); + divarc(xus[3 * k], + xus[1 + 3 * k], + xus[2 + 3 * k], + xus[3 * j], + xus[1 + 3 * j], + xus[2 + 3 * j], + tl2, + tess, + &xkj, + &ykj, + &zkj); + divarc(xus[3 * i], + xus[1 + 3 * i], + xus[2 + 3 * i], + xus[3 * k], + xus[1 + 3 * k], + xus[2 + 3 * k], + tess - tl - tl2, + tess, + &xik, + &yik, + &zik); + divarc(xus[3 * j], + xus[1 + 3 * j], + xus[2 + 3 * j], + xus[3 * k], + xus[1 + 3 * k], + xus[2 + 3 * k], + tess - tl - tl2, + tess, + &xjk, + &yjk, + &zjk); divarc(xki, yki, zki, xji, yji, zji, tl2, tess - tl, &x, &y, &z); divarc(xkj, ykj, zkj, xij, yij, zij, tl, tess - tl2, &x2, &y2, &z2); divarc(xjk, yjk, zjk, xik, yik, zik, tl, tl + tl2, &x3, &y3, &z3); @@ -875,8 +1001,20 @@ void SurfaceAreaCalculator::calculate(const rvec* x, { *n_dots = 0; } - nsc_dclm_pbc(x, impl_->radius_, nat, &impl_->unitSphereDots_[0], impl_->unitSphereDots_.size() / 3, - flags, area, at_area, volume, lidots, n_dots, index, &impl_->nb_, pbc); + nsc_dclm_pbc(x, + impl_->radius_, + nat, + &impl_->unitSphereDots_[0], + impl_->unitSphereDots_.size() / 3, + flags, + area, + at_area, + volume, + lidots, + n_dots, + index, + &impl_->nb_, + pbc); } } // namespace gmx diff --git a/src/gromacs/trajectoryanalysis/runnercommon.cpp b/src/gromacs/trajectoryanalysis/runnercommon.cpp index 2807d5894e..4fdf2768d5 100644 --- a/src/gromacs/trajectoryanalysis/runnercommon.cpp +++ b/src/gromacs/trajectoryanalysis/runnercommon.cpp @@ -230,7 +230,8 @@ void TrajectoryAnalysisRunnerCommon::Impl::initFirstFrame() { const std::string message = formatString("Trajectory (%d atoms) does not match topology (%d atoms)", - fr->natoms, topologyAtomCount); + fr->natoms, + topologyAtomCount); GMX_THROW(InconsistentInputError(message)); } } @@ -280,7 +281,8 @@ void TrajectoryAnalysisRunnerCommon::Impl::initFrameIndexGroup() const std::string message = formatString( "Selection specified with -fgroup has %d atoms, but " "the trajectory (-f) has %d atoms.", - trajectoryGroup_.atomCount(), fr->natoms); + trajectoryGroup_.atomCount(), + fr->natoms); GMX_THROW(InconsistentInputError(message)); } fr->bIndex = TRUE; diff --git a/src/gromacs/trajectoryanalysis/tests/convert_trj.cpp b/src/gromacs/trajectoryanalysis/tests/convert_trj.cpp index 004491019c..f1aea17efe 100644 --- a/src/gromacs/trajectoryanalysis/tests/convert_trj.cpp +++ b/src/gromacs/trajectoryanalysis/tests/convert_trj.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -95,8 +95,9 @@ TEST_F(ConvertTrjModuleTest, WorksWithAtomAdding) TEST_F(ConvertTrjModuleTest, WorksWithAtomsAndSelection) { - const char* const cmdline[] = { "convert-trj", "-atoms", "always-from-structure", "-select", - "not resname = CO2" }; + const char* const cmdline[] = { + "convert-trj", "-atoms", "always-from-structure", "-select", "not resname = CO2" + }; // TODO check output structures once this is supported. setTopology("clustsize.tpr"); setInputFile("-f", "clustsize.pdb"); diff --git a/src/gromacs/trajectoryanalysis/tests/extract_cluster.cpp b/src/gromacs/trajectoryanalysis/tests/extract_cluster.cpp index 2493d52c2a..d18cf47d82 100644 --- a/src/gromacs/trajectoryanalysis/tests/extract_cluster.cpp +++ b/src/gromacs/trajectoryanalysis/tests/extract_cluster.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -146,8 +146,9 @@ TEST_F(ExtractClusterModuleTest, WorksWithAllAtoms) TEST_F(ExtractClusterModuleTest, WorksWithAtomSubset) { std::string realFileName = TestFileManager::getTestSpecificFileName("test.g96"); - const char* const cmdline[] = { "extract-cluster", "-o", realFileName.c_str(), "-select", - "atomnr 1 2" }; + const char* const cmdline[] = { + "extract-cluster", "-o", realFileName.c_str(), "-select", "atomnr 1 2" + }; runTest(CommandLine(cmdline)); compareFiles(); diff --git a/src/gromacs/trajectoryanalysis/tests/moduletest.cpp b/src/gromacs/trajectoryanalysis/tests/moduletest.cpp index 228fd8ee46..bb1e0594f0 100644 --- a/src/gromacs/trajectoryanalysis/tests/moduletest.cpp +++ b/src/gromacs/trajectoryanalysis/tests/moduletest.cpp @@ -207,8 +207,8 @@ void AbstractTrajectoryAnalysisModuleTestFixture::runTest(const CommandLine& arg { const char* const name = dataset->first.c_str(); AbstractAnalysisData& data = module.datasetFromName(name); - AnalysisDataTestFixture::addReferenceCheckerModule(dataChecker, name, &data, - dataset->second.tolerance); + AnalysisDataTestFixture::addReferenceCheckerModule( + dataChecker, name, &data, dataset->second.tolerance); } } } diff --git a/src/gromacs/trajectoryanalysis/tests/rdf.cpp b/src/gromacs/trajectoryanalysis/tests/rdf.cpp index 8bae34f47d..4fa13642e8 100644 --- a/src/gromacs/trajectoryanalysis/tests/rdf.cpp +++ b/src/gromacs/trajectoryanalysis/tests/rdf.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2014,2015,2019, by the GROMACS development team, led by + * Copyright (c) 2014,2015,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -84,11 +84,16 @@ TEST_F(RdfModuleTest, BasicTest) TEST_F(RdfModuleTest, SelectionsSolelyFromIndexFileWork) { - const char* const cmdline[] = { "rdf", "-bin", "0.05", + const char* const cmdline[] = { "rdf", + "-bin", + "0.05", // Use selection that names a group in the index file - "-ref", "name_OW", + "-ref", + "name_OW", // Use selections that name groups in the index file - "-sel", "name_OW", "not_name_OW" }; + "-sel", + "name_OW", + "not_name_OW" }; // Note not supplying a topology file to -s setTrajectory("spc216.gro"); setInputFile("-n", "index.ndx"); @@ -99,11 +104,16 @@ TEST_F(RdfModuleTest, SelectionsSolelyFromIndexFileWork) TEST_F(RdfModuleTest, SelectionsFromBothTopologyFileAndIndexFileWork) { - const char* const cmdline[] = { "rdf", "-bin", "0.05", + const char* const cmdline[] = { "rdf", + "-bin", + "0.05", // Use selection whose parsing requires topology file - "-ref", "name OW", + "-ref", + "name OW", // Use selections that name groups in the index file - "-sel", "name_OW", "not_name_OW" }; + "-sel", + "name_OW", + "not_name_OW" }; // Note supplying a topology file to -s setTopology("spc216.gro"); setInputFile("-n", "index.ndx"); diff --git a/src/gromacs/trajectoryanalysis/tests/select.cpp b/src/gromacs/trajectoryanalysis/tests/select.cpp index 5e6487ea51..16edcaf6f0 100644 --- a/src/gromacs/trajectoryanalysis/tests/select.cpp +++ b/src/gromacs/trajectoryanalysis/tests/select.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2012,2013,2014,2015,2019, by the GROMACS development team, led by + * Copyright (c) 2012,2013,2014,2015,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -143,8 +143,9 @@ TEST_F(SelectModuleTest, WritesResidueNumbers) TEST_F(SelectModuleTest, WritesResidueIndices) { - const char* const cmdline[] = { "select", "-select", "res_com of resname RA RD", "-resnr", - "index" }; + const char* const cmdline[] = { + "select", "-select", "res_com of resname RA RD", "-resnr", "index" + }; setTopology("simple.gro"); includeDataset("index"); runTest(CommandLine(cmdline)); diff --git a/src/gromacs/trajectoryanalysis/tests/surfacearea.cpp b/src/gromacs/trajectoryanalysis/tests/surfacearea.cpp index 1bb99bac10..27ec3a30ff 100644 --- a/src/gromacs/trajectoryanalysis/tests/surfacearea.cpp +++ b/src/gromacs/trajectoryanalysis/tests/surfacearea.cpp @@ -147,8 +147,16 @@ public: gmx::SurfaceAreaCalculator calculator; calculator.setDotCount(ndots); calculator.setRadii(radius_); - calculator.calculate(as_rvec_array(x_.data()), bPBC ? &pbc : nullptr, index_.size(), - index_.data(), flags, &area_, &volume_, &atomArea_, &dots_, &dotCount_); + calculator.calculate(as_rvec_array(x_.data()), + bPBC ? &pbc : nullptr, + index_.size(), + index_.data(), + flags, + &area_, + &volume_, + &atomArea_, + &dots_, + &dotCount_); } real resultArea() const { return area_; } real resultVolume() const { return volume_; } diff --git a/src/gromacs/trajectoryanalysis/tests/test_selection.cpp b/src/gromacs/trajectoryanalysis/tests/test_selection.cpp index 2a04f0d225..baf3dcb253 100644 --- a/src/gromacs/trajectoryanalysis/tests/test_selection.cpp +++ b/src/gromacs/trajectoryanalysis/tests/test_selection.cpp @@ -2,7 +2,7 @@ * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2010-2018, The GROMACS development team. - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -144,8 +144,14 @@ void SelectionTester::analyzeFrame(int /*frnr*/, for (int i = 0; i < n; ++i) { const SelectionPosition& p = sel.position(i); - fprintf(stderr, " (%.2f,%.2f,%.2f) r=%d, m=%d, n=%d\n", p.x()[XX], p.x()[YY], - p.x()[ZZ], p.refId(), p.mappedId(), p.atomCount()); + fprintf(stderr, + " (%.2f,%.2f,%.2f) r=%d, m=%d, n=%d\n", + p.x()[XX], + p.x()[YY], + p.x()[ZZ], + p.refId(), + p.mappedId(), + p.atomCount()); } if (n < sel.posCount()) { diff --git a/src/gromacs/utility/binaryinformation.cpp b/src/gromacs/utility/binaryinformation.cpp index 7127a5b4d5..ae0ee9dbcd 100644 --- a/src/gromacs/utility/binaryinformation.cpp +++ b/src/gromacs/utility/binaryinformation.cpp @@ -154,7 +154,8 @@ void printCopyright(gmx::TextWriter* writer) static const char* const CopyrightText[] = { "Copyright (c) 1991-2000, University of Groningen, The Netherlands.", "Copyright (c) 2001-2019, The GROMACS development team at", - "Uppsala University, Stockholm University and", "the Royal Institute of Technology, Sweden.", + "Uppsala University, Stockholm University and", + "the Royal Institute of Technology, Sweden.", "check out http://www.gromacs.org for more information." }; @@ -318,8 +319,8 @@ void gmx_print_version_info(gmx::TextWriter* writer) #if HAVE_EXTRAE unsigned major, minor, revision; Extrae_get_version(&major, &minor, &revision); - writer->writeLine(formatString("Tracing support: enabled. Using Extrae-%d.%d.%d", major, - minor, revision)); + writer->writeLine(formatString( + "Tracing support: enabled. Using Extrae-%d.%d.%d", major, minor, revision)); #else writer->writeLine("Tracing support: disabled"); #endif @@ -329,15 +330,15 @@ void gmx_print_version_info(gmx::TextWriter* writer) * them. Can wait for later, as the master branch has ready code to do all * that. */ writer->writeLine(formatString("C compiler: %s", BUILD_C_COMPILER)); - writer->writeLine(formatString("C compiler flags: %s %s", BUILD_CFLAGS, - CMAKE_BUILD_CONFIGURATION_C_FLAGS)); + writer->writeLine(formatString( + "C compiler flags: %s %s", BUILD_CFLAGS, CMAKE_BUILD_CONFIGURATION_C_FLAGS)); writer->writeLine(formatString("C++ compiler: %s", BUILD_CXX_COMPILER)); - writer->writeLine(formatString("C++ compiler flags: %s %s", BUILD_CXXFLAGS, - CMAKE_BUILD_CONFIGURATION_CXX_FLAGS)); + writer->writeLine(formatString( + "C++ compiler flags: %s %s", BUILD_CXXFLAGS, CMAKE_BUILD_CONFIGURATION_CXX_FLAGS)); #ifdef HAVE_LIBMKL /* MKL might be used for LAPACK/BLAS even if FFTs use FFTW, so keep it separate */ - writer->writeLine(formatString("Linked with Intel MKL version %d.%d.%d.", __INTEL_MKL__, - __INTEL_MKL_MINOR__, __INTEL_MKL_UPDATE__)); + writer->writeLine(formatString( + "Linked with Intel MKL version %d.%d.%d.", __INTEL_MKL__, __INTEL_MKL_MINOR__, __INTEL_MKL_UPDATE__)); #endif #if GMX_GPU_OPENCL writer->writeLine(formatString("OpenCL include dir: %s", OPENCL_INCLUDE_DIR)); @@ -346,8 +347,8 @@ void gmx_print_version_info(gmx::TextWriter* writer) #endif #if GMX_GPU_CUDA writer->writeLine(formatString("CUDA compiler: %s", CUDA_COMPILER_INFO)); - writer->writeLine(formatString("CUDA compiler flags:%s %s", CUDA_COMPILER_FLAGS, - CMAKE_BUILD_CONFIGURATION_CXX_FLAGS)); + writer->writeLine(formatString( + "CUDA compiler flags:%s %s", CUDA_COMPILER_FLAGS, CMAKE_BUILD_CONFIGURATION_CXX_FLAGS)); writer->writeLine("CUDA driver: " + gmx::getCudaDriverVersionString()); writer->writeLine("CUDA runtime: " + gmx::getCudaRuntimeVersionString()); #endif @@ -424,8 +425,8 @@ void printBinaryInformation(TextWriter* writer, // necessary to read stuff above the copyright notice. // The line above the copyright notice puts the copyright notice is // context, though. - writer->writeLine(formatString("%sGROMACS: %s, version %s%s%s", prefix, name, - gmx_version(), precisionString, suffix)); + writer->writeLine(formatString( + "%sGROMACS: %s, version %s%s%s", prefix, name, gmx_version(), precisionString, suffix)); } const char* const binaryPath = programContext.fullBinaryPath(); if (!gmx::isNullOrEmpty(binaryPath)) @@ -435,8 +436,11 @@ void printBinaryInformation(TextWriter* writer, const gmx::InstallationPrefixInfo installPrefix = programContext.installationPrefix(); if (!gmx::isNullOrEmpty(installPrefix.path)) { - writer->writeLine(formatString("%sData prefix: %s%s%s", prefix, installPrefix.path, - installPrefix.bSourceLayout ? " (source tree)" : "", suffix)); + writer->writeLine(formatString("%sData prefix: %s%s%s", + prefix, + installPrefix.path, + installPrefix.bSourceLayout ? " (source tree)" : "", + suffix)); } const std::string workingDir = Path::getWorkingDirectory(); if (!workingDir.empty()) @@ -450,8 +454,8 @@ void printBinaryInformation(TextWriter* writer, const char* const commandLine = programContext.commandLine(); if (!gmx::isNullOrEmpty(commandLine)) { - writer->writeLine(formatString("%sCommand line:%s\n%s %s%s", prefix, suffix, prefix, - commandLine, suffix)); + writer->writeLine(formatString( + "%sCommand line:%s\n%s %s%s", prefix, suffix, prefix, commandLine, suffix)); } if (settings.bExtendedInfo_) { diff --git a/src/gromacs/utility/coolstuff.cpp b/src/gromacs/utility/coolstuff.cpp index 14c0f1561a..6dd122ea86 100644 --- a/src/gromacs/utility/coolstuff.cpp +++ b/src/gromacs/utility/coolstuff.cpp @@ -395,8 +395,7 @@ std::string getCoolQuote() { "Disturb the Peace of a John Q Citizen", "Urban Dance Squad" }, { "Wicky-wicky Wa-wild West", "Will Smith" }, { "This is Tense !", "Star Wars Episode I The Phantom Menace" }, - { "Fly to the Court of England and Unfold", - "Macbeth, Act 3, Scene 6, William Shakespeare" }, + { "Fly to the Court of England and Unfold", "Macbeth, Act 3, Scene 6, William Shakespeare" }, { "Why, how now, Claudio ! Whence Comes this Restraint ?", "Lucio in Measure for measure, Act 1, Scene 4, William Shakespeare" }, { "In the End Science Comes Down to Praying", "P. v.d. Berg" }, @@ -454,8 +453,7 @@ std::string getCoolQuote() { "Nobody Never Learnt No-Nothing from No History", "Gogol Bordello" }, { "I'd be Safe and Warm if I was in L.A.", "The Mamas and the Papas" }, { "It's Unacceptable That Chocolate Makes You Fat", "MI 3" }, - { "My Brothers are Protons (Protons!), My Sisters are Neurons (Neurons)", - "Gogol Bordello" }, + { "My Brothers are Protons (Protons!), My Sisters are Neurons (Neurons)", "Gogol Bordello" }, { "Put Me Inside SSC, Let's Test Superstring Theory, Oh Yoi Yoi Accelerate the Protons", "Gogol Bordello" }, { "Do You Have Sex Maniacs or Schizophrenics or Astrophysicists in Your Family?", @@ -536,8 +534,7 @@ std::string getCoolQuote() { "The scientific method is an integral part of human intelligence, and when it has once " "been set at work it can only be dismissed by dismissing the intelligence itself", "George H. Mead" }, - { "Der Ball ist rund, das Spiel dauert 90 minuten, alles andere ist Theorie", - "Lola rennt" }, + { "Der Ball ist rund, das Spiel dauert 90 minuten, alles andere ist Theorie", "Lola rennt" }, { "Life in the streets is not easy", "Marky Mark" }, { "How will I know it's working right?", "MGMT" }, { "There was no preconception on what to do", "Daft Punk" }, @@ -1309,8 +1306,7 @@ std::string getCoolQuote() { "All sorts of things can happen when you're open to new ideas and playing around with " "things.", "Stephanie Kwolek, inventor of Kevlar" }, - { "As always in life, people want a simple answer... and it's always wrong.", - "Marie Daly" }, + { "As always in life, people want a simple answer... and it's always wrong.", "Marie Daly" }, { "For a research worker the unforgotten moments of his life are those rare ones which " "come after years of plodding work, when the veil over natures secret seems suddenly to " "lift & when what was dark & chaotic appears in a clear & beautiful light & pattern.", @@ -1380,8 +1376,7 @@ std::string getCoolQuote() "3-phosphoshikimate-carboxyvinyl transferase?' Shopkeeper: 'You mean Roundup?' " "Scientist: 'Yeah, that's it. I can never remember that dang name!'", "John Pickett" }, - { "It is not clear that intelligence has any long-term survival value.", - "Stephen Hawking" }, + { "It is not clear that intelligence has any long-term survival value.", "Stephen Hawking" }, { "The greatest shortcoming of the human race is our inability to understand the " "exponential function.", "Albert Bartlett" }, diff --git a/src/gromacs/utility/cstringutil.cpp b/src/gromacs/utility/cstringutil.cpp index 576f793527..0d1a14a7d1 100644 --- a/src/gromacs/utility/cstringutil.cpp +++ b/src/gromacs/utility/cstringutil.cpp @@ -98,7 +98,9 @@ char* fgets2(char* line, int n, FILE* stream) gmx_fatal(FARGS, "An input file contains a line longer than %d characters, while the buffer " "passed to fgets2 has size %d. The line starts with: '%20.20s'", - n, n, line); + n, + n, + line); } } if ((c = strchr(line, '\r')) != nullptr) diff --git a/src/gromacs/utility/directoryenumerator.cpp b/src/gromacs/utility/directoryenumerator.cpp index 6631b74c97..838bdee3d4 100644 --- a/src/gromacs/utility/directoryenumerator.cpp +++ b/src/gromacs/utility/directoryenumerator.cpp @@ -139,8 +139,8 @@ public: } else { - GMX_THROW_WITH_ERRNO(FileIOError("Failed to list files in a directory"), - "_findnext", errno); + GMX_THROW_WITH_ERRNO( + FileIOError("Failed to list files in a directory"), "_findnext", errno); } } *filename = finddata.name; diff --git a/src/gromacs/utility/exceptions.cpp b/src/gromacs/utility/exceptions.cpp index 784cf34b25..0bda422e35 100644 --- a/src/gromacs/utility/exceptions.cpp +++ b/src/gromacs/utility/exceptions.cpp @@ -340,8 +340,7 @@ public: std::fprintf(fp_, "%*sReason: %s\n", indent, "", std::strerror(errorNumber)); if (funcName != nullptr) { - std::fprintf(fp_, "%*s(call to %s() returned error code %d)\n", indent, "", funcName, - errorNumber); + std::fprintf(fp_, "%*s(call to %s() returned error code %d)\n", indent, "", funcName, errorNumber); } } @@ -467,8 +466,8 @@ void formatExceptionMessageInternal(IMessageWriter* writer, const std::exception if (errorNumber != nullptr && *errorNumber != 0) { const char* const* funcName = gmxEx->getInfo(); - writer->writeErrNoInfo(*errorNumber, funcName != nullptr ? *funcName : nullptr, - (indent + 1) * 2); + writer->writeErrNoInfo( + *errorNumber, funcName != nullptr ? *funcName : nullptr, (indent + 1) * 2); bAnythingWritten = true; } diff --git a/src/gromacs/utility/fatalerror.cpp b/src/gromacs/utility/fatalerror.cpp index f29b400a80..6d9a347b5b 100644 --- a/src/gromacs/utility/fatalerror.cpp +++ b/src/gromacs/utility/fatalerror.cpp @@ -254,7 +254,10 @@ void _range_check(int n, int n_min, int n_max, const char* warn_str, const char* buf += gmx::formatString( "Variable %s has value %d. It should have been " "within [ %d .. %d ]\n", - var, n, n_min, n_max); + var, + n, + n_min, + n_max); _gmx_error("range", buf, file, line); } diff --git a/src/gromacs/utility/filestream.cpp b/src/gromacs/utility/filestream.cpp index 4773b5c2c8..2aa94b9bd3 100644 --- a/src/gromacs/utility/filestream.cpp +++ b/src/gromacs/utility/filestream.cpp @@ -105,8 +105,8 @@ public: fp_ = std::fopen(filename, mode); if (fp_ == nullptr) { - GMX_THROW_WITH_ERRNO(FileIOError(formatString("Could not open file '%s'", filename)), - "fopen", errno); + GMX_THROW_WITH_ERRNO( + FileIOError(formatString("Could not open file '%s'", filename)), "fopen", errno); } } ~FileStreamImpl() @@ -178,8 +178,8 @@ FilePtr TextInputFile::openRawHandle(const char* filename) FilePtr fp(fopen(filename, "r")); if (fp == nullptr) { - GMX_THROW_WITH_ERRNO(FileIOError(formatString("Could not open file '%s'", filename)), - "fopen", errno); + GMX_THROW_WITH_ERRNO( + FileIOError(formatString("Could not open file '%s'", filename)), "fopen", errno); } return fp; } diff --git a/src/gromacs/utility/futil.cpp b/src/gromacs/utility/futil.cpp index 6f631efc8b..2399188036 100644 --- a/src/gromacs/utility/futil.cpp +++ b/src/gromacs/utility/futil.cpp @@ -381,7 +381,8 @@ static std::string backup_fn(const std::string& file) gmx_fatal(FARGS, "Won't make more than %d backups of %s for you.\n" "The env.var. GMX_MAXBACKUP controls this maximum, -1 disables backups.", - s_maxBackupCount, fn.c_str()); + s_maxBackupCount, + fn.c_str()); } return buf; @@ -729,8 +730,8 @@ void gmx_chdir(const char* directory) #endif if (rc != 0) { - auto message = gmx::formatString("Cannot change directory to '%s'. Reason: %s", directory, - strerror(errno)); + auto message = gmx::formatString( + "Cannot change directory to '%s'. Reason: %s", directory, strerror(errno)); GMX_THROW(gmx::FileIOError(message)); } } diff --git a/src/gromacs/utility/gmxomp.cpp b/src/gromacs/utility/gmxomp.cpp index 1acd0f7d2a..fb943100ee 100644 --- a/src/gromacs/utility/gmxomp.cpp +++ b/src/gromacs/utility/gmxomp.cpp @@ -125,7 +125,8 @@ gmx_bool gmx_omp_check_thread_affinity(char** message) " setting as the two can conflict and cause performance degradation.\n" " To keep using the %s internal affinity setting, unset the\n" " GOMP_CPU_AFFINITY environment variable.", - programName, programName); + programName, + programName); *message = gmx_strdup(buf.c_str()); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR @@ -148,7 +149,8 @@ gmx_bool gmx_omp_check_thread_affinity(char** message) " setting as the two can conflict and cause performance degradation.\n" " To keep using the %s internal affinity setting, unset the\n" " KMP_AFFINITY environment variable or set it to 'none' or 'disabled'.", - programName, programName); + programName, + programName); *message = gmx_strdup(buf.c_str()); } GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR; diff --git a/src/gromacs/utility/keyvaluetree.cpp b/src/gromacs/utility/keyvaluetree.cpp index 2d49c09448..ab7a55ea54 100644 --- a/src/gromacs/utility/keyvaluetree.cpp +++ b/src/gromacs/utility/keyvaluetree.cpp @@ -199,7 +199,8 @@ private: else if (!areSimpleValuesOfSameTypeEqual(value1, value2)) { writer_->writeString(currentPath_.toString()); - writer_->writeLine(formatString(" (%s - %s)", simpleValueToString(value1).c_str(), + writer_->writeLine(formatString(" (%s - %s)", + simpleValueToString(value1).c_str(), simpleValueToString(value2).c_str())); } } @@ -264,13 +265,15 @@ private: void handleMissingKeyInFirstObject(const KeyValueTreeValue& value) { - const std::string message = formatString("%s (missing - %s)", currentPath_.toString().c_str(), + const std::string message = formatString("%s (missing - %s)", + currentPath_.toString().c_str(), formatValueForMissingMessage(value).c_str()); writer_->writeLine(message); } void handleMissingKeyInSecondObject(const KeyValueTreeValue& value) { - const std::string message = formatString("%s (%s - missing)", currentPath_.toString().c_str(), + const std::string message = formatString("%s (%s - missing)", + currentPath_.toString().c_str(), formatValueForMissingMessage(value).c_str()); writer_->writeLine(message); } diff --git a/src/gromacs/utility/path.cpp b/src/gromacs/utility/path.cpp index 1b0f4645af..374e2f5111 100644 --- a/src/gromacs/utility/path.cpp +++ b/src/gromacs/utility/path.cpp @@ -162,11 +162,21 @@ bool Path::isEquivalent(const std::string& path1, const std::string& path2) // p2 is done first, so any error reported is for p1 // FixME: #1635 - handle_wrapper h2(CreateFile(path2.c_str(), 0, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, - 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)); - - handle_wrapper h1(CreateFile(path1.c_str(), 0, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, - 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0)); + handle_wrapper h2(CreateFile(path2.c_str(), + 0, + FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, + 0, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, + 0)); + + handle_wrapper h1(CreateFile(path1.c_str(), + 0, + FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, + 0, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, + 0)); if (h1.handle == INVALID_HANDLE_VALUE || h2.handle == INVALID_HANDLE_VALUE) { @@ -213,8 +223,8 @@ bool Path::isEquivalent(const std::string& path1, const std::string& path2) // but if both are invalid then it is an error. if (e1 != 0 && e2 != 0) { - GMX_THROW_WITH_ERRNO(FileIOError("Path::isEquivalent called with two invalid files"), - "stat", errno); + GMX_THROW_WITH_ERRNO( + FileIOError("Path::isEquivalent called with two invalid files"), "stat", errno); } return false; } @@ -488,8 +498,8 @@ void File::throwOnError(const NotFoundInfo& info) void File::throwOnNotFound(const NotFoundInfo& info) { throwOnError(info); - const std::string message = formatString("File '%s' does not exist or is not accessible.\n%s", - info.filename, info.message); + const std::string message = formatString( + "File '%s' does not exist or is not accessible.\n%s", info.filename, info.message); GMX_THROW_WITH_ERRNO(InvalidInputError(message), info.call, info.err); } diff --git a/src/gromacs/utility/pleasecite.cpp b/src/gromacs/utility/pleasecite.cpp index c5985c48fd..0d49d451b7 100644 --- a/src/gromacs/utility/pleasecite.cpp +++ b/src/gromacs/utility/pleasecite.cpp @@ -60,241 +60,500 @@ typedef struct void please_cite(FILE* fp, const char* key) { static const t_citerec citedb[] = { - { "Allen1987a", "M. P. Allen and D. J. Tildesley", "Computer simulation of liquids", - "Oxford Science Publications", 1, 1987, "1" }, - { "Berendsen95a", "H. J. C. Berendsen, D. van der Spoel and R. van Drunen", + { "Allen1987a", + "M. P. Allen and D. J. Tildesley", + "Computer simulation of liquids", + "Oxford Science Publications", + 1, + 1987, + "1" }, + { "Berendsen95a", + "H. J. C. Berendsen, D. van der Spoel and R. van Drunen", "GROMACS: A message-passing parallel molecular dynamics implementation", - "Comp. Phys. Comm.", 91, 1995, "43-56" }, - { "Berendsen84a", "H. J. C. Berendsen, J. P. M. Postma, A. DiNola and J. R. Haak", - "Molecular dynamics with coupling to an external bath", "J. Chem. Phys.", 81, 1984, + "Comp. Phys. Comm.", + 91, + 1995, + "43-56" }, + { "Berendsen84a", + "H. J. C. Berendsen, J. P. M. Postma, A. DiNola and J. R. Haak", + "Molecular dynamics with coupling to an external bath", + "J. Chem. Phys.", + 81, + 1984, "3684-3690" }, - { "Ryckaert77a", "J. P. Ryckaert and G. Ciccotti and H. J. C. Berendsen", + { "Ryckaert77a", + "J. P. Ryckaert and G. Ciccotti and H. J. C. Berendsen", "Numerical Integration of the Cartesian Equations of Motion of a System with " "Constraints; Molecular Dynamics of n-Alkanes", - "J. Comp. Phys.", 23, 1977, "327-341" }, - { "Miyamoto92a", "S. Miyamoto and P. A. Kollman", + "J. Comp. Phys.", + 23, + 1977, + "327-341" }, + { "Miyamoto92a", + "S. Miyamoto and P. A. Kollman", "SETTLE: An Analytical Version of the SHAKE and RATTLE Algorithms for Rigid Water Models", - "J. Comp. Chem.", 13, 1992, "952-962" }, - { "Cromer1968a", "D. T. Cromer & J. B. Mann", + "J. Comp. Chem.", + 13, + 1992, + "952-962" }, + { "Cromer1968a", + "D. T. Cromer & J. B. Mann", "X-ray scattering factors computed from numerical Hartree-Fock wave functions", - "Acta Cryst. A", 24, 1968, "321" }, - { "Barth95a", "E. Barth and K. Kuczera and B. Leimkuhler and R. D. Skeel", - "Algorithms for Constrained Molecular Dynamics", "J. Comp. Chem.", 16, 1995, "1192-1209" }, + "Acta Cryst. A", + 24, + 1968, + "321" }, + { "Barth95a", + "E. Barth and K. Kuczera and B. Leimkuhler and R. D. Skeel", + "Algorithms for Constrained Molecular Dynamics", + "J. Comp. Chem.", + 16, + 1995, + "1192-1209" }, { "Essmann95a", "U. Essmann, L. Perera, M. L. Berkowitz, T. Darden, H. Lee and L. G. Pedersen ", - "A smooth particle mesh Ewald method", "J. Chem. Phys.", 103, 1995, "8577-8592" }, - { "Torda89a", "A. E. Torda and R. M. Scheek and W. F. van Gunsteren", + "A smooth particle mesh Ewald method", + "J. Chem. Phys.", + 103, + 1995, + "8577-8592" }, + { "Torda89a", + "A. E. Torda and R. M. Scheek and W. F. van Gunsteren", "Time-dependent distance restraints in molecular dynamics simulations", - "Chem. Phys. Lett.", 157, 1989, "289-294" }, - { "Tironi95a", "I. G. Tironi and R. Sperb and P. E. Smith and W. F. van Gunsteren", - "Generalized reaction field method for molecular dynamics simulations", "J. Chem. Phys", - 102, 1995, "5451-5459" }, - { "Hess97a", "B. Hess and H. Bekker and H. J. C. Berendsen and J. G. E. M. Fraaije", - "LINCS: A Linear Constraint Solver for molecular simulations", "J. Comp. Chem.", 18, 1997, + "Chem. Phys. Lett.", + 157, + 1989, + "289-294" }, + { "Tironi95a", + "I. G. Tironi and R. Sperb and P. E. Smith and W. F. van Gunsteren", + "Generalized reaction field method for molecular dynamics simulations", + "J. Chem. Phys", + 102, + 1995, + "5451-5459" }, + { "Hess97a", + "B. Hess and H. Bekker and H. J. C. Berendsen and J. G. E. M. Fraaije", + "LINCS: A Linear Constraint Solver for molecular simulations", + "J. Comp. Chem.", + 18, + 1997, "1463-1472" }, - { "Hess2008a", "B. Hess", + { "Hess2008a", + "B. Hess", "P-LINCS: A Parallel Linear Constraint Solver for molecular simulation", - "J. Chem. Theory Comput.", 4, 2008, "116-122" }, - { "Hess2008b", "B. Hess and C. Kutzner and D. van der Spoel and E. Lindahl", + "J. Chem. Theory Comput.", + 4, + 2008, + "116-122" }, + { "Hess2008b", + "B. Hess and C. Kutzner and D. van der Spoel and E. Lindahl", "GROMACS 4: Algorithms for highly efficient, load-balanced, and scalable molecular " "simulation", - "J. Chem. Theory Comput.", 4, 2008, "435-447" }, - { "Hub2010", "J. S. Hub, B. L. de Groot and D. van der Spoel", + "J. Chem. Theory Comput.", + 4, + 2008, + "435-447" }, + { "Hub2010", + "J. S. Hub, B. L. de Groot and D. van der Spoel", "g_wham - A free weighted histogram analysis implementation including robust error and " "autocorrelation estimates", - "J. Chem. Theory Comput.", 6, 2010, "3713-3720" }, - { "In-Chul99a", "Y. In-Chul and M. L. Berkowitz", - "Ewald summation for systems with slab geometry", "J. Chem. Phys.", 111, 1999, + "J. Chem. Theory Comput.", + 6, + 2010, + "3713-3720" }, + { "In-Chul99a", + "Y. In-Chul and M. L. Berkowitz", + "Ewald summation for systems with slab geometry", + "J. Chem. Phys.", + 111, + 1999, "3155-3162" }, { "DeGroot97a", "B. L. de Groot and D. M. F. van Aalten and R. M. Scheek and A. Amadei and G. Vriend and " "H. J. C. Berendsen", - "Prediction of Protein Conformational Freedom From Distance Constrains", "Proteins", 29, - 1997, "240-251" }, - { "Spoel98a", "D. van der Spoel and P. J. van Maaren and H. J. C. Berendsen", + "Prediction of Protein Conformational Freedom From Distance Constrains", + "Proteins", + 29, + 1997, + "240-251" }, + { "Spoel98a", + "D. van der Spoel and P. J. van Maaren and H. J. C. Berendsen", "A systematic study of water models for molecular simulation. Derivation of models " "optimized for use with a reaction-field.", - "J. Chem. Phys.", 108, 1998, "10220-10230" }, - { "Wishart98a", "D. S. Wishart and A. M. Nip", - "Protein Chemical Shift Analysis: A Practical Guide", "Biochem. Cell Biol.", 76, 1998, + "J. Chem. Phys.", + 108, + 1998, + "10220-10230" }, + { "Wishart98a", + "D. S. Wishart and A. M. Nip", + "Protein Chemical Shift Analysis: A Practical Guide", + "Biochem. Cell Biol.", + 76, + 1998, "153-163" }, - { "Maiorov95", "V. N. Maiorov and G. M. Crippen", + { "Maiorov95", + "V. N. Maiorov and G. M. Crippen", "Size-Independent Comparison of Protein Three-Dimensional Structures", - "PROTEINS: Struct. Funct. Gen.", 22, 1995, "273-283" }, - { "Feenstra99", "K. A. Feenstra and B. Hess and H. J. C. Berendsen", + "PROTEINS: Struct. Funct. Gen.", + 22, + 1995, + "273-283" }, + { "Feenstra99", + "K. A. Feenstra and B. Hess and H. J. C. Berendsen", "Improving Efficiency of Large Time-scale Molecular Dynamics Simulations of " "Hydrogen-rich Systems", - "J. Comput. Chem.", 20, 1999, "786-798" }, + "J. Comput. Chem.", + 20, + 1999, + "786-798" }, { "Lourenco2013a", "Tuanan C. Lourenco and Mariny F. C. Coelho and Teodorico C. Ramalho and David van der " "Spoel and Luciano T. Costa", "Insights on the Solubility of CO2 in 1-Ethyl-3-methylimidazolium " "Bis(trifluoromethylsulfonyl)imide from the Microscopic Point of View", - "Environ. Sci. Technol.", 47, 2013, "7421-7429" }, - { "Timneanu2004a", "N. Timneanu and C. Caleman and J. Hajdu and D. van der Spoel", - "Auger Electron Cascades in Water and Ice", "Chem. Phys.", 299, 2004, "277-283" }, - { "Pascal2011a", "T. A. Pascal and S. T. Lin and W. A. Goddard III", + "Environ. Sci. Technol.", + 47, + 2013, + "7421-7429" }, + { "Timneanu2004a", + "N. Timneanu and C. Caleman and J. Hajdu and D. van der Spoel", + "Auger Electron Cascades in Water and Ice", + "Chem. Phys.", + 299, + 2004, + "277-283" }, + { "Pascal2011a", + "T. A. Pascal and S. T. Lin and W. A. Goddard III", "Thermodynamics of liquids: standard molar entropies and heat capacities of common " "solvents from 2PT molecular dynamics", - "Phys. Chem. Chem. Phys.", 13, 2011, "169-181" }, - { "Caleman2008a", "C. Caleman and D. van der Spoel", + "Phys. Chem. Chem. Phys.", + 13, + 2011, + "169-181" }, + { "Caleman2008a", + "C. Caleman and D. van der Spoel", "Picosecond Melting of Ice by an Infrared Laser Pulse: A Simulation Study", - "Angew. Chem. Int. Ed", 47, 2008, "1417-1420" }, + "Angew. Chem. Int. Ed", + 47, + 2008, + "1417-1420" }, { "Caleman2011b", "C. Caleman and P. J. van Maaren and M. Hong and J. S. Hub and L. T. da Costa and D. van " "der Spoel", "Force Field Benchmark of Organic Liquids: Density, Enthalpy of Vaporization, Heat " "Capacities, Surface Tension, Isothermal Compressibility, Volumetric Expansion " "Coefficient, and Dielectric Constant", - "J. Chem. Theo. Comp.", 8, 2012, "61" }, - { "Lindahl2001a", "E. Lindahl and B. Hess and D. van der Spoel", - "GROMACS 3.0: A package for molecular simulation and trajectory analysis", "J. Mol. Mod.", - 7, 2001, "306-317" }, - { "Wang2001a", "J. Wang and W. Wang and S. Huo and M. Lee and P. A. Kollman", - "Solvation model based on weighted solvent accessible surface area", "J. Phys. Chem. B", - 105, 2001, "5055-5067" }, - { "Eisenberg86a", "D. Eisenberg and A. D. McLachlan", - "Solvation energy in protein folding and binding", "Nature", 319, 1986, "199-203" }, - { "Bondi1964a", "A. Bondi", "van der Waals Volumes and Radii", "J. Phys. Chem.", 68, 1964, + "J. Chem. Theo. Comp.", + 8, + 2012, + "61" }, + { "Lindahl2001a", + "E. Lindahl and B. Hess and D. van der Spoel", + "GROMACS 3.0: A package for molecular simulation and trajectory analysis", + "J. Mol. Mod.", + 7, + 2001, + "306-317" }, + { "Wang2001a", + "J. Wang and W. Wang and S. Huo and M. Lee and P. A. Kollman", + "Solvation model based on weighted solvent accessible surface area", + "J. Phys. Chem. B", + 105, + 2001, + "5055-5067" }, + { "Eisenberg86a", + "D. Eisenberg and A. D. McLachlan", + "Solvation energy in protein folding and binding", + "Nature", + 319, + 1986, + "199-203" }, + { "Bondi1964a", + "A. Bondi", + "van der Waals Volumes and Radii", + "J. Phys. Chem.", + 68, + 1964, "441-451" }, { "Eisenhaber95", "Frank Eisenhaber and Philip Lijnzaad and Patrick Argos and Chris Sander and Michael " "Scharf", "The Double Cube Lattice Method: Efficient Approaches to Numerical Integration of " "Surface Area and Volume and to Dot Surface Contouring of Molecular Assemblies", - "J. Comp. Chem.", 16, 1995, "273-284" }, - { "Hess2002", "B. Hess, H. Saint-Martin and H.J.C. Berendsen", + "J. Comp. Chem.", + 16, + 1995, + "273-284" }, + { "Hess2002", + "B. Hess, H. Saint-Martin and H.J.C. Berendsen", "Flexible constraints: an adiabatic treatment of quantum degrees of freedom, with " "application to the flexible and polarizable MCDHO model for water", - "J. Chem. Phys.", 116, 2002, "9602-9610" }, - { "Hess2003", "B. Hess and R.M. Scheek", + "J. Chem. Phys.", + 116, + 2002, + "9602-9610" }, + { "Hess2003", + "B. Hess and R.M. Scheek", "Orientation restraints in molecular dynamics simulations using time and ensemble " "averaging", - "J. Magn. Res.", 164, 2003, "19-27" }, - { "Rappe1991a", "A. K. Rappe and W. A. Goddard III", - "Charge Equillibration for Molecular Dynamics Simulations", "J. Phys. Chem.", 95, 1991, + "J. Magn. Res.", + 164, + 2003, + "19-27" }, + { "Rappe1991a", + "A. K. Rappe and W. A. Goddard III", + "Charge Equillibration for Molecular Dynamics Simulations", + "J. Phys. Chem.", + 95, + 1991, "3358-3363" }, - { "Mu2005a", "Y. Mu, P. H. Nguyen and G. Stock", + { "Mu2005a", + "Y. Mu, P. H. Nguyen and G. Stock", "Energy landscape of a small peptide revelaed by dihedral angle principal component " "analysis", - "Prot. Struct. Funct. Bioinf.", 58, 2005, "45-52" }, - { "Okabe2001a", "T. Okabe and M. Kawata and Y. Okamoto and M. Mikami", + "Prot. Struct. Funct. Bioinf.", + 58, + 2005, + "45-52" }, + { "Okabe2001a", + "T. Okabe and M. Kawata and Y. Okamoto and M. Mikami", "Replica-exchange {M}onte {C}arlo method for the isobaric-isothermal ensemble", - "Chem. Phys. Lett.", 335, 2001, "435-439" }, - { "Hukushima96a", "K. Hukushima and K. Nemoto", + "Chem. Phys. Lett.", + 335, + 2001, + "435-439" }, + { "Hukushima96a", + "K. Hukushima and K. Nemoto", "Exchange Monte Carlo Method and Application to Spin Glass Simulations", - "J. Phys. Soc. Jpn.", 65, 1996, "1604-1608" }, - { "Tropp80a", "J. Tropp", + "J. Phys. Soc. Jpn.", + 65, + 1996, + "1604-1608" }, + { "Tropp80a", + "J. Tropp", "Dipolar Relaxation and Nuclear Overhauser effects in nonrigid molecules: The effect of " "fluctuating internuclear distances", - "J. Chem. Phys.", 72, 1980, "6035-6043" }, + "J. Chem. Phys.", + 72, + 1980, + "6035-6043" }, { "Bultinck2002a", "P. Bultinck and W. Langenaeker and P. Lahorte and F. De Proft and P. Geerlings and M. " "Waroquier and J. P. Tollenaere", "The electronegativity equalization method I: Parametrization and validation for atomic " "charge calculations", - "J. Phys. Chem. A", 106, 2002, "7887-7894" }, - { "Yang2006b", "Q. Y. Yang and K. A. Sharp", + "J. Phys. Chem. A", + 106, + 2002, + "7887-7894" }, + { "Yang2006b", + "Q. Y. Yang and K. A. Sharp", "Atomic charge parameters for the finite difference Poisson-Boltzmann method using " "electronegativity neutralization", - "J. Chem. Theory Comput.", 2, 2006, "1152-1167" }, + "J. Chem. Theory Comput.", + 2, + 2006, + "1152-1167" }, { "Spoel2005a", "D. van der Spoel, E. Lindahl, B. Hess, G. Groenhof, A. E. Mark and H. J. C. Berendsen", - "GROMACS: Fast, Flexible and Free", "J. Comp. Chem.", 26, 2005, "1701-1719" }, - { "Spoel2006b", "D. van der Spoel, P. J. van Maaren, P. Larsson and N. Timneanu", + "GROMACS: Fast, Flexible and Free", + "J. Comp. Chem.", + 26, + 2005, + "1701-1719" }, + { "Spoel2006b", + "D. van der Spoel, P. J. van Maaren, P. Larsson and N. Timneanu", "Thermodynamics of hydrogen bonding in hydrophilic and hydrophobic media", - "J. Phys. Chem. B", 110, 2006, "4393-4398" }, - { "Spoel2006d", "D. van der Spoel and M. M. Seibert", + "J. Phys. Chem. B", + 110, + 2006, + "4393-4398" }, + { "Spoel2006d", + "D. van der Spoel and M. M. Seibert", "Protein folding kinetics and thermodynamics from atomistic simulations", - "Phys. Rev. Letters", 96, 2006, "238102" }, - { "Palmer94a", "B. J. Palmer", + "Phys. Rev. Letters", + 96, + 2006, + "238102" }, + { "Palmer94a", + "B. J. Palmer", "Transverse-current autocorrelation-function calculations of the shear viscosity for " "molecular liquids", - "Phys. Rev. E", 49, 1994, "359-366" }, - { "Bussi2007a", "G. Bussi, D. Donadio and M. Parrinello", - "Canonical sampling through velocity rescaling", "J. Chem. Phys.", 126, 2007, "014101" }, - { "Hub2006", "J. S. Hub and B. L. de Groot", "Does CO2 permeate through Aquaporin-1?", - "Biophys. J.", 91, 2006, "842-848" }, - { "Hub2008", "J. S. Hub and B. L. de Groot", - "Mechanism of selectivity in aquaporins and aquaglyceroporins", "PNAS", 105, 2008, + "Phys. Rev. E", + 49, + 1994, + "359-366" }, + { "Bussi2007a", + "G. Bussi, D. Donadio and M. Parrinello", + "Canonical sampling through velocity rescaling", + "J. Chem. Phys.", + 126, + 2007, + "014101" }, + { "Hub2006", + "J. S. Hub and B. L. de Groot", + "Does CO2 permeate through Aquaporin-1?", + "Biophys. J.", + 91, + 2006, + "842-848" }, + { "Hub2008", + "J. S. Hub and B. L. de Groot", + "Mechanism of selectivity in aquaporins and aquaglyceroporins", + "PNAS", + 105, + 2008, "1198-1203" }, { "Friedrich2009", "M. S. Friedrichs, P. Eastman, V. Vaidyanathan, M. Houston, S. LeGrand, A. L. Beberg, D. " "L. Ensign, C. M. Bruns, and V. S. Pande", "Accelerating Molecular Dynamic Simulation on Graphics Processing Units", - "J. Comp. Chem.", 30, 2009, "864-872" }, - { "Engin2010", "O. Engin, A. Villa, M. Sayar and B. Hess", + "J. Comp. Chem.", + 30, + 2009, + "864-872" }, + { "Engin2010", + "O. Engin, A. Villa, M. Sayar and B. Hess", "Driving Forces for Adsorption of Amphiphilic Peptides to Air-Water Interface", - "J. Phys. Chem. B", 114, 2010, "11093" }, - { "Wang2010", "H. Wang, F. Dommert, C.Holm", + "J. Phys. Chem. B", + 114, + 2010, + "11093" }, + { "Wang2010", + "H. Wang, F. Dommert, C.Holm", "Optimizing working parameters of the smooth particle mesh Ewald algorithm in terms of " "accuracy and efficiency", - "J. Chem. Phys. B", 133, 2010, "034117" }, - { "Sugita1999a", "Y. Sugita, Y. Okamoto", - "Replica-exchange molecular dynamics method for protein folding", "Chem. Phys. Lett.", - 314, 1999, "141-151" }, - { "Kutzner2011", "C. Kutzner and J. Czub and H. Grubmuller", + "J. Chem. Phys. B", + 133, + 2010, + "034117" }, + { "Sugita1999a", + "Y. Sugita, Y. Okamoto", + "Replica-exchange molecular dynamics method for protein folding", + "Chem. Phys. Lett.", + 314, + 1999, + "141-151" }, + { "Kutzner2011", + "C. Kutzner and J. Czub and H. Grubmuller", "Keep it Flexible: Driving Macromolecular Rotary Motions in Atomistic Simulations with " "GROMACS", - "J. Chem. Theory Comput.", 7, 2011, "1381-1393" }, + "J. Chem. Theory Comput.", + 7, + 2011, + "1381-1393" }, { "Hoefling2011", "M. Hoefling, N. Lima, D. Haenni, C.A.M. Seidel, B. Schuler, H. Grubmuller", "Structural Heterogeneity and Quantitative FRET Efficiency Distributions of Polyprolines " "through a Hybrid Atomistic Simulation and Monte Carlo Approach", - "PLoS ONE", 6, 2011, "e19791" }, - { "Hockney1988", "R. W. Hockney and J. W. Eastwood", "Computer simulation using particles", - "IOP, Bristol", 1, 1988, "1" }, - { "Ballenegger2012", "V. Ballenegger, J.J. Cerda, and C. Holm", + "PLoS ONE", + 6, + 2011, + "e19791" }, + { "Hockney1988", + "R. W. Hockney and J. W. Eastwood", + "Computer simulation using particles", + "IOP, Bristol", + 1, + 1988, + "1" }, + { "Ballenegger2012", + "V. Ballenegger, J.J. Cerda, and C. Holm", "How to Convert SPME to P3M: Influence Functions and Error Estimates", - "J. Chem. Theory Comput.", 8, 2012, "936-947" }, + "J. Chem. Theory Comput.", + 8, + 2012, + "936-947" }, { "Garmay2012", "Garmay Yu, Shvetsov A, Karelov D, Lebedev D, Radulescu A, Petukhov M, Isaev-Ivanov V", "Correlated motion of protein subdomains and large-scale conformational flexibility of " "RecA protein filament", - "Journal of Physics: Conference Series", 340, 2012, "012094" }, - { "Kutzner2011b", "C. Kutzner, H. Grubmuller, B. L. de Groot, and U. Zachariae", + "Journal of Physics: Conference Series", + 340, + 2012, + "012094" }, + { "Kutzner2011b", + "C. Kutzner, H. Grubmuller, B. L. de Groot, and U. Zachariae", "Computational Electrophysiology: The Molecular Dynamics of Ion Channel Permeation and " "Selectivity in Atomistic Detail", - "Biophys. J.", 101, 2011, "809-817" }, + "Biophys. J.", + 101, + 2011, + "809-817" }, { "Lundborg2014", "M. Lundborg, R. Apostolov, D. Spangberg, A. Gardenas, D. van der Spoel and E. Lindahl", "An efficient and extensible format, library, and API for binary trajectory data from " "molecular simulations", - "J. Comput. Chem.", 35, 2014, "260-269" }, + "J. Comput. Chem.", + 35, + 2014, + "260-269" }, { "Goga2012", "N. Goga and A. J. Rzepiela and A. H. de Vries and S. J. Marrink and H. J. C. Berendsen", - "Efficient Algorithms for Langevin and DPD Dynamics", "J. Chem. Theory Comput.", 8, 2012, + "Efficient Algorithms for Langevin and DPD Dynamics", + "J. Chem. Theory Comput.", + 8, + 2012, "3637--3649" }, { "Pronk2013", "S. Pronk, S. Páll, R. Schulz, P. Larsson, P. Bjelkmar, R. Apostolov, M. R. Shirts, J. " "C. Smith, P. M. Kasson, D. van der Spoel, B. Hess, and E. Lindahl", "GROMACS 4.5: a high-throughput and highly parallel open source molecular simulation " "toolkit", - "Bioinformatics", 29, 2013, "845-54" }, - { "Pall2015", "S. Páll, M. J. Abraham, C. Kutzner, B. Hess, E. Lindahl", + "Bioinformatics", + 29, + 2013, + "845-54" }, + { "Pall2015", + "S. Páll, M. J. Abraham, C. Kutzner, B. Hess, E. Lindahl", "Tackling Exascale Software Challenges in Molecular Dynamics Simulations with GROMACS", - "In S. Markidis & E. Laure (Eds.), Solving Software Challenges for Exascale", 8759, 2015, + "In S. Markidis & E. Laure (Eds.), Solving Software Challenges for Exascale", + 8759, + 2015, "3-27" }, { "Abraham2015", "M. J. Abraham, T. Murtola, R. Schulz, S. Páll, J. C. Smith, B. Hess, E. Lindahl", "GROMACS: High performance molecular simulations through multi-level parallelism from " "laptops to supercomputers", - "SoftwareX", 1, 2015, "19-25" }, - { "Ballenegger2009", "V. Ballenegger, A. Arnold, J. J. Cerdà", + "SoftwareX", + 1, + 2015, + "19-25" }, + { "Ballenegger2009", + "V. Ballenegger, A. Arnold, J. J. Cerdà", "Simulations of non-neutral slab systems with long-range electrostatic interactions in " "two-dimensional periodic boundary conditions", - "J. Chem. Phys", 131, 2009, "094107" }, - { "Hub2014a", "J. S. Hub, B. L. de Groot, H. Grubmueller, G. Groenhof", + "J. Chem. Phys", + 131, + 2009, + "094107" }, + { "Hub2014a", + "J. S. Hub, B. L. de Groot, H. Grubmueller, G. Groenhof", "Quantifying Artifacts in Ewald Simulations of Inhomogeneous Systems with a Net Charge", - "J. Chem. Theory Comput.", 10, 2014, "381-393" }, - { "Spoel2018a", "D. van der Spoel, M. M. Ghahremanpour, J. Lemkul", + "J. Chem. Theory Comput.", + 10, + 2014, + "381-393" }, + { "Spoel2018a", + "D. van der Spoel, M. M. Ghahremanpour, J. Lemkul", "Small Molecule Thermochemistry: A Tool For Empirical Force Field Development", - "J. Phys. Chem. A", 122, 2018, "8982-8988" }, - { "Lindahl2014", "V. Lindahl, J. Lidmar, B. Hess", + "J. Phys. Chem. A", + 122, + 2018, + "8982-8988" }, + { "Lindahl2014", + "V. Lindahl, J. Lidmar, B. Hess", "Accelerated weight histogram method for exploring free energy landscapes", - "J. Chem. Phys.", 141, 2014, "044110" }, - { "Bernetti2020", "M. Bernetti, G. Bussi", - "Pressure control using stochastic cell rescaling", "J. Chem. Phys.", 153, 2020, + "J. Chem. Phys.", + 141, + 2014, + "044110" }, + { "Bernetti2020", + "M. Bernetti, G. Bussi", + "Pressure control using stochastic cell rescaling", + "J. Chem. Phys.", + 153, + 2020, "114107" }, }; #define NSTR static_cast(asize(citedb)) @@ -317,8 +576,14 @@ void please_cite(FILE* fp, const char* key) /* Insert newlines */ author = wrap_lines(citedb[index].author, LINE_WIDTH, 0, FALSE); title = wrap_lines(citedb[index].title, LINE_WIDTH, 0, FALSE); - fprintf(fp, "%s\n%s\n%s %d (%d) pp. %s\n", author, title, citedb[index].journal, - citedb[index].volume, citedb[index].year, citedb[index].pages); + fprintf(fp, + "%s\n%s\n%s %d (%d) pp. %s\n", + author, + title, + citedb[index].journal, + citedb[index].volume, + citedb[index].year, + citedb[index].pages); sfree(author); sfree(title); } diff --git a/src/gromacs/utility/smalloc.cpp b/src/gromacs/utility/smalloc.cpp index 81895f9c3e..c0511c32dc 100644 --- a/src/gromacs/utility/smalloc.cpp +++ b/src/gromacs/utility/smalloc.cpp @@ -77,11 +77,16 @@ void* save_malloc(const char* name, const char* file, int line, size_t size) { if ((p = malloc(size)) == nullptr) { - gmx_fatal(errno, __FILE__, __LINE__, + gmx_fatal(errno, + __FILE__, + __LINE__, "Not enough memory. Failed to malloc %" PRId64 " bytes for %s\n" "(called from file %s, line %d)", - static_cast(size), name, file, line); + static_cast(size), + name, + file, + line); } (void)memset(p, 0, size); } @@ -104,7 +109,11 @@ void* save_calloc(const char* name, const char* file, int line, size_t nelem, si { int rank = gmx_node_rank(); printf("Allocating %.1f MB for %s (called from file %s, line %d on %d)\n", - nelem * elsize / 1048576.0, name, file, line, rank); + nelem * elsize / 1048576.0, + name, + file, + line, + rank); } #endif #if GMX_BROKEN_CALLOC @@ -112,19 +121,31 @@ void* save_calloc(const char* name, const char* file, int line, size_t nelem, si a broken calloc, e.g. in -lgmalloc on cray xt3. */ if ((p = malloc((size_t)nelem * (size_t)elsize)) == NULL) { - gmx_fatal(errno, __FILE__, __LINE__, + gmx_fatal(errno, + __FILE__, + __LINE__, "Not enough memory. Failed to calloc %" PRId64 " elements of size %" PRId64 " for %s\n(called from file %s, line %d)", - (int64_t)nelem, (int64_t)elsize, name, file, line); + (int64_t)nelem, + (int64_t)elsize, + name, + file, + line); } memset(p, 0, (size_t)(nelem * elsize)); #else if ((p = calloc(nelem, elsize)) == nullptr) { - gmx_fatal(errno, __FILE__, __LINE__, + gmx_fatal(errno, + __FILE__, + __LINE__, "Not enough memory. Failed to calloc %" PRId64 " elements of size %" PRId64 " for %s\n(called from file %s, line %d)", - static_cast(nelem), static_cast(elsize), name, file, line); + static_cast(nelem), + static_cast(elsize), + name, + file, + line); } #endif } @@ -148,7 +169,11 @@ void* save_realloc(const char* name, const char* file, int line, void* ptr, size { int rank = gmx_node_rank(); printf("Reallocating %.1f MB for %s (called from file %s, line %d on %d)\n", - size / 1048576.0, name, file, line, rank); + size / 1048576.0, + name, + file, + line, + rank); } #endif if (ptr == nullptr) @@ -161,10 +186,17 @@ void* save_realloc(const char* name, const char* file, int line, void* ptr, size } if (p == nullptr) { - gmx_fatal(errno, __FILE__, __LINE__, + gmx_fatal(errno, + __FILE__, + __LINE__, "Not enough memory. Failed to realloc %zu bytes for %s, %s=%p\n" "(called from file %s, line %d)", - size, name, name, ptr, file, line); + size, + name, + name, + ptr, + file, + line); } } return p; @@ -189,19 +221,26 @@ void* save_malloc_aligned(const char* name, const char* file, int line, size_t n if (alignment == 0) { - gmx_fatal(errno, __FILE__, __LINE__, + gmx_fatal(errno, + __FILE__, + __LINE__, "Cannot allocate aligned memory with alignment of zero!\n(called from file %s, " "line %d)", - file, line); + file, + line); } size_t alignmentSize = gmx::AlignedAllocationPolicy::alignment(); if (alignment > alignmentSize) { - gmx_fatal(errno, __FILE__, __LINE__, + gmx_fatal(errno, + __FILE__, + __LINE__, "Cannot allocate aligned memory with alignment > %zu bytes\n(called from file " "%s, line %d)", - alignmentSize, file, line); + alignmentSize, + file, + line); } @@ -216,7 +255,11 @@ void* save_malloc_aligned(const char* name, const char* file, int line, size_t n { int rank = gmx_node_rank(); printf("Allocating %.1f MB for %s (called from file %s, line %d on %d)\n", - nelem * elsize / 1048576.0, name, file, line, rank); + nelem * elsize / 1048576.0, + name, + file, + line, + rank); } #endif @@ -224,10 +267,16 @@ void* save_malloc_aligned(const char* name, const char* file, int line, size_t n if (p == nullptr) { - gmx_fatal(errno, __FILE__, __LINE__, + gmx_fatal(errno, + __FILE__, + __LINE__, "Not enough memory. Failed to allocate %zu aligned elements of size %zu for " "%s\n(called from file %s, line %d)", - nelem, elsize, name, file, line); + nelem, + elsize, + name, + file, + line); } } return p; diff --git a/src/gromacs/utility/strconvert.h b/src/gromacs/utility/strconvert.h index 805717fb7e..2af389fcdd 100644 --- a/src/gromacs/utility/strconvert.h +++ b/src/gromacs/utility/strconvert.h @@ -268,7 +268,9 @@ parsedArrayFromInputString(const std::string& str) // will throw if any conversion from string to value fails std::array valuesAsArray; - std::transform(std::begin(valuesAsStrings), std::end(valuesAsStrings), std::begin(valuesAsArray), + std::transform(std::begin(valuesAsStrings), + std::end(valuesAsStrings), + std::begin(valuesAsArray), [](const std::string& split) { return fromString(split); }); return { valuesAsArray }; diff --git a/src/gromacs/utility/strdb.cpp b/src/gromacs/utility/strdb.cpp index 4b3642d257..8704b16055 100644 --- a/src/gromacs/utility/strdb.cpp +++ b/src/gromacs/utility/strdb.cpp @@ -70,7 +70,8 @@ gmx_bool get_a_line(FILE* fp, char line[], int n) else if (static_cast(std::strlen(line0)) == n) { fprintf(stderr, - "Warning: line length exceeds buffer length (%d), data might be corrupted\n", n); + "Warning: line length exceeds buffer length (%d), data might be corrupted\n", + n); line0[n - 1] = '\0'; } else diff --git a/src/gromacs/utility/stringutil.cpp b/src/gromacs/utility/stringutil.cpp index a487ae0b69..e5dbb9241e 100644 --- a/src/gromacs/utility/stringutil.cpp +++ b/src/gromacs/utility/stringutil.cpp @@ -2,7 +2,7 @@ * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2011-2018, The GROMACS development team. - * Copyright (c) 2019, by the GROMACS development team, led by + * Copyright (c) 2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -328,8 +328,9 @@ bool equalCaseInsensitive(const std::string& source, const std::string& target, } comparisonEnd = source.begin() + maxLengthOfComparison; } - return std::equal(source.begin(), comparisonEnd, target.begin(), - [](const char& s, const char& t) { return std::tolower(s) == std::tolower(t); }); + return std::equal(source.begin(), comparisonEnd, target.begin(), [](const char& s, const char& t) { + return std::tolower(s) == std::tolower(t); + }); } /******************************************************************** diff --git a/src/gromacs/utility/tests/inmemoryserializer.cpp b/src/gromacs/utility/tests/inmemoryserializer.cpp index 2db9b643f5..ed502096d3 100644 --- a/src/gromacs/utility/tests/inmemoryserializer.cpp +++ b/src/gromacs/utility/tests/inmemoryserializer.cpp @@ -204,8 +204,8 @@ TEST_F(InMemorySerializerTest, RoundtripWithEndianessSwap) auto buffer = serializerWithSwap.finishAndGetBuffer(); - InMemoryDeserializer deserializerWithSwap(buffer, std::is_same_v, - EndianSwapBehavior::Swap); + InMemoryDeserializer deserializerWithSwap( + buffer, std::is_same_v, EndianSwapBehavior::Swap); SerializerValues deserialisedValues = deserialize(&deserializerWithSwap); @@ -234,8 +234,8 @@ TEST_F(InMemorySerializerTest, DeserializerExplicitEndianessSwap) auto buffer = serializer.finishAndGetBuffer(); - InMemoryDeserializer deserializerWithSwap(buffer, std::is_same_v, - EndianSwapBehavior::Swap); + InMemoryDeserializer deserializerWithSwap( + buffer, std::is_same_v, EndianSwapBehavior::Swap); SerializerValues deserialisedValues = deserialize(&deserializerWithSwap); checkSerializerValuesforEquality(endianessSwappedValues_, deserialisedValues); diff --git a/src/gromacs/utility/tests/keyvaluetreetransform.cpp b/src/gromacs/utility/tests/keyvaluetreetransform.cpp index 1d119bae61..7c6a549ea8 100644 --- a/src/gromacs/utility/tests/keyvaluetreetransform.cpp +++ b/src/gromacs/utility/tests/keyvaluetreetransform.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2016,2017,2019, by the GROMACS development team, led by + * Copyright (c) 2016,2017,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -66,8 +66,8 @@ public: gmx::test::TestReferenceChecker checker(data.rootChecker()); checker.checkKeyValueTreeObject(input, "Input"); auto mappedPaths = transform.mappedPaths(); - checker.checkSequence(mappedPaths.begin(), mappedPaths.end(), "MappedPaths", - &TreeValueTransformTest::checkMappedPath); + checker.checkSequence( + mappedPaths.begin(), mappedPaths.end(), "MappedPaths", &TreeValueTransformTest::checkMappedPath); checker.checkKeyValueTreeObject(object, "Tree"); checkBackMapping(&checker, object, result.backMapping()); } diff --git a/src/gromacs/utility/tests/path.cpp b/src/gromacs/utility/tests/path.cpp index 89d43b0ed4..38638befd5 100644 --- a/src/gromacs/utility/tests/path.cpp +++ b/src/gromacs/utility/tests/path.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2016,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2016,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -76,10 +76,17 @@ TEST(PathTest, SearchOperationsWork) { gmx::test::TestReferenceData data; gmx::test::TestReferenceChecker rootChecker(data.rootChecker()); - for (const std::string& input : - { "", "md.log", "md", "/tmp/absolute.txt", "simpledir/traj.tng", "simpledir/traj", - "windowsdir\\traj.tng", "complex.dir/traj.tng", "complex.dir/traj", - "nested/dir/conf.pdb", "/tmp/absolutedir/conf.pdb" }) + for (const std::string& input : { "", + "md.log", + "md", + "/tmp/absolute.txt", + "simpledir/traj.tng", + "simpledir/traj", + "windowsdir\\traj.tng", + "complex.dir/traj.tng", + "complex.dir/traj", + "nested/dir/conf.pdb", + "/tmp/absolutedir/conf.pdb" }) { SCOPED_TRACE(std::string("for input '") + input + "'"); auto checker = rootChecker.checkCompound("PathToTest", input); diff --git a/src/gromacs/utility/tests/stringutil.cpp b/src/gromacs/utility/tests/stringutil.cpp index 0b2acccc24..db0c1f1857 100644 --- a/src/gromacs/utility/tests/stringutil.cpp +++ b/src/gromacs/utility/tests/stringutil.cpp @@ -241,8 +241,8 @@ TEST(formatAndJoinTest, Works) { const char* const words[] = { "The", "quick", "brown", "fox" }; EXPECT_EQ("The .quick .brown .fox ", - gmx::formatAndJoin(gmx::ArrayRef(words), ".", - gmx::StringFormatter("%-10s"))); + gmx::formatAndJoin( + gmx::ArrayRef(words), ".", gmx::StringFormatter("%-10s"))); const int values[] = { 0, 1, 4 }; EXPECT_EQ("0,1,4", diff --git a/src/gromacs/utility/tests/template_mp.cpp b/src/gromacs/utility/tests/template_mp.cpp index dba10585d1..3fe00e7a4c 100644 --- a/src/gromacs/utility/tests/template_mp.cpp +++ b/src/gromacs/utility/tests/template_mp.cpp @@ -61,8 +61,7 @@ TEST(TemplateMPTest, DispatchTemplatedFunction) { int five = 5; int two1plus2plus5 = dispatchTemplatedFunction( - [=](auto p1, auto p2) { return testEnumTwoIPlusJPlusK(five); }, Options::Op1, - Options::Op2); + [=](auto p1, auto p2) { return testEnumTwoIPlusJPlusK(five); }, Options::Op1, Options::Op2); EXPECT_EQ(two1plus2plus5, 9); } diff --git a/src/programs/legacymodules.cpp b/src/programs/legacymodules.cpp index f591e2c61b..17ef06f0cd 100644 --- a/src/programs/legacymodules.cpp +++ b/src/programs/legacymodules.cpp @@ -176,63 +176,82 @@ void registerLegacyModules(gmx::CommandLineModuleManager* manager) gmx::ICommandLineOptionsModule::registerModuleFactory( manager, gmx::DumpInfo::name, gmx::DumpInfo::shortDescription, &gmx::DumpInfo::create); registerModule(manager, &gmx_grompp, "grompp", "Make a run input file"); - gmx::ICommandLineOptionsModule::registerModuleFactory(manager, gmx::ConvertTprInfo::name, + gmx::ICommandLineOptionsModule::registerModuleFactory(manager, + gmx::ConvertTprInfo::name, gmx::ConvertTprInfo::shortDescription, &gmx::ConvertTprInfo::create); registerObsoleteTool(manager, "tpbconv"); registerModule(manager, &gmx_x2top, "x2top", "Generate a primitive topology from coordinates"); registerModuleNoNice( - manager, &gmx::gmx_mdrun, "mdrun", + manager, + &gmx::gmx_mdrun, + "mdrun", "Perform a simulation, do a normal mode analysis or an energy minimization"); - gmx::ICommandLineOptionsModule::registerModuleFactory( - manager, gmx::NonbondedBenchmarkInfo::name, - gmx::NonbondedBenchmarkInfo::shortDescription, &gmx::NonbondedBenchmarkInfo::create); + gmx::ICommandLineOptionsModule::registerModuleFactory(manager, + gmx::NonbondedBenchmarkInfo::name, + gmx::NonbondedBenchmarkInfo::shortDescription, + &gmx::NonbondedBenchmarkInfo::create); - gmx::ICommandLineOptionsModule::registerModuleFactory(manager, gmx::InsertMoleculesInfo::name(), + gmx::ICommandLineOptionsModule::registerModuleFactory(manager, + gmx::InsertMoleculesInfo::name(), gmx::InsertMoleculesInfo::shortDescription(), &gmx::InsertMoleculesInfo::create); - gmx::ICommandLineOptionsModule::registerModuleFactory(manager, gmx::ReportMethodsInfo::name, + gmx::ICommandLineOptionsModule::registerModuleFactory(manager, + gmx::ReportMethodsInfo::name, gmx::ReportMethodsInfo::shortDescription, &gmx::ReportMethodsInfo::create); - gmx::ICommandLineOptionsModule::registerModuleFactory(manager, gmx::pdb2gmxInfo::name, - gmx::pdb2gmxInfo::shortDescription, - &gmx::pdb2gmxInfo::create); + gmx::ICommandLineOptionsModule::registerModuleFactory( + manager, gmx::pdb2gmxInfo::name, gmx::pdb2gmxInfo::shortDescription, &gmx::pdb2gmxInfo::create); // Modules from gmx_ana.h. - registerModule(manager, &gmx_do_dssp, "do_dssp", + registerModule(manager, + &gmx_do_dssp, + "do_dssp", "Assign secondary structure and calculate solvent accessible surface area"); registerModule(manager, &gmx_editconf, "editconf", "Convert and manipulates structure files"); registerModule(manager, &gmx_eneconv, "eneconv", "Convert energy files"); registerModule(manager, &gmx_solvate, "solvate", "Solvate a system"); registerObsoleteTool(manager, "genbox"); - registerModule(manager, &gmx_genconf, "genconf", - "Multiply a conformation in 'random' orientations"); - registerModule(manager, &gmx_genion, "genion", + registerModule( + manager, &gmx_genconf, "genconf", "Multiply a conformation in 'random' orientations"); + registerModule(manager, + &gmx_genion, + "genion", "Generate monoatomic ions on energetically favorable positions"); - registerModule(manager, &gmx_genrestr, "genrestr", + registerModule(manager, + &gmx_genrestr, + "genrestr", "Generate position restraints or distance restraints for index groups"); - registerModule(manager, &gmx_make_edi, "make_edi", + registerModule(manager, + &gmx_make_edi, + "make_edi", "Generate input files for essential dynamics sampling"); registerModule(manager, &gmx_make_ndx, "make_ndx", "Make index files"); registerModule(manager, &gmx_mk_angndx, "mk_angndx", "Generate index files for 'gmx angle'"); registerModule(manager, &gmx_trjcat, "trjcat", "Concatenate trajectory files"); registerModule(manager, &gmx_trjconv, "trjconv", "Convert and manipulates trajectory files"); - registerModule(manager, &gmx_trjorder, "trjorder", + registerModule(manager, + &gmx_trjorder, + "trjorder", "Order molecules according to their distance to a group"); - registerModule(manager, &gmx_xpm2ps, "xpm2ps", - "Convert XPM (XPixelMap) matrices to postscript or XPM"); + registerModule( + manager, &gmx_xpm2ps, "xpm2ps", "Convert XPM (XPixelMap) matrices to postscript or XPM"); registerModule(manager, &gmx_anaeig, "anaeig", "Analyze eigenvectors/normal modes"); registerModule(manager, &gmx_analyze, "analyze", "Analyze data sets"); - registerModule(manager, &gmx_g_angle, "angle", + registerModule(manager, + &gmx_g_angle, + "angle", "Calculate distributions and correlations for angles and dihedrals"); - registerModule(manager, &gmx_awh, "awh", - "Extract data from an accelerated weight histogram (AWH) run"); - registerModule(manager, &gmx_bar, "bar", + registerModule( + manager, &gmx_awh, "awh", "Extract data from an accelerated weight histogram (AWH) run"); + registerModule(manager, + &gmx_bar, + "bar", "Calculate free energy difference estimates through Bennett's acceptance ratio"); registerObsoleteTool(manager, "bond"); registerObsoleteTool(manager, "dist"); @@ -240,90 +259,134 @@ void registerLegacyModules(gmx::CommandLineModuleManager* manager) registerObsoleteTool(manager, "sgangle"); registerModule(manager, &gmx_bundle, "bundle", "Analyze bundles of axes, e.g., helices"); - registerModule(manager, &gmx_chi, "chi", + registerModule(manager, + &gmx_chi, + "chi", "Calculate everything you want to know about chi and other dihedrals"); registerModule(manager, &gmx_cluster, "cluster", "Cluster structures"); - registerModule(manager, &gmx_clustsize, "clustsize", - "Calculate size distributions of atomic clusters"); + registerModule( + manager, &gmx_clustsize, "clustsize", "Calculate size distributions of atomic clusters"); registerModule(manager, &gmx_confrms, "confrms", "Fit two structures and calculates the RMSD"); registerModule(manager, &gmx_covar, "covar", "Calculate and diagonalize the covariance matrix"); - registerModule(manager, &gmx_current, "current", + registerModule(manager, + &gmx_current, + "current", "Calculate dielectric constants and current autocorrelation function"); registerModule(manager, &gmx_density, "density", "Calculate the density of the system"); - registerModule(manager, &gmx_densmap, "densmap", - "Calculate 2D planar or axial-radial density maps"); + registerModule( + manager, &gmx_densmap, "densmap", "Calculate 2D planar or axial-radial density maps"); registerModule(manager, &gmx_densorder, "densorder", "Calculate surface fluctuations"); - registerModule(manager, &gmx_dielectric, "dielectric", + registerModule(manager, + &gmx_dielectric, + "dielectric", "Calculate frequency dependent dielectric constants"); registerModule(manager, &gmx_dipoles, "dipoles", "Compute the total dipole plus fluctuations"); registerModule(manager, &gmx_disre, "disre", "Analyze distance restraints"); - registerModule(manager, &gmx_dos, "dos", - "Analyze density of states and properties based on that"); + registerModule( + manager, &gmx_dos, "dos", "Analyze density of states and properties based on that"); registerModule(manager, &gmx_dyecoupl, "dyecoupl", "Extract dye dynamics from trajectories"); registerModule(manager, &gmx_enemat, "enemat", "Extract an energy matrix from an energy file"); - registerModule(manager, &gmx_energy, "energy", - "Writes energies to xvg files and display averages"); - registerModule(manager, &gmx_filter, "filter", + registerModule( + manager, &gmx_energy, "energy", "Writes energies to xvg files and display averages"); + registerModule(manager, + &gmx_filter, + "filter", "Frequency filter trajectories, useful for making smooth movies"); registerModule(manager, &gmx_gyrate, "gyrate", "Calculate the radius of gyration"); registerModule(manager, &gmx_h2order, "h2order", "Compute the orientation of water molecules"); registerModule(manager, &gmx_hbond, "hbond", "Compute and analyze hydrogen bonds"); registerModule(manager, &gmx_helix, "helix", "Calculate basic properties of alpha helices"); - registerModule(manager, &gmx_helixorient, "helixorient", + registerModule(manager, + &gmx_helixorient, + "helixorient", "Calculate local pitch/bending/rotation/orientation inside helices"); - registerModule(manager, &gmx_hydorder, "hydorder", + registerModule(manager, + &gmx_hydorder, + "hydorder", "Compute tetrahedrality parameters around a given atom"); registerModule(manager, &gmx_lie, "lie", "Estimate free energy from linear combinations"); registerModule(manager, &gmx_mdmat, "mdmat", "Calculate residue contact maps"); - registerModule(manager, &gmx_mindist, "mindist", - "Calculate the minimum distance between two groups"); + registerModule( + manager, &gmx_mindist, "mindist", "Calculate the minimum distance between two groups"); registerModule(manager, &gmx_msd, "msd", "Calculates mean square displacements"); registerModule(manager, &gmx_nmeig, "nmeig", "Diagonalize the Hessian for normal mode analysis"); - registerModule(manager, &gmx_nmens, "nmens", + registerModule(manager, + &gmx_nmens, + "nmens", "Generate an ensemble of structures from the normal modes"); - registerModule(manager, &gmx_nmr, "nmr", + registerModule(manager, + &gmx_nmr, + "nmr", "Analyze nuclear magnetic resonance properties from an energy file"); - registerModule(manager, &gmx_nmtraj, "nmtraj", + registerModule(manager, + &gmx_nmtraj, + "nmtraj", "Generate a virtual oscillating trajectory from an eigenvector"); - registerModule(manager, &gmx_order, "order", - "Compute the order parameter per atom for carbon tails"); - registerModule(manager, &gmx_pme_error, "pme_error", + registerModule( + manager, &gmx_order, "order", "Compute the order parameter per atom for carbon tails"); + registerModule(manager, + &gmx_pme_error, + "pme_error", "Estimate the error of using PME with a given input file"); registerModule(manager, &gmx_polystat, "polystat", "Calculate static properties of polymers"); - registerModule(manager, &gmx_potential, "potential", + registerModule(manager, + &gmx_potential, + "potential", "Calculate the electrostatic potential across the box"); - registerModule(manager, &gmx_principal, "principal", + registerModule(manager, + &gmx_principal, + "principal", "Calculate principal axes of inertia for a group of atoms"); registerModule(manager, &gmx_rama, "rama", "Compute Ramachandran plots"); - registerModule(manager, &gmx_rms, "rms", + registerModule(manager, + &gmx_rms, + "rms", "Calculate RMSDs with a reference structure and RMSD matrices"); - registerModule(manager, &gmx_rmsdist, "rmsdist", + registerModule(manager, + &gmx_rmsdist, + "rmsdist", "Calculate atom pair distances averaged with power -2, -3 or -6"); registerModule(manager, &gmx_rmsf, "rmsf", "Calculate atomic fluctuations"); - registerModule(manager, &gmx_rotacf, "rotacf", + registerModule(manager, + &gmx_rotacf, + "rotacf", "Calculate the rotational correlation function for molecules"); - registerModule(manager, &gmx_rotmat, "rotmat", + registerModule(manager, + &gmx_rotmat, + "rotmat", "Plot the rotation matrix for fitting to a reference structure"); registerModule(manager, &gmx_saltbr, "saltbr", "Compute salt bridges"); registerModule(manager, &gmx_sans, "sans", "Compute small angle neutron scattering spectra"); registerModule(manager, &gmx_saxs, "saxs", "Compute small angle X-ray scattering spectra"); - registerModule(manager, &gmx_sham, "sham", - "Compute free energies or other histograms from histograms"); - registerModule(manager, &gmx_sigeps, "sigeps", + registerModule( + manager, &gmx_sham, "sham", "Compute free energies or other histograms from histograms"); + registerModule(manager, + &gmx_sigeps, + "sigeps", "Convert c6/12 or c6/cn combinations to and from sigma/epsilon"); registerModule(manager, &gmx_sorient, "sorient", "Analyze solvent orientation around solutes"); registerModule(manager, &gmx_spatial, "spatial", "Calculate the spatial distribution function"); - registerModule(manager, &gmx_spol, "spol", + registerModule(manager, + &gmx_spol, + "spol", "Analyze solvent dipole orientation and polarization around solutes"); registerModule(manager, &gmx_tcaf, "tcaf", "Calculate viscosities of liquids"); - registerModule(manager, &gmx_traj, "traj", + registerModule(manager, + &gmx_traj, + "traj", "Plot x, v, f, box, temperature and rotational energy from trajectories"); - registerModule(manager, &gmx_tune_pme, "tune_pme", + registerModule(manager, + &gmx_tune_pme, + "tune_pme", "Time mdrun as a function of PME ranks to optimize settings"); - registerModule(manager, &gmx_vanhove, "vanhove", + registerModule(manager, + &gmx_vanhove, + "vanhove", "Compute Van Hove displacement and correlation functions"); registerModule(manager, &gmx_velacc, "velacc", "Calculate velocity autocorrelation functions"); - registerModule(manager, &gmx_wham, "wham", + registerModule(manager, + &gmx_wham, + "wham", "Perform weighted histogram analysis after umbrella sampling"); registerModule(manager, &gmx_wheel, "wheel", "Plot helical wheels"); registerModuleNoNice(manager, &gmx_view, "view", "View a trajectory on an X-Windows terminal"); diff --git a/src/programs/mdrun/mdrun.cpp b/src/programs/mdrun/mdrun.cpp index 77a25f1fdf..7c59e4e677 100644 --- a/src/programs/mdrun/mdrun.cpp +++ b/src/programs/mdrun/mdrun.cpp @@ -236,9 +236,12 @@ int gmx_mdrun(MPI_Comm communicator, const gmx_hw_info_t& hwinfo, int argc, char StartingBehavior startingBehavior = StartingBehavior::NewSimulation; LogFilePtr logFileGuard = nullptr; gmx_multisim_t* ms = simulationContext.multiSimulation_.get(); - std::tie(startingBehavior, logFileGuard) = handleRestart( - findIsSimulationMasterRank(ms, communicator), communicator, ms, - options.mdrunOptions.appendingBehavior, ssize(options.filenames), options.filenames.data()); + std::tie(startingBehavior, logFileGuard) = handleRestart(findIsSimulationMasterRank(ms, communicator), + communicator, + ms, + options.mdrunOptions.appendingBehavior, + ssize(options.filenames), + options.filenames.data()); /* The named components for the builder exposed here are descriptive of the * state of mdrun at implementation and are not intended to be prescriptive diff --git a/src/programs/mdrun/tests/energycomparison.cpp b/src/programs/mdrun/tests/energycomparison.cpp index cea5e9d021..3325d1708a 100644 --- a/src/programs/mdrun/tests/energycomparison.cpp +++ b/src/programs/mdrun/tests/energycomparison.cpp @@ -114,8 +114,8 @@ void EnergyComparison::operator()(const EnergyFrame& reference, const EnergyFram { auto& energyValueInReference = referenceIt->second; auto& energyValueInTest = testIt->second; - EXPECT_REAL_EQ_TOL(energyValueInReference, energyValueInTest, - energyTermsToCompare_.at(energyName)); + EXPECT_REAL_EQ_TOL( + energyValueInReference, energyValueInTest, energyTermsToCompare_.at(energyName)); } else { @@ -185,8 +185,8 @@ void checkEnergiesAgainstReferenceData(const std::string& energyFilenam const EnergyTermsToCompare& energyTermsToCompare, TestReferenceChecker* checker) { - checkEnergiesAgainstReferenceData(energyFilename, energyTermsToCompare, checker, - MaxNumFrames::compareAllFrames()); + checkEnergiesAgainstReferenceData( + energyFilename, energyTermsToCompare, checker, MaxNumFrames::compareAllFrames()); } } // namespace test diff --git a/src/programs/mdrun/tests/ewaldsurfaceterm.cpp b/src/programs/mdrun/tests/ewaldsurfaceterm.cpp index 367d0abb42..df6c75b82e 100644 --- a/src/programs/mdrun/tests/ewaldsurfaceterm.cpp +++ b/src/programs/mdrun/tests/ewaldsurfaceterm.cpp @@ -104,7 +104,9 @@ TEST_P(EwaldSurfaceTermTest, WithinTolerances) fprintf(stdout, "Test system '%s' cannot run with %d ranks.\n" "The supported numbers are %s 1.\n", - simulationName.c_str(), numRanksAvailable, numRanksAvailable == 1 ? ">" : "="); + simulationName.c_str(), + numRanksAvailable, + numRanksAvailable == 1 ? ">" : "="); return; } diff --git a/src/programs/mdrun/tests/exactcontinuation.cpp b/src/programs/mdrun/tests/exactcontinuation.cpp index ed70e3d663..8c922b8e6c 100644 --- a/src/programs/mdrun/tests/exactcontinuation.cpp +++ b/src/programs/mdrun/tests/exactcontinuation.cpp @@ -224,7 +224,8 @@ void runTest(TestFileManager* fileManager, fprintf(stdout, "Test system '%s' cannot run with %d ranks.\n" "The supported numbers are: %s\n", - simulationName.c_str(), numRanksAvailable, + simulationName.c_str(), + numRanksAvailable, reportNumbersOfPpRanksSupported(simulationName).c_str()); return; } @@ -377,10 +378,13 @@ TEST_P(MdrunNoAppendContinuationIsExact, WithinTolerances) SCOPED_TRACE( formatString("Comparing normal and two-part run of simulation '%s' " "with integrator '%s'", - simulationName.c_str(), integrator.c_str())); + simulationName.c_str(), + integrator.c_str())); - auto mdpFieldValues = prepareMdpFieldValues(simulationName.c_str(), integrator.c_str(), - temperatureCoupling.c_str(), pressureCoupling.c_str()); + auto mdpFieldValues = prepareMdpFieldValues(simulationName.c_str(), + integrator.c_str(), + temperatureCoupling.c_str(), + pressureCoupling.c_str()); // The exact lambda state choice is unimportant, so long as there // is one when using an FEP input. mdpFieldValues["other"] += formatString("\ninit-lambda-state = %d", 3); @@ -417,20 +421,19 @@ TEST_P(MdrunNoAppendContinuationIsExact, WithinTolerances) if (pressureCoupling == "parrinello-rahman") { - energyTermsToCompare.insert( - { "Box-Vel-XX", relativeToleranceAsPrecisionDependentUlp(1e-12, ulpToleranceInMixed, - ulpToleranceInDouble) }); - energyTermsToCompare.insert( - { "Box-Vel-YY", relativeToleranceAsPrecisionDependentUlp(1e-12, ulpToleranceInMixed, - ulpToleranceInDouble) }); - energyTermsToCompare.insert( - { "Box-Vel-ZZ", relativeToleranceAsPrecisionDependentUlp(1e-12, ulpToleranceInMixed, - ulpToleranceInDouble) }); + energyTermsToCompare.insert({ "Box-Vel-XX", + relativeToleranceAsPrecisionDependentUlp( + 1e-12, ulpToleranceInMixed, ulpToleranceInDouble) }); + energyTermsToCompare.insert({ "Box-Vel-YY", + relativeToleranceAsPrecisionDependentUlp( + 1e-12, ulpToleranceInMixed, ulpToleranceInDouble) }); + energyTermsToCompare.insert({ "Box-Vel-ZZ", + relativeToleranceAsPrecisionDependentUlp( + 1e-12, ulpToleranceInMixed, ulpToleranceInDouble) }); } int numWarningsToTolerate = 1; - runTest(&fileManager_, &runner_, simulationName, numWarningsToTolerate, mdpFieldValues, - energyTermsToCompare); + runTest(&fileManager_, &runner_, simulationName, numWarningsToTolerate, mdpFieldValues, energyTermsToCompare); } // TODO The time for OpenCL kernel compilation means these tests time diff --git a/src/programs/mdrun/tests/freeenergy.cpp b/src/programs/mdrun/tests/freeenergy.cpp index 2e012bfb16..6c39160bf3 100644 --- a/src/programs/mdrun/tests/freeenergy.cpp +++ b/src/programs/mdrun/tests/freeenergy.cpp @@ -158,8 +158,8 @@ TEST_P(FreeEnergyReferenceTest, WithinTolerances) } else { - checkTrajectoryAgainstReferenceData(simulationTrajectoryFileName, trajectoryComparison, - &rootChecker, MaxNumFrames(1)); + checkTrajectoryAgainstReferenceData( + simulationTrajectoryFileName, trajectoryComparison, &rootChecker, MaxNumFrames(1)); } if (File::exists(simulationDhdlFileName, File::returnFalseOnError)) { diff --git a/src/programs/mdrun/tests/initialconstraints.cpp b/src/programs/mdrun/tests/initialconstraints.cpp index d4ae76ae5b..66bbeb797e 100644 --- a/src/programs/mdrun/tests/initialconstraints.cpp +++ b/src/programs/mdrun/tests/initialconstraints.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2017,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2017,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -92,7 +92,9 @@ TEST_P(InitialConstraintsTest, Works) "integrator = %s\n" "nsteps = %d\n" "dt = %f\n", - integratorName.c_str(), nsteps, timestep); + integratorName.c_str(), + nsteps, + timestep); runner_.useStringAsMdpFile(theMdpFile); diff --git a/src/programs/mdrun/tests/minimize.cpp b/src/programs/mdrun/tests/minimize.cpp index 1a0077c960..5a3d920eac 100644 --- a/src/programs/mdrun/tests/minimize.cpp +++ b/src/programs/mdrun/tests/minimize.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2018,2019, by the GROMACS development team, led by + * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -101,7 +101,8 @@ TEST_P(EnergyMinimizationTest, WithinTolerances) auto simulationName = std::get<0>(params); auto minimizer = std::get<1>(params); SCOPED_TRACE(formatString("Comparing '%s' energy minimization for simulation '%s'", - minimizer.c_str(), simulationName.c_str())); + minimizer.c_str(), + simulationName.c_str())); // TODO At some point we should also test PME-only ranks. int numRanksAvailable = getNumberOfTestMpiRanks(); @@ -110,7 +111,8 @@ TEST_P(EnergyMinimizationTest, WithinTolerances) fprintf(stdout, "Test system '%s' cannot run with %d ranks.\n" "The supported numbers are: %s\n", - simulationName.c_str(), numRanksAvailable, + simulationName.c_str(), + numRanksAvailable, reportNumbersOfPpRanksSupported(simulationName).c_str()); return; } @@ -168,7 +170,8 @@ std::vector unconstrainedSystemsToTest_g = { "argon12", "glycine_no_constraints_vacuo" }; std::vector minimizersToTest_g = { "steep", "cg", "l-bfgs" }; -std::vector constrainedSystemsToTest_g = { "tip3p5", "glycine_vacuo", +std::vector constrainedSystemsToTest_g = { "tip3p5", + "glycine_vacuo", "alanine_vsite_vacuo" }; std::vector minimizersToTestWithConstraints_g = { "steep", "cg" }; //! \} diff --git a/src/programs/mdrun/tests/moduletest.cpp b/src/programs/mdrun/tests/moduletest.cpp index 9cb67be37e..7442deacb1 100644 --- a/src/programs/mdrun/tests/moduletest.cpp +++ b/src/programs/mdrun/tests/moduletest.cpp @@ -316,8 +316,10 @@ int SimulationRunner::callMdrun(const CommandLine& callerRef) caller.addOption("-ntomp", g_numOpenMPThreads); #endif - return gmx_mdrun(MdrunTestFixtureBase::communicator_, *MdrunTestFixtureBase::hwinfo_, - caller.argc(), caller.argv()); + return gmx_mdrun(MdrunTestFixtureBase::communicator_, + *MdrunTestFixtureBase::hwinfo_, + caller.argc(), + caller.argv()); } int SimulationRunner::callMdrun() diff --git a/src/programs/mdrun/tests/multiple_time_stepping.cpp b/src/programs/mdrun/tests/multiple_time_stepping.cpp index a3022f3d43..6851b7bdc1 100644 --- a/src/programs/mdrun/tests/multiple_time_stepping.cpp +++ b/src/programs/mdrun/tests/multiple_time_stepping.cpp @@ -87,8 +87,8 @@ TEST_P(MtsComparisonTest, WithinTolerances) auto mtsScheme = std::get<1>(params); // Note that there should be no relevant limitation on MPI ranks and OpenMP threads - SCOPED_TRACE(formatString("Comparing for '%s' no MTS with MTS scheme '%s'", - simulationName.c_str(), mtsScheme.c_str())); + SCOPED_TRACE(formatString( + "Comparing for '%s' no MTS with MTS scheme '%s'", simulationName.c_str(), mtsScheme.c_str())); const bool isPullTest = (mtsScheme.find("pull") != std::string::npos); @@ -104,7 +104,8 @@ TEST_P(MtsComparisonTest, WithinTolerances) "rcoulomb = 0.9\n" "rvdw = 0.9\n" "constraints = h-bonds\n", - numSteps, isPullTest ? "reaction-field" : "PME"); + numSteps, + isPullTest ? "reaction-field" : "PME"); if (isPullTest) { @@ -131,7 +132,9 @@ TEST_P(MtsComparisonTest, WithinTolerances) "nstxout = 0\n" "nstvout = 0\n" "nstfout = %d\n", - numSteps, numSteps, nstfout); + numSteps, + numSteps, + nstfout); auto mtsMdpOptions = sharedMdpOptions + gmx::formatString( @@ -144,7 +147,10 @@ TEST_P(MtsComparisonTest, WithinTolerances) "nstxout = 0\n" "nstvout = 0\n" "nstfout = %d\n", - mtsScheme.c_str(), numSteps, numSteps, nstfout); + mtsScheme.c_str(), + numSteps, + numSteps, + nstfout); // At step 0 the energy and virial should only differ due to rounding errors EnergyTermsToCompare energyTermsToCompareStep0 = energyTermsToCompare(0.001, 0.01); @@ -190,12 +196,14 @@ TEST_P(MtsComparisonTest, WithinTolerances) runMdrun(&runner_); // Compare simulation results at step 0, which should be indentical - compareEnergies(simulator1EdrFileName, simulator2EdrFileName, energyTermsToCompareStep0, - MaxNumFrames(1)); + compareEnergies( + simulator1EdrFileName, simulator2EdrFileName, energyTermsToCompareStep0, MaxNumFrames(1)); compareTrajectories(simulator1TrajectoryFileName, simulator2TrajectoryFileName, trajectoryComparison); // Compare energies at the last step (and step 0 again) with lower tolerance - compareEnergies(simulator1EdrFileName, simulator2EdrFileName, energyTermsToCompareAllSteps, + compareEnergies(simulator1EdrFileName, + simulator2EdrFileName, + energyTermsToCompareAllSteps, MaxNumFrames::compareAllFrames()); } diff --git a/src/programs/mdrun/tests/multisimtest.cpp b/src/programs/mdrun/tests/multisimtest.cpp index b53756599b..8295f42112 100644 --- a/src/programs/mdrun/tests/multisimtest.cpp +++ b/src/programs/mdrun/tests/multisimtest.cpp @@ -114,13 +114,16 @@ void MultiSimTest::organizeMdpFile(SimulationRunner* runner, const char* control "gen-temp = %f\n" // control variable specification "%s\n", - numSteps, baseTemperature + 0.0001 * rank_, basePressure * std::pow(1.01, rank_), + numSteps, + baseTemperature + 0.0001 * rank_, + basePressure * std::pow(1.01, rank_), /* Set things up so that the initial KE decreases with increasing replica number, so that the (identical) starting PE decreases on the first step more for the replicas with higher number, which will tend to force replica exchange to occur. */ - std::max(baseTemperature - 10 * rank_, real(0)), controlVariable); + std::max(baseTemperature - 10 * rank_, real(0)), + controlVariable); runner->useStringAsMdpFile(mdpFileContents); } diff --git a/src/programs/mdrun/tests/nonbonded_bench.cpp b/src/programs/mdrun/tests/nonbonded_bench.cpp index ea92e2c80b..1bbb0023a4 100644 --- a/src/programs/mdrun/tests/nonbonded_bench.cpp +++ b/src/programs/mdrun/tests/nonbonded_bench.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2018,2019, by the GROMACS development team, led by + * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -63,8 +63,9 @@ TEST(NonbondedBenchTest, BasicEndToEndTest) const char* const command[] = { "nonbonded-benchmark" }; CommandLine cmdline(command); cmdline.addOption("-iter", 1); - EXPECT_EQ(0, gmx::test::CommandLineTestHelper::runModuleFactory( - &gmx::NonbondedBenchmarkInfo::create, &cmdline)); + EXPECT_EQ(0, + gmx::test::CommandLineTestHelper::runModuleFactory( + &gmx::NonbondedBenchmarkInfo::create, &cmdline)); } } // namespace diff --git a/src/programs/mdrun/tests/normalmodes.cpp b/src/programs/mdrun/tests/normalmodes.cpp index 23bf340824..3ef84e572a 100644 --- a/src/programs/mdrun/tests/normalmodes.cpp +++ b/src/programs/mdrun/tests/normalmodes.cpp @@ -102,7 +102,8 @@ TEST_P(NormalModesTest, WithinTolerances) fprintf(stdout, "Test system '%s' cannot run with %d ranks.\n" "The supported numbers are: %s\n", - simulationName.c_str(), numRanksAvailable, + simulationName.c_str(), + numRanksAvailable, reportNumbersOfPpRanksSupported(simulationName).c_str()); return; } @@ -151,7 +152,10 @@ TEST_P(NormalModesTest, WithinTolerances) //! Containers of systems and integrators to test. //! \{ -std::vector systemsToTest_g = { "scaled-water", "villin", "spc-dimer", "one-tip5p", +std::vector systemsToTest_g = { "scaled-water", + "villin", + "spc-dimer", + "one-tip5p", "sw-dimer" }; std::vector integratorsToTest_g = { "nm" }; diff --git a/src/programs/mdrun/tests/outputfiles.cpp b/src/programs/mdrun/tests/outputfiles.cpp index 9414b16c9f..e8fddc65e6 100644 --- a/src/programs/mdrun/tests/outputfiles.cpp +++ b/src/programs/mdrun/tests/outputfiles.cpp @@ -81,7 +81,8 @@ TEST_P(OutputFiles, FilesArePresent) SCOPED_TRACE( formatString("Checking for presence of expected output files using " "simulation '%s' with integrator '%s'", - simulationName.c_str(), integrator.c_str())); + simulationName.c_str(), + integrator.c_str())); // Prepare the .tpr file { @@ -98,8 +99,10 @@ TEST_P(OutputFiles, FilesArePresent) } // Check if expected files are present { - for (const auto& file : { runner_.fullPrecisionTrajectoryFileName_, runner_.logFileName_, - runner_.edrFileName_, fileManager_.getTemporaryFilePath("state.gro"), + for (const auto& file : { runner_.fullPrecisionTrajectoryFileName_, + runner_.logFileName_, + runner_.edrFileName_, + fileManager_.getTemporaryFilePath("state.gro"), fileManager_.getTemporaryFilePath("state.cpt") }) { EXPECT_TRUE(File::exists(file, File::returnFalseOnError)) diff --git a/src/programs/mdrun/tests/periodicactions.cpp b/src/programs/mdrun/tests/periodicactions.cpp index 6dc8f02e42..eae2f19b71 100644 --- a/src/programs/mdrun/tests/periodicactions.cpp +++ b/src/programs/mdrun/tests/periodicactions.cpp @@ -117,10 +117,14 @@ void PeriodicActionsTest::doMdrun(const PeriodicOutputParameters& output) auto propagation = std::get<0>(GetParam()); SCOPED_TRACE( formatString("Doing %s simulation with %s integrator, %s tcoupling and %s pcoupling\n", - propagation["simulationName"].c_str(), propagation["integrator"].c_str(), - propagation["tcoupl"].c_str(), propagation["pcoupl"].c_str())); - auto mdpFieldValues = prepareMdpFieldValues(propagation["simulationName"], propagation["integrator"], - propagation["tcoupl"], propagation["pcoupl"]); + propagation["simulationName"].c_str(), + propagation["integrator"].c_str(), + propagation["tcoupl"].c_str(), + propagation["pcoupl"].c_str())); + auto mdpFieldValues = prepareMdpFieldValues(propagation["simulationName"], + propagation["integrator"], + propagation["tcoupl"], + propagation["pcoupl"]); mdpFieldValues.insert(propagation.begin(), propagation.end()); mdpFieldValues.insert(output.begin(), output.end()); @@ -205,7 +209,8 @@ TEST_P(PeriodicActionsTest, PeriodicActionsAgreeWithReference) { auto propagation = std::get<0>(GetParam()); SCOPED_TRACE(formatString("Comparing two simulations of '%s' with integrator '%s'", - propagation["simulationName"].c_str(), propagation["integrator"].c_str())); + propagation["simulationName"].c_str(), + propagation["integrator"].c_str())); prepareReferenceData(); @@ -233,7 +238,8 @@ TEST_P(PeriodicActionsTest, PeriodicActionsAgreeWithReference) + "' and test '" + runner_.edrFileName_ + "'"); shouldContinueComparing = shouldContinueComparing && compareFrames(referenceEnergyFrameReader.get(), - testEnergyFrameReader.get(), energyComparison_); + testEnergyFrameReader.get(), + energyComparison_); } } } diff --git a/src/programs/mdrun/tests/rerun.cpp b/src/programs/mdrun/tests/rerun.cpp index e358b9cd1e..8bf4485e71 100644 --- a/src/programs/mdrun/tests/rerun.cpp +++ b/src/programs/mdrun/tests/rerun.cpp @@ -124,7 +124,8 @@ void executeRerunTest(TestFileManager* fileManager, fprintf(stdout, "Test system '%s' cannot run with %d ranks.\n" "The supported numbers are: %s\n", - simulationName.c_str(), numRanksAvailable, + simulationName.c_str(), + numRanksAvailable, reportNumbersOfPpRanksSupported(simulationName).c_str()); return; } @@ -169,7 +170,8 @@ TEST_P(MdrunRerunTest, WithinTolerances) SCOPED_TRACE( formatString("Comparing normal and rerun of simulation '%s' " "with integrator '%s'", - simulationName.c_str(), integrator.c_str())); + simulationName.c_str(), + integrator.c_str())); auto mdpFieldValues = prepareMdpFieldValues(simulationName.c_str(), integrator.c_str(), "no", "no"); @@ -178,8 +180,8 @@ TEST_P(MdrunRerunTest, WithinTolerances) const int toleranceScaleFactor = (integrator == "bd") ? 2 : 1; EnergyTermsToCompare energyTermsToCompare{ { { interaction_function[F_EPOT].longname, - relativeToleranceAsPrecisionDependentUlp(10.0, 24 * toleranceScaleFactor, - 40 * toleranceScaleFactor) }, + relativeToleranceAsPrecisionDependentUlp( + 10.0, 24 * toleranceScaleFactor, 40 * toleranceScaleFactor) }, } }; // Specify how trajectory frame matching must work @@ -187,8 +189,13 @@ TEST_P(MdrunRerunTest, WithinTolerances) TrajectoryComparison::s_defaultTrajectoryTolerances }; int numWarningsToTolerate = 0; - executeRerunTest(&fileManager_, &runner_, simulationName, numWarningsToTolerate, mdpFieldValues, - energyTermsToCompare, trajectoryComparison); + executeRerunTest(&fileManager_, + &runner_, + simulationName, + numWarningsToTolerate, + mdpFieldValues, + energyTermsToCompare, + trajectoryComparison); } // TODO The time for OpenCL kernel compilation means these tests time @@ -223,7 +230,9 @@ TEST_P(MdrunRerunFreeEnergyTest, WithinTolerances) SCOPED_TRACE( formatString("Comparing normal and rerun of simulation '%s' " "with integrator '%s' for initial lambda state %d", - simulationName.c_str(), integrator.c_str(), initLambdaState)); + simulationName.c_str(), + integrator.c_str(), + initLambdaState)); auto mdpFieldValues = prepareMdpFieldValues(simulationName.c_str(), integrator.c_str(), "no", "no"); @@ -246,8 +255,13 @@ TEST_P(MdrunRerunFreeEnergyTest, WithinTolerances) // The md integrator triggers a warning for nearly decoupled // states, which we need to suppress. TODO sometimes? int numWarningsToTolerate = (integrator == "md") ? 1 : 0; - executeRerunTest(&fileManager_, &runner_, simulationName, numWarningsToTolerate, mdpFieldValues, - energyTermsToCompare, trajectoryComparison); + executeRerunTest(&fileManager_, + &runner_, + simulationName, + numWarningsToTolerate, + mdpFieldValues, + energyTermsToCompare, + trajectoryComparison); } // TODO The time for OpenCL kernel compilation means these tests time diff --git a/src/programs/mdrun/tests/simple_mdrun.cpp b/src/programs/mdrun/tests/simple_mdrun.cpp index 7d0bf8c017..66cc3acdee 100644 --- a/src/programs/mdrun/tests/simple_mdrun.cpp +++ b/src/programs/mdrun/tests/simple_mdrun.cpp @@ -117,7 +117,8 @@ TEST_P(SimpleMdrunTest, WithinTolerances) fprintf(stdout, "Test system '%s' cannot run with %d ranks.\n" "The supported numbers are: %s\n", - simulationName.c_str(), numRanksAvailable, + simulationName.c_str(), + numRanksAvailable, reportNumbersOfPpRanksSupported(simulationName).c_str()); return; } diff --git a/src/programs/mdrun/tests/simulator.cpp b/src/programs/mdrun/tests/simulator.cpp index 31be90d878..b8aec654a7 100644 --- a/src/programs/mdrun/tests/simulator.cpp +++ b/src/programs/mdrun/tests/simulator.cpp @@ -97,7 +97,8 @@ TEST_P(SimulatorComparisonTest, WithinTolerances) fprintf(stdout, "Test system '%s' cannot run with %d ranks.\n" "The supported numbers are: %s\n", - simulationName.c_str(), numRanksAvailable, + simulationName.c_str(), + numRanksAvailable, reportNumbersOfPpRanksSupported(simulationName).c_str()); return; } @@ -115,11 +116,14 @@ TEST_P(SimulatorComparisonTest, WithinTolerances) "Comparing two simulations of '%s' " "with integrator '%s', '%s' temperature coupling, and '%s' pressure coupling " "switching environment variable '%s'", - simulationName.c_str(), integrator.c_str(), tcoupling.c_str(), pcoupling.c_str(), + simulationName.c_str(), + integrator.c_str(), + tcoupling.c_str(), + pcoupling.c_str(), environmentVariable.c_str())); - const auto mdpFieldValues = prepareMdpFieldValues(simulationName.c_str(), integrator.c_str(), - tcoupling.c_str(), pcoupling.c_str()); + const auto mdpFieldValues = prepareMdpFieldValues( + simulationName.c_str(), integrator.c_str(), tcoupling.c_str(), pcoupling.c_str()); EnergyTermsToCompare energyTermsToCompare{ { { interaction_function[F_EPOT].longname, relativeToleranceAsPrecisionDependentUlp(10.0, 100, 80) }, diff --git a/src/programs/mdrun/tests/termination.cpp b/src/programs/mdrun/tests/termination.cpp index 105baba910..cbc587effa 100644 --- a/src/programs/mdrun/tests/termination.cpp +++ b/src/programs/mdrun/tests/termination.cpp @@ -108,9 +108,7 @@ TEST_F(MdrunTerminationTest, CheckpointRestartAppendsByDefault) ASSERT_EQ(0, runner_.callMdrun(secondPart)); auto logFileContents = TextReader::readFileToString(runner_.logFileName_); - EXPECT_NE( - std::string::npos, - logFileContents.find("Restarting from checkpoint, appending to previous log file")) + EXPECT_NE(std::string::npos, logFileContents.find("Restarting from checkpoint, appending to previous log file")) << "appending was not detected"; } } @@ -297,9 +295,7 @@ TEST_F(MdrunTerminationTest, CheckpointRestartWorksEvenWithMissingCheckpointFile ASSERT_EQ(0, runner_.callMdrun(secondPart)); auto logFileContents = TextReader::readFileToString(runner_.logFileName_); - EXPECT_EQ( - std::string::npos, - logFileContents.find("Restarting from checkpoint, appending to previous log file")) + EXPECT_EQ(std::string::npos, logFileContents.find("Restarting from checkpoint, appending to previous log file")) << "appending was not detected"; } } diff --git a/src/programs/mdrun/tests/tpitest.cpp b/src/programs/mdrun/tests/tpitest.cpp index 242e476b79..9802164ceb 100644 --- a/src/programs/mdrun/tests/tpitest.cpp +++ b/src/programs/mdrun/tests/tpitest.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2018,2019, by the GROMACS development team, led by + * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -134,7 +134,8 @@ TEST_P(TpiTest, ReproducesOutput) ref_t = 298 nsteps = %d )", - randomSeed, nsteps); + randomSeed, + nsteps); runner_.useStringAsMdpFile(mdpFileContents); runTest(); diff --git a/src/programs/mdrun/tests/trajectorycomparison.cpp b/src/programs/mdrun/tests/trajectorycomparison.cpp index 72aea1dcef..d8f3657198 100644 --- a/src/programs/mdrun/tests/trajectorycomparison.cpp +++ b/src/programs/mdrun/tests/trajectorycomparison.cpp @@ -405,8 +405,8 @@ void checkTrajectoryAgainstReferenceData(const std::string& trajectoryF const TrajectoryComparison& trajectoryComparison, TestReferenceChecker* checker) { - checkTrajectoryAgainstReferenceData(trajectoryFilename, trajectoryComparison, checker, - MaxNumFrames::compareAllFrames()); + checkTrajectoryAgainstReferenceData( + trajectoryFilename, trajectoryComparison, checker, MaxNumFrames::compareAllFrames()); } void checkTrajectoryAgainstReferenceData(const std::string& trajectoryFilename, diff --git a/src/programs/mdrun/tests/trajectoryreader.cpp b/src/programs/mdrun/tests/trajectoryreader.cpp index ff08891e90..5543cb9786 100644 --- a/src/programs/mdrun/tests/trajectoryreader.cpp +++ b/src/programs/mdrun/tests/trajectoryreader.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2016,2017,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2016,2017,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -118,8 +118,8 @@ bool TrajectoryFrameReader::readNextFrame() { t_trxstatus* trajectoryFile; int flags = TRX_READ_X | TRX_READ_V | TRX_READ_F; - nextFrameExists_ = read_first_frame(oenvGuard_.get(), &trajectoryFile, filename_.c_str(), - trxframeGuard_.get(), flags); + nextFrameExists_ = read_first_frame( + oenvGuard_.get(), &trajectoryFile, filename_.c_str(), trxframeGuard_.get(), flags); if (!trajectoryFile) { GMX_THROW(FileIOError("Could not open trajectory file " + filename_ + " for reading")); diff --git a/src/programs/mdrun_main.cpp b/src/programs/mdrun_main.cpp index 1e77a6a4da..416c3c3468 100644 --- a/src/programs/mdrun_main.cpp +++ b/src/programs/mdrun_main.cpp @@ -1,7 +1,7 @@ /* * This file is part of the GROMACS molecular simulation package. * - * Copyright (c) 2013,2014,2016,2018,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2016,2018,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -52,6 +52,6 @@ void initSettingsNoNice(gmx::CommandLineModuleSettings* settings) int main(int argc, char* argv[]) { - return gmx::CommandLineModuleManager::runAsMainCMainWithSettings(argc, argv, &gmx::gmx_mdrun, - &initSettingsNoNice); + return gmx::CommandLineModuleManager::runAsMainCMainWithSettings( + argc, argv, &gmx::gmx_mdrun, &initSettingsNoNice); } diff --git a/src/programs/view/buttons.cpp b/src/programs/view/buttons.cpp index ea66889c2b..82c5114578 100644 --- a/src/programs/view/buttons.cpp +++ b/src/programs/view/buttons.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2013, The GROMACS development team. - * Copyright (c) 2013,2014,2015,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2015,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -178,10 +178,15 @@ t_butbox* init_vbox(t_x11* x11, Window Parent, Window SendTo, unsigned long fg, /* VBox holder */ y0 = XTextHeight(x11->font) + 2 * AIR + 2; - InitWin(&vb->wd, 0, 0, vb->nbut * (play_width + AIR) + AIR, y0 + play_height + 2 * AIR, 1, + InitWin(&vb->wd, + 0, + 0, + vb->nbut * (play_width + AIR) + AIR, + y0 + play_height + 2 * AIR, + 1, "VCR - Control"); - vb->wd.self = XCreateSimpleWindow(x11->disp, Parent, vb->wd.x, vb->wd.y, vb->wd.width, - vb->wd.height, vb->wd.bwidth, fg, bg); + vb->wd.self = XCreateSimpleWindow( + x11->disp, Parent, vb->wd.x, vb->wd.y, vb->wd.width, vb->wd.height, vb->wd.bwidth, fg, bg); x11->RegisterCallback(x11, vb->wd.self, Parent, VBCallBack, vb); x11->SetInputMask(x11, vb->wd.self, ExposureMask); @@ -199,12 +204,12 @@ t_butbox* init_vbox(t_x11* x11, Window Parent, Window SendTo, unsigned long fg, default: fprintf(stderr, "Invalid bitmap in init_vbox %d\n", ID); std::exit(1); } /* Rely on the fact that all bitmaps are equal size */ - pm = XCreatePixmapFromBitmapData(x11->disp, x11->root, (char*)data, play_width, play_height, - BLACK, LIGHTGREY, x11->depth); + pm = XCreatePixmapFromBitmapData( + x11->disp, x11->root, (char*)data, play_width, play_height, BLACK, LIGHTGREY, x11->depth); vb->b[i].ID = ID; vb->b[i].wd.Parent = SendTo; - vb->b[i].wd.self = XCreateSimpleWindow(x11->disp, vb->wd.self, x, y0 + AIR, play_width, - play_height, 0, WHITE, BLACK); + vb->b[i].wd.self = XCreateSimpleWindow( + x11->disp, vb->wd.self, x, y0 + AIR, play_width, play_height, 0, WHITE, BLACK); XSetWindowBackgroundPixmap(x11->disp, vb->b[i].wd.self, pm); x11->RegisterCallback(x11, vb->b[i].wd.self, vb->wd.self, ButtonCallBack, &(vb->b[i])); @@ -245,8 +250,8 @@ t_butbox* init_bbox(t_x11* x11, Window Parent, Window SendTo, int width, unsigne InitWin(&(bbox->wd), 0, 0, /*width,(y0+AIR)*IDBUTNR+AIR+2*BORDER,*/ 1, 1, 1, "Button Box"); width -= 2 * AIR + 2 * BORDER; - bbox->wd.self = XCreateSimpleWindow(x11->disp, Parent, bbox->wd.x, bbox->wd.y, bbox->wd.width, - bbox->wd.height, bbox->wd.bwidth, fg, bg); + bbox->wd.self = XCreateSimpleWindow( + x11->disp, Parent, bbox->wd.x, bbox->wd.y, bbox->wd.width, bbox->wd.height, bbox->wd.bwidth, fg, bg); x11->RegisterCallback(x11, bbox->wd.self, Parent, BBCallBack, bbox); x11->SetInputMask(x11, bbox->wd.self, StructureNotifyMask); @@ -259,8 +264,8 @@ t_butbox* init_bbox(t_x11* x11, Window Parent, Window SendTo, int width, unsigne h0 += y0 + AIR; but->wd.Parent = SendTo; but->ID = i; - but->wd.self = XCreateSimpleWindow(x11->disp, DrawOn, but->wd.x, but->wd.y, but->wd.width, - but->wd.height, but->wd.bwidth, bg, bg); + but->wd.self = XCreateSimpleWindow( + x11->disp, DrawOn, but->wd.x, but->wd.y, but->wd.width, but->wd.height, but->wd.bwidth, bg, bg); x11->RegisterCallback(x11, but->wd.self, DrawOn, ButtonCallBack, but); x11->SetInputMask(x11, but->wd.self, ExposureMask | ButtonPressMask | EnterLeave); } diff --git a/src/programs/view/dialogs.cpp b/src/programs/view/dialogs.cpp index bf1cbc0335..af943597ae 100644 --- a/src/programs/view/dialogs.cpp +++ b/src/programs/view/dialogs.cpp @@ -138,13 +138,14 @@ static void MBCallback(t_x11* /*x11*/, int dlg_mess, int /*item_id*/, char* /*se static t_dlg* about_mb(t_x11* x11, t_gmx* gmx) { - const char* lines[] = { " G R O M A C S", " Machine for Simulating Chemistry", + const char* lines[] = { " G R O M A C S", + " Machine for Simulating Chemistry", " Copyright (c) 1992-2013", " Berk Hess, David van der Spoel, Erik Lindahl", " and many collaborators!" }; - return MessageBox(x11, gmx->wd->self, gmx->wd->text, asize(lines), lines, - MB_OK | MB_ICONGMX | MBFLAGS, MBCallback, gmx); + return MessageBox( + x11, gmx->wd->self, gmx->wd->text, asize(lines), lines, MB_OK | MB_ICONGMX | MBFLAGS, MBCallback, gmx); } static void QuitCB(t_x11* x11, int dlg_mess, int /*item_id*/, char* set, void* data) @@ -166,24 +167,24 @@ static t_dlg* quit_mb(t_x11* x11, t_gmx* gmx) { const char* lines[] = { " Do you really want to Quit ?" }; - return MessageBox(x11, gmx->wd->self, gmx->wd->text, asize(lines), lines, - MB_YESNO | MB_ICONSTOP | MBFLAGS, QuitCB, gmx); + return MessageBox( + x11, gmx->wd->self, gmx->wd->text, asize(lines), lines, MB_YESNO | MB_ICONSTOP | MBFLAGS, QuitCB, gmx); } static t_dlg* help_mb(t_x11* x11, t_gmx* gmx) { const char* lines[] = { " Help will soon be added" }; - return MessageBox(x11, gmx->wd->self, gmx->wd->text, asize(lines), lines, - MB_OK | MB_ICONINFORMATION | MBFLAGS, MBCallback, gmx); + return MessageBox( + x11, gmx->wd->self, gmx->wd->text, asize(lines), lines, MB_OK | MB_ICONINFORMATION | MBFLAGS, MBCallback, gmx); } static t_dlg* ni_mb(t_x11* x11, t_gmx* gmx) { const char* lines[] = { " This feature has not been", " implemented yet." }; - return MessageBox(x11, gmx->wd->self, gmx->wd->text, asize(lines), lines, - MB_OK | MB_ICONEXCLAMATION | MBFLAGS, MBCallback, gmx); + return MessageBox( + x11, gmx->wd->self, gmx->wd->text, asize(lines), lines, MB_OK | MB_ICONEXCLAMATION | MBFLAGS, MBCallback, gmx); } enum @@ -392,8 +393,8 @@ void init_dlgs(t_x11* x11, t_gmx* gmx) snew(gmx->dlgs, edNR); for (int i = 0; (i < asize(di)); i++) { - gmx->dlgs[i] = ReadDlg(x11, gmx->wd->self, di[i].dlgfile, di[i].dlgfile, 0, 0, true, false, - di[i].cb, gmx); + gmx->dlgs[i] = ReadDlg( + x11, gmx->wd->self, di[i].dlgfile, di[i].dlgfile, 0, 0, true, false, di[i].cb, gmx); } gmx->dlgs[edFilter] = select_filter(x11, gmx); diff --git a/src/programs/view/fgrid.cpp b/src/programs/view/fgrid.cpp index 940e84e573..924eac3834 100644 --- a/src/programs/view/fgrid.cpp +++ b/src/programs/view/fgrid.cpp @@ -434,8 +434,12 @@ static void DumpFItem(t_fitem* fitem) { int i; - std::printf(" type: %s, set: '%s', get: '%s', def: '%s', help: '%s'\n {", type[fitem->edlg], - fitem->set, fitem->get, fitem->def, fitem->help); + std::printf(" type: %s, set: '%s', get: '%s', def: '%s', help: '%s'\n {", + type[fitem->edlg], + fitem->set, + fitem->get, + fitem->def, + fitem->help); for (i = 0; (i < fitem->nname); i++) { std::printf(" '%s'", fitem->name[i]); diff --git a/src/programs/view/filter.cpp b/src/programs/view/filter.cpp index 3064c79de7..80a7ade897 100644 --- a/src/programs/view/filter.cpp +++ b/src/programs/view/filter.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2013, The GROMACS development team. - * Copyright (c) 2013,2014,2015,2017,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2015,2017,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -159,13 +159,18 @@ t_dlg* select_filter(t_x11* x11, t_gmx* gmx) { if (!gmx->filter->bDisable[k]) { - std::fprintf(tmp, "checkbox \"%s\" \"%d\" %s %s %s\n", gmx->filter->grpnames[k], k, - dummy, dummy, dummy); + std::fprintf( + tmp, "checkbox \"%s\" \"%d\" %s %s %s\n", gmx->filter->grpnames[k], k, dummy, dummy, dummy); } else { - std::fprintf(tmp, "statictext { \" %s\" } \"%d\" %s %s %s\n", - gmx->filter->grpnames[k], k, dummy, dummy, dummy); + std::fprintf(tmp, + "statictext { \" %s\" } \"%d\" %s %s %s\n", + gmx->filter->grpnames[k], + k, + dummy, + dummy, + dummy); } } std::fprintf(tmp, "}\n\n"); diff --git a/src/programs/view/logo.cpp b/src/programs/view/logo.cpp index e8fb69d6f6..d1e47e9fc4 100644 --- a/src/programs/view/logo.cpp +++ b/src/programs/view/logo.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2013, The GROMACS development team. - * Copyright (c) 2013,2014,2015,2017,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2015,2017,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -134,8 +134,13 @@ static bool LogoCallBack(t_x11* x11, XEvent* event, Window /*w*/, void* data) XSetLineAttributes(x11->disp, x11->gc, 3, LineSolid, CapNotLast, JoinRound); for (i = 0; (i < asize(lines)); i += 2) { - XDrawLine(x11->disp, wd->self, x11->gc, c[lines[i]].x, c[lines[i]].y, - c[lines[i + 1]].x, c[lines[i + 1]].y); + XDrawLine(x11->disp, + wd->self, + x11->gc, + c[lines[i]].x, + c[lines[i]].y, + c[lines[i + 1]].x, + c[lines[i + 1]].y); } XSetLineAttributes(x11->disp, x11->gc, 1, LineSolid, CapNotLast, JoinRound); for (i = 0; (i < asize(c)); i++) @@ -147,8 +152,8 @@ static bool LogoCallBack(t_x11* x11, XEvent* event, Window /*w*/, void* data) XDrawRectangle(x11->disp, wd->self, x11->gc, 2, 2, wd->width - 5, wd->height - 5); for (i = 0; (i < NMESS); i++) { - SpecialTextInRect(x11, Mess[i].fnt, wd->self, Mess[i].text, 0, Mess[i].y, wd->width, - Mess[i].h, eXCenter, eYCenter); + SpecialTextInRect( + x11, Mess[i].fnt, wd->self, Mess[i].text, 0, Mess[i].y, wd->width, Mess[i].h, eXCenter, eYCenter); } XSetForeground(x11->disp, x11->gc, x11->fg); break; @@ -186,8 +191,8 @@ t_logo* init_logo(t_x11* x11, Window parent, bool bQuitOnClick) { GetNamedColor(x11, newcol, &bg); } - logo->wd.self = XCreateSimpleWindow(x11->disp, parent, logo->wd.x, logo->wd.y, logo->wd.width, - logo->wd.height, logo->wd.bwidth, WHITE, bg); + logo->wd.self = XCreateSimpleWindow( + x11->disp, parent, logo->wd.x, logo->wd.y, logo->wd.width, logo->wd.height, logo->wd.bwidth, WHITE, bg); for (i = 0, logo->bigfont = nullptr; (i < NBF); i++) { if ((logo->bigfont = XLoadQueryFont(x11->disp, bfname[i])) != nullptr) diff --git a/src/programs/view/manager.cpp b/src/programs/view/manager.cpp index d5fbd842f3..ad67d7837f 100644 --- a/src/programs/view/manager.cpp +++ b/src/programs/view/manager.cpp @@ -186,8 +186,8 @@ static void do_label(t_x11* x11, t_manager* man, int x, int y, bool bSet) return; } XSetForeground(x11->disp, x11->gc, col); - XDrawString(x11->disp, man->molw->wd.self, x11->gc, x + 2, y - 2, man->szLab[ai], - std::strlen(man->szLab[ai])); + XDrawString( + x11->disp, man->molw->wd.self, x11->gc, x + 2, y - 2, man->szLab[ai], std::strlen(man->szLab[ai])); XSetForeground(x11->disp, x11->gc, x11->fg); } } @@ -236,7 +236,10 @@ void set_file(t_x11* x11, t_manager* man, const char* trajectory, const char* st gmx_fatal(FARGS, "Topology %s (%d atoms) and trajectory %s (%d atoms) " "do not match", - status, man->top.atoms.nr, trajectory, man->natom); + status, + man->top.atoms.nr, + trajectory, + man->natom); } man->title.text = @@ -634,8 +637,8 @@ t_manager* init_man(t_x11* x11, man->bSort = true; man->oenv = oenv; InitWin(&(man->wd), x, y, width, height, 0, "Manager"); - man->wd.self = XCreateSimpleWindow(x11->disp, Parent, man->wd.x, man->wd.y, man->wd.width, - man->wd.height, man->wd.bwidth, fg, bg); + man->wd.self = XCreateSimpleWindow( + x11->disp, Parent, man->wd.x, man->wd.y, man->wd.width, man->wd.height, man->wd.bwidth, fg, bg); x11->RegisterCallback(x11, man->wd.self, Parent, ManCallBack, man); x11->SetInputMask(x11, man->wd.self, StructureNotifyMask | ExposureMask | ButtonPressMask); @@ -645,9 +648,15 @@ t_manager* init_man(t_x11* x11, /* Title Window */ InitWin(&(man->title), 0, 0, 1, 1, 0, nullptr); - man->title.self = - XCreateSimpleWindow(x11->disp, man->molw->wd.self, man->title.x, man->title.y, - man->title.width, man->title.height, man->title.bwidth, WHITE, BLUE); + man->title.self = XCreateSimpleWindow(x11->disp, + man->molw->wd.self, + man->title.x, + man->title.y, + man->title.width, + man->title.height, + man->title.bwidth, + WHITE, + BLUE); x11->RegisterCallback(x11, man->title.self, man->molw->wd.self, TitleCallBack, &(man->title)); x11->SetInputMask(x11, man->title.self, ExposureMask | StructureNotifyMask); diff --git a/src/programs/view/molps.cpp b/src/programs/view/molps.cpp index 3f2dcf5158..daa0645764 100644 --- a/src/programs/view/molps.cpp +++ b/src/programs/view/molps.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2013, The GROMACS development team. - * Copyright (c) 2013,2014,2015,2017,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2015,2017,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -186,8 +186,7 @@ static void draw_box(t_psdata* ps, t_3dview* view, matrix box, int x0, int y0, r ps_color(ps, 0, 0, 0.5); for (i = 0; (i < 12); i++) { - ps_line(ps, vec2[bonds[i][0]][XX], vec2[bonds[i][0]][YY], vec2[bonds[i][1]][XX], - vec2[bonds[i][1]][YY]); + ps_line(ps, vec2[bonds[i][0]][XX], vec2[bonds[i][0]][YY], vec2[bonds[i][1]][XX], vec2[bonds[i][1]][YY]); } } diff --git a/src/programs/view/nmol.cpp b/src/programs/view/nmol.cpp index 1c1123ea6c..4a272709ee 100644 --- a/src/programs/view/nmol.cpp +++ b/src/programs/view/nmol.cpp @@ -590,8 +590,18 @@ void draw_mol(t_x11* x11, t_manager* man) } /* Draw the objects */ - draw_objects(x11->disp, win->self, x11->gc, nvis, man->obj, man->ix, man->x, man->col, - man->size, mw->bShowHydrogen, mw->bond_type, man->bPlus); + draw_objects(x11->disp, + win->self, + x11->gc, + nvis, + man->obj, + man->ix, + man->x, + man->col, + man->size, + mw->bShowHydrogen, + mw->bond_type, + man->bPlus); /* Draw the labels */ XSetForeground(x11->disp, x11->gc, WHITE); @@ -599,8 +609,13 @@ void draw_mol(t_x11* x11, t_manager* man) { if (man->bLabel[i] && man->bVis[i]) { - XDrawString(x11->disp, win->self, x11->gc, vec2[i][XX] + 2, vec2[i][YY] - 2, - man->szLab[i], std::strlen(man->szLab[i])); + XDrawString(x11->disp, + win->self, + x11->gc, + vec2[i][XX] + 2, + vec2[i][YY] - 2, + man->szLab[i], + std::strlen(man->szLab[i])); } } diff --git a/src/programs/view/popup.cpp b/src/programs/view/popup.cpp index 63d2d465ff..b0f298e6a7 100644 --- a/src/programs/view/popup.cpp +++ b/src/programs/view/popup.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2013, The GROMACS development team. - * Copyright (c) 2013,2014,2015,2017,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2015,2017,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -98,9 +98,16 @@ static bool MenuCallBack(t_x11* x11, XEvent* event, Window /*w*/, void* data) /* Nothing to be done */ if (m->bGrabbed) { - m->bGrabbed = GrabOK(stderr, XGrabPointer(x11->disp, m->wd.self, True, ButtonReleaseMask, - GrabModeAsync, GrabModeAsync, m->wd.self, - None, CurrentTime)); + m->bGrabbed = GrabOK(stderr, + XGrabPointer(x11->disp, + m->wd.self, + True, + ButtonReleaseMask, + GrabModeAsync, + GrabModeAsync, + m->wd.self, + None, + CurrentTime)); } break; case ButtonRelease: hide_menu(x11, m); break; @@ -163,8 +170,8 @@ t_menu* init_menu(t_x11* x11, Window Parent, unsigned long fg, unsigned long bg, } InitWin(&(m->wd), 10, 10, fcol * mlen, frows * mht, 1, "Menu"); snew(m->item, nent); - m->wd.self = XCreateSimpleWindow(x11->disp, Parent, m->wd.x, m->wd.y, m->wd.width, m->wd.height, - m->wd.bwidth, fg, bg); + m->wd.self = XCreateSimpleWindow( + x11->disp, Parent, m->wd.x, m->wd.y, m->wd.width, m->wd.height, m->wd.bwidth, fg, bg); x11->RegisterCallback(x11, m->wd.self, Parent, MenuCallBack, m); x11->SetInputMask(x11, m->wd.self, ExposureMask | OwnerGrabButtonMask | ButtonReleaseMask); @@ -177,10 +184,11 @@ t_menu* init_menu(t_x11* x11, Window Parent, unsigned long fg, unsigned long bg, kid->Parent = Parent; w = &(kid->wd); InitWin(w, j * mlen, k * mht, mlen - 2, mht - 2, 1, nullptr); - w->self = XCreateSimpleWindow(x11->disp, m->wd.self, w->x, w->y, w->width, w->height, - w->bwidth, bg, bg); + w->self = XCreateSimpleWindow( + x11->disp, m->wd.self, w->x, w->y, w->width, w->height, w->bwidth, bg, bg); x11->RegisterCallback(x11, w->self, m->wd.self, ChildCallBack, kid); - x11->SetInputMask(x11, w->self, + x11->SetInputMask(x11, + w->self, ButtonPressMask | ButtonReleaseMask | OwnerGrabButtonMask | ExposureMask | EnterWindowMask | LeaveWindowMask); } diff --git a/src/programs/view/pulldown.cpp b/src/programs/view/pulldown.cpp index 6c4bbb703c..36df602e90 100644 --- a/src/programs/view/pulldown.cpp +++ b/src/programs/view/pulldown.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2013, The GROMACS development team. - * Copyright (c) 2013,2014,2015,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2015,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -62,8 +62,13 @@ static bool PDCallBack(t_x11* x11, XEvent* event, Window w, void* data) XDrawLine(x11->disp, w, x11->gc, 0, y - 1, pd->wd.width, y - 1); for (i = 0; (i < pd->nmenu); i++) { - XDrawString(x11->disp, pd->wd.self, x11->gc, pd->xpos[i], x11->font->ascent, - pd->title[i], std::strlen(pd->title[i])); + XDrawString(x11->disp, + pd->wd.self, + x11->gc, + pd->xpos[i], + x11->font->ascent, + pd->title[i], + std::strlen(pd->title[i])); } break; case ButtonPress: @@ -116,11 +121,11 @@ t_pulldown* init_pd(t_x11* x11, } InitWin(&(pd->wd), 0, 0, width, XTextHeight(x11->font) + 2, 0, "PullDown"); - pd->wd.self = XCreateSimpleWindow(x11->disp, Parent, pd->wd.x, pd->wd.y, pd->wd.width, - pd->wd.height, pd->wd.bwidth, fg, bg); + pd->wd.self = XCreateSimpleWindow( + x11->disp, Parent, pd->wd.x, pd->wd.y, pd->wd.width, pd->wd.height, pd->wd.bwidth, fg, bg); x11->RegisterCallback(x11, pd->wd.self, Parent, PDCallBack, pd); - x11->SetInputMask(x11, pd->wd.self, - ExposureMask | ButtonPressMask | OwnerGrabButtonMask | ButtonReleaseMask); + x11->SetInputMask( + x11, pd->wd.self, ExposureMask | ButtonPressMask | OwnerGrabButtonMask | ButtonReleaseMask); XMapWindow(x11->disp, pd->wd.self); for (i = 0; (i < nmenu); i++) diff --git a/src/programs/view/view.cpp b/src/programs/view/view.cpp index 15395ab090..c307a4e239 100644 --- a/src/programs/view/view.cpp +++ b/src/programs/view/view.cpp @@ -129,8 +129,13 @@ static bool HandleClient(t_x11* x11, int ID, t_gmx* gmx) case IDIMPORT: case IDEXPORT: ShowDlg(gmx->dlgs[edExport]); break; case IDDOEXPORT: - write_sto_conf(gmx->confout, *gmx->man->top.name, &(gmx->man->top.atoms), gmx->man->x, - nullptr, gmx->man->molw->pbcType, gmx->man->box); + write_sto_conf(gmx->confout, + *gmx->man->top.name, + &(gmx->man->top.atoms), + gmx->man->x, + nullptr, + gmx->man->molw->pbcType, + gmx->man->box); break; case IDQUIT: show_mb(gmx, emQuit); break; case IDTERM: done_gmx(x11, gmx); return true; @@ -259,17 +264,18 @@ static void init_gmx(t_x11* x11, char* program, int nfile, t_filenm fnm[], gmx_o w0 = DisplayWidth(x11->disp, x11->screen) - 132; h0 = DisplayHeight(x11->disp, x11->screen) - 140; InitWin(gmx->wd, 0, 0, w0, h0, 3, gmx::bromacs().c_str()); - gmx->wd->self = XCreateSimpleWindow(x11->disp, x11->root, gmx->wd->x, gmx->wd->y, gmx->wd->width, - gmx->wd->height, gmx->wd->bwidth, WHITE, BLACK); - pm = XCreatePixmapFromBitmapData(x11->disp, x11->root, (char*)gromacs_bits, gromacs_width, - gromacs_height, WHITE, BLACK, 1); + gmx->wd->self = XCreateSimpleWindow( + x11->disp, x11->root, gmx->wd->x, gmx->wd->y, gmx->wd->width, gmx->wd->height, gmx->wd->bwidth, WHITE, BLACK); + pm = XCreatePixmapFromBitmapData( + x11->disp, x11->root, (char*)gromacs_bits, gromacs_width, gromacs_height, WHITE, BLACK, 1); hints.flags = PMinSize; hints.min_width = 2 * EWIDTH + 40; hints.min_height = EHEIGHT + LDHEIGHT + LEGHEIGHT + 40; XSetStandardProperties(x11->disp, gmx->wd->self, gmx->wd->text, program, pm, nullptr, 0, &hints); x11->RegisterCallback(x11, gmx->wd->self, x11->root, MainCallBack, gmx); - x11->SetInputMask(x11, gmx->wd->self, + x11->SetInputMask(x11, + gmx->wd->self, ButtonPressMask | ButtonReleaseMask | OwnerGrabButtonMask | ExposureMask | StructureNotifyMask); @@ -285,8 +291,8 @@ static void init_gmx(t_x11* x11, char* program, int nfile, t_filenm fnm[], gmx_o map_man(x11, gmx->man); /* Pull Down menu */ - gmx->pd = init_pd(x11, gmx->wd->self, gmx->wd->width, x11->fg, x11->bg, MSIZE, gmx_pd_size, - gmx_pd, MenuTitle); + gmx->pd = init_pd( + x11, gmx->wd->self, gmx->wd->width, x11->fg, x11->bg, MSIZE, gmx_pd_size, gmx_pd, MenuTitle); /* Dialogs & Filters */ @@ -328,8 +334,8 @@ int gmx_view(int argc, char* argv[]) { efNDX, nullptr, nullptr, ffOPTRD } }; #define NFILE asize(fnm) - if (parse_common_args(&argc, argv, PCA_CAN_TIME, NFILE, fnm, 0, nullptr, asize(desc), desc, - asize(bugs), bugs, &oenv)) + if (parse_common_args( + &argc, argv, PCA_CAN_TIME, NFILE, fnm, 0, nullptr, asize(desc), desc, asize(bugs), bugs, &oenv)) { #if !GMX_X11 std::fprintf(stderr, "Compiled without X-Windows - can not run viewer.\n"); diff --git a/src/programs/view/x11.cpp b/src/programs/view/x11.cpp index b429024522..96707325a4 100644 --- a/src/programs/view/x11.cpp +++ b/src/programs/view/x11.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2013, The GROMACS development team. - * Copyright (c) 2013,2014,2015,2017,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2015,2017,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -419,8 +419,10 @@ t_x11* GetX11(int* argc, char* argv[]) else { /* We have real color! */ - std::fprintf(x11->console, "%s screen with depth %d.\n", - (i == NCLASS) ? "Unknown" : v_name[i], x11->depth); + std::fprintf(x11->console, + "%s screen with depth %d.\n", + (i == NCLASS) ? "Unknown" : v_name[i], + x11->depth); GetNamedColor(x11, "midnight blue", &BLUE); GetNamedColor(x11, "DarkGreen", &GREEN); GetNamedColor(x11, "SeaGreen", &CYAN); diff --git a/src/programs/view/xdlg.cpp b/src/programs/view/xdlg.cpp index b403a9e71b..92126604d2 100644 --- a/src/programs/view/xdlg.cpp +++ b/src/programs/view/xdlg.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team. - * Copyright (c) 2013,2014,2015,2017,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2015,2017,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -179,8 +179,12 @@ bool SetDlgItemSize(t_dlg* dlg, t_id id, int w, int h) dlgitem->win.height = h; } #ifdef DEBUG - std::fprintf(dlg->x11->console, "Size window from: %dx%d to %dx%d\n", old_w, old_h, - dlgitem->win.width, dlgitem->win.height); + std::fprintf(dlg->x11->console, + "Size window from: %dx%d to %dx%d\n", + old_w, + old_h, + dlgitem->win.width, + dlgitem->win.height); dlg->x11->Flush(dlg->x11); #endif if (dlgitem->win.self) @@ -359,16 +363,15 @@ void HideDlg(t_dlg* dlg) void NoHelp(t_dlg* dlg) { const char* lines[2] = { "Error", "No help for this item" }; - MessageBox(dlg->x11, dlg->wDad, "No Help", 2, lines, MB_OK | MB_ICONSTOP | MB_APPLMODAL, - nullptr, nullptr); + MessageBox(dlg->x11, dlg->wDad, "No Help", 2, lines, MB_OK | MB_ICONSTOP | MB_APPLMODAL, nullptr, nullptr); } void HelpDlg(t_dlg* dlg) { const char* lines[] = { "Place the cursor over one of the items", - "and press the F1 key to get more help.", "First press the OK button." }; - MessageBox(dlg->x11, dlg->win.self, "Help Dialogbox", 3, lines, - MB_OK | MB_ICONINFORMATION | MB_APPLMODAL, nullptr, nullptr); + "and press the F1 key to get more help.", + "First press the OK button." }; + MessageBox(dlg->x11, dlg->win.self, "Help Dialogbox", 3, lines, MB_OK | MB_ICONINFORMATION | MB_APPLMODAL, nullptr, nullptr); } void HelpNow(t_dlg* dlg, t_dlgitem* dlgitem) @@ -416,8 +419,7 @@ void HelpNow(t_dlg* dlg, t_dlgitem* dlgitem) } } } while (bCont); - MessageBox(dlg->x11, dlg->wDad, "Help", nlines, lines, - MB_OK | MB_ICONINFORMATION | MB_APPLMODAL, nullptr, nullptr); + MessageBox(dlg->x11, dlg->wDad, "Help", nlines, lines, MB_OK | MB_ICONINFORMATION | MB_APPLMODAL, nullptr, nullptr); for (i = 0; (i < nlines); i++) { sfree(lines[i]); @@ -429,9 +431,10 @@ static void EnterDlg(t_dlg* dlg) { if (dlg->flags & DLG_APPLMODAL) { - dlg->bGrab = GrabOK(dlg->x11->console, - XGrabPointer(dlg->x11->disp, dlg->win.self, True, 0, GrabModeAsync, - GrabModeAsync, dlg->win.self, None, CurrentTime)); + dlg->bGrab = GrabOK( + dlg->x11->console, + XGrabPointer( + dlg->x11->disp, dlg->win.self, True, 0, GrabModeAsync, GrabModeAsync, dlg->win.self, None, CurrentTime)); } dlg->x11->Flush(dlg->x11); } @@ -483,8 +486,10 @@ static bool DlgCB(t_x11* x11, XEvent* event, Window w, void* data) { if ((dlg->dlgitem[i]->type == edlgBN) && (dlg->dlgitem[i]->u.button.bDefault)) { - PushMouse(x11->disp, dlg->dlgitem[i]->win.self, - dlg->dlgitem[i]->win.width / 2, dlg->dlgitem[i]->win.height / 2); + PushMouse(x11->disp, + dlg->dlgitem[i]->win.self, + dlg->dlgitem[i]->win.width / 2, + dlg->dlgitem[i]->win.height / 2); break; } } @@ -585,9 +590,18 @@ static void DoCreateDlg(t_dlg* dlg) attr.save_under = True; attr.cursor = XCreateFontCursor(dlg->x11->disp, XC_hand2); Val = CWBackPixel | CWBorderPixel | CWOverrideRedirect | CWSaveUnder | CWCursor; - dlg->win.self = XCreateWindow(dlg->x11->disp, dlg->wDad, dlg->win.x, dlg->win.y, dlg->win.width, - dlg->win.height, dlg->win.bwidth, CopyFromParent, InputOutput, - CopyFromParent, Val, &attr); + dlg->win.self = XCreateWindow(dlg->x11->disp, + dlg->wDad, + dlg->win.x, + dlg->win.y, + dlg->win.width, + dlg->win.height, + dlg->win.bwidth, + CopyFromParent, + InputOutput, + CopyFromParent, + Val, + &attr); dlg->x11->RegisterCallback(dlg->x11, dlg->win.self, dlg->wDad, DlgCB, dlg); dlg->x11->SetInputMask(dlg->x11, dlg->win.self, ExposureMask | ButtonPressMask | KeyPressMask); @@ -624,9 +638,15 @@ void AddDlgItem(t_dlg* dlg, t_dlgitem* item) { gmx_fatal(FARGS, "dlgitem not allocated"); } - item->win.self = XCreateSimpleWindow(dlg->x11->disp, dlg->win.self, item->win.x, item->win.y, - item->win.width, item->win.height, item->win.bwidth, - dlg->x11->fg, dlg->x11->bg); + item->win.self = XCreateSimpleWindow(dlg->x11->disp, + dlg->win.self, + item->win.x, + item->win.y, + item->win.width, + item->win.height, + item->win.bwidth, + dlg->x11->fg, + dlg->x11->bg); CheckWindow(item->win.self); dlg->x11->RegisterCallback(dlg->x11, item->win.self, dlg->win.self, DlgCB, dlg); @@ -799,8 +819,12 @@ void SetDlgSize(t_dlg* dlg, int w, int h, bool bAutoPosition) dlg->win.height = h; #ifdef DEBUG - std::fprintf(dlg->x11->console, "SetDlgSize: Dialog is %dx%d, at %d,%d\n", dlg->win.width, - dlg->win.height, dlg->win.x, dlg->win.y); + std::fprintf(dlg->x11->console, + "SetDlgSize: Dialog is %dx%d, at %d,%d\n", + dlg->win.width, + dlg->win.height, + dlg->win.x, + dlg->win.y); dlg->x11->Flush(dlg->x11); #endif if (dlg->win.self) diff --git a/src/programs/view/xdlghi.cpp b/src/programs/view/xdlghi.cpp index a57a6c1e81..8a966861f9 100644 --- a/src/programs/view/xdlghi.cpp +++ b/src/programs/view/xdlghi.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2013, The GROMACS development team. - * Copyright (c) 2013,2014,2015,2017,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2015,2017,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -269,8 +269,8 @@ AddListFItem(t_x11* x11, t_dlgitemlist* list, t_fitem* fitem, t_id GroupID, t_id switch (fitem->edlg) { case edlgBN: - AddListItem(list, CreateButton(x11, fitem->name[0], fitem->bDef, (*ID)++, GroupID, x, - (*y), 0, 0, 0)); + AddListItem(list, + CreateButton(x11, fitem->name[0], fitem->bDef, (*ID)++, GroupID, x, (*y), 0, 0, 0)); break; case edlgRB: std::strcpy(buf, fitem->def); @@ -289,8 +289,9 @@ AddListFItem(t_x11* x11, t_dlgitemlist* list, t_fitem* fitem, t_id GroupID, t_id for (i = 0; (i < fitem->nname); i++) { - AddListItem(list, CreateRadioButton(x11, fitem->name[i], (iSel == i), (*ID)++, - GroupID, x, (*y), 0, 0, 0)); + AddListItem(list, + CreateRadioButton( + x11, fitem->name[i], (iSel == i), (*ID)++, GroupID, x, (*y), 0, 0, 0)); (*y) += list->list[list->nitem - 1]->win.height + OFFS_Y; (*w) = std::max((*w), list->list[list->nitem - 1]->win.width); SetDlgitemOpts(list->list[list->nitem - 1], bUseMon, fitem->set, fitem->get, fitem->help); @@ -301,18 +302,20 @@ AddListFItem(t_x11* x11, t_dlgitemlist* list, t_fitem* fitem, t_id GroupID, t_id bool bCheck; bCheck = gmx_strcasecmp(fitem->def, "TRUE") == 0; - AddListItem(list, CreateCheckBox(x11, fitem->name[0], bCheck, (*ID)++, GroupID, x, (*y), - 0, 0, 0)); + AddListItem(list, + CreateCheckBox(x11, fitem->name[0], bCheck, (*ID)++, GroupID, x, (*y), 0, 0, 0)); break; } case edlgST: - AddListItem(list, CreateStaticText(x11, fitem->nname, fitem->name, (*ID)++, GroupID, x, - (*y), 0, 0, 0)); + AddListItem(list, + CreateStaticText( + x11, fitem->nname, fitem->name, (*ID)++, GroupID, x, (*y), 0, 0, 0)); break; case edlgET: slen = std::strlen(fitem->name[0]) + strlen(fitem->def); - AddListItem(list, CreateEditText(x11, fitem->name[0], slen, fitem->def, (*ID)++, - GroupID, x, (*y), 0, 0, 0)); + AddListItem(list, + CreateEditText( + x11, fitem->name[0], slen, fitem->def, (*ID)++, GroupID, x, (*y), 0, 0, 0)); break; case edlgPM: case edlgGB: @@ -353,8 +356,8 @@ static void AddListFGroup(t_x11* x11, t_dlgitemlist** grid, t_fgroup* fgroup, t_ { ids[i] = GroupID + i + 1; } - item->list[0] = CreateGroupBox(x11, fgroup->name, GroupID, item->nitem - 1, ids, 2 * OFFS_X, - 2 * OFFS_Y, w + 2 * OFFS_X, y, 0); + item->list[0] = CreateGroupBox( + x11, fgroup->name, GroupID, item->nitem - 1, ids, 2 * OFFS_X, 2 * OFFS_Y, w + 2 * OFFS_X, y, 0); sfree(ids); item->w = fgroup->w; item->h = fgroup->h; diff --git a/src/programs/view/xdlgitem.cpp b/src/programs/view/xdlgitem.cpp index 3bd79a29c8..dd5c415a55 100644 --- a/src/programs/view/xdlgitem.cpp +++ b/src/programs/view/xdlgitem.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2013, The GROMACS development team. - * Copyright (c) 2013,2014,2015,2017,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2015,2017,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -226,8 +226,8 @@ static int WndProcGB(t_x11* x11, t_dlgitem* dlgitem, XEvent* event) { case Expose: XSetForeground(x11->disp, x11->gc, x11->fg); - XDrawRoundRect(x11->disp, win->self, x11->gc, 0, y / 2, win->width - 1, - win->height - y / 2 - 1); + XDrawRoundRect( + x11->disp, win->self, x11->gc, 0, y / 2, win->width - 1, win->height - y / 2 - 1); XClearArea(x11->disp, win->self, OFFS_X, 0, x + OFFS_X, y, False); TextInRect(x11, win->self, win->text, 2 * OFFS_X, 0, x, y, eXCenter, eYCenter); break; @@ -296,8 +296,7 @@ static int WndProcST(t_x11* x11, t_dlgitem* dlgitem, XEvent* event) dy = XTextHeight(x11->font) + OFFS_Y; for (i = 0; (i < st->nlines); i++) { - TextInRect(x11, win->self, st->lines[i], 0, OFFS_Y + i * dy, win->width, dy, eXLeft, - eYCenter); + TextInRect(x11, win->self, st->lines[i], 0, OFFS_Y + i * dy, win->width, dy, eXLeft, eYCenter); } break; default: return DefWndProc(x11, dlgitem, event); diff --git a/src/programs/view/xmb.cpp b/src/programs/view/xmb.cpp index 1d564cf9b7..7e6eeab86a 100644 --- a/src/programs/view/xmb.cpp +++ b/src/programs/view/xmb.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2013, The GROMACS development team. - * Copyright (c) 2013,2014,2015,2017,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2015,2017,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -141,9 +141,16 @@ t_dlg* MessageBox(t_x11* x11, if (nicon > 0) { AddDlgItem(dlg, - CreatePixmap(XCreatePixmapFromBitmapData(x11->disp, dlg->win.self, icon_bits, icon_width, - icon_height, icon_fg, icon_bg, x11->depth), - ID_ICON, ID_BOX, 2 * OFFS_X, 2 * OFFS_Y, icon_width, icon_height, 0)); + CreatePixmap( + XCreatePixmapFromBitmapData( + x11->disp, dlg->win.self, icon_bits, icon_width, icon_height, icon_fg, icon_bg, x11->depth), + ID_ICON, + ID_BOX, + 2 * OFFS_X, + 2 * OFFS_Y, + icon_width, + icon_height, + 0)); x += QueryDlgItemW(dlg, ID_ICON) + 2 * OFFS_X; } diff --git a/src/programs/view/xutil.cpp b/src/programs/view/xutil.cpp index 17d2081c04..b10e3ad4e4 100644 --- a/src/programs/view/xutil.cpp +++ b/src/programs/view/xutil.cpp @@ -3,7 +3,7 @@ * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2013, The GROMACS development team. - * Copyright (c) 2013,2014,2015,2017,2019, by the GROMACS development team, led by + * Copyright (c) 2013,2014,2015,2017,2019,2020, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. @@ -225,8 +225,8 @@ void RoundRectWin(Display* disp, GC gc, t_windata* win, int offsx, int offsy, un { XSetLineAttributes(disp, gc, 1, LineOnOffDash, CapButt, JoinRound); XSetForeground(disp, gc, color); - XDrawRoundRect(disp, win->self, gc, offsx, offsy, win->width - 2 * offsx - 1, - win->height - 2 * offsy - 1); + XDrawRoundRect( + disp, win->self, gc, offsx, offsy, win->width - 2 * offsx - 1, win->height - 2 * offsy - 1); XSetLineAttributes(disp, gc, 1, LineSolid, CapButt, JoinRound); } diff --git a/src/testutils/cmdlinetest.cpp b/src/testutils/cmdlinetest.cpp index 9746d3ba51..ab2b4c0b2e 100644 --- a/src/testutils/cmdlinetest.cpp +++ b/src/testutils/cmdlinetest.cpp @@ -114,8 +114,8 @@ namespace std::vector convertFromStringArrayRef(const ArrayRef& cmdline) { std::vector v(cmdline.size()); - std::transform(cmdline.begin(), cmdline.end(), v.begin(), - [](const std::string& s) { return s.c_str(); }); + std::transform( + cmdline.begin(), cmdline.end(), v.begin(), [](const std::string& s) { return s.c_str(); }); return v; } diff --git a/src/testutils/include/testutils/testasserts.h b/src/testutils/include/testutils/testasserts.h index a737f03e4c..9b1c3d4cea 100644 --- a/src/testutils/include/testutils/testasserts.h +++ b/src/testutils/include/testutils/testasserts.h @@ -509,8 +509,12 @@ static inline FloatingPointTolerance relativeToleranceAsPrecisionDependentUlp(do uint64_t doubleUlpDiff) { return FloatingPointTolerance(float(magnitude) * singleUlpDiff * GMX_FLOAT_EPS, - magnitude * doubleUlpDiff * GMX_DOUBLE_EPS, 0.0, 0.0, - singleUlpDiff, doubleUlpDiff, false); + magnitude * doubleUlpDiff * GMX_DOUBLE_EPS, + 0.0, + 0.0, + singleUlpDiff, + doubleUlpDiff, + false); } /*! \brief @@ -573,7 +577,8 @@ static inline FloatingPointTolerance defaultRealTolerance() static inline FloatingPointTolerance defaultFloatTolerance() { return relativeToleranceAsPrecisionDependentUlp( - 1.0, detail::g_defaultUlpTolerance, + 1.0, + detail::g_defaultUlpTolerance, static_cast(detail::g_defaultUlpTolerance * (GMX_FLOAT_EPS / GMX_DOUBLE_EPS))); } diff --git a/src/testutils/refdata.cpp b/src/testutils/refdata.cpp index 6f44673a64..cfc320c04b 100644 --- a/src/testutils/refdata.cpp +++ b/src/testutils/refdata.cpp @@ -704,9 +704,12 @@ TestReferenceChecker TestReferenceData::rootChecker() return TestReferenceChecker(new TestReferenceChecker::Impl(true)); } impl_->compareRootEntry_->setChecked(); - return TestReferenceChecker(new TestReferenceChecker::Impl( - "", impl_->compareRootEntry_.get(), impl_->outputRootEntry_.get(), - impl_->updateMismatchingEntries_, impl_->bSelfTestMode_, defaultRealTolerance())); + return TestReferenceChecker(new TestReferenceChecker::Impl("", + impl_->compareRootEntry_.get(), + impl_->outputRootEntry_.get(), + impl_->updateMismatchingEntries_, + impl_->bSelfTestMode_, + defaultRealTolerance())); } @@ -823,8 +826,11 @@ TestReferenceChecker TestReferenceChecker::checkCompound(const char* type, const { impl_->outputRootEntry_->addChild(entry->cloneToOutputEntry()); } - return TestReferenceChecker(new Impl(fullId, entry, entry->correspondingOutputEntry(), - impl_->updateMismatchingEntries_, impl_->bSelfTestMode_, + return TestReferenceChecker(new Impl(fullId, + entry, + entry->correspondingOutputEntry(), + impl_->updateMismatchingEntries_, + impl_->bSelfTestMode_, impl_->defaultTolerance_)); } @@ -861,8 +867,8 @@ static void throwIfNonEmptyAndOnlyWhitespace(const std::string& s, const char* i void TestReferenceChecker::checkBoolean(bool value, const char* id) { - EXPECT_PLAIN(impl_->processItem(Impl::cBooleanNodeName, id, - ExactStringChecker(value ? "true" : "false"))); + EXPECT_PLAIN(impl_->processItem( + Impl::cBooleanNodeName, id, ExactStringChecker(value ? "true" : "false"))); } @@ -888,38 +894,38 @@ void TestReferenceChecker::checkTextBlock(const std::string& value, const char* void TestReferenceChecker::checkUChar(unsigned char value, const char* id) { - EXPECT_PLAIN(impl_->processItem(Impl::cUCharNodeName, id, - ExactStringChecker(formatString("%d", value)))); + EXPECT_PLAIN(impl_->processItem( + Impl::cUCharNodeName, id, ExactStringChecker(formatString("%d", value)))); } void TestReferenceChecker::checkInteger(int value, const char* id) { - EXPECT_PLAIN(impl_->processItem(Impl::cIntegerNodeName, id, - ExactStringChecker(formatString("%d", value)))); + EXPECT_PLAIN(impl_->processItem( + Impl::cIntegerNodeName, id, ExactStringChecker(formatString("%d", value)))); } void TestReferenceChecker::checkInt32(int32_t value, const char* id) { - EXPECT_PLAIN(impl_->processItem(Impl::cInt32NodeName, id, - ExactStringChecker(formatString("%" PRId32, value)))); + EXPECT_PLAIN(impl_->processItem( + Impl::cInt32NodeName, id, ExactStringChecker(formatString("%" PRId32, value)))); } void TestReferenceChecker::checkUInt32(uint32_t value, const char* id) { - EXPECT_PLAIN(impl_->processItem(Impl::cUInt32NodeName, id, - ExactStringChecker(formatString("%" PRIu32, value)))); + EXPECT_PLAIN(impl_->processItem( + Impl::cUInt32NodeName, id, ExactStringChecker(formatString("%" PRIu32, value)))); } void TestReferenceChecker::checkInt64(int64_t value, const char* id) { - EXPECT_PLAIN(impl_->processItem(Impl::cInt64NodeName, id, - ExactStringChecker(formatString("%" PRId64, value)))); + EXPECT_PLAIN(impl_->processItem( + Impl::cInt64NodeName, id, ExactStringChecker(formatString("%" PRId64, value)))); } void TestReferenceChecker::checkUInt64(uint64_t value, const char* id) { - EXPECT_PLAIN(impl_->processItem(Impl::cUInt64NodeName, id, - ExactStringChecker(formatString("%" PRIu64, value)))); + EXPECT_PLAIN(impl_->processItem( + Impl::cUInt64NodeName, id, ExactStringChecker(formatString("%" PRIu64, value)))); } void TestReferenceChecker::checkDouble(double value, const char* id) diff --git a/src/testutils/simulationdatabase.cpp b/src/testutils/simulationdatabase.cpp index 52d866f258..3c4e02b700 100644 --- a/src/testutils/simulationdatabase.cpp +++ b/src/testutils/simulationdatabase.cpp @@ -80,20 +80,44 @@ const MdpFileValues mdpFileValueDatabase_g{ { { { "ref-t", "80" } }, { // TODO This test case is not currently used, so we // have not tested which rank counts work. - 1, 2, 3, 4, 5, 6, 7, 8, 9 } } }, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9 } } }, // Simple system with 2 nearby water molecules { "spc2", { {}, { // TODO This test case is not currently used, so we // have not tested which rank counts work. - 1, 2, 3, 4, 5, 6, 7, 8, 9 } } }, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9 } } }, // Simple system with 216 water molecules, condensed phase { "spc216", { {}, { // TODO This test case is not currently used, so we // have not tested which rank counts work. - 1, 2, 3, 4, 5, 6, 7, 8, 9 // TODO tpi test + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9 // TODO tpi test } } }, // Capped alanine peptide in vacuo with virtual sites { "alanine_vsite_vacuo", @@ -104,7 +128,15 @@ const MdpFileValues mdpFileValueDatabase_g{ { { { "constraints", "all-bonds" }, { "compressibility", "5e-10" }, { "tau-p", "1000" } }, { // TODO This test case is not currently used, so we // have not tested which rank counts work. - 1, 2, 3, 4, 5, 6, 7, 8, 9 } } }, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9 } } }, // Zwitterionic glycine in vacuo { "glycine_vacuo", { { { "constraints", "h-bonds" } }, { 1, 2, 3, 4, 5, 6, 7, 8, 9 } } }, // Zwitterionic glycine in vacuo, without constraints @@ -203,8 +235,8 @@ bool isNumberOfPpRanksSupported(const std::string& simulationName, int possibleN std::string reportNumbersOfPpRanksSupported(const std::string& simulationName) { const auto& possibleNumbers = mdpFileValueDatabase_g.at(simulationName).validPpRankCounts; - return formatAndJoin(std::begin(possibleNumbers), std::end(possibleNumbers), ",", - StringFormatter("%d")); + return formatAndJoin( + std::begin(possibleNumbers), std::end(possibleNumbers), ",", StringFormatter("%d")); } MdpFieldValues prepareMdpFieldValues(const std::string& simulationName, @@ -288,18 +320,30 @@ std::string prepareMdpFileContents(const MdpFieldValues& mdpFieldValues) comm-mode = %s nstcomm = %s %s)", - mdpFieldValues.at("coulombtype").c_str(), mdpFieldValues.at("rcoulomb").c_str(), - mdpFieldValues.at("vdwtype").c_str(), mdpFieldValues.at("rvdw").c_str(), - mdpFieldValues.at("nsteps").c_str(), mdpFieldValues.at("nstenergy").c_str(), - mdpFieldValues.at("nstxout").c_str(), mdpFieldValues.at("nstvout").c_str(), - mdpFieldValues.at("nstfout").c_str(), mdpFieldValues.at("nstxout-compressed").c_str(), - mdpFieldValues.at("nstdhdl").c_str(), mdpFieldValues.at("integrator").c_str(), - mdpFieldValues.at("tcoupl").c_str(), mdpFieldValues.at("nsttcouple").c_str(), - mdpFieldValues.at("ref-t").c_str(), mdpFieldValues.at("pcoupl").c_str(), - mdpFieldValues.at("nstpcouple").c_str(), mdpFieldValues.at("tau-p").c_str(), - mdpFieldValues.at("compressibility").c_str(), mdpFieldValues.at("constraints").c_str(), - mdpFieldValues.at("nstcalcenergy").c_str(), mdpFieldValues.at("comm-mode").c_str(), - mdpFieldValues.at("nstcomm").c_str(), mdpFieldValues.at("other").c_str()); + mdpFieldValues.at("coulombtype").c_str(), + mdpFieldValues.at("rcoulomb").c_str(), + mdpFieldValues.at("vdwtype").c_str(), + mdpFieldValues.at("rvdw").c_str(), + mdpFieldValues.at("nsteps").c_str(), + mdpFieldValues.at("nstenergy").c_str(), + mdpFieldValues.at("nstxout").c_str(), + mdpFieldValues.at("nstvout").c_str(), + mdpFieldValues.at("nstfout").c_str(), + mdpFieldValues.at("nstxout-compressed").c_str(), + mdpFieldValues.at("nstdhdl").c_str(), + mdpFieldValues.at("integrator").c_str(), + mdpFieldValues.at("tcoupl").c_str(), + mdpFieldValues.at("nsttcouple").c_str(), + mdpFieldValues.at("ref-t").c_str(), + mdpFieldValues.at("pcoupl").c_str(), + mdpFieldValues.at("nstpcouple").c_str(), + mdpFieldValues.at("tau-p").c_str(), + mdpFieldValues.at("compressibility").c_str(), + mdpFieldValues.at("constraints").c_str(), + mdpFieldValues.at("nstcalcenergy").c_str(), + mdpFieldValues.at("comm-mode").c_str(), + mdpFieldValues.at("nstcomm").c_str(), + mdpFieldValues.at("other").c_str()); } } // namespace test diff --git a/src/testutils/testasserts.cpp b/src/testutils/testasserts.cpp index 83fbf5568c..45c483a32b 100644 --- a/src/testutils/testasserts.cpp +++ b/src/testutils/testasserts.cpp @@ -228,8 +228,11 @@ std::string FloatingPointDifference::toString() const relDiffStr = formatString("Inf"); } - return formatString("%g (%" PRIu64 " %s-prec. ULPs, rel. %s)%s", absoluteDifference_, - ulpDifference_, isDouble() ? "double" : "single", relDiffStr.c_str(), + return formatString("%g (%" PRIu64 " %s-prec. ULPs, rel. %s)%s", + absoluteDifference_, + ulpDifference_, + isDouble() ? "double" : "single", + relDiffStr.c_str(), bSignDifference_ ? ", signs differ" : ""); } diff --git a/src/testutils/testinit.cpp b/src/testutils/testinit.cpp index 330e2563b6..87687202c7 100644 --- a/src/testutils/testinit.cpp +++ b/src/testutils/testinit.cpp @@ -172,7 +172,8 @@ void initTestUtils(const char* dataPath, "NOTE: You are running %s on %d MPI ranks, " "but it is does not contain MPI-enabled tests. " "The test will now exit.\n", - context.programName(), gmx_node_num()); + context.programName(), + gmx_node_num()); } finalizeForCommandLine(); std::exit(1); diff --git a/src/testutils/tests/xvgtest_tests.cpp b/src/testutils/tests/xvgtest_tests.cpp index c8dc14164f..7188644487 100644 --- a/src/testutils/tests/xvgtest_tests.cpp +++ b/src/testutils/tests/xvgtest_tests.cpp @@ -97,7 +97,8 @@ TEST(XvgTests, CheckMissing) checkXvgFile(&sis, &checker, XvgMatchSettings()); } { - const char* const input[] = { "0 2905.86 -410.199", "0.2 6656.67 -430.437", + const char* const input[] = { "0 2905.86 -410.199", + "0.2 6656.67 -430.437", "0.4 5262.44 -409.399" }; // Now check with missing data TestReferenceData data(ReferenceDataMode::Compare); diff --git a/src/testutils/unittest_main.cpp b/src/testutils/unittest_main.cpp index e5bb19f76a..f63b8bd589 100644 --- a/src/testutils/unittest_main.cpp +++ b/src/testutils/unittest_main.cpp @@ -72,8 +72,8 @@ int main(int argc, char* argv[]) { // Calls ::testing::InitGoogleMock() - ::gmx::test::initTestUtils(TEST_DATA_PATH, TEST_TEMP_PATH, TEST_USES_MPI, - TEST_USES_HARDWARE_DETECTION, &argc, &argv); + ::gmx::test::initTestUtils( + TEST_DATA_PATH, TEST_TEMP_PATH, TEST_USES_MPI, TEST_USES_HARDWARE_DETECTION, &argc, &argv); int errcode = RUN_ALL_TESTS(); ::gmx::test::finalizeTestUtils(); return errcode;