source: src/config.cpp@ 50e4e5

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 50e4e5 was 42127c, checked in by Frederik Heber <heber@…>, 13 years ago

Extracted definition of MoleculeListClass and put into own header module.

  • Property mode set to 100644
File size: 72.9 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/** \file config.cpp
9 *
10 * Function implementations for the class config.
11 *
12 */
13
14// include config.h
15#ifdef HAVE_CONFIG_H
16#include <config.h>
17#endif
18
19#include "CodePatterns/MemDebug.hpp"
20
21#include <stdio.h>
22#include <cstring>
23#include <iostream>
24#include <boost/tokenizer.hpp>
25#include <string>
26
27#include "atom.hpp"
28#include "Bond/bond.hpp"
29#include "Box.hpp"
30#include "CodePatterns/Info.hpp"
31#include "CodePatterns/Log.hpp"
32#include "CodePatterns/toString.hpp"
33#include "CodePatterns/Verbose.hpp"
34#include "config.hpp"
35#include "ConfigFileBuffer.hpp"
36#include "Element/element.hpp"
37#include "Element/periodentafel.hpp"
38#include "Graph/BondGraph.hpp"
39#include "Helpers/helpers.hpp"
40#include "LinearAlgebra/RealSpaceMatrix.hpp"
41#include "molecule.hpp"
42#include "MoleculeListClass.hpp"
43#include "ThermoStatContainer.hpp"
44#include "World.hpp"
45
46/************************************* Functions for class config ***************************/
47
48/** Constructor for config file class.
49 */
50config::config() :
51 PsiType(0),
52 MaxPsiDouble(0),
53 PsiMaxNoUp(0),
54 PsiMaxNoDown(0),
55 MaxMinStopStep(1),
56 InitMaxMinStopStep(1),
57 ProcPEGamma(8),
58 ProcPEPsi(1),
59 configname(NULL),
60 FastParsing(false),
61 Deltat(0.01),
62 databasepath(NULL),
63 DoConstrainedMD(0),
64 MaxOuterStep(0),
65 mainname(NULL),
66 defaultpath(NULL),
67 pseudopotpath(NULL),
68 DoOutVis(0),
69 DoOutMes(1),
70 DoOutNICS(0),
71 DoOutOrbitals(0),
72 DoOutCurrent(0),
73 DoFullCurrent(0),
74 DoPerturbation(0),
75 DoWannier(0),
76 CommonWannier(0),
77 SawtoothStart(0.01),
78 VectorPlane(0),
79 VectorCut(0.),
80 UseAddGramSch(1),
81 Seed(1),
82 OutVisStep(10),
83 OutSrcStep(5),
84 MaxPsiStep(0),
85 EpsWannier(1e-7),
86 MaxMinStep(100),
87 RelEpsTotalEnergy(1e-7),
88 RelEpsKineticEnergy(1e-5),
89 MaxMinGapStopStep(0),
90 MaxInitMinStep(100),
91 InitRelEpsTotalEnergy(1e-5),
92 InitRelEpsKineticEnergy(1e-4),
93 InitMaxMinGapStopStep(0),
94 ECut(128.),
95 MaxLevel(5),
96 RiemannTensor(0),
97 LevRFactor(0),
98 RiemannLevel(0),
99 Lev0Factor(2),
100 RTActualUse(0),
101 AddPsis(0),
102 RCut(20.),
103 StructOpt(0),
104 IsAngstroem(1),
105 RelativeCoord(0),
106 MaxTypes(0)
107{
108 mainname = new char[MAXSTRINGSIZE];
109 defaultpath = new char[MAXSTRINGSIZE];
110 pseudopotpath = new char[MAXSTRINGSIZE];
111 databasepath = new char[MAXSTRINGSIZE];
112 configname = new char[MAXSTRINGSIZE];
113 strcpy(mainname,"pcp");
114 strcpy(defaultpath,"not specified");
115 strcpy(pseudopotpath,"not specified");
116 configname[0]='\0';
117};
118
119/** Destructor for config file class.
120 */
121config::~config()
122{
123 delete[](mainname);
124 delete[](defaultpath);
125 delete[](pseudopotpath);
126 delete[](databasepath);
127 delete[](configname);
128};
129
130/** Displays menu for editing each entry of the config file.
131 * Nothing fancy here, just lots of Log() << Verbose(0)s for the menu and a switch/case
132 * for each entry of the config file structure.
133 */
134void config::Edit()
135{
136 char choice;
137
138 do {
139 DoLog(0) && (Log() << Verbose(0) << "===========EDIT CONFIGURATION============================" << endl);
140 DoLog(0) && (Log() << Verbose(0) << " A - mainname (prefix for all runtime files)" << endl);
141 DoLog(0) && (Log() << Verbose(0) << " B - Default path (for runtime files)" << endl);
142 DoLog(0) && (Log() << Verbose(0) << " C - Path of pseudopotential files" << endl);
143 DoLog(0) && (Log() << Verbose(0) << " D - Number of coefficient sharing processes" << endl);
144 DoLog(0) && (Log() << Verbose(0) << " E - Number of wave function sharing processes" << endl);
145 DoLog(0) && (Log() << Verbose(0) << " F - 0: Don't output density for OpenDX, 1: do" << endl);
146 DoLog(0) && (Log() << Verbose(0) << " G - 0: Don't output physical data, 1: do" << endl);
147 DoLog(0) && (Log() << Verbose(0) << " H - 0: Don't output densities of each unperturbed orbital for OpenDX, 1: do" << endl);
148 DoLog(0) && (Log() << Verbose(0) << " I - 0: Don't output current density for OpenDX, 1: do" << endl);
149 DoLog(0) && (Log() << Verbose(0) << " J - 0: Don't do the full current calculation, 1: do" << endl);
150 DoLog(0) && (Log() << Verbose(0) << " K - 0: Don't do perturbation calculation to obtain susceptibility and shielding, 1: do" << endl);
151 DoLog(0) && (Log() << Verbose(0) << " L - 0: Wannier centres as calculated, 1: common centre for all, 2: unite centres according to spread, 3: cell centre, 4: shifted to nearest grid point" << endl);
152 DoLog(0) && (Log() << Verbose(0) << " M - Absolute begin of unphysical sawtooth transfer for position operator within cell" << endl);
153 DoLog(0) && (Log() << Verbose(0) << " N - (0,1,2) x,y,z-plane to do two-dimensional current vector cut" << endl);
154 DoLog(0) && (Log() << Verbose(0) << " O - Absolute position along vector cut axis for cut plane" << endl);
155 DoLog(0) && (Log() << Verbose(0) << " P - Additional Gram-Schmidt-Orthonormalization to stabilize numerics" << endl);
156 DoLog(0) && (Log() << Verbose(0) << " Q - Initial integer value of random number generator" << endl);
157 DoLog(0) && (Log() << Verbose(0) << " R - for perturbation 0, for structure optimization defines upper limit of iterations" << endl);
158 DoLog(0) && (Log() << Verbose(0) << " T - Output visual after ...th step" << endl);
159 DoLog(0) && (Log() << Verbose(0) << " U - Output source densities of wave functions after ...th step" << endl);
160 DoLog(0) && (Log() << Verbose(0) << " X - minimization iterations per wave function, if unsure leave at default value 0" << endl);
161 DoLog(0) && (Log() << Verbose(0) << " Y - tolerance value for total spread in iterative Jacobi diagonalization" << endl);
162 DoLog(0) && (Log() << Verbose(0) << " Z - Maximum number of minimization iterations" << endl);
163 DoLog(0) && (Log() << Verbose(0) << " a - Relative change in total energy to stop min. iteration" << endl);
164 DoLog(0) && (Log() << Verbose(0) << " b - Relative change in kinetic energy to stop min. iteration" << endl);
165 DoLog(0) && (Log() << Verbose(0) << " c - Check stop conditions every ..th step during min. iteration" << endl);
166 DoLog(0) && (Log() << Verbose(0) << " e - Maximum number of minimization iterations during initial level" << endl);
167 DoLog(0) && (Log() << Verbose(0) << " f - Relative change in total energy to stop min. iteration during initial level" << endl);
168 DoLog(0) && (Log() << Verbose(0) << " g - Relative change in kinetic energy to stop min. iteration during initial level" << endl);
169 DoLog(0) && (Log() << Verbose(0) << " h - Check stop conditions every ..th step during min. iteration during initial level" << endl);
170// Log() << Verbose(0) << " j - six lower diagonal entries of matrix, defining the unit cell" << endl;
171 DoLog(0) && (Log() << Verbose(0) << " k - Energy cutoff of plane wave basis in Hartree" << endl);
172 DoLog(0) && (Log() << Verbose(0) << " l - Maximum number of levels in multi-level-ansatz" << endl);
173 DoLog(0) && (Log() << Verbose(0) << " m - Factor by which grid nodes increase between standard and upper level" << endl);
174 DoLog(0) && (Log() << Verbose(0) << " n - 0: Don't use RiemannTensor, 1: Do" << endl);
175 DoLog(0) && (Log() << Verbose(0) << " o - Factor by which grid nodes increase between Riemann and standard(?) level" << endl);
176 DoLog(0) && (Log() << Verbose(0) << " p - Number of Riemann levels" << endl);
177 DoLog(0) && (Log() << Verbose(0) << " r - 0: Don't Use RiemannTensor, 1: Do" << endl);
178 DoLog(0) && (Log() << Verbose(0) << " s - 0: Doubly occupied orbitals, 1: Up-/Down-Orbitals" << endl);
179 DoLog(0) && (Log() << Verbose(0) << " t - Number of orbitals (depends pn SpinType)" << endl);
180 DoLog(0) && (Log() << Verbose(0) << " u - Number of SpinUp orbitals (depends on SpinType)" << endl);
181 DoLog(0) && (Log() << Verbose(0) << " v - Number of SpinDown orbitals (depends on SpinType)" << endl);
182 DoLog(0) && (Log() << Verbose(0) << " w - Number of additional, unoccupied orbitals" << endl);
183 DoLog(0) && (Log() << Verbose(0) << " x - radial cutoff for ewald summation in Bohrradii" << endl);
184 DoLog(0) && (Log() << Verbose(0) << " y - 0: Don't do structure optimization beforehand, 1: Do" << endl);
185 DoLog(0) && (Log() << Verbose(0) << " z - 0: Units are in Bohr radii, 1: units are in Aengstrom" << endl);
186 DoLog(0) && (Log() << Verbose(0) << " i - 0: Coordinates given in file are absolute, 1: ... are relative to unit cell" << endl);
187 DoLog(0) && (Log() << Verbose(0) << "=========================================================" << endl);
188 DoLog(0) && (Log() << Verbose(0) << "INPUT: ");
189 cin >> choice;
190
191 switch (choice) {
192 case 'A': // mainname
193 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::mainname << "\t new: ");
194 cin >> config::mainname;
195 break;
196 case 'B': // defaultpath
197 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::defaultpath << "\t new: ");
198 cin >> config::defaultpath;
199 break;
200 case 'C': // pseudopotpath
201 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::pseudopotpath << "\t new: ");
202 cin >> config::pseudopotpath;
203 break;
204
205 case 'D': // ProcPEGamma
206 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::ProcPEGamma << "\t new: ");
207 cin >> config::ProcPEGamma;
208 break;
209 case 'E': // ProcPEPsi
210 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::ProcPEPsi << "\t new: ");
211 cin >> config::ProcPEPsi;
212 break;
213 case 'F': // DoOutVis
214 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::DoOutVis << "\t new: ");
215 cin >> config::DoOutVis;
216 break;
217 case 'G': // DoOutMes
218 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::DoOutMes << "\t new: ");
219 cin >> config::DoOutMes;
220 break;
221 case 'H': // DoOutOrbitals
222 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::DoOutOrbitals << "\t new: ");
223 cin >> config::DoOutOrbitals;
224 break;
225 case 'I': // DoOutCurrent
226 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::DoOutCurrent << "\t new: ");
227 cin >> config::DoOutCurrent;
228 break;
229 case 'J': // DoFullCurrent
230 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::DoFullCurrent << "\t new: ");
231 cin >> config::DoFullCurrent;
232 break;
233 case 'K': // DoPerturbation
234 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::DoPerturbation << "\t new: ");
235 cin >> config::DoPerturbation;
236 break;
237 case 'L': // CommonWannier
238 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::CommonWannier << "\t new: ");
239 cin >> config::CommonWannier;
240 break;
241 case 'M': // SawtoothStart
242 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::SawtoothStart << "\t new: ");
243 cin >> config::SawtoothStart;
244 break;
245 case 'N': // VectorPlane
246 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::VectorPlane << "\t new: ");
247 cin >> config::VectorPlane;
248 break;
249 case 'O': // VectorCut
250 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::VectorCut << "\t new: ");
251 cin >> config::VectorCut;
252 break;
253 case 'P': // UseAddGramSch
254 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::UseAddGramSch << "\t new: ");
255 cin >> config::UseAddGramSch;
256 break;
257 case 'Q': // Seed
258 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::Seed << "\t new: ");
259 cin >> config::Seed;
260 break;
261
262 case 'R': // MaxOuterStep
263 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::MaxOuterStep << "\t new: ");
264 cin >> config::MaxOuterStep;
265 break;
266 case 'T': // OutVisStep
267 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::OutVisStep << "\t new: ");
268 cin >> config::OutVisStep;
269 break;
270 case 'U': // OutSrcStep
271 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::OutSrcStep << "\t new: ");
272 cin >> config::OutSrcStep;
273 break;
274 case 'X': // MaxPsiStep
275 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::MaxPsiStep << "\t new: ");
276 cin >> config::MaxPsiStep;
277 break;
278 case 'Y': // EpsWannier
279 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::EpsWannier << "\t new: ");
280 cin >> config::EpsWannier;
281 break;
282
283 case 'Z': // MaxMinStep
284 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::MaxMinStep << "\t new: ");
285 cin >> config::MaxMinStep;
286 break;
287 case 'a': // RelEpsTotalEnergy
288 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::RelEpsTotalEnergy << "\t new: ");
289 cin >> config::RelEpsTotalEnergy;
290 break;
291 case 'b': // RelEpsKineticEnergy
292 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::RelEpsKineticEnergy << "\t new: ");
293 cin >> config::RelEpsKineticEnergy;
294 break;
295 case 'c': // MaxMinStopStep
296 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::MaxMinStopStep << "\t new: ");
297 cin >> config::MaxMinStopStep;
298 break;
299 case 'e': // MaxInitMinStep
300 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::MaxInitMinStep << "\t new: ");
301 cin >> config::MaxInitMinStep;
302 break;
303 case 'f': // InitRelEpsTotalEnergy
304 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::InitRelEpsTotalEnergy << "\t new: ");
305 cin >> config::InitRelEpsTotalEnergy;
306 break;
307 case 'g': // InitRelEpsKineticEnergy
308 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::InitRelEpsKineticEnergy << "\t new: ");
309 cin >> config::InitRelEpsKineticEnergy;
310 break;
311 case 'h': // InitMaxMinStopStep
312 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::InitMaxMinStopStep << "\t new: ");
313 cin >> config::InitMaxMinStopStep;
314 break;
315
316// case 'j': // BoxLength
317// Log() << Verbose(0) << "enter lower triadiagonalo form of basis matrix" << endl << endl;
318// double * const cell_size = World::getInstance().getDomain();
319// for (int i=0;i<6;i++) {
320// Log() << Verbose(0) << "Cell size" << i << ": ";
321// cin >> cell_size[i];
322// }
323// break;
324
325 case 'k': // ECut
326 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::ECut << "\t new: ");
327 cin >> config::ECut;
328 break;
329 case 'l': // MaxLevel
330 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::MaxLevel << "\t new: ");
331 cin >> config::MaxLevel;
332 break;
333 case 'm': // RiemannTensor
334 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::RiemannTensor << "\t new: ");
335 cin >> config::RiemannTensor;
336 break;
337 case 'n': // LevRFactor
338 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::LevRFactor << "\t new: ");
339 cin >> config::LevRFactor;
340 break;
341 case 'o': // RiemannLevel
342 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::RiemannLevel << "\t new: ");
343 cin >> config::RiemannLevel;
344 break;
345 case 'p': // Lev0Factor
346 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::Lev0Factor << "\t new: ");
347 cin >> config::Lev0Factor;
348 break;
349 case 'r': // RTActualUse
350 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::RTActualUse << "\t new: ");
351 cin >> config::RTActualUse;
352 break;
353 case 's': // PsiType
354 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::PsiType << "\t new: ");
355 cin >> config::PsiType;
356 break;
357 case 't': // MaxPsiDouble
358 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::MaxPsiDouble << "\t new: ");
359 cin >> config::MaxPsiDouble;
360 break;
361 case 'u': // PsiMaxNoUp
362 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::PsiMaxNoUp << "\t new: ");
363 cin >> config::PsiMaxNoUp;
364 break;
365 case 'v': // PsiMaxNoDown
366 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::PsiMaxNoDown << "\t new: ");
367 cin >> config::PsiMaxNoDown;
368 break;
369 case 'w': // AddPsis
370 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::AddPsis << "\t new: ");
371 cin >> config::AddPsis;
372 break;
373
374 case 'x': // RCut
375 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::RCut << "\t new: ");
376 cin >> config::RCut;
377 break;
378 case 'y': // StructOpt
379 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::StructOpt << "\t new: ");
380 cin >> config::StructOpt;
381 break;
382 case 'z': // IsAngstroem
383 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::IsAngstroem << "\t new: ");
384 cin >> config::IsAngstroem;
385 break;
386 case 'i': // RelativeCoord
387 DoLog(0) && (Log() << Verbose(0) << "Old: " << config::RelativeCoord << "\t new: ");
388 cin >> config::RelativeCoord;
389 break;
390 };
391 } while (choice != 'q');
392};
393
394/** Tests whether a given configuration file adhears to old or new syntax.
395 * \param *filename filename of config file to be tested
396 * \param *periode pointer to a periodentafel class with all elements
397 * \return 0 - old syntax, 1 - new syntax, -1 - unknown syntax
398 */
399int config::TestSyntax(const char * const filename, const periodentafel * const periode) const
400{
401 int test;
402 ifstream file(filename);
403
404 // search file for keyword: ProcPEGamma (new syntax)
405 if (ParseForParameter(1,&file,"ProcPEGamma", 0, 1, 1, int_type, &test, 1, optional)) {
406 file.close();
407 return 1;
408 }
409 // search file for keyword: ProcsGammaPsi (old syntax)
410 if (ParseForParameter(1,&file,"ProcsGammaPsi", 0, 1, 1, int_type, &test, 1, optional)) {
411 file.close();
412 return 0;
413 }
414 file.close();
415 return -1;
416}
417
418/** Returns private config::IsAngstroem.
419 * \return IsAngstroem
420 */
421bool config::GetIsAngstroem() const
422{
423 return (IsAngstroem == 1);
424};
425
426/** Returns private config::*defaultpath.
427 * \return *defaultpath
428 */
429char * config::GetDefaultPath() const
430{
431 return defaultpath;
432};
433
434
435/** Returns private config::*defaultpath.
436 * \return *defaultpath
437 */
438void config::SetDefaultPath(const char * const path)
439{
440 strcpy(defaultpath, path);
441};
442
443/** Loads a molecule from a ConfigFileBuffer.
444 * \param *mol molecule to load
445 * \param *FileBuffer ConfigFileBuffer to use
446 * \param *periode periodentafel for finding elements
447 * \param FastParsing whether to parse trajectories or not
448 */
449void LoadMolecule(molecule * const &mol, struct ConfigFileBuffer * const &FileBuffer, const periodentafel * const periode, const bool FastParsing)
450{
451 int MaxTypes = 0;
452 const element *elementhash[MAX_ELEMENTS];
453 char name[MAXSTRINGSIZE];
454 int Z = -1;
455 int No[MAX_ELEMENTS];
456 int verbose = DoLog(4);
457 double value[3];
458
459 if (mol == NULL) {
460 ELOG(0, "Molecule is not allocated in LoadMolecule(), exit.");
461 performCriticalExit();
462 }
463
464 ParseForParameter(verbose,FileBuffer,"MaxTypes", 0, 1, 1, int_type, &(MaxTypes), 1, critical);
465 if (MaxTypes == 0) {
466 ELOG(1, "There are no atoms according to MaxTypes in this config file." << endl);
467 //performCriticalExit();
468 } else {
469 // prescan number of ions per type
470 LOG(0, "STATUS: Prescanning ions per type: " << endl);
471 int NoAtoms = 0;
472 for (int i=0; i < MaxTypes; i++) {
473 sprintf(name,"Ion_Type%i",i+1);
474 ParseForParameter(verbose,FileBuffer, (const char*)name, 0, 1, 1, int_type, &No[i], 1, critical);
475 ParseForParameter(verbose,FileBuffer, name, 0, 2, 1, int_type, &Z, 1, critical);
476 elementhash[i] = periode->FindElement(Z);
477 DoLog(1) && (Log() << Verbose(1) << i << ". Z = " << elementhash[i]->getAtomicNumber() << " with " << No[i] << " ions." << endl);
478 NoAtoms += No[i];
479 }
480 int repetition = -1; // which repeated keyword shall be read
481
482 // sort the lines via the LineMapping
483 sprintf(name,"Ion_Type%i",MaxTypes);
484 if (!ParseForParameter(verbose,FileBuffer, (const char*)name, 1, 1, 1, int_type, &value[0], 1, critical)) {
485 ELOG(0, "There are no atoms in the config file!" << endl);
486 performCriticalExit();
487 return;
488 }
489
490 FileBuffer->CurrentLine++; // skip to next line
491 FileBuffer->MapIonTypesInBuffer(NoAtoms);
492 for (int i=FileBuffer->CurrentLine; i<FileBuffer->NoLines;++i) {
493 LOG(4, FileBuffer->buffer[ FileBuffer->LineMapping[i] ]);
494 }
495
496 map<int, atom *> AtomList[MaxTypes];
497 map<int, atom *> LinearList;
498 atom *neues = NULL;
499 Vector tempVector;
500 int _fixedion;
501
502 typedef boost::tokenizer<boost::char_separator<char> >
503 tokenizer;
504 boost::char_separator<char> sep("\t ");
505 ConvertTo<double> toDouble;
506 ConvertTo<int> toInt;
507
508 for (int i=0; i < MaxTypes; i++) {
509 for(int j=0;j<No[i];j++) {
510 int step = 0;
511 std::stringstream keyword_stream;
512 keyword_stream << "Ion_Type" << i+1 << "_" << j+1;
513 const std::string keyword = keyword_stream.str();
514 LOG(3, "INFO: Parsing for " << keyword << "." << std::endl);
515 while (true) {
516 const std::string line(FileBuffer->buffer[ FileBuffer->LineMapping[FileBuffer->CurrentLine] ]);
517 const std::string line_without_comment = line.substr(0,line.find("#"));
518 tokenizer tokens(line_without_comment, sep);
519 if (tokens.begin() != tokens.end()) {
520 tokenizer::iterator tok_iter = tokens.begin();
521 const std::string token = *tok_iter++;
522 if (token == keyword) {
523 LOG(3, "INFO: Found keyword " << keyword << " in line " << FileBuffer->CurrentLine << std::endl);
524 if (step == 0) {
525 neues = World::getInstance().createAtom();
526 AtomList[i][j] = neues;
527 LOG(4, "Filling LinearList [ (FileBuffer->LineMapping[" << FileBuffer->CurrentLine << "]) = " << FileBuffer->LineMapping[FileBuffer->CurrentLine] << " with " << neues << endl);
528 LinearList[ FileBuffer->LineMapping[FileBuffer->CurrentLine] ] = neues;
529 neues->setType(elementhash[i]); // find element type
530 } else
531 neues = AtomList[i][j];
532
533 // count tokens
534 size_t tokens_size = 0;
535 for (tokenizer::iterator tokiter = tokens.begin(); tokiter != tokens.end(); ++tokiter)
536 ++tokens_size;
537 LOG(3, "INFO: Line contains " << tokens_size << " tokens." << std::endl);
538 // and parse
539 tempVector.Zero();
540 if (tokens_size >= 5) { // only AtomicPosition and FixedIon
541 for (int i=0;i<NDIM;++i)
542 tempVector[i] = toDouble(*tok_iter++);
543 neues->setPositionAtStep(step, tempVector);
544 _fixedion = toInt(*tok_iter++);
545 neues->setFixedIon(_fixedion == 1);
546 LOG(3, "INFO: Parsing AtomicPosition " << tempVector << " and FixedIon " << _fixedion << "." << std::endl);
547 }
548 tempVector.Zero();
549 if (tokens_size >= 8) { // AtomicVelocity
550 for (int i=0;i<NDIM;++i)
551 tempVector[i] = toDouble(*tok_iter++);
552 LOG(3, "INFO: Parsing AtomicVelocity " << tempVector << "." << std::endl);
553 }
554 neues->setAtomicVelocityAtStep(step, tempVector);
555 tempVector.Zero();
556 if (tokens_size >= 11) { // AtomicForce
557 LOG(3, "INFO: Parsing AtomicForce" << std::endl);
558 for (int i=0;i<NDIM;++i)
559 tempVector[i] = toDouble(*tok_iter++);
560 }
561 neues->setAtomicForceAtStep(step, tempVector);
562 std::stringstream output;
563 output << "Parsed position of step " << (step+1) << ": ";
564 output << neues->getPositionAtStep(step); // next step
565 output << "\t";
566 output << (neues->getFixedIon() ? "true" : "false");
567 output << "\t";
568 output << neues->getAtomicVelocityAtStep(step); // next step
569 output << "\t";
570 output << neues->getAtomicForceAtStep(step); // next step
571 DoLog(2) && (Log() << Verbose(2) << output.str() << endl);
572
573 step++;
574 } else {
575 if ((repetition > step) || (repetition == -1))
576 repetition = step;
577 break;
578 }
579 }
580 FileBuffer->CurrentLine++;
581 }
582 }
583 }
584
585 if (repetition <= 1) // if onyl one step, desactivate use of trajectories
586 mol->MDSteps = 0;
587 else {
588 DoLog(0) && (Log() << Verbose(0) << "Found " << repetition << " trajectory step(s)." << endl);
589 mol->MDSteps = repetition;
590 }
591
592 // put atoms into the molecule in their original order
593 for(map<int, atom*>::iterator runner = LinearList.begin(); runner != LinearList.end(); ++runner) {
594 mol->AddAtom(runner->second);
595 }
596 }
597};
598
599/** Stores all elements of config structure from which they can be re-read.
600 * \param *filename name of file
601 * \param *periode pointer to a periodentafel class with all elements
602 * \param *mol pointer to molecule containing all atoms of the molecule
603 */
604bool config::Save(const char * const filename, const periodentafel * const periode, molecule * const mol) const
605{
606 bool result = true;
607 const RealSpaceMatrix &domain = World::getInstance().getDomain().getM();
608 ThermoStatContainer *Thermostats = World::getInstance().getThermostats();
609 ofstream * const output = new ofstream(filename, ios::out);
610 if (output != NULL) {
611 *output << "# ParallelCarParinello - main configuration file - created with molecuilder" << endl;
612 *output << endl;
613 *output << "mainname\t" << config::mainname << "\t# programm name (for runtime files)" << endl;
614 *output << "defaultpath\t" << config::defaultpath << "\t# where to put files during runtime" << endl;
615 *output << "pseudopotpath\t" << config::pseudopotpath << "\t# where to find pseudopotentials" << endl;
616 *output << endl;
617 *output << "ProcPEGamma\t" << config::ProcPEGamma << "\t# for parallel computing: share constants" << endl;
618 *output << "ProcPEPsi\t" << config::ProcPEPsi << "\t# for parallel computing: share wave functions" << endl;
619 *output << "DoOutVis\t" << config::DoOutVis << "\t# Output data for OpenDX" << endl;
620 *output << "DoOutMes\t" << config::DoOutMes << "\t# Output data for measurements" << endl;
621 *output << "DoOutOrbitals\t" << config::DoOutOrbitals << "\t# Output all Orbitals" << endl;
622 *output << "DoOutCurr\t" << config::DoOutCurrent << "\t# Ouput current density for OpenDx" << endl;
623 *output << "DoOutNICS\t" << config::DoOutNICS << "\t# Output Nucleus independent current shieldings" << endl;
624 *output << "DoPerturbation\t" << config::DoPerturbation << "\t# Do perturbation calculate and determine susceptibility and shielding" << endl;
625 *output << "DoFullCurrent\t" << config::DoFullCurrent << "\t# Do full perturbation" << endl;
626 *output << "DoConstrainedMD\t" << config::DoConstrainedMD << "\t# Do perform a constrained (>0, relating to current MD step) instead of unconstrained (0) MD" << endl;
627 *output << "Thermostat\t" << Thermostats->activeThermostat->name() << "\t";
628 *output << Thermostats->activeThermostat->writeParams();
629 *output << "\t# Which Thermostat and its parameters to use in MD case." << endl;
630 *output << "CommonWannier\t" << config::CommonWannier << "\t# Put virtual centers at indivual orbits, all common, merged by variance, to grid point, to cell center" << endl;
631 *output << "SawtoothStart\t" << config::SawtoothStart << "\t# Absolute value for smooth transition at cell border " << endl;
632 *output << "VectorPlane\t" << config::VectorPlane << "\t# Cut plane axis (x, y or z: 0,1,2) for two-dim current vector plot" << endl;
633 *output << "VectorCut\t" << config::VectorCut << "\t# Cut plane axis value" << endl;
634 *output << "AddGramSch\t" << config::UseAddGramSch << "\t# Additional GramSchmidtOrtogonalization to be safe" << endl;
635 *output << "Seed\t\t" << config::Seed << "\t# initial value for random seed for Psi coefficients" << endl;
636 *output << endl;
637 *output << "MaxOuterStep\t" << config::MaxOuterStep << "\t# number of MolecularDynamics/Structure optimization steps" << endl;
638 *output << "Deltat\t" << config::Deltat << "\t# time per MD step" << endl;
639 *output << "OutVisStep\t" << config::OutVisStep << "\t# Output visual data every ...th step" << endl;
640 *output << "OutSrcStep\t" << config::OutSrcStep << "\t# Output \"restart\" data every ..th step" << endl;
641 *output << "TargetTemp\t" << Thermostats->TargetTemp << "\t# Target temperature" << endl;
642 *output << "MaxPsiStep\t" << config::MaxPsiStep << "\t# number of Minimisation steps per state (0 - default)" << endl;
643 *output << "EpsWannier\t" << config::EpsWannier << "\t# tolerance value for spread minimisation of orbitals" << endl;
644 *output << endl;
645 *output << "# Values specifying when to stop" << endl;
646 *output << "MaxMinStep\t" << config::MaxMinStep << "\t# Maximum number of steps" << endl;
647 *output << "RelEpsTotalE\t" << config::RelEpsTotalEnergy << "\t# relative change in total energy" << endl;
648 *output << "RelEpsKineticE\t" << config::RelEpsKineticEnergy << "\t# relative change in kinetic energy" << endl;
649 *output << "MaxMinStopStep\t" << config::MaxMinStopStep << "\t# check every ..th steps" << endl;
650 *output << "MaxMinGapStopStep\t" << config::MaxMinGapStopStep << "\t# check every ..th steps" << endl;
651 *output << endl;
652 *output << "# Values specifying when to stop for INIT, otherwise same as above" << endl;
653 *output << "MaxInitMinStep\t" << config::MaxInitMinStep << "\t# Maximum number of steps" << endl;
654 *output << "InitRelEpsTotalE\t" << config::InitRelEpsTotalEnergy << "\t# relative change in total energy" << endl;
655 *output << "InitRelEpsKineticE\t" << config::InitRelEpsKineticEnergy << "\t# relative change in kinetic energy" << endl;
656 *output << "InitMaxMinStopStep\t" << config::InitMaxMinStopStep << "\t# check every ..th steps" << endl;
657 *output << "InitMaxMinGapStopStep\t" << config::InitMaxMinGapStopStep << "\t# check every ..th steps" << endl;
658 *output << endl;
659 *output << "BoxLength\t\t\t# (Length of a unit cell)" << endl;
660 *output << domain.at(0,0) << "\t" << endl;
661 *output << domain.at(1,0) << "\t" << domain.at(1,1) << "\t" << endl;
662 *output << domain.at(2,0) << "\t" << domain.at(2,1) << "\t" << domain.at(2,2) << "\t" << endl;
663 // FIXME
664 *output << endl;
665 *output << "ECut\t\t" << config::ECut << "\t# energy cutoff for discretization in Hartrees" << endl;
666 *output << "MaxLevel\t" << config::MaxLevel << "\t# number of different levels in the code, >=2" << endl;
667 *output << "Level0Factor\t" << config::Lev0Factor << "\t# factor by which node number increases from S to 0 level" << endl;
668 *output << "RiemannTensor\t" << config::RiemannTensor << "\t# (Use metric)" << endl;
669 switch (config::RiemannTensor) {
670 case 0: //UseNoRT
671 break;
672 case 1: // UseRT
673 *output << "RiemannLevel\t" << config::RiemannLevel << "\t# Number of Riemann Levels" << endl;
674 *output << "LevRFactor\t" << config::LevRFactor << "\t# factor by which node number increases from 0 to R level from" << endl;
675 break;
676 }
677 *output << "PsiType\t\t" << config::PsiType << "\t# 0 - doubly occupied, 1 - SpinUp,SpinDown" << endl;
678 // write out both types for easier changing afterwards
679 // switch (PsiType) {
680 // case 0:
681 *output << "MaxPsiDouble\t" << config::MaxPsiDouble << "\t# here: specifying both maximum number of SpinUp- and -Down-states" << endl;
682 // break;
683 // case 1:
684 *output << "PsiMaxNoUp\t" << config::PsiMaxNoUp << "\t# here: specifying maximum number of SpinUp-states" << endl;
685 *output << "PsiMaxNoDown\t" << config::PsiMaxNoDown << "\t# here: specifying maximum number of SpinDown-states" << endl;
686 // break;
687 // }
688 *output << "AddPsis\t\t" << config::AddPsis << "\t# Additional unoccupied Psis for bandgap determination" << endl;
689 *output << endl;
690 *output << "RCut\t\t" << config::RCut << "\t# R-cut for the ewald summation" << endl;
691 *output << "StructOpt\t" << config::StructOpt << "\t# Do structure optimization beforehand" << endl;
692 *output << "IsAngstroem\t" << config::IsAngstroem << "\t# 0 - Bohr, 1 - Angstroem" << endl;
693 *output << "RelativeCoord\t" << config::RelativeCoord << "\t# whether ion coordinates are relative (1) or absolute (0)" << endl;
694 *output << "MaxTypes\t" << mol->getElementCount() << "\t# maximum number of different ion types" << endl;
695 *output << endl;
696 result = result && mol->Checkout(output);
697 if (mol->MDSteps <=1 )
698 result = result && mol->Output(output);
699 else
700 result = result && mol->OutputTrajectories(output);
701 output->close();
702 output->clear();
703 delete(output);
704 return result;
705 } else {
706 DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open output file:" << filename << endl);
707 return false;
708 }
709};
710
711/** Stores all elements in a MPQC input file.
712 * Note that this format cannot be parsed again.
713 * \param *filename name of file (without ".in" suffix!)
714 * \param *mol pointer to molecule containing all atoms of the molecule
715 */
716bool config::SaveMPQC(const char * const filename, const molecule * const mol) const
717{
718 Vector *center = NULL;
719 ofstream *output = NULL;
720
721 // first without hessian
722 {
723 stringstream * const fname = new stringstream;;
724 *fname << filename << ".in";
725 output = new ofstream(fname->str().c_str(), ios::out);
726 if (output == NULL) {
727 DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open mpqc output file:" << fname << endl);
728 delete(fname);
729 return false;
730 }
731 *output << "% Created by MoleCuilder" << endl;
732 *output << "mpqc: (" << endl;
733 *output << "\tsavestate = no" << endl;
734 *output << "\tdo_gradient = yes" << endl;
735 *output << "\tmole<MBPT2>: (" << endl;
736 *output << "\t\tmaxiter = 200" << endl;
737 *output << "\t\tbasis = $:basis" << endl;
738 *output << "\t\tmolecule = $:molecule" << endl;
739 *output << "\t\treference<CLHF>: (" << endl;
740 *output << "\t\t\tbasis = $:basis" << endl;
741 *output << "\t\t\tmolecule = $:molecule" << endl;
742 *output << "\t\t)" << endl;
743 *output << "\t)" << endl;
744 *output << ")" << endl;
745 *output << "molecule<Molecule>: (" << endl;
746 *output << "\tunit = " << (IsAngstroem ? "angstrom" : "bohr" ) << endl;
747 *output << "\t{ atoms geometry } = {" << endl;
748 center = mol->DetermineCenterOfAll();
749 // output of atoms
750 for(molecule::const_iterator iter = mol->begin(); iter!=mol->end();++iter){
751 (*iter)->OutputMPQCLine(output,center);
752 }
753 delete(center);
754 *output << "\t}" << endl;
755 *output << ")" << endl;
756 *output << "basis<GaussianBasisSet>: (" << endl;
757 *output << "\tname = \"3-21G\"" << endl;
758 *output << "\tmolecule = $:molecule" << endl;
759 *output << ")" << endl;
760 output->close();
761 delete(output);
762 delete(fname);
763 }
764
765 // second with hessian
766 {
767 stringstream * const fname = new stringstream;
768 *fname << filename << ".hess.in";
769 output = new ofstream(fname->str().c_str(), ios::out);
770 if (output == NULL) {
771 DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open mpqc hessian output file:" << fname << endl);
772 delete(fname);
773 return false;
774 }
775 *output << "% Created by MoleCuilder" << endl;
776 *output << "mpqc: (" << endl;
777 *output << "\tsavestate = no" << endl;
778 *output << "\tdo_gradient = yes" << endl;
779 *output << "\tmole<CLHF>: (" << endl;
780 *output << "\t\tmaxiter = 200" << endl;
781 *output << "\t\tbasis = $:basis" << endl;
782 *output << "\t\tmolecule = $:molecule" << endl;
783 *output << "\t)" << endl;
784 *output << "\tfreq<MolecularFrequencies>: (" << endl;
785 *output << "\t\tmolecule=$:molecule" << endl;
786 *output << "\t)" << endl;
787 *output << ")" << endl;
788 *output << "molecule<Molecule>: (" << endl;
789 *output << "\tunit = " << (IsAngstroem ? "angstrom" : "bohr" ) << endl;
790 *output << "\t{ atoms geometry } = {" << endl;
791 center = mol->DetermineCenterOfAll();
792 // output of atoms
793 for(molecule::const_iterator iter = mol->begin(); iter!=mol->end();++iter){
794 (*iter)->OutputMPQCLine(output,center);
795 }
796 delete(center);
797 *output << "\t}" << endl;
798 *output << ")" << endl;
799 *output << "basis<GaussianBasisSet>: (" << endl;
800 *output << "\tname = \"3-21G\"" << endl;
801 *output << "\tmolecule = $:molecule" << endl;
802 *output << ")" << endl;
803 output->close();
804 delete(output);
805 delete(fname);
806 }
807
808 return true;
809};
810
811/** Stores all atoms from all molecules in a PDB input file.
812 * Note that this format cannot be parsed again.
813 * \param *filename name of file (without ".in" suffix!)
814 * \param *MolList pointer to MoleculeListClass containing all atoms
815 */
816bool config::SavePDB(const char * const filename, const MoleculeListClass * const MolList) const
817{
818 int AtomNo = -1;
819 int MolNo = 0;
820 FILE *f = NULL;
821
822 char name[MAXSTRINGSIZE];
823 strncpy(name, filename, MAXSTRINGSIZE-1);
824 strncat(name, ".pdb", MAXSTRINGSIZE-(strlen(name)+1));
825 f = fopen(name, "w" );
826 if (f == NULL) {
827 DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open pdb output file:" << name << endl);
828 return false;
829 }
830 fprintf(f, "# Created by MoleCuilder\n");
831
832 for (MoleculeList::const_iterator MolRunner = MolList->ListOfMolecules.begin(); MolRunner != MolList->ListOfMolecules.end(); MolRunner++) {
833 int *elementNo = new int[MAX_ELEMENTS];
834 for (int i=0;i<MAX_ELEMENTS;i++)
835 elementNo[i] = 0;
836 AtomNo = 0;
837 for (molecule::const_iterator iter = (*MolRunner)->begin(); iter != (*MolRunner)->end(); ++iter) {
838 sprintf(name, "%2s%2d",(*iter)->getType()->getSymbol().c_str(), elementNo[(*iter)->getType()->getAtomicNumber()]);
839 elementNo[(*iter)->getType()->getAtomicNumber()] = (elementNo[(*iter)->getType()->getAtomicNumber()]+1) % 100; // confine to two digits
840 fprintf(f,
841 "ATOM %6u %-4s %4s%c%4u %8.3f%8.3f%8.3f%6.2f%6.2f %4s%2s%2s\n",
842 (*iter)->getNr(), /* atom serial number */
843 name, /* atom name */
844 (*MolRunner)->name, /* residue name */
845 'a'+(unsigned char)(AtomNo % 26), /* letter for chain */
846 MolNo, /* residue sequence number */
847 (*iter)->at(0), /* position X in Angstroem */
848 (*iter)->at(1), /* position Y in Angstroem */
849 (*iter)->at(2), /* position Z in Angstroem */
850 (double)(*iter)->getType()->getValence(), /* occupancy */
851 (double)(*iter)->getType()->getNoValenceOrbitals(), /* temperature factor */
852 "0", /* segment identifier */
853 (*iter)->getType()->getSymbol().c_str(), /* element symbol */
854 "0"); /* charge */
855 AtomNo++;
856 }
857 delete[](elementNo);
858 MolNo++;
859 }
860 fclose(f);
861
862 return true;
863};
864
865/** Stores all atoms in a PDB input file.
866 * Note that this format cannot be parsed again.
867 * \param *filename name of file (without ".in" suffix!)
868 * \param *mol pointer to molecule
869 */
870bool config::SavePDB(const char * const filename, const molecule * const mol) const
871{
872 int AtomNo = -1;
873 FILE *f = NULL;
874
875 int *elementNo = new int[MAX_ELEMENTS];
876 for (int i=0;i<MAX_ELEMENTS;i++)
877 elementNo[i] = 0;
878 char name[MAXSTRINGSIZE];
879 strncpy(name, filename, MAXSTRINGSIZE-1);
880 strncat(name, ".pdb", MAXSTRINGSIZE-(strlen(name)+1));
881 f = fopen(name, "w" );
882 if (f == NULL) {
883 DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open pdb output file:" << name << endl);
884 delete[](elementNo);
885 return false;
886 }
887 fprintf(f, "# Created by MoleCuilder\n");
888
889 AtomNo = 0;
890 for (molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
891 sprintf(name, "%2s%2d",(*iter)->getType()->getSymbol().c_str(), elementNo[(*iter)->getType()->getAtomicNumber()]);
892 elementNo[(*iter)->getType()->getAtomicNumber()] = (elementNo[(*iter)->getType()->getAtomicNumber()]+1) % 100; // confine to two digits
893 fprintf(f,
894 "ATOM %6u %-4s %4s%c%4u %8.3f%8.3f%8.3f%6.2f%6.2f %4s%2s%2s\n",
895 (*iter)->getNr(), /* atom serial number */
896 name, /* atom name */
897 mol->name, /* residue name */
898 'a'+(unsigned char)(AtomNo % 26), /* letter for chain */
899 0, /* residue sequence number */
900 (*iter)->at(0), /* position X in Angstroem */
901 (*iter)->at(1), /* position Y in Angstroem */
902 (*iter)->at(2), /* position Z in Angstroem */
903 (double)(*iter)->getType()->getValence(), /* occupancy */
904 (double)(*iter)->getType()->getNoValenceOrbitals(), /* temperature factor */
905 "0", /* segment identifier */
906 (*iter)->getType()->getSymbol().c_str(), /* element symbol */
907 "0"); /* charge */
908 AtomNo++;
909 }
910 fclose(f);
911 delete[](elementNo);
912
913 return true;
914};
915
916/** Stores all atoms in a TREMOLO data input file.
917 * Note that this format cannot be parsed again.
918 * Note that TREMOLO does not like Id starting at 0, but at 1. Atoms with Id 0 are discarded!
919 * \param *filename name of file (without ".in" suffix!)
920 * \param *mol pointer to molecule
921 */
922bool config::SaveTREMOLO(const char * const filename, const molecule * const mol) const
923{
924 ofstream *output = NULL;
925 stringstream * const fname = new stringstream;
926
927 *fname << filename << ".data";
928 output = new ofstream(fname->str().c_str(), ios::out);
929 if (output == NULL) {
930 DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open tremolo output file:" << fname << endl);
931 delete(fname);
932 return false;
933 }
934
935 // scan maximum number of neighbours
936 int MaxNeighbours = 0;
937 for (molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
938 const int count = (*iter)->getListOfBonds().size();
939 if (MaxNeighbours < count)
940 MaxNeighbours = count;
941 }
942 *output << "# ATOMDATA Id name resName resSeq x=3 Charge type neighbors=" << MaxNeighbours << endl;
943
944 for (molecule::const_iterator iter = mol->begin(); iter != mol->end(); ++iter) {
945 *output << (*iter)->getNr() << "\t";
946 *output << (*iter)->getName() << "\t";
947 *output << mol->name << "\t";
948 *output << 0 << "\t";
949 *output << (*iter)->at(0) << "\t" << (*iter)->at(1) << "\t" << (*iter)->at(2) << "\t";
950 *output << static_cast<double>((*iter)->getType()->getValence()) << "\t";
951 *output << (*iter)->getType()->getSymbol() << "\t";
952 const BondList& ListOfBonds = (*iter)->getListOfBonds();
953 for (BondList::const_iterator runner = ListOfBonds.begin();
954 runner != ListOfBonds.end();
955 runner++) {
956 *output << (*runner)->GetOtherAtom(*iter)->getNr() << "\t";
957 }
958 for(int i = ListOfBonds.size(); i < MaxNeighbours; i++)
959 *output << "-\t";
960 *output << endl;
961 }
962 output->flush();
963 output->close();
964 delete(output);
965 delete(fname);
966
967 return true;
968};
969
970/** Stores all atoms from all molecules in a TREMOLO data input file.
971 * Note that this format cannot be parsed again.
972 * Note that TREMOLO does not like Id starting at 0, but at 1. Atoms with Id 0 are discarded!
973 * \param *filename name of file (without ".in" suffix!)
974 * \param *MolList pointer to MoleculeListClass containing all atoms
975 */
976bool config::SaveTREMOLO(const char * const filename, const MoleculeListClass * const MolList) const
977{
978 Info FunctionInfo(__func__);
979 ofstream *output = NULL;
980 stringstream * const fname = new stringstream;
981
982 *fname << filename << ".data";
983 output = new ofstream(fname->str().c_str(), ios::out);
984 if (output == NULL) {
985 DoeLog(1) && (eLog()<< Verbose(1) << "Cannot open tremolo output file:" << fname << endl);
986 delete(fname);
987 return false;
988 }
989
990 // scan maximum number of neighbours
991 int MaxNeighbours = 0;
992 for (MoleculeList::const_iterator MolWalker = MolList->ListOfMolecules.begin(); MolWalker != MolList->ListOfMolecules.end(); MolWalker++) {
993 for (molecule::const_iterator iter = (*MolWalker)->begin(); iter != (*MolWalker)->end(); ++iter) {
994 const int count = (*iter)->getListOfBonds().size();
995 if (MaxNeighbours < count)
996 MaxNeighbours = count;
997 }
998 }
999 *output << "# ATOMDATA Id name resName resSeq x=3 Charge type neighbors=" << MaxNeighbours << endl;
1000
1001 // create global to local id map
1002 map<int, int> LocalNotoGlobalNoMap;
1003 {
1004 unsigned int MolCounter = 0;
1005 int AtomNo = 1;
1006 for (MoleculeList::const_iterator MolWalker = MolList->ListOfMolecules.begin(); MolWalker != MolList->ListOfMolecules.end(); MolWalker++) {
1007 for(molecule::iterator AtomRunner = (*MolWalker)->begin(); AtomRunner != (*MolWalker)->end(); ++AtomRunner) {
1008 LocalNotoGlobalNoMap.insert( pair<int,int>((*AtomRunner)->getId(), AtomNo++) );
1009 }
1010 MolCounter++;
1011 }
1012 ASSERT(MolCounter == MolList->ListOfMolecules.size(), "SaveTREMOLO: LocalNotoGlobalNoMap[] has not been correctly initialized for each molecule");
1013 }
1014
1015 // write the file
1016 {
1017 int MolCounter = 0;
1018 int AtomNo = 0;
1019 for (MoleculeList::const_iterator MolWalker = MolList->ListOfMolecules.begin(); MolWalker != MolList->ListOfMolecules.end(); MolWalker++) {
1020 for (molecule::const_iterator iter = (*MolWalker)->begin(); iter != (*MolWalker)->end(); ++iter) {
1021 *output << LocalNotoGlobalNoMap[ (*iter)->getId() ] << "\t";
1022 *output << (*iter)->getName() << "\t";
1023 *output << (*MolWalker)->name << "\t";
1024 *output << MolCounter+1 << "\t";
1025 *output << (*iter)->at(0) << "\t" << (*iter)->at(1) << "\t" << (*iter)->at(2) << "\t";
1026 *output << (double)(*iter)->getType()->getValence() << "\t";
1027 *output << (*iter)->getType()->getSymbol() << "\t";
1028 const BondList& ListOfBonds = (*iter)->getListOfBonds();
1029 for (BondList::const_iterator runner = ListOfBonds.begin();
1030 runner != ListOfBonds.end();
1031 runner++) {
1032 *output << LocalNotoGlobalNoMap[ (*runner)->GetOtherAtom((*iter))->getId() ] << "\t";
1033 }
1034 for(int i = ListOfBonds.size(); i < MaxNeighbours; i++)
1035 *output << "-\t";
1036 *output << endl;
1037 AtomNo++;
1038 }
1039 MolCounter++;
1040 }
1041 }
1042
1043 // store & free
1044 output->flush();
1045 output->close();
1046 delete(output);
1047 delete(fname);
1048
1049 return true;
1050};
1051
1052
1053/** Tries given filename or standard on saving the config file.
1054 * \param *ConfigFileName name of file
1055 * \param *periode pointer to periodentafel structure with all the elements
1056 * \param *molecules list of molecules structure with all the atoms and coordinates
1057 */
1058void config::SaveAll(char *ConfigFileName, periodentafel *periode, MoleculeListClass *molecules)
1059{
1060 char filename[MAXSTRINGSIZE];
1061 ofstream output;
1062 molecule *mol = NULL;
1063
1064 // first save as PDB data
1065 if (ConfigFileName != NULL)
1066 strcpy(filename, ConfigFileName);
1067 if (output == NULL)
1068 strcpy(filename,"main_pcp_linux");
1069 Log() << Verbose(0) << "Saving as pdb input ... " << endl;
1070 if (SavePDB(filename, molecules))
1071 Log() << Verbose(0) << "\t... done." << endl;
1072 else
1073 Log() << Verbose(0) << "\t... failed." << endl;
1074
1075 // then save as tremolo data file
1076 if (ConfigFileName != NULL)
1077 strcpy(filename, ConfigFileName);
1078 if (output == NULL)
1079 strcpy(filename,"main_pcp_linux");
1080 Log() << Verbose(0) << "Saving as tremolo data input ... " << endl;
1081 if (SaveTREMOLO(filename, molecules))
1082 Log() << Verbose(0) << "\t... done." << endl;
1083 else
1084 Log() << Verbose(0) << "\t... failed." << endl;
1085
1086 // translate each to its center and merge all molecules in MoleculeListClass into this molecule
1087 int N = molecules->ListOfMolecules.size();
1088 if (N != 1) { // don't do anything in case of only one molecule (shifts mol ids otherwise)
1089 int *src = new int[N];
1090 N=0;
1091 for (MoleculeList::iterator ListRunner = molecules->ListOfMolecules.begin(); ListRunner != molecules->ListOfMolecules.end(); ListRunner++) {
1092 src[N++] = (*ListRunner)->IndexNr;
1093 }
1094 mol = World::getInstance().createMolecule();
1095 mol->SetNameFromFilename(ConfigFileName);
1096 //mol->CalculateOrbitals(*this);
1097 delete[](src);
1098 } else {
1099 if (!molecules->ListOfMolecules.empty()) {
1100 mol = *(molecules->ListOfMolecules.begin());
1101 mol->doCountAtoms();
1102 //mol->CalculateOrbitals(*this);
1103 } else {
1104 DoeLog(1) && (eLog() << Verbose(1) << "There are no molecules to save!" << endl);
1105 }
1106 }
1107
1108 Log() << Verbose(0) << "Storing configuration ... " << endl;
1109 // get correct valence orbitals
1110 if (ConfigFileName != NULL) { // test the file name
1111 strcpy(filename, ConfigFileName);
1112 output.open(filename, ios::trunc);
1113 } else if (strlen(configname) != 0) {
1114 strcpy(filename, configname);
1115 output.open(configname, ios::trunc);
1116 } else {
1117 strcpy(filename, DEFAULTCONFIG);
1118 output.open(DEFAULTCONFIG, ios::trunc);
1119 }
1120 output.close();
1121 output.clear();
1122 Log() << Verbose(0) << "Saving of config file ... " << endl;
1123 if (Save(filename, periode, mol))
1124 Log() << Verbose(0) << "\t... successful." << endl;
1125 else
1126 Log() << Verbose(0) << "\t... failed." << endl;
1127
1128 // and save to xyz file
1129 if (ConfigFileName != NULL) {
1130 strcpy(filename, ConfigFileName);
1131 strcat(filename, ".xyz");
1132 output.open(filename, ios::trunc);
1133 }
1134 if (output == NULL) {
1135 strcpy(filename,"main_pcp_linux");
1136 strcat(filename, ".xyz");
1137 output.open(filename, ios::trunc);
1138 }
1139 Log() << Verbose(0) << "Saving of XYZ file ... " << endl;
1140 if (mol->MDSteps <= 1) {
1141 if (mol->OutputXYZ(&output))
1142 Log() << Verbose(0) << "\t... successful." << endl;
1143 else
1144 Log() << Verbose(0) << "\t... failed." << endl;
1145 } else {
1146 if (mol->OutputTrajectoriesXYZ(&output))
1147 Log() << Verbose(0) << "\t... successful." << endl;
1148 else
1149 Log() << Verbose(0) << "\t... failed." << endl;
1150 }
1151 output.close();
1152 output.clear();
1153
1154 // and save as MPQC configuration
1155 if (ConfigFileName != NULL)
1156 strcpy(filename, ConfigFileName);
1157 if (output == NULL)
1158 strcpy(filename,"main_pcp_linux");
1159 Log() << Verbose(0) << "Saving as mpqc input .. " << endl;
1160 if (SaveMPQC(filename, mol))
1161 Log() << Verbose(0) << "\t... done." << endl;
1162 else
1163 Log() << Verbose(0) << "\t... failed." << endl;
1164
1165 // don't destroy molecule as it contains all our atoms
1166 //World::getInstance().destroyMolecule(mol);
1167};
1168
1169/** Reads parameter from a parsed file.
1170 * The file is either parsed for a certain keyword or if null is given for
1171 * the value in row yth and column xth. If the keyword was necessity#critical,
1172 * then an error is thrown and the programme aborted.
1173 * \warning value is modified (both in contents and position)!
1174 * \param verbose 1 - print found value to stderr, 0 - don't
1175 * \param *file file to be parsed
1176 * \param name Name of value in file (at least 3 chars!)
1177 * \param sequential 1 - do not reset file pointer to begin of file, 0 - set to beginning
1178 * (if file is sequentially parsed this can be way faster! However, beware of multiple values per line, as whole line is read -
1179 * best approach: 0 0 0 1 (not resetted only on last value of line) - and of yth, which is now
1180 * counted from this unresetted position!)
1181 * \param xth Which among a number of parameters it is (in grid case it's row number as grid is read as a whole!)
1182 * \param yth In grid case specifying column number, otherwise the yth \a name matching line
1183 * \param type Type of the Parameter to be read
1184 * \param value address of the value to be read (must have been allocated)
1185 * \param repetition determines, if the keyword appears multiply in the config file, which repetition shall be parsed, i.e. 1 if not multiply
1186 * \param critical necessity of this keyword being specified (optional, critical)
1187 * \return 1 - found, 0 - not found
1188 * \note Routine is taken from the pcp project and hack-a-slack adapted to C++
1189 */
1190int ParseForParameter(const int verbose, ifstream * const file, const char * const name, const int sequential, const int xth, const int yth, const int type, void * value, const int repetition, const int critical) {
1191 int i = 0;
1192 int j = 0; // loop variables
1193 int length = 0;
1194 int maxlength = -1;
1195 long file_position = file->tellg(); // mark current position
1196 char *dummy1 = NULL;
1197 char *dummy = NULL;
1198 char free_dummy[MAXSTRINGSIZE]; // pointers in the line that is read in per step
1199 dummy1 = free_dummy;
1200
1201 //fprintf(stderr,"Parsing for %s\n",name);
1202 if (repetition == 0)
1203 //Error(SomeError, "ParseForParameter(): argument repetition must not be 0!");
1204 return 0;
1205
1206 int line = 0; // marks line where parameter was found
1207 int found = (type >= grid) ? 0 : (-yth + 1); // marks if yth parameter name was found
1208 while((found != repetition)) {
1209 dummy1 = dummy = free_dummy;
1210 do {
1211 file->getline(dummy1, 256); // Read the whole line
1212 if (file->eof()) {
1213 if ((critical) && (found == 0)) {
1214 //Error(InitReading, name);
1215 fprintf(stderr,"Error:InitReading, critical %s not found\n", name);
1216 exit(255);
1217 } else {
1218 //if (!sequential)
1219 file->clear();
1220 file->seekg(file_position, ios::beg); // rewind to start position
1221 return 0;
1222 }
1223 }
1224 line++;
1225 } while (dummy != NULL && dummy1 != NULL && ((dummy1[0] == '#') || (dummy1[0] == '\0'))); // skip commentary and empty lines
1226
1227 // C++ getline removes newline at end, thus re-add
1228 if ((dummy1 != NULL) && (strchr(dummy1,'\n') == NULL)) {
1229 i = strlen(dummy1);
1230 dummy1[i] = '\n';
1231 dummy1[i+1] = '\0';
1232 }
1233 //fprintf(stderr,"line %i ends at %i, newline at %i\n", line, strlen(dummy1), strchr(dummy1,'\n')-free_dummy);
1234
1235 if (dummy1 == NULL) {
1236 if (verbose) fprintf(stderr,"Error reading line %i\n",line);
1237 } else {
1238 //fprintf(stderr,"Now parsing the line %i: %s\n", line, dummy1);
1239 }
1240 // Seek for possible end of keyword on line if given ...
1241 if (name != NULL) {
1242 dummy = strchr(dummy1,'\t'); // set dummy on first tab or space which ever's nearer
1243 if (dummy == NULL) {
1244 dummy = strchr(dummy1, ' '); // if not found seek for space
1245 while ((dummy != NULL) && ((*dummy == '\t') || (*dummy == ' '))) // skip some more tabs and spaces if necessary
1246 dummy++;
1247 }
1248 if (dummy == NULL) {
1249 dummy = strchr(dummy1, '\n'); // set on line end then (whole line = keyword)
1250 //fprintf(stderr,"Error: Cannot find tabs or spaces on line %i in search for %s\n", line, name);
1251 //Error(FileOpenParams, NULL);
1252 } else {
1253 //fprintf(stderr,"found tab at %i\n",(char *)dummy-(char *)dummy1);
1254 }
1255 } else dummy = dummy1;
1256 // ... and check if it is the keyword!
1257 //fprintf(stderr,"name %p, dummy %i/%c, dummy1 %i/%c, strlen(name) %i\n", &name, dummy, *dummy, dummy1, *dummy1, strlen(name));
1258 if ((name == NULL) || (((dummy-dummy1 >= 3) && (strncmp(dummy1, name, strlen(name)) == 0)) && ((unsigned int)(dummy-dummy1) == strlen(name)))) {
1259 found++; // found the parameter!
1260 //fprintf(stderr,"found %s at line %i between %i and %i\n", name, line, dummy1, dummy);
1261
1262 if (found == repetition) {
1263 for (i=0;i<xth;i++) { // i = rows
1264 if (type >= grid) {
1265 // grid structure means that grid starts on the next line, not right after keyword
1266 dummy1 = dummy = free_dummy;
1267 do {
1268 file->getline(dummy1, 256); // Read the whole line, skip commentary and empty ones
1269 if (file->eof()) {
1270 if ((critical) && (found == 0)) {
1271 //Error(InitReading, name);
1272 fprintf(stderr,"Error:InitReading, critical %s not found\n", name);
1273 exit(255);
1274 } else {
1275 //if (!sequential)
1276 file->clear();
1277 file->seekg(file_position, ios::beg); // rewind to start position
1278 return 0;
1279 }
1280 }
1281 line++;
1282 } while ((dummy1[0] == '#') || (dummy1[0] == '\n'));
1283 if (dummy1 == NULL){
1284 if (verbose) fprintf(stderr,"Error reading line %i\n", line);
1285 } else {
1286 //fprintf(stderr,"Reading next line %i: %s\n", line, dummy1);
1287 }
1288 } else { // simple int, strings or doubles start in the same line
1289 while ((*dummy == '\t') || (*dummy == ' ')) // skip interjacent tabs and spaces
1290 dummy++;
1291 }
1292 // C++ getline removes newline at end, thus re-add
1293 if ((dummy1 != NULL) && (strchr(dummy1,'\n') == NULL)) {
1294 j = strlen(dummy1);
1295 dummy1[j] = '\n';
1296 dummy1[j+1] = '\0';
1297 }
1298
1299 int start = (type >= grid) ? 0 : yth-1 ;
1300 for (j=start;j<yth;j++) { // j = columns
1301 // check for lower triangular area and upper triangular area
1302 if ( ((i > j) && (type == upper_trigrid)) || ((j > i) && (type == lower_trigrid))) {
1303 *((double *)value) = 0.0;
1304 fprintf(stderr,"%f\t",*((double *)value));
1305 value = (void *)((long)value + sizeof(double));
1306 //value += sizeof(double);
1307 } else {
1308 // otherwise we must skip all interjacent tabs and spaces and find next value
1309 dummy1 = dummy;
1310 dummy = strchr(dummy1, '\t'); // seek for tab or space
1311 if (dummy == NULL)
1312 dummy = strchr(dummy1, ' '); // if not found seek for space
1313 if (dummy == NULL) { // if still zero returned ...
1314 dummy = strchr(dummy1, '\n'); // ... at line end then
1315 if ((j < yth-1) && (type < 4)) { // check if xth value or not yet
1316 if (critical) {
1317 if (verbose) fprintf(stderr,"Error: EoL at %i and still missing %i value(s) for parameter %s\n", line, yth-j, name);
1318 //return 0;
1319 exit(255);
1320 //Error(FileOpenParams, NULL);
1321 } else {
1322 //if (!sequential)
1323 file->clear();
1324 file->seekg(file_position, ios::beg); // rewind to start position
1325 return 0;
1326 }
1327 }
1328 } else {
1329 //fprintf(stderr,"found tab at %i\n",(char *)dummy-(char *)free_dummy);
1330 }
1331 if (*dummy1 == '#') {
1332 // found comment, skipping rest of line
1333 //if (verbose) fprintf(stderr,"Error: '#' at %i and still missing %i value(s) for parameter %s\n", line, yth-j, name);
1334 if (!sequential) { // here we need it!
1335 file->seekg(file_position, ios::beg); // rewind to start position
1336 }
1337 return 0;
1338 }
1339 //fprintf(stderr,"value from %i to %i\n",(char *)dummy1-(char *)free_dummy,(char *)dummy-(char *)free_dummy);
1340 switch(type) {
1341 case (row_int):
1342 *((int *)value) = atoi(dummy1);
1343 if ((verbose) && (i==0) && (j==0)) fprintf(stderr,"%s = ", name);
1344 if (verbose) fprintf(stderr,"%i\t",*((int *)value));
1345 value = (void *)((long)value + sizeof(int));
1346 //value += sizeof(int);
1347 break;
1348 case(row_double):
1349 case(grid):
1350 case(lower_trigrid):
1351 case(upper_trigrid):
1352 *((double *)value) = atof(dummy1);
1353 if ((verbose) && (i==0) && (j==0)) fprintf(stderr,"%s = ", name);
1354 if (verbose) fprintf(stderr,"%lg\t",*((double *)value));
1355 value = (void *)((long)value + sizeof(double));
1356 //value += sizeof(double);
1357 break;
1358 case(double_type):
1359 *((double *)value) = atof(dummy1);
1360 if ((verbose) && (i == xth-1)) fprintf(stderr,"%s = %lg\n", name, *((double *) value));
1361 //value += sizeof(double);
1362 break;
1363 case(int_type):
1364 *((int *)value) = atoi(dummy1);
1365 if ((verbose) && (i == xth-1)) fprintf(stderr,"%s = %i\n", name, *((int *) value));
1366 //value += sizeof(int);
1367 break;
1368 default:
1369 case(string_type):
1370 if (value != NULL) {
1371 //if (maxlength == -1) maxlength = strlen((char *)value); // get maximum size of string array
1372 maxlength = MAXSTRINGSIZE;
1373 length = maxlength > (dummy-dummy1) ? (dummy-dummy1) : maxlength; // cap at maximum
1374 strncpy((char *)value, dummy1, length); // copy as much
1375 ((char *)value)[length] = '\0'; // and set end marker
1376 if ((verbose) && (i == xth-1)) fprintf(stderr,"%s is '%s' (%i chars)\n",name,((char *) value), length);
1377 //value += sizeof(char);
1378 } else {
1379 }
1380 break;
1381 }
1382 }
1383 while (*dummy == '\t')
1384 dummy++;
1385 }
1386 }
1387 }
1388 }
1389 }
1390 if ((type >= row_int) && (verbose))
1391 fprintf(stderr,"\n");
1392 if (!sequential) {
1393 file->clear();
1394 file->seekg(file_position, ios::beg); // rewind to start position
1395 }
1396 //fprintf(stderr, "End of Parsing\n\n");
1397
1398 return (found); // true if found, false if not
1399}
1400
1401
1402/** Reads parameter from a parsed file.
1403 * The file is either parsed for a certain keyword or if null is given for
1404 * the value in row yth and column xth. If the keyword was necessity#critical,
1405 * then an error is thrown and the programme aborted.
1406 * \warning value is modified (both in contents and position)!
1407 * \param verbose 1 - print found value to stderr, 0 - don't
1408 * \param *FileBuffer pointer to buffer structure
1409 * \param name Name of value in file (at least 3 chars!)
1410 * \param sequential 1 - do not reset file pointer to begin of file, 0 - set to beginning
1411 * (if file is sequentially parsed this can be way faster! However, beware of multiple values per line, as whole line is read -
1412 * best approach: 0 0 0 1 (not resetted only on last value of line) - and of yth, which is now
1413 * counted from this unresetted position!)
1414 * \param xth Which among a number of parameters it is (in grid case it's row number as grid is read as a whole!)
1415 * \param yth In grid case specifying column number, otherwise the yth \a name matching line
1416 * \param type Type of the Parameter to be read
1417 * \param value address of the value to be read (must have been allocated)
1418 * \param repetition determines, if the keyword appears multiply in the config file, which repetition shall be parsed, i.e. 1 if not multiply
1419 * \param critical necessity of this keyword being specified (optional, critical)
1420 * \return 1 - found, 0 - not found
1421 * \note Routine is taken from the pcp project and hack-a-slack adapted to C++
1422 */
1423int ParseForParameter(const int verbose, struct ConfigFileBuffer * const FileBuffer, const char * const name, const int sequential, const int xth, const int yth, const int type, void * value, const int repetition, const int critical) {
1424 int i = 0;
1425 int j = 0; // loop variables
1426 int length = 0;
1427 int maxlength = -1;
1428 int OldCurrentLine = FileBuffer->CurrentLine;
1429 char *dummy1 = NULL;
1430 char *dummy = NULL; // pointers in the line that is read in per step
1431 char *free_dummy = NULL;
1432
1433 if (verbose) fprintf(stderr,"Begin of Parsing for %s\n",name);
1434 if (repetition == 0)
1435 //Error(SomeError, "ParseForParameter(): argument repetition must not be 0!");
1436 return 0;
1437
1438 int found = (type >= grid) ? 0 : (-yth + 1); // marks if yth parameter name was found
1439 while((found != repetition)) {
1440 dummy1 = dummy = NULL;
1441 do {
1442 if (FileBuffer->CurrentLine < FileBuffer->NoLines)
1443 free_dummy = dummy1 = FileBuffer->buffer[ FileBuffer->LineMapping[FileBuffer->CurrentLine++] ];
1444 if (FileBuffer->CurrentLine >= FileBuffer->NoLines) {
1445 if ((critical) && (found == 0)) {
1446 //Error(InitReading, name);
1447 fprintf(stderr,"Error:InitReading, critical %s not found\n", name);
1448 return 0;
1449 } else {
1450 //fprintf(stdout,"Rewinding to OldCurrentLine due to search till end of file.\n");
1451 FileBuffer->CurrentLine = OldCurrentLine; // rewind to start position
1452 return 0;
1453 }
1454 }
1455 if (dummy1 == NULL) {
1456 if (verbose) fprintf(stderr,"Error reading line %i\n",FileBuffer->CurrentLine);
1457 } else {
1458 if (verbose) fprintf(stderr,"Now parsing the line %i: %s\n", FileBuffer->CurrentLine, dummy1);
1459 }
1460 //FileBuffer->CurrentLine++;
1461 } while (dummy1 != NULL && ((dummy1[0] == '#') || (dummy1[0] == '\0'))); // skip commentary and empty lines
1462
1463 // Seek for possible end of keyword on line if given ...
1464 if (name != NULL) {
1465 dummy = strchr(dummy1,'\t'); // set dummy on first tab or space which ever's nearer
1466 if (dummy == NULL) {
1467 dummy = strchr(dummy1, ' '); // if not found seek for space
1468 while ((dummy != NULL) && ((*dummy == '\t') || (*dummy == ' '))) // skip some more tabs and spaces if necessary
1469 dummy++;
1470 }
1471 if (dummy == NULL) {
1472 dummy = strchr(dummy1, '\n'); // set on line end then (whole line = keyword)
1473 //fprintf(stderr,"Error: Cannot find tabs or spaces on line %i in search for %s\n", line, name);
1474 //Error(FileOpenParams, NULL);
1475 } else {
1476 if (verbose) fprintf(stderr,"found tab at line %i at position %li\n",FileBuffer->CurrentLine, (char *)dummy-(char *)dummy1);
1477 }
1478 } else dummy = dummy1;
1479 // ... and check if it is the keyword!
1480 //fprintf(stderr,"name %p, dummy %i/%c, dummy1 %i/%c, strlen(name) %i\n", &name, dummy, *dummy, dummy1, *dummy1, strlen(name));
1481 if ((name == NULL) || (((dummy-dummy1 >= 3) && (strncmp(dummy1, name, strlen(name)) == 0)) && ((unsigned int)(dummy-dummy1) == strlen(name)))) {
1482 found++; // found the parameter!
1483 if (verbose) fprintf(stderr,"found %s at line %i between %li and %li\n", name, FileBuffer->CurrentLine, (unsigned long)dummy1, (unsigned long)dummy);
1484
1485 if (found == repetition) {
1486 for (i=0;i<xth;i++) { // i = rows
1487 if (type >= grid) {
1488 // grid structure means that grid starts on the next line, not right after keyword
1489 dummy1 = dummy = NULL;
1490 do {
1491 dummy1 = FileBuffer->buffer[ FileBuffer->LineMapping[ FileBuffer->CurrentLine++] ];
1492 if (FileBuffer->CurrentLine >= FileBuffer->NoLines) {
1493 if ((critical) && (found == 0)) {
1494 //Error(InitReading, name);
1495 fprintf(stderr,"Error:InitReading, critical %s not found\n", name);
1496 exit(255);
1497 } else {
1498 //fprintf(stdout,"Rewinding to OldCurrentLine due to search till end of line.\n");
1499 FileBuffer->CurrentLine = OldCurrentLine; // rewind to start position
1500 return 0;
1501 }
1502 }
1503 if (dummy1 == NULL) {
1504 if (verbose) fprintf(stderr,"Error reading line %i\n", FileBuffer->CurrentLine);
1505 } else {
1506 if (verbose) fprintf(stderr,"Reading next line %i: %s\n", FileBuffer->CurrentLine, dummy1);
1507 }
1508 //FileBuffer->CurrentLine++;
1509 } while ((dummy1 != NULL) && ((dummy1[0] == '#') || (dummy1[0] == '\n')));
1510 dummy = dummy1;
1511 } else { // simple int, strings or doubles start in the same line
1512 while ((*dummy == '\t') || (*dummy == ' ')) // skip interjacent tabs and spaces
1513 dummy++;
1514 }
1515
1516 for (j=((type >= grid) ? 0 : yth-1);j<yth;j++) { // j = columns
1517 // check for lower triangular area and upper triangular area
1518 if ( ((i > j) && (type == upper_trigrid)) || ((j > i) && (type == lower_trigrid))) {
1519 *((double *)value) = 0.0;
1520 fprintf(stderr,"%f\t",*((double *)value));
1521 value = (void *)((long)value + sizeof(double));
1522 //value += sizeof(double);
1523 } else {
1524 // otherwise we must skip all interjacent tabs and spaces and find next value
1525 dummy1 = dummy;
1526 dummy = strchr(dummy1, '\t'); // seek for tab or space
1527 if (dummy == NULL)
1528 dummy = strchr(dummy1, ' '); // if not found seek for space
1529 if (dummy == NULL) { // if still zero returned ...
1530 dummy = strchr(dummy1, '\n'); // ... at line end then
1531 if ((j < yth-1) && (type < 4)) { // check if xth value or not yet
1532 if (critical) {
1533 if (verbose) fprintf(stderr,"Error: EoL at %i and still missing %i value(s) for parameter %s\n", FileBuffer->CurrentLine, yth-j, name);
1534 //return 0;
1535 exit(255);
1536 //Error(FileOpenParams, NULL);
1537 } else {
1538 if (!sequential) { // here we need it!
1539 //fprintf(stdout,"Rewinding to OldCurrentLine due to end of line and sequential %d.\n", sequential);
1540 FileBuffer->CurrentLine = OldCurrentLine; // rewind to start position
1541 }
1542 return 0;
1543 }
1544 }
1545 } else {
1546 if (verbose) fprintf(stderr,"found tab at line %i at position %li\n",FileBuffer->CurrentLine, (char *)dummy-(char *)free_dummy);
1547 }
1548 if (*dummy1 == '#') {
1549 // found comment, skipping rest of line
1550 //if (verbose) fprintf(stderr,"Error: '#' at %i and still missing %i value(s) for parameter %s\n", line, yth-j, name);
1551 if (!sequential) { // here we need it!
1552 //fprintf(stdout,"Rewinding to OldCurrentLine due to comment and sequential %d.\n", sequential);
1553 FileBuffer->CurrentLine = OldCurrentLine; // rewind to start position
1554 }
1555 return 0;
1556 }
1557 if (verbose) fprintf(stderr,"value from %li to %li\n",(char *)dummy1-(char *)free_dummy,(char *)dummy-(char *)free_dummy);
1558 switch(type) {
1559 case (row_int):
1560 *((int *)value) = atoi(dummy1);
1561 if ((verbose) && (i==0) && (j==0)) fprintf(stderr,"%s = ", name);
1562 if (verbose) fprintf(stderr,"%i\t",*((int *)value));
1563 value = (void *)((long)value + sizeof(int));
1564 //value += sizeof(int);
1565 break;
1566 case(row_double):
1567 case(grid):
1568 case(lower_trigrid):
1569 case(upper_trigrid):
1570 *((double *)value) = atof(dummy1);
1571 if ((verbose) && (i==0) && (j==0)) fprintf(stderr,"%s = ", name);
1572 if (verbose) fprintf(stderr,"%lg\t",*((double *)value));
1573 value = (void *)((long)value + sizeof(double));
1574 //value += sizeof(double);
1575 break;
1576 case(double_type):
1577 *((double *)value) = atof(dummy1);
1578 if ((verbose) && (i == xth-1)) fprintf(stderr,"%s = %lg\n", name, *((double *) value));
1579 //value += sizeof(double);
1580 break;
1581 case(int_type):
1582 *((int *)value) = atoi(dummy1);
1583 if ((verbose) && (i == xth-1)) fprintf(stderr,"%s = %i\n", name, *((int *) value));
1584 //value += sizeof(int);
1585 break;
1586 default:
1587 case(string_type):
1588 if (value != NULL) {
1589 //if (maxlength == -1) maxlength = strlen((char *)value); // get maximum size of string array
1590 maxlength = MAXSTRINGSIZE;
1591 length = maxlength > (dummy-dummy1) ? (dummy-dummy1) : maxlength; // cap at maximum
1592 strncpy((char *)value, dummy1, length); // copy as much
1593 ((char *)value)[length] = '\0'; // and set end marker
1594 if ((verbose) && (i == xth-1)) fprintf(stderr,"%s is '%s' (%i chars)\n",name,((char *) value), length);
1595 //value += sizeof(char);
1596 } else {
1597 }
1598 break;
1599 }
1600 }
1601 while (*dummy == '\t')
1602 dummy++;
1603 }
1604 }
1605 }
1606 }
1607 }
1608 if ((type >= row_int) && (verbose)) fprintf(stderr,"\n");
1609 if (!sequential) {
1610 //fprintf(stdout,"Rewinding to OldCurrentLine due to sequential %d.\n", sequential);
1611 FileBuffer->CurrentLine = OldCurrentLine; // rewind to start position
1612 }
1613 if (verbose) fprintf(stderr, "End of Parsing for %s\n\n",name);
1614
1615 return (found); // true if found, false if not
1616}
1617
1618/** Reading of Thermostat related values from parameter file.
1619 * \param *fb file buffer containing the config file
1620 */
1621void config::ParseThermostats(class ConfigFileBuffer * const fb)
1622{
1623 char * const thermo = new char[12];
1624 const int verbose = 0;
1625 ThermoStatContainer *Thermostats = World::getInstance().getThermostats();
1626
1627 // read desired Thermostat from file along with needed additional parameters
1628 if (ParseForParameter(verbose,fb,"Thermostat", 0, 1, 1, string_type, thermo, 1, optional)) {
1629 Thermostats->makeActive(thermo,fb);
1630 } else {
1631 if ((Thermostats->TargetTemp != 0))
1632 DoLog(2) && (Log() << Verbose(2) << "No thermostat chosen despite finite temperature MD, falling back to None." << endl);
1633 Thermostats->chooseNone();
1634 }
1635 delete[](thermo);
1636};
1637
Note: See TracBrowser for help on using the repository browser.