<commit_before>
// macro to calculate the pt RecAnCuts/MCAcc
// efficiency, from a CF container
// Author: C. Zampolli

// channel could be:
// D0: D0 -> Kpi, from old task
// D0_New: D0 -> Kpi, from new CF common implementation
// Dplus_New: D+ -> Kpipi, from new CF common implementation
//
// eff = sum of the efficiency indexes to compute
// MCAcc_over_MCLimAcc = 0x001
// RecPPR_over_MCAcc = 0x002
// RecPID_over_MCAcc = 0x004
// all = 0x007
//
// selection = D origin
// 0 --> from c only
// 1 --> from b only
// 2 --> from both c and b

#include <Riostream.h>

extern TRandom *gRandom;
extern TBenchmark *gBenchmark;
extern TSystem *gSystem;

void DrawEfficiency(const char* channel, Int_t selection = 0, Int_t ieff = 7){

	gROOT->SetStyle("Plain");
	gStyle->SetPalette(1);
	gStyle->SetOptStat(0);
	gStyle->SetPalette(1);
	gStyle->SetCanvasColor(0);
	gStyle->SetFrameFillColor(0);
	gStyle->SetOptTitle(0);

	gSystem->SetIncludePath("-I. -I$ALICE_ROOT/include  -I$ROOTSYS/include");
	gSystem->Load("libANALYSIS.so");
	gSystem->Load("libANALYSISalice.so");
	gSystem->Load("$ALICE_ROOT/CORRFW/libCORRFW.so") ;
	gSystem->Load("libPWG3base.so");
	gSystem->Load("libPWG3vertexingHF.so");

	Int_t mcAcc_over_mcLimAcc = 0x001;
	Int_t recPPR_over_mcAcc = 0x002;
	Int_t recPID_over_mcAcc = 0x004;

	// pt index
	Int_t ipt =0;

	Int_t stepNum = -1;
	Int_t stepDen = -1;

	// Read the  container from file
	TFile* f = new TFile("AnalysisResults.root");
	TString directoryName;
	TString containerName;
	TString cutName;
	TString outfileName;

	if (channel == "D0") {
		if (selection == 0){
			directoryName = "PWG3_D2H_CFtaskD0toKpi";
			containerName = "CFHFccontainer0";
			cutName = "Cuts";
			outfileName = "fileEff_D0_from_c.root";
		}
		else if (selection == 1){
			directoryName = "PWG3_D2H_CFtaskD0toKpiKeepD0fromBOnly";
			containerName = "CFHFccontainer0D0fromB";
			cutName = "Cuts";
			outfileName = "fileEff_D0_from_b.root";
		}
		else if (selection == 2){
			directoryName = "PWG3_D2H_CFtaskD0toKpiKeepD0fromB";
			containerName = "CFHFccontainer0allD0";
			cutName = "Cuts";
			outfileName = "fileEff_D0_from_c_and_b.root";
		}
		else {
			Printf("not a valid selection, return");
			return;
		}
	}
	else if (channel == "D0_New"){
		if (selection == 0){
			directoryName = "PWG3_D2H_CFtaskD0toKpi_NEW";
			containerName = "CFHFccontainer0_New";
			cutName = "Cuts_New";
			//directoryName = "PWG3_D2H_CFtaskD0toKpi_CommonFramework";
			//containerName = "CFHFccontainer0_CommonFramework";
			//cutName = "Cuts_CommonFramework";
			outfileName = "fileEff_D0_CommonFramework_from_c.root";
		}
		else if (selection == 1){
			directoryName = "PWG3_D2H_CFtaskD0toKpiKeepDfromBOnly";
			containerName = "CFHFccontainer0DfromB_New";
			cutName = "Cuts_New";
			//directoryName = "PWG3_D2H_CFtaskD0toKpiKeepDfromBOnly_CommonFramework";
			//containerName = "CFHFccontainer0DfromB_CommonFramework";
			//cutName = "Cuts_CommonFramework";
			outfileName = "fileEff_D0_CommonFramework_from_b.root";
		}
		else if (selection == 2){
			directoryName = "PWG3_D2H_CFtaskD0toKpiKeepDfromB_NEW";
			containerName = "CFHFccontainer0allD_New";
			cutName = "Cuts_New";
			//directoryName = "PWG3_D2H_CFtaskD0toKpiKeepDfromB_CommonFramework";
			//containerName = "CFHFccontainer0allD_CommonFramework";
			//cutName = "Cuts_CommonFramework";
			outfileName = "fileEff_D0_CommonFramework_from_c_and_b.root";
		}
		else {
			Printf("not a valid selection, return");
			return;
		}
	}
	else if (channel == "Dplus_New"){
		if (selection == 0){
			directoryName = "PWG3_D2H_CFtaskDplustoKpipi_NEW";
			containerName = "CFHFccontainer0_New_3Prong";
			cutName = "Cuts_3Prong";
			//directoryName = "PWG3_D2H_CFtaskDplustoKpipi_CommonFramework";
			//containerName = "CFHFccontainer0_3Prong_CommonFramework";
			//cutName =  "Cuts_3Prong_CommonFramework";
			outfileName = "fileEff_Dplus_CommonFramework_from_c.root";
		}
		else if (selection == 1){
			directoryName = "PWG3_D2H_CFtaskDplustoKpipiKeepDfromBOnly";
			containerName = "CFHFccontainer0DfromB_New_3Prong";
			cutName = "Cuts_3Prong";
			//directoryName = "PWG3_D2H_CFtaskDplustoKpipiKeepDfromBOnly_CommonFramework";
			//containerName = "CFHFccontainer0DfromB_3Prong_CommonFramework";
			//cutName =  "Cuts_3Prong_CommonFramework";
			outfileName = "fileEff_Dplus_CommonFramework_from_b.root";
		}
		else if (selection == 2){
			directoryName = "PWG3_D2H_CFtaskDplustoKpipiKeepDfromB_NEW";
			containerName = "CFHFccontainer0allD_New_3Prong";
			cutName = "Cuts_3Prong";
			//directoryName = "PWG3_D2H_CFtaskDplustoKpipiKeepDfromB_CommonFramework";
			//containerName = "CFHFccontainer0allD_3Prong_CommonFramework";
			//cutName =  "Cuts_3Prong_CommonFramework";
			outfileName = "fileEff_Dplus_CommonFramework_from_c_and_b.root";
		}
		else {
			Printf("not a valid selection, return");
			return;
		}
	}
	else {
		Printf("not a valid channel, return");
		return;
	}

	Printf("Opening file Analysisresults.root");
	Printf("Reading Directory \"%s\"",directoryName.Data());
	Printf("Getting CF Container \"%s\"",containerName.Data());
	Printf("Getting Cut Object \"%s\"",cutName.Data());

	TDirectoryFile* d = (TDirectoryFile*)f->Get(directoryName.Data());
	if (!d){
		Printf("Directory does not exist! Check directory name (%s) in file AnalysisResults.root - returning...", directoryName.Data());
		return;
	}
	AliCFContainer *data = (AliCFContainer*) (d->Get(containerName.Data()));
	AliRDHFCuts *cutsRDHF = (AliRDHFCuts*)(d->Get(cutName.Data()));

	if (!data){
		Printf("Container does not exist! Check container name (%s) in directory %s - returning...", containerName.Data(), directoryName.Data());
		return;
	}

	TFile* fileEff = new TFile(outfileName.Data(), "RECREATE");
	TString plotDir(Form("EffPlots/%s",channel));
	gSystem->Exec(Form("mkdir EffPlots"));
	gSystem->Exec(Form("mkdir %s",plotDir.Data()));

	//construct the efficiency grid from the data container
	AliCFEffGrid *eff = new AliCFEffGrid("eff"," The efficiency",*data);

	TCanvas *ceffpt = new TCanvas("ceffpt","Efficiency vs pt",50,50,550,550);
	ceffpt->cd();
	ceffpt->SetLeftMargin(0.15);
	ceffpt->SetRightMargin(0.05);
	TH1D *hpteffCF = 0x0; //the efficiency vs pt

	if (ieff & mcAcc_over_mcLimAcc){
		AliCFEffGrid *eff = new AliCFEffGrid("eff"," The efficiency",*data);
		stepDen = (Int_t)(AliCFTaskVertexingHF::kStepGeneratedLimAcc);
		stepNum = (Int_t)(AliCFTaskVertexingHF::kStepAcceptance);
		printf("Calculating efficiency for mcAcc_over_mcLimAcc: stepDen = %d, stepNum = %d\n",stepDen,stepNum);
		eff->CalculateEfficiency(stepNum,stepDen); //eff= step1/step0

		//canvas
		ceffpt->cd();

		//The efficiency along the variables
		hpteffCF = eff->Project(ipt);
		SetHisto(hpteffCF,8,20,"mcAcc_over_mcLimAcc");
		hpteffCF->Draw("hist");
		hpteffCF->Draw("err same");
		fileEff->cd();
		hpteffCF->Write("hpteffCF_mcAcc_over_mcLimAcc");

		// printing png files
		ceffpt->Print(Form("%s/effpt_mcAcc_over_mcLimAcc.png", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_mcAcc_over_mcLimAcc.eps", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_mcAcc_over_mcLimAcc.gif", plotDir.Data()));
		delete eff;
		eff = 0x0;
	}

	if (ieff & recPPR_over_mcAcc){
		AliCFEffGrid *eff = new AliCFEffGrid("eff"," The efficiency",*data);
		stepDen = (Int_t)(AliCFTaskVertexingHF::kStepAcceptance);
		stepNum = (Int_t)(AliCFTaskVertexingHF::kStepRecoPPR);
		printf("Calculating efficiency for RecPPR_over_mcAcc: stepDen = %d, stepNum = %d\n",stepDen,stepNum);
		eff->CalculateEfficiency(stepNum,stepDen); //eff= step1/step0

		//canvas
		ceffpt->cd();

		//The efficiency along the variables
		hpteffCF = eff->Project(ipt);
		SetHisto(hpteffCF,8,20, "recAnCuts_over_mcAcc");
		hpteffCF->Draw("hist");
		hpteffCF->Draw("err same");
		fileEff->cd();
		hpteffCF->Write("hpteffCF_RecAnCut_over_mcAcc");

		// printing png files
		ceffpt->Print(Form("%s/effpt_RecAnCut_over_mcAcc.png", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_RecAnCut_over_mcAcc.eps", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_RecAnCut_over_mcAcc.gif", plotDir.Data()));
		delete eff;
		eff = 0x0;
	}

	if (ieff & recPID_over_mcAcc){
		AliCFEffGrid *eff = new AliCFEffGrid("eff"," The efficiency",*data);
		stepDen = (Int_t)(AliCFTaskVertexingHF::kStepAcceptance);
		stepNum = (Int_t)(AliCFTaskVertexingHF::kStepRecoPID);
		printf("Calculating efficiency for RecPID_over_mcAcc: stepDen = %d, stepNum = %d\n",stepDen,stepNum);
		eff->CalculateEfficiency(stepNum,stepDen); //eff= step1/step0

		//canvas
		ceffpt->cd();

		//The efficiency along the variables
		hpteffCF = eff->Project(ipt);
		SetHisto(hpteffCF,8,20,"recPID_over_mcAcc");
		hpteffCF->Draw("hist");
		hpteffCF->Draw("err same");
		fileEff->cd();
		hpteffCF->Write("hpteffCF_RecPID_over_mcAcc");

		// printing png files
		ceffpt->Print(Form("%s/effpt_RecPID_over_mcAcc.png", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_RecPID_over_mcAcc.eps", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_RecPID_over_mcAcc.gif", plotDir.Data()));
		delete eff;
		eff = 0x0;
	}

	cutsRDHF->Write("Cuts");

	//	fileEff->Close(); // commented out to see the canvas on the screen....
}

void SetHisto(TH1D* h, Int_t color, Int_t style, const char* effType){

	h->SetLineColor(color);
	h->SetLineWidth(3);
	h->SetMarkerStyle(style);
	h->SetMarkerColor(color);
	h->SetMarkerSize(1.2);
	h->GetYaxis()->SetTitleOffset(1.5);
	h->GetXaxis()->SetTitle("p_{t} [GeV/c]");
	h->GetYaxis()->SetTitle(Form("%s, Efficiency",effType));
	return;
}
<commit_msg>Added plot (ChiaraZ)<commit_after>
// macro to calculate the pt RecAnCuts/MCAcc
// efficiency, from a CF container
// Author: C. Zampolli

// channel could be:
// D0: D0 -> Kpi, from old task
// D0_New: D0 -> Kpi, from new CF common implementation
// Dplus_New: D+ -> Kpipi, from new CF common implementation
//
// eff = sum of the efficiency indexes to compute
// MCAcc_over_MCLimAcc = 0x001
// RecPPR_over_MCAcc = 0x002
// RecPID_over_MCAcc = 0x004
// all = 0x007
//
// selection = D origin
// 0 --> from c only
// 1 --> from b only
// 2 --> from both c and b

#include <Riostream.h>

extern TRandom *gRandom;
extern TBenchmark *gBenchmark;
extern TSystem *gSystem;

void DrawEfficiency(const char* channel, Int_t selection = 0, Int_t ieff = 7){

	gROOT->SetStyle("Plain");
	gStyle->SetPalette(1);
	gStyle->SetOptStat(0);
	gStyle->SetPalette(1);
	gStyle->SetCanvasColor(0);
	gStyle->SetFrameFillColor(0);
	gStyle->SetOptTitle(0);

	gSystem->SetIncludePath("-I. -I$ALICE_ROOT/include  -I$ROOTSYS/include");
	gSystem->Load("libANALYSIS.so");
	gSystem->Load("libANALYSISalice.so");
	gSystem->Load("$ALICE_ROOT/CORRFW/libCORRFW.so") ;
	gSystem->Load("libPWG3base.so");
	gSystem->Load("libPWG3vertexingHF.so");

	Int_t mcAcc_over_mcLimAcc = 0x001;
	Int_t recPPR_over_mcAcc = 0x002;
	Int_t recPID_over_mcAcc = 0x004;

	// pt index
	Int_t ipt =0;

	Int_t stepNum = -1;
	Int_t stepDen = -1;

	// Read the  container from file
	TFile* f = new TFile("AnalysisResults.root");
	TString directoryName;
	TString containerName;
	TString cutName;
	TString outfileName;

	if (channel == "D0") {
		if (selection == 0){
			directoryName = "PWG3_D2H_CFtaskD0toKpi";
			containerName = "CFHFccontainer0";
			cutName = "Cuts";
			outfileName = "fileEff_D0_from_c.root";
		}
		else if (selection == 1){
			directoryName = "PWG3_D2H_CFtaskD0toKpiKeepD0fromBOnly";
			containerName = "CFHFccontainer0D0fromB";
			cutName = "Cuts";
			outfileName = "fileEff_D0_from_b.root";
		}
		else if (selection == 2){
			directoryName = "PWG3_D2H_CFtaskD0toKpiKeepD0fromB";
			containerName = "CFHFccontainer0allD0";
			cutName = "Cuts";
			outfileName = "fileEff_D0_from_c_and_b.root";
		}
		else {
			Printf("not a valid selection, return");
			return;
		}
	}
	else if (channel == "D0_New"){
		if (selection == 0){
			directoryName = "PWG3_D2H_CFtaskD0toKpi_NEW";
			containerName = "CFHFccontainer0_New";
			cutName = "Cuts_New";
			//directoryName = "PWG3_D2H_CFtaskD0toKpi_CommonFramework";
			//containerName = "CFHFccontainer0_CommonFramework";
			//cutName = "Cuts_CommonFramework";
			outfileName = "fileEff_D0_CommonFramework_from_c.root";
		}
		else if (selection == 1){
			directoryName = "PWG3_D2H_CFtaskD0toKpiKeepDfromBOnly";
			containerName = "CFHFccontainer0DfromB_New";
			cutName = "Cuts_New";
			//directoryName = "PWG3_D2H_CFtaskD0toKpiKeepDfromBOnly_CommonFramework";
			//containerName = "CFHFccontainer0DfromB_CommonFramework";
			//cutName = "Cuts_CommonFramework";
			outfileName = "fileEff_D0_CommonFramework_from_b.root";
		}
		else if (selection == 2){
			directoryName = "PWG3_D2H_CFtaskD0toKpiKeepDfromB_NEW";
			containerName = "CFHFccontainer0allD_New";
			cutName = "Cuts_New";
			//directoryName = "PWG3_D2H_CFtaskD0toKpiKeepDfromB_CommonFramework";
			//containerName = "CFHFccontainer0allD_CommonFramework";
			//cutName = "Cuts_CommonFramework";
			outfileName = "fileEff_D0_CommonFramework_from_c_and_b.root";
		}
		else {
			Printf("not a valid selection, return");
			return;
		}
	}
	else if (channel == "Dplus_New"){
		if (selection == 0){
			directoryName = "PWG3_D2H_CFtaskDplustoKpipi_NEW";
			containerName = "CFHFccontainer0_New_3Prong";
			cutName = "Cuts_3Prong";
			//directoryName = "PWG3_D2H_CFtaskDplustoKpipi_CommonFramework";
			//containerName = "CFHFccontainer0_3Prong_CommonFramework";
			//cutName =  "Cuts_3Prong_CommonFramework";
			outfileName = "fileEff_Dplus_CommonFramework_from_c.root";
		}
		else if (selection == 1){
			directoryName = "PWG3_D2H_CFtaskDplustoKpipiKeepDfromBOnly";
			containerName = "CFHFccontainer0DfromB_New_3Prong";
			cutName = "Cuts_3Prong";
			//directoryName = "PWG3_D2H_CFtaskDplustoKpipiKeepDfromBOnly_CommonFramework";
			//containerName = "CFHFccontainer0DfromB_3Prong_CommonFramework";
			//cutName =  "Cuts_3Prong_CommonFramework";
			outfileName = "fileEff_Dplus_CommonFramework_from_b.root";
		}
		else if (selection == 2){
			directoryName = "PWG3_D2H_CFtaskDplustoKpipiKeepDfromB_NEW";
			containerName = "CFHFccontainer0allD_New_3Prong";
			cutName = "Cuts_3Prong";
			//directoryName = "PWG3_D2H_CFtaskDplustoKpipiKeepDfromB_CommonFramework";
			//containerName = "CFHFccontainer0allD_3Prong_CommonFramework";
			//cutName =  "Cuts_3Prong_CommonFramework";
			outfileName = "fileEff_Dplus_CommonFramework_from_c_and_b.root";
		}
		else {
			Printf("not a valid selection, return");
			return;
		}
	}
	else {
		Printf("not a valid channel, return");
		return;
	}

	Printf("Opening file Analysisresults.root");
	Printf("Reading Directory \"%s\"",directoryName.Data());
	Printf("Getting CF Container \"%s\"",containerName.Data());
	Printf("Getting Cut Object \"%s\"",cutName.Data());

	TDirectoryFile* d = (TDirectoryFile*)f->Get(directoryName.Data());
	if (!d){
		Printf("Directory does not exist! Check directory name (%s) in file AnalysisResults.root - returning...", directoryName.Data());
		return;
	}
	AliCFContainer *data = (AliCFContainer*) (d->Get(containerName.Data()));
	AliRDHFCuts *cutsRDHF = (AliRDHFCuts*)(d->Get(cutName.Data()));

	if (!data){
		Printf("Container does not exist! Check container name (%s) in directory %s - returning...", containerName.Data(), directoryName.Data());
		return;
	}

	TFile* fileEff = new TFile(outfileName.Data(), "RECREATE");
	TString plotDir(Form("EffPlots/%s",channel));
	gSystem->Exec(Form("mkdir EffPlots"));
	gSystem->Exec(Form("mkdir %s",plotDir.Data()));

	//construct the efficiency grid from the data container
	AliCFEffGrid *eff = new AliCFEffGrid("eff"," The efficiency",*data);

	TCanvas *ceffpt = new TCanvas("ceffpt","Efficiency vs pt",50,50,550,550);
	ceffpt->cd();
	ceffpt->SetLeftMargin(0.15);
	ceffpt->SetRightMargin(0.05);
	TH1D *hpteffCF = 0x0; //the efficiency vs pt

	if (ieff & mcAcc_over_mcLimAcc){
		AliCFEffGrid *eff = new AliCFEffGrid("eff"," The efficiency",*data);
		stepDen = (Int_t)(AliCFTaskVertexingHF::kStepGeneratedLimAcc);
		stepNum = (Int_t)(AliCFTaskVertexingHF::kStepAcceptance);
		printf("Calculating efficiency for mcAcc_over_mcLimAcc: stepDen = %d, stepNum = %d\n",stepDen,stepNum);
		eff->CalculateEfficiency(stepNum,stepDen); //eff= step1/step0

		//canvas
		ceffpt->cd();

		//The efficiency along the variables
		hpteffCF = eff->Project(ipt);
		SetHistoEff(hpteffCF,8,20,"mcAcc_over_mcLimAcc");
		hpteffCF->Draw("hist");
		hpteffCF->Draw("err same");
		fileEff->cd();
		hpteffCF->Write("hpteffCF_mcAcc_over_mcLimAcc");

		// printing png files
		ceffpt->Print(Form("%s/effpt_mcAcc_over_mcLimAcc.png", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_mcAcc_over_mcLimAcc.eps", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_mcAcc_over_mcLimAcc.gif", plotDir.Data()));
		delete eff;
		eff = 0x0;
	}

	if (ieff & recPPR_over_mcAcc){
		AliCFEffGrid *eff = new AliCFEffGrid("eff"," The efficiency",*data);
		stepDen = (Int_t)(AliCFTaskVertexingHF::kStepAcceptance);
		stepNum = (Int_t)(AliCFTaskVertexingHF::kStepRecoPPR);
		printf("Calculating efficiency for RecPPR_over_mcAcc: stepDen = %d, stepNum = %d\n",stepDen,stepNum);
		eff->CalculateEfficiency(stepNum,stepDen); //eff= step1/step0

		//canvas
		ceffpt->cd();

		//The efficiency along the variables
		hpteffCF = eff->Project(ipt);
		SetHistoEff(hpteffCF,8,20, "recAnCuts_over_mcAcc");
		hpteffCF->Draw("hist");
		hpteffCF->Draw("err same");
		fileEff->cd();
		hpteffCF->Write("hpteffCF_RecAnCut_over_mcAcc");

		// printing png files
		ceffpt->Print(Form("%s/effpt_RecAnCut_over_mcAcc.png", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_RecAnCut_over_mcAcc.eps", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_RecAnCut_over_mcAcc.gif", plotDir.Data()));
		delete eff;
		eff = 0x0;
	}

	if (ieff & recPID_over_mcAcc){
		AliCFEffGrid *eff = new AliCFEffGrid("eff"," The efficiency",*data);
		stepDen = (Int_t)(AliCFTaskVertexingHF::kStepAcceptance);
		stepNum = (Int_t)(AliCFTaskVertexingHF::kStepRecoPID);
		printf("Calculating efficiency for RecPID_over_mcAcc: stepDen = %d, stepNum = %d\n",stepDen,stepNum);
		eff->CalculateEfficiency(stepNum,stepDen); //eff= step1/step0

		//canvas
		ceffpt->cd();

		//The efficiency along the variables
		hpteffCF = eff->Project(ipt);
		SetHistoEff(hpteffCF,8,20,"recPID_over_mcAcc");
		hpteffCF->Draw("hist");
		hpteffCF->Draw("err same");
		fileEff->cd();
		hpteffCF->Write("hpteffCF_RecPID_over_mcAcc");

		// printing png files
		ceffpt->Print(Form("%s/effpt_RecPID_over_mcAcc.png", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_RecPID_over_mcAcc.eps", plotDir.Data()));
		ceffpt->Print(Form("%s/effpt_RecPID_over_mcAcc.gif", plotDir.Data()));
		delete eff;
		eff = 0x0;
	}

	cutsRDHF->Write("Cuts");

	// writing single distributions
	TH1D *hMCAccpt = data->ShowProjection(ipt, AliCFTaskVertexingHF::kStepAcceptance);
	SetHistoDistribution(hMCAccpt, 1, 20);
	hMCAccpt->Draw();
	TH1D *hMCLimAccpt = data->ShowProjection(ipt, AliCFHeavyFlavourTaskMultiVarMultiStep::kStepGeneratedLimAcc);
	SetHistoDistribution(hMCLimAccpt, 4, 20);
	TH1D *hRecoAnCutspt = data->ShowProjection(ipt, AliCFTaskVertexingHF::kStepRecoPPR);
	SetHistoDistribution(hRecoAnCutspt, 8, 20);
	TH1D *hRecoPIDpt = data->ShowProjection(ipt, AliCFTaskVertexingHF::kStepRecoPID);
	SetHistoDistribution(hRecoPIDpt, 6, 20);
	hMCAccpt->Write("hMCAccpt");
	hMCLimAccpt->Write("hMCLimAccpt");
	hRecoAnCutspt->Write("hRecoAnCutspt");
	hRecoPIDpt->Write("hRecoPIDpt");

	//	fileEff->Close(); // commented out to see the canvas on the screen....

}

void SetHistoEff(TH1D* h, Int_t color, Int_t style, const char* effType){

	h->SetLineColor(color);
	h->SetLineWidth(3);
	h->SetMarkerStyle(style);
	h->SetMarkerColor(color);
	h->SetMarkerSize(1.2);
	h->GetYaxis()->SetTitleOffset(1.5);
	h->GetXaxis()->SetTitleOffset(1.2);
	h->GetXaxis()->SetTitle("p_{t} [GeV/c]");
	h->GetYaxis()->SetTitle(Form("%s, Efficiency",effType));
	return;
}
void SetHistoDistribution(TH1D* h, Int_t color, Int_t style){

	h->SetLineColor(color);
	h->SetLineWidth(3);
	h->SetMarkerStyle(style);
	h->SetMarkerColor(color);
	h->SetMarkerSize(1.2);
	h->GetXaxis()->SetTitleOffset(1.2);
	h->GetXaxis()->SetTitle("p_{t} [GeV/c]");
	return;
}
<|endoftext|>


<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#include <boost/test/unit_test.hpp>

#include <pdal/drivers/pipeline/Reader.hpp>
#include <pdal/filters/Index.hpp>
#include <pdal/StageIterator.hpp>
#include <pdal/Schema.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/Options.hpp>

#include "Support.hpp"

using namespace pdal;

BOOST_AUTO_TEST_SUITE(IndexFilterTest)
//
// BOOST_AUTO_TEST_CASE(test_3d)
// {
// #ifdef PDAL_HAVE_FLANN
//     pdal::Option option("filename", Support::datapath("pipeline/pipeline_index.xml"));
//     pdal::Options options(option);
//
//     pdal::drivers::pipeline::Reader reader(options);
//     reader.initialize();
//
//     pdal::filters::Index const* filter = static_cast<pdal::filters::Index const*>(reader.getManager().getStage());
//     pdal::Options opt = filter->getOptions();
//     // std::cout << "filter ops: " << opt << std::endl;
//
//     const pdal::Schema& schema = filter->getSchema();
//     pdal::PointBuffer data(schema, 20);
//
//     pdal::StageSequentialIterator* it = filter->createSequentialIterator(data);
//
//     boost::uint32_t numRead = it->read(data);
//     BOOST_CHECK(numRead == 20);
//
//
//     pdal::filters::iterators::sequential::Index* iter = dynamic_cast<pdal::filters::iterators::sequential::Index*>(it);
//
//     iter->build();
//     unsigned k = 8;
//
//     // If the query distance is 0, just return the k nearest neighbors
//     std::vector<boost::uint32_t> ids = iter->query(636199, 849238, 428.05, 0.0, k);
//
//     BOOST_CHECK_EQUAL(ids.size(), k);
//     if (ids.size())
//     {
//         BOOST_CHECK_EQUAL(ids[0], 8u);
//         BOOST_CHECK_EQUAL(ids[4], 10u);
//     }
//
//     std::vector<boost::uint32_t> dist_ids = iter->query(636199, 849238, 428.05, 100.0, k);
//
//     if (dist_ids.size())
//     {
//         BOOST_CHECK_EQUAL(dist_ids.size(), 3u);
//         BOOST_CHECK_EQUAL(dist_ids[0], 8u);
//     }
//
//     delete it;
// #endif
//
//     return;
// }
//
//
// BOOST_AUTO_TEST_CASE(test_new2d)
// {
// #ifdef PDAL_HAVE_FLANN
//     pdal::Option option("filename", Support::datapath("pipeline/pipeline_index.xml"));
//     pdal::Options options(option);
//
//     pdal::drivers::pipeline::Reader reader(options);
//     reader.initialize();
//
//     pdal::filters::Index * filter = static_cast<pdal::filters::Index *>(reader.getManager().getStage());
//
//     filter->setNumDimensions(2);
//
//     const pdal::Schema& schema = filter->getSchema();
//     pdal::PointBuffer data(schema, 20);
//
//     pdal::StageSequentialIterator* it = filter->createSequentialIterator(data);
//
//     boost::uint32_t numRead = it->read(data);
//     BOOST_CHECK(numRead == 20);
//
//
//     pdal::filters::iterators::sequential::Index* iter = dynamic_cast<pdal::filters::iterators::sequential::Index*>(it);
//
//     iter->build();
//     unsigned k = 8;
//
//     // If the query distance is 0, just return the k nearest neighbors
//     std::vector<boost::uint32_t> ids = iter->query(636199, 849238, 428.05, 0.0, k);
//
//     BOOST_CHECK_EQUAL(ids.size(), k);
//
//     if (ids.size())
//     {
//         BOOST_CHECK_EQUAL(ids[0], 8u);
//         BOOST_CHECK_EQUAL(ids[4], 10u);
//     }
//
//     std::vector<boost::uint32_t> dist_ids = iter->query(636199, 849238, 428.05, 100.0, k);
//
//     if (dist_ids.size())
//     {
//         BOOST_CHECK_EQUAL(dist_ids.size(), 3u);
//         BOOST_CHECK_EQUAL(dist_ids[0], 8u);
//     }
//
//     delete it;
// #endif
//
//     return;
// }

}<commit_msg>*really* turn off index tests<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#include <boost/test/unit_test.hpp>

#include <pdal/drivers/pipeline/Reader.hpp>
#include <pdal/filters/Index.hpp>
#include <pdal/StageIterator.hpp>
#include <pdal/Schema.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/Options.hpp>

#include "Support.hpp"

using namespace pdal;
//
// BOOST_AUTO_TEST_SUITE(IndexFilterTest)
// //
// // BOOST_AUTO_TEST_CASE(test_3d)
// // {
// // #ifdef PDAL_HAVE_FLANN
// //     pdal::Option option("filename", Support::datapath("pipeline/pipeline_index.xml"));
// //     pdal::Options options(option);
// //
// //     pdal::drivers::pipeline::Reader reader(options);
// //     reader.initialize();
// //
// //     pdal::filters::Index const* filter = static_cast<pdal::filters::Index const*>(reader.getManager().getStage());
// //     pdal::Options opt = filter->getOptions();
// //     // std::cout << "filter ops: " << opt << std::endl;
// //
// //     const pdal::Schema& schema = filter->getSchema();
// //     pdal::PointBuffer data(schema, 20);
// //
// //     pdal::StageSequentialIterator* it = filter->createSequentialIterator(data);
// //
// //     boost::uint32_t numRead = it->read(data);
// //     BOOST_CHECK(numRead == 20);
// //
// //
// //     pdal::filters::iterators::sequential::Index* iter = dynamic_cast<pdal::filters::iterators::sequential::Index*>(it);
// //
// //     iter->build();
// //     unsigned k = 8;
// //
// //     // If the query distance is 0, just return the k nearest neighbors
// //     std::vector<boost::uint32_t> ids = iter->query(636199, 849238, 428.05, 0.0, k);
// //
// //     BOOST_CHECK_EQUAL(ids.size(), k);
// //     if (ids.size())
// //     {
// //         BOOST_CHECK_EQUAL(ids[0], 8u);
// //         BOOST_CHECK_EQUAL(ids[4], 10u);
// //     }
// //
// //     std::vector<boost::uint32_t> dist_ids = iter->query(636199, 849238, 428.05, 100.0, k);
// //
// //     if (dist_ids.size())
// //     {
// //         BOOST_CHECK_EQUAL(dist_ids.size(), 3u);
// //         BOOST_CHECK_EQUAL(dist_ids[0], 8u);
// //     }
// //
// //     delete it;
// // #endif
// //
// //     return;
// // }
// //
// //
// // BOOST_AUTO_TEST_CASE(test_new2d)
// // {
// // #ifdef PDAL_HAVE_FLANN
// //     pdal::Option option("filename", Support::datapath("pipeline/pipeline_index.xml"));
// //     pdal::Options options(option);
// //
// //     pdal::drivers::pipeline::Reader reader(options);
// //     reader.initialize();
// //
// //     pdal::filters::Index * filter = static_cast<pdal::filters::Index *>(reader.getManager().getStage());
// //
// //     filter->setNumDimensions(2);
// //
// //     const pdal::Schema& schema = filter->getSchema();
// //     pdal::PointBuffer data(schema, 20);
// //
// //     pdal::StageSequentialIterator* it = filter->createSequentialIterator(data);
// //
// //     boost::uint32_t numRead = it->read(data);
// //     BOOST_CHECK(numRead == 20);
// //
// //
// //     pdal::filters::iterators::sequential::Index* iter = dynamic_cast<pdal::filters::iterators::sequential::Index*>(it);
// //
// //     iter->build();
// //     unsigned k = 8;
// //
// //     // If the query distance is 0, just return the k nearest neighbors
// //     std::vector<boost::uint32_t> ids = iter->query(636199, 849238, 428.05, 0.0, k);
// //
// //     BOOST_CHECK_EQUAL(ids.size(), k);
// //
// //     if (ids.size())
// //     {
// //         BOOST_CHECK_EQUAL(ids[0], 8u);
// //         BOOST_CHECK_EQUAL(ids[4], 10u);
// //     }
// //
// //     std::vector<boost::uint32_t> dist_ids = iter->query(636199, 849238, 428.05, 100.0, k);
// //
// //     if (dist_ids.size())
// //     {
// //         BOOST_CHECK_EQUAL(dist_ids.size(), 3u);
// //         BOOST_CHECK_EQUAL(dist_ids[0], 8u);
// //     }
// //
// //     delete it;
// // #endif
// //
// //     return;
// // }
//
// }<|endoftext|>


<commit_before>#ifndef MAPNIK_UNIT_GEOMETRY_EQUAL
#define MAPNIK_UNIT_GEOMETRY_EQUAL

#include "catch.hpp"

// boost
#include <type_traits>
#include <iterator>

#include <mapnik/warning.hpp>
MAPNIK_DISABLE_WARNING_PUSH
#include <mapnik/warning_ignore.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/iterator/zip_iterator.hpp>
#include <boost/range/iterator_range.hpp>
MAPNIK_DISABLE_WARNING_POP

// helper namespace to ensure correct functionality
namespace aux{
namespace adl{
using std::begin;
using std::end;

template<class T>
auto do_begin(T& v) -> decltype(begin(v));
template<class T>
auto do_end(T& v) -> decltype(end(v));
} // adl::

template<class... Its>
using zipper_it = boost::zip_iterator<boost::tuple<Its...>>;

template<class T>
T const& as_const(T const& v){ return v; }
} // aux::

template<class... Conts>
auto zip_begin(Conts&... conts)
  -> aux::zipper_it<decltype(aux::adl::do_begin(conts))...>
{
  using std::begin;
  return {boost::make_tuple(begin(conts)...)};
}

template<class... Conts>
auto zip_end(Conts&... conts)
  -> aux::zipper_it<decltype(aux::adl::do_end(conts))...>
{
  using std::end;
  return {boost::make_tuple(end(conts)...)};
}

template<class... Conts>
auto zip_range(Conts&... conts)
  -> boost::iterator_range<decltype(zip_begin(conts...))>
{
  return {zip_begin(conts...), zip_end(conts...)};
}

// for const access
template<class... Conts>
auto zip_cbegin(Conts&... conts)
  -> decltype(zip_begin(aux::as_const(conts)...))
{
  using std::begin;
  return zip_begin(aux::as_const(conts)...);
}

template<class... Conts>
auto zip_cend(Conts&... conts)
  -> decltype(zip_end(aux::as_const(conts)...))
{
  using std::end;
  return zip_end(aux::as_const(conts)...);
}

template<class... Conts>
auto zip_crange(Conts&... conts)
  -> decltype(zip_range(aux::as_const(conts)...))
{
  return zip_range(aux::as_const(conts)...);
}

// mapnik
#include <mapnik/geometry.hpp>
#include <mapnik/util/variant.hpp>

using mapnik::geometry::geometry;
using mapnik::geometry::geometry_empty;
using mapnik::geometry::point;
using mapnik::geometry::line_string;
using mapnik::geometry::polygon;
using mapnik::geometry::multi_point;
using mapnik::geometry::multi_line_string;
using mapnik::geometry::multi_polygon;
using mapnik::geometry::geometry_collection;

template <typename T>
void assert_g_equal(geometry<T> const& g1, geometry<T> const& g2);

struct geometry_equal_visitor
{
    template <typename T1, typename T2>
    void operator() (T1 const&, T2 const&) const
    {
        // comparing two different types!
        REQUIRE(false);
    }

    template <typename T>
    void operator() (geometry_empty const&, geometry_empty const&) const
    {
        REQUIRE(true);
    }

    template <typename T>
    void operator() (point<T> const& p1, point<T> const& p2) const
    {
        REQUIRE(p1.x == Approx(p2.x));
        REQUIRE(p1.y == Approx(p2.y));
    }

    template <typename T>
    void operator() (std::vector<point<T>> const& ls1, std::vector<point<T>> const& ls2) const
    {
        if (ls1.size() != ls2.size())
        {
            REQUIRE(false);
        }

        for(auto const& p : zip_crange(ls1, ls2))
        {
            REQUIRE(p.template get<0>().x == Approx(p.template get<1>().x));
            REQUIRE(p.template get<0>().y == Approx(p.template get<1>().y));
        }
    }

    template <typename T>
    void operator() (polygon<T> const& p1, polygon<T> const& p2) const
    {
        if (p1.size() != p2.size())
        {
            REQUIRE(false);
        }

        for (auto const& p : zip_crange(p1, p2))
        {
            (*this)(static_cast<std::vector<point<T>> const&>(p.template get<0>()),
                    static_cast<std::vector<point<T>> const&>(p.template get<1>()));
        }
    }

    template <typename T>
    void operator() (line_string<T> const& ls1, line_string<T> const& ls2) const
    {
        (*this)(static_cast<std::vector<point<T>> const&>(ls1),
                static_cast<std::vector<point<T>> const&>(ls2));
    }

    template <typename T>
    void operator() (multi_point<T> const& mp1, multi_point<T> const& mp2) const
    {
        (*this)(static_cast<std::vector<point<T>> const&>(mp1),
                static_cast<std::vector<point<T>> const&>(mp2));
    }

    template <typename T>
    void operator() (multi_line_string<T> const& mls1, multi_line_string<T> const& mls2) const
    {
        if (mls1.size() != mls2.size())
        {
            REQUIRE(false);
        }

        for (auto const& ls : zip_crange(mls1, mls2))
        {
            (*this)(ls.template get<0>(),ls.template get<1>());
        }
    }

    template <typename T>
    void operator() (multi_polygon<T> const& mpoly1, multi_polygon<T> const& mpoly2) const
    {
        if (mpoly1.size() != mpoly2.size())
        {
            REQUIRE(false);
        }

        for (auto const& poly : zip_crange(mpoly1, mpoly2))
        {
            (*this)(poly.template get<0>(),poly.template get<1>());
        }
    }

    template <typename T>
    void operator() (mapnik::util::recursive_wrapper<geometry_collection<T> > const& c1_, mapnik::util::recursive_wrapper<geometry_collection<T> > const& c2_) const
    {
        geometry_collection<T> const& c1 = static_cast<geometry_collection<T> const&>(c1_);
        geometry_collection<T> const& c2 = static_cast<geometry_collection<T> const&>(c2_);
        if (c1.size() != c2.size())
        {
            REQUIRE(false);
        }

        for (auto const& g : zip_crange(c1, c2))
        {
            assert_g_equal(g.template get<0>(),g.template get<1>());
        }
    }

    template <typename T>
    void operator() (geometry_collection<T> const& c1, geometry_collection<T> const& c2) const
    {
        if (c1.size() != c2.size())
        {
            REQUIRE(false);
        }

        for (auto const& g : zip_crange(c1, c2))
        {
            assert_g_equal(g.template get<0>(),g.template get<1>());
        }
    }
};

template <typename T>
void assert_g_equal(geometry<T> const& g1, geometry<T> const& g2)
{
    return mapnik::util::apply_visitor(geometry_equal_visitor(), g1, g2);
}

template <typename T>
void assert_g_equal(T const& g1, T const& g2)
{
    return geometry_equal_visitor()(g1,g2);
}

#endif // MAPNIK_UNIT_GEOMETRY_EQUAL
<commit_msg>Fix compiler warning - use non-reference type 'boost::tuples::cons<...>'<commit_after>#ifndef MAPNIK_UNIT_GEOMETRY_EQUAL
#define MAPNIK_UNIT_GEOMETRY_EQUAL

#include "catch.hpp"

// boost
#include <type_traits>
#include <iterator>

#include <mapnik/warning.hpp>
MAPNIK_DISABLE_WARNING_PUSH
#include <mapnik/warning_ignore.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/iterator/zip_iterator.hpp>
#include <boost/range/iterator_range.hpp>
MAPNIK_DISABLE_WARNING_POP

// helper namespace to ensure correct functionality
namespace aux{
namespace adl{
using std::begin;
using std::end;

template<class T>
auto do_begin(T& v) -> decltype(begin(v));
template<class T>
auto do_end(T& v) -> decltype(end(v));
} // adl::

template<class... Its>
using zipper_it = boost::zip_iterator<boost::tuple<Its...>>;

template<class T>
T const& as_const(T const& v){ return v; }
} // aux::

template<class... Conts>
auto zip_begin(Conts&... conts)
  -> aux::zipper_it<decltype(aux::adl::do_begin(conts))...>
{
  using std::begin;
  return {boost::make_tuple(begin(conts)...)};
}

template<class... Conts>
auto zip_end(Conts&... conts)
  -> aux::zipper_it<decltype(aux::adl::do_end(conts))...>
{
  using std::end;
  return {boost::make_tuple(end(conts)...)};
}

template<class... Conts>
auto zip_range(Conts&... conts)
  -> boost::iterator_range<decltype(zip_begin(conts...))>
{
  return {zip_begin(conts...), zip_end(conts...)};
}

// for const access
template<class... Conts>
auto zip_cbegin(Conts&... conts)
  -> decltype(zip_begin(aux::as_const(conts)...))
{
  using std::begin;
  return zip_begin(aux::as_const(conts)...);
}

template<class... Conts>
auto zip_cend(Conts&... conts)
  -> decltype(zip_end(aux::as_const(conts)...))
{
  using std::end;
  return zip_end(aux::as_const(conts)...);
}

template<class... Conts>
auto zip_crange(Conts&... conts)
  -> decltype(zip_range(aux::as_const(conts)...))
{
  return zip_range(aux::as_const(conts)...);
}

// mapnik
#include <mapnik/geometry.hpp>
#include <mapnik/util/variant.hpp>

using mapnik::geometry::geometry;
using mapnik::geometry::geometry_empty;
using mapnik::geometry::point;
using mapnik::geometry::line_string;
using mapnik::geometry::polygon;
using mapnik::geometry::multi_point;
using mapnik::geometry::multi_line_string;
using mapnik::geometry::multi_polygon;
using mapnik::geometry::geometry_collection;

template <typename T>
void assert_g_equal(geometry<T> const& g1, geometry<T> const& g2);

struct geometry_equal_visitor
{
    template <typename T1, typename T2>
    void operator() (T1 const&, T2 const&) const
    {
        // comparing two different types!
        REQUIRE(false);
    }

    template <typename T>
    void operator() (geometry_empty const&, geometry_empty const&) const
    {
        REQUIRE(true);
    }

    template <typename T>
    void operator() (point<T> const& p1, point<T> const& p2) const
    {
        REQUIRE(p1.x == Approx(p2.x));
        REQUIRE(p1.y == Approx(p2.y));
    }

    template <typename T>
    void operator() (std::vector<point<T>> const& ls1, std::vector<point<T>> const& ls2) const
    {
        if (ls1.size() != ls2.size())
        {
            REQUIRE(false);
        }

        for (auto const p : zip_crange(ls1, ls2))
        {
            REQUIRE(p.template get<0>().x == Approx(p.template get<1>().x));
            REQUIRE(p.template get<0>().y == Approx(p.template get<1>().y));
        }
    }

    template <typename T>
    void operator() (polygon<T> const& p1, polygon<T> const& p2) const
    {
        if (p1.size() != p2.size())
        {
            REQUIRE(false);
        }

        for (auto const p : zip_crange(p1, p2))
        {
            (*this)(static_cast<std::vector<point<T>> const&>(p.template get<0>()),
                    static_cast<std::vector<point<T>> const&>(p.template get<1>()));
        }
    }

    template <typename T>
    void operator() (line_string<T> const& ls1, line_string<T> const& ls2) const
    {
        (*this)(static_cast<std::vector<point<T>> const&>(ls1),
                static_cast<std::vector<point<T>> const&>(ls2));
    }

    template <typename T>
    void operator() (multi_point<T> const& mp1, multi_point<T> const& mp2) const
    {
        (*this)(static_cast<std::vector<point<T>> const&>(mp1),
                static_cast<std::vector<point<T>> const&>(mp2));
    }

    template <typename T>
    void operator() (multi_line_string<T> const& mls1, multi_line_string<T> const& mls2) const
    {
        if (mls1.size() != mls2.size())
        {
            REQUIRE(false);
        }

        for (auto const ls : zip_crange(mls1, mls2))
        {
            (*this)(ls.template get<0>(),ls.template get<1>());
        }
    }

    template <typename T>
    void operator() (multi_polygon<T> const& mpoly1, multi_polygon<T> const& mpoly2) const
    {
        if (mpoly1.size() != mpoly2.size())
        {
            REQUIRE(false);
        }

        for (auto const poly : zip_crange(mpoly1, mpoly2))
        {
            (*this)(poly.template get<0>(),poly.template get<1>());
        }
    }

    template <typename T>
    void operator() (mapnik::util::recursive_wrapper<geometry_collection<T> > const& c1_, mapnik::util::recursive_wrapper<geometry_collection<T> > const& c2_) const
    {
        geometry_collection<T> const& c1 = static_cast<geometry_collection<T> const&>(c1_);
        geometry_collection<T> const& c2 = static_cast<geometry_collection<T> const&>(c2_);
        if (c1.size() != c2.size())
        {
            REQUIRE(false);
        }

        for (auto const g : zip_crange(c1, c2))
        {
            assert_g_equal(g.template get<0>(),g.template get<1>());
        }
    }

    template <typename T>
    void operator() (geometry_collection<T> const& c1, geometry_collection<T> const& c2) const
    {
        if (c1.size() != c2.size())
        {
            REQUIRE(false);
        }

        for (auto const g : zip_crange(c1, c2))
        {
            assert_g_equal(g.template get<0>(),g.template get<1>());
        }
    }
};

template <typename T>
void assert_g_equal(geometry<T> const& g1, geometry<T> const& g2)
{
    return mapnik::util::apply_visitor(geometry_equal_visitor(), g1, g2);
}

template <typename T>
void assert_g_equal(T const& g1, T const& g2)
{
    return geometry_equal_visitor()(g1,g2);
}

#endif // MAPNIK_UNIT_GEOMETRY_EQUAL
<|endoftext|>


<commit_before>/*
 * corrections.cc
 *
 *  Copyright (C) 2013 Diamond Light Source
 *
 *  Author: James Parkhurst
 *
 *  This code is distributed under the BSD license, a copy of which is
 *  included in the root directory of this package.
 */
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <dials/algorithms/integration/corrections.h>

using namespace boost::python;

namespace dials { namespace algorithms { namespace boost_python {

  void export_corrections() {

    def("lp_correction", &lp_correction, (
          arg("s0"),
          arg("pn"),
          arg("pf"),
          arg("m2"),
          arg("s1")));

    def("dqe_correction", &dqe_correction, (
          arg("mu"),
          arg("t0"),
          arg("s1"),
          arg("n")));

    class_<Corrections>("Corrections", no_init)
      .def(init< const BeamBase&,
                 const Goniometer&,
                 const Detector& >())
      .def("lp", &Corrections::lp, (
            arg("s1")))
      .def("dqe", &Corrections::lp, (
            arg("s1")))
      ;

    class_<CorrectionsMulti>("CorrectionsMulti")
      .def("append", &CorrectionsMulti::push_back)
      .def("__len__", &CorrectionsMulti::size)
      .def("lp", &CorrectionsMulti::lp)
      .def("dqe", &CorrectionsMulti::dqe)
      ;
  }

}}} // namespace = dials::algorithms::boost_python
<commit_msg>Fixed boost python export of dqe<commit_after>/*
 * corrections.cc
 *
 *  Copyright (C) 2013 Diamond Light Source
 *
 *  Author: James Parkhurst
 *
 *  This code is distributed under the BSD license, a copy of which is
 *  included in the root directory of this package.
 */
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <dials/algorithms/integration/corrections.h>

using namespace boost::python;

namespace dials { namespace algorithms { namespace boost_python {

  void export_corrections() {

    def("lp_correction", &lp_correction, (
          arg("s0"),
          arg("pn"),
          arg("pf"),
          arg("m2"),
          arg("s1")));

    def("dqe_correction", &dqe_correction, (
          arg("mu"),
          arg("t0"),
          arg("s1"),
          arg("n")));

    class_<Corrections>("Corrections", no_init)
      .def(init< const BeamBase&,
                 const Goniometer&,
                 const Detector& >())
      .def("lp", &Corrections::lp, (
            arg("s1")))
      .def("dqe", &Corrections::dqe, (
            arg("s1"),
            arg("panel")))
      ;

    class_<CorrectionsMulti>("CorrectionsMulti")
      .def("append", &CorrectionsMulti::push_back)
      .def("__len__", &CorrectionsMulti::size)
      .def("lp", &CorrectionsMulti::lp)
      .def("dqe", &CorrectionsMulti::dqe)
      ;
  }

}}} // namespace = dials::algorithms::boost_python
<|endoftext|>


<commit_before>/*

 Copyright (c) 2018, Ford Motor Company
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

 Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following
 disclaimer in the documentation and/or other materials provided with the
 distribution.

 Neither the name of the Ford Motor Company nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

#include "sdl_rpc_plugin/commands/mobile/add_sub_menu_request.h"

#include "application_manager/application.h"
#include "application_manager/message_helper.h"
#include "utils/helpers.h"

namespace sdl_rpc_plugin {
using namespace application_manager;

namespace commands {

AddSubMenuRequest::AddSubMenuRequest(
    const application_manager::commands::MessageSharedPtr& message,
    ApplicationManager& application_manager,
    rpc_service::RPCService& rpc_service,
    HMICapabilities& hmi_capabilities,
    policy::PolicyHandlerInterface& policy_handler)
    : CommandRequestImpl(message,
                         application_manager,
                         rpc_service,
                         hmi_capabilities,
                         policy_handler) {}

AddSubMenuRequest::~AddSubMenuRequest() {}

void AddSubMenuRequest::Run() {
  LOG4CXX_AUTO_TRACE(logger_);

  ApplicationSharedPtr app = application_manager_.application(connection_key());

  if (!app) {
    LOG4CXX_ERROR(logger_, "NULL pointer");
    SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
    return;
  }

  smart_objects::SmartObject received_msg_params =
      (*message_)[strings::msg_params];
  mobile_apis::Result::eType verification_result =
      mobile_apis::Result::INVALID_ENUM;

  if (received_msg_params.keyExists(strings::menu_icon)) {
    verification_result = MessageHelper::VerifyImage(
        received_msg_params[strings::menu_icon], app, application_manager_);

    if (mobile_apis::Result::INVALID_DATA == verification_result) {
      LOG4CXX_ERROR(
          logger_, "MessageHelper::VerifyImage return " << verification_result);
      SendResponse(false, verification_result);
      return;
    }
  }

  const int32_t menu_id = received_msg_params[strings::menu_id].asInt();
  if (app->FindSubMenu(menu_id)) {
    LOG4CXX_ERROR(logger_, "Menu with id " << menu_id << " is not found.");
    SendResponse(false, mobile_apis::Result::INVALID_ID);
    return;
  }

  const std::string& menu_name =
      received_msg_params[strings::menu_name].asString();

  if (app->IsSubMenuNameAlreadyExist(menu_name)) {
    LOG4CXX_ERROR(logger_, "Menu name " << menu_name << " is duplicated.");
    SendResponse(false, mobile_apis::Result::DUPLICATE_NAME);
    return;
  }

  if (!CheckSubMenuName()) {
    LOG4CXX_ERROR(logger_, "Sub-menu name is not valid.");
    SendResponse(false, mobile_apis::Result::INVALID_DATA);
    return;
  }

  smart_objects::SmartObject msg_params =
      smart_objects::SmartObject(smart_objects::SmartType_Map);

  msg_params[strings::menu_id] = received_msg_params[strings::menu_id];
  if (received_msg_params.keyExists(strings::position)) {
    msg_params[strings::menu_params][strings::position] =
        received_msg_params[strings::position];
  }
  msg_params[strings::menu_params][strings::menu_name] =
      received_msg_params[strings::menu_name];
  msg_params[strings::app_id] = app->app_id();
  msg_params[strings::menu_icon] = received_msg_params[strings::menu_icon];

  StartAwaitForInterface(HmiInterfaces::HMI_INTERFACE_UI);
  SendHMIRequest(hmi_apis::FunctionID::UI_AddSubMenu, &msg_params, true);
}

void AddSubMenuRequest::on_event(const event_engine::Event& event) {
  LOG4CXX_AUTO_TRACE(logger_);
  const smart_objects::SmartObject& message = event.smart_object();

  switch (event.id()) {
    case hmi_apis::FunctionID::UI_AddSubMenu: {
      EndAwaitForInterface(HmiInterfaces::HMI_INTERFACE_UI);
      hmi_apis::Common_Result::eType result_code =
          static_cast<hmi_apis::Common_Result::eType>(
              message[strings::params][hmi_response::code].asInt());
      std::string response_info;
      GetInfo(message, response_info);
      const bool result = PrepareResultForMobileResponse(
          result_code, HmiInterfaces::HMI_INTERFACE_UI);

      ApplicationSharedPtr application =
          application_manager_.application(connection_key());

      if (!application) {
        LOG4CXX_ERROR(logger_, "NULL pointer");
        return;
      }

      if (result) {
        application->AddSubMenu(
            (*message_)[strings::msg_params][strings::menu_id].asInt(),
            (*message_)[strings::msg_params]);
      }
      SendResponse(result,
                   MessageHelper::HMIToMobileResult(result_code),
                   response_info.empty() ? NULL : response_info.c_str(),
                   &(message[strings::msg_params]));
      break;
    }
    default: {
      LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
      return;
    }
  }
}

bool AddSubMenuRequest::Init() {
  hash_update_mode_ = HashUpdateMode::kDoHashUpdate;
  return true;
}

bool AddSubMenuRequest::CheckSubMenuName() {
  LOG4CXX_AUTO_TRACE(logger_);
  const char* str = NULL;

  str = (*message_)[strings::msg_params][strings::menu_name].asCharArray();
  if (!CheckSyntax(str)) {
    LOG4CXX_INFO(logger_, "Invalid subMenu name.");
    return false;
  }
  return true;
}

}  // namespace commands

}  // namespace sdl_rpc_plugin
<commit_msg>Add check for missing option parameter `menu_icon`<commit_after>/*

 Copyright (c) 2018, Ford Motor Company
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this
 list of conditions and the following disclaimer.

 Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following
 disclaimer in the documentation and/or other materials provided with the
 distribution.

 Neither the name of the Ford Motor Company nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

#include "sdl_rpc_plugin/commands/mobile/add_sub_menu_request.h"

#include "application_manager/application.h"
#include "application_manager/message_helper.h"
#include "utils/helpers.h"

namespace sdl_rpc_plugin {
using namespace application_manager;

namespace commands {

AddSubMenuRequest::AddSubMenuRequest(
    const application_manager::commands::MessageSharedPtr& message,
    ApplicationManager& application_manager,
    rpc_service::RPCService& rpc_service,
    HMICapabilities& hmi_capabilities,
    policy::PolicyHandlerInterface& policy_handler)
    : CommandRequestImpl(message,
                         application_manager,
                         rpc_service,
                         hmi_capabilities,
                         policy_handler) {}

AddSubMenuRequest::~AddSubMenuRequest() {}

void AddSubMenuRequest::Run() {
  LOG4CXX_AUTO_TRACE(logger_);

  ApplicationSharedPtr app = application_manager_.application(connection_key());

  if (!app) {
    LOG4CXX_ERROR(logger_, "NULL pointer");
    SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
    return;
  }

  smart_objects::SmartObject received_msg_params =
      (*message_)[strings::msg_params];
  mobile_apis::Result::eType verification_result =
      mobile_apis::Result::INVALID_ENUM;

  if (received_msg_params.keyExists(strings::menu_icon)) {
    verification_result = MessageHelper::VerifyImage(
        received_msg_params[strings::menu_icon], app, application_manager_);

    if (mobile_apis::Result::INVALID_DATA == verification_result) {
      LOG4CXX_ERROR(
          logger_, "MessageHelper::VerifyImage return " << verification_result);
      SendResponse(false, verification_result);
      return;
    }
  }

  const int32_t menu_id = received_msg_params[strings::menu_id].asInt();
  if (app->FindSubMenu(menu_id)) {
    LOG4CXX_ERROR(logger_, "Menu with id " << menu_id << " is not found.");
    SendResponse(false, mobile_apis::Result::INVALID_ID);
    return;
  }

  const std::string& menu_name =
      received_msg_params[strings::menu_name].asString();

  if (app->IsSubMenuNameAlreadyExist(menu_name)) {
    LOG4CXX_ERROR(logger_, "Menu name " << menu_name << " is duplicated.");
    SendResponse(false, mobile_apis::Result::DUPLICATE_NAME);
    return;
  }

  if (!CheckSubMenuName()) {
    LOG4CXX_ERROR(logger_, "Sub-menu name is not valid.");
    SendResponse(false, mobile_apis::Result::INVALID_DATA);
    return;
  }

  smart_objects::SmartObject msg_params =
      smart_objects::SmartObject(smart_objects::SmartType_Map);

  msg_params[strings::menu_id] = received_msg_params[strings::menu_id];
  if (received_msg_params.keyExists(strings::position)) {
    msg_params[strings::menu_params][strings::position] =
        received_msg_params[strings::position];
  }
  if (received_msg_params.keyExists(strings::menu_icon)) {
    msg_params[strings::menu_icon] = received_msg_params[strings::menu_icon];
  }
  msg_params[strings::menu_params][strings::menu_name] =
      received_msg_params[strings::menu_name];
  msg_params[strings::app_id] = app->app_id();

  StartAwaitForInterface(HmiInterfaces::HMI_INTERFACE_UI);
  SendHMIRequest(hmi_apis::FunctionID::UI_AddSubMenu, &msg_params, true);
}

void AddSubMenuRequest::on_event(const event_engine::Event& event) {
  LOG4CXX_AUTO_TRACE(logger_);
  const smart_objects::SmartObject& message = event.smart_object();

  switch (event.id()) {
    case hmi_apis::FunctionID::UI_AddSubMenu: {
      EndAwaitForInterface(HmiInterfaces::HMI_INTERFACE_UI);
      hmi_apis::Common_Result::eType result_code =
          static_cast<hmi_apis::Common_Result::eType>(
              message[strings::params][hmi_response::code].asInt());
      std::string response_info;
      GetInfo(message, response_info);
      const bool result = PrepareResultForMobileResponse(
          result_code, HmiInterfaces::HMI_INTERFACE_UI);

      ApplicationSharedPtr application =
          application_manager_.application(connection_key());

      if (!application) {
        LOG4CXX_ERROR(logger_, "NULL pointer");
        return;
      }

      if (result) {
        application->AddSubMenu(
            (*message_)[strings::msg_params][strings::menu_id].asInt(),
            (*message_)[strings::msg_params]);
      }
      SendResponse(result,
                   MessageHelper::HMIToMobileResult(result_code),
                   response_info.empty() ? NULL : response_info.c_str(),
                   &(message[strings::msg_params]));
      break;
    }
    default: {
      LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
      return;
    }
  }
}

bool AddSubMenuRequest::Init() {
  hash_update_mode_ = HashUpdateMode::kDoHashUpdate;
  return true;
}

bool AddSubMenuRequest::CheckSubMenuName() {
  LOG4CXX_AUTO_TRACE(logger_);
  const char* str = NULL;

  str = (*message_)[strings::msg_params][strings::menu_name].asCharArray();
  if (!CheckSyntax(str)) {
    LOG4CXX_INFO(logger_, "Invalid subMenu name.");
    return false;
  }
  return true;
}

}  // namespace commands

}  // namespace sdl_rpc_plugin
<|endoftext|>


<commit_before>#pragma once

#include <agency/detail/config.hpp>
#include <agency/new_executor_traits.hpp>

namespace agency
{
namespace detail
{
namespace new_executor_traits_detail
{
namespace multi_agent_execute_with_shared_inits_returning_user_specified_container_implementation_strategies
{

struct use_multi_agent_execute_with_shared_inits_returning_user_specified_container_member_function {};

// XXX struct use_multi_agent_execute_with_shared_inits_returning_user_specified_container_member_function {};

struct use_multi_agent_execute_returning_user_specified_container {};

template<class Container, class Executor, class Function, class T1, class... Types>
using select_multi_agent_execute_with_shared_inits_returning_user_specified_container_implementation =
  typename std::conditional<
    has_multi_agent_execute_with_shared_inits_returning_user_specified_container<
      Container,
      Executor,
      Function,
      T1,
      Types...
    >::value,
    use_multi_agent_execute_with_shared_inits_returning_user_specified_container_member_function,
    use_multi_agent_execute_returning_user_specified_container
  >::type;

template<class Container, class Executor, class Function, class T1, class... Types>
Container multi_agent_execute_with_shared_inits_returning_user_specified_container(use_multi_agent_execute_with_shared_inits_returning_user_specified_container_member_function,
                                                                                Executor& ex,
                                                                                Function f,
                                                                                typename new_executor_traits<Executor>::shape_type shape,
                                                                                T1&& outer_shared_init, Types&&... inner_shared_inits)
{
  return ex.template execute<Container>(f, std::forward<T1>(outer_shared_init), std::forward<Types>(inner_shared_inits)...);
} // end multi_agent_execute_with_shared_inits_returning_user_specified_container()

template<class Result, class Function, class Shape, class TupleOfContainers>
struct multi_agent_execute_with_shared_inits_functor
{
  mutable Function f;
  Shape shape;
  TupleOfContainers& shared_arg_containers;

  template<size_t depth, class AgentIndex>
  __AGENCY_ANNOTATION
  size_t rank_in_group(const AgentIndex& idx) const
  {
    // to compute the rank of an index at a particular depth,
    // first prepend 0 (1) to idx (shape) to represent an index of the root group (it has none otherwise)
    // XXX seems like index_cast() should just do the right thing for empty indices
    //     it would correspond to a single-agent task
    auto augmented_idx   = detail::tuple_prepend(detail::wrap_scalar(idx), size_t{0});
    auto augmented_shape = detail::tuple_prepend(detail::wrap_scalar(shape), size_t{1});

    // take the first depth+1 (plus one because we prepended 1) indices of the index & shape and do an index_cast to size_t
    return detail::index_cast<size_t>(detail::tuple_take<depth+1>(augmented_idx),
                                      detail::tuple_take<depth+1>(augmented_shape),
                                      detail::shape_size(detail::tuple_take<depth+1>(augmented_shape)));
  }

  template<size_t... ContainerIndices, class AgentIndex>
  __AGENCY_ANNOTATION
  Result impl(detail::index_sequence<ContainerIndices...>, AgentIndex&& agent_idx) const
  {
    return f(std::forward<AgentIndex>(agent_idx),                                                      // pass the agent index
      std::get<ContainerIndices>(shared_arg_containers)[rank_in_group<ContainerIndices>(agent_idx)]... // pass the arguments coming in from shared parameters
    );
  }

  template<class Index>
  __AGENCY_ANNOTATION
  Result operator()(Index&& idx) const
  {
    static const size_t num_containers = std::tuple_size<TupleOfContainers>::value;
    return impl(detail::make_index_sequence<num_containers>(), std::forward<Index>(idx));
  }
};

template<class Result, class Function, class Shape, class TupleOfContainers>
__AGENCY_ANNOTATION
multi_agent_execute_with_shared_inits_functor<Result,Function,Shape,TupleOfContainers>
  make_multi_agent_execute_with_shared_inits_functor(Function f, Shape shape, TupleOfContainers& tuple_of_containers)
{
  return multi_agent_execute_with_shared_inits_functor<Result,Function,Shape,TupleOfContainers>{f,shape,tuple_of_containers};
}

template<class Container, class Executor, class Function, class... Types>
Container multi_agent_execute_with_shared_inits_returning_user_specified_container(use_multi_agent_execute_returning_user_specified_container,
                                                                                Executor& ex,
                                                                                Function f,
                                                                                typename new_executor_traits<Executor>::shape_type shape,
                                                                                Types&&... shared_inits)
{
  // create a tuple of containers holding a shared parameter for each group
  auto shared_param_containers_tuple = make_tuple_of_shared_parameter_containers(ex, shape, std::forward<Types>(shared_inits)...);

  using index_type = typename new_executor_traits<Executor>::index_type;
  using result_type = typename std::result_of<
    Function(
      index_type,
      typename std::decay<Types>::type&...
    )
  >::type;

  // wrap f with a functor to map container elements to shared parameters
  auto g = make_multi_agent_execute_with_shared_inits_functor<result_type>(f, shape, shared_param_containers_tuple);

  return new_executor_traits<Executor>::template execute<Container>(ex, g, shape);
} // end multi_agent_execute_with_shared_inits_returning_user_specified_container()

} // end multi_agent_execute_with_shared_inits_returning_user_specified_container_implementation_strategies
} // end new_executor_traits_detail
} // end detail

template<class Executor>
  template<class Container, class Function, class T1, class... Types,
           class Enable>
Container new_executor_traits<Executor>
  ::execute(typename new_executor_traits<Executor>::executor_type& ex,
            Function f,
            typename new_executor_traits<Executor>::shape_type shape,
            T1&& outer_shared_init, Types&&... inner_shared_inits)
{
  namespace ns = detail::new_executor_traits_detail::multi_agent_execute_with_shared_inits_returning_user_specified_container_implementation_strategies;

  using implementation_strategy = ns::select_multi_agent_execute_with_shared_inits_returning_user_specified_container_implementation<
    Container,
    Executor,
    Function,
    T1&&, Types&&...
  >;

  return ns::multi_agent_execute_with_shared_inits_returning_user_specified_container<Container>(implementation_strategy(), ex, f, shape, std::forward<T1>(outer_shared_init), std::forward<Types>(inner_shared_inits)...);
} // end new_executor_traits::execute()

} // end agency

<commit_msg>Add missing parameter to function call<commit_after>#pragma once

#include <agency/detail/config.hpp>
#include <agency/new_executor_traits.hpp>

namespace agency
{
namespace detail
{
namespace new_executor_traits_detail
{
namespace multi_agent_execute_with_shared_inits_returning_user_specified_container_implementation_strategies
{

struct use_multi_agent_execute_with_shared_inits_returning_user_specified_container_member_function {};

// XXX struct use_multi_agent_execute_with_shared_inits_returning_user_specified_container_member_function {};

struct use_multi_agent_execute_returning_user_specified_container {};

template<class Container, class Executor, class Function, class T1, class... Types>
using select_multi_agent_execute_with_shared_inits_returning_user_specified_container_implementation =
  typename std::conditional<
    has_multi_agent_execute_with_shared_inits_returning_user_specified_container<
      Container,
      Executor,
      Function,
      T1,
      Types...
    >::value,
    use_multi_agent_execute_with_shared_inits_returning_user_specified_container_member_function,
    use_multi_agent_execute_returning_user_specified_container
  >::type;

template<class Container, class Executor, class Function, class T1, class... Types>
Container multi_agent_execute_with_shared_inits_returning_user_specified_container(use_multi_agent_execute_with_shared_inits_returning_user_specified_container_member_function,
                                                                                Executor& ex,
                                                                                Function f,
                                                                                typename new_executor_traits<Executor>::shape_type shape,
                                                                                T1&& outer_shared_init, Types&&... inner_shared_inits)
{
  return ex.template execute<Container>(f, shape, std::forward<T1>(outer_shared_init), std::forward<Types>(inner_shared_inits)...);
} // end multi_agent_execute_with_shared_inits_returning_user_specified_container()

template<class Result, class Function, class Shape, class TupleOfContainers>
struct multi_agent_execute_with_shared_inits_functor
{
  mutable Function f;
  Shape shape;
  TupleOfContainers& shared_arg_containers;

  template<size_t depth, class AgentIndex>
  __AGENCY_ANNOTATION
  size_t rank_in_group(const AgentIndex& idx) const
  {
    // to compute the rank of an index at a particular depth,
    // first prepend 0 (1) to idx (shape) to represent an index of the root group (it has none otherwise)
    // XXX seems like index_cast() should just do the right thing for empty indices
    //     it would correspond to a single-agent task
    auto augmented_idx   = detail::tuple_prepend(detail::wrap_scalar(idx), size_t{0});
    auto augmented_shape = detail::tuple_prepend(detail::wrap_scalar(shape), size_t{1});

    // take the first depth+1 (plus one because we prepended 1) indices of the index & shape and do an index_cast to size_t
    return detail::index_cast<size_t>(detail::tuple_take<depth+1>(augmented_idx),
                                      detail::tuple_take<depth+1>(augmented_shape),
                                      detail::shape_size(detail::tuple_take<depth+1>(augmented_shape)));
  }

  template<size_t... ContainerIndices, class AgentIndex>
  __AGENCY_ANNOTATION
  Result impl(detail::index_sequence<ContainerIndices...>, AgentIndex&& agent_idx) const
  {
    return f(std::forward<AgentIndex>(agent_idx),                                                      // pass the agent index
      std::get<ContainerIndices>(shared_arg_containers)[rank_in_group<ContainerIndices>(agent_idx)]... // pass the arguments coming in from shared parameters
    );
  }

  template<class Index>
  __AGENCY_ANNOTATION
  Result operator()(Index&& idx) const
  {
    static const size_t num_containers = std::tuple_size<TupleOfContainers>::value;
    return impl(detail::make_index_sequence<num_containers>(), std::forward<Index>(idx));
  }
};

template<class Result, class Function, class Shape, class TupleOfContainers>
__AGENCY_ANNOTATION
multi_agent_execute_with_shared_inits_functor<Result,Function,Shape,TupleOfContainers>
  make_multi_agent_execute_with_shared_inits_functor(Function f, Shape shape, TupleOfContainers& tuple_of_containers)
{
  return multi_agent_execute_with_shared_inits_functor<Result,Function,Shape,TupleOfContainers>{f,shape,tuple_of_containers};
}

template<class Container, class Executor, class Function, class... Types>
Container multi_agent_execute_with_shared_inits_returning_user_specified_container(use_multi_agent_execute_returning_user_specified_container,
                                                                                Executor& ex,
                                                                                Function f,
                                                                                typename new_executor_traits<Executor>::shape_type shape,
                                                                                Types&&... shared_inits)
{
  // create a tuple of containers holding a shared parameter for each group
  auto shared_param_containers_tuple = make_tuple_of_shared_parameter_containers(ex, shape, std::forward<Types>(shared_inits)...);

  using index_type = typename new_executor_traits<Executor>::index_type;
  using result_type = typename std::result_of<
    Function(
      index_type,
      typename std::decay<Types>::type&...
    )
  >::type;

  // wrap f with a functor to map container elements to shared parameters
  auto g = make_multi_agent_execute_with_shared_inits_functor<result_type>(f, shape, shared_param_containers_tuple);

  return new_executor_traits<Executor>::template execute<Container>(ex, g, shape);
} // end multi_agent_execute_with_shared_inits_returning_user_specified_container()

} // end multi_agent_execute_with_shared_inits_returning_user_specified_container_implementation_strategies
} // end new_executor_traits_detail
} // end detail

template<class Executor>
  template<class Container, class Function, class T1, class... Types,
           class Enable>
Container new_executor_traits<Executor>
  ::execute(typename new_executor_traits<Executor>::executor_type& ex,
            Function f,
            typename new_executor_traits<Executor>::shape_type shape,
            T1&& outer_shared_init, Types&&... inner_shared_inits)
{
  namespace ns = detail::new_executor_traits_detail::multi_agent_execute_with_shared_inits_returning_user_specified_container_implementation_strategies;

  using implementation_strategy = ns::select_multi_agent_execute_with_shared_inits_returning_user_specified_container_implementation<
    Container,
    Executor,
    Function,
    T1&&, Types&&...
  >;

  return ns::multi_agent_execute_with_shared_inits_returning_user_specified_container<Container>(implementation_strategy(), ex, f, shape, std::forward<T1>(outer_shared_init), std::forward<Types>(inner_shared_inits)...);
} // end new_executor_traits::execute()

} // end agency

<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef CONTEXT_H
#define CONTEXT_H

#include <string>
#include <map>
#include <vector>

#include "Types.hpp"

#include "AssemblyFileWriter.hpp"

namespace eddic {

enum PositionType {
    STACK,
    GLOBAL
};

class Position {
    private:
        const PositionType m_type;
        const int m_offset;
        const std::string m_name;

    public:
        Position() : m_type(STACK), m_offset(0), m_name("") {} //TODO Delete that later, just here for compilation
        Position(PositionType type, int offset) : m_type(type), m_offset(offset), m_name("") {}
        Position(PositionType type, std::string name) : m_type(type), m_offset(0), m_name(name) {}

        bool isStack(){
            return m_type == STACK;
        }

        bool isGlobal(){
            return m_type == GLOBAL;
        }

        int offset(){
            return m_offset;
        }

        std::string name(){
            return m_name;
        }
};

class Variable {
    private:
        const std::string m_name;
        const Type m_type;
        const int m_index;
        Position position;

    public:
        Variable(const std::string& name, Type type, int index) : m_name(name), m_type(type), m_index(index) {}
        std::string name() const  {
            return m_name;
        }
        int index() const {
            return m_index;
        }
        Type type() const {
            return m_type;
        }
};

class Context {
    private:
        static std::vector<Context*> contexts;
        static unsigned int currentVariable;

        std::map<std::string, Variable*> variables;
        Context* m_parent;

    public:
        Context() : m_parent(NULL) {
            contexts.push_back(this);
        }
        Context(Context* parent) : m_parent(parent) {
            contexts.push_back(this);
        }
        ~Context();

        bool exists(const std::string& variable) const;
        unsigned int index(const std::string& variable) const;
        Variable* create(const std::string& variable, Type type);
        Variable* find(const std::string& variable);
        void write(AssemblyFileWriter& writer);

        Context* parent() {
            return m_parent;
        }

        static void writeAll(AssemblyFileWriter& writer);
        static void cleanup();
};

//TODO Rename to Context when finished the implementation
class TempContext {
    private:
        static std::vector<TempContext*> contexts;

        std::map<std::string, Variable*> variables;
        TempContext* m_parent;

    public:
       virtual void addVariable(const std::string a, Type type);
       virtual bool exists(const std::string& a) const;
       virtual Variable* getVariable(std::string& variable) const;

        TempContext* parent() const  {
            return m_parent;
        }
};

class FunctionContext : public TempContext {

};

class GlobalContext : public TempContext {

};

class BlockContext : public TempContext {
    private:
        FunctionContext* m_functionContext;

    public:
        BlockContext(FunctionContext* functionContext) : m_functionContext(functionContext) {}
};

} //end of eddic

#endif
<commit_msg>Finish interfaces of the different variables context<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef CONTEXT_H
#define CONTEXT_H

#include <string>
#include <map>
#include <vector>

#include <unordered_map>
#include <unordered_set>

#include "Types.hpp"

#include "AssemblyFileWriter.hpp"

namespace eddic {

enum PositionType {
    STACK,
    GLOBAL
};

class Position {
    private:
        const PositionType m_type;
        const int m_offset;
        const std::string m_name;

    public:
        Position() : m_type(STACK), m_offset(0), m_name("") {} //TODO Delete that later, just here for compilation
        Position(PositionType type, int offset) : m_type(type), m_offset(offset), m_name("") {}
        Position(PositionType type, std::string name) : m_type(type), m_offset(0), m_name(name) {}

        bool isStack(){
            return m_type == STACK;
        }

        bool isGlobal(){
            return m_type == GLOBAL;
        }

        int offset(){
            return m_offset;
        }

        std::string name(){
            return m_name;
        }
};

class Variable {
    private:
        const std::string m_name;
        const Type m_type;
        const int m_index;
        Position position;

    public:
        Variable(const std::string& name, Type type, int index) : m_name(name), m_type(type), m_index(index) {}
        std::string name() const  {
            return m_name;
        }
        int index() const {
            return m_index;
        }
        Type type() const {
            return m_type;
        }
};

class Context {
    private:
        static std::vector<Context*> contexts;
        static unsigned int currentVariable;

        std::map<std::string, Variable*> variables;
        Context* m_parent;

    public:
        Context() : m_parent(NULL) {
            contexts.push_back(this);
        }
        Context(Context* parent) : m_parent(parent) {
            contexts.push_back(this);
        }
        ~Context();

        bool exists(const std::string& variable) const;
        unsigned int index(const std::string& variable) const;
        Variable* create(const std::string& variable, Type type);
        Variable* find(const std::string& variable);
        void write(AssemblyFileWriter& writer);

        Context* parent() {
            return m_parent;
        }

        static void writeAll(AssemblyFileWriter& writer);
        static void cleanup();
};

//TODO Rename to Context when finished the implementation
class TempContext {
    private:
        TempContext* m_parent;

        static std::vector<TempContext*> contexts;

    protected:
        std::unordered_map<std::string, Variable*> m_stored;
        std::unordered_set<std::string> m_visibles;

    public:
        TempContext(TempContext* parent) : m_parent(parent) {
            contexts.push_back(this);
        }
        virtual ~TempContext();

        virtual void addVariable(const std::string a, Type type);
        virtual bool exists(const std::string& a) const;
        virtual Variable* getVariable(std::string& variable) const;

        TempContext* parent() const  {
            return m_parent;
        }
};

class GlobalContext : public TempContext {
    public:
        GlobalContext() : TempContext(NULL) {}
};

class FunctionContext : public TempContext {
    public:
        FunctionContext(TempContext* parent) : TempContext(parent) {}
};

class BlockContext : public TempContext {
    private:
        FunctionContext* m_functionContext;

    public:
        BlockContext(TempContext* parent, FunctionContext* functionContext) : TempContext(parent), m_functionContext(functionContext) {}

        void addVariable(const std::string a, Type type);
};

} //end of eddic

#endif
<|endoftext|>


<commit_before>#pragma once
#include <cstdio>
#include <cassert>

#ifndef __CUDACC__
#define __host__
#define __device__
#define __global__
#endif

namespace gassert
{

template<int N>
struct static_string
{
private:
  char str_[N+1];
  int size_;
public:

  __host__ __device__
  static_string(const char *str)
  {
    size_ = 0;
    while (str[size_] != 0 && size_ <= N)
    {
      str_[size_] = str[size_];
      ++size_;
    }
    str_[size_] = 0;
  }

  __host__ __device__
  static_string(const char *str, int count)
  {
    size_ = 0;
    while (str[size_] != 0 && size_ <= N && count > 0)
    {
      str_[size_] = str[size_];
      ++size_;
      count--;
    }
    str_[size_] = 0;
  }

  __host__ __device__
  char const* c_str() const
  {
    return str_;
  }
  __host__ __device__
  int size() const
  {
    return size_;
  }
}; // struct static_string

  __host__ __device__
bool __isalnum(char c)
{
  bool ret = false;
  ret |= c >= '0' && c <= '9';
  ret |= c >= 'a' && c <= 'z';
  ret |= c >= 'A' && c <= 'Z';
  return ret;
}

template<class LHS, class RHS>
struct expression
{
private:
  char const *filename;
  int const linenumber;
  char const *expr;
  LHS const lhs_value;
  RHS const rhs_value;
  bool const result;
  const char *op;
  bool expected;

  int  lhs_expr_begin, lhs_expr_end;
  int  rhs_expr_begin, rhs_expr_end;

public:
  __host__ __device__
  expression(char const *filename, int linenumber, char const *expr,
             LHS const &lhs, RHS const &rhs, bool result,
             const char * op)
      : filename(filename), linenumber(linenumber), expr(expr), lhs_value(lhs),
        rhs_value(rhs), result(result),  op(op), expected(true)
  {
    int displ = 0;
    while (expr[displ] && !__isalnum(expr[displ]))
      ++displ;
    lhs_expr_begin = displ;
    while (expr[displ] && __isalnum(expr[displ]))
      ++displ;
    lhs_expr_end = displ;

    while (expr[displ] && !__isalnum(expr[displ]))
      ++displ;
    rhs_expr_begin = displ;
    while (expr[displ] && __isalnum(expr[displ]))
      ++displ;
    rhs_expr_end = displ;
  }

  __host__ __device__
  operator bool() const
  {
    return expected == result;
  }

  __host__ __device__
  void set_expected(bool b) { expected = b; }

  //-----------------------------------
  // Specialize value printing here
  //-----------------------------------

  __host__ __device__
  void print_value(int val) const
  {
    printf("%d",val);
  }
  __host__ __device__
  void print_value(float val)
  {
    printf("%f",val);
  }

  __host__ __device__
  void print(const char *what) const
  {
#ifndef GASSERT_NO_COLOURS
#define GASSERT_RESET      "\033[0m"
#define GASSERT_BOLDRED    "\033[1m\033[31m"
#define GASSERT_GREEN      "\033[32m"
#define GASSERT_GREY       "\033[90m"
#define GASSERT_BOLDBLACK  "\033[1m\033[30m"
#else
#define GASSERT_RESET      ""
#define GASSERT_BOLDRED    ""
#define GASSERT_GREEN      ""
#define GASSERT_GREY       ""
#define GASSERT_BOLDBLACK  ""
#endif

    printf(GASSERT_BOLDBLACK "\n%s:%d "
           GASSERT_BOLDRED "[FAILED]" GASSERT_RESET "\n",
           filename, linenumber);
    const int N = 16;
    typedef static_string<N> expr_t;
    expr_t lhs(expr+lhs_expr_begin, lhs_expr_end-lhs_expr_begin);
    expr_t rhs(expr+rhs_expr_begin, rhs_expr_end-rhs_expr_begin);
    printf(GASSERT_GREY "    %s(", what);
    printf("%s %s %s", lhs.c_str(), op, rhs.c_str());
    printf(")" GASSERT_RESET "\n");
    printf("with expansion:\n");

    printf(GASSERT_GREEN "    %s(", (expected ? "" : "!"));
    print_value(lhs_value);
    printf(" %s ", op);
    print_value(rhs_value);
    printf(")" GASSERT_RESET);
    printf("\n\n");

#undef GASSERT_RESET
#undef GASSERT_BOLDRED
#undef GASSERT_GREEN
#undef GASSERT_GREY
#undef GASSERT_BOLDBLACK
  }
};

struct eval;

template <class LHS>
struct comparator
{
private:
  char const *filename;
  int const line_number;
  char const *expr;
  LHS const lhs;

public:

  __host__ __device__
  comparator(char const *filename, int const line_number, char const *expr,
             const LHS &lhs)
      : filename(filename), line_number(line_number), expr(expr), lhs(lhs)
  {
  }

private:

  template<class RHS>
  __host__ __device__
  expression<LHS,RHS> construct_expression(RHS const &rhs,
                                           bool result,
                                           const char *op)
  {
    return expression<LHS, RHS>(filename, line_number, expr, lhs, rhs, result,
                                op);
  }

public:

  //  operator==
  template <class RHS>
  __host__ __device__
  expression<LHS, RHS> operator==(RHS const &rhs)
  {
    return construct_expression(rhs, lhs == rhs, "==");
  }

  //  operator!=
  template <class RHS>
  __host__ __device__
  expression<LHS, RHS> operator!=(RHS const &rhs)
  {
    return construct_expression(rhs, lhs != rhs, "!=");
  }

  //  operator>=
  template<class RHS>
  __host__ __device__
  expression<LHS,RHS> operator>=(RHS const &rhs)
  {
    return construct_expression(rhs, lhs >= rhs, ">=");
  }

  //  operator>
  template<class RHS>
  __host__ __device__
  expression<LHS,RHS> operator>(RHS const &rhs)
  {
    return construct_expression(rhs, lhs > rhs, ">");
  }

  //  operator<=
  template<class RHS>
  __host__ __device__
  expression<LHS,RHS> operator<=(RHS const &rhs)
  {
    return construct_expression(rhs, lhs <= rhs, "<=");
  }

  //  operator<
  template<class RHS>
  __host__ __device__
  expression<LHS,RHS> operator<(RHS const &rhs)
  {
    return construct_expression(rhs, lhs < rhs, "<");
  }
}; // struct comparator

struct eval
{
private:
  const char *filename;
  const int linenumber;
  const char *expr;

public:
  __host__ __device__
  eval(const char *filename, int linenumber, const char *expr)
      : filename(filename), linenumber(linenumber), expr(expr)
  {}

  template <class LHS>
  __host__ __device__
  comparator<LHS> operator->*(LHS const &lhs)
  {
    return comparator<LHS>(filename, linenumber, expr, lhs);
  }
}; // eval

void __host__ __device__
trap()
{
  assert(0);
}

template<class LHS, class RHS>
void __host__ __device__
require(expression<LHS,RHS> expr)
{
  if (!expr)
  {
    expr.print("ASSERT");
    trap();
  }
}

template<class LHS, class RHS>
__host__ __device__
void require_false(expression<LHS,RHS> expr)
{
  expr.set_expected(false);
  if (!expr)
  {
    expr.print("ASSERT_FALSE");
    trap();
  }
}

template <class LHS, class RHS>
void __host__ __device__
check(expression<LHS, RHS> expr)
{
  if (!expr)
  {
    expr.print("CHECK");
  }
}

template<class LHS, class RHS>
void __host__ __device__
check_false(expression<LHS,RHS> expr)
{
  expr.set_expected(false);
  if (!expr)
  {
    expr.print("CHECK_FALSE");
  }
}

} // namespace gassert
#define REQUIRE(expr) (gassert::require(gassert::eval(__FILE__, __LINE__, #expr)->* expr))
#define REQUIRE_FALSE(expr) (gassert::require_false(gassert::eval(__FILE__, __LINE__, #expr)->* expr))
#define CHECK(expr) (gassert::check(gassert::eval(__FILE__, __LINE__, #expr)->* expr))
#define CHECK_FALSE(expr) (gassert::check_false(gassert::eval(__FILE__, __LINE__, #expr)->* expr))

<commit_msg>[fix] add const qualified<commit_after>#pragma once
#include <cstdio>
#include <cassert>

#ifndef __CUDACC__
#define __host__
#define __device__
#define __global__
#endif

namespace gassert
{

template<int N>
struct static_string
{
private:
  char str_[N+1];
  int size_;
public:

  __host__ __device__
  static_string(const char *str)
  {
    size_ = 0;
    while (str[size_] != 0 && size_ <= N)
    {
      str_[size_] = str[size_];
      ++size_;
    }
    str_[size_] = 0;
  }

  __host__ __device__
  static_string(const char *str, int count)
  {
    size_ = 0;
    while (str[size_] != 0 && size_ <= N && count > 0)
    {
      str_[size_] = str[size_];
      ++size_;
      count--;
    }
    str_[size_] = 0;
  }

  __host__ __device__
  char const* c_str() const
  {
    return str_;
  }
  __host__ __device__
  int size() const
  {
    return size_;
  }
}; // struct static_string

  __host__ __device__
bool __isalnum(char c)
{
  bool ret = false;
  ret |= c >= '0' && c <= '9';
  ret |= c >= 'a' && c <= 'z';
  ret |= c >= 'A' && c <= 'Z';
  return ret;
}

template<class LHS, class RHS>
struct expression
{
private:
  char const *filename;
  int const linenumber;
  char const *expr;
  LHS const lhs_value;
  RHS const rhs_value;
  bool const result;
  const char *op;
  bool expected;

  int  lhs_expr_begin, lhs_expr_end;
  int  rhs_expr_begin, rhs_expr_end;

public:
  __host__ __device__
  expression(char const *filename, int linenumber, char const *expr,
             LHS const &lhs, RHS const &rhs, bool result,
             const char * op)
      : filename(filename), linenumber(linenumber), expr(expr), lhs_value(lhs),
        rhs_value(rhs), result(result),  op(op), expected(true)
  {
    int displ = 0;
    while (expr[displ] && !__isalnum(expr[displ]))
      ++displ;
    lhs_expr_begin = displ;
    while (expr[displ] && __isalnum(expr[displ]))
      ++displ;
    lhs_expr_end = displ;

    while (expr[displ] && !__isalnum(expr[displ]))
      ++displ;
    rhs_expr_begin = displ;
    while (expr[displ] && __isalnum(expr[displ]))
      ++displ;
    rhs_expr_end = displ;
  }

  __host__ __device__
  operator bool() const
  {
    return expected == result;
  }

  __host__ __device__
  void set_expected(bool b) { expected = b; }

  //-----------------------------------
  // Specialize value printing here
  //-----------------------------------

  __host__ __device__
  void print_value(int val) const
  {
    printf("%d",val);
  }
  __host__ __device__
  void print_value(float val) const
  {
    printf("%f",val);
  }

  __host__ __device__
  void print(const char *what) const
  {
#ifndef GASSERT_NO_COLOURS
#define GASSERT_RESET      "\033[0m"
#define GASSERT_BOLDRED    "\033[1m\033[31m"
#define GASSERT_GREEN      "\033[32m"
#define GASSERT_GREY       "\033[90m"
#define GASSERT_BOLDBLACK  "\033[1m\033[30m"
#else
#define GASSERT_RESET      ""
#define GASSERT_BOLDRED    ""
#define GASSERT_GREEN      ""
#define GASSERT_GREY       ""
#define GASSERT_BOLDBLACK  ""
#endif

    printf(GASSERT_BOLDBLACK "\n%s:%d "
           GASSERT_BOLDRED "[FAILED]" GASSERT_RESET "\n",
           filename, linenumber);
    const int N = 16;
    typedef static_string<N> expr_t;
    expr_t lhs(expr+lhs_expr_begin, lhs_expr_end-lhs_expr_begin);
    expr_t rhs(expr+rhs_expr_begin, rhs_expr_end-rhs_expr_begin);
    printf(GASSERT_GREY "    %s(", what);
    printf("%s %s %s", lhs.c_str(), op, rhs.c_str());
    printf(")" GASSERT_RESET "\n");
    printf("with expansion:\n");

    printf(GASSERT_GREEN "    %s(", (expected ? "" : "!"));
    print_value(lhs_value);
    printf(" %s ", op);
    print_value(rhs_value);
    printf(")" GASSERT_RESET);
    printf("\n\n");

#undef GASSERT_RESET
#undef GASSERT_BOLDRED
#undef GASSERT_GREEN
#undef GASSERT_GREY
#undef GASSERT_BOLDBLACK
  }
};

struct eval;

template <class LHS>
struct comparator
{
private:
  char const *filename;
  int const line_number;
  char const *expr;
  LHS const lhs;

public:

  __host__ __device__
  comparator(char const *filename, int const line_number, char const *expr,
             const LHS &lhs)
      : filename(filename), line_number(line_number), expr(expr), lhs(lhs)
  {
  }

private:

  template<class RHS>
  __host__ __device__
  expression<LHS,RHS> construct_expression(RHS const &rhs,
                                           bool result,
                                           const char *op)
  {
    return expression<LHS, RHS>(filename, line_number, expr, lhs, rhs, result,
                                op);
  }

public:

  //  operator==
  template <class RHS>
  __host__ __device__
  expression<LHS, RHS> operator==(RHS const &rhs)
  {
    return construct_expression(rhs, lhs == rhs, "==");
  }

  //  operator!=
  template <class RHS>
  __host__ __device__
  expression<LHS, RHS> operator!=(RHS const &rhs)
  {
    return construct_expression(rhs, lhs != rhs, "!=");
  }

  //  operator>=
  template<class RHS>
  __host__ __device__
  expression<LHS,RHS> operator>=(RHS const &rhs)
  {
    return construct_expression(rhs, lhs >= rhs, ">=");
  }

  //  operator>
  template<class RHS>
  __host__ __device__
  expression<LHS,RHS> operator>(RHS const &rhs)
  {
    return construct_expression(rhs, lhs > rhs, ">");
  }

  //  operator<=
  template<class RHS>
  __host__ __device__
  expression<LHS,RHS> operator<=(RHS const &rhs)
  {
    return construct_expression(rhs, lhs <= rhs, "<=");
  }

  //  operator<
  template<class RHS>
  __host__ __device__
  expression<LHS,RHS> operator<(RHS const &rhs)
  {
    return construct_expression(rhs, lhs < rhs, "<");
  }
}; // struct comparator

struct eval
{
private:
  const char *filename;
  const int linenumber;
  const char *expr;

public:
  __host__ __device__
  eval(const char *filename, int linenumber, const char *expr)
      : filename(filename), linenumber(linenumber), expr(expr)
  {}

  template <class LHS>
  __host__ __device__
  comparator<LHS> operator->*(LHS const &lhs)
  {
    return comparator<LHS>(filename, linenumber, expr, lhs);
  }
}; // eval

void __host__ __device__
trap()
{
  assert(0);
}

template<class LHS, class RHS>
void __host__ __device__
require(expression<LHS,RHS> expr)
{
  if (!expr)
  {
    expr.print("ASSERT");
    trap();
  }
}

template<class LHS, class RHS>
__host__ __device__
void require_false(expression<LHS,RHS> expr)
{
  expr.set_expected(false);
  if (!expr)
  {
    expr.print("ASSERT_FALSE");
    trap();
  }
}

template <class LHS, class RHS>
void __host__ __device__
check(expression<LHS, RHS> expr)
{
  if (!expr)
  {
    expr.print("CHECK");
  }
}

template<class LHS, class RHS>
void __host__ __device__
check_false(expression<LHS,RHS> expr)
{
  expr.set_expected(false);
  if (!expr)
  {
    expr.print("CHECK_FALSE");
  }
}

} // namespace gassert
#define REQUIRE(expr) (gassert::require(gassert::eval(__FILE__, __LINE__, #expr)->* expr))
#define REQUIRE_FALSE(expr) (gassert::require_false(gassert::eval(__FILE__, __LINE__, #expr)->* expr))
#define CHECK(expr) (gassert::check(gassert::eval(__FILE__, __LINE__, #expr)->* expr))
#define CHECK_FALSE(expr) (gassert::check_false(gassert::eval(__FILE__, __LINE__, #expr)->* expr))

<|endoftext|>