/***************************************************************************
**
**  This file is part of ArrayCore.
**
**  ArrayCore 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.
**
**  ArrayCore 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: 2017-11-17
**  Copyright: 2017-2019
**    Marc Wathelet (ISTerre, Grenoble, France)
**
***************************************************************************/

#include "HRFKRayleigh.h"
#include "HRFKRayleighEllipticity.h"
#include "FKCrossSpectrum.h"
#include "FKGridSearch.h"
#include "FKPower.h"
#include "FKSteeringTwoComponentRayleighRadial.h"

namespace ArrayCore {

  /*!
    \class HRFKRayleigh HRFKRayleigh.h
    \brief Rayleigh high resolution FK power

    Rayleigh high resolution FK power versus wavenumber (k) function.
    The cross-spectrum is already projected on the radial direction.
  */

  HRFKRayleigh::HRFKRayleigh(FKCache * gridCache)
    : ConvFKRayleigh(gridCache)
  {
    delete _steering;
    _steering=new FKSteeringTwoComponentRayleighRadial;
    _steering->setArray(gridCache->array());
    static_cast<FKSteeringTwoComponentRayleighRadial *>(_steering)->resize();

    _RoverN=0.0;
    _ellipticity=0.0;
  }

  bool HRFKRayleigh::invertCrossSpectrum()
  {
    return _crossSpectrum->invertRotatedRayleigh();
  }

  void HRFKRayleigh::setGrid(FKGridSearch * g, double step, double size)
  {
    // Classical kx, ky and ell
    g->setGrid(-size, size, step, -size, size, step, -0.5*M_PI, 0.5*M_PI, M_PI/20.0);
  }

  bool HRFKRayleigh::initGrid(int n)
  {
    if(_gridCache->isEmpty(FKCache::TwoComponentRayleigh)) {
      App::log(tr("Caching steering vectors for 2-component Rayleigh ... (%1 values)\n").arg(n) );
      _gridCache->resize(FKCache::TwoComponentRayleigh, n);
      return true;
    } else {
      return false;
    }
  }

  void HRFKRayleigh::initGrid(const Point& kell, int index)
  {
    FKSteeringTwoComponentRayleighRadial::init(_gridCache, index , kell);
  }

  double HRFKRayleigh::value(const Point& kell, int index) const
  {
    if(isInsideLimits(kell)) {
      FKPower p(&FKSteeringTwoComponentRayleighRadial::cache(_gridCache, index));
      double ell=::tan(kell.z());
      p.setCaponValue(_crossSpectrum->rotatedRayleigh(kell));
      return p.value()*p.value()*ell*ell;
    } else {
      return -1.0;
    }
  }

  double HRFKRayleigh::value(const Point& kell) const
  {
    if(isInsideLimits(kell)) {
      FKSteeringTwoComponentRayleighRadial * s=static_cast<FKSteeringTwoComponentRayleighRadial *>(_steering);
      double ell=::tan(kell.z());
      s->initValue(kell, ell);
      FKPower p(s);
      p.setCaponValue(_crossSpectrum->rotatedRayleigh(kell));
      return p.value()*p.value()*ell*ell;
    } else {
      return -1.0;
    }
  }

  double HRFKRayleigh::ellipticity(const Point& kell)
  {
    const ComplexMatrix& covmat=_crossSpectrum->rotatedRayleigh(kell);
    FKGridSearch grid;
    grid.setEllipticityPrecision(0);
    double ellh=0.0, ellz=0.0;

    HRFKRayleighRadialEllipticity * fh;
    fh=new HRFKRayleighRadialEllipticity(_gridCache);
    grid.setFunction(fh);
    fh->setK(kell);
    fh->setCrossSpectrum(&covmat);
    // Look at 20 deg. above and below current estimation
    grid.setGrid(kell.z()-M_PI/9.0, kell.z()+M_PI/9.0, M_PI/40.0);
    grid.globalMax(0.0);
    if(grid.maximaCount()>0) {
      ellh=::tan(grid.pos().x());
    }

    HRFKRayleighVerticalEllipticity * fz;
    fz=new HRFKRayleighVerticalEllipticity(_gridCache);
    grid.setFunction(fz);
    fz->setK(kell);
    fz->setCrossSpectrum(&covmat);
    grid.setGrid(kell.z()-M_PI/9.0, kell.z()+M_PI/9.0, M_PI/40.0);
    grid.globalMax(0.0);
    if(grid.maximaCount()>0) {
      ellz=::tan(grid.pos().x());
    }

    double ellR=adjustEllipticity(ellh, ellz);
    // Check that the two ways of getting ellipticity provides the same results
    if(fabs(kell.z()-::atan(ellR))>Angle::degreesToRadians(1.0)) {
      _ellipticity=0.0;
    } else {
      _ellipticity=::tan(kell.z());
    }
    return _ellipticity;
  }

  double HRFKRayleigh::noise(const Point&) const
  {
    return _crossSpectrum->array().count()*_RoverN;
  }

  /*!
    \a ellz may be null if no corresponding peak is found for vertical steering.
  */
  double HRFKRayleigh::adjustEllipticity(double ellh, double ellz)
  {
    double ellRatio=ellz/ellh;
    if(ellRatio>=1.0) {
      _RoverN=::sqrt(ellRatio)-1.0;
      double RoverN1=1.0+_RoverN;
      ellz/=RoverN1;
      ellh*=RoverN1;
      if(fabs(ellz-ellh)>1e-5) {
        APP_LOG(1, tr("Difference between ellh (%1) and ellz (%2)=%3\n").arg(ellh).arg(ellz).arg(ellz-ellh))
      }
      return ellz;
    } else {
      _RoverN=std::numeric_limits<double>::infinity();
      return 0.0;
    }
  }

  double HRFKRayleigh::power(double optimumPower) const
  {
    if(_ellipticity!=0.0) {
      return ::pow(optimumPower/(_ellipticity*_ellipticity), 0.5);
    } else {
      return 0.0;
    }
  }

} // namespace ArrayCore

