<commit_before>// Copyright CERN. This software is distributed under the terms of the GNU
// General Public License v3 (GPL Version 3).
//
// See http://www.gnu.org/licenses/ for full licensing information.
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.

//**************************************************************************************
// \class AliHFMLResponseLctoV0bachelor
// \brief helper class to handle application of ML models for LctopK0s analyses trained
// with python libraries
// \authors:
// L. Vermunt, luuk.vermunt@cern.ch
/////////////////////////////////////////////////////////////////////////////////////////

#include <TDatabasePDG.h>

#include "AliHFMLResponseLctoV0bachelor.h"
#include "AliAODRecoCascadeHF.h"
#include "AliVertexingHFUtils.h"
#ifndef HomogeneousField
#define HomogeneousField
#endif

/// \cond CLASSIMP
ClassImp(AliHFMLResponseLctoV0bachelor);
/// \endcond

//--------------------------------------------------------------------------
AliHFMLResponseLctoV0bachelor::AliHFMLResponseLctoV0bachelor() : AliHFMLResponse()
{
  //
  // Default constructor
  //
}

//--------------------------------------------------------------------------
AliHFMLResponseLctoV0bachelor::AliHFMLResponseLctoV0bachelor(const Char_t *name, const Char_t *title,
                                                             const std::string configfilepath) : AliHFMLResponse(name, title, configfilepath)
{
  //
  // Standard constructor
  //
}

//--------------------------------------------------------------------------
AliHFMLResponseLctoV0bachelor::~AliHFMLResponseLctoV0bachelor()
{
  //
  // Destructor
  //
}

//--------------------------------------------------------------------------
AliHFMLResponseLctoV0bachelor::AliHFMLResponseLctoV0bachelor(const AliHFMLResponseLctoV0bachelor &source) : AliHFMLResponse(source)
{
  //
  // Copy constructor
  //
}

//--------------------------------------------------------------------------
AliHFMLResponseLctoV0bachelor &AliHFMLResponseLctoV0bachelor::operator=(const AliHFMLResponseLctoV0bachelor &source)
{
  //
  // assignment operator
  //
  if (&source == this)
    return *this;

  AliHFMLResponse::operator=(source);

  return *this;
}

//--------------------------------------------------------------------------
void AliHFMLResponseLctoV0bachelor::SetMapOfVariables(AliAODRecoDecayHF *cand, double bfield, AliAODPidHF *pidHF, int /*masshypo*/)
{
  fVars["pt_cand"] = cand->Pt();
  fVars["d_len"] = cand->DecayLength();
  fVars["d_len_xy"] = cand->DecayLengthXY();
  fVars["norm_dl"] = cand->NormalizedDecayLength();
  fVars["norm_dl_xy"] = cand->NormalizedDecayLengthXY();
  fVars["cos_p"] = cand->CosPointingAngle();
  fVars["cos_p_xy"] = cand->CosPointingAngleXY();
  fVars["imp_par_xy"] = cand->ImpParXY();
  fVars["dca"] = cand->GetDCA();
  fVars["inv_mass"] = dynamic_cast<AliAODRecoCascadeHF *>(cand)->InvMassLctoK0sP();

  AliAODv0 * v0part = ((AliAODRecoCascadeHF*)cand)->Getv0();
  fVars["imp_par_prong0"] = cand->Getd0Prong(0);
  fVars["imp_par_prong1"] = v0part->Getd0Prong(0);
  fVars["imp_par_prong2"] = v0part->Getd0Prong(1);

  fVars["inv_mass_K0s"] = v0part->MassK0Short();
  fVars["dca_K0s"] = v0part->GetDCA();
  fVars["imp_par_K0s"] = cand->Getd0Prong(1);
  fVars["d_len_K0s"] = ((AliAODRecoCascadeHF*)cand)->DecayLengthV0();
  fVars["DecayLxy_Ks0"] = ((AliAODRecoCascadeHF*)cand)->DecayLengthXYV0();
  fVars["ctau_K0s"] = ((AliAODRecoCascadeHF*)cand)->DecayLengthV0()*0.497/(v0part->P());
  fVars["cos_p_K0s"] = ((AliAODRecoCascadeHF*)cand)->CosV0PointingAngle();
  fVars["pt_K0s"] = v0part->Pt();

  // Cosine of proton emission angle (theta*) in the rest frame of the mother particle
  // (from AliRDHFCutsLctoV0)
  TLorentzVector vpr, vk0s,vlc;
  Double_t massK0SPDG = TDatabasePDG::Instance()->GetParticle(310)->Mass();    // mass K0S PDG
  Double_t massPrPDG = TDatabasePDG::Instance()->GetParticle(2212)->Mass();    // mass Proton PDG
  vpr.SetXYZM(cand->PxProng(0), cand->PyProng(0), cand->PzProng(0), massPrPDG);
  vk0s.SetXYZM(cand->PxProng(1), cand->PyProng(1), cand->PzProng(1), massK0SPDG);
  vlc = vpr + vk0s;
  TVector3 vboost = vlc.BoostVector();
  vpr.Boost(-vboost);
  fVars["cos_t_star"] = TMath::Cos(vpr.Angle(vlc.Vect()));

  // Sign of d0 proton (different from regular d0)
  // (from AliRDHFCutsLctoV0)
  AliAODTrack *bachelor = (AliAODTrack*)((AliAODRecoCascadeHF*)cand)->GetBachelor();
  fVars["pt_Pr"] = bachelor->Pt();
  AliAODVertex *primvert = dynamic_cast<AliAODVertex*>(cand->GetPrimaryVtx());
  Double_t d0z0bach[2], covd0z0bach[3];
  bachelor->PropagateToDCA(primvert, bfield, kVeryBig, d0z0bach, covd0z0bach); // HOW DO WE SET THE B FIELD?; kVeryBig should come from AliExternalTrackParam
  Double_t tx[3];
  bachelor->GetXYZ(tx);
  tx[0] -= primvert->GetX();
  tx[1] -= primvert->GetY();
  tx[2] -= primvert->GetZ();
  Double_t innerpro = tx[0]*cand->Px()+tx[1]*cand->Py();
  Double_t signd0 = 1.;
  if(innerpro<0.) signd0 = -1.;
  fVars["signd0"] = signd0*TMath::Abs(d0z0bach[0]);

  //Armenteros qT/|alpha|
  fVars["armenteros_K0s"] = v0part->PtArmV0()/TMath::Abs(v0part->AlphaV0());

  for(int iProng = 0; iProng < 3; iProng++){
    AliAODTrack *dautrack;
    if(iProng == 0) dautrack = dynamic_cast<AliAODTrack *>(cand->GetDaughter(iProng));
    else            dautrack = dynamic_cast<AliAODTrack *>(v0part->GetDaughter(iProng-1));

    double nsigmaTPCpi = -999., nsigmaTPCK = -999., nsigmaTPCp = -999., nsigmaTOFpi = -999., nsigmaTOFK = -999., nsigmaTOFp = -999.;
    pidHF->GetnSigmaTPC(dautrack, 2, nsigmaTPCpi);
    pidHF->GetnSigmaTPC(dautrack, 3, nsigmaTPCK);
    pidHF->GetnSigmaTPC(dautrack, 4, nsigmaTPCp);
    pidHF->GetnSigmaTOF(dautrack, 2, nsigmaTOFpi);
    pidHF->GetnSigmaTOF(dautrack, 3, nsigmaTOFK);
    pidHF->GetnSigmaTOF(dautrack, 4, nsigmaTOFp);

    fVars[Form("nsigTPC_Pi_%d", iProng)] = nsigmaTPCpi;
    fVars[Form("nsigTPC_K_%d", iProng)]  = nsigmaTPCK;
    fVars[Form("nsigTPC_Pr_%d", iProng)]  = nsigmaTPCp;
    fVars[Form("nsigTOF_Pi_%d", iProng)] = nsigmaTOFpi;
    fVars[Form("nsigTOF_K_%d", iProng)]  = nsigmaTOFK;
    fVars[Form("nsigTOF_Pr_%d", iProng)]  = nsigmaTOFp;

    fVars[Form("nsigComb_Pi_%d", iProng)] = AliVertexingHFUtils::CombineNsigmaTPCTOF(nsigmaTPCpi, nsigmaTOFpi);
    fVars[Form("nsigComb_K_%d", iProng)]  = AliVertexingHFUtils::CombineNsigmaTPCTOF(nsigmaTPCK, nsigmaTOFK);
    fVars[Form("nsigComb_Pr_%d", iProng)]  = AliVertexingHFUtils::CombineNsigmaTPCTOF(nsigmaTPCp, nsigmaTOFp);
  }

//  variables used by KFparticle

      ///! KFParticle kfpLc
      KFPVertex pVertex;
      Double_t pos[3],cov[6];

      ///fpVtx  === primvert
      primvert->GetXYZ(pos);
      primvert->GetCovarianceMatrix(cov);
      pVertex.SetXYZ((Float_t)pos[0],(Float_t)pos[1], (Float_t)pos[2]);
      Float_t covF[6];
      for (Int_t i=0;i<6;i++) {covF[i] = (Float_t)cov[i]; }
      pVertex.SetCovarianceMatrix(covF);
      pVertex.SetChi2(primvert->GetChi2());
      pVertex.SetNDF(primvert->GetNDF());
      pVertex.SetNContributors(primvert->GetNContributors());
      KFParticle PV(pVertex);

      AliAODTrack * v0Pos = dynamic_cast<AliAODTrack*>(((AliAODRecoCascadeHF*)cand)->Getv0PositiveTrack());
      AliAODTrack * v0Neg = dynamic_cast<AliAODTrack*>(((AliAODRecoCascadeHF*)cand)->Getv0NegativeTrack());

       // check charge of the first daughter, if negative, define it as the second one
      if (v0Pos->Charge()<0) {
        v0Pos = (AliAODTrack*) (((AliAODRecoCascadeHF*)cand)->Getv0NegativeTrack());
        v0Neg = (AliAODTrack*) (((AliAODRecoCascadeHF*)cand)->Getv0PositiveTrack());
      }

      KFParticle kfpPionPlus = AliVertexingHFUtils::CreateKFParticleFromAODtrack(v0Pos,211);
      KFParticle kfpPionMinus = AliVertexingHFUtils::CreateKFParticleFromAODtrack(v0Neg,-211);

      KFParticle kfpKs0;
      const KFParticle *Ks0Daughters[2] = {&kfpPionPlus, &kfpPionMinus};
      kfpKs0.Construct(Ks0Daughters,2);

      fVars["ldl_Ks0"] = AliVertexingHFUtils::ldlFromKF(kfpKs0,PV);
      KFParticle kfpKs0_massConstraint = kfpKs0;
      const Float_t massKs0_PDG = TDatabasePDG::Instance()->GetParticle(310)->Mass();

      kfpKs0_massConstraint.SetNonlinearMassConstraint(massKs0_PDG);

      //! NEED kfpProton then go back to 882
      KFParticle kfpProton;
      AliAODTrack *bachPart = dynamic_cast<AliAODTrack*>(((AliAODRecoCascadeHF*)cand)->GetBachelor());
      if (bachPart->Charge() > 0) kfpProton = AliVertexingHFUtils::CreateKFParticleFromAODtrack(bachPart,2212);
      if (bachPart->Charge() < 0) kfpProton = AliVertexingHFUtils::CreateKFParticleFromAODtrack(bachPart,-2212);

      KFParticle kfpLc;
      const KFParticle *LcDaughters[2] = {&kfpProton, &kfpKs0_massConstraint};
      kfpLc.Construct(LcDaughters,2);

      Double_t cosPA_Ks0 = AliVertexingHFUtils::CosPointingAngleFromKF(kfpKs0_massConstraint, kfpLc);
      fVars["PA_Ks0"] = TMath::ACos(cosPA_Ks0);

      KFParticle kfpLc_PV = kfpLc;
      kfpLc_PV.SetProductionVertex(PV);

      fVars["chi2topo_Lc"] = kfpLc_PV.GetChi2()/kfpLc_PV.GetNDF();

}

<commit_msg>add extra missing variable; fix indentation in last commit<commit_after>// Copyright CERN. This software is distributed under the terms of the GNU
// General Public License v3 (GPL Version 3).
//
// See http://www.gnu.org/licenses/ for full licensing information.
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.

//**************************************************************************************
// \class AliHFMLResponseLctoV0bachelor
// \brief helper class to handle application of ML models for LctopK0s analyses trained
// with python libraries
// \authors:
// L. Vermunt, luuk.vermunt@cern.ch
/////////////////////////////////////////////////////////////////////////////////////////

#include <TDatabasePDG.h>

#include "AliHFMLResponseLctoV0bachelor.h"
#include "AliAODRecoCascadeHF.h"
#include "AliVertexingHFUtils.h"
#ifndef HomogeneousField
#define HomogeneousField
#endif

/// \cond CLASSIMP
ClassImp(AliHFMLResponseLctoV0bachelor);
/// \endcond

//--------------------------------------------------------------------------
AliHFMLResponseLctoV0bachelor::AliHFMLResponseLctoV0bachelor() : AliHFMLResponse()
{
  //
  // Default constructor
  //
}

//--------------------------------------------------------------------------
AliHFMLResponseLctoV0bachelor::AliHFMLResponseLctoV0bachelor(const Char_t *name, const Char_t *title,
                                                             const std::string configfilepath) : AliHFMLResponse(name, title, configfilepath)
{
  //
  // Standard constructor
  //
}

//--------------------------------------------------------------------------
AliHFMLResponseLctoV0bachelor::~AliHFMLResponseLctoV0bachelor()
{
  //
  // Destructor
  //
}

//--------------------------------------------------------------------------
AliHFMLResponseLctoV0bachelor::AliHFMLResponseLctoV0bachelor(const AliHFMLResponseLctoV0bachelor &source) : AliHFMLResponse(source)
{
  //
  // Copy constructor
  //
}

//--------------------------------------------------------------------------
AliHFMLResponseLctoV0bachelor &AliHFMLResponseLctoV0bachelor::operator=(const AliHFMLResponseLctoV0bachelor &source)
{
  //
  // assignment operator
  //
  if (&source == this)
    return *this;

  AliHFMLResponse::operator=(source);

  return *this;
}

//--------------------------------------------------------------------------
void AliHFMLResponseLctoV0bachelor::SetMapOfVariables(AliAODRecoDecayHF *cand, double bfield, AliAODPidHF *pidHF, int /*masshypo*/)
{
  fVars["pt_cand"] = cand->Pt();
  fVars["d_len"] = cand->DecayLength();
  fVars["d_len_xy"] = cand->DecayLengthXY();
  fVars["norm_dl"] = cand->NormalizedDecayLength();
  fVars["norm_dl_xy"] = cand->NormalizedDecayLengthXY();
  fVars["cos_p"] = cand->CosPointingAngle();
  fVars["cos_p_xy"] = cand->CosPointingAngleXY();
  fVars["imp_par_xy"] = cand->ImpParXY();
  fVars["dca"] = cand->GetDCA();
  fVars["inv_mass"] = dynamic_cast<AliAODRecoCascadeHF *>(cand)->InvMassLctoK0sP();

  AliAODv0 * v0part = ((AliAODRecoCascadeHF*)cand)->Getv0();
  fVars["imp_par_prong0"] = cand->Getd0Prong(0);
  fVars["imp_par_prong1"] = v0part->Getd0Prong(0);
  fVars["imp_par_prong2"] = v0part->Getd0Prong(1);

  fVars["inv_mass_K0s"] = v0part->MassK0Short();
  fVars["dca_K0s"] = v0part->GetDCA();
  fVars["imp_par_K0s"] = cand->Getd0Prong(1);
  fVars["d_len_K0s"] = ((AliAODRecoCascadeHF*)cand)->DecayLengthV0();
  fVars["DecayLxy_Ks0"] = ((AliAODRecoCascadeHF*)cand)->DecayLengthXYV0();
  fVars["ctau_K0s"] = ((AliAODRecoCascadeHF*)cand)->DecayLengthV0()*0.497/(v0part->P());
  fVars["cos_p_K0s"] = ((AliAODRecoCascadeHF*)cand)->CosV0PointingAngle();
  fVars["pt_K0s"] = v0part->Pt();

  // Cosine of proton emission angle (theta*) in the rest frame of the mother particle
  // (from AliRDHFCutsLctoV0)
  TLorentzVector vpr, vk0s,vlc;
  Double_t massK0SPDG = TDatabasePDG::Instance()->GetParticle(310)->Mass();    // mass K0S PDG
  Double_t massPrPDG = TDatabasePDG::Instance()->GetParticle(2212)->Mass();    // mass Proton PDG
  vpr.SetXYZM(cand->PxProng(0), cand->PyProng(0), cand->PzProng(0), massPrPDG);
  vk0s.SetXYZM(cand->PxProng(1), cand->PyProng(1), cand->PzProng(1), massK0SPDG);
  vlc = vpr + vk0s;
  TVector3 vboost = vlc.BoostVector();
  vpr.Boost(-vboost);
  fVars["cos_t_star"] = TMath::Cos(vpr.Angle(vlc.Vect()));

  // Sign of d0 proton (different from regular d0)
  // (from AliRDHFCutsLctoV0)
  AliAODTrack *bachelor = (AliAODTrack*)((AliAODRecoCascadeHF*)cand)->GetBachelor();
  fVars["pt_Pr"] = bachelor->Pt();
  AliAODVertex *primvert = dynamic_cast<AliAODVertex*>(cand->GetPrimaryVtx());
  Double_t d0z0bach[2], covd0z0bach[3];
  bachelor->PropagateToDCA(primvert, bfield, kVeryBig, d0z0bach, covd0z0bach); // HOW DO WE SET THE B FIELD?; kVeryBig should come from AliExternalTrackParam
  Double_t tx[3];
  bachelor->GetXYZ(tx);
  tx[0] -= primvert->GetX();
  tx[1] -= primvert->GetY();
  tx[2] -= primvert->GetZ();
  Double_t innerpro = tx[0]*cand->Px()+tx[1]*cand->Py();
  Double_t signd0 = 1.;
  if(innerpro<0.) signd0 = -1.;
  fVars["signd0"] = signd0*TMath::Abs(d0z0bach[0]);

  //Armenteros qT/|alpha|
  fVars["armenteros_K0s"] = v0part->PtArmV0()/TMath::Abs(v0part->AlphaV0());

  for(int iProng = 0; iProng < 3; iProng++){
    AliAODTrack *dautrack;
    if(iProng == 0) dautrack = dynamic_cast<AliAODTrack *>(cand->GetDaughter(iProng));
    else            dautrack = dynamic_cast<AliAODTrack *>(v0part->GetDaughter(iProng-1));

    double nsigmaTPCpi = -999., nsigmaTPCK = -999., nsigmaTPCp = -999., nsigmaTOFpi = -999., nsigmaTOFK = -999., nsigmaTOFp = -999.;
    pidHF->GetnSigmaTPC(dautrack, 2, nsigmaTPCpi);
    pidHF->GetnSigmaTPC(dautrack, 3, nsigmaTPCK);
    pidHF->GetnSigmaTPC(dautrack, 4, nsigmaTPCp);
    pidHF->GetnSigmaTOF(dautrack, 2, nsigmaTOFpi);
    pidHF->GetnSigmaTOF(dautrack, 3, nsigmaTOFK);
    pidHF->GetnSigmaTOF(dautrack, 4, nsigmaTOFp);

    fVars[Form("nsigTPC_Pi_%d", iProng)] = nsigmaTPCpi;
    fVars[Form("nsigTPC_K_%d", iProng)]  = nsigmaTPCK;
    fVars[Form("nsigTPC_Pr_%d", iProng)]  = nsigmaTPCp;
    fVars[Form("nsigTOF_Pi_%d", iProng)] = nsigmaTOFpi;
    fVars[Form("nsigTOF_K_%d", iProng)]  = nsigmaTOFK;
    fVars[Form("nsigTOF_Pr_%d", iProng)]  = nsigmaTOFp;

    fVars[Form("nsigComb_Pi_%d", iProng)] = AliVertexingHFUtils::CombineNsigmaTPCTOF(nsigmaTPCpi, nsigmaTOFpi);
    fVars[Form("nsigComb_K_%d", iProng)]  = AliVertexingHFUtils::CombineNsigmaTPCTOF(nsigmaTPCK, nsigmaTOFK);
    fVars[Form("nsigComb_Pr_%d", iProng)]  = AliVertexingHFUtils::CombineNsigmaTPCTOF(nsigmaTPCp, nsigmaTOFp);
  }

//  variables used by KFparticle

      ///! KFParticle kfpLc
  KFPVertex pVertex;
  Double_t pos[3],cov[6];

  ///fpVtx  === primvert
  primvert->GetXYZ(pos);
  primvert->GetCovarianceMatrix(cov);
  pVertex.SetXYZ((Float_t)pos[0],(Float_t)pos[1], (Float_t)pos[2]);
  Float_t covF[6];
  for (Int_t i=0;i<6;i++) {covF[i] = (Float_t)cov[i]; }
  pVertex.SetCovarianceMatrix(covF);
  pVertex.SetChi2(primvert->GetChi2());
  pVertex.SetNDF(primvert->GetNDF());
  pVertex.SetNContributors(primvert->GetNContributors());
  KFParticle PV(pVertex);

  AliAODTrack * v0Pos = dynamic_cast<AliAODTrack*>(((AliAODRecoCascadeHF*)cand)->Getv0PositiveTrack());
  AliAODTrack * v0Neg = dynamic_cast<AliAODTrack*>(((AliAODRecoCascadeHF*)cand)->Getv0NegativeTrack());

   // check charge of the first daughter, if negative, define it as the second one
  if (v0Pos->Charge()<0) {
    v0Pos = (AliAODTrack*) (((AliAODRecoCascadeHF*)cand)->Getv0NegativeTrack());
    v0Neg = (AliAODTrack*) (((AliAODRecoCascadeHF*)cand)->Getv0PositiveTrack());
  }

  KFParticle kfpPionPlus = AliVertexingHFUtils::CreateKFParticleFromAODtrack(v0Pos,211);
  KFParticle kfpPionMinus = AliVertexingHFUtils::CreateKFParticleFromAODtrack(v0Neg,-211);

  KFParticle kfpKs0;
  const KFParticle *Ks0Daughters[2] = {&kfpPionPlus, &kfpPionMinus};
  kfpKs0.Construct(Ks0Daughters,2);

  fVars["ldl_Ks0"] = AliVertexingHFUtils::ldlFromKF(kfpKs0,PV);
  KFParticle kfpKs0_massConstraint = kfpKs0;
  const Float_t massKs0_PDG = TDatabasePDG::Instance()->GetParticle(310)->Mass();

  kfpKs0_massConstraint.SetNonlinearMassConstraint(massKs0_PDG);

  //! NEED kfpProton then go back to 882
  KFParticle kfpProton;
  AliAODTrack *bachPart = dynamic_cast<AliAODTrack*>(((AliAODRecoCascadeHF*)cand)->GetBachelor());
  if (bachPart->Charge() > 0) kfpProton = AliVertexingHFUtils::CreateKFParticleFromAODtrack(bachPart,2212);
  if (bachPart->Charge() < 0) kfpProton = AliVertexingHFUtils::CreateKFParticleFromAODtrack(bachPart,-2212);

  KFParticle kfpLc;
  const KFParticle *LcDaughters[2] = {&kfpProton, &kfpKs0_massConstraint};
  kfpLc.Construct(LcDaughters,2);

  Double_t cosPA_Ks0 = AliVertexingHFUtils::CosPointingAngleFromKF(kfpKs0_massConstraint, kfpLc);
  Double_t cosPA_Lc  = AliVertexingHFUtils::CosPointingAngleFromKF(kfpLc, PV);
  fVars["PA_Ks0"] = TMath::ACos(cosPA_Ks0);
  fVars["PA_Lc"] = TMath::ACos(cosPA_Lc);

  KFParticle kfpLc_PV = kfpLc;
  kfpLc_PV.SetProductionVertex(PV);

  fVars["chi2topo_Lc"] = kfpLc_PV.GetChi2()/kfpLc_PV.GetNDF();

}

<|endoftext|>


<commit_before>#include <iostream>

#include "matrix.h"
#include "checks.h"

template <std::size_t NumberOfRows, std::size_t NumberOfCulomns>
std::size_t TestMatrixPlus() {
    AMatrix::Matrix<double, NumberOfRows, NumberOfCulomns> a_matrix;
    AMatrix::Matrix<double, NumberOfRows, NumberOfCulomns> b_matrix;
    AMatrix::Matrix<double, NumberOfRows, NumberOfCulomns> c_matrix;
    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            a_matrix(i, j) = 2.33 * i - 4.52 * j;

    b_matrix = a_matrix;
    c_matrix = a_matrix + b_matrix;

    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            AMATRIX_CHECK_EQUAL(c_matrix(i, j), 2 * (2.33 * i - 4.52 * j));

    return 0;  // not failed
}

template <std::size_t NumberOfRows, std::size_t NumberOfCulomns>
std::size_t TestMatrixPlusEqual() {
    AMatrix::Matrix<double, NumberOfRows, NumberOfCulomns> a_matrix;
    AMatrix::Matrix<double, NumberOfRows, NumberOfCulomns> b_matrix;
    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            a_matrix(i, j) = 2.33 * i - 4.52 * j;

    b_matrix = a_matrix;
    a_matrix += b_matrix;

    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            AMATRIX_CHECK_EQUAL(a_matrix(i, j), 2 * (2.33 * i - 4.52 * j));

    return 0;  // not failed
}

int main() {
    std::size_t number_of_failed_tests = 0;
    number_of_failed_tests += TestMatrixPlus<1, 1>();

    number_of_failed_tests += TestMatrixPlus<1, 2>();
    number_of_failed_tests += TestMatrixPlus<2, 1>();
    number_of_failed_tests += TestMatrixPlus<2, 2>();

    number_of_failed_tests += TestMatrixPlus<3, 1>();
    number_of_failed_tests += TestMatrixPlus<3, 2>();
    number_of_failed_tests += TestMatrixPlus<3, 3>();
    number_of_failed_tests += TestMatrixPlus<1, 3>();
    number_of_failed_tests += TestMatrixPlus<2, 3>();
    number_of_failed_tests += TestMatrixPlus<3, 3>();

    number_of_failed_tests += TestMatrixPlusEqual<1, 1>();

    number_of_failed_tests += TestMatrixPlusEqual<1, 2>();
    number_of_failed_tests += TestMatrixPlusEqual<2, 1>();
    number_of_failed_tests += TestMatrixPlusEqual<2, 2>();

    number_of_failed_tests += TestMatrixPlusEqual<3, 1>();
    number_of_failed_tests += TestMatrixPlusEqual<3, 2>();
    number_of_failed_tests += TestMatrixPlusEqual<3, 3>();
    number_of_failed_tests += TestMatrixPlusEqual<1, 3>();
    number_of_failed_tests += TestMatrixPlusEqual<2, 3>();
    number_of_failed_tests += TestMatrixPlusEqual<3, 3>();

    std::cout << number_of_failed_tests << "tests failed" << std::endl;

    return number_of_failed_tests;
}
<commit_msg>changing arguments names<commit_after>#include <iostream>

#include "matrix.h"
#include "checks.h"

template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestMatrixPlus() {
    AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
    AMatrix::Matrix<double, TSize1, TSize2> b_matrix;
    AMatrix::Matrix<double, TSize1, TSize2> c_matrix;
    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            a_matrix(i, j) = 2.33 * i - 4.52 * j;

    b_matrix = a_matrix;
    c_matrix = a_matrix + b_matrix;

    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            AMATRIX_CHECK_EQUAL(c_matrix(i, j), 2 * (2.33 * i - 4.52 * j));

    return 0;  // not failed
}

template <std::size_t TSize1, std::size_t TSize2>
std::size_t TestMatrixPlusEqual() {
    AMatrix::Matrix<double, TSize1, TSize2> a_matrix;
    AMatrix::Matrix<double, TSize1, TSize2> b_matrix;
    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            a_matrix(i, j) = 2.33 * i - 4.52 * j;

    b_matrix = a_matrix;
    a_matrix += b_matrix;

    for (std::size_t i = 0; i < a_matrix.size1(); i++)
        for (std::size_t j = 0; j < a_matrix.size2(); j++)
            AMATRIX_CHECK_EQUAL(a_matrix(i, j), 2 * (2.33 * i - 4.52 * j));

    return 0;  // not failed
}

int main() {
    std::size_t number_of_failed_tests = 0;
    number_of_failed_tests += TestMatrixPlus<1, 1>();

    number_of_failed_tests += TestMatrixPlus<1, 2>();
    number_of_failed_tests += TestMatrixPlus<2, 1>();
    number_of_failed_tests += TestMatrixPlus<2, 2>();

    number_of_failed_tests += TestMatrixPlus<3, 1>();
    number_of_failed_tests += TestMatrixPlus<3, 2>();
    number_of_failed_tests += TestMatrixPlus<3, 3>();
    number_of_failed_tests += TestMatrixPlus<1, 3>();
    number_of_failed_tests += TestMatrixPlus<2, 3>();
    number_of_failed_tests += TestMatrixPlus<3, 3>();

    number_of_failed_tests += TestMatrixPlusEqual<1, 1>();

    number_of_failed_tests += TestMatrixPlusEqual<1, 2>();
    number_of_failed_tests += TestMatrixPlusEqual<2, 1>();
    number_of_failed_tests += TestMatrixPlusEqual<2, 2>();

    number_of_failed_tests += TestMatrixPlusEqual<3, 1>();
    number_of_failed_tests += TestMatrixPlusEqual<3, 2>();
    number_of_failed_tests += TestMatrixPlusEqual<3, 3>();
    number_of_failed_tests += TestMatrixPlusEqual<1, 3>();
    number_of_failed_tests += TestMatrixPlusEqual<2, 3>();
    number_of_failed_tests += TestMatrixPlusEqual<3, 3>();

    std::cout << number_of_failed_tests << "tests failed" << std::endl;

    return number_of_failed_tests;
}
<|endoftext|>


<commit_before>#include "property_diversity_reranker.h"

#include <mining-manager/group-label-logger/GroupLabelLogger.h>

#include <list>
#include <algorithm>
#include <glog/logging.h>

using sf1r::GroupLabelLogger;

NS_FACETED_BEGIN

PropertyDiversityReranker::PropertyDiversityReranker(
    const std::string& property,
    const GroupManager::PropValueMap& propValueMap,
    const std::string& boostingProperty
)
    :property_(property)
    ,propValueMap_(propValueMap)
    ,groupLabelLogger_(NULL)
    ,boostingProperty_(boostingProperty)
{
}

PropertyDiversityReranker::~PropertyDiversityReranker()
{
}

void PropertyDiversityReranker::simplererank(
    std::vector<unsigned int>& docIdList,
    std::vector<float>& rankScoreList
)
{
    typedef std::list<std::pair<unsigned int,float> > DocIdList;
    typedef std::map<PropValueTable::pvid_t, DocIdList> DocIdMap;

    GroupManager::PropValueMap::const_iterator pvIt = propValueMap_.find(property_);
    if (pvIt == propValueMap_.end())
    {
        LOG(ERROR) << "in GroupManager: group index file is not loaded for group property " << property_;
        return;
    }

    const PropValueTable& pvTable = pvIt->second;
    const std::vector<PropValueTable::pvid_t>& idTable = pvTable.propIdTable();

    std::size_t numDoc = docIdList.size();
    std::vector<unsigned int> newDocIdList;
    std::vector<float> newScoreList;
    newDocIdList.reserve(numDoc);
    newScoreList.reserve(numDoc);

    DocIdMap docIdMap;
    DocIdList missDocs;
    for (std::size_t i = 0; i < numDoc; ++i)
    {
        docid_t docId = docIdList[i];

        // this doc has not built group index data
        if (docId >= idTable.size())
            continue;

        PropValueTable::pvid_t pvId = idTable[docId];
        if (pvId != 0)
        {
            docIdMap[pvId].push_back(std::make_pair(docId, rankScoreList[i]));
        }
        else
        {
            missDocs.push_back(std::make_pair(docId, rankScoreList[i]));
        }
    }
    if(docIdMap.size() <= 1) return; // single property or empty
    do{
        DocIdMap::iterator mapIt = docIdMap.begin();
        while(mapIt != docIdMap.end())
        {
            if(mapIt->second.empty())
            {
                docIdMap.erase(mapIt++);
            }
            else
            {
                std::pair<unsigned int, float> element = mapIt->second.front();
                mapIt->second.pop_front();
                newDocIdList.push_back(element.first);
                newScoreList.push_back(element.second);
                ++mapIt;
            }
        }
    }while(!docIdMap.empty());

    for(DocIdList::iterator missIt = missDocs.begin(); missIt != missDocs.end(); ++missIt)
    {
        newDocIdList.push_back(missIt->first);
        newScoreList.push_back(missIt->second);
    }

    using std::swap;
    swap(docIdList, newDocIdList);
    swap(rankScoreList, newScoreList);
}

void PropertyDiversityReranker::rerank(
    std::vector<unsigned int>& docIdList,
    std::vector<float>& rankScoreList,
    const std::string& query
)
{
    typedef std::list<std::pair<unsigned int,float> > DocIdList;
    typedef std::map<PropValueTable::pvid_t, DocIdList> DocIdMap;

    std::vector<std::string> propValueVec;
    std::vector<int> freqVec;
    if(groupLabelLogger_)
    {
        groupLabelLogger_->getFreqLabel(query, 1, propValueVec, freqVec);
    }

    if(!propValueVec.empty())
    {
        std::string& boostingCategoryLabel = propValueVec[0];
        //std::cout<<"boosting category "<<boostingCategoryLabel<<std::endl;
        GroupManager::PropValueMap::const_iterator pvIt = propValueMap_.find(boostingProperty_);
        if (pvIt == propValueMap_.end())
        {
            LOG(ERROR) << "in GroupManager: group index file is not loaded for group property " << boostingProperty_;
            simplererank(docIdList, rankScoreList);
            return;
        }
        const PropValueTable& pvTable = pvIt->second;
        const std::vector<PropValueTable::pvid_t>& idTable = pvTable.propIdTable();
        const std::vector<PropValueTable::pvid_t>& parentTable = pvTable.parentIdTable();
        izenelib::util::UString labelUStr(boostingCategoryLabel, izenelib::util::UString::UTF_8);
        PropValueTable::pvid_t labelId = pvTable.propValueId(labelUStr);
        if (labelId == 0)
        {
            LOG(WARNING) << "in GroupManager: group index has not been built for Category value: " << boostingCategoryLabel;
            simplererank(docIdList, rankScoreList);
            return;
        }

        std::size_t numDoc = docIdList.size();

        std::vector<unsigned int> boostingDocIdList;
        std::vector<float> boostingScoreList;
        boostingDocIdList.reserve(numDoc);;
        boostingScoreList.reserve(numDoc);

        std::vector<unsigned int> leftDocIdList;
        std::vector<float> leftScoreList;
        leftDocIdList.reserve(numDoc);;
        leftScoreList.reserve(numDoc);

        for(std::size_t i = 0; i < numDoc; ++i)
        {
            docid_t docId = docIdList[i];

            // this doc has not built group index data
            if (docId >= idTable.size())
                continue;

            PropValueTable::pvid_t pvId = idTable[docId];

            // check whether pvId is the child (or itself) of labelId
            bool isChild = false;
            while (pvId != 0)
            {
                if (pvId == labelId)
                {
                    isChild = true;
                    break;
                }
                pvId = parentTable[pvId];
            }

            if (isChild)
            {
                boostingDocIdList.push_back(docId);
                boostingScoreList.push_back(rankScoreList[i]);
            }
            else
            {
                leftDocIdList.push_back(docId);
                leftScoreList.push_back(rankScoreList[i]);
            }
        }
        if(!boostingDocIdList.empty())
        {
            simplererank(boostingDocIdList, boostingScoreList);
        }
        if(!leftDocIdList.empty())
        {
            simplererank(leftDocIdList, leftScoreList);
        }
        boostingDocIdList.resize(numDoc);
        boostingScoreList.resize(numDoc);
        std::copy_backward(leftDocIdList.begin(), leftDocIdList.end(), boostingDocIdList.end());
        std::copy_backward(leftScoreList.begin(), leftScoreList.end(), boostingScoreList.end());
        using std::swap;
        swap(docIdList, boostingDocIdList);
        swap(rankScoreList, boostingScoreList);
    }
    else
        simplererank(docIdList, rankScoreList);
}

NS_FACETED_END

<commit_msg>print boosting category for ease of debug.<commit_after>#include "property_diversity_reranker.h"

#include <mining-manager/group-label-logger/GroupLabelLogger.h>

#include <list>
#include <algorithm>
#include <glog/logging.h>

using sf1r::GroupLabelLogger;

NS_FACETED_BEGIN

PropertyDiversityReranker::PropertyDiversityReranker(
    const std::string& property,
    const GroupManager::PropValueMap& propValueMap,
    const std::string& boostingProperty
)
    :property_(property)
    ,propValueMap_(propValueMap)
    ,groupLabelLogger_(NULL)
    ,boostingProperty_(boostingProperty)
{
}

PropertyDiversityReranker::~PropertyDiversityReranker()
{
}

void PropertyDiversityReranker::simplererank(
    std::vector<unsigned int>& docIdList,
    std::vector<float>& rankScoreList
)
{
    typedef std::list<std::pair<unsigned int,float> > DocIdList;
    typedef std::map<PropValueTable::pvid_t, DocIdList> DocIdMap;

    GroupManager::PropValueMap::const_iterator pvIt = propValueMap_.find(property_);
    if (pvIt == propValueMap_.end())
    {
        LOG(ERROR) << "in GroupManager: group index file is not loaded for group property " << property_;
        return;
    }

    const PropValueTable& pvTable = pvIt->second;
    const std::vector<PropValueTable::pvid_t>& idTable = pvTable.propIdTable();

    std::size_t numDoc = docIdList.size();
    std::vector<unsigned int> newDocIdList;
    std::vector<float> newScoreList;
    newDocIdList.reserve(numDoc);
    newScoreList.reserve(numDoc);

    DocIdMap docIdMap;
    DocIdList missDocs;
    for (std::size_t i = 0; i < numDoc; ++i)
    {
        docid_t docId = docIdList[i];

        // this doc has not built group index data
        if (docId >= idTable.size())
            continue;

        PropValueTable::pvid_t pvId = idTable[docId];
        if (pvId != 0)
        {
            docIdMap[pvId].push_back(std::make_pair(docId, rankScoreList[i]));
        }
        else
        {
            missDocs.push_back(std::make_pair(docId, rankScoreList[i]));
        }
    }
    if(docIdMap.size() <= 1) return; // single property or empty
    do{
        DocIdMap::iterator mapIt = docIdMap.begin();
        while(mapIt != docIdMap.end())
        {
            if(mapIt->second.empty())
            {
                docIdMap.erase(mapIt++);
            }
            else
            {
                std::pair<unsigned int, float> element = mapIt->second.front();
                mapIt->second.pop_front();
                newDocIdList.push_back(element.first);
                newScoreList.push_back(element.second);
                ++mapIt;
            }
        }
    }while(!docIdMap.empty());

    for(DocIdList::iterator missIt = missDocs.begin(); missIt != missDocs.end(); ++missIt)
    {
        newDocIdList.push_back(missIt->first);
        newScoreList.push_back(missIt->second);
    }

    using std::swap;
    swap(docIdList, newDocIdList);
    swap(rankScoreList, newScoreList);
}

void PropertyDiversityReranker::rerank(
    std::vector<unsigned int>& docIdList,
    std::vector<float>& rankScoreList,
    const std::string& query
)
{
    typedef std::list<std::pair<unsigned int,float> > DocIdList;
    typedef std::map<PropValueTable::pvid_t, DocIdList> DocIdMap;

    std::vector<std::string> propValueVec;
    std::vector<int> freqVec;
    if(groupLabelLogger_)
    {
        groupLabelLogger_->getFreqLabel(query, 1, propValueVec, freqVec);
    }

    if(!propValueVec.empty())
    {
        std::string& boostingCategoryLabel = propValueVec[0];
        std::cout<<"boosting category "<<boostingCategoryLabel<<std::endl;
        GroupManager::PropValueMap::const_iterator pvIt = propValueMap_.find(boostingProperty_);
        if (pvIt == propValueMap_.end())
        {
            LOG(ERROR) << "in GroupManager: group index file is not loaded for group property " << boostingProperty_;
            simplererank(docIdList, rankScoreList);
            return;
        }
        const PropValueTable& pvTable = pvIt->second;
        const std::vector<PropValueTable::pvid_t>& idTable = pvTable.propIdTable();
        const std::vector<PropValueTable::pvid_t>& parentTable = pvTable.parentIdTable();
        izenelib::util::UString labelUStr(boostingCategoryLabel, izenelib::util::UString::UTF_8);
        PropValueTable::pvid_t labelId = pvTable.propValueId(labelUStr);
        if (labelId == 0)
        {
            LOG(WARNING) << "in GroupManager: group index has not been built for Category value: " << boostingCategoryLabel;
            simplererank(docIdList, rankScoreList);
            return;
        }

        std::size_t numDoc = docIdList.size();

        std::vector<unsigned int> boostingDocIdList;
        std::vector<float> boostingScoreList;
        boostingDocIdList.reserve(numDoc);;
        boostingScoreList.reserve(numDoc);

        std::vector<unsigned int> leftDocIdList;
        std::vector<float> leftScoreList;
        leftDocIdList.reserve(numDoc);;
        leftScoreList.reserve(numDoc);

        for(std::size_t i = 0; i < numDoc; ++i)
        {
            docid_t docId = docIdList[i];

            // this doc has not built group index data
            if (docId >= idTable.size())
                continue;

            PropValueTable::pvid_t pvId = idTable[docId];

            // check whether pvId is the child (or itself) of labelId
            bool isChild = false;
            while (pvId != 0)
            {
                if (pvId == labelId)
                {
                    isChild = true;
                    break;
                }
                pvId = parentTable[pvId];
            }

            if (isChild)
            {
                boostingDocIdList.push_back(docId);
                boostingScoreList.push_back(rankScoreList[i]);
            }
            else
            {
                leftDocIdList.push_back(docId);
                leftScoreList.push_back(rankScoreList[i]);
            }
        }
        if(!boostingDocIdList.empty())
        {
            simplererank(boostingDocIdList, boostingScoreList);
        }
        if(!leftDocIdList.empty())
        {
            simplererank(leftDocIdList, leftScoreList);
        }
        boostingDocIdList.resize(numDoc);
        boostingScoreList.resize(numDoc);
        std::copy_backward(leftDocIdList.begin(), leftDocIdList.end(), boostingDocIdList.end());
        std::copy_backward(leftScoreList.begin(), leftScoreList.end(), boostingScoreList.end());
        using std::swap;
        swap(docIdList, boostingDocIdList);
        swap(rankScoreList, boostingScoreList);
    }
    else
        simplererank(docIdList, rankScoreList);
}

NS_FACETED_END

<|endoftext|>


<commit_before>#include "property_diversity_reranker.h"

#include <list>
#include <glog/logging.h>

NS_FACETED_BEGIN

PropertyDiversityReranker::PropertyDiversityReranker(
    const std::string& property,
    GroupManager* groupManager
)
    :property_(property)
    ,groupManager_(groupManager)
{
}

PropertyDiversityReranker::~PropertyDiversityReranker()
{
}

void PropertyDiversityReranker::rerank(
    std::vector<unsigned int>& docIdList,
    std::vector<float>& rankScoreList
)
{
    typedef std::list<std::pair<unsigned int,float> > DocIdList;
    typedef std::map<PropValueTable::pvid_t, DocIdList> DocIdMap;

    GroupManager::PropValueMap::const_iterator pvIt = groupManager_->propValueMap_.find(property_);
    if (pvIt == groupManager_->propValueMap_.end())
    {
        LOG(ERROR) << "in GroupManager: group index file is not loaded for group property " << property_;
        return;
    }

    const PropValueTable& pvTable = pvIt->second;
    const std::vector<PropValueTable::pvid_t>& idTable = pvTable.propIdTable();

    std::size_t numDoc = docIdList.size();
    std::vector<unsigned int> newDocIdList;
    std::vector<float> newScoreList;
    newDocIdList.reserve(numDoc);;
    rankScoreList.reserve(numDoc);

    DocIdMap docIdMap;
    DocIdList missDocs;
    for (std::size_t i = 0; i < numDoc; ++i)
    {
        docid_t docId = docIdList[i];

        // this doc has not built group index data
        if (docId >= idTable.size())
            continue;

        PropValueTable::pvid_t pvId = idTable[docId];
        if (pvId != 0)
        {
            docIdMap[pvId].push_back(std::make_pair(docId, rankScoreList[i]));
        }
        else
        {
            missDocs.push_back(std::make_pair(docId, rankScoreList[i]));
        }
    }
    if(docIdMap.size() <= 1) return; // single property or empty
    do{
        for(DocIdMap::iterator mapIt = docIdMap.begin(); mapIt != docIdMap.end(); ++mapIt)
        {
            if(mapIt->second.empty())
            {
                docIdMap.erase(mapIt++);
            }
            else
            {
                std::pair<unsigned int, float> element = mapIt->second.front();
                mapIt->second.pop_front();
                newDocIdList.push_back(element.first);
                newScoreList.push_back(element.second);
            }
        }
    }while(!docIdMap.empty());

    for(DocIdList::iterator missIt = missDocs.begin(); missIt != missDocs.end(); ++missIt)
    {
        newDocIdList.push_back(missIt->first);
        newScoreList.push_back(missIt->second);
    }

    using std::swap;
    swap(docIdList, newDocIdList);
    swap(rankScoreList, newScoreList);
}

NS_FACETED_END

<commit_msg>fix property reranker<commit_after>#include "property_diversity_reranker.h"

#include <list>
#include <glog/logging.h>

NS_FACETED_BEGIN

PropertyDiversityReranker::PropertyDiversityReranker(
    const std::string& property,
    GroupManager* groupManager
)
    :property_(property)
    ,groupManager_(groupManager)
{
}

PropertyDiversityReranker::~PropertyDiversityReranker()
{
}

void PropertyDiversityReranker::rerank(
    std::vector<unsigned int>& docIdList,
    std::vector<float>& rankScoreList
)
{
    typedef std::list<std::pair<unsigned int,float> > DocIdList;
    typedef std::map<PropValueTable::pvid_t, DocIdList> DocIdMap;

    GroupManager::PropValueMap::const_iterator pvIt = groupManager_->propValueMap_.find(property_);
    if (pvIt == groupManager_->propValueMap_.end())
    {
        LOG(ERROR) << "in GroupManager: group index file is not loaded for group property " << property_;
        return;
    }

    const PropValueTable& pvTable = pvIt->second;
    const std::vector<PropValueTable::pvid_t>& idTable = pvTable.propIdTable();

    std::size_t numDoc = docIdList.size();
    std::vector<unsigned int> newDocIdList;
    std::vector<float> newScoreList;
    newDocIdList.reserve(numDoc);;
    rankScoreList.reserve(numDoc);

    DocIdMap docIdMap;
    DocIdList missDocs;
    for (std::size_t i = 0; i < numDoc; ++i)
    {
        docid_t docId = docIdList[i];

        // this doc has not built group index data
        if (docId >= idTable.size())
            continue;

        PropValueTable::pvid_t pvId = idTable[docId];
        if (pvId != 0)
        {
            docIdMap[pvId].push_back(std::make_pair(docId, rankScoreList[i]));
        }
        else
        {
            missDocs.push_back(std::make_pair(docId, rankScoreList[i]));
        }
    }
    if(docIdMap.size() <= 1) return; // single property or empty
    do{
        for(DocIdMap::iterator mapIt = docIdMap.begin(); mapIt != docIdMap.end(); ++mapIt)
        {
            if(mapIt->second.empty())
            {
                docIdMap.erase(mapIt);
            }
            else
            {
                std::pair<unsigned int, float> element = mapIt->second.front();
                mapIt->second.pop_front();
                newDocIdList.push_back(element.first);
                newScoreList.push_back(element.second);
            }
        }
    }while(!docIdMap.empty());

    for(DocIdList::iterator missIt = missDocs.begin(); missIt != missDocs.end(); ++missIt)
    {
        newDocIdList.push_back(missIt->first);
        newScoreList.push_back(missIt->second);
    }

    using std::swap;
    swap(docIdList, newDocIdList);
    swap(rankScoreList, newScoreList);
}

NS_FACETED_END

<|endoftext|>


<commit_before>#include "DerivativeParsedMaterialHelper.h"

template<>
InputParameters validParams<DerivativeParsedMaterialHelper>()
{
  InputParameters params = validParams<DerivativeBaseMaterial>();
  params.addClassDescription("Parsed Function Material with automatic derivatives.");

  // Just in time compilation for the FParser objects
#ifdef LIBMESH_HAVE_FPARSER_JIT
  params.addParam<bool>( "enable_jit", false, "Enable Just In Time compilation of the parsed functions");
#endif
  params.addParam<bool>( "disable_fpoptimizer", false, "Disable the function parser algebraic optimizer");
  params.addParam<bool>( "fail_on_evalerror", false, "Fail fatally if a function evaluation returns an error code (otherwise just pass on NaN)");
  return params;
}

const char * DerivativeParsedMaterialHelper::_eval_error_msg[] = {
  "Unknown",
  "Division by zero",
  "Square root of a negative value",
  "Logarithm of negative value",
  "Trigonometric error (asin or acos of illegal value)",
  "Maximum recursion level reached"
};

DerivativeParsedMaterialHelper::DerivativeParsedMaterialHelper(const std::string & name,
                                                               InputParameters parameters,
                                                               VariableNameMappingMode map_mode) :
    DerivativeBaseMaterial(name, parameters),
    _func_F(NULL),
    _nmat_props(0),
    _enable_jit(isParamValid("enable_jit") && getParam<bool>("enable_jit")),
    _disable_fpoptimizer(getParam<bool>("disable_fpoptimizer")),
    _fail_on_evalerror(getParam<bool>("fail_on_evalerror")),
    _map_mode(map_mode),
    _nan(std::numeric_limits<Real>::quiet_NaN())
{
}

DerivativeParsedMaterialHelper::~DerivativeParsedMaterialHelper()
{
  delete[] _func_params;
}

void DerivativeParsedMaterialHelper::functionParse(const std::string & function_expression)
{
  std::vector<std::string> empty_string_vector;
  functionParse(function_expression,
                empty_string_vector, empty_string_vector);
}

void DerivativeParsedMaterialHelper::functionParse(const std::string & function_expression,
                                                   const std::vector<std::string> & constant_names,
                                                   const std::vector<std::string> & constant_expressions)
{
  std::vector<std::string> empty_string_vector;
  std::vector<Real> empty_real_vector;
  functionParse(function_expression, constant_names, constant_expressions,
                empty_string_vector, empty_string_vector, empty_real_vector);
}

void DerivativeParsedMaterialHelper::functionParse(const std::string & function_expression,
                                                   const std::vector<std::string> & constant_names,
                                                   const std::vector<std::string> & constant_expressions,
                                                   const std::vector<std::string> & mat_prop_names,
                                                   const std::vector<std::string> & tol_names,
                                                   const std::vector<Real> & tol_values)
{
  // check number of coupled variables
  if (_nargs == 0)
    mooseError("Need at least one coupled variable for DerivativeParsedMaterialHelper.");

  // check constant vectors
  unsigned int nconst = constant_expressions.size();
  if (nconst != constant_expressions.size())
    mooseError("The parameter vectors constant_names and constant_values must have equal length.");

  // build base function object
  _func_F =  new ADFunction();

  // initialize constants
  ADFunction *expression;
  std::vector<Real> constant_values(nconst);
  for (unsigned int i = 0; i < nconst; ++i)
  {
    expression = new ADFunction();

    // add previously evaluated constants
    for (unsigned int j = 0; j < i; ++j)
      if (!expression->AddConstant(constant_names[j], constant_values[j]))
        mooseError("Invalid constant name in DerivativeParsedMaterialHelper");

    // build the temporary comnstant expression function
    if (expression->Parse(constant_expressions[i], "") >= 0)
       mooseError(std::string("Invalid constant expression\n" + constant_expressions[i] + "\n in DerivativeParsedMaterialHelper. ") + expression->ErrorMsg());

    constant_values[i] = expression->Eval(NULL);

#ifdef DEBUG
    _console << "Constant value " << i << ' ' << constant_expressions[i] << " = " << constant_values[i] << std::endl;
#endif

    if (!_func_F->AddConstant(constant_names[i], constant_values[i]))
      mooseError("Invalid constant name in DerivativeParsedMaterialHelper");

    delete expression;
  }

  // tolerance vectors
  if (tol_names.size() != tol_values.size())
    mooseError("The parameter vectors tol_names and tol_values must have equal length.");

  // set tolerances
  _tol.resize(_nargs);
  for (unsigned int i = 0; i < _nargs; ++i)
  {
    _tol[i] = -1.0;

    // for every argument look throug the entire tolerance vector to find a match
    for (unsigned int j = 0; j < tol_names.size(); ++j)
      if (_arg_names[i] == tol_names[j])
      {
        _tol[i] = tol_values[j];
        break;
      }
  }

  // build 'variables' argument for fparser
  std::string variables;
  switch (_map_mode)
  {
    case USE_MOOSE_NAMES:
      variables = _arg_names[0];
      for (unsigned i = 1; i < _nargs; ++i)
        variables += "," + _arg_names[i];
      break;

    case USE_PARAM_NAMES:
      // we do not allow vector coupling in this mode
      if (!_mapping_is_unique)
        mooseError("Derivative parsed materials must couple exactly one non-linear variable per coupled variable input parameter.");

      variables = _arg_param_names[0];
      for (unsigned i = 1; i < _nargs; ++i)
        variables += "," + _arg_param_names[i];
      break;

    default:
      mooseError("Unnknown variable mapping mode.");
  }

  // get all material properties
  _nmat_props = mat_prop_names.size();
  _mat_props.resize(_nmat_props);
  for (unsigned int i = 0; i < _nmat_props; ++i)
  {
    _mat_props[i] = &getMaterialProperty<Real>(mat_prop_names[i]);
    variables += "," + mat_prop_names[i];
  }

  // build the base function
  if (_func_F->Parse(function_expression, variables) >= 0)
     mooseError(std::string("Invalid function\n" + function_expression + "\nin DerivativeParsedMaterialHelper.\n") + _func_F->ErrorMsg());

  // Auto-Derivatives
  functionsDerivative();

  // Optimization
  functionsOptimize();

  // create parameter passing buffer
  _func_params = new Real[_nargs + _nmat_props];
}

void DerivativeParsedMaterialHelper::functionsDerivative()
{
  unsigned int i, j, k;

  // first derivatives
  _func_dF.resize(_nargs);
  _func_d2F.resize(_nargs);
  _func_d3F.resize(_nargs);
  for (i = 0; i < _nargs; ++i)
  {
    _func_dF[i] = new ADFunction(*_func_F);
    if (_func_dF[i]->AutoDiff(_arg_names[i]) != -1)
      mooseError("Failed to take first derivative.");

    // second derivatives
    _func_d2F[i].resize(_nargs);
    _func_d3F[i].resize(_nargs);
    for (j = i; j < _nargs; ++j)
    {
      _func_d2F[i][j] = new ADFunction(*_func_dF[i]);
      if (_func_d2F[i][j]->AutoDiff(_arg_names[j]) != -1)
        mooseError("Failed to take second derivative.");

      // third derivatives
      if (_third_derivatives)
      {
        _func_d3F[i][j].resize(_nargs);
        for (k = j; k < _nargs; ++k)
        {
          _func_d3F[i][j][k] = new ADFunction(*_func_d2F[i][j]);
          if (_func_d3F[i][j][k]->AutoDiff(_arg_names[k]) != -1)
            mooseError("Failed to take third derivative.");
        }
      }
    }
  }
}

void DerivativeParsedMaterialHelper::functionsOptimize()
{
  unsigned int i, j, k;

  // base function
  if (!_disable_fpoptimizer)
    _func_F->Optimize();
  if (_enable_jit && !_func_F->JITCompile())
    mooseWarning("Failed to JIT compile expression, falling back to byte code interpretation.");

  // optimize first derivatives
  for (i = 0; i < _nargs; ++i)
  {
    if (!_disable_fpoptimizer)
      _func_dF[i]->Optimize();
    if (_enable_jit && !_func_dF[i]->JITCompile())
      mooseWarning("Failed to JIT compile expression, falling back to byte code interpretation.");

    // if the derivative vanishes set the function back to NULL
    if (_func_dF[i]->isZero())
    {
      delete _func_dF[i];
      _func_dF[i] = NULL;
    }

    // optimize second derivatives
    for (j = i; j < _nargs; ++j)
    {
      if (!_disable_fpoptimizer)
        _func_d2F[i][j]->Optimize();
      if (_enable_jit && !_func_d2F[i][j]->JITCompile())
        mooseWarning("Failed to JIT compile expression, falling back to byte code interpretation.");

      // if the derivative vanishes set the function back to NULL
      if (_func_d2F[i][j]->isZero())
      {
        delete _func_d2F[i][j];
        _func_d2F[i][j] = NULL;
      }

      // optimize third derivatives
      if (_third_derivatives)
      {
        for (k = j; k < _nargs; ++k)
        {
          if (!_disable_fpoptimizer)
            _func_d3F[i][j][k]->Optimize();
          if (_enable_jit && !_func_d3F[i][j][k]->JITCompile())
            mooseWarning("Failed to JIT compile expression, falling back to byte code interpretation.");

          // if the derivative vanishes set the function back to NULL
          if (_func_d3F[i][j][k]->isZero())
          {
            delete _func_d3F[i][j][k];
            _func_d3F[i][j][k] = NULL;
          }
        }
      }
    }
  }
}

/// need to implment these virtuals, although they never get called
Real DerivativeParsedMaterialHelper::computeF() { return 0.0; }
Real DerivativeParsedMaterialHelper::computeDF(unsigned int) { return 0.0; }
Real DerivativeParsedMaterialHelper::computeD2F(unsigned int, unsigned int) { return 0.0; }

Real
DerivativeParsedMaterialHelper::evaluate(ADFunction * parser)
{
  // null pointer is a shortcut for vanishing derivatives, see functionsOptimize()
  if (parser == NULL) return 0.0;

  // evaluate expression
  Real result = parser->Eval(_func_params);

  // fetch fparser evaluation error
  int error_code = parser->EvalError();

  // no error
  if (error_code == 0)
    return result;

  // hard fail or return not a number
  if (_fail_on_evalerror)
    mooseError("DerivativeParsedMaterial function evaluation encountered an error: "
               << _eval_error_msg[(error_code < 0 || error_code > 5) ? 0 : error_code]);

  return _nan;
}

void
DerivativeParsedMaterialHelper::computeProperties()
{
  unsigned int i, j, k;
  Real a;

  for (_qp = 0; _qp < _qrule->n_points(); _qp++)
  {
    // fill the parameter vector, apply tolerances
    for (i = 0; i < _nargs; ++i)
    {
      if (_tol[i] < 0.0)
        _func_params[i] = (*_args[i])[_qp];
      else
      {
        a = (*_args[i])[_qp];
        _func_params[i] = a < _tol[i] ? _tol[i] : (a > 1.0 - _tol[i] ? 1.0 - _tol[i] : a);
      }
    }

    // insert material property values
    for (i = 0; i < _nmat_props; ++i)
      _func_params[i + _nargs] = (*_mat_props[i])[_qp];

    // set function value
    if (_prop_F)
      (*_prop_F)[_qp] = evaluate(_func_F);

    for (i = 0; i < _nargs; ++i)
    {
      if (_prop_dF[i])
        (*_prop_dF[i])[_qp] = evaluate(_func_dF[i]);

      // second derivatives
      for (j = i; j < _nargs; ++j)
      {
        if (_prop_d2F[i][j])
          (*_prop_d2F[i][j])[_qp] = evaluate(_func_d2F[i][j]);

        // third derivatives
        if (_third_derivatives)
          for (k = j; k < _nargs; ++k)
            if (_prop_d3F[i][j][k])
              (*_prop_d3F[i][j][k])[_qp] = evaluate(_func_d3F[i][j][k]);
      }
    }
  }
}
<commit_msg>Better error messages (#4441)<commit_after>#include "DerivativeParsedMaterialHelper.h"

template<>
InputParameters validParams<DerivativeParsedMaterialHelper>()
{
  InputParameters params = validParams<DerivativeBaseMaterial>();
  params.addClassDescription("Parsed Function Material with automatic derivatives.");

  // Just in time compilation for the FParser objects
#ifdef LIBMESH_HAVE_FPARSER_JIT
  params.addParam<bool>( "enable_jit", false, "Enable Just In Time compilation of the parsed functions");
#endif
  params.addParam<bool>( "disable_fpoptimizer", false, "Disable the function parser algebraic optimizer");
  params.addParam<bool>( "fail_on_evalerror", false, "Fail fatally if a function evaluation returns an error code (otherwise just pass on NaN)");
  return params;
}

const char * DerivativeParsedMaterialHelper::_eval_error_msg[] = {
  "Unknown",
  "Division by zero",
  "Square root of a negative value",
  "Logarithm of negative value",
  "Trigonometric error (asin or acos of illegal value)",
  "Maximum recursion level reached"
};

DerivativeParsedMaterialHelper::DerivativeParsedMaterialHelper(const std::string & name,
                                                               InputParameters parameters,
                                                               VariableNameMappingMode map_mode) :
    DerivativeBaseMaterial(name, parameters),
    _func_F(NULL),
    _nmat_props(0),
    _enable_jit(isParamValid("enable_jit") && getParam<bool>("enable_jit")),
    _disable_fpoptimizer(getParam<bool>("disable_fpoptimizer")),
    _fail_on_evalerror(getParam<bool>("fail_on_evalerror")),
    _map_mode(map_mode),
    _nan(std::numeric_limits<Real>::quiet_NaN())
{
}

DerivativeParsedMaterialHelper::~DerivativeParsedMaterialHelper()
{
  delete[] _func_params;
}

void DerivativeParsedMaterialHelper::functionParse(const std::string & function_expression)
{
  std::vector<std::string> empty_string_vector;
  functionParse(function_expression,
                empty_string_vector, empty_string_vector);
}

void DerivativeParsedMaterialHelper::functionParse(const std::string & function_expression,
                                                   const std::vector<std::string> & constant_names,
                                                   const std::vector<std::string> & constant_expressions)
{
  std::vector<std::string> empty_string_vector;
  std::vector<Real> empty_real_vector;
  functionParse(function_expression, constant_names, constant_expressions,
                empty_string_vector, empty_string_vector, empty_real_vector);
}

void DerivativeParsedMaterialHelper::functionParse(const std::string & function_expression,
                                                   const std::vector<std::string> & constant_names,
                                                   const std::vector<std::string> & constant_expressions,
                                                   const std::vector<std::string> & mat_prop_names,
                                                   const std::vector<std::string> & tol_names,
                                                   const std::vector<Real> & tol_values)
{
  // check number of coupled variables
  if (_nargs == 0)
    mooseError("Need at least one coupled variable for DerivativeParsedMaterialHelper.");

  // check constant vectors
  unsigned int nconst = constant_expressions.size();
  if (nconst != constant_expressions.size())
    mooseError("The parameter vectors constant_names and constant_values must have equal length.");

  // build base function object
  _func_F =  new ADFunction();

  // initialize constants
  ADFunction *expression;
  std::vector<Real> constant_values(nconst);
  for (unsigned int i = 0; i < nconst; ++i)
  {
    expression = new ADFunction();

    // add previously evaluated constants
    for (unsigned int j = 0; j < i; ++j)
      if (!expression->AddConstant(constant_names[j], constant_values[j]))
        mooseError("Invalid constant name in DerivativeParsedMaterialHelper");

    // build the temporary comnstant expression function
    if (expression->Parse(constant_expressions[i], "") >= 0)
       mooseError(std::string("Invalid constant expression\n" + constant_expressions[i] + "\n in DerivativeParsedMaterialHelper. ") + expression->ErrorMsg());

    constant_values[i] = expression->Eval(NULL);

#ifdef DEBUG
    _console << "Constant value " << i << ' ' << constant_expressions[i] << " = " << constant_values[i] << std::endl;
#endif

    if (!_func_F->AddConstant(constant_names[i], constant_values[i]))
      mooseError("Invalid constant name in DerivativeParsedMaterialHelper");

    delete expression;
  }

  // tolerance vectors
  if (tol_names.size() != tol_values.size())
    mooseError("The parameter vectors tol_names and tol_values must have equal length.");

  // set tolerances
  _tol.resize(_nargs);
  for (unsigned int i = 0; i < _nargs; ++i)
  {
    _tol[i] = -1.0;

    // for every argument look throug the entire tolerance vector to find a match
    for (unsigned int j = 0; j < tol_names.size(); ++j)
      if (_arg_names[i] == tol_names[j])
      {
        _tol[i] = tol_values[j];
        break;
      }
  }

  // build 'variables' argument for fparser
  std::string variables;
  switch (_map_mode)
  {
    case USE_MOOSE_NAMES:
      variables = _arg_names[0];
      for (unsigned i = 1; i < _nargs; ++i)
        variables += "," + _arg_names[i];
      break;

    case USE_PARAM_NAMES:
      // we do not allow vector coupling in this mode
      if (!_mapping_is_unique)
        mooseError("Derivative parsed materials must couple exactly one non-linear variable per coupled variable input parameter.");

      variables = _arg_param_names[0];
      for (unsigned i = 1; i < _nargs; ++i)
        variables += "," + _arg_param_names[i];
      break;

    default:
      mooseError("Unnknown variable mapping mode.");
  }

  // get all material properties
  _nmat_props = mat_prop_names.size();
  _mat_props.resize(_nmat_props);
  for (unsigned int i = 0; i < _nmat_props; ++i)
  {
    _mat_props[i] = &getMaterialProperty<Real>(mat_prop_names[i]);
    variables += "," + mat_prop_names[i];
  }

  // build the base function
  if (_func_F->Parse(function_expression, variables) >= 0)
     mooseError(std::string("Invalid function\n" + function_expression + "\nin DerivativeParsedMaterialHelper.\n") + _func_F->ErrorMsg());

  // Auto-Derivatives
  functionsDerivative();

  // Optimization
  functionsOptimize();

  // create parameter passing buffer
  _func_params = new Real[_nargs + _nmat_props];
}

void DerivativeParsedMaterialHelper::functionsDerivative()
{
  unsigned int i, j, k;

  // first derivatives
  _func_dF.resize(_nargs);
  _func_d2F.resize(_nargs);
  _func_d3F.resize(_nargs);
  for (i = 0; i < _nargs; ++i)
  {
    _func_dF[i] = new ADFunction(*_func_F);
    if (_func_dF[i]->AutoDiff(_arg_names[i]) != -1)
      mooseError("Failed to take first derivative w.r.t. "
                 << _arg_names[i]);

    // second derivatives
    _func_d2F[i].resize(_nargs);
    _func_d3F[i].resize(_nargs);
    for (j = i; j < _nargs; ++j)
    {
      _func_d2F[i][j] = new ADFunction(*_func_dF[i]);
      if (_func_d2F[i][j]->AutoDiff(_arg_names[j]) != -1)
        mooseError("Failed to take second derivative w.r.t. "
                   << _arg_names[i] << " and " << _arg_names[j]);

      // third derivatives
      if (_third_derivatives)
      {
        _func_d3F[i][j].resize(_nargs);
        for (k = j; k < _nargs; ++k)
        {
          _func_d3F[i][j][k] = new ADFunction(*_func_d2F[i][j]);
          if (_func_d3F[i][j][k]->AutoDiff(_arg_names[k]) != -1)
            mooseError("Failed to take third derivative w.r.t. "
                       << _arg_names[i] << ", " << _arg_names[j] << ", and " << _arg_names[k]);
        }
      }
    }
  }
}

void DerivativeParsedMaterialHelper::functionsOptimize()
{
  unsigned int i, j, k;

  // base function
  if (!_disable_fpoptimizer)
    _func_F->Optimize();
  if (_enable_jit && !_func_F->JITCompile())
    mooseWarning("Failed to JIT compile expression, falling back to byte code interpretation.");

  // optimize first derivatives
  for (i = 0; i < _nargs; ++i)
  {
    if (!_disable_fpoptimizer)
      _func_dF[i]->Optimize();
    if (_enable_jit && !_func_dF[i]->JITCompile())
      mooseWarning("Failed to JIT compile expression, falling back to byte code interpretation.");

    // if the derivative vanishes set the function back to NULL
    if (_func_dF[i]->isZero())
    {
      delete _func_dF[i];
      _func_dF[i] = NULL;
    }

    // optimize second derivatives
    for (j = i; j < _nargs; ++j)
    {
      if (!_disable_fpoptimizer)
        _func_d2F[i][j]->Optimize();
      if (_enable_jit && !_func_d2F[i][j]->JITCompile())
        mooseWarning("Failed to JIT compile expression, falling back to byte code interpretation.");

      // if the derivative vanishes set the function back to NULL
      if (_func_d2F[i][j]->isZero())
      {
        delete _func_d2F[i][j];
        _func_d2F[i][j] = NULL;
      }

      // optimize third derivatives
      if (_third_derivatives)
      {
        for (k = j; k < _nargs; ++k)
        {
          if (!_disable_fpoptimizer)
            _func_d3F[i][j][k]->Optimize();
          if (_enable_jit && !_func_d3F[i][j][k]->JITCompile())
            mooseWarning("Failed to JIT compile expression, falling back to byte code interpretation.");

          // if the derivative vanishes set the function back to NULL
          if (_func_d3F[i][j][k]->isZero())
          {
            delete _func_d3F[i][j][k];
            _func_d3F[i][j][k] = NULL;
          }
        }
      }
    }
  }
}

/// need to implment these virtuals, although they never get called
Real DerivativeParsedMaterialHelper::computeF() { return 0.0; }
Real DerivativeParsedMaterialHelper::computeDF(unsigned int) { return 0.0; }
Real DerivativeParsedMaterialHelper::computeD2F(unsigned int, unsigned int) { return 0.0; }

Real
DerivativeParsedMaterialHelper::evaluate(ADFunction * parser)
{
  // null pointer is a shortcut for vanishing derivatives, see functionsOptimize()
  if (parser == NULL) return 0.0;

  // evaluate expression
  Real result = parser->Eval(_func_params);

  // fetch fparser evaluation error
  int error_code = parser->EvalError();

  // no error
  if (error_code == 0)
    return result;

  // hard fail or return not a number
  if (_fail_on_evalerror)
    mooseError("DerivativeParsedMaterial function evaluation encountered an error: "
               << _eval_error_msg[(error_code < 0 || error_code > 5) ? 0 : error_code]);

  return _nan;
}

void
DerivativeParsedMaterialHelper::computeProperties()
{
  unsigned int i, j, k;
  Real a;

  for (_qp = 0; _qp < _qrule->n_points(); _qp++)
  {
    // fill the parameter vector, apply tolerances
    for (i = 0; i < _nargs; ++i)
    {
      if (_tol[i] < 0.0)
        _func_params[i] = (*_args[i])[_qp];
      else
      {
        a = (*_args[i])[_qp];
        _func_params[i] = a < _tol[i] ? _tol[i] : (a > 1.0 - _tol[i] ? 1.0 - _tol[i] : a);
      }
    }

    // insert material property values
    for (i = 0; i < _nmat_props; ++i)
      _func_params[i + _nargs] = (*_mat_props[i])[_qp];

    // set function value
    if (_prop_F)
      (*_prop_F)[_qp] = evaluate(_func_F);

    for (i = 0; i < _nargs; ++i)
    {
      if (_prop_dF[i])
        (*_prop_dF[i])[_qp] = evaluate(_func_dF[i]);

      // second derivatives
      for (j = i; j < _nargs; ++j)
      {
        if (_prop_d2F[i][j])
          (*_prop_d2F[i][j])[_qp] = evaluate(_func_d2F[i][j]);

        // third derivatives
        if (_third_derivatives)
          for (k = j; k < _nargs; ++k)
            if (_prop_d3F[i][j][k])
              (*_prop_d3F[i][j][k])[_qp] = evaluate(_func_d3F[i][j][k]);
      }
    }
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015 SeNDA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
/**
 * FILE BasicBundleProcessor.cpp
 * AUTHOR Blackcatn13
 * DATE Dec 17, 2015
 * VERSION 1
 *
 */

#include "Node/BundleProcessor/BasicBundleProcessor.h"
#include <memory>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
#include <functional>
#include "Node/BundleProcessor/BundleProcessor.h"
#include "Node/BundleQueue/BundleQueue.h"
#include "Node/Neighbour/NeighbourTable.h"
#include "Node/Neighbour/Neighbour.h"
#include "Node/Config.h"
#include "Node/BundleQueue/BundleContainer.h"
#include "Bundle/Bundle.h"
#include "Bundle/BundleInfo.h"
#include "Bundle/PrimaryBlock.h"
#include "Utils/Logger.h"
#include "Utils/TimestampManager.h"
#include "Node/EndpointListener/ListeningEndpointsTable.h"
#include "Node/BundleProcessor/RoutingSelectionBundleProcessor.h"
#include "Node/BundleProcessor/PluginAPI.h"
#include "Utils/globals.h"

#ifdef BASE_PLUGIN
NEW_PLUGIN(BasicBundleProcessor,
    "Basic bundle processor", "1.0",
    "Forwards a bundle this processor only checks for anti-rebooting.")
#endif

const std::string BasicBundleProcessor::m_forwardHeader = "#include <vector>\n"
    "#include <string>\n"
    "#include <algorithm>\n"
    "#include <cstdlib>\n"
    "#include \"adtnPlus/Json.h\"\n"
    "extern \"C\" {"
    " std::vector<std::string> f(Json ns) {";
const std::string BasicBundleProcessor::m_lifeHeader = "#include <cstdint>\n"
    "#include \"Bundle/BundleInfo.h\"\n"
    "#include \"adtnPlus/Json.h\"\n"
    "extern \"C\" {"
    "const uint64_t g_timeFrom2000 = 946684800;"
    "bool f(Json ns, BundleInfo bi) {";
const std::string BasicBundleProcessor::m_destinationHeader =
    "#include <string>\n"
        "#include \"adtnPlus/Json.h\"\n"
        "#include \"Bundle/BundleInfo.h\"\n"
        "extern \"C\" {"
        "bool f(Json ns, BundleInfo bi) {";
const std::string BasicBundleProcessor::m_footer = "}}";
const std::string BasicBundleProcessor::m_commandLine =
    "g++ -w -fPIC -shared -std=c++11 %s -o %s 2>&1";

BasicBundleProcessor::BasicBundleProcessor()
    : m_forwardWorker(m_forwardHeader, m_footer, "f", m_commandLine, "./"),
      m_lifeWorker(m_lifeHeader, m_footer, "f", m_commandLine, "./"),
      m_destinationWorker(m_destinationHeader, m_footer, "f", m_commandLine,
                          "./") {
}

BasicBundleProcessor::~BasicBundleProcessor() {
  if (!m_nodeState.empty()) {
    std::ofstream nodeState(m_config.getNodeStatePath());
    nodeState << m_nodeState.dump(2);
    nodeState.close();
  }
}

void BasicBundleProcessor::start(
    Config config, std::shared_ptr<BundleQueue> bundleQueue,
    std::shared_ptr<NeighbourTable> neighbourTable,
    std::shared_ptr<ListeningEndpointsTable> listeningAppsTable) {
  BundleProcessor::start(config, bundleQueue, neighbourTable,
                         listeningAppsTable);
  std::ifstream nodeState(m_config.getNodeStatePath());
  m_nodeState.start(std::bind(&NeighbourTable::getValues, m_neighbourTable));
  m_forwardWorker.setPath(m_config.getCodesPath());
  m_lifeWorker.setPath(m_config.getCodesPath());
  m_destinationWorker.setPath(m_config.getCodesPath());
  if (nodeState) {
    try {
      nodeState >> m_nodeState;
      m_oldNodeState = m_nodeState;
      nodeState.close();
      std::string defaultForwardingCode =
          m_nodeState["configuration"]["defaultCodes"]["forwarding"];
      std::string defaultLifeCode =
          m_nodeState["configuration"]["defaultCodes"]["lifetime"];
      std::string defaultDestinationCode =
          m_nodeState["configuration"]["defaultCodes"]["destination"];
      try {
        m_forwardWorker.generateFunction(defaultForwardingCode);
        m_lifeWorker.generateFunction(defaultLifeCode);
        m_destinationWorker.generateFunction(defaultDestinationCode);
      } catch (const WorkerException &e) {
        LOG(11) << "Cannot create code worker, reason: " << e.what();
      }
    } catch (const std::invalid_argument &e) {
      LOG(1) << "Error in NodeState json: " << e.what();
      g_stop = true;
    }
  } else {
    LOG(11) << "Cannot open the file " << m_config.getNodeStatePath();
  }
}

void BasicBundleProcessor::processBundle(
    std::unique_ptr<BundleContainer> bundleContainer) {
  LOG(51) << "Processing a bundle container.";
  LOG(55) << "Checking destination node.";
  if (checkDestination(*bundleContainer)) {
    LOG(55) << "We are the destination node.";
    LOG(55) << "Checking destination app listening.";
    std::vector<std::string> destinations = checkDispatch(*bundleContainer);
    if (destinations.size() > 0) {
      LOG(55) << "There is a listening app, dispatching the bundle.";
      try {
        dispatch(bundleContainer->getBundle(), destinations);
        discard(std::move(bundleContainer));
      } catch (const TableException &e) {
        LOG(55) << "Restoring not dispatched bundle.";
        restore(std::move(bundleContainer));
      }
    } else {
      LOG(55) << "No listening app, restoring the bundle.";
      restore(std::move(bundleContainer));
    }
  } else {
    LOG(55) << "We are not the destination node.";
    LOG(55) << "Checking lifetime.";
    if (checkLifetime(*bundleContainer)) {
      LOG(55) << "Bundle expired, discarding it.";
      discard(std::move(bundleContainer));
    } else {
      LOG(55) << "Bundle is not expired yet.";
      LOG(55) << "Checking neighbours. " << "";
      std::vector<std::string> neighbours = checkForward(*bundleContainer);
      if (neighbours.size() > 0) {
        LOG(55) << "There are some neighbours.";
        LOG(55) << "Checking if one of them is the bundle destination.";
        auto it = std::find(
            neighbours.begin(),
            neighbours.end(),
            bundleContainer->getBundle().getPrimaryBlock()->getDestination()
                .substr(
                0,
                bundleContainer->getBundle().getPrimaryBlock()->getDestination()
                    .find(":")));
        if (it != neighbours.end()) {
          LOG(55) << "Destination found, sending the bundle to it.";
          std::vector<std::string> nextHop = std::vector<std::string>();
          nextHop.push_back(*it);
          try {
            forward(bundleContainer->getBundle(), nextHop);
            LOG(55) << "Discarding the bundle.";
            discard(std::move(bundleContainer));
          } catch (const ForwardException &e) {
            LOG(1) << e.what();
            LOG(55) << "The bundle has not been send, restoring the bundle.";
            restore(std::move(bundleContainer));
          }
        } else {
          LOG(55) << "Destination not found, "
                  << "sending the bundle to all the neighbours.";
          try {
            forward(bundleContainer->getBundle(), neighbours);
            LOG(55) << "Discarding the bundle.";
            discard(std::move(bundleContainer));
          } catch (const ForwardException &e) {
            LOG(1) << e.what();
            LOG(55) << "The bundle has not been send, restoring the bundle.";
            restore(std::move(bundleContainer));
          }
        }
      } else {
        LOG(55) << "No neighbours found, restoring the bundle.";
        restore(std::move(bundleContainer));
      }
    }
  }
  checkNodeStateChanges();
}

std::unique_ptr<BundleContainer> BasicBundleProcessor::createBundleContainer(
    std::unique_ptr<Bundle> bundle) {
  return std::unique_ptr<BundleContainer>(
      new BundleContainer(std::move(bundle)));
}

bool BasicBundleProcessor::checkDestination(BundleContainer &bundleContainer) {
  try {
    BundleInfo bi = BundleInfo(bundleContainer.getBundle());
    m_destinationWorker.execute(m_nodeState, bi);
    return m_destinationWorker.getResult();
  } catch (const WorkerException &e) {
    LOG(11) << "Cannot execute code, reason: " << e.what();
  }
  return false;
}

std::vector<std::string> BasicBundleProcessor::checkDispatch(
    BundleContainer &bundleContainer) {
  std::string destination = bundleContainer.getBundle().getPrimaryBlock()
      ->getDestination();
  std::string appId = destination.substr(destination.find(":") + 1);
  std::vector<std::string> dispatch;
  dispatch.push_back(appId);
  return dispatch;
}

std::vector<std::string> BasicBundleProcessor::checkForward(
    BundleContainer &bundleContainer) {
  std::vector<std::string> neighbours = m_neighbourTable->getValues();
  try {
    m_forwardWorker.execute(m_nodeState);
    return m_forwardWorker.getResult();
  } catch (const WorkerException &e) {
    LOG(11) << "Cannot execute code, reason: " << e.what()
            << " Executing flooding.";
    return neighbours;
  }
}

bool BasicBundleProcessor::checkLifetime(BundleContainer &bundleContainer) {
  try {
    BundleInfo bi = BundleInfo(bundleContainer.getBundle());
    m_lifeWorker.execute(m_nodeState, bi);
    return m_lifeWorker.getResult();
  } catch (const WorkerException &e) {
    LOG(11) << "Cannot create code worker, reason: " << e.what();
  }
  return false;
}

void BasicBundleProcessor::checkNodeStateChanges() {
  if (m_nodeState["state"]["changed"]) {
    m_nodeState["state"]["changed"] = false;
    // Check what changed and act accordingly
    if (m_nodeState["state"]["stop"]) {
      m_nodeState["state"]["stop"] = false;
      g_stop = true;
    }
    if (m_nodeState["configuration"]["logLevel"]
        != m_oldNodeState["configuration"]["logLevel"]) {
      Logger::getInstance()->setLogLevel(
          m_nodeState["configuration"]["logLevel"]);
    }
    std::string code =
        m_nodeState["configuration"]["defaultCodes"]["forwarding"];
    if (code.compare(
        m_oldNodeState["configuration"]["defaultCodes"]["forwarding"]) != 0) {
      try {
        m_forwardWorker.generateFunction(code);
      } catch (const WorkerException &e) {
        LOG(11) << "Cannot create forward code worker, reason: " << e.what();
      }
    }
    code = m_nodeState["configuration"]["defaultCodes"]["lifetime"];
    if (code.compare(
        m_oldNodeState["configuration"]["defaultCodes"]["lifetime"]) != 0) {
      try {
        m_lifeWorker.generateFunction(code);
      } catch (const WorkerException &e) {
        LOG(11) << "Cannot create life code worker, reason: " << e.what();
      }
    }
    m_oldNodeState = m_nodeState;
  }
}
<commit_msg>Updates BasicBundleProcessor to return the nodes to forward from the given endpoints.<commit_after>/*
 * Copyright (c) 2015 SeNDA
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
/**
 * FILE BasicBundleProcessor.cpp
 * AUTHOR Blackcatn13
 * DATE Dec 17, 2015
 * VERSION 1
 *
 */

#include "Node/BundleProcessor/BasicBundleProcessor.h"
#include <memory>
#include <vector>
#include <string>
#include <algorithm>
#include <fstream>
#include <functional>
#include "Node/BundleProcessor/BundleProcessor.h"
#include "Node/BundleQueue/BundleQueue.h"
#include "Node/Neighbour/NeighbourTable.h"
#include "Node/Neighbour/Neighbour.h"
#include "Node/Config.h"
#include "Node/BundleQueue/BundleContainer.h"
#include "Bundle/Bundle.h"
#include "Bundle/BundleInfo.h"
#include "Bundle/PrimaryBlock.h"
#include "Utils/Logger.h"
#include "Utils/TimestampManager.h"
#include "Node/EndpointListener/ListeningEndpointsTable.h"
#include "Node/BundleProcessor/RoutingSelectionBundleProcessor.h"
#include "Node/BundleProcessor/PluginAPI.h"
#include "Utils/globals.h"

#ifdef BASE_PLUGIN
NEW_PLUGIN(BasicBundleProcessor,
    "Basic bundle processor", "1.0",
    "Forwards a bundle this processor only checks for anti-rebooting.")
#endif

const std::string BasicBundleProcessor::m_forwardHeader = "#include <vector>\n"
    "#include <string>\n"
    "#include <algorithm>\n"
    "#include <cstdlib>\n"
    "#include \"adtnPlus/Json.h\"\n"
    "extern \"C\" {"
    " std::vector<std::string> f(Json ns) {";
const std::string BasicBundleProcessor::m_lifeHeader = "#include <cstdint>\n"
    "#include \"Bundle/BundleInfo.h\"\n"
    "#include \"adtnPlus/Json.h\"\n"
    "extern \"C\" {"
    "const uint64_t g_timeFrom2000 = 946684800;"
    "bool f(Json ns, BundleInfo bi) {";
const std::string BasicBundleProcessor::m_destinationHeader =
    "#include <string>\n"
        "#include \"adtnPlus/Json.h\"\n"
        "#include \"Bundle/BundleInfo.h\"\n"
        "extern \"C\" {"
        "bool f(Json ns, BundleInfo bi) {";
const std::string BasicBundleProcessor::m_footer = "}}";
const std::string BasicBundleProcessor::m_commandLine =
    "g++ -w -fPIC -shared -std=c++11 %s -o %s 2>&1";

BasicBundleProcessor::BasicBundleProcessor()
    : m_forwardWorker(m_forwardHeader, m_footer, "f", m_commandLine, "./"),
      m_lifeWorker(m_lifeHeader, m_footer, "f", m_commandLine, "./"),
      m_destinationWorker(m_destinationHeader, m_footer, "f", m_commandLine,
                          "./") {
}

BasicBundleProcessor::~BasicBundleProcessor() {
  if (!m_nodeState.empty()) {
    std::ofstream nodeState(m_config.getNodeStatePath());
    nodeState << m_nodeState.dump(2);
    nodeState.close();
  }
}

void BasicBundleProcessor::start(
    Config config, std::shared_ptr<BundleQueue> bundleQueue,
    std::shared_ptr<NeighbourTable> neighbourTable,
    std::shared_ptr<ListeningEndpointsTable> listeningAppsTable) {
  BundleProcessor::start(config, bundleQueue, neighbourTable,
                         listeningAppsTable);
  std::ifstream nodeState(m_config.getNodeStatePath());
  m_nodeState.start(std::bind(&NeighbourTable::getValues, m_neighbourTable));
  m_forwardWorker.setPath(m_config.getCodesPath());
  m_lifeWorker.setPath(m_config.getCodesPath());
  m_destinationWorker.setPath(m_config.getCodesPath());
  if (nodeState) {
    try {
      nodeState >> m_nodeState;
      m_oldNodeState = m_nodeState;
      nodeState.close();
      std::string defaultForwardingCode =
          m_nodeState["configuration"]["defaultCodes"]["forwarding"];
      std::string defaultLifeCode =
          m_nodeState["configuration"]["defaultCodes"]["lifetime"];
      std::string defaultDestinationCode =
          m_nodeState["configuration"]["defaultCodes"]["destination"];
      try {
        m_forwardWorker.generateFunction(defaultForwardingCode);
        m_lifeWorker.generateFunction(defaultLifeCode);
        m_destinationWorker.generateFunction(defaultDestinationCode);
      } catch (const WorkerException &e) {
        LOG(11) << "Cannot create code worker, reason: " << e.what();
      }
    } catch (const std::invalid_argument &e) {
      LOG(1) << "Error in NodeState json: " << e.what();
      g_stop = true;
    }
  } else {
    LOG(11) << "Cannot open the file " << m_config.getNodeStatePath();
  }
}

void BasicBundleProcessor::processBundle(
    std::unique_ptr<BundleContainer> bundleContainer) {
  LOG(51) << "Processing a bundle container.";
  LOG(55) << "Checking destination node.";
  if (checkDestination(*bundleContainer)) {
    LOG(55) << "We are the destination node.";
    LOG(55) << "Checking destination app listening.";
    std::vector<std::string> destinations = checkDispatch(*bundleContainer);
    if (destinations.size() > 0) {
      LOG(55) << "There is a listening app, dispatching the bundle.";
      try {
        dispatch(bundleContainer->getBundle(), destinations);
        discard(std::move(bundleContainer));
      } catch (const TableException &e) {
        LOG(55) << "Restoring not dispatched bundle.";
        restore(std::move(bundleContainer));
      }
    } else {
      LOG(55) << "No listening app, restoring the bundle.";
      restore(std::move(bundleContainer));
    }
  } else {
    LOG(55) << "We are not the destination node.";
    LOG(55) << "Checking lifetime.";
    if (checkLifetime(*bundleContainer)) {
      LOG(55) << "Bundle expired, discarding it.";
      discard(std::move(bundleContainer));
    } else {
      LOG(55) << "Bundle is not expired yet.";
      LOG(55) << "Checking neighbours. " << "";
      std::vector<std::string> neighbours = checkForward(*bundleContainer);
      if (neighbours.size() > 0) {
        LOG(55) << "There are some neighbours.";
        LOG(55) << "Checking if one of them is the bundle destination.";
        auto it = std::find(
            neighbours.begin(),
            neighbours.end(),
            bundleContainer->getBundle().getPrimaryBlock()->getDestination()
                .substr(
                0,
                bundleContainer->getBundle().getPrimaryBlock()->getDestination()
                    .find(":")));
        if (it != neighbours.end()) {
          LOG(55) << "Destination found, sending the bundle to it.";
          std::vector<std::string> nextHop = std::vector<std::string>();
          nextHop.push_back(*it);
          try {
            forward(bundleContainer->getBundle(), nextHop);
            LOG(55) << "Discarding the bundle.";
            discard(std::move(bundleContainer));
          } catch (const ForwardException &e) {
            LOG(1) << e.what();
            LOG(55) << "The bundle has not been send, restoring the bundle.";
            restore(std::move(bundleContainer));
          }
        } else {
          LOG(55) << "Destination not found, "
                  << "sending the bundle to all the neighbours.";
          try {
            forward(bundleContainer->getBundle(), neighbours);
            LOG(55) << "Discarding the bundle.";
            discard(std::move(bundleContainer));
          } catch (const ForwardException &e) {
            LOG(1) << e.what();
            LOG(55) << "The bundle has not been send, restoring the bundle.";
            restore(std::move(bundleContainer));
          }
        }
      } else {
        LOG(55) << "No neighbours found, restoring the bundle.";
        restore(std::move(bundleContainer));
      }
    }
  }
  checkNodeStateChanges();
}

std::unique_ptr<BundleContainer> BasicBundleProcessor::createBundleContainer(
    std::unique_ptr<Bundle> bundle) {
  return std::unique_ptr<BundleContainer>(
      new BundleContainer(std::move(bundle)));
}

bool BasicBundleProcessor::checkDestination(BundleContainer &bundleContainer) {
  try {
    BundleInfo bi = BundleInfo(bundleContainer.getBundle());
    m_destinationWorker.execute(m_nodeState, bi);
    return m_destinationWorker.getResult();
  } catch (const WorkerException &e) {
    LOG(11) << "Cannot execute code, reason: " << e.what();
  }
  return false;
}

std::vector<std::string> BasicBundleProcessor::checkDispatch(
    BundleContainer &bundleContainer) {
  std::string destination = bundleContainer.getBundle().getPrimaryBlock()
      ->getDestination();
  std::string appId = destination.substr(destination.find(":") + 1);
  std::vector<std::string> dispatch;
  dispatch.push_back(appId);
  return dispatch;
}

std::vector<std::string> BasicBundleProcessor::checkForward(
    BundleContainer &bundleContainer) {
  std::vector<std::string> neighbours = m_neighbourTable->getValues();
  try {
    m_forwardWorker.execute(m_nodeState);
    auto result = m_forwardWorker.getResult();
    return m_neighbourTable->getMinNeighbours(result);
  } catch (const WorkerException &e) {
    LOG(11) << "Cannot execute code, reason: " << e.what()
            << " Executing flooding.";
    return neighbours;
  }
}

bool BasicBundleProcessor::checkLifetime(BundleContainer &bundleContainer) {
  try {
    BundleInfo bi = BundleInfo(bundleContainer.getBundle());
    m_lifeWorker.execute(m_nodeState, bi);
    return m_lifeWorker.getResult();
  } catch (const WorkerException &e) {
    LOG(11) << "Cannot create code worker, reason: " << e.what();
  }
  return false;
}

void BasicBundleProcessor::checkNodeStateChanges() {
  if (m_nodeState["state"]["changed"]) {
    m_nodeState["state"]["changed"] = false;
    // Check what changed and act accordingly
    if (m_nodeState["state"]["stop"]) {
      m_nodeState["state"]["stop"] = false;
      g_stop = true;
    }
    if (m_nodeState["configuration"]["logLevel"]
        != m_oldNodeState["configuration"]["logLevel"]) {
      Logger::getInstance()->setLogLevel(
          m_nodeState["configuration"]["logLevel"]);
    }
    std::string code =
        m_nodeState["configuration"]["defaultCodes"]["forwarding"];
    if (code.compare(
        m_oldNodeState["configuration"]["defaultCodes"]["forwarding"]) != 0) {
      try {
        m_forwardWorker.generateFunction(code);
      } catch (const WorkerException &e) {
        LOG(11) << "Cannot create forward code worker, reason: " << e.what();
      }
    }
    code = m_nodeState["configuration"]["defaultCodes"]["lifetime"];
    if (code.compare(
        m_oldNodeState["configuration"]["defaultCodes"]["lifetime"]) != 0) {
      try {
        m_lifeWorker.generateFunction(code);
      } catch (const WorkerException &e) {
        LOG(11) << "Cannot create life code worker, reason: " << e.what();
      }
    }
    m_oldNodeState = m_nodeState;
  }
}
<|endoftext|>


<commit_before>#include <irtkBep.h>

int Zcheck = 0;

void usage()
{
	cerr << "Usage: bep [originalsequence] [transformation] [PointSet] [ResultOutput] [MaxOutput] [SegmentationOutput]" << endl;
	cerr << "where PointSet is the sector landmarks of the bull's eye plot" << endl;
	cerr << "AA is the slice landmark between apex and apical" << endl;
	cerr << "AM is the slice landmark between apical and mid" << endl;
	cerr << "MB is the slice landmark between mid and basal" << endl;
	cerr << "-threshold [thresholdname] segmentation information for segmentation"    << endl;
	cerr << "-segmentation [thresholdname] segmentation information for segmentation"    << endl;
	cerr << "-dofprefix [value] transformation filename prefix"    << endl;
	cerr << "-mode [0/1/2/3/4/5] radial/motion/strain/longitudinal strain/ radial and circumferential strain/normalized strain" << endl;
	exit(1);
}

void checkslice(irtkGreyImage& target, int z){
	if(z < 0 || z > target.GetZ()){
		cerr<<"Invaliade z slice number: "<< z <<endl;
		exit(1);
	}
	if(z == target.GetZ() && Zcheck == 0){
		Zcheck == 1;
	}
	if(z == target.GetZ() && Zcheck == 1){
		cerr<<"Invaliade z slice number: "<< z <<endl;
		exit(1);
	}
	return;
}

int main( int argc, char** argv )
{
	irtkGreyImage target,source,late,*interest = NULL;
	irtkPointSet landmarks;
	irtkPointSet olandmarks;
	int tip,aa,am,mb,bottom,swapped,mode,prefix;
	double gap = 0;
	char *outputfilename = NULL;
	char *maxfilename = NULL;
	char *osequence = NULL;
	char *segout = NULL;
	char *thresholdname = NULL;
	char *segmentname = NULL;
	irtkRealImage threshold,compare,segmentation;
	irtkImageAttributes atr;
	irtkBep bf;
	int i,j,k,l,t,ok;
	double x,y,z;

	if( argc < 7 ) usage();

	tip = 0;
	mode = 0;
	prefix = -1;

	// Read image
	cout << "Reading original image: " << argv[1] << endl;
	target.Read(argv[1]);
	argc--;
	argv++;
	osequence = argv[1];
	argc--;
	argv++;
	olandmarks.ReadVTK(argv[1]);
	argc--;
	argv++;
	outputfilename = argv[1];
	argc--;
	argv++;
	maxfilename = argv[1];
	argc--;
	argv++;
	segout = argv[1];
	argc--;
	argv++;
	remove(outputfilename);
	remove(maxfilename);

	while (argc > 1) {
		ok = false;
		if ((ok == false) && (strcmp(argv[1], "-threshold") == 0)) {
			argc--;
			argv++;
			thresholdname = argv[1];
			argc--;
			argv++;
			ok = true;
		}
		if ((ok == false) && (strcmp(argv[1], "-segmentation") == 0)) {
			argc--;
			argv++;
			segmentname = argv[1];
			argc--;
			argv++;
			ok = true;
		}
		if ((ok == false) && (strcmp(argv[1], "-mode") == 0)) {
			argc--;
			argv++;
			mode = atoi(argv[1]);
			argc--;
			argv++;
			ok = true;
		}
		if ((ok == false) && (strcmp(argv[1], "-prefix") == 0)) {
			argc--;
			argv++;
			prefix = atoi(argv[1]);
			argc--;
			argv++;
			ok = true;
		}
		if (ok == false) {
			cerr << "Can not parse argument " << argv[1] << endl;
			usage();
		}
	}

	if(!thresholdname){
		//find out number of time frame
		cerr << "Segmentation result not given please use graphcut4D to generate segmentation"<< endl;
		exit(1);
	}else{
		threshold.Read(thresholdname);
	}

	//Initialize landmark
	if(!segmentname){
		for( i=0; i<olandmarks.Size(); i++){
			target.WorldToImage(olandmarks(i));
		}
		aa = round(olandmarks(5)._z);
		bottom = round(olandmarks(6)._z);
		swapped = 0;
		if(aa>bottom){
			swap(aa,bottom);
			swapped = 1;
		}
		l = 0;
		for( k = aa; k < bottom; k++){
			for( j = 0; j < threshold.GetY(); j++){
				for( i = 0; i < threshold.GetX(); i++){
					if(threshold.GetAsDouble(i,j,k) == 2 && l == 0){
						l = k;
					}
				}
			}
		}
		aa = l;
		gap = (double)(bottom - aa)/3.0;
		am = round(aa + gap);
		mb = round(bottom - gap);
		checkslice(target,aa);
		checkslice(target,am);
		checkslice(target,mb);
		checkslice(target,bottom);
		if(swapped == 1){
			swap(aa,bottom);
			swap(am,mb);
		}
		tip = 0;
	}

	bf.SetInput(target,threshold,osequence);
	if(!segmentname){
		bf.SetLandmarks(olandmarks,tip,aa,am,mb,bottom);
	}
	bf.SetOutput(outputfilename,maxfilename);

	//Generate PointSet from 3 landmarks
	if(!segmentname){
		bf.Initialize();
		bf.GenerateSegmentation(segout);
	}else{
		segmentation.Read(segmentname);
		bf.SetSegmentation(segmentation);
	}

	//Now start
	if(mode == 0)
		bf.AnalysisRadius(prefix);
	else if(mode == 1){
		if(prefix == -1)
			bf.AnalysisMotion();
		else
			bf.AnalysisMotion(prefix);
	}else if(mode >= 2){
		if(prefix == -1)
			bf.AnalysisStrain(3,mode - 2);
		else
			bf.AnalysisStrain(prefix, mode - 2);
	}
	bf.Bullseyeplot();
}<commit_msg>final warnings.<commit_after>#include <irtkBep.h>

int Zcheck = 0;

void usage()
{
	cerr << "Usage: bep [originalsequence] [transformation] [PointSet] [ResultOutput] [MaxOutput] [SegmentationOutput]" << endl;
	cerr << "where PointSet is the sector landmarks of the bull's eye plot" << endl;
	cerr << "AA is the slice landmark between apex and apical" << endl;
	cerr << "AM is the slice landmark between apical and mid" << endl;
	cerr << "MB is the slice landmark between mid and basal" << endl;
	cerr << "-threshold [thresholdname] segmentation information for segmentation"    << endl;
	cerr << "-segmentation [thresholdname] segmentation information for segmentation"    << endl;
	cerr << "-dofprefix [value] transformation filename prefix"    << endl;
	cerr << "-mode [0/1/2/3/4/5] radial/motion/strain/longitudinal strain/ radial and circumferential strain/normalized strain" << endl;
	exit(1);
}

void checkslice(irtkGreyImage& target, int z){
	if(z < 0 || z > target.GetZ()){
		cerr<<"Invaliade z slice number: "<< z <<endl;
		exit(1);
	}
	if(z == target.GetZ() && Zcheck == 0){
		Zcheck == 1;
	}
	if(z == target.GetZ() && Zcheck == 1){
		cerr<<"Invaliade z slice number: "<< z <<endl;
		exit(1);
	}
	return;
}

int main( int argc, char** argv )
{
	irtkGreyImage target,source,late;
	irtkPointSet landmarks;
	irtkPointSet olandmarks;
	int tip,aa,am,mb,bottom,swapped,mode,prefix;
	double gap = 0;
	char *outputfilename = NULL;
	char *maxfilename = NULL;
	char *osequence = NULL;
	char *segout = NULL;
	char *thresholdname = NULL;
	char *segmentname = NULL;
	irtkRealImage threshold,compare,segmentation;
	irtkImageAttributes atr;
	irtkBep bf;
	int i,j,k,l,ok;

	if( argc < 7 ) usage();

	tip = 0;
	mode = 0;
	prefix = -1;
	aa = 0; am = 0; mb = 0; bottom = 0;

	// Read image
	cout << "Reading original image: " << argv[1] << endl;
	target.Read(argv[1]);
	argc--;
	argv++;
	osequence = argv[1];
	argc--;
	argv++;
	olandmarks.ReadVTK(argv[1]);
	argc--;
	argv++;
	outputfilename = argv[1];
	argc--;
	argv++;
	maxfilename = argv[1];
	argc--;
	argv++;
	segout = argv[1];
	argc--;
	argv++;
	remove(outputfilename);
	remove(maxfilename);

	while (argc > 1) {
		ok = false;
		if ((ok == false) && (strcmp(argv[1], "-threshold") == 0)) {
			argc--;
			argv++;
			thresholdname = argv[1];
			argc--;
			argv++;
			ok = true;
		}
		if ((ok == false) && (strcmp(argv[1], "-segmentation") == 0)) {
			argc--;
			argv++;
			segmentname = argv[1];
			argc--;
			argv++;
			ok = true;
		}
		if ((ok == false) && (strcmp(argv[1], "-mode") == 0)) {
			argc--;
			argv++;
			mode = atoi(argv[1]);
			argc--;
			argv++;
			ok = true;
		}
		if ((ok == false) && (strcmp(argv[1], "-prefix") == 0)) {
			argc--;
			argv++;
			prefix = atoi(argv[1]);
			argc--;
			argv++;
			ok = true;
		}
		if (ok == false) {
			cerr << "Can not parse argument " << argv[1] << endl;
			usage();
		}
	}

	if(!thresholdname){
		//find out number of time frame
		cerr << "Segmentation result not given please use graphcut4D to generate segmentation"<< endl;
		exit(1);
	}else{
		threshold.Read(thresholdname);
	}

	//Initialize landmark
	if(!segmentname){
		for( i=0; i<olandmarks.Size(); i++){
			target.WorldToImage(olandmarks(i));
		}
		aa = round(olandmarks(5)._z);
		bottom = round(olandmarks(6)._z);
		swapped = 0;
		if(aa>bottom){
			swap(aa,bottom);
			swapped = 1;
		}
		l = 0;
		for( k = aa; k < bottom; k++){
			for( j = 0; j < threshold.GetY(); j++){
				for( i = 0; i < threshold.GetX(); i++){
					if(threshold.GetAsDouble(i,j,k) == 2 && l == 0){
						l = k;
					}
				}
			}
		}
		aa = l;
		gap = (double)(bottom - aa)/3.0;
		am = round(aa + gap);
		mb = round(bottom - gap);
		checkslice(target,aa);
		checkslice(target,am);
		checkslice(target,mb);
		checkslice(target,bottom);
		if(swapped == 1){
			swap(aa,bottom);
			swap(am,mb);
		}
		tip = 0;
	}

	bf.SetInput(target,threshold,osequence);
	if(!segmentname){
		bf.SetLandmarks(olandmarks,tip,aa,am,mb,bottom);
	}
	bf.SetOutput(outputfilename,maxfilename);

	//Generate PointSet from 3 landmarks
	if(!segmentname){
		bf.Initialize();
		bf.GenerateSegmentation(segout);
	}else{
		segmentation.Read(segmentname);
		bf.SetSegmentation(segmentation);
	}

	//Now start
	if(mode == 0)
		bf.AnalysisRadius(prefix);
	else if(mode == 1){
		if(prefix == -1)
			bf.AnalysisMotion();
		else
			bf.AnalysisMotion(prefix);
	}else if(mode >= 2){
		if(prefix == -1)
			bf.AnalysisStrain(3,mode - 2);
		else
			bf.AnalysisStrain(prefix, mode - 2);
	}
	bf.Bullseyeplot();
}<|endoftext|>