Flow123d  release_2.1.2-337-g6b7a56b
main.cc
Go to the documentation of this file.
1 /*!
2  *
3  * Copyright (C) 2015 Technical University of Liberec. All rights reserved.
4  *
5  * This program is free software; you can redistribute it and/or modify it under
6  * the terms of the GNU General Public License version 3 as published by the
7  * Free Software Foundation. (http://www.gnu.org/licenses/gpl-3.0.en.html)
8  *
9  * This program is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
12  *
13  *
14  * @file main.cc
15  * @brief This file should contain only creation of Application object.
16  */
17 
18 
19 #include "system/system.hh"
20 #include "system/sys_profiler.hh"
21 #include "system/python_loader.hh"
23 #include "input/accessors.hh"
26 
27 #include <iostream>
28 #include <fstream>
29 #include <regex>
30 #include <boost/program_options/parsers.hpp>
31 #include <boost/program_options/variables_map.hpp>
32 #include <boost/program_options/options_description.hpp>
33 #include <boost/filesystem.hpp>
34 
35 #include "main.h"
36 
37 #include "rev_num.h"
38 
39 /// named version of the program
40 //#define _PROGRAM_VERSION_ "0.0.0"
41 
42 //#ifndef _PROGRAM_REVISION_
43 // #define _PROGRAM_REVISION_ "(unknown revision)"
44 //#endif
45 
46 //#ifndef _PROGRAM_BRANCH_
47 // #define _PROGRAM_BRANCH_ "(unknown branch)"
48 //#endif
49 
50 #ifndef FLOW123D_COMPILER_FLAGS_
51  #define FLOW123D_COMPILER_FLAGS_ "(unknown compiler flags)"
52 #endif
53 
54 
55 namespace it = Input::Type;
56 
57 // this should be part of a system class containing all support information
59  static it::Record type = it::Record("Root", "Root record of JSON input for Flow123d.")
60  .declare_key("flow123d_version", it::String(), it::Default::obligatory(),
61  "Version of Flow123d for which the input file was created."
62  "Flow123d only warn about version incompatibility. "
63  "However, external tools may use this information to provide conversion "
64  "of the input file to the structure required by another version of Flow123d.")
66  "Simulation problem to be solved.")
67  .declare_key("pause_after_run", it::Bool(), it::Default("false"),
68  "If true, the program will wait for key press before it terminates.")
69  .close();
70 
71  return type;
72 }
73 
74 
75 
76 Application::Application( int argc, char ** argv)
77 : ApplicationBase(argc, argv),
78  problem_(nullptr),
80  //passed_argc_(0),
81  //passed_argv_(0),
82  use_profiler(true),
84 {
85  // initialize python stuff if we have
86  // nonstandard python home (release builds)
87 #ifdef FLOW123D_HAVE_PYTHON
88  PythonLoader::initialize(argv[0]);
89 #endif
90 
91 }
92 
93 
95  Input::Type::RevNumData rev_num_data;
96 
97  rev_num_data.version = string(FLOW123D_VERSION_NAME_);
98  rev_num_data.revision = string(FLOW123D_GIT_REVISION_);
99  rev_num_data.branch = string(FLOW123D_GIT_BRANCH_);
100  rev_num_data.url = string(FLOW123D_GIT_URL_);
101 
102  return rev_num_data;
103 }
104 
105 
107  // Say Hello
108  // make strings from macros in order to check type
109  Input::Type::RevNumData rev_num_data = this->get_rev_num_data();
110  string build = string(__DATE__) + ", " + string(__TIME__)
111  + " flags: " + string(FLOW123D_COMPILER_FLAGS_);
112 
113 
114  MessageOut().fmt("This is Flow123d, version {} commit: {}\n",
115  rev_num_data.version, rev_num_data.revision);
116  MessageOut().fmt("Branch: {}\nBuild: {}\nFetch URL: {}\n",
117  rev_num_data.branch, build, rev_num_data.url );
118  Profiler::instance()->set_program_info("Flow123d",
119  rev_num_data.version, rev_num_data.branch, rev_num_data.revision, build);
120 }
121 
122 
123 
125  if (main_input_filename_ == "") {
126  cout << "Usage error: The main input file has to be specified through -s parameter.\n\n";
127  cout << program_arguments_desc_ << "\n";
128  exit( exit_failure );
129  }
130 
131  // read main input file
132  FilePath fpath(main_input_filename_, FilePath::FileType::input_file);
133  try {
134  Input::ReaderToStorage json_reader(fpath, get_input_type() );
136  } catch (Input::ReaderInternalBase::ExcInputError &e ) {
137  e << Input::ReaderInternalBase::EI_File(fpath); throw;
138  } catch (Input::ReaderInternalBase::ExcNotJSONFormat &e) {
139  e << Input::ReaderInternalBase::EI_File(fpath); throw;
140  }
141  return root_record;
142 }
143 
144 
145 
146 void Application::parse_cmd_line(const int argc, char ** argv) {
147  namespace po = boost::program_options;
148 
149 
150  // Declare the supported options.
151  po::options_description desc("Allowed options");
152  desc.add_options()
153  ("help", "produce help message")
154  ("solve,s", po::value< string >(), "Main input file to solve.")
155  ("input_dir,i", po::value< string >()->default_value("input"), "Directory for the ${INPUT} placeholder in the main input file.")
156  ("output_dir,o", po::value< string >()->default_value("output"), "Directory for all produced output files.")
157  ("log,l", po::value< string >()->default_value("flow123"), "Set base name for log files.")
158  ("version", "Display version and build information and exit.")
159  ("no_log", "Turn off logging.")
160  ("no_signal_handler", "Turn off signal handling. Useful for debugging with valgrind.")
161  ("no_profiler", "Turn off profiler output.")
162  ("input_format", po::value< string >(), "Writes full structure of the main input file into given file.")
163  ("petsc_redirect", po::value<string>(), "Redirect all PETSc stdout and stderr to given file.")
164  ("yaml_balance", "Redirect balance output to YAML format too (simultaneously with the selected balance output format).");
165 
166  ;
167 
168  // Can not use positional arguments together with PETSC options.
169  // Use our own solution trying to use the first unrecognized option as the main input file.
170 
171  // parse the command line
172  po::variables_map vm;
173  auto parser = po::basic_command_line_parser<char>(argc, argv)
174  .options(desc)
175  .allow_unregistered();
176  po::parsed_options parsed = parser.run();
177  po::store(parsed, vm);
178  po::notify(vm);
179 
180  // get unknown options
181  vector<string> to_pass_further = po::collect_unrecognized(parsed.options, po::include_positional);
182 
183 
184  /*
185  passed_argc_ = to_pass_further.size();
186  passed_argv_ = new char * [passed_argc_+1];
187 
188  // first copy the program executable in argv[0]
189  int arg_i=0;
190  if (argc > 0) passed_argv_[arg_i++] = xstrcpy( argv[0] );
191 
192  for(int i=0; i < passed_argc_; i++) {
193  passed_argv_[arg_i++] = xstrcpy( to_pass_further[i].c_str() );
194  }
195  passed_argc_ = arg_i;
196  */
197 
198  // possibly turn off profilling
199  if (vm.count("no_profiler")) use_profiler=false;
200 
201  // if there is "help" option
202  if (vm.count("help")) {
203  display_version();
204  cout << endl;
205  cout << "Usage:" << endl;
206  cout << " flow123d -s <main_input>.yaml <other options> <PETSC options>" << endl;
207  cout << " flow123d <main_input>.yaml <other options> <PETSC options>" << endl;
208  cout << desc << "\n";
209  exit( exit_output );
210  }
211 
212  if (vm.count("version")) {
213  display_version();
214  exit( exit_output );
215  }
216 
217  // if there is "input_format" option
218  if (vm.count("input_format")) {
219  // write ist to json file
220  ofstream json_stream;
221  FilePath(vm["input_format"].as<string>(), FilePath::output_file).open_stream(json_stream);
222  // create the root Record
223  it::Record root_type = get_input_type();
224  root_type.finish();
226  json_stream << Input::Type::OutputJSONMachine( root_type, this->get_rev_num_data() );
227  json_stream.close();
228  exit( exit_output );
229  }
230 
231  if (vm.count("petsc_redirect")) {
232  this->petsc_redirect_file_ = vm["petsc_redirect"].as<string>();
233  }
234 
235  if (vm.count("no_signal_handler")) {
236  this->signal_handler_off_ = true;
237  }
238 
239  // if there is "solve" option
240  string input_filename = "";
241 
242  // check for positional main input file
243  if (to_pass_further.size()) {
244  string file_candidate = to_pass_further[0];
245  if (file_candidate[0] != '-') {
246  // pop the first option
247  input_filename = file_candidate;
248  to_pass_further.erase(to_pass_further.begin());
249  }
250  }
251 
252  if (vm.count("solve")) {
253  input_filename = vm["solve"].as<string>();
254  }
255 
256  if (input_filename == "")
257  THROW(ExcMessage() << EI_Message("Main input file not specified (option -s)."));
258 
259  // preserves output of balance in YAML format
260  if (vm.count("yaml_balance")) yaml_balance_output_=true;
261 
262  string input_dir;
263  string output_dir;
264  if (vm.count("input_dir")) {
265  input_dir = vm["input_dir"].as<string>();
266  }
267  if (vm.count("output_dir")) {
268  output_dir = vm["output_dir"].as<string>();
269  }
270 
271  // assumes working directory "."
272  try {
273  main_input_filename_ = FilePath::set_dirs_from_input(input_filename, input_dir, output_dir );
274  } catch (FilePath::ExcMkdirFail &e) {
275  use_profiler = false; // avoid profiler output
276  throw e;
277  }
278 
279  if (vm.count("log")) {
280  this->log_filename_ = vm["log"].as<string>();
281  }
282 
283  if (vm.count("no_log")) {
284  this->log_filename_="//"; // override; do not open log files
285  }
286 
287  ostringstream tmp_stream(program_arguments_desc_);
288  tmp_stream << desc;
289  // TODO: catch specific exceptions and output usage messages
290 }
291 
292 
293 
294 
295 
297  START_TIMER("Application::run");
298  display_version();
299 
300  START_TIMER("Read Input");
301  // get main input record handle
302  Input::Record i_rec = read_input();
303  END_TIMER("Read Input");
304 
305  {
306  using namespace Input;
307  // check input file version against the version of executable
308  std::regex version_re("([^.]*)[.]([^.]*)[.]([^.]*)");
309  std::smatch match;
310  std::string version(FLOW123D_VERSION_NAME_);
311  vector<string> ver_fields(3);
312  if ( std::regex_match(version, match, version_re) ) {
313  ver_fields[0]=match[1];
314  ver_fields[1]=match[2];
315  ver_fields[2]=match[3];
316  } else {
317  OLD_ASSERT(1, "Bad Flow123d version format: %s\n", version.c_str() );
318  }
319 
320  std::string input_version = i_rec.val<string>("flow123d_version");
321  vector<string> iver_fields(3);
322  if ( std::regex_match(input_version, match, version_re) ) {
323  iver_fields[0]=match[1];
324  iver_fields[1]=match[2];
325  iver_fields[2]=match[3];
326  } else {
327  THROW( ExcVersionFormat() << EI_InputVersionStr(input_version) );
328  }
329 
330  if ( iver_fields[0] != ver_fields[0] || iver_fields[1] > ver_fields[1] ) {
331  WarningOut().fmt("Input file with version: '{}' is no compatible with the program version: '{}' \n",
332  input_version, version);
333  }
334 
335  // should flow123d wait for pressing "Enter", when simulation is completed
336  sys_info.pause_after_run = i_rec.val<bool>("pause_after_run");
337  // read record with problem configuration
338  Input::AbstractRecord i_problem = i_rec.val<AbstractRecord>("problem");
339 
340  if (i_problem.type() == HC_ExplicitSequential::get_input_type() ) {
341 
342  problem_ = new HC_ExplicitSequential(i_problem);
343 
344  // run simulation
346  } else {
347  xprintf(UsrErr,"Problem type not implemented.");
348  }
349 
350  }
351 }
352 
353 
354 
355 
358  printf("\nPress <ENTER> for closing the window\n");
359  getchar();
360  }
361 }
362 
363 
364 
365 
367  if (problem_) delete problem_;
368 
369  // remove balance output files in YAML format if "yaml_balance" option is not set
370  if ( (sys_info.my_proc==0) && !yaml_balance_output_ ) {
371  boost::filesystem::path mass_file( string(FilePath("mass_balance.yaml", FilePath::output_file)) );
372  boost::filesystem::path water_file( string(FilePath("water_balance.yaml", FilePath::output_file)) );
373  boost::filesystem::path energy_file( string(FilePath("energy_balance.yaml", FilePath::output_file)) );
374 
375  if (boost::filesystem::exists(mass_file)) {
376  boost::filesystem::remove(mass_file);
377  }
378  if (boost::filesystem::exists(water_file)) {
379  boost::filesystem::remove(water_file);
380  }
381  if (boost::filesystem::exists(energy_file)) {
382  boost::filesystem::remove(energy_file);
383  }
384  }
385 
386  if (use_profiler) {
387  if (petsc_initialized) {
388  // log profiler data to this stream
389  Profiler::instance()->output (PETSC_COMM_WORLD);
390  } else {
392  }
393 
394  // call python script which transforms json file at given location
395  // Profiler::instance()->transform_profiler_data (".csv", "CSVFormatter");
396  Profiler::instance()->transform_profiler_data (".txt", "SimpleTableFormatter");
397 
398  // finally uninitialize
400  }
401 }
402 
403 
404 //=============================================================================
405 
406 /**
407  * FUNCTION "MAIN"
408  */
409 int main(int argc, char **argv) {
410  try {
411  Application app(argc, argv);
412  app.init(argc, argv);
413  } catch (std::exception & e) {
414  _LOG( Logger::MsgType::error ) << e.what();
416  } catch (...) {
417  _LOG( Logger::MsgType::error ) << "Unknown exception" << endl;
419  }
420 
421  // Say Goodbye
423 }
static Input::Type::Abstract & get_input_type()
int my_proc
Definition: system.hh:78
virtual void run()
Definition: main.cc:296
Input::Type::RevNumData get_rev_num_data()
Get version of program and other base data from rev_num.h and store them to map.
Definition: main.cc:94
virtual void parse_cmd_line(const int argc, char **argv)
Definition: main.cc:146
Reader for (slightly) modified input files.
Class Input::Type::Default specifies default value of keys of a Input::Type::Record.
Definition: type_record.hh:61
Class for declaration of the input of type Bool.
Definition: type_base.hh:458
#define MessageOut()
Macro defining &#39;message&#39; record of log.
Definition: logger.hh:233
string main_input_filename_
filename of main input file
Definition: main.h:97
virtual void after_run()
Definition: main.cc:356
static bool petsc_initialized
Application(int argc, char **argv)
Application constructor.
Definition: main.cc:76
static Default obligatory()
The factory function to make an empty default value which is obligatory.
Definition: type_record.hh:110
Class for create JSON machine readable documentation.
Definition: type_output.hh:252
std::string branch
Actual branch of application.
Definition: type_output.hh:47
bool use_profiler
If true, we do output of profiling information.
Definition: main.h:106
static string set_dirs_from_input(const string main_yaml, const string input, const string output)
Method for set input and output directories.
Definition: file_path.cc:137
Record & close() const
Close the Record for further declarations of keys.
Definition: type_record.cc:303
HC_ExplicitSequential * problem_
Main Flow123d problem.
Definition: main.h:94
#define OLD_ASSERT(...)
Definition: global_defs.h:131
void open_stream(Stream &stream) const
Definition: file_path.cc:211
Stores version of program and other base data of application.
Definition: type_output.hh:44
static void uninitialize()
static const int exit_failure
static const int exit_success
Return codes of application.
T get_root_interface() const
Returns the root accessor.
#define _LOG(type)
Internal macro defining universal record of log.
Definition: logger.hh:230
Accessor to the data with type Type::Record.
Definition: accessors.hh:292
const Ret val(const string &key) const
#define xprintf(...)
Definition: system.hh:92
bool yaml_balance_output_
If true, preserves output of balance in YAML format.
Definition: main.h:109
#define START_TIMER(tag)
Starts a timer with specified tag.
Record & declare_key(const string &key, std::shared_ptr< TypeBase > type, const Default &default_value, const string &description, TypeBase::attribute_map key_attributes=TypeBase::attribute_map())
Declares a new key of the Record.
Definition: type_record.cc:490
void display_version()
Definition: main.cc:106
void set_program_info(string program_name, string program_version, string branch, string revision, string build)
bool signal_handler_off_
Turn off signal handling useful to debug with valgrind.
static Input::Type::Record & get_input_type()
Root of the Input::Type tree. Description of whole input structure.
Definition: main.cc:58
int main(int argc, char **argv)
Definition: main.cc:409
void init(int argc, char **argv)
Accessor to the polymorphic input data of a type given by an AbstracRecord object.
Definition: accessors.hh:459
void transform_profiler_data(const string &output_file_suffix, const string &formatter)
Dedicated class for storing path to input and output files.
Definition: file_path.hh:54
Definition: system.hh:64
std::string revision
Actual revision of application.
Definition: type_output.hh:46
FinishStatus finish(FinishStatus finish_type=FinishStatus::regular_) override
Finish declaration of the Record type.
Definition: type_record.cc:242
static const int exit_output
static Profiler * instance()
string program_arguments_desc_
Description of possible command line arguments.
Definition: main.h:103
SystemInfo sys_info
Definition: system.cc:41
#define WarningOut()
Macro defining &#39;warning&#39; record of log.
Definition: logger.hh:236
#define END_TIMER(tag)
Ends a timer with specified tag.
static const Input::Type::Record & get_input_type()
static void delete_unfinished_types()
Finishes and marks all types registered in type repositories and unused in IST.
Definition: type_base.cc:108
Record type proxy class.
Definition: type_record.hh:182
std::string version
Actual version of application.
Definition: type_output.hh:45
Class for solution of steady or unsteady flow with sequentially coupled explicit transport.
virtual ~Application()
Destructor.
Definition: main.cc:366
#define FLOW123D_COMPILER_FLAGS_
named version of the program
Definition: main.cc:51
Input::Record root_record
root input record
Definition: main.h:112
Class for declaration of the input data that are in string format.
Definition: type_base.hh:588
#define THROW(whole_exception_expr)
Wrapper for throw. Saves the throwing point.
Definition: exceptions.hh:53
void output(MPI_Comm comm, ostream &os)
int pause_after_run
Definition: system.hh:73
Input::Record read_input()
Definition: main.cc:124
void printf(BasicWriter< Char > &w, BasicCStringRef< Char > format, ArgList args)
Definition: printf.h:444
std::string url
Url of application.
Definition: type_output.hh:48