<commit_before>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include "etl/expr/base_temporary_expr.hpp"

namespace etl {

/*!
 * \brief A batch softmax function expression
 *
 * \tparam A The unary sub type
 */
template <typename A, bool Stable>
struct batch_softmax_expr : base_temporary_expr_un<batch_softmax_expr<A, Stable>, A> {
    using value_type = value_t<A>;                           ///< The type of value of the expression
    using this_type  = batch_softmax_expr<A, Stable>;        ///< The type of this expression
    using base_type  = base_temporary_expr_un<this_type, A>; ///< The base type
    using sub_traits = decay_traits<A>;                      ///< The traits of the sub type

    static constexpr auto storage_order = sub_traits::storage_order; ///< The sub storage order

    /*!
     * \brief Construct a new expression
     * \param a The sub expression
     */
    explicit batch_softmax_expr(A a) : base_type(a) {
        //Nothing else to init
    }

    /*!
     * \brief Validate the function dimensions
     * \param a The input matrix
     * \þaram c The output matrix
     */
    template <typename C, cpp_enable_if(all_fast<A,C>)>
    static void check(const A& a, const C& c) {
        cpp_unused(a);
        cpp_unused(c);

        static constexpr etl::order order_lhs = decay_traits<C>::storage_order;
        static constexpr etl::order order_rhs = decay_traits<A>::storage_order;

        static_assert(order_lhs == order_rhs, "Cannot change storage order");
        static_assert(decay_traits<A>::dimensions() == decay_traits<C>::dimensions(), "Invalid dimensions");
        static_assert(decay_traits<A>::size() == decay_traits<C>::size(), "Invalid size");
    }

    /*!
     * \brief Validate the function dimensions
     * \param a The input matrix
     * \þaram c The output matrix
     */
    template <typename C, cpp_disable_if(all_fast<A,C>)>
    static void check(const A& a, const C& c) {
        static constexpr etl::order order_lhs = decay_traits<C>::storage_order;
        static constexpr etl::order order_rhs = decay_traits<A>::storage_order;

        static_assert(order_lhs == order_rhs, "Cannot change storage order");
        static_assert(decay_traits<A>::dimensions() == decay_traits<C>::dimensions(), "Invalid dimensions");
        cpp_assert(etl::size(a) == etl::size(c), "Invalid size");

        cpp_unused(a);
        cpp_unused(c);
    }

    // Assignment functions

    /*!
     * \brief Select the best possible implementation for the batch softmax operation
     *
     * This routine does not consider the local context
     */
    template<typename C>
    constexpr static batch_softmax_impl select_default_impl(bool no_gpu){
        if (cudnn_enabled && all_homogeneous<A, C> && all_floating<A, C> && !no_gpu) {
            return batch_softmax_impl::CUDNN;
        }

        return batch_softmax_impl::STD;
    }

#ifdef ETL_MANUAL_SELECT

    /*!
     * \brief Select the best possible implementation for the batch softmax operation
     */
    template<typename C>
    static batch_softmax_impl select_impl(){
        return select_default_impl<C>(local_context().cpu);
    }

#else

    /*!
     * \brief Select the best possible implementation for the batch softmax operation
     */
    template<typename C>
    constexpr static batch_softmax_impl select_impl(){
        return select_default_impl<C>(false);
    }

#endif

    /*!
     * \brief Assign to a matrix of the same storage order
     * \param c The expression to which assign
     */
    template<typename C, cpp_enable_if(decay_traits<C>::storage_order == storage_order)>
    void assign_to(C&& c)  const {
        static_assert(all_etl_expr<A, C>, "Function expression only supported for ETL expressions");

        auto& a = this->a();

        standard_evaluator::pre_assign_rhs(a);

        check(a, c);

        constexpr_select auto impl = select_impl<C>();

        if /*constexpr_select*/ (impl == batch_softmax_impl::CUDNN) {
            decltype(auto) a_gpu = smart_forward_gpu(a);

            if /*constexpr*/ (Stable) {
                impl::cudnn::stable_softmax(a_gpu, c);
            } else {
                impl::cudnn::softmax(a_gpu, c);
            }
        } else if /*constexpr_select*/ (impl == batch_softmax_impl::STD) {
            if /*constexpr*/ (Stable) {
                for (size_t i = 0; i < etl::dim<0>(c); ++i) {
                    c(i) = exp(a(i)) / sum(exp(a(i)));
                }
            } else {
                for (size_t i = 0; i < etl::dim<0>(c); ++i) {
                    auto m = max(a(i));
                    c(i)   = exp(a(i) - m) / sum(exp(a(i) - m));
                }
            }
        } else {
            cpp_unreachable("Invalid selection for batch_softmax");
        }
    }

    /*!
     * \brief Assign to a matrix of a different storage order
     * \param c The expression to which assign
     */
    template<typename C, cpp_enable_if(decay_traits<C>::storage_order != storage_order)>
    void assign_to(C&& c)  const {
        std_assign_evaluate(*this, c);
    }

    /*!
     * \brief Add to the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_add_to(L&& lhs)  const {
        std_add_evaluate(*this, lhs);
    }

    /*!
     * \brief Sub from the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_sub_to(L&& lhs)  const {
        std_sub_evaluate(*this, lhs);
    }

    /*!
     * \brief Multiply the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_mul_to(L&& lhs)  const {
        std_mul_evaluate(*this, lhs);
    }

    /*!
     * \brief Divide the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_div_to(L&& lhs)  const {
        std_div_evaluate(*this, lhs);
    }

    /*!
     * \brief Modulo the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_mod_to(L&& lhs)  const {
        std_mod_evaluate(*this, lhs);
    }

    /*!
     * \brief Print a representation of the expression on the given stream
     * \param os The output stream
     * \param expr The expression to print
     * \return the output stream
     */
    friend std::ostream& operator<<(std::ostream& os, const batch_softmax_expr& expr) {
        return os << "batch_softmax(" << expr._a << ")";
    }
};

/*!
 * \brief Traits for an unary function expression
 * \tparam A The unary sub type
 */
template <typename A, bool Stable>
struct etl_traits<etl::batch_softmax_expr<A, Stable>> {
    using expr_t     = etl::batch_softmax_expr<A, Stable>; ///< The expression type
    using sub_expr_t = std::decay_t<A>;                    ///< The sub expression type
    using sub_traits = etl_traits<sub_expr_t>;             ///< The sub traits
    using value_type = value_t<A>;                       ///< The value type of the expression

    static constexpr bool is_etl         = true;                                 ///< Indicates if the type is an ETL expression
    static constexpr bool is_transformer = false;                                ///< Indicates if the type is a transformer
    static constexpr bool is_view        = false;                                ///< Indicates if the type is a view
    static constexpr bool is_magic_view  = false;                                ///< Indicates if the type is a magic view
    static constexpr bool is_fast        = sub_traits::is_fast;                  ///< Indicates if the expression is fast
    static constexpr bool is_linear      = true;                                 ///< Indicates if the expression is linear
    static constexpr bool is_thread_safe = true;                                 ///< Indicates if the expression is thread safe
    static constexpr bool is_value       = false;                                ///< Indicates if the expression is of value type
    static constexpr bool is_direct      = true;                                 ///< Indicates if the expression has direct memory access
    static constexpr bool is_generator   = false;                                ///< Indicates if the expression is a generator
    static constexpr bool is_padded      = false;                                ///< Indicates if the expression is padded
    static constexpr bool is_aligned     = true;                                 ///< Indicates if the expression is padded
    static constexpr bool is_temporary   = true;                                 ///< Indicates if the expression needs a evaluator visitor
    static constexpr bool gpu_computable = is_gpu_t<value_type> && cuda_enabled; ///< Indicates if the expression can be computed on GPU
    static constexpr order storage_order = sub_traits::storage_order;            ///< The expression's storage order

    /*!
     * \brief Indicates if the expression is vectorizable using the
     * given vector mode
     * \tparam V The vector mode
     */
    template <vector_mode_t V>
    using vectorizable = std::true_type;

    /*!
     * \brief Returns the DDth dimension of the expression
     * \return the DDth dimension of the expression
     */
    template <size_t DD>
    static constexpr size_t dim() {
        return decay_traits<A>::template dim<DD>();
    }

    /*!
     * \brief Returns the dth dimension of the expression
     * \param e The sub expression
     * \param d The dimension to get
     * \return the dth dimension of the expression
     */
    static size_t dim(const expr_t& e, size_t d) {
        return etl::dim(e._a, d);
    }

    /*!
     * \brief Returns the size of the expression
     * \param e The sub expression
     * \return the size of the expression
     */
    static size_t size(const expr_t& e) {
        return etl::size(e._a);
    }

    /*!
     * \brief Returns the size of the expression
     * \return the size of the expression
     */
    static constexpr size_t size() {
        return decay_traits<A>::size();
    }

    /*!
     * \brief Returns the number of dimensions of the expression
     * \return the number of dimensions of the expression
     */
    static constexpr size_t dimensions() {
        return decay_traits<A>::dimensions();
    }
};

} //end of namespace etl
<commit_msg>Cleanup<commit_after>//=======================================================================
// Copyright (c) 2014-2017 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include "etl/expr/base_temporary_expr.hpp"

namespace etl {

/*!
 * \brief A batch softmax function expression
 *
 * \tparam A The unary sub type
 */
template <typename A, bool Stable>
struct batch_softmax_expr : base_temporary_expr_un<batch_softmax_expr<A, Stable>, A> {
    using value_type = value_t<A>;                           ///< The type of value of the expression
    using this_type  = batch_softmax_expr<A, Stable>;        ///< The type of this expression
    using base_type  = base_temporary_expr_un<this_type, A>; ///< The base type
    using sub_traits = decay_traits<A>;                      ///< The traits of the sub type

    static constexpr auto storage_order = sub_traits::storage_order; ///< The sub storage order

    /*!
     * \brief Construct a new expression
     * \param a The sub expression
     */
    explicit batch_softmax_expr(A a) : base_type(a) {
        //Nothing else to init
    }

    /*!
     * \brief Validate the function dimensions
     * \param a The input matrix
     * \þaram c The output matrix
     */
    template <typename C, cpp_enable_iff(all_fast<A,C>)>
    static void check(const A& a, const C& c) {
        cpp_unused(a);
        cpp_unused(c);

        static constexpr etl::order order_lhs = decay_traits<C>::storage_order;
        static constexpr etl::order order_rhs = decay_traits<A>::storage_order;

        static_assert(order_lhs == order_rhs, "Cannot change storage order");
        static_assert(decay_traits<A>::dimensions() == decay_traits<C>::dimensions(), "Invalid dimensions");
        static_assert(decay_traits<A>::size() == decay_traits<C>::size(), "Invalid size");
    }

    /*!
     * \brief Validate the function dimensions
     * \param a The input matrix
     * \þaram c The output matrix
     */
    template <typename C, cpp_disable_if(all_fast<A,C>)>
    static void check(const A& a, const C& c) {
        static constexpr etl::order order_lhs = decay_traits<C>::storage_order;
        static constexpr etl::order order_rhs = decay_traits<A>::storage_order;

        static_assert(order_lhs == order_rhs, "Cannot change storage order");
        static_assert(decay_traits<A>::dimensions() == decay_traits<C>::dimensions(), "Invalid dimensions");
        cpp_assert(etl::size(a) == etl::size(c), "Invalid size");

        cpp_unused(a);
        cpp_unused(c);
    }

    // Assignment functions

    /*!
     * \brief Select the best possible implementation for the batch softmax operation
     *
     * This routine does not consider the local context
     */
    template<typename C>
    constexpr static batch_softmax_impl select_default_impl(bool no_gpu){
        if (cudnn_enabled && all_homogeneous<A, C> && all_floating<A, C> && !no_gpu) {
            return batch_softmax_impl::CUDNN;
        }

        return batch_softmax_impl::STD;
    }

#ifdef ETL_MANUAL_SELECT

    /*!
     * \brief Select the best possible implementation for the batch softmax operation
     */
    template<typename C>
    static batch_softmax_impl select_impl(){
        return select_default_impl<C>(local_context().cpu);
    }

#else

    /*!
     * \brief Select the best possible implementation for the batch softmax operation
     */
    template<typename C>
    constexpr static batch_softmax_impl select_impl(){
        return select_default_impl<C>(false);
    }

#endif

    /*!
     * \brief Assign to a matrix of the same storage order
     * \param c The expression to which assign
     */
    template<typename C, cpp_enable_iff(decay_traits<C>::storage_order == storage_order)>
    void assign_to(C&& c)  const {
        static_assert(all_etl_expr<A, C>, "Function expression only supported for ETL expressions");

        auto& a = this->a();

        standard_evaluator::pre_assign_rhs(a);

        check(a, c);

        constexpr_select auto impl = select_impl<C>();

        if /*constexpr_select*/ (impl == batch_softmax_impl::CUDNN) {
            decltype(auto) a_gpu = smart_forward_gpu(a);

            if /*constexpr*/ (Stable) {
                impl::cudnn::stable_softmax(a_gpu, c);
            } else {
                impl::cudnn::softmax(a_gpu, c);
            }
        } else if /*constexpr_select*/ (impl == batch_softmax_impl::STD) {
            if /*constexpr*/ (Stable) {
                for (size_t i = 0; i < etl::dim<0>(c); ++i) {
                    c(i) = exp(a(i)) / sum(exp(a(i)));
                }
            } else {
                for (size_t i = 0; i < etl::dim<0>(c); ++i) {
                    auto m = max(a(i));
                    c(i)   = exp(a(i) - m) / sum(exp(a(i) - m));
                }
            }
        } else {
            cpp_unreachable("Invalid selection for batch_softmax");
        }
    }

    /*!
     * \brief Assign to a matrix of a different storage order
     * \param c The expression to which assign
     */
    template<typename C, cpp_enable_iff(decay_traits<C>::storage_order != storage_order)>
    void assign_to(C&& c)  const {
        std_assign_evaluate(*this, c);
    }

    /*!
     * \brief Add to the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_add_to(L&& lhs)  const {
        std_add_evaluate(*this, lhs);
    }

    /*!
     * \brief Sub from the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_sub_to(L&& lhs)  const {
        std_sub_evaluate(*this, lhs);
    }

    /*!
     * \brief Multiply the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_mul_to(L&& lhs)  const {
        std_mul_evaluate(*this, lhs);
    }

    /*!
     * \brief Divide the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_div_to(L&& lhs)  const {
        std_div_evaluate(*this, lhs);
    }

    /*!
     * \brief Modulo the given left-hand-side expression
     * \param lhs The expression to which assign
     */
    template<typename L>
    void assign_mod_to(L&& lhs)  const {
        std_mod_evaluate(*this, lhs);
    }

    /*!
     * \brief Print a representation of the expression on the given stream
     * \param os The output stream
     * \param expr The expression to print
     * \return the output stream
     */
    friend std::ostream& operator<<(std::ostream& os, const batch_softmax_expr& expr) {
        return os << "batch_softmax(" << expr._a << ")";
    }
};

/*!
 * \brief Traits for an unary function expression
 * \tparam A The unary sub type
 */
template <typename A, bool Stable>
struct etl_traits<etl::batch_softmax_expr<A, Stable>> {
    using expr_t     = etl::batch_softmax_expr<A, Stable>; ///< The expression type
    using sub_expr_t = std::decay_t<A>;                    ///< The sub expression type
    using sub_traits = etl_traits<sub_expr_t>;             ///< The sub traits
    using value_type = value_t<A>;                       ///< The value type of the expression

    static constexpr bool is_etl         = true;                                 ///< Indicates if the type is an ETL expression
    static constexpr bool is_transformer = false;                                ///< Indicates if the type is a transformer
    static constexpr bool is_view        = false;                                ///< Indicates if the type is a view
    static constexpr bool is_magic_view  = false;                                ///< Indicates if the type is a magic view
    static constexpr bool is_fast        = sub_traits::is_fast;                  ///< Indicates if the expression is fast
    static constexpr bool is_linear      = true;                                 ///< Indicates if the expression is linear
    static constexpr bool is_thread_safe = true;                                 ///< Indicates if the expression is thread safe
    static constexpr bool is_value       = false;                                ///< Indicates if the expression is of value type
    static constexpr bool is_direct      = true;                                 ///< Indicates if the expression has direct memory access
    static constexpr bool is_generator   = false;                                ///< Indicates if the expression is a generator
    static constexpr bool is_padded      = false;                                ///< Indicates if the expression is padded
    static constexpr bool is_aligned     = true;                                 ///< Indicates if the expression is padded
    static constexpr bool is_temporary   = true;                                 ///< Indicates if the expression needs a evaluator visitor
    static constexpr bool gpu_computable = is_gpu_t<value_type> && cuda_enabled; ///< Indicates if the expression can be computed on GPU
    static constexpr order storage_order = sub_traits::storage_order;            ///< The expression's storage order

    /*!
     * \brief Indicates if the expression is vectorizable using the
     * given vector mode
     * \tparam V The vector mode
     */
    template <vector_mode_t V>
    using vectorizable = std::true_type;

    /*!
     * \brief Returns the DDth dimension of the expression
     * \return the DDth dimension of the expression
     */
    template <size_t DD>
    static constexpr size_t dim() {
        return decay_traits<A>::template dim<DD>();
    }

    /*!
     * \brief Returns the dth dimension of the expression
     * \param e The sub expression
     * \param d The dimension to get
     * \return the dth dimension of the expression
     */
    static size_t dim(const expr_t& e, size_t d) {
        return etl::dim(e._a, d);
    }

    /*!
     * \brief Returns the size of the expression
     * \param e The sub expression
     * \return the size of the expression
     */
    static size_t size(const expr_t& e) {
        return etl::size(e._a);
    }

    /*!
     * \brief Returns the size of the expression
     * \return the size of the expression
     */
    static constexpr size_t size() {
        return decay_traits<A>::size();
    }

    /*!
     * \brief Returns the number of dimensions of the expression
     * \return the number of dimensions of the expression
     */
    static constexpr size_t dimensions() {
        return decay_traits<A>::dimensions();
    }
};

} //end of namespace etl
<|endoftext|>


<commit_before>/*

PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante

Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle

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

*/

#ifndef PIC_GL_FILTERING_FILTER_CHANNEL_HPP
#define PIC_GL_FILTERING_FILTER_CHANNEL_HPP

#include "../../base.hpp"

#include "../../gl/filtering/filter.hpp"

namespace pic {

/**
 * @brief The FilterGLChannel class
 */
class FilterGLChannel: public FilterGL
{
protected:
    /**
     * @brief initShaders
     */
    void initShaders();

    int channel;

public:

    /**
     * @brief FilterGLChannel
     * @param channel
     */
    FilterGLChannel(int channel);

    /**
     * @brief update
     * @param channel
     */
    void update(int channel);

    /**
     * @brief OutputSize
     * @param imgIn
     * @param width
     * @param height
     * @param channels
     * @param frames
     */
    void OutputSize(ImageGLVec imgIn, int &width, int &height, int &channels, int &frames)
    {
        width       = imgIn[0]->width;
        height      = imgIn[0]->height;
        channels    = 1;
        frames      = imgIn[0]->frames;
    }

    /**
     * @brief execute
     * @param imgIn
     * @param imgOut
     * @param channel
     * @return
     */
    static ImageGL *execute(ImageGL *imgIn, ImageGL *imgOut, int channel = 0)
    {
        FilterGLChannel flt(channel);
        return flt.Process(SingleGL(imgIn), imgOut);
    }

    /**
     * @brief Test
     */
    static void Test()
    {
        ImageGL imgIn(1, 512, 512, 3, IMG_GPU_CPU, GL_TEXTURE_2D);

        for(auto i = 0; i < imgIn.size(); i += 3) {
            imgIn.data[i    ] = 1.0f;
            imgIn.data[i + 1] = 0.5f;
            imgIn.data[i + 2] = 0.25f;
        }

        imgIn.generateTextureGL();

        FilterGLChannel filter(0);
        ImageGL *outR = filter.Process(SingleGL(&imgIn), NULL);

        filter.update(1);
        ImageGL *outG = filter.Process(SingleGL(&imgIn), NULL);

        filter.update(2);
        ImageGL *outB = filter.Process(SingleGL(&imgIn), NULL);

        outR->loadToMemory();
        outR->Write("channel_R.pfm");
        outG->loadToMemory();
        outG->Write("channel_G.pfm");
        outB->loadToMemory();
        outB->Write("channel_B.pfm");
    }
};

PIC_INLINE FilterGLChannel::FilterGLChannel(int channel) : FilterGL()
{
    initShaders();
    update(channel);
}

PIC_INLINE void FilterGLChannel::initShaders()
{
    fragment_source = MAKE_STRING
                      (
    uniform sampler2D u_tex; \n
    uniform int channel; \n
    out     vec4 f_color; \n
    \n
    void main(void) {
        \n
        ivec2 coords = ivec2(gl_FragCoord.xy); \n
        vec3 color = texelFetch(u_tex, coords, 0).xyz; \n
        float v = color[channel]; \n
        f_color = vec4(v, v, v, 1.0); \n

    }
                      );

    technique.initStandard("330", vertex_source, fragment_source, "FilterGLChannel");
}

PIC_INLINE void FilterGLChannel::update(int channel)
{
    this->channel = channel > -1 ? channel : 0;

    if(technique.isValid()) {
        technique.bind();
        technique.setUniform1i("u_tex", 0);
        technique.setUniform1i("channel", channel);
        technique.unbind();
    }
}

} // end namespace pic

#endif /* PIC_GL_FILTERING_FILTER_CHANNEL_HPP */

<commit_msg>Update filter_channel.hpp<commit_after>/*

PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante

Copyright (C) 2014
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
First author: Francesco Banterle

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

*/

#ifndef PIC_GL_FILTERING_FILTER_CHANNEL_HPP
#define PIC_GL_FILTERING_FILTER_CHANNEL_HPP

#include "../../base.hpp"
#include "../../util/math.hpp"
#include "../../gl/filtering/filter.hpp"

namespace pic {

/**
 * @brief The FilterGLChannel class
 */
class FilterGLChannel: public FilterGL
{
protected:
    /**
     * @brief initShaders
     */
    void initShaders()
    {
        fragment_source = MAKE_STRING
                          (
        uniform sampler2D u_tex; \n
        uniform int channel; \n
        out     vec4 f_color; \n
        \n
        void main(void) {
            \n
            ivec2 coords = ivec2(gl_FragCoord.xy); \n
            vec4 color = texelFetch(u_tex, coords, 0); \n
            float v = color[channel]; \n
            f_color = vec4(v, v, v, 1.0); \n

        }
                          );

        technique.initStandard("330", vertex_source, fragment_source, "FilterGLChannel");
    }

    int channel;

public:

    /**
     * @brief FilterGLChannel
     * @param channel
     */
    FilterGLChannel(int channel) : FilterGL()
    {
        initShaders();
        update(channel);
    }

    /**
     * @brief update
     * @param channel
     */
    void update(int channel)
    {
        this->channel = CLAMP(channel, 4);

        if(technique.isValid()) {
            technique.bind();
            technique.setUniform1i("u_tex", 0);
            technique.setUniform1i("channel", channel);
            technique.unbind();
        }
    }

    /**
     * @brief OutputSize
     * @param imgIn
     * @param width
     * @param height
     * @param channels
     * @param frames
     */
    void OutputSize(ImageGLVec imgIn, int &width, int &height, int &channels, int &frames)
    {
        width       = imgIn[0]->width;
        height      = imgIn[0]->height;
        channels    = 1;
        frames      = imgIn[0]->frames;
    }

    /**
     * @brief execute
     * @param imgIn
     * @param imgOut
     * @param channel
     * @return
     */
    static ImageGL *execute(ImageGL *imgIn, ImageGL *imgOut, int channel = 0)
    {
        FilterGLChannel flt(channel);
        return flt.Process(SingleGL(imgIn), imgOut);
    }

    /**
     * @brief Test
     */
    static void Test()
    {
        ImageGL imgIn(1, 512, 512, 3, IMG_GPU_CPU, GL_TEXTURE_2D);

        for(auto i = 0; i < imgIn.size(); i += 3) {
            imgIn.data[i    ] = 1.0f;
            imgIn.data[i + 1] = 0.5f;
            imgIn.data[i + 2] = 0.25f;
        }

        imgIn.generateTextureGL();

        FilterGLChannel filter(0);
        ImageGL *outR = filter.Process(SingleGL(&imgIn), NULL);

        filter.update(1);
        ImageGL *outG = filter.Process(SingleGL(&imgIn), NULL);

        filter.update(2);
        ImageGL *outB = filter.Process(SingleGL(&imgIn), NULL);

        outR->loadToMemory();
        outR->Write("channel_R.bmp");
        outG->loadToMemory();
        outG->Write("channel_G.bmp");
        outB->loadToMemory();
        outB->Write("channel_B.bmp");
    }
};

} // end namespace pic

#endif /* PIC_GL_FILTERING_FILTER_CHANNEL_HPP */

<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg
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 author 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.

*/

#ifndef TORRENT_SESSION_SETTINGS_HPP_INCLUDED
#define TORRENT_SESSION_SETTINGS_HPP_INCLUDED

#include "libtorrent/version.hpp"
#include "libtorrent/config.hpp"

namespace libtorrent
{

	struct TORRENT_EXPORT proxy_settings
	{
		proxy_settings() : port(0), type(none) {}

		std::string hostname;
		int port;

		std::string username;
		std::string password;

		enum proxy_type
		{
			// a plain tcp socket is used, and
			// the other settings are ignored.
			none,
			// socks4 server, requires username.
			socks4,
			// the hostname and port settings are
			// used to connect to the proxy. No
			// username or password is sent.
			socks5,
			// the hostname and port are used to
			// connect to the proxy. the username
			// and password are used to authenticate
			// with the proxy server.
			socks5_pw,
			// the http proxy is only available for
			// tracker and web seed traffic
			// assumes anonymous access to proxy
			http,
			// http proxy with basic authentication
			// uses username and password
			http_pw
		};

		proxy_type type;

	};

	struct TORRENT_EXPORT session_settings
	{
		session_settings(std::string const& user_agent_ = "libtorrent/"
			LIBTORRENT_VERSION)
			: user_agent(user_agent_)
			, tracker_completion_timeout(60)
			, tracker_receive_timeout(20)
			, stop_tracker_timeout(5)
			, tracker_maximum_response_length(1024*1024)
			, piece_timeout(10)
			, request_queue_time(3.f)
			, max_allowed_in_request_queue(250)
			, max_out_request_queue(200)
			, whole_pieces_threshold(20)
			, peer_timeout(120)
			, urlseed_timeout(20)
			, urlseed_pipeline_size(5)
			, urlseed_wait_retry(30)
			, file_pool_size(40)
			, allow_multiple_connections_per_ip(false)
			, max_failcount(3)
			, min_reconnect_time(60)
			, peer_connect_timeout(7)
			, ignore_limits_on_local_network(true)
			, connection_speed(20)
			, send_redundant_have(false)
			, lazy_bitfields(true)
			, inactivity_timeout(600)
			, unchoke_interval(15)
			, optimistic_unchoke_multiplier(4)
			, num_want(200)
			, initial_picker_threshold(4)
			, allowed_fast_set_size(10)
			, max_outstanding_disk_bytes_per_connection(64 * 1024)
			, handshake_timeout(10)
#ifndef TORRENT_DISABLE_DHT
			, use_dht_as_fallback(true)
#endif
			, free_torrent_hashes(true)
		{}

		// this is the user agent that will be sent to the tracker
		// when doing requests. It is used to identify the client.
		// It cannot contain \r or \n
		std::string user_agent;

		// the number of seconds to wait until giving up on a
		// tracker request if it hasn't finished
		int tracker_completion_timeout;

		// the number of seconds where no data is received
		// from the tracker until it should be considered
		// as timed out
		int tracker_receive_timeout;

		// the time to wait when sending a stopped message
		// before considering a tracker to have timed out.
		// this is usually shorter, to make the client quit
		// faster
		int stop_tracker_timeout;

		// if the content-length is greater than this value
		// the tracker connection will be aborted
		int tracker_maximum_response_length;

		// the number of seconds from a request is sent until
		// it times out if no piece response is returned.
		int piece_timeout;

		// the length of the request queue given in the number
		// of seconds it should take for the other end to send
		// all the pieces. i.e. the actual number of requests
		// depends on the download rate and this number.
		float request_queue_time;

		// the number of outstanding block requests a peer is
		// allowed to queue up in the client. If a peer sends
		// more requests than this (before the first one has
		// been sent) the last request will be dropped.
		// the higher this is, the faster upload speeds the
		// client can get to a single peer.
		int max_allowed_in_request_queue;

		// the maximum number of outstanding requests to
		// send to a peer. This limit takes precedence over
		// request_queue_time.
		int max_out_request_queue;

		// if a whole piece can be downloaded in this number
		// of seconds, or less, the peer_connection will prefer
		// to request whole pieces at a time from this peer.
		// The benefit of this is to better utilize disk caches by
		// doing localized accesses and also to make it easier
		// to identify bad peers if a piece fails the hash check.
		int whole_pieces_threshold;

		// the number of seconds to wait for any activity on
		// the peer wire before closing the connectiong due
		// to time out.
		int peer_timeout;

		// same as peer_timeout, but only applies to url-seeds.
		// this is usually set lower, because web servers are
		// expected to be more reliable.
		int urlseed_timeout;

		// controls the pipelining size of url-seeds
		int urlseed_pipeline_size;

		// time to wait until a new retry takes place
		int urlseed_wait_retry;

		// sets the upper limit on the total number of files this
		// session will keep open. The reason why files are
		// left open at all is that some anti virus software
		// hooks on every file close, and scans the file for
		// viruses. deferring the closing of the files will
		// be the difference between a usable system and
		// a completely hogged down system. Most operating
		// systems also has a limit on the total number of
		// file descriptors a process may have open. It is
		// usually a good idea to find this limit and set the
		// number of connections and the number of files
		// limits so their sum is slightly below it.
		int file_pool_size;

		// false to not allow multiple connections from the same
		// IP address. true will allow it.
		bool allow_multiple_connections_per_ip;

		// the number of times we can fail to connect to a peer
		// before we stop retrying it.
		int max_failcount;

		// the number of seconds to wait to reconnect to a peer.
		// this time is multiplied with the failcount.
		int min_reconnect_time;

		// this is the timeout for a connection attempt. If
		// the connect does not succeed within this time, the
		// connection is dropped. The time is specified in seconds.
		int peer_connect_timeout;

		// if set to true, upload, download and unchoke limits
		// are ignored for peers on the local network.
		bool ignore_limits_on_local_network;

		// the number of connection attempts that
		// are made per second.
		int connection_speed;

		// if this is set to true, have messages will be sent
		// to peers that already have the piece. This is
		// typically not necessary, but it might be necessary
		// for collecting statistics in some cases. Default is false.
		bool send_redundant_have;

		// if this is true, outgoing bitfields will never be fuil. If the
		// client is seed, a few bits will be set to 0, and later filled
		// in with have messages. This is to prevent certain ISPs
		// from stopping people from seeding.
		bool lazy_bitfields;

		// if a peer is uninteresting and uninterested for longer
		// than this number of seconds, it will be disconnected.
		// default is 10 minutes
		int inactivity_timeout;

		// the number of seconds between chokes/unchokes
		int unchoke_interval;

		// the number of unchoke intervals between
		// optimistic unchokes
		int optimistic_unchoke_multiplier;

		// if this is set, this IP will be reported do the
		// tracker in the ip= parameter.
		address announce_ip;

		// the num want sent to trackers
		int num_want;

		// while we have fewer pieces than this, pick
		// random pieces instead of rarest first.
		int initial_picker_threshold;

		// the number of allowed pieces to send to peers
		// that supports the fast extensions
		int allowed_fast_set_size;

		// the maximum number of bytes a connection may have
		// pending in the disk write queue before its download
		// rate is being throttled. This prevents fast downloads
		// to slow medias to allocate more and more memory
		// indefinitely. This should be set to at least 32 kB
		// to not completely disrupt normal downloads.
		int max_outstanding_disk_bytes_per_connection;

		// the number of seconds to wait for a handshake
		// response from a peer. If no response is received
		// within this time, the peer is disconnected.
		int handshake_timeout;

#ifndef TORRENT_DISABLE_DHT
		// while this is true, the dht will note be used unless the
		// tracker is online
		bool use_dht_as_fallback;
#endif

		// if this is true, the piece hashes will be freed, in order
		// to save memory, once the torrent is seeding. This will
		// make the get_torrent_info() function to return an incomplete
		// torrent object that cannot be passed back to add_torrent()
		bool free_torrent_hashes;
	};

#ifndef TORRENT_DISABLE_DHT
	struct dht_settings
	{
		dht_settings()
			: max_peers_reply(50)
			, search_branching(5)
			, service_port(0)
			, max_fail_count(20)
		{}

		// the maximum number of peers to send in a
		// reply to get_peers
		int max_peers_reply;

		// the number of simultanous "connections" when
		// searching the DHT.
		int search_branching;

		// the listen port for the dht. This is a UDP port.
		// zero means use the same as the tcp interface
		int service_port;

		// the maximum number of times a node can fail
		// in a row before it is removed from the table.
		int max_fail_count;
	};
#endif

#ifndef TORRENT_DISABLE_ENCRYPTION

	struct pe_settings
	{
		pe_settings()
			: out_enc_policy(enabled)
			, in_enc_policy(enabled)
			, allowed_enc_level(both)
			, prefer_rc4(false)
		{}

		enum enc_policy
		{
			forced,  // disallow non encrypted connections
			enabled, // allow encrypted and non encrypted connections
			disabled // disallow encrypted connections
		};

		enum enc_level
		{
			plaintext, // use only plaintext encryption
			rc4, // use only rc4 encryption
			both // allow both
		};

		enc_policy out_enc_policy;
		enc_policy in_enc_policy;

		enc_level allowed_enc_level;
		// if the allowed encryption level is both, setting this to
		// true will prefer rc4 if both methods are offered, plaintext
		// otherwise
		bool prefer_rc4;
	};
#endif

}

#endif
<commit_msg>increased default tracker timeout from 20 seconds to 40 seconds<commit_after>/*

Copyright (c) 2003, Arvid Norberg
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 author 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.

*/

#ifndef TORRENT_SESSION_SETTINGS_HPP_INCLUDED
#define TORRENT_SESSION_SETTINGS_HPP_INCLUDED

#include "libtorrent/version.hpp"
#include "libtorrent/config.hpp"

namespace libtorrent
{

	struct TORRENT_EXPORT proxy_settings
	{
		proxy_settings() : port(0), type(none) {}

		std::string hostname;
		int port;

		std::string username;
		std::string password;

		enum proxy_type
		{
			// a plain tcp socket is used, and
			// the other settings are ignored.
			none,
			// socks4 server, requires username.
			socks4,
			// the hostname and port settings are
			// used to connect to the proxy. No
			// username or password is sent.
			socks5,
			// the hostname and port are used to
			// connect to the proxy. the username
			// and password are used to authenticate
			// with the proxy server.
			socks5_pw,
			// the http proxy is only available for
			// tracker and web seed traffic
			// assumes anonymous access to proxy
			http,
			// http proxy with basic authentication
			// uses username and password
			http_pw
		};

		proxy_type type;

	};

	struct TORRENT_EXPORT session_settings
	{
		session_settings(std::string const& user_agent_ = "libtorrent/"
			LIBTORRENT_VERSION)
			: user_agent(user_agent_)
			, tracker_completion_timeout(60)
			, tracker_receive_timeout(40)
			, stop_tracker_timeout(5)
			, tracker_maximum_response_length(1024*1024)
			, piece_timeout(10)
			, request_queue_time(3.f)
			, max_allowed_in_request_queue(250)
			, max_out_request_queue(200)
			, whole_pieces_threshold(20)
			, peer_timeout(120)
			, urlseed_timeout(20)
			, urlseed_pipeline_size(5)
			, urlseed_wait_retry(30)
			, file_pool_size(40)
			, allow_multiple_connections_per_ip(false)
			, max_failcount(3)
			, min_reconnect_time(60)
			, peer_connect_timeout(7)
			, ignore_limits_on_local_network(true)
			, connection_speed(20)
			, send_redundant_have(false)
			, lazy_bitfields(true)
			, inactivity_timeout(600)
			, unchoke_interval(15)
			, optimistic_unchoke_multiplier(4)
			, num_want(200)
			, initial_picker_threshold(4)
			, allowed_fast_set_size(10)
			, max_outstanding_disk_bytes_per_connection(64 * 1024)
			, handshake_timeout(10)
#ifndef TORRENT_DISABLE_DHT
			, use_dht_as_fallback(true)
#endif
			, free_torrent_hashes(true)
		{}

		// this is the user agent that will be sent to the tracker
		// when doing requests. It is used to identify the client.
		// It cannot contain \r or \n
		std::string user_agent;

		// the number of seconds to wait until giving up on a
		// tracker request if it hasn't finished
		int tracker_completion_timeout;

		// the number of seconds where no data is received
		// from the tracker until it should be considered
		// as timed out
		int tracker_receive_timeout;

		// the time to wait when sending a stopped message
		// before considering a tracker to have timed out.
		// this is usually shorter, to make the client quit
		// faster
		int stop_tracker_timeout;

		// if the content-length is greater than this value
		// the tracker connection will be aborted
		int tracker_maximum_response_length;

		// the number of seconds from a request is sent until
		// it times out if no piece response is returned.
		int piece_timeout;

		// the length of the request queue given in the number
		// of seconds it should take for the other end to send
		// all the pieces. i.e. the actual number of requests
		// depends on the download rate and this number.
		float request_queue_time;

		// the number of outstanding block requests a peer is
		// allowed to queue up in the client. If a peer sends
		// more requests than this (before the first one has
		// been sent) the last request will be dropped.
		// the higher this is, the faster upload speeds the
		// client can get to a single peer.
		int max_allowed_in_request_queue;

		// the maximum number of outstanding requests to
		// send to a peer. This limit takes precedence over
		// request_queue_time.
		int max_out_request_queue;

		// if a whole piece can be downloaded in this number
		// of seconds, or less, the peer_connection will prefer
		// to request whole pieces at a time from this peer.
		// The benefit of this is to better utilize disk caches by
		// doing localized accesses and also to make it easier
		// to identify bad peers if a piece fails the hash check.
		int whole_pieces_threshold;

		// the number of seconds to wait for any activity on
		// the peer wire before closing the connectiong due
		// to time out.
		int peer_timeout;

		// same as peer_timeout, but only applies to url-seeds.
		// this is usually set lower, because web servers are
		// expected to be more reliable.
		int urlseed_timeout;

		// controls the pipelining size of url-seeds
		int urlseed_pipeline_size;

		// time to wait until a new retry takes place
		int urlseed_wait_retry;

		// sets the upper limit on the total number of files this
		// session will keep open. The reason why files are
		// left open at all is that some anti virus software
		// hooks on every file close, and scans the file for
		// viruses. deferring the closing of the files will
		// be the difference between a usable system and
		// a completely hogged down system. Most operating
		// systems also has a limit on the total number of
		// file descriptors a process may have open. It is
		// usually a good idea to find this limit and set the
		// number of connections and the number of files
		// limits so their sum is slightly below it.
		int file_pool_size;

		// false to not allow multiple connections from the same
		// IP address. true will allow it.
		bool allow_multiple_connections_per_ip;

		// the number of times we can fail to connect to a peer
		// before we stop retrying it.
		int max_failcount;

		// the number of seconds to wait to reconnect to a peer.
		// this time is multiplied with the failcount.
		int min_reconnect_time;

		// this is the timeout for a connection attempt. If
		// the connect does not succeed within this time, the
		// connection is dropped. The time is specified in seconds.
		int peer_connect_timeout;

		// if set to true, upload, download and unchoke limits
		// are ignored for peers on the local network.
		bool ignore_limits_on_local_network;

		// the number of connection attempts that
		// are made per second.
		int connection_speed;

		// if this is set to true, have messages will be sent
		// to peers that already have the piece. This is
		// typically not necessary, but it might be necessary
		// for collecting statistics in some cases. Default is false.
		bool send_redundant_have;

		// if this is true, outgoing bitfields will never be fuil. If the
		// client is seed, a few bits will be set to 0, and later filled
		// in with have messages. This is to prevent certain ISPs
		// from stopping people from seeding.
		bool lazy_bitfields;

		// if a peer is uninteresting and uninterested for longer
		// than this number of seconds, it will be disconnected.
		// default is 10 minutes
		int inactivity_timeout;

		// the number of seconds between chokes/unchokes
		int unchoke_interval;

		// the number of unchoke intervals between
		// optimistic unchokes
		int optimistic_unchoke_multiplier;

		// if this is set, this IP will be reported do the
		// tracker in the ip= parameter.
		address announce_ip;

		// the num want sent to trackers
		int num_want;

		// while we have fewer pieces than this, pick
		// random pieces instead of rarest first.
		int initial_picker_threshold;

		// the number of allowed pieces to send to peers
		// that supports the fast extensions
		int allowed_fast_set_size;

		// the maximum number of bytes a connection may have
		// pending in the disk write queue before its download
		// rate is being throttled. This prevents fast downloads
		// to slow medias to allocate more and more memory
		// indefinitely. This should be set to at least 32 kB
		// to not completely disrupt normal downloads.
		int max_outstanding_disk_bytes_per_connection;

		// the number of seconds to wait for a handshake
		// response from a peer. If no response is received
		// within this time, the peer is disconnected.
		int handshake_timeout;

#ifndef TORRENT_DISABLE_DHT
		// while this is true, the dht will note be used unless the
		// tracker is online
		bool use_dht_as_fallback;
#endif

		// if this is true, the piece hashes will be freed, in order
		// to save memory, once the torrent is seeding. This will
		// make the get_torrent_info() function to return an incomplete
		// torrent object that cannot be passed back to add_torrent()
		bool free_torrent_hashes;
	};

#ifndef TORRENT_DISABLE_DHT
	struct dht_settings
	{
		dht_settings()
			: max_peers_reply(50)
			, search_branching(5)
			, service_port(0)
			, max_fail_count(20)
		{}

		// the maximum number of peers to send in a
		// reply to get_peers
		int max_peers_reply;

		// the number of simultanous "connections" when
		// searching the DHT.
		int search_branching;

		// the listen port for the dht. This is a UDP port.
		// zero means use the same as the tcp interface
		int service_port;

		// the maximum number of times a node can fail
		// in a row before it is removed from the table.
		int max_fail_count;
	};
#endif

#ifndef TORRENT_DISABLE_ENCRYPTION

	struct pe_settings
	{
		pe_settings()
			: out_enc_policy(enabled)
			, in_enc_policy(enabled)
			, allowed_enc_level(both)
			, prefer_rc4(false)
		{}

		enum enc_policy
		{
			forced,  // disallow non encrypted connections
			enabled, // allow encrypted and non encrypted connections
			disabled // disallow encrypted connections
		};

		enum enc_level
		{
			plaintext, // use only plaintext encryption
			rc4, // use only rc4 encryption
			both // allow both
		};

		enc_policy out_enc_policy;
		enc_policy in_enc_policy;

		enc_level allowed_enc_level;
		// if the allowed encryption level is both, setting this to
		// true will prefer rc4 if both methods are offered, plaintext
		// otherwise
		bool prefer_rc4;
	};
#endif

}

#endif
<|endoftext|>


<commit_before>#include <gsl/gsl_vector.h>
#include <gsl/gsl_multimin.h>
#include "counts.h"
#include "backward.h"
#include "util.h"

#define LagrangeMultiplierPrefix "LagrangeMultiplier"

MachineCounts::MachineCounts (const EvaluatedMachine& machine, const SeqPair& seqPair) :
  count (machine.nStates())
{
  for (StateIndex s = 0; s < machine.nStates(); ++s)
    count[s].resize (machine.state[s].nTransitions);

  const ForwardMatrix forward (machine, seqPair);
  const BackwardMatrix backward (machine, seqPair);

  backward.getCounts (forward, *this);
}

MachineCounts& MachineCounts::operator+= (const MachineCounts& counts) {
  for (StateIndex s = 0; s < count.size(); ++s)
    for (size_t t = 0; t < count[s].size(); ++t)
      count[s][t] += counts.count[s][t];
  return *this;
}

void MachineCounts::writeJson (ostream& outs) const {
  vguard<string> s;
  for (const auto& c: count)
    s.push_back (string("[") + to_string_join (c, ",") + "]");
  outs << "[" << join (s, ",\n ") << "]" << endl;
}

MachineLagrangian::MachineLagrangian (const Machine& machine, const MachineCounts& counts, const Constraints& constraints) {

  for (StateIndex s = 0; s < machine.state.size(); ++s) {
    EvaluatedMachineState::TransIndex t = 0;
    for (TransList::const_iterator iter = machine.state[s].trans.begin();
	 iter != machine.state[s].trans.end(); ++iter, ++t)
      lagrangian = WeightAlgebra::add (lagrangian,
				       WeightAlgebra::multiply (counts.count[s][t],
								WeightAlgebra::logOf ((*iter).weight)));
  }

  const auto p = WeightAlgebra::params (lagrangian);
  param.insert (param.end(), p.begin(), p.end());

  int lm = 0;
  for (const auto& c: constraints.norm) {
    string lambda;
    do
      lambda = string(LagrangeMultiplierPrefix) + to_string(lm++);
    while (p.count(lambda));
    lagrangeMultiplier.push_back (lambda);

    TransWeight cSum;
    for (const auto& cParam: c)
      cSum = WeightAlgebra::add (cSum, cParam);
    lagrangian = WeightAlgebra::add (lagrangian,
				     WeightAlgebra::multiply (lambda,
							      WeightAlgebra::subtract (true, cSum)));
  }

  paramDeriv.reserve (param.size());
  multiplierDeriv.reserve (lagrangeMultiplier.size());
  for (const auto& p: param)
    paramDeriv.push_back (WeightAlgebra::deriv (lagrangian, p));
  for (const auto& lambda: lagrangeMultiplier)
    multiplierDeriv.push_back (WeightAlgebra::deriv (lagrangian, lambda));
}

Params gsl_vector_to_params (const gsl_vector *v, const MachineLagrangian& ml) {
  Params p;

  // acidbot_param_n = exp (gsl_param_n)
  for (size_t n = 0; n < ml.param.size(); ++n)
    p.param[ml.param[n]] = exp (gsl_vector_get (v, n));

  for (size_t n = 0; n < ml.lagrangeMultiplier.size(); ++n)
    p.param[ml.param[n]] = gsl_vector_get (v, n + ml.param.size());

  return p;
}

double gsl_machine_lagrangian (const gsl_vector *v, void *voidML)
{
  const MachineLagrangian& ml (*((MachineLagrangian*)voidML));
  const Params pv = gsl_vector_to_params (v, ml);
  return WeightAlgebra::eval (ml.lagrangian, pv);
}

void gsl_machine_lagrangian_deriv (const gsl_vector *v, void *voidML, gsl_vector *df)
{
  const MachineLagrangian& ml (*((MachineLagrangian*)voidML));
  const Params pv = gsl_vector_to_params (v, ml);

  // acidbot_param_n = exp (gsl_param_n)
  // so d(lagrangian)/d(gsl_param_n) = d(lagrangian)/d(acidbot_param_n) * acidbot_param_n
  for (size_t n = 0; n < ml.param.size(); ++n)
    gsl_vector_set (df, n, WeightAlgebra::eval (ml.paramDeriv[n], pv) * pv.param.at (ml.param[n]));

  for (size_t n = 0; n < ml.lagrangeMultiplier.size(); ++n)
    gsl_vector_set (df, n + ml.param.size(), WeightAlgebra::eval (ml.multiplierDeriv[n], pv));
}

void gsl_machine_lagrangian_with_deriv (const gsl_vector *x, void *voidML, double *f, gsl_vector *df)
{
  *f = gsl_machine_lagrangian (x, voidML);
  gsl_machine_lagrangian_deriv (x, voidML, df);
}

#define StepSize 0.01
#define LineSearchTolerance 1e-4
#define EpsilonAbsolute 1e-3
#define MaxIterations 100
Params MachineLagrangian::optimize (const Params& seed) const {
  gsl_vector *v;
  gsl_multimin_function_fdf func;
  func.n = param.size() + lagrangeMultiplier.size();
  func.f = gsl_machine_lagrangian;
  func.df = gsl_machine_lagrangian_deriv;
  func.fdf = gsl_machine_lagrangian_with_deriv;
  func.params = (void*) this;

  gsl_vector* x = gsl_vector_alloc (func.n);
  for (size_t n = 0; n < param.size(); ++n)
    gsl_vector_set (x, n, log (seed.param.at (param[n])));

  for (size_t n = 0; n < lagrangeMultiplier.size(); ++n)
    gsl_vector_set (x, n + param.size(), 0.);

  const gsl_multimin_fdfminimizer_type *T = gsl_multimin_fdfminimizer_vector_bfgs2;
  gsl_multimin_fdfminimizer *s = gsl_multimin_fdfminimizer_alloc (T, func.n);

  gsl_multimin_fdfminimizer_set (s, &func, x, StepSize, LineSearchTolerance);

  size_t iter = 0;
  int status;
  do
    {
      iter++;
      status = gsl_multimin_fdfminimizer_iterate (s);

      if (status)
        break;

      status = gsl_multimin_test_gradient (s->gradient, EpsilonAbsolute);
    }
  while (status == GSL_CONTINUE && iter < MaxIterations);

  const Params finalParams = gsl_vector_to_params (x, *this);

  gsl_multimin_fdfminimizer_free (s);
  gsl_vector_free (x);

  return finalParams;
}
<commit_msg>comment<commit_after>#include <gsl/gsl_vector.h>
#include <gsl/gsl_multimin.h>
#include "counts.h"
#include "backward.h"
#include "util.h"

#define LagrangeMultiplierPrefix "LagrangeMultiplier"

MachineCounts::MachineCounts (const EvaluatedMachine& machine, const SeqPair& seqPair) :
  count (machine.nStates())
{
  for (StateIndex s = 0; s < machine.nStates(); ++s)
    count[s].resize (machine.state[s].nTransitions);

  const ForwardMatrix forward (machine, seqPair);
  const BackwardMatrix backward (machine, seqPair);

  backward.getCounts (forward, *this);
}

MachineCounts& MachineCounts::operator+= (const MachineCounts& counts) {
  for (StateIndex s = 0; s < count.size(); ++s)
    for (size_t t = 0; t < count[s].size(); ++t)
      count[s][t] += counts.count[s][t];
  return *this;
}

void MachineCounts::writeJson (ostream& outs) const {
  vguard<string> s;
  for (const auto& c: count)
    s.push_back (string("[") + to_string_join (c, ",") + "]");
  outs << "[" << join (s, ",\n ") << "]" << endl;
}

MachineLagrangian::MachineLagrangian (const Machine& machine, const MachineCounts& counts, const Constraints& constraints) {

  for (StateIndex s = 0; s < machine.state.size(); ++s) {
    EvaluatedMachineState::TransIndex t = 0;
    for (TransList::const_iterator iter = machine.state[s].trans.begin();
	 iter != machine.state[s].trans.end(); ++iter, ++t)
      lagrangian = WeightAlgebra::add (lagrangian,
				       WeightAlgebra::multiply (counts.count[s][t],
								WeightAlgebra::logOf ((*iter).weight)));
  }

  const auto p = WeightAlgebra::params (lagrangian);
  param.insert (param.end(), p.begin(), p.end());

  int lm = 0;
  for (const auto& c: constraints.norm) {
    string lambda;
    do
      lambda = string(LagrangeMultiplierPrefix) + to_string(lm++);
    while (p.count(lambda));
    lagrangeMultiplier.push_back (lambda);

    TransWeight cSum;
    for (const auto& cParam: c)
      cSum = WeightAlgebra::add (cSum, cParam);
    lagrangian = WeightAlgebra::add (lagrangian,
				     WeightAlgebra::multiply (lambda,
							      WeightAlgebra::subtract (true, cSum)));
  }

  paramDeriv.reserve (param.size());
  multiplierDeriv.reserve (lagrangeMultiplier.size());
  for (const auto& p: param)
    paramDeriv.push_back (WeightAlgebra::deriv (lagrangian, p));
  for (const auto& lambda: lagrangeMultiplier)
    multiplierDeriv.push_back (WeightAlgebra::deriv (lagrangian, lambda));
}

Params gsl_vector_to_params (const gsl_vector *v, const MachineLagrangian& ml) {
  Params p;

  // acidbot_param_n = exp (gsl_param_n)
  for (size_t n = 0; n < ml.param.size(); ++n)
    p.param[ml.param[n]] = exp (gsl_vector_get (v, n));

  for (size_t n = 0; n < ml.lagrangeMultiplier.size(); ++n)
    p.param[ml.param[n]] = gsl_vector_get (v, n + ml.param.size());

  return p;
}

double gsl_machine_lagrangian (const gsl_vector *v, void *voidML)
{
  const MachineLagrangian& ml (*((MachineLagrangian*)voidML));
  const Params pv = gsl_vector_to_params (v, ml);
  return WeightAlgebra::eval (ml.lagrangian, pv);
}

void gsl_machine_lagrangian_deriv (const gsl_vector *v, void *voidML, gsl_vector *df)
{
  const MachineLagrangian& ml (*((MachineLagrangian*)voidML));
  const Params pv = gsl_vector_to_params (v, ml);

  // acidbot_param_n = exp (gsl_param_n)
  // so d(lagrangian)/d(gsl_param_n) = d(lagrangian)/d(acidbot_param_n) * acidbot_param_n
  for (size_t n = 0; n < ml.param.size(); ++n)
    gsl_vector_set (df, n, WeightAlgebra::eval (ml.paramDeriv[n], pv) * pv.param.at (ml.param[n]));

  for (size_t n = 0; n < ml.lagrangeMultiplier.size(); ++n)
    gsl_vector_set (df, n + ml.param.size(), WeightAlgebra::eval (ml.multiplierDeriv[n], pv));
}

void gsl_machine_lagrangian_with_deriv (const gsl_vector *x, void *voidML, double *f, gsl_vector *df)
{
  *f = gsl_machine_lagrangian (x, voidML);
  gsl_machine_lagrangian_deriv (x, voidML, df);
}

#define StepSize 0.01
#define LineSearchTolerance 1e-4
#define EpsilonAbsolute 1e-3
#define MaxIterations 100
Params MachineLagrangian::optimize (const Params& seed) const {
  gsl_vector *v;
  gsl_multimin_function_fdf func;
  func.n = param.size() + lagrangeMultiplier.size();
  func.f = gsl_machine_lagrangian;
  func.df = gsl_machine_lagrangian_deriv;
  func.fdf = gsl_machine_lagrangian_with_deriv;
  func.params = (void*) this;

  gsl_vector* x = gsl_vector_alloc (func.n);
  // acidbot_param_n = exp (gsl_param_n)
  // so gsl_param_n = log (acidbot_param_n)
  for (size_t n = 0; n < param.size(); ++n)
    gsl_vector_set (x, n, log (seed.param.at (param[n])));

  for (size_t n = 0; n < lagrangeMultiplier.size(); ++n)
    gsl_vector_set (x, n + param.size(), 0.);

  const gsl_multimin_fdfminimizer_type *T = gsl_multimin_fdfminimizer_vector_bfgs2;
  gsl_multimin_fdfminimizer *s = gsl_multimin_fdfminimizer_alloc (T, func.n);

  gsl_multimin_fdfminimizer_set (s, &func, x, StepSize, LineSearchTolerance);

  size_t iter = 0;
  int status;
  do
    {
      iter++;
      status = gsl_multimin_fdfminimizer_iterate (s);

      if (status)
        break;

      status = gsl_multimin_test_gradient (s->gradient, EpsilonAbsolute);
    }
  while (status == GSL_CONTINUE && iter < MaxIterations);

  const Params finalParams = gsl_vector_to_params (x, *this);

  gsl_multimin_fdfminimizer_free (s);
  gsl_vector_free (x);

  return finalParams;
}
<|endoftext|>


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

#ifndef DUNE_GDT_ASSEMBLER_SYSTEM_HH
#define DUNE_GDT_ASSEMBLER_SYSTEM_HH

#include <type_traits>
#include <memory>

#include <dune/common/version.hh>

#include <dune/stuff/grid/walker.hh>
#include <dune/stuff/common/parallel/helper.hh>

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/constraints.hh>

#include "local/codim0.hh"
#include "local/codim1.hh"
#include "wrapper.hh"

namespace Dune {
namespace GDT {

template< class TestSpaceImp,
          class GridViewImp = typename TestSpaceImp::GridViewType,
          class AnsatzSpaceImp = TestSpaceImp >
class SystemAssembler
  : public DSG::Walker< GridViewImp >
{
  static_assert(std::is_base_of< SpaceInterface< typename TestSpaceImp::Traits >, TestSpaceImp >::value,
                "TestSpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of< SpaceInterface< typename AnsatzSpaceImp::Traits >, AnsatzSpaceImp >::value,
                "AnsatzSpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_same< typename TestSpaceImp::RangeFieldType, typename AnsatzSpaceImp::RangeFieldType >::value,
                "Types do not match!");
  typedef DSG::Walker< GridViewImp >                                  BaseType;
  typedef SystemAssembler<TestSpaceImp, GridViewImp, AnsatzSpaceImp > ThisType;
public:
  typedef TestSpaceImp                           TestSpaceType;
  typedef AnsatzSpaceImp                         AnsatzSpaceType;
  typedef typename TestSpaceType::RangeFieldType RangeFieldType;

  typedef typename BaseType::GridViewType     GridViewType;
  typedef typename BaseType::EntityType       EntityType;
  typedef typename BaseType::IntersectionType IntersectionType;

  typedef DSG::ApplyOn::WhichEntity< GridViewType >       ApplyOnWhichEntity;
  typedef DSG::ApplyOn::WhichIntersection< GridViewType > ApplyOnWhichIntersection;

  SystemAssembler(TestSpaceType test, AnsatzSpaceType ansatz, GridViewType grid_view)
    : BaseType(grid_view)
    , test_space_(test)
    , ansatz_space_(ansatz)
  {}

  SystemAssembler(TestSpaceType test, AnsatzSpaceType ansatz)
    : BaseType(test.grid_view())
    , test_space_(test)
    , ansatz_space_(ansatz)
  {}

  explicit SystemAssembler(TestSpaceType test)
    : BaseType(test.grid_view())
    , test_space_(test)
    , ansatz_space_(test)
  {}

  SystemAssembler(TestSpaceType test, GridViewType grid_view_in)
    : BaseType(grid_view_in)
    , test_space_(test)
    , ansatz_space_(test)
  {}

  const TestSpaceType& test_space() const
  {
    return *test_space_;
  }

  const AnsatzSpaceType& ansatz_space() const
  {
    return *ansatz_space_;
  }

  using BaseType::add;

  template< class C, class M >
  void add(Spaces::ConstraintsInterface< C, RangeFieldType >& constraints,
           Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
           const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    assert(matrix.rows() == test_space_->mapper().size());
    assert(matrix.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalMatrixConstraintsWrapper< TestSpaceType,
                                                     AnsatzSpaceType,
                                                     GridViewType,
                                                     typename C::derived_type,
                                                     typename M::derived_type > WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_,
                                                        ansatz_space_,
                                                        where,
                                                        constraints.as_imp(),
                                                        matrix.as_imp()));
  } // ... add(...)

  /** \todo Investigate why the ConstraintsInterface is not used here! */
  template< class ConstraintsType, class V >
  void add(ConstraintsType& constraints,
           Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
           const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = vector.as_imp();
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalVectorConstraintsWrapper< ThisType, ConstraintsType, VectorType > WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, constraints, vector_imp));
  } // ... add(...)

  template< class L, class M >
  void add(const LocalAssembler::Codim0Matrix< L >& local_assembler,
           Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
           const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalVolumeMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim0Matrix< L >, MatrixType >
        WrapperType;
    this->codim0_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class Codim0Assembler, class M >
  void add_codim0_assembler(const Codim0Assembler& local_assembler,
                            Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
                            const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalVolumeMatrixAssemblerWrapper< ThisType, Codim0Assembler, MatrixType > WrapperType;
    this->codim0_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class Codim0Assembler, class V >
  void add_codim0_assembler(const Codim0Assembler& local_assembler,
                            Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
                            const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = vector.as_imp();
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalVolumeVectorAssemblerWrapper< ThisType, Codim0Assembler, VectorType > WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
  } // ... add(...)

  template< class L, class M >
  void add(const LocalAssembler::Codim1CouplingMatrix< L >& local_assembler,
           Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
           const ApplyOnWhichIntersection* where
              = new DSG::ApplyOn::AllIntersections< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalFaceMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim1CouplingMatrix< L >, MatrixType >
        WrapperType;
    this->codim1_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class L, class M >
  void add(const LocalAssembler::Codim1BoundaryMatrix< L >& local_assembler,
           Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
           const ApplyOnWhichIntersection* where
              = new DSG::ApplyOn::AllIntersections< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalFaceMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim1BoundaryMatrix< L >, MatrixType >
        WrapperType;
    this->codim1_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class L, class V >
  void add(const LocalAssembler::Codim0Vector< L >& local_assembler,
           Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
           const ApplyOnWhichEntity* where
              = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = vector.as_imp();
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalVolumeVectorAssemblerWrapper< ThisType, LocalAssembler::Codim0Vector< L >, VectorType >
        WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
  } // ... add(...)

  template< class L, class V >
  void add(const LocalAssembler::Codim1Vector< L >& local_assembler,
           Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
           const ApplyOnWhichIntersection* where
              = new DSG::ApplyOn::AllIntersections< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = static_cast< VectorType& >(vector);
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalFaceVectorAssemblerWrapper< ThisType, LocalAssembler::Codim1Vector< L >, VectorType >
        WrapperType;
    this->codim1_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
  } // ... add(...)

  void assemble(const bool use_tbb = false)
  {
    this->walk(use_tbb);
  }

private:
  const DS::PerThreadValue<const TestSpaceType> test_space_;
  const DS::PerThreadValue<const AnsatzSpaceType> ansatz_space_;
}; // class SystemAssembler

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_ASSEMBLER_SYSTEM_HH
<commit_msg>[system.assembler] allow passing custom Partitioning to assemble()<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_ASSEMBLER_SYSTEM_HH
#define DUNE_GDT_ASSEMBLER_SYSTEM_HH

#include <type_traits>
#include <memory>

#include <dune/common/version.hh>

#include <dune/stuff/grid/walker.hh>
#include <dune/stuff/common/parallel/helper.hh>

#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/constraints.hh>

#include "local/codim0.hh"
#include "local/codim1.hh"
#include "wrapper.hh"

namespace Dune {
namespace GDT {

template< class TestSpaceImp,
          class GridViewImp = typename TestSpaceImp::GridViewType,
          class AnsatzSpaceImp = TestSpaceImp >
class SystemAssembler
  : public DSG::Walker< GridViewImp >
{
  static_assert(std::is_base_of< SpaceInterface< typename TestSpaceImp::Traits >, TestSpaceImp >::value,
                "TestSpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_base_of< SpaceInterface< typename AnsatzSpaceImp::Traits >, AnsatzSpaceImp >::value,
                "AnsatzSpaceImp has to be derived from SpaceInterface!");
  static_assert(std::is_same< typename TestSpaceImp::RangeFieldType, typename AnsatzSpaceImp::RangeFieldType >::value,
                "Types do not match!");
  typedef DSG::Walker< GridViewImp >                                  BaseType;
  typedef SystemAssembler<TestSpaceImp, GridViewImp, AnsatzSpaceImp > ThisType;
public:
  typedef TestSpaceImp                           TestSpaceType;
  typedef AnsatzSpaceImp                         AnsatzSpaceType;
  typedef typename TestSpaceType::RangeFieldType RangeFieldType;

  typedef typename BaseType::GridViewType     GridViewType;
  typedef typename BaseType::EntityType       EntityType;
  typedef typename BaseType::IntersectionType IntersectionType;

  typedef DSG::ApplyOn::WhichEntity< GridViewType >       ApplyOnWhichEntity;
  typedef DSG::ApplyOn::WhichIntersection< GridViewType > ApplyOnWhichIntersection;

  SystemAssembler(TestSpaceType test, AnsatzSpaceType ansatz, GridViewType grid_view)
    : BaseType(grid_view)
    , test_space_(test)
    , ansatz_space_(ansatz)
  {}

  SystemAssembler(TestSpaceType test, AnsatzSpaceType ansatz)
    : BaseType(test.grid_view())
    , test_space_(test)
    , ansatz_space_(ansatz)
  {}

  explicit SystemAssembler(TestSpaceType test)
    : BaseType(test.grid_view())
    , test_space_(test)
    , ansatz_space_(test)
  {}

  SystemAssembler(TestSpaceType test, GridViewType grid_view_in)
    : BaseType(grid_view_in)
    , test_space_(test)
    , ansatz_space_(test)
  {}

  const TestSpaceType& test_space() const
  {
    return *test_space_;
  }

  const AnsatzSpaceType& ansatz_space() const
  {
    return *ansatz_space_;
  }

  using BaseType::add;

  template< class C, class M >
  void add(Spaces::ConstraintsInterface< C, RangeFieldType >& constraints,
           Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
           const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    assert(matrix.rows() == test_space_->mapper().size());
    assert(matrix.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalMatrixConstraintsWrapper< TestSpaceType,
                                                     AnsatzSpaceType,
                                                     GridViewType,
                                                     typename C::derived_type,
                                                     typename M::derived_type > WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_,
                                                        ansatz_space_,
                                                        where,
                                                        constraints.as_imp(),
                                                        matrix.as_imp()));
  } // ... add(...)

  /** \todo Investigate why the ConstraintsInterface is not used here! */
  template< class ConstraintsType, class V >
  void add(ConstraintsType& constraints,
           Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
           const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = vector.as_imp();
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalVectorConstraintsWrapper< ThisType, ConstraintsType, VectorType > WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, constraints, vector_imp));
  } // ... add(...)

  template< class L, class M >
  void add(const LocalAssembler::Codim0Matrix< L >& local_assembler,
           Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
           const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalVolumeMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim0Matrix< L >, MatrixType >
        WrapperType;
    this->codim0_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class Codim0Assembler, class M >
  void add_codim0_assembler(const Codim0Assembler& local_assembler,
                            Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
                            const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalVolumeMatrixAssemblerWrapper< ThisType, Codim0Assembler, MatrixType > WrapperType;
    this->codim0_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class Codim0Assembler, class V >
  void add_codim0_assembler(const Codim0Assembler& local_assembler,
                            Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
                            const ApplyOnWhichEntity* where = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = vector.as_imp();
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalVolumeVectorAssemblerWrapper< ThisType, Codim0Assembler, VectorType > WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
  } // ... add(...)

  template< class L, class M >
  void add(const LocalAssembler::Codim1CouplingMatrix< L >& local_assembler,
           Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
           const ApplyOnWhichIntersection* where
              = new DSG::ApplyOn::AllIntersections< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalFaceMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim1CouplingMatrix< L >, MatrixType >
        WrapperType;
    this->codim1_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class L, class M >
  void add(const LocalAssembler::Codim1BoundaryMatrix< L >& local_assembler,
           Stuff::LA::MatrixInterface< M, RangeFieldType >& matrix,
           const ApplyOnWhichIntersection* where
              = new DSG::ApplyOn::AllIntersections< GridViewType >())
  {
    typedef typename M::derived_type MatrixType;
    MatrixType& matrix_imp = matrix.as_imp();
    assert(matrix_imp.rows() == test_space_->mapper().size());
    assert(matrix_imp.cols() == ansatz_space_->mapper().size());
    typedef internal::LocalFaceMatrixAssemblerWrapper< ThisType, LocalAssembler::Codim1BoundaryMatrix< L >, MatrixType >
        WrapperType;
    this->codim1_functors_.emplace_back(
          new WrapperType(test_space_, ansatz_space_, where, local_assembler, matrix_imp));
  } // ... add(...)

  template< class L, class V >
  void add(const LocalAssembler::Codim0Vector< L >& local_assembler,
           Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
           const ApplyOnWhichEntity* where
              = new DSG::ApplyOn::AllEntities< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = vector.as_imp();
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalVolumeVectorAssemblerWrapper< ThisType, LocalAssembler::Codim0Vector< L >, VectorType >
        WrapperType;
    this->codim0_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
  } // ... add(...)

  template< class L, class V >
  void add(const LocalAssembler::Codim1Vector< L >& local_assembler,
           Stuff::LA::VectorInterface< V, RangeFieldType >& vector,
           const ApplyOnWhichIntersection* where
              = new DSG::ApplyOn::AllIntersections< GridViewType >())
  {
    typedef typename V::derived_type VectorType;
    VectorType& vector_imp = static_cast< VectorType& >(vector);
    assert(vector_imp.size() == test_space_->mapper().size());
    typedef internal::LocalFaceVectorAssemblerWrapper< ThisType, LocalAssembler::Codim1Vector< L >, VectorType >
        WrapperType;
    this->codim1_functors_.emplace_back(new WrapperType(test_space_, where, local_assembler, vector_imp));
  } // ... add(...)

  void assemble(const bool use_tbb = false)
  {
    this->walk(use_tbb);
  }

  template <class Partitioning>
  void assemble(const Partitioning& partitioning)
  {
    this->walk(partitioning);
  }

private:
  const DS::PerThreadValue<const TestSpaceType> test_space_;
  const DS::PerThreadValue<const AnsatzSpaceType> ansatz_space_;
}; // class SystemAssembler

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_ASSEMBLER_SYSTEM_HH
<|endoftext|>