<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_OPERATOR_PROLONGATIONS_HH
#define DUNE_GDT_OPERATOR_PROLONGATIONS_HH

#include <type_traits>
#include <vector>
#include <limits>

#include <dune/common/dynmatrix.hh>

#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/grid/intersection.hh>

#include <dune/geometry/quadraturerules.hh>

#include <dune/stuff/grid/search.hh>

#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/space/continuouslagrange/fem.hh>

namespace Dune {
namespace GDT {
namespace ProlongationOperator {

template< class GridPartType >
class L2
{
  typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
  typedef typename GridPartType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridPartType::dimension;

public:
  L2(const GridPartType& grid_part)
    : grid_part_(grid_part)
  {}

  /**
   *  \todo This is only correct for DG functions. For CG/in general we need a global solve here!
   */
  template< class SourceSpaceType, class VS, class RangeSpaceType, class VR >
  void apply(const ConstDiscreteFunction< SourceSpaceType, VS >& source,
             DiscreteFunction< RangeSpaceType, VR >& range) const
  {
    // check
    static_assert(std::is_same< typename SourceSpaceType::RangeFieldType,
                                typename RangeSpaceType::RangeFieldType >::value, "Types do not match!");
    static_assert(SourceSpaceType::dimRange == RangeSpaceType::dimRange, "Dimensions do not match!");
    static_assert(SourceSpaceType::dimRangeCols == RangeSpaceType::dimRangeCols, "Dimensions do not match!");
    static_assert(SourceSpaceType::dimRangeCols == 1, "Not implemented yet!");
    typedef typename RangeSpaceType::BaseFunctionSetType::DomainType DomainType;
    typedef typename RangeSpaceType::BaseFunctionSetType::RangeType RangeType;
    typedef typename RangeSpaceType::BaseFunctionSetType::RangeFieldType RangeFieldType;
    // clear
    range.vector().backend() *= RangeFieldType(0);
    // create search in the source grid part
    typedef typename SourceSpaceType::GridPartType::GridViewType SourceGridViewType;
    typedef Stuff::Grid::EntityInlevelSearch< SourceGridViewType > EntitySearch;
    EntitySearch entity_search(source.space().gridPart()->gridView());
    // walk the grid
    RangeType source_value(0);
    std::vector< RangeType > basis_values(range.space().mapper().maxNumDofs());
    const auto entity_it_end = grid_part_.template end< 0 >();
    for (auto entity_it = grid_part_.template begin< 0 >();
         entity_it != entity_it_end;
         ++entity_it) {
      // prepare
      const auto& entity = *entity_it;
      const auto local_basis = range.space().baseFunctionSet(entity);
      auto local_range = range.local_discrete_function(entity);
      DynamicMatrix< RangeFieldType > local_matrix(local_basis.size(), local_basis.size(), RangeFieldType(0));
      DynamicVector< RangeFieldType > local_vector(local_basis.size(), RangeFieldType(0));
      // create quadrature
      const size_t quadrature_order = local_range.order();
      assert((2*quadrature_order + 1) < std::numeric_limits< int >::max());
      const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain >::rule(entity.type(),
                                                                                int(2*quadrature_order + 1));
      // get global quadrature points
      std::vector< DomainType > quadrature_points;
      for (const auto& quadrature_point : quadrature)
        quadrature_points.emplace_back(entity.geometry().global(quadrature_point.position()));
      // get source entities
      const auto source_entities = entity_search(quadrature_points);
      assert(source_entities.size() == quadrature_points.size());
      // loop over all quadrature points
      size_t pp = 0;
      for (const auto& quadrature_point : quadrature) {
        const auto local_point = quadrature_point.position();
        const auto quadrature_weight = quadrature_point.weight();
        const auto integration_element = entity.geometry().integrationElement(local_point);
        // evaluate source
        const auto source_entity_ptr = source_entities[pp];
        const auto& source_entity = *source_entity_ptr;
        const auto local_source = source.local_function(source_entity);
        local_source->evaluate(source_entity.geometry().local(entity.geometry().global(local_point)), source_value);
        // evaluate
        local_basis.evaluate(local_point, basis_values);
        // compute integrals
        for (size_t ii = 0; ii < local_basis.size(); ++ii) {
          local_vector[ii] += integration_element * quadrature_weight * (source_value * basis_values[ii]);
          auto& local_matrix_row = local_matrix[ii];
          for (size_t jj = 0; jj < local_basis.size(); ++jj) {
            local_matrix_row[jj] += integration_element * quadrature_weight * (basis_values[ii] * basis_values[jj]);
          }
        }
        ++pp;
      } // loop over all quadrature points
      // compute local DoFs
      DynamicVector< RangeFieldType > local_DoFs(local_basis.size(), 0);
      local_matrix.solve(local_DoFs, local_vector);
      // set local DoFs
      auto local_range_vector = local_range.vector();
      for (size_t ii = 0; ii < local_range_vector.size(); ++ii)
        local_range_vector.set(ii, local_DoFs[ii]);
    } // walk the grid
  } // ... apply(...)

private:
  const GridPartType& grid_part_;
}; // class L2

template< class GridPartType >
class Generic
{
public:
  typedef typename GridPartType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridPartType::dimension;

  Generic(const GridPartType& grid_part)
    : grid_part_(grid_part)
  {}

  template< class SGP, int sp, class R, int r, class SV, class RGP, int rp, class RV >
  void apply(const ConstDiscreteFunction< ContinuousLagrangeSpace::FemWrapper< SGP, sp, R, r >, SV >& source,
             DiscreteFunction< ContinuousLagrangeSpace::FemWrapper< RGP, rp, R, r >, RV >& range) const
  {
    // create search in the source grid part
    typedef ConstDiscreteFunction< ContinuousLagrangeSpace::FemWrapper< SGP, sp, R, r >, SV > SourceType;
    typedef DiscreteFunction< ContinuousLagrangeSpace::FemWrapper< RGP, rp, R, r >, RV >      TargetType;
    typedef typename SourceType::RangeFieldType RangeFieldType;
    static const unsigned int dimRange = SourceType::dimRangeRows;

    typedef typename SourceType::SpaceType::GridPartType::GridViewType SourceGridViewType;
    typedef Stuff::Grid::EntityInlevelSearch< SourceGridViewType > EntitySearch;
    EntitySearch entity_search(source.space().gridPart()->gridView());

    // set all dofs to infinity
    const auto infinity = std::numeric_limits< RangeFieldType >::infinity();
    for (size_t ii = 0; ii < range.vector().size(); ++ii)
      range.vector().set(ii, infinity);

    // walk the grid
    const auto entity_it_end = grid_part_.template end< 0 >();
    for (auto entity_it = grid_part_.template begin< 0 >();
         entity_it != entity_it_end;
         ++entity_it) {
      const auto& entity = *entity_it;

      // get global lagrange point coordinates
      const auto lagrange_point_set = range.space().backend().lagrangePointSet(entity);
      typedef FieldVector< typename SourceGridViewType::ctype, SourceGridViewType::dimension > DomainType;
      std::vector< DomainType > lagrange_points(lagrange_point_set.nop());
      for (size_t ii = 0; ii < lagrange_point_set.nop(); ++ii)
        lagrange_points[ii] = entity.geometry().global(lagrange_point_set.point(ii));

      // get source entities
      const auto source_entities = entity_search(lagrange_points);
      assert(source_entities.size() == lagrange_points.size());

      auto local_range = range.local_discrete_function(entity);
      auto local_range_vector = local_range.vector();

      size_t kk = 0;
      for (size_t ii = 0; ii < lagrange_points.size(); ++ii) {
        if (std::isinf(local_range_vector.get(kk))) {
          const auto& global_point = lagrange_points[ii];
          // evaluate source function
          const auto source_entity_ptr = source_entities[ii];
          const auto& source_entity = *source_entity_ptr;
          const auto local_source_point = source_entity.geometry().local(global_point);
          const auto local_source = source.local_function(source_entity);
          const auto source_value = local_source->evaluate(local_source_point);
          for (size_t jj = 0; jj < dimRange; ++jj, ++kk)
            local_range_vector.set(kk, source_value[jj]);
        }
        else
          kk += dimRange;
      }
    } // walk the grid
  } // ... apply(...)

private:
  const GridPartType& grid_part_;
}; // class Generic

} // namespace ProlongationOperator
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_OPERATOR_PROLONGATIONS_HH
<commit_msg>[operator.prolongation] fix Generic<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_OPERATOR_PROLONGATIONS_HH
#define DUNE_GDT_OPERATOR_PROLONGATIONS_HH

#include <type_traits>
#include <vector>
#include <limits>

#include <dune/common/dynmatrix.hh>

#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/grid/intersection.hh>

#include <dune/geometry/quadraturerules.hh>

#include <dune/stuff/grid/search.hh>

#include <dune/gdt/discretefunction/default.hh>
#include <dune/gdt/space/continuouslagrange/fem.hh>

namespace Dune {
namespace GDT {
namespace ProlongationOperator {

template< class GridPartType >
class L2
{
  typedef typename GridPartType::template Codim< 0 >::EntityType EntityType;
  typedef typename GridPartType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridPartType::dimension;

public:
  L2(const GridPartType& grid_part)
    : grid_part_(grid_part)
  {}

  /**
   *  \todo This is only correct for DG functions. For CG/in general we need a global solve here!
   */
  template< class SourceSpaceType, class VS, class RangeSpaceType, class VR >
  void apply(const ConstDiscreteFunction< SourceSpaceType, VS >& source,
             DiscreteFunction< RangeSpaceType, VR >& range) const
  {
    // check
    static_assert(std::is_same< typename SourceSpaceType::RangeFieldType,
                                typename RangeSpaceType::RangeFieldType >::value, "Types do not match!");
    static_assert(SourceSpaceType::dimRange == RangeSpaceType::dimRange, "Dimensions do not match!");
    static_assert(SourceSpaceType::dimRangeCols == RangeSpaceType::dimRangeCols, "Dimensions do not match!");
    static_assert(SourceSpaceType::dimRangeCols == 1, "Not implemented yet!");
    typedef typename RangeSpaceType::BaseFunctionSetType::DomainType DomainType;
    typedef typename RangeSpaceType::BaseFunctionSetType::RangeType RangeType;
    typedef typename RangeSpaceType::BaseFunctionSetType::RangeFieldType RangeFieldType;
    // clear
    range.vector().backend() *= RangeFieldType(0);
    // create search in the source grid part
    typedef typename SourceSpaceType::GridPartType::GridViewType SourceGridViewType;
    typedef Stuff::Grid::EntityInlevelSearch< SourceGridViewType > EntitySearch;
    EntitySearch entity_search(source.space().gridPart()->gridView());
    // walk the grid
    RangeType source_value(0);
    std::vector< RangeType > basis_values(range.space().mapper().maxNumDofs());
    const auto entity_it_end = grid_part_.template end< 0 >();
    for (auto entity_it = grid_part_.template begin< 0 >();
         entity_it != entity_it_end;
         ++entity_it) {
      // prepare
      const auto& entity = *entity_it;
      const auto local_basis = range.space().baseFunctionSet(entity);
      auto local_range = range.local_discrete_function(entity);
      DynamicMatrix< RangeFieldType > local_matrix(local_basis.size(), local_basis.size(), RangeFieldType(0));
      DynamicVector< RangeFieldType > local_vector(local_basis.size(), RangeFieldType(0));
      // create quadrature
      const size_t quadrature_order = local_range.order();
      assert((2*quadrature_order + 1) < std::numeric_limits< int >::max());
      const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain >::rule(entity.type(),
                                                                                int(2*quadrature_order + 1));
      // get global quadrature points
      std::vector< DomainType > quadrature_points;
      for (const auto& quadrature_point : quadrature)
        quadrature_points.emplace_back(entity.geometry().global(quadrature_point.position()));
      // get source entities
      const auto source_entities = entity_search(quadrature_points);
      assert(source_entities.size() == quadrature_points.size());
      // loop over all quadrature points
      size_t pp = 0;
      for (const auto& quadrature_point : quadrature) {
        const auto local_point = quadrature_point.position();
        const auto quadrature_weight = quadrature_point.weight();
        const auto integration_element = entity.geometry().integrationElement(local_point);
        // evaluate source
        const auto source_entity_ptr = source_entities[pp];
        const auto& source_entity = *source_entity_ptr;
        const auto local_source = source.local_function(source_entity);
        local_source->evaluate(source_entity.geometry().local(entity.geometry().global(local_point)), source_value);
        // evaluate
        local_basis.evaluate(local_point, basis_values);
        // compute integrals
        for (size_t ii = 0; ii < local_basis.size(); ++ii) {
          local_vector[ii] += integration_element * quadrature_weight * (source_value * basis_values[ii]);
          auto& local_matrix_row = local_matrix[ii];
          for (size_t jj = 0; jj < local_basis.size(); ++jj) {
            local_matrix_row[jj] += integration_element * quadrature_weight * (basis_values[ii] * basis_values[jj]);
          }
        }
        ++pp;
      } // loop over all quadrature points
      // compute local DoFs
      DynamicVector< RangeFieldType > local_DoFs(local_basis.size(), 0);
      local_matrix.solve(local_DoFs, local_vector);
      // set local DoFs
      auto local_range_vector = local_range.vector();
      for (size_t ii = 0; ii < local_range_vector.size(); ++ii)
        local_range_vector.set(ii, local_DoFs[ii]);
    } // walk the grid
  } // ... apply(...)

private:
  const GridPartType& grid_part_;
}; // class L2

template< class GridPartType >
class Generic
{
public:
  typedef typename GridPartType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridPartType::dimension;

  Generic(const GridPartType& grid_part)
    : grid_part_(grid_part)
  {}

  template< class SGP, int sp, class R, int r, class SV, class RGP, int rp, class RV >
  void apply(const ConstDiscreteFunction< ContinuousLagrangeSpace::FemWrapper< SGP, sp, R, r >, SV >& source,
             DiscreteFunction< ContinuousLagrangeSpace::FemWrapper< RGP, rp, R, r >, RV >& range) const
  {
    // create search in the source grid part
    typedef ConstDiscreteFunction< ContinuousLagrangeSpace::FemWrapper< SGP, sp, R, r >, SV > SourceType;
    typedef DiscreteFunction< ContinuousLagrangeSpace::FemWrapper< RGP, rp, R, r >, RV >      TargetType;
    typedef typename SourceType::RangeFieldType RangeFieldType;
    static const unsigned int dimRange = SourceType::dimRange;

    typedef typename SourceType::SpaceType::GridPartType::GridViewType SourceGridViewType;
    typedef Stuff::Grid::EntityInlevelSearch< SourceGridViewType > EntitySearch;
    EntitySearch entity_search(source.space().gridPart()->gridView());

    // set all dofs to infinity
    const auto infinity = std::numeric_limits< RangeFieldType >::infinity();
    for (size_t ii = 0; ii < range.vector().size(); ++ii)
      range.vector().set(ii, infinity);

    // walk the grid
    const auto entity_it_end = grid_part_.template end< 0 >();
    for (auto entity_it = grid_part_.template begin< 0 >();
         entity_it != entity_it_end;
         ++entity_it) {
      const auto& entity = *entity_it;

      // get global lagrange point coordinates
      const auto lagrange_point_set = range.space().backend().lagrangePointSet(entity);
      typedef FieldVector< typename SourceGridViewType::ctype, SourceGridViewType::dimension > DomainType;
      std::vector< DomainType > lagrange_points(lagrange_point_set.nop());
      for (size_t ii = 0; ii < lagrange_point_set.nop(); ++ii)
        lagrange_points[ii] = entity.geometry().global(lagrange_point_set.point(ii));

      // get source entities
      const auto source_entities = entity_search(lagrange_points);
      assert(source_entities.size() == lagrange_points.size());

      auto local_range = range.local_discrete_function(entity);
      auto local_range_vector = local_range.vector();

      size_t kk = 0;
      for (size_t ii = 0; ii < lagrange_points.size(); ++ii) {
        if (std::isinf(local_range_vector.get(kk))) {
          const auto& global_point = lagrange_points[ii];
          // evaluate source function
          const auto source_entity_ptr = source_entities[ii];
          const auto& source_entity = *source_entity_ptr;
          const auto local_source_point = source_entity.geometry().local(global_point);
          const auto local_source = source.local_function(source_entity);
          const auto source_value = local_source->evaluate(local_source_point);
          for (size_t jj = 0; jj < dimRange; ++jj, ++kk)
            local_range_vector.set(kk, source_value[jj]);
        }
        else
          kk += dimRange;
      }
    } // walk the grid
  } // ... apply(...)

private:
  const GridPartType& grid_part_;
}; // class Generic

} // namespace ProlongationOperator
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_OPERATOR_PROLONGATIONS_HH
<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include "main.hxx"

#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/ranges.hh>

using namespace Dune::Stuff::Common;
const size_t wait_ms = 142;

void scoped_busywait(const std::string& name, size_t ms) {
  ScopedTiming DUNE_UNUSED(scopedTiming)(name);
  busywait(ms);
}

static double confidence_margin() { return 0.90f; }

TEST(ProfilerTest, Timing) {
  for ( auto i : valueRange(1,4)) {
    DSC_PROFILER.startTiming("ProfilerTest.Timing");
    busywait(wait_ms);
    DSC_PROFILER.stopTiming("ProfilerTest.Timing");
    EXPECT_GE(DSC_PROFILER.getTiming("ProfilerTest.Timing"), i * wait_ms * confidence_margin());
  }
}

TEST(ProfilerTest, ScopedTiming) {
  const auto dvalueRange = valueRange(1,4);
  for ( auto DUNE_UNUSED(i) : dvalueRange) {
    scoped_busywait("ProfilerTest.ScopedTiming", wait_ms);
  }
  EXPECT_GE(DSC_PROFILER.getTiming("ProfilerTest.ScopedTiming"), long(dvalueRange.size() * wait_ms));
}

TEST(ProfilerTest, OutputConstness) {
  DSC_PROFILER.reset(1);
  const auto& prof = DSC_PROFILER;
  prof.outputAveraged(0,0);
  prof.outputTimings("timings");
  prof.outputTimings(DSC::dev_null);
}

TEST(ProfilerTest, ExpectedFailures) {
  EXPECT_THROW(DSC_PROFILER.reset(0),Dune::RangeError);
  EXPECT_THROW(DSC_PROFILER.reset(-1),Dune::RangeError);
  EXPECT_THROW(DSC_PROFILER.stopTiming("This_section_was_never_started"),Dune::RangeError);
}

TEST(ProfilerTest, NestedTiming) {
  auto& prof = DSC_PROFILER;
  prof.reset(1);
  prof.startTiming("NestedTiming.Outer");
  busywait(100);
  prof.startTiming("NestedTiming.Inner");
  busywait(100);
  auto inner = prof.getTiming("NestedTiming.Inner");
  auto outer = prof.getTiming("NestedTiming.Outer");
  EXPECT_GT(outer, inner);
}

<commit_msg>[tests] removes now obsolete test for Profiler.reset(-1)<commit_after>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#include "main.hxx"

#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/ranges.hh>

using namespace Dune::Stuff::Common;
const size_t wait_ms = 142;

void scoped_busywait(const std::string& name, size_t ms) {
  ScopedTiming DUNE_UNUSED(scopedTiming)(name);
  busywait(ms);
}

static double confidence_margin() { return 0.90f; }

TEST(ProfilerTest, Timing) {
  for ( auto i : valueRange(1,4)) {
    DSC_PROFILER.startTiming("ProfilerTest.Timing");
    busywait(wait_ms);
    DSC_PROFILER.stopTiming("ProfilerTest.Timing");
    EXPECT_GE(DSC_PROFILER.getTiming("ProfilerTest.Timing"), i * wait_ms * confidence_margin());
  }
}

TEST(ProfilerTest, ScopedTiming) {
  const auto dvalueRange = valueRange(1,4);
  for ( auto DUNE_UNUSED(i) : dvalueRange) {
    scoped_busywait("ProfilerTest.ScopedTiming", wait_ms);
  }
  EXPECT_GE(DSC_PROFILER.getTiming("ProfilerTest.ScopedTiming"), long(dvalueRange.size() * wait_ms));
}

TEST(ProfilerTest, OutputConstness) {
  DSC_PROFILER.reset(1);
  const auto& prof = DSC_PROFILER;
  prof.outputAveraged(0,0);
  prof.outputTimings("timings");
  prof.outputTimings(DSC::dev_null);
}

TEST(ProfilerTest, ExpectedFailures) {
  EXPECT_THROW(DSC_PROFILER.reset(0),Dune::RangeError);
  EXPECT_THROW(DSC_PROFILER.stopTiming("This_section_was_never_started"),Dune::RangeError);
}

TEST(ProfilerTest, NestedTiming) {
  auto& prof = DSC_PROFILER;
  prof.reset(1);
  prof.startTiming("NestedTiming.Outer");
  busywait(100);
  prof.startTiming("NestedTiming.Inner");
  busywait(100);
  auto inner = prof.getTiming("NestedTiming.Inner");
  auto outer = prof.getTiming("NestedTiming.Outer");
  EXPECT_GT(outer, inner);
}

<|endoftext|>


<commit_before>// Copyright 2012-2013 Samplecount S.L.
//
// 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.

#include "Methcla/Audio/Synth.hpp"

using namespace Methcla::Audio;
using namespace Methcla::Memory;

template <class T> T offset_cast(Synth* self, size_t offset)
{
    return reinterpret_cast<T>(reinterpret_cast<char*>(self) + offset);
}

Synth::Synth( Environment& env
            , Group* target
            , Node::AddAction addAction
            , const Plugin::Plugin& synthDef
            , size_t synthOffset
            , size_t audioInputOffset
            , size_t audioOutputOffset
            , size_t controlBufferOffset
            , size_t audioBufferOffset
            )
    : Node(env, target, addAction)
    , m_synthDef(synthDef)
    , m_synth(synthDef.construct(offset_cast<void*>(this, synthOffset), env.sampleRate()))
    , m_controlBuffers(offset_cast<sample_t*>(this, controlBufferOffset))
    , m_audioBuffers(offset_cast<sample_t*>(this, audioBufferOffset))
{
    const size_t blockSize = env.blockSize();

    // Uninitialized audio connection memory
    AudioInputConnection* audioInputConnections   = offset_cast<AudioInputConnection*>(this, audioInputOffset);
    AudioOutputConnection* audioOutputConnections = offset_cast<AudioOutputConnection*>(this, audioOutputOffset);

    // Audio buffer memory
    sample_t* audioInputBuffers = m_audioBuffers;
    sample_t* audioOutputBuffers = m_audioBuffers + synthDef.numAudioInputs() * blockSize;

    for (size_t i=0; i < synthDef.numPorts(); i++) {
        const FloatPort& port = synthDef.port(i);
        // Connect control ports
        if (port.isa(Port::kControl)) {
            if (port.isa(Port::kInput)) {
                m_controlBuffers[port.index()] = port.defaultValue();
                m_synthDef.connectPort(
                    m_synth
                  , i
                  , &m_controlBuffers[port.index()] );
            } else if (port.isa(Port::kOutput)) {
                m_synthDef.connectPort(
                    m_synth
                  , i
                  , &m_controlBuffers[numControlInputs() + port.index()] );
            } else {
                BOOST_ASSERT_MSG( false, "Invalid port type" );
            }
        } else if (port.isa(Port::kAudio)) {
            // Connect audio ports
            if (port.isa(Port::kInput)) {
                new (&audioInputConnections[port.index()]) AudioInputConnection(m_audioInputConnections.size());
                m_audioInputConnections.push_back(audioInputConnections[port.index()]);
                m_synthDef.connectPort( m_synth
                                      , i
                                      , audioInputBuffers + port.index() * blockSize );

            } else if (port.isa(Port::kOutput)) {
                new (&audioOutputConnections[port.index()]) AudioOutputConnection(m_audioOutputConnections.size());
                m_audioOutputConnections.push_back(audioOutputConnections[port.index()]);
                m_synthDef.connectPort( m_synth
                                      , i
                                      , audioOutputBuffers + port.index() * blockSize );
            } else {
                BOOST_ASSERT_MSG( false, "Invalid port type" );
            }
        } else {
            BOOST_ASSERT_MSG( false, "Invalid port type" );
        }
    }

    // Check for control input triggers
//    for (size_t i=0; i < numControlInputs(); i++) {
//        if (m_synthDef.controlInputSpec(i).flags & kMethclaControlTrigger) {
//            m_flags.set(kHasTriggerInput);
//            break;
//        }
//    }

    // Activate the synth
    m_synthDef.activate(m_synth);
}

Synth::~Synth()
{
    m_synthDef.deactivate(m_synth);
    m_synthDef.destroy(m_synth);
}

Synth* Synth::construct(Environment& env, Group* target, Node::AddAction addAction, const Plugin::Plugin& synthDef)
{
    typedef Alignment<kSIMDAlignment> BufferAlignment;

    static_assert(   (allocated_super::kAlignment >= BufferAlignment::kAlignment)
                  && ((allocated_super::kAlignment % BufferAlignment::kAlignment) == 0)
                 , "allocated_super::kAlignment multiple of kSIMDAlignment" );

    // TODO: This is not really necessary; each buffer could be aligned correctly, with some padding in between buffers.
    BOOST_ASSERT_MSG( BufferAlignment::isAligned(env.blockSize() * sizeof(sample_t))
                    , "Environment.blockSize must be aligned to Alignment::SIMDAlignment" );

    const size_t numControlInputs           = synthDef.numControlInputs();
    const size_t numControlOutputs          = synthDef.numControlOutputs();
    const size_t numAudioInputs             = synthDef.numAudioInputs();
    const size_t numAudioOutputs            = synthDef.numAudioOutputs();
    const size_t blockSize                  = env.blockSize();

    const size_t synthAllocSize             = sizeof(Synth) + synthDef.instanceSize();
    const size_t audioInputOffset           = synthAllocSize;
    const size_t audioInputAllocSize        = numAudioInputs * sizeof(AudioInputConnection);
    const size_t audioOutputOffset          = audioInputOffset + audioInputAllocSize;
    const size_t audioOutputAllocSize       = numAudioOutputs * sizeof(AudioOutputConnection);
    const size_t controlBufferOffset        = audioOutputOffset + audioOutputAllocSize;
    const size_t controlBufferAllocSize     = (numControlInputs + numControlOutputs) * sizeof(sample_t);
    const size_t audioBufferOffset          = BufferAlignment::align(controlBufferOffset + controlBufferAllocSize);
    const size_t audioBufferAllocSize       = (numAudioInputs + numAudioOutputs) * blockSize * sizeof(sample_t);
    const size_t allocSize                  = audioBufferOffset + audioBufferAllocSize;

    // Instantiate synth
    return new (env.rtMem(), allocSize - sizeof(Synth))
               Synth( env, target, addAction
                    , synthDef
                    , sizeof(Synth)
                    , audioInputOffset
                    , audioOutputOffset
                    , controlBufferOffset
                    , audioBufferOffset );
}

template <class Connection>
struct IfConnectionIndex
{
    IfConnectionIndex(size_t index)
        : m_index(index)
    { }

    bool operator () (const Connection& conn)
    {
        return conn.index() == m_index;
    }

    size_t m_index;
};

template <class Connection>
struct SortByBusId
{
    bool operator () (const Connection& a, const Connection& b)
    {
        return a.busId() < b.busId();
    }
};

void Synth::mapInput(size_t index, const AudioBusId& busId, InputConnectionType type)
{
    AudioInputConnections::iterator conn =
        find_if( m_audioInputConnections.begin()
               , m_audioInputConnections.end()
               , IfConnectionIndex<AudioInputConnection>(index) );
    if (conn != m_audioInputConnections.end()) {
        if (conn->connect(busId, type)) {
            m_flags.set(kAudioInputConnectionsChanged);
        }
    }
}

void Synth::mapOutput(size_t index, const AudioBusId& busId, OutputConnectionType type)
{
    size_t offset = sampleOffset();
    sample_t* buffer = offset > 0 ? env().rtMem().allocOf<sample_t>(offset) : 0;
    AudioOutputConnections::iterator conn =
        find_if( m_audioOutputConnections.begin()
               , m_audioOutputConnections.end()
               , IfConnectionIndex<AudioOutputConnection>(index) );
    if (conn != m_audioOutputConnections.end()) {
        conn->release(env());
        if (conn->connect(busId, type, offset, buffer)) {
            m_flags.set(kAudioOutputConnectionsChanged);
        }
    }
}

void Synth::process(size_t numFrames)
{
    // Sort connections by bus id (if necessary)
    if (m_flags.test(kAudioInputConnectionsChanged)) {
        m_audioInputConnections.sort(SortByBusId<AudioInputConnection>());
        m_flags.reset(kAudioInputConnectionsChanged);
    }
    if (m_flags.test(kAudioOutputConnectionsChanged)) {
        m_audioOutputConnections.sort(SortByBusId<AudioOutputConnection>());
        m_flags.reset(kAudioOutputConnectionsChanged);
    }

    Environment& env = this->env();
    const size_t blockSize = env.blockSize();

    sample_t* const inputBuffers = m_audioBuffers;
    for (auto& x : m_audioInputConnections) {
        x.read(env, numFrames, inputBuffers + x.index() * blockSize);
    }

    m_synthDef.run(m_synth, numFrames);

    sample_t* const outputBuffers = m_audioBuffers + m_synthDef.numAudioInputs() * blockSize;
    for (auto& x : m_audioOutputConnections) {
        x.write(env, numFrames, outputBuffers + x.index() * blockSize);
    }

    // Reset triggers
//    if (m_flags.test(kHasTriggerInput)) {
//        for (size_t i=0; i < numControlInputs(); i++) {
//            if (synthDef().controlInputSpec(i).flags & kMethclaControlTrigger) {
//                *controlInput(i) = 0.f;
//            }
//        }
//    }
}
<commit_msg>Align sample offset buffer for SIMD<commit_after>// Copyright 2012-2013 Samplecount S.L.
//
// 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.

#include "Methcla/Audio/Synth.hpp"

using namespace Methcla::Audio;
using namespace Methcla::Memory;

template <class T> T offset_cast(Synth* self, size_t offset)
{
    return reinterpret_cast<T>(reinterpret_cast<char*>(self) + offset);
}

Synth::Synth( Environment& env
            , Group* target
            , Node::AddAction addAction
            , const Plugin::Plugin& synthDef
            , size_t synthOffset
            , size_t audioInputOffset
            , size_t audioOutputOffset
            , size_t controlBufferOffset
            , size_t audioBufferOffset
            )
    : Node(env, target, addAction)
    , m_synthDef(synthDef)
    , m_synth(synthDef.construct(offset_cast<void*>(this, synthOffset), env.sampleRate()))
    , m_controlBuffers(offset_cast<sample_t*>(this, controlBufferOffset))
    , m_audioBuffers(offset_cast<sample_t*>(this, audioBufferOffset))
{
    const size_t blockSize = env.blockSize();

    // Uninitialized audio connection memory
    AudioInputConnection* audioInputConnections   = offset_cast<AudioInputConnection*>(this, audioInputOffset);
    AudioOutputConnection* audioOutputConnections = offset_cast<AudioOutputConnection*>(this, audioOutputOffset);

    // Audio buffer memory
    sample_t* audioInputBuffers = m_audioBuffers;
    sample_t* audioOutputBuffers = m_audioBuffers + synthDef.numAudioInputs() * blockSize;

    for (size_t i=0; i < synthDef.numPorts(); i++) {
        const FloatPort& port = synthDef.port(i);
        // Connect control ports
        if (port.isa(Port::kControl)) {
            if (port.isa(Port::kInput)) {
                m_controlBuffers[port.index()] = port.defaultValue();
                m_synthDef.connectPort(
                    m_synth
                  , i
                  , &m_controlBuffers[port.index()] );
            } else if (port.isa(Port::kOutput)) {
                m_synthDef.connectPort(
                    m_synth
                  , i
                  , &m_controlBuffers[numControlInputs() + port.index()] );
            } else {
                BOOST_ASSERT_MSG( false, "Invalid port type" );
            }
        } else if (port.isa(Port::kAudio)) {
            // Connect audio ports
            if (port.isa(Port::kInput)) {
                new (&audioInputConnections[port.index()]) AudioInputConnection(m_audioInputConnections.size());
                m_audioInputConnections.push_back(audioInputConnections[port.index()]);
                m_synthDef.connectPort( m_synth
                                      , i
                                      , audioInputBuffers + port.index() * blockSize );

            } else if (port.isa(Port::kOutput)) {
                new (&audioOutputConnections[port.index()]) AudioOutputConnection(m_audioOutputConnections.size());
                m_audioOutputConnections.push_back(audioOutputConnections[port.index()]);
                m_synthDef.connectPort( m_synth
                                      , i
                                      , audioOutputBuffers + port.index() * blockSize );
            } else {
                BOOST_ASSERT_MSG( false, "Invalid port type" );
            }
        } else {
            BOOST_ASSERT_MSG( false, "Invalid port type" );
        }
    }

    // Check for control input triggers
//    for (size_t i=0; i < numControlInputs(); i++) {
//        if (m_synthDef.controlInputSpec(i).flags & kMethclaControlTrigger) {
//            m_flags.set(kHasTriggerInput);
//            break;
//        }
//    }

    // Activate the synth
    m_synthDef.activate(m_synth);
}

Synth::~Synth()
{
    m_synthDef.deactivate(m_synth);
    m_synthDef.destroy(m_synth);
}

Synth* Synth::construct(Environment& env, Group* target, Node::AddAction addAction, const Plugin::Plugin& synthDef)
{
    typedef Alignment<kSIMDAlignment> BufferAlignment;

    static_assert(   (allocated_super::kAlignment >= BufferAlignment::kAlignment)
                  && ((allocated_super::kAlignment % BufferAlignment::kAlignment) == 0)
                 , "allocated_super::kAlignment multiple of kSIMDAlignment" );

    // TODO: This is not really necessary; each buffer could be aligned correctly, with some padding in between buffers.
    BOOST_ASSERT_MSG( BufferAlignment::isAligned(env.blockSize() * sizeof(sample_t))
                    , "Environment.blockSize must be aligned to Alignment::SIMDAlignment" );

    const size_t numControlInputs           = synthDef.numControlInputs();
    const size_t numControlOutputs          = synthDef.numControlOutputs();
    const size_t numAudioInputs             = synthDef.numAudioInputs();
    const size_t numAudioOutputs            = synthDef.numAudioOutputs();
    const size_t blockSize                  = env.blockSize();

    const size_t synthAllocSize             = sizeof(Synth) + synthDef.instanceSize();
    const size_t audioInputOffset           = synthAllocSize;
    const size_t audioInputAllocSize        = numAudioInputs * sizeof(AudioInputConnection);
    const size_t audioOutputOffset          = audioInputOffset + audioInputAllocSize;
    const size_t audioOutputAllocSize       = numAudioOutputs * sizeof(AudioOutputConnection);
    const size_t controlBufferOffset        = audioOutputOffset + audioOutputAllocSize;
    const size_t controlBufferAllocSize     = (numControlInputs + numControlOutputs) * sizeof(sample_t);
    const size_t audioBufferOffset          = BufferAlignment::align(controlBufferOffset + controlBufferAllocSize);
    const size_t audioBufferAllocSize       = (numAudioInputs + numAudioOutputs) * blockSize * sizeof(sample_t);
    const size_t allocSize                  = audioBufferOffset + audioBufferAllocSize;

    // Instantiate synth
    return new (env.rtMem(), allocSize - sizeof(Synth))
               Synth( env, target, addAction
                    , synthDef
                    , sizeof(Synth)
                    , audioInputOffset
                    , audioOutputOffset
                    , controlBufferOffset
                    , audioBufferOffset );
}

template <class Connection>
struct IfConnectionIndex
{
    IfConnectionIndex(size_t index)
        : m_index(index)
    { }

    bool operator () (const Connection& conn)
    {
        return conn.index() == m_index;
    }

    size_t m_index;
};

template <class Connection>
struct SortByBusId
{
    bool operator () (const Connection& a, const Connection& b)
    {
        return a.busId() < b.busId();
    }
};

void Synth::mapInput(size_t index, const AudioBusId& busId, InputConnectionType type)
{
    AudioInputConnections::iterator conn =
        find_if( m_audioInputConnections.begin()
               , m_audioInputConnections.end()
               , IfConnectionIndex<AudioInputConnection>(index) );
    if (conn != m_audioInputConnections.end()) {
        if (conn->connect(busId, type)) {
            m_flags.set(kAudioInputConnectionsChanged);
        }
    }
}

void Synth::mapOutput(size_t index, const AudioBusId& busId, OutputConnectionType type)
{
    size_t offset = sampleOffset();
    sample_t* buffer = offset > 0 ? env().rtMem().allocAlignedOf<sample_t,kSIMDAlignment>(offset) : 0;
    AudioOutputConnections::iterator conn =
        find_if( m_audioOutputConnections.begin()
               , m_audioOutputConnections.end()
               , IfConnectionIndex<AudioOutputConnection>(index) );
    if (conn != m_audioOutputConnections.end()) {
        conn->release(env());
        if (conn->connect(busId, type, offset, buffer)) {
            m_flags.set(kAudioOutputConnectionsChanged);
        }
    }
}

void Synth::process(size_t numFrames)
{
    // Sort connections by bus id (if necessary)
    if (m_flags.test(kAudioInputConnectionsChanged)) {
        m_audioInputConnections.sort(SortByBusId<AudioInputConnection>());
        m_flags.reset(kAudioInputConnectionsChanged);
    }
    if (m_flags.test(kAudioOutputConnectionsChanged)) {
        m_audioOutputConnections.sort(SortByBusId<AudioOutputConnection>());
        m_flags.reset(kAudioOutputConnectionsChanged);
    }

    Environment& env = this->env();
    const size_t blockSize = env.blockSize();

    sample_t* const inputBuffers = m_audioBuffers;
    for (auto& x : m_audioInputConnections) {
        x.read(env, numFrames, inputBuffers + x.index() * blockSize);
    }

    m_synthDef.run(m_synth, numFrames);

    sample_t* const outputBuffers = m_audioBuffers + m_synthDef.numAudioInputs() * blockSize;
    for (auto& x : m_audioOutputConnections) {
        x.write(env, numFrames, outputBuffers + x.index() * blockSize);
    }

    // Reset triggers
//    if (m_flags.test(kHasTriggerInput)) {
//        for (size_t i=0; i < numControlInputs(); i++) {
//            if (synthDef().controlInputSpec(i).flags & kMethclaControlTrigger) {
//                *controlInput(i) = 0.f;
//            }
//        }
//    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/browser.h"
#include "atom/browser/native_window_views.h"
#include "content/public/browser/browser_accessibility_state.h"

namespace atom {

namespace {

// Convert Win32 WM_APPCOMMANDS to strings.
const char* AppCommandToString(int command_id) {
  switch (command_id) {
    case APPCOMMAND_BROWSER_BACKWARD       : return "browser-backward";
    case APPCOMMAND_BROWSER_FORWARD        : return "browser-forward";
    case APPCOMMAND_BROWSER_REFRESH        : return "browser-refresh";
    case APPCOMMAND_BROWSER_STOP           : return "browser-stop";
    case APPCOMMAND_BROWSER_SEARCH         : return "browser-search";
    case APPCOMMAND_BROWSER_FAVORITES      : return "browser-favorites";
    case APPCOMMAND_BROWSER_HOME           : return "browser-home";
    case APPCOMMAND_VOLUME_MUTE            : return "volume-mute";
    case APPCOMMAND_VOLUME_DOWN            : return "volume-down";
    case APPCOMMAND_VOLUME_UP              : return "volume-up";
    case APPCOMMAND_MEDIA_NEXTTRACK        : return "media-nexttrack";
    case APPCOMMAND_MEDIA_PREVIOUSTRACK    : return "media-previoustrack";
    case APPCOMMAND_MEDIA_STOP             : return "media-stop";
    case APPCOMMAND_MEDIA_PLAY_PAUSE       : return "media-play_pause";
    case APPCOMMAND_LAUNCH_MAIL            : return "launch-mail";
    case APPCOMMAND_LAUNCH_MEDIA_SELECT    : return "launch-media-select";
    case APPCOMMAND_LAUNCH_APP1            : return "launch-app1";
    case APPCOMMAND_LAUNCH_APP2            : return "launch-app2";
    case APPCOMMAND_BASS_DOWN              : return "bass-down";
    case APPCOMMAND_BASS_BOOST             : return "bass-boost";
    case APPCOMMAND_BASS_UP                : return "bass-up";
    case APPCOMMAND_TREBLE_DOWN            : return "treble-down";
    case APPCOMMAND_TREBLE_UP              : return "treble-up";
    case APPCOMMAND_MICROPHONE_VOLUME_MUTE : return "microphone-volume-mute";
    case APPCOMMAND_MICROPHONE_VOLUME_DOWN : return "microphone-volume-down";
    case APPCOMMAND_MICROPHONE_VOLUME_UP   : return "microphone-volume-up";
    case APPCOMMAND_HELP                   : return "help";
    case APPCOMMAND_FIND                   : return "find";
    case APPCOMMAND_NEW                    : return "new";
    case APPCOMMAND_OPEN                   : return "open";
    case APPCOMMAND_CLOSE                  : return "close";
    case APPCOMMAND_SAVE                   : return "save";
    case APPCOMMAND_PRINT                  : return "print";
    case APPCOMMAND_UNDO                   : return "undo";
    case APPCOMMAND_REDO                   : return "redo";
    case APPCOMMAND_COPY                   : return "copy";
    case APPCOMMAND_CUT                    : return "cut";
    case APPCOMMAND_PASTE                  : return "paste";
    case APPCOMMAND_REPLY_TO_MAIL          : return "reply-to-mail";
    case APPCOMMAND_FORWARD_MAIL           : return "forward-mail";
    case APPCOMMAND_SEND_MAIL              : return "send-mail";
    case APPCOMMAND_SPELL_CHECK            : return "spell-check";
    case APPCOMMAND_MIC_ON_OFF_TOGGLE      : return "mic-on-off-toggle";
    case APPCOMMAND_CORRECTION_LIST        : return "correction-list";
    case APPCOMMAND_MEDIA_PLAY             : return "media-play";
    case APPCOMMAND_MEDIA_PAUSE            : return "media-pause";
    case APPCOMMAND_MEDIA_RECORD           : return "media-record";
    case APPCOMMAND_MEDIA_FAST_FORWARD     : return "media-fast-forward";
    case APPCOMMAND_MEDIA_REWIND           : return "media-rewind";
    case APPCOMMAND_MEDIA_CHANNEL_UP       : return "media-channel-up";
    case APPCOMMAND_MEDIA_CHANNEL_DOWN     : return "media-channel-down";
    case APPCOMMAND_DELETE                 : return "delete";
    case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE:
      return "dictate-or-command-control-toggle";
    default:
      return "unknown";
  }
}

}  // namespace

bool NativeWindowViews::ExecuteWindowsCommand(int command_id) {
  std::string command = AppCommandToString(command_id);
  NotifyWindowExecuteWindowsCommand(command);
  return false;
}

bool NativeWindowViews::PreHandleMSG(
    UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) {
  NotifyWindowMessage(message, w_param, l_param);

  switch (message) {
    // Screen readers send WM_GETOBJECT in order to get the accessibility
    // object, so take this opportunity to push Chromium into accessible
    // mode if it isn't already, always say we didn't handle the message
    // because we still want Chromium to handle returning the actual
    // accessibility object.
    case WM_GETOBJECT: {
      const DWORD obj_id = static_cast<DWORD>(l_param);
      if (enabled_a11y_support_) return false;

      if (obj_id == OBJID_CLIENT) {
        const auto axState = content::BrowserAccessibilityState::GetInstance();
        if (axState && !axState->IsAccessibleBrowser()) {
          axState->OnScreenReaderDetected();
          enabled_a11y_support_ = true;
          Browser::Get()->OnAccessibilitySupportChanged();
        }
      }

      return false;
    }
    case WM_COMMAND:
      // Handle thumbar button click message.
      if (HIWORD(w_param) == THBN_CLICKED)
        return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param));
      return false;

    case WM_SIZE:
      // Handle window state change.
      HandleSizeEvent(w_param, l_param);
      return false;

    case WM_MOVING: {
      if (!movable_)
        ::GetWindowRect(GetAcceleratedWidget(), (LPRECT)l_param);
      return false;
    }

    default:
      return false;
  }
}

void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) {
  // Here we handle the WM_SIZE event in order to figure out what is the current
  // window state and notify the user accordingly.
  switch (w_param) {
    case SIZE_MAXIMIZED:
      last_window_state_ = ui::SHOW_STATE_MAXIMIZED;
      NotifyWindowMaximize();
      break;
    case SIZE_MINIMIZED:
      last_window_state_ = ui::SHOW_STATE_MINIMIZED;
      NotifyWindowMinimize();
      break;
    case SIZE_RESTORED:
      if (last_window_state_ == ui::SHOW_STATE_NORMAL) {
        // Window was resized so we save it's new size.
        last_normal_bounds_ = GetBounds();
      } else {
        switch (last_window_state_) {
          case ui::SHOW_STATE_MAXIMIZED:
            last_window_state_ = ui::SHOW_STATE_NORMAL;

            // When the window is restored we resize it to the previous known
            // normal size.
            SetBounds(last_normal_bounds_, false);

            NotifyWindowUnmaximize();
            break;
          case ui::SHOW_STATE_MINIMIZED:
            if (IsFullscreen()) {
              last_window_state_ = ui::SHOW_STATE_FULLSCREEN;
              NotifyWindowEnterFullScreen();
            } else {
              last_window_state_ = ui::SHOW_STATE_NORMAL;

              // When the window is restored we resize it to the previous known
              // normal size.
              SetBounds(last_normal_bounds_, false);

              NotifyWindowRestore();
            }
            break;
        }
      }
      break;
  }
}

}  // namespace atom
<commit_msg>issue 6574 - Window position doesn't restore correctly<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/browser.h"
#include "atom/browser/native_window_views.h"
#include "content/public/browser/browser_accessibility_state.h"

namespace atom {

namespace {

// Convert Win32 WM_APPCOMMANDS to strings.
const char* AppCommandToString(int command_id) {
  switch (command_id) {
    case APPCOMMAND_BROWSER_BACKWARD       : return "browser-backward";
    case APPCOMMAND_BROWSER_FORWARD        : return "browser-forward";
    case APPCOMMAND_BROWSER_REFRESH        : return "browser-refresh";
    case APPCOMMAND_BROWSER_STOP           : return "browser-stop";
    case APPCOMMAND_BROWSER_SEARCH         : return "browser-search";
    case APPCOMMAND_BROWSER_FAVORITES      : return "browser-favorites";
    case APPCOMMAND_BROWSER_HOME           : return "browser-home";
    case APPCOMMAND_VOLUME_MUTE            : return "volume-mute";
    case APPCOMMAND_VOLUME_DOWN            : return "volume-down";
    case APPCOMMAND_VOLUME_UP              : return "volume-up";
    case APPCOMMAND_MEDIA_NEXTTRACK        : return "media-nexttrack";
    case APPCOMMAND_MEDIA_PREVIOUSTRACK    : return "media-previoustrack";
    case APPCOMMAND_MEDIA_STOP             : return "media-stop";
    case APPCOMMAND_MEDIA_PLAY_PAUSE       : return "media-play_pause";
    case APPCOMMAND_LAUNCH_MAIL            : return "launch-mail";
    case APPCOMMAND_LAUNCH_MEDIA_SELECT    : return "launch-media-select";
    case APPCOMMAND_LAUNCH_APP1            : return "launch-app1";
    case APPCOMMAND_LAUNCH_APP2            : return "launch-app2";
    case APPCOMMAND_BASS_DOWN              : return "bass-down";
    case APPCOMMAND_BASS_BOOST             : return "bass-boost";
    case APPCOMMAND_BASS_UP                : return "bass-up";
    case APPCOMMAND_TREBLE_DOWN            : return "treble-down";
    case APPCOMMAND_TREBLE_UP              : return "treble-up";
    case APPCOMMAND_MICROPHONE_VOLUME_MUTE : return "microphone-volume-mute";
    case APPCOMMAND_MICROPHONE_VOLUME_DOWN : return "microphone-volume-down";
    case APPCOMMAND_MICROPHONE_VOLUME_UP   : return "microphone-volume-up";
    case APPCOMMAND_HELP                   : return "help";
    case APPCOMMAND_FIND                   : return "find";
    case APPCOMMAND_NEW                    : return "new";
    case APPCOMMAND_OPEN                   : return "open";
    case APPCOMMAND_CLOSE                  : return "close";
    case APPCOMMAND_SAVE                   : return "save";
    case APPCOMMAND_PRINT                  : return "print";
    case APPCOMMAND_UNDO                   : return "undo";
    case APPCOMMAND_REDO                   : return "redo";
    case APPCOMMAND_COPY                   : return "copy";
    case APPCOMMAND_CUT                    : return "cut";
    case APPCOMMAND_PASTE                  : return "paste";
    case APPCOMMAND_REPLY_TO_MAIL          : return "reply-to-mail";
    case APPCOMMAND_FORWARD_MAIL           : return "forward-mail";
    case APPCOMMAND_SEND_MAIL              : return "send-mail";
    case APPCOMMAND_SPELL_CHECK            : return "spell-check";
    case APPCOMMAND_MIC_ON_OFF_TOGGLE      : return "mic-on-off-toggle";
    case APPCOMMAND_CORRECTION_LIST        : return "correction-list";
    case APPCOMMAND_MEDIA_PLAY             : return "media-play";
    case APPCOMMAND_MEDIA_PAUSE            : return "media-pause";
    case APPCOMMAND_MEDIA_RECORD           : return "media-record";
    case APPCOMMAND_MEDIA_FAST_FORWARD     : return "media-fast-forward";
    case APPCOMMAND_MEDIA_REWIND           : return "media-rewind";
    case APPCOMMAND_MEDIA_CHANNEL_UP       : return "media-channel-up";
    case APPCOMMAND_MEDIA_CHANNEL_DOWN     : return "media-channel-down";
    case APPCOMMAND_DELETE                 : return "delete";
    case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE:
      return "dictate-or-command-control-toggle";
    default:
      return "unknown";
  }
}

}  // namespace

bool NativeWindowViews::ExecuteWindowsCommand(int command_id) {
  std::string command = AppCommandToString(command_id);
  NotifyWindowExecuteWindowsCommand(command);
  return false;
}

bool NativeWindowViews::PreHandleMSG(
    UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) {
  NotifyWindowMessage(message, w_param, l_param);

  switch (message) {
    // Screen readers send WM_GETOBJECT in order to get the accessibility
    // object, so take this opportunity to push Chromium into accessible
    // mode if it isn't already, always say we didn't handle the message
    // because we still want Chromium to handle returning the actual
    // accessibility object.
    case WM_GETOBJECT: {
      const DWORD obj_id = static_cast<DWORD>(l_param);
      if (enabled_a11y_support_) return false;

      if (obj_id == OBJID_CLIENT) {
        const auto axState = content::BrowserAccessibilityState::GetInstance();
        if (axState && !axState->IsAccessibleBrowser()) {
          axState->OnScreenReaderDetected();
          enabled_a11y_support_ = true;
          Browser::Get()->OnAccessibilitySupportChanged();
        }
      }

      return false;
    }
    case WM_COMMAND:
      // Handle thumbar button click message.
      if (HIWORD(w_param) == THBN_CLICKED)
        return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param));
      return false;

    case WM_SIZE:
      // Handle window state change.
      HandleSizeEvent(w_param, l_param);
      return false;

    case WM_MOVING: {
      if (!movable_)
        ::GetWindowRect(GetAcceleratedWidget(), (LPRECT)l_param);
      return false;
    }
    case WM_MOVE: {
      last_normal_bounds_ = GetBounds();
      return false;
    }
    default:
      return false;
  }
}

void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) {
  // Here we handle the WM_SIZE event in order to figure out what is the current
  // window state and notify the user accordingly.
  switch (w_param) {
    case SIZE_MAXIMIZED:
      last_window_state_ = ui::SHOW_STATE_MAXIMIZED;
      NotifyWindowMaximize();
      break;
    case SIZE_MINIMIZED:
      last_window_state_ = ui::SHOW_STATE_MINIMIZED;
      NotifyWindowMinimize();
      break;
    case SIZE_RESTORED:
      if (last_window_state_ == ui::SHOW_STATE_NORMAL) {
        // Window was resized so we save it's new size.
        last_normal_bounds_ = GetBounds();
      } else {
        switch (last_window_state_) {
          case ui::SHOW_STATE_MAXIMIZED:
            last_window_state_ = ui::SHOW_STATE_NORMAL;

            // When the window is restored we resize it to the previous known
            // normal size.
            SetBounds(last_normal_bounds_, false);

            NotifyWindowUnmaximize();
            break;
          case ui::SHOW_STATE_MINIMIZED:
            if (IsFullscreen()) {
              last_window_state_ = ui::SHOW_STATE_FULLSCREEN;
              NotifyWindowEnterFullScreen();
            } else {
              last_window_state_ = ui::SHOW_STATE_NORMAL;

              // When the window is restored we resize it to the previous known
              // normal size.
              SetBounds(last_normal_bounds_, false);

              NotifyWindowRestore();
            }
            break;
        }
      }
      break;
  }
}

}  // namespace atom
<|endoftext|>


<commit_before>// $Id: templates.C,v 1.5 2000/02/10 15:16:57 oliver Exp $
//

#include <BALL/MOLMEC/PARAMETER/templates.h>
#include <BALL/KERNEL/residue.h>

using namespace std;

namespace BALL
{

	FFPSTemplates::FFPSTemplates()
		: FFParameterSection()
	{
	}

	FFPSTemplates::FFPSTemplates(const FFPSTemplates& templates, bool /* deep */)
		: FFParameterSection(templates)
	{
		charges_ = templates.charges_;
		type_names_ = templates.type_names_;
	}

	void FFPSTemplates::destroy()
	{
		charges_.destroy();
		type_names_.destroy();

		FFParameterSection::destroy();
	}

	FFPSTemplates::~FFPSTemplates()
	{
		destroy();
	}

	FFPSTemplates& FFPSTemplates::operator = (const FFPSTemplates& templates)
	{
		charges_.set(templates.charges_);
		type_names_.set(templates.type_names_);

		return *this;
	}

	bool FFPSTemplates::extractSection
		(ForceFieldParameters& parameters,
		 const String& section_name)
	{
		// clean up first
		type_names_.destroy();
		charges_.destroy();

		// extract the basis information
		if (!FFParameterSection::extractSection(parameters, section_name))
		{
			Log.level(LogStream::ERROR) << "Didn't find section for " << section_name << endl;
			return false;
		}

		// check for the correct entries:
		if (!hasVariable("q") || !hasVariable("type"))
		{
			Log.level(LogStream::ERROR) << "residue template section [" << section_name << "] requires variables q and type." << endl;
			return false;
		}

		// check for the correct unit
		if (!options.has("unit_q") || (options["unit_q"] != "e0"))
		{
			Log.level(LogStream::ERROR) << "unknown unit in section [" << section_name
				<< "]. Please specify charges in multiples of the elementary charge (e0)" << endl;
			return false;
		}

		// iterate over all entries and store charges and types in the
		// corresponding hash maps
		StringHashMap<Index>::Iterator	it;
		for (it = section_entries_.begin(); it != section_entries_.end(); ++it)
		{
			type_names_[it->first] = getValue(it->first, "type");
			charges_[it->first] = getValue(it->first, "q").toFloat();
		}

		return true;
	}

	bool FFPSTemplates::has(const String& name) const
	{
		return type_names_.has(name);
	}

	float FFPSTemplates::getCharge(const String& name) const
	{
		if (charges_.has(name))
		{
			return (*charges_.find(name)).second;
		} else {
			return 0.0;
		}
	}

	String FFPSTemplates::getTypeName(const String& name) const
	{
		if (type_names_.has(name))
		{
			return (*type_names_.find(name)).second;
		} else {
			return "";
		}
	}

	void FFPSTemplates::assign(System& system, bool overwrite_existing_type_names, bool overwrite_non_zero_charges) const
	{
		// remember the current parent to avoid
		// the recalculation of the parent`s name
		Fragment* parent = 0;
		String		parent_name(":");

		// iterate over all atoms
		AtomIterator it = system.beginAtom();
		for (; +it; ++it)
		{
			String name(it->getFullName());
			if (overwrite_non_zero_charges || (it->getCharge() == 0.0))
			{
				if (charges_.has(name))
				{
					it->setCharge(charges_[name]);
				} else {
					Log.warn() << "FFPSTemplates::assign: cannot assign charge for atom " << name << endl;
				}
			}
			if (overwrite_existing_type_names || (it->getTypeName() == BALL_ATOM_DEFAULT_TYPE_NAME))
			{
				if (type_names_.has(name))
				{
					it->setTypeName(type_names_[name]);
				} else {
					Log.warn() << "FFPSTemplates::assign: cannot assign type name for atom " << name << endl;
				}
			}
		}
	}

	void FFPSTemplates::assignTypeNames(System& system, bool overwrite_existing_type_names) const
	{
		// remember the current parent to avoid
		// the recalculation of the parent`s name
		Fragment* parent = 0;
		String		parent_name(":");

		// iterate over all atoms
		AtomIterator it = system.beginAtom();
		for (; +it; ++it)
		{
			// determine the parent`s name
			if (it->getFragment() != parent)
			{
				parent = it->getFragment();
				if (parent == 0)
				{
					parent_name = ":";
				} else {
					parent_name = parent->getName().trim();
					Residue* res = dynamic_cast<Residue*>(parent);
					// if the parent fragment is a residue, determine its properties
					if (res != 0)
					{
						String suffix = "-";
						if (res->isNTerminal())
						{
							suffix = "-N";
						}
						if (res->isCTerminal())
						{
							suffix = "-C";
						}
						if (res->hasProperty(Residue::PROPERTY__HAS_SSBOND))
						{
							suffix += "S";
						}

						if (suffix != "-")
						{
							parent_name += suffix;
						}
					}

					parent_name += ":";
				}
			}

			String name(parent_name + it->getName().trim());
			if ((overwrite_existing_type_names || (it->getTypeName() == BALL_ATOM_DEFAULT_TYPE_NAME)))
			{
				if (type_names_.has(name))
				{
					it->setTypeName(type_names_[name]);
				} else {
					Log.warn() << "FFPSTemplates::assignTypeNames: cannot assign type name for atom " << name << endl;
				}
			}
		}
	}

	void FFPSTemplates::assignCharges(System& system, bool overwrite_non_zero_charges) const
	{
		// remember the current parent to avoid
		// the recalculation of the parent`s name
		Fragment* parent = 0;
		String		parent_name(":");

		// iterate over all atoms
		AtomIterator it = system.beginAtom();
		for (; +it; ++it)
		{
			// determine the parent`s name
			if (it->getFragment() != parent)
			{
				parent = it->getFragment();
				if (parent == 0)
				{
					parent_name = ":";
				} else {
					parent_name = parent->getName().trim();
					Residue* res = dynamic_cast<Residue*>(parent);
					// if the parent fragment is a residue, determine its properties
					if (res != 0)
					{
						String suffix = "-";
						if (res->isNTerminal())
						{
							suffix = "-N";
						}
						if (res->isCTerminal())
						{
							suffix = "-C";
						}
						if (res->hasProperty(Residue::PROPERTY__HAS_SSBOND))
						{
							suffix += "S";
						}

						if (suffix != "-")
						{
							parent_name += suffix;
						}
					}

					parent_name += ":";
				}
			}

			String name(parent_name + it->getName().trim());
			if ((overwrite_non_zero_charges || (it->getCharge() == 0.0)))
			{
				if (charges_.has(name))
				{
					it->setCharge(charges_[name]);
				} else {
					Log.warn() << "FFPSTemplates::assignCharges: cannot assign charge for atom " << name << endl;
				}
			}
		}
	}

} // namespace BALL
<commit_msg>fxied: warning due to an unused variable<commit_after>// $Id: templates.C,v 1.6 2000/02/13 16:54:47 oliver Exp $
//

#include <BALL/MOLMEC/PARAMETER/templates.h>
#include <BALL/KERNEL/residue.h>

using namespace std;

namespace BALL
{

	FFPSTemplates::FFPSTemplates()
		: FFParameterSection()
	{
	}

	FFPSTemplates::FFPSTemplates(const FFPSTemplates& templates, bool /* deep */)
		: FFParameterSection(templates)
	{
		charges_ = templates.charges_;
		type_names_ = templates.type_names_;
	}

	void FFPSTemplates::destroy()
	{
		charges_.destroy();
		type_names_.destroy();

		FFParameterSection::destroy();
	}

	FFPSTemplates::~FFPSTemplates()
	{
		destroy();
	}

	FFPSTemplates& FFPSTemplates::operator = (const FFPSTemplates& templates)
	{
		charges_.set(templates.charges_);
		type_names_.set(templates.type_names_);

		return *this;
	}

	bool FFPSTemplates::extractSection
		(ForceFieldParameters& parameters,
		 const String& section_name)
	{
		// clean up first
		type_names_.destroy();
		charges_.destroy();

		// extract the basis information
		if (!FFParameterSection::extractSection(parameters, section_name))
		{
			Log.level(LogStream::ERROR) << "Didn't find section for " << section_name << endl;
			return false;
		}

		// check for the correct entries:
		if (!hasVariable("q") || !hasVariable("type"))
		{
			Log.level(LogStream::ERROR) << "residue template section [" << section_name << "] requires variables q and type." << endl;
			return false;
		}

		// check for the correct unit
		if (!options.has("unit_q") || (options["unit_q"] != "e0"))
		{
			Log.level(LogStream::ERROR) << "unknown unit in section [" << section_name
				<< "]. Please specify charges in multiples of the elementary charge (e0)" << endl;
			return false;
		}

		// iterate over all entries and store charges and types in the
		// corresponding hash maps
		StringHashMap<Index>::Iterator	it;
		for (it = section_entries_.begin(); it != section_entries_.end(); ++it)
		{
			type_names_[it->first] = getValue(it->first, "type");
			charges_[it->first] = getValue(it->first, "q").toFloat();
		}

		return true;
	}

	bool FFPSTemplates::has(const String& name) const
	{
		return type_names_.has(name);
	}

	float FFPSTemplates::getCharge(const String& name) const
	{
		if (charges_.has(name))
		{
			return (*charges_.find(name)).second;
		} else {
			return 0.0;
		}
	}

	String FFPSTemplates::getTypeName(const String& name) const
	{
		if (type_names_.has(name))
		{
			return (*type_names_.find(name)).second;
		} else {
			return "";
		}
	}

	void FFPSTemplates::assign(System& system, bool overwrite_existing_type_names, bool overwrite_non_zero_charges) const
	{
		// remember the current parent to avoid
		// the recalculation of the parent`s name
		String		parent_name(":");

		// iterate over all atoms
		AtomIterator it = system.beginAtom();
		for (; +it; ++it)
		{
			String name(it->getFullName());
			if (overwrite_non_zero_charges || (it->getCharge() == 0.0))
			{
				if (charges_.has(name))
				{
					it->setCharge(charges_[name]);
				} else {
					Log.warn() << "FFPSTemplates::assign: cannot assign charge for atom " << name << endl;
				}
			}
			if (overwrite_existing_type_names || (it->getTypeName() == BALL_ATOM_DEFAULT_TYPE_NAME))
			{
				if (type_names_.has(name))
				{
					it->setTypeName(type_names_[name]);
				} else {
					Log.warn() << "FFPSTemplates::assign: cannot assign type name for atom " << name << endl;
				}
			}
		}
	}

	void FFPSTemplates::assignTypeNames(System& system, bool overwrite_existing_type_names) const
	{
		// remember the current parent to avoid
		// the recalculation of the parent`s name
		Fragment* parent = 0;
		String		parent_name(":");

		// iterate over all atoms
		AtomIterator it = system.beginAtom();
		for (; +it; ++it)
		{
			// determine the parent`s name
			if (it->getFragment() != parent)
			{
				parent = it->getFragment();
				if (parent == 0)
				{
					parent_name = ":";
				} else {
					parent_name = parent->getName().trim();
					Residue* res = dynamic_cast<Residue*>(parent);
					// if the parent fragment is a residue, determine its properties
					if (res != 0)
					{
						String suffix = "-";
						if (res->isNTerminal())
						{
							suffix = "-N";
						}
						if (res->isCTerminal())
						{
							suffix = "-C";
						}
						if (res->hasProperty(Residue::PROPERTY__HAS_SSBOND))
						{
							suffix += "S";
						}

						if (suffix != "-")
						{
							parent_name += suffix;
						}
					}

					parent_name += ":";
				}
			}

			String name(parent_name + it->getName().trim());
			if ((overwrite_existing_type_names || (it->getTypeName() == BALL_ATOM_DEFAULT_TYPE_NAME)))
			{
				if (type_names_.has(name))
				{
					it->setTypeName(type_names_[name]);
				} else {
					Log.warn() << "FFPSTemplates::assignTypeNames: cannot assign type name for atom " << name << endl;
				}
			}
		}
	}

	void FFPSTemplates::assignCharges(System& system, bool overwrite_non_zero_charges) const
	{
		// remember the current parent to avoid
		// the recalculation of the parent`s name
		Fragment* parent = 0;
		String		parent_name(":");

		// iterate over all atoms
		AtomIterator it = system.beginAtom();
		for (; +it; ++it)
		{
			// determine the parent`s name
			if (it->getFragment() != parent)
			{
				parent = it->getFragment();
				if (parent == 0)
				{
					parent_name = ":";
				} else {
					parent_name = parent->getName().trim();
					Residue* res = dynamic_cast<Residue*>(parent);
					// if the parent fragment is a residue, determine its properties
					if (res != 0)
					{
						String suffix = "-";
						if (res->isNTerminal())
						{
							suffix = "-N";
						}
						if (res->isCTerminal())
						{
							suffix = "-C";
						}
						if (res->hasProperty(Residue::PROPERTY__HAS_SSBOND))
						{
							suffix += "S";
						}

						if (suffix != "-")
						{
							parent_name += suffix;
						}
					}

					parent_name += ":";
				}
			}

			String name(parent_name + it->getName().trim());
			if ((overwrite_non_zero_charges || (it->getCharge() == 0.0)))
			{
				if (charges_.has(name))
				{
					it->setCharge(charges_[name]);
				} else {
					Log.warn() << "FFPSTemplates::assignCharges: cannot assign charge for atom " << name << endl;
				}
			}
		}
	}

} // namespace BALL
<|endoftext|>


<commit_before>// $Id: PoissonBoltzmann_test.C,v 1.4 2000/05/04 19:57:47 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

#include <BALL/SOLVATION/poissonBoltzmann.h>

#undef PRECISION
#define PRECISION 0.005

START_TEST(FDPB, "$Id: PoissonBoltzmann_test.C,v 1.4 2000/05/04 19:57:47 oliver Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

System*		system = new System;
Atom*			atom = new Atom;
Molecule*	molecule = new Molecule;
molecule->insert(*atom);
system->insert(*molecule);
atom->setRadius( 2.0);
atom->setCharge(+1.0);

FDPB*		fdpb;

CHECK(default constructor)
	fdpb = new FDPB;
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

CHECK(destructor)
	delete fdpb;
RESULT

CHECK(constructor/1)
	fdpb = new FDPB(*system);
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

Options options;
CHECK(constructor/2)
	options = fdpb->options;
	delete fdpb;
	fdpb = new FDPB(options);
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

CHECK(constructor/3)
	delete fdpb;
	options.destroy();
	options.setReal(FDPB::Option::SOLVENT_DC, 78.0);
	options.setReal(FDPB::Option::SOLUTE_DC, 1.0);
	options.setReal(FDPB::Option::SPACING, 0.4);
	options.setReal(FDPB::Option::BORDER, 10.0);
	options.set(FDPB::Option::CHARGE_DISTRIBUTION, FDPB::ChargeDistribution::UNIFORM);
	options.set(FDPB::Option::DIELECTRIC_SMOOTHING, FDPB::DielectricSmoothing::NONE);
	options[FDPB::Option::IONIC_STRENGTH] = 0.0;
	options[FDPB::Option::VERBOSITY] = 0;
	fdpb = new FDPB(*system, options);
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

CHECK(solve)
	fdpb->solve();
	TEST_EQUAL(fdpb->results["converged"], "true")
RESULT

CHECK(energy - reaction field energy - and numerical accuracy)
	float E_water = fdpb->getEnergy();
	float E_RF_water = fdpb->getReactionFieldEnergy();

	fdpb->options.setReal(FDPB::Option::SOLVENT_DC, 1.0);
	fdpb->setup(*system);
	fdpb->solve();
	float E_vacuum = fdpb->getEnergy();
	float E_RF_vacuum = fdpb->getReactionFieldEnergy();

#undef PRECISION
#define PRECISION 0.5
	TEST_REAL_EQUAL(E_water - E_vacuum, -357.68)
#undef PRECISION
#define PRECISION 0.005
	TEST_REAL_EQUAL(E_RF_water, -342.897)
	TEST_REAL_EQUAL(E_RF_vacuum, 0.0)
	delete fdpb;
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

END_TEST
<commit_msg>changed: PRECISION adapted to problems with Linux<commit_after>// $Id: PoissonBoltzmann_test.C,v 1.5 2000/05/05 18:01:08 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

#include <BALL/SOLVATION/poissonBoltzmann.h>

#undef PRECISION
#define PRECISION 0.005

START_TEST(FDPB, "$Id: PoissonBoltzmann_test.C,v 1.5 2000/05/05 18:01:08 oliver Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

System*		system = new System;
Atom*			atom = new Atom;
Molecule*	molecule = new Molecule;
molecule->insert(*atom);
system->insert(*molecule);
atom->setRadius( 2.0);
atom->setCharge(+1.0);

FDPB*		fdpb;

CHECK(default constructor)
	fdpb = new FDPB;
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

CHECK(destructor)
	delete fdpb;
RESULT

CHECK(constructor/1)
	fdpb = new FDPB(*system);
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

Options options;
CHECK(constructor/2)
	options = fdpb->options;
	delete fdpb;
	fdpb = new FDPB(options);
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

CHECK(constructor/3)
	delete fdpb;
	options.destroy();
	options.setReal(FDPB::Option::SOLVENT_DC, 78.0);
	options.setReal(FDPB::Option::SOLUTE_DC, 1.0);
	options.setReal(FDPB::Option::SPACING, 0.4);
	options.setReal(FDPB::Option::BORDER, 10.0);
	options.set(FDPB::Option::CHARGE_DISTRIBUTION, FDPB::ChargeDistribution::UNIFORM);
	options.set(FDPB::Option::DIELECTRIC_SMOOTHING, FDPB::DielectricSmoothing::NONE);
	options[FDPB::Option::IONIC_STRENGTH] = 0.0;
	options[FDPB::Option::VERBOSITY] = 0;
	fdpb = new FDPB(*system, options);
	TEST_NOT_EQUAL(fdpb, 0)
RESULT

CHECK(solve)
	fdpb->solve();
	TEST_EQUAL(fdpb->results["converged"], "true")
RESULT

CHECK(energy - reaction field energy - and numerical accuracy)
	float E_water = fdpb->getEnergy();
	float E_RF_water = fdpb->getReactionFieldEnergy();

	fdpb->options.setReal(FDPB::Option::SOLVENT_DC, 1.0);
	fdpb->setup(*system);
	fdpb->solve();
	float E_vacuum = fdpb->getEnergy();
	float E_RF_vacuum = fdpb->getReactionFieldEnergy();

#undef PRECISION
#define PRECISION 1.0
	TEST_REAL_EQUAL(E_water - E_vacuum, -357.68)
#undef PRECISION
#define PRECISION 0.005
	TEST_REAL_EQUAL(E_RF_water, -342.897)
	TEST_REAL_EQUAL(E_RF_vacuum, 0.0)
	delete fdpb;
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

END_TEST
<|endoftext|>


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

#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <mutex>
#include <miopen/errors.hpp>
#include <miopen/config.h>

namespace miopen {

#define MIOPEN_DECLARE_HANDLE_MUTEX(x)                               \
    struct x                                                         \
    {                                                                \
        static const char* value() { return ".miopen-" #x ".lock"; } \
    };

#if MIOPEN_GPU_SYNC
MIOPEN_DECLARE_HANDLE_MUTEX(gpu_handle_mutex)
#define MIOPEN_HANDLE_LOCK \
    auto miopen_handle_lock_guard_##__LINE__ = miopen::get_handle_lock(miopen::gpu_handle_mutex{});
#else
#define MIOPEN_HANDLE_LOCK
#endif

inline boost::filesystem::path get_handle_lock_path(const char* name)
{
    auto p = boost::filesystem::current_path() / name;
    if(!boost::filesystem::exists(p))
    {
        auto tmp = boost::filesystem::current_path() / boost::filesystem::unique_path();
        boost::filesystem::ofstream{tmp};
        boost::filesystem::rename(tmp, p);
    }
    return p;
}

using handle_mutex = boost::interprocess::file_lock;
template <class T>
inline handle_mutex& get_handle_mutex(T)
{
    static handle_mutex m{get_handle_lock_path(T::value()).c_str()};
    return m;
}

using handle_lock = std::unique_lock<handle_mutex>;
template <class T>
inline handle_lock get_handle_lock(T)
{
    auto& m = get_handle_mutex(T{});
    if(m.timed_lock(boost::posix_time::second_clock::universal_time() +
                    boost::posix_time::seconds(120)))
    {
        return {m, std::adopt_lock_t{}};
    }
    else
    {
        m.unlock();
        MIOPEN_THROW("GPU is stalled");
    }
}

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

#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <mutex>
#include <miopen/errors.hpp>
#include <miopen/config.h>

namespace miopen {

#define MIOPEN_DECLARE_HANDLE_MUTEX(x)                               \
    struct x                                                         \
    {                                                                \
        static const char* value() { return ".miopen-" #x ".lock"; } \
    };

#if MIOPEN_GPU_SYNC
MIOPEN_DECLARE_HANDLE_MUTEX(gpu_handle_mutex)
#define MIOPEN_HANDLE_LOCK \
    auto miopen_handle_lock_guard_##__LINE__ = miopen::get_handle_lock(miopen::gpu_handle_mutex{});
#else
#define MIOPEN_HANDLE_LOCK
#endif

inline boost::filesystem::path get_handle_lock_path(const char* name)
{
    auto p = boost::filesystem::current_path() / name;
    if(!boost::filesystem::exists(p))
    {
        auto tmp = boost::filesystem::current_path() / boost::filesystem::unique_path();
        boost::filesystem::ofstream{tmp};
        boost::filesystem::rename(tmp, p);
    }
    return p;
}

using handle_mutex = boost::interprocess::file_lock;
template <class T>
inline handle_mutex& get_handle_mutex(T)
{
    static handle_mutex m{get_handle_lock_path(T::value()).c_str()};
    return m;
}

using handle_lock = std::unique_lock<handle_mutex>;
template <class T>
inline handle_lock get_handle_lock(T, int timeout = 120)
{
    auto& m = get_handle_mutex(T{});
    if(m.timed_lock(boost::posix_time::second_clock::universal_time() +
                    boost::posix_time::seconds(timeout)))
    {
        return {m, std::adopt_lock_t{}};
    }
    else
    {
        m.unlock();
        MIOPEN_THROW("GPU is stalled");
    }
}

} // namespace miopen
<|endoftext|>


<commit_before>//---------------------------------------------------------
// Copyright 2019 Ontario Institute for Cancer Research
// Written by Jared Simpson (jared.simpson@oicr.on.ca)
//---------------------------------------------------------
//
// nanopolish_fast5_loader -- A class that manages
// opening and reading from fast5 files
//
#include <omp.h>
#include "nanopolish_fast5_loader.h"

//
Fast5Loader::Fast5Loader()
{

}

//
Fast5Loader::~Fast5Loader()
{

}

Fast5Data Fast5Loader::load_read(const std::string& filename, const std::string& read_name)
{
    Fast5Data data;
    fast5_file f5_file = fast5_open(filename);
    if(!fast5_is_open(f5_file)) {
        data.is_valid = false;
        return data;
    }

    data.read_name = read_name;
    data.is_valid = true;

    // metadata
    data.sequencing_kit = fast5_get_sequencing_kit(f5_file, read_name);
    data.experiment_type = fast5_get_experiment_type(f5_file, read_name);

    // raw data
    data.channel_params = fast5_get_channel_params(f5_file, read_name);
    data.rt = fast5_get_raw_samples(f5_file, read_name, data.channel_params);

    data.start_time = fast5_get_start_time(f5_file, read_name);
    fast5_close(f5_file);

    return data;
}
<commit_msg>initialize fast5 data structure<commit_after>//---------------------------------------------------------
// Copyright 2019 Ontario Institute for Cancer Research
// Written by Jared Simpson (jared.simpson@oicr.on.ca)
//---------------------------------------------------------
//
// nanopolish_fast5_loader -- A class that manages
// opening and reading from fast5 files
//
#include <omp.h>
#include "nanopolish_fast5_loader.h"

//
Fast5Loader::Fast5Loader()
{

}

//
Fast5Loader::~Fast5Loader()
{

}

Fast5Data Fast5Loader::load_read(const std::string& filename, const std::string& read_name)
{
    Fast5Data data;
    data.rt.n = 0;
    data.rt.raw = NULL;

    fast5_file f5_file = fast5_open(filename);
    if(!fast5_is_open(f5_file)) {
        data.is_valid = false;
        return data;
    }

    data.read_name = read_name;
    data.is_valid = true;

    // metadata
    data.sequencing_kit = fast5_get_sequencing_kit(f5_file, read_name);
    data.experiment_type = fast5_get_experiment_type(f5_file, read_name);

    // raw data
    data.channel_params = fast5_get_channel_params(f5_file, read_name);
    data.rt = fast5_get_raw_samples(f5_file, read_name, data.channel_params);

    data.start_time = fast5_get_start_time(f5_file, read_name);
    fast5_close(f5_file);

    return data;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

#include "joedb/io/type_io.h"
#include "joedb/io/base64.h"
#include "joedb/compiler/nested_namespace.h"

/////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
/////////////////////////////////////////////////////////////////////////////
{
 if (argc != 4 && argc != 5)
 {
  std::cerr << "usage: " << argv[0];
  std::cerr << " [--base64|raw|escape] <file_name.joedb> <namespace> <identifier>\n";
  std::cerr << "output: <namespace>_<identifer>.{h,cpp}\n";
  return 1;
 }

 enum Mode {base64, raw, escape};

 Mode mode = escape;

 if (argc == 5)
 {
  argv++;
  if (argv[0] == std::string("--base64"))
   mode = base64;
  else if (argv[0] == std::string("--raw"))
   mode = raw;
  else if (argv[0] == std::string("--escape"))
   mode = escape;
 }

 char const * const joedb_file_name = argv[1];
 std::vector<std::string> name_space = joedb::split_namespace(argv[2]);
 char const * const identifier = argv[3];

 std::ostringstream file_name;
 file_name << name_space.back() << '_' << identifier;

 {
  std::ofstream cpp
  (
   file_name.str() + ".cpp",
   std::ios::binary | std::ios::out
  );

  std::ostringstream file_content;

  {
   std::ifstream in(joedb_file_name, std::ios::binary | std::ios::in);
   file_content << in.rdbuf();
  }

  cpp << "#include \"" << file_name.str() << ".h\"\n";
  cpp << "#include \"" << name_space.back() << "_readonly.h\"\n";
  cpp << "#include \"joedb/journal/Readonly_Memory_File.h\"\n";
  if (mode == base64)
   cpp << "#include \"joedb/io/base64.h\"\n";
  cpp << '\n';
  cpp << "#include <memory>\n\n";

  joedb::namespace_open(cpp, name_space);

  if (mode != base64)
  {
   cpp << " const size_t " << identifier << "_size = ";
   cpp << file_content.str().size() << ";\n";
  }
  cpp << " char const * const " << identifier << "_data = ";

  if (mode == raw)
  {
   char const * const delimiter = "glouglou";
   // TODO: generate delimiter from data
   cpp << "R\"" << delimiter << "(";
   cpp << file_content.str();
   cpp << ")" << delimiter << '\"';
  }
  else if (mode == escape)
   joedb::write_string(cpp, file_content.str());
  else if (mode == base64)
   cpp << '"' << joedb::base64_encode(file_content.str()) << '"';

  cpp << ";\n\n";

  cpp << " struct struct_for_" << identifier << '\n';
  cpp << " {\n";
  cpp << "  std::unique_ptr<Database> db;\n";
  cpp << '\n';
  cpp << "  struct_for_" << identifier << "()\n";
  cpp << "  {\n";

  if (mode == base64)
  {
   cpp << "   const std::string decoded(joedb::base64_decode(" << identifier << "_data));\n";
   cpp << "   joedb::Readonly_Memory_File file(&decoded[0], decoded.size());\n";
  }
  else
  {
   cpp << "   joedb::Readonly_Memory_File file(" << identifier << "_data, " << identifier << "_size);\n";
  }

  cpp << "   db.reset(new Readonly_Database(file));\n";
  cpp << "  }\n";
  cpp << " };\n";
  cpp << '\n';
  cpp << " const Database &get_embedded_" << identifier << "()\n";
  cpp << " {\n";
  cpp << "  static struct_for_" << identifier << " s;\n";
  cpp << "  return *s.db;\n";
  cpp << " }\n";

  if (mode != base64)
  {
   cpp << "\n size_t get_embedded_" << identifier;
   cpp << "_size() {return " << identifier << "_size;}\n";

   cpp << " char const *get_embedded_" << identifier;
   cpp << "_data() {return " << identifier << "_data;}\n";
  }

  joedb::namespace_close(cpp, name_space);
 }

 {
  std::ofstream h(file_name.str() + ".h", std::ios::binary | std::ios::out);

  joedb::namespace_include_guard(h, identifier, name_space);

  h << "\n#include <stddef.h>\n\n";

  joedb::namespace_open(h, name_space);

  h << " class Database;\n";
  h << " const Database &get_embedded_" << identifier << "();\n";

  if (mode != base64)
  {
   h << " size_t get_embedded_" << identifier << "_size();\n";
   h << " char const *get_embedded_" << identifier << "_data();\n";
  }

  joedb::namespace_close(h, name_space);

  h << "#endif\n";
 }

 return 0;
}
<commit_msg>test for file-opening error in joedb_embed<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

#include "joedb/io/type_io.h"
#include "joedb/io/base64.h"
#include "joedb/compiler/nested_namespace.h"

/////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
/////////////////////////////////////////////////////////////////////////////
{
 if (argc != 4 && argc != 5)
 {
  std::cerr << "usage: " << argv[0];
  std::cerr << " [--base64|raw|escape] <file_name.joedb> <namespace> <identifier>\n";
  std::cerr << "output: <namespace>_<identifer>.{h,cpp}\n";
  return 1;
 }

 enum Mode {base64, raw, escape};

 Mode mode = escape;

 if (argc == 5)
 {
  argv++;
  if (argv[0] == std::string("--base64"))
   mode = base64;
  else if (argv[0] == std::string("--raw"))
   mode = raw;
  else if (argv[0] == std::string("--escape"))
   mode = escape;
 }

 char const * const joedb_file_name = argv[1];
 std::vector<std::string> name_space = joedb::split_namespace(argv[2]);
 char const * const identifier = argv[3];

 std::ostringstream file_name;
 file_name << name_space.back() << '_' << identifier;

 {
  std::ofstream cpp
  (
   file_name.str() + ".cpp",
   std::ios::binary | std::ios::out
  );

  std::ostringstream file_content;

  {
   std::ifstream in(joedb_file_name, std::ios::binary | std::ios::in);
   if (!in.good())
   {
    std::cerr << "Error opening " << joedb_file_name << '\n';
    return 1;
   }
   file_content << in.rdbuf();
  }

  cpp << "#include \"" << file_name.str() << ".h\"\n";
  cpp << "#include \"" << name_space.back() << "_readonly.h\"\n";
  cpp << "#include \"joedb/journal/Readonly_Memory_File.h\"\n";
  if (mode == base64)
   cpp << "#include \"joedb/io/base64.h\"\n";
  cpp << '\n';
  cpp << "#include <memory>\n\n";

  joedb::namespace_open(cpp, name_space);

  if (mode != base64)
  {
   cpp << " const size_t " << identifier << "_size = ";
   cpp << file_content.str().size() << ";\n";
  }
  cpp << " char const * const " << identifier << "_data = ";

  if (mode == raw)
  {
   char const * const delimiter = "glouglou";
   // TODO: generate delimiter from data
   cpp << "R\"" << delimiter << "(";
   cpp << file_content.str();
   cpp << ")" << delimiter << '\"';
  }
  else if (mode == escape)
   joedb::write_string(cpp, file_content.str());
  else if (mode == base64)
   cpp << '"' << joedb::base64_encode(file_content.str()) << '"';

  cpp << ";\n\n";

  cpp << " struct struct_for_" << identifier << '\n';
  cpp << " {\n";
  cpp << "  std::unique_ptr<Database> db;\n";
  cpp << '\n';
  cpp << "  struct_for_" << identifier << "()\n";
  cpp << "  {\n";

  if (mode == base64)
  {
   cpp << "   const std::string decoded(joedb::base64_decode(" << identifier << "_data));\n";
   cpp << "   joedb::Readonly_Memory_File file(&decoded[0], decoded.size());\n";
  }
  else
  {
   cpp << "   joedb::Readonly_Memory_File file(" << identifier << "_data, " << identifier << "_size);\n";
  }

  cpp << "   db.reset(new Readonly_Database(file));\n";
  cpp << "  }\n";
  cpp << " };\n";
  cpp << '\n';
  cpp << " const Database &get_embedded_" << identifier << "()\n";
  cpp << " {\n";
  cpp << "  static struct_for_" << identifier << " s;\n";
  cpp << "  return *s.db;\n";
  cpp << " }\n";

  if (mode != base64)
  {
   cpp << "\n size_t get_embedded_" << identifier;
   cpp << "_size() {return " << identifier << "_size;}\n";

   cpp << " char const *get_embedded_" << identifier;
   cpp << "_data() {return " << identifier << "_data;}\n";
  }

  joedb::namespace_close(cpp, name_space);
 }

 {
  std::ofstream h(file_name.str() + ".h", std::ios::binary | std::ios::out);

  joedb::namespace_include_guard(h, identifier, name_space);

  h << "\n#include <stddef.h>\n\n";

  joedb::namespace_open(h, name_space);

  h << " class Database;\n";
  h << " const Database &get_embedded_" << identifier << "();\n";

  if (mode != base64)
  {
   h << " size_t get_embedded_" << identifier << "_size();\n";
   h << " char const *get_embedded_" << identifier << "_data();\n";
  }

  joedb::namespace_close(h, name_space);

  h << "#endif\n";
 }

 return 0;
}
<|endoftext|>