| 1 | /* | 
|---|
| 2 | * Project: MoleCuilder | 
|---|
| 3 | * Description: creates and alters molecular systems | 
|---|
| 4 | * Copyright (C)  2013 University of Bonn. All rights reserved. | 
|---|
| 5 | * Copyright (C)  2013 Frederik Heber. All rights reserved. | 
|---|
| 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 |  | 
|---|
| 49 | #include "Actions/PotentialAction/FitPotentialAction.hpp" | 
|---|
| 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" | 
|---|
| 62 | #include "Potentials/CompoundPotential.hpp" | 
|---|
| 63 | #include "Potentials/Exceptions.hpp" | 
|---|
| 64 | #include "Potentials/PotentialDeserializer.hpp" | 
|---|
| 65 | #include "Potentials/PotentialFactory.hpp" | 
|---|
| 66 | #include "Potentials/PotentialRegistry.hpp" | 
|---|
| 67 | #include "Potentials/PotentialSerializer.hpp" | 
|---|
| 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 | 
|---|
| 95 | HomologyContainer::const_key_iterator olditer = homologies.key_end(); | 
|---|
| 96 | for (HomologyContainer::const_key_iterator iter = | 
|---|
| 97 | homologies.key_begin(); iter != homologies.key_end(); olditer = iter++) { | 
|---|
| 98 | // if it's the same as the old one, skip it | 
|---|
| 99 | if (*olditer == *iter) | 
|---|
| 100 | continue; | 
|---|
| 101 | // if it's a new key, check if every element has the right number of counts | 
|---|
| 102 | Extractors::elementcounts_t::const_iterator countiter = counts_per_charge.begin(); | 
|---|
| 103 | for (; countiter != counts_per_charge.end(); ++countiter) | 
|---|
| 104 | if (!(*iter).hasTimesAtomicNumber( | 
|---|
| 105 | static_cast<size_t>(countiter->first), | 
|---|
| 106 | static_cast<size_t>(countiter->second)) | 
|---|
| 107 | ) | 
|---|
| 108 | break; | 
|---|
| 109 | if( countiter == counts_per_charge.end()) | 
|---|
| 110 | return *iter; | 
|---|
| 111 | } | 
|---|
| 112 | return HomologyGraph(); | 
|---|
| 113 | } | 
|---|
| 114 |  | 
|---|
| 115 | SerializablePotential::ParticleTypes_t getNumbersFromElements( | 
|---|
| 116 | const std::vector<const element *> &fragment) | 
|---|
| 117 | { | 
|---|
| 118 | SerializablePotential::ParticleTypes_t fragmentnumbers; | 
|---|
| 119 | std::transform(fragment.begin(), fragment.end(), std::back_inserter(fragmentnumbers), | 
|---|
| 120 | boost::bind(&element::getAtomicNumber, _1)); | 
|---|
| 121 | return fragmentnumbers; | 
|---|
| 122 | } | 
|---|
| 123 |  | 
|---|
| 124 |  | 
|---|
| 125 | ActionState::ptr PotentialFitPotentialAction::performCall() { | 
|---|
| 126 | // fragment specifies the homology fragment to use | 
|---|
| 127 | SerializablePotential::ParticleTypes_t fragmentnumbers = | 
|---|
| 128 | getNumbersFromElements(params.fragment.get()); | 
|---|
| 129 |  | 
|---|
| 130 | // either charges and a potential is specified or a file | 
|---|
| 131 | if (boost::filesystem::exists(params.potential_file.get())) { | 
|---|
| 132 | std::ifstream returnstream(params.potential_file.get().string().c_str()); | 
|---|
| 133 | if (returnstream.good()) { | 
|---|
| 134 | try { | 
|---|
| 135 | PotentialDeserializer deserialize(returnstream); | 
|---|
| 136 | deserialize(); | 
|---|
| 137 | } catch (SerializablePotentialMissingValueException &e) { | 
|---|
| 138 | if (const std::string *key = boost::get_error_info<SerializablePotentialKey>(e)) | 
|---|
| 139 | STATUS("Missing value when parsing information for potential "+*key+"."); | 
|---|
| 140 | else | 
|---|
| 141 | STATUS("Missing value parsing information for potential with unknown key."); | 
|---|
| 142 | return Action::failure; | 
|---|
| 143 | } catch (SerializablePotentialIllegalKeyException &e) { | 
|---|
| 144 | if (const std::string *key = boost::get_error_info<SerializablePotentialKey>(e)) | 
|---|
| 145 | STATUS("Illegal key parsing information for potential "+*key+"."); | 
|---|
| 146 | else | 
|---|
| 147 | STATUS("Illegal key parsing information for potential with unknown key."); | 
|---|
| 148 | return Action::failure; | 
|---|
| 149 | } | 
|---|
| 150 | } else { | 
|---|
| 151 | STATUS("Failed to parse from "+params.potential_file.get().string()+"."); | 
|---|
| 152 | return Action::failure; | 
|---|
| 153 | } | 
|---|
| 154 | returnstream.close(); | 
|---|
| 155 |  | 
|---|
| 156 | LOG(0, "STATUS: I'm training now a set of potentials parsed from " | 
|---|
| 157 | << params.potential_file.get().string() << " on a fragment " | 
|---|
| 158 | << fragmentnumbers << " on data from World's homologies."); | 
|---|
| 159 |  | 
|---|
| 160 | } else { | 
|---|
| 161 | if (params.charges.get().empty()) { | 
|---|
| 162 | STATUS("Neither charges nor potential file given!"); | 
|---|
| 163 | return Action::failure; | 
|---|
| 164 | } else { | 
|---|
| 165 | // charges specify the potential type | 
|---|
| 166 | SerializablePotential::ParticleTypes_t chargenumbers = | 
|---|
| 167 | getNumbersFromElements(params.charges.get()); | 
|---|
| 168 |  | 
|---|
| 169 | LOG(0, "STATUS: I'm training now a " << params.potentialtype.get() | 
|---|
| 170 | << " potential on charges " << chargenumbers << " on data from World's homologies."); | 
|---|
| 171 |  | 
|---|
| 172 | // register desired potential and an additional constant one | 
|---|
| 173 | { | 
|---|
| 174 | EmpiricalPotential *potential = | 
|---|
| 175 | PotentialFactory::getInstance().createInstance( | 
|---|
| 176 | params.potentialtype.get(), | 
|---|
| 177 | chargenumbers); | 
|---|
| 178 | // check whether such a potential already exists | 
|---|
| 179 | const std::string potential_name = potential->getName(); | 
|---|
| 180 | if (PotentialRegistry::getInstance().isPresentByName(potential_name)) { | 
|---|
| 181 | delete potential; | 
|---|
| 182 | potential = PotentialRegistry::getInstance().getByName(potential_name); | 
|---|
| 183 | } else | 
|---|
| 184 | PotentialRegistry::getInstance().registerInstance(potential); | 
|---|
| 185 | } | 
|---|
| 186 | { | 
|---|
| 187 | EmpiricalPotential *constant = | 
|---|
| 188 | PotentialFactory::getInstance().createInstance( | 
|---|
| 189 | std::string("constant"), | 
|---|
| 190 | SerializablePotential::ParticleTypes_t()); | 
|---|
| 191 | // check whether such a potential already exists | 
|---|
| 192 | const std::string constant_name = constant->getName(); | 
|---|
| 193 | if (PotentialRegistry::getInstance().isPresentByName(constant_name)) { | 
|---|
| 194 | delete constant; | 
|---|
| 195 | constant = PotentialRegistry::getInstance().getByName(constant_name); | 
|---|
| 196 | } else | 
|---|
| 197 | PotentialRegistry::getInstance().registerInstance(constant); | 
|---|
| 198 | } | 
|---|
| 199 | } | 
|---|
| 200 | } | 
|---|
| 201 |  | 
|---|
| 202 | // parse homologies into container | 
|---|
| 203 | HomologyContainer &homologies = World::getInstance().getHomologies(); | 
|---|
| 204 |  | 
|---|
| 205 | // first we try to look into the HomologyContainer | 
|---|
| 206 | LOG(1, "INFO: Listing all present homologies ..."); | 
|---|
| 207 | for (HomologyContainer::container_t::const_iterator iter = | 
|---|
| 208 | homologies.begin(); iter != homologies.end(); ++iter) { | 
|---|
| 209 | LOG(1, "INFO: graph " << iter->first | 
|---|
| 210 | << " has Fragment " << iter->second.fragment | 
|---|
| 211 | << ", associated energy " << iter->second.energy | 
|---|
| 212 | << ", and sampled grid integral " << iter->second.charge_distribution.integral() | 
|---|
| 213 | << "."); | 
|---|
| 214 | } | 
|---|
| 215 |  | 
|---|
| 216 | // then we ought to pick the right HomologyGraph ... | 
|---|
| 217 | const HomologyGraph graph = getFirstGraphwithSpecifiedElements(homologies,fragmentnumbers); | 
|---|
| 218 | if (graph != HomologyGraph()) { | 
|---|
| 219 | LOG(1, "First representative graph containing fragment " | 
|---|
| 220 | << fragmentnumbers << " is " << graph << "."); | 
|---|
| 221 | } else { | 
|---|
| 222 | STATUS("Specific fragment "+toString(fragmentnumbers)+" not found in homologies!"); | 
|---|
| 223 | return Action::failure; | 
|---|
| 224 | } | 
|---|
| 225 |  | 
|---|
| 226 | // fit potential | 
|---|
| 227 | FunctionModel *model = new CompoundPotential(graph); | 
|---|
| 228 | ASSERT( model != NULL, | 
|---|
| 229 | "PotentialFitPotentialAction::performCall() - model is NULL."); | 
|---|
| 230 |  | 
|---|
| 231 | /******************** TRAINING ********************/ | 
|---|
| 232 | // fit potential | 
|---|
| 233 | FunctionModel::parameters_t bestparams(model->getParameterDimension(), 0.); | 
|---|
| 234 | { | 
|---|
| 235 | // Afterwards we go through all of this type and gather the distance and the energy value | 
|---|
| 236 | TrainingData data(model->getSpecificFilter()); | 
|---|
| 237 | data(homologies.getHomologousGraphs(graph)); | 
|---|
| 238 |  | 
|---|
| 239 | // print distances and energies if desired for debugging | 
|---|
| 240 | if (!data.getTrainingInputs().empty()) { | 
|---|
| 241 | // print which distance is which | 
|---|
| 242 | size_t counter=1; | 
|---|
| 243 | if (DoLog(3)) { | 
|---|
| 244 | const FunctionModel::arguments_t &inputs = data.getAllArguments()[0]; | 
|---|
| 245 | for (FunctionModel::arguments_t::const_iterator iter = inputs.begin(); | 
|---|
| 246 | iter != inputs.end(); ++iter) { | 
|---|
| 247 | const argument_t &arg = *iter; | 
|---|
| 248 | LOG(3, "DEBUG: distance " << counter++ << " is between (#" | 
|---|
| 249 | << arg.indices.first << "c" << arg.types.first << "," | 
|---|
| 250 | << arg.indices.second << "c" << arg.types.second << ")."); | 
|---|
| 251 | } | 
|---|
| 252 | } | 
|---|
| 253 |  | 
|---|
| 254 | // print table | 
|---|
| 255 | if (params.training_file.get().string().empty()) { | 
|---|
| 256 | LOG(3, "DEBUG: I gathered the following training data:\n" << | 
|---|
| 257 | _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable())); | 
|---|
| 258 | } else { | 
|---|
| 259 | std::ofstream trainingstream(params.training_file.get().string().c_str()); | 
|---|
| 260 | if (trainingstream.good()) { | 
|---|
| 261 | LOG(3, "DEBUG: Writing training data to file " << | 
|---|
| 262 | params.training_file.get().string() << "."); | 
|---|
| 263 | trainingstream << _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable()); | 
|---|
| 264 | } | 
|---|
| 265 | trainingstream.close(); | 
|---|
| 266 | } | 
|---|
| 267 | } | 
|---|
| 268 |  | 
|---|
| 269 | if ((params.threshold.get() < 1) && (params.best_of_howmany.isSet())) | 
|---|
| 270 | ELOG(2, "threshold parameter always overrules max_runs, both are specified."); | 
|---|
| 271 | // now perform the function approximation by optimizing the model function | 
|---|
| 272 | FunctionApproximation approximator(data, *model); | 
|---|
| 273 | if (model->isBoxConstraint() && approximator.checkParameterDerivatives()) { | 
|---|
| 274 | double l2error = std::numeric_limits<double>::max(); | 
|---|
| 275 | // seed with current time | 
|---|
| 276 | srand((unsigned)time(0)); | 
|---|
| 277 | unsigned int runs=0; | 
|---|
| 278 | // threshold overrules max_runs | 
|---|
| 279 | const double threshold = params.threshold.get(); | 
|---|
| 280 | const unsigned int max_runs = (threshold >= 1.) ? | 
|---|
| 281 | (params.best_of_howmany.isSet() ? params.best_of_howmany.get() : 1) : 0; | 
|---|
| 282 | LOG(1, "INFO: Maximum runs is " << max_runs << " and threshold set to " << threshold << "."); | 
|---|
| 283 | do { | 
|---|
| 284 | // generate new random initial parameter values | 
|---|
| 285 | model->setParametersToRandomInitialValues(data); | 
|---|
| 286 | LOG(1, "INFO: Initial parameters of run " << runs << " are " | 
|---|
| 287 | << model->getParameters() << "."); | 
|---|
| 288 | approximator(FunctionApproximation::ParameterDerivative); | 
|---|
| 289 | LOG(1, "INFO: Final parameters of run " << runs << " are " | 
|---|
| 290 | << model->getParameters() << "."); | 
|---|
| 291 | const double new_l2error = data.getL2Error(*model); | 
|---|
| 292 | if (new_l2error < l2error) { | 
|---|
| 293 | // store currently best parameters | 
|---|
| 294 | l2error = new_l2error; | 
|---|
| 295 | bestparams = model->getParameters(); | 
|---|
| 296 | LOG(1, "STATUS: New fit from run " << runs | 
|---|
| 297 | << " has better error of " << l2error << "."); | 
|---|
| 298 | } | 
|---|
| 299 | } while (( ++runs < max_runs) || (l2error > threshold)); | 
|---|
| 300 | // reset parameters from best fit | 
|---|
| 301 | model->setParameters(bestparams); | 
|---|
| 302 | LOG(1, "INFO: Best parameters with L2 error of " | 
|---|
| 303 | << l2error << " are " << model->getParameters() << "."); | 
|---|
| 304 | } else { | 
|---|
| 305 | STATUS("No required parameter derivatives for a box constraint minimization known."); | 
|---|
| 306 | return Action::failure; | 
|---|
| 307 | } | 
|---|
| 308 |  | 
|---|
| 309 | // create a map of each fragment with error. | 
|---|
| 310 | HomologyContainer::range_t fragmentrange = homologies.getHomologousGraphs(graph); | 
|---|
| 311 | TrainingData::L2ErrorConfigurationIndexMap_t WorseFragmentMap = | 
|---|
| 312 | data.getWorstFragmentMap(*model, fragmentrange); | 
|---|
| 313 | LOG(0, "RESULT: WorstFragmentMap " << WorseFragmentMap << "."); | 
|---|
| 314 |  | 
|---|
| 315 | // print fitted potentials | 
|---|
| 316 | std::stringstream potentials; | 
|---|
| 317 | PotentialSerializer serialize(potentials); | 
|---|
| 318 | serialize(); | 
|---|
| 319 | LOG(1, "STATUS: Resulting parameters are " << std::endl << potentials.str()); | 
|---|
| 320 | std::ofstream returnstream(params.potential_file.get().string().c_str()); | 
|---|
| 321 | if (returnstream.good()) { | 
|---|
| 322 | returnstream << potentials.str(); | 
|---|
| 323 | } | 
|---|
| 324 | } | 
|---|
| 325 | delete model; | 
|---|
| 326 |  | 
|---|
| 327 | return Action::success; | 
|---|
| 328 | } | 
|---|
| 329 |  | 
|---|
| 330 | ActionState::ptr PotentialFitPotentialAction::performUndo(ActionState::ptr _state) { | 
|---|
| 331 | return Action::success; | 
|---|
| 332 | } | 
|---|
| 333 |  | 
|---|
| 334 | ActionState::ptr PotentialFitPotentialAction::performRedo(ActionState::ptr _state){ | 
|---|
| 335 | return Action::success; | 
|---|
| 336 | } | 
|---|
| 337 |  | 
|---|
| 338 | bool PotentialFitPotentialAction::canUndo() { | 
|---|
| 339 | return false; | 
|---|
| 340 | } | 
|---|
| 341 |  | 
|---|
| 342 | bool PotentialFitPotentialAction::shouldUndo() { | 
|---|
| 343 | return false; | 
|---|
| 344 | } | 
|---|
| 345 | /** =========== end of function ====================== */ | 
|---|