<commit_before>// @(#)root/test:$Id$
// Author: Rene Brun   19/01/97

////////////////////////////////////////////////////////////////////////
//
//             A simple example with a ROOT tree
//             =================================
//
//  This program creates :
//    - a ROOT file
//    - a tree
//  Additional arguments can be passed to the program to control the flow
//  of execution. (see comments describing the arguments in the code).
//      Event  nevent comp split fill
//  All arguments are optional. Default is:
//      Event  400      1    1     1
//
//  In this example, the tree consists of one single "super branch"
//  The statement ***tree->Branch("event", &event, 64000,split);*** below
//  will parse the structure described in Event.h and will make
//  a new branch for each data member of the class if split is set to 1.
//    - 9 branches corresponding to the basic types fType, fNtrack,fNseg,
//           fNvertex,fFlag,fTemperature,fMeasures,fMatrix,fClosesDistance.
//    - 3 branches corresponding to the members of the subobject EventHeader.
//    - one branch for each data member of the class Track of TClonesArray.
//    - one branch for the TRefArray of high Pt tracks
//    - one branch for the TRefArray of muon tracks
//    - one branch for the reference pointer to the last track
//    - one branch for the object fH (histogram of class TH1F).
//
//  if split = 0 only one single branch is created and the complete event
//  is serialized in one single buffer.
//  if split = -2 the event is split using the old TBranchObject mechanism
//  if split = -1 the event is streamed using the old TBranchObject mechanism
//  if split > 0  the event is split using the new TBranchElement mechanism.
//
//  if comp = 0 no compression at all.
//  if comp = 1 event is compressed.
//  if comp = 2 same as 1. In addition branches with floats in the TClonesArray
//                         are also compressed.
//  The 4th argument fill can be set to 0 if one wants to time
//     the percentage of time spent in creating the event structure and
//     not write the event in the file.
//  In this example, one loops over nevent events.
//  The branch "event" is created at the first event.
//  The branch address is set for all other events.
//  For each event, the event header is filled and ntrack tracks
//  are generated and added to the TClonesArray list.
//  For each event the event histogram is saved as well as the list
//  of all tracks.
//
//  The two TRefArray contain only references to the original tracks owned by
//  the TClonesArray fTracks.
//
//  The number of events can be given as the first argument to the program.
//  By default 400 events are generated.
//  The compression option can be activated/deactivated via the second argument.
//
//   ---Running/Linking instructions----
//  This program consists of the following files and procedures.
//    - Event.h event class description
//    - Event.C event class implementation
//    - MainEvent.C the main program to demo this class might be used (this file)
//    - EventCint.C  the CINT dictionary for the event and Track classes
//        this file is automatically generated by rootcint (see Makefile),
//        when the class definition in Event.h is modified.
//
//   ---Analyzing the Event.root file with the interactive root
//        example of a simple session
//   Root > TFile f("Event.root")
//   Root > T.Draw("fNtrack")   //histogram the number of tracks per event
//   Root > T.Draw("fPx")       //histogram fPx for all tracks in all events
//   Root > T.Draw("fXfirst:fYfirst","fNtrack>600")
//                              //scatter-plot for x versus y of first point of each track
//   Root > T.Draw("fH.GetRMS()")  //histogram of the RMS of the event histogram
//
//   Look also in the same directory at the following macros:
//     - eventa.C  an example how to read the tree
//     - eventb.C  how to read events conditionally
//
////////////////////////////////////////////////////////////////////////

#include <stdlib.h>

#include "Riostream.h"
#include "TROOT.h"
#include "TFile.h"
#include "TNetFile.h"
#include "TRandom.h"
#include "TTree.h"
#include "TTreeCache.h"
#include "TBranch.h"
#include "TClonesArray.h"
#include "TStopwatch.h"
#include "TTreeCacheUnzip.h"

#include "Event.h"

//______________________________________________________________________________
int main(int argc, char **argv)
{
   Int_t nevent = 400;     // by default create 400 events
   Int_t comp   = 1;       // by default file is compressed
   Int_t split  = 1;       // by default, split Event in sub branches
   Int_t write  = 1;       // by default the tree is filled
   Int_t hfill  = 0;       // by default histograms are not filled
   Int_t read   = 0;
   Int_t arg4   = 1;
   Int_t arg5   = 600;     //default number of tracks per event
   Int_t netf   = 0;
   Int_t punzip = 0;

   if (argc > 1)  nevent = atoi(argv[1]);
   if (argc > 2)  comp   = atoi(argv[2]);
   if (argc > 3)  split  = atoi(argv[3]);
   if (argc > 4)  arg4   = atoi(argv[4]);
   if (argc > 5)  arg5   = atoi(argv[5]);
   if (arg4 ==  0) { write = 0; hfill = 0; read = 1;}
   if (arg4 ==  1) { write = 1; hfill = 0;}
   if (arg4 ==  2) { write = 0; hfill = 0;}
   if (arg4 == 10) { write = 0; hfill = 1;}
   if (arg4 == 11) { write = 1; hfill = 1;}
   if (arg4 == 20) { write = 0; read  = 1;}  //read sequential
   if (arg4 == 21) { write = 0; read  = 1;  punzip = 1;}  //read sequential + parallel unzipping
   if (arg4 == 25) { write = 0; read  = 2;}  //read random
   if (arg4 >= 30) { netf  = 1; }            //use TNetFile
   if (arg4 == 30) { write = 0; read  = 1;}  //netfile + read sequential
   if (arg4 == 35) { write = 0; read  = 2;}  //netfile + read random
   if (arg4 == 36) { write = 1; }            //netfile + write sequential
   Int_t branchStyle = 1; //new style by default
   if (split < 0) {branchStyle = 0; split = -1-split;}

   TFile *hfile;
   TTree *tree;
   Event *event = 0;

   // Fill event, header and tracks with some random numbers
   //   Create a timer object to benchmark this loop
   TStopwatch timer;
   timer.Start();
   Long64_t nb = 0;
   Int_t ev;
   Int_t bufsize;
   Double_t told = 0;
   Double_t tnew = 0;
   Int_t printev = 100;
   if (arg5 < 100) printev = 1000;
   if (arg5 < 10)  printev = 10000;

   //Authorize Trees up to 2 Terabytes (if the system can do it)
   TTree::SetMaxTreeSize(1000*Long64_t(2000000000));

//         Read case
   if (read) {
      if (netf) {
         hfile = new TNetFile("root://localhost/root/test/EventNet.root");
      } else
         hfile = new TFile("Event.root");
      if(punzip) TTreeCacheUnzip::SetParallelUnzip(TTreeCacheUnzip::kEnable);
      tree = (TTree*)hfile->Get("T");
      TBranch *branch = tree->GetBranch("event");
      branch->SetAddress(&event);
      Int_t nentries = (Int_t)tree->GetEntries();
      nevent = TMath::Max(nevent,nentries);
      if (read == 1) {  //read sequential
         //set the read cache
         Int_t cachesize = 10000000; //this is the default value: 10 MBytes
         tree->SetCacheSize(cachesize);
         TTreeCache::SetLearnEntries(1); //one entry is sufficient to learn
         TTreeCache *tc = (TTreeCache*)hfile->GetCacheRead();
         tc->SetEntryRange(0,nevent);
         for (ev = 0; ev < nevent; ev++) {
            tree->LoadTree(ev);  //this call is required when using the cache
            if (ev%printev == 0) {
               tnew = timer.RealTime();
               printf("event:%d, rtime=%f s\n",ev,tnew-told);
               told=tnew;
               timer.Continue();
            }
            nb += tree->GetEntry(ev);        //read complete event in memory
         }
      } else {    //read random
         Int_t evrandom;
         for (ev = 0; ev < nevent; ev++) {
            if (ev%printev == 0) cout<<"event="<<ev<<endl;
            evrandom = Int_t(nevent*gRandom->Rndm(1));
            nb += tree->GetEntry(evrandom);  //read complete event in memory
         }
      }
   } else {
//         Write case
      // Create a new ROOT binary machine independent file.
      // Note that this file may contain any kind of ROOT objects, histograms,
      // pictures, graphics objects, detector geometries, tracks, events, etc..
      // This file is now becoming the current directory.
      if (netf) {
         hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file");
      } else
         hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file");
      hfile->SetCompressionLevel(comp);

     // Create histogram to show write_time in function of time
     Float_t curtime = -0.5;
     Int_t ntime = nevent/printev;
     TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime);
     HistogramManager *hm = 0;
     if (hfill) {
        TDirectory *hdir = new TDirectory("histograms", "all histograms");
        hm = new HistogramManager(hdir);
     }

     // Create a ROOT Tree and one superbranch
      tree = new TTree("T","An example of a ROOT tree");
      tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written
      tree->SetCacheSize(10000000);  //set a 10 MBytes cache (useless when writing local files)
      bufsize = 64000;
      if (split)  bufsize /= 4;
      event = new Event();
      TTree::SetBranchStyle(branchStyle);
      TBranch *branch = tree->Branch("event", &event, bufsize,split);
      branch->SetAutoDelete(kFALSE);
      if(split >= 0 && branchStyle) tree->BranchRef();
      Float_t ptmin = 1;

      for (ev = 0; ev < nevent; ev++) {
         if (ev%printev == 0) {
            tnew = timer.RealTime();
            printf("event:%d, rtime=%f s\n",ev,tnew-told);
            htime->Fill(curtime,tnew-told);
            curtime += 1;
            told=tnew;
            timer.Continue();
         }

         event->Build(ev, arg5, ptmin);

         if (write) nb += tree->Fill();  //fill the tree

         if (hm) hm->Hfill(event);      //fill histograms
      }
      if (write) {
         hfile = tree->GetCurrentFile(); //just in case we switched to a new file
         hfile->Write();
         tree->Print();
      }
   }

   //  Stop timer and print results
   timer.Stop();
   Float_t mbytes = 0.000001*nb;
   Double_t rtime = timer.RealTime();
   Double_t ctime = timer.CpuTime();

   printf("\n%d events and %lld bytes processed.\n",nevent,nb);
   printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime);
   if (read) {
      printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime);
      printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime);
   } else {
      printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4);
      printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime);
      printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime);
      //printf("file compression factor = %f\n",hfile.GetCompressionFactor());
   }
   hfile->Close();
   return 0;
}
<commit_msg>When writing baskets are automatically optimized once we have written 10 MBytes to the file.<commit_after>// @(#)root/test:$Id$
// Author: Rene Brun   19/01/97

////////////////////////////////////////////////////////////////////////
//
//             A simple example with a ROOT tree
//             =================================
//
//  This program creates :
//    - a ROOT file
//    - a tree
//  Additional arguments can be passed to the program to control the flow
//  of execution. (see comments describing the arguments in the code).
//      Event  nevent comp split fill
//  All arguments are optional. Default is:
//      Event  400      1    1     1
//
//  In this example, the tree consists of one single "super branch"
//  The statement ***tree->Branch("event", &event, 64000,split);*** below
//  will parse the structure described in Event.h and will make
//  a new branch for each data member of the class if split is set to 1.
//    - 9 branches corresponding to the basic types fType, fNtrack,fNseg,
//           fNvertex,fFlag,fTemperature,fMeasures,fMatrix,fClosesDistance.
//    - 3 branches corresponding to the members of the subobject EventHeader.
//    - one branch for each data member of the class Track of TClonesArray.
//    - one branch for the TRefArray of high Pt tracks
//    - one branch for the TRefArray of muon tracks
//    - one branch for the reference pointer to the last track
//    - one branch for the object fH (histogram of class TH1F).
//
//  if split = 0 only one single branch is created and the complete event
//  is serialized in one single buffer.
//  if split = -2 the event is split using the old TBranchObject mechanism
//  if split = -1 the event is streamed using the old TBranchObject mechanism
//  if split > 0  the event is split using the new TBranchElement mechanism.
//  if split > 90 the branch buffer sizes are optimized once 10 MBytes written to the file
//
//  if comp = 0 no compression at all.
//  if comp = 1 event is compressed.
//  if comp = 2 same as 1. In addition branches with floats in the TClonesArray
//                         are also compressed.
//  The 4th argument fill can be set to 0 if one wants to time
//     the percentage of time spent in creating the event structure and
//     not write the event in the file.
//  In this example, one loops over nevent events.
//  The branch "event" is created at the first event.
//  The branch address is set for all other events.
//  For each event, the event header is filled and ntrack tracks
//  are generated and added to the TClonesArray list.
//  For each event the event histogram is saved as well as the list
//  of all tracks.
//
//  The two TRefArray contain only references to the original tracks owned by
//  the TClonesArray fTracks.
//
//  The number of events can be given as the first argument to the program.
//  By default 400 events are generated.
//  The compression option can be activated/deactivated via the second argument.
//
//   ---Running/Linking instructions----
//  This program consists of the following files and procedures.
//    - Event.h event class description
//    - Event.C event class implementation
//    - MainEvent.C the main program to demo this class might be used (this file)
//    - EventCint.C  the CINT dictionary for the event and Track classes
//        this file is automatically generated by rootcint (see Makefile),
//        when the class definition in Event.h is modified.
//
//   ---Analyzing the Event.root file with the interactive root
//        example of a simple session
//   Root > TFile f("Event.root")
//   Root > T.Draw("fNtrack")   //histogram the number of tracks per event
//   Root > T.Draw("fPx")       //histogram fPx for all tracks in all events
//   Root > T.Draw("fXfirst:fYfirst","fNtrack>600")
//                              //scatter-plot for x versus y of first point of each track
//   Root > T.Draw("fH.GetRMS()")  //histogram of the RMS of the event histogram
//
//   Look also in the same directory at the following macros:
//     - eventa.C  an example how to read the tree
//     - eventb.C  how to read events conditionally
//
////////////////////////////////////////////////////////////////////////

#include <stdlib.h>

#include "Riostream.h"
#include "TROOT.h"
#include "TFile.h"
#include "TNetFile.h"
#include "TRandom.h"
#include "TTree.h"
#include "TTreeCache.h"
#include "TBranch.h"
#include "TClonesArray.h"
#include "TStopwatch.h"
#include "TTreeCacheUnzip.h"

#include "Event.h"

//______________________________________________________________________________
int main(int argc, char **argv)
{
   Int_t nevent = 400;     // by default create 400 events
   Int_t comp   = 1;       // by default file is compressed
   Int_t split  = 1;       // by default, split Event in sub branches
   Int_t write  = 1;       // by default the tree is filled
   Int_t hfill  = 0;       // by default histograms are not filled
   Int_t read   = 0;
   Int_t arg4   = 1;
   Int_t arg5   = 600;     //default number of tracks per event
   Int_t netf   = 0;
   Int_t punzip = 0;

   if (argc > 1)  nevent = atoi(argv[1]);
   if (argc > 2)  comp   = atoi(argv[2]);
   if (argc > 3)  split  = atoi(argv[3]);
   if (argc > 4)  arg4   = atoi(argv[4]);
   if (argc > 5)  arg5   = atoi(argv[5]);
   if (arg4 ==  0) { write = 0; hfill = 0; read = 1;}
   if (arg4 ==  1) { write = 1; hfill = 0;}
   if (arg4 ==  2) { write = 0; hfill = 0;}
   if (arg4 == 10) { write = 0; hfill = 1;}
   if (arg4 == 11) { write = 1; hfill = 1;}
   if (arg4 == 20) { write = 0; read  = 1;}  //read sequential
   if (arg4 == 21) { write = 0; read  = 1;  punzip = 1;}  //read sequential + parallel unzipping
   if (arg4 == 25) { write = 0; read  = 2;}  //read random
   if (arg4 >= 30) { netf  = 1; }            //use TNetFile
   if (arg4 == 30) { write = 0; read  = 1;}  //netfile + read sequential
   if (arg4 == 35) { write = 0; read  = 2;}  //netfile + read random
   if (arg4 == 36) { write = 1; }            //netfile + write sequential
   Int_t branchStyle = 1; //new style by default
   if (split < 0) {branchStyle = 0; split = -1-split;}

   TFile *hfile;
   TTree *tree;
   Event *event = 0;

   // Fill event, header and tracks with some random numbers
   //   Create a timer object to benchmark this loop
   TStopwatch timer;
   timer.Start();
   Long64_t nb = 0;
   Int_t ev;
   Int_t bufsize;
   Double_t told = 0;
   Double_t tnew = 0;
   Int_t printev = 100;
   if (arg5 < 100) printev = 1000;
   if (arg5 < 10)  printev = 10000;

   //Authorize Trees up to 2 Terabytes (if the system can do it)
   TTree::SetMaxTreeSize(1000*Long64_t(2000000000));

//         Read case
   if (read) {
      if (netf) {
         hfile = new TNetFile("root://localhost/root/test/EventNet.root");
      } else
         hfile = new TFile("Event.root");
      if(punzip) TTreeCacheUnzip::SetParallelUnzip(TTreeCacheUnzip::kEnable);
      tree = (TTree*)hfile->Get("T");
      TBranch *branch = tree->GetBranch("event");
      branch->SetAddress(&event);
      Int_t nentries = (Int_t)tree->GetEntries();
      nevent = TMath::Max(nevent,nentries);
      if (read == 1) {  //read sequential
         //set the read cache
         Int_t cachesize = 10000000; //this is the default value: 10 MBytes
         tree->SetCacheSize(cachesize);
         TTreeCache::SetLearnEntries(1); //one entry is sufficient to learn
         TTreeCache *tc = (TTreeCache*)hfile->GetCacheRead();
         tc->SetEntryRange(0,nevent);
         for (ev = 0; ev < nevent; ev++) {
            tree->LoadTree(ev);  //this call is required when using the cache
            if (ev%printev == 0) {
               tnew = timer.RealTime();
               printf("event:%d, rtime=%f s\n",ev,tnew-told);
               told=tnew;
               timer.Continue();
            }
            nb += tree->GetEntry(ev);        //read complete event in memory
         }
      } else {    //read random
         Int_t evrandom;
         for (ev = 0; ev < nevent; ev++) {
            if (ev%printev == 0) cout<<"event="<<ev<<endl;
            evrandom = Int_t(nevent*gRandom->Rndm(1));
            nb += tree->GetEntry(evrandom);  //read complete event in memory
         }
      }
   } else {
//         Write case
      // Create a new ROOT binary machine independent file.
      // Note that this file may contain any kind of ROOT objects, histograms,
      // pictures, graphics objects, detector geometries, tracks, events, etc..
      // This file is now becoming the current directory.
      if (netf) {
         hfile = new TNetFile("root://localhost/root/test/EventNet.root","RECREATE","TTree benchmark ROOT file");
      } else
         hfile = new TFile("Event.root","RECREATE","TTree benchmark ROOT file");
      hfile->SetCompressionLevel(comp);

     // Create histogram to show write_time in function of time
     Float_t curtime = -0.5;
     Int_t ntime = nevent/printev;
     TH1F *htime = new TH1F("htime","Real-Time to write versus time",ntime,0,ntime);
     HistogramManager *hm = 0;
     if (hfill) {
        TDirectory *hdir = new TDirectory("histograms", "all histograms");
        hm = new HistogramManager(hdir);
     }

     // Create a ROOT Tree and one superbranch
      tree = new TTree("T","An example of a ROOT tree");
      tree->SetAutoSave(1000000000); // autosave when 1 Gbyte written
      tree->SetCacheSize(10000000);  //set a 10 MBytes cache (useless when writing local files)
      bufsize = 64000;
      if (split)  bufsize /= 4;
      event = new Event();
      TTree::SetBranchStyle(branchStyle);
      TBranch *branch = tree->Branch("event", &event, bufsize,split);
      branch->SetAutoDelete(kFALSE);
      if(split >= 0 && branchStyle) tree->BranchRef();
      Float_t ptmin = 1;

      Bool_t optimize = kTRUE;
      if (split < 90) optimize = kFALSE;
      for (ev = 0; ev < nevent; ev++) {
         if (ev%printev == 0) {
            tnew = timer.RealTime();
            printf("event:%d, rtime=%f s\n",ev,tnew-told);
            htime->Fill(curtime,tnew-told);
            curtime += 1;
            told=tnew;
            timer.Continue();
         }

         event->Build(ev, arg5, ptmin);

         if (write) nb += tree->Fill();  //fill the tree
         if (optimize) { //optimize baskets sizes once we have written 10 MBytes
            if (tree->GetZipBytes() > 10000000) {
               tree->OptimizeBaskets(5000000,1); // 5Mbytes for basket buffers
               optimize = kFALSE;
            }
         }

         if (hm) hm->Hfill(event);      //fill histograms
      }
      if (write) {
         hfile = tree->GetCurrentFile(); //just in case we switched to a new file
         hfile->Write();
         tree->Print();
      }
   }

   //  Stop timer and print results
   timer.Stop();
   Float_t mbytes = 0.000001*nb;
   Double_t rtime = timer.RealTime();
   Double_t ctime = timer.CpuTime();

   printf("\n%d events and %lld bytes processed.\n",nevent,nb);
   printf("RealTime=%f seconds, CpuTime=%f seconds\n",rtime,ctime);
   if (read) {
      printf("You read %f Mbytes/Realtime seconds\n",mbytes/rtime);
      printf("You read %f Mbytes/Cputime seconds\n",mbytes/ctime);
   } else {
      printf("compression level=%d, split=%d, arg4=%d\n",comp,split,arg4);
      printf("You write %f Mbytes/Realtime seconds\n",mbytes/rtime);
      printf("You write %f Mbytes/Cputime seconds\n",mbytes/ctime);
      //printf("file compression factor = %f\n",hfile.GetCompressionFactor());
   }
   hfile->Close();
   return 0;
}
<|endoftext|>


<commit_before>
#include "TestUtil.hpp"

#include "LuaCpp/LuaReference.hpp"

using namespace luacpp;

class LuaReferenceTest : public LuaStateTest
{};

TEST_F(LuaReferenceTest, Create)
{
	{
		lua_pushboolean(L, 1);
		lua_pushnumber(L, 42.0);

		auto top = lua_gettop(L);

		auto ref = LuaReference::create(L, -2);

		// This may not modify the stack!
		ASSERT_EQ(top, lua_gettop(L));

		ref->pushValue();

		ASSERT_TRUE(lua_isboolean(L, -1) == 1);
		ASSERT_TRUE(lua_toboolean(L, -1) == 1);
	}
}

TEST_F(LuaReferenceTest, IsValid)
{
	{
		LuaReference ref;

		ASSERT_FALSE(ref.isValid());
	}
	{
		lua_pushboolean(L, 1);

		LuaReferencePtr refPtr = LuaReference::create(L);

		ASSERT_TRUE(refPtr->isValid());

		refPtr->removeReference();

		ASSERT_FALSE(refPtr->isValid());
	}
}

TEST_F(LuaReferenceTest, RemoveReference)
{
	lua_pushboolean(L, 1);

	LuaReferencePtr refPtr = LuaReference::create(L);

	ASSERT_TRUE(refPtr->removeReference());

	ASSERT_FALSE(refPtr->removeReference());
}

TEST_F(LuaReferenceTest, PushValue)
{
	lua_pushboolean(L, 1);

	LuaReferencePtr refPtr = LuaReference::create(L);

	lua_pop(L, 1);

	refPtr->pushValue();

	ASSERT_TRUE(lua_isboolean(L, -1) == 1);
	ASSERT_EQ(1, lua_toboolean(L, -1));
}
<commit_msg>Fix reference tests<commit_after>
#include "TestUtil.hpp"

#include "LuaCpp/LuaReference.hpp"

using namespace luacpp;

class LuaReferenceTest : public LuaStateTest
{};

TEST_F(LuaReferenceTest, Create)
{
	{
		lua_pushboolean(L, 1);
		lua_pushnumber(L, 42.0);

		auto top = lua_gettop(L);

		auto ref = LuaReference::create(L, -2);

		// This may not modify the stack!
		ASSERT_EQ(top, lua_gettop(L));

		// Remove the two values again
		lua_pop(L, 2);

		ref->pushValue();

		ASSERT_TRUE(lua_isboolean(L, -1) == 1);
		ASSERT_TRUE(lua_toboolean(L, -1) == 1);

		lua_pop(L, 1);
	}
}

TEST_F(LuaReferenceTest, IsValid)
{
	{
		LuaReference ref;

		ASSERT_FALSE(ref.isValid());
	}
	{
		lua_pushboolean(L, 1);

		LuaReferencePtr refPtr = LuaReference::create(L);

		lua_pop(L, 1);

		ASSERT_TRUE(refPtr->isValid());

		refPtr->removeReference();

		ASSERT_FALSE(refPtr->isValid());
	}
}

TEST_F(LuaReferenceTest, RemoveReference)
{
	lua_pushboolean(L, 1);

	LuaReferencePtr refPtr = LuaReference::create(L);

	lua_pop(L, 1);

	ASSERT_TRUE(refPtr->removeReference());

	ASSERT_FALSE(refPtr->removeReference());
}

TEST_F(LuaReferenceTest, PushValue)
{
	lua_pushboolean(L, 1);

	LuaReferencePtr refPtr = LuaReference::create(L);

	lua_pop(L, 1);

	refPtr->pushValue();

	ASSERT_TRUE(lua_isboolean(L, -1) == 1);
	ASSERT_EQ(1, lua_toboolean(L, -1));

	lua_pop(L, 1);
}
<|endoftext|>


<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <iostream>
#include <sstream>
#include <iterator>
#include <stdexcept>
#include <limits>

#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/BriefTestProgressListener.h>

#include <nix.hpp>

class TestBlock : public CPPUNIT_NS::TestFixture {

private:

    CPPUNIT_TEST_SUITE(TestBlock);

    CPPUNIT_TEST(testId);
    CPPUNIT_TEST(testType);
    CPPUNIT_TEST(testName);
    CPPUNIT_TEST(testDefinition);

    CPPUNIT_TEST(testMetadataAccess);
    CPPUNIT_TEST(testSourceAccess);
    CPPUNIT_TEST(testDataArrayAccess);
    CPPUNIT_TEST(testSimpleTagAccess);
    CPPUNIT_TEST(testDataTagAccess);

    CPPUNIT_TEST(testUpdatedAt);
    CPPUNIT_TEST(testCreatedAt);

    CPPUNIT_TEST_SUITE_END ();

    nix::File file;
    nix::Section section;
    nix::Block block, block_other, block_null;
    time_t startup_time;

public:

    void setUp();
    void tearDown();

    void testId();
    void testType();
    void testName();
    void testDefinition();

    void testMetadataAccess();
    void testSourceAccess();
    void testDataArrayAccess();
    void testSimpleTagAccess();
    void testDataTagAccess();

    void testOperators();
    void testUpdatedAt();
    void testCreatedAt();

};
<commit_msg>Method testOperators was not registered on TestBlock<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <iostream>
#include <sstream>
#include <iterator>
#include <stdexcept>
#include <limits>

#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/BriefTestProgressListener.h>

#include <nix.hpp>

class TestBlock : public CPPUNIT_NS::TestFixture {

private:

    CPPUNIT_TEST_SUITE(TestBlock);

    CPPUNIT_TEST(testId);
    CPPUNIT_TEST(testType);
    CPPUNIT_TEST(testName);
    CPPUNIT_TEST(testDefinition);

    CPPUNIT_TEST(testMetadataAccess);
    CPPUNIT_TEST(testSourceAccess);
    CPPUNIT_TEST(testDataArrayAccess);
    CPPUNIT_TEST(testSimpleTagAccess);
    CPPUNIT_TEST(testDataTagAccess);

    CPPUNIT_TEST(testOperators);
    CPPUNIT_TEST(testUpdatedAt);
    CPPUNIT_TEST(testCreatedAt);

    CPPUNIT_TEST_SUITE_END ();

    nix::File file;
    nix::Section section;
    nix::Block block, block_other, block_null;
    time_t startup_time;

public:

    void setUp();
    void tearDown();

    void testId();
    void testType();
    void testName();
    void testDefinition();

    void testMetadataAccess();
    void testSourceAccess();
    void testDataArrayAccess();
    void testSimpleTagAccess();
    void testDataTagAccess();

    void testOperators();
    void testUpdatedAt();
    void testCreatedAt();

};
<|endoftext|>


<commit_before>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2018 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#include "test.hpp"
#include <array>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <miopen/convolution.hpp>
#include <miopen/miopen.h>
#include <miopen/tensor.hpp>
#include <utility>

// #include "network_data.hpp"
#include "driver.hpp"
#include "get_handle.hpp"
#include "tensor_holder.hpp"
#include "verify.hpp"
#include <miopen/stringutils.hpp>

template <class T>
struct verify_backwards_bias
{
    tensor<T> output;
    tensor<T> bias;
    miopenConvolutionMode_t mode;

    tensor<T> cpu() const
    {
        auto rbias = bias;
        int out_n, out_c, out_h, out_w;
        std::tie(out_n, out_c, out_h, out_w) = miopen::tien<4>(output.desc.GetLengths());

        par_ford(out_c)([&](int c) {
            double acc = 0;
            ford(out_n, out_h, out_w)([&](int n, int h, int w) { acc += output(n, c, h, w); });
            rbias[c] = acc;
        });
        return rbias;
    }

    tensor<T> gpu() const
    {
        auto&& handle = get_handle();
        auto rbias    = bias;

        auto out_dev  = handle.Write(output.data);
        auto bias_dev = handle.Write(rbias.data);

        float alpha = 1, beta = 0;
        ConvolutionBackwardBias(
            handle, &alpha, output.desc, out_dev.get(), &beta, rbias.desc, bias_dev.get());

        rbias.data = handle.Read<T>(bias_dev, rbias.data.size());
        return rbias;
    }

    void fail(int = 0) const
    {
        std::cout << "Backwards bias: " << std::endl;
        std::cout << "Output tensor: " << output.desc.ToString() << std::endl;
        std::cout << "Bias tensor: " << bias.desc.ToString() << std::endl;
    }
};

template <class T>
struct conv_bias_driver : test_driver
{
    tensor<T> output;
    std::string conv_mode;

    std::unordered_map<std::string, miopenConvolutionMode_t> cmode_lookup = {
        {"CONV", miopenConvolution}, {"TRANS", miopenTranspose}};

    conv_bias_driver() { add(output, "output", get_input_tensor()); }

    void run()
    {
        auto mode      = cmode_lookup[miopen::ToUpper(conv_mode)];
        tensor<T> bias = {1, output.desc.GetLengths()[1], 1, 1};
	int out_h, out_w;
	std::tie(std::ignore, std::ignore, out_h, out_w) = miopen::tien<4>(output.desc.GetLengths());
        output.par_for_each(
            [&](int n, int c, int h, int w) { output(n, c, h, w) = T(output(n, c, h, w) * 65535.0f / (4 * out_h * out_w)); });
        verify(verify_backwards_bias<T>{output, bias, mode});
    }
};

int main(int argc, const char* argv[]) { test_drive<conv_bias_driver>(argc, argv); }
<commit_msg>Fixed clang formatting<commit_after>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2018 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#include "test.hpp"
#include <array>
#include <iostream>
#include <iterator>
#include <limits>
#include <memory>
#include <miopen/convolution.hpp>
#include <miopen/miopen.h>
#include <miopen/tensor.hpp>
#include <utility>

// #include "network_data.hpp"
#include "driver.hpp"
#include "get_handle.hpp"
#include "tensor_holder.hpp"
#include "verify.hpp"
#include <miopen/stringutils.hpp>

template <class T>
struct verify_backwards_bias
{
    tensor<T> output;
    tensor<T> bias;
    miopenConvolutionMode_t mode;

    tensor<T> cpu() const
    {
        auto rbias = bias;
        int out_n, out_c, out_h, out_w;
        std::tie(out_n, out_c, out_h, out_w) = miopen::tien<4>(output.desc.GetLengths());

        par_ford(out_c)([&](int c) {
            double acc = 0;
            ford(out_n, out_h, out_w)([&](int n, int h, int w) { acc += output(n, c, h, w); });
            rbias[c] = acc;
        });
        return rbias;
    }

    tensor<T> gpu() const
    {
        auto&& handle = get_handle();
        auto rbias    = bias;

        auto out_dev  = handle.Write(output.data);
        auto bias_dev = handle.Write(rbias.data);

        float alpha = 1, beta = 0;
        ConvolutionBackwardBias(
            handle, &alpha, output.desc, out_dev.get(), &beta, rbias.desc, bias_dev.get());

        rbias.data = handle.Read<T>(bias_dev, rbias.data.size());
        return rbias;
    }

    void fail(int = 0) const
    {
        std::cout << "Backwards bias: " << std::endl;
        std::cout << "Output tensor: " << output.desc.ToString() << std::endl;
        std::cout << "Bias tensor: " << bias.desc.ToString() << std::endl;
    }
};

template <class T>
struct conv_bias_driver : test_driver
{
    tensor<T> output;
    std::string conv_mode;

    std::unordered_map<std::string, miopenConvolutionMode_t> cmode_lookup = {
        {"CONV", miopenConvolution}, {"TRANS", miopenTranspose}};

    conv_bias_driver() { add(output, "output", get_input_tensor()); }

    void run()
    {
        auto mode      = cmode_lookup[miopen::ToUpper(conv_mode)];
        tensor<T> bias = {1, output.desc.GetLengths()[1], 1, 1};
        int out_h, out_w;
        std::tie(std::ignore, std::ignore, out_h, out_w) =
            miopen::tien<4>(output.desc.GetLengths());
        output.par_for_each([&](int n, int c, int h, int w) {
            output(n, c, h, w) = T(output(n, c, h, w) * 65535.0f / (4 * out_h * out_w));
        });
        verify(verify_backwards_bias<T>{output, bias, mode});
    }
};

int main(int argc, const char* argv[]) { test_drive<conv_bias_driver>(argc, argv); }
<|endoftext|>


<commit_before><commit_msg>coverity#1210161 Uninitialized scalar variable<commit_after><|endoftext|>


<commit_before>#ifndef VIENNAGRID_DETAIL_DOMAIN_LAYERS_HPP
#define VIENNAGRID_DETAIL_DOMAIN_LAYERS_HPP

/* =======================================================================
   Copyright (c) 2011, Institute for Microelectronics,
                       Institute for Analysis and Scientific Computing,
                       TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at
                 Josef Weinbub                    weinbub@iue.tuwien.ac.at

   (A list of additional contributors can be found in the PDF manual)

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <stack>
#include <algorithm>
#include "viennagrid/forwards.h"
#include "viennagrid/point.hpp"
#include "viennagrid/element.hpp"
#include "viennagrid/detail/element_key.hpp"
#include "viennagrid/segment.hpp"
#include "viennagrid/traits/container.hpp"

/** @file domain_layers.hpp
    @brief Provides the topological layers for the domain
*/

namespace viennagrid
{
  namespace detail
  {
    /** @brief Class responsible for holding the segments inside a domain */
    template <typename DomainType, typename SegmentType>
    class domain_segment_container
    {
        typedef std::deque<SegmentType>     container_type;

      public:
        typedef typename container_type::iterator           iterator;
        typedef typename container_type::const_iterator     const_iterator;
        typedef typename container_type::value_type         value_type;
        typedef typename container_type::reference          reference;
        typedef typename container_type::const_reference    const_reference;
        typedef typename container_type::difference_type    difference_type;
        typedef typename container_type::pointer            pointer;
        typedef typename container_type::size_type          size_type;

        domain_segment_container(DomainType * d) : domain_ptr(d) {}

        SegmentType & operator[](std::size_t i) { return segments_[i]; }
        SegmentType const & operator[](std::size_t i) const { return segments_[i]; }

        SegmentType & at(std::size_t i) { return segments_.at(i); }
        SegmentType const & at(std::size_t i) const { return segments_.at(i); }

        std::size_t size() const { return segments_.size(); }
        std::size_t max_size() const { return segments_.max_size(); }
        bool empty() const { return segments_.empty(); }

        void resize(std::size_t n)
        {
          std::size_t old_size = segments_.size();
          segments_.resize(n);
          for (std::size_t i=old_size; i<n; ++i)
            segments_[i].domain(*domain_ptr);
        }

        iterator begin() { return segments_.begin(); }
        const_iterator begin() const { return segments_.begin(); }

        iterator end() { return segments_.end(); }
        const_iterator end() const { return segments_.end(); }

        void swap(domain_segment_container & other)
        {
          assert(domain_ptr == other.domain_ptr);
          segments_.swap(other.segments_);
        }
      private:
        container_type segments_;
        DomainType * domain_ptr;
    };

    /** @brief Class holding all n-cells of a particular topological dimension n. Uses recursive inheritance similar to n-cells themselves
     *
     * @tparam Config           Configuration class
     * @tparam dim              Topological dimension n of the layer
     * @tparam is_cell          Helper flag for resolving ambiguities at cell level
     * @tparam STOR             The storage scheme used for this layer
     */
    template <typename Config, // config class
              long dim,  // dimension of the elements covered here
              bool is_cell = false,                   // whether this layer holds the cells (i.e. highest topological element)
              typename STOR = typename viennagrid::result_of::bndcell_handling<Config, domain_t<Config>, dim>::type       //Storage scheme: Full storage, or ignore layer
            >
    class domain_layers  : public domain_layers<Config,
                                                dim-1>
    {
        //typedef typename result_of::tag<typename Config::cell_tag, dim>::type    tag;
        typedef domain_t<Config>                                                          domain_type;
        typedef typename topology::bndcells<typename Config::cell_tag, dim>::tag    tag;
        typedef topology::bndcells<tag, 0>                                       VertexOnElementSpecs;
        typedef element_t<Config, tag >                                              element_type;
        typedef element_t<Config, typename Config::cell_tag>                                   cell_type;
        typedef typename result_of::element_container<domain_type, dim, Config::cell_tag::dim>::type           container_type;
        typedef domain_layers<Config,
                              dim-1>                                               base_type;
        typedef element_orientation<VertexOnElementSpecs::num>                    ElementOrientationType;
        typedef element_key<Config, element_type>                                 ElementKeyType;

      public:
        typedef Config                                    config_type;

        using base_type::push_back;

        /** @brief Adds a n-cell to the domain.
         *
         * @param elem          The n-cell to be added
         * @param orientation   Pointer to a permutation array
         */
        element_type *
        push_back(element_type & elem, ElementOrientationType * orientation) {

          typedef typename std::map< element_key<Config, element_type>, element_type >::iterator  ElementIterator;

          typedef typename result_of::ncell_range<element_type, 0>::type      VertexOnElementRange;
          typedef typename result_of::iterator<element_type, 0>::type         VertexOnElementIterator;

          ElementKeyType epc(elem);
          //check whether already inserted:
          ElementIterator elit = elements.find(epc);
          //std::cout << "Candidate: "; elem.print_short();

          if (elit == elements.end())
          {
            //provide ID for element:
            elem.id(elements.size());

            //std::cout << "ACCEPTED " << std::endl;

            //set default orientation:
            if (orientation != NULL)
              orientation->setDefaultOrientation();

            std::pair<ElementKeyType, element_type> p(epc, elem);
            return &((elements.insert(p).first)->second);
          }

          //std::cout << "REJECTED" << std::endl;
          dim_type i=0; dim_type j=0;

          //set orientation:
          VertexOnElementRange vertices_on_element = ncells<0>(elem);
          for (VertexOnElementIterator voeit = vertices_on_element.begin();
                voeit != vertices_on_element.end();
                ++voeit, ++i)
          {

              VertexOnElementRange vertices_on_element_2 = ncells<0>(elit->second);
              for (VertexOnElementIterator voeit2 = vertices_on_element_2.begin();
                    voeit2 != vertices_on_element_2.end();
                    ++voeit2, ++j)
              {
                if (voeit->id() == voeit2->id())
                {
                  if (orientation != NULL)
                    orientation->setPermutation(i,j);   //local (elem) to global (elit->second)
                    //orientation->setPermutation(j,i);   //global (elit->second) to local (elem)
                  break;
                }
              }
              j=0;
          }

          return &(elit->second);
        }

        ///////////////////// container retrieval /////////////////////////

        using base_type::container;

        //non-const:
        container_type *
        container(dimension_tag<dim>) { return &elements; }

        //const:
        const container_type *
        container(dimension_tag<dim>) const { return &elements; }

      private:
        container_type    elements;        //container of elements
    };

    /** @brief Specialization of a domin layer without the storage of n-cells. */
    template <typename Config,
              long dim>
    class domain_layers<Config, dim, false, no_handling_tag> : public domain_layers<Config, dim-1>
    {
        //typedef typename result_of::tag<typename Config::cell_tag, dim>::type    tag;
        typedef typename Config::cell_tag                                                 CellTag;
        typedef domain_t<Config>                                                          domain_type;
        typedef domain_layers<Config, dim-1>        base_type;
        typedef typename result_of::element_container<domain_type, dim, Config::cell_tag::dim>::type           container_type;

      public:

        ///////////////////// container retrieval /////////////////////////
        using base_type::container;

        //non-const:
        container_type *
        container(dimension_tag<dim>)
        {
          typedef typename result_of::bndcell_handling<Config,
                                                          domain_type,
                                                          dim
                                                         >::ERROR_HANDLING_OF_ELEMENTS_AT_THIS_TOPOLOGICAL_LEVEL_NOT_PROVIDED   error_type;
          return NULL;
        }

        //const:
        const container_type *
        container(dimension_tag<dim>) const
        {
          typedef typename result_of::bndcell_handling<Config,
                                                          domain_type,
                                                          dim
                                                         >::ERROR_HANDLING_OF_ELEMENTS_AT_THIS_TOPOLOGICAL_LEVEL_NOT_PROVIDED   error_type;
          return NULL;
        }
    };

    // special handling for cells:
    /** @brief Specialization for the cell level */
    template <typename Config,
              long dim>
    class domain_layers<Config, dim, true, full_handling_tag> : public domain_layers<Config,
                                                                                dim-1>
    {
        //typedef typename result_of::tag<typename Config::cell_tag, 0>::type   tag;
        typedef domain_t<Config>                                                          domain_type;
        typedef element_t<Config, typename Config::cell_tag >                                         element_type;
        typedef typename result_of::element_container<domain_type,
                                                      Config::cell_tag::dim,
                                                      Config::cell_tag::dim>::type                container_type;
        typedef domain_layers<Config,
                              dim-1>                                               base_type;

      public:
        typedef Config    config_type;
        typedef std::size_t   size_type;

        using base_type::push_back;

        element_type * push_back(element_type & e)
        {
          assert(viennagrid::traits::capacity(elements) > elements.size() && "Not enough memory for cells reserved!");

          elements.push_back(e);
          elements.back().id(elements.size()-1);
          //std::cout << "Filling cell for domain " << this << std::endl;
          elements.back().fill(*this);
          return &(elements.back());
        }

        using base_type::container;

        //non-const:
        container_type *
        container(dimension_tag<dim>) { return &elements; }

        //const:
        const container_type *
        container(dimension_tag<dim>) const { return &elements; }

      private:
        container_type    elements;        //container of elements
    };

    //terminate recursion at vertex level:
    /** @brief Specialization for the vertex level. Terminates the recursive inheritance */
    template <typename Config,
              bool is_cell,
              typename STOR >
    class domain_layers<Config, 0, is_cell, STOR>
    {
        //typedef typename result_of::tag<typename Config::cell_tag, 0>::type   tag;
        typedef typename result_of::point<Config>::type                                   PointType;
        typedef domain_t<Config>                                                          domain_type;
        typedef element_t<Config, point_tag >                                             element_type;
        typedef element_t<Config, typename Config::cell_tag >                             cell_type;
        typedef typename result_of::element_container<domain_type,
                                                      0,
                                                      Config::cell_tag::dim
                                                      >::type                            container_type;

      public:
        typedef Config    config_type;
        typedef std::size_t size_type;

        element_type * push_back(element_type const & e)
        {
          assert(viennagrid::traits::capacity(elements) > elements.size() && "Not enough memory for vertices reserved!");
          //element_type temp(e);
          //temp.id(elements.size());
          elements.push_back(e);
          elements.back().id(elements.size()-1);
          return &(elements.back());
        }

        element_type * push_back(PointType const & p)
        {
          element_type temp_vertex(p);
          return push_back(temp_vertex);
        }

        //non-const:
        container_type *
        container(dimension_tag<0>) { return &elements; }

        //const:
        const container_type *
        container(dimension_tag<0>) const { return &elements; }

      private:
        container_type    elements;        //container of elements
    };

  } //namespace detail

} //namespace viennagrid
#endif
<commit_msg>took care of failing regressions after the lass introduction of the segment_iterators.hpp in the element_iterators.hpp:     added element_orientation.hpp to domain_layers.hpp -> regression runs through now --> coming up: tests on gcc 4.1.2@TCAD<commit_after>#ifndef VIENNAGRID_DETAIL_DOMAIN_LAYERS_HPP
#define VIENNAGRID_DETAIL_DOMAIN_LAYERS_HPP

/* =======================================================================
   Copyright (c) 2011, Institute for Microelectronics,
                       Institute for Analysis and Scientific Computing,
                       TU Wien.

                            -----------------
                     ViennaGrid - The Vienna Grid Library
                            -----------------

   Authors:      Karl Rupp                           rupp@iue.tuwien.ac.at
                 Josef Weinbub                    weinbub@iue.tuwien.ac.at

   (A list of additional contributors can be found in the PDF manual)

   License:      MIT (X11), see file LICENSE in the base directory
======================================================================= */

#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <stack>
#include <algorithm>
#include "viennagrid/forwards.h"
#include "viennagrid/point.hpp"
#include "viennagrid/element.hpp"
#include "viennagrid/detail/element_key.hpp"
#include "viennagrid/detail/element_orientation.hpp"
#include "viennagrid/segment.hpp"
#include "viennagrid/traits/container.hpp"

/** @file domain_layers.hpp
    @brief Provides the topological layers for the domain
*/

namespace viennagrid
{
  namespace detail
  {
    /** @brief Class responsible for holding the segments inside a domain */
    template <typename DomainType, typename SegmentType>
    class domain_segment_container
    {
        typedef std::deque<SegmentType>     container_type;

      public:
        typedef typename container_type::iterator           iterator;
        typedef typename container_type::const_iterator     const_iterator;
        typedef typename container_type::value_type         value_type;
        typedef typename container_type::reference          reference;
        typedef typename container_type::const_reference    const_reference;
        typedef typename container_type::difference_type    difference_type;
        typedef typename container_type::pointer            pointer;
        typedef typename container_type::size_type          size_type;

        domain_segment_container(DomainType * d) : domain_ptr(d) {}

        SegmentType & operator[](std::size_t i) { return segments_[i]; }
        SegmentType const & operator[](std::size_t i) const { return segments_[i]; }

        SegmentType & at(std::size_t i) { return segments_.at(i); }
        SegmentType const & at(std::size_t i) const { return segments_.at(i); }

        std::size_t size() const { return segments_.size(); }
        std::size_t max_size() const { return segments_.max_size(); }
        bool empty() const { return segments_.empty(); }

        void resize(std::size_t n)
        {
          std::size_t old_size = segments_.size();
          segments_.resize(n);
          for (std::size_t i=old_size; i<n; ++i)
            segments_[i].domain(*domain_ptr);
        }

        iterator begin() { return segments_.begin(); }
        const_iterator begin() const { return segments_.begin(); }

        iterator end() { return segments_.end(); }
        const_iterator end() const { return segments_.end(); }

        void swap(domain_segment_container & other)
        {
          assert(domain_ptr == other.domain_ptr);
          segments_.swap(other.segments_);
        }
      private:
        container_type segments_;
        DomainType * domain_ptr;
    };

    /** @brief Class holding all n-cells of a particular topological dimension n. Uses recursive inheritance similar to n-cells themselves
     *
     * @tparam Config           Configuration class
     * @tparam dim              Topological dimension n of the layer
     * @tparam is_cell          Helper flag for resolving ambiguities at cell level
     * @tparam STOR             The storage scheme used for this layer
     */
    template <typename Config, // config class
              long dim,  // dimension of the elements covered here
              bool is_cell = false,                   // whether this layer holds the cells (i.e. highest topological element)
              typename STOR = typename viennagrid::result_of::bndcell_handling<Config, domain_t<Config>, dim>::type       //Storage scheme: Full storage, or ignore layer
            >
    class domain_layers  : public domain_layers<Config,
                                                dim-1>
    {
        //typedef typename result_of::tag<typename Config::cell_tag, dim>::type    tag;
        typedef domain_t<Config>                                                          domain_type;
        typedef typename topology::bndcells<typename Config::cell_tag, dim>::tag    tag;
        typedef topology::bndcells<tag, 0>                                       VertexOnElementSpecs;
        typedef element_t<Config, tag >                                              element_type;
        typedef element_t<Config, typename Config::cell_tag>                                   cell_type;
        typedef typename result_of::element_container<domain_type, dim, Config::cell_tag::dim>::type           container_type;
        typedef domain_layers<Config,
                              dim-1>                                               base_type;
        typedef element_orientation<VertexOnElementSpecs::num>                    ElementOrientationType;
        typedef element_key<Config, element_type>                                 ElementKeyType;

      public:
        typedef Config                                    config_type;

        using base_type::push_back;

        /** @brief Adds a n-cell to the domain.
         *
         * @param elem          The n-cell to be added
         * @param orientation   Pointer to a permutation array
         */
        element_type *
        push_back(element_type & elem, ElementOrientationType * orientation) {

          typedef typename std::map< element_key<Config, element_type>, element_type >::iterator  ElementIterator;

          typedef typename result_of::ncell_range<element_type, 0>::type      VertexOnElementRange;
          typedef typename result_of::iterator<element_type, 0>::type         VertexOnElementIterator;

          ElementKeyType epc(elem);
          //check whether already inserted:
          ElementIterator elit = elements.find(epc);
          //std::cout << "Candidate: "; elem.print_short();

          if (elit == elements.end())
          {
            //provide ID for element:
            elem.id(elements.size());

            //std::cout << "ACCEPTED " << std::endl;

            //set default orientation:
            if (orientation != NULL)
              orientation->setDefaultOrientation();

            std::pair<ElementKeyType, element_type> p(epc, elem);
            return &((elements.insert(p).first)->second);
          }

          //std::cout << "REJECTED" << std::endl;
          dim_type i=0; dim_type j=0;

          //set orientation:
          VertexOnElementRange vertices_on_element = ncells<0>(elem);
          for (VertexOnElementIterator voeit = vertices_on_element.begin();
                voeit != vertices_on_element.end();
                ++voeit, ++i)
          {

              VertexOnElementRange vertices_on_element_2 = ncells<0>(elit->second);
              for (VertexOnElementIterator voeit2 = vertices_on_element_2.begin();
                    voeit2 != vertices_on_element_2.end();
                    ++voeit2, ++j)
              {
                if (voeit->id() == voeit2->id())
                {
                  if (orientation != NULL)
                    orientation->setPermutation(i,j);   //local (elem) to global (elit->second)
                    //orientation->setPermutation(j,i);   //global (elit->second) to local (elem)
                  break;
                }
              }
              j=0;
          }

          return &(elit->second);
        }

        ///////////////////// container retrieval /////////////////////////

        using base_type::container;

        //non-const:
        container_type *
        container(dimension_tag<dim>) { return &elements; }

        //const:
        const container_type *
        container(dimension_tag<dim>) const { return &elements; }

      private:
        container_type    elements;        //container of elements
    };

    /** @brief Specialization of a domin layer without the storage of n-cells. */
    template <typename Config,
              long dim>
    class domain_layers<Config, dim, false, no_handling_tag> : public domain_layers<Config, dim-1>
    {
        //typedef typename result_of::tag<typename Config::cell_tag, dim>::type    tag;
        typedef typename Config::cell_tag                                                 CellTag;
        typedef domain_t<Config>                                                          domain_type;
        typedef domain_layers<Config, dim-1>        base_type;
        typedef typename result_of::element_container<domain_type, dim, Config::cell_tag::dim>::type           container_type;

      public:

        ///////////////////// container retrieval /////////////////////////
        using base_type::container;

        //non-const:
        container_type *
        container(dimension_tag<dim>)
        {
          typedef typename result_of::bndcell_handling<Config,
                                                          domain_type,
                                                          dim
                                                         >::ERROR_HANDLING_OF_ELEMENTS_AT_THIS_TOPOLOGICAL_LEVEL_NOT_PROVIDED   error_type;
          return NULL;
        }

        //const:
        const container_type *
        container(dimension_tag<dim>) const
        {
          typedef typename result_of::bndcell_handling<Config,
                                                          domain_type,
                                                          dim
                                                         >::ERROR_HANDLING_OF_ELEMENTS_AT_THIS_TOPOLOGICAL_LEVEL_NOT_PROVIDED   error_type;
          return NULL;
        }
    };

    // special handling for cells:
    /** @brief Specialization for the cell level */
    template <typename Config,
              long dim>
    class domain_layers<Config, dim, true, full_handling_tag> : public domain_layers<Config,
                                                                                dim-1>
    {
        //typedef typename result_of::tag<typename Config::cell_tag, 0>::type   tag;
        typedef domain_t<Config>                                                          domain_type;
        typedef element_t<Config, typename Config::cell_tag >                                         element_type;
        typedef typename result_of::element_container<domain_type,
                                                      Config::cell_tag::dim,
                                                      Config::cell_tag::dim>::type                container_type;
        typedef domain_layers<Config,
                              dim-1>                                               base_type;

      public:
        typedef Config    config_type;
        typedef std::size_t   size_type;

        using base_type::push_back;

        element_type * push_back(element_type & e)
        {
          assert(viennagrid::traits::capacity(elements) > elements.size() && "Not enough memory for cells reserved!");

          elements.push_back(e);
          elements.back().id(elements.size()-1);
          //std::cout << "Filling cell for domain " << this << std::endl;
          elements.back().fill(*this);
          return &(elements.back());
        }

        using base_type::container;

        //non-const:
        container_type *
        container(dimension_tag<dim>) { return &elements; }

        //const:
        const container_type *
        container(dimension_tag<dim>) const { return &elements; }

      private:
        container_type    elements;        //container of elements
    };

    //terminate recursion at vertex level:
    /** @brief Specialization for the vertex level. Terminates the recursive inheritance */
    template <typename Config,
              bool is_cell,
              typename STOR >
    class domain_layers<Config, 0, is_cell, STOR>
    {
        //typedef typename result_of::tag<typename Config::cell_tag, 0>::type   tag;
        typedef typename result_of::point<Config>::type                                   PointType;
        typedef domain_t<Config>                                                          domain_type;
        typedef element_t<Config, point_tag >                                             element_type;
        typedef element_t<Config, typename Config::cell_tag >                             cell_type;
        typedef typename result_of::element_container<domain_type,
                                                      0,
                                                      Config::cell_tag::dim
                                                      >::type                            container_type;

      public:
        typedef Config    config_type;
        typedef std::size_t size_type;

        element_type * push_back(element_type const & e)
        {
          assert(viennagrid::traits::capacity(elements) > elements.size() && "Not enough memory for vertices reserved!");
          //element_type temp(e);
          //temp.id(elements.size());
          elements.push_back(e);
          elements.back().id(elements.size()-1);
          return &(elements.back());
        }

        element_type * push_back(PointType const & p)
        {
          element_type temp_vertex(p);
          return push_back(temp_vertex);
        }

        //non-const:
        container_type *
        container(dimension_tag<0>) { return &elements; }

        //const:
        const container_type *
        container(dimension_tag<0>) const { return &elements; }

      private:
        container_type    elements;        //container of elements
    };

  } //namespace detail

} //namespace viennagrid
#endif
<|endoftext|>


<commit_before>#include "TTree.h"
#include "TFile.h"
#include "TList.h"
#include "TROOT.h"
#include <TBenchmark.h>

int gHasLibrary = kFALSE;
int gBranchStyle = 1;
TList gSkipped;

void DrawSkippable(TTree* tree, const char* what, const char* where, Bool_t draw = true) {
  //cerr << "Doing " << what << " which is " << skip << endl;
   if (draw) {
      TString cut = what;
      cut.Append(">>");
      cut.Append(where);
      tree->Draw(cut.Data(),"","goff");
      TH1* h = (TH1*)gDirectory->FindObject(where);
      if (h) h->SetTitle(Form("histo made from T->Draw(\"%s\")",what));
   } else {
      gSkipped.Add(new TNamed(where,where));
   }
};

void DrawSkippable(TTree* tree, const char* what, const char* cond,
                   const char* where, Bool_t draw = true) {
   //cerr << "Doing " << what << " which is " << skip << endl;
   if (draw) {
      TString cut = what;
      cut.Append(">>");
      cut.Append(where);
      tree->Draw(cut.Data(),cond,"goff");
      TH1* h = (TH1*)gDirectory->FindObject(where);
      if (h) h->SetTitle(Form("histo made from T->Draw(\"%s\",\"%s\")",what,cond));
   } else {
      gSkipped.Add(new TNamed(where,where));
   }
};

// Rootmarks for fcdflnx1 is 153.4
void DrawMarks() {

  // The base is currently: RunDrawTest.C++("Event.old.split.root",0)
  Float_t rt_base = 2.33/10.0;
  Float_t cp_base = 2.34/10.0;

  Float_t rt = gBenchmark->GetRealTime("DrawTest");
  Float_t ct = gBenchmark->GetCpuTime("DrawTest");

  // gBenchmark->Print("DrawTest");

  Float_t rootmarks = 200*(rt_base + cp_base)/(rt + ct);

  printf("*  ROOTMARKS =%6.1f   *  Root%-8s  %d/%d\n",rootmarks,gROOT->GetVersion(),gROOT->GetVersionDate(),gROOT->GetVersionTime());

}

//_______________________________________________________________
TDirectory* GenerateDrawHist(TTree *tree, int quietLevel = 0, int level = 3)
{
// Test selections via TreeFormula
// tree is a TTree when called by stress9
// tree is a TChain when called from stres11
// This is a quite complex test checking the results of TTree::Draw
// or TChain::Draw with an explicit loop on events.
// Also a good test for the interpreter

   gROOT->cd();
   TDirectory *hfile = gDirectory;

   gBenchmark = new TBenchmark();
   gBenchmark->Start("DrawTest");

   // Each tree->Draw generates an histogram
   DrawSkippable(tree,"GetNtrack()","hGetNtrack",(level>0 && gHasLibrary));

   //gBenchmark->Show("DrawTest");  gBenchmark->Start("DrawTest");

   DrawSkippable(tree,"fNtrack","hNtrack");
   DrawSkippable(tree,"fNseg","hNseg");
   DrawSkippable(tree,"fTemperature","hTemp");

   DrawSkippable(tree,"fH.GetMean()","hHmean");
   if (level>0) DrawSkippable(tree,"fH.fXaxis.fXmax","hHAxisMax");
   if (level>0) DrawSkippable(tree,"fH.fXaxis.GetXmax()","hHAxisGetMax");
   DrawSkippable(tree,"fH.GetXaxis().GetXmax()","hHGetAxisGetMax",(level>0));
   DrawSkippable(tree,"fH.GetXaxis().fXmax","hHGetAxisMax",(level>0));
   DrawSkippable(tree,"GetHistogram().GetXaxis().GetXmax()","hGetHGetAxisMax",
                 (level>0&&gHasLibrary));
   DrawSkippable(tree,"event.GetHistogram().GetXaxis().GetXmax()",
                 "hGetRefHGetAxisMax",(level>0&&gHasLibrary));

   DrawSkippable(tree,"fTracks.fPx","fEvtHdr.fEvtNum%10 == 0","hPx");
   DrawSkippable(tree,"fTracks.fPy","fEvtHdr.fEvtNum%10 == 0","hPy");
   DrawSkippable(tree,"fTracks.fPz","fEvtHdr.fEvtNum%10 == 0","hPz");
   DrawSkippable(tree,"fRandom","3*(fEvtHdr.fEvtNum%10 == 1)","hRandom");
   DrawSkippable(tree,"fMass2",  "fEvtHdr.fEvtNum%10 == 1","hMass2");
   DrawSkippable(tree,"fBx",        "fEvtHdr.fEvtNum%10 == 1","hBx");
   DrawSkippable(tree,"fBy",        "fEvtHdr.fEvtNum%10 == 1","hBy");
   DrawSkippable(tree,"fXfirst","fEvtHdr.fEvtNum%10 == 2","hXfirst");
   DrawSkippable(tree,"fYfirst","fEvtHdr.fEvtNum%10 == 2","hYfirst");
   DrawSkippable(tree,"fZfirst","fEvtHdr.fEvtNum%10 == 2","hZfirst");
   DrawSkippable(tree,"fXlast",  "fEvtHdr.fEvtNum%10 == 3","hXlast");
   DrawSkippable(tree,"fYlast",  "fEvtHdr.fEvtNum%10 == 3","hYlast");
   DrawSkippable(tree,"fZlast",  "fEvtHdr.fEvtNum%10 == 3","hZlast");
   DrawSkippable(tree,"fCharge","fPx < 0","hCharge");
   DrawSkippable(tree,"fNpoint","fPx < 0","hNpoint");
   DrawSkippable(tree,"fValid",  "fPx < 0","hValid");
   DrawSkippable(tree,"fPointValue","hPointValue", gBranchStyle!=0);
   tree->SetAlias("mult","fPx*fPy");
   DrawSkippable(tree,"fEvtHdr.fEvtNum*6+mult", "hAlias", 1);
   tree->SetAlias("track","event.fTracks");
   DrawSkippable(tree,"track.fPx+track.fPy", "hAliasSymbol", 1);
   DrawSkippable(tree,"track.GetPx()+track.GetPy()","hAliasSymbolFunc", gBranchStyle!=0 && gHasLibrary);

   DrawSkippable(tree,"fIsValid","hBool");

   DrawSkippable(tree,"fMatrix","hFullMatrix");
   DrawSkippable(tree,"fMatrix[][0]","hColMatrix");
   DrawSkippable(tree,"fMatrix[1][]","hRowMatrix");
   DrawSkippable(tree,"fMatrix[2][2]","hCellMatrix");

   DrawSkippable(tree,"fMatrix - fVertex","hFullOper");
   DrawSkippable(tree,"fMatrix[2][1] - fVertex[5][1]","hCellOper");
   DrawSkippable(tree,"fMatrix[][1]  - fVertex[5][1]","hColOper");
   DrawSkippable(tree,"fMatrix[2][]  - fVertex[5][2]","hRowOper");
   DrawSkippable(tree,"fMatrix[2][]  - fVertex[5][]","hMatchRowOper");
   DrawSkippable(tree,"fMatrix[][2]  - fVertex[][1]","hMatchColOper");
   DrawSkippable(tree,"fMatrix[][2]  - fVertex[][]","hRowMatOper");
   DrawSkippable(tree,"fMatrix[][2]  - fVertex[5][]","hMatchDiffOper");
   DrawSkippable(tree,"fMatrix[][]   - fVertex[][]","hFullOper2");

   // Test on variable arrays
   DrawSkippable(tree,"fClosestDistance","hClosestDistance");
   DrawSkippable(tree,"fClosestDistance[2]","hClosestDistance2");
   DrawSkippable(tree,"fClosestDistance[9]","hClosestDistance9");

   // Test variable indexing
   DrawSkippable(tree,"fClosestDistance[fNvertex/2]","hClosestDistanceIndex",
                 (level>0));
   DrawSkippable(tree,"fPx:fPy[fNpoint/6]","fPy[fNpoint/6]>0","hPxInd",(level>0));

   // Test of simple function calls
   DrawSkippable(tree,"sqrt(fNtrack)","hSqrtNtrack",(level>0));

   // Test string operations
   DrawSkippable(tree,"fEvtHdr.fEvtNum","fType==\"type1\" ","hString",(level>0));
   DrawSkippable(tree,"fEvtHdr.fEvtNum","1 && strstr(fType,\"1\") ","+hString",(level>0));
   tree->SetAlias("typ","fType");
   DrawSkippable(tree,"strstr(typ,\"1\") ", "hAliasStr", 1);
   DrawSkippable(tree,"fH.fTitle.fData==\"Event Histogram\"","hStringSpace",1);

   // Test binary operators
   DrawSkippable(tree,"fValid<<4","hShiftValid",(level>0));
   DrawSkippable(tree,"((fValid<<4)>>2)","+hShiftValid",(level>0));
   DrawSkippable(tree,"fValid&0x1","(fNvertex>10) && (fNseg<=6000)"
                 ,"hAndValid",(level>0));

   // Test weight
   DrawSkippable(tree,"fPx","(fBx>.15) || (fBy<=-.15)","hPxBx",(level>0));
   DrawSkippable(tree,"fPx","fBx*fBx*(fBx>.15) + fBy*fBy*(fBy<=-.15)",
                 "hPxBxWeight",(level>0));

   DrawSkippable(tree,"event.fTriggerBits",
                 "hTriggerBits",level>1 && gBranchStyle!=0);
   DrawSkippable(tree,"event.fTriggerBits.fNbits",
                 "event.fTriggerBits.TestBitNumber(28)",
                 "hFiltTriggerBits",level>1 && gBranchStyle!=0);

   DrawSkippable(tree,"event.GetTriggerBits()",
                 "hTriggerBitsFunc",level>1 && gBranchStyle!=0 && gHasLibrary );

   DrawSkippable(tree,"fTracks.fTriggerBits",
                 "hTrackTrigger", level>1 && gBranchStyle!=0);
   DrawSkippable(tree,"fPx",
                 "fTracks.fTriggerBits.TestBitNumber(5)",
                 "hFiltTrackTrigger", level>1 && gBranchStyle!=0);

   DrawSkippable(tree,"TMath::BreitWigner(fPx,3,2)",
                 "",
                 "hBreit", level>1 && gBranchStyle!=0);

   // Test on alternate value
   DrawSkippable(tree,"fMatrix-Alt$(fClosestDistance,0)",
                 "",
                 "hAlt", level>1 && gBranchStyle!=0);

   // Test on the @ notation to access the collection object itself
   DrawSkippable(tree,"event.@fTracks.size()","","hSize",level>2 && !(gBranchStyle==0 && !gHasLibrary));
   DrawSkippable(tree,"event.fTracks@.size()","","+hSize",level>2 && !(gBranchStyle==0 && !gHasLibrary));
   DrawSkippable(tree,"@fTracks.size()","","hSize2",level>2 && gBranchStyle!=0);
   DrawSkippable(tree,"fTracks@.size()","","+hSize2",level>2 && gBranchStyle!=0);
   DrawSkippable(tree,"Sum$(fPx)","","hSumPx",level>2);

   if (quietLevel<2) gBenchmark->Show("DrawTest");
   else gBenchmark->Stop("DrawTest");
   gBenchmark->Start("DrawTest");

   return hfile;

}

<commit_msg>The old style split branch do not store Double32_t with annotation with the same precision. since the interface is deprecated skip the test<commit_after>#include "TTree.h"
#include "TFile.h"
#include "TList.h"
#include "TROOT.h"
#include <TBenchmark.h>

int gHasLibrary = kFALSE;
int gBranchStyle = 1;
TList gSkipped;

void DrawSkippable(TTree* tree, const char* what, const char* where, Bool_t draw = true) {
  //cerr << "Doing " << what << " which is " << skip << endl;
   if (draw) {
      TString cut = what;
      cut.Append(">>");
      cut.Append(where);
      tree->Draw(cut.Data(),"","goff");
      TH1* h = (TH1*)gDirectory->FindObject(where);
      if (h) h->SetTitle(Form("histo made from T->Draw(\"%s\")",what));
   } else {
      gSkipped.Add(new TNamed(where,where));
   }
};

void DrawSkippable(TTree* tree, const char* what, const char* cond,
                   const char* where, Bool_t draw = true) {
   //cerr << "Doing " << what << " which is " << skip << endl;
   if (draw) {
      TString cut = what;
      cut.Append(">>");
      cut.Append(where);
      tree->Draw(cut.Data(),cond,"goff");
      TH1* h = (TH1*)gDirectory->FindObject(where);
      if (h) h->SetTitle(Form("histo made from T->Draw(\"%s\",\"%s\")",what,cond));
   } else {
      gSkipped.Add(new TNamed(where,where));
   }
};

// Rootmarks for fcdflnx1 is 153.4
void DrawMarks() {

  // The base is currently: RunDrawTest.C++("Event.old.split.root",0)
  Float_t rt_base = 2.33/10.0;
  Float_t cp_base = 2.34/10.0;

  Float_t rt = gBenchmark->GetRealTime("DrawTest");
  Float_t ct = gBenchmark->GetCpuTime("DrawTest");

  // gBenchmark->Print("DrawTest");

  Float_t rootmarks = 200*(rt_base + cp_base)/(rt + ct);

  printf("*  ROOTMARKS =%6.1f   *  Root%-8s  %d/%d\n",rootmarks,gROOT->GetVersion(),gROOT->GetVersionDate(),gROOT->GetVersionTime());

}

//_______________________________________________________________
TDirectory* GenerateDrawHist(TTree *tree, int quietLevel = 0, int level = 3)
{
// Test selections via TreeFormula
// tree is a TTree when called by stress9
// tree is a TChain when called from stres11
// This is a quite complex test checking the results of TTree::Draw
// or TChain::Draw with an explicit loop on events.
// Also a good test for the interpreter

   gROOT->cd();
   TDirectory *hfile = gDirectory;

   gBenchmark = new TBenchmark();
   gBenchmark->Start("DrawTest");

   // Each tree->Draw generates an histogram
   DrawSkippable(tree,"GetNtrack()","hGetNtrack",(level>0 && gHasLibrary));

   //gBenchmark->Show("DrawTest");  gBenchmark->Start("DrawTest");

   DrawSkippable(tree,"fNtrack","hNtrack");
   DrawSkippable(tree,"fNseg","hNseg");
   DrawSkippable(tree,"fTemperature","hTemp");

   DrawSkippable(tree,"fH.GetMean()","hHmean");
   if (level>0) DrawSkippable(tree,"fH.fXaxis.fXmax","hHAxisMax");
   if (level>0) DrawSkippable(tree,"fH.fXaxis.GetXmax()","hHAxisGetMax");
   DrawSkippable(tree,"fH.GetXaxis().GetXmax()","hHGetAxisGetMax",(level>0));
   DrawSkippable(tree,"fH.GetXaxis().fXmax","hHGetAxisMax",(level>0));
   DrawSkippable(tree,"GetHistogram().GetXaxis().GetXmax()","hGetHGetAxisMax",
                 (level>0&&gHasLibrary));
   DrawSkippable(tree,"event.GetHistogram().GetXaxis().GetXmax()",
                 "hGetRefHGetAxisMax",(level>0&&gHasLibrary));

   DrawSkippable(tree,"fTracks.fPx","fEvtHdr.fEvtNum%10 == 0","hPx");
   DrawSkippable(tree,"fTracks.fPy","fEvtHdr.fEvtNum%10 == 0","hPy");
   DrawSkippable(tree,"fTracks.fPz","fEvtHdr.fEvtNum%10 == 0","hPz");
   DrawSkippable(tree,"fRandom","3*(fEvtHdr.fEvtNum%10 == 1)","hRandom");
   DrawSkippable(tree,"fMass2",  "fEvtHdr.fEvtNum%10 == 1","hMass2");
   DrawSkippable(tree,"fBx",        "fEvtHdr.fEvtNum%10 == 1","hBx");
   DrawSkippable(tree,"fBy",        "fEvtHdr.fEvtNum%10 == 1","hBy");
   DrawSkippable(tree,"fXfirst","fEvtHdr.fEvtNum%10 == 2","hXfirst");
   DrawSkippable(tree,"fYfirst","fEvtHdr.fEvtNum%10 == 2","hYfirst");
   DrawSkippable(tree,"fZfirst","fEvtHdr.fEvtNum%10 == 2","hZfirst");
   DrawSkippable(tree,"fXlast",  "fEvtHdr.fEvtNum%10 == 3","hXlast");
   DrawSkippable(tree,"fYlast",  "fEvtHdr.fEvtNum%10 == 3","hYlast");
   DrawSkippable(tree,"fZlast",  "fEvtHdr.fEvtNum%10 == 3","hZlast");
   DrawSkippable(tree,"fCharge","fPx < 0","hCharge");
   DrawSkippable(tree,"fNpoint","fPx < 0","hNpoint");
   DrawSkippable(tree,"fValid",  "fPx < 0","hValid");
   DrawSkippable(tree,"fPointValue","hPointValue", gBranchStyle!=0);
   tree->SetAlias("mult","fPx*fPy");
   DrawSkippable(tree,"fEvtHdr.fEvtNum*6+mult", "hAlias", 1);
   tree->SetAlias("track","event.fTracks");
   DrawSkippable(tree,"track.fPx+track.fPy", "hAliasSymbol", 1);
   DrawSkippable(tree,"track.GetPx()+track.GetPy()","hAliasSymbolFunc", gBranchStyle!=0 && gHasLibrary);

   DrawSkippable(tree,"fIsValid","hBool");

   DrawSkippable(tree,"fMatrix","hFullMatrix");
   DrawSkippable(tree,"fMatrix[][0]","hColMatrix");
   DrawSkippable(tree,"fMatrix[1][]","hRowMatrix");
   DrawSkippable(tree,"fMatrix[2][2]","hCellMatrix");

   DrawSkippable(tree,"fMatrix - fVertex","hFullOper");
   DrawSkippable(tree,"fMatrix[2][1] - fVertex[5][1]","hCellOper");
   DrawSkippable(tree,"fMatrix[][1]  - fVertex[5][1]","hColOper");
   DrawSkippable(tree,"fMatrix[2][]  - fVertex[5][2]","hRowOper");
   DrawSkippable(tree,"fMatrix[2][]  - fVertex[5][]","hMatchRowOper");
   DrawSkippable(tree,"fMatrix[][2]  - fVertex[][1]","hMatchColOper");
   DrawSkippable(tree,"fMatrix[][2]  - fVertex[][]","hRowMatOper");
   DrawSkippable(tree,"fMatrix[][2]  - fVertex[5][]","hMatchDiffOper");
   DrawSkippable(tree,"fMatrix[][]   - fVertex[][]","hFullOper2");

   // Test on variable arrays
   DrawSkippable(tree,"fClosestDistance","hClosestDistance",gBranchStyle!=0);
   DrawSkippable(tree,"fClosestDistance[2]","hClosestDistance2",gBranchStyle!=0);
   DrawSkippable(tree,"fClosestDistance[9]","hClosestDistance9",gBranchStyle!=0);

   // Test variable indexing
   DrawSkippable(tree,"fClosestDistance[fNvertex/2]","hClosestDistanceIndex",
                 (level>0)&&gBranchStyle!=0);
   DrawSkippable(tree,"fPx:fPy[fNpoint/6]","fPy[fNpoint/6]>0","hPxInd",(level>0));

   // Test of simple function calls
   DrawSkippable(tree,"sqrt(fNtrack)","hSqrtNtrack",(level>0));

   // Test string operations
   DrawSkippable(tree,"fEvtHdr.fEvtNum","fType==\"type1\" ","hString",(level>0));
   DrawSkippable(tree,"fEvtHdr.fEvtNum","1 && strstr(fType,\"1\") ","+hString",(level>0));
   tree->SetAlias("typ","fType");
   DrawSkippable(tree,"strstr(typ,\"1\") ", "hAliasStr", 1);
   DrawSkippable(tree,"fH.fTitle.fData==\"Event Histogram\"","hStringSpace",1);

   // Test binary operators
   DrawSkippable(tree,"fValid<<4","hShiftValid",(level>0));
   DrawSkippable(tree,"((fValid<<4)>>2)","+hShiftValid",(level>0));
   DrawSkippable(tree,"fValid&0x1","(fNvertex>10) && (fNseg<=6000)"
                 ,"hAndValid",(level>0));

   // Test weight
   DrawSkippable(tree,"fPx","(fBx>.15) || (fBy<=-.15)","hPxBx",(level>0));
   DrawSkippable(tree,"fPx","fBx*fBx*(fBx>.15) + fBy*fBy*(fBy<=-.15)",
                 "hPxBxWeight",(level>0));

   DrawSkippable(tree,"event.fTriggerBits",
                 "hTriggerBits",level>1 && gBranchStyle!=0);
   DrawSkippable(tree,"event.fTriggerBits.fNbits",
                 "event.fTriggerBits.TestBitNumber(28)",
                 "hFiltTriggerBits",level>1 && gBranchStyle!=0);

   DrawSkippable(tree,"event.GetTriggerBits()",
                 "hTriggerBitsFunc",level>1 && gBranchStyle!=0 && gHasLibrary );

   DrawSkippable(tree,"fTracks.fTriggerBits",
                 "hTrackTrigger", level>1 && gBranchStyle!=0);
   DrawSkippable(tree,"fPx",
                 "fTracks.fTriggerBits.TestBitNumber(5)",
                 "hFiltTrackTrigger", level>1 && gBranchStyle!=0);

   DrawSkippable(tree,"TMath::BreitWigner(fPx,3,2)",
                 "",
                 "hBreit", level>1 && gBranchStyle!=0);

   // Test on alternate value
   DrawSkippable(tree,"fMatrix-Alt$(fClosestDistance,0)",
                 "",
                 "hAlt", level>1 && gBranchStyle!=0);

   // Test on the @ notation to access the collection object itself
   DrawSkippable(tree,"event.@fTracks.size()","","hSize",level>2 && !(gBranchStyle==0 && !gHasLibrary));
   DrawSkippable(tree,"event.fTracks@.size()","","+hSize",level>2 && !(gBranchStyle==0 && !gHasLibrary));
   DrawSkippable(tree,"@fTracks.size()","","hSize2",level>2 && gBranchStyle!=0);
   DrawSkippable(tree,"fTracks@.size()","","+hSize2",level>2 && gBranchStyle!=0);
   DrawSkippable(tree,"Sum$(fPx)","","hSumPx",level>2);

   if (quietLevel<2) gBenchmark->Show("DrawTest");
   else gBenchmark->Stop("DrawTest");
   gBenchmark->Start("DrawTest");

   return hfile;

}

<|endoftext|>


<commit_before>// File: btBoostDynamics.hpp
#ifndef _btBoostDynamics_hpp
#define _btBoostDynamics_hpp

#include "btBoostDynamicsDbvtBroadphase.hpp"
#include "btBoostDynamicsDefaultCollisionConfiguration.hpp"
#include "btBoostDynamicsCollisionDispatcher.hpp"
#include "btBoostDynamicsSequentialImpulseConstraintSolver.hpp"
#include "btBoostDynamicsDiscreteDynamicsWorld.hpp"

void defineDynamics()
{
    defineDbvtBroadphase();
    defineDefaultCollisionConfiguration();
    defineCollisionDispatcher();
    defineSequentialImpulseConstraintSolver();
    defineDiscreteDynamicsWorld();
}

#endif // _btBoostDynamics_hpp
<commit_msg>Add call to shapes define<commit_after>// File: btBoostDynamics.hpp
#ifndef _btBoostDynamics_hpp
#define _btBoostDynamics_hpp

#include "btBoostDynamicsDbvtBroadphase.hpp"
#include "btBoostDynamicsDefaultCollisionConfiguration.hpp"
#include "btBoostDynamicsCollisionDispatcher.hpp"
#include "btBoostDynamicsSequentialImpulseConstraintSolver.hpp"
#include "btBoostDynamicsDiscreteDynamicsWorld.hpp"
#include "btBoostDynamicsShapes.hpp"

void defineDynamics()
{
    defineDbvtBroadphase();
    defineDefaultCollisionConfiguration();
    defineCollisionDispatcher();
    defineSequentialImpulseConstraintSolver();
    defineDiscreteDynamicsWorld();
    defineShapes();
}

#endif // _btBoostDynamics_hpp
<|endoftext|>


<commit_before>/*
 * =====================================================================================
 *
 *       Filename:  grep.cpp
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  2013年06月06日 13时21分39秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Kevin Hu (), hukai.kevin@snda.com
 *        Company:  Snda.com
 *
 * =====================================================================================
 */
#include <string>
#include<iostream>
#include<fstream>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <vector>

#include "am/hashtable/khash_table.hpp"
#include "am/util/line_reader.h"

#include <boost/thread/thread.hpp>

using namespace std;
using namespace izenelib::am::util;
using namespace izenelib;

int main(int argc,char * argv[])
{
    if (argc < 4)
    {
        std::cout<<argv[0]<<" [corpus] [token1 token2]\n";
        return 0;
    }

	std::string tks(argv[2]);
	std::vector<std::string> vstr;
	uint32_t last = 0;
	for ( uint32_t i=0; i<tks.length(); ++i)
	  if (tks[i] == ' ' && i > last)
	  {
		  vstr.push_back(tks.substr(last, i-last));
		  last = i + 1;
	  }
	  else if (i == last)last++;

	if (last < tks.length())
	  vstr.push_back(tks.substr(last));

	LineReader lr(argv[1], 1000000000);
	char* line = NULL;
	while((line=lr.line(line))!=NULL)
	{
		char* low = line;
		while(*low)
		{
			if(isupper(*low))
			  *low = tolower(*low);
			++low;
		}
		bool good = true;
		for ( uint32_t i=0; i<vstr.size(); ++i)
		  if ((low = strstr(line, vstr[i].c_str()))==NULL)
		  {
			  good = false;
			  break;
		  }
		if (good)
		  std::cout<<line<<std::endl;
	}
}
<commit_msg>add grep<commit_after>/*
 * =====================================================================================
 *
 *       Filename:  grep.cpp
 *
 *    Description:
 *
 *        Version:  1.0
 *        Created:  2013年06月06日 13时21分39秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Kevin Hu (), hukai.kevin@snda.com
 *        Company:  Snda.com
 *
 * =====================================================================================
 */
#include <string>
#include<iostream>
#include<fstream>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <vector>

#include "am/hashtable/khash_table.hpp"
#include "am/util/line_reader.h"

#include <boost/thread/thread.hpp>

using namespace std;
using namespace izenelib::am::util;
using namespace izenelib;

int main(int argc,char * argv[])
{
    if (argc < 4)
    {
        std::cout<<argv[0]<<" [corpus] [token1 token2] [max num]\n";
        return 0;
    }

	uint32_t MAX_N = atoi(argv[3]);
	std::string tks(argv[2]);
	std::vector<std::string> vstr;
	uint32_t last = 0;
	for ( uint32_t i=0; i<tks.length(); ++i)
	  if (tks[i] == ' ' && i > last)
	  {
		  vstr.push_back(tks.substr(last, i-last));
		  last = i + 1;
	  }
	  else if (i == last)last++;

	if (last < tks.length())
	  vstr.push_back(tks.substr(last));

	LineReader lr(argv[1], 1000000000);
	char* line = NULL;
	while((line=lr.line(line))!=NULL)
	{
		char* low = line;
		while(*low)
		{
			if(isupper(*low))
			  *low = tolower(*low);
			++low;
		}
		bool good = true;
		for ( uint32_t i=0; i<vstr.size(); ++i)
		  if ((low = strstr(line, vstr[i].c_str()))==NULL)
		  {
			  good = false;
			  break;
		  }
		if (good)
		  std::cout<<line<<std::endl;
	}
}
<|endoftext|>


<commit_before>#include "player.h"
#include "s_game.h"
#include "utilities.h"
#include "gameExceptions.h"
#include "rectButton.h"
#include "deck.h"
#include "hand.h"
#include "fonts.h"
#include "localization.h"

#include <string>
#include <fstream>
#include <exception>
#include <iomanip>
#include <sstream>

#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>

std::string Player::_playersFileName = std::string("players.txt");

Player::Player(std::ifstream& file, S_Game* game)
{
    if (!ReadText(file))
        throw InvalidPlayerException();

    _game = game;
    _hand = new Hand(Vector2D(0,0));
    // TODO Don't forget to delete this

    _doubleBet = false;
}

void Player::WriteText(std::ofstream& out) const
{
    out << std::fixed << std::setprecision(2) << _balance << " " << _name;
}

bool Player::ReadText(std::ifstream& file)
{
    file >> _balance;

    getline(file, _name, '\n');

    while (!_name.empty() && _name[0] == ' ')
        _name.erase(_name.begin());

    return !_name.empty();
}

void Player::PlaceBet()
{
    double bet = S_Game::GetBet();

    if (bet <= 0 || bet > _balance)
        throw InvalidBetException("Invalid bet exception at Player::PlaceBet(double bet)!");

    _balance -= bet;

    _game->PlayerBet(this);
}

bool Player::Hit(RectButton* btn)
{
    Card* tempCard = NULL;
    if (S_Game* game = _game)
        if (Deck* deck = game->GetDeck())
            tempCard = deck->WithdrawCard();

    if (tempCard != NULL)
    {
        _hand->AddCard(tempCard);
        _game->PlayerHit(this);
    }
    else
        _game->HandleOutOfCards();
    return true;
}

bool Player::Stand(RectButton* btn)
{
    _game->PlayerStand(this);
    return true;
}

bool Player::Double(RectButton* btn)
{
    Card* tempCard = _game->GetDeck()->WithdrawCard();

    if (tempCard != NULL)
    {
        _hand->AddCard(tempCard);
        _balance -= S_Game::GetBet();
        _doubleBet = true;
        _game->PlayerDouble(this);
    }
    else
        _game->HandleOutOfCards();

    // ...
    return true;
}

void Player::Lose()
{
    // ...

    // ResetPlayer();
}

void Player::ResetPlayer()
{
    _doubleBet = false;
    ClearHand();
}

void Player::Draw(bool activePlayer /*= false*/)
{
    if (_drawPosition.X == 0 && _drawPosition.Y == 0)
        return;

    // must draw hand, player name and total money
    const char* name = _name.c_str();

    std::stringstream ss;
    ss << _balance << ' ' << "€"; // euro symbol

    // must convert to USTR because we got the euro special symbol
    // P.S Encodings suck.
    ALLEGRO_USTR* balance = al_ustr_new(ss.str().c_str());

    if (activePlayer) al_draw_filled_rectangle(
        _drawPosition.X + 10,
        _drawPosition.Y + 10 + 105,
        _drawPosition.X + Fonts::GetFont(20)->vtable->text_length(Fonts::GetFont(20), al_ustr_new(name)) + 10,
        _drawPosition.Y + 10 + 105 + Fonts::GetFont(20)->height,
        al_map_rgb(120,120,255));
    al_draw_text(Fonts::GetFont(20), al_map_rgb(255, 255, 255),
        _drawPosition.X + 10, _drawPosition.Y + 10 + 105, 0, name);
    al_draw_ustr(Fonts::GetFont(20), al_map_rgb(255, 255, 255),
        _drawPosition.X + 10, _drawPosition.Y - 10 + 105, 0, balance);

    _hand->Draw();

    al_draw_scaled_bitmap(_game->GetChip(), 0, 0, al_get_bitmap_width(_game->GetChip()), al_get_bitmap_height(_game->GetChip()), _drawPosition.X - 30 - 5, _drawPosition.Y + 5, 30, 30, 0);
    if (_doubleBet)
        al_draw_scaled_bitmap(_game->GetChip(), 0, 0, al_get_bitmap_width(_game->GetChip()), al_get_bitmap_height(_game->GetChip()), _drawPosition.X - 30 - 5, _drawPosition.Y + 5 + 30 + 5, 30, 30, 0);
}

void Player::SetPosition(Vector2D position)
{
    _drawPosition = position;
    _hand->SetPosition(position);
}

<commit_msg>Revert unintended change<commit_after>#include "player.h"
#include "s_game.h"
#include "utilities.h"
#include "gameExceptions.h"
#include "rectButton.h"
#include "deck.h"
#include "hand.h"
#include "fonts.h"
#include "localization.h"

#include <string>
#include <fstream>
#include <exception>
#include <iomanip>
#include <sstream>

#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>

std::string Player::_playersFileName = std::string("players.txt");

Player::Player(std::ifstream& file, S_Game* game)
{
    if (!ReadText(file))
        throw InvalidPlayerException();

    _game = game;
    _hand = new Hand(Vector2D(0,0));
    // TODO Don't forget to delete this

    _doubleBet = false;
}

void Player::WriteText(std::ofstream& out) const
{
    out << std::fixed << std::setprecision(2) << _balance << " " << _name;
}

bool Player::ReadText(std::ifstream& file)
{
    file >> _balance;

    getline(file, _name, '\n');

    while (!_name.empty() && _name[0] == ' ')
        _name.erase(_name.begin());

    return !_name.empty();
}

void Player::PlaceBet()
{
    double bet = S_Game::GetBet();

    if (bet <= 0 || bet > _balance)
        throw InvalidBetException("Invalid bet exception at Player::PlaceBet(double bet)!");

    _balance -= bet;

    _game->PlayerBet(this);
}

bool Player::Hit(RectButton* btn)
{
    if (Card* tempCard = _game->GetDeck()->WithdrawCard())
    {
        _hand->AddCard(tempCard);
        _game->PlayerHit(this);
    }
    else
        _game->HandleOutOfCards();
    return true;
}

bool Player::Stand(RectButton* btn)
{
    _game->PlayerStand(this);
    return true;
}

bool Player::Double(RectButton* btn)
{
    Card* tempCard = _game->GetDeck()->WithdrawCard();

    if (tempCard != NULL)
    {
        _hand->AddCard(tempCard);
        _balance -= S_Game::GetBet();
        _doubleBet = true;
        _game->PlayerDouble(this);
    }
    else
        _game->HandleOutOfCards();

    // ...
    return true;
}

void Player::Lose()
{
    // ...

    // ResetPlayer();
}

void Player::ResetPlayer()
{
    _doubleBet = false;
    ClearHand();
}

void Player::Draw(bool activePlayer /*= false*/)
{
    if (_drawPosition.X == 0 && _drawPosition.Y == 0)
        return;

    // must draw hand, player name and total money
    const char* name = _name.c_str();

    std::stringstream ss;
    ss << _balance << ' ' << "€"; // euro symbol

    // must convert to USTR because we got the euro special symbol
    // P.S Encodings suck.
    ALLEGRO_USTR* balance = al_ustr_new(ss.str().c_str());

    if (activePlayer) al_draw_filled_rectangle(
        _drawPosition.X + 10,
        _drawPosition.Y + 10 + 105,
        _drawPosition.X + Fonts::GetFont(20)->vtable->text_length(Fonts::GetFont(20), al_ustr_new(name)) + 10,
        _drawPosition.Y + 10 + 105 + Fonts::GetFont(20)->height,
        al_map_rgb(120,120,255));
    al_draw_text(Fonts::GetFont(20), al_map_rgb(255, 255, 255),
        _drawPosition.X + 10, _drawPosition.Y + 10 + 105, 0, name);
    al_draw_ustr(Fonts::GetFont(20), al_map_rgb(255, 255, 255),
        _drawPosition.X + 10, _drawPosition.Y - 10 + 105, 0, balance);

    _hand->Draw();

    al_draw_scaled_bitmap(_game->GetChip(), 0, 0, al_get_bitmap_width(_game->GetChip()), al_get_bitmap_height(_game->GetChip()), _drawPosition.X - 30 - 5, _drawPosition.Y + 5, 30, 30, 0);
    if (_doubleBet)
        al_draw_scaled_bitmap(_game->GetChip(), 0, 0, al_get_bitmap_width(_game->GetChip()), al_get_bitmap_height(_game->GetChip()), _drawPosition.X - 30 - 5, _drawPosition.Y + 5 + 30 + 5, 30, 30, 0);
}

void Player::SetPosition(Vector2D position)
{
    _drawPosition = position;
    _hand->SetPosition(position);
}

<|endoftext|>


<commit_before>
#include <ros/ros.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <boost/foreach.hpp>
#include <stdio.h>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <ctime>

typedef pcl::PointCloud<pcl::PointXYZRGB> PointCloud;

sensor_msgs::ImageConstPtr image;

void callback_image_saver(const sensor_msgs::ImageConstPtr& msg)
{
  image = msg;
}

void callback_human_detection(const PointCloud::ConstPtr& msg)
{
  //printf ("Cloud: width = %d, height = %d\n", msg->width, msg->height);
  int cnt = 0;
  int blue_cnt = 0;
  float dis = 0.0;

  float max_y = -10000.0;
  float min_y = 10000.0;
  BOOST_FOREACH (const pcl::PointXYZRGB& pt, msg->points) {
    cnt++;

    // here we assume the waist height is 90cm, and neck height is 160cm
    // the robot sensor's height is 60cm
    if (pt.y > max_y)
      max_y = pt.y;

    if (pt.y < min_y)
      min_y = pt.y;

    if (pt.y > -0.9 && pt.y < -0.2) {
      // distance to BLUE (0, 0, 255)
      // dis = pow(pow(pt.r-0.0, 2.0) + pow(pt.g-0.0, 2.0) + pow(pt.b-255.0, 2.0), 0.5);
      dis = pow(pow(pt.r-175.0, 2.0) + pow(pt.g-255.0, 2.0) + pow(pt.b-175.0, 2.0), 0.5);
      if (dis < 200)
        blue_cnt++;
    }
  }

  float ratio = (float)blue_cnt/(float)cnt;
  printf("ratio: %f\n", ratio);

  if (ratio > 0.30) {

    printf("person with GREEN SHIRT!!! \n");

    cv_bridge::CvImageConstPtr cv_ptr;
    try {

      time_t now = time(0);
      char* dt = ctime(&now);
      std::string str(dt);

      cv_ptr = cv_bridge::toCvShare(image, sensor_msgs::image_encodings::BGR8);
      cv::imwrite("/home/bwi/Desktop/" + str + ".jpg", cv_ptr->image);
    }
    catch (cv_bridge::Exception& e) {
      ROS_ERROR("cv_bridge exception: %s", e.what());
      return;
    }
  }
}

int main(int argc, char** argv)
{
  ros::init(argc, argv, "segbot_blue_shirt");
  ros::NodeHandle nh;

  ros::Subscriber sub1 = nh.subscribe<PointCloud>("/segbot_pcl_person_detector/human_clouds", 1, callback_human_detection);

  image_transport::ImageTransport it(nh);
  image_transport::Subscriber sub2 = it.subscribe("/nav_kinect/rgb/image_color", 1, callback_image_saver);
  // ros::Subscriber sub2 = nh.subscribe<sensor_msgs::Image>("/nav_kinect/rgb/image_color", 1, callback_image_saver);

  ros::spin();
}
<commit_msg>some changes on blue-shirt task<commit_after>
#include <ros/ros.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <boost/foreach.hpp>
#include <stdio.h>
#include <cv_bridge/cv_bridge.h>
#include <image_transport/image_transport.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <ctime>

typedef pcl::PointCloud<pcl::PointXYZRGB> PointCloud;

sensor_msgs::ImageConstPtr image;

void callback_image_saver(const sensor_msgs::ImageConstPtr& msg)
{
  image = msg;
}

void callback_human_detection(const PointCloud::ConstPtr& msg)
{
  //printf ("Cloud: width = %d, height = %d\n", msg->width, msg->height);
  int cnt = 0;
  int blue_cnt = 0;
  float dis = 0.0;

  float max_y = -10000.0;
  float min_y = 10000.0;
  BOOST_FOREACH (const pcl::PointXYZRGB& pt, msg->points) {
    cnt++;

    // here we assume the waist height is 90cm, and neck height is 160cm
    // the robot sensor's height is 60cm
    if (pt.y > max_y)
      max_y = pt.y;

    if (pt.y < min_y)
      min_y = pt.y;

    if (pt.y > -0.9 && pt.y < -0.1) {
      // distance to BLUE (0, 0, 255)
      dis = pow(pow(pt.r-0.0, 2.0) + pow(pt.g-0.0, 2.0) + pow(pt.b-255.0, 2.0), 0.5);
      if (dis < 200)
        blue_cnt++;
    }
  }

  float ratio = (float)blue_cnt/(float)cnt;
  printf("ratio: %f\n", ratio);

  if (ratio > 0.25) {

    ROS_INFO("person with BLUE SHIRT!!! \n");

    cv_bridge::CvImageConstPtr cv_ptr;
    try {

      time_t now = time(0);
      char* dt = ctime(&now);
      std::string str(dt);

      cv_ptr = cv_bridge::toCvShare(image, sensor_msgs::image_encodings::BGR8);
      cv::imwrite("/home/bwi/Desktop/" + str + ".jpg", cv_ptr->image);
    }
    catch (cv_bridge::Exception& e) {
      ROS_ERROR("cv_bridge exception: %s", e.what());
      return;
    }
  }
}

int main(int argc, char** argv)
{
  ros::init(argc, argv, "segbot_blue_shirt");
  ros::NodeHandle nh;

  ros::Subscriber sub1 = nh.subscribe<PointCloud>("/segbot_pcl_person_detector/human_clouds", 1, callback_human_detection);

  image_transport::ImageTransport it(nh);
  image_transport::Subscriber sub2 = it.subscribe("/nav_kinect/rgb/image_color", 1, callback_image_saver);

  ros::spin();
}
<|endoftext|>