<commit_before>/* This file is part of the KDE libraries
   Copyright (C) 2001-2005 Christoph Cullmann <cullmann@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

   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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "kateglobal.h"
#include "katedocument.h"

#include <ktexteditor/factory.h>

/**
 * wrapper factory to be sure nobody external deletes our kateglobal object
 * each instance will just increment the reference counter of our internal
 * super private global instance ;)
 */
class KateFactory : public KTextEditor::Factory
{
  public:
    /**
     * constructor, increments reference count of KateGlobal
     * @param parent parent object
     * @param name name of factory
     */
    KateFactory ( QObject *parent = 0 )
      : KTextEditor::Factory (parent)
    {
      KateGlobal::incRef ();
    }

    /**
     * destructor, decrements reference count of KateGlobal
     */
    virtual ~KateFactory ()
    {
      KateGlobal::decRef ();
    }

    KTextEditor::Editor *editor () { return KateGlobal::self(); }

    /**
     * reimplemented create object method
     * @param parentWidget parent widget
     * @param parent QObject parent
     * @param args additional arguments
     * @return constructed part object
     */
    KParts::Part *createPartObject ( QWidget *parentWidget, QObject *parent, const char *_classname, const QStringList & )
    {
      QByteArray classname( _classname );

      // default to the kparts::* behavior of having one single widget() if the user don't requested a pure document
      bool bWantSingleView = ( classname != "KTextEditor::Document" );

      // does user want browserview?
      bool bWantBrowserView = false;

      // should we be readonly?
      bool bWantReadOnly = (bWantBrowserView || ( classname == "KParts::ReadOnlyPart" ));

      // set simple mode on for read-only part per default
      KateGlobal::self ()->setSimpleMode (bWantReadOnly);

      KParts::ReadWritePart *part = new KateDocument (bWantSingleView, bWantBrowserView, bWantReadOnly, parentWidget, parent);
      part->setReadWrite( !bWantReadOnly );

      return part;
    }
};

K_EXPORT_PLUGIN( KateFactory )

// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>same here, mostly my code, with just compile fixes by others<commit_after>/*  This file is part of the KDE libraries and the Kate part.
 *
 *  Copyright (C) 2001-2010 Christoph Cullmann <cullmann@kde.org>
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Library General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 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
 *  Library General Public License for more details.
 *
 *  You should have received a copy of the GNU Library General Public License
 *  along with this library; see the file COPYING.LIB.  If not, write to
 *  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 *  Boston, MA 02110-1301, USA.
 */

#include "kateglobal.h"
#include "katedocument.h"

#include <ktexteditor/factory.h>

/**
 * wrapper factory to be sure nobody external deletes our kateglobal object
 * each instance will just increment the reference counter of our internal
 * super private global instance ;)
 */
class KateFactory : public KTextEditor::Factory
{
  public:
    /**
     * constructor, increments reference count of KateGlobal
     * @param parent parent object
     * @param name name of factory
     */
    KateFactory ( QObject *parent = 0 )
      : KTextEditor::Factory (parent)
    {
      KateGlobal::incRef ();
    }

    /**
     * destructor, decrements reference count of KateGlobal
     */
    virtual ~KateFactory ()
    {
      KateGlobal::decRef ();
    }

    KTextEditor::Editor *editor () { return KateGlobal::self(); }

    /**
     * reimplemented create object method
     * @param parentWidget parent widget
     * @param parent QObject parent
     * @param args additional arguments
     * @return constructed part object
     */
    KParts::Part *createPartObject ( QWidget *parentWidget, QObject *parent, const char *_classname, const QStringList & )
    {
      QByteArray classname( _classname );

      // default to the kparts::* behavior of having one single widget() if the user don't requested a pure document
      bool bWantSingleView = ( classname != "KTextEditor::Document" );

      // does user want browserview?
      bool bWantBrowserView = false;

      // should we be readonly?
      bool bWantReadOnly = (bWantBrowserView || ( classname == "KParts::ReadOnlyPart" ));

      // set simple mode on for read-only part per default
      KateGlobal::self ()->setSimpleMode (bWantReadOnly);

      KParts::ReadWritePart *part = new KateDocument (bWantSingleView, bWantBrowserView, bWantReadOnly, parentWidget, parent);
      part->setReadWrite( !bWantReadOnly );

      return part;
    }
};

K_EXPORT_PLUGIN( KateFactory )

// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/yosys.h"
#include "kernel/sigtools.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

template<class T> bool includes(const T &lhs, const T &rhs) {
	return std::includes(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
#include "passes/pmgen/xilinx_dsp_pm.h"

void pack_xilinx_dsp(xilinx_dsp_pm &pm)
{
	auto &st = pm.st_xilinx_dsp;

#if 1
	log("\n");
	log("ffA:   %s\n", log_id(st.ffA, "--"));
	log("ffB:   %s\n", log_id(st.ffB, "--"));
	log("dsp:   %s\n", log_id(st.dsp, "--"));
	log("ffP:   %s\n", log_id(st.ffP, "--"));
	log("muxP:  %s\n", log_id(st.muxP, "--"));
	log("sigPused: %s\n", log_signal(st.sigPused));
	log_module(pm.module);
#endif

	log("Analysing %s.%s for Xilinx DSP register packing.\n", log_id(pm.module), log_id(st.dsp));

	Cell *cell = st.dsp;
	log_assert(cell);

	if (st.clock != SigBit())
	{
		cell->setPort("\\CLK", st.clock);

		if (st.ffA) {
			SigSpec A = cell->getPort("\\A");
			SigSpec D = st.ffA->getPort("\\D");
			SigSpec Q = st.ffA->getPort("\\Q");
			A.replace(Q, D);
			cell->setPort("\\A", A);
			cell->setParam("\\AREG", State::S1);
			if (st.ffA->type == "$dff")
				cell->setPort("\\CEA2", State::S1);
			else if (st.ffA->type == "$dffe")
				cell->setPort("\\CEA2", st.ffA->getPort("\\EN"));
			else log_abort();
		}
		if (st.ffB) {
			SigSpec B = cell->getPort("\\B");
			SigSpec D = st.ffB->getPort("\\D");
			SigSpec Q = st.ffB->getPort("\\Q");
			B.replace(Q, D);
			cell->setPort("\\B", B);
			cell->setParam("\\BREG", State::S1);
			if (st.ffB->type == "$dff")
				cell->setPort("\\CEB2", State::S1);
			else if (st.ffB->type == "$dffe")
				cell->setPort("\\CEB2", st.ffB->getPort("\\EN"));
			else log_abort();
		}
		if (st.ffP) {
			SigSpec P = cell->getPort("\\P");
			SigSpec D;
			if (st.muxP)
				D = st.muxP->getPort("\\B");
			else
				D = st.ffP->getPort("\\D");
			SigSpec Q = st.ffP->getPort("\\Q");
			P.replace(pm.sigmap(D), Q);
			cell->setPort("\\P", P);
			cell->setParam("\\PREG", State::S1);
			if (st.ffP->type == "$dff")
				cell->setPort("\\CEP", State::S1);
			else if (st.ffP->type == "$dffe")
				cell->setPort("\\CEP", st.ffP->getPort("\\EN"));
			else log_abort();

			st.ffP->connections_.at("\\Q").replace(P, pm.module->addWire(NEW_ID, GetSize(P)));
		}

		log("  clock: %s (%s)", log_signal(st.clock), "posedge");

		if (st.ffA)
			log(" ffA:%s", log_id(st.ffA));

		if (st.ffB)
			log(" ffB:%s", log_id(st.ffB));

		if (st.ffP)
			log(" ffY:%s", log_id(st.ffP));

		log("\n");
	}

	pm.blacklist(cell);
}

struct Ice40DspPass : public Pass {
	Ice40DspPass() : Pass("xilinx_dsp", "Xilinx: pack DSP registers") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    xilinx_dsp [options] [selection]\n");
		log("\n");
		log("Pack registers into Xilinx DSPs\n");
		log("\n");
	}
	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		log_header(design, "Executing XILINX_DSP pass (pack DSPs).\n");

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			// if (args[argidx] == "-singleton") {
			// 	singleton_mode = true;
			// 	continue;
			// }
			break;
		}
		extra_args(args, argidx, design);

		for (auto module : design->selected_modules())
			xilinx_dsp_pm(module, module->selected_cells()).run_xilinx_dsp(pack_xilinx_dsp);
	}
} Ice40DspPass;

PRIVATE_NAMESPACE_END
<commit_msg>Disable $dffe<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/yosys.h"
#include "kernel/sigtools.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

template<class T> bool includes(const T &lhs, const T &rhs) {
	return std::includes(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
#include "passes/pmgen/xilinx_dsp_pm.h"

void pack_xilinx_dsp(xilinx_dsp_pm &pm)
{
	auto &st = pm.st_xilinx_dsp;

#if 1
	log("\n");
	log("ffA:   %s\n", log_id(st.ffA, "--"));
	log("ffB:   %s\n", log_id(st.ffB, "--"));
	log("dsp:   %s\n", log_id(st.dsp, "--"));
	log("ffP:   %s\n", log_id(st.ffP, "--"));
	log("muxP:  %s\n", log_id(st.muxP, "--"));
	log("sigPused: %s\n", log_signal(st.sigPused));
	log_module(pm.module);
#endif

	log("Analysing %s.%s for Xilinx DSP register packing.\n", log_id(pm.module), log_id(st.dsp));

	Cell *cell = st.dsp;
	log_assert(cell);

	if (st.clock != SigBit())
	{
		cell->setPort("\\CLK", st.clock);

		if (st.ffA) {
			SigSpec A = cell->getPort("\\A");
			SigSpec D = st.ffA->getPort("\\D");
			SigSpec Q = st.ffA->getPort("\\Q");
			A.replace(Q, D);
			cell->setPort("\\A", A);
			cell->setParam("\\AREG", 1);
			if (st.ffA->type == "$dff")
				cell->setPort("\\CEA2", State::S1);
			//else if (st.ffA->type == "$dffe")
			//	cell->setPort("\\CEA2", st.ffA->getPort("\\EN"));
			else log_abort();
		}
		if (st.ffB) {
			SigSpec B = cell->getPort("\\B");
			SigSpec D = st.ffB->getPort("\\D");
			SigSpec Q = st.ffB->getPort("\\Q");
			B.replace(Q, D);
			cell->setPort("\\B", B);
			cell->setParam("\\BREG", 1);
			if (st.ffB->type == "$dff")
				cell->setPort("\\CEB2", State::S1);
			//else if (st.ffB->type == "$dffe")
			//	cell->setPort("\\CEB2", st.ffB->getPort("\\EN"));
			else log_abort();
		}
		if (st.ffP) {
			SigSpec P = cell->getPort("\\P");
			SigSpec D;
			if (st.muxP)
				D = st.muxP->getPort("\\B");
			else
				D = st.ffP->getPort("\\D");
			SigSpec Q = st.ffP->getPort("\\Q");
			P.replace(pm.sigmap(D), Q);
			cell->setPort("\\P", P);
			cell->setParam("\\PREG", State::S1);
			if (st.ffP->type == "$dff")
				cell->setPort("\\CEP", State::S1);
			//else if (st.ffP->type == "$dffe")
			//	cell->setPort("\\CEP", st.ffP->getPort("\\EN"));
			else log_abort();

			st.ffP->connections_.at("\\Q").replace(P, pm.module->addWire(NEW_ID, GetSize(P)));
		}

		log("  clock: %s (%s)", log_signal(st.clock), "posedge");

		if (st.ffA)
			log(" ffA:%s", log_id(st.ffA));

		if (st.ffB)
			log(" ffB:%s", log_id(st.ffB));

		if (st.ffP)
			log(" ffY:%s", log_id(st.ffP));

		log("\n");
	}

	pm.blacklist(cell);
}

struct Ice40DspPass : public Pass {
	Ice40DspPass() : Pass("xilinx_dsp", "Xilinx: pack DSP registers") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    xilinx_dsp [options] [selection]\n");
		log("\n");
		log("Pack registers into Xilinx DSPs\n");
		log("\n");
	}
	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		log_header(design, "Executing XILINX_DSP pass (pack DSPs).\n");

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			// if (args[argidx] == "-singleton") {
			// 	singleton_mode = true;
			// 	continue;
			// }
			break;
		}
		extra_args(args, argidx, design);

		for (auto module : design->selected_modules())
			xilinx_dsp_pm(module, module->selected_cells()).run_xilinx_dsp(pack_xilinx_dsp);
	}
} Ice40DspPass;

PRIVATE_NAMESPACE_END
<|endoftext|>


<commit_before>/*
    Copyright (c) 2016-2017 ZeroMQ community
    Copyright (c) 2016 VOCA AS / Harald Nøkland

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

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

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

#ifndef __ZMQ_ADDON_HPP_INCLUDED__
#define __ZMQ_ADDON_HPP_INCLUDED__

#include <zmq.hpp>

#include <deque>
#include <iomanip>
#include <sstream>
#include <stdexcept>

namespace zmq {

#ifdef ZMQ_HAS_RVALUE_REFS

/*
    This class handles multipart messaging. It is the C++ equivalent of zmsg.h,
    which is part of CZMQ (the high-level C binding). Furthermore, it is a major
    improvement compared to zmsg.hpp, which is part of the examples in the ØMQ
    Guide. Unnecessary copying is avoided by using move semantics to efficiently
    add/remove parts.
*/
class multipart_t
{
private:
    std::deque<message_t> m_parts;

public:

    typedef std::deque<message_t>::iterator iterator;
    typedef std::deque<message_t>::const_iterator const_iterator;

    typedef std::deque<message_t>::reverse_iterator reverse_iterator;
    typedef std::deque<message_t>::const_reverse_iterator const_reverse_iterator;

    // Default constructor
    multipart_t()
    {}

    // Construct from socket receive
    multipart_t(socket_t& socket)
    {
        recv(socket);
    }

    // Construct from memory block
    multipart_t(const void *src, size_t size)
    {
        addmem(src, size);
    }

    // Construct from string
    multipart_t(const std::string& string)
    {
        addstr(string);
    }

    // Construct from message part
    multipart_t(message_t&& message)
    {
        add(std::move(message));
    }

    // Move constructor
    multipart_t(multipart_t&& other)
    {
        m_parts = std::move(other.m_parts);
    }

    // Move assignment operator
    multipart_t& operator=(multipart_t&& other)
    {
        m_parts = std::move(other.m_parts);
        return *this;
    }

    // Destructor
    virtual ~multipart_t()
    {
        clear();
    }

    message_t& operator[] (size_t n)
    {
        return m_parts[n];
    }

    const message_t& operator[] (size_t n) const
    {
        return m_parts[n];
    }

    message_t& at (size_t n)
    {
        return m_parts.at(n);
    }

    const message_t& at (size_t n) const
    {
        return m_parts.at(n);
    }

    iterator begin()
    {
        return m_parts.begin();
    }

    const_iterator begin() const
    {
        return m_parts.begin();
    }

    const_iterator cbegin() const
    {
        return m_parts.cbegin();
    }

    reverse_iterator rbegin()
    {
        return m_parts.rbegin();
    }

    const_reverse_iterator rbegin() const
    {
        return m_parts.rbegin();
    }

    iterator end()
    {
        return m_parts.end();
    }

    const_iterator end() const
    {
        return m_parts.end();
    }

    const_iterator cend() const
    {
        return m_parts.cend();
    }

    reverse_iterator rend()
    {
        return m_parts.rend();
    }

    const_reverse_iterator rend() const
    {
        return m_parts.rend();
    }

    // Delete all parts
    void clear()
    {
        m_parts.clear();
    }

    // Get number of parts
    size_t size() const
    {
        return m_parts.size();
    }

    // Check if number of parts is zero
    bool empty() const
    {
        return m_parts.empty();
    }

    // Receive multipart message from socket
    bool recv(socket_t& socket, int flags = 0)
    {
        clear();
        bool more = true;
        while (more)
        {
            message_t message;
            if (!socket.recv(&message, flags))
                return false;
            more = message.more();
            add(std::move(message));
        }
        return true;
    }

    // Send multipart message to socket
    bool send(socket_t& socket, int flags = 0)
    {
        flags &= ~(ZMQ_SNDMORE);
        bool more = size() > 0;
        while (more)
        {
            message_t message = pop();
            more = size() > 0;
            if (!socket.send(message, (more ? ZMQ_SNDMORE : 0) | flags))
                return false;
        }
        clear();
        return true;
    }

    // Concatenate other multipart to front
    void prepend(multipart_t&& other)
    {
        while (!other.empty())
            push(other.remove());
    }

    // Concatenate other multipart to back
    void append(multipart_t&& other)
    {
        while (!other.empty())
            add(other.pop());
    }

    // Push memory block to front
    void pushmem(const void *src, size_t size)
    {
        m_parts.push_front(message_t(src, size));
    }

    // Push memory block to back
    void addmem(const void *src, size_t size)
    {
        m_parts.push_back(message_t(src, size));
    }

    // Push string to front
    void pushstr(const std::string& string)
    {
        m_parts.push_front(message_t(string.data(), string.size()));
    }

    // Push string to back
    void addstr(const std::string& string)
    {
        m_parts.push_back(message_t(string.data(), string.size()));
    }

    // Push type (fixed-size) to front
    template<typename T>
    void pushtyp(const T& type)
    {
        static_assert(!std::is_same<T, std::string>::value, "Use pushstr() instead of pushtyp<std::string>()");
        m_parts.push_front(message_t(&type, sizeof(type)));
    }

    // Push type (fixed-size) to back
    template<typename T>
    void addtyp(const T& type)
    {
        static_assert(!std::is_same<T, std::string>::value, "Use addstr() instead of addtyp<std::string>()");
        m_parts.push_back(message_t(&type, sizeof(type)));
    }

    // Push message part to front
    void push(message_t&& message)
    {
        m_parts.push_front(std::move(message));
    }

    // Push message part to back
    void add(message_t&& message)
    {
        m_parts.push_back(std::move(message));
    }

    // Pop string from front
    std::string popstr()
    {
        std::string string(m_parts.front().data<char>(), m_parts.front().size());
        m_parts.pop_front();
        return string;
    }

    // Pop type (fixed-size) from front
    template<typename T>
    T poptyp()
    {
        static_assert(!std::is_same<T, std::string>::value, "Use popstr() instead of poptyp<std::string>()");
        if (sizeof(T) != m_parts.front().size())
            throw std::runtime_error("Invalid type, size does not match the message size");
        T type = *m_parts.front().data<T>();
        m_parts.pop_front();
        return type;
    }

    // Pop message part from front
    message_t pop()
    {
        message_t message = std::move(m_parts.front());
        m_parts.pop_front();
        return message;
    }

    // Pop message part from back
    message_t remove()
    {
        message_t message = std::move(m_parts.back());
        m_parts.pop_back();
        return message;
    }

    // Get pointer to a specific message part
    const message_t* peek(size_t index) const
    {
        return &m_parts[index];
    }

    // Get a string copy of a specific message part
    std::string peekstr(size_t index) const
    {
        std::string string(m_parts[index].data<char>(), m_parts[index].size());
        return string;
    }

    // Peek type (fixed-size) from front
    template<typename T>
    T peektyp(size_t index) const
    {
        static_assert(!std::is_same<T, std::string>::value, "Use peekstr() instead of peektyp<std::string>()");
        if(sizeof(T) != m_parts[index].size())
            throw std::runtime_error("Invalid type, size does not match the message size");
        T type = *m_parts[index].data<T>();
        return type;
    }

    // Create multipart from type (fixed-size)
    template<typename T>
    static multipart_t create(const T& type)
    {
        multipart_t multipart;
        multipart.addtyp(type);
        return multipart;
    }

    // Copy multipart
    multipart_t clone() const
    {
        multipart_t multipart;
        for (size_t i = 0; i < size(); i++)
            multipart.addmem(m_parts[i].data(), m_parts[i].size());
        return multipart;
    }

    // Dump content to string
    std::string str() const
    {
        std::stringstream ss;
        for (size_t i = 0; i < m_parts.size(); i++)
        {
            const unsigned char* data = m_parts[i].data<unsigned char>();
            size_t size = m_parts[i].size();

            // Dump the message as text or binary
            bool isText = true;
            for (size_t j = 0; j < size; j++)
            {
                if (data[j] < 32 || data[j] > 127)
                {
                    isText = false;
                    break;
                }
            }
            ss << "\n[" << std::dec << std::setw(3) << std::setfill('0') << size << "] ";
            if (size >= 1000)
            {
                ss << "... (to big to print)";
                continue;
            }
            for (size_t j = 0; j < size; j++)
            {
                if (isText)
                    ss << static_cast<char>(data[j]);
                else
                    ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<short>(data[j]);
            }
        }
        return ss.str();
    }

    // Check if equal to other multipart
    bool equal(const multipart_t* other) const
    {
        if (size() != other->size())
            return false;
        for (size_t i = 0; i < size(); i++)
            if (!peek(i)->equal(other->peek(i)))
                return false;
        return true;
    }

private:
    // Disable implicit copying (moving is more efficient)
    multipart_t(const multipart_t& other) ZMQ_DELETED_FUNCTION;
    void operator=(const multipart_t& other) ZMQ_DELETED_FUNCTION;
};  // class multipart_t

#endif  // ZMQ_HAS_RVALUE_REFS

inline std::ostream& operator<<(std::ostream& os, const multipart_t& msg)
{
    return os << msg.str();
}

#if defined(ZMQ_BUILD_DRAFT_API) && defined(ZMQ_CPP11) && defined(ZMQ_HAVE_POLLER)
    class active_poller_t
    {
    public:
        active_poller_t () = default;
        ~active_poller_t () = default;

        active_poller_t(const active_poller_t&) = delete;
        active_poller_t &operator=(const active_poller_t&) = delete;

        active_poller_t(active_poller_t&& src) = default;
        active_poller_t &operator=(active_poller_t&& src) = default;

        using handler_t = std::function<void(short)>;

        void add (zmq::socket_t &socket, short events, handler_t handler)
        {
            auto it = decltype (handlers)::iterator {};
            auto inserted = bool {};
            std::tie(it, inserted) = handlers.emplace (static_cast<void*>(socket), std::make_shared<handler_t> (std::move (handler)));
            try
            {
                base_poller.add (socket, events, inserted && *(it->second) ? it->second.get() : nullptr);
                need_rebuild |= inserted;
            }
            catch (const zmq::error_t&)
            {
                // rollback
                if (inserted)
                {
                    handlers.erase (static_cast<void*>(socket));
                }
                throw;
            }
        }

        void remove (zmq::socket_t &socket)
        {
            base_poller.remove (socket);
            handlers.erase (static_cast<void*>(socket));
            need_rebuild = true;
        }

        void modify (zmq::socket_t &socket, short events)
        {
            base_poller.modify (socket, events);
        }

        int wait (std::chrono::milliseconds timeout)
        {
            if (need_rebuild) {
                poller_events.clear ();
                poller_handlers.clear ();
                poller_events.reserve (handlers.size ());
                poller_handlers.reserve (handlers.size ());
                for (const auto &handler : handlers) {
                    poller_events.emplace_back (zmq_poller_event_t {});
                    poller_handlers.push_back (handler.second);
                }
                need_rebuild = false;
            }
            const int count = base_poller.wait_all (poller_events, timeout);
            if (count != 0) {
                std::for_each (poller_events.begin (), poller_events.begin () + count,
                               [](zmq_poller_event_t& event) {
                    if (event.user_data != NULL)
                        (*reinterpret_cast<handler_t*> (event.user_data)) (event.events);
                });
            }
            return count;
        }

        bool empty () const
        {
            return handlers.empty ();
        }

        size_t size () const
        {
            return handlers.size ();
        }

    private:
        bool need_rebuild {false};

        poller_t<handler_t> base_poller {};
        std::unordered_map<void*, std::shared_ptr<handler_t>> handlers {};
        std::vector<zmq_poller_event_t> poller_events {};
        std::vector<std::shared_ptr<handler_t>> poller_handlers {};
    };  // class active_poller_t
#endif //  defined(ZMQ_BUILD_DRAFT_API) && defined(ZMQ_CPP11) && defined(ZMQ_HAVE_POLLER)

}  // namespace zmq

#endif  // __ZMQ_ADDON_HPP_INCLUDED__
<commit_msg>Problem: deprecation warning in multipart_t<commit_after>/*
    Copyright (c) 2016-2017 ZeroMQ community
    Copyright (c) 2016 VOCA AS / Harald Nøkland

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

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

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

#ifndef __ZMQ_ADDON_HPP_INCLUDED__
#define __ZMQ_ADDON_HPP_INCLUDED__

#include <zmq.hpp>

#include <deque>
#include <iomanip>
#include <sstream>
#include <stdexcept>

namespace zmq {

#ifdef ZMQ_HAS_RVALUE_REFS

/*
    This class handles multipart messaging. It is the C++ equivalent of zmsg.h,
    which is part of CZMQ (the high-level C binding). Furthermore, it is a major
    improvement compared to zmsg.hpp, which is part of the examples in the ØMQ
    Guide. Unnecessary copying is avoided by using move semantics to efficiently
    add/remove parts.
*/
class multipart_t
{
private:
    std::deque<message_t> m_parts;

public:

    typedef std::deque<message_t>::iterator iterator;
    typedef std::deque<message_t>::const_iterator const_iterator;

    typedef std::deque<message_t>::reverse_iterator reverse_iterator;
    typedef std::deque<message_t>::const_reverse_iterator const_reverse_iterator;

    // Default constructor
    multipart_t()
    {}

    // Construct from socket receive
    multipart_t(socket_t& socket)
    {
        recv(socket);
    }

    // Construct from memory block
    multipart_t(const void *src, size_t size)
    {
        addmem(src, size);
    }

    // Construct from string
    multipart_t(const std::string& string)
    {
        addstr(string);
    }

    // Construct from message part
    multipart_t(message_t&& message)
    {
        add(std::move(message));
    }

    // Move constructor
    multipart_t(multipart_t&& other)
    {
        m_parts = std::move(other.m_parts);
    }

    // Move assignment operator
    multipart_t& operator=(multipart_t&& other)
    {
        m_parts = std::move(other.m_parts);
        return *this;
    }

    // Destructor
    virtual ~multipart_t()
    {
        clear();
    }

    message_t& operator[] (size_t n)
    {
        return m_parts[n];
    }

    const message_t& operator[] (size_t n) const
    {
        return m_parts[n];
    }

    message_t& at (size_t n)
    {
        return m_parts.at(n);
    }

    const message_t& at (size_t n) const
    {
        return m_parts.at(n);
    }

    iterator begin()
    {
        return m_parts.begin();
    }

    const_iterator begin() const
    {
        return m_parts.begin();
    }

    const_iterator cbegin() const
    {
        return m_parts.cbegin();
    }

    reverse_iterator rbegin()
    {
        return m_parts.rbegin();
    }

    const_reverse_iterator rbegin() const
    {
        return m_parts.rbegin();
    }

    iterator end()
    {
        return m_parts.end();
    }

    const_iterator end() const
    {
        return m_parts.end();
    }

    const_iterator cend() const
    {
        return m_parts.cend();
    }

    reverse_iterator rend()
    {
        return m_parts.rend();
    }

    const_reverse_iterator rend() const
    {
        return m_parts.rend();
    }

    // Delete all parts
    void clear()
    {
        m_parts.clear();
    }

    // Get number of parts
    size_t size() const
    {
        return m_parts.size();
    }

    // Check if number of parts is zero
    bool empty() const
    {
        return m_parts.empty();
    }

    // Receive multipart message from socket
    bool recv(socket_t& socket, int flags = 0)
    {
        clear();
        bool more = true;
        while (more)
        {
            message_t message;
            if (!socket.recv(&message, flags))
                return false;
            more = message.more();
            add(std::move(message));
        }
        return true;
    }

    // Send multipart message to socket
    bool send(socket_t& socket, int flags = 0)
    {
        flags &= ~(ZMQ_SNDMORE);
        bool more = size() > 0;
        while (more)
        {
            message_t message = pop();
            more = size() > 0;
            if (!socket.send(message, (more ? ZMQ_SNDMORE : 0) | flags))
                return false;
        }
        clear();
        return true;
    }

    // Concatenate other multipart to front
    void prepend(multipart_t&& other)
    {
        while (!other.empty())
            push(other.remove());
    }

    // Concatenate other multipart to back
    void append(multipart_t&& other)
    {
        while (!other.empty())
            add(other.pop());
    }

    // Push memory block to front
    void pushmem(const void *src, size_t size)
    {
        m_parts.push_front(message_t(src, size));
    }

    // Push memory block to back
    void addmem(const void *src, size_t size)
    {
        m_parts.push_back(message_t(src, size));
    }

    // Push string to front
    void pushstr(const std::string& string)
    {
        m_parts.push_front(message_t(string.data(), string.size()));
    }

    // Push string to back
    void addstr(const std::string& string)
    {
        m_parts.push_back(message_t(string.data(), string.size()));
    }

    // Push type (fixed-size) to front
    template<typename T>
    void pushtyp(const T& type)
    {
        static_assert(!std::is_same<T, std::string>::value, "Use pushstr() instead of pushtyp<std::string>()");
        m_parts.push_front(message_t(&type, sizeof(type)));
    }

    // Push type (fixed-size) to back
    template<typename T>
    void addtyp(const T& type)
    {
        static_assert(!std::is_same<T, std::string>::value, "Use addstr() instead of addtyp<std::string>()");
        m_parts.push_back(message_t(&type, sizeof(type)));
    }

    // Push message part to front
    void push(message_t&& message)
    {
        m_parts.push_front(std::move(message));
    }

    // Push message part to back
    void add(message_t&& message)
    {
        m_parts.push_back(std::move(message));
    }

    // Pop string from front
    std::string popstr()
    {
        std::string string(m_parts.front().data<char>(), m_parts.front().size());
        m_parts.pop_front();
        return string;
    }

    // Pop type (fixed-size) from front
    template<typename T>
    T poptyp()
    {
        static_assert(!std::is_same<T, std::string>::value, "Use popstr() instead of poptyp<std::string>()");
        if (sizeof(T) != m_parts.front().size())
            throw std::runtime_error("Invalid type, size does not match the message size");
        T type = *m_parts.front().data<T>();
        m_parts.pop_front();
        return type;
    }

    // Pop message part from front
    message_t pop()
    {
        message_t message = std::move(m_parts.front());
        m_parts.pop_front();
        return message;
    }

    // Pop message part from back
    message_t remove()
    {
        message_t message = std::move(m_parts.back());
        m_parts.pop_back();
        return message;
    }

    // Get pointer to a specific message part
    const message_t* peek(size_t index) const
    {
        return &m_parts[index];
    }

    // Get a string copy of a specific message part
    std::string peekstr(size_t index) const
    {
        std::string string(m_parts[index].data<char>(), m_parts[index].size());
        return string;
    }

    // Peek type (fixed-size) from front
    template<typename T>
    T peektyp(size_t index) const
    {
        static_assert(!std::is_same<T, std::string>::value, "Use peekstr() instead of peektyp<std::string>()");
        if(sizeof(T) != m_parts[index].size())
            throw std::runtime_error("Invalid type, size does not match the message size");
        T type = *m_parts[index].data<T>();
        return type;
    }

    // Create multipart from type (fixed-size)
    template<typename T>
    static multipart_t create(const T& type)
    {
        multipart_t multipart;
        multipart.addtyp(type);
        return multipart;
    }

    // Copy multipart
    multipart_t clone() const
    {
        multipart_t multipart;
        for (size_t i = 0; i < size(); i++)
            multipart.addmem(m_parts[i].data(), m_parts[i].size());
        return multipart;
    }

    // Dump content to string
    std::string str() const
    {
        std::stringstream ss;
        for (size_t i = 0; i < m_parts.size(); i++)
        {
            const unsigned char* data = m_parts[i].data<unsigned char>();
            size_t size = m_parts[i].size();

            // Dump the message as text or binary
            bool isText = true;
            for (size_t j = 0; j < size; j++)
            {
                if (data[j] < 32 || data[j] > 127)
                {
                    isText = false;
                    break;
                }
            }
            ss << "\n[" << std::dec << std::setw(3) << std::setfill('0') << size << "] ";
            if (size >= 1000)
            {
                ss << "... (to big to print)";
                continue;
            }
            for (size_t j = 0; j < size; j++)
            {
                if (isText)
                    ss << static_cast<char>(data[j]);
                else
                    ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<short>(data[j]);
            }
        }
        return ss.str();
    }

    // Check if equal to other multipart
    bool equal(const multipart_t* other) const
    {
        if (size() != other->size())
            return false;
        for (size_t i = 0; i < size(); i++)
            if (*peek(i) != *other->peek(i))
                return false;
        return true;
    }

private:
    // Disable implicit copying (moving is more efficient)
    multipart_t(const multipart_t& other) ZMQ_DELETED_FUNCTION;
    void operator=(const multipart_t& other) ZMQ_DELETED_FUNCTION;
};  // class multipart_t

inline std::ostream& operator<<(std::ostream& os, const multipart_t& msg)
{
    return os << msg.str();
}

#endif  // ZMQ_HAS_RVALUE_REFS

#if defined(ZMQ_BUILD_DRAFT_API) && defined(ZMQ_CPP11) && defined(ZMQ_HAVE_POLLER)
    class active_poller_t
    {
    public:
        active_poller_t () = default;
        ~active_poller_t () = default;

        active_poller_t(const active_poller_t&) = delete;
        active_poller_t &operator=(const active_poller_t&) = delete;

        active_poller_t(active_poller_t&& src) = default;
        active_poller_t &operator=(active_poller_t&& src) = default;

        using handler_t = std::function<void(short)>;

        void add (zmq::socket_t &socket, short events, handler_t handler)
        {
            auto it = decltype (handlers)::iterator {};
            auto inserted = bool {};
            std::tie(it, inserted) = handlers.emplace (static_cast<void*>(socket), std::make_shared<handler_t> (std::move (handler)));
            try
            {
                base_poller.add (socket, events, inserted && *(it->second) ? it->second.get() : nullptr);
                need_rebuild |= inserted;
            }
            catch (const zmq::error_t&)
            {
                // rollback
                if (inserted)
                {
                    handlers.erase (static_cast<void*>(socket));
                }
                throw;
            }
        }

        void remove (zmq::socket_t &socket)
        {
            base_poller.remove (socket);
            handlers.erase (static_cast<void*>(socket));
            need_rebuild = true;
        }

        void modify (zmq::socket_t &socket, short events)
        {
            base_poller.modify (socket, events);
        }

        int wait (std::chrono::milliseconds timeout)
        {
            if (need_rebuild) {
                poller_events.clear ();
                poller_handlers.clear ();
                poller_events.reserve (handlers.size ());
                poller_handlers.reserve (handlers.size ());
                for (const auto &handler : handlers) {
                    poller_events.emplace_back (zmq_poller_event_t {});
                    poller_handlers.push_back (handler.second);
                }
                need_rebuild = false;
            }
            const int count = base_poller.wait_all (poller_events, timeout);
            if (count != 0) {
                std::for_each (poller_events.begin (), poller_events.begin () + count,
                               [](zmq_poller_event_t& event) {
                    if (event.user_data != NULL)
                        (*reinterpret_cast<handler_t*> (event.user_data)) (event.events);
                });
            }
            return count;
        }

        bool empty () const
        {
            return handlers.empty ();
        }

        size_t size () const
        {
            return handlers.size ();
        }

    private:
        bool need_rebuild {false};

        poller_t<handler_t> base_poller {};
        std::unordered_map<void*, std::shared_ptr<handler_t>> handlers {};
        std::vector<zmq_poller_event_t> poller_events {};
        std::vector<std::shared_ptr<handler_t>> poller_handlers {};
    };  // class active_poller_t
#endif //  defined(ZMQ_BUILD_DRAFT_API) && defined(ZMQ_CPP11) && defined(ZMQ_HAVE_POLLER)

}  // namespace zmq

#endif  // __ZMQ_ADDON_HPP_INCLUDED__
<|endoftext|>


<commit_before>#include <cstring>
#include <vector>

#include "IQOAreaResizerImpl.hpp"

namespace iqo {

    //! Calculate number of coefficients for area resampling
    size_t calcNumCoefsForArea(size_t srcLen, size_t dstLen)
    {
        // down-sampling
        //
        // case decimal number of coefs:
        //        scale = 5:4
        // num of coefs = ceil(5/4) = 2
        //
        //  |   o   |   o   |   o   |   o   |   o   |
        //  |    o    |    o    |    o    |    o    |
        //  +---------+
        // 0.0        +---------+
        //           1.25       +---------+
        //                     2.5        +---------+
        //                               3.75      5.0
        //
        // case decimal number of coefs:
        //        scale = 5:3
        // num of coefs = ceil(5/3) = 2 -> 3
        //  |  o  |  o  |  o  |  o  |  o  |
        //  |    o    |    o    |    o    |
        //  +---------+
        // 0.0        +---------+
        //           1.66  :    +---------+
        //                 :   3.33      5.0
        //                 :
        //              3 coefs
        //   (1.66-2.0, 2.0-3.0, 3.0-3.33)
        //
        // if ( lcm(1.0, scale-floor(scale)) > 1.0 ) { numCoefs += 1; }
        //
        // 3 times to source (3 is destination length)
        //  | o | o | o | o | o | o | o | o | o | o | o | o | o | o | o |
        //  |         o         |         o         |         o         |
        //  +-------------------+
        // 0.0          :       +-------------------+
        //             1.0     1.66                 +-------------------+
        //                                         3.33                5.0
        //
        // 1.66 * 3 = 5
        // floor(1.66) * 3 = (int(5) / int(3)) * 3 = 3
        // if ( lcm(5, 5 - (int(5) / int(3))*3) > 5 ) { numCoefs += 1; }

        size_t iScale = (srcLen / dstLen) * dstLen;             // floor(src/dst) * dst
        size_t numCoefs = alignCeil(srcLen, dstLen) / dstLen;   // ceil(src/dst)
        if ( lcm(srcLen, iScale) > ptrdiff_t(srcLen) ) {
            numCoefs++;
        }

        return numCoefs;
    }

    //! @brief Set Area table
    //! @param srcLen     Number of pixels of the source image
    //! @param dstLen     Number of pixels of the destination image
    //! @param dstOffset  The coordinate of the destination image
    //! @param numCoefs   Number of coefficients
    //! @param fTable     The table
    //! @return Sum of the table
    float setAreaTable(
        size_t srcLen,
        size_t dstLen,
        ptrdiff_t dstOffset,
        int numCoefs,
        float * __restrict fTable
    ) {

        double srcBeginX = ( dstOffset      * srcLen) / double(dstLen);
        double srcEndX   = ((dstOffset + 1) * srcLen) / double(dstLen);
        double srcX = srcBeginX;
        float fSum = 0;

        for ( ptrdiff_t i = 0; i < numCoefs; ++i ) {
            //     nextSrcX = std::min(srcEndX, std::floor(srcX + 1.0))
            double nextSrcX = std::min(srcEndX, std::floor(srcX) + 1.0);
            float v = float(nextSrcX - srcX);
            fTable[i] = v;
            fSum     += v;
            srcX = nextSrcX;
        }

        return fSum;
    }

    template<>
    class AreaResizerImpl<ArchGeneric> : public IAreaResizerImpl
    {
    public:
        //! Destructor
        virtual ~AreaResizerImpl() {}

        //! Construct
        virtual void init(
            size_t srcW, size_t srcH,
            size_t dstW, size_t dstH
        );

        //! Run image resizing
        virtual void resize(
            size_t srcSt, const uint8_t * src,
            size_t dstSt, uint8_t * dst
        );

    private:
        //! round(a / b)
        static int roundedDiv(int a, int b, int biasbit)
        {
            const int k0_5 = (1 << biasbit) / 2;
            return (a + k0_5) / b;
        }

        //! fixed_point_to_int(round(a))
        static int convertToInt(int a, int biasbit)
        {
            const int k0_5 = (1 << biasbit) / 2;
            return (a + k0_5) >> biasbit;
        }

        //! dst[i] = src[i] * kBias / srcSum (src will be broken)
        void adjustCoefs(
            float * srcBegin, float * srcEnd,
            float srcSum,
            int bias,
            int16_t * dst
        );

        void resizeYmain(
            ptrdiff_t srcSt, const uint8_t * src,
            ptrdiff_t dstW, int16_t * dst,
            ptrdiff_t srcOY,
            const int16_t * coefs
        );
        void resizeX(const int16_t * src, uint8_t * dst);
        void resizeXmain(const int16_t * src, uint8_t * dst);

        enum {
            // for fixed point
            kBiasBit = 6,
            kBias    = 1 << kBiasBit,

            kBias15Bit = 15,
            kBias15  = 1 << kBias15Bit,
        };

        ptrdiff_t m_SrcW;
        ptrdiff_t m_SrcH;
        ptrdiff_t m_DstW;
        ptrdiff_t m_DstH;
        ptrdiff_t m_NumCoefsX;
        ptrdiff_t m_NumCoefsY;
        ptrdiff_t m_NumTablesX;
        ptrdiff_t m_NumTablesY;
        std::vector<int16_t> m_TablesX; //!< Area table * m_NumTablesX
        std::vector<int16_t> m_TablesY; //!< Area table * m_NumTablesY
        std::vector<int16_t> m_Work;    //!< working memory
        std::vector<int16_t> m_Nume;
        std::vector<int16_t> m_Deno;
    };

    template<>
    bool AreaResizerImpl_hasFeature<ArchGeneric>()
    {
        return true;
    }

    template<>
    IAreaResizerImpl * AreaResizerImpl_new<ArchGeneric>()
    {
        return new AreaResizerImpl<ArchGeneric>();
    }

    // Constructor
    void AreaResizerImpl<ArchGeneric>::init(
        size_t srcW, size_t srcH,
        size_t dstW, size_t dstH
    ) {
        m_SrcW = srcW;
        m_SrcH = srcH;
        m_DstW = dstW;
        m_DstH = dstH;

        // setup coefficients
        size_t gcdW = gcd(m_SrcW, m_DstW);
        size_t gcdH = gcd(m_SrcH, m_DstH);
        size_t rSrcW = m_SrcW / gcdW;   // reduction
        size_t rDstW = m_DstW / gcdW;
        size_t rSrcH = m_SrcH / gcdH;
        size_t rDstH = m_DstH / gcdH;
        m_NumCoefsX = calcNumCoefsForArea(rSrcW, rDstW);
        m_NumCoefsY = calcNumCoefsForArea(rSrcH, rDstH);
        m_NumTablesX = rDstW;
        m_NumTablesY = rDstH;
        m_TablesX.reserve(m_NumCoefsX * m_NumTablesX);
        m_TablesX.resize(m_NumCoefsX * m_NumTablesX);
        m_TablesY.reserve(m_NumCoefsY * m_NumTablesY);
        m_TablesY.resize(m_NumCoefsY * m_NumTablesY);

        std::vector<float> tablesX(m_NumCoefsX);
        for ( ptrdiff_t dstX = 0; dstX < m_NumTablesX; ++dstX ) {
            int16_t * table = &m_TablesX[dstX * m_NumCoefsX];
            double sumCoefs = setAreaTable(rSrcW, rDstW, dstX, m_NumCoefsX, &tablesX[0]);
            adjustCoefs(&tablesX[0], &tablesX[m_NumCoefsX], sumCoefs, kBias15, &table[0]);
        }
        std::vector<float> tablesY(m_NumCoefsY);
        for ( ptrdiff_t dstY = 0; dstY < m_NumTablesY; ++dstY ) {
            int16_t * table = &m_TablesY[dstY * m_NumCoefsY];
            double sumCoefs = setAreaTable(rSrcH, rDstH, dstY, m_NumCoefsY, &tablesY[0]);
            adjustCoefs(&tablesY[0], &tablesY[m_NumCoefsY], sumCoefs, kBias, &table[0]);
        }

        // allocate workspace
        m_Work.reserve(m_SrcW);
        m_Work.resize(m_SrcW);
        size_t maxW = std::max(m_SrcW, m_DstW);
        m_Nume.reserve(maxW);
        m_Nume.resize(maxW);
        m_Deno.reserve(maxW);
        m_Deno.resize(maxW);
    }

    void AreaResizerImpl<ArchGeneric>::adjustCoefs(
        float * __restrict srcBegin, float * __restrict srcEnd,
        float srcSum,
        int bias,
        int16_t * __restrict dst)
    {
        const int k1_0 = bias;
        size_t numCoefs = srcEnd - srcBegin;
        int dstSum = 0;

        for ( size_t i = 0; i < numCoefs; ++i ) {
            dst[i] = round(srcBegin[i] * bias / srcSum);
            dstSum += dst[i];
        }
        while ( dstSum < k1_0 ) {
            size_t i = std::distance(&srcBegin[0], std::max_element(&srcBegin[0], &srcBegin[numCoefs]));
            dst[i]++;
            srcBegin[i] = 0;
            dstSum++;
        }
        while ( dstSum > k1_0 ) {
            size_t i = std::distance(&srcBegin[0], std::max_element(&srcBegin[0], &srcBegin[numCoefs]));
            dst[i]--;
            srcBegin[i] = 0;
            dstSum--;
        }
    }

    void AreaResizerImpl<ArchGeneric>::resize(
        size_t srcSt, const uint8_t * src,
        size_t dstSt, uint8_t * __restrict dst
    ) {
        // resize
        int16_t * work = &m_Work[0];

        if ( m_SrcH == m_DstH ) {
            // resize only X axis
            for ( ptrdiff_t y = 0; y < m_SrcH; ++y ) {
                for ( ptrdiff_t x = 0; x < m_SrcW; ++x ) {
                    m_Work[m_SrcW * y + x] = src[srcSt * y + x];
                }
                resizeX(work, &dst[dstSt * y]);
            }

            return;
        }

        ptrdiff_t numCoefs = m_NumCoefsY;
        const int16_t * tablesY = &m_TablesY[0];
        ptrdiff_t tableSize = m_NumTablesY * m_NumCoefsY;
        ptrdiff_t iTable = 0;
        LinearIterator iSrcOY(m_DstH, m_SrcH);
        ptrdiff_t dstH = m_DstH;

        // main loop
        for ( ptrdiff_t dstY = 0; dstY < dstH; ++dstY ) {
            //        srcOY = floor(dstY / scale);
            ptrdiff_t srcOY = *iSrcOY++;
            //              coefs = &tablesY[dstY % m_NumTablesY * m_NumCoefsY];
            const int16_t * coefs = &tablesY[iTable];
            iTable += numCoefs;
            if ( iTable == tableSize ) {
                iTable = 0;
            }
            resizeYmain(
                srcSt, &src[0],
                m_SrcW, work,
                srcOY,
                coefs);
            resizeX(work, &dst[dstSt * dstY]);
        }
    }

    //! resize vertical (main loop)
    //!
    //! @param srcSt  Stride in src (in byte)
    //! @param src    A row of source
    //! @param dst    A row of destination (multiplied by kBias)
    //! @param srcOY  The origin of current line
    //! @param coefs  The coefficients (multiplied by kBias)
    void AreaResizerImpl<ArchGeneric>::resizeYmain(
        ptrdiff_t srcSt, const uint8_t * src,
        ptrdiff_t dstW, int16_t * __restrict dst,
        ptrdiff_t srcOY,
        const int16_t * coefs)
    {
        ptrdiff_t numCoefs = m_NumCoefsY;

        std::memset(dst, 0, dstW * sizeof(*dst));

        for ( ptrdiff_t i = 0; i < numCoefs; ++i ) {
            int16_t coef = coefs[i];
            for ( ptrdiff_t dstX = 0; dstX < dstW; ++dstX ) {
                ptrdiff_t srcY = srcOY + i;
                dst[dstX] += src[dstX + srcSt * srcY] * coef;
            }
        }
    }

    void AreaResizerImpl<ArchGeneric>::resizeX(const int16_t * src, uint8_t * __restrict dst)
    {
        if ( m_SrcW == m_DstW ) {
            // resize only Y axis
            ptrdiff_t dstW = m_DstW;
            for ( ptrdiff_t dstX = 0; dstX < dstW; dstX++ ) {
                dst[dstX] = convertToInt(src[dstX], kBiasBit);
            }
            return;
        }

        resizeXmain(src, dst);
    }

    //! resize horizontal (main loop)
    //!
    //! @param src    A row of source (multiplied by kBias)
    //! @param dst    A row of destination
    void AreaResizerImpl<ArchGeneric>::resizeXmain(const int16_t * src, uint8_t * __restrict dst)
    {
        ptrdiff_t numCoefs = m_NumCoefsX;
        const int16_t * tablesX = &m_TablesX[0];
        ptrdiff_t tableSize = m_NumTablesX * m_NumCoefsX;
        ptrdiff_t iTable = 0;
        LinearIterator iSrcOX(m_DstW, m_SrcW);
        ptrdiff_t dstW = m_DstW;

        for ( ptrdiff_t dstX = 0; dstX < dstW; ++dstX ) {
            //        srcOX = floor(dstX / scale);
            ptrdiff_t srcOX = *iSrcOX++;
            //              coefs = &tablesX[dstX % m_NumTablesX * m_NumCoefsX];
            const int16_t * coefs = &tablesX[iTable];
            int sum = 0;

            // iTable = (iTable + m_NumCoefsX) % tableSize;
            iTable += numCoefs;
            if ( iTable == tableSize ) {
                iTable = 0;
            }
            for ( ptrdiff_t i = 0; i < numCoefs; ++i ) {
                ptrdiff_t srcX = srcOX + i;
                sum += src[srcX] * coefs[i];
            }

            dst[dstX] = clamp<int16_t>(0, 255, convertToInt(sum, kBias15Bit+kBiasBit));
        }
    }

}
<commit_msg>AreaResizer: Improve precision.<commit_after>#include <cstring>
#include <vector>

#include "IQOAreaResizerImpl.hpp"

namespace iqo {

    //! Calculate number of coefficients for area resampling
    size_t calcNumCoefsForArea(size_t srcLen, size_t dstLen)
    {
        // down-sampling
        //
        // case decimal number of coefs:
        //        scale = 5:4
        // num of coefs = ceil(5/4) = 2
        //
        //  |   o   |   o   |   o   |   o   |   o   |
        //  |    o    |    o    |    o    |    o    |
        //  +---------+
        // 0.0        +---------+
        //           1.25       +---------+
        //                     2.5        +---------+
        //                               3.75      5.0
        //
        // case decimal number of coefs:
        //        scale = 5:3
        // num of coefs = ceil(5/3) = 2 -> 3
        //  |  o  |  o  |  o  |  o  |  o  |
        //  |    o    |    o    |    o    |
        //  +---------+
        // 0.0        +---------+
        //           1.66  :    +---------+
        //                 :   3.33      5.0
        //                 :
        //              3 coefs
        //   (1.66-2.0, 2.0-3.0, 3.0-3.33)
        //
        // if ( lcm(1.0, scale-floor(scale)) > 1.0 ) { numCoefs += 1; }
        //
        // 3 times to source (3 is destination length)
        //  | o | o | o | o | o | o | o | o | o | o | o | o | o | o | o |
        //  |         o         |         o         |         o         |
        //  +-------------------+
        // 0.0          :       +-------------------+
        //             1.0     1.66                 +-------------------+
        //                                         3.33                5.0
        //
        // 1.66 * 3 = 5
        // floor(1.66) * 3 = (int(5) / int(3)) * 3 = 3
        // if ( lcm(5, 5 - (int(5) / int(3))*3) > 5 ) { numCoefs += 1; }

        size_t iScale = (srcLen / dstLen) * dstLen;             // floor(src/dst) * dst
        size_t numCoefs = alignCeil(srcLen, dstLen) / dstLen;   // ceil(src/dst)
        if ( lcm(srcLen, iScale) > ptrdiff_t(srcLen) ) {
            numCoefs++;
        }

        return numCoefs;
    }

    //! @brief Set Area table
    //! @param srcLen     Number of pixels of the source image
    //! @param dstLen     Number of pixels of the destination image
    //! @param dstOffset  The coordinate of the destination image
    //! @param numCoefs   Number of coefficients
    //! @param fTable     The table
    //! @return Sum of the table
    float setAreaTable(
        size_t srcLen,
        size_t dstLen,
        ptrdiff_t dstOffset,
        int numCoefs,
        float * __restrict fTable
    ) {

        double srcBeginX = ( dstOffset      * srcLen) / double(dstLen);
        double srcEndX   = ((dstOffset + 1) * srcLen) / double(dstLen);
        double srcX = srcBeginX;
        float fSum = 0;

        for ( ptrdiff_t i = 0; i < numCoefs; ++i ) {
            //     nextSrcX = std::min(srcEndX, std::floor(srcX + 1.0))
            double nextSrcX = std::min(srcEndX, std::floor(srcX) + 1.0);
            float v = float(nextSrcX - srcX);
            fTable[i] = v;
            fSum     += v;
            srcX = nextSrcX;
        }

        return fSum;
    }

    template<>
    class AreaResizerImpl<ArchGeneric> : public IAreaResizerImpl
    {
    public:
        //! Destructor
        virtual ~AreaResizerImpl() {}

        //! Construct
        virtual void init(
            size_t srcW, size_t srcH,
            size_t dstW, size_t dstH
        );

        //! Run image resizing
        virtual void resize(
            size_t srcSt, const uint8_t * src,
            size_t dstSt, uint8_t * dst
        );

    private:
        //! round(a / b)
        static int roundedDiv(int a, int b, int biasbit)
        {
            const int k0_5 = (1 << biasbit) / 2;
            return (a + k0_5) / b;
        }

        //! fixed_point_to_int(round(a))
        static int convertToInt(int a, int biasbit)
        {
            const int k0_5 = (1 << biasbit) / 2;
            return (a + k0_5) >> biasbit;
        }

        //! dst[i] = src[i] * kBias / srcSum (src will be broken)
        void adjustCoefs(
            float * srcBegin, float * srcEnd,
            float srcSum,
            int bias,
            uint16_t * dst
        );

        void resizeYmain(
            ptrdiff_t srcSt, const uint8_t * src,
            ptrdiff_t dstW, uint16_t * dst,
            ptrdiff_t srcOY,
            const uint16_t * coefs
        );
        void resizeX(const uint16_t * src, uint8_t * dst);
        void resizeXmain(const uint16_t * src, uint8_t * dst);

        enum {
            // for fixed point
            kBiasBit = 8,
            kBias    = 1 << kBiasBit,

            kBias15Bit = 15,
            kBias15  = 1 << kBias15Bit,
        };

        ptrdiff_t m_SrcW;
        ptrdiff_t m_SrcH;
        ptrdiff_t m_DstW;
        ptrdiff_t m_DstH;
        ptrdiff_t m_NumCoefsX;
        ptrdiff_t m_NumCoefsY;
        ptrdiff_t m_NumTablesX;
        ptrdiff_t m_NumTablesY;
        std::vector<uint16_t> m_TablesX;    //!< Area table * m_NumTablesX
        std::vector<uint16_t> m_TablesY;    //!< Area table * m_NumTablesY
        std::vector<uint16_t> m_Work;       //!< working memory
        std::vector<uint16_t> m_Nume;
        std::vector<uint16_t> m_Deno;
    };

    template<>
    bool AreaResizerImpl_hasFeature<ArchGeneric>()
    {
        return true;
    }

    template<>
    IAreaResizerImpl * AreaResizerImpl_new<ArchGeneric>()
    {
        return new AreaResizerImpl<ArchGeneric>();
    }

    // Constructor
    void AreaResizerImpl<ArchGeneric>::init(
        size_t srcW, size_t srcH,
        size_t dstW, size_t dstH
    ) {
        m_SrcW = srcW;
        m_SrcH = srcH;
        m_DstW = dstW;
        m_DstH = dstH;

        // setup coefficients
        size_t gcdW = gcd(m_SrcW, m_DstW);
        size_t gcdH = gcd(m_SrcH, m_DstH);
        size_t rSrcW = m_SrcW / gcdW;   // reduction
        size_t rDstW = m_DstW / gcdW;
        size_t rSrcH = m_SrcH / gcdH;
        size_t rDstH = m_DstH / gcdH;
        m_NumCoefsX = calcNumCoefsForArea(rSrcW, rDstW);
        m_NumCoefsY = calcNumCoefsForArea(rSrcH, rDstH);
        m_NumTablesX = rDstW;
        m_NumTablesY = rDstH;
        m_TablesX.reserve(m_NumCoefsX * m_NumTablesX);
        m_TablesX.resize(m_NumCoefsX * m_NumTablesX);
        m_TablesY.reserve(m_NumCoefsY * m_NumTablesY);
        m_TablesY.resize(m_NumCoefsY * m_NumTablesY);

        std::vector<float> tablesX(m_NumCoefsX);
        for ( ptrdiff_t dstX = 0; dstX < m_NumTablesX; ++dstX ) {
            uint16_t * table = &m_TablesX[dstX * m_NumCoefsX];
            double sumCoefs = setAreaTable(rSrcW, rDstW, dstX, m_NumCoefsX, &tablesX[0]);
            adjustCoefs(&tablesX[0], &tablesX[m_NumCoefsX], sumCoefs, kBias15, &table[0]);
        }
        std::vector<float> tablesY(m_NumCoefsY);
        for ( ptrdiff_t dstY = 0; dstY < m_NumTablesY; ++dstY ) {
            uint16_t * table = &m_TablesY[dstY * m_NumCoefsY];
            double sumCoefs = setAreaTable(rSrcH, rDstH, dstY, m_NumCoefsY, &tablesY[0]);
            adjustCoefs(&tablesY[0], &tablesY[m_NumCoefsY], sumCoefs, kBias, &table[0]);
        }

        // allocate workspace
        m_Work.reserve(m_SrcW);
        m_Work.resize(m_SrcW);
        size_t maxW = std::max(m_SrcW, m_DstW);
        m_Nume.reserve(maxW);
        m_Nume.resize(maxW);
        m_Deno.reserve(maxW);
        m_Deno.resize(maxW);
    }

    void AreaResizerImpl<ArchGeneric>::adjustCoefs(
        float * __restrict srcBegin, float * __restrict srcEnd,
        float srcSum,
        int bias,
        uint16_t * __restrict dst)
    {
        const int k1_0 = bias;
        size_t numCoefs = srcEnd - srcBegin;
        int dstSum = 0;

        for ( size_t i = 0; i < numCoefs; ++i ) {
            dst[i] = round(srcBegin[i] * bias / srcSum);
            dstSum += dst[i];
        }
        while ( dstSum < k1_0 ) {
            size_t i = std::distance(&srcBegin[0], std::max_element(&srcBegin[0], &srcBegin[numCoefs]));
            dst[i]++;
            srcBegin[i] = 0;
            dstSum++;
        }
        while ( dstSum > k1_0 ) {
            size_t i = std::distance(&srcBegin[0], std::max_element(&srcBegin[0], &srcBegin[numCoefs]));
            dst[i]--;
            srcBegin[i] = 0;
            dstSum--;
        }
    }

    void AreaResizerImpl<ArchGeneric>::resize(
        size_t srcSt, const uint8_t * src,
        size_t dstSt, uint8_t * __restrict dst
    ) {
        uint16_t * work = &m_Work[0];

        if ( m_SrcH == m_DstH ) {
            // resize only X axis
            for ( ptrdiff_t y = 0; y < m_SrcH; ++y ) {
                for ( ptrdiff_t x = 0; x < m_SrcW; ++x ) {
                    m_Work[m_SrcW * y + x] = src[srcSt * y + x];
                }
                resizeX(work, &dst[dstSt * y]);
            }

            return;
        }

        ptrdiff_t numCoefs = m_NumCoefsY;
        const uint16_t * tablesY = &m_TablesY[0];
        ptrdiff_t tableSize = m_NumTablesY * m_NumCoefsY;
        ptrdiff_t iTable = 0;
        LinearIterator iSrcOY(m_DstH, m_SrcH);
        ptrdiff_t dstH = m_DstH;

        // main loop
        for ( ptrdiff_t dstY = 0; dstY < dstH; ++dstY ) {
            //        srcOY = floor(dstY / scale);
            ptrdiff_t srcOY = *iSrcOY++;
            //               coefs = &tablesY[dstY % m_NumTablesY * m_NumCoefsY];
            const uint16_t * coefs = &tablesY[iTable];
            iTable += numCoefs;
            if ( iTable == tableSize ) {
                iTable = 0;
            }
            resizeYmain(
                srcSt, &src[0],
                m_SrcW, work,
                srcOY,
                coefs);
            resizeX(work, &dst[dstSt * dstY]);
        }
    }

    //! resize vertical (main loop)
    //!
    //! @param srcSt  Stride in src (in byte)
    //! @param src    A row of source
    //! @param dst    A row of destination (multiplied by kBias)
    //! @param srcOY  The origin of current line
    //! @param coefs  The coefficients (multiplied by kBias)
    void AreaResizerImpl<ArchGeneric>::resizeYmain(
        ptrdiff_t srcSt, const uint8_t * src,
        ptrdiff_t dstW, uint16_t * __restrict dst,
        ptrdiff_t srcOY,
        const uint16_t * coefs)
    {
        ptrdiff_t numCoefs = m_NumCoefsY;

        std::memset(dst, 0, dstW * sizeof(*dst));

        for ( ptrdiff_t i = 0; i < numCoefs; ++i ) {
            uint16_t coef = coefs[i];
            for ( ptrdiff_t dstX = 0; dstX < dstW; ++dstX ) {
                ptrdiff_t srcY = srcOY + i;
                dst[dstX] += src[dstX + srcSt * srcY] * coef;
            }
        }
    }

    void AreaResizerImpl<ArchGeneric>::resizeX(const uint16_t * src, uint8_t * __restrict dst)
    {
        if ( m_SrcW == m_DstW ) {
            // resize only Y axis
            ptrdiff_t dstW = m_DstW;
            for ( ptrdiff_t dstX = 0; dstX < dstW; dstX++ ) {
                dst[dstX] = convertToInt(src[dstX], kBiasBit);
            }
            return;
        }

        resizeXmain(src, dst);
    }

    //! resize horizontal (main loop)
    //!
    //! @param src    A row of source (multiplied by kBias)
    //! @param dst    A row of destination
    void AreaResizerImpl<ArchGeneric>::resizeXmain(const uint16_t * src, uint8_t * __restrict dst)
    {
        ptrdiff_t numCoefs = m_NumCoefsX;
        const uint16_t * tablesX = &m_TablesX[0];
        ptrdiff_t tableSize = m_NumTablesX * m_NumCoefsX;
        ptrdiff_t iTable = 0;
        LinearIterator iSrcOX(m_DstW, m_SrcW);
        ptrdiff_t dstW = m_DstW;

        for ( ptrdiff_t dstX = 0; dstX < dstW; ++dstX ) {
            //        srcOX = floor(dstX / scale);
            ptrdiff_t srcOX = *iSrcOX++;
            //               coefs = &tablesX[dstX % m_NumTablesX * m_NumCoefsX];
            const uint16_t * coefs = &tablesX[iTable];
            int sum = 0;

            // iTable = (iTable + m_NumCoefsX) % tableSize;
            iTable += numCoefs;
            if ( iTable == tableSize ) {
                iTable = 0;
            }
            for ( ptrdiff_t i = 0; i < numCoefs; ++i ) {
                ptrdiff_t srcX = srcOX + i;
                sum += src[srcX] * coefs[i];
            }

            dst[dstX] = clamp<uint16_t>(0, 255, convertToInt(sum, kBias15Bit+kBiasBit));
        }
    }

}
<|endoftext|>


<commit_before>#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <map>
#include <vector>
#include <tr1/functional>

#include "Scheduler.hpp"
#include "DP/taskScheduling.hpp"
#include "compSet/ca_ts.hpp"
#include "nnet/nnetmultitask.hpp"
#include "ParseCommandLine.hpp"
#include "VoltageTable.hpp"

using namespace std;
using namespace std::tr1;

int hees_parse_command_line(int argc, char *argv[]);

static double randomRatio;
extern double ratio_runtime_and_deadline;

static const size_t pxaVoltageLevel = 4;
static const double pxaVoltageTable[pxaVoltageLevel] = {0.75, 1.0, 1.3, 1.6};

int main(int argc, char *argv[]) {

	hees_parse_command_line(argc, argv);
	randomRatio = ratio_runtime_and_deadline;
	cout << randomRatio << endl;
	generateSchedule();
	return 0;
}

vector<TaskVoltageTable> vec_tvt;

int generateSchedule() {

	int m_numOfVolt;
	double m_deadline;
	vector<double> m_inputDuration, m_inputEnergy;

	randomTaskSetGenerator(number_of_tasks, m_numOfVolt, m_deadline, m_inputDuration, m_inputEnergy);

	// Baseline policy
	minEnergyScheduleFixed(number_of_tasks, m_numOfVolt, m_deadline, m_inputDuration, m_inputEnergy, vec_tvt);

	// Then use dynamic programming to generate optimal schedule
	dynProg taskSet1(vec_tvt.size(), m_deadline, vec_tvt);
	taskSet1.dynamicProgrammingWithIdleTasks();
	m_deadline = taskSet1.getDeadline();
	m_deadline /= 10.0;

	return 0;
}

void randomTaskSetGenerator(int &m_numOfTask, int &m_numOfVolt, double &m_deadline, vector<double> &m_inputDuration, vector<double> &m_inputEnergy) {
	// Generate 10 tasks
	m_deadline = 0;
	m_numOfVolt = 5;

    vector<double> InDuration;
    vector<double> InEnergy;
    vector<double> InPower;
	ofstream outfile;
	// Random the seed
	srand(time(NULL));
	for (int i = 0; i < m_numOfTask; ++i) {
		// Each task is between [10 100] with a timestamp 10
		int tasklen = (10 + rand() % 200);
		// Each task power is between 0.6 ~ 2.0
		double taskpower = min_task_power + (rand() % 100) * (max_task_power - min_task_power) / 100.0;
		double taskEnergy = tasklen * taskpower;
		InDuration.push_back(tasklen);
		InEnergy.push_back(taskEnergy);
		InPower.push_back(taskpower);

		m_deadline += tasklen;

		vec_tvt.push_back(TaskVoltageTable(*cpu_voltage_table_ptr, taskpower, tasklen));

	}
	outfile.open("TasksOrigNoSorting.txt");
	if (!outfile) {
		cerr << "Can not open TasksOrigNoSorting.txt for write!" << endl;
	}
	for (size_t i = 0; i < InEnergy.size(); ++i) {
		outfile << InDuration[i] << " "
		<< InPower[i] << " "
		<< InEnergy[i] << endl;
	}
	outfile.close();

	// highPowerLongTask(InDuration, InEnergy, InPower);
	outfile.open("TasksOrig.txt");
	if (!outfile) {
		cerr << "Can not open TasksOrig.txt for write!" << endl;
	}
	for (size_t i = 0; i < InEnergy.size(); ++i) {
		outfile << InDuration[i] << " "
		<< InPower[i] << " "
		<< InEnergy[i] << endl;
	}
	outfile.close();

	m_deadline /= randomRatio;
	m_inputDuration = InDuration;
	m_inputEnergy = InEnergy;

	return;
}

void dummyTaskSetGenerator(int &m_numOfTask, int &m_numOfVolt, double &m_deadline, vector<double> &m_inputDuration, vector<double> &m_inputEnergy) {

    m_deadline = 25;
    m_numOfTask = 3;
	m_numOfVolt = 5;

    vector<double>InDuration;
    InDuration.push_back(6.0);
    InDuration.push_back(7.0);
    InDuration.push_back(8.0);

	m_inputDuration = InDuration;

    vector<double>InEnergy;
    InEnergy.push_back(6.0);
    InEnergy.push_back(7.0);
    InEnergy.push_back(8.0);

	m_inputEnergy = InEnergy;

	return;
}

void highPowerLongTask(vector<double> &m_taskDuration, vector<double> &m_taskEnergy, vector<double> &m_taskPower) {
	vector<double> taskDuration(m_taskDuration);
	vector<double> taskPower(m_taskPower);
	map<double, double> taskMap;

	// Sort the task len and power vector in descending order
	sort(taskDuration.begin(), taskDuration.end(), greater<double>());
	sort(taskPower.begin(), taskPower.end(), greater<double>());

	for (size_t i = 0; i < taskDuration.size(); ++i) {
		taskMap[taskDuration[i]] = taskPower[i];
	}

	for (size_t i = 0; i < taskDuration.size(); ++i) {
		m_taskEnergy[i] = taskMap[m_taskDuration[i]] * m_taskDuration[i];
		m_taskPower[i] = taskMap[m_taskDuration[i]];
	}

	return;
}
<commit_msg>In Scheduler.cpp, use the deadline by the base line policy<commit_after>#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <map>
#include <vector>
#include <tr1/functional>

#include "Scheduler.hpp"
#include "DP/taskScheduling.hpp"
#include "compSet/ca_ts.hpp"
#include "nnet/nnetmultitask.hpp"
#include "ParseCommandLine.hpp"
#include "VoltageTable.hpp"

using namespace std;
using namespace std::tr1;

int hees_parse_command_line(int argc, char *argv[]);

static double randomRatio;
extern double ratio_runtime_and_deadline;

static const size_t pxaVoltageLevel = 4;
static const double pxaVoltageTable[pxaVoltageLevel] = {0.75, 1.0, 1.3, 1.6};

int main(int argc, char *argv[]) {

	hees_parse_command_line(argc, argv);
	randomRatio = ratio_runtime_and_deadline;
	cout << randomRatio << endl;
	generateSchedule();
	return 0;
}

vector<TaskVoltageTable> vec_tvt;

int generateSchedule() {

	int m_numOfVolt;
	double m_deadline;
	vector<double> m_inputDuration, m_inputEnergy;

	randomTaskSetGenerator(number_of_tasks, m_numOfVolt, m_deadline, m_inputDuration, m_inputEnergy);

	// Baseline policy
	int intDeadline = minEnergyScheduleFixed(number_of_tasks, m_numOfVolt, m_deadline, m_inputDuration, m_inputEnergy, vec_tvt);

	// Then use dynamic programming to generate optimal schedule
	dynProg taskSet1(vec_tvt.size(), intDeadline, vec_tvt);
	taskSet1.dynamicProgrammingWithIdleTasks();
	m_deadline = taskSet1.getDeadline();
	m_deadline /= 10.0;

	return 0;
}

void randomTaskSetGenerator(int &m_numOfTask, int &m_numOfVolt, double &m_deadline, vector<double> &m_inputDuration, vector<double> &m_inputEnergy) {
	// Generate 10 tasks
	m_deadline = 0;
	m_numOfVolt = 5;

    vector<double> InDuration;
    vector<double> InEnergy;
    vector<double> InPower;
	ofstream outfile;
	// Random the seed
	srand(time(NULL));
	for (int i = 0; i < m_numOfTask; ++i) {
		// Each task is between [10 100] with a timestamp 10
		int tasklen = (10 + rand() % 200);
		// Each task power is between 0.6 ~ 2.0
		double taskpower = min_task_power + (rand() % 100) * (max_task_power - min_task_power) / 100.0;
		double taskEnergy = tasklen * taskpower;
		InDuration.push_back(tasklen);
		InEnergy.push_back(taskEnergy);
		InPower.push_back(taskpower);

		m_deadline += tasklen;

		vec_tvt.push_back(TaskVoltageTable(*cpu_voltage_table_ptr, taskpower, tasklen));

	}
	outfile.open("TasksOrigNoSorting.txt");
	if (!outfile) {
		cerr << "Can not open TasksOrigNoSorting.txt for write!" << endl;
	}
	for (size_t i = 0; i < InEnergy.size(); ++i) {
		outfile << InDuration[i] << " "
		<< InPower[i] << " "
		<< InEnergy[i] << endl;
	}
	outfile.close();

	// highPowerLongTask(InDuration, InEnergy, InPower);
	outfile.open("TasksOrig.txt");
	if (!outfile) {
		cerr << "Can not open TasksOrig.txt for write!" << endl;
	}
	for (size_t i = 0; i < InEnergy.size(); ++i) {
		outfile << InDuration[i] << " "
		<< InPower[i] << " "
		<< InEnergy[i] << endl;
	}
	outfile.close();

	m_deadline /= randomRatio;
	m_inputDuration = InDuration;
	m_inputEnergy = InEnergy;

	return;
}

void dummyTaskSetGenerator(int &m_numOfTask, int &m_numOfVolt, double &m_deadline, vector<double> &m_inputDuration, vector<double> &m_inputEnergy) {

    m_deadline = 25;
    m_numOfTask = 3;
	m_numOfVolt = 5;

    vector<double>InDuration;
    InDuration.push_back(6.0);
    InDuration.push_back(7.0);
    InDuration.push_back(8.0);

	m_inputDuration = InDuration;

    vector<double>InEnergy;
    InEnergy.push_back(6.0);
    InEnergy.push_back(7.0);
    InEnergy.push_back(8.0);

	m_inputEnergy = InEnergy;

	return;
}

void highPowerLongTask(vector<double> &m_taskDuration, vector<double> &m_taskEnergy, vector<double> &m_taskPower) {
	vector<double> taskDuration(m_taskDuration);
	vector<double> taskPower(m_taskPower);
	map<double, double> taskMap;

	// Sort the task len and power vector in descending order
	sort(taskDuration.begin(), taskDuration.end(), greater<double>());
	sort(taskPower.begin(), taskPower.end(), greater<double>());

	for (size_t i = 0; i < taskDuration.size(); ++i) {
		taskMap[taskDuration[i]] = taskPower[i];
	}

	for (size_t i = 0; i < taskDuration.size(); ++i) {
		m_taskEnergy[i] = taskMap[m_taskDuration[i]] * m_taskDuration[i];
		m_taskPower[i] = taskMap[m_taskDuration[i]];
	}

	return;
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2014, Scott Zuyderduyn
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/

//----------------------------------------------------------------------------
// matrix.hpp
// An STL-like structure that resides in video memory.
//
// Author: Scott D. Zuyderduyn, Ph.D. (scott.zuyderduyn@utoronto.ca)
//----------------------------------------------------------------------------

#pragma once
#ifndef ECUDA_MATRIX_HPP
#define ECUDA_MATRIX_HPP

#include <cstddef>
#include <vector>
#include <estd/matrix.hpp>
#include "global.hpp"
#include "containers.hpp"
#include "memory.hpp"

namespace ecuda {

///
/// A video memory-bound matrix structure.
///
template<typename T>
class matrix {

public:
	typedef T value_type; //!< cell data type
	typedef std::size_t size_type; //!< index data type
	typedef std::ptrdiff_t difference_type; //!<
	typedef value_type& reference; //!< cell reference type
	typedef const value_type& const_reference; //!< cell const reference type
	typedef value_type* pointer; //!< cell pointer type
	typedef const value_type* const_pointer; //!< cell const pointer type

	typedef ecuda::OffsettingContainer< matrix<T> > row_type; //!< matrix row container type
	typedef ecuda::OffsettingContainer< matrix<T> > column_type; //!< matrix column container type
	typedef const ecuda::OffsettingContainer< const matrix<T>, size_type, const_pointer > const_row_type; //!< matrix const row container type
	typedef const ecuda::OffsettingContainer< const matrix<T>, size_type, const_pointer > const_column_type; //!< matrix const column container type

private:
	// REMEMBER: numberRows, numberColumns, and pitch altered on device memory won't be
	//           reflected on the host object. Don't allow the device to perform any operations that
	//           change their value.
	size_type numberRows; //!< number of matrix rows
	size_type numberColumns; //!< number of matrix columns
	size_type pitch; //!< the padded width of the 2D memory allocation in bytes
	device_ptr<T> deviceMemory; //!< smart pointer to video card memory

public:
	HOST matrix( const size_type numberRows=0, const size_type numberColumns=0, const_reference value = T() );
	HOST DEVICE matrix( const matrix<T>& src );
	template<typename U,typename V>
	HOST matrix( const estd::matrix<T,U,V>& src );
	HOST DEVICE virtual ~matrix() {}

	DEVICE inline reference at( size_type rowIndex, size_type columnIndex ) { return *(deviceMemory.get()+(rowIndex*pitch/sizeof(T)+columnIndex)); }
	DEVICE inline reference at( size_type index ) { return at( index/(pitch/sizeof(T)), index % (pitch/sizeof(T)) ); }

	DEVICE inline const_reference at( size_type rowIndex, size_type columnIndex ) const { return *(deviceMemory.get()+(rowIndex*pitch/sizeof(T)+columnIndex)); }
	DEVICE inline const_reference at( size_type index ) const { return at( index/(pitch/sizeof(T)), index % (pitch/sizeof(T)) ); }

	HOST DEVICE inline size_type size() const { return numberRows*numberColumns; }
	HOST DEVICE inline size_type row_size() const { return numberRows; }
	HOST DEVICE inline size_type column_size() const { return numberColumns; }
	HOST DEVICE inline size_type get_pitch() const { return pitch; }
	HOST DEVICE inline T* data() { return deviceMemory.get(); }
	HOST DEVICE inline const T* data() const { return deviceMemory.get(); }

	HOST DEVICE inline row_type get_row( const size_type rowIndex ) { return row_type( *this, column_size(), rowIndex*pitch/sizeof(T) ); }
	HOST DEVICE inline column_type get_column( const size_type columnIndex ) { return column_type( *this, row_size(), columnIndex, pitch/sizeof(T) ); }
	HOST DEVICE inline const_row_type get_row( const size_type rowIndex ) const { return const_row_type( *this, column_size(), rowIndex*pitch/sizeof(T) ); }
	HOST DEVICE inline const_column_type get_column( const size_type columnIndex ) const { return const_column_type( *this, row_size(), columnIndex, pitch/sizeof(T) ); }

	HOST DEVICE inline row_type operator[]( const size_type rowIndex ) { return get_row(rowIndex); }
	HOST DEVICE inline const_row_type operator[]( const size_type rowIndex ) const { return get_row(rowIndex); }

	// critical function used to bridge host->device code
	HOST DEVICE matrix<T>& operator=( const matrix<T>& other ) {
		numberRows = other.numberRows;
		numberColumns = other.numberColumns;
		pitch = other.pitch;
		deviceMemory = other.deviceMemory;
		return *this;
	}

	template<typename U,typename V>
	HOST matrix<T>& operator>>( estd::matrix<T,U,V>& dest ) {
		dest.resize( static_cast<U>(numberRows), static_cast<V>(numberColumns) );
		CUDA_CALL( cudaMemcpy2D( dest.data(), numberColumns*sizeof(T), deviceMemory.get(), pitch, numberColumns*sizeof(T), numberRows, cudaMemcpyDeviceToHost ) );
		return *this;
	}

	template<typename Alloc>
	HOST matrix<T>& operator>>( std::vector<T,Alloc>& other ) {
		other.resize( size() );
		CUDA_CALL( cudaMemcpy2D( &other[0], numberColumns*sizeof(T), deviceMemory.get(), pitch, numberColumns*sizeof(T), numberRows, cudaMemcpyDeviceToHost ) );
		return *this;
	}

	HOST void resize( const size_type numberRows, const size_type numberColumns ) {
		if( row_size() == numberRows and column_size() == numberColumns ) return; // no resize needed
		// allocate memory
		this->numberRows = numberRows;
		this->numberColumns = numberColumns;
		deviceMemory = device_ptr<T>();
		CUDA_CALL( cudaMallocPitch( deviceMemory.alloc_ptr(), &pitch, numberColumns*sizeof(T), numberRows ) );
	}

	template<typename U,typename V>
	HOST matrix<T>& operator<<( const estd::matrix<T,U,V>& src ) {
		resize( src.row_size(), src.column_size() );
		CUDA_CALL( cudaMemcpy2D( deviceMemory.get(), pitch, src.data(), numberColumns*sizeof(T), numberColumns*sizeof(T), numberRows, cudaMemcpyHostToDevice ) );
		return *this;
	}

	template<typename Alloc>
	HOST matrix<T>& operator<<( std::vector<T,Alloc>& other ) {
		CUDA_CALL( cudaMemcpy2D( data(), pitch, &other[0], numberColumns*sizeof(T), numberColumns*sizeof(T), numberRows, cudaMemcpyHostToDevice ) );
		return *this;
	}

};

template<typename T>
HOST matrix<T>::matrix( const size_type numberRows, const size_type numberColumns, const_reference value ) : numberRows(numberRows), numberColumns(numberColumns), pitch(0) {
	if( numberRows and numberColumns ) {
		CUDA_CALL( cudaMallocPitch( deviceMemory.alloc_ptr(), &pitch, numberColumns*sizeof(T), numberRows ) );
		// cudaMemset2D method not general since sizeof(T) > int
		//CUDA_CALL( cudaMemset2D( deviceMemory.get(), pitch, static_cast<int>(value), numberColumns*sizeof(T), numberRows ) );
		std::vector<T> v( numberRows*numberColumns, value );
		CUDA_CALL( cudaMemcpy2D( deviceMemory.get(), pitch, &v[0], numberColumns*sizeof(T), numberColumns*sizeof(T), numberRows, cudaMemcpyHostToDevice ) );
	}
}

template<typename T>
HOST DEVICE matrix<T>::matrix( const matrix<T>& src ) : numberRows(src.numberRows), numberColumns(src.numberColumns), pitch(src.pitch), deviceMemory(src.deviceMemory) {}

template<typename T>
template<typename U,typename V>
HOST matrix<T>::matrix( const estd::matrix<T,U,V>& src ) : numberRows(static_cast<size_type>(src.row_size())), numberColumns(static_cast<size_type>(src.column_size())), pitch(0) {
	if( numberRows and numberColumns ) {
		CUDA_CALL( cudaMallocPitch( deviceMemory.alloc_ptr(), &pitch, numberColumns*sizeof(T), numberRows ) );
		CUDA_CALL( cudaMemcpy2D( deviceMemory.get(), pitch, src.data(), numberColumns*sizeof(T), numberColumns*sizeof(T), numberRows, cudaMemcpyHostToDevice ) );
	}
}

} // namespace ecuda

#endif
<commit_msg>added assign() function to matrix - TODO implement similar methods to other containers<commit_after>/*
Copyright (c) 2014, Scott Zuyderduyn
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/

//----------------------------------------------------------------------------
// matrix.hpp
// An STL-like structure that resides in video memory.
//
// Author: Scott D. Zuyderduyn, Ph.D. (scott.zuyderduyn@utoronto.ca)
//----------------------------------------------------------------------------

#pragma once
#ifndef ECUDA_MATRIX_HPP
#define ECUDA_MATRIX_HPP

#include <cstddef>
#include <vector>
#include <estd/matrix.hpp>
#include "global.hpp"
#include "containers.hpp"
#include "memory.hpp"

namespace ecuda {

///
/// A video memory-bound matrix structure.
///
template<typename T>
class matrix {

public:
	typedef T value_type; //!< cell data type
	typedef std::size_t size_type; //!< index data type
	typedef std::ptrdiff_t difference_type; //!<
	typedef value_type& reference; //!< cell reference type
	typedef const value_type& const_reference; //!< cell const reference type
	typedef value_type* pointer; //!< cell pointer type
	typedef const value_type* const_pointer; //!< cell const pointer type

	typedef ecuda::OffsettingContainer< matrix<T> > row_type; //!< matrix row container type
	typedef ecuda::OffsettingContainer< matrix<T> > column_type; //!< matrix column container type
	typedef const ecuda::OffsettingContainer< const matrix<T>, size_type, const_pointer > const_row_type; //!< matrix const row container type
	typedef const ecuda::OffsettingContainer< const matrix<T>, size_type, const_pointer > const_column_type; //!< matrix const column container type

private:
	// REMEMBER: numberRows, numberColumns, and pitch altered on device memory won't be
	//           reflected on the host object. Don't allow the device to perform any operations that
	//           change their value.
	size_type numberRows; //!< number of matrix rows
	size_type numberColumns; //!< number of matrix columns
	size_type pitch; //!< the padded width of the 2D memory allocation in bytes
	device_ptr<T> deviceMemory; //!< smart pointer to video card memory

public:
	HOST matrix( const size_type numberRows=0, const size_type numberColumns=0, const_reference value = T() );
	HOST DEVICE matrix( const matrix<T>& src );
	template<typename U,typename V>
	HOST matrix( const estd::matrix<T,U,V>& src );
	HOST DEVICE virtual ~matrix() {}

	template<class RandomAccessIterator>
	HOST assign( RandomAccessIterator begin, RandomAccessIterator end );

	DEVICE inline reference at( size_type rowIndex, size_type columnIndex ) { return *(deviceMemory.get()+(rowIndex*pitch/sizeof(T)+columnIndex)); }
	DEVICE inline reference at( size_type index ) { return at( index/(pitch/sizeof(T)), index % (pitch/sizeof(T)) ); }

	DEVICE inline const_reference at( size_type rowIndex, size_type columnIndex ) const { return *(deviceMemory.get()+(rowIndex*pitch/sizeof(T)+columnIndex)); }
	DEVICE inline const_reference at( size_type index ) const { return at( index/(pitch/sizeof(T)), index % (pitch/sizeof(T)) ); }

	HOST DEVICE inline size_type size() const { return numberRows*numberColumns; }
	HOST DEVICE inline size_type row_size() const { return numberRows; }
	HOST DEVICE inline size_type column_size() const { return numberColumns; }
	HOST DEVICE inline size_type get_pitch() const { return pitch; }
	HOST DEVICE inline T* data() { return deviceMemory.get(); }
	HOST DEVICE inline const T* data() const { return deviceMemory.get(); }

	HOST DEVICE inline row_type get_row( const size_type rowIndex ) { return row_type( *this, column_size(), rowIndex*pitch/sizeof(T) ); }
	HOST DEVICE inline column_type get_column( const size_type columnIndex ) { return column_type( *this, row_size(), columnIndex, pitch/sizeof(T) ); }
	HOST DEVICE inline const_row_type get_row( const size_type rowIndex ) const { return const_row_type( *this, column_size(), rowIndex*pitch/sizeof(T) ); }
	HOST DEVICE inline const_column_type get_column( const size_type columnIndex ) const { return const_column_type( *this, row_size(), columnIndex, pitch/sizeof(T) ); }

	HOST DEVICE inline row_type operator[]( const size_type rowIndex ) { return get_row(rowIndex); }
	HOST DEVICE inline const_row_type operator[]( const size_type rowIndex ) const { return get_row(rowIndex); }

	// critical function used to bridge host->device code
	HOST DEVICE matrix<T>& operator=( const matrix<T>& other ) {
		numberRows = other.numberRows;
		numberColumns = other.numberColumns;
		pitch = other.pitch;
		deviceMemory = other.deviceMemory;
		return *this;
	}

	template<typename U,typename V>
	HOST matrix<T>& operator>>( estd::matrix<T,U,V>& dest ) {
		dest.resize( static_cast<U>(numberRows), static_cast<V>(numberColumns) );
		CUDA_CALL( cudaMemcpy2D( dest.data(), numberColumns*sizeof(T), deviceMemory.get(), pitch, numberColumns*sizeof(T), numberRows, cudaMemcpyDeviceToHost ) );
		return *this;
	}

	template<typename Alloc>
	HOST matrix<T>& operator>>( std::vector<T,Alloc>& other ) {
		other.resize( size() );
		CUDA_CALL( cudaMemcpy2D( &other[0], numberColumns*sizeof(T), deviceMemory.get(), pitch, numberColumns*sizeof(T), numberRows, cudaMemcpyDeviceToHost ) );
		return *this;
	}

	HOST void resize( const size_type numberRows, const size_type numberColumns ) {
		if( row_size() == numberRows and column_size() == numberColumns ) return; // no resize needed
		// allocate memory
		this->numberRows = numberRows;
		this->numberColumns = numberColumns;
		deviceMemory = device_ptr<T>();
		CUDA_CALL( cudaMallocPitch( deviceMemory.alloc_ptr(), &pitch, numberColumns*sizeof(T), numberRows ) );
	}

	template<typename U,typename V>
	HOST matrix<T>& operator<<( const estd::matrix<T,U,V>& src ) {
		resize( src.row_size(), src.column_size() );
		CUDA_CALL( cudaMemcpy2D( deviceMemory.get(), pitch, src.data(), numberColumns*sizeof(T), numberColumns*sizeof(T), numberRows, cudaMemcpyHostToDevice ) );
		return *this;
	}

	template<typename Alloc>
	HOST matrix<T>& operator<<( std::vector<T,Alloc>& other ) {
		CUDA_CALL( cudaMemcpy2D( data(), pitch, &other[0], numberColumns*sizeof(T), numberColumns*sizeof(T), numberRows, cudaMemcpyHostToDevice ) );
		return *this;
	}

};

template<typename T>
HOST matrix<T>::matrix( const size_type numberRows, const size_type numberColumns, const_reference value ) : numberRows(numberRows), numberColumns(numberColumns), pitch(0) {
	if( numberRows and numberColumns ) {
		CUDA_CALL( cudaMallocPitch( deviceMemory.alloc_ptr(), &pitch, numberColumns*sizeof(T), numberRows ) );
		// cudaMemset2D method not general since sizeof(T) > int
		//CUDA_CALL( cudaMemset2D( deviceMemory.get(), pitch, static_cast<int>(value), numberColumns*sizeof(T), numberRows ) );
		std::vector<T> v( numberRows*numberColumns, value );
		CUDA_CALL( cudaMemcpy2D( deviceMemory.get(), pitch, &v[0], numberColumns*sizeof(T), numberColumns*sizeof(T), numberRows, cudaMemcpyHostToDevice ) );
	}
}

template<typename T>
HOST DEVICE matrix<T>::matrix( const matrix<T>& src ) : numberRows(src.numberRows), numberColumns(src.numberColumns), pitch(src.pitch), deviceMemory(src.deviceMemory) {}

template<typename T>
template<typename U,typename V>
HOST matrix<T>::matrix( const estd::matrix<T,U,V>& src ) : numberRows(static_cast<size_type>(src.row_size())), numberColumns(static_cast<size_type>(src.column_size())), pitch(0) {
	if( numberRows and numberColumns ) {
		CUDA_CALL( cudaMallocPitch( deviceMemory.alloc_ptr(), &pitch, numberColumns*sizeof(T), numberRows ) );
		CUDA_CALL( cudaMemcpy2D( deviceMemory.get(), pitch, src.data(), numberColumns*sizeof(T), numberColumns*sizeof(T), numberRows, cudaMemcpyHostToDevice ) );
	}
}

template<typename T>
template<class RandomAccessIterator>
HOST matrix<T>::assign( RandomAccessIterator begin, RandomAccessIterator end ) {
	std::size_t n = end-begin;
	if( n > size() ) n = size();
	RandomAccessIterator current = begin;
	for( std::size_t i = 0; i < n; i += row_size(), begin += row_size() ) {
		std::size_t len = row_size();
		if( i+len > size() ) len = size()-i;
		std::vector<T> row( current, current+len );
		CUDA_CALL( cudaMemcpy( deviceMemory.get()+(i*pitch/sizeof(T)), &row[0], len*sizeof(T), cudaMemcpyHostToDevice ) );
	}
} // namespace ecuda

#endif
<|endoftext|>