/* ----------------------------------------------------------------------------

Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007.

A. Ronald Gallant

This program 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.

This program 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 this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

-----------------------------------------------------------------------------*/

#include "libsmm.h"
using namespace std;  
using namespace scl;
using namespace libsmm;

REAL libsmm::cachemgr::evaluate(const realmat& rho, realmat& stats)
{
  REAL v;

  /*
  Setting the parameter before checking support is intentional.
  Do not change it.  SNP will not work if you do.  Support has 
  to be checked even though mcmc has already done so because of 
  moving rho to a grid.
  */

  model.set_rho(rho);

  realmat sim;

  bool success = ( model.support(rho) && model.gen_sim(sim,stats) );

  if (success) {
    v = obj(rho,sim,stats);
    if (!IsFinite(v)) {
      v = REAL_MAX;
    }
  }
  else {
    v = REAL_MAX;
    stats.resize(model.len_stats(),1,0.0);
  }

  return v;
}

den_val libsmm::cachemgr::operator()(const realmat& rho, realmat& stats)
{
  REAL v;

  if (cache_size <= 10 && miss >= 10) {
    
    v = evaluate(rho, stats);

  }
  else {

    map<realmat,val,realmat_cmp>::const_iterator itr=past_values.find(rho);
  
    bool previous_exists = (itr == past_values.end() ? false : true);
  
    if (previous_exists) { 
      ++hit;
      val previous = itr->second;
      v = previous.v;
      stats = previous.stats;
    }
    else {
      ++miss;
      v = evaluate(rho, stats);
      past_values[rho] = val(v,stats);
      cache.push(rho);
      if (cache.size() > cache_size) {
        past_values.erase(cache.front());
        cache.pop();
      }
    }
  }

  if (v == REAL_MAX) {
    return den_val(false, -REAL_MAX);
  }
  else {
    return den_val(true, -v);
  }
}

bool libsmm::cachemgr::set_cache(const realmat& cache_new) 
{
  INTEGER c = cache_new.get_cols();
  return this->set_cache(cache_new,c);
}

bool libsmm::cachemgr::set_cache(const realmat& cache_new, INTEGER limit) 
{
  INTEGER r = model.len_rho(); 
  INTEGER s = model.len_stats();
  INTEGER c = cache_new.get_cols();

  if (c <= 0) {
    warn("Warning, cachemgr, cache read in is null");
    return false;
  }
  
  c = (c<limit) ? c : limit;

  if (cache_new.get_rows() != r+s+1) {
    warn("Warning, cachemgr, cache read in has wrong row length");
    return false;
  }

  realmat rho_grid(r,1);

  val additional;
  additional.stats.resize(s,1);
  
  INTEGER t = 1;

  for (INTEGER i=1; i<=r; i++) {
    rho_grid[i] = cache_new(i,t);
  }

  additional.v = cache_new(r+1,t);

  for (INTEGER i=1; i<=s; i++) {
    additional.stats[i] = cache_new(r+1+i,t);
  }

  /*
  Setting the parameter before checking support is intentional.
  Do not change it.  SNP will not work if you do.  
  */

  model.set_rho(rho_grid);

  if (!model.support(rho_grid)) {
    warn("Warning, cachemgr, cache read in has a rho not in model support");
    return false;
  }
  
  realmat sim;
  realmat stats;

  bool success = model.gen_sim(sim,stats);

  REAL v;

  if (success) {
    v = obj(rho_grid,sim,stats);
    if (!IsFinite(v)) {
      v = REAL_MAX;
    }
  }
  else {
    v = REAL_MAX;
    stats.resize(model.len_stats(),1,0.0);
  }

  bool agree = true;

  if (v == REAL_MAX) {
    if (additional.v != REAL_MAX) agree = false;
  }
  else {
    if ( fabs(v - additional.v) > 1.0e-3*(fabs(v) + EPS) ) agree = false;
    for (INTEGER i=1; i<=s; i++) {
      REAL si = stats[i];
      REAL asi = additional.stats[i];
      if ( fabs(si - asi) > 1.0e-3*(fabs(si) + EPS) ) agree = false;
    }
  }

  if (!agree) {
    warn("Warning, cachemgr, cache read in does not agree with model");
    return false;
  }


  for (INTEGER t=1; t<=c; t++) {
  
    for (INTEGER i=1; i<=r; i++) {
      rho_grid[i] = cache_new(i,t);
    }

    map<realmat,val,realmat_cmp>::const_iterator itr=past_values.find(rho_grid);

    bool previous_exists = (itr == past_values.end() ? false : true);

    if (previous_exists) continue;   // i.e. go to end of loop

    additional.v = cache_new(r+1,t);

    for (INTEGER i=1; i<=s; i++) {
      additional.stats[i] = cache_new(r+1+i,t);
    }

    past_values[rho_grid] = additional;
    cache.push(rho_grid);

    if (cache.size() > cache_size) {
      past_values.erase(cache.front());
      cache.pop();
    }
  }

 return true;
}


void libsmm::cachemgr::get_cache(realmat& cache_sav) const
{
  INTEGER r = model.len_rho();
  INTEGER s = model.len_stats();
  INTEGER c = past_values.size();

  if ( cache_sav.get_rows() != r+s+1 || cache_sav.get_cols() != c ) {
    cache_sav.resize(r+s+1,c);
  }
  
  map<realmat,val,realmat_cmp>::const_iterator itr = past_values.begin();  
  
  INTEGER j=0;
  while ( itr != past_values.end() ) {
    j++;
    for (INTEGER i=1; i<=r; i++) {
      cache_sav.check(i,j) = itr->first[i];
    }
    cache_sav.check(r+1,j) = itr->second.v;
    for (INTEGER i=1; i<=s; i++) {
      cache_sav.check(r+1+i,j) = itr->second.stats[i];
    }
    ++itr;
  }
}

bool libsmm::cachemgr::read_cache(const char* filename) 
{
  ifstream cache_stream(filename);
  if (!cache_stream) return false;

  realmat cache_in; 
  if (vecread(cache_stream,cache_in) == 0) return false;

  return this->set_cache(cache_in);

}

bool libsmm::cachemgr::write_cache(const char* filename) const
{
  if (cache_size <= 10) return true;

  ofstream cache_stream(filename);
  if (!cache_stream) return false;
  
  realmat cache_out;
  this->get_cache(cache_out);
  
  if(vecwrite(cache_stream,cache_out) == 0) {
     return false;
  }
  else { 
    return true; 
  }
}

