Example #1
1
 void Response::get_header( const string& name, double& value, const double default_value ) const
 {
     try
     {
         value = stod( get_header( name ) );
     }
     catch ( const invalid_argument& )
     {
         value = default_value;
     }
 }
int DatabaseInterface::getFlowData(string experimentName, int flowID,
		string label, list<double>& value_list)
{
	int rc = 0; 							//control output flag
	int experimentID;
	double value; 							//rows values
	char strFlowId[INT_BUFFER_SIZE]; 		// FlowID string
	char strExperimentId[INT_BUFFER_SIZE]; 	// FlowID string
	char* sql = NULL; 						//SQL char[] query
	string string_sql; 						//SQL string query
	sqlite3_stmt *res; 						//database handle

	this->getTraceData(experimentName, "experimentName", &experimentID);
	//convert flowID and experimentID to string
	snprintf(strFlowId, sizeof(strFlowId), "%d", flowID);
	snprintf(strExperimentId, sizeof(strExperimentId), "%d", experimentID);

	//create SQL query
	string_sql = "select " + label + " from " + capture_table
			+ " where  FlowID=\"" + strFlowId + "\" and experimentID=\""
			+ strExperimentId + "\";";
	sql = new char[string_sql.length() + 1];
	strcpy(sql, string_sql.c_str());

	//create SQL statement definition
	rc = sqlite3_prepare_v2(db, sql, -1, &res, 0);
	if (rc != SQLITE_OK)
	{
		errno = ENOENT;
		fprintf(stderr, "Failed to fetch data: %s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		databaseInterface_error = 2;
		return (1);
	}

	//capture values until the table finishes
	while (true)
	{
		rc = sqlite3_step(res);
		if (rc != SQLITE_ROW)
		{
			break;
		}
		value = stod((const char*) sqlite3_column_text(res, 0), NULL);
		value_list.push_back(value);

	}

	//free allocated memory
	delete[] sql;
	sqlite3_finalize(res);
	return (0);
}
std::vector< std::vector< std::vector<double> > > NeuralNetwork::readDataFromFile(std::string fpath){
    std::vector< std::vector<double> > inputMatrix;
    std::vector< std::vector<double> > outputMatrix;
    std::ifstream trainingFile(fpath);
    std::string line;
    while(getline(trainingFile, line)){
        //structure is x_1,...,x_n y_1,y_2,...,y_m (comma and space separated)
        int spacePosition = (int)line.find(" ");
        int lastCommaPosition = -1;
        int nextCommaPosition = (int)line.find(",",lastCommaPosition+1);

        //get inputs
        std::vector<double> input;
        while(nextCommaPosition != std::string::npos && nextCommaPosition < spacePosition){
            input.push_back(stod(line.substr(lastCommaPosition+1,nextCommaPosition)));
            lastCommaPosition = nextCommaPosition;
            nextCommaPosition = (int)line.find(",",nextCommaPosition+1);
        }
        input.push_back(stod(line.substr(lastCommaPosition+1,spacePosition)));

        //get outputs
        std::vector<double> output;
        lastCommaPosition = spacePosition;
        nextCommaPosition = (int)line.find(",",lastCommaPosition+1);
        while(nextCommaPosition != std::string::npos && nextCommaPosition < line.length()){
            output.push_back(stod(line.substr(lastCommaPosition+1,nextCommaPosition)));
            lastCommaPosition = nextCommaPosition;
            nextCommaPosition = (int)line.find(",",lastCommaPosition+1);
        }
        output.push_back(stod(line.substr(lastCommaPosition+1)));

        //add these training data points to the training matrices
        inputMatrix.push_back(input);
        outputMatrix.push_back(output);
    }
    trainingFile.close();
    std::vector< std::vector< std::vector<double> > > dataFromFile;
    dataFromFile.push_back(inputMatrix);
    dataFromFile.push_back(outputMatrix);
    return dataFromFile;
}
Example #4
0
void CreatePoint(const std::vector<std::string>& command, std::vector<std::shared_ptr<CShape>>& figures, std::vector<std::shared_ptr<sf::Shape>>& drawableFigures)
{
	if (command.size() != 4)
	{
		throw std::exception("\tError: Invalid parameters count to create point");
	}
	try
	{
		double x = stod(command[1]);
		double y = stod(command[2]);
		figures.push_back(std::make_shared<CPoint>(x, y, command[3]));
		std::shared_ptr<sf::Shape> point = std::make_shared<sf::CircleShape>(2.f);
		point->setPosition(float(x), float(y));
		point->setFillColor(HexToRgb(command[3]));
		drawableFigures.push_back(point);
	}
	catch (const std::exception&)
	{
		throw std::exception("\tError: Invalid parameters to create point");
	}
}
Example #5
0
void SimplePhraseTable::
read(string filename, bool reverse){
    ifstream is(filename.c_str());
    for(string line; getline(is,line);){
        trim(line);
        if(line=="")continue;
        vector<string> content;
        split_regex(content,line,regex(" => | \\|\\|\\| "));
        if(content.size()<3)continue;
        vector<string> features;
        split_regex(features,content[2],regex(" "));
        if(features.size()==1){
            double fraccount=(double)stod(features[0]);
            (*this)[content[0]][content[1]]=
            SimplePhraseInfo(fraccount,fraccount);
        }
        else if(features.size()==2){
            //double count=(double)stod(features[1]);
            double fraccount=(double)stod(features[0]);
            (*this)[content[0]][content[1]]=
            SimplePhraseInfo(fraccount,fraccount);
        }
        else if(features.size()>=4){
            if(reverse){
                (*this)[content[1]][content[0]]=
                SimplePhraseInfo(stod(features[3]),stod(features[3]));
            }
            else{
                (*this)[content[0]][content[1]]=
                SimplePhraseInfo(stod(features[1]),stod(features[1]));
            }
        }
    }
    is.close();
}
Example #6
0
void CreateTriangle(const std::vector<std::string>& command, std::vector<std::shared_ptr<CShape>>& figures, std::vector<std::shared_ptr<sf::Shape>>& drawableFigures)
{
	if (command.size() != 9)
	{
		throw std::exception("\tError: Invalid parameters count to create triangle");
	}
	try
	{
		double x1 = stod(command[1]);
		double y1 = stod(command[2]);
		double x2 = stod(command[3]);
		double y2 = stod(command[4]);
		double x3 = stod(command[5]);
		double y3 = stod(command[6]);
		figures.push_back(std::make_shared<CTriangle>(x1, y1, x2, y2, x3,
			y3, command[7], command[8]));
		std::shared_ptr<sf::ConvexShape> triangle = std::make_shared<sf::ConvexShape>(3);
		triangle->setPoint(0, (sf::Vector2f(float(x1), float(y1))));
		triangle->setPoint(1, (sf::Vector2f(float(x2), float(y2))));
		triangle->setPoint(2, (sf::Vector2f(float(x3), float(y3))));
		triangle->setOutlineThickness(3);
		triangle->setOutlineColor(HexToRgb(command[7]));
		triangle->setFillColor(HexToRgb(command[8]));
		drawableFigures.push_back(triangle);
	}
	catch (const std::exception&)
	{
		throw std::exception("\tError: Invalid parameters to create triangle");
	}
}
Example #7
0
Matrix DataCollector::readFromText(string filename, vector<string> &assetNames)
{
	//filename = "Stocks.txt";

	unsigned int numAssets, numDates;

	countStuff(filename, numAssets, numDates);

	//cout << numAssets << "\t" << numDates << endl;

	Matrix priceMatrix(numDates, numAssets);

	ifstream infile; //input file stream object
	infile.open(filename);

	if (!infile) {
		cerr << "Bad input! Can't open " << filename << endl;
		exit(1);
	}

	unsigned int i = 0;
	unsigned int j = 0;

	string line;
	string token;
	double price;
	getline(infile, line, '\n');
	stringstream ss(line);
	while (getline(ss, token, ' '))
	{
		//cout << token << "\t";
		assetNames.push_back(token);
	}
	//cout << endl;
	while (!infile.eof())
	{
		getline(infile, line, '\n');
		stringstream ss(line);
		j = 0;
		while (getline(ss, token, ','))
		{
			price = stod(token);
			priceMatrix(i, j) = price;
			j++;
			//cout << price << "\t";
		}
		//cout << endl;
		i++;
	}
	//cout << priceMatrix << endl;
	return priceMatrix;
}
Example #8
0
Aris::Core::MSG parseShovel(const std::string &cmd, const map<std::string, std::string> &params)
{
    SHOVEL_PARAM  param;

    param.radius=2;
    param.periodNum = 7;
    for(int i = 0; i < param.periodNum; i++)
    {
        param.periodCount[i]=3000;
    }

    for(auto &i:params)
    {
        if(i.first=="height")
        {
            param.height=stod(i.second);
        }
        else if(i.first=="length")
        {
            param.length=stod(i.second);
        }
        else if(i.first=="degree")
        {
            param.rad=stod(i.second)/180*PI;
        }
        else
        {
            std::cout<<"parse failed"<<std::endl;
            return MSG{};
        }
    }

    Aris::Core::MSG msg;
    msg.CopyStruct(param);

    std::cout<<"finished parse"<<std::endl;

    return msg;
}
Example #9
0
/********** Private lf_snapshot_file methods *************/
inline bool lf_snapshot_file::read_frame_meta(struct Frame &frame) {
  frame.meta_data.clear();
  std::string line;
  while(getline(f, line)) {
    if (!line.empty()) {
      break;
    }
  };
  if (line.empty()) {
    return false;
  }
  auto frame_meta = split(line, " ");
  if (frame_meta[0] != "#") {
    throw std::runtime_error(" Ill-formed frame header.");
  }
  frame.meta_data["curvilinear strain"] = stod(frame_meta[1]);
  frame.meta_data["shear disp x"] = stod(frame_meta[2]);
  frame.meta_data["rate"] = stod(frame_meta[3]);
  frame.meta_data["target stress"] = stod(frame_meta[4]);
  frame.meta_data["time"] = stod(frame_meta[5]);
  return true;
}
void Handle_Pressure_Vessel(Initial_Data& InitialParameters, vector<string> Input)
{

	PressureVessel Pressure_Vessel;

	int i;
	for(i=0;i<(int)Input.size();i++)
	{
		vector< string > line_content;

		if(Test_If_Word_Found(Input[i],"Liquid Volume"))
		{
			line_content = Tokenise_String_To_String(Input[i]," \t");

			// it is mL -> make into m^3
			Pressure_Vessel.Liquid_Sample_Volume = stod(line_content[3],NULL)*1e-6;
			cout << "Sample Size: " << InitialParameters.PetroOxy.SampleSize << "\n";
			line_content.clear();
		}

		if(Test_If_Word_Found(Input[i],"Gas Volume"))
		{
			line_content = Tokenise_String_To_String(Input[i]," \t");

			// it is mL -> make into m^3
			Pressure_Vessel.Gas_Sample_Volume = stod(line_content[3],NULL)*1e-6;
			cout << "Sample Size: " << InitialParameters.PetroOxy.SampleSize << "\n";
			line_content.clear();
		}
	}

	// Need to think about useful additional information
	// Maybe Gas Phase pressure so that we can calculate a concentration in case we do not know it?
	// how do I handle a "gap" between expected and actual pressure - mainly from the PetroOxy calculation where I had
	// an initial pressure and a max pressure which wasn't fully covered by the oxygen component...
	// assume fuel filled the rest? ...

	InitialParameters.Pressure_Vessel = Pressure_Vessel;
}
Example #11
0
void plus(int n)
{
	int len;
	char a[100][100] = {0,};
	a[n][100] = fir[n][100];
	a[n+1][100] = fir[n+1][100];
	if( strlen(a[n]) > strlen(a[n+1]) )
		len = strlen(a[n]);
	else len = strlen(a[n+1]);

	reverse(a[n], strlen(a[n]));
	reverse(a[n+1], strlen(a[n+1]));

	char an[100][100];
	int i, up = 0;
	for(i=0; i<len; i++){
		an[n][i] = (stod(a[n][i]) + stod(a[n+1][i])+up)%10+'0';
		if((stod(a[n][i]) + stod(a[n+1][i]) + up) > 9)
			up=1;
		else up=0;
	}
}
int main(int argc, char *argv[]) {
    const double def_max_time = {1000.0};
    const size_t def_nr_particles {5};
    const size_t def_grid_size {10};
    double max_time {def_max_time};
    size_t nr_particles {def_nr_particles};
    size_t grid_size {def_grid_size};
    bool is_verbose = false;
    char opt {'\0'};
    while ((opt = getopt(argc, argv, "t:p:g:vh")) != -1) {
        try {
            switch (opt) {
                case 't':
                    max_time = stod(optarg);
                    break;
                case 'p':
                    nr_particles = stoi(optarg);
                    break;
                case 'g':
                    grid_size = stoi(optarg);
                    break;
                case 'h':
                    print_help(std::cout);
                    return 0;
                case 'v':
                    is_verbose = true;
                    break;
                default:
                    print_help(std::cerr);
                    return 1;
            }
        } catch (invalid_argument& e) {
            std::cerr << "# error: invalid argument for option -"
                      << opt << endl;
            print_help(std::cerr);
            return 1;
        }
    }
    double time {0.0};
    System system(nr_particles, grid_size);
    system.print_grid();
    while (time < max_time) {
        if (is_verbose)
            cout << "time = " << time << endl;
        if (is_verbose)
            system.print_queue();
        time += system.update();
    }
    system.print_grid();
    return 0;
}
Example #13
0
void ofApp::populate_tw()
{
	tw_users.clear();
	for (int i = 0; i < num_tw_draw ; i++)
	{
		Twitter *t = new Twitter();
		t->set_twitter(twitter_csv.data[rand2[i]][0]);
		t->set_user_name(twitter_csv.data[rand2[i]][1]);
		t->set_length((t->get_twitter()).length());
		t->set_rad_limit(t->get_length() / 2.5);
		t->set_rad(1.0 / 100);
		t->set_rad_grow(true);
		t->set_x(stod(twitter_csv.data[rand2[i]][3]));
		t->set_y(stod(twitter_csv.data[rand2[i]][2]));
		t->w_div_t = w_div;
		t->h_div_t = h_div;
		t->w_mult_t = w_mult;
		t->h_mult_t = h_mult;
		t->w_glob_t = w_glob_add;
		t->h_glob_t = h_glob_add;
		tw_users.push_back(*t);
	}
}
Example #14
0
int DataPreprocessor::addIndicators(string fileName)
{
	ifstream inputStream;
	inputStream.open(fileName);

	ofstream outputStream;
	outputStream.open(fileName + string("_preprocessed.csv"));

	if (inputStream.is_open() && outputStream.is_open())
	{
		int closePriceIndex = 4;
		int volumeIndex = 5;
		int storedPricesCount = 200;
		closePrices = list<double>();

		string token;
		string line;

		istringstream ss;

		int i;
		getline(inputStream, line);
		addHeaders(line, indicators, outputStream);

		while (getline(inputStream, line))
		{
			ss = istringstream(line);
			i = 0;
			outputStream << line;
			while (getline(ss, token, ','))
			{
				if (i == closePriceIndex)
				{
					if (closePrices.size() == storedPricesCount)
					{
						closePrices.pop_front();
					}
					closePrices.push_back(stod(token));
				}
				i++;
			}
			addIndicatorValues(outputStream);
		}
		return 0;
	}
	else
	{
		return -1;
	}
}
Example #15
0
exparser::return_type exparser::parse_constant(const std::string& s) {
    try {
        std::size_t pos = 0;
        auto c = stod(s, &pos);
        if (pos == s.length())
            return return_type(make_constant(c));
        else
            return return_false;
    } catch (std::invalid_argument e) {
        return return_false;
    } catch (std::out_of_range e) {
        throw e;
    }
}
/******************************************************************************
Function:	 Split Strings
Author: 	 Stephanie Athow
Description: 
	Parses a csv file, it will break up a comma sperated line
Parameters:
	in: line		line to break up
	in: delim		character to delineate a break
Returns:
	data_values		a vector of doubles that contains the year, burned acres
					and 12 months of PDSI values
******************************************************************************/
vector<double> split_string( string line, char delim )
{
	vector<double> data_values;				// holds data values to be returned
	stringstream line_stream( line );		// turn into stream to use getline
	string tok;								// holds return from getline
	double val;								// holds double val converted from getline

	while( getline( line_stream, tok, delim ) )
	{
		val = stod( tok );
		data_values.push_back( val );
	}

	return data_values;
}
Example #17
0
void ScaleFilter::ParseArgument(CommandLineArgModel* arg)
{
	ScaleFilterModel* model = new ScaleFilterModel();
	model->Scale = -1;

	for (unsigned int index = 0; index < arg->Parameters->size(); index++)
	{
		if (model->Scale < 0)
		{
			model->Scale = stod(trim(arg->Parameters->at(index)));
		}
	} 

	arg->ParsedModel = model;
}
Example #18
0
void ofApp::populate_fb()
{
	fb_users.clear();
	for(int i = 0; i < num_fb_draw ; i++)
	{
		Facebook *f = new Facebook();
		f->set_name(facebook_csv.data[rand[i]][0]);
		f->set_category(facebook_csv.data[rand[i]][1]);
		f->set_checkins(stod(facebook_csv.data[rand[i]][2]));
		f->set_rad_limit(-1.0*stod(facebook_csv.data[rand[i]][2])/10000);
		f->set_rad(1.0/100);
		f->set_rad_grow(true);
		f->set_x(stod(facebook_csv.data[rand[i]][4]));
		f->set_y(stod(facebook_csv.data[rand[i]][3]));
		f->w_div_f = w_div;
		f->h_div_f = h_div;
		f->w_mult_f = w_mult;
		f->h_mult_f = h_mult;
		f->w_glob_f = w_glob_add;
		f->h_glob_f = h_glob_add;
		fb_users.push_back(*f);
		
	}
}
Example #19
0
void CreateLine(const std::vector<std::string>& command, std::vector<std::shared_ptr<CShape>>& figures, std::vector<std::shared_ptr<sf::Shape>>& drawableFigures)
{
	if (command.size() != 6)
	{
		throw std::exception("\tError: Invalid parameters count to create line");
	}
	try
	{
		double x1 = stod(command[1]);
		double y1 = stod(command[2]);
		double x2 = stod(command[3]);
		double y2 = stod(command[4]);
		figures.push_back(std::make_shared<CLineSegment>(x1, y1, x2, y2, command[5]));
		std::shared_ptr<sf::Shape> line = std::make_shared<sf::RectangleShape>(sf::Vector2f(float(figures.back()->GetPerimeter()), 3.f));
		x2 < x1 ? line->setPosition(float(x2), float(y2)) : line->setPosition(float(x1), float(y1));
		line->setRotation(float(std::atan((y2 - y1) / (x2 - x1)) * 180 / C_PI));
		line->setFillColor(HexToRgb(command[5]));
		drawableFigures.push_back(line);
	}
	catch (const std::exception&)
	{
		throw std::exception("\tError: Invalid parameters to create line");
	}
}
void solveWithPlaku(const VREPInterface *interface, const InstanceFileMap *args, const VREPInterface::State &start, const VREPInterface::State &goal) {
	dfpair(stdout, "planner", "%s", "Plaku IROS 2014");

	typedef PRMLite<VREPInterface, VREPInterface> PRMLite;
	typedef PlakuTreeInterface<VREPInterface, VREPInterface, PRMLite> PlakuTreeInterface;
	typedef RRT<VREPInterface, VREPInterface, PlakuTreeInterface> Plaku;

	unsigned int numberOfPRMVertices = stol(args->value("Number Of PRM Vertices"));
	unsigned int numberOfNearestNeighborEdgeConsiderations = stol(args->value("Nearest Neighbors To Consider In PRM Edge Construction"));
	double prmCollisionCheckDT = stod(args->value("PRM Collision Check DT"));

	PRMLite prmLite(*interface, *interface, start, numberOfPRMVertices, numberOfNearestNeighborEdgeConsiderations, prmCollisionCheckDT);

	double alpha = stod(args->value("Plaku Alpha Value"));
	double b = stod(args->value("Plaku b Value"));
	double stateRadius = stod(args->value("Plaku PRM State Selection Radius"));

	PlakuTreeInterface plakuTreeInterface(*interface, *interface, prmLite, start, goal, alpha, b, stateRadius);

	// plakuTreeInterface.draw();

	Plaku plaku(*interface, *interface, plakuTreeInterface, *args);
	plaku.query(start, goal);
}
Example #21
0
void DescentOptimizer::initialize() {
  cout << "Duplex initialization started. It make take a while to analyze the "
          "root."
       << endl;
  double *init = getInitialState();
  max = new double[objectiveDimension];
  min = new double[objectiveDimension];
  vector<string> objectiveMinStringVector =
      settings->listValues("objective", "uid-objective.min");
  vector<string> objectiveMaxStringVector =
      settings->listValues("objective", "uid-objective.max");
  for (int i = 0; i < objectiveDimension; i++) {
    min[i] = stod(objectiveMinStringVector[i]);
    max[i] = stod(objectiveMaxStringVector[i]);
  }
  stat = new Stat(settings, max, min, opt);
  // Setting up the root node
  State *root = new State(parameterDimension, objectiveDimension);
  root->setParameter(init);
  root->setID(0);
  root->setParentID(-1);
  system->eval(root);
  insert(0, root, root);
}
Example #22
0
OptionValue parse(option_type t, std::string s) {
	switch(t) {
	case options::option_type::bool_type:
		return options::OptionValue(s == "true");
	case option_type::int_type:
		return options::OptionValue(stoi(s));
	case option_type::double_type:
		return options::OptionValue(stod(s));
	case option_type::string_type:
		return options::OptionValue(s);
	case option_type::list_type:
		// TODO:
		return options::OptionValue(false);
	}
	return options::OptionValue(false);
}
Example #23
0
bool Dynamics::from_log_string(Dynamics & d, string &s) {
  auto fields = split(s,',');
  if(fields.size() <2) {
    return false;
  }
  if(fields[1] != "TD")
    return false;
  if(fields.size() != 41) {
    cerr << "field size was " << fields.size() << endl;
    //usb_error_count++;
    return false;
  }
//    self.datetime = dateutil.parser.parse(fields[0])

  try {
    d.datetime = time_from_string(fields[0]);
    d.str = stoi(fields[3]);
    d.esc = stoi(fields[5]);

    d.ax = stod(fields[7]);
    d.ay = stod(fields[8]);
    d.az = stod(fields[9]);

    d.spur_delta_us = stoul(fields[11]);
    d.spur_last_us = stoul(fields[12]);
    d.spur_odo = stoi(fields[14]);
    d.ping_millimeters = stoi(fields[16]);
    d.odometer_front_left =  stoi(fields[18]);
    d.odometer_front_left_last_us =  stoul(fields[19]);
    d.odometer_front_right = stoi(fields[21]);
    d.odometer_front_right_last_us = stoul(fields[22]);
    d.odometer_back_left = stoi(fields[24]);
    d.odometer_back_left_last_us = stoul(fields[25]);
    d.odometer_back_right = stoi(fields[27]);
    d.odometer_back_right_last_us = stoul(fields[28]);
    d.ms = stoul(fields[30]);
    d.us = stoul(fields[32]);
    d.yaw = Angle::degrees(stod(fields[34]));
    d.pitch = Angle::degrees(stod(fields[35]));
    d.roll = Angle::degrees(stod(fields[36]));
    d.battery_voltage = stod(fields[38]);
    d.calibration_status = stoi(fields[40]);
  } catch (...)
  {
    return false;
  }

  return true;

}
/**
 * @brief get_poses
 * @param dir_root
 * @param rotations      - Vector of rotation matrix(3,3)
 * @param pts            - Vector of translation vector
 * @return 1: file found, 0: file not found
 */
bool get_poses(string dir_root,string sequence,vector<Eigen::Matrix3d> &rotations,vector<geometry_msgs::Point> &pts) {

    string poseFile=sequence+".txt";

    string infile =(fs::path(dir_root) / fs::path("poses") /poseFile).string();
    fstream input(infile.c_str());
    string line;
    if(!input.good())
    {
        ROS_ERROR_STREAM ( "Could not read file: " << infile );
        return false;
    }
    //Transform each Isometric matrix stored in the file into a rotation Matrix and a translation vector
    while (getline (input,line))
    {
        stringstream ss(line);
        Eigen::Matrix3d rotation;
        geometry_msgs::Point pt;
        string entry;
        int i=0;

        while (ss >> entry) {
            double value=stod(entry);

            switch(i) {
            case 3:
                pt.x=value;
                break;
            case 7:
                pt.y=value;
                break;
            case 11:
                pt.z=value;
                break;
            default:
                rotation(i/4,i%4)= value;
                break;
            }
            i++;
        }

        rotations.push_back(rotation);
        pts.push_back(pt);
    }
    input.close();
    return true;
}
Example #25
0
bool Parser::readDouble(double& val, std::string& del)
{
    std::string str;

    readString(str, del);

    try
    {
        val = stod(str);
    }
    catch (std::invalid_argument ex)
    {
        return 0;
    }

    return 1;
}
Example #26
0
    void SyntaxModel::ReadFromText(const string& file)
    {
        wifstream in(file);
        wstring str;
        getline(in, str);
        int size = stoi(str);
        parameters.resize(size);

        vector<wstring> splitted;
        for (int it = 0; it < size; ++it)
        {
            getline(in, str);
            splitted = Tools::Split(str, L"\t");
            alphabet->LookUpIndex_Adding(splitted[0]);
            parameters[it] = stod(splitted[1]);
        }
        in.close();
    }
// the function only expects a line of doubles separated with whitespaces, has no argument validation 
vector<double> inputHandler::parseLineOfDoubles (string line) 
{
	vector<double> result;
	int pos = 0;
	int spacePosition = line.find(" ", pos);
	double tmp;
	while(spacePosition!=-1)
	{
		tmp = stod(line.substr(pos, spacePosition));
		inputHandler::furthestPoint = max(tmp, inputHandler::furthestPoint);
		inputHandler::closestPoint = min(tmp, inputHandler::closestPoint);
		result.push_back(tmp);

		pos = spacePosition+1;		
		spacePosition = line.find(" ", pos);
	}	
	return result;
}
	Map* MapLoader::loadMap(const string& mapFileName, const string& constrFileName) {
		ifstream mapFile(mapFileName);
		LoadableLocationSet locations;
		LoadableReaderSet readers;
		NameIdMap locationsMap;
		string line;
		if (mapFile.is_open()) {
			unsigned int lId = 0, rId = 0;
			while (getline(mapFile, line)) {
				Util::trim(line);
				// Jump if blank line or comment (starts with '#')
				if (line.length() == 0 || line[0] == '#') continue;
				vector<string> v = Util::split(line, SEP);
				if (v.size() == 5) { // Location line
					string name = v[0];
					double x = stod(v[1]), y = stod(v[2]),
					       w = stod(v[3]), h = stod(v[4]);
					locationsMap.insert(NameIdPair(name, lId));
					locations.push_back(Location(lId++, name, x, y, w, h));
				} else if (v.size() == 3) { // Reader line
					string name = v[0];
					double x = stod(v[1]), y = stod(v[2]);
					readers.push_back(Reader(rId++, name, x, y));
				} else throw BadInput();
			}
		} else throw BadInput();
		Map* map = Map::createMap<LoadableLocationSet,LoadableReaderSet>(locations, readers);
		ifstream constrFile(constrFileName);
		if (constrFile.is_open()) {
			while (getline(constrFile, line)) {
				Util::trim(line);
				// Jump if blank line or comment (starts with '#')
				if (line.length() == 0 || line[0] == '#') continue;
				vector<string> v = Util::split(line, CSEP);
				if (v[0] == "DR") { // Direct Reachability Constraint
					unsigned int id1 = locationsMap.at(v[1]), id2 = locationsMap.at(v[2]);
					map->setDR(id1, id2);
				} else if (v[0] == "DU") { // Direct Unreachability Constraint
					unsigned int id1 = locationsMap.at(v[1]), id2 = locationsMap.at(v[2]);
					map->setDU(id1, id2);
				} else if (v[0] == "LT") { // Latency Constraint
					unsigned int id = locationsMap.at(v[1]), latency = stoi(v[2]);
					map->setLT(id, latency);
				} else if (v[0] == "TT") { // Traveling Time Constraint
					unsigned int id1 = locationsMap.at(v[1]), id2 = locationsMap.at(v[2]),
						     travelingTime = stoi(v[3]);
					map->setTT(id1, id2, travelingTime);
				} else throw BadInput();
			}
		}
		return map;
	}
Example #29
0
Matrix DataCollector::readQMatrixFromText(string filename)
{
	unsigned int rows, columns;
	countLines(filename, rows, columns);
	ifstream infile; //input file stream object
	infile.open(filename);
	if (!infile) {
		cerr << "Bad input! Can't open " << filename << endl;
		exit(1);
	}
	Matrix Q(rows, 1);
	unsigned int i = 0;
	string line;
	while (getline(infile, line, '\n'))
	{
		Q(i++, 0) = stod(line);
	}
	return Q;
}
/*
    getDouble
    
    Gets double value from key.
    Throws an error if appropriate.
    If an error occurs, value is set to zero.
*/
void KeyValueReader::getDouble(const std::string &key, double &value) const
{
    string valueString;
    
    // Default value
    value = 0.0;
    
    // Get value as string
    getString(key, valueString);
    
    // Convert to double
    try {
        value = stod(valueString);
    }
    catch (...) {
        c_data->printMessage("Error converting value to double");
        throw ExceptionStringConversionError;
    }
}