text:
// -------------------------------------------------------------------
// $ProjectName     : DiffusionRunner_D64
// $FileName        : DiffusionRunner_D64.cpp$
// $Programmer      : Tran Quoc Hoan$
// -------------------------------------------------------------------

#include "stdafx.h"
#include "DiffusionRunner_D64.h"
#include "NpMatUtils.h"
#include "../TopoUtils_D64/StringUtils.h"
#include "../RipserLib_D64/RipserComputeUtils.h"

#include <boost/filesystem.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/foreach.hpp>
#include "boost/program_options.hpp"
#include <fstream>

#include <ppl.h>
#include <ppltasks.h>

using namespace NRipserComputeUtils;
using namespace NNpMatUtils;

std::vector<std::wstring> ReadMultiLinesFromFile(const std::wstring& filepath) {
	std::vector<std::wstring> rstr;
	std::ifstream read_op;
	read_op.open(filepath);
	if (!read_op.good()) {
		return rstr;
	}
	else {
		size_t index = 0;
		while (read_op.good()) {
			std::string line;
			std::getline(read_op, line);
			if (line.empty() == false)
				rstr.push_back(NStringUtil::_s2w(line));
		}
	}
	read_op.close();
	return rstr;
}

bool WriteDiffusionBarcodesToFile(std::vector<std::pair<size_t, RipsComputePrmPtr>> diffusion_barcodes,
	std::wstring out_dir, size_t maxdim, std::wstring basename) {
	namespace io = boost::iostreams;
	// Make output directory if not exist
	boost::filesystem::path outpath(out_dir);
	if (!boost::filesystem::is_directory(outpath)) {
		boost::filesystem::create_directory(outpath);
	}
	for (size_t dim = 0; dim <= maxdim; ++dim) {
		std::wstring outfile = out_dir + L"/diffusion_barcode_" + basename + L"_dim_" + std::to_wstring(dim) + L".txt";
		io::stream_buffer<io::file_sink> buf(NStringUtil::_w2s(outfile));
		std::ostream out(&buf);

		for (auto dbar : diffusion_barcodes) {
			size_t tau = dbar.first;
			RipsComputePrmPtr prm = dbar.second;
			if (!prm) continue;
			OutputPrmPtr output_prm = prm->output_prm;
			if (!output_prm) continue;
			auto bvec = output_prm->Barcodes();
			if (bvec.size() <= dim) continue;
			for (auto bar : bvec[dim]->barcodes()) {
				out << bar->birth << " " << bar->death << " " << tau << " " << std::endl;
			}
		}
        std::cout << "Saved diffusion barcodes to file: " << NStringUtil::_w2s(outfile) << std::endl;
	}
	return true;
}

int main(int argc, char** argv)
{
	using namespace boost::program_options;
	namespace fs = boost::filesystem;
	int nRetCode = 0;
	options_description description("Persistence runner for diffusion distance");
	description.add_options()
		("debug,x", value<bool>()->default_value(false), "Print Debug Information")
        ("norm", value<size_t>()->default_value(0), "Normalize the distance before calculating")
        ("nthreads", value<int>()->default_value(-1), "Number of threads to use, -1: use all as possible")
		("modulus,m", value<coefficient_t>()->default_value(2), "Compute homology with coefficients in the prime field Z/<p>Z")
		("maxdim,d", value<index_t>()->default_value(0), "Compute persistent homology up to dimension <k>")
		("thres", value<value_t>()->default_value(std::numeric_limits<value_t>::max()), "Compute Rips complexes up to diameter <t>")
		("outdir,o", value<std::string>()->default_value("output"), "Output directory")
		("input,i", value<std::string>()->default_value("network"), "Input folder")
		("taumax,t", value<size_t>()->default_value(0), "Compute with diffusion time up to taumax")
		("nbegin,b", value<size_t>()->default_value(0), "Begin index")
		("nend,e", value<size_t>()->default_value(0), "End index")
        ("skiptime,s", value<size_t>()->default_value(0), "Stop and continue for slow compute of Rips")
		("help,H", "Help: Usage DiffusionRunner_D64 [options]")
		("version,v", "v1.0")
		;
	variables_map vm;
	store(parse_command_line(argc, argv, description), vm);
	notify(vm);

	if (vm.count("help")) {
		std::cout << description << std::endl;
		return nRetCode;
	}
    size_t norm = vm["norm"].as<size_t>();
	size_t taumax = vm["taumax"].as<size_t>();
	size_t nbegin = vm["nbegin"].as<size_t>();
	size_t nend   = vm["nend"].as<size_t>();
    size_t skiptime = vm["skiptime"].as<size_t>();
    if (skiptime > 0) {
        std::cout << "Enable skiptime: " << skiptime << std::endl;
    }

    auto nthreads = vm["nthreads"].as<int>();
    if (nthreads <= 0) {
        nthreads = std::thread::hardware_concurrency();
    }
    std::cout << "Number of threads (= " << nthreads << ")" << std::endl;

    auto input_str = vm["input"].as<std::string>();
    std::cout << "Input: " << input_str.c_str() << std::endl;

	RipsComputePrmPtr prm(new RipsComputePrm());
    prm->skiptime = skiptime;
	RipsPrmPtr rip_prm = prm->rip_prm;
	InputPrmPtr input_prm = prm->input_prm;
	OutputPrmPtr output_prm = prm->output_prm;

	auto maxdim = vm["maxdim"].as<index_t>();
	auto out_dir = NStringUtil::_s2w(vm["outdir"].as<std::string>());
    std::cout << "Output: " << NStringUtil::_w2s(out_dir) << std::endl;

	rip_prm->modulus = vm["modulus"].as<coefficient_t>();
    if (false == NRipserUtils::isPrime(rip_prm->modulus)) {
        std::cout << "Modulus = (" << rip_prm->modulus << ") must be a prime number" << std::endl;
        return false;
    }
	rip_prm->dim_max = maxdim;
	rip_prm->diameter_max = vm["thres"].as<value_t>();

	output_prm->write_mode = INOUT_MODE::INNER_MODE;
	output_prm->out_dir = out_dir;
	input_prm->read_mode = INOUT_MODE::INNER_MODE;
	input_prm->format = LOWER_DISTANCE_MATRIX;

	// read all input distance matrices
	std::vector<fs::path> input_files;
	fs::path input_path(input_str);
	std::vector<std::wstring> rstr;

	if (fs::is_directory(input_path)) {
		// loop for all files in folder
		fs::directory_iterator it(input_path), eod;
		BOOST_FOREACH(fs::path const &p, std::make_pair(it, eod)) {
			if (fs::is_regular_file(p) && (fs::extension(p) == ".npy")) {
				input_files.push_back(p);
			}
		}
	}
	else if (fs::is_regular_file(input_path) && (fs::extension(input_path) == ".npy")) {
		input_files.push_back(input_path);
	}
	else {
        std::cout << "Error: no input files" << std::endl;
		return nRetCode;
	}

    size_t n_end_files = input_files.size();
    if (nend > 0) n_end_files = std::min(n_end_files, nend);
    std::cout << "Number of input files to process: " << n_end_files << std::endl;

	for (size_t i = nbegin; i < n_end_files; ++i) {
		auto p = input_files[i];
		NpyArray narr;
        const std::string pathname = NStringUtil::_w2s(p.c_str());
        //std::cout << "Process file: " << pathname << std::endl;
        if (false == NNpMatUtils::NpyLoad(pathname, narr)) {
            std::cout << "Error: loading npy file" << std::endl;
            return false;
        }

		const size_t num_taus = (size_t)narr.shape[0];
		const size_t Nr = (size_t)narr.shape[1];
		const size_t Nc = (size_t)narr.shape[2];
		const size_t N = Nr * Nc;
        // std::cout << "Size of loaded npy file: " << num_taus << "," << Nr << "," << Nc << std::endl;

		FType* dat = reinterpret_cast<FType*>(narr.data);
		std::vector<std::pair<size_t, RipsComputePrmPtr>> diffusion_barcodes;
		std::vector<RipsComputePrmPtr> prm_vec;

        size_t ntaus_to_process = num_taus;
        if (taumax > 0) ntaus_to_process = std::min(num_taus, taumax);

		for (size_t n = 0; n < ntaus_to_process; ++n) {
			RipsComputePrmPtr prm_f(new RipsComputePrm());
			prm_f->ParamCopy(prm);
            // Compute the maximum distance
            FType maxdist = dat[n*N];
            for (size_t i = 0; i < Nr; ++i) {
                for (size_t j = 0; j < i; ++j) {
                    const FType tmp = dat[n*N + i*Nc + j];
                    if (tmp > maxdist) maxdist = tmp;
                }
            }
            if (maxdist <= 0) continue;
			// Make distance
			std::vector<value_t> distvec;
			for (size_t i = 0; i < Nr; ++i)
                for (size_t j = 0; j < i; ++j) {
                    FType tmp = dat[n*N + i*Nc + j];
                    if (norm > 0) tmp = tmp / maxdist;
                    distvec.push_back(tmp);
                }
			prm_f->input_prm->distances = distvec;
			prm_vec.push_back(prm_f);
			diffusion_barcodes.push_back(std::make_pair(n, prm_f));
		}
		if (!prm_vec.empty()) {
			ComputeRipPHMultiFiles(nthreads, prm_vec);
		}
		std::wstring basename = p.stem().c_str();
		WriteDiffusionBarcodesToFile(diffusion_barcodes, out_dir, maxdim, basename);
	}
	return nRetCode;
}

max_stars_repo_name: OminiaVincit/scale-variant-topo

max_issues_repo_name: OminiaVincit/scale-variant-topo

max_forks_repo_name: OminiaVincit/scale-variant-topo


text:
// -*-c++-*-

/***************************************************************************
                                logger.cpp
                         Classes for game logging
                             -------------------
    begin                : 2008-02-15
    copyright            : (C) 2008 by The RoboCup Soccer Simulator
                           Maintenance Group.
    email                : sserver-admin@lists.sourceforge.net
***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU LGPL as published by the Free Software  *
 *   Foundation; either version 3 of the License, or (at your option) any  *
 *   later version.                                                        *
 *                                                                         *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "logger.h"

#include "player.h"
#include "clangmsg.h"
#include "coach.h"
#include "stadium.h"
#include "heteroplayer.h"
#include "monitor.h"
#include "playerparam.h"
#include "serverparam.h"
#include "team.h"
#include "xpmholder.h"

#include "dispsender.h"
#include "initsenderlogger.h"
#include "serializermonitor.h"

#include "serializercommonstdv8.h"

#include <boost/lexical_cast.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/convenience.hpp>

#include <sstream>

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
// #ifdef HAVE_NETINET_IN_H
// #include <netinet/in.h>
// #endif
// #ifdef HAVE_WINSOCK2_H
// #include <winsock2.h>
// #endif

#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION > 2

#define BOOST_FS_ABSOLUTE absolute
#define BOOST_FS_FILE_STRING string
#define BOOST_FS_DIRECTORY_STRING string
#define BOOST_FS_PARENT_PATH parent_path

#else

#define BOOST_FS_ABSOLUTE complete

#  ifdef BOOST_FILESYSTEM_NO_DEPRECATED
#    define BOOST_FS_FILE_STRING file_string
#    define BOOST_FS_DIRECTORY_STRING directory_string
#    define BOOST_FS_PARENT_PATH parent_path
#  else
#    define BOOST_FS_FILE_STRING native_file_string
#    define BOOST_FS_DIRECTORY_STRING native_directory_string
#    define BOOST_FS_PARENT_PATH branch_path
#  endif

#endif

const std::string Logger::DEF_TEXT_NAME = "incomplete";
const std::string Logger::DEF_TEXT_SUFFIX = ".rcl";
const std::string Logger::DEF_GAME_NAME = "incomplete";
const std::string Logger::DEF_GAME_SUFFIX = ".rcg";
const std::string Logger::DEF_KAWAY_NAME = "incomplete";
const std::string Logger::DEF_KAWAY_SUFFIX = ".kwy";

Logger::Logger( Stadium & stadium )
    : M_init_observer( new rcss::InitObserverLogger )
    , M_observer( new rcss::ObserverLogger )
    , M_stadium( stadium )
    , M_game_log( static_cast< std::ostream * >( 0 ) )
    , M_text_log( static_cast< std::ostream * >( 0 ) )
    , M_playmode( PM_Null )
    , M_team_l_score( 0 )
    , M_team_r_score( 0 )
    , M_team_l_pen_taken( 0 )
    , M_team_r_pen_taken( 0 )
{

}

Logger::~Logger()
{
    this->close();
}

bool
Logger::setSenders()
{
    if ( ! isGameLogOpen() )
    {
        return true;
    }

    int log_version = ServerParam::instance().gameLogVersion();
    int monitor_version = log_version - 1;
    if ( log_version == REC_OLD_VERSION )
    {
        monitor_version = 1;
    }

    rcss::SerializerMonitor::Creator ser_cre;
    if ( ! rcss::SerializerMonitor::factory().getCreator( ser_cre, monitor_version ) )
    {
        std::cerr << "No SerializerMonitor::Creator v" << monitor_version << std::endl;
        return false;
    }

    const rcss::SerializerMonitor::Ptr ser = ser_cre();
    if ( ! ser )
    {
        std::cerr << "No SerializerMonitor v" << monitor_version << std::endl;
        return false;
    }

    //
    // init sender
    //
    {
        rcss::InitSenderLogger::Params init_params( *M_game_log,
                                                    *this,
                                                    ser,
                                                    M_stadium );
        rcss::InitSenderLogger::Creator init_cre;
        if ( ! rcss::InitSenderLogger::factory().getCreator( init_cre, log_version ) )
        {
            std::cerr << "No InitSenderLogger::Creator v" << log_version << std::endl;
            return false;
        }
        M_init_observer->setInitSender( init_cre( init_params ) );
    }

    // disp sender
    {
        rcss::DispSenderLogger::Params disp_params( *M_game_log,
                                                    *this,
                                                    ser,
                                                    M_stadium );
        rcss::DispSenderLogger::Creator disp_cre;
        if ( ! rcss::DispSenderLogger::factory().getCreator( disp_cre, log_version ) )
        {
            std::cerr << "No DispSenderLogger::Creator v" << log_version << std::endl;
            return false;
        }
        M_observer->setDispSender( disp_cre( disp_params ) );
    }

    return true;
}

bool
Logger::open()
{
    if ( ServerParam::instance().gameLogging() )
    {
        if ( ! openGameLog() )
        {
            return false;
        }
    }

    if ( ServerParam::instance().textLogging() )
    {
        if ( ! openTextLog() )
        {
            return false;
        }
    }

    if ( ServerParam::instance().keepAwayMode()
         && ServerParam::instance().kawayLogging() )
    {
        if ( ! openKawayLog() )
        {
            return false;
        }
    }

    return true;
}

void
Logger::close()
{
    renameLogs();

    closeGameLog();
    closeTextLog();
    closeKawayLog();
}

bool
Logger::openGameLog()
{
    // create the log directory & file path string
    try
    {
        boost::filesystem::path game_log( ServerParam::instance().gameLogDir()
#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2
#  ifndef BOOST_FILESYSTEM_NO_DEPRECATED
                                          , &boost::filesystem::native
#  endif
#endif
                                          );
        if ( ! boost::filesystem::exists( game_log )
             && ! boost::filesystem::create_directories( game_log ) )
        {
            std::cerr << __FILE__ << ": " << __LINE__
                      << ": can't create game log directory '"
                      << game_log.BOOST_FS_DIRECTORY_STRING() << "'" << std::endl;
            return false;
        }

        if ( ServerParam::instance().gameLogFixed() )
        {
            game_log /= ServerParam::instance().gameLogFixedName() + Logger::DEF_GAME_SUFFIX;
        }
        else
        {
            game_log /= Logger::DEF_GAME_NAME + Logger::DEF_GAME_SUFFIX;
        }

        M_game_log_name = game_log.BOOST_FS_FILE_STRING();
    }
    catch ( std::exception & e )
    {
        std::cerr << __FILE__ << ": " << __LINE__
                  << " Exception caught! " << e.what()
                  << "\nCould not create game log directory '"
                  << ServerParam::instance().gameLogDir()
                  << "'" << std::endl;
        return false;
    }

    // open the output file stream
#ifndef HAVE_LIBZ
    if ( ServerParam::instance().gameLogCompression() > 0 )
    {
        std::cerr << "No zlib. Ignored game log compression." << std::endl;
    }
#endif

#ifdef HAVE_LIBZ
    if ( ServerParam::instance().gameLogCompression() > 0 )
    {
        M_game_log_name += ".gz";
        rcss::gz::gzofstream * f
            = new rcss::gz::gzofstream( M_game_log_name.c_str(),
                                        ServerParam::instance().gameLogCompression() );
        M_game_log = f;
    }
    else
#endif
    {
        std::ofstream * f
            = new std::ofstream( M_game_log_name.c_str(),
                                 ( std::ofstream::binary
                                   | std::ofstream::out
                                   | std::ofstream::trunc ) );
        M_game_log = f;
    }

    if ( ! isGameLogOpen() )
    {
        std::cerr << __FILE__ << ": " << __LINE__
                  << ": can't open the game log file " << M_game_log_name << std::endl;
        return false;
    }

    // write header and configration parameters
    if ( ! setSenders() )
    {
        std::cerr << __FILE__ << ": " << __LINE__
                  << ": can't set senders " << M_game_log_name << std::endl;
        return false;
    }

    M_init_observer->sendHeader();
    M_init_observer->sendServerParams();
    M_init_observer->sendPlayerParams();
    M_init_observer->sendPlayerTypes();
    M_game_log->flush();

    return true;
}

bool
Logger::openTextLog()
{
    // create the log directory & file path string
    try
    {
        boost::filesystem::path text_log( ServerParam::instance().textLogDir()
#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2
#  ifndef BOOST_FILESYSTEM_NO_DEPRECATED
                                          , &boost::filesystem::native
#  endif
#endif
                                          );
        if ( ! boost::filesystem::exists( text_log )
             && ! boost::filesystem::create_directories( text_log ) )
        {
            std::cerr << __FILE__ << ": " << __LINE__
                      << ": can't create text log directory '"
                      << text_log.BOOST_FS_DIRECTORY_STRING() << "'" << std::endl;
            return false;
        }

        if ( ServerParam::instance().textLogFixed() )
        {
            text_log /= ServerParam::instance().textLogFixedName() + Logger::DEF_TEXT_SUFFIX;
        }
        else
        {
            text_log /= Logger::DEF_TEXT_NAME + Logger::DEF_TEXT_SUFFIX;
        }

        M_text_log_name = text_log.BOOST_FS_FILE_STRING();
    }
    catch ( std::exception & e )
    {
        std::cerr << __FILE__ << ": " << __LINE__
                  << " Exception caught! " << e.what()
                  << "\nCould not create text log directory '"
                  << ServerParam::instance().textLogDir()
                  << "'" << std::endl;
        return false;
    }

    // open the output file stream
#ifndef HAVE_LIBZ
    if ( ServerParam::instance().textLogCompression() > 0 )
    {
        std::cerr << "No zlib. Ignored text log compression." << std::endl;
    }
#endif

#ifdef HAVE_LIBZ
    if ( ServerParam::instance().textLogCompression() > 0 )
    {
        M_text_log_name += std::string ( ".gz" );
        rcss::gz::gzofstream * f
            = new rcss::gz::gzofstream( M_text_log_name.c_str(),
                                        ServerParam::instance().textLogCompression() );
        M_text_log = f;
    }
    else
#endif
    {
        std::ofstream * f = new std::ofstream( M_text_log_name.c_str() );
        M_text_log = f;
    }

    if ( ! isTextLogOpen() )
    {
        std::cerr << __FILE__ << ": " << __LINE__
                  << ": can't open the text log file '" << M_text_log_name
                  << "'" << std::endl;
        return false;
    }

    return true;
}

bool
Logger::openKawayLog()
{
    // create the log directory & file path string
    try
    {
        boost::filesystem::path kaway_log( ServerParam::instance().kawayLogDir()
#if defined(BOOST_FILESYSTEM_VERSION) && BOOST_FILESYSTEM_VERSION == 2
#  ifndef BOOST_FILESYSTEM_NO_DEPRECATED
                                           , &boost::filesystem::native
#  endif
#endif
                                           );
        if ( ! boost::filesystem::exists( kaway_log )
             && ! boost::filesystem::create_directories( kaway_log ) )
        {
            std::cerr << __FILE__ << ": " << __LINE__
                      << ": can't create keepaway log directory '"
                      << kaway_log.BOOST_FS_DIRECTORY_STRING() << "'" << std::endl;
            return false;
        }

        if ( ServerParam::instance().kawayLogFixed() )
        {
            kaway_log /= ServerParam::instance().kawayLogFixedName() + Logger::DEF_KAWAY_SUFFIX;
        }
        else
        {
            kaway_log /= Logger::DEF_KAWAY_NAME + Logger::DEF_KAWAY_SUFFIX;
        }

        M_kaway_log_name = kaway_log.BOOST_FS_FILE_STRING();
    }
    catch ( std::exception & e )
    {
        std::cerr << __FILE__ << ": " << __LINE__
                  << " Exception caught! " << e.what()
                  << "\nCould not create keepaway log directory '"
                  << ServerParam::instance().kawayLogDir()
                  << "'" << std::endl;
        return false;
    }

    // open the output file stream
    M_kaway_log.open( M_kaway_log_name.c_str() );

    if ( ! M_kaway_log.is_open() )
    {
        std::cerr << __FILE__ << ": " << __LINE__
                  << ": can't open keepaway_log_file " << M_kaway_log_name
                  << std::endl;
        return false;
    }

    return true;
}

void
Logger::closeGameLog()
{
    if ( M_game_log )
    {
        M_game_log->flush();
        delete M_game_log;
        M_game_log =  static_cast< std::ostream * >( 0 );
    }
}

void
Logger::closeTextLog()
{
    if ( M_text_log )
    {
        M_text_log->flush();
        delete M_text_log;
        M_text_log =  static_cast< std::ostream * >( 0 );
    }
}

void
Logger::closeKawayLog()
{
    if ( M_kaway_log.is_open() )
    {
        M_kaway_log.flush();
        M_kaway_log.close();
    }
}

void
Logger::renameLogs()
{
    if ( ! isGameLogOpen()
         && ! isTextLogOpen()
         && ! M_kaway_log.is_open() )
    {
        return;
    }

    // add penalty to logfile when penalties are score or was draw and one team won
    bool bAddPenaltyScore = ( M_stadium.teamRight().point() == M_stadium.teamLeft().point()
                              && M_stadium.teamLeft().penaltyTaken() > 0
                              && M_stadium.teamRight().penaltyTaken() > 0 );

    char time_str[32];
    std::strftime( time_str, 32,
                   ServerParam::instance().logDateFormat().c_str(),
                   &( M_stadium.realTime() ) );

    std::string team_name_score( "" );

    if ( M_stadium.teamLeft().enabled() )
    {
        team_name_score += M_stadium.teamLeft().name();
        team_name_score += "_";
        if ( ! M_stadium.teamLeft().olcoach()->name().empty() )
        {
            team_name_score += M_stadium.teamLeft().olcoach()->name();
            team_name_score += "_";
        }
        team_name_score += boost::lexical_cast< std::string >( M_stadium.teamLeft().point() );
        if ( bAddPenaltyScore )
        {
            team_name_score += "_";
            team_name_score += boost::lexical_cast< std::string >( M_stadium.teamLeft().penaltyPoint() );
            team_name_score += ( M_stadium.teamLeft().penaltyWon() ? "w" : "" );
        }
    }
    else
    {
        team_name_score += "null";
    }

    team_name_score += "-vs-";
    if ( M_stadium.teamRight().enabled() )
    {
        team_name_score += M_stadium.teamRight().name();
        team_name_score += "_";
        if ( ! M_stadium.teamRight().olcoach()->name().empty() )
        {
            team_name_score += M_stadium.teamRight().olcoach()->name();
            team_name_score += "_";
        }
        team_name_score += boost::lexical_cast< std::string >( M_stadium.teamRight().point() );
        if ( bAddPenaltyScore )
        {
            team_name_score += "_";
            team_name_score += boost::lexical_cast< std::string >( M_stadium.teamRight().penaltyPoint() );
            team_name_score += ( M_stadium.teamRight().penaltyWon() ? "w" : "" );
        }
    }
    else
    {
        team_name_score += "null";
    }

    //
    // write result
    //
    if ( isGameLogOpen() )
    {
        char time_stamp[32];
        std::strftime( time_stamp, 32,
                       "%Y%m%d%H%M",
                       &( M_stadium.realTime() ) );
        char msg[256];
        snprintf( msg, 256, "(result %s %s)", time_stamp, team_name_score.c_str() );
        writeMsgToGameLog( MSG_BOARD, msg, true );
    }

    //
    // rename text log
    //
    if ( isTextLogOpen()
         && ! ServerParam::instance().textLogFixed() )
    {
        std::string newname = ServerParam::instance().textLogDir();
        if ( *newname.rbegin() != '/' )
        {
            newname += '/';
        }
        if ( ServerParam::instance().textLogDated() )
        {
            newname += time_str;
        }
        newname += team_name_score;
        newname += Logger::DEF_TEXT_SUFFIX;
        if ( ServerParam::instance().textLogCompression() > 0 )
        {
            newname += ".gz";
        }

        closeTextLog();

        if ( std::rename( M_text_log_name.c_str(),
                          newname.c_str() ) )
        {
            std::cerr << __FILE__ << ": " << __LINE__
                      << ": error renaming " << M_text_log_name << std::endl;
        }
        M_text_log_name = newname;
    }

    //
    // rename game log
    //
    if ( isGameLogOpen()
         && ! ServerParam::instance().gameLogFixed() )
    {
        std::string newname = ServerParam::instance().gameLogDir();
        if ( *newname.rbegin() != '/' )
        {
            newname += '/';
        }
        if ( ServerParam::instance().gameLogDated() )
        {
            newname += time_str;
        }
        newname += team_name_score;
        newname += Logger::DEF_GAME_SUFFIX;
        if ( ServerParam::instance().gameLogCompression() > 0 )
        {
            newname += ".gz";
        }

        closeGameLog();

        if ( std::rename( M_game_log_name.c_str(),
                          newname.c_str() ) )
        {
            std::cerr << __FILE__ << ": " << __LINE__
                      << ": error renaming " << M_game_log_name << std::endl;
        }
        M_game_log_name = newname;
    }

    //
    // rename keepaway log
    //
    if ( M_kaway_log.is_open()
         && ! ServerParam::instance().kawayLogFixed() )
    {
        std::string newname = ServerParam::instance().kawayLogDir();
        if ( *newname.rbegin() != '/' )
        {
            newname += '/';
        }
        if ( ServerParam::instance().kawayLogDated() )
        {
            newname += time_str;
        }
        newname += team_name_score;
        newname += Logger::DEF_KAWAY_SUFFIX;

        closeKawayLog();

        if( std::rename( M_kaway_log_name.c_str(),
                         newname.c_str() ) )
        {
            std::cerr << __FILE__ << ": " << __LINE__
                      << ": error renaming " << M_kaway_log_name << std::endl;
        }
    }

}

void
Logger::writeToGameLog( const char * str,
                        const std::streamsize n )
{
    if ( M_game_log )
    {
        M_game_log->write( str, n );
    }
}

void
Logger::writeMsgToGameLog( const BoardType board_type,
                           const char * msg,
                           const bool force )
{
    if ( ! isGameLogOpen() )
    {
        return;
    }

    if ( force
         || ServerParam::instance().recordMessages()
         || ServerParam::instance().gameLogVersion() == REC_OLD_VERSION )
    {
        M_observer->sendMsg( board_type, msg );
    }

//     if ( ServerParam::instance().gameLogVersion() >= REC_VERSION_4 )
//     {
//         if ( force
//              || ServerParam::instance().recordMessages() )
//         {
//             std::string str( msg );
//             std::replace( str.begin(), str.end(), '\n', ' ' );

//             *M_game_log << "(msg " << M_stadium.time()
//                         << ' ' << board_type << " \"" << str << "\")\n";
//         }
//     }
//     else if ( ServerParam::instance().gameLogVersion() != REC_OLD_VERSION )
//     {
//         if ( force
//              || ServerParam::instance().recordMessages() )
//         {
//             Int16 mode = htons( MSG_MODE );
//             writeToGameLog( reinterpret_cast< const char * >( &mode ),
//                             sizeof( mode ) );
//             Int16 board = htons( board_type );
//             writeToGameLog( reinterpret_cast< const char * >( &board ),
//                             sizeof( board ) );
//             // calculate the string length and write it

//             const Int16 max_len = std::min( Int16( std::strlen( msg ) ), Int16( 2048 ) );
//             Int16 len = 1;
//             while ( (msg[len-1] != '\0') && (len < max_len) )
//             {
//                 ++len;
//             }
//             /* pfr 1/7/00 Need to put length in network byte order */
//             Int16 nlen = htons( len );
//             writeToGameLog( reinterpret_cast< const char* >( &nlen ),
//                             sizeof( nlen ) );
//             // write the message
//             writeToGameLog( msg, len );
//         }
//     }
//     else
//     {
//         dispinfo_t disp;
//         disp.mode = htons( MSG_MODE );
//         disp.body.msg.board = htons( board_type );
//         std::strncpy( disp.body.msg.message,
//                       msg,
//                       std::min( sizeof( disp.body.msg.message ),
//                                 std::strlen( msg ) ) );
//         writeToGameLog( reinterpret_cast< const char * >( &disp ),
//                         sizeof( dispinfo_t ) );
//     }
}

void
Logger::writeGameLog()
{
    /* TH - 2-NOV-2000 */
    static bool wrote_final_cycle = false;

    if ( ! isGameLogOpen() )
    {
        return;
    }

    if ( M_stadium.playmode() != PM_BeforeKickOff
         && M_stadium.playmode() != PM_TimeOver )
    {
        writeGameLogImpl();
//         switch ( ServerParam::instance().gameLogVersion() ) {
//         case REC_VERSION_4:
//             writeGameLogV4();
//             break;
//         case REC_VERSION_3:
//             writeGameLogV3();
//             break;
//         case REC_VERSION_2:
//             writeGameLogV2();
//             break;
//         case REC_OLD_VERSION:
//             writeGameLogV1();
//             break;
//         default:
//             break;
//         }
    }
    else if ( M_stadium.playmode() == PM_TimeOver
              && ! wrote_final_cycle )
    {
        writeGameLogImpl();
//         switch ( ServerParam::instance().gameLogVersion() ) {
//         case REC_VERSION_4:
//             writeGameLogV4();
//             break;
//         case REC_VERSION_3:
//             writeGameLogV3();
//             break;
//         case REC_VERSION_2:
//             writeGameLogV2();
//             break;
//         case REC_OLD_VERSION:
//             writeGameLogV1();
//             break;
//         default:
//             break;
//         }
        wrote_final_cycle = true;
    }
}

void
Logger::writeGameLogImpl()
{
    static PlayMode pm = PM_Null;
    static std::string team_l_name, team_r_name;
    static int team_l_score = 0, team_r_score = 0;
    static int team_l_pen_taken = 0, team_r_pen_taken = 0;

   // if playmode has changed wirte playmode
    if ( pm != M_stadium.playmode() )
    {
        pm = M_stadium.playmode();
        M_init_observer->sendPlayMode();
    }

    // if teams or score has changed, write teams and score
    if ( team_l_score != M_stadium.teamLeft().point()
         || team_r_score != M_stadium.teamRight().point()
         || team_l_pen_taken != M_stadium.teamLeft().penaltyTaken()
         || team_r_pen_taken != M_stadium.teamRight().penaltyTaken()
         || M_stadium.teamLeft().name() != team_l_name
         || M_stadium.teamRight().name() != team_r_name
         )
    {
        team_l_name = M_stadium.teamLeft().name();
        team_r_name = M_stadium.teamRight().name();
        team_l_score = M_stadium.teamLeft().point();
        team_r_score = M_stadium.teamRight().point();
        team_l_pen_taken = M_stadium.teamLeft().penaltyTaken();
        team_r_pen_taken = M_stadium.teamRight().penaltyTaken();

        M_init_observer->sendTeam();
    }

    M_observer->sendShow();
}

#if 0
// This method has no longer be used.
void
Logger::writeGameLogV1()
{
    dispinfo_t disp;

    disp.mode = htons( SHOW_MODE );

    disp.body.show.time = htons( M_stadium.time() );

    disp.body.show.pmode = static_cast< char >( M_stadium.playmode() );

    disp.body.show.pos[0].x = htons( (Int16)rint( ( M_stadium.ball().pos().x * SHOWINFO_SCALE ) ) );
    disp.body.show.pos[0].y = htons( (Int16)rint( ( M_stadium.ball().pos().y * SHOWINFO_SCALE ) ) );

    const Stadium::PlayerCont & players = M_stadium.players();
    for ( int i = 0; i < MAX_PLAYER * 2; ++i )
    {
        disp.body.show.pos[i+1].enable = htons( players[i]->state() );
        disp.body.show.pos[i+1].x = htons( (Int16)rint( players[i]->pos().x * SHOWINFO_SCALE ) );
        disp.body.show.pos[i+1].y = htons( (Int16)rint( players[i]->pos().y * SHOWINFO_SCALE ) );
        disp.body.show.pos[i+1].angle = htons( (Int16)Rad2IDegRound( players[i]->angleBodyCommitted() ) );
        disp.body.show.pos[i+1].side = htons( players[i]->side() );
        disp.body.show.pos[i+1].unum = htons( players[i]->unum() );
    }

    if ( ! M_stadium.teamLeft().name().empty() )
    {
        std::strncpy( disp.body.show.team[0].name,
                      M_stadium.teamLeft().name().c_str(),
                      std::min( M_stadium.teamLeft().name().length() + 1, size_t( 16 ) ) );
        disp.body.show.team[0].score = htons( M_stadium.teamLeft().point() );
    }
    else
    {
        std::memset( &disp.body.show.team[0].name,
                     0,
                     sizeof( disp.body.show.team[0].name ) );
    }

    if ( ! M_stadium.teamRight().name().empty() )
    {
        std::strncpy( disp.body.show.team[1].name,
                      M_stadium.teamRight().name().c_str(),
                      std::min( M_stadium.teamRight().name().length() + 1, size_t( 16 ) ) );
        disp.body.show.team[1].score = htons( M_stadium.teamRight().point() );
    }
    else
    {
        std::memset( &disp.body.show.team[1].name,
                     0,
                     sizeof( disp.body.show.team[1].name ) );
    }

    writeToGameLog( reinterpret_cast< const char * >( &disp ),
                    sizeof( dispinfo_t ) );
}

// This method has no longer be used.
void
Logger::writeGameLogV2()
{
    Int16 mode = htons( SHOW_MODE );

    showinfo_t show;

    show.time = htons( M_stadium.time() );

    show.pmode = static_cast< char >( M_stadium.playmode() );

    show.pos[0].x = htons( (Int16)rint( ( M_stadium.ball().pos().x * SHOWINFO_SCALE ) ) );
    show.pos[0].y = htons( (Int16)rint( ( M_stadium.ball().pos().y * SHOWINFO_SCALE ) ) );

    const Stadium::PlayerCont & players = M_stadium.players();
    for ( int i = 0; i < MAX_PLAYER * 2; ++i )
    {
        show.pos[i+1].enable = htons( players[i]->state() );
        show.pos[i+1].x = htons( (Int16)rint( players[i]->pos().x * SHOWINFO_SCALE ) );
        show.pos[i+1].y = htons( (Int16)rint( players[i]->pos().y * SHOWINFO_SCALE ) );
        show.pos[i+1].angle = htons( (Int16)Rad2IDegRound( players[i]->angleBodyCommitted() ) );
        show.pos[i+1].side = htons( players[i]->side() );
        show.pos[i+1].unum = htons( players[i]->unum() );
    }

    if ( ! M_stadium.teamLeft().name().empty() )
    {
        std::strncpy( show.team[0].name,
                      M_stadium.teamLeft().name().c_str(),
                      std::min( M_stadium.teamLeft().name().length() + 1, size_t( 16 ) ) );
        show.team[0].score = htons( M_stadium.teamLeft().point() );
    }
    else
    {
        std::memset( &show.team[0].name,
                     0,
                     sizeof( show.team[0].name ) );
        show.team[0].score = htons( 0 );
    }

    if ( ! M_stadium.teamRight().name().empty() )
    {
        std::strncpy( show.team[1].name,
                      M_stadium.teamRight().name().c_str(),
                      std::min( M_stadium.teamRight().name().length() + 1, size_t( 16 ) ) );
        show.team[1].score = htons( M_stadium.teamRight().point() );
    }
    else
    {
        std::memset( &show.team[1].name,
                     0,
                     sizeof( show.team[1].name ) );
        show.team[1].score = htons( 0 );
    }

    // write a show struct
    writeToGameLog( reinterpret_cast< const char * >( &mode ),
                    sizeof( Int16 ) );
    writeToGameLog( reinterpret_cast< const char * >( &show ),
                    sizeof( showinfo_t ) );
}

// This method has no longer be used.
void
Logger::writeGameLogV3()
{
    static PlayMode pmode = PM_Null;
    static team_t teams[2] = { { "", 0 },
                               { "", 0 } };
    static int score_l = 0;
    static int score_r = 0;

    Int16 mode;

    // if playmode has changed wirte playmode
    if ( pmode != M_stadium.playmode() )
    {
        pmode = M_stadium.playmode();

        char pm = static_cast< char >( pmode );

        mode = htons( PM_MODE );
        writeToGameLog( reinterpret_cast< const char * >( &mode ),
                        sizeof( mode ) );
        writeToGameLog( reinterpret_cast< const char * >( &pm ),
                        sizeof( char ) );
    }

    // if teams or score has changed, write teams and score
    if ( M_stadium.teamLeft().point() != score_l
         || M_stadium.teamRight().point() != score_r
         || M_stadium.teamLeft().name() != teams[ 0 ].name
         || M_stadium.teamRight().name() != teams[ 1 ].name )
    {
        score_l = M_stadium.teamLeft().point();
        score_r = M_stadium.teamLeft().point();

        std::strncpy( teams[ 0 ].name,
                      M_stadium.teamLeft().name().c_str(),
                      std::min( M_stadium.teamLeft().name().length() + 1, size_t( 16 ) ) );
        teams[ 0 ].score = htons( score_l );

        std::strncpy( teams[ 1 ].name,
                      M_stadium.teamRight().name().c_str(),
                      std::min( M_stadium.teamRight().name().length() + 1, size_t( 16 ) ) );
        teams[ 1 ].score = htons( score_r );

        mode = htons( TEAM_MODE );
        writeToGameLog( reinterpret_cast< const char * >( &mode ),
                        sizeof( mode ) );
        writeToGameLog( reinterpret_cast< const char * >( teams ),
                        sizeof( team_t ) * 2 );

    }

    // write positional data
    short_showinfo_t2 show;

    show.time = htons( M_stadium.time() );

    show.ball.x = htonl( (Int32)rint( ( M_stadium.ball().pos().x * SHOWINFO_SCALE2 ) ) );
    show.ball.y = htonl( (Int32)rint( ( M_stadium.ball().pos().y * SHOWINFO_SCALE2 ) ) );
    show.ball.deltax = htonl( (Int32)rint( ( M_stadium.ball().vel().x * SHOWINFO_SCALE2 ) ) );
    show.ball.deltay = htonl( (Int32)rint( ( M_stadium.ball().vel().y * SHOWINFO_SCALE2) ) );

    const Stadium::PlayerCont & players = M_stadium.players();
    for ( int i = 0; i < MAX_PLAYER * 2; ++i )
    {
        show.pos[i].mode = htons( players[i]->state() );
        show.pos[i].type = htons( players[i]->playerTypeId() );

        show.pos[i].x = htonl( (Int32)rint( players[i]->pos().x * SHOWINFO_SCALE2 ) );
        show.pos[i].y = htonl( (Int32)rint( players[i]->pos().y * SHOWINFO_SCALE2 ) );
        show.pos[i].deltax = htonl( (Int32)rint( players[i]->vel().x * SHOWINFO_SCALE2 ) );
        show.pos[i].deltay = htonl( (Int32)rint( players[i]->vel().y * SHOWINFO_SCALE2 ) );
        show.pos[i].body_angle = htonl( (Int32)rint( players[i]->angleBodyCommitted() * SHOWINFO_SCALE2 ) );
        show.pos[i].head_angle = htonl( (Int32)rint( players[i]->angleNeckCommitted() * SHOWINFO_SCALE2 ) );
        show.pos[i].view_width = htonl( (Int32)rint( players[i]->visibleAngle() * SHOWINFO_SCALE2 ) );
        show.pos[i].view_quality = htons( (Int16)rint( players[i]->highquality() ) );

        show.pos[i].stamina = htonl( (Int32)rint( players[i]->stamina() * SHOWINFO_SCALE2 ) );
        show.pos[i].effort = htonl( (Int32)rint( players[i]->effort() * SHOWINFO_SCALE2 ) );
        show.pos[i].recovery = htonl( (Int32)rint( players[i]->recovery() * SHOWINFO_SCALE2 ) );

        show.pos[i].kick_count = htons( players[i]->kickCount() );
        show.pos[i].dash_count = htons( players[i]->dashCount() );
        show.pos[i].turn_count = htons( players[i]->turnCount() );
        show.pos[i].say_count = htons( players[i]->sayCount() );
        show.pos[i].tneck_count = htons( players[i]->turnNeckCount() );
        show.pos[i].catch_count = htons( players[i]->catchCount() );
        show.pos[i].move_count = htons( players[i]->moveCount() );
        show.pos[i].chg_view_count = htons( players[i]->changeViewCount() );
    }

    mode = htons( SHOW_MODE );
    writeToGameLog( reinterpret_cast< const char * >( &mode ),
                    sizeof( mode ) );
    writeToGameLog( reinterpret_cast< const char * >( &show ),
                    sizeof( short_showinfo_t2 ) );
}

// This method has no longer be used.
void
Logger::writeGameLogV4()
{
    static const char * playmode_strings[] = PLAYMODE_STRINGS;

    static PlayMode pm = PM_Null;
    static std::string team_l_name, team_r_name;
    static int team_l_score = 0, team_r_score = 0;
    static int team_l_pen_taken = 0, team_r_pen_taken = 0;

    const double prec = 0.0001;
    const double dprec = 0.001;

    std::ostream & os = *M_game_log;

    // if playmode has changed wirte playmode
    if ( pm != M_stadium.playmode() )
    {
        pm = M_stadium.playmode();

        os << "(playmode " << M_stadium.time()
           << ' ' << playmode_strings[pm] << ")\n";
    }

    // if teams or score has changed, write teams and score
    if ( team_l_score != M_stadium.teamLeft().point()
         || team_r_score != M_stadium.teamRight().point()
         || team_l_pen_taken != M_stadium.teamLeft().penaltyTaken()
         || team_r_pen_taken != M_stadium.teamRight().penaltyTaken()
         || M_stadium.teamLeft().name() != team_l_name
         || M_stadium.teamRight().name() != team_r_name
         )
    {
        team_l_name = M_stadium.teamLeft().name();
        team_r_name = M_stadium.teamRight().name();
        team_l_score = M_stadium.teamLeft().point();
        team_r_score = M_stadium.teamRight().point();
        team_l_pen_taken = M_stadium.teamLeft().penaltyTaken();
        team_r_pen_taken = M_stadium.teamRight().penaltyTaken();

        os << "(team " << M_stadium.time()
           << ' ' << ( team_l_name.empty() ? "null" : team_l_name.c_str() )
           << ' ' << ( team_r_name.empty() ? "null" : team_r_name.c_str() )
           << ' ' << team_l_score
           << ' ' << team_r_score;
        if ( team_l_pen_taken > 0 || team_r_pen_taken > 0 )
        {
            os << ' ' << M_stadium.teamLeft().penaltyPoint()
               << ' ' << team_l_pen_taken - M_stadium.teamLeft().penaltyPoint()
               << ' ' << M_stadium.teamRight().penaltyPoint()
               << ' ' << team_r_pen_taken - M_stadium.teamRight().penaltyPoint();
        }
        os << ")\n";
    }

    os << "(show " << M_stadium.time();
    os << " (" << BALL_NAME_SHORT
       << ' ' << Quantize( M_stadium.ball().pos().x, prec )
       << ' ' << Quantize( M_stadium.ball().pos().y, prec )
       << ' ' << Quantize( M_stadium.ball().vel().x, prec )
       << ' ' << Quantize( M_stadium.ball().vel().y, prec )
       << ')';

    const Stadium::PlayerCont::const_iterator end = M_stadium.players().end();
    for ( Stadium::PlayerCont::const_iterator p = M_stadium.players().begin();
          p != end;
          ++p )
    {
        os << " (";
        os << "(" << SideStr( (*p)->side() )
           << ' ' << (*p)->unum()
           << ')';
        os << ' ' << (*p)->playerTypeId()
           << ' ' << std::hex << std::showbase
           << (*p)->state() // include goalie flag
           << std::dec << std::noshowbase;

        os << ' ' << Quantize( (*p)->pos().x, prec )
           << ' ' << Quantize( (*p)->pos().y, prec )
           << ' ' << Quantize( (*p)->vel().x, prec )
           << ' ' << Quantize( (*p)->vel().y, prec )
           << ' ' << Quantize( Rad2Deg( (*p)->angleBodyCommitted() ), dprec )
           << ' ' << Quantize( Rad2Deg( (*p)->angleNeckCommitted() ), dprec );
        if ( (*p)->arm().isPointing() )
        {
            os << ' ' << Quantize( (*p)->arm().dest().getX(), prec )
               << ' ' << Quantize( (*p)->arm().dest().getY(), prec );
//             rcss::geom::Vector2D arm_dest;
//             if ( (*p)->arm().getRelDest( rcss::geom::Vector2D( (*p)->pos().x,
//                                                                (*p)->pos().y ),
//                                          0.0,
//                                          arm_dest ) )
//             {
//                 os << ' ' << Quantize( arm_dest.getMag(), prec )
//                    << ' ' << Quantize( Rad2Deg( arm_dest.getHead() ), dprec );
//             }
        }

        os << " (v "
           << ( (*p)->highquality() ? "h " : "l " )
           << Quantize( Rad2Deg( (*p)->visibleAngle() ), dprec )
           << ')';
        os << " (s "
           << (*p)->stamina() << ' '
           << (*p)->effort() << ' '
           << (*p)->recovery() << ')';
        if ( (*p)->isEnabled()
             && (*p)->getFocusTarget() != NULL )
        {
            os << " (f " << SideStr( (*p)->getFocusTarget()->side() )
               << ' ' << (*p)->getFocusTarget()->unum()
               << ')';
        }
        os << " (c "
           << (*p)->kickCount()
           << ' ' << (*p)->dashCount()
           << ' ' << (*p)->turnCount()
           << ' ' << (*p)->catchCount()
           << ' ' << (*p)->moveCount()
           << ' ' << (*p)->turnNeckCount()
           << ' ' << (*p)->changeViewCount()
           << ' ' << (*p)->sayCount()
           << ' ' << (*p)->tackleCount()
           << ' ' << (*p)->arm().getCounter()
           << ' ' << (*p)->attentiontoCount()
           << ')';
        os << ')'; // end of player
    }

    os << ")\n";
}
#endif

void
Logger::writeTeamGraphic( const Side side,
                          const unsigned int x,
                          const unsigned int y )
{
    if ( ! isGameLogOpen() )
    {
        return;
    }

    M_observer->sendTeamGraphic( side, x, y );

//     const XPMHolder * xpm = ( side == LEFT
//                               ? M_stadium.teamLeft().teamGraphic( x, y )
//                               : side == RIGHT
//                               ? M_stadium.teamRight().teamGraphic( x, y )
//                               : static_cast< const XPMHolder * >( 0 ) );
//     if ( ! xpm )
//     {
//         return;
//     }

// #ifdef HAVE_SSTREAM
//     std::ostringstream data;
// #else
//     std::ostrstream data;
// #endif
//     data << "(team_graphic_"
//          << ( side == LEFT ? "l" : "r" )
//          << " (" << x << " " << y << " "
//          << *xpm << ")";

// #ifndef HAVE_SSTREAM
//     data << std::ends;
// #endif

//     std::string msg = data.str();

// #ifndef HAVE_SSTREAM
//     data.freeze( false );
// #endif

//     writeMsgToGameLog( MSG_BOARD, msg.c_str(), true );
}

void
Logger::writeTextLog( const char * message,
                      const TextLogFlag flag )
{
    if ( flag == RECV || flag == LOG_TEXT )
    {
        if ( isTextLogOpen() )
        {
            *M_text_log << M_stadium.time()
                        << ',' << M_stadium.stoppageTime()
                        << "\t" << message << '\n';
        }
    }

    if ( ( flag == RECV || flag == SUBS )
         && isGameLogOpen()
         && ServerParam::instance().recordMessages()
         && M_stadium.playmode() != PM_TimeOver )
    {
        char buf[max_message_length_for_display];
        std::strncpy( buf, message, std::min( max_message_length_for_display,
                                              (int)std::strlen( message ) ) );

        writeMsgToGameLog( LOG_BOARD, buf );
    }

//     if ( ( flag == RECV || flag == SUBS )
//          && ServerParam::instance().sendComms() )
//     {
//         char buf[max_message_length_for_display];
//         std::strncpy( buf, message, std::min( max_message_length_for_display,
//                                               (int)std::strlen( message ) ) );

//         for ( Stadium::MonitorCont::iterator i = M_stadium.monitors().begin();
//               i != M_stadium.monitors().end();
//               ++i )
//         {
//             (*i)->sendMsg( LOG_BOARD, buf );
//         }
//     }

}

void
Logger::writePlayerLog( const Player & player,
                        const char * message,
                        const TextLogFlag flag )
{
    if ( isTextLogOpen()
         || ( flag == RECV && isGameLogOpen() )
         || ( flag == RECV && ServerParam::instance().sendComms() ) )
    {
        char tmp[MaxMesg];
        snprintf( tmp, MaxMesg,
                  "%s %s_%d: %s",
                  ( flag == SEND ? "Send" : "Recv" ),
                  player.team()->name().c_str(),
                  player.unum(),
                  message );
        writeTextLog( tmp, flag );
    }
}

void
Logger::writeCoachLog( const char * message,
                       const TextLogFlag flag )
{
    if ( isTextLogOpen()
         || ( flag == RECV && isGameLogOpen() )
         || ( flag == RECV && ServerParam::instance().sendComms() ) )
    {
        char tmp[MaxMesg];
        snprintf( tmp, MaxMesg,
                  "%s Coach: %s",
                  ( flag == SEND ? "Send" : "Recv" ),
                  message ) ;
        writeTextLog( tmp, flag );
    }
}

void
Logger::writeOnlineCoachLog( const OnlineCoach & coach,
                             const char * message,
                             const TextLogFlag flag )
{
    if ( isTextLogOpen()
         || ( flag == RECV && isGameLogOpen() )
         || ( flag == RECV && ServerParam::instance().sendComms() ) )
    {
        char tmp[MaxMesg];
        snprintf( tmp, MaxMesg,
                  "%s %s_Coach: %s",
                  ( flag == SEND ? "Send" : "Recv" ),
                  ( coach.side() == LEFT
                    ? M_stadium.teamLeft().name().c_str()
                    : M_stadium.teamRight().name().c_str() ),
                  message );
        writeTextLog( tmp, flag );
    }
}

void
Logger::writeRefereeAudio( const char * msg )
{
    if ( isTextLogOpen()
         || ( isGameLogOpen()
              && M_stadium.playmode() != PM_BeforeKickOff
              && M_stadium.playmode() != PM_TimeOver ) )
    {
        char buf[max_message_length_for_display];
        snprintf( buf,
                  max_message_length_for_display,
                  "(%s %s)",
                  REFEREE_NAME, msg );

        if ( isTextLogOpen() )
        {
            writeTextLog( buf, LOG_TEXT );
        }

        if ( isGameLogOpen() )
        {
            writeMsgToGameLog( MSG_BOARD, buf );
        }
    }
}

void
Logger::writePlayerAudio( const Player & player,
                          const char * msg )
{

    if ( isGameLogOpen()
         && ServerParam::instance().recordMessages()
         && M_stadium.playmode() != PM_BeforeKickOff
         && M_stadium.playmode() != PM_TimeOver )
    {
        char buf[max_message_length_for_display];
        snprintf( buf,
                  max_message_length_for_display,
                  "(%s %s)",
                  player.name().c_str(), msg );

        writeMsgToGameLog( MSG_BOARD, buf );
    }
}

void
Logger::writeCoachAudio( const Coach & coach,
                         const char * msg )
{
    if ( isGameLogOpen()
         && ServerParam::instance().recordMessages()
         && M_stadium.playmode() != PM_BeforeKickOff
         && M_stadium.playmode() != PM_TimeOver )
    {
        char buf[max_message_length_for_display];
        char format[40];
        snprintf( format, 40, "(%%s %%.%ds)",
                  max_message_length_for_display - (MaxMesg - MaxCoachMesg) );
        snprintf( buf,
                  max_message_length_for_display,
                  format,
                  ( coach.side() == RIGHT
                    ? OLCOACH_NAME_R
                    : coach.side() == LEFT
                    ? OLCOACH_NAME_L
                    : REFEREE_NAME ),
                  msg );

        writeMsgToGameLog( MSG_BOARD, buf );
    }
}

void
Logger::writeCoachStdAudio( const OnlineCoach & coach,
                            const rcss::clang::Msg & msg )
{
    if ( isGameLogOpen()
         && ServerParam::instance().recordMessages()
         && M_stadium.playmode() != PM_BeforeKickOff
         && M_stadium.playmode() != PM_TimeOver )
    {
        std::ostringstream coach_mess;

        coach_mess << msg.getTimeRecv() << " ";
        msg.print( coach_mess );

        char buf[max_message_length_for_display];
        char format[40];
        snprintf( format, 40, "(%%s %%.%ds)",
                  max_message_length_for_display - (MaxMesg - MaxCoachMesg));
        snprintf( buf,
                  max_message_length_for_display,
                  format,
                  (coach.side() == RIGHT) ? OLCOACH_NAME_R : OLCOACH_NAME_L,
                  coach_mess.str().c_str() );

        writeMsgToGameLog( MSG_BOARD, buf );
    }
}

void
Logger::writeTimes( const timeval & old_time,
                    const timeval & new_time )
{
    if ( isTextLogOpen()
         && ServerParam::instance().logTimes() )
    {
        double diff = (new_time.tv_sec - old_time.tv_sec) * 1000
            + (double)(new_time.tv_usec - old_time.tv_usec) / 1000;

        *M_text_log << M_stadium.time()
                    << ',' << M_stadium.stoppageTime()
                    << "\tCYCLE_TIMES: " << diff << '\n';
    }
}

void
Logger::writeProfile( const timeval & start_time,
                      const timeval & end_time,
                      const char * str )
{
    if ( isTextLogOpen()
         && ServerParam::instance().profile() )
    {
        double diff = (end_time.tv_sec - start_time.tv_sec) * 1000
            + (double)(end_time.tv_usec - start_time.tv_usec) / 1000;

        *M_text_log << M_stadium.time()
                    << ',' << M_stadium.stoppageTime()
                    << "\t" << str << ": " << diff << '\n';
    }
}

ext: cpp


text:
/**
 * MIT License
 * Copyright (c) 2018 Patrick Geneva
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <boost/filesystem.hpp>
#include <iostream>
#include <torch/data.h>
#include <torch/torch.h>

#include "data/CityscapesDataset.h"
#include "data/Comma10kDataset.h"
#include "network/models/UNetModel.h"

int main() {

  // See if we can use the GPU or should train using the CPU
  torch::DeviceType device_type;
  if (torch::cuda::is_available()) {
    std::cout << "CUDA available! Training on GPU." << std::endl;
    device_type = torch::kCUDA;
  } else {
    std::cout << "Training on CPU. Are you using the CUDA TorchLib??" << std::endl;
    device_type = torch::kCPU;
  }
  torch::Device device(device_type);

  // Load the data from disk
  std::string rootdir = "/media/patrick/DATA 02/SEGNET/comma10k/";
  // auto dataset =
  //     CityscapesDataset(rootdir, CityscapesDataset::ModeDataSplit::kTrain, CityscapesDataset::ModeGroundtruth::kSegmentation, true);
  auto dataset = Comma10kDataset(rootdir, Comma10kDataset::ModeDataSplit::kTrain, true);

  // Create the network (RGB image => class masks)
  size_t n_channels = 3;
  size_t n_classes = dataset.map_id2class.size();
  UNetModel model(n_channels, n_classes);
  std::cout << "num params: " << model->parameters(true).size() << std::endl;

  // Load from disk if we can
  std::string modelpath = "checkpoint-seg.pt";
  if (boost::filesystem::exists(modelpath)) {
    torch::load(model, modelpath);
  } else {
    std::cerr << "no checkpoint found on disk, creating new model." << std::endl;
  }
  model->to(device);

  // Create the log file for our loss values
  std::string logpath = "loss_history_seg.txt";
  std::ofstream loghist;
  loghist.open(logpath, std::ofstream::out | std::ofstream::app);

  // Finally convert it to a unique pointer dataloader
  auto dataset_mapped = dataset.map(torch::data::transforms::Stack<>());
  auto sampler = torch::data::samplers::RandomSampler(dataset.size().value());
  auto options = torch::data::DataLoaderOptions().enforce_ordering(false).batch_size(5).workers(30);
  auto data_loader = torch::data::make_data_loader(std::move(dataset_mapped), sampler, options);

  // Create the optimizer
  // torch::optim::SGD optimizer(model->parameters(), torch::optim::SGDOptions(0.01).momentum(0.5));
  torch::optim::Adam optimizer(model->parameters(), torch::optim::AdamOptions(0.0002));

  // Loop through our epochs
  size_t max_epochs = 100;
  for (size_t epoch = 1; epoch <= max_epochs; epoch++) {

    // Enable training mode
    model->train();

    // Loop through our batches of training data
    size_t batch_idx = 0;
    for (auto &batch : *data_loader) {

      // Send that data to the device
      auto d_rgb = batch.data.to(device);
      auto d_masks = batch.target.to(device);

      // Zero the gradient from the last run
      optimizer.zero_grad();

      // Send the data through and calc the loss
      auto output = model->forward(d_rgb);

      // There is not a cross entropy loss
      // We do a softmax first along the classes [N, classes, H, W]
      // Also note that our dataloader will add an extra dimension to the labels (so we squeese the class dim)
      // https://discuss.pytorch.org/t/c-loss-functions/27471/5
      d_masks = torch::squeeze(d_masks, 1);
      auto loss = torch::nll_loss2d(torch::log_softmax(output, 1), d_masks);
      loghist << std::fixed << std::setprecision(10) << loss.item<float>() << std::endl;

      // Back propagate!
      loss.backward();
      optimizer.step();

      // Print our the loss every once in a while
      if (batch_idx % 100 == 0) {

        // Debug printout
        size_t items_curr = batch_idx * batch.data.size(0);
        size_t items_total = dataset.size().value();
        std::cout << epoch << " - " << items_curr << "/" << items_total << " | loss = " << loss.item<float>() << std::endl;

        // Softmax the output to get our total class probabilities
        // Thus across all classes, our probabilities should sum to 1
        auto output_probs = torch::softmax(output, 1);

        // Plot the first image, need to change to opencv format [H,W,C]
        // Note that we arg max the softmax network output, then need to add an dimension
        // We scale up the 0..1 range back to the 0..255 that opencv expects (later cast to int)
        torch::Tensor cv_input = 255.0 * batch.data[0].permute({1, 2, 0}).clone().cpu();
        torch::Tensor cv_label = batch.target[0].permute({1, 2, 0}).clone().cpu();
        torch::Tensor cv_output = torch::unsqueeze(output_probs[0].argmax(0), 0).permute({1, 2, 0}).clone().cpu();

        // Convert them all to 0..255 ranges
        cv_input = cv_input.to(torch::kInt8);
        cv_label = cv_label.to(torch::kInt8);
        cv_output = cv_output.to(torch::kInt8);

        // Point the cv::Mats to the transformed locations in memory
        cv::Mat img_input(cv::Size((int)cv_input.size(1), (int)cv_input.size(0)), CV_8UC3, cv_input.data_ptr<int8_t>());
        cv::Mat img_label(cv::Size((int)cv_label.size(1), (int)cv_label.size(0)), CV_8UC1, cv_label.data_ptr<int8_t>());
        cv::Mat img_output(cv::Size((int)cv_output.size(1), (int)cv_output.size(0)), CV_8UC1, cv_output.data_ptr<int8_t>());

        // Convert labeled images to color
        cv::cvtColor(img_label, img_label, cv::COLOR_GRAY2BGR);
        cv::cvtColor(img_output, img_output, cv::COLOR_GRAY2BGR);
        // img_label = 255.0 / (double)n_classes * img_label;
        // img_output = 255.0 / (double)n_classes * img_output;

        // Change both to be colored like the comma10k
        img_label.forEach<cv::Vec3b>([&](cv::Vec3b &px, const int *pos) -> void { px = dataset.map_id2hex[(char)px[0]]; });
        img_output.forEach<cv::Vec3b>([&](cv::Vec3b &px, const int *pos) -> void { px = dataset.map_id2hex[(char)px[0]]; });

        // Finally, stack and display in a window
        cv::Mat outimg1, outimg2, outimg3;
        cv::hconcat(img_input, img_label, outimg1);
        cv::hconcat(img_input, img_output, outimg2);
        cv::vconcat(outimg1, outimg2, outimg3);
        cv::imshow("current status", outimg3);
        cv::waitKey(100);

        // Save the model to disk
        torch::save(model, modelpath);
      }
      batch_idx++;
    }
  }

  // Save model to file
  torch::save(model, modelpath);

  // Close file
  loghist.close();
}

max_stars_repo_name: goldbattle/segnet

max_issues_repo_name: goldbattle/segnet

max_forks_repo_name: goldbattle/segnet


text:
//==================================================================================================
/*!
    @file

    @Copyright 2016 Numscale SAS

    Distributed under the Boost Software License, Version 1.0.
    (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_X86_SSE2_SIMD_FUNCTION_TOFLOAT_HPP_INCLUDED
#define BOOST_SIMD_ARCH_X86_SSE2_SIMD_FUNCTION_TOFLOAT_HPP_INCLUDED
#include <boost/simd/detail/overload.hpp>

#include <boost/simd/function/bitwise_cast.hpp>
#include <boost/simd/function/bitwise_notand.hpp>
#include <boost/simd/function/if_plus.hpp>
#include <boost/simd/constant/signmask.hpp>
#include <boost/simd/constant/twoto31.hpp>
#include <boost/simd/detail/dispatch/meta/as_integer.hpp>
#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>
#include <boost/simd/detail/dispatch/meta/as_floating.hpp>

namespace boost { namespace simd { namespace ext
{
  namespace bd =  boost::dispatch;
  namespace bs =  boost::simd;
  BOOST_DISPATCH_OVERLOAD ( tofloat_
                          , (typename A0)
                          , bs::sse2_
                          , bs::pack_<bd::int32_<A0>, bs::sse_>
                         )
  {
    using result = bd::as_floating_t<A0>;
    BOOST_FORCEINLINE result operator() ( const A0 & a0) const BOOST_NOEXCEPT
    {
      return _mm_cvtepi32_ps(a0);
    }
  };

  BOOST_DISPATCH_OVERLOAD ( tofloat_
                          , (typename A0)
                          , bs::sse2_
                          , bs::pack_<bd::uint64_<A0>, bs::sse_>
                         )
  {
    using result = bd::as_floating_t<A0>;
    using stype = bd::scalar_of_t<result>;
    BOOST_FORCEINLINE result operator() ( const A0 & a0) const BOOST_NOEXCEPT
    {
      return {static_cast<stype>(a0[0]), static_cast<stype>(a0[1])};
    }
  };

  BOOST_DISPATCH_OVERLOAD ( tofloat_
                          , (typename A0)
                          , bs::sse2_
                          , bs::pack_<bd::int64_<A0>, bs::sse_>
                         )
  {
    using result = bd::as_floating_t<A0>;
    using stype = bd::scalar_of_t<result>;
    BOOST_FORCEINLINE result operator() ( const A0 & a0) const BOOST_NOEXCEPT
    {
      return {static_cast<stype>(a0[0]), static_cast<stype>(a0[1])};
    }
  };

  BOOST_DISPATCH_OVERLOAD ( tofloat_
                          , (typename A0)
                          , bs::sse2_
                          , bs::pack_<bd::uint32_<A0>, bs::sse_>
                         )
  {
    using result = bd::as_floating_t<A0>;
    BOOST_FORCEINLINE result operator() ( const A0 & a0) const BOOST_NOEXCEPT
    {
      using si_type = bd::as_integer_t<A0, signed>;
      si_type a00 = bitwise_cast<si_type>(a0);
      si_type a01 = bitwise_notand(Signmask<si_type>(), a0);
      return if_plus(is_ltz(a00), tofloat(a01), Twoto31<result>());
    }
  };

} } }

#endif

ext: hpp

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
#pragma once

#include <Eigen/Core>
#include <limits>
#include <vector>

namespace collision2d {
template <typename N>
using Point = Eigen::Matrix<N, 2, 1>;

template <typename N>
using Polygon = std::vector<Point<N>>;

/**
 * Computes potential separating axes for a convex polygon.
 */
template <typename N>
void separatingAxes(const Polygon<N> &a, std::vector<Point<N>> &axes) {
  for (auto i = 0u; i < a.size(); ++i) {
    const auto current = a[i];
    const auto next = a[(i + 1) % a.size()];
    const auto edge = (next - current).normalized();
    // axis is the normal of an edge
    axes.emplace_back(Point<N>{-edge[1], edge[0]});
  }
}

/**
 * Projects the polygon onto the given axis and returns the maximum and minimum
 * coordinate on the axis. Note that the axis has to be normalized.
 */
template <typename N>
void project(const Polygon<N> &a, const Point<N> &axis, N &minProj,
             N &maxProj) {
  maxProj = -std::numeric_limits<N>::infinity();
  minProj = std::numeric_limits<N>::infinity();
  for (const Point<N> &v : a) {
    const N proj = axis.dot(v);
    if (proj < minProj) minProj = proj;
    if (proj > maxProj) maxProj = proj;
  }
}

/**
 * Check for collision between polygons a and b via the Separating Axis Theorem.
 */
template <typename N>
bool intersect(const Polygon<N> &a, const Polygon<N> &b) {
  // compute separating axes
  std::vector<Point<N>> axes;
  separatingAxes(a, axes);
  separatingAxes(b, axes);
  for (const auto &axis : axes) {
    N aMaxProj, aMinProj, bMaxProj, bMinProj;
    project(a, axis, aMinProj, aMaxProj);
    project(b, axis, bMinProj, bMaxProj);
    // check if projections overlap
    if (aMinProj > bMaxProj || bMinProj > aMaxProj) return false;
  }

  return true;
}

// /**
//  * Efficient test for a point to be in a convex polygon.
//  *
//  * Robert Nowak "An Efficient Test for a Point to Be in a Convex Polygon"
//  * http://demonstrations.wolfram.com/AnEfficientTestForAPointToBeInAConvexPolygon/
//  * Wolfram Demonstrations Project
//  * Published: March 7 2011
//  */
// template <typename N>
// bool intersect2(const Point<N> &point, const Polygon<N> &polygon,
//                 const N &epsilon = 1e-4) {
//   bool angle = false;  // stores the sign of the last angle
//   for (auto i = 0u; i < polygon.size(); ++i) {
//     const auto &a = polygon[i] - point;
//     const auto &b = polygon[(i + 1) % polygon.size()] - point;
//     const bool newAngle = b(0) * a(1) - a(0) * b(1) > -epsilon;
//     if (i > 0 && angle != newAngle) return false;
//     angle = newAngle;
//   }
//   return true;
// }

/**
 * Tests whether point intersects with convex polygon.
 * Source: https://stackoverflow.com/a/8721483
 */
template <typename N>
bool intersect(const Point<N> &point, const Polygon<N> &polygon,
               const N &epsilon = 1e-4) {
  bool result = false;
  std::size_t i, j;
  for (i = 0, j = polygon.size() - 1; i < polygon.size(); j = i++) {
    if ((polygon[i].y() > point.y()) != (polygon[j].y() > point.y()) &&
        (point.x() < (polygon[j].x() - polygon[i].x()) * (point.y() - polygon[i].y()) /
                          (polygon[j].y() - polygon[i].y() + epsilon) +
                      polygon[i].x())) {
      result = !result;
    }
  }
  return result;
}
}  // namespace collision2d


text:
#include <iostream>
#include <limits.h>
#include <boost/tokenizer.hpp>

#include <opencv_workbench/syllo/syllo.h>
#include <opencv_workbench/wb/WB.h>

#include "Entity.h"

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

namespace wb {

     Entity::Entity() : id_(-1), name_("unknown:-1"),
                        type_(Unknown), age_(0), occluded_age_(0),
                        occluded_(false), is_confirmed_(false), visited_(false),
                        cluster_id_(0), avg_pixel_value_(-1)
     {
          stream_ = NULL;
          matched_ = false;

          confirmed_age_ = 3;
          dead_occluded_age_ = 11;

          class_age_ = 0;

          /////
          left_tracker.set_P(60);
          right_tracker.set_P(60);

          double T = 0.066666667; // dt
          double q= T * 1;
          left_tracker.set_Q(q);
          right_tracker.set_Q(q);
     }

     void Entity::set_estimated_pixel_centroid(cv::Point p)
     {
          pixel_tracker_.set_position(p);
     }

     void Entity::set_estimated_centroid(cv::Point2d p)
     {
          tracker_.set_position(p);
     }

     void Entity::init()
     {
          compute_metrics();

          start_pixel_centroid_ = pixel_centroid_;

          pixel_tracker_.set_measurement(pixel_centroid_);
          tracker_.set_measurement(centroid_);
     }

     cv::Point Entity::trail_history(int past)
     {
          cv::Point result;
          int count = 0;
          for (std::list<cv::Point2f>::reverse_iterator rit = trail_.rbegin();
               rit != trail_.rend(); ++rit) {
               result = *rit;
               if (count >= past) {
                    return result;
               }
               count++;
          }
          return result;
     }

     cv::Point Entity::estimated_pixel_centroid()
     {
          // the Kalman filter's estimate centroid. Otherwise, use the entity's
          // current centroid if it isn't confirmed yet
          //if (this->is_confirmed()) {
               return pixel_tracker_.position();
          //     //return est_pixel_centroid_;
          //} else {
          //     return pixel_centroid_;
          //}
     }

     cv::Point Entity::estimated_pixel_velocity()
     {
          return pixel_tracker_.velocity();
     }

     cv::Point2d Entity::estimated_centroid()
     {
          // the Kalman filter's estimate centroid. Otherwise, use the entity's
          // current centroid if it isn't confirmed yet
          //if (this->is_confirmed()) {
               return tracker_.position();
          //} else {
          //     return centroid_;
          //}
          return centroid_;
     }

     int Entity::estimated_pixel_value()
     {
          return floor(pixel_value_tracker_.value());
     }

     int Entity::estimated_blob_size()
     {
          return floor(size_tracker_.value());
     }

     int Entity::lower_pixel_value(float num_stds)
     {
          return pixel_value_tracker_.lower_end(num_stds);
     }

     int Entity::lower_blob_size(float num_stds)
     {
          return size_tracker_.lower_end(num_stds);
     }

     Ellipse Entity::error_ellipse(double confidence)
     {
          //return kf_.error_ellipse(confidence);
          return pixel_tracker_.error_ellipse(confidence);
     }

     void Entity::predict_tracker()
     {
          pixel_tracker_.predict();
          tracker_.predict();

          pixel_value_tracker_.predict();
          size_tracker_.predict();

          //cout << "Update - Track: " << id_ << " , size=" << size_tracker_.value()
          //     << ", value=" << pixel_value_tracker_.value() << endl;
     }

     void Entity::correct_tracker()
     {
          //// correct tracker update using the newly computed centroid.
          pixel_tracker_.set_measurement(pixel_centroid_);
          tracker_.set_measurement(centroid_);

          // Correct average pixel value tracker
          pixel_value_tracker_.set_value(avg_pixel_value_);

          // Correct blob size tracker
          size_tracker_.set_value((float)points_.size());
     }

     void Entity::update_trail()
     {
          trail_.push_back(estimated_pixel_centroid());
     }

     void Entity::compute_metrics()
     {
          ////////////////////////////////////////////////////////
          // Compute Centroid and Bounding Box Rectangle
          ////////////////////////////////////////////////////////
          int sum_x_pixel = 0, sum_y_pixel = 0, sum_value_pixel = 0;
          int xmin_pixel = INT_MAX, ymin_pixel = INT_MAX;
          int xmax_pixel = INT_MIN, ymax_pixel = INT_MIN;

          for (std::vector<Point>::iterator it = points_.begin();
               it != points_.end(); it++) {

               // Calculate centroid in "image" space
               int x_pixel = it->position().x;
               int y_pixel = it->position().y;

               int value_pixel = it->value();
               sum_value_pixel += value_pixel;

               sum_x_pixel += x_pixel * value_pixel;
               sum_y_pixel += y_pixel * value_pixel;

               if (x_pixel < xmin_pixel) {
                    xmin_pixel = x_pixel;
               }
               if (x_pixel > xmax_pixel) {
                    xmax_pixel = x_pixel;
               }
               if (y_pixel < ymin_pixel) {
                    ymin_pixel = y_pixel;
               }
               if (y_pixel > ymax_pixel) {
                    ymax_pixel = y_pixel;
               }
          }

          double avg_x_pixel = (double)sum_x_pixel / (double)sum_value_pixel;
          double avg_y_pixel = (double)sum_y_pixel / (double)sum_value_pixel;

          avg_pixel_value_ = (double)sum_value_pixel / (double)points_.size();

          pixel_value_tracker_.set_value(avg_pixel_value_);
          size_tracker_.set_value((float)points_.size());

          pixel_centroid_ = cv::Point(cvRound(avg_x_pixel), cvRound(avg_y_pixel));

          // +1's to account for slight error in rectangle drawing?
          //bbox_ = cv::Rect rect(xmin, ymin, xmax-xmin+1, ymax-ymin+1);
          bbox_.set_box(xmin_pixel, xmax_pixel+1, ymin_pixel, ymax_pixel+1);

          // Get the centroid in X/Y Cartesian space
          if (stream_ != NULL) {
               centroid_ = wb::rowcol2cartesian(stream_, pixel_centroid_.y, pixel_centroid_.x);
          } else {
               cout << "Missing stream object" << endl;
               centroid_ = cv::Point2d(-1,-1);
          }
     }

     cv::Rect Entity::rectangle()
     {
          return bbox_.rectangle();
     }

     bool Entity::is_confirmed()
     {
          if (is_confirmed_) return true;

          if (age_ >= confirmed_age_) {
               is_confirmed_ = true;
               return true;
          } else {
               is_confirmed_ = false;
               return false;
          }
     }

     bool Entity::is_dead()
     {
          if (occluded_age_ >= dead_occluded_age_) {
               return true;
          } else {
               return false;
          }
     }

     void Entity::inc_age()
     {
          age_++;
     }

     void Entity::set_age(int age)
     {
          age_ = age;
     }

     void Entity::dec_age()
     {
          age_--;
     }

     void Entity::missed_track()
     {
          this->set_occluded(true);
          this->inc_occluded_age();
     }

     void Entity::detected_track()
     {
          this->inc_age();
          this->set_occluded(false);

          // Update the Kalman Filter Tracker
          this->correct_tracker();

          //cout << "Detected - Track: " << id_ << " , size=" << points_.size()
          //     << ", value=" << avg_pixel_value_ << endl;
     }

     void Entity::new_track(int id)
     {
          this->set_id(id);
          this->set_age(1);
          this->set_occluded(false);
     }

     void Entity::set_occluded(bool occluded)
     {
          occluded_ = occluded;
          if (!occluded_) {
               this->set_occluded_age(0);
          }
     }

     void Entity::copy_track_info(Entity &other)
     {
          this->set_id(other.id());
          this->set_age(other.age());
          this->set_estimated_pixel_centroid(other.estimated_pixel_centroid());
          this->set_estimated_centroid(other.estimated_centroid());
          this->set_start_centroid(other.start_centroid());
          this->set_start_pixel_centroid(other.start_pixel_centroid());
          this->set_tracker(other.tracker());
          this->set_pixel_tracker(other.pixel_tracker());
          this->trail_ = other.trail_;
     }

     void Entity::copy_meas_info(Entity &other)
     {
          this->centroid_ = other.centroid();
          this->pixel_centroid_ = other.pixel_centroid();
          this->bbox_ = other.bbox();
          this->points_ = other.points();

          this->avg_pixel_value_ = other.avg_pixel_value();
     }

     void Entity::matched_track(Entity &match)
     {
          // Update the current entity with the track info from "match"
          this->copy_track_info(match);

          // Update track variables
          this->detected_track();
     }

     void Entity::set_pixel_R(double r)
     {
          pixel_tracker_.set_R(r);
     }

     void Entity::set_pixel_P(double p)
     {
          pixel_tracker_.set_P(p);
     }

     void Entity::set_R(double r)
     {
          tracker_.set_R(r);
     }

     void Entity::set_R(double r0, double r1, double r2, double r3)
     {
          tracker_.set_R(r0, r1, r2, r3);
     }

     void Entity::set_P(double p)
     {
          tracker_.set_P(p);
     }

     void Entity::remove_point(wb::Point &p)
     {
          std::vector<Point>::iterator it = points_.begin();
          for (; it != points_.end(); it++) {
               if (it->position() == p.position()) {
                    points_.erase(it);
                    break;
               }
          }
     }

     void Entity::add_points(std::vector<wb::Point> &points)
     {
          std::vector<wb::Point>::iterator it = points.begin();
          for (; it != points.end(); it++) {
               points_.push_back(*it);
          }
     }

     std::string Entity::name()
     {
          std::ostringstream convert;
          convert << id_;

          switch (type_) {
          case Unknown:
               name_ = "unknown:" + convert.str();
               break;
          case Diver:
               name_ = "diver:" + convert.str();
               break;
          case Fish:
               name_ = "fish:" + convert.str();
               break;
          case Clutter:
               name_ = "clutter:" + convert.str();
               break;
          case APoint:
               name_ = "point:" + convert.str();
               break;
          default:
               name_ = "unknown:" + convert.str();
          }

          return name_;
     }

     std::string Entity::type_str()
     {
          switch (type_) {
          case Unknown:
               return "unknown";
               break;
          case Diver:
               return "diver";
               break;
          case Fish:
               return "fish";
               break;
          case Clutter:
               return "clutter";
               break;
          case APoint:
               return "point";
               break;
          default:
               return "unknown";
          }
     }

     wb::Entity::EntityType_t Entity::str_2_type(std::string str)
     {
          if (str == "unknown") {
               return Unknown;
          } else if (str == "diver") {
               return Diver;
          } else if (str == "fish") {
               return Fish;
          } else if (str == "clutter") {
               return Clutter;
          } else if (str == "point") {
               return APoint;
          } else {
               return Unknown;
          }
     }

     void Entity::set_name(std::string name)
     {
          boost::char_separator<char> sep(":");
          boost::tokenizer<boost::char_separator<char> > tokens(name, sep);
          int iter = 0;
          std::string type_str = "unknown";
          id_ = -2;
          for (boost::tokenizer<boost::char_separator<char> >::iterator tok_iter = tokens.begin();
               tok_iter != tokens.end(); ++tok_iter) {

               if (iter == 0) {
                    type_str = *tok_iter;
               } else if (iter == 1) {
                    id_  = syllo::str2int(std::string(*tok_iter));
               }
               iter++;
          }
          type_ = Entity::str_2_type(type_str);
     }
}

max_stars_repo_name: SyllogismRXS/opencv-workbench

max_issues_repo_name: SyllogismRXS/opencv-workbench

max_forks_repo_name: SyllogismRXS/opencv-workbench


text: #include <boost/spirit/home/qi/operator.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Common test utils and macros.

#define BEGIN_SEQUENCER_TEST(name)                                    \
  BOOST_AUTO_TEST_CASE(name) {                                        \
    BOOST_REQUIRE_EQUAL(*async::sequencer_state_count(), 0);       \
    auto time_start = boost::posix_time::second_clock::local_time();  \
    // Run the sequencer code in its own scope, before then checking  \
    // get_sequencer_state_count()==0.

#define END_SEQUENCER_TEST()                                \
  }                                                         \
  BOOST_CHECK_EQUAL(*async::sequencer_state_count(), 0);

// ASIO helpers --------------------------------------------------

#include <boost/asio.hpp>
#include <boost/asio/steady_timer.hpp>

using boost::posix_time::seconds;

#define BEGIN_SEQUENCER_ASIO_TEST(name)                                 \
  BOOST_AUTO_TEST_CASE(name) {                                          \
    BOOST_REQUIRE_EQUAL(*async::sequencer_state_count(), 0);         \
    boost::asio::io_service io_service;                                 \
    auto time_start = boost::posix_time::second_clock::local_time();    \
    std::vector<std::unique_ptr<boost::asio::deadline_timer>> timers;   \
    // Run the sequencer code in its own scope, before then checking    \
    // get_sequencer_state_count()==0.

#define END_SEQUENCER_ASIO_TEST(TO_DELETE)                        \
    io_service.run();                                             \
    delete TO_DELETE;                                             \
  }                                                               \
  BOOST_CHECK_EQUAL(*async::sequencer_state_count(), 0);

#define CHECK_TIME_LAPSE(expected)                                      \
  {                                                                     \
  auto time_diff = boost::posix_time::second_clock::local_time() - time_start; \
  /*printf("time_diff: %d\n", time_diff.total_milliseconds());   */     \
  BOOST_CHECK(time_diff.total_milliseconds() > expected - 100 && \
      time_diff.total_milliseconds() < expected + 100); \
  }

void invoke_or_defer(boost::asio::io_service& io_service,
    std::vector<std::unique_ptr<boost::asio::deadline_timer>>& timers,
    int timer_seconds, std::function<void()> func) {
  if (timer_seconds >= 0) {
    // Use boost::asio.
    printf("task w/delayed callback: %d seconds\n", timer_seconds);
    timers.emplace_back(new boost::asio::deadline_timer(io_service));
    timers.back()->expires_from_now(seconds(timer_seconds));
    timers.back()->async_wait([=] (const boost::system::error_code& error) {
          func();
        });
  } else {
    // Negative seconds means return a result immediately and do not
    // defer this result.
    func();
  }
}

async::Task<int> make_task_callback_no_input(boost::asio::io_service& io_service,
    std::vector<std::unique_ptr<boost::asio::deadline_timer>>& timers,
    int timer_seconds, int output) {
  return [=, &io_service, &timers](async::TaskCallback<int> callback) {
    invoke_or_defer(io_service, timers, timer_seconds,
        [=]() { callback(async::OK, output); });
  };
}

async::MapCallback<int> make_task_callback_square(boost::asio::io_service& io_service,
    std::vector<std::unique_ptr<boost::asio::deadline_timer>>& timers,
    int timer_seconds) {
  return [=, &io_service, &timers](int input, async::TaskCallback<int> callback) {
    invoke_or_defer(io_service, timers, timer_seconds,
        [=]() { callback(async::OK, input * input); });
  };
}

max_stars_repo_name: curtkim/asyncpp

max_issues_repo_name: curtkim/asyncpp

max_forks_repo_name: curtkim/asyncpp