<commit_before>/**
 * @author Parikshit Ram (pram@cc.gatech.edu)
 * @file gmm_main.cpp
 *
 * This program trains a mixture of Gaussians on a given data matrix.
 */
#include "gmm.hpp"

PROGRAM_INFO("Gaussian Mixture Model (GMM) Training",
    "This program takes a parametric estimate of a Gaussian mixture model (GMM)"
    " using the EM algorithm to find the maximum likelihood estimate.  The "
    "model is saved to an XML file, which contains information about each "
    "Gaussian."
    "\n\n"
    "If GMM training fails with an error indicating that a covariance matrix "
    "could not be inverted, be sure that the 'no_force_positive' flag was not "
    "specified.  Alternately, adding a small amount of Gaussian noise to the "
    "entire dataset may help prevent Gaussians with zero variance in a "
    "particular dimension, which is usually the cause of non-invertible "
    "covariance matrices."
    "\n\n"
    "The 'no_force_positive' flag, if set, will avoid the checks after each "
    "iteration of the EM algorithm which ensure that the covariance matrices "
    "are positive definite.  Specifying the flag can cause faster runtime, "
    "but may also cause non-positive definite covariance matrices, which will "
    "cause the program to crash.");

PARAM_STRING_REQ("input_file", "File containing the data on which the model "
    "will be fit.", "i");
PARAM_INT("gaussians", "Number of Gaussians in the GMM.", "g", 1);
PARAM_STRING("output_file", "The file to write the trained GMM parameters into "
    "(as XML).", "o", "gmm.xml");
PARAM_INT("seed", "Random seed.  If 0, 'std::time(NULL)' is used.", "s", 0);
PARAM_INT("trials", "Number of trials to perform in training GMM.", "t", 10);

// Parameters for EM algorithm.
PARAM_DOUBLE("tolerance", "Tolerance for convergence of EM.", "T", 1e-10);
PARAM_FLAG("no_force_positive", "Do not force the covariance matrices to be "
    "positive definite.", "P");
PARAM_INT("max_iterations", "Maximum number of iterations of EM algorithm "
    "(passing 0 will run until convergence).", "n", 250);

// Parameters for dataset modification.
PARAM_DOUBLE("noise", "Variance of zero-mean Gaussian noise to add to data.",
    "N", 0);

using namespace mlpack;
using namespace mlpack::gmm;
using namespace mlpack::util;

int main(int argc, char* argv[])
{
  CLI::ParseCommandLine(argc, argv);

  // Check parameters and load data.
  if (CLI::GetParam<int>("seed") != 0)
    math::RandomSeed((size_t) CLI::GetParam<int>("seed"));
  else
    math::RandomSeed((size_t) std::time(NULL));

  arma::mat dataPoints;
  data::Load(CLI::GetParam<std::string>("input_file").c_str(), dataPoints,
      true);

  const int gaussians = CLI::GetParam<int>("gaussians");
  if (gaussians <= 0)
  {
    Log::Fatal << "Invalid number of Gaussians (" << gaussians << "); must "
        "be greater than or equal to 1." << std::endl;
  }

  // Do we need to add noise to the dataset?
  if (CLI::HasParam("noise"))
  {
    Timer::Start("noise_addition");
    const double noise = CLI::GetParam<double>("noise");
    dataPoints += noise * arma::randn(dataPoints.n_rows, dataPoints.n_cols);
    Log::Info << "Added zero-mean Gaussian noise with variance " << noise
        << " to dataset." << std::endl;
    Timer::Stop("noise_addition");
  }

  // Gather parameters for EMFit object.
  const size_t maxIterations = (size_t) CLI::GetParam<int>("max_iterations");
  const double tolerance = CLI::GetParam<double>("tolerance");
  const bool forcePositive = !CLI::HasParam("no_force_positive");
  EMFit<> em(maxIterations, tolerance, forcePositive);

  // Calculate mixture of Gaussians.
  GMM<> gmm(size_t(gaussians), dataPoints.n_rows, em);

  // Compute the parameters of the model using the EM algorithm.
  Timer::Start("em");
  double likelihood = gmm.Estimate(dataPoints, CLI::GetParam<int>("trials"));
  Timer::Stop("em");

  Log::Info << "Log-likelihood of estimate: " << likelihood << ".\n";

  // Save results.
  gmm.Save(CLI::GetParam<std::string>("output_file"));
}
<commit_msg>Allow Bradley-Fayyad initialization for k-means as initialization for EM algorithm.<commit_after>/**
 * @author Parikshit Ram (pram@cc.gatech.edu)
 * @file gmm_main.cpp
 *
 * This program trains a mixture of Gaussians on a given data matrix.
 */
#include <mlpack/core.hpp>

#include "gmm.hpp"

#include <mlpack/methods/kmeans/refined_start.hpp>

using namespace mlpack;
using namespace mlpack::gmm;
using namespace mlpack::util;
using namespace mlpack::kmeans;

PROGRAM_INFO("Gaussian Mixture Model (GMM) Training",
    "This program takes a parametric estimate of a Gaussian mixture model (GMM)"
    " using the EM algorithm to find the maximum likelihood estimate.  The "
    "model is saved to an XML file, which contains information about each "
    "Gaussian."
    "\n\n"
    "If GMM training fails with an error indicating that a covariance matrix "
    "could not be inverted, be sure that the 'no_force_positive' flag was not "
    "specified.  Alternately, adding a small amount of Gaussian noise to the "
    "entire dataset may help prevent Gaussians with zero variance in a "
    "particular dimension, which is usually the cause of non-invertible "
    "covariance matrices."
    "\n\n"
    "The 'no_force_positive' flag, if set, will avoid the checks after each "
    "iteration of the EM algorithm which ensure that the covariance matrices "
    "are positive definite.  Specifying the flag can cause faster runtime, "
    "but may also cause non-positive definite covariance matrices, which will "
    "cause the program to crash.");

PARAM_STRING_REQ("input_file", "File containing the data on which the model "
    "will be fit.", "i");
PARAM_INT("gaussians", "Number of Gaussians in the GMM.", "g", 1);
PARAM_STRING("output_file", "The file to write the trained GMM parameters into "
    "(as XML).", "o", "gmm.xml");
PARAM_INT("seed", "Random seed.  If 0, 'std::time(NULL)' is used.", "s", 0);
PARAM_INT("trials", "Number of trials to perform in training GMM.", "t", 10);

// Parameters for EM algorithm.
PARAM_DOUBLE("tolerance", "Tolerance for convergence of EM.", "T", 1e-10);
PARAM_FLAG("no_force_positive", "Do not force the covariance matrices to be "
    "positive definite.", "P");
PARAM_INT("max_iterations", "Maximum number of iterations of EM algorithm "
    "(passing 0 will run until convergence).", "n", 250);

// Parameters for dataset modification.
PARAM_DOUBLE("noise", "Variance of zero-mean Gaussian noise to add to data.",
    "N", 0);

// Parameters for k-means initialization.
PARAM_FLAG("refined_start", "During the initialization, use refined initial "
    "positions for k-means clustering (Bradley and Fayyad, 1998).", "r");
PARAM_INT("samplings", "If using --refined_start, specify the number of "
    "samplings used for initial points.", "S", 100);
PARAM_DOUBLE("percentage", "If using --refined_start, specify the percentage of"
    " the dataset used for each sampling (should be between 0.0 and 1.0).",
    "p", 0.02);

int main(int argc, char* argv[])
{
  CLI::ParseCommandLine(argc, argv);

  // Check parameters and load data.
  if (CLI::GetParam<int>("seed") != 0)
    math::RandomSeed((size_t) CLI::GetParam<int>("seed"));
  else
    math::RandomSeed((size_t) std::time(NULL));

  arma::mat dataPoints;
  data::Load(CLI::GetParam<std::string>("input_file").c_str(), dataPoints,
      true);

  const int gaussians = CLI::GetParam<int>("gaussians");
  if (gaussians <= 0)
  {
    Log::Fatal << "Invalid number of Gaussians (" << gaussians << "); must "
        "be greater than or equal to 1." << std::endl;
  }

  // Do we need to add noise to the dataset?
  if (CLI::HasParam("noise"))
  {
    Timer::Start("noise_addition");
    const double noise = CLI::GetParam<double>("noise");
    dataPoints += noise * arma::randn(dataPoints.n_rows, dataPoints.n_cols);
    Log::Info << "Added zero-mean Gaussian noise with variance " << noise
        << " to dataset." << std::endl;
    Timer::Stop("noise_addition");
  }

  // Gather parameters for EMFit object.
  const size_t maxIterations = (size_t) CLI::GetParam<int>("max_iterations");
  const double tolerance = CLI::GetParam<double>("tolerance");
  const bool forcePositive = !CLI::HasParam("no_force_positive");

  // This gets a bit weird because we need different types depending on whether
  // --refined_start is specified.
  double likelihood;
  if (CLI::HasParam("refined_start"))
  {
    const int samplings = CLI::GetParam<int>("samplings");
    const double percentage = CLI::GetParam<double>("percentage");

    if (samplings <= 0)
      Log::Fatal << "Number of samplings (" << samplings << ") must be greater"
          << " than 0!" << std::endl;

    if (percentage <= 0.0 || percentage > 1.0)
      Log::Fatal << "Percentage for sampling (" << percentage << ") must be "
          << "greater than 0.0 and less than or equal to 1.0!" << std::endl;

    typedef KMeans<metric::SquaredEuclideanDistance, RefinedStart> KMeansType;

    // These are default parameters.
    KMeansType k(1000, 1.0, metric::SquaredEuclideanDistance(),
        RefinedStart(samplings, percentage));

    EMFit<KMeansType> em(maxIterations, tolerance, forcePositive, k);

    GMM<EMFit<KMeansType> > gmm(size_t(gaussians), dataPoints.n_rows, em);

    // Compute the parameters of the model using the EM algorithm.
    Timer::Start("em");
    likelihood = gmm.Estimate(dataPoints, CLI::GetParam<int>("trials"));
    Timer::Stop("em");

    // Save results.
    gmm.Save(CLI::GetParam<std::string>("output_file"));
  }
  else
  {
    EMFit<> em(maxIterations, tolerance, forcePositive);

    // Calculate mixture of Gaussians.
    GMM<> gmm(size_t(gaussians), dataPoints.n_rows, em);

    // Compute the parameters of the model using the EM algorithm.
    Timer::Start("em");
    likelihood = gmm.Estimate(dataPoints, CLI::GetParam<int>("trials"));
    Timer::Stop("em");

    // Save results.
    gmm.Save(CLI::GetParam<std::string>("output_file"));
  }

  Log::Info << "Log-likelihood of estimate: " << likelihood << ".\n";

}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2006 by FThauer FHammer   *
 *   f.thauer@web.de   *
 *                                                                         *
 *   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.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "configfile.h"
#include "game_defs.h"
#include "log.h"
#include "playerinterface.h"
#include <sqlite3.h>
#include <iostream>
#include <dirent.h>
#include <boost/lexical_cast.hpp>

using namespace std;

Log::Log(string logDirString, int logOnOffInt) : curGameID(0), logOnOff(false)
{

    if(SQLITE_LOG) {

        // logging activated
        if(logOnOffInt) {

            logOnOff = true;

            DIR *logDir;
            logDir = opendir(logDirString.c_str());

            // check if logging path exist
            if(logDirString != "" && logDir) {

                int i;
                string sql;
                char *errmsg;

                // detect current time
                char curDateTime[20];
                char curDate[11];
                char curTime[9];
                time_t now = time(NULL);
                tm *z = localtime(&now);
                strftime(curDateTime,20,"%Y-%m-%d_%H.%M.%S",z);
                strftime(curDate,11,"%Y-%m-%d",z);
                strftime(curTime,9,"%H:%M:%S",z);

                string mySqliteLogFileName = boost::lexical_cast<string>(logDirString.c_str());
                       mySqliteLogFileName += "pokerth-log-" + boost::lexical_cast<string>(curDateTime) + ".pdb";

                // open sqlite-db
                sqlite3_open(mySqliteLogFileName.data(), &mySqliteLogDb);
                if( mySqliteLogDb != 0 ) {

                    // create session table
                    sql = "CREATE TABLE Session (";
                        sql += "PokerTH_Version TEXT NOT NULL";
                        sql += ",Date TEXT NOT NULL";
                        sql += ",Time TEXT NOT NULL";
                    sql += ", PRIMARY KEY(Date,Time))";
                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
                        cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
                    }

                    sql = "INSERT INTO Session (";
                        sql += "PokerTH_Version";
                        sql += ",Date";
                        sql += ",Time";
                    sql += ") VALUES (";
                        sql += "\"" + boost::lexical_cast<string>(POKERTH_BETA_RELEASE_STRING) + "\",";
                        sql += "\"" + boost::lexical_cast<string>(curDate) + "\",";
                        sql += "\"" + boost::lexical_cast<string>(curTime) + "\")";
                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
                        cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
                    }

                    // create game table
                    sql = "CREATE TABLE Game (";
                        sql += "GameID INTEGER NOT NULL PRIMARY KEY";
                        sql += ",Startmoney INTEGER NOT NULL";
                        sql += ",StartSb INTEGER NOT NULL";
                        sql += ",DealerPos INTEGER NOT NULL";
                        for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {
                            sql += ",Seat_" + boost::lexical_cast<std::string>(i) + " TEXT";
                        }
                        sql += ",Winner_Seat INTEGER";
                    sql += ")";
                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
                        cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
                    }

                    // create hand table
                    sql = "CREATE TABLE Hand (";
                        sql += "HandID INTEGER NOT NULL";
                        sql += ",GameID INTEGER NOT NULL";
                        sql += ",Dealer_Seat INTEGER";
                        sql += ",Sb_Amount INTEGER NOT NULL";
                        sql += ",Sb_Seat INTEGER NOT NULL";
                        sql += ",Bb_Amount INTEGER NOT NULL";
                        sql += ",Bb_Seat INTEGER NOT NULL";
                        for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {
                            sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Cash INTEGER";
                            sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Card_1 INTEGER";
                            sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Card_2 INTEGER";
                            sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Hand_text TEXT";
                            sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Hand_int INTEGER";
                        }
                        for(i=1; i<=5; i++) {
                            sql += ",BoardCard_" + boost::lexical_cast<std::string>(i) + " INTEGER";
                        }
                    sql += ",PRIMARY KEY(HandID,GameID))";
                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
                        cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
                    }

                    // create action table
                    sql = "CREATE TABLE Action (";
                        sql += "ActionID INTEGER PRIMARY KEY AUTOINCREMENT";
                        sql += ",HandID INTEGER NOT NULL";
                        sql += ",GameID INTEGER NOT NULL";
                        sql += ",BeRo INTEGER NOT NULL";
                        sql += ",Player INTEGER NOT NULL";
                        sql += ",Action TEXT NOT NULL";
                        sql += ",Amount INTEGER";
                    sql += ")";
                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
                        cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
                    }

                }

            }

        }

    }
}

Log::~Log()
{
    if(SQLITE_LOG) {
        sqlite3_close(mySqliteLogDb);
    }
}

void
Log::logNewGameMsg(int gameID, int startCash, int startSmallBlind, unsigned dealerPosition, PlayerList seatsList) {

    curGameID = gameID;

    if(SQLITE_LOG) {

        if(logOnOff) {
            //if write logfiles is enabled

            PlayerListConstIterator it_c;
            string sql;
            int i;
            char *errmsg;

            if( mySqliteLogDb != 0 ) {
                // sqlite-db is open

                sql = "INSERT INTO Game (";
                    sql += "GameID";
                    sql += ",Startmoney";
                    sql += ",StartSb";
                    sql += ",DealerPos";
                    for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {
                        sql += ",Seat_" + boost::lexical_cast<std::string>(i);
                    }
                sql += ") VALUES (";
                    sql += boost::lexical_cast<string>(curGameID);
                    sql += "," + boost::lexical_cast<string>(startCash);
                    sql += "," + boost::lexical_cast<string>(startSmallBlind);
                    sql += "," + boost::lexical_cast<string>(dealerPosition);
                    for(it_c = seatsList->begin();it_c!=seatsList->end();it_c++) {
                        if((*it_c)->getMyActiveStatus()) {
                            sql += ",\"" + (*it_c)->getMyName() +"\"";
                        } else {
                            sql += ",NULL";
                        }
                    }
                    sql += ")";
                if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
                    cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
                }
            }
        }
    }
}

void
Log::logNewHandMsg(int handID, unsigned dealerPosition, int smallBlind, unsigned smallBlindPosition, int bigBlind, unsigned bigBlindPosition, PlayerList seatsList) {

    if(SQLITE_LOG) {

        if(logOnOff) {
            //if write logfiles is enabled

            PlayerListConstIterator it_c;
            string sql;
            int i;
            char *errmsg;

            if( mySqliteLogDb != 0 ) {
                // sqlite-db is open

                sql = "INSERT INTO Hand (";
                    sql += "HandID";
                    sql += ",GameID";
                    sql += ",Dealer_Seat";
                    sql += ",Sb_Amount";
                    sql += ",Sb_Seat";
                    sql += ",Bb_Amount";
                    sql += ",Bb_Seat";
                    for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {
                        sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Cash";
                    }
                sql += ") VALUES (";
                    sql += boost::lexical_cast<string>(handID);
                    sql += "," + boost::lexical_cast<string>(curGameID);
                    sql += "," + boost::lexical_cast<string>(dealerPosition+1);
                    sql += "," + boost::lexical_cast<string>(smallBlind);
                    sql += "," + boost::lexical_cast<string>(smallBlindPosition+1);
                    sql += "," + boost::lexical_cast<string>(bigBlind);
                    sql += "," + boost::lexical_cast<string>(bigBlindPosition+1);
                    for(it_c = seatsList->begin();it_c!=seatsList->end();it_c++) {
                        if((*it_c)->getMyActiveStatus()) {
                            sql += "," + boost::lexical_cast<string>((*it_c)->getMyCash());
                        } else {
                            sql += ",NULL";
                        }
                    }
                    sql += ")";
                if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
                    cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
                }

            }

        }

    }
}

//void
//Log::closeLogDbAtExit()
//{
//    if(SQLITE_LOG) {
//        // close sqlite-db
//        sqlite3_close(mySqliteLogDb);
//        mySqliteLogDb = NULL;
//    }

//}
<commit_msg>Fixing memory leaks (in currently unused code).<commit_after>/***************************************************************************
 *   Copyright (C) 2006 by FThauer FHammer   *
 *   f.thauer@web.de   *
 *                                                                         *
 *   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.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "configfile.h"
#include "game_defs.h"
#include "log.h"
#include "playerinterface.h"
#include <sqlite3.h>
#include <iostream>
#include <dirent.h>
#include <boost/lexical_cast.hpp>

using namespace std;

Log::Log(string logDirString, int logOnOffInt) : curGameID(0), logOnOff(false)
{

    if(SQLITE_LOG) {

        // logging activated
        if(logOnOffInt) {

            logOnOff = true;

            DIR *logDir;
            logDir = opendir(logDirString.c_str());

            // check if logging path exist
            if(logDirString != "" && logDir) {
				closedir(logDir);

                int i;
                string sql;
                char *errmsg;

                // detect current time
                char curDateTime[20];
                char curDate[11];
                char curTime[9];
                time_t now = time(NULL);
                tm *z = localtime(&now);
                strftime(curDateTime,20,"%Y-%m-%d_%H.%M.%S",z);
                strftime(curDate,11,"%Y-%m-%d",z);
                strftime(curTime,9,"%H:%M:%S",z);

                string mySqliteLogFileName = boost::lexical_cast<string>(logDirString.c_str());
                       mySqliteLogFileName += "pokerth-log-" + boost::lexical_cast<string>(curDateTime) + ".pdb";

                // open sqlite-db
                sqlite3_open(mySqliteLogFileName.data(), &mySqliteLogDb);
                if( mySqliteLogDb != 0 ) {

                    // create session table
                    sql = "CREATE TABLE Session (";
                        sql += "PokerTH_Version TEXT NOT NULL";
                        sql += ",Date TEXT NOT NULL";
                        sql += ",Time TEXT NOT NULL";
                    sql += ", PRIMARY KEY(Date,Time))";
                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
                        cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
						sqlite3_free(errmsg);
					}

                    sql = "INSERT INTO Session (";
                        sql += "PokerTH_Version";
                        sql += ",Date";
                        sql += ",Time";
                    sql += ") VALUES (";
                        sql += "\"" + boost::lexical_cast<string>(POKERTH_BETA_RELEASE_STRING) + "\",";
                        sql += "\"" + boost::lexical_cast<string>(curDate) + "\",";
                        sql += "\"" + boost::lexical_cast<string>(curTime) + "\")";
                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
                        cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
						sqlite3_free(errmsg);
					}

                    // create game table
                    sql = "CREATE TABLE Game (";
                        sql += "GameID INTEGER NOT NULL PRIMARY KEY";
                        sql += ",Startmoney INTEGER NOT NULL";
                        sql += ",StartSb INTEGER NOT NULL";
                        sql += ",DealerPos INTEGER NOT NULL";
                        for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {
                            sql += ",Seat_" + boost::lexical_cast<std::string>(i) + " TEXT";
                        }
                        sql += ",Winner_Seat INTEGER";
                    sql += ")";
                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
                        cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
						sqlite3_free(errmsg);
					}

                    // create hand table
                    sql = "CREATE TABLE Hand (";
                        sql += "HandID INTEGER NOT NULL";
                        sql += ",GameID INTEGER NOT NULL";
                        sql += ",Dealer_Seat INTEGER";
                        sql += ",Sb_Amount INTEGER NOT NULL";
                        sql += ",Sb_Seat INTEGER NOT NULL";
                        sql += ",Bb_Amount INTEGER NOT NULL";
                        sql += ",Bb_Seat INTEGER NOT NULL";
                        for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {
                            sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Cash INTEGER";
                            sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Card_1 INTEGER";
                            sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Card_2 INTEGER";
                            sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Hand_text TEXT";
                            sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Hand_int INTEGER";
                        }
                        for(i=1; i<=5; i++) {
                            sql += ",BoardCard_" + boost::lexical_cast<std::string>(i) + " INTEGER";
                        }
                    sql += ",PRIMARY KEY(HandID,GameID))";
                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
                        cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
						sqlite3_free(errmsg);
					}

                    // create action table
                    sql = "CREATE TABLE Action (";
                        sql += "ActionID INTEGER PRIMARY KEY AUTOINCREMENT";
                        sql += ",HandID INTEGER NOT NULL";
                        sql += ",GameID INTEGER NOT NULL";
                        sql += ",BeRo INTEGER NOT NULL";
                        sql += ",Player INTEGER NOT NULL";
                        sql += ",Action TEXT NOT NULL";
                        sql += ",Amount INTEGER";
                    sql += ")";
                    if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
                        cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
						sqlite3_free(errmsg);
					}

                }

            }

        }

    }
}

Log::~Log()
{
    if(SQLITE_LOG) {
        sqlite3_close(mySqliteLogDb);
    }
}

void
Log::logNewGameMsg(int gameID, int startCash, int startSmallBlind, unsigned dealerPosition, PlayerList seatsList) {

    curGameID = gameID;

    if(SQLITE_LOG) {

        if(logOnOff) {
            //if write logfiles is enabled

            PlayerListConstIterator it_c;
            string sql;
            int i;
            char *errmsg;

            if( mySqliteLogDb != 0 ) {
                // sqlite-db is open

                sql = "INSERT INTO Game (";
                    sql += "GameID";
                    sql += ",Startmoney";
                    sql += ",StartSb";
                    sql += ",DealerPos";
                    for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {
                        sql += ",Seat_" + boost::lexical_cast<std::string>(i);
                    }
                sql += ") VALUES (";
                    sql += boost::lexical_cast<string>(curGameID);
                    sql += "," + boost::lexical_cast<string>(startCash);
                    sql += "," + boost::lexical_cast<string>(startSmallBlind);
                    sql += "," + boost::lexical_cast<string>(dealerPosition);
                    for(it_c = seatsList->begin();it_c!=seatsList->end();it_c++) {
                        if((*it_c)->getMyActiveStatus()) {
                            sql += ",\"" + (*it_c)->getMyName() +"\"";
                        } else {
                            sql += ",NULL";
                        }
                    }
                    sql += ")";
                if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
                    cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
                }
            }
        }
    }
}

void
Log::logNewHandMsg(int handID, unsigned dealerPosition, int smallBlind, unsigned smallBlindPosition, int bigBlind, unsigned bigBlindPosition, PlayerList seatsList) {

    if(SQLITE_LOG) {

        if(logOnOff) {
            //if write logfiles is enabled

            PlayerListConstIterator it_c;
            string sql;
            int i;
            char *errmsg;

            if( mySqliteLogDb != 0 ) {
                // sqlite-db is open

                sql = "INSERT INTO Hand (";
                    sql += "HandID";
                    sql += ",GameID";
                    sql += ",Dealer_Seat";
                    sql += ",Sb_Amount";
                    sql += ",Sb_Seat";
                    sql += ",Bb_Amount";
                    sql += ",Bb_Seat";
                    for(i=1; i<=MAX_NUMBER_OF_PLAYERS; i++) {
                        sql += ",Seat_" + boost::lexical_cast<std::string>(i) + "_Cash";
                    }
                sql += ") VALUES (";
                    sql += boost::lexical_cast<string>(handID);
                    sql += "," + boost::lexical_cast<string>(curGameID);
                    sql += "," + boost::lexical_cast<string>(dealerPosition+1);
                    sql += "," + boost::lexical_cast<string>(smallBlind);
                    sql += "," + boost::lexical_cast<string>(smallBlindPosition+1);
                    sql += "," + boost::lexical_cast<string>(bigBlind);
                    sql += "," + boost::lexical_cast<string>(bigBlindPosition+1);
                    for(it_c = seatsList->begin();it_c!=seatsList->end();it_c++) {
                        if((*it_c)->getMyActiveStatus()) {
                            sql += "," + boost::lexical_cast<string>((*it_c)->getMyCash());
                        } else {
                            sql += ",NULL";
                        }
                    }
                    sql += ")";
                if(sqlite3_exec(mySqliteLogDb, sql.data(), 0, 0, &errmsg) != SQLITE_OK) {
                    cout << "Error in statement: " << sql.data() << "[" << errmsg << "]." << endl;
                }

            }

        }

    }
}

//void
//Log::closeLogDbAtExit()
//{
//    if(SQLITE_LOG) {
//        // close sqlite-db
//        sqlite3_close(mySqliteLogDb);
//        mySqliteLogDb = NULL;
//    }

//}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkXMLUnstructuredGridWriter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkXMLUnstructuredGridWriter.h"

#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnstructuredGrid.h"

vtkCxxRevisionMacro(vtkXMLUnstructuredGridWriter, "1.3");
vtkStandardNewMacro(vtkXMLUnstructuredGridWriter);

//----------------------------------------------------------------------------
vtkXMLUnstructuredGridWriter::vtkXMLUnstructuredGridWriter()
{
}

//----------------------------------------------------------------------------
vtkXMLUnstructuredGridWriter::~vtkXMLUnstructuredGridWriter()
{
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::SetInput(vtkUnstructuredGrid* input)
{
  this->vtkProcessObject::SetNthInput(0, input);
}

//----------------------------------------------------------------------------
vtkUnstructuredGrid* vtkXMLUnstructuredGridWriter::GetInput()
{
  if(this->NumberOfInputs < 1)
    {
    return 0;
    }

  return static_cast<vtkUnstructuredGrid*>(this->Inputs[0]);
}

//----------------------------------------------------------------------------
const char* vtkXMLUnstructuredGridWriter::GetDataSetName()
{
  return "UnstructuredGrid";
}

//----------------------------------------------------------------------------
const char* vtkXMLUnstructuredGridWriter::GetDefaultFileExtension()
{
  return "vtu";
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::SetInputUpdateExtent(int piece,
                                                        int numPieces,
                                                        int ghostLevel)
{
  this->GetInput()->SetUpdateExtent(piece, numPieces, ghostLevel);
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteInlinePieceAttributes()
{
  vtkUnstructuredGrid* input = this->GetInput();
  this->WriteScalarAttribute("NumberOfCells", input->GetNumberOfCells());
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteInlinePiece(vtkIndent indent)
{
  vtkUnstructuredGrid* input = this->GetInput();

  // Split progress range by the approximate fraction of data written
  // by each step in this method.
  float progressRange[2] = {0,0};
  this->GetProgressRange(progressRange);
  float fractions[3];
  this->CalculateSuperclassFraction(fractions);

  // Set the range of progress for superclass.
  this->SetProgressRange(progressRange, 0, fractions);

  // Let the superclass write its data.
  this->Superclass::WriteInlinePiece(indent);

  // Set range of progress for the cell specifications.
  this->SetProgressRange(progressRange, 1, fractions);

  // Write the cell specifications.
  this->WriteCellsInline("Cells", input->GetCells(),
                         input->GetCellTypesArray(), indent);
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteAppendedMode(vtkIndent indent)
{
  this->NumberOfCellsPositions = new unsigned long[this->NumberOfPieces];
  this->CellsPositions = new unsigned long*[this->NumberOfPieces];
  this->Superclass::WriteAppendedMode(indent);
  delete [] this->CellsPositions;
  delete [] this->NumberOfCellsPositions;
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteAppendedPieceAttributes(int index)
{
  this->Superclass::WriteAppendedPieceAttributes(index);
  this->NumberOfCellsPositions[index] =
    this->ReserveAttributeSpace("NumberOfCells");
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteAppendedPiece(int index,
                                                      vtkIndent indent)
{
  vtkUnstructuredGrid* input = this->GetInput();
  this->Superclass::WriteAppendedPiece(index, indent);
  this->CellsPositions[index] =
    this->WriteCellsAppended("Cells", input->GetCellTypesArray(), indent);
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteAppendedPieceData(int index)
{
  ostream& os = *(this->Stream);
  vtkUnstructuredGrid* input = this->GetInput();
  unsigned long returnPosition = os.tellp();
  os.seekp(this->NumberOfCellsPositions[index]);
  this->WriteScalarAttribute("NumberOfCells", input->GetNumberOfCells());
  os.seekp(returnPosition);

  // Split progress range by the approximate fraction of data written
  // by each step in this method.
  float progressRange[2] = {0,0};
  this->GetProgressRange(progressRange);
  float fractions[3];
  this->CalculateSuperclassFraction(fractions);

  // Set the range of progress for superclass.
  this->SetProgressRange(progressRange, 0, fractions);

  // Let the superclass write its data.
  this->Superclass::WriteAppendedPieceData(index);

  // Set range of progress for the cell specifications.
  this->SetProgressRange(progressRange, 1, fractions);

  // Write the cell specifications.
  this->WriteCellsAppendedData(input->GetCells(), input->GetCellTypesArray(),
                               this->CellsPositions[index]);
}

//----------------------------------------------------------------------------
vtkIdType vtkXMLUnstructuredGridWriter::GetNumberOfInputCells()
{
  return this->GetInput()->GetNumberOfCells();
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::CalculateSuperclassFraction(float* fractions)
{
  vtkUnstructuredGrid* input = this->GetInput();

  // The superclass will write point/cell data and point specifications.
  int pdArrays = input->GetPointData()->GetNumberOfArrays();
  int cdArrays = input->GetCellData()->GetNumberOfArrays();
  vtkIdType pdSize = pdArrays*this->GetNumberOfInputPoints();
  vtkIdType cdSize = cdArrays*this->GetNumberOfInputCells();
  vtkIdType pointsSize = this->GetNumberOfInputPoints();

  // This class will write cell specifications.
  vtkIdType connectSize = (input->GetCells()->GetData()->GetNumberOfTuples() -
                           input->GetNumberOfCells());
  vtkIdType offsetSize = input->GetNumberOfCells();
  vtkIdType typesSize = input->GetNumberOfCells();
  int total = (pdSize+cdSize+pointsSize+connectSize+offsetSize+typesSize);
  if(total == 0)
    {
    total = 1;
    }
  fractions[0] = 0;
  fractions[1] = float(pdSize+cdSize+pointsSize)/total;
  fractions[2] = 1;
}
<commit_msg>BUG: WriteInlinePieceAttributes was not calling its superclass's implementation.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkXMLUnstructuredGridWriter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkXMLUnstructuredGridWriter.h"

#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkUnsignedCharArray.h"
#include "vtkUnstructuredGrid.h"

vtkCxxRevisionMacro(vtkXMLUnstructuredGridWriter, "1.4");
vtkStandardNewMacro(vtkXMLUnstructuredGridWriter);

//----------------------------------------------------------------------------
vtkXMLUnstructuredGridWriter::vtkXMLUnstructuredGridWriter()
{
}

//----------------------------------------------------------------------------
vtkXMLUnstructuredGridWriter::~vtkXMLUnstructuredGridWriter()
{
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::SetInput(vtkUnstructuredGrid* input)
{
  this->vtkProcessObject::SetNthInput(0, input);
}

//----------------------------------------------------------------------------
vtkUnstructuredGrid* vtkXMLUnstructuredGridWriter::GetInput()
{
  if(this->NumberOfInputs < 1)
    {
    return 0;
    }

  return static_cast<vtkUnstructuredGrid*>(this->Inputs[0]);
}

//----------------------------------------------------------------------------
const char* vtkXMLUnstructuredGridWriter::GetDataSetName()
{
  return "UnstructuredGrid";
}

//----------------------------------------------------------------------------
const char* vtkXMLUnstructuredGridWriter::GetDefaultFileExtension()
{
  return "vtu";
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::SetInputUpdateExtent(int piece,
                                                        int numPieces,
                                                        int ghostLevel)
{
  this->GetInput()->SetUpdateExtent(piece, numPieces, ghostLevel);
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteInlinePieceAttributes()
{
  this->Superclass::WriteInlinePieceAttributes();
  vtkUnstructuredGrid* input = this->GetInput();
  this->WriteScalarAttribute("NumberOfCells", input->GetNumberOfCells());
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteInlinePiece(vtkIndent indent)
{
  vtkUnstructuredGrid* input = this->GetInput();

  // Split progress range by the approximate fraction of data written
  // by each step in this method.
  float progressRange[2] = {0,0};
  this->GetProgressRange(progressRange);
  float fractions[3];
  this->CalculateSuperclassFraction(fractions);

  // Set the range of progress for superclass.
  this->SetProgressRange(progressRange, 0, fractions);

  // Let the superclass write its data.
  this->Superclass::WriteInlinePiece(indent);

  // Set range of progress for the cell specifications.
  this->SetProgressRange(progressRange, 1, fractions);

  // Write the cell specifications.
  this->WriteCellsInline("Cells", input->GetCells(),
                         input->GetCellTypesArray(), indent);
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteAppendedMode(vtkIndent indent)
{
  this->NumberOfCellsPositions = new unsigned long[this->NumberOfPieces];
  this->CellsPositions = new unsigned long*[this->NumberOfPieces];
  this->Superclass::WriteAppendedMode(indent);
  delete [] this->CellsPositions;
  delete [] this->NumberOfCellsPositions;
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteAppendedPieceAttributes(int index)
{
  this->Superclass::WriteAppendedPieceAttributes(index);
  this->NumberOfCellsPositions[index] =
    this->ReserveAttributeSpace("NumberOfCells");
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteAppendedPiece(int index,
                                                      vtkIndent indent)
{
  vtkUnstructuredGrid* input = this->GetInput();
  this->Superclass::WriteAppendedPiece(index, indent);
  this->CellsPositions[index] =
    this->WriteCellsAppended("Cells", input->GetCellTypesArray(), indent);
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::WriteAppendedPieceData(int index)
{
  ostream& os = *(this->Stream);
  vtkUnstructuredGrid* input = this->GetInput();
  unsigned long returnPosition = os.tellp();
  os.seekp(this->NumberOfCellsPositions[index]);
  this->WriteScalarAttribute("NumberOfCells", input->GetNumberOfCells());
  os.seekp(returnPosition);

  // Split progress range by the approximate fraction of data written
  // by each step in this method.
  float progressRange[2] = {0,0};
  this->GetProgressRange(progressRange);
  float fractions[3];
  this->CalculateSuperclassFraction(fractions);

  // Set the range of progress for superclass.
  this->SetProgressRange(progressRange, 0, fractions);

  // Let the superclass write its data.
  this->Superclass::WriteAppendedPieceData(index);

  // Set range of progress for the cell specifications.
  this->SetProgressRange(progressRange, 1, fractions);

  // Write the cell specifications.
  this->WriteCellsAppendedData(input->GetCells(), input->GetCellTypesArray(),
                               this->CellsPositions[index]);
}

//----------------------------------------------------------------------------
vtkIdType vtkXMLUnstructuredGridWriter::GetNumberOfInputCells()
{
  return this->GetInput()->GetNumberOfCells();
}

//----------------------------------------------------------------------------
void vtkXMLUnstructuredGridWriter::CalculateSuperclassFraction(float* fractions)
{
  vtkUnstructuredGrid* input = this->GetInput();

  // The superclass will write point/cell data and point specifications.
  int pdArrays = input->GetPointData()->GetNumberOfArrays();
  int cdArrays = input->GetCellData()->GetNumberOfArrays();
  vtkIdType pdSize = pdArrays*this->GetNumberOfInputPoints();
  vtkIdType cdSize = cdArrays*this->GetNumberOfInputCells();
  vtkIdType pointsSize = this->GetNumberOfInputPoints();

  // This class will write cell specifications.
  vtkIdType connectSize = (input->GetCells()->GetData()->GetNumberOfTuples() -
                           input->GetNumberOfCells());
  vtkIdType offsetSize = input->GetNumberOfCells();
  vtkIdType typesSize = input->GetNumberOfCells();
  int total = (pdSize+cdSize+pointsSize+connectSize+offsetSize+typesSize);
  if(total == 0)
    {
    total = 1;
    }
  fractions[0] = 0;
  fractions[1] = float(pdSize+cdSize+pointsSize)/total;
  fractions[2] = 1;
}
<|endoftext|>


<commit_before>#include "EM_Classes.h"

Transitions::Transitions(const Model &model): N(model.N), Nm(model.Nm){
	F.setZero(Nm, Nm);
}

// updateF needs the smooth probabilities
void updateF(const MatrixXd & Xtt, const MatrixXd & Xt1t,
			 const MatrixXd & XiS, const int &T, const int & N){
	for(unsigned int j = 0; j <= parSelect.N - 1; ++j){
		for(unsigned int i = 0;  i <= parSelect.N - 1; ++i){
			xS = XiS.row(j).tail(T - 1);
			xtt_lag1 = Xitt.row(i).head(T - 1);
			xt1t = Xit1t.row(j).head(T).tail(T - 1);
			xS_lag1 = XiS.row(i).head(T - 1);
			F(j, i) = F(j, i)*((xS.cwiseProduct(xtt_lag1).cwiseQuotient(xt1t)).sum())/(xS_lag1.sum());
		}
	}
}

void updateRho(const MatrixXd & Xtt, const MatrixXd & Xt1t,
			   const MatrixXd & XiS){

}
<commit_msg>Finish transition class methods<commit_after>#include "EM_Classes.h"
#include "RN_Class.h"

void Transitions::createF(){
	F.setZero(Nm, Nm);
	P.setZero(N, N);
	randomNb rnb;
	P = P.unaryExpr(std::ptr_fun(rnb.sampleUniform));
	VectorXd normTerm(N);
	normTerm = P.colwise().sum();
	for (int i = 0; i <= N - 1; i++){
		P.col(i) = P.col(i)/normTerm(i);
	}
	if (Nm != N){
		MatrixXd Fi(Nm, N);
		Fi.setZero(Nm, N);
		for(unsigned int i = 0, j = 0;
			i < N; i++, j+=N){
			Fi.col(i).segment(j, N) = P.col(i);
		}
		for (unsigned int i = 0; i<Nm; i+=N){
			F.block(0,i,Nm,N) = Fi;
		}
	} else
		F = P;
}

// rho = (A'A)^{-1}A'e
// Since A'A is positive semidefinite matrix we use ldlt method of matrix

void Transitions::createRho(){
	rho.setZero(Nm);
	MatrixXd A(Nm+1, Nm+1);
	MatrixXd I;
	I.setIdentity(Nm, Nm);
	A << (I - F), MatrixXd::setOnes(0,d);
	rho = (A.transpose()*A).ldlt.solve(A.transpos()*I.col(Nm));
}

// updateF needs the smooth probabilities
void Transitions::updateF(const MatrixXd & Xtt, const MatrixXd & Xt1t,
						  const MatrixXd & XiS, const int &T,
						  const int & N){
	for(unsigned int j = 0; j < Nm; ++j){
		for(unsigned int i = 0;  i < Nm; ++i){
			xS = XiS.row(j).tail(T - 1);
			xtt_lag1 = Xitt.row(i).head(T - 1);
			xt1t = Xit1t.row(j).head(T).tail(T - 1);
			xS_lag1 = XiS.row(i).head(T - 1);
			F(j, i) = F(j, i)*((xS.cwiseProduct(xtt_lag1).cwiseQuotient(xt1t)).sum())/(xS_lag1.sum());
		}
	}
}

void Transitions::updateRho(const MatrixXd & XiS){
	rho = Xis.row(0);
}

Transitions::Transitions(const Model &model): N(model.N), Nm(model.Nm){
	createF();
	createRho();
}
<|endoftext|>


<commit_before>/* Chrome Linux plugin
*
* This software is released under either the GNU Library General Public
* License (see LICENSE.LGPL).
*
* Note that the only valid version of the LGPL license as far as this
* project is concerned is the original GNU Library General Public License
* Version 2.1, February 1999
*/

#include "IOCommunicator.h"
#include "jsonxx.h"
#include "RequestHandler.h"
#include "Logger.h"
#include "HostExceptions.h"

using namespace std;
using namespace jsonxx;

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

	IOCommunicator ioCommunicator;

	while (true)
	{
		_log("Parsing input...");
		string response;
		try
		{
			string request = ioCommunicator.readMessage();
			RequestHandler handler(request);
			response = handler.handleRequest().json();
		}
		catch (BaseException &e)
		{
			string msg = "Handling exception: " + e.getErrorCode();
			_log(msg.c_str());
			Object json;
			json << "result" << e.getErrorCode() << "message" << e.getErrorMessage();
			response = json.json();
		}
		catch (const std::runtime_error &e)
		{
			Object json;
			json << "result" << "invalid_argument" << "message" << e.what();
			response = json.json();
		}
		ioCommunicator.sendMessage(response);
	}
	return EXIT_SUCCESS;
}
<commit_msg>Ending windows host process in case of errors<commit_after>/* Chrome Linux plugin
*
* This software is released under either the GNU Library General Public
* License (see LICENSE.LGPL).
*
* Note that the only valid version of the LGPL license as far as this
* project is concerned is the original GNU Library General Public License
* Version 2.1, February 1999
*/

#include "IOCommunicator.h"
#include "jsonxx.h"
#include "RequestHandler.h"
#include "Logger.h"
#include "HostExceptions.h"

using namespace std;
using namespace jsonxx;

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

	IOCommunicator ioCommunicator;

	while (true)
	{
		_log("Parsing input...");
		try
		{
			string request = ioCommunicator.readMessage();
			RequestHandler handler(request);
			string response = handler.handleRequest().json();
			ioCommunicator.sendMessage(response);
		}
		catch (BaseException &e)
		{
			string msg = "Handling exception: " + e.getErrorCode();
			_log(msg.c_str());
			Object json;
			json << "result" << e.getErrorCode() << "message" << e.getErrorMessage();
			string response = json.json();
			ioCommunicator.sendMessage(response);
			break;
		}
		catch (const std::runtime_error &e)
		{
			Object json;
			json << "result" << "invalid_argument" << "message" << e.what();
			string response = json.json();
			ioCommunicator.sendMessage(response);
			break;
		}
	}
	return EXIT_SUCCESS;
}
<|endoftext|>


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

#include "debug.h"
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>

#if _WIN32
#define strerror_r(errno,buf,len) strerror_s(buf,len,errno)
#endif

namespace kj {
namespace _ {  // private

Debug::Severity Debug::minSeverity = Debug::Severity::WARNING;

ArrayPtr<const char> KJ_STRINGIFY(Debug::Severity severity) {
  static const char* SEVERITY_STRINGS[] = {
    "info",
    "warning",
    "error",
    "fatal",
    "debug"
  };

  const char* s = SEVERITY_STRINGS[static_cast<uint>(severity)];
  return arrayPtr(s, strlen(s));
}

namespace {

Exception::Type typeOfErrno(int error) {
  switch (error) {
#ifdef EDQUOT
    case EDQUOT:
#endif
#ifdef EMFILE
    case EMFILE:
#endif
#ifdef ENFILE
    case ENFILE:
#endif
#ifdef ENOBUFS
    case ENOBUFS:
#endif
#ifdef ENOLCK
    case ENOLCK:
#endif
#ifdef ENOMEM
    case ENOMEM:
#endif
#ifdef ENOSPC
    case ENOSPC:
#endif
#ifdef ETIMEDOUT
    case ETIMEDOUT:
#endif
#ifdef EUSERS
    case EUSERS:
#endif
      return Exception::Type::OVERLOADED;

#ifdef ENOTCONN:
    case ENOTCONN:
#endif
#ifdef ECONNABORTED
    case ECONNABORTED:
#endif
#ifdef ECONNREFUSED
    case ECONNREFUSED:
#endif
#ifdef ECONNRESET
    case ECONNRESET:
#endif
#ifdef EHOSTDOWN
    case EHOSTDOWN:
#endif
#ifdef EHOSTUNREACH
    case EHOSTUNREACH:
#endif
#ifdef ENETDOWN
    case ENETDOWN:
#endif
#ifdef ENETRESET
    case ENETRESET:
#endif
#ifdef ENETUNREACH
    case ENETUNREACH:
#endif
#ifdef ENONET
    case ENONET:
#endif
#ifdef EPIPE
    case EPIPE:
#endif
      return Exception::Type::DISCONNECTED;

#ifdef ENOSYS
    case ENOSYS:
#endif
#ifdef ENOTSUP
    case ENOTSUP:
#endif
#if defined(EOPNOTSUPP) && EOPNOTSUPP != ENOTSUP
    case EOPNOTSUPP:
#endif
#ifdef ENOPROTOOPT
    case ENOPROTOOPT:
#endif
#ifdef ENOTSOCK
    // This is really saying "syscall not implemented for non-sockets".
    case ENOTSOCK:
#endif
      return Exception::Type::UNIMPLEMENTED;

    default:
      return Exception::Type::FAILED;
  }
}

enum DescriptionStyle {
  LOG,
  ASSERTION,
  SYSCALL
};

static String makeDescriptionImpl(DescriptionStyle style, const char* code, int errorNumber,
                                  const char* macroArgs, ArrayPtr<String> argValues) {
  KJ_STACK_ARRAY(ArrayPtr<const char>, argNames, argValues.size(), 8, 64);

  if (argValues.size() > 0) {
    size_t index = 0;
    const char* start = macroArgs;
    while (isspace(*start)) ++start;
    const char* pos = start;
    uint depth = 0;
    bool quoted = false;
    while (char c = *pos++) {
      if (quoted) {
        if (c == '\\' && *pos != '\0') {
          ++pos;
        } else if (c == '\"') {
          quoted = false;
        }
      } else {
        if (c == '(') {
          ++depth;
        } else if (c == ')') {
          --depth;
        } else if (c == '\"') {
          quoted = true;
        } else if (c == ',' && depth == 0) {
          if (index < argValues.size()) {
            argNames[index] = arrayPtr(start, pos - 1);
          }
          ++index;
          while (isspace(*pos)) ++pos;
          start = pos;
        }
      }
    }
    if (index < argValues.size()) {
      argNames[index] = arrayPtr(start, pos - 1);
    }
    ++index;

    if (index != argValues.size()) {
      getExceptionCallback().logMessage(__FILE__, __LINE__, 0,
          str("Failed to parse logging macro args into ",
              argValues.size(), " names: ", macroArgs, '\n'));
    }
  }

  if (style == SYSCALL) {
    // Strip off leading "foo = " from code, since callers will sometimes write things like:
    //   ssize_t n;
    //   RECOVERABLE_SYSCALL(n = read(fd, buffer, sizeof(buffer))) { return ""; }
    //   return std::string(buffer, n);
    const char* equalsPos = strchr(code, '=');
    if (equalsPos != nullptr && equalsPos[1] != '=') {
      code = equalsPos + 1;
      while (isspace(*code)) ++code;
    }
  }

  if (style == ASSERTION && code == nullptr) {
    style = LOG;
  }

  {
    StringPtr expected = "expected ";
    StringPtr codeArray = style == LOG ? nullptr : StringPtr(code);
    StringPtr sep = " = ";
    StringPtr delim = "; ";
    StringPtr colon = ": ";

    StringPtr sysErrorArray;
#if __USE_GNU
    char buffer[256];
    if (style == SYSCALL) {
      sysErrorArray = strerror_r(errorNumber, buffer, sizeof(buffer));
    }
#else
    char buffer[256];
    if (style == SYSCALL) {
      strerror_r(errorNumber, buffer, sizeof(buffer));
      sysErrorArray = buffer;
    }
#endif

    size_t totalSize = 0;
    switch (style) {
      case LOG:
        break;
      case ASSERTION:
        totalSize += expected.size() + codeArray.size();
        break;
      case SYSCALL:
        totalSize += codeArray.size() + colon.size() + sysErrorArray.size();
        break;
    }

    for (size_t i = 0; i < argValues.size(); i++) {
      if (i > 0 || style != LOG) {
        totalSize += delim.size();
      }
      if (argNames[i].size() > 0 && argNames[i][0] != '\"') {
        totalSize += argNames[i].size() + sep.size();
      }
      totalSize += argValues[i].size();
    }

    String result = heapString(totalSize);
    char* pos = result.begin();

    switch (style) {
      case LOG:
        break;
      case ASSERTION:
        pos = _::fill(pos, expected, codeArray);
        break;
      case SYSCALL:
        pos = _::fill(pos, codeArray, colon, sysErrorArray);
        break;
    }
    for (size_t i = 0; i < argValues.size(); i++) {
      if (i > 0 || style != LOG) {
        pos = _::fill(pos, delim);
      }
      if (argNames[i].size() > 0 && argNames[i][0] != '\"') {
        pos = _::fill(pos, argNames[i], sep);
      }
      pos = _::fill(pos, argValues[i]);
    }

    return result;
  }
}

}  // namespace

void Debug::logInternal(const char* file, int line, Severity severity, const char* macroArgs,
                        ArrayPtr<String> argValues) {
  getExceptionCallback().logMessage(file, line, 0,
      str(severity, ": ", makeDescriptionImpl(LOG, nullptr, 0, macroArgs, argValues), '\n'));
}

Debug::Fault::~Fault() noexcept(false) {
  if (exception != nullptr) {
    Exception copy = mv(*exception);
    delete exception;
    throwRecoverableException(mv(copy));
  }
}

void Debug::Fault::fatal() {
  Exception copy = mv(*exception);
  delete exception;
  exception = nullptr;
  throwFatalException(mv(copy));
  abort();
}

void Debug::Fault::init(
    const char* file, int line, Exception::Type type,
    const char* condition, const char* macroArgs, ArrayPtr<String> argValues) {
  exception = new Exception(type, file, line,
      makeDescriptionImpl(ASSERTION, condition, 0, macroArgs, argValues));
}

void Debug::Fault::init(
    const char* file, int line, int osErrorNumber,
    const char* condition, const char* macroArgs, ArrayPtr<String> argValues) {
  exception = new Exception(typeOfErrno(osErrorNumber), file, line,
      makeDescriptionImpl(SYSCALL, condition, osErrorNumber, macroArgs, argValues));
}

String Debug::makeDescriptionInternal(const char* macroArgs, ArrayPtr<String> argValues) {
  return makeDescriptionImpl(LOG, nullptr, 0, macroArgs, argValues);
}

int Debug::getOsErrorNumber(bool nonblocking) {
  int result = errno;

  // On many systems, EAGAIN and EWOULDBLOCK have the same value, but this is not strictly required
  // by POSIX, so we need to check both.
  return result == EINTR ? -1
       : nonblocking && (result == EAGAIN || result == EWOULDBLOCK) ? 0
       : result;
}

Debug::Context::Context(): logged(false) {}
Debug::Context::~Context() noexcept(false) {}

Debug::Context::Value Debug::Context::ensureInitialized() {
  KJ_IF_MAYBE(v, value) {
    return Value(v->file, v->line, heapString(v->description));
  } else {
    Value result = evaluate();
    value = Value(result.file, result.line, heapString(result.description));
    return result;
  }
}

void Debug::Context::onRecoverableException(Exception&& exception) {
  Value v = ensureInitialized();
  exception.wrapContext(v.file, v.line, mv(v.description));
  next.onRecoverableException(kj::mv(exception));
}
void Debug::Context::onFatalException(Exception&& exception) {
  Value v = ensureInitialized();
  exception.wrapContext(v.file, v.line, mv(v.description));
  next.onFatalException(kj::mv(exception));
}
void Debug::Context::logMessage(const char* file, int line, int contextDepth, String&& text) {
  if (!logged) {
    Value v = ensureInitialized();
    next.logMessage(v.file, v.line, 0, str("context: ", mv(v.description), '\n'));
    logged = true;
  }

  next.logMessage(file, line, contextDepth + 1, mv(text));
}

}  // namespace _ (private)
}  // namespace kj
<commit_msg>Fix typo (only a warning, not an error, apparently).<commit_after>// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#include "debug.h"
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <errno.h>

#if _WIN32
#define strerror_r(errno,buf,len) strerror_s(buf,len,errno)
#endif

namespace kj {
namespace _ {  // private

Debug::Severity Debug::minSeverity = Debug::Severity::WARNING;

ArrayPtr<const char> KJ_STRINGIFY(Debug::Severity severity) {
  static const char* SEVERITY_STRINGS[] = {
    "info",
    "warning",
    "error",
    "fatal",
    "debug"
  };

  const char* s = SEVERITY_STRINGS[static_cast<uint>(severity)];
  return arrayPtr(s, strlen(s));
}

namespace {

Exception::Type typeOfErrno(int error) {
  switch (error) {
#ifdef EDQUOT
    case EDQUOT:
#endif
#ifdef EMFILE
    case EMFILE:
#endif
#ifdef ENFILE
    case ENFILE:
#endif
#ifdef ENOBUFS
    case ENOBUFS:
#endif
#ifdef ENOLCK
    case ENOLCK:
#endif
#ifdef ENOMEM
    case ENOMEM:
#endif
#ifdef ENOSPC
    case ENOSPC:
#endif
#ifdef ETIMEDOUT
    case ETIMEDOUT:
#endif
#ifdef EUSERS
    case EUSERS:
#endif
      return Exception::Type::OVERLOADED;

#ifdef ENOTCONN
    case ENOTCONN:
#endif
#ifdef ECONNABORTED
    case ECONNABORTED:
#endif
#ifdef ECONNREFUSED
    case ECONNREFUSED:
#endif
#ifdef ECONNRESET
    case ECONNRESET:
#endif
#ifdef EHOSTDOWN
    case EHOSTDOWN:
#endif
#ifdef EHOSTUNREACH
    case EHOSTUNREACH:
#endif
#ifdef ENETDOWN
    case ENETDOWN:
#endif
#ifdef ENETRESET
    case ENETRESET:
#endif
#ifdef ENETUNREACH
    case ENETUNREACH:
#endif
#ifdef ENONET
    case ENONET:
#endif
#ifdef EPIPE
    case EPIPE:
#endif
      return Exception::Type::DISCONNECTED;

#ifdef ENOSYS
    case ENOSYS:
#endif
#ifdef ENOTSUP
    case ENOTSUP:
#endif
#if defined(EOPNOTSUPP) && EOPNOTSUPP != ENOTSUP
    case EOPNOTSUPP:
#endif
#ifdef ENOPROTOOPT
    case ENOPROTOOPT:
#endif
#ifdef ENOTSOCK
    // This is really saying "syscall not implemented for non-sockets".
    case ENOTSOCK:
#endif
      return Exception::Type::UNIMPLEMENTED;

    default:
      return Exception::Type::FAILED;
  }
}

enum DescriptionStyle {
  LOG,
  ASSERTION,
  SYSCALL
};

static String makeDescriptionImpl(DescriptionStyle style, const char* code, int errorNumber,
                                  const char* macroArgs, ArrayPtr<String> argValues) {
  KJ_STACK_ARRAY(ArrayPtr<const char>, argNames, argValues.size(), 8, 64);

  if (argValues.size() > 0) {
    size_t index = 0;
    const char* start = macroArgs;
    while (isspace(*start)) ++start;
    const char* pos = start;
    uint depth = 0;
    bool quoted = false;
    while (char c = *pos++) {
      if (quoted) {
        if (c == '\\' && *pos != '\0') {
          ++pos;
        } else if (c == '\"') {
          quoted = false;
        }
      } else {
        if (c == '(') {
          ++depth;
        } else if (c == ')') {
          --depth;
        } else if (c == '\"') {
          quoted = true;
        } else if (c == ',' && depth == 0) {
          if (index < argValues.size()) {
            argNames[index] = arrayPtr(start, pos - 1);
          }
          ++index;
          while (isspace(*pos)) ++pos;
          start = pos;
        }
      }
    }
    if (index < argValues.size()) {
      argNames[index] = arrayPtr(start, pos - 1);
    }
    ++index;

    if (index != argValues.size()) {
      getExceptionCallback().logMessage(__FILE__, __LINE__, 0,
          str("Failed to parse logging macro args into ",
              argValues.size(), " names: ", macroArgs, '\n'));
    }
  }

  if (style == SYSCALL) {
    // Strip off leading "foo = " from code, since callers will sometimes write things like:
    //   ssize_t n;
    //   RECOVERABLE_SYSCALL(n = read(fd, buffer, sizeof(buffer))) { return ""; }
    //   return std::string(buffer, n);
    const char* equalsPos = strchr(code, '=');
    if (equalsPos != nullptr && equalsPos[1] != '=') {
      code = equalsPos + 1;
      while (isspace(*code)) ++code;
    }
  }

  if (style == ASSERTION && code == nullptr) {
    style = LOG;
  }

  {
    StringPtr expected = "expected ";
    StringPtr codeArray = style == LOG ? nullptr : StringPtr(code);
    StringPtr sep = " = ";
    StringPtr delim = "; ";
    StringPtr colon = ": ";

    StringPtr sysErrorArray;
#if __USE_GNU
    char buffer[256];
    if (style == SYSCALL) {
      sysErrorArray = strerror_r(errorNumber, buffer, sizeof(buffer));
    }
#else
    char buffer[256];
    if (style == SYSCALL) {
      strerror_r(errorNumber, buffer, sizeof(buffer));
      sysErrorArray = buffer;
    }
#endif

    size_t totalSize = 0;
    switch (style) {
      case LOG:
        break;
      case ASSERTION:
        totalSize += expected.size() + codeArray.size();
        break;
      case SYSCALL:
        totalSize += codeArray.size() + colon.size() + sysErrorArray.size();
        break;
    }

    for (size_t i = 0; i < argValues.size(); i++) {
      if (i > 0 || style != LOG) {
        totalSize += delim.size();
      }
      if (argNames[i].size() > 0 && argNames[i][0] != '\"') {
        totalSize += argNames[i].size() + sep.size();
      }
      totalSize += argValues[i].size();
    }

    String result = heapString(totalSize);
    char* pos = result.begin();

    switch (style) {
      case LOG:
        break;
      case ASSERTION:
        pos = _::fill(pos, expected, codeArray);
        break;
      case SYSCALL:
        pos = _::fill(pos, codeArray, colon, sysErrorArray);
        break;
    }
    for (size_t i = 0; i < argValues.size(); i++) {
      if (i > 0 || style != LOG) {
        pos = _::fill(pos, delim);
      }
      if (argNames[i].size() > 0 && argNames[i][0] != '\"') {
        pos = _::fill(pos, argNames[i], sep);
      }
      pos = _::fill(pos, argValues[i]);
    }

    return result;
  }
}

}  // namespace

void Debug::logInternal(const char* file, int line, Severity severity, const char* macroArgs,
                        ArrayPtr<String> argValues) {
  getExceptionCallback().logMessage(file, line, 0,
      str(severity, ": ", makeDescriptionImpl(LOG, nullptr, 0, macroArgs, argValues), '\n'));
}

Debug::Fault::~Fault() noexcept(false) {
  if (exception != nullptr) {
    Exception copy = mv(*exception);
    delete exception;
    throwRecoverableException(mv(copy));
  }
}

void Debug::Fault::fatal() {
  Exception copy = mv(*exception);
  delete exception;
  exception = nullptr;
  throwFatalException(mv(copy));
  abort();
}

void Debug::Fault::init(
    const char* file, int line, Exception::Type type,
    const char* condition, const char* macroArgs, ArrayPtr<String> argValues) {
  exception = new Exception(type, file, line,
      makeDescriptionImpl(ASSERTION, condition, 0, macroArgs, argValues));
}

void Debug::Fault::init(
    const char* file, int line, int osErrorNumber,
    const char* condition, const char* macroArgs, ArrayPtr<String> argValues) {
  exception = new Exception(typeOfErrno(osErrorNumber), file, line,
      makeDescriptionImpl(SYSCALL, condition, osErrorNumber, macroArgs, argValues));
}

String Debug::makeDescriptionInternal(const char* macroArgs, ArrayPtr<String> argValues) {
  return makeDescriptionImpl(LOG, nullptr, 0, macroArgs, argValues);
}

int Debug::getOsErrorNumber(bool nonblocking) {
  int result = errno;

  // On many systems, EAGAIN and EWOULDBLOCK have the same value, but this is not strictly required
  // by POSIX, so we need to check both.
  return result == EINTR ? -1
       : nonblocking && (result == EAGAIN || result == EWOULDBLOCK) ? 0
       : result;
}

Debug::Context::Context(): logged(false) {}
Debug::Context::~Context() noexcept(false) {}

Debug::Context::Value Debug::Context::ensureInitialized() {
  KJ_IF_MAYBE(v, value) {
    return Value(v->file, v->line, heapString(v->description));
  } else {
    Value result = evaluate();
    value = Value(result.file, result.line, heapString(result.description));
    return result;
  }
}

void Debug::Context::onRecoverableException(Exception&& exception) {
  Value v = ensureInitialized();
  exception.wrapContext(v.file, v.line, mv(v.description));
  next.onRecoverableException(kj::mv(exception));
}
void Debug::Context::onFatalException(Exception&& exception) {
  Value v = ensureInitialized();
  exception.wrapContext(v.file, v.line, mv(v.description));
  next.onFatalException(kj::mv(exception));
}
void Debug::Context::logMessage(const char* file, int line, int contextDepth, String&& text) {
  if (!logged) {
    Value v = ensureInitialized();
    next.logMessage(v.file, v.line, 0, str("context: ", mv(v.description), '\n'));
    logged = true;
  }

  next.logMessage(file, line, contextDepth + 1, mv(text));
}

}  // namespace _ (private)
}  // namespace kj
<|endoftext|>


<commit_before><commit_msg>Update FexWrite.cpp<commit_after><|endoftext|>


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

#ifndef _IDLC_ASTDECLARATION_HXX_
#include <idlc/astdeclaration.hxx>
#endif
#ifndef _IDLC_ASTEXPRESSION_HXX_
#include <idlc/astexpression.hxx>
#endif

class AstConstant : public AstDeclaration
{
public:
    AstConstant(const ExprType type, const NodeType nodeType,
                AstExpression* pExpr, const ::rtl::OString& name, AstScope* pScope);
    AstConstant(const ExprType type, AstExpression* pExpr,
                const ::rtl::OString& name, AstScope* pScope);
    virtual ~AstConstant();

    AstExpression* getConstValue()
        { return m_pConstValue; }
    const ExprType getConstValueType()
        { return m_constValueType; }

    sal_Bool dumpBlob(RegistryTypeWriter& rBlob, sal_uInt16 index);
private:
    AstExpression*                  m_pConstValue;
    const ExprType  m_constValueType;
};

#endif // _IDLC_ASTCONSTANT_HXX_

<commit_msg>INTEGRATION: CWS sb14 (1.1.96); FILE MERGED 2004/03/15 09:53:51 sb 1.1.96.1: #i21150# Adapted to new extensible type writer interface; added support for bound interface attributes.<commit_after>/*************************************************************************
 *
 *  $RCSfile: astconstant.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2004-03-30 16:40:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _IDLC_ASTCONSTANT_HXX_
#define _IDLC_ASTCONSTANT_HXX_

#ifndef _IDLC_ASTDECLARATION_HXX_
#include <idlc/astdeclaration.hxx>
#endif
#ifndef _IDLC_ASTEXPRESSION_HXX_
#include <idlc/astexpression.hxx>
#endif

namespace typereg { class Writer; }

class AstConstant : public AstDeclaration
{
public:
    AstConstant(const ExprType type, const NodeType nodeType,
                AstExpression* pExpr, const ::rtl::OString& name, AstScope* pScope);
    AstConstant(const ExprType type, AstExpression* pExpr,
                const ::rtl::OString& name, AstScope* pScope);
    virtual ~AstConstant();

    AstExpression* getConstValue()
        { return m_pConstValue; }
    const ExprType getConstValueType()
        { return m_constValueType; }

    sal_Bool dumpBlob(typereg::Writer & rBlob, sal_uInt16 index);
private:
    AstExpression*                  m_pConstValue;
    const ExprType  m_constValueType;
};

#endif // _IDLC_ASTCONSTANT_HXX_

<|endoftext|>


<commit_before>/**
 * OpenAL++ - an object oriented toolkit for spatial sound
 * Copyright (C) 2002 VRlab, Ume University
 *
 * OpenAL++ was created using the libraries:
 *                 OpenAL (http://www.openal.org),
 *              PortAudio (http://www.portaudio.com/), and
 *              CommonC++ (http://cplusplus.sourceforge.net/)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
 */

#include "openalpp/filestream.h"

namespace openalpp {

FileStream::FileStream(const char *filename,const int buffersize)
  throw (NameError,InitError,FileError) : Stream() {

  FILE *filehandle=fopen(filename,"r");
  if(!filehandle)
    throw FileError("FileStream: Couldn't open file");

  // Check for file type, create a FileStreamUpdater if a known type is
  // detected, otherwise throw an error.
  OggVorbis_File oggfile;
  if(ov_open(filehandle,&oggfile,NULL,0)>=0) {
    vorbis_info *ogginfo=ov_info(&oggfile,-1);
    ALenum format;
    if(ogginfo->channels==1) // We'll request 16 bit later...
      format=AL_FORMAT_MONO16;
    else
      format=AL_FORMAT_STEREO16;
    updater_=new FileStreamUpdater(oggfile,
				   buffername_,buffer2_->GetName(),
				   format,ogginfo->rate,
				   buffersize);
  } else {
    fclose(filehandle);
    throw FileError("FileStream: File of unknown type");
  }
}

FileStream::FileStream(const FileStream &stream)
  : Stream((const Stream &)stream) {
}

FileStream::~FileStream() {
}

FileStream &FileStream::operator=(const FileStream &stream) {
  if(&stream!=this) {
    Stream::operator=((const Stream &)stream);
  }
  return *this;
}

}
<commit_msg>Moved an include here from header<commit_after>/**
 * OpenAL++ - an object oriented toolkit for spatial sound
 * Copyright (C) 2002 VRlab, Ume University
 *
 * OpenAL++ was created using the libraries:
 *                 OpenAL (http://www.openal.org),
 *              PortAudio (http://www.portaudio.com/), and
 *              CommonC++ (http://cplusplus.sourceforge.net/)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
 */

#include "openalpp/filestreamupdater.h"
#include "openalpp/filestream.h"

namespace openalpp {

FileStream::FileStream(const char *filename,const int buffersize)
  throw (NameError,InitError,FileError) : Stream() {

  FILE *filehandle=fopen(filename,"r");
  if(!filehandle)
    throw FileError("FileStream: Couldn't open file");

  // Check for file type, create a FileStreamUpdater if a known type is
  // detected, otherwise throw an error.
  OggVorbis_File oggfile;
  if(ov_open(filehandle,&oggfile,NULL,0)>=0) {
    vorbis_info *ogginfo=ov_info(&oggfile,-1);
    ALenum format;
    if(ogginfo->channels==1) // We'll request 16 bit later...
      format=AL_FORMAT_MONO16;
    else
      format=AL_FORMAT_STEREO16;
    updater_=new FileStreamUpdater(oggfile,
				   buffername_,buffer2_->GetName(),
				   format,ogginfo->rate,
				   buffersize);
  } else {
    fclose(filehandle);
    throw FileError("FileStream: File of unknown type");
  }
}

FileStream::FileStream(const FileStream &stream)
  : Stream((const Stream &)stream) {
}

FileStream::~FileStream() {
}

FileStream &FileStream::operator=(const FileStream &stream) {
  if(&stream!=this) {
    Stream::operator=((const Stream &)stream);
  }
  return *this;
}

}
<|endoftext|>


<commit_before>#include <vector>
#include <string>
#include <iostream>
#include <math.h>
#include "matrix.h"
#include "field2.h"
#include "monitors/surface_monitor.h"

using namespace std;

namespace qbox {
    surface_monitor::surface_monitor(string name, const surface &surf, const freq_data &freq, bool extendable): monitor(name,freq,extendable), surf(surf), dir(0), length(0) {
        F = nullptr;
    }

    void surface_monitor::set_F(Field2D *newF) {
        monitor::set_F(newF);
        auto isurf = newF->grid.to_grid(surf);
        int length = isurf.dim.norm();

        prevE = matrix<double,1>(length+1);
        rE = matrix<double,2>(length, freq.size());
        iE = matrix<double,2>(length, freq.size());
        rH = matrix<double,2>(length, freq.size());
        iH = matrix<double,2>(length, freq.size());

        for (int i = 0; i != length; i++) {
            prevE(i) = 0;
            for (int j = 0; j!= freq.size(); j++) {
                rE(i,j) = 0;
                iE(i,j) = 0;
                rH(i,j) = 0;
                iH(i,j) = 0;
            }
        }
        prevE(length) = 0;

        auto gName = get_group();
        auto dspace = h5cpp::dspace(vector<hsize_t>{2});
        auto attr = gName.create_attribute("p1", h5cpp::dtype::Double, dspace);
        attr.write(surf.a.data());
        attr = gName.create_attribute("p2", h5cpp::dtype::Double, dspace);
        attr.write(surf.b.data());
    }

    void surface_monitor::update() {
        //*** this dir, Hfield combo is bad design (maybe use enum)
        auto isurf = F->grid.to_grid(surf);
        auto *Hfield = isurf.dim[0] == 0 ? &F->Hy : &F->Hx;

        double E = 0;
        double H = 0;
        freq.update(F->t);

        //this if check could be done outside the for loop somehow
        int i = 0;
        for (ivec p = isurf.a; p != isurf.b; p += isurf.tangent) {
            H = ((*Hfield)(p)+ (*Hfield)(p - isurf.normal)
                    + (*Hfield)(p + isurf.tangent) + (*Hfield)(p - isurf.normal + isurf.tangent))/4;
            E = (F->Ez(p) + F->Ez(p + isurf.tangent)
                    + prevE(i) + prevE(i+1))/4;

            prevE(i) = F->Ez(p);

            for (int j = 0; j != freq.size(); j++) {
                rE(i,j) += E*freq.get_cosf(j);
                iE(i,j) += E*freq.get_sinf(j);
                rH(i,j) += H*freq.get_cosf(j);
                iH(i,j) += H*freq.get_sinf(j);
            }
            i += 1;
        }
        prevE(length) = F->Ez(isurf.b + isurf.tangent);
    }

    Eigen::ArrayXd surface_monitor::compute_flux() const {
        Eigen::ArrayXd S = Eigen::ArrayXd::Zero(freq.size());

        for (int j = 0; j != freq.size(); j++) {
            for (int i = 0; i != length; i++) {
                S[j] += rE(i,j)*rH(i,j) + iE(i,j)*iH(i,j);
            }
        }
        S *= F->dx;
        return S;
    }

    void surface_monitor::write_flux() {
        auto S = compute_flux();
        auto gName = get_group();

        h5cpp::h5dset dset;
        if (!gName.object_exists("flux")) {
            vector<hsize_t> dims = {hsize_t(freq.size())};
            vector<hsize_t> max_dims = {hsize_t(freq.size())};
            if (!extendable) {
                h5cpp::dspace ds(dims, max_dims);
                dset = gName.create_dataset("flux",
                             h5cpp::dtype::Double, ds);
            }
            else {
                dims.push_back(1);
                max_dims.push_back(h5cpp::inf);
                vector<hsize_t> chunk_dims = dims;
                h5cpp::dspace ds(dims, max_dims, chunk_dims);
                dset = gName.create_dataset("flux",
                             h5cpp::dtype::Double, ds);
            }
            dset.write(S.data());
        }
        else {
            dset = gName.open_dataset("flux");
            dset.append(S.data());
        }
    }
}

<commit_msg>surface monitor flux calculations fixed<commit_after>#include <vector>
#include <string>
#include <iostream>
#include <math.h>
#include "matrix.h"
#include "field2.h"
#include "monitors/surface_monitor.h"

using namespace std;

namespace qbox {
    surface_monitor::surface_monitor(string name, const surface &surf, const freq_data &freq, bool extendable): monitor(name,freq,extendable), surf(surf), dir(0), length(0) {
        F = nullptr;
    }

    void surface_monitor::set_F(Field2D *newF) {
        monitor::set_F(newF);
        auto isurf = newF->grid.to_grid(surf);
        length = isurf.dim.norm();

        prevE = matrix<double,1>(length+1);
        rE = matrix<double,2>(length, freq.size());
        iE = matrix<double,2>(length, freq.size());
        rH = matrix<double,2>(length, freq.size());
        iH = matrix<double,2>(length, freq.size());

        for (int i = 0; i != length; i++) {
            prevE(i) = 0;
            for (int j = 0; j!= freq.size(); j++) {
                rE(i,j) = 0;
                iE(i,j) = 0;
                rH(i,j) = 0;
                iH(i,j) = 0;
            }
        }
        prevE(length) = 0;

        auto gName = get_group();
        auto dspace = h5cpp::dspace(vector<hsize_t>{2});
        auto attr = gName.create_attribute("p1", h5cpp::dtype::Double, dspace);
        attr.write(surf.a.data());
        attr = gName.create_attribute("p2", h5cpp::dtype::Double, dspace);
        attr.write(surf.b.data());
    }

    void surface_monitor::update() {
        //*** this dir, Hfield combo is bad design (maybe use enum)
        auto isurf = F->grid.to_grid(surf);
        auto *Hfield = isurf.dim[0] == 0 ? &F->Hy : &F->Hx;

        double E = 0;
        double H = 0;
        freq.update(F->t);

        int i = 0;
        for (ivec p = isurf.a; p != isurf.b; p += isurf.tangent) {
            H = ((*Hfield)(p)+ (*Hfield)(p - isurf.normal)
                    + (*Hfield)(p + isurf.tangent) + (*Hfield)(p - isurf.normal + isurf.tangent))/4;
            E = (F->Ez(p) + F->Ez(p + isurf.tangent)
                    + prevE(i) + prevE(i+1))/4;

            prevE(i) = F->Ez(p);

            for (int j = 0; j != freq.size(); j++) {
                rE(i,j) += E*freq.get_cosf(j);
                iE(i,j) += E*freq.get_sinf(j);
                rH(i,j) += H*freq.get_cosf(j);
                iH(i,j) += H*freq.get_sinf(j);
            }
            i += 1;
        }
        prevE(length) = F->Ez(isurf.b);
    }

    Eigen::ArrayXd surface_monitor::compute_flux() const {
        Eigen::ArrayXd S = Eigen::ArrayXd::Zero(freq.size());

        for (int j = 0; j != freq.size(); j++) {
            for (int i = 0; i != length; i++) {
                S[j] += rE(i,j)*rH(i,j) + iE(i,j)*iH(i,j);
            }
        }
        S *= F->dx;
        return S;
    }

    void surface_monitor::write_flux() {
        auto S = compute_flux();
        auto gName = get_group();

        h5cpp::h5dset dset;
        if (!gName.object_exists("flux")) {
            vector<hsize_t> dims = {hsize_t(freq.size())};
            vector<hsize_t> max_dims = {hsize_t(freq.size())};
            if (!extendable) {
                h5cpp::dspace ds(dims, max_dims);
                dset = gName.create_dataset("flux",
                             h5cpp::dtype::Double, ds);
            }
            else {
                dims.push_back(1);
                max_dims.push_back(h5cpp::inf);
                vector<hsize_t> chunk_dims = dims;
                h5cpp::dspace ds(dims, max_dims, chunk_dims);
                dset = gName.create_dataset("flux",
                             h5cpp::dtype::Double, ds);
            }
            dset.write(S.data());
        }
        else {
            dset = gName.open_dataset("flux");
            dset.append(S.data());
        }
    }
}

<|endoftext|>