/*
 * 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"
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();
}
/* Meyer's (reformulated) problem, minimum at (2.48, 6.18, 3.45) */
void meyer(double *p, double *x, int m, int n, void *data)
{
register int i;
double ui;
        for(i=0; i(), "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::vector< std::pair > DistanceEnergyVector_t;
  DistanceEnergyVector_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< Vector > 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(Vector((*positer)[0], (*positer)[1], (*positer)[2]));
      }
    }
    ASSERT( DistanceVectors.size() == (size_t)2,
        "main() - found not exactly two carbon atoms in fragment.");
    const double distance = DistanceVectors[0].distance(DistanceVectors[1]);
    const double energy = iter->second.second;
    DistanceEnergyVector.push_back( std::make_pair(distance, energy) );
  }
  LOG(1, "INFO: I gathered the following " << DistanceEnergyVector.size() << " data pairs: ");
  for (DistanceEnergyVector_t::const_iterator dataiter = DistanceEnergyVector.begin();
      dataiter != DistanceEnergyVector.end(); ++dataiter) {
    LOG(1, "INFO: " << dataiter->first << " with energy " << dataiter->second);
  }
  // NOTICE that distance are in bohrradi as they come from MPQC!
  // let levmar optimize
  register int i, j;
  int ret;
  double p[5], // 5 is max(2, 3, 5)
             x[16]; // 16 is max(2, 3, 5, 6, 16)
  int m, n;
  double opts[LM_OPTS_SZ], info[LM_INFO_SZ];
  opts[0]=LM_INIT_MU; opts[1]=1E-15; opts[2]=1E-15; opts[3]=1E-20;
  opts[4]= LM_DIFF_DELTA; // relevant only if the Jacobian is approximated using finite differences; specifies forward differencing
  //opts[4]=-LM_DIFF_DELTA; // specifies central differencing to approximate Jacobian; more accurate but more expensive to compute!
  m=3; n=16;
  p[0]=8.85; p[1]=4.0; p[2]=2.5;
  x[0]=34.780;        x[1]=28.610; x[2]=23.650; x[3]=19.630;
  x[4]=16.370;        x[5]=13.720; x[6]=11.540; x[7]=9.744;
  x[8]=8.261; x[9]=7.030; x[10]=6.005; x[11]=5.147;
  x[12]=4.427;        x[13]=3.820; x[14]=3.307; x[15]=2.872;
  ret=dlevmar_der(meyer, jacmeyer, p, x, m, n, 1000, opts, info, NULL, NULL, NULL); // with analytic Jacobian
 { double *work, *covar;
  work=(double *)malloc((LM_DIF_WORKSZ(m, n)+m*m)*sizeof(double));
  if(!work){
      fprintf(stderr, "memory allocation request failed in main()\n");
    exit(1);
  }
  covar=work+LM_DIF_WORKSZ(m, n);
  ret=dlevmar_dif(meyer, p, x, m, n, 1000, opts, info, work, covar, NULL); // no Jacobian, caller allocates work memory, covariance estimated
  printf("Covariance of the fit:\n");
  for(i=0; i