File: snapShotManager.C

package info (click to toggle)
ball 1.5.0%2Bgit20180813.37fc53c-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 239,848 kB
  • sloc: cpp: 326,149; ansic: 4,208; python: 2,303; yacc: 1,778; lex: 1,099; xml: 958; sh: 322; makefile: 93
file content (626 lines) | stat: -rw-r--r-- 17,595 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: snapShotManager.C,v 1.15.20.2 2007/06/09 16:08:08 anhi Exp $
//

#include <BALL/KERNEL/PTE.h>
#include <BALL/MOLMEC/COMMON/snapShotManager.h>
#include <BALL/MOLMEC/COMMON/forceField.h>
#include <BALL/FORMAT/trajectoryFile.h>

#include <iostream>

using namespace std;

namespace BALL
{

	// Definition of class-specific options and default values
	const char *SnapShotManager::Option::FLUSH_TO_DISK_FREQUENCY = "flush_to_disk_frequency";
	const Size SnapShotManager::Default::FLUSH_TO_DISK_FREQUENCY = 10;

	SnapShotManager::SnapShotManager()
		: options(),
		  system_ptr_(0),
		  force_field_ptr_(0),
		  snapshot_buffer_(0),
		  trajectory_file_ptr_(0),
		  flush_to_disk_frequency_(0),
		  buffer_counter_(0),
		  current_snapshot_(0)
	{
		options.setDefaultInteger(SnapShotManager::Option::FLUSH_TO_DISK_FREQUENCY,
		                          SnapShotManager::Default::FLUSH_TO_DISK_FREQUENCY);
	}

	// The constructor of the SnapshotManager.  
	// It expects a valid system, a force field, and a filename  of a
	// snapshot file along with a boolean that indicates if an existing file
	// shall be overwritten.  If the file does not exist yet, it will be
	// created and a header consisting of the system and some internal
	// information will be written to it.  If the file is already existent,
	// the header will read in and compared
	// with the given system. They must match.  Subsequent snapshots will
	// then be appended to the file.
	SnapShotManager::SnapShotManager(System* my_system, const ForceField* my_forcefield,
	                                 TrajectoryFile* file)
		: options(),
		  system_ptr_(my_system),
		  force_field_ptr_(my_forcefield),
		  snapshot_buffer_(0),
		  trajectory_file_ptr_(file),
		  flush_to_disk_frequency_(0),
		  buffer_counter_(0),
		  current_snapshot_(0)
	{
		options.setDefaultInteger(SnapShotManager::Option::FLUSH_TO_DISK_FREQUENCY,
		                          SnapShotManager::Default::FLUSH_TO_DISK_FREQUENCY);

		// call the setup method
		setup();
	}

	SnapShotManager::SnapShotManager(System* my_system, TrajectoryFile* file)
		: options(),
		  system_ptr_(my_system),
		  force_field_ptr_(0),
		  snapshot_buffer_(0),
		  trajectory_file_ptr_(file),
		  flush_to_disk_frequency_(0),
		  buffer_counter_(0),
		  current_snapshot_(0)
	{
		options.setDefaultInteger(SnapShotManager::Option::FLUSH_TO_DISK_FREQUENCY,
		                          SnapShotManager::Default::FLUSH_TO_DISK_FREQUENCY);

		// call the setup method
		setup();
	}

	// The constructor of the SnapshotManager.
	// It expects a valid system and force field, a filename  of a snapshot
	// file along with a boolean that indicates if an existing file shall be
	// overwritten, and the options.  If the file does not exist yet, it will
	// be created and a header consisting of the system and some internal
	// information will be written to it.  If the file is already existent
	// the header will read in and compared
	// with the given system. They must match. Subsequent snapshots will be
	// appended to the file. 
	SnapShotManager::SnapShotManager(System* my_system, const ForceField* my_forcefield,
	                                 const Options& my_options, TrajectoryFile* file)
		: options(my_options),
		  system_ptr_(my_system),
		  force_field_ptr_(my_forcefield),
		  snapshot_buffer_(0),
		  trajectory_file_ptr_(file),
		  flush_to_disk_frequency_(0),
		  buffer_counter_(0),
		  current_snapshot_(0)
	{
		// simply call the setup method
		setup();
	}


	// The copy constructor of the SnapShotManager
	// All data will be copied. But the copy will flush snapshots to the same
	// file as the original instance and it will use the same system and
	// force field!
	// NOTE, that this copy constructor DOES NOT copy the system and force
	// field but only the pointers!
	SnapShotManager::SnapShotManager (const SnapShotManager& manager)
		: options(manager.options),
		  system_ptr_(manager.system_ptr_),
		  force_field_ptr_(manager.force_field_ptr_),
		  snapshot_buffer_(manager.snapshot_buffer_),
		  trajectory_file_ptr_(manager.trajectory_file_ptr_),
		  flush_to_disk_frequency_(manager.flush_to_disk_frequency_),
		  buffer_counter_(0),
		  current_snapshot_(0)
	{
	}

	// The destructor of SnapShotManager 
	SnapShotManager::~SnapShotManager()
	{
		// clear() handles open files, so the destructor does not handle them
		clear();
	}

	const SnapShotManager& SnapShotManager::operator = (const SnapShotManager& manager)
	{
		options = manager.options;
		system_ptr_ = manager.system_ptr_;
		force_field_ptr_ = manager.force_field_ptr_;
		snapshot_buffer_ = manager.snapshot_buffer_;
		trajectory_file_ptr_ = manager.trajectory_file_ptr_;
		flush_to_disk_frequency_ = manager.flush_to_disk_frequency_;
		buffer_counter_ = 0;
		current_snapshot_ = 0;

		return *this;
	}

	void SnapShotManager::clear()
	{
		// bring the instance to initial state
		options.clear();
		system_ptr_ = 0;
		force_field_ptr_ = 0;
		snapshot_buffer_.clear();
		// this destructor does not destruct or clear the associated
		// trajectory file
		trajectory_file_ptr_ = 0;
		flush_to_disk_frequency_ = (Size)options.getInteger(SnapShotManager::Option::FLUSH_TO_DISK_FREQUENCY);
		buffer_counter_ = 0;
		current_snapshot_ = 0;
	}

	bool SnapShotManager::isValid() const
	{
		// first test for existence of system and force field
		if (system_ptr_ == 0 || !system_ptr_->isValid())
		{
			Log.error() << "SnapShotManager::setup(): No/invalid system." << endl;
			return false;
		}

		/// we dont really always need a force field, do we ?????
		if (force_field_ptr_ == 0) return true;

		if (!force_field_ptr_->isValid())
		{
			Log.error() << "SnapShotManager::setup(): No/invald force field." << endl;
			return false;
		}

		// now check that the force field is assigned to the system
		if (force_field_ptr_->getSystem() != system_ptr_)
		{
			Log.error() << "SnapShotManager::setup(): Systems do not match." << endl;
			return false;
		}

		return true;
	}


	// The setup method does the actual preparations
	bool SnapShotManager::setup(System* my_system, const ForceField* my_forcefield,
	                            TrajectoryFile* my_snapshot_file)
	{
		setSystem(my_system);
		setForceField(my_forcefield);
		setTrajectoryFile(my_snapshot_file);
		return setup();
	}

	// The setup method does the actual preparations
	bool SnapShotManager::setup(System* my_system, TrajectoryFile* my_snapshot_file)
	{
		setSystem(my_system);
		setForceField(0);
		setTrajectoryFile(my_snapshot_file);
		return setup();
	}

	// The setup method does the actual preparations
	bool SnapShotManager::setup()
	{
		if (!isValid()) return false;

		// first get the options
		flush_to_disk_frequency_ = (Size)options.getInteger(SnapShotManager::Option::FLUSH_TO_DISK_FREQUENCY);

		// if there was already snapshot data, clear it.
		// clear() does too much... Should I rewrite setup()? Or do I believe,
		// that setup is called only(!) in a constructor?
		snapshot_buffer_.clear();
		current_snapshot_ = 0;
		buffer_counter_ = 0;
		return true;
	}

	// This method calculates the current kinetic energy of the system
	// (only selected atoms are considered) 
	double SnapShotManager::calculateKineticEnergy_()
	{
		if (force_field_ptr_ == 0) return 0;

		// First define some local variables 
		double sq_velocity;
		double sum, result;

		AtomVector::Iterator atom_it;
		AtomVector selected_atoms;

		sum = 0.0;
		selected_atoms = force_field_ptr_->getAtoms();

		// The current temperature (calculated as instantaneous kinetic energy)
		// If we use a periodic boundary box, then we use the molecules' centres of
		// gravity, otherwise we iterate directly over the individual atoms of the system 

		atom_it = selected_atoms.begin();

		if (force_field_ptr_->periodic_boundary.isEnabled())
		{
			float molecule_mass = 0;
			float mass;

			int no_of_molecules = 0;

			Molecule *old, *current;
			Vector3 centre_velocity;
			centre_velocity.x = centre_velocity.y = centre_velocity.z = 0;

			// Get the molecule of the first atom in the system 
			old = (*atom_it)->getMolecule();

			// Iterate over all atoms in the system and determine for every
			// molecule the velocity of its centre of mass
			// This velocity contributes to the overall temperature 
			AtomVector::Iterator end_it = selected_atoms.end();

			while (atom_it != end_it)
			{
				// determine the molecule of the current atom
				current = (*atom_it)->getMolecule();

				if (current != old)
				{
					// This atom belongs to an other molecule than the 
					// previous atom -> all atoms of the previous 
					// molecule have been visited
					centre_velocity /= molecule_mass;
					sq_velocity = centre_velocity * centre_velocity;
					sum += molecule_mass * sq_velocity;

					no_of_molecules++;

					// reset some values for the new molecule
					molecule_mass = 0;
					centre_velocity.x = centre_velocity.y = centre_velocity.z = 0;

					// the new molecule is now the old one
					old = current;
				}

				// add the atom's velocity to the total velocity  
				// of the current molecule
				mass = (*atom_it)->getElement().getAtomicWeight();
				molecule_mass += mass;
				centre_velocity += mass * (*atom_it)->getVelocity();

				// go on to the next atom
				++atom_it;
			}

			// The last molecule must be added as this is not done in the while-loop
			if (molecule_mass == 0)
			{
				// A strange molecule. Let the centre_velocity as it is
			}
			else
			{
				centre_velocity /= molecule_mass;
			}

			sq_velocity = centre_velocity * centre_velocity;
			sum += molecule_mass * sq_velocity;
			no_of_molecules++;

			// 0.01 scales Da*A^2/ps^2 to kJ/mol 
			result = 0.5 * sum * 0.01;
		}
		else
		{
			// Iterate over all atoms and calculate \sum m_i \cdot v_i^2  
			for (atom_it = selected_atoms.begin(); atom_it != selected_atoms.end(); ++atom_it)
			{
				sq_velocity = (*atom_it)->getVelocity() * (*atom_it)->getVelocity();
				sum += (*atom_it)->getElement().getAtomicWeight() * sq_velocity;
			}

			// 0.01 scales Da*A^2/ps^2 to kJ/mol 
			result = 0.5 * sum * 0.01;
		}

		return result;

	} // end of 'calculateKineticEnergy'


	void SnapShotManager::setSystem(System* my_system)
	{
		system_ptr_ = my_system;
	}


	System* SnapShotManager::getSystem() const
	{
		return system_ptr_;
	}


	void SnapShotManager::setForceField(const ForceField* my_ff)
	{
		force_field_ptr_ = my_ff;
	}


	const ForceField* SnapShotManager::getForceField() const
	{
		return force_field_ptr_;
	}


	void SnapShotManager::setTrajectoryFile(TrajectoryFile* my_file)
	{
		trajectory_file_ptr_ = my_file;
	}


	TrajectoryFile* SnapShotManager::getTrajectoryFile() const
	{
		return trajectory_file_ptr_;
	}


	void SnapShotManager::setFlushToDiskFrequency(Size number)
	{
		flush_to_disk_frequency_ = number;
	}


	Size SnapShotManager::getFlushToDiskFrequency() const
	{
		return flush_to_disk_frequency_;
	}


	// The following is not true at the moment...
	// This method takes a snapshot of the system's current state and stores
	// it in memory. If no memory is available or a maximum number of
	// snapshots has been taken, all snapshots so far are saved to disk The
	// first snapshot taken (and with no other previous snapshots in a file)
	// has index 1. 
	void SnapShotManager::takeSnapShot()
	{
		if (system_ptr_ == 0) return;

		// One more snapshot. Add it to the current list of snapshots
		// The way we do it here should be faster, than filling the 
		// SnapShot with data first and pushing it into the vector afterwards.
		snapshot_buffer_.push_back(SnapShot());
		SnapShot& snapshot = snapshot_buffer_[snapshot_buffer_.size() - 1];

		// store all current positions, forces, velocities in the
		// snapshot object
		snapshot.takeSnapShot(*system_ptr_);

		// store the potential energies      
		if (force_field_ptr_ != 0)
		{
			snapshot.setPotentialEnergy(force_field_ptr_->getEnergy());
		}

		// store the kinetic energy of all selected atoms in the system 
		// the current value must be calculated as it is not provided by
		// the force field 
		snapshot.setKineticEnergy(calculateKineticEnergy_());

		buffer_counter_++;

		// We could! use pushback() and size() to determine when to flush the
		// buffers, but this is faster. 
		if (buffer_counter_ >= flush_to_disk_frequency_)
		{
			// write all snapshots to disk in order to prevent memory overflow
			flushToDisk();
		}
	} // end of SnapShotManager::takeSnapShot()


	bool SnapShotManager::applySnapShot(Size number)
	{
		// we start at SnapShot number 1!
		if (number > 0) number --;

		if (system_ptr_ == 0) return false;

		// if we have read the Snapshots from the trajectory file
		// use these, otherwise "seek" to the correct file position
		if (!snapshot_buffer_.empty())
		{
			if (snapshot_buffer_.size() <= number) return false;

			snapshot_buffer_[number].applySnapShot(*system_ptr_);
			current_snapshot_ = number;
			return true;
		}

		// ok, we are gone read from the file
		if (trajectory_file_ptr_ == 0) return false;

		SnapShot buffer;

		if (number >= trajectory_file_ptr_->getNumberOfSnapShots())
		{
			Log.error() << "SnapShotManager::applySnapShot(): "
			            << "requested SnapShot number " << number
			            << " while the file only contains "
			            << trajectory_file_ptr_->getNumberOfSnapShots()
			            << " SnapShots" << endl;
			return false;
		}

		// We have to avoid seek() so we need to reopen and read from the
		// beginning
		trajectory_file_ptr_->reopen();
		trajectory_file_ptr_->readHeader();
		for (Size count = 0; count <= number; ++count)
		{
			if (!trajectory_file_ptr_->read(buffer))
			{
				Log.error() << "SnapShotManager::applySnapShot(): "
				            << "error reading from the TrajectoryFile" << endl;
				return false;
			}
		}
		// now apply the last snapshot we read
		buffer.applySnapShot(*system_ptr_);
		current_snapshot_ = number;
		return true;
	}


	bool SnapShotManager::applyFirstSnapShot()
	{
		if (system_ptr_ == 0) return false;

		// if we have read the Snapshots from the trajectory file
		// use these, otherwise read one Snapshot from the file
		if (!snapshot_buffer_.empty())
		{
			snapshot_buffer_[0].applySnapShot(*system_ptr_);
			current_snapshot_ = 0;
			return true;
		}

		// ok, we are gone read from the file
		if (trajectory_file_ptr_ == 0) return false;

		trajectory_file_ptr_->reopen();
		trajectory_file_ptr_->readHeader();
		current_snapshot_ = 0;

		if (trajectory_file_ptr_->getNumberOfSnapShots() == 0) return false;

		return applyNextSnapShot();
	}


	bool SnapShotManager::applyNextSnapShot()
	{
		if (system_ptr_ == 0) return false;

		// if we have read the Snapshots from the trajectory file
		// use these, otherwise read one Snapshot from the file
		if (!snapshot_buffer_.empty())
		{
			current_snapshot_++;
			if (current_snapshot_ >= snapshot_buffer_.size()) return false;

			snapshot_buffer_[current_snapshot_].applySnapShot(*system_ptr_);
			return true;
		}

		// ok, we are gone read from the file
		if (trajectory_file_ptr_ == 0) return false;

		SnapShot buffer;

		if (trajectory_file_ptr_->read(buffer))
		{
			buffer.applySnapShot(*system_ptr_);
			current_snapshot_++;
			return true;
		}
		else
		{
			Log.error() << "SnapShotManager::applyNextSnapShot() "
			            << "error reading from the TrajectoryFile" << endl;
			return false;
		}
	}


	bool SnapShotManager::applyLastSnapShot()
	{
		if (system_ptr_ == 0) return false;

		// if we have read the Snapshots from the trajectory file
		// use these, otherwise read one Snapshot from the file
		if (!snapshot_buffer_.empty())
		{
			snapshot_buffer_[snapshot_buffer_.size() - 1].applySnapShot(*system_ptr_);
			current_snapshot_ = snapshot_buffer_.size() - 1;
			return true;
		}

		// ok, we are gone read from the file
		if (trajectory_file_ptr_ == 0) return false;

		Size count = 0;
		SnapShot buffer;

		while (trajectory_file_ptr_->read(buffer))
		{
			count++;
		}

		if (count == trajectory_file_ptr_->getNumberOfSnapShots())
		{
			buffer.applySnapShot(*system_ptr_);
			current_snapshot_ = count - 1;
			return true;
		}

		Log.error() << "SnapShotManager::applyLastSnapShot(): "
		            << "read " << count
		            << " SnapShots while TrajectoryFile claims to have "
		            << trajectory_file_ptr_->getNumberOfSnapShots()
		            << " SnapShots" << endl;

		return false;
	}


	// This method writes all snapshots in memory to the snapshot file on disk
	void SnapShotManager::flushToDisk()
	{
		// if no snapshots are in main memory, then there is nothing to do
		// also abort, if no trajectory file was set
		if (snapshot_buffer_.empty() || !trajectory_file_ptr_)
		{
			return;
		}

		trajectory_file_ptr_->flushToDisk(snapshot_buffer_);
		snapshot_buffer_.clear();
		buffer_counter_ = 0;
	}

	bool SnapShotManager::readFromFile()
	{
		if (trajectory_file_ptr_ == 0) return false;
		snapshot_buffer_.clear();

		trajectory_file_ptr_->reopen();
		trajectory_file_ptr_->readHeader();
		Size number = trajectory_file_ptr_->getNumberOfSnapShots();
		for (Size count = 0; count < number; ++count)
		{
			SnapShot buffer;
			if (!trajectory_file_ptr_->read(buffer))
			{
				Log.error() << "SnapShotManager::Could not read "
				            << "from the TrajectoryFile (Out of memory?)" << endl;
				return false;
			}
			snapshot_buffer_.push_back(buffer);
		}

		return true;
	}

	void SnapShotManager::clearBuffer()
	{
		snapshot_buffer_.clear();
		current_snapshot_ = 0;
		buffer_counter_ = 0;
	}

}