Skip to content

Commit

Permalink
Tweaks to allow loading old data
Browse files Browse the repository at this point in the history
also some changes to BindingPMF API
  • Loading branch information
daveminh committed Jan 24, 2020
1 parent a9245f5 commit e307d9a
Show file tree
Hide file tree
Showing 5 changed files with 153 additions and 144 deletions.
33 changes: 10 additions & 23 deletions AlGDock/BindingPMF.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
from collections import OrderedDict

from AlGDock import dictionary_tools
from AlGDock import path_tools

import MMTK
import MMTK.Units
Expand All @@ -36,11 +35,6 @@
import multiprocessing
from multiprocessing import Process

try:
import requests # for downloading additional files
except:
print ' no requests module for downloading additional files'

# For profiling. Unnecessary for normal execution.
# from memory_profiler import profile

Expand Down Expand Up @@ -78,13 +72,13 @@ def HMStime(s):

class BPMF:
def __init__(self, **kwargs):
"""Parses the input arguments and runs the requested CD calculation"""
"""Parses the input arguments and runs the requested calculation"""

# mod_path = os.path.join(os.path.dirname(a.__file__), 'BindingPMF.py')
# print """###########
# # AlGDock #
# ###########
# Molecular CD with adaptively scaled alchemical interaction grids
# Molecular docking with adaptively scaled alchemical interaction grids
#
# in {0}
# last modified {1}
Expand All @@ -100,6 +94,8 @@ def __init__(self, **kwargs):
self.data['CD'] = SimulationData(self.args.dir['CD'], 'CD', \
self.args.params['CD']['pose'])

if not 'max_time' in kwargs.keys():
kwargs['max_time'] = None
if not 'run_type' in kwargs.keys():
kwargs['run_type'] = None

Expand All @@ -117,7 +113,7 @@ def __init__(self, **kwargs):
print '\nfor %s:' % p
print dictionary_tools.dict_view(self.args.params[p])[:-1]

self._run(kwargs['run_type'])
self.run(kwargs['run_type'])

def _setup(self):
"""Creates an MMTK InfiniteUniverse and adds the ligand"""
Expand Down Expand Up @@ -249,13 +245,6 @@ def _setup(self):
self.top.universe.setConfiguration(
Configuration(self.top.universe, confs[-1]))

# Samplers may accept the following options:
# steps - number of MD steps
# T - temperature in K
# delta_t - MD time step
# normalize - normalizes configurations
# adapt - uses an adaptive time step

from AlGDock.simulation_iterator import SimulationIterator
self.iterator = SimulationIterator(self.args, self.top, self.system)

Expand All @@ -269,7 +258,7 @@ def _setup(self):
if self.args.random_seed > 0:
np.random.seed(self.args.random_seed)

def _run(self, run_type):
def run(self, run_type):
from AlGDock.postprocessing import Postprocessing

self.log.recordStart('run')
Expand Down Expand Up @@ -484,7 +473,7 @@ def calc_f_L(self, readOnly=False, do_solvation=True, redo=False):
for BC_Es_state in self.data['BC'].Es:
BC_Es.append(BC_Es_state[fromCycle:toCycle])
(u_kln, N_k) = self._u_kln(BC_Es, self.data['BC'].protocol)
MBAR = self._run_MBAR(u_kln, N_k)[0]
MBAR = self.run_MBAR(u_kln, N_k)[0]
self.f_L['BC_MBAR'].append(MBAR)

# Average acceptance probabilities
Expand Down Expand Up @@ -714,7 +703,7 @@ def set_updated_to_True(updated, start_string, quiet=False):

# Use MBAR for the grid scaling free energy estimate
(u_kln, N_k) = self._u_kln(CD_Es, self.data['CD'].protocol)
MBAR = self._run_MBAR(u_kln, N_k)[0]
MBAR = self.run_MBAR(u_kln, N_k)[0]
self.f_RL['grid_MBAR'][c] = MBAR
updated = set_updated_to_True(updated,
start_string,
Expand Down Expand Up @@ -1144,8 +1133,6 @@ def configuration_energies(self, minimize=False, max_confs=None):
confs = confs[:max_confs]

# Implicit solvent energies
self._load_programs(self.args.params['CD']['phases'])

self.data['CD'].confs['starting_poses'] = None
from AlGDock.postprocessing import Postprocessing
pp_complete = Postprocessing(self.args, self.log, self.top, self.top_RL, self.system, self.data, self.save).run([('original', 0, 0, 'R')])
Expand Down Expand Up @@ -1380,7 +1367,7 @@ def _insert_CD_state(self, alpha, clear=True):
u_kln[k, -1, :] = u_kln_n[k, 0, :]

# Determine SIR weights
weights = self._run_MBAR(u_kln, N_k, augmented=True)[1][:, -1]
weights = self.run_MBAR(u_kln, N_k, augmented=True)[1][:, -1]
weights = weights / sum(weights)

# Resampling
Expand Down Expand Up @@ -1692,7 +1679,7 @@ def _checkedMinimizer(self, confs):
', '.join(['%.2f'%e for e in energies[:10]]))
return confs, energies

def _run_MBAR(self, u_kln, N_k, augmented=False):
def run_MBAR(self, u_kln, N_k, augmented=False):
"""
Estimates the free energy of a transition using BAR and MBAR
"""
Expand Down
6 changes: 4 additions & 2 deletions AlGDock/path_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@

### Google drive downloader from
# http://stackoverflow.com/questions/25010369/wget-curl-large-file-from-google-drive
import requests

try:
import requests # for downloading additional files
except:
print ' no requests module for downloading additional files'

def download_file_from_google_drive(id, destination):
URL = "https://docs.google.com/uc?export=download"
Expand Down
49 changes: 33 additions & 16 deletions AlGDock/postprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,13 @@ def __init__(self, args, log, top, top_RL, system, data, save):
self.elsize = self._get_elsize()

def _load_programs(self, phases):
# Find the necessary programs, downloading them if necessary
"""Locate the necessary external programs, downloading them if necessary
Parameters
----------
phases : list of str
The names of the phases that will be used
"""
programs = []
for phase in phases:
for (prefix,program) in [('NAMD','namd'), \
Expand All @@ -103,13 +109,24 @@ def run(self,
('CD', -1,-1,'L'), ('CD',-1,-1,'RL')],
phases=None,
readOnly=False, redo_CD=False, debug=DEBUG):
"""
Obtains the NAMD energies of all the conditions using all the phases.
Saves both MMTK and NAMD energies after NAMD energies are estimated.
"""Obtains and stores energies of all conditions in all phases
state == -1 means the last state
cycle == -1 means all cycles
Energies are stored in self.data
Parameters
----------
conditions : list of tuples
Each tuple contains the process, the thermodynamic state index,
the simulation cycle, and moeity.
state == -1 means the last state
cycle == -1 means all cycles
phases : list of str
The names of the phases that will be considered
readOnly : bool
If True, no calculations will be performed. The data will simply be
loaded into memory.
"""
# Clear evaluators to save memory
self.system.clear_evaluators()
Expand Down Expand Up @@ -317,6 +334,8 @@ def run(self,
return len(incomplete) == len(results)

def _energy_worker(self, input, output, time_per_snap):
"""Performs energy calculation for one process
"""
for args in iter(input.get, 'STOP'):
(confs, moiety, phase, traj_FN, outputname, debug, reference) = args
(p, state, c, label) = reference
Expand Down Expand Up @@ -358,8 +377,7 @@ def _NAMD_Energy(self,
outputname,
debug=DEBUG,
reference=None):
"""
Uses NAMD to calculate the energy of a set of configurations
"""Uses NAMD to calculate the energy of a set of configurations.
Units are the MMTK standard, kJ/mol
"""
# NAMD ENERGY FIELDS:
Expand Down Expand Up @@ -556,8 +574,10 @@ def _sander_Energy(self, confs, moiety, phase, AMBER_mdcrd_FN, \
# 5. EPB 6. 1-4 VWD 7. 1-4 EEL 8. RESTRAINT 9. ECAVITY 10. EDISPER

def _get_elsize(self):
# Calculates the electrostatic size of the receptor for ALPB calculations
# Writes the coordinates in AMBER format
"""Calculates the electrostatic size of the receptor for ALPB calculations
Writes the coordinates in AMBER format
"""
if hasattr(self, 'elsize'):
return

Expand Down Expand Up @@ -623,9 +643,7 @@ def _gbnsr6_Energy(self,
outputname,
debug=DEBUG,
reference=None):
"""
Uses gbnsr6 (part of AmberTools)
to calculate the energy of a set of configurations
"""Uses gbnsr6 (part of AmberTools) to calculate the energy of a set of configurations
"""
# Prepare configurations for writing to crd file
factor = 1.0 / MMTK.Units.Ang
Expand Down Expand Up @@ -731,9 +749,8 @@ def _APBS_Energy(self,
outputname,
debug=DEBUG,
reference=None):
"""
Uses APBS to calculate the solvation energy of a set of configurations
Units are the MMTK standard, kJ/mol
"""Uses APBS to calculate the solvation energy of a set of configurations.
Units are the MMTK standard, kJ/mol.
"""
# Prepare configurations for writing to crd file
factor = 1.0 / MMTK.Units.Ang
Expand Down
7 changes: 5 additions & 2 deletions AlGDock/topology.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __init__(self, args, includeReceptor=False):
os.path.dirname(args.FNs['ligand_database'])
self.molecule = MMTK.Molecule(\
os.path.basename(args.FNs['ligand_database']))
if includeReceptor:
if includeReceptor and (args.FNs['receptor_database']is not None):
self.molecule_R = MMTK.Molecule(\
os.path.basename(args.FNs['receptor_database']))
else:
Expand Down Expand Up @@ -77,7 +77,10 @@ def __init__(self, args, includeReceptor=False):
self.universe = MMTK.Universe.InfiniteUniverse()
self.universe.addObject(self.molecule)
if includeReceptor:
self.universe.addObject(self.molecule_R)
if self.molecule_R is not None:
self.universe.addObject(self.molecule_R)
else:
self.universe = None

# Define L_first_atom
if includeReceptor:
Expand Down
Loading

0 comments on commit e307d9a

Please sign in to comment.