<commit_before>/*  This file is part of the Vc library. {{{

    Copyright (C) 2012 Matthias Kretz <kretz@kde.org>

    Vc is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Vc is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with Vc.  If not, see <http://www.gnu.org/licenses/>.

}}}*/

#ifndef VC_SCALAR_INTERLEAVEDMEMORY_TCC
#define VC_SCALAR_INTERLEAVEDMEMORY_TCC

namespace Vc
{
namespace Common
{

template<> inline void InterleavedMemoryAccessBase<float_v>::deinterleave(float_v &v0, float_v &v1) const
{
    v0.data() = m_data[m_indexes.data() + 0];
    v1.data() = m_data[m_indexes.data() + 1];
}

template<> inline void InterleavedMemoryAccessBase<float_v>::deinterleave(float_v &v0, float_v &v1, float_v &v2) const
{
    v0.data() = m_data[m_indexes.data() + 0];
    v1.data() = m_data[m_indexes.data() + 1];
    v2.data() = m_data[m_indexes.data() + 2];
}

template<> inline void InterleavedMemoryAccessBase<float_v>::deinterleave(float_v &v0, float_v &v1, float_v &v2, float_v &v3) const
{
    v0.data() = m_data[m_indexes.data() + 0];
    v1.data() = m_data[m_indexes.data() + 1];
    v2.data() = m_data[m_indexes.data() + 2];
    v3.data() = m_data[m_indexes.data() + 3];
}

template<> inline void InterleavedMemoryAccessBase<float_v>::deinterleave(float_v &v0, float_v &v1, float_v &v2, float_v &v3, float_v &v4) const
{
    v0.data() = m_data[m_indexes.data() + 0];
    v1.data() = m_data[m_indexes.data() + 1];
    v2.data() = m_data[m_indexes.data() + 2];
    v3.data() = m_data[m_indexes.data() + 3];
    v4.data() = m_data[m_indexes.data() + 4];
}

template<> inline void InterleavedMemoryAccessBase<float_v>::deinterleave(float_v &v0, float_v &v1, float_v &v2, float_v &v3, float_v &v4, float_v &v5) const
{
    v0.data() = m_data[m_indexes.data() + 0];
    v1.data() = m_data[m_indexes.data() + 1];
    v2.data() = m_data[m_indexes.data() + 2];
    v3.data() = m_data[m_indexes.data() + 3];
    v4.data() = m_data[m_indexes.data() + 4];
    v5.data() = m_data[m_indexes.data() + 5];
}

template<> inline void InterleavedMemoryAccessBase<float_v>::deinterleave(float_v &v0, float_v &v1, float_v &v2, float_v &v3, float_v &v4, float_v &v5, float_v &v6) const
{
    v0.data() = m_data[m_indexes.data() + 0];
    v1.data() = m_data[m_indexes.data() + 1];
    v2.data() = m_data[m_indexes.data() + 2];
    v3.data() = m_data[m_indexes.data() + 3];
    v4.data() = m_data[m_indexes.data() + 4];
    v5.data() = m_data[m_indexes.data() + 5];
    v6.data() = m_data[m_indexes.data() + 6];
}

template<> inline void InterleavedMemoryAccessBase<float_v>::deinterleave(float_v &v0, float_v &v1, float_v &v2, float_v &v3, float_v &v4, float_v &v5, float_v &v6, float_v &v7) const
{
    v0.data() = m_data[m_indexes.data() + 0];
    v1.data() = m_data[m_indexes.data() + 1];
    v2.data() = m_data[m_indexes.data() + 2];
    v3.data() = m_data[m_indexes.data() + 3];
    v4.data() = m_data[m_indexes.data() + 4];
    v5.data() = m_data[m_indexes.data() + 5];
    v6.data() = m_data[m_indexes.data() + 6];
    v7.data() = m_data[m_indexes.data() + 7];
}

} // namespace Common
} // namespace Vc

#endif // VC_SCALAR_INTERLEAVEDMEMORY_TCC
<commit_msg>implement Scalar InterleavedMemoryAccess for all types generically<commit_after>/*  This file is part of the Vc library. {{{

    Copyright (C) 2012 Matthias Kretz <kretz@kde.org>

    Vc is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Vc is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with Vc.  If not, see <http://www.gnu.org/licenses/>.

}}}*/

#ifndef VC_SCALAR_INTERLEAVEDMEMORY_TCC
#define VC_SCALAR_INTERLEAVEDMEMORY_TCC

namespace Vc
{
namespace Common
{

template<typename V> inline void InterleavedMemoryAccessBase<V>::deinterleave(V &v0, V &v1) const/*{{{*/
{
    v0.data() = m_data[m_indexes.data() + 0];
    v1.data() = m_data[m_indexes.data() + 1];
}/*}}}*/
template<typename V> inline void InterleavedMemoryAccessBase<V>::deinterleave(V &v0, V &v1, V &v2) const/*{{{*/
{
    v0.data() = m_data[m_indexes.data() + 0];
    v1.data() = m_data[m_indexes.data() + 1];
    v2.data() = m_data[m_indexes.data() + 2];
}/*}}}*/
template<typename V> inline void InterleavedMemoryAccessBase<V>::deinterleave(V &v0, V &v1, V &v2, V &v3) const/*{{{*/
{
    v0.data() = m_data[m_indexes.data() + 0];
    v1.data() = m_data[m_indexes.data() + 1];
    v2.data() = m_data[m_indexes.data() + 2];
    v3.data() = m_data[m_indexes.data() + 3];
}/*}}}*/
template<typename V> inline void InterleavedMemoryAccessBase<V>::deinterleave(V &v0, V &v1, V &v2, V &v3, V &v4) const/*{{{*/
{
    v0.data() = m_data[m_indexes.data() + 0];
    v1.data() = m_data[m_indexes.data() + 1];
    v2.data() = m_data[m_indexes.data() + 2];
    v3.data() = m_data[m_indexes.data() + 3];
    v4.data() = m_data[m_indexes.data() + 4];
}/*}}}*/
template<typename V> inline void InterleavedMemoryAccessBase<V>::deinterleave(V &v0, V &v1, V &v2, V &v3, V &v4, V &v5) const/*{{{*/
{
    v0.data() = m_data[m_indexes.data() + 0];
    v1.data() = m_data[m_indexes.data() + 1];
    v2.data() = m_data[m_indexes.data() + 2];
    v3.data() = m_data[m_indexes.data() + 3];
    v4.data() = m_data[m_indexes.data() + 4];
    v5.data() = m_data[m_indexes.data() + 5];
}/*}}}*/
template<typename V> inline void InterleavedMemoryAccessBase<V>::deinterleave(V &v0, V &v1, V &v2, V &v3, V &v4, V &v5, V &v6) const/*{{{*/
{
    v0.data() = m_data[m_indexes.data() + 0];
    v1.data() = m_data[m_indexes.data() + 1];
    v2.data() = m_data[m_indexes.data() + 2];
    v3.data() = m_data[m_indexes.data() + 3];
    v4.data() = m_data[m_indexes.data() + 4];
    v5.data() = m_data[m_indexes.data() + 5];
    v6.data() = m_data[m_indexes.data() + 6];
}/*}}}*/
template<typename V> inline void InterleavedMemoryAccessBase<V>::deinterleave(V &v0, V &v1, V &v2, V &v3, V &v4, V &v5, V &v6, V &v7) const/*{{{*/
{
    v0.data() = m_data[m_indexes.data() + 0];
    v1.data() = m_data[m_indexes.data() + 1];
    v2.data() = m_data[m_indexes.data() + 2];
    v3.data() = m_data[m_indexes.data() + 3];
    v4.data() = m_data[m_indexes.data() + 4];
    v5.data() = m_data[m_indexes.data() + 5];
    v6.data() = m_data[m_indexes.data() + 6];
    v7.data() = m_data[m_indexes.data() + 7];
}/*}}}*/

} // namespace Common
} // namespace Vc

#endif // VC_SCALAR_INTERLEAVEDMEMORY_TCC

// vim: foldmethod=marker
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014, 2018 Pavel Kirienko <pavel.kirienko@gmail.com>
 * Kinetis Port Author David Sidrane <david_s5@nscdg.com>
 */

#pragma once

#include <uavcan_kinetis/build_config.hpp>

#if UAVCAN_KINETIS_NUTTX
# include <nuttx/arch.h>
# include "up_arch.h"
# include <arch/board/board.h>
# include <hardware/kinetis_pit.h>
# include <hardware/kinetis_sim.h>
# include <syslog.h>
#else
# error "Unknown OS"
#endif

/**
 * Debug output
 */
#ifndef UAVCAN_KINETIS_LOG
# if 1
#  define UAVCAN_KINETIS_LOG(fmt, ...)  syslog(LOG_INFO, "uavcan_kinetis: " fmt "\n", ## __VA_ARGS__)
# else
#  define UAVCAN_KINETIS_LOG(...)       ((void)0)
# endif
#endif

/**
 * IRQ handler macros
 */
#define UAVCAN_KINETIS_IRQ_HANDLER(id)  int id(int irq, FAR void* context, FAR void *arg)

/**
 * Glue macros
 */
#define UAVCAN_KINETIS_GLUE2_(A, B)       A ## B
#define UAVCAN_KINETIS_GLUE2(A, B)        UAVCAN_KINETIS_GLUE2_(A, B)

#define UAVCAN_KINETIS_GLUE3_(A, B, C)    A ## B ## C
#define UAVCAN_KINETIS_GLUE3(A, B, C)     UAVCAN_KINETIS_GLUE3_(A, B, C)

namespace uavcan_kinetis
{
#if UAVCAN_KINETIS_NUTTX

struct CriticalSectionLocker {
	const irqstate_t flags_;

	CriticalSectionLocker()
		: flags_(enter_critical_section())
	{
	}

	~CriticalSectionLocker()
	{
		leave_critical_section(flags_);
	}
};

#endif

namespace clock
{
uavcan::uint64_t getUtcUSecFromCanInterrupt();
}
}
<commit_msg>kinetis uavcan_drivers Updates for NuttX 9.1.0-<commit_after>/*
 * Copyright (C) 2014, 2018 Pavel Kirienko <pavel.kirienko@gmail.com>
 * Kinetis Port Author David Sidrane <david_s5@nscdg.com>
 */

#pragma once

#include <uavcan_kinetis/build_config.hpp>

#if UAVCAN_KINETIS_NUTTX
# include <nuttx/arch.h>
# include "arm_arch.h"
# include <arch/board/board.h>
# include <hardware/kinetis_pit.h>
# include <hardware/kinetis_sim.h>
# include <syslog.h>
#else
# error "Unknown OS"
#endif

/**
 * Debug output
 */
#ifndef UAVCAN_KINETIS_LOG
# if 1
#  define UAVCAN_KINETIS_LOG(fmt, ...)  syslog(LOG_INFO, "uavcan_kinetis: " fmt "\n", ## __VA_ARGS__)
# else
#  define UAVCAN_KINETIS_LOG(...)       ((void)0)
# endif
#endif

/**
 * IRQ handler macros
 */
#define UAVCAN_KINETIS_IRQ_HANDLER(id)  int id(int irq, FAR void* context, FAR void *arg)

/**
 * Glue macros
 */
#define UAVCAN_KINETIS_GLUE2_(A, B)       A ## B
#define UAVCAN_KINETIS_GLUE2(A, B)        UAVCAN_KINETIS_GLUE2_(A, B)

#define UAVCAN_KINETIS_GLUE3_(A, B, C)    A ## B ## C
#define UAVCAN_KINETIS_GLUE3(A, B, C)     UAVCAN_KINETIS_GLUE3_(A, B, C)

namespace uavcan_kinetis
{
#if UAVCAN_KINETIS_NUTTX

struct CriticalSectionLocker {
	const irqstate_t flags_;

	CriticalSectionLocker()
		: flags_(enter_critical_section())
	{
	}

	~CriticalSectionLocker()
	{
		leave_critical_section(flags_);
	}
};

#endif

namespace clock
{
uavcan::uint64_t getUtcUSecFromCanInterrupt();
}
}
<|endoftext|>


<commit_before>#ifndef MJOLNIR_INPUT_READ_INTEGRATOR_HPP
#define MJOLNIR_INPUT_READ_INTEGRATOR_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/core/VelocityVerletIntegrator.hpp>
#include <mjolnir/core/UnderdampedLangevinIntegrator.hpp>
#include <mjolnir/core/BAOABLangevinIntegrator.hpp>
#include <mjolnir/input/utility.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/util/throw_exception.hpp>

namespace mjolnir
{

template<typename traitsT>
VelocityVerletIntegrator<traitsT>
read_velocity_verlet_integrator(const toml::value& simulator)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_LOG_FUNCTION();
    using real_type = typename traitsT::real_type;

    const real_type delta_t = toml::find<real_type>(simulator, "delta_t");
    MJOLNIR_LOG_INFO("delta_t = ", delta_t);

    return VelocityVerletIntegrator<traitsT>(delta_t);
}

template<typename traitsT>
UnderdampedLangevinIntegrator<traitsT>
read_underdamped_langevin_integrator(const toml::value& simulator)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_LOG_FUNCTION();
    using real_type = typename traitsT::real_type;

    const real_type delta_t = toml::find<real_type>(simulator, "delta_t");
    MJOLNIR_LOG_INFO("delta_t = ", delta_t);

    const auto& integrator = toml::find(simulator, "integrator");

    check_keys_available(integrator, {"type"_s, "seed"_s, "parameters"_s});

    const auto parameters = toml::find<toml::array  >(integrator, "parameters");

    std::vector<real_type> gamma(parameters.size());
    for(const auto& params : parameters)
    {
        const auto idx = toml::find<std::size_t>(params, "index");
        const auto  gm = toml::expect<real_type>(params, u8"γ").or_other(
                         toml::expect<real_type>(params, "gamma")).unwrap();
        if(gamma.size() <= idx){gamma.resize(idx+1);}
        gamma.at(idx) = gm;

        MJOLNIR_LOG_INFO("idx = ", idx, ", gamma = ", gm);
    }
    return UnderdampedLangevinIntegrator<traitsT>(delta_t, std::move(gamma));
}

template<typename traitsT>
BAOABLangevinIntegrator<traitsT>
read_BAOAB_langevin_integrator(const toml::value& simulator)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_LOG_FUNCTION();
    using real_type = typename traitsT::real_type;

    const real_type delta_t = toml::find<real_type>(simulator, "delta_t");
    MJOLNIR_LOG_INFO("delta_t = ", delta_t);

    const auto& integrator = toml::find(simulator, "integrator");

    check_keys_available(integrator, {"type"_s, "seed"_s, "parameters"_s});

    const auto parameters = toml::find<toml::array  >(integrator, "parameters");

    std::vector<real_type> gamma(parameters.size());
    for(const auto& params : parameters)
    {
        const auto idx = toml::find<std::size_t>(params, "index");
        const auto  gm = toml::expect<real_type>(params, u8"γ").or_other(
                         toml::expect<real_type>(params, "gamma")).unwrap();
        if(gamma.size() <= idx) {gamma.resize(idx+1);}
        gamma.at(idx) = gm;

        MJOLNIR_LOG_INFO("idx = ", idx, ", gamma = ", gm);
    }
    return BAOABLangevinIntegrator<traitsT>(delta_t, std::move(gamma));
}

// A mapping object from type information (template parameter) to the actual
// read_xxx_integrator function
template<typename T>
struct read_integrator_impl;

template<typename traitsT>
struct read_integrator_impl<VelocityVerletIntegrator<traitsT>>
{
    static VelocityVerletIntegrator<traitsT> invoke(const toml::value& sim)
    {
        return read_velocity_verlet_integrator<traitsT>(sim);
    }
};

template<typename traitsT>
struct read_integrator_impl<UnderdampedLangevinIntegrator<traitsT>>
{
    static UnderdampedLangevinIntegrator<traitsT> invoke(const toml::value& sim)
    {
        return read_underdamped_langevin_integrator<traitsT>(sim);
    }
};

template<typename traitsT>
struct read_integrator_impl<BAOABLangevinIntegrator<traitsT>>
{
    static BAOABLangevinIntegrator<traitsT> invoke(const toml::value& sim)
    {
        return read_BAOAB_langevin_integrator<traitsT>(sim);
    }
};

template<typename integratorT>
integratorT read_integrator(const toml::value& sim)
{
    if(sim.as_table().count("integrator") == 0)
    {
        throw_exception<std::runtime_error>(toml::format_error("[error] "
            "mjolnir::read_integrator: No integrator defined: ", sim, "here", {
            "expected value is one of the following.",
            "- \"VelocityVerlet\"     : simple and standard Velocity Verlet integrator.",
            "- \"UnderdampedLangevin\": simple Underdamped Langevin Integrator"
                                      " based on the Velocity Verlet",
            "- \"BAOABLangevin\"      : well-known BAOAB Langevin Integrator"
            }));
    }
    return read_integrator_impl<integratorT>::invoke(sim);
}

#ifdef MJOLNIR_SEPARATE_BUILD
extern template VelocityVerletIntegrator<SimulatorTraits<double, UnlimitedBoundary>       > read_velocity_verlet_integrator(const toml::value& simulator);
extern template VelocityVerletIntegrator<SimulatorTraits<float,  UnlimitedBoundary>       > read_velocity_verlet_integrator(const toml::value& simulator);
extern template VelocityVerletIntegrator<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_velocity_verlet_integrator(const toml::value& simulator);
extern template VelocityVerletIntegrator<SimulatorTraits<float,  CuboidalPeriodicBoundary>> read_velocity_verlet_integrator(const toml::value& simulator);

extern template UnderdampedLangevinIntegrator<SimulatorTraits<double, UnlimitedBoundary>       > read_underdamped_langevin_integrator(const toml::value& simulator);
extern template UnderdampedLangevinIntegrator<SimulatorTraits<float,  UnlimitedBoundary>       > read_underdamped_langevin_integrator(const toml::value& simulator);
extern template UnderdampedLangevinIntegrator<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_underdamped_langevin_integrator(const toml::value& simulator);
extern template UnderdampedLangevinIntegrator<SimulatorTraits<float,  CuboidalPeriodicBoundary>> read_underdamped_langevin_integrator(const toml::value& simulator);

extern template BAOABLangevinIntegrator<SimulatorTraits<double, UnlimitedBoundary>       > read_BAOAB_langevin_integrator(const toml::value& simulator);
extern template BAOABLangevinIntegrator<SimulatorTraits<float,  UnlimitedBoundary>       > read_BAOAB_langevin_integrator(const toml::value& simulator);
extern template BAOABLangevinIntegrator<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_BAOAB_langevin_integrator(const toml::value& simulator);
extern template BAOABLangevinIntegrator<SimulatorTraits<float,  CuboidalPeriodicBoundary>> read_BAOAB_langevin_integrator(const toml::value& simulator);
#endif

} // mjolnir
#endif// MJOLNIR_READ_INTEGRATOR
<commit_msg>feat: enable to read system_motion_remover<commit_after>#ifndef MJOLNIR_INPUT_READ_INTEGRATOR_HPP
#define MJOLNIR_INPUT_READ_INTEGRATOR_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/core/VelocityVerletIntegrator.hpp>
#include <mjolnir/core/UnderdampedLangevinIntegrator.hpp>
#include <mjolnir/core/BAOABLangevinIntegrator.hpp>
#include <mjolnir/core/SystemMotionRemover.hpp>
#include <mjolnir/input/utility.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/util/throw_exception.hpp>

namespace mjolnir
{

template<typename traitsT>
SystemMotionRemover<traitsT>
read_system_motion_remover(const toml::value& simulator)
{
    const auto& integrator = toml::find(simulator, "integrator");

    if(!integrator.contains("remove"))
    {
        return SystemMotionRemover<traitsT>(false, false, false);
    }
    const auto& remove = toml::find(integrator.at("remove"));

    const bool translation = toml::find_or(remove, "translation");
    const bool rotation    = toml::find_or(remove, "rotation");
    const bool rescale     = toml::find_or(remove, "rescale");

    return SystemMotionRemover<traitsT>(translation, rotation, rescale);
}

template<typename traitsT>
VelocityVerletIntegrator<traitsT>
read_velocity_verlet_integrator(const toml::value& simulator)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_LOG_FUNCTION();
    using real_type = typename traitsT::real_type;

    const real_type delta_t = toml::find<real_type>(simulator, "delta_t");
    MJOLNIR_LOG_INFO("delta_t = ", delta_t);

    return VelocityVerletIntegrator<traitsT>(delta_t,
            read_system_motion_remover<traitsT>(simulator));
}

template<typename traitsT>
UnderdampedLangevinIntegrator<traitsT>
read_underdamped_langevin_integrator(const toml::value& simulator)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_LOG_FUNCTION();
    using real_type = typename traitsT::real_type;

    const real_type delta_t = toml::find<real_type>(simulator, "delta_t");
    MJOLNIR_LOG_INFO("delta_t = ", delta_t);

    const auto& integrator = toml::find(simulator, "integrator");

    check_keys_available(integrator, {"type"_s, "seed"_s, "parameters"_s});

    const auto parameters = toml::find<toml::array  >(integrator, "parameters");

    std::vector<real_type> gamma(parameters.size());
    for(const auto& params : parameters)
    {
        const auto idx = toml::find<std::size_t>(params, "index");
        const auto  gm = toml::expect<real_type>(params, u8"γ").or_other(
                         toml::expect<real_type>(params, "gamma")).unwrap();
        if(gamma.size() <= idx){gamma.resize(idx+1);}
        gamma.at(idx) = gm;

        MJOLNIR_LOG_INFO("idx = ", idx, ", gamma = ", gm);
    }
    return UnderdampedLangevinIntegrator<traitsT>(delta_t, std::move(gamma),
            read_system_motion_remover<traitsT>(simulator));
}

template<typename traitsT>
BAOABLangevinIntegrator<traitsT>
read_BAOAB_langevin_integrator(const toml::value& simulator)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_LOG_FUNCTION();
    using real_type = typename traitsT::real_type;

    const real_type delta_t = toml::find<real_type>(simulator, "delta_t");
    MJOLNIR_LOG_INFO("delta_t = ", delta_t);

    const auto& integrator = toml::find(simulator, "integrator");

    check_keys_available(integrator, {"type"_s, "seed"_s, "parameters"_s});

    const auto parameters = toml::find<toml::array  >(integrator, "parameters");

    std::vector<real_type> gamma(parameters.size());
    for(const auto& params : parameters)
    {
        const auto idx = toml::find<std::size_t>(params, "index");
        const auto  gm = toml::expect<real_type>(params, u8"γ").or_other(
                         toml::expect<real_type>(params, "gamma")).unwrap();
        if(gamma.size() <= idx) {gamma.resize(idx+1);}
        gamma.at(idx) = gm;

        MJOLNIR_LOG_INFO("idx = ", idx, ", gamma = ", gm);
    }
    return BAOABLangevinIntegrator<traitsT>(delta_t, std::move(gamma),
            read_system_motion_remover<traitsT>(simulator));
}

// A mapping object from type information (template parameter) to the actual
// read_xxx_integrator function
template<typename T>
struct read_integrator_impl;

template<typename traitsT>
struct read_integrator_impl<VelocityVerletIntegrator<traitsT>>
{
    static VelocityVerletIntegrator<traitsT> invoke(const toml::value& sim)
    {
        return read_velocity_verlet_integrator<traitsT>(sim);
    }
};

template<typename traitsT>
struct read_integrator_impl<UnderdampedLangevinIntegrator<traitsT>>
{
    static UnderdampedLangevinIntegrator<traitsT> invoke(const toml::value& sim)
    {
        return read_underdamped_langevin_integrator<traitsT>(sim);
    }
};

template<typename traitsT>
struct read_integrator_impl<BAOABLangevinIntegrator<traitsT>>
{
    static BAOABLangevinIntegrator<traitsT> invoke(const toml::value& sim)
    {
        return read_BAOAB_langevin_integrator<traitsT>(sim);
    }
};

template<typename integratorT>
integratorT read_integrator(const toml::value& sim)
{
    if(sim.as_table().count("integrator") == 0)
    {
        throw_exception<std::runtime_error>(toml::format_error("[error] "
            "mjolnir::read_integrator: No integrator defined: ", sim, "here", {
            "expected value is one of the following.",
            "- \"VelocityVerlet\"     : simple and standard Velocity Verlet integrator.",
            "- \"UnderdampedLangevin\": simple Underdamped Langevin Integrator"
                                      " based on the Velocity Verlet",
            "- \"BAOABLangevin\"      : well-known BAOAB Langevin Integrator"
            }));
    }
    return read_integrator_impl<integratorT>::invoke(sim);
}

#ifdef MJOLNIR_SEPARATE_BUILD
extern template VelocityVerletIntegrator<SimulatorTraits<double, UnlimitedBoundary>       > read_velocity_verlet_integrator(const toml::value& simulator);
extern template VelocityVerletIntegrator<SimulatorTraits<float,  UnlimitedBoundary>       > read_velocity_verlet_integrator(const toml::value& simulator);
extern template VelocityVerletIntegrator<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_velocity_verlet_integrator(const toml::value& simulator);
extern template VelocityVerletIntegrator<SimulatorTraits<float,  CuboidalPeriodicBoundary>> read_velocity_verlet_integrator(const toml::value& simulator);

extern template UnderdampedLangevinIntegrator<SimulatorTraits<double, UnlimitedBoundary>       > read_underdamped_langevin_integrator(const toml::value& simulator);
extern template UnderdampedLangevinIntegrator<SimulatorTraits<float,  UnlimitedBoundary>       > read_underdamped_langevin_integrator(const toml::value& simulator);
extern template UnderdampedLangevinIntegrator<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_underdamped_langevin_integrator(const toml::value& simulator);
extern template UnderdampedLangevinIntegrator<SimulatorTraits<float,  CuboidalPeriodicBoundary>> read_underdamped_langevin_integrator(const toml::value& simulator);

extern template BAOABLangevinIntegrator<SimulatorTraits<double, UnlimitedBoundary>       > read_BAOAB_langevin_integrator(const toml::value& simulator);
extern template BAOABLangevinIntegrator<SimulatorTraits<float,  UnlimitedBoundary>       > read_BAOAB_langevin_integrator(const toml::value& simulator);
extern template BAOABLangevinIntegrator<SimulatorTraits<double, CuboidalPeriodicBoundary>> read_BAOAB_langevin_integrator(const toml::value& simulator);
extern template BAOABLangevinIntegrator<SimulatorTraits<float,  CuboidalPeriodicBoundary>> read_BAOAB_langevin_integrator(const toml::value& simulator);
#endif

} // mjolnir
#endif// MJOLNIR_READ_INTEGRATOR
<|endoftext|>


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

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

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

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

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

#include <iostream>

#include "itkSimilarity2DTransform.h"
#include "vnl/vnl_vector_fixed.h"
#include "itkVector.h"

int itkSimilarity2DTransformTest(int ,char *[] )
{

  std::cout << "==================================" << std::endl;
  std::cout << "Testing Similarity 2D Transform" << std::endl << std::endl;

  const double epsilon = 1e-10;
  const unsigned int N = 2;
  bool Ok = true;

  typedef itk::Similarity2DTransform<double>  SimilarityTransformType;
  SimilarityTransformType::Pointer transform = SimilarityTransformType::New();

  // Test the identity transform
  std::cout << "Testing Identity:";
  transform->SetIdentity();

  SimilarityTransformType::InputPointType::ValueType pInit[2] = {10,10};
  SimilarityTransformType::InputPointType p = pInit;
  SimilarityTransformType::OutputPointType r;

  r = transform->TransformPoint( p );
  for(unsigned int i=0; i<N; i++)
  {
     if( fabs( p[i]- r[i] ) > epsilon )
     {
        Ok = false;
        break;
     }
  }
  if( !Ok )
  {
    std::cerr << "Error with Identity transform" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << " [ PASSED ] " << std::endl;
  }

  // Test the Set/Get Parameters
  std::cout << "Testing Set/GetParameters():" << std::endl;
  SimilarityTransformType::ParametersType params(6);

  for(unsigned int i=0;i<6;i++)
    {
    params[i]=i;
    }

  std::cout << "Input Parameters = " << params << std::endl;

  transform->SetParameters(params);
  SimilarityTransformType::ParametersType outputParams(6);

  outputParams = transform->GetParameters();

  std::cout << "Output Parameters = " << outputParams << std::endl;

  for(unsigned int i=0; i<4; i++) // do not test for the offset
  {
     if( fabs( outputParams[i]-params[i] ) > epsilon )
     {
        Ok = false;
        break;
     }
  }
  if( !Ok )
  {
    std::cerr << "Error with Set/GetParameters:" << std::endl;
    std::cerr << "Input:" << params << std::endl;
    std::cerr << "Output:" << outputParams << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << " [ PASSED ] " << std::endl;
  }

  // 15 degrees in radians
  transform->SetIdentity();
  const double angle = 15.0 * atan( 1.0f ) / 45.0;
  const double sinth = sin( angle );
  const double costh = cos( angle );

  std::cout << "Testing Rotation:";
  transform->SetAngle(angle);

  // Rotate an itk::Point
  SimilarityTransformType::InputPointType q;
  p = pInit;
  q[0] =  p[0] * costh - p[1] * sinth;
  q[1] =  p[0] * sinth + p[1] * costh;
  r = transform->TransformPoint( p );
  for(unsigned int i=0; i<N; i++)
  {
     if( fabs( q[i]- r[i] ) > epsilon )
     {
        Ok = false;
        break;
     }
  }
  if( !Ok )
  {
    std::cerr << "Error rotating point   : " << p << std::endl;
    std::cerr << "Result should be       : " << q << std::endl;
    std::cerr << "Reported Result is     : " << r << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << " [ PASSED ] " << std::endl;
  }

  std::cout << "Testing Translation:";

  transform->SetAngle(0);

  SimilarityTransformType::OffsetType::ValueType ioffsetInit[2] = {1,4};
  SimilarityTransformType::OffsetType ioffset = ioffsetInit;

  transform->SetOffset( ioffset );

  q = p + ioffset;

  r = transform->TransformPoint( p );
  for(unsigned int i=0; i<N; i++)
  {
    if( fabs( q[i]- r[i] ) > epsilon )
    {
      Ok = false;
      break;
    }
  }
  if( !Ok )
    {
    std::cerr << "Error translating point: " << p << std::endl;
    std::cerr << "Result should be       : " << q << std::endl;
    std::cerr << "Reported Result is     : " << r << std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout << " [ PASSED ] " << std::endl;
    }

  // Testing the Jacobian
  std::cout << "Testing Jacobian:";
  SimilarityTransformType::JacobianType jacobian =  transform->GetJacobian(p);

  if(
    (jacobian[0][0] != 10) || (jacobian[0][1] != -10) || (jacobian[0][2] != 0) || (jacobian[0][3] != 0)
    || (jacobian[0][4] != 1) || (jacobian[0][5] != 0) || (jacobian[1][0] != 10) || (jacobian[1][1] != 10)
    || (jacobian[1][2] !=0 ) || (jacobian[1][3] != 0) || (jacobian[1][4] !=0) || (jacobian[1][5] != 1)
    )
    {
    std::cerr << "Error with Jacobian: " << jacobian << std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout << " [ PASSED ] " << std::endl;
    }

  return EXIT_SUCCESS;

}
<commit_msg>FIX: Division by zero<commit_after>/*=========================================================================

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

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

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

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

#include <iostream>

#include "itkSimilarity2DTransform.h"
#include "vnl/vnl_vector_fixed.h"
#include "itkVector.h"

int itkSimilarity2DTransformTest(int ,char *[] )
{

  std::cout << "==================================" << std::endl;
  std::cout << "Testing Similarity 2D Transform" << std::endl << std::endl;

  const double epsilon = 1e-10;
  const unsigned int N = 2;
  bool Ok = true;

  typedef itk::Similarity2DTransform<double>  SimilarityTransformType;
  SimilarityTransformType::Pointer transform = SimilarityTransformType::New();

  // Test the identity transform
  std::cout << "Testing Identity:";
  transform->SetIdentity();

  SimilarityTransformType::InputPointType::ValueType pInit[2] = {10,10};
  SimilarityTransformType::InputPointType p = pInit;
  SimilarityTransformType::OutputPointType r;

  r = transform->TransformPoint( p );
  for(unsigned int i=0; i<N; i++)
  {
     if( fabs( p[i]- r[i] ) > epsilon )
     {
        Ok = false;
        break;
     }
  }
  if( !Ok )
  {
    std::cerr << "Error with Identity transform" << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << " [ PASSED ] " << std::endl;
  }

  // Test the Set/Get Parameters
  std::cout << "Testing Set/GetParameters():" << std::endl;
  SimilarityTransformType::ParametersType params(6);

  for(unsigned int i=0;i<6;i++)
    {
    params[i]=i+1;
    }

  std::cout << "Input Parameters = " << params << std::endl;

  transform->SetParameters(params);
  SimilarityTransformType::ParametersType outputParams(6);

  outputParams = transform->GetParameters();

  std::cout << "Output Parameters = " << outputParams << std::endl;

  for(unsigned int i=0; i<4; i++) // do not test for the offset
  {
     if( fabs( outputParams[i]-params[i] ) > epsilon )
     {
        Ok = false;
        break;
     }
  }
  if( !Ok )
  {
    std::cerr << "Error with Set/GetParameters:" << std::endl;
    std::cerr << "Input:" << params << std::endl;
    std::cerr << "Output:" << outputParams << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << " [ PASSED ] " << std::endl;
  }

  // 15 degrees in radians
  transform->SetIdentity();
  const double angle = 15.0 * atan( 1.0f ) / 45.0;
  const double sinth = sin( angle );
  const double costh = cos( angle );

  std::cout << "Testing Rotation:";
  transform->SetAngle(angle);

  // Rotate an itk::Point
  SimilarityTransformType::InputPointType q;
  p = pInit;
  q[0] =  p[0] * costh - p[1] * sinth;
  q[1] =  p[0] * sinth + p[1] * costh;
  r = transform->TransformPoint( p );
  for(unsigned int i=0; i<N; i++)
  {
     if( fabs( q[i]- r[i] ) > epsilon )
     {
        Ok = false;
        break;
     }
  }
  if( !Ok )
  {
    std::cerr << "Error rotating point   : " << p << std::endl;
    std::cerr << "Result should be       : " << q << std::endl;
    std::cerr << "Reported Result is     : " << r << std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout << " [ PASSED ] " << std::endl;
  }

  std::cout << "Testing Translation:";

  transform->SetAngle(0);

  SimilarityTransformType::OffsetType::ValueType ioffsetInit[2] = {1,4};
  SimilarityTransformType::OffsetType ioffset = ioffsetInit;

  transform->SetOffset( ioffset );

  q = p + ioffset;

  r = transform->TransformPoint( p );
  for(unsigned int i=0; i<N; i++)
  {
    if( fabs( q[i]- r[i] ) > epsilon )
    {
      Ok = false;
      break;
    }
  }
  if( !Ok )
    {
    std::cerr << "Error translating point: " << p << std::endl;
    std::cerr << "Result should be       : " << q << std::endl;
    std::cerr << "Reported Result is     : " << r << std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout << " [ PASSED ] " << std::endl;
    }

  // Testing the Jacobian
  std::cout << "Testing Jacobian:";
  SimilarityTransformType::JacobianType jacobian =  transform->GetJacobian(p);

  if(
    (jacobian[0][0] != 10) || (jacobian[0][1] != -10) || (jacobian[0][2] != 0) || (jacobian[0][3] != 0)
    || (jacobian[0][4] != 1) || (jacobian[0][5] != 0) || (jacobian[1][0] != 10) || (jacobian[1][1] != 10)
    || (jacobian[1][2] !=0 ) || (jacobian[1][3] != 0) || (jacobian[1][4] !=0) || (jacobian[1][5] != 1)
    )
    {
    std::cerr << "Error with Jacobian: " << jacobian << std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout << " [ PASSED ] " << std::endl;
    }

  return EXIT_SUCCESS;

}
<|endoftext|>


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

#include "ros_image_texture.h"

#include <tf/tf.h>

#include <OGRE/OgreTextureManager.h>

namespace rviz
{

ROSImageTexture::ROSImageTexture(const ros::NodeHandle& nh)
: nh_(nh)
, new_image_(false)
, width_(0)
, height_(0)
, tf_client_(0)
, image_count_(0)
{
  empty_image_.load("no_image.png", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

  static uint32_t count = 0;
  std::stringstream ss;
  ss << "ROSImageTexture" << count++;
  texture_ = Ogre::TextureManager::getSingleton().loadImage(ss.str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, empty_image_);
}

ROSImageTexture::~ROSImageTexture()
{
}

void ROSImageTexture::clear()
{
  boost::mutex::scoped_lock lock(mutex_);

  texture_->unload();
  texture_->loadImage(empty_image_);

  new_image_ = false;
  current_image_.reset();

  if (tf_filter_)
  {
    tf_filter_->clear();
  }

  image_count_ = 0;
}

void ROSImageTexture::setFrame(const std::string& frame, tf::TransformListener* tf_client)
{
  tf_client_ = tf_client;
  frame_ = frame;
  setTopic(topic_);
}

void ROSImageTexture::setTopic(const std::string& topic)
{
  topic_ = topic;
  tf_filter_.reset();
  sub_.reset(new message_filters::Subscriber<sensor_msgs::Image>());

  if (!topic.empty())
  {
    sub_->subscribe(nh_, topic, 1);

    if (frame_.empty())
    {
      sub_->registerCallback(boost::bind(&ROSImageTexture::callback, this, _1));
    }
    else
    {
      ROS_ASSERT(tf_client_);
      tf_filter_.reset(new tf::MessageFilter<sensor_msgs::Image>(*sub_, (tf::Transformer&)*tf_client_, frame_, 2, nh_));
      tf_filter_->registerCallback(boost::bind(&ROSImageTexture::callback, this, _1));
    }
  }
}

const sensor_msgs::Image::ConstPtr& ROSImageTexture::getImage()
{
  boost::mutex::scoped_lock lock(mutex_);

  return current_image_;
}

bool ROSImageTexture::update()
{
  sensor_msgs::Image::ConstPtr image;
  bool new_image = false;
  {
    boost::mutex::scoped_lock lock(mutex_);

    image = current_image_;
    new_image = new_image_;
  }

  if (!image || !new_image)
  {
    return false;
  }

  new_image_ = false;

  Ogre::PixelFormat format = Ogre::PF_R8G8B8;

  if (image->encoding == sensor_msgs::image_encodings::RGB8)
  {
    format = Ogre::PF_BYTE_RGB;
  }
  else if (image->encoding == sensor_msgs::image_encodings::RGBA8)
  {
    format = Ogre::PF_BYTE_RGBA;
  }
  else if (image->encoding == sensor_msgs::image_encodings::TYPE_8UC4 ||
           //image->encoding == sensor_msgs::image_encodings::TYPE_8SC4 ||
           image->encoding == sensor_msgs::image_encodings::BGRA8)
  {
    format = Ogre::PF_BYTE_BGRA;
  }
  else if (image->encoding == sensor_msgs::image_encodings::TYPE_8UC3 ||
           //image->encoding == sensor_msgs::image_encodings::TYPE_8SC3 ||
           image->encoding == sensor_msgs::image_encodings::BGR8)
  {
    format = Ogre::PF_BYTE_BGR;
  }
  else if (image->encoding == sensor_msgs::image_encodings::TYPE_8UC1 ||
           //image->encoding == sensor_msgs::image_encodings::TYPE_8SC1 ||
           image->encoding == sensor_msgs::image_encodings::MONO8)
  {
    format = Ogre::PF_L8;
  }
  else if (image->encoding == sensor_msgs::image_encodings::TYPE_16UC1 ||
           //image->encoding == sensor_msgs::image_encodings::TYPE_16SC1 ||
           image->encoding == sensor_msgs::image_encodings::MONO16)
  {
    format = Ogre::PF_L16;
  }
  else
  {
    throw UnsupportedImageEncoding(image->encoding);
  }

  width_ = image->width;
  height_ = image->height;

  uint32_t size = image->height * image->step;
  Ogre::DataStreamPtr pixel_stream;
  pixel_stream.bind(new Ogre::MemoryDataStream((void*)(&image->data[0]), size));
  texture_->unload();
  texture_->loadRawData(pixel_stream, width_, height_, format);

  return true;
}

void ROSImageTexture::callback(const sensor_msgs::Image::ConstPtr& msg)
{
  boost::mutex::scoped_lock lock(mutex_);
  current_image_ = msg;
  new_image_ = true;

  ++image_count_;
}

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

#include <climits>

#include "ros_image_texture.h"

#include <tf/tf.h>

#include <OGRE/OgreTextureManager.h>

namespace rviz
{

ROSImageTexture::ROSImageTexture(const ros::NodeHandle& nh)
: nh_(nh)
, new_image_(false)
, width_(0)
, height_(0)
, tf_client_(0)
, image_count_(0)
{
  empty_image_.load("no_image.png", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

  static uint32_t count = 0;
  std::stringstream ss;
  ss << "ROSImageTexture" << count++;
  texture_ = Ogre::TextureManager::getSingleton().loadImage(ss.str(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, empty_image_);
}

ROSImageTexture::~ROSImageTexture()
{
}

void ROSImageTexture::clear()
{
  boost::mutex::scoped_lock lock(mutex_);

  texture_->unload();
  texture_->loadImage(empty_image_);

  new_image_ = false;
  current_image_.reset();

  if (tf_filter_)
  {
    tf_filter_->clear();
  }

  image_count_ = 0;
}

void ROSImageTexture::setFrame(const std::string& frame, tf::TransformListener* tf_client)
{
  tf_client_ = tf_client;
  frame_ = frame;
  setTopic(topic_);
}

void ROSImageTexture::setTopic(const std::string& topic)
{
  topic_ = topic;
  tf_filter_.reset();
  sub_.reset(new message_filters::Subscriber<sensor_msgs::Image>());

  if (!topic.empty())
  {
    sub_->subscribe(nh_, topic, 1);

    if (frame_.empty())
    {
      sub_->registerCallback(boost::bind(&ROSImageTexture::callback, this, _1));
    }
    else
    {
      ROS_ASSERT(tf_client_);
      tf_filter_.reset(new tf::MessageFilter<sensor_msgs::Image>(*sub_, (tf::Transformer&)*tf_client_, frame_, 2, nh_));
      tf_filter_->registerCallback(boost::bind(&ROSImageTexture::callback, this, _1));
    }
  }
}

const sensor_msgs::Image::ConstPtr& ROSImageTexture::getImage()
{
  boost::mutex::scoped_lock lock(mutex_);

  return current_image_;
}

bool ROSImageTexture::update()
{
  sensor_msgs::Image::ConstPtr image;
  bool new_image = false;
  {
    boost::mutex::scoped_lock lock(mutex_);

    image = current_image_;
    new_image = new_image_;
  }

  if (!image || !new_image)
  {
    return false;
  }

  new_image_ = false;

  if (image->data.empty())
  {
    return false;
  }

  Ogre::PixelFormat format = Ogre::PF_R8G8B8;
  Ogre::Image ogre_image;
  std::vector<uint8_t> buffer;
  void* data_ptr = (void*)&image->data[0];
  uint32_t data_size = image->data.size();
  if (image->encoding == sensor_msgs::image_encodings::RGB8)
  {
    format = Ogre::PF_BYTE_RGB;
  }
  else if (image->encoding == sensor_msgs::image_encodings::RGBA8)
  {
    format = Ogre::PF_BYTE_RGBA;
  }
  else if (image->encoding == sensor_msgs::image_encodings::TYPE_8UC4 ||
           image->encoding == sensor_msgs::image_encodings::TYPE_8SC4 ||
           image->encoding == sensor_msgs::image_encodings::BGRA8)
  {
    format = Ogre::PF_BYTE_BGRA;
  }
  else if (image->encoding == sensor_msgs::image_encodings::TYPE_8UC3 ||
           image->encoding == sensor_msgs::image_encodings::TYPE_8SC3 ||
           image->encoding == sensor_msgs::image_encodings::BGR8)
  {
    format = Ogre::PF_BYTE_BGR;
  }
  else if (image->encoding == sensor_msgs::image_encodings::TYPE_8UC1 ||
           image->encoding == sensor_msgs::image_encodings::TYPE_8SC1 ||
           image->encoding == sensor_msgs::image_encodings::MONO8)
  {
    format = Ogre::PF_BYTE_L;
  }
  else if (image->encoding == sensor_msgs::image_encodings::TYPE_16UC1 ||
           image->encoding == sensor_msgs::image_encodings::TYPE_16SC1 ||
           image->encoding == sensor_msgs::image_encodings::MONO16)
  {
    format = Ogre::PF_BYTE_L;

    // downsample manually to 8-bit, because otherwise the lower 8-bits are simply removed
    buffer.resize(image->data.size() / 2);
    data_size = buffer.size();
    data_ptr = (void*)&buffer[0];
    for (size_t i = 0; i < data_size; ++i)
    {
      uint16_t s = image->data[2*i] << 8 | image->data[2*i + 1];
      float val = (float)s / std::numeric_limits<uint16_t>::max();
      buffer[i] = val * 255;
    }
  }
  else
  {
    throw UnsupportedImageEncoding(image->encoding);
  }

  width_ = image->width;
  height_ = image->height;

  // TODO: Support different steps/strides

  Ogre::DataStreamPtr pixel_stream;
  pixel_stream.bind(new Ogre::MemoryDataStream(data_ptr, data_size));

  try
  {
    ogre_image.loadRawData(pixel_stream, width_, height_, format);
  }
  catch (Ogre::Exception& e)
  {
    // TODO: signal error better
    ROS_ERROR("Error loading image: %s", e.what());
    return false;
  }

  texture_->unload();
  texture_->loadImage(ogre_image);

  return true;
}

void ROSImageTexture::callback(const sensor_msgs::Image::ConstPtr& msg)
{
  boost::mutex::scoped_lock lock(mutex_);
  current_image_ = msg;
  new_image_ = true;

  ++image_count_;
}

}
<|endoftext|>


<commit_before>#include "Test.hh"

namespace sieve {

Test::Test() {
    // TODO: Set up usage and validation map here
}

bool Test::validate(const ASTTest *test) {
    if (!_validation_fn_map[test->value()])
        return true;

    return _validation_fn_map[test->value()](test);
}

std::string Test::usage(const ASTTest *test) {
    return "Usage: " + _usage_map[test->value()];
}

}<commit_msg>Start adding some test validation.<commit_after>#include <string>

#include "ASTString.hh"
#include "ASTStringList.hh"
#include "ASTTag.hh"
#include "Test.hh"

namespace sieve {

bool validateBareTest(const ASTNode *node) {
    const ASTTest *test = dynamic_cast<const ASTTest*>(node);
    size_t size = test->children().size();

    if (size == 0)
        return true;
    else
        return false;
}

bool validateExists(const ASTNode *node) {
    const ASTTest *test = dynamic_cast<const ASTTest*>(node);
    size_t size = test->children().size();

    if (size < 1 || size > 3)
        return false;

    const ASTString *stringChild = dynamic_cast<const ASTString*>(test->children()[size - 1]);
    const ASTStringList *stringListChild = dynamic_cast<const ASTStringList*>(test->children()[size - 1]);
    if (stringChild == NULL && stringListChild == NULL)
        return false;

    // If we have more than 1 child, check that they are either :mime or :anychild
    if (size > 1) {
        const ASTTag *firstTag = dynamic_cast<const ASTTag*>(test->children()[0]);
        if (firstTag == NULL)
            return false;

        if (firstTag->value() != ":mime" && firstTag->value() != ":anychild")
            return false;
    }

    if (size > 2) {
        const ASTTag *secondTag = dynamic_cast<const ASTTag*>(test->children()[1]);
        if (secondTag == NULL)
            return false;

        if (secondTag->value() != ":mime" && secondTag->value() != ":anychild")
            return false;
    }

    return true;
}

bool validateHasOnlyTestList(const ASTNode *node) {
    const ASTTest *test = dynamic_cast<const ASTTest*>(node);
    std::vector<sieve::ASTNode *> children = test->children();

    for (std::vector<ASTNode *>::iterator it = children.begin(); it != children.end(); ++it) {
        const ASTTest *child = dynamic_cast<ASTTest*>(*it);

        if (child == NULL)
            return false;
    }

    return true;
}

bool validateNotTest(const ASTNode *node) {
    const ASTTest *test = dynamic_cast<const ASTTest*>(node);
    size_t size = test->children().size();

    if (size != 1)
        return false;

    return true;
}

bool validateSizeTest(const ASTNode *node) {
    const ASTTest *test = dynamic_cast<const ASTTest*>(node);
    size_t size = test->children().size();

    if (size != 2)
        return false;

    const ASTTag *tag = dynamic_cast<const ASTTag*>(test->children()[0]);
    if (tag == NULL || (tag->value() != ":over" && tag->value() != ":under"))
        return false;

    return true;
}

Test::Test() {
    _usage_map["allof"]  = "allof <tests: test-list>";
    _usage_map["anyof"]  = "anyof <tests: test-list>";
    _usage_map["exists"] = "exists [:mime] [:anychild] <header-names: string-list>";
    _usage_map["not"]    = "not <test1: test>";
    _usage_map["size"]   = "size <:over / :under> <limit: number>";

    _validation_fn_map["allof"]  = &validateHasOnlyTestList;
    _validation_fn_map["anyof"]  = &validateHasOnlyTestList;
    _validation_fn_map["exists"] = &validateExists;
    _validation_fn_map["not"]    = &validateNotTest;
    _validation_fn_map["size"]   = &validateSizeTest;
}

bool Test::validate(const ASTTest *test) {
    if (!_validation_fn_map[test->value()])
        return true;

    return _validation_fn_map[test->value()](test);
}

std::string Test::usage(const ASTTest *test) {
    return "Usage: " + _usage_map[test->value()];
}

}<|endoftext|>


<commit_before>/* Learn.cpp
 *
 * Kubo Ryosuke
 */

#ifndef NLEARN

#include "./Learn.h"
#include "core/move/MoveGenerator.h"
#include "core/record/CsaReader.h"
#include "core/util/FileList.h"
#include "core/util/Timer.h"
#include "core/def.h"
#include "logger/Logger.h"
#include <algorithm>
#include <cmath>
#include <ctime>

#define CONF_KIFU               "kifu"
#define CONF_DEPTH              "depth"
#define CONF_THREADS            "threads"

#define CONFPATH                "learn.conf"

#define NUMBER_OF_SIBLING_NODES 8
#define MINI_BATCH_COUNT        20

namespace sunfish {

namespace {

  Board getPvLeaf(const Board& root, const Move& rmove, const Pv& pv) {
    Board board = root;
    board.makeMoveIrr(rmove);
    for (int d = 0; d < pv.size(); d++) {
      Move move = pv.get(d).move;
      if (move.isEmpty() || !board.makeMove(move)) {
        break;
      }
    }
    return board;
  }

  inline float sigmoid(float x) {
    return 1.0f / (1.0f + std::exp(-x));
  }

  inline float gradient(float x) {
    CONSTEXPR float a = 0.025f;
    CONSTEXPR float b = 1.8f;
    float s = sigmoid(a * x);
    return (1.0f - s) * s * b;
  }

  inline float norm(float x) {
    CONSTEXPR float n = 0.01f;
    if (x > 0.0f) {
      return -n;
    } else if (x < 0.0f) {
      return n;
    } else {
      return 0.0f;
    }
  }

}

/**
 * コンストラクタ
 */
Learn::Learn() : _rgen(static_cast<unsigned>(time(NULL))) {
  _config.addDef(CONF_KIFU, "");
  _config.addDef(CONF_DEPTH, "3");
  _config.addDef(CONF_THREADS, "1");
}

/**
 * 特徴抽出を行いパラメータを更新します。
 */
bool Learn::adjust(Board board, Move move0) {
  Value val0;
  Pv pv0;
  Move tmpMove;

  // 合法手生成
  Moves moves;
  MoveGenerator::generate(board, moves);

  if (moves.size() < 2) {
    return true;
  }

  // シャッフル
  std::shuffle(moves.begin(), moves.end(), _rgen);

  // 棋譜の手
  {
    // 探索
    board.makeMove(move0);
    _searcher.idsearch(board, tmpMove);
    board.unmakeMove(move0);

    // PV と評価値
    const auto& info = _searcher.getInfo();
    const auto& pv = info.pv;
    val0 = -info.eval;
    pv0.copy(pv);
  }

  // その他の手
  int nmove = 0;
  float gsum = 0;
  for (auto& move : moves) {
    // 探索
    bool valid = board.makeMove(move);
    if (!valid) { continue; }
    _searcher.idsearch(board, tmpMove);
    board.unmakeMove(move);

    // PV と評価値
    const auto& info = _searcher.getInfo();
    const auto& pv = info.pv;
    Value val = -info.eval;

    // 詰みは除外
    if (val <= -Value::Mate || val >= Value::Mate) {
      continue;
    }

    // leaf 局面
    Board leaf = getPvLeaf(board, move, pv);

    // 特徴抽出
    float g = gradient(val.int32() - val0.int32());
    g = g * (1.0f / MINI_BATCH_COUNT);
    _w.extract<float, true>(leaf, g);
    gsum += g;

    nmove++;
    if (nmove >= NUMBER_OF_SIBLING_NODES) {
      break;
    }
  }

  {
    // leaf 局面
    Board leaf = getPvLeaf(board, move0, pv0);

    // 特徴抽出
    _w.extract<float, true>(leaf, -gsum);
  }

  if (++_miniBatchCount >= MINI_BATCH_COUNT) {
    auto& eval = _searcher.getEvaluator();

    // 値更新
    float max = 0.0f;
    float magnitude = 0.0f;
    for (int i = 0; i < KPP_ALL; i++) {
      _w._t->kpp[0][i] += norm(_w._t->kpp[0][i]);
      eval._t->kpp[0][i] = _w._t->kpp[0][i];
      _u._t->kpp[0][i] += _w._t->kpp[0][i] * _count;
      max = std::max(max, std::abs(_w._t->kpp[0][i]));
      magnitude += std::abs(_w._t->kpp[0][i]);
    }
    for (int i = 0; i < KKP_ALL; i++) {
      _w._t->kkp[0][0][i] += norm(_w._t->kkp[0][0][i]);
      eval._t->kkp[0][0][i] = _w._t->kkp[0][0][i];
      _u._t->kkp[0][0][i] += _w._t->kkp[0][0][i] * _count;
      max = std::max(max, std::abs(_w._t->kkp[0][0][i]));
      magnitude += std::abs(_w._t->kkp[0][0][i]);
    }

    Loggers::message << "max=" << max << " magnitude=" << magnitude;

    _count++;
    _miniBatchCount = 0;
  }

  return true;
}

/**
 * 棋譜ファイルを読み込んで学習します。
 */
bool Learn::readCsa(const char* path) {
  Loggers::message << "load: [" << path << "]";

  Record record;
  if (!CsaReader::read(path, record)) {
    Loggers::warning << "Could not read csa file. [" << path << "]";
    return false;
  }

  // 棋譜の先頭へ
  while (record.unmakeMove())
    ;

  while (true) {
    // 次の1手を取得
    Move move = record.getNextMove();
    if (move.isEmpty()) {
      break;
    }

    bool ok = adjust(record.getBoard(), move);

    if (!ok) {
      return false;
    }

    // 1手進める
    if (!record.makeMove()) {
      break;
    }
  }

  return true;
}

/**
 * 機械学習を実行します。
 */
bool Learn::run() {
  // 設定読み込み
  if (!_config.read(CONFPATH)) {
    return false;
  }
  Loggers::message << _config.toString();

  Timer timer;
  timer.set();

  // 探索設定
  auto searchConfig = _searcher.getConfig();
  searchConfig.maxDepth = _config.getInt(CONF_DEPTH);
  searchConfig.workerSize = _config.getInt(CONF_THREADS);
  searchConfig.treeSize = Searcher::standardTreeSize(searchConfig.workerSize);
  searchConfig.enableLimit = false;
  searchConfig.enableTimeManagement = false;
  searchConfig.ponder = false;
  searchConfig.logging = false;
  _searcher.setConfig(searchConfig);

  // csa ファイルを列挙
  FileList fileList;
  std::string dir = _config.getString(CONF_KIFU);
  fileList.enumerate(dir.c_str(), "csa");

  // 初期化
  _count = 1;
  _miniBatchCount = 0;
  _w.init();
  _u.init();

  for (const auto& filename : fileList) {
    readCsa(filename.c_str());
  }

  // 平均を取る
  auto& eval = _searcher.getEvaluator();
  uint16_t max = 0;
  uint64_t magnitude = 0ull;
  for (int i = 0; i < KPP_ALL; i++) {
    eval._t->kpp[0][i] = _w._t->kpp[0][i] - _u._t->kpp[0][i] / _count;
    max = std::max(max, (uint16_t)std::abs(eval._t->kpp[0][i]));
    magnitude += std::abs(eval._t->kpp[0][i]);
  }
  for (int i = 0; i < KKP_ALL; i++) {
    eval._t->kkp[0][0][i] = _w._t->kkp[0][0][i] - _u._t->kkp[0][0][i] / _count;
    max = std::max(max, (uint16_t)std::abs(eval._t->kkp[0][0][i]));
    magnitude += std::abs(eval._t->kkp[0][0][i]);
  }

  Loggers::message << "max=" << max << " magnitude=" << magnitude;

  // 重みベクトルを保存
  eval.writeFile();

  double elapsed = timer.get();
  Loggers::message << "elapsed: " << elapsed;

  return true;
}

}

#endif // NLEARN
<commit_msg>except mate value<commit_after>/* Learn.cpp
 *
 * Kubo Ryosuke
 */

#ifndef NLEARN

#include "./Learn.h"
#include "core/move/MoveGenerator.h"
#include "core/record/CsaReader.h"
#include "core/util/FileList.h"
#include "core/util/Timer.h"
#include "core/def.h"
#include "logger/Logger.h"
#include <algorithm>
#include <cmath>
#include <ctime>

#define CONF_KIFU               "kifu"
#define CONF_DEPTH              "depth"
#define CONF_THREADS            "threads"

#define CONFPATH                "learn.conf"

#define NUMBER_OF_SIBLING_NODES 8
#define MINI_BATCH_COUNT        20

namespace sunfish {

namespace {

  Board getPvLeaf(const Board& root, const Move& rmove, const Pv& pv) {
    Board board = root;
    board.makeMoveIrr(rmove);
    for (int d = 0; d < pv.size(); d++) {
      Move move = pv.get(d).move;
      if (move.isEmpty() || !board.makeMove(move)) {
        break;
      }
    }
    return board;
  }

  inline float sigmoid(float x) {
    return 1.0f / (1.0f + std::exp(-x));
  }

  inline float gradient(float x) {
    CONSTEXPR float a = 0.025f;
    CONSTEXPR float b = 1.8f;
    float s = sigmoid(a * x);
    return (1.0f - s) * s * b;
  }

  inline float norm(float x) {
    CONSTEXPR float n = 0.01f;
    if (x > 0.0f) {
      return -n;
    } else if (x < 0.0f) {
      return n;
    } else {
      return 0.0f;
    }
  }

}

/**
 * コンストラクタ
 */
Learn::Learn() : _rgen(static_cast<unsigned>(time(NULL))) {
  _config.addDef(CONF_KIFU, "");
  _config.addDef(CONF_DEPTH, "3");
  _config.addDef(CONF_THREADS, "1");
}

/**
 * 特徴抽出を行いパラメータを更新します。
 */
bool Learn::adjust(Board board, Move move0) {
  Value val0;
  Pv pv0;
  Move tmpMove;

  // 合法手生成
  Moves moves;
  MoveGenerator::generate(board, moves);

  if (moves.size() < 2) {
    return true;
  }

  // シャッフル
  std::shuffle(moves.begin(), moves.end(), _rgen);

  // 棋譜の手
  {
    // 探索
    board.makeMove(move0);
    _searcher.idsearch(board, tmpMove);
    board.unmakeMove(move0);

    // PV と評価値
    const auto& info = _searcher.getInfo();
    const auto& pv = info.pv;
    val0 = -info.eval;
    pv0.copy(pv);

    // 詰みは除外
    if (val0 <= -Value::Mate || val0 >= Value::Mate) {
      return true;
    }
  }

  // その他の手
  int nmove = 0;
  float gsum = 0;
  for (auto& move : moves) {
    // 探索
    bool valid = board.makeMove(move);
    if (!valid) { continue; }
    _searcher.idsearch(board, tmpMove);
    board.unmakeMove(move);

    // PV と評価値
    const auto& info = _searcher.getInfo();
    const auto& pv = info.pv;
    Value val = -info.eval;

    // 詰みは除外
    if (val <= -Value::Mate || val >= Value::Mate) {
      continue;
    }

    // leaf 局面
    Board leaf = getPvLeaf(board, move, pv);

    // 特徴抽出
    float g = gradient(val.int32() - val0.int32());
    g = g * (1.0f / MINI_BATCH_COUNT);
    _w.extract<float, true>(leaf, g);
    gsum += g;

    nmove++;
    if (nmove >= NUMBER_OF_SIBLING_NODES) {
      break;
    }
  }

  {
    // leaf 局面
    Board leaf = getPvLeaf(board, move0, pv0);

    // 特徴抽出
    _w.extract<float, true>(leaf, -gsum);
  }

  if (++_miniBatchCount >= MINI_BATCH_COUNT) {
    auto& eval = _searcher.getEvaluator();

    // 値更新
    float max = 0.0f;
    float magnitude = 0.0f;
    for (int i = 0; i < KPP_ALL; i++) {
      _w._t->kpp[0][i] += norm(_w._t->kpp[0][i]);
      eval._t->kpp[0][i] = _w._t->kpp[0][i];
      _u._t->kpp[0][i] += _w._t->kpp[0][i] * _count;
      max = std::max(max, std::abs(_w._t->kpp[0][i]));
      magnitude += std::abs(_w._t->kpp[0][i]);
    }
    for (int i = 0; i < KKP_ALL; i++) {
      _w._t->kkp[0][0][i] += norm(_w._t->kkp[0][0][i]);
      eval._t->kkp[0][0][i] = _w._t->kkp[0][0][i];
      _u._t->kkp[0][0][i] += _w._t->kkp[0][0][i] * _count;
      max = std::max(max, std::abs(_w._t->kkp[0][0][i]));
      magnitude += std::abs(_w._t->kkp[0][0][i]);
    }

    Loggers::message << "max=" << max << " magnitude=" << magnitude;

    _count++;
    _miniBatchCount = 0;
  }

  return true;
}

/**
 * 棋譜ファイルを読み込んで学習します。
 */
bool Learn::readCsa(const char* path) {
  Loggers::message << "load: [" << path << "]";

  Record record;
  if (!CsaReader::read(path, record)) {
    Loggers::warning << "Could not read csa file. [" << path << "]";
    return false;
  }

  // 棋譜の先頭へ
  while (record.unmakeMove())
    ;

  while (true) {
    // 次の1手を取得
    Move move = record.getNextMove();
    if (move.isEmpty()) {
      break;
    }

    bool ok = adjust(record.getBoard(), move);

    if (!ok) {
      return false;
    }

    // 1手進める
    if (!record.makeMove()) {
      break;
    }
  }

  return true;
}

/**
 * 機械学習を実行します。
 */
bool Learn::run() {
  // 設定読み込み
  if (!_config.read(CONFPATH)) {
    return false;
  }
  Loggers::message << _config.toString();

  Timer timer;
  timer.set();

  // 探索設定
  auto searchConfig = _searcher.getConfig();
  searchConfig.maxDepth = _config.getInt(CONF_DEPTH);
  searchConfig.workerSize = _config.getInt(CONF_THREADS);
  searchConfig.treeSize = Searcher::standardTreeSize(searchConfig.workerSize);
  searchConfig.enableLimit = false;
  searchConfig.enableTimeManagement = false;
  searchConfig.ponder = false;
  searchConfig.logging = false;
  _searcher.setConfig(searchConfig);

  // csa ファイルを列挙
  FileList fileList;
  std::string dir = _config.getString(CONF_KIFU);
  fileList.enumerate(dir.c_str(), "csa");

  // 初期化
  _count = 1;
  _miniBatchCount = 0;
  _w.init();
  _u.init();

  for (const auto& filename : fileList) {
    readCsa(filename.c_str());
  }

  // 平均を取る
  auto& eval = _searcher.getEvaluator();
  uint16_t max = 0;
  uint64_t magnitude = 0ull;
  for (int i = 0; i < KPP_ALL; i++) {
    eval._t->kpp[0][i] = _w._t->kpp[0][i] - _u._t->kpp[0][i] / _count;
    max = std::max(max, (uint16_t)std::abs(eval._t->kpp[0][i]));
    magnitude += std::abs(eval._t->kpp[0][i]);
  }
  for (int i = 0; i < KKP_ALL; i++) {
    eval._t->kkp[0][0][i] = _w._t->kkp[0][0][i] - _u._t->kkp[0][0][i] / _count;
    max = std::max(max, (uint16_t)std::abs(eval._t->kkp[0][0][i]));
    magnitude += std::abs(eval._t->kkp[0][0][i]);
  }

  Loggers::message << "max=" << max << " magnitude=" << magnitude;

  // 重みベクトルを保存
  eval.writeFile();

  double elapsed = timer.get();
  Loggers::message << "elapsed: " << elapsed;

  return true;
}

}

#endif // NLEARN
<|endoftext|>


<commit_before>#include "template.h"

static void attr_set_value(CK_ATTRIBUTE_PTR attr, const char* value, uint32_t valueLen) {
	try {
		attr->pValue = (char*)malloc(valueLen);
		memcpy(attr->pValue, value, valueLen);
		attr->ulValueLen = valueLen;
	}
	CATCH_ERROR;
}

static Scoped<CK_ATTRIBUTE> v2c_ATTRIBUTE(Local<Value> v8Attribute) {
	try {
		if (!v8Attribute->IsObject()) {
			THROW_ERROR("Parameter 1 MSUT be Object", NULL);
		}

		Local<Object> v8Object = v8Attribute->ToObject();

		Local<Value> v8Type = v8Object->Get(Nan::New(STR_TYPE).ToLocalChecked());
		if (!v8Type->IsNumber()) {
			THROW_ERROR("Member 'type' MUST be Number", NULL);
		}

		Local<Value> v8Value = v8Object->Get(Nan::New(STR_VALUE).ToLocalChecked());
		if (!(v8Value->IsUndefined() || v8Value->IsNull() ||
			node::Buffer::HasInstance(v8Value) ||
			v8Value->IsBoolean() ||
			v8Value->IsString() ||
			v8Value->IsNumber())) {
			THROW_ERROR("Member 'value' MUST has wrong type", NULL);
		}

		Scoped<CK_ATTRIBUTE> attr(new CK_ATTRIBUTE());
		attr->pValue = NULL;
		attr->ulValueLen = 0;

		attr->type = Nan::To<v8::Number>(v8Type).ToLocalChecked()->Uint32Value();
		if (node::Buffer::HasInstance(v8Value)) {
			// Buffer
			GET_BUFFER_SMPL(data, v8Value);
			attr_set_value(attr.get(), data, (uint32_t)dataLen);
		}
		else if (v8Value->IsBoolean()) {
			// Boolean
			char data[1];
			data[0] = (char)v8Value->ToBoolean()->Value();
			attr_set_value(attr.get(), data, 1);
		}
		else if (v8Value->IsNumber()) {
			// Number
			CK_ULONG num = Nan::To<v8::Number>(v8Value).ToLocalChecked()->Uint32Value();

			uint32_t long_size = sizeof(CK_ULONG);

			attr->pValue = (char*)malloc(long_size);
			for (uint32_t i = 0; i < long_size; i++)
				((char*)attr->pValue)[i] = (char)(num >> (i * 8));
			attr->ulValueLen = long_size;
		}
		else if (v8Value->IsString()) {
			// String
			String::Utf8Value utf8Val(v8Value);
			char* val = *utf8Val;
			int valLen = utf8Val.length();
			attr_set_value(attr.get(), val, valLen);
		}

		return attr;
	}
	CATCH_ERROR;
}

static Local<Object> c2v_ATTRIBUTE(CK_ATTRIBUTE_PTR attr) {
	try {
		Nan::HandleScope();

		if (!attr) {
			THROW_ERROR("Parameter 1 is EMPTY", NULL);
		}

		Local<Object> v8Attribute = Nan::New<Object>();

		// Type
		v8Attribute->Set(Nan::New(STR_TYPE).ToLocalChecked(), Nan::New<Number>(attr->type));

		// Value
		Local<Object> v8Value = node::Buffer::Copy(Isolate::GetCurrent(), (char *)attr->pValue, attr->ulValueLen).ToLocalChecked();
		v8Attribute->Set(Nan::New(STR_VALUE).ToLocalChecked(), v8Value);

		return v8Attribute;
	}
	CATCH_ERROR;
}

static void TEMPLATE_free(TEMPLATE* tmpl) {
	if (tmpl && tmpl->items) {
		// Free attr values
		for (CK_ULONG i = 0; i < tmpl->size; i++) {
			if (&tmpl->items[i] && tmpl->items[i].pValue) {
				free(tmpl->items[i].pValue);
			}
		}
		free(tmpl->items);
	}
}

Attributes::Attributes() {
	data = TEMPLATE();
	data.size = 0;
	data.items = NULL;
}

Attributes::~Attributes() {
	TEMPLATE_free(Get());
}

TEMPLATE* Attributes::New() {
	TEMPLATE_free(Get());
	data = TEMPLATE();
	data.size = 0;
	data.items = NULL;
	return Get();
}

void Attributes::Push(CK_ATTRIBUTE_PTR attr) {
	try {
		if (!attr)
			THROW_ERROR("Parameter 1 is EMPTY", NULL);
		if (Get()) {
			data.items = (CK_ATTRIBUTE_PTR)realloc(data.items, ++data.size * sizeof(CK_ATTRIBUTE));
			data.items[data.size - 1] = *(attr);
		}
	}
	CATCH_ERROR;
}

void Attributes::FromV8(Local<Value> v8Value) {
	try {
		Nan::HandleScope();

		if (!v8Value->IsArray()) {
			THROW_ERROR("Parameter 1 MUST be Array", NULL);
		}

		Local<Object> v8Template = v8Value->ToObject();
		uint32_t templateLen = Nan::To<v8::Number>(v8Template->Get(Nan::New("length").ToLocalChecked())).ToLocalChecked()->Uint32Value();

		uint32_t i = 0;
		New();
		for (i = 0; i < templateLen; i++) {
			Local<Value> v8Attribute = v8Template->Get(i);
			Scoped<CK_ATTRIBUTE> attr = v2c_ATTRIBUTE(v8Attribute);
			this->Push(attr.get());
		}
	}
	CATCH_ERROR;
}

Local<Object> Attributes::ToV8() {
	try {
		Nan::HandleScope();

		Local<Array> v8Res = Nan::New<Array>();
		for (uint32_t i = 0; i < data.size; i++) {
			CK_ATTRIBUTE_PTR pItem = &data.items[i];
			Local<Object> v8Attribute = c2v_ATTRIBUTE(pItem);

			v8Res->Set(i, v8Attribute);
		}
		return v8Res;
	}
	CATCH_ERROR;
}<commit_msg>V8 number attribute value in template converted to CK_ULONG incorrectly in s390x<commit_after>#include "template.h"

static void attr_set_value(CK_ATTRIBUTE_PTR attr, const char* value, uint32_t valueLen) {
	try {
		attr->pValue = (char*)malloc(valueLen);
		memcpy(attr->pValue, value, valueLen);
		attr->ulValueLen = valueLen;
	}
	CATCH_ERROR;
}

static Scoped<CK_ATTRIBUTE> v2c_ATTRIBUTE(Local<Value> v8Attribute) {
	try {
		if (!v8Attribute->IsObject()) {
			THROW_ERROR("Parameter 1 MSUT be Object", NULL);
		}

		Local<Object> v8Object = v8Attribute->ToObject();

		Local<Value> v8Type = v8Object->Get(Nan::New(STR_TYPE).ToLocalChecked());
		if (!v8Type->IsNumber()) {
			THROW_ERROR("Member 'type' MUST be Number", NULL);
		}

		Local<Value> v8Value = v8Object->Get(Nan::New(STR_VALUE).ToLocalChecked());
		if (!(v8Value->IsUndefined() || v8Value->IsNull() ||
			node::Buffer::HasInstance(v8Value) ||
			v8Value->IsBoolean() ||
			v8Value->IsString() ||
			v8Value->IsNumber())) {
			THROW_ERROR("Member 'value' MUST has wrong type", NULL);
		}

		Scoped<CK_ATTRIBUTE> attr(new CK_ATTRIBUTE());
		attr->pValue = NULL;
		attr->ulValueLen = 0;

		attr->type = Nan::To<v8::Number>(v8Type).ToLocalChecked()->Uint32Value();
		if (node::Buffer::HasInstance(v8Value)) {
			// Buffer
			GET_BUFFER_SMPL(data, v8Value);
			attr_set_value(attr.get(), data, (uint32_t)dataLen);
		}
		else if (v8Value->IsBoolean()) {
			// Boolean
			char data[1];
			data[0] = (char)v8Value->ToBoolean()->Value();
			attr_set_value(attr.get(), data, 1);
		}
		else if (v8Value->IsNumber()) {
			// Number
			CK_ULONG num = Nan::To<v8::Number>(v8Value).ToLocalChecked()->Uint32Value();

			uint32_t long_size = sizeof(CK_ULONG);

			attr->pValue = (char*)malloc(long_size);
			//for (uint32_t i = 0; i < long_size; i++)
			//	((char*)attr->pValue)[i] = (char)(num >> (i * 8));
			*(CK_ULONG*)attr->pValue = num;
			attr->ulValueLen = long_size;
		}
		else if (v8Value->IsString()) {
			// String
			String::Utf8Value utf8Val(v8Value);
			char* val = *utf8Val;
			int valLen = utf8Val.length();
			attr_set_value(attr.get(), val, valLen);
		}

		return attr;
	}
	CATCH_ERROR;
}

static Local<Object> c2v_ATTRIBUTE(CK_ATTRIBUTE_PTR attr) {
	try {
		Nan::HandleScope();

		if (!attr) {
			THROW_ERROR("Parameter 1 is EMPTY", NULL);
		}

		Local<Object> v8Attribute = Nan::New<Object>();

		// Type
		v8Attribute->Set(Nan::New(STR_TYPE).ToLocalChecked(), Nan::New<Number>(attr->type));

		// Value
		Local<Object> v8Value = node::Buffer::Copy(Isolate::GetCurrent(), (char *)attr->pValue, attr->ulValueLen).ToLocalChecked();
		v8Attribute->Set(Nan::New(STR_VALUE).ToLocalChecked(), v8Value);

		return v8Attribute;
	}
	CATCH_ERROR;
}

static void TEMPLATE_free(TEMPLATE* tmpl) {
	if (tmpl && tmpl->items) {
		// Free attr values
		for (CK_ULONG i = 0; i < tmpl->size; i++) {
			if (&tmpl->items[i] && tmpl->items[i].pValue) {
				free(tmpl->items[i].pValue);
			}
		}
		free(tmpl->items);
	}
}

Attributes::Attributes() {
	data = TEMPLATE();
	data.size = 0;
	data.items = NULL;
}

Attributes::~Attributes() {
	TEMPLATE_free(Get());
}

TEMPLATE* Attributes::New() {
	TEMPLATE_free(Get());
	data = TEMPLATE();
	data.size = 0;
	data.items = NULL;
	return Get();
}

void Attributes::Push(CK_ATTRIBUTE_PTR attr) {
	try {
		if (!attr)
			THROW_ERROR("Parameter 1 is EMPTY", NULL);
		if (Get()) {
			data.items = (CK_ATTRIBUTE_PTR)realloc(data.items, ++data.size * sizeof(CK_ATTRIBUTE));
			data.items[data.size - 1] = *(attr);
		}
	}
	CATCH_ERROR;
}

void Attributes::FromV8(Local<Value> v8Value) {
	try {
		Nan::HandleScope();

		if (!v8Value->IsArray()) {
			THROW_ERROR("Parameter 1 MUST be Array", NULL);
		}

		Local<Object> v8Template = v8Value->ToObject();
		uint32_t templateLen = Nan::To<v8::Number>(v8Template->Get(Nan::New("length").ToLocalChecked())).ToLocalChecked()->Uint32Value();

		uint32_t i = 0;
		New();
		for (i = 0; i < templateLen; i++) {
			Local<Value> v8Attribute = v8Template->Get(i);
			Scoped<CK_ATTRIBUTE> attr = v2c_ATTRIBUTE(v8Attribute);
			this->Push(attr.get());
		}
	}
	CATCH_ERROR;
}

Local<Object> Attributes::ToV8() {
	try {
		Nan::HandleScope();

		Local<Array> v8Res = Nan::New<Array>();
		for (uint32_t i = 0; i < data.size; i++) {
			CK_ATTRIBUTE_PTR pItem = &data.items[i];
			Local<Object> v8Attribute = c2v_ATTRIBUTE(pItem);

			v8Res->Set(i, v8Attribute);
		}
		return v8Res;
	}
	CATCH_ERROR;
}
<|endoftext|>


<commit_before>/// HEADER
#include "register_core_plugins.h"

/// COMPONENT
#include "../io/file_importer.h"

/// PROJECT
#include <csapex/factory/message_factory.h>
#include <csapex/model/tag.h>
#include <csapex/factory/node_factory.h>
#include <csapex/model/graph.h>
#include <csapex/model/node_state.h>
#include <csapex/param/parameter_factory.h>

/// SYSTEM
#include <csapex/utility/register_apex_plugin.h>

CSAPEX_REGISTER_CLASS(csapex::RegisterCorePlugins, csapex::CorePlugin)

using namespace csapex;

RegisterCorePlugins::RegisterCorePlugins()
{
}

void RegisterCorePlugins::init(CsApexCore& core)
{
    Tag::createIfNotExists("Buffer");
    Tag::createIfNotExists("General");
    Tag::createIfNotExists("Input");
    Tag::createIfNotExists("Output");
    Tag::createIfNotExists("RosIO");
    Tag::createIfNotExists("ConsoleIO");
    Tag::createIfNotExists("Debug");
}

void RegisterCorePlugins::shutdown()
{
}
<commit_msg>registering values for vectors<commit_after>/// HEADER
#include "register_core_plugins.h"

/// COMPONENT
#include "../io/file_importer.h"

/// PROJECT
#include <csapex/factory/message_factory.h>
#include <csapex/model/tag.h>
#include <csapex/factory/node_factory.h>
#include <csapex/model/graph.h>
#include <csapex/model/node_state.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/msg/generic_vector_message.hpp>
#include <csapex/utility/yaml_io.hpp>

/// SYSTEM
#include <csapex/utility/register_apex_plugin.h>

CSAPEX_REGISTER_CLASS(csapex::RegisterCorePlugins, csapex::CorePlugin)

using namespace csapex;

RegisterCorePlugins::RegisterCorePlugins()
{
}

void RegisterCorePlugins::init(CsApexCore& core)
{
    Tag::createIfNotExists("Buffer");
    Tag::createIfNotExists("General");
    Tag::createIfNotExists("Input");
    Tag::createIfNotExists("Output");
    Tag::createIfNotExists("RosIO");
    Tag::createIfNotExists("ConsoleIO");
    Tag::createIfNotExists("Debug");

    connection_types::GenericVectorMessage::registerType<int>();
    connection_types::GenericVectorMessage::registerType<double>();
    connection_types::GenericVectorMessage::registerType<std::string>();
}

void RegisterCorePlugins::shutdown()
{
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: chips/p9/procedures/hwp/memory/lib/eff_config/timing.C $      */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* EKB Project                                                            */
/*                                                                        */
/* COPYRIGHT 2016                                                         */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include <fapi2.H>
#include <mss.H>
#include <lib/utils/find.H>
#include <lib/eff_config/timing.H>

namespace mss
{

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TREFI_BASE =
{
    // { density in GBs, tREFI(base) in nanoseconds }
    {2, 7800},
    {4, 7800},
    {8, 7800},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC1_MIN =
{
    // { density in GBs, tRFC1(min) in nanoseconds }
    {2, 160},
    {4, 260},
    {8, 350},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC2_MIN =
{
    // { density in GBs, tRFC2(min) in nanoseconds }
    {2, 110},
    {4, 160},
    {8, 260},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC4_MIN =
{
    // { density in GBs, tRFC4(min) in nanoseconds }
    {2, 90},
    {4, 110},
    {8, 160},
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR1 =
{
    // { density in GBs, tRFC4(min) in nanoseconds }
    {4, 90},
    {8, 120},
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR2 =
{
    // { density in GBs, tRFC4(min) in nanoseconds }
    {4, 55},
    {8, 90}
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR4 =
{
    // { density in GBs, tRFC4(min) in nanoseconds }
    {4, 40},
    {8, 55}
    // 16Gb - TBD
};

/// @brief Calculates refresh interval time 1 (tREFI 1)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi1(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                              uint64_t& o_value)
{
    uint8_t  l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_ref_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );
    FAPI_TRY( mss::mrw_temp_ref_range(l_temp_ref_range) );

    switch(l_temp_ref_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_NORMAL:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "normal temp_ref_range.") );
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_EXTEND:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "extended temp_ref_range.") );
            l_quotient = l_output / 2;
            l_remainder = l_output % 2;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // l_temp_ref_range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_ref_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_ref_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Calculates refresh interval time 2 (tREFI 2)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi2(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                              uint64_t& o_value)
{
    uint8_t l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_ref_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::mrw_temp_ref_range(l_temp_ref_range) );
    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );

    switch(l_temp_ref_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_NORMAL:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "normal temp_ref_range.") );

            l_remainder = l_output % 2;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_EXTEND:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "extended temp_ref_range.") );
            l_quotient = l_output / 4;
            l_remainder = l_output % 4;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // l_temp_ref_range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_ref_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_ref_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Calculates refresh interval time 4 (tREFI 4)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi4( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                               uint64_t& o_value)
{
    uint8_t l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_ref_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::mrw_temp_ref_range(l_temp_ref_range) );
    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );

    switch(l_temp_ref_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_NORMAL:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "normal temp_ref_range.") );
            l_quotient = l_output / 4;
            l_remainder = l_output % 4;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_EXTEND:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "extended temp_ref_range.") );
            l_quotient = l_output / 8;
            l_remainder = l_output % 8;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // l_temp_ref_range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_ref_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_ref_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

}// mss
<commit_msg>Add eff_config functionality needed for RIT, fix cas_latency bug & attr files<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: chips/p9/procedures/hwp/memory/lib/eff_config/timing.C $      */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* EKB Project                                                            */
/*                                                                        */
/* COPYRIGHT 2016                                                         */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include <fapi2.H>
#include <mss.H>
#include <lib/utils/find.H>
#include <lib/eff_config/timing.H>

namespace mss
{

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TREFI_BASE =
{
    // { density in GBs, tREFI(base) in picoseconds }
    {2, 7800000},
    {4, 7800000},
    {8, 7800000},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC1_MIN =
{
    // { density in GBs, tRFC1(min) in picoseconds }
    {2, 160000},
    {4, 260000},
    {8, 350000},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC2_MIN =
{
    // { density in GBs, tRFC2(min) in picoseconds }
    {2, 110000},
    {4, 160000},
    {8, 260000},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC4_MIN =
{
    // { density in GBs, tRFC4(min) in picoseconds }
    {2, 90000},
    {4, 110000},
    {8, 160000},
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR1 =
{
    // { density in GBs, tRFC4(min) in picoseconds }
    {4, 90000},
    {8, 120000},
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR2 =
{
    // { density in GBs, tRFC4(min) in picoseconds }
    {4, 55000},
    {8, 90000}
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR4 =
{
    // { density in GBs, tRFC4(min) in picoseconds }
    {4, 40000},
    {8, 55000}
    // 16Gb - TBD
};

/// @brief Calculates refresh interval time 1 (tREFI 1)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi1(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                              uint64_t& o_value)
{
    uint8_t  l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_refresh_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );
    FAPI_TRY( mss::mrw_temp_refresh_range(l_temp_refresh_range) );

    l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);

    switch(l_temp_refresh_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REFRESH_RANGE_NORMAL:
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_refresh_range,
                                                  "Could not find sdram density given "
                                                  "normal temp_refresh_range.") );
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REFRESH_RANGE_EXTEND:
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_refresh_range,
                                                  "Could not find sdram density given "
                                                  "extended temp_refresh_range.") );
            l_quotient = l_output / 2;
            l_remainder = l_output % 2;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // Temperature Refresh Range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_refresh_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_refresh_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Calculates refresh interval time 2 (tREFI 2)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi2(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                              uint64_t& o_value)
{
    uint8_t l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_refresh_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::mrw_temp_refresh_range(l_temp_refresh_range) );
    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );

    l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);

    switch(l_temp_refresh_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REFRESH_RANGE_NORMAL:
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_refresh_range,
                                                  "Could not find sdram density given "
                                                  "normal temp_refresh_range.") );

            l_remainder = l_output % 2;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REFRESH_RANGE_EXTEND:
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_refresh_range,
                                                  "Could not find sdram density given "
                                                  "extended temp_refresh_range.") );
            l_quotient = l_output / 4;
            l_remainder = l_output % 4;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // Temperature Refresh Range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_refresh_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_refresh_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Calculates refresh interval time 4 (tREFI 4)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi4( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                               uint64_t& o_value)
{
    uint8_t l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_refresh_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::mrw_temp_refresh_range(l_temp_refresh_range) );
    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );

    l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);

    switch(l_temp_refresh_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REFRESH_RANGE_NORMAL:
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_refresh_range,
                                                  "Could not find sdram density given "
                                                  "normal temp_refresh_range.") );
            l_quotient = l_output / 4;
            l_remainder = l_output % 4;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REFRESH_RANGE_EXTEND:
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_refresh_range,
                                                  "Could not find sdram density given "
                                                  "extended temp_refresh_range.") );
            l_quotient = l_output / 8;
            l_remainder = l_output % 8;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // Temperature Refresh Range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_refresh_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_refresh_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

}// mss
<|endoftext|>