/*
 *  Open BEAGLE
 *  Copyright (C) 2001-2007 by Christian Gagne and Marc Parizeau
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *  Contact:
 *  Laboratoire de Vision et Systemes Numeriques
 *  Departement de genie electrique et de genie informatique
 *  Universite Laval, Quebec, Canada, G1K 7P4
 *  http://vision.gel.ulaval.ca
 *
 */

/*!
 *  \file   beagle/src/OversizeOp.cpp
 *  \brief  Source code of class OversizeOp.
 *  \author Christian Gagne
 *  \author Marc Parizeau
 *  $Revision: 1.10.2.2 $
 *  $Date: 2007/08/21 02:07:24 $
 */

#include "beagle/Beagle.hpp"

#include <cmath>
#include <algorithm>

using namespace std;
using namespace Beagle;


/*!
 *  \brief Build oversize replacement strategy operator.
 *  \param inOversizeRatioName Oversize ratio parameter name used in the register.
 *  \param inName Name of the oversize operator.
 */
OversizeOp::OversizeOp(Beagle::string inOversizeRatioName, Beagle::string inName) :
  ReplacementStrategyOp(inName),
  mOversizeRatioName(inOversizeRatioName)
{ }


/*!
 *  \brief Initialize the operator.
 *  \param ioSystem Reference to the evolutionary system.
 */
void OversizeOp::initialize(System& ioSystem)
{
  Beagle_StackTraceBeginM();
  ReplacementStrategyOp::initialize(ioSystem);

  if(ioSystem.getRegister().isRegistered(mOversizeRatioName)) {
    mOversizeRatio = castHandleT<Float>(ioSystem.getRegister().getEntry(mOversizeRatioName));
  } else {
    mOversizeRatio = new Float((float)7.0);
    Register::Description lDescription(
      "Oversizing ratio",
      "Float",
      "7.0",
      string("Oversizing ratio, which mean how much bigger is the child population from ") +
      string("the parent population.")
    );
    ioSystem.getRegister().addEntry(mOversizeRatioName, mOversizeRatio, lDescription);
  }
  Beagle_StackTraceEndM("void OversizeOp::initialize(System& ioSystem)");
}


/*!
 *  \brief Apply the oversize replacement strategy operation on a deme.
 *  \param ioDeme Reference to the deme on which the operation takes place.
 *  \param ioContext Evolutionary context of the operation.
 */
void OversizeOp::operate(Deme& ioDeme, Context& ioContext)
{
  Beagle_StackTraceBeginM();
  Beagle_NonNullPointerAssertM(getRootNode());
  Beagle_ValidateParameterM
  (mOversizeRatio->getWrappedValue() >= 1.0
   || mOversizeRatio->getWrappedValue() == -1.0,
   mOversizeRatioName,
   "The oversize ratio must be greater than or equal to 1.0, or equal to -1.0.");

  Beagle_LogTraceM(
      ioContext.getSystem().getLogger(),
      "replacement-strategy", "Beagle::OversizeOp",
      string("Using oversize replacement strategy to process the ")+
      uint2ordinal(ioContext.getDemeIndex()+1)+" deme"
  );
  Beagle_LogObjectM(
      ioContext.getSystem().getLogger(),
      Logger::eTrace,
      "replacement-strategy", "Beagle::OversizeOp",
      (*this)
  );

  RouletteT<unsigned int> lRoulette;
  buildRoulette(lRoulette, ioContext);

  // Calculate the increase in size (lambda)
  float lRatio = mOversizeRatio->getWrappedValue();
  unsigned int lLambda;
  if (lRatio == -1.0) {
    // Using special ratio of -1.0 ensures deme grows to size specified in 'ec.pop.size'
    if (!ioContext.getSystem().getRegister().isRegistered("ec.pop.size")) {
      throw Beagle_RunTimeExceptionM(getName()+" requires register variable 'ec.pop.size'");
    }
    UIntArray::Handle lPopSize = castHandleT<UIntArray>
                                 (ioContext.getSystem().getRegister().getEntry("ec.pop.size"));
    unsigned int lSpecifiedDemeSize = (*lPopSize)[ioContext.getDemeIndex()];
    unsigned int lCurrentDemeSize = ioDeme.size();
    if (lSpecifiedDemeSize < lCurrentDemeSize) {
      throw Beagle_RunTimeExceptionM
      (std::string("For the ")+uint2ordinal(ioContext.getDemeIndex()+1)+
       " deme, the size specified in 'ec.pop.size' ("+uint2str(lSpecifiedDemeSize)+
       ") is less than the current deme size ("+uint2str(lCurrentDemeSize)+
       ").  "+getName()+" can only increase the size of the deme.  Consider using DecimateOp "+
       "if you wish to decrease the size of the deme");
    }
    lLambda = lSpecifiedDemeSize - lCurrentDemeSize;
  } else {
    // Using ratio to scale the deme's population
    lLambda = (unsigned int)ceil((lRatio-1.0)*float(ioDeme.size()));
  }
  Beagle_LogTraceM(
      ioContext.getSystem().getLogger(),
      "replacement-strategy", "Beagle::OversizeOp",
      string("Population will be increased in size by ")+uint2str(lLambda)+" individuals"
  );

  // Create the new individuals.
  Individual::Bag lOffsprings;
  for(unsigned int i=0; i<lLambda; ++i) {
    unsigned int lIndexBreeder = lRoulette.select(ioContext.getSystem().getRandomizer());
    BreederNode::Handle lSelectedBreeder=getRootNode();
    for(unsigned int j=0; j<lIndexBreeder; ++j)
      lSelectedBreeder=lSelectedBreeder->getNextSibling();
    Beagle_NonNullPointerAssertM(lSelectedBreeder);
    Beagle_NonNullPointerAssertM(lSelectedBreeder->getBreederOp());
    Individual::Handle lBredIndiv =
        lSelectedBreeder->getBreederOp()->breed(ioDeme, lSelectedBreeder->getFirstChild(), ioContext);
    Beagle_NonNullPointerAssertM(lBredIndiv);
    lOffsprings.push_back(lBredIndiv);
  }

  // Add the new individuals into the deme.
  ioDeme.insert(ioDeme.end(), lOffsprings.begin(), lOffsprings.end());
  Beagle_LogDetailedM(
      ioContext.getSystem().getLogger(),
      "replacement-strategy", "Beagle::OversizeOp",
      string("There are now ")+uint2str(ioDeme.size())+" individuals in the "+
      uint2ordinal(ioContext.getDemeIndex()+1)+" deme"
  );
  Beagle_StackTraceEndM("void OversizeOp::operate(Deme& ioDeme, Context& ioContext)");
}


/*!
 *  \brief Read a OversizeOp operator for XML tree.
 *  \param inIter XML iterator to use to read OversizeOp operator.
 *  \param inOpMap Operator map to use to read OversizeOp operator.
 */
void OversizeOp::readWithMap(PACC::XML::ConstIterator inIter, OperatorMap& inOpMap)
{
  Beagle_StackTraceBeginM();
  if((inIter->getType()!=PACC::XML::eData) || (inIter->getValue()!=getName().c_str())) {
    std::ostringstream lOSS;
    lOSS << "tag <" << getName() << "> expected!" << std::flush;
    throw Beagle_IOExceptionNodeM(*inIter, lOSS.str().c_str());
  }
  string lOversizeRatioReadName = inIter->getAttribute("ratio_name").c_str();
  if(lOversizeRatioReadName.empty() == false) mOversizeRatioName = lOversizeRatioReadName;

  ReplacementStrategyOp::readWithMap(inIter, inOpMap);
  Beagle_StackTraceEndM("void OversizeOp::readWithMap(PACC::XML::ConstIterator inIter, OperatorMap& inOpMap)");
}


/*!
 *  \brief Write OversizeOp operator into XML streamer.
 *  \param ioStreamer XML streamer to write OversizeOp operator into.
 *  \param inIndent Whether XML output should be indented.
 */
void OversizeOp::write(PACC::XML::Streamer& ioStreamer, bool inIndent) const
{
  Beagle_StackTraceBeginM();
  ioStreamer.openTag(getName().c_str(), inIndent);
  ioStreamer.insertAttribute("ratio_name", mOversizeRatioName);
  if(getRootNode() != NULL) getRootNode()->write(ioStreamer, inIndent);
  ioStreamer.closeTag();
  Beagle_StackTraceEndM("void OversizeOp::write(PACC::XML::Streamer& ioStreamer, bool inIndent) const");
}
