<commit_before>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef MFEM_ELASTICITY_MAT_NEOHOOKEAN_HPP
#define MFEM_ELASTICITY_MAT_NEOHOOKEAN_HPP

#include "general/enzyme.hpp"
#include "gradient_type.hpp"
#include "linalg/tensor.hpp"
#include "mfem.hpp"

using mfem::internal::tensor;
using mfem::internal::make_tensor;

/**
 * @brief Neo-Hookean material
 *
 * Defines a Neo-Hookean material response. It satisfies the material_type
 * interface for ElasticityOperator::SetMaterial. This material type allows
 * choosing the method of derivative calculation in `action_of_gradient`.
 * Choices include methods derived by hand using symbolic calculation and a
 * variety of automatically computed gradient applications, like
 * - Enzyme forward mode
 * - Enzyme reverse mode
 * - Dual number type forward mode
 * - Finite difference mode
 *
 * @tparam dim
 * @tparam gradient_type
 */
template <int dim = 3, GradientType gradient_type = GradientType::Symbolic>
struct NeoHookeanMaterial
{
   static_assert(dim == 3, "NeoHookean model currently implemented only in 3D");

   /**
    * @brief Compute the stress response.
    *
    * @param[in] dudx derivative of the displacement
    * @return
    */
   template <typename T>
   MFEM_HOST_DEVICE tensor<T, dim, dim>
   stress(const tensor<T, dim, dim> &__restrict__ dudx) const
   {
      constexpr auto I = mfem::internal::IsotropicIdentity<dim>();
      T J = det(I + dudx);
      T p = -2.0 * D1 * J * (J - 1);
      auto devB = dev(dudx + transpose(dudx) + dot(dudx, transpose(dudx)));
      auto sigma = -(p / J) * I + 2 * (C1 / pow(J, 5.0 / 3.0)) * devB;
      return sigma;
   }

   /**
    * @brief A method to wrap the stress calculation into a static function.
    *
    * This is necessary for Enzyme to access the class pointer (self).
    *
    * @param[in] self
    * @param[in] dudx
    * @param[in] sigma
    * @return stress
    */
   MFEM_HOST_DEVICE static void
   stress_wrapper(NeoHookeanMaterial<dim, gradient_type> *self,
                  tensor<double, dim, dim> &dudx,
                  tensor<double, dim, dim> &sigma)
   {
      sigma = self->stress(dudx);
   }

   /**
    * @brief Compute the gradient.
    *
    * This method is used in the ElasticityDiagonalPreconditioner type to
    * compute the gradient matrix entries of the current quadrature point,
    * instead of the action.
    *
    * @param[in] dudx
    * @return
    */
   MFEM_HOST_DEVICE tensor<double, dim, dim, dim, dim>
   gradient(tensor<double, dim, dim> dudx) const
   {
      constexpr auto I = mfem::internal::IsotropicIdentity<dim>();

      tensor<double, dim, dim> F = I + dudx;
      tensor<double, dim, dim> invF = inv(F);
      tensor<double, dim, dim> devB =
         dev(dudx + transpose(dudx) + dot(dudx, transpose(dudx)));
      double J = det(F);
      double coef = (C1 / pow(J, 5.0 / 3.0));
      return make_tensor<dim, dim, dim, dim>([&](int i, int j, int k,
                                                 int l)
      {
         return 2.0 * (D1 * J * (i == j) - (5.0 / 3.0) * coef * devB[i][j]) *
                invF[l][k] +
                2.0 * coef *
                ((i == k) * F[j][l] + F[i][l] * (j == k) -
                 (2.0 / 3.0) * ((i == j) * F[k][l]));
      });
   }

   /**
    * @brief Apply the gradient of the stress.
    *
    * @param[in] dudx
    * @param[in] ddudx
    * @return
    */
   MFEM_HOST_DEVICE tensor<double, dim, dim>
   action_of_gradient(const tensor<double, dim, dim> &dudx,
                      const tensor<double, dim, dim> &ddudx) const
   {
      if (gradient_type == GradientType::Symbolic)
      {
         return action_of_gradient_symbolic(dudx, ddudx);
      }
#ifdef MFEM_USE_ENZYME
      else if (gradient_type == GradientType::EnzymeFwd)
      {
         return action_of_gradient_enzyme_fwd(dudx, ddudx);
      }
      else if (gradient_type == GradientType::EnzymeRev)
      {
         return action_of_gradient_enzyme_rev(dudx, ddudx);
      }
#endif
      else if (gradient_type == GradientType::FiniteDiff)
      {
         return action_of_gradient_finite_diff(dudx, ddudx);
      }
      else if (gradient_type == GradientType::InternalFwd)
      {
         return action_of_gradient_dual(dudx, ddudx);
      }
   }

   MFEM_HOST_DEVICE tensor<double, dim, dim>
   action_of_gradient_dual(const tensor<double, dim, dim> &dudx,
                           const tensor<double, dim, dim> &ddudx) const
   {
      auto sigma = stress(make_tensor<dim, dim>([&](int i, int j)
      {
         return mfem::internal::dual<double, double> {dudx[i][j], ddudx[i][j]};
      }));
      return make_tensor<dim, dim>(
      [&](int i, int j) { return sigma[i][j].gradient; });
   }

#ifdef MFEM_USE_ENZYME
   MFEM_HOST_DEVICE tensor<double, dim, dim>
   action_of_gradient_enzyme_fwd(const tensor<double, dim, dim> &dudx,
                                 const tensor<double, dim, dim> &ddudx) const
   {
      tensor<double, dim, dim> sigma{};
      tensor<double, dim, dim> dsigma{};

      __enzyme_fwddiff<void>(stress_wrapper, enzyme_const, this, enzyme_dup,
                             &dudx, &ddudx, enzyme_dupnoneed, &sigma, &dsigma);
      return dsigma;
   }

   MFEM_HOST_DEVICE tensor<double, dim, dim>
   action_of_gradient_enzyme_rev(const tensor<double, dim, dim> &dudx,
                                 const tensor<double, dim, dim> &ddudx) const
   {
      tensor<double, dim, dim, dim, dim> gradient{};
      tensor<double, dim, dim> sigma{};
      tensor<double, dim, dim> dir{};

      for (int i = 0; i < dim; i++)
      {
         for (int j = 0; j < dim; j++)
         {
            dir[i][j] = 1;
            __enzyme_autodiff<void>(stress_wrapper, enzyme_const, this, enzyme_dup,
                                    &dudx, &gradient[i][j], enzyme_dupnoneed,
                                    &sigma, &dir);
            dir[i][j] = 0;
         }
      }
      return ddot(gradient, ddudx);
   }
#endif

   MFEM_HOST_DEVICE tensor<double, dim, dim>
   action_of_gradient_finite_diff(const tensor<double, dim, dim> &dudx,
                         const tensor<double, dim, dim> &ddudx) const
   {
      return (stress(dudx + 1.0e-8 * ddudx) - stress(dudx - 1.0e-8 * ddudx)) /
             2.0e-8;
   }

   // d(stress)_{ij} := (d(stress)_ij / d(du_dx)_{kl}) * d(du_dx)_{kl}
   // Only works with 3D stress
   MFEM_HOST_DEVICE tensor<double, dim, dim>
   action_of_gradient_symbolic(const tensor<double, dim, dim> &du_dx,
                               const tensor<double, dim, dim> &ddu_dx) const
   {
      constexpr auto I = mfem::internal::IsotropicIdentity<dim>();

      tensor<double, dim, dim> F = I + du_dx;
      tensor<double, dim, dim> invFT = inv(transpose(F));
      tensor<double, dim, dim> devB =
         dev(du_dx + transpose(du_dx) + dot(du_dx, transpose(du_dx)));
      double J = det(F);
      double coef = (C1 / pow(J, 5.0 / 3.0));
      double a1 = ddot(invFT, ddu_dx);
      double a2 = ddot(F, ddu_dx);

      return (2.0 * D1 * J * a1 - (4.0 / 3.0) * coef * a2) * I -
             ((10.0 / 3.0) * coef * a1) * devB +
             (2 * coef) * (dot(ddu_dx, transpose(F)) + dot(F, transpose(ddu_dx)));
   }

   // Parameters
   double D1 = 100.0;
   double C1 = 50.0;
};

#endif
<commit_msg>remove restrict keyword<commit_after>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef MFEM_ELASTICITY_MAT_NEOHOOKEAN_HPP
#define MFEM_ELASTICITY_MAT_NEOHOOKEAN_HPP

#include "general/enzyme.hpp"
#include "gradient_type.hpp"
#include "linalg/tensor.hpp"
#include "mfem.hpp"

using mfem::internal::tensor;
using mfem::internal::make_tensor;

/**
 * @brief Neo-Hookean material
 *
 * Defines a Neo-Hookean material response. It satisfies the material_type
 * interface for ElasticityOperator::SetMaterial. This material type allows
 * choosing the method of derivative calculation in `action_of_gradient`.
 * Choices include methods derived by hand using symbolic calculation and a
 * variety of automatically computed gradient applications, like
 * - Enzyme forward mode
 * - Enzyme reverse mode
 * - Dual number type forward mode
 * - Finite difference mode
 *
 * @tparam dim
 * @tparam gradient_type
 */
template <int dim = 3, GradientType gradient_type = GradientType::Symbolic>
struct NeoHookeanMaterial
{
   static_assert(dim == 3, "NeoHookean model currently implemented only in 3D");

   /**
    * @brief Compute the stress response.
    *
    * @param[in] dudx derivative of the displacement
    * @return
    */
   template <typename T>
   MFEM_HOST_DEVICE tensor<T, dim, dim>
   stress(const tensor<T, dim, dim> &dudx) const
   {
      constexpr auto I = mfem::internal::IsotropicIdentity<dim>();
      T J = det(I + dudx);
      T p = -2.0 * D1 * J * (J - 1);
      auto devB = dev(dudx + transpose(dudx) + dot(dudx, transpose(dudx)));
      auto sigma = -(p / J) * I + 2 * (C1 / pow(J, 5.0 / 3.0)) * devB;
      return sigma;
   }

   /**
    * @brief A method to wrap the stress calculation into a static function.
    *
    * This is necessary for Enzyme to access the class pointer (self).
    *
    * @param[in] self
    * @param[in] dudx
    * @param[in] sigma
    * @return stress
    */
   MFEM_HOST_DEVICE static void
   stress_wrapper(NeoHookeanMaterial<dim, gradient_type> *self,
                  tensor<double, dim, dim> &dudx,
                  tensor<double, dim, dim> &sigma)
   {
      sigma = self->stress(dudx);
   }

   /**
    * @brief Compute the gradient.
    *
    * This method is used in the ElasticityDiagonalPreconditioner type to
    * compute the gradient matrix entries of the current quadrature point,
    * instead of the action.
    *
    * @param[in] dudx
    * @return
    */
   MFEM_HOST_DEVICE tensor<double, dim, dim, dim, dim>
   gradient(tensor<double, dim, dim> dudx) const
   {
      constexpr auto I = mfem::internal::IsotropicIdentity<dim>();

      tensor<double, dim, dim> F = I + dudx;
      tensor<double, dim, dim> invF = inv(F);
      tensor<double, dim, dim> devB =
         dev(dudx + transpose(dudx) + dot(dudx, transpose(dudx)));
      double J = det(F);
      double coef = (C1 / pow(J, 5.0 / 3.0));
      return make_tensor<dim, dim, dim, dim>([&](int i, int j, int k,
                                                 int l)
      {
         return 2.0 * (D1 * J * (i == j) - (5.0 / 3.0) * coef * devB[i][j]) *
                invF[l][k] +
                2.0 * coef *
                ((i == k) * F[j][l] + F[i][l] * (j == k) -
                 (2.0 / 3.0) * ((i == j) * F[k][l]));
      });
   }

   /**
    * @brief Apply the gradient of the stress.
    *
    * @param[in] dudx
    * @param[in] ddudx
    * @return
    */
   MFEM_HOST_DEVICE tensor<double, dim, dim>
   action_of_gradient(const tensor<double, dim, dim> &dudx,
                      const tensor<double, dim, dim> &ddudx) const
   {
      if (gradient_type == GradientType::Symbolic)
      {
         return action_of_gradient_symbolic(dudx, ddudx);
      }
#ifdef MFEM_USE_ENZYME
      else if (gradient_type == GradientType::EnzymeFwd)
      {
         return action_of_gradient_enzyme_fwd(dudx, ddudx);
      }
      else if (gradient_type == GradientType::EnzymeRev)
      {
         return action_of_gradient_enzyme_rev(dudx, ddudx);
      }
#endif
      else if (gradient_type == GradientType::FiniteDiff)
      {
         return action_of_gradient_finite_diff(dudx, ddudx);
      }
      else if (gradient_type == GradientType::InternalFwd)
      {
         return action_of_gradient_dual(dudx, ddudx);
      }
   }

   MFEM_HOST_DEVICE tensor<double, dim, dim>
   action_of_gradient_dual(const tensor<double, dim, dim> &dudx,
                           const tensor<double, dim, dim> &ddudx) const
   {
      auto sigma = stress(make_tensor<dim, dim>([&](int i, int j)
      {
         return mfem::internal::dual<double, double> {dudx[i][j], ddudx[i][j]};
      }));
      return make_tensor<dim, dim>(
      [&](int i, int j) { return sigma[i][j].gradient; });
   }

#ifdef MFEM_USE_ENZYME
   MFEM_HOST_DEVICE tensor<double, dim, dim>
   action_of_gradient_enzyme_fwd(const tensor<double, dim, dim> &dudx,
                                 const tensor<double, dim, dim> &ddudx) const
   {
      tensor<double, dim, dim> sigma{};
      tensor<double, dim, dim> dsigma{};

      __enzyme_fwddiff<void>(stress_wrapper, enzyme_const, this, enzyme_dup,
                             &dudx, &ddudx, enzyme_dupnoneed, &sigma, &dsigma);
      return dsigma;
   }

   MFEM_HOST_DEVICE tensor<double, dim, dim>
   action_of_gradient_enzyme_rev(const tensor<double, dim, dim> &dudx,
                                 const tensor<double, dim, dim> &ddudx) const
   {
      tensor<double, dim, dim, dim, dim> gradient{};
      tensor<double, dim, dim> sigma{};
      tensor<double, dim, dim> dir{};

      for (int i = 0; i < dim; i++)
      {
         for (int j = 0; j < dim; j++)
         {
            dir[i][j] = 1;
            __enzyme_autodiff<void>(stress_wrapper, enzyme_const, this, enzyme_dup,
                                    &dudx, &gradient[i][j], enzyme_dupnoneed,
                                    &sigma, &dir);
            dir[i][j] = 0;
         }
      }
      return ddot(gradient, ddudx);
   }
#endif

   MFEM_HOST_DEVICE tensor<double, dim, dim>
   action_of_gradient_finite_diff(const tensor<double, dim, dim> &dudx,
                         const tensor<double, dim, dim> &ddudx) const
   {
      return (stress(dudx + 1.0e-8 * ddudx) - stress(dudx - 1.0e-8 * ddudx)) /
             2.0e-8;
   }

   // d(stress)_{ij} := (d(stress)_ij / d(du_dx)_{kl}) * d(du_dx)_{kl}
   // Only works with 3D stress
   MFEM_HOST_DEVICE tensor<double, dim, dim>
   action_of_gradient_symbolic(const tensor<double, dim, dim> &du_dx,
                               const tensor<double, dim, dim> &ddu_dx) const
   {
      constexpr auto I = mfem::internal::IsotropicIdentity<dim>();

      tensor<double, dim, dim> F = I + du_dx;
      tensor<double, dim, dim> invFT = inv(transpose(F));
      tensor<double, dim, dim> devB =
         dev(du_dx + transpose(du_dx) + dot(du_dx, transpose(du_dx)));
      double J = det(F);
      double coef = (C1 / pow(J, 5.0 / 3.0));
      double a1 = ddot(invFT, ddu_dx);
      double a2 = ddot(F, ddu_dx);

      return (2.0 * D1 * J * a1 - (4.0 / 3.0) * coef * a2) * I -
             ((10.0 / 3.0) * coef * a1) * devB +
             (2 * coef) * (dot(ddu_dx, transpose(F)) + dot(F, transpose(ddu_dx)));
   }

   // Parameters
   double D1 = 100.0;
   double C1 = 50.0;
};

#endif
<|endoftext|>


<commit_before>/*
 * Copyright 2008-2010 Google Inc.
 *
 * 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 "esnpapi.h"
#include "proxyImpl.h"

#include <any.h>
#include <reflect.h>
#include <org/w3c/dom.h>

using namespace org::w3c::dom;

void initializeHtmlMetaData()
{
    registerMetaData(html::ApplicationCache::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::ApplicationCache_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::BarProp::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::BarProp_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::BeforeUnloadEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::BeforeUnloadEvent_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::CanvasGradient::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasGradient_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::CanvasPattern::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasPattern_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::CanvasPixelArray::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasPixelArray_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::CanvasRenderingContext2D::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasRenderingContext2D_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::DataTransfer::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DataTransfer_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::DOMSettableTokenList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DOMSettableTokenList_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::DOMStringMap::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DOMStringMap_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::DOMTokenList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DOMTokenList_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::DragEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DragEvent_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::Function::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Function_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::History::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::History_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::ImageData::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::ImageData_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::Location::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Location_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::MediaError::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MediaError_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::MessageChannel::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MessageChannel_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::MessageEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MessageEvent_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::MessagePort::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MessagePort_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::Navigator::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Navigator_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::PopStateEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::PopStateEvent_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::PropertyNodeList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::PropertyNodeList_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::RadioNodeList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::RadioNodeList_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::Screen::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Screen_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::Selection::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Selection_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::StyleMedia::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::StyleMedia_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::TextMetrics::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::TextMetrics_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::TimeRanges::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::TimeRanges_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::UndoManagerEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::UndoManagerEvent_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::UndoManager::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::UndoManager_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::ValidityState::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::ValidityState_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::Window::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Window_Bridge<Any, invoke> >::createInstance));

    initializeHtmlMetaDataA_G();
    initializeHtmlMetaDataH_N();
    initializeHtmlMetaDataO_U();
    initializeHtmlMetaDataV_Z();

    // In HTML5, HTMLDocument is a mixin of Document, but historically it was a separate interface extended from Document.
    // Existing browsers uses HTMLDocument as a class name, and we need to register 'HTMLDocument' as a valid interface name for Document.
    registerMetaData(Document::getMetaData(),
                     reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, Document_Bridge<Any, invoke> >::createInstance),
                     "HTMLDocument");
}
<commit_msg>(initializeHtmlMetaData) : Regiseter DOMWindow for WebKit.<commit_after>/*
 * Copyright 2008-2010 Google Inc.
 *
 * 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 "esnpapi.h"
#include "proxyImpl.h"

#include <any.h>
#include <reflect.h>
#include <org/w3c/dom.h>

using namespace org::w3c::dom;

void initializeHtmlMetaData()
{
    registerMetaData(html::ApplicationCache::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::ApplicationCache_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::BarProp::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::BarProp_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::BeforeUnloadEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::BeforeUnloadEvent_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::CanvasGradient::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasGradient_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::CanvasPattern::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasPattern_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::CanvasPixelArray::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasPixelArray_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::CanvasRenderingContext2D::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::CanvasRenderingContext2D_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::DataTransfer::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DataTransfer_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::DOMSettableTokenList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DOMSettableTokenList_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::DOMStringMap::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DOMStringMap_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::DOMTokenList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DOMTokenList_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::DragEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::DragEvent_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::Function::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Function_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::History::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::History_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::ImageData::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::ImageData_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::Location::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Location_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::MediaError::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MediaError_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::MessageChannel::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MessageChannel_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::MessageEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MessageEvent_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::MessagePort::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::MessagePort_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::Navigator::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Navigator_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::PopStateEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::PopStateEvent_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::PropertyNodeList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::PropertyNodeList_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::RadioNodeList::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::RadioNodeList_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::Screen::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Screen_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::Selection::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Selection_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::StyleMedia::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::StyleMedia_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::TextMetrics::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::TextMetrics_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::TimeRanges::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::TimeRanges_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::UndoManagerEvent::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::UndoManagerEvent_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::UndoManager::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::UndoManager_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::ValidityState::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::ValidityState_Bridge<Any, invoke> >::createInstance));
    registerMetaData(html::Window::getMetaData(), reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Window_Bridge<Any, invoke> >::createInstance));

    initializeHtmlMetaDataA_G();
    initializeHtmlMetaDataH_N();
    initializeHtmlMetaDataO_U();
    initializeHtmlMetaDataV_Z();

    // In HTML5, HTMLDocument is a mixin of Document, but historically it was a separate interface extended from Document.
    // Existing browsers uses HTMLDocument as a class name, and we need to register 'HTMLDocument' as a valid interface name for Document.
    registerMetaData(Document::getMetaData(),
                     reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, Document_Bridge<Any, invoke> >::createInstance),
                     "HTMLDocument");

    // WebKit uses "DOMWindow" instead of "Window"
    registerMetaData(html::Window::getMetaData(),
                     reinterpret_cast<Object* (*)(ProxyObject)>(Proxy_Impl<ProxyObject, html::Window_Bridge<Any, invoke> >::createInstance),
                     "DOMWindow");
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
using namespace std;

int atoi(char a)
{
    return (int)(a - 48);
}

char itoa(int i)
{
    return (char)(i + 48);
}

string append(string s,string maxs)
{
    string a;
    for(int i = 0;i < maxs.length() - s.length();i++)
        a += "0";
    a += s;
    return a;
}

bool judgeplus(string a,string b,string c,int control)
{
    string sum(a.length(),0);int carry = 0;
    for(int  i = a.length() - 1;i >= 0;i--)
    {
        sum[i] = itoa(atoi(a[i]) + atoi(b[i]) + carry);
        carry = (atoi(a[i]) + atoi(b[i])) / 10;
    }
    switch(control)
    {
        case 1:{if(sum > c) return true;else return false;}
        case 2:{if(sum < c) return true;else return false;}
    }
}

bool judgeminus(string a,string b,string c,int control)
{
    string maxs = (a > b ? a : b);string mins = (a < b ? a : b);
    string diff(a.length(),0);const int borrow = 10;
    for(int i = 0;i < a.length();i++)
        diff[i] = itoa((atoi(maxs[i]) - atoi(mins[i]) + borrow) % 10);
    switch(control)
    {
        case 1:{if(diff > c) return true;else return false;}
        case 2:{if(diff < c) return true;else return false;}
    }
}

int main()
{
    int n;
    cin>>n;
    for(int i = 1;i <= n;i++)
    {
        string a,b,c;bool flag = false;
        cin>>a>>b>>c;
        if(c[0] == '-')
        {
            if(a[0] == '-' && b[0] == '-')
            {
                a = a.substr(1,string::npos);
                b = b.substr(1,string::npos);
                c = c.substr(1,string::npos);
                a = append(a,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                b = append(b,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                c = append(c,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                flag =  judgeplus(a,b,c,2);
            }
            else if(a[0] == '-' && b[0] != '-')
            {
                a = a.substr(1,string::npos);
                c = c.substr(1,string::npos);
                a = append(a,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                b = append(b,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                c = append(c,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                flag = judgeminus(a,b,c,2);
            }
            else if(a[0] != '-' && b[0] == '-')
            {
                b = b.substr(1,string::npos);
                c = c.substr(1,string::npos);
                a = append(a,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                b = append(b,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                c = append(c,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                flag = judgeminus(a,b,c,2);
            }
            else
                flag = true;
        }
        else
        {
            if(a[0] != '-' && b[0] != '-')
            {
                a = append(a,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                b = append(b,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                c = append(c,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                flag =  judgeplus(a,b,c,1);
            }
            else if(a[0] == '-' && b[0] != '-')
            {
                a = a.substr(1,string::npos);
                a = append(a,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                b = append(b,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                c = append(c,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                flag = judgeminus(a,b,c,1);
            }
            else if(a[0] != '-' && b[0] == '-')
            {
                b = b.substr(1,string::npos);
                a = append(a,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                b = append(b,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                c = append(c,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c));
                flag = judgeminus(a,b,c,1);
            }
        }
        if(flag) cout<<"Case #"<<i<<": true"<<endl;
        else cout<<"Case #"<<i<<": false"<<endl;
    }
}
<commit_msg>Clean up.<commit_after>#include <iostream>
#include <string>
using namespace std;

void append(string& s,int&& length)
{
    int limit = length - s.size();
    for(int i = 0;i < limit;i++) s.push_back('0');
}

bool judgeplus(string& a,string& b,string& c,int control)
{
    auto atoi = [](char a)-> int {return (a - 48);};
    auto itoa = [](int i)-> char {return (i + 48);};
    string sum(a.length(),0);int carry = 0;
    for(int  i = a.length() - 1;i >= 0;i--)
    {
        sum[i] = itoa(atoi(a[i]) + atoi(b[i]) + carry);
        carry = (atoi(a[i]) + atoi(b[i])) / 10;
    }
    switch(control)
    {
        case 1:{if(sum > c) return true;else return false;}
        case 2:{if(sum < c) return true;else return false;}
    }
}

bool judgeminus(string& a,string& b,string& c,int control)
{
    auto atoi = [](char a)-> int {return (a - 48);};
    auto itoa = [](int i)-> char {return (i + 48);};
    string maxs = (a > b ? a : b);string mins = (a < b ? a : b);
    string diff(a.length(),0);const int borrow = 10;
    for(int i = 0;i < a.length();i++)
        diff[i] = itoa((atoi(maxs[i]) - atoi(mins[i]) + borrow) % 10);
    switch(control)
    {
        case 1:{if(diff > c) return true;else return false;}
        case 2:{if(diff < c) return true;else return false;}
    }
}

int main()
{
    int n;
    cin>>n;
    for(int i = 1;i <= n;i++)
    {
        string a,b,c;bool flag = false;
        cin>>a>>b>>c;
        if(c.front() == '-')
        {
            if(a.front() == '-' && b.front() == '-')
            {
                a.erase(0,1);b.erase(0,1);c.erase(0,1);
                append(a,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                append(b,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                append(c,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                flag =  judgeplus(a,b,c,2);
            }
            else if(a.front() == '-' && b.front() != '-')
            {
                a.erase(0,1);c.erase(0,1);
                append(a,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                append(b,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                append(c,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                flag = judgeminus(a,b,c,2);
            }
            else if(a.front() != '-' && b.front() == '-')
            {
                b.erase(0,1);c.erase(0,1);
                append(a,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                append(b,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                append(c,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                flag = judgeminus(a,b,c,2);
            }
            else flag = true;
        }
        else
        {
            if(a.front() != '-' && b.front() != '-')
            {
                append(a,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                append(b,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                append(c,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                flag =  judgeplus(a,b,c,1);
            }
            else if(a.front() == '-' && b.front() != '-')
            {
                a.erase(0,1);
                append(a,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                append(b,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                append(c,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                flag = judgeminus(a,b,c,1);
            }
            else if(a.front() != '-' && b.front() == '-')
            {
                b.erase(0,1);
                append(a,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                append(b,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                append(c,((a.length() >= b.length() ? a : b).length() >= c.length() ? (a.length() >= b.length() ? a : b) : c).size());
                flag = judgeminus(a,b,c,1);
            }
        }
        cout<<"Case #"<<i<<": "<<boolalpha<<flag<<endl;
    }
}
<|endoftext|>


<commit_before>#include "nxtStringPropertyConverter.h"

using namespace qReal::robots::generators;
using namespace converters;
using namespace parts;

NxtStringPropertyConverter::NxtStringPropertyConverter(Variables const &variables
		, parts::Subprograms &subprograms)
	: mVariables(variables)
{
	QString const formatStringCode =
			"char *formatString(char *format, ...)\n"\
			"{\n"\
			"	char buffer[256];\n"\
			"	va_list args;\n"\
			"	va_start(args, format);\n"\
			"	vsnprintf(buffer, 256, format, args);\n"\
			"	va_end(args);\n"\
			"	return buffer;\n"\
			"}";
	subprograms.appendManualSubprogram("formatString", formatStringCode);
}

QString NxtStringPropertyConverter::convert(QString const &data) const
{
	QString const preparedString = StringPropertyConverter::convert(data);
	QStringList metVariables;
	QString const formatString = TextExpressionProcessorBase::processExpression(preparedString, metVariables);
	QString const formatVariables =  metVariables.join(", ");
	return QString("formatString(%1, %2)").arg(formatString, formatVariables);
}

bool NxtStringPropertyConverter::variableExists(QString const &variable) const
{
	return mVariables.expressionType(variable) != enums::variableType::unknown;
}

QString NxtStringPropertyConverter::value(QString const &variable) const
{
	return mVariables.expressionType(variable) == enums::variableType::intType ? "%d" : "%.4f";
}
<commit_msg>Made it working for floats<commit_after>#include "nxtStringPropertyConverter.h"

using namespace qReal::robots::generators;
using namespace converters;
using namespace parts;

NxtStringPropertyConverter::NxtStringPropertyConverter(Variables const &variables
		, parts::Subprograms &subprograms)
	: mVariables(variables)
{
	QString const formatStringCode =
			"char *formatString(char *format, ...)\n"\
			"{\n"\
			"	char buffer[256];\n"\
			"	va_list args;\n"\
			"	va_start(args, format);\n"\
			"	vsnprintf(buffer, 256, format, args);\n"\
			"	va_end(args);\n"\
			"	return buffer;\n"\
			"}";
	subprograms.appendManualSubprogram("formatString", formatStringCode);
}

QString NxtStringPropertyConverter::convert(QString const &data) const
{
	QString const preparedString = StringPropertyConverter::convert(data);
	QStringList metVariables;
	QString const formatString = TextExpressionProcessorBase::processExpression(preparedString, metVariables);

	// Nxt OSEK does not support floating point numbers printing, so hello hacks
	// (we print each float variable like two int ones separated with '.')
	QStringList hackedVariables;
	foreach (QString const &variable, metVariables) {
		if (mVariables.expressionType(variable) == enums::variableType::intType) {
			hackedVariables << variable;
		} else {
			hackedVariables << "(int)" + variable
					<< QString("((int)((%1 - (int)%1) * 1000))").arg(variable);
		}
	}
	QString const formatVariables = hackedVariables.join(", ");
	return QString("formatString(%1, %2)").arg(formatString, formatVariables);
}

bool NxtStringPropertyConverter::variableExists(QString const &variable) const
{
	return mVariables.expressionType(variable) != enums::variableType::unknown;
}

QString NxtStringPropertyConverter::value(QString const &variable) const
{
	return mVariables.expressionType(variable) == enums::variableType::intType ? "%d" : "%d.%d";
}
<|endoftext|>


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

#include <iterator>
#include <algorithm>
// ospray
#include "api/Device.h"
#include "DistributedModel.h"
#include "mpiCommon/MPICommon.h"
#include "Messaging.h"
#include "common/Data.h"
// ispc exports
#include "DistributedModel_ispc.h"

namespace ospray {
  namespace mpi {

    extern "C" void *ospray_getEmbreeDevice()
    {
      return api::Device::current->embreeDevice;
    }

    DistributedModel::DistributedModel()
    {
      managedObjectType = OSP_MODEL;
      this->ispcEquivalent = ispc::DistributedModel_create(this);
    }

    std::string DistributedModel::toString() const
    {
      return "ospray::mpi::DistributedModel";
    }

    void DistributedModel::commit()
    {
      // TODO: We may need to override the ISPC calls made
      // to the Model or customize the model struct on the ISPC
      // side. In which case we need some ISPC side inheritence
      // for the model type. Currently the code is actually identical.
      Model::commit();
      // Send my bounding boxes to other nodes, recieve theirs for a
      // "full picture" of what geometries live on what nodes
      Data *regionData = getParamData("regions");

      // The box3f data is sent as data of FLOAT3 items
      // TODO: It's a little awkward to copy the boxes again like this, maybe
      // can re-thinkg the send side of the bcast call? One that takes
      // a ptr and a size since we know we won't be writing out to it?
      // TODO: For now it doesn't matter that we don't know who owns the
      // other boxes, just that we know they exist and their bounds, and that
      // they aren't ours.
      if (regionData) {
        box3f *boxes = reinterpret_cast<box3f*>(regionData->data);
        myRegions = std::vector<box3f>(boxes, boxes + regionData->numItems / 2);
      }

      // If the user hasn't set any regions, there's an implicit infinitely
      // large region box we can place around the entire world.
      if (myRegions.empty()) {
        postStatusMsg("No regions found, making implicit "
                      "infinitely large region");
        myRegions.push_back(box3f(vec3f(neg_inf), vec3f(pos_inf)));
      }

      for (size_t i = 0; i < mpicommon::numGlobalRanks(); ++i) {
        if (i == mpicommon::globalRank()) {
          messaging::bcast(i, myRegions);
        } else {
          std::vector<box3f> recv;
          messaging::bcast(i, recv);
          std::copy(recv.begin(), recv.end(),
                    std::back_inserter(othersRegions));
        }
      }

      if (logLevel() >= 1) {
        const bool asyncWasRunning = messaging::asyncMessagingEnabled();
        messaging::disableAsyncMessaging();

        // TODO: WILL: Just for making the debug log more readable,
        // this will NOT stick around
        for (size_t i = 0; i < mpicommon::numGlobalRanks(); ++i) {
          if (i == mpicommon::globalRank()) {
            postStatusMsg(1) << "Rank " << mpicommon::globalRank()
              << ": Got regions from others {";
            for (const auto &b : othersRegions) {
              postStatusMsg(1) << "\t" << b << ",";
            }
            postStatusMsg(1) << "}";
          }

          mpicommon::world.barrier();
        }

        if (asyncWasRunning) {
          postStatusMsg("Async was running, re-enabling", 1);
          messaging::enableAsyncMessaging();
        }
      }
    }

  } // ::ospray::mpi
} // ::ospray
<commit_msg>Post the infinite region log msg at appropriate log level<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include <iterator>
#include <algorithm>
// ospray
#include "api/Device.h"
#include "DistributedModel.h"
#include "mpiCommon/MPICommon.h"
#include "Messaging.h"
#include "common/Data.h"
// ispc exports
#include "DistributedModel_ispc.h"

namespace ospray {
  namespace mpi {

    extern "C" void *ospray_getEmbreeDevice()
    {
      return api::Device::current->embreeDevice;
    }

    DistributedModel::DistributedModel()
    {
      managedObjectType = OSP_MODEL;
      this->ispcEquivalent = ispc::DistributedModel_create(this);
    }

    std::string DistributedModel::toString() const
    {
      return "ospray::mpi::DistributedModel";
    }

    void DistributedModel::commit()
    {
      // TODO: We may need to override the ISPC calls made
      // to the Model or customize the model struct on the ISPC
      // side. In which case we need some ISPC side inheritence
      // for the model type. Currently the code is actually identical.
      Model::commit();
      // Send my bounding boxes to other nodes, recieve theirs for a
      // "full picture" of what geometries live on what nodes
      Data *regionData = getParamData("regions");

      // The box3f data is sent as data of FLOAT3 items
      // TODO: It's a little awkward to copy the boxes again like this, maybe
      // can re-thinkg the send side of the bcast call? One that takes
      // a ptr and a size since we know we won't be writing out to it?
      // TODO: For now it doesn't matter that we don't know who owns the
      // other boxes, just that we know they exist and their bounds, and that
      // they aren't ours.
      if (regionData) {
        box3f *boxes = reinterpret_cast<box3f*>(regionData->data);
        myRegions = std::vector<box3f>(boxes, boxes + regionData->numItems / 2);
      }

      // If the user hasn't set any regions, there's an implicit infinitely
      // large region box we can place around the entire world.
      if (myRegions.empty()) {
        postStatusMsg("No regions found, making implicit "
                      "infinitely large region", 1);
        myRegions.push_back(box3f(vec3f(neg_inf), vec3f(pos_inf)));
      }

      for (size_t i = 0; i < mpicommon::numGlobalRanks(); ++i) {
        if (i == mpicommon::globalRank()) {
          messaging::bcast(i, myRegions);
        } else {
          std::vector<box3f> recv;
          messaging::bcast(i, recv);
          std::copy(recv.begin(), recv.end(),
                    std::back_inserter(othersRegions));
        }
      }

      if (logLevel() >= 1) {
        const bool asyncWasRunning = messaging::asyncMessagingEnabled();
        messaging::disableAsyncMessaging();

        // TODO: WILL: Just for making the debug log more readable,
        // this will NOT stick around
        for (size_t i = 0; i < mpicommon::numGlobalRanks(); ++i) {
          if (i == mpicommon::globalRank()) {
            postStatusMsg(1) << "Rank " << mpicommon::globalRank()
              << ": Got regions from others {";
            for (const auto &b : othersRegions) {
              postStatusMsg(1) << "\t" << b << ",";
            }
            postStatusMsg(1) << "}";
          }

          mpicommon::world.barrier();
        }

        if (asyncWasRunning) {
          postStatusMsg("Async was running, re-enabling", 1);
          messaging::enableAsyncMessaging();
        }
      }
    }

  } // ::ospray::mpi
} // ::ospray
<|endoftext|>


<commit_before>
// Copyright (c) 2012, 2013 Pierre MOULON

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "CppUnitLite/TestHarness.h"
#include "testing/testing.h"

#include "openMVG/tracks/tracks.hpp"
#include "openMVG/matching/indMatch.hpp"
using namespace openMVG::tracks;
using namespace openMVG::matching;

#include <vector>
#include <utility>

TEST(Tracks, Simple) {

  // Create some tracks for image (A,B,C)
  // {A,B,C} imageId will be {0,1,2}
  // For those image link some features id depicted below
  //A    B    C
  //0 -> 0 -> 0
  //1 -> 1 -> 6
  //2 -> 3

  // Create the input pairwise correspondences
  PairWiseMatches map_pairwisematches;

  const IndMatch testAB[] = {IndMatch(0,0), IndMatch(1,1), IndMatch(2,3)};
  const IndMatch testBC[] = {IndMatch(0,0), IndMatch(1,6)};

  const std::vector<IndMatch> ab(testAB, testAB+3);
  const std::vector<IndMatch> bc(testBC, testBC+2);
  const int A = 0;
  const int B = 1;
  const int C = 2;
  map_pairwisematches[ std::make_pair(A,B) ] = ab;
  map_pairwisematches[ std::make_pair(B,C) ] = bc;

  //-- Build tracks using the interface tracksbuilder
  TracksBuilder trackBuilder;
  trackBuilder.Build( map_pairwisematches );

  trackBuilder.ExportToStream(std::cout);

  STLMAPTracks map_tracks;
  trackBuilder.ExportToSTL(map_tracks);

  //-------------------
  // Unit Test check
  //-------------------

  //0, {(0,0) (1,0) (2,0)}
  //1, {(0,1) (1,1) (2,6)}
  //2, {(0,2) (1,3)}
  const std::pair<std::size_t,std::size_t> GT_Tracks[] =
  {
    std::make_pair(0,0), std::make_pair(1,0), std::make_pair(2,0),
    std::make_pair(0,1), std::make_pair(1,1), std::make_pair(2,6),
    std::make_pair(0,2), std::make_pair(1,3)
  };

  CHECK_EQUAL(3,  map_tracks.size());
  std::size_t cpt = 0, i = 0;
  for (STLMAPTracks::const_iterator iterT = map_tracks.begin();
    iterT != map_tracks.end();
    ++iterT, ++i)
  {
    CHECK_EQUAL(i, iterT->first);
    for (submapTrack::const_iterator iter = iterT->second.begin();
      iter != iterT->second.end();
      ++iter)
    {
      CHECK( GT_Tracks[cpt] == std::make_pair(iter->first, iter->second));
      ++cpt;
    }
  }
}

TEST(Tracks, filter_3viewAtLeast) {

  //
  //A    B    C
  //0 -> 0 -> 0
  //1 -> 1 -> 6
  //2 -> 3
  //

  // Create the input pairwise correspondences
  PairWiseMatches map_pairwisematches;

  IndMatch testAB[] = {IndMatch(0,0), IndMatch(1,1), IndMatch(2,3)};
  IndMatch testBC[] = {IndMatch(0,0), IndMatch(1,6)};

  std::vector<IndMatch> ab(testAB, testAB+3);
  std::vector<IndMatch> bc(testBC, testBC+2);
  const int A = 0;
  const int B = 1;
  const int C = 2;
  map_pairwisematches[ std::make_pair(A,B) ] = ab;
  map_pairwisematches[ std::make_pair(B,C) ] = bc;

  //-- Build tracks using the interface tracksbuilder
  TracksBuilder trackBuilder;
  trackBuilder.Build( map_pairwisematches );
  CHECK_EQUAL(3, trackBuilder.NbTracks());
  trackBuilder.Filter(3);
  CHECK_EQUAL(2, trackBuilder.NbTracks());
}

TEST(Tracks, Conflict) {

  //
  //A    B    C
  //0 -> 0 -> 0
  //1 -> 1 -> 6
  //{2 -> 3 -> 2
  //      3 -> 8 } This track must be deleted, index 3 appears two times
  //

  // Create the input pairwise correspondences
  PairWiseMatches map_pairwisematches;

  const IndMatch testAB[] = {IndMatch(0,0), IndMatch(1,1), IndMatch(2,3)};
  const IndMatch testBC[] = {IndMatch(0,0), IndMatch(1,6), IndMatch(3,2), IndMatch(3,8)};

  std::vector<IndMatch> ab(testAB, testAB+3);
  std::vector<IndMatch> bc(testBC, testBC+4);
  const int A = 0;
  const int B = 1;
  const int C = 2;
  map_pairwisematches[ std::make_pair(A,B) ] = ab;
  map_pairwisematches[ std::make_pair(B,C) ] = bc;

  //-- Build tracks using the interface tracksbuilder
  TracksBuilder trackBuilder;
  trackBuilder.Build( map_pairwisematches );

  CHECK_EQUAL(3, trackBuilder.NbTracks());
  trackBuilder.Filter(); // Key feature tested here to kill the conflicted track
  CHECK_EQUAL(2, trackBuilder.NbTracks());

  STLMAPTracks map_tracks;
  trackBuilder.ExportToSTL(map_tracks);

  //-------------------
  // Unit Test check
  //-------------------

  //0, {(0,0) (1,0) (2,0)}
  //1, {(0,1) (1,1) (2,6)}
  const std::pair<std::size_t,std::size_t> GT_Tracks[] =
    {std::make_pair(0,0), std::make_pair(1,0), std::make_pair(2,0),
     std::make_pair(0,1), std::make_pair(1,1), std::make_pair(2,6)};

  CHECK_EQUAL(2,  map_tracks.size());
  std::size_t cpt = 0, i = 0;
  for (STLMAPTracks::const_iterator iterT = map_tracks.begin();
    iterT != map_tracks.end();
    ++iterT, ++i)
  {
    CHECK_EQUAL(i, iterT->first);
    for (submapTrack::const_iterator iter = iterT->second.begin();
      iter != iterT->second.end();
      ++iter)
    {
      CHECK( GT_Tracks[cpt] == std::make_pair(iter->first, iter->second));
      ++cpt;
    }
  }
}

TEST(Tracks, GetCommonTracksInImages)
{
  {
    std::set<std::size_t> set_imageIndex {15, 20};
    TracksPerView map_tracksPerView;

    std::vector<std::size_t> base{1,2,3,4};
    map_tracksPerView[10] = base;
    map_tracksPerView[15] = base;
    map_tracksPerView[20] = base;
    map_tracksPerView[40] = base;
    map_tracksPerView[15].push_back(5);
    map_tracksPerView[20].push_back(6);

    std::set<std::size_t> set_visibleTracks;
    TracksUtilsMap::GetCommonTracksInImages(set_imageIndex, map_tracksPerView, set_visibleTracks);
    CHECK_EQUAL(base.size(), set_visibleTracks.size());
  }
  {
    std::set<std::size_t> set_imageIndex {15, 20, 10, 40};
    TracksPerView map_tracksPerView;

    std::vector<std::size_t> base{1,2,3,4};
    map_tracksPerView[10] = base;
    map_tracksPerView[15] = base;
    map_tracksPerView[20] = base;
    map_tracksPerView[40] = base;

    map_tracksPerView[10].push_back(100);
    map_tracksPerView[15].push_back(100);
    map_tracksPerView[20].push_back(100);

    map_tracksPerView[15].push_back(200);
    map_tracksPerView[20].push_back(200);
    map_tracksPerView[40].push_back(200);

    map_tracksPerView[15].push_back(5);
    map_tracksPerView[20].push_back(6);

    std::set<std::size_t> set_visibleTracks;
    TracksUtilsMap::GetCommonTracksInImages(set_imageIndex, map_tracksPerView, set_visibleTracks);
    CHECK_EQUAL(base.size(), set_visibleTracks.size());
  }
}

/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */
<commit_msg>[tracks] added a test to check common tracks with a view without visible tracks<commit_after>
// Copyright (c) 2012, 2013 Pierre MOULON

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include "CppUnitLite/TestHarness.h"
#include "testing/testing.h"

#include "openMVG/tracks/tracks.hpp"
#include "openMVG/matching/indMatch.hpp"
using namespace openMVG::tracks;
using namespace openMVG::matching;

#include <vector>
#include <utility>

TEST(Tracks, Simple) {

  // Create some tracks for image (A,B,C)
  // {A,B,C} imageId will be {0,1,2}
  // For those image link some features id depicted below
  //A    B    C
  //0 -> 0 -> 0
  //1 -> 1 -> 6
  //2 -> 3

  // Create the input pairwise correspondences
  PairWiseMatches map_pairwisematches;

  const IndMatch testAB[] = {IndMatch(0,0), IndMatch(1,1), IndMatch(2,3)};
  const IndMatch testBC[] = {IndMatch(0,0), IndMatch(1,6)};

  const std::vector<IndMatch> ab(testAB, testAB+3);
  const std::vector<IndMatch> bc(testBC, testBC+2);
  const int A = 0;
  const int B = 1;
  const int C = 2;
  map_pairwisematches[ std::make_pair(A,B) ] = ab;
  map_pairwisematches[ std::make_pair(B,C) ] = bc;

  //-- Build tracks using the interface tracksbuilder
  TracksBuilder trackBuilder;
  trackBuilder.Build( map_pairwisematches );

  trackBuilder.ExportToStream(std::cout);

  STLMAPTracks map_tracks;
  trackBuilder.ExportToSTL(map_tracks);

  //-------------------
  // Unit Test check
  //-------------------

  //0, {(0,0) (1,0) (2,0)}
  //1, {(0,1) (1,1) (2,6)}
  //2, {(0,2) (1,3)}
  const std::pair<std::size_t,std::size_t> GT_Tracks[] =
  {
    std::make_pair(0,0), std::make_pair(1,0), std::make_pair(2,0),
    std::make_pair(0,1), std::make_pair(1,1), std::make_pair(2,6),
    std::make_pair(0,2), std::make_pair(1,3)
  };

  CHECK_EQUAL(3,  map_tracks.size());
  std::size_t cpt = 0, i = 0;
  for (STLMAPTracks::const_iterator iterT = map_tracks.begin();
    iterT != map_tracks.end();
    ++iterT, ++i)
  {
    CHECK_EQUAL(i, iterT->first);
    for (submapTrack::const_iterator iter = iterT->second.begin();
      iter != iterT->second.end();
      ++iter)
    {
      CHECK( GT_Tracks[cpt] == std::make_pair(iter->first, iter->second));
      ++cpt;
    }
  }
}

TEST(Tracks, filter_3viewAtLeast) {

  //
  //A    B    C
  //0 -> 0 -> 0
  //1 -> 1 -> 6
  //2 -> 3
  //

  // Create the input pairwise correspondences
  PairWiseMatches map_pairwisematches;

  IndMatch testAB[] = {IndMatch(0,0), IndMatch(1,1), IndMatch(2,3)};
  IndMatch testBC[] = {IndMatch(0,0), IndMatch(1,6)};

  std::vector<IndMatch> ab(testAB, testAB+3);
  std::vector<IndMatch> bc(testBC, testBC+2);
  const int A = 0;
  const int B = 1;
  const int C = 2;
  map_pairwisematches[ std::make_pair(A,B) ] = ab;
  map_pairwisematches[ std::make_pair(B,C) ] = bc;

  //-- Build tracks using the interface tracksbuilder
  TracksBuilder trackBuilder;
  trackBuilder.Build( map_pairwisematches );
  CHECK_EQUAL(3, trackBuilder.NbTracks());
  trackBuilder.Filter(3);
  CHECK_EQUAL(2, trackBuilder.NbTracks());
}

TEST(Tracks, Conflict) {

  //
  //A    B    C
  //0 -> 0 -> 0
  //1 -> 1 -> 6
  //{2 -> 3 -> 2
  //      3 -> 8 } This track must be deleted, index 3 appears two times
  //

  // Create the input pairwise correspondences
  PairWiseMatches map_pairwisematches;

  const IndMatch testAB[] = {IndMatch(0,0), IndMatch(1,1), IndMatch(2,3)};
  const IndMatch testBC[] = {IndMatch(0,0), IndMatch(1,6), IndMatch(3,2), IndMatch(3,8)};

  std::vector<IndMatch> ab(testAB, testAB+3);
  std::vector<IndMatch> bc(testBC, testBC+4);
  const int A = 0;
  const int B = 1;
  const int C = 2;
  map_pairwisematches[ std::make_pair(A,B) ] = ab;
  map_pairwisematches[ std::make_pair(B,C) ] = bc;

  //-- Build tracks using the interface tracksbuilder
  TracksBuilder trackBuilder;
  trackBuilder.Build( map_pairwisematches );

  CHECK_EQUAL(3, trackBuilder.NbTracks());
  trackBuilder.Filter(); // Key feature tested here to kill the conflicted track
  CHECK_EQUAL(2, trackBuilder.NbTracks());

  STLMAPTracks map_tracks;
  trackBuilder.ExportToSTL(map_tracks);

  //-------------------
  // Unit Test check
  //-------------------

  //0, {(0,0) (1,0) (2,0)}
  //1, {(0,1) (1,1) (2,6)}
  const std::pair<std::size_t,std::size_t> GT_Tracks[] =
    {std::make_pair(0,0), std::make_pair(1,0), std::make_pair(2,0),
     std::make_pair(0,1), std::make_pair(1,1), std::make_pair(2,6)};

  CHECK_EQUAL(2,  map_tracks.size());
  std::size_t cpt = 0, i = 0;
  for (STLMAPTracks::const_iterator iterT = map_tracks.begin();
    iterT != map_tracks.end();
    ++iterT, ++i)
  {
    CHECK_EQUAL(i, iterT->first);
    for (submapTrack::const_iterator iter = iterT->second.begin();
      iter != iterT->second.end();
      ++iter)
    {
      CHECK( GT_Tracks[cpt] == std::make_pair(iter->first, iter->second));
      ++cpt;
    }
  }
}

TEST(Tracks, GetCommonTracksInImages)
{
  {
    std::set<std::size_t> set_imageIndex {15, 20};
    TracksPerView map_tracksPerView;

    std::vector<std::size_t> base{1,2,3,4};
    map_tracksPerView[10] = base;
    map_tracksPerView[15] = base;
    map_tracksPerView[20] = base;
    map_tracksPerView[40] = base;
    map_tracksPerView[15].push_back(5);
    map_tracksPerView[20].push_back(6);

    std::set<std::size_t> set_visibleTracks;
    TracksUtilsMap::GetCommonTracksInImages(set_imageIndex, map_tracksPerView, set_visibleTracks);
    CHECK_EQUAL(base.size(), set_visibleTracks.size());
    set_visibleTracks.clear();
    // test non-existing view index
    TracksUtilsMap::GetCommonTracksInImages({15, 50}, map_tracksPerView, set_visibleTracks);
    CHECK(set_visibleTracks.empty());
  }
  {
    std::set<std::size_t> set_imageIndex {15, 20, 10, 40};
    TracksPerView map_tracksPerView;

    std::vector<std::size_t> base{1,2,3,4};
    map_tracksPerView[10] = base;
    map_tracksPerView[15] = base;
    map_tracksPerView[20] = base;
    map_tracksPerView[40] = base;

    map_tracksPerView[10].push_back(100);
    map_tracksPerView[15].push_back(100);
    map_tracksPerView[20].push_back(100);

    map_tracksPerView[15].push_back(200);
    map_tracksPerView[20].push_back(200);
    map_tracksPerView[40].push_back(200);

    map_tracksPerView[15].push_back(5);
    map_tracksPerView[20].push_back(6);

    std::set<std::size_t> set_visibleTracks;
    TracksUtilsMap::GetCommonTracksInImages(set_imageIndex, map_tracksPerView, set_visibleTracks);
    CHECK_EQUAL(base.size(), set_visibleTracks.size());
  }
}

/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr);}
/* ************************************************************************* */
<|endoftext|>


<commit_before>/*
 * AccumulateLayer.cpp
 *
 *  Created on: Nov 18, 2013
 *      Author: pschultz
 */

#include "AccumulateLayer.hpp"

namespace PV {

AccumulateLayer::AccumulateLayer(const char * name, HyPerCol * hc, int numChannels) {
   initialize_base();
   initialize(name, hc, numChannels);
}

AccumulateLayer::AccumulateLayer() {
   initialize_base();
}

int AccumulateLayer::initialize_base() {
   syncedInputLayerName = NULL;
   syncedInputLayer = NULL;
   return PV_SUCCESS;
}

int AccumulateLayer::initialize(const char * name, HyPerCol * hc, int numChannels) {
   return ANNLayer::initialize(name, hc, numChannels);
}

int AccumulateLayer::setParams(PVParams * inputParams) {
   int status = ANNLayer::setParams(inputParams);
   readSyncedInputLayer(inputParams);
   return status;
}

void AccumulateLayer::readSyncedInputLayer(PVParams * params) {
   const char * synced_input_layer_name = params->stringValue(name, "syncedInputLayer");
   if (synced_input_layer_name != NULL) {
      syncedInputLayerName = strdup(synced_input_layer_name);
      if (syncedInputLayerName == NULL) {
         fprintf(stderr, "%s \"%s\": unable to allocate memory for syncedInputLayer: %s\n", params->groupKeywordFromName(name), name, strerror(errno));
         exit(EXIT_FAILURE);
      }
   }
}

int AccumulateLayer::communicateInitInfo() {
   if (syncedInputLayerName != NULL) {
      syncedInputLayer = parent->getLayerFromName(syncedInputLayerName);
      if (syncedInputLayer == NULL) {
         fprintf(stderr, "%s \"%s\": syncedInputLayer \"%s\" is not a layer in the column.\n", parent->parameters()->groupKeywordFromName(name), name, syncedInputLayerName);
         exit(EXIT_FAILURE);
      }
   }
   return PV_SUCCESS;
}

int AccumulateLayer::doUpdateState(double time, double dt, const PVLayerLoc * loc, pvdata_t * A,
      pvdata_t * V, int num_channels, pvdata_t * gSynHead, bool spiking,
      unsigned int * active_indices, unsigned int * num_active)
{
   bool needsUpdate = false;
   if (syncedInputLayer != NULL) {
      if (getPhase() > syncedInputLayer->getPhase()) {
         needsUpdate = syncedInputLayer->getLastUpdateTime() >= lastUpdateTime;
      }
      else {
         needsUpdate = syncedInputLayer->getLastUpdateTime() > lastUpdateTime;
      }
   }
   if (needsUpdate) {
      memset(clayer->activity->data, 0, sizeof(pvdata_t)*getNumExtended());
   }
   update_timer->start();
#ifdef PV_USE_OPENCL
   if(gpuAccelerateFlag) {
      updateStateOpenCL(time, dt);
      //HyPerLayer::updateState(time, dt);
   }
   else {
#endif
      int nx = loc->nx;
      int ny = loc->ny;
      int nf = loc->nf;
      int num_neurons = nx*ny*nf;
      updateV_AccumulateLayer(num_neurons, V, num_channels, gSynHead, A,
              VMax, VMin, VThresh, VShift, VWidth, nx, ny, nf, loc->nb);
      if (this->writeSparseActivity){
         updateActiveIndices();  // added by GTK to allow for sparse output, can this be made an inline function???
      }
#ifdef PV_USE_OPENCL
   }
#endif

   update_timer->stop();
   return PV_SUCCESS;
}

int AccumulateLayer::setActivity() {
   const PVLayerLoc * loc = getLayerLoc();
   int nx = loc->nx;
   int ny = loc->ny;
   int nf = loc->nf;
   int nb = loc->nb;
   int num_neurons = nx*ny*nf;
   int status;
   memset(clayer->activity->data, 0, sizeof(pvdata_t)*getNumExtended());
   if( status == PV_SUCCESS ) status = applyVThresh_ANNLayer(num_neurons, getV(), VMin, VThresh, VShift, VWidth, getCLayer()->activity->data, nx, ny, nf, nb);
   if( status == PV_SUCCESS ) status = applyVMax_ANNLayer(num_neurons, getV(), VMax, getCLayer()->activity->data, nx, ny, nf, nb);
   return status;
}

AccumulateLayer::~AccumulateLayer() {
}

} /* namespace PV */
<commit_msg>Eliminate uninitialized-variable warning<commit_after>/*
 * AccumulateLayer.cpp
 *
 *  Created on: Nov 18, 2013
 *      Author: pschultz
 */

#include "AccumulateLayer.hpp"

namespace PV {

AccumulateLayer::AccumulateLayer(const char * name, HyPerCol * hc, int numChannels) {
   initialize_base();
   initialize(name, hc, numChannels);
}

AccumulateLayer::AccumulateLayer() {
   initialize_base();
}

int AccumulateLayer::initialize_base() {
   syncedInputLayerName = NULL;
   syncedInputLayer = NULL;
   return PV_SUCCESS;
}

int AccumulateLayer::initialize(const char * name, HyPerCol * hc, int numChannels) {
   return ANNLayer::initialize(name, hc, numChannels);
}

int AccumulateLayer::setParams(PVParams * inputParams) {
   int status = ANNLayer::setParams(inputParams);
   readSyncedInputLayer(inputParams);
   return status;
}

void AccumulateLayer::readSyncedInputLayer(PVParams * params) {
   const char * synced_input_layer_name = params->stringValue(name, "syncedInputLayer");
   if (synced_input_layer_name != NULL) {
      syncedInputLayerName = strdup(synced_input_layer_name);
      if (syncedInputLayerName == NULL) {
         fprintf(stderr, "%s \"%s\": unable to allocate memory for syncedInputLayer: %s\n", params->groupKeywordFromName(name), name, strerror(errno));
         exit(EXIT_FAILURE);
      }
   }
}

int AccumulateLayer::communicateInitInfo() {
   if (syncedInputLayerName != NULL) {
      syncedInputLayer = parent->getLayerFromName(syncedInputLayerName);
      if (syncedInputLayer == NULL) {
         fprintf(stderr, "%s \"%s\": syncedInputLayer \"%s\" is not a layer in the column.\n", parent->parameters()->groupKeywordFromName(name), name, syncedInputLayerName);
         exit(EXIT_FAILURE);
      }
   }
   return PV_SUCCESS;
}

int AccumulateLayer::doUpdateState(double time, double dt, const PVLayerLoc * loc, pvdata_t * A,
      pvdata_t * V, int num_channels, pvdata_t * gSynHead, bool spiking,
      unsigned int * active_indices, unsigned int * num_active)
{
   bool needsUpdate = false;
   if (syncedInputLayer != NULL) {
      if (getPhase() > syncedInputLayer->getPhase()) {
         needsUpdate = syncedInputLayer->getLastUpdateTime() >= lastUpdateTime;
      }
      else {
         needsUpdate = syncedInputLayer->getLastUpdateTime() > lastUpdateTime;
      }
   }
   if (needsUpdate) {
      memset(clayer->activity->data, 0, sizeof(pvdata_t)*getNumExtended());
   }
   update_timer->start();
#ifdef PV_USE_OPENCL
   if(gpuAccelerateFlag) {
      updateStateOpenCL(time, dt);
      //HyPerLayer::updateState(time, dt);
   }
   else {
#endif
      int nx = loc->nx;
      int ny = loc->ny;
      int nf = loc->nf;
      int num_neurons = nx*ny*nf;
      updateV_AccumulateLayer(num_neurons, V, num_channels, gSynHead, A,
              VMax, VMin, VThresh, VShift, VWidth, nx, ny, nf, loc->nb);
      if (this->writeSparseActivity){
         updateActiveIndices();  // added by GTK to allow for sparse output, can this be made an inline function???
      }
#ifdef PV_USE_OPENCL
   }
#endif

   update_timer->stop();
   return PV_SUCCESS;
}

int AccumulateLayer::setActivity() {
   const PVLayerLoc * loc = getLayerLoc();
   int nx = loc->nx;
   int ny = loc->ny;
   int nf = loc->nf;
   int nb = loc->nb;
   int num_neurons = nx*ny*nf;
   int status = PV_SUCCESS;
   memset(clayer->activity->data, 0, sizeof(pvdata_t)*getNumExtended());
   if( status == PV_SUCCESS ) status = applyVThresh_ANNLayer(num_neurons, getV(), VMin, VThresh, VShift, VWidth, getCLayer()->activity->data, nx, ny, nf, nb);
   if( status == PV_SUCCESS ) status = applyVMax_ANNLayer(num_neurons, getV(), VMax, getCLayer()->activity->data, nx, ny, nf, nb);
   return status;
}

AccumulateLayer::~AccumulateLayer() {
}

} /* namespace PV */
<|endoftext|>


<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 "native_client/src/shared/ppapi_proxy/browser_ppp_input_event.h"

#include "native_client/src/include/nacl_scoped_ptr.h"
#include "native_client/src/include/portability.h"
#include "native_client/src/shared/ppapi_proxy/browser_globals.h"
#include "native_client/src/shared/ppapi_proxy/input_event_data.h"
#include "native_client/src/shared/ppapi_proxy/object_serialize.h"
#include "native_client/src/shared/ppapi_proxy/browser_ppp.h"
#include "native_client/src/shared/ppapi_proxy/trusted/srpcgen/ppp_rpc.h"
#include "native_client/src/shared/ppapi_proxy/utility.h"
#include "ppapi/c/pp_resource.h"
#include "ppapi/c/ppp_input_event.h"

namespace ppapi_proxy {

namespace {

PP_Bool HandleInputEvent(PP_Instance instance, PP_Resource input_event) {
  DebugPrintf("PPP_InputEvent::HandleInputEvent: instance=%"NACL_PRIu32", "
              "input_event = %"NACL_PRIu32"\n",
              instance, input_event);

  PP_Var character_text = PP_MakeUndefined();
  InputEventData data;
  data.event_type = PPBInputEventInterface()->GetType(input_event);
  data.event_time_stamp = PPBInputEventInterface()->GetTimeStamp(input_event);
  data.event_modifiers = PPBInputEventInterface()->GetModifiers(input_event);

  switch (data.event_type) {
    // These events all use the PPB_MouseInputEvent interface.
    case PP_INPUTEVENT_TYPE_MOUSEDOWN:
    case PP_INPUTEVENT_TYPE_MOUSEUP:
    case PP_INPUTEVENT_TYPE_MOUSEENTER:
    case PP_INPUTEVENT_TYPE_MOUSELEAVE:
    case PP_INPUTEVENT_TYPE_MOUSEMOVE:
    case PP_INPUTEVENT_TYPE_CONTEXTMENU:
      data.mouse_button =
          PPBMouseInputEventInterface()->GetButton(input_event);
      data.mouse_position =
          PPBMouseInputEventInterface()->GetPosition(input_event);
      data.mouse_click_count =
          PPBMouseInputEventInterface()->GetClickCount(input_event);
      data.mouse_movement =
          PPBMouseInputEventInterface()->GetMovement(input_event);
      break;
    // This event uses the PPB_WheelInputEvent interface.
    case PP_INPUTEVENT_TYPE_WHEEL:
      data.wheel_delta =
          PPBWheelInputEventInterface()->GetDelta(input_event);
      data.wheel_ticks =
          PPBWheelInputEventInterface()->GetTicks(input_event);
      data.wheel_scroll_by_page =
          PPBWheelInputEventInterface()->GetScrollByPage(input_event);
      break;
    // These events all use the PPB_KeyInputEvent interface.
    case PP_INPUTEVENT_TYPE_RAWKEYDOWN:
    case PP_INPUTEVENT_TYPE_KEYDOWN:
    case PP_INPUTEVENT_TYPE_KEYUP:
    case PP_INPUTEVENT_TYPE_CHAR:
      data.key_code =
          PPBKeyboardInputEventInterface()->GetKeyCode(input_event);
      character_text =
          PPBKeyboardInputEventInterface()->GetCharacterText(input_event);
      break;
    case PP_INPUTEVENT_TYPE_UNDEFINED:
      return PP_FALSE;
    // No default case; if any new types are added we should get a compile
    // warning.
  }
  // Now data and character_text have all the data we want to send to the
  // untrusted side.

  // character_text should either be undefined or a string type.
  DCHECK((character_text.type == PP_VARTYPE_UNDEFINED) ||
         (character_text.type == PP_VARTYPE_STRING));
  // Serialize the character_text Var.
  uint32_t text_size = kMaxVarSize;
  nacl::scoped_array<char> text_bytes(Serialize(&character_text, 1,
                                                &text_size));
  int32_t handled;
  NaClSrpcError srpc_result =
      PppInputEventRpcClient::PPP_InputEvent_HandleInputEvent(
          GetMainSrpcChannel(instance),
          instance,
          input_event,
          sizeof(data),
          reinterpret_cast<char*>(&data),
          text_size,
          text_bytes.get(),
          &handled);
  DebugPrintf("PPP_Instance::HandleInputEvent: %s\n",
              NaClSrpcErrorString(srpc_result));
  if (srpc_result != NACL_SRPC_RESULT_OK) {
    return PP_FALSE;
  }
  // The 'handled' int should only ever have a value matching one of PP_FALSE
  // or PP_TRUE. Otherwise, there's an error in the proxy.
  DCHECK((handled == static_cast<int32_t>(PP_FALSE) ||
         (handled == static_cast<int32_t>(PP_TRUE))));
  PP_Bool handled_bool = static_cast<PP_Bool>(handled);
  return handled_bool;
}

}  // namespace

const PPP_InputEvent* BrowserInputEvent::GetInterface() {
  static const PPP_InputEvent input_event_interface = {
    HandleInputEvent
  };
  return &input_event_interface;
}

}  // namespace ppapi_proxy
<commit_msg>Add new input event enums for deps roll BUG= none TEST= existing test suites Review URL: http://codereview.chromium.org/7925019<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 "native_client/src/shared/ppapi_proxy/browser_ppp_input_event.h"

#include "native_client/src/include/nacl_scoped_ptr.h"
#include "native_client/src/include/portability.h"
#include "native_client/src/shared/ppapi_proxy/browser_globals.h"
#include "native_client/src/shared/ppapi_proxy/input_event_data.h"
#include "native_client/src/shared/ppapi_proxy/object_serialize.h"
#include "native_client/src/shared/ppapi_proxy/browser_ppp.h"
#include "native_client/src/shared/ppapi_proxy/trusted/srpcgen/ppp_rpc.h"
#include "native_client/src/shared/ppapi_proxy/utility.h"
#include "ppapi/c/pp_resource.h"
#include "ppapi/c/ppp_input_event.h"

namespace ppapi_proxy {

namespace {

PP_Bool HandleInputEvent(PP_Instance instance, PP_Resource input_event) {
  DebugPrintf("PPP_InputEvent::HandleInputEvent: instance=%"NACL_PRIu32", "
              "input_event = %"NACL_PRIu32"\n",
              instance, input_event);

  PP_Var character_text = PP_MakeUndefined();
  InputEventData data;
  data.event_type = PPBInputEventInterface()->GetType(input_event);
  data.event_time_stamp = PPBInputEventInterface()->GetTimeStamp(input_event);
  data.event_modifiers = PPBInputEventInterface()->GetModifiers(input_event);

  switch (data.event_type) {
    // These events all use the PPB_MouseInputEvent interface.
    case PP_INPUTEVENT_TYPE_MOUSEDOWN:
    case PP_INPUTEVENT_TYPE_MOUSEUP:
    case PP_INPUTEVENT_TYPE_MOUSEENTER:
    case PP_INPUTEVENT_TYPE_MOUSELEAVE:
    case PP_INPUTEVENT_TYPE_MOUSEMOVE:
    case PP_INPUTEVENT_TYPE_CONTEXTMENU:
      data.mouse_button =
          PPBMouseInputEventInterface()->GetButton(input_event);
      data.mouse_position =
          PPBMouseInputEventInterface()->GetPosition(input_event);
      data.mouse_click_count =
          PPBMouseInputEventInterface()->GetClickCount(input_event);
      data.mouse_movement =
          PPBMouseInputEventInterface()->GetMovement(input_event);
      break;
    // This event uses the PPB_WheelInputEvent interface.
    case PP_INPUTEVENT_TYPE_WHEEL:
      data.wheel_delta =
          PPBWheelInputEventInterface()->GetDelta(input_event);
      data.wheel_ticks =
          PPBWheelInputEventInterface()->GetTicks(input_event);
      data.wheel_scroll_by_page =
          PPBWheelInputEventInterface()->GetScrollByPage(input_event);
      break;
    // These events all use the PPB_KeyInputEvent interface.
    case PP_INPUTEVENT_TYPE_RAWKEYDOWN:
    case PP_INPUTEVENT_TYPE_KEYDOWN:
    case PP_INPUTEVENT_TYPE_KEYUP:
    case PP_INPUTEVENT_TYPE_CHAR:
      data.key_code =
          PPBKeyboardInputEventInterface()->GetKeyCode(input_event);
      character_text =
          PPBKeyboardInputEventInterface()->GetCharacterText(input_event);
      break;
    case PP_INPUTEVENT_TYPE_UNDEFINED:
      return PP_FALSE;
    // TODO(nfullagar): Implement support for event types below.
    case PP_INPUTEVENT_TYPE_COMPOSITION_START:
    case PP_INPUTEVENT_TYPE_COMPOSITION_UPDATE:
    case PP_INPUTEVENT_TYPE_COMPOSITION_END:
    case PP_INPUTEVENT_TYPE_IME_TEXT:
      DebugPrintf("   No implementation for event type %d\n",
          data.event_type);
      return PP_FALSE;
    // No default case; if any new types are added we should get a compile
    // warning.
  }
  // Now data and character_text have all the data we want to send to the
  // untrusted side.

  // character_text should either be undefined or a string type.
  DCHECK((character_text.type == PP_VARTYPE_UNDEFINED) ||
         (character_text.type == PP_VARTYPE_STRING));
  // Serialize the character_text Var.
  uint32_t text_size = kMaxVarSize;
  nacl::scoped_array<char> text_bytes(Serialize(&character_text, 1,
                                                &text_size));
  int32_t handled;
  NaClSrpcError srpc_result =
      PppInputEventRpcClient::PPP_InputEvent_HandleInputEvent(
          GetMainSrpcChannel(instance),
          instance,
          input_event,
          sizeof(data),
          reinterpret_cast<char*>(&data),
          text_size,
          text_bytes.get(),
          &handled);
  DebugPrintf("PPP_Instance::HandleInputEvent: %s\n",
              NaClSrpcErrorString(srpc_result));
  if (srpc_result != NACL_SRPC_RESULT_OK) {
    return PP_FALSE;
  }
  // The 'handled' int should only ever have a value matching one of PP_FALSE
  // or PP_TRUE. Otherwise, there's an error in the proxy.
  DCHECK((handled == static_cast<int32_t>(PP_FALSE) ||
         (handled == static_cast<int32_t>(PP_TRUE))));
  PP_Bool handled_bool = static_cast<PP_Bool>(handled);
  return handled_bool;
}

}  // namespace

const PPP_InputEvent* BrowserInputEvent::GetInterface() {
  static const PPP_InputEvent input_event_interface = {
    HandleInputEvent
  };
  return &input_event_interface;
}

}  // namespace ppapi_proxy
<|endoftext|>