<commit_before>/**
 * This file defines the lock graph data structure used during the post-mortem
 * program analysis.
 */

#ifndef D2_CORE_LOCK_GRAPH_HPP
#define D2_CORE_LOCK_GRAPH_HPP

#include <d2/detail/lock_debug_info.hpp>
#include <d2/lock_id.hpp>
#include <d2/segment.hpp>
#include <d2/thread_id.hpp>

#include <boost/assert.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/named_graph.hpp>
#include <boost/move/move.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/operators.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/unordered_set.hpp>

namespace d2 {
namespace lock_graph_detail {
/**
 * Set whose underlying representation can be shared by several owners.
 *
 * @note This structure is optimized so that several duplicated read-only
 *       copies of it are space efficient.
 */
template <typename Set>
struct shared_set {
    typedef Set underlying_set_type;

    //! Construct an empty set.
    shared_set()
        : set_(new underlying_set_type())
    { }

    //! Construct a shared set sharing its underlying set with `other`.
    /*implicit*/ shared_set(shared_set const& other)
        : set_(other.set_)
    { }

    //! Construct a shared set with an underlying set equal to `other`.
    explicit shared_set(BOOST_RV_REF(underlying_set_type) other)
        : set_(new underlying_set_type(boost::move(other)))
    { }

    //! Return a constant reference to the underlying set of `*this`.
    operator underlying_set_type const&() const {
        BOOST_ASSERT_MSG(set_, "invariant broken: the shared_ptr of a "
                               "shared set instance is invalid");
        return *set_;
    }

private:
    boost::shared_ptr<underlying_set_type const> set_;
};

/**
 * Set of locks held by a thread.
 *
 * @note We use a `shared_set` because an instance of `Gatelocks` is stored
 *       on each edge of the lock graph. We could use a `flyweight` too, but
 *       benchmarking shows that the current solution offers a better
 *       space/time tradeoff.
 *       The main differences between the two approaches are:
 *       - `flyweight` requires the set to be hashed everytime, which is
 *         more CPU intensive.
 *       - Using a `shared_set` is suboptimal because there may be some
 *         repetition of the gatelocks in the lock graph when the gatelocks
 *         are the same on different events.
 */
typedef shared_set<boost::unordered_set<LockId> > Gatelocks;

/**
 * Label stored on each edge of a lock graph.
 */
struct LockGraphLabel : boost::equality_comparable<LockGraphLabel> {
    LockGraphLabel(Segment s1, ThreadId thread,
                   Gatelocks const& gatelocks, Segment s2)
        : s1(s1), s2(s2), thread_(thread), gatelocks_(gatelocks)
    { }

    detail::LockDebugInfo l1_info, l2_info;
    Segment s1, s2;

    friend Gatelocks::underlying_set_type const&
    gatelocks_of(LockGraphLabel const& self) {
        return self.gatelocks_;
    }

    friend ThreadId const& thread_of(LockGraphLabel const& self) {
        return self.thread_;
    }

    friend bool operator==(LockGraphLabel const& a, LockGraphLabel const& b) {
        // Note: We test the easiest first, i.e. the threads and segments,
        //       which are susceptible of being similar to integers.
        return a.s1 == b.s1 &&
               a.s2 == b.s2 &&
               thread_of(a) == thread_of(b) &&
               a.l1_info == b.l1_info &&
               a.l2_info == b.l2_info &&
               gatelocks_of(a) == gatelocks_of(b);
    }

private:
    ThreadId thread_;
    Gatelocks gatelocks_;
};

/**
 * Directed graph representing the contexts in which synchronization objects
 * were acquired by threads.
 */
typedef boost::adjacency_list<
            boost::vecS, boost::vecS, boost::directedS, LockId, LockGraphLabel
        > LockGraph;

} // end namespace lock_graph_detail

namespace core {
    using lock_graph_detail::LockGraph;
    using lock_graph_detail::LockGraphLabel;
    using lock_graph_detail::Gatelocks;
}
} // end namespace d2

namespace boost {
namespace graph {
    // This is to be able to refer to a vertex in the lock graph using the
    // LockId associated to it.
    template <> struct internal_vertex_name<d2::LockId> {
        typedef multi_index::identity<d2::LockId> type;
    };
} // end namespace graph
} // end namespace boost

#endif // !D2_CORE_LOCK_GRAPH_HPP
<commit_msg>Use make_shared in the shared_set.<commit_after>/**
 * This file defines the lock graph data structure used during the post-mortem
 * program analysis.
 */

#ifndef D2_CORE_LOCK_GRAPH_HPP
#define D2_CORE_LOCK_GRAPH_HPP

#include <d2/detail/lock_debug_info.hpp>
#include <d2/lock_id.hpp>
#include <d2/segment.hpp>
#include <d2/thread_id.hpp>

#include <boost/assert.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/named_graph.hpp>
#include <boost/make_shared.hpp>
#include <boost/move/move.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/operators.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/unordered_set.hpp>

namespace d2 {
namespace lock_graph_detail {
/**
 * Set whose underlying representation can be shared by several owners.
 *
 * @note This structure is optimized so that several duplicated read-only
 *       copies of it are space efficient.
 */
template <typename Set>
struct shared_set {
    typedef Set underlying_set_type;

    //! Construct an empty set.
    shared_set()
        : set_(boost::make_shared<underlying_set_type>())
    { }

    //! Construct a shared set sharing its underlying set with `other`.
    /*implicit*/ shared_set(shared_set const& other)
        : set_(other.set_)
    { }

    //! Construct a shared set with an underlying set equal to `other`.
    explicit shared_set(BOOST_RV_REF(underlying_set_type) other)
        : set_(boost::make_shared<underlying_set_type>(boost::move(other)))
    { }

    //! Return a constant reference to the underlying set of `*this`.
    operator underlying_set_type const&() const {
        BOOST_ASSERT_MSG(set_, "invariant broken: the shared_ptr of a "
                               "shared set instance is invalid");
        return *set_;
    }

private:
    boost::shared_ptr<underlying_set_type const> set_;
};

/**
 * Set of locks held by a thread.
 *
 * @note We use a `shared_set` because an instance of `Gatelocks` is stored
 *       on each edge of the lock graph. We could use a `flyweight` too, but
 *       benchmarking shows that the current solution offers a better
 *       space/time tradeoff.
 *       The main differences between the two approaches are:
 *       - `flyweight` requires the set to be hashed everytime, which is
 *         more CPU intensive.
 *       - Using a `shared_set` is suboptimal because there may be some
 *         repetition of the gatelocks in the lock graph when the gatelocks
 *         are the same on different events.
 */
typedef shared_set<boost::unordered_set<LockId> > Gatelocks;

/**
 * Label stored on each edge of a lock graph.
 */
struct LockGraphLabel : boost::equality_comparable<LockGraphLabel> {
    LockGraphLabel(Segment s1, ThreadId thread,
                   Gatelocks const& gatelocks, Segment s2)
        : s1(s1), s2(s2), thread_(thread), gatelocks_(gatelocks)
    { }

    detail::LockDebugInfo l1_info, l2_info;
    Segment s1, s2;

    friend Gatelocks::underlying_set_type const&
    gatelocks_of(LockGraphLabel const& self) {
        return self.gatelocks_;
    }

    friend ThreadId const& thread_of(LockGraphLabel const& self) {
        return self.thread_;
    }

    friend bool operator==(LockGraphLabel const& a, LockGraphLabel const& b) {
        // Note: We test the easiest first, i.e. the threads and segments,
        //       which are susceptible of being similar to integers.
        return a.s1 == b.s1 &&
               a.s2 == b.s2 &&
               thread_of(a) == thread_of(b) &&
               a.l1_info == b.l1_info &&
               a.l2_info == b.l2_info &&
               gatelocks_of(a) == gatelocks_of(b);
    }

private:
    ThreadId thread_;
    Gatelocks gatelocks_;
};

/**
 * Directed graph representing the contexts in which synchronization objects
 * were acquired by threads.
 */
typedef boost::adjacency_list<
            boost::vecS, boost::vecS, boost::directedS, LockId, LockGraphLabel
        > LockGraph;

} // end namespace lock_graph_detail

namespace core {
    using lock_graph_detail::LockGraph;
    using lock_graph_detail::LockGraphLabel;
    using lock_graph_detail::Gatelocks;
}
} // end namespace d2

namespace boost {
namespace graph {
    // This is to be able to refer to a vertex in the lock graph using the
    // LockId associated to it.
    template <> struct internal_vertex_name<d2::LockId> {
        typedef multi_index::identity<d2::LockId> type;
    };
} // end namespace graph
} // end namespace boost

#endif // !D2_CORE_LOCK_GRAPH_HPP
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 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 "cpp_utils/assert.hpp" //Assertions

#include "etl/etl.hpp"

#include "neural_base.hpp"
#include "util/tmp.hpp"
#include "layer_traits.hpp"

namespace dll {

/*!
 * \brief Standard dynamic convolutional layer of neural network.
 */
template <typename Desc>
struct dyn_conv_layer final : neural_base<dyn_conv_layer<Desc>> {
    using desc      = Desc;                  ///< The descriptor type
    using weight    = typename desc::weight; ///< The weight type
    using this_type = dyn_conv_layer<desc>;  ///< This type

    static constexpr const bool dbn_only = layer_traits<this_type>::is_dbn_only();

    static constexpr const function activation_function = desc::activation_function;

    using input_one_t  = etl::dyn_matrix<weight, 3>; ///< The type for one input
    using output_one_t = etl::dyn_matrix<weight, 3>; ///< The type for one output
    using input_t      = std::vector<input_one_t>;   ///< The type for many input
    using output_t     = std::vector<output_one_t>;  ///< The type for many output

    //TODO CHECK
    template <std::size_t B>
    using input_batch_t = etl::fast_dyn_matrix<weight, B, 1>;

    using w_type = etl::dyn_matrix<weight, 4>;
    using b_type = etl::dyn_matrix<weight, 1>;

    //Weights and biases
    w_type w; //!< Weights
    b_type b; //!< Hidden biases

    //Backup weights and biases
    std::unique_ptr<w_type> bak_w; //!< Backup Weights
    std::unique_ptr<b_type> bak_b; //!< Backup Hidden biases

    //No copying
    dyn_conv_layer(const dyn_conv_layer& layer) = delete;
    dyn_conv_layer& operator=(const dyn_conv_layer& layer) = delete;

    //No moving
    dyn_conv_layer(dyn_conv_layer&& layer) = delete;
    dyn_conv_layer& operator=(dyn_conv_layer&& layer) = delete;

    size_t nv1; ///< The first visible dimension
    size_t nv2; ///< The second visible dimension
    size_t nh1; ///< The first output dimension
    size_t nh2; ///< The second output dimension
    size_t nc;  ///< The number of input channels
    size_t k;   ///< The number of filters

    size_t nw1; ///< The first dimension of the filters
    size_t nw2; ///< The second dimension of the filters

    dyn_conv_layer(){
        // Nothing else to init
    }

    void init_layer(size_t nc, size_t nv1, size_t nv2, size_t k, size_t nh1, size_t nh2){
        this->nv1 = nv1;
        this->nv2 = nv2;
        this->nh1 = nh1;
        this->nh2 = nh2;
        this->nc = nc;
        this->k = k;

        this->nw1 = nv1 - nh1 + 1;
        this->nw2 = nv2 - nh2 + 1;

        w = etl::dyn_matrix<weight, 4>(nc, k, nw1, nw2);

        b = etl::dyn_vector<weight>(k);

        //Initialize the weights and biases following Lecun approach
        //to initialization [lecun-98b]

        w = etl::normal_generator<weight>() * std::sqrt(2.0 / double(nc * nv1 * nv2));

        if (activation_function == function::RELU) {
            b = 0.01;
        } else {
            b = etl::normal_generator<weight>() * std::sqrt(2.0 / double(nc * nv1 * nv2));
        }
    }

    std::size_t input_size() const noexcept {
        return nc * nv1 * nv2;
    }

    std::size_t output_size() const noexcept {
        return k * nh1 * nh2;
    }

    std::size_t parameters() const noexcept {
        return k * nw1 * nw2;
    }

    std::string to_short_string() const {
        char buffer[1024];
        snprintf(buffer, 1024, "Conv(dyn): %lux%lux%lu -> (%lux%lux%lu) -> %s -> %lux%lux%lu", nc, nv1, nv2, k, nw1, nw2, to_string(activation_function).c_str(), k, nh1, nh2);
        return {buffer};
    }

    void display() const {
        std::cout << to_short_string() << std::endl;
    }

    void backup_weights() {
        unique_safe_get(bak_w) = w;
        unique_safe_get(bak_b) = b;
    }

    void restore_weights() {
        w = *bak_w;
        b = *bak_b;
    }

    template <typename V>
    void activate_hidden(output_one_t& output, const V& v) const {
        etl::dyn_matrix<weight, 4> v_cv(2UL, k, nh1, nh2); //Temporary convolution

        auto w_f = etl::force_temporary(w);

        //flip all the kernels horizontally and vertically

        for (std::size_t channel = 0; channel < nc; ++channel) {
            for (size_t k = 0; k < k; ++k) {
                w_f(channel)(k).fflip_inplace();
            }
        }

        v_cv(1) = 0;

        for (std::size_t channel = 0; channel < nc; ++channel) {
            etl::conv_2d_valid_multi(v(channel), w_f(channel), v_cv(0));

            v_cv(1) += v_cv(0);
        }

        output = f_activate<activation_function>(etl::rep(b, nh1, nh2) + v_cv(1));
    }

    template <typename H1, typename V>
    void batch_activate_hidden(H1&& output, const V& v) const {
        etl::dyn_matrix<weight, 4> v_cv(2UL, k, nh1, nh2); //Temporary convolution

        const auto Batch = etl::dim<0>(v);

        auto w_f = force_temporary(w);

        //flip all the kernels horizontally and vertically

        for (std::size_t channel = 0; channel < nc; ++channel) {
            for (size_t k = 0; k < k; ++k) {
                w_f(channel)(k).fflip_inplace();
            }
        }

        for (std::size_t batch = 0; batch < Batch; ++batch) {
            v_cv(1) = 0;

            for (std::size_t channel = 0; channel < nc; ++channel) {
                etl::conv_2d_valid_multi(v(batch)(channel), w_f(channel), v_cv(0));

                v_cv(1) += v_cv(0);
            }

            output(batch) = f_activate<activation_function>(etl::rep(b, nh1, nh2) + v_cv(1));
        }
    }

    void prepare_input(input_one_t& input) const {
        input = input_one_t(nc, nv1, nv2);
    }

    template <typename Input>
    output_t prepare_output(std::size_t samples) const {
        output_t output;
        output.reserve(samples);
        for(size_t i = 0; i < samples; ++i){
            output.emplace_back(k, nh1, nh2);
        }
        return output;
    }

    template <typename Input>
    output_one_t prepare_one_output() const {
        return output_one_t(k, nh1, nh2);
    }

    template <std::size_t B>
    auto prepare_input_batch(){
        return etl::dyn_matrix<weight, 4>(B, nc, nv1, nv2);
    }

    template <std::size_t B>
    auto prepare_output_batch(){
        return etl::dyn_matrix<weight, 4>(B, k, nh1, nh2);
    }

    template <typename DBN>
    void init_sgd_context() {
        this->sgd_context_ptr = std::make_shared<sgd_context<DBN, this_type>>(nc, nv1, nv2, k, nh1, nh2);
    }
};

} //end of dll namespace
<commit_msg>Fix dyn_conv :(<commit_after>//=======================================================================
// Copyright (c) 2014-2016 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 "cpp_utils/assert.hpp" //Assertions

#include "etl/etl.hpp"

#include "neural_base.hpp"
#include "util/tmp.hpp"
#include "layer_traits.hpp"

namespace dll {

/*!
 * \brief Standard dynamic convolutional layer of neural network.
 */
template <typename Desc>
struct dyn_conv_layer final : neural_base<dyn_conv_layer<Desc>> {
    using desc      = Desc;                  ///< The descriptor type
    using weight    = typename desc::weight; ///< The weight type
    using this_type = dyn_conv_layer<desc>;  ///< This type

    static constexpr const bool dbn_only = layer_traits<this_type>::is_dbn_only();

    static constexpr const function activation_function = desc::activation_function;

    using input_one_t  = etl::dyn_matrix<weight, 3>; ///< The type for one input
    using output_one_t = etl::dyn_matrix<weight, 3>; ///< The type for one output
    using input_t      = std::vector<input_one_t>;   ///< The type for many input
    using output_t     = std::vector<output_one_t>;  ///< The type for many output

    //TODO CHECK
    template <std::size_t B>
    using input_batch_t = etl::fast_dyn_matrix<weight, B, 1>;

    using w_type = etl::dyn_matrix<weight, 4>;
    using b_type = etl::dyn_matrix<weight, 1>;

    //Weights and biases
    w_type w; //!< Weights
    b_type b; //!< Hidden biases

    //Backup weights and biases
    std::unique_ptr<w_type> bak_w; //!< Backup Weights
    std::unique_ptr<b_type> bak_b; //!< Backup Hidden biases

    //No copying
    dyn_conv_layer(const dyn_conv_layer& layer) = delete;
    dyn_conv_layer& operator=(const dyn_conv_layer& layer) = delete;

    //No moving
    dyn_conv_layer(dyn_conv_layer&& layer) = delete;
    dyn_conv_layer& operator=(dyn_conv_layer&& layer) = delete;

    size_t nv1; ///< The first visible dimension
    size_t nv2; ///< The second visible dimension
    size_t nh1; ///< The first output dimension
    size_t nh2; ///< The second output dimension
    size_t nc;  ///< The number of input channels
    size_t k;   ///< The number of filters

    size_t nw1; ///< The first dimension of the filters
    size_t nw2; ///< The second dimension of the filters

    dyn_conv_layer(){
        // Nothing else to init
    }

    void init_layer(size_t nc, size_t nv1, size_t nv2, size_t k, size_t nh1, size_t nh2){
        this->nv1 = nv1;
        this->nv2 = nv2;
        this->nh1 = nh1;
        this->nh2 = nh2;
        this->nc = nc;
        this->k = k;

        this->nw1 = nv1 - nh1 + 1;
        this->nw2 = nv2 - nh2 + 1;

        w = etl::dyn_matrix<weight, 4>(nc, k, nw1, nw2);

        b = etl::dyn_vector<weight>(k);

        //Initialize the weights and biases following Lecun approach
        //to initialization [lecun-98b]

        w = etl::normal_generator<weight>() * std::sqrt(2.0 / double(nc * nv1 * nv2));

        if (activation_function == function::RELU) {
            b = 0.01;
        } else {
            b = etl::normal_generator<weight>() * std::sqrt(2.0 / double(nc * nv1 * nv2));
        }
    }

    std::size_t input_size() const noexcept {
        return nc * nv1 * nv2;
    }

    std::size_t output_size() const noexcept {
        return k * nh1 * nh2;
    }

    std::size_t parameters() const noexcept {
        return k * nw1 * nw2;
    }

    std::string to_short_string() const {
        char buffer[1024];
        snprintf(buffer, 1024, "Conv(dyn): %lux%lux%lu -> (%lux%lux%lu) -> %s -> %lux%lux%lu", nc, nv1, nv2, k, nw1, nw2, to_string(activation_function).c_str(), k, nh1, nh2);
        return {buffer};
    }

    void display() const {
        std::cout << to_short_string() << std::endl;
    }

    void backup_weights() {
        unique_safe_get(bak_w) = w;
        unique_safe_get(bak_b) = b;
    }

    void restore_weights() {
        w = *bak_w;
        b = *bak_b;
    }

    template <typename V>
    void activate_hidden(output_one_t& output, const V& v) const {
        etl::dyn_matrix<weight, 4> v_cv(2UL, k, nh1, nh2); //Temporary convolution

        const auto K = k;

        auto w_f = etl::force_temporary(w);

        //flip all the kernels horizontally and vertically

        for (std::size_t channel = 0; channel < nc; ++channel) {
            for (size_t k = 0; k < K; ++k) {
                w_f(channel)(k).fflip_inplace();
            }
        }

        v_cv(1) = 0;

        for (std::size_t channel = 0; channel < nc; ++channel) {
            etl::conv_2d_valid_multi(v(channel), w_f(channel), v_cv(0));

            v_cv(1) += v_cv(0);
        }

        output = f_activate<activation_function>(etl::rep(b, nh1, nh2) + v_cv(1));
    }

    template <typename H1, typename V>
    void batch_activate_hidden(H1&& output, const V& v) const {
        etl::dyn_matrix<weight, 4> v_cv(2UL, k, nh1, nh2); //Temporary convolution

        const auto Batch = etl::dim<0>(v);
        const auto K = k;

        auto w_f = force_temporary(w);

        //flip all the kernels horizontally and vertically

        for (std::size_t channel = 0; channel < nc; ++channel) {
            for (size_t k = 0; k < K; ++k) {
                w_f(channel)(k).fflip_inplace();
            }
        }

        for (std::size_t batch = 0; batch < Batch; ++batch) {
            v_cv(1) = 0;

            for (std::size_t channel = 0; channel < nc; ++channel) {
                etl::conv_2d_valid_multi(v(batch)(channel), w_f(channel), v_cv(0));

                v_cv(1) += v_cv(0);
            }

            output(batch) = f_activate<activation_function>(etl::rep(b, nh1, nh2) + v_cv(1));
        }
    }

    void prepare_input(input_one_t& input) const {
        input = input_one_t(nc, nv1, nv2);
    }

    template <typename Input>
    output_t prepare_output(std::size_t samples) const {
        output_t output;
        output.reserve(samples);
        for(size_t i = 0; i < samples; ++i){
            output.emplace_back(k, nh1, nh2);
        }
        return output;
    }

    template <typename Input>
    output_one_t prepare_one_output() const {
        return output_one_t(k, nh1, nh2);
    }

    template <std::size_t B>
    auto prepare_input_batch(){
        return etl::dyn_matrix<weight, 4>(B, nc, nv1, nv2);
    }

    template <std::size_t B>
    auto prepare_output_batch(){
        return etl::dyn_matrix<weight, 4>(B, k, nh1, nh2);
    }

    template <typename DBN>
    void init_sgd_context() {
        this->sgd_context_ptr = std::make_shared<sgd_context<DBN, this_type>>(nc, nv1, nv2, k, nh1, nh2);
    }
};

} //end of dll namespace
<|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_VERSION_HPP_INCLUDED
#define TORRENT_VERSION_HPP_INCLUDED

#define LIBTORRENT_VERSION_MAJOR 0
#define LIBTORRENT_VERSION_MINOR 13

#define LIBTORRENT_VERSION "0.13.0.0"

#endif
<commit_msg>bumped version number<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_VERSION_HPP_INCLUDED
#define TORRENT_VERSION_HPP_INCLUDED

#define LIBTORRENT_VERSION_MAJOR 0
#define LIBTORRENT_VERSION_MINOR 14

#define LIBTORRENT_VERSION "0.14.0.0"

#endif
<|endoftext|>


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

/**
 * @file
 **/

#include "modules/planning/lattice/trajectory_generator/trajectory_evaluator.h"

#include <cmath>
#include <functional>
#include <limits>
#include <utility>

#include "modules/common/log.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/constraint_checker/constraint_checker1d.h"

namespace apollo {
namespace planning {

using Trajectory1d = Curve1d;

TrajectoryEvaluator::TrajectoryEvaluator(
    const PlanningTarget& planning_target,
    const std::vector<std::shared_ptr<Trajectory1d>>& lon_trajectories,
    const std::vector<std::shared_ptr<Trajectory1d>>& lat_trajectories,
    bool is_auto_tuning,
    std::shared_ptr<PathTimeNeighborhood> pathtime_neighborhood)
    : is_auto_tuning_(is_auto_tuning),
      pathtime_neighborhood_(pathtime_neighborhood) {
  for (const auto lon_trajectory : lon_trajectories) {
    if (!ConstraintChecker1d::IsValidLongitudinalTrajectory(*lon_trajectory)) {
      continue;
    }
    for (const auto lat_trajectory : lat_trajectories) {
      if (!ConstraintChecker1d::IsValidLateralTrajectory(*lat_trajectory,
                                                         *lon_trajectory)) {
        continue;
      }
      if (!is_auto_tuning_) {
        double cost =
            evaluate(planning_target, lon_trajectory, lat_trajectory, nullptr);
        cost_queue_.push(PairCost({lon_trajectory, lat_trajectory}, cost));
      } else {
        std::vector<double> cost_components;
        double cost = evaluate(planning_target, lon_trajectory, lat_trajectory,
                               &cost_components);
        cost_queue_with_components_.push(PairCostWithComponents(
            {lon_trajectory, lat_trajectory}, {cost_components, cost}));
      }
    }
  }
  if (!is_auto_tuning_) {
    ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_.size();
  } else {
    ADEBUG << "Number of valid 1d trajectory pairs: "
           << cost_queue_with_components_.size();
  }
}

bool TrajectoryEvaluator::has_more_trajectory_pairs() const {
  if (!is_auto_tuning_) {
    return !cost_queue_.empty();
  } else {
    return !cost_queue_with_components_.empty();
  }
}

std::size_t TrajectoryEvaluator::num_of_trajectory_pairs() const {
  if (!is_auto_tuning_) {
    return cost_queue_.size();
  } else {
    return cost_queue_with_components_.empty();
  }
}

std::pair<std::shared_ptr<Trajectory1d>, std::shared_ptr<Trajectory1d>>
TrajectoryEvaluator::next_top_trajectory_pair() {
  CHECK(has_more_trajectory_pairs() == true);
  if (!is_auto_tuning_) {
    auto top = cost_queue_.top();
    cost_queue_.pop();
    return top.first;
  } else {
    auto top = cost_queue_with_components_.top();
    cost_queue_with_components_.pop();
    return top.first;
  }
}

double TrajectoryEvaluator::top_trajectory_pair_cost() const {
  if (!is_auto_tuning_) {
    return cost_queue_.top().second;
  } else {
    return cost_queue_with_components_.top().second.second;
  }
}

std::vector<double> TrajectoryEvaluator::top_trajectory_pair_component_cost()
    const {
  CHECK(is_auto_tuning_);
  return cost_queue_with_components_.top().second.first;
}

double TrajectoryEvaluator::evaluate(
    const PlanningTarget& planning_target,
    const std::shared_ptr<Trajectory1d>& lon_trajectory,
    const std::shared_ptr<Trajectory1d>& lat_trajectory,
    std::vector<double>* cost_components) const {
  // currently consider three costs:
  // 1. the cost of jerk, currently only consider longitudinal jerk.
  // 2. the cost of time to achieve the objective
  // 3. the cost of failure to achieve the planning objective.

  double weight_lon_travel = 1000.0;
  double weight_lon_jerk = 1.0;
  double weight_lon_obstacle = 100.0;
  double weight_lat_offset = 1.0;

  double lon_travel_cost =
      compute_lon_objective_cost(lon_trajectory, planning_target);

  double lon_jerk_cost = compute_lon_comfort_cost(lon_trajectory);

  // for evaluating lateral trajectories
  std::vector<double> s_values;
  double s = 0.0;
  while (s < FLAGS_decision_horizon) {
    s_values.push_back(s);
    s += FLAGS_trajectory_space_resolution;
  }
  double lat_offset_cost = compute_lat_offset_cost(lat_trajectory, s_values);

  double lon_obstacle_cost = compute_lon_obstacle_cost(lon_trajectory);

  if (cost_components) {
    cost_components->push_back(lon_travel_cost);
    cost_components->push_back(lon_jerk_cost);
    cost_components->push_back(lon_obstacle_cost);
    cost_components->push_back(lat_offset_cost);
  }
  return lon_travel_cost * weight_lon_travel + lon_jerk_cost * weight_lon_jerk +
         lat_offset_cost * weight_lat_offset +
         lon_obstacle_cost * weight_lon_obstacle;
}

double TrajectoryEvaluator::compute_lat_offset_cost(
    const std::shared_ptr<Trajectory1d>& lat_trajectory,
    const std::vector<double>& s_values) const {
  double lat_offset_start = lat_trajectory->Evaluate(0, 0.0);
  double weight_same_side_offset = 1.0;
  double weight_opposite_side_offset = 10.0;

  double cost = 0.0;
  for (const auto& s : s_values) {
    double c = lat_trajectory->Evaluate(0, s);
    if (c * lat_offset_start < 0.0) {
      c = c * c * weight_opposite_side_offset;
    } else {
      c = c * c * weight_same_side_offset;
    }
    cost += c;
  }
  return cost;
}

double TrajectoryEvaluator::compute_lon_comfort_cost(
    const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
  double cost = 0.0;
  double t = 0.0;

  while (t < FLAGS_trajectory_time_length) {
    double c = lon_trajectory->Evaluate(3, t);
    cost += c * c;
    t = t + FLAGS_trajectory_time_resolution;
  }
  return cost;
}

double TrajectoryEvaluator::compute_lon_objective_cost(
    const std::shared_ptr<Trajectory1d>& lon_trajectory,
    const PlanningTarget& planning_target) const {
  double weight_dist_travelled = 10.0;
  double weight_on_reference_speed = 1.0;
  double t_max = lon_trajectory->ParamLength();

  double dist_s =
      lon_trajectory->Evaluate(0, t_max) - lon_trajectory->Evaluate(0, 0.0);

  double cost = 0.0;
  double t = 0.0;
  while (t < FLAGS_trajectory_time_length) {
    double c = planning_target.cruise_speed() - lon_trajectory->Evaluate(1, t);
    cost += std::fabs(c);
    t += FLAGS_trajectory_time_resolution;
  }
  cost *= weight_on_reference_speed;
  cost += weight_dist_travelled * 1.0 / (1.0 + dist_s);
  return cost;
}

// TODO(@all): consider putting pointer of reference_line_info and frame
// while constructing trajectory evaluator
double TrajectoryEvaluator::compute_lon_obstacle_cost(
    const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
  double start_time = 0.0;
  double end_time = FLAGS_trajectory_time_length;
  const auto& pt_intervals = pathtime_neighborhood_->GetPathBlockingIntervals(
      start_time, end_time, FLAGS_trajectory_time_resolution);

  double obstacle_cost = 0.0;
  for (std::size_t i = 0; i < pt_intervals.size(); ++i) {
    const auto& pt_interval = pt_intervals[i];
    if (pt_interval.empty()) {
      continue;
    }

    double t = start_time + i * FLAGS_trajectory_time_resolution;
    double traj_s = lon_trajectory->Evaluate(0, t);

    for (const auto& m : pt_interval) {
      double mid_s = (m.first + m.second) * 0.5;
      obstacle_cost += 1.0 / std::exp(std::abs(traj_s - mid_s));
    }
  }
  return obstacle_cost;
}

std::vector<double> TrajectoryEvaluator::evaluate_per_lonlat_trajectory(
    const PlanningTarget& planning_target,
    const std::vector<apollo::common::SpeedPoint> st_points,
    const std::vector<apollo::common::FrenetFramePoint> sl_points) {
  std::vector<double> ret;
  return ret;
}

}  // namespace planning
}  // namespace apollo
<commit_msg>Planning: [lattice] adjust cost functions to make them in the same scale<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/

#include "modules/planning/lattice/trajectory_generator/trajectory_evaluator.h"

#include <cmath>
#include <functional>
#include <limits>
#include <utility>

#include "modules/common/log.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/constraint_checker/constraint_checker1d.h"

namespace apollo {
namespace planning {

using Trajectory1d = Curve1d;

TrajectoryEvaluator::TrajectoryEvaluator(
    const PlanningTarget& planning_target,
    const std::vector<std::shared_ptr<Trajectory1d>>& lon_trajectories,
    const std::vector<std::shared_ptr<Trajectory1d>>& lat_trajectories,
    bool is_auto_tuning,
    std::shared_ptr<PathTimeNeighborhood> pathtime_neighborhood)
    : is_auto_tuning_(is_auto_tuning),
      pathtime_neighborhood_(pathtime_neighborhood) {
  for (const auto lon_trajectory : lon_trajectories) {
    if (!ConstraintChecker1d::IsValidLongitudinalTrajectory(*lon_trajectory)) {
      continue;
    }
    for (const auto lat_trajectory : lat_trajectories) {
      if (!ConstraintChecker1d::IsValidLateralTrajectory(*lat_trajectory,
                                                         *lon_trajectory)) {
        continue;
      }
      if (!is_auto_tuning_) {
        double cost =
            evaluate(planning_target, lon_trajectory, lat_trajectory, nullptr);
        cost_queue_.push(PairCost({lon_trajectory, lat_trajectory}, cost));
      } else {
        std::vector<double> cost_components;
        double cost = evaluate(planning_target, lon_trajectory, lat_trajectory,
                               &cost_components);
        cost_queue_with_components_.push(PairCostWithComponents(
            {lon_trajectory, lat_trajectory}, {cost_components, cost}));
      }
    }
  }
  if (!is_auto_tuning_) {
    ADEBUG << "Number of valid 1d trajectory pairs: " << cost_queue_.size();
  } else {
    ADEBUG << "Number of valid 1d trajectory pairs: "
           << cost_queue_with_components_.size();
  }
}

bool TrajectoryEvaluator::has_more_trajectory_pairs() const {
  if (!is_auto_tuning_) {
    return !cost_queue_.empty();
  } else {
    return !cost_queue_with_components_.empty();
  }
}

std::size_t TrajectoryEvaluator::num_of_trajectory_pairs() const {
  if (!is_auto_tuning_) {
    return cost_queue_.size();
  } else {
    return cost_queue_with_components_.empty();
  }
}

std::pair<std::shared_ptr<Trajectory1d>, std::shared_ptr<Trajectory1d>>
TrajectoryEvaluator::next_top_trajectory_pair() {
  CHECK(has_more_trajectory_pairs() == true);
  if (!is_auto_tuning_) {
    auto top = cost_queue_.top();
    cost_queue_.pop();
    return top.first;
  } else {
    auto top = cost_queue_with_components_.top();
    cost_queue_with_components_.pop();
    return top.first;
  }
}

double TrajectoryEvaluator::top_trajectory_pair_cost() const {
  if (!is_auto_tuning_) {
    return cost_queue_.top().second;
  } else {
    return cost_queue_with_components_.top().second.second;
  }
}

std::vector<double>
TrajectoryEvaluator::top_trajectory_pair_component_cost() const {
  CHECK(is_auto_tuning_);
  return cost_queue_with_components_.top().second.first;
}

double TrajectoryEvaluator::evaluate(
    const PlanningTarget& planning_target,
    const std::shared_ptr<Trajectory1d>& lon_trajectory,
    const std::shared_ptr<Trajectory1d>& lat_trajectory,
    std::vector<double>* cost_components) const {
  // currently consider three costs:
  // 1. the cost of jerk, currently only consider longitudinal jerk.
  // 2. the cost of time to achieve the objective
  // 3. the cost of failure to achieve the planning objective.

  double weight_lon_travel = 5.0;
  double weight_lon_jerk = 1.0;
  double weight_lon_obstacle = 1.0;
  double weight_lat_offset = 1.0;

  double lon_travel_cost =
      compute_lon_objective_cost(lon_trajectory, planning_target);

  double lon_jerk_cost = compute_lon_comfort_cost(lon_trajectory);

  // for evaluating lateral trajectories
  std::vector<double> s_values;
  double s = 0.0;
  while (s < FLAGS_decision_horizon) {
    s_values.push_back(s);
    s += FLAGS_trajectory_space_resolution;
  }
  double lat_offset_cost = compute_lat_offset_cost(lat_trajectory, s_values);

  double lon_obstacle_cost = compute_lon_obstacle_cost(lon_trajectory);

  if (cost_components) {
    cost_components->push_back(lon_travel_cost);
    cost_components->push_back(lon_jerk_cost);
    cost_components->push_back(lon_obstacle_cost);
    cost_components->push_back(lat_offset_cost);
  }
  return lon_travel_cost * weight_lon_travel +
         lon_jerk_cost * weight_lon_jerk +
         lat_offset_cost * weight_lat_offset +
         lon_obstacle_cost * weight_lon_obstacle;
}

double TrajectoryEvaluator::compute_lat_offset_cost(
    const std::shared_ptr<Trajectory1d>& lat_trajectory,
    const std::vector<double>& s_values) const {
  double lat_offset_start = lat_trajectory->Evaluate(0, 0.0);
  double weight_same_side_offset = 1.0;
  double weight_opposite_side_offset = 10.0;
  double lat_offset_bound = 3.0;

  double cost_sqr_sum = 0.0;
  double cost_abs_sum = 0.0;
  for (const auto& s : s_values) {
    double lat_offset = lat_trajectory->Evaluate(0, s);
    double cost = lat_offset / lat_offset_bound;
    if (lat_offset * lat_offset_start < 0.0) {
      cost_sqr_sum += cost * cost * weight_opposite_side_offset;
      cost_abs_sum += std::abs(cost) * weight_opposite_side_offset;
    } else {
      cost_sqr_sum += cost * cost * weight_same_side_offset;
      cost_abs_sum += std::abs(cost) * weight_same_side_offset;
    }
  }
  return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}

double TrajectoryEvaluator::compute_lon_comfort_cost(
    const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
  double cost_sqr_sum = 0.0;
  double cost_abs_sum = 0.0;
  // TODO(all) need a new gflag for jerk_bound?
  double jerk_bound = FLAGS_longitudinal_jerk_upper_bound;
  for (double t = 0.0; t < FLAGS_trajectory_time_length;
       t += FLAGS_trajectory_time_resolution) {
    double jerk = lon_trajectory->Evaluate(3, t);
    double cost = jerk / jerk_bound;
    cost_sqr_sum += cost * cost;
    cost_abs_sum += std::abs(cost);
  }
  return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}

double TrajectoryEvaluator::compute_lon_objective_cost(
    const std::shared_ptr<Trajectory1d>& lon_trajectory,
    const PlanningTarget& planning_target) const {
  double weight_dist_travelled = 10.0;
  double weight_on_reference_speed = 1.0;
  double t_max = lon_trajectory->ParamLength();

  double dist_s =
      lon_trajectory->Evaluate(0, t_max) - lon_trajectory->Evaluate(0, 0.0);

  double speed_cost_sqr_sum = 0.0;
  double speed_cost_abs_sum = 0.0;
  for (double t = 0.0; t < FLAGS_trajectory_time_length;
       t += FLAGS_trajectory_time_resolution) {
    double cost = planning_target.cruise_speed() -
                  lon_trajectory->Evaluate(1, t);
    speed_cost_sqr_sum += cost * cost;
    speed_cost_abs_sum += std::abs(cost);
  }
  double speed_cost = speed_cost_sqr_sum /
                      (speed_cost_abs_sum + FLAGS_lattice_epsilon);
  double dist_travelled_cost = 1.0 / (1.0 + dist_s);
  return (weight_on_reference_speed * speed_cost +
            weight_dist_travelled * dist_travelled_cost) /
         (weight_on_reference_speed + weight_dist_travelled);
}

// TODO(@all): consider putting pointer of reference_line_info and frame
// while constructing trajectory evaluator
double TrajectoryEvaluator::compute_lon_obstacle_cost(
    const std::shared_ptr<Trajectory1d>& lon_trajectory) const {
  double start_time = 0.0;
  double end_time = FLAGS_trajectory_time_length;
  const auto& pt_intervals = pathtime_neighborhood_->GetPathBlockingIntervals(
      start_time, end_time, FLAGS_trajectory_time_resolution);
  // TODO(all) move buffer and sigma to gflags
  double buffer = 1.0;
  double sigma = 0.5;
  double cost_sqr_sum = 0.0;
  double cost_abs_sum = 0.0;
  for (std::size_t i = 0; i < pt_intervals.size(); ++i) {
    const auto& pt_interval = pt_intervals[i];
    if (pt_interval.empty()) {
      continue;
    }

    double t = start_time + i * FLAGS_trajectory_time_resolution;
    double traj_s = lon_trajectory->Evaluate(0, t);

    for (const auto& m : pt_interval) {
      double cost = 0.0;
      if (traj_s > m.first - buffer && traj_s < m.second + buffer) {
        cost = 1.0;
      } else if (traj_s < m.first) {
        double dist = traj_s - m.first + buffer;
        cost = std::exp(-dist * dist / (2.0 * sigma * sigma));
      } else if (traj_s > m.second) {
        double dist = m.second + buffer - traj_s;
        cost = std::exp(-dist * dist / (2.0 * sigma * sigma));
      }
      cost_sqr_sum += cost * cost;
      cost_abs_sum += std::abs(cost);
    }
  }
  return cost_sqr_sum / (cost_abs_sum + FLAGS_lattice_epsilon);
}

std::vector<double> TrajectoryEvaluator::evaluate_per_lonlat_trajectory(
    const PlanningTarget& planning_target,
    const std::vector<apollo::common::SpeedPoint> st_points,
    const std::vector<apollo::common::FrenetFramePoint> sl_points) {
  std::vector<double> ret;
  return ret;
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
 .L $ALICE_ROOT/../src/STAT/AliTreeTrending.cxx+

*/

#include "TStatToolkit.h"
#include "Riostream.h"
#include <iostream>
#include "TSystem.h"
#include "TNamed.h"
#include "TFile.h"
#include "TTree.h"
#include "TPRegexp.h"
#include "TFriendElement.h"
#include "AliExternalInfo.h"
#include "TTreeFormula.h"
#include "TTreeFormulaManager.h"
#include "AliTreeTrending.h"
#include "TEntryList.h"
#include "AliLog.h"
#include "TStyle.h"
#include "TROOT.h"
#include "AliTreeTrending.h"

ClassImp(AliTreeTrending)

using std::cout;
using std::endl;

// constants
const Int_t   kMaxCanvasWidth=3000;
const Int_t   kMinCanvasWidth=1000;
const Int_t   kStepCanvasWidth=500;

AliTreeTrending::AliTreeTrending():
  TNamed(),
  fTree(NULL),
  fUserDescription(NULL),
  fLatexDescription(NULL),
  fStatusGraph(NULL)
{
}
//_____________________________________________________________________________
AliTreeTrending::AliTreeTrending(const char *name, const char *title):
  TNamed(name, title),
  fTree(NULL),
  fUserDescription(NULL),
  fLatexDescription(NULL),
  fStatusGraph(NULL)
{
  //
  //
}

TObjArray * AliTreeTrending::GetTexDescription(TLatex *latex){
  //
  // Get latex version of description
  //
  TObjArray * description= new TObjArray();
  TString sTimestamp  = TString::Format("Creation time:%s",gSystem->GetFromPipe("date").Data());
  TString sUser=TString::Format("User:%s",gSystem->GetFromPipe("echo $USER").Data());
  TString sAlirootVer;
  TString sAliphysicsVer;
  if (gSystem->GetFromPipe("echo $ALICE_VER") == "master" || gSystem->GetFromPipe("echo $ALICE_VER") == ""){
    sAlirootVer = "AliRoot: " + gSystem->GetFromPipe("wdir=`pwd`; cd $ALICE_ROOT/../src; git describe; cd $wdir;");
  }else {
    sAlirootVer = "AliRoot: " + gSystem->GetFromPipe("echo $ALIROOT_VERSION");
  }
  if (gSystem->GetFromPipe("echo $ALIPHYSICS_VER") == "master" || gSystem->GetFromPipe("echo $ALIPHYSICS_VER") == ""){
    sAliphysicsVer = "AliPhysics: " + gSystem->GetFromPipe("wdir=`pwd`; cd $ALICE_PHYSICS/../src; git describe; cd $wdir;");
  }else {
    sAliphysicsVer = "AliPhysics: " + gSystem->GetFromPipe("echo $ALIPHYSICS_VERSION");
  }
  //
  description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY(),sTimestamp.Data()));
  description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-1.1*latex->GetTextSize(),sUser.Data()));
  description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-4.4*latex->GetTextSize(),sAlirootVer.Data()));
  description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-5.5*latex->GetTextSize(),sAliphysicsVer.Data()));
  if (fUserDescription!=NULL){
    Int_t entries=fUserDescription->GetEntries();
    for (Int_t i=0; i<entries; i++){
      description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-((6+i)*1.1)*latex->GetTextSize(),
					       TString::Format("%s: %s",fUserDescription->At(i)->GetName(), fUserDescription->At(i)->GetTitle()).Data()));
    }
  }
  return description;
}

void AliTreeTrending::AddUserDescription(TNamed * description){
  //
  // Add user description
  // AliTreeTrending is owner
  //
  if (fUserDescription==NULL) fUserDescription = new TObjArray;
  fUserDescription->AddLast(description);
}

Bool_t  AliTreeTrending::InitSummaryTrending(TString statusDescription[3], Float_t descriptionSize){
  //
  // Init drawing for the <detector> QA
  // Detector specific qaConfig() has to be called before invoking this function
  //    0.) Make descriptor
  //    1.) Make default canvas - addopt canvas width to the number of entries to draw
  //    3.) compute detector  status graphs

  //
  //   0.) Make descriptor
  //
  if (fTree==NULL) {
    AliError("Input tree not defined");
    return 0;
  }
  if (fTree->GetAlias("tagID")==NULL && fTree->GetBranch("tagID")==NULL) {
    AliError("tagID is not defined");
    return 0;
  }
  TLatex *latex= new TLatex;
  latex->SetX(0.11);
  latex->SetY(0.8);
  latex->SetTextSize(descriptionSize);
  fLatexDescription = GetTexDescription(latex);
  //
  //   1.) Make default canvas - addopt canvas width to the number of entries to draw
  //
  TGraphErrors *gr = (TGraphErrors*) TStatToolkit::MakeGraphSparse(fTree,"tagID:tagID","");
  Int_t numberOfTags = gr->GetN();
  cout<<"number of graph entries: "<<numberOfTags<<endl;
  double SpaceForLegend = 0.;
  Int_t canvas_width  = SpaceForLegend + (numberOfTags+5)*30;
  Int_t canvas_height = 600;
  if ( canvas_width>kMaxCanvasWidth)   canvas_width=kMaxCanvasWidth;
  if ( canvas_width<kMinCanvasWidth)   canvas_width=kMinCanvasWidth;

  fWorkingCanvas = new TCanvas("fWorkingCanvas","fWorkingCanvas",canvas_width,canvas_height);
  fWorkingCanvas->SetGrid(3);
  fWorkingCanvas->cd();
  gPad->SetTicks(1,2);
  // fWorkingCanvas->SetRightMargin(SpaceForLegend/canvas_width);
  double leftlegend  = 1 - 180./fWorkingCanvas->GetWw();
  double rightlegend = 1 - 10./fWorkingCanvas->GetWw();
  //
  // 2.) process config file qaConfig.C to initialize status aliases (outliers etc.), status bar criteria, status lines, ...
  //
  TString sStatusbarVars  = statusDescription[0];
  TString sStatusbarNames = statusDescription[1];
  TString sCriteria       = statusDescription[2];
  cout << "sStatusbarVars = " << sStatusbarVars.Data() << endl;
  cout << "sCriteria      = " << sCriteria.Data() << endl;
  //
  // 3.) compute detector status graphs
  //
  TObjArray* oaStatusbarVars = sStatusbarVars.Tokenize(";");
  TObjArray* oaStatusbarNames = sStatusbarNames.Tokenize(";");
  fStatusGraph = new TObjArray();
  int igr=0;
  for (Int_t vari=oaStatusbarVars->GetEntriesFast()-1; vari>=0; vari--){ // invert the order of the status graphs
    TString sVar = Form("%s:tagID", oaStatusbarVars->At(vari)->GetName()); //e.g. -> dcar:run
    fStatusGraph->Add( TStatToolkit::MakeStatusMultGr(fTree, sVar.Data(),  "", sCriteria.Data(), igr) );
    TString sYtitle = oaStatusbarNames->At(vari)->GetName(); // set better name for y axis of statuspad
    ((TMultiGraph*) fStatusGraph->At(igr))->SetTitle(sYtitle.Data());
    igr++;
  }
  return kTRUE;
}

void  AliTreeTrending::SetDefaultStyle(){
  //
  // ??? Who is owner of drawing style ???
  //
  //
  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetLabelSize(0.04,"x");
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
}

void AliTreeTrending::AppendStatusPad(Float_t padratio, Float_t bottomMargin, Float_t rightMargin){
  //
  // Add status pad and latex description to the canvas (can be pad?)
  // status pad and latex description using data mbers of trendingDraw class
  //
  // 1.) Split canvase
  // 2.) Draw status bar in lower part of canvas
  //
  if (fLatexDescription==NULL){
    AliError("LatexDescription not initialized. Run AliTreeTrending::InitSummaryTrending");
    return;
  }
  TCanvas *c1 = fWorkingCanvas;
  c1->cd();
  fLatexDescription->DrawClone();
  //
  // 1.) Split canvas
  //
  TCanvas* c1_clone = (TCanvas*) c1->Clone("c1_clone");
  c1->Clear();
  // produce new pads
  c1->cd();
  TPad* pad1 = new TPad("pad1", "pad1", 0., padratio, 1., 1.);
  pad1->Draw();
  pad1->SetNumber(1); // so it can be called via "c1->cd(1);"
  c1->cd();
  TPad* pad2 = new TPad("pad2", "pad2", 0., 0., 1., padratio);
  pad2->Draw();
  pad2->SetNumber(2);
  // draw original canvas into first pad
  c1->cd(1);
  c1_clone->DrawClonePad();
  pad1->SetBottomMargin(0.001);
  pad1->SetRightMargin(rightMargin);
  // set up second pad
  c1->cd(2);
  pad2->SetGrid(3);
  pad2->SetTopMargin(0);
  pad2->SetBottomMargin(bottomMargin); // for the long x-axis labels (runnumbers)
  pad2->SetRightMargin(rightMargin);
  //
  //
  const Int_t nvars = fStatusGraph->GetEntriesFast();
  TGraph* grAxis = (TGraph*) ((TMultiGraph*) fStatusGraph->At(0))->GetListOfGraphs()->At(0);
  grAxis->SetMaximum(0.5*nvars+0.5);
  grAxis->SetMinimum(0);
  grAxis->GetYaxis()->SetLabelSize(0);
  grAxis->GetYaxis()->SetTitle("");
  grAxis->SetTitle("");
  Int_t entries = grAxis->GetN();
  grAxis->GetXaxis()->SetLabelSize(5.7*TMath::Min(TMath::Max(5./entries,0.01),0.03));
  grAxis->GetXaxis()->LabelsOption("v");
  grAxis->Draw("ap");
  //
  // draw multigraphs & names of status variables on the y axis
  for (Int_t i=0; i<nvars; i++){
    ((TMultiGraph*) fStatusGraph->At(i))->Draw("p");
    TLatex* ylabel = new TLatex(-0.1, 0.5*i+0.5, ((TMultiGraph*) fStatusGraph->At(i))->GetTitle());
    ylabel->SetTextAlign(32); //hor:right & vert:centered
    ylabel->SetTextSize(0.025/gPad->GetHNDC());
    ylabel->Draw();
  }
  c1->cd(1)->Draw();
}

<commit_msg>ATO-46, ATO-83 - +using std::cout; Needed in  ROOT6<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
 .L $ALICE_ROOT/../src/STAT/AliTreeTrending.cxx+

*/

#include "TStatToolkit.h"
#include "Riostream.h"
#include <iostream>
#include "TSystem.h"
#include "TNamed.h"
#include "TFile.h"
#include "TTree.h"
#include "TPRegexp.h"
#include "TFriendElement.h"
#include "AliExternalInfo.h"
#include "TTreeFormula.h"
#include "TTreeFormulaManager.h"
#include "AliTreeTrending.h"
#include "TEntryList.h"
#include "AliLog.h"
#include "TStyle.h"
#include "TROOT.h"
#include "AliTreeTrending.h"

using std::cout;
using std::cerr;
using std::endl;

ClassImp(AliTreeTrending)

using std::cout;
using std::endl;

// constants
const Int_t   kMaxCanvasWidth=3000;
const Int_t   kMinCanvasWidth=1000;
const Int_t   kStepCanvasWidth=500;

AliTreeTrending::AliTreeTrending():
  TNamed(),
  fTree(NULL),
  fUserDescription(NULL),
  fLatexDescription(NULL),
  fStatusGraph(NULL)
{
}
//_____________________________________________________________________________
AliTreeTrending::AliTreeTrending(const char *name, const char *title):
  TNamed(name, title),
  fTree(NULL),
  fUserDescription(NULL),
  fLatexDescription(NULL),
  fStatusGraph(NULL)
{
  //
  //
}

TObjArray * AliTreeTrending::GetTexDescription(TLatex *latex){
  //
  // Get latex version of description
  //
  TObjArray * description= new TObjArray();
  TString sTimestamp  = TString::Format("Creation time:%s",gSystem->GetFromPipe("date").Data());
  TString sUser=TString::Format("User:%s",gSystem->GetFromPipe("echo $USER").Data());
  TString sAlirootVer;
  TString sAliphysicsVer;
  if (gSystem->GetFromPipe("echo $ALICE_VER") == "master" || gSystem->GetFromPipe("echo $ALICE_VER") == ""){
    sAlirootVer = "AliRoot: " + gSystem->GetFromPipe("wdir=`pwd`; cd $ALICE_ROOT/../src; git describe; cd $wdir;");
  }else {
    sAlirootVer = "AliRoot: " + gSystem->GetFromPipe("echo $ALIROOT_VERSION");
  }
  if (gSystem->GetFromPipe("echo $ALIPHYSICS_VER") == "master" || gSystem->GetFromPipe("echo $ALIPHYSICS_VER") == ""){
    sAliphysicsVer = "AliPhysics: " + gSystem->GetFromPipe("wdir=`pwd`; cd $ALICE_PHYSICS/../src; git describe; cd $wdir;");
  }else {
    sAliphysicsVer = "AliPhysics: " + gSystem->GetFromPipe("echo $ALIPHYSICS_VERSION");
  }
  //
  description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY(),sTimestamp.Data()));
  description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-1.1*latex->GetTextSize(),sUser.Data()));
  description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-4.4*latex->GetTextSize(),sAlirootVer.Data()));
  description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-5.5*latex->GetTextSize(),sAliphysicsVer.Data()));
  if (fUserDescription!=NULL){
    Int_t entries=fUserDescription->GetEntries();
    for (Int_t i=0; i<entries; i++){
      description->AddLast(latex->DrawLatexNDC(latex->GetX(), latex->GetY()-((6+i)*1.1)*latex->GetTextSize(),
					       TString::Format("%s: %s",fUserDescription->At(i)->GetName(), fUserDescription->At(i)->GetTitle()).Data()));
    }
  }
  return description;
}

void AliTreeTrending::AddUserDescription(TNamed * description){
  //
  // Add user description
  // AliTreeTrending is owner
  //
  if (fUserDescription==NULL) fUserDescription = new TObjArray;
  fUserDescription->AddLast(description);
}

Bool_t  AliTreeTrending::InitSummaryTrending(TString statusDescription[3], Float_t descriptionSize){
  //
  // Init drawing for the <detector> QA
  // Detector specific qaConfig() has to be called before invoking this function
  //    0.) Make descriptor
  //    1.) Make default canvas - addopt canvas width to the number of entries to draw
  //    3.) compute detector  status graphs

  //
  //   0.) Make descriptor
  //
  if (fTree==NULL) {
    AliError("Input tree not defined");
    return 0;
  }
  if (fTree->GetAlias("tagID")==NULL && fTree->GetBranch("tagID")==NULL) {
    AliError("tagID is not defined");
    return 0;
  }
  TLatex *latex= new TLatex;
  latex->SetX(0.11);
  latex->SetY(0.8);
  latex->SetTextSize(descriptionSize);
  fLatexDescription = GetTexDescription(latex);
  //
  //   1.) Make default canvas - addopt canvas width to the number of entries to draw
  //
  TGraphErrors *gr = (TGraphErrors*) TStatToolkit::MakeGraphSparse(fTree,"tagID:tagID","");
  Int_t numberOfTags = gr->GetN();
  cout<<"number of graph entries: "<<numberOfTags<<endl;
  double SpaceForLegend = 0.;
  Int_t canvas_width  = SpaceForLegend + (numberOfTags+5)*30;
  Int_t canvas_height = 600;
  if ( canvas_width>kMaxCanvasWidth)   canvas_width=kMaxCanvasWidth;
  if ( canvas_width<kMinCanvasWidth)   canvas_width=kMinCanvasWidth;

  fWorkingCanvas = new TCanvas("fWorkingCanvas","fWorkingCanvas",canvas_width,canvas_height);
  fWorkingCanvas->SetGrid(3);
  fWorkingCanvas->cd();
  gPad->SetTicks(1,2);
  // fWorkingCanvas->SetRightMargin(SpaceForLegend/canvas_width);
  double leftlegend  = 1 - 180./fWorkingCanvas->GetWw();
  double rightlegend = 1 - 10./fWorkingCanvas->GetWw();
  //
  // 2.) process config file qaConfig.C to initialize status aliases (outliers etc.), status bar criteria, status lines, ...
  //
  TString sStatusbarVars  = statusDescription[0];
  TString sStatusbarNames = statusDescription[1];
  TString sCriteria       = statusDescription[2];
  cout << "sStatusbarVars = " << sStatusbarVars.Data() << endl;
  cout << "sCriteria      = " << sCriteria.Data() << endl;
  //
  // 3.) compute detector status graphs
  //
  TObjArray* oaStatusbarVars = sStatusbarVars.Tokenize(";");
  TObjArray* oaStatusbarNames = sStatusbarNames.Tokenize(";");
  fStatusGraph = new TObjArray();
  int igr=0;
  for (Int_t vari=oaStatusbarVars->GetEntriesFast()-1; vari>=0; vari--){ // invert the order of the status graphs
    TString sVar = Form("%s:tagID", oaStatusbarVars->At(vari)->GetName()); //e.g. -> dcar:run
    fStatusGraph->Add( TStatToolkit::MakeStatusMultGr(fTree, sVar.Data(),  "", sCriteria.Data(), igr) );
    TString sYtitle = oaStatusbarNames->At(vari)->GetName(); // set better name for y axis of statuspad
    ((TMultiGraph*) fStatusGraph->At(igr))->SetTitle(sYtitle.Data());
    igr++;
  }
  return kTRUE;
}

void  AliTreeTrending::SetDefaultStyle(){
  //
  // ??? Who is owner of drawing style ???
  //
  //
  gROOT->SetStyle("Plain");
  gStyle->SetPalette(1);
  gStyle->SetLabelSize(0.04,"x");
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);
}

void AliTreeTrending::AppendStatusPad(Float_t padratio, Float_t bottomMargin, Float_t rightMargin){
  //
  // Add status pad and latex description to the canvas (can be pad?)
  // status pad and latex description using data mbers of trendingDraw class
  //
  // 1.) Split canvase
  // 2.) Draw status bar in lower part of canvas
  //
  if (fLatexDescription==NULL){
    AliError("LatexDescription not initialized. Run AliTreeTrending::InitSummaryTrending");
    return;
  }
  TCanvas *c1 = fWorkingCanvas;
  c1->cd();
  fLatexDescription->DrawClone();
  //
  // 1.) Split canvas
  //
  TCanvas* c1_clone = (TCanvas*) c1->Clone("c1_clone");
  c1->Clear();
  // produce new pads
  c1->cd();
  TPad* pad1 = new TPad("pad1", "pad1", 0., padratio, 1., 1.);
  pad1->Draw();
  pad1->SetNumber(1); // so it can be called via "c1->cd(1);"
  c1->cd();
  TPad* pad2 = new TPad("pad2", "pad2", 0., 0., 1., padratio);
  pad2->Draw();
  pad2->SetNumber(2);
  // draw original canvas into first pad
  c1->cd(1);
  c1_clone->DrawClonePad();
  pad1->SetBottomMargin(0.001);
  pad1->SetRightMargin(rightMargin);
  // set up second pad
  c1->cd(2);
  pad2->SetGrid(3);
  pad2->SetTopMargin(0);
  pad2->SetBottomMargin(bottomMargin); // for the long x-axis labels (runnumbers)
  pad2->SetRightMargin(rightMargin);
  //
  //
  const Int_t nvars = fStatusGraph->GetEntriesFast();
  TGraph* grAxis = (TGraph*) ((TMultiGraph*) fStatusGraph->At(0))->GetListOfGraphs()->At(0);
  grAxis->SetMaximum(0.5*nvars+0.5);
  grAxis->SetMinimum(0);
  grAxis->GetYaxis()->SetLabelSize(0);
  grAxis->GetYaxis()->SetTitle("");
  grAxis->SetTitle("");
  Int_t entries = grAxis->GetN();
  grAxis->GetXaxis()->SetLabelSize(5.7*TMath::Min(TMath::Max(5./entries,0.01),0.03));
  grAxis->GetXaxis()->LabelsOption("v");
  grAxis->Draw("ap");
  //
  // draw multigraphs & names of status variables on the y axis
  for (Int_t i=0; i<nvars; i++){
    ((TMultiGraph*) fStatusGraph->At(i))->Draw("p");
    TLatex* ylabel = new TLatex(-0.1, 0.5*i+0.5, ((TMultiGraph*) fStatusGraph->At(i))->GetTitle());
    ylabel->SetTextAlign(32); //hor:right & vert:centered
    ylabel->SetTextSize(0.025/gPad->GetHNDC());
    ylabel->Draw();
  }
  c1->cd(1)->Draw();
}

<|endoftext|>


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

#include <PrimitiveResource.h>
#include <ResourceAttributes.h>
#include <ResponseStatement.h>

#include <internal/ResourceAtrributesConverter.h>

#include <OCPlatform.h>

using OC::QueryParamsMap;
using OC::OCRepresentation;
using OC::ObserveType;

using std::bind;
using std::shared_ptr;
using std::vector;
using std::string;

using namespace std::placeholders;

namespace
{
    using namespace OIC::Service;

    ResponseStatement createResponseStatement(const OCRepresentation& ocRepresentation)
    {
        return ResponseStatement::create(
                ResourceAttributesConverter::fromOCRepresentation(ocRepresentation));
    }

} // unnamed namespace

namespace OIC
{
    namespace Service
    {

        PrimitiveResource::PrimitiveResource(const BaseResourcePtr& ocResource) :
                m_ocResource{ ocResource }
        {
        }

        PrimitiveResource::Ptr PrimitiveResource::create(const BaseResourcePtr& ptr)
        {
            return std::shared_ptr< PrimitiveResource >(new PrimitiveResource{ ptr });
        }

        void PrimitiveResource::requestGet(GetCallback callback)
        {
            m_ocResource->get(QueryParamsMap(), bind(callback, _1, bind(createResponseStatement, _2), _3));
        }

        void PrimitiveResource::requestSet(const ResourceAttributes& attrs, SetCallback callback)
        {
            m_ocResource->put(ResourceAttributesConverter::toOCRepresentation(attrs), QueryParamsMap{},
                    bind(callback, _1, bind(createResponseStatement, _2), _3));
        }

        void PrimitiveResource::requestObserve(ObserveCallback callback)
        {
            m_ocResource->observe(ObserveType::ObserveAll, QueryParamsMap{},
                    bind(callback, _1, bind(createResponseStatement, _2), _3, _4));
        }

        void PrimitiveResource::cancelObserve()
        {
            m_ocResource->cancelObserve();
        }

        bool PrimitiveResource::isObservable() const
        {
            return m_ocResource->isObservable();
        }

        string PrimitiveResource::getUri() const
        {
            return m_ocResource->uri();
        }

        string PrimitiveResource::getHost() const
        {
            return m_ocResource->host();
        }

        vector< string > PrimitiveResource::getTypes() const
        {
            return m_ocResource->getResourceTypes();
        }

        vector< string > PrimitiveResource::getInterfaces() const
        {
            return m_ocResource->getResourceInterfaces();
        }

        void discoverResource(const std::string& host, const std::string& resourceURI,
                OCConnectivityType connectivityType, FindCallback resourceHandler)
        {
            OC::OCPlatform::findResource(host, resourceURI, connectivityType,
                    std::bind(&PrimitiveResource::create, std::placeholders::_1));
        }

    }
}
<commit_msg>Remove unnecessary using-declarations from PrimitiveResource<commit_after>//******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#include <PrimitiveResource.h>
#include <ResourceAttributes.h>
#include <ResponseStatement.h>

#include <internal/ResourceAtrributesConverter.h>

#include <OCPlatform.h>

namespace
{
    using namespace OIC::Service;

    ResponseStatement createResponseStatement(const OC::OCRepresentation& ocRepresentation)
    {
        return ResponseStatement::create(
                ResourceAttributesConverter::fromOCRepresentation(ocRepresentation));
    }

} // unnamed namespace

namespace OIC
{
    namespace Service
    {
        using namespace std::placeholders;

        PrimitiveResource::PrimitiveResource(const BaseResourcePtr& ocResource) :
                m_ocResource{ ocResource }
        {
        }

        PrimitiveResource::Ptr PrimitiveResource::create(const BaseResourcePtr& ptr)
        {
            return std::shared_ptr< PrimitiveResource >(new PrimitiveResource{ ptr });
        }

        void PrimitiveResource::requestGet(GetCallback callback)
        {
            m_ocResource->get(OC::QueryParamsMap(),
                    std::bind(callback, _1, std::bind(createResponseStatement, _2), _3));
        }

        void PrimitiveResource::requestSet(const ResourceAttributes& attrs, SetCallback callback)
        {
            m_ocResource->put(ResourceAttributesConverter::toOCRepresentation(attrs),
                    OC::QueryParamsMap{},
                    std::bind(callback, _1, std::bind(createResponseStatement, _2), _3));
        }

        void PrimitiveResource::requestObserve(ObserveCallback callback)
        {
            m_ocResource->observe(OC::ObserveType::ObserveAll, OC::QueryParamsMap{},
                    bind(callback, _1, bind(createResponseStatement, _2), _3, _4));
        }

        void PrimitiveResource::cancelObserve()
        {
            m_ocResource->cancelObserve();
        }

        bool PrimitiveResource::isObservable() const
        {
            return m_ocResource->isObservable();
        }

        std::string PrimitiveResource::getUri() const
        {
            return m_ocResource->uri();
        }

        std::string PrimitiveResource::getHost() const
        {
            return m_ocResource->host();
        }

        std::vector< std::string > PrimitiveResource::getTypes() const
        {
            return m_ocResource->getResourceTypes();
        }

        std::vector< std::string > PrimitiveResource::getInterfaces() const
        {
            return m_ocResource->getResourceInterfaces();
        }

        void discoverResource(const std::string& host, const std::string& resourceURI,
                OCConnectivityType connectivityType, FindCallback resourceHandler)
        {
            OC::OCPlatform::findResource(host, resourceURI, connectivityType,
                    std::bind(&PrimitiveResource::create, std::placeholders::_1));
        }

    }
}
<|endoftext|>


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

#ifndef MCKL_RANDOM_RDRAND_HPP
#define MCKL_RANDOM_RDRAND_HPP

#include <mckl/random/internal/common.hpp>
#include <immintrin.h>

#ifndef MCKL_RDRAND_NTRIAL_MAX
#define MCKL_RDRAND_NTRIAL_MAX 0
#endif

namespace mckl
{

/// \brief Invoke the RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType, std::size_t W>
inline bool rdrand(UIntType *, std::integral_constant<int, W>);

/// \brief Invoke the 16-bit RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType>
inline bool rdrand(UIntType *rand, std::integral_constant<int, 16>)
{
    unsigned short r;
    int cf = _rdrand16_step(&r);
    *rand = static_cast<UIntType>(r);

    return cf != 0;
}

/// \brief Invoke the 32-bit RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType>
inline bool rdrand(UIntType *rand, std::integral_constant<int, 32>)
{
    unsigned r;
    int cf = _rdrand32_step(&r);
    *rand = static_cast<UIntType>(r);

    return cf != 0;
}

/// \brief Invoke the 64-bit RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType>
inline bool rdrand(UIntType *rand, std::integral_constant<int, 64>)
{
#if defined(MCKL_MSVC) || (defined(MCKL_INTEL) && MCKL_INTEL_VERSION < 1600)
    unsigned __int64 r;
#else
    unsigned long long r;
#endif
    int cf = _rdrand64_step(&r);
    *rand = static_cast<UIntType>(r);

    return cf != 0;
}

/// \brief RDRAND generator
/// \ingroup RDRAND
template <typename ResultType, std::size_t NTrialMax = MCKL_RDRAND_NTRIAL_MAX>
class RDRANDEngine
{
    static_assert(std::is_unsigned<ResultType>::value,
        "**RDRANDEngine** used with ResultType other than unsigned integer "
        "types");

    static_assert(std::numeric_limits<ResultType>::digits == 16 ||
            std::numeric_limits<ResultType>::digits == 32 ||
            std::numeric_limits<ResultType>::digits == 64,
        "**RDRANDEngine** used with ResultType of size other than 16, 32 or "
        "64 bits");

    public:
    using result_type = ResultType;

    template <typename Seed>
    explicit RDRANDEngine(const Seed &)
    {
    }

    template <typename Seed>
    void seed(const Seed &)
    {
    }

    result_type operator()()
    {
        return generate(std::integral_constant<bool, NTrialMax != 0>());
    }

    void discard(std::size_t) {}

    static constexpr result_type min()
    {
        return std::numeric_limits<result_type>::min();
    }

    static constexpr result_type max()
    {
        return std::numeric_limits<result_type>::max();
    }

    friend bool operator==(const RDRANDEngine<ResultType, NTrialMax> &,
        const RDRANDEngine<ResultType, NTrialMax> &)
    {
        return false;
    }

    friend bool operator!=(const RDRANDEngine<ResultType, NTrialMax> &,
        const RDRANDEngine<ResultType, NTrialMax> &)
    {
        return true;
    }

    template <typename CharT, typename CharTraits>
    friend std::basic_ostream<CharT, CharTraits> &operator<<(
        std::basic_ostream<CharT, CharTraits> &os,
        const RDRANDEngine<ResultType, NTrialMax> &)
    {
        return os;
    }

    template <typename CharT, typename CharTraits>
    friend std::basic_istream<CharT, CharTraits> &operator>>(
        std::basic_istream<CharT, CharTraits> &is,
        RDRANDEngine<ResultType, NTrialMax> &)
    {
        return is;
    }

    private:
    result_type generate(std::true_type)
    {
        result_type r;
        std::size_t ntrial = 0;
        while (true) {
            ++ntrial;
            bool success = rdrand<result_type>(
                &r, std::integral_constant<int,
                        std::numeric_limits<result_type>::digits>());
            if (success || ntrial > NTrialMax)
                break;
        }
        runtime_assert(ntrial < NTrialMax,
            "**RDRAND::generator** maximum number of trials exceeded", true);

        return r;
    }

    result_type generate(std::false_type)
    {
        result_type r;
        while (true) {
            bool success = rdrand<result_type>(
                &r, std::integral_constant<int,
                        std::numeric_limits<result_type>::digits>());
            if (success)
                break;
        }

        return r;
    }
}; // class RDRANDEngine

/// \brief C++11 Engine using 16-bit RDRAND instruction
/// \ingroup RDRAND
using RDRAND16 = RDRANDEngine<std::uint16_t>;

/// \brief C++11 Engine using 32-bit RDRAND instruction
/// \ingroup RDRAND
using RDRAND32 = RDRANDEngine<std::uint32_t>;

/// \brief C++11 Engine using 64-bit RDRAND instruction
/// \ingroup RDRAND
using RDRAND64 = RDRANDEngine<std::uint64_t>;

} // namespace mckl

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

#ifndef MCKL_RANDOM_RDRAND_HPP
#define MCKL_RANDOM_RDRAND_HPP

#include <mckl/random/internal/common.hpp>
#include <immintrin.h>

#ifndef MCKL_RDRAND_NTRIAL_MAX
#define MCKL_RDRAND_NTRIAL_MAX 0
#endif

namespace mckl
{

/// \brief Invoke the RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType, std::size_t W>
inline bool rdrand(UIntType *, std::integral_constant<int, W>);

/// \brief Invoke the 16-bit RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType>
inline bool rdrand(UIntType *rand, std::integral_constant<int, 16>)
{
    unsigned short r;
    int cf = _rdrand16_step(&r);
    *rand = static_cast<UIntType>(r);

    return cf != 0;
}

/// \brief Invoke the 32-bit RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType>
inline bool rdrand(UIntType *rand, std::integral_constant<int, 32>)
{
    unsigned r;
    int cf = _rdrand32_step(&r);
    *rand = static_cast<UIntType>(r);

    return cf != 0;
}

/// \brief Invoke the 64-bit RDRAND instruction and return the carry flag
/// \ingroup RDRAND
template <typename UIntType>
inline bool rdrand(UIntType *rand, std::integral_constant<int, 64>)
{
#if defined(MCKL_MSVC) || (defined(MCKL_INTEL) && MCKL_INTEL_VERSION < 1600)
    unsigned __int64 r;
#else
    unsigned long long r;
#endif
    int cf = _rdrand64_step(&r);
    *rand = static_cast<UIntType>(r);

    return cf != 0;
}

/// \brief RDRAND generator
/// \ingroup RDRAND
template <typename ResultType, std::size_t NTrialMax = MCKL_RDRAND_NTRIAL_MAX>
class RDRANDEngine
{
    static_assert(std::is_unsigned<ResultType>::value,
        "**RDRANDEngine** used with ResultType other than unsigned integer "
        "types");

    static_assert(std::numeric_limits<ResultType>::digits == 16 ||
            std::numeric_limits<ResultType>::digits == 32 ||
            std::numeric_limits<ResultType>::digits == 64,
        "**RDRANDEngine** used with ResultType of size other than 16, 32 or "
        "64 bits");

    public:
    using result_type = ResultType;

    RDRANDEngine() {}

    template <typename Seed>
    explicit RDRANDEngine(const Seed &)
    {
    }

    template <typename Seed>
    void seed(const Seed &)
    {
    }

    result_type operator()()
    {
        return generate(std::integral_constant<bool, NTrialMax != 0>());
    }

    void discard(std::size_t) {}

    static constexpr result_type min()
    {
        return std::numeric_limits<result_type>::min();
    }

    static constexpr result_type max()
    {
        return std::numeric_limits<result_type>::max();
    }

    friend bool operator==(const RDRANDEngine<ResultType, NTrialMax> &,
        const RDRANDEngine<ResultType, NTrialMax> &)
    {
        return false;
    }

    friend bool operator!=(const RDRANDEngine<ResultType, NTrialMax> &,
        const RDRANDEngine<ResultType, NTrialMax> &)
    {
        return true;
    }

    template <typename CharT, typename CharTraits>
    friend std::basic_ostream<CharT, CharTraits> &operator<<(
        std::basic_ostream<CharT, CharTraits> &os,
        const RDRANDEngine<ResultType, NTrialMax> &)
    {
        return os;
    }

    template <typename CharT, typename CharTraits>
    friend std::basic_istream<CharT, CharTraits> &operator>>(
        std::basic_istream<CharT, CharTraits> &is,
        RDRANDEngine<ResultType, NTrialMax> &)
    {
        return is;
    }

    private:
    result_type generate(std::true_type)
    {
        result_type r;
        std::size_t ntrial = 0;
        while (true) {
            ++ntrial;
            bool success = rdrand<result_type>(
                &r, std::integral_constant<int,
                        std::numeric_limits<result_type>::digits>());
            if (success || ntrial > NTrialMax)
                break;
        }
        runtime_assert(ntrial < NTrialMax,
            "**RDRAND::generator** maximum number of trials exceeded", true);

        return r;
    }

    result_type generate(std::false_type)
    {
        result_type r;
        while (true) {
            bool success = rdrand<result_type>(
                &r, std::integral_constant<int,
                        std::numeric_limits<result_type>::digits>());
            if (success)
                break;
        }

        return r;
    }
}; // class RDRANDEngine

/// \brief C++11 Engine using 16-bit RDRAND instruction
/// \ingroup RDRAND
using RDRAND16 = RDRANDEngine<std::uint16_t>;

/// \brief C++11 Engine using 32-bit RDRAND instruction
/// \ingroup RDRAND
using RDRAND32 = RDRANDEngine<std::uint32_t>;

/// \brief C++11 Engine using 64-bit RDRAND instruction
/// \ingroup RDRAND
using RDRAND64 = RDRANDEngine<std::uint64_t>;

} // namespace mckl

#endif //  MCKL_RANDOM_RDRAND_HPP
<|endoftext|>