<commit_before>/**************************************************************************
 * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

#include <TClonesArray.h>
#include "AliLog.h"
#include "AliESDVertex.h"
#include "AliRunLoader.h"
#include "AliITSLoader.h"
#include "AliITSgeomTGeo.h"
#include "AliITSRecPoint.h"
#include "AliITSVertexerCosmics.h"
#include "AliStrLine.h"

//------------------------------------------------------------------------
// This class implements a method to construct a "fake" primary
// vertex for cosmic events in which the muon crosses one of 5 inner
// ITS layers. A fake primary vertex is needed for the reconstruction,
// with e.g. AliITStrackerSA, of the two tracks produced by the muon
// in the ITS.
//   We build pairs of clusters on a given layer and define the fake vertex as
// the mid-point of the straight line joining the two clusters.
//   We use the innermost layer that has at least two clusters.
//   We reject the background by requiring at least one cluster on the outer
// layer, closer than fMaxDistOnOuterLayer to the tracklet prolongation.
//   We can reject (potentially pathological) events with the muon track
// tangential to the layer by the requiring the radial position of
// the vertex to be smaller than fMaxVtxRadius.
//   Due to background clusters, more than one vertex per event can
// be found. We consider the first found.
//   The errors on x,y,z of the vertex are calculated as errors on the mean
// of clusters coordinates. Non-diag elements of vertex cov. mat. are set to 0.
//   The number of contributors set in the AliESDVertex object is the
// number of the layer on which the tracklet was built; if this number is -1,
// the procedure could not find a vertex position and by default
// the vertex coordinates are set to (0,0,0) with large errors (100,100,100)
//
// Origin: A.Dainese, andrea.dainese@lnl.infn.it
//-------------------------------------------------------------------------

ClassImp(AliITSVertexerCosmics)

//-------------------------------------------------------------------------
AliITSVertexerCosmics::AliITSVertexerCosmics():AliITSVertexer(),
fMaxDistOnOuterLayer(0),
fMinDist2Vtxs(0)
{
  // Default constructor
  SetFirstLastModules(0,0,79);
  SetFirstLastModules(1,80,239);
  SetFirstLastModules(2,240,323);
  SetFirstLastModules(3,324,499);
  SetFirstLastModules(4,500,1247);
  SetFirstLastModules(5,1248,2197);
  SetMaxVtxRadius(0,3.5);
  SetMaxVtxRadius(1,6.5);
  SetMaxVtxRadius(2,14.5);
  SetMaxVtxRadius(3,23.5);
  SetMaxVtxRadius(4,37.5);
  SetMaxVtxRadius(5,42.5);
  SetMaxDistOnOuterLayer();
  SetMinDist2Vtxs();
}
//--------------------------------------------------------------------------
AliESDVertex* AliITSVertexerCosmics::FindVertexForCurrentEvent(Int_t evnumber)
{
  // Defines the AliESDVertex for the current event

  fCurrentVertex = 0;
  AliRunLoader *rl =AliRunLoader::GetRunLoader();
  AliITSLoader* itsLoader = (AliITSLoader*)rl->GetLoader("ITSLoader");
  itsLoader->LoadRecPoints();
  rl->GetEvent(evnumber);

  TTree *rpTree = itsLoader->TreeR();

  TClonesArray *recpoints=new TClonesArray("AliITSRecPoint",10000);
  rpTree->SetBranchAddress("ITSRecPoints",&recpoints);

  Int_t lay,lad,det;

  // Search for innermost layer with at least two clusters
  // on two different modules
  Int_t ilayer=0;
  while(ilayer<6) {
    Int_t nHitModules=0;
    for(Int_t imodule=fFirst[ilayer]; imodule<=fLast[ilayer]; imodule++) {
      rpTree->GetEvent(imodule);
      AliITSgeomTGeo::GetModuleId(imodule,lay,lad,det);
      lay -= 1;  // AliITSgeomTGeo gives layer from 1 to 6, we want 0 to 5
      if(lay!=ilayer) AliFatal("Layer mismatch!");
      if(recpoints->GetEntriesFast()>0) nHitModules++;
    }
    if(nHitModules>=2) break;
    ilayer++;
  }
  printf("Building tracklets on layer %d\n",ilayer);

  Float_t xclInnLay[100],yclInnLay[100],zclInnLay[100],modclInnLay[100];
  Float_t e2xclInnLay[100],e2yclInnLay[100],e2zclInnLay[100];
  Int_t nclInnLayStored=0;
  Float_t xclOutLay[100],yclOutLay[100],zclOutLay[100],modclOutLay[100];
  Int_t nclOutLayStored=0;
  Int_t nRecPoints,nRecPointsInnLay=0;

  Float_t gc[3],gcov[5];

  Float_t x[100],y[100],z[100],e2x[100],e2y[100],e2z[100];
  Double_t p1[3],p2[3],p3[3];
  Int_t nvtxs;
  Bool_t good,matchtoOutLay;
  Float_t xvtx,yvtx,zvtx,rvtx;

  // Collect clusters in the selected layer and the outer one
  for(Int_t imodule=fFirst[ilayer]; imodule<=fLast[ilayer+1]; imodule++) {
    rpTree->GetEvent(imodule);
    AliITSgeomTGeo::GetModuleId(imodule,lay,lad,det);
    lay -= 1; // AliITSgeomTGeo gives layer from 1 to 6, we want 0 to 5
    nRecPoints=recpoints->GetEntriesFast();
    if(imodule<=fLast[ilayer]) nRecPointsInnLay += nRecPoints;
    //printf("cosmics: module %d clusters %d\n",imodule,nRecPoints);
    for(Int_t irp=0; irp<nRecPoints; irp++) {
      AliITSRecPoint *rp=(AliITSRecPoint*)recpoints->UncheckedAt(irp);
      // Local coordinates of this recpoint
      rp->GetGlobalXYZ(gc);
      if(lay==ilayer) { // store InnLay clusters
	xclInnLay[nclInnLayStored]=gc[0];
	yclInnLay[nclInnLayStored]=gc[1];
	zclInnLay[nclInnLayStored]=gc[2];
	rp->GetGlobalCov(gcov);
	e2xclInnLay[nclInnLayStored]=gcov[0];
	e2yclInnLay[nclInnLayStored]=gcov[3];
	e2zclInnLay[nclInnLayStored]=gcov[5];
	modclInnLay[nclInnLayStored]=imodule;
	nclInnLayStored++;
      }
      if(lay==ilayer+1) { // store OutLay clusters
	xclOutLay[nclOutLayStored]=gc[0];
	yclOutLay[nclOutLayStored]=gc[1];
	zclOutLay[nclOutLayStored]=gc[2];
	modclOutLay[nclOutLayStored]=imodule;
	nclOutLayStored++;
      }
      if(nclInnLayStored>100 || nclOutLayStored>100)
	AliFatal("More than 100 clusters per layer");
    }// end clusters in a module
  }// end modules

  // build fake vertices
  nvtxs=0;
  // InnLay - first cluster
  for(Int_t i1InnLay=0; i1InnLay<nclInnLayStored; i1InnLay++) {
    p1[0]=xclInnLay[i1InnLay];
    p1[1]=yclInnLay[i1InnLay];
    p1[2]=zclInnLay[i1InnLay];
    // InnLay - second cluster
    for(Int_t i2InnLay=i1InnLay+1; i2InnLay<nclInnLayStored; i2InnLay++) {
      if(modclInnLay[i1InnLay]==modclInnLay[i2InnLay]) continue;
      p2[0]=xclInnLay[i2InnLay];
      p2[1]=yclInnLay[i2InnLay];
      p2[2]=zclInnLay[i2InnLay];
      // look for point on OutLay
      AliStrLine InnLayline(p1,p2,kTRUE);
      matchtoOutLay = kFALSE;
      for(Int_t iOutLay=0; iOutLay<nclOutLayStored; iOutLay++) {
	p3[0]=xclOutLay[iOutLay];
	p3[1]=yclOutLay[iOutLay];
	p3[2]=zclOutLay[iOutLay];
	//printf(" %f\n",InnLayline.GetDistFromPoint(p3));
	if(InnLayline.GetDistFromPoint(p3)<fMaxDistOnOuterLayer)
	  { matchtoOutLay = kTRUE; break; }
      }
      if(!matchtoOutLay) continue;
      xvtx = 0.5*(xclInnLay[i1InnLay]+xclInnLay[i2InnLay]);
      yvtx = 0.5*(yclInnLay[i1InnLay]+yclInnLay[i2InnLay]);
      zvtx = 0.5*(zclInnLay[i1InnLay]+zclInnLay[i2InnLay]);
      rvtx = TMath::Sqrt(xvtx*xvtx+yvtx*yvtx);
      if(rvtx>fMaxVtxRadius[ilayer]) continue;
      good = kTRUE;
      for(Int_t iv=0; iv<nvtxs; iv++) {
	if(TMath::Sqrt((xvtx- x[iv])*(xvtx- x[iv])+
		       (yvtx- y[iv])*(yvtx- y[iv])+
		       (zvtx- z[iv])*(zvtx- z[iv])) < fMinDist2Vtxs)
	  good = kFALSE;
      }
      if(good) {
	x[nvtxs]=xvtx;
	y[nvtxs]=yvtx;
	z[nvtxs]=zvtx;
	e2x[nvtxs]=0.25*(e2xclInnLay[i1InnLay]+e2xclInnLay[i2InnLay]);
	e2y[nvtxs]=0.25*(e2yclInnLay[i1InnLay]+e2yclInnLay[i2InnLay]);
	e2z[nvtxs]=0.25*(e2zclInnLay[i1InnLay]+e2zclInnLay[i2InnLay]);
	nvtxs++;
      }
    } // InnLay - second cluster
  } // InnLay - first cluster

  Double_t pos[3]={0.,0.,0.};
  Double_t err[3]={100.,100.,100.};
  if(nvtxs) {
    pos[0]=x[0];
    pos[1]=y[0];
    pos[2]=z[0];
    err[0]=TMath::Sqrt(e2x[0]);
    err[1]=TMath::Sqrt(e2y[0]);
    err[2]=TMath::Sqrt(e2z[0]);
  }
  fCurrentVertex = new AliESDVertex(pos,err,"cosmics");
  if(nvtxs) {
    fCurrentVertex->SetNContributors(ilayer);
  } else {
    fCurrentVertex->SetNContributors(-1);
  }
  fCurrentVertex->SetTitle("cosmics fake vertex");

  if(nvtxs>=0) fCurrentVertex->Print();

  delete recpoints;
  itsLoader->UnloadRecPoints();

  return fCurrentVertex;
}
//-------------------------------------------------------------------------
void AliITSVertexerCosmics::FindVertices()
{
  // computes the vertices of the events in the range FirstEvent - LastEvent
  AliRunLoader *rl = AliRunLoader::GetRunLoader();
  AliITSLoader* itsLoader =  (AliITSLoader*) rl->GetLoader("ITSLoader");
  itsLoader->ReloadRecPoints();
  for(Int_t i=fFirstEvent;i<=fLastEvent;i++){
    //  printf("Processing event %d\n",i);
    rl->GetEvent(i);
    FindVertexForCurrentEvent(i);
    if(fCurrentVertex){
      WriteCurrentVertex();
    }
  }
}
//-------------------------------------------------------------------------
void AliITSVertexerCosmics::PrintStatus() const
{
  // Print current status
  printf("=======================================================\n");
  printf(" fMaxDistOnOuterLayer: %f\n",fMaxDistOnOuterLayer);
  printf(" fMaxVtxRadius[0]:  %f\n",fMaxVtxRadius[0]);
  printf(" fMinDist2Vtxs:  %f\n",fMinDist2Vtxs);
  printf("=======================================================\n");
}
//-------------------------------------------------------------------------
<commit_msg>Enlarged arrays<commit_after>/**************************************************************************
 * Copyright(c) 1998-2007, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

#include <TClonesArray.h>
#include "AliLog.h"
#include "AliESDVertex.h"
#include "AliRunLoader.h"
#include "AliITSLoader.h"
#include "AliITSgeomTGeo.h"
#include "AliITSRecPoint.h"
#include "AliITSVertexerCosmics.h"
#include "AliStrLine.h"

//------------------------------------------------------------------------
// This class implements a method to construct a "fake" primary
// vertex for cosmic events in which the muon crosses one of 5 inner
// ITS layers. A fake primary vertex is needed for the reconstruction,
// with e.g. AliITStrackerSA, of the two tracks produced by the muon
// in the ITS.
//   We build pairs of clusters on a given layer and define the fake vertex as
// the mid-point of the straight line joining the two clusters.
//   We use the innermost layer that has at least two clusters.
//   We reject the background by requiring at least one cluster on the outer
// layer, closer than fMaxDistOnOuterLayer to the tracklet prolongation.
//   We can reject (potentially pathological) events with the muon track
// tangential to the layer by the requiring the radial position of
// the vertex to be smaller than fMaxVtxRadius.
//   Due to background clusters, more than one vertex per event can
// be found. We consider the first found.
//   The errors on x,y,z of the vertex are calculated as errors on the mean
// of clusters coordinates. Non-diag elements of vertex cov. mat. are set to 0.
//   The number of contributors set in the AliESDVertex object is the
// number of the layer on which the tracklet was built; if this number is -1,
// the procedure could not find a vertex position and by default
// the vertex coordinates are set to (0,0,0) with large errors (100,100,100)
//
// Origin: A.Dainese, andrea.dainese@lnl.infn.it
//-------------------------------------------------------------------------

ClassImp(AliITSVertexerCosmics)

//-------------------------------------------------------------------------
AliITSVertexerCosmics::AliITSVertexerCosmics():AliITSVertexer(),
fMaxDistOnOuterLayer(0),
fMinDist2Vtxs(0)
{
  // Default constructor
  SetFirstLastModules(0,0,79);
  SetFirstLastModules(1,80,239);
  SetFirstLastModules(2,240,323);
  SetFirstLastModules(3,324,499);
  SetFirstLastModules(4,500,1247);
  SetFirstLastModules(5,1248,2197);
  SetMaxVtxRadius(0,3.5);
  SetMaxVtxRadius(1,6.5);
  SetMaxVtxRadius(2,14.5);
  SetMaxVtxRadius(3,23.5);
  SetMaxVtxRadius(4,37.5);
  SetMaxVtxRadius(5,42.5);
  SetMaxDistOnOuterLayer();
  SetMinDist2Vtxs();
}
//--------------------------------------------------------------------------
AliESDVertex* AliITSVertexerCosmics::FindVertexForCurrentEvent(Int_t evnumber)
{
  // Defines the AliESDVertex for the current event

  fCurrentVertex = 0;
  AliRunLoader *rl =AliRunLoader::GetRunLoader();
  AliITSLoader* itsLoader = (AliITSLoader*)rl->GetLoader("ITSLoader");
  itsLoader->LoadRecPoints();
  rl->GetEvent(evnumber);

  TTree *rpTree = itsLoader->TreeR();

  TClonesArray *recpoints=new TClonesArray("AliITSRecPoint",10000);
  rpTree->SetBranchAddress("ITSRecPoints",&recpoints);

  Int_t lay,lad,det;

  // Search for innermost layer with at least two clusters
  // on two different modules
  Int_t ilayer=0;
  while(ilayer<6) {
    Int_t nHitModules=0;
    for(Int_t imodule=fFirst[ilayer]; imodule<=fLast[ilayer]; imodule++) {
      rpTree->GetEvent(imodule);
      AliITSgeomTGeo::GetModuleId(imodule,lay,lad,det);
      lay -= 1;  // AliITSgeomTGeo gives layer from 1 to 6, we want 0 to 5
      if(lay!=ilayer) AliFatal("Layer mismatch!");
      if(recpoints->GetEntriesFast()>0) nHitModules++;
    }
    if(nHitModules>=2) break;
    ilayer++;
  }
  printf("Building tracklets on layer %d\n",ilayer);

  const Int_t arrSize = 1000;
  Float_t xclInnLay[arrSize],yclInnLay[arrSize],zclInnLay[arrSize],modclInnLay[arrSize];
  Float_t e2xclInnLay[arrSize],e2yclInnLay[arrSize],e2zclInnLay[arrSize];
  Int_t nclInnLayStored=0;
  Float_t xclOutLay[arrSize],yclOutLay[arrSize],zclOutLay[arrSize],modclOutLay[arrSize];
  Int_t nclOutLayStored=0;
  Int_t nRecPoints,nRecPointsInnLay=0;

  Float_t gc[3],gcov[5];

  Float_t x[arrSize],y[arrSize],z[arrSize],e2x[arrSize],e2y[arrSize],e2z[arrSize];
  Double_t p1[3],p2[3],p3[3];
  Int_t nvtxs;
  Bool_t good,matchtoOutLay;
  Float_t xvtx,yvtx,zvtx,rvtx;

  // Collect clusters in the selected layer and the outer one
  for(Int_t imodule=fFirst[ilayer]; imodule<=fLast[ilayer+1]; imodule++) {
    rpTree->GetEvent(imodule);
    AliITSgeomTGeo::GetModuleId(imodule,lay,lad,det);
    lay -= 1; // AliITSgeomTGeo gives layer from 1 to 6, we want 0 to 5
    nRecPoints=recpoints->GetEntriesFast();
    if(imodule<=fLast[ilayer]) nRecPointsInnLay += nRecPoints;
    //printf("cosmics: module %d clusters %d\n",imodule,nRecPoints);
    for(Int_t irp=0; irp<nRecPoints; irp++) {
      AliITSRecPoint *rp=(AliITSRecPoint*)recpoints->UncheckedAt(irp);
      // Local coordinates of this recpoint
      rp->GetGlobalXYZ(gc);
      if(lay==ilayer) { // store InnLay clusters
	xclInnLay[nclInnLayStored]=gc[0];
	yclInnLay[nclInnLayStored]=gc[1];
	zclInnLay[nclInnLayStored]=gc[2];
	rp->GetGlobalCov(gcov);
	e2xclInnLay[nclInnLayStored]=gcov[0];
	e2yclInnLay[nclInnLayStored]=gcov[3];
	e2zclInnLay[nclInnLayStored]=gcov[5];
	modclInnLay[nclInnLayStored]=imodule;
	nclInnLayStored++;
      }
      if(lay==ilayer+1) { // store OutLay clusters
	xclOutLay[nclOutLayStored]=gc[0];
	yclOutLay[nclOutLayStored]=gc[1];
	zclOutLay[nclOutLayStored]=gc[2];
	modclOutLay[nclOutLayStored]=imodule;
	nclOutLayStored++;
      }
      if(nclInnLayStored>arrSize || nclOutLayStored>arrSize)
	AliFatal("More than arrSize clusters per layer");
    }// end clusters in a module
  }// end modules

  // build fake vertices
  nvtxs=0;
  // InnLay - first cluster
  for(Int_t i1InnLay=0; i1InnLay<nclInnLayStored; i1InnLay++) {
    p1[0]=xclInnLay[i1InnLay];
    p1[1]=yclInnLay[i1InnLay];
    p1[2]=zclInnLay[i1InnLay];
    // InnLay - second cluster
    for(Int_t i2InnLay=i1InnLay+1; i2InnLay<nclInnLayStored; i2InnLay++) {
      if(modclInnLay[i1InnLay]==modclInnLay[i2InnLay]) continue;
      p2[0]=xclInnLay[i2InnLay];
      p2[1]=yclInnLay[i2InnLay];
      p2[2]=zclInnLay[i2InnLay];
      // look for point on OutLay
      AliStrLine InnLayline(p1,p2,kTRUE);
      matchtoOutLay = kFALSE;
      for(Int_t iOutLay=0; iOutLay<nclOutLayStored; iOutLay++) {
	p3[0]=xclOutLay[iOutLay];
	p3[1]=yclOutLay[iOutLay];
	p3[2]=zclOutLay[iOutLay];
	//printf(" %f\n",InnLayline.GetDistFromPoint(p3));
	if(InnLayline.GetDistFromPoint(p3)<fMaxDistOnOuterLayer)
	  { matchtoOutLay = kTRUE; break; }
      }
      if(!matchtoOutLay) continue;
      xvtx = 0.5*(xclInnLay[i1InnLay]+xclInnLay[i2InnLay]);
      yvtx = 0.5*(yclInnLay[i1InnLay]+yclInnLay[i2InnLay]);
      zvtx = 0.5*(zclInnLay[i1InnLay]+zclInnLay[i2InnLay]);
      rvtx = TMath::Sqrt(xvtx*xvtx+yvtx*yvtx);
      if(rvtx>fMaxVtxRadius[ilayer]) continue;
      good = kTRUE;
      for(Int_t iv=0; iv<nvtxs; iv++) {
	if(TMath::Sqrt((xvtx- x[iv])*(xvtx- x[iv])+
		       (yvtx- y[iv])*(yvtx- y[iv])+
		       (zvtx- z[iv])*(zvtx- z[iv])) < fMinDist2Vtxs)
	  good = kFALSE;
      }
      if(good) {
	x[nvtxs]=xvtx;
	y[nvtxs]=yvtx;
	z[nvtxs]=zvtx;
	e2x[nvtxs]=0.25*(e2xclInnLay[i1InnLay]+e2xclInnLay[i2InnLay]);
	e2y[nvtxs]=0.25*(e2yclInnLay[i1InnLay]+e2yclInnLay[i2InnLay]);
	e2z[nvtxs]=0.25*(e2zclInnLay[i1InnLay]+e2zclInnLay[i2InnLay]);
	nvtxs++;
      }
    } // InnLay - second cluster
  } // InnLay - first cluster

  Double_t pos[3]={0.,0.,0.};
  Double_t err[3]={100.,100.,100.};
  if(nvtxs) {
    pos[0]=x[0];
    pos[1]=y[0];
    pos[2]=z[0];
    err[0]=TMath::Sqrt(e2x[0]);
    err[1]=TMath::Sqrt(e2y[0]);
    err[2]=TMath::Sqrt(e2z[0]);
  }
  fCurrentVertex = new AliESDVertex(pos,err,"cosmics");
  if(nvtxs) {
    fCurrentVertex->SetNContributors(ilayer);
  } else {
    fCurrentVertex->SetNContributors(-1);
  }
  fCurrentVertex->SetTitle("cosmics fake vertex");

  if(nvtxs>=0) fCurrentVertex->Print();

  delete recpoints;
  itsLoader->UnloadRecPoints();

  return fCurrentVertex;
}
//-------------------------------------------------------------------------
void AliITSVertexerCosmics::FindVertices()
{
  // computes the vertices of the events in the range FirstEvent - LastEvent
  AliRunLoader *rl = AliRunLoader::GetRunLoader();
  AliITSLoader* itsLoader =  (AliITSLoader*) rl->GetLoader("ITSLoader");
  itsLoader->ReloadRecPoints();
  for(Int_t i=fFirstEvent;i<=fLastEvent;i++){
    //  printf("Processing event %d\n",i);
    rl->GetEvent(i);
    FindVertexForCurrentEvent(i);
    if(fCurrentVertex){
      WriteCurrentVertex();
    }
  }
}
//-------------------------------------------------------------------------
void AliITSVertexerCosmics::PrintStatus() const
{
  // Print current status
  printf("=======================================================\n");
  printf(" fMaxDistOnOuterLayer: %f\n",fMaxDistOnOuterLayer);
  printf(" fMaxVtxRadius[0]:  %f\n",fMaxVtxRadius[0]);
  printf(" fMinDist2Vtxs:  %f\n",fMinDist2Vtxs);
  printf("=======================================================\n");
}
//-------------------------------------------------------------------------
<|endoftext|>


<commit_before><commit_msg>liblibo: use gettimeofday not clock_gettime for better portability.<commit_after><|endoftext|>


<commit_before>#include <iostream>
/**
 * Multiplies two user defined integers.
 *
 * @return 0 upon succesfuel program execution
 */
int main()
{
    std::cout << "Enter two numbers:" << std::endl;
    int v1 = 0, v2 = 0;
    std::cin >> v1 >> v2;
    std::cout << "The product of " << v1 << " and " << v2 << " is " << v1 * v2
            << std::endl;
    return 0;
}
<commit_msg>committing product.cpp before merge<commit_after>#include <iostream>
/**
 * Multiplies two user defined integers.
 *
 * @return 0 upon succesfuel program execution
 */
int main()
{
    std::cout << "Enter two numbers:" << std::endl;
    int v1 = 0, v2 = 0;
    std::cin >> v1 >> v2;
    std::cout << "The product of " << v1; << " and " << v2 << " is " << v1 * v2
            << std::endl;
    return 0;
}
<|endoftext|>


<commit_before>#include <boost/test/unit_test.hpp>
#include <eosio/testing/tester.hpp>

#include <eosio/chain/contracts/staked_balance_objects.hpp>

using namespace eosio;
using namespace eosio::chain;
using namespace eosio::chain::contracts;
using namespace eosio::testing;

BOOST_AUTO_TEST_SUITE(transfer_tests)

BOOST_AUTO_TEST_CASE( transfer_test ) { try {
  tester test;
  test.produce_blocks(2);

  test.create_accounts( {N(dan), N(bart)}, asset::from_string("10.0000 EOS") );
  test.transfer( N(inita), N(dan), "10.0000 EOS", "memo" );

  {
     const auto& dans_balance = test.get_balance( N(dan) );
     FC_ASSERT( dans_balance == asset::from_string("10.0000 EOS") );
  }

  test.produce_block();

  {
     const auto& dans_balance = test.get_balance( N(dan) );
     FC_ASSERT( dans_balance == asset::from_string("10.0000 EOS") );
  }

  /// insufficient funds
  BOOST_REQUIRE_THROW(test.transfer(N(dan),N(bart), "11.0000 EOS", "memo"), action_validate_exception);

  /// this should succeed because dan has sufficient balance
  test.transfer(N(dan),N(bart), "10.0000 EOS", "memo");

  /// verify that bart now has 10.000
  const auto& barts_balance = test.get_balance( N(bart) );
  FC_ASSERT( barts_balance == asset::from_string("10.0000 EOS") );

  {
     /// verify that dan now has 0.000
     const auto& dans_balance = test.get_balance( N(dan) );
     FC_ASSERT( dans_balance == asset::from_string("0.0000 EOS") );
  }

  /// should throw because -1 becomes uint64 max which is greater than balance
  BOOST_REQUIRE_THROW(test.transfer(N(bart),N(dan), asset(-1), "memo"), action_validate_exception);

  {
      auto from = N(bart);
      auto to   = N(dan);
      asset amount(1);
      signed_transaction trx;
      trx.write_scope = {from,to};
      trx.actions.emplace_back( vector<permission_level>{{from,config::active_name}},
                                contracts::transfer{
                                   .from   = from,
                                   .to     = to,
                                   .amount = amount.amount,
                                   .memo   = "memo"
                                } );

      test.set_tapos( trx );
      BOOST_REQUIRE_THROW( test.control->push_transaction( trx ), tx_missing_sigs );
      trx.sign( test.get_private_key( from, "active" ), chain_id_type()  );
      test.control->push_transaction( trx );
  }

  {
      auto from = N(bart);
      auto to   = N(dan);
      asset amount(1);
      signed_transaction trx;
      trx.write_scope = {from,to};
      trx.actions.emplace_back( vector<permission_level>{{to,config::active_name}},
                                contracts::transfer{
                                   .from   = from,
                                   .to     = to,
                                   .amount = amount.amount,
                                   .memo   = "memo"
                                } );

      test.set_tapos( trx );
      trx.sign( test.get_private_key( to, "active" ), chain_id_type()  );
      /// action not provided from authority
      BOOST_REQUIRE_THROW( test.control->push_transaction( trx ), tx_missing_auth);
  }

  {
      auto from = N(bart);
      auto to   = N(dan);
      asset amount(1);
      signed_transaction trx;
     // trx.write_scope = {from,to};
      trx.actions.emplace_back( vector<permission_level>{{from,config::active_name}},
                                contracts::transfer{
                                   .from   = from,
                                   .to     = to,
                                   .amount = amount.amount,
                                   .memo   = "memo"
                                } );

      test.set_tapos( trx );
      trx.sign( test.get_private_key( from, "active" ), chain_id_type()  );
      BOOST_REQUIRE_THROW( test.control->push_transaction( trx ), tx_missing_write_scope);
  }

} FC_LOG_AND_RETHROW() } /// transfer_test

/**
 *  This test case will attempt to allow one account to transfer on behalf
 *  of another account by updating the active authority.
 */
BOOST_AUTO_TEST_CASE( transfer_delegation ) { try {
   tester test;
   test.produce_blocks(2);
   test.create_accounts( {N(dan),N(bart),N(trust)}, asset::from_string("10.0000 EOS") );
   test.transfer( N(inita), N(dan), "10.0000 EOS" );
   test.transfer( N(inita), N(trust), "10.0000 EOS" );
   test.transfer( N(trust), N(dan), "1.0000 EOS" );

   test.produce_block();

   auto dans_active_auth = authority( 1, {},
                          {
                            { .permission = {N(trust),config::active_name}, .weight = 1}
                          });

   test.set_authority( N(dan), config::active_name,  dans_active_auth );

   const auto& danauth = test.control->get_permission( permission_level{N(dan),config::active_name} );
   const auto& trustauth = test.control->get_permission( permission_level{N(trust),config::active_name} );

   test.produce_block( fc::hours(2) ); ///< skip 2 hours

  /// execute a transfer from dan to bart signed by trust
  {
      auto from = N(dan);
      auto to   = N(bart);
      asset amount(1);

      signed_transaction trx;
      trx.write_scope = {from,to};
      trx.actions.emplace_back( vector<permission_level>{{from,config::active_name}},
                                contracts::transfer{
                                   .from   = from,
                                   .to     = to,
                                   .amount = amount.amount,
                                   .memo   = "memo"
                                } );

      test.set_tapos( trx );
      trx.sign( test.get_private_key( N(trust), "active" ), chain_id_type()  );
      wdump((fc::raw::pack_size(trx)));

      /// action not provided from authority
      test.control->push_transaction( trx );
  }

} FC_LOG_AND_RETHROW() }

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>add a little bit of stake and prime the chain to resolve rate limiting issues in unit tests<commit_after>#include <boost/test/unit_test.hpp>
#include <eosio/testing/tester.hpp>

#include <eosio/chain/contracts/staked_balance_objects.hpp>

using namespace eosio;
using namespace eosio::chain;
using namespace eosio::chain::contracts;
using namespace eosio::testing;

BOOST_AUTO_TEST_SUITE(transfer_tests)

BOOST_AUTO_TEST_CASE( transfer_test ) { try {
  tester test;
  test.produce_blocks(1000);

  test.create_accounts( {N(dan), N(bart)}, asset::from_string("100.0000 EOS") );
  test.transfer( N(inita), N(dan), "10.0000 EOS", "memo" );

  {
     const auto& dans_balance = test.get_balance( N(dan) );
     FC_ASSERT( dans_balance == asset::from_string("10.0000 EOS") );
  }

  test.produce_block();

  {
     const auto& dans_balance = test.get_balance( N(dan) );
     FC_ASSERT( dans_balance == asset::from_string("10.0000 EOS") );
  }

  /// insufficient funds
  BOOST_REQUIRE_THROW(test.transfer(N(dan),N(bart), "11.0000 EOS", "memo"), action_validate_exception);

  /// this should succeed because dan has sufficient balance
  test.transfer(N(dan),N(bart), "10.0000 EOS", "memo");

  /// verify that bart now has 10.000
  const auto& barts_balance = test.get_balance( N(bart) );
  FC_ASSERT( barts_balance == asset::from_string("10.0000 EOS") );

  {
     /// verify that dan now has 0.000
     const auto& dans_balance = test.get_balance( N(dan) );
     FC_ASSERT( dans_balance == asset::from_string("0.0000 EOS") );
  }

  /// should throw because -1 becomes uint64 max which is greater than balance
  BOOST_REQUIRE_THROW(test.transfer(N(bart),N(dan), asset(-1), "memo"), action_validate_exception);

  {
      auto from = N(bart);
      auto to   = N(dan);
      asset amount(1);
      signed_transaction trx;
      trx.write_scope = {from,to};
      trx.actions.emplace_back( vector<permission_level>{{from,config::active_name}},
                                contracts::transfer{
                                   .from   = from,
                                   .to     = to,
                                   .amount = amount.amount,
                                   .memo   = "memo"
                                } );

      test.set_tapos( trx );
      BOOST_REQUIRE_THROW( test.control->push_transaction( trx ), tx_missing_sigs );
      trx.sign( test.get_private_key( from, "active" ), chain_id_type()  );
      test.control->push_transaction( trx );
  }

  {
      auto from = N(bart);
      auto to   = N(dan);
      asset amount(1);
      signed_transaction trx;
      trx.write_scope = {from,to};
      trx.actions.emplace_back( vector<permission_level>{{to,config::active_name}},
                                contracts::transfer{
                                   .from   = from,
                                   .to     = to,
                                   .amount = amount.amount,
                                   .memo   = "memo"
                                } );

      test.set_tapos( trx );
      trx.sign( test.get_private_key( to, "active" ), chain_id_type()  );
      /// action not provided from authority
      BOOST_REQUIRE_THROW( test.control->push_transaction( trx ), tx_missing_auth);
  }

  {
      auto from = N(bart);
      auto to   = N(dan);
      asset amount(1);
      signed_transaction trx;
     // trx.write_scope = {from,to};
      trx.actions.emplace_back( vector<permission_level>{{from,config::active_name}},
                                contracts::transfer{
                                   .from   = from,
                                   .to     = to,
                                   .amount = amount.amount,
                                   .memo   = "memo"
                                } );

      test.set_tapos( trx );
      trx.sign( test.get_private_key( from, "active" ), chain_id_type()  );
      BOOST_REQUIRE_THROW( test.control->push_transaction( trx ), tx_missing_write_scope);
  }

} FC_LOG_AND_RETHROW() } /// transfer_test

/**
 *  This test case will attempt to allow one account to transfer on behalf
 *  of another account by updating the active authority.
 */
BOOST_AUTO_TEST_CASE( transfer_delegation ) { try {
   tester test;
   test.produce_blocks(1000);
   test.create_accounts( {N(dan),N(bart),N(trust)}, asset::from_string("100.0000 EOS") );
   test.transfer( N(inita), N(dan), "10.0000 EOS" );
   test.transfer( N(inita), N(trust), "10.0000 EOS" );
   test.transfer( N(trust), N(dan), "1.0000 EOS" );

   test.produce_block();

   auto dans_active_auth = authority( 1, {},
                          {
                            { .permission = {N(trust),config::active_name}, .weight = 1}
                          });

   test.set_authority( N(dan), config::active_name,  dans_active_auth );

   const auto& danauth = test.control->get_permission( permission_level{N(dan),config::active_name} );
   const auto& trustauth = test.control->get_permission( permission_level{N(trust),config::active_name} );

   test.produce_block( fc::hours(2) ); ///< skip 2 hours

  /// execute a transfer from dan to bart signed by trust
  {
      auto from = N(dan);
      auto to   = N(bart);
      asset amount(1);

      signed_transaction trx;
      trx.write_scope = {from,to};
      trx.actions.emplace_back( vector<permission_level>{{from,config::active_name}},
                                contracts::transfer{
                                   .from   = from,
                                   .to     = to,
                                   .amount = amount.amount,
                                   .memo   = "memo"
                                } );

      test.set_tapos( trx );
      trx.sign( test.get_private_key( N(trust), "active" ), chain_id_type()  );
      wdump((fc::raw::pack_size(trx)));

      /// action not provided from authority
      test.control->push_transaction( trx );
  }

} FC_LOG_AND_RETHROW() }

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include "Log.h"

namespace vl
{
	namespace database
	{
	}
}
<commit_msg>Log page structure comment<commit_after>#include "Log.h"

/*
 *	Page Structure
 *		Index Page				: [uint64 AddressItems][uint64 NextIndexPage]{[uint64 AddressItem] ...}
 *			The first index page is the index page from the source.
 *			Each address item is the address of transactions of 0, 1, ...
 * 		Log Page				:
 * 			Transaction Header	: [uint64 Transaction]<Item-Header>
 * 				Min Size = 5 * sizeof(uint64)
 * 			Item Header			: [uint64 ItemLength]<Item-Block>
 * 				Min Size = 4 * sizeof(uint64)
 * 			Item Block			: [uint64 CurrentBlockLength][uint64 NextBlockAddress/NextItemAddress][data, adjust to sizeof(uint64)]
 * 				Min Size = 3 * sizeof(uint64)
 */

namespace vl
{
	namespace database
	{
	}
}
<|endoftext|>


<commit_before>// Copyright 2016 Robo@FIT

#include "art_pr2_grasping/pr2grasp.h"
#include <algorithm>
#include <string>
#include <vector>

namespace art_pr2_grasping
{

float artPr2Grasping::getGripperValue()
{
  pr2_controllers_msgs::JointControllerStateConstPtr msg =
      ros::topic::waitForMessage<pr2_controllers_msgs::JointControllerState>(
          gripper_state_topic_, ros::Duration(1));

  if (msg)
    return msg->process_value;
  else
    return 1000;  // TODO(ZdenekM): NaN / exception?
}

artPr2Grasping::artPr2Grasping(boost::shared_ptr<tf::TransformListener> tfl,
                               boost::shared_ptr<Objects> objects,
                               std::string group_name,
                               std::string default_target,
                               std::string gripper_state_topic)
    : group_name_(group_name), default_target_(default_target),
      gripper_state_topic_(gripper_state_topic), nh_("~")
{
  tfl_ = tfl;
  objects_ = objects;

  move_group_.reset(new move_group_interface::MoveGroup(group_name_));
  move_group_->setPlanningTime(30.0);
  move_group_->allowLooking(false);
  move_group_->allowReplanning(false);
  move_group_->setGoalTolerance(0.005);
  move_group_->setPlannerId("RRTConnectkConfigDefault");

  ROS_INFO_NAMED(group_name_, "Planning frame: %s", getPlanningFrame().c_str());

  // Load grasp generator
  if (!grasp_data_.loadRobotGraspData(nh_, group_name_))
    ros::shutdown();

  // Load the Robot Viz Tools for publishing to rviz
  visual_tools_.reset(
      new moveit_visual_tools::VisualTools(getPlanningFrame(), "markers"));
  // visual_tools_->setFloorToBaseHeight(0.0);
  visual_tools_->loadEEMarker(grasp_data_.ee_group_, group_name_);
  visual_tools_->loadPlanningSceneMonitor();
  visual_tools_->setLifetime(10.0);

  visual_tools_->setMuted(false);

  grasped_object_.reset();

  simple_grasps_.reset(new moveit_simple_grasps::SimpleGrasps(visual_tools_));

  planning_scene_monitor_.reset(
      new planning_scene_monitor::PlanningSceneMonitor("robot_description"));
  robot_state::RobotState robot_state =
      planning_scene_monitor_->getPlanningScene()->getCurrentState();
  grasp_filter_.reset(
      new moveit_simple_grasps::GraspFilter(robot_state, visual_tools_));

  grasped_object_pub_ = nh_.advertise<std_msgs::String>(
      "/art/pr2/" + group_name_ + "/grasped_object", 1, true);

  look_at_pub_ = nh_.advertise<geometry_msgs::PointStamped>(
      "/art/pr2/look_at", 10);

  publishObject();
}

void artPr2Grasping::publishObject(std::string object_id)
{
  std_msgs::String msg;
  msg.data = object_id;
  grasped_object_pub_.publish(msg);
}

bool artPr2Grasping::transformPose(geometry_msgs::PoseStamped& ps)
{
  try
  {
    if (tfl_->waitForTransform(getPlanningFrame(), ps.header.frame_id,
                               ps.header.stamp, ros::Duration(1.0)))
    {
      tfl_->transformPose(getPlanningFrame(), ps, ps);
    }
    else
    {
      ROS_ERROR_NAMED(group_name_, "Transform between %s and %s not available!",
                      getPlanningFrame().c_str(),
                      std::string(ps.header.frame_id).c_str());
      return false;
    }
  }
  catch (tf::TransformException& ex)
  {
    ROS_ERROR_NAMED(group_name_, "TF exception: %s",
                    std::string(ex.what()).c_str());
    return false;
  }

  return true;
}

bool artPr2Grasping::getReady()
{
  move_group_->clearPathConstraints();
  if (!move_group_->setNamedTarget(default_target_))
  {
    ROS_ERROR_NAMED(group_name_, "Unknown default target name: %s",
                    default_target_.c_str());
    return false;
  }

  if (!move_group_->move())
  {
    ROS_WARN_NAMED(group_name_, "Failed to get ready.");
    return false;
  }

  return true;
}

void artPr2Grasping::look_at(const geometry_msgs::PoseStamped& ps)
{
    geometry_msgs::PointStamped pt;
    pt.header = ps.header;
    pt.point = ps.pose.position;

    look_at_pub_.publish(pt);
}

bool artPr2Grasping::place(const geometry_msgs::Pose& ps,
                           double z_axis_angle_increment, bool keep_orientation)
{
  if (!hasGraspedObject())
  {
    ROS_ERROR_NAMED(group_name_, "No object to place.");
    return false;
  }

  std::vector<moveit_msgs::PlaceLocation> place_locations;

  geometry_msgs::PoseStamped pose_stamped;
  pose_stamped.pose = ps;
  pose_stamped.header.frame_id = getPlanningFrame();
  pose_stamped.header.stamp = ros::Time::now();

  look_at(pose_stamped);

  shape_msgs::SolidPrimitive bb = grasped_object_->type.bbox;

  visual_tools_->publishBlock(pose_stamped.pose, moveit_visual_tools::ORANGE,
                              bb.dimensions[0], bb.dimensions[1],
                              bb.dimensions[2]);

  if (z_axis_angle_increment < 0)
    z_axis_angle_increment *= -1.0;  // only positive increment allowed
  if (z_axis_angle_increment == 0)
    z_axis_angle_increment =
        2 * M_PI;  // for 0 we only want one cycle (only given orientation)

  // Create 360 degrees of place location rotated around a center
  for (double angle = 0; angle < 2 * M_PI; angle += z_axis_angle_increment)
  {
    geometry_msgs::PoseStamped pps = pose_stamped;

    // Orientation
    tf::Quaternion tfq2 = tf::createQuaternionFromYaw(angle);

    tf::Quaternion tfq1;
    tf::quaternionMsgToTF(pps.pose.orientation, tfq1);

    tf::quaternionTFToMsg(tfq1 * tfq2, pps.pose.orientation);

    // Create new place location
    moveit_msgs::PlaceLocation place_loc;

    place_loc.place_pose = pps;

    // Approach
    moveit_msgs::GripperTranslation pre_place_approach;
    pre_place_approach.direction.header.stamp = ros::Time::now();
    pre_place_approach.desired_distance =
        grasp_data_.approach_retreat_desired_dist_;  // The distance the origin
                                                     // of a robot link needs
                                                     // to travel
    pre_place_approach.min_distance =
        grasp_data_
            .approach_retreat_min_dist_;  // half of the desired? Untested.
    pre_place_approach.direction.header.frame_id = grasp_data_.base_link_;
    pre_place_approach.direction.vector.x = 0;
    pre_place_approach.direction.vector.y = 0;
    pre_place_approach.direction.vector.z = -1;  // Approach direction
                                                 // (negative z axis)
                                                 // document this assumption
    place_loc.pre_place_approach = pre_place_approach;

    // Retreat
    moveit_msgs::GripperTranslation post_place_retreat;
    post_place_retreat.direction.header.stamp = ros::Time::now();
    // TODO(ZdenekM): is box_z always height of the object?
    // assume that robot holds the object in the middle of its height

    double des_dist =
        std::max(grasp_data_.approach_retreat_desired_dist_,
                 0.1 +
                     0.5 *
                         grasped_object_->type.bbox
                             .dimensions[shape_msgs::SolidPrimitive::BOX_Z]);

    post_place_retreat.desired_distance =
        des_dist;  // The distance the origin of a robot link needs to travel
                   // -> depends on the object size
    post_place_retreat.min_distance =
        grasp_data_
            .approach_retreat_min_dist_;  // half of the desired? Untested.
    post_place_retreat.direction.header.frame_id = grasp_data_.base_link_;
    post_place_retreat.direction.vector.x = 0;
    post_place_retreat.direction.vector.y = 0;
    post_place_retreat.direction.vector.z = 1;  // Retreat direction (pos z axis)
    place_loc.post_place_retreat = post_place_retreat;

    // Post place posture - use same as pre-grasp posture (the OPEN command)
    place_loc.post_place_posture = grasp_data_.pre_grasp_posture_;

    place_locations.push_back(place_loc);
  }

  if (keep_orientation)
  {
    ROS_INFO_NAMED(group_name_, "Applying orientation constraint...");

    moveit_msgs::OrientationConstraint ocm;
    ocm.link_name = move_group_->getEndEffectorLink();
    ocm.header.frame_id = getPlanningFrame();
    ocm.orientation = move_group_->getCurrentPose().pose.orientation;
    ocm.absolute_x_axis_tolerance = 0.2;
    ocm.absolute_y_axis_tolerance = 0.2;
    ocm.absolute_z_axis_tolerance = M_PI;
    ocm.weight = 1.0;

    moveit_msgs::Constraints c;
    c.orientation_constraints.push_back(ocm);

    move_group_->setPathConstraints(c);
  }

  // Prevent collision with table
  // move_group_->setSupportSurfaceName(SUPPORT_SURFACE3_NAME)

  if (move_group_->place(grasped_object_->object_id, place_locations))
  {
    grasped_object_.reset();
    publishObject();
    move_group_->clearPathConstraints();
    return true;
  }

  ROS_WARN_NAMED(group_name_, "Failed to place");
  return false;
}

std::string artPr2Grasping::getPlanningFrame()
{
  return move_group_->getPlanningFrame();
}

bool artPr2Grasping::hasGraspedObject() { return grasped_object_; }

bool artPr2Grasping::pick(const std::string& object_id, bool pick_only_y_axis)
{
  if (hasGraspedObject())
  {
    ROS_ERROR_NAMED(group_name_, "Can't grasp another object.");
    return false;
  }

  TObjectInfo obj;

  try
  {
    obj = objects_->getObject(object_id);
  }
  catch (const std::invalid_argument& e)
  {
    ROS_ERROR_NAMED(group_name_, "Unknown object_id: %s", object_id.c_str());
    return false;
  }

  std::vector<moveit_msgs::Grasp> grasps;

  geometry_msgs::PoseStamped p = obj.pose;
  p.header.stamp = ros::Time::now();

  if (!transformPose(p))
  {
    return false;
  }

  // visualization only -> published by publishCollisionBB
  // visual_tools_->publishBlock(objects_[id].p, moveit_visual_tools::ORANGE,
  // objects_[id].bb.dimensions[0], objects_[id].bb.dimensions[1],
  // objects_[id].bb.dimensions[2]);

  if (!simple_grasps_->generateShapeGrasps(obj.type.bbox, true, true, p,
                                           grasp_data_, grasps, pick_only_y_axis))
  {
    ROS_ERROR_NAMED(group_name_, "No grasps found.");
    return false;
  }

  // todo fix this (No kinematic solver found)
  std::vector<trajectory_msgs::JointTrajectoryPoint>
      ik_solutions;  // save each grasps ik solution for visualization
  if (!grasp_filter_->filterGrasps(grasps, ik_solutions, true,
                                   grasp_data_.ee_parent_link_, group_name_))
  {
    ROS_ERROR_NAMED(group_name_, "Grasp filtering failed.");
    return false;
  }

  if (grasps.size() == 0)
  {
    ROS_ERROR_NAMED(group_name_, "No feasible grasps found.");
    return false;
  }

  look_at(p);

  // visualization only - takes time
  /*if (!groups_[group]->visual_tools_->publishAnimatedGrasps(grasps,
  groups_[group]->grasp_data_.ee_parent_link_, 0.02)) {

      ROS_WARN("Grasp animation failed");
  }*/

  std::vector<std::string> allowed_touch_objects;
  allowed_touch_objects.push_back(object_id);

  // Add this list to all grasps
  for (std::size_t i = 0; i < grasps.size(); ++i)
  {
    grasps[i].allowed_touch_objects = allowed_touch_objects;
  }

  grasped_object_ = boost::make_shared<TObjectInfo>(obj);
  grasped_object_->object_id = object_id;

  if (!move_group_->pick(object_id, grasps))
  {
    ROS_WARN_NAMED(group_name_, "Failed to pick");
    grasped_object_.reset();
    return false;
  }

  float gripper = getGripperValue();

  if (gripper < 0.005)
  {
    visual_tools_->cleanupACO(object_id);
    grasped_object_.reset();
    ROS_ERROR_NAMED(group_name_,
                    "Gripper is closed - object missed or dropped :-(");
    return false;
  }

  ROS_INFO_NAMED(group_name_, "Picked the object.");
  publishObject(object_id);
  return true;
}

// TODO(ZdenekM): move to Objects? Or somewhere else?
bool artPr2Grasping::addTable(double x, double y, double angle, double width,
                              double height, double depth, std::string name)
{
  ROS_INFO_NAMED(group_name_, "Adding table: %s", name.c_str());

  visual_tools_->cleanupCO(name);

  for (int j = 0; j < 3; j++)  // hmm, sometimes the table is not added
  {
    if (!visual_tools_->publishCollisionTable(x, y, angle, width, height, depth,
                                              name))
      return false;
    move_group_->setSupportSurfaceName(name);
    ros::Duration(0.1).sleep();
  }

  return true;
}

}  // namespace art_pr2_grasping
<commit_msg>art_pr2_grasping: table<commit_after>// Copyright 2016 Robo@FIT

#include "art_pr2_grasping/pr2grasp.h"
#include <algorithm>
#include <string>
#include <vector>

namespace art_pr2_grasping
{

float artPr2Grasping::getGripperValue()
{
  pr2_controllers_msgs::JointControllerStateConstPtr msg =
      ros::topic::waitForMessage<pr2_controllers_msgs::JointControllerState>(
          gripper_state_topic_, ros::Duration(1));

  if (msg)
    return msg->process_value;
  else
    return 1000;  // TODO(ZdenekM): NaN / exception?
}

artPr2Grasping::artPr2Grasping(boost::shared_ptr<tf::TransformListener> tfl,
                               boost::shared_ptr<Objects> objects,
                               std::string group_name,
                               std::string default_target,
                               std::string gripper_state_topic)
    : group_name_(group_name), default_target_(default_target),
      gripper_state_topic_(gripper_state_topic), nh_("~")
{
  tfl_ = tfl;
  objects_ = objects;

  move_group_.reset(new move_group_interface::MoveGroup(group_name_));
  move_group_->setPlanningTime(30.0);
  move_group_->allowLooking(false);
  move_group_->allowReplanning(false);
  move_group_->setGoalTolerance(0.005);
  move_group_->setPlannerId("RRTConnectkConfigDefault");

  ROS_INFO_NAMED(group_name_, "Planning frame: %s", getPlanningFrame().c_str());

  // Load grasp generator
  if (!grasp_data_.loadRobotGraspData(nh_, group_name_))
    ros::shutdown();

  // Load the Robot Viz Tools for publishing to rviz
  visual_tools_.reset(
      new moveit_visual_tools::VisualTools(getPlanningFrame(), "markers"));
  // visual_tools_->setFloorToBaseHeight(0.0);
  visual_tools_->loadEEMarker(grasp_data_.ee_group_, group_name_);
  visual_tools_->loadPlanningSceneMonitor();
  visual_tools_->setLifetime(10.0);

  visual_tools_->setMuted(false);

  grasped_object_.reset();

  simple_grasps_.reset(new moveit_simple_grasps::SimpleGrasps(visual_tools_));

  planning_scene_monitor_.reset(
      new planning_scene_monitor::PlanningSceneMonitor("robot_description"));
  robot_state::RobotState robot_state =
      planning_scene_monitor_->getPlanningScene()->getCurrentState();
  grasp_filter_.reset(
      new moveit_simple_grasps::GraspFilter(robot_state, visual_tools_));

  grasped_object_pub_ = nh_.advertise<std_msgs::String>(
      "/art/pr2/" + group_name_ + "/grasped_object", 1, true);

  look_at_pub_ = nh_.advertise<geometry_msgs::PointStamped>(
      "/art/pr2/look_at", 10);

  publishObject();
}

void artPr2Grasping::publishObject(std::string object_id)
{
  std_msgs::String msg;
  msg.data = object_id;
  grasped_object_pub_.publish(msg);
}

bool artPr2Grasping::transformPose(geometry_msgs::PoseStamped& ps)
{
  try
  {
    if (tfl_->waitForTransform(getPlanningFrame(), ps.header.frame_id,
                               ps.header.stamp, ros::Duration(1.0)))
    {
      tfl_->transformPose(getPlanningFrame(), ps, ps);
    }
    else
    {
      ROS_ERROR_NAMED(group_name_, "Transform between %s and %s not available!",
                      getPlanningFrame().c_str(),
                      std::string(ps.header.frame_id).c_str());
      return false;
    }
  }
  catch (tf::TransformException& ex)
  {
    ROS_ERROR_NAMED(group_name_, "TF exception: %s",
                    std::string(ex.what()).c_str());
    return false;
  }

  return true;
}

bool artPr2Grasping::getReady()
{
  move_group_->clearPathConstraints();
  if (!move_group_->setNamedTarget(default_target_))
  {
    ROS_ERROR_NAMED(group_name_, "Unknown default target name: %s",
                    default_target_.c_str());
    return false;
  }

  if (!move_group_->move())
  {
    ROS_WARN_NAMED(group_name_, "Failed to get ready.");
    return false;
  }

  return true;
}

void artPr2Grasping::look_at(const geometry_msgs::PoseStamped& ps)
{
    geometry_msgs::PointStamped pt;
    pt.header = ps.header;
    pt.point = ps.pose.position;

    look_at_pub_.publish(pt);
}

bool artPr2Grasping::place(const geometry_msgs::Pose& ps,
                           double z_axis_angle_increment, bool keep_orientation)
{
  if (!hasGraspedObject())
  {
    ROS_ERROR_NAMED(group_name_, "No object to place.");
    return false;
  }

  std::vector<moveit_msgs::PlaceLocation> place_locations;

  geometry_msgs::PoseStamped pose_stamped;
  pose_stamped.pose = ps;
  pose_stamped.header.frame_id = getPlanningFrame();
  pose_stamped.header.stamp = ros::Time::now();

  look_at(pose_stamped);

  shape_msgs::SolidPrimitive bb = grasped_object_->type.bbox;

  visual_tools_->publishBlock(pose_stamped.pose, moveit_visual_tools::ORANGE,
                              bb.dimensions[0], bb.dimensions[1],
                              bb.dimensions[2]);

  if (z_axis_angle_increment < 0)
    z_axis_angle_increment *= -1.0;  // only positive increment allowed
  if (z_axis_angle_increment == 0)
    z_axis_angle_increment =
        2 * M_PI;  // for 0 we only want one cycle (only given orientation)

  // Create 360 degrees of place location rotated around a center
  for (double angle = 0; angle < 2 * M_PI; angle += z_axis_angle_increment)
  {
    geometry_msgs::PoseStamped pps = pose_stamped;

    // Orientation
    tf::Quaternion tfq2 = tf::createQuaternionFromYaw(angle);

    tf::Quaternion tfq1;
    tf::quaternionMsgToTF(pps.pose.orientation, tfq1);

    tf::quaternionTFToMsg(tfq1 * tfq2, pps.pose.orientation);

    // Create new place location
    moveit_msgs::PlaceLocation place_loc;

    place_loc.place_pose = pps;

    // Approach
    moveit_msgs::GripperTranslation pre_place_approach;
    pre_place_approach.direction.header.stamp = ros::Time::now();
    pre_place_approach.desired_distance =
        grasp_data_.approach_retreat_desired_dist_;  // The distance the origin
                                                     // of a robot link needs
                                                     // to travel
    pre_place_approach.min_distance =
        grasp_data_
            .approach_retreat_min_dist_;  // half of the desired? Untested.
    pre_place_approach.direction.header.frame_id = grasp_data_.base_link_;
    pre_place_approach.direction.vector.x = 0;
    pre_place_approach.direction.vector.y = 0;
    pre_place_approach.direction.vector.z = -1;  // Approach direction
                                                 // (negative z axis)
                                                 // document this assumption
    place_loc.pre_place_approach = pre_place_approach;

    // Retreat
    moveit_msgs::GripperTranslation post_place_retreat;
    post_place_retreat.direction.header.stamp = ros::Time::now();
    // TODO(ZdenekM): is box_z always height of the object?
    // assume that robot holds the object in the middle of its height

    double des_dist =
        std::max(grasp_data_.approach_retreat_desired_dist_,
                 0.1 +
                     0.5 *
                         grasped_object_->type.bbox
                             .dimensions[shape_msgs::SolidPrimitive::BOX_Z]);

    post_place_retreat.desired_distance =
        des_dist;  // The distance the origin of a robot link needs to travel
                   // -> depends on the object size
    post_place_retreat.min_distance =
        grasp_data_
            .approach_retreat_min_dist_;  // half of the desired? Untested.
    post_place_retreat.direction.header.frame_id = grasp_data_.base_link_;
    post_place_retreat.direction.vector.x = 0;
    post_place_retreat.direction.vector.y = 0;
    post_place_retreat.direction.vector.z = 1;  // Retreat direction (pos z axis)
    place_loc.post_place_retreat = post_place_retreat;

    // Post place posture - use same as pre-grasp posture (the OPEN command)
    place_loc.post_place_posture = grasp_data_.pre_grasp_posture_;

    place_locations.push_back(place_loc);
  }

  if (keep_orientation)
  {
    ROS_INFO_NAMED(group_name_, "Applying orientation constraint...");

    moveit_msgs::OrientationConstraint ocm;
    ocm.link_name = move_group_->getEndEffectorLink();
    ocm.header.frame_id = getPlanningFrame();
    ocm.orientation = move_group_->getCurrentPose().pose.orientation;
    ocm.absolute_x_axis_tolerance = 0.2;
    ocm.absolute_y_axis_tolerance = 0.2;
    ocm.absolute_z_axis_tolerance = M_PI;
    ocm.weight = 1.0;

    moveit_msgs::Constraints c;
    c.orientation_constraints.push_back(ocm);

    move_group_->setPathConstraints(c);
  }

  // Prevent collision with table
  // move_group_->setSupportSurfaceName(SUPPORT_SURFACE3_NAME)

  if (move_group_->place(grasped_object_->object_id, place_locations))
  {
    grasped_object_.reset();
    publishObject();
    move_group_->clearPathConstraints();
    return true;
  }

  ROS_WARN_NAMED(group_name_, "Failed to place");
  return false;
}

std::string artPr2Grasping::getPlanningFrame()
{
  return move_group_->getPlanningFrame();
}

bool artPr2Grasping::hasGraspedObject() { return grasped_object_; }

bool artPr2Grasping::pick(const std::string& object_id, bool pick_only_y_axis)
{
  if (hasGraspedObject())
  {
    ROS_ERROR_NAMED(group_name_, "Can't grasp another object.");
    return false;
  }

  TObjectInfo obj;

  try
  {
    obj = objects_->getObject(object_id);
  }
  catch (const std::invalid_argument& e)
  {
    ROS_ERROR_NAMED(group_name_, "Unknown object_id: %s", object_id.c_str());
    return false;
  }

  std::vector<moveit_msgs::Grasp> grasps;

  geometry_msgs::PoseStamped p = obj.pose;
  p.header.stamp = ros::Time::now();

  if (!transformPose(p))
  {
    return false;
  }

  // visualization only -> published by publishCollisionBB
  // visual_tools_->publishBlock(objects_[id].p, moveit_visual_tools::ORANGE,
  // objects_[id].bb.dimensions[0], objects_[id].bb.dimensions[1],
  // objects_[id].bb.dimensions[2]);

  if (!simple_grasps_->generateShapeGrasps(obj.type.bbox, true, true, p,
                                           grasp_data_, grasps, pick_only_y_axis))
  {
    ROS_ERROR_NAMED(group_name_, "No grasps found.");
    return false;
  }

  // todo fix this (No kinematic solver found)
  std::vector<trajectory_msgs::JointTrajectoryPoint>
      ik_solutions;  // save each grasps ik solution for visualization
  if (!grasp_filter_->filterGrasps(grasps, ik_solutions, true,
                                   grasp_data_.ee_parent_link_, group_name_))
  {
    ROS_ERROR_NAMED(group_name_, "Grasp filtering failed.");
    return false;
  }

  if (grasps.size() == 0)
  {
    ROS_ERROR_NAMED(group_name_, "No feasible grasps found.");
    return false;
  }

  look_at(p);

  // visualization only - takes time
  /*if (!groups_[group]->visual_tools_->publishAnimatedGrasps(grasps,
  groups_[group]->grasp_data_.ee_parent_link_, 0.02)) {

      ROS_WARN("Grasp animation failed");
  }*/

  std::vector<std::string> allowed_touch_objects;
  allowed_touch_objects.push_back(object_id);

  // Add this list to all grasps
  for (std::size_t i = 0; i < grasps.size(); ++i)
  {
    grasps[i].allowed_touch_objects = allowed_touch_objects;
  }

  grasped_object_ = boost::make_shared<TObjectInfo>(obj);
  grasped_object_->object_id = object_id;

  if (!move_group_->pick(object_id, grasps))
  {
    ROS_WARN_NAMED(group_name_, "Failed to pick");
    grasped_object_.reset();
    return false;
  }

  float gripper = getGripperValue();

  if (gripper < 0.005)
  {
    visual_tools_->cleanupACO(object_id);
    grasped_object_.reset();
    ROS_ERROR_NAMED(group_name_,
                    "Gripper is closed - object missed or dropped :-(");
    return false;
  }

  ROS_INFO_NAMED(group_name_, "Picked the object.");
  publishObject(object_id);
  return true;
}

// TODO(ZdenekM): move to Objects? Or somewhere else?
bool artPr2Grasping::addTable()
{

  visual_tools_->cleanupCO("table");

  geometry_msgs::PoseStamped ps;
  ps.header.frame_id = "marker";

  if (!transformPose(ps)) return false;

  for (int j = 0; j < 3; j++)  // hmm, sometimes the table is not added
  {
    if (!visual_tools_->publishCollisionFloor(ps.pose.position.z, "table"))
      return false;
    move_group_->setSupportSurfaceName(name);
    ros::Duration(0.1).sleep();
  }

  return true;
}

}  // namespace art_pr2_grasping
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
$Log$
Revision 1.3  2000/06/25 13:06:39  hristov
Inline functions moved from *.cxx to *.h files instead of forward declarations

Revision 1.2  2000/06/15 07:58:48  morsch
Code from MUON-dev joined

Revision 1.1.2.4  2000/06/12 10:11:10  morsch
Dummy copy constructor and assignment operator added

Revision 1.1.2.3  2000/06/09 22:14:43  morsch
Make includes consistent with new file naming.

Revision 1.1.2.2  2000/06/09 12:58:05  gosset
Removed comment beginnings in Log sections of .cxx files
Suppressed most violations of coding rules

Revision 1.1.2.1  2000/06/07 14:44:53  gosset
Addition of files for track reconstruction in C++
*/

//__________________________________________________________________________
//
// Hit for reconstruction in ALICE dimuon spectrometer
//__________________________________________________________________________

#include "AliMUONHitForRec.h"
#include "AliMUONTrackParam.h"
#include "AliMUONRawCluster.h"
#include "AliMUONHit.h"

ClassImp(AliMUONHitForRec) // Class implementation in ROOT context

  //__________________________________________________________________________
AliMUONHitForRec::AliMUONHitForRec(AliMUONHit* Ghit)
{
  // Constructor for AliMUONHitForRec from a GEANT hit.
  // Fills the bending, non bending, and Z coordinates,
  // which are taken from the coordinates of the GEANT hit,
  // the track number (GEANT and not TH),
  // and the chamber number (0...).
  fBendingCoor = Ghit->Y();
  fNonBendingCoor = Ghit->X();
  fZ = Ghit->Z();
  // fTrack = Ghit->fTrack; ?????????
  fChamberNumber = Ghit->fChamber - 1;
  // other fields will be updated in
  // AliMUONEventReconstructor::NewHitForRecFromGEANT,
  // except the following ones
  fIndexOfFirstSegment = -1;
  fNSegments = 0;
  fFirstTrackHitPtr = fLastTrackHitPtr = NULL;
  fNTrackHits = 0;
  return;
}

//   //__________________________________________________________________________
// AliMUONHitForRec::AliMUONHitForRec(AliMUONReconstHit* CathCorrel)
// {
//   // Constructor for AliMUONHitForRec from a (cathode correlated) raw cluster.
//   // Fills the bending and non bending coordinates.
//   // Only the first correlation is taken into account.
//   // The bending coordinate is taken from the first cathode.
//   // The non bending coordinate is taken
//   // from the second cathode if it exists,
//   // from the first one otherwise.
//   fBendingCoor = CathCorrel->fY[3];
//   if (CathCorrel->fCorrelIndex[0] >= 0) fNonBendingCoor = CathCorrel->fX[0];
//   else fNonBendingCoor = CathCorrel->fX[3];
//   return;
// }

  //__________________________________________________________________________
AliMUONHitForRec::AliMUONHitForRec(AliMUONRawCluster* RawCluster)
{
  // Constructor for AliMUONHitForRec from a raw cluster.
  // Fills the bending and non bending coordinates.
  fNonBendingCoor = RawCluster->fX[0];
  fBendingCoor = RawCluster->fY[0];
  // other fields will be updated in
  // AliMUONEventReconstructor::AddHitsForRecFromRawClusters,
  // except the following ones
  fTHTrack = -1;
  fGeantSignal = -1;
  fIndexOfFirstSegment = -1;
  fNSegments = 0;
  fFirstTrackHitPtr = fLastTrackHitPtr = NULL;
  fNTrackHits = 0;
  return;
}

AliMUONHitForRec::AliMUONHitForRec (const AliMUONHitForRec& MUONHitForRec)
{
// Dummy copy constructor
}

AliMUONHitForRec & AliMUONHitForRec::operator=(const AliMUONHitForRec& MUONHitForRec)
{
// Dummy assignment operator
    return *this;
}
  //__________________________________________________________________________
Int_t AliMUONHitForRec::Compare(TObject* Hit)
{
  // "Compare" function to sort with increasing chamber number.
  // Returns -1 (0, +1) if ChamberNumber of current HitForRec
  // is smaller than (equal to, larger than) ChamberNumber of Hit
  if (fChamberNumber <  ((AliMUONHitForRec*)Hit)->fChamberNumber) return(-1);
  else if (fChamberNumber == ((AliMUONHitForRec*)Hit)->fChamberNumber) return( 0);
  else return(+1);
}

  //__________________________________________________________________________
Double_t AliMUONHitForRec::NormalizedChi2WithHitForRec(AliMUONHitForRec* HitForRec, Double_t Sigma2Cut)
{
  // Calculate the normalized Chi2 between the current HitForRec (this)
  // and the HitForRec pointed to by "HitForRec",
  // i.e. the square deviations between the coordinates,
  // in both the bending and the non bending plane,
  // divided by the variance of the same quantities and by "Sigma2Cut".
  // Returns 3 if none of the 2 quantities is OK,
  // something smaller than or equal to 2 otherwise.
  // Would it be more correct to use a real chi square
  // including the non diagonal term ????
  Double_t chi2, chi2Max, diff, normDiff;
  chi2 = 0.0;
  chi2Max = 3.0;
  // coordinate in bending plane
  diff = this->fBendingCoor - HitForRec->fBendingCoor;
  normDiff = diff * diff /
    (this->fBendingReso2 + HitForRec->fBendingReso2) / Sigma2Cut;
  if (normDiff > 1.0) return chi2Max;
  chi2 = chi2 + normDiff;
  // coordinate in non bending plane
  diff = this->fNonBendingCoor - HitForRec->fNonBendingCoor;
  normDiff = diff * diff /
    (this->fNonBendingReso2 + HitForRec->fNonBendingReso2) / Sigma2Cut;
  if (normDiff > 1.0) return chi2Max;
  chi2 = chi2 + normDiff;
  return chi2;
}
<commit_msg>Use access functions to MUONHit, ... data members.<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
$Log$
Revision 1.4  2000/10/02 21:28:09  fca
Removal of useless dependecies via forward declarations

Revision 1.3  2000/06/25 13:06:39  hristov
Inline functions moved from *.cxx to *.h files instead of forward declarations

Revision 1.2  2000/06/15 07:58:48  morsch
Code from MUON-dev joined

Revision 1.1.2.4  2000/06/12 10:11:10  morsch
Dummy copy constructor and assignment operator added

Revision 1.1.2.3  2000/06/09 22:14:43  morsch
Make includes consistent with new file naming.

Revision 1.1.2.2  2000/06/09 12:58:05  gosset
Removed comment beginnings in Log sections of .cxx files
Suppressed most violations of coding rules

Revision 1.1.2.1  2000/06/07 14:44:53  gosset
Addition of files for track reconstruction in C++
*/

//__________________________________________________________________________
//
// Hit for reconstruction in ALICE dimuon spectrometer
//__________________________________________________________________________

#include "AliMUONHitForRec.h"
#include "AliMUONTrackParam.h"
#include "AliMUONRawCluster.h"
#include "AliMUONHit.h"

ClassImp(AliMUONHitForRec) // Class implementation in ROOT context

  //__________________________________________________________________________
AliMUONHitForRec::AliMUONHitForRec(AliMUONHit* Ghit)
{
  // Constructor for AliMUONHitForRec from a GEANT hit.
  // Fills the bending, non bending, and Z coordinates,
  // which are taken from the coordinates of the GEANT hit,
  // the track number (GEANT and not TH),
  // and the chamber number (0...).
  fBendingCoor = Ghit->Y();
  fNonBendingCoor = Ghit->X();
  fZ = Ghit->Z();
  // fTrack = Ghit->fTrack; ?????????
  fChamberNumber = Ghit->Chamber() - 1;
  // other fields will be updated in
  // AliMUONEventReconstructor::NewHitForRecFromGEANT,
  // except the following ones
  fIndexOfFirstSegment = -1;
  fNSegments = 0;
  fFirstTrackHitPtr = fLastTrackHitPtr = NULL;
  fNTrackHits = 0;
  return;
}

//   //__________________________________________________________________________
// AliMUONHitForRec::AliMUONHitForRec(AliMUONReconstHit* CathCorrel)
// {
//   // Constructor for AliMUONHitForRec from a (cathode correlated) raw cluster.
//   // Fills the bending and non bending coordinates.
//   // Only the first correlation is taken into account.
//   // The bending coordinate is taken from the first cathode.
//   // The non bending coordinate is taken
//   // from the second cathode if it exists,
//   // from the first one otherwise.
//   fBendingCoor = CathCorrel->fY[3];
//   if (CathCorrel->fCorrelIndex[0] >= 0) fNonBendingCoor = CathCorrel->fX[0];
//   else fNonBendingCoor = CathCorrel->fX[3];
//   return;
// }

  //__________________________________________________________________________
AliMUONHitForRec::AliMUONHitForRec(AliMUONRawCluster* RawCluster)
{
  // Constructor for AliMUONHitForRec from a raw cluster.
  // Fills the bending and non bending coordinates.
  fNonBendingCoor = RawCluster->fX[0];
  fBendingCoor = RawCluster->fY[0];
  // other fields will be updated in
  // AliMUONEventReconstructor::AddHitsForRecFromRawClusters,
  // except the following ones
  fTHTrack = -1;
  fGeantSignal = -1;
  fIndexOfFirstSegment = -1;
  fNSegments = 0;
  fFirstTrackHitPtr = fLastTrackHitPtr = NULL;
  fNTrackHits = 0;
  return;
}

AliMUONHitForRec::AliMUONHitForRec (const AliMUONHitForRec& MUONHitForRec)
{
// Dummy copy constructor
}

AliMUONHitForRec & AliMUONHitForRec::operator=(const AliMUONHitForRec& MUONHitForRec)
{
// Dummy assignment operator
    return *this;
}
  //__________________________________________________________________________
Int_t AliMUONHitForRec::Compare(TObject* Hit)
{
  // "Compare" function to sort with increasing chamber number.
  // Returns -1 (0, +1) if ChamberNumber of current HitForRec
  // is smaller than (equal to, larger than) ChamberNumber of Hit
  if (fChamberNumber <  ((AliMUONHitForRec*)Hit)->fChamberNumber) return(-1);
  else if (fChamberNumber == ((AliMUONHitForRec*)Hit)->fChamberNumber) return( 0);
  else return(+1);
}

  //__________________________________________________________________________
Double_t AliMUONHitForRec::NormalizedChi2WithHitForRec(AliMUONHitForRec* HitForRec, Double_t Sigma2Cut)
{
  // Calculate the normalized Chi2 between the current HitForRec (this)
  // and the HitForRec pointed to by "HitForRec",
  // i.e. the square deviations between the coordinates,
  // in both the bending and the non bending plane,
  // divided by the variance of the same quantities and by "Sigma2Cut".
  // Returns 3 if none of the 2 quantities is OK,
  // something smaller than or equal to 2 otherwise.
  // Would it be more correct to use a real chi square
  // including the non diagonal term ????
  Double_t chi2, chi2Max, diff, normDiff;
  chi2 = 0.0;
  chi2Max = 3.0;
  // coordinate in bending plane
  diff = this->fBendingCoor - HitForRec->fBendingCoor;
  normDiff = diff * diff /
    (this->fBendingReso2 + HitForRec->fBendingReso2) / Sigma2Cut;
  if (normDiff > 1.0) return chi2Max;
  chi2 = chi2 + normDiff;
  // coordinate in non bending plane
  diff = this->fNonBendingCoor - HitForRec->fNonBendingCoor;
  normDiff = diff * diff /
    (this->fNonBendingReso2 + HitForRec->fNonBendingReso2) / Sigma2Cut;
  if (normDiff > 1.0) return chi2Max;
  chi2 = chi2 + normDiff;
  return chi2;
}
<|endoftext|>


<commit_before><commit_msg>improv(module_php): Deleted reset of headers and removed raw response fill (#62)<commit_after><|endoftext|>


<commit_before><commit_msg>Fix const-correctness noted by bdash<commit_after><|endoftext|>


<commit_before>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */
#include "appletloader.h"
#include <QTest>
#include <dcpappletif.h>
#include <dcpappletmetadata.h>
#include <dcpbrief.h>
#include <dcpwidget.h>

#ifndef DCP_APPLET_LOADER_DEPRECATED
#include <dcpappletloader.h>
#else
#include <dcpappletplugin.h>
#endif

#define DESKTOP_PATH "/usr/lib/duicontrolpanel/"

void
Ft_AppletLoader::init ()
{
    // Instantiate the classes what we want to test
}

void
Ft_AppletLoader::cleanup ()
{
    // Drop the (tested) objects
}

void
Ft_AppletLoader::initTestCase ()
{
    int argc = 1;
    char *argv[] = {
        "./ft_dcpapplets",
        NULL
    };

    m_app = new DuiApplication (argc, argv);
}

void
Ft_AppletLoader::cleanupTestCase ()
{
    delete m_app;
}

/*!
 * This function will do the basic loading/unloading tests on the applet variant
 * described in the deaktop file.
 */
void
Ft_AppletLoader::DoAppletTest (const char *desktopfile)
{
    DcpAppletMetadata metadata(QString (DESKTOP_PATH) + QString (desktopfile));

#ifndef DCP_APPLET_LOADER_DEPRECATED
    DcpAppletLoader loader (&metadata);
#else
    DcpAppletPlugin loader (&metadata);
#endif

    /*
     * Getting the DcpAppletIf applet interface object. Checking if the applet
     * loaded, the type of the applet interface is right.
     */
    DcpAppletIf *applet = loader.applet ();
    QVERIFY2(applet, qPrintable (loader.errorMsg ()));

    /*
     * Checking if the applet has a non-empty title string.
     */
    QVERIFY(! applet->title ().isEmpty ());

    /*
     * Checking if the applet brief is constructed.
     */
    DcpBrief *brief = applet->constructBrief ();
    QVERIFY2(brief,
		    "Error when creating brief widget");

    /*
     * Checking if the the main view (the applet widget) is constructed. FIXME:
     * We should call the getMainWidgetId here, but I'm not sure how it is done
     * after the refactoring.
     */
    DuiWidget *widget = applet->constructWidget (0);
    QVERIFY2(widget,
		    "Error when creating applet's main widget");

    delete widget;
    delete brief;
}

void
Ft_AppletLoader::testbatteryapplet ()
{
    DoAppletTest ("battery.desktop");
}

void
Ft_AppletLoader::testdisplayapplet ()
{
    DoAppletTest ("display.desktop");
}

void
Ft_AppletLoader::testledapplet ()
{
    DoAppletTest ("ledapplet.desktop");
}

void
Ft_AppletLoader::testprofileapplet ()
{
    DoAppletTest ("profile.desktop");
}

void
Ft_AppletLoader::testusbapplet ()
{
    DoAppletTest ("usbapplet.desktop");
}

QTEST_APPLESS_MAIN(Ft_AppletLoader)
<commit_msg>Fix a warning at build<commit_after>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */
#include "appletloader.h"
#include <QTest>
#include <dcpappletif.h>
#include <dcpappletmetadata.h>
#include <dcpbrief.h>
#include <dcpwidget.h>

#ifndef DCP_APPLET_LOADER_DEPRECATED
#include <dcpappletloader.h>
#else
#include <dcpappletplugin.h>
#endif

#define DESKTOP_PATH "/usr/lib/duicontrolpanel/"

void
Ft_AppletLoader::init ()
{
    // Instantiate the classes what we want to test
}

void
Ft_AppletLoader::cleanup ()
{
    // Drop the (tested) objects
}

void
Ft_AppletLoader::initTestCase ()
{
    int argc = 1;
    char *argv[] = {
        (char *) "./ft_dcpapplets",
        NULL
    };

    m_app = new DuiApplication (argc, argv);
}

void
Ft_AppletLoader::cleanupTestCase ()
{
    delete m_app;
}

/*!
 * This function will do the basic loading/unloading tests on the applet variant
 * described in the deaktop file.
 */
void
Ft_AppletLoader::DoAppletTest (const char *desktopfile)
{
    DcpAppletMetadata metadata(QString (DESKTOP_PATH) + QString (desktopfile));

#ifndef DCP_APPLET_LOADER_DEPRECATED
    DcpAppletLoader loader (&metadata);
#else
    DcpAppletPlugin loader (&metadata);
#endif

    /*
     * Getting the DcpAppletIf applet interface object. Checking if the applet
     * loaded, the type of the applet interface is right.
     */
    DcpAppletIf *applet = loader.applet ();
    QVERIFY2(applet, qPrintable (loader.errorMsg ()));

    /*
     * Checking if the applet has a non-empty title string.
     */
    QVERIFY(! applet->title ().isEmpty ());

    /*
     * Checking if the applet brief is constructed.
     */
    DcpBrief *brief = applet->constructBrief ();
    QVERIFY2(brief,
		    "Error when creating brief widget");

    /*
     * Checking if the the main view (the applet widget) is constructed. FIXME:
     * We should call the getMainWidgetId here, but I'm not sure how it is done
     * after the refactoring.
     */
    DuiWidget *widget = applet->constructWidget (0);
    QVERIFY2(widget,
		    "Error when creating applet's main widget");

    delete widget;
    delete brief;
}

void
Ft_AppletLoader::testbatteryapplet ()
{
    DoAppletTest ("battery.desktop");
}

void
Ft_AppletLoader::testdisplayapplet ()
{
    DoAppletTest ("display.desktop");
}

void
Ft_AppletLoader::testledapplet ()
{
    DoAppletTest ("ledapplet.desktop");
}

void
Ft_AppletLoader::testprofileapplet ()
{
    DoAppletTest ("profile.desktop");
}

void
Ft_AppletLoader::testusbapplet ()
{
    DoAppletTest ("usbapplet.desktop");
}

QTEST_APPLESS_MAIN(Ft_AppletLoader)
<|endoftext|>


<commit_before><commit_msg>- fix truncated stdout/err in subprocess<commit_after><|endoftext|>


<commit_before>/****************************************************************************
 * Copyright (c) 2012-2019 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/
#ifndef DTK_DETAILS_TREE_VISUALIZATION_HPP
#define DTK_DETAILS_TREE_VISUALIZATION_HPP

#include <DTK_DetailsTreeTraversal.hpp>

#include <Kokkos_View.hpp>

#if !defined( ARBORX_ENABLE_VIZ )
static_assert(
    false,
    "do not include this header when tree visualization mode is not enabled" );
#endif

namespace DataTransferKit
{
namespace Details
{
template <typename DeviceType>
struct TreeVisualization
{
    // You have been warned :)
    using TreeAccess = typename TreeTraversal<
        DeviceType>::DoNotUseUnlessYouKnowWhatYouAreDoing;

    template <typename Tree>
    static std::string getNodeLabel( Node const *node, Tree const &tree )
    {
        auto const node_is_leaf = TreeAccess::isLeaf( node, tree );
        auto const node_index = TreeAccess::getIndex( node, tree );
        std::string label = node_is_leaf ? "l" : "i";
        label.append( std::to_string( node_index ) );
        return label;
    }

    template <typename Tree>
    static std::string getNodeAttributes( Node const *node, Tree const &tree )
    {
        return TreeAccess::isLeaf( node, tree ) ? "[leaf]" : "[internal]";
    }

    template <typename Tree>
    static std::string getEdgeAttributes( Node const *parent, Node const *child,
                                          Tree const &tree )
    {
        return TreeAccess::isLeaf( child, tree ) ? "[pendant]" : "[edge]";
    }

    struct GraphvizVisitor
    {
        std::ostream &_os;

        template <typename Tree>
        void visit( Node const *node, Tree const &tree ) const
        {
            visitNode( node, tree );
            visitEdgesStartingFromNode( node, tree );
        }

        template <typename Tree>
        void visitNode( Node const *node, Tree const &tree ) const
        {
            auto const node_label = getNodeLabel( node, tree );
            auto const node_attributes = getNodeAttributes( node, tree );

            _os << "    " << node_label << " " << node_attributes << ";\n";
        }

        template <typename Tree>
        void visitEdgesStartingFromNode( Node const *node,
                                         Tree const &tree ) const
        {
            auto const node_label = getNodeLabel( node, tree );
            auto const node_is_internal = !TreeAccess::isLeaf( node, tree );

            if ( node_is_internal )
                for ( Node const *child :
                      {node->children.first, node->children.second} )
                {
                    auto const child_label = getNodeLabel( child, tree );
                    auto const edge_attributes =
                        getEdgeAttributes( node, child, tree );

                    _os << "    " << node_label << " -> " << child_label << " "
                        << edge_attributes << ";\n";
                }
        }
    };

    template <typename Tree, typename Visitor>
    static void visitAllIterative( Tree const &tree, Visitor const &visitor )
    {
        Stack<Node const *> stack;
        stack.emplace( TreeAccess::getRoot( tree ) );
        while ( !stack.empty() )
        {
            Node const *node = stack.top();
            stack.pop();

            visitor.visit( node, tree );

            if ( !TreeAccess::isLeaf( node, tree ) )
                for ( Node const *child :
                      {node->children.first, node->children.second} )
                    stack.push( child );
        }
    }

    template <typename Tree, typename Predicate, typename Visitor>
    static int visit( Tree const &tree, Predicate const &pred,
                      Visitor const &visitor )
    {
        auto const geometry = pred._geometry;
        auto const k = pred._k;
        Kokkos::View<Kokkos::pair<int, double> *, DeviceType> buffer( "buffer",
                                                                      k );
        int const count = TreeTraversal<DeviceType>::nearestQuery(
            tree,
            [geometry, &visitor, &tree]( Node const *node ) {
                visitor.visit( node, tree );
                return distance( geometry,
                                 TreeAccess::getBoundingVolume( node, tree ) );
            },
            k, []( int, double ) {}, buffer );
        return count;
    }
};
} // namespace Details
} // namespace DataTransferKit

#endif
<commit_msg>Silent warnings about calling a __host__ function from a __host__ __device__ function in viz<commit_after>/****************************************************************************
 * Copyright (c) 2012-2019 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/
#ifndef DTK_DETAILS_TREE_VISUALIZATION_HPP
#define DTK_DETAILS_TREE_VISUALIZATION_HPP

#include <DTK_DetailsTreeTraversal.hpp>

#include <Kokkos_View.hpp>

#if !defined( ARBORX_ENABLE_VIZ )
static_assert(
    false,
    "do not include this header when tree visualization mode is not enabled" );
#endif

namespace DataTransferKit
{
namespace Details
{
template <typename DeviceType>
struct TreeVisualization
{
    // You have been warned :)
    using TreeAccess = typename TreeTraversal<
        DeviceType>::DoNotUseUnlessYouKnowWhatYouAreDoing;

    template <typename Tree>
    static std::string getNodeLabel( Node const *node, Tree const &tree )
    {
        auto const node_is_leaf = TreeAccess::isLeaf( node, tree );
        auto const node_index = TreeAccess::getIndex( node, tree );
        std::string label = node_is_leaf ? "l" : "i";
        label.append( std::to_string( node_index ) );
        return label;
    }

    template <typename Tree>
    static std::string getNodeAttributes( Node const *node, Tree const &tree )
    {
        return TreeAccess::isLeaf( node, tree ) ? "[leaf]" : "[internal]";
    }

    template <typename Tree>
    static std::string getEdgeAttributes( Node const *parent, Node const *child,
                                          Tree const &tree )
    {
        return TreeAccess::isLeaf( child, tree ) ? "[pendant]" : "[edge]";
    }

    struct GraphvizVisitor
    {
        std::ostream &_os;

        template <typename Tree>
        void visit( Node const *node, Tree const &tree ) const
        {
            visitNode( node, tree );
            visitEdgesStartingFromNode( node, tree );
        }

        template <typename Tree>
        void visitNode( Node const *node, Tree const &tree ) const
        {
            auto const node_label = getNodeLabel( node, tree );
            auto const node_attributes = getNodeAttributes( node, tree );

            _os << "    " << node_label << " " << node_attributes << ";\n";
        }

        template <typename Tree>
        void visitEdgesStartingFromNode( Node const *node,
                                         Tree const &tree ) const
        {
            auto const node_label = getNodeLabel( node, tree );
            auto const node_is_internal = !TreeAccess::isLeaf( node, tree );

            if ( node_is_internal )
                for ( Node const *child :
                      {node->children.first, node->children.second} )
                {
                    auto const child_label = getNodeLabel( child, tree );
                    auto const edge_attributes =
                        getEdgeAttributes( node, child, tree );

                    _os << "    " << node_label << " -> " << child_label << " "
                        << edge_attributes << ";\n";
                }
        }
    };

    template <typename Tree, typename Visitor>
    static void visitAllIterative( Tree const &tree, Visitor const &visitor )
    {
        Stack<Node const *> stack;
        stack.emplace( TreeAccess::getRoot( tree ) );
        while ( !stack.empty() )
        {
            Node const *node = stack.top();
            stack.pop();

            visitor.visit( node, tree );

            if ( !TreeAccess::isLeaf( node, tree ) )
                for ( Node const *child :
                      {node->children.first, node->children.second} )
                    stack.push( child );
        }
    }

    template <typename Tree, typename Predicate, typename Visitor>
    static int visit( Tree const &tree, Predicate const &pred,
                      Visitor const &visitor )
    {
#if defined( __CUDA_ARCH__ )
        throw std::runtime_error( "not meant to execute on the GPU" );
#else
        auto const geometry = pred._geometry;
        auto const k = pred._k;
        Kokkos::View<Kokkos::pair<int, double> *, DeviceType> buffer( "buffer",
                                                                      k );
        int const count = TreeTraversal<DeviceType>::nearestQuery(
            tree,
            [geometry, &visitor, &tree]( Node const *node ) {
                visitor.visit( node, tree );
                return distance( geometry,
                                 TreeAccess::getBoundingVolume( node, tree ) );
            },
            k, []( int, double ) {}, buffer );
        return count;
#endif
    }
};
} // namespace Details
} // namespace DataTransferKit

#endif
<|endoftext|>