def test_cr(TOP, CRD, PERT, RULE): combining_rules = Parameter( "combining rules", RULE, """Combining rules to use for the non-bonded interactions.""") amber = Amber() (molecules, space) = amber.readCrdTop(CRD, TOP) system = createSystemFreeEnergy(molecules, PERT) system = setupForceFieldsFreeEnergy(system, space, RULE) if random_seed.val: ranseed = random_seed.val else: ranseed = RanGenerator().randInt(100000, 1000000) moves = setupMovesFreeEnergy(system, ranseed, reference.val, lambda_val.val, RULE) # Get energy from Sire nrg_sire = system.energy() # Get energy from SOMD mdmoves = moves.moves()[0] integrator = mdmoves.integrator() nrg_somd = integrator.getPotentialEnergy(system) if (RULE == 'arithmetic'): global diff_arith diff_arith = (nrg_sire - nrg_somd).value() print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("TESTING ARITHMETIC COMBINING RULES") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("* The energy from Sire is: %s" % nrg_sire) print("* The energy from SOMD is: %s" % nrg_somd) print( " For the arithmetic combining rules the single point energy difference between sire and somd at lambda %s is %s " % (lambda_val.val, diff_arith)) elif (RULE == 'geometric'): global diff_geom diff_geom = (nrg_sire - nrg_somd).value() print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("TESTING GEOMETRIC COMBINING RULES") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("* The energy from Sire is: %s" % nrg_sire) print("* The energy from SOMD is: %s" % nrg_somd) print( " For the geometric combining rules the single point energy difference between sire and somd at lambda %s is %s " % (lambda_val.val, diff_geom))
from Sire.System import * from Sire.Move import * from Sire.MM import * from Sire.FF import * from Sire.Units import * from Sire.Vol import * from Sire.Maths import * from Sire.Base import * from Sire.Qt import * from Sire.ID import * from Sire.Config import * from Sire.Analysis import * from Sire.Tools import Parameter, resolveParameters cutoff_type = Parameter("cutoff type", "cutoffperiodic", """The cutoff method to use during the simulation.""") cutoff_dist = Parameter( "cutoff distance", 10 * angstrom, """The cutoff distance to use for the non-bonded interactions.""") rf_dielectric = Parameter( "reaction field dielectric", 78.3, """Dielectric constant to use if the reaction field cutoff method is used.""" ) use_restraints = Parameter( "use restraints", False, """Whether or not to use harmonic restaints on the solute atoms.""") combining_rules = Parameter(
from Sire.Maths import * from Sire.Base import * from Sire.Qt import * from Sire.ID import * from Sire.Config import * import Sire.Stream from Sire.Tools import Parameter, resolveParameters from Sire.Tools.WaterChanger import convertTip3PtoTip4P ################################### # Parameters used by this module # ################################### dobonds = Parameter("move bonds", True, """Whether or not to move the ligands bonds""") doangles = Parameter("move angles", True, """Whether or not to move the ligands angles""") dodihedrals = Parameter("move dihedrals", True, """Whether or not to move the ligands dihedrals""") water_model = Parameter( "water model", None, """The water model to use. Note, by default the water model is read from the protein and water crd/top files. If you want to force a change in water model, then set it here, e.g. if you are loading a TIP3P box but want to use TIP4P, then set this parameter to "tip4p".""" ) BASE_DIHEDRALH_FLEX = Parameter("h dihedral flex", 30 * degrees, "Base dihedral rotation for H")
def estimateDG(topfile=None,crdfile=None,pertfile=None, trajfile=None,librarypath=None): """ This subroutine loads a trajectory for an alchemical state, and a list of ligand molecules For each frame of the trajectory for each perturbed ligand Align the perturbed ligand onto reference ligand. Generate K poses Accumulate exp energy difference Estimate (w bootstrapping) free energy difference & uncertainties """ print ("HELLO ESTIMATE DG") # Setup system describing alchemical state amber = Amber() (molecules, space) = amber.readCrdTop(crdfile, topfile) morphfile = Parameter("morphfile",pertfile,""".""") system = createSystemFreeEnergy(molecules, morphfile=morphfile) cutoff_type = Parameter(".","cutoffperiodic",""".""") cutoff_dist = Parameter(".",10*angstrom,""".""") rf_dielectric = Parameter(".",82.0,""".""") shift_delta = Parameter(".",2.0,""".""") coulomb_power = Parameter(".",0,""".""") combining_rules = Parameter(".","arithmetic",""".""") lambda_val = Parameter(".",0.0,""".""") system = setupForceFieldsFreeEnergy(system, space, cutoff_type=cutoff_type, cutoff_dist=cutoff_dist, rf_dielectric=rf_dielectric, shift_delta=shift_delta, coulomb_power=coulomb_power, combining_rules=combining_rules, lambda_val=lambda_val) # Load ligands library # FIX ME ! Don't include ligands that have already been simulated ! library = loadLibrary(librarypath) library_deltaenergies = {} # library_deltaenergies contain the list of computed energy differences for ligand in library: library_deltaenergies[ligand] = [] #import pdb; pdb.set_trace() # Now scan trajectory start_frame = 1 end_frame = 3 step_frame = 1 trajfile = Parameter(".",trajfile,""".""") mdtraj_trajfile = mdtraj.open(trajfile.val,'r') nframes = len(mdtraj_trajfile) if end_frame > (nframes - 1): end_frame = nframes - 1 mdtraj_trajfile.seek(start_frame) current_frame = start_frame energies = {} for (ID, ligand) in library: energies[ID] = [] while (current_frame <= end_frame): print ("#Processing frame %s " % current_frame) frames_xyz, cell_lengths, cell_angles = mdtraj_trajfile.read(n_frames=1) system = updateSystemfromTraj(system, frames_xyz, cell_lengths, cell_angles) ref_ligand = system[MGName("solutes")].molecules().first().molecule() ref_nrg = system.energy() print (ref_nrg) for (ID, ligand) in library: # Align ligand onto reference ligand mapping = AtomMCSMatcher(1*second).match(ref_ligand, PropertyMap(), ligand, PropertyMap()) mapper = AtomResultMatcher(mapping) # This does a RB alignment # TODO) Explore optimised alignment codes # For instance could construct aligned ligand by reusing MCSS coordinates # and completing topology for variable part using BAT internal coordinates # Also, better otherwise never get intramolecular energy variations ! # Basic test...SAME LIGAND should give 0 energy difference ! # FIXME) Return multiple coordinates and update system in each instance aligned_ligand = ligand.move().align(ref_ligand, AtomMatchInverter(mapper)) #print (ref_ligand.property("coordinates").toVector()) #print ("####") #print (aligned_ligand.property("coordinates").toVector()) # FIXME) Optimise for speed new_system = System() new_space = system.property("space") new_system.add( system[MGName("solvent")] ) sols = MoleculeGroup("solutes") solref = MoleculeGroup("solute_ref") solhard = MoleculeGroup("solute_ref_hard") soltodummy = MoleculeGroup("solute_ref_todummy") solfromdummy = MoleculeGroup("solute_ref_fromdummy") sols.add(aligned_ligand) solref.add(aligned_ligand) solhard.add(aligned_ligand) new_system.add(sols) new_system.add(solref) new_system.add(solhard) new_system.add(soltodummy) new_system.add(solfromdummy) #print ("###") # DONE) Optimise for speed, only doing ligand energies #print (new_system[MGName("solutes")].first().molecule().property("coordinates").toVector()) new_system = setupForceFieldsFreeEnergy(new_system, new_space, cutoff_type=cutoff_type, cutoff_dist=cutoff_dist, rf_dielectric=rf_dielectric, shift_delta=shift_delta, coulomb_power=coulomb_power, combining_rules=combining_rules, lambda_val=lambda_val) new_nrg = new_system.energy() print (new_nrg) energies[ID].append( new_nrg - ref_nrg ) # for each conformation generated # consider further optimisation (rapid MC --> if loaded flex files?) # update 'perturbed' group with aligned ligand coordinates # compute 'perturbed' energy # accumulate 'perturbed' - reference #import pdb; pdb.set_trace() current_frame += step_frame import pdb; pdb.set_trace() # Now convert accumulated data int return 0
import ast except ImportError: print( "StandarState.py depends on a working install of the python module ast. Please install ast in your sire python." ) sys.exit(-1) try: import shutil except ImportError: print( "StandarState.py depends on a working install of the python module shutil. Please install shutil in your sire python." ) sys.exit(-1) trajfile = Parameter("trajfile", "traj000000001.dcd", """File name of the trajectory to process.""") stepframe = Parameter( "step_frame", 1, """The number of frames to step to between two succcessive evaluations.""") simfile = Parameter( "simfile", "sim.cfg", """ Configuration file with distance restraints dictionary""") topfile = Parameter( "topfile", "SYSTEM.top", """File name of the topology file containing the system to be simulated.""" ) buff = Parameter( "buff", 5.0, """Buffer to be added to coordinates to create domain of integration""")
for nrg in delta_nrgs: free_nrg.accumulate(nrg.value()) deltaG = free_nrg.average() * kcal_per_mol return deltaG if __name__ == "__main__": try: host = os.environ['HOSTNAME'] except KeyError: host = "unknown" print("### Running electrostatics correction calculation on %s ###" % host) if True: #verbose.val: print("###================= Simulation Parameters=====================###") Parameter.printAll() print ("###===========================================================###\n") print("lambda is %s" % lambda_val.val) if os.path.exists(s3file.val): (molecules, space) = Sire.Stream.load(s3file.val) else: amber = Amber() (molecules, space) = amber.readCrdTop(crdfile.val, topfile.val) Sire.Stream.save((molecules, space), s3file.val) # What to do with this... system = createSystemFreeEnergy(molecules) lam = Symbol("lambda") solutes = system[MGName("solutes")] solute_ref = system[MGName("solute_ref")]
import Sire.Config import Sire.Stream from Sire.Tools.AmberLoader import * from Sire.Tools import Parameter, resolveParameters import os import shutil import copy ######################################################## # ALL OF THE GLOBAL USER-AVAILABLE QuanToMM PARAMETERS # ######################################################## cutoff_method = Parameter( "cutoff method", "shift electrostatics", """Method used to apply the non-bonded electrostatic cutoff.""") rf_dielectric = Parameter( "reaction field dielectric", 78.3, """Dielectric constant to use if the reaction field cutoff method is used.""" ) coul_cutoff = Parameter("coulomb cutoff", 15 * angstrom, """Coulomb cutoff length""") lj_cutoff = Parameter("LJ cutoff", 15 * angstrom, """Lennard Jones cutoff length""") grid_spacing = Parameter( "grid spacing", 1.0 * angstrom,
import numpy as np #try: # import mdtraj #except ImportError: # print ("LJcutoff.py depends on a working install of the python module mdtraj. Please install mdtraj in your sire python.") # sys.exit(-1) # #try: # import numpy as np #except ImportError: # print ("LJcutoff.py depends on a working install of the python module mdtraj. Please install mdtraj in your sire python.") # sys.exit(-1) bulk_rho = Parameter("bulk_rho", 1.0 * gram/(centimeter*centimeter*centimeter)\ ,"""The density of buk solvent.""") trajfile = Parameter("trajfile", "traj000000001.dcd", """File name of the trajectory to process.""") stepframe = Parameter( "step_frame", 1, """The number of frames to step to between two succcessive evaluations.""") def setupLJFF(system, space, cutoff=10 * angstrom): print("Creating force fields... ") solutes = system[MGName("solutes")] solute = system[MGName("solute_ref")] solute_hard = system[MGName("solute_ref_hard")]
from BioSimSpace._SireWrappers import System as _System from BioSimSpace._Exceptions import IncompatibleError as _IncompatibleError from BioSimSpace.Types import Length as _Length from BioSimSpace._Exceptions import AlignmentError as _AlignmentError from BioSimSpace._Exceptions import MissingSoftwareError as _MissingSoftwareError from BioSimSpace._SireWrappers import Molecule as _Molecule from BioSimSpace import IO as _IO from BioSimSpace import Units as _Units from BioSimSpace import _Utils as _Utils ######################################### # Config file parameters # ######################################### combining_rules = Parameter( "combining rules", "geometric", """Combining rules to use for the non-bonded interactions.""") cutoff_type = Parameter("cutoff type", "nocutoff", """The cutoff method to use during the simulation.""") cutoff_dist = Parameter( "cutoff distance", 500 * angstrom, """The cutoff distance to use for the non-bonded interactions.""") use_restraints = Parameter( "use restraints", False, """Whether or not to use harmonic restaints on the solute atoms.""") perturbed_resnum = Parameter( "perturbed residue number", 1,
def runLambda(): try: host = os.environ['HOSTNAME'] except KeyError: host = "unknown" print("### Running LJ tail correction calculation on %s ###" % host) if verbose.val: print("###================= Simulation Parameters=====================###") Parameter.printAll() print ("###===========================================================###\n") print("lambda is %s" % lambda_val.val) if os.path.exists(s3file.val): (molecules, space) = Sire.Stream.load(s3file.val) else: amber = Amber() (molecules, space) = amber.readCrdTop(crdfile.val, topfile.val) Sire.Stream.save((molecules, space), s3file.val) system = createSystemFreeEnergy(molecules) # !!! NEED TO DISABLE CHANGE IN COULOMBIC CUTOFF !! #system = zeroCharges(system) #import pdb; pdb.set_trace() # THIS IS THE ONE WITH SHORT CUTOFF system_shortc = System() system_shortc.copy(system) #import pdb; pdb.set_trace() system_shortc = setupLJFF(system_shortc, space, \ cutoff=cutoff_dist.val) #import pdb; pdb.set_trace() # Determine longest cutoff that can be used. Take lowest space dimension, # and decrease by 5% dims = space.dimensions() mindim = dims.x() if mindim > dims.y(): mindim = dims.y() if mindim > dims.z(): mindim = dims.z() long_cutoff = (mindim/2.0 * 0.95) * angstrom print (long_cutoff) system_longc = System() system_longc.copy(system) system_longc = setupLJFF(system_longc, space, \ cutoff=long_cutoff) # NOW ADD ANALYTICAL CORRECTION TERM TO longc E_lrc_full = addAnalyticalLRC(system_longc, long_cutoff, bulk_rho.val) #import pdb; pdb.set_trace() # Now loop over snapshots in dcd and accumulate energies start_frame = 1 end_frame = 1000000000 step_frame = stepframe.val #mdtraj_top = mdtraj.load_prmtop(topfile.val) mdtraj_trajfile = mdtraj.open(trajfile.val,'r') nframes = len(mdtraj_trajfile) if end_frame > (nframes - 1): end_frame = nframes - 1 mdtraj_trajfile.seek(start_frame) current_frame = start_frame delta_nrgs = [] while (current_frame <= end_frame): print ("Processing frame %s " % current_frame) print ("CURRENT POSITION %s " % mdtraj_trajfile.tell() ) frames_xyz, cell_lengths, cell_angles = mdtraj_trajfile.read(n_frames=1) #print (system_shortc.energy()) #print (system_longc.energy()) system_shortc = updateSystemfromTraj(system_shortc, frames_xyz, cell_lengths, cell_angles) system_longcc = updateSystemfromTraj(system_longc, frames_xyz, cell_lengths, cell_angles) #print (system_shortc.energy()) #print (system_longc.energy()) delta_nrg = (system_longc.energy()+E_lrc_full - system_shortc.energy()) delta_nrgs.append(delta_nrg) current_frame += step_frame mdtraj_trajfile.seek(current_frame) #print (delta_nrgs) # Now compute free energy change deltaG = getFreeEnergy(delta_nrgs) #print (deltaG) nbootstrap = 100 deltaG_bootstrap = np.zeros(nbootstrap) for x in range(0,nbootstrap): resampled_nrgs = resample(delta_nrgs) dG = getFreeEnergy(resampled_nrgs) deltaG_bootstrap[x] = dG.value() dev = deltaG_bootstrap.std() print ("DG_LJ = %8.5f +/- %8.5f kcal/mol (1 sigma) " % (deltaG.value(), dev))
# try: import mdtraj except ImportError: print ("CoulCutoff.py depends on a working install of the python module mdtraj. Please install mdtraj in your sire python.") sys.exit(-1) try: import numpy as np except ImportError: print ("CoulCutoff.py depends on a working install of the python module mdtraj. Please install mdtraj in your sire python.") sys.exit(-1) ## Free energy specific keywords cutoff_type = Parameter("cutoff type", "cutoffperiodic", """The cutoff method to use during the simulation.""") cutoff_dist = Parameter("cutoff distance", 12 * angstrom, """The cutoff distance to use for the non-bonded interactions.""") topfile = Parameter("topfile", "SYSTEM.top", """File name of the topology file containing the system to be simulated.""") crdfile = Parameter("crdfile", "SYSTEM.crd", """File name of the coordinate file containing the coordinates of the system to be simulated.""") morphfile = Parameter("morphfile", "MORPH.pert", """Name of the morph file containing the perturbation to apply to the system.""") #lambda_val = Parameter("lambda_val", 0.0,
max_delta_bond = 0.02 * angstrom max_delta_angle = 1.0 * degrees max_delta_dihedral = 2.0 * degrees ## specify the maximum number of bonds, ## angles and dihedrals to move per move max_num_move = 1 # set the maximum delta parameters params = {} params["bond flex"] = max_delta_bond params["angle flex"] = max_delta_angle params["dihedral flex"] = max_delta_dihedral params["h dihedral flex"] = max_delta_dihedral params["maxvar"] = max_num_move Parameter.push(params) # Load the molecules and the periodic box from the crd/top files (mols, space) = Amber().readCrdTop("l7n.crd", "l7n.top") # extract the ligand molecule (molecule with residue called "L7N") ligand_mol = mols[ MolWithResID("L7N") ].molecule() # auto-generate the flexibility for the ligand flexibility = AmberLoader.generateFlexibility(ligand_mol) # attach this flexibility to the ligand using the 'flexibility' property ligand_mol = ligand_mol.edit() \ .setProperty("flexibility", flexibility) \ .commit()
def runFreeNrg(): # if (save_coords.val): # buffer_freq = 500 # else: # buffer_freq = 0 try: host = os.environ["HOSTNAME"] except KeyError: host = "unknown" print(" ### Running Single Topology Molecular Dynamics Free Energy on %s ### " % host) print("### Simulation Parameters ### ") Parameter.printAll() print("### ###") timer = QTime() timer.start() # Setup the system from scratch if no restart file is available if not os.path.exists(restart_file.val): print("New run. Loading input and creating restart") print("lambda is %s" % lambda_val.val) amber = Amber() if os.path.exists(s3file.val): (molecules, space) = Sire.Stream.load(s3file.val) else: (molecules, space) = amber.readCrdTop(crdfile.val, topfile.val) Sire.Stream.save((molecules, space), s3file.val) system = createSystemFreeEnergy(molecules) if center_solute.val: system = centerSolute(system, space) if use_restraints.val: system = setupRestraints(system) if use_distance_restraints.val: system = setupDistanceRestraints(system) # Note that this just set the mass to zero which freezes residues in OpenMM but Sire doesn't known that if freeze_residues.val: system = freezeResidues(system) system = setupForcefieldsFreeEnergy(system, space) if random_seed.val: ranseed = random_seed.val else: ranseed = RanGenerator().randInt(100000, 1000000) print("Setting up the simulation with random seed %s" % ranseed) moves = setupMovesFreeEnergy(system, ranseed, gpu.val, lambda_val.val) print("Saving restart") Sire.Stream.save([system, moves], restart_file.val) else: system, moves = Sire.Stream.load(restart_file.val) move0 = moves.moves()[0] integrator = move0.integrator() integrator.setDeviceIndex(str(gpu.val)) move0.setIntegrator(integrator) moves = WeightedMoves() moves.add(move0) print("Index GPU = %s " % moves.moves()[0].integrator().getDeviceIndex()) print("Loaded a restart file on wich we have performed %d moves." % moves.nMoves()) cycle_start = int(moves.nMoves() / nmoves.val) + 1 cycle_end = cycle_start + ncycles.val lam_str = "%7.5f" % lambda_val.val outgradients = open("gradients.dat", "a", 1) outgradients.write("# lambba_val.val %s\n" % lam_str) if save_coords.val: trajectory = setupDCD(dcd_root.val, system) s1 = timer.elapsed() / 1000.0 print("Running MD simulation ") grads = {} grads[lambda_val.val] = AverageAndStddev() for i in range(cycle_start, cycle_end): print("\nCycle = ", i, "\n") # print("Energy before = %s kJ mol-1" % (system.energy().to(kJ_per_mol))) # import ipdb; ipdb.set_trace() system = moves.move(system, nmoves.val, True) # print("Energy after = %s kJ mol-1" % (system.energy().to(kJ_per_mol))) if save_coords.val: writeSystemData(system, moves, trajectory, i) mdmoves = moves.moves()[0] integrator = mdmoves.integrator() gradients = integrator.getGradients() outgradients.write("%5d %20.10f\n" % (i, gradients[i - 1])) grads[lambda_val.val].accumulate(gradients[i - 1]) s2 = timer.elapsed() / 1000.0 print("Simulation took %d s " % (s2 - s1)) if os.path.exists("gradients.s3"): siregrads = Sire.Stream.load("gradients.s3") else: siregrads = Gradients() siregrads = siregrads + Gradients(grads) Sire.Stream.save(siregrads, "gradients.s3") if buffered_coords_freq.val > 0: system = clearBuffers(system) # Necessary to write correct restart system.mustNowRecalculateFromScratch() print("Backing up previous restart") cmd = "cp %s %s.previous" % (restart_file.val, restart_file.val) os.system(cmd) print("Saving new restart") Sire.Stream.save([system, moves], restart_file.val)
max_delta_bond = 0.02 * angstrom max_delta_angle = 1.0 * degrees max_delta_dihedral = 2.0 * degrees ## specify the maximum number of bonds, ## angles and dihedrals to move per move max_num_move = 1 # set the maximum delta parameters params = {} params["bond flex"] = max_delta_bond params["angle flex"] = max_delta_angle params["dihedral flex"] = max_delta_dihedral params["h dihedral flex"] = max_delta_dihedral params["maxvar"] = max_num_move Parameter.push(params) # Load the molecules and the periodic box from the crd/top files (mols, space) = Amber().readCrdTop("l7n.crd", "l7n.top") # extract the ligand molecule (molecule with residue called "L7N") ligand_mol = mols[MolWithResID("L7N")].molecule() # auto-generate the flexibility for the ligand flexibility = AmberLoader.generateFlexibility(ligand_mol) # attach this flexibility to the ligand using the 'flexibility' property ligand_mol = ligand_mol.edit() \ .setProperty("flexibility", flexibility) \ .commit()
def run(): try: host = os.environ['HOSTNAME'] except KeyError: host = "unknown" print("### Running Standard state correction calculation on %s ###" % host) if verbose.val: print( "###================= Simulation Parameters=====================###" ) Parameter.printAll() print( "###===========================================================###\n" ) #Constants delta = 0.10 delta_over_two = delta / 2.0 deltavol = delta * delta * delta kb = 0.001987 T = 298 kbT = kb * T beta = 1 / kbT ROT = 8 * pi**2 Ztrans = 0.0 Uavg = 0 #import pdb; pdb.set_trace() #open the simfile and extract the reestraint dictionary #sim = open(simfile.val,"r") #for line in sim.readlines(): # if "dictionary" in line: # sim_dictionary = line # print("Found restraint dictionary: %s" % sim_dictionary) # else: # continue # #Sanity Check #if the dictionary was not found in the simfile exit from the script #if line==None: # print("Error! Impossible to find dictionary restraint in sim.cfg") # sys.exit(-1) #ast automatically transform a string into a dictionary #sim_dictionary=ast.literal_eval(sim_dictionary.strip("distance restraint dictionary=")) sim_dictionary = distance_restraints_dict.val if sim_dictionary == {}: print( "Error, no distance restraints dictionary was found in the supplied config file. Abort." ) sys.exit(-1) #now create a dictionary in this way: #dict[pairs] = {[Req,D,K] [coords] [coords]...} restr_dict = {} #create a list of host indexes to be used with mdtraj for alignment hosts = [] for pairs in sim_dictionary: req = sim_dictionary[pairs][0] K = sim_dictionary[pairs][1] D = sim_dictionary[pairs][2] restr_dict[pairs] = [[req, K, D]] idx = max(pairs) hosts.append(idx) #load the trajectory start_frame = 1 end_frame = 1000000000 step_frame = stepframe.val #Check the extension of the topology file if ".top" in topfile.val: shutil.copy(topfile.val, "SYSTEM.prmtop") #top doesn't work with mdtraj top_file = "SYSTEM.prmtop" else: top_file = topfile.val print("Loading trajectory and topology files") # mdtraj_trajfile = mdtraj.load(trajfile.val, top=top_file) nframes = len(mdtraj_trajfile) if end_frame > (nframes - 1): end_frame = nframes - 1 current_frame = start_frame #Aligning everything along the first frame print("Aligning frames along first frame of trajectory") aligned_traj = mdtraj_trajfile.superpose(mdtraj_trajfile, 0, atom_indices=hosts) print("Processing frames") while (current_frame <= end_frame): #now for each lig:host pairs append the host coordinates for pairs in restr_dict: host_idx = max(pairs) restr_dict[pairs].append(aligned_traj.xyz[current_frame, host_idx, :].tolist()) current_frame += step_frame #now restr_dict has: #restr_dict[lig,host]=[ [req,K,D], [coords],[coords],...] print("Calculating average coordinates for restrained atoms") restr_dict = averageCoordinates(restr_dict) #now the restr_dict is: #restr_dict[pairs]=[[req,K,D],[avgx,avgy,avgz]] space = defineIntegrationDomain(restr_dict) if verbose.val: print("Integration space") print(space) #Grid creation Nx = int(round((space[1][0] - space[0][0]) / delta)) Ny = int(round((space[1][0] - space[0][0]) / delta)) Nz = int(round((space[1][0] - space[0][0]) / delta)) #Constants print("Number of elements to be evaluated %d" % (Nx * Ny * Nz)) print("Evaluation...") for i in range(0, Nx): for j in range(0, Ny): for k in range(0, Nz): x = space[0][0] + delta * i + delta_over_two y = space[0][1] + delta * j + delta_over_two z = space[0][2] + delta * k + delta_over_two counter = 0 for pairs in restr_dict: #restr_dict[pairs]=[[req,K,D],[coords]] x_dict = float(restr_dict[pairs][1][0]) y_dict = float(restr_dict[pairs][1][1]) z_dict = float(restr_dict[pairs][1][2]) distance = ((x - x_dict)**2 + (y - y_dict)**2 + (z - z_dict)**2) upper_bound = restr_dict[pairs][0][1] + restr_dict[pairs][ 0][2] intmd_bound = restr_dict[pairs][0][1] lower_bound = restr_dict[pairs][0][1] - restr_dict[pairs][ 0][2] if distance < upper_bound and distance > intmd_bound: if counter == len(restr_dict) - 1: U = 0.0 else: counter += 1 elif distance < intmd_bound and distance > lower_bound: if counter == len(restr_dict) - 1: U = 0.0 else: counter += 1 else: dist = (math.sqrt(distance)) K = (restr_dict[pairs][0][1]) D = (restr_dict[pairs][0][2]) U = (K * (dist - D)**2) break Boltz = math.exp(-beta * U) * deltavol Ztrans += (Boltz) Uavg += U * Boltz * ROT #Calculation of Ztot, Uavg, S, Frestraint: Ztot = Ztrans * ROT Uavg /= (Ztot) Zideal = 1661. * ROT Delta_F = -kbT * math.log(Ztot / Zideal) minTDelta_S = -T * (kb * math.log(Ztot / Zideal) + Uavg / T) print("Ztrans = %8.5f Angstrom^3" % Ztrans) print("Free energy Cost of removing the restraint = %8.5f kcal/mol" % -Delta_F) #tidy up the folder by removing prmtop cmd = "rm SYSTEM.prmtop" os.system(cmd)
try: shutil = Sire.try_import("shutil") except: pass try: numpy = Sire.try_import("numpy") except: pass # Constant for conversion NM_TO_ANG = 10.0 trajfile = Parameter("trajfile", "traj000000001.dcd", """File name of the trajectory to process.""") stepframe = Parameter("step_frame",1,"""The number of frames to step to between two succcessive evaluations.""") simfile = Parameter("simfile", "sim.cfg", """ Configuration file with distance restraints dictionary""") topfile = Parameter("topfile", "SYSTEM.top", """File name of the topology file containing the system to be simulated.""") buffer = Parameter("buffer", 5.0, """Buffer to be added to coordinates to create domain of integration""") delta_trans = Parameter("dtrans", 0.20, """Step size for translational volume elements, in Angstrom""") norient = Parameter("norient", 4, """Number of orientations per [0,2pi] Euler Angles interval""") temperature = Parameter("temperature",298 * kelvin,"""The temperature of the system""") verbose = Parameter("verbose", False, """Print debug output""") def averageCoordinates(restr_dict): r"""This function computes the average x,y and z coordinates for host atoms
def run(): try: host = os.environ['HOSTNAME'] except KeyError: host = "unknown" print("### Running Standard state correction calculation on %s ###" % host) if verbose.val: print("###================= Simulation Parameters=====================###") Parameter.printAll() print ("###===========================================================###\n") #Constants delta_over_two = delta_trans.val/2.0 deltavol = delta_trans.val*delta_trans.val*delta_trans.val ROT = 8 * pi**2 deltarot = ROT# To adjsut after number of orientations has been determined kb = Sire.Units.k_boltz T = temperature.val.value() kbT = kb*T beta = 1/kbT Ztot = 0.0 Uavg = 0 sim_dictionary = distance_restraints_dict.val if sim_dictionary == {}: print ("Error, no distance restraints dictionary was found in the supplied config file. Abort.") sys.exit(-1) #now create a dictionary in this way: #dict[pairs] = {[Req,D,K] [coords] [coords]...} restr_dict = {} #create a list of host/guest indexes to be used with mdtraj for alignment host_indices = [] guest_indices = [] for pairs in sim_dictionary: req = sim_dictionary[pairs][0] K = sim_dictionary[pairs][1] D = sim_dictionary[pairs][2] # First entry are parameters, second and third entries for coordinates of first and second atom restr_dict[pairs]=[[req,K,D],[],[]] if not pairs[1] in host_indices: host_indices.append(pairs[1]) if not pairs[0] in guest_indices: guest_indices.append(pairs[0]) #idx = max(pairs) #hosts.append(idx) #FIXME: code assumes guest atoms have lower indices than host atoms # a more reliable algorithm could work out whether the atoms belong # to a guest residue? # FIXME: # Support loading a crd file only to define restraint parameters #load the trajectory start_frame = 0 end_frame = 1000000000 step_frame = stepframe.val #Check the extension of the topology file if ".top" in topfile.val: shutil.copy(topfile.val,"SYSTEM.prmtop") #top doesn't work with mdtraj top_file = "SYSTEM.prmtop" else: top_file = topfile.val #Check the extension of the traj file if ".crd" in trajfile.val: shutil.copy(trajfile.val,"SYSTEM.rst7") #crd doesn't work with mdtraj traj_file = "SYSTEM.rst7" else: traj_file = trajfile.val print("Loading trajectory and topology files") # mdtraj_trajfile = mdtraj.load(traj_file,top=top_file) nframes = len(mdtraj_trajfile) if end_frame > (nframes - 1): end_frame = nframes - 1 current_frame = start_frame #Aligning everything along the first frame # Either use restrained host atoms, or a default selection if less than 3 unique atoms selection_default = "not water and not resname 'Na+' and not resname 'Cl-' and mass > 1" if len(host_indices) >2: selection = "index %s " % host_indices[0] for idx in host_indices[1:]: selection += " or index %s" % idx else: selection = selection_default print (selection) align_indices = mdtraj_trajfile.topology.select(selection) #print (align_indices) # FIXME: check whether alignment tolerates PBC artefacts print("Host: Aligning frames along first frame of trajectory") aligned_traj = mdtraj_trajfile.superpose(mdtraj_trajfile,0, atom_indices=align_indices) # First pass, collect aligned host coordinates while (current_frame <= end_frame): for pairs in restr_dict: idx1 = pairs[0] idx2 = pairs[1] #coord1 = aligned_traj.xyz[current_frame,idx1,:].tolist() coord2 = aligned_traj.xyz[current_frame,idx2,:].tolist() #restr_dict[pairs][1].append(coord1) restr_dict[pairs][2].append(coord2) current_frame += step_frame # Second pass, align against guest coordinates # and collect aligned guest coordinates if len(guest_indices) >2: selection = "index %s" % (guest_indices[0]) for idx in guest_indices[1:]: selection += " or index %s" % idx else: selection = selection_default print (selection) align_indices = mdtraj_trajfile.topology.select(selection) #print (align_indices) # FIXME: check whether alignment tolerates PBC artefacts print("Guest: Aligning frames along first frame of trajectory") aligned_traj = mdtraj_trajfile.superpose(mdtraj_trajfile,0, atom_indices=align_indices) current_frame = start_frame while (current_frame <= end_frame): for pairs in restr_dict: idx1 = pairs[0] idx2 = pairs[1] coord1 = aligned_traj.xyz[current_frame,idx1,:].tolist() restr_dict[pairs][1].append(coord1) current_frame += step_frame #now restr_dict has: #restr_dict[lig,host]=[ [req,K,D], [ [coords]...] ,[ [coords],...] ] print("Calculating average coordinates for restrained atoms") #import pdb; pdb.set_trace() restr_dict = averageCoordinates(restr_dict) print(restr_dict) #now the restr_dict is: #restr_dict[pairs]=[[req,K,D],[avgx,avgy,avgz]] # Create N orientations of restrained guest atoms by # rigib body rotations around COM guest_orientations = genOrientations(restr_dict, norientations=norient.val) deltarot /= len(guest_orientations) # FIXME: make sure space extends well into regions where restraint energy # is high space = defineIntegrationDomain(restr_dict) if verbose.val: print("Integration space") print(space) #Grid creation Nx = int ( round ( ( space[1][0] - space[0][0] ) / delta_trans.val ) ) Ny = int ( round ( ( space[1][0] - space[0][0] ) / delta_trans.val ) ) Nz = int ( round ( ( space[1][0] - space[0][0] ) / delta_trans.val ) ) print("Number of grid points to be evaluated %d (%d orientations per point)" %(Nx*Ny*Nz,norient.val*(norient.val/2)*norient.val)) print("Evaluation...") count = 0 free = 0 loweight = 0 for i in range(0,Nx): # FIXME: OpenMP ? for j in range(0,Ny): for k in range(0,Nz): count += 1 if ( (count % 100000) == 0): print ("Done %s grid points..." % (count)) xgrid = space[0][0] + delta_trans.val*i + delta_over_two ygrid = space[0][1] + delta_trans.val*j + delta_over_two zgrid = space[0][2] + delta_trans.val*k + delta_over_two for orientation in guest_orientations: pos = 0 U = 0.0 for pairs in restr_dict: req = restr_dict[pairs][0][0] k = restr_dict[pairs][0][1] dtol = restr_dict[pairs][0][2] host_coord = restr_dict[pairs][2] guest_coord = orientation[pos] # Accumulate energy d2 = ((guest_coord[0]+xgrid) - host_coord[0])**2+\ ((guest_coord[1]+ygrid) - host_coord[1])**2+\ ((guest_coord[2]+zgrid) - host_coord[2])**2 d = math.sqrt(d2) if (d > (req+dtol)): U += k*(d-req-dtol)**2 elif (d < (req-dtol)): U += k*(d-req+dtol)**2 else: U += 0.0 pos += 1 #print ("d %s U %s " % (d,U)) Boltz = math.exp(-beta*U)*deltavol*deltarot Uavg += U*Boltz Ztot += Boltz if (U < 0.000001): free += 1/(norient.val*(norient.val/2)*norient.val) if ( U*beta < 10): loweight += 1/(norient.val*(norient.val/2)*norient.val) #import pdb;pdb.set_trace() #Calculation of Ztot, Uavg, S, Frestraint: free_vol = free*deltavol loweight_frac = loweight/float(count) print ("Volume where restraint is null %8.2f Angstrom^3" % (free_vol)) print ("Fraction of points considered were restraint is under 10kbT %8.2f" % loweight_frac) if (loweight_frac > 0.25): print ("WARNING !!! The integration domain does not contain a significant number of datapoints with high restraint energy. It is possible that the domain does not cover all low restraint energy regions. Please check and if necessary increase the buffer keyword.") #sys.exit(-1) Uavg /= (Ztot) Zideal = 1661.*ROT Delta_F = -kbT*math.log(Zideal/Ztot) minTDelta_S = -T*(kb*math.log(Zideal/Ztot)-Uavg/T) print ("Ztot = %8.2f Angstrom^3" % Ztot) print ("WARNING !!! Have you checked that Ztot does not increase significantly when the value of the command line argument -b/--buffer size is increased?") print ("WARNING !!! This calculation was done with the argument -b %s Angstrom" % buffer.val) print ("Free energy change upon removing the restraint and applying standard state conditions = %8.2f kcal/mol" % Delta_F) #tidy up the folder by removing prmtop cmd = "rm -f SYSTEM.prmtop SYSTEM.rst7" os.system(cmd)
from Sire.Tools.AmberLoader import * from Sire.Tools import Parameter, resolveParameters import os import shutil import copy # We will use the waterbox held in the WSRC tools directory wsrc_tools_dir = "%s/Tools/WSRC" % Sire.Config.share_directory #################################################### # ALL OF THE GLOBAL USER-AVAILABLE LSRC PARAMETERS # #################################################### cutoff_method = Parameter( "cutoff method", "shift electrostatics", """Method used to apply the non-bonded electrostatic cutoff.""") rf_dielectric = Parameter( "reaction field dielectric", 78.3, """Dielectric constant to use if the reaction field cutoff method is used.""" ) coul_cutoff = Parameter("coulomb cutoff", 15 * angstrom, """Coulomb cutoff length""") lj_cutoff = Parameter("LJ cutoff", 15 * angstrom, """Lennard Jones cutoff length""") grid_spacing = Parameter( "grid spacing", 1.0 * angstrom,
def runLambda(): try: host = os.environ['HOSTNAME'] except KeyError: host = "unknown" print("### Running LJ tail correction calculation on %s ###" % host) if verbose.val: print( "###================= Simulation Parameters=====================###" ) Parameter.printAll() print( "###===========================================================###\n" ) print("lambda is %s" % lambda_val.val) if os.path.exists(s3file.val): (molecules, space) = Sire.Stream.load(s3file.val) else: amber = Amber() (molecules, space) = amber.readCrdTop(crdfile.val, topfile.val) Sire.Stream.save((molecules, space), s3file.val) system = createSystemFreeEnergy(molecules) # !!! NEED TO DISABLE CHANGE IN COULOMBIC CUTOFF !! #system = zeroCharges(system) #import pdb; pdb.set_trace() # THIS IS THE ONE WITH SHORT CUTOFF system_shortc = System() system_shortc.copy(system) #import pdb; pdb.set_trace() system_shortc = setupLJFF(system_shortc, space, \ cutoff=cutoff_dist.val) #import pdb; pdb.set_trace() # Determine longest cutoff that can be used. Take lowest space dimension, # and decrease by 5% dims = space.dimensions() mindim = dims.x() if mindim > dims.y(): mindim = dims.y() if mindim > dims.z(): mindim = dims.z() long_cutoff = (mindim / 2.0 * 0.95) * angstrom print(long_cutoff) system_longc = System() system_longc.copy(system) system_longc = setupLJFF(system_longc, space, \ cutoff=long_cutoff) # NOW ADD ANALYTICAL CORRECTION TERM TO longc E_lrc_full = addAnalyticalLRC(system_longc, long_cutoff, bulk_rho.val) #import pdb; pdb.set_trace() # Now loop over snapshots in dcd and accumulate energies start_frame = 1 end_frame = 1000000000 step_frame = stepframe.val #mdtraj_top = mdtraj.load_prmtop(topfile.val) mdtraj_trajfile = mdtraj.open(trajfile.val, 'r') nframes = len(mdtraj_trajfile) if end_frame > (nframes - 1): end_frame = nframes - 1 mdtraj_trajfile.seek(start_frame) current_frame = start_frame delta_nrgs = [] while (current_frame <= end_frame): print("Processing frame %s " % current_frame) print("CURRENT POSITION %s " % mdtraj_trajfile.tell()) frames_xyz, cell_lengths, cell_angles = mdtraj_trajfile.read( n_frames=1) #print (system_shortc.energy()) #print (system_longc.energy()) system_shortc = updateSystemfromTraj(system_shortc, frames_xyz, cell_lengths, cell_angles) system_longcc = updateSystemfromTraj(system_longc, frames_xyz, cell_lengths, cell_angles) #print (system_shortc.energy()) #print (system_longc.energy()) delta_nrg = (system_longc.energy() + E_lrc_full - system_shortc.energy()) delta_nrgs.append(delta_nrg) current_frame += step_frame mdtraj_trajfile.seek(current_frame) #print (delta_nrgs) # Now compute free energy change deltaG = getFreeEnergy(delta_nrgs) #print (deltaG) nbootstrap = 100 deltaG_bootstrap = np.zeros(nbootstrap) for x in range(0, nbootstrap): resampled_nrgs = resample(delta_nrgs) dG = getFreeEnergy(resampled_nrgs) deltaG_bootstrap[x] = dG.value() dev = deltaG_bootstrap.std() print("DG_LJ = %8.5f +/- %8.5f kcal/mol (1 sigma) " % (deltaG.value(), dev))
from Sire.Qt import * from Sire.ID import * from Sire.Config import * from Sire.Analysis import * from Sire.Tools.DCDFile import * from Sire.Tools import Parameter, resolveParameters import Sire.Stream import time import numpy as np #################################################################################################### # # Config file parameters # #################################################################################################### gpu = Parameter( "gpu", 0, """The device ID of the GPU on which to run the simulation.""") rf_dielectric = Parameter( "reaction field dielectric", 78.3, """Dielectric constant to use if the reaction field cutoff method is used.""" ) temperature = Parameter("temperature", 25 * celsius, """Simulation temperature""") pressure = Parameter("pressure", 1 * atm, """Simulation pressure""") topfile = Parameter( "topfile", "SYSTEM.top", """File name of the topology file containing the system to be simulated.""" )
from Sire.Config import * from Sire.Tools import Parameter, resolveParameters, readParams ###### CALCULATION PARAMETERS ## temperature = 298 * kelvin ## the dielectric for the reaction field rfdielectric=78.3 kb = 0.0019872041 # Boltzmann constant kcal/mol K ############################################# SOLVENT_RESNAMES = ["CYC","ZBT","WAT","T3P","HOH","T4P"] IONS_RESNAMES = ["Na+","Cl-"] ################################################ shift_delta = Parameter("shift delta", 2.0, """Value of the Lennard-Jones softcore parameter.""") coulomb_power = Parameter("coulomb power", 0, """Value of the Coulombic softcore parameter.""") combining_rules = Parameter("combining rules", "arithmetic", """Combining rules to use for the non-bonded interactions.""") def createSystem(molecules): #print("Applying flexibility and zmatrix templates...") print("Creating the system...") moleculeNumbers = molecules.molNums() moleculeList = [] for moleculeNumber in moleculeNumbers:
from Sire.Qt import * from Sire.ID import * from Sire.Config import * from Sire.Analysis import * from Sire.Tools.DCDFile import * from Sire.Tools import Parameter, resolveParameters import Sire.Stream import time import numpy as np ######################################### # Config file parameters # ######################################### combining_rules = Parameter( "combining rules", "geometric", """Combining rules to use for the non-bonded interactions.""") cutoff_type = Parameter("cutoff type", "nocutoff", """The cutoff method to use during the simulation.""") cutoff_dist = Parameter( "cutoff distance", 500 * angstrom, """The cutoff distance to use for the non-bonded interactions.""") use_restraints = Parameter( "use restraints", False, """Whether or not to use harmonic restaints on the solute atoms.""") def createSystem(molecules):
# # Evaluates electrostatics corrections to free energy changes # import os, sys, random import math import mdtraj from Sire.Tools.OpenMMMD import * from Sire.Tools import Parameter, resolveParameters # from Sire.Tools.LJcutoff import getFreeEnergy, resample solvent_residues = ["WAT", "ZBK", "ZBT", "CYC"] ion_residues = ["Cl-", "Na+"] DIME = 97 model_eps = Parameter("model_eps", 78.4, """The dielectric constant of the modelled solvent.""") trajfile = Parameter("trajfile", "traj000000001.dcd", """File name of the trajectory to process.""") stepframe = Parameter( "step_frame", 20, """The number of frames to step to between two succcessive evaluations.""") simfile = Parameter( "simfile", "sim.cfg", """ Configuration file with distance restraints dictionary""") topfile = Parameter( "topfile", "SYSTEM.top", """File name of the topology file containing the system to be simulated.""" ) crdfile = Parameter( "crdfile", "SYSTEM.crd",
from Sire.Qt import * from Sire.ID import * from Sire.Config import * from Sire.Analysis import * from Sire.Tools.DCDFile import * from Sire.Tools import Parameter, resolveParameters import Sire.Stream import time import numpy as np ######################################### # Config file parameters # ######################################### gpu = Parameter("gpu", 0, """The device ID of the GPU on which to run the simulation.""") platform = Parameter("platform", "OpenCL", """Which OpenMM platform should be used to perform the dynamics.""") timestep = Parameter("timestep", 2 * femtosecond, """Timestep for the dynamics simulation.""") temperature = Parameter("temperature", 25 * celsius, """Simulation temperature""") pressure = Parameter("pressure", 1 * atm, """Simulation pressure""") rf_dielectric = Parameter("reaction field dielectric", 78.3, """Dielectric constant to use if the reaction field cutoff method is used.""") combining_rules = Parameter("combining rules", "arithmetic",