/*
 * Project: MoleCuilder
 * Description: creates and alters molecular systems
 * Copyright (C)  2012 University of Bonn. All rights reserved.
 * Please see the COPYING file or "Copyright notice" in builder.cpp for details.
 * 
 *
 *   This file is part of MoleCuilder.
 *
 *    MoleCuilder is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    MoleCuilder is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with MoleCuilder.  If not, see . 
 */
/*
 * LevMartester.cpp
 *
 *  Created on: Sep 27, 2012
 *      Author: heber
 */
// include config.h
#ifdef HAVE_CONFIG_H
#include 
#endif
#include "CodePatterns/MemDebug.hpp"
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include "CodePatterns/Assert.hpp"
#include "CodePatterns/Log.hpp"
#include "LinearAlgebra/Vector.hpp"
#include "Fragmentation/Homology/HomologyContainer.hpp"
#include "Fragmentation/SetValues/Fragment.hpp"
#include "FunctionApproximation/FunctionApproximation.hpp"
#include "FunctionApproximation/FunctionModel.hpp"
#include "Potentials/Specifics/PairPotential_Morse.hpp"
namespace po = boost::program_options;
HomologyGraph getFirstGraphWithTwoCarbons(const HomologyContainer &homologies)
{
  FragmentNode SaturatedCarbon(6,4); // carbon has atomic number 6 and should have 4 bonds for C2H6
  for (HomologyContainer::container_t::const_iterator iter =
      homologies.begin(); iter != homologies.end(); ++iter) {
    if (iter->first.hasNode(SaturatedCarbon,2))
      return iter->first;
  }
  return HomologyGraph();
}
int main(int argc, char **argv)
{
  std::cout << "Hello to the World from LevMar!" << std::endl;
  // load homology file
  po::options_description desc("Allowed options");
  desc.add_options()
      ("help", "produce help message")
      ("homology-file", po::value< boost::filesystem::path >(), "homology file to parse")
  ;
  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);
  if (vm.count("help")) {
      std::cout << desc << "\n";
      return 1;
  }
  boost::filesystem::path homology_file;
  if (vm.count("homology-file")) {
    homology_file = vm["homology-file"].as();
    LOG(1, "INFO: Parsing " << homology_file.string() << ".");
  } else {
    LOG(0, "homology-file level was not set.");
  }
  HomologyContainer homologies;
  if (boost::filesystem::exists(homology_file)) {
    std::ifstream returnstream(homology_file.string().c_str());
    if (returnstream.good()) {
      boost::archive::text_iarchive ia(returnstream);
      ia >> homologies;
    } else {
      ELOG(2, "Failed to parse from " << homology_file.string() << ".");
    }
    returnstream.close();
  } else {
    ELOG(0, homology_file << " does not exist.");
  }
  // first we try to look into the HomologyContainer
  LOG(1, "INFO: Listing all present homologies ...");
  for (HomologyContainer::container_t::const_iterator iter =
      homologies.begin(); iter != homologies.end(); ++iter) {
    LOG(1, "INFO: graph " << iter->first << " has Fragment "
        << iter->second.first << " and associated energy " << iter->second.second << ".");
  }
  // then we ought to pick the right HomologyGraph ...
  const HomologyGraph graph = getFirstGraphWithTwoCarbons(homologies);
  LOG(1, "First representative graph containing two saturated carbons is " << graph << ".");
  // Afterwards we go through all of this type and gather the distance and the energy value
  typedef std::pair<
      FunctionApproximation::inputs_t,
      FunctionApproximation::outputs_t> InputOutputVector_t;
  InputOutputVector_t DistanceEnergyVector;
  std::pair range =
      homologies.getHomologousGraphs(graph);
  for (HomologyContainer::const_iterator iter = range.first; iter != range.second; ++iter) {
    // get distance out of Fragment
    const Fragment &fragment = iter->second.first;
    const Fragment::charges_t charges = fragment.getCharges();
    const Fragment::positions_t positions = fragment.getPositions();
    std::vector< std::pair > DistanceVectors;
    for (Fragment::charges_t::const_iterator chargeiter = charges.begin();
        chargeiter != charges.end(); ++chargeiter) {
      if (*chargeiter == 6) {
        Fragment::positions_t::const_iterator positer = positions.begin();
        const size_t steps = std::distance(charges.begin(), chargeiter);
        std::advance(positer, steps);
        DistanceVectors.push_back(
            std::make_pair(Vector((*positer)[0], (*positer)[1], (*positer)[2]),
                steps));
      }
    }
    if (DistanceVectors.size() == (size_t)2) {
      argument_t arg;
      arg.indices.first = DistanceVectors[0].second;
      arg.indices.second = DistanceVectors[1].second;
      arg.distance = DistanceVectors[0].first.distance(DistanceVectors[1].first);
      const double energy = iter->second.second;
      DistanceEnergyVector.first.push_back( FunctionModel::arguments_t(1,arg) );
      DistanceEnergyVector.second.push_back( FunctionModel::results_t(1,energy) );
    } else {
      ELOG(2, "main() - found not exactly two carbon atoms in fragment "
          << fragment << ".");
    }
  }
  // print training data for debugging
  {
    LOG(1, "INFO: I gathered the following (" << DistanceEnergyVector.first.size()
        << "," << DistanceEnergyVector.second.size() << ") data pairs: ");
    FunctionApproximation::inputs_t::const_iterator initer = DistanceEnergyVector.first.begin();
    FunctionApproximation::outputs_t::const_iterator outiter = DistanceEnergyVector.second.begin();
    for (; initer != DistanceEnergyVector.first.end(); ++initer, ++outiter) {
      LOG(1, "INFO: (" << (*initer)[0].indices.first << "," << (*initer)[0].indices.second
          << ") " << (*initer)[0].distance << " with energy " << *outiter);
    }
  }
  // NOTICE that distance are in bohrradi as they come from MPQC!
  // now perform the function approximation by optimizing the model function
  PairPotential_Morse morse(1., 2.9, 0.5, -80.);
  FunctionModel &model = morse;
  FunctionApproximation approximator(1, 1, model);
  approximator.setTrainingData(DistanceEnergyVector.first,DistanceEnergyVector.second);
  approximator();
  const FunctionModel::parameters_t params = model.getParameters();
  LOG(0, "RESULT: Best parameters are " << params[0] << ","
      << params[1] << "," << params[2] << " and " << params[3] << ".");
  return 0;
}