| [98d166] | 1 | /* | 
|---|
|  | 2 | * Project: MoleCuilder | 
|---|
|  | 3 | * Description: creates and alters molecular systems | 
|---|
|  | 4 | * Copyright (C)  2014 Frederik Heber. All rights reserved. | 
|---|
|  | 5 | * | 
|---|
|  | 6 | * | 
|---|
|  | 7 | *   This file is part of MoleCuilder. | 
|---|
|  | 8 | * | 
|---|
|  | 9 | *    MoleCuilder is free software: you can redistribute it and/or modify | 
|---|
|  | 10 | *    it under the terms of the GNU General Public License as published by | 
|---|
|  | 11 | *    the Free Software Foundation, either version 2 of the License, or | 
|---|
|  | 12 | *    (at your option) any later version. | 
|---|
|  | 13 | * | 
|---|
|  | 14 | *    MoleCuilder 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 | 
|---|
|  | 17 | *    GNU General Public License for more details. | 
|---|
|  | 18 | * | 
|---|
|  | 19 | *    You should have received a copy of the GNU General Public License | 
|---|
|  | 20 | *    along with MoleCuilder.  If not, see <http://www.gnu.org/licenses/>. | 
|---|
|  | 21 | */ | 
|---|
|  | 22 |  | 
|---|
|  | 23 | /* | 
|---|
|  | 24 | * PotentialTrainer.cpp | 
|---|
|  | 25 | * | 
|---|
|  | 26 | *  Created on: Sep 11, 2014 | 
|---|
|  | 27 | *      Author: heber | 
|---|
|  | 28 | */ | 
|---|
|  | 29 |  | 
|---|
|  | 30 | // include config.h | 
|---|
|  | 31 | #ifdef HAVE_CONFIG_H | 
|---|
|  | 32 | #include <config.h> | 
|---|
|  | 33 | #endif | 
|---|
|  | 34 |  | 
|---|
|  | 35 | // needs to come before MemDebug due to placement new | 
|---|
|  | 36 | #include <boost/archive/text_iarchive.hpp> | 
|---|
|  | 37 |  | 
|---|
|  | 38 | #include "CodePatterns/MemDebug.hpp" | 
|---|
|  | 39 |  | 
|---|
|  | 40 | #include "PotentialTrainer.hpp" | 
|---|
|  | 41 |  | 
|---|
|  | 42 | #include <algorithm> | 
|---|
|  | 43 | #include <boost/lambda/lambda.hpp> | 
|---|
|  | 44 | #include <boost/filesystem.hpp> | 
|---|
|  | 45 | #include <fstream> | 
|---|
|  | 46 | #include <sstream> | 
|---|
|  | 47 |  | 
|---|
|  | 48 | #include "CodePatterns/Assert.hpp" | 
|---|
|  | 49 | #include "CodePatterns/Log.hpp" | 
|---|
|  | 50 |  | 
|---|
|  | 51 | #include "Element/element.hpp" | 
|---|
|  | 52 | #include "Fragmentation/Homology/HomologyContainer.hpp" | 
|---|
|  | 53 | #include "Fragmentation/Homology/HomologyGraph.hpp" | 
|---|
|  | 54 | #include "FunctionApproximation/Extractors.hpp" | 
|---|
|  | 55 | #include "FunctionApproximation/FunctionApproximation.hpp" | 
|---|
|  | 56 | #include "FunctionApproximation/FunctionModel.hpp" | 
|---|
|  | 57 | #include "FunctionApproximation/TrainingData.hpp" | 
|---|
|  | 58 | #include "FunctionApproximation/writeDistanceEnergyTable.hpp" | 
|---|
|  | 59 | #include "Potentials/CompoundPotential.hpp" | 
|---|
|  | 60 | #include "Potentials/PotentialSerializer.hpp" | 
|---|
|  | 61 | #include "Potentials/SerializablePotential.hpp" | 
|---|
|  | 62 |  | 
|---|
|  | 63 | PotentialTrainer::PotentialTrainer() | 
|---|
|  | 64 | {} | 
|---|
|  | 65 |  | 
|---|
|  | 66 | PotentialTrainer::~PotentialTrainer() | 
|---|
|  | 67 | {} | 
|---|
|  | 68 |  | 
|---|
|  | 69 | bool PotentialTrainer::operator()( | 
|---|
|  | 70 | const HomologyContainer &_homologies, | 
|---|
|  | 71 | const HomologyGraph &_graph, | 
|---|
|  | 72 | const boost::filesystem::path &_trainingfile, | 
|---|
|  | 73 | const double _threshold, | 
|---|
|  | 74 | const unsigned int _best_of_howmany) const | 
|---|
|  | 75 | { | 
|---|
|  | 76 | // fit potential | 
|---|
|  | 77 | FunctionModel *model = new CompoundPotential(_graph); | 
|---|
|  | 78 | ASSERT( model != NULL, | 
|---|
|  | 79 | "PotentialTrainer::operator() - model is NULL."); | 
|---|
|  | 80 |  | 
|---|
|  | 81 | /******************** TRAINING ********************/ | 
|---|
|  | 82 | // fit potential | 
|---|
|  | 83 | FunctionModel::parameters_t bestparams(model->getParameterDimension(), 0.); | 
|---|
|  | 84 | { | 
|---|
|  | 85 | // Afterwards we go through all of this type and gather the distance and the energy value | 
|---|
|  | 86 | TrainingData data(model->getSpecificFilter()); | 
|---|
|  | 87 | data(_homologies.getHomologousGraphs(_graph)); | 
|---|
|  | 88 |  | 
|---|
|  | 89 | // print distances and energies if desired for debugging | 
|---|
|  | 90 | if (!data.getTrainingInputs().empty()) { | 
|---|
|  | 91 | // print which distance is which | 
|---|
|  | 92 | size_t counter=1; | 
|---|
|  | 93 | if (DoLog(3)) { | 
|---|
|  | 94 | const FunctionModel::arguments_t &inputs = data.getAllArguments()[0]; | 
|---|
|  | 95 | for (FunctionModel::arguments_t::const_iterator iter = inputs.begin(); | 
|---|
|  | 96 | iter != inputs.end(); ++iter) { | 
|---|
|  | 97 | const argument_t &arg = *iter; | 
|---|
|  | 98 | LOG(3, "DEBUG: distance " << counter++ << " is between (#" | 
|---|
|  | 99 | << arg.indices.first << "c" << arg.types.first << "," | 
|---|
|  | 100 | << arg.indices.second << "c" << arg.types.second << ")."); | 
|---|
|  | 101 | } | 
|---|
|  | 102 | } | 
|---|
|  | 103 |  | 
|---|
|  | 104 | // print table | 
|---|
|  | 105 | if (_trainingfile.string().empty()) { | 
|---|
|  | 106 | LOG(3, "DEBUG: I gathered the following training data:\n" << | 
|---|
|  | 107 | _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable())); | 
|---|
|  | 108 | } else { | 
|---|
|  | 109 | std::ofstream trainingstream(_trainingfile.string().c_str()); | 
|---|
|  | 110 | if (trainingstream.good()) { | 
|---|
|  | 111 | LOG(3, "DEBUG: Writing training data to file " << | 
|---|
|  | 112 | _trainingfile.string() << "."); | 
|---|
|  | 113 | trainingstream << _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable()); | 
|---|
|  | 114 | } | 
|---|
|  | 115 | trainingstream.close(); | 
|---|
|  | 116 | } | 
|---|
|  | 117 | } | 
|---|
|  | 118 |  | 
|---|
|  | 119 | if ((_threshold < 1.) && (_best_of_howmany)) | 
|---|
|  | 120 | ELOG(2, "threshold parameter always overrules max_runs, both are specified."); | 
|---|
|  | 121 | // now perform the function approximation by optimizing the model function | 
|---|
|  | 122 | FunctionApproximation approximator(data, *model); | 
|---|
|  | 123 | if (model->isBoxConstraint() && approximator.checkParameterDerivatives()) { | 
|---|
|  | 124 | double l2error = std::numeric_limits<double>::max(); | 
|---|
|  | 125 | // seed with current time | 
|---|
|  | 126 | srand((unsigned)time(0)); | 
|---|
|  | 127 | unsigned int runs=0; | 
|---|
|  | 128 | // threshold overrules max_runs | 
|---|
|  | 129 | const double threshold = _threshold; | 
|---|
|  | 130 | const unsigned int max_runs = (threshold >= 1.) ? _best_of_howmany : 1; | 
|---|
|  | 131 | LOG(1, "INFO: Maximum runs is " << max_runs << " and threshold set to " << threshold << "."); | 
|---|
|  | 132 | do { | 
|---|
|  | 133 | // generate new random initial parameter values | 
|---|
|  | 134 | model->setParametersToRandomInitialValues(data); | 
|---|
|  | 135 | LOG(1, "INFO: Initial parameters of run " << runs << " are " | 
|---|
|  | 136 | << model->getParameters() << "."); | 
|---|
|  | 137 | approximator(FunctionApproximation::ParameterDerivative); | 
|---|
|  | 138 | LOG(1, "INFO: Final parameters of run " << runs << " are " | 
|---|
|  | 139 | << model->getParameters() << "."); | 
|---|
|  | 140 | const double new_l2error = data.getL2Error(*model); | 
|---|
|  | 141 | if (new_l2error < l2error) { | 
|---|
|  | 142 | // store currently best parameters | 
|---|
|  | 143 | l2error = new_l2error; | 
|---|
|  | 144 | bestparams = model->getParameters(); | 
|---|
|  | 145 | LOG(1, "STATUS: New fit from run " << runs | 
|---|
|  | 146 | << " has better error of " << l2error << "."); | 
|---|
|  | 147 | } | 
|---|
|  | 148 | } while (( ++runs < max_runs) || (l2error > threshold)); | 
|---|
|  | 149 | // reset parameters from best fit | 
|---|
|  | 150 | model->setParameters(bestparams); | 
|---|
|  | 151 | LOG(1, "INFO: Best parameters with L2 error of " | 
|---|
|  | 152 | << l2error << " are " << model->getParameters() << "."); | 
|---|
|  | 153 | } else { | 
|---|
|  | 154 | return false; | 
|---|
|  | 155 | } | 
|---|
|  | 156 |  | 
|---|
|  | 157 | // create a map of each fragment with error. | 
|---|
|  | 158 | HomologyContainer::range_t fragmentrange = _homologies.getHomologousGraphs(_graph); | 
|---|
|  | 159 | TrainingData::L2ErrorConfigurationIndexMap_t WorseFragmentMap = | 
|---|
|  | 160 | data.getWorstFragmentMap(*model, fragmentrange); | 
|---|
|  | 161 | LOG(0, "RESULT: WorstFragmentMap " << WorseFragmentMap << "."); | 
|---|
|  | 162 |  | 
|---|
|  | 163 | } | 
|---|
|  | 164 | delete model; | 
|---|
|  | 165 |  | 
|---|
|  | 166 | return true; | 
|---|
|  | 167 | } | 
|---|
|  | 168 |  | 
|---|
|  | 169 | HomologyGraph PotentialTrainer::getFirstGraphwithSpecifiedElements( | 
|---|
|  | 170 | const HomologyContainer &homologies, | 
|---|
|  | 171 | const SerializablePotential::ParticleTypes_t &types) | 
|---|
|  | 172 | { | 
|---|
|  | 173 | ASSERT( !types.empty(), | 
|---|
|  | 174 | "getFirstGraphwithSpecifiedElements() - charges is empty?"); | 
|---|
|  | 175 | // create charges | 
|---|
|  | 176 | Fragment::charges_t charges; | 
|---|
|  | 177 | charges.resize(types.size()); | 
|---|
|  | 178 | std::transform(types.begin(), types.end(), | 
|---|
|  | 179 | charges.begin(), boost::lambda::_1); | 
|---|
|  | 180 | // convert into count map | 
|---|
|  | 181 | Extractors::elementcounts_t counts_per_charge = | 
|---|
|  | 182 | Extractors::_detail::getElementCounts(charges); | 
|---|
|  | 183 | ASSERT( !counts_per_charge.empty(), | 
|---|
|  | 184 | "getFirstGraphwithSpecifiedElements() - charge counts are empty?"); | 
|---|
|  | 185 | LOG(2, "DEBUG: counts_per_charge is " << counts_per_charge << "."); | 
|---|
|  | 186 | // we want to check each (unique) key only once | 
|---|
|  | 187 | HomologyContainer::const_key_iterator olditer = homologies.key_end(); | 
|---|
|  | 188 | for (HomologyContainer::const_key_iterator iter = | 
|---|
| [e63edb] | 189 | homologies.key_begin(); iter != homologies.key_end(); | 
|---|
|  | 190 | iter = homologies.getNextKey(iter)) { | 
|---|
| [98d166] | 191 | // if it's the same as the old one, skip it | 
|---|
| [e63edb] | 192 | if (olditer == iter) | 
|---|
| [98d166] | 193 | continue; | 
|---|
| [e63edb] | 194 | else | 
|---|
|  | 195 | olditer = iter; | 
|---|
| [98d166] | 196 | // if it's a new key, check if every element has the right number of counts | 
|---|
|  | 197 | Extractors::elementcounts_t::const_iterator countiter = counts_per_charge.begin(); | 
|---|
|  | 198 | for (; countiter != counts_per_charge.end(); ++countiter) | 
|---|
|  | 199 | if (!(*iter).hasTimesAtomicNumber( | 
|---|
|  | 200 | static_cast<size_t>(countiter->first), | 
|---|
|  | 201 | static_cast<size_t>(countiter->second)) | 
|---|
|  | 202 | ) | 
|---|
|  | 203 | break; | 
|---|
|  | 204 | if( countiter == counts_per_charge.end()) | 
|---|
|  | 205 | return *iter; | 
|---|
|  | 206 | } | 
|---|
|  | 207 | return HomologyGraph(); | 
|---|
|  | 208 | } | 
|---|
|  | 209 |  | 
|---|
|  | 210 | SerializablePotential::ParticleTypes_t PotentialTrainer::getNumbersFromElements( | 
|---|
|  | 211 | const std::vector<const element *> &fragment) | 
|---|
|  | 212 | { | 
|---|
|  | 213 | SerializablePotential::ParticleTypes_t fragmentnumbers; | 
|---|
|  | 214 | std::transform(fragment.begin(), fragment.end(), std::back_inserter(fragmentnumbers), | 
|---|
|  | 215 | boost::bind(&element::getAtomicNumber, _1)); | 
|---|
|  | 216 | return fragmentnumbers; | 
|---|
|  | 217 | } | 
|---|