Coverage for ase/md/melchionna.py: 68.90%
283 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""Constant pressure/stress and temperature dynamics.
3**This dynamics is not recommended due to stability problems.**
5Combined Nose-Hoover and Parrinello-Rahman dynamics, creating an NPT
6(or N,stress,T) ensemble.
8The method is the one proposed by Melchionna et al. [1] and later
9modified by Melchionna [2]. The differential equations are integrated
10using a centered difference method [3].
12 1. S. Melchionna, G. Ciccotti and B. L. Holian, "Hoover NPT dynamics
13 for systems varying in shape and size", Molecular Physics 78, p. 533
14 (1993).
16 2. S. Melchionna, "Constrained systems and statistical distribution",
17 Physical Review E, 61, p. 6165 (2000).
19 3. B. L. Holian, A. J. De Groot, W. G. Hoover, and C. G. Hoover,
20 "Time-reversible equilibrium and nonequilibrium isothermal-isobaric
21 simulations with centered-difference Stoermer algorithms.", Physical
22 Review A, 41, p. 4552 (1990).
23"""
25import sys
26import weakref
27from typing import IO
29import numpy as np
31from ase import Atoms, units
32from ase.md.md import MolecularDynamics
34linalg = np.linalg
36# Delayed imports: If the trajectory object is reading a special ASAP version
37# of HooverNPT, that class is imported from Asap.Dynamics.NPTDynamics.
40class MelchionnaNPT(MolecularDynamics):
41 classname = 'MelchionnaNPT' # Used by the trajectory.
42 _npt_version = 2 # Version number, used for Asap compatibility.
44 def __init__(
45 self,
46 atoms: Atoms,
47 timestep: float,
48 temperature: float | None = None,
49 externalstress: float | None = None,
50 ttime: float | None = None,
51 pfactor: float | None = None,
52 *,
53 temperature_K: float | None = None,
54 mask: tuple[int] | np.ndarray | None = None,
55 trajectory: str | None = None,
56 logfile: IO | str | None = None,
57 loginterval: int = 1,
58 append_trajectory: bool = False,
59 ):
60 """Constant pressure/stress and temperature dynamics.
62 Combined Nose-Hoover and Parrinello-Rahman dynamics, creating an
63 NPT (or N,stress,T) ensemble.
65 The method is the one proposed by Melchionna et al. [1]_ and later
66 modified by Melchionna [2]_. The differential equations are integrated
67 using a centered difference method [3]_. See also NPTdynamics.tex
69 Parameters
70 ----------
71 atoms: Atoms object
72 The list of atoms.
74 timestep: float
75 The timestep in units matching eV, Å, u.
77 temperature: float (deprecated)
78 The desired temperature in eV.
80 temperature_K: float
81 The desired temperature in K.
83 externalstress: float or nparray
84 The external stress in eV/A^3. Either a symmetric
85 3x3 tensor, a 6-vector representing the same, or a
86 scalar representing the pressure. Note that the
87 stress is positive in tension whereas the pressure is
88 positive in compression: giving a scalar p is
89 equivalent to giving the tensor (-p, -p, -p, 0, 0, 0).
91 ttime: float
92 Characteristic timescale of the thermostat, in ASE internal units
93 Set to None to disable the thermostat.
95 WARNING: Not specifying ttime sets it to None, disabling the
96 thermostat.
98 pfactor: float
99 A constant in the barostat differential equation. If
100 a characteristic barostat timescale of ptime is
101 desired, set pfactor to ptime^2 * B
102 (where ptime is in units matching
103 eV, Å, u; and B is the Bulk Modulus, given in eV/Å^3).
104 Set to None to disable the barostat.
105 Typical metallic bulk moduli are of the order of
106 100 GPa or 0.6 eV/A^3.
108 WARNING: Not specifying pfactor sets it to None, disabling the
109 barostat.
111 mask: None or 3-tuple or 3x3 nparray (optional)
112 Optional argument. A tuple of three integers (0 or 1),
113 indicating if the system can change size along the
114 three Cartesian axes. Set to (1,1,1) or None to allow
115 a fully flexible computational box. Set to (1,1,0)
116 to disallow elongations along the z-axis etc.
117 mask may also be specified as a symmetric 3x3 array
118 indicating which strain values may change.
120 Notes
121 -----
122 **This module is not recommended!** There is a strong tendency for
123 oscillations in the temperature and/or pressure, unless the starting
124 configuration is chosen with great care.
126 * The same timestep can be used as in Verlet dynamics, i.e. 5 fs is fine
127 for bulk copper.
129 * The ttime and pfactor are quite critical [4]_, too small values may
130 cause instabilites and/or wrong fluctuations in T / p. Too
131 large values cause an oscillation which is slow to die. Good
132 values for the characteristic times seem to be 25 fs for ttime,
133 and 75 fs for ptime (used to calculate pfactor), at least for
134 bulk copper with 15000-200000 atoms. But this is not well
135 tested, it is IMPORTANT to monitor the temperature and
136 stress/pressure fluctuations.
138 References
139 ----------
140 .. [1] S. Melchionna, G. Ciccotti and B. L. Holian,
141 Mol. Phys. 78, 533–544 (1993).
142 https://doi.org/10.1080/00268979300100371
144 .. [2] S. Melchionna,
145 Phys. Rev. E 61, 6165–6170 (2000).
146 https://doi.org/10.1103/PhysRevE.61.6165
148 .. [3] B. L. Holian, A. J. De Groot, W. G. Hoover, and C. G. Hoover,
149 Phys. Rev. A 41, 4552–4553 (1990).
150 https://doi.org/10.1103/PhysRevA.41.4552
152 .. [4] F. D. Di Tolla and M. Ronchetti,
153 Phys. Rev. E 48, 1726–1737 (1993).
154 https://doi.org/10.1103/PhysRevE.48.1726
156 """
158 MolecularDynamics.__init__(
159 self,
160 atoms,
161 timestep,
162 trajectory,
163 logfile,
164 loginterval,
165 append_trajectory=append_trajectory,
166 )
167 # self.atoms = atoms
168 # self.timestep = timestep
169 if externalstress is None and pfactor is not None:
170 raise TypeError("Missing 'externalstress' argument.")
171 self.zero_center_of_mass_momentum(verbose=1)
172 self.temperature = units.kB * self._process_temperature(
173 temperature, temperature_K, 'eV'
174 )
175 if externalstress is not None:
176 self.set_stress(externalstress)
177 self.set_mask(mask)
178 self.eta = np.zeros((3, 3), float)
179 self.zeta = 0.0
180 self.zeta_integrated = 0.0
181 self.initialized = 0
182 self.ttime = ttime
183 self.pfactor_given = pfactor
184 self._calculateconstants()
185 self.timeelapsed = 0.0
186 self.frac_traceless = 1
188 def set_temperature(self, temperature=None, *, temperature_K=None):
189 """Set the temperature.
191 Parameters
192 ----------
194 temperature: float (deprecated)
195 The new temperature in eV. Deprecated, use ``temperature_K``.
197 temperature_K: float (keyword-only argument)
198 The new temperature, in K.
199 """
200 self.temperature = units.kB * self._process_temperature(
201 temperature, temperature_K, 'eV'
202 )
203 self._calculateconstants()
205 def set_stress(self, stress):
206 """Set the applied stress.
208 Must be a symmetric 3x3 tensor, a 6-vector representing a symmetric
209 3x3 tensor, or a number representing the pressure.
211 Use with care, it is better to set the correct stress when creating
212 the object.
213 """
215 if np.isscalar(stress):
216 stress = np.array([-stress, -stress, -stress, 0.0, 0.0, 0.0])
217 else:
218 stress = np.array(stress)
219 if stress.shape == (3, 3):
220 if not self._issymmetric(stress):
221 raise ValueError(
222 'The external stress must be a symmetric tensor.'
223 )
224 stress = np.array(
225 (
226 stress[0, 0],
227 stress[1, 1],
228 stress[2, 2],
229 stress[1, 2],
230 stress[0, 2],
231 stress[0, 1],
232 )
233 )
234 elif stress.shape != (6,):
235 raise ValueError('The external stress has the wrong shape.')
236 self.externalstress = stress
238 def set_mask(self, mask):
239 """Set the mask indicating dynamic elements of the computational box.
241 If set to None, all elements may change. If set to a 3-vector
242 of ones and zeros, elements which are zero specify directions
243 along which the size of the computational box cannot change.
244 For example, if mask = (1,1,0) the length of the system along
245 the z-axis cannot change, although xz and yz shear is still
246 possible. May also be specified as a symmetric 3x3 array indicating
247 which strain values may change.
249 Use with care, as you may "freeze in" a fluctuation in the strain rate.
250 """
251 if mask is None:
252 mask = np.ones((3,))
253 if not hasattr(mask, 'shape'):
254 mask = np.array(mask)
255 if mask.shape != (3,) and mask.shape != (3, 3):
256 raise RuntimeError(
257 'The mask has the wrong shape '
258 + '(must be a 3-vector or 3x3 matrix)'
259 )
260 else:
261 mask = np.not_equal(mask, 0) # Make sure it is 0/1
263 if mask.shape == (3,):
264 self.mask = np.outer(mask, mask)
265 else:
266 self.mask = mask
268 def set_fraction_traceless(self, fracTraceless):
269 """set what fraction of the traceless part of the force
270 on eta is kept.
272 By setting this to zero, the volume may change but the shape may not.
273 """
274 self.frac_traceless = fracTraceless
276 def get_strain_rate(self):
277 """Get the strain rate as a triangular 3x3 matrix.
279 This includes the fluctuations in the shape of the computational box.
281 """
282 return np.array(self.eta, copy=1)
284 def set_strain_rate(self, rate):
285 """Set the strain rate. Must be a triangular 3x3 matrix.
287 If you set a strain rate along a direction that is "masked out"
288 (see ``set_mask``), the strain rate along that direction will be
289 maintained constantly.
290 """
291 if not (rate.shape == (3, 3) and self._istriangular(rate)):
292 raise ValueError('Strain rate must be a triangular matrix.')
293 self.eta = rate
294 if self.initialized:
295 # Recalculate h_past and eta_past so they match the current value.
296 self._initialize_eta_h()
298 def get_time(self):
299 "Get the elapsed time."
300 return self.timeelapsed
302 def irun(self, steps):
303 """Run dynamics algorithm as generator.
305 Parameters
306 ----------
307 steps : int
308 Number of dynamics steps to be run.
310 Yields
311 ------
312 complete : bool
313 True if the maximum number of steps are reached.
314 """
316 if not self.initialized:
317 self.initialize()
318 else:
319 if self.have_the_atoms_been_changed():
320 raise NotImplementedError(
321 'You have modified the atoms since the last timestep.'
322 )
324 yield from super().irun(steps)
326 def run(self, steps):
327 """Perform a number of time steps.
329 Parameters
330 ----------
331 steps : int
332 Number of dynamics steps to be run.
334 Yields
335 ------
336 complete : bool
337 True if the maximum number of steps are reached.
338 """
340 for complete in self.irun(steps):
341 pass
342 return complete
344 def have_the_atoms_been_changed(self):
345 "Checks if the user has modified the positions or momenta of the atoms"
346 limit = 1e-10
347 h = self._getbox()
348 if max(abs((h - self.h).ravel())) > limit:
349 self._warning('The computational box has been modified.')
350 return 1
351 expected_r = np.dot(self.q + 0.5, h)
352 err = max(abs((expected_r - self.atoms.get_positions()).ravel()))
353 if err > limit:
354 self._warning(
355 'The atomic positions have been modified: ' + str(err)
356 )
357 return 1
358 return 0
360 def step(self):
361 """Perform a single time step.
363 Assumes that the forces and stresses are up to date, and that
364 the positions and momenta have not been changed since last
365 timestep.
366 """
368 # Assumes the following variables are OK
369 # q_past, q, q_future, p, eta, eta_past, zeta, zeta_past, h, h_past
370 #
371 # q corresponds to the current positions
372 # p must be equal to self.atoms.GetCartesianMomenta()
373 # h must be equal to self.atoms.GetUnitCell()
374 #
375 # print "Making a timestep"
376 dt = self.dt
377 h_future = self.h_past + 2 * dt * np.dot(self.h, self.eta)
378 if self.pfactor_given is None:
379 deltaeta = np.zeros(6, float)
380 else:
381 stress = self.stresscalculator()
382 deltaeta = (
383 -2
384 * dt
385 * (
386 self.pfact
387 * linalg.det(self.h)
388 * (stress - self.externalstress)
389 )
390 )
392 if self.frac_traceless == 1:
393 eta_future = self.eta_past + self.mask * self._maketriangular(
394 deltaeta
395 )
396 else:
397 trace_part, traceless_part = self._separatetrace(
398 self._maketriangular(deltaeta)
399 )
400 eta_future = (
401 self.eta_past
402 + trace_part
403 + self.frac_traceless * traceless_part
404 )
406 deltazeta = (
407 2
408 * dt
409 * self.tfact
410 * (self.atoms.get_kinetic_energy() - self.desiredEkin)
411 )
412 zeta_future = self.zeta_past + deltazeta
413 # Advance time
414 self.timeelapsed += dt
415 self.h_past = self.h
416 self.h = h_future
417 self.inv_h = linalg.inv(self.h)
418 self.q_past = self.q
419 self.q = self.q_future
420 self._setbox_and_positions(self.h, self.q)
421 self.eta_past = self.eta
422 self.eta = eta_future
423 self.zeta_past = self.zeta
424 self.zeta = zeta_future
425 self._synchronize() # for parallel simulations.
426 self.zeta_integrated += dt * self.zeta
427 force = self.forcecalculator()
428 self._calculate_q_future(force)
429 self.atoms.set_momenta(
430 np.dot(self.q_future - self.q_past, self.h / (2 * dt))
431 * self._getmasses()
432 )
433 # self.stresscalculator()
435 def forcecalculator(self):
436 return self.atoms.get_forces(md=True)
438 def stresscalculator(self):
439 return self.atoms.get_stress(include_ideal_gas=True)
441 def initialize(self):
442 """Initialize the dynamics.
444 The dynamics requires positions etc for the two last times to
445 do a timestep, so the algorithm is not self-starting. This
446 method performs a 'backwards' timestep to generate a
447 configuration before the current.
449 This is called automatically the first time ``run()`` is called.
450 """
451 # print "Initializing the NPT dynamics."
452 dt = self.dt
453 atoms = self.atoms
454 self.h = self._getbox()
455 if not self._istriangular(self.h):
456 raise NotImplementedError(
457 f'Can (so far) only operate on lists of atoms where the '
458 f'computational box is a triangular matrix. {self.h}'
459 )
460 self.inv_h = linalg.inv(self.h)
461 # The contents of the q arrays should migrate in parallel simulations.
462 # self._make_special_q_arrays()
463 self.q = np.dot(self.atoms.get_positions(), self.inv_h) - 0.5
464 # zeta and eta were set in __init__
465 self._initialize_eta_h()
466 deltazeta = (
467 dt * self.tfact * (atoms.get_kinetic_energy() - self.desiredEkin)
468 )
469 self.zeta_past = self.zeta - deltazeta
470 self._calculate_q_past_and_future()
471 self.initialized = 1
473 def get_gibbs_free_energy(self):
474 """Return the Gibb's free energy, which is supposed to be conserved.
476 Requires that the energies of the atoms are up to date.
478 This is mainly intended as a diagnostic tool. If called before the
479 first timestep, Initialize will be called.
480 """
481 if not self.initialized:
482 self.initialize()
483 n = self._getnatoms()
484 # tretaTeta = sum(diagonal(matrixmultiply(transpose(self.eta),
485 # self.eta)))
486 contractedeta = np.sum((self.eta * self.eta).ravel())
487 gibbs = (
488 self.atoms.get_potential_energy()
489 + self.atoms.get_kinetic_energy()
490 - np.sum(self.externalstress[0:3]) * linalg.det(self.h) / 3.0
491 )
492 if self.ttime is not None:
493 gibbs += (
494 1.5 * n * self.temperature * (self.ttime * self.zeta) ** 2
495 + 3 * self.temperature * (n - 1) * self.zeta_integrated
496 )
497 else:
498 assert self.zeta == 0.0
499 if self.pfactor_given is not None:
500 gibbs += 0.5 / self.pfact * contractedeta
501 else:
502 assert contractedeta == 0.0
503 return gibbs
505 def get_center_of_mass_momentum(self):
506 "Get the center of mass momentum."
507 return self.atoms.get_momenta().sum(0)
509 def zero_center_of_mass_momentum(self, verbose=0):
510 "Set the center of mass momentum to zero."
511 cm = self.get_center_of_mass_momentum()
512 abscm = np.sqrt(np.sum(cm * cm))
513 if verbose and abscm > 1e-4:
514 self._warning(
515 self.classname
516 + ': Setting the center-of-mass momentum to zero '
517 '(was %.6g %.6g %.6g)' % tuple(cm)
518 )
519 self.atoms.set_momenta(
520 self.atoms.get_momenta() - cm / self._getnatoms()
521 )
523 def attach_atoms(self, atoms):
524 """Assign atoms to a restored dynamics object.
526 This function must be called to set the atoms immediately after the
527 dynamics object has been read from a trajectory.
528 """
529 try:
530 self.atoms
531 except AttributeError:
532 pass
533 else:
534 raise RuntimeError(
535 'Cannot call attach_atoms on a dynamics '
536 'which already has atoms.'
537 )
538 MolecularDynamics.__init__(self, atoms, self.dt)
539 limit = 1e-6
540 h = self._getbox()
541 if max(abs((h - self.h).ravel())) > limit:
542 raise RuntimeError(
543 'The unit cell of the atoms does not match '
544 'the unit cell stored in the file.'
545 )
546 self.inv_h = linalg.inv(self.h)
547 self.q = np.dot(self.atoms.get_positions(), self.inv_h) - 0.5
548 self._calculate_q_past_and_future()
549 self.initialized = 1
551 def attach(self, function, interval=1, *args, **kwargs):
552 """Attach callback function or trajectory.
554 At every *interval* steps, call *function* with arguments
555 *args* and keyword arguments *kwargs*.
557 If *function* is a trajectory object, its write() method is
558 attached, but if *function* is a BundleTrajectory (or another
559 trajectory supporting set_extra_data(), said method is first
560 used to instruct the trajectory to also save internal
561 data from the NPT dynamics object.
562 """
563 if hasattr(function, 'set_extra_data'):
564 # We are attaching a BundleTrajectory or similar
565 function.set_extra_data(
566 'npt_init', WeakMethodWrapper(self, 'get_init_data'), once=True
567 )
568 function.set_extra_data(
569 'npt_dynamics', WeakMethodWrapper(self, 'get_data')
570 )
571 MolecularDynamics.attach(self, function, interval, *args, **kwargs)
573 def get_init_data(self):
574 "Return the data needed to initialize a new NPT dynamics."
575 return {
576 'dt': self.dt,
577 'temperature': self.temperature,
578 'desiredEkin': self.desiredEkin,
579 'externalstress': self.externalstress,
580 'mask': self.mask,
581 'ttime': self.ttime,
582 'tfact': self.tfact,
583 'pfactor_given': self.pfactor_given,
584 'pfact': self.pfact,
585 'frac_traceless': self.frac_traceless,
586 }
588 def get_data(self):
589 "Return data needed to restore the state."
590 return {
591 'eta': self.eta,
592 'eta_past': self.eta_past,
593 'zeta': self.zeta,
594 'zeta_past': self.zeta_past,
595 'zeta_integrated': self.zeta_integrated,
596 'h': self.h,
597 'h_past': self.h_past,
598 'timeelapsed': self.timeelapsed,
599 }
601 @classmethod
602 def read_from_trajectory(cls, trajectory, frame=-1, atoms=None):
603 """Read dynamics and atoms from trajectory (Class method).
605 Simultaneously reads the atoms and the dynamics from a BundleTrajectory,
606 including the internal data of the NPT dynamics object (automatically
607 saved when attaching a BundleTrajectory to an NPT object).
609 Arguments:
611 trajectory
612 The filename or an open BundleTrajectory object.
614 frame (optional)
615 Which frame to read. Default: the last.
617 atoms (optional, internal use only)
618 Pre-read atoms. Do not use.
619 """
620 if isinstance(trajectory, str):
621 if trajectory.endswith('/'):
622 trajectory = trajectory[:-1]
623 if trajectory.endswith('.bundle'):
624 from ase.io.bundletrajectory import BundleTrajectory
626 trajectory = BundleTrajectory(trajectory)
627 else:
628 raise ValueError(
629 f"Cannot open '{trajectory}': unsupported file format"
630 )
631 # trajectory is now a BundleTrajectory object (or compatible)
632 if atoms is None:
633 atoms = trajectory[frame]
634 init_data = trajectory.read_extra_data('npt_init', 0)
635 frame_data = trajectory.read_extra_data('npt_dynamics', frame)
636 dyn = cls(
637 atoms,
638 timestep=init_data['dt'],
639 temperature=init_data['temperature'],
640 externalstress=init_data['externalstress'],
641 ttime=init_data['ttime'],
642 pfactor=init_data['pfactor_given'],
643 mask=init_data['mask'],
644 )
645 dyn.desiredEkin = init_data['desiredEkin']
646 dyn.tfact = init_data['tfact']
647 dyn.pfact = init_data['pfact']
648 dyn.frac_traceless = init_data['frac_traceless']
649 for k, v in frame_data.items():
650 setattr(dyn, k, v)
651 return (dyn, atoms)
653 def _getbox(self):
654 "Get the computational box."
655 return self.atoms.get_cell()
657 def _getmasses(self):
658 "Get the masses as an Nx1 array."
659 return np.reshape(self.atoms.get_masses(), (-1, 1))
661 def _separatetrace(self, mat):
662 """return two matrices, one proportional to the identity
663 the other traceless, which sum to the given matrix
664 """
665 tracePart = ((mat[0][0] + mat[1][1] + mat[2][2]) / 3.0) * np.identity(3)
666 return tracePart, mat - tracePart
668 # A number of convenient helper methods
669 def _warning(self, text):
670 "Emit a warning."
671 sys.stderr.write('WARNING: ' + text + '\n')
672 sys.stderr.flush()
674 def _calculate_q_future(self, force):
675 "Calculate future q. Needed in Timestep and Initialization."
676 dt = self.dt
677 id3 = np.identity(3)
678 alpha = (dt * dt) * np.dot(force / self._getmasses(), self.inv_h)
679 beta = dt * np.dot(
680 self.h, np.dot(self.eta + 0.5 * self.zeta * id3, self.inv_h)
681 )
682 inv_b = linalg.inv(beta + id3)
683 self.q_future = np.dot(
684 2 * self.q + np.dot(self.q_past, beta - id3) + alpha, inv_b
685 )
687 def _calculate_q_past_and_future(self):
688 def ekin(p, m=self.atoms.get_masses()):
689 p2 = np.sum(p * p, -1)
690 return 0.5 * np.sum(p2 / m) / len(m)
692 p0 = self.atoms.get_momenta()
693 m = self._getmasses()
694 p = np.array(p0, copy=1)
695 dt = self.dt
696 for i in range(2):
697 self.q_past = self.q - dt * np.dot(p / m, self.inv_h)
698 self._calculate_q_future(self.atoms.get_forces(md=True))
699 p = np.dot(self.q_future - self.q_past, self.h / (2 * dt)) * m
700 e = ekin(p)
701 if e < 1e-5:
702 # The kinetic energy and momenta are virtually zero
703 return
704 p = (p0 - p) + p0
706 def _initialize_eta_h(self):
707 self.h_past = self.h - self.dt * np.dot(self.h, self.eta)
708 if self.pfactor_given is None:
709 deltaeta = np.zeros(6, float)
710 else:
711 deltaeta = (
712 -self.dt
713 * self.pfact
714 * linalg.det(self.h)
715 * (self.stresscalculator() - self.externalstress)
716 )
717 if self.frac_traceless == 1:
718 self.eta_past = self.eta - self.mask * self._maketriangular(
719 deltaeta
720 )
721 else:
722 trace_part, traceless_part = self._separatetrace(
723 self._maketriangular(deltaeta)
724 )
725 self.eta_past = (
726 self.eta - trace_part - self.frac_traceless * traceless_part
727 )
729 @staticmethod
730 def _isuppertriangular(m) -> bool:
731 "Check that a 3x3 matrix is of upper triangular form."
732 return m[1, 0] == m[2, 0] == m[2, 1] == 0.0
734 @classmethod
735 def _islowertriangular(cls, m) -> bool:
736 "Check that a 3x3 matrix is of lower triangular form."
737 return cls._isuppertriangular(m.T)
739 @classmethod
740 def _istriangular(cls, m) -> bool:
741 "Check that a 3x3 matrix is of triangular form."
742 return cls._isuppertriangular(m) or cls._islowertriangular(m)
744 def _maketriangular(self, sixvector):
745 "Make 3x3 triangular matrix from a 6-vector."
746 if self._isuppertriangular(self.h):
747 return np.array(
748 (
749 (sixvector[0], sixvector[5], sixvector[4]),
750 (0, sixvector[1], sixvector[3]),
751 (0, 0, sixvector[2]),
752 )
753 )
755 if self._islowertriangular(self.h):
756 return np.array(
757 (
758 (sixvector[0], 0, 0),
759 (sixvector[5], sixvector[1], 0),
760 (sixvector[4], sixvector[3], sixvector[2]),
761 )
762 )
764 def _calculateconstants(self):
765 """(Re)calculate some constants when pfactor,
766 ttime or temperature have been changed."""
768 n = self._getnatoms()
769 if self.ttime is None:
770 self.tfact = 0.0
771 else:
772 self.tfact = 2.0 / (
773 3 * n * self.temperature * self.ttime * self.ttime
774 )
775 if self.pfactor_given is None:
776 self.pfact = 0.0
777 else:
778 self.pfact = 1.0 / (self.pfactor_given * linalg.det(self._getbox()))
779 # self.pfact = 1.0/(n * self.temperature * self.ptime * self.ptime)
780 self.desiredEkin = 1.5 * (n - 1) * self.temperature
782 def _setbox_and_positions(self, h, q):
783 """Set the computational box and the positions."""
784 self.atoms.set_cell(h)
785 r = np.dot(q + 0.5, h)
786 self.atoms.set_positions(r)
788 # A few helper methods, which have been placed in separate methods
789 # so they can be replaced in the parallel version.
790 def _synchronize(self):
791 """Synchronize eta, h and zeta on all processors.
793 In a parallel simulation, eta, h and zeta are communicated
794 from the master to all slaves, to prevent numerical noise from
795 causing them to diverge.
797 In a serial simulation, do nothing.
798 """
799 # This is a serial simulation object. Do nothing.
801 def _getnatoms(self):
802 """Get the number of atoms.
804 In a parallel simulation, this is the total number of atoms on all
805 processors.
806 """
807 return len(self.atoms)
809 def _make_special_q_arrays(self):
810 """Make the arrays used to store data about the atoms.
812 In a parallel simulation, these are migrating arrays. In a
813 serial simulation they are ordinary Numeric arrays.
814 """
815 natoms = len(self.atoms)
816 self.q = np.zeros((natoms, 3), float)
817 self.q_past = np.zeros((natoms, 3), float)
818 self.q_future = np.zeros((natoms, 3), float)
821class WeakMethodWrapper:
822 """A weak reference to a method.
824 Create an object storing a weak reference to an instance and
825 the name of the method to call. When called, calls the method.
827 Just storing a weak reference to a bound method would not work,
828 as the bound method object would go away immediately.
829 """
831 def __init__(self, obj, method):
832 self.obj = weakref.proxy(obj)
833 self.method = method
835 def __call__(self, *args, **kwargs):
836 m = getattr(self.obj, self.method)
837 return m(*args, **kwargs)