-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestsystems.py
4556 lines (3354 loc) · 165 KB
/
testsystems.py
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
### This is a slightly modified version of the OpenMMTools "testsystems" file.
### Changes have been made to the Lennard-Jones Pair test-system, specifically,
### setting the force to be NonBonded with CutOffPeriodic.
"""
Module to generate Systems and positions for simple reference molecular systems for testing.
DESCRIPTION
This module provides functions for building a number of test systems of varying complexity,
useful for testing both OpenMM and various codes based on pyopenmm.
Note that the PYOPENMM_SOURCE_DIR must be set to point to where the PyOpenMM package is unpacked.
EXAMPLES
Create a 3D harmonic oscillator.
>>> from openmmtools import testsystems
>>> ho = testsystems.HarmonicOscillator()
>>> system, positions = ho.system, ho.positions
See list of methods for a complete list of provided test systems.
COPYRIGHT
@author John D. Chodera <[email protected]>
@author Randall J. Radmer <[email protected]>
All code in this repository is released under the MIT License.
This program is free software: you can redistribute it and/or modify it under
the terms of the MIT License.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the MIT License for more details.
You should have received a copy of the MIT License along with this program.
TODO
* Add units checking code to check arguments.
* Change default arguments to Quantity objects, rather than None?
"""
import os
import os.path
import numpy as np
import numpy.random
import itertools
import copy
import inspect
import scipy
import scipy.special
import scipy.integrate
from simtk import openmm
from simtk import unit
from simtk.openmm import app
#from .constants import kB
kB = unit.BOLTZMANN_CONSTANT_kB * unit.AVOGADRO_CONSTANT_NA
ONE_4PI_EPS0 = 138.935456
# Standard-state volume for a single molecule in a box of size (1 L) / (avogadros number).
LITER = 1000.0 * unit.centimeters**3
STANDARD_STATE_VOLUME = LITER / (unit.AVOGADRO_CONSTANT_NA*unit.mole)
pi = np.pi
DEFAULT_EWALD_ERROR_TOLERANCE = 1.0e-5 # default Ewald error tolerance
DEFAULT_CUTOFF_DISTANCE = 10.0 * unit.angstroms # default cutoff distance
DEFAULT_SWITCH_WIDTH = 1.5 * unit.angstroms # default switch width
#=============================================================================================
# SUBROUTINES
#=============================================================================================
def unwrap_py2(func):
"""Unwrap a wrapped function.
The function inspect.unwrap has been implemented only in Python 3.4. With
Python 2, this works only for functions wrapped by wraps_py2().
"""
unwrapped_func = func
try:
while True:
unwrapped_func = unwrapped_func.__wrapped__
except AttributeError:
return unwrapped_func
def handle_kwargs(func, defaults, input_kwargs):
"""Override defaults with provided kwargs that appear in `func` signature.
Parameters
----------
func : function
The function to which the resulting modified kwargs is to be fed
defaults : dict
The default kwargs.
input_kwargs: dict
Input kwargs, which should override default kwargs or be added to output kwargs
if the key is present in the function signature.
Returns
-------
kwargs : dict
Dictionary of kwargs that appear in function signature.
"""
# Get arguments that appear in function signature.
args, _, _, kwarg_defaults = inspect.getargspec(unwrap_py2(func))
# Add defaults
kwargs = { k : v for (k,v) in defaults.items() }
# Override those that appear in args
kwargs.update({ k : v for (k,v) in input_kwargs.items() if k in args })
return kwargs
def in_openmm_units(quantity):
"""Strip the units from a simtk.unit.Quantity object after converting to natural OpenMM units
Parameters
----------
quantity : simtk.unit.Quantity
The quantity to convert
Returns
-------
unitless_quantity : float
The quantity in natural OpenMM units, stripped of units.
"""
unitless_quantity = quantity.in_unit_system(unit.md_unit_system)
unitless_quantity /= unitless_quantity.unit
return unitless_quantity
def get_data_filename(relative_path):
"""Get the full path to one of the reference files in testsystems.
In the source distribution, these files are in ``openmmtools/data/*/``,
but on installation, they're moved to somewhere in the user's python
site-packages directory.
Parameters
----------
name : str
Name of the file to load (with respect to the repex folder).
"""
from pkg_resources import resource_filename
fn = resource_filename('openmmtools', relative_path)
if not os.path.exists(fn):
raise ValueError("Sorry! %s does not exist. If you just added it, you'll have to re-install" % fn)
return fn
def halton_sequence(p, n):
"""
Halton deterministic sequence on [0,1].
Parameters
----------
p : int
Prime number for sequence.
n : int
Sequence length to generate.
Returns
-------
u : numpy.array of double
Sequence on [0,1].
Notes
-----
Code source: http://blue.math.buffalo.edu/sauer2py/
More info: http://en.wikipedia.org/wiki/Halton_sequence
Examples
--------
Generate some sequences with different prime number bases.
>>> x = halton_sequence(2,100)
>>> y = halton_sequence(3,100)
>>> z = halton_sequence(5,100)
"""
eps = np.finfo(np.double).eps
# largest number of digits (adding one for halton_sequence(2,64) corner case)
b = np.zeros(int(np.ceil(np.log(n) / np.log(p))) + 1)
u = np.empty(n)
for j in range(n):
i = 0
b[0] += 1 # add one to current integer
while b[i] > p - 1 + eps: # this loop does carrying in base p
b[i] = 0
i = i + 1
b[i] += 1
u[j] = 0
for k in range(len(b)): # add up reversed digits
u[j] += b[k] * p**-(k + 1)
return u
def subrandom_particle_positions(nparticles, box_vectors, method='sobol'):
"""Generate a deterministic list of subrandom particle positions.
Parameters
----------
nparticles : int
The number of particles.
box_vectors : simtk.unit.Quantity of (3,3) with units compatible with nanometer
Periodic box vectors in which particles should lie.
method : str, optional, default='sobol'
Method for creating subrandom sequence (one of 'halton' or 'sobol')
Returns
-------
positions : simtk.unit.Quantity of (natoms,3) with units compatible with nanometer
The particle positions.
Examples
--------
>>> nparticles = 216
>>> box_vectors = openmm.System().getDefaultPeriodicBoxVectors()
>>> positions = subrandom_particle_positions(nparticles, box_vectors)
Use halton sequence:
>>> nparticles = 216
>>> box_vectors = openmm.System().getDefaultPeriodicBoxVectors()
>>> positions = subrandom_particle_positions(nparticles, box_vectors, method='halton')
"""
# Create positions array.
positions = unit.Quantity(np.zeros([nparticles, 3], np.float32), unit.nanometers)
if method == 'halton':
# Fill in each dimension.
primes = [2, 3, 5] # prime bases for Halton sequence
for dim in range(3):
x = halton_sequence(primes[dim], nparticles)
l = box_vectors[dim][dim]
positions[:, dim] = unit.Quantity(x * l / l.unit, l.unit)
elif method == 'sobol':
# Generate Sobol' sequence.
from openmmtools import sobol
ivec = sobol.i4_sobol_generate(3, nparticles, 1)
x = np.array(ivec, np.float32)
for dim in range(3):
l = box_vectors[dim][dim]
positions[:, dim] = unit.Quantity(x[dim, :] * l / l.unit, l.unit)
else:
raise Exception("method '%s' must be 'halton' or 'sobol'" % method)
return positions
def build_lattice_cell():
"""Build a single (4 atom) unit cell of a FCC lattice, assuming a cell length
of 1.0.
Returns
-------
xyz : np.ndarray, shape=(4, 3), dtype=float
Coordinates of each particle in cell
"""
xyz = [[0, 0, 0], [0, 0.5, 0.5], [0.5, 0.5, 0], [0.5, 0, 0.5]]
xyz = np.array(xyz)
return xyz
def build_lattice(n_particles):
"""Build a FCC lattice with n_particles, where (n_particles / 4) must be a cubed integer.
Parameters
----------
n_particles : int
How many particles.
Returns
-------
xyz : np.ndarray, shape=(n_particles, 3), dtype=float
Coordinates of each particle in box. Each subcell is based on a unit-sized
cell output by build_lattice_cell()
n : int
The number of cells along each direction. Because each cell has unit
length, `n` is also the total box length of the `n_particles` system.
Notes
-----
Equations eyeballed from http://en.wikipedia.org/wiki/Close-packing_of_equal_spheres
"""
n = ((n_particles / 4.) ** (1 / 3.))
if np.abs(n - np.round(n)) > 1E-10:
raise(ValueError("Must input 4 m^3 particles for some integer m!"))
else:
n = int(np.round(n))
xyz = []
cell = build_lattice_cell()
x, y, z = np.eye(3)
for atom, (i, j, k) in enumerate(itertools.product(np.arange(n), repeat=3)):
xi = cell + i * x + j * y + k * z
xyz.append(xi)
xyz = np.concatenate(xyz)
return xyz, n
def generate_dummy_trajectory(xyz, box):
"""Convert xyz coordinates and box vectors into an MDTraj Trajectory (with Topology)."""
try:
import mdtraj as md
import pandas as pd
except ImportError as e:
print("Error: generate_dummy_trajectory() requires mdtraj and pandas!")
raise(e)
n_atoms = len(xyz)
data = []
for i in range(n_atoms):
data.append(dict(serial=i, name="H", element="H", resSeq=i + 1, resName="UNK", chainID=0))
data = pd.DataFrame(data)
unitcell_lengths = box * np.ones((1, 3))
unitcell_angles = 90 * np.ones((1, 3))
top = md.Topology.from_dataframe(data, np.zeros((0, 2), dtype='int'))
traj = md.Trajectory(xyz, top, unitcell_lengths=unitcell_lengths, unitcell_angles=unitcell_angles)
return traj
def construct_restraining_potential(particle_indices, K):
"""Make a CustomExternalForce that puts an origin-centered spring on the chosen particles"""
# Add a restraining potential centered at the origin.
energy_expression = '(K/2.0) * (x^2 + y^2 + z^2);'
energy_expression += 'K = %f;' % (K / (unit.kilojoules_per_mole / unit.nanometers ** 2)) # in OpenMM units
force = openmm.CustomExternalForce(energy_expression)
for particle_index in particle_indices:
force.addParticle(particle_index, [])
return force
#=============================================================================================
# Thermodynamic state description
#=============================================================================================
class ThermodynamicState(object):
"""Object describing a thermodynamic state obeying Boltzmann statistics.
Examples
--------
Specify an NVT state for a water box at 298 K.
>>> from openmmtools import testsystems
>>> system_container = testsystems.WaterBox()
>>> (system, positions) = system_container.system, system_container.positions
>>> state = ThermodynamicState(system=system, temperature=298.0*unit.kelvin)
Specify an NPT state at 298 K and 1 atm pressure.
>>> state = ThermodynamicState(system=system, temperature=298.0*unit.kelvin, pressure=1.0*unit.atmospheres)
Note that the pressure is only relevant for periodic systems.
A barostat will be added to the system if none is attached.
Notes
-----
This state object cannot describe states obeying non-Boltzamnn statistics, such as Tsallis statistics.
ToDo
----
* Implement a more fundamental ProbabilityState as a base class?
* Implement pH.
"""
def __init__(self, system=None, temperature=None, pressure=None):
"""Construct a thermodynamic state with given system and temperature.
Parameters
----------
system : simtk.openmm.System, optional, default=None
System object describing the potential energy function for the system
temperature : simtk.unit.Quantity compatible with 'kelvin', optional, default=None
Temperature for a system with constant temperature
pressure : simtk.unit.Quantity compatible with 'atmospheres', optional, default=None
If not None, specifies the pressure for constant-pressure systems.
"""
self.system = system
self.temperature = temperature
self.pressure = pressure
return
#=============================================================================================
# Abstract base class for test systems
#=============================================================================================
class TestSystem(object):
"""Abstract base class for test systems, demonstrating how to implement a test system.
Parameters
----------
Attributes
----------
system : simtk.openmm.System
System object for the test system
positions : list
positions of test system
topology : list
topology of the test system
Notes
-----
Unimplemented methods will default to the base class methods, which raise a NotImplementedException.
Examples
--------
Create a test system.
>>> testsystem = TestSystem()
Retrieve a deep copy of the System object.
>>> system = testsystem.system
Retrieve a deep copy of the positions.
>>> positions = testsystem.positions
Retrieve a deep copy of the topology.
>>> topology = testsystem.topology
Serialize system and positions to XML (to aid in debugging).
>>> (system_xml, positions_xml) = testsystem.serialize()
"""
def __init__(self, **kwargs):
"""Abstract base class for test system.
Parameters
----------
"""
# Create an empty system object.
self._system = openmm.System()
# Store positions.
self._positions = unit.Quantity(np.zeros([0, 3], np.float), unit.nanometers)
# Empty topology.
self._topology = app.Topology()
# MDTraj Topology is built on demand.
self._mdtraj_topology = None
return
@property
def system(self):
"""The simtk.openmm.System object corresponding to the test system."""
return self._system
@system.setter
def system(self, value):
self._system = value
@system.deleter
def system(self):
del self._system
@property
def positions(self):
"""The simtk.unit.Quantity object containing the particle positions, with units compatible with simtk.unit.nanometers."""
return self._positions
@positions.setter
def positions(self, value):
self._positions = value
@positions.deleter
def positions(self):
del self._positions
@property
def topology(self):
"""The simtk.openmm.app.Topology object corresponding to the test system."""
return self._topology
@topology.setter
def topology(self, value):
self._topology = value
self._mdtraj_topology = None
@topology.deleter
def topology(self):
del self._topology
@property
def mdtraj_topology(self):
"""The mdtraj.Topology object corresponding to the test system (read-only)."""
import mdtraj as md
if self._mdtraj_topology is None:
self._mdtraj_topology = md.Topology.from_openmm(self._topology)
return self._mdtraj_topology
@property
def analytical_properties(self):
"""A list of available analytical properties, accessible via 'get_propertyname(thermodynamic_state)' calls."""
return [method[4:] for method in dir(self) if (method[0:4] == 'get_')]
def reduced_potential_expectation(self, state_sampled_from, state_evaluated_in):
"""Calculate the expected potential energy in state_sampled_from, divided by kB * T in state_evaluated_in.
Notes
-----
This is not called get_reduced_potential_expectation because this function
requires two, not one, inputs.
"""
if hasattr(self, "get_potential_expectation"):
U = self.get_potential_expectation(state_sampled_from)
U_red = U / (kB * state_evaluated_in.temperature)
return U_red
else:
raise AttributeError("Cannot return reduced potential energy because system lacks get_potential_expectation")
def serialize(self):
"""Return the System and positions in serialized XML form.
Returns
-------
system_xml : str
Serialized XML form of System object.
state_xml : str
Serialized XML form of State object containing particle positions.
"""
from simtk.openmm import XmlSerializer
# Serialize System.
system_xml = XmlSerializer.serialize(self._system)
# Serialize positions via State.
if self._system.getNumParticles() == 0:
# Cannot serialize the State of a system with no particles.
state_xml = None
else:
platform = openmm.Platform.getPlatformByName('Reference')
integrator = openmm.VerletIntegrator(1.0 * unit.femtoseconds)
context = openmm.Context(self._system, integrator, platform)
context.setPositions(self._positions)
state = context.getState(getPositions=True)
del context, integrator
state_xml = XmlSerializer.serialize(state)
return (system_xml, state_xml)
@property
def name(self):
"""The name of the test system."""
return self.__class__.__name__
class CustomExternalForcesTestSystem(TestSystem):
"""Create a system with an arbitrary number of CustomExternalForces.
Parameters
----------
energy_expressions : tuple(string)
Each string in the tuple will add a CustomExternalForce to the
OpenMM system. Each force will be assigned a different force
group, starting with 0. By default this will be a 3D harmonic oscillator.
mass : simtk.unit.Quantity, optional, default=39.948 * unit.amu
particle mass. Default corresponds to argon.
n_particles : int, optional, default=500
Number of (identical) particles to add.
Notes
-----
This may be useful for testing multiple timestep integrators.
"""
def __init__(self, energy_expressions=("x^2 + y^2 + z^2",), mass=39.948 * unit.amu, n_particles=500, **kwargs):
TestSystem.__init__(self, **kwargs)
system = openmm.System()
for n in range(n_particles):
system.addParticle(mass)
positions = unit.Quantity(np.zeros([n_particles, 3], np.float32), unit.angstroms)
forces = [openmm.CustomExternalForce(energy_expression) for energy_expression in energy_expressions]
for i, force in enumerate(forces):
for n in range(n_particles):
parameters = ()
force.addParticle(n, parameters)
force.setForceGroup(i)
system.addForce(force)
# Create topology.
topology = app.Topology()
element = app.Element.getBySymbol('Ar')
chain = topology.addChain()
for particle in range(n_particles):
residue = topology.addResidue('Ar', chain)
topology.addAtom('Ar', element, residue)
self.topology = topology
self.system, self.positions = system, positions
self.n_particles = n_particles
self.mass = mass
self.ndof = 3 * n_particles
#=============================================================================================
# 3D harmonic oscillator
#=============================================================================================
class HarmonicOscillator(TestSystem):
"""Create a 3D harmonic oscillator, with a single particle confined in an isotropic harmonic well.
Parameters
----------
K : simtk.unit.Quantity, optional, default=100.0 * unit.kilocalories_per_mole/unit.angstrom**2
harmonic restraining potential
mass : simtk.unit.Quantity, optional, default=39.948 * unit.amu
particle mass
U0 : simtk.unit.Quantity, optional, default=0.0 * unit.kilocalories_per_mole
Potential offset for harmonic oscillator
The functional form is given by
U(x) = (K/2) * ( (x-x0)^2 + y^2 + z^2 ) + U0
Attributes
----------
system : simtk.openmm.System
Openmm system with the harmonic oscillator
positions : list
positions of harmonic oscillator
Context parameters
------------------
testsystems_HarmonicOscillator_K
Spring constant of harmonic oscillator
testsystems_HarmonicOscillator_x0
Reference x position for harmonic oscillator
testsystems_HarmonicOscillator_U0
Reference potential additive constant for harmonic oscillator
Notes
-----
The natural period of a harmonic oscillator is T = 2*pi*sqrt(m/K), so you will want to use an
integration timestep smaller than ~ T/10.
The standard deviation in position in each dimension is sigma = (kT / K)^(1/2)
The expectation and standard deviation of the potential energy of a 3D harmonic oscillator is (3/2)kT.
Examples
--------
Create a 3D harmonic oscillator with default parameters:
>>> ho = HarmonicOscillator()
>>> (system, positions) = ho.system, ho.positions
Create a harmonic oscillator with specified mass and spring constant:
>>> mass = 12.0 * unit.amu
>>> K = 1.0 * unit.kilocalories_per_mole / unit.angstroms**2
>>> ho = HarmonicOscillator(K=K, mass=mass)
>>> (system, positions) = ho.system, ho.positions
Get a list of the available analytically-computed properties.
>>> print(ho.analytical_properties)
['potential_expectation', 'potential_standard_deviation']
Compute the potential expectation and standard deviation
>>> import simtk.unit as u
>>> thermodynamic_state = ThermodynamicState(temperature=298.0*u.kelvin, system=system)
>>> potential_mean = ho.get_potential_expectation(thermodynamic_state)
>>> potential_stddev = ho.get_potential_standard_deviation(thermodynamic_state)
TODO:
* Add getters and setters for K, x0, U0 that access current global parameter in system
* Add method to compute free energy of the harmonic oscillator(s)
"""
def __init__(self, K=100.0*unit.kilocalories_per_mole / unit.angstroms**2, mass=39.948*unit.amu, U0=0.0*unit.kilojoules_per_mole, **kwargs):
TestSystem.__init__(self, **kwargs)
# Create an empty system object.
system = openmm.System()
# Add the particle to the system.
system.addParticle(mass)
# Set the positions.
positions = unit.Quantity(np.zeros([1, 3], np.float32), unit.angstroms)
# Enlarge periodic box vectors, just in case
edge = 1000 * unit.nanometers
system.setDefaultPeriodicBoxVectors([edge,0,0], [0,edge,0], [0,0,edge])
# Add a restrining potential centered at the origin.
energy_expression = '(K/2.0) * ((x-x0)^2 + y^2 + z^2) + U0;'
energy_expression += 'K = testsystems_HarmonicOscillator_K;'
energy_expression += 'x0 = testsystems_HarmonicOscillator_x0;'
energy_expression += 'U0 = testsystems_HarmonicOscillator_U0;'
force = openmm.CustomExternalForce(energy_expression)
force.addGlobalParameter('testsystems_HarmonicOscillator_K', K.value_in_unit_system(unit.md_unit_system))
force.addGlobalParameter('testsystems_HarmonicOscillator_x0', 0.0)
force.addGlobalParameter('testsystems_HarmonicOscillator_U0', U0.value_in_unit_system(unit.md_unit_system))
force.addParticle(0, [])
system.addForce(force)
# Create topology.
topology = app.Topology()
element = app.Element.getBySymbol('Ar')
chain = topology.addChain()
residue = topology.addResidue('OSC', chain)
topology.addAtom('Ar', element, residue)
self.topology = topology
self.K, self.mass, self.U0 = K, mass, U0
self.system, self.positions = system, positions
# Number of degrees of freedom.
self.ndof = 3
def get_potential_expectation(self, state):
"""Return the expectation of the potential energy, computed analytically or numerically.
Arguments
---------
state : ThermodynamicState with temperature defined
The thermodynamic state at which the property is to be computed.
Returns
-------
potential_mean : simtk.unit.Quantity compatible with simtk.unit.kilojoules_per_mole
The expectation of the potential energy.
"""
return (3. / 2.) * kB * state.temperature
def get_potential_standard_deviation(self, state):
"""Return the standard deviation of the potential energy, computed analytically or numerically.
Arguments
---------
state : ThermodynamicState with temperature defined
The thermodynamic state at which the property is to be computed.
Returns
-------
potential_stddev : simtk.unit.Quantity compatible with simtk.unit.kilojoules_per_mole
potential energy standard deviation if implemented, or else None
"""
return (3. / 2.) * kB * state.temperature
class PowerOscillator(TestSystem):
"""Create a 3D Power oscillator, with a single particle confined in an isotropic x^b well.
Parameters
----------
K : simtk.unit.Quantity, optional, default=100.0
harmonic restraining potential. The units depend on the power,
so we accept unitless inputs and add units of the form
unit.kilocalories_per_mole / unit.angstrom ** b
mass : simtk.unit.Quantity, optional, default=39.948 * unit.amu
particle mass
Attributes
----------
system : simtk.openmm.System
Openmm system with the harmonic oscillator
positions : list
positions of harmonic oscillator
Notes
-----
Here we assume a potential energy of the form U(x) = k * x^b.
By the generalized equipartition theorem, the expectation of the
potential energy is 3 kT / b.
"""
def __init__(self, K=100.0, b=2.0, mass=39.948 * unit.amu, **kwargs):
TestSystem.__init__(self, **kwargs)
K = K * unit.kilocalories_per_mole / unit.angstroms ** b
# Create an empty system object.
system = openmm.System()
# Add the particle to the system.
system.addParticle(mass)
# Set the positions.
positions = unit.Quantity(np.zeros([1, 3], np.float32), unit.angstroms)
# Add a restrining potential centered at the origin.
energy_expression = 'K * (x^%d + y^%d + z^%d);' % (b, b, b)
energy_expression += 'K = testsystems_PowerOscillator_K;'
force = openmm.CustomExternalForce(energy_expression)
force.addGlobalParameter('testsystems_PowerOscillator_K', K)
force.addParticle(0, [])
system.addForce(force)
# Create topology.
topology = app.Topology()
element = app.Element.getBySymbol('Ar')
chain = topology.addChain()
residue = topology.addResidue('OSC', chain)
topology.addAtom('Ar', element, residue)
self.topology = topology
self.K, self.mass = K, mass
self.b = b
self.system, self.positions = system, positions
# Number of degrees of freedom.
self.ndof = 3
def get_potential_expectation(self, state):
"""Return the expectation of the potential energy, computed analytically or numerically.
Arguments
---------
state : ThermodynamicState with temperature defined
The thermodynamic state at which the property is to be computed.
Returns
-------
potential_mean : simtk.unit.Quantity compatible with simtk.unit.kilojoules_per_mole
The expectation of the potential energy.
"""
return (3.) * kB * state.temperature / self.b
def _get_power_expectation(self, state, n):
"""Return the power of x^n. Not currently used"""
b = 1.0 * self.b
beta = (1.0 * kB * state.temperature) ** -1.
gamma = scipy.special.gamma
return (self.K * beta) ** (-n / b) * gamma((n + 1.) / b) / gamma(1. / b)
@classmethod
def reduced_potential(cls, beta, a, b, a2, b2):
gamma = scipy.special.gamma
reduced_u = 3 * a2 * (a * beta) ** (-b2 / b) * gamma((b2 + 1.) / b) / gamma(1. / b) * beta
return reduced_u
#=============================================================================================
# Diatomic molecule
#=============================================================================================
class Diatom(TestSystem):
"""Create a free diatomic molecule with a single harmonic bond between the two atoms.
Parameters
----------
K : simtk.unit.Quantity, optional, default=290.1 * unit.kilocalories_per_mole / unit.angstrom**2
harmonic bond potential. default is GAFF c-c bond
r0 : simtk.unit.Quantity, optional, default=1.550 * unit.amu
bond length. Default is Amber GAFF c-c bond.
constraint : bool, default=False
if True, the bond length will be constrained
m1 : simtk.unit.Quantity, optional, default=12.01 * unit.amu
particle1 mass
m2 : simtk.unit.Quantity, optional, default=12.01 * unit.amu
particle2 mass
use_central_potential : bool, optional, default=False
if True, a soft central potential will also be added to keep the system from drifting away
Notes
-----
The natural period of a harmonic oscillator is T = sqrt(m/K), so you will want to use an
integration timestep smaller than ~ T/10.
Examples
--------
Create a Diatom:
>>> diatom = Diatom()
>>> system, positions = diatom.system, diatom.positions
Create a Diatom with constraint in a central potential
>>> diatom = Diatom(constraint=True, use_central_potential=True)
>>> system, positions = diatom.system, diatom.positions
"""
def __init__(self,
K=290.1 * unit.kilocalories_per_mole / unit.angstrom**2,
r0=1.550 * unit.angstroms,
m1=39.948 * unit.amu,
m2=39.948 * unit.amu,
constraint=False,
use_central_potential=False, **kwargs):
TestSystem.__init__(self, **kwargs)
# Create an empty system object.
system = openmm.System()
# Add two particles to the system.
system.addParticle(m1)
system.addParticle(m2)
# Add a harmonic bond.
force = openmm.HarmonicBondForce()
force.addBond(0, 1, r0, K)
system.addForce(force)
if constraint:
# Add constraint between particles.
system.addConstraint(0, 1, r0)
# Set the positions.
positions = unit.Quantity(np.zeros([2, 3], np.float32), unit.angstroms)
positions[1, 0] = r0
if use_central_potential:
# Add a central restraining potential.
Kcentral = 1.0 * unit.kilocalories_per_mole / unit.nanometer**2
energy_expression = '(K/2.0) * (x^2 + y^2 + z^2);'
energy_expression += 'K = testsystems_Diatom_Kcentral;'
force = openmm.CustomExternalForce(energy_expression)
force.addGlobalParameter('testsystems_Diatom_Kcentral', Kcentral)
force.addParticle(0, [])
force.addParticle(1, [])
system.addForce(force)