<commit_before>#include <papyrus/PapyrusScript.h>

#include <boost/filesystem.hpp>

#include <Windows.h>
#include <lmcons.h>

#include <common/CapricaConfig.h>

namespace caprica { namespace papyrus {

pex::PexFile* PapyrusScript::buildPex() const {
  auto pex = new pex::PexFile();
  if (CapricaConfig::emitDebugInfo) {
    pex->debugInfo = new pex::PexDebugInfo();
    pex->debugInfo->modificationTime = boost::filesystem::last_write_time(sourceFileName);
  }
  pex->compilationTime = time(nullptr);
  pex->sourceFileName = sourceFileName;

  char compNameBuf[MAX_COMPUTERNAME_LENGTH + 1];
  DWORD compNameBufLength = sizeof(compNameBuf);
  if (!GetComputerNameA(compNameBuf, &compNameBufLength))
    CapricaError::logicalFatal("Failed to get the computer name!");
  pex->computerName = std::string(compNameBuf, compNameBufLength);

  char userNameBuf[UNLEN + 1];
  DWORD userNameBufLength = sizeof(userNameBuf);
  if (!GetUserNameA(userNameBuf, &userNameBufLength))
    CapricaError::logicalFatal("Failed to get the user name!");
  if (userNameBufLength > 0)
    userNameBufLength--;
  pex->userName = std::string(userNameBuf, userNameBufLength);

  for (auto o : objects)
    o->buildPex(pex);
  return pex;
}

}}
<commit_msg>Cache the username, because apparently it's expensive to get.<commit_after>#include <papyrus/PapyrusScript.h>

#include <boost/filesystem.hpp>

#include <Windows.h>
#include <lmcons.h>

#include <common/CapricaConfig.h>

namespace caprica { namespace papyrus {

pex::PexFile* PapyrusScript::buildPex() const {
  auto pex = new pex::PexFile();
  if (CapricaConfig::emitDebugInfo) {
    pex->debugInfo = new pex::PexDebugInfo();
    pex->debugInfo->modificationTime = boost::filesystem::last_write_time(sourceFileName);
  }
  pex->compilationTime = time(nullptr);
  pex->sourceFileName = sourceFileName;

  static std::string computerName = []() -> std::string {
    char compNameBuf[MAX_COMPUTERNAME_LENGTH + 1];
    DWORD compNameBufLength = sizeof(compNameBuf);
    if (!GetComputerNameA(compNameBuf, &compNameBufLength))
      CapricaError::logicalFatal("Failed to get the computer name!");
    return std::string(compNameBuf, compNameBufLength);
  }();
  pex->computerName = computerName;

  static std::string userName = []() -> std::string {
    char userNameBuf[UNLEN + 1];
    DWORD userNameBufLength = sizeof(userNameBuf);
    if (!GetUserNameA(userNameBuf, &userNameBufLength))
      CapricaError::logicalFatal("Failed to get the user name!");
    if (userNameBufLength > 0)
      userNameBufLength--;
    return std::string(userNameBuf, userNameBufLength);
  }();
  pex->userName = userName;

  for (auto o : objects)
    o->buildPex(pex);
  return pex;
}

}}
<|endoftext|>


<commit_before>
#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_MULTISCALE_COUPLING_HH
#define DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_MULTISCALE_COUPLING_HH

// system
#include <vector>

// dune-common
#include <dune/common/dynmatrix.hh>

namespace Dune {

namespace Detailed {

namespace Discretizations {

namespace Assembler {

namespace Multiscale {

namespace Coupling {

template <class CouplingGridPartImp, class InnerAnsatzSpaceImp, class InnerTestSpaceImp, class OuterAnsatzSpaceImp,
          class OuterTestSpaceImp>
class Primal
{
public:
  typedef CouplingGridPartImp CouplingGridPartType;

  typedef InnerAnsatzSpaceImp InnerAnsatzSpaceType;

  typedef InnerTestSpaceImp InnerTestSpaceType;

  typedef OuterAnsatzSpaceImp OuterAnsatzSpaceType;

  typedef OuterTestSpaceImp OuterTestSpaceType;

  typedef Primal<CouplingGridPartType, InnerAnsatzSpaceType, InnerTestSpaceType, OuterAnsatzSpaceType,
                 OuterTestSpaceType> ThisType;

  Primal(const CouplingGridPartType& couplingGridPart, const InnerAnsatzSpaceType& innerAnsatzSpace,
         const InnerTestSpaceType& innerTestSpace, const OuterAnsatzSpaceType& outerAnsatzSpace,
         const OuterTestSpaceType& outerTestSpace)
    : couplingGridPart_(couplingGridPart)
    , innerAnsatzSpace_(innerAnsatzSpace)
    , innerTestSpace_(innerTestSpace)
    , outerAnsatzSpace_(outerAnsatzSpace)
    , outerTestSpace_(outerTestSpace)
  {
  }

  const CouplingGridPartType& couplingGridPart() const
  {
    return couplingGridPart_;
  }

  const InnerAnsatzSpaceType& innerAnsatzSpace() const
  {
    return innerAnsatzSpace_;
  }

  const InnerTestSpaceType& innerTestSpace() const
  {
    return innerTestSpace_;
  }

  const OuterAnsatzSpaceType& outerAnsatzSpace() const
  {
    return outerAnsatzSpace_;
  }

  const OuterTestSpaceType& outerTestSpace() const
  {
    return outerTestSpace_;
  }

  template <class LocalAssemblerType, class MatrixBackendType>
  void assembleMatrices(const LocalAssemblerType& localAssembler, MatrixBackendType& innerInnerMatrix,
                        MatrixBackendType& outerOuterMatrix, MatrixBackendType& innerOuterMatrix,
                        MatrixBackendType& outerInnerMatrix) const
  {
    // preparations
    typedef typename CouplingGridPartType::template Codim<0>::EntityType EntityType;
    typedef typename CouplingGridPartType::IntersectionIteratorType IntersectionIteratorType;
    typedef typename IntersectionIteratorType::Intersection IntersectionType;
    typedef typename IntersectionType::EntityPointer EntityPointerType;
    typedef typename InnerAnsatzSpaceType::RangeFieldType RangeFieldType;
    typedef Dune::DynamicMatrix<RangeFieldType> LocalMatrixType;
    // common tmp storage for all entities
    std::vector<unsigned int> numberTmpMatrices = localAssembler.numTmpObjectsRequired();
    std::vector<LocalMatrixType> tmpLocalAssemblerMatrices(
        numberTmpMatrices[0],
        LocalMatrixType(std::max(innerAnsatzSpace_.map().maxLocalSize(), outerAnsatzSpace_.map().maxLocalSize()),
                        std::max(innerTestSpace_.map().maxLocalSize(), outerTestSpace_.map().maxLocalSize()),
                        RangeFieldType(0.0)));
    std::vector<LocalMatrixType> tmpLocalOperatorMatrices(
        numberTmpMatrices[1],
        LocalMatrixType(std::max(innerAnsatzSpace_.map().maxLocalSize(), outerAnsatzSpace_.map().maxLocalSize()),
                        std::max(innerTestSpace_.map().maxLocalSize(), outerTestSpace_.map().maxLocalSize()),
                        RangeFieldType(0.0)));
    std::vector<std::vector<LocalMatrixType>> tmpLocalMatricesContainer;
    tmpLocalMatricesContainer.push_back(tmpLocalAssemblerMatrices);
    tmpLocalMatricesContainer.push_back(tmpLocalOperatorMatrices);
    // walk the coupling grid part
    for (typename CouplingGridPartType::template Codim<0>::IteratorType entityIt =
             couplingGridPart_.template begin<0>();
         entityIt != couplingGridPart_.template end<0>();
         ++entityIt) {
      const EntityType& insideEntity = *entityIt;
      // walk the intersections
      for (IntersectionIteratorType interectionIt = couplingGridPart_.ibegin(insideEntity);
           interectionIt != couplingGridPart_.iend(insideEntity);
           ++interectionIt) {
        // with a coupling grid part we can be sure to only get inner intersection (so we only need the assert, not an
        // if)
        const IntersectionType& intersection = *interectionIt;
        assert(intersection.neighbor() && !intersection.boundary());
        // call the local assembler
        localAssembler.assembleLocal(intersection,
                                     innerAnsatzSpace_,
                                     innerTestSpace_,
                                     outerAnsatzSpace_,
                                     outerTestSpace_,
                                     innerInnerMatrix,
                                     outerOuterMatrix,
                                     innerOuterMatrix,
                                     outerInnerMatrix,
                                     tmpLocalMatricesContainer);
      } // walk the intersections
    } // walk the coupling grid part
  } // void assembleMatrices() const

private:
  const CouplingGridPartType& couplingGridPart_;
  const InnerAnsatzSpaceType& innerAnsatzSpace_;
  const InnerTestSpaceType& innerTestSpace_;
  const OuterAnsatzSpaceType& outerAnsatzSpace_;
  const OuterTestSpaceType& outerTestSpace_;
}; // class Primal

} // namespace Coupling

} // namespace Multiscale

} // namespace Assembler

} // namespace Discretizations

} // namespace Detailed

} // namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_MULTISCALE_COUPLING_HH
<commit_msg>[assembler.multiscale.coupling] changed argument order<commit_after>
#ifndef DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_MULTISCALE_COUPLING_HH
#define DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_MULTISCALE_COUPLING_HH

// system
#include <vector>

// dune-common
#include <dune/common/dynmatrix.hh>

namespace Dune {

namespace Detailed {

namespace Discretizations {

namespace Assembler {

namespace Multiscale {

namespace Coupling {

template <class CouplingGridPartImp, class InnerAnsatzSpaceImp, class InnerTestSpaceImp, class OuterAnsatzSpaceImp,
          class OuterTestSpaceImp>
class Primal
{
public:
  typedef CouplingGridPartImp CouplingGridPartType;

  typedef InnerAnsatzSpaceImp InnerAnsatzSpaceType;

  typedef InnerTestSpaceImp InnerTestSpaceType;

  typedef OuterAnsatzSpaceImp OuterAnsatzSpaceType;

  typedef OuterTestSpaceImp OuterTestSpaceType;

  typedef Primal<CouplingGridPartType, InnerAnsatzSpaceType, InnerTestSpaceType, OuterAnsatzSpaceType,
                 OuterTestSpaceType> ThisType;

  Primal(const CouplingGridPartType& couplingGridPart, const InnerAnsatzSpaceType& innerAnsatzSpace,
         const InnerTestSpaceType& innerTestSpace, const OuterAnsatzSpaceType& outerAnsatzSpace,
         const OuterTestSpaceType& outerTestSpace)
    : couplingGridPart_(couplingGridPart)
    , innerAnsatzSpace_(innerAnsatzSpace)
    , innerTestSpace_(innerTestSpace)
    , outerAnsatzSpace_(outerAnsatzSpace)
    , outerTestSpace_(outerTestSpace)
  {
  }

  const CouplingGridPartType& couplingGridPart() const
  {
    return couplingGridPart_;
  }

  const InnerAnsatzSpaceType& innerAnsatzSpace() const
  {
    return innerAnsatzSpace_;
  }

  const InnerTestSpaceType& innerTestSpace() const
  {
    return innerTestSpace_;
  }

  const OuterAnsatzSpaceType& outerAnsatzSpace() const
  {
    return outerAnsatzSpace_;
  }

  const OuterTestSpaceType& outerTestSpace() const
  {
    return outerTestSpace_;
  }

  template <class LocalAssemblerType, class MatrixBackendType>
  void assembleMatrices(const LocalAssemblerType& localAssembler, MatrixBackendType& innerInnerMatrix,
                        MatrixBackendType& innerOuterMatrix, MatrixBackendType& outerInnerMatrix,
                        MatrixBackendType& outerOuterMatrix) const
  {
    // preparations
    typedef typename CouplingGridPartType::template Codim<0>::EntityType EntityType;
    typedef typename CouplingGridPartType::IntersectionIteratorType IntersectionIteratorType;
    typedef typename IntersectionIteratorType::Intersection IntersectionType;
    typedef typename IntersectionType::EntityPointer EntityPointerType;
    typedef typename InnerAnsatzSpaceType::RangeFieldType RangeFieldType;
    typedef Dune::DynamicMatrix<RangeFieldType> LocalMatrixType;
    // common tmp storage for all entities
    std::vector<unsigned int> numberTmpMatrices = localAssembler.numTmpObjectsRequired();
    std::vector<LocalMatrixType> tmpLocalAssemblerMatrices(
        numberTmpMatrices[0],
        LocalMatrixType(std::max(innerAnsatzSpace_.map().maxLocalSize(), outerAnsatzSpace_.map().maxLocalSize()),
                        std::max(innerTestSpace_.map().maxLocalSize(), outerTestSpace_.map().maxLocalSize()),
                        RangeFieldType(0.0)));
    std::vector<LocalMatrixType> tmpLocalOperatorMatrices(
        numberTmpMatrices[1],
        LocalMatrixType(std::max(innerAnsatzSpace_.map().maxLocalSize(), outerAnsatzSpace_.map().maxLocalSize()),
                        std::max(innerTestSpace_.map().maxLocalSize(), outerTestSpace_.map().maxLocalSize()),
                        RangeFieldType(0.0)));
    std::vector<std::vector<LocalMatrixType>> tmpLocalMatricesContainer;
    tmpLocalMatricesContainer.push_back(tmpLocalAssemblerMatrices);
    tmpLocalMatricesContainer.push_back(tmpLocalOperatorMatrices);
    // walk the coupling grid part
    for (typename CouplingGridPartType::template Codim<0>::IteratorType entityIt =
             couplingGridPart_.template begin<0>();
         entityIt != couplingGridPart_.template end<0>();
         ++entityIt) {
      const EntityType& insideEntity = *entityIt;
      // walk the intersections
      for (IntersectionIteratorType interectionIt = couplingGridPart_.ibegin(insideEntity);
           interectionIt != couplingGridPart_.iend(insideEntity);
           ++interectionIt) {
        // with a coupling grid part we can be sure to only get inner intersection (so we only need the assert, not an
        // if)
        const IntersectionType& intersection = *interectionIt;
        assert(intersection.neighbor() && !intersection.boundary());
        // call the local assembler
        localAssembler.assembleLocal(intersection,
                                     innerAnsatzSpace_,
                                     innerTestSpace_,
                                     outerAnsatzSpace_,
                                     outerTestSpace_,
                                     innerInnerMatrix,
                                     outerOuterMatrix,
                                     innerOuterMatrix,
                                     outerInnerMatrix,
                                     tmpLocalMatricesContainer);
      } // walk the intersections
    } // walk the coupling grid part
  } // void assembleMatrices() const

private:
  const CouplingGridPartType& couplingGridPart_;
  const InnerAnsatzSpaceType& innerAnsatzSpace_;
  const InnerTestSpaceType& innerTestSpace_;
  const OuterAnsatzSpaceType& outerAnsatzSpace_;
  const OuterTestSpaceType& outerTestSpace_;
}; // class Primal

} // namespace Coupling

} // namespace Multiscale

} // namespace Assembler

} // namespace Discretizations

} // namespace Detailed

} // namespace Dune

#endif // DUNE_DETAILED_DISCRETIZATIONS_ASSEMBLER_MULTISCALE_COUPLING_HH
<|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.

=========================================================================*/
#ifndef __otbWrapperDocExampleStructure_cxx
#define __otbWrapperDocExampleStructure_cxx

#include "otbWrapperDocExampleStructure.h"

namespace otb
{
namespace Wrapper
{

DocExampleStructure::DocExampleStructure() : m_ParameterList(), m_ApplicationName(""), m_ExampleCommentList(), m_NbOfExamples(1)
{
  m_ExampleCommentList.push_back("");
  m_ParameterList.push_back(ParametersVectorType());
}

DocExampleStructure::~DocExampleStructure()
{
}

void
DocExampleStructure::AddParameter( const std::string key, const std::string value, unsigned int exId)
{

  m_ParameterList.at(exId).push_back(std::make_pair(key, value));
}

DocExampleStructure::ParametersVectorOfVectorType
DocExampleStructure::GetParameterList()
{
  return m_ParameterList;
}

unsigned int DocExampleStructure::GetNumberOfParameters(unsigned int exId)
{
  return m_ParameterList.at(exId).size();
}

/** Get a specific parameter couple.*/
std::string
DocExampleStructure::GetParameterKey( unsigned int i, unsigned int exId)
{
  return m_ParameterList.at(exId).at(i).first;
}

std::string
DocExampleStructure::GetParameterValue( unsigned int i, unsigned int exId )
{
  return m_ParameterList.at(exId).at(i).second;
}

void
DocExampleStructure::SetApplicationName( const std::string name )
{
  m_ApplicationName = name;
}

std::string
DocExampleStructure::GetApplicationName()
{
  return m_ApplicationName;
}

std::vector<std::string>
DocExampleStructure::GetExampleCommentList()
{
  return m_ExampleCommentList;
}

std::string
DocExampleStructure::GetExampleComment( unsigned int i)
{
  return m_ExampleCommentList.at(i);
}

void
DocExampleStructure::SetExampleComment( const std::string & comm, unsigned int i )
{
  if( m_ExampleCommentList.size() < i )
    itkGenericExceptionMacro( "Index "<<i<<" out of range. (max index: "<<m_ExampleCommentList.size()-1<<")." );

  this->m_ExampleCommentList[i] = comm;
}

unsigned int
DocExampleStructure::AddExample( const std::string & comm )
{
  m_ExampleCommentList.push_back( comm );
  m_NbOfExamples++;

  m_ParameterList.push_back(ParametersVectorType());

  return m_ExampleCommentList.size()-1;
}

std::string
DocExampleStructure::GenerateCLExample( unsigned int exId )
{
  if( m_ApplicationName.empty() || m_ParameterList.at(exId).empty() )
    {
    return "";
    }

  std::ostringstream oss;
  oss << "otbcli_" << m_ApplicationName << " ";

  for (ParametersVectorType::const_iterator it = m_ParameterList.at(exId).begin();
       it != m_ParameterList.at(exId).end(); ++it)
    {
    if( it->second != "" )
      {
      oss<< "-" << it->first << " " << it->second <<" ";
      }
    }

  std::string res = oss.str();

  // Supress last added space
  res.erase( res.size()-1, 1);

  return res;
}

std::string
DocExampleStructure::GenerateCLExample()
{
  std::ostringstream oss;
  for( unsigned int exId=0; exId<m_NbOfExamples; exId++)
    {
    if( !m_ExampleCommentList[exId].empty() )
      oss << m_ExampleCommentList[exId]<< std::endl;
    oss << this->GenerateCLExample( exId );
    oss << std::endl;
    }

  std::string res = oss.str();
  return res;
}

std::string
DocExampleStructure::GenerateHtmlExample( unsigned int exId )
{
  if( m_ApplicationName.empty() || m_ParameterList.size() == 0 )
    {
    return "";
    }

  std::ostringstream oss;
  oss << "
";

  for (ParametersVectorType::const_iterator it = m_ParameterList.at(exId).begin();
       it != m_ParameterList.at(exId).end(); ++it)
    {
    if( it->second != "" )
      {
      oss << "
";
      oss << "
";
      oss << it->first << ": " << it->second;
      oss << "
";
      oss << "
";
      }
    }
  oss << "
";

  std::string res = oss.str();

  return res;

}

std::string
DocExampleStructure::GenerateHtmlExample()
{
  std::ostringstream oss;
  if( m_NbOfExamples>1 )
    oss << "
";

  for( unsigned int exId=0; exId<m_NbOfExamples; exId++)
    {
    if( m_NbOfExamples>1 )
      oss << "
";
    if( !m_ExampleCommentList[exId].empty() )
      oss << m_ExampleCommentList[exId];
    oss << this->GenerateHtmlExample( exId );
    if( m_NbOfExamples>1 )
      oss << "
";
    }
  if( m_NbOfExamples>1 )
    oss << "
";

  std::string res = oss.str();

  return res;
}

} // End namespace Wrapper
} // End namespace otb

#endif
<commit_msg>ENH: fix bug in DocStrucutre when no example parameter is given<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.

=========================================================================*/
#ifndef __otbWrapperDocExampleStructure_cxx
#define __otbWrapperDocExampleStructure_cxx

#include "otbWrapperDocExampleStructure.h"

namespace otb
{
namespace Wrapper
{

DocExampleStructure::DocExampleStructure() : m_ParameterList(), m_ApplicationName(""), m_ExampleCommentList(), m_NbOfExamples(1)
{
  m_ExampleCommentList.push_back("");
}

DocExampleStructure::~DocExampleStructure()
{
}

void
DocExampleStructure::AddParameter( const std::string key, const std::string value, unsigned int exId)
{
  if( m_ParameterList.size() < exId+1 )
    {
    while( m_ParameterList.size()<exId+1)
      {
      m_ParameterList.push_back(ParametersVectorType());
      }
    }

  m_ParameterList.at(exId).push_back(std::make_pair(key, value));
}

DocExampleStructure::ParametersVectorOfVectorType
DocExampleStructure::GetParameterList()
{
  return m_ParameterList;
}

unsigned int DocExampleStructure::GetNumberOfParameters(unsigned int exId)
{
  return m_ParameterList.at(exId).size();
}

/** Get a specific parameter couple.*/
std::string
DocExampleStructure::GetParameterKey( unsigned int i, unsigned int exId)
{
  return m_ParameterList.at(exId).at(i).first;
}

std::string
DocExampleStructure::GetParameterValue( unsigned int i, unsigned int exId )
{
  return m_ParameterList.at(exId).at(i).second;
}

void
DocExampleStructure::SetApplicationName( const std::string name )
{
  m_ApplicationName = name;
}

std::string
DocExampleStructure::GetApplicationName()
{
  return m_ApplicationName;
}

std::vector<std::string>
DocExampleStructure::GetExampleCommentList()
{
  return m_ExampleCommentList;
}

std::string
DocExampleStructure::GetExampleComment( unsigned int i)
{
  return m_ExampleCommentList.at(i);
}

void
DocExampleStructure::SetExampleComment( const std::string & comm, unsigned int i )
{
  if( m_ExampleCommentList.size() < i )
    itkGenericExceptionMacro( "Index "<<i<<" out of range. (max index: "<<m_ExampleCommentList.size()-1<<")." );

  this->m_ExampleCommentList[i] = comm;
}

unsigned int
DocExampleStructure::AddExample( const std::string & comm )
{
  m_ExampleCommentList.push_back( comm );
  m_NbOfExamples++;

  m_ParameterList.push_back(ParametersVectorType());

  return m_ExampleCommentList.size()-1;
}

std::string
DocExampleStructure::GenerateCLExample( unsigned int exId )
{
  if( m_ApplicationName.empty() || m_ParameterList.at(exId).empty() )
    {
    return "";
    }

  std::ostringstream oss;
  oss << "otbcli_" << m_ApplicationName << " ";

  for (ParametersVectorType::const_iterator it = m_ParameterList.at(exId).begin();
       it != m_ParameterList.at(exId).end(); ++it)
    {
    if( it->second != "" )
      {
      oss<< "-" << it->first << " " << it->second <<" ";
      }
    }

  std::string res = oss.str();

  // Supress last added space
  res.erase( res.size()-1, 1);

  return res;
}

std::string
DocExampleStructure::GenerateCLExample()
{
  std::ostringstream oss;
  for( unsigned int exId=0; exId<m_NbOfExamples; exId++)
    {
    if( !m_ExampleCommentList[exId].empty() )
      oss << m_ExampleCommentList[exId]<< std::endl;
    oss << this->GenerateCLExample( exId );
    oss << std::endl;
    }

  std::string res = oss.str();
  return res;
}

std::string
DocExampleStructure::GenerateHtmlExample( unsigned int exId )
{
  if( m_ApplicationName.empty() || m_ParameterList.size() == 0 )
    {
    return "";
    }

  std::ostringstream oss;
  oss << "
";

  for (ParametersVectorType::const_iterator it = m_ParameterList.at(exId).begin();
       it != m_ParameterList.at(exId).end(); ++it)
    {
    if( it->second != "" )
      {
      oss << "
";
      oss << "
";
      oss << it->first << ": " << it->second;
      oss << "
";
      oss << "
";
      }
    }
  oss << "
";

  std::string res = oss.str();

  return res;

}

std::string
DocExampleStructure::GenerateHtmlExample()
{
  std::ostringstream oss;
  if( m_NbOfExamples>1 )
    oss << "
";

  for( unsigned int exId=0; exId<m_NbOfExamples; exId++)
    {
    if( m_NbOfExamples>1 )
      oss << "
";
    if( !m_ExampleCommentList[exId].empty() )
      oss << m_ExampleCommentList[exId];
    oss << this->GenerateHtmlExample( exId );
    if( m_NbOfExamples>1 )
      oss << "
";
    }
  if( m_NbOfExamples>1 )
    oss << "
";

  std::string res = oss.str();

  return res;
}

} // End namespace Wrapper
} // End namespace otb

#endif
<|endoftext|>


<commit_before>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s

/* Copyright (c) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the  GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
* ========LICENCE========
*/

#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular.h>

#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/Matio.h"
#include "fflas-ffpack/utils/args-parser.h"

using namespace std;
using namespace FFLAS;
using namespace FFPACK;
int main(int argc, char** argv) {

	size_t iter = 3;
	int    q    = 131071;
	size_t    n    = 1000;
	size_t    k    = 1000;
	size_t threshold = 64;
	bool up =true;
	std::string file = "";

	Argument as[] = {
		{ 'q', "-q Q", "Set the field characteristic (-1 for random).",  TYPE_INT , &q },
		{ 'n', "-n N", "Set the dimension of the matrix C.",               TYPE_INT , &n },
		{ 'k', "-k K", "Set the other dimension of the matrix A.",               TYPE_INT , &k },
		{ 'u', "-u yes/no", "Updates an upper/lower triangular matrix.",  TYPE_BOOL , &up },
		{ 'i', "-i R", "Set number of repetitions.",                     TYPE_INT , &iter },
		{ 't', "-t T", "Set the threshold to the base case.",                     TYPE_INT , &threshold },
		END_OF_ARGUMENTS
	};

	FFLAS::parseArguments(argc,argv,as);

	typedef Givaro::ModularBalanced<double> Field;
	typedef Field::Element Element;

	Field F(q);
	Field::Element * A, *C;

	FFLAS::Timer chrono;
	double time=0.0;

	FFLAS_UPLO uplo = up?FflasUpper:FflasLower;
	for (size_t i=0;i<=iter;++i){
		A = fflas_new<Element>(n*k);
		size_t lda=k;
		C = fflas_new<Element>(n*n);
		size_t ldc=n;
		Field::RandIter G(F);
		RandomMatrix (F, n, k, A, k, G);
		RandomTriangularMatrix (F, n,n,uplo, FflasNonUnit, true, C, ldc, G);
		Field::Element_ptr D = FFLAS::fflas_new(F,k,1);
		Givaro::GeneralRingNonZeroRandIter<Field,Field::RandIter> nzG (G);
		for (size_t i=0; i<k; i++)
			nzG.random(D[i]);
		chrono.clear();
		if (i) chrono.start();
		fsyrk (F, uplo, FflasTrans, n, k, F.mOne, A, lda, D, 1, F.one, C, ldc, threshold);
		if (i) chrono.stop();

		time+=chrono.usertime();
		FFLAS::fflas_delete( A);
	}

		// -----------
		// Standard output for benchmark - Alexis Breust 2014/11/14
#define CUBE(x) ((x)*(x)*(x))
	std::cout << "Time: " << time / double(iter)
			  << " Gflops: " << CUBE(double(n)/1000.)/ time * double(iter);
	FFLAS::writeCommandString(std::cout, as) << std::endl;
	return 0;
}
<commit_msg>Each execution lost 32MB of memory. Added two fflas_delete()'s.<commit_after>/* -*- mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
// vim:sts=4:sw=4:ts=4:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s

/* Copyright (c) FFLAS-FFPACK
* Written by Clément Pernet <clement.pernet@imag.fr>
* ========LICENCE========
* This file is part of the library FFLAS-FFPACK.
*
* FFLAS-FFPACK is free software: you can redistribute it and/or modify
* it under the terms of the  GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
* ========LICENCE========
*/

#include "fflas-ffpack/fflas-ffpack-config.h"
#include <iostream>
#include <givaro/modular.h>

#include "fflas-ffpack/fflas-ffpack.h"
#include "fflas-ffpack/utils/timer.h"
#include "fflas-ffpack/utils/Matio.h"
#include "fflas-ffpack/utils/args-parser.h"

using namespace std;
using namespace FFLAS;
using namespace FFPACK;
int main(int argc, char** argv) {

	size_t iter = 3;
	int    q    = 131071;
	size_t    n    = 1000;
	size_t    k    = 1000;
	size_t threshold = 64;
	bool up =true;
	std::string file = "";

	Argument as[] = {
		{ 'q', "-q Q", "Set the field characteristic (-1 for random).",  TYPE_INT , &q },
		{ 'n', "-n N", "Set the dimension of the matrix C.",               TYPE_INT , &n },
		{ 'k', "-k K", "Set the other dimension of the matrix A.",               TYPE_INT , &k },
		{ 'u', "-u yes/no", "Updates an upper/lower triangular matrix.",  TYPE_BOOL , &up },
		{ 'i', "-i R", "Set number of repetitions.",                     TYPE_INT , &iter },
		{ 't', "-t T", "Set the threshold to the base case.",                     TYPE_INT , &threshold },
		END_OF_ARGUMENTS
	};

	FFLAS::parseArguments(argc,argv,as);

	typedef Givaro::ModularBalanced<double> Field;
	typedef Field::Element Element;

	Field F(q);
	Field::Element * A, *C;

	FFLAS::Timer chrono;
	double time=0.0;

	FFLAS_UPLO uplo = up?FflasUpper:FflasLower;
	for (size_t i=0;i<=iter;++i){
		A = fflas_new<Element>(n*k);
		size_t lda=k;
		C = fflas_new<Element>(n*n);
		size_t ldc=n;
		Field::RandIter G(F);
		RandomMatrix (F, n, k, A, k, G);
		RandomTriangularMatrix (F, n,n,uplo, FflasNonUnit, true, C, ldc, G);
		Field::Element_ptr D = FFLAS::fflas_new(F,k,1);
		Givaro::GeneralRingNonZeroRandIter<Field,Field::RandIter> nzG (G);
		for (size_t i=0; i<k; i++)
			nzG.random(D[i]);
		chrono.clear();
		if (i) chrono.start();
		fsyrk (F, uplo, FflasTrans, n, k, F.mOne, A, lda, D, 1, F.one, C, ldc, threshold);
		if (i) chrono.stop();

		time+=chrono.usertime();
		FFLAS::fflas_delete( A);
		FFLAS::fflas_delete( C);
		FFLAS::fflas_delete( D);
	}

		// -----------
		// Standard output for benchmark - Alexis Breust 2014/11/14
#define CUBE(x) ((x)*(x)*(x))
	std::cout << "Time: " << time / double(iter)
			  << " Gflops: " << CUBE(double(n)/1000.)/ time * double(iter);
	FFLAS::writeCommandString(std::cout, as) << std::endl;
	return 0;
}
<|endoftext|>


<commit_before>/**
 * @file Link.cpp
 *
 * @author Xu, Yuan
 * Implementation of Kinematic Link
 */

#include "Link.h"
#include "Tools/Debug/NaoTHAssert.h"

namespace Kinematics
{

Link::Link()
  :
  _id(-1),
  _sister(NULL),
  _child(NULL),
  _mother(NULL),
  _jointID(-1),

  _mass(0.0),

  // public access references
  id(_id),
  jointID(_jointID),
  a(_a),
  sister(_sister),
  child(_child),
  mother(_mother),
  mass(_mass),
  b(_b),

  p(M.translation),
  R(M.rotation),

  q(NULL),
  dq(NULL),
  ddq(NULL)
{
}

Link::~Link()
{
}

void Link::normalizeJointAngle()
{
  (*q) = Math::normalizeAngle(*q);
}

Link& Link::connect(Link& c)
{
  ASSERT(c._mother == NULL);
  c._mother = this;

  if (_child == NULL)
  {
    _child = &c;
  }
  else
  {
    Link* s = _child;
    while (s->_sister != NULL)
    {
      s = s->_sister;
    }
    s->_sister = &c;
  }

  return c;
}//end connect

void Link::updateFromMother()
{
  if (NULL != mother)
  {
    p = mother->R * b + mother->p;
    if (NULL != q)// joint rotation
    {
      R = mother->R * Rodrigues(A, A2, *q);
    } else
    {
      R = mother->R;
    }
  }
  // TODO: remove this?
  //        else{
  //            p = Vector3<double>(0,0,0);
  //            R = RotationMatrix(Vector3<double>(1,0,0),Vector3<double>(0,1,0),Vector3<double>(0,0,1));
  //        }
}//end updateFromMother

void Link::updateAllFromMother()
{
  if (NULL != mother)
  {
    p = mother->R * b + mother->p;
    if (NULL != q)// joint rotation
    {
      R *= Rodrigues(A, A2, *q);
      // senity check if R is still a kind of a rotation matrix...
      assert(fabs(1.0-fabs(R.det())) < 0.001);

//      Vector3<double> sw = R * a;
//      Vector3<double> sv = p ^ sw;
//      Vector3<double> dsv = (w ^ sv) + (v ^ sw);
//      Vector3<double> dsw = w ^ sw;

      // velocity
//      w += (sw * (*dq));
//      v += (sv * (*dq));

      // acceleration
//      dw += dsw * (*dq) + sw * (*ddq);
//      dv += dsv * (*dq) + sv * (*ddq);
    }
    else
    {
      R = mother->R;
//    w = mother->w;
//    v = mother->v;
//    dw = mother->dw;
//    dv = mother->dv;
    }
  }
}//end updateAllFromMother

void Link::updateMother()
{
  if (NULL == mother) return;

  mother->R = R * Rodrigues(A, A2, -(*(q)));
  mother->p = p - mother->R * b;
}//end updateMother

void Link::updateCoM()
{
  c = R * d + p;
}

void Link::setMass(double m, const Vector3<double>& cog)
{
  _mass = m;
  d = cog;
}

void Link::setJoint(const Vector3<double>& axis, int JointId)
{
  _a = axis;
  _jointID = JointId;

  A = Matrix3x3<double>(Vector3d(0, a.z, -a.y), Vector3d(-a.z, 0, a.x), Vector3d(a.y, -a.x, 0));
  A2 = A * A;
}

void Link::setLink(double x, double y, double z)
{
  _b.x = x;
  _b.y = y;
  _b.z = z;
}

} // namespace Kinematics
<commit_msg>bugfix: reverted a change I applyied a couple revisions ago (the joint rotation is applied to mothers rotation)<commit_after>/**
 * @file Link.cpp
 *
 * @author Xu, Yuan
 * Implementation of Kinematic Link
 */

#include "Link.h"
#include "Tools/Debug/NaoTHAssert.h"

namespace Kinematics
{

Link::Link()
  :
  _id(-1),
  _sister(NULL),
  _child(NULL),
  _mother(NULL),
  _jointID(-1),

  _mass(0.0),

  // public access references
  id(_id),
  jointID(_jointID),
  a(_a),
  sister(_sister),
  child(_child),
  mother(_mother),
  mass(_mass),
  b(_b),

  p(M.translation),
  R(M.rotation),

  q(NULL),
  dq(NULL),
  ddq(NULL)
{
}

Link::~Link()
{
}

void Link::normalizeJointAngle()
{
  (*q) = Math::normalizeAngle(*q);
}

Link& Link::connect(Link& c)
{
  ASSERT(c._mother == NULL);
  c._mother = this;

  if (_child == NULL)
  {
    _child = &c;
  }
  else
  {
    Link* s = _child;
    while (s->_sister != NULL)
    {
      s = s->_sister;
    }
    s->_sister = &c;
  }

  return c;
}//end connect

void Link::updateFromMother()
{
  if (NULL != mother)
  {
    p = mother->R * b + mother->p;
    if (NULL != q)// joint rotation
    {
      R = mother->R * Rodrigues(A, A2, *q);
    } else
    {
      R = mother->R;
    }
  }
  // TODO: remove this?
  //        else{
  //            p = Vector3<double>(0,0,0);
  //            R = RotationMatrix(Vector3<double>(1,0,0),Vector3<double>(0,1,0),Vector3<double>(0,0,1));
  //        }
}//end updateFromMother

void Link::updateAllFromMother()
{
  if (NULL != mother)
  {
    p = mother->R * b + mother->p;
    R = mother->R;
//    w = mother->w;
//    v = mother->v;
//    dw = mother->dw;
//    dv = mother->dv;

    // update by joint if there is one
    if (NULL != q)
    {
      R *= Rodrigues(A, A2, *q);
      // senity check if R is still a kind of a rotation matrix...
      assert(fabs(1.0-fabs(R.det())) < 0.001);

//      Vector3<double> sw = R * a;
//      Vector3<double> sv = p ^ sw;
//      Vector3<double> dsv = (w ^ sv) + (v ^ sw);
//      Vector3<double> dsw = w ^ sw;

      // velocity
//      w += (sw * (*dq));
//      v += (sv * (*dq));

      // acceleration
//      dw += dsw * (*dq) + sw * (*ddq);
//      dv += dsv * (*dq) + sv * (*ddq);
    }
  }//end if NULL != mother
}//end updateAllFromMother

void Link::updateMother()
{
  if (NULL == mother) return;

  mother->R = R * Rodrigues(A, A2, -(*(q)));
  mother->p = p - mother->R * b;
}//end updateMother

void Link::updateCoM()
{
  c = R * d + p;
}

void Link::setMass(double m, const Vector3<double>& cog)
{
  _mass = m;
  d = cog;
}

void Link::setJoint(const Vector3<double>& axis, int JointId)
{
  _a = axis;
  _jointID = JointId;

  A = Matrix3x3<double>(Vector3d(0, a.z, -a.y), Vector3d(-a.z, 0, a.x), Vector3d(a.y, -a.x, 0));
  A2 = A * A;
}

void Link::setLink(double x, double y, double z)
{
  _b.x = x;
  _b.y = y;
  _b.z = z;
}

} // namespace Kinematics
<|endoftext|>


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

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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 "mvdHistogramModel.h"

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdVectorImageModel.h"

namespace mvd
{
/*
  TRANSLATOR mvd::HistogramModel

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */

/*******************************************************************************/
HistogramModel
::HistogramModel( QObject* parent ) :
  AbstractModel( parent ),
  m_Histograms(),
  m_MinPixel(),
  m_MaxPixel()
{
}

/*******************************************************************************/
HistogramModel
::~HistogramModel()
{
}

/*******************************************************************************/
double
HistogramModel
::Percentile( CountType band, MeasurementType intensity, Bound bound ) const
{
  // Get histogram of band.
  Histogram::Pointer histogram( m_Histograms->GetNthElement( band ) );

  // Contruct 1D measurement vector.
  Histogram::MeasurementVectorType measurement( 1 );
  measurement[ 0 ] = intensity;

  // Get the index of measurement in 1D-histogram.
  Histogram::IndexType index;
  if( !histogram->GetIndex( measurement, index ) )
    throw itk::RangeError( __FILE__, __LINE__ );

  assert( Histogram::IndexType::GetIndexDimension()==1 );

  // Min/max intensities of bin.
  MeasurementType minI = histogram->GetBinMin( 0, index[ 0 ] );
  MeasurementType maxI = histogram->GetBinMax( 0, index[ 0 ] );

  // Min/max frequencies of
  Histogram::FrequencyType frequency( histogram->GetFrequency( index ) );

  // Initialize result.
  double percent = frequency * ( intensity - minI ) / ( maxI - minI );

  // Number of bins of histogram.
  Histogram::SizeType::SizeValueType binCount = histogram->Size();

  // Initialize bound indices.
  assert( index[ 0 ]>=0 );
  Histogram::SizeType::SizeValueType index0 = index[ 0 ];
  Histogram::SizeType::SizeValueType i0 = 0;
  Histogram::SizeType::SizeValueType iN = binCount;

  switch( bound )
    {
    case BOUND_LOWER:
      i0 = 0;
      iN = index[ 0 ];
      break;

    case BOUND_UPPER:
      i0 = index0 < binCount ? index0 + 1 : binCount;
      iN = binCount;
      break;

    default:
      assert( false && "Implement case statement of switch instruction." );
      break;
    };

  // Traverse lower/upper bound.
  Histogram::SizeType::SizeValueType i;

  for( i=i0; i<iN; ++i )
    percent += histogram->GetFrequency( i, 0 );

  // Calculate frequency rate.
  percent /= histogram->GetTotalFrequency();

  // Return frequency rate.
  return percent;
}

/*******************************************************************************/
void
HistogramModel
::virtual_BuildModel( void* context )
{
  // template_BuildModel_I< VectorImageModel::SourceImageType >();
  template_BuildModel_M< VectorImageModel >();

  // template_BuildModel< otb::Image< FixedArray< double, 4 >, 2 > >();
  // template_BuildModel< otb::Image< itk::FixedArray< float, 4 >, 2 > >();

  /*
  template_BuildModel< otb::VectorImage< float, 2 > >();
  template_BuildModel< otb::Image< float, 2 > >();
  */
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/

/*******************************************************************************/

} // end namespace 'mvd'
<commit_msg>BUG: avoid RangeError due to float/double conversion between histogram and widget<commit_after>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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 "mvdHistogramModel.h"

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdVectorImageModel.h"

namespace mvd
{
/*
  TRANSLATOR mvd::HistogramModel

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION                                              */

/*******************************************************************************/
HistogramModel
::HistogramModel( QObject* parent ) :
  AbstractModel( parent ),
  m_Histograms(),
  m_MinPixel(),
  m_MaxPixel()
{
}

/*******************************************************************************/
HistogramModel
::~HistogramModel()
{
}

/*******************************************************************************/
double
HistogramModel
::Percentile( CountType band, MeasurementType intensity, Bound bound ) const
{
  // Get histogram of band.
  Histogram::Pointer histogram( m_Histograms->GetNthElement( band ) );

  // Contruct 1D measurement vector.
  Histogram::MeasurementVectorType measurement( 1 );
  measurement[ 0 ] = intensity;

  // Due to float/double conversion, it can happen
  // that the minimum or maximum value go slightly outside the histogram
  // Clamping the value solves the issue and avoid RangeError
  measurement[0] =
    itk::NumericTraits<MeasurementType>::Clamp(
      measurement[0],
      histogram->GetBinMin(0, 0),
      histogram->GetBinMax(0, histogram->GetSize(0) - 1)
      );

  // Get the index of measurement in 1D-histogram.
  Histogram::IndexType index;
  if( !histogram->GetIndex( measurement, index ) )
    throw itk::RangeError( __FILE__, __LINE__ );

  assert( Histogram::IndexType::GetIndexDimension()==1 );

  // Min/max intensities of bin.
  MeasurementType minI = histogram->GetBinMin( 0, index[ 0 ] );
  MeasurementType maxI = histogram->GetBinMax( 0, index[ 0 ] );

  // Min/max frequencies of
  Histogram::FrequencyType frequency( histogram->GetFrequency( index ) );

  // Initialize result.
  double percent = frequency * ( intensity - minI ) / ( maxI - minI );

  // Number of bins of histogram.
  Histogram::SizeType::SizeValueType binCount = histogram->Size();

  // Initialize bound indices.
  assert( index[ 0 ]>=0 );
  Histogram::SizeType::SizeValueType index0 = index[ 0 ];
  Histogram::SizeType::SizeValueType i0 = 0;
  Histogram::SizeType::SizeValueType iN = binCount;

  switch( bound )
    {
    case BOUND_LOWER:
      i0 = 0;
      iN = index[ 0 ];
      break;

    case BOUND_UPPER:
      i0 = index0 < binCount ? index0 + 1 : binCount;
      iN = binCount;
      break;

    default:
      assert( false && "Implement case statement of switch instruction." );
      break;
    };

  // Traverse lower/upper bound.
  Histogram::SizeType::SizeValueType i;

  for( i=i0; i<iN; ++i )
    percent += histogram->GetFrequency( i, 0 );

  // Calculate frequency rate.
  percent /= histogram->GetTotalFrequency();

  // Return frequency rate.
  return percent;
}

/*******************************************************************************/
void
HistogramModel
::virtual_BuildModel( void* context )
{
  // template_BuildModel_I< VectorImageModel::SourceImageType >();
  template_BuildModel_M< VectorImageModel >();

  // template_BuildModel< otb::Image< FixedArray< double, 4 >, 2 > >();
  // template_BuildModel< otb::Image< itk::FixedArray< float, 4 >, 2 > >();

  /*
  template_BuildModel< otb::VectorImage< float, 2 > >();
  template_BuildModel< otb::Image< float, 2 > >();
  */
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/

/*******************************************************************************/

} // end namespace 'mvd'
<|endoftext|>


<commit_before>#include "sitkPixelIDValues.h"

namespace itk
{
namespace simple
{

  const std::string GetPixelIDValueAsString( PixelIDValueType type )
{

  if ( type == sitkUnknown )
    {
    // Unknow must be first because other enums may be -1 if they are
    // not instantiated
    return "Unknown pixel id";
    }
  else if ( type == sitkUInt8 )
    {
    return "8-bit unsigned integer";
    }
  else if ( type == sitkInt8 )
    {
    return "8-bit signed integer";
    }
  else if ( type ==  sitkUInt16 )
    {
    return "16-bit unsigned integer";
    }
  else if ( type == sitkInt16 )
    {
    return "16-bit signed integer";
    }
  else if ( type == sitkUInt32 )
    {
    return "32-bit unsigned integer";
    }
  else if ( type == sitkInt32 )
    {
    return "32-bit signed integer";
    }
  else if ( type == sitkUInt64 )
    {
    return "64-bit unsigned integer";
    }
  else if ( type == sitkInt64 )
    {
    return "64-bit signed integer";
    }
  else if ( type == sitkFloat32 )
    {
    return "32-bit float";
    }
  else if ( type == sitkFloat64 )
    {
    return "64-bit float";
    }
  else if ( type == sitkComplexFloat32 )
    {
    return "conplex of 32-bit float";
    }
  else if ( type == sitkComplexFloat64 )
    {
    return "complex of 64-bit float";
    }
  else if ( type == sitkVectorUInt8 )
    {
    return "vector of 8-bit unsigned integer";
    }
  else if ( type == sitkVectorInt8 )
    {
    return "vector of 8-bit signed integer";
    }
  else if ( type ==  sitkVectorUInt16 )
    {
    return "vector of 16-bit unsigned integer";
    }
  else if ( type == sitkVectorInt16 )
    {
    return "vector of 16-bit signed integer";
    }
  else if ( type == sitkVectorUInt32 )
    {
    return "vector of 32-bit unsigned integer";
    }
  else if ( type == sitkVectorInt32 )
    {
    return "vector of 32-bit signed integer";
    }
  else if ( type == sitkVectorUInt64 )
    {
    return "vector of 64-bit unsigned integer";
    }
  else if ( type == sitkVectorInt64 )
    {
    return "vector of 64-bit signed integer";
    }
  else if ( type == sitkVectorFloat32 )
    {
    return "vector of 32-bit float";
    }
  else if ( type == sitkVectorFloat64 )
    {
    return "vector of 64-bit float";
    }
  else if ( type == sitkLabelUInt8 )
    {
    return "label of 8-bit unsigned integer";
    }
  else if ( sitkLabelUInt16 )
    {
    return "label of 16-bit unsigned integer";
    }
  else if ( sitkLabelUInt32 )
    {
    return "label of 32-bit unsigned integer";
    }
  else if ( sitkLabelUInt64 )
    {
    return "label of 64-bit unsigned integer";
    }
  else
    {
    return "ERRONEOUS PIXEL ID!";
    }
}

}
}
<commit_msg>BUG: Fixed typo in sitkPixelIDValues.cxx<commit_after>#include "sitkPixelIDValues.h"

namespace itk
{
namespace simple
{

  const std::string GetPixelIDValueAsString( PixelIDValueType type )
{

  if ( type == sitkUnknown )
    {
    // Unknow must be first because other enums may be -1 if they are
    // not instantiated
    return "Unknown pixel id";
    }
  else if ( type == sitkUInt8 )
    {
    return "8-bit unsigned integer";
    }
  else if ( type == sitkInt8 )
    {
    return "8-bit signed integer";
    }
  else if ( type ==  sitkUInt16 )
    {
    return "16-bit unsigned integer";
    }
  else if ( type == sitkInt16 )
    {
    return "16-bit signed integer";
    }
  else if ( type == sitkUInt32 )
    {
    return "32-bit unsigned integer";
    }
  else if ( type == sitkInt32 )
    {
    return "32-bit signed integer";
    }
  else if ( type == sitkUInt64 )
    {
    return "64-bit unsigned integer";
    }
  else if ( type == sitkInt64 )
    {
    return "64-bit signed integer";
    }
  else if ( type == sitkFloat32 )
    {
    return "32-bit float";
    }
  else if ( type == sitkFloat64 )
    {
    return "64-bit float";
    }
  else if ( type == sitkComplexFloat32 )
    {
    return "complex of 32-bit float";
    }
  else if ( type == sitkComplexFloat64 )
    {
    return "complex of 64-bit float";
    }
  else if ( type == sitkVectorUInt8 )
    {
    return "vector of 8-bit unsigned integer";
    }
  else if ( type == sitkVectorInt8 )
    {
    return "vector of 8-bit signed integer";
    }
  else if ( type ==  sitkVectorUInt16 )
    {
    return "vector of 16-bit unsigned integer";
    }
  else if ( type == sitkVectorInt16 )
    {
    return "vector of 16-bit signed integer";
    }
  else if ( type == sitkVectorUInt32 )
    {
    return "vector of 32-bit unsigned integer";
    }
  else if ( type == sitkVectorInt32 )
    {
    return "vector of 32-bit signed integer";
    }
  else if ( type == sitkVectorUInt64 )
    {
    return "vector of 64-bit unsigned integer";
    }
  else if ( type == sitkVectorInt64 )
    {
    return "vector of 64-bit signed integer";
    }
  else if ( type == sitkVectorFloat32 )
    {
    return "vector of 32-bit float";
    }
  else if ( type == sitkVectorFloat64 )
    {
    return "vector of 64-bit float";
    }
  else if ( type == sitkLabelUInt8 )
    {
    return "label of 8-bit unsigned integer";
    }
  else if ( sitkLabelUInt16 )
    {
    return "label of 16-bit unsigned integer";
    }
  else if ( sitkLabelUInt32 )
    {
    return "label of 32-bit unsigned integer";
    }
  else if ( sitkLabelUInt64 )
    {
    return "label of 64-bit unsigned integer";
    }
  else
    {
    return "ERRONEOUS PIXEL ID!";
    }
}

}
}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkTxtTransformIO.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

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

#include "itkTxtTransformIO.h"
#include <itksys/SystemTools.hxx>
#include <vnl/vnl_matlab_read.h>
#include <vnl/vnl_matlab_write.h>

namespace itk
{
TxtTransformIO::
TxtTransformIO()
{
}

TxtTransformIO::
~TxtTransformIO()
{
}

bool
TxtTransformIO::
CanReadFile(const char *fileName)
{
  bool recognizedExtension = false;
  recognizedExtension |= (itksys::SystemTools::GetFilenameLastExtension(fileName) == ".txt");
  recognizedExtension |= (itksys::SystemTools::GetFilenameLastExtension(fileName) == ".tfm");
  return recognizedExtension;
}

bool
TxtTransformIO::
CanWriteFile(const char *fileName)
{
  bool recognizedExtension = false;
  recognizedExtension |= (itksys::SystemTools::GetFilenameLastExtension(fileName) == ".txt");
  recognizedExtension |= (itksys::SystemTools::GetFilenameLastExtension(fileName) == ".tfm");
  return recognizedExtension;
}

std::string
TxtTransformIO::
trim(std::string const& source, char const* delims)
{
  std::string result(source);
  std::string::size_type index = result.find_last_not_of(delims);
  if(index != std::string::npos)
    {
    result.erase(++index);
    }

  index = result.find_first_not_of(delims);
  if(index != std::string::npos)
    {
    result.erase(0, index);
    }
  else
    {
    result.erase();
    }
  return result;
}

void
TxtTransformIO::
Read()
{
  TransformPointer transform;
  std::ifstream in;
  in.open ( this->GetFileName(), std::ios::in | std::ios::binary );
  if( in.fail() )
    {
    in.close();
    itkExceptionMacro ( "The file could not be opened for read access "
                        << std::endl << "Filename: \"" << this->GetFileName() << "\"" );
    }

  OStringStream InData;

  // in.get ( InData );
  std::filebuf *pbuf;
  pbuf=in.rdbuf();

  // get file size using buffer's members
  int size=pbuf->pubseekoff (0,std::ios::end,std::ios::in);
  pbuf->pubseekpos (0,std::ios::in);

  // allocate memory to contain file data
  char* buffer=new char[size+1];

  // get file data
  pbuf->sgetn (buffer,size);
  buffer[size]='\0';
  itkDebugMacro ( "Read file transform Data" );
  InData << buffer;

  delete[] buffer;
  std::string data = InData.str();
  in.close();

  // Read line by line
  vnl_vector<double> VectorBuffer;
  std::string::size_type position = 0;

  Array<double> TmpParameterArray;
  Array<double> TmpFixedParameterArray;
  TmpParameterArray.clear();
  TmpFixedParameterArray.clear();
  bool haveFixedParameters = false;
  bool haveParameters = false;

  while ( position < data.size() )
    {
    // Find the next string
    std::string::size_type end = data.find ( "\n", position );
    std::string line = trim ( data.substr ( position, end - position ) );
    position = end+1;
    itkDebugMacro ("Found line: \"" << line << "\"" );

    if ( line.length() == 0 )
      {
      continue;
      }
    if (line[0] == '#' || std::string::npos == line.find_first_not_of (" \t"))
      {
      // Skip lines beginning with #, or blank lines
      continue;
      }

    // Get the name
    end = line.find ( ":" );
    if ( end == std::string::npos )
      {
      // Throw an error
      itkExceptionMacro ( "Tags must be delimited by :" );
      }
    std::string Name = trim ( line.substr ( 0, end ) );
    std::string Value = trim ( line.substr ( end + 1, line.length() ) );
    // Push back
    itkDebugMacro ( "Name: \"" << Name << "\"" );
    itkDebugMacro ( "Value: \"" << Value << "\"" );
    itksys_ios::istringstream parse ( Value );
    VectorBuffer.clear();
    if ( Name == "Transform" )
      {
      this->CreateTransform(transform,Value);
      this->GetReadTransformList().push_back ( transform );
      }
    else if ( Name == "Parameters" || Name == "FixedParameters" )
      {
      VectorBuffer.clear();

      // Read them
      parse >> VectorBuffer;
      itkDebugMacro ( "Parsed: " << VectorBuffer );
      if ( Name == "Parameters" )
        {
        TmpParameterArray = VectorBuffer;
        itkDebugMacro ( "Setting Parameters: " << TmpParameterArray );
        if ( haveFixedParameters )
          {
          transform->SetFixedParameters ( TmpFixedParameterArray );
          itkDebugMacro ( "Set Transform Fixed Parameters" );
          transform->SetParametersByValue ( TmpParameterArray );
          itkDebugMacro ( "Set Transform Parameters" );
          TmpParameterArray.clear();
          TmpFixedParameterArray.clear();
          haveFixedParameters = false;
          haveParameters = false;
          }
        else
          {
          haveParameters = true;
          }
        }
      else if ( Name == "FixedParameters" )
        {
        TmpFixedParameterArray = VectorBuffer;
        itkDebugMacro ( "Setting Fixed Parameters: " << TmpFixedParameterArray );
        if ( !transform )
          {
          itkExceptionMacro ("Please set the transform before parameters"
                             "or fixed parameters" );
          }
        if ( haveParameters )
          {
          transform->SetFixedParameters ( TmpFixedParameterArray );
          itkDebugMacro ( "Set Transform Fixed Parameters" );
          transform->SetParametersByValue ( TmpParameterArray );
          itkDebugMacro ( "Set Transform Parameters" );
          TmpParameterArray.clear();
          TmpFixedParameterArray.clear();
          haveFixedParameters = false;
          haveParameters = false;
          }
        else
          {
          haveFixedParameters = true;
          }
        }
      }
    }
}

void
TxtTransformIO::
Write()
{
  ConstTransformListType::iterator it = this->GetWriteTransformList().begin();
  vnl_vector<double> TempArray;
  std::ofstream out;
  this->OpenStream(out,false);

  out << "#Insight Transform File V1.0" << std::endl;
  int count = 0;
  while(it != this->GetWriteTransformList().end())
    {
    out << "# Transform " << count << std::endl;
    out << "Transform: " << (*it)->GetTransformTypeAsString() << std::endl;

    TempArray = (*it)->GetParameters();
    out << "Parameters: " << TempArray << std::endl;
    TempArray = (*it)->GetFixedParameters();
    out << "FixedParameters: " << TempArray << std::endl;
    it++;
    count++;
    }
  out.close();
}

}
<commit_msg>BUG: deal with Mac line end conventions in TXT transforms<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkTxtTransformIO.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

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

#include "itkTxtTransformIO.h"
#include <itksys/SystemTools.hxx>
#include <vnl/vnl_matlab_read.h>
#include <vnl/vnl_matlab_write.h>

namespace itk
{
TxtTransformIO::
TxtTransformIO()
{
}

TxtTransformIO::
~TxtTransformIO()
{
}

bool
TxtTransformIO::
CanReadFile(const char *fileName)
{
  bool recognizedExtension = false;
  recognizedExtension |= (itksys::SystemTools::GetFilenameLastExtension(fileName) == ".txt");
  recognizedExtension |= (itksys::SystemTools::GetFilenameLastExtension(fileName) == ".tfm");
  return recognizedExtension;
}

bool
TxtTransformIO::
CanWriteFile(const char *fileName)
{
  bool recognizedExtension = false;
  recognizedExtension |= (itksys::SystemTools::GetFilenameLastExtension(fileName) == ".txt");
  recognizedExtension |= (itksys::SystemTools::GetFilenameLastExtension(fileName) == ".tfm");
  return recognizedExtension;
}

std::string
TxtTransformIO::
trim(std::string const& source, char const* delims)
{
  std::string result(source);
  std::string::size_type index = result.find_last_not_of(delims);
  if(index != std::string::npos)
    {
    result.erase(++index);
    }

  index = result.find_first_not_of(delims);
  if(index != std::string::npos)
    {
    result.erase(0, index);
    }
  else
    {
    result.erase();
    }
  return result;
}

void
TxtTransformIO::
Read()
{
  TransformPointer transform;
  std::ifstream in;
  in.open ( this->GetFileName(), std::ios::in | std::ios::binary );
  if( in.fail() )
    {
    in.close();
    itkExceptionMacro ( "The file could not be opened for read access "
                        << std::endl << "Filename: \"" << this->GetFileName() << "\"" );
    }

  OStringStream InData;

  // in.get ( InData );
  std::filebuf *pbuf;
  pbuf=in.rdbuf();

  // get file size using buffer's members
  int size=pbuf->pubseekoff (0,std::ios::end,std::ios::in);
  pbuf->pubseekpos (0,std::ios::in);

  // allocate memory to contain file data
  char* buffer=new char[size+1];

  // get file data
  pbuf->sgetn (buffer,size);
  buffer[size]='\0';
  itkDebugMacro ( "Read file transform Data" );
  InData << buffer;

  delete[] buffer;
  std::string data = InData.str();
  in.close();

  // Read line by line
  vnl_vector<double> VectorBuffer;
  std::string::size_type position = 0;

  Array<double> TmpParameterArray;
  Array<double> TmpFixedParameterArray;
  TmpParameterArray.clear();
  TmpFixedParameterArray.clear();
  bool haveFixedParameters = false;
  bool haveParameters = false;
  //
  // check for line end convention
  std::string line_end("\n");
  if(data.find('\n') == std::string::npos)
    {
    if(data.find('\r') == std::string::npos)
      {
      itkExceptionMacro ( "No line ending character found, not a valid ITK Transform TXT file" );
      }
    line_end = "\r";
    }
  while ( position < data.size() )
    {
    // Find the next string
    std::string::size_type end = data.find ( line_end, position );
    std::string line = trim ( data.substr ( position, end - position ) );
    position = end+1;
    itkDebugMacro ("Found line: \"" << line << "\"" );

    if ( line.length() == 0 )
      {
      continue;
      }
    if (line[0] == '#' || std::string::npos == line.find_first_not_of (" \t"))
      {
      // Skip lines beginning with #, or blank lines
      continue;
      }

    // Get the name
    end = line.find ( ":" );
    if ( end == std::string::npos )
      {
      // Throw an error
      itkExceptionMacro ( "Tags must be delimited by :" );
      }
    std::string Name = trim ( line.substr ( 0, end ) );
    std::string Value = trim ( line.substr ( end + 1, line.length() ) );
    // Push back
    itkDebugMacro ( "Name: \"" << Name << "\"" );
    itkDebugMacro ( "Value: \"" << Value << "\"" );
    itksys_ios::istringstream parse ( Value );
    VectorBuffer.clear();
    if ( Name == "Transform" )
      {
      this->CreateTransform(transform,Value);
      this->GetReadTransformList().push_back ( transform );
      }
    else if ( Name == "Parameters" || Name == "FixedParameters" )
      {
      VectorBuffer.clear();

      // Read them
      parse >> VectorBuffer;
      itkDebugMacro ( "Parsed: " << VectorBuffer );
      if ( Name == "Parameters" )
        {
        TmpParameterArray = VectorBuffer;
        itkDebugMacro ( "Setting Parameters: " << TmpParameterArray );
        if ( haveFixedParameters )
          {
          transform->SetFixedParameters ( TmpFixedParameterArray );
          itkDebugMacro ( "Set Transform Fixed Parameters" );
          transform->SetParametersByValue ( TmpParameterArray );
          itkDebugMacro ( "Set Transform Parameters" );
          TmpParameterArray.clear();
          TmpFixedParameterArray.clear();
          haveFixedParameters = false;
          haveParameters = false;
          }
        else
          {
          haveParameters = true;
          }
        }
      else if ( Name == "FixedParameters" )
        {
        TmpFixedParameterArray = VectorBuffer;
        itkDebugMacro ( "Setting Fixed Parameters: " << TmpFixedParameterArray );
        if ( !transform )
          {
          itkExceptionMacro ("Please set the transform before parameters"
                             "or fixed parameters" );
          }
        if ( haveParameters )
          {
          transform->SetFixedParameters ( TmpFixedParameterArray );
          itkDebugMacro ( "Set Transform Fixed Parameters" );
          transform->SetParametersByValue ( TmpParameterArray );
          itkDebugMacro ( "Set Transform Parameters" );
          TmpParameterArray.clear();
          TmpFixedParameterArray.clear();
          haveFixedParameters = false;
          haveParameters = false;
          }
        else
          {
          haveFixedParameters = true;
          }
        }
      }
    }
}

void
TxtTransformIO::
Write()
{
  ConstTransformListType::iterator it = this->GetWriteTransformList().begin();
  vnl_vector<double> TempArray;
  std::ofstream out;
  this->OpenStream(out,false);

  out << "#Insight Transform File V1.0" << std::endl;
  int count = 0;
  while(it != this->GetWriteTransformList().end())
    {
    out << "# Transform " << count << std::endl;
    out << "Transform: " << (*it)->GetTransformTypeAsString() << std::endl;

    TempArray = (*it)->GetParameters();
    out << "Parameters: " << TempArray << std::endl;
    TempArray = (*it)->GetFixedParameters();
    out << "FixedParameters: " << TempArray << std::endl;
    it++;
    count++;
    }
  out.close();
}

}
<|endoftext|>


<commit_before>#include <cctag/visualDebug.hpp>
#include <cctag/fileDebug.hpp>

#include <boost/filesystem.hpp>
#include <opencv2/opencv.hpp>

namespace bfs = boost::filesystem;

namespace cctag
{

CCTagVisualDebug::CCTagVisualDebug()
{
}

CCTagVisualDebug::~CCTagVisualDebug()
{
}

void CCTagVisualDebug::initializeFolders(const boost::filesystem::path & rootPath, std::size_t nCrowns)
{
#ifdef CCTAG_SERIALIZE
  // Create inputImagePath/result if it does not exist
  std::stringstream resultFolderName, localizationFolderName, identificationFolderName;
  resultFolderName << rootPath.string() << "/cctag" << nCrowns << "CC";
  localizationFolderName << resultFolderName.str() << "/localization";
  identificationFolderName << resultFolderName.str() << "/identification";

  if (!bfs::exists(resultFolderName.str())) {
      bfs::create_directory(resultFolderName.str());
  }

  if (!bfs::exists(localizationFolderName.str())) {
      bfs::create_directory(localizationFolderName.str());
  }

  if (!bfs::exists(identificationFolderName.str())) {
      bfs::create_directory(identificationFolderName.str());
  }

  _pathRoot = resultFolderName.str();
  CCTAG_COUT_VAR(_pathRoot);
#endif
}

void CCTagVisualDebug::setPyramidLevel(int level) {
#ifdef CCTAG_SERIALIZE
  _pyramidLevel = level;
#endif
}

int CCTagVisualDebug::getPyramidLevel() {
    return _pyramidLevel;
}

std::string CCTagVisualDebug::getPath() const {
  return _path;
}

void CCTagVisualDebug::setImageFileName(const std::string& imageFileName) {
#ifdef CCTAG_SERIALIZE
  _imageFileName = imageFileName;
    CCTAG_COUT_VAR(_imageFileName);
  _path = _pathRoot + "/" + imageFileName;
  CCTAG_COUT_VAR(_path);
  if (!bfs::exists(_path)) {
    bfs::create_directory(_path);
    CCTAG_COUT("creation done");
  }
  CCTAG_COUT("exit");
#endif
}

void CCTagVisualDebug::initBackgroundImage(const cv::Mat & back)
{
#ifdef CCTAG_SERIALIZE
  cv::Mat temp; // todo@Lilian: why do I need to use temp ?
  cvtColor(back, temp, cv::COLOR_GRAY2RGB);
  _backImage = temp.clone();
#endif
}

void CCTagVisualDebug::newSession(const std::string & sessionName) {
#ifdef CCTAG_SERIALIZE
  // Don't erase old sessions
  if (_sessions.find(sessionName) == _sessions.end()) {
      _sessions[sessionName] = _backImage;
  }
#endif
}

void CCTagVisualDebug::drawText(const cctag::Point2dN<double> & p, const std::string & text, const cctag::Color & color) {
#ifdef CCTAG_SERIALIZE
  CvFont font1;
  cvInitFont(&font1, CV_FONT_HERSHEY_SIMPLEX, 0.8, 0.8, 0, 2);

  IplImage iplBack = _backImage;
  cvPutText( &iplBack, text.c_str(),
          cvPoint((int) p.x(), (int) p.y()),
          &font1, CV_RGB(color[0] * 255, color[1] * 255, color[2] * 255));
#endif
}

void CCTagVisualDebug::drawPoint(const cctag::Point2dN<double> & p, const cctag::Color & color) {
#ifdef CCTAG_SERIALIZE
  if (p.x() >= 1 && p.x() < _backImage.cols-1 &&
          p.y() >= 1 && p.y() < _backImage.rows-1)
  {
    cv::rectangle(_backImage, cvPoint(p.x()-1.0,p.y()-1.0), cvPoint(p.x()+1.0,p.y()+1.0), cv::Scalar(color[0], color[1], color[2]));
  }
#endif
}

void CCTagVisualDebug::drawPoints(const std::vector<cctag::Point2dN<double> > & pts, const cctag::Color & color)
{
#ifdef CCTAG_SERIALIZE
  BOOST_FOREACH(const cctag::Point2dN<double> & p, pts) {
      CCTagVisualDebug::instance().drawPoint(p, cctag::color_red);
  }
#endif
}

void CCTagVisualDebug::drawMarker(const cctag::CCTag& marker, bool drawScaledMarker)
{
#ifdef CCTAG_SERIALIZE
  numerical::geometry::Ellipse rescaledOuterEllipse;
  if (drawScaledMarker) {
      rescaledOuterEllipse = marker.rescaledOuterEllipse();
  } else {
      rescaledOuterEllipse = marker.outerEllipse();
  }
  Point2dN<double> & center = rescaledOuterEllipse.center();

  // Display ellipses
  if (drawScaledMarker) {
      rescaledOuterEllipse = marker.rescaledOuterEllipse();
  } else {
      rescaledOuterEllipse = marker.outerEllipse();
  }

  cv::Scalar color;
  // Set the color
  if (marker.getStatus() == status::no_collected_cuts) {
    // Magenta
    color = cv::Scalar(255,0,255);
  }else if (marker.getStatus() == status::no_selected_cuts) {
    // Cyan
    color = cv::Scalar(0,255,255);
  }else if(marker.getStatus() == status::opti_has_diverged){
    // Red
    color = cv::Scalar(255,0,0);
  }else if(marker.getStatus() == status::id_not_reliable){
    // Cyan
    color = cv::Scalar(0,255,255);
  }else if(marker.getStatus() == status::id_reliable){
    // Green
    color = cv::Scalar(0,255,0);
  }else if(marker.getStatus() == 0 ){
    // Green
    color = cv::Scalar(0,255,0);
  }

  //CCTAT_COUT_VAR(color);

  cv::ellipse(_backImage , cv::Point(center.x(),center.y()),
      cv::Size(rescaledOuterEllipse.a(), rescaledOuterEllipse.b()),
      rescaledOuterEllipse.angle()*180/M_PI, 0, 360, color);
#endif
}

void CCTagVisualDebug::drawInfos(const cctag::CCTag& marker, bool drawScaledMarker)
{
#ifdef CCTAG_SERIALIZE
    CvFont font1;
  cvInitFont(&font1, CV_FONT_HERSHEY_SIMPLEX, 0.8, 0.8, 0, 2);

  std::string sId = boost::lexical_cast<std::string>(marker.id() + 1);

  int x, y;
  if (drawScaledMarker) {
      x = int (marker.rescaledOuterEllipse().center().x());
      y = int (marker.rescaledOuterEllipse().center().y());
  } else {
      x = int (marker.outerEllipse().center().x());
      y = int (marker.outerEllipse().center().y());
  }

  IplImage iplImg = _backImage;
  cvPutText( &iplImg, sId.c_str(),
          cvPoint(x, y),
          &font1, CV_RGB(128, 255, 0));
#endif
}

std::string CCTagVisualDebug::getImageFileName() const {
    return _imageFileName;
}

void CCTagVisualDebug::out(const std::string & filename) const {
#ifdef CCTAG_SERIALIZE
  cv::imwrite(filename, _backImage);
#endif
}

void CCTagVisualDebug::outPutAllSessions() const {
#ifdef CCTAG_SERIALIZE
    BOOST_FOREACH(const Sessions::const_iterator::value_type & v, _sessions) {
        const std::string filename = _path + "/" + v.first + ".png";
        cv::imwrite(filename, v.second);
    }
#endif
}

void CCTagVisualDebug::writeLocalizationView(cctag::CCTag::List& markers) const {
#ifdef CCTAG_SERIALIZE
    std::stringstream localizationResultFileName;
    localizationResultFileName << "../localization/" << _imageFileName;
    CCTagVisualDebug::instance().newSession(localizationResultFileName.str());

    BOOST_FOREACH(const cctag::CCTag & marker, markers) {
        CCTagVisualDebug::instance().drawMarker(marker);
        CCTagVisualDebug::instance().drawInfos(marker);
    }
#endif
}

void CCTagVisualDebug::writeIdentificationView(cctag::CCTag::List& markers) const {
#ifdef CCTAG_SERIALIZE

    std::stringstream identificationResultFileName;
    identificationResultFileName << "../identification/" << _imageFileName;
    CCTagVisualDebug::instance().newSession(identificationResultFileName.str());

    BOOST_FOREACH(const cctag::CCTag & marker, markers) {
        CCTagVisualDebug::instance().drawMarker(marker);
        CCTagVisualDebug::instance().drawPoints(marker.rescaledOuterEllipsePoints(), cctag::color_red);
        CCTagVisualDebug::instance().drawInfos(marker);
    }

#endif
}

void CCTagVisualDebug::clearSessions() {
#ifdef CCTAG_SERIALIZE
    _sessions.erase(_sessions.begin(), _sessions.end());
#endif
}

} // namespace cctag
<commit_msg>Visual debug: fix opencv color<commit_after>#include <cctag/visualDebug.hpp>
#include <cctag/fileDebug.hpp>

#include <boost/filesystem.hpp>
#include <opencv2/opencv.hpp>

namespace bfs = boost::filesystem;

namespace cctag
{

CCTagVisualDebug::CCTagVisualDebug()
{
}

CCTagVisualDebug::~CCTagVisualDebug()
{
}

void CCTagVisualDebug::initializeFolders(const boost::filesystem::path & rootPath, std::size_t nCrowns)
{
#ifdef CCTAG_SERIALIZE
  // Create inputImagePath/result if it does not exist
  std::stringstream resultFolderName, localizationFolderName, identificationFolderName;
  resultFolderName << rootPath.string() << "/cctag" << nCrowns << "CC";
  localizationFolderName << resultFolderName.str() << "/localization";
  identificationFolderName << resultFolderName.str() << "/identification";

  if (!bfs::exists(resultFolderName.str())) {
      bfs::create_directory(resultFolderName.str());
  }

  if (!bfs::exists(localizationFolderName.str())) {
      bfs::create_directory(localizationFolderName.str());
  }

  if (!bfs::exists(identificationFolderName.str())) {
      bfs::create_directory(identificationFolderName.str());
  }

  _pathRoot = resultFolderName.str();
  CCTAG_COUT_VAR(_pathRoot);
#endif
}

void CCTagVisualDebug::setPyramidLevel(int level) {
#ifdef CCTAG_SERIALIZE
  _pyramidLevel = level;
#endif
}

int CCTagVisualDebug::getPyramidLevel() {
    return _pyramidLevel;
}

std::string CCTagVisualDebug::getPath() const {
  return _path;
}

void CCTagVisualDebug::setImageFileName(const std::string& imageFileName) {
#ifdef CCTAG_SERIALIZE
  _imageFileName = imageFileName;
    CCTAG_COUT_VAR(_imageFileName);
  _path = _pathRoot + "/" + imageFileName;
  CCTAG_COUT_VAR(_path);
  if (!bfs::exists(_path)) {
    bfs::create_directory(_path);
    CCTAG_COUT("creation done");
  }
  CCTAG_COUT("exit");
#endif
}

void CCTagVisualDebug::initBackgroundImage(const cv::Mat & back)
{
#ifdef CCTAG_SERIALIZE
  cv::Mat temp; // todo@Lilian: why do I need to use temp ?
  cvtColor(back, temp, cv::COLOR_GRAY2RGB);
  _backImage = temp.clone();
#endif
}

void CCTagVisualDebug::newSession(const std::string & sessionName) {
#ifdef CCTAG_SERIALIZE
  // Don't erase old sessions
  if (_sessions.find(sessionName) == _sessions.end()) {
      _sessions[sessionName] = _backImage;
  }
#endif
}

void CCTagVisualDebug::drawText(const cctag::Point2dN<double> & p, const std::string & text, const cctag::Color & color) {
#ifdef CCTAG_SERIALIZE
  CvFont font1;
  cvInitFont(&font1, CV_FONT_HERSHEY_SIMPLEX, 0.8, 0.8, 0, 2);

  IplImage iplBack = _backImage;
  cvPutText( &iplBack, text.c_str(),
          cvPoint((int) p.x(), (int) p.y()),
          &font1, CV_RGB(color[0] * 255, color[1] * 255, color[2] * 255));
#endif
}

void CCTagVisualDebug::drawPoint(const cctag::Point2dN<double> & p, const cctag::Color & color) {
#ifdef CCTAG_SERIALIZE
  if (p.x() >= 1 && p.x() < _backImage.cols-1 &&
          p.y() >= 1 && p.y() < _backImage.rows-1)
  {
    cv::rectangle(_backImage, cvPoint(p.x()-1.0,p.y()-1.0), cvPoint(p.x()+1.0,p.y()+1.0), cv::Scalar(255*color[0], 255*color[1], 255*color[2]),0);
  }
#endif
}

void CCTagVisualDebug::drawPoints(const std::vector<cctag::Point2dN<double> > & pts, const cctag::Color & color)
{
#ifdef CCTAG_SERIALIZE
  BOOST_FOREACH(const cctag::Point2dN<double> & p, pts) {
      CCTagVisualDebug::instance().drawPoint(p, cctag::color_red);
  }
#endif
}

void CCTagVisualDebug::drawMarker(const cctag::CCTag& marker, bool drawScaledMarker)
{
#ifdef CCTAG_SERIALIZE
  numerical::geometry::Ellipse rescaledOuterEllipse;
  if (drawScaledMarker) {
      rescaledOuterEllipse = marker.rescaledOuterEllipse();
  } else {
      rescaledOuterEllipse = marker.outerEllipse();
  }
  Point2dN<double> & center = rescaledOuterEllipse.center();

  // Display ellipses
  if (drawScaledMarker) {
      rescaledOuterEllipse = marker.rescaledOuterEllipse();
  } else {
      rescaledOuterEllipse = marker.outerEllipse();
  }

  cv::Scalar color;
  // Set the color
  if (marker.getStatus() == status::no_collected_cuts) {
    // Magenta
    color = cv::Scalar(255,0,255);
  }else if (marker.getStatus() == status::no_selected_cuts) {
    // Cyan
    color = cv::Scalar(0,255,255);
  }else if(marker.getStatus() == status::opti_has_diverged){
    // Red
    color = cv::Scalar(255,0,0);
  }else if(marker.getStatus() == status::id_not_reliable){
    // Cyan
    color = cv::Scalar(0,255,255);
  }else if(marker.getStatus() == status::id_reliable){
    // Green
    color = cv::Scalar(0,255,0);
  }else if(marker.getStatus() == 0 ){
    // Green
    color = cv::Scalar(0,255,0);
  }

  //CCTAT_COUT_VAR(color);

  cv::ellipse(_backImage , cv::Point(center.x(),center.y()),
      cv::Size(rescaledOuterEllipse.a(), rescaledOuterEllipse.b()),
      rescaledOuterEllipse.angle()*180/M_PI, 0, 360, color);
#endif
}

void CCTagVisualDebug::drawInfos(const cctag::CCTag& marker, bool drawScaledMarker)
{
#ifdef CCTAG_SERIALIZE
    CvFont font1;
  cvInitFont(&font1, CV_FONT_HERSHEY_SIMPLEX, 0.8, 0.8, 0, 2);

  std::string sId = boost::lexical_cast<std::string>(marker.id() + 1);

  int x, y;
  if (drawScaledMarker) {
      x = int (marker.rescaledOuterEllipse().center().x());
      y = int (marker.rescaledOuterEllipse().center().y());
  } else {
      x = int (marker.outerEllipse().center().x());
      y = int (marker.outerEllipse().center().y());
  }

  IplImage iplImg = _backImage;
  cvPutText( &iplImg, sId.c_str(),
          cvPoint(x, y),
          &font1, CV_RGB(128, 255, 0));
#endif
}

std::string CCTagVisualDebug::getImageFileName() const {
    return _imageFileName;
}

void CCTagVisualDebug::out(const std::string & filename) const {
#ifdef CCTAG_SERIALIZE
  cv::imwrite(filename, _backImage);
#endif
}

void CCTagVisualDebug::outPutAllSessions() const {
#ifdef CCTAG_SERIALIZE
    BOOST_FOREACH(const Sessions::const_iterator::value_type & v, _sessions) {
        const std::string filename = _path + "/" + v.first + ".png";
        cv::imwrite(filename, v.second);
    }
#endif
}

void CCTagVisualDebug::writeLocalizationView(cctag::CCTag::List& markers) const {
#ifdef CCTAG_SERIALIZE
    std::stringstream localizationResultFileName;
    localizationResultFileName << "../localization/" << _imageFileName;
    CCTagVisualDebug::instance().newSession(localizationResultFileName.str());

    BOOST_FOREACH(const cctag::CCTag & marker, markers) {
        CCTagVisualDebug::instance().drawMarker(marker);
        CCTagVisualDebug::instance().drawInfos(marker);
    }
#endif
}

void CCTagVisualDebug::writeIdentificationView(cctag::CCTag::List& markers) const {
#ifdef CCTAG_SERIALIZE

    std::stringstream identificationResultFileName;
    identificationResultFileName << "../identification/" << _imageFileName;
    CCTagVisualDebug::instance().newSession(identificationResultFileName.str());

    BOOST_FOREACH(const cctag::CCTag & marker, markers) {
        CCTagVisualDebug::instance().drawMarker(marker);
        CCTagVisualDebug::instance().drawPoints(marker.rescaledOuterEllipsePoints(), cctag::color_red);
        CCTagVisualDebug::instance().drawInfos(marker);
    }

#endif
}

void CCTagVisualDebug::clearSessions() {
#ifdef CCTAG_SERIALIZE
    _sessions.erase(_sessions.begin(), _sessions.end());
#endif
}

} // namespace cctag
<|endoftext|>


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

/**
 * @file mixer_group.cpp
 *
 * Mixer collection.
 */

#include <nuttx/config.h>

#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <errno.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>

#include "mixer.h"

#define debug(fmt, args...)	do { } while(0)
//#define debug(fmt, args...)	do { printf("[mixer] " fmt "\n", ##args); } while(0)

MixerGroup::MixerGroup(ControlCallback control_cb, uintptr_t cb_handle) :
	Mixer(control_cb, cb_handle),
	_first(nullptr)
{
}

MixerGroup::~MixerGroup()
{
	reset();
}

void
MixerGroup::add_mixer(Mixer *mixer)
{
	Mixer **mpp;

	mpp = &_first;

	while (*mpp != nullptr)
		mpp = &((*mpp)->_next);

	*mpp = mixer;
	mixer->_next = nullptr;
}

void
MixerGroup::reset()
{
	Mixer *mixer;

	/* discard sub-mixers */
	while (_first != nullptr) {
		mixer = _first;
		_first = mixer->_next;
		delete mixer;
	}
}

unsigned
MixerGroup::mix(float *outputs, unsigned space)
{
	Mixer	*mixer = _first;
	unsigned index = 0;

	while ((mixer != nullptr) && (index < space)) {
		index += mixer->mix(outputs + index, space - index);
		mixer = mixer->_next;
	}

	return index;
}

void
MixerGroup::groups_required(uint32_t &groups)
{
	Mixer	*mixer = _first;

	while (mixer != nullptr) {
		mixer->groups_required(groups);
		mixer = mixer->_next;
	}
}

int
MixerGroup::load_from_buf(const char *buf, unsigned &buflen)
{
	int ret = -1;
	const char *end = buf + buflen;

	/* loop until we have consumed the buffer */
	while (buflen > 0) {
		Mixer *m = nullptr;
		const char *p = end - buflen;

		/* use the next character as a hint to decide which mixer class to construct */
		switch (*p) {
		case 'Z':
			m = NullMixer::from_text(p, buflen);
			break;

		case 'M':
			m = SimpleMixer::from_text(_control_cb, _cb_handle, p, buflen);
			break;

		case 'R':
			m = MultirotorMixer::from_text(_control_cb, _cb_handle, p, buflen);
			break;

		default:
			/* it's probably junk or whitespace */
			break;
		}

		if (m != nullptr) {
			add_mixer(m);
			ret = 0;

		} else {
			/* skip whitespace or junk in the buffer */
			buflen--;
		}
	}

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

/**
 * @file mixer_group.cpp
 *
 * Mixer collection.
 */

#include <nuttx/config.h>

#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#include <errno.h>
#include <stdio.h>
#include <math.h>
#include <unistd.h>

#include "mixer.h"

#define debug(fmt, args...)	do { } while(0)
//#define debug(fmt, args...)	do { printf("[mixer] " fmt "\n", ##args); } while(0)

MixerGroup::MixerGroup(ControlCallback control_cb, uintptr_t cb_handle) :
	Mixer(control_cb, cb_handle),
	_first(nullptr)
{
}

MixerGroup::~MixerGroup()
{
	reset();
}

void
MixerGroup::add_mixer(Mixer *mixer)
{
	Mixer **mpp;

	mpp = &_first;

	while (*mpp != nullptr)
		mpp = &((*mpp)->_next);

	*mpp = mixer;
	mixer->_next = nullptr;
}

void
MixerGroup::reset()
{
	Mixer *mixer;

	/* discard sub-mixers */
	while (_first != nullptr) {
		mixer = _first;
		_first = mixer->_next;
		delete mixer;
	}
}

unsigned
MixerGroup::mix(float *outputs, unsigned space)
{
	Mixer	*mixer = _first;
	unsigned index = 0;

	while ((mixer != nullptr) && (index < space)) {
		index += mixer->mix(outputs + index, space - index);
		mixer = mixer->_next;
	}

	return index;
}

void
MixerGroup::groups_required(uint32_t &groups)
{
	Mixer	*mixer = _first;

	while (mixer != nullptr) {
		mixer->groups_required(groups);
		mixer = mixer->_next;
	}
}

int
MixerGroup::load_from_buf(const char *buf, unsigned &buflen)
{
	int ret = -1;
	const char *end = buf + buflen;

	/*
	 * Loop until either we have emptied the buffer, or we have failed to
	 * allocate something when we expected to.
	 */
	while (buflen > 0) {
		Mixer *m = nullptr;
		const char *p = end - buflen;
		unsigned resid = buflen;

		/*
		 * Use the next character as a hint to decide which mixer class to construct.
		 */
		switch (*p) {
		case 'Z':
			m = NullMixer::from_text(p, resid);
			break;

		case 'M':
			m = SimpleMixer::from_text(_control_cb, _cb_handle, p, resid);
			break;

		case 'R':
			m = MultirotorMixer::from_text(_control_cb, _cb_handle, p, resid);
			break;

		default:
			/* it's probably junk or whitespace, skip a byte and retry */
			buflen--;
			continue;
		}

		/*
		 * If we constructed something, add it to the group.
		 */
		if (m != nullptr) {
			add_mixer(m);

			/* we constructed something */
			ret = 0;

			/* only adjust buflen if parsing was successful */
			buflen = resid;
		} else {

			/*
			 * There is data in the buffer that we expected to parse, but it didn't,
			 * so give up for now.
			 */
			break;
		}
	}

	/* nothing more in the buffer for us now */
	return ret;
}
<|endoftext|>


<commit_before>//
// Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include <backendsCommon/MemoryManager.hpp>
#include <armnn/utility/IgnoreUnused.hpp>

#include <doctest/doctest.h>
#include <numeric>

namespace armnn
{
/// @brief Class that implements a sample custom allocator.
class SampleCustomAllocator : public armnn::ICustomAllocator
{
public:
    SampleCustomAllocator() = default;

    void* allocate(size_t size, size_t alignment) override
    {
        IgnoreUnused(alignment);
        CHECK(size == m_Values.size());
        m_CounterAllocate+=1;
        return m_Values.data();
    }

    void free(void* ptr) override
    {
        CHECK(ptr == m_Values.data());
        m_CounterFree+=1;
    }

    armnn::MemorySource GetMemorySourceType() override
    {
        return armnn::MemorySource::Malloc;
    }

    virtual void* GetMemoryRegionAtOffset(void* buffer, size_t offset, size_t alignment = 0 ) override
    {
        IgnoreUnused(alignment);
        return (static_cast<char*>(buffer) + offset);
    }

    /// Holds the data in the tensors. Create for testing purposes.
    std::vector<uint8_t> m_Values;
    /// Counts the number of times the function allocate is called.
    unsigned long m_CounterAllocate= 0;
    /// Counts the number of times the function free is called.
    unsigned long m_CounterFree = 0;
};

TEST_SUITE("MemoryManagerTests")
{
/// Unit test Storing, Allocating and Deallocating with a custom allocator.
TEST_CASE("MemoryManagerTest")
{
    using namespace armnn;

    // Create mock up bufferStorageVector with 2 BufferStorage with the same TensorMemory
    size_t numTensors = 5;
    std::vector<TensorMemory*> tensorMemoryPointerVector(numTensors);
    std::vector<TensorMemory> tensorMemoryVector;
    tensorMemoryVector.reserve(numTensors);

    std::vector<size_t> offsets(numTensors);
    std::iota(std::begin(offsets), std::end(offsets), 0);

    for (uint idx = 0; idx < tensorMemoryPointerVector.size(); ++idx)
    {
        tensorMemoryVector.emplace_back(TensorMemory{offsets[idx], nullptr, 0});
        tensorMemoryPointerVector[idx] = &tensorMemoryVector[idx];
    }

    std::vector<BufferStorage> bufferStorageVector;
    bufferStorageVector.emplace_back(BufferStorage{tensorMemoryPointerVector, numTensors});
    bufferStorageVector.emplace_back(BufferStorage{tensorMemoryPointerVector, numTensors});

    // Create an instance of the SampleCustomAllocator
    SampleCustomAllocator customAllocator = SampleCustomAllocator();
    customAllocator.m_Values = {10, 11, 12, 13, 14};
    // Check that the test was set up correctly
    CHECK(customAllocator.m_Values.size() == numTensors);

    // Utilise 3 functions in the MemoryManager. Check the counters and the pointer to the values are correct.
    MemoryManager memoryManager;
    memoryManager.StoreMemToAllocate(bufferStorageVector, &customAllocator);

    memoryManager.Allocate();
    CHECK(customAllocator.m_CounterAllocate == bufferStorageVector.size());
    for (const auto& bufferStorage : bufferStorageVector)
    {
        uint idx = 0;
        for (auto tensorMemory : bufferStorage.m_TensorMemoryVector)
        {
            auto value = reinterpret_cast<uint8_t *>(tensorMemory->m_Data);
            CHECK(customAllocator.m_Values[idx] == *value);
            idx += 1;
        }
    }

    memoryManager.Deallocate();
    CHECK(customAllocator.m_CounterFree == bufferStorageVector.size());
}
}

} // namespace armnn<commit_msg>Fix use of non-standard "uint" type<commit_after>//
// Copyright © 2021 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include <backendsCommon/MemoryManager.hpp>
#include <armnn/utility/IgnoreUnused.hpp>

#include <doctest/doctest.h>
#include <numeric>

namespace armnn
{
/// @brief Class that implements a sample custom allocator.
class SampleCustomAllocator : public armnn::ICustomAllocator
{
public:
    SampleCustomAllocator() = default;

    void* allocate(size_t size, size_t alignment) override
    {
        IgnoreUnused(alignment);
        CHECK(size == m_Values.size());
        m_CounterAllocate+=1;
        return m_Values.data();
    }

    void free(void* ptr) override
    {
        CHECK(ptr == m_Values.data());
        m_CounterFree+=1;
    }

    armnn::MemorySource GetMemorySourceType() override
    {
        return armnn::MemorySource::Malloc;
    }

    virtual void* GetMemoryRegionAtOffset(void* buffer, size_t offset, size_t alignment = 0 ) override
    {
        IgnoreUnused(alignment);
        return (static_cast<char*>(buffer) + offset);
    }

    /// Holds the data in the tensors. Create for testing purposes.
    std::vector<uint8_t> m_Values;
    /// Counts the number of times the function allocate is called.
    unsigned long m_CounterAllocate= 0;
    /// Counts the number of times the function free is called.
    unsigned long m_CounterFree = 0;
};

TEST_SUITE("MemoryManagerTests")
{
/// Unit test Storing, Allocating and Deallocating with a custom allocator.
TEST_CASE("MemoryManagerTest")
{
    using namespace armnn;

    // Create mock up bufferStorageVector with 2 BufferStorage with the same TensorMemory
    size_t numTensors = 5;
    std::vector<TensorMemory*> tensorMemoryPointerVector(numTensors);
    std::vector<TensorMemory> tensorMemoryVector;
    tensorMemoryVector.reserve(numTensors);

    std::vector<size_t> offsets(numTensors);
    std::iota(std::begin(offsets), std::end(offsets), 0);

    for (uint32_t idx = 0; idx < tensorMemoryPointerVector.size(); ++idx)
    {
        tensorMemoryVector.emplace_back(TensorMemory{offsets[idx], nullptr, 0});
        tensorMemoryPointerVector[idx] = &tensorMemoryVector[idx];
    }

    std::vector<BufferStorage> bufferStorageVector;
    bufferStorageVector.emplace_back(BufferStorage{tensorMemoryPointerVector, numTensors});
    bufferStorageVector.emplace_back(BufferStorage{tensorMemoryPointerVector, numTensors});

    // Create an instance of the SampleCustomAllocator
    SampleCustomAllocator customAllocator = SampleCustomAllocator();
    customAllocator.m_Values = {10, 11, 12, 13, 14};
    // Check that the test was set up correctly
    CHECK(customAllocator.m_Values.size() == numTensors);

    // Utilise 3 functions in the MemoryManager. Check the counters and the pointer to the values are correct.
    MemoryManager memoryManager;
    memoryManager.StoreMemToAllocate(bufferStorageVector, &customAllocator);

    memoryManager.Allocate();
    CHECK(customAllocator.m_CounterAllocate == bufferStorageVector.size());
    for (const auto& bufferStorage : bufferStorageVector)
    {
        uint32_t idx = 0;
        for (auto tensorMemory : bufferStorage.m_TensorMemoryVector)
        {
            auto value = reinterpret_cast<uint8_t *>(tensorMemory->m_Data);
            CHECK(customAllocator.m_Values[idx] == *value);
            idx += 1;
        }
    }

    memoryManager.Deallocate();
    CHECK(customAllocator.m_CounterFree == bufferStorageVector.size());
}
}

} // namespace armnn<|endoftext|>