Exemplo n.º 1
0
void Startphase::setStatistics(vector<Player*>* gamePlayers) {
	//Select Desired statitics to follow
	int option;
	Statistic* stat = new Statistic();
	do {
		cout << "Select desired statistics to follow: " << endl;
		cout << "0. Follow Number Of Countries per player;" << endl;
		cout << "1. Follow Total Number of Armies per player" << endl;
		cout << "2. Follow Number of cards per player" << endl;
		cout << "3. Done" << endl;
		cin >> option;
		switch (option) {
		case 0:
			stat = new CountriesStat(stat);		// Decorate statistics with Country Stats
			break;
		case 1:
			stat = new ArmiesStat(stat);		// Decorate statistics with Armies Stats
			break;
		case 2:
			stat = new CardsStat(stat);			// Decorate statistics with Cards Stats
		}
	} while (option != 3);

	for (int i = 0; i < gamePlayers->size(); i++) {
		(*gamePlayers)[i]->attach(stat);
		stat->attachPlayer((*gamePlayers)[i]);
	}
}
Exemplo n.º 2
0
/**
 * Example of a test. To be completed.
 *
 */
bool testStatistics()
{
  unsigned int nbok = 0;
  unsigned int nb = 3;
  
  trace.beginBlock ( "Testing Statistics ..." );

  Statistic<double> stat;
  
  for(unsigned int k=0; k < 1000; k++)
    stat.addValue((double)k);
  
  stat.terminate();
  
  trace.info() << "Mean value = "<<stat.mean()  << std::endl;
  nbok += (stat.mean()==499.5) ? 1 : 0; 
  trace.info() << "Variance value = "<<stat.variance()<<std::endl;
  trace.info() << "Max value = "<<stat.max()<<std::endl;
  nbok += (stat.max()==999) ? 1 : 0; 
  trace.info() << "Min value = "<<stat.min()<<std::endl;
  nbok += (stat.min()==0)  ? 1 : 0; 
 
  trace.info() << "(" << nbok << "/" << nb << ") "
         << "true == true" << std::endl;
  trace.endBlock();
  
  return nbok == nb;
}
int main()  {
    Statistic statistic;

    statistic.setUDPTraffic(11);

    statistic.WriteToFile("/re/unitTest/GenerateDataForML/aaa", "aaa");
    return 0;
}
 void PrintStats(const std::string& title, const Statistic& stats)
 {
     using namespace DPL::Colors::Text;
     printf("\n%sResults [%s]: %s\n", BOLD_GREEN_BEGIN, title.c_str(), BOLD_GREEN_END);
     printf("%s%s%3d%s\n", CYAN_BEGIN,     "Total tests:            ", stats.GetTotal(), CYAN_END);
     printf("  %s%s%3d%s\n", CYAN_BEGIN,   "Succeeded:            ", stats.GetPassed(), CYAN_END);
     printf("  %s%s%3d%s\n", CYAN_BEGIN,   "Failed:               ", stats.GetFailed(), CYAN_END);
     printf("  %s%s%3d%s\n", CYAN_BEGIN,   "Ignored:              ", stats.GetIgnored(), CYAN_END);
 }
Exemplo n.º 5
0
void MultyBuffer::ShowStatictics(Statistic& statistic, std::ofstream& resFile)
{
	for(auto i = statistic.begin(); i != statistic.end(); ++i)
	{
		const double average = static_cast<double>(i->second.types) / static_cast<double>( i->second.seconds);

		resFile.write( reinterpret_cast< const char* >(& ( i->first ) ), sizeof( boost::uint32_t ) );
		resFile.write( reinterpret_cast< const char* >( &average ), sizeof(double) );
	}
}
Exemplo n.º 6
0
int main()
{
    Statistic stats;
    stats.Add(5);
    stats.Add(10);
    stats.Add(12);
    stats.Add(6);
    stats.Add(15);
    stats.Add(4);

    stats.getNumbers();
    stats.getAverage();
    stats.getSTD();
    

    Statistic stats1;
    stats1.Add(5.4);
    stats1.Add(10);
    stats1.Add(12.3);
    stats1.Add(6.4);
    stats1.Add(15);
    stats1.Add(4.332);

    stats1.getNumbers();
    stats1.getAverage();
    stats1.getSTD();

    //using https://www.easycalculation.com/statistics/standard-deviation.php
    //I verified that my equations were correct
    return 0;
}
Exemplo n.º 7
0
void NoGUI::loadState()
{
    IniFile iniFile;
    iniFile.setFilename( QString("%1/state.ini").arg(m_filePath) );
    if(!iniFile.ready()) return;
    if(m_monteCarlo) m_monteCarlo->loadState(&iniFile);
    m_geometry->loadState(&iniFile);
    for(QVariant &variant : m_statistics) {
        Statistic *statistic = variant.value<Statistic*>();
        statistic->loadState(&iniFile);
    }
}
Exemplo n.º 8
0
long CountValidLast( StatList *byStat )
{
	Statistic *p;
	long i = 0, count = 0;

	while( (p=byStat->GetStat(i)) && i<byStat->num ){
		if ( p->GetVisitIn() != 0 )
			count++;
		i++;
	}
	return count;
}
Exemplo n.º 9
0
void NoGUI::saveState()
{
    QString fileName = QString("%1/state.ini").arg(m_filePath);
    QFile file(fileName);
    if(!file.open(QFileDevice::WriteOnly | QFileDevice::Text)) {
        qDebug() << "Error, could not not save file " << fileName;
        return;
    }
    if(m_monteCarlo) m_monteCarlo->saveState(file);
    m_geometry->saveState(file);
    for(QVariant &variant : m_statistics) {
        Statistic *statistic = variant.value<Statistic*>();
        statistic->saveState(file);
    }
}
Exemplo n.º 10
0
void QueryLoggingSolver::startQuery(const Query& query, const char* typeName,
                                    const Query* falseQuery,
                                    const std::vector<const Array*> *objects) {
    Statistic *S = theStatisticManager->getStatisticByName("Instructions");
    uint64_t instructions = S ? S->getValue() : 0;

    logBuffer << queryCommentSign << " Query " << queryCount++ << " -- "
              << "Type: " << typeName << ", "
              << "Instructions: " << instructions << "\n";
    
    printQuery(query, falseQuery, objects);
    
    startTime = getWallTime();
    
}
Exemplo n.º 11
0
void EndlessGameWidget::badMove()
{
  // Add sound effect
  PublicGameSounds::addSound(PublicGameSounds::BadMove);

  statistic.changeStatistic(Statistic::BadMoveCount, 1, true);
}
Exemplo n.º 12
0
 void startQuery(const Query& query, const char *typeName,
                 const ref<Expr> *evalExprsBegin = 0,
                 const ref<Expr> *evalExprsEnd = 0,
                 const Array * const* evalArraysBegin = 0,
                 const Array * const* evalArraysEnd = 0) {
   Statistic *S = theStatisticManager->getStatisticByName("Instructions");
   uint64_t instructions = S ? S->getValue() : 0;
   os << "# Query " << queryCount++ << " -- "
      << "Type: " << typeName << ", "
      << "Instructions: " << instructions << "\n";
   printer->printQuery(os, query.constraints, query.expr,
                       evalExprsBegin, evalExprsEnd,
                       evalArraysBegin, evalArraysEnd);
   
   startTime = getWallTime();
 }
Exemplo n.º 13
0
int main (int argc, char **argv)
{
	clock_t t1,t2;
	t1 = clock();
	
	/* 
	 * Parses command line 
	 */
	try {
		Options::Get().Parse(argc, argv);
	}
	catch (exception &e) {
		cerr << e.what() << "\n";
		Options::Get().print_usage();
		exit(0);
	}
	cout << "Statistic: " << Options::Get().statistic << "\n";
	/* 
	 * Initiates Statistic factory
	 */
	try {
	  AddAllStatistics();
	} catch (exception &e){ 
		cerr << e.what() << "\n";
		exit(0);
	}
	
	/*
	 * Read the multiple alignment 
	 */
	Msa msa(Options::Get().input_fname);
	
	/* 
	 * Calculate the statistic & print it
	 */
	Statistic * stat = StatisticFactory::CreateByName(Options::Get().statistic);
	stat->calculate(msa);
	stat->print(msa);
	delete stat;
	
	/*
	 * Print time
	 */
	t2 = clock();		
	cout << "Mstatx computed in "<< (t2 - t1) / (double)CLOCKS_PER_SEC <<" seconds\nResults are written in " << Options::Get().output_fname << "\n\n";
	return 0;
}
Exemplo n.º 14
0
	void startQuery(const Query& query, const char *typeName, const std::vector<const Array*>* objects=NULL)
	{
		Statistic *S = theStatisticManager->getStatisticByName("Instructions");
		uint64_t instructions = S ? S->getValue() : 0;
		os << ";SMTLIBv2 Query " << queryCount++ << " -- "
		   << "Type: " << typeName << ", "
		   << "Instructions: " << instructions << "\n";
		printer->setQuery(query);

		if(objects!=NULL)
			printer->setArrayValuesToGet(*objects);

		printer->generateOutput();
		os << "\n";

		startTime = getWallTime();
	}
Exemplo n.º 15
0
void Registry::merge(const Registry &other)
{
    for (const_iterator i = other.begin(); i != other.end(); i++)
    {
        boost::ptr_map<std::string, Statistic>::iterator pos = statistics.find(i->getName());
        if (pos == statistics.end())
        {
            Statistic *clone = i->clone();
            std::string name = clone->getName();
            statistics.insert(name, clone);
        }
        else
        {
            pos->second->merge(*i);
        }
    }
}
Exemplo n.º 16
0
static long DBIO_LoadStatistic( VDinfoP VDptr, Statistic *stat, gzFile fh, long useOtherNames, char *id )
{
	long	dataread = 0;

	if ( !fh ) return 0;

	// read one statistic
	if ( stat ) {
		dataread += gzread( fh, stat ,sizeof(Statistic) );

		if ( useOtherNames == NAMEIS_NORMAL || useOtherNames == NAMEIS_IP ) {
			if ( stat->GetName() && stat->length>0 ){
				char *name;
				name = stat->AllocateName( stat->length );
				dataread += ReadString( fh, name, stat->length );
			}
		} else 
		if ( (long)stat->GetName() == NAMEIS_STATIC )
		{
			if( !mystrcmpi( "hour", id ) )					RestoreHourNames( stat );
			else if( !mystrcmpi( "wkday", id ) )			RestoreWeekdaysNames( stat );
			else if( !mystrcmpi( "wdays", id ) )			RestoreHourNames( stat );
			else if( !mystrcmpi( "oper", id ) )				RestoreOpersysNames( stat );
			else if( !mystrcmpi( "errs", id ) )				RestoreErrorsNames( stat );
			else if( !mystrcmpi( s_errorsWithTopReferralsTag, id ) ) RestoreErrorsNames( stat );
			else if( !mystrcmpi( "pages", id ) )			RestoreStatisticName( stat, VDptr->byFile );
			else if( !mystrcmpi( "down", id ) )				RestoreStatisticName( stat, VDptr->byFile );
			else if( !mystrcmpi( "audio", id ) ) 			RestoreStatisticName( stat, VDptr->byFile );
			else if( !mystrcmpi( "video", id ) ) 			RestoreStatisticName( stat, VDptr->byFile );
			else if( !mystrcmpi( s_brokenLinkReferalsTag, id ) ) 	RestoreStatisticName( stat, VDptr->byRefer );
			else if( !mystrcmpi( s_intBrokenLinkReferalsTag, id ) ) RestoreStatisticName( stat, VDptr->byRefer );
			else											stat->name = NULL;
		}
	} else {
	// read to where? empty area just incase
		Statistic Lstat;
		dataread += gzread( fh, &Lstat ,sizeof(Statistic) );
		if ( Lstat.GetName() && !useOtherNames ) {
			char tmp[1024];
			dataread += gzread( fh, tmp , stat->length );
		}
		if ( (long)stat->GetName() == NAMEIS_STATIC ) 
			stat->name = NULL;
	}
	return dataread;
}
bool
checkPlane( Integer a, Integer b, Integer c, Integer d, 
            int diameter, unsigned int nbpoints,
            Statistic<double> & stats )
{
  typedef typename NaivePlaneComputer::Point Point;
  typedef typename Point::Component PointInteger;
  IntegerComputer<Integer> ic;
  Integer absA = ic.abs( a );
  Integer absB = ic.abs( b );
  Integer absC = ic.abs( c );
  Integer x, y, z;
  Dimension axis;
  if ( ( absA >= absB ) && ( absA >= absC ) )
    axis = 0;
  else if ( ( absB >= absA ) && ( absB >= absC ) )
    axis = 1;
  else
    axis = 2;
  Point p;
  NaivePlaneComputer plane;
  plane.init( axis, diameter, 1, 1 );
  // Checks that points within the naive plane are correctly recognized.
  unsigned int nb = 0;
  unsigned int nbok = 0;
  unsigned int nbchanges = 0;
  unsigned int complexity = plane.complexity();
  while ( nb != nbpoints )
    {
      p[ 0 ] = getRandomInteger<PointInteger>( -diameter+1, diameter ); 
      p[ 1 ] = getRandomInteger<PointInteger>( -diameter+1, diameter ); 
      p[ 2 ] = getRandomInteger<PointInteger>( -diameter+1, diameter );
      x = (Integer) p[ 0 ];
      y = (Integer) p[ 1 ];
      z = (Integer) p[ 2 ];
      switch ( axis ) {
      case 0: p[ 0 ] = NumberTraits<Integer>::castToInt64_t( ic.ceilDiv( d - b * y - c * z, a ) ); break;
      case 1: p[ 1 ] = NumberTraits<Integer>::castToInt64_t( ic.ceilDiv( d - a * x - c * z, b ) ); break;
      case 2: p[ 2 ] = NumberTraits<Integer>::castToInt64_t( ic.ceilDiv( d - a * x - b * y, c ) ); break;
      } 
      bool ok = plane.extend( p ); // should be ok
      ++nb, nbok += ok ? 1 : 0;
      if ( ! ok )
        {
          std::cerr << "[ERROR] p=" << p << " NOT IN plane=" << plane << std::endl;
          break;
        }
      if ( plane.complexity() != complexity )
        {
          complexity = plane.complexity();
          ++nbchanges;
        }
    }
  stats.addValue( (double) nbchanges );
  return nb == nbok;
}
Exemplo n.º 18
0
void NoGUI::tick()
{
    if(!isValid()) {
        for(QVariant &variant : m_statistics) {
            Statistic *statistic = variant.value<Statistic*>();
            statistic->compute(m_geometry, m_timestep);
        }

        for(QVariant &variant : m_models) {
            Statistic *statistic = variant.value<Statistic*>();
            statistic->compute(m_geometry, m_timestep);
        }

        for(QVariant &variant : m_datas) {
            Statistic *statistic = variant.value<Statistic*>();
            statistic->compute(m_geometry, m_timestep);
        }
        if(!isValid()) {
            qDebug() << "Error, NoGUI or children not ready...";
            exit(1);
        }
    }
    if(!m_timer.isValid()) m_timer.start();
    if(m_monteCarlo) m_monteCarlo->tick(m_timestep);

    if( m_monteCarlo && (m_timestep % m_printEvery) == 0) {
        double timeLeft = m_timer.elapsed() / ( double(m_timestep+1)) * (m_timesteps-m_timestep) / 1000.; // seconds
        QTextStream logStream(&m_log);
        qDebug() << "MC step " << m_timestep << "/" << m_timesteps << ". χ^2: " << QString::number( m_monteCarlo->chiSquared(), 'f', 10 ) << ", T=" << m_monteCarlo->temperature() << " with acceptance ratio " << m_monteCarlo->acceptanceRatio() << " (" << m_monteCarlo->accepted() << " / " << m_monteCarlo->steps() << ") and random walk fraction " << m_geometry->randomWalkFraction() << ". Estimated time left: " << timeLeft << " seconds.";
        logStream << "MC step " << m_timestep << "/" << m_timesteps << ". χ^2: " << QString::number( m_monteCarlo->chiSquared(), 'f', 10 ) << ", T=" << m_monteCarlo->temperature() << " with acceptance ratio " << m_monteCarlo->acceptanceRatio() << " (" << m_monteCarlo->accepted() << " / " << m_monteCarlo->steps() << ") and random walk fraction " << m_geometry->randomWalkFraction() << ". Estimated time left: " << timeLeft << " seconds.\n";
        if(m_visualize) {
            for(QVariant &variant : m_statistics) {
                Statistic *statistic = variant.value<Statistic*>();
                statistic->compute(m_geometry, m_timestep);
                if(m_visualize) {
                    statistic->updateQML();
                }
            }
        }
    }

    m_timestep++;

    if(m_timestep >= m_timesteps) {
        setFinished(true);
    }
}
int main( int argc, char** argv )
{
  using namespace Z3i;
  Statistic<double> stats;
  unsigned int nbtries = ( argc > 1 ) ? atoi( argv[ 1 ] ) : 100;
  unsigned int nbpoints = ( argc > 2 ) ? atoi( argv[ 2 ] ) : 100;
  unsigned int diameter = ( argc > 3 ) ? atoi( argv[ 3 ] ) : 100;
  std::cout << "# Usage: " << argv[0] << " <nbtries> <nbpoints> <diameter>." << std::endl;
  std::cout << "# Test class COBANaivePlaneComputer. Points are randomly chosen in [-diameter,diameter]^3." << std::endl;
  std::cout << "# Integer nbtries nbpoints diameter time/plane(ms) E(comp) V(comp)" << std::endl;
  
 // Max diameter is ~20 for int32_t, ~500 for int64_t, any with BigInteger.
  trace.beginBlock ( "Testing class COBANaivePlaneComputer" );
  bool res = true 
    && checkPlanes<COBANaivePlaneComputer<Z3, DGtal::BigInteger> >( nbtries, diameter, nbpoints, stats );
  trace.emphase() << ( res ? "Passed." : "Error." ) << endl;
  long t = trace.endBlock();
  stats.terminate();
  std::cout << "BigInteger" << " " << stats.samples()
            << " " << nbpoints
            << " " << diameter 
            << " " << ( (double) t / (double) stats.samples() )
            << " " << stats.mean()
            << " " << stats.variance()
            << std::endl;
  return res ? 0 : 1;
}
Exemplo n.º 20
0
int main(int argc, char* argv[])
{
	if(argc == 1) {
		cerr << "usage: play_game rounds [other arguments which your AI needs]" << endl;
		return 1;
	}
	int iPlayRounds = atoi(argv[1]);
	// create and initialize AI
	Fib2584Ai ai;
	ai.initialize(argc, argv);

	// initialize statistic data
	Statistic statistic;
	statistic.setStartTime();
	// play each round
	for(int i = 0;i < iPlayRounds;i++) {
		GameBoard gameBoard;
		gameBoard.initialize();
		int iScore = 0;
		int arrayBoard[4][4];
		while(!gameBoard.terminated()) {
			gameBoard.getArrayBoard(arrayBoard);
			MoveDirection moveDirection = ai.generateMove(arrayBoard);

			GameBoard originalBoard = gameBoard;
			iScore += gameBoard.move(moveDirection);
			if(originalBoard == gameBoard) {
				printf("Repeated\n");
				exit(1);
			}
			statistic.increaseOneMove();

			gameBoard.addRandomTile();
		}
		gameBoard.getArrayBoard(arrayBoard);
		ai.gameOver(arrayBoard, iScore);
		statistic.increaseOneGame();

		// update statistic data
		statistic.updateScore(iScore);
		statistic.updateMaxTile(gameBoard.getMaxTile());
	}
	statistic.setFinishTime();

	// output statistic data
	statistic.show();

	return 0;
}
Exemplo n.º 21
0
void
getStatsFromDistanceMap(Statistic<double> & stats, const Image3D &imageA, int aMin, int aMax,
			const Image3D & imageB,  int bMin, int bMax, 
			bool statOnFalsePositiveOnly=false, Point *ptMax=0){

  // Get the digital set from ref image by computing the surface (use -1 and +1 since the interval of append function are open)
  Z3i::DigitalSet set3dRef (imageA.domain()); 
  SetFromImage<Z3i::DigitalSet>::append<Image3D>(set3dRef, imageA, aMin-1,aMax);  
  typedef functors::NotPointPredicate<Z3i::DigitalSet> NegPredicate;
  

  // Applying the distance transform on the digital surface of the set: 
  typedef  DistanceTransformation<Z3i::Space, NegPredicate, Z3i::L2Metric> DTL2;
  const NegPredicate aPredicate( set3dRef );
  DTL2 dtL2( imageA.domain(), aPredicate, Z3i::l2Metric );

  // Get the set of point of imageB: (use -1 and +1 since the interval of append function are open)
  Z3i::DigitalSet set3dComp (imageB.domain()); 
  SetFromImage<Z3i::DigitalSet>::append<Image3D>(set3dComp, imageB, bMin-1, bMax);

  unsigned int nbAdded=0;
  double maxDist=0;
  //Applying stats from the set to be compared (from imageB)
  for(Z3i::DigitalSet::ConstIterator it= set3dComp.begin();  it!= set3dComp.end(); ++it){
    if((!statOnFalsePositiveOnly) || (isDiff(imageA, aMin, aMax, imageB, bMin, bMax, *it))){
      DTL2::Value distance = dtL2(*it);   
      stats.addValue(distance);
      nbAdded++;
      if(maxDist<distance){
	maxDist=distance;
	if(ptMax!=0){
	  (*ptMax)[0]=(*it)[0]; 
	  (*ptMax)[1]=(*it)[1];
	  (*ptMax)[2]=(*it)[2];
	}
      }
    }
  }
  
  if(nbAdded==0)
    trace.error() << "No point added to statistics, will failed..." << endl;
}
Exemplo n.º 22
0
AbstractAchievementItem *Achievements::getAchievementItem
      (AbstractAchievementItem::ItemType type, QPainter *painter)
{
  AbstractAchievementItem *item = NULL;
  switch (type)
  {
  case AbstractAchievementItem::FlameGet:
    item = new FlameGetItem
           (getAchievementLevel(AbstractAchievementItem::FlameGet),
            statistic.getStatistic(Statistic::FlameGetCount),
            painter);
    break;
  case AbstractAchievementItem::StarGet:
    item = new StarGetItem
           (getAchievementLevel(AbstractAchievementItem::StarGet),
            statistic.getStatistic(Statistic::StarGetCount),
            painter);
    break;
  case AbstractAchievementItem::RotateClassic:
    item = new RotateClassicPointItem
           (getAchievementLevel(AbstractAchievementItem::RotateClassic),
            statistic.getStatistic(Statistic::RotateClassicPoint),
            painter);
    break;
  case AbstractAchievementItem::Timing:
    item = new TimingPointItem
           (getAchievementLevel(AbstractAchievementItem::Timing),
            qMax(statistic.getStatistic(Statistic::SwapTimingPoint),
                 statistic.getStatistic(Statistic::RotateTimingPoint)),
            painter);
    break;
  case AbstractAchievementItem::RotatePuzzle:
    item = new RotatePuzzleFinishedItem
           (statistic.getStatistic(Statistic::RotatePuzzleFinished),
            statistic.getStatistic(Statistic::RotatePuzzleTotal),
            painter);
    break;
  default:
    break;
  }
  return item;
}
Exemplo n.º 23
0
int Achievements::getAchievementLevel(AbstractAchievementItem::ItemType type,
                                      int value)
{
  if (value == -1)
  {
    switch (type)
    {
    case AbstractAchievementItem::FlameGet:
      value = statistic.getStatistic(Statistic::FlameGetCount);
      break;
    case AbstractAchievementItem::StarGet:
      value = statistic.getStatistic(Statistic::StarGetCount);
      break;
    case AbstractAchievementItem::RotateClassic:
      value = statistic.getStatistic(Statistic::RotateClassicPoint);
      break;
    case AbstractAchievementItem::Timing:
      value = qMax(statistic.getStatistic(Statistic::SwapTimingPoint),
                   statistic.getStatistic(Statistic::RotateTimingPoint));
      break;
    case AbstractAchievementItem::RotatePuzzle:
      if (statistic.getStatistic(Statistic::RotatePuzzleFinished) == 0)
        value = 0;
      else if (statistic.getStatistic(Statistic::RotatePuzzleFinished) ==
               statistic.getStatistic(Statistic::RotatePuzzleTotal))
        value = 2;
      else
        value = 1;
      break;
    default:
      return 0;
      break;
    }
  }
  return calculateLevel(type, value);
}
Exemplo n.º 24
0
void NoGUI::compute() {
    qDebug() << "Doing compute";
    m_timestep++;
    for(QVariant &variant : m_models) {
        Statistic *statistic = variant.value<Statistic*>();
        statistic->compute(m_geometry, m_timestep);
    }

    for(QVariant &variant : m_datas) {
        Statistic *statistic = variant.value<Statistic*>();
        statistic->compute(m_geometry, m_timestep);
    }

    for(QVariant &variant : m_statistics) {
        Statistic *statistic = variant.value<Statistic*>();
        statistic->compute(m_geometry, m_timestep);
        if(m_visualize) {
            statistic->updateQML();
        }
    }
}
Exemplo n.º 25
0
bool NoGUI::isValid()
{
    for(QVariant &variant : m_statistics) {
        Statistic *statistic = variant.value<Statistic*>();
        if(!statistic->isValid()) return false;
    }

    for(QVariant &variant : m_models) {
        Statistic *statistic = variant.value<Statistic*>();
        if(!statistic->isValid()) return false;
    }

    for(QVariant &variant : m_datas) {
        Statistic *statistic = variant.value<Statistic*>();
        if(!statistic->isValid()) return false;
    }

    if(!m_geometry->isValid()) return false;
    if(!m_monteCarlo->isValid()) return false;

    return true;
}
Exemplo n.º 26
0
logical ClientObject :: Start ( )
{
  int32                    lindx0 = 0;
  int32                   *loid_array;
  int32                    count;
  int32                    err_count = 0;
  Statistic               stats;
  ODABAClient             client;
  DBObjectHandle          obhandle(utility_handle->sdbures->dbhandle);
  logical                 term = NO;
BEGINSEQ
  if ( !this )                                       ERROR
  (*client_count)++;

  stats.Start();
  
  if ( !obhandle.IsServer() )  // client/server application
  {
    ds_handle = new DataSourceHandle();
    ds_handle->SetDataSource(utility_handle->sdbures);
    client.Open(NULL,"TestCS");
    if ( ds_handle->Open(client) )                   ERROR
    obhandle = ds_handle->dbhandle;
  }

  PropertyHandle  ext_ph(obhandle,extent,PI_Read);  SDBCERR
  PropertyHandle  void_ph(obhandle,"VOID",PI_Read); SDBCERR

  printf("\nThread %i started (%s)",id,extent);

  if ( (count = ext_ph.GetCount()) > 0 )
  {
    loid_array = new int32[count];
    memset(loid_array,0,count*sizeof(int32));
    
    while ( ext_ph.Get(lindx0) )
      loid_array[lindx0++] = ext_ph.GetLOID();
    
    lindx0 = 0;
    while ( lindx0 < count ) 
      if ( !void_ph.Get(loid_array[lindx0++]) )
        err_count++;
      
    delete loid_array;
  }
  stats.Stop();


  printf("\nThread %i stopped (%s) normally. Errors: %i",id,extent,err_count);
  printf("\n          total time: %s",stats.GetTotalTime());

RECOVER
  printf("\nThread %i terminated (%s) with error",id,extent);
  term = YES;
ENDSEQ
  if ( this ) 
  {  
    obhandle.Close();
    Close();
    client.ShutDown();
    (*client_count)--;
    delete this;
  }
  return(term);
}
Exemplo n.º 27
0
int main(){

Statistic<double,24> hourly;
hourly.setData(36,0);
hourly.setData(37,1);
hourly.setData(38,2);
hourly.setData(39,3);
hourly.setData(40,4);
hourly.setData(41,5);
hourly.setData(42,6);
hourly.setData(43,7);
hourly.setData(44,8);
hourly.setData(45,9);
hourly.setData(10,10);
hourly.setData(11,11);
hourly.setData(12,12);
hourly.setData(20,13);
hourly.setData(24,14);
hourly.setData(24,15);
hourly.setData(41.25,16);
hourly.setData(41.25,17);
hourly.setData(41.25,18);

hourly.setData(31.875,19);
hourly.setData(32,20);
hourly.setData(32,21);
hourly.setData(38,22);
hourly.setData(38,23);

//std::cout<<hourly.getMean()<<"\n";
//std::cout<<hourly.getVariance()<<"\n";
//std::cout<<hourly.getStdDev()<<"\n";
Statistic<bool,24> booler;
Statistic<float,24> flaoter;


    char* texts[4]={"23","00","01","02"};
    //cout<<hourly.toCsv(texts,4);
    cout<<"\n\n";
    cout<<hourly.toSVG(400,200,3,texts,4);
 }
Exemplo n.º 28
0
void EndlessGameWidget::dealStableEliminate(Connections connections)
{
  // Calculate the bonus
  for (int i = 0;i < gameboardInfo->totalBallCounts();++i)
  {
    QVector<QVector<int> *>& connect = connections.connectionsOfIndex[i];
    int connectionCountOfThePosition = 0;
    for (int j = 0;j < 10;++j)
    {
      if (j == 3 || connect[j] == NULL)
        continue;
      ++connectionCountOfThePosition;
    }
    if (connectionCountOfThePosition > 0)
      effectPainter->highlightAt(i);
    if (connectionCountOfThePosition > 1)
    {
      if (connectionCountOfThePosition >= 2)
        effectPainter->flash();
      if (connectionCountOfThePosition == 2)
      {
        // Add sound effect
        PublicGameSounds::addSound(PublicGameSounds::GetFlame);

        // Get a flame
        flame->addOne();

        statistic.changeStatistic(Statistic::FlameGetCount, 1, true);
      }
      if (connectionCountOfThePosition >= 3)
      {
        // Add sound effect
        PublicGameSounds::addSound(PublicGameSounds::GetStar);

        // Get a star
        star->addOne();

        statistic.changeStatistic(Statistic::StarGetCount, 1, true);
      }
    }
  }
  for (int i = 0;i < connections.connections.size();++i)
  {
    int size = connections.connections[i]->size();
    QPointF pos1(gameboardInfo->positionOfIndex(connections.connections[i]->at(0)));
    QPointF pos2(gameboardInfo->positionOfIndex(connections.connections[i]->at(size - 1)));
    effectPainter->wordsAt(QPointF((pos1.x() + pos2.x()) / 2,
                                   (pos1.y() + pos2.y()) / 2),
                           tr("%1").arg(size),
                           size);
    if (size >= 4)
      effectPainter->flash();
    if (size == 4)
    {
      // Add sound effect
      PublicGameSounds::addSound(PublicGameSounds::GetFlame);

      // Get a flame
      flame->addOne();

      statistic.changeStatistic(Statistic::FlameGetCount, 1, true);
    }
    if (size >= 5)
    {
      // Add sound effect
      PublicGameSounds::addSound(PublicGameSounds::GetStar);

      // Get a star
      star->addOne();

      statistic.changeStatistic(Statistic::StarGetCount, 1, true);
    }
  }
}
Exemplo n.º 29
0
//層次
void experimentWorkSpace(){

	//A是產生完 B是計算完branch and dead ends
	//phase A
	GameControl* gameControl = GameControl::getInstance();

	//gameControl->file.open(".\\data\\gameboard20\\db_13.dat");//設定自動產生的關卡要存在哪邊
	//db_release = new GameDB(10, 10);
	//db_release->loadGames(".\\data\\gameboard10\\db_release10_phaseA.dat");
	//loadScore();
	/*GameDB* db = new GameDB(10, 10);
	db->loadGames(".\\data\\gameboard10\\db_release10_phaseB.dat");



	PersonalData* personalData = new PersonalData(".\\data\\gameboard10\\db_ALL_GAME_remove_same.dat");

	personalData->loadScore(".\\statistic\\");
	//personalData->printAllScore();

	Statistic ss;

	for(int i = 0; i < personalData->datas.size(); i ++){
		vector<ScoreData*> sortedScore = 
			personalData->sortbyDifficulty(PersonalData::DIFFICULTY, 
			                               personalData->datas[i]);
		vector<GameState*> complexState = GameControl::getInstance()->
			                              sortbyComplexity(GameControl::ASCENT, 
			                              personalData->getState(sortedScore));


	}*/

	//SimulationAnnealing sa(personalData);
	//GameParameter* p = new GameParameter(1);
	//sa.begin(p);
	
	
	GameDB* veryEasyDB = new GameDB();
	veryEasyDB->loadGames(".\\data\\gameboard10\\db_e2_VeryEasy.dat");

	GameDB* easyDB = new GameDB();
	easyDB->loadGames(".\\data\\gameboard10\\db_e2_Easy.dat");

	GameDB* normalDB = new GameDB();
	normalDB->loadGames(".\\data\\gameboard10\\db_e2_Normal.dat");

	GameDB* hardDB = new GameDB();
	hardDB->loadGames(".\\data\\gameboard10\\db_e2_Hard.dat");

	GameDB* veryHardDB = new GameDB();
	veryHardDB->loadGames(".\\data\\gameboard10\\db_e2_VeryHard.dat");

	vector<GameState*> pickVeryEasyStates = veryEasyDB->getRandomStates(2);
	vector<GameState*> pickEasyStates = easyDB->getRandomStates(3);
	vector<GameState*> pickNormalStates = normalDB->getRandomStates(3);
	vector<GameState*> pickHardStates = hardDB->getRandomStates(1);
	vector<GameState*> pickVeryHardStates = veryHardDB->getRandomStates(1);

	vector<GameState*> releaseStates = easyDB->merge(pickVeryEasyStates, pickEasyStates);
	releaseStates = easyDB->merge(releaseStates, pickNormalStates);
	releaseStates = easyDB->merge(releaseStates, pickHardStates);
	releaseStates = easyDB->merge(releaseStates, pickVeryHardStates);

	releaseStates = GameControl::getInstance()->sortbyComplexity(GameControl::ASCENT, releaseStates);

	easyDB->saveGames(".\\data\\gameboard10\\db_e2_release_random10.dat", releaseStates);

	Statistic ss;
	cout << ss.mean(Statistic::BRANCH, veryEasyDB->states) << endl;
	cout << ss.mean(Statistic::BRANCH, easyDB->states) << endl;
	cout << ss.mean(Statistic::BRANCH, normalDB->states) << endl;
	cout << ss.mean(Statistic::BRANCH, hardDB->states) << endl;
	cout << ss.mean(Statistic::BRANCH, veryHardDB->states) << endl;


	cout << "==============" << endl;
	cout << ss.mean(Statistic::DEADEND, veryEasyDB->states) << endl;
	cout << ss.mean(Statistic::DEADEND, easyDB->states) << endl;
	cout << ss.mean(Statistic::DEADEND, normalDB->states) << endl;
	cout << ss.mean(Statistic::DEADEND, hardDB->states) << endl;
	cout << ss.mean(Statistic::DEADEND, veryHardDB->states) << endl;
	cout << "==============" << endl;

	cout << ss.mean(Statistic::COMPLEXITY, veryEasyDB->states) << endl;
	cout << ss.mean(Statistic::COMPLEXITY, easyDB->states) << endl;
	cout << ss.mean(Statistic::COMPLEXITY, normalDB->states) << endl;
	cout << ss.mean(Statistic::COMPLEXITY, hardDB->states) << endl;
	cout << ss.mean(Statistic::COMPLEXITY, veryHardDB->states) << endl;

	//vector<GameState*> states = db->pickStates(personalData->puzzleDB->states, db->states);
	GameControl::getInstance()->states = veryEasyDB->states;
	gameControl->setStateIndex(0);
	//GameControl::getInstance()->sortSolvedSequence();
	//db->saveGames(".\\data\\gameboard10\\db_ALL_GAME_remove_same.dat", db->states);
	//system("pause");

}
Exemplo n.º 30
0
void EndlessGameWidget::dealReleased(QPointF mousePos, Qt::MouseButton button)
{
  if (itemAtPressPos != NULL)
  {
    if (itemAtPressPos == flame && flame->notEmpty())
    {
      int index = gameboardInfo->indexOfPosition(mousePos);
      if (index != -1)
      {
        // Add sound effect
        PublicGameSounds::addSound(PublicGameSounds::UseFlame);

        // Tell the controller to eliminate the balls
        controller->flameAt(index);

        // Add effects to effect painter
        effectPainter->explodeAt(index);
        effectPainter->flash();

        // Minus the value of the flame
        flame->minusOne();

        statistic.changeStatistic(Statistic::FlameUsedCount, 1, true);
      }
    }
    else if (itemAtPressPos == star && star->notEmpty())
    {
      int index = gameboardInfo->indexOfPosition(mousePos);
      if (index != -1)
      {
        // Add sound effect
        PublicGameSounds::addSound(PublicGameSounds::UseStar);

        // Tell the controller to eliminate the balls
        controller->starAt(index);

        // Add effects to effect painter
        effectPainter->lightningAt(index);
        effectPainter->flash();

        // Minus the value of the flame
        star->minusOne();

        statistic.changeStatistic(Statistic::StarUsedCount, 1, true);
      }
    }
    else if (itemAtPressPos == hint &&
             hint->in(mousePos,
                      gameboardInfo->width(),
                      gameboardInfo->height()))
    {
      // Reduce the score
      int score = qMax(progressBar->getCurrent() - 10,
                       progressBar->getMin());
      progressBar->setCurrent(score);

      // Show the hint
      showHint();
    }
    else if (itemAtPressPos == resetItem &&
             resetItem->in(mousePos,
                           gameboardInfo->width(),
                           gameboardInfo->height()))
    {
      // Create the reset widget
      ResetWidget *w = new ResetWidget();

      // Connect
      connect(w, SIGNAL(confirm()), this, SLOT(reset()));

      // Give control to it
      emit giveControlTo(w, false);
    }
    else if (itemAtPressPos == exitItem &&
             exitItem->in(mousePos,
                          gameboardInfo->width(),
                          gameboardInfo->height()))
    {
      // Quit game
      quitGame();
      return;
    }
  }

  // Clear user moving elimination hints
  effectPainter->clearUserMovingEliminationHints();
  itemAtPressPos = NULL;

  // Let the gesture controller to deal the release event
  gestureController->dealReleased(mousePos);
}