<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"

#include "etl/impl/functions.hpp"

namespace etl {

/*!
 * \brief An unary function expression.
 * \tparam A The unary sub type
 */
template <typename A, typename Impl>
struct unary_function_expr : base_temporary_expr_un<unary_function_expr<A, Impl>, A> {
    using value_type = value_t<A>;                           ///< The type of value of the expression
    using this_type  = unary_function_expr<A, Impl>;               ///< 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 unary_function_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>::value)>
    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>::value)>
    static void check(const A& a, const C& c) {
        static constexpr etl::order order_lhs = decay_traits<A>::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 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>::value, "Function expression only supported for ETL expressions");

        auto& a = this->a();

        standard_evaluator::pre_assign_rhs(a);

        check(a, c);

        Impl::apply(make_temporary(a), c);
    }

    /*!
     * \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 unary_function_expr& expr) {
        return os << Impl::name() << "(" << expr._a << ")";
    }
};

/*!
 * \brief Traits for an unary function expression
 * \tparam A The unary sub type
 */
template <typename A, typename Impl>
struct etl_traits<etl::unary_function_expr<A, Impl>> {
    using expr_t     = etl::unary_function_expr<A, Impl>; ///< 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 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>Fix bug in check<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"

#include "etl/impl/functions.hpp"

namespace etl {

/*!
 * \brief An unary function expression.
 * \tparam A The unary sub type
 */
template <typename A, typename Impl>
struct unary_function_expr : base_temporary_expr_un<unary_function_expr<A, Impl>, A> {
    using value_type = value_t<A>;                           ///< The type of value of the expression
    using this_type  = unary_function_expr<A, Impl>;               ///< 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 unary_function_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>::value)>
    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>::value)>
    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 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>::value, "Function expression only supported for ETL expressions");

        auto& a = this->a();

        standard_evaluator::pre_assign_rhs(a);

        check(a, c);

        Impl::apply(make_temporary(a), c);
    }

    /*!
     * \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 unary_function_expr& expr) {
        return os << Impl::name() << "(" << expr._a << ")";
    }
};

/*!
 * \brief Traits for an unary function expression
 * \tparam A The unary sub type
 */
template <typename A, typename Impl>
struct etl_traits<etl::unary_function_expr<A, Impl>> {
    using expr_t     = etl::unary_function_expr<A, Impl>; ///< 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 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>/*
 * ArcEmu MMORPG Server
 * Copyright (C) 2008-2020 <http://www.ArcEmu.org/>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "StdAfx.h"
#include "LFGPacketHandlers.h"

DEFINE_PACKET_HANDLER_METHOD( LFGProposalResultPacketHandler )
{
	Player *_player = session.GetPlayer();
	CHECK_INWORLD_RETURN

	Arcemu::GamePackets::LFG::CLFGProposalResult result;
	result.deserialize( recv_data );

	LOG_DEBUG( "Received proposal result" );
}

DEFINE_PACKET_HANDLER_METHOD( LFGSetCommentHandler )
{
	Player *_player = session.GetPlayer();
	CHECK_INWORLD_RETURN

	Arcemu::GamePackets::LFG::CLFGSetComment packet;
	packet.deserialize( recv_data );

	_player->Lfgcomment = packet.comment;

	LOG_DEBUG( "Received set comment message" );
}

DEFINE_PACKET_HANDLER_METHOD( LFGPlayerInfoHandler )
{
	Player *_player = session.GetPlayer();
	CHECK_INWORLD_RETURN

	LOG_DEBUG( "Received LFG player info request." );

	PacketBuffer response( SMSG_LFG_PLAYER_INFO, 5 );
	response << uint8( 0 );
	response << uint32( 0 );
	_player->SendPacket( &response );

	LOG_DEBUG( "Sent (empty) LFG player info response." );
}

DEFINE_PACKET_HANDLER_METHOD( LFGPartyInfoHandler )
{
	Player *_player = session.GetPlayer();
	CHECK_INWORLD_RETURN

	LOG_DEBUG( "Received LFG party info request." );

	PacketBuffer response( SMSG_LFG_PARTY_INFO, 1 );
	response << uint8( 0 );
	_player->SendPacket( &response );

	LOG_DEBUG( "Sent (empty) LFG party info response." );
}

DEFINE_PACKET_HANDLER_METHOD( LFGJoinHandler )
{
	Player *_player = session.GetPlayer();
	CHECK_INWORLD_RETURN

	Arcemu::GamePackets::LFG::CLFGJoin packet;
	packet.deserialize( recv_data );

	LOG_DEBUG( "Received LFG join request." );

	// If experimental LFG is not enabled, just send an internal LFG error message
	if( !Config.OptionalConfig.GetBoolDefault( "Experimental", "lfg", false ) )
	{
		PacketBuffer buffer;
		Arcemu::GamePackets::LFG::SLFGJoinResult response;
		response.result = Arcemu::GamePackets::LFG::SLFGJoinResult::LFG_JOIN_INTERNAL_ERROR;
		response.state = 0;
		response.serialize( buffer );
		_player->SendPacket( &buffer );

		LOG_DEBUG( "Sent LFG join result" );

		return;
	}
}

DEFINE_PACKET_HANDLER_METHOD( LFGLeaveHandler )
{
	Player *_player = session.GetPlayer();
	CHECK_INWORLD_RETURN

	LOG_DEBUG( "Received LFG leave request." );
}
<commit_msg>Print roles, and first dungeon entry's details to the console<commit_after>/*
 * ArcEmu MMORPG Server
 * Copyright (C) 2008-2020 <http://www.ArcEmu.org/>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "StdAfx.h"
#include "LFGPacketHandlers.h"

DEFINE_PACKET_HANDLER_METHOD( LFGProposalResultPacketHandler )
{
	Player *_player = session.GetPlayer();
	CHECK_INWORLD_RETURN

	Arcemu::GamePackets::LFG::CLFGProposalResult result;
	result.deserialize( recv_data );

	LOG_DEBUG( "Received proposal result" );
}

DEFINE_PACKET_HANDLER_METHOD( LFGSetCommentHandler )
{
	Player *_player = session.GetPlayer();
	CHECK_INWORLD_RETURN

	Arcemu::GamePackets::LFG::CLFGSetComment packet;
	packet.deserialize( recv_data );

	_player->Lfgcomment = packet.comment;

	LOG_DEBUG( "Received set comment message" );
}

DEFINE_PACKET_HANDLER_METHOD( LFGPlayerInfoHandler )
{
	Player *_player = session.GetPlayer();
	CHECK_INWORLD_RETURN

	LOG_DEBUG( "Received LFG player info request." );

	PacketBuffer response( SMSG_LFG_PLAYER_INFO, 5 );
	response << uint8( 0 );
	response << uint32( 0 );
	_player->SendPacket( &response );

	LOG_DEBUG( "Sent (empty) LFG player info response." );
}

DEFINE_PACKET_HANDLER_METHOD( LFGPartyInfoHandler )
{
	Player *_player = session.GetPlayer();
	CHECK_INWORLD_RETURN

	LOG_DEBUG( "Received LFG party info request." );

	PacketBuffer response( SMSG_LFG_PARTY_INFO, 1 );
	response << uint8( 0 );
	_player->SendPacket( &response );

	LOG_DEBUG( "Sent (empty) LFG party info response." );
}

DEFINE_PACKET_HANDLER_METHOD( LFGJoinHandler )
{
	Player *_player = session.GetPlayer();
	CHECK_INWORLD_RETURN

	Arcemu::GamePackets::LFG::CLFGJoin packet;
	packet.deserialize( recv_data );

	if( packet.dungeons.size() == 0 )
	{
		LOG_DEBUG( "Received LFG join request without dungeons." );
		return;
	}

	LOG_DEBUG( "Received LFG join request. Roles: %u Dungeon1: %u Type1: %u", packet.roles, packet.dungeons[ 0 ].dungeon, packet.dungeons[ 0 ].unk2 );

	// If experimental LFG is not enabled, just send an internal LFG error message
	if( !Config.OptionalConfig.GetBoolDefault( "Experimental", "lfg", false ) )
	{
		PacketBuffer buffer;
		Arcemu::GamePackets::LFG::SLFGJoinResult response;
		response.result = Arcemu::GamePackets::LFG::SLFGJoinResult::LFG_JOIN_INTERNAL_ERROR;
		response.state = 0;
		response.serialize( buffer );
		_player->SendPacket( &buffer );

		LOG_DEBUG( "Sent LFG join result" );

		return;
	}
}

DEFINE_PACKET_HANDLER_METHOD( LFGLeaveHandler )
{
	Player *_player = session.GetPlayer();
	CHECK_INWORLD_RETURN

	LOG_DEBUG( "Received LFG leave request." );
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

using namespace std;

int main(){
    int length;
    cin >> length;

    vector<int> vector(length);

    for (int i = 0; i < length; i++)
    {
        cin >> vector[i];
    }
    for (int i = 0; i < length; i++)
    {
        int j = i-1;
        int intermediate = vector[i];
        while(j >= 0 && vector[j] > intermediate)
        {
            vector[j+1] = vector[j];
            vector[j] = intermediate;
            j--;
        }
        cout << vector[0];
        for (int k = 1; k < length; k++)
        {
            cout << ' ' << vector[k];
        }
        cout << endl;
    }
}<commit_msg>Refactor curly bracket.<commit_after>#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int length;
    cin >> length;

    vector<int> vector(length);

    for (int i = 0; i < length; i++)
    {
        cin >> vector[i];
    }
    for (int i = 0; i < length; i++)
    {
        int j = i-1;
        int intermediate = vector[i];
        while(j >= 0 && vector[j] > intermediate)
        {
            vector[j+1] = vector[j];
            vector[j] = intermediate;
            j--;
        }
        cout << vector[0];
        for (int k = 1; k < length; k++)
        {
            cout << ' ' << vector[k];
        }
        cout << endl;
    }
}<|endoftext|>


<commit_before>#include "Halide.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include "mkl_cblas.h"

#include "sgemm_wrapper.h"
#include "benchmarks.h"

#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
}  // extern "C"
#endif

int main(int, char **)
{
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;

    float a = 3, b = 3;

#if 1
    bool run_mkl = false;
    bool run_tiramisu = false;

    const char* env_mkl = std::getenv("RUN_REF");
    if ((env_mkl != NULL) && (env_mkl[0] == '1'))
	run_mkl = true;
    const char* env_tira = std::getenv("RUN_TIRAMISU");
    if ((env_tira != NULL) && (env_tira[0] == '1'))
	run_tiramisu = true;
#else
    bool run_mkl = true;
    bool run_tiramisu = true;
#endif

	int sizes[27][4], D = 1060 * 1060;

	/************ SIZE_IS_MULTIPLE_OF_TILE 1 ******************/

	sizes[0][0] = 4096;
	sizes[0][1] = 4096;
	sizes[0][2] = 4096;
	sizes[0][3] = 65536 * 4096;

	sizes[1][0] = 128;
	sizes[1][1] = 128;
	sizes[1][2] = 128;
	sizes[1][3] = 128;

	sizes[2][0] = 512;
	sizes[2][1] = 512;
	sizes[2][2] = 512;
	sizes[2][3] = 1024;

	sizes[3][0] = 1024;
	sizes[3][1] = 1024;
	sizes[3][2] = 1024;
	sizes[3][3] = 1024 * 1024;

	sizes[4][0] = 128;
	sizes[4][1] = 128;
	sizes[4][2] = 256;
	sizes[4][3] = D;

	sizes[5][0] = 2048;
	sizes[5][1] = 2048;
	sizes[5][2] = 2048;
	sizes[5][3] = D;

	sizes[6][0] = 2048;
	sizes[6][1] = 2048;
	sizes[6][2] = 1024;
	sizes[6][3] = D;

	sizes[7][0] = 1024;
	sizes[7][1] = 1024;
	sizes[7][2] = 2048;
	sizes[7][3] = D;

	sizes[8][0] = 1024;
	sizes[8][1] = 1024;
	sizes[8][2] = 512;
	sizes[8][3] = D;

	sizes[9][0] = 512;
	sizes[9][1] = 512;
	sizes[9][2] = 1024;
	sizes[9][3] = D;

	sizes[10][0] = 512;
	sizes[10][1] = 512;
	sizes[10][2] = 256;
	sizes[10][3] = D;

	sizes[11][0] = 128;
	sizes[11][1] = 128;
	sizes[11][2] = 2048;
	sizes[11][3] = D;

	sizes[12][0] = 256;
	sizes[12][1] = 256;
	sizes[12][2] = 256;
	sizes[12][3] = D;

	sizes[13][0] = 128;
	sizes[13][1] = 128;
	sizes[13][2] = 512;
	sizes[13][3] = D;

	sizes[14][0] = 128;
	sizes[14][1] = 128;
	sizes[14][2] = 1024;
	sizes[14][3] = D;

	sizes[15][0] = 128;
	sizes[15][1] = 128;
	sizes[15][2] = 64;
	sizes[15][3] = D;

	/**************  SIZE_IS_MULTIPLE_OF_TILE 0  ****************/

	sizes[16][0] = 1060;
	sizes[16][1] = 1060;
	sizes[16][2] = 1060;
	sizes[16][3] = D;

	sizes[17][0] = 4;
	sizes[17][1] = 4;
	sizes[17][2] = 4;
	sizes[17][3] = D;

	sizes[18][0] = 8;
	sizes[18][1] = 8;
	sizes[18][2] = 4;
	sizes[18][3] = D;

	sizes[19][0] = 16;
	sizes[19][1] = 16;
	sizes[19][2] = 4;
	sizes[19][3] = D;

	sizes[20][0] = 16;
	sizes[20][1] = 16;
	sizes[20][2] = 16;
	sizes[20][3] = D;

	sizes[21][0] = 8;
	sizes[21][1] = 8;
	sizes[21][2] = 16;
	sizes[21][3] = D;

	int p, q;

	if (SIZE_IS_MULTIPLE_OF_TILE)
	{
		p = 0;
		q = 16;
	}
	else
	{
		p = 16;
		q = 22;
	}

	for (int j = p; j < q; j++)
	{

	int local_N = sizes[j][0];
	int local_M = sizes[j][1];
	int local_K = sizes[j][2];
	int local_size = sizes[j][3];

	Halide::Buffer<int> SIZES(3, "SIZES");
	Halide::Buffer<float> alpha(1, "alpha");
	Halide::Buffer<float> beta(1, "beta");
	Halide::Buffer<float> A(local_N, local_K, "A");
	Halide::Buffer<float> B(local_K, local_M, "B");
	Halide::Buffer<float> C(local_N, local_M, "C");
	Halide::Buffer<float> C_mkl(local_N, local_M, "C_mkl");

	SIZES(0) = local_N; SIZES(1) = local_M; SIZES(2) = local_K;
	alpha(0) = a; beta(0) = b;
	init_buffer(A, (float)1);
	init_buffer(B, (float)1);
	init_buffer(C, (float)1);
	init_buffer(C_mkl, (float)1);

	// Calling MKL
	{
		long long int   lda, ldb, ldc;
		long long int   rmaxa, cmaxa, rmaxb, cmaxb, rmaxc, cmaxc;
		CBLAS_LAYOUT    layout = CblasRowMajor;
		CBLAS_TRANSPOSE transA = CblasNoTrans, transB = CblasNoTrans;
		long long int ma, na, mb, nb;

		if( transA == CblasNoTrans ) {
			rmaxa = local_M + 1;
			cmaxa = local_K;
			ma    = local_M;
			na    = local_K;
		} else {
			rmaxa = local_K + 1;
			cmaxa = local_M;
			ma    = local_K;
			na    = local_M;
		}
		if( transB == CblasNoTrans ) {
			rmaxb = local_K + 1;
			cmaxb = local_N;
			mb    = local_K;
			nb    = local_N;
		} else {
			rmaxb = local_N + 1;
			cmaxb = local_K;
			mb    = local_N;
			nb    = local_K;
		}
		rmaxc = local_M + 1;
		cmaxc = local_N;
	if (layout == CblasRowMajor) {
		lda=cmaxa;
		ldb=cmaxb;
		ldc=cmaxc;
	} else {
		lda=rmaxa;
		ldb=rmaxb;
		ldc=rmaxc;
	}

        for (int i = 0; i < NB_TESTS; i++)
	{
	    init_buffer(C_mkl, (float)1);
	    auto start1 = std::chrono::high_resolution_clock::now();
	    if (run_mkl == true)
	    	cblas_sgemm(layout, transA, transB, local_M, local_N, local_K, a, (float *) A.raw_buffer()->host, lda, (float *) B.raw_buffer()->host, ldb, b, (float *) C_mkl.raw_buffer()->host, ldc);
	    auto end1 = std::chrono::high_resolution_clock::now();
	    std::chrono::duration<double,std::milli> duration1 = end1 - start1;
	    duration_vector_1.push_back(duration1);
	}
    }

    for (int i = 0; i < NB_TESTS; i++)
    {
	    init_buffer(C, (float)1);
	    auto start2 = std::chrono::high_resolution_clock::now();
 	    if (run_tiramisu == true)
	    	sgemm_tiramisu(SIZES.raw_buffer(), alpha.raw_buffer(), beta.raw_buffer(), A.raw_buffer(), B.raw_buffer(), C.raw_buffer());
	    auto end2 = std::chrono::high_resolution_clock::now();
	    std::chrono::duration<double,std::milli> duration2 = end2 - start2;
	    duration_vector_2.push_back(duration2);
    }

    print_time("performance_CPU.csv", "sgemm",
               {"MKL", "Tiramisu"},
               {median(duration_vector_1), median(duration_vector_2)});

    if (CHECK_CORRECTNESS)
 	if (run_mkl == 1 && run_tiramisu == 1)
	{
		compare_buffers("sgemm", C, C_mkl);
        }

    if (PRINT_OUTPUT)
    {
	std::cout << "Tiramisu sgemm " << std::endl;
	print_buffer(C);
	std::cout << "MKL sgemm " << std::endl;
	print_buffer(C_mkl);
    }
    }
    return 0;
}
<commit_msg>Update sgemm_wrapper.cpp<commit_after>#include "Halide.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include "mkl_cblas.h"

#include "sgemm_wrapper.h"
#include "benchmarks.h"

#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
}  // extern "C"
#endif

int main(int, char **)
{
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_1;
    std::vector<std::chrono::duration<double,std::milli>> duration_vector_2;

    float a = 3, b = 3;

#if 1
    bool run_mkl = false;
    bool run_tiramisu = false;

    const char* env_mkl = std::getenv("RUN_REF");
    if ((env_mkl != NULL) && (env_mkl[0] == '1'))
	run_mkl = true;
    const char* env_tira = std::getenv("RUN_TIRAMISU");
    if ((env_tira != NULL) && (env_tira[0] == '1'))
	run_tiramisu = true;
#else
    bool run_mkl = true;
    bool run_tiramisu = true;
#endif

	int sizes[27][4], D = 1060 * 1060;

	/************ SIZE_IS_MULTIPLE_OF_TILE 1 ******************/

	sizes[0][0] = 4096;
	sizes[0][1] = 4096;
	sizes[0][2] = 4096;
	sizes[0][3] = 65536 * 4096;

	sizes[1][0] = 128;
	sizes[1][1] = 128;
	sizes[1][2] = 128;
	sizes[1][3] = 128;

	sizes[2][0] = 512;
	sizes[2][1] = 512;
	sizes[2][2] = 512;
	sizes[2][3] = 1024;

	sizes[3][0] = 1024;
	sizes[3][1] = 1024;
	sizes[3][2] = 1024;
	sizes[3][3] = 1024 * 1024;

	sizes[4][0] = 128;
	sizes[4][1] = 128;
	sizes[4][2] = 256;
	sizes[4][3] = D;

	sizes[5][0] = 2048;
	sizes[5][1] = 2048;
	sizes[5][2] = 2048;
	sizes[5][3] = D;

	sizes[6][0] = 2048;
	sizes[6][1] = 2048;
	sizes[6][2] = 1024;
	sizes[6][3] = D;

	sizes[7][0] = 1024;
	sizes[7][1] = 1024;
	sizes[7][2] = 2048;
	sizes[7][3] = D;

	sizes[8][0] = 1024;
	sizes[8][1] = 1024;
	sizes[8][2] = 512;
	sizes[8][3] = D;

	sizes[9][0] = 512;
	sizes[9][1] = 512;
	sizes[9][2] = 1024;
	sizes[9][3] = D;

	sizes[10][0] = 512;
	sizes[10][1] = 512;
	sizes[10][2] = 256;
	sizes[10][3] = D;

	sizes[11][0] = 128;
	sizes[11][1] = 128;
	sizes[11][2] = 2048;
	sizes[11][3] = D;

	sizes[12][0] = 256;
	sizes[12][1] = 256;
	sizes[12][2] = 256;
	sizes[12][3] = D;

	sizes[13][0] = 128;
	sizes[13][1] = 128;
	sizes[13][2] = 512;
	sizes[13][3] = D;

	sizes[14][0] = 128;
	sizes[14][1] = 128;
	sizes[14][2] = 1024;
	sizes[14][3] = D;

	sizes[15][0] = 128;
	sizes[15][1] = 128;
	sizes[15][2] = 64;
	sizes[15][3] = D;

	/**************  SIZE_IS_MULTIPLE_OF_TILE 0  ****************/

	sizes[16][0] = 1060;
	sizes[16][1] = 1060;
	sizes[16][2] = 1060;
	sizes[16][3] = D;

	sizes[17][0] = 4;
	sizes[17][1] = 4;
	sizes[17][2] = 4;
	sizes[17][3] = D;

	sizes[18][0] = 8;
	sizes[18][1] = 8;
	sizes[18][2] = 4;
	sizes[18][3] = D;

	sizes[19][0] = 16;
	sizes[19][1] = 16;
	sizes[19][2] = 4;
	sizes[19][3] = D;

	sizes[20][0] = 16;
	sizes[20][1] = 16;
	sizes[20][2] = 16;
	sizes[20][3] = D;

	sizes[21][0] = 8;
	sizes[21][1] = 8;
	sizes[21][2] = 16;
	sizes[21][3] = D;

	int p, q;

	if (SIZE_IS_MULTIPLE_OF_TILE)
	{
		p = 0;
		q = 16;
	}
	else
	{
		p = 16;
		q = 22;
	}

	for (int j = p; j < q; j++)
	{

	int local_N = sizes[j][0];
	int local_M = sizes[j][1];
	int local_K = sizes[j][2];
	int local_size = sizes[j][3];

    Halide::Buffer<int> SIZES(3, "SIZES");
    Halide::Buffer<float> alpha(1, "alpha");
    Halide::Buffer<float> beta(1, "beta");
    Halide::Buffer<float> A(local_N, local_K, "A");
    Halide::Buffer<float> B(local_K, local_M, "B");
    Halide::Buffer<float> C(local_N, local_M, "C");
    Halide::Buffer<float> C_mkl(local_N, local_M, "C_mkl");

    SIZES(0) = local_N; SIZES(1) = local_M; SIZES(2) = local_K;
    alpha(0) = a; beta(0) = b;
    init_buffer(A, (float)1);
    init_buffer(B, (float)1);
    init_buffer(C, (float)1);
    init_buffer(C_mkl, (float)1);

    // Calling MKL
    {
	long long int   lda, ldb, ldc;
      	long long int   rmaxa, cmaxa, rmaxb, cmaxb, rmaxc, cmaxc;
      	CBLAS_LAYOUT    layout = CblasRowMajor;
      	CBLAS_TRANSPOSE transA = CblasNoTrans, transB = CblasNoTrans;
      	long long int    ma, na, mb, nb;

        if( transA == CblasNoTrans ) {
        	rmaxa = local_M + 1;
         	cmaxa = local_K;
		ma    = local_M;
		na    = local_K;
	} else {
		rmaxa = local_K + 1;
		cmaxa = local_M;
		ma    = local_K;
		na    = local_M;
	}
	if( transB == CblasNoTrans ) {
		rmaxb = local_K + 1;
		cmaxb = local_N;
		mb    = local_K;
		nb    = local_N;
	} else {
		rmaxb = local_N + 1;
		cmaxb = local_K;
		mb    = local_N;
		nb    = local_K;
	}
	rmaxc = local_M + 1;
	cmaxc = local_N;
	if (layout == CblasRowMajor) {
		lda=cmaxa;
		ldb=cmaxb;
		ldc=cmaxc;
	} else {
		lda=rmaxa;
		ldb=rmaxb;
		ldc=rmaxc;
	}

        for (int i = 0; i < NB_TESTS; i++)
	{
	    init_buffer(C_mkl, (float)1);
	    auto start1 = std::chrono::high_resolution_clock::now();
	    if (run_mkl == true)
	    	cblas_sgemm(layout, transA, transB, local_M, local_N, local_K, a, (float *) A.raw_buffer()->host, lda, (float *) B.raw_buffer()->host, ldb, b, (float *) C_mkl.raw_buffer()->host, ldc);
	    auto end1 = std::chrono::high_resolution_clock::now();
	    std::chrono::duration<double,std::milli> duration1 = end1 - start1;
	    duration_vector_1.push_back(duration1);
	}
    }

    for (int i = 0; i < NB_TESTS; i++)
    {
	    init_buffer(C, (float)1);
	    auto start2 = std::chrono::high_resolution_clock::now();
 	    if (run_tiramisu == true)
	    	sgemm_tiramisu(SIZES.raw_buffer(), alpha.raw_buffer(), beta.raw_buffer(), A.raw_buffer(), B.raw_buffer(), C.raw_buffer());
	    auto end2 = std::chrono::high_resolution_clock::now();
	    std::chrono::duration<double,std::milli> duration2 = end2 - start2;
	    duration_vector_2.push_back(duration2);
    }

    print_time("performance_CPU.csv", "sgemm",
               {"MKL", "Tiramisu"},
               {median(duration_vector_1), median(duration_vector_2)});

    if (CHECK_CORRECTNESS)
 	if (run_mkl == 1 && run_tiramisu == 1)
	{
		compare_buffers("sgemm", C, C_mkl);
        }

    if (PRINT_OUTPUT)
    {
	std::cout << "Tiramisu sgemm " << std::endl;
	print_buffer(C);
	std::cout << "MKL sgemm " << std::endl;
	print_buffer(C_mkl);
    }
    }
    return 0;
}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2020 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Interface/Modules/Python/CompositeModuleDialog.h>
#include <Modules/Basic/CompositeModuleWithStaticPorts.h>
#include <Interface/Modules/Base/ModuleDialogManager.h>
#include <Interface/Modules/Base/ModuleLogWindow.h>
//#include <Interface/Modules/Base/CustomWidgets/CodeEditorWidgets.h>

using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms::Python;

CompositeModuleDialog::CompositeModuleDialog(const std::string& name, ModuleStateHandle state,
  QWidget* parent /* = 0 */)
  : ModuleDialogGeneric(state, parent)
{
  setupUi(this);
  setWindowTitle(QString::fromStdString(name));
  fixSize();

  addPlainTextEditManager(networkXMLplainTextEdit_, Parameters::NetworkXml);
  addPlainTextEditManager(portReportPlainTextEdit_, Parameters::PortSettings);

  connect(clearPushButton_, &QPushButton::clicked, [this]() { networkXMLplainTextEdit_->clear(); });
  connect(pastePushButton_, &QPushButton::clicked, [this]() { networkXMLplainTextEdit_->setPlainText(QGuiApplication::clipboard()->text()); });

  state_->connectSpecificStateChanged(Parameters::ModuleIdList,
    [this]() { updateModuleUIButtons(); });
}

CompositeModuleDialog::~CompositeModuleDialog()
{
  for (auto& dialog : dialogManagers_)
  {
    dialog->destroyLog();
    dialog->closeOptions();
    dialog->destroyOptions();
  }
}

void CompositeModuleDialog::updateModuleUIButtons()
{
  auto moduleMap = transient_value_cast<SCIRun::Modules::Basic::CompositeModuleInfoMap>(state_->getTransientValue(Parameters::ModuleIdList));

  if (moduleMap.empty())
  {
    for (int i = 0; i < moduleUIgridLayout_->rowCount(); ++i)
    {
      for (int j = 0; j < moduleUIgridLayout_->columnCount(); ++j)
      {
        delete moduleUIgridLayout_->itemAtPosition(i, j)->widget();
      }
    }
    for (auto& dialog : dialogManagers_)
    {
      dialog->destroyLog();
      dialog->closeOptions();
      dialog->destroyOptions();
    }
    dialogManagers_.clear();
    return;
  }

  int i = 0;
  for (const auto& p : moduleMap)
  {
    auto mod = p.second;
    auto dialogs = makeShared<ModuleDialogManager>(mod);
    if (mod->hasUI())
    {
      auto uiLabel = p.first.id_.c_str() + QString(" UI");
      auto ui = new QPushButton(uiLabel);
      moduleUIgridLayout_->addWidget(ui, i, 0);
      dialogs->createOptions();
      auto options = dialogs->options();
      connect(ui, &QPushButton::clicked, [options]() { options->show(); options->raise(); });
    }
    {
      auto logLabel = p.first.id_.c_str() + QString(" log");
      auto log = new QPushButton(logLabel);
      moduleUIgridLayout_->addWidget(log, i, 1);
      auto logWindow = dialogs->setupLogging(nullptr, nullptr, this);
      connect(log, &QPushButton::clicked, [logWindow]() { logWindow->show(); logWindow->raise(); });
    }
    dialogManagers_.push_back(dialogs);
    ++i;
  }
}
<commit_msg>Initial pull<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2020 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Interface/Modules/Python/CompositeModuleDialog.h>
#include <Modules/Basic/CompositeModuleWithStaticPorts.h>
#include <Interface/Modules/Base/ModuleDialogManager.h>
#include <Interface/Modules/Base/ModuleLogWindow.h>
//#include <Interface/Modules/Base/CustomWidgets/CodeEditorWidgets.h>

using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Core::Algorithms::Python;

CompositeModuleDialog::CompositeModuleDialog(const std::string& name, ModuleStateHandle state,
  QWidget* parent /* = 0 */)
  : ModuleDialogGeneric(state, parent)
{
  setupUi(this);
  setWindowTitle(QString::fromStdString(name));
  fixSize();

  addPlainTextEditManager(networkXMLplainTextEdit_, Parameters::NetworkXml);
  addPlainTextEditManager(portReportPlainTextEdit_, Parameters::PortSettings);

  connect(clearPushButton_, &QPushButton::clicked, [this]() { networkXMLplainTextEdit_->clear(); });
  connect(pastePushButton_, &QPushButton::clicked, [this]() { networkXMLplainTextEdit_->setPlainText(QGuiApplication::clipboard()->text()); });

  state_->connectSpecificStateChanged(Parameters::ModuleIdList,
    [this]() { updateModuleUIButtons(); });
}

CompositeModuleDialog::~CompositeModuleDialog()
{
  for (auto& dialog : dialogManagers_)
  {
    dialog->destroyLog();
    dialog->closeOptions();
    dialog->destroyOptions();
  }
}

void CompositeModuleDialog::updateModuleUIButtons()
{
  auto moduleMap = transient_value_cast<SCIRun::Modules::Basic::CompositeModuleInfoMap>(state_->getTransientValue(Parameters::ModuleIdList));

  if (moduleMap.empty())
  {
    for (int i = 0; i < moduleUIgridLayout_->rowCount(); ++i)
    {
      for (int j = 0; j < moduleUIgridLayout_->columnCount(); ++j)
      {
        delete moduleUIgridLayout_->itemAtPosition(i, j)->widget();
      }
    }
    for (auto& dialog : dialogManagers_)
    {
      dialog->destroyLog();
      dialog->closeOptions();
      dialog->destroyOptions();
    }
    dialogManagers_.clear();
    return;
  }

  int i = 0;
  for (const auto& p : moduleMap)
  {
    auto mod = p.second;
    auto dialogs = makeShared<ModuleDialogManager>(mod);
    if (mod->hasUI())
    {
      auto uiLabel = p.first.id_.c_str() + QString(" UI");
      auto ui = new QPushButton(uiLabel);
      moduleUIgridLayout_->addWidget(ui, i, 0);
      dialogs->createOptions();
      auto options = dialogs->options();
      connect(ui, &QPushButton::clicked, [options]() { options->show(); options->raise(); });
      options->pull();
    }
    {
      auto logLabel = p.first.id_.c_str() + QString(" log");
      auto log = new QPushButton(logLabel);
      moduleUIgridLayout_->addWidget(log, i, 1);
      auto logWindow = dialogs->setupLogging(nullptr, nullptr, this);
      connect(log, &QPushButton::clicked, [logWindow]() { logWindow->show(); logWindow->raise(); });
    }
    dialogManagers_.push_back(dialogs);
    ++i;
  }
}
<|endoftext|>


<commit_before>#include "schedulers/schedule.h"

namespace schedulers {

//TODO: Why the compiler asks me for explicit schedulers::?
schedulers::Sched::Sched(game::CarTracker* car_tracker, int horizon)
  : car_tracker_(car_tracker), throttles_(horizon, 0), distance_(0), switch_position_(-1) {
  // There is no state given, so we assume no initial speed, thus distance = 0,
  // but this state of Sched is actually invalid, because no CarState is provided
}

void schedulers::Sched::UpdateDistance(const game::CarState& state) {
  distance_ = car_tracker_->velocity_model().PredictDistance(state.velocity(), throttles_);
}

void schedulers::Sched::UpdateDistance(double new_distance) {
  distance_ = new_distance;
}

int schedulers::Sched::GetTicksToTheRequiredSwitch(const game::CarState& state, double distance_to_switch) {
  if (distance_to_switch < 0)
    return -1;

  int distance = 0;
  game::CarState next = state;
  for (int pos = 0; pos < size(); ++pos) {
    //TODO(minor) I could use the quicker PredictVelocity (waiting for turbo)
    next = car_tracker_->Predict(next, game::Command(throttles_[pos]));

    distance += next.velocity();
    if (distance >= distance_to_switch) {
      if (throttles_[pos] == 0.0) {
        return pos;
      } else {
        // +1 might be too much in some cases, but I am looking for the upper bound
        return pos + 1;
      }
    }
  }
  // Distance longer then the current horizon. We will not care yet.
  return -1;
}

void schedulers::Sched::UpdateSwitchPosition(int switch_position) {
  switch_position_ = switch_position;
}

void schedulers::Sched::RemoveSwitch() {
  UpdateSwitchPosition(-1);
}

void schedulers::Sched::CorrectSwitch(const game::CarState& state, double last_throttle) {
  bool switch_is_planned = (switch_position_ >= 0);
  if (switch_is_planned) {
    if (switch_position_ > 0) {
      last_throttle = throttles_[switch_position_ - 1];
    }
    throttles_[switch_position_] = last_throttle;
  }
}

// Return if succeded (the resulting schedule is safe and switch-correct).
bool schedulers::Sched::TryUpdateSwitchPosition(const game::CarState& state, int new_switch_position,
    double distance_to_switch, double last_throttle) {
  int saved_switch_position = switch_position_;
  double saved_throttle = throttles_[new_switch_position];

  UpdateSwitchPosition(new_switch_position);
  CorrectSwitch(state, last_throttle);

  bool success = IsSafe(state, distance_to_switch, last_throttle);

  if (!success) {
    // Undo if failed
    switch_position_ = saved_switch_position;
    throttles_[new_switch_position] = saved_throttle;
  }

  return success;
}

//TODO: Improve performance by adding "from"
// Whether schedule is safe and switch-correct
bool schedulers::Sched::IsSafe(const game::CarState& state, double distance_to_switch, double last_throttle) {
  bool check_switch = (distance_to_switch >= 0);

  int distance = 0;
  game::CarState next = state;
  // Are all scheduled states safe and switch-correct?
  for (int pos = 0; pos < size(); ++pos) {
    // Are angles safe?
    next = car_tracker_->Predict(next, game::Command(throttles_[pos]));
    if (!car_tracker_->crash_model().IsSafe(next.position().angle())) {
      std::cerr << "here: " << pos << std::endl;
      return false;
    }

    if (check_switch) {
      // Check whether switch is planned in tick from range [0,pos]
      distance += next.velocity();
      if (distance_to_switch <= distance) {
        bool switch_done = (switch_position_ >= 0 && switch_position_ <= pos);
        if (!switch_done) {
          // Switch was supposed to be done before distance_to_switch, but it was not
          std::cerr << "check: " << pos << " " << distance << " " << distance_to_switch << std::endl;
          return false;
        }
      }
    }
  }

  // Check whether the planned switch is correct
  if (check_switch && distance_to_switch <= distance) {
    if (switch_position_ < 0) {
        // We should have switch before the end of the horizon, but we have not
        std::cerr << "bbbb: " << distance << " " << distance_to_switch << std::endl;
        return false;
    }

    // Now, check if there are two consecutive throttles
    if (switch_position_ > 0) {
      last_throttle = throttles_[switch_position_ - 1];
    }
    if (throttles_[switch_position_] != last_throttle) {
      // It still could be safe, but I treat it as incorrect. So it should be first corrected
      // by calling CorrectSwitch().
      std::cerr << "Schedule has incorrect throttles" << std::endl;
      return false;
    }
  }

  // This check is last, for efficiency
  return car_tracker_->IsSafe(next);
}

// No guarantee it is still safe
void schedulers::Sched::ShiftLeft(const game::CarState& state) {
  for (int i = 0; i < size() - 1; ++i) {
    throttles_[i] = throttles_[i + 1];
  }
  throttles_[size() - 1] = 0.0;
  switch_position_ -= 1;

  UpdateDistance(state);
}

void schedulers::Sched::ShiftLeftFillSafe(const game::CarState& state, double distance_to_switch, double last_throttle) {
  ShiftLeft(state);
  // Try 1.0 at the end
  throttles_[size() - 1] = 1.0;
  if (IsSafe(state, distance_to_switch, last_throttle)) {
    return ;
  }

  // If not then try to set the last value + switch at the end.
  // Tt might work if a switch appeared in the horizon
  if (distance_to_switch >= 0) {
    throttles_[size() - 1] = throttles_[size() - 2];

    int saved_switch_position_ = switch_position_;
    switch_position_ = size() - 1;
    if (IsSafe(state, distance_to_switch, last_throttle)) {
      return;
    }
    // Undo switch position change
    switch_position_ = saved_switch_position_;
  }

  // Otherwise, fall back to 0.0
  throttles_[size() - 1] = 0.0;
}

void schedulers::Sched::Reset(const game::CarState& state) {
  for (int i = 0; i<size(); ++i) {
    throttles_[i] = 0;
  }
  switch_position_ = -1;
  UpdateDistance(state);
}

void schedulers::Sched::Print() {
  for (int i = 0; i < size(); ++i) {
    printf("%.1f ", throttles_[i]);
  }
  printf(" [%.1f] s=%d\n", distance_, switch_position_);
}

} // namespace
<commit_msg>Commented out some debug messages<commit_after>#include "schedulers/schedule.h"

namespace schedulers {

//TODO: Why the compiler asks me for explicit schedulers::?
schedulers::Sched::Sched(game::CarTracker* car_tracker, int horizon)
  : car_tracker_(car_tracker), throttles_(horizon, 0), distance_(0), switch_position_(-1) {
  // There is no state given, so we assume no initial speed, thus distance = 0,
  // but this state of Sched is actually invalid, because no CarState is provided
}

void schedulers::Sched::UpdateDistance(const game::CarState& state) {
  distance_ = car_tracker_->velocity_model().PredictDistance(state.velocity(), throttles_);
}

void schedulers::Sched::UpdateDistance(double new_distance) {
  distance_ = new_distance;
}

int schedulers::Sched::GetTicksToTheRequiredSwitch(const game::CarState& state, double distance_to_switch) {
  if (distance_to_switch < 0)
    return -1;

  int distance = 0;
  game::CarState next = state;
  for (int pos = 0; pos < size(); ++pos) {
    //TODO(minor) I could use the quicker PredictVelocity (waiting for turbo)
    next = car_tracker_->Predict(next, game::Command(throttles_[pos]));

    distance += next.velocity();
    if (distance >= distance_to_switch) {
      if (throttles_[pos] == 0.0) {
        return pos;
      } else {
        // +1 might be too much in some cases, but I am looking for the upper bound
        return pos + 1;
      }
    }
  }
  // Distance longer then the current horizon. We will not care yet.
  return -1;
}

void schedulers::Sched::UpdateSwitchPosition(int switch_position) {
  switch_position_ = switch_position;
}

void schedulers::Sched::RemoveSwitch() {
  UpdateSwitchPosition(-1);
}

void schedulers::Sched::CorrectSwitch(const game::CarState& state, double last_throttle) {
  bool switch_is_planned = (switch_position_ >= 0);
  if (switch_is_planned) {
    if (switch_position_ > 0) {
      last_throttle = throttles_[switch_position_ - 1];
    }
    throttles_[switch_position_] = last_throttle;
  }
}

// Return if succeded (the resulting schedule is safe and switch-correct).
bool schedulers::Sched::TryUpdateSwitchPosition(const game::CarState& state, int new_switch_position,
    double distance_to_switch, double last_throttle) {
  int saved_switch_position = switch_position_;
  double saved_throttle = throttles_[new_switch_position];

  UpdateSwitchPosition(new_switch_position);
  CorrectSwitch(state, last_throttle);

  bool success = IsSafe(state, distance_to_switch, last_throttle);

  if (!success) {
    // Undo if failed
    switch_position_ = saved_switch_position;
    throttles_[new_switch_position] = saved_throttle;
  }

  return success;
}

//TODO: Improve performance by adding "from"
// Whether schedule is safe and switch-correct
bool schedulers::Sched::IsSafe(const game::CarState& state, double distance_to_switch, double last_throttle) {
  bool check_switch = (distance_to_switch >= 0);

  int distance = 0;
  game::CarState next = state;
  // Are all scheduled states safe and switch-correct?
  for (int pos = 0; pos < size(); ++pos) {
    // Are angles safe?
    next = car_tracker_->Predict(next, game::Command(throttles_[pos]));
    if (!car_tracker_->crash_model().IsSafe(next.position().angle())) {
      //std::cerr << "here: " << pos << std::endl;
      return false;
    }

    if (check_switch) {
      // Check whether switch is planned in tick from range [0,pos]
      distance += next.velocity();
      if (distance_to_switch <= distance) {
        bool switch_done = (switch_position_ >= 0 && switch_position_ <= pos);
        if (!switch_done) {
          // Switch was supposed to be done before distance_to_switch, but it was not
          //std::cerr << "check: " << pos << " " << distance << " " << distance_to_switch << std::endl;
          return false;
        }
      }
    }
  }

  // Check whether the planned switch is correct
  if (check_switch && distance_to_switch <= distance) {
    if (switch_position_ < 0) {
        // We should have switch before the end of the horizon, but we have not
        //std::cerr << "bbbb: " << distance << " " << distance_to_switch << std::endl;
        return false;
    }

    // Now, check if there are two consecutive throttles
    if (switch_position_ > 0) {
      last_throttle = throttles_[switch_position_ - 1];
    }
    if (throttles_[switch_position_] != last_throttle) {
      // It still could be safe, but I treat it as incorrect. So it should be first corrected
      // by calling CorrectSwitch().
      //std::cerr << "Schedule has incorrect throttles" << std::endl;
      return false;
    }
  }

  // This check is last, for efficiency
  return car_tracker_->IsSafe(next);
}

// No guarantee it is still safe
void schedulers::Sched::ShiftLeft(const game::CarState& state) {
  for (int i = 0; i < size() - 1; ++i) {
    throttles_[i] = throttles_[i + 1];
  }
  throttles_[size() - 1] = 0.0;
  switch_position_ -= 1;

  UpdateDistance(state);
}

void schedulers::Sched::ShiftLeftFillSafe(const game::CarState& state, double distance_to_switch, double last_throttle) {
  ShiftLeft(state);
  // Try 1.0 at the end
  throttles_[size() - 1] = 1.0;
  if (IsSafe(state, distance_to_switch, last_throttle)) {
    return ;
  }

  // If not then try to set the last value + switch at the end.
  // Tt might work if a switch appeared in the horizon
  if (distance_to_switch >= 0) {
    throttles_[size() - 1] = throttles_[size() - 2];

    int saved_switch_position_ = switch_position_;
    switch_position_ = size() - 1;
    if (IsSafe(state, distance_to_switch, last_throttle)) {
      return;
    }
    // Undo switch position change
    switch_position_ = saved_switch_position_;
  }

  // Otherwise, fall back to 0.0
  throttles_[size() - 1] = 0.0;
}

void schedulers::Sched::Reset(const game::CarState& state) {
  for (int i = 0; i<size(); ++i) {
    throttles_[i] = 0;
  }
  switch_position_ = -1;
  UpdateDistance(state);
}

void schedulers::Sched::Print() {
  for (int i = 0; i < size(); ++i) {
    printf("%.1f ", throttles_[i]);
  }
  printf(" [%.1f] s=%d\n", distance_, switch_position_);
}

} // namespace
<|endoftext|>


<commit_before>//
//  yas_operation.cpp
//

#include <atomic>
#include <deque>
#include <mutex>
#include <thread>
#include <vector>
#include "yas_operation.h"

using namespace yas;

#pragma mark - operation

class operation::impl : public base::impl {
   public:
    std::atomic<bool> canceled;
    execution_f execution;
    operation_option_t option;

    impl(execution_f const &exe, operation_option_t &&option)
        : canceled(false), execution(exe), option(std::move(option)) {
    }

    impl(execution_f &&exe, operation_option_t &&option)
        : canceled(false), execution(std::move(exe)), option(std::move(option)) {
    }
};

operation::operation(execution_f const &exe, operation_option_t option)
    : super_class(std::make_unique<impl>(exe, std::move(option))) {
}

operation::operation(execution_f &&exe, operation_option_t opt)
    : super_class(std::make_unique<impl>(std::move(exe), std::move(opt))) {
}

operation::operation(std::nullptr_t) : super_class(nullptr) {
}

void operation::cancel() {
    _cancel();
}

bool operation::is_canceled() const {
    return impl_ptr<impl>()->canceled;
}

operation_option_t const &operation::option() const {
    return impl_ptr<impl>()->option;
}

void operation::_execute() {
    if (auto &exe = impl_ptr<impl>()->execution) {
        if (!is_canceled()) {
            exe(*this);
        }
    }
}

void operation::_cancel() {
    impl_ptr<impl>()->canceled = true;
}

#pragma mark - queue

class operation_queue::impl : public base::impl {
   public:
    impl(size_t const count) : _operations(count) {
    }

    ~impl() {
        cancel();
    }

    void push_back(operation &&op) {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        auto &dq = _operations.at(op.option().priority);
        dq.emplace_back(std::move(op));

        _start_next_operation_if_needed();
    }

    void push_front(operation &&op) {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        auto &dq = _operations.at(op.option().priority);
        dq.emplace_front(std::move(op));

        _start_next_operation_if_needed();
    }

    void cancel(operation const &operation) {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        for (auto &dq : _operations) {
            for (auto &op : dq) {
                if (operation == op) {
                    op.cancel();
                }
            }
        }

        if (_current_operation) {
            if (_current_operation == operation) {
                _current_operation.cancel();
            }
        }
    }

    void cancel() {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        for (auto &dq : _operations) {
            for (auto &op : dq) {
                op.cancel();
            }
            dq.clear();
        }

        if (_current_operation) {
            _current_operation.cancel();
        }
    }

    void wait_until_all_operations_are_finished() {
        while (true) {
            std::lock_guard<std::recursive_mutex> lock(_mutex);

            bool op_exists = _current_operation != nullptr;
            if (!op_exists) {
                for (auto &dq : _operations) {
                    if (dq.size() > 0) {
                        op_exists = true;
                    }
                }
            }

            if (op_exists) {
                if (_suspended) {
                    throw "operation_queue is suspended.";
                }
                std::this_thread::yield();
            } else {
                break;
            }
        }
    }

    void suspend() {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        _suspended = true;
    }

    void resume() {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        if (_suspended) {
            _suspended = false;
            _start_next_operation_if_needed();
        }
    }

   private:
    operation _current_operation = nullptr;
    std::vector<std::deque<operation>> _operations;
    bool _suspended = false;
    mutable std::recursive_mutex _mutex;

    void _start_next_operation_if_needed() {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        if (!_current_operation && !_suspended) {
            operation op{nullptr};

            for (auto &dq : _operations) {
                if (!dq.empty()) {
                    op = dq.front();
                    dq.pop_front();
                    break;
                }
            }

            if (op) {
                _current_operation = op;

                auto weak_ope = to_weak(op);
                auto weak_queue = to_weak(cast<operation_queue>());

                std::thread thread{[weak_ope, weak_queue]() {
                    auto ope = weak_ope.lock();
                    if (ope) {
                        auto &ope_for_queue = static_cast<operation_controllable &>(ope);
                        ope_for_queue._execute();
                        if (auto queue = weak_queue.lock()) {
                            queue.impl_ptr<impl>()->_operation_did_finish(ope);
                        }
                    }
                }};

                thread.detach();
            }
        }
    }

    void _operation_did_finish(operation const &prev_op) {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        if (_current_operation == prev_op) {
            _current_operation = nullptr;
        }

        _start_next_operation_if_needed();
    }
};

operation_queue::operation_queue(size_t const count) : super_class(std::make_unique<impl>(count)) {
}

operation_queue::operation_queue(std::nullptr_t) : super_class(nullptr) {
}

void operation_queue::push_back(operation op) {
    impl_ptr<impl>()->push_back(std::move(op));
}

void operation_queue::push_front(operation op) {
    impl_ptr<impl>()->push_front(std::move(op));
}

void operation_queue::cancel(operation const &op) {
    impl_ptr<impl>()->cancel(op);
}

void operation_queue::cancel() {
    impl_ptr<impl>()->cancel();
}

void operation_queue::wait_until_all_operations_are_finished() {
    impl_ptr<impl>()->wait_until_all_operations_are_finished();
}

void operation_queue::suspend() {
    impl_ptr<impl>()->suspend();
}

void operation_queue::resume() {
    impl_ptr<impl>()->resume();
}
<commit_msg>push cancel<commit_after>//
//  yas_operation.cpp
//

#include <atomic>
#include <deque>
#include <mutex>
#include <thread>
#include <vector>
#include "yas_operation.h"
#include "yas_stl_utils.h"

using namespace yas;

#pragma mark - operation

class operation::impl : public base::impl {
   public:
    std::atomic<bool> canceled;
    execution_f execution;
    operation_option_t option;

    impl(execution_f const &exe, operation_option_t &&option)
        : canceled(false), execution(exe), option(std::move(option)) {
    }

    impl(execution_f &&exe, operation_option_t &&option)
        : canceled(false), execution(std::move(exe)), option(std::move(option)) {
    }
};

operation::operation(execution_f const &exe, operation_option_t option)
    : super_class(std::make_unique<impl>(exe, std::move(option))) {
}

operation::operation(execution_f &&exe, operation_option_t opt)
    : super_class(std::make_unique<impl>(std::move(exe), std::move(opt))) {
}

operation::operation(std::nullptr_t) : super_class(nullptr) {
}

void operation::cancel() {
    _cancel();
}

bool operation::is_canceled() const {
    return impl_ptr<impl>()->canceled;
}

operation_option_t const &operation::option() const {
    return impl_ptr<impl>()->option;
}

void operation::_execute() {
    if (auto &exe = impl_ptr<impl>()->execution) {
        if (!is_canceled()) {
            exe(*this);
        }
    }
}

void operation::_cancel() {
    impl_ptr<impl>()->canceled = true;
}

#pragma mark - queue

class operation_queue::impl : public base::impl {
   public:
    impl(size_t const count) : _operations(count) {
    }

    ~impl() {
        cancel();
    }

    void push_back(operation &&op) {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        auto &cancel_id = op.option().push_cancel_id;

        for (auto &dq : _operations) {
            erase_if(dq, [&cancel_id](auto const &value) { return value.option().push_cancel_id == cancel_id; });
        }

        if (_current_operation) {
            if (_current_operation.option().push_cancel_id == cancel_id) {
                _current_operation.cancel();
            }
        }

        auto &dq = _operations.at(op.option().priority);
        dq.emplace_back(std::move(op));

        _start_next_operation_if_needed();
    }

    void push_front(operation &&op) {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        auto &cancel_id = op.option().push_cancel_id;

        for (auto &dq : _operations) {
            erase_if(dq, [&cancel_id](auto const &value) { return value.option().push_cancel_id == cancel_id; });
        }

        if (_current_operation) {
            if (_current_operation.option().push_cancel_id == cancel_id) {
                _current_operation.cancel();
            }
        }

        auto &dq = _operations.at(op.option().priority);
        dq.emplace_front(std::move(op));

        _start_next_operation_if_needed();
    }

    void cancel(operation const &operation) {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        for (auto &dq : _operations) {
            for (auto &op : dq) {
                if (operation == op) {
                    op.cancel();
                }
            }
        }

        if (_current_operation) {
            if (_current_operation == operation) {
                _current_operation.cancel();
            }
        }
    }

    void cancel() {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        for (auto &dq : _operations) {
            for (auto &op : dq) {
                op.cancel();
            }
            dq.clear();
        }

        if (_current_operation) {
            _current_operation.cancel();
        }
    }

    void wait_until_all_operations_are_finished() {
        while (true) {
            std::lock_guard<std::recursive_mutex> lock(_mutex);

            bool op_exists = _current_operation != nullptr;
            if (!op_exists) {
                for (auto &dq : _operations) {
                    if (dq.size() > 0) {
                        op_exists = true;
                    }
                }
            }

            if (op_exists) {
                if (_suspended) {
                    throw "operation_queue is suspended.";
                }
                std::this_thread::yield();
            } else {
                break;
            }
        }
    }

    void suspend() {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        _suspended = true;
    }

    void resume() {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        if (_suspended) {
            _suspended = false;
            _start_next_operation_if_needed();
        }
    }

   private:
    operation _current_operation = nullptr;
    std::vector<std::deque<operation>> _operations;
    bool _suspended = false;
    mutable std::recursive_mutex _mutex;

    void _start_next_operation_if_needed() {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        if (!_current_operation && !_suspended) {
            operation op{nullptr};

            for (auto &dq : _operations) {
                if (!dq.empty()) {
                    op = dq.front();
                    dq.pop_front();
                    break;
                }
            }

            if (op) {
                _current_operation = op;

                auto weak_ope = to_weak(op);
                auto weak_queue = to_weak(cast<operation_queue>());

                std::thread thread{[weak_ope, weak_queue]() {
                    auto ope = weak_ope.lock();
                    if (ope) {
                        auto &ope_for_queue = static_cast<operation_controllable &>(ope);
                        ope_for_queue._execute();
                        if (auto queue = weak_queue.lock()) {
                            queue.impl_ptr<impl>()->_operation_did_finish(ope);
                        }
                    }
                }};

                thread.detach();
            }
        }
    }

    void _operation_did_finish(operation const &prev_op) {
        std::lock_guard<std::recursive_mutex> lock(_mutex);

        if (_current_operation == prev_op) {
            _current_operation = nullptr;
        }

        _start_next_operation_if_needed();
    }
};

operation_queue::operation_queue(size_t const count) : super_class(std::make_unique<impl>(count)) {
}

operation_queue::operation_queue(std::nullptr_t) : super_class(nullptr) {
}

void operation_queue::push_back(operation op) {
    impl_ptr<impl>()->push_back(std::move(op));
}

void operation_queue::push_front(operation op) {
    impl_ptr<impl>()->push_front(std::move(op));
}

void operation_queue::cancel(operation const &op) {
    impl_ptr<impl>()->cancel(op);
}

void operation_queue::cancel() {
    impl_ptr<impl>()->cancel();
}

void operation_queue::wait_until_all_operations_are_finished() {
    impl_ptr<impl>()->wait_until_all_operations_are_finished();
}

void operation_queue::suspend() {
    impl_ptr<impl>()->suspend();
}

void operation_queue::resume() {
    impl_ptr<impl>()->resume();
}
<|endoftext|>


<commit_before>/*Copyright (c) 2018 PaddlePaddle 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. */

#include "paddle/fluid/operators/detection/density_prior_box_op.h"

namespace paddle {
namespace operators {

class DensityPriorBoxOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("Input"),
                   "Input(Input) of DensityPriorBoxOp should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Image"),
                   "Input(Image) of DensityPriorBoxOp should not be null.");

    auto image_dims = ctx->GetInputDim("Image");
    auto input_dims = ctx->GetInputDim("Input");
    PADDLE_ENFORCE(image_dims.size() == 4, "The layout of image is NCHW.");
    PADDLE_ENFORCE(input_dims.size() == 4, "The layout of input is NCHW.");

    PADDLE_ENFORCE_LT(input_dims[2], image_dims[2],
                      "The height of input must smaller than image.");

    PADDLE_ENFORCE_LT(input_dims[3], image_dims[3],
                      "The width of input must smaller than image.");
    auto variances = ctx->Attrs().Get<std::vector<float>>("variances");

    auto fixed_sizes = ctx->Attrs().Get<std::vector<float>>("fixed_sizes");
    auto fixed_ratios = ctx->Attrs().Get<std::vector<float>>("fixed_ratios");
    auto densities = ctx->Attrs().Get<std::vector<int>>("densities");
    bool flatten = ctx->Attrs().Get<bool>("flatten_to_2d");

    PADDLE_ENFORCE_EQ(fixed_sizes.size(), densities.size(),
                      "The number of fixed_sizes and densities must be equal.");
    size_t num_priors = 0;
    for (size_t i = 0; i < densities.size(); ++i) {
      num_priors += (fixed_ratios.size()) * (pow(densities[i], 2));
    }
    if (!flatten) {
      std::vector<int64_t> dim_vec(4);
      dim_vec[0] = input_dims[2];
      dim_vec[1] = input_dims[3];
      dim_vec[2] = num_priors;
      dim_vec[3] = 4;
      ctx->SetOutputDim("Boxes", framework::make_ddim(dim_vec));
      ctx->SetOutputDim("Variances", framework::make_ddim(dim_vec));
    } else {
      int64_t dim0 = input_dims[2] * input_dims[3] * num_priors;
      ctx->SetOutputDim("Boxes", {dim0, 4});
      ctx->SetOutputDim("Variances", {dim0, 4});
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "Input"), ctx.GetPlace());
  }
};

class DensityPriorBoxOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput(
        "Input",
        "(Tensor, default Tensor<float>), "
        "the input feature data of DensityPriorBoxOp, the layout is NCHW.");
    AddInput("Image",
             "(Tensor, default Tensor<float>), "
             "the input image data of DensityPriorBoxOp, the layout is NCHW.");
    AddOutput("Boxes",
              "(Tensor, default Tensor<float>), the output prior boxes of "
              "DensityPriorBoxOp. The layout is [H, W, num_priors, 4]. "
              "H is the height of input, W is the width of input, num_priors "
              "is the box count of each position.");
    AddOutput("Variances",
              "(Tensor, default Tensor<float>), the expanded variances of "
              "DensityPriorBoxOp. The layout is [H, W, num_priors, 4]. "
              "H is the height of input, W is the width of input, num_priors "
              "is the box count of each position.");
    AddAttr<std::vector<float>>("variances",
                                "(vector<float>) List of variances to be "
                                "encoded in density prior boxes.")
        .AddCustomChecker([](const std::vector<float>& variances) {
          PADDLE_ENFORCE_EQ(variances.size(), 4,
                            "Must and only provide 4 variance.");
          for (size_t i = 0; i < variances.size(); ++i) {
            PADDLE_ENFORCE_GT(variances[i], 0.0,
                              "variance[%d] must be greater than 0.", i);
          }
        });
    AddAttr<bool>("clip", "(bool) Whether to clip out-of-boundary boxes.")
        .SetDefault(true);
    AddAttr<bool>("flatten_to_2d",
                  "(bool) Whether to flatten to 2D and "
                  "the second dim is 4.")
        .SetDefault(false);
    AddAttr<float>(
        "step_w",
        "Density prior boxes step across width, 0.0 for auto calculation.")
        .SetDefault(0.0)
        .AddCustomChecker([](const float& step_w) {
          PADDLE_ENFORCE_GE(step_w, 0.0, "step_w should be larger than 0.");
        });
    AddAttr<float>(
        "step_h",
        "Density prior boxes step across height, 0.0 for auto calculation.")
        .SetDefault(0.0)
        .AddCustomChecker([](const float& step_h) {
          PADDLE_ENFORCE_GE(step_h, 0.0, "step_h should be larger than 0.");
        });

    AddAttr<float>("offset",
                   "(float) "
                   "Density prior boxes center offset.")
        .SetDefault(0.5);
    AddAttr<std::vector<float>>("fixed_sizes",
                                "(vector<float>) List of fixed sizes "
                                "of generated density prior boxes.")
        .SetDefault(std::vector<float>{})
        .AddCustomChecker([](const std::vector<float>& fixed_sizes) {
          for (size_t i = 0; i < fixed_sizes.size(); ++i) {
            PADDLE_ENFORCE_GT(fixed_sizes[i], 0.0,
                              "fixed_sizes[%d] should be larger than 0.", i);
          }
        });

    AddAttr<std::vector<float>>("fixed_ratios",
                                "(vector<float>) List of fixed ratios "
                                "of generated density prior boxes.")
        .SetDefault(std::vector<float>{})
        .AddCustomChecker([](const std::vector<float>& fixed_ratios) {
          for (size_t i = 0; i < fixed_ratios.size(); ++i) {
            PADDLE_ENFORCE_GT(fixed_ratios[i], 0.0,
                              "fixed_ratios[%d] should be larger than 0.", i);
          }
        });

    AddAttr<std::vector<int>>("densities",
                              "(vector<float>) List of densities "
                              "of generated density prior boxes.")
        .SetDefault(std::vector<int>{})
        .AddCustomChecker([](const std::vector<int>& densities) {
          for (size_t i = 0; i < densities.size(); ++i) {
            PADDLE_ENFORCE_GT(densities[i], 0,
                              "densities[%d] should be larger than 0.", i);
          }
        });
    AddComment(R"DOC(
        Density Prior box operator
        Each position of the input produce N density prior boxes, N is determined by
        the count of fixed_ratios, densities, the calculation of N is as follows:
        for density in densities:
        N += size(fixed_ratios)*density^2
        )DOC");
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(
    density_prior_box, ops::DensityPriorBoxOp, ops::DensityPriorBoxOpMaker,
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);

REGISTER_OP_CPU_KERNEL(density_prior_box, ops::DensityPriorBoxOpKernel<float>,
                       ops::DensityPriorBoxOpKernel<double>);
<commit_msg>fix shape check in density_prior_box, test=develop (#21414)<commit_after>/*Copyright (c) 2018 PaddlePaddle 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. */

#include "paddle/fluid/operators/detection/density_prior_box_op.h"

namespace paddle {
namespace operators {

class DensityPriorBoxOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("Input"),
                   "Input(Input) of DensityPriorBoxOp should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Image"),
                   "Input(Image) of DensityPriorBoxOp should not be null.");

    auto image_dims = ctx->GetInputDim("Image");
    auto input_dims = ctx->GetInputDim("Input");
    PADDLE_ENFORCE(image_dims.size() == 4, "The layout of image is NCHW.");
    PADDLE_ENFORCE(input_dims.size() == 4, "The layout of input is NCHW.");

    if (ctx->IsRuntime()) {
      PADDLE_ENFORCE_LT(
          input_dims[2], image_dims[2],
          platform::errors::InvalidArgument(
              "The input tensor Input's height"
              "of DensityPriorBoxOp should be smaller than input tensor Image's"
              "hight. But received Input's height = %d, Image's height = %d",
              input_dims[2], image_dims[2]));

      PADDLE_ENFORCE_LT(
          input_dims[3], image_dims[3],
          platform::errors::InvalidArgument(
              "The input tensor Input's width"
              "of DensityPriorBoxOp should be smaller than input tensor Image's"
              "width. But received Input's width = %d, Image's width = %d",
              input_dims[3], image_dims[3]));
    }
    auto variances = ctx->Attrs().Get<std::vector<float>>("variances");

    auto fixed_sizes = ctx->Attrs().Get<std::vector<float>>("fixed_sizes");
    auto fixed_ratios = ctx->Attrs().Get<std::vector<float>>("fixed_ratios");
    auto densities = ctx->Attrs().Get<std::vector<int>>("densities");
    bool flatten = ctx->Attrs().Get<bool>("flatten_to_2d");

    PADDLE_ENFORCE_EQ(fixed_sizes.size(), densities.size(),
                      "The number of fixed_sizes and densities must be equal.");
    size_t num_priors = 0;
    for (size_t i = 0; i < densities.size(); ++i) {
      num_priors += (fixed_ratios.size()) * (pow(densities[i], 2));
    }
    if (!flatten) {
      std::vector<int64_t> dim_vec(4);
      dim_vec[0] = input_dims[2];
      dim_vec[1] = input_dims[3];
      dim_vec[2] = num_priors;
      dim_vec[3] = 4;
      ctx->SetOutputDim("Boxes", framework::make_ddim(dim_vec));
      ctx->SetOutputDim("Variances", framework::make_ddim(dim_vec));
    } else if (ctx->IsRuntime()) {
      int64_t dim0 = input_dims[2] * input_dims[3] * num_priors;
      ctx->SetOutputDim("Boxes", {dim0, 4});
      ctx->SetOutputDim("Variances", {dim0, 4});
    } else {
      ctx->SetOutputDim("Boxes", {-1, 4});
      ctx->SetOutputDim("Variances", {-1, 4});
    }
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "Input"), ctx.GetPlace());
  }
};

class DensityPriorBoxOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput(
        "Input",
        "(Tensor, default Tensor<float>), "
        "the input feature data of DensityPriorBoxOp, the layout is NCHW.");
    AddInput("Image",
             "(Tensor, default Tensor<float>), "
             "the input image data of DensityPriorBoxOp, the layout is NCHW.");
    AddOutput("Boxes",
              "(Tensor, default Tensor<float>), the output prior boxes of "
              "DensityPriorBoxOp. The layout is [H, W, num_priors, 4]. "
              "H is the height of input, W is the width of input, num_priors "
              "is the box count of each position.");
    AddOutput("Variances",
              "(Tensor, default Tensor<float>), the expanded variances of "
              "DensityPriorBoxOp. The layout is [H, W, num_priors, 4]. "
              "H is the height of input, W is the width of input, num_priors "
              "is the box count of each position.");
    AddAttr<std::vector<float>>("variances",
                                "(vector<float>) List of variances to be "
                                "encoded in density prior boxes.")
        .AddCustomChecker([](const std::vector<float>& variances) {
          PADDLE_ENFORCE_EQ(variances.size(), 4,
                            "Must and only provide 4 variance.");
          for (size_t i = 0; i < variances.size(); ++i) {
            PADDLE_ENFORCE_GT(variances[i], 0.0,
                              "variance[%d] must be greater than 0.", i);
          }
        });
    AddAttr<bool>("clip", "(bool) Whether to clip out-of-boundary boxes.")
        .SetDefault(true);
    AddAttr<bool>("flatten_to_2d",
                  "(bool) Whether to flatten to 2D and "
                  "the second dim is 4.")
        .SetDefault(false);
    AddAttr<float>(
        "step_w",
        "Density prior boxes step across width, 0.0 for auto calculation.")
        .SetDefault(0.0)
        .AddCustomChecker([](const float& step_w) {
          PADDLE_ENFORCE_GE(step_w, 0.0, "step_w should be larger than 0.");
        });
    AddAttr<float>(
        "step_h",
        "Density prior boxes step across height, 0.0 for auto calculation.")
        .SetDefault(0.0)
        .AddCustomChecker([](const float& step_h) {
          PADDLE_ENFORCE_GE(step_h, 0.0, "step_h should be larger than 0.");
        });

    AddAttr<float>("offset",
                   "(float) "
                   "Density prior boxes center offset.")
        .SetDefault(0.5);
    AddAttr<std::vector<float>>("fixed_sizes",
                                "(vector<float>) List of fixed sizes "
                                "of generated density prior boxes.")
        .SetDefault(std::vector<float>{})
        .AddCustomChecker([](const std::vector<float>& fixed_sizes) {
          for (size_t i = 0; i < fixed_sizes.size(); ++i) {
            PADDLE_ENFORCE_GT(fixed_sizes[i], 0.0,
                              "fixed_sizes[%d] should be larger than 0.", i);
          }
        });

    AddAttr<std::vector<float>>("fixed_ratios",
                                "(vector<float>) List of fixed ratios "
                                "of generated density prior boxes.")
        .SetDefault(std::vector<float>{})
        .AddCustomChecker([](const std::vector<float>& fixed_ratios) {
          for (size_t i = 0; i < fixed_ratios.size(); ++i) {
            PADDLE_ENFORCE_GT(fixed_ratios[i], 0.0,
                              "fixed_ratios[%d] should be larger than 0.", i);
          }
        });

    AddAttr<std::vector<int>>("densities",
                              "(vector<float>) List of densities "
                              "of generated density prior boxes.")
        .SetDefault(std::vector<int>{})
        .AddCustomChecker([](const std::vector<int>& densities) {
          for (size_t i = 0; i < densities.size(); ++i) {
            PADDLE_ENFORCE_GT(densities[i], 0,
                              "densities[%d] should be larger than 0.", i);
          }
        });
    AddComment(R"DOC(
        Density Prior box operator
        Each position of the input produce N density prior boxes, N is determined by
        the count of fixed_ratios, densities, the calculation of N is as follows:
        for density in densities:
        N += size(fixed_ratios)*density^2
        )DOC");
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
REGISTER_OPERATOR(
    density_prior_box, ops::DensityPriorBoxOp, ops::DensityPriorBoxOpMaker,
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>);

REGISTER_OP_CPU_KERNEL(density_prior_box, ops::DensityPriorBoxOpKernel<float>,
                       ops::DensityPriorBoxOpKernel<double>);
<|endoftext|>


<commit_before>#ifndef CmdLineInterface_hpp
#define CmdLineInterface_hpp

#include "AppConfig.hpp"

class CmdLineInterface
{
    private:
        //void printUsage(std::string name);
        AppConfig config;
    public:
        CmdLineInterface(int argc, char *argv[]);
        AppConfig getConfig();
};

#endif /* CmdLineInterface_hpp */
<commit_msg>Deleting old files<commit_after><|endoftext|>