| 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/RegistrySerializer.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 unsigned int _maxiterations, | 
|---|
| 74 | const double _threshold, | 
|---|
| 75 | const unsigned int _best_of_howmany) const | 
|---|
| 76 | { | 
|---|
| 77 | // fit potential | 
|---|
| 78 | CompoundPotential compound(_graph); | 
|---|
| 79 | FunctionModel &model = assert_cast<FunctionModel &>(compound); | 
|---|
| 80 |  | 
|---|
| 81 | if (compound.begin() == compound.end()) { | 
|---|
| 82 | ELOG(1, "Could not find any suitable potentials for the compound potential."); | 
|---|
| 83 | return false; | 
|---|
| 84 | } | 
|---|
| 85 |  | 
|---|
| 86 | /******************** TRAINING ********************/ | 
|---|
| 87 | // fit potential | 
|---|
| 88 | FunctionModel::parameters_t bestparams(model.getParameterDimension(), 0.); | 
|---|
| 89 | { | 
|---|
| 90 | // Afterwards we go through all of this type and gather the distance and the energy value | 
|---|
| 91 | TrainingData data(model.getSpecificFilter()); | 
|---|
| 92 | data(_homologies.getHomologousGraphs(_graph)); | 
|---|
| 93 |  | 
|---|
| 94 | // check data | 
|---|
| 95 | const TrainingData::FilteredInputVector_t &inputs = data.getTrainingInputs(); | 
|---|
| 96 | for (TrainingData::FilteredInputVector_t::const_iterator iter = inputs.begin(); | 
|---|
| 97 | iter != inputs.end(); ++iter) | 
|---|
| 98 | if (((*iter).empty()) || ((*iter).front().empty())) { | 
|---|
| 99 | ELOG(1, "At least one of the training inputs is empty! Correct fragment and potential charges selected?"); | 
|---|
| 100 | return false; | 
|---|
| 101 | } | 
|---|
| 102 | const TrainingData::OutputVector_t &outputs = data.getTrainingOutputs(); | 
|---|
| 103 | for (TrainingData::OutputVector_t::const_iterator iter = outputs.begin(); | 
|---|
| 104 | iter != outputs.end(); ++iter) | 
|---|
| 105 | if ((*iter).empty()) { | 
|---|
| 106 | ELOG(1, "At least one of the training outputs is empty! Correct fragment and potential charges selected?"); | 
|---|
| 107 | return false; | 
|---|
| 108 | } | 
|---|
| 109 |  | 
|---|
| 110 | // print distances and energies if desired for debugging | 
|---|
| 111 | if (!data.getTrainingInputs().empty()) { | 
|---|
| 112 | // print which distance is which | 
|---|
| 113 | size_t counter=1; | 
|---|
| 114 | if (DoLog(3)) { | 
|---|
| 115 | const FunctionModel::arguments_t &inputs = data.getAllArguments()[0]; | 
|---|
| 116 | for (FunctionModel::arguments_t::const_iterator iter = inputs.begin(); | 
|---|
| 117 | iter != inputs.end(); ++iter) { | 
|---|
| 118 | const argument_t &arg = *iter; | 
|---|
| 119 | LOG(3, "DEBUG: distance " << counter++ << " is between (#" | 
|---|
| 120 | << arg.indices.first << "c" << arg.types.first << "," | 
|---|
| 121 | << arg.indices.second << "c" << arg.types.second << ")."); | 
|---|
| 122 | } | 
|---|
| 123 | } | 
|---|
| 124 |  | 
|---|
| 125 | // print table | 
|---|
| 126 | if (_trainingfile.string().empty()) { | 
|---|
| 127 | LOG(3, "DEBUG: I gathered the following training data:\n" << | 
|---|
| 128 | _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable())); | 
|---|
| 129 | } else { | 
|---|
| 130 | std::ofstream trainingstream(_trainingfile.string().c_str()); | 
|---|
| 131 | if (trainingstream.good()) { | 
|---|
| 132 | LOG(3, "DEBUG: Writing training data to file " << | 
|---|
| 133 | _trainingfile.string() << "."); | 
|---|
| 134 | trainingstream << _detail::writeDistanceEnergyTable(data.getDistanceEnergyTable()); | 
|---|
| 135 | } | 
|---|
| 136 | trainingstream.close(); | 
|---|
| 137 | } | 
|---|
| 138 | } | 
|---|
| 139 |  | 
|---|
| 140 | if ((_threshold < 1.) && (_best_of_howmany)) | 
|---|
| 141 | ELOG(2, "threshold parameter always overrules max_runs, both are specified."); | 
|---|
| 142 | // now perform the function approximation by optimizing the model function | 
|---|
| 143 | FunctionApproximation approximator(data, model, _threshold, _maxiterations); | 
|---|
| 144 | if (model.isBoxConstraint() && approximator.checkParameterDerivatives()) { | 
|---|
| 145 | double l2error = std::numeric_limits<double>::max(); | 
|---|
| 146 | // seed with current time | 
|---|
| 147 | srand((unsigned)time(0)); | 
|---|
| 148 | unsigned int runs=0; | 
|---|
| 149 | // threshold overrules max_runs | 
|---|
| 150 | const double threshold = _threshold; | 
|---|
| 151 | const unsigned int max_runs = (threshold >= 1.) ? _best_of_howmany : 1; | 
|---|
| 152 | LOG(1, "INFO: Maximum runs is " << max_runs << " and threshold set to " << threshold << "."); | 
|---|
| 153 | do { | 
|---|
| 154 | // generate new random initial parameter values | 
|---|
| 155 | model.setParametersToRandomInitialValues(data); | 
|---|
| 156 | LOG(1, "INFO: Initial parameters of run " << runs << " are " | 
|---|
| 157 | << model.getParameters() << "."); | 
|---|
| 158 | approximator(FunctionApproximation::ParameterDerivative); | 
|---|
| 159 | LOG(1, "INFO: Final parameters of run " << runs << " are " | 
|---|
| 160 | << model.getParameters() << "."); | 
|---|
| 161 | const double new_l2error = data.getL2Error(model); | 
|---|
| 162 | if (new_l2error < l2error) { | 
|---|
| 163 | // store currently best parameters | 
|---|
| 164 | l2error = new_l2error; | 
|---|
| 165 | bestparams = model.getParameters(); | 
|---|
| 166 | LOG(1, "STATUS: New fit from run " << runs | 
|---|
| 167 | << " has better error of " << l2error << "."); | 
|---|
| 168 | } | 
|---|
| 169 | } while (( ++runs < max_runs) || (l2error > threshold)); | 
|---|
| 170 | // reset parameters from best fit | 
|---|
| 171 | model.setParameters(bestparams); | 
|---|
| 172 | LOG(1, "INFO: Best parameters with L2 error of " | 
|---|
| 173 | << l2error << " are " << model.getParameters() << "."); | 
|---|
| 174 | } else { | 
|---|
| 175 | return false; | 
|---|
| 176 | } | 
|---|
| 177 |  | 
|---|
| 178 | // create a map of each fragment with error. | 
|---|
| 179 | HomologyContainer::range_t fragmentrange = _homologies.getHomologousGraphs(_graph); | 
|---|
| 180 | TrainingData::L2ErrorConfigurationIndexMap_t WorseFragmentMap = | 
|---|
| 181 | data.getWorstFragmentMap(model, fragmentrange); | 
|---|
| 182 | LOG(0, "RESULT: WorstFragmentMap " << WorseFragmentMap << "."); | 
|---|
| 183 |  | 
|---|
| 184 | } | 
|---|
| 185 |  | 
|---|
| 186 | return true; | 
|---|
| 187 | } | 
|---|
| 188 |  | 
|---|
| 189 | HomologyGraph PotentialTrainer::getFirstGraphwithSpecifiedElements( | 
|---|
| 190 | const HomologyContainer &homologies, | 
|---|
| 191 | const SerializablePotential::ParticleTypes_t &types) | 
|---|
| 192 | { | 
|---|
| 193 | ASSERT( !types.empty(), | 
|---|
| 194 | "getFirstGraphwithSpecifiedElements() - charges is empty?"); | 
|---|
| 195 |  | 
|---|
| 196 | // convert into count map | 
|---|
| 197 | Extractors::elementcounts_t counts_per_element = | 
|---|
| 198 | Extractors::_detail::getElementCounts(types); | 
|---|
| 199 | ASSERT( !counts_per_element.empty(), | 
|---|
| 200 | "getFirstGraphwithSpecifiedElements() - element counts are empty?"); | 
|---|
| 201 | LOG(1, "DEBUG: counts_per_element is " << counts_per_element << "."); | 
|---|
| 202 | // we want to check each (unique) key only once | 
|---|
| 203 | HomologyContainer::const_key_iterator olditer = homologies.key_end(); | 
|---|
| 204 | for (HomologyContainer::const_key_iterator iter = | 
|---|
| 205 | homologies.key_begin(); iter != homologies.key_end(); | 
|---|
| 206 | iter = homologies.getNextKey(iter)) { | 
|---|
| 207 | // if it's the same as the old one, skip it | 
|---|
| 208 | if (olditer == iter) | 
|---|
| 209 | continue; | 
|---|
| 210 | else | 
|---|
| 211 | olditer = iter; | 
|---|
| 212 | // check whether we have the same set of atomic numbers | 
|---|
| 213 | const HomologyGraph::nodes_t &nodes = (*iter).getNodes(); | 
|---|
| 214 | Extractors::elementcounts_t nodes_counts_per_element; | 
|---|
| 215 | for (HomologyGraph::nodes_t::const_iterator nodeiter = nodes.begin(); | 
|---|
| 216 | nodeiter != nodes.end(); ++nodeiter) { | 
|---|
| 217 | const Extractors::element_t elem = nodeiter->first.getAtomicNumber(); | 
|---|
| 218 | const std::pair<Extractors::elementcounts_t::iterator, bool> inserter = | 
|---|
| 219 | nodes_counts_per_element.insert( std::make_pair(elem, (Extractors::count_t)nodeiter->second ) ); | 
|---|
| 220 | if (!inserter.second) | 
|---|
| 221 | inserter.first->second += (Extractors::count_t)nodeiter->second; | 
|---|
| 222 | } | 
|---|
| 223 | LOG(1, "DEBUG: Node (" << *iter << ")'s counts_per_element is " << nodes_counts_per_element << "."); | 
|---|
| 224 | if (counts_per_element == nodes_counts_per_element) | 
|---|
| 225 | return *iter; | 
|---|
| 226 | } | 
|---|
| 227 | return HomologyGraph(); | 
|---|
| 228 | } | 
|---|
| 229 |  | 
|---|
| 230 | SerializablePotential::ParticleTypes_t PotentialTrainer::getNumbersFromElements( | 
|---|
| 231 | const std::vector<const element *> &fragment) | 
|---|
| 232 | { | 
|---|
| 233 | SerializablePotential::ParticleTypes_t fragmentnumbers; | 
|---|
| 234 | std::transform(fragment.begin(), fragment.end(), std::back_inserter(fragmentnumbers), | 
|---|
| 235 | boost::bind(&element::getAtomicNumber, _1)); | 
|---|
| 236 | return fragmentnumbers; | 
|---|
| 237 | } | 
|---|