<commit_before>#include "gtest-1.7.0/include/gtest/gtest.h"
#include "xgldevice.h"

XglDevice::XglDevice(XGL_UINT id, XGL_PHYSICAL_GPU obj) :
    m_flags(0),
    XglGpu(id, obj)
{
    init_device();
    init_formats();
}

void XglDevice::init_device()
{
    XGL_DEVICE_CREATE_INFO info = {};
    XGL_RESULT err;
    XGL_SIZE size;
    XGL_UINT i;

    info.sType = XGL_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
    info.maxValidationLevel = XGL_VALIDATION_LEVEL_END_RANGE;
    info.flags = XGL_DEVICE_CREATE_VALIDATION_BIT;

    /* request all queues */
    info.queueRecordCount = this->queue_count;
    info.pRequestedQueues = this->queue_reqs;

    /* enable all extensions */
    info.extensionCount = this->extension_count;
    info.ppEnabledExtensionNames = this->extensions;

    err = xglCreateDevice(this->gpuObj, &info, &m_xgl_device_object);
    ASSERT_XGL_SUCCESS(err);

    err = xglGetMemoryHeapCount(m_xgl_device_object, &this->heap_count);
    ASSERT_XGL_SUCCESS(err);
    ASSERT_GE(1, this->heap_count) << "No memory heaps available";

    this->heap_props = new XGL_MEMORY_HEAP_PROPERTIES [this->heap_count];
    ASSERT_TRUE(NULL != this->heap_props) << "Out of memory";

    for (i = 0; i < this->heap_count; i++) {
        err = xglGetMemoryHeapInfo(m_xgl_device_object, i,
                                   XGL_INFO_TYPE_MEMORY_HEAP_PROPERTIES,
                                   &size, &this->heap_props[i]);
        ASSERT_XGL_SUCCESS(err);
        ASSERT_EQ(size, sizeof(this->heap_props[0])) << "Invalid heap property size";
    }
}

void XglDevice::init_formats()
{
    XGL_CHANNEL_FORMAT ch;
    XGL_NUM_FORMAT num;

    for (int chInt = XGL_CH_FMT_UNDEFINED; chInt < XGL_MAX_CH_FMT; chInt++) {
        for (int numInt = 0; numInt < XGL_MAX_NUM_FMT; numInt++) {
            XGL_FORMAT fmt = {};
            XGL_RESULT err;
            XGL_SIZE size;

            fmt.channelFormat = static_cast<XGL_CHANNEL_FORMAT>(chInt);
            fmt.numericFormat = static_cast<XGL_NUM_FORMAT>(numInt);

            err = xglGetFormatInfo(m_xgl_device_object, fmt,
                                   XGL_INFO_TYPE_FORMAT_PROPERTIES,
                                   &size, &this->format_props[ch][num]);
            if (err) {
                memset(&this->format_props[ch][num], 0,
                       sizeof(this->format_props[ch][num]));
            }
            else if (size != sizeof(this->format_props[ch][num])) {
                ASSERT_EQ(size, sizeof(this->format_props[ch][num])) << "Incorrect data size";
            }
        }
    }
}

void XglDevice::get_device_queue(XGL_QUEUE_TYPE queue_type, XGL_UINT queue_idx)
{
    XGL_RESULT err;

    err = xglGetDeviceQueue(this->device(), queue_type, queue_idx, &this->m_queue);
    ASSERT_XGL_SUCCESS(err) << "xglGetDeviceQueue failed";
}

XGL_RESULT XglDevice::AllocAndBindGpuMemory(XGL_OBJECT obj, const std::string &objName, XGL_GPU_MEMORY *pMem)
{
    XGL_RESULT err;
    XGL_MEMORY_REQUIREMENTS mem_req;
    XGL_UINT data_size;
    err = xglGetObjectInfo(obj, XGL_INFO_TYPE_MEMORY_REQUIREMENTS, &data_size, &mem_req);
    if (err != XGL_SUCCESS) return err;

    if (mem_req.size > 0) {
        XGL_MEMORY_ALLOC_INFO mem_info = {
            XGL_STRUCTURE_TYPE_MEMORY_ALLOC_INFO,
            XGL_NULL_HANDLE,
            mem_req.size,                                   // allocationSize
            mem_req.alignment,                              // alignment
            XGL_MEMORY_ALLOC_SHAREABLE_BIT,                 // XGL_MEMORY_ALLOC_FLAGS
            mem_req.heapCount,                              // heapCount
            {0},                                            // heaps
            XGL_MEMORY_PRIORITY_NORMAL                      // XGL_MEMORY_PRIORITY
        };
        memcpy(mem_info.heaps, mem_req.heaps, sizeof(XGL_UINT)*XGL_MAX_MEMORY_HEAPS);

        err = xglAllocMemory(device(), &mem_info, pMem);
        if (err != XGL_SUCCESS) return err;

        err = xglBindObjectMemory(obj, *pMem, 0);
        if (err != XGL_SUCCESS) return err;
    }

    return err;
}
<commit_msg>tests: fix memory access with uninitialized values<commit_after>#include "gtest-1.7.0/include/gtest/gtest.h"
#include "xgldevice.h"

XglDevice::XglDevice(XGL_UINT id, XGL_PHYSICAL_GPU obj) :
    m_flags(0),
    XglGpu(id, obj)
{
    init_device();
    init_formats();
}

void XglDevice::init_device()
{
    XGL_DEVICE_CREATE_INFO info = {};
    XGL_RESULT err;
    XGL_SIZE size;
    XGL_UINT i;

    info.sType = XGL_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
    info.maxValidationLevel = XGL_VALIDATION_LEVEL_END_RANGE;
    info.flags = XGL_DEVICE_CREATE_VALIDATION_BIT;

    /* request all queues */
    info.queueRecordCount = this->queue_count;
    info.pRequestedQueues = this->queue_reqs;

    /* enable all extensions */
    info.extensionCount = this->extension_count;
    info.ppEnabledExtensionNames = this->extensions;

    err = xglCreateDevice(this->gpuObj, &info, &m_xgl_device_object);
    ASSERT_XGL_SUCCESS(err);

    err = xglGetMemoryHeapCount(m_xgl_device_object, &this->heap_count);
    ASSERT_XGL_SUCCESS(err);
    ASSERT_GE(1, this->heap_count) << "No memory heaps available";

    this->heap_props = new XGL_MEMORY_HEAP_PROPERTIES [this->heap_count];
    ASSERT_TRUE(NULL != this->heap_props) << "Out of memory";

    for (i = 0; i < this->heap_count; i++) {
        err = xglGetMemoryHeapInfo(m_xgl_device_object, i,
                                   XGL_INFO_TYPE_MEMORY_HEAP_PROPERTIES,
                                   &size, &this->heap_props[i]);
        ASSERT_XGL_SUCCESS(err);
        ASSERT_EQ(size, sizeof(this->heap_props[0])) << "Invalid heap property size";
    }
}

void XglDevice::init_formats()
{
    for (int chInt = XGL_CH_FMT_UNDEFINED; chInt < XGL_MAX_CH_FMT; chInt++) {
        for (int numInt = 0; numInt < XGL_MAX_NUM_FMT; numInt++) {
            XGL_FORMAT fmt = {};
            XGL_RESULT err;
            XGL_SIZE size;

            fmt.channelFormat = static_cast<XGL_CHANNEL_FORMAT>(chInt);
            fmt.numericFormat = static_cast<XGL_NUM_FORMAT>(numInt);

            err = xglGetFormatInfo(m_xgl_device_object, fmt,
                                   XGL_INFO_TYPE_FORMAT_PROPERTIES,
                                   &size, &this->format_props[chInt][numInt]);
            if (err) {
                memset(&this->format_props[chInt][numInt], 0,
                       sizeof(this->format_props[chInt][numInt]));
            }
            else if (size != sizeof(this->format_props[chInt][numInt])) {
                ASSERT_EQ(size, sizeof(this->format_props[chInt][numInt])) << "Incorrect data size";
            }
        }
    }
}

void XglDevice::get_device_queue(XGL_QUEUE_TYPE queue_type, XGL_UINT queue_idx)
{
    XGL_RESULT err;

    err = xglGetDeviceQueue(this->device(), queue_type, queue_idx, &this->m_queue);
    ASSERT_XGL_SUCCESS(err) << "xglGetDeviceQueue failed";
}

XGL_RESULT XglDevice::AllocAndBindGpuMemory(XGL_OBJECT obj, const std::string &objName, XGL_GPU_MEMORY *pMem)
{
    XGL_RESULT err;
    XGL_MEMORY_REQUIREMENTS mem_req;
    XGL_UINT data_size;
    err = xglGetObjectInfo(obj, XGL_INFO_TYPE_MEMORY_REQUIREMENTS, &data_size, &mem_req);
    if (err != XGL_SUCCESS) return err;

    if (mem_req.size > 0) {
        XGL_MEMORY_ALLOC_INFO mem_info = {
            XGL_STRUCTURE_TYPE_MEMORY_ALLOC_INFO,
            XGL_NULL_HANDLE,
            mem_req.size,                                   // allocationSize
            mem_req.alignment,                              // alignment
            XGL_MEMORY_ALLOC_SHAREABLE_BIT,                 // XGL_MEMORY_ALLOC_FLAGS
            mem_req.heapCount,                              // heapCount
            {0},                                            // heaps
            XGL_MEMORY_PRIORITY_NORMAL                      // XGL_MEMORY_PRIORITY
        };
        memcpy(mem_info.heaps, mem_req.heaps, sizeof(XGL_UINT)*XGL_MAX_MEMORY_HEAPS);

        err = xglAllocMemory(device(), &mem_info, pMem);
        if (err != XGL_SUCCESS) return err;

        err = xglBindObjectMemory(obj, *pMem, 0);
        if (err != XGL_SUCCESS) return err;
    }

    return err;
}
<|endoftext|>


<commit_before>/*************************************************************************
Analyse - Classe de [...]
-------------------
dbut                :	06/05/17
copyright            :	(C) 2017 par VOGEL
e-mail               :	hugues.vogel@insa-lyon.fr
*************************************************************************/

//--------- Ralisation de la classe <Analyse> (fichier Analyse.cpp) ---------//

//---------------------------------------------------------------- INCLUDE

//-------------------------------------------------------- Include systme

//------------------------------------------------------ Include personnel

#include "Analyse.h"

//----------------------------------------------------------------- PUBLIC

Analyse & Analyse::ObtenirInstance()
{
	// TODO: changer le retour par l'instance du singleton
	return *((Analyse*) nullptr);
}

bool Analyse::AnalysePrecise(unsigned int size, const unsigned char genome[], const Maladie maladie) {
	// TODO
}

bool Analyse::AnalyseGlobal(const unsigned char genome[], const Maladie maladie) {
	// TODO
}

//----------------------------------------------------------------- PRIVEE

Analyse::Analyse()
{
}

Analyse::~Analyse()
{
}
<commit_msg>correction du paramétage de AnalyseGlobal<commit_after>/*************************************************************************
Analyse - Classe de [...]
-------------------
dbut                :	06/05/17
copyright            :	(C) 2017 par VOGEL
e-mail               :	hugues.vogel@insa-lyon.fr
*************************************************************************/

//--------- Ralisation de la classe <Analyse> (fichier Analyse.cpp) ---------//

//---------------------------------------------------------------- INCLUDE

//-------------------------------------------------------- Include systme

//------------------------------------------------------ Include personnel

#include "Analyse.h"

//----------------------------------------------------------------- PUBLIC

Analyse & Analyse::ObtenirInstance()
{
	// TODO: changer le retour par l'instance du singleton
	return *((Analyse*) nullptr);
}

bool Analyse::AnalysePrecise(unsigned int size, const unsigned char genome[], const Maladie maladie) {
	// TODO
	return false;
}

unordered_map<const Maladie&, bool> Analyse::AnalyseGlobal(unsigned int size,const unsigned char genome[]) {
	// TODO
	return unordered_map<const Maladie&, bool>();
}

//----------------------------------------------------------------- PRIVEE

Analyse::Analyse()
{
}

Analyse::~Analyse()
{
}
<|endoftext|>


<commit_before>/*
 *  VHDL code generation for processes.
 *
 *  Copyright (C) 2008  Nick Gasson (nick@nickg.me.uk)
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "vhdl_target.h"
#include "vhdl_element.hh"

#include <iostream>
#include <cassert>
#include <sstream>
#include <map>

/*
 * Implementing blocking assignment is a little tricky since
 * the semantics are a little different to VHDL:
 *
 * In Verilog a blocking assignment (=) can be used anywhere
 * non-blocking assignment (<=) can be. In VHDL blocking
 * assignment (:=) can only be used with variables, and
 * non-blocking assignment (<=) can only be used with signals.
 * All Verilog variables are translated into signals in the
 * VHDL architecture. This means we cannot use the VHDL :=
 * operator directly. Furthermore, VHDL variables can only
 * be declared within processes, so it wouldn't help to
 * make all Verilog variables VHDL variables.
 *
 * The solution is to generate a VHDL variable in a process
 * whenever a blocking assignment is made to a signal. The
 * assignment is made to this variable instead, and
 * g_assign_vars below remembers the temporary variables
 * that have been generated. Any subsequent blocking assignments
 * are made to the same variable. At either the end of the
 * process or a `wait' statement, the temporaries are assigned
 * back to the signals, and the temporaries are forgotten. This
 * has exactly the same (external) behaviour as the Verilog
 * blocking assignment, since no external process will be able
 * to observe that the assignment wasn't made immediately.
 *
 * For example:
 *
 *   initial begin
 *     a = 5;
 *     b = a + 3;
 *   end
 *
 * Is translated to:
 *
 *   process is
 *     variable a_Var : Some_Type;
 *     variable b_Var : Some_Type;
 *   begin
 *     a_Var := 5;
 *     b_Var := a_Var + 3;
 *     a <= a_Var;
 *     b <= b_Var;
 *   end process;
 */
typedef std::map<std::string, ivl_signal_t> var_temp_set_t;
static var_temp_set_t g_assign_vars;

/*
 * Called whenever a blocking assignment is made to sig.
 */
void blocking_assign_to(vhdl_process *proc, ivl_signal_t sig)
{
   std::string var(get_renamed_signal(sig));
   std::string tmpname(var + "_Var");

   if (g_assign_vars.find(var) == g_assign_vars.end()) {
      // This is the first time a non-blocking assignment
      // has been made to this signal: create a variable
      // to shadow it.
      if (!proc->have_declared_var(tmpname)) {
         vhdl_decl *decl = proc->get_parent()->get_decl(var);
         assert(decl);
         vhdl_type *type = new vhdl_type(*decl->get_type());

         proc->add_decl(new vhdl_var_decl(tmpname.c_str(), type));
      }

      rename_signal(sig, tmpname);
      g_assign_vars[tmpname] = sig;
   }
}

/*
 * Assign all _Var variables to the corresponding signals. This makes
 * the new values visible outside the current process. This should be
 * called before any `wait' statement or the end of the process.
 */
void draw_blocking_assigns(vhdl_process *proc)
{
   var_temp_set_t::const_iterator it;
   for (it = g_assign_vars.begin(); it != g_assign_vars.end(); ++it) {
      std::string stripped(strip_var((*it).first));

      vhdl_decl *decl = proc->get_decl(stripped);
      assert(decl);
      vhdl_type *type = new vhdl_type(*decl->get_type());

      vhdl_var_ref *lhs = new vhdl_var_ref(stripped.c_str(), NULL);
      vhdl_expr *rhs = new vhdl_var_ref((*it).first.c_str(), type);

      // TODO: I'm not sure this will work properly if, e.g., the delay
      // is inside a `if' statement
      proc->get_container()->add_stmt(new vhdl_nbassign_stmt(lhs, rhs));

      // Undo the renaming (since the temporary is no longer needed)
      rename_signal((*it).second, stripped);
   }

   g_assign_vars.clear();
}

/*
 * Remove _Var from the end of a string, if it is present.
 */
std::string strip_var(const std::string &str)
{
   std::string result(str);
   size_t pos = result.find("_Var");
   if (pos != std::string::npos)
      result.erase(pos, 4);
   return result;
}

/*
 * Convert a Verilog process to VHDL and add it to the architecture
 * of the given entity.
 */
static int generate_vhdl_process(vhdl_entity *ent, ivl_process_t proc)
{
   // Create a new process and store it in the entity's
   // architecture. This needs to be done first or the
   // parent link won't be valid (and draw_stmt needs this
   // to add information to the architecture)
   vhdl_process *vhdl_proc = new vhdl_process();
   ent->get_arch()->add_stmt(vhdl_proc);

   // If this is an initial process, push signal initialisation
   // into the declarations
   if (ivl_process_type(proc) == IVL_PR_INITIAL)
      vhdl_proc->set_initial(true);

   ivl_statement_t stmt = ivl_process_stmt(proc);
   int rc = draw_stmt(vhdl_proc, vhdl_proc->get_container(), stmt);
   if (rc != 0)
      return rc;

   // Initial processes are translated to VHDL processes with
   // no sensitivity list and and indefinite wait statement at
   // the end
   // However, if no statements were added to the container
   // by draw_stmt, don't bother adding a wait as `emit'
   // will optimise the process out of the output
   if (ivl_process_type(proc) == IVL_PR_INITIAL
       && !vhdl_proc->get_container()->empty()) {
      vhdl_wait_stmt *wait = new vhdl_wait_stmt();
      vhdl_proc->get_container()->add_stmt(wait);
   }

   // Add a comment indicating where it came from
   ivl_scope_t scope = ivl_process_scope(proc);
   const char *type = ivl_process_type(proc) == IVL_PR_INITIAL
      ? "initial" : "always";
   std::ostringstream ss;
   ss << "Generated from " << type << " process in ";
   ss << ivl_scope_tname(scope);
   vhdl_proc->set_comment(ss.str());

   // Output any remaning blocking assignments
   draw_blocking_assigns(vhdl_proc);

   return 0;
}

int draw_process(ivl_process_t proc, void *cd)
{
   ivl_scope_t scope = ivl_process_scope(proc);
   const char *scope_name = ivl_scope_name(scope);

   // A process should occur in a module scope, therefore it
   // should have already been assigned a VHDL entity
   assert(ivl_scope_type(scope) == IVL_SCT_MODULE);
   vhdl_entity *ent = find_entity(ivl_scope_tname(scope));
   assert(ent != NULL);

   // If the scope this process belongs to is the same as the
   // VHDL entity was generated from, then create a VHDL process
   // from this Verilog process. This ensures that each process
   // is translated at most once, no matter how many times it
   // appears in the hierarchy.
   if (ent->get_derived_from() == scope_name)
      return generate_vhdl_process(ent, proc);
   else
      return 0;
}
<commit_msg>Statements might be emitted in wrong order<commit_after>/*
 *  VHDL code generation for processes.
 *
 *  Copyright (C) 2008  Nick Gasson (nick@nickg.me.uk)
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "vhdl_target.h"
#include "vhdl_element.hh"

#include <iostream>
#include <cassert>
#include <sstream>
#include <map>

/*
 * Implementing blocking assignment is a little tricky since
 * the semantics are a little different to VHDL:
 *
 * In Verilog a blocking assignment (=) can be used anywhere
 * non-blocking assignment (<=) can be. In VHDL blocking
 * assignment (:=) can only be used with variables, and
 * non-blocking assignment (<=) can only be used with signals.
 * All Verilog variables are translated into signals in the
 * VHDL architecture. This means we cannot use the VHDL :=
 * operator directly. Furthermore, VHDL variables can only
 * be declared within processes, so it wouldn't help to
 * make all Verilog variables VHDL variables.
 *
 * The solution is to generate a VHDL variable in a process
 * whenever a blocking assignment is made to a signal. The
 * assignment is made to this variable instead, and
 * g_assign_vars below remembers the temporary variables
 * that have been generated. Any subsequent blocking assignments
 * are made to the same variable. At either the end of the
 * process or a `wait' statement, the temporaries are assigned
 * back to the signals, and the temporaries are forgotten. This
 * has exactly the same (external) behaviour as the Verilog
 * blocking assignment, since no external process will be able
 * to observe that the assignment wasn't made immediately.
 *
 * For example:
 *
 *   initial begin
 *     a = 5;
 *     b = a + 3;
 *   end
 *
 * Is translated to:
 *
 *   process is
 *     variable a_Var : Some_Type;
 *     variable b_Var : Some_Type;
 *   begin
 *     a_Var := 5;
 *     b_Var := a_Var + 3;
 *     a <= a_Var;
 *     b <= b_Var;
 *   end process;
 */
typedef std::map<std::string, ivl_signal_t> var_temp_set_t;
static var_temp_set_t g_assign_vars;

/*
 * Called whenever a blocking assignment is made to sig.
 */
void blocking_assign_to(vhdl_process *proc, ivl_signal_t sig)
{
   std::string var(get_renamed_signal(sig));
   std::string tmpname(var + "_Var");

   if (g_assign_vars.find(var) == g_assign_vars.end()) {
      // This is the first time a non-blocking assignment
      // has been made to this signal: create a variable
      // to shadow it.
      if (!proc->have_declared_var(tmpname)) {
         vhdl_decl *decl = proc->get_parent()->get_decl(var);
         assert(decl);
         vhdl_type *type = new vhdl_type(*decl->get_type());

         proc->add_decl(new vhdl_var_decl(tmpname.c_str(), type));
      }

      rename_signal(sig, tmpname);
      g_assign_vars[tmpname] = sig;
   }
}

/*
 * Assign all _Var variables to the corresponding signals. This makes
 * the new values visible outside the current process. This should be
 * called before any `wait' statement or the end of the process.
 */
void draw_blocking_assigns(vhdl_process *proc)
{
   var_temp_set_t::const_iterator it;
   for (it = g_assign_vars.begin(); it != g_assign_vars.end(); ++it) {
      std::string stripped(strip_var((*it).first));

      vhdl_decl *decl = proc->get_decl(stripped);
      assert(decl);
      vhdl_type *type = new vhdl_type(*decl->get_type());

      vhdl_var_ref *lhs = new vhdl_var_ref(stripped.c_str(), NULL);
      vhdl_expr *rhs = new vhdl_var_ref((*it).first.c_str(), type);

      // TODO: I'm not sure this will work properly if, e.g., the delay
      // is inside a `if' statement
      proc->get_container()->add_stmt(new vhdl_nbassign_stmt(lhs, rhs));

      // Undo the renaming (since the temporary is no longer needed)
      rename_signal((*it).second, stripped);
   }

   g_assign_vars.clear();
}

/*
 * Remove _Var from the end of a string, if it is present.
 */
std::string strip_var(const std::string &str)
{
   std::string result(str);
   size_t pos = result.find("_Var");
   if (pos != std::string::npos)
      result.erase(pos, 4);
   return result;
}

/*
 * Convert a Verilog process to VHDL and add it to the architecture
 * of the given entity.
 */
static int generate_vhdl_process(vhdl_entity *ent, ivl_process_t proc)
{
   // Create a new process and store it in the entity's
   // architecture. This needs to be done first or the
   // parent link won't be valid (and draw_stmt needs this
   // to add information to the architecture)
   vhdl_process *vhdl_proc = new vhdl_process();
   ent->get_arch()->add_stmt(vhdl_proc);

   // If this is an initial process, push signal initialisation
   // into the declarations
   if (ivl_process_type(proc) == IVL_PR_INITIAL)
      vhdl_proc->set_initial(true);

   ivl_statement_t stmt = ivl_process_stmt(proc);
   int rc = draw_stmt(vhdl_proc, vhdl_proc->get_container(), stmt);
   if (rc != 0)
      return rc;

   // Output any remaning blocking assignments
   draw_blocking_assigns(vhdl_proc);

   // Initial processes are translated to VHDL processes with
   // no sensitivity list and and indefinite wait statement at
   // the end
   // However, if no statements were added to the container
   // by draw_stmt, don't bother adding a wait as `emit'
   // will optimise the process out of the output
   if (ivl_process_type(proc) == IVL_PR_INITIAL
       && !vhdl_proc->get_container()->empty()) {
      vhdl_wait_stmt *wait = new vhdl_wait_stmt();
      vhdl_proc->get_container()->add_stmt(wait);
   }

   // Add a comment indicating where it came from
   ivl_scope_t scope = ivl_process_scope(proc);
   const char *type = ivl_process_type(proc) == IVL_PR_INITIAL
      ? "initial" : "always";
   std::ostringstream ss;
   ss << "Generated from " << type << " process in ";
   ss << ivl_scope_tname(scope);
   vhdl_proc->set_comment(ss.str());

   return 0;
}

int draw_process(ivl_process_t proc, void *cd)
{
   ivl_scope_t scope = ivl_process_scope(proc);
   const char *scope_name = ivl_scope_name(scope);

   // A process should occur in a module scope, therefore it
   // should have already been assigned a VHDL entity
   assert(ivl_scope_type(scope) == IVL_SCT_MODULE);
   vhdl_entity *ent = find_entity(ivl_scope_tname(scope));
   assert(ent != NULL);

   // If the scope this process belongs to is the same as the
   // VHDL entity was generated from, then create a VHDL process
   // from this Verilog process. This ensures that each process
   // is translated at most once, no matter how many times it
   // appears in the hierarchy.
   if (ent->get_derived_from() == scope_name)
      return generate_vhdl_process(ent, proc);
   else
      return 0;
}
<|endoftext|>


<commit_before>#include "MoonSchlyterModel.h"

#include "EarthSchlyterModel.h"

#include "Time/J2000.h"

/*

N = 125.1228 - 0.0529538083 * d
i = 5.1454
w = 318.0634 + 0.1643573223 * d
a = 60.2666  (Earth radii)
e = 0.054900
M = 115.3654 + 13.0649929509 * d

*/
const double kdEarthRadiiAU = 0.01;

const KeplerElements MoonSchlyterOrbitalEphemeris::kxBaseElements =
{
	PDE::Deg2Rad( 125.1228 ),
	PDE::Deg2Rad( 5.1454 ),
	PDE::Deg2Rad( 282.9404 ),
	-60.2666 * kdEarthRadiiAU,
	0.054900,
	PDE::Deg2Rad( 115.3654 ),
	PDE::Deg2Rad( 13.0649929509 ),
	static_cast< double >( J2000 - 1.5 )    // SE - NOTE: these elements have an epoch of '0' Jan 2000, 1.5 days before J2000.0
};

const KeplerElements MoonSchlyterOrbitalEphemeris::kxLinearPerturbations =
{
	PDE::Deg2Rad( 0.0529538083 ),
	0.0,
	PDE::Deg2Rad( 0.1643573223 ),
	0.0,
	0.000000001151,
	0.0,
	0.0,
	0.0
};

EphemerisVector4 MoonSchlyterOrbitalEphemeris::Perturb( const EphemerisVector4 xPosition, const double dT ) const
{
	const double dEclipticLongitude = CalculateLongitude( xPosition );
	const double dEclipticLatitude = CalculateLatitude( xPosition );

	const double dMeanAnomalyMoon = MeanAnomaly( dT );
	const double dMeanAnomalyEarth = EarthSchlyterOrbitalEphemeris::MeanAnomaly( dT );

	EarthSchlyterOrbitalEphemeris xEarthEphemeris;
	MoonSchlyterOrbitalEphemeris xMoonEphemeris;
	const double dArgumentOfPerifocusEarth = xEarthEphemeris.EvaluateArgumentOfPerifocus( dT );
	//const double dTrueAnomalyEarth = xEarthEphemeris.EvaluateTrueAnomaly( dT );

	const double dLongitudeOfAscendingNodeMoon = xMoonEphemeris.EvaluateLongitudeOfAscendingNode( dT );
	const double dArgumentOfPerifocusMoon = xMoonEphemeris.EvaluateArgumentOfPerifocus( dT );
	//const double dTrueAnomalyMoon = xMoonEphemeris.EvaluateTrueAnomaly( dT );

	const double dLongitudeSun = dMeanAnomalyEarth + dArgumentOfPerifocusEarth;
	const double dLongitudeMoon = dMeanAnomalyMoon + dArgumentOfPerifocusMoon + dLongitudeOfAscendingNodeMoon;

	const double dElongationMoon = dLongitudeMoon - dLongitudeSun;
	const double dArgumentOfLatitudeMoon = dLongitudeMoon - dLongitudeOfAscendingNodeMoon;

	// D = elongation moon
	// F = latitude thing
	const double dCorrectedLongitude = dEclipticLongitude
		- 1.274 * PDE::Sin( dMeanAnomalyEarth - 2 * dElongationMoon )	// evection
		+ 0.658 * PDE::Sin( 2.0 * dElongationMoon )						// variation
		- 0.186 * PDE::Sin( dMeanAnomalyEarth )							// yearly equation
		- 0.059 * PDE::Sin( 2.0 * ( dMeanAnomalyMoon - dElongationMoon ) )
		- 0.057 * PDE::Sin( dMeanAnomalyMoon - 2.0 * dElongationMoon + dMeanAnomalyEarth )
		+ 0.053 * PDE::Sin( dMeanAnomalyMoon + 2.0 * dElongationMoon )
		+ 0.046 * PDE::Sin( 2.0 * dElongationMoon - dMeanAnomalyEarth )
		+ 0.041 * PDE::Sin( dMeanAnomalyMoon - dMeanAnomalyEarth )
		- 0.035 * PDE::Sin( dElongationMoon )							// parallactic equation
		- 0.031 * PDE::Sin( dMeanAnomalyMoon + dMeanAnomalyEarth )
		- 0.015 * PDE::Sin( 2.0 * ( dArgumentOfLatitudeMoon - dElongationMoon ) )
		+ 0.011 * PDE::Sin( dMeanAnomalyMoon - 4.0 * dElongationMoon );

	const double dCorrectedLatitude = dEclipticLatitude
		- 0.173 * PDE::Sin( dArgumentOfLatitudeMoon - 2.0 * dElongationMoon )
		- 0.055 * PDE::Sin( dMeanAnomalyMoon - dArgumentOfLatitudeMoon - 2.0 * dElongationMoon )
		- 0.046 * PDE::Sin( dMeanAnomalyMoon + dArgumentOfLatitudeMoon - 2.0 * dElongationMoon )
		+ 0.033 * PDE::Sin( dArgumentOfLatitudeMoon + 2.0 * dElongationMoon )
		+ 0.017 * PDE::Sin( 2.0 * dMeanAnomalyMoon + dArgumentOfLatitudeMoon );

	const double dCorrectedDistance = xPosition.xyz().Magnitude();

    return PositionFromLatLonRad( dCorrectedLatitude, dCorrectedLongitude, dCorrectedDistance );
}
<commit_msg>corrections to lunar schlyter model<commit_after>#include "MoonSchlyterModel.h"

#include "EarthSchlyterModel.h"

#include "Time/J2000.h"

/*

N = 125.1228 - 0.0529538083 * d
i = 5.1454
w = 318.0634 + 0.1643573223 * d
a = 60.2666  (Earth radii)
e = 0.054900
M = 115.3654 + 13.0649929509 * d

*/
const double kdEarthRadiiAU = 6371.009 / 149597870.7;

const KeplerElements MoonSchlyterOrbitalEphemeris::kxBaseElements =
{
	PDE::Deg2Rad( 125.1228 ),
	PDE::Deg2Rad( 5.1454 ),
	PDE::Deg2Rad( 282.9404 ),
	-60.2666 * kdEarthRadiiAU,
	0.054900,
	PDE::Deg2Rad( 115.3654 ),
	PDE::Deg2Rad( 13.0649929509 ),
	static_cast< double >( J2000 - 1.5 )    // SE - NOTE: these elements have an epoch of '0' Jan 2000, 1.5 days before J2000.0
};

const KeplerElements MoonSchlyterOrbitalEphemeris::kxLinearPerturbations =
{
	PDE::Deg2Rad( 0.0529538083 ),
	0.0,
	PDE::Deg2Rad( 0.1643573223 ),
	0.0,
	0.000000001151,
	0.0,
	0.0,
	0.0
};

EphemerisVector4 MoonSchlyterOrbitalEphemeris::Perturb( const EphemerisVector4 xPosition, const double dT ) const
{
	const double dEclipticLongitude = CalculateLongitude( xPosition );
	const double dEclipticLatitude = CalculateLatitude( xPosition );

	const double dMeanAnomalyMoon = MeanAnomaly( dT );
	const double dMeanAnomalyEarth = EarthSchlyterOrbitalEphemeris::MeanAnomaly( dT );

	EarthSchlyterOrbitalEphemeris xEarthEphemeris;
	MoonSchlyterOrbitalEphemeris xMoonEphemeris;
	const double dArgumentOfPerifocusEarth = xEarthEphemeris.EvaluateArgumentOfPerifocus( dT );
	//const double dTrueAnomalyEarth = xEarthEphemeris.EvaluateTrueAnomaly( dT );

	const double dLongitudeOfAscendingNodeMoon = xMoonEphemeris.EvaluateLongitudeOfAscendingNode( dT );
	const double dArgumentOfPerifocusMoon = xMoonEphemeris.EvaluateArgumentOfPerifocus( dT );
	//const double dTrueAnomalyMoon = xMoonEphemeris.EvaluateTrueAnomaly( dT );

	const double dLongitudeSun = dMeanAnomalyEarth + dArgumentOfPerifocusEarth;
	const double dLongitudeMoon = dMeanAnomalyMoon + dArgumentOfPerifocusMoon + dLongitudeOfAscendingNodeMoon;

	const double dElongationMoon = dLongitudeMoon - dLongitudeSun;
	const double dArgumentOfLatitudeMoon = dLongitudeMoon - dLongitudeOfAscendingNodeMoon;

	// D = elongation moon
	// F = latitude thing
	const double dCorrectedLongitude = dEclipticLongitude
		- 1.274 * PDE::Sin( dMeanAnomalyEarth - 2.0 * dElongationMoon )	// evection
		+ 0.658 * PDE::Sin( 2.0 * dElongationMoon )						// variation
		- 0.186 * PDE::Sin( dMeanAnomalyEarth )							// yearly equation
		- 0.059 * PDE::Sin( 2.0 * ( dMeanAnomalyMoon - dElongationMoon ) )
		- 0.057 * PDE::Sin( dMeanAnomalyMoon - 2.0 * dElongationMoon + dMeanAnomalyEarth )
		+ 0.053 * PDE::Sin( dMeanAnomalyMoon + 2.0 * dElongationMoon )
		+ 0.046 * PDE::Sin( 2.0 * dElongationMoon - dMeanAnomalyEarth )
		+ 0.041 * PDE::Sin( dMeanAnomalyMoon - dMeanAnomalyEarth )
		- 0.035 * PDE::Sin( dElongationMoon )							// parallactic equation
		- 0.031 * PDE::Sin( dMeanAnomalyMoon + dMeanAnomalyEarth )
		- 0.015 * PDE::Sin( 2.0 * ( dArgumentOfLatitudeMoon - dElongationMoon ) )
		+ 0.011 * PDE::Sin( dMeanAnomalyMoon - 4.0 * dElongationMoon );

	const double dCorrectedLatitude = dEclipticLatitude
		- 0.173 * PDE::Sin( dArgumentOfLatitudeMoon - 2.0 * dElongationMoon )
		- 0.055 * PDE::Sin( dMeanAnomalyMoon - dArgumentOfLatitudeMoon - 2.0 * dElongationMoon )
		- 0.046 * PDE::Sin( dMeanAnomalyMoon + dArgumentOfLatitudeMoon - 2.0 * dElongationMoon )
		+ 0.033 * PDE::Sin( dArgumentOfLatitudeMoon + 2.0 * dElongationMoon )
		+ 0.017 * PDE::Sin( 2.0 * dMeanAnomalyMoon + dArgumentOfLatitudeMoon );

    const double dCorrectedDistance = xPosition.xyz().Magnitude()
        - 0.58 * kdEarthRadiiAU * PDE::Cos( dMeanAnomalyMoon - 2.0 * dElongationMoon )
        - 0.46 * kdEarthRadiiAU * PDE::Cos( 2.0 * dElongationMoon );
        ;

    return PositionFromLatLonRad( dCorrectedLatitude, dCorrectedLongitude, dCorrectedDistance );
}
<|endoftext|>


<commit_before>#include "broker.h"
#include "frame.h"
#include <sstream>

Broker::Broker() {

}

Broker::~Broker() {

}

MQTT_ERROR Broker::Start() {
    return NO_ERROR;
}

std::string Broker::ApplyDummyClientID() {
    std::stringstream ss;
    ss << "DummyClientID" << clients.size() + 1;
    return ss.str();
}

BrokerSideClient::BrokerSideClient(Transport* ct, Broker* b) : broker(b), Terminal("", NULL, 0, NULL) {
    this->ct = ct;
}

BrokerSideClient::~BrokerSideClient() {}

MQTT_ERROR BrokerSideClient::recvConnectMessage(ConnectMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvConnackMessage(ConnackMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvPublishMessage(PublishMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubackMessage(PubackMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubrecMessage(PubrecMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubrelMessage(PubrelMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubcompMessage(PubcompMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvSubscribeMessage(SubscribeMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvSubackMessage(SubackMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvUnsubscribeMessage(UnsubscribeMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvUnsubackMessage(UnsubackMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvPingreqMessage(PingreqMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPingrespMessage(PingrespMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvDisconnectMessage(DisconnectMessage* m) {return NO_ERROR;}
<commit_msg>add inside of constractor and destractor<commit_after>#include "broker.h"
#include "frame.h"
#include <sstream>

Broker::Broker() {
    topicRoot = new TopicNode("");
}

Broker::~Broker() {
    delete topicRoot;
}

MQTT_ERROR Broker::Start() {
    return NO_ERROR;
}

std::string Broker::ApplyDummyClientID() {
    std::stringstream ss;
    ss << "DummyClientID" << clients.size() + 1;
    return ss.str();
}

BrokerSideClient::BrokerSideClient(Transport* ct, Broker* b) : broker(b), Terminal("", NULL, 0, NULL) {
    this->ct = ct;
}

BrokerSideClient::~BrokerSideClient() {}

MQTT_ERROR BrokerSideClient::recvConnectMessage(ConnectMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvConnackMessage(ConnackMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvPublishMessage(PublishMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubackMessage(PubackMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubrecMessage(PubrecMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubrelMessage(PubrelMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPubcompMessage(PubcompMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvSubscribeMessage(SubscribeMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvSubackMessage(SubackMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvUnsubscribeMessage(UnsubscribeMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvUnsubackMessage(UnsubackMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvPingreqMessage(PingreqMessage* m) {return NO_ERROR;}
MQTT_ERROR BrokerSideClient::recvPingrespMessage(PingrespMessage* m) {return INVALID_MESSAGE_CAME;}
MQTT_ERROR BrokerSideClient::recvDisconnectMessage(DisconnectMessage* m) {return NO_ERROR;}
<|endoftext|>


<commit_before>#include "nixexpr.hh"
#include "parser.hh"
#include "hash.hh"
#include "util.hh"
#include "nixexpr-ast.hh"

#include <cstdlib>

using namespace nix;

struct Env;
struct Value;

typedef std::map<string, Value> Bindings;

struct Env
{
    Env * up;
    Bindings bindings;
};

typedef enum {
    tInt = 1,
    tAttrs,
    tThunk,
    tLambda,
    tCopy,
    tBlackhole
} ValueType;

struct Value
{
    ValueType type;
    union
    {
        int integer;
        Bindings * attrs;
        struct {
            Env * env;
            Expr expr;
        } thunk;
        struct {
            Env * env;
            Pattern pat;
            Expr body;
        } lambda;
        Value * val;
    };
};

std::ostream & operator << (std::ostream & str, Value & v)
{
    switch (v.type) {
    case tInt:
        str << v.integer;
        break;
    case tAttrs:
        str << "{ ";
        foreach (Bindings::iterator, i, *v.attrs)
            str << i->first << " = " << i->second << "; ";
        str << "}";
        break;
    case tThunk:
        str << "<CODE>";
        break;
    case tLambda:
        str << "<LAMBDA>";
        break;
    default:
        abort();
    }
    return str;
}

static void eval(Env * env, Expr e, Value & v);

void forceValue(Value & v)
{
    if (v.type == tThunk) {
        v.type = tBlackhole;
        eval(v.thunk.env, v.thunk.expr, v);
    }
    else if (v.type == tCopy) {
        forceValue(*v.val);
        v = *v.val;
    }
    else if (v.type == tBlackhole)
        throw EvalError("infinite recursion encountered");
}

Value * lookupVar(Env * env, const string & name)
{
    for ( ; env; env = env->up) {
        Bindings::iterator i = env->bindings.find(name);
        if (i != env->bindings.end()) return &i->second;
    }
    throw Error("undefined variable");
}

unsigned long nrValues = 0;

unsigned long nrEnvs = 0;

Env * allocEnv()
{
    nrEnvs++;
    return new Env;
}

static void eval(Env * env, Expr e, Value & v)
{
    printMsg(lvlError, format("eval: %1%") % e);

    ATerm name;
    if (matchVar(e, name)) {
        Value * v2 = lookupVar(env, aterm2String(name));
        forceValue(*v2);
        v = *v2;
        return;
    }

    int n;
    if (matchInt(e, n)) {
        v.type = tInt;
        v.integer = n;
        return;
    }

    ATermList es;
    if (matchAttrs(e, es)) {
        v.type = tAttrs;
        v.attrs = new Bindings;
        ATerm e2, pos;
        for (ATermIterator i(es); i; ++i) {
            if (!matchBind(*i, name, e2, pos)) abort(); /* can't happen */
            Value & v2 = (*v.attrs)[aterm2String(name)];
            nrValues++;
            v2.type = tThunk;
            v2.thunk.env = env;
            v2.thunk.expr = e2;
        }
        return;
    }

    ATermList rbnds, nrbnds;
    if (matchRec(e, rbnds, nrbnds)) {
        Env * env2 = allocEnv();
        env2->up = env;

        v.type = tAttrs;
        v.attrs = &env2->bindings;
        ATerm name, e2, pos;
        for (ATermIterator i(rbnds); i; ++i) {
            if (!matchBind(*i, name, e2, pos)) abort(); /* can't happen */
            Value & v2 = env2->bindings[aterm2String(name)];
            nrValues++;
            v2.type = tThunk;
            v2.thunk.env = env2;
            v2.thunk.expr = e2;
        }

        return;
    }

    Expr e2;
    if (matchSelect(e, e2, name)) {
        eval(env, e2, v);
        if (v.type != tAttrs) throw TypeError("expected attribute set");
        Bindings::iterator i = v.attrs->find(aterm2String(name));
        if (i == v.attrs->end()) throw TypeError("attribute not found");
        forceValue(i->second);
        v = i->second;
        return;
    }

    Pattern pat; Expr body; Pos pos;
    if (matchFunction(e, pat, body, pos)) {
        v.type = tLambda;
        v.lambda.env = env;
        v.lambda.pat = pat;
        v.lambda.body = body;
        return;
    }

    Expr fun, arg;
    if (matchCall(e, fun, arg)) {
        eval(env, fun, v);
        if (v.type != tLambda) throw TypeError("expected function");

        Env * env2 = allocEnv();
        env2->up = env;

        ATermList formals; ATerm ellipsis;

        if (matchVarPat(v.lambda.pat, name)) {
            Value & vArg = env2->bindings[aterm2String(name)];
            vArg.type = tThunk;
            vArg.thunk.env = env;
            vArg.thunk.expr = arg;
        }

        else if (matchAttrsPat(v.lambda.pat, formals, ellipsis, name)) {
            Value * vArg;
            Value vArg_;

            if (name == sNoAlias)
                vArg = &vArg_;
            else
                vArg = &env2->bindings[aterm2String(name)];

            eval(env, arg, *vArg);
            if (vArg->type != tAttrs) throw TypeError("expected attribute set");

            /* For each formal argument, get the actual argument.  If
               there is no matching actual argument but the formal
               argument has a default, use the default. */
            unsigned int attrsUsed = 0;
            for (ATermIterator i(formals); i; ++i) {
                Expr name, def;
                DefaultValue def2;
                if (!matchFormal(*i, name, def2)) abort(); /* can't happen */

                Bindings::iterator j = vArg->attrs->find(aterm2String(name));

                Value & v = env2->bindings[aterm2String(name)];

                if (j == vArg->attrs->end()) {
                    if (!matchDefaultValue(def2, def)) def = 0;
                    if (def == 0) throw TypeError(format("the argument named `%1%' required by the function is missing")
                        % aterm2String(name));
                    v.type = tThunk;
                    v.thunk.env = env2;
                    v.thunk.expr = def;
                } else {
                    attrsUsed++;
                    v.type = tCopy;
                    v.val = &j->second;
                }
            }

            /* Check that each actual argument is listed as a formal
               argument (unless the attribute match specifies a
               `...').  TODO: show the names of the
               expected/unexpected arguments. */
            if (ellipsis == eFalse && attrsUsed != vArg->attrs->size())
                throw TypeError("function called with unexpected argument");
        }

        else abort();

        eval(env2, v.lambda.body, v);
        return;
    }

    abort();
}

void doTest(string s)
{
    EvalState state;
    Expr e = parseExprFromString(state, s, "/");
    printMsg(lvlError, format(">>>>> %1%") % e);
    Value v;
    eval(0, e, v);
    printMsg(lvlError, format("result: %1%") % v);
}

void run(Strings args)
{
    printMsg(lvlError, format("size of value: %1% bytes") % sizeof(Value));

    doTest("123");
    doTest("{ x = 1; y = 2; }");
    doTest("{ x = 1; y = 2; }.y");
    doTest("rec { x = 1; y = x; }.y");
    doTest("(x: x) 1");
    doTest("(x: y: y) 1 2");
    doTest("x: x");
    doTest("({x, y}: x) { x = 1; y = 2; }");
    doTest("({x, y}@args: args.x) { x = 1; y = 2; }");
    doTest("(args@{x, y}: args.x) { x = 1; y = 2; }");
    doTest("({x ? 1}: x) { }");
    doTest("({x ? 1, y ? x}: y) { x = 2; }");
    doTest("({x, y, ...}: x) { x = 1; y = 2; z = 3; }");
    doTest("({x, y, ...}@args: args.z) { x = 1; y = 2; z = 3; }");
    //doTest("({x ? y, y ? x}: y) { }");

    printMsg(lvlError, format("alloced %1% values") % nrValues);
    printMsg(lvlError, format("alloced %1% environments") % nrEnvs);
}

void printHelp()
{
}

string programId = "eval-test";
<commit_msg>* Don't convert variable names to strings.<commit_after>#include "nixexpr.hh"
#include "parser.hh"
#include "hash.hh"
#include "util.hh"
#include "nixexpr-ast.hh"

#include <cstdlib>

using namespace nix;

struct Env;
struct Value;

typedef ATerm Sym;

typedef std::map<Sym, Value> Bindings;

struct Env
{
    Env * up;
    Bindings bindings;
};

typedef enum {
    tInt = 1,
    tAttrs,
    tThunk,
    tLambda,
    tCopy,
    tBlackhole
} ValueType;

struct Value
{
    ValueType type;
    union
    {
        int integer;
        Bindings * attrs;
        struct {
            Env * env;
            Expr expr;
        } thunk;
        struct {
            Env * env;
            Pattern pat;
            Expr body;
        } lambda;
        Value * val;
    };
};

std::ostream & operator << (std::ostream & str, Value & v)
{
    switch (v.type) {
    case tInt:
        str << v.integer;
        break;
    case tAttrs:
        str << "{ ";
        foreach (Bindings::iterator, i, *v.attrs)
            str << i->first << " = " << i->second << "; ";
        str << "}";
        break;
    case tThunk:
        str << "<CODE>";
        break;
    case tLambda:
        str << "<LAMBDA>";
        break;
    default:
        abort();
    }
    return str;
}

static void eval(Env * env, Expr e, Value & v);

void forceValue(Value & v)
{
    if (v.type == tThunk) {
        v.type = tBlackhole;
        eval(v.thunk.env, v.thunk.expr, v);
    }
    else if (v.type == tCopy) {
        forceValue(*v.val);
        v = *v.val;
    }
    else if (v.type == tBlackhole)
        throw EvalError("infinite recursion encountered");
}

Value * lookupVar(Env * env, Sym name)
{
    for ( ; env; env = env->up) {
        Bindings::iterator i = env->bindings.find(name);
        if (i != env->bindings.end()) return &i->second;
    }
    throw Error("undefined variable");
}

unsigned long nrValues = 0;

unsigned long nrEnvs = 0;

Env * allocEnv()
{
    nrEnvs++;
    return new Env;
}

static void eval(Env * env, Expr e, Value & v)
{
    printMsg(lvlError, format("eval: %1%") % e);

    Sym name;
    if (matchVar(e, name)) {
        Value * v2 = lookupVar(env, name);
        forceValue(*v2);
        v = *v2;
        return;
    }

    int n;
    if (matchInt(e, n)) {
        v.type = tInt;
        v.integer = n;
        return;
    }

    ATermList es;
    if (matchAttrs(e, es)) {
        v.type = tAttrs;
        v.attrs = new Bindings;
        ATerm e2, pos;
        for (ATermIterator i(es); i; ++i) {
            if (!matchBind(*i, name, e2, pos)) abort(); /* can't happen */
            Value & v2 = (*v.attrs)[name];
            nrValues++;
            v2.type = tThunk;
            v2.thunk.env = env;
            v2.thunk.expr = e2;
        }
        return;
    }

    ATermList rbnds, nrbnds;
    if (matchRec(e, rbnds, nrbnds)) {
        Env * env2 = allocEnv();
        env2->up = env;

        v.type = tAttrs;
        v.attrs = &env2->bindings;
        ATerm name, e2, pos;
        for (ATermIterator i(rbnds); i; ++i) {
            if (!matchBind(*i, name, e2, pos)) abort(); /* can't happen */
            Value & v2 = env2->bindings[name];
            nrValues++;
            v2.type = tThunk;
            v2.thunk.env = env2;
            v2.thunk.expr = e2;
        }

        return;
    }

    Expr e2;
    if (matchSelect(e, e2, name)) {
        eval(env, e2, v);
        if (v.type != tAttrs) throw TypeError("expected attribute set");
        Bindings::iterator i = v.attrs->find(name);
        if (i == v.attrs->end()) throw TypeError("attribute not found");
        forceValue(i->second);
        v = i->second;
        return;
    }

    Pattern pat; Expr body; Pos pos;
    if (matchFunction(e, pat, body, pos)) {
        v.type = tLambda;
        v.lambda.env = env;
        v.lambda.pat = pat;
        v.lambda.body = body;
        return;
    }

    Expr fun, arg;
    if (matchCall(e, fun, arg)) {
        eval(env, fun, v);
        if (v.type != tLambda) throw TypeError("expected function");

        Env * env2 = allocEnv();
        env2->up = env;

        ATermList formals; ATerm ellipsis;

        if (matchVarPat(v.lambda.pat, name)) {
            Value & vArg = env2->bindings[name];
            vArg.type = tThunk;
            vArg.thunk.env = env;
            vArg.thunk.expr = arg;
        }

        else if (matchAttrsPat(v.lambda.pat, formals, ellipsis, name)) {
            Value * vArg;
            Value vArg_;

            if (name == sNoAlias)
                vArg = &vArg_;
            else
                vArg = &env2->bindings[name];

            eval(env, arg, *vArg);
            if (vArg->type != tAttrs) throw TypeError("expected attribute set");

            /* For each formal argument, get the actual argument.  If
               there is no matching actual argument but the formal
               argument has a default, use the default. */
            unsigned int attrsUsed = 0;
            for (ATermIterator i(formals); i; ++i) {
                Expr def; Sym name;
                DefaultValue def2;
                if (!matchFormal(*i, name, def2)) abort(); /* can't happen */

                Bindings::iterator j = vArg->attrs->find(name);

                Value & v = env2->bindings[name];

                if (j == vArg->attrs->end()) {
                    if (!matchDefaultValue(def2, def)) def = 0;
                    if (def == 0) throw TypeError(format("the argument named `%1%' required by the function is missing")
                        % aterm2String(name));
                    v.type = tThunk;
                    v.thunk.env = env2;
                    v.thunk.expr = def;
                } else {
                    attrsUsed++;
                    v.type = tCopy;
                    v.val = &j->second;
                }
            }

            /* Check that each actual argument is listed as a formal
               argument (unless the attribute match specifies a
               `...').  TODO: show the names of the
               expected/unexpected arguments. */
            if (ellipsis == eFalse && attrsUsed != vArg->attrs->size())
                throw TypeError("function called with unexpected argument");
        }

        else abort();

        eval(env2, v.lambda.body, v);
        return;
    }

    abort();
}

void doTest(string s)
{
    EvalState state;
    Expr e = parseExprFromString(state, s, "/");
    printMsg(lvlError, format(">>>>> %1%") % e);
    Value v;
    eval(0, e, v);
    printMsg(lvlError, format("result: %1%") % v);
}

void run(Strings args)
{
    printMsg(lvlError, format("size of value: %1% bytes") % sizeof(Value));

    doTest("123");
    doTest("{ x = 1; y = 2; }");
    doTest("{ x = 1; y = 2; }.y");
    doTest("rec { x = 1; y = x; }.y");
    doTest("(x: x) 1");
    doTest("(x: y: y) 1 2");
    doTest("x: x");
    doTest("({x, y}: x) { x = 1; y = 2; }");
    doTest("({x, y}@args: args.x) { x = 1; y = 2; }");
    doTest("(args@{x, y}: args.x) { x = 1; y = 2; }");
    doTest("({x ? 1}: x) { }");
    doTest("({x ? 1, y ? x}: y) { x = 2; }");
    doTest("({x, y, ...}: x) { x = 1; y = 2; z = 3; }");
    doTest("({x, y, ...}@args: args.z) { x = 1; y = 2; z = 3; }");
    //doTest("({x ? y, y ? x}: y) { }");
    doTest("let x = 1; in x");

    printMsg(lvlError, format("alloced %1% values") % nrValues);
    printMsg(lvlError, format("alloced %1% environments") % nrEnvs);
}

void printHelp()
{
}

string programId = "eval-test";
<|endoftext|>


<commit_before>/*
    This program shows how to process BLAS LEVEL2 syr2

    for i = 0 .. N
        for j = 0 .. N
            C[i,j] = A[i,j] + alpha * X[i]*Y[j] + alpha * X[j]*Y[i]
*/

#include <tiramisu/tiramisu.h>
#define NN 100
#define alpha 3
using namespace tiramisu;

int main(int argc, char **argv)
{
    tiramisu::init("syr2");

    // -------------------------------------------------------
    // Layer I
    // -------------------------------------------------------
    constant N("N", NN);
    var i("i", 0, N), j("j", 0, N);
    // Declare inputs : A(Matrix N*N) , X(Vector dim=N) , Y(Vector dim=N)
    input A("A", {i, j}, p_uint8);
    input x("B", {i}, p_uint8);
    input y("C", {j}, p_uint8);
    // Declare output which is result of computation
    computation output("output", {i,j}, expr((uint8_t)alpha) * x(i) * y(j) + expr((uint8_t)alpha) * x(j) * y(i)  + A(i, j) );

    // -------------------------------------------------------
    // Layer III
    // -------------------------------------------------------
    // Declare the buffers.
    buffer b_A("b_A", {N,N}, p_uint8, a_input);
    buffer b_x("b_x", {N}, p_uint8, a_input);
    buffer b_y("b_y", {N}, p_uint8, a_input);
    buffer b_output("b_output", {N,N}, p_uint8, a_output);
    // Map the computations to a buffer.
    A.store_in(&b_A);
    x.store_in(&b_x);
    y.store_in(&b_y);
    output.store_in(&b_output,{i,j});

    // -------------------------------------------------------
    // Code Generation
    // -------------------------------------------------------
    tiramisu::codegen({&b_A, &b_x, &b_y, &b_output}, "build/generated_syr2_2.o");

    return 0;
}
<commit_msg>Delete syr2_2_generator.cpp<commit_after><|endoftext|>


<commit_before>/*
 * DiscoveryListener
 * Aug 2014
 * nathan lachenmyer
 */

#include <memory>
#include "DiscoveryListener.h"
#include "DeviceHeader.h"

using namespace ofxPixelPusher;

DiscoveryListener* DiscoveryListener::mDiscoveryService = NULL;

DiscoveryListener* DiscoveryListener::getInstance() {
	if (mDiscoveryService == NULL) {
		mDiscoveryService = new DiscoveryListener();
	}
	return mDiscoveryService;
}

void DiscoveryListener::freeInstance() {
	delete mDiscoveryService;
	mDiscoveryService = NULL;
}

int DiscoveryListener::getFrameLimit() {
	return mFrameLimit;
}

std::vector<std::shared_ptr<PixelPusher> > DiscoveryListener::getPushers() {
	mUpdateMutex.lock();
	std::vector<std::shared_ptr<PixelPusher> > pusherVector;
	for (std::map<std::string, std::shared_ptr<PixelPusher> >::iterator it = mPusherMap.begin();
	it != mPusherMap.end();
		++it) {
		pusherVector.push_back(it->second);
	}
	mUpdateMutex.unlock();
	return pusherVector;
}

std::vector<std::shared_ptr<PixelPusher> > DiscoveryListener::getGroup(long groupId) {
	mUpdateMutex.lock();
	std::vector<std::shared_ptr<PixelPusher> > pusherVector;
	for (std::map<long, std::shared_ptr<PixelPusher> >::iterator it = mGroupMap.lower_bound(groupId);
	it != mGroupMap.upper_bound(groupId);
		++it) {
		pusherVector.push_back(it->second);
	}
	mUpdateMutex.unlock();
	return pusherVector;
}

std::shared_ptr<PixelPusher> DiscoveryListener::getController(long groupId, long controllerId) {
	mUpdateMutex.lock();
	for (std::map<long, std::shared_ptr<PixelPusher> >::iterator it = mGroupMap.lower_bound(groupId);
	it != mGroupMap.upper_bound(groupId);
		++it) {
		if (it->second->getControllerId() == controllerId) {
			mUpdateMutex.unlock();
			return it->second;
		}
	}
	//if no matching PixelPusher is found, return a nullPtr
	std::shared_ptr<PixelPusher> nullPtr;
	mUpdateMutex.unlock();
	return nullPtr;
}

DiscoveryListener::DiscoveryListener() {
	mDiscoveryServiceSocket.Create();
	mDiscoveryServiceSocket.Bind(mPort);
	mDiscoveryServiceSocket.SetNonBlocking(true);
	std::printf("Starting Discovery Listener Service...\n");

	mAutoThrottle = true;
	mFrameLimit = 60;

	mUpdateMapThread = std::thread(&DiscoveryListener::updatePusherMap, this);
}

DiscoveryListener::~DiscoveryListener() {
	if (mUpdateMapThread.joinable()) {
		mUpdateMapThread.join();
	}
}

void DiscoveryListener::receive() {
	char udpMessage[4096];
	int bytesReceived = mDiscoveryServiceSocket.Receive(udpMessage, 4096);
	if (bytesReceived > 0) {
		DiscoveryListener::getInstance()->update(std::string(udpMessage));
	}
}

void DiscoveryListener::update(std::string udpMessage) {
	std::printf("Updating registry...\n");
	mUpdateMutex.lock();
	DeviceHeader* header;

	header = new DeviceHeader(reinterpret_cast<const unsigned char*> (udpMessage.c_str()), udpMessage.length());
	if (header->getDeviceType() != PIXELPUSHER) {
		//if the device type isn't PixelPusher, end processing it right here.
		return;
	}

	std::shared_ptr<PixelPusher> incomingDevice(new PixelPusher(header));
	std::string macAddress = incomingDevice->getMacAddress();
	std::string ipAddress = incomingDevice->getIpAddress();
	mLastSeenMap[macAddress] = std::clock() / CLOCKS_PER_SEC;

	if (mPusherMap.count(macAddress) == 0) {
		//does not already exist in the map
		addNewPusher(macAddress, incomingDevice);
		std::printf("Adding new PixelPusher %s at address %s\n", macAddress.c_str(), ipAddress.c_str());
	}
	else {
		//already exists in the map
		if (!mPusherMap[macAddress]->isEqual(incomingDevice)) {
			//if the pushers are not equal, replace it with this one
			updatePusher(macAddress, incomingDevice);
			std::printf("Updating PixelPusher %s at address %s\n", macAddress.c_str(), ipAddress.c_str());
		}
		else {
			//if they're the same, then just update it
			mPusherMap[macAddress]->updateVariables(incomingDevice);
			std::printf("Updating PixelPusher %s at address %s\n", macAddress.c_str(), ipAddress.c_str());
			if (incomingDevice->getDeltaSequence() > 3) {
				mPusherMap[macAddress]->increaseExtraDelay(5);
			}
			if (incomingDevice->getDeltaSequence() < 1) {
				mPusherMap[macAddress]->decreaseExtraDelay(1);
			}
		}
	}

	mUpdateMutex.unlock();
}

void DiscoveryListener::addNewPusher(std::string macAddress, std::shared_ptr<PixelPusher> pusher) {
	mPusherMap.insert(std::make_pair(macAddress, pusher));
	mGroupMap.insert(std::make_pair(pusher->getGroupId(), pusher));
	pusher->createCardThread();
}

void DiscoveryListener::updatePusher(std::string macAddress, std::shared_ptr<PixelPusher> pusher) {
	mPusherMap[macAddress]->copyHeader(pusher);
}

void DiscoveryListener::updatePusherMap() {
	mRunUpdateMapThread = true;
	while (mRunUpdateMapThread) {
		mUpdateMutex.lock();
		for (std::map<std::string, std::shared_ptr<PixelPusher> >::iterator pusher = mPusherMap.begin(); pusher != mPusherMap.end();) {
			//pusher->first is Mac Address, pusher->second is the shared pointer to the PixelPusher
			if (!pusher->second->isAlive()) {
				std::printf("DiscoveryListener removing PixelPusher %s from all maps.\n", pusher->first.c_str());
				pusher->second->destroyCardThread();
				//remove pusher from maps
				mLastSeenMap.erase(pusher->first);
				mPusherMap.erase(pusher++);
			}
			else {
				++pusher;
			}
		}
		mUpdateMutex.unlock();
		this_thread::sleep_for(std::chrono::milliseconds(1000));
	}
}
<commit_msg>integrated with ofxNetwork, but ofxNetwork doesnt appear to handle broadcasts properly<commit_after>/*
 * DiscoveryListener
 * Aug 2014
 * nathan lachenmyer
 */

#include <memory>
#include "DiscoveryListener.h"
#include "DeviceHeader.h"

using namespace ofxPixelPusher;

DiscoveryListener* DiscoveryListener::mDiscoveryService = NULL;

DiscoveryListener* DiscoveryListener::getInstance() {
	if (mDiscoveryService == NULL) {
		mDiscoveryService = new DiscoveryListener();
	}
	return mDiscoveryService;
}

void DiscoveryListener::freeInstance() {
	delete mDiscoveryService;
	mDiscoveryService = NULL;
}

int DiscoveryListener::getFrameLimit() {
	return mFrameLimit;
}

std::vector<std::shared_ptr<PixelPusher> > DiscoveryListener::getPushers() {
	mUpdateMutex.lock();
	std::vector<std::shared_ptr<PixelPusher> > pusherVector;
	for (std::map<std::string, std::shared_ptr<PixelPusher> >::iterator it = mPusherMap.begin();
	it != mPusherMap.end();
		++it) {
		pusherVector.push_back(it->second);
	}
	mUpdateMutex.unlock();
	return pusherVector;
}

std::vector<std::shared_ptr<PixelPusher> > DiscoveryListener::getGroup(long groupId) {
	mUpdateMutex.lock();
	std::vector<std::shared_ptr<PixelPusher> > pusherVector;
	for (std::map<long, std::shared_ptr<PixelPusher> >::iterator it = mGroupMap.lower_bound(groupId);
	it != mGroupMap.upper_bound(groupId);
		++it) {
		pusherVector.push_back(it->second);
	}
	mUpdateMutex.unlock();
	return pusherVector;
}

std::shared_ptr<PixelPusher> DiscoveryListener::getController(long groupId, long controllerId) {
	mUpdateMutex.lock();
	for (std::map<long, std::shared_ptr<PixelPusher> >::iterator it = mGroupMap.lower_bound(groupId);
	it != mGroupMap.upper_bound(groupId);
		++it) {
		if (it->second->getControllerId() == controllerId) {
			mUpdateMutex.unlock();
			return it->second;
		}
	}
	//if no matching PixelPusher is found, return a nullPtr
	std::shared_ptr<PixelPusher> nullPtr;
	mUpdateMutex.unlock();
	return nullPtr;
}

DiscoveryListener::DiscoveryListener() {
	mDiscoveryServiceSocket.Create();
	mDiscoveryServiceSocket.BindMcast("0.0.0.0", mPort);
	mDiscoveryServiceSocket.SetNonBlocking(true);
	std::printf("Starting Discovery Listener Service...\n");

	mAutoThrottle = true;
	mFrameLimit = 60;

	mUpdateMapThread = std::thread(&DiscoveryListener::updatePusherMap, this);
}

DiscoveryListener::~DiscoveryListener() {
	if (mUpdateMapThread.joinable()) {
		mUpdateMapThread.join();
	}
}

void DiscoveryListener::receive() {
	char udpMessage[4096];
	int bytesReceived = mDiscoveryServiceSocket.Receive(udpMessage, 4096);
	if (bytesReceived > 0) {
		DiscoveryListener::getInstance()->update(std::string(udpMessage));
	}
}

void DiscoveryListener::update(std::string udpMessage) {
	std::printf("Updating registry...\n");
	mUpdateMutex.lock();
	DeviceHeader* header;

	header = new DeviceHeader(reinterpret_cast<const unsigned char*> (udpMessage.c_str()), udpMessage.length());
	if (header->getDeviceType() != PIXELPUSHER) {
		//if the device type isn't PixelPusher, end processing it right here.
		return;
	}

	std::shared_ptr<PixelPusher> incomingDevice(new PixelPusher(header));
	std::string macAddress = incomingDevice->getMacAddress();
	std::string ipAddress = incomingDevice->getIpAddress();
	mLastSeenMap[macAddress] = std::clock() / CLOCKS_PER_SEC;

	if (mPusherMap.count(macAddress) == 0) {
		//does not already exist in the map
		addNewPusher(macAddress, incomingDevice);
		std::printf("Adding new PixelPusher %s at address %s\n", macAddress.c_str(), ipAddress.c_str());
	}
	else {
		//already exists in the map
		if (!mPusherMap[macAddress]->isEqual(incomingDevice)) {
			//if the pushers are not equal, replace it with this one
			updatePusher(macAddress, incomingDevice);
			std::printf("Updating PixelPusher %s at address %s\n", macAddress.c_str(), ipAddress.c_str());
		}
		else {
			//if they're the same, then just update it
			mPusherMap[macAddress]->updateVariables(incomingDevice);
			std::printf("Updating PixelPusher %s at address %s\n", macAddress.c_str(), ipAddress.c_str());
			if (incomingDevice->getDeltaSequence() > 3) {
				mPusherMap[macAddress]->increaseExtraDelay(5);
			}
			if (incomingDevice->getDeltaSequence() < 1) {
				mPusherMap[macAddress]->decreaseExtraDelay(1);
			}
		}
	}

	mUpdateMutex.unlock();
}

void DiscoveryListener::addNewPusher(std::string macAddress, std::shared_ptr<PixelPusher> pusher) {
	mPusherMap.insert(std::make_pair(macAddress, pusher));
	mGroupMap.insert(std::make_pair(pusher->getGroupId(), pusher));
	pusher->createCardThread();
}

void DiscoveryListener::updatePusher(std::string macAddress, std::shared_ptr<PixelPusher> pusher) {
	mPusherMap[macAddress]->copyHeader(pusher);
}

void DiscoveryListener::updatePusherMap() {
	mRunUpdateMapThread = true;
	while (mRunUpdateMapThread) {
		mUpdateMutex.lock();
		for (std::map<std::string, std::shared_ptr<PixelPusher> >::iterator pusher = mPusherMap.begin(); pusher != mPusherMap.end();) {
			//pusher->first is Mac Address, pusher->second is the shared pointer to the PixelPusher
			if (!pusher->second->isAlive()) {
				std::printf("DiscoveryListener removing PixelPusher %s from all maps.\n", pusher->first.c_str());
				pusher->second->destroyCardThread();
				//remove pusher from maps
				mLastSeenMap.erase(pusher->first);
				mPusherMap.erase(pusher++);
			}
			else {
				++pusher;
			}
		}
		mUpdateMutex.unlock();
		this_thread::sleep_for(std::chrono::milliseconds(1000));
	}
}
<|endoftext|>


<commit_before>#include <rang.hpp>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>
#include <date.h>

#include "Tools/Display/Terminal/Terminal.hpp"

#ifdef ENABLE_MPI
#include <mpi.h>
#endif

#include "Tools/general_utils.h"
#include "Tools/system_functions.h"
#include "Tools/Display/rang_format/rang_format.h"
#include "Tools/Exception/exception.hpp"

#include "Factory/Module/Source/Source.hpp"
#include "Factory/Module/CRC/CRC.hpp"
#include "Factory/Module/Encoder/Encoder.hpp"
#include "Factory/Module/Puncturer/Puncturer.hpp"
#include "Factory/Module/Interleaver/Interleaver.hpp"
#include "Factory/Module/Modem/Modem.hpp"
#include "Factory/Module/Channel/Channel.hpp"
#include "Factory/Module/Quantizer/Quantizer.hpp"
#include "Factory/Module/Decoder/Decoder.hpp"
#include "Factory/Module/Monitor/Monitor.hpp"
#include "Factory/Tools/Display/Terminal/Terminal.hpp"

#include "Launcher.hpp"

using namespace aff3ct;
using namespace aff3ct::launcher;

Launcher::Launcher(const int argc, const char **argv, factory::Simulation::parameters &params_common,
                   std::ostream &stream)
: simu(nullptr), ah(argc, argv), params_common(params_common), stream(stream)
{
	cmd_line += std::string(argv[0]) + std::string(" ");
	for (auto i = 1; i < argc; i++)
	{
		if (argv[i][0] == '-')
			cmd_line += std::string(argv[i]);
		else
			cmd_line += std::string("\"") + std::string(argv[i]) + std::string("\"");

		cmd_line += std::string(" ");
	}
}

Launcher::~Launcher()
{
}

void Launcher::get_description_args()
{
}

void Launcher::store_args()
{
}

int Launcher::read_arguments()
{
	this->get_description_args();

	std::vector<std::string> cmd_error;

	this->arg_vals = ah.parse_arguments(this->args, this->cmd_warn, cmd_error);

	try
	{
		this->store_args();
	}
	catch(const std::exception& e)
	{
		auto save = tools::exception::no_backtrace;
		tools::exception::no_backtrace = true;
		cmd_error.emplace_back(e.what());
		tools::exception::no_backtrace = save;
	}

	if (params_common.display_help)
	{
		auto grps = factory::Factory::create_groups({&params_common});
		ah.print_help(this->args, grps, params_common.display_adv_help);
	}

	// print usage
	if (!cmd_error.empty() && !params_common.display_help)
		ah.print_usage(this->args);

	// print the errors
	if (!cmd_error.empty()) std::cerr << std::endl;
	for (unsigned e = 0; e < cmd_error.size(); e++)
		std::cerr << rang::tag::error << cmd_error[e] << std::endl;

	// print the help tags
	if (!cmd_error.empty() && !params_common.display_help)
	{
		tools::Argument_tag help_tag = {"help", "h"};

		std::string message = "For more information please display the help (\"";
		message += tools::Argument_handler::print_tag(help_tag) += "\").";

		std::cerr << std::endl << rang::tag::info << message << std::endl;
	}

	return (!cmd_error.empty() || params_common.display_help) ? EXIT_FAILURE : EXIT_SUCCESS;
}

void Launcher::print_header()
{
	// display configuration and simulation parameters
	stream << rang::tag::comment << rang::style::bold << "----------------------------------------------------" << std::endl;
	stream << rang::tag::comment << rang::style::bold << "---- A FAST FORWARD ERROR CORRECTION TOOLBOX >> ----" << std::endl;
	stream << rang::tag::comment << rang::style::bold << "----------------------------------------------------" << std::endl;
	stream << rang::tag::comment << rang::style::bold << rang::style::underline << "Parameters :"<< rang::style::reset << std::endl;
	factory::Header::print_parameters({&params_common}, false, this->stream);
	this->stream << rang::tag::comment << std::endl;
}

int Launcher::launch()
{
	int exit_code = EXIT_SUCCESS;

	std::srand((unsigned)this->params_common.global_seed);

	// in case of the user call launch multiple times
	if (simu != nullptr)
	{
		delete simu;
		simu = nullptr;
	}

	if (this->read_arguments() == EXIT_FAILURE)
	{
		// print the warnings
#ifdef ENABLE_MPI
		if (this->params_common.mpi_rank == 0)
#endif
			for (unsigned w = 0; w < this->cmd_warn.size(); w++)
				std::clog << rang::tag::warning << this->cmd_warn[w] << std::endl;
		return EXIT_FAILURE;
	}

	// write the command and he curve name in the PyBER format
#ifdef ENABLE_MPI
	if (!this->params_common.pyber.empty() && this->params_common.mpi_rank == 0)
#else
	if (!this->params_common.pyber.empty())
#endif
	{
		stream << "Run command:"     << std::endl;
		stream << cmd_line           << std::endl;
		stream << "Curve name:"      << std::endl;
		stream << this->params_common.pyber << std::endl;
	}

	if (this->params_common.display_legend)
#ifdef ENABLE_MPI
		if (this->params_common.mpi_rank == 0)
#endif
			this->print_header();

	// print the warnings
#ifdef ENABLE_MPI
	if (this->params_common.mpi_rank == 0)
#endif
		for (unsigned w = 0; w < this->cmd_warn.size(); w++)
			std::clog << rang::tag::warning << this->cmd_warn[w] << std::endl;

	try
	{
		simu = this->build_simu();
	}
	catch(const std::exception& e)
	{
		rang::format_on_each_line(std::cerr, std::string(e.what()) + "\n", rang::tag::error);
		exit_code = EXIT_FAILURE;
	}

	if (simu != nullptr)
	{
		// launch the simulation
		if (this->params_common.display_legend)
#ifdef ENABLE_MPI
			if (this->params_common.mpi_rank == 0)
#endif
				stream << rang::tag::comment << "The simulation is running..." << std::endl;

		try
		{
			simu->launch();
			if (simu->is_error())
				exit_code = EXIT_FAILURE;
		}
		catch(const std::exception& e)
		{
			rang::format_on_each_line(std::cerr, std::string(e.what()) + "\n", rang::tag::error);
			exit_code = EXIT_FAILURE;
		}
	}

	if (this->params_common.display_legend)
#ifdef ENABLE_MPI
		if (this->params_common.mpi_rank == 0)
#endif
			stream << rang::tag::comment << "End of the simulation." << std::endl;

	if (simu != nullptr)
	{
		delete simu;
		simu = nullptr;
	}

	return exit_code;
}
<commit_msg>Put back 'Trace:' when --sim-pyber.<commit_after>#include <rang.hpp>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional>
#include <date.h>

#include "Tools/Display/Terminal/Terminal.hpp"

#ifdef ENABLE_MPI
#include <mpi.h>
#endif

#include "Tools/general_utils.h"
#include "Tools/system_functions.h"
#include "Tools/Display/rang_format/rang_format.h"
#include "Tools/Exception/exception.hpp"

#include "Factory/Module/Source/Source.hpp"
#include "Factory/Module/CRC/CRC.hpp"
#include "Factory/Module/Encoder/Encoder.hpp"
#include "Factory/Module/Puncturer/Puncturer.hpp"
#include "Factory/Module/Interleaver/Interleaver.hpp"
#include "Factory/Module/Modem/Modem.hpp"
#include "Factory/Module/Channel/Channel.hpp"
#include "Factory/Module/Quantizer/Quantizer.hpp"
#include "Factory/Module/Decoder/Decoder.hpp"
#include "Factory/Module/Monitor/Monitor.hpp"
#include "Factory/Tools/Display/Terminal/Terminal.hpp"

#include "Launcher.hpp"

using namespace aff3ct;
using namespace aff3ct::launcher;

Launcher::Launcher(const int argc, const char **argv, factory::Simulation::parameters &params_common,
                   std::ostream &stream)
: simu(nullptr), ah(argc, argv), params_common(params_common), stream(stream)
{
	cmd_line += std::string(argv[0]) + std::string(" ");
	for (auto i = 1; i < argc; i++)
	{
		if (argv[i][0] == '-')
			cmd_line += std::string(argv[i]);
		else
			cmd_line += std::string("\"") + std::string(argv[i]) + std::string("\"");

		cmd_line += std::string(" ");
	}
}

Launcher::~Launcher()
{
}

void Launcher::get_description_args()
{
}

void Launcher::store_args()
{
}

int Launcher::read_arguments()
{
	this->get_description_args();

	std::vector<std::string> cmd_error;

	this->arg_vals = ah.parse_arguments(this->args, this->cmd_warn, cmd_error);

	try
	{
		this->store_args();
	}
	catch(const std::exception& e)
	{
		auto save = tools::exception::no_backtrace;
		tools::exception::no_backtrace = true;
		cmd_error.emplace_back(e.what());
		tools::exception::no_backtrace = save;
	}

	if (params_common.display_help)
	{
		auto grps = factory::Factory::create_groups({&params_common});
		ah.print_help(this->args, grps, params_common.display_adv_help);
	}

	// print usage
	if (!cmd_error.empty() && !params_common.display_help)
		ah.print_usage(this->args);

	// print the errors
	if (!cmd_error.empty()) std::cerr << std::endl;
	for (unsigned e = 0; e < cmd_error.size(); e++)
		std::cerr << rang::tag::error << cmd_error[e] << std::endl;

	// print the help tags
	if (!cmd_error.empty() && !params_common.display_help)
	{
		tools::Argument_tag help_tag = {"help", "h"};

		std::string message = "For more information please display the help (\"";
		message += tools::Argument_handler::print_tag(help_tag) += "\").";

		std::cerr << std::endl << rang::tag::info << message << std::endl;
	}

	return (!cmd_error.empty() || params_common.display_help) ? EXIT_FAILURE : EXIT_SUCCESS;
}

void Launcher::print_header()
{
	// display configuration and simulation parameters
	stream << rang::tag::comment << rang::style::bold << "----------------------------------------------------" << std::endl;
	stream << rang::tag::comment << rang::style::bold << "---- A FAST FORWARD ERROR CORRECTION TOOLBOX >> ----" << std::endl;
	stream << rang::tag::comment << rang::style::bold << "----------------------------------------------------" << std::endl;
	stream << rang::tag::comment << rang::style::bold << rang::style::underline << "Parameters :"<< rang::style::reset << std::endl;
	factory::Header::print_parameters({&params_common}, false, this->stream);
	this->stream << rang::tag::comment << std::endl;
}

int Launcher::launch()
{
	int exit_code = EXIT_SUCCESS;

	std::srand((unsigned)this->params_common.global_seed);

	// in case of the user call launch multiple times
	if (simu != nullptr)
	{
		delete simu;
		simu = nullptr;
	}

	if (this->read_arguments() == EXIT_FAILURE)
	{
		// print the warnings
#ifdef ENABLE_MPI
		if (this->params_common.mpi_rank == 0)
#endif
			for (unsigned w = 0; w < this->cmd_warn.size(); w++)
				std::clog << rang::tag::warning << this->cmd_warn[w] << std::endl;
		return EXIT_FAILURE;
	}

	// write the command and he curve name in the PyBER format
#ifdef ENABLE_MPI
	if (!this->params_common.pyber.empty() && this->params_common.mpi_rank == 0)
#else
	if (!this->params_common.pyber.empty())
#endif
	{
		stream << "Run command:"            << std::endl;
		stream << cmd_line                  << std::endl;
		stream << "Curve name:"             << std::endl;
		stream << this->params_common.pyber << std::endl;
		stream << "Trace:"                  << std::endl;
	}

	if (this->params_common.display_legend)
#ifdef ENABLE_MPI
		if (this->params_common.mpi_rank == 0)
#endif
			this->print_header();

	// print the warnings
#ifdef ENABLE_MPI
	if (this->params_common.mpi_rank == 0)
#endif
		for (unsigned w = 0; w < this->cmd_warn.size(); w++)
			std::clog << rang::tag::warning << this->cmd_warn[w] << std::endl;

	try
	{
		simu = this->build_simu();
	}
	catch(const std::exception& e)
	{
		rang::format_on_each_line(std::cerr, std::string(e.what()) + "\n", rang::tag::error);
		exit_code = EXIT_FAILURE;
	}

	if (simu != nullptr)
	{
		// launch the simulation
		if (this->params_common.display_legend)
#ifdef ENABLE_MPI
			if (this->params_common.mpi_rank == 0)
#endif
				stream << rang::tag::comment << "The simulation is running..." << std::endl;

		try
		{
			simu->launch();
			if (simu->is_error())
				exit_code = EXIT_FAILURE;
		}
		catch(const std::exception& e)
		{
			rang::format_on_each_line(std::cerr, std::string(e.what()) + "\n", rang::tag::error);
			exit_code = EXIT_FAILURE;
		}
	}

	if (this->params_common.display_legend)
#ifdef ENABLE_MPI
		if (this->params_common.mpi_rank == 0)
#endif
			stream << rang::tag::comment << "End of the simulation." << std::endl;

	if (simu != nullptr)
	{
		delete simu;
		simu = nullptr;
	}

	return exit_code;
}
<|endoftext|>