source: src/config.cpp@ 9dba5f

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 9dba5f was fcac72, checked in by Frederik Heber <heber@…>, 14 years ago

Added multiple time steps to PcpParser::OutputAtoms().

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