<commit_before>/**
@file tty/Defs.hpp
@brief TTY definitions.

@author Tim Howard
@copyright 2013 Tim Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/

#ifndef BEARD_TTY_DEFS_HPP_
#define BEARD_TTY_DEFS_HPP_

#include <Beard/config.hpp>
#include <Beard/keys.hpp>
#include <Beard/geometry.hpp>
#include <Beard/txt/Defs.hpp>

namespace Beard {
namespace tty {

// Forward declarations
struct Cell;

enum class EventType : unsigned;
struct Event;

/**
	@addtogroup tty
	@{
*/

/**
	File descriptor type.
*/
using fd_type = signed;

enum : tty::fd_type {
	/**
		Invalid file descriptor.
	*/
	FD_INVALID = tty::fd_type{-1}
};

/**
	Color + attribute type.
*/
using attr_type = std::uint16_t;

/**
	%Attributes.
*/
namespace Attr {
enum enum_type : tty::attr_type {
	bold		= 0x0100,
	underline	= 0x0200,
	inverted	= 0x0400,
	blink		= 0x0800
};
}

/**
	%Colors.
*/
namespace Color {
enum enum_type : tty::attr_type {
	// NB: Unless c == term_default, c - 1 for actual digit in
	// terminal color (3<c>, 4<c>)

	/** %Terminal default color. */
	term_default	= 0x00,
	black			= 0x01,
	red				= 0x02,
	green			= 0x03,
	yellow			= 0x04,
	blue			= 0x05,
	magenta			= 0x06,
	cyan			= 0x07,
	white			= 0x08
	// TODO: What is the canonical 38/48?
};
}

/**
	%Terminal cell.

	@sa tty::Terminal,
		txt::UTF8Block,
		tty::Attr,
		tty::Color
*/
struct Cell final {
/** @name Properties */ /// @{
	/** UTF-8 code unit block. */
	txt::UTF8Block u8block;

	/** Foreground color and attributes. */
	tty::attr_type attr_fg;
	/** Background color and attributes. */
	tty::attr_type attr_bg;
/// @}
};

/**
	Construct a cell.

	@param u8block Code unit block.
	@param attr_fg Foreground attributes.
	@param attr_bg Background attributes.
*/
inline constexpr tty::Cell
make_cell(
	txt::UTF8Block&& u8block,
	tty::attr_type attr_fg = tty::Color::term_default,
	tty::attr_type attr_bg = tty::Color::term_default
) noexcept {
	return tty::Cell{
		u8block,
		attr_fg,
		attr_bg
	};
}

/** @name Pre-defined cells and frames */ /// @{

static constexpr Cell const
	/**
		Default buffer cell.
	*/
	s_cell_default = make_cell(
		' ',
		tty::Color::term_default,
		tty::Color::term_default
	)
;

static txt::UTF8Block const
	/**
		Single-lined frame.
	*/
	s_frame_single[]{
		{U'┌'},
		{U'─'},
		{U'┐'},
		{U'│'},
		{U'┘'},
		{U'─'},
		{U'└'},
		{U'│'}
	},
	/**
		Heavy single-lined frame.
	*/
	s_frame_single_heavy[]{
		{U'┏'},
		{U'━'},
		{U'┓'},
		{U'┃'},
		{U'┛'},
		{U'━'},
		{U'┗'},
		{U'┃'}
	},
	/**
		Double-lined frame.
	*/
	s_frame_double[]{
		{U'╔'},
		{U'═'},
		{U'╗'},
		{U'║'},
		{U'╝'},
		{U'═'},
		{U'╚'},
		{U'║'}
	}
;

/// @}

/**
	%Event types.

	@sa tty::Event
*/
enum class EventType : unsigned {
	none = 0u,
	resize,
	key_input,
};

/**
	%Event.

	@sa tty::EventType
*/
struct Event final {
	/**
		Type.
	*/
	tty::EventType type;

	/**
		%Event data for tty::EventType::resize.

		@sa tty::Terminal::get_size()
	*/
	struct {
		/** Old size of terminal. */
		Vec2 old_size;
	} resize;

	/**
		%Event data for tty::EventType::key_input.
	*/
	KeyInputData key_input;
};

/** @} */ // end of doc-group tty

} // namespace tty
} // namespace Beard

#endif // BEARD_TTY_DEFS_HPP_
<commit_msg>tty::Event: added member field initializers.<commit_after>/**
@file tty/Defs.hpp
@brief TTY definitions.

@author Tim Howard
@copyright 2013 Tim Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/

#ifndef BEARD_TTY_DEFS_HPP_
#define BEARD_TTY_DEFS_HPP_

#include <Beard/config.hpp>
#include <Beard/keys.hpp>
#include <Beard/geometry.hpp>
#include <Beard/txt/Defs.hpp>

namespace Beard {
namespace tty {

// Forward declarations
struct Cell;

enum class EventType : unsigned;
struct Event;

/**
	@addtogroup tty
	@{
*/

/**
	File descriptor type.
*/
using fd_type = signed;

enum : tty::fd_type {
	/**
		Invalid file descriptor.
	*/
	FD_INVALID = tty::fd_type{-1}
};

/**
	Color + attribute type.
*/
using attr_type = std::uint16_t;

/**
	%Attributes.
*/
namespace Attr {
enum enum_type : tty::attr_type {
	bold		= 0x0100,
	underline	= 0x0200,
	inverted	= 0x0400,
	blink		= 0x0800
};
}

/**
	%Colors.
*/
namespace Color {
enum enum_type : tty::attr_type {
	// NB: Unless c == term_default, c - 1 for actual digit in
	// terminal color (3<c>, 4<c>)

	/** %Terminal default color. */
	term_default	= 0x00,
	black			= 0x01,
	red				= 0x02,
	green			= 0x03,
	yellow			= 0x04,
	blue			= 0x05,
	magenta			= 0x06,
	cyan			= 0x07,
	white			= 0x08
	// TODO: What is the canonical 38/48?
};
}

/**
	%Terminal cell.

	@sa tty::Terminal,
		txt::UTF8Block,
		tty::Attr,
		tty::Color
*/
struct Cell final {
/** @name Properties */ /// @{
	/** UTF-8 code unit block. */
	txt::UTF8Block u8block;

	/** Foreground color and attributes. */
	tty::attr_type attr_fg;
	/** Background color and attributes. */
	tty::attr_type attr_bg;
/// @}
};

/**
	Construct a cell.

	@param u8block Code unit block.
	@param attr_fg Foreground attributes.
	@param attr_bg Background attributes.
*/
inline constexpr tty::Cell
make_cell(
	txt::UTF8Block&& u8block,
	tty::attr_type attr_fg = tty::Color::term_default,
	tty::attr_type attr_bg = tty::Color::term_default
) noexcept {
	return tty::Cell{
		u8block,
		attr_fg,
		attr_bg
	};
}

/** @name Pre-defined cells and frames */ /// @{

static constexpr Cell const
	/**
		Default buffer cell.
	*/
	s_cell_default = make_cell(
		' ',
		tty::Color::term_default,
		tty::Color::term_default
	)
;

static txt::UTF8Block const
	/**
		Single-lined frame.
	*/
	s_frame_single[]{
		{U'┌'},
		{U'─'},
		{U'┐'},
		{U'│'},
		{U'┘'},
		{U'─'},
		{U'└'},
		{U'│'}
	},
	/**
		Heavy single-lined frame.
	*/
	s_frame_single_heavy[]{
		{U'┏'},
		{U'━'},
		{U'┓'},
		{U'┃'},
		{U'┛'},
		{U'━'},
		{U'┗'},
		{U'┃'}
	},
	/**
		Double-lined frame.
	*/
	s_frame_double[]{
		{U'╔'},
		{U'═'},
		{U'╗'},
		{U'║'},
		{U'╝'},
		{U'═'},
		{U'╚'},
		{U'║'}
	}
;

/// @}

/**
	%Event types.

	@sa tty::Event
*/
enum class EventType : unsigned {
	none = 0u,
	resize,
	key_input,
};

/**
	%Event.

	@sa tty::EventType
*/
struct Event final {
	/**
		Type.
	*/
	tty::EventType type{tty::EventType::none};

	/**
		%Event data for tty::EventType::resize.

		@sa tty::Terminal::get_size()
	*/
	struct {
		/** Old size of terminal. */
		Vec2 old_size{0, 0};
	} resize{};

	/**
		%Event data for tty::EventType::key_input.
	*/
	KeyInputData key_input{};
};

/** @} */ // end of doc-group tty

} // namespace tty
} // namespace Beard

#endif // BEARD_TTY_DEFS_HPP_
<|endoftext|>


<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once

#include <armnn/NetworkFwd.hpp>
#include <armnn/DescriptorsFwd.hpp>
#include <armnn/TensorFwd.hpp>
#include <armnn/Optional.hpp>

#include <armnn/Types.hpp>

#include <memory>
#include <vector>

namespace armnn
{

/// @brief An input connection slot for a layer.
/// The input slot can be connected to an output slot of the preceding layer in the graph.
/// Only one connection to the input slot is allowed.
class IInputSlot
{
public:
    virtual const IOutputSlot* GetConnection() const = 0;
    virtual IOutputSlot* GetConnection() = 0;

protected:
   /// Not user deletable.
    ~IInputSlot() {}
};

/// @brief An output connection slot for a layer.
/// The output slot may be connected to 1 or more input slots of subsequent layers in the graph.
class IOutputSlot
{
public:
    virtual unsigned int GetNumConnections() const = 0;
    virtual const IInputSlot* GetConnection(unsigned int index) const = 0;
    virtual IInputSlot* GetConnection(unsigned int index) = 0;

    virtual void SetTensorInfo(const TensorInfo& tensorInfo) = 0;
    virtual const TensorInfo& GetTensorInfo() const = 0;
    virtual bool IsTensorInfoSet() const = 0;

    virtual int Connect(IInputSlot& destination) = 0;
    virtual void Disconnect(IInputSlot& slot) = 0;

protected:
    /// Not user deletable.
    ~IOutputSlot() {}
};

/// @brief Interface for a layer that is connectable to other layers via InputSlots and OutputSlots.
class IConnectableLayer
{
public:
    virtual const char* GetName() const = 0;

    virtual unsigned int GetNumInputSlots() const = 0;
    virtual unsigned int GetNumOutputSlots() const = 0;

    virtual const IInputSlot& GetInputSlot(unsigned int index) const = 0;
    virtual IInputSlot& GetInputSlot(unsigned int index) = 0;

    virtual const IOutputSlot& GetOutputSlot(unsigned int index) const = 0;
    virtual IOutputSlot& GetOutputSlot(unsigned int index) = 0;

    virtual std::vector<TensorShape> InferOutputShapes(const std::vector<TensorShape>& inputShapes) const = 0;

    virtual LayerGuid GetGuid() const = 0;
protected:
      /// Objects are not deletable via the handle
    ~IConnectableLayer() {}
};

using INetworkPtr = std::unique_ptr<INetwork, void(*)(INetwork* network)>;

/// Main network class which provides the interface for building up a neural network.
/// This object is subsequently required by the IRuntime::Load() method.
class INetwork
{
public:
    static INetwork* CreateRaw();
    static INetworkPtr Create();
    static void Destroy(INetwork* network);

    virtual Status PrintGraph() = 0;

    /// Adds an input layer to the network.
    /// @param id - User generated id to uniquely identify a particular input. The same id needs to be specified.
    /// when passing the inputs to the IRuntime::EnqueueWorkload() function.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddInputLayer(LayerBindingId id, const char* name = nullptr) = 0;

    /// Adds a 2D convolution layer to the network.
    /// @param convolution2dDescriptor - Description of the 2D convolution layer.
    /// @param weights - Tensor for the weights data.
    /// @param biases - (Optional) Tensor for the bias data. Must match the output tensor shape.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
        const ConstTensor& weights,
        const char* name = nullptr) = 0;

    virtual IConnectableLayer* AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
        const ConstTensor& weights,
        const ConstTensor& biases,
        const char* name = nullptr) = 0;

    /// Adds a 2D depthwise convolution layer to the network.
    /// @param convolution2dDescriptor - Description of the 2D depthwise convolution layer.
    /// @param weights - Tensor for the weights data. Expected format: [1, outputChannels, height, width].
    /// @param biases (Optional) - Tensor for the bias data. Must match the output tensor shape.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddDepthwiseConvolution2dLayer(
        const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
        const ConstTensor& weights,
        const char* name = nullptr) = 0;

    virtual IConnectableLayer* AddDepthwiseConvolution2dLayer(
        const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
        const ConstTensor& weights,
        const ConstTensor& biases,
        const char* name = nullptr) = 0;

    /// Adds a fully connected layer to the network.
    /// @param fullyConnectedDescriptor - Description of the fully connected layer.
    /// @param weights - Tensor for the weights data.
    /// @param biases - (Optional) Tensor for the bias data.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
        const ConstTensor& weights,
        const char* name = nullptr) = 0;

    virtual IConnectableLayer* AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
        const ConstTensor& weights,
        const ConstTensor& biases,
        const char* name = nullptr) = 0;

    /// Adds a permute layer to the network.
    /// @param permuteDescriptor - PermuteDescriptor to configure the permute.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddPermuteLayer(const PermuteDescriptor& permuteDescriptor,
                                               const char* name = nullptr) = 0;

    /// Adds a batch to space ND layer to the network.
    /// @param batchToSpaceNdDescriptor - Description of the layer.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddBatchToSpaceNdLayer(const BatchToSpaceNdDescriptor& batchToSpaceNdDescriptor,
                                                      const char* name = nullptr) = 0;

    /// Adds a pooling layer to the network.
    /// @param pooling2dDescriptor - Pooling2dDescriptor to configure the pooling.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddPooling2dLayer(const Pooling2dDescriptor& pooling2dDescriptor,
        const char* name = nullptr) = 0;

    /// Adds an activation layer to the network.
    /// @param activationDescriptor - ActivationDescriptor to configure the activation.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddActivationLayer(const ActivationDescriptor& activationDescriptor,
        const char* name = nullptr) = 0;

    /// Adds a normalization layer to the network.
    /// @param normalizationDescriptor - NormalizationDescriptor to configure the normalization.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddNormalizationLayer(const NormalizationDescriptor& normalizationDescriptor,
        const char* name = nullptr) = 0;

    /// Adds a softmax layer to the network.
    /// @param softmaxDescriptor - SoftmaxDescriptor to configure the softmax.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddSoftmaxLayer(const SoftmaxDescriptor& softmaxDescriptor,
        const char* name = nullptr) = 0;

    /// Adds a splitter layer to the network.
    /// @param splitterDescriptor - WindowsDescriptor to configure the splitting process.
    ///                             Number of Views must be equal to the number of outputs,
    ///                             and their order must match - e.g. first view corresponds to
    ///                             the first output, second view to the second output, etc....
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddSplitterLayer(const ViewsDescriptor& splitterDescriptor
        , const char* name = nullptr) = 0;

    /// Adds a merger layer to the network.
    /// @param mergerDescriptor - WindowsDescriptor to configure the merging process. Number of Views must be equal to
    ///                           the number of inputs, and their order must match - e.g. first view corresponds to
    ///                           the first input, second view to the second input, etc....
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddMergerLayer(const OriginsDescriptor& mergerDescriptor,
        const char* name = nullptr) = 0;

    /// Adds an addition layer to the network.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddAdditionLayer(const char* name = nullptr) = 0;

    /// Adds a multiplication layer to the network.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddMultiplicationLayer(const char* name = nullptr) = 0;

    /// Adds a batch normalization layer to the network.
    /// @param mean - Pre-calculated mean for each channel.
    /// @param variance - Pre-calculated variance for each channel.
    /// @param beta - Per-channel additive factor.
    /// @param gamma - Per-channel multiplicative factor.
    /// @return - Interface for configuring the layer.
    /// @param name - Optional name for the layer.
    virtual IConnectableLayer* AddBatchNormalizationLayer(const BatchNormalizationDescriptor& desc,
        const ConstTensor& mean,
        const ConstTensor& variance,
        const ConstTensor& beta,
        const ConstTensor& gamma,
        const char* name = nullptr) = 0;

    /// Adds a resize bilinear layer to the network.
    /// @param resizeDesc - Parameters for the resize operation.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddResizeBilinearLayer(const ResizeBilinearDescriptor& resizeDesc,
                                                      const char* name = nullptr) = 0;

    /// Adds an L2 normalization layer to the network.
    /// Normalization is performed along dimension 1, but requires a 4d input.
    /// @param desc - Parameters for the L2 normalization operation.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddL2NormalizationLayer(const L2NormalizationDescriptor& desc,
                                                       const char* name = nullptr) = 0;

    /// Adds a layer with no inputs and a single output, which always corresponds to
    /// the passed in constant tensor.
    /// @param input - Tensor to be provided as the only output of the layer. The layer will maintain
    ///                its own copy of the tensor data, meaning the memory referenced by @a input can
    ///                be freed or reused after this function is called.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddConstantLayer(const ConstTensor& input,
        const char* name = nullptr) = 0;

    /// Adds a reshape layer to the network.
    /// @param reshapeDescriptor - Parameters for the reshape operation.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddReshapeLayer(const ReshapeDescriptor& reshapeDescriptor,
                                               const char* name = nullptr) = 0;

    /// Adds a space to batch layer to the network.
    /// @param spaceToBatchNdDescriptor - Parameters for the space to batch operation.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddSpaceToBatchNdLayer(const SpaceToBatchNdDescriptor& spaceToBatchNdDescriptor,
                                                      const char* name = nullptr) = 0;

    /// Adds a floor layer to the network.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddFloorLayer(const char* name = nullptr) = 0;

    /// Adds an output layer to the network.
    /// @param id - User generated id to uniquely identify a particular output. The same id needs to be specified
    /// when passing the outputs to the IRuntime::EnqueueWorkload() function.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddOutputLayer(LayerBindingId id, const char* name = nullptr) = 0;

    /// Add a Lstm layer to the network
    /// @param descriptor Parameters for the Lstm operation
    /// @param name Optional name for the layer
    /// @return Interface for configuring the layer.
    virtual IConnectableLayer* AddLstmLayer(const LstmDescriptor& descriptor,
                                            const LstmInputParams& params,
                                            const char* name = nullptr) = 0;

    /// Adds a division layer to the network.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddDivisionLayer(const char* name = nullptr) = 0;

    /// Adds a subtraction layer to the network.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddSubtractionLayer(const char* name = nullptr) = 0;

    /// Add a Mean layer to the network.
    /// @param meanDescriptor - Parameters for the mean operation.
    /// @param name - Optional name for the layer.
    /// @ return - Interface for configuring the layer.
    virtual IConnectableLayer* AddMeanLayer(const MeanDescriptor& meanDescriptor, const char* name = nullptr) = 0;

    /// Adds a fully pad layer to the network.
    /// @param paddings - n by 2 tensor, where n is the rank of the input tensor,
    ///                   such that paddings[i,0] indicates the amount of padding to add in front of dimonsion i, and
    ///                   paddings[i,1] indicates the amount of padding to add after the end of dimension i
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddPadLayer(const PadDescriptor& padDescriptor,
                                           const char* name = nullptr) = 0;

    /// Adds a strided slice layer to the network.
    /// @param StridedSliceDescriptor - Parameters for the strided slice operation.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddStridedSliceLayer(const StridedSliceDescriptor& stridedSliceDescriptor,
                                                    const char* name = nullptr) = 0;

protected:
    ~INetwork() {}
};

using IOptimizedNetworkPtr = std::unique_ptr<IOptimizedNetwork, void(*)(IOptimizedNetwork* network)>;

class IOptimizedNetwork
{
public:
    static void Destroy(IOptimizedNetwork* network);

    virtual Status PrintGraph() = 0;
    virtual Status SerializeToDot(std::ostream& stream) const = 0;

protected:
    ~IOptimizedNetwork() {}
};

struct OptimizerOptions
{
    OptimizerOptions() : m_ReduceFp32ToFp16(false) {}

    OptimizerOptions(bool reduceFp32ToFp16)
        : m_ReduceFp32ToFp16(reduceFp32ToFp16)
    {
    }

    // Reduce Fp32 data to Fp16 for faster processing
    bool m_ReduceFp32ToFp16;
};

/// Create an optimized version of the network
/// @param network INetwork description of the network to be optimized.
/// @param backendPreferences The choice of the backend ordered by user preferences.
/// @param deviceSpec DeviceSpec object as queried from the runtime. See IRuntime::GetDeviceSpec()
/// @param errMessages if there are failures or warnings a string describing same will be added to the vector
/// @param options OptimizerOptions object with optimizer configuration options
/// @return An IOptimizedNetworkPtr interface to the optimized network, throws an exception derived from
/// armnn::Exception if process fails.

IOptimizedNetworkPtr Optimize(const INetwork& network,
                              const std::vector<BackendId>& backendPreferences,
                              const IDeviceSpec& deviceSpec,
                              const OptimizerOptions& options = OptimizerOptions(),
                              Optional<std::vector<std::string>&> errMessages = EmptyOptional());
} //namespace armnn
<commit_msg>Fix documentation for depthwise convolution<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once

#include <armnn/NetworkFwd.hpp>
#include <armnn/DescriptorsFwd.hpp>
#include <armnn/TensorFwd.hpp>
#include <armnn/Optional.hpp>

#include <armnn/Types.hpp>

#include <memory>
#include <vector>

namespace armnn
{

/// @brief An input connection slot for a layer.
/// The input slot can be connected to an output slot of the preceding layer in the graph.
/// Only one connection to the input slot is allowed.
class IInputSlot
{
public:
    virtual const IOutputSlot* GetConnection() const = 0;
    virtual IOutputSlot* GetConnection() = 0;

protected:
   /// Not user deletable.
    ~IInputSlot() {}
};

/// @brief An output connection slot for a layer.
/// The output slot may be connected to 1 or more input slots of subsequent layers in the graph.
class IOutputSlot
{
public:
    virtual unsigned int GetNumConnections() const = 0;
    virtual const IInputSlot* GetConnection(unsigned int index) const = 0;
    virtual IInputSlot* GetConnection(unsigned int index) = 0;

    virtual void SetTensorInfo(const TensorInfo& tensorInfo) = 0;
    virtual const TensorInfo& GetTensorInfo() const = 0;
    virtual bool IsTensorInfoSet() const = 0;

    virtual int Connect(IInputSlot& destination) = 0;
    virtual void Disconnect(IInputSlot& slot) = 0;

protected:
    /// Not user deletable.
    ~IOutputSlot() {}
};

/// @brief Interface for a layer that is connectable to other layers via InputSlots and OutputSlots.
class IConnectableLayer
{
public:
    virtual const char* GetName() const = 0;

    virtual unsigned int GetNumInputSlots() const = 0;
    virtual unsigned int GetNumOutputSlots() const = 0;

    virtual const IInputSlot& GetInputSlot(unsigned int index) const = 0;
    virtual IInputSlot& GetInputSlot(unsigned int index) = 0;

    virtual const IOutputSlot& GetOutputSlot(unsigned int index) const = 0;
    virtual IOutputSlot& GetOutputSlot(unsigned int index) = 0;

    virtual std::vector<TensorShape> InferOutputShapes(const std::vector<TensorShape>& inputShapes) const = 0;

    virtual LayerGuid GetGuid() const = 0;
protected:
      /// Objects are not deletable via the handle
    ~IConnectableLayer() {}
};

using INetworkPtr = std::unique_ptr<INetwork, void(*)(INetwork* network)>;

/// Main network class which provides the interface for building up a neural network.
/// This object is subsequently required by the IRuntime::Load() method.
class INetwork
{
public:
    static INetwork* CreateRaw();
    static INetworkPtr Create();
    static void Destroy(INetwork* network);

    virtual Status PrintGraph() = 0;

    /// Adds an input layer to the network.
    /// @param id - User generated id to uniquely identify a particular input. The same id needs to be specified.
    /// when passing the inputs to the IRuntime::EnqueueWorkload() function.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddInputLayer(LayerBindingId id, const char* name = nullptr) = 0;

    /// Adds a 2D convolution layer to the network.
    /// @param convolution2dDescriptor - Description of the 2D convolution layer.
    /// @param weights - Tensor for the weights data.
    /// @param biases - (Optional) Tensor for the bias data. Must match the output tensor shape.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
        const ConstTensor& weights,
        const char* name = nullptr) = 0;

    virtual IConnectableLayer* AddConvolution2dLayer(const Convolution2dDescriptor& convolution2dDescriptor,
        const ConstTensor& weights,
        const ConstTensor& biases,
        const char* name = nullptr) = 0;

    /// Adds a 2D depthwise convolution layer to the network.
    /// @param convolution2dDescriptor - Description of the 2D depthwise convolution layer.
    /// @param weights - Tensor for the weights. Expected format: [channelMultiplier, inputChannels, height, width].
    /// @param biases (Optional) - Tensor for the bias data. Must match the output tensor shape.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddDepthwiseConvolution2dLayer(
        const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
        const ConstTensor& weights,
        const char* name = nullptr) = 0;

    virtual IConnectableLayer* AddDepthwiseConvolution2dLayer(
        const DepthwiseConvolution2dDescriptor& convolution2dDescriptor,
        const ConstTensor& weights,
        const ConstTensor& biases,
        const char* name = nullptr) = 0;

    /// Adds a fully connected layer to the network.
    /// @param fullyConnectedDescriptor - Description of the fully connected layer.
    /// @param weights - Tensor for the weights data.
    /// @param biases - (Optional) Tensor for the bias data.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
        const ConstTensor& weights,
        const char* name = nullptr) = 0;

    virtual IConnectableLayer* AddFullyConnectedLayer(const FullyConnectedDescriptor& fullyConnectedDescriptor,
        const ConstTensor& weights,
        const ConstTensor& biases,
        const char* name = nullptr) = 0;

    /// Adds a permute layer to the network.
    /// @param permuteDescriptor - PermuteDescriptor to configure the permute.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddPermuteLayer(const PermuteDescriptor& permuteDescriptor,
                                               const char* name = nullptr) = 0;

    /// Adds a batch to space ND layer to the network.
    /// @param batchToSpaceNdDescriptor - Description of the layer.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddBatchToSpaceNdLayer(const BatchToSpaceNdDescriptor& batchToSpaceNdDescriptor,
                                                      const char* name = nullptr) = 0;

    /// Adds a pooling layer to the network.
    /// @param pooling2dDescriptor - Pooling2dDescriptor to configure the pooling.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddPooling2dLayer(const Pooling2dDescriptor& pooling2dDescriptor,
        const char* name = nullptr) = 0;

    /// Adds an activation layer to the network.
    /// @param activationDescriptor - ActivationDescriptor to configure the activation.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddActivationLayer(const ActivationDescriptor& activationDescriptor,
        const char* name = nullptr) = 0;

    /// Adds a normalization layer to the network.
    /// @param normalizationDescriptor - NormalizationDescriptor to configure the normalization.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddNormalizationLayer(const NormalizationDescriptor& normalizationDescriptor,
        const char* name = nullptr) = 0;

    /// Adds a softmax layer to the network.
    /// @param softmaxDescriptor - SoftmaxDescriptor to configure the softmax.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddSoftmaxLayer(const SoftmaxDescriptor& softmaxDescriptor,
        const char* name = nullptr) = 0;

    /// Adds a splitter layer to the network.
    /// @param splitterDescriptor - WindowsDescriptor to configure the splitting process.
    ///                             Number of Views must be equal to the number of outputs,
    ///                             and their order must match - e.g. first view corresponds to
    ///                             the first output, second view to the second output, etc....
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddSplitterLayer(const ViewsDescriptor& splitterDescriptor
        , const char* name = nullptr) = 0;

    /// Adds a merger layer to the network.
    /// @param mergerDescriptor - WindowsDescriptor to configure the merging process. Number of Views must be equal to
    ///                           the number of inputs, and their order must match - e.g. first view corresponds to
    ///                           the first input, second view to the second input, etc....
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddMergerLayer(const OriginsDescriptor& mergerDescriptor,
        const char* name = nullptr) = 0;

    /// Adds an addition layer to the network.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddAdditionLayer(const char* name = nullptr) = 0;

    /// Adds a multiplication layer to the network.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddMultiplicationLayer(const char* name = nullptr) = 0;

    /// Adds a batch normalization layer to the network.
    /// @param mean - Pre-calculated mean for each channel.
    /// @param variance - Pre-calculated variance for each channel.
    /// @param beta - Per-channel additive factor.
    /// @param gamma - Per-channel multiplicative factor.
    /// @return - Interface for configuring the layer.
    /// @param name - Optional name for the layer.
    virtual IConnectableLayer* AddBatchNormalizationLayer(const BatchNormalizationDescriptor& desc,
        const ConstTensor& mean,
        const ConstTensor& variance,
        const ConstTensor& beta,
        const ConstTensor& gamma,
        const char* name = nullptr) = 0;

    /// Adds a resize bilinear layer to the network.
    /// @param resizeDesc - Parameters for the resize operation.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddResizeBilinearLayer(const ResizeBilinearDescriptor& resizeDesc,
                                                      const char* name = nullptr) = 0;

    /// Adds an L2 normalization layer to the network.
    /// Normalization is performed along dimension 1, but requires a 4d input.
    /// @param desc - Parameters for the L2 normalization operation.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddL2NormalizationLayer(const L2NormalizationDescriptor& desc,
                                                       const char* name = nullptr) = 0;

    /// Adds a layer with no inputs and a single output, which always corresponds to
    /// the passed in constant tensor.
    /// @param input - Tensor to be provided as the only output of the layer. The layer will maintain
    ///                its own copy of the tensor data, meaning the memory referenced by @a input can
    ///                be freed or reused after this function is called.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddConstantLayer(const ConstTensor& input,
        const char* name = nullptr) = 0;

    /// Adds a reshape layer to the network.
    /// @param reshapeDescriptor - Parameters for the reshape operation.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddReshapeLayer(const ReshapeDescriptor& reshapeDescriptor,
                                               const char* name = nullptr) = 0;

    /// Adds a space to batch layer to the network.
    /// @param spaceToBatchNdDescriptor - Parameters for the space to batch operation.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddSpaceToBatchNdLayer(const SpaceToBatchNdDescriptor& spaceToBatchNdDescriptor,
                                                      const char* name = nullptr) = 0;

    /// Adds a floor layer to the network.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddFloorLayer(const char* name = nullptr) = 0;

    /// Adds an output layer to the network.
    /// @param id - User generated id to uniquely identify a particular output. The same id needs to be specified
    /// when passing the outputs to the IRuntime::EnqueueWorkload() function.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddOutputLayer(LayerBindingId id, const char* name = nullptr) = 0;

    /// Add a Lstm layer to the network
    /// @param descriptor Parameters for the Lstm operation
    /// @param name Optional name for the layer
    /// @return Interface for configuring the layer.
    virtual IConnectableLayer* AddLstmLayer(const LstmDescriptor& descriptor,
                                            const LstmInputParams& params,
                                            const char* name = nullptr) = 0;

    /// Adds a division layer to the network.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddDivisionLayer(const char* name = nullptr) = 0;

    /// Adds a subtraction layer to the network.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddSubtractionLayer(const char* name = nullptr) = 0;

    /// Add a Mean layer to the network.
    /// @param meanDescriptor - Parameters for the mean operation.
    /// @param name - Optional name for the layer.
    /// @ return - Interface for configuring the layer.
    virtual IConnectableLayer* AddMeanLayer(const MeanDescriptor& meanDescriptor, const char* name = nullptr) = 0;

    /// Adds a fully pad layer to the network.
    /// @param paddings - n by 2 tensor, where n is the rank of the input tensor,
    ///                   such that paddings[i,0] indicates the amount of padding to add in front of dimonsion i, and
    ///                   paddings[i,1] indicates the amount of padding to add after the end of dimension i
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddPadLayer(const PadDescriptor& padDescriptor,
                                           const char* name = nullptr) = 0;

    /// Adds a strided slice layer to the network.
    /// @param StridedSliceDescriptor - Parameters for the strided slice operation.
    /// @param name - Optional name for the layer.
    /// @return - Interface for configuring the layer.
    virtual IConnectableLayer* AddStridedSliceLayer(const StridedSliceDescriptor& stridedSliceDescriptor,
                                                    const char* name = nullptr) = 0;

protected:
    ~INetwork() {}
};

using IOptimizedNetworkPtr = std::unique_ptr<IOptimizedNetwork, void(*)(IOptimizedNetwork* network)>;

class IOptimizedNetwork
{
public:
    static void Destroy(IOptimizedNetwork* network);

    virtual Status PrintGraph() = 0;
    virtual Status SerializeToDot(std::ostream& stream) const = 0;

protected:
    ~IOptimizedNetwork() {}
};

struct OptimizerOptions
{
    OptimizerOptions() : m_ReduceFp32ToFp16(false) {}

    OptimizerOptions(bool reduceFp32ToFp16)
        : m_ReduceFp32ToFp16(reduceFp32ToFp16)
    {
    }

    // Reduce Fp32 data to Fp16 for faster processing
    bool m_ReduceFp32ToFp16;
};

/// Create an optimized version of the network
/// @param network INetwork description of the network to be optimized.
/// @param backendPreferences The choice of the backend ordered by user preferences.
/// @param deviceSpec DeviceSpec object as queried from the runtime. See IRuntime::GetDeviceSpec()
/// @param errMessages if there are failures or warnings a string describing same will be added to the vector
/// @param options OptimizerOptions object with optimizer configuration options
/// @return An IOptimizedNetworkPtr interface to the optimized network, throws an exception derived from
/// armnn::Exception if process fails.

IOptimizedNetworkPtr Optimize(const INetwork& network,
                              const std::vector<BackendId>& backendPreferences,
                              const IDeviceSpec& deviceSpec,
                              const OptimizerOptions& options = OptimizerOptions(),
                              Optional<std::vector<std::string>&> errMessages = EmptyOptional());
} //namespace armnn
<|endoftext|>


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

#ifndef DLL_RBM_TRAITS_HPP
#define DLL_RBM_TRAITS_HPP

#include "tmp.hpp"
#include "decay_type.hpp"

namespace dll {

template<typename Desc>
class dyn_rbm;

template<typename Desc>
class conv_rbm;

template<typename Desc>
class conv_rbm_mp;

/*!
 * \brief Type Traits to get information on RBM type
 */
template<typename RBM>
struct rbm_traits {
    using rbm_t = RBM;

    HAS_STATIC_FIELD(BatchSize, has_batch_size_field)
    HAS_STATIC_FIELD(Sparsity, has_sparsity_field)
    HAS_STATIC_FIELD(Decay, has_decay_field)
    HAS_STATIC_FIELD(Init, has_init_field)
    HAS_STATIC_FIELD(Momentum, has_momentum_field)

    /*!
     * \brief Indicates if the RBM is convolutional
     */
    static constexpr bool is_convolutional(){
        return detail::is_instantiation_of<conv_rbm, rbm_t>::value
            || detail::is_instantiation_of<conv_rbm_mp, rbm_t>::value;
    }

    /*!
     * \brief Indicates if the RBM is dynamic
     */
    static constexpr bool is_dynamic(){
        return detail::is_instantiation_of<dyn_rbm, rbm_t>::value;
    }

    /*!
     * \brief Indicates if the RBM is convolutional and has probabilistic max
     * pooling
     */
    static constexpr bool has_probabilistic_max_pooling(){
        return detail::is_instantiation_of<conv_rbm_mp, rbm_t>::value;
    }

    template<typename R = RBM, enable_if_u<has_batch_size_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr std::size_t batch_size(){
        return rbm_t::desc::BatchSize;
    }

    template<typename R = RBM, disable_if_u<has_batch_size_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr std::size_t batch_size(){
        return 1;
    }

    template<typename R = RBM, enable_if_u<has_momentum_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr bool has_momentum(){
        return rbm_t::desc::Momentum;
    }

    template<typename R = RBM, disable_if_u<has_momentum_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr bool has_momentum(){
        return false;
    }

    template<typename R = RBM, enable_if_u<has_sparsity_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr bool has_sparsity(){
        return rbm_t::desc::Sparsity;
    }

    template<typename R = RBM, disable_if_u<has_sparsity_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr bool has_sparsity(){
        return false;
    }

    template<typename R = RBM, enable_if_u<has_decay_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr decay_type decay(){
        return rbm_t::desc::Decay;
    }

    template<typename R = RBM, disable_if_u<has_decay_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr decay_type decay(){
        return decay_type::NONE;
    }

    template<typename R = RBM, enable_if_u<has_init_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr bool init_weights(){
        return rbm_t::desc::Init;
    }

    template<typename R = RBM, disable_if_u<has_init_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr bool init_weights(){
        return false;
    }
};

template<typename RBM, enable_if_u<rbm_traits<RBM>::is_dynamic()> = ::detail::dummy>
std::size_t get_batch_size(const RBM& rbm){
    return rbm.batch_size;
}

template<typename RBM, disable_if_u<rbm_traits<RBM>::is_dynamic()> = ::detail::dummy>
constexpr std::size_t get_batch_size(const RBM&){
    return rbm_traits<RBM>::batch_size();
}

} //end of dbn namespace

#endif<commit_msg>Add way to get the size of RBM<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef DLL_RBM_TRAITS_HPP
#define DLL_RBM_TRAITS_HPP

#include "tmp.hpp"
#include "decay_type.hpp"

namespace dll {

template<typename Desc>
class dyn_rbm;

template<typename Desc>
class conv_rbm;

template<typename Desc>
class conv_rbm_mp;

/*!
 * \brief Type Traits to get information on RBM type
 */
template<typename RBM>
struct rbm_traits {
    using rbm_t = RBM;

    HAS_STATIC_FIELD(BatchSize, has_batch_size_field)
    HAS_STATIC_FIELD(Sparsity, has_sparsity_field)
    HAS_STATIC_FIELD(Decay, has_decay_field)
    HAS_STATIC_FIELD(Init, has_init_field)
    HAS_STATIC_FIELD(Momentum, has_momentum_field)

    /*!
     * \brief Indicates if the RBM is convolutional
     */
    static constexpr bool is_convolutional(){
        return detail::is_instantiation_of<conv_rbm, rbm_t>::value
            || detail::is_instantiation_of<conv_rbm_mp, rbm_t>::value;
    }

    /*!
     * \brief Indicates if the RBM is dynamic
     */
    static constexpr bool is_dynamic(){
        return detail::is_instantiation_of<dyn_rbm, rbm_t>::value;
    }

    /*!
     * \brief Indicates if the RBM is convolutional and has probabilistic max
     * pooling
     */
    static constexpr bool has_probabilistic_max_pooling(){
        return detail::is_instantiation_of<conv_rbm_mp, rbm_t>::value;
    }

    template<typename R = RBM, enable_if_u<has_batch_size_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr std::size_t batch_size(){
        return rbm_t::desc::BatchSize;
    }

    template<typename R = RBM, disable_if_u<has_batch_size_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr std::size_t batch_size(){
        return 1;
    }

    template<typename R = RBM, enable_if_u<has_momentum_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr bool has_momentum(){
        return rbm_t::desc::Momentum;
    }

    template<typename R = RBM, disable_if_u<has_momentum_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr bool has_momentum(){
        return false;
    }

    template<typename R = RBM, enable_if_u<has_sparsity_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr bool has_sparsity(){
        return rbm_t::desc::Sparsity;
    }

    template<typename R = RBM, disable_if_u<has_sparsity_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr bool has_sparsity(){
        return false;
    }

    template<typename R = RBM, enable_if_u<has_decay_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr decay_type decay(){
        return rbm_t::desc::Decay;
    }

    template<typename R = RBM, disable_if_u<has_decay_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr decay_type decay(){
        return decay_type::NONE;
    }

    template<typename R = RBM, enable_if_u<has_init_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr bool init_weights(){
        return rbm_t::desc::Init;
    }

    template<typename R = RBM, disable_if_u<has_init_field<typename R::desc>::value> = ::detail::dummy>
    static constexpr bool init_weights(){
        return false;
    }
};

template<typename RBM, enable_if_u<rbm_traits<RBM>::is_dynamic()> = ::detail::dummy>
std::size_t get_batch_size(const RBM& rbm){
    return rbm.batch_size;
}

template<typename RBM, disable_if_u<rbm_traits<RBM>::is_dynamic()> = ::detail::dummy>
constexpr std::size_t get_batch_size(const RBM&){
    return rbm_traits<RBM>::batch_size();
}

template<typename RBM, enable_if_u<rbm_traits<RBM>::is_dynamic()> = ::detail::dummy>
std::size_t num_visible(const RBM& rbm){
    return rbm.num_visible;
}

template<typename RBM, disable_if_u<rbm_traits<RBM>::is_dynamic()> = ::detail::dummy>
constexpr std::size_t num_visible(const RBM&){
    return RBM::desc::num_visible;
}

template<typename RBM, enable_if_u<rbm_traits<RBM>::is_dynamic()> = ::detail::dummy>
std::size_t num_hidden(const RBM& rbm){
    return rbm.num_hidden;
}

template<typename RBM, disable_if_u<rbm_traits<RBM>::is_dynamic()> = ::detail::dummy>
constexpr std::size_t num_hidden(const RBM&){
    return RBM::desc::num_hidden;
}

} //end of dbn namespace

#endif<|endoftext|>


<commit_before>#ifndef QRW_CONSTANTS_HPP
#define QRW_CONSTANTS_HPP

#include <SFML/Graphics/Color.hpp>

namespace qrw
{

const sf::Color PLAYER_ONE_COLOR(255, 255, 0, 80);
const sf::Color PLAYER_TWO_COLOR(255, 0, 0 , 80);

const float SQUARE_DIMENSION = 64.0f;

} // namespace qrw

#endif // QRW_CONSTANTS_HPP<commit_msg>Fixing colors of deployment zones<commit_after>#ifndef QRW_CONSTANTS_HPP
#define QRW_CONSTANTS_HPP

#include <SFML/Graphics/Color.hpp>

namespace qrw
{

const sf::Color PLAYER_ONE_COLOR(255, 0, 0 , 80);
const sf::Color PLAYER_TWO_COLOR(255, 255, 0, 80);

const float SQUARE_DIMENSION = 64.0f;

} // namespace qrw

#endif // QRW_CONSTANTS_HPP<|endoftext|>


<commit_before>/* LineDriver is the interface designed to abstact the hardware from I/O pins implementations.
 *
 * Copyright (C) 2011 Artem Borisovskiy (bytefu@gmail.com), http://robocraft.ru
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "LineDriver.h"
#include <inttypes.h>
#include "WProgram.h"

DefaultLineDriver DefaultLineDriver::g_instance;

void DefaultLineDriver::lineConfig(uint8_t pin, uint8_t mode)
{
  pinMode(pin, mode);
}

void DefaultLineDriver::lineWrite(uint8_t pin, uint8_t value)
{
  digitalWrite(pin, value);
}

uint8_t DefaultLineDriver::lineRead(uint8_t pin)
{
  return digitalRead(pin);
}

DefaultLineDriver* DefaultLineDriver::getInstance()
{
  return &g_instance;
}
<commit_msg>Arduino 1.x compatibility fixes.<commit_after>/* LineDriver is the interface designed to abstact the hardware from I/O pins implementations.
 *
 * Copyright (C) 2011 Artem Borisovskiy (bytefu@gmail.com), http://robocraft.ru
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "LineDriver.h"
#include <inttypes.h>

#if defined(ARDUINO) && ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

DefaultLineDriver DefaultLineDriver::g_instance;

void DefaultLineDriver::lineConfig(uint8_t pin, uint8_t mode)
{
  pinMode(pin, mode);
}

void DefaultLineDriver::lineWrite(uint8_t pin, uint8_t value)
{
  digitalWrite(pin, value);
}

uint8_t DefaultLineDriver::lineRead(uint8_t pin)
{
  return digitalRead(pin);
}

DefaultLineDriver* DefaultLineDriver::getInstance()
{
  return &g_instance;
}
<|endoftext|>


<commit_before>#include "LittleNode.h"

LittleNode::LittleNode() {}

double LittleNode::getValue() const {
    return value;
}

void LittleNode::setValue(double value) {
    LittleNode::value = value;
}

const vector<Segment> &LittleNode::getSegments() const {
    return segments;
}

void LittleNode::setSegments(const vector<Segment> &segments) {
    LittleNode::segments = segments;
}

LittleNode::LittleNode(MatrixXd *matrix) : matrix(matrix) {
    value = -1;
    segments = vector<Segment>();
}

LittleNode::LittleNode(MatrixXd *matrix, double value, const vector<Segment> &segments) : matrix(matrix), value(value),
                                                                                segments(segments) {}

MatrixXd *LittleNode::getMatrix() const {
    return matrix;
}

void LittleNode::setMatrix(MatrixXd *matrix) {
    LittleNode::matrix = matrix;
}

double LittleNode::reduceMatrixRow(long row) {
    if (matrix->rows() > row) {
        double rowMin = matrix->row(row).minCoeff();

        for (size_t col = 0; col < matrix->cols(); ++col) {
            (*matrix)(row, col) -= rowMin;
        }

        return rowMin;
    } else {
        throw out_of_range("Provided row index is out of matrix bounds.");
    }
}

double LittleNode::reduceMatrixCol(long col) {
    if (matrix->cols() > col) {
        double colMin = matrix->col(col).minCoeff();

        for (size_t row = 0; row < matrix->rows(); ++row) {
            (*matrix)(row, col) -= colMin;
        }

        return colMin;
    } else {
        throw out_of_range("Provided column index is out of matrix bounds.");
    }
}

double LittleNode::reduceMatrixRows() {
    double reducedSum = 0;

    for (size_t row = 0; row < matrix->rows(); ++row) {
        reducedSum += reduceMatrixRow(row);
    }

    return reducedSum;
}

double LittleNode::reduceMatrixCols() {
    double reducedSum = 0;

    for (size_t col = 0; col < matrix->rows(); ++col) {
        reducedSum += reduceMatrixCol(col);
    }

    return reducedSum;
}

double LittleNode::reduceMatrix() {
    double reducedSum = 0;

    reducedSum += reduceMatrixRows();
    reducedSum += reduceMatrixCols();

    return reducedSum;
}

void LittleNode::removeMatrixRow(long row) {
    long nbRows = matrix->rows() - 1;
    long nbCols = matrix->cols();

    if (row < nbRows) {
        matrix->block(row, 0, nbRows - row, nbCols) = matrix->block(row + 1, 0, nbRows - row, nbCols);
    }

    matrix->conservativeResize(nbRows, nbCols);
}

void LittleNode::removeMatrixCol(long col) {
    long nbRows = matrix->rows();
    long nbCols = matrix->cols() - 1;

    if (col < nbCols) {
        matrix->block(0, col, nbRows, nbCols - col) = matrix->block(0, col + 1, nbRows, nbCols - col);
    }

    matrix->conservativeResize(nbRows, nbCols);
}

<commit_msg>Add exceptions to columns and rows removal functions.<commit_after>#include "LittleNode.h"

LittleNode::LittleNode() {}

double LittleNode::getValue() const {
    return value;
}

void LittleNode::setValue(double value) {
    LittleNode::value = value;
}

const vector<Segment> &LittleNode::getSegments() const {
    return segments;
}

void LittleNode::setSegments(const vector<Segment> &segments) {
    LittleNode::segments = segments;
}

LittleNode::LittleNode(MatrixXd *matrix) : matrix(matrix) {
    value = -1;
    segments = vector<Segment>();
}

LittleNode::LittleNode(MatrixXd *matrix, double value, const vector<Segment> &segments) : matrix(matrix), value(value),
                                                                                segments(segments) {}

MatrixXd *LittleNode::getMatrix() const {
    return matrix;
}

void LittleNode::setMatrix(MatrixXd *matrix) {
    LittleNode::matrix = matrix;
}

double LittleNode::reduceMatrixRow(long row) {
    if (matrix->rows() > row) {
        double rowMin = matrix->row(row).minCoeff();

        for (size_t col = 0; col < matrix->cols(); ++col) {
            (*matrix)(row, col) -= rowMin;
        }

        return rowMin;
    } else {
        throw out_of_range("Provided row index is out of matrix bounds.");
    }
}

double LittleNode::reduceMatrixCol(long col) {
    if (matrix->cols() > col) {
        double colMin = matrix->col(col).minCoeff();

        for (size_t row = 0; row < matrix->rows(); ++row) {
            (*matrix)(row, col) -= colMin;
        }

        return colMin;
    } else {
        throw out_of_range("Provided column index is out of matrix bounds.");
    }
}

double LittleNode::reduceMatrixRows() {
    double reducedSum = 0;

    for (size_t row = 0; row < matrix->rows(); ++row) {
        reducedSum += reduceMatrixRow(row);
    }

    return reducedSum;
}

double LittleNode::reduceMatrixCols() {
    double reducedSum = 0;

    for (size_t col = 0; col < matrix->rows(); ++col) {
        reducedSum += reduceMatrixCol(col);
    }

    return reducedSum;
}

double LittleNode::reduceMatrix() {
    double reducedSum = 0;

    reducedSum += reduceMatrixRows();
    reducedSum += reduceMatrixCols();

    return reducedSum;
}

void LittleNode::removeMatrixRow(long row) {
    long nbRows = matrix->rows() - 1;
    long nbCols = matrix->cols();

    if (row > nbRows) {
        throw out_of_range("Provided row index is out of matrix range.");
    }

    if (row < nbRows) {
        matrix->block(row, 0, nbRows - row, nbCols) = matrix->block(row + 1, 0, nbRows - row, nbCols);
    }

    matrix->conservativeResize(nbRows, nbCols);
}

void LittleNode::removeMatrixCol(long col) {
    long nbRows = matrix->rows();
    long nbCols = matrix->cols() - 1;

    if (col > nbCols) {
        throw out_of_range("Provided column index is out of matrix range.");
    }

    if (col < nbCols) {
        matrix->block(0, col, nbRows, nbCols - col) = matrix->block(0, col + 1, nbRows, nbCols - col);
    }

    matrix->conservativeResize(nbRows, nbCols);
}

<|endoftext|>


<commit_before>#ifndef __CFG_BUILDER_HH_
#define __CFG_BUILDER_HH_

/* Build a CFG from a LLVM function */

#include "llvm/IR/Function.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"

//#include "avy/AvyDebug.h"

#include <ikos_cfg/Cfg.hpp>
#include <ikos_cfg/VarFactory.hpp>
#include <ikos_domains/bignums.hpp>

#include <boost/optional.hpp>
#include <boost/noncopyable.hpp>

namespace cfg
{
  namespace var_factory_impl
  {
    namespace indexed_string_impl
    {
      // To print variable names
      template<> inline std::string get_str(const llvm::Value *v)
      {return v->getName().str();}
    }
  }
}

namespace cfg_impl
{
  using namespace cfg;

  // To print basic block labels
  template<> inline std::string get_label_str(llvm::BasicBlock *B)
  { return B->getName (); }

  // Variable factory from llvm::Value's
  class LlvmVariableFactory : public boost::noncopyable
  {
    typedef var_factory_impl::VariableFactory< const llvm::Value* > LlvmVariableFactory_t;
    std::unique_ptr< LlvmVariableFactory_t > m_factory;

   public:

    typedef LlvmVariableFactory_t::variable_t varname_t;

    LlvmVariableFactory(): m_factory (new LlvmVariableFactory_t()){ }

    varname_t operator[](const llvm::Value &v)
    {
      const llvm::Value *V = &v;
      return (*m_factory)[V];
    }
  };

  typedef LlvmVariableFactory VariableFactory;
  typedef typename VariableFactory::varname_t varname_t;

  // CFG
  typedef ikos::variable< ikos::z_number, varname_t > z_var;
  typedef llvm::BasicBlock*                           basic_block_label_t;
  typedef Cfg< basic_block_label_t, varname_t>        cfg_t;
  typedef cfg_t::BasicBlock_t                         basic_block_t;
  typedef typename cfg_t::BasicBlock_t::ZLinearExpression ZLinearExpression;
  typedef typename cfg_t::BasicBlock_t::ZLinearConstraint ZLinearConstraint;
  typedef ikos::linear_constraint_system<ikos::z_number, varname_t> ZLinearConstraintSystem;

} // end namespace cfg_impl

namespace{
  llvm::raw_ostream& operator<< (llvm::raw_ostream& o, cfg_impl::cfg_t cfg)
  {
    std::ostringstream s;
    s << cfg;
    o << s.str ();
    return o;
  }
}

namespace llvm_ikos
{
  using namespace std;
  using namespace cfg_impl;
  using namespace llvm;

  class CfgBuilder: public boost::noncopyable
  {

    friend class SymExecSelectVisitor;

   public:

    typedef boost::optional<basic_block_t&> opt_basic_block_t;

   private:

    typedef boost::unordered_map< basic_block_label_t,
                                  basic_block_t& > llvm_bb_map_t;
    Function&         m_func;
    VariableFactory&  m_vfac;
    unsigned          m_id;
    cfg_t             m_cfg;
    llvm_bb_map_t     m_bb_map;

   public:

    CfgBuilder(Function &func, VariableFactory &vfac):
        m_func (func),
        m_vfac (vfac),
        m_id (0),
        m_cfg (&m_func.getEntryBlock (), NULL)
    { }

    cfg_t & operator()()
    {
      make_cfg ();
      return m_cfg;
    }

   private:

    string create_bb_name(string prefix = "")
    {
      if (prefix == "") prefix = string("_bb_");
      ++m_id;
      string id_str = std::to_string(m_id);
      return prefix + id_str;
    }

    void make_cfg();

    opt_basic_block_t lookup(const llvm::BasicBlock &);

    void add_block(llvm::BasicBlock &BB);

    void add_edge(llvm::BasicBlock &Src, const llvm::BasicBlock &Target);

    opt_basic_block_t execBr(llvm::BasicBlock &Src,
                             const llvm::BasicBlock &Target);

    basic_block_t& add_block_in_between (basic_block_t &src,
                                         basic_block_t &dst,
                                         basic_block_label_t bb_id) ;

  }; // end class CfgBuilder

} // end namespace llvm_ikos

#endif
<commit_msg>[FIX] mark operator<< inline<commit_after>#ifndef __CFG_BUILDER_HH_
#define __CFG_BUILDER_HH_

/* Build a CFG from a LLVM function */

#include "llvm/IR/Function.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"

//#include "avy/AvyDebug.h"

#include <ikos_cfg/Cfg.hpp>
#include <ikos_cfg/VarFactory.hpp>
#include <ikos_domains/bignums.hpp>

#include <boost/optional.hpp>
#include <boost/noncopyable.hpp>

namespace cfg
{
  namespace var_factory_impl
  {
    namespace indexed_string_impl
    {
      // To print variable names
      template<> inline std::string get_str(const llvm::Value *v)
      {return v->getName().str();}
    }
  }
}

namespace cfg_impl
{
  using namespace cfg;

  // To print basic block labels
  template<> inline std::string get_label_str(llvm::BasicBlock *B)
  { return B->getName (); }

  // Variable factory from llvm::Value's
  class LlvmVariableFactory : public boost::noncopyable
  {
    typedef var_factory_impl::VariableFactory< const llvm::Value* > LlvmVariableFactory_t;
    std::unique_ptr< LlvmVariableFactory_t > m_factory;

   public:

    typedef LlvmVariableFactory_t::variable_t varname_t;

    LlvmVariableFactory(): m_factory (new LlvmVariableFactory_t()){ }

    varname_t operator[](const llvm::Value &v)
    {
      const llvm::Value *V = &v;
      return (*m_factory)[V];
    }
  };

  typedef LlvmVariableFactory VariableFactory;
  typedef typename VariableFactory::varname_t varname_t;

  // CFG
  typedef ikos::variable< ikos::z_number, varname_t > z_var;
  typedef llvm::BasicBlock*                           basic_block_label_t;
  typedef Cfg< basic_block_label_t, varname_t>        cfg_t;
  typedef cfg_t::BasicBlock_t                         basic_block_t;
  typedef typename cfg_t::BasicBlock_t::ZLinearExpression ZLinearExpression;
  typedef typename cfg_t::BasicBlock_t::ZLinearConstraint ZLinearConstraint;
  typedef ikos::linear_constraint_system<ikos::z_number, varname_t> ZLinearConstraintSystem;

} // end namespace cfg_impl

namespace{
  inline llvm::raw_ostream& operator<< (llvm::raw_ostream& o, cfg_impl::cfg_t cfg)
  {
    std::ostringstream s;
    s << cfg;
    o << s.str ();
    return o;
  }
}

namespace llvm_ikos
{
  using namespace std;
  using namespace cfg_impl;
  using namespace llvm;

  class CfgBuilder: public boost::noncopyable
  {

    friend class SymExecSelectVisitor;

   public:

    typedef boost::optional<basic_block_t&> opt_basic_block_t;

   private:

    typedef boost::unordered_map< basic_block_label_t,
                                  basic_block_t& > llvm_bb_map_t;
    Function&         m_func;
    VariableFactory&  m_vfac;
    unsigned          m_id;
    cfg_t             m_cfg;
    llvm_bb_map_t     m_bb_map;

   public:

    CfgBuilder(Function &func, VariableFactory &vfac):
        m_func (func),
        m_vfac (vfac),
        m_id (0),
        m_cfg (&m_func.getEntryBlock (), NULL)
    { }

    cfg_t & operator()()
    {
      make_cfg ();
      return m_cfg;
    }

   private:

    string create_bb_name(string prefix = "")
    {
      if (prefix == "") prefix = string("_bb_");
      ++m_id;
      string id_str = std::to_string(m_id);
      return prefix + id_str;
    }

    void make_cfg();

    opt_basic_block_t lookup(const llvm::BasicBlock &);

    void add_block(llvm::BasicBlock &BB);

    void add_edge(llvm::BasicBlock &Src, const llvm::BasicBlock &Target);

    opt_basic_block_t execBr(llvm::BasicBlock &Src,
                             const llvm::BasicBlock &Target);

    basic_block_t& add_block_in_between (basic_block_t &src,
                                         basic_block_t &dst,
                                         basic_block_label_t bb_id) ;

  }; // end class CfgBuilder

} // end namespace llvm_ikos

#endif
<|endoftext|>


<commit_before>#pragma once

#ifndef SIPL_IMPROC_UTILITY_H
#define SIPL_IMPROC_UTILITY_H

#include <limits>
#include <cmath>
#include "matrix/Vector"

namespace sipl
{

// Available kinds of interpolators
enum class InterpolateType { BILINEAR, NEAREST_NEIGHBOR, UNKNOWN };

template <typename T>
T clamp(double val)
{
    const auto min = std::numeric_limits<T>::min();
    const auto max = std::numeric_limits<T>::max();
    if (val > max) {
        return max;
    } else if (val < min) {
        return min;
    } else {
        return T(std::round(val));
    }
}

// Overload for double vals so they don't get rounded
double clamp(double val) { return val; }

// Overload for Vector3d types
RgbPixel clamp(const Vector3d& v)
{
    return v.apply([](auto e) { return clamp(e); });
}

template <typename T>
Vector3<T> homogenize(const Vector3<T>& v)
{
    return v / v[2];
}
}

#endif
<commit_msg>This functionality was moved elsewhere<commit_after><|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#ifndef __MESOS_V1_HPP__
#define __MESOS_V1_HPP__

#include <iosfwd>
#include <string>
#include <vector>

#include <boost/functional/hash.hpp>

#include <google/protobuf/repeated_field.h>

#include <mesos/v1/mesos.pb.h> // ONLY USEFUL AFTER RUNNING PROTOC.

#include <stout/strings.hpp>

// This file includes definitions for operators on public protobuf
// classes (defined in mesos.proto, module.proto, etc.) that don't
// have these operators generated by the protobuf compiler. The
// corresponding definitions are in src/v1/type_utils.cpp.
//
// Mesos modules need some of the protobuf classes defined in
// mesos.proto, module.proto, etc., and require some of these
// operators declared in mesos.hpp. Exposing mesos.hpp
// allows us to build modules without having a dependency on mesos
// source tree (src/*).

namespace mesos {
namespace v1 {

bool operator==(const CommandInfo& left, const CommandInfo& right);
bool operator==(const CommandInfo::URI& left, const CommandInfo::URI& right);
bool operator==(const Credential& left, const Credential& right);
bool operator==(const DiscoveryInfo& left, const DiscoveryInfo& right);
bool operator==(const Environment& left, const Environment& right);
bool operator==(const ExecutorInfo& left, const ExecutorInfo& right);
bool operator==(const FileInfo& left, const FileInfo& right);
bool operator==(const Label& left, const Label& right);
bool operator==(const Labels& left, const Labels& right);
bool operator==(const MasterInfo& left, const MasterInfo& right);

bool operator==(
    const ResourceStatistics& left,
    const ResourceStatistics& right);

bool operator==(const AgentInfo& left, const AgentInfo& right);
bool operator==(const TaskStatus& left, const TaskStatus& right);
bool operator==(const URL& left, const URL& right);
bool operator==(const Volume& left, const Volume& right);

bool operator!=(const Labels& left, const Labels& right);
bool operator!=(const TaskStatus& left, const TaskStatus& right);

inline bool operator==(const ContainerID& left, const ContainerID& right)
{
  return left.value() == right.value();
}

inline bool operator==(const ExecutorID& left, const ExecutorID& right)
{
  return left.value() == right.value();
}

inline bool operator==(const FrameworkID& left, const FrameworkID& right)
{
  return left.value() == right.value();
}

inline bool operator==(const FrameworkInfo& left, const FrameworkInfo& right)
{
  return (left.name() == right.name()) && (left.user() == right.user());
}

inline bool operator==(const OfferID& left, const OfferID& right)
{
  return left.value() == right.value();
}

inline bool operator==(const AgentID& left, const AgentID& right)
{
  return left.value() == right.value();
}

inline bool operator==(const TaskID& left, const TaskID& right)
{
  return left.value() == right.value();
}

inline bool operator==(const TimeInfo& left, const TimeInfo& right)
{
  return left.nanoseconds() == right.nanoseconds();
}

inline bool operator==(const DurationInfo& left, const DurationInfo& right)
{
  return left.nanoseconds() == right.nanoseconds();
}

inline bool operator==(const ContainerID& left, const std::string& right)
{
  return left.value() == right;
}

inline bool operator==(const ExecutorID& left, const std::string& right)
{
  return left.value() == right;
}

inline bool operator==(const FrameworkID& left, const std::string& right)
{
  return left.value() == right;
}

inline bool operator==(const OfferID& left, const std::string& right)
{
  return left.value() == right;
}

inline bool operator==(const AgentID& left, const std::string& right)
{
  return left.value() == right;
}

inline bool operator==(const TaskID& left, const std::string& right)
{
  return left.value() == right;
}

/**
 * For machines to match, both the `hostname` and `ip` must be equivalent.
 * Hostname is not case sensitive, so it is lowercased before comparison.
 */
inline bool operator==(const MachineID& left, const MachineID& right)
{
  // NOTE: Both fields default to the empty string if they are not specified,
  // so the string comparisons are safe.
  return left.has_hostname() == right.has_hostname() &&
    strings::lower(left.hostname()) == strings::lower(right.hostname()) &&
    left.has_ip() == right.has_ip() &&
    left.ip() == right.ip();
}

inline bool operator!=(const ContainerID& left, const ContainerID& right)
{
  return left.value() != right.value();
}

inline bool operator!=(const ExecutorID& left, const ExecutorID& right)
{
  return left.value() != right.value();
}

inline bool operator!=(const FrameworkID& left, const FrameworkID& right)
{
  return left.value() != right.value();
}

inline bool operator!=(const AgentID& left, const AgentID& right)
{
  return left.value() != right.value();
}

inline bool operator!=(const TimeInfo& left, const TimeInfo& right)
{
  return !(left == right);
}

inline bool operator!=(const DurationInfo& left, const DurationInfo& right)
{
  return !(left == right);
}

inline bool operator<(const ContainerID& left, const ContainerID& right)
{
  return left.value() < right.value();
}

inline bool operator<(const ExecutorID& left, const ExecutorID& right)
{
  return left.value() < right.value();
}

inline bool operator<(const FrameworkID& left, const FrameworkID& right)
{
  return left.value() < right.value();
}

inline bool operator<(const OfferID& left, const OfferID& right)
{
  return left.value() < right.value();
}

inline bool operator<(const AgentID& left, const AgentID& right)
{
  return left.value() < right.value();
}

inline bool operator<(const TaskID& left, const TaskID& right)
{
  return left.value() < right.value();
}

std::ostream& operator<<(
    std::ostream& stream,
    const CapabilityInfo& capabilityInfo);

std::ostream& operator<<(std::ostream& stream, const ContainerID& containerId);

std::ostream& operator<<(
    std::ostream& stream,
    const ContainerInfo& containerInfo);

std::ostream& operator<<(std::ostream& stream, const ExecutorID& executorId);

std::ostream& operator<<(std::ostream& stream, const ExecutorInfo& executor);

std::ostream& operator<<(std::ostream& stream, const FrameworkID& frameworkId);

std::ostream& operator<<(std::ostream& stream, const MasterInfo& master);

std::ostream& operator<<(std::ostream& stream, const OfferID& offerId);

std::ostream& operator<<(std::ostream& stream, const RateLimits& limits);

std::ostream& operator<<(std::ostream& stream, const AgentID& agentId);

std::ostream& operator<<(std::ostream& stream, const AgentInfo& agent);

std::ostream& operator<<(std::ostream& stream, const TaskID& taskId);

std::ostream& operator<<(std::ostream& stream, const MachineID& machineId);

std::ostream& operator<<(std::ostream& stream, const TaskInfo& task);

std::ostream& operator<<(
    std::ostream& stream,
    const TaskGroupInfo& taskGroupInfo);

std::ostream& operator<<(std::ostream& stream, const TaskState& state);

std::ostream& operator<<(
    std::ostream& stream,
    const std::vector<TaskID>& taskIds);

std::ostream& operator<<(
    std::ostream& stream,
    const FrameworkInfo::Capability& capability);

std::ostream& operator<<(std::ostream& stream, const Image::Type& imageType);

template <typename T>
inline std::ostream& operator<<(
    std::ostream& stream,
    const google::protobuf::RepeatedPtrField<T>& messages)
{
  stream << "[ ";
  for (auto it = messages.begin(); it != messages.end(); ++it) {
    if (it != messages.begin()) {
      stream << ", ";
    }
    stream << *it;
  }
  stream << " ]";
  return stream;
}

std::ostream& operator<<(
    std::ostream& stream,
    const hashmap<std::string, std::string>& map);

} // namespace v1 {
} // namespace mesos {

namespace std {

template <>
struct hash<mesos::v1::CommandInfo::URI>
{
  typedef size_t result_type;

  typedef mesos::v1::CommandInfo::URI argument_type;

  result_type operator()(const argument_type& uri) const
  {
    size_t seed = 0;

    if (uri.extract()) {
      seed += 11;
    }

    if (uri.executable()) {
      seed += 2003;
    }

    boost::hash_combine(seed, uri.value());
    return seed;
  }
};

template <>
struct hash<mesos::v1::ContainerID>
{
  typedef size_t result_type;

  typedef mesos::v1::ContainerID argument_type;

  result_type operator()(const argument_type& containerId) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, containerId.value());
    return seed;
  }
};

template <>
struct hash<mesos::v1::ExecutorID>
{
  typedef size_t result_type;

  typedef mesos::v1::ExecutorID argument_type;

  result_type operator()(const argument_type& executorId) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, executorId.value());
    return seed;
  }
};

template <>
struct hash<mesos::v1::FrameworkID>
{
  typedef size_t result_type;

  typedef mesos::v1::FrameworkID argument_type;

  result_type operator()(const argument_type& frameworkId) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, frameworkId.value());
    return seed;
  }
};

template <>
struct hash<mesos::v1::OfferID>
{
  typedef size_t result_type;

  typedef mesos::v1::OfferID argument_type;

  result_type operator()(const argument_type& offerId) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, offerId.value());
    return seed;
  }
};

template <>
struct hash<mesos::v1::AgentID>
{
  typedef size_t result_type;

  typedef mesos::v1::AgentID argument_type;

  result_type operator()(const argument_type& agentId) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, agentId.value());
    return seed;
  }
};

template <>
struct hash<mesos::v1::TaskID>
{
  typedef size_t result_type;

  typedef mesos::v1::TaskID argument_type;

  result_type operator()(const argument_type& taskId) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, taskId.value());
    return seed;
  }
};

template <>
struct hash<mesos::v1::TaskState>
{
  typedef size_t result_type;

  typedef mesos::v1::TaskState argument_type;

  result_type operator()(const argument_type& taskState) const
  {
    // Use the underlying type of the enum as hash value.
    return static_cast<size_t>(taskState);
  }
};

template <>
struct hash<mesos::v1::TaskStatus_Source>
{
  typedef size_t result_type;

  typedef mesos::v1::TaskStatus_Source argument_type;

  result_type operator()(const argument_type& source) const
  {
    // Use the underlying type of the enum as hash value.
    return static_cast<size_t>(source);
  }
};

template <>
struct hash<mesos::v1::TaskStatus_Reason>
{
  typedef size_t result_type;

  typedef mesos::v1::TaskStatus_Reason argument_type;

  result_type operator()(const argument_type& reason) const
  {
    // Use the underlying type of the enum as hash value.
    return static_cast<size_t>(reason);
  }
};

template <>
struct hash<mesos::v1::Image::Type>
{
  typedef size_t result_type;

  typedef mesos::v1::Image::Type argument_type;

  result_type operator()(const argument_type& imageType) const
  {
    // Use the underlying type of the enum as hash value.
    return static_cast<size_t>(imageType);
  }
};

template <>
struct hash<std::pair<mesos::v1::FrameworkID, mesos::v1::ExecutorID>>
{
  typedef size_t result_type;

  typedef std::pair<
      mesos::v1::FrameworkID, mesos::v1::ExecutorID> argument_type;

  result_type operator()(const argument_type& pair) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, std::hash<mesos::v1::FrameworkID>()(pair.first));
    boost::hash_combine(seed, std::hash<mesos::v1::ExecutorID>()(pair.second));
    return seed;
  }
};

template <>
struct hash<mesos::v1::MachineID>
{
  typedef size_t result_type;

  typedef mesos::v1::MachineID argument_type;

  result_type operator()(const argument_type& machineId) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, strings::lower(machineId.hostname()));
    boost::hash_combine(seed, machineId.ip());
    return seed;
  }
};

} // namespace std {

#endif // __MESOS_V1_HPP__
<commit_msg>Added a missing declaration to the v1 header.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.

#ifndef __MESOS_V1_HPP__
#define __MESOS_V1_HPP__

#include <iosfwd>
#include <string>
#include <vector>

#include <boost/functional/hash.hpp>

#include <google/protobuf/repeated_field.h>

#include <mesos/v1/mesos.pb.h> // ONLY USEFUL AFTER RUNNING PROTOC.

#include <stout/strings.hpp>

// This file includes definitions for operators on public protobuf
// classes (defined in mesos.proto, module.proto, etc.) that don't
// have these operators generated by the protobuf compiler. The
// corresponding definitions are in src/v1/type_utils.cpp.
//
// Mesos modules need some of the protobuf classes defined in
// mesos.proto, module.proto, etc., and require some of these
// operators declared in mesos.hpp. Exposing mesos.hpp
// allows us to build modules without having a dependency on mesos
// source tree (src/*).

namespace mesos {
namespace v1 {

bool operator==(const CommandInfo& left, const CommandInfo& right);
bool operator==(const CommandInfo::URI& left, const CommandInfo::URI& right);
bool operator==(const Credential& left, const Credential& right);
bool operator==(const DiscoveryInfo& left, const DiscoveryInfo& right);
bool operator==(const Environment& left, const Environment& right);
bool operator==(const ExecutorInfo& left, const ExecutorInfo& right);
bool operator==(const FileInfo& left, const FileInfo& right);
bool operator==(const Label& left, const Label& right);
bool operator==(const Labels& left, const Labels& right);
bool operator==(const MasterInfo& left, const MasterInfo& right);

bool operator==(
    const ResourceStatistics& left,
    const ResourceStatistics& right);

bool operator==(const AgentInfo& left, const AgentInfo& right);
bool operator==(const TaskStatus& left, const TaskStatus& right);
bool operator==(const URL& left, const URL& right);
bool operator==(const Volume& left, const Volume& right);

bool operator!=(const Labels& left, const Labels& right);
bool operator!=(const TaskStatus& left, const TaskStatus& right);

inline bool operator==(const ContainerID& left, const ContainerID& right)
{
  return left.value() == right.value();
}

inline bool operator==(const ExecutorID& left, const ExecutorID& right)
{
  return left.value() == right.value();
}

inline bool operator==(const FrameworkID& left, const FrameworkID& right)
{
  return left.value() == right.value();
}

inline bool operator==(const FrameworkInfo& left, const FrameworkInfo& right)
{
  return (left.name() == right.name()) && (left.user() == right.user());
}

inline bool operator==(const OfferID& left, const OfferID& right)
{
  return left.value() == right.value();
}

inline bool operator==(const AgentID& left, const AgentID& right)
{
  return left.value() == right.value();
}

inline bool operator==(const TaskID& left, const TaskID& right)
{
  return left.value() == right.value();
}

inline bool operator==(const TimeInfo& left, const TimeInfo& right)
{
  return left.nanoseconds() == right.nanoseconds();
}

inline bool operator==(const DurationInfo& left, const DurationInfo& right)
{
  return left.nanoseconds() == right.nanoseconds();
}

inline bool operator==(const ContainerID& left, const std::string& right)
{
  return left.value() == right;
}

inline bool operator==(const ExecutorID& left, const std::string& right)
{
  return left.value() == right;
}

inline bool operator==(const FrameworkID& left, const std::string& right)
{
  return left.value() == right;
}

inline bool operator==(const OfferID& left, const std::string& right)
{
  return left.value() == right;
}

inline bool operator==(const AgentID& left, const std::string& right)
{
  return left.value() == right;
}

inline bool operator==(const TaskID& left, const std::string& right)
{
  return left.value() == right;
}

/**
 * For machines to match, both the `hostname` and `ip` must be equivalent.
 * Hostname is not case sensitive, so it is lowercased before comparison.
 */
inline bool operator==(const MachineID& left, const MachineID& right)
{
  // NOTE: Both fields default to the empty string if they are not specified,
  // so the string comparisons are safe.
  return left.has_hostname() == right.has_hostname() &&
    strings::lower(left.hostname()) == strings::lower(right.hostname()) &&
    left.has_ip() == right.has_ip() &&
    left.ip() == right.ip();
}

inline bool operator!=(const ContainerID& left, const ContainerID& right)
{
  return left.value() != right.value();
}

inline bool operator!=(const ExecutorID& left, const ExecutorID& right)
{
  return left.value() != right.value();
}

inline bool operator!=(const FrameworkID& left, const FrameworkID& right)
{
  return left.value() != right.value();
}

inline bool operator!=(const AgentID& left, const AgentID& right)
{
  return left.value() != right.value();
}

inline bool operator!=(const TimeInfo& left, const TimeInfo& right)
{
  return !(left == right);
}

inline bool operator!=(const DurationInfo& left, const DurationInfo& right)
{
  return !(left == right);
}

inline bool operator<(const ContainerID& left, const ContainerID& right)
{
  return left.value() < right.value();
}

inline bool operator<(const ExecutorID& left, const ExecutorID& right)
{
  return left.value() < right.value();
}

inline bool operator<(const FrameworkID& left, const FrameworkID& right)
{
  return left.value() < right.value();
}

inline bool operator<(const OfferID& left, const OfferID& right)
{
  return left.value() < right.value();
}

inline bool operator<(const AgentID& left, const AgentID& right)
{
  return left.value() < right.value();
}

inline bool operator<(const TaskID& left, const TaskID& right)
{
  return left.value() < right.value();
}

std::ostream& operator<<(
    std::ostream& stream,
    const CapabilityInfo& capabilityInfo);

std::ostream& operator<<(std::ostream& stream, const ContainerID& containerId);

std::ostream& operator<<(
    std::ostream& stream,
    const ContainerInfo& containerInfo);

std::ostream& operator<<(std::ostream& stream, const ExecutorID& executorId);

std::ostream& operator<<(std::ostream& stream, const ExecutorInfo& executor);

std::ostream& operator<<(std::ostream& stream, const FrameworkID& frameworkId);

std::ostream& operator<<(std::ostream& stream, const MasterInfo& master);

std::ostream& operator<<(std::ostream& stream, const OfferID& offerId);

std::ostream& operator<<(std::ostream& stream, const RateLimits& limits);

std::ostream& operator<<(std::ostream& stream, const RLimitInfo& limits);

std::ostream& operator<<(std::ostream& stream, const AgentID& agentId);

std::ostream& operator<<(std::ostream& stream, const AgentInfo& agent);

std::ostream& operator<<(std::ostream& stream, const TaskID& taskId);

std::ostream& operator<<(std::ostream& stream, const MachineID& machineId);

std::ostream& operator<<(std::ostream& stream, const TaskInfo& task);

std::ostream& operator<<(
    std::ostream& stream,
    const TaskGroupInfo& taskGroupInfo);

std::ostream& operator<<(std::ostream& stream, const TaskState& state);

std::ostream& operator<<(
    std::ostream& stream,
    const std::vector<TaskID>& taskIds);

std::ostream& operator<<(
    std::ostream& stream,
    const FrameworkInfo::Capability& capability);

std::ostream& operator<<(std::ostream& stream, const Image::Type& imageType);

template <typename T>
inline std::ostream& operator<<(
    std::ostream& stream,
    const google::protobuf::RepeatedPtrField<T>& messages)
{
  stream << "[ ";
  for (auto it = messages.begin(); it != messages.end(); ++it) {
    if (it != messages.begin()) {
      stream << ", ";
    }
    stream << *it;
  }
  stream << " ]";
  return stream;
}

std::ostream& operator<<(
    std::ostream& stream,
    const hashmap<std::string, std::string>& map);

} // namespace v1 {
} // namespace mesos {

namespace std {

template <>
struct hash<mesos::v1::CommandInfo::URI>
{
  typedef size_t result_type;

  typedef mesos::v1::CommandInfo::URI argument_type;

  result_type operator()(const argument_type& uri) const
  {
    size_t seed = 0;

    if (uri.extract()) {
      seed += 11;
    }

    if (uri.executable()) {
      seed += 2003;
    }

    boost::hash_combine(seed, uri.value());
    return seed;
  }
};

template <>
struct hash<mesos::v1::ContainerID>
{
  typedef size_t result_type;

  typedef mesos::v1::ContainerID argument_type;

  result_type operator()(const argument_type& containerId) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, containerId.value());
    return seed;
  }
};

template <>
struct hash<mesos::v1::ExecutorID>
{
  typedef size_t result_type;

  typedef mesos::v1::ExecutorID argument_type;

  result_type operator()(const argument_type& executorId) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, executorId.value());
    return seed;
  }
};

template <>
struct hash<mesos::v1::FrameworkID>
{
  typedef size_t result_type;

  typedef mesos::v1::FrameworkID argument_type;

  result_type operator()(const argument_type& frameworkId) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, frameworkId.value());
    return seed;
  }
};

template <>
struct hash<mesos::v1::OfferID>
{
  typedef size_t result_type;

  typedef mesos::v1::OfferID argument_type;

  result_type operator()(const argument_type& offerId) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, offerId.value());
    return seed;
  }
};

template <>
struct hash<mesos::v1::AgentID>
{
  typedef size_t result_type;

  typedef mesos::v1::AgentID argument_type;

  result_type operator()(const argument_type& agentId) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, agentId.value());
    return seed;
  }
};

template <>
struct hash<mesos::v1::TaskID>
{
  typedef size_t result_type;

  typedef mesos::v1::TaskID argument_type;

  result_type operator()(const argument_type& taskId) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, taskId.value());
    return seed;
  }
};

template <>
struct hash<mesos::v1::TaskState>
{
  typedef size_t result_type;

  typedef mesos::v1::TaskState argument_type;

  result_type operator()(const argument_type& taskState) const
  {
    // Use the underlying type of the enum as hash value.
    return static_cast<size_t>(taskState);
  }
};

template <>
struct hash<mesos::v1::TaskStatus_Source>
{
  typedef size_t result_type;

  typedef mesos::v1::TaskStatus_Source argument_type;

  result_type operator()(const argument_type& source) const
  {
    // Use the underlying type of the enum as hash value.
    return static_cast<size_t>(source);
  }
};

template <>
struct hash<mesos::v1::TaskStatus_Reason>
{
  typedef size_t result_type;

  typedef mesos::v1::TaskStatus_Reason argument_type;

  result_type operator()(const argument_type& reason) const
  {
    // Use the underlying type of the enum as hash value.
    return static_cast<size_t>(reason);
  }
};

template <>
struct hash<mesos::v1::Image::Type>
{
  typedef size_t result_type;

  typedef mesos::v1::Image::Type argument_type;

  result_type operator()(const argument_type& imageType) const
  {
    // Use the underlying type of the enum as hash value.
    return static_cast<size_t>(imageType);
  }
};

template <>
struct hash<std::pair<mesos::v1::FrameworkID, mesos::v1::ExecutorID>>
{
  typedef size_t result_type;

  typedef std::pair<
      mesos::v1::FrameworkID, mesos::v1::ExecutorID> argument_type;

  result_type operator()(const argument_type& pair) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, std::hash<mesos::v1::FrameworkID>()(pair.first));
    boost::hash_combine(seed, std::hash<mesos::v1::ExecutorID>()(pair.second));
    return seed;
  }
};

template <>
struct hash<mesos::v1::MachineID>
{
  typedef size_t result_type;

  typedef mesos::v1::MachineID argument_type;

  result_type operator()(const argument_type& machineId) const
  {
    size_t seed = 0;
    boost::hash_combine(seed, strings::lower(machineId.hostname()));
    boost::hash_combine(seed, machineId.ip());
    return seed;
  }
};

} // namespace std {

#endif // __MESOS_V1_HPP__
<|endoftext|>