source: src/config.cpp@ 435065

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

Moved files bondgraph.?pp -> Graph/BondGraph.?pp.

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