args.h 12.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/* ALTA --- Analysis of Bidirectional Reflectance Distribution Functions

   Copyright (C) 2013, 2014 Inria

   This file is part of ALTA.

   This Source Code Form is subject to the terms of the Mozilla Public
   License, v. 2.0.  If a copy of the MPL was not distributed with this
   file, You can obtain one at http://mozilla.org/MPL/2.0/.  */

11 12 13
#pragma once

#include <string>
14
#include <sstream>
15 16 17 18
#include <map>
#include <cstdlib>
#include <iostream>

Laurent Belcour's avatar
Laurent Belcour committed
19 20
#include "common.h"

21 22
/*! \brief A useful class for storing the high-level arguments of a program
 *  or a function.
23 24
 *  \ingroup core
 *  \internal
25 26 27 28 29
 *
 *  The set of parameters are parsed from the command line using the 
 *  constructor. They are stored as std::string in a std::map.
 *  \todo add functionalities to provide new parameters values.
 */
30 31 32 33 34
class arguments
{
	public: // functions

		// Constructor and destructor
Laurent Belcour's avatar
Laurent Belcour committed
35 36
		arguments()
		{
37
		}
38
		arguments(int argc, char** const argv)
39 40 41 42 43 44 45 46
    {
      for(int i=0; i<argc; ++i)
      {
        std::string temp(argv[i]) ;
        std::string key;
        std::string data;

        if(temp.compare(0, 2, "--") == 0)
47
        {
48 49 50 51 52
            key = temp.substr(2, temp.size()-2) ;
  #ifdef DEBUG_ARGS
            std::cout << "<<DEBUG>> (" << i << ")" << key << " -> [ ";
  #endif
            if(++i < argc)
53
            {
54 55
                std::string next(argv[i]) ;
                if(next[0] == '-')
56
                {
57 58 59 60 61
                    --i;
                }
                else if(next[0] == '[' && next[next.size()-1] != ']')
                {
                    data.append(next);
62

63 64 65 66 67 68 69 70 71 72 73 74 75
                    ++i;
                    while(i < argc && next[next.size()-1] != ']')
                    {
                        next = argv[i] ;
                        data.append(" ");
  #ifdef DEBUG_ARGS
                        std::cout << " ";
  #endif
                        data.append(next);
  #ifdef DEBUG_ARGS
                        std::cout << "(" << i << ")" << next;
  #endif
                        ++i;
76
                    }
77
                    --i;
78
                }
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
                else
                {
  #ifdef DEBUG_ARGS
                    std::cout << next;
  #endif
                    data.append(next);
                }
            }//end of if 
  #ifdef DEBUG_ARGS
            std::cout << "]" << std::endl;
  #endif
            _map.insert(std::pair<std::string, std::string>(key, data)) ;
        }//end of if test with "--"
      }//end of for-loop
    }
		
    ~arguments()
96 97
		{
		}
98

99
		//! \brief is the elements in the command line ?
100 101 102 103 104 105 106 107 108 109
		bool is_defined(const std::string& key) const
		{
			if(_map.count(key) > 0)
			{
				return true ;
			}
			else
			{
				return false ;
			}
110
    }
111

112 113 114 115 116 117 118
    //! \brief is the data at the given key in a vector format?
    //! No matter the type of the data, this function will test is the
    //! mapped string is of type "[ .... ]".
    //! It returns false if there is no associated entry.
    bool is_vec(const std::string& key) const
    {
        if(_map.count(key) > 0)
119
        {
120 121 122 123 124
            return _map.find(key)->second[0] == '[' ;
        }
        else
        {
            return false ;
125
        }
126
    }
127

128
		//! \brief access the element stored value
129 130
		std::string operator[](const std::string& key) const
		{
131 132 133 134 135 136
  		if(_map.count(key) > 0)
  		{
  			return _map.find(key)->second ;
  		}
  		else
  		{
137
                //std::cerr << "Underfined request to key : \"" << key << "\"" << std::endl ;
138 139 140 141 142 143 144 145 146 147 148
  			return std::string() ;
  		}
    }
    
    //! \brief update the value \a val stored under key \a key
    void update(const std::string& key, const std::string& val)
    {
        _map[key] = val;
    }
		
    //! \brief acces to the string value associated with the parameter
149 150 151 152 153 154 155 156 157 158 159
		//! \a key.
		//!
		//! The \a default_value argument will be returned if the \a key
		//! has no associated value.
		std::string get_string(const std::string& key, std::string default_value = "") const
		{
			if(_map.count(key) > 0)
				return _map.find(key)->second.c_str() ;
			else
				return default_value ;
		}
160

161 162 163 164 165
		//! \brief acces to the float value associated with the parameter
		//! \a key.
		//!
		//! The \a default_value argument will be returned if the \a key
		//! has no associated value.
166
		float get_float(const std::string& key, float default_value = 0.0f) const
167
		{
168
			if(_map.count(key) > 0)
Laurent Belcour's avatar
Laurent Belcour committed
169
				return (float)atof(_map.find(key)->second.c_str()) ;
170
			else
171
				return default_value ;
Laurent Belcour's avatar
Laurent Belcour committed
172
		}
173

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    //! \brief access to the double value associated with the parameter \a key
    //!
    //! The \a default_value argument will be returned if the \a key
    //! has no associated value.
    double get_double(const std::string& key, double default_value = 0.0) const
    {
      //IF C++ 2011 is supported and activated
      #if __cplusplus > 199711L
        
      auto search = _map.find(key);
      if ( search != _map.end() )
      {
        return std::stod( search->second );
      }
      return default_value;

      #else
      
      std::map<std::string,std::string>::const_iterator res = _map.find(key);
      if ( res != _map.end() )
      {
        return std::atof( res->second.c_str() );
      }
      
      return default_value;
      #endif
    }

202 203 204 205 206
		//! \brief acces to the integer value associated with the parameter
		//! \a key.
		//!
		//! The \a default_value argument will be returned if the \a key
		//! has no associated value.
207
		int get_int(const std::string& key, int default_value = 0) const
208
		{
209
			if(_map.count(key) > 0)
Laurent Belcour's avatar
Laurent Belcour committed
210
				return atoi(_map.find(key)->second.c_str()) ;
211
			else
212
				return default_value ;
Laurent Belcour's avatar
Laurent Belcour committed
213
		} 
214 215
	
  	//! \brief acces to a vector of float of size \a size associated with
216 217 218 219
		//! the parameter \a key.
		//!
		//! The \a default_value argument will be returned if the \a key
		//! has no associated value.
220
		vec get_vec(const std::string& key, int size, float default_value = 0.0f) const
Laurent Belcour's avatar
Laurent Belcour committed
221
		{
222
			vec res(size);
223 224
			for(int i=0; i<size; ++i)
				res[i] = default_value;
225

Laurent Belcour's avatar
Laurent Belcour committed
226 227
			if(_map.count(key) > 0)
			{
Laurent Belcour's avatar
Laurent Belcour committed
228
				std::string s = _map.find(key)->second;
229
				if(s[0] == '[') // Is an array of type [a, b, c]
Laurent Belcour's avatar
Laurent Belcour committed
230 231
				{
					int i = 0;
232
					size_t pos = 1;
233
					while(pos != std::string::npos && i<size)
Laurent Belcour's avatar
Laurent Belcour committed
234
					{
235
						size_t ppos = s.find(',', pos);
Laurent Belcour's avatar
Laurent Belcour committed
236 237 238

						if(ppos != std::string::npos)
						{
239
							res[i] = atof(s.substr(pos, ppos-pos).c_str());
Laurent Belcour's avatar
Laurent Belcour committed
240 241 242
							pos = ppos+1;
							++i;
						}
243 244
						else
						{
245 246
							std::string temp = s.substr(pos, std::string::npos);
							res[i] = atof(temp.substr(0, temp.size()-1).c_str());
247 248 249
							pos = ppos;
							++i;
						}
Laurent Belcour's avatar
Laurent Belcour committed
250 251 252 253 254 255
					}
					return res;
				}
			}

			float val = get_float(key, default_value);
256 257 258 259
			for(int i=0; i<size; ++i)
			{
				res[i] = val;
			}
Laurent Belcour's avatar
Laurent Belcour committed
260 261
			return res;
		}
262

263 264 265 266 267 268
		//! \brief access a vector of element of type \a T of variable length.
		//! the string associated with the key \a key should have the form
		//! "[a, b, c]" where a, b, c are of type \a T.
		template<typename T>
		std::vector<T> get_vec(const std::string& key) const
		{
269
		  std::vector<T> res;
270

271 272 273 274
      //TODO: RP: it is not very efficient to call count + find 
      // because find is called twice !!! 
      // My advice: find should be called once, check if the key exist
      // and if yes use the iterator returned by find
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
			if(_map.count(key) > 0)
			{
				std::string str = _map.find(key)->second;
				if(str[0] == '[' && str[str.size()-1] == ']') // Is an array of type [a, b, c]
				{
					std::stringstream stream(str.substr(1, str.size()-2));
					char s[256];
					while(stream.good())
					{
						// Extract the value v from the stream s
						stream.get(s, 256, ',');
						stream.ignore(1);
						std::stringstream sstream(s);
						T v;
						sstream >> v;

						// Push the value at the end of the vector
						res.push_back(v);
					}
				}
			}
			return res;
		}

299
    //RP: why is this method coded and specialized ?
300 301 302 303 304 305
    std::vector<std::string> get_vec(const std::string& key) const
    {
      std::vector<std::string> res;
      if(_map.count(key) > 0)
      {
          std::string s = _map.find(key)->second;
306

307 308 309 310 311 312
          if(s[0] == '[') // Is an array of type [a, b, c]
          {
              size_t pos = 1;
              while(pos != std::string::npos)
              {
                  size_t ppos = s.find(',', pos);
313

314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
                  if(ppos != std::string::npos)
                  {
                      std::string temp = s.substr(pos, ppos-pos);
                      res.push_back(temp);
                      pos = ppos+1;
                  }
                  else
                  {
                      std::string temp = s.substr(pos, std::string::npos);
                      temp = temp.substr(0, temp.size()-1);
                      res.push_back(temp);
                      pos = ppos;
                  }
              }
          }
329
        }
330 331
      return res;
    }
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
		
		//! \brief access a pair of element of type \a T.
		//! the string associated with the key \a key should have the form
		//! "a b" where a, b are compatible with type \a T.
		template<typename T>
		std::pair<T, T> get_pair(const std::string& key) const {

			std::pair<T, T> res;

			//TODO: RP: it is not very efficient to call count + find 
			// because find is called twice !!! 
			// My advice: find should be called once, check if the key exist
			// and if yes use the iterator returned by find
			if(_map.count(key) > 0) {

				std::string str = _map.find(key)->second;
				std::stringstream sstream(str);

				T first, second;
				sstream >> first >> second;

				// Update the pair
				res.first  = first;
				res.second = second;
			}
			return res;
		}
359

360 361 362 363 364 365 366 367 368
		  //! \brief get the reconstructed command line arguments (without
		  //! the executable name
		  std::string get_cmd() const
		  {
			  std::string cmd;

			  std::map<std::string, std::string>::const_iterator it = _map.begin();
			  for(;it != _map.end(); it++)
			  {
369 370 371 372 373 374 375
				  if(!it->first.empty())
				  {
					  cmd.append(" --");
					  cmd.append(it->first);
					  cmd.append(" ");
					  cmd.append(it->second);
				  }
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
			  }

			  return cmd;
		  }

		  //! \brief Create an argument object from a string describing a command
		  //! line.
		  static arguments create_arguments(const std::string& n)
		  {
			  std::vector<std::string> cmd_vec;
			  std::stringstream stream(n);
#ifdef DEBUG_ARGS
			  std::cout << "<<DEBUG>> create argument vector: [";
#endif
			  while(stream.good())
			  {
				  std::string temp;
				  stream >> temp;
#ifdef DEBUG_ARGS
				  std::cout << temp << ", ";
#endif

				  cmd_vec.push_back(temp);
			  }
#ifdef DEBUG_ARGS
			  std::cout << "]" << std::endl;
#endif

			  int argc = cmd_vec.size();
405 406
			  char** argv;
			  argv = new char*[argc];
407 408 409 410 411 412
			  for(int i=0; i<argc; ++i)
			  {
				  argv[i] = &cmd_vec[i][0];
			  }

			  arguments current_args(argc, argv);
413
			  delete[] argv;
414 415 416
			  return current_args;
		  }

417 418 419 420 421
      //! \brief Friend function to display the content of an argument object
      friend std::ostream& operator<<(std::ostream& out, const arguments& args)
      {
          std::map<std::string, std::string>::const_iterator it;
          for(it=args._map.begin(); it!=args._map.end(); ++it)
422
          {
423
              out<< "[" << it->first << "] -> " << it->second << std::endl;
424
          }
425 426
          return out;
      }
427

428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
		//! \brief Parse a data file header.
		//
		//! \detail
		//! ALTA file header should appear at the beginning of each file. Each
		//! line starts with '#' and describe a couple key, value. For example,
		//! parametrizations are described as:
		//!	#PARAM_IN NAME
		//!
		//! Note: A header should always start and ends by:
		//!	#ALTA HEADER BEGIN
		//!	#ALTA HEADER END
		//!
		static arguments parse_header(std::istream &input) {

			// Argument object to be returned
			arguments args;

			while(input.good())
			{
				if (input.peek() == '#')
				{
					// consume the hash sign
					input.get();

					// Get the line
					std::string line;
					std::getline(input, line);
					std::stringstream linestream(line);

					// Lines starting with '# ' are real comments and we ignore
					// them.  Others are key/value associations that we want to use.
					if (linestream.peek() != ' ')	{

						linestream.flags(std::ios_base::skipws);

						std::string key, data;
						linestream >> key;
						if (!key.empty()) {

							// ALTA header starts and ends with '#ALTA'
							if (key == "ALTA") {
								std::string first, second;
								linestream >> first >> second;
								if (second == "HEADER")	{

									// Add the header type
									if (first != "END") {
										args.update("TYPE", second);
									} else {
										break;
									}
								}

							// Store the line into the argument 
							} else {
								while(!linestream.eof()	&& std::isspace(linestream.peek()))	{
									linestream.get();
								}

								getline(linestream, data);
								args.update(key, data) ;
							}
						}
					}
					
				// The first non-comment line terminates the header.
				} else {
					break;
				}
			}

			return args;
		}

502

503 504 505 506 507
	private: // data

		std::map<std::string, std::string> _map ;

} ;