<commit_before>/*
 * Copyright (c) 2000-2004 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

///
/// @file sim/main.cc
///
#include <sys/types.h>
#include <sys/stat.h>
#include <libgen.h>
#include <stdlib.h>
#include <signal.h>

#include <list>
#include <string>
#include <vector>

#include "base/copyright.hh"
#include "base/embedfile.hh"
#include "base/inifile.hh"
#include "base/misc.hh"
#include "base/output.hh"
#include "base/pollevent.hh"
#include "base/statistics.hh"
#include "base/str.hh"
#include "base/time.hh"
#include "cpu/base_cpu.hh"
#include "cpu/full_cpu/smt.hh"
#include "sim/async.hh"
#include "sim/builder.hh"
#include "sim/configfile.hh"
#include "sim/host.hh"
#include "sim/sim_events.hh"
#include "sim/sim_exit.hh"
#include "sim/sim_object.hh"
#include "sim/stat_control.hh"
#include "sim/stats.hh"
#include "sim/universe.hh"
#include "sim/pyconfig/pyconfig.hh"

using namespace std;

// See async.h.
volatile bool async_event = false;
volatile bool async_dump = false;
volatile bool async_dumpreset = false;
volatile bool async_exit = false;
volatile bool async_io = false;
volatile bool async_alarm = false;

/// Stats signal handler.
void
dumpStatsHandler(int sigtype)
{
    async_event = true;
    async_dump = true;
}

void
dumprstStatsHandler(int sigtype)
{
    async_event = true;
    async_dumpreset = true;
}

/// Exit signal handler.
void
exitNowHandler(int sigtype)
{
    async_event = true;
    async_exit = true;
}

/// Abort signal handler.
void
abortHandler(int sigtype)
{
    cerr << "Program aborted at cycle " << curTick << endl;

#if TRACING_ON
    // dump trace buffer, if there is one
    Trace::theLog.dump(cerr);
#endif
}

/// Simulator executable name
const char *myProgName = "";

/// Show brief help message.
void
showBriefHelp(ostream &out)
{
    char *prog = basename(myProgName);

    ccprintf(out, "Usage:\n");
    ccprintf(out,
"%s [-d <dir>] [-E <var>[=<val>]] [-I <dir>] [-P <python>]\n"
"        [--<var>=<val>] <config file>\n"
"\n"
"   -d            set the output directory to <dir>\n"
"   -E            set the environment variable <var> to <val> (or 'True')\n"
"   -I            add the directory <dir> to python's path\n"
"   -P            execute <python> directly in the configuration\n"
"   --var=val     set the python variable <var> to '<val>'\n"
"   <configfile>  config file name (.py or .mpy)\n",
             prog);

    ccprintf(out, "%s -X\n    -X            extract embedded files\n", prog);
    ccprintf(out, "%s -h\n    -h            print long help\n", prog);
}

/// Show verbose help message.  Includes parameter listing from
/// showBriefHelp(), plus an exhaustive list of ini-file parameters
/// and SimObjects (with their parameters).
void
showLongHelp(ostream &out)
{
    showBriefHelp(out);

    out << endl
        << endl
        << "-----------------" << endl
        << "Global Parameters" << endl
        << "-----------------" << endl
        << endl;

    ParamContext::describeAllContexts(out);

    out << endl
        << endl
        << "-----------------" << endl
        << "Simulator Objects" << endl
        << "-----------------" << endl
        << endl;

    SimObjectClass::describeAllClasses(out);
}

/// Print welcome message.
void
sayHello(ostream &out)
{
    extern const char *compileDate;	// from date.cc

    ccprintf(out, "M5 Simulator System\n");
    // display copyright
    ccprintf(out, "%s\n", briefCopyright);
    ccprintf(out, "M5 compiled on %d\n", compileDate);

    char *host = getenv("HOSTNAME");
    if (!host)
        host = getenv("HOST");

    if (host)
        ccprintf(out, "M5 executing on %s\n", host);

    ccprintf(out, "M5 simulation started %s\n", Time::start);
}

///
/// Echo the command line for posterity in such a way that it can be
/// used to rerun the same simulation (given the same .ini files).
///
void
echoCommandLine(int argc, char **argv, ostream &out)
{
    out << "command line: " << argv[0];
    for (int i = 1; i < argc; i++) {
        string arg(argv[i]);

        out << ' ';

        // If the arg contains spaces, we need to quote it.
        // The rest of this is overkill to make it look purty.

        // print dashes first outside quotes
        int non_dash_pos = arg.find_first_not_of("-");
        out << arg.substr(0, non_dash_pos);	// print dashes
        string body = arg.substr(non_dash_pos);	// the rest

        // if it's an assignment, handle the lhs & rhs separately
        int eq_pos = body.find("=");
        if (eq_pos == string::npos) {
            out << quote(body);
        }
        else {
            string lhs(body.substr(0, eq_pos));
            string rhs(body.substr(eq_pos + 1));

            out << quote(lhs) << "=" << quote(rhs);
        }
    }
    out << endl << endl;
}

char *
getOptionString(int &index, int argc, char **argv)
{
    char *option = argv[index] + 2;
    if (*option != '\0')
        return option;

    // We didn't find an argument, it must be in the next variable.
    if (++index >= argc)
        panic("option string for option '%s' not found", argv[index - 1]);

    return argv[index];
}

int
main(int argc, char **argv)
{
    // Save off program name
    myProgName = argv[0];

    signal(SIGFPE, SIG_IGN);		// may occur on misspeculated paths
    signal(SIGTRAP, SIG_IGN);
    signal(SIGUSR1, dumpStatsHandler);		// dump intermediate stats
    signal(SIGUSR2, dumprstStatsHandler);	// dump and reset stats
    signal(SIGINT, exitNowHandler);		// dump final stats and exit
    signal(SIGABRT, abortHandler);

    sayHello(cerr);

    bool configfile_found = false;
    PythonConfig pyconfig;
    string outdir;

    // Parse command-line options.
    // Since most of the complex options are handled through the
    // config database, we don't mess with getopts, and just parse
    // manually.
    for (int i = 1; i < argc; ++i) {
        char *arg_str = argv[i];

        // if arg starts with '--', parse as a special python option
        // of the format --<python var>=<string value>, if the arg
        // starts with '-', it should be a simulator option with a
        // format similar to getopt.  In any other case, treat the
        // option as a configuration file name and load it.
        if (arg_str[0] == '-' && arg_str[1] == '-') {
            string str = &arg_str[2];
            string var, val;

            if (!split_first(str, var, val, '='))
                panic("Could not parse configuration argument '%s'\n"
                      "Expecting --<variable>=<value>\n", arg_str);

            pyconfig.setVariable(var, val);
        } else if (arg_str[0] == '-') {
            char *option;
            string var, val;

            // switch on second char
            switch (arg_str[1]) {
              case 'd':
                outdir = getOptionString(i, argc, argv);
                break;

              case 'h':
                showLongHelp(cerr);
                exit(1);

              case 'E':
                option = getOptionString(i, argc, argv);
                if (!split_first(option, var, val, '='))
                    val = "True";

                if (setenv(var.c_str(), val.c_str(), true) == -1)
                    panic("setenv: %s\n", strerror(errno));
                break;

              case 'I':
                option = getOptionString(i, argc, argv);
                pyconfig.addPath(option);
                break;

              case 'P':
                option = getOptionString(i, argc, argv);
                pyconfig.writeLine(option);
                break;

              case 'X': {
                  list<EmbedFile> lst;
                  EmbedMap::all(lst);
                  list<EmbedFile>::iterator i = lst.begin();
                  list<EmbedFile>::iterator end = lst.end();

                  while (i != end) {
                      cprintf("Embedded File: %s\n", i->name);
                      cout.write(i->data, i->length);
                      ++i;
                  }

                  return 0;
              }

              default:
                showBriefHelp(cerr);
                panic("invalid argument '%s'\n", arg_str);
            }
        } else {
            string file(arg_str);
            string base, ext;

            if (!split_last(file, base, ext, '.') ||
                ext != "py" && ext != "mpy")
                panic("Config file '%s' must end in '.py' or '.mpy'\n", file);

            pyconfig.load(file);
            configfile_found = true;
        }
    }

    if (outdir.empty()) {
        char *env = getenv("OUTPUT_DIR");
        outdir = env ? env : ".";
    }

    simout.setDirectory(outdir);

    char *env = getenv("CONFIG_OUTPUT");
    if (!env)
        env = "config.out";
    configStream = simout.find(env);

    if (!configfile_found)
        panic("no configuration file specified!");

    // The configuration database is now complete; start processing it.
    IniFile inifile;
    if (!pyconfig.output(inifile))
        panic("Error processing python code");

    // Initialize statistics database
    Stats::InitSimStats();

    // Now process the configuration hierarchy and create the SimObjects.
    ConfigHierarchy configHierarchy(inifile);
    configHierarchy.build();
    configHierarchy.createSimObjects();

    // Parse and check all non-config-hierarchy parameters.
    ParamContext::parseAllContexts(inifile);
    ParamContext::checkAllContexts();

    // Print hello message to stats file if it's actually a file.  If
    // it's not (i.e. it's cout or cerr) then we already did it above.
    if (simout.isFile(*outputStream))
        sayHello(*outputStream);

    // Echo command line and all parameter settings to stats file as well.
    echoCommandLine(argc, argv, *outputStream);
    ParamContext::showAllContexts(*configStream);

    // Do a second pass to finish initializing the sim objects
    SimObject::initAll();

    // Restore checkpointed state, if any.
    configHierarchy.unserializeSimObjects();

    // Done processing the configuration database.
    // Check for unreferenced entries.
    if (inifile.printUnreferenced())
        panic("unreferenced sections/entries in the intermediate ini file");

    SimObject::regAllStats();

    // uncomment the following to get PC-based execution-time profile
#ifdef DO_PROFILE
    init_profile((char *)&_init, (char *)&_fini);
#endif

    // Check to make sure that the stats package is properly initialized
    Stats::check();

    // Reset to put the stats in a consistent state.
    Stats::reset();

    // Nothing to simulate if we don't have at least one CPU somewhere.
    if (BaseCPU::numSimulatedCPUs() == 0) {
        cerr << "Fatal: no CPUs to simulate." << endl;
        exit(1);
    }

    warn("Entering event queue.  Starting simulation...\n");
    SimStartup();
    while (!mainEventQueue.empty()) {
        assert(curTick <= mainEventQueue.nextTick() &&
               "event scheduled in the past");

        // forward current cycle to the time of the first event on the
        // queue
        curTick = mainEventQueue.nextTick();
        mainEventQueue.serviceOne();

        if (async_event) {
            async_event = false;
            if (async_dump) {
                async_dump = false;

                using namespace Stats;
                SetupEvent(Dump, curTick);
            }

            if (async_dumpreset) {
                async_dumpreset = false;

                using namespace Stats;
                SetupEvent(Dump | Reset, curTick);
            }

            if (async_exit) {
                async_exit = false;
                new SimExitEvent("User requested STOP");
            }

            if (async_io || async_alarm) {
                async_io = false;
                async_alarm = false;
                pollQueue.service();
            }
        }
    }

    // This should never happen... every conceivable way for the
    // simulation to terminate (hit max cycles/insts, signal,
    // simulated system halts/exits) generates an exit event, so we
    // should never run out of events on the queue.
    exitNow("no events on event loop!  All CPUs must be idle.", 1);

    return 0;
}
<commit_msg>Fix compile on linux<commit_after>/*
 * Copyright (c) 2000-2004 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

///
/// @file sim/main.cc
///
#include <sys/types.h>
#include <sys/stat.h>
#include <libgen.h>
#include <stdlib.h>
#include <signal.h>

#include <list>
#include <string>
#include <vector>

#include "base/copyright.hh"
#include "base/embedfile.hh"
#include "base/inifile.hh"
#include "base/misc.hh"
#include "base/output.hh"
#include "base/pollevent.hh"
#include "base/statistics.hh"
#include "base/str.hh"
#include "base/time.hh"
#include "cpu/base_cpu.hh"
#include "cpu/full_cpu/smt.hh"
#include "sim/async.hh"
#include "sim/builder.hh"
#include "sim/configfile.hh"
#include "sim/host.hh"
#include "sim/sim_events.hh"
#include "sim/sim_exit.hh"
#include "sim/sim_object.hh"
#include "sim/stat_control.hh"
#include "sim/stats.hh"
#include "sim/universe.hh"
#include "sim/pyconfig/pyconfig.hh"

using namespace std;

// See async.h.
volatile bool async_event = false;
volatile bool async_dump = false;
volatile bool async_dumpreset = false;
volatile bool async_exit = false;
volatile bool async_io = false;
volatile bool async_alarm = false;

/// Stats signal handler.
void
dumpStatsHandler(int sigtype)
{
    async_event = true;
    async_dump = true;
}

void
dumprstStatsHandler(int sigtype)
{
    async_event = true;
    async_dumpreset = true;
}

/// Exit signal handler.
void
exitNowHandler(int sigtype)
{
    async_event = true;
    async_exit = true;
}

/// Abort signal handler.
void
abortHandler(int sigtype)
{
    cerr << "Program aborted at cycle " << curTick << endl;

#if TRACING_ON
    // dump trace buffer, if there is one
    Trace::theLog.dump(cerr);
#endif
}

/// Simulator executable name
char *myProgName = "";

/// Show brief help message.
void
showBriefHelp(ostream &out)
{
    char *prog = basename(myProgName);

    ccprintf(out, "Usage:\n");
    ccprintf(out,
"%s [-d <dir>] [-E <var>[=<val>]] [-I <dir>] [-P <python>]\n"
"        [--<var>=<val>] <config file>\n"
"\n"
"   -d            set the output directory to <dir>\n"
"   -E            set the environment variable <var> to <val> (or 'True')\n"
"   -I            add the directory <dir> to python's path\n"
"   -P            execute <python> directly in the configuration\n"
"   --var=val     set the python variable <var> to '<val>'\n"
"   <configfile>  config file name (.py or .mpy)\n",
             prog);

    ccprintf(out, "%s -X\n    -X            extract embedded files\n", prog);
    ccprintf(out, "%s -h\n    -h            print long help\n", prog);
}

/// Show verbose help message.  Includes parameter listing from
/// showBriefHelp(), plus an exhaustive list of ini-file parameters
/// and SimObjects (with their parameters).
void
showLongHelp(ostream &out)
{
    showBriefHelp(out);

    out << endl
        << endl
        << "-----------------" << endl
        << "Global Parameters" << endl
        << "-----------------" << endl
        << endl;

    ParamContext::describeAllContexts(out);

    out << endl
        << endl
        << "-----------------" << endl
        << "Simulator Objects" << endl
        << "-----------------" << endl
        << endl;

    SimObjectClass::describeAllClasses(out);
}

/// Print welcome message.
void
sayHello(ostream &out)
{
    extern const char *compileDate;	// from date.cc

    ccprintf(out, "M5 Simulator System\n");
    // display copyright
    ccprintf(out, "%s\n", briefCopyright);
    ccprintf(out, "M5 compiled on %d\n", compileDate);

    char *host = getenv("HOSTNAME");
    if (!host)
        host = getenv("HOST");

    if (host)
        ccprintf(out, "M5 executing on %s\n", host);

    ccprintf(out, "M5 simulation started %s\n", Time::start);
}

///
/// Echo the command line for posterity in such a way that it can be
/// used to rerun the same simulation (given the same .ini files).
///
void
echoCommandLine(int argc, char **argv, ostream &out)
{
    out << "command line: " << argv[0];
    for (int i = 1; i < argc; i++) {
        string arg(argv[i]);

        out << ' ';

        // If the arg contains spaces, we need to quote it.
        // The rest of this is overkill to make it look purty.

        // print dashes first outside quotes
        int non_dash_pos = arg.find_first_not_of("-");
        out << arg.substr(0, non_dash_pos);	// print dashes
        string body = arg.substr(non_dash_pos);	// the rest

        // if it's an assignment, handle the lhs & rhs separately
        int eq_pos = body.find("=");
        if (eq_pos == string::npos) {
            out << quote(body);
        }
        else {
            string lhs(body.substr(0, eq_pos));
            string rhs(body.substr(eq_pos + 1));

            out << quote(lhs) << "=" << quote(rhs);
        }
    }
    out << endl << endl;
}

char *
getOptionString(int &index, int argc, char **argv)
{
    char *option = argv[index] + 2;
    if (*option != '\0')
        return option;

    // We didn't find an argument, it must be in the next variable.
    if (++index >= argc)
        panic("option string for option '%s' not found", argv[index - 1]);

    return argv[index];
}

int
main(int argc, char **argv)
{
    // Save off program name
    myProgName = argv[0];

    signal(SIGFPE, SIG_IGN);		// may occur on misspeculated paths
    signal(SIGTRAP, SIG_IGN);
    signal(SIGUSR1, dumpStatsHandler);		// dump intermediate stats
    signal(SIGUSR2, dumprstStatsHandler);	// dump and reset stats
    signal(SIGINT, exitNowHandler);		// dump final stats and exit
    signal(SIGABRT, abortHandler);

    sayHello(cerr);

    bool configfile_found = false;
    PythonConfig pyconfig;
    string outdir;

    // Parse command-line options.
    // Since most of the complex options are handled through the
    // config database, we don't mess with getopts, and just parse
    // manually.
    for (int i = 1; i < argc; ++i) {
        char *arg_str = argv[i];

        // if arg starts with '--', parse as a special python option
        // of the format --<python var>=<string value>, if the arg
        // starts with '-', it should be a simulator option with a
        // format similar to getopt.  In any other case, treat the
        // option as a configuration file name and load it.
        if (arg_str[0] == '-' && arg_str[1] == '-') {
            string str = &arg_str[2];
            string var, val;

            if (!split_first(str, var, val, '='))
                panic("Could not parse configuration argument '%s'\n"
                      "Expecting --<variable>=<value>\n", arg_str);

            pyconfig.setVariable(var, val);
        } else if (arg_str[0] == '-') {
            char *option;
            string var, val;

            // switch on second char
            switch (arg_str[1]) {
              case 'd':
                outdir = getOptionString(i, argc, argv);
                break;

              case 'h':
                showLongHelp(cerr);
                exit(1);

              case 'E':
                option = getOptionString(i, argc, argv);
                if (!split_first(option, var, val, '='))
                    val = "True";

                if (setenv(var.c_str(), val.c_str(), true) == -1)
                    panic("setenv: %s\n", strerror(errno));
                break;

              case 'I':
                option = getOptionString(i, argc, argv);
                pyconfig.addPath(option);
                break;

              case 'P':
                option = getOptionString(i, argc, argv);
                pyconfig.writeLine(option);
                break;

              case 'X': {
                  list<EmbedFile> lst;
                  EmbedMap::all(lst);
                  list<EmbedFile>::iterator i = lst.begin();
                  list<EmbedFile>::iterator end = lst.end();

                  while (i != end) {
                      cprintf("Embedded File: %s\n", i->name);
                      cout.write(i->data, i->length);
                      ++i;
                  }

                  return 0;
              }

              default:
                showBriefHelp(cerr);
                panic("invalid argument '%s'\n", arg_str);
            }
        } else {
            string file(arg_str);
            string base, ext;

            if (!split_last(file, base, ext, '.') ||
                ext != "py" && ext != "mpy")
                panic("Config file '%s' must end in '.py' or '.mpy'\n", file);

            pyconfig.load(file);
            configfile_found = true;
        }
    }

    if (outdir.empty()) {
        char *env = getenv("OUTPUT_DIR");
        outdir = env ? env : ".";
    }

    simout.setDirectory(outdir);

    char *env = getenv("CONFIG_OUTPUT");
    if (!env)
        env = "config.out";
    configStream = simout.find(env);

    if (!configfile_found)
        panic("no configuration file specified!");

    // The configuration database is now complete; start processing it.
    IniFile inifile;
    if (!pyconfig.output(inifile))
        panic("Error processing python code");

    // Initialize statistics database
    Stats::InitSimStats();

    // Now process the configuration hierarchy and create the SimObjects.
    ConfigHierarchy configHierarchy(inifile);
    configHierarchy.build();
    configHierarchy.createSimObjects();

    // Parse and check all non-config-hierarchy parameters.
    ParamContext::parseAllContexts(inifile);
    ParamContext::checkAllContexts();

    // Print hello message to stats file if it's actually a file.  If
    // it's not (i.e. it's cout or cerr) then we already did it above.
    if (simout.isFile(*outputStream))
        sayHello(*outputStream);

    // Echo command line and all parameter settings to stats file as well.
    echoCommandLine(argc, argv, *outputStream);
    ParamContext::showAllContexts(*configStream);

    // Do a second pass to finish initializing the sim objects
    SimObject::initAll();

    // Restore checkpointed state, if any.
    configHierarchy.unserializeSimObjects();

    // Done processing the configuration database.
    // Check for unreferenced entries.
    if (inifile.printUnreferenced())
        panic("unreferenced sections/entries in the intermediate ini file");

    SimObject::regAllStats();

    // uncomment the following to get PC-based execution-time profile
#ifdef DO_PROFILE
    init_profile((char *)&_init, (char *)&_fini);
#endif

    // Check to make sure that the stats package is properly initialized
    Stats::check();

    // Reset to put the stats in a consistent state.
    Stats::reset();

    // Nothing to simulate if we don't have at least one CPU somewhere.
    if (BaseCPU::numSimulatedCPUs() == 0) {
        cerr << "Fatal: no CPUs to simulate." << endl;
        exit(1);
    }

    warn("Entering event queue.  Starting simulation...\n");
    SimStartup();
    while (!mainEventQueue.empty()) {
        assert(curTick <= mainEventQueue.nextTick() &&
               "event scheduled in the past");

        // forward current cycle to the time of the first event on the
        // queue
        curTick = mainEventQueue.nextTick();
        mainEventQueue.serviceOne();

        if (async_event) {
            async_event = false;
            if (async_dump) {
                async_dump = false;

                using namespace Stats;
                SetupEvent(Dump, curTick);
            }

            if (async_dumpreset) {
                async_dumpreset = false;

                using namespace Stats;
                SetupEvent(Dump | Reset, curTick);
            }

            if (async_exit) {
                async_exit = false;
                new SimExitEvent("User requested STOP");
            }

            if (async_io || async_alarm) {
                async_io = false;
                async_alarm = false;
                pollQueue.service();
            }
        }
    }

    // This should never happen... every conceivable way for the
    // simulation to terminate (hit max cycles/insts, signal,
    // simulated system halts/exits) generates an exit event, so we
    // should never run out of events on the queue.
    exitNow("no events on event loop!  All CPUs must be idle.", 1);

    return 0;
}
<|endoftext|>


<commit_before>#include "xchainer/array_fill.h"

#include "xchainer/array.h"
#include "xchainer/dtype.h"
#include "xchainer/scalar.h"

namespace xchainer {

void Fill(Array& out, Scalar value) {
    VisitDtype(out.dtype(), [&](auto pt) {
        using T = typename decltype(pt)::type;
        auto c_value = static_cast<T>(value);

        int64_t size = out.total_size();
        auto ptr = static_cast<T*>(out.data().get());
        for (int64_t i = 0; i < size; ++i) {
            ptr[i] = c_value;
        }
    });
}

}  // namespace xchainer
<commit_msg>auto -> auto*<commit_after>#include "xchainer/array_fill.h"

#include "xchainer/array.h"
#include "xchainer/dtype.h"
#include "xchainer/scalar.h"

namespace xchainer {

void Fill(Array& out, Scalar value) {
    VisitDtype(out.dtype(), [&](auto pt) {
        using T = typename decltype(pt)::type;
        auto c_value = static_cast<T>(value);

        int64_t size = out.total_size();
        auto* ptr = static_cast<T*>(out.data().get());
        for (int64_t i = 0; i < size; ++i) {
            ptr[i] = c_value;
        }
    });
}

}  // namespace xchainer
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/fnet/frt/frt.h>
#include <vespa/fastos/app.h>

#include <sstream>

#include <vespa/log/log.h>
LOG_SETUP("vespa-ping-configproxy");

class PingProxy : public FastOS_Application
{
private:
    std::unique_ptr<fnet::frt::StandaloneFRT> _server;
    FRT_Target     *_target;

    PingProxy(const PingProxy &);
    PingProxy &operator=(const PingProxy &);

public:
    PingProxy() : _server(), _target(nullptr) {}
    virtual ~PingProxy();
    int usage();
    void initRPC(const char *spec);
    void finiRPC();
    int Main() override;
};

PingProxy::~PingProxy()
{
    LOG_ASSERT(!_server);
    LOG_ASSERT(_target == nullptr);
}

int
PingProxy::usage()
{
    fprintf(stderr, "usage: %s\n", _argv[0]);
    fprintf(stderr, "-s [server]        (server hostname, default localhost)\n");
    fprintf(stderr, "-p [port]          (server port number, default 19090)\n");
    return 1;
}

void
PingProxy::initRPC(const char *spec)
{
    _server = std::make_unique<fnet::frt::StandaloneFRT>();
    _target     = _server->supervisor().GetTarget(spec);
}

void
PingProxy::finiRPC()
{
    if (_target != nullptr) {
        _target->SubRef();
        _target = nullptr;
    }
    _server.reset();
}

int
PingProxy::Main()
{
    int retval = 0;
    bool debugging = false;
    char c = -1;

    const char *serverHost = "localhost";
    int clientTimeout = 5;
    int serverPort = 19090;

    const char *optArg = nullptr;
    int optInd = 0;
    while ((c = GetOpt("w:s:p:dh", optArg, optInd)) != -1) {
        switch (c) {
        case 'w':
            clientTimeout = atoi(optArg);
            break;
        case 's':
            serverHost = optArg;
            break;
        case 'p':
            serverPort = atoi(optArg);
            break;
        case 'd':
            debugging = true;
            break;
        case '?':
        default:
            retval = 1;
            [[fallthrough]];
        case 'h':
            usage();
            return retval;
        }
    }

    if (serverPort == 0) {
        usage();
        return 1;
    }

    std::ostringstream tmp;
    tmp << "tcp/";
    tmp << serverHost;
    tmp << ":";
    tmp << serverPort;
    std::string sspec = tmp.str();
    const char *spec = sspec.c_str();
    if (debugging) {
        printf("connecting to '%s'\n", spec);
        LOG(info, "connecting to '%s'\n", spec);
    }
    try {
        initRPC(spec);
    } catch (std::exception& ex) {
        LOG(error, "Got exception while initializing RPC: '%s'", ex.what());
        return 1;
    }

    FRT_RPCRequest *req = _server->supervisor().AllocRPCRequest();

    req->SetMethodName("ping");

    _target->InvokeSync(req, clientTimeout); // seconds

    if (req->IsError()) {
        retval = 1;
        fprintf(stderr, "error %d: %s\n",
                req->GetErrorCode(), req->GetErrorMessage());
    } else {
        FRT_Values &answer = *(req->GetReturn());
        const char *atypes = answer.GetTypeString();
        if (strcmp(atypes, "i") == 0) {
            if (debugging) {
                printf("ping %d\n", answer[0]._intval32);
            }
        } else {
            fprintf(stderr, "unexpected return types in RPC answer: '%s'\n", atypes);
            retval = 1;
        }
    }
    finiRPC();
    return retval;
}

int main(int argc, char **argv)
{
    PingProxy app;
    return app.Entry(argc, argv);
}
<commit_msg>Invoke SubRef on RPC request before exiting process<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include <vespa/fnet/frt/frt.h>
#include <vespa/fastos/app.h>

#include <sstream>

#include <vespa/log/log.h>
LOG_SETUP("vespa-ping-configproxy");

class PingProxy : public FastOS_Application
{
private:
    std::unique_ptr<fnet::frt::StandaloneFRT> _server;
    FRT_Target     *_target;

    PingProxy(const PingProxy &);
    PingProxy &operator=(const PingProxy &);

public:
    PingProxy() : _server(), _target(nullptr) {}
    virtual ~PingProxy();
    int usage();
    void initRPC(const char *spec);
    void finiRPC();
    int Main() override;
};

PingProxy::~PingProxy()
{
    LOG_ASSERT(!_server);
    LOG_ASSERT(_target == nullptr);
}

int
PingProxy::usage()
{
    fprintf(stderr, "usage: %s\n", _argv[0]);
    fprintf(stderr, "-s [server]        (server hostname, default localhost)\n");
    fprintf(stderr, "-p [port]          (server port number, default 19090)\n");
    return 1;
}

void
PingProxy::initRPC(const char *spec)
{
    _server = std::make_unique<fnet::frt::StandaloneFRT>();
    _target     = _server->supervisor().GetTarget(spec);
}

void
PingProxy::finiRPC()
{
    if (_target != nullptr) {
        _target->SubRef();
        _target = nullptr;
    }
    _server.reset();
}

int
PingProxy::Main()
{
    int retval = 0;
    bool debugging = false;
    char c = -1;

    const char *serverHost = "localhost";
    int clientTimeout = 5;
    int serverPort = 19090;

    const char *optArg = nullptr;
    int optInd = 0;
    while ((c = GetOpt("w:s:p:dh", optArg, optInd)) != -1) {
        switch (c) {
        case 'w':
            clientTimeout = atoi(optArg);
            break;
        case 's':
            serverHost = optArg;
            break;
        case 'p':
            serverPort = atoi(optArg);
            break;
        case 'd':
            debugging = true;
            break;
        case '?':
        default:
            retval = 1;
            [[fallthrough]];
        case 'h':
            usage();
            return retval;
        }
    }

    if (serverPort == 0) {
        usage();
        return 1;
    }

    std::ostringstream tmp;
    tmp << "tcp/";
    tmp << serverHost;
    tmp << ":";
    tmp << serverPort;
    std::string sspec = tmp.str();
    const char *spec = sspec.c_str();
    if (debugging) {
        printf("connecting to '%s'\n", spec);
        LOG(info, "connecting to '%s'\n", spec);
    }
    try {
        initRPC(spec);
    } catch (std::exception& ex) {
        LOG(error, "Got exception while initializing RPC: '%s'", ex.what());
        return 1;
    }

    FRT_RPCRequest *req = _server->supervisor().AllocRPCRequest();

    req->SetMethodName("ping");

    _target->InvokeSync(req, clientTimeout); // seconds

    if (req->IsError()) {
        retval = 1;
        fprintf(stderr, "error %d: %s\n",
                req->GetErrorCode(), req->GetErrorMessage());
    } else {
        FRT_Values &answer = *(req->GetReturn());
        const char *atypes = answer.GetTypeString();
        if (strcmp(atypes, "i") == 0) {
            if (debugging) {
                printf("ping %d\n", answer[0]._intval32);
            }
        } else {
            fprintf(stderr, "unexpected return types in RPC answer: '%s'\n", atypes);
            retval = 1;
        }
    }
    req->SubRef();
    finiRPC();
    return retval;
}

int main(int argc, char **argv)
{
    PingProxy app;
    return app.Entry(argc, argv);
}
<|endoftext|>


<commit_before>#pragma once

#include <stdint.h>
#include <vector>
#include <boost/optional.hpp>
#include <boost/array.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <QColor>
#include <Eigen/Geometry>
#include <Constants.hpp>
#include <planning/Path.hpp>
#include <planning/RRTPlanner.hpp>
#include <protobuf/RadioTx.pb.h>
#include <protobuf/RadioRx.pb.h>

class SystemState;
class RobotConfig;
class RobotStatus;
class MotionControl;
class RobotFilter;

namespace Packet
{
	class DebugText;
	class LogFrame_Robot;
};

namespace Gameplay
{
	class GameplayModule;
	class Behavior;
}

namespace Planning
{
	class RRTPlanner;
}

/**
 * @brief Contains robot motion state data
 * @details This class contains data that comes from the vision system
 * including position data and which camera this robot was seen by and
 * what time it was last seen.
 */
class RobotPose
{
public:
	RobotPose():
		visible(false),
		angle(0),
		angleVel(0),
		time(0),
		visionFrame(0)
	{
	}

	bool visible;
	Geometry2d::Point pos;
	Geometry2d::Point vel;
	float angle;
	float angleVel;

	// Time at which this estimate is valid
	uint64_t time;
	int visionFrame;
};

class Robot: public RobotPose
{
public:
	Robot(unsigned int shell, bool self);
	~Robot();

	/**
	 * ID number for the robot.  This is the number that the dot pattern on the
	 * top of the robot represents
	 */
	unsigned int shell() const
	{
		return _shell;
	}

	/**
	 * Check whether or not this robot is on our team
	 */
	bool self() const
	{
		return _self;
	}

	/**
	 * Get the robot's position filter.
	 */
	RobotFilter *filter() const
	{
		return _filter;
	}

	bool operator==(const Robot &other) {
		return shell() == other.shell();
	}

private:
	unsigned int _shell;
	bool _self;
	RobotFilter *_filter;
};

/**
 * This class contains the motion constraints that the high-level logic sets for a robot.
 * For position: set EITHER @motionTarget OR @targetWorldVel.
 * For angle: set EITHER @targetAngleVel OR @faceTarget.
 */
struct MotionConstraints {

	/**
	 * Position
	 */

	///	A point on the field that the robot should use path-planning to get to
	boost::optional<Geometry2d::Point> targetPos;

	/// Set the velocity in world coordinates directly (circumvents path planning)
	boost::optional<Geometry2d::Point> targetWorldVel;

	/**
	 * Angle
	 */

	/// Angular velocity in rad/s counterclockwise
	boost::optional<float> targetAngleVel;

	///	A global point on the field that the robot should face towards
	boost::optional<Geometry2d::Point> faceTarget;
};

/**
 * @brief A robot on our team
 * @details This extends Robot and provides methods for interacting with our robots.
 * A few things this class is responsible for:
 * - specifying target position, velocity, angle, etc
 * - kicking and chipping the ball
 * - keeping track of which hardware revision this bot is
 * - avoidance of the ball and other robots (this info is fed to the path planner)
 * - playing the GT fight song
 */
class OurRobot: public Robot {
public:
	typedef boost::array<float,Num_Shells> RobotMask;

	RobotConfig *config;
	RobotStatus *status;

	/**
	 * @brief Construct a new OurRobot
	 * @param shell The robot ID
	 * @param state A pointer to the global system state object
	 */
	OurRobot(int shell, SystemState *state);
	~OurRobot();

	void addStatusText();

	void addText(const QString &text, const QColor &color = Qt::white, const QString &layerPrefix = "RobotText");

	// kicker readiness checks
	bool charged() const; /// true if the kicker is ready
	float kickTimer() const; /// returns the time since the kicker was last charged, 0.0 if ready

	/**
	 * state variable updates - includes timers, etc.  Called each frame
	 */
	//FIXME - Remove
	void update();

	const Geometry2d::Segment kickerBar() const; /// segment for the location of the kicker
	Geometry2d::Point pointInRobotSpace(const Geometry2d::Point& pt) const; /// converts a point to the frame of reference of robot

	// simple checks to do geometry
	/** returns true if the position specified is behind the robot */
	//FIXME - Function name and comment don't match
	bool behindBall(const Geometry2d::Point& ballPos) const;

	// Gets the robot quaternion.  Returns false (and does not change q) if not available.
	boost::optional<Eigen::Quaternionf> quaternion() const;

	// Commands

	const MotionConstraints &motionConstraints() const {
		return _motionConstraints;
	}

	const boost::optional<Planning::Path> &path() const {
		return _path;
	}

	//  FIXME: document
	void setPath(Planning::Path path);

	//	FIXME: document
	void setMotionConstraints(const MotionConstraints &constraints);

	///	clears old radioTx stuff, resets robot debug text, and clears local obstacles
	void resetForNextIteration();

	///	clears all fields in the robot's MotionConstraints object, causing the robot to stop
	void resetMotionConstraints();

	/** Stop the robot */
	void stop();

	/**
	 * @brief Move to a given point using the default RRT planner
	 * @param stopAtEnd UNUSED
	 */
	void move(const Geometry2d::Point &goal, bool stopAtEnd = false);

	uint64_t pathStartTime() const {
		return _pathStartTime;
	}

	/**
	 * Sets the worldVelocity in the robot's MotionConstraints
	 */
	void worldVelocity(const Geometry2d::Point &targetWorldVel);

	/*
	 * Enable dribbler (0 to 127)
	 */
	void dribble(int8_t speed);

	/**
	 * Face a point while remaining in place
	 */
	void face(const Geometry2d::Point &pt);

	/**
	 * Remove the facing command
	 */
	void faceNone();

	/**
	 * enable kick when ready at a given strength
	 */
	void kick(uint8_t strength);

	/**
	 * enable chip when ready at a given strength
	 */
	void chip(uint8_t strength);

	/**
	 * ignore ball sense and kick immediately
	 */
	void immediate(bool im);

	boost::ptr_vector<Packet::DebugText> robotText;

	// True if this robot will treat opponents as obstacles
	// Set to false for defenders to avoid being herded
	bool avoidOpponents() const;
	void avoidOpponents(bool enable);

	// Add a custom radius avoidance of the ball
	// creates an obstacle around the ball
	// if radius is 0 or less, it disables avoidance
	void disableAvoidBall();
	void avoidBallRadius(float radius);
	float avoidBallRadius() const;
	void resetAvoidBall();	//	sets avoid ball radius to Ball_Avoid_Small

	/**
	 * Adds an obstacle to the local set of obstacles for avoidance
	 * Cleared after every frame
	 */
	void localObstacles(const ObstaclePtr& obs) { _local_obstacles.add(obs); }
	void localObstacles(const ObstacleGroup& obs) { _local_obstacles.add(obs); }
	const ObstacleGroup& localObstacles() const { return _local_obstacles; }
	void clearLocalObstacles() { _local_obstacles.clear(); }

	// opponent approach interface

	void approachAllOpponents(bool enable = true);
	void avoidAllOpponents(bool enable = true);

	/** checks if opponents are avoided at all */
	bool avoidOpponent(unsigned shell_id) const;

	/** @return true if we are able to approach the given opponent */
	bool approachOpponent(unsigned shell_id) const;

	/** returns the avoidance radius */
	float avoidOpponentRadius(unsigned shell_id) const;

	/** returns the avoidance radius */
	void avoidAllOpponentRadius(float radius);

	/** enable/disable for opponent avoidance */
	void avoidOpponent(unsigned shell_id, bool enable_avoid);

	/** enable/disable approach of opponents - diable uses larger avoidance radius */
	void approachOpponent(unsigned shell_id, bool enable_approach);

	void avoidOpponentRadius(unsigned shell_id, float radius);

	// self approach interface

	/** determines whether a robot will avoid another robot when it plans - use for priority */

	void avoidAllTeammates(bool enable = true);
	void avoidTeammate(unsigned shell_id, bool enable = true);
	void avoidTeammateRadius(unsigned shell_id, float radius);
	bool avoidTeammate(unsigned shell_id) const;
	float avoidTeammateRadius(unsigned shell_id) const;

	// gameplay interface - interface for delayed update/planning

	/**
	 * Executes last motion command, retrieves the necessary set of
	 * obstacles, and performs planning
	 *
	 * Needs a set of global obstacles to use - assuming field regions and goal
	 */
	//	FIXME: rewrite comment to describe new behavior
	void replanIfNeeded(const ObstacleGroup& global_obstacles);

	/** status evaluations for choosing robots in behaviors - combines multiple checks */
	bool chipper_available() const;
	bool kicker_available() const;
	bool dribbler_available() const;
	bool driving_available(bool require_all = true) const; // checks for motor faults - allows one wheel failure if require_all = false

	// lower level status checks
	bool hasBall() const;
	bool ballSenseWorks() const;
	bool kickerWorks() const;
	float kickerVoltage() const;
	Packet::HardwareVersion hardwareVersion() const;

	uint64_t lastKickTime() const;

	/** radio packets */
	Packet::RadioTx::Robot radioTx;

	void setRadioRx(Packet::RadioRx rx);

	Packet::RadioRx &radioRx() {
		return _radioRx;
	}

	MotionControl *motionControl() const
	{
		return _motionControl;
	}

	SystemState *state() const
	{
		return _state;
	}

	/**
	 * @param age Time (in microseconds) that defines non-fresh
	 */
	bool rxIsFresh(uint64_t age = 500000) const;

	/**
	 * @brief Starts the robot playing the fight song
	 */
	void sing()
	{
		addText("GO TECH!", QColor(255,0,255), "Sing");
		radioTx.set_sing(true);
	}

	/**
	 * @brief Undoes any calls to kick() or chip().
	 */
	void unkick()
	{
		kick(0);
		chip(0);
		radioTx.set_use_chipper(false);
	}

protected:
	MotionControl *_motionControl;

	SystemState *_state;

	// obstacle management
	ObstacleGroup _local_obstacles; /// set of obstacles added by plays
	RobotMask _self_avoid_mask, _opp_avoid_mask;  /// masks for obstacle avoidance
	float _avoidBallRadius; /// radius of ball obstacle

	MotionConstraints _motionConstraints;

	Planning::RRTPlanner *_planner;	/// single-robot RRT planner
	boost::optional<Planning::Path> _path;	/// latest path
	uint64_t _pathStartTime;

	///	whenever the constraints for the robot path are changed, this is set to true to trigger a replan
	bool _pathInvalidated;

	/**
	 * Creates a set of obstacles from a given robot team mask,
	 * where mask values < 0 create no obstacle, and larger values
	 * create an obstacle of a given radius
	 *
	 * NOTE: mask must not be set for this robot
	 *
	 * @param robots is the set of robots to use to create a mask - either self or opp from _state
	 */
	template<class ROBOT>
	ObstacleGroup createRobotObstacles(const std::vector<ROBOT*>& robots, const RobotMask& mask) const {
		ObstacleGroup result;
		for (size_t i=0; i<RobotMask::size(); ++i)
			if (mask[i] > 0 && robots[i] && robots[i]->visible)
				result.add(ObstaclePtr(new CircleObstacle(robots[i]->pos, mask[i])));
		return result;
	}

	/**
	 * Creates an obstacle for the ball if necessary
	 */
	ObstaclePtr createBallObstacle() const;

private:
	uint32_t _lastKickerStatus;
	uint64_t _lastKickTime;
	uint64_t _lastChargedTime;

	Packet::RadioRx _radioRx;
};

/**
 * @brief A robot that is not on our team
 * @details This is a subclass of Robot, but really doesn't provide
 * any extra functionality.
 */
class OpponentRobot: public Robot {
public:
	OpponentRobot(unsigned int shell): Robot(shell, false) {}
};
<commit_msg>improved OurRobot.unkick() a bit<commit_after>#pragma once

#include <stdint.h>
#include <vector>
#include <boost/optional.hpp>
#include <boost/array.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <QColor>
#include <Eigen/Geometry>
#include <Constants.hpp>
#include <planning/Path.hpp>
#include <planning/RRTPlanner.hpp>
#include <protobuf/RadioTx.pb.h>
#include <protobuf/RadioRx.pb.h>

class SystemState;
class RobotConfig;
class RobotStatus;
class MotionControl;
class RobotFilter;

namespace Packet
{
	class DebugText;
	class LogFrame_Robot;
};

namespace Gameplay
{
	class GameplayModule;
	class Behavior;
}

namespace Planning
{
	class RRTPlanner;
}

/**
 * @brief Contains robot motion state data
 * @details This class contains data that comes from the vision system
 * including position data and which camera this robot was seen by and
 * what time it was last seen.
 */
class RobotPose
{
public:
	RobotPose():
		visible(false),
		angle(0),
		angleVel(0),
		time(0),
		visionFrame(0)
	{
	}

	bool visible;
	Geometry2d::Point pos;
	Geometry2d::Point vel;
	float angle;
	float angleVel;

	// Time at which this estimate is valid
	uint64_t time;
	int visionFrame;
};

class Robot: public RobotPose
{
public:
	Robot(unsigned int shell, bool self);
	~Robot();

	/**
	 * ID number for the robot.  This is the number that the dot pattern on the
	 * top of the robot represents
	 */
	unsigned int shell() const
	{
		return _shell;
	}

	/**
	 * Check whether or not this robot is on our team
	 */
	bool self() const
	{
		return _self;
	}

	/**
	 * Get the robot's position filter.
	 */
	RobotFilter *filter() const
	{
		return _filter;
	}

	bool operator==(const Robot &other) {
		return shell() == other.shell();
	}

private:
	unsigned int _shell;
	bool _self;
	RobotFilter *_filter;
};

/**
 * This class contains the motion constraints that the high-level logic sets for a robot.
 * For position: set EITHER @motionTarget OR @targetWorldVel.
 * For angle: set EITHER @targetAngleVel OR @faceTarget.
 */
struct MotionConstraints {

	/**
	 * Position
	 */

	///	A point on the field that the robot should use path-planning to get to
	boost::optional<Geometry2d::Point> targetPos;

	/// Set the velocity in world coordinates directly (circumvents path planning)
	boost::optional<Geometry2d::Point> targetWorldVel;

	/**
	 * Angle
	 */

	/// Angular velocity in rad/s counterclockwise
	boost::optional<float> targetAngleVel;

	///	A global point on the field that the robot should face towards
	boost::optional<Geometry2d::Point> faceTarget;
};

/**
 * @brief A robot on our team
 * @details This extends Robot and provides methods for interacting with our robots.
 * A few things this class is responsible for:
 * - specifying target position, velocity, angle, etc
 * - kicking and chipping the ball
 * - keeping track of which hardware revision this bot is
 * - avoidance of the ball and other robots (this info is fed to the path planner)
 * - playing the GT fight song
 */
class OurRobot: public Robot {
public:
	typedef boost::array<float,Num_Shells> RobotMask;

	RobotConfig *config;
	RobotStatus *status;

	/**
	 * @brief Construct a new OurRobot
	 * @param shell The robot ID
	 * @param state A pointer to the global system state object
	 */
	OurRobot(int shell, SystemState *state);
	~OurRobot();

	void addStatusText();

	void addText(const QString &text, const QColor &color = Qt::white, const QString &layerPrefix = "RobotText");

	// kicker readiness checks
	bool charged() const; /// true if the kicker is ready
	float kickTimer() const; /// returns the time since the kicker was last charged, 0.0 if ready

	/**
	 * state variable updates - includes timers, etc.  Called each frame
	 */
	//FIXME - Remove
	void update();

	const Geometry2d::Segment kickerBar() const; /// segment for the location of the kicker
	Geometry2d::Point pointInRobotSpace(const Geometry2d::Point& pt) const; /// converts a point to the frame of reference of robot

	// simple checks to do geometry
	/** returns true if the position specified is behind the robot */
	//FIXME - Function name and comment don't match
	bool behindBall(const Geometry2d::Point& ballPos) const;

	// Gets the robot quaternion.  Returns false (and does not change q) if not available.
	boost::optional<Eigen::Quaternionf> quaternion() const;

	// Commands

	const MotionConstraints &motionConstraints() const {
		return _motionConstraints;
	}

	const boost::optional<Planning::Path> &path() const {
		return _path;
	}

	//  FIXME: document
	void setPath(Planning::Path path);

	//	FIXME: document
	void setMotionConstraints(const MotionConstraints &constraints);

	///	clears old radioTx stuff, resets robot debug text, and clears local obstacles
	void resetForNextIteration();

	///	clears all fields in the robot's MotionConstraints object, causing the robot to stop
	void resetMotionConstraints();

	/** Stop the robot */
	void stop();

	/**
	 * @brief Move to a given point using the default RRT planner
	 * @param stopAtEnd UNUSED
	 */
	void move(const Geometry2d::Point &goal, bool stopAtEnd = false);

	uint64_t pathStartTime() const {
		return _pathStartTime;
	}

	/**
	 * Sets the worldVelocity in the robot's MotionConstraints
	 */
	void worldVelocity(const Geometry2d::Point &targetWorldVel);

	/*
	 * Enable dribbler (0 to 127)
	 */
	void dribble(int8_t speed);

	/**
	 * Face a point while remaining in place
	 */
	void face(const Geometry2d::Point &pt);

	/**
	 * Remove the facing command
	 */
	void faceNone();

	/**
	 * enable kick when ready at a given strength
	 */
	void kick(uint8_t strength);

	/**
	 * enable chip when ready at a given strength
	 */
	void chip(uint8_t strength);

	/**
	 * ignore ball sense and kick immediately
	 */
	void immediate(bool im);

	boost::ptr_vector<Packet::DebugText> robotText;

	// True if this robot will treat opponents as obstacles
	// Set to false for defenders to avoid being herded
	bool avoidOpponents() const;
	void avoidOpponents(bool enable);

	// Add a custom radius avoidance of the ball
	// creates an obstacle around the ball
	// if radius is 0 or less, it disables avoidance
	void disableAvoidBall();
	void avoidBallRadius(float radius);
	float avoidBallRadius() const;
	void resetAvoidBall();	//	sets avoid ball radius to Ball_Avoid_Small

	/**
	 * Adds an obstacle to the local set of obstacles for avoidance
	 * Cleared after every frame
	 */
	void localObstacles(const ObstaclePtr& obs) { _local_obstacles.add(obs); }
	void localObstacles(const ObstacleGroup& obs) { _local_obstacles.add(obs); }
	const ObstacleGroup& localObstacles() const { return _local_obstacles; }
	void clearLocalObstacles() { _local_obstacles.clear(); }

	// opponent approach interface

	void approachAllOpponents(bool enable = true);
	void avoidAllOpponents(bool enable = true);

	/** checks if opponents are avoided at all */
	bool avoidOpponent(unsigned shell_id) const;

	/** @return true if we are able to approach the given opponent */
	bool approachOpponent(unsigned shell_id) const;

	/** returns the avoidance radius */
	float avoidOpponentRadius(unsigned shell_id) const;

	/** returns the avoidance radius */
	void avoidAllOpponentRadius(float radius);

	/** enable/disable for opponent avoidance */
	void avoidOpponent(unsigned shell_id, bool enable_avoid);

	/** enable/disable approach of opponents - diable uses larger avoidance radius */
	void approachOpponent(unsigned shell_id, bool enable_approach);

	void avoidOpponentRadius(unsigned shell_id, float radius);

	// self approach interface

	/** determines whether a robot will avoid another robot when it plans - use for priority */

	void avoidAllTeammates(bool enable = true);
	void avoidTeammate(unsigned shell_id, bool enable = true);
	void avoidTeammateRadius(unsigned shell_id, float radius);
	bool avoidTeammate(unsigned shell_id) const;
	float avoidTeammateRadius(unsigned shell_id) const;

	// gameplay interface - interface for delayed update/planning

	/**
	 * Executes last motion command, retrieves the necessary set of
	 * obstacles, and performs planning
	 *
	 * Needs a set of global obstacles to use - assuming field regions and goal
	 */
	//	FIXME: rewrite comment to describe new behavior
	void replanIfNeeded(const ObstacleGroup& global_obstacles);

	/** status evaluations for choosing robots in behaviors - combines multiple checks */
	bool chipper_available() const;
	bool kicker_available() const;
	bool dribbler_available() const;
	bool driving_available(bool require_all = true) const; // checks for motor faults - allows one wheel failure if require_all = false

	// lower level status checks
	bool hasBall() const;
	bool ballSenseWorks() const;
	bool kickerWorks() const;
	float kickerVoltage() const;
	Packet::HardwareVersion hardwareVersion() const;

	uint64_t lastKickTime() const;

	/** radio packets */
	Packet::RadioTx::Robot radioTx;

	void setRadioRx(Packet::RadioRx rx);

	Packet::RadioRx &radioRx() {
		return _radioRx;
	}

	MotionControl *motionControl() const
	{
		return _motionControl;
	}

	SystemState *state() const
	{
		return _state;
	}

	/**
	 * @param age Time (in microseconds) that defines non-fresh
	 */
	bool rxIsFresh(uint64_t age = 500000) const;

	/**
	 * @brief Starts the robot playing the fight song
	 */
	void sing()
	{
		addText("GO TECH!", QColor(255,0,255), "Sing");
		radioTx.set_sing(true);
	}

	/**
	 * @brief Undoes any calls to kick() or chip().
	 */
	void unkick()
	{
		kick(0);
		chip(0);
		radioTx.set_use_chipper(false);
		radioTx.set_kick_immediate(false);
	}

protected:
	MotionControl *_motionControl;

	SystemState *_state;

	// obstacle management
	ObstacleGroup _local_obstacles; /// set of obstacles added by plays
	RobotMask _self_avoid_mask, _opp_avoid_mask;  /// masks for obstacle avoidance
	float _avoidBallRadius; /// radius of ball obstacle

	MotionConstraints _motionConstraints;

	Planning::RRTPlanner *_planner;	/// single-robot RRT planner
	boost::optional<Planning::Path> _path;	/// latest path
	uint64_t _pathStartTime;

	///	whenever the constraints for the robot path are changed, this is set to true to trigger a replan
	bool _pathInvalidated;

	/**
	 * Creates a set of obstacles from a given robot team mask,
	 * where mask values < 0 create no obstacle, and larger values
	 * create an obstacle of a given radius
	 *
	 * NOTE: mask must not be set for this robot
	 *
	 * @param robots is the set of robots to use to create a mask - either self or opp from _state
	 */
	template<class ROBOT>
	ObstacleGroup createRobotObstacles(const std::vector<ROBOT*>& robots, const RobotMask& mask) const {
		ObstacleGroup result;
		for (size_t i=0; i<RobotMask::size(); ++i)
			if (mask[i] > 0 && robots[i] && robots[i]->visible)
				result.add(ObstaclePtr(new CircleObstacle(robots[i]->pos, mask[i])));
		return result;
	}

	/**
	 * Creates an obstacle for the ball if necessary
	 */
	ObstaclePtr createBallObstacle() const;

private:
	uint32_t _lastKickerStatus;
	uint64_t _lastKickTime;
	uint64_t _lastChargedTime;

	Packet::RadioRx _radioRx;
};

/**
 * @brief A robot that is not on our team
 * @details This is a subclass of Robot, but really doesn't provide
 * any extra functionality.
 */
class OpponentRobot: public Robot {
public:
	OpponentRobot(unsigned int shell): Robot(shell, false) {}
};
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <ros/publisher.h>
#include <sensor_msgs/Imu.h>
#include <igvc/SerialPort.h>
#include <vector>
#include <sstream>
#include <tf/transform_datatypes.h>

using namespace std;

vector<string> split(const string &s, const char &delim) {
    vector<string> elems;
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

int main(int argc, char** argv)
{
    ros::init(argc, argv, "ardupilot");

    ros::NodeHandle nh;

    ros::Publisher pub = nh.advertise<sensor_msgs::Imu>("/imu", 1000);

    SerialPort port("/dev/igvc_imu", 115200);

    while(ros::ok() && port.isOpen())
    {
        ros::spinOnce();

        auto line = port.readln();

        if(line[0] != 'A') continue;

        auto tokens = split(line, ' ');

        if(tokens.size() == 7)
        {
            sensor_msgs::Imu msg;

            try
            {
                auto roll = stof(tokens[1]);
                auto pitch = stof(tokens[2]);
                auto yaw = stof(tokens[3]);

                msg.orientation = tf::createQuaternionMsgFromRollPitchYaw(roll, pitch, yaw);

                msg.linear_acceleration.x = stof(tokens[4]);
                msg.linear_acceleration.y = stof(tokens[5]);
                msg.linear_acceleration.z = stof(tokens[6]);

                // Indicate that no angular velocities are available
                msg.angular_velocity_covariance[0] = -1;
            } catch(const invalid_argument &e) {
                ROS_ERROR_STREAM("Exception in parsing IMU message.");
                ROS_ERROR_STREAM(e.what());
            }

            pub.publish(msg);

        } else {
            ROS_WARN_STREAM("IMU received " << tokens.size() << " tokens. Expected 7.");
            ROS_WARN_STREAM(line);
        }
    }

    return 0;
}
<commit_msg>Adds frame_id to imu msgs.<commit_after>#include <ros/ros.h>
#include <ros/publisher.h>
#include <sensor_msgs/Imu.h>
#include <igvc/SerialPort.h>
#include <vector>
#include <sstream>
#include <tf/transform_datatypes.h>

using namespace std;

vector<string> split(const string &s, const char &delim) {
    vector<string> elems;
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

int main(int argc, char** argv)
{
    ros::init(argc, argv, "ardupilot");

    ros::NodeHandle nh;

    ros::Publisher pub = nh.advertise<sensor_msgs::Imu>("/imu", 1000);

    SerialPort port("/dev/igvc_imu", 115200);

    while(ros::ok() && port.isOpen())
    {
        ros::spinOnce();

        auto line = port.readln();

        if(line[0] != 'A') continue;

        auto tokens = split(line, ' ');

        if(tokens.size() == 7)
        {
            sensor_msgs::Imu msg;

            msg.header.frame_id = "/world";

            try
            {
                auto roll = stof(tokens[1]);
                auto pitch = stof(tokens[2]);
                auto yaw = stof(tokens[3]);

                msg.orientation = tf::createQuaternionMsgFromRollPitchYaw(roll, pitch, yaw);

                msg.linear_acceleration.x = stof(tokens[4]);
                msg.linear_acceleration.y = stof(tokens[5]);
                msg.linear_acceleration.z = stof(tokens[6]);

                // Indicate that no angular velocities are available
                msg.angular_velocity_covariance[0] = -1;
            } catch(const invalid_argument &e) {
                ROS_ERROR_STREAM("Exception in parsing IMU message.");
                ROS_ERROR_STREAM(e.what());
            }

            pub.publish(msg);

        } else {
            ROS_WARN_STREAM("IMU received " << tokens.size() << " tokens. Expected 7.");
            ROS_WARN_STREAM(line);
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
** Copyright 2009-2011 MERETHIS
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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 Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#ifndef CCB_LOGGING_DEFINES_HH_
# define CCB_LOGGING_DEFINES_HH_

namespace com {
  namespace centreon {
    namespace broker {
      namespace logging {
        // Log levels.
        enum    level {
          NONE = 0,
          HIGH,
          MEDIUM,
          LOW
        };

        // Log types.
        enum    type {
          CONFIG = 1,
          DEBUG = 2,
          ERROR = 4,
          INFO = 8
        };
      }
    }
  }
}

#endif /* !CCB_LOGGING_DEFINES_HH_ */
<commit_msg>Minor typo fix.<commit_after>/*
** Copyright 2009-2011 MERETHIS
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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 Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#ifndef CCB_LOGGING_DEFINES_HH_
# define CCB_LOGGING_DEFINES_HH_

namespace       com {
  namespace     centreon {
    namespace   broker {
      namespace logging {
        // Log levels.
        enum    level {
          NONE = 0,
          HIGH,
          MEDIUM,
          LOW
        };

        // Log types.
        enum    type {
          CONFIG = 1,
          DEBUG = 2,
          ERROR = 4,
          INFO = 8
        };
      }
    }
  }
}

#endif /* !CCB_LOGGING_DEFINES_HH_ */
<|endoftext|>


<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <string>

#include <utils.hpp>
#include <Observation.hpp>

#ifndef BEAM_FORMER_HPP
#define BEAM_FORMER_HPP

namespace RadioAstronomy {

// Sequential beam forming algorithm
template< typename T > void beamFormer(const AstroData::Observation & observation, std::vector< T > & samples, std::vector< T > & output, std::vector< float > & weights);
// OpenCL beam forming algorithm
std::string * getBeamFormerOpenCL(const bool local, const unsigned int nrSamplesPerBlock, const unsigned int nrBeamsPerBlock, const unsigned int nrSamplesPerThread, const unsigned int nrBeamsPerThread, const std::string & dataType, const AstroData::Observation & observation);

// Implementations
template< typename T > void beamFormer(const AstroData::Observation & observation, std::vector< T > & samples, std::vector< T > & output, std::vector< float > & weights) {
  for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
    for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
      for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) {
        T beamP0_r = 0;
        T beamP0_i = 0;
        T beamP1_r = 0;
        T beamP1_i = 0;

        for ( unsigned int station = 0; station < observation.getNrStations(); station++ ) {
          T * samplePointer = &(samples.data()[(channel * observation.getNrStations() * observation.getNrSamplesPerPaddedSecond() * 4) + (station * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4)]);
          float * weightPointer = &(weights.data()[(channel * observation.getNrStations() * observation.getNrPaddedBeams() * 2) + (station * observation.getNrPaddedBeams() * 2) + (beam * 2)]);

          beamP0_r += (samplePointer[0] * weightPointer[0]) - (samplePointer[1] * weightPointer[1]);
          beamP0_i += (samplePointer[0] * weightPointer[1]) + (samplePointer[1] * weightPointer[0]);
          beamP1_r += (samplePointer[2] * weightPointer[0]) - (samplePointer[3] * weightPointer[1]);
          beamP1_i += (samplePointer[2] * weightPointer[1]) + (samplePointer[3] * weightPointer[0]);
        }
        beamP0_r /= observation.getNrStations();
        beamP0_i /= observation.getNrStations();
        beamP1_r /= observation.getNrStations();
        beamP1_i /= observation.getNrStations();
        output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4)] = beamP0_r;
        output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 1] = beamP0_i;
        output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 2] = beamP1_r;
        output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 3] = beamP1_i;
      }
    }
  }
}

std::string * getBeamFormerOpenCL(const bool local, const unsigned int nrSamplesPerBlock, const unsigned int nrBeamsPerBlock, const unsigned int nrSamplesPerThread, const unsigned int nrBeamsPerThread, const std::string & dataType, const AstroData::Observation & observation) {
  std::string * code = new std::string();

  // Begin kernel's template
  *code = "__kernel void beamFormer(__global const " + dataType + "4 * restrict const samples, __global " + dataType + "4 * restrict const output, __global const float2 * restrict const weights) {\n"
    "const unsigned int channel = get_group_id(2);\n"
    "const unsigned int beam = (get_group_id(1) * " + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + ") + (get_local_id(1) * " + isa::utils::toString(nrBeamsPerThread) + ");\n"
    "<%DEF_SAMPLES%>"
    "<%DEF_SUMS%>"
    + dataType + "4 sample = (" + dataType + "4)(0);\n";
  if ( local ) {
    *code += "__local float2 localWeights[" + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + "];\n"
      "__local float localSamples[" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 4) + "];\n";
  }
  *code += "float2 weight = (float2)(0);\n"
    "\n"
    "for ( unsigned int station = 0; station < " + isa::utils::toString(observation.getNrStations()) + "; station++ ) {\n";
  if ( local ) {
    *code += "unsigned int itemGlobal = (channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrPaddedBeams()) + ") + (station * " + isa::utils::toString(observation.getNrPaddedBeams()) + ") + (get_group_id(1) * " + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + ") + (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n"
      "unsigned int itemLocal = (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n"
      "while ( itemLocal < " + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + ") {\n"
      "localWeights[itemLocal] = weights[itemGlobal];\n"
      "itemLocal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n"
      "itemGlobal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n"
      "}\n"
      "globalItem = (channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrSamplesPerPaddedSecond()) + ") + (station * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + (get_group_id(0) * " + isa::utils::toString(nrSamplesPerBlock * nrSamplesPerThread) + ") + (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n"
      "itemLocal = (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n"
      "while ( itemLocal < " + isa::utils::toString(nrSamplesPerBlock * nrSamplesPerThread) + ") {\n"
      "sample = samples[itemGlobal];\n"
      "localSamples[itemLocal] = sample.x;\n"
      "localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding())) + ") + itemLocal] = sample.y;\n"
      "localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 2) + ") + itemLocal] = sample.z;\n"
      "localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 3) + ") + itemLocal] = sample.w;\n"
      "itemLocal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n"
      "itemGlobal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n"
      "}\n"
      "barrier(CLK_LOCAL_MEM_FENCE);\n";
  }
  *code += "<%LOAD_COMPUTE%>"
    "}\n"
    "<%AVERAGE%>"
    "<%STORE%>"
    "}\n";
  std::string defSamplesTemplate = "const unsigned int sample<%SNUM%> = (get_group_id(0) * " + isa::utils::toString(nrSamplesPerBlock * nrSamplesPerThread) + ") + get_local_id(0) + <%OFFSET%>;\n";
  std::string defSumsTemplate = dataType + "4 beam<%BNUM%>s<%SNUM%> = (" + dataType + "4)(0);\n";
  std::string loadComputeTemplate;
  if ( local ) {
   loadComputeTemplate += "sample.x = localSamples[get_local_id(0) + <%OFFSET%>];\n"
     "sample.y = localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding())) + ") + get_local_id(0) + <%OFFSET%>];\n"
     "sample.z = localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 2) + ") + get_local_id(0) + <%OFFSET%>];\n"
     "sample.w = localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 3) + ") + get_local_id(0) + <%OFFSET%>];\n";
  } else {
   loadComputeTemplate += "sample = samples[(channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrSamplesPerPaddedSecond()) + ") + (station * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + sample<%SNUM%>];\n";
  }
  loadComputeTemplate += "<%SUMS%>";
  std::string sumsTemplate;
  if ( local ) {
    sumsTemplate += "weight = localWeights[(get_local_id(1) * " + isa::utils::toString(nrBeamsPerThread) + ") + <%BNUM%>];\n";
  } else {
    sumsTemplate += "weight = weights[(channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrPaddedBeams()) + ") + (station * " + isa::utils::toString(observation.getNrPaddedBeams()) + ") + beam + <%BNUM%>];\n";
  }
  sumsTemplate += "beam<%BNUM%>s<%SNUM%>.x += (sample.x * weight.x) - (sample.y * weight.y);\n"
    "beam<%BNUM%>s<%SNUM%>.y += (sample.x * weight.y) + (sample.y * weight.x);\n"
    "beam<%BNUM%>s<%SNUM%>.z += (sample.z * weight.x) - (sample.w * weight.y);\n"
    "beam<%BNUM%>s<%SNUM%>.w += (sample.z * weight.y) + (sample.w * weight.x);\n";
  std::string averageTemplate = "beam<%BNUM%>s<%SNUM%> *= " + isa::utils::toString(1.0f / observation.getNrStations()) + "f;\n";
  std::string storeTemplate = "output[((beam + <%BNUM%>) * " + isa::utils::toString(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond()) + ") + (channel * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + sample<%SNUM%>] = beam<%BNUM%>s<%SNUM%>;\n";
  // End kernel's template

  std::string * defSamples_s = new std::string();
  std::string * defSums_s = new std::string();
  std::string * loadCompute_s = new std::string();
  std::string * average_s = new std::string();
  std::string * store_s = new std::string();

  for ( unsigned int sample = 0; sample < nrSamplesPerThread; sample++ ) {
    std::string sample_s = isa::utils::toString(sample);
    std::string offset_s = isa::utils::toString(sample * nrSamplesPerBlock);
    std::string * sums_s = new std::string();
    std::string * temp_s = 0;

    temp_s = isa::utils::replace(&defSamplesTemplate, "<%SNUM%>", sample_s);
    temp_s = isa::utils::replace(temp_s, "<%OFFSET%>", offset_s, true);
    defSamples_s->append(*temp_s);
    delete temp_s;

    for ( unsigned int beam = 0; beam < nrBeamsPerThread; beam++ ) {
      std::string beam_s = isa::utils::toString(beam);
      std::string * temp_s = 0;

      temp_s = isa::utils::replace(&defSumsTemplate, "<%BNUM%>", beam_s);
      defSums_s->append(*temp_s);
      delete temp_s;
      temp_s = isa::utils::replace(&sumsTemplate, "<%BNUM%>", beam_s);
      sums_s->append(*temp_s);
      delete temp_s;
      temp_s = isa::utils::replace(&averageTemplate, "<%BNUM%>", beam_s);
      average_s->append(*temp_s);
      delete temp_s;
      temp_s = isa::utils::replace(&storeTemplate, "<%BNUM%>", beam_s);
      store_s->append(*temp_s);
      delete temp_s;
    }
    defSums_s = isa::utils::replace(defSums_s, "<%SNUM%>", sample_s, true);
    temp_s = isa::utils::replace(&loadComputeTemplate, "<%SNUM%>", sample_s);
    temp_s = isa::utils::replace(temp_s, "<%OFFSET%>", offset_s, true);
    temp_s = isa::utils::replace(temp_s, "<%SUMS%>", *sums_s, true);
    temp_s = isa::utils::replace(temp_s, "<%SNUM%>", sample_s, true);
    loadCompute_s->append(*temp_s);
    delete temp_s;
    average_s = isa::utils::replace(average_s, "<%SNUM%>", sample_s, true);
    store_s = isa::utils::replace(store_s, "<%SNUM%>", sample_s, true);
  }

  code = isa::utils::replace(code, "<%DEF_SAMPLES%>", *defSamples_s, true);
  code = isa::utils::replace(code, "<%DEF_SUMS%>", *defSums_s, true);
  code = isa::utils::replace(code, "<%LOAD_COMPUTE%>", *loadCompute_s, true);
  code = isa::utils::replace(code, "<%AVERAGE%>", *average_s, true);
  code = isa::utils::replace(code, "<%STORE%>", *store_s, true);

  return code;
}

} // RadioAstronomy

#endif // BEAM_FORMER_HPP

<commit_msg>Typo.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <string>

#include <utils.hpp>
#include <Observation.hpp>

#ifndef BEAM_FORMER_HPP
#define BEAM_FORMER_HPP

namespace RadioAstronomy {

// Sequential beam forming algorithm
template< typename T > void beamFormer(const AstroData::Observation & observation, std::vector< T > & samples, std::vector< T > & output, std::vector< float > & weights);
// OpenCL beam forming algorithm
std::string * getBeamFormerOpenCL(const bool local, const unsigned int nrSamplesPerBlock, const unsigned int nrBeamsPerBlock, const unsigned int nrSamplesPerThread, const unsigned int nrBeamsPerThread, const std::string & dataType, const AstroData::Observation & observation);

// Implementations
template< typename T > void beamFormer(const AstroData::Observation & observation, std::vector< T > & samples, std::vector< T > & output, std::vector< float > & weights) {
  for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
    for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
      for ( unsigned int beam = 0; beam < observation.getNrBeams(); beam++ ) {
        T beamP0_r = 0;
        T beamP0_i = 0;
        T beamP1_r = 0;
        T beamP1_i = 0;

        for ( unsigned int station = 0; station < observation.getNrStations(); station++ ) {
          T * samplePointer = &(samples.data()[(channel * observation.getNrStations() * observation.getNrSamplesPerPaddedSecond() * 4) + (station * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4)]);
          float * weightPointer = &(weights.data()[(channel * observation.getNrStations() * observation.getNrPaddedBeams() * 2) + (station * observation.getNrPaddedBeams() * 2) + (beam * 2)]);

          beamP0_r += (samplePointer[0] * weightPointer[0]) - (samplePointer[1] * weightPointer[1]);
          beamP0_i += (samplePointer[0] * weightPointer[1]) + (samplePointer[1] * weightPointer[0]);
          beamP1_r += (samplePointer[2] * weightPointer[0]) - (samplePointer[3] * weightPointer[1]);
          beamP1_i += (samplePointer[2] * weightPointer[1]) + (samplePointer[3] * weightPointer[0]);
        }
        beamP0_r /= observation.getNrStations();
        beamP0_i /= observation.getNrStations();
        beamP1_r /= observation.getNrStations();
        beamP1_i /= observation.getNrStations();
        output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4)] = beamP0_r;
        output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 1] = beamP0_i;
        output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 2] = beamP1_r;
        output[(beam * observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond() * 4) + (channel * observation.getNrSamplesPerPaddedSecond() * 4) + (sample * 4) + 3] = beamP1_i;
      }
    }
  }
}

std::string * getBeamFormerOpenCL(const bool local, const unsigned int nrSamplesPerBlock, const unsigned int nrBeamsPerBlock, const unsigned int nrSamplesPerThread, const unsigned int nrBeamsPerThread, const std::string & dataType, const AstroData::Observation & observation) {
  std::string * code = new std::string();

  // Begin kernel's template
  *code = "__kernel void beamFormer(__global const " + dataType + "4 * restrict const samples, __global " + dataType + "4 * restrict const output, __global const float2 * restrict const weights) {\n"
    "const unsigned int channel = get_group_id(2);\n"
    "const unsigned int beam = (get_group_id(1) * " + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + ") + (get_local_id(1) * " + isa::utils::toString(nrBeamsPerThread) + ");\n"
    "<%DEF_SAMPLES%>"
    "<%DEF_SUMS%>"
    + dataType + "4 sample = (" + dataType + "4)(0);\n";
  if ( local ) {
    *code += "__local float2 localWeights[" + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + "];\n"
      "__local float localSamples[" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 4) + "];\n";
  }
  *code += "float2 weight = (float2)(0);\n"
    "\n"
    "for ( unsigned int station = 0; station < " + isa::utils::toString(observation.getNrStations()) + "; station++ ) {\n";
  if ( local ) {
    *code += "unsigned int itemGlobal = (channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrPaddedBeams()) + ") + (station * " + isa::utils::toString(observation.getNrPaddedBeams()) + ") + (get_group_id(1) * " + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + ") + (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n"
      "unsigned int itemLocal = (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n"
      "while ( itemLocal < " + isa::utils::toString(nrBeamsPerBlock * nrBeamsPerThread) + ") {\n"
      "localWeights[itemLocal] = weights[itemGlobal];\n"
      "itemLocal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n"
      "itemGlobal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n"
      "}\n"
      "itemGlobal = (channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrSamplesPerPaddedSecond()) + ") + (station * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + (get_group_id(0) * " + isa::utils::toString(nrSamplesPerBlock * nrSamplesPerThread) + ") + (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n"
      "itemLocal = (get_local_id(1) * " + isa::utils::toString(nrSamplesPerBlock) + ") + get_local_id(0);\n"
      "while ( itemLocal < " + isa::utils::toString(nrSamplesPerBlock * nrSamplesPerThread) + ") {\n"
      "sample = samples[itemGlobal];\n"
      "localSamples[itemLocal] = sample.x;\n"
      "localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding())) + ") + itemLocal] = sample.y;\n"
      "localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 2) + ") + itemLocal] = sample.z;\n"
      "localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 3) + ") + itemLocal] = sample.w;\n"
      "itemLocal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n"
      "itemGlobal += " + isa::utils::toString(nrSamplesPerBlock * nrBeamsPerBlock) + ";\n"
      "}\n"
      "barrier(CLK_LOCAL_MEM_FENCE);\n";
  }
  *code += "<%LOAD_COMPUTE%>"
    "}\n"
    "<%AVERAGE%>"
    "<%STORE%>"
    "}\n";
  std::string defSamplesTemplate = "const unsigned int sample<%SNUM%> = (get_group_id(0) * " + isa::utils::toString(nrSamplesPerBlock * nrSamplesPerThread) + ") + get_local_id(0) + <%OFFSET%>;\n";
  std::string defSumsTemplate = dataType + "4 beam<%BNUM%>s<%SNUM%> = (" + dataType + "4)(0);\n";
  std::string loadComputeTemplate;
  if ( local ) {
   loadComputeTemplate += "sample.x = localSamples[get_local_id(0) + <%OFFSET%>];\n"
     "sample.y = localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding())) + ") + get_local_id(0) + <%OFFSET%>];\n"
     "sample.z = localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 2) + ") + get_local_id(0) + <%OFFSET%>];\n"
     "sample.w = localSamples[(" + isa::utils::toString(isa::utils::pad(nrSamplesPerBlock * nrSamplesPerThread, observation.getPadding()) * 3) + ") + get_local_id(0) + <%OFFSET%>];\n";
  } else {
   loadComputeTemplate += "sample = samples[(channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrSamplesPerPaddedSecond()) + ") + (station * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + sample<%SNUM%>];\n";
  }
  loadComputeTemplate += "<%SUMS%>";
  std::string sumsTemplate;
  if ( local ) {
    sumsTemplate += "weight = localWeights[(get_local_id(1) * " + isa::utils::toString(nrBeamsPerThread) + ") + <%BNUM%>];\n";
  } else {
    sumsTemplate += "weight = weights[(channel * " + isa::utils::toString(observation.getNrStations() * observation.getNrPaddedBeams()) + ") + (station * " + isa::utils::toString(observation.getNrPaddedBeams()) + ") + beam + <%BNUM%>];\n";
  }
  sumsTemplate += "beam<%BNUM%>s<%SNUM%>.x += (sample.x * weight.x) - (sample.y * weight.y);\n"
    "beam<%BNUM%>s<%SNUM%>.y += (sample.x * weight.y) + (sample.y * weight.x);\n"
    "beam<%BNUM%>s<%SNUM%>.z += (sample.z * weight.x) - (sample.w * weight.y);\n"
    "beam<%BNUM%>s<%SNUM%>.w += (sample.z * weight.y) + (sample.w * weight.x);\n";
  std::string averageTemplate = "beam<%BNUM%>s<%SNUM%> *= " + isa::utils::toString(1.0f / observation.getNrStations()) + "f;\n";
  std::string storeTemplate = "output[((beam + <%BNUM%>) * " + isa::utils::toString(observation.getNrChannels() * observation.getNrSamplesPerPaddedSecond()) + ") + (channel * " + isa::utils::toString(observation.getNrSamplesPerPaddedSecond()) + ") + sample<%SNUM%>] = beam<%BNUM%>s<%SNUM%>;\n";
  // End kernel's template

  std::string * defSamples_s = new std::string();
  std::string * defSums_s = new std::string();
  std::string * loadCompute_s = new std::string();
  std::string * average_s = new std::string();
  std::string * store_s = new std::string();

  for ( unsigned int sample = 0; sample < nrSamplesPerThread; sample++ ) {
    std::string sample_s = isa::utils::toString(sample);
    std::string offset_s = isa::utils::toString(sample * nrSamplesPerBlock);
    std::string * sums_s = new std::string();
    std::string * temp_s = 0;

    temp_s = isa::utils::replace(&defSamplesTemplate, "<%SNUM%>", sample_s);
    temp_s = isa::utils::replace(temp_s, "<%OFFSET%>", offset_s, true);
    defSamples_s->append(*temp_s);
    delete temp_s;

    for ( unsigned int beam = 0; beam < nrBeamsPerThread; beam++ ) {
      std::string beam_s = isa::utils::toString(beam);
      std::string * temp_s = 0;

      temp_s = isa::utils::replace(&defSumsTemplate, "<%BNUM%>", beam_s);
      defSums_s->append(*temp_s);
      delete temp_s;
      temp_s = isa::utils::replace(&sumsTemplate, "<%BNUM%>", beam_s);
      sums_s->append(*temp_s);
      delete temp_s;
      temp_s = isa::utils::replace(&averageTemplate, "<%BNUM%>", beam_s);
      average_s->append(*temp_s);
      delete temp_s;
      temp_s = isa::utils::replace(&storeTemplate, "<%BNUM%>", beam_s);
      store_s->append(*temp_s);
      delete temp_s;
    }
    defSums_s = isa::utils::replace(defSums_s, "<%SNUM%>", sample_s, true);
    temp_s = isa::utils::replace(&loadComputeTemplate, "<%SNUM%>", sample_s);
    temp_s = isa::utils::replace(temp_s, "<%OFFSET%>", offset_s, true);
    temp_s = isa::utils::replace(temp_s, "<%SUMS%>", *sums_s, true);
    temp_s = isa::utils::replace(temp_s, "<%SNUM%>", sample_s, true);
    loadCompute_s->append(*temp_s);
    delete temp_s;
    average_s = isa::utils::replace(average_s, "<%SNUM%>", sample_s, true);
    store_s = isa::utils::replace(store_s, "<%SNUM%>", sample_s, true);
  }

  code = isa::utils::replace(code, "<%DEF_SAMPLES%>", *defSamples_s, true);
  code = isa::utils::replace(code, "<%DEF_SUMS%>", *defSums_s, true);
  code = isa::utils::replace(code, "<%LOAD_COMPUTE%>", *loadCompute_s, true);
  code = isa::utils::replace(code, "<%AVERAGE%>", *average_s, true);
  code = isa::utils::replace(code, "<%STORE%>", *store_s, true);

  return code;
}

} // RadioAstronomy

#endif // BEAM_FORMER_HPP

<|endoftext|>