/***************************************************************************
**
**  This file is part of geopsynr.
**
**  geopsynr 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 3 of the License, or
**  (at your option) any later version.
**
**  geopsynr 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 Foobar.  If not, see <http://www.gnu.org/licenses/>
**
**  See http://www.geopsy.org for more information.
**
**  Created: 2007-08-28
**  Copyright: 2007-2019
**    Marc Wathelet
**    Marc Wathelet (LGIT, Grenoble, France)
**
***************************************************************************/

#include <DinverCore.h>
#include "StackWeights.h"
#include "ShotRecord.h"

/*!
  \class StackWeights StackWeights.h
  \brief Brief description of class still missing

  There n-1 parameters if there are n shots. There values are from 0 to 1 with
  a condition that values must increase. There in fact represent the cumulative
  weights. Effective weights are calculated by subtracting two adjacent
  parameters.
*/

/*!
  Description of constructor still missing
*/
StackWeights::StackWeights(QList<ShotRecord *> shots)
{
  TRACE;
  _shots=shots;
  setParameters();
}

/*!
  Initialize parameters for optimization
*/
void StackWeights::setParameters()
{
  TRACE;
  RealSpace& ps=parameterSpace();
  int nShots=_shots.count();
  QString str("w%1");
  Parameter * w1, *w2=ps.addParameter(str.arg(0), "", 0.0, 1.0, ParameterGrid::Linear, 0);
  for(int i=1; i<nShots-1; i++ ) {
    w1=w2;
    w2=ps.addParameter(str.arg(i), "", 0.0, 1.0, ParameterGrid::Linear, 0);
    ps.addCondition(new SimpleCondition(w1, SimpleCondition::LessThan, 1.0, w2, 0.0) );
  }
}

/*!
  Set current parameter values to uniform weights. Use stack()
  right after to get signal stacked.
*/
void StackWeights::setUniformWeights()
{
  TRACE;
  int nShots=_shots.count();
  double v=1.0/nShots;
  for(int i=1;i < nShots;i++ ) {
    parameterSpace().parameter(i-1)->setRealValue(i*v);
  }
}

/*!
  Set current parameter values to arbitrary weights. Use stack()
  right after to get signal stacked. \a gridWeights is usually
  obtained after an inversion (best model).
*/
void StackWeights::setWeights(const int * gridWeights)
{
  TRACE;
  int nShots=_shots.count();
  for(int i=0; i < nShots-1; i++ ) {
    parameterSpace().parameter(i)->setGridValue(gridWeights[i] );
  }
}
/*!
  Calculate effective weights from the conditional parameterization
*/
void StackWeights::param2weights(double * weights)
{
  TRACE;
  int nShots=_shots.count();
  for(int i=0; i<nShots-1; i++ ) {
    weights[i]=parameterSpace().parameter(i)->realValue();
  }
  weights[nShots-1]=1.0-weights[nShots-2];
  for(int i=nShots-2; i>0; i-- ) {
    weights[i]-=weights[i-1];
  }
}

AbstractForward * StackWeights::clone() const
{
  StackWeights * c=new StackWeights(_shots);
  c->setParameters();
  return c;
}

double StackWeights::misfit(bool& )
{
  TRACE;
  int nShots=_shots.count();
  double weights[nShots];
  param2weights(weights);
  double sum=0.0;
  Signal * sig=_shots.first()->receivers()->at(_receiverIndex);
  TimeRange globalTw=_globalTimeLimits.absoluteRange(sig);
  TimeRange signalTw=_signalTimeLimits.absoluteRange(sig);
  int nSamples=sig->nSamples();
  const DateTime& startTime=sig->startTime();
  double samplingFrequency=1.0/sig->samplingPeriod();
  int iGlobalStart=qRound((startTime.secondsTo(globalTw.start()))*samplingFrequency);
  int iGlobalEnd=qRound((startTime.secondsTo(globalTw.end()))*samplingFrequency);
  if(iGlobalStart<0) iGlobalStart=0;
  if(iGlobalStart>nSamples) iGlobalStart=nSamples;
  if(iGlobalEnd<0) iGlobalEnd=0;
  if(iGlobalEnd>nSamples) iGlobalEnd=nSamples;
  int iStart=qRound((startTime.secondsTo(signalTw.start()))*samplingFrequency);
  int iEnd=qRound((startTime.secondsTo(signalTw.end()))*samplingFrequency);
  if(iStart<iGlobalStart) iStart=iGlobalStart;
  if(iStart>iGlobalEnd) iStart=iGlobalEnd;
  if(iEnd<iGlobalStart) iEnd=iGlobalStart;
  if(iEnd>iGlobalEnd) iEnd=iGlobalEnd;
  double stack[nSamples];
  // Reset stack vector
  for(int i=iGlobalStart; i<iStart; i++) {
    stack[i]=0.0;
  }
  for(int i=iEnd; i<iGlobalEnd; i++) {
    stack[i]=0.0;
  }
  // Stack
  for(int iShot=0; iShot<nShots; iShot++) {
    const Signal * sig=_shots.at(iShot)->receivers()->at(_receiverIndex);
    CONST_LOCK_SAMPLES(double, samp, sig)
      double w=weights[iShot];
      for(int i=iGlobalStart; i<iStart; i++) {
        stack[i]+=w*samp[i];
      }
      for(int i=iEnd; i<iGlobalEnd; i++) {
        stack[i]+=w*samp[i];
      }
    UNLOCK_SAMPLES(sig)
  }
  // compute stack total energy
  for(int i=iGlobalStart; i<iStart; i++) {
    sum+=stack[i]*stack[i];
  }
  for(int i=iEnd; i<iGlobalEnd; i++) {
    sum+=stack[i]*stack[i];
  }
  return sum;
}

/*!
  Stacks shots into \a results using the current weights.

  \sa setUniformWeights() or setWeights()
*/
void StackWeights::stack(SubSignalPool& results)
{
  TRACE;
  int nShots=_shots.count();
  int nSamples=_shots.at(0)->receivers()->first()->nSamples();
  double weights[nShots];
  param2weights(weights);
  for(int i=0; i<nShots; i++) {
    App::log(tr("Best stack weight for shot %1=%2\n")
             .arg(_shots.at(i)->receivers()->name()).arg(weights[i]));
  }
  Signal * resSig=0;
  ASSERT(_receiverIndex<=results.count());
  if(_receiverIndex==results.count()) {
    resSig=new Signal(*_shots.at(0)->receivers()->at(_receiverIndex));
    results.addSignal(resSig);
  } else {
    resSig=results.at(_receiverIndex);
  }
  resSig->initValues(0.0, 0, nSamples);
  LOCK_SAMPLES(double, resSamp, resSig)
    for(int iShot=0; iShot < nShots; iShot++ ) {
      const Signal * sig=_shots.at(iShot)->receivers()->at(_receiverIndex);
      CONST_LOCK_SAMPLES(double, samp, sig)
        double w=weights[iShot];
        for(int i=0; i < nSamples; i++ ) {
          resSamp[i] += w * samp[i];
        }
      UNLOCK_SAMPLES(sig)
    }
  UNLOCK_SAMPLES(resSig)
}
