<commit_before>#include <string>
#include <iostream>

#include "../../inmost.h"
using namespace INMOST;

#if defined(USE_MPI)
#define BARRIER MPI_Barrier(MPI_COMM_WORLD);
#else
#define BARRIER
#endif

int main(int argc, char ** argv)
{
	int rank,procs;
	if( argc < 3 )
	{
		std::cout << "Usage: " << argv[0] << " method_number<0:INNER_ILU2,1:INNER_MLILUC,2:ANI,3:PETSc,4:Trilinos_Aztec,5:Trilinos_Belos,6:Trilinos_Ifpack,7:Trilinos_ML> matrix.mtx [right_hand_side.rhs] [solver_options.txt]" << std::endl;
		return -1;
	}
	Solver::Type type;
	switch(atoi(argv[1]))
	{
		case 0: type = Solver::INNER_ILU2; break;
		case 1: type = Solver::INNER_MLILUC; break;
		case 2: type = Solver::PETSc; break;
		case 3: type = Solver::Trilinos_Aztec; break;
		case 4: type = Solver::Trilinos_Belos; break;
		case 5: type = Solver::Trilinos_Ifpack; break;
		case 6: type = Solver::Trilinos_ML; break;
    case 7: type = Solver::ANI; break;
	}
	Solver::Initialize(&argc,&argv,argc > 4 ? argv[4] : NULL); // Initialize the linear solver in accordance with args
	{
#if defined(USE_MPI)
		MPI_Comm_rank(MPI_COMM_WORLD,&rank);  // Get the rank of the current process
		MPI_Comm_size(MPI_COMM_WORLD,&procs); // Get the total number of processors used
#else
		rank = 0;
		procs = 1;
#endif
		//std::cout << rank << "/" << procs << " " << argv[0] << std::endl;
		Solver::Matrix mat("A"); // Declare the matrix of the linear system to be solved
		Solver::Vector b("rhs"); // Declare the right-hand side vector
		Solver::Vector x("sol"); // Declare the solution vector
		//std::cout << rank << " load matrix from " << std::string(argv[2]) << " ..." << std::endl;
		double t = Timer(), tt = Timer();
		mat.Load(std::string(argv[2])); //if interval parameters not set, matrix will be divided automatically
		BARRIER
		if( !rank ) std::cout << "load matrix: " << Timer() - t << std::endl;
		//mat.Save("test.mtx");
		t = Timer();
		if( argc > 3 )
		{
			//std::cout << rank << " load vector from " << std::string(argv[3]) << std::endl;
			b.Load(std::string(argv[3])); // Load RHS vector
		}
		else // Set local RHS to 1 if it was not specified
		{
			INMOST_DATA_ENUM_TYPE mbeg,mend,k;
			mat.GetInterval(mbeg,mend);
			b.SetInterval(mbeg,mend);
			for( k = mbeg; k < mend; ++k ) b[k] = 1.0;
		}
		BARRIER
		if( !rank ) std::cout << "load vector: " << Timer() - t << std::endl;
		bool success = false;
		int iters;
		double resid, realresid = 0;
		std::string reason;
		{
			Solver s(type); // Declare the linear solver by specified type

			s.SetParameterEnum("gmres_substeps",3);

			s.SetParameterEnum("reorder_nonzeros",0);
			s.SetParameterEnum("rescale_iterations",8);
			s.SetParameterEnum("adapt_ddpq_tolerance",0);

			s.SetParameterReal("drop_tolerance",0.001);
			s.SetParameterReal("reuse_tolerance",0.00001);
			s.SetParameterReal("ddpq_tolerance",0.7);

			t = Timer();
			s.SetMatrix(mat); // Compute the preconditioner for the original matrix
			BARRIER
			if( !rank ) std::cout << "preconditioner: " << Timer() - t << std::endl;
			t = Timer();
			success = s.Solve(b,x); // Solve the linear system with the previously computted preconditioner
			BARRIER
			if( !rank ) std::cout << "solver: " << Timer() - t << std::endl;
			iters = s.Iterations(); // Get the number of iterations performed
			resid = s.Residual();   // Get the final residual achieved
			reason = s.GetReason();
			//x.Save("output.rhs");
		}
		tt = Timer() - tt;

		{ // Compute the true residual
			double aresid = 0, bresid = 0;
			Solver::Vector test;
			t = Timer();
			Solver::OrderInfo info;
			info.PrepareMatrix(mat,0);
			info.PrepareVector(x);
			info.Update(x);

			mat.MatVec(1.0,x,0.0,test); // Multiply the original matrix by a vector

			{
				INMOST_DATA_ENUM_TYPE mbeg,mend,k;
				info.GetLocalRegion(info.GetRank(),mbeg,mend);
				for( k = mbeg; k < mend; ++k )
				{
					aresid += (test[k]-b[k])*(test[k]-b[k]);
					bresid += b[k]*b[k];
				}
			}
			double temp[2] = {aresid,bresid}, recv[2] = {aresid,bresid};
#if defined(USE_MPI)
			MPI_Reduce(temp,recv,2,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
			if( info.GetRank() == 0 ) std::cout << "||Ax-b|| " << sqrt(recv[0]) << " ||b|| " << sqrt(recv[1]) << " ||Ax-b||/||b|| " << sqrt(recv[0]/recv[1]) << std::endl;
#endif
			realresid = sqrt(recv[0]/recv[1]);
			//realresid = sqrt(realresid);

			info.RestoreVector(x);
			if( !rank ) std::cout << "norms: " << Timer() - t << std::endl;
		}

		{
			if( rank == 0 )
			{
				std::cout << procs << " processors";
				if( success )
				{
					std::cout << " solved in " << tt << " secs";
					std::cout << " with " << iters << " iterations to " << resid << " norm";
				}
				else std::cout << " failed to solve";
				std::cout  << " matrix \"" << argv[2] << "\"";
				if( argc > 3 ) std::cout  << " vector \"" << argv[3] << "\"";
				std::cout << " true residual ||Ax-b||/||b|| " << realresid;
				std::cout << std::endl;
				std::cout << "reason: " << reason << std::endl;
			}
		}
	}

	Solver::Finalize(); // Finalize solver and close MPI activity
	return 0;
}

<commit_msg>Fixed MatSolve example help<commit_after>#include <string>
#include <iostream>

#include "../../inmost.h"
using namespace INMOST;

#if defined(USE_MPI)
#define BARRIER MPI_Barrier(MPI_COMM_WORLD);
#else
#define BARRIER
#endif

int main(int argc, char ** argv)
{
	int rank,procs;
	if( argc < 3 )
	{
		std::cout << "Usage: " << argv[0] << " method_number<0:INNER_ILU2,1:INNER_MLILUC,2:PETSc,3:Trilinos_Aztec,4:Trilinos_Belos,5:Trilinos_Ifpack,6:Trilinos_ML,7:ANI> matrix.mtx [right_hand_side.rhs] [solver_options.txt]" << std::endl;
		return -1;
	}
	Solver::Type type;
	switch(atoi(argv[1]))
	{
		case 0: type = Solver::INNER_ILU2; break;
		case 1: type = Solver::INNER_MLILUC; break;
		case 2: type = Solver::PETSc; break;
		case 3: type = Solver::Trilinos_Aztec; break;
		case 4: type = Solver::Trilinos_Belos; break;
		case 5: type = Solver::Trilinos_Ifpack; break;
		case 6: type = Solver::Trilinos_ML; break;
    case 7: type = Solver::ANI; break;
	}
	Solver::Initialize(&argc,&argv,argc > 4 ? argv[4] : NULL); // Initialize the linear solver in accordance with args
	{
#if defined(USE_MPI)
		MPI_Comm_rank(MPI_COMM_WORLD,&rank);  // Get the rank of the current process
		MPI_Comm_size(MPI_COMM_WORLD,&procs); // Get the total number of processors used
#else
		rank = 0;
		procs = 1;
#endif
		//std::cout << rank << "/" << procs << " " << argv[0] << std::endl;
		Solver::Matrix mat("A"); // Declare the matrix of the linear system to be solved
		Solver::Vector b("rhs"); // Declare the right-hand side vector
		Solver::Vector x("sol"); // Declare the solution vector
		//std::cout << rank << " load matrix from " << std::string(argv[2]) << " ..." << std::endl;
		double t = Timer(), tt = Timer();
		mat.Load(std::string(argv[2])); //if interval parameters not set, matrix will be divided automatically
		BARRIER
		if( !rank ) std::cout << "load matrix: " << Timer() - t << std::endl;
		//mat.Save("test.mtx");
		t = Timer();
		if( argc > 3 )
		{
			//std::cout << rank << " load vector from " << std::string(argv[3]) << std::endl;
			b.Load(std::string(argv[3])); // Load RHS vector
		}
		else // Set local RHS to 1 if it was not specified
		{
			INMOST_DATA_ENUM_TYPE mbeg,mend,k;
			mat.GetInterval(mbeg,mend);
			b.SetInterval(mbeg,mend);
			for( k = mbeg; k < mend; ++k ) b[k] = 1.0;
		}
		BARRIER
		if( !rank ) std::cout << "load vector: " << Timer() - t << std::endl;
		bool success = false;
		int iters;
		double resid, realresid = 0;
		std::string reason;
		{
			Solver s(type); // Declare the linear solver by specified type

			s.SetParameterEnum("gmres_substeps",3);

			s.SetParameterEnum("reorder_nonzeros",0);
			s.SetParameterEnum("rescale_iterations",8);
			s.SetParameterEnum("adapt_ddpq_tolerance",0);

			s.SetParameterReal("drop_tolerance",0.001);
			s.SetParameterReal("reuse_tolerance",0.00001);
			s.SetParameterReal("ddpq_tolerance",0.7);

			t = Timer();
			s.SetMatrix(mat); // Compute the preconditioner for the original matrix
			BARRIER
			if( !rank ) std::cout << "preconditioner: " << Timer() - t << std::endl;
			t = Timer();
			success = s.Solve(b,x); // Solve the linear system with the previously computted preconditioner
			BARRIER
			if( !rank ) std::cout << "solver: " << Timer() - t << std::endl;
			iters = s.Iterations(); // Get the number of iterations performed
			resid = s.Residual();   // Get the final residual achieved
			reason = s.GetReason();
			//x.Save("output.rhs");
		}
		tt = Timer() - tt;

		{ // Compute the true residual
			double aresid = 0, bresid = 0;
			Solver::Vector test;
			t = Timer();
			Solver::OrderInfo info;
			info.PrepareMatrix(mat,0);
			info.PrepareVector(x);
			info.Update(x);

			mat.MatVec(1.0,x,0.0,test); // Multiply the original matrix by a vector

			{
				INMOST_DATA_ENUM_TYPE mbeg,mend,k;
				info.GetLocalRegion(info.GetRank(),mbeg,mend);
				for( k = mbeg; k < mend; ++k )
				{
					aresid += (test[k]-b[k])*(test[k]-b[k]);
					bresid += b[k]*b[k];
				}
			}
			double temp[2] = {aresid,bresid}, recv[2] = {aresid,bresid};
#if defined(USE_MPI)
			MPI_Reduce(temp,recv,2,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
			if( info.GetRank() == 0 ) std::cout << "||Ax-b|| " << sqrt(recv[0]) << " ||b|| " << sqrt(recv[1]) << " ||Ax-b||/||b|| " << sqrt(recv[0]/recv[1]) << std::endl;
#endif
			realresid = sqrt(recv[0]/recv[1]);
			//realresid = sqrt(realresid);

			info.RestoreVector(x);
			if( !rank ) std::cout << "norms: " << Timer() - t << std::endl;
		}

		{
			if( rank == 0 )
			{
				std::cout << procs << " processors";
				if( success )
				{
					std::cout << " solved in " << tt << " secs";
					std::cout << " with " << iters << " iterations to " << resid << " norm";
				}
				else std::cout << " failed to solve";
				std::cout  << " matrix \"" << argv[2] << "\"";
				if( argc > 3 ) std::cout  << " vector \"" << argv[3] << "\"";
				std::cout << " true residual ||Ax-b||/||b|| " << realresid;
				std::cout << std::endl;
				std::cout << "reason: " << reason << std::endl;
			}
		}
	}

	Solver::Finalize(); // Finalize solver and close MPI activity
	return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: thread.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: jl $ $Date: 2001-03-20 15:30:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CPPU_THREADPOOL_THREAD_HXX
#define _CPPU_THREADPOOL_THREAD_HXX

#include <list>

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#include <osl/thread.h>

#include "jobqueue.hxx"

namespace cppu_threadpool {

    class JobQueue;

    //-----------------------------------------
    // private thread class for the threadpool
    // independent from vos
    //-----------------------------------------
    class ORequestThread
    {
    public:
        ORequestThread( JobQueue * ,
                        const ::rtl::ByteSequence &aThreadId,
                        sal_Bool bAsynchron );
        ~ORequestThread();

        void setTask( JobQueue * , const ::rtl::ByteSequence & aThreadId , sal_Bool bAsynchron );

        sal_Bool create();
        void join();
        void onTerminated();
        void run();
        inline void setDeleteSelf( sal_Bool b )
            { m_bDeleteSelf = b; }

    private:
        oslThread m_thread;
        JobQueue *m_pQueue;
        ::rtl::ByteSequence m_aThreadId;
        sal_Bool m_bAsynchron;
        sal_Bool m_bDeleteSelf;
    };

    class ThreadAdmin
    {
    public:
        ~ThreadAdmin ();
        static ThreadAdmin *getInstance();
        void add( ORequestThread * );
        void remove( ORequestThread * );
        void join();

    private:
        ::osl::Mutex m_mutex;
        ::std::list< ORequestThread * > m_lst;
    };

} // end cppu_threadpool

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.190); FILE MERGED 2005/09/05 13:54:26 rt 1.3.190.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: thread.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 08:47:30 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _CPPU_THREADPOOL_THREAD_HXX
#define _CPPU_THREADPOOL_THREAD_HXX

#include <list>

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#include <osl/thread.h>

#include "jobqueue.hxx"

namespace cppu_threadpool {

    class JobQueue;

    //-----------------------------------------
    // private thread class for the threadpool
    // independent from vos
    //-----------------------------------------
    class ORequestThread
    {
    public:
        ORequestThread( JobQueue * ,
                        const ::rtl::ByteSequence &aThreadId,
                        sal_Bool bAsynchron );
        ~ORequestThread();

        void setTask( JobQueue * , const ::rtl::ByteSequence & aThreadId , sal_Bool bAsynchron );

        sal_Bool create();
        void join();
        void onTerminated();
        void run();
        inline void setDeleteSelf( sal_Bool b )
            { m_bDeleteSelf = b; }

    private:
        oslThread m_thread;
        JobQueue *m_pQueue;
        ::rtl::ByteSequence m_aThreadId;
        sal_Bool m_bAsynchron;
        sal_Bool m_bDeleteSelf;
    };

    class ThreadAdmin
    {
    public:
        ~ThreadAdmin ();
        static ThreadAdmin *getInstance();
        void add( ORequestThread * );
        void remove( ORequestThread * );
        void join();

    private:
        ::osl::Mutex m_mutex;
        ::std::list< ORequestThread * > m_lst;
    };

} // end cppu_threadpool

#endif

<|endoftext|>


<commit_before>#include "../utils/utils.hpp"
#include "../utils/geom2d.hpp"
#include <cstdio>
#include <vector>
#include <cmath>
#include <utility>

struct Segments {
private:
	friend void mkinst(FILE*);

	// A Pose gives the pose of a particular segment.
	struct Pose {
		Pose() { }

		Pose(unsigned int xx, unsigned int yy, unsigned int r) : x(xx), y(yy), rot(r) {
		}

		bool operator==(const Pose &o) const {
			return x == o.x && y == o.y &&  rot == o.rot;
		}

		bool operator!=(const Pose &o) const {
			return !(*this == o);
		}

		unsigned int x, y, rot;
	};

	// Angle contains information about angles.
	struct Angle {
		Angle(double);

		double theta;
		double sine;
		double cosine;
	};

public:

	// A Sweep contains the geometry primitives that
	// represent a segment sweeping through space.
	struct Sweep {
		Sweep() : narcs(0), nlines(0), npolys(0) { }

		// hits returns true if the line segment hits
		// the sweep;
		bool hits(const geom2d::LineSg&) const;

		geom2d::Bbox bbox;

		unsigned int narcs, nlines, npolys;
		geom2d::Arc arcs[2];
		geom2d::LineSg lines[3];
		geom2d::Poly polys[1];
	};

	// Seg contains segment specific information.
	struct Seg {
		double radius;
		Pose goal;
		Pose start;
	};

	Segments(FILE*);

	Segments(unsigned int w, unsigned int h, unsigned int t, const std::vector<Seg>&);

	struct PackedState;

	struct State {
		State() { }

		// This constructor creates a state from the given poses.
		State(const Segments &dom, const std::vector<Pose> &ps,
			unsigned int xx, unsigned int yy) : x(xx), y(yy) {
			init(dom, ps);
		}

		State(const Segments &dom, const PackedState &pkd) : x(pkd.x), y(pkd.y) {
			init(dom, pkd.poses);
		}

		State(const State &o) : x(o.x), y(o.y), poses(o.poses), lines(o.lines), nleft(o.nleft) { }

		State(State &&o) : x(o.x), y(o.y), nleft(o.nleft) {
			std::swap(poses, o.poses);
			std::swap(lines, o.lines);
		}

		State& operator=(const State &o) {
			x = o.x;
			y = o.y;
			nleft = o.nleft;
			poses = o.poses;
			lines = o.lines;
			return *this;
		}

		State& operator=(State &&o) {
			x = o.x;
			y = o.y;
			nleft = o.nleft;
			std::swap(poses, o.poses);
			std::swap(lines, o.lines);
			return *this;
		}

		bool operator==(const State&) const;

		// x and y are the gripper's position.
		unsigned int x, y;

		// poses gives the pose of each segment.
		std::vector<Pose> poses;

		// lines gives the line segment representing
		// each segment.
		std::vector<geom2d::LineSg> lines;

		// nleft is the number of segments that still
		// need to be moved to their goal location.
		unsigned int nleft;

	private:
		// init initializes the poses, lines, and nleft fields of a
		// state from a vector of poses.
		void init(const Segments&, const std::vector<Pose>&);
	};

	struct PackedState {
		PackedState() { }

		PackedState(const State &s) : poses(s.poses), x(s.x), y(s.y) {
		}

		PackedState(PackedState &&o) : poses(std::move(o.poses)), x(o.x), y(o.y) {
		}

		PackedState &operator=(PackedState &&o) {
			x = o.x;
			y = o.y;
			std::swap(poses, o.poses);
			return *this;
		}

		bool operator==(const PackedState &o) const {
			for (unsigned int i = 0; i < poses.size(); i++) {
				if (poses[i] != o.poses[i])
					return false;
			}
			return x == o.x && y == o.y;
		}

		std::vector<Pose> poses;
		unsigned int x, y;
	};

	typedef double Cost;

	struct Oper {
		enum Op { None = 0, Rotate, Move };

		Oper() { }

		Oper(Op o, unsigned int s, int d, int y) : op(o), seg(s), delta(d), dy(y) {
		}

		// Equality test.
		//
		// All Gripper operations are equal regardless
		// of their seg fields.
		bool operator==(const Oper &o) const;

		// reverse returns the operator that, if applied
		// to the resulting state, would undo this operator.
		//
		// The reverse of a Gripper operation is the same
		// operation, this works because all Gripper ops
		// are equivalent.  This means that the Gripper is
		// never moved twice in a row.
		Oper reverse() const;

		// cost returns the cost of applying this operator
		// in the given state.
		Cost cost(const State&) const;

		// sweep returns the Sweep when applying
		// this operator in the given state.
		Sweep sweep(const Segments&, const State&) const;

		// rotatesweep returns the Sweep for a rotation.
		Sweep rotatesweep(const Segments&, const State&) const;

		// moveweep returns the Sweep for a move.
		Sweep movesweep(const Segments&, const State&) const;

		// ok returns true if the operator is applicable
		// in the given state.
		bool ok(const Segments&, const State&) const;

		// op is the operation.
		Op op;

		// seg is the target of the operation.
		unsigned int seg;

		// delta is either the change in x or in rotation.
		int delta, dy;
	};

	static Oper Nop;

	struct Operators {
		Operators(const Segments&, const State&);

		unsigned int size() const {
			return ops.size();
		}

		Oper operator[](unsigned int i) const {
			return ops[i];
		}

		std::vector<Oper> ops;
	};

	struct Edge {
		Cost cost;
		Oper revop;
		State state;

		Edge(const Segments&, const State&, Oper);

		~Edge() { }
	};

	State initialstate() const;

	State goalstate() const;

	unsigned long hash(const PackedState&) const;

	Cost h(const State&) const;

	Cost d(const State&) const;

	bool isgoal(const State &s) const {
		return s.nleft == 0;
	}

	void pack(PackedState &dst, const State &src) const {
		dst = PackedState(src);
	}

	State &unpack(State &buf, const PackedState &pkd) const {
		buf = State(*this, pkd);
		return buf;
	}

	Cost pathcost(const std::vector<State>&, const std::vector<Oper>&);

	// prinitial prints the initial state to the given
	// file in datafile format.
	void prinitial(FILE*) const;

	// width, height, and nangles give the discretization
	// of this problem instance.
	unsigned int width, height, nangles;

	// bounds are the lines defining the boundaries on the
	// working space of the segments.
	geom2d::LineSg bounds[4];

private:

	// line returns the line for the given segment
	// in the given pose.
	geom2d::LineSg line(const Seg&, const Pose&) const;

	// segs is the segments.
	std::vector<Seg> segs;

	// angles holds information about the different angles
	// at which a segment can be rotated.
	std::vector<Angle> angles;

	// dtheta is the change in angle for each rotation.
	double dtheta;
};

// scanops scans an operator vector from an
// operator string.
std::vector<Segments::Oper> scanops(const std::string&);

struct Solution {
	int width, height, nangles;
	std::vector<Segments::Seg> segs;
	std::vector<Segments::Oper> ops;
};

// readdf reads the segments instance and
// operators from a datafile.  If echo is
// non-null then each line of the datafile is
// echoed to the given FILE*.
Solution readdf(FILE *in, FILE *echo);
<commit_msg>segments: use a class, not a struct.<commit_after>#include "../utils/utils.hpp"
#include "../utils/geom2d.hpp"
#include <cstdio>
#include <vector>
#include <cmath>
#include <utility>

class Segments {
	friend void mkinst(FILE*);

	// A Pose gives the pose of a particular segment.
	struct Pose {
		Pose() { }

		Pose(unsigned int xx, unsigned int yy, unsigned int r) : x(xx), y(yy), rot(r) {
		}

		bool operator==(const Pose &o) const {
			return x == o.x && y == o.y &&  rot == o.rot;
		}

		bool operator!=(const Pose &o) const {
			return !(*this == o);
		}

		unsigned int x, y, rot;
	};

	// Angle contains information about angles.
	struct Angle {
		Angle(double);

		double theta;
		double sine;
		double cosine;
	};

public:

	// A Sweep contains the geometry primitives that
	// represent a segment sweeping through space.
	struct Sweep {
		Sweep() : narcs(0), nlines(0), npolys(0) { }

		// hits returns true if the line segment hits
		// the sweep;
		bool hits(const geom2d::LineSg&) const;

		geom2d::Bbox bbox;

		unsigned int narcs, nlines, npolys;
		geom2d::Arc arcs[2];
		geom2d::LineSg lines[3];
		geom2d::Poly polys[1];
	};

	// Seg contains segment specific information.
	struct Seg {
		double radius;
		Pose goal;
		Pose start;
	};

	Segments(FILE*);

	Segments(unsigned int w, unsigned int h, unsigned int t, const std::vector<Seg>&);

	struct PackedState;

	struct State {
		State() { }

		// This constructor creates a state from the given poses.
		State(const Segments &dom, const std::vector<Pose> &ps,
			unsigned int xx, unsigned int yy) : x(xx), y(yy) {
			init(dom, ps);
		}

		State(const Segments &dom, const PackedState &pkd) : x(pkd.x), y(pkd.y) {
			init(dom, pkd.poses);
		}

		State(const State &o) : x(o.x), y(o.y), poses(o.poses), lines(o.lines), nleft(o.nleft) { }

		State(State &&o) : x(o.x), y(o.y), nleft(o.nleft) {
			std::swap(poses, o.poses);
			std::swap(lines, o.lines);
		}

		State& operator=(const State &o) {
			x = o.x;
			y = o.y;
			nleft = o.nleft;
			poses = o.poses;
			lines = o.lines;
			return *this;
		}

		State& operator=(State &&o) {
			x = o.x;
			y = o.y;
			nleft = o.nleft;
			std::swap(poses, o.poses);
			std::swap(lines, o.lines);
			return *this;
		}

		bool operator==(const State&) const;

		// x and y are the gripper's position.
		unsigned int x, y;

		// poses gives the pose of each segment.
		std::vector<Pose> poses;

		// lines gives the line segment representing
		// each segment.
		std::vector<geom2d::LineSg> lines;

		// nleft is the number of segments that still
		// need to be moved to their goal location.
		unsigned int nleft;

	private:
		// init initializes the poses, lines, and nleft fields of a
		// state from a vector of poses.
		void init(const Segments&, const std::vector<Pose>&);
	};

	struct PackedState {
		PackedState() { }

		PackedState(const State &s) : poses(s.poses), x(s.x), y(s.y) {
		}

		PackedState(PackedState &&o) : poses(std::move(o.poses)), x(o.x), y(o.y) {
		}

		PackedState &operator=(PackedState &&o) {
			x = o.x;
			y = o.y;
			std::swap(poses, o.poses);
			return *this;
		}

		bool operator==(const PackedState &o) const {
			for (unsigned int i = 0; i < poses.size(); i++) {
				if (poses[i] != o.poses[i])
					return false;
			}
			return x == o.x && y == o.y;
		}

		std::vector<Pose> poses;
		unsigned int x, y;
	};

	typedef double Cost;

	struct Oper {
		enum Op { None = 0, Rotate, Move };

		Oper() { }

		Oper(Op o, unsigned int s, int d, int y) : op(o), seg(s), delta(d), dy(y) {
		}

		// Equality test.
		//
		// All Gripper operations are equal regardless
		// of their seg fields.
		bool operator==(const Oper &o) const;

		// reverse returns the operator that, if applied
		// to the resulting state, would undo this operator.
		//
		// The reverse of a Gripper operation is the same
		// operation, this works because all Gripper ops
		// are equivalent.  This means that the Gripper is
		// never moved twice in a row.
		Oper reverse() const;

		// cost returns the cost of applying this operator
		// in the given state.
		Cost cost(const State&) const;

		// sweep returns the Sweep when applying
		// this operator in the given state.
		Sweep sweep(const Segments&, const State&) const;

		// rotatesweep returns the Sweep for a rotation.
		Sweep rotatesweep(const Segments&, const State&) const;

		// moveweep returns the Sweep for a move.
		Sweep movesweep(const Segments&, const State&) const;

		// ok returns true if the operator is applicable
		// in the given state.
		bool ok(const Segments&, const State&) const;

		// op is the operation.
		Op op;

		// seg is the target of the operation.
		unsigned int seg;

		// delta is either the change in x or in rotation.
		int delta, dy;
	};

	static Oper Nop;

	struct Operators {
		Operators(const Segments&, const State&);

		unsigned int size() const {
			return ops.size();
		}

		Oper operator[](unsigned int i) const {
			return ops[i];
		}

		std::vector<Oper> ops;
	};

	struct Edge {
		Cost cost;
		Oper revop;
		State state;

		Edge(const Segments&, const State&, Oper);

		~Edge() { }
	};

	State initialstate() const;

	State goalstate() const;

	unsigned long hash(const PackedState&) const;

	Cost h(const State&) const;

	Cost d(const State&) const;

	bool isgoal(const State &s) const {
		return s.nleft == 0;
	}

	void pack(PackedState &dst, const State &src) const {
		dst = PackedState(src);
	}

	State &unpack(State &buf, const PackedState &pkd) const {
		buf = State(*this, pkd);
		return buf;
	}

	Cost pathcost(const std::vector<State>&, const std::vector<Oper>&);

	// prinitial prints the initial state to the given
	// file in datafile format.
	void prinitial(FILE*) const;

	// width, height, and nangles give the discretization
	// of this problem instance.
	unsigned int width, height, nangles;

	// bounds are the lines defining the boundaries on the
	// working space of the segments.
	geom2d::LineSg bounds[4];

private:

	// line returns the line for the given segment
	// in the given pose.
	geom2d::LineSg line(const Seg&, const Pose&) const;

	// segs is the segments.
	std::vector<Seg> segs;

	// angles holds information about the different angles
	// at which a segment can be rotated.
	std::vector<Angle> angles;

	// dtheta is the change in angle for each rotation.
	double dtheta;
};

// scanops scans an operator vector from an
// operator string.
std::vector<Segments::Oper> scanops(const std::string&);

struct Solution {
	int width, height, nangles;
	std::vector<Segments::Seg> segs;
	std::vector<Segments::Oper> ops;
};

// readdf reads the segments instance and
// operators from a datafile.  If echo is
// non-null then each line of the datafile is
// echoed to the given FILE*.
Solution readdf(FILE *in, FILE *echo);
<|endoftext|>


<commit_before>#ifndef color_hh_INCLUDED
#define color_hh_INCLUDED

#include "hash.hh"

namespace Kakoune
{

class String;
class StringView;

enum class Colors : char
{
    Default,
    Black,
    Red,
    Green,
    Yellow,
    Blue,
    Magenta,
    Cyan,
    White,
    RGB,
};

struct Color
{
    Colors color;
    unsigned char r;
    unsigned char g;
    unsigned char b;

    Color() : Color{Colors::Default} {}
    Color(Colors c) : color{c}, r{0}, g{0}, b{0} {}
    Color(unsigned char r, unsigned char g, unsigned char b)
        : color{Colors::RGB}, r{r}, g{g}, b{b} {}
};

inline bool operator==(Color lhs, Color rhs)
{
    return lhs.color == rhs.color and
           lhs.r == rhs.r and lhs.g == rhs.g and lhs.b == rhs.b;
}

inline bool operator!=(Color lhs, Color rhs)
{
    return not (lhs == rhs);
}

Color str_to_color(StringView color);
String color_to_str(Color color);

String option_to_string(Color color);
void option_from_string(StringView str, Color& color);

bool is_color_name(StringView color);

inline size_t hash_value(const Color& val)
{
    return val.color == Colors::RGB ?
        hash_values(val.color, val.r, val.g, val.b)
      : hash_value(val.color);
}

}

#endif // color_hh_INCLUDED
<commit_msg>constexprify Color (in)equality operator<commit_after>#ifndef color_hh_INCLUDED
#define color_hh_INCLUDED

#include "hash.hh"

namespace Kakoune
{

class String;
class StringView;

enum class Colors : char
{
    Default,
    Black,
    Red,
    Green,
    Yellow,
    Blue,
    Magenta,
    Cyan,
    White,
    RGB,
};

struct Color
{
    Colors color;
    unsigned char r;
    unsigned char g;
    unsigned char b;

    Color() : Color{Colors::Default} {}
    Color(Colors c) : color{c}, r{0}, g{0}, b{0} {}
    Color(unsigned char r, unsigned char g, unsigned char b)
        : color{Colors::RGB}, r{r}, g{g}, b{b} {}
};

constexpr bool operator==(Color lhs, Color rhs)
{
    return lhs.color == rhs.color and
           lhs.r == rhs.r and lhs.g == rhs.g and lhs.b == rhs.b;
}

constexpr bool operator!=(Color lhs, Color rhs)
{
    return not (lhs == rhs);
}

Color str_to_color(StringView color);
String color_to_str(Color color);

String option_to_string(Color color);
void option_from_string(StringView str, Color& color);

bool is_color_name(StringView color);

inline size_t hash_value(const Color& val)
{
    return val.color == Colors::RGB ?
        hash_values(val.color, val.r, val.g, val.b)
      : hash_value(val.color);
}

}

#endif // color_hh_INCLUDED
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "RTPFile.h"

#include <stdlib.h>

#ifdef WIN32
#   include <Winsock2.h>
#else
#   include <arpa/inet.h>
#endif

#include "audio_coding_module.h"
#include "engine_configurations.h"
#include "gtest/gtest.h" // TODO (tlegrand): Consider removing usage of gtest.
#include "rw_lock_wrapper.h"

namespace webrtc {

void RTPStream::ParseRTPHeader(WebRtcRTPHeader* rtpInfo,
                               const uint8_t* rtpHeader) {
  rtpInfo->header.payloadType = rtpHeader[1];
  rtpInfo->header.sequenceNumber = (static_cast<uint16_t>(rtpHeader[2]) << 8) |
      rtpHeader[3];
  rtpInfo->header.timestamp = (static_cast<uint32_t>(rtpHeader[4]) << 24) |
      (static_cast<uint32_t>(rtpHeader[5]) << 16) |
      (static_cast<uint32_t>(rtpHeader[6]) << 8) | rtpHeader[7];
  rtpInfo->header.ssrc = (static_cast<uint32_t>(rtpHeader[8]) << 24) |
      (static_cast<uint32_t>(rtpHeader[9]) << 16) |
      (static_cast<uint32_t>(rtpHeader[10]) << 8) | rtpHeader[11];
}

void RTPStream::MakeRTPheader(uint8_t* rtpHeader, uint8_t payloadType,
                              int16_t seqNo, uint32_t timeStamp,
                              uint32_t ssrc) {
  rtpHeader[0] = (unsigned char) 0x80;
  rtpHeader[1] = (unsigned char) (payloadType & 0xFF);
  rtpHeader[2] = (unsigned char) ((seqNo >> 8) & 0xFF);
  rtpHeader[3] = (unsigned char) ((seqNo) & 0xFF);
  rtpHeader[4] = (unsigned char) ((timeStamp >> 24) & 0xFF);
  rtpHeader[5] = (unsigned char) ((timeStamp >> 16) & 0xFF);

  rtpHeader[6] = (unsigned char) ((timeStamp >> 8) & 0xFF);
  rtpHeader[7] = (unsigned char) (timeStamp & 0xFF);

  rtpHeader[8] = (unsigned char) ((ssrc >> 24) & 0xFF);
  rtpHeader[9] = (unsigned char) ((ssrc >> 16) & 0xFF);

  rtpHeader[10] = (unsigned char) ((ssrc >> 8) & 0xFF);
  rtpHeader[11] = (unsigned char) (ssrc & 0xFF);
}

RTPPacket::RTPPacket(uint8_t payloadType, uint32_t timeStamp, int16_t seqNo,
                     const uint8_t* payloadData, uint16_t payloadSize,
                     uint32_t frequency)
    : payloadType(payloadType),
      timeStamp(timeStamp),
      seqNo(seqNo),
      payloadSize(payloadSize),
      frequency(frequency) {
  if (payloadSize > 0) {
    this->payloadData = new uint8_t[payloadSize];
    memcpy(this->payloadData, payloadData, payloadSize);
  }
}

RTPPacket::~RTPPacket() {
  delete[] payloadData;
}

RTPBuffer::RTPBuffer() {
  _queueRWLock = RWLockWrapper::CreateRWLock();
}

RTPBuffer::~RTPBuffer() {
  delete _queueRWLock;
}

void RTPBuffer::Write(const uint8_t payloadType, const uint32_t timeStamp,
                      const int16_t seqNo, const uint8_t* payloadData,
                      const uint16_t payloadSize, uint32_t frequency) {
  RTPPacket *packet = new RTPPacket(payloadType, timeStamp, seqNo, payloadData,
                                    payloadSize, frequency);
  _queueRWLock->AcquireLockExclusive();
  _rtpQueue.push(packet);
  _queueRWLock->ReleaseLockExclusive();
}

uint16_t RTPBuffer::Read(WebRtcRTPHeader* rtpInfo, uint8_t* payloadData,
                         uint16_t payloadSize, uint32_t* offset) {
  _queueRWLock->AcquireLockShared();
  RTPPacket *packet = _rtpQueue.front();
  _rtpQueue.pop();
  _queueRWLock->ReleaseLockShared();
  rtpInfo->header.markerBit = 1;
  rtpInfo->header.payloadType = packet->payloadType;
  rtpInfo->header.sequenceNumber = packet->seqNo;
  rtpInfo->header.ssrc = 0;
  rtpInfo->header.timestamp = packet->timeStamp;
  if (packet->payloadSize > 0 && payloadSize >= packet->payloadSize) {
    memcpy(payloadData, packet->payloadData, packet->payloadSize);
  } else {
    return 0;
  }
  *offset = (packet->timeStamp / (packet->frequency / 1000));

  return packet->payloadSize;
}

bool RTPBuffer::EndOfFile() const {
  _queueRWLock->AcquireLockShared();
  bool eof = _rtpQueue.empty();
  _queueRWLock->ReleaseLockShared();
  return eof;
}

void RTPFile::Open(const char *filename, const char *mode) {
  if ((_rtpFile = fopen(filename, mode)) == NULL) {
    printf("Cannot write file %s.\n", filename);
    ADD_FAILURE() << "Unable to write file";
    exit(1);
  }
}

void RTPFile::Close() {
  if (_rtpFile != NULL) {
    fclose(_rtpFile);
    _rtpFile = NULL;
  }
}

void RTPFile::WriteHeader() {
  // Write data in a format that NetEQ and RTP Play can parse
  fprintf(_rtpFile, "#!RTPencode%s\n", "1.0");
  uint32_t dummy_variable = 0;
  // should be converted to network endian format, but does not matter when 0
  if (fwrite(&dummy_variable, 4, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(&dummy_variable, 4, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(&dummy_variable, 4, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(&dummy_variable, 2, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(&dummy_variable, 2, 1, _rtpFile) != 1) {
    return;
  }
  fflush(_rtpFile);
}

void RTPFile::ReadHeader() {
  uint32_t start_sec, start_usec, source;
  uint16_t port, padding;
  char fileHeader[40];
  EXPECT_TRUE(fgets(fileHeader, 40, _rtpFile) != 0);
  EXPECT_EQ(1u, fread(&start_sec, 4, 1, _rtpFile));
  start_sec = ntohl(start_sec);
  EXPECT_EQ(1u, fread(&start_usec, 4, 1, _rtpFile));
  start_usec = ntohl(start_usec);
  EXPECT_EQ(1u, fread(&source, 4, 1, _rtpFile));
  source = ntohl(source);
  EXPECT_EQ(1u, fread(&port, 2, 1, _rtpFile));
  port = ntohs(port);
  EXPECT_EQ(1u, fread(&padding, 2, 1, _rtpFile));
  padding = ntohs(padding);
}

void RTPFile::Write(const uint8_t payloadType, const uint32_t timeStamp,
                    const int16_t seqNo, const uint8_t* payloadData,
                    const uint16_t payloadSize, uint32_t frequency) {
  /* write RTP packet to file */
  uint8_t rtpHeader[12];
  MakeRTPheader(rtpHeader, payloadType, seqNo, timeStamp, 0);
  uint16_t lengthBytes = htons(12 + payloadSize + 8);
  uint16_t plen = htons(12 + payloadSize);
  uint32_t offsetMs;

  offsetMs = (timeStamp / (frequency / 1000));
  offsetMs = htonl(offsetMs);
  if (fwrite(&lengthBytes, 2, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(&plen, 2, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(&offsetMs, 4, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(rtpHeader, 12, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(payloadData, 1, payloadSize, _rtpFile) != payloadSize) {
    return;
  }
}

uint16_t RTPFile::Read(WebRtcRTPHeader* rtpInfo, uint8_t* payloadData,
                       uint16_t payloadSize, uint32_t* offset) {
  uint16_t lengthBytes;
  uint16_t plen;
  uint8_t rtpHeader[12];
  size_t read_len = fread(&lengthBytes, 2, 1, _rtpFile);
  /* Check if we have reached end of file. */
  if ((read_len == 0) && feof(_rtpFile)) {
    _rtpEOF = true;
    return 0;
  }
  EXPECT_EQ(1u, fread(&plen, 2, 1, _rtpFile));
  EXPECT_EQ(1u, fread(offset, 4, 1, _rtpFile));
  lengthBytes = ntohs(lengthBytes);
  plen = ntohs(plen);
  *offset = ntohl(*offset);
  EXPECT_GT(plen, 11);

  EXPECT_EQ(1u, fread(rtpHeader, 12, 1, _rtpFile));
  ParseRTPHeader(rtpInfo, rtpHeader);
  rtpInfo->type.Audio.isCNG = false;
  rtpInfo->type.Audio.channel = 1;
  EXPECT_EQ(lengthBytes, plen + 8);

  if (plen == 0) {
    return 0;
  }
  if (payloadSize < (lengthBytes - 20)) {
    return 0;
  }
  if (lengthBytes < 20) {
    return 0;
  }
  lengthBytes -= 20;
  EXPECT_EQ(lengthBytes, fread(payloadData, 1, lengthBytes, _rtpFile));
  return lengthBytes;
}

}  // namespace webrtc
<commit_msg>cast return values in uint16_t RTPFile::Read() to uint16_t to avoid compile error BUG=3663 TESTED=ninja local build on windows. R=andrew@webrtc.org, kwiberg@webrtc.org, thorcarpenter@google.com<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "RTPFile.h"

#include <stdlib.h>

#ifdef WIN32
#   include <Winsock2.h>
#else
#   include <arpa/inet.h>
#endif

#include "audio_coding_module.h"
#include "engine_configurations.h"
#include "gtest/gtest.h" // TODO (tlegrand): Consider removing usage of gtest.
#include "rw_lock_wrapper.h"

namespace webrtc {

void RTPStream::ParseRTPHeader(WebRtcRTPHeader* rtpInfo,
                               const uint8_t* rtpHeader) {
  rtpInfo->header.payloadType = rtpHeader[1];
  rtpInfo->header.sequenceNumber = (static_cast<uint16_t>(rtpHeader[2]) << 8) |
      rtpHeader[3];
  rtpInfo->header.timestamp = (static_cast<uint32_t>(rtpHeader[4]) << 24) |
      (static_cast<uint32_t>(rtpHeader[5]) << 16) |
      (static_cast<uint32_t>(rtpHeader[6]) << 8) | rtpHeader[7];
  rtpInfo->header.ssrc = (static_cast<uint32_t>(rtpHeader[8]) << 24) |
      (static_cast<uint32_t>(rtpHeader[9]) << 16) |
      (static_cast<uint32_t>(rtpHeader[10]) << 8) | rtpHeader[11];
}

void RTPStream::MakeRTPheader(uint8_t* rtpHeader, uint8_t payloadType,
                              int16_t seqNo, uint32_t timeStamp,
                              uint32_t ssrc) {
  rtpHeader[0] = (unsigned char) 0x80;
  rtpHeader[1] = (unsigned char) (payloadType & 0xFF);
  rtpHeader[2] = (unsigned char) ((seqNo >> 8) & 0xFF);
  rtpHeader[3] = (unsigned char) ((seqNo) & 0xFF);
  rtpHeader[4] = (unsigned char) ((timeStamp >> 24) & 0xFF);
  rtpHeader[5] = (unsigned char) ((timeStamp >> 16) & 0xFF);

  rtpHeader[6] = (unsigned char) ((timeStamp >> 8) & 0xFF);
  rtpHeader[7] = (unsigned char) (timeStamp & 0xFF);

  rtpHeader[8] = (unsigned char) ((ssrc >> 24) & 0xFF);
  rtpHeader[9] = (unsigned char) ((ssrc >> 16) & 0xFF);

  rtpHeader[10] = (unsigned char) ((ssrc >> 8) & 0xFF);
  rtpHeader[11] = (unsigned char) (ssrc & 0xFF);
}

RTPPacket::RTPPacket(uint8_t payloadType, uint32_t timeStamp, int16_t seqNo,
                     const uint8_t* payloadData, uint16_t payloadSize,
                     uint32_t frequency)
    : payloadType(payloadType),
      timeStamp(timeStamp),
      seqNo(seqNo),
      payloadSize(payloadSize),
      frequency(frequency) {
  if (payloadSize > 0) {
    this->payloadData = new uint8_t[payloadSize];
    memcpy(this->payloadData, payloadData, payloadSize);
  }
}

RTPPacket::~RTPPacket() {
  delete[] payloadData;
}

RTPBuffer::RTPBuffer() {
  _queueRWLock = RWLockWrapper::CreateRWLock();
}

RTPBuffer::~RTPBuffer() {
  delete _queueRWLock;
}

void RTPBuffer::Write(const uint8_t payloadType, const uint32_t timeStamp,
                      const int16_t seqNo, const uint8_t* payloadData,
                      const uint16_t payloadSize, uint32_t frequency) {
  RTPPacket *packet = new RTPPacket(payloadType, timeStamp, seqNo, payloadData,
                                    payloadSize, frequency);
  _queueRWLock->AcquireLockExclusive();
  _rtpQueue.push(packet);
  _queueRWLock->ReleaseLockExclusive();
}

uint16_t RTPBuffer::Read(WebRtcRTPHeader* rtpInfo, uint8_t* payloadData,
                         uint16_t payloadSize, uint32_t* offset) {
  _queueRWLock->AcquireLockShared();
  RTPPacket *packet = _rtpQueue.front();
  _rtpQueue.pop();
  _queueRWLock->ReleaseLockShared();
  rtpInfo->header.markerBit = 1;
  rtpInfo->header.payloadType = packet->payloadType;
  rtpInfo->header.sequenceNumber = packet->seqNo;
  rtpInfo->header.ssrc = 0;
  rtpInfo->header.timestamp = packet->timeStamp;
  if (packet->payloadSize > 0 && payloadSize >= packet->payloadSize) {
    memcpy(payloadData, packet->payloadData, packet->payloadSize);
  } else {
    return 0;
  }
  *offset = (packet->timeStamp / (packet->frequency / 1000));

  return packet->payloadSize;
}

bool RTPBuffer::EndOfFile() const {
  _queueRWLock->AcquireLockShared();
  bool eof = _rtpQueue.empty();
  _queueRWLock->ReleaseLockShared();
  return eof;
}

void RTPFile::Open(const char *filename, const char *mode) {
  if ((_rtpFile = fopen(filename, mode)) == NULL) {
    printf("Cannot write file %s.\n", filename);
    ADD_FAILURE() << "Unable to write file";
    exit(1);
  }
}

void RTPFile::Close() {
  if (_rtpFile != NULL) {
    fclose(_rtpFile);
    _rtpFile = NULL;
  }
}

void RTPFile::WriteHeader() {
  // Write data in a format that NetEQ and RTP Play can parse
  fprintf(_rtpFile, "#!RTPencode%s\n", "1.0");
  uint32_t dummy_variable = 0;
  // should be converted to network endian format, but does not matter when 0
  if (fwrite(&dummy_variable, 4, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(&dummy_variable, 4, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(&dummy_variable, 4, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(&dummy_variable, 2, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(&dummy_variable, 2, 1, _rtpFile) != 1) {
    return;
  }
  fflush(_rtpFile);
}

void RTPFile::ReadHeader() {
  uint32_t start_sec, start_usec, source;
  uint16_t port, padding;
  char fileHeader[40];
  EXPECT_TRUE(fgets(fileHeader, 40, _rtpFile) != 0);
  EXPECT_EQ(1u, fread(&start_sec, 4, 1, _rtpFile));
  start_sec = ntohl(start_sec);
  EXPECT_EQ(1u, fread(&start_usec, 4, 1, _rtpFile));
  start_usec = ntohl(start_usec);
  EXPECT_EQ(1u, fread(&source, 4, 1, _rtpFile));
  source = ntohl(source);
  EXPECT_EQ(1u, fread(&port, 2, 1, _rtpFile));
  port = ntohs(port);
  EXPECT_EQ(1u, fread(&padding, 2, 1, _rtpFile));
  padding = ntohs(padding);
}

void RTPFile::Write(const uint8_t payloadType, const uint32_t timeStamp,
                    const int16_t seqNo, const uint8_t* payloadData,
                    const uint16_t payloadSize, uint32_t frequency) {
  /* write RTP packet to file */
  uint8_t rtpHeader[12];
  MakeRTPheader(rtpHeader, payloadType, seqNo, timeStamp, 0);
  uint16_t lengthBytes = htons(12 + payloadSize + 8);
  uint16_t plen = htons(12 + payloadSize);
  uint32_t offsetMs;

  offsetMs = (timeStamp / (frequency / 1000));
  offsetMs = htonl(offsetMs);
  if (fwrite(&lengthBytes, 2, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(&plen, 2, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(&offsetMs, 4, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(rtpHeader, 12, 1, _rtpFile) != 1) {
    return;
  }
  if (fwrite(payloadData, 1, payloadSize, _rtpFile) != payloadSize) {
    return;
  }
}

uint16_t RTPFile::Read(WebRtcRTPHeader* rtpInfo, uint8_t* payloadData,
                       uint16_t payloadSize, uint32_t* offset) {
  uint16_t lengthBytes;
  uint16_t plen;
  uint8_t rtpHeader[12];
  size_t read_len = fread(&lengthBytes, 2, 1, _rtpFile);
  /* Check if we have reached end of file. */
  if ((read_len == 0) && feof(_rtpFile)) {
    _rtpEOF = true;
    return 0;
  }
  EXPECT_EQ(1u, fread(&plen, 2, 1, _rtpFile));
  EXPECT_EQ(1u, fread(offset, 4, 1, _rtpFile));
  lengthBytes = ntohs(lengthBytes);
  plen = ntohs(plen);
  *offset = ntohl(*offset);
  EXPECT_GT(plen, 11);

  EXPECT_EQ(1u, fread(rtpHeader, 12, 1, _rtpFile));
  ParseRTPHeader(rtpInfo, rtpHeader);
  rtpInfo->type.Audio.isCNG = false;
  rtpInfo->type.Audio.channel = 1;
  EXPECT_EQ(lengthBytes, plen + 8);

  if (plen == 0) {
    return static_cast<uint16_t>(0);
  }
  if (payloadSize < (lengthBytes - 20)) {
    return static_cast<uint16_t>(0);
  }
  if (lengthBytes < 20) {
    return static_cast<uint16_t>(0);
  }
  lengthBytes -= 20;
  EXPECT_EQ(lengthBytes, fread(payloadData, 1, lengthBytes, _rtpFile));
  return lengthBytes;
}

}  // namespace webrtc
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: cairo_cairo.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_canvas.hxx"

/****************************************************************************************
 * Platform independent part of surface backends for OpenOffice.org Cairo Canvas        *
 * For rest of the functions, see platform specific cairo_<platform>_cairo.cxx          *
 ****************************************************************************************/

#include "cairo_cairo.hxx"

namespace cairo
{

/**
   * Surface::getCairo:  Create Cairo for the Canvas surface
   *
   * @return new Cairo or NULL
   **/
    Cairo* Surface::getCairo()
    {
        Cairo *cr = NULL;
        if (mpSurface) {
            cr = cairo_create( mpSurface );
        }
        return cr;
    }

// This is needed to distinguish support for Cairo versions < 1.2.
#if !defined (USE_CAIRO10_APIS)

  /**
   * Surface::~Surface:  Destroy the Canvas surface
   *
   * Cairo itself takes care of freeing any resources, such as
   * image data and other references related to the surface.
   *
   **/
    Surface::~Surface()
    {
        if( mpSurface )
        {
            cairo_surface_destroy( mpSurface );
            mpSurface = NULL;
        }
    }

  /**
   * Surface::getSimilar:  Create new similar Canvas surface
   * @param aContent format of the new surface (cairo_content_t from cairo/src/cairo.h)
   * @param width width of the new surface
   * @param height height of the new surface
   *
   * Creates a new Canvas surface. This should create platform native surface, even though
   * generic function is used.
   *
   * Cairo surface from aContent (cairo_content_t)
   *
   * @return new surface or NULL
   **/
    Surface* Surface::getSimilar( Content aContent, int width, int height )
    {
        // This should create platform native Cairo surface on ALL platforms.
        return new Surface( cairo_surface_create_similar( mpSurface, aContent, width, height ) );

        // For example on Mac OS X, cairo_surface_create_similar() actually results in native surface,
        // equivalent to cairo_quartz_surface_create()
    }
#endif   // !defined (USE_CAIRO10_APIS)

  /**
   * Surface::createVirtualDevice:  Create new VCL virtual device
   *
   * Creates a new virtual device in VCL, with the current mpSurface contents as data.
   * This is used by e.g. cairo_canvashelper_text.cxx to make VCL draw text on the cairo surface.
   *
   * @return new virtual device
   **/
    VirtualDevice* Surface::createVirtualDevice()
    {
        // struct SystemGraphicsData in vcl/inc/sysdata.hxx
        SystemGraphicsData aSystemGraphicsData;

        aSystemGraphicsData.nSize = sizeof(SystemGraphicsData);
        fillSystemGraphicsData( aSystemGraphicsData );

        /**
         *    Contrary to the description of
         *    VirtualDevice(SystemGraphicsData*, nBitCount);  (in vcl/inc/virdev.hxx)
         *    at least X11 behaves differently, i.e. nBitCount is color depth, not just 1 or 0.
        **/
        return new VirtualDevice( &aSystemGraphicsData,
                                  sal::static_int_cast<USHORT>(getDepth()) );
    }

}  // namespace cairo

<commit_msg>INTEGRATION: CWS canvas05 (1.5.24); FILE MERGED 2008/04/21 07:32:13 thb 1.5.24.8: RESYNC: (1.7-1.8); FILE MERGED 2008/04/16 13:47:38 thb 1.5.24.7: Made cairocanvas build on Win32 again 2008/04/07 14:34:03 thb 1.5.24.6: RESYNC: (1.5-1.7); FILE MERGED 2008/04/03 20:12:35 thb 1.5.24.5: Improved the system-dependent passing-around of the OS handles - now much more opaque 2008/04/03 16:02:25 thb 1.5.24.4: Merged in cairoquartz01 changes, reworked into the polymorphic Surface concept now 2008/04/02 22:56:26 thb 1.5.24.3: Reworked Surface class to abstract interface; changed all manual refcount handling to RAII 2008/03/18 22:00:55 thb 1.5.24.2: Implementing non-backbuffered canvas for cairocanvas as well - reworked to share most of the code 2007/12/18 10:05:52 thb 1.5.24.1: #i84049# Applying patch from jnavrati to fix a crash when xrender is not available<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: cairo_cairo.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_canvas.hxx"

#include "cairo_cairo.hxx"

#ifdef WNT
# include <tools/prewin.h>
# include <windows.h>
# include <tools/postwin.h>
#endif

#include <vcl/sysdata.hxx>
#include <vcl/syschild.hxx>

namespace cairo
{
/****************************************************************************************
 * Platform independent part of surface backends for OpenOffice.org Cairo Canvas        *
 * For the rest of the functions (and the platform-specific derived                     *
 *  Surface classes), see platform specific cairo_<platform>_cairo.cxx                  *
 ****************************************************************************************/

    const SystemEnvData* GetSysData(const Window *pOutputWindow)
    {
        const SystemEnvData* pSysData = NULL;
        // check whether we're a SysChild: have to fetch system data
        // directly from SystemChildWindow, because the GetSystemData
        // method is unfortunately not virtual
        const SystemChildWindow* pSysChild = dynamic_cast< const SystemChildWindow* >( pOutputWindow );
        if( pSysChild )
            pSysData = pSysChild->GetSystemData();
        else
            pSysData = pOutputWindow->GetSystemData();
        return pSysData;
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 ScyllaDB
 *
 * Modified by ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "schema.hh"
#include "query-request.hh"

namespace query {

class clustering_key_filter_ranges {
    clustering_row_ranges _storage;
    const clustering_row_ranges& _ref;
public:
    clustering_key_filter_ranges(const clustering_row_ranges& ranges) : _ref(ranges) { }
    struct reversed { };
    clustering_key_filter_ranges(reversed, const clustering_row_ranges& ranges)
        : _storage(ranges.rbegin(), ranges.rend()), _ref(_storage) { }

    clustering_key_filter_ranges(clustering_key_filter_ranges&& other) noexcept
        : _storage(std::move(other._storage))
        , _ref(&other._ref == &other._storage ? _storage : other._ref)
    { }

    clustering_key_filter_ranges& operator=(clustering_key_filter_ranges&& other) noexcept {
        if (this != &other) {
            this->~clustering_key_filter_ranges();
            new (this) clustering_key_filter_ranges(std::move(other));
        }
        return *this;
    }

    auto begin() const { return _ref.begin(); }
    auto end() const { return _ref.end(); }
    bool empty() const { return _ref.empty(); }
    size_t size() const { return _ref.size(); }
    const clustering_row_ranges& ranges() const { return _ref; }

    static clustering_key_filter_ranges get_ranges(const schema& schema, const query::partition_slice& slice, const partition_key& key) {
        const query::clustering_row_ranges& ranges = slice.row_ranges(schema, key);
        if (slice.options.contains(query::partition_slice::option::reversed)) {
            return clustering_key_filter_ranges(clustering_key_filter_ranges::reversed{}, ranges);
        }
        return clustering_key_filter_ranges(ranges);
    }
};

}
<commit_msg>clustering_key_filter_ranges: Fix move assignment to avoid undefined behaviour.<commit_after>/*
 * Copyright (C) 2016 ScyllaDB
 *
 * Modified by ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "schema.hh"
#include "query-request.hh"

namespace query {

class clustering_key_filter_ranges {
    clustering_row_ranges _storage;
    std::reference_wrapper<const clustering_row_ranges> _ref;
public:
    clustering_key_filter_ranges(const clustering_row_ranges& ranges) : _ref(ranges) { }
    struct reversed { };
    clustering_key_filter_ranges(reversed, const clustering_row_ranges& ranges)
        : _storage(ranges.rbegin(), ranges.rend()), _ref(_storage) { }

    clustering_key_filter_ranges(clustering_key_filter_ranges&& other) noexcept
        : _storage(std::move(other._storage))
        , _ref(&other._ref.get() == &other._storage ? _storage : other._ref.get())
    { }

    clustering_key_filter_ranges& operator=(clustering_key_filter_ranges&& other) noexcept {
        if (this != &other) {
            _storage = std::move(other._storage);
            _ref = (&other._ref.get() == &other._storage) ? _storage : other._ref.get();
        }
        return *this;
    }

    auto begin() const { return _ref.get().begin(); }
    auto end() const { return _ref.get().end(); }
    bool empty() const { return _ref.get().empty(); }
    size_t size() const { return _ref.get().size(); }
    const clustering_row_ranges& ranges() const { return _ref; }

    static clustering_key_filter_ranges get_ranges(const schema& schema, const query::partition_slice& slice, const partition_key& key) {
        const query::clustering_row_ranges& ranges = slice.row_ranges(schema, key);
        if (slice.options.contains(query::partition_slice::option::reversed)) {
            return clustering_key_filter_ranges(clustering_key_filter_ranges::reversed{}, ranges);
        }
        return clustering_key_filter_ranges(ranges);
    }
};

}
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/core/base_Layer.h"

#include "gtest/gtest.h"

#include <memory>

#include "elm/core/exception.h"
#include "elm/core/layerconfig.h"
#include "elm/core/signal.h"

using namespace std;
using std::shared_ptr;
using std::unique_ptr;
using namespace cv;
using namespace elm;

/** class for deriving from base Layer for test purposes
  */
class DummyChildLayer : public base_Layer
{
public:
    void Clear() {}

    void Reconfigure(const LayerConfig &config) {}

    void InputNames(const LayerInputNames &io) {}

    void OutputNames(const LayerOutputNames &io);

    void Activate(const Signal &signal) {}

    void Response(Signal &signal) {}

    DummyChildLayer() {}
};

class LayerTest : public ::testing::Test
{
protected:
    virtual void SetUp()
    {
        to_.reset(new DummyChildLayer());
    }

    shared_ptr<base_Layer> to_; ///< test object
};

TEST_F(LayerTest, Reset)
{
    EXPECT_NO_THROW(to_->Reset(LayerConfig()));
}

TEST_F(LayerTest, Reset_unique_ptr)
{
    unique_ptr<base_Layer> to(new DummyChildLayer());
    EXPECT_NO_THROW(to_->Reset(LayerConfig()));
}
<commit_msg>add missing method definition<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/core/base_Layer.h"

#include "gtest/gtest.h"

#include <memory>

#include "elm/core/exception.h"
#include "elm/core/layerconfig.h"
#include "elm/core/signal.h"

using namespace std;
using std::shared_ptr;
using std::unique_ptr;
using namespace cv;
using namespace elm;

/** class for deriving from base Layer for test purposes
  */
class DummyChildLayer : public base_Layer
{
public:
    void Clear() {}

    void Reconfigure(const LayerConfig &config) {}

    void InputNames(const LayerInputNames &io) {}

    void OutputNames(const LayerOutputNames &io) {}

    void Activate(const Signal &signal) {}

    void Response(Signal &signal) {}

    DummyChildLayer()
        : base_Layer()
    {}
};

class LayerTest : public ::testing::Test
{
protected:
    virtual void SetUp()
    {
        to_.reset(new DummyChildLayer());
    }

    shared_ptr<base_Layer> to_; ///< test object
};

TEST_F(LayerTest, Reset)
{
    EXPECT_NO_THROW(to_->Reset(LayerConfig()));
}

TEST_F(LayerTest, Reset_unique_ptr)
{
    unique_ptr<base_Layer> to(new DummyChildLayer());
    EXPECT_NO_THROW(to_->Reset(LayerConfig()));
}
<|endoftext|>


<commit_before>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.

// Copyright (C) 2014, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.

#include "../test_precomp.hpp"
#include "opencv2/ts/ocl_test.hpp"

#ifdef HAVE_OPENCL

namespace cvtest {
namespace ocl {

PARAM_TEST_CASE(FastNlMeansDenoisingTestBase, Channels, bool, bool)
{
    int cn, templateWindowSize, searchWindowSize;
    float h;
    bool use_roi, use_image;

    TEST_DECLARE_INPUT_PARAMETER(src);
    TEST_DECLARE_OUTPUT_PARAMETER(dst);

    virtual void SetUp()
    {
        cn = GET_PARAM(0);
        use_roi = GET_PARAM(1);
        use_image = GET_PARAM(2);

        templateWindowSize = 7;
        searchWindowSize = 21;
        h = 3.0f;
    }

    virtual void generateTestData()
    {
        const int type = CV_8UC(cn);
        Mat image;

        if (use_image) {
            image = readImage("denoising/lena_noised_gaussian_sigma=10.png",
                                  cn == 1 ? IMREAD_GRAYSCALE : IMREAD_COLOR);
            ASSERT_FALSE(image.empty());
        }

        Size roiSize = use_image ? image.size() : randomSize(1, MAX_VALUE);
        Border srcBorder = randomBorder(0, use_roi ? MAX_VALUE : 0);
        randomSubMat(src, src_roi, roiSize, srcBorder, type, 0, 255);
        if (use_image) {
            ASSERT_TRUE(cn == 1 || cn == 2 || cn == 3 || cn == 4);
            if (cn == 2) {
                int from_to[] = { 0,0, 1,1 };
                src_roi.create(roiSize, type);
                mixChannels(&image, 1, &src_roi, 1, from_to, 2);
            }
            else if (cn == 4) {
                int from_to[] = { 0,0, 1,1, 2,2, 1,3};
                src_roi.create(roiSize, type);
                mixChannels(&image, 1, &src_roi, 1, from_to, 4);
            }
            else image.copyTo(src_roi);
        }

        Border dstBorder = randomBorder(0, use_roi ? MAX_VALUE : 0);
        randomSubMat(dst, dst_roi, roiSize, dstBorder, type, 0, 255);

        UMAT_UPLOAD_INPUT_PARAMETER(src);
        UMAT_UPLOAD_OUTPUT_PARAMETER(dst);
    }
};

typedef FastNlMeansDenoisingTestBase FastNlMeansDenoising;

OCL_TEST_P(FastNlMeansDenoising, Mat)
{
    for (int j = 0; j < test_loop_times; j++)
    {
        generateTestData();

        OCL_OFF(cv::fastNlMeansDenoising(src_roi, dst_roi, h, templateWindowSize, searchWindowSize));
        OCL_ON(cv::fastNlMeansDenoising(usrc_roi, udst_roi, h, templateWindowSize, searchWindowSize));

        OCL_EXPECT_MATS_NEAR(dst, 1);
    }
}

typedef FastNlMeansDenoisingTestBase FastNlMeansDenoisingAbs;

OCL_TEST_P(FastNlMeansDenoisingAbs, Mat)
{
    for (int j = 0; j < test_loop_times; j++)
    {
        generateTestData();

        OCL_OFF(cv::fastNlMeansDenoisingAbs(src_roi, dst_roi, h, templateWindowSize, searchWindowSize));
        OCL_ON(cv::fastNlMeansDenoisingAbs(usrc_roi, udst_roi, h, templateWindowSize, searchWindowSize));

        OCL_EXPECT_MATS_NEAR(dst, 1);
    }
}

typedef FastNlMeansDenoisingTestBase FastNlMeansDenoisingColored;

OCL_TEST_P(FastNlMeansDenoisingColored, Mat)
{
    for (int j = 0; j < test_loop_times; j++)
    {
        generateTestData();

        OCL_OFF(cv::fastNlMeansDenoisingColored(src_roi, dst_roi, h, h, templateWindowSize, searchWindowSize));
        OCL_ON(cv::fastNlMeansDenoisingColored(usrc_roi, udst_roi, h, h, templateWindowSize, searchWindowSize));

        OCL_EXPECT_MATS_NEAR(dst, 1);
    }
}

OCL_INSTANTIATE_TEST_CASE_P(Photo, FastNlMeansDenoising,
                            Combine(Values(1, 2, 3, 4), Bool(), Bool()));
OCL_INSTANTIATE_TEST_CASE_P(Photo, FastNlMeansDenoisingAbs,
                            Combine(Values(1, 2, 3, 4), Bool(), Bool()));
OCL_INSTANTIATE_TEST_CASE_P(Photo, FastNlMeansDenoisingColored,
                            Combine(Values(3, 4), Bool(), Values(false)));

} } // namespace cvtest::ocl

#endif // HAVE_OPENCL
<commit_msg>Addition of test cases<commit_after>// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.

// Copyright (C) 2014, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.

#include "../test_precomp.hpp"
#include "opencv2/ts/ocl_test.hpp"

#ifdef HAVE_OPENCL

namespace cvtest {
namespace ocl {

PARAM_TEST_CASE(FastNlMeansDenoisingTestBase, Channels, bool, bool)
{
    int cn, templateWindowSize, searchWindowSize;
    float h[4];
    bool use_roi, use_image;

    TEST_DECLARE_INPUT_PARAMETER(src);
    TEST_DECLARE_OUTPUT_PARAMETER(dst);

    virtual void SetUp()
    {
        cn = GET_PARAM(0);
        use_roi = GET_PARAM(1);
        use_image = GET_PARAM(2);

        templateWindowSize = 7;
        searchWindowSize = 21;

        ASSERT_TRUE(cn > 0 && cn <= 4);
        for (int i=0; i<cn; i++)
            h[i] = 3.0f + 0.5f*i;
    }

    virtual void generateTestData()
    {
        const int type = CV_8UC(cn);
        Mat image;

        if (use_image) {
            image = readImage("denoising/lena_noised_gaussian_sigma=10.png",
                                  cn == 1 ? IMREAD_GRAYSCALE : IMREAD_COLOR);
            ASSERT_FALSE(image.empty());
        }

        Size roiSize = use_image ? image.size() : randomSize(1, MAX_VALUE);
        Border srcBorder = randomBorder(0, use_roi ? MAX_VALUE : 0);
        randomSubMat(src, src_roi, roiSize, srcBorder, type, 0, 255);
        if (use_image) {
            if (cn == 2) {
                int from_to[] = { 0,0, 1,1 };
                src_roi.create(roiSize, type);
                mixChannels(&image, 1, &src_roi, 1, from_to, 2);
            }
            else if (cn == 4) {
                int from_to[] = { 0,0, 1,1, 2,2, 1,3};
                src_roi.create(roiSize, type);
                mixChannels(&image, 1, &src_roi, 1, from_to, 4);
            }
            else image.copyTo(src_roi);
        }

        Border dstBorder = randomBorder(0, use_roi ? MAX_VALUE : 0);
        randomSubMat(dst, dst_roi, roiSize, dstBorder, type, 0, 255);

        UMAT_UPLOAD_INPUT_PARAMETER(src);
        UMAT_UPLOAD_OUTPUT_PARAMETER(dst);
    }
};

typedef FastNlMeansDenoisingTestBase FastNlMeansDenoising;

OCL_TEST_P(FastNlMeansDenoising, Mat)
{
    for (int j = 0; j < test_loop_times; j++)
    {
        generateTestData();

        OCL_OFF(cv::fastNlMeansDenoising(src_roi, dst_roi, h[0], templateWindowSize, searchWindowSize));
        OCL_ON(cv::fastNlMeansDenoising(usrc_roi, udst_roi, h[0], templateWindowSize, searchWindowSize));

        OCL_EXPECT_MATS_NEAR(dst, 1);
    }
}

typedef FastNlMeansDenoisingTestBase FastNlMeansDenoising_hsep;

OCL_TEST_P(FastNlMeansDenoising_hsep, Mat)
{
    for (int j = 0; j < test_loop_times; j++)
    {
        generateTestData();

        OCL_OFF(cv::fastNlMeansDenoising(src_roi, dst_roi, h, templateWindowSize, searchWindowSize));
        OCL_ON(cv::fastNlMeansDenoising(usrc_roi, udst_roi, h, templateWindowSize, searchWindowSize));

        OCL_EXPECT_MATS_NEAR(dst, 1);
    }
}

typedef FastNlMeansDenoisingTestBase FastNlMeansDenoisingAbs;

OCL_TEST_P(FastNlMeansDenoisingAbs, Mat)
{
    for (int j = 0; j < test_loop_times; j++)
    {
        generateTestData();

        OCL_OFF(cv::fastNlMeansDenoisingAbs(src_roi, dst_roi, h[0], templateWindowSize, searchWindowSize));
        OCL_ON(cv::fastNlMeansDenoisingAbs(usrc_roi, udst_roi, h[0], templateWindowSize, searchWindowSize));

        OCL_EXPECT_MATS_NEAR(dst, 1);
    }
}

typedef FastNlMeansDenoisingTestBase FastNlMeansDenoisingAbs_hsep;

OCL_TEST_P(FastNlMeansDenoisingAbs_hsep, Mat)
{
    for (int j = 0; j < test_loop_times; j++)
    {
        generateTestData();

        OCL_OFF(cv::fastNlMeansDenoisingAbs(src_roi, dst_roi, h, templateWindowSize, searchWindowSize));
        OCL_ON(cv::fastNlMeansDenoisingAbs(usrc_roi, udst_roi, h, templateWindowSize, searchWindowSize));

        OCL_EXPECT_MATS_NEAR(dst, 1);
    }
}

typedef FastNlMeansDenoisingTestBase FastNlMeansDenoisingColored;

OCL_TEST_P(FastNlMeansDenoisingColored, Mat)
{
    for (int j = 0; j < test_loop_times; j++)
    {
        generateTestData();

        OCL_OFF(cv::fastNlMeansDenoisingColored(src_roi, dst_roi, h[0], h[0], templateWindowSize, searchWindowSize));
        OCL_ON(cv::fastNlMeansDenoisingColored(usrc_roi, udst_roi, h[0], h[0], templateWindowSize, searchWindowSize));

        OCL_EXPECT_MATS_NEAR(dst, 1);
    }
}

OCL_INSTANTIATE_TEST_CASE_P(Photo, FastNlMeansDenoising,
                            Combine(Values(1, 2, 3, 4), Bool(), Values(true)));
OCL_INSTANTIATE_TEST_CASE_P(Photo, FastNlMeansDenoising_hsep,
                            Combine(Values(1, 2, 3, 4), Bool(), Values(true)));
OCL_INSTANTIATE_TEST_CASE_P(Photo, FastNlMeansDenoisingAbs,
                            Combine(Values(1, 2, 3, 4), Bool(), Values(true)));
OCL_INSTANTIATE_TEST_CASE_P(Photo, FastNlMeansDenoisingAbs_hsep,
                            Combine(Values(1, 2, 3, 4), Bool(), Values(true)));
OCL_INSTANTIATE_TEST_CASE_P(Photo, FastNlMeansDenoisingColored,
                            Combine(Values(3, 4), Bool(), Values(false)));

} } // namespace cvtest::ocl

#endif // HAVE_OPENCL
<|endoftext|>


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

#include "modules/planning/planner/em/em_planner.h"

#include <fstream>
#include <utility>

#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/time/time.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/common/util/string_util.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/map/hdmap/hdmap.h"
#include "modules/map/hdmap/hdmap_common.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/constraint_checker/constraint_checker.h"
#include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h"
#include "modules/planning/planner/em/decider.h"
#include "modules/planning/tasks/dp_poly_path/dp_poly_path_optimizer.h"
#include "modules/planning/tasks/dp_st_speed/dp_st_speed_optimizer.h"
#include "modules/planning/tasks/path_decider/path_decider.h"
#include "modules/planning/tasks/qp_spline_path/qp_spline_path_optimizer.h"
#include "modules/planning/tasks/qp_spline_st_speed/qp_spline_st_speed_optimizer.h"
#include "modules/planning/tasks/traffic_decider/traffic_decider.h"

namespace apollo {
namespace planning {

using common::Status;
using common::adapter::AdapterManager;
using common::time::Clock;
using common::ErrorCode;
using common::SpeedPoint;
using common::SLPoint;
using common::TrajectoryPoint;
using common::math::Vec2d;

void EMPlanner::RegisterTasks() {
  task_factory_.Register(TRAFFIC_DECIDER,
                         []() -> Task* { return new TrafficDecider(); });
  task_factory_.Register(DP_POLY_PATH_OPTIMIZER,
                         []() -> Task* { return new DpPolyPathOptimizer(); });
  task_factory_.Register(PATH_DECIDER,
                         []() -> Task* { return new PathDecider(); });
  task_factory_.Register(DP_ST_SPEED_OPTIMIZER,
                         []() -> Task* { return new DpStSpeedOptimizer(); });
  task_factory_.Register(QP_SPLINE_PATH_OPTIMIZER,
                         []() -> Task* { return new QpSplinePathOptimizer(); });
  task_factory_.Register(QP_SPLINE_ST_SPEED_OPTIMIZER, []() -> Task* {
    return new QpSplineStSpeedOptimizer();
  });
}

Status EMPlanner::Init(const PlanningConfig& config) {
  AINFO << "In EMPlanner::Init()";
  RegisterTasks();
  for (const auto task : config.em_planner_config().task()) {
    tasks_.emplace_back(
        task_factory_.CreateObject(static_cast<TaskType>(task)));
    AINFO << "Created task:" << tasks_.back()->Name();
  }
  for (auto& task : tasks_) {
    if (!task->Init(config)) {
      std::string msg(
          common::util::StrCat("Init task[", task->Name(), "] failed."));
      AERROR << msg;
      return Status(ErrorCode::PLANNING_ERROR, msg);
    }
  }
  return Status::OK();
}

void EMPlanner::RecordDebugInfo(const std::string& name,
                                const double time_diff_ms,
                                planning::LatencyStats* ptr_latency_stats) {
  if (!FLAGS_enable_record_debug) {
    ADEBUG << "Skip record debug info";
    return;
  }
  auto ptr_stats = ptr_latency_stats->add_task_stats();
  ptr_stats->set_name(name);
  ptr_stats->set_time_ms(time_diff_ms);
}

void EMPlanner::PopulateDecision(const ReferenceLineInfo& reference_line_info,
                                 Frame* frame) {
  auto* planning_pb = frame->MutableADCTrajectory();
  *planning_pb->mutable_decision() = Decider::MakeDecision(reference_line_info);
}

Status EMPlanner::Plan(const TrajectoryPoint& planning_start_point,
                       Frame* frame, ReferenceLineInfo* reference_line_info) {
  if (!frame) {
    AERROR << "Frame is empty in EMPlanner";
    return Status(ErrorCode::PLANNING_ERROR, "Frame is null");
  }

  ADEBUG << "planning start point:" << planning_start_point.DebugString();
  auto* heuristic_speed_data = reference_line_info->mutable_speed_data();
  auto speed_profile =
      GenerateInitSpeedProfile(planning_start_point, reference_line_info);
  if (speed_profile.empty()) {
    speed_profile = GenerateSpeedHotStart(planning_start_point);
    ADEBUG << "Using dummy hot start for speed vector";
  }
  heuristic_speed_data->set_speed_vector(speed_profile);

  auto ptr_debug = reference_line_info->mutable_debug();
  auto ptr_latency_stats = reference_line_info->mutable_latency_stats();
  auto ret = Status::OK();
  for (auto& optimizer : tasks_) {
    const double start_timestamp = Clock::NowInSecond();
    ret = optimizer->Execute(frame, reference_line_info);
    if (!ret.ok()) {
      AERROR << "Failed to run tasks[" << optimizer->Name()
             << "], Error message: " << ret.error_message();
      break;
    }
    const double end_timestamp = Clock::NowInSecond();
    const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;

    ADEBUG << "after optimizer " << optimizer->Name() << ":"
           << reference_line_info->PathSpeedDebugString() << std::endl;
    ADEBUG << optimizer->Name() << " time spend: " << time_diff_ms << " ms.";

    if (FLAGS_enable_record_debug && ptr_debug != nullptr &&
        ptr_latency_stats != nullptr) {
      RecordDebugInfo(optimizer->Name(), time_diff_ms, ptr_latency_stats);
    }
  }
  DiscretizedTrajectory trajectory;
  if (!reference_line_info->CombinePathAndSpeedProfile(
          FLAGS_output_trajectory_time_resolution,
          planning_start_point.relative_time(), &trajectory)) {
    std::string msg("Fail to aggregate planning trajectory.");
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }

  if (FLAGS_enable_trajectory_check) {
    ConstraintChecker::ValidTrajectory(trajectory);
  }

  reference_line_info->SetTrajectory(trajectory);
  PopulateDecision(*reference_line_info, frame);

  return ret;
}

std::vector<SpeedPoint> EMPlanner::GenerateInitSpeedProfile(
    const TrajectoryPoint& planning_init_point,
    const ReferenceLineInfo* reference_line_info) {
  std::vector<SpeedPoint> speed_profile;
  const auto* last_frame = FrameHistory::instance()->Latest();
  if (!last_frame) {
    AWARN << "last frame is empty";
    return speed_profile;
  }
  const ReferenceLineInfo* last_reference_line_info =
      last_frame->DriveReferenceLinfInfo();
  if (!last_reference_line_info) {
    ADEBUG << "last reference line info is empty";
    return speed_profile;
  }
  if (!reference_line_info->IsStartFrom(*last_reference_line_info)) {
    ADEBUG << "Current reference line is not started previous drived line";
    return speed_profile;
  }
  const auto& last_speed_vector =
      last_reference_line_info->speed_data().speed_vector();

  if (!last_speed_vector.empty()) {
    const auto& last_init_point = last_frame->PlanningStartPoint().path_point();
    Vec2d last_xy_point(last_init_point.x(), last_init_point.y());
    SLPoint last_sl_point;
    if (!last_reference_line_info->reference_line().XYToSL(last_xy_point,
                                                           &last_sl_point)) {
      AERROR << "Fail to transfer xy to sl when init speed profile";
    }

    Vec2d xy_point(planning_init_point.path_point().x(),
                   planning_init_point.path_point().y());
    SLPoint sl_point;
    if (!last_reference_line_info->reference_line().XYToSL(xy_point,
                                                           &last_sl_point)) {
      AERROR << "Fail to transfer xy to sl when init speed profile";
    }
    double s_diff = sl_point.s() - last_sl_point.s();
    double start_time = 0.0;
    double start_s = 0.0;
    bool is_updated_start = false;
    for (const auto& speed_point : last_speed_vector) {
      if (speed_point.s() < s_diff) {
        continue;
      }
      if (!is_updated_start) {
        start_time = speed_point.t();
        start_s = speed_point.s();
        is_updated_start = true;
      }
      SpeedPoint refined_speed_point;
      refined_speed_point.set_s(speed_point.s() - start_s);
      refined_speed_point.set_t(speed_point.t() - start_time);
      refined_speed_point.set_v(speed_point.v());
      refined_speed_point.set_a(speed_point.a());
      refined_speed_point.set_da(speed_point.da());
      speed_profile.push_back(std::move(refined_speed_point));
    }
  }
  return speed_profile;
}

// This is a dummy simple hot start, need refine later
std::vector<SpeedPoint> EMPlanner::GenerateSpeedHotStart(
    const TrajectoryPoint& planning_init_point) {
  std::vector<SpeedPoint> hot_start_speed_profile;
  double s = 0.0;
  double t = 0.0;
  while (t < FLAGS_trajectory_time_length) {
    SpeedPoint speed_point;
    speed_point.set_s(s);
    speed_point.set_t(t);
    speed_point.set_v(FLAGS_planning_upper_speed_limit);

    hot_start_speed_profile.push_back(std::move(speed_point));

    t += FLAGS_trajectory_time_resolution;
    s += FLAGS_planning_upper_speed_limit * FLAGS_trajectory_time_resolution;
  }
  return hot_start_speed_profile;
}

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

#include "modules/planning/planner/em/em_planner.h"

#include <fstream>
#include <utility>

#include "modules/common/adapters/adapter_manager.h"
#include "modules/common/log.h"
#include "modules/common/time/time.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/common/util/string_util.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/map/hdmap/hdmap.h"
#include "modules/map/hdmap/hdmap_common.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/constraint_checker/constraint_checker.h"
#include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h"
#include "modules/planning/planner/em/decider.h"
#include "modules/planning/tasks/dp_poly_path/dp_poly_path_optimizer.h"
#include "modules/planning/tasks/dp_st_speed/dp_st_speed_optimizer.h"
#include "modules/planning/tasks/path_decider/path_decider.h"
#include "modules/planning/tasks/qp_spline_path/qp_spline_path_optimizer.h"
#include "modules/planning/tasks/qp_spline_st_speed/qp_spline_st_speed_optimizer.h"
#include "modules/planning/tasks/traffic_decider/traffic_decider.h"

namespace apollo {
namespace planning {

using common::Status;
using common::adapter::AdapterManager;
using common::time::Clock;
using common::ErrorCode;
using common::SpeedPoint;
using common::SLPoint;
using common::TrajectoryPoint;
using common::math::Vec2d;

void EMPlanner::RegisterTasks() {
  task_factory_.Register(TRAFFIC_DECIDER,
                         []() -> Task* { return new TrafficDecider(); });
  task_factory_.Register(DP_POLY_PATH_OPTIMIZER,
                         []() -> Task* { return new DpPolyPathOptimizer(); });
  task_factory_.Register(PATH_DECIDER,
                         []() -> Task* { return new PathDecider(); });
  task_factory_.Register(DP_ST_SPEED_OPTIMIZER,
                         []() -> Task* { return new DpStSpeedOptimizer(); });
  task_factory_.Register(QP_SPLINE_PATH_OPTIMIZER,
                         []() -> Task* { return new QpSplinePathOptimizer(); });
  task_factory_.Register(QP_SPLINE_ST_SPEED_OPTIMIZER, []() -> Task* {
    return new QpSplineStSpeedOptimizer();
  });
}

Status EMPlanner::Init(const PlanningConfig& config) {
  AINFO << "In EMPlanner::Init()";
  RegisterTasks();
  for (const auto task : config.em_planner_config().task()) {
    tasks_.emplace_back(
        task_factory_.CreateObject(static_cast<TaskType>(task)));
    AINFO << "Created task:" << tasks_.back()->Name();
  }
  for (auto& task : tasks_) {
    if (!task->Init(config)) {
      std::string msg(
          common::util::StrCat("Init task[", task->Name(), "] failed."));
      AERROR << msg;
      return Status(ErrorCode::PLANNING_ERROR, msg);
    }
  }
  return Status::OK();
}

void EMPlanner::RecordDebugInfo(const std::string& name,
                                const double time_diff_ms,
                                planning::LatencyStats* ptr_latency_stats) {
  if (!FLAGS_enable_record_debug) {
    ADEBUG << "Skip record debug info";
    return;
  }
  auto ptr_stats = ptr_latency_stats->add_task_stats();
  ptr_stats->set_name(name);
  ptr_stats->set_time_ms(time_diff_ms);
}

void EMPlanner::PopulateDecision(const ReferenceLineInfo& reference_line_info,
                                 Frame* frame) {
  auto* planning_pb = frame->MutableADCTrajectory();
  *planning_pb->mutable_decision() = Decider::MakeDecision(reference_line_info);
}

Status EMPlanner::Plan(const TrajectoryPoint& planning_start_point,
                       Frame* frame, ReferenceLineInfo* reference_line_info) {
  if (!frame) {
    AERROR << "Frame is empty in EMPlanner";
    return Status(ErrorCode::PLANNING_ERROR, "Frame is null");
  }

  ADEBUG << "planning start point:" << planning_start_point.DebugString();
  auto* heuristic_speed_data = reference_line_info->mutable_speed_data();
  auto speed_profile =
      GenerateInitSpeedProfile(planning_start_point, reference_line_info);
  if (speed_profile.empty()) {
    speed_profile = GenerateSpeedHotStart(planning_start_point);
    ADEBUG << "Using dummy hot start for speed vector";
  }
  heuristic_speed_data->set_speed_vector(speed_profile);

  auto ptr_debug = reference_line_info->mutable_debug();
  auto ptr_latency_stats = reference_line_info->mutable_latency_stats();
  auto ret = Status::OK();
  for (auto& optimizer : tasks_) {
    const double start_timestamp = Clock::NowInSecond();
    ret = optimizer->Execute(frame, reference_line_info);
    if (!ret.ok()) {
      AERROR << "Failed to run tasks[" << optimizer->Name()
             << "], Error message: " << ret.error_message();
      break;
    }
    const double end_timestamp = Clock::NowInSecond();
    const double time_diff_ms = (end_timestamp - start_timestamp) * 1000;

    ADEBUG << "after optimizer " << optimizer->Name() << ":"
           << reference_line_info->PathSpeedDebugString() << std::endl;
    ADEBUG << optimizer->Name() << " time spend: " << time_diff_ms << " ms.";

    if (FLAGS_enable_record_debug && ptr_debug != nullptr &&
        ptr_latency_stats != nullptr) {
      RecordDebugInfo(optimizer->Name(), time_diff_ms, ptr_latency_stats);
    }
  }
  DiscretizedTrajectory trajectory;
  if (!reference_line_info->CombinePathAndSpeedProfile(
          FLAGS_output_trajectory_time_resolution,
          planning_start_point.relative_time(), &trajectory)) {
    std::string msg("Fail to aggregate planning trajectory.");
    AERROR << msg;
    return Status(ErrorCode::PLANNING_ERROR, msg);
  }

  if (FLAGS_enable_trajectory_check) {
    ConstraintChecker::ValidTrajectory(trajectory);
  }

  reference_line_info->SetTrajectory(trajectory);
  PopulateDecision(*reference_line_info, frame);

  return ret;
}

std::vector<SpeedPoint> EMPlanner::GenerateInitSpeedProfile(
    const TrajectoryPoint& planning_init_point,
    const ReferenceLineInfo* reference_line_info) {
  std::vector<SpeedPoint> speed_profile;
  const auto* last_frame = FrameHistory::instance()->Latest();
  if (!last_frame) {
    AWARN << "last frame is empty";
    return speed_profile;
  }
  const ReferenceLineInfo* last_reference_line_info =
      last_frame->DriveReferenceLinfInfo();
  if (!last_reference_line_info) {
    ADEBUG << "last reference line info is empty";
    return speed_profile;
  }
  if (!reference_line_info->IsStartFrom(*last_reference_line_info)) {
    ADEBUG << "Current reference line is not started previous drived line";
    return speed_profile;
  }
  const auto& last_speed_vector =
      last_reference_line_info->speed_data().speed_vector();

  if (!last_speed_vector.empty()) {
    const auto& last_init_point = last_frame->PlanningStartPoint().path_point();
    Vec2d last_xy_point(last_init_point.x(), last_init_point.y());
    SLPoint last_sl_point;
    if (!last_reference_line_info->reference_line().XYToSL(last_xy_point,
                                                           &last_sl_point)) {
      AERROR << "Fail to transfer xy to sl when init speed profile";
    }

    Vec2d xy_point(planning_init_point.path_point().x(),
                   planning_init_point.path_point().y());
    SLPoint sl_point;
    if (!last_reference_line_info->reference_line().XYToSL(xy_point,
                                                           &last_sl_point)) {
      AERROR << "Fail to transfer xy to sl when init speed profile";
    }
    double s_diff = sl_point.s() - last_sl_point.s();
    double start_time = 0.0;
    double start_s = 0.0;
    bool is_updated_start = false;
    for (const auto& speed_point : last_speed_vector) {
      if (speed_point.s() < s_diff) {
        continue;
      }
      if (!is_updated_start) {
        start_time = speed_point.t();
        start_s = speed_point.s();
        is_updated_start = true;
      }
      SpeedPoint refined_speed_point;
      refined_speed_point.set_s(speed_point.s() - start_s);
      refined_speed_point.set_t(speed_point.t() - start_time);
      refined_speed_point.set_v(speed_point.v());
      refined_speed_point.set_a(speed_point.a());
      refined_speed_point.set_da(speed_point.da());
      speed_profile.push_back(std::move(refined_speed_point));
    }
  }
  return speed_profile;
}

// This is a dummy simple hot start, need refine later
std::vector<SpeedPoint> EMPlanner::GenerateSpeedHotStart(
    const TrajectoryPoint& planning_init_point) {
  std::vector<SpeedPoint> hot_start_speed_profile;
  double s = 0.0;
  double t = 0.0;
  double v = planning_init_point.v();
  while (t < FLAGS_trajectory_time_length) {
    SpeedPoint speed_point;
    speed_point.set_s(s);
    speed_point.set_t(t);
    speed_point.set_v(v);

    hot_start_speed_profile.push_back(std::move(speed_point));

    t += FLAGS_trajectory_time_resolution;
    s += v * FLAGS_trajectory_time_resolution;
  }
  return hot_start_speed_profile;
}

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


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

#include <charconv>

#include "cpp_utils/assert.hpp"

#include "date.hpp"
#include "config.hpp"
#include "expenses.hpp"
#include "earnings.hpp"

budget::date budget::local_day(){
    auto tt = time( NULL );
    auto timeval = localtime( &tt );

    return {
        static_cast<date_type>(timeval->tm_year + 1900),
        static_cast<date_type>(timeval->tm_mon + 1),
        static_cast<date_type>(timeval->tm_mday)};
}

budget::date budget::from_string(std::string_view str){
    if (str.size() != 10) {
        throw date_exception("Invalid size for from_string");
    }

    // Note: all these will be string views with zero memory-copies
    auto y_str = str.substr(0, 4);
    auto m_str = str.substr(5, 2);
    auto d_str = str.substr(8, 2);

    date_type y;
    date_type m;
    date_type d;

    if (auto [p, ec] = std::from_chars(y_str.data(), y_str.data() + y_str.size(), y); ec != std::errc() || p != y_str.data() + y_str.size()) {
        throw date_exception("Invalid year in from_string");
    }

    if (auto [p, ec] = std::from_chars(m_str.data(), m_str.data() + m_str.size(), m); ec != std::errc() || p != m_str.data() + m_str.size()) {
        throw date_exception("Invalid month in from_string");
    }

    if (auto [p, ec] = std::from_chars(d_str.data(), d_str.data() + d_str.size(), d); ec != std::errc() || p != d_str.data() + d_str.size()) {
        throw date_exception("Invalid day in from_string");
    }

    return {y, m, d};
}

std::string budget::date_to_string(budget::date date){
    return std::to_string(date.year())
        + "-" + (date.month() < 10 ? "0" : "") + std::to_string(date.month())
        + "-" + (date.day() < 10 ? "0" : "") + std::to_string(date.day());
}

unsigned short budget::start_month(budget::year year){
    budget::month m = 12;

    for(auto& expense : all_expenses()){
        if(expense.date.year() == year){
            m = std::min(expense.date.month(), m);
        }
    }

    for(auto& earning : all_earnings()){
        if(earning.date.year() == year){
            m = std::min(earning.date.month(), m);
        }
    }

    return m;
}

unsigned short budget::start_year(){
    auto today = budget::local_day();
    auto y = today.year();

    for(auto& expense : all_expenses()){
        if(expense.date != TEMPLATE_DATE){
            y = std::min(expense.date.year(), y);
        }
    }

    for(auto& earning : all_earnings()){
        if(earning.date != TEMPLATE_DATE){
            y = std::min(earning.date.year(), y);
        }
    }

    return y;
}

std::ostream& budget::operator<<(std::ostream& stream, const date& date){
    return stream << date.year() << "-" << date.month() << "-" << date.day();
}

std::ostream& budget::operator<<(std::ostream& stream, const month& month){
    return stream << month.as_short_string();
}
<commit_msg>Cleanup<commit_after>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <charconv>

#include "cpp_utils/assert.hpp"

#include "date.hpp"
#include "config.hpp"
#include "expenses.hpp"
#include "earnings.hpp"

budget::date budget::local_day(){
    auto tt = time( NULL );
    auto timeval = localtime( &tt );

    return {
        static_cast<date_type>(timeval->tm_year + 1900),
        static_cast<date_type>(timeval->tm_mon + 1),
        static_cast<date_type>(timeval->tm_mday)};
}

budget::date budget::from_string(std::string_view str){
    if (str.size() != 10) {
        throw date_exception("Invalid size for from_string");
    }

    date_type y;
    date_type m;
    date_type d;

    if (auto [p, ec] = std::from_chars(str.data(), str.data() + 4, y); ec != std::errc() || p != str.data() + 4) {
        throw date_exception("Invalid year in from_string");
    }

    if (auto [p, ec] = std::from_chars(str.data() + 5, str.data() + 7, m); ec != std::errc() || p != str.data() + 7) {
        throw date_exception("Invalid month in from_string");
    }

    if (auto [p, ec] = std::from_chars(str.data() + 8, str.data() + 10, d); ec != std::errc() || p != str.data() + 10) {
        throw date_exception("Invalid day in from_string");
    }

    return {y, m, d};
}

std::string budget::date_to_string(budget::date date){
    return std::to_string(date.year())
        + "-" + (date.month() < 10 ? "0" : "") + std::to_string(date.month())
        + "-" + (date.day() < 10 ? "0" : "") + std::to_string(date.day());
}

unsigned short budget::start_month(budget::year year){
    budget::month m = 12;

    for(auto& expense : all_expenses()){
        if(expense.date.year() == year){
            m = std::min(expense.date.month(), m);
        }
    }

    for(auto& earning : all_earnings()){
        if(earning.date.year() == year){
            m = std::min(earning.date.month(), m);
        }
    }

    return m;
}

unsigned short budget::start_year(){
    auto today = budget::local_day();
    auto y = today.year();

    for(auto& expense : all_expenses()){
        if(expense.date != TEMPLATE_DATE){
            y = std::min(expense.date.year(), y);
        }
    }

    for(auto& earning : all_earnings()){
        if(earning.date != TEMPLATE_DATE){
            y = std::min(earning.date.year(), y);
        }
    }

    return y;
}

std::ostream& budget::operator<<(std::ostream& stream, const date& date){
    return stream << date.year() << "-" << date.month() << "-" << date.day();
}

std::ostream& budget::operator<<(std::ostream& stream, const month& month){
    return stream << month.as_short_string();
}
<|endoftext|>