<commit_before>
TGraphErrors * MakeGraphSparse(TTree * tree, const Char_t * expr="mean-fdelta:run", const Char_t * cut="isTPC&&ptype==0&&theta>0"){
  // Format of expr: Var:Error:Run
  //
  // Make a sparse draw of the variables
  //  Format of expr : Var:Error:Run
  //

  const Int_t entries =  tree->Draw(expr,cut,"goff");

  Double_t *graphX, *graphY, *graphError;

  //check whether error argument exists in expr
  if(!tree->GetV3()){
      graphX = tree->GetV2();
      graphY = tree->GetV1();
  }
  else{
      graphX = tree->GetV3();
      graphY = tree->GetV1();
      graphError = tree->GetV2();
  }

  // sort according to run number
  Int_t *index = new Int_t[entries];
  TMath::Sort(entries,graphX,index,false);

  // define arrays for the new graph
  Double_t *tempArray = new Double_t[entries];
  Double_t *xError = new Double_t[entries];
  Double_t *yError = new Double_t[entries];
  Int_t *vrun = new Int_t[entries];
  Double_t count = 0.5;

  // evaluate arrays for the new graph accroding to the run-number
  Int_t icount=0;
  tempArray[index[0]] = count;
  xError[0] = 0;
  yError[0] = 0;
  if(tree->GetV3())
      yError[index[0]] = graphError[index[0]];
  vrun[0] = graphX[index[0]];

  // loop the rest entries
  for(Int_t i=1;i<entries;i++){
      xError[i] = 0;
      yError[i] = 0;

      if(tree->GetV3())
	  yError[i] = graphError[index[i]];

      if(graphX[index[i]]==graphX[index[i-1]])
	  tempArray[index[i]] = count;
      else if((graphX[index[i]]!=graphX[index[i-1]])){
	      count++;
	      icount++;
	      tempArray[index[i]] = count;
	      vrun[icount]=graphX[index[i]];
      }
  }

  // count the number of xbins (run-wise) for the new graph
  const Int_t newNbins = int(count+0.5);
  Double_t *newBins = new Double_t[newNbins+1];
  for(Int_t i=0; i<=count+1;i++){
    newBins[i] = i;
  }

  // define and fill the new graph
  TGraphErrors *graphNew = new TGraphErrors(entries,tempArray,graphY,xError,yError);
  graphNew->GetXaxis()->Set(newNbins,newBins);

  // set the bins for the x-axis
  Char_t xName[50];
  for(Int_t i=0;i<count;i++){
    sprintf(xName,"%d",Int_t(vrun[i]));
    graphNew->GetXaxis()->SetBinLabel(i+1,xName);
  }
  graphNew->GetHistogram()->SetTitle("");

  // memory clearing
  delete [] xError;
  delete [] yError;
  delete [] tempArray;
  delete [] index;
  delete [] newBins;
  delete [] vrun;
  return graphNew;

}
//------------------------------------------------------------------------------------------------
drawPerformanceT0QATrends(const char* inFile = "trending.root", const char* runType="pp") {
  //
  //
  gROOT->Reset();
  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetLabelSize(0.04,"x");

  // open input file
  //
  TFile *file = TFile::Open(inFile);
  if(!file) return;
  file->cd();

  TTree *tree = (TTree*)file->Get("trending");
  if(!tree) return;
  int const entries = tree->GetEntries();
  cout<<"number of entries   "<<entries<<endl;
  TH1F *frame = new TH1F();

  //const float norm_runs = 8.0;
  if(entries<8)
    const float norm_runs =10.0;
  else if(entries>=8&&entries<16)
    const float norm_runs =20.0;
 else
   const float norm_runs =50.0;
  int const canvas_width = int(((entries*1.0)/norm_runs)*2000.0);
  if(entries>50){
    gStyle->SetTickLength(0.03*norm_runs/(entries*1.0),"Y");
    gStyle->SetTitleYOffset((norm_runs/(entries*1.0))*0.8);
    gStyle->SetPadLeftMargin(0.1*norm_runs/(entries*1.0));
    gStyle->SetPadRightMargin(0.1*norm_runs/(entries*1.0));
  }

  //Define ranges of you trending plots
  double resolutionMin = 10,   resolutionMax = 100;    // OR A - OR C
  double oraplusorcMin = -100, oraplusorcMax = 100;   // OR A + OR CA
  double oraMin        = -100, oraMax        = 100;   // OR A
  double orcMin        = -100, orcMax        = 100;   // OR C
  double amplMin       =0,    amplMax    =3   ;     // amplitude in each PMT
  double timeMin       ,   timeMax       ;     // amplitude in each PMT
  //-----> add ranges of your new trending plot

  TCanvas *c1  = new  TCanvas("can","can",canvas_width,500);
  c1->SetGridy(1);
  c1->SetGridx(1);
  c1->SetBottomMargin(0.17);

  /****** T0 ORA+ORC ******/
  TGraphErrors *grSum = MakeGraphSparse(tree,"tzeroOrAPlusOrC:run","");
  grSum->SetMarkerStyle(20);
  grSum->SetMarkerSize(1.0);
  grSum->SetMarkerColor(2);
  TGraphErrors *grORA = MakeGraphSparse(tree,"tzeroOrA:run","");
  grORA->SetMarkerStyle(28);
  grORA->SetMarkerSize(1.0);
  grORA->SetMarkerColor(4);
  TGraphErrors *grORC = MakeGraphSparse(tree,"tzeroOrC:run","");
  grORC->SetMarkerStyle(25);
  grORC->SetMarkerSize(1.0);
  grORC->SetMarkerColor(1);

  grSum->GetHistogram()->SetYTitle("mean [ps]");
  grSum->GetHistogram()->SetTitle("T0 ORA, ORC and (ORA+ORC)/2");
  grSum->GetHistogram()->SetMinimum(oraplusorcMin);
  grSum->GetHistogram()->SetMaximum(oraplusorcMax);
  grSum->Draw("AP");
  grORA->Draw("psame");
  grORC->Draw("psame");
  TLegend *leg = new TLegend(0.1,0.85,0.3,0.95," ","brNDC");
  leg->SetFillStyle(0); leg->SetBorderSize(0); leg->SetTextSize(0.05);leg->SetNColumns(3);leg->SetColumnSeparation(1);
  leg->AddEntry(grORA,"ORA","p");
  leg->AddEntry(grORC,"ORC","p");
  leg->AddEntry(grSum,"(ORA+ORC)/2","p");
  leg->Draw();

  grSum->GetXaxis()->LabelsOption("v");
  c1->SaveAs("meanT0OrAPlusOrC_vs_run.gif");

  /****** T0 Resolution ******/
  TGraphErrors *gr = MakeGraphSparse(tree,"resolution:run","");
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(1.0);
  gr->SetMarkerColor(2);
  gr->GetHistogram()->SetMinimum(resolutionMin);
  gr->GetHistogram()->SetMaximum(resolutionMax);
  gr->Draw("AP");
  gr->GetXaxis()->LabelsOption("v");
  gr->GetHistogram()->SetYTitle("sigma [ps]");
  gr->GetHistogram()->SetTitle("T0 resolution (ORA -ORC)/2");
  c1->SaveAs("sigmaResolutionT0_vs_run.gif");

   /****** Mean T0 OR A ******/
 /* TGraphErrors *gr = MakeGraphSparse(tree,"tzeroOrA:run","");
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(1.0);
  gr->SetMarkerColor(2);
  gr->GetHistogram()->SetYTitle("mean [ps]");
  gr->GetHistogram()->SetTitle("T0 OR A");
  gr->GetHistogram()->SetMinimum(oraMin);
  gr->GetHistogram()->SetMaximum(oraMax);
  gr->Draw("AP");
  gr->GetXaxis()->LabelsOption("v");
  c1->SaveAs("meanT0OrA_vs_run.gif");
*/

  /****** Mean T0 OR C ******/
 /* TGraphErrors *gr = MakeGraphSparse(tree,"tzeroOrC:run","");
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(1.0);
  gr->SetMarkerColor(2);
  gr->GetHistogram()->SetYTitle("mean [ps]");
  gr->GetHistogram()->SetTitle("T0 OR C");
  gr->GetHistogram()->SetMinimum(orcMin);
  gr->GetHistogram()->SetMaximum(orcMax);
  gr->Draw("AP");
  gr->GetXaxis()->LabelsOption("v");
  c1->SaveAs("meanT0OrC_vs_run.gif");
*/

  /****** Mean Amplitude in PMT ******/
  const int kNPMTs = 24;
  char name[200];

  for(int ipmt=1;ipmt<=kNPMTs; ipmt++){
    sprintf(name,"amplPMT%d:run",ipmt);
    gr = MakeGraphSparse(tree,name,"");
    gr->SetMarkerStyle(20);
    gr->SetMarkerSize(1.0);
    gr->SetMarkerColor(6);
    gr->GetHistogram()->SetYTitle("mean");
    gr->GetHistogram()->SetTitle(Form("Amplitude PMT%d",ipmt));

    int nRuns = gr->GetN();
    double *y =  gr->GetY();
	double min = y[0];
	double max = y[0];
    for(int irun =1; irun<nRuns;irun++){
      if(min > y[irun] & y[irun]>0) min = y[irun];
      if(max < y[irun]) max = y[irun];
    }
    //  amplMin = min - 2;
    //  amplMax = max + 2;

    gr->GetHistogram()->SetMinimum(amplMin);
    gr->GetHistogram()->SetMaximum(amplMax);
    gr->Draw("AP");
    gr->GetXaxis()->LabelsOption("v");
    c1->SaveAs(Form("meanAmplPMT%d_vs_run.gif",ipmt));
  }
  /****** Mean Time in PMT ******/
  for(int ipmt=1;ipmt<=kNPMTs; ipmt++){
    sprintf(name,"timePMT%d:run",ipmt);
    gr = MakeGraphSparse(tree,name,"");

    sprintf(name,"timeDelayPMT%d:run",ipmt);
    TGraphErrors *grDelay = MakeGraphSparse(tree,name,"");
    //regular run
    int nRuns = gr->GetN();
    double *y =  gr->GetY();
	double min = y[0];
	double max = y[0];
    for(int irun =1; irun<nRuns;irun++){
      if(min > y[irun] && y[irun]>0) min = y[irun];
      if(max < y[irun]) max = y[irun];
    }
    //Delay
    //   double *yDelay =  grDelay->GetY();
    //  nRuns = grDelay->GetN();
    //   for(int irun =0; irun<nRuns;irun++){
    //      if(min > yDelay[irun] && yDelay[irun]>0) min = yDelay[irun];
    //    if(max < yDelay[irun]) max = yDelay[irun];
    //  }

    timeMin = min - 2;
    timeMax = max + 2;

    gr->SetMarkerStyle(20);
    gr->SetMarkerSize(1.0);
    gr->SetMarkerColor(2);
    grDelay->SetMarkerStyle(24);
    grDelay->SetMarkerSize(1.0);
    grDelay->SetMarkerColor(1);

    gr->GetHistogram()->SetYTitle("mean [channels]");
    gr->GetHistogram()->SetTitle(Form("Time PMT%d",ipmt));
    gr->GetHistogram()->SetMinimum(timeMin);
    gr->GetHistogram()->SetMaximum(timeMax);
    gr->GetXaxis()->LabelsOption("v");
    gr->Draw("AP");
    grDelay->Draw("Psame");

    TLegend *leg = new TLegend(0.1,0.85,0.3,0.95," ","brNDC");
    leg->SetFillStyle(0); leg->SetBorderSize(0); leg->SetTextSize(0.05);leg->SetNColumns(3);
    leg->AddEntry(gr,"mean time","p");
    //leg->AddEntry(grDelay,"Time Delay OCDB","p");
    leg->Draw();

    c1->SaveAs(Form("meanTimePMT%d_vs_run.gif",ipmt));
  }

  //-----> draw your new trending plot here
}

<commit_msg>set Yaxis range for CFD time trend<commit_after>
TGraphErrors * MakeGraphSparse(TTree * tree, const Char_t * expr="mean-fdelta:run", const Char_t * cut="isTPC&&ptype==0&&theta>0"){
  // Format of expr: Var:Error:Run
  //
  // Make a sparse draw of the variables
  //  Format of expr : Var:Error:Run
  //

  const Int_t entries =  tree->Draw(expr,cut,"goff");

  Double_t *graphX, *graphY, *graphError;

  //check whether error argument exists in expr
  if(!tree->GetV3()){
      graphX = tree->GetV2();
      graphY = tree->GetV1();
  }
  else{
      graphX = tree->GetV3();
      graphY = tree->GetV1();
      graphError = tree->GetV2();
  }

  // sort according to run number
  Int_t *index = new Int_t[entries];
  TMath::Sort(entries,graphX,index,false);

  // define arrays for the new graph
  Double_t *tempArray = new Double_t[entries];
  Double_t *xError = new Double_t[entries];
  Double_t *yError = new Double_t[entries];
  Int_t *vrun = new Int_t[entries];
  Double_t count = 0.5;

  // evaluate arrays for the new graph accroding to the run-number
  Int_t icount=0;
  tempArray[index[0]] = count;
  xError[0] = 0;
  yError[0] = 0;
  if(tree->GetV3())
      yError[index[0]] = graphError[index[0]];
  vrun[0] = graphX[index[0]];

  // loop the rest entries
  for(Int_t i=1;i<entries;i++){
      xError[i] = 0;
      yError[i] = 0;

      if(tree->GetV3())
	  yError[i] = graphError[index[i]];

      if(graphX[index[i]]==graphX[index[i-1]])
	  tempArray[index[i]] = count;
      else if((graphX[index[i]]!=graphX[index[i-1]])){
	      count++;
	      icount++;
	      tempArray[index[i]] = count;
	      vrun[icount]=graphX[index[i]];
      }
  }

  // count the number of xbins (run-wise) for the new graph
  const Int_t newNbins = int(count+0.5);
  Double_t *newBins = new Double_t[newNbins+1];
  for(Int_t i=0; i<=count+1;i++){
    newBins[i] = i;
  }

  // define and fill the new graph
  TGraphErrors *graphNew = new TGraphErrors(entries,tempArray,graphY,xError,yError);
  graphNew->GetXaxis()->Set(newNbins,newBins);

  // set the bins for the x-axis
  Char_t xName[50];
  for(Int_t i=0;i<count;i++){
    sprintf(xName,"%d",Int_t(vrun[i]));
    graphNew->GetXaxis()->SetBinLabel(i+1,xName);
  }
  graphNew->GetHistogram()->SetTitle("");

  // memory clearing
  delete [] xError;
  delete [] yError;
  delete [] tempArray;
  delete [] index;
  delete [] newBins;
  delete [] vrun;
  return graphNew;

}
//------------------------------------------------------------------------------------------------
drawPerformanceT0QATrends(const char* inFile = "trending.root", const char* runType="pp") {
  //
  //
  gROOT->Reset();
  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetLabelSize(0.04,"x");

  // open input file
  //
  TFile *file = TFile::Open(inFile);
  if(!file) return;
  file->cd();

  TTree *tree = (TTree*)file->Get("trending");
  if(!tree) return;
  int const entries = tree->GetEntries();
  cout<<"number of entries   "<<entries<<endl;
  TH1F *frame = new TH1F();

  //const float norm_runs = 8.0;
  if(entries<8)
    const float norm_runs =10.0;
  else if(entries>=8&&entries<16)
    const float norm_runs =20.0;
 else
   const float norm_runs =50.0;
  int const canvas_width = int(((entries*1.0)/norm_runs)*2000.0);
  if(entries>50){
    gStyle->SetTickLength(0.03*norm_runs/(entries*1.0),"Y");
    gStyle->SetTitleYOffset((norm_runs/(entries*1.0))*0.8);
    gStyle->SetPadLeftMargin(0.1*norm_runs/(entries*1.0));
    gStyle->SetPadRightMargin(0.1*norm_runs/(entries*1.0));
  }

  //Define ranges of you trending plots
  double resolutionMin = 10,   resolutionMax = 100;    // OR A - OR C
  double oraplusorcMin = -100, oraplusorcMax = 100;   // OR A + OR CA
  double oraMin        = -100, oraMax        = 100;   // OR A
  double orcMin        = -100, orcMax        = 100;   // OR C
  double amplMin       =0,    amplMax    =3   ;     // amplitude in each PMT
  double timeMin     =  2900,   timeMax =3300       ;     // amplitude in each PMT
  //-----> add ranges of your new trending plot

  TCanvas *c1  = new  TCanvas("can","can",canvas_width,500);
  c1->SetGridy(1);
  c1->SetGridx(1);
  c1->SetBottomMargin(0.17);

  /****** T0 ORA+ORC ******/
  TGraphErrors *grSum = MakeGraphSparse(tree,"tzeroOrAPlusOrC:run","");
  grSum->SetMarkerStyle(20);
  grSum->SetMarkerSize(1.0);
  grSum->SetMarkerColor(2);
  TGraphErrors *grORA = MakeGraphSparse(tree,"tzeroOrA:run","");
  grORA->SetMarkerStyle(28);
  grORA->SetMarkerSize(1.0);
  grORA->SetMarkerColor(4);
  TGraphErrors *grORC = MakeGraphSparse(tree,"tzeroOrC:run","");
  grORC->SetMarkerStyle(25);
  grORC->SetMarkerSize(1.0);
  grORC->SetMarkerColor(1);

  grSum->GetHistogram()->SetYTitle("mean [ps]");
  grSum->GetHistogram()->SetTitle("T0 ORA, ORC and (ORA+ORC)/2");
  grSum->GetHistogram()->SetMinimum(oraplusorcMin);
  grSum->GetHistogram()->SetMaximum(oraplusorcMax);
  grSum->Draw("AP");
  grORA->Draw("psame");
  grORC->Draw("psame");
  TLegend *leg = new TLegend(0.1,0.85,0.3,0.95," ","brNDC");
  leg->SetFillStyle(0); leg->SetBorderSize(0); leg->SetTextSize(0.05);leg->SetNColumns(3);leg->SetColumnSeparation(1);
  leg->AddEntry(grORA,"ORA","p");
  leg->AddEntry(grORC,"ORC","p");
  leg->AddEntry(grSum,"(ORA+ORC)/2","p");
  leg->Draw();

  grSum->GetXaxis()->LabelsOption("v");
  c1->SaveAs("meanT0OrAPlusOrC_vs_run.gif");

  /****** T0 Resolution ******/
  TGraphErrors *gr = MakeGraphSparse(tree,"resolution:run","");
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(1.0);
  gr->SetMarkerColor(2);
  gr->GetHistogram()->SetMinimum(resolutionMin);
  gr->GetHistogram()->SetMaximum(resolutionMax);
  gr->Draw("AP");
  gr->GetXaxis()->LabelsOption("v");
  gr->GetHistogram()->SetYTitle("sigma [ps]");
  gr->GetHistogram()->SetTitle("T0 resolution (ORA -ORC)/2");
  c1->SaveAs("sigmaResolutionT0_vs_run.gif");

   /****** Mean T0 OR A ******/
 /* TGraphErrors *gr = MakeGraphSparse(tree,"tzeroOrA:run","");
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(1.0);
  gr->SetMarkerColor(2);
  gr->GetHistogram()->SetYTitle("mean [ps]");
  gr->GetHistogram()->SetTitle("T0 OR A");
  gr->GetHistogram()->SetMinimum(oraMin);
  gr->GetHistogram()->SetMaximum(oraMax);
  gr->Draw("AP");
  gr->GetXaxis()->LabelsOption("v");
  c1->SaveAs("meanT0OrA_vs_run.gif");
*/

  /****** Mean T0 OR C ******/
 /* TGraphErrors *gr = MakeGraphSparse(tree,"tzeroOrC:run","");
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(1.0);
  gr->SetMarkerColor(2);
  gr->GetHistogram()->SetYTitle("mean [ps]");
  gr->GetHistogram()->SetTitle("T0 OR C");
  gr->GetHistogram()->SetMinimum(orcMin);
  gr->GetHistogram()->SetMaximum(orcMax);
  gr->Draw("AP");
  gr->GetXaxis()->LabelsOption("v");
  c1->SaveAs("meanT0OrC_vs_run.gif");
*/

  /****** Mean Amplitude in PMT ******/
  const int kNPMTs = 24;
  char name[200];

  for(int ipmt=1;ipmt<=kNPMTs; ipmt++){
    sprintf(name,"amplPMT%d:run",ipmt);
    gr = MakeGraphSparse(tree,name,"");
    gr->SetMarkerStyle(20);
    gr->SetMarkerSize(1.0);
    gr->SetMarkerColor(6);
    gr->GetHistogram()->SetYTitle("mean");
    gr->GetHistogram()->SetTitle(Form("Amplitude PMT%d",ipmt));

    int nRuns = gr->GetN();
    double *y =  gr->GetY();
	double min = y[0];
	double max = y[0];
    for(int irun =1; irun<nRuns;irun++){
      if(min > y[irun] & y[irun]>0) min = y[irun];
      if(max < y[irun]) max = y[irun];
    }
    //  amplMin = min - 2;
    //  amplMax = max + 2;

    gr->GetHistogram()->SetMinimum(amplMin);
    gr->GetHistogram()->SetMaximum(amplMax);
    gr->Draw("AP");
    gr->GetXaxis()->LabelsOption("v");
    c1->SaveAs(Form("meanAmplPMT%d_vs_run.gif",ipmt));
  }
  /****** Mean Time in PMT ******/
  for(int ipmt=1;ipmt<=kNPMTs; ipmt++){
    sprintf(name,"timePMT%d:run",ipmt);
    gr = MakeGraphSparse(tree,name,"");

    sprintf(name,"timeDelayPMT%d:run",ipmt);
    TGraphErrors *grDelay = MakeGraphSparse(tree,name,"");
    //regular run
    int nRuns = gr->GetN();
    double *y =  gr->GetY();
	double min = y[0];
	double max = y[0];
    for(int irun =1; irun<nRuns;irun++){
      if(min > y[irun] && y[irun]>0) min = y[irun];
      if(max < y[irun]) max = y[irun];
    }
    //Delay
    //   double *yDelay =  grDelay->GetY();
    //  nRuns = grDelay->GetN();
    //   for(int irun =0; irun<nRuns;irun++){
    //      if(min > yDelay[irun] && yDelay[irun]>0) min = yDelay[irun];
    //    if(max < yDelay[irun]) max = yDelay[irun];
    //  }

    //  timeMin = min - 2;
    //   timeMax = max + 2;

    gr->SetMarkerStyle(20);
    gr->SetMarkerSize(1.0);
    gr->SetMarkerColor(2);
    grDelay->SetMarkerStyle(24);
    grDelay->SetMarkerSize(1.0);
    grDelay->SetMarkerColor(1);

    gr->GetHistogram()->SetYTitle("mean [channels]");
    gr->GetHistogram()->SetTitle(Form("Time PMT%d",ipmt));
    gr->GetHistogram()->SetMinimum(timeMin);
    gr->GetHistogram()->SetMaximum(timeMax);
    gr->GetXaxis()->LabelsOption("v");
    gr->Draw("AP");
    grDelay->Draw("Psame");

    TLegend *leg = new TLegend(0.1,0.85,0.3,0.95," ","brNDC");
    leg->SetFillStyle(0); leg->SetBorderSize(0); leg->SetTextSize(0.05);leg->SetNColumns(3);
    leg->AddEntry(gr,"mean time","p");
    //leg->AddEntry(grDelay,"Time Delay OCDB","p");
    leg->Draw();

    c1->SaveAs(Form("meanTimePMT%d_vs_run.gif",ipmt));
  }

  //-----> draw your new trending plot here
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkKitwareContourFilter.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkKitwareContourFilter.h"

#include "vtkCell.h"
#include "vtkCellData.h"
#include "vtkContourValues.h"
#include "vtkGridSynchronizedTemplates3D.h"
#include "vtkImageData.h"
#include "vtkMergePoints.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkRectilinearGrid.h"
#include "vtkRectilinearSynchronizedTemplates.h"
#include "vtkScalarTree.h"
#include "vtkStructuredGrid.h"
#include "vtkSynchronizedTemplates2D.h"
#include "vtkSynchronizedTemplates3D.h"

#include <math.h>

vtkCxxRevisionMacro(vtkKitwareContourFilter, "1.37");
vtkStandardNewMacro(vtkKitwareContourFilter);

// Construct object with initial range (0,1) and single contour value
// of 0.0.
vtkKitwareContourFilter::vtkKitwareContourFilter()
{
  this->ArrayComponent = 0;
}

vtkKitwareContourFilter::~vtkKitwareContourFilter()
{
}

int vtkKitwareContourFilter::ComputeInputUpdateExtent(
  vtkInformation* request,
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector)
{
  vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
  vtkDataSet *input = vtkDataSet::SafeDownCast(
    inInfo->Get(vtkDataObject::DATA_OBJECT()));

  vtkInformation* info = outputVector->GetInformationObject(0);
  vtkDataSet *output = vtkDataSet::SafeDownCast(
    info->Get(vtkDataObject::DATA_OBJECT()));

  if (!input || !output)
    {
    return 0;
    }

  int inputObjectType = input->GetDataObjectType();

  if ( inputObjectType == VTK_STRUCTURED_POINTS ||
       inputObjectType == VTK_IMAGE_DATA )
    {

    int ext[6], dims[3], dim=0;
    ((vtkImageData *)input)->GetWholeExtent(ext);
    for(int j=0; j<3; j++)
      {
      dims[j] = ext[2*j+1]-ext[2*j];
      if ( dims[j] != 0 )
        {
        dim++;
        }
      }

    if ((dim == 2) && (dims[2] == 0))
      {
      vtkSynchronizedTemplates2D *syncTemp2D =
        vtkSynchronizedTemplates2D::New();
      syncTemp2D->SetInput(vtkImageData::SafeDownCast(input));
      syncTemp2D->SetDebug(this->Debug);
      syncTemp2D->ComputeInputUpdateExtents(output);
      syncTemp2D->Delete();
      return 1;
      }
    else if (dim == 3)
      {
      vtkSynchronizedTemplates3D *syncTemp3D =
        vtkSynchronizedTemplates3D::New();
      syncTemp3D->SetInput(vtkImageData::SafeDownCast(input));
      syncTemp3D->SetDebug(this->Debug);
      syncTemp3D->SetComputeNormals (this->ComputeNormals);
      syncTemp3D->SetComputeGradients (this->ComputeGradients);
      syncTemp3D->SetComputeScalars (this->ComputeScalars);
      syncTemp3D->ComputeInputUpdateExtents(output);
      syncTemp3D->Delete();
      return 1;
      }
    }

  if ( inputObjectType  == VTK_STRUCTURED_GRID )
    {
    int ext[6], dim=0;
    ((vtkStructuredGrid *)input)->GetWholeExtent(ext);
    for(int j=0; j<3; j++)
      {
      if ( ( ext[2*j+1]-ext[2*j] ) != 0 )
        {
        dim++;
        }
      }
    if (dim == 3)
      {
      vtkGridSynchronizedTemplates3D *gridTemp3D =
        vtkGridSynchronizedTemplates3D::New();
      gridTemp3D->SetInput(vtkStructuredGrid::SafeDownCast(input));
      gridTemp3D->SetComputeNormals (this->ComputeNormals);
      gridTemp3D->SetComputeGradients (this->ComputeGradients);
      gridTemp3D->SetComputeScalars (this->ComputeScalars);
      gridTemp3D->SetDebug(this->Debug);
      gridTemp3D->ComputeInputUpdateExtents(output);
      gridTemp3D->Delete();
      return 1;
      }
    }

  if ( inputObjectType == VTK_RECTILINEAR_GRID )
    {
    int ext[6], dim=0;
    ((vtkRectilinearGrid *)input)->GetWholeExtent(ext);
    for(int j=0; j<3; j++)
      {
      if ( ( ext[2*j+1]-ext[2*j] ) != 0 )
        {
        dim++;
        }
      }
    if (dim == 3)
      {
      vtkRectilinearSynchronizedTemplates *rTemp =
        vtkRectilinearSynchronizedTemplates::New();
      rTemp->SetInput(vtkRectilinearGrid::SafeDownCast(input));
      rTemp->SetComputeNormals (this->ComputeNormals);
      rTemp->SetComputeGradients (this->ComputeGradients);
      rTemp->SetComputeScalars (this->ComputeScalars);
      rTemp->SetDebug(this->Debug);
      rTemp->ComputeInputUpdateExtents(output);
      rTemp->Delete();
      return 1;
      }
    }

  return this->Superclass::ComputeInputUpdateExtent(request,
                                                    inputVector,
                                                    outputVector);
}

//
// General contouring filter.  Handles arbitrary input.
//
int vtkKitwareContourFilter::RequestData(
  vtkInformation* request,
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector)
{
  vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
  vtkDataSet *input = vtkDataSet::SafeDownCast(
    inInfo->Get(vtkDataObject::DATA_OBJECT()));
  if (!input) {return 0;}

  vtkDataArray *inScalars;
  vtkIdType numCells;

  vtkDebugMacro(<< "Executing contour filter");

  numCells = input->GetNumberOfCells();
  inScalars = input->GetPointData()->GetScalars(this->InputScalarsSelection);
  if ( ! inScalars || numCells < 1 )
    {
    // vtkErrorMacro(<<"No data to contour");
    return 0;
    }

  // If structured points and structured grid, use more efficient algorithms
  if ( input->GetDataObjectType() == VTK_STRUCTURED_POINTS ||
       input->GetDataObjectType() == VTK_IMAGE_DATA )
    {
    int dim = 3;
    int *uExt = input->GetUpdateExtent();
    if (uExt[0] == uExt[1])
      {
      --dim;
      }
    if (uExt[2] == uExt[3])
      {
      --dim;
      }
    if (uExt[4] == uExt[5])
      {
      --dim;
      }

    if ( dim >= 2 )
      {
      this->StructuredPointsContour(dim, input);
      return 1;
      }
    }

  if ( input->GetDataObjectType() == VTK_STRUCTURED_GRID )
    {
    int dim = 3;
    int *uExt = input->GetUpdateExtent();
    if (uExt[0] == uExt[1])
      {
      --dim;
      }
    if (uExt[2] == uExt[3])
      {
      --dim;
      }
    if (uExt[4] == uExt[5])
      {
      --dim;
      }

    // only do 3D structured grids (to be extended in the future)
    if ( dim == 3 )
      {
      this->StructuredGridContour(dim, input);
      return 1;
      }
    }

  if ( input->GetDataObjectType() == VTK_RECTILINEAR_GRID )
    {
    int dim = 3;
    int *uExt = input->GetUpdateExtent();
    if (uExt[0] == uExt[1])
      {
      --dim;
      }
    if (uExt[2] == uExt[3])
      {
      --dim;
      }
    if (uExt[4] == uExt[5])
      {
      --dim;
      }

    if ( dim == 3 )
      {
      this->RectilinearGridContour(dim, input);
      return 1;
      }
    }

  // otherwise just use the normal one
  return this->Superclass::RequestData(request, inputVector, outputVector);
}

//
// Special method handles structured points
//
void vtkKitwareContourFilter::StructuredPointsContour(int dim, vtkDataSet* input)
{
  vtkPolyData *output;
  vtkPolyData *thisOutput = this->GetOutput();
  int numContours=this->ContourValues->GetNumberOfContours();
  double *values=this->ContourValues->GetValues();

  if ( dim == 2 )
    {
    vtkSynchronizedTemplates2D *syncTemp2D;
    int i;

    syncTemp2D = vtkSynchronizedTemplates2D::New();
    syncTemp2D->SetInput(vtkImageData::SafeDownCast(input));
    syncTemp2D->SetDebug(this->Debug);
    syncTemp2D->SetNumberOfContours(numContours);
    syncTemp2D->SetArrayComponent(this->ArrayComponent);
    for (i=0; i < numContours; i++)
      {
      syncTemp2D->SetValue(i,values[i]);
      }

    syncTemp2D->GetOutput()->SetUpdateExtent(thisOutput->GetUpdatePiece(),
                                             thisOutput->GetUpdateNumberOfPieces(),
                                             thisOutput->GetUpdateGhostLevel());
    syncTemp2D->SelectInputScalars(this->InputScalarsSelection);
    syncTemp2D->Update();
    output = syncTemp2D->GetOutput();
    output->Register(this);
    syncTemp2D->Delete();
    }

  else
    {
    vtkSynchronizedTemplates3D *syncTemp3D;
    int i;

    syncTemp3D = vtkSynchronizedTemplates3D::New();

    syncTemp3D->SetInput(vtkImageData::SafeDownCast(input));
    syncTemp3D->SetComputeNormals (this->ComputeNormals);
    syncTemp3D->SetComputeGradients (this->ComputeGradients);
    syncTemp3D->SetComputeScalars (this->ComputeScalars);
    syncTemp3D->SetDebug(this->Debug);
    syncTemp3D->SetNumberOfContours(numContours);
    syncTemp3D->SetArrayComponent(this->ArrayComponent);
    for (i=0; i < numContours; i++)
      {
      syncTemp3D->SetValue(i,values[i]);
      }

    syncTemp3D->GetOutput()->SetUpdateExtent(thisOutput->GetUpdatePiece(),
                                             thisOutput->GetUpdateNumberOfPieces(),
                                             thisOutput->GetUpdateGhostLevel());
    syncTemp3D->SelectInputScalars(this->InputScalarsSelection);
    syncTemp3D->Update();
    output = syncTemp3D->GetOutput();
    output->Register(this);
    syncTemp3D->Delete();
    }

  thisOutput->CopyStructure(output);
  thisOutput->GetPointData()->ShallowCopy(output->GetPointData());
  thisOutput->GetCellData()->ShallowCopy(output->GetCellData());
  output->UnRegister(this);
}
//
// Special method handles structured grids
//
void vtkKitwareContourFilter::StructuredGridContour(int dim, vtkDataSet* input)
{
  vtkPolyData *output = NULL;
  vtkPolyData *thisOutput = this->GetOutput();
  int numContours=this->ContourValues->GetNumberOfContours();
  double *values=this->ContourValues->GetValues();

  if ( dim == 3 )
    {
    vtkGridSynchronizedTemplates3D *gridTemp3D;
    int i;

    gridTemp3D = vtkGridSynchronizedTemplates3D::New();
    gridTemp3D->SetInput(vtkStructuredGrid::SafeDownCast(input));
    gridTemp3D->SetComputeNormals (this->ComputeNormals);
    gridTemp3D->SetComputeGradients (this->ComputeGradients);
    gridTemp3D->SetComputeScalars (this->ComputeScalars);
    gridTemp3D->SetDebug(this->Debug);
    gridTemp3D->SetNumberOfContours(numContours);
    for (i=0; i < numContours; i++)
      {
      gridTemp3D->SetValue(i,values[i]);
      }

    output = gridTemp3D->GetOutput();
    output->SetUpdateNumberOfPieces(thisOutput->GetUpdateNumberOfPieces());
    output->SetUpdatePiece(thisOutput->GetUpdatePiece());
    output->SetUpdateGhostLevel(thisOutput->GetUpdateGhostLevel());
    gridTemp3D->SelectInputScalars(this->InputScalarsSelection);
    gridTemp3D->Update();
    output->Register(this);
    gridTemp3D->Delete();
    }

  thisOutput->CopyStructure(output);
  thisOutput->GetPointData()->ShallowCopy(output->GetPointData());
  thisOutput->GetCellData()->ShallowCopy(output->GetCellData());
  output->UnRegister(this);
}

//
// Special method handles rectilinear grids
//
void vtkKitwareContourFilter::RectilinearGridContour(int dim, vtkDataSet* input)
{
  vtkPolyData *output = NULL;
  vtkPolyData *thisOutput = this->GetOutput();
  int numContours=this->ContourValues->GetNumberOfContours();
  double *values=this->ContourValues->GetValues();

  if ( dim == 3 )
    {
    vtkRectilinearSynchronizedTemplates *rTemp;
    int i;

    rTemp = vtkRectilinearSynchronizedTemplates::New();
    rTemp->SetInput(vtkRectilinearGrid::SafeDownCast(input));
    rTemp->SetComputeNormals (this->ComputeNormals);
    rTemp->SetComputeGradients (this->ComputeGradients);
    rTemp->SetComputeScalars (this->ComputeScalars);
    rTemp->SetDebug(this->Debug);
    rTemp->SetNumberOfContours(numContours);
    for (i=0; i < numContours; i++)
      {
      rTemp->SetValue(i,values[i]);
      }

    output = rTemp->GetOutput();
    output->SetUpdateNumberOfPieces(thisOutput->GetUpdateNumberOfPieces());
    output->SetUpdatePiece(thisOutput->GetUpdatePiece());
    output->SetUpdateGhostLevel(thisOutput->GetUpdateGhostLevel());
    rTemp->SelectInputScalars(this->InputScalarsSelection);
    rTemp->Update();
    output->Register(this);
    rTemp->Delete();
    }

  thisOutput->CopyStructure(output);
  thisOutput->GetPointData()->ShallowCopy(output->GetPointData());
  thisOutput->GetCellData()->ShallowCopy(output->GetCellData());
  output->UnRegister(this);
}

//----------------------------------------------------------------------------
void vtkKitwareContourFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << "ArrayComponent: " << this->ArrayComponent << endl;
}
<commit_msg>BUG: Extremely subtle bug.  The logic in ComputeInputUpdateExtent to choose which internal filter to use must match the logic in RequestData.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkKitwareContourFilter.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkKitwareContourFilter.h"

#include "vtkCell.h"
#include "vtkCellData.h"
#include "vtkContourValues.h"
#include "vtkGridSynchronizedTemplates3D.h"
#include "vtkImageData.h"
#include "vtkMergePoints.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkRectilinearGrid.h"
#include "vtkRectilinearSynchronizedTemplates.h"
#include "vtkScalarTree.h"
#include "vtkStructuredGrid.h"
#include "vtkSynchronizedTemplates2D.h"
#include "vtkSynchronizedTemplates3D.h"

#include <math.h>

vtkCxxRevisionMacro(vtkKitwareContourFilter, "1.38");
vtkStandardNewMacro(vtkKitwareContourFilter);

// Construct object with initial range (0,1) and single contour value
// of 0.0.
vtkKitwareContourFilter::vtkKitwareContourFilter()
{
  this->ArrayComponent = 0;
}

vtkKitwareContourFilter::~vtkKitwareContourFilter()
{
}

int vtkKitwareContourFilter::ComputeInputUpdateExtent(
  vtkInformation* request,
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector)
{
  vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
  vtkDataSet *input = vtkDataSet::SafeDownCast(
    inInfo->Get(vtkDataObject::DATA_OBJECT()));

  vtkInformation* info = outputVector->GetInformationObject(0);
  vtkDataSet *output = vtkDataSet::SafeDownCast(
    info->Get(vtkDataObject::DATA_OBJECT()));

  if (!input || !output)
    {
    return 0;
    }

  int inputObjectType = input->GetDataObjectType();

  if ( inputObjectType == VTK_STRUCTURED_POINTS ||
       inputObjectType == VTK_IMAGE_DATA )
    {

    int ext[6], dims[3], dim=0;
    ((vtkImageData *)input)->GetWholeExtent(ext);
    for(int j=0; j<3; j++)
      {
      dims[j] = ext[2*j+1]-ext[2*j];
      if ( dims[j] != 0 )
        {
        dim++;
        }
      }

    if (dim == 2)
      {
      vtkSynchronizedTemplates2D *syncTemp2D =
        vtkSynchronizedTemplates2D::New();
      syncTemp2D->SetInput(vtkImageData::SafeDownCast(input));
      syncTemp2D->SetDebug(this->Debug);
      syncTemp2D->ComputeInputUpdateExtents(output);
      syncTemp2D->Delete();
      return 1;
      }
    else if (dim == 3)
      {
      vtkSynchronizedTemplates3D *syncTemp3D =
        vtkSynchronizedTemplates3D::New();
      syncTemp3D->SetInput(vtkImageData::SafeDownCast(input));
      syncTemp3D->SetDebug(this->Debug);
      syncTemp3D->SetComputeNormals (this->ComputeNormals);
      syncTemp3D->SetComputeGradients (this->ComputeGradients);
      syncTemp3D->SetComputeScalars (this->ComputeScalars);
      syncTemp3D->ComputeInputUpdateExtents(output);
      syncTemp3D->Delete();
      return 1;
      }
    }

  if ( inputObjectType  == VTK_STRUCTURED_GRID )
    {
    int ext[6], dim=0;
    ((vtkStructuredGrid *)input)->GetWholeExtent(ext);
    for(int j=0; j<3; j++)
      {
      if ( ( ext[2*j+1]-ext[2*j] ) != 0 )
        {
        dim++;
        }
      }
    if (dim == 3)
      {
      vtkGridSynchronizedTemplates3D *gridTemp3D =
        vtkGridSynchronizedTemplates3D::New();
      gridTemp3D->SetInput(vtkStructuredGrid::SafeDownCast(input));
      gridTemp3D->SetComputeNormals (this->ComputeNormals);
      gridTemp3D->SetComputeGradients (this->ComputeGradients);
      gridTemp3D->SetComputeScalars (this->ComputeScalars);
      gridTemp3D->SetDebug(this->Debug);
      gridTemp3D->ComputeInputUpdateExtents(output);
      gridTemp3D->Delete();
      return 1;
      }
    }

  if ( inputObjectType == VTK_RECTILINEAR_GRID )
    {
    int ext[6], dim=0;
    ((vtkRectilinearGrid *)input)->GetWholeExtent(ext);
    for(int j=0; j<3; j++)
      {
      if ( ( ext[2*j+1]-ext[2*j] ) != 0 )
        {
        dim++;
        }
      }
    if (dim == 3)
      {
      vtkRectilinearSynchronizedTemplates *rTemp =
        vtkRectilinearSynchronizedTemplates::New();
      rTemp->SetInput(vtkRectilinearGrid::SafeDownCast(input));
      rTemp->SetComputeNormals (this->ComputeNormals);
      rTemp->SetComputeGradients (this->ComputeGradients);
      rTemp->SetComputeScalars (this->ComputeScalars);
      rTemp->SetDebug(this->Debug);
      rTemp->ComputeInputUpdateExtents(output);
      rTemp->Delete();
      return 1;
      }
    }

  return this->Superclass::ComputeInputUpdateExtent(request,
                                                    inputVector,
                                                    outputVector);
}

//
// General contouring filter.  Handles arbitrary input.
//
int vtkKitwareContourFilter::RequestData(
  vtkInformation* request,
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector)
{
  vtkInformation* inInfo = inputVector[0]->GetInformationObject(0);
  vtkDataSet *input = vtkDataSet::SafeDownCast(
    inInfo->Get(vtkDataObject::DATA_OBJECT()));
  if (!input) {return 0;}

  vtkDataArray *inScalars;
  vtkIdType numCells;

  vtkDebugMacro(<< "Executing contour filter");

  numCells = input->GetNumberOfCells();
  inScalars = input->GetPointData()->GetScalars(this->InputScalarsSelection);
  if ( ! inScalars || numCells < 1 )
    {
    // vtkErrorMacro(<<"No data to contour");
    return 0;
    }

  // If structured points and structured grid, use more efficient algorithms
  if ( input->GetDataObjectType() == VTK_STRUCTURED_POINTS ||
       input->GetDataObjectType() == VTK_IMAGE_DATA )
    {
    int dim = 3;
    int *uExt = input->GetUpdateExtent();
    if (uExt[0] == uExt[1])
      {
      --dim;
      }
    if (uExt[2] == uExt[3])
      {
      --dim;
      }
    if (uExt[4] == uExt[5])
      {
      --dim;
      }

    if ( dim >= 2 )
      {
      this->StructuredPointsContour(dim, input);
      return 1;
      }
    }

  if ( input->GetDataObjectType() == VTK_STRUCTURED_GRID )
    {
    int dim = 3;
    int *uExt = input->GetUpdateExtent();
    if (uExt[0] == uExt[1])
      {
      --dim;
      }
    if (uExt[2] == uExt[3])
      {
      --dim;
      }
    if (uExt[4] == uExt[5])
      {
      --dim;
      }

    // only do 3D structured grids (to be extended in the future)
    if ( dim == 3 )
      {
      this->StructuredGridContour(dim, input);
      return 1;
      }
    }

  if ( input->GetDataObjectType() == VTK_RECTILINEAR_GRID )
    {
    int dim = 3;
    int *uExt = input->GetUpdateExtent();
    if (uExt[0] == uExt[1])
      {
      --dim;
      }
    if (uExt[2] == uExt[3])
      {
      --dim;
      }
    if (uExt[4] == uExt[5])
      {
      --dim;
      }

    if ( dim == 3 )
      {
      this->RectilinearGridContour(dim, input);
      return 1;
      }
    }

  // otherwise just use the normal one
  return this->Superclass::RequestData(request, inputVector, outputVector);
}

//
// Special method handles structured points
//
void vtkKitwareContourFilter::StructuredPointsContour(int dim, vtkDataSet* input)
{
  vtkPolyData *output;
  vtkPolyData *thisOutput = this->GetOutput();
  int numContours=this->ContourValues->GetNumberOfContours();
  double *values=this->ContourValues->GetValues();

  if ( dim == 2 )
    {
    vtkSynchronizedTemplates2D *syncTemp2D;
    int i;

    syncTemp2D = vtkSynchronizedTemplates2D::New();
    syncTemp2D->SetInput(vtkImageData::SafeDownCast(input));
    syncTemp2D->SetDebug(this->Debug);
    syncTemp2D->SetNumberOfContours(numContours);
    syncTemp2D->SetArrayComponent(this->ArrayComponent);
    for (i=0; i < numContours; i++)
      {
      syncTemp2D->SetValue(i,values[i]);
      }

    syncTemp2D->GetOutput()->SetUpdateExtent(thisOutput->GetUpdatePiece(),
                                             thisOutput->GetUpdateNumberOfPieces(),
                                             thisOutput->GetUpdateGhostLevel());
    syncTemp2D->SelectInputScalars(this->InputScalarsSelection);
    syncTemp2D->Update();
    output = syncTemp2D->GetOutput();
    output->Register(this);
    syncTemp2D->Delete();
    }

  else
    {
    vtkSynchronizedTemplates3D *syncTemp3D;
    int i;

    syncTemp3D = vtkSynchronizedTemplates3D::New();

    syncTemp3D->SetInput(vtkImageData::SafeDownCast(input));
    syncTemp3D->SetComputeNormals (this->ComputeNormals);
    syncTemp3D->SetComputeGradients (this->ComputeGradients);
    syncTemp3D->SetComputeScalars (this->ComputeScalars);
    syncTemp3D->SetDebug(this->Debug);
    syncTemp3D->SetNumberOfContours(numContours);
    syncTemp3D->SetArrayComponent(this->ArrayComponent);
    for (i=0; i < numContours; i++)
      {
      syncTemp3D->SetValue(i,values[i]);
      }

    syncTemp3D->GetOutput()->SetUpdateExtent(thisOutput->GetUpdatePiece(),
                                             thisOutput->GetUpdateNumberOfPieces(),
                                             thisOutput->GetUpdateGhostLevel());
    syncTemp3D->SelectInputScalars(this->InputScalarsSelection);
    syncTemp3D->Update();
    output = syncTemp3D->GetOutput();
    output->Register(this);
    syncTemp3D->Delete();
    }

  thisOutput->CopyStructure(output);
  thisOutput->GetPointData()->ShallowCopy(output->GetPointData());
  thisOutput->GetCellData()->ShallowCopy(output->GetCellData());
  output->UnRegister(this);
}
//
// Special method handles structured grids
//
void vtkKitwareContourFilter::StructuredGridContour(int dim, vtkDataSet* input)
{
  vtkPolyData *output = NULL;
  vtkPolyData *thisOutput = this->GetOutput();
  int numContours=this->ContourValues->GetNumberOfContours();
  double *values=this->ContourValues->GetValues();

  if ( dim == 3 )
    {
    vtkGridSynchronizedTemplates3D *gridTemp3D;
    int i;

    gridTemp3D = vtkGridSynchronizedTemplates3D::New();
    gridTemp3D->SetInput(vtkStructuredGrid::SafeDownCast(input));
    gridTemp3D->SetComputeNormals (this->ComputeNormals);
    gridTemp3D->SetComputeGradients (this->ComputeGradients);
    gridTemp3D->SetComputeScalars (this->ComputeScalars);
    gridTemp3D->SetDebug(this->Debug);
    gridTemp3D->SetNumberOfContours(numContours);
    for (i=0; i < numContours; i++)
      {
      gridTemp3D->SetValue(i,values[i]);
      }

    output = gridTemp3D->GetOutput();
    output->SetUpdateNumberOfPieces(thisOutput->GetUpdateNumberOfPieces());
    output->SetUpdatePiece(thisOutput->GetUpdatePiece());
    output->SetUpdateGhostLevel(thisOutput->GetUpdateGhostLevel());
    gridTemp3D->SelectInputScalars(this->InputScalarsSelection);
    gridTemp3D->Update();
    output->Register(this);
    gridTemp3D->Delete();
    }

  thisOutput->CopyStructure(output);
  thisOutput->GetPointData()->ShallowCopy(output->GetPointData());
  thisOutput->GetCellData()->ShallowCopy(output->GetCellData());
  output->UnRegister(this);
}

//
// Special method handles rectilinear grids
//
void vtkKitwareContourFilter::RectilinearGridContour(int dim, vtkDataSet* input)
{
  vtkPolyData *output = NULL;
  vtkPolyData *thisOutput = this->GetOutput();
  int numContours=this->ContourValues->GetNumberOfContours();
  double *values=this->ContourValues->GetValues();

  if ( dim == 3 )
    {
    vtkRectilinearSynchronizedTemplates *rTemp;
    int i;

    rTemp = vtkRectilinearSynchronizedTemplates::New();
    rTemp->SetInput(vtkRectilinearGrid::SafeDownCast(input));
    rTemp->SetComputeNormals (this->ComputeNormals);
    rTemp->SetComputeGradients (this->ComputeGradients);
    rTemp->SetComputeScalars (this->ComputeScalars);
    rTemp->SetDebug(this->Debug);
    rTemp->SetNumberOfContours(numContours);
    for (i=0; i < numContours; i++)
      {
      rTemp->SetValue(i,values[i]);
      }

    output = rTemp->GetOutput();
    output->SetUpdateNumberOfPieces(thisOutput->GetUpdateNumberOfPieces());
    output->SetUpdatePiece(thisOutput->GetUpdatePiece());
    output->SetUpdateGhostLevel(thisOutput->GetUpdateGhostLevel());
    rTemp->SelectInputScalars(this->InputScalarsSelection);
    rTemp->Update();
    output->Register(this);
    rTemp->Delete();
    }

  thisOutput->CopyStructure(output);
  thisOutput->GetPointData()->ShallowCopy(output->GetPointData());
  thisOutput->GetCellData()->ShallowCopy(output->GetCellData());
  output->UnRegister(this);
}

//----------------------------------------------------------------------------
void vtkKitwareContourFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
  os << indent << "ArrayComponent: " << this->ArrayComponent << endl;
}
<|endoftext|>


<commit_before>#include "Host.h"
#include <math.h> // ceil

static const int INITIAL_WINDOW_SIZE = 0; // TODO: change this number
static const int DATA_PKT_SIZE = 1; // TODO: change this number

Host::Host(CongestionAlg congestion_algorithm , Link &host_link) : my_link(host_link)
{
    window_size = INITIAL_WINDOW_SIZE;
    congestion_alg = congestion_algorithm;
    my_link = host_link;
    packet_id = 0;
    unack_packets = 0;
}

void Host::addFlow(std::string dest, float data_size)
{
    float temp_num_pkts = data_size / DATA_PKT_SIZE;
    int num_packets = (int) ceil(temp_num_pkts);

    std::queue<Packet> flow;

    for (int count = 0; count < num_packets; count++){
        std::string pack_id = this->uuid + std::to_string(packet_id);
        Packet new_packet(pack_id, dest, this->uuid, DATA_PKT_SIZE, false, false, count+1);
        flow.push(new_packet);
        packet_id++;
    }

    packet_queue.addQueue(flow);
}

void Host::giveEvent(std::unique_ptr<FlowEvent> flow_event)
{
    // Create queue of packets for host to make events out of
    addFlow(flow_event->destination, flow_event->data_size);

    // Create PacketEvents based on queue of packets based on
    // number of unacknowledged packets
    int num_events = window_size - unack_packets;
    int time_now = flow_event->eventTime();
    // push PacketEvents onto eventheap
    for (int pck = 1; pck <= num_events; pck++) {
        Packet new_pack = packet_queue.pop();
        time_now +=  float(new_pack.size) / throughput;
        PacketEvent packetEvent = PacketEvent(new_pack, new_pack.final_dest, new_pack.source, time_now);
        eventHeap.push(packetEvent);
        unack_packets++;
    }
}

void Host::giveEvent(std::unique_ptr<PacketEvent> new_event)
{
    if (new_event->type == ackPacket) {
        Packet new_packet = new_event->packet;
        std::string source = new_event->source;
        float now = new_event->eventTime();
    }

}

<commit_msg>passing host to Anish<commit_after>#include "Host.h"
#include <math.h> // ceil

static const int INITIAL_WINDOW_SIZE = 0; // TODO: change this number
static const int DATA_PKT_SIZE = 1; // TODO: change this number

Host::Host(CongestionAlg congestion_algorithm , Link &host_link) : my_link(host_link)
{
    window_size = INITIAL_WINDOW_SIZE;
    congestion_alg = congestion_algorithm;
    my_link = host_link;
    packet_id = 0;
    unack_packets = 0;
}

void Host::addFlow(std::string dest, float data_size)
{
    float temp_num_pkts = data_size / DATA_PKT_SIZE;
    int num_packets = (int) ceil(temp_num_pkts);

    std::queue<Packet> flow;

    for (int count = 0; count < num_packets; count++){
        std::string pack_id = this->uuid + std::to_string(packet_id);
        Packet new_packet(pack_id, dest, this->uuid, DATA_PKT_SIZE, false, false, count+1);
        flow.push(new_packet);
        packet_id++;
    }

    packet_queue.addQueue(flow);
}

void Host::giveEvent(std::unique_ptr<FlowEvent> flow_event)
{
    // Create queue of packets for host to make events out of
    addFlow(flow_event->destination, flow_event->data_size);

    // Create PacketEvents based on queue of packets based on
    // number of unacknowledged packets
    int num_events = window_size - unack_packets;
    int time_now = flow_event->eventTime();
    // push PacketEvents onto eventheap
    for (int pck = 1; pck <= num_events; pck++) {
        Packet new_pack = packet_queue.pop();
        time_now +=  float(new_pack.size) / throughput;
        PacketEvent packetEvent = PacketEvent(new_pack, new_pack.final_dest, new_pack.source, time_now);
        eventHeap.push(packetEvent);
        unack_packets++;
    }
}

void Host::giveEvent(std::unique_ptr<PacketEvent> new_event)
{
    Packet pkt = new_event->packet;

    if (pkt.ack)
    {
        Packet new_packet = new_event->packet;
        std::string source = new_event->source;
        float now = new_event->eventTime();
    }
    else if (<#condition#>)

}

<|endoftext|>


<commit_before>/*
 * Copyright 2015-2017, Robotics and Biology Lab, TU Berlin
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 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 "hybrid_automaton/ForceTorqueSensor.h"

namespace ha
{
	HA_SENSOR_REGISTER("ForceTorqueSensor", ForceTorqueSensor);

        ForceTorqueSensor::ForceTorqueSensor() : _port(DEFAULT_FT_PORT)
	{
	}

	ForceTorqueSensor::~ForceTorqueSensor()
	{
	}

	ForceTorqueSensor::ForceTorqueSensor(const ForceTorqueSensor& ss)
		:Sensor(ss)
	{
		_port = ss._port;
	}

  ::Eigen::MatrixXd ForceTorqueSensor::transformWrench(const ::Eigen::MatrixXd& wrench, const ::Eigen::MatrixXd& transform) const
  {
    ::Eigen::Matrix3d frameRot = transform.block(0,0,3,3);
    ::Eigen::Vector3d frameTrans(transform(0,3), transform(1,3), transform(2,3));
    ::Eigen::Vector3d forcePart(wrench(0,0), wrench(1,0),wrench(2,0));
    ::Eigen::Vector3d momentPart(wrench(3,0), wrench(4,0),wrench(5,0));

    forcePart = frameRot*forcePart;
    momentPart = frameRot*(momentPart - frameTrans.cross(forcePart));

    Eigen::MatrixXd wrenchOut(6,1);
    wrenchOut(0) = forcePart(0); wrenchOut(1) = forcePart(1); wrenchOut(2) = forcePart(2);
    wrenchOut(3) = momentPart(0); wrenchOut(4) = momentPart(1); wrenchOut(5) = momentPart(2);
    return wrenchOut;
  }

	::Eigen::MatrixXd ForceTorqueSensor::getCurrentValue() const
	{
    //This is the F/T wrench from the hardware - It must be in EE frame
    ::Eigen::MatrixXd forceTorque = _system->getForceTorqueMeasurement(DEFAULT_FT_PORT);
    ::Eigen::MatrixXd eeFrame = _system->getFramePose("EE");

    //Transform FT wrench to world frame
    Eigen::MatrixXd ftOut = transformWrench(forceTorque, eeFrame.inverse());

    //Transform FT wrench to given frame
    ftOut = transformWrench(forceTorque, _frame);

    return ftOut;
	}

	DescriptionTreeNode::Ptr ForceTorqueSensor::serialize(const DescriptionTree::ConstPtr& factory) const
	{
		DescriptionTreeNode::Ptr tree = factory->createNode("Sensor");
		tree->setAttribute<std::string>(std::string("type"), this->getType());
		tree->setAttribute<int>(std::string("port"), _port);
        return tree;
	}

	void ForceTorqueSensor::deserialize(const DescriptionTreeNode::ConstPtr& tree, const System::ConstPtr& system, const HybridAutomaton* ha)
	{
		if (tree->getType() != "Sensor") {
			HA_THROW_ERROR("ForceTorqueSensor.deserialize", "DescriptionTreeNode must have type 'Sensor', not '" << tree->getType() << "'!");
		}
		tree->getAttribute<std::string>("type", _type, "");
		tree->getAttribute<int>("port", _port, DEFAULT_FT_PORT);

		if(_port > 2 || _port <0)
		{
			HA_THROW_ERROR("ForceTorqueSensor.deserialize", "Port number " << _port << " "
				<< "invalid - it must be between 0 and 2!");
		}

		if (_type == "" || !HybridAutomaton::isSensorRegistered(_type)) {
			HA_THROW_ERROR("ForceTorqueSensor.deserialize", "SensorType type '" << _type << "' "
				<< "invalid - empty or not registered with HybridAutomaton!");
		}

    _frame.resize(4,4);
    _frame.setIdentity();
    if(tree->getAttribute< Eigen::MatrixXd>("frame", _frame))
		{
      HA_INFO("ForceTorqueSensor.deserialize", "Using external frame to express F/T value in");
      if(_frame.cols()!=4 || _frame.rows()!=4)
      {
        HA_THROW_ERROR("ForceTorqueSensor.deserialize", "frame parameter must be 4x4 homogeneous transform!");
      }
		}

		_system = system;
	}
}
<commit_msg>tmp commit - still not working<commit_after>/*
 * Copyright 2015-2017, Robotics and Biology Lab, TU Berlin
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 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 "hybrid_automaton/ForceTorqueSensor.h"

namespace ha
{
	HA_SENSOR_REGISTER("ForceTorqueSensor", ForceTorqueSensor);

        ForceTorqueSensor::ForceTorqueSensor() : _port(DEFAULT_FT_PORT)
	{
	}

	ForceTorqueSensor::~ForceTorqueSensor()
	{
	}

	ForceTorqueSensor::ForceTorqueSensor(const ForceTorqueSensor& ss)
		:Sensor(ss)
	{
		_port = ss._port;
	}
	::Eigen::MatrixXd ForceTorqueSensor::transformWrench(const ::Eigen::MatrixXd& wrench, const ::Eigen::MatrixXd& transform) const
	{
		::Eigen::Matrix3d frameRot = transform.block(0,0,3,3);
		::Eigen::Vector3d frameTrans(transform(0,3), transform(1,3), transform(2,3));
		::Eigen::Vector3d forcePart(wrench(0,0), wrench(1,0),wrench(2,0));
		::Eigen::Vector3d momentPart(wrench(3,0), wrench(4,0),wrench(5,0));

		forcePart = frameRot*forcePart;
		momentPart = frameRot*(momentPart - frameTrans.cross(forcePart));

		Eigen::MatrixXd wrenchOut(6,1);
		wrenchOut(0) = forcePart(0); wrenchOut(1) = forcePart(1); wrenchOut(2) = forcePart(2);
		wrenchOut(3) = momentPart(0); wrenchOut(4) = momentPart(1); wrenchOut(5) = momentPart(2);
		return wrenchOut;
	}

	int k;
	::Eigen::MatrixXd ForceTorqueSensor::getCurrentValue() const
	{
		//This is the F/T wrench from the hardware - It must be in EE frame
		::Eigen::MatrixXd forceTorque = _system->getForceTorqueMeasurement(_port);
		::Eigen::MatrixXd eeFrame = _system->getFramePose("EE");

		//Transform FT wrench to world frame
		Eigen::MatrixXd ftOut = transformWrench(forceTorque, eeFrame.inverse());

		//Transform FT wrench to given frame
		ftOut = transformWrench(ftOut, _frame);

		if((k++)%2000 == 0)
			HA_INFO("ForceTorqueSensor.getCurrentValue","ftout: "<<ftOut.transpose());
		return ftOut;
	}

	DescriptionTreeNode::Ptr ForceTorqueSensor::serialize(const DescriptionTree::ConstPtr& factory) const
	{
		DescriptionTreeNode::Ptr tree = factory->createNode("Sensor");
		tree->setAttribute<std::string>(std::string("type"), this->getType());
		tree->setAttribute<int>(std::string("port"), _port);
        return tree;
	}

	void ForceTorqueSensor::deserialize(const DescriptionTreeNode::ConstPtr& tree, const System::ConstPtr& system, const HybridAutomaton* ha)
	{
		if (tree->getType() != "Sensor") {
			HA_THROW_ERROR("ForceTorqueSensor.deserialize", "DescriptionTreeNode must have type 'Sensor', not '" << tree->getType() << "'!");
		}
		tree->getAttribute<std::string>("type", _type, "");
		tree->getAttribute<int>("port", _port, DEFAULT_FT_PORT);

		if(_port > 2 || _port <0)
		{
			HA_THROW_ERROR("ForceTorqueSensor.deserialize", "Port number " << _port << " "
				<< "invalid - it must be between 0 and 2!");
		}

		if (_type == "" || !HybridAutomaton::isSensorRegistered(_type)) {
			HA_THROW_ERROR("ForceTorqueSensor.deserialize", "SensorType type '" << _type << "' "
				<< "invalid - empty or not registered with HybridAutomaton!");
		}

    _frame.resize(4,4);
    _frame.setIdentity();
    if(tree->getAttribute< Eigen::MatrixXd>("frame", _frame))
		{
      HA_INFO("ForceTorqueSensor.deserialize", "Using external frame to express F/T value in");
      if(_frame.cols()!=4 || _frame.rows()!=4)
      {
        HA_THROW_ERROR("ForceTorqueSensor.deserialize", "frame parameter must be 4x4 homogeneous transform!");
      }
		}

		_system = system;
	}
}
<|endoftext|>


<commit_before>#include "GameController.h"

#include "Tools/Debug/DebugRequest.h"
#include <Representations/Infrastructure/Configuration.h>
#include <PlatformInterface/Platform.h>

GameController::GameController()
  : lastChestButtonEventCounter(0)
{
  DEBUG_REQUEST_REGISTER("gamecontroller:play", "force the play state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:penalized", "force the penalized state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:initial", "force the initial state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:ready", "force the ready state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:set", "force the set state", false);

  loadPlayerInfoFromFile();
}

void GameController::loadPlayerInfoFromFile()
{
  // load player.cfg
  naoth::Configuration& config = naoth::Platform::getInstance().theConfiguration;

  if (config.hasKey("player", "NumOfPlayer"))
  {
    getPlayerInfo().numOfPlayers = config.getInt("player", "NumOfPlayer");
  } else
  {
    std::cerr << "No number of players (NumOfPlayers) given" << std::endl;
  }

  if (config.hasKey("player", "PlayerNumber"))
  {
    getPlayerInfo().playerNumber = config.getInt("player", "PlayerNumber");
  } else
  {
    std::cerr << "No player number (PlayerNumber) given" << std::endl;
    getPlayerInfo().playerNumber = 3;
  }

  if (config.hasKey("player", "TeamColor"))
  {
    getPlayerInfo().teamColor = PlayerInfo::teamColorFromString(config.getString("player", "TeamColor"));
    if (getPlayerInfo().teamColor == PlayerInfo::numOfTeamColor)
    {
      getPlayerInfo().teamColor = PlayerInfo::red;
      std::cerr << "Invalid team color (TeamColor) \""
        << config.getString("player", "TeamColor") << "\" given" << std::endl;
    }
  } else
  {
    std::cerr << "No team color (TeamColor) given" << std::endl;
    getPlayerInfo().teamColor = PlayerInfo::red;
  }

  if (config.hasKey("player", "TeamNumber"))
  {
    getPlayerInfo().teamNumber = config.getInt("player", "TeamNumber");
  } else
  {
    std::cerr << "No team number (TeamNumber) given" << std::endl;
    getPlayerInfo().teamNumber = 0;
  }
} // end loadPlayerInfoFromFile

void GameController::readButtons()
{

  // state change?
  if (getButtonData().eventCounter[ButtonData::Chest] > lastChestButtonEventCounter )
  {
    lastChestButtonEventCounter = getButtonData().eventCounter[ButtonData::Chest];
    switch (getPlayerInfo().gameState)
    {
      case PlayerInfo::inital :

          getPlayerInfo().gameState = PlayerInfo::penalized;
        break;
      case PlayerInfo::playing :

          getPlayerInfo().gameState = PlayerInfo::penalized;
        break;
      case PlayerInfo::penalized :

          getPlayerInfo().gameState = PlayerInfo::playing;
        break;
     default:
        break;
    }
  }

  // re-set team color or kickoff in initial
  if (getPlayerInfo().gameState == PlayerInfo::inital)
  {
    if (getButtonData().numOfFramesPressed[ButtonData::LeftFootLeft] == 1
      || getButtonData().numOfFramesPressed[ButtonData::LeftFootRight] == 1)
    {
      // switch team color
      PlayerInfo::TeamColor oldColor = getPlayerInfo().teamColor;
      if (oldColor == PlayerInfo::blue)
      {
        getPlayerInfo().teamColor = PlayerInfo::red;
      }
      else if (oldColor == PlayerInfo::red)
      {
        getPlayerInfo().teamColor = PlayerInfo::blue;
      }
    }

    if (getButtonData().numOfFramesPressed[ButtonData::RightFootLeft] == 1
      || getButtonData().numOfFramesPressed[ButtonData::RightFootRight] == 1)
    {
      // switch kickof team
      getPlayerInfo().ownKickOff = !getPlayerInfo().ownKickOff;
    }
  }
    // go back from penalized to initial both foot bumpers are pressed for over 30 frames
  else if (getPlayerInfo()  .gameState == PlayerInfo::penalized &&
    (getButtonData().numOfFramesPressed[ButtonData::LeftFootLeft] > 30
    || getButtonData().numOfFramesPressed[ButtonData::LeftFootRight] > 30
    )
    &&
    (getButtonData().numOfFramesPressed[ButtonData::RightFootLeft] > 30
    || getButtonData().numOfFramesPressed[ButtonData::RightFootRight] > 30
    )
    )
  {
    getPlayerInfo().gameState = PlayerInfo::inital;
  }

} // end readButtons

void GameController::readWLAN()
{
  // TODO: WLAN GameController support
}

void GameController::execute()
{
  PlayerInfo::GameState oldState = getPlayerInfo().gameState;
  PlayerInfo::TeamColor oldTeamColor = getPlayerInfo().teamColor;
  bool oldOwnKickOff = getPlayerInfo().ownKickOff;

  readButtons();

  DEBUG_REQUEST("gamecontroller:initial",
    getPlayerInfo().gameState = PlayerInfo::inital;
  );
  DEBUG_REQUEST("gamecontroller:ready",
    getPlayerInfo().gameState = PlayerInfo::ready;
  );
  DEBUG_REQUEST("gamecontroller:set",
    getPlayerInfo().gameState = PlayerInfo::set;
  );
  DEBUG_REQUEST("gamecontroller:play",
    getPlayerInfo().gameState = PlayerInfo::playing;
  );
  DEBUG_REQUEST("gamecontroller:penalized",
    getPlayerInfo().gameState = PlayerInfo::penalized;
  );

} // end execute

void GameController::updateLEDs()
{
  // reset
  getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 0.0;

  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.0;

  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 0.0;

  // show game state in torso
  switch (getPlayerInfo().gameState)
  {
    case PlayerInfo::ready :
      std::cout << "in ready" << std::endl;
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 1.0;
      break;
    case PlayerInfo::set :
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;
      getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;
      break;
    case PlayerInfo::playing :
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;
      break;
    case PlayerInfo::penalized :
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;
      break;
    default:
      break;
  }

  // show team color on left foot
  if (getPlayerInfo().teamColor == PlayerInfo::red)
  {
    getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 1.0;
  }
  else if (getPlayerInfo().teamColor == PlayerInfo::blue)
  {
    getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 1.0;
  }

  // show kickoff state on right foot in initial, ready and set
  if (getPlayerInfo().gameState == PlayerInfo::inital
    || getPlayerInfo().gameState == PlayerInfo::ready
    || getPlayerInfo().gameState == PlayerInfo::set)
  {
    if (getPlayerInfo().ownKickOff)
    {
      getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.7;
      getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 1.0;
      getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 1.0;
    }
  }
} // end updateLEDs

GameController::~GameController()
{
}
<commit_msg>updateLEDs<commit_after>#include "GameController.h"

#include "Tools/Debug/DebugRequest.h"
#include <Representations/Infrastructure/Configuration.h>
#include <PlatformInterface/Platform.h>

GameController::GameController()
  : lastChestButtonEventCounter(0)
{
  DEBUG_REQUEST_REGISTER("gamecontroller:play", "force the play state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:penalized", "force the penalized state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:initial", "force the initial state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:ready", "force the ready state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:set", "force the set state", false);

  loadPlayerInfoFromFile();
}

void GameController::loadPlayerInfoFromFile()
{
  // load player.cfg
  naoth::Configuration& config = naoth::Platform::getInstance().theConfiguration;

  if (config.hasKey("player", "NumOfPlayer"))
  {
    getPlayerInfo().numOfPlayers = config.getInt("player", "NumOfPlayer");
  } else
  {
    std::cerr << "No number of players (NumOfPlayers) given" << std::endl;
  }

  if (config.hasKey("player", "PlayerNumber"))
  {
    getPlayerInfo().playerNumber = config.getInt("player", "PlayerNumber");
  } else
  {
    std::cerr << "No player number (PlayerNumber) given" << std::endl;
    getPlayerInfo().playerNumber = 3;
  }

  if (config.hasKey("player", "TeamColor"))
  {
    getPlayerInfo().teamColor = PlayerInfo::teamColorFromString(config.getString("player", "TeamColor"));
    if (getPlayerInfo().teamColor == PlayerInfo::numOfTeamColor)
    {
      getPlayerInfo().teamColor = PlayerInfo::red;
      std::cerr << "Invalid team color (TeamColor) \""
        << config.getString("player", "TeamColor") << "\" given" << std::endl;
    }
  } else
  {
    std::cerr << "No team color (TeamColor) given" << std::endl;
    getPlayerInfo().teamColor = PlayerInfo::red;
  }

  if (config.hasKey("player", "TeamNumber"))
  {
    getPlayerInfo().teamNumber = config.getInt("player", "TeamNumber");
  } else
  {
    std::cerr << "No team number (TeamNumber) given" << std::endl;
    getPlayerInfo().teamNumber = 0;
  }
} // end loadPlayerInfoFromFile

void GameController::readButtons()
{

  // state change?
  if (getButtonData().eventCounter[ButtonData::Chest] > lastChestButtonEventCounter )
  {
    lastChestButtonEventCounter = getButtonData().eventCounter[ButtonData::Chest];
    switch (getPlayerInfo().gameState)
    {
      case PlayerInfo::inital :

          getPlayerInfo().gameState = PlayerInfo::penalized;
        break;
      case PlayerInfo::playing :

          getPlayerInfo().gameState = PlayerInfo::penalized;
        break;
      case PlayerInfo::penalized :

          getPlayerInfo().gameState = PlayerInfo::playing;
        break;
     default:
        break;
    }
  }

  // re-set team color or kickoff in initial
  if (getPlayerInfo().gameState == PlayerInfo::inital)
  {
    if (getButtonData().numOfFramesPressed[ButtonData::LeftFootLeft] == 1
      || getButtonData().numOfFramesPressed[ButtonData::LeftFootRight] == 1)
    {
      // switch team color
      PlayerInfo::TeamColor oldColor = getPlayerInfo().teamColor;
      if (oldColor == PlayerInfo::blue)
      {
        getPlayerInfo().teamColor = PlayerInfo::red;
      }
      else if (oldColor == PlayerInfo::red)
      {
        getPlayerInfo().teamColor = PlayerInfo::blue;
      }
    }

    if (getButtonData().numOfFramesPressed[ButtonData::RightFootLeft] == 1
      || getButtonData().numOfFramesPressed[ButtonData::RightFootRight] == 1)
    {
      // switch kickof team
      getPlayerInfo().ownKickOff = !getPlayerInfo().ownKickOff;
    }
  }
    // go back from penalized to initial both foot bumpers are pressed for over 30 frames
  else if (getPlayerInfo()  .gameState == PlayerInfo::penalized &&
    (getButtonData().numOfFramesPressed[ButtonData::LeftFootLeft] > 30
    || getButtonData().numOfFramesPressed[ButtonData::LeftFootRight] > 30
    )
    &&
    (getButtonData().numOfFramesPressed[ButtonData::RightFootLeft] > 30
    || getButtonData().numOfFramesPressed[ButtonData::RightFootRight] > 30
    )
    )
  {
    getPlayerInfo().gameState = PlayerInfo::inital;
  }

} // end readButtons

void GameController::readWLAN()
{
  // TODO: WLAN GameController support
}

void GameController::execute()
{
  PlayerInfo::GameState oldState = getPlayerInfo().gameState;
  PlayerInfo::TeamColor oldTeamColor = getPlayerInfo().teamColor;
  bool oldOwnKickOff = getPlayerInfo().ownKickOff;

  readButtons();

  DEBUG_REQUEST("gamecontroller:initial",
    getPlayerInfo().gameState = PlayerInfo::inital;
  );
  DEBUG_REQUEST("gamecontroller:ready",
    getPlayerInfo().gameState = PlayerInfo::ready;
  );
  DEBUG_REQUEST("gamecontroller:set",
    getPlayerInfo().gameState = PlayerInfo::set;
  );
  DEBUG_REQUEST("gamecontroller:play",
    getPlayerInfo().gameState = PlayerInfo::playing;
  );
  DEBUG_REQUEST("gamecontroller:penalized",
    getPlayerInfo().gameState = PlayerInfo::penalized;
  );

  if(oldState != getPlayerInfo().gameState
    || oldTeamColor != getPlayerInfo().teamColor
    || oldOwnKickOff != getPlayerInfo().ownKickOff
    || getPlayerInfo().gameState == PlayerInfo::inital)
  {
    updateLEDs();
  }

} // end execute

void GameController::updateLEDs()
{
  // reset
  getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 0.0;

  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.0;

  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 0.0;

  // show game state in torso
  switch (getPlayerInfo().gameState)
  {
    case PlayerInfo::ready :
      std::cout << "in ready" << std::endl;
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 1.0;
      break;
    case PlayerInfo::set :
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;
      getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;
      break;
    case PlayerInfo::playing :
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;
      break;
    case PlayerInfo::penalized :
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;
      break;
    default:
      break;
  }

  // show team color on left foot
  if (getPlayerInfo().teamColor == PlayerInfo::red)
  {
    getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 1.0;
  }
  else if (getPlayerInfo().teamColor == PlayerInfo::blue)
  {
    getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 1.0;
  }

  // show kickoff state on right foot in initial, ready and set
  if (getPlayerInfo().gameState == PlayerInfo::inital
    || getPlayerInfo().gameState == PlayerInfo::ready
    || getPlayerInfo().gameState == PlayerInfo::set)
  {
    if (getPlayerInfo().ownKickOff)
    {
      getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.7;
      getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 1.0;
      getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 1.0;
    }
  }
} // end updateLEDs

GameController::~GameController()
{
}
<|endoftext|>


<commit_before>#include "../test.h"
#include <QFile>
#include "../../src/placement/constraint_updater.h"
#include "../../src/graphics/qimage_drawer.h"

TEST(Test_ConstraintUpdater, Draw)
{
  int width = 512;
  int height = 256;
  auto drawer = std::make_shared<Graphics::QImageDrawer>(width, height);
  ConstraintUpdater constraintUpdater(drawer, width, height);

  constraintUpdater.clear();

  Eigen::Vector2i anchorPosition(100, 50);
  Eigen::Vector2i labelSize(62, 20);
  Eigen::Vector2i lastAnchorPosition(200, 70);
  Eigen::Vector2i lastLabelPosition(150, 120);
  Eigen::Vector2i lastLabelSize(60, 40);
  constraintUpdater.drawConstraintRegionFor(anchorPosition, labelSize,
                                            lastAnchorPosition,
                                            lastLabelPosition, lastLabelSize);

  drawer->image->save("constraints.png");

  QFile expectedFile("expected-constraints.png");
  ASSERT_TRUE(expectedFile.exists())
      << "File 'expected-constraints.png' does not "
         "exists. Check 'constraints.png' and "
         "rename it if it is correct.";

  QImage expectedImage(expectedFile.fileName());
  ASSERT_EQ(expectedImage.width(), drawer->image->width());
  ASSERT_EQ(expectedImage.height(), drawer->image->height());

  for (int y = 0; y < expectedImage.width(); ++y)
    for (int x = 0; x < expectedImage.width(); ++x)
      EXPECT_EQ(expectedImage.pixel(x, y), drawer->image->pixel(x, y));
}

<commit_msg>Fix ConstraintUpdater test and add another test case.<commit_after>#include "../test.h"
#include <QFile>
#include "../../src/placement/constraint_updater.h"
#include "../../src/graphics/qimage_drawer.h"

TEST(Test_ConstraintUpdater, DrawWithConnectorShadows)
{
  int width = 512;
  int height = 256;
  auto drawer = std::make_shared<Graphics::QImageDrawer>(width, height);
  ConstraintUpdater constraintUpdater(drawer, width, height);
  constraintUpdater.setIsConnectorShadowEnabled(true);

  constraintUpdater.clear();

  Eigen::Vector2i anchorPosition(100, 50);
  Eigen::Vector2i labelSize(62, 20);
  Eigen::Vector2i lastAnchorPosition(200, 70);
  Eigen::Vector2i lastLabelPosition(150, 120);
  Eigen::Vector2i lastLabelSize(60, 40);
  constraintUpdater.drawConstraintRegionFor(anchorPosition, labelSize,
                                            lastAnchorPosition,
                                            lastLabelPosition, lastLabelSize);

  drawer->image->save("constraints-with-connectors.png");

  QFile expectedFile("expected-constraints-with-connectors.png");
  ASSERT_TRUE(expectedFile.exists())
      << "File 'expected-constraints.png' does not "
         "exists. Check 'constraints.png' and "
         "rename it if it is correct.";

  QImage expectedImage(expectedFile.fileName());
  ASSERT_EQ(expectedImage.width(), drawer->image->width());
  ASSERT_EQ(expectedImage.height(), drawer->image->height());

  for (int y = 0; y < expectedImage.width(); ++y)
    for (int x = 0; x < expectedImage.width(); ++x)
      EXPECT_EQ(expectedImage.pixel(x, y), drawer->image->pixel(x, y));
}

TEST(Test_ConstraintUpdater, DrawWithoutConnectorShadows)
{
  int width = 512;
  int height = 256;
  auto drawer = std::make_shared<Graphics::QImageDrawer>(width, height);
  ConstraintUpdater constraintUpdater(drawer, width, height);
  constraintUpdater.setIsConnectorShadowEnabled(false);

  constraintUpdater.clear();

  Eigen::Vector2i anchorPosition(100, 50);
  Eigen::Vector2i labelSize(62, 20);
  Eigen::Vector2i lastAnchorPosition(200, 70);
  Eigen::Vector2i lastLabelPosition(150, 120);
  Eigen::Vector2i lastLabelSize(60, 40);
  constraintUpdater.drawConstraintRegionFor(anchorPosition, labelSize,
                                            lastAnchorPosition,
                                            lastLabelPosition, lastLabelSize);

  drawer->image->save("constraints-without-connectors.png");

  QFile expectedFile("expected-constraints-without-connectors.png");
  ASSERT_TRUE(expectedFile.exists())
      << "File 'expected-constraints.png' does not "
         "exists. Check 'constraints.png' and "
         "rename it if it is correct.";

  QImage expectedImage(expectedFile.fileName());
  ASSERT_EQ(expectedImage.width(), drawer->image->width());
  ASSERT_EQ(expectedImage.height(), drawer->image->height());

  for (int y = 0; y < expectedImage.width(); ++y)
    for (int x = 0; x < expectedImage.width(); ++x)
      EXPECT_EQ(expectedImage.pixel(x, y), drawer->image->pixel(x, y));
}
<|endoftext|>


<commit_before>
#include <irtkImage.h>
#include <nr.h>

#include <irtkModeFilter.h>

#include <map>

#ifdef WIN32
#include <time.h>
#else
#include <sys/time.h>
#endif

template <class VoxelType> irtkModeFilter<VoxelType>::irtkModeFilter()
{
	// Default connectivity.
	this->_Connectivity = CONNECTIVITY_26;
}

template <class VoxelType> irtkModeFilter<VoxelType>::~irtkModeFilter(void)
{
}

template <class VoxelType> bool irtkModeFilter<VoxelType>::RequiresBuffering(void)
{
  return true;
}

template <class VoxelType> const char *irtkModeFilter<VoxelType>::NameOfClass()
{
  return "irtkModeFilter";
}

template <class VoxelType> void irtkModeFilter<VoxelType>::Initialize()
{
  // Do the initial set up
  this->irtkImageToImage<VoxelType>::Initialize();

  this->_offsets.Initialize(this->_input, this->_Connectivity);
}

template <class VoxelType> void irtkModeFilter<VoxelType>::Run()
{
  int i, x, y, z, t, maskSize;
  VoxelType value;
  VoxelType *ptr2current, *ptr2offset;

  map<short, short> labelCount;
  map<short, short>::iterator iter;
  int ties, maxCount;
  short mode = 0;
  double inputMin, inputMax;

  int *tiedLabels;

  int randChoice;
  long ran2Seed;
  long ran2initialSeed;

  // Do the initial set up
  this->Initialize();

  // Get ready for random stuff.
  time_t tv;
  tv = time(NULL);

  ran2Seed = tv;
  ran2initialSeed = -1 * ran2Seed;
  (void) ran2(&ran2initialSeed);

  this->_input->GetMinMaxAsDouble(&inputMin, &inputMax);
  tiedLabels = new int[(int) inputMax];

  maskSize = this->_offsets.GetSize();

  for (t = 0; t < this->_input->GetT(); t++) {

    for (z = 0; z < this->_input->GetZ(); z++) {
      for (y = 0; y < this->_input->GetY(); y++) {
        this->_output->Put(0, y, z, t, this->_input->Get(0, y, z, t));
      }
    }

    for (z = 0; z < this->_input->GetZ(); z++) {
      for (x = 0; x < this->_input->GetX(); x++) {
        this->_output->Put(x, 0, z, t, this->_input->Get(x, 0, z, t));
      }
    }

    for (y = 0; y < this->_input->GetY(); y++) {
      for (x = 0; x < this->_input->GetX(); x++) {
        this->_output->Put(x, y, 0, t, this->_input->Get(x, y, 0, t));
      }
    }

    for (z = 1; z < this->_input->GetZ() - 1; z++) {
      for (y = 1; y < this->_input->GetY() - 1; y++) {
        for (x = 1; x < this->_input->GetX() - 1; x++) {

          labelCount.clear();

          ptr2current = this->_input->GetPointerToVoxels(x, y, z, t);

          // Collect labels from neighbourhood.
          for (i = 0; i < maskSize; ++i) {
            ptr2offset = ptr2current + this->_offsets(i);
            labelCount[*ptr2offset]++;
          }

          // Seek modal label (but there may be ties for the mode)
          maxCount = 0;
          for (iter = labelCount.begin(); iter != labelCount.end(); ++iter){
            if (iter->second > maxCount){
              maxCount = iter->second;
              mode     = iter->first;
            }
          }

          ties = 0;
          for (iter = labelCount.begin(); iter != labelCount.end(); ++iter){
            if (iter->second == maxCount){
              tiedLabels[ties] = iter->first;
              ++ties;
            }
          }

          if (ties > 1){
            randChoice = (int) floor( ran2(&ran2Seed) * ties );
            value = tiedLabels[ randChoice ];
          } else {
            value = mode;
          }

          this->_output->Put(x, y, z, t, value);
        }
      }
    }
  }

  delete [] tiedLabels;

  // Do the final cleaning up
  this->Finalize();
}

template class irtkModeFilter<irtkBytePixel>;
template class irtkModeFilter<irtkGreyPixel>;
<commit_msg>Replaced recipes ran2 function in irtkModeFilter.cc<commit_after>
#include <irtkImage.h>
#include <boost/random.hpp>
#include <boost/random/uniform_int.hpp>

#include <irtkModeFilter.h>

#include <map>

#ifdef WIN32
#include <time.h>
#else
#include <sys/time.h>
#endif

template <class VoxelType> irtkModeFilter<VoxelType>::irtkModeFilter()
{
	// Default connectivity.
	this->_Connectivity = CONNECTIVITY_26;
}

template <class VoxelType> irtkModeFilter<VoxelType>::~irtkModeFilter(void)
{
}

template <class VoxelType> bool irtkModeFilter<VoxelType>::RequiresBuffering(void)
{
  return true;
}

template <class VoxelType> const char *irtkModeFilter<VoxelType>::NameOfClass()
{
  return "irtkModeFilter";
}

template <class VoxelType> void irtkModeFilter<VoxelType>::Initialize()
{
  // Do the initial set up
  this->irtkImageToImage<VoxelType>::Initialize();

  this->_offsets.Initialize(this->_input, this->_Connectivity);
}

template <class VoxelType> void irtkModeFilter<VoxelType>::Run()
{
  int i, x, y, z, t, maskSize;
  VoxelType value;
  VoxelType *ptr2current, *ptr2offset;

  map<short, short> labelCount;
  map<short, short>::iterator iter;
  int ties, maxCount;
  short mode = 0;
  double inputMin, inputMax;

  int *tiedLabels;

  int randChoice;

  // Do the initial set up
  this->Initialize();

  // Get ready for random stuff.
  long inSeed = time(NULL);
  boost::mt19937 rng;
  rng.seed(inSeed);

  boost::uniform_int<> ud(0, 1);
  boost::variate_generator<boost::mt19937&, boost::uniform_int<> > engine(rng, ud);

  (void) engine();

  this->_input->GetMinMaxAsDouble(&inputMin, &inputMax);
  tiedLabels = new int[(int) inputMax];

  maskSize = this->_offsets.GetSize();

  for (t = 0; t < this->_input->GetT(); t++) {

    for (z = 0; z < this->_input->GetZ(); z++) {
      for (y = 0; y < this->_input->GetY(); y++) {
        this->_output->Put(0, y, z, t, this->_input->Get(0, y, z, t));
      }
    }

    for (z = 0; z < this->_input->GetZ(); z++) {
      for (x = 0; x < this->_input->GetX(); x++) {
        this->_output->Put(x, 0, z, t, this->_input->Get(x, 0, z, t));
      }
    }

    for (y = 0; y < this->_input->GetY(); y++) {
      for (x = 0; x < this->_input->GetX(); x++) {
        this->_output->Put(x, y, 0, t, this->_input->Get(x, y, 0, t));
      }
    }

    for (z = 1; z < this->_input->GetZ() - 1; z++) {
      for (y = 1; y < this->_input->GetY() - 1; y++) {
        for (x = 1; x < this->_input->GetX() - 1; x++) {

          labelCount.clear();

          ptr2current = this->_input->GetPointerToVoxels(x, y, z, t);

          // Collect labels from neighbourhood.
          for (i = 0; i < maskSize; ++i) {
            ptr2offset = ptr2current + this->_offsets(i);
            labelCount[*ptr2offset]++;
          }

          // Seek modal label (but there may be ties for the mode)
          maxCount = 0;
          for (iter = labelCount.begin(); iter != labelCount.end(); ++iter){
            if (iter->second > maxCount){
              maxCount = iter->second;
              mode     = iter->first;
            }
          }

          ties = 0;
          for (iter = labelCount.begin(); iter != labelCount.end(); ++iter){
            if (iter->second == maxCount){
              tiedLabels[ties] = iter->first;
              ++ties;
            }
          }

          if (ties > 1){
            randChoice = (int) floor( engine() * ties );
            value = tiedLabels[ randChoice ];
          } else {
            value = mode;
          }

          this->_output->Put(x, y, z, t, value);
        }
      }
    }
  }

  delete [] tiedLabels;

  // Do the final cleaning up
  this->Finalize();
}

template class irtkModeFilter<irtkBytePixel>;
template class irtkModeFilter<irtkGreyPixel>;
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2022.  All rights reserved
 */
#ifndef _Stroika_Foundation_Cryptography_Digest_ResultTypes_inl_
#define _Stroika_Foundation_Cryptography_Digest_ResultTypes_inl_ 1
/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

#include <type_traits>

#include "../Format.h"

namespace Stroika::Foundation::Cryptography::Digest {

    namespace Private_ {
        // Try to use simple constuction of result from argument if possible
        template <typename OUT_RESULT, typename IN_RESULT>
        constexpr OUT_RESULT mkReturnType_ (IN_RESULT hashVal, enable_if_t<is_constructible_v<OUT_RESULT, IN_RESULT>, void>* = nullptr)
        {
            return OUT_RESULT (hashVal); // intentionally allow narrowing conversions (so () not {})
        }
        // Else if both (IN AND OUT) values trivially copyable, use memcpy (and zero fill result as needed)
        template <typename OUT_RESULT, typename IN_RESULT>
        OUT_RESULT mkReturnType_ (IN_RESULT hashVal,
                                  enable_if_t<
                                      not is_constructible_v<OUT_RESULT, IN_RESULT> and (is_trivially_copyable_v<IN_RESULT> and is_trivially_copyable_v<OUT_RESULT>), char>* = nullptr)
        {
            size_t     mBytes2Copy = std::min (sizeof (OUT_RESULT), sizeof (IN_RESULT));
            OUT_RESULT result{}; // zero initialize non-copied bits (@todo could just zero-fill end bits)
            DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Wclass-memaccess\"")     // memcpy only requires trivially_copyable, not is_trivial
            ::memcpy (&result, &hashVal, mBytes2Copy);
            DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Wclass-memaccess\"")
            return result;
        }
        // NOTE - mkReturnType1_<string,XXX> () here uses enable_if and is_same, since C++ doesn't currently allow partial function template
        // specialization -- LGP 2020-10-02
        template <typename OUT_RESULT, typename IN_RESULT>
        inline OUT_RESULT mkReturnType_ (IN_RESULT hashVal, enable_if_t<not is_constructible_v<OUT_RESULT, IN_RESULT> and
                                                                            not(is_trivially_copyable_v<IN_RESULT> and is_trivially_copyable_v<OUT_RESULT>) and
                                                                            (is_same_v<OUT_RESULT, string> or is_same_v<OUT_RESULT, Characters::String> or is_same_v<OUT_RESULT, Common::GUID>),
                                                                        short>* = nullptr)
        {
            return Format<OUT_RESULT> (hashVal);
        }
    }

    template <typename OUT_RESULT, typename IN_RESULT>
    constexpr OUT_RESULT ConvertResult (IN_RESULT inResult)
    {
        return Private_::mkReturnType_<OUT_RESULT> (inResult);
    }

}

#endif /*_Stroika_Foundation_Cryptography_Digest_ResultTypes_inl_*/
<commit_msg>format<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2022.  All rights reserved
 */
#ifndef _Stroika_Foundation_Cryptography_Digest_ResultTypes_inl_
#define _Stroika_Foundation_Cryptography_Digest_ResultTypes_inl_ 1
/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */

#include <type_traits>

#include "../Format.h"

namespace Stroika::Foundation::Cryptography::Digest {

    namespace Private_ {
        // Try to use simple constuction of result from argument if possible
        template <typename OUT_RESULT, typename IN_RESULT>
        constexpr OUT_RESULT mkReturnType_ (IN_RESULT hashVal, enable_if_t<is_constructible_v<OUT_RESULT, IN_RESULT>, void>* = nullptr)
        {
            return OUT_RESULT (hashVal); // intentionally allow narrowing conversions (so () not {})
        }
        // Else if both (IN AND OUT) values trivially copyable, use memcpy (and zero fill result as needed)
        template <typename OUT_RESULT, typename IN_RESULT>
        OUT_RESULT mkReturnType_ (IN_RESULT hashVal,
                                  enable_if_t<
                                      not is_constructible_v<OUT_RESULT, IN_RESULT> and (is_trivially_copyable_v<IN_RESULT> and is_trivially_copyable_v<OUT_RESULT>), char>* = nullptr)
        {
            size_t     mBytes2Copy = std::min (sizeof (OUT_RESULT), sizeof (IN_RESULT));
            OUT_RESULT result{};                                                                // zero initialize non-copied bits (@todo could just zero-fill end bits)
            DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Wclass-memaccess\"") // memcpy only requires trivially_copyable, not is_trivial
            ::memcpy (&result, &hashVal, mBytes2Copy);
            DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Wclass-memaccess\"")
            return result;
        }
        // NOTE - mkReturnType1_<string,XXX> () here uses enable_if and is_same, since C++ doesn't currently allow partial function template
        // specialization -- LGP 2020-10-02
        template <typename OUT_RESULT, typename IN_RESULT>
        inline OUT_RESULT mkReturnType_ (IN_RESULT hashVal, enable_if_t<not is_constructible_v<OUT_RESULT, IN_RESULT> and
                                                                            not(is_trivially_copyable_v<IN_RESULT> and is_trivially_copyable_v<OUT_RESULT>) and
                                                                            (is_same_v<OUT_RESULT, string> or is_same_v<OUT_RESULT, Characters::String> or is_same_v<OUT_RESULT, Common::GUID>),
                                                                        short>* = nullptr)
        {
            return Format<OUT_RESULT> (hashVal);
        }
    }

    template <typename OUT_RESULT, typename IN_RESULT>
    constexpr OUT_RESULT ConvertResult (IN_RESULT inResult)
    {
        return Private_::mkReturnType_<OUT_RESULT> (inResult);
    }

}

#endif /*_Stroika_Foundation_Cryptography_Digest_ResultTypes_inl_*/
<|endoftext|>