Пример #1
0
void LearningInterface::trainCurrent()
{
    //Only train if user falls into both classes
    if(!m_one_class_only)
    {
        //Normalize the training set.
        m_normalizer.train(m_training_set);
        for (unsigned long i = 0; i < m_training_set.size(); ++i)
            m_training_set[i] = m_normalizer(m_training_set[i]);

        //Perform cross-validation over a range of values of C and gamma
        //to determine the best parameters
        double C_best = 0;
        double gamma_best = 0;
        double best_accuracy = 0.0;

        //Different values, simple implementation
        //Could look into better methods of doing this but this is a nice
        //and simple implementation at the cost of speed and efficiency
        for(double gamma = 0.0001; gamma < 300; gamma *= 5)
        {
            for(double C = 0.0001; C < 300; C *= 5)
            {
                //Set a new kernel
                m_trainer.set_kernel(kernel_type(gamma));

                //Set a new C
                m_trainer.set_c(C);

                //Perform 3-fold cross validation and look at the accuracy
                matrix<double, 1, 2> accuracy = cross_validate_trainer(m_trainer, m_training_set, m_labels, 3);
                DEBUG() << " cross-validation accuracy: " << accuracy(0,0) << " " << accuracy(0,1);
                //See if this has the best accuracy so far by multiplying the 0 class accuracy and 1 class accuracy
                double curr_accuracy = accuracy(0,0) * accuracy(0,1);
                if(curr_accuracy > best_accuracy)
                {
                    best_accuracy = curr_accuracy;
                    C_best = C;
                    gamma_best = gamma;
                }

            }
        }

        //Set C, epsilon and cache size
        m_trainer.set_c(C_best);

        //For now just leave defaults

        //Set gamma
        m_trainer.set_kernel(kernel_type(gamma_best));
        m_decision_function.normalizer = m_normalizer;

        //Train
        m_decision_function.function = m_trainer.train(m_training_set, m_labels);

        m_is_trained = true;
    }

}
Пример #2
0
double QgsQuickPositionKit::calculateScreenAccuracy()
{
  if ( !mMapSettings )
    return 2.0;

  if ( accuracy() > 0 )
  {
    double scpm = QgsQuickUtils::screenUnitsToMeters( mMapSettings, 1 );
    if ( scpm > 0 )
      return 2 * ( accuracy() / scpm );
    else
      return 2.0;
  }
  return 2.0;
}
Пример #3
0
//-- Training
//------------------------------------------------------------------
void NNTrainer::trainNetwork()
{
    //-- Training parameters:
    //---------------------------------------------------------------
    //-- Randomize weights
    std::cout << "Randomize weights...";
    randomWeights();
    std::cout  << "\033[0;32m" << "[ok]" << "\033[0m" << std::endl
	       << "Starting Gradient Descend... " << std::endl << std::endl;

    //-- Calculate the frequency of information update:
    int showPeriod = iter > 10 ? iter / 10 : iter;

    //-- Start gradient descend:
    for (int i = 0; i < iter; i++)
    {
	//-- Calculate gradient:
	std::vector<double> grad = gradient( global_lambda );

	//-- Convert the gradient in matrices:
	std::vector<Matrix *> matGrad = unrolledToMatrices( grad );

	//-- Operate matrices
	for (int l = 0; l < (int) nn->getWeights().size(); l++)
	    *nn->getWeights().at(l) = ( *nn->getWeights().at(l) ) - (*matGrad.at(l) * alpha) ;

	//-- Deallocate memory:
	for (int l = (int) matGrad.size() - 1; l >= 0; l--)
	    delete matGrad.at(l);

	//-- Periodically, show percentage completed and accuracy:
	if ( (double) (i % showPeriod) == 0)
	{
	    std::cout << "\033[1A" <<  "\033[K";// << "\033[0;0H";
	    std::cout << "Completed: "<< "\033[0;31m" <<   (i / (double) iter ) * 100 << "%"  << "\033[0m"
		      << " Current accuracy: "  << "\033[0;31m" << accuracy() * 100 << "%" << "\033[0m"
		      << " Current cost: "  << "\033[0;31m" << costFunction(global_lambda)  << "\033[0m" << std::endl;
	}

    }

    std::cout << "Done. Final accuracy: " << accuracy() * 100 << "%" << std::endl
	      << "Press enter to continue." << std::endl;

    std::cin.ignore();


}
Пример #4
0
void network_test_performance(DeepNetwork* network, DataSet* dataset) {
  //Test set performance
  const std::vector<std::unique_ptr<Data>> &test_data = dataset->get_test_data_batches();
  std::vector<std::unique_ptr<Data>>::const_iterator current_test_data = test_data.begin();
  const std::vector<std::unique_ptr<Data>> &test_labels = dataset->get_test_labels_batches();
  std::vector<std::unique_ptr<Data>>::const_iterator current_test_labels = test_labels.begin();
  
  std::vector<std::unique_ptr<Data>> test_predictions;
  
  int subset_count = 1000;
  int subset_idx = 0;
  for (; current_test_data != test_data.end(); current_test_data++, current_test_labels++) {
    network->forward((*current_test_data).get());
    
    std::unique_ptr<Data> probabilities = network->get_output();
    std::unique_ptr<Data> predictions = MaxProbabilityPrediction().execute(probabilities.get());
    test_predictions.push_back(std::move(predictions));
    
    if (subset_idx > subset_count) {
      break;
    }
  }
  std::cout << "Test set accuracy: " << accuracy(test_predictions, test_labels) << std::endl;
  test_predictions.clear();
}
Пример #5
0
void
opf_supervised_train_iterative (struct opf_graph *sg, double split)
{
  int i = 0;
  double acc = DBL_MIN, acc_prev = DBL_MIN, delta;

  struct opf_graph sg_train, sg_eval;
  opf_graph_split_mirrored (sg, split, &sg_train, &sg_eval);

  do
    {
      acc_prev = acc;

      opf_supervised_train (&sg_train);
      supervised_classify_opf_graph (&sg_train, &sg_eval);
      acc = accuracy (&sg_eval);

      swap_wrong_prototypes (&sg_train, &sg_eval);

      delta = fabs(acc-acc_prev);
      i++;
    }
  while ((delta > DBL_EPSILON) && (i < ITER_MAX));

  /* just the training part will remain */
  opf_graph_resize (sg, sg_train.node_n);
}
void RouteSimulationPositionProviderPlugin::update()
{
    ++m_currentIndex;

    if ( m_currentIndex >= 0 && m_currentIndex < m_lineString.size() ) {
        if ( m_status != PositionProviderStatusAvailable ) {
            m_status = PositionProviderStatusAvailable;
            emit statusChanged( PositionProviderStatusAvailable );
        }

        GeoDataCoordinates newPosition = m_lineString.at( m_currentIndex );
        const QDateTime newDateTime = QDateTime::currentDateTime();
        if ( m_currentPosition.isValid() ) {
            m_speed = distanceSphere( m_currentPosition, newPosition ) * m_marbleModel->planetRadius() / ( m_currentDateTime.msecsTo( newDateTime ) ) * 1000;
            m_direction = m_currentPosition.bearing( newPosition, GeoDataCoordinates::Degree, GeoDataCoordinates::FinalBearing );
        }
        m_currentPosition = newPosition;
        m_currentDateTime = newDateTime;
        emit positionChanged( position(), accuracy() );
    }
    else {
        // Repeat from start
        m_currentIndex = -1;
        if ( m_status != PositionProviderStatusUnavailable ) {
            m_status = PositionProviderStatusUnavailable;
            emit statusChanged( PositionProviderStatusUnavailable );
        }
    }

    QTimer::singleShot( 1000.0 / c_frequency, this, SLOT(update()) );
}
Пример #7
0
void testSolverSpeed(const std::string inputFilePath,const std::string outputFilePath,const int sizeThreshold,std::string solverType,user_IndexTree & usrTree){
  Eigen::MatrixXd inputMatrix = readBinaryIntoMatrixXd(inputFilePath);
  int matrixSize = inputMatrix.rows();
  Eigen::VectorXd exactSoln = Eigen::VectorXd::LinSpaced(Eigen::Sequential,matrixSize,-2,2);
  Eigen::VectorXd inputF = inputMatrix * exactSoln;
  HODLR_Matrix test_HODLR(inputMatrix,sizeThreshold,usrTree);
  
  std::ofstream outputFile_Error;
  std::ofstream outputFile_Speed;
  std::string errorFileName = outputFilePath + "errorVsTolerance";
  std::string speedFileName = outputFilePath + "speedVsTolerance";
  outputFile_Error.open(errorFileName.c_str());
  outputFile_Speed.open(speedFileName.c_str());

  double accuracyVal[] = {1e-5,1e-6,1e-7,1e-8};
  std::vector<double> accuracy(accuracyVal, accuracyVal + sizeof(accuracyVal) / sizeof(double));
  for (unsigned int i = 0; i < accuracy.size();i++){
    test_HODLR.set_LRTolerance(accuracy[i]);
    Eigen::VectorXd solverSoln;
    if (solverType == "recLU"){
      solverSoln = test_HODLR.recLU_Solve(inputF);
      outputFile_Speed<<accuracy[i]<<" "<<test_HODLR.get_recLU_TotalTime()<<std::endl;
    }else if (solverType == "extendedSp"){
      solverSoln = test_HODLR.extendedSp_Solve(inputF);
      outputFile_Speed<<accuracy[i]<<" "<<test_HODLR.get_extendedSp_TotalTime()<<std::endl;
    }
    Eigen::VectorXd difference = solverSoln - exactSoln;
    double relError = difference.norm()/exactSoln.norm();
    outputFile_Error<<accuracy[i]<<" "<<relError<<std::endl;
  }
  outputFile_Error.close();
  outputFile_Speed.close();
}
Пример #8
0
int main()
{ 
  int d;
  for(d=1; d<4; d++)
    accuracy(d);
  
  return 1;
}
Пример #9
0
/**
 * Print benchmark results.
 */
void logResults(std::vector<Result>& results, unsigned long time)
{
  typedef OpenANN::FloatingPointFormatter fmt;
  OpenANN::Logger resultLogger(OpenANN::Logger::CONSOLE);
  resultLogger << "\t\tCorrect\t\tAccuracy\tTime/ms\t\tIterations\n";
  Eigen::VectorXd correct(results.size());
  Eigen::VectorXd accuracy(results.size());
  Eigen::VectorXd iterations(results.size());
  for(unsigned i = 0; i < results.size(); i++)
  {
    correct(i) = (double) results[i].correct;
    accuracy(i) = results[i].accuracy;
    iterations(i) = results[i].iterations;
  }
  double correctMean = correct.mean();
  double accuracyMean = accuracy.mean();
  double iterationsMean = iterations.mean();
  double correctMin = correct.minCoeff();
  double accuracyMin = accuracy.minCoeff();
  double iterationsMin = iterations.minCoeff();
  double correctMax = correct.maxCoeff();
  double accuracyMax = accuracy.maxCoeff();
  double iterationsMax = iterations.maxCoeff();
  for(unsigned i = 0; i < results.size(); i++)
  {
    correct(i) -= correctMean;
    accuracy(i) -= accuracyMean;
    iterations(i) -= iterationsMean;
  }
  correct = correct.cwiseAbs();
  accuracy = accuracy.cwiseAbs();
  iterations = iterations.cwiseAbs();
  double correctStdDev = std::sqrt(correct.mean());
  double accuracyStdDev = std::sqrt(accuracy.mean());
  double iterationsStdDev = std::sqrt(iterations.mean());
  resultLogger << "Mean+-StdDev\t";
  resultLogger << fmt(correctMean, 3) << "+-" << fmt(correctStdDev, 3) << "\t"
               << fmt(accuracyMean, 3) << "+-" << fmt(accuracyStdDev, 3) << "\t"
               << (int)((double)time / (double)results.size()) << "\t\t"
               << iterationsMean << "+-" << fmt(iterationsStdDev, 3) << "\n";
  resultLogger << "[min,max]\t";
  resultLogger << "[" << correctMin << "," << correctMax << "]\t"
               << "[" << fmt(accuracyMin, 3) << "," << fmt(accuracyMax, 3) << "]\t\t\t"
               << "[" << (int) iterationsMin << "," << (int) iterationsMax << "]\n\n";
}
Пример #10
0
int main(int argc, char *argv[]) {
  PSInit(&argc, &argv, 3, NX, NX, NX);
  PSGrid3DReal g = PSGrid3DRealNew(NX, NX, NX);
  PSDomain3D d = PSDomain3DNew(0, NX, 0, NX, 0, NX);  

  struct timeval time_begin, time_end;
  int    nx    = NX;
  int    ny    = NX;
  int    nz    = NX;
  REAL  *buff  = (REAL *)malloc(sizeof(REAL) *nx*ny*nz);
  REAL   time  = 0.0;
  int    count = 1000;
  REAL l, dx, dy, dz, kx, ky, kz, kappa, dt;
  REAL ce, cw, cn, cs, ct, cb, cc;

  l = 1.0;
  kappa = 0.1;
  dx = dy = dz = l / nx;
  kx = ky = kz = 2.0 * M_PI;
  dt = 0.1*dx*dx / kappa;

  init(buff, nx, ny, nz, kx, ky, kz, dx, dy, dz, kappa, time);

  PSGridCopyin(g, buff);

  ce = cw = kappa*dt/(dx*dx);
  cn = cs = kappa*dt/(dy*dy);
  ct = cb = kappa*dt/(dz*dz);
  cc = 1.0 - (ce + cw + cn + cs + ct + cb);

  gettimeofday(&time_begin, NULL);
  PSStencilRun(PSStencilMap(kernel, d, g,ce,cw,cn,cs,ct,cb,cc),
               count);
  gettimeofday(&time_end, NULL);

  time += dt * count;
  REAL *answer = (REAL *)malloc(sizeof(REAL) * nx*ny*nz);
  init(answer, nx, ny, nz, kx, ky, kz, dx, dy, dz, kappa, time);
  PSGridCopyout(g, buff);
  REAL err = accuracy(buff, answer, nx*ny*nz);
  double elapsed_time = (time_end.tv_sec - time_begin.tv_sec)
                        + (time_end.tv_usec - time_begin.tv_usec)*1.0e-6;
  REAL mflops = (nx*ny*nz)*13.0*count/elapsed_time * 1.0e-06;
  double thput = (nx * ny * nz) * sizeof(REAL) * 2.0 * count
                 / elapsed_time / (1000 * 1000 * 1000);

  fprintf(stderr, "elapsed time : %.3f (s)\n", elapsed_time);
  fprintf(stderr, "flops        : %.3f (MFlops)\n", mflops);
  fprintf(stderr, "throughput   : %.3f (GB/s)\n", thput);
  fprintf(stderr, "accuracy     : %e\n", err);  
  fprintf(stderr, "count        : %d\n", count);
  free(answer);
  PSGridFree(g);
  PSFinalize();
  return 0;
}
Пример #11
0
qreal LearningProgressModel::minAccuracy() const
{
    qreal min = 1;

    for (int i = 0; i < rowCount(); i++)
    {
        min = qMin(min, accuracy(i));
    }

    return min;
}
Пример #12
0
void exitEvent(equations *tobedestroyed){

	time(&end);
	double diff= difftime(end,start);
	ostringstream oss;
	oss<<" You took :"<<diff<<" seconds To solve "<<correct+wrong<<" equations of difficulty level:"<<tobedestroyed->difficulty<<endl;
	double a=accuracy(correct,wrong);
	if(a>90 && double((correct+wrong)*(tobedestroyed->difficulty) *100)/(diff)>50*(tobedestroyed->difficulty)){
		oss<<"\nyou are genius !! your accuracy was :"<<a<<"%"<<" and your avg. speed was more than 30 eqs per min"<<endl;
	} 
	else oss<<"\nYour accuracy :"<<a<<"%"<<endl;
	tobedestroyed->wraped->str.assign(oss.str());
	delete tobedestroyed;
	exit(0);
}
Пример #13
0
/// Return a map containing all metrics.
StringMapDouble CoverMetrics::all() const {
    StringMapDouble m;
    m["tp"] = tp();
    m["fp"] = fp();
    m["tn"] = tn();
    m["fn"] = fn();
    m["precision"]   = precision();
    m["recall"]      = recall();
    m["f1score"]     = f1score();
    m["accuracy"]    = accuracy();
    m["fprate"]      = fprate();
    m["specificity"] = specificity();
    m["fnrate"]      = fnrate();
    m["matthews"]    = matthews();
    return m;
}
Пример #14
0
play()
{
	ozcls();
	ozsetactivepage(0);
	ozsetdisplaypage(0);
	ozcls();
	if(shots<1)
	{
		ozcls();
		ozputs(0,0,"Out of Bullets!  Game Over!");
		ozngetch();
		exit(0);
	}
	ozsetfont(FONT_OZ_NORMAL);
	drawgun();
	addtoscore(0);
	addtoshots(0);
	sprintf(bullseye,"Bullseyes: %ld",bullseyes);
	ozputs(170,60,bullseye);
	accuracy(170,70);
	getsound();
	ozputs(0,70,soundstat);
	ozputs(0,30,"Press <ENTER> to pull, then <SPACE> to fire.");
	switch(ozgetch())
	{
		case KEY_BACKLIGHT: oztogglelight(); break;
		case KEY_MYPROGRAMS: endgameswitch(); exit(0);
		case KEY_LOWER_ESC: endgameswitch(); main();
		case KEY_LOWER_ENTER: pull(); break;
		case KEY_LEFT: gunpos=LEFT; break;
		case KEY_RIGHT: gunpos=RIGHT; break;
		case KEY_LOWER_MENU: help(); break;
		case 'h': help(); break;
		case 's': changesound(); break;
		case KEY_NEWLINE: ozsnap(); break;
	}
	play();
}
Пример #15
0
void gradient_descent(int num_threads, matrix_t* rolled_theta, unsigned int layer_sizes[], unsigned int num_layers,
		unsigned int num_labels, matrix_t* X, matrix_t* y, double lamda, unsigned int iteration_number)
{
	double start, end;
	double cpu_time_used;
	start = omp_get_wtime();

	unsigned int theta_sizes[][2] = {{25, 401}, {10, 26}};
	matrix_t* gradient;

	unsigned int i;
	for(i=0; i < iteration_number; i++)
	{
		NN_cost_function(num_threads, &gradient, rolled_theta, layer_sizes, num_layers, num_labels, X, y, lamda);

		matrix_t* tmp;
		tmp = matrix_scalar_multiply(gradient, ALPHA);
		free_matrix(gradient);
		gradient = tmp;

		tmp = matrix_subtract(rolled_theta, gradient);
		free_matrix(rolled_theta);
		rolled_theta = tmp;

		free_matrix(gradient);

		if((i+1) % 100 == 0)
		{
			end = omp_get_wtime();
			cpu_time_used = end - start;
			matrix_list_t* theta = unroll_matrix_list(rolled_theta, num_layers-1, theta_sizes);
			printf("iteration #%d, accuracy: %f, time used: %f\n", i+1, accuracy(theta, X, y), cpu_time_used);
			free_matrix_list(theta);
		}
	}
	free_matrix(rolled_theta);
}
Пример #16
0
std::string item::info(bool showtext)
{
 std::stringstream dump;
 if( !is_null() )
 {
  dump << " Volume: " << volume() << "    Weight: " << weight() << "\n" <<
          " Bash: " << int(type->melee_dam) <<
          (has_flag(IF_SPEAR) ? "  Pierce: " : "  Cut: ") <<
          int(type->melee_cut) << "  To-hit bonus: " <<
          (type->m_to_hit > 0 ? "+" : "" ) << int(type->m_to_hit) << "\n" <<
          " Moves per attack: " << attack_time() << "\n";
 }

 if (is_food()) {

  it_comest* food = dynamic_cast<it_comest*>(type);
  dump << " Nutrition: " << int(food->nutr) << "\n Quench: " <<
          int(food->quench) << "\n Enjoyability: " << int(food->fun);

 } else if (is_food_container()) {

 // added charge display for debugging
 
  it_comest* food = dynamic_cast<it_comest*>(contents[0].type);
  dump << " Nutrition: " << int(food->nutr) << "\n Quench: " <<
          int(food->quench) << "\n Enjoyability: " << int(food->fun)
          << "\n Charges: " << int(contents[0].charges);

 } else if (is_ammo()) {
 
  // added charge display for debugging

  it_ammo* ammo = dynamic_cast<it_ammo*>(type);
  dump << " Type: " << ammo_name(ammo->type) << "\n Damage: " <<
           int(ammo->damage) << "\n Armor-pierce: " << int(ammo->pierce) <<
           "\n Range: " << int(ammo->range) << "\n Accuracy: " <<
           int(100 - ammo->accuracy) << "\n Recoil: " << int(ammo->recoil)
           << "\n Count: " << int(ammo->count);

 } else if (is_ammo_container()) {

  it_ammo* ammo = dynamic_cast<it_ammo*>(contents[0].type);
  dump << " Type: " << ammo_name(ammo->type) << "\n Damage: " <<
           int(ammo->damage) << "\n Armor-pierce: " << int(ammo->pierce) <<
           "\n Range: " << int(ammo->range) << "\n Accuracy: " <<
           int(100 - ammo->accuracy) << "\n Recoil: " << int(ammo->recoil)
           << "\n Count: " << int(contents[0].charges); 
           
 } else if (is_gun()) {

  it_gun* gun = dynamic_cast<it_gun*>(type);
  int ammo_dam = 0, ammo_recoil = 0;
  bool has_ammo = (curammo != NULL && charges > 0);
  if (has_ammo) {
   ammo_dam = curammo->damage;
   ammo_recoil = curammo->recoil;
  }
   
  dump << " Skill used: " << skill_name(gun->skill_used) << "\n Ammunition: " <<
          clip_size() << " rounds of " << ammo_name(ammo_type());

  dump << "\n Damage: ";
  if (has_ammo)
   dump << ammo_dam;
  dump << (gun_damage(false) >= 0 ? "+" : "" ) << gun_damage(false);
  if (has_ammo)
   dump << " = " << gun_damage();

  dump << "\n Accuracy: " << int(100 - accuracy());

  dump << "\n Recoil: ";
  if (has_ammo)
   dump << ammo_recoil;
  dump << (recoil(false) >= 0 ? "+" : "" ) << recoil(false);
  if (has_ammo)
   dump << " = " << recoil();

  dump << "\n Reload time: " << int(gun->reload_time);
  if (has_flag(IF_RELOAD_ONE))
   dump << " per round";

  if (burst_size() == 0) {
   if (gun->skill_used == sk_pistol && has_flag(IF_RELOAD_ONE))
    dump << "\n Revolver.";
   else
    dump << "\n Semi-automatic.";
  } else
   dump << "\n Burst size: " << burst_size();
  if (contents.size() > 0)
   dump << "\n";
  for (int i = 0; i < contents.size(); i++)
   dump << "\n+" << contents[i].tname();

 } else if (is_gunmod()) {

  it_gunmod* mod = dynamic_cast<it_gunmod*>(type);
  if (mod->accuracy != 0)
   dump << " Accuracy: " << (mod->accuracy > 0 ? "+" : "") <<
           int(mod->accuracy);
  if (mod->damage != 0)
   dump << "\n Damage: " << (mod->damage > 0 ? "+" : "") << int(mod->damage);
  if (mod->clip != 0)
   dump << "\n Magazine: " << (mod->clip > 0 ? "+" : "") << int(mod->damage) << "%";
  if (mod->recoil != 0)
   dump << "\n Recoil: " << int(mod->recoil);
  if (mod->burst != 0)
   dump << "\n Burst: " << (mod->clip > 0 ? "+" : "") << int(mod->clip);
  if (mod->newtype != AT_NULL)
   dump << "\n " << ammo_name(mod->newtype);
  dump << "\n Used on: ";
  if (mod->used_on_pistol)
   dump << "Pistols.  ";
  if (mod->used_on_shotgun)
   dump << "Shotguns.  ";
  if (mod->used_on_smg)
   dump << "SMGs.  ";
  if (mod->used_on_rifle)
   dump << "Rifles.";

 } else if (is_armor()) {

  it_armor* armor = dynamic_cast<it_armor*>(type);
  dump << " Covers: ";
  if (armor->covers & mfb(bp_head))
   dump << "The head. ";
  if (armor->covers & mfb(bp_eyes))
   dump << "The eyes. ";
  if (armor->covers & mfb(bp_mouth))
   dump << "The mouth. ";
  if (armor->covers & mfb(bp_torso))
   dump << "The torso. ";
  if (armor->covers & mfb(bp_arms))
   dump << "The arms. ";   
  if (armor->covers & mfb(bp_hands))
   dump << "The hands. ";
  if (armor->covers & mfb(bp_legs))
   dump << "The legs. ";
  if (armor->covers & mfb(bp_feet))
   dump << "The feet. ";
  dump << "\n Encumberment: "			<< int(armor->encumber) <<
          "\n Bashing protection: "		<< int(armor->dmg_resist) <<
          "\n Cut protection: "			<< int(armor->cut_resist) <<
          "\n Environmental protection: "	<< int(armor->env_resist) <<
          "\n Warmth: "				<< int(armor->warmth) <<
          "\n Storage: "			<< int(armor->storage);

} else if (is_book()) {

  it_book* book = dynamic_cast<it_book*>(type);
  if (book->type == sk_null)
   dump << " Just for fun.\n";
  else {
   dump << " Can bring your " << skill_name(book->type) << " skill to " <<
           int(book->level) << std::endl;
   if (book->req == 0)
    dump << " It can be understood by beginners.\n";
   else
    dump << " Requires " << skill_name(book->type) << " level " <<
            int(book->req) << " to understand.\n";
  }
  dump << " Requires intelligence of " << int(book->intel) << " to easily read." << std::endl;
  if (book->fun != 0)
   dump << " Reading this book affects your morale by " <<
           (book->fun > 0 ? "+" : "") << int(book->fun) << std::endl;
  dump << " This book takes " << int(book->time) << " minutes to read.";

 } else if (is_tool()) {

  it_tool* tool = dynamic_cast<it_tool*>(type);
  dump << " Maximum " << tool->max_charges << " charges";
  if (tool->ammo == AT_NULL)
   dump << ".";
  else
   dump << " of " << ammo_name(tool->ammo) << ".";

 } else if (is_style()) {

  dump << "\n";
  it_style* style = dynamic_cast<it_style*>(type);
  for (int i = 0; i < style->moves.size(); i++) {
   dump << default_technique_name(style->moves[i].tech) <<
           ". Requires Unarmed Skill of " << style->moves[i].level << "\n";
  }

 } else if (!is_null() && type->techniques != 0) {

  dump << "\n";
  for (int i = 1; i < NUM_TECHNIQUES; i++) {
   if (type->techniques & mfb(i))
    dump << default_technique_name( technique_id(i) ) << "; ";
  }

 }

 if ( showtext && !is_null() ) {
  dump << "\n\n" << type->description << "\n";
  if (contents.size() > 0) {
   if (is_gun()) {
    for (int i = 0; i < contents.size(); i++)
     dump << "\n " << contents[i].type->description;
   } else
    dump << "\n " << contents[0].type->description;
   dump << "\n";
  }
 }
 return dump.str();
}
Пример #17
0
void s_accuracy(void)
{
    accuracy(0);
}
Пример #18
0
int bench_main(int argc, char *argv[])
{
     double tmin = 0.0;
     double tol;
     int repeat = 0;
     int rounds = 10;
     int iarounds = 0;
     int arounds = 1; /* this is too low for precise results */
     int c;

     report = report_verbose; /* default */
     verbose = 0;

     tol = SINGLE_PRECISION ? 1.0e-3 : (QUAD_PRECISION ? 1e-29 : 1.0e-10);

     main_init(&argc, &argv);

     bench_srand(1);

     while ((c = my_getopt (argc, argv, options)) != -1) {
	  switch (c) {
	      case 't' :
		   tmin = strtod(my_optarg, 0);
		   break;
	      case 'r':
		   repeat = atoi(my_optarg);
		   break;
	      case 's':
		   timer_init(tmin, repeat);
		   speed(my_optarg, 0);
		   break;
	      case 'S':
		   timer_init(tmin, repeat);
		   speed(my_optarg, 1);
		   break;
	      case 'd':
		   report_can_do(my_optarg);
		   break;
	      case 'o':
		   useropt(my_optarg);
		   break;
	      case 'v':
		   if (verbose >= 0) { /* verbose < 0 disables output */
			if (my_optarg)
			     verbose = atoi(my_optarg);
			else
			     ++verbose;
		   }
		   break;
	      case 'y':
		   verify(my_optarg, rounds, tol);
		   break;
	      case 'a':
		   accuracy(my_optarg, arounds, iarounds);
		   break;
	      case 'i':
		   report_info(my_optarg);
		   break;
	      case 'I':
		   report_info_all();
		   break;
	      case 'h':
		   if (verbose >= 0) my_usage(argv[0], options);
		   break;

	      case 300: /* --report-mflops */
		   report = report_mflops;
		   break;

	      case 310: /* --report-time */
		   report = report_time;
		   break;

 	      case 320: /* --report-benchmark */
		   report = report_benchmark;
		   break;

 	      case 330: /* --report-verbose */
		   report = report_verbose;
		   break;

	      case 400: /* --print-time-min */
		   timer_init(tmin, repeat);
		   ovtpvt("%g\n", time_min);
		   break;

	      case 401: /* --verify-rounds */
		   rounds = atoi(my_optarg);
		   break;

	      case 402: /* --print-precision */
		   if (SINGLE_PRECISION)
			ovtpvt("single\n");
		   else if (QUAD_PRECISION)
			ovtpvt("quad\n");
		   else if (LDOUBLE_PRECISION)
			ovtpvt("long-double\n");
		   else if (DOUBLE_PRECISION)
			ovtpvt("double\n");
		   else 
			ovtpvt("unknown %d\n", sizeof(bench_real));
		   break;

	      case 403: /* --verify-tolerance */
		   tol = strtod(my_optarg, 0);
		   break;

	      case 404: /* --random-seed */
		   bench_srand(atoi(my_optarg));
		   break;

	      case 405: /* --accuracy-rounds */
		   arounds = atoi(my_optarg);
		   break;
		   
	      case 406: /* --impulse-accuracy-rounds */
		   iarounds = atoi(my_optarg);
		   break;
		   
	      case '?':
		   /* my_getopt() already printed an error message. */
		   cleanup();
		   return 1;

	      default:
		   abort ();
	  }
     }

     /* assume that any remaining arguments are problems to be
        benchmarked */
     while (my_optind < argc) {
	  timer_init(tmin, repeat);
	  speed(argv[my_optind++], 0);
     }

     cleanup();
     return 0;
}
Пример #19
0
int main(int argc, char** argv)
{
    if (argc != 7)
    {
        usage(argc,argv);
    }

    char *pfile, *tfile, *ofile;// *testFile;
    int iterations = atoi(argv[3]);

    pfile = argv[4];
    tfile = argv[5];
    ofile = argv[6];
    //testFile = argv[7];
    int numCols = atoi(argv[1]);
    int numRows = atoi(argv[1]);
    int layers = atoi(argv[2]);

    /* calculating parameters*/

    float dx = chip_height/numRows;
    float dy = chip_width/numCols;
    float dz = t_chip/layers;

    float Cap = FACTOR_CHIP * SPEC_HEAT_SI * t_chip * dx * dy;
    float Rx = dy / (2.0 * K_SI * t_chip * dx);
    float Ry = dx / (2.0 * K_SI * t_chip * dy);
    float Rz = dz / (K_SI * dx * dy);

    // cout << Rx << " " << Ry << " " << Rz << endl;
    float max_slope = MAX_PD / (FACTOR_CHIP * t_chip * SPEC_HEAT_SI);
    float dt = PRECISION / max_slope;


    float *powerIn, *tempOut, *tempIn, *tempCopy;// *pCopy;
    //    float *d_powerIn, *d_tempIn, *d_tempOut;
    int size = numCols * numRows * layers;

    powerIn = (float*)calloc(size, sizeof(float));
    tempCopy = (float*)malloc(size * sizeof(float));
    tempIn = (float*)calloc(size,sizeof(float));
    tempOut = (float*)calloc(size, sizeof(float));
    //pCopy = (float*)calloc(size,sizeof(float));
    float* answer = (float*)calloc(size, sizeof(float));

    // outCopy = (float*)calloc(size, sizeof(float));
    readinput(powerIn,numRows, numCols, layers,pfile);
    readinput(tempIn, numRows, numCols, layers, tfile);

    memcpy(tempCopy,tempIn, size * sizeof(float));

hclib_pragma_marker("omp_to_hclib", "", "pragma254_omp_to_hclib");
    {
    struct timeval start, stop;
    float time;
    gettimeofday(&start,NULL);
    computeTempOMP(powerIn, tempIn, tempOut, numCols, numRows, layers, Cap, Rx, Ry, Rz, dt,iterations);
    gettimeofday(&stop,NULL);
    time = (stop.tv_usec-start.tv_usec)*1.0e-6 + stop.tv_sec - start.tv_sec;
    computeTempCPU(powerIn, tempCopy, answer, numCols, numRows, layers, Cap, Rx, Ry, Rz, dt,iterations);

    float acc = accuracy(tempOut,answer,numRows*numCols*layers);
    printf("Time: %.3f (s)\n",time);
    printf("Accuracy: %e\n",acc);
    }
    writeoutput(tempOut,numRows, numCols, layers, ofile);
    free(tempIn);
    free(tempOut); free(powerIn);
    return 0;
}	
Пример #20
0
int doubles_are_equal(const double tried, const double expected) {
    return max(tried, expected) - min(tried, expected) < accuracy(significant_figures, max(tried, expected));
}
/* Test a composite of a given operation, source, and destination picture.  */
Bool
blend_test(Display *dpy, picture_info *win, picture_info *dst,
	   const int *op, int num_op,
	   const picture_info **src_color, int num_src,
	   const picture_info **dst_color, int num_dst)
{
	color4d expected, tested, tdst;
	char testname[20];
	int i, j, k, y, iter;
	int page, num_pages;

	/* If the window is smaller than the number of sources to test,
	 * we need to break the sources up into pages.
	 *
	 * We however assume that the window will always be wider than num_ops.
	 */
	num_pages = num_src / win_height + 1;

	k = y = 0;
	while (k < num_dst) {
	    XImage *image;
	    int k0 = k, k1 = k;
	    int this_src, rem_src;

	    rem_src = num_src;
	    for (page = 0; page < num_pages; page++) {
		    this_src = rem_src / (num_pages - page);
		    for (iter = 0; iter < pixmap_move_iter; iter++) {
			    k1 = k0;
			    y = 0;
			    while (k1 < num_dst && y + this_src <= win_height) {
				    XRenderComposite(dpy, PictOpSrc,
						     dst_color[k1++]->pict, 0, dst->pict,
						     0, 0,
						     0, 0,
						     0, y,
						     num_op, this_src);
				    for (j = 0; j < this_src; j++) {
					    for (i = 0; i < num_op; i++) {
						    XRenderComposite(dpy, ops[op[i]].op,
								     src_color[j]->pict, 0, dst->pict,
								     0, 0,
								     0, 0,
								     i, y,
								     1, 1);
					    }
					    y++;
				    }
			    }
		    }

		    image = XGetImage(dpy, dst->d,
				      0, 0, num_ops, y,
				      0xffffffff, ZPixmap);
		    copy_pict_to_win(dpy, dst, win, win_width, win_height);

		    y = 0;
		    for (k = k0; k < k1; k++) {
			    XRenderDirectFormat dst_acc;

			    accuracy(&dst_acc,
				     &dst->format->direct,
				     &dst_color[k]->format->direct);

			    tdst = dst_color[k]->color;
			    color_correct(dst, &tdst);

			    for (j = 0; j < this_src; j++) {
				    XRenderDirectFormat acc;

				    accuracy(&acc, &src_color[j]->format->direct, &dst_acc);

				    for (i = 0; i < num_op; i++) {
					    get_pixel_from_image(image, dst, i, y, &tested);

					    do_composite(ops[op[i]].op,
							 &src_color[j]->color,
							 NULL,
							 &tdst,
							 &expected,
							 FALSE);
					    color_correct(dst, &expected);

					    if (eval_diff(&acc, &expected, &tested) > 3.) {
						    char *srcformat;

						    snprintf(testname, 20, "%s blend", ops[op[i]].name);
						    describe_format(&srcformat, NULL, src_color[j]->format);
						    print_fail(testname, &expected, &tested, 0, 0,
							       eval_diff(&acc, &expected, &tested));
						    printf("src color: %.2f %.2f %.2f %.2f (%s)\n"
							   "dst color: %.2f %.2f %.2f %.2f\n",
							   src_color[j]->color.r, src_color[j]->color.g,
							   src_color[j]->color.b, src_color[j]->color.a,
							   srcformat,
							   dst_color[k]->color.r,
							   dst_color[k]->color.g,
							   dst_color[k]->color.b,
							   dst_color[k]->color.a);
						    printf("src: %s, dst: %s\n", src_color[j]->name, dst->name);
						    free(srcformat);
						    return FALSE;
					    }
				    }
				    y++;
			    }
		    }

		    XDestroyImage(image);
		    rem_src -= this_src;
	    }
	}

	return TRUE;
}
Пример #22
0
bool double_is_greater(double actual, double expected) {
    return expected > actual - accuracy(significant_figures, max(actual, expected));
}
Пример #23
0
void binary_class_predict(FILE *input, FILE *output){
	int    total = 0;
	int    *labels;
	int    max_nr_attr = 64;
	struct svm_node *x = Malloc(struct svm_node, max_nr_attr);
	dvec_t dec_values;
	ivec_t true_labels;


	int svm_type=svm_get_svm_type(model);

	if (svm_type==NU_SVR || svm_type==EPSILON_SVR){
		fprintf(stderr, "wrong svm type.");
		exit(1);
	}

	labels = Malloc(int, svm_get_nr_class(model));
	svm_get_labels(model, labels);

	max_line_len = 1024;
	line = (char *)malloc(max_line_len*sizeof(char));
	while(readline(input) != NULL)
	{
		int i = 0;
		double target_label, predict_label;
		char *idx, *val, *label, *endptr;
		int inst_max_index = -1; // strtol gives 0 if wrong format, and precomputed kernel has <index> start from 0

		label = strtok(line," \t");
		target_label = strtod(label,&endptr);
		if(endptr == label)
			exit_input_error(total+1);

		while(1)
		{
			if(i>=max_nr_attr - 2)	// need one more for index = -1
			{
				max_nr_attr *= 2;
				x = (struct svm_node *) realloc(x,max_nr_attr*sizeof(struct svm_node));
			}

			idx = strtok(NULL,":");
			val = strtok(NULL," \t");

			if(val == NULL)
				break;
			errno = 0;
			x[i].index = (int) strtol(idx,&endptr,10);
			if(endptr == idx || errno != 0 || *endptr != '\0' || x[i].index <= inst_max_index)
				exit_input_error(total+1);
			else
				inst_max_index = x[i].index;

			errno = 0;
			x[i].value = strtod(val,&endptr);
			if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
				exit_input_error(total+1);

			++i;
		}
		x[i].index = -1;

		predict_label = svm_predict(model,x);
		fprintf(output,"%g\n",predict_label);


		double dec_value;
		svm_predict_values(model, x, &dec_value);
		true_labels.push_back((target_label > 0)? 1: -1);
		if(labels[0] <= 0) dec_value *= -1;
		dec_values.push_back(dec_value);
	}

	// validation_function(dec_values, true_labels);
	accuracy(dec_values, true_labels);
	bac(dec_values, true_labels);

	free(labels);
	free(x);
}
Пример #24
0
void i_accuracy(pob o)
{
    if (o->known < 1) o->known = 1;
    Objects[o->id].known = 1;
    accuracy(o->blessing);
}
Пример #25
0
int main(int argc, char *argv[]) 
{
  
  struct timeval time_begin, time_end;

  int    nx    = NX;
  int    ny    = NX;
  int    nz    = NX;
  REAL *f1 = (REAL *)malloc(sizeof(REAL)*NX*NX*NX);
  REAL *f2 = (REAL *)malloc(sizeof(REAL)*NX*NX*NX);  

  REAL   time  = 0.0;
  int    count = 0;  

  REAL l, dx, dy, dz, kx, ky, kz, kappa, dt;
  REAL ce, cw, cn, cs, ct, cb, cc;

  l = 1.0;
  kappa = 0.1;
  dx = dy = dz = l / nx;
  kx = ky = kz = 2.0 * M_PI;
  dt = 0.1*dx*dx / kappa;

  init(f1, nx, ny, nz, kx, ky, kz, dx, dy, dz, kappa, time);

  ce = cw = kappa*dt/(dx*dx);
  cn = cs = kappa*dt/(dy*dy);
  ct = cb = kappa*dt/(dz*dz);
  cc = 1.0 - (ce + cw + cn + cs + ct + cb);

  diffusion_loop_t diffusion_loop = diffusion_baseline;
  if (argc == 2) {
    if (strcmp(argv[1], "openmp") == 0) {
      diffusion_loop = diffusion_openmp;
    }
  }
  
  gettimeofday(&time_begin, NULL);
  diffusion_loop(f1, f2, nx, ny, nz, ce, cw, cn, cs, ct, cb, cc, dt,
                 &f1, &time, &count);
  gettimeofday(&time_end, NULL);

  REAL *answer = (REAL *)malloc(sizeof(REAL) * nx*ny*nz);
  init(answer, nx, ny, nz, kx, ky, kz, dx, dy, dz, kappa, time);

  REAL err = accuracy(f1, answer, nx*ny*nz);
  double elapsed_time = (time_end.tv_sec - time_begin.tv_sec)
      + (time_end.tv_usec - time_begin.tv_usec)*1.0e-6;
  REAL mflops = (nx*ny*nz)*13.0*count/elapsed_time * 1.0e-06;
  double thput = (nx * ny * nz) * sizeof(REAL) * 2.0 * count
      / elapsed_time / (1 << 30);

  fprintf(stderr, "elapsed time : %.3f (s)\n", elapsed_time);
  fprintf(stderr, "flops        : %.3f (MFlops)\n", mflops);
  fprintf(stderr, "throughput   : %.3f (GB/s)\n", thput);  
  fprintf(stderr, "accuracy     : %e\n", err);
  free(answer);
  free(f1);
  free(f2);
  return 0;
}
Пример #26
0
std::string item::info(bool showtext, std::vector<iteminfo> *dump)
{
 std::stringstream temp1, temp2;

 if( !is_null() )
 {
  dump->push_back(iteminfo("BASE", " Volume: ", "", int(volume()), "", false, true));
  dump->push_back(iteminfo("BASE", "    Weight: ", "", int(weight()), "", true, true));
  dump->push_back(iteminfo("BASE", " Bash: ", "", int(type->melee_dam), "", false));
  dump->push_back(iteminfo("BASE", (has_flag(IF_SPEAR) ? "  Pierce: " : "  Cut: "), "", int(type->melee_cut), "", false));
  dump->push_back(iteminfo("BASE", "  To-hit bonus: ", ((type->m_to_hit > 0) ? "+" : ""), int(type->m_to_hit), ""));
  dump->push_back(iteminfo("BASE", " Moves per attack: ", "", int(attack_time()), "", true, true));

 if (type->techniques != 0)
  for (int i = 1; i < NUM_TECHNIQUES; i++)
   if (type->techniques & mfb(i))
    dump->push_back(iteminfo("TECHNIQUE", " +",default_technique_name( technique_id(i) )));
 }

 if (is_food()) {
  it_comest* food = dynamic_cast<it_comest*>(type);

  dump->push_back(iteminfo("FOOD", " Nutrition: ", "", int(food->nutr)));
  dump->push_back(iteminfo("FOOD", " Quench: ", "", int(food->quench)));
  dump->push_back(iteminfo("FOOD", " Enjoyability: ", "", int(food->fun)));

 } else if (is_food_container()) {
 // added charge display for debugging
  it_comest* food = dynamic_cast<it_comest*>(contents[0].type);

  dump->push_back(iteminfo("FOOD", " Nutrition: ", "", int(food->nutr)));
  dump->push_back(iteminfo("FOOD", " Quench: ", "", int(food->quench)));
  dump->push_back(iteminfo("FOOD", " Enjoyability: ", "", int(food->fun)));
  dump->push_back(iteminfo("FOOD", " Portions: ", "", abs(int(contents[0].charges))));

 } else if (is_ammo()) {
  // added charge display for debugging
  it_ammo* ammo = dynamic_cast<it_ammo*>(type);

  dump->push_back(iteminfo("AMMO", " Type: ", ammo_name(ammo->type)));
  dump->push_back(iteminfo("AMMO", " Damage: ", "", int(ammo->damage)));
  dump->push_back(iteminfo("AMMO", " Armor-pierce: ", "", int(ammo->pierce)));
  dump->push_back(iteminfo("AMMO", " Range: ", "", int(ammo->range)));
  dump->push_back(iteminfo("AMMO", " Accuracy: ", "", int(100 - ammo->accuracy)));
  dump->push_back(iteminfo("AMMO", " Recoil: ", "", int(ammo->recoil), "", true, true));
  dump->push_back(iteminfo("AMMO", " Count: ", "", int(ammo->count)));

 } else if (is_ammo_container()) {
  it_ammo* ammo = dynamic_cast<it_ammo*>(contents[0].type);

  dump->push_back(iteminfo("AMMO", " Type: ", ammo_name(ammo->type)));
  dump->push_back(iteminfo("AMMO", " Damage: ", "", int(ammo->damage)));
  dump->push_back(iteminfo("AMMO", " Armor-pierce: ", "", int(ammo->pierce)));
  dump->push_back(iteminfo("AMMO", " Range: ", "", int(ammo->range)));
  dump->push_back(iteminfo("AMMO", " Accuracy: ", "", int(100 - ammo->accuracy)));
  dump->push_back(iteminfo("AMMO", " Recoil: ", "", int(ammo->recoil), "", true, true));
  dump->push_back(iteminfo("AMMO", " Count: ", "", int(contents[0].charges)));

 } else if (is_gun()) {
  it_gun* gun = dynamic_cast<it_gun*>(type);
  int ammo_dam = 0, ammo_recoil = 0;
  bool has_ammo = (curammo != NULL && charges > 0);
  if (has_ammo) {
   ammo_dam = curammo->damage;
   ammo_recoil = curammo->recoil;
  }

  dump->push_back(iteminfo("GUN", " Skill used: ", gun->skill_used->name()));
  dump->push_back(iteminfo("GUN", " Ammunition: ", "", int(clip_size()), " rounds of " + ammo_name(ammo_type())));

  temp1.str("");
  if (has_ammo)
   temp1 << ammo_dam;

  temp1 << (gun_damage(false) >= 0 ? "+" : "" );

  temp2.str("");
  if (has_ammo)
   temp2 << " = " << gun_damage();

  dump->push_back(iteminfo("GUN", " Damage: ", temp1.str(), int(gun_damage(false)), temp2.str()));
  dump->push_back(iteminfo("GUN", " Accuracy: ", "", int(100 - accuracy())));

  temp1.str("");
  if (has_ammo)
   temp1 << ammo_recoil;

  temp1 << (recoil(false) >= 0 ? "+" : "" );

  temp2.str("");
  if (has_ammo)
   temp2 << " = " << recoil();

  dump->push_back(iteminfo("GUN"," Recoil: ", temp1.str(), int(recoil(false)), temp2.str(), true, true));

  dump->push_back(iteminfo("GUN", " Reload time: ", "", int(gun->reload_time), ((has_flag(IF_RELOAD_ONE)) ? " per round" : ""), true, true));

  if (burst_size() == 0) {
   if (gun->skill_used == Skill::skill("pistol") && has_flag(IF_RELOAD_ONE))
    dump->push_back(iteminfo("GUN", " Revolver."));
   else
    dump->push_back(iteminfo("GUN", " Semi-automatic."));
  } else
   dump->push_back(iteminfo("GUN", " Burst size: ", "", int(burst_size())));

  if (contents.size() > 0)
   dump->push_back(iteminfo("GUN", "\n"));

  temp1.str("");
  for (int i = 0; i < contents.size(); i++)
   temp1 << "\n+" << contents[i].tname();

  dump->push_back(iteminfo("GUN", temp1.str()));

 } else if (is_gunmod()) {
  it_gunmod* mod = dynamic_cast<it_gunmod*>(type);

  if (mod->accuracy != 0)
   dump->push_back(iteminfo("GUNMOD", " Accuracy: ", ((mod->accuracy > 0) ? "+" : ""), int(mod->accuracy)));
  if (mod->damage != 0)
   dump->push_back(iteminfo("GUNMOD", " Damage: ", ((mod->damage > 0) ? "+" : ""), int(mod->damage)));
  if (mod->clip != 0)
   dump->push_back(iteminfo("GUNMOD", " Magazine: ", ((mod->clip > 0) ? "+" : ""), int(mod->clip), "%"));
  if (mod->recoil != 0)
   dump->push_back(iteminfo("GUNMOD", " Recoil: ", ((mod->recoil > 0) ? "+" : ""), int(mod->recoil), "", true, true));
  if (mod->burst != 0)
   dump->push_back(iteminfo("GUNMOD", " Burst: ", (mod->burst > 0 ? "+" : ""), int(mod->burst)));

  if (mod->newtype != AT_NULL)
   dump->push_back(iteminfo("GUNMOD", " " + ammo_name(mod->newtype)));

  temp1.str("");
  temp1 << " Used on: ";
  if (mod->used_on_pistol)
   temp1 << "Pistols.  ";
  if (mod->used_on_shotgun)
   temp1 << "Shotguns.  ";
  if (mod->used_on_smg)
   temp1 << "SMGs.  ";
  if (mod->used_on_rifle)
   temp1 << "Rifles.";

  dump->push_back(iteminfo("GUNMOD", temp1.str()));

 } else if (is_armor()) {
  it_armor* armor = dynamic_cast<it_armor*>(type);
  
  temp1.str("");
  temp1 << " Covers: ";
  if (armor->covers & mfb(bp_head))
   temp1 << "The head. ";
  if (armor->covers & mfb(bp_eyes))
   temp1 << "The eyes. ";
  if (armor->covers & mfb(bp_mouth))
   temp1 << "The mouth. ";
  if (armor->covers & mfb(bp_torso))
   temp1 << "The torso. ";
  if (armor->covers & mfb(bp_arms))
   temp1 << "The arms. ";
  if (armor->covers & mfb(bp_hands))
   temp1 << "The hands. ";
  if (armor->covers & mfb(bp_legs))
   temp1 << "The legs. ";
  if (armor->covers & mfb(bp_feet))
   temp1 << "The feet. ";

  dump->push_back(iteminfo("ARMOR", temp1.str()));

    if (has_flag(IF_FIT))
    {
        dump->push_back(iteminfo("ARMOR", " Encumberment: ", "", int(armor->encumber) - 1, " (fits)", true, true));
    }
    else
    {
        dump->push_back(iteminfo("ARMOR", " Encumberment: ", "", int(armor->encumber), "", true, true));
    }

  dump->push_back(iteminfo("ARMOR", " Bashing protection: ", "", int(armor->dmg_resist)));
  dump->push_back(iteminfo("ARMOR", " Cut protection: ", "", int(armor->cut_resist)));
  dump->push_back(iteminfo("ARMOR", " Environmental protection: ", "", int(armor->env_resist)));
  dump->push_back(iteminfo("ARMOR", " Warmth: ", "", int(armor->warmth)));
  dump->push_back(iteminfo("ARMOR", " Storage: ", "", int(armor->storage)));

} else if (is_book()) {

  it_book* book = dynamic_cast<it_book*>(type);
  if (!book->type)
   dump->push_back(iteminfo("BOOK", " Just for fun."));
  else {
    dump->push_back(iteminfo("BOOK", " Can bring your ", book->type->name() + " skill to ", int(book->level)));

   if (book->req == 0)
    dump->push_back(iteminfo("BOOK", " It can be understood by beginners."));
   else
    dump->push_back(iteminfo("BOOK", " Requires ", book->type->name() + " level ", int(book->req), " to understand.", true, true));
  }

  dump->push_back(iteminfo("BOOK", " Requires intelligence of ", "", int(book->intel), " to easily read.", true, true));
  if (book->fun != 0)
   dump->push_back(iteminfo("BOOK", " Reading this book affects your morale by ", (book->fun > 0 ? "+" : ""), int(book->fun)));

  dump->push_back(iteminfo("BOOK", " This book takes ", "", int(book->time), " minutes to read.", true, true));

 } else if (is_tool()) {
  it_tool* tool = dynamic_cast<it_tool*>(type);

  if ((tool->max_charges)!=0)
   dump->push_back(iteminfo("TOOL", " Maximum ", "", int(tool->max_charges), " charges" + ((tool->ammo == AT_NULL) ? "" : (" of " + ammo_name(tool->ammo))) + "."));

 } else if (is_style()) {
  it_style* style = dynamic_cast<it_style*>(type);

  for (int i = 0; i < style->moves.size(); i++) {
   dump->push_back(iteminfo("STYLE", default_technique_name(style->moves[i].tech), ". Requires Unarmed Skill of ", int(style->moves[i].level)));
  }

 }

 if ( showtext && !is_null() ) {
  dump->push_back(iteminfo("DESCRIPTION", type->description));
    if (is_armor() && has_flag(IF_FIT))
    {
        dump->push_back(iteminfo("DESCRIPTION", "\n\n"));
        dump->push_back(iteminfo("DESCRIPTION", "This piece of clothing fits you perfectly."));
    }  
  if (contents.size() > 0) {
   if (is_gun()) {
    for (int i = 0; i < contents.size(); i++)
     dump->push_back(iteminfo("DESCRIPTION", contents[i].type->description));
   } else
    dump->push_back(iteminfo("DESCRIPTION", contents[0].type->description));
  }
 }

 temp1.str("");
 std::vector<iteminfo>& vecData = *dump; // vector is not copied here
 for (int i = 0; i < vecData.size(); i++) {
  if (vecData[i].sType == "DESCRIPTION")
   temp1 << "\n";

  temp1 << vecData[i].sName;
  temp1 << vecData[i].sPre;

  if (vecData[i].iValue != -999)
   temp1 << vecData[i].iValue;

  temp1 << vecData[i].sPost;
  temp1 << ((vecData[i].bNewLine) ? "\n" : "");
 }

 return temp1.str();
}
Пример #27
0
 std::string BarrelPart::describe() const
 {
   std::stringstream ss;
   ss << "Barrel: " << name() << ", Accuracy: " << accuracy();
   return ss.str();
 }
Пример #28
0
int main(int argc, char *argv[])
{
    PhysisInit(&argc, &argv);
    grid3d_real g = grid3d_real_new(NX, NX, NX);
    struct timeval time_begin, time_end;

    int    nx    = NX;
    int    ny    = NX;
    int    nz    = NX;
    REAL  *buff  = (REAL *)malloc(sizeof(REAL) *nx*ny*nz);
    REAL   time  = 0.0;
    int    count = 0;
    REAL l, dx, dy, dz, kx, ky, kz, kappa, dt;
    REAL ce, cw, cn, cs, ct, cb, cc;

    l = 1.0;
    kappa = 0.1;
    dx = dy = dz = l / nx;
    kx = ky = kz = 2.0 * M_PI;
    dt = 0.1*dx*dx / kappa;

    init(buff, nx, ny, nz, kx, ky, kz, dx, dy, dz, kappa, time);

    grid_copyin(g, buff);

    ce = cw = kappa*dt/(dx*dx);
    cn = cs = kappa*dt/(dy*dy);
    ct = cb = kappa*dt/(dz*dz);
    cc = 1.0 - (ce + cw + cn + cs + ct + cb);

    //clock_gettime(CLOCK_REALTIME, &time_begin);
    gettimeofday(&time_begin, NULL);
    do {
        if (count && (count % 100 == 0)) {
            fprintf(stderr, "time(%4d)=%7.5f\n", count, time + dt);
        }
        grid_update2(kernel,g,ce,cw,cn,cs,ct,cb,cc);
        time += dt;
        count++;
    } while (time + 0.5*dt < 0.1);
    //clock_gettime(CLOCK_REALTIME, &time_end);
    gettimeofday(&time_end, NULL);

    REAL *answer = (REAL *)malloc(sizeof(REAL) * nx*ny*nz);
    init(answer, nx, ny, nz, kx, ky, kz, dx, dy, dz, kappa, time);
    grid_copyout(g, buff);

    REAL err = accuracy(buff, answer, nx*ny*nz);
    double elapsed_time = (time_end.tv_sec - time_begin.tv_sec)
                          + (time_end.tv_usec - time_begin.tv_usec)*1.0e-6;
    REAL mflops = (nx*ny*nz)*13.0*count/elapsed_time * 1.0e-06;
    double thput = (nx * ny * nz) * sizeof(REAL) * 2.0 * count
                   / elapsed_time * 1.0e-9;

    fprintf(stderr, "elapsed time : %.3f (s)\n", elapsed_time);
    fprintf(stderr, "flops        : %.3f (MFlops)\n", mflops);
    fprintf(stderr, "throughput   : %.3f (GB/s)\n", thput);
    fprintf(stderr, "accuracy     : %e\n", err);
    free(answer);
    PhysisFinalize();
    return 0;
}
Пример #29
0
 bool Miniball::is_valid (double tolerance) const
 {
     double slack;
     return ( (accuracy (slack) < tolerance) && (slack == 0) );
 }
Пример #30
0
bool double_is_lesser(double actual, double expected) {
    return expected < actual + accuracy(significant_figures, max(actual, expected));
}