<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ppapi/shared_impl/audio_impl.h"

#include "base/logging.h"

namespace ppapi {

AudioImpl::AudioImpl()
    : playing_(false),
      shared_memory_size_(0),
      callback_(NULL),
      user_data_(NULL) {
}

AudioImpl::~AudioImpl() {
  // Closing the socket causes the thread to exit - wait for it.
  if (socket_.get())
    socket_->Close();
  if (audio_thread_.get()) {
    audio_thread_->Join();
    audio_thread_.reset();
  }
}

::ppapi::thunk::PPB_Audio_API* AudioImpl::AsPPB_Audio_API() {
  return this;
}

void AudioImpl::SetCallback(PPB_Audio_Callback callback, void* user_data) {
  callback_ = callback;
  user_data_ = user_data;
}

void AudioImpl::SetStartPlaybackState() {
  DCHECK(!playing_);
  DCHECK(!audio_thread_.get());

  // If the socket doesn't exist, that means that the plugin has started before
  // the browser has had a chance to create all the shared memory info and
  // notify us. This is a common case. In this case, we just set the playing_
  // flag and the playback will automatically start when that data is available
  // in SetStreamInfo.
  if (callback_ && socket_.get())
    StartThread();
  playing_ = true;
}

void AudioImpl::SetStopPlaybackState() {
  DCHECK(playing_);

  if (audio_thread_.get()) {
    audio_thread_->Join();
    audio_thread_.reset();
  }
  playing_ = false;
}

void AudioImpl::SetStreamInfo(base::SharedMemoryHandle shared_memory_handle,
                              size_t shared_memory_size,
                              base::SyncSocket::Handle socket_handle) {
  socket_.reset(new base::SyncSocket(socket_handle));
  shared_memory_.reset(new base::SharedMemory(shared_memory_handle, false));
  shared_memory_size_ = shared_memory_size;

  if (callback_) {
    shared_memory_->Map(shared_memory_size_);

    // In common case StartPlayback() was called before StreamCreated().
    if (playing_)
      StartThread();
  }
}

void AudioImpl::StartThread() {
  DCHECK(callback_);
  DCHECK(!audio_thread_.get());
  audio_thread_.reset(new base::DelegateSimpleThread(
      this, "plugin_audio_thread"));
  audio_thread_->Start();
}

void AudioImpl::Run() {
  int pending_data;
  void* buffer = shared_memory_->memory();

  while (sizeof(pending_data) ==
      socket_->Receive(&pending_data, sizeof(pending_data)) &&
      pending_data >= 0) {
    callback_(buffer, shared_memory_size_, user_data_);
  }
}

}  // namespace ppapi
<commit_msg>Prepare ppapi for chrome audio changes. Now chrome writes length of audio data to buffers, thus allowing to correctly handle short audio streams (e.g. sound effects in games).<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ppapi/shared_impl/audio_impl.h"

#include "base/atomicops.h"
#include "base/logging.h"

using base::subtle::Atomic32;

namespace ppapi {

AudioImpl::AudioImpl()
    : playing_(false),
      shared_memory_size_(0),
      callback_(NULL),
      user_data_(NULL) {
}

AudioImpl::~AudioImpl() {
  // Closing the socket causes the thread to exit - wait for it.
  if (socket_.get())
    socket_->Close();
  if (audio_thread_.get()) {
    audio_thread_->Join();
    audio_thread_.reset();
  }
}

::ppapi::thunk::PPB_Audio_API* AudioImpl::AsPPB_Audio_API() {
  return this;
}

void AudioImpl::SetCallback(PPB_Audio_Callback callback, void* user_data) {
  callback_ = callback;
  user_data_ = user_data;
}

void AudioImpl::SetStartPlaybackState() {
  DCHECK(!playing_);
  DCHECK(!audio_thread_.get());

  // If the socket doesn't exist, that means that the plugin has started before
  // the browser has had a chance to create all the shared memory info and
  // notify us. This is a common case. In this case, we just set the playing_
  // flag and the playback will automatically start when that data is available
  // in SetStreamInfo.
  if (callback_ && socket_.get())
    StartThread();
  playing_ = true;
}

void AudioImpl::SetStopPlaybackState() {
  DCHECK(playing_);

  if (audio_thread_.get()) {
    audio_thread_->Join();
    audio_thread_.reset();
  }
  playing_ = false;
}

void AudioImpl::SetStreamInfo(base::SharedMemoryHandle shared_memory_handle,
                              size_t shared_memory_size,
                              base::SyncSocket::Handle socket_handle) {
  socket_.reset(new base::SyncSocket(socket_handle));
  shared_memory_.reset(new base::SharedMemory(shared_memory_handle, false));
  shared_memory_size_ = shared_memory_size;

  if (callback_) {
    shared_memory_->Map(shared_memory_size_);

    // In common case StartPlayback() was called before StreamCreated().
    if (playing_)
      StartThread();
  }
}

void AudioImpl::StartThread() {
  DCHECK(callback_);
  DCHECK(!audio_thread_.get());
  audio_thread_.reset(new base::DelegateSimpleThread(
      this, "plugin_audio_thread"));
  audio_thread_->Start();
}

// PPB_AudioBuffersState defines the type of an audio buffer state structure
// sent when requesting to fill the audio buffer with data.
typedef struct {
  int pending_bytes;
  int hardware_delay_bytes;
  uint64_t timestamp;
} PPB_AudioBuffersState;
PP_COMPILE_ASSERT_SIZE_IN_BYTES(PPB_AudioBuffersState, 16);

void AudioImpl::Run() {
  PPB_AudioBuffersState buffer_state;

  for (;;) {
    int bytes_received = socket_->Receive(&buffer_state, sizeof(buffer_state));
    if (bytes_received == sizeof(int)) {
      // Accoding to C++ Standard, address of structure == address of its first
      // member, so it is safe to use buffer_state.bytes_received when we
      // receive just one int.
      COMPILE_ASSERT(
          offsetof(PPB_AudioBuffersState, pending_bytes) == 0,
          pending_bytes_should_be_first_member_of_PPB_AudioBuffersState);
      if (buffer_state.pending_bytes < 0)
        break;
      callback_(shared_memory_->memory(), shared_memory_size_, user_data_);
    } else if (bytes_received == sizeof(buffer_state)) {
      if (buffer_state.pending_bytes + buffer_state.hardware_delay_bytes < 0)
        break;

      // Assert that shared memory is properly aligned, so we can cast pointer
      // to the pointer to Atomic32.
      DCHECK_EQ(0u, reinterpret_cast<size_t>(shared_memory_->memory()) & 3);

      // TODO(enal): Instead of address arithmetics use functions that
      // encapsulate internal buffer structure. They should be moved somewhere
      // into ppapi, right now they are defined in media/audio/audio_util.h.
      uint32 data_size = shared_memory_size_ - sizeof(Atomic32);
      callback_(static_cast<char*>(shared_memory_->memory()) + sizeof(Atomic32),
                data_size,
                user_data_);
      base::subtle::Release_Store(
          static_cast<volatile Atomic32*>(shared_memory_->memory()),
          data_size);
    } else {
      break;
    }
  }
}

}  // namespace ppapi
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef itkTransformToStrainFilter_hxx
#define itkTransformToStrainFilter_hxx

#include "itkImageRegionIteratorWithIndex.h"
#include "itkTransformToStrainFilter.h"

namespace itk
{

template < typename TTransform, typename TOperatorValue,
           typename TOutputValue >
TransformToStrainFilter< TTransform, TOperatorValue, TOutputValue >
::TransformToStrainFilter():
  m_StrainForm( INFINITESIMAL )
{
}

template < typename TTransform, typename TOperatorValue,
           typename TOutputValue >
void
TransformToStrainFilter< TTransform, TOperatorValue, TOutputValue >
::BeforeThreadedGenerateData()
{
  OutputImageType * output = this->GetOutput();
  output->FillBuffer( NumericTraits< OutputPixelType >::Zero );

  const TransformType * input = this->GetTransform();
  if( input == ITK_NULLPTR )
    {
    itkExceptionMacro( "Input transform not available!" );
    }

  const StrainFormType strainForm = this->GetStrainForm();
  if( strainForm != INFINITESIMAL && strainForm != GREENLAGRANGIAN && strainForm != EULERIANALMANSI )
    {
    itkExceptionMacro( "Invalid StrainForm!" );
    }
}

template < typename TTransform, typename TOperatorValue,
           typename TOutputValue >
void
TransformToStrainFilter< TTransform, TOperatorValue, TOutputValue >
::ThreadedGenerateData( const OutputRegionType& region,
                        ThreadIdType itkNotUsed( threadId ) )
{
  const TransformType * input = this->GetTransform();

  OutputImageType * output = this->GetOutput();
  typedef ImageRegionIteratorWithIndex< OutputImageType > ImageIteratorType;
  ImageIteratorType outputIt( output, region );

  typename TransformType::JacobianType identity;
  identity.SetSize( ImageDimension, ImageDimension );
  identity.Fill( 0.0 );
  for( unsigned int i = 0; i < ImageDimension; ++i )
    {
    identity.SetElement( i, i, 1.0);
    }

  // e_ij += 1/2( du_i/dx_j + du_j/dx_i )
  for( outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt )
    {
    const typename OutputImageType::IndexType index = outputIt.GetIndex();
    typename OutputImageType::PointType point;
    output->TransformIndexToPhysicalPoint( index, point );
    typename TransformType::JacobianType jacobian;
    input->ComputeJacobianWithRespectToPosition( point, jacobian );
    typename OutputImageType::PixelType outputPixel = outputIt.Get();
    for( unsigned int i = 0; i < ImageDimension; ++i )
      {
      for( unsigned int j = 0; j < i; ++j )
        {
        outputPixel( i, j ) += jacobian( i, j ) / static_cast< TOutputValue >( 2 );
        }
      for( unsigned int j = i + 1; j < ImageDimension; ++j )
        {
        outputPixel( i, j ) += jacobian( i, j ) / static_cast< TOutputValue >( 2 );
        }
      outputPixel( i, i ) = jacobian( i, i ) - static_cast< TOutputValue >( 1 );
      }
    outputIt.Set( outputPixel );
    }
  switch( m_StrainForm )
    {
  case INFINITESIMAL:
      break;
  // e_ij += 1/2 du_m/du_i du_m/du_j
  case GREENLAGRANGIAN:
    for( outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt )
      {
      const typename OutputImageType::IndexType index = outputIt.GetIndex();
      typename OutputImageType::PointType point;
      output->TransformIndexToPhysicalPoint( index, point );
      typename TransformType::JacobianType jacobian;
      input->ComputeJacobianWithRespectToPosition( point, jacobian );
      jacobian -= identity;
      typename OutputImageType::PixelType outputPixel = outputIt.Get();
      for( unsigned int i = 0; i < ImageDimension; ++i )
        {
        for( unsigned int j = 0; j < ImageDimension; ++j )
          {
          for( unsigned int k = 0; k <= j; ++k )
            {
            outputPixel( j, k ) += jacobian( i, j ) * jacobian( i, k ) / static_cast< TOutputValue >( 2 );
            }
          }
        }
      outputIt.Set( outputPixel );
      }
      break;
  // e_ij -= 1/2 du_m/du_i du_m/du_j
  case EULERIANALMANSI:
    for( outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt )
      {
      const typename OutputImageType::IndexType index = outputIt.GetIndex();
      typename OutputImageType::PointType point;
      output->TransformIndexToPhysicalPoint( index, point );
      typename TransformType::JacobianType jacobian;
      input->ComputeJacobianWithRespectToPosition( point, jacobian );
      jacobian -= identity;
      typename OutputImageType::PixelType outputPixel = outputIt.Get();
      for( unsigned int i = 0; i < ImageDimension; ++i )
        {
        for( unsigned int j = 0; j < ImageDimension; ++j )
          {
          for( unsigned int k = 0; k <= j; ++k )
            {
            outputPixel( j, k ) -= jacobian( i, j ) * jacobian( i, k ) / static_cast< TOutputValue >( 2 );
            }
          }
        }
      outputIt.Set( outputPixel );
      }
      break;
  default:
    itkExceptionMacro( << "Unknown strain form." );
    }
}

template < typename TTransform, typename TOperatorValue,
           typename TOutputValue >
void
TransformToStrainFilter< TTransform, TOperatorValue, TOutputValue >
::PrintSelf( std::ostream & os, Indent indent ) const
{
  Superclass::PrintSelf( os, indent );

  os << indent << "StrainForm: "
    << static_cast< typename NumericTraits< StrainFormType >::PrintType >( m_StrainForm )
    << std::endl;
}
} // end namespace itk

#endif
<commit_msg>COMP:  Use C++11 nullptr directly<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef itkTransformToStrainFilter_hxx
#define itkTransformToStrainFilter_hxx

#include "itkImageRegionIteratorWithIndex.h"
#include "itkTransformToStrainFilter.h"

namespace itk
{

template < typename TTransform, typename TOperatorValue,
           typename TOutputValue >
TransformToStrainFilter< TTransform, TOperatorValue, TOutputValue >
::TransformToStrainFilter():
  m_StrainForm( INFINITESIMAL )
{
}

template < typename TTransform, typename TOperatorValue,
           typename TOutputValue >
void
TransformToStrainFilter< TTransform, TOperatorValue, TOutputValue >
::BeforeThreadedGenerateData()
{
  OutputImageType * output = this->GetOutput();
  output->FillBuffer( NumericTraits< OutputPixelType >::Zero );

  const TransformType * input = this->GetTransform();
  if( input == nullptr )
    {
    itkExceptionMacro( "Input transform not available!" );
    }

  const StrainFormType strainForm = this->GetStrainForm();
  if( strainForm != INFINITESIMAL && strainForm != GREENLAGRANGIAN && strainForm != EULERIANALMANSI )
    {
    itkExceptionMacro( "Invalid StrainForm!" );
    }
}

template < typename TTransform, typename TOperatorValue,
           typename TOutputValue >
void
TransformToStrainFilter< TTransform, TOperatorValue, TOutputValue >
::ThreadedGenerateData( const OutputRegionType& region,
                        ThreadIdType itkNotUsed( threadId ) )
{
  const TransformType * input = this->GetTransform();

  OutputImageType * output = this->GetOutput();
  typedef ImageRegionIteratorWithIndex< OutputImageType > ImageIteratorType;
  ImageIteratorType outputIt( output, region );

  typename TransformType::JacobianType identity;
  identity.SetSize( ImageDimension, ImageDimension );
  identity.Fill( 0.0 );
  for( unsigned int i = 0; i < ImageDimension; ++i )
    {
    identity.SetElement( i, i, 1.0);
    }

  // e_ij += 1/2( du_i/dx_j + du_j/dx_i )
  for( outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt )
    {
    const typename OutputImageType::IndexType index = outputIt.GetIndex();
    typename OutputImageType::PointType point;
    output->TransformIndexToPhysicalPoint( index, point );
    typename TransformType::JacobianType jacobian;
    input->ComputeJacobianWithRespectToPosition( point, jacobian );
    typename OutputImageType::PixelType outputPixel = outputIt.Get();
    for( unsigned int i = 0; i < ImageDimension; ++i )
      {
      for( unsigned int j = 0; j < i; ++j )
        {
        outputPixel( i, j ) += jacobian( i, j ) / static_cast< TOutputValue >( 2 );
        }
      for( unsigned int j = i + 1; j < ImageDimension; ++j )
        {
        outputPixel( i, j ) += jacobian( i, j ) / static_cast< TOutputValue >( 2 );
        }
      outputPixel( i, i ) = jacobian( i, i ) - static_cast< TOutputValue >( 1 );
      }
    outputIt.Set( outputPixel );
    }
  switch( m_StrainForm )
    {
  case INFINITESIMAL:
      break;
  // e_ij += 1/2 du_m/du_i du_m/du_j
  case GREENLAGRANGIAN:
    for( outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt )
      {
      const typename OutputImageType::IndexType index = outputIt.GetIndex();
      typename OutputImageType::PointType point;
      output->TransformIndexToPhysicalPoint( index, point );
      typename TransformType::JacobianType jacobian;
      input->ComputeJacobianWithRespectToPosition( point, jacobian );
      jacobian -= identity;
      typename OutputImageType::PixelType outputPixel = outputIt.Get();
      for( unsigned int i = 0; i < ImageDimension; ++i )
        {
        for( unsigned int j = 0; j < ImageDimension; ++j )
          {
          for( unsigned int k = 0; k <= j; ++k )
            {
            outputPixel( j, k ) += jacobian( i, j ) * jacobian( i, k ) / static_cast< TOutputValue >( 2 );
            }
          }
        }
      outputIt.Set( outputPixel );
      }
      break;
  // e_ij -= 1/2 du_m/du_i du_m/du_j
  case EULERIANALMANSI:
    for( outputIt.GoToBegin(); !outputIt.IsAtEnd(); ++outputIt )
      {
      const typename OutputImageType::IndexType index = outputIt.GetIndex();
      typename OutputImageType::PointType point;
      output->TransformIndexToPhysicalPoint( index, point );
      typename TransformType::JacobianType jacobian;
      input->ComputeJacobianWithRespectToPosition( point, jacobian );
      jacobian -= identity;
      typename OutputImageType::PixelType outputPixel = outputIt.Get();
      for( unsigned int i = 0; i < ImageDimension; ++i )
        {
        for( unsigned int j = 0; j < ImageDimension; ++j )
          {
          for( unsigned int k = 0; k <= j; ++k )
            {
            outputPixel( j, k ) -= jacobian( i, j ) * jacobian( i, k ) / static_cast< TOutputValue >( 2 );
            }
          }
        }
      outputIt.Set( outputPixel );
      }
      break;
  default:
    itkExceptionMacro( << "Unknown strain form." );
    }
}

template < typename TTransform, typename TOperatorValue,
           typename TOutputValue >
void
TransformToStrainFilter< TTransform, TOperatorValue, TOutputValue >
::PrintSelf( std::ostream & os, Indent indent ) const
{
  Superclass::PrintSelf( os, indent );

  os << indent << "StrainForm: "
    << static_cast< typename NumericTraits< StrainFormType >::PrintType >( m_StrainForm )
    << std::endl;
}
} // end namespace itk

#endif
<|endoftext|>


<commit_before>#pragma once

#include <mtao/types.hpp>

namespace mtao::geometry::trigonometry {

    // pushes an angle to the range [0,2*M_PI)
    template <typename S>
    S angle_clamp_positive(S ang) {
        while(ang > 2* M_PI) {
            ang -= 2 * M_PI;
        }
        while(ang < 0) {
            ang += 2*M_PI;
        }
        return ang;
    }
    // pushes an angle to the range [-M_PI,M_PI)
    template <typename S>
    S angle_clamp_pi(S ang) {
        while(ang > M_PI) {
            ang -= 2 * M_PI;
        }
        while(ang < -M_PI) {
            ang += 2*M_PI;
        }
        return ang;
    }
    // Returns the angle between a vector and [1,0]^*
    template <typename S>
        S angle_scalar(S x, S y) {
            return angle_clamp_positive(std::atan2(y,x));
        }

    // Returns the angle for each vector in a ColVector and returns a rowvector
    template <typename Derived>
        auto angle(const Eigen::MatrixBase<Derived>& P) {
            using S = typename Derived::Scalar;
            Eigen::Matrix<S,1,Derived::ColsAtCompileTime> A(1,P.cols());

            A = P.row(0).binaryExpr(P.row(1), std::function(angle_scalar<S>));
            return A;
        }

    // Returns the angle of between each col from A to B clockwise
    template <typename Derived, typename Derived1>
        auto angle(const Eigen::MatrixBase<Derived>& A, const Eigen::MatrixBase<Derived1>& B) {
            using S = typename Derived::Scalar;
            auto R = (angle(B) - angle(A)).eval();
            R.noalias() = R.unaryExpr(std::function(angle_clamp_positive<S>));
            return R;
        }

    // The interior angle of a polygon with size vertices/edges
    template <typename T = double>
        T interior_angle_sum(int size) {
            return  M_PI * ( size - 2);
        }
    // The exterior angle of a polygon with size vertices/edges
    template <typename T = double>
        T exterior_angle_sum(int size) {
            return  M_PI * ( size + 2);
        }

    // The sum of angles generated by a collection of points.
    // Should be equal to interior_angle_sum(n) or exterior_angle_sum(n)
    // for n = std::distance(beginit,endit)
    template <typename Derived,typename BeginIt, typename EndIt>
        typename Derived::Scalar angle_sum(const Eigen::MatrixBase<Derived>& V, const BeginIt& beginit, const EndIt& endit) {
            using S = typename Derived::Scalar;
            S ang_sum = 0;
            for(auto it = beginit; it != endit; ++it) {
                auto it1 = it;
                it1++;
                if(it1 == endit) { it1 = beginit; }
                auto it2 = it1;
                it2++;
                if(it2 == endit) { it2 = beginit; }
                auto a = V.col(*it);
                auto b = V.col(*it1);
                auto c = V.col(*it2);
                double ang = angle(c-b,a-b)(0);
                ang_sum += ang;
            }

            return ang_sum;
        }
    template <typename Derived,typename Container>
        auto angle_sum(const Eigen::MatrixBase<Derived>& V, const Container& C) {
            return angle_sum(V,C.begin(),C.end());
        }
    template <typename Derived,typename T = int>
        auto angle_sum(const Eigen::MatrixBase<Derived>& V, const std::initializer_list<T>& C) {
            return angle_sum(V,C.begin(),C.end());
        }

    template <typename Derived,typename BeginIt, typename EndIt>
        bool clockwise_cell(const Eigen::MatrixBase<Derived>& V, const BeginIt& beginit, const EndIt& endit) {

            using S = typename Derived::Scalar;
            int size =  std::distance(beginit,endit);
            S ang = angle_sum(V,beginit,endit);

            /*
            //counteract size when we have degenerate cells
            for(auto it = beginit; it != endit; ++it) {
                auto it1 = it;
                it1++;
                if(it1 == endit) { it1 = beginit; }
                auto it2 = it1;
                it2++;
                if(it2 == endit) { it2 = beginit; }
                    auto a = V.col(*it);
                    auto b = V.col(*it1);
                    auto c = V.col(*it2);
                    double ang = angle(c-b,a-b)(0);
            }
            */
            S expected=  interior_angle_sum<S>(size);
            bool ret = std::abs(ang - expected) < 1e-5;

            if(ret) {
                assert(std::abs(ang-exterior_angle_sum<S>(size)) > 1e-5);
            } else {
                assert(std::abs(ang-exterior_angle_sum<S>(size)) < 1e-5);
            }
            return ret;
        }
    template <typename Derived,typename Container>
        auto clockwise_cell(const Eigen::MatrixBase<Derived>& V, const Container& C) {
            return clockwise_cell(V,C.begin(),C.end());
        }
    template <typename Derived,typename T = int>
        auto clockwise_cell(const Eigen::MatrixBase<Derived>& V, const std::initializer_list<T>& C) {
            return clockwise_cell(V,C.begin(),C.end());
        }
}
<commit_msg>fixing a mysterious issue noticed on osx with binaryexpr<commit_after>#pragma once

#include <mtao/types.hpp>

namespace mtao::geometry::trigonometry {

    // pushes an angle to the range [0,2*M_PI)
    template <typename S>
    S angle_clamp_positive(S ang) {
        while(ang > 2* M_PI) {
            ang -= 2 * M_PI;
        }
        while(ang < 0) {
            ang += 2*M_PI;
        }
        return ang;
    }
    // pushes an angle to the range [-M_PI,M_PI)
    template <typename S>
    S angle_clamp_pi(S ang) {
        while(ang > M_PI) {
            ang -= 2 * M_PI;
        }
        while(ang < -M_PI) {
            ang += 2*M_PI;
        }
        return ang;
    }
    // Returns the angle between a vector and [1,0]^*
    template <typename S>
        S angle_scalar(S x, S y) {
            return angle_clamp_positive(std::atan2(y,x));
        }

    // Returns the angle for each vector in a ColVector and returns a rowvector
    template <typename Derived>
        auto angle(const Eigen::MatrixBase<Derived>& P) {
            using S = typename Derived::Scalar;
            Eigen::Matrix<S,1,Derived::ColsAtCompileTime> A(1,P.cols());

#ifdef TODO_CHECK_WHEN_THIS_IS_OK
            A = P.row(0).binaryExpr(P.row(1), std::function(angle_scalar<S>));
#else
            auto a = P.row(0);
            auto b = P.row(1);
            for(int i = 0; i < P.cols(); ++i) {
                A(i) = angle_scalar<S>(a(i),b(i));
            }
#endif
            return A;
        }

    // Returns the angle of between each col from A to B clockwise
    template <typename Derived, typename Derived1>
        auto angle(const Eigen::MatrixBase<Derived>& A, const Eigen::MatrixBase<Derived1>& B) {
            using S = typename Derived::Scalar;
            auto R = (angle(B) - angle(A)).eval();
            R.noalias() = R.unaryExpr(std::function(angle_clamp_positive<S>));
            return R;
        }

    // The interior angle of a polygon with size vertices/edges
    template <typename T = double>
        T interior_angle_sum(int size) {
            return  M_PI * ( size - 2);
        }
    // The exterior angle of a polygon with size vertices/edges
    template <typename T = double>
        T exterior_angle_sum(int size) {
            return  M_PI * ( size + 2);
        }

    // The sum of angles generated by a collection of points.
    // Should be equal to interior_angle_sum(n) or exterior_angle_sum(n)
    // for n = std::distance(beginit,endit)
    template <typename Derived,typename BeginIt, typename EndIt>
        typename Derived::Scalar angle_sum(const Eigen::MatrixBase<Derived>& V, const BeginIt& beginit, const EndIt& endit) {
            using S = typename Derived::Scalar;
            S ang_sum = 0;
            for(auto it = beginit; it != endit; ++it) {
                auto it1 = it;
                it1++;
                if(it1 == endit) { it1 = beginit; }
                auto it2 = it1;
                it2++;
                if(it2 == endit) { it2 = beginit; }
                auto a = V.col(*it);
                auto b = V.col(*it1);
                auto c = V.col(*it2);
                double ang = angle(c-b,a-b)(0);
                ang_sum += ang;
            }

            return ang_sum;
        }
    template <typename Derived,typename Container>
        auto angle_sum(const Eigen::MatrixBase<Derived>& V, const Container& C) {
            return angle_sum(V,C.begin(),C.end());
        }
    template <typename Derived,typename T = int>
        auto angle_sum(const Eigen::MatrixBase<Derived>& V, const std::initializer_list<T>& C) {
            return angle_sum(V,C.begin(),C.end());
        }

    template <typename Derived,typename BeginIt, typename EndIt>
        bool clockwise_cell(const Eigen::MatrixBase<Derived>& V, const BeginIt& beginit, const EndIt& endit) {

            using S = typename Derived::Scalar;
            int size =  std::distance(beginit,endit);
            S ang = angle_sum(V,beginit,endit);

            /*
            //counteract size when we have degenerate cells
            for(auto it = beginit; it != endit; ++it) {
                auto it1 = it;
                it1++;
                if(it1 == endit) { it1 = beginit; }
                auto it2 = it1;
                it2++;
                if(it2 == endit) { it2 = beginit; }
                    auto a = V.col(*it);
                    auto b = V.col(*it1);
                    auto c = V.col(*it2);
                    double ang = angle(c-b,a-b)(0);
            }
            */
            S expected=  interior_angle_sum<S>(size);
            bool ret = std::abs(ang - expected) < 1e-5;

            if(ret) {
                assert(std::abs(ang-exterior_angle_sum<S>(size)) > 1e-5);
            } else {
                assert(std::abs(ang-exterior_angle_sum<S>(size)) < 1e-5);
            }
            return ret;
        }
    template <typename Derived,typename Container>
        auto clockwise_cell(const Eigen::MatrixBase<Derived>& V, const Container& C) {
            return clockwise_cell(V,C.begin(),C.end());
        }
    template <typename Derived,typename T = int>
        auto clockwise_cell(const Eigen::MatrixBase<Derived>& V, const std::initializer_list<T>& C) {
            return clockwise_cell(V,C.begin(),C.end());
        }
}
<|endoftext|>


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

#include <vespa/eval/eval/fast_value.h>
#include <vespa/eval/eval/tensor_function.h>
#include <vespa/eval/eval/test/eval_fixture.h>
#include <vespa/eval/eval/test/tensor_model.hpp>
#include <vespa/vespalib/gtest/gtest.h>

using namespace vespalib::eval::operation;
using namespace vespalib::eval::tensor_function;
using namespace vespalib::eval::test;
using namespace vespalib::eval;
//using namespace vespalib;

const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get();

EvalFixture::ParamRepo make_params() {
    return EvalFixture::ParamRepo()
        .add("a", spec(1.5))
        .add("b", spec(2.5))
        .add("sparse", spec({x({"a","b"})}, N()))
        .add("mixed", spec({x({"a"}),y(5)}, N()))
        .add_matrix("x", 5, "y", 3);
}
EvalFixture::ParamRepo param_repo = make_params();

void verify_optimized(const vespalib::string &expr, op1_t op1, bool inplace = false) {
    EvalFixture slow_fixture(prod_factory, expr, param_repo, false);
    EvalFixture fixture(prod_factory, expr, param_repo, true, true);
    EXPECT_EQ(fixture.result(), EvalFixture::ref(expr, param_repo));
    EXPECT_EQ(fixture.result(), slow_fixture.result());
    auto info = fixture.find_all<tensor_function::Map>();
    ASSERT_EQ(info.size(), 1u);
    EXPECT_TRUE(info[0]->result_is_mutable());
    EXPECT_EQ(info[0]->function(), op1);
    ASSERT_EQ(fixture.num_params(), 1);
    if (inplace) {
        EXPECT_EQ(fixture.get_param(0), fixture.result());
    } else {
        EXPECT_TRUE(!(fixture.get_param(0) == fixture.result()));
    }
}

void verify_not_optimized(const vespalib::string &expr) {
    EvalFixture slow_fixture(prod_factory, expr, param_repo, false);
    EvalFixture fixture(prod_factory, expr, param_repo, true);
    EXPECT_EQ(fixture.result(), EvalFixture::ref(expr, param_repo));
    EXPECT_EQ(fixture.result(), slow_fixture.result());
    auto info = fixture.find_all<Map>();
    EXPECT_TRUE(info.empty());
}

TEST(PowAsMapTest, squared_dense_tensor_is_optimized) {
    verify_optimized("x5y3^2.0", Square::f);
    verify_optimized("pow(x5y3,2.0)", Square::f);
    verify_optimized("join(x5y3,2.0,f(x,y)(x^y))", Square::f);
    verify_optimized("join(x5y3,2.0,f(x,y)(pow(x,y)))", Square::f);
    verify_optimized("join(x5y3f,2.0,f(x,y)(pow(x,y)))", Square::f);
    verify_optimized("join(@x5y3,2.0,f(x,y)(pow(x,y)))", Square::f, true);
    verify_optimized("join(@x5y3f,2.0,f(x,y)(pow(x,y)))", Square::f, true);
}

TEST(PowAsMapTest, cubed_dense_tensor_is_optimized) {
    verify_optimized("x5y3^3.0", Cube::f);
    verify_optimized("pow(x5y3,3.0)", Cube::f);
    verify_optimized("join(x5y3,3.0,f(x,y)(x^y))", Cube::f);
    verify_optimized("join(x5y3,3.0,f(x,y)(pow(x,y)))", Cube::f);
    verify_optimized("join(x5y3f,3.0,f(x,y)(pow(x,y)))", Cube::f);
    verify_optimized("join(@x5y3,3.0,f(x,y)(pow(x,y)))", Cube::f, true);
    verify_optimized("join(@x5y3f,3.0,f(x,y)(pow(x,y)))", Cube::f, true);
}

TEST(PowAsMapTest, hypercubed_dense_tensor_is_not_optimized) {
    verify_not_optimized("join(x5y3,4.0,f(x,y)(pow(x,y)))");
}

TEST(PowAsMapTest, scalar_join_is_optimized) {
    verify_optimized("join(a,2.0,f(x,y)(pow(x,y)))", Square::f);
}

TEST(PowAsMapTest, sparse_join_is_optimized) {
    verify_optimized("join(sparse,2.0,f(x,y)(pow(x,y)))", Square::f);
}

TEST(PowAsMapTest, mixed_join_is_optimized) {
    verify_optimized("join(mixed,2.0,f(x,y)(pow(x,y)))", Square::f);
}

GTEST_MAIN_RUN_ALL_TESTS()
<commit_msg>use GenSpec in pow_as_map_optimizer_test<commit_after>// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/eval/eval/fast_value.h>
#include <vespa/eval/eval/tensor_function.h>
#include <vespa/eval/eval/test/eval_fixture.h>
#include <vespa/eval/eval/test/gen_spec.h>
#include <vespa/vespalib/gtest/gtest.h>

using namespace vespalib::eval::operation;
using namespace vespalib::eval::tensor_function;
using namespace vespalib::eval::test;
using namespace vespalib::eval;
//using namespace vespalib;

const ValueBuilderFactory &prod_factory = FastValueBuilderFactory::get();

TensorSpec spec(double v) { return TensorSpec("double").add({}, v); }

EvalFixture::ParamRepo make_params() {
    return EvalFixture::ParamRepo()
        .add("a", spec(1.5))
        .add("b", spec(2.5))
        .add("sparse", GenSpec().map("x", {"a","b"}).gen())
        .add("mixed", GenSpec().map("x", {"a"}).idx("y", 5).gen())
        .add_variants("x5y3", GenSpec().idx("x", 5).idx("y", 3));
}
EvalFixture::ParamRepo param_repo = make_params();

void verify_optimized(const vespalib::string &expr, op1_t op1, bool inplace = false) {
    EvalFixture slow_fixture(prod_factory, expr, param_repo, false);
    EvalFixture fixture(prod_factory, expr, param_repo, true, true);
    EXPECT_EQ(fixture.result(), EvalFixture::ref(expr, param_repo));
    EXPECT_EQ(fixture.result(), slow_fixture.result());
    auto info = fixture.find_all<tensor_function::Map>();
    ASSERT_EQ(info.size(), 1u);
    EXPECT_TRUE(info[0]->result_is_mutable());
    EXPECT_EQ(info[0]->function(), op1);
    ASSERT_EQ(fixture.num_params(), 1);
    if (inplace) {
        EXPECT_EQ(fixture.get_param(0), fixture.result());
    } else {
        EXPECT_TRUE(!(fixture.get_param(0) == fixture.result()));
    }
}

void verify_not_optimized(const vespalib::string &expr) {
    EvalFixture slow_fixture(prod_factory, expr, param_repo, false);
    EvalFixture fixture(prod_factory, expr, param_repo, true);
    EXPECT_EQ(fixture.result(), EvalFixture::ref(expr, param_repo));
    EXPECT_EQ(fixture.result(), slow_fixture.result());
    auto info = fixture.find_all<Map>();
    EXPECT_TRUE(info.empty());
}

TEST(PowAsMapTest, squared_dense_tensor_is_optimized) {
    verify_optimized("x5y3^2.0", Square::f);
    verify_optimized("pow(x5y3,2.0)", Square::f);
    verify_optimized("join(x5y3,2.0,f(x,y)(x^y))", Square::f);
    verify_optimized("join(x5y3,2.0,f(x,y)(pow(x,y)))", Square::f);
    verify_optimized("join(x5y3_f,2.0,f(x,y)(pow(x,y)))", Square::f);
    verify_optimized("join(@x5y3,2.0,f(x,y)(pow(x,y)))", Square::f, true);
    verify_optimized("join(@x5y3_f,2.0,f(x,y)(pow(x,y)))", Square::f, true);
}

TEST(PowAsMapTest, cubed_dense_tensor_is_optimized) {
    verify_optimized("x5y3^3.0", Cube::f);
    verify_optimized("pow(x5y3,3.0)", Cube::f);
    verify_optimized("join(x5y3,3.0,f(x,y)(x^y))", Cube::f);
    verify_optimized("join(x5y3,3.0,f(x,y)(pow(x,y)))", Cube::f);
    verify_optimized("join(x5y3_f,3.0,f(x,y)(pow(x,y)))", Cube::f);
    verify_optimized("join(@x5y3,3.0,f(x,y)(pow(x,y)))", Cube::f, true);
    verify_optimized("join(@x5y3_f,3.0,f(x,y)(pow(x,y)))", Cube::f, true);
}

TEST(PowAsMapTest, hypercubed_dense_tensor_is_not_optimized) {
    verify_not_optimized("join(x5y3,4.0,f(x,y)(pow(x,y)))");
}

TEST(PowAsMapTest, scalar_join_is_optimized) {
    verify_optimized("join(a,2.0,f(x,y)(pow(x,y)))", Square::f);
}

TEST(PowAsMapTest, sparse_join_is_optimized) {
    verify_optimized("join(sparse,2.0,f(x,y)(pow(x,y)))", Square::f);
}

TEST(PowAsMapTest, mixed_join_is_optimized) {
    verify_optimized("join(mixed,2.0,f(x,y)(pow(x,y)))", Square::f);
}

GTEST_MAIN_RUN_ALL_TESTS()
<|endoftext|>


<commit_before>//============================================================================
// vSMC/include/vsmc/internal/compiler/gcc.hpp
//----------------------------------------------------------------------------
//                         vSMC: Scalable Monte Carlo
//----------------------------------------------------------------------------
// Copyright (c) 2013-2015, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
//   Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================

#ifndef VSMC_INTERNAL_COMPILER_GCC_HPP
#define VSMC_INTERNAL_COMPILER_GCC_HPP

#define VSMC_GCC_NONEXIST 0xFFFFFFFFUL

#define VSMC_GCC_VERSION                                                      \
    (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)

#ifndef VSMC_INT64
#define VSMC_INT64 long long
#endif

#ifdef __x86_64__
#ifndef VSMC_HAS_INT128
#define VSMC_HAS_INT128 1
#endif
#ifndef VSMC_INT128
#define VSMC_INT128 __int128
#endif
#endif

#ifdef __AES__
#ifndef VSMC_HAS_AES_NI
#define VSMC_HAS_AES_NI 1
#endif
#endif

#ifdef __RDRND__
#ifndef VSMC_HAS_RDRAND
#define VSMC_HAS_RDRAND 1
#endif
#endif

#if VSMC_GCC_VERSION >= 50100
#ifndef VSMC_HAS_CILK
#define VSMC_HAS_CILK 1
#endif
#endif

#endif // VSMC_INTERNAL_COMPILER_GCC_HPP
<commit_msg>disable cilk on gcc<commit_after>//============================================================================
// vSMC/include/vsmc/internal/compiler/gcc.hpp
//----------------------------------------------------------------------------
//                         vSMC: Scalable Monte Carlo
//----------------------------------------------------------------------------
// Copyright (c) 2013-2015, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
//   Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================

#ifndef VSMC_INTERNAL_COMPILER_GCC_HPP
#define VSMC_INTERNAL_COMPILER_GCC_HPP

#define VSMC_GCC_NONEXIST 0xFFFFFFFFUL

#define VSMC_GCC_VERSION                                                      \
    (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)

#ifndef VSMC_INT64
#define VSMC_INT64 long long
#endif

#ifdef __x86_64__
#ifndef VSMC_HAS_INT128
#define VSMC_HAS_INT128 1
#endif
#ifndef VSMC_INT128
#define VSMC_INT128 __int128
#endif
#endif

#ifdef __AES__
#ifndef VSMC_HAS_AES_NI
#define VSMC_HAS_AES_NI 1
#endif
#endif

#ifdef __RDRND__
#ifndef VSMC_HAS_RDRAND
#define VSMC_HAS_RDRAND 1
#endif
#endif

#endif // VSMC_INTERNAL_COMPILER_GCC_HPP
<|endoftext|>


<commit_before>#include "opt/pipeline/pipeliner.h"

#include "design/design_tool.h"
#include "design/design_util.h"
#include "iroha/i_design.h"
#include "iroha/resource_class.h"
#include "opt/loop/loop_block.h"
#include "opt/optimizer_log.h"

namespace iroha {
namespace opt {
namespace pipeline {

Pipeliner::Pipeliner(ITable *tab, loop::LoopBlock *lb)
    : tab_(tab),
      lb_(lb),
      interval_(1),
      opt_log_(nullptr),
      prologue_st_(nullptr) {
  opt_log_ = tab->GetModule()->GetDesign()->GetOptimizerLog();
}

bool Pipeliner::Pipeline() {
  lb_->Annotate(opt_log_);
  ostream &os = opt_log_->GetDumpStream();
  int ns = lb_->GetStates().size();
  os << "Pipeliner " << lb_->GetStates().size() << " states, "
     << lb_->GetLoopCount() << " loop, interval=" << interval_ << "
";
  // prepare states.
  prologue_st_ = new IState(tab_);
  tab_->states_.push_back(prologue_st_);
  int plen = (ns + (ns - 1)) * interval_;
  for (int i = 0; i < plen; ++i) {
    IState *st = new IState(tab_);
    pipeline_st_.push_back(st);
    tab_->states_.push_back(st);
  }
  for (int i = 0; i < ns; ++i) {
    for (int j = 0; j <= i; ++j) {
      PlaceState(i, j);
    }
  }
  for (int i = 1; i < ns; ++i) {
    for (int j = i; j < ns; ++j) {
      PlaceState(i + ns - 1, j);
    }
  }
  SetupCounter();
  SetupCounterIncrement();
  ConnectPipelineState();
  SetupExit();
  ConnectPipeline();
  return true;
}

void Pipeliner::PlaceState(int pidx, int lidx) {
  IState *pst = pipeline_st_[pidx * interval_];
  ostream &os = opt_log_->State(pst);
  os << "[" << lidx << "]";
  IState *lst = lb_->GetStates().at(lidx);
  for (IInsn *insn : lst->insns_) {
    IResource *res = insn->GetResource();
    if (resource::IsTransition(*(res->GetClass()))) {
      continue;
    }
    IInsn *new_insn = new IInsn(res);
    new_insn->inputs_ = insn->inputs_;
    new_insn->outputs_ = insn->outputs_;
    pst->insns_.push_back(new_insn);
  }
}

void Pipeliner::ConnectPipelineState() {
  DesignTool::AddNextState(prologue_st_, pipeline_st_[0]);
  for (int i = 0; i < pipeline_st_.size() - 1; ++i) {
    IState *cur = pipeline_st_[i];
    IState *next = pipeline_st_[i + 1];
    DesignTool::AddNextState(cur, next);
  }
}

void Pipeliner::ConnectPipeline() {
  // To entry.
  IState *is = lb_->GetEntryAssignState();
  IInsn *einsn = DesignUtil::GetTransitionInsn(is);
  einsn->target_states_[0] = prologue_st_;
  // From last.
  IState *lst = pipeline_st_[pipeline_st_.size() - 1];
  IInsn *linsn = DesignUtil::GetTransitionInsn(lst);
  linsn->target_states_.push_back(lb_->GetExitState());
}

void Pipeliner::SetupCounter() {
  int llen = lb_->GetStates().size();
  IRegister *orig_counter = lb_->GetRegister();
  for (int i = 0; i < llen; ++i) {
    IRegister *counter =
        new IRegister(tab_, orig_counter->GetName() + "ps" + Util::Itoa(i));
    counter->value_type_ = orig_counter->value_type_;
    tab_->registers_.push_back(counter);
    counters_.push_back(counter);
  }
  IResource *assign = DesignUtil::FindAssignResource(tab_);
  for (int i = 0; i < llen * 2 - 1; ++i) {
    IState *st = pipeline_st_[i * interval_ + (interval_ - 1)];
    int start = 0;
    if (i >= llen) {
      start = i - llen + 1;
    }
    for (int j = start; j <= i; ++j) {
      if (j + 1 >= counters_.size()) {
        continue;
      }
      IInsn *insn = new IInsn(assign);
      st->insns_.push_back(insn);
      insn->inputs_.push_back(counters_[j]);
      insn->outputs_.push_back(counters_[j + 1]);
    }
  }
}

void Pipeliner::SetupCounterIncrement() {
  // Assign at the prologue.
  IInsn *insn = new IInsn(DesignUtil::FindAssignResource(tab_));
  IRegister *orig_counter = lb_->GetRegister();
  insn->inputs_.push_back(orig_counter);
  IRegister *counter0 = counters_[0];
  insn->outputs_.push_back(counter0);
  prologue_st_->insns_.push_back(insn);
  // Increment count0.
  int llen = lb_->GetStates().size();
  int cwidth = counter0->value_type_.GetWidth();
  IResource *adder = DesignUtil::CreateResource(tab_, resource::kAdd);
  adder->input_types_.push_back(counter0->value_type_);
  adder->input_types_.push_back(counter0->value_type_);
  adder->output_types_.push_back(counter0->value_type_);
  IRegister *one = DesignTool::AllocConstNum(tab_, cwidth, 1);
  for (int i = 0; i < llen; ++i) {
    IInsn *add_insn = new IInsn(adder);
    add_insn->inputs_.push_back(counter0);
    add_insn->inputs_.push_back(one);
    add_insn->outputs_.push_back(counter0);
    pipeline_st_[i * interval_ + (interval_ - 1)]->insns_.push_back(add_insn);
  }
}

void Pipeliner::SetupExit() {
  int llen = lb_->GetStates().size();
  IState *st = pipeline_st_[(llen - 1) * interval_ + (interval_ - 1)];
  IInsn *tr_insn = DesignUtil::GetTransitionInsn(st);
  tr_insn->target_states_.push_back(st);
  IRegister *cond = new IRegister(tab_, "cond_ps0");
  tab_->registers_.push_back(cond);
  tr_insn->inputs_.push_back(cond);

  IRegister *counter0 = counters_[0];
  int cwidth = counter0->value_type_.GetWidth();
  IRegister *max = DesignTool::AllocConstNum(tab_, cwidth, 1);
  IResource *comparator = DesignUtil::CreateResource(tab_, resource::kGt);
  comparator->input_types_.push_back(counter0->value_type_);
  comparator->input_types_.push_back(counter0->value_type_);
  IValueType o;
  o.SetWidth(0);
  comparator->output_types_.push_back(o);
  IInsn *compare = new IInsn(comparator);
  compare->outputs_.push_back(cond);
  compare->inputs_.push_back(max);
  compare->inputs_.push_back(counter0);
  st->insns_.push_back(compare);
}

}  // namespace pipeline
}  // namespace opt
}  // namespace iroha
<commit_msg>Fix loop exit condition.<commit_after>#include "opt/pipeline/pipeliner.h"

#include "design/design_tool.h"
#include "design/design_util.h"
#include "iroha/i_design.h"
#include "iroha/resource_class.h"
#include "opt/loop/loop_block.h"
#include "opt/optimizer_log.h"

namespace iroha {
namespace opt {
namespace pipeline {

Pipeliner::Pipeliner(ITable *tab, loop::LoopBlock *lb)
    : tab_(tab),
      lb_(lb),
      interval_(1),
      opt_log_(nullptr),
      prologue_st_(nullptr) {
  opt_log_ = tab->GetModule()->GetDesign()->GetOptimizerLog();
}

bool Pipeliner::Pipeline() {
  lb_->Annotate(opt_log_);
  ostream &os = opt_log_->GetDumpStream();
  int ns = lb_->GetStates().size();
  os << "Pipeliner " << lb_->GetStates().size() << " states, "
     << lb_->GetLoopCount() << " loop, interval=" << interval_ << "
";
  // prepare states.
  prologue_st_ = new IState(tab_);
  tab_->states_.push_back(prologue_st_);
  int plen = (ns + (ns - 1)) * interval_;
  for (int i = 0; i < plen; ++i) {
    IState *st = new IState(tab_);
    pipeline_st_.push_back(st);
    tab_->states_.push_back(st);
  }
  for (int i = 0; i < ns; ++i) {
    for (int j = 0; j <= i; ++j) {
      PlaceState(i, j);
    }
  }
  for (int i = 1; i < ns; ++i) {
    for (int j = i; j < ns; ++j) {
      PlaceState(i + ns - 1, j);
    }
  }
  SetupCounter();
  SetupCounterIncrement();
  ConnectPipelineState();
  SetupExit();
  ConnectPipeline();
  return true;
}

void Pipeliner::PlaceState(int pidx, int lidx) {
  IState *pst = pipeline_st_[pidx * interval_];
  ostream &os = opt_log_->State(pst);
  os << "[" << lidx << "]";
  IState *lst = lb_->GetStates().at(lidx);
  for (IInsn *insn : lst->insns_) {
    IResource *res = insn->GetResource();
    if (resource::IsTransition(*(res->GetClass()))) {
      continue;
    }
    IInsn *new_insn = new IInsn(res);
    new_insn->inputs_ = insn->inputs_;
    new_insn->outputs_ = insn->outputs_;
    pst->insns_.push_back(new_insn);
  }
}

void Pipeliner::ConnectPipelineState() {
  DesignTool::AddNextState(prologue_st_, pipeline_st_[0]);
  for (int i = 0; i < pipeline_st_.size() - 1; ++i) {
    IState *cur = pipeline_st_[i];
    IState *next = pipeline_st_[i + 1];
    DesignTool::AddNextState(cur, next);
  }
}

void Pipeliner::ConnectPipeline() {
  // To entry.
  IState *is = lb_->GetEntryAssignState();
  IInsn *einsn = DesignUtil::GetTransitionInsn(is);
  einsn->target_states_[0] = prologue_st_;
  // From last.
  IState *lst = pipeline_st_[pipeline_st_.size() - 1];
  IInsn *linsn = DesignUtil::GetTransitionInsn(lst);
  linsn->target_states_.push_back(lb_->GetExitState());
}

void Pipeliner::SetupCounter() {
  int llen = lb_->GetStates().size();
  IRegister *orig_counter = lb_->GetRegister();
  for (int i = 0; i < llen; ++i) {
    IRegister *counter =
        new IRegister(tab_, orig_counter->GetName() + "ps" + Util::Itoa(i));
    counter->value_type_ = orig_counter->value_type_;
    tab_->registers_.push_back(counter);
    counters_.push_back(counter);
  }
  IResource *assign = DesignUtil::FindAssignResource(tab_);
  for (int i = 0; i < llen * 2 - 1; ++i) {
    IState *st = pipeline_st_[i * interval_ + (interval_ - 1)];
    int start = 0;
    if (i >= llen) {
      start = i - llen + 1;
    }
    for (int j = start; j <= i; ++j) {
      if (j + 1 >= counters_.size()) {
        continue;
      }
      IInsn *insn = new IInsn(assign);
      st->insns_.push_back(insn);
      insn->inputs_.push_back(counters_[j]);
      insn->outputs_.push_back(counters_[j + 1]);
    }
  }
}

void Pipeliner::SetupCounterIncrement() {
  // Assign at the prologue.
  IInsn *insn = new IInsn(DesignUtil::FindAssignResource(tab_));
  IRegister *orig_counter = lb_->GetRegister();
  insn->inputs_.push_back(orig_counter);
  IRegister *counter0 = counters_[0];
  insn->outputs_.push_back(counter0);
  prologue_st_->insns_.push_back(insn);
  // Increment count0.
  int llen = lb_->GetStates().size();
  int cwidth = counter0->value_type_.GetWidth();
  IResource *adder = DesignUtil::CreateResource(tab_, resource::kAdd);
  adder->input_types_.push_back(counter0->value_type_);
  adder->input_types_.push_back(counter0->value_type_);
  adder->output_types_.push_back(counter0->value_type_);
  IRegister *one = DesignTool::AllocConstNum(tab_, cwidth, 1);
  for (int i = 0; i < llen; ++i) {
    IInsn *add_insn = new IInsn(adder);
    add_insn->inputs_.push_back(counter0);
    add_insn->inputs_.push_back(one);
    add_insn->outputs_.push_back(counter0);
    pipeline_st_[i * interval_ + (interval_ - 1)]->insns_.push_back(add_insn);
  }
}

void Pipeliner::SetupExit() {
  int llen = lb_->GetStates().size();
  IState *st = pipeline_st_[(llen - 1) * interval_ + (interval_ - 1)];
  IInsn *tr_insn = DesignUtil::GetTransitionInsn(st);
  tr_insn->target_states_.push_back(st);
  IRegister *cond = new IRegister(tab_, "cond_ps0");
  cond->SetStateLocal(true);
  tab_->registers_.push_back(cond);
  tr_insn->inputs_.push_back(cond);

  IRegister *counter0 = counters_[0];
  int cwidth = counter0->value_type_.GetWidth();
  IRegister *max = DesignTool::AllocConstNum(tab_, cwidth, lb_->GetLoopCount());
  IResource *comparator = DesignUtil::CreateResource(tab_, resource::kGt);
  comparator->input_types_.push_back(counter0->value_type_);
  comparator->input_types_.push_back(counter0->value_type_);
  IValueType o;
  o.SetWidth(0);
  comparator->output_types_.push_back(o);
  IInsn *compare = new IInsn(comparator);
  compare->outputs_.push_back(cond);
  compare->inputs_.push_back(max);
  compare->inputs_.push_back(counter0);
  st->insns_.push_back(compare);
}

}  // namespace pipeline
}  // namespace opt
}  // namespace iroha
<|endoftext|>


<commit_before>/*
 * percival_global_params.cpp
 *
 *  Created on: 31 Jul 2015
 *      Author: pqm78245
 */
#include <cstdlib>
#include "percival_processing.h"

//image height, image width, total frame number, default file locations, calibration height, calibration width, rotated?

bool percival_global_params::is_initialised = false;
bool percival_global_params::is_initialised_every_member[255] = {};
unsigned int percival_global_params::total_number_of_frames;
unsigned int percival_global_params::frame_height;
unsigned int percival_global_params::frame_width;
std::string percival_global_params::default_path_name;
std::string percival_global_params::default_data_set_name;
bool percival_global_params::is_transposed_calib_params;
unsigned int percival_global_params::calib_params_height;
unsigned int percival_global_params::calib_params_width;
std::string percival_global_params::default_location_Gc;
std::string percival_global_params::default_location_Gf;
std::string percival_global_params::default_location_Oc;
std::string percival_global_params::default_location_Of;
std::string percival_global_params::default_location_ADU_to_electrons_conversion;
std::string percival_global_params::default_calib_params_dataset_name;

percival_global_params::percival_global_params(const std::string & master_param_file){
		percival_global_params::initialisation(master_param_file);
}

percival_global_params::percival_global_params(){
	if(!percival_global_params::is_initialised){
	std::string default_master_param_file = "./data/test_param_file.txt";
	percival_global_params::initialisation(default_master_param_file);
	}
}

void percival_global_params::initialisation(const std::string & master_param_file){
	percival_global_params::load_master_param_file(master_param_file);
	if(!percival_global_params::check_initialisation()){
		std::cerr << "Key entries missing in the configuration file. Initialisation Incomplete." << std::endl;
	}
}

bool percival_global_params::load_master_param_file(const std::string & master_param_file){
	std::string line;

	std::ifstream myfile (master_param_file.c_str());

	//std::cout<<"I am in here!" <<std::endl;

	if (myfile.is_open())
	{
		while (! myfile.eof() )
		{
			getline (myfile,line);
			//std::cout << line << std::endl;

			std::string::size_type colon_position = line.find(":");
			if(colon_position!=std::string::npos && (line.find_first_not_of(" ", colon_position+1)!=std::string::npos)){
				if(line.find("total_number_of_frames") != std::string::npos){
					percival_global_params::total_number_of_frames = static_cast<unsigned int>(std::atoi(line.substr(colon_position + 1).c_str()));
					is_initialised_every_member[0] = true;
				}
				if(line.find("frame_height") != std::string::npos){
					percival_global_params::frame_height = static_cast<unsigned int>(std::atoi(line.substr(colon_position + 1).c_str()));
					is_initialised_every_member[1] = true;
				}
				if(line.find("frame_width") != std::string::npos){
					percival_global_params::frame_width = static_cast<unsigned int>(std::atoi(line.substr(colon_position + 1).c_str()));
					is_initialised_every_member[2] = true;
				}
				if(line.find("calib_params_height") != std::string::npos){
					percival_global_params::calib_params_height = static_cast<unsigned int>(std::atoi(line.substr(colon_position + 1).c_str()));
					is_initialised_every_member[3] = true;
				}
				if(line.find("calib_params_width") != std::string::npos){
					percival_global_params::calib_params_width = static_cast<unsigned int>(std::atoi(line.substr(colon_position + 1).c_str()));
					is_initialised_every_member[4] = true;
				}

				if(line.find("is_transposed_calib_params") != std::string::npos){
					percival_global_params::is_transposed_calib_params = (line.find("yes") != std::string::npos);
					is_initialised_every_member[5] = true;
				}
				//
				std::string::size_type quotation_begin = line.find_first_of("\"")+1;
				std::string::size_type quotation_end = line.find_last_of("\"");

				//
				if((line.find("\"")!=std::string::npos) && (line.rfind("\"")!=std::string::npos)){
					if(line.find("default_path_name") != std::string::npos){
						percival_global_params::default_path_name = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[6] = true;
					}
					if(line.find("default_data_set_name") != std::string::npos){
						percival_global_params::default_data_set_name = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[7] = true;
					}
					if(line.find("default_location_Gc") != std::string::npos){
						percival_global_params::default_location_Gc = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[8] = true;
					}
					if(line.find("default_location_Gf") != std::string::npos){
						percival_global_params::default_location_Gf = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[9] = true;
					}
					if(line.find("default_location_Oc") != std::string::npos){
						percival_global_params::default_location_Oc = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[10] = true;
					}
					if(line.find("default_location_Of") != std::string::npos){
						percival_global_params::default_location_Of = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[11] = true;
					}
					if(line.find("default_calib_params_dataset_name") != std::string::npos){
						percival_global_params::default_calib_params_dataset_name = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[12] = true;
					}
					if(line.find("default_location_ADU_to_electrons_conversion") != std::string::npos){
						percival_global_params::default_location_ADU_to_electrons_conversion = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[13] = true;
					}

				}
			}
			//			std::cout << std::stoi(" 124 ") << std::endl;
			//			std::cout << percival_global_params::total_number_of_frames << std::endl;

//			std::cout << total_number_of_frames << std::endl;
//			std::cout << frame_height << std::endl;
//			std::cout << frame_width << std::endl;
//			std::cout << default_path_name << std::endl;
//			std::cout << default_data_set_name << std::endl;
//			std::cout << is_transposed_calib_params << std::endl;
//			std::cout << calib_params_height << std::endl;
//			std::cout << calib_params_width << std::endl;
//			std::cout << default_location_Gc << std::endl;
//			std::cout << default_location_Gf << std::endl;
//			std::cout << default_location_Oc << std::endl;
//			std::cout << default_location_Of << std::endl;
		}

		myfile.close();
		return 1;
	}
	else {
		std::cerr << "Cannot open file " << master_param_file << std:: endl;
		return 0;
	}
}

bool percival_global_params::check_initialisation(){

//total_number_of_frames
//is_initialised_every_member[0] = true;
//frame_height
//is_initialised_every_member[1] = true;
//frame_width
//is_initialised_every_member[2] = true;
//calib_params_height
//is_initialised_every_member[3] = true;
//calib_params_width
//is_initialised_every_member[4] = true;
//is_transposed_calib_params
//is_initialised_every_member[5] = true;
//
//default_path_name
//is_initialised_every_member[6] = true;
//default_data_set_name
//is_initialised_every_member[7] = true;
//default_location_Gc
//is_initialised_every_member[8] = true;
//default_location_Gf
//is_initialised_every_member[9] = true;
//default_location_Oc
//is_initialised_every_member[10] = true;
//default_location_Of
//is_initialised_every_member[11] = true;

	if((percival_global_params::is_initialised_every_member[6] == false) ||
			(percival_global_params::is_initialised_every_member[7] == false) ||
				(percival_global_params::is_initialised_every_member[8] == false) ||
					(percival_global_params::is_initialised_every_member[9] == false) ||
						(percival_global_params::is_initialised_every_member[10] == false) ||
							(percival_global_params::is_initialised_every_member[11] == false)||
								(percival_global_params::is_initialised_every_member[12] == false)||
									(percival_global_params::is_initialised_every_member[13] == false)){
		return 0;
	}
//	else if((percival_global_params::is_initialised_every_member[0] == false) ||
//					(percival_global_params::is_initialised_every_member[1] == false)){
//
//
//	}else if((percival_global_params::is_initialised_every_member[3] == false) ||
//				(percival_global_params::is_initialised_every_member[4] == false)){
//
//	}else if(percival_global_params::is_initialised_every_member[5] == false){
//
//	}
	percival_global_params::is_initialised = true;
	return 1;
}

bool percival_global_params::initialised(){
	return percival_global_params::is_initialised;
}
<commit_msg>pathname and dataset no longer needs to be supplied in the master parameter file.<commit_after>/*
 * percival_global_params.cpp
 *
 *  Created on: 31 Jul 2015
 *      Author: pqm78245
 */
#include <cstdlib>
#include "percival_processing.h"

//image height, image width, total frame number, default file locations, calibration height, calibration width, rotated?

bool percival_global_params::is_initialised = false;
bool percival_global_params::is_initialised_every_member[255] = {};
unsigned int percival_global_params::total_number_of_frames;
unsigned int percival_global_params::frame_height;
unsigned int percival_global_params::frame_width;
std::string percival_global_params::default_path_name;
std::string percival_global_params::default_data_set_name;
bool percival_global_params::is_transposed_calib_params;
unsigned int percival_global_params::calib_params_height;
unsigned int percival_global_params::calib_params_width;
std::string percival_global_params::default_location_Gc;
std::string percival_global_params::default_location_Gf;
std::string percival_global_params::default_location_Oc;
std::string percival_global_params::default_location_Of;
std::string percival_global_params::default_location_ADU_to_electrons_conversion;
std::string percival_global_params::default_calib_params_dataset_name;

percival_global_params::percival_global_params(const std::string & master_param_file){
		percival_global_params::initialisation(master_param_file);
}

percival_global_params::percival_global_params(){
	if(!percival_global_params::is_initialised){
	std::string default_master_param_file = "./data/test_param_file.txt";
	percival_global_params::initialisation(default_master_param_file);
	}
}

void percival_global_params::initialisation(const std::string & master_param_file){
	percival_global_params::load_master_param_file(master_param_file);
	if(!percival_global_params::check_initialisation()){
		std::cerr << "Key entries missing in the configuration file. Initialisation Incomplete." << std::endl;
	}
}

bool percival_global_params::load_master_param_file(const std::string & master_param_file){
	std::string line;

	std::ifstream myfile (master_param_file.c_str());

	//std::cout<<"I am in here!" <<std::endl;

	if (myfile.is_open())
	{
		while (! myfile.eof() )
		{
			getline (myfile,line);
			//std::cout << line << std::endl;

			std::string::size_type colon_position = line.find(":");
			if(colon_position!=std::string::npos && (line.find_first_not_of(" ", colon_position+1)!=std::string::npos)){
				if(line.find("total_number_of_frames") != std::string::npos){
					percival_global_params::total_number_of_frames = static_cast<unsigned int>(std::atoi(line.substr(colon_position + 1).c_str()));
					is_initialised_every_member[0] = true;
				}
				if(line.find("frame_height") != std::string::npos){
					percival_global_params::frame_height = static_cast<unsigned int>(std::atoi(line.substr(colon_position + 1).c_str()));
					is_initialised_every_member[1] = true;
				}
				if(line.find("frame_width") != std::string::npos){
					percival_global_params::frame_width = static_cast<unsigned int>(std::atoi(line.substr(colon_position + 1).c_str()));
					is_initialised_every_member[2] = true;
				}
				if(line.find("calib_params_height") != std::string::npos){
					percival_global_params::calib_params_height = static_cast<unsigned int>(std::atoi(line.substr(colon_position + 1).c_str()));
					is_initialised_every_member[3] = true;
				}
				if(line.find("calib_params_width") != std::string::npos){
					percival_global_params::calib_params_width = static_cast<unsigned int>(std::atoi(line.substr(colon_position + 1).c_str()));
					is_initialised_every_member[4] = true;
				}

				if(line.find("is_transposed_calib_params") != std::string::npos){
					percival_global_params::is_transposed_calib_params = (line.find("yes") != std::string::npos);
					is_initialised_every_member[5] = true;
				}
				//
				std::string::size_type quotation_begin = line.find_first_of("\"")+1;
				std::string::size_type quotation_end = line.find_last_of("\"");

				//
				if((line.find("\"")!=std::string::npos) && (line.rfind("\"")!=std::string::npos)){
					if(line.find("default_path_name") != std::string::npos){
						percival_global_params::default_path_name = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[6] = true;
					}
					if(line.find("default_data_set_name") != std::string::npos){
						percival_global_params::default_data_set_name = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[7] = true;
					}
					if(line.find("default_location_Gc") != std::string::npos){
						percival_global_params::default_location_Gc = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[8] = true;
					}
					if(line.find("default_location_Gf") != std::string::npos){
						percival_global_params::default_location_Gf = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[9] = true;
					}
					if(line.find("default_location_Oc") != std::string::npos){
						percival_global_params::default_location_Oc = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[10] = true;
					}
					if(line.find("default_location_Of") != std::string::npos){
						percival_global_params::default_location_Of = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[11] = true;
					}
					if(line.find("default_calib_params_dataset_name") != std::string::npos){
						percival_global_params::default_calib_params_dataset_name = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[12] = true;
					}
					if(line.find("default_location_ADU_to_electrons_conversion") != std::string::npos){
						percival_global_params::default_location_ADU_to_electrons_conversion = line.substr(quotation_begin,quotation_end-quotation_begin);
						is_initialised_every_member[13] = true;
					}

				}
			}
			//			std::cout << std::stoi(" 124 ") << std::endl;
			//			std::cout << percival_global_params::total_number_of_frames << std::endl;

//			std::cout << total_number_of_frames << std::endl;
//			std::cout << frame_height << std::endl;
//			std::cout << frame_width << std::endl;
//			std::cout << default_path_name << std::endl;
//			std::cout << default_data_set_name << std::endl;
//			std::cout << is_transposed_calib_params << std::endl;
//			std::cout << calib_params_height << std::endl;
//			std::cout << calib_params_width << std::endl;
//			std::cout << default_location_Gc << std::endl;
//			std::cout << default_location_Gf << std::endl;
//			std::cout << default_location_Oc << std::endl;
//			std::cout << default_location_Of << std::endl;
		}

		myfile.close();
		return 1;
	}
	else {
		std::cerr << "Cannot open file " << master_param_file << std:: endl;
		return 0;
	}
}

bool percival_global_params::check_initialisation(){

//total_number_of_frames
//is_initialised_every_member[0] = true;
//frame_height
//is_initialised_every_member[1] = true;
//frame_width
//is_initialised_every_member[2] = true;
//calib_params_height
//is_initialised_every_member[3] = true;
//calib_params_width
//is_initialised_every_member[4] = true;
//is_transposed_calib_params
//is_initialised_every_member[5] = true;
//
//default_path_name
//is_initialised_every_member[6] = true;
//default_data_set_name
//is_initialised_every_member[7] = true;
//default_location_Gc
//is_initialised_every_member[8] = true;
//default_location_Gf
//is_initialised_every_member[9] = true;
//default_location_Oc
//is_initialised_every_member[10] = true;
//default_location_Of
//is_initialised_every_member[11] = true;

	if((//percival_global_params::is_initialised_every_member[6] == false) ||
			//(percival_global_params::is_initialised_every_member[7] == false) ||			//not necessary as the dataset name and path name will be supplied through main.
				(percival_global_params::is_initialised_every_member[8] == false) ||
					(percival_global_params::is_initialised_every_member[9] == false) ||
						(percival_global_params::is_initialised_every_member[10] == false) ||
							(percival_global_params::is_initialised_every_member[11] == false)||
								(percival_global_params::is_initialised_every_member[12] == false)||
									(percival_global_params::is_initialised_every_member[13] == false)){
		return 0;
	}
//	else if((percival_global_params::is_initialised_every_member[0] == false) ||
//					(percival_global_params::is_initialised_every_member[1] == false)){
//
//
//	}else if((percival_global_params::is_initialised_every_member[3] == false) ||
//				(percival_global_params::is_initialised_every_member[4] == false)){
//
//	}else if(percival_global_params::is_initialised_every_member[5] == false){
//
//	}
	percival_global_params::is_initialised = true;
	return 1;
}

bool percival_global_params::initialised(){
	return percival_global_params::is_initialised;
}
<|endoftext|>


<commit_before>//==================================================
// Copyright (c) 2015 Deividas Kazlauskas
//
// See the file license.txt for copying permission.
//==================================================

/*
 * =====================================================================================
 *
 *       Filename:  Filter.hpp
 *
 *    Description:  Filter class
 *
 *        Version:  1.0
 *        Created:  08/04/2014 07:37:01 PM
 *       Compiler:  gcc
 *
 *         Author:  David Kazlauskas (dk), david@templatious.org
 *
 * =====================================================================================
 */

#ifndef FILTER_O8Y22ICC
#define FILTER_O8Y22ICC

#include <utility>

#include <templatious/util/Exceptions.hpp>
#include <templatious/CollectionAdapter.hpp>
#include <templatious/proxy/Picker.hpp>

namespace templatious {

TEMPLATIOUS_BOILERPLATE_EXCEPTION( FilterPastEndIterationException,
    "Trying to iterate past end of filter.");

template <class T,class Fn,template <class> class StoragePolicy>
struct Filter {

    template <class I,class Fun>
    struct PIterator;

    typedef typename adapters::CollectionAdapter<T> Ad;
    typedef PIterator<typename Ad::Iterator,Fn> Iterator;
    typedef PIterator<typename Ad::ConstIterator,Fn> ConstIterator;
    typedef detail::IsProxy<T> ProxUtil;
    typedef typename ProxUtil::ICollection ICollection;
    typedef Filter<T,Fn,StoragePolicy> ThisFilter;

    static const bool proxy_inside = ProxUtil::val;
    static const bool floating_iterator = Ad::floating_iterator;
    static const bool random_access_iterator = false;

    static_assert(Ad::is_valid,"Adapter is invalid.");

    typedef typename StoragePolicy<T>::Container Ref;
    typedef typename StoragePolicy<Fn>::Container Fun;

#ifndef TEMPLATIOUS_TESTING
private:
#endif

    Ref _c;
    Fun _fn;
    Iterator _b;
    Iterator _e;
    bool _cleared;

    void assertUncleared() const {
        if (_cleared) {
            throw detail::ProxyClearedUsageException();
        }
    }

    void tagCleared() {
        _cleared = true;
    }

#ifndef TEMPLATIOUS_TESTING
public:
#endif

    template <class V,class FnRef>
    Filter(V&& v,FnRef&& fn) :
        _c(std::forward<V>(v)),
        _fn(std::forward<FnRef>(fn)),
        _b(Ad::begin(_c.getRef()),
           Ad::end(_c.getRef()),
           _fn.getRef()),
        _e(Ad::end(_c.getRef()),
           Ad::end(_c.getRef()),
           _fn.getRef()),
        _cleared(false)
    {
        bool begEqEnd = _b == _e;
        if (!begEqEnd && !_fn.getRef()(*_b)) {
            ++_b;
        }
    }

    Filter(ThisFilter&& other)
        : _c(other._c.cpy()),
          _fn(other._fn.cpy()),
          _b(Ad::begin(_c.getRef()),
             Ad::end(_c.getRef()),
             _fn.getRef()),
          _e(Ad::end(_c.getRef()),
              Ad::end(_c.getRef()),
              _fn.getRef()),
          _cleared(other._cleared)
    {
        bool begEqEnd = _b == _e;
        if (!begEqEnd && !_fn.getRef()(*_b)) {
            ++_b;
        }
    }

    Iterator begin() {
        assertUncleared();
        return _b;
    }

    Iterator end() {
        assertUncleared();
        return _e;
    }

    ConstIterator cbegin() const {
        assertUncleared();
        return ConstIterator(
            ProxUtil::const_iter_cast(_b._i),
            ProxUtil::const_iter_cast(_b._e),
            _b._fn
        );
    }

    ConstIterator cend() const {
        assertUncleared();
        return ConstIterator(
            ProxUtil::const_iter_cast(_e._i),
            ProxUtil::const_iter_cast(_e._e),
            _e._fn
        );
    }

    Iterator iterAt(long i) {
        assertUncleared();
        auto res(_b);
        detail::naiveIterAdvance(res,_e,i);
        return res;
    }

    long size() const {
        if (!_cleared) {
            return -1;
        } else {
            return 0;
        }
    }

    template <class I,class Fun>
    struct PIterator {
    private:
        I _i;
        I _e;
        typedef typename StoragePolicy<Fn>::Container Func;
        Func _fn;

        friend struct Filter<T,Fun,StoragePolicy>;

        template <class V>
        friend struct detail::IsProxy;
    public:

        typedef PIterator<I,Fun> ThisIter;
        typedef decltype(*_i) IVal;
        static const bool is_rvalue =
            std::is_rvalue_reference<IVal>::value;
        typedef typename std::conditional< !is_rvalue,
            I,void*>::type PtrDerefType;

        template <class V>
        PIterator(const I& i,const I& e,V&& fn) :
            _i(i), _e(e), _fn(std::forward<V>(fn)) {}

        PIterator& operator=(const PIterator& rhs) {
            _i = rhs._i;
            _e = rhs._e;
            return *this;
        }

        ThisIter& operator++() {
            if (_e == _i) {
                throw FilterPastEndIterationException();
            }

            do {
                ++_i;
            } while (_e != _i && !_fn.getRef()(*_i));
            return *this;
        }

        bool operator==(const ThisIter& rhs) const {
            return _i == rhs._i;
        }

        bool operator!=(const ThisIter& rhs) const {
            return !(*this == rhs);
        }

        auto operator*() -> decltype(
            *std::declval<ThisIter>()._i)
        {
            return *(this->_i);
        }

        auto operator*() const -> decltype(
            *std::declval<ThisIter>()._i)
        {
            return *(this->_i);
        }

        template <bool Rval = is_rvalue>
        auto operator->()
            -> typename std::enable_if<
                !Rval,decltype(std::addressof(
                    *std::declval<PtrDerefType>()))
            >::type
        const {
            return std::addressof(*(this->_i));
        }

        auto getInternal()
            -> decltype(ProxUtil::iter_unwrap(_i))&
        {
            return ProxUtil::iter_unwrap(_i);
        }

    };

    void clear() {
        detail::clearRoutine<floating_iterator>(*this);
        tagCleared();
        ProxUtil::tag_cleared(_c.getRef());
        _b._i = _e._i;
    }

    auto getInternal()
        -> decltype(ProxUtil::unwrap(_c.getRef()))&
    {
        return ProxUtil::unwrap(_c.getRef());
    }

    template <class V>
    static auto iterUnwrap(V&& v)
        -> decltype(ProxUtil::iter_unwrap(
            std::forward<V>(v)))&
    {
        return ProxUtil::iter_unwrap(
            std::forward<V>(v)
        );
    }

};

namespace detail {

template <class T,class Fn,template <class> class StoragePolicy>
struct IsProxy< Filter< T,Fn,StoragePolicy > > {
    typedef IsProxy<T> Internal;
    typedef Filter<T,Fn,StoragePolicy> ThisCol;
    typedef typename ThisCol::ConstIterator ConstIterator;
    static const bool val = true;
    static const bool random_access_iterator = false;

    typedef adapters::CollectionAdapter<T> Ad;
    typedef typename Ad::ThisCol ICollection;
    typedef typename
        adapters::CollectionAdapter<ICollection> IAdapter;

    template <class C>
    static auto unwrap(C&& c)
        -> decltype(c.getInternal())&
    {
        return c.getInternal();
    }

    template <class C>
    static auto iter_unwrap(C&& c)
        -> decltype(c.getInternal())&
    {
        return c.getInternal();
    }

    template <class C>
    static void iter_advance(C& i,C& e,long s) {
        naiveIterAdvance(i,e,s);
    }

    template <class C>
    static long get_mul(C&& a) {
        return -1;
    }

    template <class U>
    static void tag_cleared(U& u) {
        u.tagCleared();
    }

    template <class Iter>
    static auto const_iter_cast(Iter&& i)
     -> decltype(
        ConstIterator(
            Internal::const_iter_cast(i._i),
            Internal::const_iter_cast(i._e),
            i._fn
        )
     )
    {
        return ConstIterator(
            Internal::const_iter_cast(i._i),
            Internal::const_iter_cast(i._e),
            i._fn
        );
    }
};

}

namespace adapters {

template <class T,class Fn,template <class> class StoragePolicy>
struct CollectionAdapter< Filter<T,Fn,StoragePolicy> > {

    static const bool is_valid = true;

    typedef Filter<T,Fn,StoragePolicy> ThisCol;
    typedef const ThisCol ConstCol;
    typedef typename ThisCol::Iterator Iterator;
    typedef typename ThisCol::ConstIterator ConstIterator;
    typedef typename ThisCol::Ad::ValueType ValueType;
    typedef typename ThisCol::Ad::ConstValueType ConstValueType;

    static const bool floating_iterator = ThisCol::Ad::floating_iterator;

    template <class C>
    static Iterator begin(C&& c) {
        return c.begin();
    }

    template <class C>
    static Iterator end(C&& c) {
        return c.end();
    }

    static ConstIterator cbegin(ConstCol& c) {
        return c.cbegin();
    }

    static ConstIterator cend(ConstCol& c) {
        return c.cend();
    }

    template <class C>
    static Iterator iterAt(C&& c,long i) {
        return c.iterAt(i);
    }

    template <class C,class V>
    static void insertAt(C&& c,Iterator i,V&& v) {
        static_assert(templatious::util::DummyResolver<C,false>::val,
            "Filter proxy class is uninsertable.");
    }

    template <class C>
    static void erase(C&& c, Iterator i) {
        static_assert(templatious::util::DummyResolver<C,false>::val,
            "Filter proxy class is uninsertable.");
    }

    template <class C>
    static void erase(C&& c, Iterator beg, Iterator end) {
        static_assert(templatious::util::DummyResolver<C,false>::val,
            "Filter proxy class is uninsertable.");
    }

    template <class C>
    static void clear(C&& c) {
        c.clear();
    }

    template <class C>
    static long size(C&& c) {
        return c.size();
    }

};

}

}

#endif /* end of include guard: FILTER_O8Y22ICC */

<commit_msg>so many commits to fix build on travis CI...<commit_after>//==================================================
// Copyright (c) 2015 Deividas Kazlauskas
//
// See the file license.txt for copying permission.
//==================================================

/*
 * =====================================================================================
 *
 *       Filename:  Filter.hpp
 *
 *    Description:  Filter class
 *
 *        Version:  1.0
 *        Created:  08/04/2014 07:37:01 PM
 *       Compiler:  gcc
 *
 *         Author:  David Kazlauskas (dk), david@templatious.org
 *
 * =====================================================================================
 */

#ifndef FILTER_O8Y22ICC
#define FILTER_O8Y22ICC

#include <utility>

#include <templatious/util/Exceptions.hpp>
#include <templatious/CollectionAdapter.hpp>
#include <templatious/proxy/Picker.hpp>

namespace templatious {

TEMPLATIOUS_BOILERPLATE_EXCEPTION( FilterPastEndIterationException,
    "Trying to iterate past end of filter.");

template <class T,class Fn,template <class> class StoragePolicy>
struct Filter {

    template <class I,class Fun>
    struct PIterator;

    typedef typename adapters::CollectionAdapter<T> Ad;
    typedef PIterator<typename Ad::Iterator,Fn> Iterator;
    typedef PIterator<typename Ad::ConstIterator,Fn> ConstIterator;
    typedef detail::IsProxy<T> ProxUtil;
    typedef typename ProxUtil::ICollection ICollection;
    typedef Filter<T,Fn,StoragePolicy> ThisFilter;

    static const bool proxy_inside = ProxUtil::val;
    static const bool floating_iterator = Ad::floating_iterator;
    static const bool random_access_iterator = false;

    static_assert(Ad::is_valid,"Adapter is invalid.");

    typedef typename StoragePolicy<T>::Container Ref;
    typedef typename StoragePolicy<Fn>::Container Fun;

#ifndef TEMPLATIOUS_TESTING
private:
#endif

    Ref _c;
    Fun _fn;
    Iterator _b;
    Iterator _e;
    bool _cleared;

    void assertUncleared() const {
        if (_cleared) {
            throw detail::ProxyClearedUsageException();
        }
    }

    void tagCleared() {
        _cleared = true;
    }

#ifndef TEMPLATIOUS_TESTING
public:
#endif

    template <class V,class FnRef>
    Filter(V&& v,FnRef&& fn) :
        _c(std::forward<V>(v)),
        _fn(std::forward<FnRef>(fn)),
        _b(Ad::begin(_c.getRef()),
           Ad::end(_c.getRef()),
           _fn.getRef()),
        _e(Ad::end(_c.getRef()),
           Ad::end(_c.getRef()),
           _fn.getRef()),
        _cleared(false)
    {
        bool begEqEnd = _b == _e;
        if (!begEqEnd && !_fn.getRef()(*_b)) {
            ++_b;
        }
    }

    Filter(ThisFilter&& other)
        : _c(other._c.cpy()),
          _fn(other._fn.cpy()),
          _b(Ad::begin(_c.getRef()),
             Ad::end(_c.getRef()),
             _fn.getRef()),
          _e(Ad::end(_c.getRef()),
              Ad::end(_c.getRef()),
              _fn.getRef()),
          _cleared(other._cleared)
    {
        bool begEqEnd = _b == _e;
        if (!begEqEnd && !_fn.getRef()(*_b)) {
            ++_b;
        }
    }

    Iterator begin() {
        assertUncleared();
        return _b;
    }

    Iterator end() {
        assertUncleared();
        return _e;
    }

    ConstIterator cbegin() const {
        assertUncleared();
        return ConstIterator(
            ProxUtil::const_iter_cast(_b._i),
            ProxUtil::const_iter_cast(_b._e),
            _b._fn
        );
    }

    ConstIterator cend() const {
        assertUncleared();
        return ConstIterator(
            ProxUtil::const_iter_cast(_e._i),
            ProxUtil::const_iter_cast(_e._e),
            _e._fn
        );
    }

    Iterator iterAt(long i) {
        assertUncleared();
        auto res(_b);
        detail::naiveIterAdvance(res,_e,i);
        return res;
    }

    long size() const {
        if (!_cleared) {
            return -1;
        } else {
            return 0;
        }
    }

    template <class I,class Fun>
    struct PIterator {
    private:
        I _i;
        I _e;
        typedef typename StoragePolicy<Fn>::Container Func;
        Func _fn;

        friend struct Filter<T,Fun,StoragePolicy>;

        template <class V>
        friend struct detail::IsProxy;
    public:

        typedef PIterator<I,Fun> ThisIter;
        typedef decltype(*_i) IVal;
        static const bool is_rvalue =
            std::is_rvalue_reference<IVal>::value;
        typedef typename std::conditional< !is_rvalue,
            I,void*>::type PtrDerefType;

        template <class V>
        PIterator(const I& i,const I& e,V&& fn) :
            _i(i), _e(e), _fn(std::forward<V>(fn)) {}

        PIterator& operator=(const PIterator& rhs) {
            _i = rhs._i;
            _e = rhs._e;
            return *this;
        }

        ThisIter& operator++() {
            if (_e == _i) {
                throw FilterPastEndIterationException();
            }

            do {
                ++_i;
            } while (_e != _i && !_fn.getRef()(*_i));
            return *this;
        }

        bool operator==(const ThisIter& rhs) const {
            return _i == rhs._i;
        }

        bool operator!=(const ThisIter& rhs) const {
            return !(*this == rhs);
        }

        auto operator*() -> decltype(
            *std::declval<ThisIter>()._i)
        {
            return *(this->_i);
        }

        auto operator*() const -> decltype(
            *std::declval<ThisIter>()._i)
        {
            return *(this->_i);
        }

        template <bool Rval = is_rvalue>
        auto operator->()
            -> typename std::enable_if<
                !Rval,decltype(std::addressof(*std::declval<PtrDerefType>()))
            >::type
        const {
            return std::addressof(*(this->_i));
        }

        auto getInternal()
            -> decltype(ProxUtil::iter_unwrap(_i))&
        {
            return ProxUtil::iter_unwrap(_i);
        }

    };

    void clear() {
        detail::clearRoutine<floating_iterator>(*this);
        tagCleared();
        ProxUtil::tag_cleared(_c.getRef());
        _b._i = _e._i;
    }

    auto getInternal()
        -> decltype(ProxUtil::unwrap(_c.getRef()))&
    {
        return ProxUtil::unwrap(_c.getRef());
    }

    template <class V>
    static auto iterUnwrap(V&& v)
        -> decltype(ProxUtil::iter_unwrap(
            std::forward<V>(v)))&
    {
        return ProxUtil::iter_unwrap(
            std::forward<V>(v)
        );
    }

};

namespace detail {

template <class T,class Fn,template <class> class StoragePolicy>
struct IsProxy< Filter< T,Fn,StoragePolicy > > {
    typedef IsProxy<T> Internal;
    typedef Filter<T,Fn,StoragePolicy> ThisCol;
    typedef typename ThisCol::ConstIterator ConstIterator;
    static const bool val = true;
    static const bool random_access_iterator = false;

    typedef adapters::CollectionAdapter<T> Ad;
    typedef typename Ad::ThisCol ICollection;
    typedef typename
        adapters::CollectionAdapter<ICollection> IAdapter;

    template <class C>
    static auto unwrap(C&& c)
        -> decltype(c.getInternal())&
    {
        return c.getInternal();
    }

    template <class C>
    static auto iter_unwrap(C&& c)
        -> decltype(c.getInternal())&
    {
        return c.getInternal();
    }

    template <class C>
    static void iter_advance(C& i,C& e,long s) {
        naiveIterAdvance(i,e,s);
    }

    template <class C>
    static long get_mul(C&& a) {
        return -1;
    }

    template <class U>
    static void tag_cleared(U& u) {
        u.tagCleared();
    }

    template <class Iter>
    static auto const_iter_cast(Iter&& i)
     -> decltype(
        ConstIterator(
            Internal::const_iter_cast(i._i),
            Internal::const_iter_cast(i._e),
            i._fn
        )
     )
    {
        return ConstIterator(
            Internal::const_iter_cast(i._i),
            Internal::const_iter_cast(i._e),
            i._fn
        );
    }
};

}

namespace adapters {

template <class T,class Fn,template <class> class StoragePolicy>
struct CollectionAdapter< Filter<T,Fn,StoragePolicy> > {

    static const bool is_valid = true;

    typedef Filter<T,Fn,StoragePolicy> ThisCol;
    typedef const ThisCol ConstCol;
    typedef typename ThisCol::Iterator Iterator;
    typedef typename ThisCol::ConstIterator ConstIterator;
    typedef typename ThisCol::Ad::ValueType ValueType;
    typedef typename ThisCol::Ad::ConstValueType ConstValueType;

    static const bool floating_iterator = ThisCol::Ad::floating_iterator;

    template <class C>
    static Iterator begin(C&& c) {
        return c.begin();
    }

    template <class C>
    static Iterator end(C&& c) {
        return c.end();
    }

    static ConstIterator cbegin(ConstCol& c) {
        return c.cbegin();
    }

    static ConstIterator cend(ConstCol& c) {
        return c.cend();
    }

    template <class C>
    static Iterator iterAt(C&& c,long i) {
        return c.iterAt(i);
    }

    template <class C,class V>
    static void insertAt(C&& c,Iterator i,V&& v) {
        static_assert(templatious::util::DummyResolver<C,false>::val,
            "Filter proxy class is uninsertable.");
    }

    template <class C>
    static void erase(C&& c, Iterator i) {
        static_assert(templatious::util::DummyResolver<C,false>::val,
            "Filter proxy class is uninsertable.");
    }

    template <class C>
    static void erase(C&& c, Iterator beg, Iterator end) {
        static_assert(templatious::util::DummyResolver<C,false>::val,
            "Filter proxy class is uninsertable.");
    }

    template <class C>
    static void clear(C&& c) {
        c.clear();
    }

    template <class C>
    static long size(C&& c) {
        return c.size();
    }

};

}

}

#endif /* end of include guard: FILTER_O8Y22ICC */

<|endoftext|>