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

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

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

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

=========================================================================*/
#include "otbWrapperOutputImageParameter.h"
#include "itkCastImageFilter.h"
#include "itkVectorCastImageFilter.h"

namespace otb
{
namespace Wrapper
{

OutputImageParameter::OutputImageParameter()
  : m_PixelType(ImagePixelType_float), m_RAMValue(0)
{
  this->SetName("Output Image");
  this->SetKey("out");
}

OutputImageParameter::~OutputImageParameter()
{
}

void OutputImageParameter::InitializeWriters()
{
  m_Int8Writer = Int8WriterType::New();
  m_UInt8Writer = UInt8WriterType::New();
  m_Int16Writer = Int16WriterType::New();
  m_UInt16Writer = UInt16WriterType::New();
  m_Int32Writer = Int32WriterType::New();
  m_UInt32Writer = UInt32WriterType::New();
  m_FloatWriter = FloatWriterType::New();
  m_DoubleWriter = DoubleWriterType::New();

  m_VectorInt8Writer = VectorInt8WriterType::New();
  m_VectorUInt8Writer = VectorUInt8WriterType::New();
  m_VectorInt16Writer = VectorInt16WriterType::New();
  m_VectorUInt16Writer = VectorUInt16WriterType::New();
  m_VectorInt32Writer = VectorInt32WriterType::New();
  m_VectorUInt32Writer = VectorUInt32WriterType::New();
  m_VectorFloatWriter = VectorFloatWriterType::New();
  m_VectorDoubleWriter = VectorDoubleWriterType::New();

  m_RGBUInt8Writer = RGBUInt8WriterType::New();
  m_RGBAUInt8Writer = RGBAUInt8WriterType::New();
}

#define otbCastAndWriteImageMacro(InputImageType, OutputImageType, writer)        \
  {                                                                               \
    typedef itk::CastImageFilter<InputImageType, OutputImageType> CastFilterType; \
    typename CastFilterType::Pointer caster = CastFilterType::New();              \
    caster->SetInput( dynamic_cast<InputImageType*>(m_Image.GetPointer()) );      \
    caster->InPlaceOn();                                                          \
    writer->SetFileName( this->GetFileName() );                                   \
    writer->SetInput(caster->GetOutput());                                        \
    writer->WriteGeomFileOn();                                                    \
    writer->SetAutomaticTiledStreaming(m_RAMValue);                               \
    writer->Update();                                                             \
  }

template <class TInputImageType>
void
OutputImageParameter::SwitchImageWrite()
{
  switch(m_PixelType )
    {
    case ImagePixelType_int8:
    {
    otbCastAndWriteImageMacro(TInputImageType, Int8ImageType, m_Int8Writer);
    break;
    }
    case ImagePixelType_uint8:
    {
    otbCastAndWriteImageMacro(TInputImageType, UInt8ImageType, m_UInt8Writer);
    break;
    }
    case ImagePixelType_int16:
    {
    otbCastAndWriteImageMacro(TInputImageType, Int16ImageType, m_Int16Writer);
    break;
    }
    case ImagePixelType_uint16:
    {
    otbCastAndWriteImageMacro(TInputImageType, UInt16ImageType, m_UInt16Writer);
    break;
    }
    case ImagePixelType_int32:
    {
    otbCastAndWriteImageMacro(TInputImageType, Int32ImageType, m_Int32Writer);
    break;
    }
    case ImagePixelType_uint32:
    {
    otbCastAndWriteImageMacro(TInputImageType, UInt32ImageType, m_UInt32Writer);
    break;
    }
    case ImagePixelType_float:
    {
    otbCastAndWriteImageMacro(TInputImageType, FloatImageType, m_FloatWriter);
    break;
    }
    case ImagePixelType_double:
    {
    otbCastAndWriteImageMacro(TInputImageType, DoubleImageType, m_DoubleWriter);
    break;
    }
    }
}

template <class TInputVectorImageType>
void
OutputImageParameter::SwitchVectorImageWrite()
  {
  switch(m_PixelType )
    {
    case ImagePixelType_int8:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, Int8VectorImageType, m_VectorInt8Writer);
    break;
    }
    case ImagePixelType_uint8:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, UInt8VectorImageType, m_VectorUInt8Writer);
    break;
    }
    case ImagePixelType_int16:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, Int16VectorImageType, m_VectorInt16Writer);
    break;
    }
    case ImagePixelType_uint16:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, UInt16VectorImageType, m_VectorUInt16Writer);
    break;
    }
    case ImagePixelType_int32:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, Int32VectorImageType, m_VectorInt32Writer);
    break;
    }
    case ImagePixelType_uint32:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, UInt32VectorImageType, m_VectorUInt32Writer);
    break;
    }
    case ImagePixelType_float:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, FloatVectorImageType, m_VectorFloatWriter);
    break;
    }
    case ImagePixelType_double:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, DoubleVectorImageType, m_VectorDoubleWriter);
    break;
    }
    }
  }

template <class TInputRGBAImageType>
void
OutputImageParameter::SwitchRGBAImageWrite()
  {
  if( m_PixelType == ImagePixelType_uint8 )
    {
    otbCastAndWriteImageMacro(TInputRGBAImageType, UInt8RGBAImageType, m_RGBAUInt8Writer);
    }
   else
     itkExceptionMacro("Unknown PixelType for RGBA Image.");
  }

template <class TInputRGBImageType>
void
OutputImageParameter::SwitchRGBImageWrite()
  {
   if( m_PixelType == ImagePixelType_uint8 )
    {
    otbCastAndWriteImageMacro(TInputRGBImageType, UInt8RGBImageType, m_RGBUInt8Writer);
    }
   else
     itkExceptionMacro("Unknown PixelType for RGB Image.");
  }

void
OutputImageParameter::Write()
{
  m_Image->UpdateOutputInformation();

  if (dynamic_cast<Int8ImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<Int8ImageType>();
    }
  else if (dynamic_cast<UInt8ImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<UInt8ImageType>();
    }
  else if (dynamic_cast<Int16ImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<Int16ImageType>();
    }
  else if (dynamic_cast<UInt16ImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<UInt16ImageType>();
    }
  else if (dynamic_cast<Int32ImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<Int32ImageType>();
    }
  else if (dynamic_cast<UInt32ImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<UInt32ImageType>();
    }
  else if (dynamic_cast<FloatImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<FloatImageType>();
    }
  else if (dynamic_cast<DoubleImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<DoubleImageType>();
    }
  else if (dynamic_cast<Int8VectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<Int8VectorImageType>();
    }
  else if (dynamic_cast<UInt8VectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<UInt8VectorImageType>();
    }
  else if (dynamic_cast<Int16VectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<Int16VectorImageType>();
    }
  else if (dynamic_cast<UInt16VectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<UInt16VectorImageType>();
    }
  else if (dynamic_cast<Int32VectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<Int32VectorImageType>();
    }
  else if (dynamic_cast<UInt32VectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<UInt32VectorImageType>();
    }
  else if (dynamic_cast<FloatVectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<FloatVectorImageType>();
    }
  else if (dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<DoubleVectorImageType>();
    }
  else if (dynamic_cast<UInt8RGBImageType*>(m_Image.GetPointer()))
    {
    SwitchRGBImageWrite<UInt8RGBImageType>();
    }
  else if (dynamic_cast<UInt8RGBAImageType*>(m_Image.GetPointer()))
    {
    SwitchRGBAImageWrite<UInt8RGBAImageType>();
    }
  else
    {
    itkExceptionMacro("Unknown image type");
    }
  }

itk::ProcessObject*
OutputImageParameter::GetWriter()
{
  int type = 0;
  // 0 : image
  // 1 : VectorImage
  // 2 : RGBAImage
  // 3 : RGBImage

  if (dynamic_cast<Int8VectorImageType*> (m_Image.GetPointer())
      || dynamic_cast<UInt8VectorImageType*> (m_Image.GetPointer())
      || dynamic_cast<Int16VectorImageType*> (m_Image.GetPointer())
      || dynamic_cast<UInt16VectorImageType*> (m_Image.GetPointer())
      || dynamic_cast<Int32VectorImageType*> (m_Image.GetPointer())
      || dynamic_cast<UInt32VectorImageType*> (m_Image.GetPointer())
      || dynamic_cast<FloatVectorImageType*> (m_Image.GetPointer())
      || dynamic_cast<DoubleVectorImageType*> (m_Image.GetPointer()))
    {
    type = 1;
    }
  else
    if (dynamic_cast<UInt8RGBAImageType*> (m_Image.GetPointer()))
      {
      type = 2;
      }
    else
      if (dynamic_cast<UInt8RGBImageType*> (m_Image.GetPointer()))
        {
        type = 3;
        }

  itk::ProcessObject* writer = 0;
  switch (GetPixelType())
    {
    case ImagePixelType_int8:
      {
      if (type == 1)
        writer = m_VectorInt8Writer;
      else
        if (type == 0) writer = m_Int8Writer;
      break;
      }
    case ImagePixelType_uint8:
      {
      if (type == 1)
        writer = m_VectorUInt8Writer;
      else
        if (type == 0)
          writer = m_UInt8Writer;
        else
          if (type == 2)
            writer = m_RGBAUInt8Writer;
          else writer = m_RGBUInt8Writer;
      break;
      }
    case ImagePixelType_int16:
      {
      if (type == 1)
        writer = m_VectorInt16Writer;
      else
        if (type == 0) writer = m_Int16Writer;
      break;
      }
    case ImagePixelType_uint16:
      {
      if (type == 1)
        writer = m_VectorUInt16Writer;
      else
        if (type == 0) writer = m_UInt16Writer;
      break;
      }
    case ImagePixelType_int32:
      {
      if (type == 1)
        writer = m_VectorInt32Writer;
      else
        if (type == 0) writer = m_Int32Writer;
      break;
      }
    case ImagePixelType_uint32:
      {
      if (type == 1)
        writer = m_VectorUInt32Writer;
      else
        if (type == 0) writer = m_UInt32Writer;
      break;
      }
    case ImagePixelType_float:
      {
      if (type == 1)
        writer = m_VectorFloatWriter;
      else
        if (type == 0) writer = m_FloatWriter;
      break;
      }
    case ImagePixelType_double:
      {
      if (type == 1)
        writer = m_VectorDoubleWriter;
      else
        if (type == 0) writer = m_DoubleWriter;
      break;
      }
    }
  if (0 == writer)
    {
    itkExceptionMacro("Unknown Writer type.");
    }

  return writer;
}

OutputImageParameter::ImageBaseType*
OutputImageParameter::GetValue( )
{
  return m_Image;
}

void
OutputImageParameter::SetValue(ImageBaseType* image)
{
  m_Image = image;
  SetActive(true);
}

bool
OutputImageParameter::HasValue() const
{
  std::string filename(this->GetFileName());
  return !filename.empty();
}

}
}
<commit_msg>BUG: RGBUInt8 writer assignement when wrtiting RGBUInt8 and RGBAUInt8 Image Format.<commit_after>/*=========================================================================

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

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

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

=========================================================================*/
#include "otbWrapperOutputImageParameter.h"
#include "itkCastImageFilter.h"
#include "itkVectorCastImageFilter.h"

namespace otb
{
namespace Wrapper
{

OutputImageParameter::OutputImageParameter()
  : m_PixelType(ImagePixelType_float), m_RAMValue(0)
{
  this->SetName("Output Image");
  this->SetKey("out");
}

OutputImageParameter::~OutputImageParameter()
{
}

void OutputImageParameter::InitializeWriters()
{
  m_Int8Writer = Int8WriterType::New();
  m_UInt8Writer = UInt8WriterType::New();
  m_Int16Writer = Int16WriterType::New();
  m_UInt16Writer = UInt16WriterType::New();
  m_Int32Writer = Int32WriterType::New();
  m_UInt32Writer = UInt32WriterType::New();
  m_FloatWriter = FloatWriterType::New();
  m_DoubleWriter = DoubleWriterType::New();

  m_VectorInt8Writer = VectorInt8WriterType::New();
  m_VectorUInt8Writer = VectorUInt8WriterType::New();
  m_VectorInt16Writer = VectorInt16WriterType::New();
  m_VectorUInt16Writer = VectorUInt16WriterType::New();
  m_VectorInt32Writer = VectorInt32WriterType::New();
  m_VectorUInt32Writer = VectorUInt32WriterType::New();
  m_VectorFloatWriter = VectorFloatWriterType::New();
  m_VectorDoubleWriter = VectorDoubleWriterType::New();

  m_RGBUInt8Writer = RGBUInt8WriterType::New();
  m_RGBAUInt8Writer = RGBAUInt8WriterType::New();
}

#define otbCastAndWriteImageMacro(InputImageType, OutputImageType, writer)        \
  {                                                                               \
    typedef itk::CastImageFilter<InputImageType, OutputImageType> CastFilterType; \
    typename CastFilterType::Pointer caster = CastFilterType::New();              \
    caster->SetInput( dynamic_cast<InputImageType*>(m_Image.GetPointer()) );      \
    caster->InPlaceOn();                                                          \
    writer->SetFileName( this->GetFileName() );                                   \
    writer->SetInput(caster->GetOutput());                                        \
    writer->WriteGeomFileOn();                                                    \
    writer->SetAutomaticTiledStreaming(m_RAMValue);                               \
    writer->Update();                                                             \
  }

template <class TInputImageType>
void
OutputImageParameter::SwitchImageWrite()
{
  switch(m_PixelType )
    {
    case ImagePixelType_int8:
    {
    otbCastAndWriteImageMacro(TInputImageType, Int8ImageType, m_Int8Writer);
    break;
    }
    case ImagePixelType_uint8:
    {
    otbCastAndWriteImageMacro(TInputImageType, UInt8ImageType, m_UInt8Writer);
    break;
    }
    case ImagePixelType_int16:
    {
    otbCastAndWriteImageMacro(TInputImageType, Int16ImageType, m_Int16Writer);
    break;
    }
    case ImagePixelType_uint16:
    {
    otbCastAndWriteImageMacro(TInputImageType, UInt16ImageType, m_UInt16Writer);
    break;
    }
    case ImagePixelType_int32:
    {
    otbCastAndWriteImageMacro(TInputImageType, Int32ImageType, m_Int32Writer);
    break;
    }
    case ImagePixelType_uint32:
    {
    otbCastAndWriteImageMacro(TInputImageType, UInt32ImageType, m_UInt32Writer);
    break;
    }
    case ImagePixelType_float:
    {
    otbCastAndWriteImageMacro(TInputImageType, FloatImageType, m_FloatWriter);
    break;
    }
    case ImagePixelType_double:
    {
    otbCastAndWriteImageMacro(TInputImageType, DoubleImageType, m_DoubleWriter);
    break;
    }
    }
}

template <class TInputVectorImageType>
void
OutputImageParameter::SwitchVectorImageWrite()
  {
  switch(m_PixelType )
    {
    case ImagePixelType_int8:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, Int8VectorImageType, m_VectorInt8Writer);
    break;
    }
    case ImagePixelType_uint8:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, UInt8VectorImageType, m_VectorUInt8Writer);
    break;
    }
    case ImagePixelType_int16:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, Int16VectorImageType, m_VectorInt16Writer);
    break;
    }
    case ImagePixelType_uint16:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, UInt16VectorImageType, m_VectorUInt16Writer);
    break;
    }
    case ImagePixelType_int32:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, Int32VectorImageType, m_VectorInt32Writer);
    break;
    }
    case ImagePixelType_uint32:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, UInt32VectorImageType, m_VectorUInt32Writer);
    break;
    }
    case ImagePixelType_float:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, FloatVectorImageType, m_VectorFloatWriter);
    break;
    }
    case ImagePixelType_double:
    {
    otbCastAndWriteImageMacro(TInputVectorImageType, DoubleVectorImageType, m_VectorDoubleWriter);
    break;
    }
    }
  }

template <class TInputRGBAImageType>
void
OutputImageParameter::SwitchRGBAImageWrite()
  {
  if( m_PixelType == ImagePixelType_uint8 )
    {
    otbCastAndWriteImageMacro(TInputRGBAImageType, UInt8RGBAImageType, m_RGBAUInt8Writer);
    }
   else
     itkExceptionMacro("Unknown PixelType for RGBA Image.");
  }

template <class TInputRGBImageType>
void
OutputImageParameter::SwitchRGBImageWrite()
  {
   if( m_PixelType == ImagePixelType_uint8 )
    {
    otbCastAndWriteImageMacro(TInputRGBImageType, UInt8RGBImageType, m_RGBUInt8Writer);
    }
   else
     itkExceptionMacro("Unknown PixelType for RGB Image.");
  }

void
OutputImageParameter::Write()
{
  m_Image->UpdateOutputInformation();

  if (dynamic_cast<Int8ImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<Int8ImageType>();
    }
  else if (dynamic_cast<UInt8ImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<UInt8ImageType>();
    }
  else if (dynamic_cast<Int16ImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<Int16ImageType>();
    }
  else if (dynamic_cast<UInt16ImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<UInt16ImageType>();
    }
  else if (dynamic_cast<Int32ImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<Int32ImageType>();
    }
  else if (dynamic_cast<UInt32ImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<UInt32ImageType>();
    }
  else if (dynamic_cast<FloatImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<FloatImageType>();
    }
  else if (dynamic_cast<DoubleImageType*>(m_Image.GetPointer()))
    {
    SwitchImageWrite<DoubleImageType>();
    }
  else if (dynamic_cast<Int8VectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<Int8VectorImageType>();
    }
  else if (dynamic_cast<UInt8VectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<UInt8VectorImageType>();
    }
  else if (dynamic_cast<Int16VectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<Int16VectorImageType>();
    }
  else if (dynamic_cast<UInt16VectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<UInt16VectorImageType>();
    }
  else if (dynamic_cast<Int32VectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<Int32VectorImageType>();
    }
  else if (dynamic_cast<UInt32VectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<UInt32VectorImageType>();
    }
  else if (dynamic_cast<FloatVectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<FloatVectorImageType>();
    }
  else if (dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()))
    {
    SwitchVectorImageWrite<DoubleVectorImageType>();
    }
  else if (dynamic_cast<UInt8RGBImageType*>(m_Image.GetPointer()))
    {
    SwitchRGBImageWrite<UInt8RGBImageType>();
    }
  else if (dynamic_cast<UInt8RGBAImageType*>(m_Image.GetPointer()))
    {
    SwitchRGBAImageWrite<UInt8RGBAImageType>();
    }
  else
    {
    itkExceptionMacro("Unknown image type");
    }
  }

itk::ProcessObject*
OutputImageParameter::GetWriter()
{
  int type = 0;
  // 0 : image
  // 1 : VectorImage
  // 2 : RGBAImage
  // 3 : RGBImage
  itk::ProcessObject* writer = 0;
  if (dynamic_cast<Int8VectorImageType*> (m_Image.GetPointer())
      || dynamic_cast<UInt8VectorImageType*> (m_Image.GetPointer())
      || dynamic_cast<Int16VectorImageType*> (m_Image.GetPointer())
      || dynamic_cast<UInt16VectorImageType*> (m_Image.GetPointer())
      || dynamic_cast<Int32VectorImageType*> (m_Image.GetPointer())
      || dynamic_cast<UInt32VectorImageType*> (m_Image.GetPointer())
      || dynamic_cast<FloatVectorImageType*> (m_Image.GetPointer())
      || dynamic_cast<DoubleVectorImageType*> (m_Image.GetPointer()))
    {
    type = 1;
    }
  else
    if (dynamic_cast<UInt8RGBAImageType*> (m_Image.GetPointer()))
      {
      type = 2;
      writer = m_RGBAUInt8Writer;
      itkWarningMacro("UInt8RGBAImageType will be saved in UInt8 format.");
      return writer;
      }
    else
      if (dynamic_cast<UInt8RGBImageType*> (m_Image.GetPointer()))
        {
        type = 3;
        writer = m_RGBUInt8Writer;
        itkWarningMacro("UInt8RGBImageType will be saved in UInt8 format.");
        return writer;
        }

  switch (GetPixelType())
    {
    case ImagePixelType_int8:
      {
      if (type == 1)
        writer = m_VectorInt8Writer;
      else
        if (type == 0) writer = m_Int8Writer;

      break;
      }
    case ImagePixelType_uint8:
      {
      if (type == 1)
        writer = m_VectorUInt8Writer;
      else
        if (type == 0)
          writer = m_UInt8Writer;
        else
          if (type == 2)
            writer = m_RGBAUInt8Writer;
          else writer = m_RGBUInt8Writer;
      break;
      }
    case ImagePixelType_int16:
      {
      if (type == 1)
        writer = m_VectorInt16Writer;
      else
        if (type == 0) writer = m_Int16Writer;
      break;
      }
    case ImagePixelType_uint16:
      {
      if (type == 1)
        writer = m_VectorUInt16Writer;
      else
        if (type == 0) writer = m_UInt16Writer;
      break;
      }
    case ImagePixelType_int32:
      {
      if (type == 1)
        writer = m_VectorInt32Writer;
      else
        if (type == 0) writer = m_Int32Writer;
      break;
      }
    case ImagePixelType_uint32:
      {
      if (type == 1)
        writer = m_VectorUInt32Writer;
      else
        if (type == 0) writer = m_UInt32Writer;
      break;
      }
    case ImagePixelType_float:
      {
      if (type == 1)
        writer = m_VectorFloatWriter;
      else
        if (type == 0) writer = m_FloatWriter;
      break;
      }
    case ImagePixelType_double:
      {
      if (type == 1)
        writer = m_VectorDoubleWriter;
      else
        if (type == 0) writer = m_DoubleWriter;
      break;
      }
    }
  if (0 == writer)
    {
    itkExceptionMacro("Unknown Writer type.");
    }

  return writer;
}

OutputImageParameter::ImageBaseType*
OutputImageParameter::GetValue( )
{
  return m_Image;
}

void
OutputImageParameter::SetValue(ImageBaseType* image)
{
  m_Image = image;
  SetActive(true);
}

bool
OutputImageParameter::HasValue() const
{
  std::string filename(this->GetFileName());
  return !filename.empty();
}

}
}
<|endoftext|>


<commit_before>//
//  gen-map.cc
//

#include <cstdio>
#include <cstdlib>
#include <functional>
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include <deque>
#include <map>
#include <set>

#include <unistd.h>

#include "util.h"
#include "cmdline.h"
#include "model.h"
#include "gen.h"

std::vector<cmdline_option> rv_gen_markdown::get_cmdline_options()
{
	return std::vector<cmdline_option>{
		{ "-md", "--print-markdown", cmdline_arg_type_none,
			"Print instruction reference in markdown",
			[&](std::string s) { return gen->set_option("print_markdown"); } },
	};
}

static void print_markdown(rv_gen *gen)
{
	static const char* fmt = "%s | %s | %s\n";

	for (auto &ext : gen->extensions) {
		if (ext->opcodes.size() == 0 || (gen->ext_subset.size() > 0 &&
			std::find(gen->ext_subset.begin(), gen->ext_subset.end(), ext) == gen->ext_subset.end())) {
			continue;
		}

		printf("_**%s**_\n\n", ext->description.c_str());
		printf(fmt, "Format", "Name", "Pseudocode");
		printf(fmt, ":--", ":--", ":--");

		for (auto &opcode : ext->opcodes) {
			if (opcode->is_pseudo()) continue;

			auto name = opcode->name;
			auto operand_comps = split(opcode->format->operands, ",");
			std::transform(name.begin(), name.end(), name.begin(), ::toupper);
			if (operand_comps.size() == 1 && operand_comps[0] == "none") operand_comps[0] = "";
			std::string format;
			format.append("");
			format.append(name);
			if (operand_comps.size() > 0) {
				format.append(" ");
				format.append(join(operand_comps, ", "));
			}
			format.append("");

			std::string fullname;
			fullname.append("");
			fullname.append(opcode->fullname);
			fullname.append("");

			std::string pseudocode;
			pseudocode.append("");
			pseudocode.append(opcode->pseudocode_alt);
			pseudocode.append("");

			printf(fmt, format.c_str(), fullname.c_str(), pseudocode.c_str());
		}
		printf("\n");
	}
}

void rv_gen_markdown::generate()
{
	if (gen->has_option("print_markdown")) print_markdown(gen);
}
<commit_msg>Don't use commas in instruction operand formats<commit_after>//
//  gen-map.cc
//

#include <cstdio>
#include <cstdlib>
#include <functional>
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include <deque>
#include <map>
#include <set>

#include <unistd.h>

#include "util.h"
#include "cmdline.h"
#include "model.h"
#include "gen.h"

std::vector<cmdline_option> rv_gen_markdown::get_cmdline_options()
{
	return std::vector<cmdline_option>{
		{ "-md", "--print-markdown", cmdline_arg_type_none,
			"Print instruction reference in markdown",
			[&](std::string s) { return gen->set_option("print_markdown"); } },
	};
}

static void print_markdown(rv_gen *gen)
{
	static const char* fmt = "%s | %s | %s\n";

	for (auto &ext : gen->extensions) {
		if (ext->opcodes.size() == 0 || (gen->ext_subset.size() > 0 &&
			std::find(gen->ext_subset.begin(), gen->ext_subset.end(), ext) == gen->ext_subset.end())) {
			continue;
		}

		printf("_**%s**_\n\n", ext->description.c_str());
		printf(fmt, "Format", "Name", "Pseudocode");
		printf(fmt, ":--", ":--", ":--");

		for (auto &opcode : ext->opcodes) {
			if (opcode->is_pseudo()) continue;

			auto name = opcode->name;
			auto operand_comps = split(opcode->format->operands, ",");
			std::transform(name.begin(), name.end(), name.begin(), ::toupper);
			if (operand_comps.size() == 1 && operand_comps[0] == "none") operand_comps[0] = "";
			std::string format;
			format.append("");
			format.append(name);
			if (operand_comps.size() > 0) {
				format.append(" ");
				format.append(join(operand_comps, ","));
			}
			format.append("");

			std::string fullname;
			fullname.append("");
			fullname.append(opcode->fullname);
			fullname.append("");

			std::string pseudocode;
			pseudocode.append("");
			pseudocode.append(opcode->pseudocode_alt);
			pseudocode.append("");

			printf(fmt, format.c_str(), fullname.c_str(), pseudocode.c_str());
		}
		printf("\n");
	}
}

void rv_gen_markdown::generate()
{
	if (gen->has_option("print_markdown")) print_markdown(gen);
}
<|endoftext|>


<commit_before>/*
 *  Copyright 2008-2010 NVIDIA Corporation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/*! \file reduce.inl
 *  \brief Inline file for reduce.h
 */

// do not attempt to compile this file with any other compiler
#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC

// to configure launch parameters
#include <thrust/experimental/arch.h>

#include <thrust/detail/type_traits.h>

#include <thrust/detail/raw_buffer.h>
#include <thrust/detail/device/cuda/block/reduce.h>
#include <thrust/detail/device/cuda/extern_shared_ptr.h>

namespace thrust
{
namespace detail
{
namespace device
{
namespace cuda
{
namespace detail
{

/*
 * Reduce a vector of n elements using binary_op()
 *
 * The order of reduction is not defined, so binary_op() should
 * be a commutative (and associative) operator such as
 * (integer) addition.  Since floating point operations
 * do not completely satisfy these criteria, the result is
 * generally not the same as a consecutive reduction of
 * the elements.
 *
 * Uses the same pattern as reduce6() in the CUDA SDK
 *
 */

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction,
         typename SharedArray>
  __device__ void
  reduce_n_device(InputIterator input,
                  const unsigned int n,
                  OutputType * block_results,
                  BinaryFunction binary_op,
                  SharedArray shared_array)
{
    // perform one level of reduction, writing per-block results to
    // global memory for subsequent processing (e.g. second level reduction)
    const unsigned int grid_size = blockDim.x * gridDim.x;
    unsigned int i = blockDim.x * blockIdx.x + threadIdx.x;

    // advance input
    input += i;

    // local (per-thread) sum
    OutputType sum;

    // initialize local sum
    if (i < n)
    {
        sum = thrust::detail::device::dereference(input);
        i += grid_size;
        input += grid_size;
    }

    // accumulate local sum
    while (i < n)
    {
        OutputType val = thrust::detail::device::dereference(input);
        sum = binary_op(sum, val);
        i += grid_size;
        input += grid_size;
    }

    // copy local sum to shared memory
    shared_array[threadIdx.x] = sum;  __syncthreads();

    // compute reduction across block
    thrust::detail::device::cuda::block::reduce_n(shared_array, min(n - blockDim.x * blockIdx.x, blockDim.x), binary_op);

    // write result for this block to global mem
    if (threadIdx.x == 0)
        block_results[blockIdx.x] = shared_array[threadIdx.x];

} // end reduce_n_device()

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  __global__ void
  reduce_n_smem(InputIterator input,
                const unsigned int n,
                OutputType * block_results,
                BinaryFunction binary_op)
{
    thrust::detail::device::cuda::extern_shared_ptr<OutputType> shared_ptr;
    OutputType *shared_array = shared_ptr;

    reduce_n_device(input, n, block_results, binary_op, shared_array);
} // end reduce_n_kernel()

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  __global__ void
  reduce_n_gmem(InputIterator input,
                const unsigned int n,
                OutputType * block_results,
                OutputType * shared_array,
                BinaryFunction binary_op)
{
    reduce_n_device(input, n, block_results, binary_op, shared_array + blockDim.x * blockIdx.x);
} // end reduce_n_kernel()

template<typename InputIterator,
         typename SizeType,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce_n(InputIterator first,
                      SizeType n,
                      OutputType init,
                      BinaryFunction binary_op,
                      thrust::detail::true_type)    // reduce in shared memory
{
    // determine launch parameters
    const size_t smem_per_thread = sizeof(OutputType);
    const size_t block_size = thrust::experimental::arch::max_blocksize_with_highest_occupancy(reduce_n_smem<InputIterator, OutputType, BinaryFunction>, smem_per_thread);
    const size_t smem_size  = block_size * smem_per_thread;
    const size_t max_blocks = thrust::experimental::arch::max_active_blocks(reduce_n_smem<InputIterator, OutputType, BinaryFunction>, block_size, smem_size);
    const size_t num_blocks = std::min(max_blocks, (n + (block_size - 1)) / block_size);

    // allocate storage for per-block results
    thrust::detail::raw_cuda_device_buffer<OutputType> temp(num_blocks + 1);

    // set first element of temp array to init
    temp[0] = init;

    // reduce input to per-block sums
    reduce_n_smem<<<num_blocks, block_size, smem_size>>>(first, n, raw_pointer_cast(&temp[1]), binary_op);

    // reduce per-block sums together with init
    {
#if CUDA_VERSION >= 3000
        const unsigned int block_size_pass2 = thrust::experimental::arch::max_blocksize(reduce_n_smem<OutputType *, OutputType, BinaryFunction>, smem_per_thread);
#else
        const unsigned int block_size_pass2 = 32;
#endif
        const unsigned int smem_size_pass2  = smem_per_thread * block_size_pass2;
        reduce_n_smem<<<1, block_size_pass2, smem_size_pass2>>>(raw_pointer_cast(&temp[0]), num_blocks + 1, raw_pointer_cast(&temp[0]), binary_op);
    }

    return temp[0];
} // end reduce_n()

template<typename InputIterator,
         typename SizeType,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce_n(InputIterator first,
                      SizeType n,
                      OutputType init,
                      BinaryFunction binary_op,
                      thrust::detail::false_type)    // reduce in global memory
{
    // determine launch parameters
    const size_t smem_per_thread = 0;
    const size_t block_size = thrust::experimental::arch::max_blocksize_with_highest_occupancy(reduce_n_gmem<InputIterator, OutputType, BinaryFunction>, smem_per_thread);
    const size_t smem_size  = block_size * smem_per_thread;
    const size_t max_blocks = thrust::experimental::arch::max_active_blocks(reduce_n_gmem<InputIterator, OutputType, BinaryFunction>, block_size, smem_size);
    const size_t num_blocks = std::min(max_blocks, (n + (block_size - 1)) / block_size);

    // allocate storage for per-block results
    thrust::detail::raw_cuda_device_buffer<OutputType> temp(num_blocks + 1);

    // allocate storage for shared array
    thrust::detail::raw_cuda_device_buffer<OutputType> shared_array(block_size * num_blocks);

    // set first element of temp array to init
    temp[0] = init;

    // reduce input to per-block sums
    detail::reduce_n_gmem<<<num_blocks, block_size, 0>>>(first, n, raw_pointer_cast(&temp[1]), raw_pointer_cast(&shared_array[0]), binary_op);

    // reduce per-block sums together with init
    {
#if CUDA_VERSION >= 3000
        const unsigned int block_size_pass2 = std::min(block_size, thrust::experimental::arch::max_blocksize(reduce_n_gmem<OutputType *, OutputType, BinaryFunction>, smem_per_thread));
#else
        const unsigned int block_size_pass2 = 32;
#endif
        const unsigned int smem_size_pass2  = smem_per_thread * block_size_pass2;
        detail::reduce_n_gmem<<<1, block_size_pass2, smem_size_pass2>>>(raw_pointer_cast(&temp[0]), num_blocks + 1, raw_pointer_cast(&temp[0]), raw_pointer_cast(&shared_array[0]), binary_op);
    }

    return temp[0];
} // end reduce_n()

} // end namespace detail

// TODO add runtime switch for SizeType vs. unsigned int
// TODO use closure approach to handle large iterators & functors (i.e. sum > 256 bytes)

template<typename InputIterator,
         typename SizeType,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce_n(InputIterator first,
                      SizeType n,
                      OutputType init,
                      BinaryFunction binary_op)
{
    // handle zero length array case first
    if( n == 0 )
        return init;

    // whether to perform blockwise reductions in shared memory or global memory
    thrust::detail::integral_constant<bool, sizeof(OutputType) <= 64> use_smem;

    return detail::reduce_n(first, n, init, binary_op, use_smem);
} // end reduce_n()

} // end namespace cuda
} // end namespace device
} // end namespace detail
} // end namespace thrust

#endif // THRUST_DEVICE_COMPILER != THRUST_DEVICE_COMPILER_NVCC

<commit_msg>reorganized cuda::reduce() to avoid uninitialized value warning<commit_after>/*
 *  Copyright 2008-2010 NVIDIA Corporation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/*! \file reduce.inl
 *  \brief Inline file for reduce.h
 */

// do not attempt to compile this file with any other compiler
#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC

// to configure launch parameters
#include <thrust/experimental/arch.h>

#include <thrust/detail/type_traits.h>

#include <thrust/detail/raw_buffer.h>
#include <thrust/detail/device/cuda/block/reduce.h>
#include <thrust/detail/device/cuda/extern_shared_ptr.h>

namespace thrust
{
namespace detail
{
namespace device
{
namespace cuda
{
namespace detail
{

/*
 * Reduce a vector of n elements using binary_op()
 *
 * The order of reduction is not defined, so binary_op() should
 * be a commutative (and associative) operator such as
 * (integer) addition.  Since floating point operations
 * do not completely satisfy these criteria, the result is
 * generally not the same as a consecutive reduction of
 * the elements.
 *
 * Uses the same pattern as reduce6() in the CUDA SDK
 *
 */

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction,
         typename SharedArray>
  __device__ void
  reduce_n_device(InputIterator input,
                  const unsigned int n,
                  OutputType * block_results,
                  BinaryFunction binary_op,
                  SharedArray shared_array)
{
    // perform one level of reduction, writing per-block results to
    // global memory for subsequent processing (e.g. second level reduction)
    const unsigned int grid_size = blockDim.x * gridDim.x;
    unsigned int i = blockDim.x * blockIdx.x + threadIdx.x;

    // advance input
    input += i;

    if (i < n)
    {
        // initialize local sum
        OutputType sum = thrust::detail::device::dereference(input);

        i     += grid_size;
        input += grid_size;

        // accumulate local sum
        while (i < n)
        {
            OutputType val = thrust::detail::device::dereference(input);
            sum = binary_op(sum, val);

            i     += grid_size;
            input += grid_size;
        }

        // copy local sum to shared memory
        shared_array[threadIdx.x] = sum;
    }

    __syncthreads();

    // compute reduction across block
    thrust::detail::device::cuda::block::reduce_n(shared_array, min(n - blockDim.x * blockIdx.x, blockDim.x), binary_op);

    // write result for this block to global mem
    if (threadIdx.x == 0)
        block_results[blockIdx.x] = shared_array[threadIdx.x];

} // end reduce_n_device()

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  __global__ void
  reduce_n_smem(InputIterator input,
                const unsigned int n,
                OutputType * block_results,
                BinaryFunction binary_op)
{
    thrust::detail::device::cuda::extern_shared_ptr<OutputType> shared_ptr;
    OutputType *shared_array = shared_ptr;

    reduce_n_device(input, n, block_results, binary_op, shared_array);
} // end reduce_n_kernel()

template<typename InputIterator,
         typename OutputType,
         typename BinaryFunction>
  __global__ void
  reduce_n_gmem(InputIterator input,
                const unsigned int n,
                OutputType * block_results,
                OutputType * shared_array,
                BinaryFunction binary_op)
{
    reduce_n_device(input, n, block_results, binary_op, shared_array + blockDim.x * blockIdx.x);
} // end reduce_n_kernel()

template<typename InputIterator,
         typename SizeType,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce_n(InputIterator first,
                      SizeType n,
                      OutputType init,
                      BinaryFunction binary_op,
                      thrust::detail::true_type)    // reduce in shared memory
{
    // determine launch parameters
    const size_t smem_per_thread = sizeof(OutputType);
    const size_t block_size = thrust::experimental::arch::max_blocksize_with_highest_occupancy(reduce_n_smem<InputIterator, OutputType, BinaryFunction>, smem_per_thread);
    const size_t smem_size  = block_size * smem_per_thread;
    const size_t max_blocks = thrust::experimental::arch::max_active_blocks(reduce_n_smem<InputIterator, OutputType, BinaryFunction>, block_size, smem_size);
    const size_t num_blocks = std::min(max_blocks, (n + (block_size - 1)) / block_size);

    // allocate storage for per-block results
    thrust::detail::raw_cuda_device_buffer<OutputType> temp(num_blocks + 1);

    // set first element of temp array to init
    temp[0] = init;

    // reduce input to per-block sums
    reduce_n_smem<<<num_blocks, block_size, smem_size>>>(first, n, raw_pointer_cast(&temp[1]), binary_op);

    // reduce per-block sums together with init
    {
#if CUDA_VERSION >= 3000
        const unsigned int block_size_pass2 = thrust::experimental::arch::max_blocksize(reduce_n_smem<OutputType *, OutputType, BinaryFunction>, smem_per_thread);
#else
        const unsigned int block_size_pass2 = 32;
#endif
        const unsigned int smem_size_pass2  = smem_per_thread * block_size_pass2;
        reduce_n_smem<<<1, block_size_pass2, smem_size_pass2>>>(raw_pointer_cast(&temp[0]), num_blocks + 1, raw_pointer_cast(&temp[0]), binary_op);
    }

    return temp[0];
} // end reduce_n()

template<typename InputIterator,
         typename SizeType,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce_n(InputIterator first,
                      SizeType n,
                      OutputType init,
                      BinaryFunction binary_op,
                      thrust::detail::false_type)    // reduce in global memory
{
    // determine launch parameters
    const size_t smem_per_thread = 0;
    const size_t block_size = thrust::experimental::arch::max_blocksize_with_highest_occupancy(reduce_n_gmem<InputIterator, OutputType, BinaryFunction>, smem_per_thread);
    const size_t smem_size  = block_size * smem_per_thread;
    const size_t max_blocks = thrust::experimental::arch::max_active_blocks(reduce_n_gmem<InputIterator, OutputType, BinaryFunction>, block_size, smem_size);
    const size_t num_blocks = std::min(max_blocks, (n + (block_size - 1)) / block_size);

    // allocate storage for per-block results
    thrust::detail::raw_cuda_device_buffer<OutputType> temp(num_blocks + 1);

    // allocate storage for shared array
    thrust::detail::raw_cuda_device_buffer<OutputType> shared_array(block_size * num_blocks);

    // set first element of temp array to init
    temp[0] = init;

    // reduce input to per-block sums
    detail::reduce_n_gmem<<<num_blocks, block_size, 0>>>(first, n, raw_pointer_cast(&temp[1]), raw_pointer_cast(&shared_array[0]), binary_op);

    // reduce per-block sums together with init
    {
#if CUDA_VERSION >= 3000
        const unsigned int block_size_pass2 = std::min(block_size, thrust::experimental::arch::max_blocksize(reduce_n_gmem<OutputType *, OutputType, BinaryFunction>, smem_per_thread));
#else
        const unsigned int block_size_pass2 = 32;
#endif
        const unsigned int smem_size_pass2  = smem_per_thread * block_size_pass2;
        detail::reduce_n_gmem<<<1, block_size_pass2, smem_size_pass2>>>(raw_pointer_cast(&temp[0]), num_blocks + 1, raw_pointer_cast(&temp[0]), raw_pointer_cast(&shared_array[0]), binary_op);
    }

    return temp[0];
} // end reduce_n()

} // end namespace detail

// TODO add runtime switch for SizeType vs. unsigned int
// TODO use closure approach to handle large iterators & functors (i.e. sum > 256 bytes)

template<typename InputIterator,
         typename SizeType,
         typename OutputType,
         typename BinaryFunction>
  OutputType reduce_n(InputIterator first,
                      SizeType n,
                      OutputType init,
                      BinaryFunction binary_op)
{
    // handle zero length array case first
    if( n == 0 )
        return init;

    // whether to perform blockwise reductions in shared memory or global memory
    thrust::detail::integral_constant<bool, sizeof(OutputType) <= 64> use_smem;

    return detail::reduce_n(first, n, init, binary_op, use_smem);
} // end reduce_n()

} // end namespace cuda
} // end namespace device
} // end namespace detail
} // end namespace thrust

#endif // THRUST_DEVICE_COMPILER != THRUST_DEVICE_COMPILER_NVCC

<|endoftext|>


<commit_before>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "streamed_value_builder_factory.h"
#include "streamed_value_builder.h"

namespace vespalib::eval {

struct SelectStreamedValueBuilder {
    template <typename T, typename ...Args>
    static std::unique_ptr<ValueBuilderBase> invoke(const ValueType &type, Args &&...args)
    {
        assert(check_cell_type<T>(type.cell_type()));
        return std::make_unique<StreamedValueBuilder<T>>(type, std::forward<Args>(args)...);
    }
};

std::unique_ptr<ValueBuilderBase>
StreamedValueBuilderFactory::create_value_builder_base(const ValueType &type,
                                                       size_t num_mapped_in,
                                                       size_t subspace_size_in,
                                                       size_t expected_subspaces) const
{
    return typify_invoke<1,TypifyCellType,SelectStreamedValueBuilder>(
        type.cell_type(),
        type, num_mapped_in, subspace_size_in, expected_subspaces);
}

StreamedValueBuilderFactory::~StreamedValueBuilderFactory() = default;
StreamedValueBuilderFactory StreamedValueBuilderFactory::_factory;

} // namespace

<commit_msg>fix arguments (names and explicit)<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "streamed_value_builder_factory.h"
#include "streamed_value_builder.h"

namespace vespalib::eval {

struct SelectStreamedValueBuilder {
    template <typename T>
    static std::unique_ptr<ValueBuilderBase> invoke(
        const ValueType &type, size_t num_mapped,
        size_t subspace_size, size_t expected_subspaces)
    {
        assert(check_cell_type<T>(type.cell_type()));
        return std::make_unique<StreamedValueBuilder<T>>(
            type, num_mapped, subspace_size, expected_subspaces);
    }
};

std::unique_ptr<ValueBuilderBase>
StreamedValueBuilderFactory::create_value_builder_base(const ValueType &type,
                                                       size_t num_mapped,
                                                       size_t subspace_size,
                                                       size_t expected_subspaces) const
{
    return typify_invoke<1,TypifyCellType,SelectStreamedValueBuilder>(
        type.cell_type(),
        type, num_mapped, subspace_size, expected_subspaces);
}

StreamedValueBuilderFactory::~StreamedValueBuilderFactory() = default;
StreamedValueBuilderFactory StreamedValueBuilderFactory::_factory;

} // namespace

<|endoftext|>


<commit_before>/*
 *  AnalyticAircraft.cpp
 *  analyticAircraft
 *
 *  Created by Michael Bell
 *  Copyright 2010. All rights reserved.
 *
 */

#include "AnalyticAircraft.h"
#include <iterator>
#include <fstream>
#include <iostream>
#include <QFile>
#include <QTextStream>
#include <GeographicLib/TransverseMercatorExact.hpp>
#include "read_dorade.h"

AnalyticAircraft::AnalyticAircraft(const QString& in, const QString& out, const QString& suffix, const int& analytic)
{

	// Setup the data path
	dataPath = QDir(in);
	outPath = QDir(out);
	swpSuffix = suffix;
	readSwpDir();

	analyticType = analytic;
	Pi = acos(-1);
	beamwidth= -999.;

}

AnalyticAircraft::~AnalyticAircraft()
{
}

bool AnalyticAircraft::readSwpDir()
{
	dataPath.setNameFilters(QStringList("swp.*"));
	dataPath.setFilter(QDir::Files);
	dataPath.setSorting(QDir::Name);
	QStringList filenames = dataPath.entryList();

	// Read in the list sweepfiles
	for (int i = 0; i < filenames.size(); ++i) {
		QStringList fileparts = filenames.at(i).split(".");
		if (fileparts.size() == 6) swpfileList.append(filenames.at(i));
	}

	if (swpfileList.isEmpty()) {
		return false;
	} else {
		return true;
	}

}

bool AnalyticAircraft::processSweeps()
{
	double refLat = 16.5;
	double refLon = 148.;
	QTime refTime(23,48);

	// Resample an analytic field
	if (getfileListsize()) {
		for (int f = 0; f < getfileListsize(); ++f) {
			if (load(f)) {
				printf("\n\nProcessing file %d\n", f);
				analyticTrack(refLat, refLon, refTime, beltrami);
				resample_wind(refLat, refLon, beltrami);
				recalculateAirborneAngles();
				resample_wind(refLat, refLon, beltrami);
				saveQCedSwp(f);
			} else {
				printf("\n\nError loading file %d\n", f);
				return false;
			}
		}
	} else {
		std::cout << "No swp files exist in " << dataPath.dirName().toStdString() << "\n";
		return false;
	}

	return true;
}

/****************************************************************************************
 ** load : This function loads the information from an individual swp file given the index.
 ****************************************************************************************/
bool AnalyticAircraft::load(const int& swpIndex)
{
	QString filename = dataPath.absolutePath() + "/" + getswpfileName(swpIndex);
	swpfile.setFilename(filename);
	// Read in the swp file
	if(swpfile.readSwpfile())
		return true;

	return false;

}

/****************************************************************************************
 ** save : This function saves a modified swp file with suffix appended to the end.
 ****************************************************************************************/
bool AnalyticAircraft::saveQCedSwp(const int& swpIndex)
{
	QString qcfilename = outPath.absolutePath() + "/" + getswpfileName(swpIndex) + "." + swpSuffix;
	if (swpfile.writeSwpfile(qcfilename)) return true;

	return false;
}

void AnalyticAircraft::recalculateAirborneAngles()
{
	swpfile.recalculateAirborneAngles();
}

void AnalyticAircraft::analyticTrack(double refLat, double refLon, QTime refTime, int analytic)
{

	GeographicLib::TransverseMercatorExact tm = GeographicLib::TransverseMercatorExact::UTM;

	// Clear the cfac block or manually enter values here
	cfac_info* cfptr = swpfile.getCfacBlock();
	cfptr->c_azimuth = 0.0;
	cfptr->c_elevation = 0.0;
	cfptr->c_range_delay = 0.0;
	cfptr->c_rad_lon = 0.0;
	cfptr->c_rad_lat = 0.0;
	cfptr->c_alt_msl = 0.0;
	cfptr->c_alt_agl = 0.0;
	cfptr->c_ew_grspeed = 0.0;
	cfptr->c_ns_grspeed = 0.0;
	cfptr->c_vert_vel = 0.0;
	cfptr->c_head = 0.0;
	cfptr->c_roll = 0.0;
	cfptr->c_pitch = 0.0;
	cfptr->c_drift = 0.0;
	cfptr->c_rotang = 0.0;
	cfptr->c_tiltang = 0.0;

	double ns_gspeed = 120.0;
	double ew_gspeed = 0.0;
	double refX, refY;
	tm.Forward(refLon, refLat, refLon, refX, refY);
	for (int i=0; i < swpfile.getNumRays(); i++) {
		asib_info* aptr = swpfile.getAircraftBlock(i);
		ryib_info* ryptr = swpfile.getRyibBlock(i);

		QTime rayTime(ryptr->hour, ryptr->min, ryptr->sec, ryptr->msec);
		int msecElapsed = refTime.msecsTo(rayTime);

		double radarX = ew_gspeed * msecElapsed/1000.0;
		double radarY = ns_gspeed * msecElapsed/1000.0;
		double radarLat, radarLon,radarAlt;
		tm.Reverse(refLon, refX + radarX, refY + radarY, radarLat, radarLon);
		radarAlt = 3.0;
		double x = radarX - refX;
		double y = radarY - refY;
		double z = radarAlt*1000;
		double t = 0.;
		double u, v, w, dz;
		if (analytic == beltrami) {
			BeltramiFlow(x, y, z, t, u, v, w, dz);
		} else if (analytic == wrf) {
			WrfResample(x, y, z, t, u, v, w, dz);
		}
		aptr->lon = radarLon;
		aptr->lat = radarLat;
		aptr->alt_msl= radarAlt;
		aptr->alt_agl= radarAlt;
		aptr->ew_gspeed= ew_gspeed;
		aptr->ns_gspeed = ns_gspeed;
		aptr->vert_vel= 0.;
		aptr->head= 0.;
		aptr->roll= 0.;
		aptr->pitch= 0.;
		aptr->drift= 0.;
		aptr->ew_horiz_wind= u;
		aptr->ns_horiz_wind= v;
		aptr->vert_wind= w;
		aptr->head_change= 0.;
		aptr->pitch_change= 0.;
	}

}

void AnalyticAircraft::resample_wind(double refLat, double refLon, int analytic)
{

	// Resample the Doppler field with a Beltrami flow from Shapiro et al. 2009

	GeographicLib::TransverseMercatorExact tm = GeographicLib::TransverseMercatorExact::UTM;
	double refX, refY;
	tm.Forward(refLon, refLat, refLon, refX, refY);

	for (int i=0; i < swpfile.getNumRays(); i++) {
		float az = swpfile.getAzimuth(i)*Pi/180.;
		float el = swpfile.getElevation(i)*Pi/180.;
		float radarLat = swpfile.getRadarLat(i);
		float radarLon = swpfile.getRadarLon(i);
		float radarAlt = swpfile.getRadarAlt(i);
		float* refdata = swpfile.getRayData(i, "ZZ");
		float* veldata = swpfile.getRayData(i, "VV");
		float* swdata = swpfile.getRayData(i, "SW");
		float* ncpdata = swpfile.getRayData(i, "NCP");
		QDateTime rayTime = swpfile.getRayTime(i);
		float* gatesp = swpfile.getGateSpacing();
		double radarX, radarY;
		tm.Forward(refLon, radarLat, radarLon, radarX, radarY);

		for (int n=0; n < swpfile.getNumGates(); n++) {
			float range = gatesp[n];
			//float dz = pow(10.0,(refdata[g]*0.1));
			//if(veldata[n] == -32768.) continue;
			double relX = range*sin(az)*cos(el);
			double relY = range*cos(az)*cos(el);
			double rEarth = 6371000;
			// Take into account curvature of the earth
			double relZ = sqrt(range*range + rEarth*rEarth + 2.0 * range * rEarth * sin(el)) - rEarth;

			double x = radarX + relX - refX;
			double y = radarY + relY - refY;
			double z = relZ + radarAlt*1000;
			double t = 0.;

			double u, v, w, dz;
			if ((z > -5000.0) and (z <= 20000.0)) {
				if (analytic == beltrami) {
					BeltramiFlow(x, y, z, t, u, v, w, dz);
				} else if (analytic == wrf) {
					WrfResample(x, y, z, t, u, v, w, dz);
				}

				/* The default beamwidth is set to -999 which assumes the beam is infinitely small.
				    Increasing it to realistic values and/or changing the beam pattern to include sidelobes increases
				    the calculation time significantly but gives a more realistic representation of the winds */
				// beamwidth = 1.8;

				if (beamwidth < 0) {
					refdata[n] = 10*log10(dz);
					swdata[n] = 1.;
					ncpdata[n] = 1.;
					veldata[n] = u*sin(az)*cos(el) + v*cos(az)*cos(el) + w*sin(el);
				} else {
					// Loop over the width of the beam
					double maxbeam = (beamwidth*3.)*Pi/180.;
					double beamincr = maxbeam/20.;
					// Circle in spherical plane to radar beam
					double reftmp, veltmp, swtmp, weight;
					reftmp = dz;
					veltmp = u*sin(az)*cos(el) + v*cos(az)*cos(el) + w*sin(el);
					swtmp = 0.0;
					weight = 1.0;
					for (double r=beamincr; r <= maxbeam; r += beamincr) {
						for (double theta=0; theta < 360; theta += 10) {
							double azmod = az + r*cos(theta * Pi / 180.);
							double elmod = el + r*sin(theta * Pi / 180.);
							relX = range*sin(azmod)*cos(elmod);
							relY = range*cos(azmod)*cos(elmod);
							relZ = sqrt(range*range + rEarth*rEarth + 2.0 * range * rEarth * sin(elmod)) - rEarth;
							double beamaxis = r/(beamwidth*Pi/180.);
							// Gaussian beam
							double power = exp(-(beamaxis*beamaxis)/1.443695);

							// Rectangular beam
							//double power = (sin(2*Pi*beamaxis)/2*Pi*beamaxis)*(sin(2*Pi*beamaxis)/2*Pi*beamaxis);

							// Gnarly sidelobes
							//double power = (sin(10*beamaxis)/sin(beamaxis));
							//power = (power > -0.1) ? fabs(power) : 0.1;

							x = radarX + relX - refX;
							y = radarY + relY - refY;
							z = relZ + radarAlt*1000;
							if (analytic == beltrami) {
								BeltramiFlow(x, y, z, t, u, v, w, dz);
							} else if (analytic == wrf) {
								WrfResample(x, y, z, t, u, v, w, dz);
							}
							reftmp += dz*power;
							double vr = u*sin(azmod)*cos(elmod) + v*cos(azmod)*cos(elmod) + w*sin(elmod);
							veltmp += vr*power;
							weight += power;
							double vrmean = veltmp/weight;
							swtmp += power*(vr - vrmean)*(vr - vrmean);
						}
					}
					refdata[n] = 10*log10(reftmp/weight);
					swdata[n] = sqrt(swtmp/weight);
					ncpdata[n] = 1.;
					veldata[n] = veltmp/weight;

				}
			} else {
				refdata[n] = -32768.;
				swdata[n] = -32768.;
				ncpdata[n] = -32768.;
				veldata[n] = -32768.;
			}

		}
	}
}

void AnalyticAircraft::BeltramiFlow(double x, double y, double z, double t, double &u, double &v, double &w, double &dz)
{
	double k = 2*Pi / 10000.; // Horizontal wavelengths
	double l = k;
	double m = 2*Pi / 32000.;
	double A = 10.; // Peak Vertical velocity
	double amp = A / (k*k + l*l);
	double wavenum = sqrt(k*k + l*l + m*m);
	double U = 10.;
	double V = 10.;
	double nu = 15.11e-6;

	u = U - amp*(wavenum*l*cos(k*(x - U*t))*sin(l*(y-V*t))*sin(m*z) +
						m*k*sin(k*(x-U*t))*cos(l*(y-V*t))*cos(m*z))
	*exp(-nu*wavenum*wavenum*t);
	v = V + amp*(wavenum*k*sin(k*(x - U*t))*cos(l*(y-V*t))*sin(m*z) -
						m*l*cos(k*(x-U*t))*sin(l*(y-V*t))*cos(m*z))
	*exp(-nu*wavenum*wavenum*t);
	w = A*cos(k*(x-U*t))*cos(l*(y-V*t))*sin(m*z)*exp(-nu*wavenum*wavenum*t);
	dz = 1.0;
	if (z < 0.01) {
		u = v = w = 0.0;
		dz = 100000.0;
	}

}

void AnalyticAircraft::WrfResample(double x, double y, double z, double t, double &u, double &v, double &w, double &dz)
{

//height(i,k,j) = 0.5*(phb(i,k,j)+phb(i,k+1,j)+ph(i,k,j)+ph(i,k+1,j))/9.81

}<commit_msg>Added comment about beamwidth<commit_after>/*
 *  AnalyticAircraft.cpp
 *  analyticAircraft
 *
 *  Created by Michael Bell
 *  Copyright 2010. All rights reserved.
 *
 */

#include "AnalyticAircraft.h"
#include <iterator>
#include <fstream>
#include <iostream>
#include <QFile>
#include <QTextStream>
#include <GeographicLib/TransverseMercatorExact.hpp>
#include "read_dorade.h"

AnalyticAircraft::AnalyticAircraft(const QString& in, const QString& out, const QString& suffix, const int& analytic)
{

	// Setup the data path
	dataPath = QDir(in);
	outPath = QDir(out);
	swpSuffix = suffix;
	readSwpDir();

	analyticType = analytic;
	Pi = acos(-1);
	beamwidth= -999.;

}

AnalyticAircraft::~AnalyticAircraft()
{
}

bool AnalyticAircraft::readSwpDir()
{
	dataPath.setNameFilters(QStringList("swp.*"));
	dataPath.setFilter(QDir::Files);
	dataPath.setSorting(QDir::Name);
	QStringList filenames = dataPath.entryList();

	// Read in the list sweepfiles
	for (int i = 0; i < filenames.size(); ++i) {
		QStringList fileparts = filenames.at(i).split(".");
		if (fileparts.size() == 6) swpfileList.append(filenames.at(i));
	}

	if (swpfileList.isEmpty()) {
		return false;
	} else {
		return true;
	}

}

bool AnalyticAircraft::processSweeps()
{
	double refLat = 16.5;
	double refLon = 148.;
	QTime refTime(23,48);

	// Resample an analytic field
	if (getfileListsize()) {
		for (int f = 0; f < getfileListsize(); ++f) {
			if (load(f)) {
				printf("\n\nProcessing file %d\n", f);
				analyticTrack(refLat, refLon, refTime, beltrami);
				resample_wind(refLat, refLon, beltrami);
				recalculateAirborneAngles();
				resample_wind(refLat, refLon, beltrami);
				saveQCedSwp(f);
			} else {
				printf("\n\nError loading file %d\n", f);
				return false;
			}
		}
	} else {
		std::cout << "No swp files exist in " << dataPath.dirName().toStdString() << "\n";
		return false;
	}

	return true;
}

/****************************************************************************************
 ** load : This function loads the information from an individual swp file given the index.
 ****************************************************************************************/
bool AnalyticAircraft::load(const int& swpIndex)
{
	QString filename = dataPath.absolutePath() + "/" + getswpfileName(swpIndex);
	swpfile.setFilename(filename);
	// Read in the swp file
	if(swpfile.readSwpfile())
		return true;

	return false;

}

/****************************************************************************************
 ** save : This function saves a modified swp file with suffix appended to the end.
 ****************************************************************************************/
bool AnalyticAircraft::saveQCedSwp(const int& swpIndex)
{
	QString qcfilename = outPath.absolutePath() + "/" + getswpfileName(swpIndex) + "." + swpSuffix;
	if (swpfile.writeSwpfile(qcfilename)) return true;

	return false;
}

void AnalyticAircraft::recalculateAirborneAngles()
{
	swpfile.recalculateAirborneAngles();
}

void AnalyticAircraft::analyticTrack(double refLat, double refLon, QTime refTime, int analytic)
{

	GeographicLib::TransverseMercatorExact tm = GeographicLib::TransverseMercatorExact::UTM;

	// Clear the cfac block or manually enter values here
	cfac_info* cfptr = swpfile.getCfacBlock();
	cfptr->c_azimuth = 0.0;
	cfptr->c_elevation = 0.0;
	cfptr->c_range_delay = 0.0;
	cfptr->c_rad_lon = 0.0;
	cfptr->c_rad_lat = 0.0;
	cfptr->c_alt_msl = 0.0;
	cfptr->c_alt_agl = 0.0;
	cfptr->c_ew_grspeed = 0.0;
	cfptr->c_ns_grspeed = 0.0;
	cfptr->c_vert_vel = 0.0;
	cfptr->c_head = 0.0;
	cfptr->c_roll = 0.0;
	cfptr->c_pitch = 0.0;
	cfptr->c_drift = 0.0;
	cfptr->c_rotang = 0.0;
	cfptr->c_tiltang = 0.0;

	double ns_gspeed = 120.0;
	double ew_gspeed = 0.0;
	double refX, refY;
	tm.Forward(refLon, refLat, refLon, refX, refY);
	for (int i=0; i < swpfile.getNumRays(); i++) {
		asib_info* aptr = swpfile.getAircraftBlock(i);
		ryib_info* ryptr = swpfile.getRyibBlock(i);

		QTime rayTime(ryptr->hour, ryptr->min, ryptr->sec, ryptr->msec);
		int msecElapsed = refTime.msecsTo(rayTime);

		double radarX = ew_gspeed * msecElapsed/1000.0;
		double radarY = ns_gspeed * msecElapsed/1000.0;
		double radarLat, radarLon,radarAlt;
		tm.Reverse(refLon, refX + radarX, refY + radarY, radarLat, radarLon);
		radarAlt = 3.0;
		double x = radarX - refX;
		double y = radarY - refY;
		double z = radarAlt*1000;
		double t = 0.;
		double u, v, w, dz;
		if (analytic == beltrami) {
			BeltramiFlow(x, y, z, t, u, v, w, dz);
		} else if (analytic == wrf) {
			WrfResample(x, y, z, t, u, v, w, dz);
		}
		aptr->lon = radarLon;
		aptr->lat = radarLat;
		aptr->alt_msl= radarAlt;
		aptr->alt_agl= radarAlt;
		aptr->ew_gspeed= ew_gspeed;
		aptr->ns_gspeed = ns_gspeed;
		aptr->vert_vel= 0.;
		aptr->head= 0.;
		aptr->roll= 0.;
		aptr->pitch= 0.;
		aptr->drift= 0.;
		aptr->ew_horiz_wind= u;
		aptr->ns_horiz_wind= v;
		aptr->vert_wind= w;
		aptr->head_change= 0.;
		aptr->pitch_change= 0.;
	}

}

void AnalyticAircraft::resample_wind(double refLat, double refLon, int analytic)
{

	// Resample the Doppler field with a Beltrami flow from Shapiro et al. 2009

	GeographicLib::TransverseMercatorExact tm = GeographicLib::TransverseMercatorExact::UTM;
	double refX, refY;
	tm.Forward(refLon, refLat, refLon, refX, refY);

	for (int i=0; i < swpfile.getNumRays(); i++) {
		float az = swpfile.getAzimuth(i)*Pi/180.;
		float el = swpfile.getElevation(i)*Pi/180.;
		float radarLat = swpfile.getRadarLat(i);
		float radarLon = swpfile.getRadarLon(i);
		float radarAlt = swpfile.getRadarAlt(i);
		float* refdata = swpfile.getRayData(i, "ZZ");
		float* veldata = swpfile.getRayData(i, "VV");
		float* swdata = swpfile.getRayData(i, "SW");
		float* ncpdata = swpfile.getRayData(i, "NCP");
		QDateTime rayTime = swpfile.getRayTime(i);
		float* gatesp = swpfile.getGateSpacing();
		double radarX, radarY;
		tm.Forward(refLon, radarLat, radarLon, radarX, radarY);

		for (int n=0; n < swpfile.getNumGates(); n++) {
			float range = gatesp[n];
			//float dz = pow(10.0,(refdata[g]*0.1));
			//if(veldata[n] == -32768.) continue;
			double relX = range*sin(az)*cos(el);
			double relY = range*cos(az)*cos(el);
			double rEarth = 6371000;
			// Take into account curvature of the earth
			double relZ = sqrt(range*range + rEarth*rEarth + 2.0 * range * rEarth * sin(el)) - rEarth;

			double x = radarX + relX - refX;
			double y = radarY + relY - refY;
			double z = relZ + radarAlt*1000;
			double t = 0.;

			double u, v, w, dz;
			if ((z > -5000.0) and (z <= 20000.0)) {
				if (analytic == beltrami) {
					BeltramiFlow(x, y, z, t, u, v, w, dz);
				} else if (analytic == wrf) {
					WrfResample(x, y, z, t, u, v, w, dz);
				}

				/* The default beamwidth is set to -999 which assumes the beam is infinitely small.
				    Increasing it to realistic values and/or changing the beam pattern to include sidelobes increases
				    the calculation time significantly but gives a more realistic representation of the winds */
				beamwidth = 1.8;

				if (beamwidth < 0) {
					refdata[n] = 10*log10(dz);
					swdata[n] = 1.;
					ncpdata[n] = 1.;
					veldata[n] = u*sin(az)*cos(el) + v*cos(az)*cos(el) + w*sin(el);
				} else {
					// Loop over the width of the beam
					double maxbeam = (beamwidth*3.)*Pi/180.;
					double beamincr = maxbeam/20.;
					// Circle in spherical plane to radar beam
					double reftmp, veltmp, swtmp, weight;
					reftmp = dz;
					veltmp = u*sin(az)*cos(el) + v*cos(az)*cos(el) + w*sin(el);
					swtmp = 0.0;
					weight = 1.0;
					for (double r=beamincr; r <= maxbeam; r += beamincr) {
						for (double theta=0; theta < 360; theta += 10) {
							double azmod = az + r*cos(theta * Pi / 180.);
							double elmod = el + r*sin(theta * Pi / 180.);
							relX = range*sin(azmod)*cos(elmod);
							relY = range*cos(azmod)*cos(elmod);
							relZ = sqrt(range*range + rEarth*rEarth + 2.0 * range * rEarth * sin(elmod)) - rEarth;
							double beamaxis = r/(beamwidth*Pi/180.);
							// Gaussian beam
							double power = exp(-(beamaxis*beamaxis)/1.443695);

							// Rectangular beam
							//double power = (sin(2*Pi*beamaxis)/2*Pi*beamaxis)*(sin(2*Pi*beamaxis)/2*Pi*beamaxis);

							// Gnarly sidelobes
							//double power = (sin(10*beamaxis)/sin(beamaxis));
							//power = (power > -0.1) ? fabs(power) : 0.1;

							x = radarX + relX - refX;
							y = radarY + relY - refY;
							z = relZ + radarAlt*1000;
							if (analytic == beltrami) {
								BeltramiFlow(x, y, z, t, u, v, w, dz);
							} else if (analytic == wrf) {
								WrfResample(x, y, z, t, u, v, w, dz);
							}
							reftmp += dz*power;
							double vr = u*sin(azmod)*cos(elmod) + v*cos(azmod)*cos(elmod) + w*sin(elmod);
							veltmp += vr*power;
							weight += power;
							double vrmean = veltmp/weight;
							swtmp += power*(vr - vrmean)*(vr - vrmean);
						}
					}
					refdata[n] = 10*log10(reftmp/weight);
					swdata[n] = sqrt(swtmp/weight);
					ncpdata[n] = 1.;
					veldata[n] = veltmp/weight;

				}
			} else {
				refdata[n] = -32768.;
				swdata[n] = -32768.;
				ncpdata[n] = -32768.;
				veldata[n] = -32768.;
			}

		}
	}
}

void AnalyticAircraft::BeltramiFlow(double x, double y, double z, double t, double &u, double &v, double &w, double &dz)
{
	double k = 2*Pi / 10000.; // Horizontal wavelengths
	double l = k;
	double m = 2*Pi / 32000.;
	double A = 10.; // Peak Vertical velocity
	double amp = A / (k*k + l*l);
	double wavenum = sqrt(k*k + l*l + m*m);
	double U = 10.;
	double V = 10.;
	double nu = 15.11e-6;

	u = U - amp*(wavenum*l*cos(k*(x - U*t))*sin(l*(y-V*t))*sin(m*z) +
						m*k*sin(k*(x-U*t))*cos(l*(y-V*t))*cos(m*z))
	*exp(-nu*wavenum*wavenum*t);
	v = V + amp*(wavenum*k*sin(k*(x - U*t))*cos(l*(y-V*t))*sin(m*z) -
						m*l*cos(k*(x-U*t))*sin(l*(y-V*t))*cos(m*z))
	*exp(-nu*wavenum*wavenum*t);
	w = A*cos(k*(x-U*t))*cos(l*(y-V*t))*sin(m*z)*exp(-nu*wavenum*wavenum*t);
	dz = 1.0;
	if (z < 0.01) {
		u = v = w = 0.0;
		dz = 100000.0;
	}

}

void AnalyticAircraft::WrfResample(double x, double y, double z, double t, double &u, double &v, double &w, double &dz)
{

//height(i,k,j) = 0.5*(phb(i,k,j)+phb(i,k+1,j)+ph(i,k,j)+ph(i,k+1,j))/9.81

}<|endoftext|>


<commit_before>#include <QUrl>
#include "module.h"
#include "kernel.h"
#include "ilwisdata.h"
#include "domain.h"
#include "mastercatalog.h"

using namespace Ilwis;

Domain::Domain(): _strict(true)
{
}

Domain::Domain(const Resource& resource) : IlwisObject(resource), _strict(true)
{
    if ( parent().isValid())
        parent()->removeChildDomain(this->id());
}

bool Ilwis::Domain::isStrict() const
{
    return _strict;
}

void Ilwis::Domain::setStrict(bool yesno)
{
    _strict = yesno;
}

IDomain Domain::parent() const
{
    return _parentDomain;
}

void Domain::setParent(const IDomain &dm)
{
    if ( dm.isValid())
        dm->addChildDomain(id());
    else
        _parentDomain->removeChildDomain(id());
    _parentDomain = dm;

}

void Domain::addChildDomain(quint64 idchild)
{
    auto iter = _childDomains.find(idchild);
    if ( iter != _childDomains.end())
        (*iter).second++;
    else
        _childDomains[idchild] = 1;
}

bool Domain::removeChildDomain(quint64 idchild)
{
    auto iter = _childDomains.find(idchild);
    if ( iter != _childDomains.end()) {
        (*iter).second--;
        if ( (*iter).second == 0)
            _childDomains.erase(idchild);
        return true;
    }
    return false;
}

IlwisTypes Domain::ilwType(const QString &value) {
    std::set<QString> booleans ={ "yes","no","true","false"};
    if ( booleans.find(value.toLower()) != booleans.end())
        return itBOOL;

    bool ok;
    ushort vu = value.toUShort(&ok);
    if ( ok && vu < 255)
        return itUINT8;
    if ( ok)
        return itUINT16;
    short vs = value.toShort(&ok);
    if ( ok && vs > -128 && vs < 128)
        return itINT8;
    if ( ok)
       return itINT16;
    value.toULong(&ok);
    if ( ok)
        return itUINT32;
    value.toLong(&ok);
    if ( ok)
       return itINT32;
    value.toLongLong(&ok);
    if ( ok)
        return itINT64;
    value.toDouble(&ok);
    if ( ok)
       return itDOUBLE;

    return IlwisObject::findType(value);
}

IlwisTypes Domain::ilwType(const QVariant &v)
{
    QVariant::Type ty = v.type();
    switch(ty) {
        case QVariant::Bool:
            return itUINT8; break;
        case QVariant::Double:
            return itDOUBLE; break;
        case QVariant::Int:
          return itINT32; break;
        case QVariant::LongLong:
        case QVariant::ULongLong:
            return itINT64; break;
        case QVariant::UInt:
            return itUINT32; break;
        case QVariant::String:
              return itSTRING; break;
        case QVariant::Time:
            return itTIME; break;
        case QVariant::Date:
            return itDATE; break;
        case QVariant::DateTime:
            return itDATETIME;
        default:
            return itUNKNOWN;

    }
    return itUNKNOWN;
}

<commit_msg>added varianttype -->ilwistype for collections<commit_after>#include <QUrl>
#include "module.h"
#include "kernel.h"
#include "ilwisdata.h"
#include "domain.h"
#include "mastercatalog.h"

using namespace Ilwis;

Domain::Domain(): _strict(true)
{
}

Domain::Domain(const Resource& resource) : IlwisObject(resource), _strict(true)
{
    if ( parent().isValid())
        parent()->removeChildDomain(this->id());
}

bool Ilwis::Domain::isStrict() const
{
    return _strict;
}

void Ilwis::Domain::setStrict(bool yesno)
{
    _strict = yesno;
}

IDomain Domain::parent() const
{
    return _parentDomain;
}

void Domain::setParent(const IDomain &dm)
{
    if ( dm.isValid())
        dm->addChildDomain(id());
    else
        _parentDomain->removeChildDomain(id());
    _parentDomain = dm;

}

void Domain::addChildDomain(quint64 idchild)
{
    auto iter = _childDomains.find(idchild);
    if ( iter != _childDomains.end())
        (*iter).second++;
    else
        _childDomains[idchild] = 1;
}

bool Domain::removeChildDomain(quint64 idchild)
{
    auto iter = _childDomains.find(idchild);
    if ( iter != _childDomains.end()) {
        (*iter).second--;
        if ( (*iter).second == 0)
            _childDomains.erase(idchild);
        return true;
    }
    return false;
}

IlwisTypes Domain::ilwType(const QString &value) {
    std::set<QString> booleans ={ "yes","no","true","false"};
    if ( booleans.find(value.toLower()) != booleans.end())
        return itBOOL;

    bool ok;
    ushort vu = value.toUShort(&ok);
    if ( ok && vu < 255)
        return itUINT8;
    if ( ok)
        return itUINT16;
    short vs = value.toShort(&ok);
    if ( ok && vs > -128 && vs < 128)
        return itINT8;
    if ( ok)
       return itINT16;
    value.toULong(&ok);
    if ( ok)
        return itUINT32;
    value.toLong(&ok);
    if ( ok)
       return itINT32;
    value.toLongLong(&ok);
    if ( ok)
        return itINT64;
    value.toDouble(&ok);
    if ( ok)
       return itDOUBLE;

    return IlwisObject::findType(value);
}

IlwisTypes Domain::ilwType(const QVariant &v)
{
    QVariant::Type ty = v.type();
    switch(ty) {
        case QVariant::Bool:
            return itUINT8; break;
        case QVariant::Double:
            return itDOUBLE; break;
        case QVariant::Int:
          return itINT32; break;
        case QVariant::LongLong:
        case QVariant::ULongLong:
            return itINT64; break;
        case QVariant::UInt:
            return itUINT32; break;
        case QVariant::String:
              return itSTRING; break;
        case QVariant::Time:
            return itTIME; break;
        case QVariant::Date:
            return itDATE; break;
        case QVariant::DateTime:
            return itDATETIME;
        case QVariant::List:
            return itCOLLECTION;
        default:
            return itUNKNOWN;

    }
    return itUNKNOWN;
}

<|endoftext|>


<commit_before>#include <string.h>
#include <math.h>
#include <iostream>
#include <stdexcept>
#include "FireLog.h"
#include "FireSight.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "jansson.h"
#include "jo_util.hpp"
#include "MatUtil.hpp"
#include "version.h"

using namespace cv;
using namespace std;
using namespace firesight;

class ComparePoint2f {
    private:
        bool isXY;

    public:
        ComparePoint2f(bool isXY=true) {
            this->isXY = isXY;
        }
    public:
        bool operator()(const Point2f &lhs, const Point2f &rhs) const {
			assert(!isnan(lhs.x));
			assert(!isnan(rhs.x));
			int cmp;
			if ( isXY ) {
				cmp = lhs.x - rhs.x;
				if (cmp == 0) {
					cmp = lhs.y - rhs.y;
				}
			} else {
				cmp = lhs.y - rhs.y;
				if (cmp == 0) {
					cmp = lhs.x - rhs.x;
				}
			}
            return cmp < 0;
        }
};

typedef map<Point2f,Point2f,ComparePoint2f> PointMap;

bool Pipeline::apply_matchGrid(json_t *pStage, json_t *pStageModel, Model &model) {
    string rectsModelName = jo_string(pStage, "model", "", model.argMap);
    double sepX = jo_double(pStage, "sepX", 5.0, model.argMap);
    double sepY = jo_double(pStage, "sepY", 5.0, model.argMap);
    double tolerance = jo_double(pStage, "tolerance", 0.35, model.argMap);
    json_t *pRectsModel = json_object_get(model.getJson(false), rectsModelName.c_str());
    string errMsg;

    if (rectsModelName.empty()) {
        errMsg = "matchGrid model: expected name of stage with rects";
    } else if (!json_is_object(pRectsModel)) {
        errMsg = "Named stage is not in model";
    }

    json_t *pRects = NULL;
    if (errMsg.empty()) {
        pRects = json_object_get(pRectsModel, "rects");
        if (!json_is_array(pRects)) {
            errMsg = "Expected array of rects to match";
        } else if (json_array_size(pRects) < 2) {
            errMsg = "Expected array of at least 2 rects to match";
        }
    }

    Point2f dTot1;
    Point2f dTot2;
    int dCount1 = 0;
    int dCount2 = 0;
    float dyMedian = FLT_MAX;
    const ComparePoint2f cmp;
    if (errMsg.empty()) {
        PointMap pointMap(cmp);
        json_t *pValue;
        int index;
        json_array_foreach(pRects, index, pValue) {
            json_t *pX = json_object_get(pValue, "x");
            json_t *pY = json_object_get(pValue, "y");
            if (json_is_number(pX) && json_is_number(pY)) {
                double x = json_real_value(pX);
                double y = json_real_value(pY);
                const Point2f key(x,y);
				cout << "adding " << key << " to pointMap(" << pointMap.size() << ")" << endl;
                pointMap[key] = Point2f(x,y);
            }
        }

		vector<float> dyList;
        Point2f prevPt;
        for (PointMap::iterator it=pointMap.begin(); it!=pointMap.end(); it++) {
            if (it != pointMap.begin()) {
                float dy = prevPt.y - it->first.y;
				dyList.push_back(dy);
            }
            prevPt = it->first;
        }
		sort(dyList.begin(), dyList.end());
        dyMedian = dyList[dyList.size()/2];
        float maxTol = dyMedian < 0 ? 1-tolerance : 1+tolerance;
        float minTol = dyMedian < 0 ? 1+tolerance : 1-tolerance;
        float maxDy1 = dyMedian * maxTol;
        float minDy1 = dyMedian * minTol;
        float maxDy2 = 2*dyMedian * maxTol;
        float minDy2 = 2*dyMedian * minTol;

        Point2f prevPt1;
        Point2f prevPt2;
		int n = 0;
        for (map<Point2f,Point2f,ComparePoint2f>::iterator it=pointMap.begin();
                it!=pointMap.end(); it++) {
            const Point2f &curPt = it->first;
            cout << "(" << curPt.x << "," << curPt.y << ")" << endl;
            if (n > 0) {
                int dy1 = prevPt1.y - curPt.y;
                if (minDy1 <= dy1 && dy1 <= maxDy1) {
                    dTot1 = dTot1 + (prevPt1 - curPt);
                    dCount1++;
                }
                if (n > 1) {
                    int dy2 = prevPt2.y - curPt.y;
                    if (minDy2 <= dy2 && dy2 <= maxDy2) {
                        dTot2 = dTot2 + (prevPt2 - curPt);
                        dCount2++;
                    }
                }
            }
            prevPt2 = prevPt1;
            prevPt1 = curPt;
			n++;
        }
        json_object_set(pStageModel, "dyMedian", json_real(dyMedian));
        json_object_set(pStageModel, "dCount1", json_integer(dCount1));
        json_object_set(pStageModel, "dCount2", json_integer(dCount2));
        if (dCount1 == 0) {
            errMsg = "No grid points matched within tolerance (level 1)";
        } else if (dCount2 == 0) {
            json_object_set(pStageModel, "dxAvg1", json_real(dTot1.x/dCount1));
            json_object_set(pStageModel, "dyAvg1", json_real(dTot1.y/dCount1));
            errMsg = "No grid points matched within tolerance (level 2)";
        } else {
            float dxAvg2 = dTot2.x/dCount2/2;
            float dyAvg2 = dTot2.y/dCount2/2;
            json_object_set(pStageModel, "dxAvg1", json_real(dTot1.x/dCount1));
            json_object_set(pStageModel, "dyAvg1", json_real(dTot1.y/dCount1));
            json_object_set(pStageModel, "dxAvg2", json_real(dxAvg2));
            json_object_set(pStageModel, "dyAvg2", json_real(dyAvg2));
            float gridY = sqrt(dxAvg2*dxAvg2 + dyAvg2*dyAvg2) / sepY;
            float gridX = sqrt(dxAvg2*dxAvg2 + dyAvg2*dyAvg2) / sepX;
            json_object_set(pStageModel, "gridY", json_real(gridY));
            json_object_set(pStageModel, "gridX", json_real(gridX));
        }
    }

    return stageOK("apply_matchGrid(%s) %s", errMsg.c_str(), pStage, pStageModel);
}

<commit_msg>CompareOp<commit_after>#include <string.h>
#include <math.h>
#include <iostream>
#include <stdexcept>
#include "FireLog.h"
#include "FireSight.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "jansson.h"
#include "jo_util.hpp"
#include "MatUtil.hpp"
#include "version.h"

using namespace cv;
using namespace std;
using namespace firesight;

enum CompareOp {
    COMPARE_XY,
    COMPARE_YX
};

typedef class ComparePoint2f {
    private:
        CompareOp op;

    public:
        ComparePoint2f(CompareOp op=COMPARE_XY) {
            this->op = op;
        }
    public:
        bool operator()(const Point2f &lhs, const Point2f &rhs) const {
            assert(!isnan(lhs.x));
            assert(!isnan(rhs.x));
            int cmp;
            switch (op) {
            case COMPARE_XY:
                cmp = lhs.x - rhs.x;
                if (cmp == 0) {
                    cmp = lhs.y - rhs.y;
                }
                break;
            case COMPARE_YX:
                cmp = lhs.y - rhs.y;
                if (cmp == 0) {
                    cmp = lhs.x - rhs.x;
                }
                break;
            }
            return cmp < 0;
        }
} ComparePoint2f;

typedef map<Point2f,Point2f,ComparePoint2f> PointMap;

bool Pipeline::apply_matchGrid(json_t *pStage, json_t *pStageModel, Model &model) {
    string rectsModelName = jo_string(pStage, "model", "", model.argMap);
    double sepX = jo_double(pStage, "sepX", 5.0, model.argMap);
    double sepY = jo_double(pStage, "sepY", 5.0, model.argMap);
    double tolerance = jo_double(pStage, "tolerance", 0.35, model.argMap);
    json_t *pRectsModel = json_object_get(model.getJson(false), rectsModelName.c_str());
    string errMsg;

    if (rectsModelName.empty()) {
        errMsg = "matchGrid model: expected name of stage with rects";
    } else if (!json_is_object(pRectsModel)) {
        errMsg = "Named stage is not in model";
    }

    json_t *pRects = NULL;
    if (errMsg.empty()) {
        pRects = json_object_get(pRectsModel, "rects");
        if (!json_is_array(pRects)) {
            errMsg = "Expected array of rects to match";
        } else if (json_array_size(pRects) < 2) {
            errMsg = "Expected array of at least 2 rects to match";
        }
    }

    Point2f dTot1;
    Point2f dTot2;
    int dCount1 = 0;
    int dCount2 = 0;
    float dyMedian = FLT_MAX;
    const ComparePoint2f cmp;
    if (errMsg.empty()) {
        PointMap pointMap(cmp);
        json_t *pValue;
        int index;
        json_array_foreach(pRects, index, pValue) {
            json_t *pX = json_object_get(pValue, "x");
            json_t *pY = json_object_get(pValue, "y");
            if (json_is_number(pX) && json_is_number(pY)) {
                double x = json_real_value(pX);
                double y = json_real_value(pY);
                const Point2f key(x,y);
                cout << "adding " << key << " to pointMap(" << pointMap.size() << ")" << endl;
                pointMap[key] = Point2f(x,y);
            }
        }

        vector<float> listXY;
        Point2f prevPt;
        for (PointMap::iterator it=pointMap.begin(); it!=pointMap.end(); it++) {
            if (it != pointMap.begin()) {
                float dy = prevPt.y - it->first.y;
                listXY.push_back(dy);
            }
            prevPt = it->first;
        }
        sort(listXY.begin(), listXY.end());
        dyMedian = listXY[listXY.size()/2];
        float maxTol = dyMedian < 0 ? 1-tolerance : 1+tolerance;
        float minTol = dyMedian < 0 ? 1+tolerance : 1-tolerance;
        float maxDy1 = dyMedian * maxTol;
        float minDy1 = dyMedian * minTol;
        float maxDy2 = 2*dyMedian * maxTol;
        float minDy2 = 2*dyMedian * minTol;

        Point2f prevPt1;
        Point2f prevPt2;
        int n = 0;
        for (map<Point2f,Point2f,ComparePoint2f>::iterator it=pointMap.begin();
                it!=pointMap.end(); it++) {
            const Point2f &curPt = it->first;
            cout << "(" << curPt.x << "," << curPt.y << ")" << endl;
            if (n > 0) {
                int dy1 = prevPt1.y - curPt.y;
                if (minDy1 <= dy1 && dy1 <= maxDy1) {
                    dTot1 = dTot1 + (prevPt1 - curPt);
                    dCount1++;
                }
                if (n > 1) {
                    int dy2 = prevPt2.y - curPt.y;
                    if (minDy2 <= dy2 && dy2 <= maxDy2) {
                        dTot2 = dTot2 + (prevPt2 - curPt);
                        dCount2++;
                    }
                }
            }
            prevPt2 = prevPt1;
            prevPt1 = curPt;
            n++;
        }
        json_object_set(pStageModel, "dyMedian", json_real(dyMedian));
        json_object_set(pStageModel, "dCount1", json_integer(dCount1));
        json_object_set(pStageModel, "dCount2", json_integer(dCount2));
        if (dCount1 == 0) {
            errMsg = "No grid points matched within tolerance (level 1)";
        } else if (dCount2 == 0) {
            json_object_set(pStageModel, "dxAvg1", json_real(dTot1.x/dCount1));
            json_object_set(pStageModel, "dyAvg1", json_real(dTot1.y/dCount1));
            errMsg = "No grid points matched within tolerance (level 2)";
        } else {
            float dxAvg2 = dTot2.x/dCount2/2;
            float dyAvg2 = dTot2.y/dCount2/2;
            json_object_set(pStageModel, "dxAvg1", json_real(dTot1.x/dCount1));
            json_object_set(pStageModel, "dyAvg1", json_real(dTot1.y/dCount1));
            json_object_set(pStageModel, "dxAvg2", json_real(dxAvg2));
            json_object_set(pStageModel, "dyAvg2", json_real(dyAvg2));
            float gridY = sqrt(dxAvg2*dxAvg2 + dyAvg2*dyAvg2) / sepY;
            float gridX = sqrt(dxAvg2*dxAvg2 + dyAvg2*dyAvg2) / sepX;
            json_object_set(pStageModel, "gridY", json_real(gridY));
            json_object_set(pStageModel, "gridX", json_real(gridX));
        }
    }

    return stageOK("apply_matchGrid(%s) %s", errMsg.c_str(), pStage, pStageModel);
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007 Tommi Maekitalo
 *
 * This program 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 program 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 program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <tnt/stressjob.h>
#include <cxxtools/log.h>

log_define("tntnet.testjob");

namespace tnt
{
  StressHttpClientStreambuf::DummyHttpClientStreambuf(const std::string& url)
  {
    request = "GET " + url + " HTTP/1.0\r\nUser-agent: dummy\r\n\r\n";
    char* p = const_cast<char*>(request.data());
    setg(p, p, p + request.size());
  }

  StressHttpClientStreambuf::int_type DummyHttpClientStreambuf::overflow(int_type c)
  {
    return 0;
  }

  StressHttpClientStreambuf::int_type DummyHttpClientStreambuf::underflow()
  {
    return traits_type::eof();
  }

  int StressHttpClientStreambuf::sync()
  {
    return 0;
  }

  cxxtools::Mutex StressJob::mutex;
  unsigned StressJob::count = 0;

  StressJob::DummyJob(Jobqueue& queue_, const std::string& url_)
    : client(url_),
      init(false),
      queue(queue_),
      url(url_)
  {
    cxxtools::MutexLock lock(mutex);
    if (++count % 10000 == 0)
      log_info(count << " dummy-jobs processed");
  }

  std::iostream& StressJob::getStream()
  {
    if (!init)
    {
      if (count % 100000 == 0)
        usleep(1000000);
      queue.put(new StressJob(queue, url));
      init = true;
    }
    return client;
  }

  int StressJob::getFd() const
  {
    return 0;
  }

  void StressJob::setRead()
  {
  }

  void StressJob::setWrite()
  {
  }

}
<commit_msg>fixed classname<commit_after>/*
 * Copyright (C) 2007 Tommi Maekitalo
 *
 * This program 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 program 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 program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <tnt/stressjob.h>
#include <cxxtools/log.h>

log_define("tntnet.testjob");

namespace tnt
{
  StressHttpClientStreambuf::StressHttpClientStreambuf(const std::string& url)
  {
    request = "GET " + url + " HTTP/1.0\r\nUser-agent: dummy\r\n\r\n";
    char* p = const_cast<char*>(request.data());
    setg(p, p, p + request.size());
  }

  StressHttpClientStreambuf::int_type StressHttpClientStreambuf::overflow(int_type c)
  {
    return 0;
  }

  StressHttpClientStreambuf::int_type StressHttpClientStreambuf::underflow()
  {
    return traits_type::eof();
  }

  int StressHttpClientStreambuf::sync()
  {
    return 0;
  }

  cxxtools::Mutex StressJob::mutex;
  unsigned StressJob::count = 0;

  StressJob::StressJob(Jobqueue& queue_, const std::string& url_)
    : client(url_),
      init(false),
      queue(queue_),
      url(url_)
  {
    cxxtools::MutexLock lock(mutex);
    if (++count % 10000 == 0)
      log_info(count << " dummy-jobs processed");
  }

  std::iostream& StressJob::getStream()
  {
    if (!init)
    {
      if (count % 100000 == 0)
        usleep(1000000);
      queue.put(new StressJob(queue, url));
      init = true;
    }
    return client;
  }

  int StressJob::getFd() const
  {
    return 0;
  }

  void StressJob::setRead()
  {
  }

  void StressJob::setWrite()
  {
  }

}
<|endoftext|>