source: src/UIElements/CommandLineUI/CommandLineParser.cpp@ ad011c

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since ad011c was ad011c, checked in by Frederik Heber <heber@…>, 14 years ago

CodePatterns places all includes now in subfolder CodePatterns/.

  • change all includes accordingly.
  • this was necessary as Helpers and Patterns are not very distinctive names for include folders. Already now, we had a conflict between Helpers from CodePatterns and Helpers from this project.
  • changed compilation test in ax_codepatterns.m4 when changing CodePatterns includes.
  • Property mode set to 100644
File size: 18.2 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/*
9 * CommandLineParser.cpp
10 *
11 * Created on: May 8, 2010
12 * Author: heber
13 */
14
15// include config.h
16#ifdef HAVE_CONFIG_H
17#include <config.h>
18#endif
19
20#include "CodePatterns/MemDebug.hpp"
21
22#include <boost/filesystem.hpp>
23#include <boost/program_options.hpp>
24#include <fstream>
25#include <iostream>
26#include <map>
27
28#include "Actions/Action.hpp"
29#include "Actions/ActionRegistry.hpp"
30#include "Actions/ActionTraits.hpp"
31#include "Actions/OptionRegistry.hpp"
32#include "Actions/OptionTrait.hpp"
33#include "Actions/Values.hpp"
34#include "CodePatterns/Log.hpp"
35#include "CodePatterns/Verbose.hpp"
36#include "CommandLineParser.hpp"
37#include "CommandLineParser_validate.hpp"
38
39#include "CodePatterns/Singleton_impl.hpp"
40
41class element;
42
43/** Constructor of class CommandLineParser.
44 *
45 */
46CommandLineParser::CommandLineParser() :
47 analysis("Analysis options"),
48 atom("Atom options"),
49 command("Command options"),
50 fragmentation("Fragmentation options"),
51 molecule("Molecule options"),
52 parser("Parser options"),
53 selection("Selection options"),
54 tesselation("Tesselation options"),
55 world("World options"),
56 options("Secondary options")
57{
58 // put all options lists into a lookup
59 CmdParserLookup["analysis"] = &analysis;
60 CmdParserLookup["atom"] = &atom;
61 CmdParserLookup["command"] = &command;
62 CmdParserLookup["edit"] = &edit;
63 CmdParserLookup["fragmentation"] = &fragmentation;
64 CmdParserLookup["molecule"] = &molecule;
65 CmdParserLookup["parser"] = &parser;
66 CmdParserLookup["selection"] = &selection;
67 CmdParserLookup["tesselation"] = &tesselation;
68 CmdParserLookup["world"] = &world;
69 CmdParserLookup["options"] = &options;
70}
71
72/** Destructor of class CommandLineParser.
73 *
74 */
75CommandLineParser::~CommandLineParser()
76{}
77
78/** Initializes command arguments to accept.
79 * Goes through ActionRegistry and puts all actions therein into the map.
80 */
81void CommandLineParser::InitializeCommandArguments()
82{
83 ActionRegistry &AR = ActionRegistry::getInstance();
84 bool ActionAlreadyAdded_flag = false;
85 for (ActionRegistry::const_iterator actioniter = AR.getBeginIter(); actioniter != AR.getEndIter(); ++actioniter) {
86 ActionAlreadyAdded_flag = false;
87 Action* const currentAction = actioniter->second;
88 //std::cout << "Current Action to initialize is: " << actioniter->first << std::endl;
89
90 for (ActionTraits::options_const_iterator optioniter = currentAction->Traits.getBeginIter();
91 optioniter != currentAction->Traits.getEndIter();
92 ++optioniter) {
93 if (optioniter->first == actioniter->first)
94 ActionAlreadyAdded_flag = true;
95 ASSERT( OptionRegistry::getInstance().isOptionPresentByName(optioniter->first),
96 "CommandLineParser::Init() - Option not present in OptionRegistry." );
97 const OptionTrait* const currentOption = OptionRegistry::getInstance().getOptionByName(optioniter->first);
98 // add the option
99// std::cout << "Registering Option "
100// << currentOption->getName()
101// << " with type '" << currentOption->getTypeName() << "' "
102// << " with description '" << currentOption->getDescription() << "' ";
103// if (currentOption->hasShortForm())
104// std::cout << ", with short form " << currentOption->getShortForm();
105// else
106// std::cout << ", with no short form ";
107// if (currentOption->hasDefaultValue())
108// std::cout << ", with default value " << currentOption->getDefaultValue();
109// else
110// std::cout << ", with no default value ";
111// std::cout << std::endl;
112
113 AddOptionToParser(currentOption, (CmdParserLookup["options"]));
114 }
115
116 if (!ActionAlreadyAdded_flag) {
117 // add the action
118// std::cout << "Registering Action "
119// << currentAction->Traits.getName()
120// << " in menu " << currentAction->Traits.getMenuName()
121// << " with type '" << currentAction->Traits.getTypeName() << "' "
122// << " with description '" << currentAction->Traits.getDescription() << "' ";
123// if (currentAction->Traits.hasShortForm())
124// std::cout << ", with short form " << currentAction->Traits.getShortForm();
125// else
126// std::cout << ", with no short form ";
127// if (currentAction->Traits.hasDefaultValue())
128// std::cout << ", with default value " << currentAction->Traits.getDefaultValue();
129// else
130// std::cout << ", with no default value ";
131// std::cout << std::endl;
132
133 ASSERT(CmdParserLookup.find(currentAction->Traits.getMenuName()) != CmdParserLookup.end(),
134 "CommandLineParser: boost::program_options::options_description for this Action not present.");
135 AddOptionToParser(dynamic_cast<const OptionTrait * const>(&(currentAction->Traits)),(CmdParserLookup[currentAction->Traits.getMenuName()]));
136 }
137 }
138 // note: positioning is not important on the command line
139}
140
141/** Adds an Action or Option to the CommandLineParser.
142 * Note that Action is derived from Option(Trait)
143 *
144 * This ugly switch function is necessary because of the compile-time problem:
145 * po::value<T> has to be instantiated at compile-time however we do know the type not until run-time.
146 * Not even a templated function like po::value<T> getProgramOptionValuefromType() does help, specialized
147 * to each available type, as the signatures of all the functions differ. Hence, they cannot not put into
148 * one type_info -> po::value<T> map ...
149 *
150 * \param *currentOption pointer to Action/Option to add
151 * \param *OptionList program_options list to add to
152 */
153void CommandLineParser::AddOptionToParser(const OptionTrait * const currentOption, po::options_description* OptionList)
154{
155 // check whether dynamic_cast in Init() suceeded
156 ASSERT(currentOption != NULL, "CommandLineParser::AddOptionToParser() - currentOption is NULL!");
157 // add other options
158 //std::cout << "Adding Action " << currentOption->getName() << " with type " << currentOption->getType()->name() << " and KeyandShortform " << currentOption->getKeyAndShortForm() << " to CommandLineParser." << std::endl;
159 switch(TypeToEnums.getEnumforType(currentOption->getType())) {
160 default:
161 case TypeEnumContainer::NoneType:
162 OptionList->add_options()
163 (currentOption->getKeyAndShortForm().c_str(), currentOption->getDescription().c_str())
164 ;
165 break;
166 case TypeEnumContainer::BooleanType:
167 OptionList->add_options()
168 (currentOption->getKeyAndShortForm().c_str(),
169 currentOption->hasDefaultValue() ?
170 po::value < bool >()->default_value(boost::lexical_cast<int>(currentOption->getDefaultValue().c_str())) :
171 po::value < bool >(),
172 currentOption->getDescription().c_str())
173 ;
174 break;
175 case TypeEnumContainer::BoxType:
176 OptionList->add_options()
177 (currentOption->getKeyAndShortForm().c_str(),
178// currentOption->hasDefaultValue() ?
179// po::value < BoxValue >()->default_value(boost::lexical_cast<BoxValue>(currentOption->getDefaultValue().c_str())) :
180 po::value < BoxValue >(),
181 currentOption->getDescription().c_str())
182 ;
183 break;
184 case TypeEnumContainer::FileType:
185 OptionList->add_options()
186 (currentOption->getKeyAndShortForm().c_str(),
187// currentOption->hasDefaultValue() ?
188// po::value < boost::filesystem::path >()->default_value(boost::lexical_cast<boost::filesystem::path>(currentOption->getDefaultValue().c_str())) :
189 po::value < boost::filesystem::path >(),
190 currentOption->getDescription().c_str())
191 ;
192 break;
193 case TypeEnumContainer::ListOfFilesType:
194 OptionList->add_options()
195 (currentOption->getKeyAndShortForm().c_str(),
196// currentOption->hasDefaultValue() ?
197// po::value < std::vector<boost::filesystem::path> >()->default_value(boost::lexical_cast< std::vector<boost::filesystem::path> >(currentOption->getDefaultValue().c_str())) :
198 po::value < std::vector<boost::filesystem::path> >()->multitoken(),
199 currentOption->getDescription().c_str())
200 ;
201 break;
202 case TypeEnumContainer::IntegerType:
203 OptionList->add_options()
204 (currentOption->getKeyAndShortForm().c_str(),
205 currentOption->hasDefaultValue() ?
206 po::value < int >()->default_value(boost::lexical_cast<int>(currentOption->getDefaultValue().c_str())) :
207 po::value < int >(),
208 currentOption->getDescription().c_str())
209 ;
210 break;
211 case TypeEnumContainer::ListOfIntegersType:
212 OptionList->add_options()
213 (currentOption->getKeyAndShortForm().c_str(),
214// currentOption->hasDefaultValue() ?
215// po::value < std::vector<int> >()->default_value(boost::lexical_cast< std::vector<int> >(currentOption->getDefaultValue().c_str())) :
216 po::value < std::vector<int> >()->multitoken(),
217 currentOption->getDescription().c_str())
218 ;
219 break;
220 case TypeEnumContainer::DoubleType:
221 OptionList->add_options()
222 (currentOption->getKeyAndShortForm().c_str(),
223 currentOption->hasDefaultValue() ?
224 po::value < double >()->default_value(boost::lexical_cast<double>(currentOption->getDefaultValue().c_str())) :
225 po::value < double >(),
226 currentOption->getDescription().c_str())
227 ;
228 break;
229 case TypeEnumContainer::ListOfDoublesType:
230 OptionList->add_options()
231 (currentOption->getKeyAndShortForm().c_str(),
232// currentOption->hasDefaultValue() ?
233// po::value < std::vector<double> >()->default_value(boost::lexical_cast< std::vector<double> >(currentOption->getDefaultValue().c_str())) :
234 po::value < std::vector<double> >()->multitoken(),
235 currentOption->getDescription().c_str())
236 ;
237 break;
238 case TypeEnumContainer::StringType:
239 OptionList->add_options()
240 (currentOption->getKeyAndShortForm().c_str(),
241 currentOption->hasDefaultValue() ?
242 po::value < std::string >()->default_value(currentOption->getDefaultValue()) :
243 po::value < std::string >(),
244 currentOption->getDescription().c_str())
245 ;
246 break;
247 case TypeEnumContainer::ListOfStringsType:
248 OptionList->add_options()
249 (currentOption->getKeyAndShortForm().c_str(),
250// currentOption->hasDefaultValue() ?
251// po::value < std::vector<std::string> >()->default_value(boost::lexical_cast< std::vector<std::string> >(currentOption->getDefaultValue().c_str())) :
252 po::value < std::vector<std::string> >()->multitoken(),
253 currentOption->getDescription().c_str())
254 ;
255 break;
256 case TypeEnumContainer::VectorType:
257 OptionList->add_options()
258 (currentOption->getKeyAndShortForm().c_str(),
259// currentOption->hasDefaultValue() ?
260// po::value < VectorValue >()->default_value(boost::lexical_cast<VectorValue>(currentOption->getDefaultValue().c_str())) :
261 po::value < VectorValue >(),
262 currentOption->getDescription().c_str())
263 ;
264 break;
265 case TypeEnumContainer::ListOfVectorsType:
266 OptionList->add_options()
267 (currentOption->getKeyAndShortForm().c_str(),
268// currentOption->hasDefaultValue() ?
269// po::value < std::vector<VectorValue> >()->default_value(boost::lexical_cast< std::vector<VectorValue> >(currentOption->getDefaultValue().c_str())) :
270 po::value < std::vector<VectorValue> >()->multitoken(),
271 currentOption->getDescription().c_str())
272 ;
273 break;
274 case TypeEnumContainer::MoleculeType:
275 OptionList->add_options()
276 (currentOption->getKeyAndShortForm().c_str(),
277// currentOption->hasDefaultValue() ?
278// po::value < const molecule * >()->default_value(boost::lexical_cast<const molecule *>(currentOption->getDefaultValue().c_str())) :
279 po::value < int >(),
280 currentOption->getDescription().c_str())
281 ;
282 break;
283 case TypeEnumContainer::ListOfMoleculesType:
284 OptionList->add_options()
285 (currentOption->getKeyAndShortForm().c_str(),
286// currentOption->hasDefaultValue() ?
287// po::value < std::vector<const molecule *> >()->default_value(boost::lexical_cast< std::vector<const molecule *> >(currentOption->getDefaultValue().c_str())) :
288 po::value < std::vector<int> >()->multitoken(),
289 currentOption->getDescription().c_str())
290 ;
291 break;
292 case TypeEnumContainer::AtomType:
293 OptionList->add_options()
294 (currentOption->getKeyAndShortForm().c_str(),
295 currentOption->hasDefaultValue() ?
296 po::value < int >()->default_value(boost::lexical_cast<int>(currentOption->getDefaultValue().c_str())) :
297 po::value < int >(),
298 currentOption->getDescription().c_str())
299 ;
300 break;
301 case TypeEnumContainer::ListOfAtomsType:
302 OptionList->add_options()
303 (currentOption->getKeyAndShortForm().c_str(),
304// currentOption->hasDefaultValue() ?
305// po::value < std::vector<const atom *> >()->default_value(boost::lexical_cast< std::vector<const atom *> >(currentOption->getDefaultValue().c_str())) :
306 po::value < std::vector<int> >()->multitoken(),
307 currentOption->getDescription().c_str())
308 ;
309 break;
310 case TypeEnumContainer::ElementType:
311 OptionList->add_options()
312 (currentOption->getKeyAndShortForm().c_str(),
313// currentOption->hasDefaultValue() ?
314// po::value < const element * >()->default_value(boost::lexical_cast<const element *>(currentOption->getDefaultValue().c_str())) :
315 po::value < int >(),
316 currentOption->getDescription().c_str())
317 ;
318 break;
319 case TypeEnumContainer::ListOfElementsType:
320 OptionList->add_options()
321 (currentOption->getKeyAndShortForm().c_str(),
322// currentOption->hasDefaultValue() ?
323// po::value < std::vector<const element *> >()->default_value(boost::lexical_cast< std::vector<const element *> >(currentOption->getDefaultValue().c_str())) :
324 po::value < std::vector<int> >()->multitoken(),
325 currentOption->getDescription().c_str())
326 ;
327 break;
328 }
329}
330
331/** States whether there are command line arguments.
332 * \return true - there are none, false - there is at least one command line argument
333 */
334bool CommandLineParser::isEmpty()
335{
336 return vm.empty();
337}
338
339/** Sets the options.
340 * \param _argc arg count from main()
341 * \param **_argv argument array from main()
342 */
343void CommandLineParser::setOptions(int _argc, char **_argv)
344{
345 argc = _argc;
346 argv = _argv;
347 cmdline_options.add(analysis).add(atom).add(command).add(edit).add(fragmentation).add(molecule).add(parser).add(selection).add(tesselation).add(world).add(options);
348 config_file_options.add(options);
349 visible.add(analysis).add(atom).add(command).add(edit).add(fragmentation).add(molecule).add(parser).add(selection).add(tesselation).add(world).add(options);
350}
351
352/** Parses the command line arguments.
353 * Calls program_options::store() and program_options::notify()
354 */
355void CommandLineParser::Parse()
356{
357 po::store(po::command_line_parser(argc,argv).options(cmdline_options).run(), vm);
358 std::ifstream input;
359 input.open("example.cfg");
360 if (!input.fail())
361 po::store(po::parse_config_file(input, config_file_options), vm);
362 input.close();
363 po::notify(vm);
364}
365
366/** Scan the argument list for -a or --arguments and store their order for later use.
367 */
368void CommandLineParser::scanforSequenceOfArguments()
369{
370 std::map <std::string, std::string> ShortFormToActionMap = getShortFormToActionMap();
371 DoLog(0) && (Log() << Verbose(0) << "Scanning command line arguments and recognizing Actions." << std::endl);
372 // go through all arguments
373 for (int i=1;i<argc;i++) {
374 DoLog(2) && (Log() << Verbose(2) << "Checking on " << argv[i] << std::endl);
375 // check whether they
376 if (argv[i][0] == '-') { // .. begin with -
377 DoLog(2) && (Log() << Verbose(2) << "Possible argument: " << argv[i] << endl);
378 if (argv[i][1] == '-') { // .. or --
379 DoLog(1) && (Log() << Verbose(1) << "Putting " << argv[i] << " into the sequence." << endl);
380 SequenceOfActions.push_back(&(argv[i][2]));
381 // .. and check that next letter is not numeric, if so insert
382 } else if (((argv[i][1] < '0') || (argv[i][1] > '9')) && ((argv[i][1] != '.'))) {
383 std::map <std::string, std::string>::iterator iter = ShortFormToActionMap.find(&(argv[i][1]));
384 if (iter != ShortFormToActionMap.end()) {
385 DoLog(1) && (Log() << Verbose(1) << "Putting " << iter->second << " for " << iter->first << " into the sequence." << endl);
386 SequenceOfActions.push_back(iter->second);
387 }
388 }
389 }
390 }
391}
392
393/** Makes the Parser parse the command line options with current known options.
394 * \param _argc arg count from main()
395 * \param **_argv argument array from main()
396 */
397void CommandLineParser::Run(int _argc, char **_argv)
398{
399 setOptions(_argc,_argv);
400 Parse();
401 scanforSequenceOfArguments();
402}
403
404/** Go through all Actions and create a map from short form to their token.
405 * \return map from Action's ShortForm to token.
406 */
407std::map <std::string, std::string> CommandLineParser::getShortFormToActionMap() const
408{
409 std::map <std::string, std::string> result;
410
411 ActionRegistry &AR = ActionRegistry::getInstance();
412 for (ActionRegistry::const_iterator iter = AR.getBeginIter(); iter != AR.getEndIter(); ++iter)
413 if ((iter->second)->Traits.hasShortForm()) {
414 ASSERT(result.find((iter->second)->Traits.getShortForm()) == result.end(),
415 "Short form "+toString((iter->second)->Traits.getShortForm())+
416 " for action "+toString(iter->first)+" already present from "+
417 std::string(result[(iter->second)->Traits.getShortForm()])+"!");
418 result[(iter->second)->Traits.getShortForm()] = (iter->second)->getName();
419 }
420
421 return result;
422}
423
424CONSTRUCT_SINGLETON(CommandLineParser)
Note: See TracBrowser for help on using the repository browser.