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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkNavigationDataSmoothingFilter.h"

mitk::NavigationDataSmoothingFilter::NavigationDataSmoothingFilter()
: mitk::NavigationDataToNavigationDataFilter()
{
m_NumerOfValues = 5;
}

mitk::NavigationDataSmoothingFilter::~NavigationDataSmoothingFilter()
{
}

void mitk::NavigationDataSmoothingFilter::GenerateData()
{
  if (GetNumberOfInputs()==0) return;

  this->CreateOutputsForAllInputs();

  //initialize list if nessesary
  if (m_LastValuesList.empty() || (m_LastValuesList.size() != this->GetNumberOfInputs()))
    {InitializeLastValuesList();}

  //add current value to list
  for (unsigned int i = 0; i < this->GetNumberOfOutputs() ; ++i)
    {AddValue(i,this->GetInput(i)->GetPosition());}

  //generate output
  for (unsigned int i = 0; i < this->GetNumberOfOutputs() ; ++i)
  {
    const mitk::NavigationData* nd = this->GetInput(i);
    assert(nd);

    mitk::NavigationData* output = this->GetOutput(i);
    assert(output);

    output->Graft(nd); // copy all information from input to output

    output->SetPosition(GetMean(i));

    output->SetDataValid(nd->IsDataValid());
  }
}

void mitk::NavigationDataSmoothingFilter::InitializeLastValuesList()
{
    m_LastValuesList = std::map< int, std::map< int , mitk::Point3D> >();
    for (int i = 0; i < this->GetNumberOfOutputs();i++)
      {
      std::map<int,mitk::Point3D> currentList;
      for (int j = 0; j < m_NumerOfValues; j++)
        {
        mitk::Point3D emptyPoint;
        emptyPoint.Fill(0);
        currentList.insert(std::pair<int, mitk::Point3D>(j, emptyPoint));
        }
      m_LastValuesList.insert(std::pair<int, std::map<int,mitk::Point3D> > (i,currentList));
      }
}

void mitk::NavigationDataSmoothingFilter::AddValue(int outputID, mitk::Point3D value)
  {
  for (int i=1; i<(m_NumerOfValues-1); i++) {m_LastValuesList[outputID][i-1] = m_LastValuesList[outputID][i];}
  m_LastValuesList[outputID][m_NumerOfValues-1] = value;
  }

mitk::Point3D mitk::NavigationDataSmoothingFilter::GetMean(int outputID)
  {
  mitk::Point3D mean;
  mean.Fill(0);
  for (int i=1; i<m_NumerOfValues; i++)
    {
    mean[0] += m_LastValuesList[outputID][i][0];
    mean[1] += m_LastValuesList[outputID][i][1];
    mean[2] += m_LastValuesList[outputID][i][2];
    }
  mean[0] /= m_NumerOfValues;
  mean[1] /= m_NumerOfValues;
  mean[2] /= m_NumerOfValues;
  return mean;
  }
<commit_msg>Fixed loop indices of smoothing filter + some code cleanup.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkNavigationDataSmoothingFilter.h"

mitk::NavigationDataSmoothingFilter::NavigationDataSmoothingFilter()
  : mitk::NavigationDataToNavigationDataFilter(),
    m_NumerOfValues(5)
{
}

mitk::NavigationDataSmoothingFilter::~NavigationDataSmoothingFilter()
{
}

void mitk::NavigationDataSmoothingFilter::GenerateData()
{
  DataObjectPointerArraySizeType numberOfInputs = this->GetNumberOfInputs();

  if ( numberOfInputs == 0 ) return;

  this->CreateOutputsForAllInputs();

  //initialize list if nessesary
  if ( m_LastValuesList.size() != numberOfInputs )
  {
    this->InitializeLastValuesList();
  }

  //add current value to list
  for ( unsigned int i = 0; i < numberOfInputs; ++i )
  {
    this->AddValue(i,this->GetInput(i)->GetPosition());
  }

  //generate output
  for (unsigned int i = 0; i < numberOfInputs; ++i)
  {
    const mitk::NavigationData* nd = this->GetInput(i);
    assert(nd);

    mitk::NavigationData* output = this->GetOutput(i);
    assert(output);

    output->Graft(nd); // copy all information from input to output

    output->SetPosition(GetMean(i));

    output->SetDataValid(nd->IsDataValid());
  }
}

void mitk::NavigationDataSmoothingFilter::InitializeLastValuesList()
{
  m_LastValuesList = std::map< int, std::map< int , mitk::Point3D> >();

  for ( int i = 0; i < this->GetNumberOfOutputs(); ++i )
  {
    std::map<int,mitk::Point3D> currentList;
    for ( int j = 0; j < m_NumerOfValues; ++j )
    {
      mitk::Point3D emptyPoint;
      emptyPoint.Fill(0);
      currentList.insert(std::pair<int, mitk::Point3D>(j, emptyPoint));
    }
    m_LastValuesList.insert(std::pair<int, std::map<int,mitk::Point3D> > (i,currentList));
  }
}

void mitk::NavigationDataSmoothingFilter::AddValue(int outputID, mitk::Point3D value)
{
  for (int i = 1; i < m_NumerOfValues; ++i)
  {
    m_LastValuesList[outputID][i-1] = m_LastValuesList[outputID][i];
  }

  m_LastValuesList[outputID][m_NumerOfValues-1] = value;
}

mitk::Point3D mitk::NavigationDataSmoothingFilter::GetMean(int outputID)
{
  mitk::Point3D mean;
  mean.Fill(0);
  for (int i=0; i<m_NumerOfValues; i++)
  {
    mean[0] += m_LastValuesList[outputID][i][0];
    mean[1] += m_LastValuesList[outputID][i][1];
    mean[2] += m_LastValuesList[outputID][i][2];
  }
  mean[0] /= m_NumerOfValues;
  mean[1] /= m_NumerOfValues;
  mean[2] /= m_NumerOfValues;
  return mean;
}
<|endoftext|>


<commit_before>#ifndef CONTROLADOR
#define CONTROLADOR

#include "FifoLectura.h"
#include "Avion.h"
#include <string>
#include "Utilitario.h"
#include "Process.h"
#include "FifoEscritura.h"
#include <iostream>
#include <queue>
#include "Logger.h"

#define TAG "ResolvedorPeticiones"

#define LOG(X) Logger::instance().debug(TAG + numero, X)

int main(int argc, char** argv) {

	Utilitario u;
	std::string numero(argv[1]);
	LOG("resolvedorPeticiones argv[1] = " + numero);
	static const std::string FIFO_RESOLVEDOR = "/tmp/fifo_controlador_" + numero;
	static const std::string FIFO_CONSUMIDOR = "/tmp/fifo_controladorc_" + numero;

	std::priority_queue<Avion> prioridadAviones;
	LOG("por lanzar el consumidor " + numero);
	Process consumidor("controlador/consumidorPeticiones", u.convertirAEntero(numero));
	LOG("consumidor "+numero+" iniciado");
	LOG("Por abrir fifo consumer " + numero);
	FifoEscritura fifoConsumer(FIFO_CONSUMIDOR);
	fifoConsumer.abrir();
	LOG("abierta la fifo del consumer " + numero);
	int resultado = 1;
	FifoLectura fifo(FIFO_RESOLVEDOR);
	LOG("por abrir la fifo lectura " + numero);
	fifo.abrir();
	LOG("abierta la fifo en resolvedor peticiones " + numero);
	do {
		char* ptr = new char[32];
		resultado = fifo.leer(ptr, (ssize_t) 32);
		ptr[31] = '\0';
		if (resultado > 0) {
			LOG("leido " + std::string(ptr));
			Avion avioneta(ptr);
			prioridadAviones.push(avioneta);
			Avion avioneta2 = prioridadAviones.top();
			prioridadAviones.pop();
			const char* serial = avioneta2.serializar();
			LOG("por recepcionar " + std::string(serial));
			resultado &= fifoConsumer.escribir(serial, (ssize_t) 32) > 0;
			delete[] serial;
		} else {
			LOG("leido EOF del resolvedor");
		}
		delete ptr;
	} while(resultado > 0);
	while(prioridadAviones.size() > 0) {
		Avion avioneta2 = prioridadAviones.top();
		prioridadAviones.pop();
		const char* serial = avioneta2.serializar();
		LOG("por recepcionar " + std::string(serial));
		resultado &= fifoConsumer.escribir(serial, (ssize_t) 32) > 0;
		delete[] serial;
	}
	Logger::instance().info(TAG + numero, "saliendo del resolvedor de peticiones");
	fifoConsumer.cerrar();
	Logger::instance().info(TAG + numero, "fifo consumer cerrado");
	fifo.cerrar();
	consumidor.wait();
	Logger::instance().info(TAG + numero, "fifo entrada cerrado");
	fifo.eliminar();
	return 0;
}

#endif
<commit_msg>eliminado el resolvedor<commit_after><|endoftext|>


<commit_before>AliAnalysisTask *AddTask_tbroeker_lowmasspPb(Bool_t getFromAlien=kFALSE,TString cFileName = "Config_tbroeker_lowmasspPb.C",Char_t* outputFileName="LMEEoutput.root"){

  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_lowmass", "No analysis manager found.");
    return 0;
  }

  //Do we have an MC handler?
  Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);

  //Base Directory for GRID / LEGO Train
  TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/";

  if(getFromAlien && (!gSystem->Exec("alien_cp alien:///alice/cern.ch/user/t/tbroker/PWGDQ/dielectron/macrosLMEE/Config_lowmasspPb.C .")) ){
    TString configBasePath=Form("%s/",gSystem->pwd());
  }

  TString configFilePath(configBasePath+cFileName);

  //if (!gROOT->GetListOfGlobalFunctions()->FindObject(cFileName.Data()))
  gROOT->LoadMacro(configFilePath.Data());

  //create task and add it to the manager (MB)
  AliAnalysisTaskMultiDielectron *task = new AliAnalysisTaskMultiDielectron("MultiDielectron_pPb");
  if (!hasMC) task->UsePhysicsSelection();
  task->SetTriggerMask(triggerMask);
//  taskMB->SetRejectPileup();
  task->SetRandomizeDaughters(randomizeDau); //default kFALSE

  //Add event filter
  task->SetEventFilter( GetEventCuts() );

  mgr->AddTask(task);

  //add dielectron analysis with different cuts to the task
  for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file
    //MB
    AliDielectron *diel_low = Config_lowmasspPb(i);
    if(!diel_low)continue;
    task->AddDielectron(diel_low);

  }//loop

  //create output container
  AliAnalysisDataContainer *coutput1 =
    mgr->CreateContainer("tree_lowmass",
                         TTree::Class(),
                         AliAnalysisManager::kExchangeContainer,
                         outputFileName);

  AliAnalysisDataContainer *cOutputHist1 =
    mgr->CreateContainer("Histos_diel_lowmass",
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName);

  AliAnalysisDataContainer *cOutputHist2 =
    mgr->CreateContainer("CF_diel_lowmass",
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName);

  AliAnalysisDataContainer *cOutputHist3 =
    mgr->CreateContainer("tbroeker_lowmass_EventStat",
                         TH1D::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName);

  mgr->ConnectInput(task,  0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 0, coutput1 );
  mgr->ConnectOutput(task, 1, cOutputHist1);
  mgr->ConnectOutput(task, 2, cOutputHist2);
  mgr->ConnectOutput(task, 3, cOutputHist3);

    return task;

}
<commit_msg>bugfix for loading config from alien<commit_after>AliAnalysisTask *AddTask_tbroeker_lowmasspPb(Bool_t getFromAlien=kFALSE,TString cFileName = "Config_tbroeker_lowmasspPb.C",Char_t* outputFileName="LMEEoutput.root"){

  //get the current analysis manager
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTask_lowmass", "No analysis manager found.");
    return 0;
  }

  //Do we have an MC handler?
  Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0);

  //Base Directory for GRID / LEGO Train
  TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/";
  if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/t/tbroker/PWGDQ/dielectron/macrosLMEE/%s .",cFileName.Data()))) ){
    TString configBasePath=Form("%s/",gSystem->pwd());
  }

  TString configFilePath(configBasePath+cFileName);

  std::cout << "Configpath:  " << configFilePath << std::endl;

  //if (!gROOT->GetListOfGlobalFunctions()->FindObject(cFileName.Data()))
  gROOT->LoadMacro(configFilePath.Data());

  //create task and add it to the manager (MB)
  AliAnalysisTaskMultiDielectron *task = new AliAnalysisTaskMultiDielectron("MultiDielectron_pPb");
  if (!hasMC) task->UsePhysicsSelection();
  task->SetTriggerMask(triggerMask);
//  taskMB->SetRejectPileup();
  task->SetRandomizeDaughters(randomizeDau); //default kFALSE

  //Add event filter
  task->SetEventFilter( GetEventCuts() );

  mgr->AddTask(task);

  //add dielectron analysis with different cuts to the task
  for (Int_t i=0; i<nDie; ++i){ //nDie defined in config file
    //MB
    AliDielectron *diel_low = Config_lowmasspPb(i);
    if(!diel_low)continue;
    task->AddDielectron(diel_low);

  }//loop

  //create output container
  AliAnalysisDataContainer *coutput1 =
    mgr->CreateContainer("tree_lowmass",
                         TTree::Class(),
                         AliAnalysisManager::kExchangeContainer,
                         outputFileName);

  AliAnalysisDataContainer *cOutputHist1 =
    mgr->CreateContainer("Histos_diel_lowmass",
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName);

  AliAnalysisDataContainer *cOutputHist2 =
    mgr->CreateContainer("CF_diel_lowmass",
                         TList::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName);

  AliAnalysisDataContainer *cOutputHist3 =
    mgr->CreateContainer("tbroeker_lowmass_EventStat",
                         TH1D::Class(),
                         AliAnalysisManager::kOutputContainer,
                         outputFileName);

  mgr->ConnectInput(task,  0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(task, 0, coutput1 );
  mgr->ConnectOutput(task, 1, cOutputHist1);
  mgr->ConnectOutput(task, 2, cOutputHist2);
  mgr->ConnectOutput(task, 3, cOutputHist3);

    return task;

}
<|endoftext|>


<commit_before>#include <tiramisu/tiramisu.h>
#include "configure.h"

using namespace tiramisu;

int main(int argc, char **argv)
{
    init("conv_tiramisu");

    // -------------------------------------------------------
    // Layer I
    // -------------------------------------------------------
    var x("x", 0, N), y("y", 0, N), n("n", 0, BATCH_SIZE);
    var k_x("k_x", 0, K), k_y("k_y", 0, K);

    var fin_b("fin_b", 0, FIN_NB_BLOCKS), ffin("ffin", 0, FIN_BLOCKING);
    var fout_b("fout_b", 0, FOUT_NB_BLOCKS), ffout("ffout", 0, FOUT_BLOCKING);

    var x_pad("x_pad", 0, N + 2), y_pad("y_pad", 0, N + 2);

    input c_input("c_input", {n, fin_b, y_pad, x_pad, ffin}, p_float32);
    input filter("filter", {fout_b, fin_b, k_y, k_x, ffin, ffout}, p_float32);
    input filter2("filter2", {fout_b, fin_b, k_x, ffin, ffout}, p_float32);
    input bias("bias", {fout_b, ffout}, p_float32);

    computation conv_init("conv_init", {n, y, fout_b, x, ffout}, bias(fout_b, ffout));
    view conv_out("conv_out", {n, y, x, fout_b, ffout}, p_float32);

    // x_bound is used to have the width dimension divisible by X_BLOCKING
    // in the conv computation.
    var x_bound("x_bound", 0, X_BOUND);
    var x_conclude("x_conclude", X_BOUND, N);

    /* Pattern 0
     *
     *   1 1 1
     *   0 0 0
     *   0 0 0
     *
     */
    computation conv_P0(
        "conv_P0",
        {n, y, fin_b, x_bound, ffin, fout_b, ffout},
	((fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) &&
	((fin_b*FIN_BLOCKING + ffin) <  ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL),
        conv_out(n, y, x_bound, fout_b, ffout) + filter2(fout_b, fin_b, 0, ffin, ffout) * c_input(n, fin_b, y + 0, x_bound + 0, ffin)
					       + filter2(fout_b, fin_b, 1, ffin, ffout) * c_input(n, fin_b, y + 0, x_bound + 1, ffin)
					       + filter2(fout_b, fin_b, 2, ffin, ffout) * c_input(n, fin_b, y + 0, x_bound + 2, ffin));

    /* Pattern 1
     *
     *   0 0 0
     *   1 1 1
     *   0 0 0
     *
     */
    computation conv_P1(
        "conv_P1",
        {n, y, fin_b, x_bound, ffin, fout_b, ffout},
	((fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) &&
	((fin_b*FIN_BLOCKING + ffin) <  ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL
									       + PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL),
        conv_out(n, y, x_bound, fout_b, ffout) + filter2(fout_b, fin_b, 0, ffin, ffout) * c_input(n, fin_b, y + 1, x_bound + 0, ffin)
					       + filter2(fout_b, fin_b, 1, ffin, ffout) * c_input(n, fin_b, y + 1, x_bound + 1, ffin)
					       + filter2(fout_b, fin_b, 2, ffin, ffout) * c_input(n, fin_b, y + 1, x_bound + 2, ffin));

    /* Pattern 2
     *
     *   0 0 0
     *   0 0 0
     *   1 1 1
     *
     */
    computation conv_P2(
        "conv_P2",
        {n, y, fin_b, x_bound, ffin, fout_b, ffout},
	((fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL
									       + PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) &&
	((fin_b*FIN_BLOCKING + ffin) <  ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL
									       + PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL
									       + PATTERN_2_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL),
        conv_out(n, y, x_bound, fout_b, ffout) + filter2(fout_b, fin_b, 0, ffin, ffout) * c_input(n, fin_b, y + 2, x_bound + 0, ffin)
					       + filter2(fout_b, fin_b, 1, ffin, ffout) * c_input(n, fin_b, y + 2, x_bound + 1, ffin)
					       + filter2(fout_b, fin_b, 2, ffin, ffout) * c_input(n, fin_b, y + 2, x_bound + 2, ffin));

    // Compute convolution from 0 to x_bound
    computation conv(
        "conv",
        {n, y, fin_b, x_bound, k_y, k_x, ffin, fout_b, ffout},
	(fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL +
										PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL +
										PATTERN_2_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL,
        conv_out(n, y, x_bound, fout_b, ffout) + filter(fout_b, fin_b, k_y, k_x, ffin, ffout) * c_input(n, fin_b, y + k_y, x_bound + k_x, ffin)
    );

    // Compute convolution from x_bound to N
    computation conv_conclude(
        "conv_conclude",
        {n, y, fin_b, k_y, k_x, ffin, fout_b, ffout, x_conclude},
	(fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL,
        conv_out(n, y, x_conclude, fout_b, ffout) + filter(fout_b, fin_b, k_y, k_x, ffin, ffout) * c_input(n, fin_b, y + k_y, x_conclude + k_x, ffin)
    );

    // -------------------------------------------------------
    // Layer II
    // -------------------------------------------------------

    // schedule for conv computation

    // We introduce those two computations to do register blocking
    computation reg_load(
        "reg_load",
        {n, y, fin_b, x_bound, fout_b, ffout},
        conv_init(n, y, fout_b, x_bound, ffout)
    );

    computation reg_store(
        "reg_store",
        {n, y, fin_b, x_bound, fout_b, ffout},
        conv(n, y, fin_b, x_bound, 0, 0, 0, fout_b, ffout)
    );

    // Split over dimension x
    var x_b, xx;
    conv.split(x_bound, X_BLOCKING, x_b, xx);
    conv_P0.split(x_bound, X_BLOCKING, x_b, xx);
    conv_P1.split(x_bound, X_BLOCKING, x_b, xx);
    conv_P2.split(x_bound, X_BLOCKING, x_b, xx);

    conv.interchange(xx, k_y);
    conv.interchange(xx, k_x);
    conv.interchange(xx, ffin);
    conv.interchange(xx, fout_b);
    conv.interchange(xx, ffout);
    conv_P0.interchange(xx, ffin);
    conv_P0.interchange(xx, fout_b);
    conv_P0.interchange(xx, ffout);
    conv_P1.interchange(xx, ffin);
    conv_P1.interchange(xx, fout_b);
    conv_P1.interchange(xx, ffout);
    conv_P2.interchange(xx, ffin);
    conv_P2.interchange(xx, fout_b);
    conv_P2.interchange(xx, ffout);

    reg_load.split(x_bound, X_BLOCKING, x_b, xx);
    reg_store.split(x_bound, X_BLOCKING, x_b, xx);

    reg_load.interchange(xx, fout_b);
    reg_load.interchange(xx, ffout);

    reg_store.interchange(xx, fout_b);
    reg_store.interchange(xx, ffout);

    // Vectorize and unroll
    reg_load.tag_vector_level(ffout, FOUT_BLOCKING);
    conv.tag_vector_level(ffout, FOUT_BLOCKING);
    conv_P0.tag_vector_level(ffout, FOUT_BLOCKING);
    conv_P1.tag_vector_level(ffout, FOUT_BLOCKING);
    conv_P2.tag_vector_level(ffout, FOUT_BLOCKING);
    reg_store.tag_vector_level(ffout, FOUT_BLOCKING);

    conv.tag_unroll_level(xx);
    conv.tag_unroll_level(fout_b);
    conv_P0.tag_unroll_level(xx);
    conv_P0.tag_unroll_level(fout_b);
    conv_P1.tag_unroll_level(xx);
    conv_P1.tag_unroll_level(fout_b);
    conv_P2.tag_unroll_level(xx);
    conv_P2.tag_unroll_level(fout_b);

    reg_load.tag_unroll_level(xx);
    reg_load.tag_unroll_level(fout_b);

    reg_store.tag_unroll_level(xx);
    reg_store.tag_unroll_level(fout_b);

    // schedule for conv_conclude
    // This schedule is the same as conv computation
    computation reg_load_conclude(
        "reg_load_conclude",
        {n, y, fin_b, fout_b, ffout, x_conclude},
        conv_init(n, y, fout_b, x_conclude, ffout)
    );

    computation reg_store_conclude(
        "reg_store_conclude",
        {n, y, fin_b, fout_b, ffout, x_conclude},
        conv_conclude(n, y, fin_b, 0, 0, 0, fout_b, ffout, x_conclude)
    );

    reg_load_conclude.tag_vector_level(ffout, FOUT_BLOCKING);
    conv_conclude.tag_vector_level(ffout, FOUT_BLOCKING);
    reg_store_conclude.tag_vector_level(ffout, FOUT_BLOCKING);

    conv_conclude.tag_unroll_level(x_conclude);
    conv_conclude.tag_unroll_level(fout_b);

    reg_load_conclude.tag_unroll_level(x_conclude);
    reg_load_conclude.tag_unroll_level(fout_b);

    reg_store_conclude.tag_unroll_level(x_conclude);
    reg_store_conclude.tag_unroll_level(fout_b);

    // Parallelize and order
    conv.tag_parallel_level(y);
    conv.tag_parallel_level(n);

    conv_init.then(reg_load, y)
             .then(conv_P0, x_b)
             .then(conv_P1, x_b)
             .then(conv_P2, x_b)
             .then(conv, x_b)
             .then(reg_store, x_b)
             .then(reg_load_conclude, y)
             .then(conv_conclude, fin_b)
             .then(reg_store_conclude, fin_b);

    // -------------------------------------------------------
    // Layer III
    // -------------------------------------------------------
    buffer conv_buf("conv_buf", {BATCH_SIZE, FOUT_NB_BLOCKS, N, N, FOUT_BLOCKING}, p_float32, a_output);

    // This is where intermediate results of convolution will be stored.
    // We rely on the compiler to detect that this buffer can be mapped to CPU registers.
    buffer reg_buf("reg_buf", {FOUT_NB_BLOCKS, X_BLOCKING, FOUT_BLOCKING}, p_float32, a_temporary);

    conv_init.store_in(&conv_buf, {n, fout_b, y, x, ffout});
    conv_out.store_in(&reg_buf, {fout_b, x%X_BLOCKING, ffout});

    reg_load.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout});
    conv.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout});
    conv_P0.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout});
    conv_P1.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout});
    conv_P2.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout});
    reg_store.store_in(&conv_buf, {n, fout_b, y, x_bound, ffout});

    reg_load_conclude.store_in(&reg_buf, {fout_b, x_conclude%X_BLOCKING, ffout});
    conv_conclude.store_in(&reg_buf, {fout_b, x_conclude%X_BLOCKING, ffout});
    reg_store_conclude.store_in(&conv_buf, {n, fout_b, y, x_conclude, ffout});

    // -------------------------------------------------------
    // Code Generation
    // -------------------------------------------------------
    tiramisu::codegen({
        c_input.get_buffer(),
        filter.get_buffer(),
        filter2.get_buffer(),
        bias.get_buffer(),
        &conv_buf
    },"generated_conv_layer.o");

    return 0;
}
<commit_msg>sparse_with_dense: simplify code<commit_after>#include <tiramisu/tiramisu.h>
#include "configure.h"

using namespace tiramisu;

#define USE_AFFINE_CONSTRAINTS 1
#define USE_NON_AFFINE_PREDICATES 0

int main(int argc, char **argv)
{
    init("conv_tiramisu");

    // -------------------------------------------------------
    // Layer I
    // -------------------------------------------------------
    var x("x", 0, N), y("y", 0, N), n("n", 0, BATCH_SIZE);
    var k_x("k_x", 0, K), k_y("k_y", 0, K);

    var fin_b("fin_b", 0, FIN_NB_BLOCKS), ffin("ffin", 0, FIN_BLOCKING);
    var fout_b("fout_b", 0, FOUT_NB_BLOCKS), ffout("ffout", 0, FOUT_BLOCKING);

    var x_pad("x_pad", 0, N + 2), y_pad("y_pad", 0, N + 2);

    input c_input("c_input", {n, fin_b, y_pad, x_pad, ffin}, p_float32);
    input filter("filter", {fout_b, fin_b, k_y, k_x, ffin, ffout}, p_float32);
    input filter2("filter2", {fout_b, fin_b, k_x, ffin, ffout}, p_float32);
    input bias("bias", {fout_b, ffout}, p_float32);

    computation conv_init("conv_init", {n, y, fout_b, x, ffout}, bias(fout_b, ffout));
    view conv_out("conv_out", {n, y, x, fout_b, ffout}, p_float32);

    // x_bound is used to have the width dimension divisible by X_BLOCKING
    // in the conv computation.
    var x_bound("x_bound", 0, X_BOUND);
    var x_conclude("x_conclude", X_BOUND, N);

#if USE_AFFINE_CONSTRAINTS
    expr constraints_P0 =
	((fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) &&
	((fin_b*FIN_BLOCKING + ffin) <  ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL);

    expr constraints_P1 =
	((fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) &&
	((fin_b*FIN_BLOCKING + ffin) <  ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL
									       + PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL);

    expr constraints_P2 =
	((fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL
									       + PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) &&
	((fin_b*FIN_BLOCKING + ffin) <  ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL
									       + PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL
									       + PATTERN_2_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL);

    expr constraints_P3 =
	((fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL +
									         PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL +
										 PATTERN_2_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL);
#else
    expr constraints_P0 = expr();
    expr constraints_P1 = expr();
    expr constraints_P2 = expr();
    expr constraints_P3 = expr();
#endif

    /* Pattern 0
     *
     *   1 1 1
     *   0 0 0
     *   0 0 0
     *
     */
    computation conv_P0(
        "conv_P0",
        {n, y, fin_b, x_bound, ffin, fout_b, ffout},
	constraints_P0,
        conv_out(n, y, x_bound, fout_b, ffout) + filter2(fout_b, fin_b, 0, ffin, ffout) * c_input(n, fin_b, y + 0, x_bound + 0, ffin)
					       + filter2(fout_b, fin_b, 1, ffin, ffout) * c_input(n, fin_b, y + 0, x_bound + 1, ffin)
					       + filter2(fout_b, fin_b, 2, ffin, ffout) * c_input(n, fin_b, y + 0, x_bound + 2, ffin));

    /* Pattern 1
     *
     *   0 0 0
     *   1 1 1
     *   0 0 0
     *
     */
    computation conv_P1(
        "conv_P1",
        {n, y, fin_b, x_bound, ffin, fout_b, ffout},
	constraints_P1,
        conv_out(n, y, x_bound, fout_b, ffout) + filter2(fout_b, fin_b, 0, ffin, ffout) * c_input(n, fin_b, y + 1, x_bound + 0, ffin)
					       + filter2(fout_b, fin_b, 1, ffin, ffout) * c_input(n, fin_b, y + 1, x_bound + 1, ffin)
					       + filter2(fout_b, fin_b, 2, ffin, ffout) * c_input(n, fin_b, y + 1, x_bound + 2, ffin));

    /* Pattern 2
     *
     *   0 0 0
     *   0 0 0
     *   1 1 1
     *
     */
    computation conv_P2(
        "conv_P2",
        {n, y, fin_b, x_bound, ffin, fout_b, ffout},
	constraints_P2,
        conv_out(n, y, x_bound, fout_b, ffout) + filter2(fout_b, fin_b, 0, ffin, ffout) * c_input(n, fin_b, y + 2, x_bound + 0, ffin)
					       + filter2(fout_b, fin_b, 1, ffin, ffout) * c_input(n, fin_b, y + 2, x_bound + 1, ffin)
					       + filter2(fout_b, fin_b, 2, ffin, ffout) * c_input(n, fin_b, y + 2, x_bound + 2, ffin));

    // Compute convolution from 0 to x_bound
    computation conv(
        "conv",
        {n, y, fin_b, x_bound, k_y, k_x, ffin, fout_b, ffout},
	constraints_P3,
        conv_out(n, y, x_bound, fout_b, ffout) + filter(fout_b, fin_b, k_y, k_x, ffin, ffout) * c_input(n, fin_b, y + k_y, x_bound + k_x, ffin)
    );

    // Compute convolution from x_bound to N
    computation conv_conclude(
        "conv_conclude",
        {n, y, fin_b, k_y, k_x, ffin, fout_b, ffout, x_conclude},
	(fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL,
        conv_out(n, y, x_conclude, fout_b, ffout) + filter(fout_b, fin_b, k_y, k_x, ffin, ffout) * c_input(n, fin_b, y + k_y, x_conclude + k_x, ffin)
    );

#if USE_NON_AFFINE_PREDICATES
    constraints_P0 =
	((fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) &&
	((fin_b*FIN_BLOCKING + ffin) <  ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL);

    constraints_P1 =
	((fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) &&
	((fin_b*FIN_BLOCKING + ffin) <  ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL
									       + PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL);

    constraints_P2 =
	((fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL
									       + PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL) &&
	((fin_b*FIN_BLOCKING + ffin) <  ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL
									       + PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL
									       + PATTERN_2_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL);

    constraints_P3 =
	((fin_b*FIN_BLOCKING + ffin) >= ZERO_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL + PATTERN_0_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL +
									         PATTERN_1_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL +
										 PATTERN_2_WEIGHT_FILTERS_PER_OUTPUT_CHANNEL);
    conv_P0.add_predicate(constraints_P0);
    conv_P1.add_predicate(constraints_P1);
    conv_P2.add_predicate(constraints_P2);
    conv.add_predicate(constraints_P3);
#endif

    // -------------------------------------------------------
    // Layer II
    // -------------------------------------------------------

    // schedule for conv computation

    // We introduce those two computations to do register blocking
    computation reg_load(
        "reg_load",
        {n, y, fin_b, x_bound, fout_b, ffout},
        conv_init(n, y, fout_b, x_bound, ffout)
    );

    computation reg_store(
        "reg_store",
        {n, y, fin_b, x_bound, fout_b, ffout},
        conv(n, y, fin_b, x_bound, 0, 0, 0, fout_b, ffout)
    );

    // Split over dimension x
    var x_b, xx;
    conv.split(x_bound, X_BLOCKING, x_b, xx);
    conv_P0.split(x_bound, X_BLOCKING, x_b, xx);
    conv_P1.split(x_bound, X_BLOCKING, x_b, xx);
    conv_P2.split(x_bound, X_BLOCKING, x_b, xx);

    conv.interchange(xx, k_y);
    conv.interchange(xx, k_x);
    conv.interchange(xx, ffin);
    conv.interchange(xx, fout_b);
    conv.interchange(xx, ffout);
    conv_P0.interchange(xx, ffin);
    conv_P0.interchange(xx, fout_b);
    conv_P0.interchange(xx, ffout);
    conv_P1.interchange(xx, ffin);
    conv_P1.interchange(xx, fout_b);
    conv_P1.interchange(xx, ffout);
    conv_P2.interchange(xx, ffin);
    conv_P2.interchange(xx, fout_b);
    conv_P2.interchange(xx, ffout);

    reg_load.split(x_bound, X_BLOCKING, x_b, xx);
    reg_store.split(x_bound, X_BLOCKING, x_b, xx);

    reg_load.interchange(xx, fout_b);
    reg_load.interchange(xx, ffout);

    reg_store.interchange(xx, fout_b);
    reg_store.interchange(xx, ffout);

    // Vectorize and unroll
    reg_load.tag_vector_level(ffout, FOUT_BLOCKING);
    conv.tag_vector_level(ffout, FOUT_BLOCKING);
    conv_P0.tag_vector_level(ffout, FOUT_BLOCKING);
    conv_P1.tag_vector_level(ffout, FOUT_BLOCKING);
    conv_P2.tag_vector_level(ffout, FOUT_BLOCKING);
    reg_store.tag_vector_level(ffout, FOUT_BLOCKING);

    conv.tag_unroll_level(xx);
    conv.tag_unroll_level(fout_b);
    conv_P0.tag_unroll_level(xx);
    conv_P0.tag_unroll_level(fout_b);
    conv_P1.tag_unroll_level(xx);
    conv_P1.tag_unroll_level(fout_b);
    conv_P2.tag_unroll_level(xx);
    conv_P2.tag_unroll_level(fout_b);

    reg_load.tag_unroll_level(xx);
    reg_load.tag_unroll_level(fout_b);

    reg_store.tag_unroll_level(xx);
    reg_store.tag_unroll_level(fout_b);

    // schedule for conv_conclude
    // This schedule is the same as conv computation
    computation reg_load_conclude(
        "reg_load_conclude",
        {n, y, fin_b, fout_b, ffout, x_conclude},
        conv_init(n, y, fout_b, x_conclude, ffout)
    );

    computation reg_store_conclude(
        "reg_store_conclude",
        {n, y, fin_b, fout_b, ffout, x_conclude},
        conv_conclude(n, y, fin_b, 0, 0, 0, fout_b, ffout, x_conclude)
    );

    reg_load_conclude.tag_vector_level(ffout, FOUT_BLOCKING);
    conv_conclude.tag_vector_level(ffout, FOUT_BLOCKING);
    reg_store_conclude.tag_vector_level(ffout, FOUT_BLOCKING);

    conv_conclude.tag_unroll_level(x_conclude);
    conv_conclude.tag_unroll_level(fout_b);

    reg_load_conclude.tag_unroll_level(x_conclude);
    reg_load_conclude.tag_unroll_level(fout_b);

    reg_store_conclude.tag_unroll_level(x_conclude);
    reg_store_conclude.tag_unroll_level(fout_b);

    // Parallelize and order
    conv.tag_parallel_level(y);
    conv.tag_parallel_level(n);

    conv_init.then(reg_load, y)
             .then(conv_P0, x_b)
             .then(conv_P1, x_b)
             .then(conv_P2, x_b)
             .then(conv, x_b)
             .then(reg_store, x_b)
             .then(reg_load_conclude, y)
             .then(conv_conclude, fin_b)
             .then(reg_store_conclude, fin_b);

    // -------------------------------------------------------
    // Layer III
    // -------------------------------------------------------
    buffer conv_buf("conv_buf", {BATCH_SIZE, FOUT_NB_BLOCKS, N, N, FOUT_BLOCKING}, p_float32, a_output);

    // This is where intermediate results of convolution will be stored.
    // We rely on the compiler to detect that this buffer can be mapped to CPU registers.
    buffer reg_buf("reg_buf", {FOUT_NB_BLOCKS, X_BLOCKING, FOUT_BLOCKING}, p_float32, a_temporary);

    conv_init.store_in(&conv_buf, {n, fout_b, y, x, ffout});
    conv_out.store_in(&reg_buf, {fout_b, x%X_BLOCKING, ffout});

    reg_load.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout});
    conv.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout});
    conv_P0.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout});
    conv_P1.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout});
    conv_P2.store_in(&reg_buf, {fout_b, x_bound%X_BLOCKING, ffout});
    reg_store.store_in(&conv_buf, {n, fout_b, y, x_bound, ffout});

    reg_load_conclude.store_in(&reg_buf, {fout_b, x_conclude%X_BLOCKING, ffout});
    conv_conclude.store_in(&reg_buf, {fout_b, x_conclude%X_BLOCKING, ffout});
    reg_store_conclude.store_in(&conv_buf, {n, fout_b, y, x_conclude, ffout});

    // -------------------------------------------------------
    // Code Generation
    // -------------------------------------------------------
    tiramisu::codegen({
        c_input.get_buffer(),
        filter.get_buffer(),
        filter2.get_buffer(),
        bias.get_buffer(),
        &conv_buf
    },"generated_conv_layer.o");

    return 0;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <qcoreapplication.h>
#include <qprocess.h>
#include <qtemporaryfile.h>
#include <qdebug.h>

#include <QtTest/QtTest>

#ifdef QT_NO_PROCESS
QTEST_NOOP_MAIN
#else

#include <stdlib.h>

QT_USE_NAMESPACE

class tst_CompilerWarnings: public QObject
{
    Q_OBJECT

private slots:
    void warnings_data();
    void warnings();
};

#if 0
/*
    Return list of all documented qfeatures (QT_NO_*)
 */
static QStringList getFeatures()
{
    QStringList srcDirs;
    srcDirs << QString::fromLocal8Bit(qgetenv("QTDIR"))
            << QString::fromLocal8Bit(qgetenv("QTSRCDIR"));

    QString featurefile;
    foreach (QString dir, srcDirs) {
        QString str = dir + "/src/corelib/global/qfeatures.txt";
        if (QFile::exists(str)) {
            featurefile = str;
            break;
        }
    }

    if (featurefile.isEmpty()) {
        qWarning("Unable to find qfeatures.txt");
        return QStringList();
    }

    QFile file(featurefile);
    if (!file.open(QIODevice::ReadOnly)) {
	qWarning("Unable to open feature file '%s'", qPrintable(featurefile));
	return QStringList();
    }

    QStringList features;
    QTextStream s(&file);
    QRegExp regexp("Feature:\\s+(\\w+)\\s*");
    for (QString line = s.readLine(); !s.atEnd(); line = s.readLine()) {
        if (regexp.exactMatch(line))
            features << regexp.cap(1);
    }

    return features;
}
#endif

void tst_CompilerWarnings::warnings_data()
{
    QTest::addColumn<QStringList>("cflags");

    QTest::newRow("standard") << QStringList();

#if 0
#ifdef Q_WS_QWS
    QStringList features = getFeatures();
    foreach (QString feature, features) {
        QStringList args;
        QString macro = QString("QT_NO_%1").arg(feature);
        args << (QString("-D%1").arg(macro));
        QTest::newRow(qPrintable(macro)) << args;
    }
#endif
#endif
}

void tst_CompilerWarnings::warnings()
{
    QFETCH(QStringList, cflags);

#if !defined(Q_CC_INTEL) && defined(Q_CC_GNU) && __GNUC__ == 3
    QSKIP("gcc 3.x outputs too many bogus warnings", SkipAll);
#endif

    static QString tmpFile;
    if (tmpFile.isEmpty()) {
        QTemporaryFile tmpQFile;
        tmpQFile.open();
        tmpFile = tmpQFile.fileName();
        tmpQFile.close();
    }
    static QString tmpSourceFile;
    bool openResult = true;
    const QString tmpBaseName("XXXXXX-test.cpp");
    QString templatePath = QDir::temp().absoluteFilePath(tmpBaseName);
    QFile tmpQSourceFile(templatePath);
    if (tmpSourceFile.isEmpty()) {
        tmpQSourceFile.open(QIODevice::ReadWrite | QIODevice::Truncate);
        tmpSourceFile = tmpQSourceFile.fileName();
        QFile cppSource(":/test.cpp");
        bool openResult = cppSource.open(QIODevice::ReadOnly);
        if (openResult)
        {
            QTextStream in(&cppSource);
            QTextStream out(&tmpQSourceFile);
            out << in.readAll();
        }
    }
    tmpQSourceFile.close();
    QVERIFY2(openResult, "Need resource temporary \"test.cpp\"");

    QStringList args;
    QString compilerName;

    static QString qtDir = QString::fromLocal8Bit(qgetenv("QTDIR"));
    QVERIFY2(!qtDir.isEmpty(), "This test needs $QTDIR");

    args << cflags;
#if !defined(Q_CC_INTEL) && defined(Q_CC_GNU)
    compilerName = "g++";
    args << "-I" + qtDir + "/include";
    args << "-I/usr/X11R6/include/";
#ifdef Q_OS_HPUX
    args << "-I/usr/local/mesa/aCC-64/include";
#endif
    args << "-c";
    args << "-Wall" << "-Wold-style-cast" << "-Woverloaded-virtual" << "-pedantic" << "-ansi"
         << "-Wno-long-long" << "-Wshadow" << "-Wpacked" << "-Wunreachable-code"
         << "-Wundef" << "-Wchar-subscripts" << "-Wformat-nonliteral" << "-Wformat-security"
         << "-Wcast-align"
         << "-Wfloat-equal"
         << "-o" << tmpFile
         << tmpSourceFile;
#elif defined(Q_CC_XLC)
    compilerName = "xlC_r";
    args << "-I" + qtDir + "/include"
# if QT_POINTER_SIZE == 8
         << "-q64"
# endif
         << "-c" << "-o" << tmpFile
         << "-info=all"
         << tmpSourceFile;
#elif defined(Q_CC_MSVC)
    compilerName = "cl";
    args << "-I" + qtDir + "/include"
         << "-nologo" << "-W3"
         << tmpSourceFile;
#elif defined (Q_CC_SUN)
    compilerName = "CC";
    // +w or +w2 outputs too much bogus
    args << "-I" + qtDir + "/include"
# if QT_POINTER_SIZE == 8
         << "-xarch=v9"
# endif
         << "-o" << tmpFile
         << tmpSourceFile;
#elif defined (Q_CC_HPACC)
    compilerName = "aCC";
    args << "-I" + qtDir + "/include"
         << "-I/usr/local/mesa/aCC-64/include"
         << "-I/opt/graphics/OpenGL/include"
# if QT_POINTER_SIZE == 8 && !defined __ia64
         << "+DA2.0W"
# endif
         // aCC generates too much bogus.
         << "-DQT_NO_STL" << "-c" << "-w"
         << "-o" << tmpFile
         << tmpSourceFile;
#elif defined(Q_CC_MIPS)
    compilerName = "CC";
    args << "-I" + qtDir + "/include"
         << "-c"
         << "-woff" << "3303" // const qualifier on return
         << "-o" << tmpFile
         << tmpSourceFile;
#else
    QSKIP("Test not implemented for this compiler", SkipAll);
#endif

    QProcess proc;
    proc.start(compilerName, args, QIODevice::ReadOnly);
    QVERIFY2(proc.waitForFinished(6000000), proc.errorString().toLocal8Bit());

#ifdef Q_CC_MSVC
    QString errs = QString::fromLocal8Bit(proc.readAllStandardOutput().constData());
    if (errs.startsWith(tmpBaseName))
        errs = errs.mid(tmpBaseName.size()).simplified();;
#else
    QString errs = QString::fromLocal8Bit(proc.readAllStandardError().constData());
#endif
    QStringList errList;
    if (!errs.isEmpty()) {
        errList = errs.split("\n");
        qDebug() << "Arguments:" << args;
        foreach (QString err, errList) {
            qDebug() << err;
        }
    }
    QCOMPARE(errList.count(), 0); // verbose info how many lines of errors in output
    QVERIFY(errs.isEmpty());

    tmpQSourceFile.remove();
}

QTEST_APPLESS_MAIN(tst_CompilerWarnings)

#include "tst_compilerwarnings.moc"
#endif // QT_NO_PROCESS
<commit_msg>Fix the compilerwarning test on GCC<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <qcoreapplication.h>
#include <qprocess.h>
#include <qtemporaryfile.h>
#include <qdebug.h>

#include <QtTest/QtTest>

#ifdef QT_NO_PROCESS
QTEST_NOOP_MAIN
#else

#include <stdlib.h>

QT_USE_NAMESPACE

class tst_CompilerWarnings: public QObject
{
    Q_OBJECT

private slots:
    void warnings_data();
    void warnings();
};

#if 0
/*
    Return list of all documented qfeatures (QT_NO_*)
 */
static QStringList getFeatures()
{
    QStringList srcDirs;
    srcDirs << QString::fromLocal8Bit(qgetenv("QTDIR"))
            << QString::fromLocal8Bit(qgetenv("QTSRCDIR"));

    QString featurefile;
    foreach (QString dir, srcDirs) {
        QString str = dir + "/src/corelib/global/qfeatures.txt";
        if (QFile::exists(str)) {
            featurefile = str;
            break;
        }
    }

    if (featurefile.isEmpty()) {
        qWarning("Unable to find qfeatures.txt");
        return QStringList();
    }

    QFile file(featurefile);
    if (!file.open(QIODevice::ReadOnly)) {
	qWarning("Unable to open feature file '%s'", qPrintable(featurefile));
	return QStringList();
    }

    QStringList features;
    QTextStream s(&file);
    QRegExp regexp("Feature:\\s+(\\w+)\\s*");
    for (QString line = s.readLine(); !s.atEnd(); line = s.readLine()) {
        if (regexp.exactMatch(line))
            features << regexp.cap(1);
    }

    return features;
}
#endif

void tst_CompilerWarnings::warnings_data()
{
    QTest::addColumn<QStringList>("cflags");

    QTest::newRow("standard") << QStringList();

#if 0
#ifdef Q_WS_QWS
    QStringList features = getFeatures();
    foreach (QString feature, features) {
        QStringList args;
        QString macro = QString("QT_NO_%1").arg(feature);
        args << (QString("-D%1").arg(macro));
        QTest::newRow(qPrintable(macro)) << args;
    }
#endif
#endif
}

void tst_CompilerWarnings::warnings()
{
    QFETCH(QStringList, cflags);

#if !defined(Q_CC_INTEL) && defined(Q_CC_GNU) && __GNUC__ == 3
    QSKIP("gcc 3.x outputs too many bogus warnings", SkipAll);
#endif

    static QString tmpFile;
    if (tmpFile.isEmpty()) {
        QTemporaryFile tmpQFile;
        tmpQFile.open();
        tmpFile = tmpQFile.fileName();
        tmpQFile.close();
    }
    static QString tmpSourceFile;
    bool openResult = true;
    const QString tmpBaseName("XXXXXX-test.cpp");
    QString templatePath = QDir::temp().absoluteFilePath(tmpBaseName);
    QFile tmpQSourceFile(templatePath);
    if (tmpSourceFile.isEmpty()) {
        tmpQSourceFile.open(QIODevice::ReadWrite | QIODevice::Truncate);
        tmpSourceFile = tmpQSourceFile.fileName();
        QFile cppSource(":/test.cpp");
        bool openResult = cppSource.open(QIODevice::ReadOnly);
        if (openResult)
        {
            QTextStream in(&cppSource);
            QTextStream out(&tmpQSourceFile);
            out << in.readAll();
        }
    }
    tmpQSourceFile.close();
    QVERIFY2(openResult, "Need resource temporary \"test.cpp\"");

    QStringList args;
    QString compilerName;

    static QString qtDir = QString::fromLocal8Bit(qgetenv("QTDIR"));
    QVERIFY2(!qtDir.isEmpty(), "This test needs $QTDIR");

    args << cflags;
#if !defined(Q_CC_INTEL) && defined(Q_CC_GNU)
    compilerName = "g++";
    args << "-I" + qtDir + "/include";
    args << "-I/usr/X11R6/include/";
#ifdef Q_OS_HPUX
    args << "-I/usr/local/mesa/aCC-64/include";
#endif
    args << "-c";
    args << "-Wall" << "-Wold-style-cast" << "-Woverloaded-virtual" << "-pedantic" << "-ansi"
         << "-Wno-long-long" << "-Wshadow" << "-Wpacked" << "-Wunreachable-code"
         << "-Wundef" << "-Wchar-subscripts" << "-Wformat-nonliteral" << "-Wformat-security"
         << "-Wcast-align"
         << "-o" << tmpFile
         << tmpSourceFile;
#elif defined(Q_CC_XLC)
    compilerName = "xlC_r";
    args << "-I" + qtDir + "/include"
# if QT_POINTER_SIZE == 8
         << "-q64"
# endif
         << "-c" << "-o" << tmpFile
         << "-info=all"
         << tmpSourceFile;
#elif defined(Q_CC_MSVC)
    compilerName = "cl";
    args << "-I" + qtDir + "/include"
         << "-nologo" << "-W3"
         << tmpSourceFile;
#elif defined (Q_CC_SUN)
    compilerName = "CC";
    // +w or +w2 outputs too much bogus
    args << "-I" + qtDir + "/include"
# if QT_POINTER_SIZE == 8
         << "-xarch=v9"
# endif
         << "-o" << tmpFile
         << tmpSourceFile;
#elif defined (Q_CC_HPACC)
    compilerName = "aCC";
    args << "-I" + qtDir + "/include"
         << "-I/usr/local/mesa/aCC-64/include"
         << "-I/opt/graphics/OpenGL/include"
# if QT_POINTER_SIZE == 8 && !defined __ia64
         << "+DA2.0W"
# endif
         // aCC generates too much bogus.
         << "-DQT_NO_STL" << "-c" << "-w"
         << "-o" << tmpFile
         << tmpSourceFile;
#elif defined(Q_CC_MIPS)
    compilerName = "CC";
    args << "-I" + qtDir + "/include"
         << "-c"
         << "-woff" << "3303" // const qualifier on return
         << "-o" << tmpFile
         << tmpSourceFile;
#else
    QSKIP("Test not implemented for this compiler", SkipAll);
#endif

    QProcess proc;
    proc.start(compilerName, args, QIODevice::ReadOnly);
    QVERIFY2(proc.waitForFinished(6000000), proc.errorString().toLocal8Bit());

#ifdef Q_CC_MSVC
    QString errs = QString::fromLocal8Bit(proc.readAllStandardOutput().constData());
    if (errs.startsWith(tmpBaseName))
        errs = errs.mid(tmpBaseName.size()).simplified();;
#else
    QString errs = QString::fromLocal8Bit(proc.readAllStandardError().constData());
#endif
    QStringList errList;
    if (!errs.isEmpty()) {
        errList = errs.split("\n");
        qDebug() << "Arguments:" << args;
        foreach (QString err, errList) {
            qDebug() << err;
        }
    }
    QCOMPARE(errList.count(), 0); // verbose info how many lines of errors in output
    QVERIFY(errs.isEmpty());

    tmpQSourceFile.remove();
}

QTEST_APPLESS_MAIN(tst_CompilerWarnings)

#include "tst_compilerwarnings.moc"
#endif // QT_NO_PROCESS
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

int main (int argc, char* argv[])
{
    cout << "Hello World !!!\n";
    //flush(stdio);
	return 0;
}
<commit_msg>change return code<commit_after>#include <iostream>

using namespace std;

int main (int argc, char* argv[])
{
    cout << "Hello World !!!\n";

	return 1;
}
<|endoftext|>


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

/*
 * Test to compare
 * 1.pciBusID from hipDeviceGetPCIBusId and hipDeviceGetAttribute **
 * 2.{pciDomainID, pciBusID, pciDeviceID} values hipDeviceGetPCIBusId vs lspci **
 */

/* HIT_START
 * BUILD: %t %s ../../test_common.cpp NVCC_OPTIONS -std=c++11
 * TEST_NAMED: %t  hipDeviceGetPCIBusId-vs-hipDeviceGetAttribute --tests 0x1
 * TEST_NAMED: %t  hipDeviceGetPCIBusId-vs-lspci --tests 0x2
 * TEST_NAMED: %t  hipDeviceGetPCIBusId-negative --tests 0x3
 * HIT_END
 */

#include "test_common.h"
#define MAX_DEVICE_LENGTH 20

static bool getPciBusId(int deviceCount,
                        char hipDeviceList[][MAX_DEVICE_LENGTH]) {
  for (int i = 0; i < deviceCount; i++) {
    HIPCHECK(hipDeviceGetPCIBusId(hipDeviceList[i], MAX_DEVICE_LENGTH, i));
  }
  return true;
}

bool comparePciBusIDWithHipDeviceGetAttribute() {
  bool testResult = true;
  int deviceCount = 0;
  HIPCHECK(hipGetDeviceCount(&deviceCount));
  HIPASSERT(deviceCount != 0);
  printf("No.of gpus in the system: %d\n", deviceCount);
  char hipDeviceList[deviceCount][MAX_DEVICE_LENGTH];

  getPciBusId(deviceCount, hipDeviceList);

  for (int i = 0; i < deviceCount; i++) {
    int pciBusID = -1;
    int pciDeviceID = -1;
    int pciDomainID = -1;
    int tempPciBusId = -1;
    sscanf(hipDeviceList[i], "%04x:%02x:%02x", &pciDomainID, &pciBusID,
           &pciDeviceID);
    HIPCHECK(hipDeviceGetAttribute(&tempPciBusId,
                                    hipDeviceAttributePciBusId, i));
    if (pciBusID != tempPciBusId) {
      testResult = false;
      printf("pciBusID from hipDeviceGetPCIBusId mismatched to that from "
             "hipDeviceGetAttribute for gpu %d\n", i);
    }
  }

  printf("pciBusID output of both hipDeviceGetPCIBusId and"
         " hipDeviceGetAttribute matched for all gpus\n");
  return testResult;
}

bool compareHipDeviceGetPCIBusIdWithLspci() {
  FILE *fpipe;
  bool testResult = false;

  {
    // Check if lspci is installed, if not, don't proceed
    char const *cmd = "lspci --version";
    char *lspciCheck;
    char temp[20];
    fpipe = popen(cmd, "r");

    if (fpipe == nullptr) {
      printf("Unable to create command file\n");
      return testResult;
    }

    lspciCheck = fgets(temp, 20, fpipe);
    pclose(fpipe);

    if (!lspciCheck) {
      printf("lspci not found. Skipping the test\n");
      return true;
    }
  }

  int deviceCount = 0;
  HIPCHECK(hipGetDeviceCount(&deviceCount));
  HIPASSERT(deviceCount != 0);
  printf("No.of gpus in the system: %d\n", deviceCount);
  char hipDeviceList[deviceCount][MAX_DEVICE_LENGTH];
  char pciDeviceList[deviceCount][MAX_DEVICE_LENGTH];

  getPciBusId(deviceCount, hipDeviceList);

  // Get lspci device list and compare with hip device list
#ifdef __HIP_PLATFORM_NVCC__
  char const *command = "lspci -D | grep controller | grep NVIDIA | "
                        "cut -d ' ' -f 1";
#else
  char const *command = "lspci -D | grep controller | grep AMD/ATI | "
                        "cut -d ' ' -f 1";
#endif
  fpipe = popen(command, "r");

  if (fpipe == nullptr) {
    printf("Unable to create command file\n");
    return testResult;
  }

  int index = 0;
  int deviceMatchCount = 0;

  while (fgets(pciDeviceList[index], sizeof(pciDeviceList[index]), fpipe)) {
    bool bMatchFound = false;
    for (int deviceNo = 0; deviceNo < deviceCount; deviceNo++) {
      if (!strncasecmp(pciDeviceList[index], hipDeviceList[deviceNo], 10)) {
        deviceMatchCount++;
        bMatchFound = true;
      }
    }
    if (bMatchFound == false) {
      printf("PCI device: %s is not reported by HIP\n",
                                   pciDeviceList[index]);
    }
    index++;
  }

  pclose(fpipe);

  if (deviceMatchCount == deviceCount) {
    printf("hip and lspci output for {pciDomainID, pciBusID, pciDeviceID} "
           "matched for all gpus\n");
    testResult = true;
  } else {
    printf("Mismatch in number GPUs reported by HIP with lscpi\n");
  }
  return testResult;
}

/**
 * Validates negative scenarios for hipDeviceGetPCIBusId
 * scenario1: pciBusId = nullptr
 * scenario2: device = -1 (Invalid Device)
 * scenario3: device = Non Existing Device
 * scenario4: len = 0
 * scenario5: len < 0
 */
bool testInvalidParameters() {
  bool TestPassed = true;
  hipError_t ret;
  int deviceCount = 0;
  HIPCHECK(hipGetDeviceCount(&deviceCount));
  HIPASSERT(deviceCount != 0);
  printf("No.of gpus in the system: %d\n", deviceCount);
  char pciBusId[MAX_DEVICE_LENGTH];
  // pciBusId = nullptr
  int device;
  HIPCHECK(hipGetDevice(&device));
  ret = hipDeviceGetPCIBusId(nullptr, MAX_DEVICE_LENGTH, device);
  if (ret == hipSuccess) {
    TestPassed &= false;
    printf("Test {pciBusId = nullptr} Failed \n");
  }
  // len = 0
  ret = hipDeviceGetPCIBusId(pciBusId, 0, device);
  if (ret == hipSuccess) {
    TestPassed &= false;
    printf("Test {len = 0} Failed \n");
  }
  // len < 0
  ret = hipDeviceGetPCIBusId(pciBusId, -1, device);
  if (ret == hipSuccess) {
    TestPassed &= false;
    printf("Test {len < 0} Failed \n");
  }
  // device = -1
  ret = hipDeviceGetPCIBusId(pciBusId, MAX_DEVICE_LENGTH, -1);
  if (ret == hipSuccess) {
    TestPassed &= false;
    printf("Test {device = -1} Failed \n");
  }
  // device = Non Existing Device
  ret = hipDeviceGetPCIBusId(pciBusId, MAX_DEVICE_LENGTH, deviceCount);
  if (ret == hipSuccess) {
    TestPassed &= false;
    printf("Test {device = Non Existing Device} Failed \n");
  }
  return TestPassed;
}

int main(int argc, char* argv[]) {
  bool testResult = true;
  HipTest::parseStandardArguments(argc, argv, true);

  if (p_tests == 0x1) {
    testResult &= comparePciBusIDWithHipDeviceGetAttribute();
  }

  if (p_tests == 0x2) {
#ifdef __unix__
    testResult &= compareHipDeviceGetPCIBusIdWithLspci();
#else
    printf("Detected non-linux OS. Skipping the test\n");
#endif
  }

  if (p_tests == 0x3) {
    testResult &= testInvalidParameters();
  }

  if (testResult) {
    passed();
  } else {
    failed("one or more tests failed\n");
  }
}
<commit_msg>SWDEV-278478 - hipDeviceGetPCIBusId-vs-lspci test enabled only for linux environment<commit_after>/*
 * Copyright (c) 2015-present Advanced Micro Devices, Inc. All rights reserved.
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * Test to compare
 * 1.pciBusID from hipDeviceGetPCIBusId and hipDeviceGetAttribute **
 * 2.{pciDomainID, pciBusID, pciDeviceID} values hipDeviceGetPCIBusId vs lspci **
 */

/* HIT_START
 * BUILD: %t %s ../../test_common.cpp NVCC_OPTIONS -std=c++11
 * TEST_NAMED: %t  hipDeviceGetPCIBusId-vs-hipDeviceGetAttribute --tests 0x1
 * TEST_NAMED: %t  hipDeviceGetPCIBusId-vs-lspci --tests 0x2
 * TEST_NAMED: %t  hipDeviceGetPCIBusId-negative --tests 0x3
 * HIT_END
 */

#include "test_common.h"
#define MAX_DEVICE_LENGTH 20

static bool getPciBusId(int deviceCount,
                        char hipDeviceList[][MAX_DEVICE_LENGTH]) {
  for (int i = 0; i < deviceCount; i++) {
    HIPCHECK(hipDeviceGetPCIBusId(hipDeviceList[i], MAX_DEVICE_LENGTH, i));
  }
  return true;
}

bool comparePciBusIDWithHipDeviceGetAttribute() {
  bool testResult = true;
  int deviceCount = 0;
  HIPCHECK(hipGetDeviceCount(&deviceCount));
  HIPASSERT(deviceCount != 0);
  printf("No.of gpus in the system: %d\n", deviceCount);
  char hipDeviceList[deviceCount][MAX_DEVICE_LENGTH];

  getPciBusId(deviceCount, hipDeviceList);

  for (int i = 0; i < deviceCount; i++) {
    int pciBusID = -1;
    int pciDeviceID = -1;
    int pciDomainID = -1;
    int tempPciBusId = -1;
    sscanf(hipDeviceList[i], "%04x:%02x:%02x", &pciDomainID, &pciBusID,
           &pciDeviceID);
    HIPCHECK(hipDeviceGetAttribute(&tempPciBusId,
                                    hipDeviceAttributePciBusId, i));
    if (pciBusID != tempPciBusId) {
      testResult = false;
      printf("pciBusID from hipDeviceGetPCIBusId mismatched to that from "
             "hipDeviceGetAttribute for gpu %d\n", i);
    }
  }

  printf("pciBusID output of both hipDeviceGetPCIBusId and"
         " hipDeviceGetAttribute matched for all gpus\n");
  return testResult;
}

#ifdef __linux__
bool compareHipDeviceGetPCIBusIdWithLspci() {
  FILE *fpipe;
  bool testResult = false;

  {
    // Check if lspci is installed, if not, don't proceed
    char const *cmd = "lspci --version";
    char *lspciCheck;
    char temp[20];
    fpipe = popen(cmd, "r");

    if (fpipe == nullptr) {
      printf("Unable to create command file\n");
      return testResult;
    }

    lspciCheck = fgets(temp, 20, fpipe);
    pclose(fpipe);

    if (!lspciCheck) {
      printf("lspci not found. Skipping the test\n");
      return true;
    }
  }

  int deviceCount = 0;
  HIPCHECK(hipGetDeviceCount(&deviceCount));
  HIPASSERT(deviceCount != 0);
  printf("No.of gpus in the system: %d\n", deviceCount);
  char hipDeviceList[deviceCount][MAX_DEVICE_LENGTH];
  char pciDeviceList[deviceCount][MAX_DEVICE_LENGTH];

  getPciBusId(deviceCount, hipDeviceList);

  // Get lspci device list and compare with hip device list
#ifdef __HIP_PLATFORM_NVCC__
  char const *command = "lspci -D | grep controller | grep NVIDIA | "
                        "cut -d ' ' -f 1";
#else
  char const *command = "lspci -D | grep controller | grep AMD/ATI | "
                        "cut -d ' ' -f 1";
#endif
  fpipe = popen(command, "r");

  if (fpipe == nullptr) {
    printf("Unable to create command file\n");
    return testResult;
  }

  int index = 0;
  int deviceMatchCount = 0;

  while (fgets(pciDeviceList[index], sizeof(pciDeviceList[index]), fpipe)) {
    bool bMatchFound = false;
    for (int deviceNo = 0; deviceNo < deviceCount; deviceNo++) {
      if (!strncasecmp(pciDeviceList[index], hipDeviceList[deviceNo], 10)) {
        deviceMatchCount++;
        bMatchFound = true;
      }
    }
    if (bMatchFound == false) {
      printf("PCI device: %s is not reported by HIP\n",
                                   pciDeviceList[index]);
    }
    index++;
  }

  pclose(fpipe);

  if (deviceMatchCount == deviceCount) {
    printf("hip and lspci output for {pciDomainID, pciBusID, pciDeviceID} "
           "matched for all gpus\n");
    testResult = true;
  } else {
    printf("Mismatch in number GPUs reported by HIP with lscpi\n");
  }
  return testResult;
}
#endif

/**
 * Validates negative scenarios for hipDeviceGetPCIBusId
 * scenario1: pciBusId = nullptr
 * scenario2: device = -1 (Invalid Device)
 * scenario3: device = Non Existing Device
 * scenario4: len = 0
 * scenario5: len < 0
 */
bool testInvalidParameters() {
  bool TestPassed = true;
  hipError_t ret;
  int deviceCount = 0;
  HIPCHECK(hipGetDeviceCount(&deviceCount));
  HIPASSERT(deviceCount != 0);
  printf("No.of gpus in the system: %d\n", deviceCount);
  char pciBusId[MAX_DEVICE_LENGTH];
  // pciBusId = nullptr
  int device;
  HIPCHECK(hipGetDevice(&device));
  ret = hipDeviceGetPCIBusId(nullptr, MAX_DEVICE_LENGTH, device);
  if (ret == hipSuccess) {
    TestPassed &= false;
    printf("Test {pciBusId = nullptr} Failed \n");
  }
  // len = 0
  ret = hipDeviceGetPCIBusId(pciBusId, 0, device);
  if (ret == hipSuccess) {
    TestPassed &= false;
    printf("Test {len = 0} Failed \n");
  }
  // len < 0
  ret = hipDeviceGetPCIBusId(pciBusId, -1, device);
  if (ret == hipSuccess) {
    TestPassed &= false;
    printf("Test {len < 0} Failed \n");
  }
  // device = -1
  ret = hipDeviceGetPCIBusId(pciBusId, MAX_DEVICE_LENGTH, -1);
  if (ret == hipSuccess) {
    TestPassed &= false;
    printf("Test {device = -1} Failed \n");
  }
  // device = Non Existing Device
  ret = hipDeviceGetPCIBusId(pciBusId, MAX_DEVICE_LENGTH, deviceCount);
  if (ret == hipSuccess) {
    TestPassed &= false;
    printf("Test {device = Non Existing Device} Failed \n");
  }
  return TestPassed;
}

int main(int argc, char* argv[]) {
  bool testResult = true;
  HipTest::parseStandardArguments(argc, argv, true);

  if (p_tests == 0x1) {
    testResult &= comparePciBusIDWithHipDeviceGetAttribute();
  }

  if (p_tests == 0x2) {
#ifdef __linux__
    testResult &= compareHipDeviceGetPCIBusIdWithLspci();
#else
    printf("Detected non-linux OS. Skipping the test\n");
#endif
  }

  if (p_tests == 0x3) {
    testResult &= testInvalidParameters();
  }

  if (testResult) {
    passed();
  } else {
    failed("one or more tests failed\n");
  }
}
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt 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 notices for more information.

  =========================================================================*/

#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbWaveletImageFilter.h"
#include "otbWaveletInverseImageFilter.h"
#include "otbWaveletGenerator.h"

#include <itkConfigure.h>
#include <itkForwardFFTImageFilter.h>
#include <itkInverseFFTImageFilter.h>
#include <itkUnaryFunctorImageFilter.h>
#include <itkFFTShiftImageFilter.h>

namespace otb
{
  namespace Wrapper
  {

    template< class TInput, class TOutput>
    class FromComplexPixel
    {
    public:
      FromComplexPixel ( ) {  };

      ~FromComplexPixel( ) {  };

      bool operator!=( const FromComplexPixel & ) const
      {
	return false;
      }

      bool operator==( const FromComplexPixel & other ) const
      {
	return !(*this != other);
      }
      inline TOutput operator( )( const TInput & A ) const
      {
	TOutput out;
	out.SetSize(2);
	out[0] = A.real();
	out[1] = A.imag();
	return out;
      }
    };

    template< class TInput, class TOutput>
    class ToComplexPixel
    {
    public:
      ToComplexPixel ( ) { };

      ~ToComplexPixel( ) { };

      bool operator!=( const ToComplexPixel & ) const
      {
	return false;
      }
      bool operator==( const ToComplexPixel & other ) const
      {
	return !(*this != other);
      }
      inline TOutput operator( )( const TInput & A ) const
      {
	TOutput out(A[0], A[1]);
	return out;
      }
    };

    class DomainTransform : public Application
    {
    public:
      /** Standard class typedefs. */
      typedef DomainTransform     Self;
      typedef Application                   Superclass;
      typedef itk::SmartPointer<Self>       Pointer;

      typedef itk::SmartPointer<const Self> ConstPointer;
      typedef float TInputPixel;
      typedef float TOutputPixel;

      /** Standard macro */
      itkNewMacro(Self);

      itkTypeMacro(Self, otb::Application);

    private:

      void DoInit() ITK_OVERRIDE
      {
	SetName("DomainTransform");

	const char * app_descr = "Domain Transform application for wavelet and fourier";
	SetDescription(app_descr);

	// Documentation
	SetDocName(app_descr);
	SetDocLongDescription("TODO");
	SetDocLimitations("None");
	SetDocAuthors("OTB-Team");
	SetDocSeeAlso("otbWaveletImageFilter, otbWaveletInverseImageFilter, otbWaveletTransform");
	AddDocTag(Tags::Filter);

	AddParameter(ParameterType_InputImage, "in",  "Input Image");
	SetParameterDescription("in", "This will take an input image to be transformed image. For FFT inverse transform, it expects a complex image as two-band image in which first band represent real part and second band represent imaginary part.");

	AddRAMParameter();

	AddParameter(ParameterType_Choice, "mode", "mode");
	SetParameterDescription("mode", "This parameter allows one to select between fft(fourier) and wavelet");
	AddChoice("mode.fft", "FFT transform");
	SetParameterDescription("mode.fft", "FFT transform");
	AddParameter(ParameterType_Empty, "mode.fft.shift", "false");
	SetParameterDescription("mode.fft.shift",
				"shift transform of fft filter");
	AddChoice("mode.wavelet", "wavelet");
	SetParameterDescription("mode.wavelet", "Wavelet transform");
	AddParameter(ParameterType_Choice,
		     "mode.wavelet.form",
		     "Select wavelet form. default is HAAR");

	AddChoice("mode.wavelet.form.haar", "HAAR");
	AddChoice("mode.wavelet.form.db4", "DAUBECHIES4");
	AddChoice("mode.wavelet.form.db6", "DAUBECHIES6");
	AddChoice("mode.wavelet.form.db8", "DAUBECHIES8");
	AddChoice("mode.wavelet.form.db12", "DAUBECHIES12");
	AddChoice("mode.wavelet.form.db20", "DAUBECHIES20");
	AddChoice("mode.wavelet.form.sb24", "SPLINE_BIORTHOGONAL_2_4");
	AddChoice("mode.wavelet.form.sb44", "SPLINE_BIORTHOGONAL_4_4");
	AddChoice("mode.wavelet.form.sym8", "SYMLET8");

	//Default value
	SetParameterString("mode", "wavelet");
	SetParameterString("mode.wavelet.form", "haar");

        AddParameter(ParameterType_Int,"mode.wavelet.nlevels","Number of decomposition levels");
        SetParameterDescription("mode.wavelet.nlevels","Number of decomposition levels");
        SetDefaultParameterInt("mode.wavelet.nlevels",2);
        SetMinimumParameterIntValue("mode.wavelet.nlevels",2);

	AddParameter(ParameterType_Choice,
		     "dir",
		     "dir: forward/inverse");

	AddChoice("dir.fwd", "fwd");
	AddChoice("dir.inv", "inv");

	AddParameter(ParameterType_OutputImage, "out", "Output Image");
	SetParameterDescription("out", "This parameter holds the output file name to which transformed image will be written. This has a slightly different behaviour depending on transform type. \n For Wavelet, output is a single band image for both forward and inverse transform. \n For FFT forward transform, output is two band image where first band represents real part and second band represents imaginary part of a complex image.");

	SetDocExampleParameterValue("in", "input.tif");
	SetDocExampleParameterValue("mode.wavelet.form", "haar");
	SetDocExampleParameterValue("out", "output_wavelet_haar.tif");
      }

      void DoUpdateParameters() ITK_OVERRIDE
      {
	// wavelet and fourier are mutually exclusive parameters.
	// check it here
#if 0
	if ( HasUserValue("mode.wavelet.form") &&
	     GetParameterString("mode") == "fft"
	     )
	  {
	    std::stringstream oss;
	    oss << std::endl
		<< this->GetNameOfClass() << "::DoUpdateParameters() "
		<< "Cannot use 'mode.wavelet.form' and '-mode fft' at same time"
		<< std::endl;

	    throw std::runtime_error( oss.str() );
	  }
#endif
      }

      void DoExecute() ITK_OVERRIDE
      {

	int dir = GetParameterInt("dir");

	int mode = GetParameterInt("mode");

	if( dir != 0 && dir != 1)
	  {
	    itkExceptionMacro( << "-dir is '"
			       << dir << "'."
			       << "It must be either 'fwd' or 'inv'");
	  }

	if( mode != 0 && mode != 1)
	  {
	    itkExceptionMacro( << "mode is '"
			       << mode << "'."
			       << "It must must be either 'fft' or 'wavelet'");
	  }

	if ( mode == 1)
	  {
	    int wavelet_type = GetParameterInt("mode.wavelet.form");
	    unsigned int nlevels = GetParameterInt("mode.wavelet.nlevels");
	    switch (wavelet_type)
	      {
	      case 0:
		DoWaveletTransform<otb::Wavelet::HAAR> ( dir, nlevels );
		break;
	      case 1:
		DoWaveletTransform< otb::Wavelet::DB4 > ( dir, nlevels );
		break;
	      case 2:
		DoWaveletTransform<otb::Wavelet::DB4> ( dir, nlevels );
		break;
	      case 3:
		DoWaveletTransform<otb::Wavelet::DB6> ( dir, nlevels );
		break;
	      case 4:
		DoWaveletTransform<otb::Wavelet::DB8> ( dir, nlevels );
		break;
	      case 5:
		DoWaveletTransform<otb::Wavelet::DB12> ( dir, nlevels );
		break;
	      case 6:
		DoWaveletTransform<otb::Wavelet::DB20> ( dir, nlevels );
		break;
	      case 7:
		DoWaveletTransform<otb::Wavelet::SPLINE_BIORTHOGONAL_2_4 > ( dir, nlevels );
		break;
	      case 8:
		DoWaveletTransform<otb::Wavelet::SPLINE_BIORTHOGONAL_4_4> ( dir, nlevels );
		break;
	      case 9:
		DoWaveletTransform<otb::Wavelet::SYMLET8> ( dir, nlevels );
		break;
	      default:
		itkExceptionMacro( << "Invalid wavelet type: '" <<  wavelet_type << "'");
		break;
	      }

	  }
	// fft ttransform
	else
	  {
	    bool shift = IsParameterEnabled( "mode.fft.shift");
	    //forward fft
	    if (dir == 0 )
	      {

		typedef otb::Image<TInputPixel>          TInputImage;
		typedef typename TInputImage::Pointer TInputImagePointer;

		//get input paramter as otb::Image<TInputPixel>
		TInputImagePointer inImage = GetParameterImage<TInputImage>("in");
		inImage->UpdateOutputInformation();
		//typedef itk::::ForwardFFTImageFilter over otbImage< TInputPixel >
		typedef itk::ForwardFFTImageFilter < TInputImage> FFTFilter;
		FFTFilter::Pointer fwdFilter = FFTFilter::New();
		fwdFilter->SetInput( inImage );

		//typedef VectorImage for output of UnaryFunctorImageFilter
		typedef otb::VectorImage<TOutputPixel>          TOutputImage;

		//UnaryFunctorImageFilter for Complex to VectorImage
		typedef itk::UnaryFunctorImageFilter<
		  typename FFTFilter::OutputImageType,
		  TOutputImage,
		  FromComplexPixel<
		    typename FFTFilter::OutputImageType::PixelType,
		    TOutputImage::PixelType> > UnaryFunctorImageFilter;

		//convert complex pixel to variable length vector
		//with unaryfunctor image filter
		UnaryFunctorImageFilter::Pointer unaryFunctorImageFilter
		  = UnaryFunctorImageFilter::New();

		if( shift)
		  {
		    otbAppLogINFO( << "Applying Shift image filter" );
		    typedef itk::FFTShiftImageFilter<
		      typename FFTFilter::OutputImageType,
		      typename FFTFilter::OutputImageType > FFTShiftFilterType;

		    FFTShiftFilterType::Pointer
		      fftShiftFilter = FFTShiftFilterType::New();

		    fftShiftFilter->SetInput( fwdFilter->GetOutput() );
		    fftShiftFilter->Update();
		    unaryFunctorImageFilter->SetInput(fftShiftFilter->GetOutput() );
		  }
		else
		  {
		    unaryFunctorImageFilter->SetInput(fwdFilter->GetOutput());
		  }

		unaryFunctorImageFilter->Update();

		//set output image
		SetParameterOutputImage<TOutputImage>
		  ( "out", unaryFunctorImageFilter->GetOutput() );
	      }
	    //inverse fft
	    else
	      {
		typedef otb::VectorImage<TInputPixel>          TInputImage;
		typedef typename TInputImage::Pointer TInputImagePointer;

		TInputImagePointer inImage = GetParameterImage("in");

		inImage->UpdateOutputInformation();

		// typedef TComplexImage for InverseFFTImageFilter input
		// This a image type of std::complex<TInputPixel>
		typedef otb::Image<
		  std::complex<TInputPixel>, 2 > TComplexImage;
		//typedef TOutputImage for InverseFFTImageFilter output
		typedef otb::Image< TOutputPixel >  TOutputImage;

		// a unary functor to convert vectorimage to complex image
		typedef itk::UnaryFunctorImageFilter
		  <TInputImage,
		   TComplexImage,
		   ToComplexPixel
		   <TInputImage::PixelType,
		    TComplexImage::PixelType> > UnaryFunctorImageFilter;

		UnaryFunctorImageFilter::Pointer
		  unaryFunctorImageFilter = UnaryFunctorImageFilter::New();

		if( shift)
		  {
		    typedef itk::FFTShiftImageFilter<
		      TInputImage,
		      TInputImage > FFTShiftFilterType;

		    FFTShiftFilterType::Pointer
		      fftShiftFilter = FFTShiftFilterType::New();
		    fftShiftFilter->SetInput( inImage );

		    fftShiftFilter->Update();

		    unaryFunctorImageFilter->SetInput(fftShiftFilter->GetOutput() );

		  }
		else
		  {
		    unaryFunctorImageFilter->SetInput(inImage);
		  }

		unaryFunctorImageFilter->Update();

		//typedef itk::::InverseFFTImageFilter over TComplexImage
		typedef itk::InverseFFTImageFilter
		  < TComplexImage,
		    TOutputImage > FFTFilter;
		FFTFilter::Pointer invFilter = FFTFilter::New();
		invFilter->SetInput( unaryFunctorImageFilter->GetOutput() );
		invFilter->Update();

		//set output image
		SetParameterOutputImage<
		  TOutputImage >
		  ( "out", invFilter->GetOutput() );
	      }

	  }

      }

      template<otb::Wavelet::Wavelet TWaveletOperator>
      void DoWaveletTransform(const int dir,
                              const unsigned int nlevels,
			      const std::string inkey = "in",
			      const std::string outkey = "out")
      {

	typedef otb::Image< TInputPixel >  TInputImage;
	typedef otb::Image< TOutputPixel >  TOutputImage;
	typedef typename TInputImage::Pointer TInputImagePointer;

	TInputImagePointer inImage = GetParameterImage<TInputImage>(inkey);

	inImage->UpdateOutputInformation();

	if( dir == 0)
	  {

	    typedef otb::WaveletImageFilter<
	      TInputImage,
	      TOutputImage,
	      TWaveletOperator> TWaveletImageFilter;

	    typedef typename
	      TWaveletImageFilter::Pointer
	      TWaveletImageFilterPointer;
	    TWaveletImageFilterPointer waveletImageFilter =
	      TWaveletImageFilter::New();

	    waveletImageFilter->SetInput(inImage);
	    waveletImageFilter->SetNumberOfDecompositions(nlevels);
	    waveletImageFilter->Update();
	    SetParameterOutputImage<TOutputImage>(outkey, waveletImageFilter->GetOutput() );

	  }

	else
	  {
	    typedef otb::WaveletInverseImageFilter<
	      TInputImage,
	      TOutputImage,
	      TWaveletOperator > TWaveletImageFilter;

	    typedef typename
	      TWaveletImageFilter::Pointer
	      TWaveletImageFilterPointer;

	    TWaveletImageFilterPointer waveletImageFilter =
	      TWaveletImageFilter::New();

	    waveletImageFilter->SetInput(inImage);
	    waveletImageFilter->SetNumberOfDecompositions(nlevels);
	    waveletImageFilter->Update();

	    SetParameterOutputImage<TOutputImage>( outkey, waveletImageFilter->GetOutput() );

	  }

      }

    };
  }
}

OTB_APPLICATION_EXPORT(otb::Wrapper::DomainTransform)
<commit_msg>COMP: fix for VC10<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt 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 notices for more information.

  =========================================================================*/

#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbWaveletImageFilter.h"
#include "otbWaveletInverseImageFilter.h"
#include "otbWaveletGenerator.h"

#include <itkConfigure.h>
#include <itkForwardFFTImageFilter.h>
#include <itkInverseFFTImageFilter.h>
#include <itkUnaryFunctorImageFilter.h>
#include <itkFFTShiftImageFilter.h>

namespace otb
{
  namespace Wrapper
  {

    template< class TInput, class TOutput>
    class FromComplexPixel
    {
    public:
      FromComplexPixel ( ) {  };

      ~FromComplexPixel( ) {  };

      bool operator!=( const FromComplexPixel & ) const
      {
	return false;
      }

      bool operator==( const FromComplexPixel & other ) const
      {
	return !(*this != other);
      }
      inline TOutput operator( )( const TInput & A ) const
      {
	TOutput out;
	out.SetSize(2);
	out[0] = A.real();
	out[1] = A.imag();
	return out;
      }
    };

    template< class TInput, class TOutput>
    class ToComplexPixel
    {
    public:
      ToComplexPixel ( ) { };

      ~ToComplexPixel( ) { };

      bool operator!=( const ToComplexPixel & ) const
      {
	return false;
      }
      bool operator==( const ToComplexPixel & other ) const
      {
	return !(*this != other);
      }
      inline TOutput operator( )( const TInput & A ) const
      {
	TOutput out(A[0], A[1]);
	return out;
      }
    };

    class DomainTransform : public Application
    {
    public:
      /** Standard class typedefs. */
      typedef DomainTransform     Self;
      typedef Application                   Superclass;
      typedef itk::SmartPointer<Self>       Pointer;

      typedef itk::SmartPointer<const Self> ConstPointer;
      typedef float TInputPixel;
      typedef float TOutputPixel;

      /** Standard macro */
      itkNewMacro(Self);

      itkTypeMacro(Self, otb::Application);

    private:

      void DoInit() ITK_OVERRIDE
      {
	SetName("DomainTransform");

	const char * app_descr = "Domain Transform application for wavelet and fourier";
	SetDescription(app_descr);

	// Documentation
	SetDocName(app_descr);
	SetDocLongDescription("TODO");
	SetDocLimitations("None");
	SetDocAuthors("OTB-Team");
	SetDocSeeAlso("otbWaveletImageFilter, otbWaveletInverseImageFilter, otbWaveletTransform");
	AddDocTag(Tags::Filter);

	AddParameter(ParameterType_InputImage, "in",  "Input Image");
	SetParameterDescription("in", "This will take an input image to be transformed image. For FFT inverse transform, it expects a complex image as two-band image in which first band represent real part and second band represent imaginary part.");

	AddRAMParameter();

	AddParameter(ParameterType_Choice, "mode", "mode");
	SetParameterDescription("mode", "This parameter allows one to select between fft(fourier) and wavelet");
	AddChoice("mode.fft", "FFT transform");
	SetParameterDescription("mode.fft", "FFT transform");
	AddParameter(ParameterType_Empty, "mode.fft.shift", "false");
	SetParameterDescription("mode.fft.shift",
				"shift transform of fft filter");
	AddChoice("mode.wavelet", "wavelet");
	SetParameterDescription("mode.wavelet", "Wavelet transform");
	AddParameter(ParameterType_Choice,
		     "mode.wavelet.form",
		     "Select wavelet form. default is HAAR");

	AddChoice("mode.wavelet.form.haar", "HAAR");
	AddChoice("mode.wavelet.form.db4", "DAUBECHIES4");
	AddChoice("mode.wavelet.form.db6", "DAUBECHIES6");
	AddChoice("mode.wavelet.form.db8", "DAUBECHIES8");
	AddChoice("mode.wavelet.form.db12", "DAUBECHIES12");
	AddChoice("mode.wavelet.form.db20", "DAUBECHIES20");
	AddChoice("mode.wavelet.form.sb24", "SPLINE_BIORTHOGONAL_2_4");
	AddChoice("mode.wavelet.form.sb44", "SPLINE_BIORTHOGONAL_4_4");
	AddChoice("mode.wavelet.form.sym8", "SYMLET8");

	//Default value
	SetParameterString("mode", "wavelet");
	SetParameterString("mode.wavelet.form", "haar");

        AddParameter(ParameterType_Int,"mode.wavelet.nlevels","Number of decomposition levels");
        SetParameterDescription("mode.wavelet.nlevels","Number of decomposition levels");
        SetDefaultParameterInt("mode.wavelet.nlevels",2);
        SetMinimumParameterIntValue("mode.wavelet.nlevels",2);

	AddParameter(ParameterType_Choice,
		     "dir",
		     "dir: forward/inverse");

	AddChoice("dir.fwd", "fwd");
	AddChoice("dir.inv", "inv");

	AddParameter(ParameterType_OutputImage, "out", "Output Image");
	SetParameterDescription("out", "This parameter holds the output file name to which transformed image will be written. This has a slightly different behaviour depending on transform type. \n For Wavelet, output is a single band image for both forward and inverse transform. \n For FFT forward transform, output is two band image where first band represents real part and second band represents imaginary part of a complex image.");

	SetDocExampleParameterValue("in", "input.tif");
	SetDocExampleParameterValue("mode.wavelet.form", "haar");
	SetDocExampleParameterValue("out", "output_wavelet_haar.tif");
      }

      void DoUpdateParameters() ITK_OVERRIDE
      {
	// wavelet and fourier are mutually exclusive parameters.
	// check it here
#if 0
	if ( HasUserValue("mode.wavelet.form") &&
	     GetParameterString("mode") == "fft"
	     )
	  {
	    std::stringstream oss;
	    oss << std::endl
		<< this->GetNameOfClass() << "::DoUpdateParameters() "
		<< "Cannot use 'mode.wavelet.form' and '-mode fft' at same time"
		<< std::endl;

	    throw std::runtime_error( oss.str() );
	  }
#endif
      }

      void DoExecute() ITK_OVERRIDE
      {

	int dir = GetParameterInt("dir");

	int mode = GetParameterInt("mode");

	if( dir != 0 && dir != 1)
	  {
	    itkExceptionMacro( << "-dir is '"
			       << dir << "'."
			       << "It must be either 'fwd' or 'inv'");
	  }

	if( mode != 0 && mode != 1)
	  {
	    itkExceptionMacro( << "mode is '"
			       << mode << "'."
			       << "It must must be either 'fft' or 'wavelet'");
	  }

	if ( mode == 1)
	  {
	    int wavelet_type = GetParameterInt("mode.wavelet.form");
	    unsigned int nlevels = GetParameterInt("mode.wavelet.nlevels");
	    switch (wavelet_type)
	      {
	      case 0:
		DoWaveletTransform<otb::Wavelet::HAAR> ( dir, nlevels );
		break;
	      case 1:
		DoWaveletTransform< otb::Wavelet::DB4 > ( dir, nlevels );
		break;
	      case 2:
		DoWaveletTransform<otb::Wavelet::DB4> ( dir, nlevels );
		break;
	      case 3:
		DoWaveletTransform<otb::Wavelet::DB6> ( dir, nlevels );
		break;
	      case 4:
		DoWaveletTransform<otb::Wavelet::DB8> ( dir, nlevels );
		break;
	      case 5:
		DoWaveletTransform<otb::Wavelet::DB12> ( dir, nlevels );
		break;
	      case 6:
		DoWaveletTransform<otb::Wavelet::DB20> ( dir, nlevels );
		break;
	      case 7:
		DoWaveletTransform<otb::Wavelet::SPLINE_BIORTHOGONAL_2_4 > ( dir, nlevels );
		break;
	      case 8:
		DoWaveletTransform<otb::Wavelet::SPLINE_BIORTHOGONAL_4_4> ( dir, nlevels );
		break;
	      case 9:
		DoWaveletTransform<otb::Wavelet::SYMLET8> ( dir, nlevels );
		break;
	      default:
		itkExceptionMacro( << "Invalid wavelet type: '" <<  wavelet_type << "'");
		break;
	      }

	  }
	// fft ttransform
	else
	  {
	    bool shift = IsParameterEnabled( "mode.fft.shift");
	    //forward fft
	    if (dir == 0 )
	      {

		typedef otb::Image<TInputPixel>          TInputImage;
		typedef TInputImage::Pointer TInputImagePointer;

		//get input paramter as otb::Image<TInputPixel>
		TInputImagePointer inImage = GetParameterImage<TInputImage>("in");
		inImage->UpdateOutputInformation();
		//typedef itk::::ForwardFFTImageFilter over otbImage< TInputPixel >
		typedef itk::ForwardFFTImageFilter < TInputImage> FFTFilter;
		FFTFilter::Pointer fwdFilter = FFTFilter::New();
		fwdFilter->SetInput( inImage );

		//typedef VectorImage for output of UnaryFunctorImageFilter
		typedef otb::VectorImage<TOutputPixel>          TOutputImage;

		//UnaryFunctorImageFilter for Complex to VectorImage
		typedef itk::UnaryFunctorImageFilter<
		  typename FFTFilter::OutputImageType,
		  TOutputImage,
		  FromComplexPixel<
		    typename FFTFilter::OutputImageType::PixelType,
		    TOutputImage::PixelType> > UnaryFunctorImageFilter;

		//convert complex pixel to variable length vector
		//with unaryfunctor image filter
		UnaryFunctorImageFilter::Pointer unaryFunctorImageFilter
		  = UnaryFunctorImageFilter::New();

		if( shift)
		  {
		    otbAppLogINFO( << "Applying Shift image filter" );
		    typedef itk::FFTShiftImageFilter<
		      typename FFTFilter::OutputImageType,
		      typename FFTFilter::OutputImageType > FFTShiftFilterType;

		    FFTShiftFilterType::Pointer
		      fftShiftFilter = FFTShiftFilterType::New();

		    fftShiftFilter->SetInput( fwdFilter->GetOutput() );
		    fftShiftFilter->Update();
		    unaryFunctorImageFilter->SetInput(fftShiftFilter->GetOutput() );
		  }
		else
		  {
		    unaryFunctorImageFilter->SetInput(fwdFilter->GetOutput());
		  }

		unaryFunctorImageFilter->Update();

		//set output image
		SetParameterOutputImage<TOutputImage>
		  ( "out", unaryFunctorImageFilter->GetOutput() );
	      }
	    //inverse fft
	    else
	      {
		typedef otb::VectorImage<TInputPixel>          TInputImage;
		typedef TInputImage::Pointer TInputImagePointer;

		TInputImagePointer inImage = GetParameterImage("in");

		inImage->UpdateOutputInformation();

		// typedef TComplexImage for InverseFFTImageFilter input
		// This a image type of std::complex<TInputPixel>
		typedef otb::Image<
		  std::complex<TInputPixel>, 2 > TComplexImage;
		//typedef TOutputImage for InverseFFTImageFilter output
		typedef otb::Image< TOutputPixel >  TOutputImage;

		// a unary functor to convert vectorimage to complex image
		typedef itk::UnaryFunctorImageFilter
		  <TInputImage,
		   TComplexImage,
		   ToComplexPixel
		   <TInputImage::PixelType,
		    TComplexImage::PixelType> > UnaryFunctorImageFilter;

		UnaryFunctorImageFilter::Pointer
		  unaryFunctorImageFilter = UnaryFunctorImageFilter::New();

		if( shift)
		  {
		    typedef itk::FFTShiftImageFilter<
		      TInputImage,
		      TInputImage > FFTShiftFilterType;

		    FFTShiftFilterType::Pointer
		      fftShiftFilter = FFTShiftFilterType::New();
		    fftShiftFilter->SetInput( inImage );

		    fftShiftFilter->Update();

		    unaryFunctorImageFilter->SetInput(fftShiftFilter->GetOutput() );

		  }
		else
		  {
		    unaryFunctorImageFilter->SetInput(inImage);
		  }

		unaryFunctorImageFilter->Update();

		//typedef itk::::InverseFFTImageFilter over TComplexImage
		typedef itk::InverseFFTImageFilter
		  < TComplexImage,
		    TOutputImage > FFTFilter;
		FFTFilter::Pointer invFilter = FFTFilter::New();
		invFilter->SetInput( unaryFunctorImageFilter->GetOutput() );
		invFilter->Update();

		//set output image
		SetParameterOutputImage<
		  TOutputImage >
		  ( "out", invFilter->GetOutput() );
	      }

	  }

      }

      template<otb::Wavelet::Wavelet TWaveletOperator>
      void DoWaveletTransform(const int dir,
                              const unsigned int nlevels,
			      const std::string inkey = "in",
			      const std::string outkey = "out")
      {

	typedef otb::Image< TInputPixel >  TInputImage;
	typedef otb::Image< TOutputPixel >  TOutputImage;
	typedef typename TInputImage::Pointer TInputImagePointer;

	TInputImagePointer inImage = GetParameterImage<TInputImage>(inkey);

	inImage->UpdateOutputInformation();

	if( dir == 0)
	  {

	    typedef otb::WaveletImageFilter<
	      TInputImage,
	      TOutputImage,
	      TWaveletOperator> TWaveletImageFilter;

	    typedef typename
	      TWaveletImageFilter::Pointer
	      TWaveletImageFilterPointer;
	    TWaveletImageFilterPointer waveletImageFilter =
	      TWaveletImageFilter::New();

	    waveletImageFilter->SetInput(inImage);
	    waveletImageFilter->SetNumberOfDecompositions(nlevels);
	    waveletImageFilter->Update();
	    SetParameterOutputImage<TOutputImage>(outkey, waveletImageFilter->GetOutput() );

	  }

	else
	  {
	    typedef otb::WaveletInverseImageFilter<
	      TInputImage,
	      TOutputImage,
	      TWaveletOperator > TWaveletImageFilter;

	    typedef typename
	      TWaveletImageFilter::Pointer
	      TWaveletImageFilterPointer;

	    TWaveletImageFilterPointer waveletImageFilter =
	      TWaveletImageFilter::New();

	    waveletImageFilter->SetInput(inImage);
	    waveletImageFilter->SetNumberOfDecompositions(nlevels);
	    waveletImageFilter->Update();

	    SetParameterOutputImage<TOutputImage>( outkey, waveletImageFilter->GetOutput() );

	  }

      }

    };
  }
}

OTB_APPLICATION_EXPORT(otb::Wrapper::DomainTransform)
<|endoftext|>