source: src/Parser/FormatParserStorage.cpp@ d2596b

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 d2596b was 98c428, checked in by Frederik Heber <heber@…>, 13 years ago

FormatParserStorage has now two convenience functions ::load().

  • this way one doesn't have to find out the suffix anymore.
  • Property mode set to 100644
File size: 10.9 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-2012 University of Bonn. All rights reserved.
5 * Please see the LICENSE file or "Copyright notice" in builder.cpp for details.
6 */
7
8/** \file FormatParserStorage.cpp
9 *
10 * date: Jun, 22 2010
11 * author: heber
12 *
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 <iostream>
23#include <fstream>
24
25#include <boost/preprocessor/iteration/local.hpp>
26
27#include "CodePatterns/Assert.hpp"
28#include "CodePatterns/Log.hpp"
29
30#include "molecule.hpp"
31#include "FormatParserStorage.hpp"
32#include "ParserTypes.hpp"
33
34#include "MpqcParser.hpp"
35#include "PcpParser.hpp"
36#include "PdbParser.hpp"
37#include "Psi3Parser.hpp"
38#include "TremoloParser.hpp"
39#include "XyzParser.hpp"
40
41#include "CodePatterns/Singleton_impl.hpp"
42
43const std::string FormatParserStorage::unknownTypeString("unknown");
44
45/** Constructor of class FormatParserStorage.
46 */
47FormatParserStorage::FormatParserStorage()
48{
49 ParserList.resize(ParserTypes_end, NULL);
50 ParserStream.resize(ParserTypes_end, NULL);
51 ParserPresent.resize(ParserTypes_end, false);
52 ParserDesiredOutputFormat.resize(ParserTypes_end, false);
53
54#include "ParserTypes.def"
55
56#define insert_print(z,n,seq,map, before, after) \
57 map .insert( std::make_pair( \
58 BOOST_PP_SEQ_ELEM(n, seq) \
59 , before < \
60 BOOST_PP_SEQ_ELEM(n, seq) \
61 > after \
62 ) );
63
64#define insert_invert_print(z,n,seq,map, before, after) \
65 map .insert( std::make_pair( before < \
66 BOOST_PP_SEQ_ELEM(n, seq) \
67 > after, \
68 BOOST_PP_SEQ_ELEM(n, seq) \
69 ) );
70
71 // fill ParserNames
72#if defined ParserTypes_END // do we have parameters at all?
73#define BOOST_PP_LOCAL_MACRO(n) insert_print(~, n, PARSERSEQUENCE, ParserNames, FormatParserTrait, ::name)
74#define BOOST_PP_LOCAL_LIMITS (0, ParserTypes_END-1)
75#include BOOST_PP_LOCAL_ITERATE()
76#endif
77
78 // fill ParserLookupNames
79#if defined ParserTypes_END // do we have parameters at all?
80#define BOOST_PP_LOCAL_MACRO(n) insert_invert_print(~, n, PARSERSEQUENCE, ParserLookupNames, FormatParserTrait, ::name)
81#define BOOST_PP_LOCAL_LIMITS (0, ParserTypes_END-1)
82#include BOOST_PP_LOCAL_ITERATE()
83#endif
84
85 // fill ParserSuffixes
86#if defined ParserTypes_END // do we have parameters at all?
87#define BOOST_PP_LOCAL_MACRO(n) insert_print(~, n, PARSERSEQUENCE, ParserSuffixes, FormatParserTrait, ::suffix)
88#define BOOST_PP_LOCAL_LIMITS (0, ParserTypes_END-1)
89#include BOOST_PP_LOCAL_ITERATE()
90#endif
91
92 // fill ParserLookupSuffixes
93#if defined ParserTypes_END // do we have parameters at all?
94#define BOOST_PP_LOCAL_MACRO(n) insert_invert_print(~, n, PARSERSEQUENCE, ParserLookupSuffixes, FormatParserTrait, ::suffix)
95#define BOOST_PP_LOCAL_LIMITS (0, ParserTypes_END-1)
96#include BOOST_PP_LOCAL_ITERATE()
97#endif
98
99 // fill ParserAddFunction
100#if defined ParserTypes_END // do we have parameters at all?
101#define BOOST_PP_LOCAL_MACRO(n) insert_print(~, n, PARSERSEQUENCE, ParserAddFunction, &FormatParserStorage::addParser, )
102#define BOOST_PP_LOCAL_LIMITS (0, ParserTypes_END-1)
103#include BOOST_PP_LOCAL_ITERATE()
104#endif
105
106#undef insert_print
107#undef insert_invert_print
108#include "ParserTypes.undef"
109
110 //std::cout << "ParserNames:" << std::endl << ParserNames << std::endl;
111 //std::cout << "ParserSuffixes:" << std::endl << ParserSuffixes << std::endl;
112 //std::cout << "ParserLookupNames:" << std::endl << ParserLookupNames << std::endl;
113 //std::cout << "ParserLookupSuffixes:" << std::endl << ParserLookupSuffixes << std::endl;
114 //std::cout << "ParserAddFunction:" << std::endl << ParserAddFunction << std::endl;
115
116}
117
118/** Destructor of class FormatParserStorage.
119 * Free all stored FormatParsers.
120 * Save on Exit.
121 */
122FormatParserStorage::~FormatParserStorage()
123{
124 for (ParserTypes iter = ParserTypes_begin; iter < ParserTypes_end; ++iter)
125 if (ParserPresent[iter]) {
126 if (ParserStream[iter] != NULL) {
127 if (ParserStream[iter]->is_open())
128 ParserStream[iter]->close();
129 delete ParserStream[iter];
130 }
131 delete ParserList[iter];
132 }
133}
134
135/** Sets the filename of all current parsers in storage to prefix.suffix.
136 * \param &prefix prefix to use.
137 */
138void FormatParserStorage::SetOutputPrefixForAll(std::string &_prefix)
139{
140 prefix=_prefix;
141};
142
143/** Sets \a type as a format to be stored on call of SaveAll.
144 *
145 * @param type type to add to desired output formats
146 */
147void FormatParserStorage::setOutputFormat(ParserTypes type)
148{
149 LOG(0, "STATUS: Adding " << ParserNames[type] << " type to output.");
150 ParserDesiredOutputFormat[type] = true;
151}
152
153/** Sets \a type as a format to be stored on call of SaveAll.
154 *
155 * @param type type to add to desired output formats
156 */
157void FormatParserStorage::setOutputFormat(std::string type)
158{
159 std::map<std::string, ParserTypes>::const_iterator iter = ParserLookupNames.find(type);
160 ASSERT(iter != ParserLookupNames.end(),
161 "FormatParserStorage::setOutputFormat() - output format "+type+" is unknown.");
162 setOutputFormat(iter->second);
163}
164
165/** Saves the world in the desired output formats.
166 *
167 */
168void FormatParserStorage::SaveAll()
169{
170 std::string filename;
171 for (ParserTypes iter = ParserTypes_begin; iter < ParserTypes_end; ++iter)
172 if (ParserPresent[iter] && ParserDesiredOutputFormat[iter]) {
173 filename = prefix;
174 filename += ".";
175 filename += ParserSuffixes[iter];
176 ParserStream[iter] = new std::ofstream(filename.c_str());
177 ParserList[iter]->setOstream((std::ostream *)ParserStream[iter]);
178 }
179}
180
181
182ParserTypes FormatParserStorage::getTypeFromName(std::string type)
183{
184 if (ParserLookupNames.find(type) == ParserLookupNames.end()) {
185 ELOG(1, "Unknown type " << type << ".");
186 return ParserTypes_end;
187 } else
188 return ParserLookupNames[type];
189}
190
191ParserTypes FormatParserStorage::getTypeFromSuffix(std::string type)
192{
193 if (ParserLookupSuffixes.find(type) == ParserLookupSuffixes.end()) {
194 ELOG(1, "Unknown type " << type << ".");
195 return ParserTypes_end;
196 } else
197 return ParserLookupSuffixes[type];
198}
199
200const std::string &FormatParserStorage::getNameFromType(ParserTypes type)
201{
202 if (ParserNames.find(type) == ParserNames.end()) {
203 ELOG(1, "Unknown type " << type << ".");
204 return unknownTypeString;
205 } else
206 return ParserNames[type];
207}
208
209const std::string &FormatParserStorage::getSuffixFromType(ParserTypes type)
210{
211 if (ParserSuffixes.find(type) == ParserSuffixes.end()) {
212 ELOG(1, "Unknown type " << type << ".");
213 return unknownTypeString;
214 } else
215 return ParserSuffixes[type];
216}
217
218bool FormatParserStorage::add(ParserTypes ptype)
219{
220 if (ptype != ParserTypes_end) {
221 if (ParserAddFunction.find(ptype) != ParserAddFunction.end()) {
222 (getInstance().*(ParserAddFunction[ptype]))(); // we still need an object to work on ...
223 return true;
224 } else {
225 ELOG(1, "No parser to add for this known type " << ParserNames[ptype] << ", not implemented?");
226 return false;
227 }
228 } else {
229 return false;
230 }
231}
232
233bool FormatParserStorage::add(std::string type)
234{
235 enum ParserTypes Ptype = getTypeFromName(type);
236 return add(Ptype);
237}
238
239/** Recognizes type of file and parse via FormatParserStorage::load().
240 * \param filename path and filename
241 * \return true - parsing ok, false - suffix unknown
242 */
243bool FormatParserStorage::load(boost::filesystem::path filename)
244{
245 return load(filename.string());
246}
247
248/** Recognizes type of file and parse via FormatParserStorage::load().
249 * \param filename path and filename
250 * \return true - parsing ok, false - suffix unknown
251 */
252bool FormatParserStorage::load(std::string &filename)
253{
254 std::string FilenameSuffix = filename.substr(filename.find_last_of('.')+1, filename.length());
255 ifstream input;
256 LOG(0, "STATUS: Loading filler molecule " << filename
257 << " of suffix " << FilenameSuffix << ".");
258 input.open(filename.c_str());
259 const bool status = load(input, FilenameSuffix);
260 input.close();
261
262 return status;
263}
264
265/** Parses an istream depending on its suffix
266 * \param &input input stream
267 * \param suffix
268 * \return true - parsing ok, false - suffix unknown
269 */
270bool FormatParserStorage::load(std::istream &input, std::string &suffix)
271{
272 enum ParserTypes type = getTypeFromSuffix(suffix);
273 if (type != ParserTypes_end)
274 get(type).load(&input);
275 else
276 return false;
277 return true;
278}
279
280/** Stores all selected atoms in an ostream depending on its suffix
281 * \param &output output stream
282 * \param suffix
283 * \return true - storing ok, false - suffix unknown
284 */
285bool FormatParserStorage::saveSelectedAtoms(std::ostream &output, std::string suffix)
286{
287 std::vector<atom *> atoms = World::getInstance().getSelectedAtoms();
288 return save(output, suffix, atoms);
289}
290
291/** Stores all selected atoms in an ostream depending on its suffix
292 * We store in the order of the atomic ids, not in the order they appear in the molecules.
293 * Hence, we first create a vector from all selected molecules' atoms.
294 *
295 * TODO: Change here atom * to const atom * when FormatParserStorage::save() uses vector<const atom *>
296 *
297 * \param &output output stream
298 * \param suffix
299 * \return true - storing ok, false - suffix unknown
300 */
301bool FormatParserStorage::saveSelectedMolecules(std::ostream &output, std::string suffix)
302{
303 std::vector<molecule *> molecules = World::getInstance().getSelectedMolecules();
304 std::map<size_t, atom *> IdAtoms;
305 for (std::vector<molecule *>::const_iterator MolIter = molecules.begin();
306 MolIter != molecules.end();
307 ++MolIter) {
308 for(molecule::iterator AtomIter = (*MolIter)->begin();
309 AtomIter != (*MolIter)->end();
310 ++AtomIter) {
311 IdAtoms.insert( make_pair((*AtomIter)->getId(), (*AtomIter)) );
312 }
313 }
314 std::vector<atom *> atoms;
315 atoms.reserve(IdAtoms.size());
316 for (std::map<size_t, atom *>::const_iterator iter = IdAtoms.begin();
317 iter != IdAtoms.end();
318 ++iter) {
319 atoms.push_back(iter->second);
320 }
321 return save(output, suffix, atoms);
322}
323
324/** Stores world in an ostream depending on its suffix
325 * \param &output output stream
326 * \param suffix
327 * \return true - storing ok, false - suffix unknown
328 */
329bool FormatParserStorage::saveWorld(std::ostream &output, std::string suffix)
330{
331 std::vector<atom *> atoms = World::getInstance().getAllAtoms();
332 return save(output, suffix, atoms);
333}
334
335/** Stores a given vector of \a atoms in an ostream depending on its suffix
336 * \param &output output stream
337 * \param suffix
338 * \return true - storing ok, false - suffix unknown
339 */
340bool FormatParserStorage::save(std::ostream &output, std::string suffix, const std::vector<atom *> &atoms)
341{
342 enum ParserTypes type = getTypeFromSuffix(suffix);
343 if (type != ParserTypes_end)
344 get(type).save(&output, atoms);
345 else
346 return false;
347 return true;
348}
349
350/** Returns reference to the desired output parser as FormatParser, adds if not present.
351 * \param _type type of desired parser
352 * \return reference to the output FormatParser with desired type
353 */
354FormatParserInterface &FormatParserStorage::get(ParserTypes _type)
355{
356 if (!ParserPresent[_type]) {
357 add(_type);
358 }
359 return *ParserList[_type];
360}
361
362CONSTRUCT_SINGLETON(FormatParserStorage)
Note: See TracBrowser for help on using the repository browser.