-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathdriver.py
1868 lines (1508 loc) · 83.9 KB
/
driver.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
# coding=utf-8
"""
Drivers for Monte Carlo sampling of chemical states, such as tautomers and protomers.
"""
import copy
import logging
import math
import random
import re
import sys
import numpy as np
import simtk
from enum import Enum
from simtk import unit as units, openmm
from .logger import log
from abc import ABCMeta, abstractmethod
from lxml import etree
from openmmtools.integrators import ExternalPerturbationLangevinIntegrator
from .integrators import GHMCIntegrator
kB = (1.0 * units.BOLTZMANN_CONSTANT_kB * units.AVOGADRO_CONSTANT_NA).in_units_of(units.kilojoules_per_mole / units.kelvin)
class _BaseDrive(object):
"""An abstract base class describing the common public interface of Drive-type classes
.. note::
Examples of a Drive class would include the _BaseProtonDrive, which has instantaneous MC, and NCMC updates of
protonation states of the system in its ``update`` method, and provides tracking tools, and calibration tools for
the relative weights of the protonation states.
"""
__metaclass__ = ABCMeta
@abstractmethod
def update(self):
"""
Update the state of the system using some kind of Monte Carlo move
"""
pass
@abstractmethod
def calibrate(self):
"""
Calibrate the relative weights, gk, of the different states of the residues that are part of the system
"""
pass
@abstractmethod
def import_gk_values(self, gk_dict):
"""
Import the relative weights, gk, of the different states of the residues that are part of the system
Parameters
----------
gk_dict : dict
dict of starting value g_k estimates in numpy arrays, with residue names as keys.
"""
pass
@abstractmethod
def reset_statistics(self):
"""
Reset statistics of titration state tracking.
"""
pass
class _BaseProtonDrive(_BaseDrive):
"""
The _BaseProtonDrive is an abstract base class Monte Carlo driver for protonation state changes and tautomerism in OpenMM.
Protonation state changes, and additionally, tautomers are treated using the constant-pH dynamics method of Mongan, Case and McCammon [Mongan2004]_, or Stern [Stern2007]_ and NCMC methods from Nilmeier [Nilmeier2011]_.
References
----------
.. [Mongan2004] Mongan J, Case DA, and McCammon JA. Constant pH molecular dynamics in generalized Born implicit solvent. J Comput Chem 25:2038, 2004.
http://dx.doi.org/10.1002/jcc.20139
.. [Stern2007] Stern HA. Molecular simulation with variable protonation states at constant pH. JCP 126:164112, 2007.
http://link.aip.org/link/doi/10.1063/1.2731781
.. [Nilmeier2011] Nonequilibrium candidate Monte Carlo is an efficient tool for equilibrium simulation. PNAS 108:E1009, 2011.
http://dx.doi.org/10.1073/pnas.1106094108
.. todo::
* Add NCMC switching moves to allow this scheme to be efficient in explicit solvent.
* Add alternative proposal types, including schemes that avoid proposing self-transitions (or always accept them):
- Parallel Monte Carlo schemes: Compute N proposals at once, and pick using Gibbs sampling or Metropolized Gibbs?
* Allow specification of probabilities for selecting N residues to change protonation state at once.
* Add automatic tuning of switching times for optimal acceptance.
* Extend to handle systems set up via OpenMM app Forcefield class.
* Make integrator optional if not using NCMC
"""
def __init__(self, system, temperature, pH, topology, compound_integrator, pressure=None,
nattempts_per_update=1, simultaneous_proposal_probability=0.1, debug=False,
ncmc_steps_per_trial=0, ncmc_prop_per_step=1, ncmc_timestep=1.0 * units.femtoseconds,
maintainChargeNeutrality=False, cationName='Na+', anionName='Cl-', implicit=False):
"""
Initialize a Monte Carlo titration driver for simulation of protonation states and tautomers.
Parameters
----------
system : simtk.openmm.System
System to be titrated, containing all possible protonation sites.
temperature : simtk.unit.Quantity compatible with kelvin
Temperature at which the system is to be simulated.
pH : float
The pH at which the system is to be simulated.
topology : simtk.openmm.app.Topology
OpenMM object containing the topology of system
compound_integrator : simtk.openmm.openmm.CompoundIntegrator
A compound integrator. The first integrator is assumed to be used for dynamics,
the second integrator is used for propagation in NCMC.
pressure : simtk.unit.Quantity compatible with atmospheres, optional, default=None
For explicit solvent simulations, the pressure.
nattempts_per_update : int, optional, default=1
Number of protonation state change attempts per update call
simultaneous_proposal_probability : float, optional, default=0.1
Probability of simultaneously proposing two updates
debug : bool, optional, default=False
Turn debug information on/off.
ncmc_steps_per_trial : int, optional, default=0
Number of perturbation steps per NCMC switching trial, or 0 if instantaneous Monte Carlo is to be used.
ncmc_prop_per_step: int, optional, default=1
Number of propagation steps for each NCMC perturbation step, unused if ncmc_steps_per_trial = 0
ncmc_timestep : simtk.unit.Quantity with units compatible with femtoseconds
Timestep to use for NCMC switching
maintainChargeNeutrality : bool, optional, default=True
If True, waters will be converted to monovalent counterions and vice-versa.
cationName : str, optional, default='Na+'
Name of cation residue from which parameters are to be taken.
anionName : str, optional, default='Cl-'
Name of anion residue from which parameters are to be taken.
implicit: bool, optional, default=False
Flag for implicit simulation. Skips ion parameter lookup.
Todo
----
* Allow constant-pH dynamics to be initialized in other ways than using the AMBER cpin file (e.g. from OpenMM app; automatically).
* Generalize simultaneous_proposal_probability to allow probability of single, double, triple, etc. proposals to be specified?
"""
if implicit and maintainChargeNeutrality:
raise ValueError("Implicit solvent and charge neutrality are mutually exclusive.")
# Set defaults.
# probability of proposing two simultaneous protonation state changes
self.simultaneous_proposal_probability = simultaneous_proposal_probability
# Store parameters.
self.system = system
self.temperature = temperature
kT = kB * temperature # thermal energy
self.beta = 1.0 / kT # inverse temperature
self.beta_unitless = strip_in_unit_system(
self.beta) # For more efficient calculation of the work (in multiples of KT) during NCMC
self.pressure = pressure
self.pH = pH
self.debug = debug
self._attempt_number = 0 # Internal tracker for current iteration attempt
self.nsteps_per_trial = ncmc_steps_per_trial
self.ncmc_prop_per_step = ncmc_prop_per_step
self.nattempts_per_update = nattempts_per_update
self.ncmc_stats_per_step = nattempts_per_update * [[None] * ncmc_steps_per_trial] # Keeps track of the last ncmc protocol attempt work.
self.nattempted = 0
self.naccepted = 0
self.nrejected = 0
self.last_proposal = [None] * nattempts_per_update
if implicit:
self.solvent = "implicit"
else:
self.solvent = "explicit"
# Create a GHMC integrator to handle NCMC integration
self.compound_integrator = compound_integrator
# Record the forces that need to be switched off for NCMC
forces = {system.getForce(index).__class__.__name__: system.getForce(index) for index in
range(system.getNumForces())}
# Control center mass remover
if 'CMMotionRemover' in forces:
self.cm_remover = forces['CMMotionRemover']
self.cm_remover_freq = self.cm_remover.getFrequency()
else:
self.cm_remover = None
self.cm_remover_freq = None
# Check that system has MonteCarloBarostat if pressure is specified
if pressure is not None:
if 'MonteCarloBarostat' not in forces:
raise Exception("`pressure` is specified, but `system` object lacks a `MonteCarloBarostat`")
# Store options for maintaining charge neutrality by converting waters to/from monovalent ions.
self.maintainChargeNeutrality = maintainChargeNeutrality
if not implicit:
self.water_residues = self._identify_water_residues(topology) # water molecules that can be converted to ions
self.anion_parameters = self._retrieve_ion_parameters(topology, system,
anionName) # dict of ['charge', 'sigma', 'epsilon'] for cation parameters
self.cation_parameters = self._retrieve_ion_parameters(topology, system,
cationName) # dict of ['charge', 'sigma', 'epsilon'] for anion parameters
self.anion_residues = list() # water molecules that have been converted to anions
self.cation_residues = list() # water molecules that have been converted to cations
# Initialize titration group records.
self.titrationGroups = list()
self.titrationStates = list()
# Keep track of forces and whether they're cached.
self.precached_forces = False
# Track simulation state
self.kin_energies = units.Quantity(list(), units.kilocalorie_per_mole)
self.pot_energies = units.Quantity(list(), units.kilocalorie_per_mole)
self.states_per_update = list()
# Determine 14 Coulomb and Lennard-Jones scaling from system.
self.coulomb14scale = self._get14scaling(system)
# Store list of exceptions that may need to be modified.
self.atomExceptions = [list() for index in range(topology.getNumAtoms())]
self._set14exceptions(system)
# Store force object pointers.
# TODO: Add Custom forces.
force_classes_to_update = ['NonbondedForce', 'GBSAOBCForce']
self.forces_to_update = list()
for force_index in range(self.system.getNumForces()):
force = self.system.getForce(force_index)
if force.__class__.__name__ in force_classes_to_update:
self.forces_to_update.append(force)
return
def _retrieve_ion_parameters(self, topology, system, resname):
"""
Retrieve parameters from specified monovalent atomic ion.
Parameters
----------
topology : simtk.openmm.app.topology
The topology from which water residues are to be identified.
system : simtk.openmm.System
The System object from which parameters are to be extracted.
resname : str
The residue name of the monovalent atomic anion or cation from which parameters are to be retrieved.
Returns
-------
parameters : dict of str:float
NonbondedForce parameter dict ('charge', 'sigma', 'epsilon') for ion parameters.
Warnings
--------
* Only `NonbondedForce` parameters are returned
* If the system contains more than one `NonbondedForce`, behavior is undefined
"""
# Find the NonbondedForce in the system
forces = {system.getForce(index).__class__.__name__: system.getForce(index) for index in range(system.getNumForces())}
nonbonded_force = forces['NonbondedForce']
# Return the first occurrence of NonbondedForce particle parameters matching `resname`
for residue in topology.residues():
if residue.name == resname:
atoms = [atom for atom in residue.atoms()]
[charge, sigma, epsilon] = nonbonded_force.getParticleParameters(atoms[0].index)
parameters = {'charge': charge, 'sigma': sigma, 'epsilon': epsilon}
if self.debug: print('_retrieve_ion_parameters: %s : %s' % (resname, str(parameters)))
return parameters
raise Exception("resname '%s' not found in topology" % resname)
def _identify_water_residues(self, topology, water_residue_names=('WAT', 'HOH', 'TP4', 'TP5', 'T4E')):
"""
Compile a list of water residues that could be converted to/from monovalent ions.
Parameters
----------
topology : simtk.openmm.app.topology
The topology from which water residues are to be identified.
water_residue_names : list of str
Residues identified as water molecules.
Returns
-------
water_residues : list of simtk.openmm.app.Residue
Water residues.
TODO
----
* Can this feature be added to simt.openmm.app.Topology?
"""
water_residues = list()
for residue in topology.residues():
if residue.name in water_residue_names:
water_residues.append(residue)
if self.debug: print('_identify_water_residues: %d water molecules identified.' % len(water_residues))
return water_residues
def _get14scaling(self, system):
"""
Determine Coulomb 14 scaling.
Parameters
----------
system : simtk.openmm.System
the system to examine
Returns
-------
coulomb14scale (float) - degree to which 1,4 coulomb interactions are scaled
"""
# Look for a NonbondedForce.
forces = {system.getForce(index).__class__.__name__: system.getForce(index) for index in range(system.getNumForces())}
force = forces['NonbondedForce']
# Determine coulomb14scale from first exception with nonzero chargeprod.
for index in range(force.getNumExceptions()):
[particle1, particle2, chargeProd, sigma, epsilon] = force.getExceptionParameters(index)
[charge1, sigma1, epsilon1] = force.getParticleParameters(particle1)
[charge2, sigma2, epsilon2] = force.getParticleParameters(particle2)
# Using 1.e-15 as necessary precision for establishing greater than 0
# Needs to be slightly larger than sys.float_info.epsilon to prevent numerical errors.
if (abs(charge1 / (units.elementary_charge)) > 1.e-15) and (abs(charge2 / units.elementary_charge) > 1.e-15) and (abs(chargeProd/(units.elementary_charge ** 2)) > 1.e-15):
coulomb14scale = chargeProd / (charge1 * charge2)
return coulomb14scale
return None
def _get14exceptions(self, system, particle_indices):
"""
Return a list of all 1,4 exceptions involving the specified particles that are not exclusions.
Parameters
----------
system : simtk.openmm.System
the system to examine
particle_indices :list of int
only exceptions involving at least one of these particles are returned
Returns
-------
exception_indices : list
list of exception indices for NonbondedForce
Todo
----
* Deal with the case where there may be multiple NonbondedForce objects.
* Deal with electrostatics implmented as CustomForce objects (by CustomNonbondedForce + CustomBondForce)
"""
# Locate NonbondedForce object.
forces = {system.getForce(index).__class__.__name__: system.getForce(index) for index in range(system.getNumForces())}
force = forces['NonbondedForce']
# Build a list of exception indices involving any of the specified particles.
exception_indices = list()
for exception_index in range(force.getNumExceptions()):
[particle1, particle2, chargeProd, sigma, epsilon] = force.getExceptionParameters(exception_index)
if (particle1 in particle_indices) or (particle2 in particle_indices):
if (particle2 in self.atomExceptions[particle1]) or (particle1 in self.atomExceptions[particle2]):
exception_indices.append(exception_index)
# BEGIN UGLY HACK
# chargeprod and sigma cannot be identically zero or else we risk the error:
# Exception: updateParametersInContext: The number of non-excluded exceptions has changed
# TODO: Once OpenMM interface permits this, omit this code.
[particle1, particle2, chargeProd, sigma, epsilon] = force.getExceptionParameters(exception_index)
if (2 * chargeProd == chargeProd):
chargeProd = sys.float_info.epsilon
if (2 * epsilon == epsilon):
epsilon = sys.float_info.epsilon
force.setExceptionParameters(exception_index, particle1, particle2, chargeProd, sigma, epsilon)
# END UGLY HACK
return exception_indices
def _set14exceptions(self, system):
"""
Collect all the NonbondedForce exceptions that pertain to 1-4 interactions.
Parameters
----------
system - OpenMM System object
Returns
-------
"""
for force in system.getForces():
if force.__class__.__name__ == "NonbondedForce":
for index in range(force.getNumExceptions()):
[atom1, atom2, chargeProd, sigma, epsilon] = force.getExceptionParameters(index)
unitless_epsilon = epsilon / units.kilojoule_per_mole
# 1-2 and 1-3 should be 0 for both chargeProd and episilon, whereas a 1-4 interaction is scaled.
# Potentially, chargeProd is 0, but epsilon should never be 0.
# Using > 1.e-15 as a reasonable float precision for being greater than 0
if abs(unitless_epsilon) > 1.e-15:
self.atomExceptions[atom1].append(atom2)
self.atomExceptions[atom2].append(atom1)
return
def reset_statistics(self):
"""
Reset statistics of titration state tracking.
Todo
----
* Keep track of more statistics regarding history of individual protonation states.
* Keep track of work values for individual trials to use for calibration.
"""
self.nattempted = 0
self.naccepted = 0
self.nrejected = 0
self.last_proposal = [None] * self.nattempts_per_update
return
@staticmethod
def _parse_fortran_namelist(filename, namelist_name):
"""
Parse a fortran namelist generated by AMBER 11 constant-pH python scripts.
Parameters
----------
filename : string
the name of the file containing the fortran namelist
namelist_name : string
name of the namelist section to parse
Returns
-------
namelist : dict
namelist[key] indexes read values, converted to Python types
Notes
-----
This code is not fully general for all Fortran namelists---it is specialized to the cpin files.
"""
# Read file contents.
infile = open(filename, 'r')
lines = infile.readlines()
infile.close()
# Concatenate all text.
contents = ''
for line in lines:
contents += line.strip()
# Extract section corresponding to keyword.
key = '&' + namelist_name
terminator = '/'
match = re.match(key + '(.*)' + terminator, contents)
contents = match.groups(1)[0]
# Parse contents.
# These regexp match strings come from fortran-namelist from Stephane Chamberland ([email protected]) [LGPL].
valueInt = re.compile(r'[+-]?[0-9]+')
valueReal = re.compile(r'[+-]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)')
valueString = re.compile(r'^[\'\"](.*)[\'\"]$')
# Parse contents.
namelist = dict()
while len(contents) > 0:
# Peel off variable name.
match = re.match(r'^([^,]+)=(.+)$', contents)
if not match:
break
name = match.group(1).strip()
contents = match.group(2).strip()
# Peel off value, which extends to either next variable name or end of section.
match = re.match(r'^([^=]+),([^,]+)=(.+)$', contents)
if match:
value = match.group(1).strip()
contents = match.group(2) + '=' + match.group(3)
else:
value = contents
contents = ''
# Split value on commas.
elements = value.split(',')
value = list()
for element in elements:
if valueReal.match(element):
element = float(element)
elif valueInt.match(element):
element = int(element)
elif valueString.match(element):
element = element[1:-1]
if element != '':
value.append(element)
if len(value) == 1:
value = value[0]
namelist[name] = value
return namelist
def _get_proton_chemical_potential(self, titration_group_index, titration_state_index):
"""Calculate the chemical potential contribution of protons of individual titratable sites.
Parameters
----------
titration_group_index : int
Index of the group
titration_state_index : int
Index of the state
Returns
-------
float
"""
titration_state = self.titrationGroups[titration_group_index]['titration_states'][titration_state_index]
proton_count = titration_state['proton_count']
pKref = titration_state['pKref']
if self.debug:
print("proton_count = %d | pH = %.1f | pKref = %.1f | %.1f " % (
proton_count, self.pH, pKref, - proton_count * (self.pH - pKref) * math.log(10)))
return proton_count * (self.pH - pKref) * math.log(10)
def _get_num_titratable_groups(self):
"""
Return the number of titratable groups.
Returns
-------
ngroups : int
the number of titratable groups that have been defined
"""
return len(self.titrationGroups)
def _add_titratable_group(self, atom_indices, name=''):
"""
Define a new titratable group.
Parameters
----------
atom_indices : list of int
the atom indices defining the titration group
Other Parameters
----------------
name : str
name of the group, e.g. Residue: LYS 13.
Notes
-----
No two titration groups may share atoms.
"""
# Check to make sure the requested group does not share atoms with any existing titration group.
for group in self.titrationGroups:
if set(group['atom_indices']).intersection(atom_indices):
raise Exception("Titration groups cannot share atoms. The requested atoms of new titration group (%s) share atoms with another group (%s)." % (
str(atom_indices), str(group['atom_indices'])))
# Define the new group.
group = dict()
group['atom_indices'] = list(atom_indices) # deep copy
group['titration_states'] = list()
group_index = len(self.titrationGroups) + 1
group['index'] = group_index
group['name'] = name
group['nstates'] = 0
# NonbondedForce exceptions associated with this titration state
group['exception_indices'] = self._get14exceptions(self.system, atom_indices)
self.titrationGroups.append(group)
# Note that we haven't yet defined any titration states, so current state is set to None.
self.titrationStates.append(None)
return group_index
def _get_num_titration_states(self, titration_group_index):
"""
Return the number of titration states defined for the specified titratable group.
Parameters
----------
titration_group_index : int
the titration group to be queried
Returns
-------
nstates : int
the number of titration states defined for the specified titration group
"""
if titration_group_index not in range(self._get_num_titratable_groups()):
raise Exception("Invalid titratable group requested. Requested %d, valid groups are in range(%d)." %
(titration_group_index, self._get_num_titratable_groups()))
return len(self.titrationGroups[titration_group_index]['titration_states'])
def _add_titration_state(self, titration_group_index, pKref, relative_energy, charges, proton_count):
"""
Add a titration state to a titratable group.
Parameters
----------
titration_group_index : int
the index of the titration group to which a new titration state is to be added
pKref : float
the pKa for the reference compound used in calibration
relative_energy : simtk.unit.Quantity with units compatible with simtk.unit.kilojoules_per_mole
the relative energy of this protonation state
charges : list or numpy array of simtk.unit.Quantity with units compatible with simtk.unit.elementary_charge
the atomic charges for this titration state
proton_count : int
number of protons in this titration state
Notes
-----
The relative free energy of a titration state is computed as
relative_energy + kT * proton_count * ln (10^(pH - pKa))
= relative_energy + kT * proton_count * (pH - pKa) * ln 10
The number of charges specified must match the number (and order) of atoms in the defined titration group.
"""
# Check input arguments.
if titration_group_index not in range(self._get_num_titratable_groups()):
raise Exception("Invalid titratable group requested. Requested %d, valid groups are in range(%d)." %
(titration_group_index, self._get_num_titratable_groups()))
if len(charges) != len(self.titrationGroups[titration_group_index]['atom_indices']):
raise Exception('The number of charges must match the number (and order) of atoms in the defined titration group.')
state = dict()
state['pKref'] = pKref
state['g_k'] = relative_energy * self.beta # dimensionless quantity
state['charges'] = copy.deepcopy(charges)
state['proton_count'] = proton_count
self.titrationGroups[titration_group_index]['titration_states'].append(state)
# Increment count of titration states and set current state to last defined state.
self.titrationStates[titration_group_index] = self.titrationGroups[titration_group_index]['nstates']
self.titrationGroups[titration_group_index]['nstates'] += 1
return
def _get_titration_state(self, titration_group_index):
"""
Return the current titration state for the specified titratable group.
Parameters
----------
titration_group_index : int
the titration group to be queried
Returns
-------
state : int
the titration state for the specified titration group
"""
if titration_group_index not in range(self._get_num_titratable_groups()):
raise Exception("Invalid titratable group requested. Requested %d, valid groups are in range(%d)." %
(titration_group_index, self._get_num_titratable_groups()))
return self.titrationStates[titration_group_index]
def _get_titration_states(self):
"""
Return the current titration states for all titratable groups.
Returns
-------
states : list of int
the titration states for all titratable groups
"""
return list(self.titrationStates) # deep copy
def _get_titration_state_total_charge(self, titration_group_index, titration_state_index):
"""
Return the total charge for the specified titration state.
Parameters
----------
titration_group_index : int
the titration group to be queried
titration_state_index : int
the titration state to be queried
Returns
-------
charge : simtk.openmm.Quantity compatible with simtk.unit.elementary_charge
total charge for the specified titration state
"""
if titration_group_index not in range(self._get_num_titratable_groups()):
raise Exception("Invalid titratable group requested. Requested %d, valid groups are in range(%d)." %
(titration_group_index, self._get_num_titratable_groups()))
if titration_state_index not in range(self._get_num_titration_states(titration_group_index)):
raise Exception("Invalid titration state requested. Requested %d, valid states are in range(%d)." %
(titration_state_index, self._get_num_titration_states(titration_group_index)))
charges = self.titrationGroups[titration_group_index]['titration_states'][titration_state_index]['charges'][:]
return simtk.unit.Quantity((charges / charges.unit).sum(), charges.unit)
def _set_titration_state(self, titration_group_index, titration_state_index, context=None, debug=False):
"""
Change the titration state of the designated group for the provided state.
Parameters
----------
titration_group_index : int
the index of the titratable group whose titration state should be updated
titration_state_index : int
the titration state to set as active
Other Parameters
----------------
context : simtk.openmm.Context
if provided, will update protonation state in the specified Context (default: None)
debug : bool
if True, will print debug information
"""
# Check parameters for validity.
if titration_group_index not in range(self._get_num_titratable_groups()):
raise Exception("Invalid titratable group requested. Requested %d, valid groups are in range(%d)." %
(titration_group_index, self._get_num_titratable_groups()))
if titration_state_index not in range(self._get_num_titration_states(titration_group_index)):
raise Exception("Invalid titration state requested. Requested %d, valid states are in range(%d)." %
(titration_state_index, self._get_num_titration_states(titration_group_index)))
self._update_forces(titration_group_index, titration_state_index, context=context)
# The context needs to be updated after the force parameters are updated
if context is not None:
for force_index, force in enumerate(self.forces_to_update):
force.updateParametersInContext(context)
self.titrationStates[titration_group_index] = titration_state_index
return
def _update_forces(self, titration_group_index, final_titration_state_index, initial_titration_state_index=None, fractional_titration_state=1.0, context=None):
"""
Update the force parameters to a new titration state by reading them from the cache.
Notes
-----
* Please ensure that the context is updated after calling this function, by using
`force.updateParametersInContext(context)` for each force that has been updated.
Parameters
----------
titration_group_index : int
Index of the group that is changing state
titration_state_index : int
Index of the state of the chosen residue
initial_titration_state_index : int, optional, default=None
If blending two titration states, the initial titration state to blend.
If `None`, set to `titration_state_index`
fractional_titration_state : float, optional, default=1.0
Fraction of `titration_state_index` to be blended with `initial_titration_state_index`.
If 0.0, `initial_titration_state_index` is fully active; if 1.0, `titration_state_index` is fully active.
context : simtk.openmm.Context, optional, default=None
If provided, will update forces state in the specified Context
Notes
-----
* Every titration state has a list called forces, which stores parameters for all forces that need updating.
* Inside each list entry is a dictionary that always contains an entry called `atoms`, with single atom parameters by name.
* NonbondedForces also have an entry called `exceptions`, containing exception parameters.
"""
# `initial_titration_state_index` should have no effect if not specified, so set it identical to `final_titration_state_index` in that case
if initial_titration_state_index is None:
initial_titration_state_index = final_titration_state_index
# Retrieve cached force parameters fro this titration state.
cache_initial = self.titrationGroups[titration_group_index]['titration_states'][initial_titration_state_index]['forces']
cache_final = self.titrationGroups[titration_group_index]['titration_states'][final_titration_state_index]['forces']
# Modify charges and exceptions.
for force_index, force in enumerate(self.forces_to_update):
# Get name of force class.
force_classname = force.__class__.__name__
# Get atom indices and charges.
# Update forces using appropriately blended parameters
for (atom_initial, atom_final) in zip(cache_initial[force_index]['atoms'], cache_final[force_index]['atoms']):
atom = {key: atom_initial[key] for key in ['atom_index']}
if force_classname == 'NonbondedForce':
# TODO : if we ever change LJ parameters, we need to look into softcore potentials
# and separate out the changes in charge, and sigma/eps into different steps.
for parameter_name in ['charge', 'sigma', 'epsilon']:
atom[parameter_name] = (1.0 - fractional_titration_state) * atom_initial[parameter_name] + \
fractional_titration_state * atom_final[parameter_name]
force.setParticleParameters(atom['atom_index'], atom['charge'], atom['sigma'], atom['epsilon'])
elif force_classname == 'GBSAOBCForce':
for parameter_name in ['charge', 'radius', 'scaleFactor']:
atom[parameter_name] = (1.0 - fractional_titration_state) * atom_initial[parameter_name] + \
fractional_titration_state * atom_final[parameter_name]
force.setParticleParameters(atom['atom_index'], atom['charge'], atom['radius'], atom['scaleFactor'])
else:
raise Exception("Don't know how to update force type '%s'" % force_classname)
# Update exceptions
# TODO: Handle Custom forces.
if force_classname == 'NonbondedForce':
for (exc_initial, exc_final) in zip(cache_initial[force_index]['exceptions'], cache_final[force_index]['exceptions']):
exc = {key: exc_initial[key] for key in ['exception_index', 'particle1', 'particle2']}
for parameter_name in ['chargeProd', 'sigma', 'epsilon']:
exc[parameter_name] = (1.0 - fractional_titration_state) * exc_initial[parameter_name] + \
fractional_titration_state * exc_final[parameter_name]
force.setExceptionParameters(
exc['exception_index'], exc['particle1'], exc['particle2'], exc['chargeProd'], exc['sigma'], exc['epsilon'])
def _cache_force(self, titration_group_index, titration_state_index):
"""
Cache the force parameters for a single titration state.
Parameters
----------
titration_group_index : int
Index of the group
titration_state_index : int
Index of the titration state of the group
Notes
-----
Call this function to set up the 'forces' information for a single titration state.
Every titration state has a list called forces, which stores parameters for all forces that need updating.
Inside each list entry is a dictionary that always contains an entry called `atoms`, with single atom parameters by name.
NonbondedForces also have an entry called `exceptions`, containing exception parameters.
Returns
-------
"""
titration_group = self.titrationGroups[titration_group_index]
titration_state = self.titrationGroups[titration_group_index]['titration_states'][titration_state_index]
# Store the parameters per individual force
f_params = list()
for force_index, force in enumerate(self.forces_to_update):
# Store parameters for this particular force
f_params.append(dict(atoms=list()))
# Get name of force class.
force_classname = force.__class__.__name__
# Get atom indices and charges.
charges = titration_state['charges']
atom_indices = titration_group['atom_indices']
charge_by_atom_index = dict(zip(atom_indices, charges))
# Update charges.
# TODO: Handle Custom forces, looking for "charge" and "chargeProd".
for atom_index in atom_indices:
if force_classname == 'NonbondedForce':
f_params[force_index]['atoms'].append(
{key: value for (key, value) in zip(['charge', 'sigma', 'epsilon'], map(strip_in_unit_system, force.getParticleParameters(atom_index)))})
elif force_classname == 'GBSAOBCForce':
f_params[force_index]['atoms'].append(
{key: value for (key, value) in zip(['charge', 'radius', 'scaleFactor'], map(strip_in_unit_system, force.getParticleParameters(atom_index)))})
else:
raise Exception("Don't know how to update force type '%s'" % force_classname)
f_params[force_index]['atoms'][-1]['charge'] = charge_by_atom_index[atom_index]
f_params[force_index]['atoms'][-1]['atom_index'] = atom_index
# Update exceptions
# TODO: Handle Custom forces.
if force_classname == 'NonbondedForce':
f_params[force_index]['exceptions'] = list()
for e_ix, exception_index in enumerate(titration_group['exception_indices']):
[particle1, particle2, chargeProd, sigma, epsilon] = map(
strip_in_unit_system, force.getExceptionParameters(exception_index))
# Deal with exceptions between atoms outside of titratable residue
try:
charge_1 = charge_by_atom_index[particle1]
except KeyError:
charge_1 = strip_in_unit_system(force.getParticleParameters(particle1)[0])
try:
charge_2 = charge_by_atom_index[particle2]
except KeyError:
charge_2 = strip_in_unit_system(force.getParticleParameters(particle2)[0])
chargeProd = self.coulomb14scale * charge_1 * charge_2
# chargeprod and sigma cannot be identically zero or else we risk the error:
# Exception: updateParametersInContext: The number of non-excluded exceptions has changed
# TODO: Once OpenMM interface permits this, omit this code.
if (2 * chargeProd == chargeProd):
chargeProd = sys.float_info.epsilon
if (2 * epsilon == epsilon):
epsilon = sys.float_info.epsilon
# store specific local variables in dict by name
exc_dict = dict()
for i in ('exception_index', 'particle1', 'particle2', 'chargeProd', 'sigma', 'epsilon'):
exc_dict[i] = locals()[i]
f_params[force_index]['exceptions'].append(exc_dict)
self.titrationGroups[titration_group_index]['titration_states'][titration_state_index]['forces'] = f_params
def _ncmc_protocol_work(self, context, titration_group_indices, initial_titration_states, final_titration_states):
"""
Performs non-equilibrium candidate Monte Carlo (NCMC) for attempting an change from an initial protonation
state to a final protonation state. This functions changes the system's state and returns the work for the
transformation. Currently, parameters are linearly interpolated between the initial and final states.
Notes
-----
The integrator is an simtk.openmm.CustomIntegrator object that calculates the protocol work internally.
To ensure the NCMC protocol is time symmetric, it has the form
propagation --> perturbation --> propagation
Parameters
----------
context : simtk.openmm.Context
The context in which NCMC will be performed.
titration_group_indices :
The indices of the titratable groups that will be perturbed
initial_titration_states :
The initial protonation state of the titration groups
final_titration_states :
The final protonation state of the titration groups
Returns
-------
work : float
the protocol work of the NCMC procedure in multiples of kT.
"""
# Turn the center of mass remover off, otherwise it contributes to the work
if self.cm_remover is not None:
self.cm_remover.setFrequency(0)
# TODO Is it correct to just replace this by using self.ncmc_propagation_integrator?
ncmc_integrator = self.compound_integrator.getIntegrator(1)
# Reset integrator statistics
if isinstance(ncmc_integrator, GHMCIntegrator):
ncmc_integrator.setGlobalVariableByName("ntrials", 0) # Reset the internally accumulated work
ncmc_integrator.setGlobalVariableByName("naccept", 0) # Reset the GHMC acceptance rate counter
elif issubclass(type(ncmc_integrator), ExternalPerturbationLangevinIntegrator):
ncmc_integrator.setGlobalVariableByName("first_step", 0)
# The "work" in the acceptance test has a contribution from the titratable group weights.
g_initial = 0
for titration_group_index, (titration_group, titration_state_index) in enumerate(zip(self.titrationGroups, self.titrationStates)):
titration_state = titration_group['titration_states'][titration_state_index]
g_initial += titration_state['g_k']
# PROPAGATION
ncmc_integrator.step(1)