<commit_before>/* $Id$ */
# ifndef CPPAD_ASSERT_INCLUDED
# define CPPAD_ASSERT_INCLUDED

/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-11 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Common Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */

/*!
\file cppad_assert.hpp
Define the CppAD error checking macros (all of which begin with CPPAD_ASSERT_)
*/

/*
-------------------------------------------------------------------------------
$begin cppad_assert$$
$spell
	CppAD
	exp
	const
	bool
$$

$index assert, error macro $$
$index error, assert macro$$
$index macro, error assert$$

$section CppAD Assertions During Execution$$

$head Syntax$$
$codei%CPPAD_ASSERT_KNOWN(%exp%, %msg%)
%$$
$codei%CPPAD_ASSERT_UNKNOWN(%exp%)%$$

$head Purpose$$
If the preprocessor symbol $code NDEBUG/$$ is not defined,
these CppAD macros are used to detect and report errors.
They are documented here because they correspond to the C++
source code that the error is reported at.

$head Restriction$$
The CppAD user should not uses these macros.
You can however write your own macros that do not begin with $code CPPAD$$
and that call the $cref/CppAD error handler/ErrorHandler/$$.

$subhead Known$$
$index CPPAD_ASSERT_KNOWN$$
The $code CPPAD_ASSERT_KNOWN$$ macro is used to check for an error
with a known cause.
For example, many CppAD routines uses these macros
to make sure their arguments conform to their specifications.

$subhead Unknown$$
$index CPPAD_ASSERT_UNKNOWN$$
The $code CPPAD_ASSERT_UNKNOWN$$ macro is used to check that the
CppAD internal data structures conform as expected.
If this is not the case, CppAD does not know why the error has
occurred; for example, the user may have written past the end
of an allocated array.

$head Exp$$
The argument $icode exp$$ is a C++ source code expression
that results in a $code bool$$ value that should be true.
If it is false, an error has occurred.
This expression may be execute any number of times
(including zero times) so it must have not side effects.

$head Msg$$
The argument $icode msg$$ has prototype
$codei%
	const char *%msg%
%$$
and contains a $code '\0'$$ terminated character string.
This string is a description of the error
corresponding to $icode exp$$ being false.

$head Error Handler$$
These macros use the
$cref/CppAD error handler/ErrorHandler/$$ to report errors.
This error handler can be replaced by the user.

$end
------------------------------------------------------------------------------
*/

# include <cassert>
# include <iostream>
# include <cppad/error_handler.hpp>

/*!
\def CPPAD_ASSERT_KNOWN(exp, msg)
Check that \a exp is true, if not print \a msg and terminate execution.

The C++ expression \a exp is expected to be true.
If it is false,
the CppAD use has made an error that is described by \a msg.
If the preprocessor symbol \a NDEBUG is not defined,
and \a exp is false,
this macro will report the source code line number at
which this expected result occurred.
In addition, it will print the specified error message \a msg.
*/
# ifdef NDEBUG
# define CPPAD_ASSERT_KNOWN(exp, msg)  // do nothing
# else
# define CPPAD_ASSERT_KNOWN(exp, msg)           \
{	if( ! ( exp ) )                         \
	CppAD::ErrorHandler::Call(              \
		true       ,                    \
		__LINE__   ,                    \
 		__FILE__   ,                    \
		#exp       ,                    \
		msg        );                   \
}
# endif

/*!
\def CPPAD_ASSERT_UNKNOWN(exp)
Check that \a exp is true, if not terminate execution.

The C++ expression \a exp is expected to be true.
If it is false,
CppAD has detected an error but does not know the cause of the error.
If the preprocessor symbol \a NDEBUG is not defined,
and \a exp is false,
this macro will report the source code line number at
which this expected result occurred.
*/
# ifdef NDEBUG
# define CPPAD_ASSERT_UNKNOWN(exp)      // do nothing
# else
# define CPPAD_ASSERT_UNKNOWN(exp)              \
{	if( ! ( exp ) )                         \
	CppAD::ErrorHandler::Call(              \
		false      ,                    \
		__LINE__   ,                    \
 		__FILE__   ,                    \
		#exp       ,                    \
		""         );                   \
}
# endif

/*!
\def CPPAD_ASSERT_NARG_NRES(op, n_arg, n_res)
Check that operator \a op has the specified number of of arguments and results.

If \a NDEBUG is not defined and either the number of arguments
or the number of results are not as expected,
execution is terminated and the source code line number is reported.
*/
# define CPPAD_ASSERT_NARG_NRES(op, n_arg, n_res)   \
	CPPAD_ASSERT_UNKNOWN( NumArg(op) == n_arg ) \
	CPPAD_ASSERT_UNKNOWN( NumRes(op) == n_res )

/*!
\def CPPAD_ASSERT_FIRST_CALL_NOT_PARALLEL
Check that the first call to a routine is not during OpenMP parallel execution
mode.

If \c NDEBUG is defined, this macro has no effect
(not even the definition of (\c assert_first_call).
Otherwise, the variable
\code
	static bool assert_first_call
\endcode
is defined and if the first call is executed in OpenMP parallel mode,
execution is terminated and the source code line number is reported.
*/
# ifdef NDEBUG
# define CPPAD_ASSERT_FIRST_CALL_NOT_PARALLEL
# else
# define CPPAD_ASSERT_FIRST_CALL_NOT_PARALLEL                 \
	static bool assert_first_call = true;                    \
	CPPAD_ASSERT_KNOWN(                                      \
		! (omp_alloc::in_parallel() && assert_first_call ), \
		"First call to this routine is in parallel mode."   \
	);                                                       \
	assert_first_call = false;
# endif

# endif
<commit_msg>Missing from previous commit.<commit_after>/* $Id$ */
# ifndef CPPAD_ASSERT_INCLUDED
# define CPPAD_ASSERT_INCLUDED

/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-11 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Common Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */

/*!
\file cppad_assert.hpp
Define the CppAD error checking macros (all of which begin with CPPAD_ASSERT_)
*/

/*
-------------------------------------------------------------------------------
$begin cppad_assert$$
$spell
	CppAD
	exp
	const
	bool
$$

$index assert, error macro $$
$index error, assert macro$$
$index macro, error assert$$

$section CppAD Assertions During Execution$$

$head Syntax$$
$codei%CPPAD_ASSERT_KNOWN(%exp%, %msg%)
%$$
$codei%CPPAD_ASSERT_UNKNOWN(%exp%)%$$

$head Purpose$$
If the preprocessor symbol $code NDEBUG/$$ is not defined,
these CppAD macros are used to detect and report errors.
They are documented here because they correspond to the C++
source code that the error is reported at.

$head Restriction$$
The CppAD user should not uses these macros.
You can however write your own macros that do not begin with $code CPPAD$$
and that call the $cref/CppAD error handler/ErrorHandler/$$.

$subhead Known$$
$index CPPAD_ASSERT_KNOWN$$
The $code CPPAD_ASSERT_KNOWN$$ macro is used to check for an error
with a known cause.
For example, many CppAD routines uses these macros
to make sure their arguments conform to their specifications.

$subhead Unknown$$
$index CPPAD_ASSERT_UNKNOWN$$
The $code CPPAD_ASSERT_UNKNOWN$$ macro is used to check that the
CppAD internal data structures conform as expected.
If this is not the case, CppAD does not know why the error has
occurred; for example, the user may have written past the end
of an allocated array.

$head Exp$$
The argument $icode exp$$ is a C++ source code expression
that results in a $code bool$$ value that should be true.
If it is false, an error has occurred.
This expression may be execute any number of times
(including zero times) so it must have not side effects.

$head Msg$$
The argument $icode msg$$ has prototype
$codei%
	const char *%msg%
%$$
and contains a $code '\0'$$ terminated character string.
This string is a description of the error
corresponding to $icode exp$$ being false.

$head Error Handler$$
These macros use the
$cref/CppAD error handler/ErrorHandler/$$ to report errors.
This error handler can be replaced by the user.

$end
------------------------------------------------------------------------------
*/

# include <cassert>
# include <iostream>
# include <cppad/error_handler.hpp>

# ifdef _OPENMP
# include <omp.h>
# endif

/*!
\def CPPAD_ASSERT_KNOWN(exp, msg)
Check that \a exp is true, if not print \a msg and terminate execution.

The C++ expression \a exp is expected to be true.
If it is false,
the CppAD use has made an error that is described by \a msg.
If the preprocessor symbol \a NDEBUG is not defined,
and \a exp is false,
this macro will report the source code line number at
which this expected result occurred.
In addition, it will print the specified error message \a msg.
*/
# ifdef NDEBUG
# define CPPAD_ASSERT_KNOWN(exp, msg)  // do nothing
# else
# define CPPAD_ASSERT_KNOWN(exp, msg)           \
{	if( ! ( exp ) )                         \
	CppAD::ErrorHandler::Call(              \
		true       ,                    \
		__LINE__   ,                    \
 		__FILE__   ,                    \
		#exp       ,                    \
		msg        );                   \
}
# endif

/*!
\def CPPAD_ASSERT_UNKNOWN(exp)
Check that \a exp is true, if not terminate execution.

The C++ expression \a exp is expected to be true.
If it is false,
CppAD has detected an error but does not know the cause of the error.
If the preprocessor symbol \a NDEBUG is not defined,
and \a exp is false,
this macro will report the source code line number at
which this expected result occurred.
*/
# ifdef NDEBUG
# define CPPAD_ASSERT_UNKNOWN(exp)      // do nothing
# else
# define CPPAD_ASSERT_UNKNOWN(exp)              \
{	if( ! ( exp ) )                         \
	CppAD::ErrorHandler::Call(              \
		false      ,                    \
		__LINE__   ,                    \
 		__FILE__   ,                    \
		#exp       ,                    \
		""         );                   \
}
# endif

/*!
\def CPPAD_ASSERT_NARG_NRES(op, n_arg, n_res)
Check that operator \a op has the specified number of of arguments and results.

If \a NDEBUG is not defined and either the number of arguments
or the number of results are not as expected,
execution is terminated and the source code line number is reported.
*/
# define CPPAD_ASSERT_NARG_NRES(op, n_arg, n_res)   \
	CPPAD_ASSERT_UNKNOWN( NumArg(op) == n_arg ) \
	CPPAD_ASSERT_UNKNOWN( NumRes(op) == n_res )

/*!
\def CPPAD_ASSERT_FIRST_CALL_NOT_PARALLEL
Check that the first call to a routine is not during OpenMP parallel execution
mode.

If \c NDEBUG is defined, this macro has no effect
(not even the definition of (\c assert_first_call).
Otherwise, the variable
\code
	static bool assert_first_call
\endcode
is defined and if the first call is executed in OpenMP parallel mode,
execution is terminated and the source code line number is reported.
*/
# ifdef NDEBUG
# define CPPAD_ASSERT_FIRST_CALL_NOT_PARALLEL
# else
# ifndef _OPENMP
# define CPPAD_ASSERT_FIRST_CALL_NOT_PARALLEL
# else
# define CPPAD_ASSERT_FIRST_CALL_NOT_PARALLEL                 \
	static bool assert_first_call = true;                    \
	CPPAD_ASSERT_KNOWN(                                      \
		! (omp_in_parallel() && assert_first_call ),        \
		"First call to this routine is in parallel mode."   \
	);                                                       \
	assert_first_call = false;
# endif  // _OPENMP
# endif  // _NDEBUG

# endif
<|endoftext|>


<commit_before>#include <cassert>
#include "PermutationScorer.h"

using namespace std;

namespace MosesTuning
{

const int PermutationScorer::SCORE_PRECISION = 5;
const int PermutationScorer::SCORE_MULTFACT = 100000; // 100000=10^SCORE_PRECISION

PermutationScorer::PermutationScorer(const string &distanceMetric, const string &config)
  :StatisticsBasedScorer(distanceMetric,config)
{
  //configure regularisation

  static string KEY_REFCHOICE = "refchoice";
  static string REFCHOICE_AVERAGE = "average";
  static string REFCHOICE_CLOSEST = "closest";

  string refchoice = getConfig(KEY_REFCHOICE,REFCHOICE_CLOSEST);
  if (refchoice == REFCHOICE_AVERAGE) {
    m_refChoiceStrategy = REFERENCE_CHOICE_AVERAGE;
  } else if (refchoice == REFCHOICE_CLOSEST) {
    m_refChoiceStrategy = REFERENCE_CHOICE_CLOSEST;
  } else {
    throw runtime_error("Unknown reference choice strategy: " + refchoice);
  }
  cerr << "Using reference choice strategy: " << refchoice << endl;

  if (distanceMetric.compare("HAMMING") == 0) {
    m_distanceMetric = HAMMING_DISTANCE;
  } else if (distanceMetric.compare("KENDALL") == 0) {
    m_distanceMetric = KENDALL_DISTANCE;
  }
  cerr << "Using permutation distance metric: " << distanceMetric << endl;

  //Get reference alignments from scconfig refalign option
  static string KEY_ALIGNMENT_FILES = "refalign";
  string refalign = getConfig(KEY_ALIGNMENT_FILES,"");
  //cout << refalign << endl;
  if (refalign.length() > 0) {
    string substring;
    while (!refalign.empty()) {
      getNextPound(refalign, substring, "+");
      m_referenceAlignments.push_back(substring);
    }
  }

  //Get length of source sentences read in from scconfig source option
  // this is essential for extractor but unneccesary for mert executable
  static string KEY_SOURCE_FILE = "source";
  string sourceFile = getConfig(KEY_SOURCE_FILE,"");
  if (sourceFile.length() > 0) {
    cerr << "Loading source sentence lengths from " << sourceFile << endl;
    ifstream sourcein(sourceFile.c_str());
    if (!sourcein) {
      throw runtime_error("Unable to open: " + sourceFile);
    }
    string line;
    while (getline(sourcein,line)) {
      size_t wordNumber = 0;
      string word;
      while(!line.empty()) {
        getNextPound(line, word, " ");
        wordNumber++;
      }
      m_sourceLengths.push_back(wordNumber);
    }
    sourcein.close();
  }
}

void PermutationScorer::setReferenceFiles(const vector<string>& referenceFiles)
{
  cout << "*******setReferenceFiles" << endl;
  //make sure reference data is clear
  m_referencePerms.clear();

  vector< vector< int> > targetLengths;
  //Just getting target length from reference text file
  for (size_t i = 0; i < referenceFiles.size(); ++i) {
    vector <int> lengths;
    cout << "Loading reference from " << referenceFiles[i] << endl;
    ifstream refin(referenceFiles[i].c_str());
    if (!refin) {
      cerr << "Unable to open: " << referenceFiles[i] << endl;
      throw runtime_error("Unable to open alignment file");
    }
    string line;
    while (getline(refin,line)) {
      int count = getNumberWords(line);
      lengths.push_back(count);
    }
    targetLengths.push_back(lengths);
  }

  //load reference data
  //NOTE ignoring normal reference file, only using previously saved alignment reference files
  for (size_t i = 0; i < m_referenceAlignments.size(); ++i) {
    vector<Permutation> referencePerms;
    cout << "Loading reference from " << m_referenceAlignments[i] << endl;
    ifstream refin(m_referenceAlignments[i].c_str());
    if (!refin) {
      cerr << "Unable to open: " << m_referenceAlignments[i] << endl;
      throw runtime_error("Unable to open alignment file");
    }
    string line;
    size_t sid = 0; //sentence counter
    while (getline(refin,line)) {
      //cout << line << endl;

      //Line needs to be of the format: 0-0 1-1 1-2 etc source-target
      Permutation perm(line, m_sourceLengths[sid],targetLengths[i][sid]);
      //perm.dump();
      referencePerms.push_back(perm);
      //check the source sentence length is the same for previous file
      if (perm.getLength() !=  m_sourceLengths[sid]) {
        cerr << "Permutation Length: " << perm.getLength() << endl;
        cerr << "Source length: " << m_sourceLengths[sid] << " for sid " << sid << endl;
        throw runtime_error("Source sentence lengths not the same: ");
      }

      sid++;
    }
    m_referencePerms.push_back(referencePerms);
  }
}

int PermutationScorer::getNumberWords (const string& text) const
{
  int count = 0;
  string line = trimStr(text);
  if (line.length()>0) {
    int pos = line.find(" ");
    while (pos!=int(string::npos)) {
      count++;
      pos = line.find(" ",pos+1);
    }
    count++;
  }
  return count;
}

void PermutationScorer::prepareStats(size_t sid, const string& text, ScoreStats& entry)
{
  //bool debug= (verboselevel()>3); // TODO: fix verboselevel()
  bool debug=false;
  if (debug) {
    cout << "*******prepareStats" ;
    cout << text << endl;
    cout << sid << endl;
    cout << "Reference0align:" << endl;
    m_referencePerms[0][sid].dump();
  }

  string sentence = "";
  string align = text;
  size_t alignmentData = text.find("|||");
  //Get sentence and alignment parts
  if(alignmentData != string::npos) {
    getNextPound(align,sentence, "|||");
  } else {
    align = text;
  }
  int translationLength = getNumberWords(sentence);

  //A vector of Permutations for each sentence
  vector< vector<Permutation> > nBestPerms;
  float distanceValue;

  //need to create permutations for each nbest line
  //here we check if the alignments extracted from the nbest are phrase-based or word-based, in which case no conversion is needed
  bool isWordAlignment=true;
  string alignCopy = align;
  string align1;
  getNextPound(alignCopy,align1," ");
  if (align1.length() > 0) {
    size_t phraseDelimeter = align1.find("=");
    if(phraseDelimeter!= string::npos)
      isWordAlignment=false;
  }
  string standardFormat = align;
  if(!isWordAlignment)
    standardFormat= Permutation::convertMosesToStandard(align);

  if (debug) {
    cerr << "Nbest alignment:  " << align << endl;
    cerr << "-->std alignment: " << standardFormat << endl;
  }

  Permutation perm(standardFormat, m_sourceLengths[sid],translationLength);
  //perm.dump();

  if (m_refChoiceStrategy == REFERENCE_CHOICE_AVERAGE) {
    float total = 0;
    for (size_t i = 0; i < m_referencePerms.size(); ++i) {
      float dist = perm.distance(m_referencePerms[i][sid], m_distanceMetric);
      total += dist;
      //cout << "Ref number: " << i << " distance: " << dist << endl;
    }
    float mean = (float)total/m_referencePerms.size();
    //cout << "MultRef strategy AVERAGE: total " << total << " mean " << mean << " number " << m_referencePerms.size() << endl;
    distanceValue = mean;
  } else if (m_refChoiceStrategy == REFERENCE_CHOICE_CLOSEST)  {
    float max_val = 0;

    for (size_t i = 0; i < m_referencePerms.size(); ++i) {
      //look for the closest reference
      float value = perm.distance(m_referencePerms[i][sid], m_distanceMetric);
      //cout << "Ref number: " << i << " distance: " << value << endl;
      if (value > max_val) {
        max_val = value;
      }
    }
    distanceValue = max_val;
    //cout << "MultRef strategy CLOSEST: max_val " << distanceValue << endl;
  } else {
    throw runtime_error("Unsupported reflength strategy");
  }

  //SCOREROUT eg: 0.04546
  distanceValue*=SCORE_MULTFACT; //SCOREROUT eg: 4546 to transform float into integer
  ostringstream tempStream;
  tempStream.precision(SCORE_PRECISION);
  tempStream << distanceValue << " 1"; //use for final normalization over the amount of test sentences
  string str = tempStream.str();
  entry.set(str);

  //cout << tempStream.str();
}

//Will just be final score
statscore_t PermutationScorer::calculateScore(const vector<int>& comps) const
{
  //cerr << "*******PermutationScorer::calculateScore" ;
  //cerr << " " << comps[0]/comps[1] << endl;
  return (((statscore_t) comps[0]) / comps[1]) / SCORE_MULTFACT;
}

}

<commit_msg>fixed bug in permutation scores due to scientific notation<commit_after>#include <cassert>
#include "PermutationScorer.h"

using namespace std;

namespace MosesTuning
{

const int PermutationScorer::SCORE_PRECISION = 5;
const int PermutationScorer::SCORE_MULTFACT = 100000; // 100000=10^SCORE_PRECISION

PermutationScorer::PermutationScorer(const string &distanceMetric, const string &config)
  :StatisticsBasedScorer(distanceMetric,config)
{
  //configure regularisation

  static string KEY_REFCHOICE = "refchoice";
  static string REFCHOICE_AVERAGE = "average";
  static string REFCHOICE_CLOSEST = "closest";

  string refchoice = getConfig(KEY_REFCHOICE,REFCHOICE_CLOSEST);
  if (refchoice == REFCHOICE_AVERAGE) {
    m_refChoiceStrategy = REFERENCE_CHOICE_AVERAGE;
  } else if (refchoice == REFCHOICE_CLOSEST) {
    m_refChoiceStrategy = REFERENCE_CHOICE_CLOSEST;
  } else {
    throw runtime_error("Unknown reference choice strategy: " + refchoice);
  }
  cerr << "Using reference choice strategy: " << refchoice << endl;

  if (distanceMetric.compare("HAMMING") == 0) {
    m_distanceMetric = HAMMING_DISTANCE;
  } else if (distanceMetric.compare("KENDALL") == 0) {
    m_distanceMetric = KENDALL_DISTANCE;
  }
  cerr << "Using permutation distance metric: " << distanceMetric << endl;

  //Get reference alignments from scconfig refalign option
  static string KEY_ALIGNMENT_FILES = "refalign";
  string refalign = getConfig(KEY_ALIGNMENT_FILES,"");
  //cout << refalign << endl;
  if (refalign.length() > 0) {
    string substring;
    while (!refalign.empty()) {
      getNextPound(refalign, substring, "+");
      m_referenceAlignments.push_back(substring);
    }
  }

  //Get length of source sentences read in from scconfig source option
  // this is essential for extractor but unneccesary for mert executable
  static string KEY_SOURCE_FILE = "source";
  string sourceFile = getConfig(KEY_SOURCE_FILE,"");
  if (sourceFile.length() > 0) {
    cerr << "Loading source sentence lengths from " << sourceFile << endl;
    ifstream sourcein(sourceFile.c_str());
    if (!sourcein) {
      throw runtime_error("Unable to open: " + sourceFile);
    }
    string line;
    while (getline(sourcein,line)) {
      size_t wordNumber = 0;
      string word;
      while(!line.empty()) {
        getNextPound(line, word, " ");
        wordNumber++;
      }
      m_sourceLengths.push_back(wordNumber);
    }
    sourcein.close();
  }
}

void PermutationScorer::setReferenceFiles(const vector<string>& referenceFiles)
{
  cout << "*******setReferenceFiles" << endl;
  //make sure reference data is clear
  m_referencePerms.clear();

  vector< vector< int> > targetLengths;
  //Just getting target length from reference text file
  for (size_t i = 0; i < referenceFiles.size(); ++i) {
    vector <int> lengths;
    cout << "Loading reference from " << referenceFiles[i] << endl;
    ifstream refin(referenceFiles[i].c_str());
    if (!refin) {
      cerr << "Unable to open: " << referenceFiles[i] << endl;
      throw runtime_error("Unable to open alignment file");
    }
    string line;
    while (getline(refin,line)) {
      int count = getNumberWords(line);
      lengths.push_back(count);
    }
    targetLengths.push_back(lengths);
  }

  //load reference data
  //NOTE ignoring normal reference file, only using previously saved alignment reference files
  for (size_t i = 0; i < m_referenceAlignments.size(); ++i) {
    vector<Permutation> referencePerms;
    cout << "Loading reference from " << m_referenceAlignments[i] << endl;
    ifstream refin(m_referenceAlignments[i].c_str());
    if (!refin) {
      cerr << "Unable to open: " << m_referenceAlignments[i] << endl;
      throw runtime_error("Unable to open alignment file");
    }
    string line;
    size_t sid = 0; //sentence counter
    while (getline(refin,line)) {
      //cout << line << endl;

      //Line needs to be of the format: 0-0 1-1 1-2 etc source-target
      Permutation perm(line, m_sourceLengths[sid],targetLengths[i][sid]);
      //perm.dump();
      referencePerms.push_back(perm);
      //check the source sentence length is the same for previous file
      if (perm.getLength() !=  m_sourceLengths[sid]) {
        cerr << "Permutation Length: " << perm.getLength() << endl;
        cerr << "Source length: " << m_sourceLengths[sid] << " for sid " << sid << endl;
        throw runtime_error("Source sentence lengths not the same: ");
      }

      sid++;
    }
    m_referencePerms.push_back(referencePerms);
  }
}

int PermutationScorer::getNumberWords (const string& text) const
{
  int count = 0;
  string line = trimStr(text);
  if (line.length()>0) {
    int pos = line.find(" ");
    while (pos!=int(string::npos)) {
      count++;
      pos = line.find(" ",pos+1);
    }
    count++;
  }
  return count;
}

void PermutationScorer::prepareStats(size_t sid, const string& text, ScoreStats& entry)
{
  //bool debug= (verboselevel()>3); // TODO: fix verboselevel()
  bool debug=false;
  if (debug) {
    cout << "*******prepareStats" ;
    cout << text << endl;
    cout << sid << endl;
    cout << "Reference0align:" << endl;
    m_referencePerms[0][sid].dump();
  }

  string sentence = "";
  string align = text;
  size_t alignmentData = text.find("|||");
  //Get sentence and alignment parts
  if(alignmentData != string::npos) {
    getNextPound(align,sentence, "|||");
  } else {
    align = text;
  }
  int translationLength = getNumberWords(sentence);

  //A vector of Permutations for each sentence
  vector< vector<Permutation> > nBestPerms;
  float distanceValue;

  //need to create permutations for each nbest line
  //here we check if the alignments extracted from the nbest are phrase-based or word-based, in which case no conversion is needed
  bool isWordAlignment=true;
  string alignCopy = align;
  string align1;
  getNextPound(alignCopy,align1," ");
  if (align1.length() > 0) {
    size_t phraseDelimeter = align1.find("=");
    if(phraseDelimeter!= string::npos)
      isWordAlignment=false;
  }
  string standardFormat = align;
  if(!isWordAlignment)
    standardFormat= Permutation::convertMosesToStandard(align);

  if (debug) {
    cerr << "Nbest alignment:  " << align << endl;
    cerr << "-->std alignment: " << standardFormat << endl;
  }

  Permutation perm(standardFormat, m_sourceLengths[sid],translationLength);
  //perm.dump();

  if (m_refChoiceStrategy == REFERENCE_CHOICE_AVERAGE) {
    float total = 0;
    for (size_t i = 0; i < m_referencePerms.size(); ++i) {
      float dist = perm.distance(m_referencePerms[i][sid], m_distanceMetric);
      total += dist;
      //cout << "Ref number: " << i << " distance: " << dist << endl;
    }
    float mean = (float)total/m_referencePerms.size();
    //cout << "MultRef strategy AVERAGE: total " << total << " mean " << mean << " number " << m_referencePerms.size() << endl;
    distanceValue = mean;
  } else if (m_refChoiceStrategy == REFERENCE_CHOICE_CLOSEST)  {
    float max_val = 0;

    for (size_t i = 0; i < m_referencePerms.size(); ++i) {
      //look for the closest reference
      float value = perm.distance(m_referencePerms[i][sid], m_distanceMetric);
      //cout << "Ref number: " << i << " distance: " << value << endl;
      if (value > max_val) {
        max_val = value;
      }
    }
    distanceValue = max_val;
    //cout << "MultRef strategy CLOSEST: max_val " << distanceValue << endl;
  } else {
    throw runtime_error("Unsupported reflength strategy");
  }

  //SCOREROUT eg: 0.04546
  distanceValue*=SCORE_MULTFACT; //SCOREROUT eg: 4546 to transform float into integer
  ostringstream tempStream;
  tempStream.precision(0);	// decimal precision not needed as score was multiplied per SCORE_MULTFACT
  tempStream << std::fixed << distanceValue << " 1"; //use for final normalization over the amount of test sentences
  string str = tempStream.str();
  entry.set(str);

//cout << distanceValue << "=" << distanceValue << " (str:" << tempStream.str() << ")" << endl;
}

//Will just be final score
statscore_t PermutationScorer::calculateScore(const vector<int>& comps) const
{
  //cerr << "*******PermutationScorer::calculateScore" ;
  //cerr << " " << comps[0]/comps[1] << endl;
  return (((statscore_t) comps[0]) / comps[1]) / SCORE_MULTFACT;
}

}

<|endoftext|>


<commit_before>/*
 * DISTRHO Plugin Framework (DPF)
 * Copyright (C) 2012-2016 Filipe Coelho <falktx@falktx.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any purpose with
 * or without fee is hereby granted, provided that the above copyright notice and this
 * permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
 * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
 * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#ifndef DGL_WIDGET_PRIVATE_DATA_HPP_INCLUDED
#define DGL_WIDGET_PRIVATE_DATA_HPP_INCLUDED

#include "../Widget.hpp"
#include "../Window.hpp"

#include <vector>

START_NAMESPACE_DGL

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

struct Widget::PrivateData {
    Widget* const self;
    Window& parent;
    Point<int> absolutePos;
    Size<uint> size;
    std::vector<Widget*> subWidgets;

    uint id;
    bool needsFullViewport;
    bool needsScaling;
    bool skipDisplay;
    bool visible;

    PrivateData(Widget* const s, Window& p, Widget* groupWidget, bool addToSubWidgets)
        : self(s),
          parent(p),
          absolutePos(0, 0),
          size(0, 0),
          subWidgets(),
          id(0),
          needsFullViewport(false),
          needsScaling(false),
          skipDisplay(false),
          visible(true)
    {
        if (addToSubWidgets && groupWidget != nullptr)
        {
            skipDisplay = true;
            groupWidget->pData->subWidgets.push_back(self);
        }
    }

    ~PrivateData()
    {
        subWidgets.clear();
    }

    void display(const uint width, const uint height)
    {
        if (skipDisplay || ! visible)
            return;

        bool needsDisableScissor = false;

        // reset color
        glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

        if (needsFullViewport || (absolutePos.isZero() && size == Size<uint>(width, height)))
        {
            // full viewport size
            glViewport(0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height));
        }
        else if (needsScaling)
        {
            // limit viewport to widget bounds
            glViewport(absolutePos.getX(),
                       static_cast<int>(height - self->getHeight()) - absolutePos.getY(),
                       static_cast<GLsizei>(self->getWidth()),
                       static_cast<GLsizei>(self->getHeight()));
        }
        else
        {
            // only set viewport pos
            glViewport(absolutePos.getX(),
                       /*static_cast<int>(height - self->getHeight())*/ - absolutePos.getY(),
                       static_cast<GLsizei>(width),
                       static_cast<GLsizei>(height));

            // then cut the outer bounds
            glScissor(absolutePos.getX(),
                      static_cast<int>(height - self->getHeight()) - absolutePos.getY(),
                      static_cast<GLsizei>(self->getWidth()),
                      static_cast<GLsizei>(self->getHeight()));

            glEnable(GL_SCISSOR_TEST);
            needsDisableScissor = true;
        }

        // display widget
        self->onDisplay();

        if (needsDisableScissor)
        {
            glDisable(GL_SCISSOR_TEST);
            needsDisableScissor = false;
        }

        displaySubWidgets(width, height);
    }

    void displaySubWidgets(const uint width, const uint height)
    {
        for (std::vector<Widget*>::iterator it = subWidgets.begin(); it != subWidgets.end(); ++it)
        {
            Widget* const widget(*it);
            DISTRHO_SAFE_ASSERT_CONTINUE(widget->pData != this);

            widget->pData->display(width, height);
        }
    }

    DISTRHO_DECLARE_NON_COPY_STRUCT(PrivateData)
};

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

END_NAMESPACE_DGL

#endif // DGL_WIDGET_PRIVATE_DATA_HPP_INCLUDED
<commit_msg>Don't try to render widgets wth invalid size<commit_after>/*
 * DISTRHO Plugin Framework (DPF)
 * Copyright (C) 2012-2016 Filipe Coelho <falktx@falktx.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any purpose with
 * or without fee is hereby granted, provided that the above copyright notice and this
 * permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
 * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
 * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
 * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#ifndef DGL_WIDGET_PRIVATE_DATA_HPP_INCLUDED
#define DGL_WIDGET_PRIVATE_DATA_HPP_INCLUDED

#include "../Widget.hpp"
#include "../Window.hpp"

#include <vector>

START_NAMESPACE_DGL

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

struct Widget::PrivateData {
    Widget* const self;
    Window& parent;
    Point<int> absolutePos;
    Size<uint> size;
    std::vector<Widget*> subWidgets;

    uint id;
    bool needsFullViewport;
    bool needsScaling;
    bool skipDisplay;
    bool visible;

    PrivateData(Widget* const s, Window& p, Widget* groupWidget, bool addToSubWidgets)
        : self(s),
          parent(p),
          absolutePos(0, 0),
          size(0, 0),
          subWidgets(),
          id(0),
          needsFullViewport(false),
          needsScaling(false),
          skipDisplay(false),
          visible(true)
    {
        if (addToSubWidgets && groupWidget != nullptr)
        {
            skipDisplay = true;
            groupWidget->pData->subWidgets.push_back(self);
        }
    }

    ~PrivateData()
    {
        subWidgets.clear();
    }

    void display(const uint width, const uint height)
    {
        if (skipDisplay || size.isInvalid() || ! visible)
            return;

        bool needsDisableScissor = false;

        // reset color
        glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

        if (needsFullViewport || (absolutePos.isZero() && size == Size<uint>(width, height)))
        {
            // full viewport size
            glViewport(0, 0, static_cast<GLsizei>(width), static_cast<GLsizei>(height));
        }
        else if (needsScaling)
        {
            // limit viewport to widget bounds
            glViewport(absolutePos.getX(),
                       static_cast<int>(height - self->getHeight()) - absolutePos.getY(),
                       static_cast<GLsizei>(self->getWidth()),
                       static_cast<GLsizei>(self->getHeight()));
        }
        else
        {
            // only set viewport pos
            glViewport(absolutePos.getX(),
                       /*static_cast<int>(height - self->getHeight())*/ - absolutePos.getY(),
                       static_cast<GLsizei>(width),
                       static_cast<GLsizei>(height));

            // then cut the outer bounds
            glScissor(absolutePos.getX(),
                      static_cast<int>(height - self->getHeight()) - absolutePos.getY(),
                      static_cast<GLsizei>(self->getWidth()),
                      static_cast<GLsizei>(self->getHeight()));

            glEnable(GL_SCISSOR_TEST);
            needsDisableScissor = true;
        }

        // display widget
        self->onDisplay();

        if (needsDisableScissor)
        {
            glDisable(GL_SCISSOR_TEST);
            needsDisableScissor = false;
        }

        displaySubWidgets(width, height);
    }

    void displaySubWidgets(const uint width, const uint height)
    {
        for (std::vector<Widget*>::iterator it = subWidgets.begin(); it != subWidgets.end(); ++it)
        {
            Widget* const widget(*it);
            DISTRHO_SAFE_ASSERT_CONTINUE(widget->pData != this);

            widget->pData->display(width, height);
        }
    }

    DISTRHO_DECLARE_NON_COPY_STRUCT(PrivateData)
};

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

END_NAMESPACE_DGL

#endif // DGL_WIDGET_PRIVATE_DATA_HPP_INCLUDED
<|endoftext|>


<commit_before>#include "circuit.h"
#include <cassert>
#include <cmath>
#include <iostream>
#include <cstddef>
#include <iterator>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>

#include "utility.h"

using namespace std;

Circuit::Circuit(vector<bool> inputs, int o)
    : output_no(o), input_no(inputs.size()) {
  // initialize statistics to 0
  and_no = or_no = not_no = wire_no = 0;
  mapped_outputs = vector<int>(output_no, -1);
  // create initial input wires
  for (bool input : inputs) {
    wire_no++;
    std::string errmsg = "Circuit::Circuit: " + std::to_string(getGateCount()) +
                         " WIRE " + std::to_string(input);
    errlog(errmsg);

    Gate* wire = new Wire(input);
    gates.push_back(wire);

    // write wire to file
    writeGateToFile(*wire, getGateCount() - 1, " NONE ", input);
  }
}

Circuit::Circuit(int inputs, int o) : output_no(o), input_no(inputs) {
  // initialize statistics to 0
  and_no = or_no = not_no = wire_no = 0;
  mapped_outputs = vector<int>(output_no, -1);
  // create initial input wires
  for (int i = 0; i < input_no; ++i) {
    wire_no++;
    std::string errmsg = "Circuit::Circuit: " + std::to_string(getGateCount()) +
                         " WIRE " + std::to_string(i);
    errlog(errmsg);

    Gate* wire = new Wire(false);
    gates.push_back(wire);

    // write wire to file
    writeGateToFile(*wire, getGateCount() - 1, " NONE ", i);
  }
}

int Circuit::addGate(GateType gate_type, int index_1) {
  Gate* built_gate = nullptr;
  Gate* input_1 = gates[index_1];
  if (gate_type == NOT) {
    built_gate = new Not(input_1);
    // increment number of nots
    not_no++;
    std::string errmsg = "Circuit::addGate: " + std::to_string(gates.size()) +
                         " NOT  " + std::to_string(index_1);
    errlog(errmsg);

    // write wire to file
    writeGateToFile(*built_gate, getGateCount(), " NOT  ", index_1);
  } else if (gate_type == WIRE) {
    built_gate = new Wire(input_1);
    // increment number of wires
    wire_no++;
    std::string errmsg = "Circuit::addGate: " + std::to_string(gates.size()) +
                         " WIRE " + std::to_string(index_1);
    errlog(errmsg);

    // write wire to file
    writeGateToFile(*built_gate, getGateCount(), " NONE ", index_1);
  }
  assert(built_gate != nullptr);
  gates.push_back(built_gate);
  // gates is zero indexed
  return (gates.size() - 1);
}

int Circuit::addGate(int output_index, GateType gate_type, int index_1) {
  int actual_output_index = addGate(gate_type, index_1);
  assert(output_index == actual_output_index);
  return actual_output_index;
}

int Circuit::addGate(GateType gate_type, int index_1, int index_2) {
  Gate* built_gate = nullptr;
  Gate* input_1 = gates[index_1];
  Gate* input_2 = gates[index_2];
  if (gate_type == AND) {
    built_gate = new And(input_1, input_2);
    // increment number of ands
    and_no++;
    std::string errmsg = "Circuit::addGate: " + std::to_string(gates.size()) +
                         " AND  " + std::to_string(index_1) + " " +
                         std::to_string(index_2);
    errlog(errmsg);

    // write wire to file
    writeGateToFile(*built_gate, getGateCount(), " AND  ", index_1, index_2);
  } else if (gate_type == OR) {
    built_gate = new Or(input_1, input_2);
    // increment number of or
    or_no++;
    std::string errmsg = "Circuit::addGate: " + std::to_string(gates.size()) +
                         " OR   " + std::to_string(index_1) + " " +
                         std::to_string(index_2);
    errlog(errmsg);

    // write wire to file
    writeGateToFile(*built_gate, getGateCount(), " OR   ", index_1, index_2);
  }
  assert(built_gate != nullptr);
  gates.push_back(built_gate);
  // gates is zero indexed
  return (gates.size() - 1);
}

int Circuit::addGate(int output_index, GateType gate_type, int index_1,
                     int index_2) {
  int actual_output_index = addGate(gate_type, index_1, index_2);
  assert(output_index == actual_output_index);
  return actual_output_index;
}

vector<vector<bool>> Circuit::evaluateAllInputs() {
  printStatistics();
  vector<vector<bool>> inputs = generateInputSet();
  vector<vector<bool>> outputs;
  for (vector<bool> input : inputs) {
    outputs.push_back(evaluateInputSet(input));
  }
  assert(!outputs.empty());
  return outputs;
}

vector<bool> Circuit::evaluateInputSet(vector<bool> input_set) {
  printStatistics();
  // initalize input wires to input_set values
  for (int i = 0; i < input_no; ++i) {
    (dynamic_cast<Wire*>(gates[i]))->setInput(input_set[i]);

    std::string errmsg = "Circuit::evaluateInputSet: input_set[" +
                         std::to_string(i) + "] = " +
                         std::to_string(input_set[i]);
    errlog(errmsg);
  }

  vector<bool> result;
  // evaluate gates in reverse order, i.e. from input to output
  reverse_iterator<vector<Gate*>::iterator> r = gates.rbegin();
  for (int i = output_no - 1; i >= 0; --i) {
    Gate* output_gate =
        ((mapped_outputs[i] != -1) ? gates[mapped_outputs[i]] : r[i]);
    bool output = output_gate->evaluate();
    // gates_reversed = {2, 1, 0}
    // i = {2,1,0}
    // result  = { 0, 1, 2}
    result.push_back(output);

    std::string errmsg = "Circuit::evaluateInputSet: output[" +
                         std::to_string(i) + "] = " + std::to_string(output) +
                         "Current Mapped Output = [" +
                         std::to_string(mapped_outputs[i]) + "]";
    errlog(errmsg);
  }

  return result;
}

vector<vector<bool>> Circuit::generateInputSet() {
  vector<vector<bool>> inputset;

  // a truth table is input_no columns wide and 2^{input_no} rows tall
  for (int i = 0; i < pow(2, input_no); ++i) {
    std::string errmsg =
        "Circuit::generateInputSet: row[" + std::to_string(i) + "] = { ";

    vector<bool> row;
    for (int j = input_no - 1; j >= 0; --j) {
      int current_bit = (i >> j) & 1;
      row.push_back(current_bit);
      errmsg += std::to_string(current_bit) + " ";
    }
    errmsg += " }";
    errlog(errmsg);

    assert(row.size() == (unsigned int)input_no);
    inputset.push_back(row);
  }
  return inputset;
}

void Circuit::mapGateToOutput(int gate_index, int desired_output_index) {
  std::string errmsg = "Called with: [" + std::to_string(gate_index) + "] ";
  errlog(errmsg);
  int actual_output_index = output_no - 1 - desired_output_index;
  mapped_outputs[actual_output_index] = gate_index;
}

void Circuit::printStatistics() {
  std::string errmsg =
      "Circuit::printStatistics: WIREs = " + std::to_string(wire_no) +
      " ANDs = " + std::to_string(and_no) + " ORs = " + std::to_string(or_no) +
      " NOTs = " + std::to_string(not_no);
  errlog(errmsg);
}

// this is the function that should be used to print gates
void Circuit::writeGateToFile(const Gate& gate, int output_index,
                              std::string type, int input_index) {
  // Create filepath
  std::string directory = "";
  std::string filename = "eugenics.circuit";
  // std::string filepath = directory + filename;
  std::string filepath = filename;

  // Open filepath
  std::ofstream circuitfile(filepath, std::ios::app);

  // increment indexes
  output_index++;
  input_index++;

  // Write circuit to circuitfile
  circuitfile << output_index << " ";
  circuitfile << type;
  circuitfile << " " << input_index;
  circuitfile << std::endl;

    std::string errmsg = "Circuit::writeGateToFile: " + std::to_string(output_index) +
      type + std::to_string(input_index);
    errlog(errmsg);

  circuitfile.close();
}

void Circuit::writeGateToFile(const Gate& gate, int output_index,
                              std::string type, int input_index1, int input_index2) {
  // Create filepath
  std::string directory = "";
  std::string filename = "eugenics.circuit";
  // std::string filepath = directory + filename;
  std::string filepath = filename;

  // Open filepath
  std::ofstream circuitfile(filepath, std::ios::app);

  // increment indexes
  output_index++;
  input_index1++;
  input_index2++;

  // Write circuit to circuitfile
  circuitfile << output_index << " ";
  circuitfile << type;
  circuitfile << " " << input_index1;
  circuitfile << " " << input_index2;
  circuitfile << std::endl;

    std::string errmsg = "Circuit::writeGateToFile: " + std::to_string(output_index) +
      type + std::to_string(input_index1) + " " + std::to_string(input_index2);
    errlog(errmsg);

  circuitfile.close();
}

// std::ostream& operator<<(std::ostream& os, const Circuit& circuit) {
//
// }

// std::ifstream& operator>>(std::ifstream& is, Circuit& circuit) {

// }

// std::ofstream &operator<<(std::ofstream &os, const Circuit &circuit) {
//   for (Gate* gate : circuit.gates) {
//     gate->
//   }

// }
<commit_msg>fix wire/none problem<commit_after>#include "circuit.h"
#include <cassert>
#include <cmath>
#include <iostream>
#include <cstddef>
#include <iterator>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>

#include "utility.h"

using namespace std;

Circuit::Circuit(vector<bool> inputs, int o)
    : output_no(o), input_no(inputs.size()) {
  // initialize statistics to 0
  and_no = or_no = not_no = wire_no = 0;
  mapped_outputs = vector<int>(output_no, -1);
  // create initial input wires
  for (bool input : inputs) {
    wire_no++;
    std::string errmsg = "Circuit::Circuit: " + std::to_string(getGateCount()) +
                         " WIRE " + std::to_string(input);
    errlog(errmsg);

    Gate* wire = new Wire(input);
    gates.push_back(wire);

    // write wire to file
    writeGateToFile(*wire, getGateCount() - 1, " NONE ", input);
  }
}

Circuit::Circuit(int inputs, int o) : output_no(o), input_no(inputs) {
  // initialize statistics to 0
  and_no = or_no = not_no = wire_no = 0;
  mapped_outputs = vector<int>(output_no, -1);
  // create initial input wires
  for (int i = 0; i < input_no; ++i) {
    wire_no++;
    std::string errmsg = "Circuit::Circuit: " + std::to_string(getGateCount()) +
                         " WIRE " + std::to_string(i);
    errlog(errmsg);

    Gate* wire = new Wire(false);
    gates.push_back(wire);

    // write wire to file
    writeGateToFile(*wire, getGateCount() - 1, " NONE ", i);
  }
}

int Circuit::addGate(GateType gate_type, int index_1) {
  Gate* built_gate = nullptr;
  Gate* input_1 = gates[index_1];
  if (gate_type == NOT) {
    built_gate = new Not(input_1);
    // increment number of nots
    not_no++;
    std::string errmsg = "Circuit::addGate: " + std::to_string(gates.size()) +
                         " NOT  " + std::to_string(index_1);
    errlog(errmsg);

    // write wire to file
    writeGateToFile(*built_gate, getGateCount(), " NOT  ", index_1);
  } else if (gate_type == WIRE) {
    built_gate = new Wire(input_1);
    // increment number of wires
    wire_no++;
    std::string errmsg = "Circuit::addGate: " + std::to_string(gates.size()) +
                         " WIRE " + std::to_string(index_1);
    errlog(errmsg);

    // // write wire to file
    // writeGateToFile(*built_gate, getGateCount(), " NONE ", index_1);
  }
  assert(built_gate != nullptr);
  gates.push_back(built_gate);
  // gates is zero indexed
  return (gates.size() - 1);
}

int Circuit::addGate(int output_index, GateType gate_type, int index_1) {
  int actual_output_index = addGate(gate_type, index_1);
  assert(output_index == actual_output_index);
  return actual_output_index;
}

int Circuit::addGate(GateType gate_type, int index_1, int index_2) {
  Gate* built_gate = nullptr;
  Gate* input_1 = gates[index_1];
  Gate* input_2 = gates[index_2];
  if (gate_type == AND) {
    built_gate = new And(input_1, input_2);
    // increment number of ands
    and_no++;
    std::string errmsg = "Circuit::addGate: " + std::to_string(gates.size()) +
                         " AND  " + std::to_string(index_1) + " " +
                         std::to_string(index_2);
    errlog(errmsg);

    // write wire to file
    writeGateToFile(*built_gate, getGateCount(), " AND  ", index_1, index_2);
  } else if (gate_type == OR) {
    built_gate = new Or(input_1, input_2);
    // increment number of or
    or_no++;
    std::string errmsg = "Circuit::addGate: " + std::to_string(gates.size()) +
                         " OR   " + std::to_string(index_1) + " " +
                         std::to_string(index_2);
    errlog(errmsg);

    // write wire to file
    writeGateToFile(*built_gate, getGateCount(), " OR   ", index_1, index_2);
  }
  assert(built_gate != nullptr);
  gates.push_back(built_gate);
  // gates is zero indexed
  return (gates.size() - 1);
}

int Circuit::addGate(int output_index, GateType gate_type, int index_1,
                     int index_2) {
  int actual_output_index = addGate(gate_type, index_1, index_2);
  assert(output_index == actual_output_index);
  return actual_output_index;
}

vector<vector<bool>> Circuit::evaluateAllInputs() {
  printStatistics();
  vector<vector<bool>> inputs = generateInputSet();
  vector<vector<bool>> outputs;
  for (vector<bool> input : inputs) {
    outputs.push_back(evaluateInputSet(input));
  }
  assert(!outputs.empty());
  return outputs;
}

vector<bool> Circuit::evaluateInputSet(vector<bool> input_set) {
  printStatistics();
  // initalize input wires to input_set values
  for (int i = 0; i < input_no; ++i) {
    (dynamic_cast<Wire*>(gates[i]))->setInput(input_set[i]);

    std::string errmsg = "Circuit::evaluateInputSet: input_set[" +
                         std::to_string(i) + "] = " +
                         std::to_string(input_set[i]);
    errlog(errmsg);
  }

  vector<bool> result;
  // evaluate gates in reverse order, i.e. from input to output
  reverse_iterator<vector<Gate*>::iterator> r = gates.rbegin();
  for (int i = output_no - 1; i >= 0; --i) {
    Gate* output_gate =
        ((mapped_outputs[i] != -1) ? gates[mapped_outputs[i]] : r[i]);
    bool output = output_gate->evaluate();
    // gates_reversed = {2, 1, 0}
    // i = {2,1,0}
    // result  = { 0, 1, 2}
    result.push_back(output);

    std::string errmsg = "Circuit::evaluateInputSet: output[" +
                         std::to_string(i) + "] = " + std::to_string(output) +
                         "Current Mapped Output = [" +
                         std::to_string(mapped_outputs[i]) + "]";
    errlog(errmsg);
  }

  return result;
}

vector<vector<bool>> Circuit::generateInputSet() {
  vector<vector<bool>> inputset;

  // a truth table is input_no columns wide and 2^{input_no} rows tall
  for (int i = 0; i < pow(2, input_no); ++i) {
    std::string errmsg =
        "Circuit::generateInputSet: row[" + std::to_string(i) + "] = { ";

    vector<bool> row;
    for (int j = input_no - 1; j >= 0; --j) {
      int current_bit = (i >> j) & 1;
      row.push_back(current_bit);
      errmsg += std::to_string(current_bit) + " ";
    }
    errmsg += " }";
    errlog(errmsg);

    assert(row.size() == (unsigned int)input_no);
    inputset.push_back(row);
  }
  return inputset;
}

void Circuit::mapGateToOutput(int gate_index, int desired_output_index) {
  std::string errmsg = "Called with: [" + std::to_string(gate_index) + "] ";
  errlog(errmsg);
  int actual_output_index = output_no - 1 - desired_output_index;
  mapped_outputs[actual_output_index] = gate_index;
}

void Circuit::printStatistics() {
  std::string errmsg =
      "Circuit::printStatistics: WIREs = " + std::to_string(wire_no) +
      " ANDs = " + std::to_string(and_no) + " ORs = " + std::to_string(or_no) +
      " NOTs = " + std::to_string(not_no);
  errlog(errmsg);
}

// this is the function that should be used to print gates
void Circuit::writeGateToFile(const Gate& gate, int output_index,
                              std::string type, int input_index) {
  // Create filepath
  std::string directory = "";
  std::string filename = "eugenics.circuit";
  // std::string filepath = directory + filename;
  std::string filepath = filename;

  // Open filepath
  std::ofstream circuitfile(filepath, std::ios::app);

  // increment indexes
  output_index++;
  input_index++;

  // Write circuit to circuitfile
  circuitfile << output_index << " ";
  circuitfile << type;
  circuitfile << " " << input_index;
  circuitfile << std::endl;

    std::string errmsg = "Circuit::writeGateToFile: " + std::to_string(output_index) +
      type + std::to_string(input_index);
    errlog(errmsg);

  circuitfile.close();
}

void Circuit::writeGateToFile(const Gate& gate, int output_index,
                              std::string type, int input_index1, int input_index2) {
  // Create filepath
  std::string directory = "";
  std::string filename = "eugenics.circuit";
  // std::string filepath = directory + filename;
  std::string filepath = filename;

  // Open filepath
  std::ofstream circuitfile(filepath, std::ios::app);

  // increment indexes
  output_index++;
  input_index1++;
  input_index2++;

  // Write circuit to circuitfile
  circuitfile << output_index << " ";
  circuitfile << type;
  circuitfile << " " << input_index1;
  circuitfile << " " << input_index2;
  circuitfile << std::endl;

    std::string errmsg = "Circuit::writeGateToFile: " + std::to_string(output_index) +
      type + std::to_string(input_index1) + " " + std::to_string(input_index2);
    errlog(errmsg);

  circuitfile.close();
}

// std::ostream& operator<<(std::ostream& os, const Circuit& circuit) {
//
// }

// std::ifstream& operator>>(std::ifstream& is, Circuit& circuit) {

// }

// std::ofstream &operator<<(std::ofstream &os, const Circuit &circuit) {
//   for (Gate* gate : circuit.gates) {
//     gate->
//   }

// }
<|endoftext|>


<commit_before>// EventPrototype.cpp : Defines the entry point for the console application.
//

#include <string>
#include <map>
#include <vector>
#include <set>
#include <chrono>
#include <algorithm>
#include <atomic>
#include <thread>
//#include <omp.h>

#pragma region Helpers
double timeGetCurrentSeconds()
{
	long long v = std::chrono::high_resolution_clock::now().time_since_epoch().count();
	double dv = static_cast<double>(v);
	dv /= 1000000000.0;
	return dv;
}

#pragma endregion

// * EVENT SYSTEM
struct SEvent
{
	std::set<std::string> topics;
	void* payload = nullptr;
};

struct SEventConsumer;

typedef void(*SEventConsumerHandler)(const SEventConsumer*, const SEvent*);

struct SEventConsumer
{
	void* custom;
	std::set<std::string> topics;
	SEventConsumerHandler handler;

	bool operator < (const SEventConsumer& o) const
	{
		if(topics != o.topics)
			return topics < o.topics;
		return this < &o;
	}
};

bool operator < (const std::set<std::string>& a, const SEventConsumer& b)
{
	return a < b.topics;
}

bool operator < (const SEventConsumer& a, const std::set<std::string>& b)
{
	return a.topics < b;
}

struct SEventConsumerCache
{
	std::map<std::string, SEventConsumerCache> keyword;
	std::vector<int> leaf;
};

struct SEventState
{
	std::vector<SEventConsumer> consumers;

	// tag caches
	SEventConsumerCache cache;
};

int eventConsumerCreate(SEventState& state, const std::set<std::string>& topics, SEventConsumerHandler handler, void* custom=nullptr)
{
	SEventConsumer consumer;
	consumer.topics = topics;
	consumer.handler = handler;
	consumer.custom = custom;
	state.consumers.push_back(consumer);
	return -1;
}

void eventStateCompile(SEventState& state)
{
	int i = 0;
	for (auto& consumer : state.consumers)
	{
		SEventConsumerCache* current = &state.cache;
		for (auto& topic : consumer.topics)
		{
			current = &current->keyword[topic];
		}
		current->leaf.push_back(i++);
	}
}

// Slow O(n^2) version.
void eventEmit(SEventState& state, const SEvent& ev)
{
	for (auto it=state.consumers.begin(); it!=state.consumers.end(); it++)
	{
 		for (auto& topic : it->topics)
 		{
 			if (ev.topics.find(topic) == ev.topics.end())
 				goto skip_emit;
 		}

		it->handler(&(*it), &ev);
	skip_emit:
		0;
	}
}

// Fast but incorrect version. Doesn't work when tags don't match fully.
void eventEmitBtree(SEventState& state, const SEvent& ev)
{
	auto itBegin = std::lower_bound(state.consumers.begin(), state.consumers.end(), ev.topics);
	auto itEnd = std::upper_bound(state.consumers.begin(), state.consumers.end(), ev.topics);
	for (auto it = itBegin; it != itEnd; it++)
	{
		it->handler(&(*it), &ev);
	}
}

void eventEmitRecurtree(SEventState& state, const SEvent& ev)
{
	std::vector<int> consider;

	for (auto itKeywordBase = ev.topics.begin(); itKeywordBase != ev.topics.end(); itKeywordBase++)
	{
		auto itKeyword = itKeywordBase;
		SEventConsumerCache* current = &state.cache;
		while (itKeyword != ev.topics.end())
		{
			auto it = current->keyword.find(*(itKeyword++));
			if (it == current->keyword.end())
				continue; // chain ends here

			current = &(it->second);
			consider.insert(consider.end(), current->leaf.begin(), current->leaf.end());
		}
	}
	std::sort(consider.begin(), consider.end());
	int lastidx = -1;
	for (auto idx : consider)
	{
		if (idx == lastidx)
			continue;
		lastidx = idx;
		state.consumers[idx].handler(&state.consumers[idx], &ev);
	}
}

template< class T>
int testValidityPermutation(std::vector<std::set<std::string>> consumer, std::set<std::string> event, const T& emit)
{
	SEventState state;
	int numHits = 0;
	for (auto& it : consumer)
	{
		eventConsumerCreate(state, it, [](const SEventConsumer* consumer, const SEvent* ev) {
			int* v = ((int*)consumer->custom);
			(*v)++;
		}, &numHits);
	}
	eventStateCompile(state);
	SEvent e;
	e.topics = event;
	emit(state, e);
	return numHits;
}

template <class T>
bool testValidity(const T& eventFunc)
{
#define test(x) if((x) == false) { printf("Test failed: %s\n", #x); ret = false; } else { printf("Test succeeded: %s\n", #x); }
	printf("-------------------------\n");
	bool ret = true;
	test(testValidityPermutation({ { "hello" } }, { "hello" }, eventFunc) == 1);
	test(testValidityPermutation({ { "hello", "test" } }, { "hello" }, eventFunc) == 0);
	test(testValidityPermutation({ { "hello" } }, { "hello", "test" }, eventFunc) == 1);
	test(testValidityPermutation({ { "hello", "test" } }, { "hello", "test" }, eventFunc) == 1);
	test(testValidityPermutation({ { "hello", "baby", "bomb" } }, { "hello", "baby", "got", "an", "atom", "bomb" }, eventFunc) == 1);
	test(testValidityPermutation({ { "hello", "bomb", "baby" }, {"atom", "baby"} }, { "hello", "baby", "got", "an", "atom", "bomb" }, eventFunc) == 2);

	return ret;
#undef test
}

template <class T>
void testProfile(const T& eventFunc)
{
	printf("-------------------------\n");
	double timeElapsed;
	double timeConsumerCreateStart = timeGetCurrentSeconds();
	int numConsumerIds = 10000;
	int numConsumers = 10000;
	int numEvents = 100000;
	std::atomic<int> numHits = 0;
	SEventState state;

	// Setup consumer states.
	for (int i = 0; i < numConsumers; i++)
	{
		std::set<std::string> set;
		set.insert("type=log");

		int group = i % numConsumerIds;
		set.insert("id=" + std::to_string(group));
		eventConsumerCreate(state, set, [](const SEventConsumer* consumer, const SEvent* ev) {
			std::atomic<int>* v = ((std::atomic<int>*)consumer->custom);
			++(*v);
		}, &numHits);
	}
	printf("Profiler: Created consumers in %f seconds.\n", timeGetCurrentSeconds() - timeConsumerCreateStart);

	// Compile & optimize tree
	double timeConsumerOptimize = timeGetCurrentSeconds();
	eventStateCompile(state);
	printf("Profiler: Created optimized structure for consumers in %f seconds.\n", timeGetCurrentSeconds() - timeConsumerOptimize);

	// Start emitting events.
	double timeConsumerEventEmit = timeGetCurrentSeconds();

	//#pragma omp parallel for
	for (int i = 0; i < numEvents; i++)
	{
		SEvent e;
		e.topics.insert("type=log");
		e.topics.insert("id=100");
 		e.topics.insert("cat");
		eventFunc(state, e);
	}

	timeElapsed = timeGetCurrentSeconds() - timeConsumerEventEmit;
	printf("Profiler: Emitted (%d) events in %f seconds (events/sec: %f).\n", numEvents, timeElapsed, ((double)numEvents) / timeElapsed);
	printf("Num hits: %d\n", numHits.fetch_add(0));
}

int main()
{

	testValidityPermutation({ { "hello", "bomb", "baby" },{ "atom", "baby" } }, { "hello", "baby", "got", "an", "atom", "bomb" }, [](SEventState& state, SEvent& ev) { eventEmitRecurtree(state, ev); });

	testValidity([](SEventState& state, SEvent& ev) { eventEmit(state, ev); });
	testValidity([](SEventState& state, SEvent& ev) { eventEmitRecurtree(state, ev); });
	testProfile([](SEventState& state, SEvent& ev) { eventEmit(state, ev); });
	testProfile([](SEventState& state, SEvent& ev) { eventEmitRecurtree(state, ev); });

	//testProfile();
    return 0;
}

<commit_msg>Fixed case for recur tree where the set of filters is empty - all events should be routed to it then.<commit_after>// EventPrototype.cpp : Defines the entry point for the console application.
//

#include <string>
#include <map>
#include <vector>
#include <set>
#include <chrono>
#include <algorithm>
#include <atomic>
#include <thread>
//#include <omp.h>

#pragma region Helpers
double timeGetCurrentSeconds()
{
	long long v = std::chrono::high_resolution_clock::now().time_since_epoch().count();
	double dv = static_cast<double>(v);
	dv /= 1000000000.0;
	return dv;
}

#pragma endregion

// * EVENT SYSTEM
struct SEvent
{
	std::set<std::string> topics;
	void* payload = nullptr;
};

struct SEventConsumer;

typedef void(*SEventConsumerHandler)(const SEventConsumer*, const SEvent*);

struct SEventConsumer
{
	void* custom;
	std::set<std::string> topics;
	SEventConsumerHandler handler;

	bool operator < (const SEventConsumer& o) const
	{
		if(topics != o.topics)
			return topics < o.topics;
		return this < &o;
	}
};

bool operator < (const std::set<std::string>& a, const SEventConsumer& b)
{
	return a < b.topics;
}

bool operator < (const SEventConsumer& a, const std::set<std::string>& b)
{
	return a.topics < b;
}

struct SEventConsumerCache
{
	std::map<std::string, SEventConsumerCache> keyword;
	std::vector<int> leaf;
};

struct SEventState
{
	std::vector<SEventConsumer> consumers;

	// tag caches
	SEventConsumerCache cache;
};

int eventConsumerCreate(SEventState& state, const std::set<std::string>& topics, SEventConsumerHandler handler, void* custom=nullptr)
{
	SEventConsumer consumer;
	consumer.topics = topics;
	consumer.handler = handler;
	consumer.custom = custom;
	state.consumers.push_back(consumer);
	return -1;
}

void eventStateCompile(SEventState& state)
{
	int i = 0;
	for (auto& consumer : state.consumers)
	{
		SEventConsumerCache* current = &state.cache;
		for (auto& topic : consumer.topics)
		{
			current = &current->keyword[topic];
		}
		current->leaf.push_back(i++);
	}
}

// Slow O(n^2) version.
void eventEmit(SEventState& state, const SEvent& ev)
{
	for (auto it=state.consumers.begin(); it!=state.consumers.end(); it++)
	{
 		for (auto& topic : it->topics)
 		{
 			if (ev.topics.find(topic) == ev.topics.end())
 				goto skip_emit;
 		}

		it->handler(&(*it), &ev);
	skip_emit:
		0;
	}
}

// Fast but incorrect version. Doesn't work when tags don't match fully.
void eventEmitBtree(SEventState& state, const SEvent& ev)
{
	auto itBegin = std::lower_bound(state.consumers.begin(), state.consumers.end(), ev.topics);
	auto itEnd = std::upper_bound(state.consumers.begin(), state.consumers.end(), ev.topics);
	for (auto it = itBegin; it != itEnd; it++)
	{
		it->handler(&(*it), &ev);
	}
}

void eventEmitRecurtree(SEventState& state, const SEvent& ev)
{
	std::vector<int> consider;

	consider.insert(consider.end(), state.cache.leaf.begin(), state.cache.leaf.end());

	for (auto itKeywordBase = ev.topics.begin(); itKeywordBase != ev.topics.end(); itKeywordBase++)
	{
		auto itKeyword = itKeywordBase;
		SEventConsumerCache* current = &state.cache;

		while (itKeyword != ev.topics.end())
		{
			auto it = current->keyword.find(*(itKeyword++));
			if (it == current->keyword.end())
				continue; // chain ends here

			current = &(it->second);
			consider.insert(consider.end(), current->leaf.begin(), current->leaf.end());
		}
	}
	std::sort(consider.begin(), consider.end());
	int lastidx = -1;
	for (auto idx : consider)
	{
		if (idx == lastidx)
			continue;
		lastidx = idx;
		state.consumers[idx].handler(&state.consumers[idx], &ev);
	}
}

template< class T>
int testValidityPermutation(std::vector<std::set<std::string>> consumer, std::set<std::string> event, const T& emit)
{
	SEventState state;
	int numHits = 0;
	for (auto& it : consumer)
	{
		eventConsumerCreate(state, it, [](const SEventConsumer* consumer, const SEvent* ev) {
			int* v = ((int*)consumer->custom);
			(*v)++;
		}, &numHits);
	}
	eventStateCompile(state);
	SEvent e;
	e.topics = event;
	emit(state, e);
	return numHits;
}

template <class T>
bool testValidity(const T& eventFunc)
{
#define test(x) if((x) == false) { printf("Test failed: %s\n", #x); ret = false; } else { printf("Test succeeded: %s\n", #x); }
	printf("-------------------------\n");
	bool ret = true;
	test(testValidityPermutation({ {  } }, { "hello" }, eventFunc) == 1);
	test(testValidityPermutation({ { "hello" } }, { "hello" }, eventFunc) == 1);
	test(testValidityPermutation({ { "hello", "test" } }, { "hello" }, eventFunc) == 0);
	test(testValidityPermutation({ { "hello" } }, { "hello", "test" }, eventFunc) == 1);
	test(testValidityPermutation({ { "hello", "test" } }, { "hello", "test" }, eventFunc) == 1);
	test(testValidityPermutation({ { "hello", "baby", "bomb" } }, { "hello", "baby", "got", "an", "atom", "bomb" }, eventFunc) == 1);
	test(testValidityPermutation({ { "hello", "bomb", "baby" }, {"atom", "baby"} }, { "hello", "baby", "got", "an", "atom", "bomb" }, eventFunc) == 2);

	return ret;
#undef test
}

template <class T>
void testProfile(const T& eventFunc)
{
	printf("-------------------------\n");
	double timeElapsed;
	double timeConsumerCreateStart = timeGetCurrentSeconds();
	int numConsumerIds = 10000;
	int numConsumers = 10000;
	int numEvents = 100000;
	std::atomic<int> numHits = 0;
	SEventState state;

	// Setup consumer states.
	for (int i = 0; i < numConsumers; i++)
	{
		std::set<std::string> set;
		set.insert("type=log");

		int group = i % numConsumerIds;
		set.insert("id=" + std::to_string(group));
		eventConsumerCreate(state, set, [](const SEventConsumer* consumer, const SEvent* ev) {
			std::atomic<int>* v = ((std::atomic<int>*)consumer->custom);
			++(*v);
		}, &numHits);
	}
	printf("Profiler: Created consumers in %f seconds.\n", timeGetCurrentSeconds() - timeConsumerCreateStart);

	// Compile & optimize tree
	double timeConsumerOptimize = timeGetCurrentSeconds();
	eventStateCompile(state);
	printf("Profiler: Created optimized structure for consumers in %f seconds.\n", timeGetCurrentSeconds() - timeConsumerOptimize);

	// Start emitting events.
	double timeConsumerEventEmit = timeGetCurrentSeconds();

	SEvent e;
	e.topics.insert("type=log");
	e.topics.insert("id=100");
	e.topics.insert("cat");
	//#pragma omp parallel for
	for (int i = 0; i < numEvents; i++)
	{

		eventFunc(state, e);
	}

	timeElapsed = timeGetCurrentSeconds() - timeConsumerEventEmit;
	printf("Profiler: Emitted (%d) events in %f seconds (events/sec: %f).\n", numEvents, timeElapsed, ((double)numEvents) / timeElapsed);
	printf("Num hits: %d\n", numHits.fetch_add(0));
}

int main()
{

	testValidityPermutation({ { "hello", "bomb", "baby" },{ "atom", "baby" } }, { "hello", "baby", "got", "an", "atom", "bomb" }, [](SEventState& state, SEvent& ev) { eventEmitRecurtree(state, ev); });

	testValidity([](SEventState& state, SEvent& ev) { eventEmit(state, ev); });
	testValidity([](SEventState& state, SEvent& ev) { eventEmitRecurtree(state, ev); });
	testProfile([](SEventState& state, SEvent& ev) { eventEmit(state, ev); });
	testProfile([](SEventState& state, SEvent& ev) { eventEmitRecurtree(state, ev); });

	//testProfile();
    return 0;
}

<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexPO.cxx
 ** Lexer for GetText Translation (PO) files.
 **/
// Copyright 2012 by Colomban Wendling <ban@herbesfolles.org>
// The License.txt file describes the conditions under which this software may be distributed.

// see https://www.gnu.org/software/gettext/manual/gettext.html#PO-Files for the syntax reference
// some details are taken from the GNU msgfmt behavior (like that indent is allows in front of lines)

// TODO:
// * add keywords for flags (fuzzy, c-format, ...)
// * highlight formats inside c-format strings (%s, %d, etc.)

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>

#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"

#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static void ColourisePODoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) {
	StyleContext sc(startPos, length, initStyle, styler);
	bool escaped = false;
	int curLine = styler.GetLine(startPos);
	// the line state holds the last state on or before the line that isn't the default style
	int curLineState = curLine > 0 ? styler.GetLineState(curLine - 1) : SCE_PO_DEFAULT;

	for (; sc.More(); sc.Forward()) {
		// whether we should leave a state
		switch (sc.state) {
			case SCE_PO_COMMENT:
			case SCE_PO_PROGRAMMER_COMMENT:
			case SCE_PO_REFERENCE:
			case SCE_PO_FLAGS:
			case SCE_PO_FUZZY:
				if (sc.atLineEnd)
					sc.SetState(SCE_PO_DEFAULT);
				else if (sc.state == SCE_PO_FLAGS && sc.Match("fuzzy"))
					// here we behave like the previous parser, but this should probably be highlighted
					// on its own like a keyword rather than changing the whole flags style
					sc.ChangeState(SCE_PO_FUZZY);
				break;

			case SCE_PO_MSGCTXT:
			case SCE_PO_MSGID:
			case SCE_PO_MSGSTR:
				if (isspacechar(sc.ch))
					sc.SetState(SCE_PO_DEFAULT);
				break;

			case SCE_PO_ERROR:
				if (sc.atLineEnd)
					sc.SetState(SCE_PO_DEFAULT);
				break;

			case SCE_PO_MSGCTXT_TEXT:
			case SCE_PO_MSGID_TEXT:
			case SCE_PO_MSGSTR_TEXT:
				if (sc.atLineEnd) { // invalid inside a string
					if (sc.state == SCE_PO_MSGCTXT_TEXT)
						sc.ChangeState(SCE_PO_MSGCTXT_TEXT_EOL);
					else if (sc.state == SCE_PO_MSGID_TEXT)
						sc.ChangeState(SCE_PO_MSGID_TEXT_EOL);
					else if (sc.state == SCE_PO_MSGSTR_TEXT)
						sc.ChangeState(SCE_PO_MSGSTR_TEXT_EOL);
					sc.SetState(SCE_PO_DEFAULT);
					escaped = false;
				} else {
					if (escaped)
						escaped = false;
					else if (sc.ch == '\\')
						escaped = true;
					else if (sc.ch == '"')
						sc.ForwardSetState(SCE_PO_DEFAULT);
				}
				break;
		}

		// whether we should enter a new state
		if (sc.state == SCE_PO_DEFAULT) {
			// forward to the first non-white character on the line
			bool atLineStart = sc.atLineStart;
			if (atLineStart) {
				while (sc.More() && ! sc.atLineEnd && isspacechar(sc.ch))
					sc.Forward();
			}

			if (atLineStart && sc.ch == '#') {
				if (sc.chNext == '.')
					sc.SetState(SCE_PO_PROGRAMMER_COMMENT);
				else if (sc.chNext == ':')
					sc.SetState(SCE_PO_REFERENCE);
				else if (sc.chNext == ',')
					sc.SetState(SCE_PO_FLAGS);
				else if (sc.chNext == '|')
					sc.SetState(SCE_PO_COMMENT); // previous untranslated string, no special style yet
				else
					sc.SetState(SCE_PO_COMMENT);
			} else if (atLineStart && sc.Match("msgid")) { // includes msgid_plural
				sc.SetState(SCE_PO_MSGID);
			} else if (atLineStart && sc.Match("msgstr")) { // includes [] suffixes
				sc.SetState(SCE_PO_MSGSTR);
			} else if (atLineStart && sc.Match("msgctxt")) {
				sc.SetState(SCE_PO_MSGCTXT);
			} else if (sc.ch == '"') {
				if (curLineState == SCE_PO_MSGCTXT || curLineState == SCE_PO_MSGCTXT_TEXT)
					sc.SetState(SCE_PO_MSGCTXT_TEXT);
				else if (curLineState == SCE_PO_MSGID || curLineState == SCE_PO_MSGID_TEXT)
					sc.SetState(SCE_PO_MSGID_TEXT);
				else if (curLineState == SCE_PO_MSGSTR || curLineState == SCE_PO_MSGSTR_TEXT)
					sc.SetState(SCE_PO_MSGSTR_TEXT);
				else
					sc.SetState(SCE_PO_ERROR);
			} else if (! isspacechar(sc.ch))
				sc.SetState(SCE_PO_ERROR);

			if (sc.state != SCE_PO_DEFAULT)
				curLineState = sc.state;
		}

		if (sc.atLineEnd) {
			// Update the line state, so it can be seen by next line
			curLine = styler.GetLine(sc.currentPos);
			styler.SetLineState(curLine, curLineState);
		}
	}
	sc.Complete();
}

static const char *const poWordListDesc[] = {
	0
};

LexerModule lmPO(SCLEX_PO, ColourisePODoc, "po", 0, poWordListDesc);
<commit_msg>Remove duplicated branch in PO lexer<commit_after>// Scintilla source code edit control
/** @file LexPO.cxx
 ** Lexer for GetText Translation (PO) files.
 **/
// Copyright 2012 by Colomban Wendling <ban@herbesfolles.org>
// The License.txt file describes the conditions under which this software may be distributed.

// see https://www.gnu.org/software/gettext/manual/gettext.html#PO-Files for the syntax reference
// some details are taken from the GNU msgfmt behavior (like that indent is allows in front of lines)

// TODO:
// * add keywords for flags (fuzzy, c-format, ...)
// * highlight formats inside c-format strings (%s, %d, etc.)
// * style for previous untranslated string? ("#|" comment)

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>

#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"

#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static void ColourisePODoc(unsigned int startPos, int length, int initStyle, WordList *[], Accessor &styler) {
	StyleContext sc(startPos, length, initStyle, styler);
	bool escaped = false;
	int curLine = styler.GetLine(startPos);
	// the line state holds the last state on or before the line that isn't the default style
	int curLineState = curLine > 0 ? styler.GetLineState(curLine - 1) : SCE_PO_DEFAULT;

	for (; sc.More(); sc.Forward()) {
		// whether we should leave a state
		switch (sc.state) {
			case SCE_PO_COMMENT:
			case SCE_PO_PROGRAMMER_COMMENT:
			case SCE_PO_REFERENCE:
			case SCE_PO_FLAGS:
			case SCE_PO_FUZZY:
				if (sc.atLineEnd)
					sc.SetState(SCE_PO_DEFAULT);
				else if (sc.state == SCE_PO_FLAGS && sc.Match("fuzzy"))
					// here we behave like the previous parser, but this should probably be highlighted
					// on its own like a keyword rather than changing the whole flags style
					sc.ChangeState(SCE_PO_FUZZY);
				break;

			case SCE_PO_MSGCTXT:
			case SCE_PO_MSGID:
			case SCE_PO_MSGSTR:
				if (isspacechar(sc.ch))
					sc.SetState(SCE_PO_DEFAULT);
				break;

			case SCE_PO_ERROR:
				if (sc.atLineEnd)
					sc.SetState(SCE_PO_DEFAULT);
				break;

			case SCE_PO_MSGCTXT_TEXT:
			case SCE_PO_MSGID_TEXT:
			case SCE_PO_MSGSTR_TEXT:
				if (sc.atLineEnd) { // invalid inside a string
					if (sc.state == SCE_PO_MSGCTXT_TEXT)
						sc.ChangeState(SCE_PO_MSGCTXT_TEXT_EOL);
					else if (sc.state == SCE_PO_MSGID_TEXT)
						sc.ChangeState(SCE_PO_MSGID_TEXT_EOL);
					else if (sc.state == SCE_PO_MSGSTR_TEXT)
						sc.ChangeState(SCE_PO_MSGSTR_TEXT_EOL);
					sc.SetState(SCE_PO_DEFAULT);
					escaped = false;
				} else {
					if (escaped)
						escaped = false;
					else if (sc.ch == '\\')
						escaped = true;
					else if (sc.ch == '"')
						sc.ForwardSetState(SCE_PO_DEFAULT);
				}
				break;
		}

		// whether we should enter a new state
		if (sc.state == SCE_PO_DEFAULT) {
			// forward to the first non-white character on the line
			bool atLineStart = sc.atLineStart;
			if (atLineStart) {
				while (sc.More() && ! sc.atLineEnd && isspacechar(sc.ch))
					sc.Forward();
			}

			if (atLineStart && sc.ch == '#') {
				if (sc.chNext == '.')
					sc.SetState(SCE_PO_PROGRAMMER_COMMENT);
				else if (sc.chNext == ':')
					sc.SetState(SCE_PO_REFERENCE);
				else if (sc.chNext == ',')
					sc.SetState(SCE_PO_FLAGS);
				else
					sc.SetState(SCE_PO_COMMENT);
			} else if (atLineStart && sc.Match("msgid")) { // includes msgid_plural
				sc.SetState(SCE_PO_MSGID);
			} else if (atLineStart && sc.Match("msgstr")) { // includes [] suffixes
				sc.SetState(SCE_PO_MSGSTR);
			} else if (atLineStart && sc.Match("msgctxt")) {
				sc.SetState(SCE_PO_MSGCTXT);
			} else if (sc.ch == '"') {
				if (curLineState == SCE_PO_MSGCTXT || curLineState == SCE_PO_MSGCTXT_TEXT)
					sc.SetState(SCE_PO_MSGCTXT_TEXT);
				else if (curLineState == SCE_PO_MSGID || curLineState == SCE_PO_MSGID_TEXT)
					sc.SetState(SCE_PO_MSGID_TEXT);
				else if (curLineState == SCE_PO_MSGSTR || curLineState == SCE_PO_MSGSTR_TEXT)
					sc.SetState(SCE_PO_MSGSTR_TEXT);
				else
					sc.SetState(SCE_PO_ERROR);
			} else if (! isspacechar(sc.ch))
				sc.SetState(SCE_PO_ERROR);

			if (sc.state != SCE_PO_DEFAULT)
				curLineState = sc.state;
		}

		if (sc.atLineEnd) {
			// Update the line state, so it can be seen by next line
			curLine = styler.GetLine(sc.currentPos);
			styler.SetLineState(curLine, curLineState);
		}
	}
	sc.Complete();
}

static const char *const poWordListDesc[] = {
	0
};

LexerModule lmPO(SCLEX_PO, ColourisePODoc, "po", 0, poWordListDesc);
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007-2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include "db/modest/ModuleLoader.h"

#include "db/rt/DynamicLibrary.h"
#include "db/rt/DynamicObject.h"

#include <cstring>

using namespace db::modest;
using namespace db::rt;

ModuleLoader::ModuleLoader()
{
}

ModuleLoader::~ModuleLoader()
{
}

ModuleInfo* ModuleLoader::loadModule(const char* filename)
{
   ModuleInfo* rval = NULL;

   // open library
   void* handle = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
   if(handle != NULL)
   {
      CreateModestModuleFn create;
      FreeModestModuleFn free;

      // clear error
      char* error = dlerror();

      // try to get create module function
      create = (CreateModestModuleFn)dlsym(handle, "createModestModule");
      if((error = dlerror()) == NULL)
      {
         // clear error
         error = dlerror();

         // try to get free module function
         free = (FreeModestModuleFn)dlsym(handle, "freeModestModule");
         error = dlerror();
      }

      if(error == NULL)
      {
         // create ModuleInfo
         rval = new ModuleInfo();
         rval->handle = handle;
         rval->module = create();
         rval->freeModule = free;
      }
      else
      {
         // could not load create or free functions
         ExceptionRef e = new Exception(
            "Could not load module.", "db.modest.BadModule");
         e->getDetails()["filename"] = filename;
         e->getDetails()["error"] = error;
         Exception::setLast(e, false);
      }
   }
   else
   {
      // failed to open module
      char* error = dlerror();
      ExceptionRef e = new Exception(
         "Could not open module file.", "db.modest.BadModuleFile");
      e->getDetails()["filename"] = filename;
      e->getDetails()["error"] = error;
      Exception::setLast(e, false);
   }

   return rval;
}

void ModuleLoader::unloadModule(ModuleInfo* mi)
{
   // free module
   mi->freeModule(mi->module);

   // close handle
   dlclose(mi->handle);

   // delete module info
   delete mi;
}
<commit_msg>Removed unneeded header.<commit_after>/*
 * Copyright (c) 2007-2009 Digital Bazaar, Inc. All rights reserved.
 */
#include "db/modest/ModuleLoader.h"

#include "db/rt/DynamicLibrary.h"

#include <cstring>

using namespace db::modest;
using namespace db::rt;

ModuleLoader::ModuleLoader()
{
}

ModuleLoader::~ModuleLoader()
{
}

ModuleInfo* ModuleLoader::loadModule(const char* filename)
{
   ModuleInfo* rval = NULL;

   // open library
   void* handle = dlopen(filename, RTLD_NOW | RTLD_GLOBAL);
   if(handle != NULL)
   {
      CreateModestModuleFn create;
      FreeModestModuleFn free;

      // clear error
      char* error = dlerror();

      // try to get create module function
      create = (CreateModestModuleFn)dlsym(handle, "createModestModule");
      if((error = dlerror()) == NULL)
      {
         // clear error
         error = dlerror();

         // try to get free module function
         free = (FreeModestModuleFn)dlsym(handle, "freeModestModule");
         error = dlerror();
      }

      if(error == NULL)
      {
         // create ModuleInfo
         rval = new ModuleInfo();
         rval->handle = handle;
         rval->module = create();
         rval->freeModule = free;
      }
      else
      {
         // could not load create or free functions
         ExceptionRef e = new Exception(
            "Could not load module.", "db.modest.BadModule");
         e->getDetails()["filename"] = filename;
         e->getDetails()["error"] = error;
         Exception::setLast(e, false);
      }
   }
   else
   {
      // failed to open module
      char* error = dlerror();
      ExceptionRef e = new Exception(
         "Could not open module file.", "db.modest.BadModuleFile");
      e->getDetails()["filename"] = filename;
      e->getDetails()["error"] = error;
      Exception::setLast(e, false);
   }

   return rval;
}

void ModuleLoader::unloadModule(ModuleInfo* mi)
{
   // free module
   mi->freeModule(mi->module);

   // close handle
   dlclose(mi->handle);

   // delete module info
   delete mi;
}
<|endoftext|>


<commit_before>//
//#include "debugger_message_types/frame_resource_tree.h"
//
//namespace v8toolkit {
//
//std::string const Page_GetResourceTree::message_name = "Page.getResourceTree";
//
//Page_GetResourceTree::Page_GetResourceTree(v8toolkit::DebugContext &debug_context, nlohmann::json const &json) :
//    RequestMessage(debug_context, json) {}
//
//
//std::unique_ptr<ResponseMessage> Page_GetResourceTree::generate_response_message() const {
//    return std::make_unique<Page_FrameResourceTree>(*this);
//}
//
//
//std::vector<std::unique_ptr<InformationalMessage> > Page_GetResourceTree::generate_additional_messages() const {
//    return {};
//}
//
//
//PageFrame::PageFrame(v8toolkit::DebugContext &debug_context) :
//    frame_id(debug_context.get_frame_id()),
//    network_loader_id(debug_context.get_frame_id()),
//    security_origin(fmt::format("v8toolkit://{}", debug_context.get_base_url())),
//    url(fmt::format("v8toolkit://{}/", debug_context.get_base_url())) {}
//
//
//FrameResource::FrameResource(v8toolkit::DebugContext &debug_context, v8toolkit::Script const &script) : url(
//    script.get_source_location()) {}
//
//
//FrameResourceTree::FrameResourceTree(DebugContext &debug_context) :
//    debug_context(debug_context),
//    page_frame(this->debug_context) {
//    // nothing to do for child frames at this point, it will always be empty for now
//
//    for (auto &script : this->debug_context.get_scripts()) {
//        this->resources.emplace_back(FrameResource(this->debug_context, *script));
//    }
//}
//
//
//Page_FrameResourceTree::Page_FrameResourceTree(RequestMessage const &request_message) :
//    ResponseMessage(request_message),
//    frame_resource_tree(this->debug_context) {
//
//}
//
//nlohmann::json Page_FrameResourceTree::to_json() const {
//    return {this->frame_resource_tree};
//}
//
//
//void to_json(nlohmann::json &j, const FrameResourceTree &frame_resource_tree) {
//    j = {
//        "frameTree", {{"frame", frame_resource_tree.page_frame},
//                       {"childFrames", frame_resource_tree.child_frames},
//                          {"resources", frame_resource_tree.resources}}
//    };
//}
//
//
//void to_json(nlohmann::json &j, const PageFrame & page_frame) {
//    j = {{"id", page_frame.frame_id},
//         {"parentId", page_frame.parent_id},
//         {"loaderId", page_frame.network_loader_id},
//         {"name", page_frame.name},
//         {"url", page_frame.url},
//         {"securityOrigin", page_frame.security_origin},
//         {"mimeType", page_frame.mime_type}
//    };
//}
//
//
//void to_json(nlohmann::json &j, const FrameResource & frame_resource) {
//    j = {{"url", frame_resource.url},
//         {"type", frame_resource.type},
//         {"mimeType", frame_resource.mime_type}
//    };
//}
//
//} // end v8toolkit namespace<commit_msg>removed file that no longer has any content<commit_after><|endoftext|>


<commit_before>#include "FitResultPrinter.h"

// STL
#include <iomanip>
#include <string>
#include <vector>

// from Boost
#include <boost/format.hpp>

// from ROOT
#include <TIterator.h>

// from RooFit
#include <RooFitResult.h>
#include <RooArgList.h>
#include <RooAbsArg.h>
#include <RooRealVar.h>

// from DooCore
#include <doocore/io/MsgStream.h>
#include <doocore/statistics/general.h>

doofit::plotting::fitresult::FitResultPrinter::FitResultPrinter(const RooFitResult& fit_result)
: fit_result_(fit_result),
  full_precision_printout_(false),
  print_pulls_(true),
  print_const_pars_(true)
{
}

void doofit::plotting::fitresult::FitResultPrinter::PlotHandler() const {
  using namespace doocore::statistics::general;
  using namespace doocore::io;
  using boost::format;
  using boost::io::group;

  std::cout << std::endl;
  std::cout << "FitResultPrinter: NLL = " << fit_result_.minNll() << ", EDM = " << fit_result_.edm() << std::endl;
  std::cout << "                  covariance matrix quality: ";
  switch(fit_result_.covQual()) {
    case -1:
      std::cout << TerminalColorCode(2) << fit_result_.covQual() << ": Unknown, matrix was externally provided" << TerminalResetCode() << std::endl;
      break;
    case 0:
      std::cout << TerminalColorCode(2) << fit_result_.covQual() << ": Not calculated at all" << TerminalResetCode() << std::endl;
      break;
    case 1:
      std::cout << TerminalColorCode(2) << fit_result_.covQual() << ": Approximation only, not accurate" << TerminalResetCode() << std::endl;
      break;
    case 2:
      std::cout << TerminalColorCode(1) << fit_result_.covQual() << ": Full matrix, but forced positive-definite" << TerminalResetCode() << std::endl;
      break;
    case 3:
      std::cout << TerminalColorCode(0) << fit_result_.covQual() << ": Full, accurate covariance matrix" << TerminalResetCode() << std::endl;
      break;
  }

  std::cout << "                  Fit status: ";
  for (unsigned int i=0; i<fit_result_.numStatusHistory(); ++i) {
    if (fit_result_.statusCodeHistory(i) == 0) {
      std::cout << TerminalColorCode(0);
    } else if (fit_result_.statusCodeHistory(i) == 1) {
      std::cout << TerminalColorCode(1);
    } else {
      std::cout << TerminalColorCode(2);
    }
    std::cout << fit_result_.statusLabelHistory(i) << "=" << fit_result_.statusCodeHistory(i) << TerminalResetCode();
    if (i<(fit_result_.numStatusHistory()-1)) {
      std::cout << ", ";
    }
  }
  std::cout << std::endl;
  std::cout << std::endl;

  if (print_const_pars_){
    RooArgList par_list_const = fit_result_.constPars();

    if (par_list_const.getSize() > 0) {
      std::cout << format("%-30s %15s") % "          Parameter          " % "     Value     " << std::endl;
      std::cout << format("%-30s %15s") % "-----------------------------" % "---------------" << std::endl;

      TIterator* it_const = par_list_const.createIterator();
      RooAbsArg* arg = NULL;
      while ((arg = dynamic_cast<RooAbsArg*>(it_const->Next()))) {
        RooRealVar* var = dynamic_cast<RooRealVar*>(arg);
        if (var != NULL) {
          std::cout << format("%-30s %15g") % var->GetName() % var->getVal() << std::endl;
        }
      }
      std::cout << std::endl;
    }
  }

	RooArgList par_list_float_final = fit_result_.floatParsFinal();
  RooArgList par_list_float_init  = fit_result_.floatParsInit();

  TIterator* it_float = par_list_float_final.createIterator();
  RooAbsArg* arg = NULL;

  std::cout << format("%-30s %15s %15s +/- %-15s ") % "          Parameter          " % "   InitValue   " % "    Fit result" % "Error         ";
  if (print_pulls_) {
    std::cout << format("%15s") % "      Pull     ";
  }
  std::cout << std::endl;

  std::cout << format("%-30s %15s %15s-----%-15s ") % "-----------------------------" % "---------------" % "--------------" % "--------------";
  if (print_pulls_) {
    std::cout << format("%15s") % "---------------";
  }
  std::cout << std::endl;

  while ((arg = dynamic_cast<RooAbsArg*>(it_float->Next()))) {
    RooRealVar* var = dynamic_cast<RooRealVar*>(arg);
    if (var != NULL) {
      ValueWithError<double> val(var->getVal(), var->getError());
      val.set_full_precision_printout(full_precision_printout_);
      RooRealVar* var_init = dynamic_cast<RooRealVar*>(par_list_float_init.find(var->GetName()));
      double val_init = 0.0, pull = 0.0;
      if (var_init != NULL) {
        val_init = var_init->getVal();
        pull = (val_init-val.value)/val.error;
      }

      std::string str_color, str_term;
      if (std::abs(pull) < 2.0) {
        str_color = TerminalColorCode(0);
      } else if (std::abs(pull) > 2.0 && std::abs(pull) <= 3.0) {
        str_color = TerminalColorCode(1);
      } else if (std::abs(pull) > 3.0) {
        str_color = TerminalColorCode(2);
      }
      str_term = TerminalResetCode();

      val.FormatString();

      std::cout << format("%-30s %15g %15s +/- %-15s ") % var->GetName() % val_init % val.str_value() % val.str_error();
      if (print_pulls_) {
        std::cout << format("%s%15g%s") % str_color % pull % str_term;
      }
      std::cout << std::endl;
    }
  }

  std::cout << std::endl;
}
<commit_msg>FitResultPrinter: column width<commit_after>#include "FitResultPrinter.h"

// STL
#include <iomanip>
#include <string>
#include <vector>

// from Boost
#include <boost/format.hpp>

// from ROOT
#include <TIterator.h>

// from RooFit
#include <RooFitResult.h>
#include <RooArgList.h>
#include <RooAbsArg.h>
#include <RooRealVar.h>

// from DooCore
#include <doocore/io/MsgStream.h>
#include <doocore/statistics/general.h>

doofit::plotting::fitresult::FitResultPrinter::FitResultPrinter(const RooFitResult& fit_result)
: fit_result_(fit_result),
  full_precision_printout_(false),
  print_pulls_(true),
  print_const_pars_(true)
{
}

void doofit::plotting::fitresult::FitResultPrinter::PlotHandler() const {
  using namespace doocore::statistics::general;
  using namespace doocore::io;
  using boost::format;
  using boost::io::group;

  std::cout << std::endl;
  std::cout << "FitResultPrinter: NLL = " << fit_result_.minNll() << ", EDM = " << fit_result_.edm() << std::endl;
  std::cout << "                  covariance matrix quality: ";
  switch(fit_result_.covQual()) {
    case -1:
      std::cout << TerminalColorCode(2) << fit_result_.covQual() << ": Unknown, matrix was externally provided" << TerminalResetCode() << std::endl;
      break;
    case 0:
      std::cout << TerminalColorCode(2) << fit_result_.covQual() << ": Not calculated at all" << TerminalResetCode() << std::endl;
      break;
    case 1:
      std::cout << TerminalColorCode(2) << fit_result_.covQual() << ": Approximation only, not accurate" << TerminalResetCode() << std::endl;
      break;
    case 2:
      std::cout << TerminalColorCode(1) << fit_result_.covQual() << ": Full matrix, but forced positive-definite" << TerminalResetCode() << std::endl;
      break;
    case 3:
      std::cout << TerminalColorCode(0) << fit_result_.covQual() << ": Full, accurate covariance matrix" << TerminalResetCode() << std::endl;
      break;
  }

  std::cout << "                  Fit status: ";
  for (unsigned int i=0; i<fit_result_.numStatusHistory(); ++i) {
    if (fit_result_.statusCodeHistory(i) == 0) {
      std::cout << TerminalColorCode(0);
    } else if (fit_result_.statusCodeHistory(i) == 1) {
      std::cout << TerminalColorCode(1);
    } else {
      std::cout << TerminalColorCode(2);
    }
    std::cout << fit_result_.statusLabelHistory(i) << "=" << fit_result_.statusCodeHistory(i) << TerminalResetCode();
    if (i<(fit_result_.numStatusHistory()-1)) {
      std::cout << ", ";
    }
  }
  std::cout << std::endl;
  std::cout << std::endl;

  if (print_const_pars_){
    RooArgList par_list_const = fit_result_.constPars();

    if (par_list_const.getSize() > 0) {
      std::cout << format("%-34s %15s") % "            Parameter            " % "     Value     " << std::endl;
      std::cout << format("%-34s %15s") % "---------------------------------" % "---------------" << std::endl;

      TIterator* it_const = par_list_const.createIterator();
      RooAbsArg* arg = NULL;
      while ((arg = dynamic_cast<RooAbsArg*>(it_const->Next()))) {
        RooRealVar* var = dynamic_cast<RooRealVar*>(arg);
        if (var != NULL) {
          std::cout << format("%-34s %15g") % var->GetName() % var->getVal() << std::endl;
        }
      }
      std::cout << std::endl;
    }
  }

	RooArgList par_list_float_final = fit_result_.floatParsFinal();
  RooArgList par_list_float_init  = fit_result_.floatParsInit();

  TIterator* it_float = par_list_float_final.createIterator();
  RooAbsArg* arg = NULL;

  std::cout << format("%-34s %15s %15s +/- %-15s ") % "            Parameter            " % "   InitValue   " % "    Fit result" % "Error         ";
  if (print_pulls_) {
    std::cout << format("%15s") % "      Pull     ";
  }
  std::cout << std::endl;

  std::cout << format("%-34s %15s %15s-----%-15s ") % "---------------------------------" % "---------------" % "--------------" % "--------------";
  if (print_pulls_) {
    std::cout << format("%15s") % "---------------";
  }
  std::cout << std::endl;

  while ((arg = dynamic_cast<RooAbsArg*>(it_float->Next()))) {
    RooRealVar* var = dynamic_cast<RooRealVar*>(arg);
    if (var != NULL) {
      ValueWithError<double> val(var->getVal(), var->getError());
      val.set_full_precision_printout(full_precision_printout_);
      RooRealVar* var_init = dynamic_cast<RooRealVar*>(par_list_float_init.find(var->GetName()));
      double val_init = 0.0, pull = 0.0;
      if (var_init != NULL) {
        val_init = var_init->getVal();
        pull = (val_init-val.value)/val.error;
      }

      std::string str_color, str_term;
      if (std::abs(pull) < 2.0) {
        str_color = TerminalColorCode(0);
      } else if (std::abs(pull) > 2.0 && std::abs(pull) <= 3.0) {
        str_color = TerminalColorCode(1);
      } else if (std::abs(pull) > 3.0) {
        str_color = TerminalColorCode(2);
      }
      str_term = TerminalResetCode();

      val.FormatString();

      std::cout << format("%-34s %15g %15s +/- %-15s ") % var->GetName() % val_init % val.str_value() % val.str_error();
      if (print_pulls_) {
        std::cout << format("%s%15g%s") % str_color % pull % str_term;
      }
      std::cout << std::endl;
    }
  }

  std::cout << std::endl;
}
<|endoftext|>