source: src/Actions/ValueStorage.hpp@ 4217e7

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 4217e7 was 336e33, checked in by Frederik Heber <heber@…>, 14 years ago

Removed MissingValueException from Exceptions.

  • Property mode set to 100644
File size: 8.1 KB
Line 
1/*
2 * ValueStorage.hpp
3 *
4 * Created on: Jul 22, 2010
5 * Author: heber
6 */
7
8#ifndef VALUESTORAGE_HPP_
9#define VALUESTORAGE_HPP_
10
11// include config.h
12#ifdef HAVE_CONFIG_H
13#include <config.h>
14#endif
15
16
17#include <boost/filesystem.hpp>
18#include <boost/lexical_cast.hpp>
19#include <boost/program_options.hpp>
20
21#include <map>
22#include <set>
23#include <vector>
24#include <typeinfo>
25#include <utility>
26
27#include "Actions/OptionTrait.hpp"
28#include "Actions/OptionRegistry.hpp"
29#include "CodePatterns/Assert.hpp"
30#include "CodePatterns/Singleton.hpp"
31
32#include <exception>
33#include <boost/exception.hpp>
34
35class MatrixContent;
36class Vector;
37
38/** Base type for all exceptions regarding ValueStorage class.
39 *
40 */
41struct ValueStorageException : virtual std::exception, virtual boost::exception { };
42
43/** ========================== General error information ================== */
44
45/** Exception information for ValueStorageException: name of option.
46 */
47typedef boost::error_info<struct tag_ValueStorageOptionName, const char *> ValueStorageOptionName;
48
49/** Exception information for ValueStorageException: name of type.
50 */
51typedef boost::error_info<struct tag_ValueStorageTypeName, const char *> ValueStorageTypeName;
52
53/** Exception information for ValueStorageException: pair of names of two types.
54 */
55typedef boost::error_info<
56 struct tag_ValueStorageTypeName,
57 std::pair<const char *,const char *> > ValueStoragePairTypeName;
58
59/** ============================ Specific exceptions ====================== */
60
61/** Exception thrown when ValueStorage is given an illegal type for a specific option.
62 */
63struct IllegalTypeException : virtual ValueStorageException { };
64
65/** Exception thrown when ValueStorage is missing a requested value.
66 */
67struct MissingValueException : virtual ValueStorageException { };
68
69
70class MapOfActionsTest;
71
72class Box;
73class atom;
74class element;
75class molecule;
76class Vector;
77class RandomNumberDistribution_Parameters;
78
79namespace po = boost::program_options;
80
81using boost::lexical_cast;
82
83#include "CodePatterns/Singleton.hpp"
84
85/** ValueStorage serves as a mediator to MapOfActions.
86 * This is needed to relax inter-dependencies between the Queries and the Actions.
87 * I.e. this is the interface implemented in MapOfActions which both can safely rely on
88 * to store&retrieve/exchange values.
89 *
90 * \section <ValueStorage> (ValueStorage howto)
91 *
92 * If you ever need to add a particular class to the ValueStorage, do as follows:
93 * -# add a specialized queryCurrentValue and setCurrentValue to the definition
94 * of ValueStorage.
95 * -# implement both in the declaration of ValueStorage.
96 * -# in the implementation either directly implement the serializing of the
97 * class' members to a stringstream or use an already implemented operator<<
98 * or operator<<, respectively.
99 *
100 */
101class ValueStorage : public Singleton<ValueStorage> {
102 friend class Singleton<ValueStorage>;
103
104public:
105
106 bool isCurrentValuePresent(const char *name) const;
107 void queryCurrentValue(const char * name, const atom * &_T);
108 void queryCurrentValue(const char * name, const element * &_T);
109 void queryCurrentValue(const char * name, const molecule * &_T);
110 void queryCurrentValue(const char * name, class Box &_T);
111 void queryCurrentValue(const char * name, class Vector &_T);
112 void queryCurrentValue(const char * name, class BoxVector &_T);
113 void queryCurrentValue(const char * name, class RandomNumberDistribution_Parameters &_T);
114 void queryCurrentValue(const char * name, std::vector<const atom *>&_T);
115 void queryCurrentValue(const char * name, std::vector<const element *>&_T);
116 void queryCurrentValue(const char * name, std::vector<const molecule *>&_T);
117 void queryCurrentValue(const char * name, boost::filesystem::path&_T);
118
119 /** Gets a value from the storage
120 * If the value is not present, an ASSERT is thrown unless optional is set to true.
121 * \param _T key of value
122 * \param optional whether this value is optional, i.e. may actually not be in the storage (i.e. may return false in this case).
123 * \return true - value present, false - value not present (only given when optional set to true)
124 */
125 template<typename T> void queryCurrentValue(const char * name, T &_T)
126 {
127 if (typeid( T ) == *(OptionRegistry_instance.getOptionByName(name)->getType())) { // constructor of type_info is private, hence can only store by ref or ptr
128 if (CurrentValueMap.find(name) == CurrentValueMap.end())
129 throw MissingValueException() << ValueStorageOptionName(name);
130 _T = lexical_cast<T>(CurrentValueMap[name].c_str());
131 CurrentValueMap.erase(name);
132 } else
133 throw IllegalTypeException() << ValueStorageOptionName(name)
134 << ValueStoragePairTypeName(std::make_pair(
135 typeid(_T).name(),
136 OptionRegistry_instance.getOptionByName(name)->getTypeName().c_str())
137 );
138 }
139 template<typename T> void queryCurrentValue(const char * name, std::vector<T> &_T)
140 {
141 T temp;
142 if (typeid( std::vector<T> ) == *(OptionRegistry_instance.getOptionByName(name)->getType())) { // constructor of type_info is private, hence can only store by ref or ptr
143 if (CurrentValueMap.find(name) == CurrentValueMap.end())
144 throw MissingValueException() << ValueStorageOptionName(name);
145 std::istringstream stream(CurrentValueMap[name]);
146 CurrentValueMap.erase(name);
147 while (!stream.fail()) {
148 stream >> temp >> std::ws;
149 if (!stream.fail()) {
150 _T.push_back(temp);
151 }
152 }
153 } else
154 throw IllegalTypeException() << ValueStorageOptionName(name)
155 << ValueStoragePairTypeName(std::make_pair(
156 typeid(_T).name(),
157 OptionRegistry_instance.getOptionByName(name)->getTypeName().c_str())
158 );
159 }
160
161 void setCurrentValue(const char * name, const atom * &_T);
162 void setCurrentValue(const char * name, const element * &_T);
163 void setCurrentValue(const char * name, const molecule * &_T);
164 void setCurrentValue(const char * name, class Box &_T);
165 void setCurrentValue(const char * name, class Vector &_T);
166 void setCurrentValue(const char * name, class RandomNumberDistribution_Parameters &_T);
167 void setCurrentValue(const char * name, std::vector<const atom *>&_T);
168 void setCurrentValue(const char * name, std::vector<const element *>&_T);
169 void setCurrentValue(const char * name, std::vector<const molecule *>&_T);
170 void setCurrentValue(const char * name, boost::filesystem::path&_T);
171
172 /** Sets a value in the storage.
173 * \param name key of value
174 * \param _T value
175 */
176 template<class T> void setCurrentValue(const char * name, T &_T)
177 {
178 std::ostringstream stream;
179 if (typeid( T ) == *(OptionRegistry_instance.getOptionByName(name)->getType())) { // constructor of type_info is private, hence can only store by ref or ptr
180 stream << _T;
181 CurrentValueMap[name] = stream.str();
182 } else
183 throw IllegalTypeException() << ValueStorageOptionName(name)
184 << ValueStoragePairTypeName(std::make_pair(
185 typeid(_T).name(),
186 OptionRegistry_instance.getOptionByName(name)->getTypeName().c_str())
187 );
188}
189 /** Sets a value in the storage.
190 * \param name key of value
191 * \param _T value
192 */
193 template<class T> void setCurrentValue(const char * name, std::vector<T> &_T)
194 {
195 std::ostringstream stream;
196 if (typeid( std::vector<T> ) == *(OptionRegistry_instance.getOptionByName(name)->getType())) { // constructor of type_info is private, hence can only store by ref or ptr
197 std::ostringstream stream;
198 for (typename std::vector<T>::const_iterator iter = _T.begin(); iter != _T.end(); ++iter) {
199 stream << (*iter) << " ";
200 }
201 CurrentValueMap[name] = stream.str();
202 } else
203 throw IllegalTypeException() << ValueStorageOptionName(name)
204 << ValueStoragePairTypeName(std::make_pair(
205 typeid(_T).name(),
206 OptionRegistry_instance.getOptionByName(name)->getTypeName().c_str())
207 );
208 }
209
210 const std::string getCurrentValue(std::string actionname);
211
212protected:
213 ValueStorage();
214 ~ValueStorage();
215
216 std::map<std::string, std::string> CurrentValueMap;
217
218 OptionRegistry &OptionRegistry_instance;
219};
220
221#endif /* VALUESTORAGE_HPP_ */
Note: See TracBrowser for help on using the repository browser.