<commit_before>#include <boost_common.h>
#include <boilerplate.cpp>
#include <autogen_converters.cpp>

bool VBoostedMaxEnt__wrap_train(VBoostedMaxEnt* inst,
                                PyObject* X_train,
                                PyObject* Y_train)
{
    PyArrayObject *xao = (PyArrayObject*)X_train;
    PyArrayObject *yao = (PyArrayObject*)Y_train;

    if (xao->dimensions[0] != yao->dimensions[0]) {
      printf("oh no, X train has %zu entries but Y train has %zu\n",
             xao->dimensions[0],
             yao->dimensions[0]);
    }

    vector<const vector<double>*> Xvec;
    vector<const vector<double>*> Yvec;

    for (int i=0; i<xao->dimensions[0]; i++) {
      vector<double> *tmp = new vector<double>(((double*)xao->data) + i*xao->dimensions[1],
                                               ((double*)xao->data) + (i+1)*xao->dimensions[1]);
      Xvec.push_back(const_cast<const vector<double>*>(tmp));

      tmp = new vector<double>(&(((double*)yao->data)[i*yao->dimensions[1]]),
                               &(((double*)yao->data)[(i+1)*yao->dimensions[1]]));
      double total_prob = 0.0;
      for (int j=0; j<yao->dimensions[1]; j++) {
          total_prob += (*tmp)[j];
      }
      Yvec.push_back(const_cast<const vector<double>*>(tmp));
    }
    vector<double> w_fold(Xvec.size(), 1.0);
    inst->train(Xvec, Yvec, w_fold, NULL, NULL);

    for (int i=0; i<xao->dimensions[0]; i++) {
      delete Xvec[i];
      delete Yvec[i];
    }
    return false;
}

PyObject* VBoostedMaxEnt__wrap_predict(VBoostedMaxEnt* inst,
                                       vector<double> query)
{
    vector<double> ret(2);
    inst->predict(query, ret);
    return vec_to_numpy(ret);
}

vector<VRandomForest*> VBoostedMaxEnt__get_vec_vrandomforest(VBoostedMaxEnt* inst)
{
  vector<VRandomForest*> ret;
  foreach (it, inst->m_vregressors) {
    /* C++ is beautiful:
     * - the innermost * dereferences the iterator;
     * - the next * dereferences the shared ptr;
     * - the & gets the address of the actual object, because boost can't deal with std
     *     tr1 shared ptrs
     * - it's officially a vector of VRegressors, but we happen to know they're really
     *     VRandomForests, so cast.
     */
    ret.push_back((VRandomForest*)&(*(*it)));
  }
  return ret;
}
/* at some point I gotta figure out how to make readonly properties of pointer
 * fields without this crap
 */
VRandomForest::VTreeNode* VTreeNode__get_left(VRandomForest::VTreeNode* inst)
{
    return inst->left;
}
VRandomForest::VTreeNode* VTreeNode__get_right(VRandomForest::VTreeNode* inst)
{
    return inst->right;
}

void VTreeNode__refill_avg_outputs(VRandomForest::VTreeNode *inst)
{
    if (inst->avg_output.size() > 0)
        return;

    if (inst->left->avg_output.size() == 0)
        VTreeNode__refill_avg_outputs(inst->left);
    if (inst->right->avg_output.size() == 0)
        VTreeNode__refill_avg_outputs(inst->right);

    for (int i=0; i<inst->left->avg_output.size(); i++) {
        inst->avg_output.push_back((inst->left->avg_output[i] +
                                    inst->right->avg_output[i]) / 2.0);
    }
}

void VRandomForest__wrap_doTrain(VRandomForest *inst,
                                 pyarr<double> X,
                                 pyarr<double> Y)
{
    vector<const vector<double>*> Xv, Yv;
    for (int i=0; i<X.dims[0]; i++) {
        vector<double>* Xtmp = new vector<double>(X.dims[1]);
        vector<double>* Ytmp = new vector<double>(Y.dims[1]);
        for (int j=0; j<X.dims[1]; j++) {
            (*Xtmp)[j] = X[ind(i,j)];
        }
        for (int j=0; j<Y.dims[1]; j++) {
            (*Ytmp)[j] = Y[ind(i,j)];
        }
        Xv.push_back(const_cast<const vector<double>*>(Xtmp));
        Yv.push_back(const_cast<const vector<double>*>(Ytmp));
    }
    vector<double> weights(X.dims[0], 1.0), feature_costs;
    vector<size_t> usable_features, required_features;

    inst->doTrain(Xv, Yv, weights, usable_features, feature_costs, required_features);
    for (int i=0; i<X.dims[0]; i++) {
        delete Xv[i];
        delete Yv[i];
    }
}

pyarr<double> VRandomForest__wrap_doPredict(VRandomForest *inst,
                                            pyarr<double> X)
{
    long int argh[] = {inst->getDimTarget()};
    pyarr<double> ret(1, argh);

    vector<double> xv(X.dims[0]), yv(ret.dims[0]);
    for (int i=0; i<X.dims[0]; i++) {
        xv[i] = X[ind(i)];
    }
    inst->doPredict(xv, yv);
    for (int i=0; i<ret.dims[0]; i++){
        ret[ind(i)] = yv[i];
    }
    return ret;
}

void set_logger_verbosity(string verbosity)
{
    misc_util::Logger::status_t s;
    if (verbosity == "debug") s = misc_util::Logger::DEBUG;
    else if (verbosity == "info") s = misc_util::Logger::INFO;
    else if (verbosity == "warning") s = misc_util::Logger::WARNING;
    else if (verbosity == "error") s = misc_util::Logger::ERROR;
    else s = misc_util::Logger::INFO;

    misc_util::Logger::setVerbosity(s);
}

static bool boosted_common = false;

void boost_common()
{
    import_array();
    if (0 && boosted_common) return;
    boosted_common = true;

    long int dims[] = {10, 10, 10};
    pyarr<double> d(3, dims);
    pyarr<float> f(3, dims);
    pyarr<int> i(3, dims);
    pyarr<long int> l(3, dims);
    pyarr<unsigned char> uc(3, dims);
    pyarr<unsigned int> ui(3, dims);
    pyarr<char> c(3, dims);

    printf("d %d f %d i %d l %d uc %d ui %d c %d\n",
           d.ao->descr->type_num,
           f.ao->descr->type_num,
           i.ao->descr->type_num,
           l.ao->descr->type_num,
           uc.ao->descr->type_num,
           ui.ao->descr->type_num,
           c.ao->descr->type_num);

    to_python_converter<MatrixMap, MatrixMap_to_numpy_str>();
    MatrixMap_from_numpy_str();

    to_python_converter<d2d::SegmentMap, SegmentMap_to_numpy_str>();
    SegmentMap_from_numpy_str();

    to_python_converter<mxArray, mxArray_to_numpy_str>();
    mxArray_from_numpy_str();

    to_python_converter<f2d::Pixel2DData, Pixel2DData_to_numpy_str>();
    Pixel2DData_from_numpy_str();

    to_python_converter<LRgbImage, LRgbImage_to_numpy_str>();
    LRgbImage_from_numpy_str();

    to_python_converter<vector<double>, vec_to_numpy_str>();
    vec_from_numpy_str();

    register_autogen_converters();

    class_<std::pair<unsigned int, double> >("uint_double_pair")
        .def_readwrite("first", &std::pair<unsigned int, double>::first)
        .def_readwrite("second", &std::pair<unsigned int, double>::second)
        ;
    class_<vector<std::pair<unsigned int, double> > >("uint_double_pair_vec")
        .def(vector_indexing_suite<vector<std::pair<unsigned int, double> > >())
        ;
    class_<vector<vector<std::pair<unsigned int, double> > > >("uint_double_pair_vec_vec")
        .def(vector_indexing_suite<vector<vector<std::pair<unsigned int, double> > > >())
        ;
    def("set_logger_verbosity", set_logger_verbosity);

    class_<vector<string> >("string_vector")
	.def(vector_indexing_suite<vector<string > >() )
	;

}

static bool boosted_ml = false;

void boost_ml()
{
    if (0 && boosted_ml) return;
    boosted_ml = true;

    class_<VRandomForest::VTreeNode>("VTreeNode", init<>())
        .def_readwrite("is_leaf", &VRandomForest::VTreeNode::is_leaf)
        .def_readwrite("count", &VRandomForest::VTreeNode::count)
        .def_readwrite("dim", &VRandomForest::VTreeNode::dim)
        .def_readwrite("avg_output", &VRandomForest::VTreeNode::avg_output)
        .def("get_left", VTreeNode__get_left, return_value_policy<reference_existing_object>())
        .def("get_right", VTreeNode__get_right, return_value_policy<reference_existing_object>())
        .def("refill_avg_outputs", VTreeNode__refill_avg_outputs)

        .def_readonly("thresh", &VRandomForest::VTreeNode::thresh)
        ;

    class_<vector<VRandomForest::VTreeNode> >("VTreeNode_vec")
        .def(vector_indexing_suite<vector<VRandomForest::VTreeNode> >())
        ;

    class_<VRandomForest>("VRandomForest", init<int, int, int, double, double>())
        .def_readwrite("m_nbr_trees", &VRandomForest::m_nbr_trees)
        .def_readwrite("m_max_depth", &VRandomForest::m_max_depth)
        .def_readwrite("m_min_node_size", &VRandomForest::m_min_node_size)
        .def_readwrite("m_rdm_dim_percent", &VRandomForest::m_rdm_dim_percent)
        .def_readwrite("m_rdm_sample_percent", &VRandomForest::m_rdm_sample_percent)
        .def_readwrite("m_seeds", &VRandomForest::m_seeds)
        .def_readwrite("m_trees", &VRandomForest::m_trees)
        .def("save", &VRandomForest::save)
        .def("doTrain", VRandomForest__wrap_doTrain)
        .def("doPredict", VRandomForest__wrap_doPredict)
        ;
    class_<vector<VRandomForest*> >("VRandomForest_vec")
        .def(vector_indexing_suite<vector<VRandomForest*> >())
        ;
    class_<VBoostedMaxEnt>("VBoostedMaxEnt", init<double, double, double, int, VRandomForest>())
        .def_readwrite("m_step_sizes", &VBoostedMaxEnt::m_step_sizes)
        .def_readwrite("m_dim", &VBoostedMaxEnt::m_dim)
        .def("get_vec_vrandomforest", VBoostedMaxEnt__get_vec_vrandomforest)
        .def("train", VBoostedMaxEnt__wrap_train)
        .def("predict", VBoostedMaxEnt__wrap_predict)
        .def("save", &VBoostedMaxEnt::save)
        .def("load", &VBoostedMaxEnt::load)
        ;
    class_<vector<VBoostedMaxEnt*> >("VBoostedMaxEnt_vec")
        .def(vector_indexing_suite<vector<VBoostedMaxEnt*> >())
        ;
}

BOOST_PYTHON_MODULE(libboost_common) {
    PyEval_InitThreads();
    import_array();
    ilInit();
    boost_common();
}
<commit_msg>(split) subbox fixes, kittilabel writing<commit_after>#include <boost_common.h>
#include <boilerplate.cpp>
#include <autogen_converters.cpp>

bool VBoostedMaxEnt__wrap_train(VBoostedMaxEnt* inst,
                                PyObject* X_train,
                                PyObject* Y_train)
{
    PyArrayObject *xao = (PyArrayObject*)X_train;
    PyArrayObject *yao = (PyArrayObject*)Y_train;

    if (xao->dimensions[0] != yao->dimensions[0]) {
      printf("oh no, X train has %zu entries but Y train has %zu\n",
             xao->dimensions[0],
             yao->dimensions[0]);
    }

    vector<const vector<double>*> Xvec;
    vector<const vector<double>*> Yvec;

    for (int i=0; i<xao->dimensions[0]; i++) {
      vector<double> *tmp = new vector<double>(((double*)xao->data) + i*xao->dimensions[1],
                                               ((double*)xao->data) + (i+1)*xao->dimensions[1]);
      Xvec.push_back(const_cast<const vector<double>*>(tmp));

      tmp = new vector<double>(&(((double*)yao->data)[i*yao->dimensions[1]]),
                               &(((double*)yao->data)[(i+1)*yao->dimensions[1]]));
      double total_prob = 0.0;
      for (int j=0; j<yao->dimensions[1]; j++) {
          total_prob += (*tmp)[j];
      }
      Yvec.push_back(const_cast<const vector<double>*>(tmp));
    }
    vector<double> w_fold(Xvec.size(), 1.0);
    inst->train(Xvec, Yvec, w_fold, NULL, NULL);

    for (int i=0; i<xao->dimensions[0]; i++) {
      delete Xvec[i];
      delete Yvec[i];
    }
    return false;
}

PyObject* VBoostedMaxEnt__wrap_predict(VBoostedMaxEnt* inst,
                                       vector<double> query)
{
    vector<double> ret(2);
    inst->predict(query, ret);
    return vec_to_numpy(ret);
}

vector<VRandomForest*> VBoostedMaxEnt__get_vec_vrandomforest(VBoostedMaxEnt* inst)
{
  vector<VRandomForest*> ret;
  foreach (it, inst->m_vregressors) {
    /* C++ is beautiful:
     * - the innermost * dereferences the iterator;
     * - the next * dereferences the shared ptr;
     * - the & gets the address of the actual object, because boost can't deal with std
     *     tr1 shared ptrs
     * - it's officially a vector of VRegressors, but we happen to know they're really
     *     VRandomForests, so cast.
     */
    ret.push_back((VRandomForest*)&(*(*it)));
  }
  return ret;
}
/* at some point I gotta figure out how to make readonly properties of pointer
 * fields without this crap
 */
VRandomForest::VTreeNode* VTreeNode__get_left(VRandomForest::VTreeNode* inst)
{
    return inst->left;
}
VRandomForest::VTreeNode* VTreeNode__get_right(VRandomForest::VTreeNode* inst)
{
    return inst->right;
}

void VTreeNode__refill_avg_outputs(VRandomForest::VTreeNode *inst)
{
    if (inst->avg_output.size() > 0)
        return;

    if (inst->left->avg_output.size() == 0)
        VTreeNode__refill_avg_outputs(inst->left);
    if (inst->right->avg_output.size() == 0)
        VTreeNode__refill_avg_outputs(inst->right);

    for (int i=0; i<inst->left->avg_output.size(); i++) {
        inst->avg_output.push_back((inst->left->avg_output[i] +
                                    inst->right->avg_output[i]) / 2.0);
    }
}

void VRandomForest__wrap_train(VRandomForest *inst,
                                 pyarr<double> X,
                                 pyarr<double> Y)
{
    vector<const vector<double>*> Xv, Yv;
    for (int i=0; i<X.dims[0]; i++) {
        vector<double>* Xtmp = new vector<double>(X.dims[1]);
        vector<double>* Ytmp = new vector<double>(Y.dims[1]);
        for (int j=0; j<X.dims[1]; j++) {
            (*Xtmp)[j] = X[ind(i,j)];
        }
        for (int j=0; j<Y.dims[1]; j++) {
            (*Ytmp)[j] = Y[ind(i,j)];
        }
        Xv.push_back(const_cast<const vector<double>*>(Xtmp));
        Yv.push_back(const_cast<const vector<double>*>(Ytmp));
    }
    vector<double> weights(X.dims[0], 1.0), feature_costs;
    vector<size_t> usable_features, required_features;

    inst->train(X.dims[1], Y.dims[1],
                Xv, Yv, weights, usable_features, feature_costs, required_features);
    for (int i=0; i<X.dims[0]; i++) {
        delete Xv[i];
        delete Yv[i];
    }
}

pyarr<double> VRandomForest__wrap_doPredict(VRandomForest *inst,
                                            pyarr<double> X)
{
    long int argh[] = {inst->getDimTarget()};
    pyarr<double> ret(1, argh);

    vector<double> xv(X.dims[0]), yv(ret.dims[0]);
    for (int i=0; i<X.dims[0]; i++) {
        xv[i] = X[ind(i)];
    }
    inst->doPredict(xv, yv);
    for (int i=0; i<ret.dims[0]; i++){
        ret[ind(i)] = yv[i];
    }
    return ret;
}

void set_logger_verbosity(string verbosity)
{
    misc_util::Logger::status_t s;
    if (verbosity == "debug") s = misc_util::Logger::DEBUG;
    else if (verbosity == "info") s = misc_util::Logger::INFO;
    else if (verbosity == "warning") s = misc_util::Logger::WARNING;
    else if (verbosity == "error") s = misc_util::Logger::ERROR;
    else s = misc_util::Logger::INFO;

    misc_util::Logger::setVerbosity(s);
}

static bool boosted_common = false;

void boost_common()
{
    import_array();
    if (0 && boosted_common) return;
    boosted_common = true;

    long int dims[] = {10, 10, 10};
    pyarr<double> d(3, dims);
    pyarr<float> f(3, dims);
    pyarr<int> i(3, dims);
    pyarr<long int> l(3, dims);
    pyarr<unsigned char> uc(3, dims);
    pyarr<unsigned int> ui(3, dims);
    pyarr<char> c(3, dims);

    printf("d %d f %d i %d l %d uc %d ui %d c %d\n",
           d.ao->descr->type_num,
           f.ao->descr->type_num,
           i.ao->descr->type_num,
           l.ao->descr->type_num,
           uc.ao->descr->type_num,
           ui.ao->descr->type_num,
           c.ao->descr->type_num);

    to_python_converter<MatrixMap, MatrixMap_to_numpy_str>();
    MatrixMap_from_numpy_str();

    to_python_converter<d2d::SegmentMap, SegmentMap_to_numpy_str>();
    SegmentMap_from_numpy_str();

    to_python_converter<mxArray, mxArray_to_numpy_str>();
    mxArray_from_numpy_str();

    to_python_converter<f2d::Pixel2DData, Pixel2DData_to_numpy_str>();
    Pixel2DData_from_numpy_str();

    to_python_converter<LRgbImage, LRgbImage_to_numpy_str>();
    LRgbImage_from_numpy_str();

    to_python_converter<vector<double>, vec_to_numpy_str>();
    vec_from_numpy_str();

    register_autogen_converters();

    class_<std::pair<unsigned int, double> >("uint_double_pair")
        .def_readwrite("first", &std::pair<unsigned int, double>::first)
        .def_readwrite("second", &std::pair<unsigned int, double>::second)
        ;
    class_<vector<std::pair<unsigned int, double> > >("uint_double_pair_vec")
        .def(vector_indexing_suite<vector<std::pair<unsigned int, double> > >())
        ;
    class_<vector<vector<std::pair<unsigned int, double> > > >("uint_double_pair_vec_vec")
        .def(vector_indexing_suite<vector<vector<std::pair<unsigned int, double> > > >())
        ;
    def("set_logger_verbosity", set_logger_verbosity);

    class_<vector<string> >("string_vector")
	.def(vector_indexing_suite<vector<string > >() )
	;

}

static bool boosted_ml = false;

void boost_ml()
{
    if (0 && boosted_ml) return;
    boosted_ml = true;

    class_<VRandomForest::VTreeNode>("VTreeNode", init<>())
        .def_readwrite("is_leaf", &VRandomForest::VTreeNode::is_leaf)
        .def_readwrite("count", &VRandomForest::VTreeNode::count)
        .def_readwrite("dim", &VRandomForest::VTreeNode::dim)
        .def_readwrite("avg_output", &VRandomForest::VTreeNode::avg_output)
        .def("get_left", VTreeNode__get_left, return_value_policy<reference_existing_object>())
        .def("get_right", VTreeNode__get_right, return_value_policy<reference_existing_object>())
        .def("refill_avg_outputs", VTreeNode__refill_avg_outputs)

        .def_readonly("thresh", &VRandomForest::VTreeNode::thresh)
        ;

    class_<vector<VRandomForest::VTreeNode> >("VTreeNode_vec")
        .def(vector_indexing_suite<vector<VRandomForest::VTreeNode> >())
        ;

    class_<VRandomForest>("VRandomForest", init<int, int, int, double, double>())
        .def_readwrite("m_nbr_trees", &VRandomForest::m_nbr_trees)
        .def_readwrite("m_max_depth", &VRandomForest::m_max_depth)
        .def_readwrite("m_min_node_size", &VRandomForest::m_min_node_size)
        .def_readwrite("m_rdm_dim_percent", &VRandomForest::m_rdm_dim_percent)
        .def_readwrite("m_rdm_sample_percent", &VRandomForest::m_rdm_sample_percent)
        .def_readwrite("m_seeds", &VRandomForest::m_seeds)
        .def_readwrite("m_trees", &VRandomForest::m_trees)
        .def("save", &VRandomForest::save)
        .def("train", VRandomForest__wrap_train)
        .def("doPredict", VRandomForest__wrap_doPredict)
        ;
    class_<vector<VRandomForest*> >("VRandomForest_vec")
        .def(vector_indexing_suite<vector<VRandomForest*> >())
        ;
    class_<VBoostedMaxEnt>("VBoostedMaxEnt", init<double, double, double, int, VRandomForest>())
        .def_readwrite("m_step_sizes", &VBoostedMaxEnt::m_step_sizes)
        .def_readwrite("m_dim", &VBoostedMaxEnt::m_dim)
        .def("get_vec_vrandomforest", VBoostedMaxEnt__get_vec_vrandomforest)
        .def("train", VBoostedMaxEnt__wrap_train)
        .def("predict", VBoostedMaxEnt__wrap_predict)
        .def("save", &VBoostedMaxEnt::save)
        .def("load", &VBoostedMaxEnt::load)
        ;
    class_<vector<VBoostedMaxEnt*> >("VBoostedMaxEnt_vec")
        .def(vector_indexing_suite<vector<VBoostedMaxEnt*> >())
        ;
}

BOOST_PYTHON_MODULE(libboost_common) {
    PyEval_InitThreads();
    import_array();
    ilInit();
    boost_common();
}
<|endoftext|>


<commit_before>#include "xUnit++/xUnit++.h"

using xUnitpp::xUnitAssert;

SUITE("AssertThrows")
{

FACT("ThrowsSuccess")
{
    struct exp
    {
        exp(int x)
            : x(x)
        {
        }

        int x;
    };

    auto x = Assert.Throws<exp>([]() { throw exp(10); });

    Assert.Equal(10, x.x);
}

FACT("ThrowsAssertsOnFailure")
{
    try
    {
        Assert.Throws<int>([=]() { });
    }
    catch(const xUnitAssert &)
    {
        return;
    }

    Assert.Fail();
}

FACT("ThrowAppendsMessages")
{
    static const std::string userMessage = "xUnit++";

    try
    {
        Assert.Throws<int>([=]() { }, userMessage);
    }
    catch(const xUnitAssert &assert)
    {
        Assert.Contains(assert.UserMessage(), userMessage.c_str());
        return;
    }

    Assert.Fail();
}

FACT("Can catch std::exception")
{
    Assert.Throws<std::exception>([]() { throw std::exception("test"); });
}

}
<commit_msg>std::exception doesn't have a public constructor that takes a char *<commit_after>#include "xUnit++/xUnit++.h"

using xUnitpp::xUnitAssert;

SUITE("AssertThrows")
{

FACT("ThrowsSuccess")
{
    struct exp
    {
        exp(int x)
            : x(x)
        {
        }

        int x;
    };

    auto x = Assert.Throws<exp>([]() { throw exp(10); });

    Assert.Equal(10, x.x);
}

FACT("ThrowsAssertsOnFailure")
{
    try
    {
        Assert.Throws<int>([=]() { });
    }
    catch(const xUnitAssert &)
    {
        return;
    }

    Assert.Fail();
}

FACT("ThrowAppendsMessages")
{
    static const std::string userMessage = "xUnit++";

    try
    {
        Assert.Throws<int>([=]() { }, userMessage);
    }
    catch(const xUnitAssert &assert)
    {
        Assert.Contains(assert.UserMessage(), userMessage.c_str());
        return;
    }

    Assert.Fail();
}

FACT("Can catch std::exception")
{
    Assert.Throws<std::exception>([]() { throw std::logic_error("test"); });
}

}
<|endoftext|>


<commit_before>#include <iostream>
#include "TrolleyInterface.h"
#include "TFile.h"
#include "TGraph.h"
#include "TString.h"
#include <cstring>

using namespace std;
using namespace TrolleyInterface;

typedef struct _TrlyDataStruct{
  //NMR
  unsigned long int NMRTimeStamp;
  unsigned short ProbeNumber;
  unsigned short NSample_NMR;
  short NMRSamples[MAX_NMR_SAMPLES];

  //Barcode
  unsigned long int BarcodeTimeStamp;
  unsigned short NSample_Barcode_PerCh;
  short BarcodeSamples[MAX_BARCODE_SAMPLES];

  //Monitor
  bool BarcodeError;
  short BCToNMROffset;
  short VMonitor1;
  short VMonitor2;
  unsigned short TMonitorIn;
  unsigned short TMonitorExt1;
  unsigned short TMonitorExt2;
  unsigned short TMonitorExt3;
  unsigned short PressureSensorCal[7];
  unsigned int PMonitorVal;
  unsigned int PMonitorTemp;

  //Register Readbacks
  unsigned short BarcodeRegisters[5];
  unsigned short TrlyRegisters[16];

  //Constructor
  _TrlyDataStruct(){}
  _TrlyDataStruct(const _TrlyDataStruct& obj)
  {
    //NMR
    NMRTimeStamp = obj.NMRTimeStamp;
    ProbeNumber = obj.ProbeNumber;
    NSample_NMR = obj.NSample_NMR;
    for (int i=0;i<MAX_NMR_SAMPLES;i++){
      NMRSamples[i] = obj.NMRSamples[i];
    }

    //Barcode
    BarcodeTimeStamp = obj.BarcodeTimeStamp;
    NSample_Barcode_PerCh = obj.NSample_Barcode_PerCh;
    for (int i=0;i<MAX_BARCODE_SAMPLES;i++){
      BarcodeSamples[i] = obj.BarcodeSamples[i];
    }
    //Monitor
    BarcodeError = obj.BarcodeError;
    BCToNMROffset = obj.BCToNMROffset;
    VMonitor1 = obj.VMonitor1;
    VMonitor2 = obj.VMonitor2;
    TMonitorIn = obj.TMonitorIn;
    TMonitorExt1 = obj.TMonitorExt1;
    TMonitorExt2 = obj.TMonitorExt2;
    TMonitorExt3 = obj.TMonitorExt3;
    for(int i=0;i<7;i++){
      PressureSensorCal[i] = obj.PressureSensorCal[i];
    }
    PMonitorVal = obj.PMonitorVal;
    PMonitorTemp = obj.PMonitorTemp;
    for(int i=0;i<5;i++){
      BarcodeRegisters[i] = obj.BarcodeRegisters[i];
    }
    for(int i=0;i<16;i++){
      TrlyRegisters[i] = obj.TrlyRegisters[i];
    }
  }
}TrlyDataStruct;

int main(int argc,char **argv){
  int NPulses = 10;
  int NBarcodes = 300;
  if (argc>1){
    NPulses = atoi(argv[1]);
  }
  if (argc>2){
    NBarcodes = atoi(argv[2]);
  }
  int err = DeviceConnect("192.168.1.123");
  cout <<err<<endl;
  if (err<0)return -1;
  //Read device
  unsigned int val;
  err = DeviceRead(0x40001060,&val);
  unsigned int LEDV = val & 0x03FF;
  unsigned int LEDDisable = val & 0x0400;
  cout <<err<<" "<<LEDV<< " "<<LEDDisable<<endl;
  //Receive Data
  char buffer[1000];
//  err = DataReceive(buffer);
//  cout <<err<<endl;

  //Try to get some data

  int LastFrameNumber = 0;
  int FrameNumber = 0;
  int FrameSize = 0;
  //Frame buffer
  short* Frame = new short[MAX_PAYLOAD_DATA/sizeof(short)];

  //Read first frame and sync
  int rc = DataReceive((void *)Frame);
  if (rc<0){
    cout <<"Data Error code "<<rc<<endl;
    return -1;
  }
//  LastFrameNumber = *((int *)(&(Frame[9])));
  memcpy(&LastFrameNumber,&(Frame[9]),sizeof(int));
//  FrameSize = *((int *)(&(Frame[7])));
  memcpy(&FrameSize,&(Frame[7]),sizeof(int));
  cout <<"data read "<<rc<<", from Frame data read="<<FrameSize<<endl;
  cout<<"number of NMR samples "<<Frame[12]<<endl;

  TGraph **gArray = new TGraph*[NPulses];
  for (int j=0;j<NPulses;j++){
    gArray[j] = new TGraph();
    gArray[j]->SetName(Form("pulse%02d",j));
  }
  TGraph **gBarcodes = new TGraph*[6];
  for (int j=0;j<6;j++){
    gBarcodes[j] = new TGraph();
    gBarcodes[j]->SetName(Form("Barcode%d",j));
  }
  //Readout loop
  int i=0;
  int gIndex = 0;
  int NCycle = NPulses;
  if (NBarcodes>NCycle)NCycle = NBarcodes;
  while (i<NCycle){
    //Read Frame
    rc = DataReceive((void *)Frame);
    if (rc<0){
      cout <<"Data Error code "<<rc<<endl;
      return -1;
    }
  //  FrameNumber = *((int *)(&(Frame[9])));
    memcpy(&FrameNumber,&(Frame[9]),sizeof(int));
    //    FrameSize = *((int *)(&(Frame[7])));
    memcpy(&FrameSize,&(Frame[7]),sizeof(int));
//    cout <<"Frame number = "<<FrameNumber<<" , Last "<<LastFrameNumber<<endl;
//    cout <<"data read "<<rc<<", from Frame data read="<<FrameSize<<endl;

    LastFrameNumber=FrameNumber;
    //Translate buffer into TrlyDataStruct
    TrlyDataStruct* TrlyDataUnit = new TrlyDataStruct;

//    TrlyDataUnit->NMRTimeStamp = *((long int *)(&(Frame[32])));
    memcpy(&(TrlyDataUnit->NMRTimeStamp),&(Frame[32]),sizeof(unsigned long int));
    TrlyDataUnit->ProbeNumber = short(0x1F & Frame[11]);
    TrlyDataUnit->NSample_NMR = Frame[12];
    short NSamNMR = Frame[12];
/*    cout<<"NMR TimeStamp "<<TrlyDataUnit->NMRTimeStamp<<" ; ";
    cout<<"number of NMR samples "<<TrlyDataUnit->NSample_NMR<<endl;
*/
    for (short ii=0;ii<NSamNMR;ii++){
      TrlyDataUnit->NMRSamples[ii] = Frame[64+ii];
    }
    //TrlyDataUnit->BarcodeTimeStamp = *((long int *)(&(Frame[36]))) ;
    memcpy(&(TrlyDataUnit->BarcodeTimeStamp),&(Frame[36]),sizeof(unsigned long int));
    TrlyDataUnit->NSample_Barcode_PerCh = Frame[13];
    short NSamBarcode = Frame[13]*BARCODE_CH_NUM;
/*    cout<<"Barcode TimeStamp "<<TrlyDataUnit->BarcodeTimeStamp<<" ; ";
    cout<<"number of Barcode Channels "<<BARCODE_CH_NUM<<" ; ";
    cout<<"number of Barcode samples per Ch "<<TrlyDataUnit->NSample_Barcode_PerCh<<endl;
*/
    //Check if this is larger than the MAX
    for (short ii=0;ii<NSamBarcode;ii++){
      TrlyDataUnit->BarcodeSamples[ii] = Frame[64+NSamNMR+ii];
    }
    TrlyDataUnit->BarcodeError = bool(0x100 & Frame[11]);
    TrlyDataUnit->BCToNMROffset = Frame[14];
    TrlyDataUnit->VMonitor1 = Frame[15];
    TrlyDataUnit->VMonitor2 = Frame[16];
    TrlyDataUnit->TMonitorIn = Frame[17];
    TrlyDataUnit->TMonitorExt1 = Frame[18];
    TrlyDataUnit->TMonitorExt2 = Frame[19];
    TrlyDataUnit->TMonitorExt3 = Frame[20];
    if (i==0){
      cout <<"Offset " <<TrlyDataUnit->BCToNMROffset<<" "<<(int(TrlyDataUnit->BarcodeTimeStamp)-int(TrlyDataUnit->NMRTimeStamp))<<endl;
      cout <<"VMonitor " <<TrlyDataUnit->VMonitor1<<" "<<TrlyDataUnit->VMonitor2<<endl;
      cout <<"TMonitors " <<TrlyDataUnit->TMonitorExt1<<" "<<TrlyDataUnit->TMonitorExt2<<endl;
      cout <<Frame[43]<<endl;
    }
    for (short ii=0;ii<7;ii++){
      TrlyDataUnit->PressureSensorCal[ii] = Frame[21+ii];;
    }
//    TrlyDataUnit->PMonitorVal = *((int *)(&(Frame[28]))) ;
//    TrlyDataUnit->PMonitorTemp = *((int *)(&(Frame[30])));
    memcpy(&(TrlyDataUnit->PMonitorVal),&(Frame[28]),sizeof(int));
    memcpy(&(TrlyDataUnit->PMonitorTemp),&(Frame[30]),sizeof(int));
    for (short ii=0;ii<5;ii++){
      TrlyDataUnit->BarcodeRegisters[ii] = Frame[43+ii];
    }
    for (short ii=0;ii<16;ii++){
      TrlyDataUnit->TrlyRegisters[ii] = Frame[48+ii];
    }
    //Fill Graph
    if (i<NPulses){
      for (int j=0;j<TrlyDataUnit->NSample_NMR;j++){
	gArray[i]->SetPoint(j,j,TrlyDataUnit->NMRSamples[j]);
      }
    }
    if (i<NBarcodes){
      for (short ii=0;ii<Frame[13];ii++){
	double BTime = TrlyDataUnit->BarcodeTimeStamp*50/1000000.0+0.1*ii;
	for (short jj=0;jj<6;jj++){
	  gBarcodes[jj]->SetPoint(gIndex,BTime,TrlyDataUnit->BarcodeSamples[jj*Frame[13]+ii]);
	}
	gIndex++;
      }
    }

    delete TrlyDataUnit;
    i++;
  }

  TFile f("Testout.root","recreate");
  for (int j=0;j<NPulses;j++){
    gArray[j]->Write();
  }
  for (int j=0;j<6;j++){
    gBarcodes[j]->Write();
  }
  f.Close();

  //Disconnect
  err = DeviceDisconnect();
  cout <<err<<endl;
  delete []Frame;
  for (int j=0;j<NPulses;j++){
    delete gArray[j];
  }
  delete []gArray;
  for (int j=0;j<6;j++){
    delete gBarcodes[j];
  }
  delete []gBarcodes;
  return 0;
}
<commit_msg>update trolley interface<commit_after>#include <iostream>
#include "TrolleyInterface.h"
#include "TFile.h"
#include "TGraph.h"
#include "TString.h"
#include <cstring>

#define BARCODE_CH_NUM 6

using namespace std;
using namespace TrolleyInterface;

typedef struct _TrlyDataStruct{
  //NMR
  unsigned long int NMRTimeStamp;
  unsigned short ProbeNumber;
  unsigned short NSample_NMR;
  short NMRSamples[MAX_NMR_SAMPLES];

  //Barcode
  unsigned long int BarcodeTimeStamp;
  unsigned short NSample_Barcode_PerCh;
  short BarcodeSamples[MAX_BARCODE_SAMPLES];

  //Monitor
  bool BarcodeError;
  short BCToNMROffset;
  short VMonitor1;
  short VMonitor2;
  unsigned short TMonitorIn;
  unsigned short TMonitorExt1;
  unsigned short TMonitorExt2;
  unsigned short TMonitorExt3;
  unsigned short PressureSensorCal[7];
  unsigned int PMonitorVal;
  unsigned int PMonitorTemp;

  //Register Readbacks
  unsigned short BarcodeRegisters[5];
  unsigned short TrlyRegisters[16];

  //Constructor
  _TrlyDataStruct(){}
  _TrlyDataStruct(const _TrlyDataStruct& obj)
  {
    //NMR
    NMRTimeStamp = obj.NMRTimeStamp;
    ProbeNumber = obj.ProbeNumber;
    NSample_NMR = obj.NSample_NMR;
    for (int i=0;i<MAX_NMR_SAMPLES;i++){
      NMRSamples[i] = obj.NMRSamples[i];
    }

    //Barcode
    BarcodeTimeStamp = obj.BarcodeTimeStamp;
    NSample_Barcode_PerCh = obj.NSample_Barcode_PerCh;
    for (int i=0;i<MAX_BARCODE_SAMPLES;i++){
      BarcodeSamples[i] = obj.BarcodeSamples[i];
    }
    //Monitor
    BarcodeError = obj.BarcodeError;
    BCToNMROffset = obj.BCToNMROffset;
    VMonitor1 = obj.VMonitor1;
    VMonitor2 = obj.VMonitor2;
    TMonitorIn = obj.TMonitorIn;
    TMonitorExt1 = obj.TMonitorExt1;
    TMonitorExt2 = obj.TMonitorExt2;
    TMonitorExt3 = obj.TMonitorExt3;
    for(int i=0;i<7;i++){
      PressureSensorCal[i] = obj.PressureSensorCal[i];
    }
    PMonitorVal = obj.PMonitorVal;
    PMonitorTemp = obj.PMonitorTemp;
    for(int i=0;i<5;i++){
      BarcodeRegisters[i] = obj.BarcodeRegisters[i];
    }
    for(int i=0;i<16;i++){
      TrlyRegisters[i] = obj.TrlyRegisters[i];
    }
  }
}TrlyDataStruct;

int main(int argc,char **argv){
  int NPulses = 10;
  int NBarcodes = 300;
  if (argc>1){
    NPulses = atoi(argv[1]);
  }
  if (argc>2){
    NBarcodes = atoi(argv[2]);
  }
  int err = DeviceConnect("192.168.1.123");
  cout <<err<<endl;
  if (err<0)return -1;
  //Read device
  unsigned int val;
  err = DeviceRead(0x40001060,&val);
  unsigned int LEDV = val & 0x03FF;
  unsigned int LEDDisable = val & 0x0400;
  cout <<err<<" "<<LEDV<< " "<<LEDDisable<<endl;
  //Receive Data
  char buffer[1000];
//  err = DataReceive(buffer);
//  cout <<err<<endl;

  //Try to get some data

  int LastFrameNumber = 0;
  int FrameNumber = 0;
  int FrameSize = 0;
  //Frame buffer
  short* Frame = new short[MAX_PAYLOAD_DATA/sizeof(short)];

  //Read first frame and sync
  int rc = DataReceive((void *)Frame);
  if (rc<0){
    cout <<"Data Error code "<<rc<<endl;
    return -1;
  }
//  LastFrameNumber = *((int *)(&(Frame[9])));
  memcpy(&LastFrameNumber,&(Frame[9]),sizeof(int));
//  FrameSize = *((int *)(&(Frame[7])));
  memcpy(&FrameSize,&(Frame[7]),sizeof(int));
  cout <<"data read "<<rc<<", from Frame data read="<<FrameSize<<endl;
  cout<<"number of NMR samples "<<Frame[12]<<endl;

  TGraph **gArray = new TGraph*[NPulses];
  for (int j=0;j<NPulses;j++){
    gArray[j] = new TGraph();
    gArray[j]->SetName(Form("pulse%02d",j));
  }
  TGraph **gBarcodes = new TGraph*[6];
  for (int j=0;j<6;j++){
    gBarcodes[j] = new TGraph();
    gBarcodes[j]->SetName(Form("Barcode%d",j));
  }
  //Readout loop
  int i=0;
  int gIndex = 0;
  int NCycle = NPulses;
  if (NBarcodes>NCycle)NCycle = NBarcodes;
  while (i<NCycle){
    //Read Frame
    rc = DataReceive((void *)Frame);
    if (rc<0){
      cout <<"Data Error code "<<rc<<endl;
      return -1;
    }
  //  FrameNumber = *((int *)(&(Frame[9])));
    memcpy(&FrameNumber,&(Frame[9]),sizeof(int));
    //    FrameSize = *((int *)(&(Frame[7])));
    memcpy(&FrameSize,&(Frame[7]),sizeof(int));
//    cout <<"Frame number = "<<FrameNumber<<" , Last "<<LastFrameNumber<<endl;
//    cout <<"data read "<<rc<<", from Frame data read="<<FrameSize<<endl;

    LastFrameNumber=FrameNumber;
    //Translate buffer into TrlyDataStruct
    TrlyDataStruct* TrlyDataUnit = new TrlyDataStruct;

//    TrlyDataUnit->NMRTimeStamp = *((long int *)(&(Frame[32])));
    memcpy(&(TrlyDataUnit->NMRTimeStamp),&(Frame[32]),sizeof(unsigned long int));
    TrlyDataUnit->ProbeNumber = short(0x1F & Frame[11]);
    TrlyDataUnit->NSample_NMR = Frame[12];
    short NSamNMR = Frame[12];
/*    cout<<"NMR TimeStamp "<<TrlyDataUnit->NMRTimeStamp<<" ; ";
    cout<<"number of NMR samples "<<TrlyDataUnit->NSample_NMR<<endl;
*/
    for (short ii=0;ii<NSamNMR;ii++){
      TrlyDataUnit->NMRSamples[ii] = Frame[64+ii];
    }
    //TrlyDataUnit->BarcodeTimeStamp = *((long int *)(&(Frame[36]))) ;
    memcpy(&(TrlyDataUnit->BarcodeTimeStamp),&(Frame[36]),sizeof(unsigned long int));
    TrlyDataUnit->NSample_Barcode_PerCh = Frame[13];
    short NSamBarcode = Frame[13]*BARCODE_CH_NUM;
/*    cout<<"Barcode TimeStamp "<<TrlyDataUnit->BarcodeTimeStamp<<" ; ";
    cout<<"number of Barcode Channels "<<BARCODE_CH_NUM<<" ; ";
    cout<<"number of Barcode samples per Ch "<<TrlyDataUnit->NSample_Barcode_PerCh<<endl;
*/
    //Check if this is larger than the MAX
    for (short ii=0;ii<NSamBarcode;ii++){
      TrlyDataUnit->BarcodeSamples[ii] = Frame[64+NSamNMR+ii];
    }
    TrlyDataUnit->BarcodeError = bool(0x100 & Frame[11]);
    TrlyDataUnit->BCToNMROffset = Frame[14];
    TrlyDataUnit->VMonitor1 = Frame[15];
    TrlyDataUnit->VMonitor2 = Frame[16];
    TrlyDataUnit->TMonitorIn = Frame[17];
    TrlyDataUnit->TMonitorExt1 = Frame[18];
    TrlyDataUnit->TMonitorExt2 = Frame[19];
    TrlyDataUnit->TMonitorExt3 = Frame[20];
    if (i==0){
      cout <<"Offset " <<TrlyDataUnit->BCToNMROffset<<" "<<(int(TrlyDataUnit->BarcodeTimeStamp)-int(TrlyDataUnit->NMRTimeStamp))<<endl;
      cout <<"VMonitor " <<TrlyDataUnit->VMonitor1<<" "<<TrlyDataUnit->VMonitor2<<endl;
      cout <<"TMonitors " <<TrlyDataUnit->TMonitorExt1<<" "<<TrlyDataUnit->TMonitorExt2<<endl;
      cout <<Frame[43]<<endl;
    }
    for (short ii=0;ii<7;ii++){
      TrlyDataUnit->PressureSensorCal[ii] = Frame[21+ii];;
    }
//    TrlyDataUnit->PMonitorVal = *((int *)(&(Frame[28]))) ;
//    TrlyDataUnit->PMonitorTemp = *((int *)(&(Frame[30])));
    memcpy(&(TrlyDataUnit->PMonitorVal),&(Frame[28]),sizeof(int));
    memcpy(&(TrlyDataUnit->PMonitorTemp),&(Frame[30]),sizeof(int));
    for (short ii=0;ii<5;ii++){
      TrlyDataUnit->BarcodeRegisters[ii] = Frame[43+ii];
    }
    for (short ii=0;ii<16;ii++){
      TrlyDataUnit->TrlyRegisters[ii] = Frame[48+ii];
    }
    //Fill Graph
    if (i<NPulses){
      for (int j=0;j<TrlyDataUnit->NSample_NMR;j++){
	gArray[i]->SetPoint(j,j,TrlyDataUnit->NMRSamples[j]);
      }
    }
    if (i<NBarcodes){
      for (short ii=0;ii<Frame[13];ii++){
	double BTime = TrlyDataUnit->BarcodeTimeStamp*50/1000000.0+0.1*ii;
	for (short jj=0;jj<6;jj++){
	  gBarcodes[jj]->SetPoint(gIndex,BTime,TrlyDataUnit->BarcodeSamples[jj*Frame[13]+ii]);
	}
	gIndex++;
      }
    }

    delete TrlyDataUnit;
    i++;
  }

  TFile f("Testout.root","recreate");
  for (int j=0;j<NPulses;j++){
    gArray[j]->Write();
  }
  for (int j=0;j<6;j++){
    gBarcodes[j]->Write();
  }
  f.Close();

  //Disconnect
  err = DeviceDisconnect();
  cout <<err<<endl;
  delete []Frame;
  for (int j=0;j<NPulses;j++){
    delete gArray[j];
  }
  delete []gArray;
  for (int j=0;j<6;j++){
    delete gBarcodes[j];
  }
  delete []gBarcodes;
  return 0;
}
<|endoftext|>


<commit_before>// Harshad Kasture, Jason Miller, Chris Celio, Charles Gruenwald,
// Nathan Beckmann, George Kurian, David Wentzlaff, James Psota
// 10.12.08
//
// Carbon Computer Simulator
//
// This simulator models future multi-core computers with thousands of cores.
// It runs on today's x86 multicores and will scale as more and more cores
// and better inter-core communications mechanisms become available.
// The simulator provides a platform for research in processor architecture,
// compilers, network interconnect topologies, and some OS.
//
// The simulator runs on top of Intel's Pin dynamic binary instrumention engine.
// Application code in the absence of instrumentation runs more or less
// natively and is thus high performance. When instrumentation is used, models
// can be hot-swapped or dynamically enabled and disabled as desired so that
// performance tracks the level of simulation detail needed.

#include <iostream>
#include <assert.h>
#include <set>
#include <sys/syscall.h>
#include <unistd.h>

#include "pin.H"
#include "log.h"
#include "routine_replace.h"

// FIXME: This list could probably be trimmed down a lot.
#include "simulator.h"
#include "tile_manager.h"
#include "config.h"
#include "tile.h"
#include "syscall_model.h"
#include "thread_manager.h"
#include "thread_scheduler.h"
#include "config_file.hpp"
#include "handle_args.h"
#include "thread_start.h"
#include "pin_config.h"
#include "log.h"
#include "vm_manager.h"
#include "instruction_modeling.h"
#include "progress_trace.h"
#include "clock_skew_management.h"
#include "handle_threads.h"

#include "redirect_memory.h"
#include "handle_syscalls.h"
#include "opcodes.h"
#include "hash_map.h"
#include <typeinfo>

// lite directories
#include "lite/routine_replace.h"
#include "lite/memory_modeling.h"
#include "lite/handle_syscalls.h"

// ---------------------------------------------------------------
// FIXME:
// There should be a better place to keep these globals
// -- a PinSimulator class or smthg
bool done_app_initialization = false;
config::ConfigFile *cfg;

// clone stuff
extern int *parent_tidptr;
extern int *child_tidptr;

extern PIN_LOCK clone_memory_update_lock;

map <ADDRINT, string> rtn_map;
PIN_LOCK rtn_map_lock;

HashMap core_map;
// ---------------------------------------------------------------

void printRtn (ADDRINT rtn_addr, bool enter)
{
   PIN_GetLock (&rtn_map_lock, 1);
   map<ADDRINT, string>::iterator it = rtn_map.find (rtn_addr);

   string point = enter ? "Enter" : "Exit";
   if (it != rtn_map.end())
   {
      LOG_PRINT ("Stack trace : %s %s", point.c_str(), (it->second).c_str());
   }
   else
   {
      LOG_PRINT ("Stack trace : %s UNKNOWN", point.c_str());
   }

   PIN_ReleaseLock (&rtn_map_lock);
}

VOID printInsInfo(CONTEXT* ctxt)
{
   __attribute__((unused)) ADDRINT reg_inst_ptr = PIN_GetContextReg(ctxt, REG_INST_PTR);
   __attribute__((unused)) ADDRINT reg_stack_ptr = PIN_GetContextReg(ctxt, REG_STACK_PTR);

   LOG_PRINT("eip(%#lx), esp(%#lx)", reg_inst_ptr, reg_stack_ptr);
}

void routineCallback(RTN rtn, void *v)
{
   string rtn_name = RTN_Name(rtn);

   replaceUserAPIFunction(rtn, rtn_name);

   // ---------------------------------------------------------------

   std::string module = Log::getSingleton()->getModule(__FILE__);
   if (Log::getSingleton()->isEnabled(module.c_str()) &&
       Sim()->getCfg()->getBool("log/stack_trace",false))
   {
      RTN_Open (rtn);

      ADDRINT rtn_addr = RTN_Address (rtn);

      PIN_GetLock (&rtn_map_lock, 1);

      rtn_map.insert (make_pair (rtn_addr, rtn_name));

      PIN_ReleaseLock (&rtn_map_lock);

      RTN_InsertCall (rtn, IPOINT_BEFORE,
                      AFUNPTR (printRtn),
                      IARG_ADDRINT, rtn_addr,
                      IARG_BOOL, true,
                      IARG_END);

      RTN_InsertCall (rtn, IPOINT_AFTER,
                      AFUNPTR (printRtn),
                      IARG_ADDRINT, rtn_addr,
                      IARG_BOOL, false,
                      IARG_END);

      RTN_Close (rtn);
   }

   // ---------------------------------------------------------------

   if (rtn_name == "CarbonSpawnThreadSpawner")
   {
      RTN_Open (rtn);

      RTN_InsertCall (rtn, IPOINT_BEFORE,
            AFUNPTR (setupCarbonSpawnThreadSpawnerStack),
            IARG_CONTEXT,
            IARG_END);

      RTN_Close (rtn);
   }

   else if (rtn_name == "CarbonThreadSpawner")
   {
      RTN_Open (rtn);

      RTN_InsertCall (rtn, IPOINT_BEFORE,
            AFUNPTR (setupCarbonThreadSpawnerStack),
            IARG_CONTEXT,
            IARG_END);

      RTN_Close(rtn);
   }
}

VOID instructionCallback(INS ins, void *v)
{
   // Debugging Function
   if (Log::getSingleton()->isLoggingEnabled())
   {
      INS_InsertCall(ins, IPOINT_BEFORE,
            AFUNPTR(printInsInfo),
            IARG_CALL_ORDER, CALL_ORDER_FIRST,
            IARG_CONTEXT,
            IARG_END);
   }

   if (Config::getSingleton()->getEnableCoreModeling())
   {
      // Core Performance Modeling
      addInstructionModeling(ins);

      // Progress Trace
      addProgressTrace(ins);

      // Clock Skew Management
      addPeriodicSync(ins);

      // Scheduling
      addYield(ins);
   }

   if (Sim()->getConfig()->getSimulationMode() == Config::FULL)
   {
      // Special handling for futex syscall because of internal Pin lock
      if (INS_IsSyscall(ins))
      {
         INS_InsertCall(ins, IPOINT_BEFORE,
               AFUNPTR(handleFutexSyscall),
               IARG_CONTEXT,
               IARG_END);
      }
      else
      {
         // Emulate(/Rewrite)  Stack and Memory Operations
         if (rewriteStackOp (ins));
         else rewriteMemOp (ins);
      }
   }
   else // Sim()->getConfig()->getSimulationMode() == Config::LITE
   {
      // Special handling for futex syscall because of internal Pin lock
      if (INS_IsSyscall(ins))
      {
         INS_InsertCall(ins, IPOINT_BEFORE,
               AFUNPTR(lite::handleFutexSyscall),
               IARG_CONTEXT,
               IARG_END);
      }
      else
      {
         // Instrument Memory Operations
         lite::addMemoryModeling(ins);
      }
   }
}

// syscall model wrappers
void initializeSyscallModeling()
{
   PIN_InitLock(&clone_memory_update_lock);
}

void ApplicationStart()
{
}

void ApplicationExit(int, void*)
{
   LOG_PRINT("Application exit.");
   Simulator::release();
   shutdownProgressTrace();
   delete cfg;
}

VOID threadStartCallback(THREADID threadIndex, CONTEXT *ctxt, INT32 flags, VOID *v)
{
   threadStartProgressTrace();

   // Conditions under which we must initialize a core
   // 1) (!done_app_initialization) && (curr_process_num == 0)
   // 2) (done_app_initialization) && (!thread_spawner)

   if (! done_app_initialization)
   {
      // The app is not initialized, start the main thread on the main core on tile 0.
      UInt32 curr_process_num = Sim()->getConfig()->getCurrentProcessNum();

      if (Sim()->getConfig()->getSimulationMode() == Config::LITE)
      {
         LOG_ASSERT_ERROR(curr_process_num == 0, "Lite mode can only be run with 1 process");
         Sim()->getTileManager()->initializeThread(Tile::getMainCoreId(0));
      }
      else // Sim()->getConfig()->getSimulationMode() == Config::FULL
      {
         ADDRINT reg_esp = PIN_GetContextReg(ctxt, REG_STACK_PTR);
         allocateStackSpace();

         if (curr_process_num == 0)
         {
            Sim()->getTileManager()->initializeThread(Tile::getMainCoreId(0));

            ADDRINT reg_eip = PIN_GetContextReg(ctxt, REG_INST_PTR);
            // 1) Copying over Static Data
            // Get the image first
            PIN_LockClient();
            IMG img = IMG_FindByAddress(reg_eip);
            PIN_UnlockClient();

            LOG_PRINT("Process: 0, Start Copying Static Data");
            copyStaticData(img);
            LOG_PRINT("Process: 0, Finished Copying Static Data");

            // 2) Copying over initial stack data
            LOG_PRINT("Process: 0, Start Copying Initial Stack Data");
            copyInitialStackData(reg_esp, Tile::getMainCoreId(0));
            LOG_PRINT("Process: 0, Finished Copying Initial Stack Data");
         }
         else
         {
            tile_id_t tile_id = Sim()->getConfig()->getCurrentThreadSpawnerTileNum();
            Sim()->getTileManager()->initializeThread(Tile::getMainCoreId(tile_id));

            Core *core = Sim()->getTileManager()->getCurrentCore();

            // main thread clock is not affected by start-up time of other processes
            core->getTile()->getNetwork()->netRecv(Tile::getMainCoreId(0), core->getId(), SYSTEM_INITIALIZATION_NOTIFY);

            LOG_PRINT("Process: %i, Start Copying Initial Stack Data");
            copyInitialStackData(reg_esp, Tile::getMainCoreId(tile_id));
            LOG_PRINT("Process: %i, Finished Copying Initial Stack Data");
         }
         // Set the current ESP accordingly
         PIN_SetContextReg(ctxt, REG_STACK_PTR, reg_esp);
      }

      // All the real initialization is done in
      // replacement_start at the moment
      done_app_initialization = true;
   }
   else
   {
      // This is NOT the main thread
      // 'application' thread or 'thread spawner'

      if (Sim()->getConfig()->getSimulationMode() == Config::LITE)
      {
         ThreadSpawnRequest req;
         Sim()->getThreadManager()->getThreadToSpawn(&req);
         Sim()->getThreadManager()->dequeueThreadSpawnReq(&req);

         LOG_ASSERT_ERROR(req.destination.tile_id < SInt32(Config::getSingleton()->getApplicationTiles()),
               "req.tile_id(%i), num application cores(%u)", req.destination.tile_id, Config::getSingleton()->getApplicationTiles());
         Sim()->getThreadManager()->onThreadStart(&req);
      }
      else // Sim()->getConfig()->getSimulationMode() == Config::FULL
      {
         ADDRINT reg_esp = PIN_GetContextReg(ctxt, REG_STACK_PTR);
         tile_id_t tile_id = PinConfig::getSingleton()->getTileIDFromStackPtr(reg_esp);
         LOG_PRINT("Got tile %d from stack ptr 0x%x", tile_id, reg_esp);

         core_id_t core_id = PinConfig::getSingleton()->getCoreIDFromStackPtr(reg_esp);
         LOG_PRINT("Got core {%d, %d} from stack ptr 0x%x", core_id.tile_id, core_id.core_type, reg_esp);

         LOG_ASSERT_ERROR(tile_id != -1, "All application threads and thread spawner are cores now");

         if (tile_id == Sim()->getConfig()->getCurrentThreadSpawnerTileNum())
         {
            // 'Thread Spawner' thread
            Sim()->getTileManager()->initializeThread(core_id);
         }
         else
         {
            // 'Application' thread
            ThreadSpawnRequest* req = Sim()->getThreadManager()->getThreadSpawnReq();

            LOG_ASSERT_ERROR (req != NULL, "ThreadSpawnRequest is NULL !!");

            // This is an application thread
            LOG_ASSERT_ERROR(tile_id == req->destination.tile_id, "Got 2 different tile_ids: req->destination = {%i, %i}, tile_id = %i", req->destination.tile_id, req->destination.core_type, tile_id);

            Sim()->getThreadManager()->onThreadStart(req);
         }

         // Restore the clone syscall arguments
         PIN_SetContextReg (ctxt, REG_GDX, (ADDRINT) parent_tidptr);
         PIN_SetContextReg (ctxt, LEVEL_BASE::REG_R10, (ADDRINT) child_tidptr);

         __attribute__((unused)) Tile *tile = Sim()->getTileManager()->getCurrentTile();
         LOG_ASSERT_ERROR(tile, "tile(NULL)");

         // Copy over thread stack data
         //copySpawnedThreadStackData(reg_esp);

         // Wait to make sure that the spawner has written stuff back to memory
         // FIXME: What is this for(?) This seems arbitrary
         PIN_GetLock (&clone_memory_update_lock, 2);
         PIN_ReleaseLock (&clone_memory_update_lock);
      }
   }

   // Initialize Tile map
   core_map.insert(threadIndex, Sim()->getTileManager()->getCurrentCore());
}

VOID threadFiniCallback(THREADID threadIndex, const CONTEXT *ctxt, INT32 flags, VOID *v)
{
   // De-initialize Tile map
   core_map.erase(threadIndex);

   Sim()->getThreadManager()->onThreadExit();
}

int main(int argc, char *argv[])
{
   // ---------------------------------------------------------------
   // FIXME:
   PIN_InitLock (&rtn_map_lock);
   // ---------------------------------------------------------------

   // Global initialization
   PIN_InitSymbols();
   PIN_Init(argc,argv);

   string_vec args;

   // Set the default config path if it isn't
   // overwritten on the command line.
   std::string config_path = "carbon_sim.cfg";

   parse_args(args, config_path, argc, argv);

   cfg = new config::ConfigFile();
   cfg->load(config_path);

   handle_args(args, *cfg);

   Simulator::setConfig(cfg);

   Simulator::allocate();
   Sim()->start();

   if (Sim()->getConfig()->getSimulationMode() == Config::FULL)
      PinConfig::allocate();

   // Instrumentation
   LOG_PRINT("Start of instrumentation.");

   // Added thread start/fini callback
   PIN_AddThreadStartFunction(threadStartCallback, 0);
   PIN_AddThreadFiniFunction(threadFiniCallback, 0);

   if ((cfg->getBool("general/enable_syscall_modeling")))
   {
      if (Sim()->getConfig()->getSimulationMode() == Config::FULL)
      {
         initializeSyscallModeling();
         PIN_AddSyscallEntryFunction(syscallEnterRunModel, 0);
         PIN_AddSyscallExitFunction(syscallExitRunModel, 0);
         PIN_AddContextChangeFunction(contextChange, NULL);
      }
      else // Sim()->getConfig()->getSimulationMode() == Config::LITE
      {
         PIN_AddSyscallEntryFunction(lite::syscallEnterRunModel, 0);
         PIN_AddSyscallExitFunction(lite::syscallExitRunModel, 0);
      }
   }

   // Add RTN instrumentation
   if (Sim()->getConfig()->getSimulationMode() == Config::FULL)
      RTN_AddInstrumentFunction(routineCallback, 0);
   else // Sim()->getConfig()->getSimulationMode() == Config::LITE
      RTN_AddInstrumentFunction(lite::routineCallback, 0);

   // Add INS instrumentation
   INS_AddInstrumentFunction(instructionCallback, 0);

   initProgressTrace();

   // Add Application Fini function
   PIN_AddFiniFunction(ApplicationExit, 0);

   // Never returns
   LOG_PRINT("Running program...");
   PIN_StartProgram();

   return 0;
}
<commit_msg>[misc][pin] Removed unnecessary LOG_PRINT calls and other formatting changes<commit_after>// Harshad Kasture, Jason Miller, Chris Celio, Charles Gruenwald,
// Nathan Beckmann, George Kurian, David Wentzlaff, James Psota
// 10.12.08
//
// Carbon Computer Simulator
//
// This simulator models future multi-core computers with thousands of cores.
// It runs on today's x86 multicores and will scale as more and more cores
// and better inter-core communications mechanisms become available.
// The simulator provides a platform for research in processor architecture,
// compilers, network interconnect topologies, and some OS.
//
// The simulator runs on top of Intel's Pin dynamic binary instrumention engine.
// Application code in the absence of instrumentation runs more or less
// natively and is thus high performance. When instrumentation is used, models
// can be hot-swapped or dynamically enabled and disabled as desired so that
// performance tracks the level of simulation detail needed.

#include <iostream>
#include <assert.h>
#include <set>
#include <sys/syscall.h>
#include <unistd.h>

#include "pin.H"
#include "log.h"
#include "routine_replace.h"

// FIXME: This list could probably be trimmed down a lot.
#include "simulator.h"
#include "tile_manager.h"
#include "config.h"
#include "tile.h"
#include "syscall_model.h"
#include "thread_manager.h"
#include "thread_scheduler.h"
#include "config_file.hpp"
#include "handle_args.h"
#include "thread_start.h"
#include "pin_config.h"
#include "log.h"
#include "vm_manager.h"
#include "instruction_modeling.h"
#include "progress_trace.h"
#include "clock_skew_management.h"
#include "handle_threads.h"

#include "redirect_memory.h"
#include "handle_syscalls.h"
#include "opcodes.h"
#include "hash_map.h"
#include <typeinfo>

// lite directories
#include "lite/routine_replace.h"
#include "lite/memory_modeling.h"
#include "lite/handle_syscalls.h"

// ---------------------------------------------------------------
// FIXME:
// There should be a better place to keep these globals
// -- a PinSimulator class or smthg
bool done_app_initialization = false;
config::ConfigFile *cfg;

// clone stuff
extern int *parent_tidptr;
extern int *child_tidptr;

extern PIN_LOCK clone_memory_update_lock;

map <ADDRINT, string> rtn_map;
PIN_LOCK rtn_map_lock;

HashMap core_map;
// ---------------------------------------------------------------

void printRtn (ADDRINT rtn_addr, bool enter)
{
   PIN_GetLock (&rtn_map_lock, 1);
   map<ADDRINT, string>::iterator it = rtn_map.find (rtn_addr);

   string point = enter ? "Enter" : "Exit";
   if (it != rtn_map.end())
   {
      LOG_PRINT ("Stack trace : %s %s", point.c_str(), (it->second).c_str());
   }
   else
   {
      LOG_PRINT ("Stack trace : %s UNKNOWN", point.c_str());
   }

   PIN_ReleaseLock (&rtn_map_lock);
}

VOID printInsInfo(CONTEXT* ctxt)
{
   __attribute__((unused)) ADDRINT reg_inst_ptr = PIN_GetContextReg(ctxt, REG_INST_PTR);
   __attribute__((unused)) ADDRINT reg_stack_ptr = PIN_GetContextReg(ctxt, REG_STACK_PTR);

   LOG_PRINT("eip(%#lx), esp(%#lx)", reg_inst_ptr, reg_stack_ptr);
}

void routineCallback(RTN rtn, void *v)
{
   string rtn_name = RTN_Name(rtn);

   replaceUserAPIFunction(rtn, rtn_name);

   // ---------------------------------------------------------------

   std::string module = Log::getSingleton()->getModule(__FILE__);
   if (Log::getSingleton()->isEnabled(module.c_str()) &&
       Sim()->getCfg()->getBool("log/stack_trace",false))
   {
      RTN_Open (rtn);

      ADDRINT rtn_addr = RTN_Address (rtn);

      PIN_GetLock (&rtn_map_lock, 1);

      rtn_map.insert (make_pair (rtn_addr, rtn_name));

      PIN_ReleaseLock (&rtn_map_lock);

      RTN_InsertCall (rtn, IPOINT_BEFORE,
                      AFUNPTR (printRtn),
                      IARG_ADDRINT, rtn_addr,
                      IARG_BOOL, true,
                      IARG_END);

      RTN_InsertCall (rtn, IPOINT_AFTER,
                      AFUNPTR (printRtn),
                      IARG_ADDRINT, rtn_addr,
                      IARG_BOOL, false,
                      IARG_END);

      RTN_Close (rtn);
   }

   // ---------------------------------------------------------------

   if (rtn_name == "CarbonSpawnThreadSpawner")
   {
      RTN_Open (rtn);

      RTN_InsertCall (rtn, IPOINT_BEFORE,
            AFUNPTR (setupCarbonSpawnThreadSpawnerStack),
            IARG_CONTEXT,
            IARG_END);

      RTN_Close (rtn);
   }

   else if (rtn_name == "CarbonThreadSpawner")
   {
      RTN_Open (rtn);

      RTN_InsertCall (rtn, IPOINT_BEFORE,
            AFUNPTR (setupCarbonThreadSpawnerStack),
            IARG_CONTEXT,
            IARG_END);

      RTN_Close(rtn);
   }
}

VOID instructionCallback(INS ins, void *v)
{
   // Debugging Function
   if (Log::getSingleton()->isLoggingEnabled())
   {
      INS_InsertCall(ins, IPOINT_BEFORE,
            AFUNPTR(printInsInfo),
            IARG_CALL_ORDER, CALL_ORDER_FIRST,
            IARG_CONTEXT,
            IARG_END);
   }

   if (Config::getSingleton()->getEnableCoreModeling())
   {
      // Core Performance Modeling
      addInstructionModeling(ins);

      // Progress Trace
      addProgressTrace(ins);

      // Clock Skew Management
      addPeriodicSync(ins);

      // Scheduling
      addYield(ins);
   }

   if (Sim()->getConfig()->getSimulationMode() == Config::FULL)
   {
      // Special handling for futex syscall because of internal Pin lock
      if (INS_IsSyscall(ins))
      {
         INS_InsertCall(ins, IPOINT_BEFORE,
               AFUNPTR(handleFutexSyscall),
               IARG_CONTEXT,
               IARG_END);
      }
      else
      {
         // Emulate(/Rewrite)  Stack and Memory Operations
         if (rewriteStackOp (ins));
         else rewriteMemOp (ins);
      }
   }
   else // Sim()->getConfig()->getSimulationMode() == Config::LITE
   {
      // Special handling for futex syscall because of internal Pin lock
      if (INS_IsSyscall(ins))
      {
         INS_InsertCall(ins, IPOINT_BEFORE,
               AFUNPTR(lite::handleFutexSyscall),
               IARG_CONTEXT,
               IARG_END);
      }
      else
      {
         // Instrument Memory Operations
         lite::addMemoryModeling(ins);
      }
   }
}

// syscall model wrappers
void initializeSyscallModeling()
{
   PIN_InitLock(&clone_memory_update_lock);
}

void ApplicationStart()
{
}

void ApplicationExit(int, void*)
{
   LOG_PRINT("Application exit.");
   Simulator::release();
   shutdownProgressTrace();
   delete cfg;
}

VOID threadStartCallback(THREADID threadIndex, CONTEXT *ctxt, INT32 flags, VOID *v)
{
   threadStartProgressTrace();

   // Conditions under which we must initialize a core
   // 1) (!done_app_initialization) && (curr_process_num == 0)
   // 2) (done_app_initialization) && (!thread_spawner)

   if (! done_app_initialization)
   {
      // The app is not initialized, start the main thread on the main core on tile 0.
      UInt32 curr_process_num = Sim()->getConfig()->getCurrentProcessNum();

      if (Sim()->getConfig()->getSimulationMode() == Config::LITE)
      {
         LOG_ASSERT_ERROR(curr_process_num == 0, "Lite mode can only be run with 1 process");
         Sim()->getTileManager()->initializeThread(Tile::getMainCoreId(0));
      }
      else // Sim()->getConfig()->getSimulationMode() == Config::FULL
      {
         ADDRINT reg_esp = PIN_GetContextReg(ctxt, REG_STACK_PTR);
         allocateStackSpace();

         if (curr_process_num == 0)
         {
            Sim()->getTileManager()->initializeThread(Tile::getMainCoreId(0));

            ADDRINT reg_eip = PIN_GetContextReg(ctxt, REG_INST_PTR);
            // 1) Copying over Static Data
            // Get the image first
            PIN_LockClient();
            IMG img = IMG_FindByAddress(reg_eip);
            PIN_UnlockClient();
            copyStaticData(img);

            // 2) Copying over initial stack data
            copyInitialStackData(reg_esp, Tile::getMainCoreId(0));
         }
         else
         {
            tile_id_t tile_id = Sim()->getConfig()->getCurrentThreadSpawnerTileNum();
            Sim()->getTileManager()->initializeThread(Tile::getMainCoreId(tile_id));

            Core *core = Sim()->getTileManager()->getCurrentCore();

            // main thread clock is not affected by start-up time of other processes
            core->getTile()->getNetwork()->netRecv(Tile::getMainCoreId(0), core->getId(), SYSTEM_INITIALIZATION_NOTIFY);

            copyInitialStackData(reg_esp, Tile::getMainCoreId(tile_id));
         }
         // Set the current ESP accordingly
         PIN_SetContextReg(ctxt, REG_STACK_PTR, reg_esp);
      }

      // All the real initialization is done in
      // replacement_start at the moment
      done_app_initialization = true;
   }
   else
   {
      // This is NOT the main thread
      // 'application' thread or 'thread spawner'

      if (Sim()->getConfig()->getSimulationMode() == Config::LITE)
      {
         ThreadSpawnRequest req;
         Sim()->getThreadManager()->getThreadToSpawn(&req);
         Sim()->getThreadManager()->dequeueThreadSpawnReq(&req);

         LOG_ASSERT_ERROR(req.destination.tile_id < SInt32(Config::getSingleton()->getApplicationTiles()),
               "req.tile_id(%i), num application cores(%u)", req.destination.tile_id, Config::getSingleton()->getApplicationTiles());
         Sim()->getThreadManager()->onThreadStart(&req);
      }
      else // Sim()->getConfig()->getSimulationMode() == Config::FULL
      {
         ADDRINT reg_esp = PIN_GetContextReg(ctxt, REG_STACK_PTR);
         tile_id_t tile_id = PinConfig::getSingleton()->getTileIDFromStackPtr(reg_esp);
         LOG_PRINT("Got tile %d from stack ptr 0x%x", tile_id, reg_esp);

         core_id_t core_id = PinConfig::getSingleton()->getCoreIDFromStackPtr(reg_esp);
         LOG_PRINT("Got core {%d, %d} from stack ptr 0x%x", core_id.tile_id, core_id.core_type, reg_esp);

         LOG_ASSERT_ERROR(tile_id != -1, "All application threads and thread spawner are cores now");

         if (tile_id == Sim()->getConfig()->getCurrentThreadSpawnerTileNum())
         {
            // 'Thread Spawner' thread
            Sim()->getTileManager()->initializeThread(core_id);
         }
         else
         {
            // 'Application' thread
            ThreadSpawnRequest* req = Sim()->getThreadManager()->getThreadSpawnReq();

            LOG_ASSERT_ERROR (req != NULL, "ThreadSpawnRequest is NULL !!");

            // This is an application thread
            LOG_ASSERT_ERROR(tile_id == req->destination.tile_id,
                             "Got 2 different tile_ids: req->destination = {%i, %i}, tile_id = %i",
                             req->destination.tile_id, req->destination.core_type, tile_id);

            Sim()->getThreadManager()->onThreadStart(req);
         }

         // Restore the clone syscall arguments
         PIN_SetContextReg (ctxt, REG_GDX, (ADDRINT) parent_tidptr);
         PIN_SetContextReg (ctxt, LEVEL_BASE::REG_R10, (ADDRINT) child_tidptr);

         __attribute__((unused)) Tile *tile = Sim()->getTileManager()->getCurrentTile();
         LOG_ASSERT_ERROR(tile, "tile(NULL)");

         // Copy over thread stack data
         // copySpawnedThreadStackData(reg_esp);

         // Wait to make sure that the spawner has written stuff back to memory
         // FIXME: What is this for(?) This seems arbitrary
         PIN_GetLock (&clone_memory_update_lock, 2);
         PIN_ReleaseLock (&clone_memory_update_lock);
      }
   }

   // Initialize Tile map
   core_map.insert(threadIndex, Sim()->getTileManager()->getCurrentCore());
}

VOID threadFiniCallback(THREADID threadIndex, const CONTEXT *ctxt, INT32 flags, VOID *v)
{
   // De-initialize Tile map
   core_map.erase(threadIndex);

   Sim()->getThreadManager()->onThreadExit();
}

int main(int argc, char *argv[])
{
   // ---------------------------------------------------------------
   // FIXME:
   PIN_InitLock (&rtn_map_lock);
   // ---------------------------------------------------------------

   // Global initialization
   PIN_InitSymbols();
   PIN_Init(argc,argv);

   string_vec args;

   // Set the default config path if it isn't
   // overwritten on the command line.
   std::string config_path = "carbon_sim.cfg";

   parse_args(args, config_path, argc, argv);

   cfg = new config::ConfigFile();
   cfg->load(config_path);

   handle_args(args, *cfg);

   Simulator::setConfig(cfg);

   Simulator::allocate();
   Sim()->start();

   if (Sim()->getConfig()->getSimulationMode() == Config::FULL)
      PinConfig::allocate();

   // Instrumentation
   LOG_PRINT("Start of instrumentation.");

   // Added thread start/fini callback
   PIN_AddThreadStartFunction(threadStartCallback, 0);
   PIN_AddThreadFiniFunction(threadFiniCallback, 0);

   if ((cfg->getBool("general/enable_syscall_modeling")))
   {
      if (Sim()->getConfig()->getSimulationMode() == Config::FULL)
      {
         initializeSyscallModeling();
         PIN_AddSyscallEntryFunction(syscallEnterRunModel, 0);
         PIN_AddSyscallExitFunction(syscallExitRunModel, 0);
         PIN_AddContextChangeFunction(contextChange, NULL);
      }
      else // Sim()->getConfig()->getSimulationMode() == Config::LITE
      {
         PIN_AddSyscallEntryFunction(lite::syscallEnterRunModel, 0);
         PIN_AddSyscallExitFunction(lite::syscallExitRunModel, 0);
      }
   }

   // Add RTN instrumentation
   if (Sim()->getConfig()->getSimulationMode() == Config::FULL)
      RTN_AddInstrumentFunction(routineCallback, 0);
   else // Sim()->getConfig()->getSimulationMode() == Config::LITE
      RTN_AddInstrumentFunction(lite::routineCallback, 0);

   // Add INS instrumentation
   INS_AddInstrumentFunction(instructionCallback, 0);

   initProgressTrace();

   // Add Application Fini function
   PIN_AddFiniFunction(ApplicationExit, 0);

   // Never returns
   LOG_PRINT("Running program...");
   PIN_StartProgram();

   return 0;
}
<|endoftext|>


<commit_before>#include "lvl.hpp"
#include "geom.hpp"
#include "player.hpp"
#include "../utils/utils.hpp"
#include <SDL/SDL.h>
#include <unistd.h>	// sleep()
#include <cstdlib>

enum {
	Width = 640,
	Height = 480,

	// from mid
	PlayerWidth = 21,
	PlayerOffx = 7,
	PlayerHeight = 29,
	PlayerOffy = 2,
};

SDL_Surface *screen;
Point tr(0, 0);

static void init(void);
static unsigned int keys(void);
static void scroll(const Point&, const Point&);
static void draw(const Lvl&, const Player&);
static void drawlvl(unsigned int z, const Lvl&);
static void drawplayer(const Player&);
static void clear(void);
static void fillrect(SDL_Rect*, Color);

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

	Lvl lvl(stdin);
	Player p(2 * Tile::Width + PlayerOffx, 2 * Tile::Height + PlayerOffy,
		0, PlayerWidth, PlayerHeight);

	for ( ; ; ) {
		unsigned int next = SDL_GetTicks() + 20;

		draw(lvl, p);

		Point l0(p.loc());
		p.act(lvl, keys());
		scroll(l0, p.loc());

		SDL_PumpEvents();

		while (SDL_GetTicks() < next)
			;
	}

	return 0;
}

static void init(void) {
	if (SDL_Init(SDL_INIT_VIDEO) < 0)
		fatal("Failed to init SDL: %s\n", SDL_GetError());

	unsigned int flags = SDL_HWSURFACE | SDL_DOUBLEBUF;
	screen = SDL_SetVideoMode(Width, Height, 0, flags);
	if (!screen)
		fatal("Failed to set video mode: %s\n", SDL_GetError());

	SDL_WM_SetCaption("play", "play");
}

#if SDLVER == 13
static unsigned int keys(void) {
	int nkeys;
	const Uint8 *state = SDL_GetKeyboardState(&nkeys);

	unsigned int keys = 0;
	if (state[SDL_SCANCODE_LEFT])
		keys |= Player::Left;
	if (state[SDL_SCANCODE_RIGHT])
		keys |= Player::Right;
	if (state[SDL_SCANCODE_UP])
		keys |= Player::Jump;
	if (state[SDL_SCANCODE_SPACE])
		keys |= Player::Act;
	if (state[SDL_SCANCODE_Q])
		exit(0);

	return keys;
}
#else
static unsigned int keys(void) {
	int nkeys;
	const Uint8 *state = SDL_GetKeyState(&nkeys);

	unsigned int keys = 0;
	if (state[SDLK_LEFT])
		keys |= Player::Left;
	if (state[SDLK_RIGHT])
		keys |= Player::Right;
	if (state[SDLK_UP])
		keys |= Player::Jump;
	if (state[SDLK_SPACE])
		keys |= Player::Act;
	if (state[SDLK_q])
		exit(0);

	return keys;
}
#endif

static void scroll(const Point &l0, const Point &l1) {
	Point delta(l1.x - l0.x, l1.y - l0.y);

	if ((delta.x > 0 && l1.x + tr.x > Width * 0.75) ||
		(delta.x < 0 && l1.x + tr.x < Width * 0.25))
		tr.x -= delta.x;
	if ((delta.y > 0 && l1.y + tr.y > Height * 0.75) ||
		(delta.y < 0 && l1.y + tr.y < Height * 0.25))
		tr.y -= delta.y;
}

static void draw(const Lvl &lvl, const Player &p) {
	clear();
	drawlvl(0, lvl);
	drawplayer(p);
	SDL_Flip(screen);
}

static void drawlvl(unsigned int z, const Lvl &lvl) {
	for (unsigned int x = 0; x < lvl.width(); x++) {
	for (unsigned int y = 0; y < lvl.height(); y++) {
		Lvl::Blkinfo bi(lvl.at(x, y, z));
		SDL_Rect r;
		r.w = Tile::Width;
		r.h = Tile::Height;
		r.x = x * Tile::Width + tr.x;
		r.y = y * Tile::Height + tr.y;

		if (bi.tile.flags & Tile::Collide)
			fillrect(&r, Image::black);
		else if (bi.tile.flags & Tile::Water)
			fillrect(&r, Image::blue);
	}
	}
}

static void drawplayer(const Player &p) {
	SDL_Rect r;
	r.w = p.body.bbox.b.x - p.body.bbox.a.x;
	r.h = p.body.bbox.b.y - p.body.bbox.a.y;
	r.x = p.body.bbox.a.x + tr.x;
	r.y = p.body.bbox.a.y + tr.y;
	fillrect(&r, Image::green);
}

static void clear(void) {
	SDL_Rect r;
	r.x = r.y = 0;
	r.w = Width;
	r.h = Height;
	fillrect(&r, Image::white);
}

static void fillrect(SDL_Rect *rect, Color color) {
	unsigned char r = color.getred255();
	unsigned char g = color.getgreen255();
	unsigned char b = color.getblue255();
	SDL_FillRect(screen, rect, SDL_MapRGB(screen->format, r, g, b));
}<commit_msg>plat2d: swap red and blue in fillrect. This must be a bug in SDL but red and blue seem to be in the wrong order.<commit_after>#include "lvl.hpp"
#include "geom.hpp"
#include "player.hpp"
#include "../utils/utils.hpp"
#include <SDL/SDL.h>
#include <unistd.h>	// sleep()
#include <cstdlib>

enum {
	Width = 640,
	Height = 480,

	// from mid
	PlayerWidth = 21,
	PlayerOffx = 7,
	PlayerHeight = 29,
	PlayerOffy = 2,
};

SDL_Surface *screen;
Point tr(0, 0);

static void init(void);
static unsigned int keys(void);
static void scroll(const Point&, const Point&);
static void draw(const Lvl&, const Player&);
static void drawlvl(unsigned int z, const Lvl&);
static void drawplayer(const Player&);
static void clear(void);
static void fillrect(SDL_Rect*, Color);

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

	Lvl lvl(stdin);
	Player p(2 * Tile::Width + PlayerOffx, 2 * Tile::Height + PlayerOffy,
		0, PlayerWidth, PlayerHeight);

	for ( ; ; ) {
		unsigned int next = SDL_GetTicks() + 20;

		draw(lvl, p);

		Point l0(p.loc());
		p.act(lvl, keys());
		scroll(l0, p.loc());

		SDL_PumpEvents();

		while (SDL_GetTicks() < next)
			;
	}

	return 0;
}

static void init(void) {
	if (SDL_Init(SDL_INIT_VIDEO) < 0)
		fatal("Failed to init SDL: %s\n", SDL_GetError());

	unsigned int flags = SDL_HWSURFACE | SDL_DOUBLEBUF;
	screen = SDL_SetVideoMode(Width, Height, 0, flags);
	if (!screen)
		fatal("Failed to set video mode: %s\n", SDL_GetError());

	SDL_WM_SetCaption("play", "play");
}

#if SDLVER == 13
static unsigned int keys(void) {
	int nkeys;
	const Uint8 *state = SDL_GetKeyboardState(&nkeys);

	unsigned int keys = 0;
	if (state[SDL_SCANCODE_LEFT])
		keys |= Player::Left;
	if (state[SDL_SCANCODE_RIGHT])
		keys |= Player::Right;
	if (state[SDL_SCANCODE_UP])
		keys |= Player::Jump;
	if (state[SDL_SCANCODE_SPACE])
		keys |= Player::Act;
	if (state[SDL_SCANCODE_Q])
		exit(0);

	return keys;
}
#else
static unsigned int keys(void) {
	int nkeys;
	const Uint8 *state = SDL_GetKeyState(&nkeys);

	unsigned int keys = 0;
	if (state[SDLK_LEFT])
		keys |= Player::Left;
	if (state[SDLK_RIGHT])
		keys |= Player::Right;
	if (state[SDLK_UP])
		keys |= Player::Jump;
	if (state[SDLK_SPACE])
		keys |= Player::Act;
	if (state[SDLK_q])
		exit(0);

	return keys;
}
#endif

static void scroll(const Point &l0, const Point &l1) {
	Point delta(l1.x - l0.x, l1.y - l0.y);

	if ((delta.x > 0 && l1.x + tr.x > Width * 0.75) ||
		(delta.x < 0 && l1.x + tr.x < Width * 0.25))
		tr.x -= delta.x;
	if ((delta.y > 0 && l1.y + tr.y > Height * 0.75) ||
		(delta.y < 0 && l1.y + tr.y < Height * 0.25))
		tr.y -= delta.y;
}

static void draw(const Lvl &lvl, const Player &p) {
	clear();
	drawlvl(0, lvl);
	drawplayer(p);
	SDL_Flip(screen);
}

static void drawlvl(unsigned int z, const Lvl &lvl) {
	for (unsigned int x = 0; x < lvl.width(); x++) {
	for (unsigned int y = 0; y < lvl.height(); y++) {
		Lvl::Blkinfo bi(lvl.at(x, y, z));
		SDL_Rect r;
		r.w = Tile::Width;
		r.h = Tile::Height;
		r.x = x * Tile::Width + tr.x;
		r.y = y * Tile::Height + tr.y;

		if (bi.tile.flags & Tile::Collide)
			fillrect(&r, Image::black);
		else if (bi.tile.flags & Tile::Water)
			fillrect(&r, Image::blue);
	}
	}
}

static void drawplayer(const Player &p) {
	SDL_Rect r;
	r.w = p.body.bbox.b.x - p.body.bbox.a.x;
	r.h = p.body.bbox.b.y - p.body.bbox.a.y;
	r.x = p.body.bbox.a.x + tr.x;
	r.y = p.body.bbox.a.y + tr.y;
	fillrect(&r, Image::green);
}

static void clear(void) {
	SDL_Rect r;
	r.x = r.y = 0;
	r.w = Width;
	r.h = Height;
	fillrect(&r, Image::white);
}

static void fillrect(SDL_Rect *rect, Color color) {
	unsigned char r = color.getred255();
	unsigned char g = color.getgreen255();
	unsigned char b = color.getblue255();
	SDL_FillRect(screen, rect, SDL_MapRGB(screen->format, b, g, r));
}<|endoftext|>


<commit_before>
#include "FemusInit.hpp"
#include "MultiLevelProblem.hpp"
#include "VTKWriter.hpp"
#include "TransientSystem.hpp"
#include "NonLinearImplicitSystem.hpp"
#include "Marker.hpp"
#include "Line.hpp"

#include "Fluid.hpp"
#include "Solid.hpp"
#include "Parameter.hpp"

#include "NumericVector.hpp"
#include "adept.h"

#include "../include/mpmFem.hpp"

using namespace femus;

double SetVariableTimeStep(const double time)
{
  double dt =  0.02;
  return dt;
}

bool SetBoundaryCondition(const std::vector < double >& x, const char name[], double& value, const int facename, const double time)
{
  bool test = 1; //dirichlet
  value = 0.;

  if (!strcmp(name, "DY")) {
    if (3 == facename || 4 == facename) {
      test = 0;
      value = 0;
    }
  }
  else if (!strcmp(name, "DX")) {
    if (1 == facename || 2 == facename) {
      test = 0;
      value = 0;
    }
  }

  return test;

}

int main(int argc, char** args)
{

  // init Petsc-MPI communicator
  FemusInit mpinit(argc, args, MPI_COMM_WORLD);

  MultiLevelMesh mlMsh;
  double scalingFactor = 1.;
  unsigned numberOfUniformLevels = 4; //for refinement in 3D
  //unsigned numberOfUniformLevels = 1;
  unsigned numberOfSelectiveLevels = 0;

  double Lref = 1.;
  double Uref = 1.;
  double rhos = 1000;
  double nu = 0.4;
  double E = 4.2 * 1.e8;

  Parameter par(Lref, Uref);

  // Generate Solid Object
  Solid solid;
  solid = Solid(par, E, nu, rhos, "Neo-Hookean");

  mlMsh.ReadCoarseMesh("../input/inclined_plane_2D.neu", "fifth", scalingFactor);
  mlMsh.RefineMesh(numberOfUniformLevels + numberOfSelectiveLevels, numberOfUniformLevels , NULL);

  unsigned dim = mlMsh.GetDimension();

  MultiLevelSolution mlSol(&mlMsh);
  // add variables to mlSol
  mlSol.AddSolution("DX", LAGRANGE, SECOND, 2);
  if (dim > 1) mlSol.AddSolution("DY", LAGRANGE, SECOND, 2);
  if (dim > 2) mlSol.AddSolution("DZ", LAGRANGE, SECOND, 2);

  mlSol.AddSolution("M", LAGRANGE, FIRST, 2);
  mlSol.AddSolution("Mat", DISCONTINOUS_POLYNOMIAL, ZERO, 0, false);

  mlSol.Initialize("All");

  mlSol.AttachSetBoundaryConditionFunction(SetBoundaryCondition);

  // ******* Set boundary conditions *******
  mlSol.GenerateBdc("DX", "Steady");
  if (dim > 1) mlSol.GenerateBdc("DY", "Steady");
  if (dim > 2) mlSol.GenerateBdc("DZ", "Steady");
  mlSol.GenerateBdc("M", "Steady");

  MultiLevelProblem ml_prob(&mlSol);

  ml_prob.parameters.set<Solid> ("SolidMPM") = solid;
  ml_prob.parameters.set<Solid> ("SolidFEM") = solid;

  // ******* Add MPM system to the MultiLevel problem *******
  TransientNonlinearImplicitSystem& system = ml_prob.add_system < TransientNonlinearImplicitSystem > ("MPM_FEM");
  system.AddSolutionToSystemPDE("DX");
  if (dim > 1)system.AddSolutionToSystemPDE("DY");
  if (dim > 2) system.AddSolutionToSystemPDE("DZ");

  // ******* System MPM Assembly *******
  system.SetAssembleFunction(AssembleMPMSys);
  //system.SetAssembleFunction(AssembleFEM);
  // ******* set MG-Solver *******
  system.SetMgType(V_CYCLE);

  system.SetAbsoluteLinearConvergenceTolerance(1.0e-10);
  system.SetMaxNumberOfLinearIterations(1);
  system.SetNonLinearConvergenceTolerance(1.e-9);
  system.SetMaxNumberOfNonLinearIterations(20);

  system.SetNumberPreSmoothingStep(1);
  system.SetNumberPostSmoothingStep(1);

  // ******* Set Preconditioner *******
  system.SetMgSmoother(GMRES_SMOOTHER);

  system.init();

  // ******* Set Smoother *******
  system.SetSolverFineGrids(GMRES);

  system.SetPreconditionerFineGrids(ILU_PRECOND);

  system.SetTolerances(1.e-10, 1.e-15, 1.e+50, 40, 40);

  unsigned size = 1;
  std::vector < std::vector < double > > x; // marker
  x.resize(size);
  x[0].resize(dim, 0.);
  x[0][1] = 0.05;

  double R = 1.6;
  double PI = acos(-1.);
  unsigned NR = 600;
  unsigned NL = NR / (2 * PI);
  double DL = R / NL;

  for (unsigned i = 0; i < NL; i++) {
    double  r = R - i * DL;
    unsigned Nr = static_cast <unsigned> (ceil(NR * r / R ));
//     std::cout << r << " " << Nr << " ";
    double dtheta = 2 * PI / Nr;
    unsigned sizeOld = x.size();
    x.resize(sizeOld + Nr);
    for (unsigned s = sizeOld; s < x.size(); s++) {
      x[s].resize(dim);
    }
//     std::cout << x.size() << " ";
    for (unsigned j = 0; j < Nr; j++) {
      x[sizeOld + j][0] = r * cos(j * dtheta);
      x[sizeOld + j][1] = 0.05 + r * sin(j * dtheta);
    }
  }

  size = x.size();
  std::vector < MarkerType > markerType;
  markerType.resize(size);

  for (unsigned j = 0; j < size; j++) {
    markerType[j] = VOLUME;
  }

  std::vector < std::vector < std::vector < double > > > line(1);
  std::vector < std::vector < std::vector < double > > > line0(1);

  unsigned solType = 2;
  linea = new Line(x, markerType, mlSol.GetLevel(numberOfUniformLevels - 1), solType);

  double diskArea = PI * R * R;
  linea->SetParticlesMass(diskArea, rhos);

  linea->GetLine(line0[0]);
  PrintLine(DEFAULT_OUTPUTDIR, line0, false, 0);

  linea->GetParticlesToGridMaterial();

  // ******* Print solution *******
  mlSol.SetWriter(VTK);

  std::vector<std::string> mov_vars;
  mov_vars.push_back("DX");
  mov_vars.push_back("DY");
  mov_vars.push_back("DZ");
  mlSol.GetWriter()->SetMovingMesh(mov_vars);

  std::vector<std::string> print_vars;
  print_vars.push_back("All");

  mlSol.GetWriter()->SetDebugOutput(true);
  mlSol.GetWriter()->Write(DEFAULT_OUTPUTDIR, "biquadratic", print_vars, 0);

  gravity[0] = 9.81 * sqrt(2.) / 2.;
  gravity[1] = -9.81 * sqrt(2.) / 2.;

  system.AttachGetTimeIntervalFunction(SetVariableTimeStep);
  unsigned n_timesteps = 200;
  for (unsigned time_step = 1; time_step <= n_timesteps; time_step++) {

    system.CopySolutionToOldSolution();

    system.MGsolve();

    // ******* Print solution *******
    mlSol.GetWriter()->Write(DEFAULT_OUTPUTDIR, "biquadratic", print_vars, time_step);

    GridToParticlesProjection(ml_prob, *linea);

    linea->GetLine(line[0]);
    PrintLine(DEFAULT_OUTPUTDIR, line, false, time_step);

  }

  delete linea;
  return 0;

} //end main

<commit_msg>testing ex1<commit_after>
#include "FemusInit.hpp"
#include "MultiLevelProblem.hpp"
#include "VTKWriter.hpp"
#include "TransientSystem.hpp"
#include "NonLinearImplicitSystem.hpp"
#include "Marker.hpp"
#include "Line.hpp"

#include "Fluid.hpp"
#include "Solid.hpp"
#include "Parameter.hpp"

#include "NumericVector.hpp"
#include "adept.h"

#include "../include/mpmFem.hpp"

using namespace femus;

double SetVariableTimeStep(const double time)
{
  double dt =  0.02;
  return dt;
}

bool SetBoundaryCondition(const std::vector < double >& x, const char name[], double& value, const int facename, const double time)
{
  bool test = 1; //dirichlet
  value = 0.;

  if (!strcmp(name, "DY")) {
    if (3 == facename || 4 == facename) {
      test = 0;
      value = 0;
    }
  }
  else if (!strcmp(name, "DX")) {
    if (1 == facename || 2 == facename) {
      test = 0;
      value = 0;
    }
  }

  return test;

}

int main(int argc, char** args)
{

  // init Petsc-MPI communicator
  FemusInit mpinit(argc, args, MPI_COMM_WORLD);

  MultiLevelMesh mlMsh;
  double scalingFactor = 1.;
  unsigned numberOfUniformLevels = 4; //for refinement in 3D
  //unsigned numberOfUniformLevels = 1;
  unsigned numberOfSelectiveLevels = 0;

  double Lref = 1.;
  double Uref = 1.;
  double rhos = 1000;
  double nu = 0.4;
  double E = 4.2 * 1.e8;

  Parameter par(Lref, Uref);

  // Generate Solid Object
  Solid solid;
  solid = Solid(par, E, nu, rhos, "Neo-Hookean");

  mlMsh.ReadCoarseMesh("../input/inclined_plane_2D.neu", "fifth", scalingFactor);
  mlMsh.RefineMesh(numberOfUniformLevels + numberOfSelectiveLevels, numberOfUniformLevels , NULL);

  unsigned dim = mlMsh.GetDimension();

  MultiLevelSolution mlSol(&mlMsh);
  // add variables to mlSol
  mlSol.AddSolution("DX", LAGRANGE, SECOND, 2);
  if (dim > 1) mlSol.AddSolution("DY", LAGRANGE, SECOND, 2);
  if (dim > 2) mlSol.AddSolution("DZ", LAGRANGE, SECOND, 2);

  mlSol.AddSolution("M", LAGRANGE, FIRST, 2);
  mlSol.AddSolution("Mat", DISCONTINOUS_POLYNOMIAL, ZERO, 0, false);

  mlSol.Initialize("All");

  mlSol.AttachSetBoundaryConditionFunction(SetBoundaryCondition);

  // ******* Set boundary conditions *******
  mlSol.GenerateBdc("DX", "Steady");
  if (dim > 1) mlSol.GenerateBdc("DY", "Steady");
  if (dim > 2) mlSol.GenerateBdc("DZ", "Steady");
  mlSol.GenerateBdc("M", "Steady");

  MultiLevelProblem ml_prob(&mlSol);

  ml_prob.parameters.set<Solid> ("SolidMPM") = solid;
  ml_prob.parameters.set<Solid> ("SolidFEM") = solid;

  // ******* Add MPM system to the MultiLevel problem *******
  TransientNonlinearImplicitSystem& system = ml_prob.add_system < TransientNonlinearImplicitSystem > ("MPM_FEM");
  system.AddSolutionToSystemPDE("DX");
  if (dim > 1)system.AddSolutionToSystemPDE("DY");
  if (dim > 2) system.AddSolutionToSystemPDE("DZ");

  // ******* System MPM Assembly *******
  system.SetAssembleFunction(AssembleMPMSys);
  //system.SetAssembleFunction(AssembleFEM);
  // ******* set MG-Solver *******
  system.SetMgType(V_CYCLE);

  system.SetAbsoluteLinearConvergenceTolerance(1.0e-10);
  system.SetMaxNumberOfLinearIterations(1);
  system.SetNonLinearConvergenceTolerance(1.e-9);
  system.SetMaxNumberOfNonLinearIterations(20);

  system.SetNumberPreSmoothingStep(1);
  system.SetNumberPostSmoothingStep(1);

  // ******* Set Preconditioner *******
  system.SetMgSmoother(GMRES_SMOOTHER);

  system.init();

  // ******* Set Smoother *******
  system.SetSolverFineGrids(GMRES);

  system.SetPreconditionerFineGrids(ILU_PRECOND);

  system.SetTolerances(1.e-10, 1.e-15, 1.e+50, 40, 40);

  unsigned size = 1;
  std::vector < std::vector < double > > x; // marker
  x.resize(size);
  x[0].resize(dim, 0.);
  x[0][1] = 0.05;

  double R = 1.6;
  double PI = acos(-1.);
  unsigned NR = 600;
  unsigned NL = NR / (2 * PI);
  double DL = R / NL;

  for (unsigned i = 0; i < NL; i++) {
    double  r = R - i * DL;
    unsigned Nr = static_cast <unsigned> (ceil(NR * r / R ));
//     std::cout << r << " " << Nr << " ";
    double dtheta = 2 * PI / Nr;
    unsigned sizeOld = x.size();
    x.resize(sizeOld + Nr);
    for (unsigned s = sizeOld; s < x.size(); s++) {
      x[s].resize(dim);
    }
//     std::cout << x.size() << " ";
    for (unsigned j = 0; j < Nr; j++) {
      x[sizeOld + j][0] = r * cos(j * dtheta);
      x[sizeOld + j][1] = 0.05 + r * sin(j * dtheta);
    }
  }

  size = x.size();
  std::vector < MarkerType > markerType;
  markerType.resize(size);

  for (unsigned j = 0; j < size; j++) {
    markerType[j] = VOLUME;
  }

  std::vector < std::vector < std::vector < double > > > line(1);
  std::vector < std::vector < std::vector < double > > > line0(1);

  unsigned solType = 2;
  linea = new Line(x, markerType, mlSol.GetLevel(numberOfUniformLevels - 1), solType);

  double diskArea = PI * R * R;
  linea->SetParticlesMass(diskArea, rhos);

  linea->GetLine(line0[0]);
  PrintLine(DEFAULT_OUTPUTDIR, line0, false, 0);

  linea->GetParticlesToGridMaterial();

  // ******* Print solution *******
  mlSol.SetWriter(VTK);

  std::vector<std::string> mov_vars;
  mov_vars.push_back("DX");
  mov_vars.push_back("DY");
  mov_vars.push_back("DZ");
  mlSol.GetWriter()->SetMovingMesh(mov_vars);

  std::vector<std::string> print_vars;
  print_vars.push_back("All");

  mlSol.GetWriter()->SetDebugOutput(true);
  mlSol.GetWriter()->Write(DEFAULT_OUTPUTDIR, "biquadratic", print_vars, 0);

  double theta = PI/8;
  gravity[0] = 9.81 * sin(theta);
  gravity[1] = -9.81 * cos(theta);

  system.AttachGetTimeIntervalFunction(SetVariableTimeStep);
  unsigned n_timesteps = 300;
  for (unsigned time_step = 1; time_step <= n_timesteps; time_step++) {

    system.CopySolutionToOldSolution();

    system.MGsolve();

    // ******* Print solution *******
    mlSol.GetWriter()->Write(DEFAULT_OUTPUTDIR, "biquadratic", print_vars, time_step);

    GridToParticlesProjection(ml_prob, *linea);

    linea->GetLine(line[0]);
    PrintLine(DEFAULT_OUTPUTDIR, line, false, time_step);

  }

  delete linea;
  return 0;

} //end main

<|endoftext|>