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