/*
 * Print complete match record to ostream 'o'.
 */
void matchRecord::printRecord(std::ostream &o) const
{
   using std::endl;
   using std::setw;
   using std::string;

   const int scrW = 79; // screen width (no. characters)

   char h  = (char)196, v  = (char)179, // horizontal,  vertical     line
        tl = (char)218, tr = (char)191, // top-left,    top-right    border corner
        bl = (char)192, br = (char)217; // bottom-left, bottom-right border corner

   int i,      // counter
       w1, w2; // widths

   string fill; // for filling rest of line with a character (eg. '-')

   string blankLine     = v + string(77, ' ') + v;
   string separatorLine = v + string(77,   h) + v;

   // print title and top border
   fill = string(scrW - 19, h);
   o << tl << h << char(17) << " Match Record " << char(16)
     << fill << tr << endl
     << blankLine  << endl;

   // print team names and date
   fill = string(scrW - 26 - teamName.get().length() - oppTeamName.get().length(), ' ');
   o << v << " " << teamName << " Vs " << oppTeamName << fill
     << "  Date: " << date << " " << v << endl
     << separatorLine << endl
     << blankLine     << endl;

   // print match result
   o << v << " Match result: ";
        if (teamScore > oppTeamScore) o << "Win ";
   else if (teamScore < oppTeamScore) o << "Loss";
   else                               o << "Draw";
   fill = string(scrW - 22, ' ');
   o << fill << " " << v << endl
     << blankLine        << endl;

   // print team scores heading
   fill = string(scrW - 15, ' ');
   o << v << " Final Scores" << fill << v << endl
     << separatorLine                     << endl;

   // print team scores
   w1 = max(teamName.get().length(), oppTeamName.get().length());
   fill = string(scrW - w1 - 8, ' ');
   o << v << " " << setw(w1) <<    teamName
     << fill     << setw(4)  <<    teamScore << " " << v << endl;
   o << v << " " << setw(w1) << oppTeamName
     << fill     << setw(4)  << oppTeamScore << " " << v << endl;
   o << blankLine                                        << endl;

   // find width of longest first and last names
   // NOTE: assuming only nPlayersPerTeam played - ie. no substitutes
   w1 = w2 = 0;
   for (i = 0; i < matchRecord::nPlayersPerTeam; ++i)
   {
      w1 = max(w1, static_cast<int>(battingRec[i].batsmansName.getFirstName().length()));
      w2 = max(w2, static_cast<int>(battingRec[i].batsmansName.getLastName().length()));
   }

   // print batting scores heading
   fill = string(scrW - 30, ' ');
   o << v << " Batting Scores";

   // print whether team batted first or second
   switch (batted1st)
   {
    case true:  o << " (batted 1st)"; break;
    case false: o << " (batted 2nd)"; break;
   }

   o << fill << v     << endl
     << separatorLine << endl;

   // print batting scores
   fill = string(scrW - w1 - w2 - 8, ' ');
   for (i = 0; i < matchRecord::nPlayersPerTeam; ++i)
   {
      o << v << " "; battingRec[i].batsmansName.printFormatted(o, w1, w2);
      o << fill;
      o << setw(3)  << battingRec[i].runsScored << " "
        << v << endl;
   }
   o << blankLine << endl;

   // print team penalty (if applicable)
   if (teamPenalty > 0)
   {
      fill = string(scrW - 18 - digits(teamPenalty), ' ');
      o << v << " Penalty Runs " << fill << -teamPenalty << " " << v << endl
        << blankLine                                             << endl;
   }

   // print bowling scores heading
   fill = string(scrW - 17, ' ');
   o << v << " Bowling Scores" << fill << v << endl
     << separatorLine << endl;

   // print bowling scores
   fill = string(scrW - w1 - w2 - 13, ' ');
   for (i = 0; i < matchRecord::nOversPerInnings; ++i)
   {
      o << v << " "; bowlingRec[i].bowlersName.printFormatted(o, w1, w2);
      o << fill;
      o << setw(2)  << bowlingRec[i].wicketsTaken << " / "
        << setw(3)  << bowlingRec[i].runsConceded << " "
        << v << endl;
   }
   o << blankLine << endl;

   // print opposition team penalty (if applicable)
   if (oppTeamPenalty > 0)
   {
      fill = string(scrW - 18 - digits(oppTeamPenalty), ' ');
      o << v << " Penalty Runs " << fill << -oppTeamPenalty << " " << v << endl
        << blankLine                                                << endl;
   }

   // print bottom border
   fill = string(scrW - 2, h);
   o << bl << fill << br << endl;
}
Example #2
0
void spit_asidstory() {
    FILE *fp = fopen("asidstory", "w");

    std::vector<ProcessKV> count_sorted_pds(process_datas.begin(), process_datas.end());
    std::sort(count_sorted_pds.begin(), count_sorted_pds.end(),
            [](const ProcessKV &lhs, const ProcessKV &rhs) {
                return lhs.second.count > rhs.second.count; });

    std::stringstream head;
    head << 
        setw(digits(max_instr)) << "Count" <<
        setw(6) << "Pid" << "  " <<
        setw(NAMELEN) << "Name" << "  " <<
        setw(sizeof(target_ulong) * 2) << "Asid" <<
        "  " << setw(digits(max_instr)) << "First" << 
        "      " << setw(digits(max_instr)) << "Last" << endl;
    fprintf(fp, "%s", head.str().c_str());
    for (auto &pd_kv : count_sorted_pds) {
        const NamePid &namepid = pd_kv.first;
        const ProcessData &pd = pd_kv.second;
        //        if (pd.count >= sample_cutoff) {
            std::stringstream ss;
            ss <<
                setw(digits(max_instr)) << pd.count <<
                setw(6) << namepid.pid << "  " <<
                setw(NAMELEN) << pd.shortname << "  " <<
                setw(sizeof(target_ulong) * 2) <<
                hex << namepid.asid << dec << setfill(' ') <<
                "  " << setw(digits(max_instr)) << pd.first <<
                "  ->  " << setw(digits(max_instr)) << pd.last << endl;
            fprintf(fp, "%s", ss.str().c_str());
            //        }
    }

    fprintf(fp, "\n");

    std::vector<ProcessKV> first_sorted_pds(process_datas.begin(), process_datas.end());
    std::sort(first_sorted_pds.begin(), first_sorted_pds.end(),
            [](const ProcessKV &lhs, const ProcessKV &rhs) {
                return lhs.second.first < rhs.second.first; });

    for (auto &pd_kv : first_sorted_pds) {
        const ProcessData &pd = pd_kv.second;

        //        if (pd.count >= sample_cutoff) {
            fprintf(fp, "%" NAMELENS "s : [", pd.shortname.c_str());
            for (unsigned i = 0; i < num_cells; i++) {
                auto it = pd.cells.find(i);
                if (it == pd.cells.end() || it->second < 2) {
                    fprintf(fp, " ");
                } else {
                    fprintf(fp, "#");
                }
            }
            fprintf(fp, "]\n");
            //        }
    }

    fclose(fp);
}
Example #3
0
int main()
{
  cout << "Example: Laplace distribution." << endl;

  try
  {
    { // Traditional tables and values.
/*`Let's start by printing some traditional tables.
*/      
      double step = 1.; // in z 
      double range = 4; // min and max z = -range to +range.
      //int precision = 17; // traditional tables are only computed to much lower precision.
      int precision = 4; // traditional table at much lower precision.
      int width = 10; // for use with setw.

      // Construct standard laplace & normal distributions l & s
        normal s; // (default location or mean = zero, and scale or standard deviation = unity)
        cout << "Standard normal distribution, mean or location = "<< s.location()
          << ", standard deviation or scale = " << s.scale() << endl;
        laplace l; // (default mean = zero, and standard deviation = unity)
        cout << "Laplace normal distribution, location = "<< l.location()
          << ", scale = " << l.scale() << endl;

/*` First the probability distribution function (pdf).
*/
      cout << "Probability distribution function values" << endl;
      cout << " z  PDF  normal     laplace    (difference)" << endl;
      cout.precision(5);
      for (double z = -range; z < range + step; z += step)
      {
        cout << left << setprecision(3) << setw(6) << z << " " 
          << setprecision(precision) << setw(width) << pdf(s, z) << "  "
          << setprecision(precision) << setw(width) << pdf(l, z)<<  "  ("
          << setprecision(precision) << setw(width) << pdf(l, z) - pdf(s, z) // difference.
          << ")" << endl;
      }
      cout.precision(6); // default
/*`Notice how the laplace is less at z = 1 , but has 'fatter' tails at 2 and 3. 

   And the area under the normal curve from -[infin] up to z,
   the cumulative distribution function (cdf).
*/
      // For a standard distribution 
      cout << "Standard location = "<< s.location()
        << ", scale = " << s.scale() << endl;
      cout << "Integral (area under the curve) from - infinity up to z " << endl;
      cout << " z  CDF  normal     laplace    (difference)" << endl;
      for (double z = -range; z < range + step; z += step)
      {
        cout << left << setprecision(3) << setw(6) << z << " " 
          << setprecision(precision) << setw(width) << cdf(s, z) << "  "
          << setprecision(precision) << setw(width) << cdf(l, z) <<  "  ("
          << setprecision(precision) << setw(width) << cdf(l, z) - cdf(s, z) // difference.
          << ")" << endl;
      }
      cout.precision(6); // default

/*`
Pretty-printing a traditional 2-dimensional table is left as an exercise for the student,
but why bother now that the Boost Math Toolkit lets you write
*/
    double z = 2.; 
    cout << "Area for gaussian z = " << z << " is " << cdf(s, z) << endl; // to get the area for z.
    cout << "Area for laplace z = " << z << " is " << cdf(l, z) << endl; // 
/*`
Correspondingly, we can obtain the traditional 'critical' values for significance levels.
For the 95% confidence level, the significance level usually called alpha,
is 0.05 = 1 - 0.95 (for a one-sided test), so we can write
*/
     cout << "95% of gaussian area has a z below " << quantile(s, 0.95) << endl;
     cout << "95% of laplace area has a z below " << quantile(l, 0.95) << endl;
   // 95% of area has a z below 1.64485
   // 95% of laplace area has a z below 2.30259
/*`and a two-sided test (a comparison between two levels, rather than a one-sided test)

*/
     cout << "95% of gaussian area has a z between " << quantile(s, 0.975)
       << " and " << -quantile(s, 0.975) << endl;
     cout << "95% of laplace area has a z between " << quantile(l, 0.975)
       << " and " << -quantile(l, 0.975) << endl;
   // 95% of area has a z between 1.95996 and -1.95996
   // 95% of laplace area has a z between 2.99573 and -2.99573
/*`Notice how much wider z has to be to enclose 95% of the area.
*/
  }
//] [/[laplace_example1]
  }
  catch(const std::exception& e)
  { // Always useful to include try & catch blocks because default policies 
    // are to throw exceptions on arguments that cause errors like underflow, overflow. 
    // Lacking try & catch blocks, the program will abort without a message below,
    // which may give some helpful clues as to the cause of the exception.
    std::cout <<
      "\n""Message from thrown exception was:\n   " << e.what() << std::endl;
  }
  return 0;
}  // int main()
Example #4
0
void Bridge_view::draw(){
  //the matrix to display
  matrix_display_t matrix;
  //if it is not sunk
  if(location_map.find(ship_name)!=location_map.end()){
    
    //get ship state info
    double course = Basic_view::state_map[ship_name].course;
    double speed = Basic_view::state_map[ship_name].speed;
    ship_location = Basic_view::location_map[ship_name];
    cout<<"Bridge view from "<<ship_name<<" position "<<ship_location<<" heading "<<course<<endl;
    
    matrix.assign(3,vector<string>(19,". "));
    
    cout.precision(0);
    for(auto it = location_map.begin(); it!=location_map.end(); it++){
      Point other_point = (*it).second;
      
      //compute the distance
      double distance = cartesian_distance(ship_location, other_point);
      
      if(distance < 0.0005 || distance > 20){
	continue;
      }

      int i;
      Course_speed cs(course, speed);

      //get horizontal script
      if(get_horizontalscripts(i, ship_location, other_point, cs)){
	if(matrix[2][i]==". "){
	  matrix[2][i][0] = (*it).first[0];
	  matrix[2][i][1] = (*it).first[1];
	}else{
	  matrix[2][i] = "**";
	}
      }
    }
  }else{
    //if it is sunk
    cout<<"Bridge view from "<<ship_name<<" sunk at "<<ship_location<<endl;
    matrix.assign(3,vector<string>(19,"w-"));
  }
  
  for(int i=0;i<3;i++){
    cout<<setw(7);
    for(int j=0;j<19;j++){
      cout<<matrix[i][j];
    }
    cout<<endl;
  }

  //Print out axle
  int startx = -90;
  for(int i=0;i<7;i++){
    cout<<setw(6)<<startx;
    startx+=30;
  }
  cout<<endl;
  
  //restore precision
  cout.precision(2);
  
  return;
}
Example #5
0
void paramFloat::print()
{
    cout<<setw(10)  << key << ": ";
    cout<< val <<endl;
}
/**
 * Loads an old 2D simulation input file and converts
 * it to the new 3D format.
 * Takes two command line arguments: the input filename and
 * output filename
 */
int main(int argc, char **argv) {
    string in_filename;     //The input filename
    string out_filename;    //The output filename
    ifstream in_file;       //Input file stream
    ofstream out_file;      //Output file stream
    int temp_int;           //Temporary int
    REAL temp_real;         //Temporary REAL
    string temp_str, title; //Temporary string
    
    int num_rows;           //The number of rows for the simulation
    int num_cols;           //The number of columns for the simulation
    int num_slices = 1;     //Total number of slices to form the 3d simulation (one 'slice' has dimension rows x columns)
    int using_convection;   //Indicates if convection is being used
    REAL **temp;
    string **cond_codes;
    string **conv_codes;
    
    //Opens the input file for reading
    //Exits the program if it fails to open
    do {
        cout << "Input File Name: ";
        cin >> in_filename;
        in_file.open(in_filename.c_str(),ios::in);
        if(!in_file.is_open()) {
            cout << "File Not found!" << endl;
        }
    } while(!in_file.is_open());
    
    //Opens the output file for reading
    //Exits the program if it fails to open
    do {
        cout << "Output File Name: ";
        cin >> out_filename;
        out_file.open(out_filename.c_str(),ios::out);
        if(!out_file.is_open()) {
            cout << "Unable to create output file" << endl;
        }
    } while(!out_file.is_open());
    
    //num_rows num_cols num_slices using_convection
    in_file >> num_rows >> num_cols >> using_convection;
    out_file << setw(20) << num_rows << setw(20) << num_cols << setw(20) << 1 << setw(20) << using_convection << endl;
    
    //chf
    in_file >> temp_real;
    out_file << setw(20) << fixed << setprecision(2) << temp_real << " ";
    
    //initial_time
    in_file >> temp_real;
    out_file << setw(20) << temp_real << endl;
    
    //title
    getline(in_file,title);
    getline(in_file,title);
    out_file << title << endl;
    
    temp = new REAL*[num_rows];
    cond_codes = new string*[num_rows];
    conv_codes = new string*[num_rows];
    for(int i = 0; i < num_rows; i++) {
        temp[i] = new REAL[num_cols];
        cond_codes[i] = new string[num_cols];
        conv_codes[i] = new string[num_cols];
    }
    
    for(int i = 0; i < num_rows; i++) {
        for(int j = 0; j < num_cols; j++) {
            in_file >> temp[i][j];
        }
    }
    
    for(int i = 0; i < num_rows; i++) {
        for(int j = 0; j < num_cols; j++) {
            in_file >> cond_codes[i][j];
        }
    }
    
    if(using_convection) {
        for(int i = 0; i < num_rows; i++) {
            for(int j = 0; j < num_cols; j++) {
                in_file >> conv_codes[i][j];
            }
        }
    }
    
    out_file << setprecision(3) << setfill(' ');
    //Prints the column (X) dimensions of the simulation to the output file
    for(int i = 0; i < num_cols; i++) {
        in_file >> temp_real;
        out_file << " " << temp_real;
    }
    out_file << endl;
    
    //Prints the row (Y) dimensions of the simulation to the output file
    for(int i = 0; i < num_rows; i++) {
        in_file >> temp_real;
        out_file << " " << temp_real;
    }
    out_file << endl;
    
    //Prints the slice (Z) dimensions of the simulation to the output file
    out_file << " " << 1.0 << endl;
    
    //Heat Production Values
    out_file << " " << 8;
    for(int i = 0; i < 8; i++) {
        in_file >> temp_real;
        out_file << " " << scientific << temp_real;
    }
    out_file << endl;
    
    //Thermal Conductivity Difference Values
    out_file << " " << 8;
    for(int i = 0; i < 8; i++) {
        in_file >> temp_real;
        out_file << " " << scientific << temp_real;
    }
    out_file << endl;
    
    if(using_convection) {
        //Fluid Heat Capacity values
        out_file << " " << 8;
        for(int i = 0; i < 8; i++) {
            in_file >> temp_real;
            out_file << " " << scientific << temp_real;
        }
        out_file << endl;
        
        //Rock Heat Capacity values
        out_file << " " << 8;
        for(int i = 0; i < 8; i++) {
            in_file >> temp_real;
            out_file << " " << scientific << temp_real;
        }
        out_file << endl;
        
        //Minimum Convection Temps
        out_file << " " << 8;
        for(int i = 0; i < 8; i++) {
            in_file >> temp_real;
            out_file << " " << scientific << temp_real;
        }
        out_file << endl;
        
        //Convection Velocity Values
        out_file << " " << 8;
        for(int i = 0; i < 8; i++) {
            in_file >> temp_real;
            out_file << " " << scientific << temp_real;
        }
        out_file << endl;
    }
    
    
    //Temperatures
    out_file << setprecision(OUT_PRECISION) << fixed;
    out_file << endl;
    for(int i = 0; i < num_rows; i++) {
        for(int j = 0; j < num_cols; j++) {
            out_file << " " << setw(OUT_PRECISION+5) << temp[i][j];
        }
        out_file << endl;
    }
    out_file << endl;
    
    //Conduction Codes
    out_file << setfill('0');
    for(int i = 0; i < num_rows; i++) {
        for(int j = 0; j < num_cols; j++) {
            temp_int = atoi(cond_codes[i][j].substr(2,2).c_str());
            out_file << " " << setw(INDEX_WIDTH) << atoi(cond_codes[i][j].substr(0,1).c_str()) << setw(INDEX_WIDTH) << atoi(cond_codes[i][j].substr(1,1).c_str());
            if(temp_int == 2) {
                out_file << setw(1) << 0;
            }
            else {
                out_file << setw(1) << 1;
            }
        }
        out_file << endl;
    }
    out_file << endl;
    
    if(using_convection) {
        //Convection Codes
        for(int i = 0; i < num_rows; i++) {
            for(int j = 0; j < num_cols; j++) {
                out_file << " " << setw(INDEX_WIDTH) << atoi(conv_codes[i][j].substr(0,1).c_str()); 
                out_file << setw(INDEX_WIDTH) << atoi(conv_codes[i][j].substr(1,1).c_str());
                out_file << setw(INDEX_WIDTH) << atoi(conv_codes[i][j].substr(2,1).c_str());
                out_file << setw(INDEX_WIDTH) << atoi(conv_codes[i][j].substr(3,1).c_str());
                if(atoi(conv_codes[i][j].substr(4,1).c_str()) == 1) {
                    out_file << setw(INDEX_WIDTH) << 2;
                }
                else if(atoi(conv_codes[i][j].substr(4,1).c_str()) == 2) {
                    out_file << setw(INDEX_WIDTH) << 1;
                }
                else if(atoi(conv_codes[i][j].substr(4,1).c_str()) == 8) {
                    out_file << setw(INDEX_WIDTH) << 9;
                }
                else if(atoi(conv_codes[i][j].substr(4,1).c_str()) == 9) {
                    out_file << setw(INDEX_WIDTH) << 8;
                }
                else {
                    out_file << setw(INDEX_WIDTH) << atoi(conv_codes[i][j].substr(4,1).c_str());
                }
            }
            out_file << endl;
        }
        out_file << endl;
    }
    
    //Close the input files
    in_file.close();
    out_file.close();
    
    for(int i = 0; i < num_rows; i++) {
        delete[] temp[i];
        delete[] cond_codes[i];
        delete[] conv_codes[i];
    }
    delete[] temp;
    delete[] cond_codes;
    delete[] conv_codes;
}
Example #7
0
bool CMT::Mixture::train(
	const MatrixXd& data,
	const Parameters& parameters,
	const Component::Parameters& componentParameters)
{
	if(data.rows() != dim())
		throw Exception("Data has wrong dimensionality.");

	if(parameters.initialize && !initialized())
		initialize(data, parameters, componentParameters);

	ArrayXXd logJoint(numComponents(), data.cols());
	Array<double, Dynamic, 1> postSum;
	Array<double, 1, Dynamic> logLik;
	ArrayXXd post;
	ArrayXXd weights;
	double avgLogLoss = numeric_limits<double>::infinity();
	double avgLogLossNew;

	for(int i = 0; i < parameters.maxIter; ++i) {
		// compute joint probability of data and assignments (E)
		#pragma omp parallel for
		for(int k = 0; k < numComponents(); ++k)
			logJoint.row(k) = mComponents[k]->logLikelihood(data) + log(mPriors[k]);

		// compute normalized posterior (E)
		logLik = logSumExp(logJoint);

		// average negative log-likelihood in bits per component
		avgLogLossNew = -logLik.mean() / log(2.) / dim();

		if(parameters.verbosity > 0)
			cout << setw(6) << i << setw(14) << setprecision(7) << avgLogLossNew << endl;

		// test for convergence
		if(avgLogLoss - avgLogLossNew < parameters.threshold)
			return true;
		avgLogLoss = avgLogLossNew;

		// compute normalized posterior (E)
		post = (logJoint.rowwise() - logLik).exp();
		postSum = post.rowwise().sum();
		weights = post.colwise() / postSum;

		// optimize prior weights (M)
		if(parameters.trainPriors) {
			mPriors = postSum / data.cols() + parameters.regularizePriors;
			mPriors /= mPriors.sum();
		}

		// optimize components (M)
		if(parameters.trainComponents) {
			#pragma omp parallel for
			for(int k = 0; k < numComponents(); ++k)
				mComponents[k]->train(data, weights.row(k), componentParameters);
		} else {
			return true;
		}
	}

	if(parameters.verbosity > 0)
		cout << setw(6) << parameters.maxIter << setw(14) << setprecision(7) << evaluate(data) << endl;

	return false;
}
void MaximalQuadratureIntegral::transformOneForm(const CellJacobianBatch& JTrans,  
  const CellJacobianBatch& JVol,
  const Array<int>& facetIndex,
  const RCP<Array<int> >& cellLIDs,
  const double* const coeff,
  RCP<Array<double> >& A) const
{
  TimeMonitor timer(maxCellQuadrature1Timer());
  Tabs tabs;
  TEUCHOS_TEST_FOR_EXCEPTION(order() != 1, std::logic_error,
    "MaximalQuadratureIntegral::transformOneForm() called for form "
    "of order " << order());
  SUNDANCE_MSG2(integrationVerb(), tabs << "doing one form by quadrature");
  int flops = 0;
  const Array<int>* cellLID = cellLIDs.get();

  int nQuad = quadWeights_.size();

  /* If the derivative order is zero, the only thing to be done 
   * is to multiply by the cell's Jacobian determinant and sum over the
   * quad points */
  if (testDerivOrder() == 0)
  {
    double* aPtr = &((*A)[0]);
    SUNDANCE_MSG5(integrationVerb(), tabs << "input A = ");
    if (integrationVerb() >= 5) writeTable(Out::os(), tabs, *A, 6);
  
    double* coeffPtr = (double*) coeff;
    int offset = 0 ;
    const Array<double>& w = W_;

    if (globalCurve().isCurveValid()) /* ----- ACI logic ---- */
    {
      Array<double> quadWeightsTmp = quadWeights_;
      Array<Point> quadPointsTmp = quadPts_; 
      bool isCutByCurve;

      for (int c=0; c<JVol.numCells(); c++, offset+=nNodes())
      {
        Tabs tab2;
        double detJ = fabs(JVol.detJ()[c]);
        int fc = 0;

        SUNDANCE_MSG4(integrationVerb(), tab2 << "c=" << c << " detJ=" << detJ);
        
        /* call the special integration routine */
        quad_.getAdaptedWeights(cellType(), dim(), (*cellLID)[c] , fc ,
          mesh() , globalCurve() , quadPointsTmp , quadWeightsTmp , isCutByCurve );
        if (isCutByCurve)
        {
          Array<double> wi;
          wi.resize(nQuad * nNodes()); //recalculate the special weights
          for (int ii = 0 ; ii < wi.size() ; ii++ ) wi[ii] = 0.0;
          for (int n = 0 ; n < nNodes() ; n++)
          {
            for (int q=0 ; q < quadWeightsTmp.size() ; q++)
            {
              //Indexing: testNode + nNodesTest()*(testDerivDir + nRefDerivTest()*q)
              wi[n + nNodes()*q] +=
                chop(quadWeightsTmp[q] * W_ACI_F1_[q][0][n]);
            }
          }
          // if it is cut by curve then use this vector
          for (int q=0; q<nQuad; q++, coeffPtr++)
          {
            double f = (*coeffPtr)*detJ;
            for (int n=0; n<nNodes(); n++)
            {
              aPtr[offset+n] += f*wi[n + nNodes()*q];
            }
          }
        } // end isCutByCurve
        else 
        {
          for (int q=0; q<nQuad; q++, coeffPtr++)
          {
            double f = (*coeffPtr)*detJ;
            for (int n=0; n<nNodes(); n++)
            {
              aPtr[offset+n] += f*w[n + nNodes()*q];
            }
          }
        }

        if (integrationVerb() >= 4)
        {
          Out::os() << tab2 << "integration results on cell:" << std::endl;
          Out::os() << tab2 << setw(10) << "n" << setw(12) << "I_n" << std::endl;
          for (int n=0; n<nNodes(); n++) 
          {
            Out::os() << tab2 << setw(10) << n 
                      << setw(12) << setprecision(6) << aPtr[offset+n] << std::endl;
          }
        }
      }
    } 
    else /* -------- No ACI -------- */ 
    {
      for (int c=0; c<JVol.numCells(); c++, offset+=nNodes())
      {
        Tabs tab2;
        double detJ = fabs(JVol.detJ()[c]);
        SUNDANCE_MSG4(integrationVerb(), tab2 << "c=" << c << " detJ=" << detJ);

        for (int q=0; q<nQuad; q++, coeffPtr++)
        {
          Tabs tab3;
          double f = (*coeffPtr)*detJ;
          SUNDANCE_MSG4(integrationVerb(), tab3 << "q=" << q << " coeff=" <<
            *coeffPtr << " coeff*detJ=" << f);
          for (int n=0; n<nNodes(); n++)
          {
            Tabs tab4;
            SUNDANCE_MSG4(integrationVerb(), tab4 << "n=" << n << " w=" <<
              w[n + nNodes()*q]);
            aPtr[offset+n] += f*w[n + nNodes()*q];
          }
        }

        if (integrationVerb() >= 4)
        {
          Out::os() << tab2 << "integration results on cell:" << std::endl;
          Out::os() << tab2 << setw(10) << "n" << setw(12) << "I_n" << std::endl;
          for (int n=0; n<nNodes(); n++) 
          {
            Out::os() << tab2 << setw(10) << n 
                      << setw(12) << setprecision(6) << aPtr[offset+n] << std::endl;
          }
        }
        
      }
    }

    SUNDANCE_MSG5(integrationVerb(), tabs << "output A = ");
    if (integrationVerb() >= 5) writeTable(Out::os(), tabs, *A, 6);
  }
  else
  {
    /* If the derivative order is nonzero, then we have to do a transformation. */
    
    createOneFormTransformationMatrix(JTrans, JVol);
    
    SUNDANCE_MSG4(transformVerb(), 
      Tabs() << "transformation matrix=" << G(alpha()));
    
    double* GPtr = &(G(alpha())[0]);      
    
    transformSummingFirst(JVol.numCells(), facetIndex, cellLIDs, GPtr, coeff, A);
  }
  addFlops(flops);
}
int main() {

  using std::setw;

  int nanosocket = nn_socket(AF_SP, NN_PULL);
  
	// zmq::context_t context(1);
	// zmq::socket_t receiver (context, ZMQ_PULL);
	// receiver.bind("tcp://*:6565");

  nn_bind(nanosocket, "tcp://*:6565");
  
  std::cout << "listening to port: 6565\n";

	while (true) {
	
    // zmq::message_t msg;
  
    //     	receiver.recv(&msg);

            void *buf = NULL;
            int msg_length = nn_recv(nanosocket, &buf, NN_MSG, 0);
            

                //usleep(10000);

    message::Node node;
    node.ParseFromArray(buf, msg_length);

    if (node.type() == message::Node::NODE) {
      std::cout << std::left
          << "Node: "      << setw(8) << node.sid() << " " << setw(8) << node.pid()
          << " " << setw(2) << node.alt() << " " << node.kids() << " " << node.status()
          << "  thread: "  << setw(2) << node.thread_id()
          << "  restart: " << setw(2) << node.restart_id()
          // << "  time: "    << setw(9) << node.time()
          << "  label: "   << setw(14) << node.label();
      if (node.has_domain_size() && node.domain_size() > 0) {
          std::cout << "  domain: "  << setw(6) << std::setprecision(4) << node.domain_size();
      }
      if (node.has_nogood() && node.nogood().length() > 0) {
          std::cout << "  nogood: "  << node.nogood();
      }
      if (node.has_info() && node.info().length() > 0) {
          std::cout << "info:\n"    << node.info() << std::endl;
      }

      std::cout << std::endl;

      if (node.status() == 0) { /// solution!
        std::cout << "-----solution-----\n";
        std::cout << node.solution();
        std::cout << "------------------\n";
      }

      nn_freemsg(buf);

      continue;
    }

    if (node.type() == message::Node::DONE) {
      std::cout << "Done receiving\n";
      continue;
    }

    if (node.type() == message::Node::START) {
      std::cout << "Start recieving, restart: " << node.restart_id() << " name: " << node.label() << " \n";
      continue;
    }
			
	}
	return 0;
}
Example #10
0
// print Time in standard-time format (HH:MM:SS AM or PM)
void Time::printStandard() // note lack of const declaration
{
   cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
      << ":" << setfill( '0' ) << setw( 2 ) << minute
      << ":" << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" );
} // end function printStandard
void VectorFillingAssemblyKernel::insertLocalVectorBatch(
  bool isBCRqc,
  bool useCofacetCells,
  const Array<int>& funcID,  
  const Array<int>& funcBlock, 
  const Array<int>& mvIndices, 
  const Array<double>& localValues) const
{
  TimeMonitor timer(vecInsertTimer());
  Tabs tab0;

  SUNDANCE_MSG1(verb(), tab0 << "inserting local vector batch");
  SUNDANCE_MSG4(verb(), tab0 << "vector values are " << localValues);

  const MapBundle& mb = mapBundle_;
  int nCells = mb.nCells();

  for (int i=0; i<funcID.size(); i++)
  {
    Tabs tab1;
    SUNDANCE_MSG2(verb(), tab1 << "function ID = "<< funcID[i] 
      << " of " << funcID.size());
    SUNDANCE_MSG2(verb(), tab1 << "is BC eqn = " << isBCRqc);
    SUNDANCE_MSG2(verb(), tab1 << "num cells = " << nCells);
    SUNDANCE_MSG2(verb(), tab1 << "using cofacet cells = " << useCofacetCells);
    SUNDANCE_MSG2(verb(), tab1 << "multivector index = " 
      << mvIndices[i]);

    /* First, find the block associated with the current function
     * so that we can find the appropriate DOF information */
    int block = funcBlock[i];

    const RCP<DOFMapBase>& dofMap = mb.dofMap(block);
    int lowestLocalRow = mb.lowestLocalIndex(block);

    int chunk = mb.mapStruct(block, useCofacetCells)->chunkForFuncID(funcID[i]);
    SUNDANCE_MSG2(verb(), tab1 << "chunk = " << chunk);

    int funcIndex = mb.mapStruct(block, useCofacetCells)->indexForFuncID(funcID[i]);
    SUNDANCE_MSG2(verb(), tab1 << "func offset into local DOF map = " 
      << funcIndex);

    const Array<int>& dofs = mb.localDOFs(block, useCofacetCells, chunk);
    SUNDANCE_MSG4(verb(), tab1 << "local dofs = " << dofs);    

    int nFuncs = mb.mapStruct(block, useCofacetCells)->numFuncs(chunk);
    SUNDANCE_MSG2(verb(), tab1 << "num funcs in chunk = " << nFuncs);

    int nNodes = mb.nNodesInChunk(block, useCofacetCells, chunk);
    SUNDANCE_MSG2(verb(), tab1 << "num nodes in chunk = " << nNodes);

    const Array<int>& isBCIndex = *(mb.isBCIndex(block));

    /* At this point, we can start to load the elements */
    int r=0;
    RCP<TSFExtended::LoadableVector<double> > vecBlock 
      = vec_[mvIndices[i]][block];

    FancyOStream& os = Out::os();

    for (int c=0; c<nCells; c++)
    {
      Tabs tab2;
      SUNDANCE_MSG2(verb(), tab2 << "cell = " << c << " of " << nCells);
      for (int n=0; n<nNodes; n++, r++)
      {
        Tabs tab3;
        int rowIndex = dofs[(c*nFuncs + funcIndex)*nNodes + n];
        int localRowIndex = rowIndex - lowestLocalRow;
        if (verb() >= 2) os << tab3 << "n=" << setw(4) << n 
                            << " G=" << setw(8) << rowIndex 
                            << " L=" << setw(8) << localRowIndex;
        if (!(dofMap->isLocalDOF(rowIndex))
          || isBCRqc!=isBCIndex[localRowIndex]) 
        {
          if (verb() >= 2)
          {
            if (!dofMap->isLocalDOF(rowIndex)) 
            {
              os << " --- skipping (is non-local) ---" << std::endl;
            }
            else if (!isBCRqc && isBCIndex[localRowIndex])
            {
              os << " --- skipping (is BC row) ---" << std::endl;
            }
            else
            {
              os << " --- skipping (is non-BC row) ---" << std::endl;
            }
          }
        }
        else
        {
          if (verb() >= 2) os << setw(15) << localValues[r] << std::endl;
          vecBlock->addToElement(rowIndex, localValues[r]);
        }
      }
    }
  }
  SUNDANCE_MSG1(verb(), tab0 << "...done vector insertion");
}
Example #12
0
// print Time in universal-time format (HH:MM:SS)
void Time::printUniversal() const
{
   cout << setfill( '0' ) << setw( 2 ) << hour << ":"
      << setw( 2 ) << minute << ":" << setw( 2 ) << second;
} // end function printUniversal
Example #13
0
void showHelp(void)
{
    using std::stringstream;
    using std::setw;
    using std::left;

    stringstream ss;

    ss << "\nRandom number visualization\n\n";
    ss << "On creation, randomFog generates 200,000 random coordinates in spherical " <<
       "coordinate space (radius, angle rho, angle theta) with curand's XORWOW algorithm. " <<
       "The coordinates are normalized for a uniform distribution through the sphere.\n\n";
    ss << "The X axis is drawn with blue in the negative direction and yellow positive.\n" <<
       "The Y axis is drawn with green in the negative direction and magenta positive.\n" <<
       "The Z axis is drawn with red in the negative direction and cyan positive.\n\n";
    ss << "The following keys can be used to control the output:\n\n";
    ss << left;
    ss << "\t" << setw(10) << "s"       << "Generate a new set of random numbers and display as spherical coordinates (Sphere)\n";
    ss << "\t" << setw(10) << "e"       << "Generate a new set of random numbers and display on a spherical surface (shEll)\n";
    ss << "\t" << setw(10) << "b"       << "Generate a new set of random numbers and display as cartesian coordinates (cuBe/Box)\n";
    ss << "\t" << setw(10) << "p"       << "Generate a new set of random numbers and display on a cartesian plane (Plane)\n\n";
    ss << "\t" << setw(10) << "i,l,j"   << "Rotate the negative Z-axis up, right, down and left respectively\n";
    ss << "\t" << setw(10) << "a"       << "Toggle auto-rotation\n";
    ss << "\t" << setw(10) << "t"       << "Toggle 10x zoom\n";
    ss << "\t" << setw(10) << "z"       << "Toggle axes display\n\n";
    ss << "\t" << setw(10) << "x"       << "Select XORWOW generator (default)\n";
    ss << "\t" << setw(10) << "c"       << "Select Sobol' generator\n";
    ss << "\t" << setw(10) << "v"       << "Select scrambled Sobol' generator\n";
    ss << "\t" << setw(10) << "r"       << "Reset XORWOW (i.e. reset to initial seed) and regenerate\n";
    ss << "\t" << setw(10) << "]"       << "Increment the number of Sobol' dimensions and regenerate\n";
    ss << "\t" << setw(10) << "["       << "Reset the number of Sobol' dimensions to 1 and regenerate\n\n";
    ss << "\t" << setw(10) << "+"       << "Increment the number of displayed points by 8,000 (up to maximum 200,000)\n";
    ss << "\t" << setw(10) << "-"       << "Decrement the number of displayed points by 8,000 (down to minimum 8,000)\n\n";
    ss << "\t" << setw(10) << "q/[ESC]" << "Quit the application.\n\n";
    printf(ss.str().c_str());
}
void SupportGraph<MatrixType>::
describe (Teuchos::FancyOStream &out,
          const Teuchos::EVerbosityLevel verbLevel) const
{
  using std::endl;
  using std::setw;
  using Teuchos::VERB_DEFAULT;
  using Teuchos::VERB_NONE;
  using Teuchos::VERB_LOW;
  using Teuchos::VERB_MEDIUM;
  using Teuchos::VERB_HIGH;
  using Teuchos::VERB_EXTREME;

  const Teuchos::EVerbosityLevel vl 
    = (verbLevel == VERB_DEFAULT) ? VERB_LOW : verbLevel;
  Teuchos::OSTab tab (out);
  //    none: print nothing
  //     low: print O(1) info from node 0
  //  medium:
  //    high:
  // extreme:
  if(vl != VERB_NONE && getComm()->getRank() == 0) {
    out << this->description() << endl;
    out << endl;
    out << "===================================================================="
      "===========" << endl;
    out << "Absolute threshold: " << getAbsoluteThreshold() << endl;
    out << "Relative threshold: " << getRelativeThreshold() << endl;

    out << "Condition number estimate: " << Condest_ << endl;

    if (isComputed()) {
      out << "Number of nonzeros in A: " << A_->getGlobalNumEntries() << endl;
      out << "Number of nonzeros in A_local: " 
          << A_local_->getGlobalNumEntries() << endl;
      out << "Number of edges in support graph: "
          << Support_->getGlobalNumEntries() - Support_->getGlobalNumDiags() 
          << endl;

      const double popFrac =
        static_cast<double> (Support_->getGlobalNumEntries() - 
                             Support_->getGlobalNumDiags()) /
        ((A_->getGlobalNumEntries() - A_->getGlobalNumDiags()) / 2.0);

      out << "Fraction of off diagonals of supportgraph/off diagonals of "
        "original: " << popFrac << endl;
    }
    out << endl;
    out << "Phase           # calls    Total Time (s) " << endl;
    out << "------------    -------    ---------------" << endl;
    out << "initialize()    " << setw(7) << getNumInitialize() << "    "
        << setw(15) << getInitializeTime() << endl;
    out << "compute()       " << setw(7) << getNumCompute()    << "    "
        << setw(15) << getComputeTime()    << endl;
    out << "apply()         " << setw(7) << getNumApply()      << "    "
        << setw(15) << getApplyTime()      << endl;
    out << "===================================================================="
      "===========" << endl;
    out << endl;

    solver_->printTiming(out, verbLevel);
  }
}
Example #15
0
ostream & operator<<(ostream &output, const hist & H1) {
    output << H1.title << endl;
    output << setw(10) << "TOT\t" << setw(15) << "MEAN\t" << setw(15) << "STD\t"
    << setw(15) << "IN\t" << setw(15) << "OVER\t" << setw(15) << "UNDER\t" 
    << setw(15) << "LOW\t" << setw(15) << "HIGH\t" << setw(15) << "BINS\t"<< endl;
    output << setw(10) << H1.Ntot << "\t" << setw(15) << setprecision(8) << H1.mean << "\t"
    << setw(15) << setprecision(8) << H1.std << "\t"
    << setw(15) << H1.Nin << "\t" << setw(15) << H1.Nover << "\t" << setw(15) << H1.Nunder 
    << "\t" << setw(15) << H1.xlow << "\t" << setw(15) << H1.xhigh << "\t" << setw(15) << H1.Nbin << endl;
	if (!H1.collapsed) {
		output << setw(10) << "bin\t" << setw(10) << H1.xlabel << "\t"<< setw(12) << "n\t" << setw(12) << "cum\t";
	} else {
		output << setw(10) << "-\t" << setw(10) << H1.xlabel << "\t" << setw(12) << "n\t" << setw(12) << "cum\t";
        
	}
    
    if (int(H1.binlabels.size()) == H1.Nbin) {
        output << setw(12) << "label" << endl;
    } else {
        output << endl;
    }
    for (int i = 0; i < H1.Nbin; i++) {
        if (H1.n[i] > 0) {
			if (!H1.collapsed) {
				output << setw(10) << i << "\t" << setw(10) << H1.xc[i] << "\t" << setw(12) << setprecision(8)
                << H1.n[i] << "\t" << setw(12) << setprecision(8) << H1.c[i] << "\t";
			} else {
				output << setw(10) << "-\t" << setw(10) << H1.xc[i]<< "\t" << setw(12) << setprecision(8)
				<< H1.n[i] << "\t" << setw(12) << setprecision(8) << H1.c[i] << "\t";
			}
            
            if (int(H1.binlabels.size()) >i) {
                output << setw(12) << H1.binlabels[i] << endl;
            } else {
                output << endl;
            }
        }
    }
    return output;
};
Example #16
0
//Prints the universal time
void Time::printUniversal()
{
  cout << setfill('0') << setw(2) << hour << ":" << setw(2) << minute <<":" <<setw(2) << second;
}
Example #17
0
// We have named the approximation u (u[i]) and the closed-form solution v (v[i])
int main()
{

    int n;
    cout << "Please enter value of n:\n>";
    cin >> n;
    cout << "n = " << n << endl;
    double h = 1.0/(n+1); //step length

    //We define vector a, b and c which make up matrix A:
    double b[ n ];
    for (int i=0 ; i<n ; i++)
    {
        b[i] = 2;
    }

    double ac = -1.0;
    //since the entrances of a and c (apart from the 1st in a and n'th in c) = -1,
    //we do not define a and c as vectors but as numbers with the value -1

    double u[ n ];
    //We define f as h^2*f(i)
    double f[n];
    for (int i=0 ; i<n ; i++)
    {
        f[i] = h*h*func(i,h);
    }

clock_t start , finish;
start = clock();

    // Forward substitution

    double abtemp[n];
    double btemp = b[0];

    for (int i=1 ; i<n ; i++)
    {
        abtemp[i] = ac/btemp;
        btemp = b[i] - ac*abtemp[i];
        f[i] = f[i] - f[i-1]*abtemp[i];
        b[i]=btemp;
    }

    // Back substitution

    u[n-1] = f[n-1]/b[n-1];

    for(int i=n-2 ; i>= 0; i--)
    {
        u[i] = (f[i]-ac*u[i+1])/b[i];
    }

finish = clock();

    //computing the closed-form solution
    double v[n];
    for (int i=0 ; i<n ; i++)
    {
        v[i] = 1-(1-exp(-10))*(1+i)*h-exp(-10*(1+i)*h);
    }

    //Computing the relative error
    double relativererror[n];
    double errortemp;

    for(int i=0 ; i< n; i++)
    {
        errortemp = abs((u[i]-v[i])/v[i]);
        relativererror[i] = log10 (errortemp);
    }

    //Printing time
    cout << "time=" << ((finish - start)/CLOCKS_PER_SEC) << endl;

    //Printing results
    cout << "i" << setw(20) << "x" << setw(20) << "u" << setw(25) << "closed-form solution" << setw(25) << "error" << endl;

    for (int i=0; i<n ; i++)
    {
         cout << i << setw(20) << (i+1)*h << setw(20) << u[i] << setw(20) << v[i] << setw(20) << relativererror[i] << endl;
    }


/*
    //Printing results to file
    ofstream myfile ("Results.txt"); //Creates output file
      if (myfile.is_open())           //checkes whether the output file is open.
                                      //if open, the following things are put in the output file
      {
          myfile << "n = " << n << endl;
          myfile << "i" << setw( 15 ) << "x" << setw( 15 )
                 << "u" << setw( 15 ) << "rel error" <<  endl;
          for ( int j = 0; j < n; j++ )
          {
               myfile << j << setw( 15 ) << (j+1)*h << setw( 15 )
                      << u[j] << setw( 15 ) << relativererror[j] << endl;
          }
      myfile.close();
      }
      else cout << "Unable to open file";
*/
    return 0;
}
Example #18
0
//Prints the standard time
void Time::printStandard()
{
  cout << ( ( hour == 0 || hour == 12) ? 12 : hour % 12) << ":" << setfill('0') <<setw(2) << minute << ":" <<setw(2) << second
   << (hour<12 ? "AM" : "PM");
}
Example #19
0
string EventWriter::formFileName() const {
    return StringBuilder() << mPath << '/' << mPrefix
                           << setw(9) << setfill('0') << mFileCount
                           << ".tds";
}
Example #20
0
bool Test<Real>::operator()()
{
    using std::stringstream;
    using std::endl;
    using std::setw;

    // Get device properties
    struct cudaDeviceProp deviceProperties;
    cudaError_t cudaResult = cudaGetDeviceProperties(&deviceProperties, device);
    if (cudaResult != cudaSuccess){
        std::string msg("Could not get device properties: ");
        msg += cudaGetErrorString(cudaResult);
        throw std::runtime_error(msg);
    }

    // This test prices a set of path-dependent options
    genericOption<Real> option;
    option.spot   = static_cast<Real>(40);
    option.strike = static_cast<Real>(35);
    option.r      = static_cast<Real>(0.03);
    option.sigma  = static_cast<Real>(0.20);
    option.tenor  = static_cast<Real>(1.0/3.0);
    option.dt     = static_cast<Real>(1.0/261);
    option.type   = genericOption<Real>::Call;
    option.valueAsian  = static_cast<Real>(0.0);
    option.golden = static_cast<Real>(5.162534);
    option.barrier = static_cast<Real>(45);
    
    // Evaluate on GPU
    shrLog("Pricing option on GPU (%s)\n\n", deviceProperties.name);
    // pricer is an instantiation of the PricingEngine class
    PricingEngine<Real> pricer(numSims, device, threadBlockSize, seed);
    //shrDeltaT(0);
    pricer(option);
    //elapsedTime = shrDeltaT(0);
    // Run PlainVanilla Option on the CPU
    shrDeltaT(1);
    pricer[option];
    elapsedTimeCPU = shrDeltaT(1);
    // Tolerance to compare result with expected
    // This is just to check that nothing has gone very wrong with the
    // test, the actual accuracy of the result depends on the number of
    // MonteCarlo trials
    const Real tolerance = static_cast<Real>(0.1);
    
    // Display results
    stringstream output;
    output << "Time Spent working on PlainVanilla on the CPU: " << elapsedTimeCPU << endl;
    //output << "Improvement CPU / GPU is: " << (elapsedTimeCPU / elapsedTime) << " times faster" << std::endl;
    output << "Precision:      " << ((typeid(Real) == typeid(double)) ? "double" : "single") << endl;
    output << "Number of simulations: " << numSims << endl;
    output << endl;
    output << "Spot|Strike|  r   |sigma|   tenor  |  Call/Put  | AsianValue |AsiaExpected|PlainVanilla|   PVCPU    | Knock-Out  |  Knock-In  | K-Out+K-In | Lookback |AsianLkBkK-O|" << endl;
    output << "----|------|------|-----|----------|------------|------------|------------|------------|------------|------------|------------|------------|----------|------------|" << std::endl;
    output << setw(3) << option.spot << " | ";
    output << setw(4) << option.strike << " | ";
    output << setw(4) << option.r << " | ";
    output << setw(3) << option.sigma << " | ";
    output << setw(3) << option.tenor << " | ";
    output << setw(10) << (option.type == genericOption<Real>::Call ? "Call" : "Put") << " | ";
    output << setw(10) << option.valueAsian << " | ";
    output << setw(10) << option.golden << " | ";
    output << setw(10) << option.valuePlainVanilla << " | ";
    output << setw(10) << option.valuePlainVanillaCPU << " | ";
    output << setw(10) << option.valueKnockout << " | ";
    output << setw(10) << option.valueKnockin << " | ";
    output << setw(10) << option.valueKnockin + option.valueKnockout << " | ";  
    output << setw(10) << option.valueLookback  << " | ";  
    output << setw(8) << option.valueALK << " | ";
    output << "\nTotal Time Spent on  GPU :" << elapsedTime;
    
    shrLog("%s\n\n", output.str().c_str());

    // Check result
    if (fabs(option.valueAsian - option.golden) > tolerance)
    {
        shrLogEx(LOGBOTH | ERRORMSG, 0, "computed result (%e) does not match expected result (%e).\n", option.valueAsian, option.golden);
        pass = false;
    }
    else
    {
        pass = true;
    }

    // Print results
#ifdef GPU_PROFILING
    shrLogEx(LOGBOTH | MASTER, 0, "MonteCarloSinglegenericOptionP, Performance = %.4f sims/s, Time = %.5f s, NumDevsUsed = %u, Blocksize = %u\n", 
            numSims / elapsedTime, elapsedTime, 1, threadBlockSize);
#endif
        
    return pass;
}
Example #21
0
bool CMT::Mixture::train(
	const MatrixXd& data,
	const MatrixXd& dataValid,
	const Parameters& parameters,
	const Component::Parameters& componentParameters)
{
	if(parameters.initialize && !initialized())
		initialize(data, parameters, componentParameters);

	ArrayXXd logJoint(numComponents(), data.cols());
	Array<double, Dynamic, 1> postSum;
	Array<double, 1, Dynamic> logLik;
	ArrayXXd post;
	ArrayXXd weights;

	// training and validation log-loss for checking convergence
	double avgLogLoss = numeric_limits<double>::infinity();
	double avgLogLossNew;
	double avgLogLossValid = evaluate(dataValid);
	double avgLogLossValidNew = avgLogLossValid;
	int counter = 0;

	// backup model parameters
	VectorXd priors = mPriors;
	vector<Component*> components;

	for(int k = 0; k < numComponents(); ++k)
		components.push_back(mComponents[k]->copy());

	for(int i = 0; i < parameters.maxIter; ++i) {
		// compute joint probability of data and assignments (E)
		#pragma omp parallel for
		for(int k = 0; k < numComponents(); ++k)
			logJoint.row(k) = mComponents[k]->logLikelihood(data) + log(mPriors[k]);

		// compute normalized posterior (E)
		logLik = logSumExp(logJoint);

		// average negative log-likelihood in bits per component
		avgLogLossNew = -logLik.mean() / log(2.) / dim();

		if(parameters.verbosity > 0) {
			if(i % parameters.valIter == 0) {
				// print training and validation error
				cout << setw(6) << i;
				cout << setw(14) << setprecision(7) << avgLogLossNew;
				cout << setw(14) << setprecision(7) << avgLogLossValidNew << endl;
			} else {
				// print training error
				cout << setw(6) << i << setw(14) << setprecision(7) << avgLogLossNew << endl;
			}
		}

		// test for convergence
		if(avgLogLoss - avgLogLossNew < parameters.threshold)
			return true;
		avgLogLoss = avgLogLossNew;

		// compute normalized posterior (E)
		post = (logJoint.rowwise() - logLik).exp();
		postSum = post.rowwise().sum();
		weights = post.colwise() / postSum;

		// optimize prior weights (M)
		if(parameters.trainPriors) {
			mPriors = postSum / data.cols() + parameters.regularizePriors;
			mPriors /= mPriors.sum();
		}

		// optimize components (M)
		if(parameters.trainComponents) {
			#pragma omp parallel for
			for(int k = 0; k < numComponents(); ++k)
				mComponents[k]->train(data, weights.row(k), componentParameters);
		} else {
			return true;
		}

		if((i + 1) % parameters.valIter == 0) {
			// check validation error
			avgLogLossValidNew = evaluate(dataValid);

			if(avgLogLossValidNew < avgLogLossValid) {
				// backup new found model parameters
				priors = mPriors;
				for(int k = 0; k < numComponents(); ++k)
					*components[k] = *mComponents[k];
				
				avgLogLossValid = avgLogLossValidNew;
			} else {
				counter++;

				if(parameters.valLookAhead > 0 && counter >= parameters.valLookAhead) {
					// set parameters to best parameters found during training
					mPriors = priors;

					for(int k = 0; k < numComponents(); ++k) {
						*mComponents[k] = *components[k];
						delete components[k];
					}

					return true;
				}
			}
		}
	}

	if(parameters.verbosity > 0)
		cout << setw(6) << parameters.maxIter << setw(11) << setprecision(5) << evaluate(data) << endl;

	return false;
}
void chi_squared_test(
       double Sd,     // Sample std deviation
       double D,      // True std deviation
       unsigned N,    // Sample size
       double alpha)  // Significance level
{
   //
   // A Chi Squared test applied to a single set of data.
   // We are testing the null hypothesis that the true
   // standard deviation of the sample is D, and that any variation is down
   // to chance.  We can also test the alternative hypothesis
   // that any difference is not down to chance.
   // See http://www.itl.nist.gov/div898/handbook/eda/section3/eda358.htm
   //
   // using namespace boost::math;
   using boost::math::chi_squared;
   using boost::math::quantile;
   using boost::math::complement;
   using boost::math::cdf;

   // Print header:
   cout <<
      "______________________________________________\n"
      "Chi Squared test for sample standard deviation\n"
      "______________________________________________\n\n";
   cout << setprecision(5);
   cout << setw(55) << left << "Number of Observations" << "=  " << N << "\n";
   cout << setw(55) << left << "Sample Standard Deviation" << "=  " << Sd << "\n";
   cout << setw(55) << left << "Expected True Standard Deviation" << "=  " << D << "\n\n";
   //
   // Now we can calculate and output some stats:
   //
   // test-statistic:
   double t_stat = (N - 1) * (Sd / D) * (Sd / D);
   cout << setw(55) << left << "Test Statistic" << "=  " << t_stat << "\n";
   //
   // Finally define our distribution, and get the probability:
   //
   chi_squared dist(N - 1);
   double p = cdf(dist, t_stat);
   cout << setw(55) << left << "CDF of test statistic: " << "=  "
      << setprecision(3) << scientific << p << "\n";
   double ucv = quantile(complement(dist, alpha));
   double ucv2 = quantile(complement(dist, alpha / 2));
   double lcv = quantile(dist, alpha);
   double lcv2 = quantile(dist, alpha / 2);
   cout << setw(55) << left << "Upper Critical Value at alpha: " << "=  "
      << setprecision(3) << scientific << ucv << "\n";
   cout << setw(55) << left << "Upper Critical Value at alpha/2: " << "=  "
      << setprecision(3) << scientific << ucv2 << "\n";
   cout << setw(55) << left << "Lower Critical Value at alpha: " << "=  "
      << setprecision(3) << scientific << lcv << "\n";
   cout << setw(55) << left << "Lower Critical Value at alpha/2: " << "=  "
      << setprecision(3) << scientific << lcv2 << "\n\n";
   //
   // Finally print out results of alternative hypothesis:
   //
   cout << setw(55) << left <<
      "Results for Alternative Hypothesis and alpha" << "=  "
      << setprecision(4) << fixed << alpha << "\n\n";
   cout << "Alternative Hypothesis              Conclusion\n";
   cout << "Standard Deviation != " << setprecision(3) << fixed << D << "            ";
   if((ucv2 < t_stat) || (lcv2 > t_stat))
      cout << "NOT REJECTED\n";
   else
      cout << "REJECTED\n";
   cout << "Standard Deviation  < " << setprecision(3) << fixed << D << "            ";
   if(lcv > t_stat)
      cout << "NOT REJECTED\n";
   else
      cout << "REJECTED\n";
   cout << "Standard Deviation  > " << setprecision(3) << fixed << D << "            ";
   if(ucv < t_stat)
      cout << "NOT REJECTED\n";
   else
      cout << "REJECTED\n";
   cout << endl << endl;
} // void chi_squared_test
Example #23
0
void paramString::print()
{
    cout<<setw(10)  << key << ": ";
    cout<< val <<endl;
}
void chi_squared_sample_sized(
        double diff,      // difference from variance to detect
        double variance)  // true variance
{
   using namespace std;
   // using boost::math;
   using boost::math::chi_squared;
   using boost::math::quantile;
   using boost::math::complement;
   using boost::math::cdf;

   try
   {
   cout <<   // Print out general info:
     "_____________________________________________________________\n"
      "Estimated sample sizes required for various confidence levels\n"
      "_____________________________________________________________\n\n";
   cout << setprecision(5);
   cout << setw(40) << left << "True Variance" << "=  " << variance << "\n";
   cout << setw(40) << left << "Difference to detect" << "=  " << diff << "\n";
   //
   // Define a table of significance levels:
   //
   double alpha[] = { 0.5, 0.33333333333333333333333, 0.25, 0.1, 0.05, 0.01, 0.001, 0.0001, 0.00001 };
   //
   // Print table header:
   //
   cout << "\n\n"
           "_______________________________________________________________\n"
           "Confidence       Estimated          Estimated\n"
           " Value (%)      Sample Size        Sample Size\n"
           "                (lower one-         (upper one-\n"
           "                 sided test)        sided test)\n"
           "_______________________________________________________________\n";
   //
   // Now print out the data for the table rows.
   //
   for(unsigned i = 0; i < sizeof(alpha)/sizeof(alpha[0]); ++i)
   {
      // Confidence value:
      cout << fixed << setprecision(3) << setw(10) << right << 100 * (1-alpha[i]);
      // Calculate df for a lower single-sided test:
      double df = chi_squared::find_degrees_of_freedom(
         -diff, alpha[i], alpha[i], variance);
      // Convert to integral sample size (df is a floating point value in this implementation):
      double size = ceil(df) + 1;
      // Print size:
      cout << fixed << setprecision(0) << setw(16) << right << size;
      // Calculate df for an upper single-sided test:
      df = chi_squared::find_degrees_of_freedom(
         diff, alpha[i], alpha[i], variance);
      // Convert to integral sample size:
      size = ceil(df) + 1;
      // Print size:
      cout << fixed << setprecision(0) << setw(16) << right << size << endl;
   }
   cout << endl;
   }
  catch(const std::exception& e)
  { // Always useful to include try & catch blocks because default policies
    // are to throw exceptions on arguments that cause errors like underflow, overflow.
    // Lacking try & catch blocks, the program will abort without a message below,
    // which may give some helpful clues as to the cause of the exception.
    std::cout <<
      "\n""Message from thrown exception was:\n   " << e.what() << std::endl;
  }
} // chi_squared_sample_sized
Example #25
0
int main()
{
	int board[ 8 ][ 8 ] = { 0 };
	int horizontal[ 8 ];
	int vertical[ 8 ];
	horizontal[ 0 ] = 2;
	horizontal[ 1 ] = 1;
	horizontal[ 2 ] = -1;
	horizontal[ 3 ] = -2;
	horizontal[ 4 ] = -2;
	horizontal[ 5 ] = -1;
	horizontal[ 6 ] = 1;
	horizontal[ 7 ] = 2;

	vertical[ 0 ] = -1;
	vertical[ 1 ] = -2;
	vertical[ 2 ] = -2;
	vertical[ 3 ] = -1;
	vertical[ 4 ] = 1;
	vertical[ 5 ] = 2;
	vertical[ 6 ] = 2;
	vertical[ 7 ] = 1;

	int currentRow = 0, currentColumn = 0;
	board[ currentRow ][ currentColumn ] = 1;

	int access [ 8 ][ 8 ] = 
	{
   	{ 2, 3, 4, 4, 4, 4, 3, 2 },
  	 	{ 3, 4, 6, 6, 6, 6, 4, 3 },
   	{ 4, 6, 8, 8, 8, 8, 6, 4 },
   	{ 4, 6, 8, 8, 8, 8, 6, 4 },
   	{ 4, 6, 8, 8, 8, 8, 6, 4 },
   	{ 4, 6, 8, 8, 8, 8, 6, 4 },
   	{ 3, 4, 6, 6, 6, 6, 4, 3 },
   	{ 2, 3, 4, 4, 4, 4, 3, 2 }
   }; 
	int x;
	int count = 2;
	for ( x = 2; x <= 64; x++ )
	{
		int moveNumber = 0;
		while ( moveNumber < 8 )
		{
			int ver = currentRow;
			int hor = currentColumn;
			ver += vertical[ moveNumber ];
			hor += horizontal[ moveNumber ];
			if ( ( ver < 0 ) || ( ver >= 8 ) )
				moveNumber++;
			else if ( ( hor < 0 ) || ( hor >= 8 ) )
				moveNumber++;
			else if ( board[ ver ][ hor ] != 0 )
				moveNumber++;
			else
			{
				board[ ver ][ hor ] = count;
				count++;
				currentRow = ver;
				currentColumn = hor;
				moveNumber = 8;
				for ( int row = 0; row < 8; row++ )
				{
					for ( int column = 0; column < 8; column++ )
						cout << setw( 3 ) << board[ row ][ column ] ;
					cout << endl;
				}
				cout << endl;
			}
		}
	}
			
			




	for ( int row = 0; row < 8; row++ )
	{
		for ( int column = 0; column < 8; column++ )
			cout << setw( 3 ) << board[ row ][ column ];
		cout << endl;
	}
	cout << count << endl;
	return 0;
}
Example #26
0
// display single record from file
void outputLine( int account, const string name, double balance )
{
   cout << left << setw( 10 ) << account << setw( 13 ) << name
      << setw( 7 ) << setprecision( 2 ) << right << balance << endl;
} // end function outputLine
int main()
{
  cout << "Negative_binomial distribution - simple example 2" << endl;
  // Construct a negative binomial distribution with:
  // 8 successes (r), success fraction (p) 0.25 = 25% or 1 in 4 successes.
  negative_binomial mynbdist(8, 0.25); // Shorter method using typedef.

  // Display (to check) properties of the distribution just constructed.
  cout << "mean(mynbdist) = " << mean(mynbdist) << endl; // 24
  cout << "mynbdist.successes() = " << mynbdist.successes()  << endl; // 8
  // r th successful trial, after k failures, is r + k th trial.
  cout << "mynbdist.success_fraction() = " << mynbdist.success_fraction() << endl; 
  // success_fraction = failures/successes or k/r = 0.25 or 25%. 
  cout << "mynbdist.percent success  = " << mynbdist.success_fraction() * 100 << "%"  << endl;
  // Show as % too.
  // Show some cumulative distribution function values for failures k = 2 and 8
  cout << "cdf(mynbdist, 2.) = " << cdf(mynbdist, 2.) << endl; // 0.000415802001953125
  cout << "cdf(mynbdist, 8.) = " << cdf(mynbdist, 8.) << endl; // 0.027129956288263202
  cout << "cdf(complement(mynbdist, 8.)) = " << cdf(complement(mynbdist, 8.)) << endl; // 0.9728700437117368
  // Check that cdf plus its complement is unity.
  cout << "cdf + complement = " << cdf(mynbdist, 8.) + cdf(complement(mynbdist, 8.))  << endl; // 1
  // Note: No complement for pdf! 

  // Compare cdf with sum of pdfs.
  double sum = 0.; // Calculate the sum of all the pdfs,
  int k = 20; // for 20 failures
  for(signed i = 0; i <= k; ++i)
  {
    sum += pdf(mynbdist, double(i));
  }
  // Compare with the cdf
  double cdf8 = cdf(mynbdist, static_cast<double>(k));
  double diff = sum - cdf8; // Expect the diference to be very small.
  cout << setprecision(17) << "Sum pdfs = " << sum << ' ' // sum = 0.40025683281803698
  << ", cdf = " << cdf(mynbdist, static_cast<double>(k)) //  cdf = 0.40025683281803687
  << ", difference = "  // difference = 0.50000000000000000
  << setprecision(1) << diff/ (std::numeric_limits<double>::epsilon() * sum)
  << " in epsilon units." << endl;

  // Note: Use boost::math::tools::epsilon rather than std::numeric_limits
  //  to cover RealTypes that do not specialize numeric_limits.

//[neg_binomial_example2

  // Print a table of values that can be used to plot
  // using Excel, or some other superior graphical display tool.

  cout.precision(17); // Use max_digits10 precision, the maximum available for a reference table.
  cout << showpoint << endl; // include trailing zeros.
  // This is a maximum possible precision for the type (here double) to suit a reference table.
  int maxk = static_cast<int>(2. * mynbdist.successes() /  mynbdist.success_fraction());
  // This maxk shows most of the range of interest, probability about 0.0001 to 0.999.
  cout << "\n"" k            pdf                      cdf""\n" << endl;
  for (int k = 0; k < maxk; k++)
  {
    cout << right << setprecision(17) << showpoint
      << right << setw(3) << k  << ", "
      << left << setw(25) << pdf(mynbdist, static_cast<double>(k))
      << left << setw(25) << cdf(mynbdist, static_cast<double>(k))
      << endl;
  }
  cout << endl;
//] [/ neg_binomial_example2]
  return 0;
} // int main()
Example #28
0
int main() {

    // Current time
    time_t now = time(0);
    cout << endl << "char* ctime():\t" << ctime(&now);
    
    tm* time_struct = gmtime(&now);
    cout << endl << "gmtime";
    cout << endl << setw(10) << "time_struct->tm_sec" << setw(10) << time_struct->tm_sec;
    cout << endl << setw(10) << "time_struct->tm_min" << setw(10) << time_struct->tm_min;
    cout << endl << setw(10) << "time_struct->tm_hour" << setw(10) << time_struct->tm_hour;
    cout << endl << setw(10) << "time_struct->tm_mday" << setw(10) << time_struct->tm_mday;
    cout << endl << setw(10) << "time_struct->tm_mon" << setw(10) << time_struct->tm_mon;
    cout << endl << setw(10) << "time_struct->tm_year" << setw(10) << time_struct->tm_year;
    cout << endl << setw(10) << "time_struct->tm_wday" << setw(10) << time_struct->tm_wday;
    cout << endl << setw(10) << "time_struct->tm_year" << setw(10) << time_struct->tm_year;
    cout << endl << setw(10) << "time_struct->tm_wday" << setw(10) << time_struct->tm_wday;
    cout << endl << setw(10) << "time_struct->tm_yday" << setw(10) << time_struct->tm_yday;
    cout << endl << setw(10) << "time_struct->tm_isdst" << setw(10) << time_struct->tm_isdst;
   
    cout << endl; 
    return 0;   
}
Example #29
0
int main()
{

	// Declare and initialize variables

   int UniqueNos[20],        //  used to store up to 20 unique #s
	   NextNumber,           //  used to store the next number read in.
	   ArrayPosition = -1;   //  points to current position in array UniqueNos where
                             //       last unique number was stored

   int LoopCounter; // used as loop counter below

   bool Found;  // Boolean flag used to signal if number unique or not

   // The following loop is used to input the 20 numbers

   for ( int I = 1; I <= 20; ++I )
   {
		Found = false;  // Start loop each time with bool flag signalling we did not find 
		                //    the next number input in the UniquNos array.

		cout << "\nEnter # " << I << " : ";
		cin >> NextNumber;
		while (NextNumber < 10 || NextNumber > 100)
		{
			cout << "The number enetered is not in the valid range of 10 to 100" << endl;
			cout << "\nEnter # " << I << " : ";
			cin >> NextNumber;
		}

		/* The following while loop checks to see if NextNumber is unique by checking
		   if it is already in the UniqueNos array.                                 */

		LoopCounter = 0;
		while (LoopCounter <= ArrayPosition) 
		{
			if (UniqueNos[LoopCounter] == NextNumber)
			{
				Found = true;  // Signal we found that number is already in array UniqueNos
				break;     // We can exit loop, since we found it in the array.
			}
			++LoopCounter;
		}

		if (!Found) // If NextNumber was NOT found in the UniqueNos array
		{
			UniqueNos[++ArrayPosition] = NextNumber;  // point to next location in array 
			                                          //   and save new value in array
			cout << "The number: "  << NextNumber << " is unique" << endl;
		}
   }

   // Output Results
   cout << "\n\nThe unique numbers are:\n\n";

   for (int lcounter = 0; lcounter <= ArrayPosition; ++lcounter){
	   cout << setw(6) << UniqueNos[lcounter];
	   if (lcounter % 5 == 4){
		   cout << '\n';
	   }
   }

   // Wait for signal to go home
   cout << '\n' << endl;
   system("pause");

   // Time to go home

   return 0;
}
void MoochoTrackerStatsStd::output_final( const Algorithm& p_algo
  , EAlgoReturn algo_return ) const
{
  using Teuchos::dyn_cast;

  const NLPAlgo           &algo    = rsqp_algo(p_algo);
  const NLPAlgoState          &s       = algo.rsqp_state();
  const NLPObjGrad     &nlp     = dyn_cast<const NLPObjGrad>(algo.nlp()); 
  const NLPFirstOrder  *nlp_foi = dynamic_cast<const NLPFirstOrder*>(&nlp); 

  const size_type
    m = nlp.m();

  std::ostream& o = this->o();

  // Stop the timer
  timer_.stop();

  // Formating info
  const int
    p      = 18,
    stat_w = 15,
    val_w  = p + 10;

  // Get a Quasi-Newton statistics.
  const QuasiNewtonStats	*quasi_newt_stats =
    ( quasi_newton_stats_.exists_in(s) && quasi_newton_stats_(s).updated_k(0)
      ? &quasi_newton_stats_(s).get_k(0)
      : NULL );
  if( quasi_newt_stats ) {
    QuasiNewtonStats::EUpdate updated = quasi_newt_stats->updated();
    if( updated == QuasiNewtonStats::DAMPENED_UPDATED || updated == QuasiNewtonStats::UPDATED )
      num_QN_updates_++;
  }

  // status
  o << left << setw(stat_w) << "status" << "= "
    << right << setw(val_w);
  switch( algo_return ) {
    case IterationPack::TERMINATE_TRUE:
      o << "solved";
      break;
    case IterationPack::TERMINATE_FALSE:
      o << "except";
      break;
    case IterationPack::MAX_ITER_EXCEEDED:
      o << "max_iter";
      break;
    case IterationPack::MAX_RUN_TIME_EXCEEDED:
      o << "max_run_time";
      break;
    case IterationPack::INTERRUPTED_TERMINATE_TRUE:
      o << "interrupted_solved";
      break;
    case IterationPack::INTERRUPTED_TERMINATE_FALSE:
      o << "interrupted_not_solved";
      break;
    default:
      TEUCHOS_TEST_FOR_EXCEPT(true);
  }
  o << "; # solved, except, max_iter, max_run_time\n";
  // niter
  o << left << setw(stat_w) << "niter" << "= "
    << right << setw(val_w) << s.k()
    << "; # Number of rSQP iterations (plus 1?)\n";
  // nfunc
  o << left << setw(stat_w) << "nfunc" << "= "
    << right << setw(val_w) << my_max(nlp.num_f_evals(),(m? nlp.num_c_evals():0) )
    << "; # max( number f(x) evals, number c(x) evals )\n";
  // ngrad
  o << left << setw(stat_w) << "ngrad" << "= "
    << right << setw(val_w) << my_max(nlp.num_Gf_evals(),(m?(nlp_foi?nlp_foi->num_Gc_evals():s.k()+1):0))
    << "; # max( number Gf(x) evals, number Gc(x) evals )\n";
  // CPU
  o << left << setw(stat_w) << "CPU" << "= "
    << right << setw(val_w) << timer_.read()
    << "; # Number of CPU seconds total\n";
  // obj_func
  o << left << setw(stat_w) << "obj_func" << "= "
    << right << setw(val_w);
  if(s.f().updated_k(0))
    o << s.f().get_k(0);
  else
    o << "-";
  o << "; # Objective function value f(x) at final point\n";
  // feas_kkt_err
  o << left << setw(stat_w) << "feas_kkt_err" << "= "
    << right << setw(val_w);
  if(s.feas_kkt_err().updated_k(0))
    o << s.feas_kkt_err().get_k(0);
  else if(s.c().updated_k(0))
    o << s.c().get_k(0).norm_inf();
  else
    o << "-";
  o << "; # Feasibility error at final point (scaled ||c(x)||inf, feas_err_k)\n";
  // opt_kkt_err
  o << left << setw(stat_w) << "opt_kkt_err" << "= "
    << right << setw(val_w);
  if(s.opt_kkt_err().updated_k(0))
    o << s.opt_kkt_err().get_k(0);
  else if(s.rGL().updated_k(0))
    o << s.rGL().get_k(0).norm_inf();
  else if(s.rGL().updated_k(-1))
    o << s.rGL().get_k(-1).norm_inf();
  else
    o << "-";
  o << "; # Optimality error at final point (scaled ||rGL||inf, opt_err_k)\n";
  // nact
  o << left << setw(stat_w) << "nact" << "= "
    << right << setw(val_w);
  if(s.nu().updated_k(0))
    o << s.nu().get_k(0).nz();
  else if(s.nu().updated_k(-1))
    o << s.nu().get_k(-1).nz();
  else
    o << "-";
  o << "; # Number of total active constraints at the final point\n";
  // nbasis_change
  const IterQuantityAccess<index_type> &num_basis = s.num_basis();
  const int lu_k = num_basis.last_updated();
  o << left << setw(stat_w) << "nbasis_change" << "= "
    << right << setw(val_w) << ( lu_k != IterQuantity::NONE_UPDATED
                   ? num_basis.get_k(lu_k)
                   : 0 ) 
    << "; # Number of basis changes\n";
  // nquasi_newton
  o << left << setw(stat_w) << "nquasi_newton" << "= "
    << right << setw(val_w) << num_QN_updates_
    << "; # Number of quasi-newton updates\n";

}