<commit_before>/**
 * Macc n Cheese - Scanner Tester
 * 9-mar-2016
 * This program is used to test the scanner. It reads in the given source file and outputs the tokens.
 */

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
using namespace std;

#include "mscan.h"

ifstream sourceFile;
ofstream listFile;
Scanner scan;

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

	if (strcmp("help", argv[1]) == 0) {
		cout << "Usage: ./scan_test [inputFile]\n       ./scan_test help\nExample: ./scan_test myProgram.mnc" << endl;
		return 0;
	} else {
		sourceFile.open(argv[1]);
		if (!sourceFile.is_open()) {
			cout << "File not found.";
			cin.get();
			return 1;
		}
	}

	listFile.open("listFile.lst");
	if (!listFile.is_open()) {
		cout << "Could not open list file.";
		cin.get();
		return 2;
	}

//	cout.width(20);
	cout << "---------- Scanner Tester ----------\n";
	cout << "TOKEN     \t\tTEXT\n";
	while (!sourceFile.eof()) {
		switch(scan.GetNextToken()) {
		case EOF_SYM:
			cout << "EOF_SYM   ";
			break;
		case BOOL_SYM:
			cout << "BOOL_SYM  ";
			break;
		case BREAK_SYM:
			cout << "BREAK_SYM ";
			break;
		case CASE_SYM:
			cout << "CASE_SYM  ";
			break;
		case CHEESE_SYM:
			cout << "CHEESE_SYM";
			break;
		case DECS_SYM:
			cout << "DECS_SYM  ";
			break;
		case DO_SYM:
			cout << "DO_SYM    ";
			break;
		case ELSE_SYM:
			cout << "ELSE_SYM  ";
			break;
		case END_SYM:
			cout << "END_SYM   ";
			break;
		case FALSE_SYM:
			cout << "FALSE_SYM ";
			break;
		case FLOAT_SYM:
			cout << "FLOAT_SYM ";
			break;
		case FOR_SYM:
			cout << "FOR_SYM   ";
			break;
		case HIPHIP_SYM:
			cout << "HIPHIP_SYM";
			break;
		case IF_SYM:
			cout << "IF_SYM    ";
			break;
		case INT_SYM:
			cout << "INT_SYM   ";
			break;
		case LISTEN_SYM:
			cout << "LISTEN_SYM";
			break;
		case OTHERWISE_SYM:
			cout << "OTHERWISE_SYM";
			break;
		case SELECT_SYM:
			cout << "SELECT_SYM";
			break;
		case SHOUT_SYM:
			cout << "SHOUT_SYM ";
			break;
		case THEN_SYM:
			cout << "THEN_SYM  ";
			break;
		case TRUE_SYM:
			cout << "TRUE_SYM  ";
			break;
		case WHILE_SYM:
			cout << "WHILE_SYM ";
			break;
		case LSTAPLE:
			cout << "LSTAPLE   ";
			break;
		case RSTAPLE:
			cout << "RSTAPLE   ";
			break;
		case LBANANA:
			cout << "LBANANA   ";
			break;
		case RBANANA:
			cout << "RBANANA   ";
			break;
		case LMUSTACHE:
			cout << "LMUSTACHE ";
			break;
		case RMUSTACHE:
			cout << "RMUSTACHE ";
			break;
		case COLON:
			cout << "COLON     ";
			break;
		case SEMICOLON:
			cout << "SEMICOLON ";
			break;
		case COMMA:
			cout << "COMMA     ";
			break;
		case ASSIGN_OP:
			cout << "ASSIGN_OP ";
			break;
		case PLUS_OP:
			cout << "PLUS_OP   ";
			break;
		case MINUS_OP:
			cout << "MINUS_OP  ";
			break;
		case MULT_OP:
			cout << "MULT_OP   ";
			break;
		case DIV_OP:
			cout << "DIV_OP    ";
			break;
		case LT_OP:
			cout << "LT_OP     ";
			break;
		case LE_OP:
			cout << "LE_OP     ";
			break;
		case GT_OP:
			cout << "GT_OP     ";
			break;
		case GE_OP:
			cout << "GE_OP     ";
			break;
		case EQ_OP1:
			cout << "EQ_OP1    ";
			break;
		case EQ_OP2:
			cout << "EQ_OP2    ";
			break;
		case NE_OP:
			cout << "NE_OP     ";
			break;
		case ID:
			cout << "ID        ";
			break;
		case BOOL_LIT:
			cout << "BOOL_LIT  ";
			break;
		case INT_LIT:
			cout << "INT_LIT   ";
			break;
		case FLOAT_LIT:
			cout << "FLOAT_LIT ";
			break;
		case CHEESE_LIT:
			cout << "CHEESE_LIT";
			break;
		default:
			break;
		}
		cout << "\t\t" << scan.tokenBuffer << "\n";
	}

	return 0;
}
<commit_msg>updated scan tester<commit_after>/**
 * Macc n Cheese - Scanner Tester
 * 9-mar-2016
 * This program is used to test the scanner. It reads in the given source file and outputs the tokens.
 */

#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
using namespace std;

#include "mscan.h"

ifstream sourceFile;
ofstream listFile;
Scanner scan;

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

	if (strcmp("help", argv[1]) == 0) {
		cout << "Usage: ./scan_test [inputFile]\n       ./scan_test help\nExample: ./scan_test myProgram.mnc" << endl;
		return 0;
	} else {
		sourceFile.open(argv[1]);
		if (!sourceFile.is_open()) {
			cout << "File not found.";
			cin.get();
			return 1;
		}
	}

	listFile.open("listFile.lst");
	if (!listFile.is_open()) {
		cout << "Could not open list file.";
		cin.get();
		return 2;
	}

//	cout.width(20);
	cout << "---------- Scanner Tester ----------\n";
	cout << "TOKEN     \t\tTEXT\n";
	while (!sourceFile.eof()) {
		switch(scan.GetNextToken()) {
		case EOF_SYM:
			cout << "EOF_SYM   ";
			break;
		case BOOL_SYM:
			cout << "BOOL_SYM  ";
			break;
		case BREAK_SYM:
			cout << "BREAK_SYM ";
			break;
		case CASE_SYM:
			cout << "CASE_SYM  ";
			break;
		case CHEESE_SYM:
			cout << "CHEESE_SYM";
			break;
		case DECS_SYM:
			cout << "DECS_SYM  ";
			break;
		case DO_SYM:
			cout << "DO_SYM    ";
			break;
		case ELSE_SYM:
			cout << "ELSE_SYM  ";
			break;
		case END_SYM:
			cout << "END_SYM   ";
			break;
		case FALSE_SYM:
			cout << "FALSE_SYM ";
			break;
		case FLOAT_SYM:
			cout << "FLOAT_SYM ";
			break;
		case FOR_SYM:
			cout << "FOR_SYM   ";
			break;
		case HIPHIP_SYM:
			cout << "HIPHIP_SYM";
			break;
		case IF_SYM:
			cout << "IF_SYM    ";
			break;
		case INT_SYM:
			cout << "INT_SYM   ";
			break;
		case LISTEN_SYM:
			cout << "LISTEN_SYM";
			break;
		case OTHERWISE_SYM:
			cout << "OTHERWISE_SYM";
			break;
		case SELECT_SYM:
			cout << "SELECT_SYM";
			break;
		case SHOUT_SYM:
			cout << "SHOUT_SYM ";
			break;
		case THEN_SYM:
			cout << "THEN_SYM  ";
			break;
		case TRUE_SYM:
			cout << "TRUE_SYM  ";
			break;
		case WHILE_SYM:
			cout << "WHILE_SYM ";
			break;
		case LSTAPLE:
			cout << "LSTAPLE   ";
			break;
		case RSTAPLE:
			cout << "RSTAPLE   ";
			break;
		case LBANANA:
			cout << "LBANANA   ";
			break;
		case RBANANA:
			cout << "RBANANA   ";
			break;
		case LMUSTACHE:
			cout << "LMUSTACHE ";
			break;
		case RMUSTACHE:
			cout << "RMUSTACHE ";
			break;
		case COLON:
			cout << "COLON     ";
			break;
		case SEMICOLON:
			cout << "SEMICOLON ";
			break;
		case COMMA:
			cout << "COMMA     ";
			break;
		case ASSIGN_OP:
			cout << "ASSIGN_OP ";
			break;
		case PLUS_OP:
			cout << "PLUS_OP   ";
			break;
		case MINUS_OP:
			cout << "MINUS_OP  ";
			break;
		case MULT_OP:
			cout << "MULT_OP   ";
			break;
		case DIV_OP:
			cout << "DIV_OP    ";
			break;
		case LT_OP:
			cout << "LT_OP     ";
			break;
		case LE_OP:
			cout << "LE_OP     ";
			break;
		case GT_OP:
			cout << "GT_OP     ";
			break;
		case GE_OP:
			cout << "GE_OP     ";
			break;
		case EQ_OP1:
			cout << "EQ_OP1    ";
			break;
		case EQ_OP2:
			cout << "EQ_OP2    ";
			break;
		case NE_OP:
			cout << "NE_OP     ";
			break;
		case ID:
			cout << "ID        ";
			break;
		case BOOL_LIT:
			cout << "BOOL_LIT  ";
			break;
		case INT_LIT:
			cout << "INT_LIT   ";
			break;
		case FLOAT_LIT:
			cout << "FLOAT_LIT ";
			break;
		case CHEESE_LIT:
			cout << "CHEESE_LIT";
			break;
		default:
			break;
		}
		cout << "\t\t" << scan.tokenBuffer << "\n";
	}
	sourceFile.close();
	listFile.close();
	return 0;
}
<|endoftext|>


<commit_before>// Copyright (C) 2010 - 2012 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

/**
 * CCrossSectionTask class.
 *
 * This class implements a cross section task.
 */

#include <string>
#include <cmath>

#include "copasi.h"

#include "CCrossSectionTask.h"
#include "CCrossSectionProblem.h"
//#include "CCrossSectionMethod.h"
#include "model/CModel.h"
#include "model/CState.h"
#include "report/CKeyFactory.h"
#include "report/CReport.h"
#include "utilities/CProcessReport.h"
#include "utilities/CCopasiException.h"
#include  "CopasiDataModel/CCopasiDataModel.h"

const unsigned int CCrossSectionTask::ValidMethods[] =
{
  CCopasiMethod::deterministic,
  //  CCopasiMethod::stochastic,
  //CCopasiMethod::directMethod,
  //CCopasiMethod::tauLeap,
  //CCopasiMethod::adaptiveSA,
  //CCopasiMethod::hybrid,
  //CCopasiMethod::hybridLSODA,
#ifdef COPASI_DEBUG
  CCopasiMethod::DsaLsodar,
#endif // COPASI_DEBUG
  CCopasiMethod::unset
};

CCrossSectionTask::CCrossSectionTask(const CCopasiContainer * pParent):
  CCopasiTask(CCopasiTask::crosssection, pParent),
  mTimeSeriesRequested(true),
  mTimeSeries(),
  mpCrossSectionProblem(NULL),
  mpTrajectoryMethod(NULL),
  mUpdateMoieties(false),
  mpCurrentState(NULL),
  mpCurrentTime(NULL),
  mOutputStartTime(0.0)
{
  mpProblem = new CCrossSectionProblem(this);
  mpMethod = createMethod(CCopasiMethod::deterministic);
  this->add(mpMethod, true);

/*  CCopasiParameter * pParameter = mpMethod->getParameter("Integrate Reduced Model");

  if (pParameter != NULL)
    mUpdateMoieties = *pParameter->getValue().pBOOL;
  else
    mUpdateMoieties = false;*/
}

CCrossSectionTask::CCrossSectionTask(const CCrossSectionTask & src,
                                     const CCopasiContainer * pParent):
  CCopasiTask(src, pParent),
  mTimeSeriesRequested(src.mTimeSeriesRequested),
  mTimeSeries(),
  mpCrossSectionProblem(NULL),
  mpTrajectoryMethod(NULL),
  mUpdateMoieties(false),
  mpCurrentState(NULL),
  mpCurrentTime(NULL),
  mOutputStartTime(0.0)
{
  mpProblem =
    new CCrossSectionProblem(*static_cast< CCrossSectionProblem * >(src.mpProblem), this);

  mpMethod = createMethod(src.mpMethod->getSubType());
  * mpMethod = * src.mpMethod;

  mpMethod->elevateChildren();

  this->add(mpMethod, true);

/*  CCopasiParameter * pParameter = mpMethod->getParameter("Integrate Reduced Model");

  if (pParameter != NULL)
    mUpdateMoieties = *pParameter->getValue().pBOOL;
  else
    mUpdateMoieties = false;*/
}

CCrossSectionTask::~CCrossSectionTask()
{
  cleanup();
}

void CCrossSectionTask::cleanup()
{
  pdelete(mpCurrentState);
}

bool CCrossSectionTask::initialize(const OutputFlag & of,
                                   COutputHandler * pOutputHandler,
                                   std::ostream * pOstream)
{
  assert(mpProblem && mpMethod);

  mpCrossSectionProblem = dynamic_cast<CCrossSectionProblem *>(mpProblem);
  assert(mpCrossSectionProblem);

  mpTrajectoryMethod = dynamic_cast<CTrajectoryMethod *>(mpMethod);
  assert(mpTrajectoryMethod);

  mpTrajectoryMethod->setProblem(mpCrossSectionProblem);

  bool success = mpMethod->isValidProblem(mpProblem);

  CCopasiParameter * pParameter = mpMethod->getParameter("Integrate Reduced Model");

  if (pParameter != NULL)
    mUpdateMoieties = *pParameter->getValue().pBOOL;
  else
    mUpdateMoieties = false;

  pdelete(mpCurrentState);
  mpCurrentState = new CState(mpCrossSectionProblem->getModel()->getState());
  mpCurrentTime = &mpCurrentState->getTime();

  //mpOutputStartTime = & mpTrajectoryProblem->getOutputStartTime();

  // Handle the time series as a regular output.
  mTimeSeriesRequested = mpCrossSectionProblem->timeSeriesRequested();

  if ((pOutputHandler != NULL) &&
      mTimeSeriesRequested &&
      (of & CCopasiTask::TIME_SERIES))
    {
      mTimeSeries.allocate(20);
      pOutputHandler->addInterface(&mTimeSeries);
    }
  else
    {
      mTimeSeries.clear();
    }

  if (!CCopasiTask::initialize(of, pOutputHandler, pOstream)) success = false;

  return success;
}

bool CCrossSectionTask::process(const bool & useInitialValues)
{
  //*****

  processStart(useInitialValues);

  //*****

  C_FLOAT64 MaxDuration = mpCrossSectionProblem->getDuration();
  //C_FLOAT64 StepSize = mpCrossSectionProblem->getStepSize();
  //C_FLOAT64 StepNumber = fabs(Duration) / StepSize;

  //if (isnan(StepNumber) || StepNumber < 1.0)
  //  StepNumber = 1.0;

  //the output starts only after "outputStartTime" has passed
  mOutputStartTime = *mpCurrentTime + mpCrossSectionProblem->getOutputStartTime();

  //C_FLOAT64 NextTimeToReport;

  const C_FLOAT64 EndTime = *mpCurrentTime + MaxDuration;
  const C_FLOAT64 StartTime = *mpCurrentTime;
  C_FLOAT64 CompareEndTime;

  // It suffices to reach the end time within machine precision
  CompareEndTime = EndTime - 100.0 * (fabs(EndTime) * std::numeric_limits< C_FLOAT64 >::epsilon() + std::numeric_limits< C_FLOAT64 >::min());

  //unsigned C_INT32 StepCounter = 1;

  //if (StepSize == 0.0 && Duration != 0.0)
  //  {
  //    CCopasiMessage(CCopasiMessage::ERROR, MCTrajectoryProblem + 1, StepSize);
  //    return false;
  //  }

  output(COutputInterface::BEFORE);

  bool flagProceed = true;
  C_FLOAT64 handlerFactor = 100.0 / MaxDuration;

  C_FLOAT64 Percentage = 0;
  size_t hProcess;

  if (mpCallBack != NULL)
    {
      mpCallBack->setName("performing simulation...");
      C_FLOAT64 hundred = 100;
      hProcess = mpCallBack->addItem("Completion",
                                     Percentage,
                                     &hundred);
    }

  try
    {
      do
        {
          // This is numerically more stable then adding
          // mpTrajectoryProblem->getStepSize().
          //NextTimeToReport =
          //  StartTime + (EndTime - StartTime) * StepCounter++ / StepNumber;

          flagProceed &= processStep(EndTime);

          if (mpCallBack != NULL )
            {
              Percentage = (*mpCurrentTime - StartTime) * handlerFactor;
              flagProceed &= mpCallBack->progressItem(hProcess);
            }

          //if ((*mpLessOrEqual)(mOutputStartTime, *mpCurrentTime))
          //  {
          //    output(COutputInterface::DURING);
          //  }
        }
      while ((*mpCurrentTime < CompareEndTime) && flagProceed);
    }

  catch (int)
    {
      mpCrossSectionProblem->getModel()->setState(*mpCurrentState);
      mpCrossSectionProblem->getModel()->updateSimulatedValues(mUpdateMoieties);

      if (mpCallBack != NULL) mpCallBack->finishItem(hProcess);

      output(COutputInterface::AFTER);

      CCopasiMessage(CCopasiMessage::EXCEPTION, MCTrajectoryMethod + 16);
    }

  catch (CCopasiException & Exception)
    {
      mpCrossSectionProblem->getModel()->setState(*mpCurrentState);
      mpCrossSectionProblem->getModel()->updateSimulatedValues(mUpdateMoieties);

      if (mpCallBack != NULL) mpCallBack->finishItem(hProcess);

      output(COutputInterface::AFTER);

      throw CCopasiException(Exception.getMessage());
    }

  if (mpCallBack != NULL) mpCallBack->finishItem(hProcess);

  output(COutputInterface::AFTER);

  return true;
}

void CCrossSectionTask::processStart(const bool & useInitialValues)
{
  if (useInitialValues)
    mpCrossSectionProblem->getModel()->applyInitialValues();

  *mpCurrentState = mpCrossSectionProblem->getModel()->getState();

  mpTrajectoryMethod->setCurrentState(mpCurrentState);
  mpTrajectoryMethod->start(mpCurrentState);

  return;
}

bool CCrossSectionTask::processStep(const C_FLOAT64 & endTime)
{
  CModel * pModel = mpCrossSectionProblem->getModel();
  bool StateChanged = false;
  bool proceed = true;

  C_FLOAT64 Tolerance = 100.0 * (fabs(endTime) * std::numeric_limits< C_FLOAT64 >::epsilon() + std::numeric_limits< C_FLOAT64 >::min());
  C_FLOAT64 NextTime = endTime;

  while (proceed)
    {
      // TODO Provide a call back method for resolving simultaneous assignments.
      StateChanged |= pModel->processQueue(*mpCurrentTime, false, NULL);

      if (StateChanged)
        {
          if (mOutputStartTime <= *mpCurrentTime )
            {
              output(COutputInterface::DURING);
            }

          *mpCurrentState = pModel->getState();
          mpTrajectoryMethod->stateChanged();
          StateChanged = false;
        }

      // std::min suffices since events are only supported in forward integration.
      NextTime = std::min(endTime, pModel->getProcessQueueExecutionTime());

      switch (mpTrajectoryMethod->step(NextTime - *mpCurrentTime))
        {
          case CTrajectoryMethod::NORMAL:
            pModel->setState(*mpCurrentState);
            pModel->updateSimulatedValues(mUpdateMoieties);

            if ((mOutputStartTime <= *mpCurrentTime) &&
                *mpCurrentTime == pModel->getProcessQueueExecutionTime() )
              {
                output(COutputInterface::DURING);
              }

            // TODO Provide a call back method for resolving simultaneous assignments.
            StateChanged |= pModel->processQueue(*mpCurrentTime, true, NULL);

            if (fabs(*mpCurrentTime - endTime) < Tolerance)
              return true;

            if ((mOutputStartTime <= *mpCurrentTime) &&
                StateChanged )
              {
                output(COutputInterface::DURING);
              }

            break;

          case CTrajectoryMethod::ROOT:
            pModel->setState(*mpCurrentState);
            pModel->updateSimulatedValues(mUpdateMoieties);

            pModel->processRoots(*mpCurrentTime, true, true, mpTrajectoryMethod->getRoots());

            if ((mOutputStartTime <= *mpCurrentTime) &&
                *mpCurrentTime == pModel->getProcessQueueExecutionTime() )
              {
                output(COutputInterface::DURING);
              }

            // TODO Provide a call back method for resolving simultaneous assignments.
            StateChanged |= pModel->processQueue(*mpCurrentTime, true, NULL);

            pModel->processRoots(*mpCurrentTime, false, true, mpTrajectoryMethod->getRoots());

            // If the root happens to coincide with end of the step we have to return and
            // inform the integrator of eventual state changes.
            if (fabs(*mpCurrentTime - endTime) < Tolerance)
              {
                if (StateChanged)
                  {
                    *mpCurrentState = pModel->getState();
                    mpTrajectoryMethod->stateChanged();
                    StateChanged = false;
                  }

                return true;
              }

            if ((mOutputStartTime <= *mpCurrentTime)  &&
                (StateChanged ||
                 *mpCurrentTime == pModel->getProcessQueueExecutionTime()))
              {
                output(COutputInterface::DURING);
              }

            break;

          case CTrajectoryMethod::FAILURE:
            CCopasiMessage(CCopasiMessage::EXCEPTION, MCTrajectoryMethod + 12);

            return false;
            break;
        }

      proceed = mpCallBack == NULL || mpCallBack->proceed();
    }

  return proceed;
}

bool CCrossSectionTask::restore()
{
  bool success = CCopasiTask::restore();

  if (mUpdateModel)
    {
      CModel * pModel = mpProblem->getModel();

      pModel->setState(*mpCurrentState);
      pModel->updateSimulatedValues(mUpdateMoieties);
      pModel->setInitialState(pModel->getState());
      pModel->updateInitialValues();
    }

  return success;
}

bool CCrossSectionTask::setMethodType(const int & type)
{
  CCopasiMethod::SubType Type = (CCopasiMethod::SubType) type;

  if (!isValidMethod(Type, ValidMethods)) return false;

  if (mpMethod->getSubType() == Type) return true;

  pdelete(mpMethod);
  mpMethod = createMethod(Type);
  this->add(mpMethod, true);

  CCopasiParameter * pParameter = mpMethod->getParameter("Integrate Reduced Model");

  if (pParameter != NULL)
    mUpdateMoieties = *pParameter->getValue().pBOOL;
  else
    mUpdateMoieties = false;

  return true;
}

// virtual
CCopasiMethod * CCrossSectionTask::createMethod(const int & type) const
{
  CCopasiMethod::SubType Type = (CCopasiMethod::SubType) type;

  return CTrajectoryMethod::createMethod(Type);
}

CState * CCrossSectionTask::getState()
{return mpCurrentState;}

const CTimeSeries & CCrossSectionTask::getTimeSeries() const
{return mTimeSeries;}
<commit_msg>debugging output added. This will be removed soon.<commit_after>// Copyright (C) 2010 - 2012 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.

/**
 * CCrossSectionTask class.
 *
 * This class implements a cross section task.
 */

#include <string>
#include <cmath>

#include "copasi.h"

#include "CCrossSectionTask.h"
#include "CCrossSectionProblem.h"
//#include "CCrossSectionMethod.h"
#include "model/CModel.h"
#include "model/CMathModel.h"
#include "model/CState.h"
#include "report/CKeyFactory.h"
#include "report/CReport.h"
#include "utilities/CProcessReport.h"
#include "utilities/CCopasiException.h"
#include  "CopasiDataModel/CCopasiDataModel.h"

const unsigned int CCrossSectionTask::ValidMethods[] =
{
  CCopasiMethod::deterministic,
  //  CCopasiMethod::stochastic,
  //CCopasiMethod::directMethod,
  //CCopasiMethod::tauLeap,
  //CCopasiMethod::adaptiveSA,
  //CCopasiMethod::hybrid,
  //CCopasiMethod::hybridLSODA,
#ifdef COPASI_DEBUG
  CCopasiMethod::DsaLsodar,
#endif // COPASI_DEBUG
  CCopasiMethod::unset
};

CCrossSectionTask::CCrossSectionTask(const CCopasiContainer * pParent):
  CCopasiTask(CCopasiTask::crosssection, pParent),
  mTimeSeriesRequested(true),
  mTimeSeries(),
  mpCrossSectionProblem(NULL),
  mpTrajectoryMethod(NULL),
  mUpdateMoieties(false),
  mpCurrentState(NULL),
  mpCurrentTime(NULL),
  mOutputStartTime(0.0)
{
  mpProblem = new CCrossSectionProblem(this);
  mpMethod = createMethod(CCopasiMethod::deterministic);
  this->add(mpMethod, true);

/*  CCopasiParameter * pParameter = mpMethod->getParameter("Integrate Reduced Model");

  if (pParameter != NULL)
    mUpdateMoieties = *pParameter->getValue().pBOOL;
  else
    mUpdateMoieties = false;*/
}

CCrossSectionTask::CCrossSectionTask(const CCrossSectionTask & src,
                                     const CCopasiContainer * pParent):
  CCopasiTask(src, pParent),
  mTimeSeriesRequested(src.mTimeSeriesRequested),
  mTimeSeries(),
  mpCrossSectionProblem(NULL),
  mpTrajectoryMethod(NULL),
  mUpdateMoieties(false),
  mpCurrentState(NULL),
  mpCurrentTime(NULL),
  mOutputStartTime(0.0)
{
  mpProblem =
    new CCrossSectionProblem(*static_cast< CCrossSectionProblem * >(src.mpProblem), this);

  mpMethod = createMethod(src.mpMethod->getSubType());
  * mpMethod = * src.mpMethod;

  mpMethod->elevateChildren();

  this->add(mpMethod, true);

/*  CCopasiParameter * pParameter = mpMethod->getParameter("Integrate Reduced Model");

  if (pParameter != NULL)
    mUpdateMoieties = *pParameter->getValue().pBOOL;
  else
    mUpdateMoieties = false;*/
}

CCrossSectionTask::~CCrossSectionTask()
{
  cleanup();
}

void CCrossSectionTask::cleanup()
{
  pdelete(mpCurrentState);
}

bool CCrossSectionTask::initialize(const OutputFlag & of,
                                   COutputHandler * pOutputHandler,
                                   std::ostream * pOstream)
{
  assert(mpProblem && mpMethod);

  mpCrossSectionProblem = dynamic_cast<CCrossSectionProblem *>(mpProblem);
  assert(mpCrossSectionProblem);

  mpTrajectoryMethod = dynamic_cast<CTrajectoryMethod *>(mpMethod);
  assert(mpTrajectoryMethod);

  mpTrajectoryMethod->setProblem(mpCrossSectionProblem);

  bool success = mpMethod->isValidProblem(mpProblem);

  CCopasiParameter * pParameter = mpMethod->getParameter("Integrate Reduced Model");

  if (pParameter != NULL)
    mUpdateMoieties = *pParameter->getValue().pBOOL;
  else
    mUpdateMoieties = false;

  pdelete(mpCurrentState);
  mpCurrentState = new CState(mpCrossSectionProblem->getModel()->getState());
  mpCurrentTime = &mpCurrentState->getTime();

  //mpOutputStartTime = & mpTrajectoryProblem->getOutputStartTime();

  // Handle the time series as a regular output.
  mTimeSeriesRequested = mpCrossSectionProblem->timeSeriesRequested();

  if ((pOutputHandler != NULL) &&
      mTimeSeriesRequested &&
      (of & CCopasiTask::TIME_SERIES))
    {
      mTimeSeries.allocate(20);
      pOutputHandler->addInterface(&mTimeSeries);
    }
  else
    {
      mTimeSeries.clear();
    }

  if (!CCopasiTask::initialize(of, pOutputHandler, pOstream)) success = false;

  return success;
}

bool CCrossSectionTask::process(const bool & useInitialValues)
{
  processStart(useInitialValues);

  C_FLOAT64 MaxDuration = mpCrossSectionProblem->getDuration();

  //the output starts only after "outputStartTime" has passed
  mOutputStartTime = *mpCurrentTime + mpCrossSectionProblem->getOutputStartTime();

  //C_FLOAT64 NextTimeToReport;

  const C_FLOAT64 EndTime = *mpCurrentTime + MaxDuration;
  const C_FLOAT64 StartTime = *mpCurrentTime;
  C_FLOAT64 CompareEndTime;

  // It suffices to reach the end time within machine precision
  CompareEndTime = EndTime - 100.0 * (fabs(EndTime) * std::numeric_limits< C_FLOAT64 >::epsilon() + std::numeric_limits< C_FLOAT64 >::min());

  output(COutputInterface::BEFORE);

  bool flagProceed = true;
  C_FLOAT64 handlerFactor = 100.0 / MaxDuration;

  C_FLOAT64 Percentage = 0;
  size_t hProcess;

  if (mpCallBack != NULL)
    {
      mpCallBack->setName("performing simulation...");
      C_FLOAT64 hundred = 100;
      hProcess = mpCallBack->addItem("Completion",
                                     Percentage,
                                     &hundred);
    }

  try
    {
      do
        {
          // This is numerically more stable then adding
          // mpTrajectoryProblem->getStepSize().
          //NextTimeToReport =
          //  StartTime + (EndTime - StartTime) * StepCounter++ / StepNumber;

          flagProceed &= processStep(EndTime);

          if (mpCallBack != NULL )
            {
              Percentage = (*mpCurrentTime - StartTime) * handlerFactor;
              flagProceed &= mpCallBack->progressItem(hProcess);
            }

          //if ((*mpLessOrEqual)(mOutputStartTime, *mpCurrentTime))
          //  {
          //    output(COutputInterface::DURING);
          //  }
        }
      while ((*mpCurrentTime < CompareEndTime) && flagProceed);
    }

  catch (int)
    {
      mpCrossSectionProblem->getModel()->setState(*mpCurrentState);
      mpCrossSectionProblem->getModel()->updateSimulatedValues(mUpdateMoieties);

      if (mpCallBack != NULL) mpCallBack->finishItem(hProcess);

      output(COutputInterface::AFTER);

      CCopasiMessage(CCopasiMessage::EXCEPTION, MCTrajectoryMethod + 16);
    }

  catch (CCopasiException & Exception)
    {
      mpCrossSectionProblem->getModel()->setState(*mpCurrentState);
      mpCrossSectionProblem->getModel()->updateSimulatedValues(mUpdateMoieties);

      if (mpCallBack != NULL) mpCallBack->finishItem(hProcess);

      output(COutputInterface::AFTER);

      throw CCopasiException(Exception.getMessage());
    }

  if (mpCallBack != NULL) mpCallBack->finishItem(hProcess);

  output(COutputInterface::AFTER);

  return true;
}

void CCrossSectionTask::processStart(const bool & useInitialValues)
{
  if (useInitialValues)
    mpCrossSectionProblem->getModel()->applyInitialValues();

  *mpCurrentState = mpCrossSectionProblem->getModel()->getState();

  mpTrajectoryMethod->setCurrentState(mpCurrentState);
  mpTrajectoryMethod->start(mpCurrentState);

  return;
}

bool CCrossSectionTask::processStep(const C_FLOAT64 & endTime)
{
  CModel * pModel = mpCrossSectionProblem->getModel();
  bool StateChanged = false;
  bool proceed = true;

  C_FLOAT64 Tolerance = 100.0 * (fabs(endTime) * std::numeric_limits< C_FLOAT64 >::epsilon() + std::numeric_limits< C_FLOAT64 >::min());
  C_FLOAT64 NextTime = endTime;

  while (proceed)
    {
      // TODO Provide a call back method for resolving simultaneous assignments.
        pModel->getMathModel()->getProcessQueue().printDebug();
      StateChanged |= pModel->processQueue(*mpCurrentTime, false, NULL);
        pModel->getMathModel()->getProcessQueue().printDebug();

      if (StateChanged)
        {
          if (mOutputStartTime <= *mpCurrentTime )
            {
              output(COutputInterface::DURING);
            }

          *mpCurrentState = pModel->getState();
          mpTrajectoryMethod->stateChanged();
          StateChanged = false;
        }

      // std::min suffices since events are only supported in forward integration.
      NextTime = std::min(endTime, pModel->getProcessQueueExecutionTime());

      switch (mpTrajectoryMethod->step(NextTime - *mpCurrentTime))
        {
          case CTrajectoryMethod::NORMAL:
            pModel->setState(*mpCurrentState);
            pModel->updateSimulatedValues(mUpdateMoieties);

            if ((mOutputStartTime <= *mpCurrentTime) &&
                *mpCurrentTime == pModel->getProcessQueueExecutionTime() )
              {
                output(COutputInterface::DURING);
              }

            // TODO Provide a call back method for resolving simultaneous assignments.
            StateChanged |= pModel->processQueue(*mpCurrentTime, true, NULL);

            if (fabs(*mpCurrentTime - endTime) < Tolerance)
              return true;

            if ((mOutputStartTime <= *mpCurrentTime) &&
                StateChanged )
              {
                output(COutputInterface::DURING);
              }

            break;

          case CTrajectoryMethod::ROOT:
            pModel->setState(*mpCurrentState);
            pModel->updateSimulatedValues(mUpdateMoieties);

                pModel->getMathModel()->getProcessQueue().printDebug();
            pModel->processRoots(*mpCurrentTime, true, true, mpTrajectoryMethod->getRoots());
                pModel->getMathModel()->getProcessQueue().printDebug();

            if ((mOutputStartTime <= *mpCurrentTime) &&
                *mpCurrentTime == pModel->getProcessQueueExecutionTime() )
              {
                output(COutputInterface::DURING);
              }

            // TODO Provide a call back method for resolving simultaneous assignments.
            StateChanged |= pModel->processQueue(*mpCurrentTime, true, NULL);

                pModel->getMathModel()->getProcessQueue().printDebug();
            pModel->processRoots(*mpCurrentTime, false, true, mpTrajectoryMethod->getRoots());
                pModel->getMathModel()->getProcessQueue().printDebug();

            // If the root happens to coincide with end of the step we have to return and
            // inform the integrator of eventual state changes.
            if (fabs(*mpCurrentTime - endTime) < Tolerance)
              {
                if (StateChanged)
                  {
                    *mpCurrentState = pModel->getState();
                    mpTrajectoryMethod->stateChanged();
                    StateChanged = false;
                  }

                return true;
              }

            if ((mOutputStartTime <= *mpCurrentTime)  &&
                (StateChanged ||
                 *mpCurrentTime == pModel->getProcessQueueExecutionTime()))
              {
                output(COutputInterface::DURING);
              }

            break;

          case CTrajectoryMethod::FAILURE:
            CCopasiMessage(CCopasiMessage::EXCEPTION, MCTrajectoryMethod + 12);

            return false;
            break;
        }

      proceed = mpCallBack == NULL || mpCallBack->proceed();
    }

  return proceed;
}

bool CCrossSectionTask::restore()
{
  bool success = CCopasiTask::restore();

  if (mUpdateModel)
    {
      CModel * pModel = mpProblem->getModel();

      pModel->setState(*mpCurrentState);
      pModel->updateSimulatedValues(mUpdateMoieties);
      pModel->setInitialState(pModel->getState());
      pModel->updateInitialValues();
    }

  return success;
}

bool CCrossSectionTask::setMethodType(const int & type)
{
  CCopasiMethod::SubType Type = (CCopasiMethod::SubType) type;

  if (!isValidMethod(Type, ValidMethods)) return false;

  if (mpMethod->getSubType() == Type) return true;

  pdelete(mpMethod);
  mpMethod = createMethod(Type);
  this->add(mpMethod, true);

  CCopasiParameter * pParameter = mpMethod->getParameter("Integrate Reduced Model");

  if (pParameter != NULL)
    mUpdateMoieties = *pParameter->getValue().pBOOL;
  else
    mUpdateMoieties = false;

  return true;
}

// virtual
CCopasiMethod * CCrossSectionTask::createMethod(const int & type) const
{
  CCopasiMethod::SubType Type = (CCopasiMethod::SubType) type;

  return CTrajectoryMethod::createMethod(Type);
}

CState * CCrossSectionTask::getState()
{return mpCurrentState;}

const CTimeSeries & CCrossSectionTask::getTimeSeries() const
{return mTimeSeries;}
<|endoftext|>


<commit_before>#include "Note.h"

using namespace std;

struct Note::Parameters Note::params;

Note::Note(Score *score, long id)
  :score(score), id(id), self(){}

Note::Note(Score *score, long id, long ms_start, unsigned char base_pitch, short base_velocity)
  :score(score),id(id),self()
{
  this->setStart(ms_start);
  this->setBasePitch(base_pitch);
  self.base_velocity = base_velocity;
}

Note::Note(const Note& other)
{
  score = other.score;
  id = other.id;
  self = other.self;
  if (other.self.margin != 0) {
    self.margin = new pair<short,short>(*(other.self.margin));
  }
  if (other.self.padding != 0) {
    self.padding = new pair<short,short>(*(other.self.padding));
  }
  if (other.self.preu != 0) {
    self.preu = new short (*(other.self.preu));
  }
  if (other.self.ovrl != 0) {
    self.ovrl = new short (*(other.self.ovrl));
  }
  if (other.self.cons != 0) {
    self.cons = new short (*(other.self.cons));
  }
}

Note::~Note()
{
  if (self.margin != 0) {
    delete self.margin;
    self.margin = 0;
  }
  if (self.padding != 0) {
    delete self.padding;
    self.padding = 0;
  }
  if (self.preu != 0) {
    delete self.preu;
    self.preu = 0;
  }
  if (self.ovrl != 0) {
    delete self.ovrl;
    self.ovrl = 0;
  }
  if (self.cons != 0) {
    delete self.cons;
    self.cons = 0;
  }
}

Note& Note::operator=(const Note& other)
{
  if (this != &other) {
    score = other.score;
    id = other.id;
    self = other.self;
    if (other.self.margin != 0) {
      self.margin = new pair<short,short>(*(other.self.margin));
    }
    if (other.self.padding != 0) {
      self.padding = new pair<short,short>(*(other.self.padding));
    }
    if (other.self.preu != 0) {
      self.preu = new short (*(other.self.preu));
    }
    if (other.self.ovrl != 0) {
      self.ovrl = new short (*(other.self.ovrl));
    }
    if (other.self.cons != 0) {
      self.cons = new short (*(other.self.cons));
    }
  }
  return *this;
}

bool Note::operator==(const Note& other) const
{
  bool is_eq = true;
  is_eq &= (score == other.score);
  is_eq &= (id == other.id);
  is_eq &= (self.start == other.self.start);
  is_eq &= (self.end == other.self.end);
  is_eq &= (self.pron_alias.prefix == other.self.pron_alias.prefix);
  is_eq &= (self.pron_alias.pron == other.self.pron_alias.pron);
  is_eq &= (self.pron_alias.suffix == other.self.pron_alias.suffix);
  is_eq &= (self.base_pitch == other.self.base_pitch);
  is_eq &= (self.base_velocity == other.self.base_velocity);
  is_eq &= (self.velocity_points == other.self.velocity_points);
  if (self.margin!=other.self.margin && self.margin!=0 && other.self.margin!=0) {
    is_eq &= (*self.margin!=*other.self.margin);
  }
  if (self.padding!=other.self.padding && self.padding!=0 && other.self.padding!=0) {
    is_eq &= (*self.padding!=*other.self.padding);
  }
  is_eq &= (this->getPreu() == other.getPreu());
  is_eq &= (this->getOvrl() == other.getOvrl());
  is_eq &= (this->getCons() == other.getCons());
  is_eq &= (self.is_vcv == other.self.is_vcv);
  return is_eq;
}

bool Note::operator!=(const Note& other) const
{
    return !(*this == other);
}

/*
 * accessor
 */
long Note::getId() const
{
  return id;
}

long Note::getStart() const
{
  return self.start;
}

long Note::getPronStart() const
{
  return self.start - getPreu() - ((getOvrl()<0)?getOvrl():0) + score->getMargin() + getFrontMargin();
}

void Note::setStart(long ms_start)
{
  this->self.start = ms_start;
}

long Note::getEnd() const
{
  return self.end;
}

long Note::getPronEnd() const
{
  long tmp_pron_end = self.end + score->getMargin() - getBackMargin();
  if (getPronStart() > tmp_pron_end) {
    cerr << "[Note::getPronEnd] pron_start > pron_end" << endl;
    return getPronStart()+1;
  }
  return tmp_pron_end;
}

void Note::setEnd(long ms_end)
{
  self.end = ms_end;
}

short Note::getFrontMargin() const
{
  if (self.margin != 0) {
    return self.margin->first;
  }

  const Note* note_prev = score->getPrevNote(this);
  if (note_prev == 0) {
    return 0;
  }

  if (isVCV()) {
    long ms_prev_cons_start = note_prev->getStart() - note_prev->getPreu() + note_prev->getCons();
    long ms_start = getStart() - getPreu();
    if (ms_start < ms_prev_cons_start) {
      long tmp_margin = ms_prev_cons_start - ms_start;
      long tmp_padding = max(params.ms_front_padding, params.ms_back_padding);
      tmp_padding = min(tmp_padding, (long)getOvrl());
      if (getPreu()-tmp_margin > tmp_padding) {
        return tmp_margin;
      } else {
        return getPreu() - tmp_padding;
      }
    }
  }
  return 0;
}

short Note::getBackMargin() const
{
  if (self.margin != 0) {
    return self.margin->second;
  }

  const Note* note_next = score->getNextNote(this);
  if (note_next==0 || getEnd() < note_next->getStart()){
    return 0;
  }

  if (isVCV() || note_next->isVCV()) {
    return getEnd()+score->getMargin() - (note_next->getPronStart()+note_next->getFrontPadding());
  }
  return note_next->getPreu() - note_next->getOvrl();
}

void Note::setMargin(short front, short back)
{
  if (self.margin != 0) {
    delete self.margin;
    self.margin = 0;
  }
  self.margin = new pair<short,short>(front, back);
}

short Note::getFrontPadding() const
{
  if (self.padding != 0) {
    return self.padding->first;
  }

  if (isVCV()) {
    long tmp_padding = getOvrl()-getFrontMargin(), default_padding = max(params.ms_front_padding, params.ms_back_padding);
    return max(tmp_padding, default_padding);
  }
  return params.ms_front_padding;
}

short Note::getBackPadding() const
{
  if (self.padding != 0) {
    return self.padding->second;
  }

  const Note* note_next = score->getNextNote(this);
  if (note_next!=0 && note_next->isVCV()) {
    if (note_next!=0) {
      return note_next->getFrontPadding();
    }
  }
  return max(params.ms_front_padding, params.ms_back_padding);
}

void Note::setPadding(short front, short back)
{
  if (self.padding != 0) {
    delete self.padding;
    self.padding = 0;
  }
  self.padding = new pair<short,short>(front, back);
}

PronunciationAlias Note::getPronAlias() const
{
  return self.pron_alias;
}

wstring Note::getPronAliasString() const
{
  return self.pron_alias.getAliasString();
}

void Note::setPronAlias(PronunciationAlias voice_alias)
{
  self.pron_alias = voice_alias;
}

void Note::setPronAlias(const std::wstring& alias)
{
  PronunciationAlias voice_alias(alias);
  setPronAlias(voice_alias);
}

unsigned char Note::getBasePitch() const
{
  return self.base_pitch;
}

float Note::getBasePitchHz() const
{
  return 440.0 * pow(2.0,(self.base_pitch-(int)0x45)/12.0);
}

void Note::setBasePitch(unsigned char base_pitch)
{
  this->self.base_pitch = base_pitch;
}

short Note::getBaseVelocity() const
{
  return self.base_velocity;
}

void Note::setBaseVelocity(short base_velocity)
{
  self.base_velocity = base_velocity;
}

void Note::addVelocityPoint(long ms, short vel)
{
  self.velocity_points.push_back(make_pair(ms, vel));
}

void Note::setVelocityPoints(const vector< pair<long,short> > &velocity_points)
{
  self.velocity_points = velocity_points;
}

const vector< pair<long,short> >& Note::getVelocityPoints() const
{
  return self.velocity_points;
}

short Note::getVelocityPointNum() const
{
  return self.velocity_points.size();
}

vector<short> Note::getVelocities() const
{
  long ms_pron_start=getPronStart(), ms_pron_end=getPronEnd();
  long velocities_size = ms_pron_end-((getPronStart()>0)?ms_pron_start:0);
  vector<short> velocities(velocities_size, self.base_velocity*(params.auto_vowel_combining?params.vowel_combining_volume:1.0));
  vector< pair<long,short> > tmp_velocity_points = getVelocityPoints();

  if (tmp_velocity_points.size() > 0) {
    // sanitize
    map<long,short> tmp_vels;
    for (vector< pair<long,short> >::iterator it=tmp_velocity_points.begin(); it!=tmp_velocity_points.end(); ++it) {
      long tmp_ms = (it->first)<0?velocities_size+it->first:it->first;
      if (tmp_ms < velocities_size && tmp_ms >= 0)
        tmp_vels[tmp_ms] = it->second;
    }
    // vels to velocities
    for (map<long,short>::iterator it=++tmp_vels.begin(); it!=tmp_vels.end(); ++it) {
      for (size_t i=0; i<it->first-boost::prior(it)->first; i++) {
        velocities[i+boost::prior(it)->first] =
          (1.0/(it->first-boost::prior(it)->first)*i*(it->second-boost::prior(it)->second)+boost::prior(it)->second);
      }
    }
  }

  // padding
  short padding_front=getFrontPadding(), padding_back=getBackPadding();
  for (size_t i=0; i<padding_front; i++) {
    velocities[i] *= i / (double)padding_front;
  }
  for (size_t i=0; i<padding_back; i++) {
    velocities[velocities.size()-1-i] *= i / (double)padding_back;
  }

  return velocities;
}

bool Note::isPreu() const
{
  return self.preu!=0;
}

short Note::getPreu() const
{
  return (self.preu==0)?0:*self.preu;
}

void Note::setPreu(short preu)
{
  if (self.preu != 0) {
    delete self.preu;
    self.preu = 0;
  }
  self.preu = new short (preu);
}

bool Note::isOvrl() const
{
  return self.ovrl!=0;
}

short Note::getOvrl() const
{
  return (self.ovrl==0)?0:*self.ovrl;
}

void Note::setOvrl(short ovrl)
{
  if (self.ovrl != 0) {
    delete self.ovrl;
    self.ovrl = 0;
  }
  self.ovrl = new short (ovrl);
}

bool Note::isCons() const
{
  return self.cons!=0;
}

short Note::getCons() const
{
  return (self.cons==0)?0:*self.cons;
}

void Note::setCons(short cons)
{
  if (self.cons != 0) {
    delete self.cons;
    self.cons = 0;
  }
  self.cons = new short (cons);
}

bool Note::isVCV() const
{
  return self.is_vcv;
}

void Note::isVCV(bool is_vcv)
{
  self.is_vcv = is_vcv;
}
<commit_msg>refactoring<commit_after>#include "Note.h"

using namespace std;

struct Note::Parameters Note::params;

Note::Note(Score *score, long id)
  :score(score), id(id), self(){}

Note::Note(Score *score, long id, long ms_start, unsigned char base_pitch, short base_velocity)
  :score(score),id(id),self()
{
  this->setStart(ms_start);
  this->setBasePitch(base_pitch);
  self.base_velocity = base_velocity;
}

Note::Note(const Note& other)
{
  score = other.score;
  id = other.id;
  self = other.self;
  if (other.self.margin != 0) {
    self.margin = new pair<short,short>(*(other.self.margin));
  }
  if (other.self.padding != 0) {
    self.padding = new pair<short,short>(*(other.self.padding));
  }
  if (other.self.preu != 0) {
    self.preu = new short (*(other.self.preu));
  }
  if (other.self.ovrl != 0) {
    self.ovrl = new short (*(other.self.ovrl));
  }
  if (other.self.cons != 0) {
    self.cons = new short (*(other.self.cons));
  }
}

Note::~Note()
{
  if (self.margin != 0) {
    delete self.margin;
    self.margin = 0;
  }
  if (self.padding != 0) {
    delete self.padding;
    self.padding = 0;
  }
  if (self.preu != 0) {
    delete self.preu;
    self.preu = 0;
  }
  if (self.ovrl != 0) {
    delete self.ovrl;
    self.ovrl = 0;
  }
  if (self.cons != 0) {
    delete self.cons;
    self.cons = 0;
  }
}

Note& Note::operator=(const Note& other)
{
  if (this != &other) {
    score = other.score;
    id = other.id;
    self = other.self;
    if (other.self.margin != 0) {
      self.margin = new pair<short,short>(*(other.self.margin));
    }
    if (other.self.padding != 0) {
      self.padding = new pair<short,short>(*(other.self.padding));
    }
    if (other.self.preu != 0) {
      self.preu = new short (*(other.self.preu));
    }
    if (other.self.ovrl != 0) {
      self.ovrl = new short (*(other.self.ovrl));
    }
    if (other.self.cons != 0) {
      self.cons = new short (*(other.self.cons));
    }
  }
  return *this;
}

bool Note::operator==(const Note& other) const
{
  bool is_eq = true;
  is_eq &= (score == other.score);
  is_eq &= (id == other.id);
  is_eq &= (self.start == other.self.start);
  is_eq &= (self.end == other.self.end);
  is_eq &= (self.pron_alias.prefix == other.self.pron_alias.prefix);
  is_eq &= (self.pron_alias.pron == other.self.pron_alias.pron);
  is_eq &= (self.pron_alias.suffix == other.self.pron_alias.suffix);
  is_eq &= (self.base_pitch == other.self.base_pitch);
  is_eq &= (self.base_velocity == other.self.base_velocity);
  is_eq &= (self.velocity_points == other.self.velocity_points);
  if (self.margin!=other.self.margin && self.margin!=0 && other.self.margin!=0) {
    is_eq &= (*self.margin!=*other.self.margin);
  }
  if (self.padding!=other.self.padding && self.padding!=0 && other.self.padding!=0) {
    is_eq &= (*self.padding!=*other.self.padding);
  }
  is_eq &= (this->getPreu() == other.getPreu());
  is_eq &= (this->getOvrl() == other.getOvrl());
  is_eq &= (this->getCons() == other.getCons());
  is_eq &= (self.is_vcv == other.self.is_vcv);
  return is_eq;
}

bool Note::operator!=(const Note& other) const
{
    return !(*this == other);
}

/*
 * accessor
 */
long Note::getId() const
{
  return id;
}

long Note::getStart() const
{
  return self.start;
}

long Note::getPronStart() const
{
  return self.start - getPreu() - ((getOvrl()<0)?getOvrl():0) + score->getMargin() + getFrontMargin();
}

void Note::setStart(long ms_start)
{
  this->self.start = ms_start;
}

long Note::getEnd() const
{
  return self.end;
}

long Note::getPronEnd() const
{
  long tmp_pron_end = self.end + score->getMargin() - getBackMargin();
  if (getPronStart() > tmp_pron_end) {
    cerr << "[Note::getPronEnd] pron_start > pron_end" << endl;
    return getPronStart()+1;
  }
  return tmp_pron_end;
}

void Note::setEnd(long ms_end)
{
  self.end = ms_end;
}

short Note::getFrontMargin() const
{
  if (self.margin != 0) {
    return self.margin->first;
  }

  const Note* note_prev = score->getPrevNote(this);
  if (note_prev == 0) {
    return 0;
  }

  if (isVCV()) {
    long ms_prev_cons_start = note_prev->getStart() - note_prev->getPreu() + note_prev->getCons();
    long ms_start = getStart() - getPreu();
    if (ms_start < ms_prev_cons_start) {
      long tmp_margin = ms_prev_cons_start - ms_start;
      long tmp_padding = max(params.ms_front_padding, params.ms_back_padding);
      tmp_padding = min(tmp_padding, (long)getOvrl());
      if (getPreu()-tmp_margin > tmp_padding) {
        return tmp_margin;
      } else {
        return getPreu() - tmp_padding;
      }
    }
  }
  return 0;
}

short Note::getBackMargin() const
{
  if (self.margin != 0) {
    return self.margin->second;
  }

  const Note* note_next = score->getNextNote(this);
  if (note_next==0 || getEnd() < note_next->getStart()){
    return 0;
  }

  if (isVCV() || note_next->isVCV()) {
    return getEnd()+score->getMargin() - (note_next->getPronStart()+note_next->getFrontPadding());
  }
  return note_next->getPreu() - note_next->getOvrl();
}

void Note::setMargin(short front, short back)
{
  if (self.margin != 0) {
    delete self.margin;
    self.margin = 0;
  }
  self.margin = new pair<short,short>(front, back);
}

short Note::getFrontPadding() const
{
  if (self.padding != 0) {
    return self.padding->first;
  }

  if (isVCV()) {
    long tmp_padding = getOvrl()-getFrontMargin(), default_padding = max(params.ms_front_padding, params.ms_back_padding);
    return max(tmp_padding, default_padding);
  }
  return params.ms_front_padding;
}

short Note::getBackPadding() const
{
  if (self.padding != 0) {
    return self.padding->second;
  }

  const Note* note_next = score->getNextNote(this);
  if (note_next!=0 && note_next->isVCV()) {
    if (note_next!=0) {
      return note_next->getFrontPadding();
    }
  }
  return max(params.ms_front_padding, params.ms_back_padding);
}

void Note::setPadding(short front, short back)
{
  if (self.padding != 0) {
    delete self.padding;
    self.padding = 0;
  }
  self.padding = new pair<short,short>(front, back);
}

PronunciationAlias Note::getPronAlias() const
{
  return self.pron_alias;
}

wstring Note::getPronAliasString() const
{
  return self.pron_alias.getAliasString();
}

void Note::setPronAlias(PronunciationAlias voice_alias)
{
  self.pron_alias = voice_alias;
}

void Note::setPronAlias(const std::wstring& alias)
{
  PronunciationAlias voice_alias(alias);
  setPronAlias(voice_alias);
}

unsigned char Note::getBasePitch() const
{
  return self.base_pitch;
}

float Note::getBasePitchHz() const
{
  return 440.0 * pow(2.0,(self.base_pitch-(int)0x45)/12.0);
}

void Note::setBasePitch(unsigned char base_pitch)
{
  this->self.base_pitch = base_pitch;
}

short Note::getBaseVelocity() const
{
  return self.base_velocity;
}

void Note::setBaseVelocity(short base_velocity)
{
  self.base_velocity = base_velocity;
}

void Note::addVelocityPoint(long ms, short vel)
{
  self.velocity_points.push_back(make_pair(ms, vel));
}

void Note::setVelocityPoints(const vector< pair<long,short> > &velocity_points)
{
  self.velocity_points = velocity_points;
}

const vector< pair<long,short> >& Note::getVelocityPoints() const
{
  return self.velocity_points;
}

short Note::getVelocityPointNum() const
{
  return self.velocity_points.size();
}

vector<short> Note::getVelocities() const
{
  long ms_pron_start=getPronStart(), ms_pron_end=getPronEnd();
  long velocities_size = ms_pron_end-((getPronStart()>0)?ms_pron_start:0);
  vector<short> velocities(velocities_size, self.base_velocity*(params.auto_vowel_combining?params.vowel_combining_volume:1.0));
  vector< pair<long,short> > tmp_velocity_points = getVelocityPoints();

  if (tmp_velocity_points.size() > 0) {
    // sanitize
    map<long,short> tmp_vels;
    for (vector< pair<long,short> >::iterator it=tmp_velocity_points.begin(); it!=tmp_velocity_points.end(); ++it) {
      long tmp_ms = (it->first)<0?velocities_size+it->first:it->first;
      if (tmp_ms < velocities_size && tmp_ms >= 0)
        tmp_vels[tmp_ms] = it->second;
    }
    // vels to velocities
    for (map<long,short>::iterator it=++tmp_vels.begin(); it!=tmp_vels.end(); ++it) {
      for (size_t i=0; i<it->first-boost::prior(it)->first; i++) {
        velocities[i+boost::prior(it)->first] =
          (1.0/(it->first-boost::prior(it)->first)*i*(it->second-boost::prior(it)->second)+boost::prior(it)->second);
      }
    }
  } else {
	// padding
	short padding_front = getFrontPadding(), padding_back = getBackPadding();
	for (size_t i = 0; i<padding_front; i++) {
		velocities[i] *= i / (double)padding_front;
	}
	for (size_t i = 0; i<padding_back; i++) {
		velocities[velocities.size() - 1 - i] *= i / (double)padding_back;
	}
  }

  return velocities;
}

bool Note::isPreu() const
{
  return self.preu!=0;
}

short Note::getPreu() const
{
  return (self.preu==0)?0:*self.preu;
}

void Note::setPreu(short preu)
{
  if (self.preu != 0) {
    delete self.preu;
    self.preu = 0;
  }
  self.preu = new short (preu);
}

bool Note::isOvrl() const
{
  return self.ovrl!=0;
}

short Note::getOvrl() const
{
  return (self.ovrl==0)?0:*self.ovrl;
}

void Note::setOvrl(short ovrl)
{
  if (self.ovrl != 0) {
    delete self.ovrl;
    self.ovrl = 0;
  }
  self.ovrl = new short (ovrl);
}

bool Note::isCons() const
{
  return self.cons!=0;
}

short Note::getCons() const
{
  return (self.cons==0)?0:*self.cons;
}

void Note::setCons(short cons)
{
  if (self.cons != 0) {
    delete self.cons;
    self.cons = 0;
  }
  self.cons = new short (cons);
}

bool Note::isVCV() const
{
  return self.is_vcv;
}

void Note::isVCV(bool is_vcv)
{
  self.is_vcv = is_vcv;
}
<|endoftext|>


<commit_before>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SkBenchmark.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkDashPathEffect.h"
#include "SkPaint.h"
#include "SkPath.h"
#include "SkRandom.h"
#include "SkString.h"
#include "SkTDArray.h"

/*
 *  Cases to consider:
 *
 *  1. antialiasing on/off (esp. width <= 1)
 *  2. strokewidth == 0, 1, 2
 *  3. hline, vline, diagonal, rect, oval
 *  4. dots [1,1] ([N,N] where N=strokeWidth?) or arbitrary (e.g. [2,1] or [1,2,3,2])
 */
static void path_hline(SkPath* path) {
    path->moveTo(SkIntToScalar(10), SkIntToScalar(10));
    path->lineTo(SkIntToScalar(600), SkIntToScalar(10));
}

class DashBench : public SkBenchmark {
protected:
    SkString            fName;
    SkTDArray<SkScalar> fIntervals;
    int                 fWidth;
    SkPoint             fPts[2];
    bool                fDoClip;

    enum {
        N = SkBENCHLOOP(100)
    };
public:
    DashBench(void* param, const SkScalar intervals[], int count, int width,
              bool doClip = false) : INHERITED(param) {
        fIntervals.append(count, intervals);
        for (int i = 0; i < count; ++i) {
            fIntervals[i] *= width;
        }
        fWidth = width;
        fName.printf("dash_%d_%s", width, doClip ? "clipped" : "noclip");
        fDoClip = doClip;

        fPts[0].set(SkIntToScalar(10), SkIntToScalar(10));
        fPts[1].set(SkIntToScalar(600), SkIntToScalar(10));
    }

    virtual void makePath(SkPath* path) {
        path_hline(path);
    }

protected:
    virtual const char* onGetName() SK_OVERRIDE {
        return fName.c_str();
    }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        SkPaint paint;
        this->setupPaint(&paint);
        paint.setStyle(SkPaint::kStroke_Style);
        paint.setStrokeWidth(SkIntToScalar(fWidth));
        paint.setAntiAlias(false);

        SkPath path;
        this->makePath(&path);

        paint.setPathEffect(new SkDashPathEffect(fIntervals.begin(),
                                                 fIntervals.count(), 0))->unref();

        if (fDoClip) {
            SkRect r = path.getBounds();
            r.inset(-SkIntToScalar(20), -SkIntToScalar(20));
            // now move it so we don't intersect
            r.offset(0, r.height() * 3 / 2);
            canvas->clipRect(r);
        }

        this->handlePath(canvas, path, paint, N);
    }

    virtual void handlePath(SkCanvas* canvas, const SkPath& path,
                            const SkPaint& paint, int N) {
        for (int i = 0; i < N; ++i) {
//            canvas->drawPoints(SkCanvas::kLines_PointMode, 2, fPts, paint);
            canvas->drawPath(path, paint);
        }
    }

private:
    typedef SkBenchmark INHERITED;
};

class RectDashBench : public DashBench {
public:
    RectDashBench(void* param, const SkScalar intervals[], int count, int width, bool doClip = false)
    : INHERITED(param, intervals, count, width) {
        fName.append("_rect");
    }

protected:
    virtual void handlePath(SkCanvas* canvas, const SkPath& path,
                            const SkPaint& paint, int N) SK_OVERRIDE {
        SkPoint pts[2];
        if (!path.isLine(pts) || pts[0].fY != pts[1].fY) {
            this->INHERITED::handlePath(canvas, path, paint, N);
        } else {
            SkRect rect;
            rect.fLeft = pts[0].fX;
            rect.fTop = pts[0].fY - paint.getStrokeWidth() / 2;
            rect.fRight = rect.fLeft + SkIntToScalar(fWidth);
            rect.fBottom = rect.fTop + paint.getStrokeWidth();

            SkPaint p(paint);
            p.setStyle(SkPaint::kFill_Style);
            p.setPathEffect(NULL);

            int count = SkScalarRoundToInt((pts[1].fX - pts[0].fX) / (2*fWidth));
            SkScalar dx = SkIntToScalar(2 * fWidth);

            for (int i = 0; i < N*10; ++i) {
                SkRect r = rect;
                for (int j = 0; j < count; ++j) {
                    canvas->drawRect(r, p);
                    r.offset(dx, 0);
                }
            }
        }
    }

private:
    typedef DashBench INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

static const SkScalar gDots[] = { SK_Scalar1, SK_Scalar1 };

#define PARAM(array)    array, SK_ARRAY_COUNT(array)

static SkBenchmark* gF0(void* p) { return new DashBench(p, PARAM(gDots), 0); }
static SkBenchmark* gF1(void* p) { return new DashBench(p, PARAM(gDots), 1); }
static SkBenchmark* gF2(void* p) { return new DashBench(p, PARAM(gDots), 1, true); }
static SkBenchmark* gF3(void* p) { return new DashBench(p, PARAM(gDots), 4); }
static SkBenchmark* gF4(void* p) { return new RectDashBench(p, PARAM(gDots), 4); }

static BenchRegistry gR0(gF0);
static BenchRegistry gR1(gF1);
static BenchRegistry gR2(gF2);
static BenchRegistry gR3(gF3);
static BenchRegistry gR4(gF4);
<commit_msg>add makedash_ variants to measure applying the dash (not drawing it)<commit_after>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "SkBenchmark.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkDashPathEffect.h"
#include "SkPaint.h"
#include "SkPath.h"
#include "SkRandom.h"
#include "SkString.h"
#include "SkTDArray.h"

/*
 *  Cases to consider:
 *
 *  1. antialiasing on/off (esp. width <= 1)
 *  2. strokewidth == 0, 1, 2
 *  3. hline, vline, diagonal, rect, oval
 *  4. dots [1,1] ([N,N] where N=strokeWidth?) or arbitrary (e.g. [2,1] or [1,2,3,2])
 */
static void path_hline(SkPath* path) {
    path->moveTo(SkIntToScalar(10), SkIntToScalar(10));
    path->lineTo(SkIntToScalar(600), SkIntToScalar(10));
}

class DashBench : public SkBenchmark {
protected:
    SkString            fName;
    SkTDArray<SkScalar> fIntervals;
    int                 fWidth;
    SkPoint             fPts[2];
    bool                fDoClip;

    enum {
        N = SkBENCHLOOP(100)
    };
public:
    DashBench(void* param, const SkScalar intervals[], int count, int width,
              bool doClip = false) : INHERITED(param) {
        fIntervals.append(count, intervals);
        for (int i = 0; i < count; ++i) {
            fIntervals[i] *= width;
        }
        fWidth = width;
        fName.printf("dash_%d_%s", width, doClip ? "clipped" : "noclip");
        fDoClip = doClip;

        fPts[0].set(SkIntToScalar(10), SkIntToScalar(10));
        fPts[1].set(SkIntToScalar(600), SkIntToScalar(10));
    }

    virtual void makePath(SkPath* path) {
        path_hline(path);
    }

protected:
    virtual const char* onGetName() SK_OVERRIDE {
        return fName.c_str();
    }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        SkPaint paint;
        this->setupPaint(&paint);
        paint.setStyle(SkPaint::kStroke_Style);
        paint.setStrokeWidth(SkIntToScalar(fWidth));
        paint.setAntiAlias(false);

        SkPath path;
        this->makePath(&path);

        paint.setPathEffect(new SkDashPathEffect(fIntervals.begin(),
                                                 fIntervals.count(), 0))->unref();

        if (fDoClip) {
            SkRect r = path.getBounds();
            r.inset(-SkIntToScalar(20), -SkIntToScalar(20));
            // now move it so we don't intersect
            r.offset(0, r.height() * 3 / 2);
            canvas->clipRect(r);
        }

        this->handlePath(canvas, path, paint, N);
    }

    virtual void handlePath(SkCanvas* canvas, const SkPath& path,
                            const SkPaint& paint, int N) {
        for (int i = 0; i < N; ++i) {
//            canvas->drawPoints(SkCanvas::kLines_PointMode, 2, fPts, paint);
            canvas->drawPath(path, paint);
        }
    }

private:
    typedef SkBenchmark INHERITED;
};

class RectDashBench : public DashBench {
public:
    RectDashBench(void* param, const SkScalar intervals[], int count, int width, bool doClip = false)
    : INHERITED(param, intervals, count, width) {
        fName.append("_rect");
    }

protected:
    virtual void handlePath(SkCanvas* canvas, const SkPath& path,
                            const SkPaint& paint, int N) SK_OVERRIDE {
        SkPoint pts[2];
        if (!path.isLine(pts) || pts[0].fY != pts[1].fY) {
            this->INHERITED::handlePath(canvas, path, paint, N);
        } else {
            SkRect rect;
            rect.fLeft = pts[0].fX;
            rect.fTop = pts[0].fY - paint.getStrokeWidth() / 2;
            rect.fRight = rect.fLeft + SkIntToScalar(fWidth);
            rect.fBottom = rect.fTop + paint.getStrokeWidth();

            SkPaint p(paint);
            p.setStyle(SkPaint::kFill_Style);
            p.setPathEffect(NULL);

            int count = SkScalarRoundToInt((pts[1].fX - pts[0].fX) / (2*fWidth));
            SkScalar dx = SkIntToScalar(2 * fWidth);

            for (int i = 0; i < N*10; ++i) {
                SkRect r = rect;
                for (int j = 0; j < count; ++j) {
                    canvas->drawRect(r, p);
                    r.offset(dx, 0);
                }
            }
        }
    }

private:
    typedef DashBench INHERITED;
};

static void make_unit_star(SkPath* path, int n) {
    SkScalar rad = -SK_ScalarPI / 2;
    const SkScalar drad = (n >> 1) * SK_ScalarPI * 2 / n;

    path->moveTo(0, -SK_Scalar1);
    for (int i = 1; i < n; i++) {
        rad += drad;
        SkScalar cosV, sinV = SkScalarSinCos(rad, &cosV);
        path->lineTo(cosV, sinV);
    }
    path->close();
}

static void make_poly(SkPath* path) {
    make_unit_star(path, 9);
    SkMatrix matrix;
    matrix.setScale(SkIntToScalar(100), SkIntToScalar(100));
    path->transform(matrix);
}

static void make_quad(SkPath* path) {
    SkScalar x0 = SkIntToScalar(10);
    SkScalar y0 = SkIntToScalar(10);
    path->moveTo(x0, y0);
    path->quadTo(x0,                    y0 + 400 * SK_Scalar1,
                 x0 + 600 * SK_Scalar1, y0 + 400 * SK_Scalar1);
}

static void make_cubic(SkPath* path) {
    SkScalar x0 = SkIntToScalar(10);
    SkScalar y0 = SkIntToScalar(10);
    path->moveTo(x0, y0);
    path->cubicTo(x0,                    y0 + 400 * SK_Scalar1,
                  x0 + 600 * SK_Scalar1, y0 + 400 * SK_Scalar1,
                  x0 + 600 * SK_Scalar1, y0);
}

class MakeDashBench : public SkBenchmark {
    SkString fName;
    SkPath   fPath;
    SkAutoTUnref<SkPathEffect> fPE;

    enum {
        N = SkBENCHLOOP(400)
    };

public:
    MakeDashBench(void* param, void (*proc)(SkPath*), const char name[]) : INHERITED(param) {
        fName.printf("makedash_%s", name);
        proc(&fPath);

        SkScalar vals[] = { SkIntToScalar(4), SkIntToScalar(4) };
        fPE.reset(new SkDashPathEffect(vals, 2, 0));
    }

protected:
    virtual const char* onGetName() SK_OVERRIDE {
        return fName.c_str();
    }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        SkPath dst;
        for (int i = 0; i < N; ++i) {
            SkScalar width = 0;

            fPE->filterPath(&dst, fPath, &width);
            dst.rewind();
        }
    }

private:
    typedef SkBenchmark INHERITED;
};

///////////////////////////////////////////////////////////////////////////////

static const SkScalar gDots[] = { SK_Scalar1, SK_Scalar1 };

#define PARAM(array)    array, SK_ARRAY_COUNT(array)

static SkBenchmark* gF0(void* p) { return new DashBench(p, PARAM(gDots), 0); }
static SkBenchmark* gF1(void* p) { return new DashBench(p, PARAM(gDots), 1); }
static SkBenchmark* gF2(void* p) { return new DashBench(p, PARAM(gDots), 1, true); }
static SkBenchmark* gF3(void* p) { return new DashBench(p, PARAM(gDots), 4); }
static SkBenchmark* gF4(void* p) { return new MakeDashBench(p, make_poly, "poly"); }
static SkBenchmark* gF5(void* p) { return new MakeDashBench(p, make_quad, "quad"); }
static SkBenchmark* gF6(void* p) { return new MakeDashBench(p, make_cubic, "cubic"); }

static BenchRegistry gR0(gF0);
static BenchRegistry gR1(gF1);
static BenchRegistry gR2(gF2);
static BenchRegistry gR3(gF3);
static BenchRegistry gR4(gF4);
static BenchRegistry gR5(gF5);
static BenchRegistry gR6(gF6);
<|endoftext|>


<commit_before>#define NDEBUG

#include <vector>
#include <list>
#include <iterator>
#include <map>
#include <set>
#include <unordered_map>
#include <algorithm>
#include <string>
#include <sstream>

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

using namespace std;

#include "common.h"

/********************************************************************************************/

static void test_list(size_t n)
{
  list<unsigned int> a1, a2;
  for(size_t i = 0; i < n; i++) {
    a1.push_back(rand_get() );
    a2.push_back(rand_get() );
  }
  unsigned int s = 0;
  for (list<unsigned int>::const_iterator ci1 = a1.begin(), ci2 = a2.begin (); ci1 != a1.end(); ++ci1, ++ci2) {
    s += *ci1 * *ci2;
  }
  g_result = s;
}

/********************************************************************************************/

static void test_array(size_t n)
{
  vector<unsigned int> a1, a2;
  for(size_t i = 0; i < n; i++) {
    a1.push_back(rand_get() );
    a2.push_back(rand_get() );
  }
  unsigned int s = 0;
  for(unsigned long i = 0; i < n; i++) {
    s += a1[i] * a2[i];
  }
  g_result = s;
}

/********************************************************************************************/

static void test_rbtree(size_t n)
{
  set<unsigned long> tree;

  for (size_t i = 0; i < n; i++) {
    tree.insert(rand_get());
  }
  rand_init();
  unsigned int s = 0;
  for (size_t i = 0; i < n; i++) {
    set<unsigned long>::iterator it = tree.find(rand_get());
    if (it != tree.end())
      s += *it;
  }
  g_result = s;
}

/********************************************************************************************/

static void
test_dict1(size_t  n)
{
  map<unsigned long, unsigned long> dict;

  for (size_t i = 0; i < n; i++) {
    dict[rand_get()] = rand_get();
  }
  rand_init();
  unsigned int s = 0;
  for (size_t i = 0; i < n; i++) {
    map<unsigned long, unsigned long>::iterator it = dict.find(rand_get());
    if (it != dict.end())
      s += it->second;
  }
  g_result = s;
}

/********************************************************************************************/

static void
test_dict2(size_t  n)
{
  unordered_map<unsigned long, unsigned long> dict;

  for (size_t i = 0; i < n; i++) {
    dict[rand_get()] = rand_get();
  }
  rand_init();
  unsigned int s = 0;
  for (size_t i = 0; i < n; i++) {
    unordered_map<unsigned long, unsigned long>::iterator it = dict.find(rand_get());
    if (it != dict.end())
      s += it->second;
  }
  g_result = s;
}

/********************************************************************************************/

struct char_array_s {
  char a[256];
  char_array_s () { a[0] = 0 ; }
  char_array_s ( const char_array_s & other) { strcpy(a, other.a); }
  bool operator==(const char_array_s &other) const { return strcmp(a, other.a) == 0; }
};

namespace std {
  template <> struct hash<char_array_s> {
    std::size_t operator()(const char_array_s &k) const {
      size_t hash = 0;
      const char *s = k.a;
      while (*s) hash = hash * 31421 + (*s++) + 6927;
      return hash;
    };
  };
}

static void
test_dict_big(size_t  n)
{
  unordered_map<char_array_s, char_array_s> dict;

  for (size_t i = 0; i < n; i++) {
    char_array_s s1, s2;
    sprintf(s1.a, "%u", rand_get());
    sprintf(s2.a, "%u", rand_get());
    dict[s1] = s2;
  }
  rand_init();
  unsigned int s = 0;
  for (size_t i = 0; i < n; i++) {
    char_array_s s1;
    sprintf(s1.a, "%u", rand_get());
    unordered_map<char_array_s, char_array_s>::iterator it = dict.find(s1);
    if (it != dict.end())
      s ++;
  }
  g_result = s;
}

/********************************************************************************************/
static void
test_dict_str(size_t  n)
{
  unordered_map<string, string> dict;

  for (size_t i = 0; i < n; i++) {
    string s1 = static_cast<ostringstream*>( &(ostringstream() << rand_get()) )->str();
    string s2 = static_cast<ostringstream*>( &(ostringstream() << rand_get()) )->str();
    dict[s1] = s2;
  }
  rand_init();
  unsigned int s = 0;
  for (size_t i = 0; i < n; i++) {
    string s1 = static_cast<ostringstream*>( &(ostringstream() << rand_get()) )->str();
    unordered_map<string, string>::iterator it = dict.find(s1);
    if (it != dict.end())
      s ++;
  }
  g_result = s;
}

static void
test_dict_str2(size_t  n)
{
  map<string, string> dict;

  for (size_t i = 0; i < n; i++) {
    string s1 = static_cast<ostringstream*>( &(ostringstream() << rand_get()) )->str();
    string s2 = static_cast<ostringstream*>( &(ostringstream() << rand_get()) )->str();
    dict[s1] = s2;
  }
  rand_init();
  unsigned int s = 0;
  for (size_t i = 0; i < n; i++) {
    string s1 = static_cast<ostringstream*>( &(ostringstream() << rand_get()) )->str();
    map<string, string>::iterator it = dict.find(s1);
    if (it != dict.end())
      s ++;
  }
  g_result = s;
}

/********************************************************************************************/

static void test_sort(size_t n)
{
  vector<float> a1;
  for(size_t i = 0; i < n; i++) {
    a1.push_back(rand_get() );
  }
  sort(a1.begin(), a1.end());
  g_result = a1[0];
}

static void test_stable_sort(size_t n)
{
  vector<float> a1;
  for(size_t i = 0; i < n; i++) {
    a1.push_back(rand_get() );
  }
  stable_sort(a1.begin(), a1.end());
  g_result = a1[0];
}

/********************************************************************************************/

int main(int argc, const char *argv[])
{
  int n = (argc > 1) ? atoi(argv[1]) : 0;
  if (n == 10)
    test_function("List   time",10000000, test_list);
  if (n == 20)
    test_function("Array  time", 100000000, test_array);
  if (n == 30)
    test_function("Rbtree time", 1000000, test_rbtree);
  if (n == 40)
    test_function("Dict(m)time", 1000000, test_dict1);
  if (n == 42)
    test_function("Dict(u)time", 1000000, test_dict2);
  if (n == 41)
    test_function("DictB  time", 1000000, test_dict_big);
  if (n == 43)
    test_function("DictS(u)  time", 1000000, test_dict_str);
  if (n == 44)
    test_function("DictS(m)  time", 1000000, test_dict_str2);
  if (n == 50)
    test_function("Sort   time", 10000000, test_sort);
  if (n == 51)
    test_function("Stable Sort time", 10000000, test_stable_sort);
  exit(0);
}
<commit_msg>Replace complex convertion from int to string into a simple call to to_string<commit_after>#define NDEBUG

#include <vector>
#include <list>
#include <iterator>
#include <map>
#include <set>
#include <unordered_map>
#include <algorithm>
#include <string>
#include <sstream>

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

using namespace std;

#include "common.h"

/********************************************************************************************/

static void test_list(size_t n)
{
  list<unsigned int> a1, a2;
  for(size_t i = 0; i < n; i++) {
    a1.push_back(rand_get() );
    a2.push_back(rand_get() );
  }
  unsigned int s = 0;
  for (list<unsigned int>::const_iterator ci1 = a1.begin(), ci2 = a2.begin (); ci1 != a1.end(); ++ci1, ++ci2) {
    s += *ci1 * *ci2;
  }
  g_result = s;
}

/********************************************************************************************/

static void test_array(size_t n)
{
  vector<unsigned int> a1, a2;
  for(size_t i = 0; i < n; i++) {
    a1.push_back(rand_get() );
    a2.push_back(rand_get() );
  }
  unsigned int s = 0;
  for(unsigned long i = 0; i < n; i++) {
    s += a1[i] * a2[i];
  }
  g_result = s;
}

/********************************************************************************************/

static void test_rbtree(size_t n)
{
  set<unsigned long> tree;

  for (size_t i = 0; i < n; i++) {
    tree.insert(rand_get());
  }
  rand_init();
  unsigned int s = 0;
  for (size_t i = 0; i < n; i++) {
    set<unsigned long>::iterator it = tree.find(rand_get());
    if (it != tree.end())
      s += *it;
  }
  g_result = s;
}

/********************************************************************************************/

static void
test_dict1(size_t  n)
{
  map<unsigned long, unsigned long> dict;

  for (size_t i = 0; i < n; i++) {
    dict[rand_get()] = rand_get();
  }
  rand_init();
  unsigned int s = 0;
  for (size_t i = 0; i < n; i++) {
    map<unsigned long, unsigned long>::iterator it = dict.find(rand_get());
    if (it != dict.end())
      s += it->second;
  }
  g_result = s;
}

/********************************************************************************************/

static void
test_dict2(size_t  n)
{
  unordered_map<unsigned long, unsigned long> dict;

  for (size_t i = 0; i < n; i++) {
    dict[rand_get()] = rand_get();
  }
  rand_init();
  unsigned int s = 0;
  for (size_t i = 0; i < n; i++) {
    unordered_map<unsigned long, unsigned long>::iterator it = dict.find(rand_get());
    if (it != dict.end())
      s += it->second;
  }
  g_result = s;
}

/********************************************************************************************/

struct char_array_s {
  char a[256];
  char_array_s () { a[0] = 0 ; }
  char_array_s ( const char_array_s & other) { strcpy(a, other.a); }
  bool operator==(const char_array_s &other) const { return strcmp(a, other.a) == 0; }
};

namespace std {
  template <> struct hash<char_array_s> {
    std::size_t operator()(const char_array_s &k) const {
      size_t hash = 0;
      const char *s = k.a;
      while (*s) hash = hash * 31421 + (*s++) + 6927;
      return hash;
    };
  };
}

static void
test_dict_big(size_t  n)
{
  unordered_map<char_array_s, char_array_s> dict;

  for (size_t i = 0; i < n; i++) {
    char_array_s s1, s2;
    sprintf(s1.a, "%u", rand_get());
    sprintf(s2.a, "%u", rand_get());
    dict[s1] = s2;
  }
  rand_init();
  unsigned int s = 0;
  for (size_t i = 0; i < n; i++) {
    char_array_s s1;
    sprintf(s1.a, "%u", rand_get());
    unordered_map<char_array_s, char_array_s>::iterator it = dict.find(s1);
    if (it != dict.end())
      s ++;
  }
  g_result = s;
}

/********************************************************************************************/
static void
test_dict_str(size_t  n)
{
  unordered_map<string, string> dict;

  for (size_t i = 0; i < n; i++) {
    string s1 = to_string(rand_get());
    string s2 = to_string(rand_get());
    dict[s1] = s2;
  }
  rand_init();
  unsigned int s = 0;
  for (size_t i = 0; i < n; i++) {
    string s1 = to_string (rand_get());
    unordered_map<string, string>::iterator it = dict.find(s1);
    if (it != dict.end())
      s ++;
  }
  g_result = s;
}

static void
test_dict_str2(size_t  n)
{
  map<string, string> dict;

  for (size_t i = 0; i < n; i++) {
    string s1 = to_string(rand_get());
    string s2 = to_string(rand_get());
    dict[s1] = s2;
  }
  rand_init();
  unsigned int s = 0;
  for (size_t i = 0; i < n; i++) {
    string s1 = to_string(rand_get());
    map<string, string>::iterator it = dict.find(s1);
    if (it != dict.end())
      s ++;
  }
  g_result = s;
}

/********************************************************************************************/

static void test_sort(size_t n)
{
  vector<float> a1;
  for(size_t i = 0; i < n; i++) {
    a1.push_back(rand_get() );
  }
  sort(a1.begin(), a1.end());
  g_result = a1[0];
}

static void test_stable_sort(size_t n)
{
  vector<float> a1;
  for(size_t i = 0; i < n; i++) {
    a1.push_back(rand_get() );
  }
  stable_sort(a1.begin(), a1.end());
  g_result = a1[0];
}

/********************************************************************************************/

int main(int argc, const char *argv[])
{
  int n = (argc > 1) ? atoi(argv[1]) : 0;
  if (n == 10)
    test_function("List   time",10000000, test_list);
  if (n == 20)
    test_function("Array  time", 100000000, test_array);
  if (n == 30)
    test_function("Rbtree time", 1000000, test_rbtree);
  if (n == 40)
    test_function("Dict(m)time", 1000000, test_dict1);
  if (n == 42)
    test_function("Dict(u)time", 1000000, test_dict2);
  if (n == 41)
    test_function("DictB  time", 1000000, test_dict_big);
  if (n == 43)
    test_function("DictS(u)  time", 1000000, test_dict_str);
  if (n == 44)
    test_function("DictS(m)  time", 1000000, test_dict_str2);
  if (n == 50)
    test_function("Sort   time", 10000000, test_sort);
  if (n == 51)
    test_function("Stable Sort time", 10000000, test_stable_sort);
  exit(0);
}
<|endoftext|>


<commit_before><commit_msg>cleanup<commit_after><|endoftext|>


<commit_before>/*

@Copyright Barrett Adair 2015-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

*/

#ifndef BOOST_CLBL_TRTS_HAS_VARARGS_HPP
#define BOOST_CLBL_TRTS_HAS_VARARGS_HPP

#include <boost/callable_traits/detail/core.hpp>

namespace boost { namespace callable_traits {

//[ has_varargs_hpp
/*`[section:ref_has_varargs has_varargs]
[heading Header]
``#include <boost/callable_traits/has_varargs.hpp>``
[heading Definition]
*/

// inherits from either std::true_type or std::false_type
template<typename T>
struct has_varargs;

//<-
template<typename T>
struct has_varargs : detail::traits<
    detail::shallow_decay<T>>::has_varargs {

    using type = typename detail::traits<
        detail::shallow_decay<T>>::has_varargs;
};

#ifdef BOOST_CLBL_TRTS_DISABLE_VARIABLE_TEMPLATES

template<typename T>
struct has_varargs_v {
    static_assert(std::is_same<T, detail::dummy>::value,
        "Variable templates not supported on this compiler.");
};

#else
//->
// only available when variable templates are supported
template<typename T>
//<-
BOOST_CLBL_TRAITS_INLINE_VAR
//->
constexpr bool has_varargs_v = //see below
//<-
    detail::traits<detail::shallow_decay<T>>::has_varargs::value;

#endif

}} // namespace boost::callable_traits
//->

/*`
[heading Constraints]
* none

[heading Behavior]
* `std::false_type` is inherited by `has_varargs<T>` and is aliased by `typename has_varargs<T>::type`, except when one of the following criteria is met, in which case `std::true_type` would be similarly inherited and aliased:
  * `T` is a function, function pointer, or function reference where the function's parameter list includes C-style variadics.
  * `T` is a pointer to a member function with C-style variadics in the parameter list.
  * `T` is a function object with a non-overloaded `operator()`, which has C-style variadics in the parameter list of its `operator()`.
* On compilers that support variable templates, `has_varargs_v<T>` is equivalent to `has_varargs<T>::value`.

[heading Input/Output Examples]
[table
    [[`T`]                              [`has_varargs_v<T>`]]
    [[`void(...)`]                      [`true`]]
    [[`void(int, ...) const`]           [`true`]]
    [[`void(* volatile)(...)`]          [`true`]]
    [[`void(&)(...)`]                   [`true`]]
    [[`void(foo::*)(...) const`]        [`true`]]
    [[`void(*)()`]                      [`false`]]
    [[`void(*&)()`]                     [`false`]]
    [[`int`]                            [`false`]]
    [[`const int`]                      [`false`]]
    [[`int foo::*`]                     [`false`]]
]

[heading Example Program]
[import ../example/has_varargs.cpp]
[has_varargs]
[endsect]
*/
//]

#endif
<commit_msg>Delete has_varargs.hpp<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    vector<int> numeros;
    long int numLeido ,mediana;
    string result = "";
    cin >> numLeido;
    numeros.push_back(numLeido);
    cout << numLeido<< endl;
    int derecha, izquierda, medio, tam=1,pos;
    while(cin >> numLeido){
        izquierda = 0;
        derecha = numeros.size();
        while(true){
            if(numLeido <= numeros[0]){
                numeros.insert(numeros.begin(),numLeido);
                break;
            }
            else if(numLeido >= numeros[numeros.size()-1]){
                numeros.insert(numeros.end(),numLeido);
                break;
            }
            else{
                medio = (derecha + izquierda)/2;
                if( numLeido >= numeros[medio]){
                    if(numLeido <= numeros[medio+1]){
                        numeros.insert(numeros.begin()+medio+1,numLeido);
                        break;
                    }
                    else
                        izquierda=medio+1;
                }
                else{
                    if(numLeido>= numeros[medio-1]){
                        numeros.insert(numeros.begin()+medio,numLeido);
                        break;
                    }
                    else
                        derecha = medio-1;
                }
            }
    	}
    	//busqueda de la media:
        tam++;
        if(tam%2){
            result += to_string(numeros[tam/2]) + "\n";
        }
        else{
            pos = tam/2;
            mediana = (numeros[pos] + numeros[pos-1])/2;
            result += to_string(mediana) + "\n";
        }
    }

    cout << result;
    return 0;
}
<commit_msg>10107 - Median position using sums instead of divisions<commit_after>#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    vector<int> numeros;
    long int numLeido ,mediana;
    string result = "";
    cin >> numLeido;
    numeros.push_back(numLeido);
    cout << numLeido<< endl;
    int derecha, izquierda, medio, tam=1,pos=0;
    while(cin >> numLeido){
        izquierda = 0;
        derecha = numeros.size();
        while(true){
            if(numLeido <= numeros[0]){
                numeros.insert(numeros.begin(),numLeido);
                break;
            }
            else if(numLeido >= numeros[numeros.size()-1]){
                numeros.insert(numeros.end(),numLeido);
                break;
            }
            else{
                medio = (derecha + izquierda)/2;
                if( numLeido >= numeros[medio]){
                    if(numLeido <= numeros[medio+1]){
                        numeros.insert(numeros.begin()+medio+1,numLeido);
                        break;
                    }
                    else
                        izquierda=medio+1;
                }
                else{
                    if(numLeido>= numeros[medio-1]){
                        numeros.insert(numeros.begin()+medio,numLeido);
                        break;
                    }
                    else
                        derecha = medio-1;
                }
            }
    	}
    	//busqueda de la media:
        tam++;
        if(tam%2){
            result += to_string(numeros[pos]) + "\n";
        }
        else{
            //pos = tam/2;
            pos++;
            mediana = (numeros[pos] + numeros[pos-1])/2;
            result += to_string(mediana) + "\n";
        }
    }

    cout << result;
    return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>

#include <boost/bind.hpp>
#include <cetty/service/ClientService.h>
#include <cetty/gearman/builder/GearmanClientBuilder.h>
#include <cetty/gearman/GearmanMessage.h>

using namespace cetty::channel;
using namespace cetty::gearman;
using namespace cetty::bootstrap;
using namespace cetty::service;
using namespace cetty::gearman::builder;

class GearmanEchoClient {
private:
    typedef ::cetty::service::ServiceFuture<GearmanMessagePtr> GearmanServiceFuture;
    typedef boost::intrusive_ptr<GearmanServiceFuture> GearmanServiceFuturePtr;

public:
    GearmanEchoClient(const ClientServicePtr& s): service(s),count(0) {
        future = new GearmanServiceFuture();
        future->addListener(boost::bind(&GearmanEchoClient::replied, this, _1, _2));
    }
    virtual ~GearmanEchoClient() {}

    void sendRequest() {
        ChannelBufferPtr buf = ChannelBuffers::buffer(10);
        buf->writeBytes("hello");

        callMethod(service,GearmanMessage::createsubmitJobMessage("test","1234",buf),future);

        service->write(ChannelMessage(
            GearmanMessage::createsubmitJobMessage("test","1234",buf)));
    }

    void replied(const GearmanServiceFuturePtr& f, const GearmanMessagePtr& resp) {
        ++count;
        if (count < 10000) {
            sendRequest();
        }
    }

private:
    int count;
    ClientServicePtr service;
    GearmanServiceFuturePtr future;
};

int main(int argc, char* argv[]) {
    GearmanClientBuilder builder;
    builder.addConnection("192.168.1.162", 4730);

    ClientServicePtr service = builder.build();
    GearmanEchoClient client(service);
    client.sendRequest();
    service->getCloseFuture()->awaitUninterruptibly();
}
<commit_msg>gearman update<commit_after>#include <stdio.h>

#include <boost/bind.hpp>
#include <cetty/service/ClientService.h>
#include <cetty/gearman/builder/GearmanClientBuilder.h>
#include <cetty/gearman/GearmanMessage.h>

using namespace cetty::channel;
using namespace cetty::gearman;
using namespace cetty::bootstrap;
using namespace cetty::service;
using namespace cetty::gearman::builder;

class GearmanEchoClient {
private:
    typedef ::cetty::service::ServiceFuture<GearmanMessagePtr> GearmanServiceFuture;
    typedef boost::intrusive_ptr<GearmanServiceFuture> GearmanServiceFuturePtr;

public:
    GearmanEchoClient(const ClientServicePtr& s): service(s),count(0) {
        future = new GearmanServiceFuture();
        future->addListener(boost::bind(&GearmanEchoClient::replied, this, _1, _2));
    }
    virtual ~GearmanEchoClient() {}

    void sendRequest() {
        ChannelBufferPtr buf = ChannelBuffers::buffer(10);
        buf->writeBytes("hello");

        callMethod(service,GearmanMessage::createsubmitJobMessage("test","1234",buf),future);

        service->write(ChannelMessage(
                           GearmanMessage::createsubmitJobMessage("test","1234",buf)));
    }

    void replied(const GearmanServiceFuturePtr& f, const GearmanMessagePtr& resp) {
        ++count;

        if (count < 10000) {
            sendRequest();
        }
    }

private:
    int count;
    ClientServicePtr service;
    GearmanServiceFuturePtr future;
};

int main(int argc, char* argv[]) {
    GearmanClientBuilder builder;
    builder.addConnection("192.168.1.162", 4730);

    ClientServicePtr service = builder.build();
    GearmanEchoClient client(service);
    client.sendRequest();
    service->getCloseFuture()->awaitUninterruptibly();
}
<|endoftext|>