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

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkAcosImageFilter.h"
#include "itkAdaptImageFilter.h"
#include "itkAddImageFilter.h"
#include "itkAnisotropicDiffusionEquation.h"
#include "itkAnisotropicDiffusionImageFilter.h"
#include "itkAsinImageFilter.h"
#include "itkAtan2ImageFilter.h"
#include "itkAtanImageFilter.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkBinaryErodeImageFilter.h"
#include "itkBinaryFunctorImageFilter.h"
#include "itkBinaryMagnitudeImageFilter.h"
#include "itkBinaryMorphologicalDialationFilter.h"
#include "itkBinaryMorphologicalErosionFilter.h"
#include "itkBinaryMorphologicalFilterBase.h"
#include "itkBinomialBlurImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkConstantPadImageFilter.h"
#include "itkCosImageFilter.h"
#include "itkCurvature2DAnisotropicDiffusionEquation.h"
#include "itkCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkCurvatureNDAnisotropicDiffusionEquation.h"
#include "itkDanielssonDistanceMapImageFilter.h"
#include "itkDerivativeImageFilter.h"
#include "itkDifferenceOfGaussiansGradientImageFilter.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkEigenAnalysis2DImageFilter.h"
#include "itkExpImageFilter.h"
#include "itkExpandImageFilter.h"
#include "itkExtractImageFilter.h"
#include "itkFileIOToImageFilter.h"
#include "itkFirstDerivativeRecursiveGaussianImageFilter.h"
#include "itkGradient2DAnisotropicDiffusionEquation.h"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
#include "itkGradientImageFilter.h"
#include "itkGradientMagnitudeImageFilter.h"
#include "itkGradientNDAnisotropicDiffusionEquation.h"
#include "itkGradientRecursiveGaussianImageFilter.h"
#include "itkGradientToMagnitudeImageFilter.h"
#include "itkGrayscaleDilateImageFilter.h"
#include "itkGrayscaleErodeImageFilter.h"
#include "itkGrayscaleFunctionDilateImageFilter.h"
#include "itkGrayscaleFunctionErodeImageFilter.h"
#include "itkImageFileReader.h"
#include "itkImageToMeshFilter.h"
#include "itkImageToParametricSpaceFilter.h"
#include "itkImageWriter.h"
#include "itkImportImageFilter.h"
#include "itkJoinImageFilter.h"
#include "itkLog10ImageFilter.h"
#include "itkLogImageFilter.h"
#include "itkMirrorPadImageFilter.h"
#include "itkMorphologyImageFilter.h"
#include "itkMultiplyImageFilter.h"
#include "itkNaryAddImageFilter.h"
#include "itkNaryFunctorImageFilter.h"
#include "itkNeighborhoodOperatorImageFilter.h"
#include "itkNonThreadedShrinkImageFilter.h"
#include "itkPadImageFilter.h"
#include "itkPlaheImageFilter.h"
#include "itkRandomImageSource.h"
#include "itkRawImageWriter.h"
#include "itkRecursiveGaussianImageFilter.h"
#include "itkRecursiveSeparableImageFilter.h"
#include "itkReflectiveImageRegionIterator.h"
#include "itkResampleImageFilter.h"
#include "itkScalarAnisotropicDiffusionEquation.h"
#include "itkSecondDerivativeRecursiveGaussianImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "itkSinImageFilter.h"
#include "itkSpatialFunctionImageEvaluatorFilter.h"
#include "itkSqrtImageFilter.h"
#include "itkStreamingImageFilter.h"
#include "itkSubtractImageFilter.h"
#include "itkTanImageFilter.h"
#include "itkTernaryAddImageFilter.h"
#include "itkTernaryFunctorImageFilter.h"
#include "itkTernaryMagnitudeImageFilter.h"
#include "itkTernaryMagnitudeSquaredImageFilter.h"
#include "itkThresholdImageFilter.h"
#include "itkTransformMeshFilter.h"
#include "itkTwoOutputExampleImageFilter.h"
#include "itkUnaryFunctorImageFilter.h"
#include "itkVTKImageExport.h"
#include "itkVTKImageExportBase.h"
#include "itkVTKImageReader.h"
#include "itkVTKImageWriter.h"
#include "itkVectorAnisotropicDiffusionEquation.h"
#include "itkVectorCastImageFilter.h"
#include "itkVectorCurvature2DAnisotropicDiffusionEquation.h"
#include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkVectorCurvatureNDAnisotropicDiffusionEquation.h"
#include "itkVectorExpandImageFilter.h"
#include "itkVectorGradient2DAnisotropicDiffusionEquation.h"
#include "itkVectorGradientAnisotropicDiffusionImageFilter.h"
#include "itkVectorGradientNDAnisotropicDiffusionEquation.h"
#include "itkVectorNeighborhoodOperatorImageFilter.h"
#include "itkWarpImageFilter.h"
#include "itkWrapPadImageFilter.h"
#include "itkWriter.h"

int main ( int argc, char* argv )
{

  return 0;
}

<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkAcosImageFilter.h"
#include "itkAdaptImageFilter.h"
#include "itkAddImageFilter.h"
#include "itkAnisotropicDiffusionEquation.h"
#include "itkAnisotropicDiffusionImageFilter.h"
#include "itkAsinImageFilter.h"
#include "itkAtan2ImageFilter.h"
#include "itkAtanImageFilter.h"
#include "itkBinaryDilateImageFilter.h"
#include "itkBinaryErodeImageFilter.h"
#include "itkBinaryFunctorImageFilter.h"
#include "itkBinaryMagnitudeImageFilter.h"
#include "itkBinaryMorphologicalDialationFilter.h"
#include "itkBinaryMorphologicalErosionFilter.h"
#include "itkBinaryMorphologicalFilterBase.h"
#include "itkBinomialBlurImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkConstantPadImageFilter.h"
#include "itkCosImageFilter.h"
#include "itkCurvature2DAnisotropicDiffusionEquation.h"
#include "itkCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkCurvatureNDAnisotropicDiffusionEquation.h"
#include "itkDanielssonDistanceMapImageFilter.h"
#include "itkDerivativeImageFilter.h"
#include "itkDifferenceOfGaussiansGradientImageFilter.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkEigenAnalysis2DImageFilter.h"
#include "itkExpImageFilter.h"
#include "itkExpandImageFilter.h"
#include "itkExtractImageFilter.h"
#include "itkFileIOToImageFilter.h"
#include "itkFirstDerivativeRecursiveGaussianImageFilter.h"
#include "itkGradient2DAnisotropicDiffusionEquation.h"
#include "itkGradientAnisotropicDiffusionImageFilter.h"
#include "itkGradientImageFilter.h"
#include "itkGradientMagnitudeImageFilter.h"
#include "itkGradientNDAnisotropicDiffusionEquation.h"
#include "itkGradientRecursiveGaussianImageFilter.h"
#include "itkGradientToMagnitudeImageFilter.h"
#include "itkGrayscaleDilateImageFilter.h"
#include "itkGrayscaleErodeImageFilter.h"
#include "itkGrayscaleFunctionDilateImageFilter.h"
#include "itkGrayscaleFunctionErodeImageFilter.h"
#include "itkImageToMeshFilter.h"
#include "itkImageToParametricSpaceFilter.h"
#include "itkImageWriter.h"
#include "itkImportImageFilter.h"
#include "itkJoinImageFilter.h"
#include "itkLog10ImageFilter.h"
#include "itkLogImageFilter.h"
#include "itkMirrorPadImageFilter.h"
#include "itkMorphologyImageFilter.h"
#include "itkMultiplyImageFilter.h"
#include "itkNaryAddImageFilter.h"
#include "itkNaryFunctorImageFilter.h"
#include "itkNeighborhoodOperatorImageFilter.h"
#include "itkNonThreadedShrinkImageFilter.h"
#include "itkPadImageFilter.h"
#include "itkPlaheImageFilter.h"
#include "itkRandomImageSource.h"
#include "itkRawImageWriter.h"
#include "itkRecursiveGaussianImageFilter.h"
#include "itkRecursiveSeparableImageFilter.h"
#include "itkReflectiveImageRegionIterator.h"
#include "itkResampleImageFilter.h"
#include "itkScalarAnisotropicDiffusionEquation.h"
#include "itkSecondDerivativeRecursiveGaussianImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "itkSinImageFilter.h"
#include "itkSpatialFunctionImageEvaluatorFilter.h"
#include "itkSqrtImageFilter.h"
#include "itkStreamingImageFilter.h"
#include "itkSubtractImageFilter.h"
#include "itkTanImageFilter.h"
#include "itkTernaryAddImageFilter.h"
#include "itkTernaryFunctorImageFilter.h"
#include "itkTernaryMagnitudeImageFilter.h"
#include "itkTernaryMagnitudeSquaredImageFilter.h"
#include "itkThresholdImageFilter.h"
#include "itkTransformMeshFilter.h"
#include "itkTwoOutputExampleImageFilter.h"
#include "itkUnaryFunctorImageFilter.h"
#include "itkVTKImageExport.h"
#include "itkVTKImageExportBase.h"
#include "itkVTKImageReader.h"
#include "itkVTKImageWriter.h"
#include "itkVectorAnisotropicDiffusionEquation.h"
#include "itkVectorCastImageFilter.h"
#include "itkVectorCurvature2DAnisotropicDiffusionEquation.h"
#include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h"
#include "itkVectorCurvatureNDAnisotropicDiffusionEquation.h"
#include "itkVectorExpandImageFilter.h"
#include "itkVectorGradient2DAnisotropicDiffusionEquation.h"
#include "itkVectorGradientAnisotropicDiffusionImageFilter.h"
#include "itkVectorGradientNDAnisotropicDiffusionEquation.h"
#include "itkVectorNeighborhoodOperatorImageFilter.h"
#include "itkWarpImageFilter.h"
#include "itkWrapPadImageFilter.h"
#include "itkWriter.h"

int main ( int argc, char* argv )
{

  return 0;
}

<|endoftext|>


<commit_before>/*
    Copyright 2002-2013 CEA LIST

    This file is part of LIMA.

    LIMA is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    LIMA is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with LIMA.  If not, see <http://www.gnu.org/licenses/>
*/

// NAUTITIA
//
// jys 24-JUL-2002
//
// Tokenizer is the main program of Tokenizer stuff.

#include "Tokenizer.h"

#include "Automaton.h"
#include "State.h"
// #include "linguisticProcessing/core/Tokenizer/CharChart.h"
#include "common/misc/Exceptions.h"
#include "common/Data/strwstrtools.h"
#include "common/AbstractFactoryPattern/SimpleFactory.h"
#include "linguisticProcessing/core/LinguisticResources/LinguisticResources.h"
#include "linguisticProcessing/core/LinguisticProcessors/LimaStringText.h"
#include "linguisticProcessing/core/LinguisticAnalysisStructure/AnalysisGraph.h"
#include "common/XMLConfigurationFiles/xmlConfigurationFileExceptions.h"
#include "common/MediaticData/mediaticData.h"
#include "common/time/timeUtilsController.h"
#include <string>

using namespace std;
using namespace Lima::LinguisticProcessing::LinguisticAnalysisStructure;
using namespace Lima::Common::XMLConfigurationFiles;
using namespace Lima::Common::Misc;

namespace Lima
{
namespace LinguisticProcessing
{
namespace FlatTokenizer
{

static SimpleFactory<MediaProcessUnit,Tokenizer> tokenizerFactory(FLATTOKENIZER_CLASSID);

class TokenizerPrivate
{
public:
  TokenizerPrivate();
  virtual ~TokenizerPrivate();

  Automaton _automaton;
  CharChart* _charChart;
  MediaId _language;

};

TokenizerPrivate::TokenizerPrivate() : _automaton()
{}

TokenizerPrivate::~TokenizerPrivate()
{
}

Tokenizer::Tokenizer() : m_d(new TokenizerPrivate())
{}

Tokenizer::~Tokenizer()
{
  delete m_d;
}

const CharChart* Tokenizer::charChart() const {return m_d->_charChart;}
CharChart* Tokenizer::charChart() {return m_d->_charChart;}
void Tokenizer::setCharChart(CharChart* charChart) {m_d->_charChart = charChart;}

void Tokenizer::init(
  Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration,
  Manager* manager)

{
  TOKENIZERLOGINIT;
  LDEBUG << "Tokenizer::init";
  m_d->_language=manager->getInitializationParameters().media;
  try
  {
    string charchartId=unitConfiguration.getParamsValueAtKey("charChart");
    AbstractResource* res=LinguisticResources::single().getResource(m_d->_language,charchartId);
    m_d->_charChart=static_cast<CharChart*>(res);
  }
  catch (NoSuchParam& )
  {
    LERROR << "no param 'charChart' in Tokenizer group configuration (language="
    << (int) m_d->_language << ")";
    throw InvalidConfiguration();
  }

  try
  {
    string resourcesPath=Common::MediaticData::MediaticData::single().getResourcesPath();
    string fileName=resourcesPath +"/"+unitConfiguration.getParamsValueAtKey("automatonFile");
    m_d->_automaton.setCharChart(m_d->_charChart);
    m_d->_automaton.loadFromFile(fileName);
  }
  catch (NoSuchParam& )
  {
    LERROR << "no param 'automatonFile' in Tokenizer group configuration (language="
    << (int) m_d->_language << ")";
    throw InvalidConfiguration();
  }
  // when input XML file is syntactically wrong
  catch (XmlSyntaxException exc)
  {
    std::ostringstream mess;
    mess << "XmlSyntaxException at line "<<exc._lineNumber<<" cause: ";
    switch (exc._why)
    {
        case XmlSyntaxException::SYNTAX_EXC : mess << "SYNTAX_EXC"; break;
        case XmlSyntaxException::NO_DATA_EXC : mess << "NO_DATA_EXC"; break;
        case XmlSyntaxException::DOUBLE_EXC : mess << "DOUBLE_EXC"; break;
        case XmlSyntaxException::FWD_CLASS_EXC : mess << "FWD_CLASS_EXC"; break;
        case XmlSyntaxException::MULT_CLASS_EXC : mess << "MULT_CLASS_EXC"; break;
        case XmlSyntaxException::EOF_EXC : mess << "EOF_EXC"; break;
        case XmlSyntaxException::NO_CODE_EXC : mess << "NO_CODE_EXC"; break;
        case XmlSyntaxException::BAD_CODE_EXC : mess << "BAD_CODE_EXC"; break;
        case XmlSyntaxException::NO_CLASS_EXC : mess << "NO_CLASS_EXC"; break;
        case XmlSyntaxException::UNK_CLASS_EXC : mess << "UNK_CLASS_EXC"; break;
        case XmlSyntaxException::INT_ERROR_EXC : mess << "INT_ERROR_EXC"; break;
        case XmlSyntaxException::INV_CLASS_EXC : mess << "INV_CLASS_EXC"; break;
        default: mess << "??";
    }
    LERROR << mess.str();
    throw InvalidConfiguration();
  }
  catch (std::exception &exc)
  {
    // @todo remove all causes of InfiniteLoopException
    LERROR << exc.what();
    throw InvalidConfiguration();
  }

}

LimaStatusCode Tokenizer::process(
  AnalysisContent& analysis) const
{
  TimeUtilsController flatTokenizerProcessTime("FlatTokenizer");
  TOKENIZERLOGINIT;
  LINFO << "start tokenizer process";
  LimaStringText* originalText=static_cast<LimaStringText*>(analysis.getData("Text"));
  AnalysisGraph* anagraph(0);

  anagraph=new AnalysisGraph("AnalysisGraph",m_d->_language,true,true);
  analysis.setData("AnalysisGraph",anagraph);
  LinguisticGraph* graph=anagraph->getGraph();
  // Gets transformed file into characters class string
  Text* text=new Text(m_d->_language, m_d->_charChart);
  text->setText(*originalText);
  text->setGraph(anagraph->firstVertex(),graph);

  LINFO << "Running automaton on '" << *originalText << "'";
  const State* newState = m_d->_automaton.run(*text);
  while (newState)
  {
    LTRACE << "Running automaton";
    newState = m_d->_automaton.run(*text, newState);
  }
  if (text->position() < text->size()-1)
  {
    LERROR << "Tokenized up to " << text->position()
        << " for a text of size " << text->size() ;
  }
  text->finalizeAndUnsetGraph();
  remove_edge(anagraph->firstVertex(),anagraph->lastVertex(),*(anagraph->getGraph()));
  delete text;
  return SUCCESS_ID;
}

} //namespace FlatTokenizer
} // namespace LinguisticProcessing
} // namespace Lima
<commit_msg>Simplify a debug output<commit_after>/*
    Copyright 2002-2013 CEA LIST

    This file is part of LIMA.

    LIMA is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    LIMA is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with LIMA.  If not, see <http://www.gnu.org/licenses/>
*/

// NAUTITIA
//
// jys 24-JUL-2002
//
// Tokenizer is the main program of Tokenizer stuff.

#include "Tokenizer.h"

#include "Automaton.h"
#include "State.h"
// #include "linguisticProcessing/core/Tokenizer/CharChart.h"
#include "common/misc/Exceptions.h"
#include "common/Data/strwstrtools.h"
#include "common/AbstractFactoryPattern/SimpleFactory.h"
#include "linguisticProcessing/core/LinguisticResources/LinguisticResources.h"
#include "linguisticProcessing/core/LinguisticProcessors/LimaStringText.h"
#include "linguisticProcessing/core/LinguisticAnalysisStructure/AnalysisGraph.h"
#include "common/XMLConfigurationFiles/xmlConfigurationFileExceptions.h"
#include "common/MediaticData/mediaticData.h"
#include "common/time/timeUtilsController.h"
#include <string>

using namespace std;
using namespace Lima::LinguisticProcessing::LinguisticAnalysisStructure;
using namespace Lima::Common::XMLConfigurationFiles;
using namespace Lima::Common::Misc;

namespace Lima
{
namespace LinguisticProcessing
{
namespace FlatTokenizer
{

static SimpleFactory<MediaProcessUnit,Tokenizer> tokenizerFactory(FLATTOKENIZER_CLASSID);

class TokenizerPrivate
{
public:
  TokenizerPrivate();
  virtual ~TokenizerPrivate();

  Automaton _automaton;
  CharChart* _charChart;
  MediaId _language;

};

TokenizerPrivate::TokenizerPrivate() : _automaton()
{}

TokenizerPrivate::~TokenizerPrivate()
{
}

Tokenizer::Tokenizer() : m_d(new TokenizerPrivate())
{}

Tokenizer::~Tokenizer()
{
  delete m_d;
}

const CharChart* Tokenizer::charChart() const {return m_d->_charChart;}
CharChart* Tokenizer::charChart() {return m_d->_charChart;}
void Tokenizer::setCharChart(CharChart* charChart) {m_d->_charChart = charChart;}

void Tokenizer::init(
  Common::XMLConfigurationFiles::GroupConfigurationStructure& unitConfiguration,
  Manager* manager)

{
  TOKENIZERLOGINIT;
  LDEBUG << "Tokenizer::init";
  m_d->_language=manager->getInitializationParameters().media;
  try
  {
    string charchartId=unitConfiguration.getParamsValueAtKey("charChart");
    AbstractResource* res=LinguisticResources::single().getResource(m_d->_language,charchartId);
    m_d->_charChart=static_cast<CharChart*>(res);
  }
  catch (NoSuchParam& )
  {
    LERROR << "no param 'charChart' in Tokenizer group configuration (language="
    << (int) m_d->_language << ")";
    throw InvalidConfiguration();
  }

  try
  {
    string resourcesPath=Common::MediaticData::MediaticData::single().getResourcesPath();
    string fileName=resourcesPath +"/"+unitConfiguration.getParamsValueAtKey("automatonFile");
    m_d->_automaton.setCharChart(m_d->_charChart);
    m_d->_automaton.loadFromFile(fileName);
  }
  catch (NoSuchParam& )
  {
    LERROR << "no param 'automatonFile' in Tokenizer group configuration (language="
    << (int) m_d->_language << ")";
    throw InvalidConfiguration();
  }
  // when input XML file is syntactically wrong
  catch (XmlSyntaxException exc)
  {
    std::ostringstream mess;
    mess << "XmlSyntaxException at line "<<exc._lineNumber<<" cause: ";
    switch (exc._why)
    {
        case XmlSyntaxException::SYNTAX_EXC : mess << "SYNTAX_EXC"; break;
        case XmlSyntaxException::NO_DATA_EXC : mess << "NO_DATA_EXC"; break;
        case XmlSyntaxException::DOUBLE_EXC : mess << "DOUBLE_EXC"; break;
        case XmlSyntaxException::FWD_CLASS_EXC : mess << "FWD_CLASS_EXC"; break;
        case XmlSyntaxException::MULT_CLASS_EXC : mess << "MULT_CLASS_EXC"; break;
        case XmlSyntaxException::EOF_EXC : mess << "EOF_EXC"; break;
        case XmlSyntaxException::NO_CODE_EXC : mess << "NO_CODE_EXC"; break;
        case XmlSyntaxException::BAD_CODE_EXC : mess << "BAD_CODE_EXC"; break;
        case XmlSyntaxException::NO_CLASS_EXC : mess << "NO_CLASS_EXC"; break;
        case XmlSyntaxException::UNK_CLASS_EXC : mess << "UNK_CLASS_EXC"; break;
        case XmlSyntaxException::INT_ERROR_EXC : mess << "INT_ERROR_EXC"; break;
        case XmlSyntaxException::INV_CLASS_EXC : mess << "INV_CLASS_EXC"; break;
        default: mess << "??";
    }
    LERROR << mess.str();
    throw InvalidConfiguration();
  }
  catch (std::exception &exc)
  {
    // @todo remove all causes of InfiniteLoopException
    LERROR << exc.what();
    throw InvalidConfiguration();
  }

}

LimaStatusCode Tokenizer::process(
  AnalysisContent& analysis) const
{
  TimeUtilsController flatTokenizerProcessTime("FlatTokenizer");
  TOKENIZERLOGINIT;
  LINFO << "start tokenizer process";
  LimaStringText* originalText=static_cast<LimaStringText*>(analysis.getData("Text"));
  AnalysisGraph* anagraph(0);

  anagraph=new AnalysisGraph("AnalysisGraph",m_d->_language,true,true);
  analysis.setData("AnalysisGraph",anagraph);
  LinguisticGraph* graph=anagraph->getGraph();
  // Gets transformed file into characters class string
  Text* text=new Text(m_d->_language, m_d->_charChart);
  text->setText(*originalText);
  text->setGraph(anagraph->firstVertex(),graph);

  LINFO << "Running automaton on" << *originalText;
  const State* newState = m_d->_automaton.run(*text);
  while (newState)
  {
    LTRACE << "Running automaton";
    newState = m_d->_automaton.run(*text, newState);
  }
  if (text->position() < text->size()-1)
  {
    LERROR << "Tokenized up to " << text->position()
        << " for a text of size " << text->size() ;
  }
  text->finalizeAndUnsetGraph();
  remove_edge(anagraph->firstVertex(),anagraph->lastVertex(),*(anagraph->getGraph()));
  delete text;
  return SUCCESS_ID;
}

} //namespace FlatTokenizer
} // namespace LinguisticProcessing
} // namespace Lima
<|endoftext|>


<commit_before>#ifndef HASHEROBJ_PY
#define HASHEROBJ_PY

#include "hasher_obj.hpp"

// Simpler HasherObject to be wrapped with SWIG
class HasherObjectPy {

    public:

        HasherObjectPy() {
            hobj = new HasherObject();
        };

        ~HasherObjectPy() {
            delete hobj;
        };

        int read_update_files() {
            return hobj->read_update_files();
        };

        int load_hashcodes() {
            return hobj->load_hashcodes();
        };

        int load_itq_model() {
            return hobj->load_itq_model();
        };

        void set_query_feats_from_disk(std::string filename) {
            hobj->set_query_feats_from_disk(filename);
        };

        void find_knn() {
            hobj->find_knn();
        };

        void set_paths() {
            hobj->set_paths();
        };

        void set_topk(int _top_k) {
            hobj->set_topk(_top_k);
        };

        void set_ratio(float _ratio) {
            hobj->set_ratio(_ratio);
        };

        void set_bit_num(int _bit_num) {
            hobj->set_bit_num(_bit_num);
        };

        void set_norm(int _norm) {
            hobj->set_norm(_norm);
        };

        void set_feature_dim(int _feature_dim) {
            hobj->set_feature_dim(_feature_dim);
        };

        void set_base_modelpath(std::string _base_modelpath){
            hobj->set_base_modelpath(_base_modelpath);
        };

        std::string get_base_modelpath(){
            return hobj->get_base_modelpath();
        };

        void set_base_updatepath(std::string _base_updatepath) {
            hobj->set_base_updatepath(_base_updatepath);
        };

        std::string get_base_updatepath() {
            return hobj->get_base_updatepath();
        };

        void set_outputfile(std::string _outname){
            hobj->set_outputfile(_outname);
        };

    private:

        HasherObject* hobj;

};

#endif
<commit_msg>auto set paths and fill data nums<commit_after>#ifndef HASHEROBJ_PY
#define HASHEROBJ_PY

#include "hasher_obj.hpp"

// Simpler HasherObject to be wrapped with SWIG
class HasherObjectPy {

    public:

        HasherObjectPy() {
            hobj = new HasherObject();
        };

        ~HasherObjectPy() {
            delete hobj;
        };

        int read_update_files() {
            return hobj->read_update_files();
        };

        int load_hashcodes() {
            hobj->fill_data_nums_accum();
            return hobj->load_hashcodes();
        };

        int load_itq_model() {
            return hobj->load_itq_model();
        };

        void set_query_feats_from_disk(std::string filename) {
            hobj->set_query_feats_from_disk(filename);
        };

        void find_knn() {
            hobj->find_knn();
        };

        void set_paths() {
            hobj->set_paths();
        };

        void set_topk(int _top_k) {
            hobj->set_topk(_top_k);
        };

        void set_ratio(float _ratio) {
            hobj->set_ratio(_ratio);
        };

        void set_bit_num(int _bit_num) {
            hobj->set_bit_num(_bit_num);
        };

        void set_norm(int _norm) {
            hobj->set_norm(_norm);
        };

        void set_feature_dim(int _feature_dim) {
            hobj->set_feature_dim(_feature_dim);
        };

        void set_base_modelpath(std::string _base_modelpath){
            hobj->set_base_modelpath(_base_modelpath);
            hobj->set_paths();
        };

        std::string get_base_modelpath(){
            return hobj->get_base_modelpath();
        };

        void set_base_updatepath(std::string _base_updatepath) {
            hobj->set_base_updatepath(_base_updatepath);
            hobj->set_paths();
        };

        std::string get_base_updatepath() {
            return hobj->get_base_updatepath();
        };

        void set_outputfile(std::string _outname){
            hobj->set_outputfile(_outname);
        };

    private:

        HasherObject* hobj;

};

#endif
<|endoftext|>


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

#include "configuration.h"

using namespace tiramisu;

int main(int argc, char **argv)
{
    // Double tiling with Register and Shared memory
    // Fused A_reg and non-square tiling

    tiramisu::init("matmul");

    // -------------------------------------------------------
    // Layer I
    // -------------------------------------------------------

    // Declare loop iterators
    var i("i", 0, M), j("j", 0, N), k("k", 0, K);
    var i0("i0", 0, M / R_BLOCK_I), i1("i1", 0, R_BLOCK_I), j0("j0", 0, N / R_BLOCK_J), j1("j1", 0, R_BLOCK_J), k0("k0", 0, K / BLOCK), k1("k1", 0, BLOCK);
    var k0_skiplast("k0", 0, K / BLOCK - 1);
    var i00("i00"), i01("i01"), j00("j00"), j01("j01");

    // Declare cpu buffers.
    buffer b_A("b_A", {M, K}, DATA_PTYPE, a_input);
    buffer b_B("b_B", {K, N}, DATA_PTYPE, a_input);
    buffer b_C("b_C", {M, N}, DATA_PTYPE, a_output);
    buffer b_Consts("b_Consts", {2}, DATA_PTYPE, a_input);
    // Declare gpu buffers.
    buffer b_A_glb("b_A_glb", {M, K}, DATA_PTYPE, a_temporary);
    buffer b_B_glb("b_B_glb", {K, N}, DATA_PTYPE, a_temporary);
    buffer b_C_glb("b_C_glb", {M, N}, DATA_PTYPE, a_temporary);
    // "+ 1" to reduce shared memory bank conflicts
    buffer b_A_shr("b_A_shr", {2, BLOCK, BLOCK * R_BLOCK_I + 1}, DATA_PTYPE, a_temporary);
    buffer b_B_shr("b_B_shr", {2, BLOCK, BLOCK * R_BLOCK_J}, DATA_PTYPE, a_temporary);
    buffer b_A_reg("b_A_reg", {1}, DATA_PTYPE, a_temporary);
    buffer b_B_reg("b_B_reg", {R_BLOCK_J}, DATA_PTYPE, a_temporary);
    buffer b_acc("b_acc", {R_BLOCK_I, R_BLOCK_J}, DATA_PTYPE, a_temporary);
    b_A_glb.tag_gpu_global();
    b_B_glb.tag_gpu_global();
    b_C_glb.tag_gpu_global();
    b_A_shr.tag_gpu_shared();
    b_B_shr.tag_gpu_shared();
    b_A_reg.tag_gpu_register();
    b_B_reg.tag_gpu_local();
    b_acc.tag_gpu_local();

    // Declare input wrappers
    input c_A_glb({i0, j0, k0, i1}, DATA_PTYPE);
    input c_A_shr({i0, j0, k0, k1, i1}, DATA_PTYPE);
    input c_A({i, k}, DATA_PTYPE);
    input c_B_glb({i0, j0, k0, j1}, DATA_PTYPE);
    input c_B_shr({i0, j0, k0, k1, j1}, DATA_PTYPE);
    input c_B({k, j}, DATA_PTYPE);
    input c_Consts({i}, DATA_PTYPE);
    constant c_alpha("alpha", c_Consts(0));
    constant c_beta("beta", c_Consts(1));
    // Declare computations
    computation c_A_glb_to_shr_pre({i0, j0, i1}, c_A_glb(i0, j0, 0, i1));
    computation c_A_glb_to_shr({i0, j0, k0_skiplast, i1}, c_A_glb(i0, j0, k0_skiplast + 1, i1));
    computation c_A_shr_to_reg({i0, j0, k0, k1, i1}, c_A_shr(i0, j0, k0, k1, i1));
    computation c_B_glb_to_shr_pre({i0, j0, j1}, c_B_glb(i0, j0, 0, j1));
    computation c_B_glb_to_shr({i0, j0, k0_skiplast, j1}, c_B_glb(i0, j0, k0_skiplast + 1, j1));
    computation c_B_shr_to_reg({i0, j0, k0, k1, j1}, c_B_shr(i0, j0, k0, k1, j1));
    computation c_acc_init({i, j}, (float) 0);
    computation c_acc({i, j, k}, DATA_PTYPE);
    c_acc.set_expression(c_acc(i, j, 0) + c_A(i, k) * c_B(k, j));
    computation c_C({i, j}, DATA_PTYPE);
    c_C.set_expression(c_acc(i, j, 0) * c_alpha + c_C(i, j) * c_beta);
    // Declare declarations
    computation c_A_shr_dec({i0, j0}, allocate(b_A_shr));
    computation c_A_reg_dec({i0, j0}, allocate(b_A_reg));
    computation c_B_shr_dec({i0, j0}, allocate(b_B_shr));
    computation c_B_reg_dec({i0, j0}, allocate(b_B_reg));
    computation c_acc_dec({i0, j0}, allocate(b_acc));
    // Declare synchronizer computations
    computation c_sync1({i0, j0}, tiramisu::sync());
    computation c_sync2({i0, j0, k0}, tiramisu::sync());
    // Declare host-gpu transfer computations.
    computation copy_A_to_device({}, memcpy(b_A, b_A_glb));
    computation copy_B_to_device({}, memcpy(b_B, b_B_glb));
    computation copy_C_to_device({}, memcpy(b_C, b_C_glb));
    computation copy_C_to_host({}, memcpy(b_C_glb, b_C));

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

    // Scheduling commands

    c_A_shr_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_A_reg_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_acc_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_A_glb_to_shr_pre.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_A_glb_to_shr.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_A_shr_to_reg.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_B_shr_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_B_reg_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_B_glb_to_shr_pre.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_B_glb_to_shr.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_B_shr_to_reg.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_acc_init.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);
    c_acc_init.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_acc.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);
    c_acc.interchange(j1, k);
    c_acc.interchange(i1, k);
    c_acc.split(k, BLOCK, k0, k1);
    c_acc.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_C.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);
    c_C.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_sync1.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_sync2.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);

    copy_A_to_device.then(copy_B_to_device, computation::root)
                    .then(copy_C_to_device, computation::root)
                    .then(c_A_shr_dec, computation::root)
                    .then(c_B_shr_dec, j01)
                    .then(c_A_reg_dec, j01)
                    .then(c_B_reg_dec, j01)
                    .then(c_acc_dec, j01)
                    .then(c_acc_init, j01)
                    .then(c_A_glb_to_shr_pre, j01)
                    .then(c_B_glb_to_shr_pre, j01)
                    .then(c_sync1, j01)
                    .then(c_A_glb_to_shr, j01)
                    .then(c_B_glb_to_shr, k0)
                    .then(c_B_shr_to_reg, k0)
                    .then(c_A_shr_to_reg, k1)
                    .then(c_acc, i1)
                    .then(c_sync2, k0)
                    .then(c_C, j01)
                    .then(copy_C_to_host, computation::root);

    // -------------------------------------------------------
    // Layer III
    // -------------------------------------------------------

    c_A_glb.store_in(&b_A_glb, {i0 * R_BLOCK_I + i1, k0 * BLOCK + j0 % BLOCK});
    // Note the transpose:
    c_A_glb_to_shr_pre.store_in(&b_A_shr, {0, j0 % BLOCK, i0 % BLOCK * R_BLOCK_I + i1});
    c_A_glb_to_shr.store_in(&b_A_shr, {(k0_skiplast + 1) % 2, j0 % BLOCK, i0 % BLOCK * R_BLOCK_I + i1});
    c_A_shr.store_in(&b_A_shr, {k0 % 2, k1, i0 % BLOCK * R_BLOCK_I + i1});
    c_A_shr_to_reg.store_in(&b_A_reg, {0});
    // Note that we use a transposed mapping to assure memory coalescing
    // This requires R_BLOCK_J to be equal to BLOCK
    c_B_glb.store_in(&b_B_glb, {k0 * BLOCK + j1, j0 * R_BLOCK_J + i0 % BLOCK});
    c_B_glb_to_shr_pre.store_in(&b_B_shr, {0, j1, j0 % BLOCK * R_BLOCK_J + i0 % BLOCK});
    c_B_glb_to_shr.store_in(&b_B_shr, {(k0_skiplast + 1) % 2, j1, j0 % BLOCK * R_BLOCK_J + i0 % BLOCK});
    c_B_shr.store_in(&b_B_shr, {k0 % 2, k1, j0 % BLOCK * R_BLOCK_J + j1});
    c_B_shr_to_reg.store_in(&b_B_reg, {j1});
    c_A.store_in(&b_A_reg, {i % R_BLOCK_I});
    c_B.store_in(&b_B_reg, {j % R_BLOCK_J});
    c_acc_init.store_in(&b_acc, {i % R_BLOCK_I, j % R_BLOCK_J});
    c_acc.store_in(&b_acc, {i % R_BLOCK_I, j % R_BLOCK_J});
    c_C.store_in(&b_C_glb);
    c_Consts.store_in(&b_Consts, {i});

    // -------------------------------------------------------
    // Code Generation
    // -------------------------------------------------------

    // Generate object files. Last argument triggers cuda compilation.
    tiramisu::codegen({&b_Consts, &b_A, &b_B, &b_C}, "fct.o", true);

    return 0;
}
<commit_msg>GPU GEMM coalescing<commit_after>#include <tiramisu/tiramisu.h>

#include "configuration.h"

using namespace tiramisu;

int main(int argc, char **argv)
{
    // Double tiling with Register and Shared memory
    // Fused A_reg and non-square tiling

    tiramisu::init("matmul");

    // -------------------------------------------------------
    // Layer I
    // -------------------------------------------------------

    // Declare loop iterators
    var i("i", 0, M), j("j", 0, N), k("k", 0, K);
    var i0("i0", 0, M / R_BLOCK_I), i1("i1", 0, R_BLOCK_I), j0("j0", 0, N / R_BLOCK_J), j1("j1", 0, R_BLOCK_J), k0("k0", 0, K / BLOCK), k1("k1", 0, BLOCK);
    var k0_skiplast("k0", 0, K / BLOCK - 1);
    var i00("i00"), i01("i01"), j00("j00"), j01("j01");

    // Declare cpu buffers.
    buffer b_A("b_A", {M, K}, DATA_PTYPE, a_input);
    buffer b_B("b_B", {K, N}, DATA_PTYPE, a_input);
    buffer b_C("b_C", {M, N}, DATA_PTYPE, a_output);
    buffer b_Consts("b_Consts", {2}, DATA_PTYPE, a_input);
    // Declare gpu buffers.
    buffer b_A_glb("b_A_glb", {M, K}, DATA_PTYPE, a_temporary);
    buffer b_B_glb("b_B_glb", {K, N}, DATA_PTYPE, a_temporary);
    buffer b_C_glb("b_C_glb", {M, N}, DATA_PTYPE, a_temporary);
    // "+ 1" to reduce shared memory bank conflicts
    buffer b_A_shr("b_A_shr", {2, BLOCK, BLOCK * R_BLOCK_I + 1}, DATA_PTYPE, a_temporary);
    buffer b_B_shr("b_B_shr", {2, BLOCK, BLOCK * R_BLOCK_J}, DATA_PTYPE, a_temporary);
    buffer b_A_reg("b_A_reg", {1}, DATA_PTYPE, a_temporary);
    buffer b_B_reg("b_B_reg", {R_BLOCK_J}, DATA_PTYPE, a_temporary);
    buffer b_acc("b_acc", {R_BLOCK_I, R_BLOCK_J}, DATA_PTYPE, a_temporary);
    b_A_glb.tag_gpu_global();
    b_B_glb.tag_gpu_global();
    b_C_glb.tag_gpu_global();
    b_A_shr.tag_gpu_shared();
    b_B_shr.tag_gpu_shared();
    b_A_reg.tag_gpu_register();
    b_B_reg.tag_gpu_local();
    b_acc.tag_gpu_local();

    // Declare input wrappers
    input c_A_glb({i0, j0, k0, i1}, DATA_PTYPE);
    input c_A_shr({i0, j0, k0, k1, i1}, DATA_PTYPE);
    input c_A({i, k}, DATA_PTYPE);
    input c_B_glb({i0, j0, k0, j1}, DATA_PTYPE);
    input c_B_shr({i0, j0, k0, k1, j1}, DATA_PTYPE);
    input c_B({k, j}, DATA_PTYPE);
    input c_Consts({i}, DATA_PTYPE);
    constant c_alpha("alpha", c_Consts(0));
    constant c_beta("beta", c_Consts(1));
    // Declare computations
    computation c_A_glb_to_shr_pre({i0, j0, i1}, c_A_glb(i0, j0, 0, i1));
    computation c_A_glb_to_shr({i0, j0, k0_skiplast, i1}, c_A_glb(i0, j0, k0_skiplast + 1, i1));
    computation c_A_shr_to_reg({i0, j0, k0, k1, i1}, c_A_shr(i0, j0, k0, k1, i1));
    computation c_B_glb_to_shr_pre({i0, j0, j1}, c_B_glb(i0, j0, 0, j1));
    computation c_B_glb_to_shr({i0, j0, k0_skiplast, j1}, c_B_glb(i0, j0, k0_skiplast + 1, j1));
    computation c_B_shr_to_reg({i0, j0, k0, k1, j1}, c_B_shr(i0, j0, k0, k1, j1));
    computation c_acc_init({i, j}, (float) 0);
    computation c_acc({i, j, k}, DATA_PTYPE);
    c_acc.set_expression(c_acc(i, j, 0) + c_A(i, k) * c_B(k, j));
    computation c_C({i, j}, DATA_PTYPE);
    c_C.set_expression(c_acc(i, j, 0) * c_alpha + c_C(i, j) * c_beta);
    // Declare declarations
    computation c_A_shr_dec({i0, j0}, allocate(b_A_shr));
    computation c_A_reg_dec({i0, j0}, allocate(b_A_reg));
    computation c_B_shr_dec({i0, j0}, allocate(b_B_shr));
    computation c_B_reg_dec({i0, j0}, allocate(b_B_reg));
    computation c_acc_dec({i0, j0}, allocate(b_acc));
    // Declare synchronizer computations
    computation c_sync1({i0, j0}, tiramisu::sync());
    computation c_sync2({i0, j0, k0}, tiramisu::sync());
    // Declare host-gpu transfer computations.
    computation copy_A_to_device({}, memcpy(b_A, b_A_glb));
    computation copy_B_to_device({}, memcpy(b_B, b_B_glb));
    computation copy_C_to_device({}, memcpy(b_C, b_C_glb));
    computation copy_C_to_host({}, memcpy(b_C_glb, b_C));

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

    // Scheduling commands

    c_A_shr_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_A_reg_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_acc_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_A_glb_to_shr_pre.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_A_glb_to_shr.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_A_shr_to_reg.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_B_shr_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_B_reg_dec.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_B_glb_to_shr_pre.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_B_glb_to_shr.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_B_shr_to_reg.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_acc_init.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);
    c_acc_init.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_acc.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);
    c_acc.interchange(j1, k);
    c_acc.interchange(i1, k);
    c_acc.split(k, BLOCK, k0, k1);
    c_acc.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_C.tile(i, j, R_BLOCK_I, R_BLOCK_J, i0, j0, i1, j1);
    c_C.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_sync1.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);
    c_sync2.gpu_tile(i0, j0, BLOCK, BLOCK, i00, j00, i01, j01);

    copy_A_to_device.then(copy_B_to_device, computation::root)
                    .then(copy_C_to_device, computation::root)
                    .then(c_A_shr_dec, computation::root)
                    .then(c_B_shr_dec, j01)
                    .then(c_A_reg_dec, j01)
                    .then(c_B_reg_dec, j01)
                    .then(c_acc_dec, j01)
                    .then(c_acc_init, j01)
                    .then(c_A_glb_to_shr_pre, j01)
                    .then(c_B_glb_to_shr_pre, j01)
                    .then(c_sync1, j01)
                    .then(c_A_glb_to_shr, j01)
                    .then(c_B_glb_to_shr, k0)
                    .then(c_B_shr_to_reg, k0)
                    .then(c_A_shr_to_reg, k1)
                    .then(c_acc, i1)
                    .then(c_sync2, k0)
                    .then(c_C, j01)
                    .then(copy_C_to_host, computation::root);

    // -------------------------------------------------------
    // Layer III
    // -------------------------------------------------------

    c_A_glb.store_in(&b_A_glb, {(i0 - i0 % BLOCK + j0 % BLOCK) * R_BLOCK_I + i1, k0 * BLOCK + i0 % BLOCK});
    // Note the transpose:
    c_A_glb_to_shr_pre.store_in(&b_A_shr, {0, i0 % BLOCK, j0 % BLOCK * R_BLOCK_I + i1});
    c_A_glb_to_shr.store_in(&b_A_shr, {(k0_skiplast + 1) % 2, i0 % BLOCK, j0 % BLOCK * R_BLOCK_I + i1});
    c_A_shr.store_in(&b_A_shr, {k0 % 2, k1, i0 % BLOCK * R_BLOCK_I + i1});
    c_A_shr_to_reg.store_in(&b_A_reg, {0});
    // Note that we use a transposed mapping to assure memory coalescing
    // This requires R_BLOCK_J to be equal to BLOCK
    c_B_glb.store_in(&b_B_glb, {k0 * BLOCK + j1, j0 * R_BLOCK_J + i0 % BLOCK});
    c_B_glb_to_shr_pre.store_in(&b_B_shr, {0, j1, j0 % BLOCK * R_BLOCK_J + i0 % BLOCK});
    c_B_glb_to_shr.store_in(&b_B_shr, {(k0_skiplast + 1) % 2, j1, j0 % BLOCK * R_BLOCK_J + i0 % BLOCK});
    c_B_shr.store_in(&b_B_shr, {k0 % 2, k1, j0 % BLOCK * R_BLOCK_J + j1});
    c_B_shr_to_reg.store_in(&b_B_reg, {j1});
    c_A.store_in(&b_A_reg, {i % R_BLOCK_I});
    c_B.store_in(&b_B_reg, {j % R_BLOCK_J});
    c_acc_init.store_in(&b_acc, {i % R_BLOCK_I, j % R_BLOCK_J});
    c_acc.store_in(&b_acc, {i % R_BLOCK_I, j % R_BLOCK_J});
    c_C.store_in(&b_C_glb);
    c_Consts.store_in(&b_Consts, {i});

    // -------------------------------------------------------
    // Code Generation
    // -------------------------------------------------------

    // Generate object files. Last argument triggers cuda compilation.
    tiramisu::codegen({&b_Consts, &b_A, &b_B, &b_C}, "fct.o", true);

    return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <ctype.h>
#include <list>
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <RhIO.hpp>
#include "Stream.h"
#include "Shell.h"
#include "utils.h"

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

namespace RhIO
{
    Shell::Shell(std::string server_)
        : server(server_), client(NULL), clientSub(NULL), stream(NULL)
    {
    }

    void Shell::terminal_set_ioconfig() {
        struct termios custom;
        int fd=fileno(stdin);
        tcgetattr(fd, &termsave);
        custom=termsave;
        custom.c_lflag &= ~(ICANON|ECHO);
        tcsetattr(fd,TCSANOW,&custom);
        // fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)|O_NONBLOCK);
        fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)); //blocking
    }

    void Shell::displayPrompt()
    {
        Terminal::setColor("yellow", true);
        std::cout << "RhIO";
        Terminal::clear();
        std::cout << ":";
        Terminal::setColor("blue", true);
        std::cout << getPath();
        Terminal::clear();
        std::cout << "# " << std::flush;
    }

    void Shell::run()
    {

        terminal_set_ioconfig();

        std::string reqServer = "tcp://"+server+":"+ServerRepPort;
        std::string subServer = "tcp://"+server+":"+ServerPubPort;
        terminate = false;
        Terminal::setColor("white", true);
        std::cout << "Rhoban I/O shell, welcome!" << std::endl;
        std::cout << "Connecting to " << server << std::endl;
        client = new ClientReq(reqServer);
        clientSub = new ClientSub(subServer);
        stream = new Stream(this);
        std::cout << "Downloading the tree..." << std::endl;
        tree = new Node(client, "");
        Terminal::clear();

        // Reading lines from stdin
        while (!terminate ) {
            displayPrompt();
            std::string line;
            // std::getline(std::cin, line);
            line=getLine();
            parse(line);
        }

        tcsetattr(fileno(stdin),TCSANOW,&termsave);
        std::cout << std::endl << std::flush;

    }

    std::string Shell::getLine()
    {

        char c;
        std::string line("");
        bool done=false;
        bool esc_mode=false;
        std::deque<std::string>::iterator hist_it=shell_history.end();
        int cursorpos=0;
        std::string lastcmd("");

        while(!done)
        {
            if ((c = getchar())>0)
            {
                switch(c)
                {
                    case 0x0a: //enter

                        putchar(c);
                        done=true;

                        lastcmd="";
                        if(shell_history.size()>0)
                            lastcmd=shell_history.back();

                        if(line.compare("")!=0 && line.compare(lastcmd)!=0) //store in history if non null and different than the last cmd
                        {
                            shell_history.push_back(line);
                            if(shell_history.size()>MAX_HISTORY)
                                shell_history.pop_front();
                            hist_it=shell_history.begin();
                        }
                        return line;
                        break;//useless

                    case 0x01: //Ctrl-a goto begin of line
                        Terminal::clearLine();
                        displayPrompt();
                        std::cout<<line;
                        cursorpos=0;
                        if(line.size()>0)
                            Terminal::cursorNLeft(line.size());

                        break;

                    case 0x05: //Ctrl-e goto end of line
                        Terminal::clearLine();
                        displayPrompt();
                        std::cout<<line;

                        if(cursorpos<line.size() )
                        {
                            // Terminal::cursorNLeft(cursorpos);
                            // Terminal::cursorNRight(line.size());
                            cursorpos=line.size();
                        }

                        break;

                    case 0xc: //Ctrl-l clear screen
                        Terminal::clearScreen();
                        Terminal::clearLine();
                        Terminal::initCursor();
                        displayPrompt();
                        line="";
                        cursorpos=0;
                        break;

                    case 0x1b: //begin break mode (arrows)
                        esc_mode=true;

                        break;

                    case 0x5b: //just after 0x1b

                        break;

                    case 0x41: //up
                        if(esc_mode)
                        {

                            if(shell_history.size()>0 && hist_it!= shell_history.begin())
                            {
                                line=*--hist_it;
                                cursorpos=line.size();
                                Terminal::clearLine();
                                displayPrompt();
                                std::cout<<line;
                            }
                            esc_mode=false;
                        }
                        break;

                    case 0x42: //down
                        if(esc_mode)
                        {
                            if(shell_history.size()>0 && hist_it!= shell_history.end())
                            {
                                line=*hist_it++;
                                cursorpos=line.size();
                                Terminal::clearLine();
                                displayPrompt();
                                std::cout<<line;
                            }
                            else if( hist_it== shell_history.end())
                            {
                                Terminal::clearLine();
                                displayPrompt();
                                line="";
                                cursorpos=0;
                            }

                            esc_mode=false;
                        }
                        break;

                    case 0x43: //right
                        if(esc_mode)
                        {

                            if(cursorpos<line.size())
                            {
                                Terminal::cursorRight();
                                cursorpos++;
                            }
                            esc_mode=false;
                        }
                        break;

                    case 0x44: //left
                        if(esc_mode)
                        {

                            if(cursorpos>0)
                            {
                                Terminal::cursorLeft();
                                cursorpos--;
                            }
                            esc_mode=false;
                        }
                        break;

                    case 0x7f: //backspace
                        if(line.size()>0)
                        {
                            line.pop_back();
                            Terminal::clearLine();
                            displayPrompt();
                            cursorpos--;
                            std::cout<<line;
                        }
                        break;

                    default:

                        if(line.size()>0)
                        {
                            std::string tmp("");
                            tmp+=c;
                            line.insert(cursorpos,tmp);
                        }
                        else{
                            line+=c;
                        }
                        cursorpos++;
                        Terminal::clearLine();
                        displayPrompt();

                        std::cout<<line;

                        if(line.size()-cursorpos>0)
                            Terminal::cursorNLeft(line.size()-cursorpos);

                        break;
                }
            }
        }
        line="";
        return line;
    }

    void Shell::parse(std::string line)
    {
        // Try to interpret command as a set
        for (int i=0; i<line.size(); i++) {
            if (line[i] == '=') {
                std::string lvalue = line.substr(0, i);
                std::string rvalue = line.substr(i+1);
                trim(lvalue);
                trim(rvalue);
                set(lvalue, rvalue);
                return;
            }
        }

        // Try to split line into parts and execute it
        std::list<std::string> parts;
        std::string part;

        for (int i=0; i<line.size(); i++) {
            if (std::isspace(line[i])) {
                if (part != "") {
                    parts.push_back(part);
                    part = "";
                }
            } else {
                part += line[i];
            }
        }
        if (part != "") {
            parts.push_back(part);
        }

        if (parts.size()) {
            auto command = parts.front();
            parts.pop_front();
            process(command, parts);
        }
    }

    void Shell::process(std::string command, std::list<std::string> args)
    {
        // First, try to quit/exit
        if (command == "quit" || command == "exit") {
            terminate = true;
        } else {
            // Checking for the command in the list
            if (commands.count(command)) {
                std::vector<std::string> argsV;
                for (auto part : args) {
                    argsV.push_back(part);
                }
                commands[command]->process(argsV);
            } else {
                auto nodeValue = getNodeValue(command);
                auto value = nodeValue.value;

                if (value) {
                    Node::get(this, nodeValue);
                    std::cout << command << "=" << Node::toString(value) << std::endl;
                } else {
                    Terminal::setColor("red", true);
                    std::cout << "Unknown command: " << command << std::endl;
                    Terminal::clear();
                }
            }
        }
    }

    void Shell::set(std::string lvalue, std::string rvalue)
    {
        auto node = getCurrentNode();
        auto nodeValue = getNodeValue(lvalue);
        auto value = nodeValue.value;

        if (value) {
            Node::setFromString(this, nodeValue, rvalue);
        } else {
            Terminal::setColor("red", true);
            std::cout << "Unknown parameter: " << lvalue << std::endl;
            Terminal::clear();
        }
    }

    void Shell::registerCommand(Command *command)
    {
        command->setShell(this);
        commands[command->getName()] = command;
    }

    std::map<std::string, Command*> Shell::getCommands()
    {
        return commands;
    }

    ClientReq *Shell::getClient()
    {
        return client;
    }

    ClientSub *Shell::getClientSub()
    {
        return clientSub;
    }

    void Shell::enterPath(std::string path_)
    {
        path.push_back(path_);
    }

    void Shell::upPath()
    {
        if (path.size()) {
            path.pop_back();
        }
    }

    bool Shell::goToPath(std::string spath)
    {
        if (auto node = getNode(spath)) {
            auto parts = pathToParts(node->getPath());

            path.clear();
            for (auto part : parts) {
                path.push_back(part);
            }
            return true;
        } else {
            return false;
        }
    }

    std::string Shell::getPath()
    {
        std::string p = "";

        for (auto part : path) {
            if (p != "") {
                p += "/";
            }
            p += part;
        }

        return p;
    }

    std::vector<std::string> Shell::pathToParts(std::string spath)
    {
        auto parts = split(spath, '/');
        std::vector<std::string> path;

        for (auto part : parts) {
            if (part != "") {
                path.push_back(part);
            }
        }

        return path;
    }

    Node *Shell::getNode(std::string spath)
    {
        if (spath.size()==0 || spath[0]!='/') {
            auto myPath = getPath();
            if (myPath != "") {
                myPath += "/";
            }
            spath = myPath + spath;
        }

        auto path = pathToParts(spath);

        Node *node = tree;
        for (auto part : path) {
            node = node->getChild(part);
            if (node == NULL) {
                return NULL;
            }
        }
        return node;
    }

    NodeValue Shell::getNodeValue(std::string path)
    {
        auto parts = pathToParts(path);

        if (parts.size() == 0) {
            return NodeValue(NULL, NULL);
        }

        // Child name
        auto name = parts[parts.size()-1];
        parts.pop_back();

        // Creating value path
        std::string prefix = "";
        for (auto part : parts) {
            if (prefix != "") prefix += "/";
            prefix += part;
        }
        if (path[0] == '/') {
            prefix = "/" + prefix;
        }

        // Getting node
        auto node = getNode(prefix);
        if (node == NULL) {
            return NodeValue(NULL, NULL);
        }

        return node->getNodeValue(name);
    }

    Stream *Shell::getStream()
    {
        return stream;
    }

    ValueBase *Shell::getValue(std::string path)
    {
        return getNodeValue(path).value;
    }

    Node *Shell::getCurrentNode()
    {
        return getNode();
    }
}
<commit_msg>fix maj<commit_after>#include <stdio.h>
#include <ctype.h>
#include <list>
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <RhIO.hpp>
#include "Stream.h"
#include "Shell.h"
#include "utils.h"

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

namespace RhIO
{
    Shell::Shell(std::string server_)
        : server(server_), client(NULL), clientSub(NULL), stream(NULL)
    {
    }

    void Shell::terminal_set_ioconfig() {
        struct termios custom;
        int fd=fileno(stdin);
        tcgetattr(fd, &termsave);
        custom=termsave;
        custom.c_lflag &= ~(ICANON|ECHO);
        tcsetattr(fd,TCSANOW,&custom);
        // fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)|O_NONBLOCK);
        fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0)); //blocking
    }

    void Shell::displayPrompt()
    {
        Terminal::setColor("yellow", true);
        std::cout << "RhIO";
        Terminal::clear();
        std::cout << ":";
        Terminal::setColor("blue", true);
        std::cout << getPath();
        Terminal::clear();
        std::cout << "# " << std::flush;
    }

    void Shell::run()
    {

        terminal_set_ioconfig();

        std::string reqServer = "tcp://"+server+":"+ServerRepPort;
        std::string subServer = "tcp://"+server+":"+ServerPubPort;
        terminate = false;
        Terminal::setColor("white", true);
        std::cout << "Rhoban I/O shell, welcome!" << std::endl;
        std::cout << "Connecting to " << server << std::endl;
        client = new ClientReq(reqServer);
        clientSub = new ClientSub(subServer);
        stream = new Stream(this);
        std::cout << "Downloading the tree..." << std::endl;
        tree = new Node(client, "");
        Terminal::clear();

        // Reading lines from stdin
        while (!terminate ) {
            displayPrompt();
            std::string line;
            // std::getline(std::cin, line);
            line=getLine();
            parse(line);
        }

        tcsetattr(fileno(stdin),TCSANOW,&termsave);
        std::cout << std::endl << std::flush;

    }

    std::string Shell::getLine()
    {

        char c;
        std::string line("");
        bool done=false;
        bool esc_mode=false;
        std::deque<std::string>::iterator hist_it=shell_history.end();
        int cursorpos=0;
        std::string lastcmd("");

        while(!done)
        {
            if ((c = getchar())>0)
            {
                switch(c)
                {
                    case 0x0a: //enter

                        putchar(c);
                        done=true;

                        lastcmd="";
                        if(shell_history.size()>0)
                            lastcmd=shell_history.back();

                        if(line.compare("")!=0 && line.compare(lastcmd)!=0) //store in history if non null and different than the last cmd
                        {
                            shell_history.push_back(line);
                            if(shell_history.size()>MAX_HISTORY)
                                shell_history.pop_front();
                            hist_it=shell_history.begin();
                        }
                        return line;
                        break;//useless

                    case 0x01: //Ctrl-a goto begin of line
                        Terminal::clearLine();
                        displayPrompt();
                        std::cout<<line;
                        cursorpos=0;
                        if(line.size()>0)
                            Terminal::cursorNLeft(line.size());

                        break;

                    case 0x05: //Ctrl-e goto end of line
                        Terminal::clearLine();
                        displayPrompt();
                        std::cout<<line;

                        if(cursorpos<line.size() )
                        {
                            // Terminal::cursorNLeft(cursorpos);
                            // Terminal::cursorNRight(line.size());
                            cursorpos=line.size();
                        }

                        break;

                    case 0xc: //Ctrl-l clear screen
                        Terminal::clearScreen();
                        Terminal::clearLine();
                        Terminal::initCursor();
                        displayPrompt();
                        line="";
                        cursorpos=0;
                        break;

                    case 0x1b: //begin break mode (arrows)
                        esc_mode=true;

                        break;

                    case 0x5b: //just after 0x1b

                        break;

                    case 0x7f: //backspace
                        if(line.size()>0)
                        {
                            line.pop_back();
                            Terminal::clearLine();
                            displayPrompt();
                            cursorpos--;
                            std::cout<<line;
                        }
                        break;

                    case 0x09: //TAB
                        break;

                            // if not esc_mode -> fall to default
                    case 0x41: //up
                        if(esc_mode && c==0x41)
                        {

                            if(shell_history.size()>0 && hist_it!= shell_history.begin())
                            {
                                line=*--hist_it;
                                cursorpos=line.size();
                                Terminal::clearLine();
                                displayPrompt();
                                std::cout<<line;
                            }
                            esc_mode=false;
                            break;
                        }

                    case 0x42: //down
                        if(esc_mode && c==0x42)
                        {
                            if(shell_history.size()>0 && hist_it!= shell_history.end())
                            {
                                line=*hist_it++;
                                cursorpos=line.size();
                                Terminal::clearLine();
                                displayPrompt();
                                std::cout<<line;
                            }
                            else if( hist_it== shell_history.end())
                            {
                                Terminal::clearLine();
                                displayPrompt();
                                line="";
                                cursorpos=0;
                            }

                            esc_mode=false;
                            break;
                        }
                        // break;

                    case 0x43: //right
                        if(esc_mode && c==0x43)
                        {

                            if(cursorpos<line.size())
                            {
                                Terminal::cursorRight();
                                cursorpos++;
                            }
                            esc_mode=false;
                            break;
                        }
                        // break;

                    case 0x44: //left
                        if(esc_mode && c==0x44)
                        {

                            if(cursorpos>0)
                            {
                                Terminal::cursorLeft();
                                cursorpos--;
                            }
                            esc_mode=false;
                            break;
                        }
                        // break;

                    default:

                        if(line.size()>0)
                        {
                            std::string tmp("");
                            tmp+=c;
                            line.insert(cursorpos,tmp);
                        }
                        else{
                            line+=c;
                        }
                        cursorpos++;
                        Terminal::clearLine();
                        displayPrompt();

                        std::cout<<line;

                        if(line.size()-cursorpos>0)
                            Terminal::cursorNLeft(line.size()-cursorpos);

                        break;
                }
            }
        }
        line="";
        return line;
    }

    void Shell::parse(std::string line)
    {
        // Try to interpret command as a set
        for (int i=0; i<line.size(); i++) {
            if (line[i] == '=') {
                std::string lvalue = line.substr(0, i);
                std::string rvalue = line.substr(i+1);
                trim(lvalue);
                trim(rvalue);
                set(lvalue, rvalue);
                return;
            }
        }

        // Try to split line into parts and execute it
        std::list<std::string> parts;
        std::string part;

        for (int i=0; i<line.size(); i++) {
            if (std::isspace(line[i])) {
                if (part != "") {
                    parts.push_back(part);
                    part = "";
                }
            } else {
                part += line[i];
            }
        }
        if (part != "") {
            parts.push_back(part);
        }

        if (parts.size()) {
            auto command = parts.front();
            parts.pop_front();
            process(command, parts);
        }
    }

    void Shell::process(std::string command, std::list<std::string> args)
    {
        // First, try to quit/exit
        if (command == "quit" || command == "exit") {
            terminate = true;
        } else {
            // Checking for the command in the list
            if (commands.count(command)) {
                std::vector<std::string> argsV;
                for (auto part : args) {
                    argsV.push_back(part);
                }
                commands[command]->process(argsV);
            } else {
                auto nodeValue = getNodeValue(command);
                auto value = nodeValue.value;

                if (value) {
                    Node::get(this, nodeValue);
                    std::cout << command << "=" << Node::toString(value) << std::endl;
                } else {
                    Terminal::setColor("red", true);
                    std::cout << "Unknown command: " << command << std::endl;
                    Terminal::clear();
                }
            }
        }
    }

    void Shell::set(std::string lvalue, std::string rvalue)
    {
        auto node = getCurrentNode();
        auto nodeValue = getNodeValue(lvalue);
        auto value = nodeValue.value;

        if (value) {
            Node::setFromString(this, nodeValue, rvalue);
        } else {
            Terminal::setColor("red", true);
            std::cout << "Unknown parameter: " << lvalue << std::endl;
            Terminal::clear();
        }
    }

    void Shell::registerCommand(Command *command)
    {
        command->setShell(this);
        commands[command->getName()] = command;
    }

    std::map<std::string, Command*> Shell::getCommands()
    {
        return commands;
    }

    ClientReq *Shell::getClient()
    {
        return client;
    }

    ClientSub *Shell::getClientSub()
    {
        return clientSub;
    }

    void Shell::enterPath(std::string path_)
    {
        path.push_back(path_);
    }

    void Shell::upPath()
    {
        if (path.size()) {
            path.pop_back();
        }
    }

    bool Shell::goToPath(std::string spath)
    {
        if (auto node = getNode(spath)) {
            auto parts = pathToParts(node->getPath());

            path.clear();
            for (auto part : parts) {
                path.push_back(part);
            }
            return true;
        } else {
            return false;
        }
    }

    std::string Shell::getPath()
    {
        std::string p = "";

        for (auto part : path) {
            if (p != "") {
                p += "/";
            }
            p += part;
        }

        return p;
    }

    std::vector<std::string> Shell::pathToParts(std::string spath)
    {
        auto parts = split(spath, '/');
        std::vector<std::string> path;

        for (auto part : parts) {
            if (part != "") {
                path.push_back(part);
            }
        }

        return path;
    }

    Node *Shell::getNode(std::string spath)
    {
        if (spath.size()==0 || spath[0]!='/') {
            auto myPath = getPath();
            if (myPath != "") {
                myPath += "/";
            }
            spath = myPath + spath;
        }

        auto path = pathToParts(spath);

        Node *node = tree;
        for (auto part : path) {
            node = node->getChild(part);
            if (node == NULL) {
                return NULL;
            }
        }
        return node;
    }

    NodeValue Shell::getNodeValue(std::string path)
    {
        auto parts = pathToParts(path);

        if (parts.size() == 0) {
            return NodeValue(NULL, NULL);
        }

        // Child name
        auto name = parts[parts.size()-1];
        parts.pop_back();

        // Creating value path
        std::string prefix = "";
        for (auto part : parts) {
            if (prefix != "") prefix += "/";
            prefix += part;
        }
        if (path[0] == '/') {
            prefix = "/" + prefix;
        }

        // Getting node
        auto node = getNode(prefix);
        if (node == NULL) {
            return NodeValue(NULL, NULL);
        }

        return node->getNodeValue(name);
    }

    Stream *Shell::getStream()
    {
        return stream;
    }

    ValueBase *Shell::getValue(std::string path)
    {
        return getNodeValue(path).value;
    }

    Node *Shell::getCurrentNode()
    {
        return getNode();
    }
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

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

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

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

#include "radialdam_user.h"
#include <fclaw2d_clawpatch.h>
#include <fc2d_clawpack46.h>

static void *
options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt)
{
    user_options_t* user = (user_options_t*) package;

    /* [user] User options */
    sc_options_add_int (opt, 0, "example", &user->example, 0, "[user] 0 - nomap; 1 - disk [0]");

    sc_options_add_double (opt, 0, "g",     &user->g,     1.0, "[user] g [1.0]");
    sc_options_add_double (opt, 0, "x0",    &user->x0,    0.0, "[user] x0 [0.0]");
    sc_options_add_double (opt, 0, "y0",    &user->y0,    0.0, "[user] y0 [0.0]");
    sc_options_add_double (opt, 0, "r0",    &user->r0,    0.5, "[user] r0 [0.5]");
    sc_options_add_double (opt, 0, "hin",   &user->hin,   2.0, "[user] hin [2.0]");
    sc_options_add_double (opt, 0, "hout",  &user->hout,  1.0, "[user] hout [1.0]");

    sc_options_add_double (opt, 0, "alpha", &user->alpha, 0.4, "[user] alpha (for 5-patch map) [0.4]");

    sc_options_add_int (opt, 0, "claw-version", &user->claw_version, 5,
                           "Clawpack_version (4 or 5) [5]");

    user->is_registered = 1;
    return NULL;
}

static fclaw_exit_type_t
options_check_user (fclaw_app_t * app, void *package, void *registered)
{
    user_options_t* user = (user_options_t*) package;

    if (user->example < 0 || user->example > 1) {
        fclaw_global_essentialf ("Option --user:example must be 0 or 1\n");
        return FCLAW_EXIT_QUIET;
    }
    if (user->example == 1 && user->claw_version == 4)
    {
        fclaw_global_essentialf("Example 1 (disk) can only be run with claw-version=5\n");
        return FCLAW_EXIT_QUIET;
    }
    return FCLAW_NOEXIT;
}

static const fclaw_app_options_vtable_t options_vtable_user =
{
    options_register_user,
    NULL,
    options_check_user,
    NULL
};

static
void register_user_options (fclaw_app_t * app,
                            const char *configfile,
                            user_options_t* user)
{
    FCLAW_ASSERT (app != NULL);

    fclaw_app_options_register (app,"user", configfile, &options_vtable_user,
                                user);
}

user_options_t* radialdam_user_get_options(fclaw2d_domain_t* domain)
{
    fclaw_app_t* app;
    app = fclaw2d_domain_get_app(domain);

    const user_options_t* user = (user_options_t*) fclaw_app_get_user(app);

    return (user_options_t*) user;
}

static
void run_program(fclaw_app_t* app)
{
    sc_MPI_Comm            mpicomm;

    /* Mapped, multi-block domain */
    p4est_connectivity_t     *conn = NULL;
    fclaw2d_domain_t	     *domain;
    fclaw2d_map_context_t    *cont = NULL;

    amr_options_t              *gparms;
    user_options_t           *user;

    mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);

    gparms = fclaw_forestclaw_get_options(app);
    user = (user_options_t*) fclaw_app_get_user(app);

    double rotate[2];

    rotate[0] = 0;
    rotate[1] = 0;

    switch (user->example)
    {
    case 0:
        /* Use [ax,bx]x[ay,by] */
        conn = p4est_connectivity_new_unitsquare();
        cont = fclaw2d_map_new_nomap();
        break;
    case 1:
        conn = p4est_connectivity_new_disk();
        cont = fclaw2d_map_new_pillowdisk5 (gparms->scale,gparms->shift,
                                            rotate,user->alpha);
        break;
    default:
        SC_ABORT_NOT_REACHED ();
    }

    domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);

    /* ---------------------------------------------------------- */
    fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_INFO);
    fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);

    fclaw2d_domain_data_new(domain);
    fclaw2d_domain_set_app(domain,app);

    radialdam_link_solvers(domain);

    fclaw2d_initialize(&domain);
    fclaw2d_run(&domain);
    fclaw2d_finalize(&domain);

    fclaw2d_map_destroy(cont);
}

int
main (int argc, char **argv)
{
    fclaw_app_t *app;
    int first_arg;
    fclaw_exit_type_t vexit;

    /* Options */
    sc_options_t                  *options;
    user_options_t suser, *user = &suser;

    int retval;

    /* Initialize application */
    app = fclaw_app_new (&argc, &argv, user);

    /* Register packages */
    fclaw_forestclaw_register(app,"fclaw_options.ini");
    fc2d_clawpack46_register(app,"fclaw_options.ini");
    fc2d_clawpack5_register(app,"fclaw_options.ini");

    register_user_options(app,"fclaw_options.ini",user);

    /* Read configuration file(s) */
    options = fclaw_app_get_options (app);
    retval  = fclaw_options_read_from_file(options);
    vexit   =  fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");

    fclaw2d_clawpatch_link_app(app);

    if (!retval & !vexit)
    {
        run_program(app);
    }

    fclaw_forestclaw_destroy(app);
    fclaw_app_destroy (app);

    return 0;
}
<commit_msg>(amrclaw/2d/shallow/radialdam) Minor updates<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

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

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

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

#include "radialdam_user.h"

static void *
options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt)
{
    user_options_t* user = (user_options_t*) package;

    /* [user] User options */
    sc_options_add_int (opt, 0, "example", &user->example, 0, "[user] 0 - nomap; 1 - disk [0]");

    sc_options_add_double (opt, 0, "g",     &user->g,     1.0, "[user] g [1.0]");
    sc_options_add_double (opt, 0, "x0",    &user->x0,    0.0, "[user] x0 [0.0]");
    sc_options_add_double (opt, 0, "y0",    &user->y0,    0.0, "[user] y0 [0.0]");
    sc_options_add_double (opt, 0, "r0",    &user->r0,    0.5, "[user] r0 [0.5]");
    sc_options_add_double (opt, 0, "hin",   &user->hin,   2.0, "[user] hin [2.0]");
    sc_options_add_double (opt, 0, "hout",  &user->hout,  1.0, "[user] hout [1.0]");

    sc_options_add_double (opt, 0, "alpha", &user->alpha, 0.4, "[user] alpha (for 5-patch map) [0.4]");

    sc_options_add_int (opt, 0, "claw-version", &user->claw_version, 5,
                           "Clawpack_version (4 or 5) [5]");

    user->is_registered = 1;
    return NULL;
}

static fclaw_exit_type_t
options_check_user (fclaw_app_t * app, void *package, void *registered)
{
    user_options_t* user = (user_options_t*) package;

    if (user->example < 0 || user->example > 1) {
        fclaw_global_essentialf ("Option --user:example must be 0 or 1\n");
        return FCLAW_EXIT_QUIET;
    }
    if (user->example == 1 && user->claw_version == 4)
    {
        fclaw_global_essentialf("Example 1 (disk) can only be run with claw-version=5\n");
        return FCLAW_EXIT_QUIET;
    }
    return FCLAW_NOEXIT;
}

static const fclaw_app_options_vtable_t options_vtable_user =
{
    options_register_user,
    NULL,
    options_check_user,
    NULL
};

static
void register_user_options (fclaw_app_t * app,
                            const char *configfile,
                            user_options_t* user)
{
    FCLAW_ASSERT (app != NULL);

    fclaw_app_options_register (app,"user", configfile, &options_vtable_user,
                                user);
}

user_options_t* radialdam_user_get_options(fclaw2d_domain_t* domain)
{
    fclaw_app_t* app;
    app = fclaw2d_domain_get_app(domain);

    const user_options_t* user = (user_options_t*) fclaw_app_get_user(app);

    return (user_options_t*) user;
}

static
void run_program(fclaw_app_t* app)
{
    sc_MPI_Comm            mpicomm;

    /* Mapped, multi-block domain */
    p4est_connectivity_t     *conn = NULL;
    fclaw2d_domain_t	     *domain;
    fclaw2d_map_context_t    *cont = NULL;

    amr_options_t              *gparms;
    user_options_t           *user;

    mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);

    gparms = fclaw_forestclaw_get_options(app);
    user = (user_options_t*) fclaw_app_get_user(app);

    double rotate[2];

    rotate[0] = 0;
    rotate[1] = 0;

    switch (user->example)
    {
    case 0:
        /* Use [ax,bx]x[ay,by] */
        conn = p4est_connectivity_new_unitsquare();
        cont = fclaw2d_map_new_nomap();
        break;
    case 1:
        conn = p4est_connectivity_new_disk();
        cont = fclaw2d_map_new_pillowdisk5 (gparms->scale,gparms->shift,
                                            rotate,user->alpha);
        break;
    default:
        SC_ABORT_NOT_REACHED ();
    }

    domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);

    /* ---------------------------------------------------------- */
    fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_INFO);
    fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);

    fclaw2d_domain_data_new(domain);
    fclaw2d_domain_set_app(domain,app);

    radialdam_link_solvers(domain);

    fclaw2d_initialize(&domain);
    fclaw2d_run(&domain);
    fclaw2d_finalize(&domain);

    fclaw2d_map_destroy(cont);
}

int
main (int argc, char **argv)
{
    fclaw_app_t *app;
    int first_arg;
    fclaw_exit_type_t vexit;

    /* Options */
    sc_options_t                  *options;
    user_options_t suser, *user = &suser;

    int retval;

    /* Initialize application */
    app = fclaw_app_new (&argc, &argv, user);

    /* Register packages */
    fclaw_forestclaw_register(app,"fclaw_options.ini");
    fc2d_clawpack46_register(app,"fclaw_options.ini");
    fc2d_clawpack5_register(app,"fclaw_options.ini");

    register_user_options(app,"fclaw_options.ini",user);

    /* Read configuration file(s) */
    options = fclaw_app_get_options (app);
    retval  = fclaw_options_read_from_file(options);
    vexit   =  fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");

    fclaw2d_clawpatch_link_app(app);

    if (!retval & !vexit)
    {
        run_program(app);
    }

    fclaw_forestclaw_destroy(app);
    fclaw_app_destroy (app);

    return 0;
}
<|endoftext|>


<commit_before>/*******************************************************************************
The MIT License (MIT)

Copyright (c) 2013, 2014 JCube001

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/

#include <math.h>

#include "quaternion.h"

Quaternion::Quaternion() :
    scalar(1.0f),
    x(0.0f),
    y(0.0f),
    z(0.0f)
{
}

Quaternion::Quaternion(const Quaternion &q) :
    scalar(q.scalar),
    x(q.x),
    y(q.y),
    z(q.z)
{
}

Quaternion::Quaternion(float scalar, float x, float y, float z) :
    scalar(scalar),
    x(x),
    y(y),
    z(z)
{
}

Quaternion Quaternion::conjugate() const
{
    return Quaternion(scalar, -x, -y, -z);
}

void Quaternion::convertToAxisAngle(float &ax, float &ay, float &az, float &angle)
{
    ax = x;
    ay = y;
    az = z;
    angle = 2.0f * acos(scalar);
}

void Quaternion::convertToEulerAngles(float &roll, float &pitch, float &yaw)
{
    roll = atan2(2.0f * ((scalar * x) + (y * z)), 1.0f - (2.0f * ((x * x) + (y * y))));
    pitch = asin(2.0f * ((scalar * y) - (z * x)));
    yaw = atan2(2.0f * ((scalar * z) + (x * y)), 1.0f - (2.0f * ((y * y) + (z * z))));
}

float Quaternion::dot(const Quaternion &q) const
{
    return (scalar * q.scalar) + (x * q.x) + (y * q.y) + (z * q.z);
}

Quaternion Quaternion::inverse() const
{
    const float n = norm();
    if (n == 0.0f)
    {
        return Quaternion();
    }
    return conjugate() / (n * n);
}

float Quaternion::norm() const
{
    return sqrt((scalar * scalar) + (x * x) + (y * y) + (z * z));
}

void Quaternion::normalize()
{
    *this /= norm();
}

Quaternion Quaternion::normalized() const
{
    return *this / norm();
}

Quaternion &Quaternion::operator=(const Quaternion &q)
{
    scalar = q.scalar;
    x = q.x;
    y = q.y;
    z = q.z;
    return *this;
}

Quaternion &Quaternion::operator+=(const Quaternion &q)
{
    scalar += q.scalar;
    x += q.x;
    y += q.y;
    z += q.z;
    return *this;
}

Quaternion &Quaternion::operator-=(const Quaternion &q)
{
    scalar -= q.scalar;
    x -= q.x;
    y -= q.y;
    z -= q.z;
    return *this;
}

Quaternion &Quaternion::operator*=(float factor)
{
    scalar *= factor;
    x *= factor;
    y *= factor;
    z *= factor;
    return *this;
}

Quaternion &Quaternion::operator*=(const Quaternion &q)
{
    scalar = (scalar * q.scalar) - (x * q.x) - (y * q.y) - (z * q.z);
    x = (scalar * q.x) + (x * q.scalar) + (y * q.z) - (z * q.y);
    y = (scalar * q.y) - (x * q.z) + (y * q.scalar) + (z * q.x);
    z = (scalar * q.z) + (x * q.y) - (y * q.x) + (z * q.scalar);
}

Quaternion &Quaternion::operator/=(float divisor)
{
    scalar /= divisor;
    x /= divisor;
    y /= divisor;
    z /= divisor;
    return *this;
}

<commit_msg>Added functions for conversions<commit_after>/*******************************************************************************
The MIT License (MIT)

Copyright (c) 2013, 2014 JCube001

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/

#include <math.h>

#include "quaternion.h"

Quaternion::Quaternion() :
    scalar(1.0f),
    x(0.0f),
    y(0.0f),
    z(0.0f)
{
}

Quaternion::Quaternion(const Quaternion &q) :
    scalar(q.scalar),
    x(q.x),
    y(q.y),
    z(q.z)
{
}

Quaternion::Quaternion(float scalar, float x, float y, float z) :
    scalar(scalar),
    x(x),
    y(y),
    z(z)
{
}

Quaternion Quaternion::conjugate() const
{
    return Quaternion(scalar, -x, -y, -z);
}

void Quaternion::convertToAxisAngle(float &ax, float &ay, float &az, float &angle)
{
    ax = x;
    ay = y;
    az = z;
    angle = 2.0f * acos(scalar);
}

void Quaternion::convertToEulerAngles(float &roll, float &pitch, float &yaw)
{
    roll = atan2((y * z) + (scalar * x), 0.5f - ((x * x) + (y * y)));
    pitch = asin(-2.0f * ((x * z) + (scalar * y)));
    yaw = atan2((x * y) + (scalar * z), 0.5f - ((y * y) + (z * z)));
}

float Quaternion::dot(const Quaternion &q) const
{
    return (scalar * q.scalar) + (x * q.x) + (y * q.y) + (z * q.z);
}

Quaternion Quaternion::inverse() const
{
    const float n = norm();
    if (n == 0.0f)
    {
        return Quaternion();
    }
    return conjugate() / (n * n);
}

float Quaternion::norm() const
{
    return sqrt((scalar * scalar) + (x * x) + (y * y) + (z * z));
}

void Quaternion::normalize()
{
    *this /= norm();
}

Quaternion Quaternion::normalized() const
{
    return *this / norm();
}

Quaternion &Quaternion::operator=(const Quaternion &q)
{
    scalar = q.scalar;
    x = q.x;
    y = q.y;
    z = q.z;
    return *this;
}

Quaternion &Quaternion::operator+=(const Quaternion &q)
{
    scalar += q.scalar;
    x += q.x;
    y += q.y;
    z += q.z;
    return *this;
}

Quaternion &Quaternion::operator-=(const Quaternion &q)
{
    scalar -= q.scalar;
    x -= q.x;
    y -= q.y;
    z -= q.z;
    return *this;
}

Quaternion &Quaternion::operator*=(float factor)
{
    scalar *= factor;
    x *= factor;
    y *= factor;
    z *= factor;
    return *this;
}

Quaternion &Quaternion::operator*=(const Quaternion &q)
{
    scalar = (scalar * q.scalar) - (x * q.x) - (y * q.y) - (z * q.z);
    x = (scalar * q.x) + (x * q.scalar) + (y * q.z) - (z * q.y);
    y = (scalar * q.y) - (x * q.z) + (y * q.scalar) + (z * q.x);
    z = (scalar * q.z) + (x * q.y) - (y * q.x) + (z * q.scalar);
}

Quaternion &Quaternion::operator/=(float divisor)
{
    scalar /= divisor;
    x /= divisor;
    y /= divisor;
    z /= divisor;
    return *this;
}

<|endoftext|>