| [48d20d] | 1 | /* | 
|---|
|  | 2 | * Project: MoleCuilder | 
|---|
|  | 3 | * Description: creates and alters molecular systems | 
|---|
|  | 4 | * Copyright (C)  2013 University of Bonn. All rights reserved. | 
|---|
| [5aaa43] | 5 | * Copyright (C)  2013 Frederik Heber. All rights reserved. | 
|---|
| [48d20d] | 6 | * | 
|---|
|  | 7 | * | 
|---|
|  | 8 | *   This file is part of MoleCuilder. | 
|---|
|  | 9 | * | 
|---|
|  | 10 | *    MoleCuilder is free software: you can redistribute it and/or modify | 
|---|
|  | 11 | *    it under the terms of the GNU General Public License as published by | 
|---|
|  | 12 | *    the Free Software Foundation, either version 2 of the License, or | 
|---|
|  | 13 | *    (at your option) any later version. | 
|---|
|  | 14 | * | 
|---|
|  | 15 | *    MoleCuilder is distributed in the hope that it will be useful, | 
|---|
|  | 16 | *    but WITHOUT ANY WARRANTY; without even the implied warranty of | 
|---|
|  | 17 | *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the | 
|---|
|  | 18 | *    GNU General Public License for more details. | 
|---|
|  | 19 | * | 
|---|
|  | 20 | *    You should have received a copy of the GNU General Public License | 
|---|
|  | 21 | *    along with MoleCuilder.  If not, see <http://www.gnu.org/licenses/>. | 
|---|
|  | 22 | */ | 
|---|
|  | 23 |  | 
|---|
|  | 24 | /* | 
|---|
|  | 25 | * FitPotentialAction.cpp | 
|---|
|  | 26 | * | 
|---|
|  | 27 | *  Created on: Apr 09, 2013 | 
|---|
|  | 28 | *      Author: heber | 
|---|
|  | 29 | */ | 
|---|
|  | 30 |  | 
|---|
|  | 31 | // include config.h | 
|---|
|  | 32 | #ifdef HAVE_CONFIG_H | 
|---|
|  | 33 | #include <config.h> | 
|---|
|  | 34 | #endif | 
|---|
|  | 35 |  | 
|---|
|  | 36 | // needs to come before MemDebug due to placement new | 
|---|
|  | 37 | #include <boost/archive/text_iarchive.hpp> | 
|---|
|  | 38 |  | 
|---|
|  | 39 | #include "CodePatterns/MemDebug.hpp" | 
|---|
|  | 40 |  | 
|---|
|  | 41 | #include <algorithm> | 
|---|
|  | 42 | #include <boost/bind.hpp> | 
|---|
|  | 43 | #include <boost/filesystem.hpp> | 
|---|
|  | 44 | #include <boost/foreach.hpp> | 
|---|
|  | 45 | #include <map> | 
|---|
|  | 46 | #include <string> | 
|---|
|  | 47 | #include <sstream> | 
|---|
|  | 48 |  | 
|---|
| [f5724f] | 49 | #include "Actions/PotentialAction/FitPotentialAction.hpp" | 
|---|
| [48d20d] | 50 |  | 
|---|
|  | 51 | #include "CodePatterns/Log.hpp" | 
|---|
|  | 52 |  | 
|---|
|  | 53 | #include "Element/element.hpp" | 
|---|
|  | 54 | #include "Fragmentation/Homology/HomologyContainer.hpp" | 
|---|
|  | 55 | #include "Fragmentation/Homology/HomologyGraph.hpp" | 
|---|
|  | 56 | #include "Fragmentation/Summation/SetValues/Fragment.hpp" | 
|---|
|  | 57 | #include "FunctionApproximation/Extractors.hpp" | 
|---|
|  | 58 | #include "FunctionApproximation/FunctionApproximation.hpp" | 
|---|
|  | 59 | #include "FunctionApproximation/FunctionModel.hpp" | 
|---|
|  | 60 | #include "FunctionApproximation/TrainingData.hpp" | 
|---|
|  | 61 | #include "FunctionApproximation/writeDistanceEnergyTable.hpp" | 
|---|
| [baccf6] | 62 | #include "Potentials/CompoundPotential.hpp" | 
|---|
| [49dcf7] | 63 | #include "Potentials/Exceptions.hpp" | 
|---|
| [baccf6] | 64 | #include "Potentials/PotentialDeserializer.hpp" | 
|---|
| [48d20d] | 65 | #include "Potentials/PotentialFactory.hpp" | 
|---|
| [baccf6] | 66 | #include "Potentials/PotentialRegistry.hpp" | 
|---|
|  | 67 | #include "Potentials/PotentialSerializer.hpp" | 
|---|
| [48d20d] | 68 | #include "Potentials/SerializablePotential.hpp" | 
|---|
|  | 69 |  | 
|---|
|  | 70 | using namespace MoleCuilder; | 
|---|
|  | 71 |  | 
|---|
|  | 72 | // and construct the stuff | 
|---|
|  | 73 | #include "FitPotentialAction.def" | 
|---|
|  | 74 | #include "Action_impl_pre.hpp" | 
|---|
|  | 75 | /** =========== define the function ====================== */ | 
|---|
|  | 76 |  | 
|---|
|  | 77 | HomologyGraph getFirstGraphwithSpecifiedElements( | 
|---|
|  | 78 | const HomologyContainer &homologies, | 
|---|
|  | 79 | const SerializablePotential::ParticleTypes_t &types) | 
|---|
|  | 80 | { | 
|---|
|  | 81 | ASSERT( !types.empty(), | 
|---|
|  | 82 | "getFirstGraphwithSpecifiedElements() - charges is empty?"); | 
|---|
|  | 83 | // create charges | 
|---|
|  | 84 | Fragment::charges_t charges; | 
|---|
|  | 85 | charges.resize(types.size()); | 
|---|
|  | 86 | std::transform(types.begin(), types.end(), | 
|---|
|  | 87 | charges.begin(), boost::lambda::_1); | 
|---|
|  | 88 | // convert into count map | 
|---|
|  | 89 | Extractors::elementcounts_t counts_per_charge = | 
|---|
|  | 90 | Extractors::_detail::getElementCounts(charges); | 
|---|
|  | 91 | ASSERT( !counts_per_charge.empty(), | 
|---|
|  | 92 | "getFirstGraphwithSpecifiedElements() - charge counts are empty?"); | 
|---|
|  | 93 | LOG(2, "DEBUG: counts_per_charge is " << counts_per_charge << "."); | 
|---|
|  | 94 | // we want to check each (unique) key only once | 
|---|
| [707a2b] | 95 | for (HomologyContainer::const_key_iterator iter = homologies.key_begin(); | 
|---|
|  | 96 | iter != homologies.key_end(); iter = homologies.getNextKey(iter)) { | 
|---|
|  | 97 | // check if every element has the right number of counts | 
|---|
| [48d20d] | 98 | Extractors::elementcounts_t::const_iterator countiter = counts_per_charge.begin(); | 
|---|
|  | 99 | for (; countiter != counts_per_charge.end(); ++countiter) | 
|---|
| [3536a5f] | 100 | if (!(*iter).hasTimesAtomicNumber( | 
|---|
|  | 101 | static_cast<size_t>(countiter->first), | 
|---|
|  | 102 | static_cast<size_t>(countiter->second)) | 
|---|
|  | 103 | ) | 
|---|
| [48d20d] | 104 | break; | 
|---|
|  | 105 | if( countiter == counts_per_charge.end()) | 
|---|
|  | 106 | return *iter; | 
|---|
|  | 107 | } | 
|---|
|  | 108 | return HomologyGraph(); | 
|---|
|  | 109 | } | 
|---|
|  | 110 |  | 
|---|
| [4e009d] | 111 | SerializablePotential::ParticleTypes_t getNumbersFromElements( | 
|---|
|  | 112 | const std::vector<const element *> &fragment) | 
|---|
|  | 113 | { | 
|---|
|  | 114 | SerializablePotential::ParticleTypes_t fragmentnumbers; | 
|---|
|  | 115 | std::transform(fragment.begin(), fragment.end(), std::back_inserter(fragmentnumbers), | 
|---|
|  | 116 | boost::bind(&element::getAtomicNumber, _1)); | 
|---|
|  | 117 | return fragmentnumbers; | 
|---|
|  | 118 | } | 
|---|
|  | 119 |  | 
|---|
|  | 120 |  | 
|---|
| [b5b01e] | 121 | ActionState::ptr PotentialFitPotentialAction::performCall() { | 
|---|
| [48d20d] | 122 | // fragment specifies the homology fragment to use | 
|---|
| [4e009d] | 123 | SerializablePotential::ParticleTypes_t fragmentnumbers = | 
|---|
|  | 124 | getNumbersFromElements(params.fragment.get()); | 
|---|
| [48d20d] | 125 |  | 
|---|
| [baccf6] | 126 | // either charges and a potential is specified or a file | 
|---|
|  | 127 | if (boost::filesystem::exists(params.potential_file.get())) { | 
|---|
|  | 128 | std::ifstream returnstream(params.potential_file.get().string().c_str()); | 
|---|
|  | 129 | if (returnstream.good()) { | 
|---|
| [49dcf7] | 130 | try { | 
|---|
|  | 131 | PotentialDeserializer deserialize(returnstream); | 
|---|
|  | 132 | deserialize(); | 
|---|
|  | 133 | } catch (SerializablePotentialMissingValueException &e) { | 
|---|
|  | 134 | if (const std::string *key = boost::get_error_info<SerializablePotentialKey>(e)) | 
|---|
| [26b4d62] | 135 | STATUS("Missing value when parsing information for potential "+*key+"."); | 
|---|
| [49dcf7] | 136 | else | 
|---|
| [26b4d62] | 137 | STATUS("Missing value parsing information for potential with unknown key."); | 
|---|
| [49dcf7] | 138 | return Action::failure; | 
|---|
|  | 139 | } catch (SerializablePotentialIllegalKeyException &e) { | 
|---|
|  | 140 | if (const std::string *key = boost::get_error_info<SerializablePotentialKey>(e)) | 
|---|
| [26b4d62] | 141 | STATUS("Illegal key parsing information for potential "+*key+"."); | 
|---|
| [49dcf7] | 142 | else | 
|---|
| [26b4d62] | 143 | STATUS("Illegal key parsing information for potential with unknown key."); | 
|---|
| [49dcf7] | 144 | return Action::failure; | 
|---|
|  | 145 | } | 
|---|
| [baccf6] | 146 | } else { | 
|---|
| [26b4d62] | 147 | STATUS("Failed to parse from "+params.potential_file.get().string()+"."); | 
|---|
| [baccf6] | 148 | return Action::failure; | 
|---|
|  | 149 | } | 
|---|
|  | 150 | returnstream.close(); | 
|---|
|  | 151 |  | 
|---|
|  | 152 | LOG(0, "STATUS: I'm training now a set of potentials parsed from " | 
|---|
|  | 153 | << params.potential_file.get().string() << " on a fragment " | 
|---|
| [d449a9] | 154 | << fragmentnumbers << " on data from World's homologies."); | 
|---|
| [baccf6] | 155 |  | 
|---|
|  | 156 | } else { | 
|---|
|  | 157 | if (params.charges.get().empty()) { | 
|---|
| [26b4d62] | 158 | STATUS("Neither charges nor potential file given!"); | 
|---|
| [baccf6] | 159 | return Action::failure; | 
|---|
|  | 160 | } else { | 
|---|
|  | 161 | // charges specify the potential type | 
|---|
| [4e009d] | 162 | SerializablePotential::ParticleTypes_t chargenumbers = | 
|---|
|  | 163 | getNumbersFromElements(params.charges.get()); | 
|---|
| [baccf6] | 164 |  | 
|---|
|  | 165 | LOG(0, "STATUS: I'm training now a " << params.potentialtype.get() | 
|---|
| [d449a9] | 166 | << " potential on charges " << chargenumbers << " on data from World's homologies."); | 
|---|
| [baccf6] | 167 |  | 
|---|
|  | 168 | // register desired potential and an additional constant one | 
|---|
| [c34711] | 169 | { | 
|---|
|  | 170 | EmpiricalPotential *potential = | 
|---|
|  | 171 | PotentialFactory::getInstance().createInstance( | 
|---|
|  | 172 | params.potentialtype.get(), | 
|---|
|  | 173 | chargenumbers); | 
|---|
|  | 174 | // check whether such a potential already exists | 
|---|
|  | 175 | const std::string potential_name = potential->getName(); | 
|---|
|  | 176 | if (PotentialRegistry::getInstance().isPresentByName(potential_name)) { | 
|---|
|  | 177 | delete potential; | 
|---|
|  | 178 | potential = PotentialRegistry::getInstance().getByName(potential_name); | 
|---|
|  | 179 | } else | 
|---|
|  | 180 | PotentialRegistry::getInstance().registerInstance(potential); | 
|---|
|  | 181 | } | 
|---|
|  | 182 | { | 
|---|
|  | 183 | EmpiricalPotential *constant = | 
|---|
|  | 184 | PotentialFactory::getInstance().createInstance( | 
|---|
|  | 185 | std::string("constant"), | 
|---|
|  | 186 | SerializablePotential::ParticleTypes_t()); | 
|---|
|  | 187 | // check whether such a potential already exists | 
|---|
|  | 188 | const std::string constant_name = constant->getName(); | 
|---|
|  | 189 | if (PotentialRegistry::getInstance().isPresentByName(constant_name)) { | 
|---|
|  | 190 | delete constant; | 
|---|
|  | 191 | constant = PotentialRegistry::getInstance().getByName(constant_name); | 
|---|
|  | 192 | } else | 
|---|
|  | 193 | PotentialRegistry::getInstance().registerInstance(constant); | 
|---|
|  | 194 | } | 
|---|
| [baccf6] | 195 | } | 
|---|
|  | 196 | } | 
|---|
|  | 197 |  | 
|---|
| [48d20d] | 198 | // parse homologies into container | 
|---|
| [d449a9] | 199 | HomologyContainer &homologies = World::getInstance().getHomologies(); | 
|---|
| [48d20d] | 200 |  | 
|---|
|  | 201 | // first we try to look into the HomologyContainer | 
|---|
|  | 202 | LOG(1, "INFO: Listing all present homologies ..."); | 
|---|
|  | 203 | for (HomologyContainer::container_t::const_iterator iter = | 
|---|
|  | 204 | homologies.begin(); iter != homologies.end(); ++iter) { | 
|---|
| [bf1d1b] | 205 | LOG(1, "INFO: graph " << iter->first | 
|---|
|  | 206 | << " has Fragment " << iter->second.fragment | 
|---|
|  | 207 | << ", associated energy " << iter->second.energy | 
|---|
|  | 208 | << ", and sampled grid integral " << iter->second.charge_distribution.integral() | 
|---|
|  | 209 | << "."); | 
|---|
| [48d20d] | 210 | } | 
|---|
|  | 211 |  | 
|---|
| [baccf6] | 212 | // then we ought to pick the right HomologyGraph ... | 
|---|
|  | 213 | const HomologyGraph graph = getFirstGraphwithSpecifiedElements(homologies,fragmentnumbers); | 
|---|
|  | 214 | if (graph != HomologyGraph()) { | 
|---|
|  | 215 | LOG(1, "First representative graph containing fragment " | 
|---|
|  | 216 | << fragmentnumbers << " is " << graph << "."); | 
|---|
|  | 217 | } else { | 
|---|
| [26b4d62] | 218 | STATUS("Specific fragment "+toString(fragmentnumbers)+" not found in homologies!"); | 
|---|
| [baccf6] | 219 | return Action::failure; | 
|---|
|  | 220 | } | 
|---|
|  | 221 |  | 
|---|
|  | 222 | // fit potential | 
|---|
|  | 223 | FunctionModel *model = new CompoundPotential(graph); | 
|---|
|  | 224 | ASSERT( model != NULL, | 
|---|
| [f5724f] | 225 | "PotentialFitPotentialAction::performCall() - model is NULL."); | 
|---|
| [48d20d] | 226 |  | 
|---|
|  | 227 | /******************** TRAINING ********************/ | 
|---|
|  | 228 | // fit potential | 
|---|
|  | 229 | FunctionModel::parameters_t bestparams(model->getParameterDimension(), 0.); | 
|---|
|  | 230 | { | 
|---|
| [baccf6] | 231 | // Afterwards we go through all of this type and gather the distance and the energy value | 
|---|
| [af2c7ec] | 232 | TrainingData data(model->getSpecificFilter()); | 
|---|
| [baccf6] | 233 | data(homologies.getHomologousGraphs(graph)); | 
|---|
| [48d20d] | 234 |  | 
|---|
| [baccf6] | 235 | // print distances and energies if desired for debugging | 
|---|
|  | 236 | if (!data.getTrainingInputs().empty()) { | 
|---|
|  | 237 | // print which distance is which | 
|---|
|  | 238 | size_t counter=1; | 
|---|
|  | 239 | if (DoLog(3)) { | 
|---|
| [e1fe7e] | 240 | const FunctionModel::arguments_t &inputs = data.getAllArguments()[0]; | 
|---|
| [baccf6] | 241 | for (FunctionModel::arguments_t::const_iterator iter = inputs.begin(); | 
|---|
|  | 242 | iter != inputs.end(); ++iter) { | 
|---|
|  | 243 | const argument_t &arg = *iter; | 
|---|
|  | 244 | LOG(3, "DEBUG: distance " << counter++ << " is between (#" | 
|---|
|  | 245 | << arg.indices.first << "c" << arg.types.first << "," | 
|---|
|  | 246 | << arg.indices.second << "c" << arg.types.second << ")."); | 
|---|
| [48d20d] | 247 | } | 
|---|
|  | 248 | } | 
|---|
|  | 249 |  | 
|---|
| [baccf6] | 250 | // print table | 
|---|
| [a504946] | 251 | if (params.training_file.get().string().empty()) { | 
|---|
|  | 252 | LOG(3, "DEBUG: I gathered the following training data:\n" << | 
|---|
|  | 253 | _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable())); | 
|---|
|  | 254 | } else { | 
|---|
|  | 255 | std::ofstream trainingstream(params.training_file.get().string().c_str()); | 
|---|
|  | 256 | if (trainingstream.good()) { | 
|---|
|  | 257 | LOG(3, "DEBUG: Writing training data to file " << | 
|---|
|  | 258 | params.training_file.get().string() << "."); | 
|---|
|  | 259 | trainingstream << _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable()); | 
|---|
|  | 260 | } | 
|---|
|  | 261 | trainingstream.close(); | 
|---|
|  | 262 | } | 
|---|
| [baccf6] | 263 | } | 
|---|
|  | 264 |  | 
|---|
| [4e009d] | 265 | if ((params.threshold.get() < 1) && (params.best_of_howmany.isSet())) | 
|---|
|  | 266 | ELOG(2, "threshold parameter always overrules max_runs, both are specified."); | 
|---|
| [baccf6] | 267 | // now perform the function approximation by optimizing the model function | 
|---|
|  | 268 | FunctionApproximation approximator(data, *model); | 
|---|
|  | 269 | if (model->isBoxConstraint() && approximator.checkParameterDerivatives()) { | 
|---|
| [4792ab] | 270 | double l2error = std::numeric_limits<double>::max(); | 
|---|
| [baccf6] | 271 | // seed with current time | 
|---|
|  | 272 | srand((unsigned)time(0)); | 
|---|
| [4792ab] | 273 | unsigned int runs=0; | 
|---|
|  | 274 | // threshold overrules max_runs | 
|---|
|  | 275 | const double threshold = params.threshold.get(); | 
|---|
|  | 276 | const unsigned int max_runs = (threshold >= 1.) ? | 
|---|
|  | 277 | (params.best_of_howmany.isSet() ? params.best_of_howmany.get() : 1) : 0; | 
|---|
|  | 278 | LOG(1, "INFO: Maximum runs is " << max_runs << " and threshold set to " << threshold << "."); | 
|---|
|  | 279 | do { | 
|---|
| [baccf6] | 280 | // generate new random initial parameter values | 
|---|
|  | 281 | model->setParametersToRandomInitialValues(data); | 
|---|
|  | 282 | LOG(1, "INFO: Initial parameters of run " << runs << " are " | 
|---|
|  | 283 | << model->getParameters() << "."); | 
|---|
|  | 284 | approximator(FunctionApproximation::ParameterDerivative); | 
|---|
|  | 285 | LOG(1, "INFO: Final parameters of run " << runs << " are " | 
|---|
|  | 286 | << model->getParameters() << "."); | 
|---|
|  | 287 | const double new_l2error = data.getL2Error(*model); | 
|---|
|  | 288 | if (new_l2error < l2error) { | 
|---|
|  | 289 | // store currently best parameters | 
|---|
|  | 290 | l2error = new_l2error; | 
|---|
|  | 291 | bestparams = model->getParameters(); | 
|---|
|  | 292 | LOG(1, "STATUS: New fit from run " << runs | 
|---|
|  | 293 | << " has better error of " << l2error << "."); | 
|---|
| [48d20d] | 294 | } | 
|---|
| [4792ab] | 295 | } while (( ++runs < max_runs) || (l2error > threshold)); | 
|---|
| [baccf6] | 296 | // reset parameters from best fit | 
|---|
|  | 297 | model->setParameters(bestparams); | 
|---|
|  | 298 | LOG(1, "INFO: Best parameters with L2 error of " | 
|---|
|  | 299 | << l2error << " are " << model->getParameters() << "."); | 
|---|
|  | 300 | } else { | 
|---|
| [26b4d62] | 301 | STATUS("No required parameter derivatives for a box constraint minimization known."); | 
|---|
| [baccf6] | 302 | return Action::failure; | 
|---|
|  | 303 | } | 
|---|
|  | 304 |  | 
|---|
|  | 305 | // create a map of each fragment with error. | 
|---|
|  | 306 | HomologyContainer::range_t fragmentrange = homologies.getHomologousGraphs(graph); | 
|---|
| [f4496d] | 307 | TrainingData::L2ErrorConfigurationIndexMap_t WorseFragmentMap = | 
|---|
|  | 308 | data.getWorstFragmentMap(*model, fragmentrange); | 
|---|
| [baccf6] | 309 | LOG(0, "RESULT: WorstFragmentMap " << WorseFragmentMap << "."); | 
|---|
|  | 310 |  | 
|---|
|  | 311 | // print fitted potentials | 
|---|
|  | 312 | std::stringstream potentials; | 
|---|
|  | 313 | PotentialSerializer serialize(potentials); | 
|---|
|  | 314 | serialize(); | 
|---|
|  | 315 | LOG(1, "STATUS: Resulting parameters are " << std::endl << potentials.str()); | 
|---|
| [62164d] | 316 | std::ofstream returnstream(params.potential_file.get().string().c_str()); | 
|---|
|  | 317 | if (returnstream.good()) { | 
|---|
|  | 318 | returnstream << potentials.str(); | 
|---|
|  | 319 | } | 
|---|
| [48d20d] | 320 | } | 
|---|
|  | 321 | delete model; | 
|---|
|  | 322 |  | 
|---|
|  | 323 | return Action::success; | 
|---|
|  | 324 | } | 
|---|
|  | 325 |  | 
|---|
| [b5b01e] | 326 | ActionState::ptr PotentialFitPotentialAction::performUndo(ActionState::ptr _state) { | 
|---|
| [48d20d] | 327 | return Action::success; | 
|---|
|  | 328 | } | 
|---|
|  | 329 |  | 
|---|
| [b5b01e] | 330 | ActionState::ptr PotentialFitPotentialAction::performRedo(ActionState::ptr _state){ | 
|---|
| [48d20d] | 331 | return Action::success; | 
|---|
|  | 332 | } | 
|---|
|  | 333 |  | 
|---|
| [f5724f] | 334 | bool PotentialFitPotentialAction::canUndo() { | 
|---|
| [48d20d] | 335 | return false; | 
|---|
|  | 336 | } | 
|---|
|  | 337 |  | 
|---|
| [f5724f] | 338 | bool PotentialFitPotentialAction::shouldUndo() { | 
|---|
| [48d20d] | 339 | return false; | 
|---|
|  | 340 | } | 
|---|
|  | 341 | /** =========== end of function ====================== */ | 
|---|