2543cd543c1692848da2a9fc7b982b6820e6620c
[alexxy/gromacs.git] / src / gromacs / applied_forces / densityfittingoptions.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2019, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  * \brief
37  * Implements force provider for density fitting
38  *
39  * \author Christian Blau <blau@kth.se>
40  * \ingroup module_applied_forces
41  */
42 #include "gmxpre.h"
43
44 #include "densityfittingoptions.h"
45
46 #include "gromacs/applied_forces/densityfitting.h"
47 #include "gromacs/math/densityfit.h"
48 #include "gromacs/options/basicoptions.h"
49 #include "gromacs/options/optionsection.h"
50 #include "gromacs/selection/indexutil.h"
51 #include "gromacs/utility/exceptions.h"
52 #include "gromacs/utility/keyvaluetreebuilder.h"
53 #include "gromacs/utility/keyvaluetreetransform.h"
54 #include "gromacs/utility/strconvert.h"
55
56 #include "densityfittingamplitudelookup.h"
57
58 namespace gmx
59 {
60
61 namespace
62 {
63
64 /*! \brief Helper to declare mdp transform rules.
65  *
66  * Enforces uniform mdp options that are always prepended with the correct
67  * string for the densityfitting mdp options.
68  *
69  * \tparam ToType type to be transformed to
70  * \tparam TransformWithFunctionType type of transformation function to be used
71  *
72  * \param[in] rules KVT transformation rules
73  * \param[in] transformationFunction the function to transform the flat kvt tree
74  * \param[in] optionTag string tag that describes the mdp option, appended to the
75  *                      default string for the density guided simulation
76  */
77 template <class ToType, class TransformWithFunctionType>
78 void densityfittingMdpTransformFromString(IKeyValueTreeTransformRules * rules,
79                                           TransformWithFunctionType     transformationFunction,
80                                           const std::string            &optionTag)
81 {
82     rules->addRule()
83         .from<std::string>("/" + DensityFittingModuleInfo::name_ + "-" + optionTag)
84         .to<ToType>("/" + DensityFittingModuleInfo::name_ +"/" + optionTag)
85         .transformWith(transformationFunction);
86 }
87 /*! \brief Helper to declare mdp output.
88  *
89  * Enforces uniform mdp options output strings that are always prepended with the
90  * correct string for the densityfitting mdp options and are consistent with the
91  * options name and transformation type.
92  *
93  * \tparam OptionType the type of the mdp option
94  * \param[in] builder the KVT builder to generate the output
95  * \param[in] option the mdp option
96  * \param[in] optionTag string tag that describes the mdp option, appended to the
97  *                      default string for the density guided simulation
98  */
99 template <class OptionType>
100 void addDensityFittingMdpOutputValue(KeyValueTreeObjectBuilder *builder,
101                                      const OptionType          &option,
102                                      const std::string         &optionTag)
103 {
104     builder->addValue<OptionType>(DensityFittingModuleInfo::name_ + "-" + optionTag,
105                                   option);
106 }
107
108 /*! \brief Helper to declare mdp output comments.
109  *
110  * Enforces uniform mdp options comment output strings that are always prepended
111  * with the correct string for the densityfitting mdp options and are consistent
112  * with the options name and transformation type.
113  *
114  * \param[in] builder the KVT builder to generate the output
115  * \param[in] comment on the mdp option
116  * \param[in] optionTag string tag that describes the mdp option
117  */
118 void addDensityFittingMdpOutputValueComment(KeyValueTreeObjectBuilder *builder,
119                                             const std::string         &comment,
120                                             const std::string         &optionTag)
121 {
122     builder->addValue<std::string>("comment-" + DensityFittingModuleInfo::name_ + "-" + optionTag, comment);
123 }
124
125 }   // namespace
126
127 void DensityFittingOptions::initMdpTransform(IKeyValueTreeTransformRules * rules)
128 {
129     const auto &stringIdentityTransform = [](std::string s){
130             return s;
131         };
132     densityfittingMdpTransformFromString<bool>(rules, &fromStdString<bool>, c_activeTag_);
133     densityfittingMdpTransformFromString<std::string>(rules, stringIdentityTransform, c_groupTag_);
134     densityfittingMdpTransformFromString<std::string>(rules, stringIdentityTransform, c_similarityMeasureTag_);
135     densityfittingMdpTransformFromString<std::string>(rules, stringIdentityTransform, c_amplitudeMethodTag_);
136     densityfittingMdpTransformFromString<real>(rules, &fromStdString<real>, c_forceConstantTag_);
137     densityfittingMdpTransformFromString<real>(rules, &fromStdString<real>, c_gaussianTransformSpreadingWidthTag_);
138     densityfittingMdpTransformFromString<real>(rules, &fromStdString<real>, c_gaussianTransformSpreadingRangeInMultiplesOfWidthTag_);
139     densityfittingMdpTransformFromString<std::string>(rules, stringIdentityTransform, c_referenceDensityFileNameTag_);
140     densityfittingMdpTransformFromString<std::int64_t>(rules, &fromStdString<std::int64_t>, c_everyNStepsTag_);
141     densityfittingMdpTransformFromString<bool>(rules, &fromStdString<bool>, c_normalizeDensitiesTag_);
142 }
143
144 void DensityFittingOptions::buildMdpOutput(KeyValueTreeObjectBuilder *builder) const
145 {
146
147     addDensityFittingMdpOutputValueComment(builder, "", "empty-line");
148     addDensityFittingMdpOutputValueComment(builder, "; Density guided simulation", "module");
149
150     addDensityFittingMdpOutputValue(builder, parameters_.active_, c_activeTag_);
151     if (parameters_.active_)
152     {
153         addDensityFittingMdpOutputValue(builder, groupString_, c_groupTag_);
154
155         addDensityFittingMdpOutputValueComment(builder, "; Similarity measure between densities: inner-product, relative-entropy, or cross-correlation", c_similarityMeasureTag_);
156         addDensityFittingMdpOutputValue<std::string>(builder,
157                                                      c_densitySimilarityMeasureMethodNames[parameters_.similarityMeasureMethod_],
158                                                      c_similarityMeasureTag_);
159
160         addDensityFittingMdpOutputValueComment(builder, "; Atom amplitude for spreading onto grid: unity, mass, or charge", c_amplitudeMethodTag_);
161         addDensityFittingMdpOutputValue<std::string>(builder,
162                                                      c_densityFittingAmplitudeMethodNames[parameters_.amplitudeLookupMethod_],
163                                                      c_amplitudeMethodTag_);
164
165         addDensityFittingMdpOutputValue(builder, parameters_.forceConstant_, c_forceConstantTag_);
166         addDensityFittingMdpOutputValue(builder, parameters_.gaussianTransformSpreadingWidth_, c_gaussianTransformSpreadingWidthTag_);
167         addDensityFittingMdpOutputValue(builder, parameters_.gaussianTransformSpreadingRangeInMultiplesOfWidth_, c_gaussianTransformSpreadingRangeInMultiplesOfWidthTag_);
168         addDensityFittingMdpOutputValueComment(builder, "; Reference density file location as absolute path or relative to the gmx mdrun calling location", c_referenceDensityFileNameTag_);
169         addDensityFittingMdpOutputValue(builder, referenceDensityFileName_, c_referenceDensityFileNameTag_);
170         addDensityFittingMdpOutputValue(builder, parameters_.calculationIntervalInSteps_, c_everyNStepsTag_);
171         addDensityFittingMdpOutputValueComment(builder, "; Normalize the sum of density voxel values to one", c_normalizeDensitiesTag_);
172         addDensityFittingMdpOutputValue(builder, parameters_.normalizeDensities_, c_normalizeDensitiesTag_);
173     }
174 }
175
176 void DensityFittingOptions::initMdpOptions(IOptionsContainerWithSections *options)
177 {
178     auto section = options->addSection(OptionSection(DensityFittingModuleInfo::name_.c_str()));
179
180     section.addOption(BooleanOption(c_activeTag_.c_str()).store(&parameters_.active_));
181     section.addOption(StringOption(c_groupTag_.c_str()).store(&groupString_));
182
183     section.addOption(EnumOption<DensitySimilarityMeasureMethod>(c_similarityMeasureTag_.c_str())
184                           .enumValue(c_densitySimilarityMeasureMethodNames.m_elements)
185                           .store(&parameters_.similarityMeasureMethod_));
186
187     section.addOption(EnumOption<DensityFittingAmplitudeMethod>(c_amplitudeMethodTag_.c_str())
188                           .enumValue(c_densityFittingAmplitudeMethodNames.m_elements)
189                           .store(&parameters_.amplitudeLookupMethod_));
190
191     section.addOption(RealOption(c_forceConstantTag_.c_str()).store(&parameters_.forceConstant_));
192     section.addOption(RealOption(c_gaussianTransformSpreadingWidthTag_.c_str()).store(&parameters_.gaussianTransformSpreadingWidth_));
193     section.addOption(RealOption(c_gaussianTransformSpreadingRangeInMultiplesOfWidthTag_.c_str()).store(&parameters_.gaussianTransformSpreadingRangeInMultiplesOfWidth_));
194     section.addOption(StringOption(c_referenceDensityFileNameTag_.c_str()).store(&referenceDensityFileName_));
195     section.addOption(Int64Option(c_everyNStepsTag_.c_str()).store(&parameters_.calculationIntervalInSteps_));
196     section.addOption(BooleanOption(c_normalizeDensitiesTag_.c_str()).store(&parameters_.normalizeDensities_));
197 }
198
199 bool DensityFittingOptions::active() const
200 {
201     return parameters_.active_;
202 }
203
204 const DensityFittingParameters &DensityFittingOptions::buildParameters()
205 {
206     // the options modules does not know unsigned integers so any input of this
207     // kind is rectified here
208     if (parameters_.calculationIntervalInSteps_ < 1)
209     {
210         parameters_.calculationIntervalInSteps_ = 1;
211     }
212     return parameters_;
213 }
214
215 void DensityFittingOptions::setFitGroupIndices(const IndexGroupsAndNames &indexGroupsAndNames)
216 {
217     if (!parameters_.active_)
218     {
219         return;
220     }
221     parameters_.indices_ = indexGroupsAndNames.indices(groupString_);
222 }
223
224 void DensityFittingOptions::writeInternalParametersToKvt(KeyValueTreeObjectBuilder treeBuilder)
225 {
226     auto groupIndexAdder = treeBuilder.addUniformArray<std::int64_t>(DensityFittingModuleInfo::name_ + "-" + c_groupTag_);
227     for (const auto &indexValue : parameters_.indices_)
228     {
229         groupIndexAdder.addValue(indexValue);
230     }
231 }
232
233 void DensityFittingOptions::readInternalParametersFromKvt(const KeyValueTreeObject &tree)
234 {
235     if (!parameters_.active_)
236     {
237         return;
238     }
239
240     if (!tree.keyExists(DensityFittingModuleInfo::name_ + "-" + c_groupTag_))
241     {
242         GMX_THROW(InconsistentInputError(
243                           "Cannot find atom index vector required for density guided simulation."));
244     }
245     auto kvtIndexArray = tree[DensityFittingModuleInfo::name_ + "-" + c_groupTag_].asArray().values();
246     parameters_.indices_.resize(kvtIndexArray.size());
247     std::transform(std::begin(kvtIndexArray), std::end(kvtIndexArray), std::begin(parameters_.indices_),
248                    [](const KeyValueTreeValue &val) { return val.cast<std::int64_t>(); });
249 }
250
251 const std::string &DensityFittingOptions::referenceDensityFileName() const
252 {
253     return referenceDensityFileName_;
254 }
255 } // namespace gmx