def get_rst_from_nc(self, frame_number, shift, parm): from parmed.amber import AmberParm, Rst7, NetCDFTraj import os traj = NetCDFTraj.open_old(MD._run_dir + "/run" + MD._pattern % self.current_step + ".nc") new_rst7 = Rst7(natom=traj.atom) new_rst7.coordinates = traj.coordinates[frame_number] new_rst7.vels = traj.velocities[frame_number] new_rst7.box = traj.box[frame_number] parm.load_rst7(new_rst7) for r in parm.residues: if r.number > 56 and r.number <= 67: for a in r: a.xx += shift[0] a.xy += shift[1] a.xz += shift[2] parm.write_rst7(MD._run_dir + "/run" + MD._pattern % self.current_step + "mod.rst") parm.save(MD._run_dir + "/run" + MD._pattern % self.current_step + "mod.pdb") if not os.path.isdir(MD._run_dir + "/lock/"): os.mkdir(MD._run_dir + "/lock/") parm.save(MD._run_dir + "/lock/lock_begin.pdb") self._restart_filename = MD._run_dir + "/run" + MD._pattern % self.current_step + "mod.rst"
def get_shift_from_nc(self, frame_number, res1_number, atom1_name, res2_number, atom2_name, parm, traj): from pyxmol.geometry import distance, angle_deg, translate from parmed.amber import NetCDFTraj, Rst7, AmberParm from parmed.geometry import distance2 import numpy as np new_rst7 = Rst7(natom=traj.atom) new_rst7.coordinates = traj.coordinates[frame_number] new_rst7.box = traj.box[frame_number] parm.load_rst7(new_rst7) for a in parm.atoms: if a.residue.number == (res1_number - 1) and a.name == atom1_name: A1 = a elif a.residue.number == (res2_number - 1) and a.name == atom2_name: A2 = a best_dist = np.sqrt(distance2(A1, A2)) A, B, C = self.make_current_lattice_vectors(traj.box[frame_number]) for i in range(-1, 2): for j in range(-1, 2): for k in range(-1, 2): shift = i * A + j * B + k * C A2.xx += shift[0] A2.xy += shift[1] A2.xz += shift[2] dist = np.sqrt(distance2(A1, A2)) if dist < best_dist: best_dist = dist best_shift = shift A2.xx -= shift[0] A2.xy -= shift[1] A2.xz -= shift[2] return best_dist, best_shift
def coords_from_rst7_AMBER(filename, natom): rst7 = Rst7(filename, natom) coords = [list(i._value) for i in rst7.positions] coords = np.array(coords) #if rst7.hasvels: # print (rst7.velocities) # velocities=rst7.velocities/1000/20.455 # return coords,velocities return coords
def coords_from_rst7_TM(filename, natom): rst7 = Rst7(filename, natom) coords = [list(i._value) for i in rst7.positions] coords = np.array(coords) if rst7.hasvels: print(rst7.velocities) velocities = rst7.velocities return coords, velocities return coords
def prepare_final_rst(self, parm_old): from parmed.amber import AmberParm, Rst7 from copy import deepcopy rst = Rst7(MD._run_dir + "/run" + MD._pattern % self.current_step + "mod.rst") parm_old.load_rst7(rst) for r in parm_old.residues: if r.name == 'LYC': # print(r.number) lyc = r for a in r: if a.name == 'CL': new_Cl = deepcopy(a) # print(r.name, r.number, a.name, a.idx, a.xx, a.xy, a.xz, a.vx, a.vy, a.vz) parm_old.strip('@CL') parm_old.add_atom_to_residue(new_Cl, lyc) parm_old.write_rst7(MD._run_dir + "/run" + MD._pattern % self.current_step + "mod.mod.rst") self._restart_filename = MD._run_dir + "/run" + MD._pattern % self.current_step + "mod.mod.rst"
def __init__(self, prmtop, coordinates, box, mm_options, qm_options=None): # Handle the case where the coordinates are actually a restart file if isinstance(coordinates, string_types): # This is a restart file name. Parse it and make sure the coordinates # and box rst = Rst7.open(coordinates) coordinates = rst.coordinates if rst.hasbox and (box is None or box is False): box = rst.box # Convert from numpy arrays to regular arrays coordinates = _np.array(coordinates, copy=False, subok=True) coordinates = coordinates.flatten().tolist() if box is None or box is False: box = _np.zeros(6) else: box = _np.array([float(x) for x in box]) if box.shape != (6,): raise ValueError('box must have 6 elements') box = box.tolist() # Check if the prmtop is an AmberParm instance or not. If it is, write out a # temporary prmtop file if isinstance(prmtop, AmberParm): parm = tempfile.mktemp(suffix='.parm7') prmtop.write_parm(parm) elif not isinstance(prmtop, string_types): raise TypeError('prmtop must be an AmberParm or string') else: parm = prmtop # Error checking if mm_options.ifqnt != 0 and qm_options is None: raise ValueError("qm_options must be provided if QM/MM is requested") # Call the setup routine if qm_options is None: _pys.setup(parm, coordinates, box, mm_options) else: _pys.setup(parm, coordinates, box, mm_options, qm_options)
def get_dist_and_angle(self, res1_number, atom1_name, res2_number, atom2_name, res3_number, atom3_name, parm): from parmed.amber import AmberParm, Rst7 from parmed.geometry import distance2 import numpy as np rst = Rst7(MD._run_dir + "/run" + MD._pattern % self.current_step + "mod.rst") parm.load_rst7(rst) for a in parm.atoms: if a.residue.number == (res1_number - 1) and a.name == atom1_name: A1 = a elif a.residue.number == (res2_number - 1) and a.name == atom2_name: A2 = a elif a.residue.number == (res3_number - 1) and a.name == atom3_name: A3 = a A1_A2 = distance2(A1, A2) A1_A3 = distance2(A1, A3) A2_A3 = distance2(A2, A3) cos = (A1_A2 + A2_A3 - A1_A3) / (2 * np.sqrt(A1_A2) * np.sqrt(A2_A3)) A1_A2_A3 = np.degrees(np.arccos(cos)) return np.sqrt(A1_A2), A1_A2_A3
def MD(self, QMQueue=None): self.sys.Create_DisMap() self.sys.Update_DisMap() self.sys.update_crd() f, e, AVG_ERR, ERROR_mols, EGCMlist, chargestr = self.sys.Cal_EFQ() self.EPot0 = e self.EPot = e self.EnergyStat = OnlineEstimator(self.EPot0) self.RealPot = 0.0 self.t = 0.0 self.KE = 0.0 self.atoms = self.sys.atoms self.m = np.array(list(map(lambda x: ATOMICMASSES[x - 1], self.atoms))) self.x = self.sys.coords - self.sys.coords[self.center] self.v = np.zeros(self.x.shape) self.a = np.zeros(self.x.shape) self.f = f self.md_log = None if self.format == "Amber": self.trajectory = AmberMdcrd(self.path + self.name + '_%d.mdcrd' % self.stageindex, natom=self.sys.natom, hasbox=False, mode='w') self.restart = Rst7(natom=len(self.atoms)) self.trajectory.add_coordinates(self.x) if self.MDV0 == "Random": np.random.seed() self.v = np.random.randn(*self.x.shape) Tstat = Thermostat(self.m, self.v, self.T, self.dt) elif self.MDV0 == "Thermal": self.v = np.random.normal(size=self.x.shape) * np.sqrt( 1.38064852e-23 * self.T / self.m)[:, None] self.Tstat = None if (self.MDThermostat == "Rescaling"): self.Tstat = Thermo(self.m, self.v, self.T, self.dt) elif (self.MDThermostat == "Andersen"): self.Tstat = Andersen(self.m, self.v, self.T, self.dt) self.a = pow(10.0, -10.0) * np.einsum("ax,a->ax", self.f, 1.0 / self.m) if self.format == "Amber": self.restart.coordinates = self.x self.restart.vels = self.v step = 0 self.md_log = np.zeros((self.maxstep + 1, 7)) res_order = np.array(range(1, self.sys.nres)) ERROR = 0 ERROR_record = [] method_record = 0 Temp_record = [] MD_Flag = True while step < self.maxstep and MD_Flag: self.t += self.dt t1 = time.time() x_new = self.x + self.v * self.dt + 0.5 * self.a * self.dt**2 #if self.icap==True: # x_new=x_new-x_new[self.center] self.sys.coords = x_new f = x_new EPot = 0 ERROR_mols = [] self.sys.Update_DisMap() self.sys.update_crd() f, EPot, ERROR, ERROR_mols, EGCMlist, chargestr = self.sys.Cal_EFQ( ) ERROR_record.append(ERROR) if self.sys.stepmethod == 'Gaussian' and self.sys.Theroylevel == 'NN': method_record += 1 if self.MODE == 'Train': if QMQueue != None: QMQueue.put(ERROR_mols) self.EPot = EPot distozero = np.sqrt(np.sum(self.sys.coords**2, axis=1)) if self.icap == True: #Vec=(self.sys.Distance_Matrix[self.center]-self.radius)/self.radius Vec = (distozero - self.radius) / self.radius for i in range(len(x_new)): if Vec[i] > 0: tmpvec = (x_new[i]) tmpvec = tmpvec / np.sqrt(np.sum(tmpvec**2)) f[i] = f[i] - tmpvec * self.fcap * Vec[ i] * JOULEPERHARTREE / 627.51 f[self. center] = f[self.center] - x_new[self.center] * 10 * Vec[ self.center] * JOULEPERHARTREE / 627.51 a_new = pow(10.0, -10.0) * np.einsum("ax,a->ax", f, 1.0 / self.m) v_new = self.v + 0.5 * (self.a + a_new) * self.dt if self.MDThermostat != None and step % 1 == 0: v_new = self.Tstat.step(self.m, v_new, self.dt) self.a = a_new self.v = v_new self.x = x_new self.f = f self.md_log[step, 0] = self.t self.md_log[step, 4] = self.KE self.md_log[step, 5] = self.EPot self.md_log[ step, 6] = self.KE + (self.EPot - self.EPot0) * JOULEPERHARTREE avE, Evar = self.EnergyStat(self.EPot) self.KE = KineticEnergy(self.v, self.m) Teff = (2. / 3.) * self.KE / IDEALGASR Temp_record.append(Teff) if (step % 50 == 0): if self.format == "Amber": self.trajectory.add_coordinates(self.x) step += 1 AVG_ERR = np.mean(np.array(ERROR_record[-1000:-1])) AVG_TEMP = np.mean(np.array(Temp_record[-1000:-1])) #if AVG_ERR>GPARAMS.Train_setting.rmse**2*GPARAMS.Train_setting.Modelnumperpoint*4: # MD_Flag=False #if method_record>2: # MD_Flag=False if AVG_TEMP > 350: MD_Flag = False if (step % self.Nprint == 0): if self.format == "Amber": if MD_Flag: self.restart.coordinates = self.x self.restart.vels = self.v self.restart.write(self.path + self.name + '_%d.rst7' % self.stageindex) self.steprecord = step else: file = open( '%straj%d.trajin' % (self.path, self.stageindex), 'w') file.write('trajin %s %d %d 1\n' % (self.name + '_%d.mdcrd' % self.stageindex, 0, math.ceil(self.steprecord, 10))) file.write('trajout %s\n' % (self.name + '_%d.mdcrd' % self.stageindex)) os.system( "cd %s && cpptraj -p %s < traj%d.trajin > traj%d.out && cd .." % (self.path, self.name + '.prmtop', self.stageindex, self.stageindex)) if MD_Flag == True: self.Outfile.write("%s Step: %i time: %.1f(fs) KE(kJ): %.5f PotE(Eh): %.5f ETot(kJ/mol): %.5f Teff(K): %.5f MAX ERROR: %.3f Method: %s AVG_ERR: %f AVG_TEMP: %f \n"\ %(self.name, step, self.t, self.KE*len(self.m)/1000.0, self.EPot, self.KE*len(self.m)/1000.0+(self.EPot)*KJPERHARTREE, Teff,ERROR,self.sys.stepmethod,AVG_ERR,AVG_TEMP)) self.Outfile.flush() self.Respfile.write(chargestr) self.Respfile.write(chargestr) else: self.Outfile.write("AVG ERR: %.3f , MD will stop~~!!" % AVG_ERR) self.Outfile.flush() self.Outfile.close() self.Respfile.close() return
def gentle_lock(self, best_frame, lock_steps, lock_nstlim_per_step, shift): from pyxmol import aName, rName, aId, rId from pyxmol.geometry import distance, angle_deg from parmed.amber import AmberParm, Rst7, NetCDFTraj from pyxmol import readPdb from copy import deepcopy import os import shutil import subprocess import numpy as np import math #change md parameters self.log('lock_steps: {}'.format(lock_steps)) nstlim_old = self.run_parameters["nstlim"] ntwr_old = self.run_parameters["ntwr"] ntwx_old = self.run_parameters["ntwx"] ntpr_old = self.run_parameters["ntpr"] self.run_parameters.set(nstlim=lock_nstlim_per_step, ntwr=lock_nstlim_per_step, ntwv=0, ntwx=lock_nstlim_per_step, ntpr=lock_nstlim_per_step) #change topology and Rst parm = AmberParm(MD._build_dir + "/box.prmtop") self.get_rst_from_nc(best_frame, shift, parm) current_dist, current_angle = self.get_dist_and_angle( 32, "SG", 68, "C2", 68, "CL", parm) self.log("Bond dist before tying: %f" % (current_dist)) self.log("Bond angle before tying: %f" % (current_angle)) self.prepare_final_rst(parm) shutil.copyfile(MD._build_dir + "/box.prmtop", MD._build_dir + "/old_box.prmtop") shutil.copyfile( os.environ["PRMTOP_HOME"] + "/prmtop_linear/prmtops_new/box_before_lock_mod.prmtop", MD._build_dir + "/box.prmtop") shutil.copyfile( os.environ["PRMTOP_HOME"] + "/prmtop_linear/prmtops_new/box_before_lock_mod.prmtop", MD._build_dir + "/box.mod.prmtop") p = subprocess.Popen([ "ambpdb", "-p", MD._build_dir + "/box.prmtop", "-c", self._restart_filename ], stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = p.communicate() with open(self.tleaprc.pdb_output_name + ".pdb", "w") as fout: fout.write(stdout) self.restricted_structure = readPdb(self.tleaprc.pdb_output_name + ".pdb")[0].asResidues >> ( rId <= (self.n_residues + 1)) ats = self.restricted_structure.asAtoms #select atoms C2 = (ats >> ((aName == "C2") & (rName == "LYZ")))[0] C1 = (ats >> ((aName == "C1") & (rName == "LYZ")))[0] H1 = (ats >> ((aName == "H1") & (rName == "LYZ")))[0] H2 = (ats >> ((aName == "H2") & (rName == "LYZ")))[0] SG = (ats >> ((aName == "SG") & (rName == "CYZ")))[0] CB = (ats >> ((aName == "CB") & (rName == "CYZ")))[0] CL = (ats >> ((aName == "Cl-") & (rName == "Cl-")))[0] def lineal(x): return x self.log('Start linear transformation') t = 0 while t < lock_steps: os.remove(MD._run_dir + "/run%05d.nc" % self.current_step) self.log('t: {}, lock_steps: {}'.format(t, lock_steps)) x = float(t + 1) / lock_steps self.log("manage C2-CL bond") self.run_parameters.add_distance_restraint(C2.aId, CL.aId, 0.0, 1.766, 1.766, 99.0, 232 * (1 - lineal(x)), 232 * (1 - lineal(x)), comment="") self.run_parameters.add_angle_restraint(CL.aId, C2.aId, C1.aId, 0.0, 110.41, 110.41, 180.0, 71.7 * (1 - lineal(x)), 71.7 * (1 - lineal(x)), comment="") self.run_parameters.add_angle_restraint(CL.aId, C2.aId, H1.aId, 0.0, 108.5, 108.5, 180.0, 50.0 * (1 - lineal(x)), 50.0 * (1 - lineal(x)), comment="") self.run_parameters.add_angle_restraint(CL.aId, C2.aId, H2.aId, 0.0, 108.5, 108.5, 180.0, 50.0 * (1 - lineal(x)), 50.0 * (1 - lineal(x)), comment="") self.log("manage C2-SG bond") self.run_parameters.add_distance_restraint(C2.aId, SG.aId, 0.0, 1.81, 1.81, 99.0, 227 * lineal(x), 227 * lineal(x), comment="") self.run_parameters.add_angle_restraint(SG.aId, C2.aId, C1.aId, 0.0, 108.84, 108.84, 180.0, 63.79 * lineal(x), 63.79 * lineal(x), comment="") self.run_parameters.add_angle_restraint(SG.aId, C2.aId, H1.aId, 0.0, 109.5, 109.5, 180.0, 50.0 * lineal(x), 50.0 * lineal(x), comment="") self.run_parameters.add_angle_restraint(SG.aId, C2.aId, H2.aId, 0.0, 109.5, 109.5, 180.0, 50.0 * lineal(x), 50.0 * lineal(x), comment="") self.log("manage CB-SG bond") self.run_parameters.add_angle_restraint(CB.aId, SG.aId, C2.aId, 0.0, 98.9, 98.9, 180.0, 62 * lineal(x), 62 * lineal(x), comment="") shutil.copyfile( os.environ["PRMTOP_HOME"] + "/prmtop_linear/prmtops_new/box_{}_parmed.prmtop".format(t), MD._build_dir + "/box.prmtop") shutil.copyfile( os.environ["PRMTOP_HOME"] + "/prmtop_linear/prmtops_new/box_{}_parmed.prmtop".format(t), MD._build_dir + "/box.mod.prmtop") self.do_md_step() # delete current restraints self.run_parameters.del_distance_restraints(C2.aId, CL.aId) self.run_parameters.del_distance_restraints(C2.aId, SG.aId) self.run_parameters.del_angle_restraint(CL.aId, C2.aId, C1.aId) self.run_parameters.del_angle_restraint(CL.aId, C2.aId, H1.aId) self.run_parameters.del_angle_restraint(CL.aId, C2.aId, H2.aId) self.run_parameters.del_angle_restraint(SG.aId, C2.aId, C1.aId) self.run_parameters.del_angle_restraint(SG.aId, C2.aId, H1.aId) self.run_parameters.del_angle_restraint(SG.aId, C2.aId, H2.aId) self.run_parameters.del_angle_restraint(CB.aId, SG.aId, C2.aId) #shift rst new_rst = Rst7(MD._run_dir + "/run" + MD._pattern % self.current_step + ".rst") parm = AmberParm(MD._build_dir + "/box.mod.prmtop") parm.load_rst7(new_rst) dist1, shift1 = self.get_shift_from_rst(32, "SG", 68, "C2", parm, new_rst) #self.log("Shift peptide: ax = %f, ay = %f, az = %f" % (shift1[0], shift1[1], shift1[2]), MD.INFO) dist2, shift2 = self.get_shift_from_rst(32, "SG", 69, "Cl-", parm, new_rst) #self.log("Shift Cl-: ax = %f, ay = %f, az = %f" % (shift2[0], shift2[1], shift2[2]), MD.INFO) self.shift_rst(shift1, shift2, parm) self.put_frame(ats, -1, -1) ats.writeAsPdb( open(MD._run_dir + "/run%05d.pdb" % self.current_step, "w")) if not os.path.isdir(MD._run_dir + "/lock/"): os.mkdir(MD._run_dir + "/lock/") ats.writeAsPdb( open(MD._run_dir + "/lock/" + "lock-%d.pdb" % t, "w")) t += 1 self.log('Finish linear transformation') self.run_parameters.set(nstlim=nstlim_old, ntwr=ntwr_old, ntwx=ntwx_old, ntpr=ntpr_old) self.log('set old nstlim: {}'.format(nstlim_old)) self.log('set old ntwr: {}'.format(ntwr_old)) self.log('set old ntwx: {}'.format(ntwx_old)) self.log('set old ntpr: {}'.format(ntpr_old)) self.set_step_as_restart_file() self._restart_filename = MD._run_dir + "/run" + MD._pattern % self.current_step + "mod.rst"